1use crate::{2 builtin::{format::FormatError, sort::SortError},3 ValType,4};5use jrsonnet_parser::{BinaryOpType, ExprLocation, UnaryOpType};6use std::{path::PathBuf, rc::Rc};7use thiserror::Error;89#[derive(Error, Debug, Clone)]10pub enum Error {11 #[error("intrinsic not found: {0}")]12 IntrinsicNotFound(Rc<str>),13 #[error("argument reordering in intrisics not supported yet")]14 IntrinsicArgumentReorderingIsNotSupportedYet,1516 #[error("operator {0} does not operate on type {1}")]17 UnaryOperatorDoesNotOperateOnType(UnaryOpType, ValType),18 #[error("binary operation {1} {0} {2} is not implemented")]19 BinaryOperatorDoesNotOperateOnValues(BinaryOpType, ValType, ValType),2021 #[error("no top level object in this context")]22 NoTopLevelObjectFound,23 #[error("self is only usable inside objects")]24 CantUseSelfOutsideOfObject,25 #[error("super is only usable inside objects")]26 CantUseSuperOutsideOfObject,2728 #[error("for loop can only iterate over arrays")]29 InComprehensionCanOnlyIterateOverArray,3031 #[error("array out of bounds: {0} is not within [0,{1})")]32 ArrayBoundsError(usize, usize),3334 #[error("assert failed: {0}")]35 AssertionFailed(Rc<str>),3637 #[error("variable is not defined: {0}")]38 VariableIsNotDefined(Rc<str>),39 #[error("type mismatch: expected {}, got {2} {0}", .1.iter().map(|e| format!("{}", e)).collect::<Vec<_>>().join(", "))]40 TypeMismatch(&'static str, Vec<ValType>, ValType),41 #[error("no such field: {0}")]42 NoSuchField(Rc<str>),4344 #[error("only functions can be called, got {0}")]45 OnlyFunctionsCanBeCalledGot(ValType),46 #[error("parameter {0} is not defined")]47 UnknownFunctionParameter(String),48 #[error("argument {0} is already bound")]49 BindingParameterASecondTime(Rc<str>),50 #[error("too many args, function has {0}")]51 TooManyArgsFunctionHas(usize),52 #[error("founction argument is not passed: {0}")]53 FunctionParameterNotBoundInCall(Rc<str>),5455 #[error("external variable is not defined: {0}")]56 UndefinedExternalVariable(Rc<str>),57 #[error("native is not defined: {0}")]58 UndefinedExternalFunction(Rc<str>),5960 #[error("field name should be string, got {0}")]61 FieldMustBeStringGot(ValType),6263 #[error("attempted to index array with string {0}")]64 AttemptedIndexAnArrayWithString(Rc<str>),65 #[error("{0} index type should be {1}, got {2}")]66 ValueIndexMustBeTypeGot(ValType, ValType, ValType),67 #[error("cant index into {0}")]68 CantIndexInto(ValType),6970 #[error("super can't be used standalone")]71 StandaloneSuper,7273 #[error("can't resolve {1} from {0}")]74 ImportFileNotFound(PathBuf, PathBuf),75 #[error("resolved file not found: {0}")]76 ResolvedFileNotFound(PathBuf),77 #[error("imported file is not valid utf-8: {0:?}")]78 ImportBadFileUtf8(PathBuf),79 #[error("tried to import {1} from {0}, but imports is not supported")]80 ImportNotSupported(PathBuf, PathBuf),81 #[error(82 "syntax error, expected one of {}, got {:?}",83 .error.expected,84 .source_code.chars().nth(error.location.offset).map(|c| c.to_string()).unwrap_or_else(|| "EOF".into())85 )]86 ImportSyntaxError {87 path: Rc<PathBuf>,88 source_code: Rc<str>,89 error: Box<jrsonnet_parser::ParseError>,90 },9192 #[error("runtime error: {0}")]93 RuntimeError(Rc<str>),94 #[error("stack overflow, try to reduce recursion, or set --max-stack to bigger value")]95 StackOverflow,96 #[error("tried to index by fractional value")]97 FractionalIndex,98 #[error("attempted to divide by zero")]99 DivisionByZero,100101 #[error("string manifest output is not an string")]102 StringManifestOutputIsNotAString,103 #[error("stream manifest output is not an array")]104 StreamManifestOutputIsNotAArray,105 #[error("multi manifest output is not an object")]106 MultiManifestOutputIsNotAObject,107108 #[error("cant recurse stream manifest")]109 StreamManifestOutputCannotBeRecursed,110 #[error("stream manifest output cannot consist of raw strings")]111 StreamManifestCannotNestString,112113 #[error("{0}")]114 ImportCallbackError(String),115 #[error("invalid unicode codepoint: {0}")]116 InvalidUnicodeCodepointGot(u32),117118 #[error("format error: {0}")]119 Format(#[from] FormatError),120 #[error("sort error: {0}")]121 Sort(#[from] SortError),122}123impl From<Error> for LocError {124 fn from(e: Error) -> Self {125 Self::new(e)126 }127}128129#[derive(Clone, Debug)]130pub struct StackTraceElement {131 pub location: ExprLocation,132 pub desc: String,133}134#[derive(Debug, Clone)]135pub struct StackTrace(pub Vec<StackTraceElement>);136137#[derive(Debug, Clone)]138pub struct LocError(Box<(Error, StackTrace)>);139impl LocError {140 pub fn new(e: Error) -> Self {141 Self(Box::new((e, StackTrace(vec![]))))142 }143144 pub const fn error(&self) -> &Error {145 &(self.0).0146 }147 pub const fn trace(&self) -> &StackTrace {148 &(self.0).1149 }150 pub fn trace_mut(&mut self) -> &mut StackTrace {151 &mut (self.0).1152 }153}154155pub type Result<V> = std::result::Result<V, LocError>;156157#[macro_export]158macro_rules! throw {159 ($e: expr) => {160 return Err($e.into());161 };162}