1use std::{2 fmt::{Debug, Display},3 path::PathBuf,4};56use jrsonnet_gcmodule::Trace;7use jrsonnet_interner::IStr;8use jrsonnet_parser::{BinaryOpType, ExprLocation, LocExpr, Source, SourcePath, UnaryOpType};9use jrsonnet_types::ValType;10use thiserror::Error;1112use crate::{function::CallLocation, stdlib::format::FormatError, typed::TypeLocError};1314fn format_found(list: &[IStr], what: &str) -> String {15 if list.is_empty() {16 return String::new();17 }18 let mut out = String::new();19 out.push_str("\nThere is ");20 out.push_str(what);21 if list.len() > 1 {22 out.push('s');23 }24 out.push_str(" with similar name");25 if list.len() > 1 {26 out.push('s');27 }28 out.push_str(" present: ");29 for (i, v) in list.iter().enumerate() {30 if i != 0 {31 out.push_str(", ");32 }33 out.push_str(v as &str);34 }35 out36}3738fn format_signature(sig: &FunctionSignature) -> String {39 let mut out = String::new();40 out.push_str("\nFunction has the following signature: ");41 out.push('(');42 if sig.is_empty() {43 out.push_str("/*no arguments*/");44 } else {45 for (i, (name, has_default)) in sig.iter().enumerate() {46 if i != 0 {47 out.push_str(", ");48 }49 if let Some(name) = name {50 out.push_str(name);51 } else {52 out.push_str("<unnamed>");53 }54 if *has_default {55 out.push_str(" = <default>");56 }57 }58 }59 out.push(')');60 out61}6263const fn format_empty_str(str: &str) -> &str {64 if str.is_empty() {65 "\"\" (empty string)"66 } else {67 str68 }69}7071type FunctionSignature = Vec<(Option<IStr>, bool)>;727374#[allow(missing_docs)]75#[derive(Error, Debug, Clone, Trace)]76#[non_exhaustive]77pub enum ErrorKind {78 #[error("intrinsic not found: {0}")]79 IntrinsicNotFound(IStr),8081 #[error("operator {0} does not operate on type {1}")]82 UnaryOperatorDoesNotOperateOnType(UnaryOpType, ValType),83 #[error("binary operation {1} {0} {2} is not implemented")]84 BinaryOperatorDoesNotOperateOnValues(BinaryOpType, ValType, ValType),8586 #[error("no top level object in this context")]87 NoTopLevelObjectFound,88 #[error("self is only usable inside objects")]89 CantUseSelfOutsideOfObject,90 #[error("no super found")]91 NoSuperFound,9293 #[error("for loop can only iterate over arrays")]94 InComprehensionCanOnlyIterateOverArray,9596 #[error("array out of bounds: {0} is not within [0,{1})")]97 ArrayBoundsError(usize, usize),98 #[error("string out of bounds: {0} is not within [0,{1})")]99 StringBoundsError(usize, usize),100101 #[error("assert failed: {}", format_empty_str(.0))]102 AssertionFailed(IStr),103104 #[error("variable is not defined: {0}{}", format_found(.1, "variable"))]105 VariableIsNotDefined(IStr, Vec<IStr>),106 #[error("duplicate local var: {0}")]107 DuplicateLocalVar(IStr),108109 #[error("type mismatch: expected {}, got {2} {0}", .1.iter().map(|e| format!("{e}")).collect::<Vec<_>>().join(", "))]110 TypeMismatch(&'static str, Vec<ValType>, ValType),111 #[error("no such field: {}{}", format_empty_str(.0), format_found(.1, "field"))]112 NoSuchField(IStr, Vec<IStr>),113114 #[error("only functions can be called, got {0}")]115 OnlyFunctionsCanBeCalledGot(ValType),116 #[error("parameter {0} is not defined")]117 UnknownFunctionParameter(String),118 #[error("argument {0} is already bound")]119 BindingParameterASecondTime(IStr),120 #[error("too many args, function has {0}{}", format_signature(.1))]121 TooManyArgsFunctionHas(usize, FunctionSignature),122 #[error("function argument is not passed: {}{}", .0.as_ref().map_or("<unnamed>", IStr::as_str), format_signature(.1))]123 FunctionParameterNotBoundInCall(Option<IStr>, FunctionSignature),124125 #[error("external variable is not defined: {0}")]126 UndefinedExternalVariable(IStr),127128 #[error("field name should be string, got {0}")]129 FieldMustBeStringGot(ValType),130 #[error("duplicate field name: {}", format_empty_str(.0))]131 DuplicateFieldName(IStr),132133 #[error("attempted to index array with string {}", format_empty_str(.0))]134 AttemptedIndexAnArrayWithString(IStr),135 #[error("{0} index type should be {1}, got {2}")]136 ValueIndexMustBeTypeGot(ValType, ValType, ValType),137 #[error("cant index into {0}")]138 CantIndexInto(ValType),139 #[error("{0} is not indexable")]140 ValueIsNotIndexable(ValType),141142 #[error("super can't be used standalone")]143 StandaloneSuper,144145 #[error("can't resolve {1} from {0}")]146 ImportFileNotFound(SourcePath, String),147 #[error("can't resolve absolute {0}")]148 AbsoluteImportFileNotFound(PathBuf),149 #[error("resolved file not found: {:?}", .0)]150 ResolvedFileNotFound(SourcePath),151 #[error("can't import {0}: is a directory")]152 ImportIsADirectory(SourcePath),153 #[error("imported file is not valid utf-8: {0:?}")]154 ImportBadFileUtf8(SourcePath),155 #[error("import io error: {0}")]156 ImportIo(String),157 #[error("tried to import {1} from {0}, but imports are not supported")]158 ImportNotSupported(SourcePath, String),159 #[error("tried to import {0}, but absolute imports are not supported")]160 AbsoluteImportNotSupported(PathBuf),161 #[error("can't import from virtual file")]162 CantImportFromVirtualFile,163 #[error(164 "syntax error: expected {}, got {:?}",165 .error.expected,166 .path.code().chars().nth(error.location.offset)167 .map_or_else(|| "EOF".into(), |c| c.to_string())168 )]169 ImportSyntaxError {170 path: Source,171 #[trace(skip)]172 error: Box<jrsonnet_parser::ParseError>,173 },174175 #[error("runtime error: {}", format_empty_str(.0))]176 RuntimeError(IStr),177 #[error("stack overflow, try to reduce recursion, or set --max-stack to bigger value")]178 StackOverflow,179 #[error("infinite recursion detected")]180 InfiniteRecursionDetected,181 #[error("tried to index by fractional value")]182 FractionalIndex,183 #[error("attempted to divide by zero")]184 DivisionByZero,185186 #[error("string manifest output is not an string")]187 StringManifestOutputIsNotAString,188 #[error("stream manifest output is not an array")]189 StreamManifestOutputIsNotAArray,190 #[error("multi manifest output is not an object")]191 MultiManifestOutputIsNotAObject,192193 #[error("cant recurse stream manifest")]194 StreamManifestOutputCannotBeRecursed,195 #[error("stream manifest output cannot consist of raw strings")]196 StreamManifestCannotNestString,197198 #[error("{}", format_empty_str(.0))]199 ImportCallbackError(String),200 #[error("invalid unicode codepoint: {0}")]201 InvalidUnicodeCodepointGot(u32),202203 #[error("format error: {0}")]204 Format(#[from] FormatError),205 #[error("type error: {0}")]206 TypeError(TypeLocError),207208 #[cfg(feature = "anyhow-error")]209 #[error(transparent)]210 Other(Rc<anyhow::Error>),211}212213#[cfg(feature = "anyhow-error")]214impl From<anyhow::Error> for Error {215 fn from(e: anyhow::Error) -> Self {216 Self::new(ErrorKind::Other(Rc::new(e)))217 }218}219220impl From<ErrorKind> for Error {221 fn from(e: ErrorKind) -> Self {222 Self::new(e)223 }224}225226227#[derive(Clone, Debug, Trace)]228pub struct StackTraceElement {229 230 231 pub location: Option<ExprLocation>,232 233 pub desc: String,234}235#[derive(Debug, Clone, Trace)]236pub struct StackTrace(pub Vec<StackTraceElement>);237238#[derive(Clone, Trace)]239pub struct Error(Box<(ErrorKind, StackTrace)>);240impl Error {241 pub fn new(e: ErrorKind) -> Self {242 Self(Box::new((e, StackTrace(vec![]))))243 }244245 pub const fn error(&self) -> &ErrorKind {246 &(self.0).0247 }248 pub fn error_mut(&mut self) -> &mut ErrorKind {249 &mut (self.0).0250 }251 pub const fn trace(&self) -> &StackTrace {252 &(self.0).1253 }254 pub fn trace_mut(&mut self) -> &mut StackTrace {255 &mut (self.0).1256 }257}258impl Display for Error {259 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {260 writeln!(f, "{}", self.0 .0)?;261 for el in &self.0 .1 .0 {262 write!(f, "\t{}", el.desc)?;263 if let Some(loc) = &el.location {264 write!(f, "at {}", loc.0 .0 .0)?;265 loc.0.map_source_locations(&[loc.1, loc.2]);266 }267 writeln!(f)?;268 }269 Ok(())270 }271}272impl Debug for Error {273 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {274 f.debug_tuple("LocError").field(&self.0).finish()275 }276}277impl std::error::Error for Error {}278279pub trait ErrorSource {280 fn to_location(self) -> Option<ExprLocation>;281}282impl ErrorSource for &LocExpr {283 fn to_location(self) -> Option<ExprLocation> {284 Some(self.1.clone())285 }286}287impl ErrorSource for &ExprLocation {288 fn to_location(self) -> Option<ExprLocation> {289 Some(self.clone())290 }291}292impl ErrorSource for CallLocation<'_> {293 fn to_location(self) -> Option<ExprLocation> {294 self.0.cloned()295 }296}297298pub type Result<V, E = Error> = std::result::Result<V, E>;299pub trait ResultExt: Sized {300 #[must_use]301 fn with_description<O: Into<String>>(self, msg: impl FnOnce() -> O) -> Self;302 #[must_use]303 fn description(self, msg: &str) -> Self {304 self.with_description(|| msg)305 }306307 #[must_use]308 fn with_description_src<O: Into<String>>(309 self,310 src: impl ErrorSource,311 msg: impl FnOnce() -> O,312 ) -> Self;313 #[must_use]314 fn description_src(self, src: impl ErrorSource, msg: &str) -> Self {315 self.with_description_src(src, || msg)316 }317}318impl<T> ResultExt for Result<T, Error> {319 fn with_description<O: Into<String>>(mut self, msg: impl FnOnce() -> O) -> Self {320 if let Err(e) = &mut self {321 let trace = e.trace_mut();322 trace.0.push(StackTraceElement {323 location: None,324 desc: msg().into(),325 });326 }327 self328 }329330 fn with_description_src<O: Into<String>>(331 mut self,332 src: impl ErrorSource,333 msg: impl FnOnce() -> O,334 ) -> Self {335 if let Err(e) = &mut self {336 let trace = e.trace_mut();337 trace.0.push(StackTraceElement {338 location: src.to_location(),339 desc: msg().into(),340 });341 }342 self343 }344}345346#[macro_export]347macro_rules! throw {348 ($w:ident$(::$i:ident)*$(($($tt:tt)*))?) => {349 return Err($w$(::$i)*$(($($tt)*))?.into())350 };351 ($l:literal) => {352 return Err($crate::error::ErrorKind::RuntimeError($l.into()).into())353 };354 ($l:literal, $($tt:tt)*) => {355 return Err($crate::error::ErrorKind::RuntimeError(format!($l, $($tt)*).into()).into())356 };357}