1use crate::{2 builtin::{format::FormatError, sort::SortError},3 typed::TypeLocError,4};5use gc::{Finalize, Trace};6use jrsonnet_interner::IStr;7use jrsonnet_parser::{BinaryOpType, ExprLocation, UnaryOpType};8use jrsonnet_types::ValType;9use std::{path::PathBuf, rc::Rc};10use thiserror::Error;1112#[derive(Error, Debug, Clone, Trace, Finalize)]13pub enum Error {14 #[error("intrinsic not found: {0}")]15 IntrinsicNotFound(IStr),16 #[error("argument reordering in intrisics not supported yet")]17 IntrinsicArgumentReorderingIsNotSupportedYet,1819 #[error("operator {0} does not operate on type {1}")]20 UnaryOperatorDoesNotOperateOnType(UnaryOpType, ValType),21 #[error("binary operation {1} {0} {2} is not implemented")]22 BinaryOperatorDoesNotOperateOnValues(BinaryOpType, ValType, ValType),2324 #[error("no top level object in this context")]25 NoTopLevelObjectFound,26 #[error("self is only usable inside objects")]27 CantUseSelfOutsideOfObject,28 #[error("no super found")]29 NoSuperFound,3031 #[error("for loop can only iterate over arrays")]32 InComprehensionCanOnlyIterateOverArray,3334 #[error("array out of bounds: {0} is not within [0,{1})")]35 ArrayBoundsError(usize, usize),3637 #[error("assert failed: {0}")]38 AssertionFailed(IStr),3940 #[error("variable is not defined: {0}")]41 VariableIsNotDefined(IStr),42 #[error("type mismatch: expected {}, got {2} {0}", .1.iter().map(|e| format!("{}", e)).collect::<Vec<_>>().join(", "))]43 TypeMismatch(&'static str, Vec<ValType>, ValType),44 #[error("no such field: {0}")]45 NoSuchField(IStr),4647 #[error("only functions can be called, got {0}")]48 OnlyFunctionsCanBeCalledGot(ValType),49 #[error("parameter {0} is not defined")]50 UnknownFunctionParameter(String),51 #[error("argument {0} is already bound")]52 BindingParameterASecondTime(IStr),53 #[error("too many args, function has {0}")]54 TooManyArgsFunctionHas(usize),55 #[error("founction argument is not passed: {0}")]56 FunctionParameterNotBoundInCall(IStr),5758 #[error("external variable is not defined: {0}")]59 UndefinedExternalVariable(IStr),60 #[error("native is not defined: {0}")]61 UndefinedExternalFunction(IStr),6263 #[error("field name should be string, got {0}")]64 FieldMustBeStringGot(ValType),6566 #[error("attempted to index array with string {0}")]67 AttemptedIndexAnArrayWithString(IStr),68 #[error("{0} index type should be {1}, got {2}")]69 ValueIndexMustBeTypeGot(ValType, ValType, ValType),70 #[error("cant index into {0}")]71 CantIndexInto(ValType),7273 #[error("super can't be used standalone")]74 StandaloneSuper,7576 #[error("can't resolve {1} from {0}")]77 ImportFileNotFound(PathBuf, PathBuf),78 #[error("resolved file not found: {0}")]79 ResolvedFileNotFound(PathBuf),80 #[error("imported file is not valid utf-8: {0:?}")]81 ImportBadFileUtf8(PathBuf),82 #[error("tried to import {1} from {0}, but imports is not supported")]83 ImportNotSupported(PathBuf, PathBuf),84 #[error(85 "syntax error, expected one of {}, got {:?}",86 .error.expected,87 .source_code.chars().nth(error.location.offset).map(|c| c.to_string()).unwrap_or_else(|| "EOF".into())88 )]89 ImportSyntaxError {90 path: Rc<PathBuf>,91 source_code: IStr,92 #[unsafe_ignore_trace]93 error: Box<jrsonnet_parser::ParseError>,94 },9596 #[error("runtime error: {0}")]97 RuntimeError(IStr),98 #[error("stack overflow, try to reduce recursion, or set --max-stack to bigger value")]99 StackOverflow,100 #[error("infinite recursion detected")]101 RecursiveLazyValueEvaluation,102 #[error("tried to index by fractional value")]103 FractionalIndex,104 #[error("attempted to divide by zero")]105 DivisionByZero,106107 #[error("string manifest output is not an string")]108 StringManifestOutputIsNotAString,109 #[error("stream manifest output is not an array")]110 StreamManifestOutputIsNotAArray,111 #[error("multi manifest output is not an object")]112 MultiManifestOutputIsNotAObject,113114 #[error("cant recurse stream manifest")]115 StreamManifestOutputCannotBeRecursed,116 #[error("stream manifest output cannot consist of raw strings")]117 StreamManifestCannotNestString,118119 #[error("{0}")]120 ImportCallbackError(String),121 #[error("invalid unicode codepoint: {0}")]122 InvalidUnicodeCodepointGot(u32),123124 #[error("format error: {0}")]125 Format(#[from] FormatError),126 #[error("type error: {0}")]127 TypeError(TypeLocError),128 #[error("sort error: {0}")]129 Sort(#[from] SortError),130131 #[cfg(feature = "anyhow-error")]132 #[error(transparent)]133 Other(Rc<anyhow::Error>),134}135136#[cfg(feature = "anyhow-error")]137impl From<anyhow::Error> for LocError {138 fn from(e: anyhow::Error) -> Self {139 Self::new(Error::Other(Rc::new(e)))140 }141}142143impl From<Error> for LocError {144 fn from(e: Error) -> Self {145 Self::new(e)146 }147}148149#[derive(Clone, Debug, Trace, Finalize)]150pub struct StackTraceElement {151 pub location: Option<ExprLocation>,152 pub desc: String,153}154#[derive(Debug, Clone, Trace, Finalize)]155pub struct StackTrace(pub Vec<StackTraceElement>);156157#[derive(Debug, Clone, Trace, Finalize)]158pub struct LocError(Box<(Error, StackTrace)>);159impl LocError {160 pub fn new(e: Error) -> Self {161 Self(Box::new((e, StackTrace(vec![]))))162 }163164 pub const fn error(&self) -> &Error {165 &(self.0).0166 }167 pub fn error_mut(&mut self) -> &mut Error {168 &mut (self.0).0169 }170 pub const fn trace(&self) -> &StackTrace {171 &(self.0).1172 }173 pub fn trace_mut(&mut self) -> &mut StackTrace {174 &mut (self.0).1175 }176}177178pub type Result<V> = std::result::Result<V, LocError>;179180#[macro_export]181macro_rules! throw {182 ($e: expr) => {183 return Err($e.into());184 };185}