git.delta.rocks / jrsonnet / refs/commits / 94fa86f59bc6

difftreelog

source

crates/jrsonnet-evaluator/src/error.rs5.7 KiBsourcehistory
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	builtin::{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("type mismatch: expected {}, got {2} {0}", .1.iter().map(|e| format!("{}", e)).collect::<Vec<_>>().join(", "))]49	TypeMismatch(&'static str, Vec<ValType>, ValType),50	#[error("no such field: {0}")]51	NoSuchField(IStr),5253	#[error("only functions can be called, got {0}")]54	OnlyFunctionsCanBeCalledGot(ValType),55	#[error("parameter {0} is not defined")]56	UnknownFunctionParameter(String),57	#[error("argument {0} is already bound")]58	BindingParameterASecondTime(IStr),59	#[error("too many args, function has {0}")]60	TooManyArgsFunctionHas(usize),61	#[error("function argument is not passed: {0}")]62	FunctionParameterNotBoundInCall(IStr),6364	#[error("external variable is not defined: {0}")]65	UndefinedExternalVariable(IStr),66	#[error("native is not defined: {0}")]67	UndefinedExternalFunction(IStr),6869	#[error("field name should be string, got {0}")]70	FieldMustBeStringGot(ValType),71	#[error("duplicate field name: {0}")]72	DuplicateFieldName(IStr),7374	#[error("attempted to index array with string {0}")]75	AttemptedIndexAnArrayWithString(IStr),76	#[error("{0} index type should be {1}, got {2}")]77	ValueIndexMustBeTypeGot(ValType, ValType, ValType),78	#[error("cant index into {0}")]79	CantIndexInto(ValType),80	#[error("{0} is not indexable")]81	ValueIsNotIndexable(ValType),8283	#[error("super can't be used standalone")]84	StandaloneSuper,8586	#[error("can't resolve {1} from {0}")]87	ImportFileNotFound(PathBuf, PathBuf),88	#[error("resolved file not found: {0}")]89	ResolvedFileNotFound(PathBuf),90	#[error("imported file is not valid utf-8: {0:?}")]91	ImportBadFileUtf8(PathBuf),92	#[error("import io error: {0}")]93	ImportIo(String),94	#[error("tried to import {1} from {0}, but imports is not supported")]95	ImportNotSupported(PathBuf, PathBuf),96	#[error(97		"syntax error: expected {}, got {:?}",98		.error.expected,99		.source_code.chars().nth(error.location.offset)100		.map_or_else(|| "EOF".into(), |c| c.to_string())101	)]102	ImportSyntaxError {103		#[skip_trace]104		path: Rc<Path>,105		source_code: IStr,106		#[skip_trace]107		error: Box<jrsonnet_parser::ParseError>,108	},109110	#[error("runtime error: {0}")]111	RuntimeError(IStr),112	#[error("stack overflow, try to reduce recursion, or set --max-stack to bigger value")]113	StackOverflow,114	#[error("infinite recursion detected")]115	InfiniteRecursionDetected,116	#[error("tried to index by fractional value")]117	FractionalIndex,118	#[error("attempted to divide by zero")]119	DivisionByZero,120121	#[error("string manifest output is not an string")]122	StringManifestOutputIsNotAString,123	#[error("stream manifest output is not an array")]124	StreamManifestOutputIsNotAArray,125	#[error("multi manifest output is not an object")]126	MultiManifestOutputIsNotAObject,127128	#[error("cant recurse stream manifest")]129	StreamManifestOutputCannotBeRecursed,130	#[error("stream manifest output cannot consist of raw strings")]131	StreamManifestCannotNestString,132133	#[error("{0}")]134	ImportCallbackError(String),135	#[error("invalid unicode codepoint: {0}")]136	InvalidUnicodeCodepointGot(u32),137138	#[error("format error: {0}")]139	Format(#[from] FormatError),140	#[error("type error: {0}")]141	TypeError(TypeLocError),142	#[error("sort error: {0}")]143	Sort(#[from] SortError),144145	#[cfg(feature = "anyhow-error")]146	#[error(transparent)]147	Other(Rc<anyhow::Error>),148}149150#[cfg(feature = "anyhow-error")]151impl From<anyhow::Error> for LocError {152	fn from(e: anyhow::Error) -> Self {153		Self::new(Error::Other(Rc::new(e)))154	}155}156157impl From<Error> for LocError {158	fn from(e: Error) -> Self {159		Self::new(e)160	}161}162163#[derive(Clone, Debug, Trace)]164pub struct StackTraceElement {165	pub location: Option<ExprLocation>,166	pub desc: String,167}168#[derive(Debug, Clone, Trace)]169pub struct StackTrace(pub Vec<StackTraceElement>);170171#[derive(Clone, Trace)]172pub struct LocError(Box<(Error, StackTrace)>);173impl LocError {174	pub fn new(e: Error) -> Self {175		Self(Box::new((e, StackTrace(vec![]))))176	}177178	pub const fn error(&self) -> &Error {179		&(self.0).0180	}181	pub fn error_mut(&mut self) -> &mut Error {182		&mut (self.0).0183	}184	pub const fn trace(&self) -> &StackTrace {185		&(self.0).1186	}187	pub fn trace_mut(&mut self) -> &mut StackTrace {188		&mut (self.0).1189	}190}191impl Debug for LocError {192	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {193		writeln!(f, "{}", self.0 .0)?;194		for el in &self.0 .1 .0 {195			writeln!(f, "\t{:?}", el)?;196		}197		Ok(())198	}199}200201pub type Result<V, E = LocError> = std::result::Result<V, E>;202203#[macro_export]204macro_rules! throw {205	($e: expr) => {206		return Err($e.into())207	};208}209210#[macro_export]211macro_rules! throw_runtime {212	($($tt:tt)*) => {213		return Err($crate::error::Error::RuntimeError(format!($($tt)*).into()).into())214	};215}