1use crate::{2 builtin::{format::FormatError, sort::SortError},3 typed::TypeLocError,4};5use jrsonnet_interner::IStr;6use jrsonnet_parser::{BinaryOpType, ExprLocation, UnaryOpType};7use jrsonnet_types::ValType;8use std::{9 path::{Path, PathBuf},10 rc::Rc,11};12use thiserror::Error;1314#[derive(Error, Debug, Clone)]15pub enum Error {16 #[error("intrinsic not found: {0}")]17 IntrinsicNotFound(IStr),18 #[error("argument reordering in intrisics not supported yet")]19 IntrinsicArgumentReorderingIsNotSupportedYet,2021 #[error("operator {0} does not operate on type {1}")]22 UnaryOperatorDoesNotOperateOnType(UnaryOpType, ValType),23 #[error("binary operation {1} {0} {2} is not implemented")]24 BinaryOperatorDoesNotOperateOnValues(BinaryOpType, ValType, ValType),2526 #[error("no top level object in this context")]27 NoTopLevelObjectFound,28 #[error("self is only usable inside objects")]29 CantUseSelfOutsideOfObject,30 #[error("no super found")]31 NoSuperFound,3233 #[error("for loop can only iterate over arrays")]34 InComprehensionCanOnlyIterateOverArray,3536 #[error("array out of bounds: {0} is not within [0,{1})")]37 ArrayBoundsError(usize, usize),3839 #[error("assert failed: {0}")]40 AssertionFailed(IStr),4142 #[error("variable is not defined: {0}")]43 VariableIsNotDefined(IStr),44 #[error("type mismatch: expected {}, got {2} {0}", .1.iter().map(|e| format!("{}", e)).collect::<Vec<_>>().join(", "))]45 TypeMismatch(&'static str, Vec<ValType>, ValType),46 #[error("no such field: {0}")]47 NoSuchField(IStr),4849 #[error("only functions can be called, got {0}")]50 OnlyFunctionsCanBeCalledGot(ValType),51 #[error("parameter {0} is not defined")]52 UnknownFunctionParameter(String),53 #[error("argument {0} is already bound")]54 BindingParameterASecondTime(IStr),55 #[error("too many args, function has {0}")]56 TooManyArgsFunctionHas(usize),57 #[error("founction argument is not passed: {0}")]58 FunctionParameterNotBoundInCall(IStr),5960 #[error("external variable is not defined: {0}")]61 UndefinedExternalVariable(IStr),62 #[error("native is not defined: {0}")]63 UndefinedExternalFunction(IStr),6465 #[error("field name should be string, got {0}")]66 FieldMustBeStringGot(ValType),6768 #[error("attempted to index array with string {0}")]69 AttemptedIndexAnArrayWithString(IStr),70 #[error("{0} index type should be {1}, got {2}")]71 ValueIndexMustBeTypeGot(ValType, ValType, ValType),72 #[error("cant index into {0}")]73 CantIndexInto(ValType),7475 #[error("super can't be used standalone")]76 StandaloneSuper,7778 #[error("can't resolve {1} from {0}")]79 ImportFileNotFound(PathBuf, PathBuf),80 #[error("resolved file not found: {0}")]81 ResolvedFileNotFound(PathBuf),82 #[error("imported file is not valid utf-8: {0:?}")]83 ImportBadFileUtf8(PathBuf),84 #[error("tried to import {1} from {0}, but imports is not supported")]85 ImportNotSupported(PathBuf, PathBuf),86 #[error(87 "syntax error, expected one of {}, got {:?}",88 .error.expected,89 .source_code.chars().nth(error.location.offset).map(|c| c.to_string()).unwrap_or_else(|| "EOF".into())90 )]91 ImportSyntaxError {92 path: Rc<Path>,93 source_code: IStr,94 error: Box<jrsonnet_parser::ParseError>,95 },9697 #[error("runtime error: {0}")]98 RuntimeError(IStr),99 #[error("stack overflow, try to reduce recursion, or set --max-stack to bigger value")]100 StackOverflow,101 #[error("tried to index by fractional value")]102 FractionalIndex,103 #[error("attempted to divide by zero")]104 DivisionByZero,105106 #[error("string manifest output is not an string")]107 StringManifestOutputIsNotAString,108 #[error("stream manifest output is not an array")]109 StreamManifestOutputIsNotAArray,110 #[error("multi manifest output is not an object")]111 MultiManifestOutputIsNotAObject,112113 #[error("cant recurse stream manifest")]114 StreamManifestOutputCannotBeRecursed,115 #[error("stream manifest output cannot consist of raw strings")]116 StreamManifestCannotNestString,117118 #[error("{0}")]119 ImportCallbackError(String),120 #[error("invalid unicode codepoint: {0}")]121 InvalidUnicodeCodepointGot(u32),122123 #[error("format error: {0}")]124 Format(#[from] FormatError),125 #[error("type error: {0}")]126 TypeError(TypeLocError),127 #[error("sort error: {0}")]128 Sort(#[from] SortError),129130 #[cfg(feature = "anyhow-error")]131 #[error(transparent)]132 Other(Rc<anyhow::Error>),133}134135#[cfg(feature = "anyhow-error")]136impl From<anyhow::Error> for LocError {137 fn from(e: anyhow::Error) -> Self {138 Self::new(Error::Other(Rc::new(e)))139 }140}141142impl From<Error> for LocError {143 fn from(e: Error) -> Self {144 Self::new(e)145 }146}147148#[derive(Clone, Debug)]149pub struct StackTraceElement {150 pub location: Option<ExprLocation>,151 pub desc: String,152}153#[derive(Debug, Clone)]154pub struct StackTrace(pub Vec<StackTraceElement>);155156#[derive(Debug, Clone)]157pub struct LocError(Box<(Error, StackTrace)>);158impl LocError {159 pub fn new(e: Error) -> Self {160 Self(Box::new((e, StackTrace(vec![]))))161 }162163 pub const fn error(&self) -> &Error {164 &(self.0).0165 }166 pub fn error_mut(&mut self) -> &mut Error {167 &mut (self.0).0168 }169 pub const fn trace(&self) -> &StackTrace {170 &(self.0).1171 }172 pub fn trace_mut(&mut self) -> &mut StackTrace {173 &mut (self.0).1174 }175}176177pub type Result<V> = std::result::Result<V, LocError>;178179#[macro_export]180macro_rules! throw {181 ($e: expr) => {182 return Err($e.into());183 };184}