1use std::{2 cmp::Ordering,3 fmt::{Debug, Display},4 path::PathBuf,5};67use jrsonnet_gcmodule::Trace;8use jrsonnet_interner::IStr;9use jrsonnet_parser::{BinaryOpType, ExprLocation, LocExpr, Source, SourcePath, UnaryOpType};10use jrsonnet_types::ValType;11use thiserror::Error;1213use crate::{function::CallLocation, stdlib::format::FormatError, typed::TypeLocError, ObjValue};1415pub(crate) fn format_found(list: &[IStr], what: &str) -> String {16 if list.is_empty() {17 return String::new();18 }19 let mut out = String::new();20 out.push_str("\nThere is ");21 out.push_str(what);22 if list.len() > 1 {23 out.push('s');24 }25 out.push_str(" with similar name");26 if list.len() > 1 {27 out.push('s');28 }29 out.push_str(" present: ");30 for (i, v) in list.iter().enumerate() {31 if i != 0 {32 out.push_str(", ");33 }34 out.push_str(v as &str);35 }36 out37}3839fn format_signature(sig: &FunctionSignature) -> String {40 let mut out = String::new();41 out.push_str("\nFunction has the following signature: ");42 out.push('(');43 if sig.is_empty() {44 out.push_str("/*no arguments*/");45 } else {46 for (i, (name, has_default)) in sig.iter().enumerate() {47 if i != 0 {48 out.push_str(", ");49 }50 if let Some(name) = name {51 out.push_str(name);52 } else {53 out.push_str("<unnamed>");54 }55 if *has_default {56 out.push_str(" = <default>");57 }58 }59 }60 out.push(')');61 out62}6364const fn format_empty_str(str: &str) -> &str {65 if str.is_empty() {66 "\"\" (empty string)"67 } else {68 str69 }70}7172pub(crate) fn suggest_object_fields(v: &ObjValue, key: IStr) -> Vec<IStr> {73 let mut heap = Vec::new();74 for field in v.fields_ex(75 true,76 #[cfg(feature = "exp-preserve-order")]77 false,78 ) {79 let conf = strsim::jaro_winkler(field.as_str(), key.as_str());80 if conf < 0.8 {81 continue;82 }83 assert!(field.as_str() != key.as_str(), "looks like string pooling failure, please write any info regarding this crash to https://github.com/CertainLach/jrsonnet/issues/113, thanks!");8485 heap.push((conf, field));86 }87 heap.sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap_or(Ordering::Equal));88 heap.into_iter().map(|v| v.1).collect()89}9091type FunctionSignature = Vec<(Option<IStr>, bool)>;929394#[allow(missing_docs)]95#[derive(Error, Debug, Clone, Trace)]96#[non_exhaustive]97pub enum ErrorKind {98 #[error("intrinsic not found: {0}")]99 IntrinsicNotFound(IStr),100101 #[error("operator {0} does not operate on type {1}")]102 UnaryOperatorDoesNotOperateOnType(UnaryOpType, ValType),103 #[error("binary operation {1} {0} {2} is not implemented")]104 BinaryOperatorDoesNotOperateOnValues(BinaryOpType, ValType, ValType),105106 #[error("no top level object in this context")]107 NoTopLevelObjectFound,108 #[error("self is only usable inside objects")]109 CantUseSelfOutsideOfObject,110 #[error("no super found")]111 NoSuperFound,112113 #[error("for loop can only iterate over arrays")]114 InComprehensionCanOnlyIterateOverArray,115116 #[error("array out of bounds: {0} is not within [0,{1})")]117 ArrayBoundsError(usize, usize),118 #[error("string out of bounds: {0} is not within [0,{1})")]119 StringBoundsError(usize, usize),120121 #[error("assert failed: {}", format_empty_str(.0))]122 AssertionFailed(IStr),123124 #[error("variable is not defined: {0}{}", format_found(.1, "variable"))]125 VariableIsNotDefined(IStr, Vec<IStr>),126 #[error("duplicate local var: {0}")]127 DuplicateLocalVar(IStr),128129 #[error("type mismatch: expected {}, got {2} {0}", .1.iter().map(|e| format!("{e}")).collect::<Vec<_>>().join(", "))]130 TypeMismatch(&'static str, Vec<ValType>, ValType),131 #[error("no such field: {}{}", format_empty_str(.0), format_found(.1, "field"))]132 NoSuchField(IStr, Vec<IStr>),133134 #[error("only functions can be called, got {0}")]135 OnlyFunctionsCanBeCalledGot(ValType),136 #[error("parameter {0} is not defined")]137 UnknownFunctionParameter(String),138 #[error("argument {0} is already bound")]139 BindingParameterASecondTime(IStr),140 #[error("too many args, function has {0}{}", format_signature(.1))]141 TooManyArgsFunctionHas(usize, FunctionSignature),142 #[error("function argument is not passed: {}{}", .0.as_ref().map_or("<unnamed>", IStr::as_str), format_signature(.1))]143 FunctionParameterNotBoundInCall(Option<IStr>, FunctionSignature),144145 #[error("external variable is not defined: {0}")]146 UndefinedExternalVariable(IStr),147148 #[error("field name should be string, got {0}")]149 FieldMustBeStringGot(ValType),150 #[error("duplicate field name: {}", format_empty_str(.0))]151 DuplicateFieldName(IStr),152153 #[error("attempted to index array with string {}", format_empty_str(.0))]154 AttemptedIndexAnArrayWithString(IStr),155 #[error("{0} index type should be {1}, got {2}")]156 ValueIndexMustBeTypeGot(ValType, ValType, ValType),157 #[error("cant index into {0}")]158 CantIndexInto(ValType),159 #[error("{0} is not indexable")]160 ValueIsNotIndexable(ValType),161162 #[error("super can't be used standalone")]163 StandaloneSuper,164165 #[error("can't resolve {1} from {0}")]166 ImportFileNotFound(SourcePath, String),167 #[error("can't resolve absolute {0}")]168 AbsoluteImportFileNotFound(PathBuf),169 #[error("resolved file not found: {:?}", .0)]170 ResolvedFileNotFound(SourcePath),171 #[error("can't import {0}: is a directory")]172 ImportIsADirectory(SourcePath),173 #[error("imported file is not valid utf-8: {0:?}")]174 ImportBadFileUtf8(SourcePath),175 #[error("import io error: {0}")]176 ImportIo(String),177 #[error("tried to import {1} from {0}, but imports are not supported")]178 ImportNotSupported(SourcePath, String),179 #[error("tried to import {0}, but absolute imports are not supported")]180 AbsoluteImportNotSupported(PathBuf),181 #[error("can't import from virtual file")]182 CantImportFromVirtualFile,183 #[error(184 "syntax error: expected {}, got {:?}",185 .error.expected,186 .path.code().chars().nth(error.location.offset)187 .map_or_else(|| "EOF".into(), |c| c.to_string())188 )]189 ImportSyntaxError {190 path: Source,191 #[trace(skip)]192 error: Box<jrsonnet_parser::ParseError>,193 },194195 #[error("runtime error: {}", format_empty_str(.0))]196 RuntimeError(IStr),197 #[error("stack overflow, try to reduce recursion, or set --max-stack to bigger value")]198 StackOverflow,199 #[error("infinite recursion detected")]200 InfiniteRecursionDetected,201 #[error("tried to index by fractional value")]202 FractionalIndex,203 #[error("attempted to divide by zero")]204 DivisionByZero,205206 #[error("string manifest output is not an string")]207 StringManifestOutputIsNotAString,208 #[error("stream manifest output is not an array")]209 StreamManifestOutputIsNotAArray,210 #[error("multi manifest output is not an object")]211 MultiManifestOutputIsNotAObject,212213 #[error("cant recurse stream manifest")]214 StreamManifestOutputCannotBeRecursed,215 #[error("stream manifest output cannot consist of raw strings")]216 StreamManifestCannotNestString,217218 #[error("{}", format_empty_str(.0))]219 ImportCallbackError(String),220 #[error("invalid unicode codepoint: {0}")]221 InvalidUnicodeCodepointGot(u32),222223 #[error("format error: {0}")]224 Format(#[from] FormatError),225 #[error("type error: {0}")]226 TypeError(TypeLocError),227228 #[cfg(feature = "anyhow-error")]229 #[error(transparent)]230 Other(#[trace(skip)] std::rc::Rc<anyhow::Error>),231}232233#[cfg(feature = "anyhow-error")]234impl From<anyhow::Error> for Error {235 fn from(e: anyhow::Error) -> Self {236 Self::new(ErrorKind::Other(std::rc::Rc::new(e)))237 }238}239240impl From<ErrorKind> for Error {241 fn from(e: ErrorKind) -> Self {242 Self::new(e)243 }244}245246247#[derive(Clone, Debug, Trace)]248pub struct StackTraceElement {249 250 251 pub location: Option<ExprLocation>,252 253 pub desc: String,254}255#[derive(Debug, Clone, Trace)]256pub struct StackTrace(pub Vec<StackTraceElement>);257258#[derive(Clone, Trace)]259pub struct Error(Box<(ErrorKind, StackTrace)>);260impl Error {261 pub fn new(e: ErrorKind) -> Self {262 Self(Box::new((e, StackTrace(vec![]))))263 }264265 pub const fn error(&self) -> &ErrorKind {266 &(self.0).0267 }268 pub fn error_mut(&mut self) -> &mut ErrorKind {269 &mut (self.0).0270 }271 pub const fn trace(&self) -> &StackTrace {272 &(self.0).1273 }274 pub fn trace_mut(&mut self) -> &mut StackTrace {275 &mut (self.0).1276 }277}278impl Display for Error {279 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {280 writeln!(f, "{}", self.0 .0)?;281 for el in &self.0 .1 .0 {282 write!(f, "\t{}", el.desc)?;283 if let Some(loc) = &el.location {284 write!(f, "at {}", loc.0 .0 .0)?;285 loc.0.map_source_locations(&[loc.1, loc.2]);286 }287 writeln!(f)?;288 }289 Ok(())290 }291}292impl Debug for Error {293 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {294 f.debug_tuple("LocError").field(&self.0).finish()295 }296}297impl std::error::Error for Error {}298299pub trait ErrorSource {300 fn to_location(self) -> Option<ExprLocation>;301}302impl ErrorSource for &LocExpr {303 fn to_location(self) -> Option<ExprLocation> {304 Some(self.1.clone())305 }306}307impl ErrorSource for &ExprLocation {308 fn to_location(self) -> Option<ExprLocation> {309 Some(self.clone())310 }311}312impl ErrorSource for CallLocation<'_> {313 fn to_location(self) -> Option<ExprLocation> {314 self.0.cloned()315 }316}317318pub type Result<V, E = Error> = std::result::Result<V, E>;319pub trait ResultExt: Sized {320 #[must_use]321 fn with_description<O: Into<String>>(self, msg: impl FnOnce() -> O) -> Self;322 #[must_use]323 fn description(self, msg: &str) -> Self {324 self.with_description(|| msg)325 }326327 #[must_use]328 fn with_description_src<O: Into<String>>(329 self,330 src: impl ErrorSource,331 msg: impl FnOnce() -> O,332 ) -> Self;333 #[must_use]334 fn description_src(self, src: impl ErrorSource, msg: &str) -> Self {335 self.with_description_src(src, || msg)336 }337}338impl<T> ResultExt for Result<T, Error> {339 fn with_description<O: Into<String>>(mut self, msg: impl FnOnce() -> O) -> Self {340 if let Err(e) = &mut self {341 let trace = e.trace_mut();342 trace.0.push(StackTraceElement {343 location: None,344 desc: msg().into(),345 });346 }347 self348 }349350 fn with_description_src<O: Into<String>>(351 mut self,352 src: impl ErrorSource,353 msg: impl FnOnce() -> O,354 ) -> Self {355 if let Err(e) = &mut self {356 let trace = e.trace_mut();357 trace.0.push(StackTraceElement {358 location: src.to_location(),359 desc: msg().into(),360 });361 }362 self363 }364}365366#[macro_export]367macro_rules! throw {368 ($w:ident$(::$i:ident)*$(($($tt:tt)*))?) => {369 return Err($w$(::$i)*$(($($tt)*))?.into())370 };371 ($w:ident$(::$i:ident)*$({$($tt:tt)*})?) => {372 return Err($w$(::$i)*$({$($tt)*})?.into())373 };374 ($l:literal) => {375 return Err($crate::error::ErrorKind::RuntimeError($l.into()).into())376 };377 ($l:literal, $($tt:tt)*) => {378 return Err($crate::error::ErrorKind::RuntimeError(format!($l, $($tt)*).into()).into())379 };380}