1use crate::{2 builtin::{format::FormatError, sort::SortError},3 typed::TypeLocError,4};5use jrsonnet_parser::{BinaryOpType, ExprLocation, UnaryOpType};6use jrsonnet_types::ValType;7use std::{path::PathBuf, rc::Rc};8use thiserror::Error;910#[derive(Error, Debug, Clone)]11pub enum Error {12 #[error("intrinsic not found: {0}")]13 IntrinsicNotFound(Rc<str>),14 #[error("argument reordering in intrisics not supported yet")]15 IntrinsicArgumentReorderingIsNotSupportedYet,1617 #[error("operator {0} does not operate on type {1}")]18 UnaryOperatorDoesNotOperateOnType(UnaryOpType, ValType),19 #[error("binary operation {1} {0} {2} is not implemented")]20 BinaryOperatorDoesNotOperateOnValues(BinaryOpType, ValType, ValType),2122 #[error("no top level object in this context")]23 NoTopLevelObjectFound,24 #[error("self is only usable inside objects")]25 CantUseSelfOutsideOfObject,26 #[error("super is only usable inside objects")]27 CantUseSuperOutsideOfObject,2829 #[error("for loop can only iterate over arrays")]30 InComprehensionCanOnlyIterateOverArray,3132 #[error("array out of bounds: {0} is not within [0,{1})")]33 ArrayBoundsError(usize, usize),3435 #[error("assert failed: {0}")]36 AssertionFailed(Rc<str>),3738 #[error("variable is not defined: {0}")]39 VariableIsNotDefined(Rc<str>),40 #[error("type mismatch: expected {}, got {2} {0}", .1.iter().map(|e| format!("{}", e)).collect::<Vec<_>>().join(", "))]41 TypeMismatch(&'static str, Vec<ValType>, ValType),42 #[error("no such field: {0}")]43 NoSuchField(Rc<str>),4445 #[error("only functions can be called, got {0}")]46 OnlyFunctionsCanBeCalledGot(ValType),47 #[error("parameter {0} is not defined")]48 UnknownFunctionParameter(String),49 #[error("argument {0} is already bound")]50 BindingParameterASecondTime(Rc<str>),51 #[error("too many args, function has {0}")]52 TooManyArgsFunctionHas(usize),53 #[error("founction argument is not passed: {0}")]54 FunctionParameterNotBoundInCall(Rc<str>),5556 #[error("external variable is not defined: {0}")]57 UndefinedExternalVariable(Rc<str>),58 #[error("native is not defined: {0}")]59 UndefinedExternalFunction(Rc<str>),6061 #[error("field name should be string, got {0}")]62 FieldMustBeStringGot(ValType),6364 #[error("attempted to index array with string {0}")]65 AttemptedIndexAnArrayWithString(Rc<str>),66 #[error("{0} index type should be {1}, got {2}")]67 ValueIndexMustBeTypeGot(ValType, ValType, ValType),68 #[error("cant index into {0}")]69 CantIndexInto(ValType),7071 #[error("super can't be used standalone")]72 StandaloneSuper,7374 #[error("can't resolve {1} from {0}")]75 ImportFileNotFound(PathBuf, PathBuf),76 #[error("resolved file not found: {0}")]77 ResolvedFileNotFound(PathBuf),78 #[error("imported file is not valid utf-8: {0:?}")]79 ImportBadFileUtf8(PathBuf),80 #[error("tried to import {1} from {0}, but imports is not supported")]81 ImportNotSupported(PathBuf, PathBuf),82 #[error(83 "syntax error, expected one of {}, got {:?}",84 .error.expected,85 .source_code.chars().nth(error.location.offset).map(|c| c.to_string()).unwrap_or_else(|| "EOF".into())86 )]87 ImportSyntaxError {88 path: Rc<PathBuf>,89 source_code: Rc<str>,90 error: Box<jrsonnet_parser::ParseError>,91 },9293 #[error("runtime error: {0}")]94 RuntimeError(Rc<str>),95 #[error("stack overflow, try to reduce recursion, or set --max-stack to bigger value")]96 StackOverflow,97 #[error("tried to index by fractional value")]98 FractionalIndex,99 #[error("attempted to divide by zero")]100 DivisionByZero,101102 #[error("string manifest output is not an string")]103 StringManifestOutputIsNotAString,104 #[error("stream manifest output is not an array")]105 StreamManifestOutputIsNotAArray,106 #[error("multi manifest output is not an object")]107 MultiManifestOutputIsNotAObject,108109 #[error("cant recurse stream manifest")]110 StreamManifestOutputCannotBeRecursed,111 #[error("stream manifest output cannot consist of raw strings")]112 StreamManifestCannotNestString,113114 #[error("{0}")]115 ImportCallbackError(String),116 #[error("invalid unicode codepoint: {0}")]117 InvalidUnicodeCodepointGot(u32),118119 #[error("format error: {0}")]120 Format(#[from] FormatError),121 #[error("type error: {0}")]122 TypeError(TypeLocError),123 #[error("sort error: {0}")]124 Sort(#[from] SortError),125}126impl From<Error> for LocError {127 fn from(e: Error) -> Self {128 Self::new(e)129 }130}131132#[derive(Clone, Debug)]133pub struct StackTraceElement {134 pub location: ExprLocation,135 pub desc: String,136}137#[derive(Debug, Clone)]138pub struct StackTrace(pub Vec<StackTraceElement>);139140#[derive(Debug, Clone)]141pub struct LocError(Box<(Error, StackTrace)>);142impl LocError {143 pub fn new(e: Error) -> Self {144 Self(Box::new((e, StackTrace(vec![]))))145 }146147 pub const fn error(&self) -> &Error {148 &(self.0).0149 }150 pub fn error_mut(&mut self) -> &mut Error {151 &mut (self.0).0152 }153 pub const fn trace(&self) -> &StackTrace {154 &(self.0).1155 }156 pub fn trace_mut(&mut self) -> &mut StackTrace {157 &mut (self.0).1158 }159}160161pub type Result<V> = std::result::Result<V, LocError>;162163#[macro_export]164macro_rules! throw {165 ($e: expr) => {166 return Err($e.into());167 };168}