1use std::{cmp::Ordering, convert::Infallible, fmt};23use jrsonnet_gcmodule::{Acyclic, Trace};4use jrsonnet_interner::IStr;5use jrsonnet_ir::{6 BinaryOpType, ConvertNumValueError, Source, SourcePath, Span, Spanned, UnaryOpType,7};8use jrsonnet_types::ValType;9use thiserror::Error;1011use crate::{12 ObjValue, ResolvePathOwned,13 analyze::Diagnostic,14 function::{CallLocation, FunctionSignature, ParamName},15 stdlib::format::FormatError,16 typed::TypeLocError,17};1819#[derive(Debug, Clone, Acyclic)]20pub struct SyntaxError {21 pub message: String,22 pub location: Span,23}24impl fmt::Display for SyntaxError {25 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {26 write!(f, "{}", self.message)27 }28}2930pub(crate) fn format_found(list: &[IStr], what: &str) -> String {31 if list.is_empty() {32 return String::new();33 }34 let mut out = String::new();35 out.push_str("\nThere ");36 if list.len() > 1 {37 out.push_str("are ");38 } else {39 out.push_str("is a ");40 }41 out.push_str(what);42 if list.len() > 1 {43 out.push('s');44 }45 out.push_str(" with similar name");46 if list.len() > 1 {47 out.push('s');48 }49 out.push_str(" present: ");50 for (i, v) in list.iter().enumerate() {51 if i != 0 {52 out.push_str(", ");53 }54 out.push_str(v as &str);55 }56 out57}5859const fn format_empty_str(str: &str) -> &str {60 if str.is_empty() {61 "\"\" (empty string)"62 } else {63 str64 }65}6667pub(crate) fn suggest_names<'a, 'b>(68 name: &'a IStr,69 names: impl IntoIterator<Item = &'b IStr>,70) -> Vec<IStr> {71 let mut heap: Vec<(f64, IStr)> = names72 .into_iter()73 .filter_map(|def| {74 let conf = strsim::jaro_winkler(def.as_str(), name.as_str());75 if conf < 0.8 {76 return None;77 }78 debug_assert!(79 def.as_str() != name.as_str(),80 "string pooling failure: look for DOC(string-pooling) comment in jrsonnet-interner"81 );8283 Some((conf, def.clone()))84 })85 .collect();86 heap.sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap_or(Ordering::Equal));87 heap.into_iter().map(|v| v.1).collect()88}8990pub(crate) fn suggest_object_fields(v: &ObjValue, key: IStr) -> Vec<IStr> {91 let fields = v.fields_ex(92 true,93 #[cfg(feature = "exp-preserve-order")]94 false,95 );96 suggest_names(&key, &fields)97}9899100#[allow(missing_docs)]101#[derive(Error, Debug, Clone, Trace)]102#[non_exhaustive]103pub enum ErrorKind {104 #[error("intrinsic not found: {0}")]105 IntrinsicNotFound(IStr),106107 #[error("operator {0} does not operate on type {1}")]108 UnaryOperatorDoesNotOperateOnType(UnaryOpType, ValType),109 #[error("binary operation {1} {0} {2} is not implemented")]110 BinaryOperatorDoesNotOperateOnValues(BinaryOpType, ValType, ValType),111112 #[error("self/super/$ are only usable inside objects")]113 CantUseSelfSupOutsideOfObject,114115 #[error("static analysis errors: {}", .0.iter().map(|d| d.message.as_str()).collect::<Vec<_>>().join("; "))]116 StaticAnalysisError(Vec<Diagnostic>),117 #[error("no super found")]118 NoSuperFound,119120 #[error("for loop can only iterate over arrays")]121 InComprehensionCanOnlyIterateOverArray,122 #[error("(should not be visible) eager compspec evaluation failed due to captured context")]123 EagerCompspecCaptured,124125 #[error("array out of bounds: {0} is not within [0,{1})")]126 ArrayBoundsError(f64, u32),127 #[error("string out of bounds: {0} is not within [0,{1})")]128 StringBoundsError(f64, u32),129130 #[error("assert failed: {}", format_empty_str(.0))]131 AssertionFailed(IStr),132133 #[error("type mismatch: expected {expected}, got {2} {0}", expected = .1.iter().map(|e| format!("{e}")).collect::<Vec<_>>().join(", "))]134 TypeMismatch(&'static str, Vec<ValType>, ValType),135 #[error("no such field: {}{}", format_empty_str(.0), format_found(.1, "field"))]136 NoSuchField(IStr, Vec<IStr>),137138 #[error("only functions can be called, got {0}")]139 OnlyFunctionsCanBeCalledGot(ValType),140 #[error("parameter {0} is not defined")]141 UnknownFunctionParameter(IStr),142 #[error("argument {0} is already bound")]143 BindingParameterASecondTime(IStr),144 #[error("too many args, function has {0}\nFunction has the following signature: {1}")]145 TooManyArgsFunctionHas(usize, FunctionSignature),146 #[error("function argument is not passed: {0}\nFunction has the following signature: {1}")]147 FunctionParameterNotBoundInCall(ParamName, FunctionSignature),148149 #[error("external variable is not defined: {0}")]150 UndefinedExternalVariable(IStr),151152 #[error("field name should be string, got {0}")]153 FieldMustBeStringGot(ValType),154 #[error("duplicate field name: {}", format_empty_str(.0))]155 DuplicateFieldName(IStr),156157 #[error("attempted to index array with string {}", format_empty_str(.0))]158 AttemptedIndexAnArrayWithString(IStr),159 #[error("{0} index type should be {1}, got {2}")]160 ValueIndexMustBeTypeGot(ValType, ValType, ValType),161 #[error("cant index into {0}")]162 CantIndexInto(ValType),163 #[error("{0} is not indexable")]164 ValueIsNotIndexable(ValType),165166 #[error("super can't be used standalone")]167 StandaloneSuper,168169 #[error("can't resolve {1} from {0}")]170 ImportFileNotFound(SourcePath, ResolvePathOwned),171 #[error("resolved file not found: {:?}", .0)]172 ResolvedFileNotFound(SourcePath),173 #[error("can't import {0}: is a directory")]174 ImportIsADirectory(SourcePath),175 #[error("imported file is not valid utf-8: {0:?}")]176 ImportBadFileUtf8(SourcePath),177 #[error("import io error: {0}")]178 ImportIo(String),179 #[error("tried to import {1} from {0}, but imports are not supported")]180 ImportNotSupported(SourcePath, ResolvePathOwned),181 #[error("can't import from virtual file")]182 CantImportFromVirtualFile,183 #[error("syntax error: {error}")]184 ImportSyntaxError {185 path: Source,186 error: Box<SyntaxError>,187 },188189 #[error("runtime error: {}", format_empty_str(.0))]190 RuntimeError(IStr),191 #[error("stack overflow, try to reduce recursion, or set --max-stack to bigger value")]192 StackOverflow,193 #[error("infinite recursion detected")]194 InfiniteRecursionDetected,195 #[error("tried to index by fractional value")]196 FractionalIndex,197 #[error("attempted to divide by zero")]198 DivisionByZero,199200 #[error("string manifest output is not an string")]201 StringManifestOutputIsNotAString,202 #[error("stream manifest output is not an array")]203 StreamManifestOutputIsNotAArray,204 #[error("multi manifest output is not an object")]205 MultiManifestOutputIsNotAObject,206207 #[error("cant recurse stream manifest")]208 StreamManifestOutputCannotBeRecursed,209 #[error("stream manifest output cannot consist of raw strings")]210 StreamManifestCannotNestString,211212 #[error("{}", format_empty_str(.0))]213 ImportCallbackError(String),214 #[error("invalid unicode codepoint: {0}")]215 InvalidUnicodeCodepointGot(u32),216217 #[error("convert num value: {0}")]218 ConvertNumValue(#[from] ConvertNumValueError),219220 #[error("format error: {0}")]221 Format(#[from] FormatError),222 #[error("type error: {0}")]223 TypeError(TypeLocError),224225 #[cfg(feature = "anyhow-error")]226 #[error(transparent)]227 Other(#[trace(skip)] std::rc::Rc<anyhow::Error>),228}229230#[cfg(feature = "anyhow-error")]231impl From<anyhow::Error> for Error {232 fn from(e: anyhow::Error) -> Self {233 Self::new(ErrorKind::Other(std::rc::Rc::new(e)))234 }235}236237impl From<ErrorKind> for Error {238 fn from(e: ErrorKind) -> Self {239 Self::new(e)240 }241}242impl From<ConvertNumValueError> for Error {243 fn from(e: ConvertNumValueError) -> Self {244 Self::new(ErrorKind::ConvertNumValue(e))245 }246}247248impl From<Infallible> for Error {249 fn from(_value: Infallible) -> Self {250 unreachable!()251 }252}253254255#[derive(Clone, Debug, Trace)]256pub struct StackTraceElement {257 258 259 pub location: Option<Span>,260 261 pub desc: String,262}263#[derive(Debug, Clone, Trace)]264pub struct StackTrace(pub Vec<StackTraceElement>);265266#[derive(Clone, Trace)]267pub struct Error(Box<(ErrorKind, StackTrace)>);268269#[cfg(target_pointer_width = "64")]270static_assertions::assert_eq_size!(Error, usize);271272impl Error {273 pub fn new(e: ErrorKind) -> Self {274 Self(Box::new((e, StackTrace(vec![]))))275 }276277 pub const fn error(&self) -> &ErrorKind {278 &(self.0).0279 }280 pub fn error_mut(&mut self) -> &mut ErrorKind {281 &mut (self.0).0282 }283 pub const fn trace(&self) -> &StackTrace {284 &(self.0).1285 }286 pub fn trace_mut(&mut self) -> &mut StackTrace {287 &mut (self.0).1288 }289}290impl fmt::Display for Error {291 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {292 writeln!(f, "{}", self.0.0)?;293 for el in &self.0.1.0 {294 write!(f, "\t{}", el.desc)?;295 if let Some(loc) = &el.location {296 write!(f, "at {}", loc.0.0.0)?;297 loc.0.map_source_locations(&[loc.1, loc.2]);298 }299 writeln!(f)?;300 }301 Ok(())302 }303}304impl fmt::Debug for Error {305 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {306 f.debug_tuple("LocError").field(&self.0).finish()307 }308}309impl std::error::Error for Error {}310311pub trait ErrorSource {312 fn to_location(self) -> Option<Span>;313}314impl<T: Acyclic> ErrorSource for &Spanned<T> {315 fn to_location(self) -> Option<Span> {316 Some(self.span.clone())317 }318}319impl ErrorSource for &Span {320 fn to_location(self) -> Option<Span> {321 Some(self.clone())322 }323}324impl ErrorSource for CallLocation<'_> {325 fn to_location(self) -> Option<Span> {326 self.0.cloned()327 }328}329330pub type Result<V, E = Error> = std::result::Result<V, E>;331pub trait ResultExt: Sized {332 #[must_use]333 fn with_description<O: Into<String>>(self, msg: impl FnOnce() -> O) -> Self;334 #[must_use]335 fn description(self, msg: &str) -> Self {336 self.with_description(|| msg)337 }338339 #[must_use]340 fn with_description_src<O: Into<String>>(341 self,342 src: impl ErrorSource,343 msg: impl FnOnce() -> O,344 ) -> Self;345 #[must_use]346 fn description_src(self, src: impl ErrorSource, msg: &str) -> Self {347 self.with_description_src(src, || msg)348 }349}350impl<T> ResultExt for Result<T, Error> {351 fn with_description<O: Into<String>>(mut self, msg: impl FnOnce() -> O) -> Self {352 if let Err(e) = &mut self {353 let trace = e.trace_mut();354 trace.0.push(StackTraceElement {355 location: None,356 desc: msg().into(),357 });358 }359 self360 }361362 fn with_description_src<O: Into<String>>(363 mut self,364 src: impl ErrorSource,365 msg: impl FnOnce() -> O,366 ) -> Self {367 if let Err(e) = &mut self {368 let trace = e.trace_mut();369 trace.0.push(StackTraceElement {370 location: src.to_location(),371 desc: msg().into(),372 });373 }374 self375 }376}377378#[macro_export]379macro_rules! bail {380 ($w:ident$(::$i:ident)*$(($($tt:tt)*))?) => {381 return Err($w$(::$i)*$(($($tt)*))?.into())382 };383 ($w:ident$(::$i:ident)*$({$($tt:tt)*})?) => {384 return Err($w$(::$i)*$({$($tt)*})?.into())385 };386 ($l:literal$(, $($tt:tt)*)?) => {387 return Err($crate::error::ErrorKind::RuntimeError($crate::jrsonnet_macros::format_istr!($l$(, $($tt)*)?)).into())388 };389}390#[macro_export]391macro_rules! error {392 ($w:ident$(::$i:ident)*$(($($tt:tt)*))?) => {393 $crate::error::Error::from($w$(::$i)*$(($($tt)*))?)394 };395 ($w:ident$(::$i:ident)*$({$($tt:tt)*})?) => {396 $crate::error::Error::from($w$(::$i)*$({$($tt)*})?)397 };398 ($l:literal$(, $($tt:tt)*)?) => {399 <$crate::error::Error as From<$crate::error::ErrorKind>>::from($crate::error::ErrorKind::RuntimeError($crate::jrsonnet_macros::format_istr!($l$(, $($tt)*)?)).into())400 };401}