git.delta.rocks / jrsonnet / refs/commits / 321e7ee3e21c

difftreelog

source

crates/jrsonnet-evaluator/src/error.rs5.5 KiBsourcehistory
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),39	#[error("string out of bounds: {0} is not within [0,{1})")]40	StringBoundsError(usize, usize),4142	#[error("assert failed: {0}")]43	AssertionFailed(IStr),4445	#[error("variable is not defined: {0}")]46	VariableIsNotDefined(IStr),47	#[error("type mismatch: expected {}, got {2} {0}", .1.iter().map(|e| format!("{}", e)).collect::<Vec<_>>().join(", "))]48	TypeMismatch(&'static str, Vec<ValType>, ValType),49	#[error("no such field: {0}")]50	NoSuchField(IStr),5152	#[error("only functions can be called, got {0}")]53	OnlyFunctionsCanBeCalledGot(ValType),54	#[error("parameter {0} is not defined")]55	UnknownFunctionParameter(String),56	#[error("argument {0} is already bound")]57	BindingParameterASecondTime(IStr),58	#[error("too many args, function has {0}")]59	TooManyArgsFunctionHas(usize),60	#[error("function argument is not passed: {0}")]61	FunctionParameterNotBoundInCall(IStr),6263	#[error("external variable is not defined: {0}")]64	UndefinedExternalVariable(IStr),65	#[error("native is not defined: {0}")]66	UndefinedExternalFunction(IStr),6768	#[error("field name should be string, got {0}")]69	FieldMustBeStringGot(ValType),70	#[error("duplicate field name: {0}")]71	DuplicateFieldName(IStr),7273	#[error("attempted to index array with string {0}")]74	AttemptedIndexAnArrayWithString(IStr),75	#[error("{0} index type should be {1}, got {2}")]76	ValueIndexMustBeTypeGot(ValType, ValType, ValType),77	#[error("cant index into {0}")]78	CantIndexInto(ValType),79	#[error("{0} is not indexable")]80	ValueIsNotIndexable(ValType),8182	#[error("super can't be used standalone")]83	StandaloneSuper,8485	#[error("can't resolve {1} from {0}")]86	ImportFileNotFound(PathBuf, PathBuf),87	#[error("resolved file not found: {0}")]88	ResolvedFileNotFound(PathBuf),89	#[error("imported file is not valid utf-8: {0:?}")]90	ImportBadFileUtf8(PathBuf),91	#[error("import io error: {0}")]92	ImportIo(String),93	#[error("tried to import {1} from {0}, but imports is not supported")]94	ImportNotSupported(PathBuf, PathBuf),95	#[error(96		"syntax error: expected {}, got {:?}",97		.error.expected,98		.source_code.chars().nth(error.location.offset).map(|c| c.to_string()).unwrap_or_else(|| "EOF".into())99	)]100	ImportSyntaxError {101		#[skip_trace]102		path: Rc<Path>,103		source_code: IStr,104		#[skip_trace]105		error: Box<jrsonnet_parser::ParseError>,106	},107108	#[error("runtime error: {0}")]109	RuntimeError(IStr),110	#[error("stack overflow, try to reduce recursion, or set --max-stack to bigger value")]111	StackOverflow,112	#[error("infinite recursion detected")]113	InfiniteRecursionDetected,114	#[error("tried to index by fractional value")]115	FractionalIndex,116	#[error("attempted to divide by zero")]117	DivisionByZero,118119	#[error("string manifest output is not an string")]120	StringManifestOutputIsNotAString,121	#[error("stream manifest output is not an array")]122	StreamManifestOutputIsNotAArray,123	#[error("multi manifest output is not an object")]124	MultiManifestOutputIsNotAObject,125126	#[error("cant recurse stream manifest")]127	StreamManifestOutputCannotBeRecursed,128	#[error("stream manifest output cannot consist of raw strings")]129	StreamManifestCannotNestString,130131	#[error("{0}")]132	ImportCallbackError(String),133	#[error("invalid unicode codepoint: {0}")]134	InvalidUnicodeCodepointGot(u32),135136	#[error("format error: {0}")]137	Format(#[from] FormatError),138	#[error("type error: {0}")]139	TypeError(TypeLocError),140	#[error("sort error: {0}")]141	Sort(#[from] SortError),142143	#[cfg(feature = "anyhow-error")]144	#[error(transparent)]145	Other(Rc<anyhow::Error>),146}147148#[cfg(feature = "anyhow-error")]149impl From<anyhow::Error> for LocError {150	fn from(e: anyhow::Error) -> Self {151		Self::new(Error::Other(Rc::new(e)))152	}153}154155impl From<Error> for LocError {156	fn from(e: Error) -> Self {157		Self::new(e)158	}159}160161#[derive(Clone, Debug, Trace)]162pub struct StackTraceElement {163	pub location: Option<ExprLocation>,164	pub desc: String,165}166#[derive(Debug, Clone, Trace)]167pub struct StackTrace(pub Vec<StackTraceElement>);168169#[derive(Debug, Clone, Trace)]170pub struct LocError(Box<(Error, StackTrace)>);171impl LocError {172	pub fn new(e: Error) -> Self {173		Self(Box::new((e, StackTrace(vec![]))))174	}175176	pub const fn error(&self) -> &Error {177		&(self.0).0178	}179	pub fn error_mut(&mut self) -> &mut Error {180		&mut (self.0).0181	}182	pub const fn trace(&self) -> &StackTrace {183		&(self.0).1184	}185	pub fn trace_mut(&mut self) -> &mut StackTrace {186		&mut (self.0).1187	}188}189190pub type Result<V, E = LocError> = std::result::Result<V, E>;191192#[macro_export]193macro_rules! throw {194	($e: expr) => {195		return Err($e.into())196	};197}198199#[macro_export]200macro_rules! throw_runtime {201	($($tt:tt)*) => {202		return Err($crate::error::Error::RuntimeError(format!($($tt)*).into()).into())203	};204}