git.delta.rocks / jrsonnet / refs/commits / 34a152fcae11

difftreelog

source

crates/jrsonnet-evaluator/src/error.rs6.7 KiBsourcehistory
1use std::{fmt::Debug, path::PathBuf};23use jrsonnet_gcmodule::Trace;4use jrsonnet_interner::IStr;5use jrsonnet_parser::{BinaryOpType, ExprLocation, Source, UnaryOpType};6use jrsonnet_types::ValType;7use thiserror::Error;89use crate::{10	stdlib::{format::FormatError, sort::SortError},11	typed::TypeLocError,12};1314fn format_found(list: &[IStr], what: &str) -> String {15	if list.is_empty() {16		return String::new();17	}18	let mut out = String::new();19	out.push_str("\nThere is ");20	out.push_str(what);21	if list.len() > 1 {22		out.push('s');23	}24	out.push_str(" with similar name");25	if list.len() > 1 {26		out.push('s');27	}28	out.push_str(" present: ");29	for (i, v) in list.iter().enumerate() {30		if i != 0 {31			out.push_str(", ");32		}33		out.push_str(v as &str);34	}35	out36}3738const fn format_empty_str(str: &str) -> &str {39	if str.is_empty() {40		"\"\" (empty string)"41	} else {42		str43	}44}4546#[derive(Error, Debug, Clone, Trace)]47pub enum Error {48	#[error("intrinsic not found: {0}")]49	IntrinsicNotFound(IStr),5051	#[error("operator {0} does not operate on type {1}")]52	UnaryOperatorDoesNotOperateOnType(UnaryOpType, ValType),53	#[error("binary operation {1} {0} {2} is not implemented")]54	BinaryOperatorDoesNotOperateOnValues(BinaryOpType, ValType, ValType),5556	#[error("no top level object in this context")]57	NoTopLevelObjectFound,58	#[error("self is only usable inside objects")]59	CantUseSelfOutsideOfObject,60	#[error("no super found")]61	NoSuperFound,6263	#[error("for loop can only iterate over arrays")]64	InComprehensionCanOnlyIterateOverArray,6566	#[error("array out of bounds: {0} is not within [0,{1})")]67	ArrayBoundsError(usize, usize),68	#[error("string out of bounds: {0} is not within [0,{1})")]69	StringBoundsError(usize, usize),7071	#[error("assert failed: {}", format_empty_str(.0))]72	AssertionFailed(IStr),7374	#[error("variable is not defined: {0}{}", format_found(.1, "variable"))]75	VariableIsNotDefined(IStr, Vec<IStr>),76	#[error("duplicate local var: {0}")]77	DuplicateLocalVar(IStr),7879	#[error("type mismatch: expected {}, got {2} {0}", .1.iter().map(|e| format!("{}", e)).collect::<Vec<_>>().join(", "))]80	TypeMismatch(&'static str, Vec<ValType>, ValType),81	#[error("no such field: {}{}", format_empty_str(.0), format_found(.1, "field"))]82	NoSuchField(IStr, Vec<IStr>),8384	#[error("only functions can be called, got {0}")]85	OnlyFunctionsCanBeCalledGot(ValType),86	#[error("parameter {0} is not defined")]87	UnknownFunctionParameter(String),88	#[error("argument {0} is already bound")]89	BindingParameterASecondTime(IStr),90	#[error("too many args, function has {0}")]91	TooManyArgsFunctionHas(usize),92	#[error("function argument is not passed: {0}")]93	FunctionParameterNotBoundInCall(IStr),9495	#[error("external variable is not defined: {0}")]96	UndefinedExternalVariable(IStr),9798	#[error("field name should be string, got {0}")]99	FieldMustBeStringGot(ValType),100	#[error("duplicate field name: {}", format_empty_str(.0))]101	DuplicateFieldName(IStr),102103	#[error("attempted to index array with string {}", format_empty_str(.0))]104	AttemptedIndexAnArrayWithString(IStr),105	#[error("{0} index type should be {1}, got {2}")]106	ValueIndexMustBeTypeGot(ValType, ValType, ValType),107	#[error("cant index into {0}")]108	CantIndexInto(ValType),109	#[error("{0} is not indexable")]110	ValueIsNotIndexable(ValType),111112	#[error("super can't be used standalone")]113	StandaloneSuper,114115	#[error("can't resolve {1} from {0}")]116	ImportFileNotFound(PathBuf, String),117	#[error("resolved file not found: {0}")]118	ResolvedFileNotFound(PathBuf),119	#[error("imported file is not valid utf-8: {0:?}")]120	ImportBadFileUtf8(PathBuf),121	#[error("import io error: {0}")]122	ImportIo(String),123	#[error("tried to import {1} from {0}, but imports is not supported")]124	ImportNotSupported(PathBuf, PathBuf),125	#[error("can't import from virtual file")]126	CantImportFromVirtualFile,127	#[error(128		"syntax error: expected {}, got {:?}",129		.error.expected,130		.source_code.chars().nth(error.location.offset)131		.map_or_else(|| "EOF".into(), |c| c.to_string())132	)]133	ImportSyntaxError {134		path: Source,135		source_code: IStr,136		#[trace(skip)]137		error: Box<jrsonnet_parser::ParseError>,138	},139140	#[error("runtime error: {}", format_empty_str(.0))]141	RuntimeError(IStr),142	#[error("stack overflow, try to reduce recursion, or set --max-stack to bigger value")]143	StackOverflow,144	#[error("infinite recursion detected")]145	InfiniteRecursionDetected,146	#[error("tried to index by fractional value")]147	FractionalIndex,148	#[error("attempted to divide by zero")]149	DivisionByZero,150151	#[error("string manifest output is not an string")]152	StringManifestOutputIsNotAString,153	#[error("stream manifest output is not an array")]154	StreamManifestOutputIsNotAArray,155	#[error("multi manifest output is not an object")]156	MultiManifestOutputIsNotAObject,157158	#[error("cant recurse stream manifest")]159	StreamManifestOutputCannotBeRecursed,160	#[error("stream manifest output cannot consist of raw strings")]161	StreamManifestCannotNestString,162163	#[error("{}", format_empty_str(.0))]164	ImportCallbackError(String),165	#[error("invalid unicode codepoint: {0}")]166	InvalidUnicodeCodepointGot(u32),167168	#[error("format error: {0}")]169	Format(#[from] FormatError),170	#[error("type error: {0}")]171	TypeError(TypeLocError),172	#[error("sort error: {0}")]173	Sort(#[from] SortError),174175	/// Thrown as error, as this is legacy feature, and error here176	/// is acceptable for defeating object field cache177	#[error("should not reach outside: std.thisFile")]178	MagicThisFileUsed,179180	#[cfg(feature = "anyhow-error")]181	#[error(transparent)]182	Other(Rc<anyhow::Error>),183}184185#[cfg(feature = "anyhow-error")]186impl From<anyhow::Error> for LocError {187	fn from(e: anyhow::Error) -> Self {188		Self::new(Error::Other(Rc::new(e)))189	}190}191192impl From<Error> for LocError {193	fn from(e: Error) -> Self {194		Self::new(e)195	}196}197198#[derive(Clone, Debug, Trace)]199pub struct StackTraceElement {200	pub location: Option<ExprLocation>,201	pub desc: String,202}203#[derive(Debug, Clone, Trace)]204pub struct StackTrace(pub Vec<StackTraceElement>);205206#[derive(Clone, Trace)]207pub struct LocError(Box<(Error, StackTrace)>);208impl LocError {209	pub fn new(e: Error) -> Self {210		Self(Box::new((e, StackTrace(vec![]))))211	}212213	pub const fn error(&self) -> &Error {214		&(self.0).0215	}216	pub fn error_mut(&mut self) -> &mut Error {217		&mut (self.0).0218	}219	pub const fn trace(&self) -> &StackTrace {220		&(self.0).1221	}222	pub fn trace_mut(&mut self) -> &mut StackTrace {223		&mut (self.0).1224	}225}226impl Debug for LocError {227	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {228		writeln!(f, "{}", self.0 .0)?;229		for el in &self.0 .1 .0 {230			writeln!(f, "\t{:?}", el)?;231		}232		Ok(())233	}234}235236pub type Result<V, E = LocError> = std::result::Result<V, E>;237238#[macro_export]239macro_rules! throw {240	($e: expr) => {241		return Err($e.into())242	};243}244245#[macro_export]246macro_rules! throw_runtime {247	($($tt:tt)*) => {248		return Err($crate::error::Error::RuntimeError(format!($($tt)*).into()).into())249	};250}