1use crate::{2 builtin::{format::FormatError, sort::SortError},3 typed::TypeLocError,4};5use gcmodule::Trace;6use jrsonnet_interner::IStr;7use jrsonnet_parser::{BinaryOpType, ExprLocation, UnaryOpType};8use jrsonnet_types::ValType;9use std::{10 path::{Path, PathBuf},11 rc::Rc,12};13use thiserror::Error;1415#[derive(Error, Debug, Clone, Trace)]16pub enum Error {17 #[error("intrinsic not found: {0}")]18 IntrinsicNotFound(IStr),1920 #[error("operator {0} does not operate on type {1}")]21 UnaryOperatorDoesNotOperateOnType(UnaryOpType, ValType),22 #[error("binary operation {1} {0} {2} is not implemented")]23 BinaryOperatorDoesNotOperateOnValues(BinaryOpType, ValType, ValType),2425 #[error("no top level object in this context")]26 NoTopLevelObjectFound,27 #[error("self is only usable inside objects")]28 CantUseSelfOutsideOfObject,29 #[error("no super found")]30 NoSuperFound,3132 #[error("for loop can only iterate over arrays")]33 InComprehensionCanOnlyIterateOverArray,3435 #[error("array out of bounds: {0} is not within [0,{1})")]36 ArrayBoundsError(usize, usize),3738 #[error("assert failed: {0}")]39 AssertionFailed(IStr),4041 #[error("variable is not defined: {0}")]42 VariableIsNotDefined(IStr),43 #[error("type mismatch: expected {}, got {2} {0}", .1.iter().map(|e| format!("{}", e)).collect::<Vec<_>>().join(", "))]44 TypeMismatch(&'static str, Vec<ValType>, ValType),45 #[error("no such field: {0}")]46 NoSuchField(IStr),4748 #[error("only functions can be called, got {0}")]49 OnlyFunctionsCanBeCalledGot(ValType),50 #[error("parameter {0} is not defined")]51 UnknownFunctionParameter(String),52 #[error("argument {0} is already bound")]53 BindingParameterASecondTime(IStr),54 #[error("too many args, function has {0}")]55 TooManyArgsFunctionHas(usize),56 #[error("function argument is not passed: {0}")]57 FunctionParameterNotBoundInCall(IStr),5859 #[error("external variable is not defined: {0}")]60 UndefinedExternalVariable(IStr),61 #[error("native is not defined: {0}")]62 UndefinedExternalFunction(IStr),6364 #[error("field name should be string, got {0}")]65 FieldMustBeStringGot(ValType),6667 #[error("attempted to index array with string {0}")]68 AttemptedIndexAnArrayWithString(IStr),69 #[error("{0} index type should be {1}, got {2}")]70 ValueIndexMustBeTypeGot(ValType, ValType, ValType),71 #[error("cant index into {0}")]72 CantIndexInto(ValType),73 #[error("{0} is not indexable")]74 ValueIsNotIndexable(ValType),7576 #[error("super can't be used standalone")]77 StandaloneSuper,7879 #[error("can't resolve {1} from {0}")]80 ImportFileNotFound(PathBuf, PathBuf),81 #[error("resolved file not found: {0}")]82 ResolvedFileNotFound(PathBuf),83 #[error("imported file is not valid utf-8: {0:?}")]84 ImportBadFileUtf8(PathBuf),85 #[error("tried to import {1} from {0}, but imports is not supported")]86 ImportNotSupported(PathBuf, PathBuf),87 #[error(88 "syntax error: expected {}, got {:?}",89 .error.expected,90 .source_code.chars().nth(error.location.offset).map(|c| c.to_string()).unwrap_or_else(|| "EOF".into())91 )]92 ImportSyntaxError {93 #[skip_trace]94 path: Rc<Path>,95 source_code: IStr,96 #[skip_trace]97 error: Box<jrsonnet_parser::ParseError>,98 },99100 #[error("runtime error: {0}")]101 RuntimeError(IStr),102 #[error("stack overflow, try to reduce recursion, or set --max-stack to bigger value")]103 StackOverflow,104 #[error("infinite recursion detected")]105 RecursiveLazyValueEvaluation,106 #[error("tried to index by fractional value")]107 FractionalIndex,108 #[error("attempted to divide by zero")]109 DivisionByZero,110111 #[error("string manifest output is not an string")]112 StringManifestOutputIsNotAString,113 #[error("stream manifest output is not an array")]114 StreamManifestOutputIsNotAArray,115 #[error("multi manifest output is not an object")]116 MultiManifestOutputIsNotAObject,117118 #[error("cant recurse stream manifest")]119 StreamManifestOutputCannotBeRecursed,120 #[error("stream manifest output cannot consist of raw strings")]121 StreamManifestCannotNestString,122123 #[error("{0}")]124 ImportCallbackError(String),125 #[error("invalid unicode codepoint: {0}")]126 InvalidUnicodeCodepointGot(u32),127128 #[error("format error: {0}")]129 Format(#[from] FormatError),130 #[error("type error: {0}")]131 TypeError(TypeLocError),132 #[error("sort error: {0}")]133 Sort(#[from] SortError),134135 #[cfg(feature = "anyhow-error")]136 #[error(transparent)]137 Other(Rc<anyhow::Error>),138}139140#[cfg(feature = "anyhow-error")]141impl From<anyhow::Error> for LocError {142 fn from(e: anyhow::Error) -> Self {143 Self::new(Error::Other(Rc::new(e)))144 }145}146147impl From<Error> for LocError {148 fn from(e: Error) -> Self {149 Self::new(e)150 }151}152153#[derive(Clone, Debug, Trace)]154pub struct StackTraceElement {155 pub location: Option<ExprLocation>,156 pub desc: String,157}158#[derive(Debug, Clone, Trace)]159pub struct StackTrace(pub Vec<StackTraceElement>);160161#[derive(Debug, Clone, Trace)]162pub struct LocError(Box<(Error, StackTrace)>);163impl LocError {164 pub fn new(e: Error) -> Self {165 Self(Box::new((e, StackTrace(vec![]))))166 }167168 pub const fn error(&self) -> &Error {169 &(self.0).0170 }171 pub fn error_mut(&mut self) -> &mut Error {172 &mut (self.0).0173 }174 pub const fn trace(&self) -> &StackTrace {175 &(self.0).1176 }177 pub fn trace_mut(&mut self) -> &mut StackTrace {178 &mut (self.0).1179 }180}181182pub type Result<V, E = LocError> = std::result::Result<V, E>;183184#[macro_export]185macro_rules! throw {186 ($e: expr) => {187 return Err($e.into())188 };189}