1use std::{2 fmt::Debug,3 path::{Path, PathBuf},4 rc::Rc,5};67use gcmodule::Trace;8use jrsonnet_interner::IStr;9use jrsonnet_parser::{BinaryOpType, ExprLocation, UnaryOpType};10use jrsonnet_types::ValType;11use thiserror::Error;1213use crate::{14 stdlib::{format::FormatError, sort::SortError},15 typed::TypeLocError,16};1718#[derive(Error, Debug, Clone, Trace)]19pub enum Error {20 #[error("intrinsic not found: {0}")]21 IntrinsicNotFound(IStr),2223 #[error("operator {0} does not operate on type {1}")]24 UnaryOperatorDoesNotOperateOnType(UnaryOpType, ValType),25 #[error("binary operation {1} {0} {2} is not implemented")]26 BinaryOperatorDoesNotOperateOnValues(BinaryOpType, ValType, ValType),2728 #[error("no top level object in this context")]29 NoTopLevelObjectFound,30 #[error("self is only usable inside objects")]31 CantUseSelfOutsideOfObject,32 #[error("no super found")]33 NoSuperFound,3435 #[error("for loop can only iterate over arrays")]36 InComprehensionCanOnlyIterateOverArray,3738 #[error("array out of bounds: {0} is not within [0,{1})")]39 ArrayBoundsError(usize, usize),40 #[error("string out of bounds: {0} is not within [0,{1})")]41 StringBoundsError(usize, usize),4243 #[error("assert failed: {0}")]44 AssertionFailed(IStr),4546 #[error("variable is not defined: {0}")]47 VariableIsNotDefined(IStr),48 #[error("duplicate local var: {0}")]49 DuplicateLocalVar(IStr),5051 #[error("type mismatch: expected {}, got {2} {0}", .1.iter().map(|e| format!("{}", e)).collect::<Vec<_>>().join(", "))]52 TypeMismatch(&'static str, Vec<ValType>, ValType),53 #[error("no such field: {0}")]54 NoSuchField(IStr),5556 #[error("only functions can be called, got {0}")]57 OnlyFunctionsCanBeCalledGot(ValType),58 #[error("parameter {0} is not defined")]59 UnknownFunctionParameter(String),60 #[error("argument {0} is already bound")]61 BindingParameterASecondTime(IStr),62 #[error("too many args, function has {0}")]63 TooManyArgsFunctionHas(usize),64 #[error("function argument is not passed: {0}")]65 FunctionParameterNotBoundInCall(IStr),6667 #[error("external variable is not defined: {0}")]68 UndefinedExternalVariable(IStr),6970 #[error("field name should be string, got {0}")]71 FieldMustBeStringGot(ValType),72 #[error("duplicate field name: {0}")]73 DuplicateFieldName(IStr),7475 #[error("attempted to index array with string {0}")]76 AttemptedIndexAnArrayWithString(IStr),77 #[error("{0} index type should be {1}, got {2}")]78 ValueIndexMustBeTypeGot(ValType, ValType, ValType),79 #[error("cant index into {0}")]80 CantIndexInto(ValType),81 #[error("{0} is not indexable")]82 ValueIsNotIndexable(ValType),8384 #[error("super can't be used standalone")]85 StandaloneSuper,8687 #[error("can't resolve {1} from {0}")]88 ImportFileNotFound(PathBuf, PathBuf),89 #[error("resolved file not found: {0}")]90 ResolvedFileNotFound(PathBuf),91 #[error("imported file is not valid utf-8: {0:?}")]92 ImportBadFileUtf8(PathBuf),93 #[error("import io error: {0}")]94 ImportIo(String),95 #[error("tried to import {1} from {0}, but imports is not supported")]96 ImportNotSupported(PathBuf, PathBuf),97 #[error(98 "syntax error: expected {}, got {:?}",99 .error.expected,100 .source_code.chars().nth(error.location.offset)101 .map_or_else(|| "EOF".into(), |c| c.to_string())102 )]103 ImportSyntaxError {104 #[skip_trace]105 path: Rc<Path>,106 source_code: IStr,107 #[skip_trace]108 error: Box<jrsonnet_parser::ParseError>,109 },110111 #[error("runtime error: {0}")]112 RuntimeError(IStr),113 #[error("stack overflow, try to reduce recursion, or set --max-stack to bigger value")]114 StackOverflow,115 #[error("infinite recursion detected")]116 InfiniteRecursionDetected,117 #[error("tried to index by fractional value")]118 FractionalIndex,119 #[error("attempted to divide by zero")]120 DivisionByZero,121122 #[error("string manifest output is not an string")]123 StringManifestOutputIsNotAString,124 #[error("stream manifest output is not an array")]125 StreamManifestOutputIsNotAArray,126 #[error("multi manifest output is not an object")]127 MultiManifestOutputIsNotAObject,128129 #[error("cant recurse stream manifest")]130 StreamManifestOutputCannotBeRecursed,131 #[error("stream manifest output cannot consist of raw strings")]132 StreamManifestCannotNestString,133134 #[error("{0}")]135 ImportCallbackError(String),136 #[error("invalid unicode codepoint: {0}")]137 InvalidUnicodeCodepointGot(u32),138139 #[error("format error: {0}")]140 Format(#[from] FormatError),141 #[error("type error: {0}")]142 TypeError(TypeLocError),143 #[error("sort error: {0}")]144 Sort(#[from] SortError),145146 147 148 #[error("should not reach outside: std.thisFile")]149 MagicThisFileUsed,150151 #[cfg(feature = "anyhow-error")]152 #[error(transparent)]153 Other(Rc<anyhow::Error>),154}155156#[cfg(feature = "anyhow-error")]157impl From<anyhow::Error> for LocError {158 fn from(e: anyhow::Error) -> Self {159 Self::new(Error::Other(Rc::new(e)))160 }161}162163impl From<Error> for LocError {164 fn from(e: Error) -> Self {165 Self::new(e)166 }167}168169#[derive(Clone, Debug, Trace)]170pub struct StackTraceElement {171 pub location: Option<ExprLocation>,172 pub desc: String,173}174#[derive(Debug, Clone, Trace)]175pub struct StackTrace(pub Vec<StackTraceElement>);176177#[derive(Clone, Trace)]178pub struct LocError(Box<(Error, StackTrace)>);179impl LocError {180 pub fn new(e: Error) -> Self {181 Self(Box::new((e, StackTrace(vec![]))))182 }183184 pub const fn error(&self) -> &Error {185 &(self.0).0186 }187 pub fn error_mut(&mut self) -> &mut Error {188 &mut (self.0).0189 }190 pub const fn trace(&self) -> &StackTrace {191 &(self.0).1192 }193 pub fn trace_mut(&mut self) -> &mut StackTrace {194 &mut (self.0).1195 }196}197impl Debug for LocError {198 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {199 writeln!(f, "{}", self.0 .0)?;200 for el in &self.0 .1 .0 {201 writeln!(f, "\t{:?}", el)?;202 }203 Ok(())204 }205}206207pub type Result<V, E = LocError> = std::result::Result<V, E>;208209#[macro_export]210macro_rules! throw {211 ($e: expr) => {212 return Err($e.into())213 };214}215216#[macro_export]217macro_rules! throw_runtime {218 ($($tt:tt)*) => {219 return Err($crate::error::Error::RuntimeError(format!($($tt)*).into()).into())220 };221}