git.delta.rocks / jrsonnet / refs/commits / bde2637fa85f

difftreelog

source

crates/jrsonnet-evaluator/src/error.rs6.5 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}3738#[derive(Error, Debug, Clone, Trace)]39pub enum Error {40	#[error("intrinsic not found: {0}")]41	IntrinsicNotFound(IStr),4243	#[error("operator {0} does not operate on type {1}")]44	UnaryOperatorDoesNotOperateOnType(UnaryOpType, ValType),45	#[error("binary operation {1} {0} {2} is not implemented")]46	BinaryOperatorDoesNotOperateOnValues(BinaryOpType, ValType, ValType),4748	#[error("no top level object in this context")]49	NoTopLevelObjectFound,50	#[error("self is only usable inside objects")]51	CantUseSelfOutsideOfObject,52	#[error("no super found")]53	NoSuperFound,5455	#[error("for loop can only iterate over arrays")]56	InComprehensionCanOnlyIterateOverArray,5758	#[error("array out of bounds: {0} is not within [0,{1})")]59	ArrayBoundsError(usize, usize),60	#[error("string out of bounds: {0} is not within [0,{1})")]61	StringBoundsError(usize, usize),6263	#[error("assert failed: {0}")]64	AssertionFailed(IStr),6566	#[error("variable is not defined: {0}{}", format_found(.1, "variable"))]67	VariableIsNotDefined(IStr, Vec<IStr>),68	#[error("duplicate local var: {0}")]69	DuplicateLocalVar(IStr),7071	#[error("type mismatch: expected {}, got {2} {0}", .1.iter().map(|e| format!("{}", e)).collect::<Vec<_>>().join(", "))]72	TypeMismatch(&'static str, Vec<ValType>, ValType),73	#[error("no such field: {0}{}", format_found(.1, "field"))]74	NoSuchField(IStr, Vec<IStr>),7576	#[error("only functions can be called, got {0}")]77	OnlyFunctionsCanBeCalledGot(ValType),78	#[error("parameter {0} is not defined")]79	UnknownFunctionParameter(String),80	#[error("argument {0} is already bound")]81	BindingParameterASecondTime(IStr),82	#[error("too many args, function has {0}")]83	TooManyArgsFunctionHas(usize),84	#[error("function argument is not passed: {0}")]85	FunctionParameterNotBoundInCall(IStr),8687	#[error("external variable is not defined: {0}")]88	UndefinedExternalVariable(IStr),8990	#[error("field name should be string, got {0}")]91	FieldMustBeStringGot(ValType),92	#[error("duplicate field name: {0}")]93	DuplicateFieldName(IStr),9495	#[error("attempted to index array with string {0}")]96	AttemptedIndexAnArrayWithString(IStr),97	#[error("{0} index type should be {1}, got {2}")]98	ValueIndexMustBeTypeGot(ValType, ValType, ValType),99	#[error("cant index into {0}")]100	CantIndexInto(ValType),101	#[error("{0} is not indexable")]102	ValueIsNotIndexable(ValType),103104	#[error("super can't be used standalone")]105	StandaloneSuper,106107	#[error("can't resolve {1} from {0}")]108	ImportFileNotFound(PathBuf, String),109	#[error("resolved file not found: {0}")]110	ResolvedFileNotFound(PathBuf),111	#[error("imported file is not valid utf-8: {0:?}")]112	ImportBadFileUtf8(PathBuf),113	#[error("import io error: {0}")]114	ImportIo(String),115	#[error("tried to import {1} from {0}, but imports is not supported")]116	ImportNotSupported(PathBuf, PathBuf),117	#[error("can't import from virtual file")]118	CantImportFromVirtualFile,119	#[error(120		"syntax error: expected {}, got {:?}",121		.error.expected,122		.source_code.chars().nth(error.location.offset)123		.map_or_else(|| "EOF".into(), |c| c.to_string())124	)]125	ImportSyntaxError {126		path: Source,127		source_code: IStr,128		#[trace(skip)]129		error: Box<jrsonnet_parser::ParseError>,130	},131132	#[error("runtime error: {0}")]133	RuntimeError(IStr),134	#[error("stack overflow, try to reduce recursion, or set --max-stack to bigger value")]135	StackOverflow,136	#[error("infinite recursion detected")]137	InfiniteRecursionDetected,138	#[error("tried to index by fractional value")]139	FractionalIndex,140	#[error("attempted to divide by zero")]141	DivisionByZero,142143	#[error("string manifest output is not an string")]144	StringManifestOutputIsNotAString,145	#[error("stream manifest output is not an array")]146	StreamManifestOutputIsNotAArray,147	#[error("multi manifest output is not an object")]148	MultiManifestOutputIsNotAObject,149150	#[error("cant recurse stream manifest")]151	StreamManifestOutputCannotBeRecursed,152	#[error("stream manifest output cannot consist of raw strings")]153	StreamManifestCannotNestString,154155	#[error("{0}")]156	ImportCallbackError(String),157	#[error("invalid unicode codepoint: {0}")]158	InvalidUnicodeCodepointGot(u32),159160	#[error("format error: {0}")]161	Format(#[from] FormatError),162	#[error("type error: {0}")]163	TypeError(TypeLocError),164	#[error("sort error: {0}")]165	Sort(#[from] SortError),166167	/// Thrown as error, as this is legacy feature, and error here168	/// is acceptable for defeating object field cache169	#[error("should not reach outside: std.thisFile")]170	MagicThisFileUsed,171172	#[cfg(feature = "anyhow-error")]173	#[error(transparent)]174	Other(Rc<anyhow::Error>),175}176177#[cfg(feature = "anyhow-error")]178impl From<anyhow::Error> for LocError {179	fn from(e: anyhow::Error) -> Self {180		Self::new(Error::Other(Rc::new(e)))181	}182}183184impl From<Error> for LocError {185	fn from(e: Error) -> Self {186		Self::new(e)187	}188}189190#[derive(Clone, Debug, Trace)]191pub struct StackTraceElement {192	pub location: Option<ExprLocation>,193	pub desc: String,194}195#[derive(Debug, Clone, Trace)]196pub struct StackTrace(pub Vec<StackTraceElement>);197198#[derive(Clone, Trace)]199pub struct LocError(Box<(Error, StackTrace)>);200impl LocError {201	pub fn new(e: Error) -> Self {202		Self(Box::new((e, StackTrace(vec![]))))203	}204205	pub const fn error(&self) -> &Error {206		&(self.0).0207	}208	pub fn error_mut(&mut self) -> &mut Error {209		&mut (self.0).0210	}211	pub const fn trace(&self) -> &StackTrace {212		&(self.0).1213	}214	pub fn trace_mut(&mut self) -> &mut StackTrace {215		&mut (self.0).1216	}217}218impl Debug for LocError {219	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {220		writeln!(f, "{}", self.0 .0)?;221		for el in &self.0 .1 .0 {222			writeln!(f, "\t{:?}", el)?;223		}224		Ok(())225	}226}227228pub type Result<V, E = LocError> = std::result::Result<V, E>;229230#[macro_export]231macro_rules! throw {232	($e: expr) => {233		return Err($e.into())234	};235}236237#[macro_export]238macro_rules! throw_runtime {239	($($tt:tt)*) => {240		return Err($crate::error::Error::RuntimeError(format!($($tt)*).into()).into())241	};242}