1use std::{2 path::{Path, PathBuf},3 rc::Rc,4};56use gcmodule::Trace;7use jrsonnet_interner::IStr;8use jrsonnet_parser::{BinaryOpType, ExprLocation, UnaryOpType};9use jrsonnet_types::ValType;10use thiserror::Error;1112use crate::{13 builtin::{format::FormatError, sort::SortError},14 typed::TypeLocError,15};1617#[derive(Error, Debug, Clone, Trace)]18pub enum Error {19 #[error("intrinsic not found: {0}")]20 IntrinsicNotFound(IStr),2122 #[error("operator {0} does not operate on type {1}")]23 UnaryOperatorDoesNotOperateOnType(UnaryOpType, ValType),24 #[error("binary operation {1} {0} {2} is not implemented")]25 BinaryOperatorDoesNotOperateOnValues(BinaryOpType, ValType, ValType),2627 #[error("no top level object in this context")]28 NoTopLevelObjectFound,29 #[error("self is only usable inside objects")]30 CantUseSelfOutsideOfObject,31 #[error("no super found")]32 NoSuperFound,3334 #[error("for loop can only iterate over arrays")]35 InComprehensionCanOnlyIterateOverArray,3637 #[error("array out of bounds: {0} is not within [0,{1})")]38 ArrayBoundsError(usize, usize),3940 #[error("assert failed: {0}")]41 AssertionFailed(IStr),4243 #[error("variable is not defined: {0}")]44 VariableIsNotDefined(IStr),45 #[error("type mismatch: expected {}, got {2} {0}", .1.iter().map(|e| format!("{}", e)).collect::<Vec<_>>().join(", "))]46 TypeMismatch(&'static str, Vec<ValType>, ValType),47 #[error("no such field: {0}")]48 NoSuchField(IStr),4950 #[error("only functions can be called, got {0}")]51 OnlyFunctionsCanBeCalledGot(ValType),52 #[error("parameter {0} is not defined")]53 UnknownFunctionParameter(String),54 #[error("argument {0} is already bound")]55 BindingParameterASecondTime(IStr),56 #[error("too many args, function has {0}")]57 TooManyArgsFunctionHas(usize),58 #[error("function argument is not passed: {0}")]59 FunctionParameterNotBoundInCall(IStr),6061 #[error("external variable is not defined: {0}")]62 UndefinedExternalVariable(IStr),63 #[error("native is not defined: {0}")]64 UndefinedExternalFunction(IStr),6566 #[error("field name should be string, got {0}")]67 FieldMustBeStringGot(ValType),68 #[error("duplicate field name: {0}")]69 DuplicateFieldName(IStr),7071 #[error("attempted to index array with string {0}")]72 AttemptedIndexAnArrayWithString(IStr),73 #[error("{0} index type should be {1}, got {2}")]74 ValueIndexMustBeTypeGot(ValType, ValType, ValType),75 #[error("cant index into {0}")]76 CantIndexInto(ValType),77 #[error("{0} is not indexable")]78 ValueIsNotIndexable(ValType),7980 #[error("super can't be used standalone")]81 StandaloneSuper,8283 #[error("can't resolve {1} from {0}")]84 ImportFileNotFound(PathBuf, PathBuf),85 #[error("resolved file not found: {0}")]86 ResolvedFileNotFound(PathBuf),87 #[error("imported file is not valid utf-8: {0:?}")]88 ImportBadFileUtf8(PathBuf),89 #[error("import io error: {0}")]90 ImportIo(String),91 #[error("tried to import {1} from {0}, but imports is not supported")]92 ImportNotSupported(PathBuf, PathBuf),93 #[error(94 "syntax error: expected {}, got {:?}",95 .error.expected,96 .source_code.chars().nth(error.location.offset).map(|c| c.to_string()).unwrap_or_else(|| "EOF".into())97 )]98 ImportSyntaxError {99 #[skip_trace]100 path: Rc<Path>,101 source_code: IStr,102 #[skip_trace]103 error: Box<jrsonnet_parser::ParseError>,104 },105106 #[error("runtime error: {0}")]107 RuntimeError(IStr),108 #[error("stack overflow, try to reduce recursion, or set --max-stack to bigger value")]109 StackOverflow,110 #[error("infinite recursion detected")]111 InfiniteRecursionDetected,112 #[error("tried to index by fractional value")]113 FractionalIndex,114 #[error("attempted to divide by zero")]115 DivisionByZero,116117 #[error("string manifest output is not an string")]118 StringManifestOutputIsNotAString,119 #[error("stream manifest output is not an array")]120 StreamManifestOutputIsNotAArray,121 #[error("multi manifest output is not an object")]122 MultiManifestOutputIsNotAObject,123124 #[error("cant recurse stream manifest")]125 StreamManifestOutputCannotBeRecursed,126 #[error("stream manifest output cannot consist of raw strings")]127 StreamManifestCannotNestString,128129 #[error("{0}")]130 ImportCallbackError(String),131 #[error("invalid unicode codepoint: {0}")]132 InvalidUnicodeCodepointGot(u32),133134 #[error("format error: {0}")]135 Format(#[from] FormatError),136 #[error("type error: {0}")]137 TypeError(TypeLocError),138 #[error("sort error: {0}")]139 Sort(#[from] SortError),140141 #[cfg(feature = "anyhow-error")]142 #[error(transparent)]143 Other(Rc<anyhow::Error>),144}145146#[cfg(feature = "anyhow-error")]147impl From<anyhow::Error> for LocError {148 fn from(e: anyhow::Error) -> Self {149 Self::new(Error::Other(Rc::new(e)))150 }151}152153impl From<Error> for LocError {154 fn from(e: Error) -> Self {155 Self::new(e)156 }157}158159#[derive(Clone, Debug, Trace)]160pub struct StackTraceElement {161 pub location: Option<ExprLocation>,162 pub desc: String,163}164#[derive(Debug, Clone, Trace)]165pub struct StackTrace(pub Vec<StackTraceElement>);166167#[derive(Debug, Clone, Trace)]168pub struct LocError(Box<(Error, StackTrace)>);169impl LocError {170 pub fn new(e: Error) -> Self {171 Self(Box::new((e, StackTrace(vec![]))))172 }173174 pub const fn error(&self) -> &Error {175 &(self.0).0176 }177 pub fn error_mut(&mut self) -> &mut Error {178 &mut (self.0).0179 }180 pub const fn trace(&self) -> &StackTrace {181 &(self.0).1182 }183 pub fn trace_mut(&mut self) -> &mut StackTrace {184 &mut (self.0).1185 }186}187188pub type Result<V, E = LocError> = std::result::Result<V, E>;189190#[macro_export]191macro_rules! throw {192 ($e: expr) => {193 return Err($e.into())194 };195}196197#[macro_export]198macro_rules! throw_runtime {199 ($($tt:tt)*) => {200 return Err($crate::error::Error::RuntimeError(format!($($tt)*).into()).into())201 };202}