git.delta.rocks / jrsonnet / refs/commits / 1ddb92c00d0f

difftreelog

source

crates/jrsonnet-evaluator/src/error.rs10.2 KiBsourcehistory
1use std::{cmp::Ordering, convert::Infallible, fmt};23use jrsonnet_gcmodule::{Acyclic, Trace};4use jrsonnet_interner::IStr;5use jrsonnet_parser::{BinaryOpType, Source, SourcePath, Span, Spanned, UnaryOpType};6use jrsonnet_types::ValType;7use thiserror::Error;89use crate::{10	function::{CallLocation, FunctionSignature, ParamName},11	stdlib::format::FormatError,12	typed::TypeLocError,13	val::ConvertNumValueError,14	ObjValue, ResolvePathOwned,15};1617pub(crate) fn format_found(list: &[IStr], what: &str) -> String {18	if list.is_empty() {19		return String::new();20	}21	let mut out = String::new();22	out.push_str("\nThere ");23	if list.len() > 1 {24		out.push_str("are ");25	} else {26		out.push_str("is a ");27	}28	out.push_str(what);29	if list.len() > 1 {30		out.push('s');31	}32	out.push_str(" with similar name");33	if list.len() > 1 {34		out.push('s');35	}36	out.push_str(" present: ");37	for (i, v) in list.iter().enumerate() {38		if i != 0 {39			out.push_str(", ");40		}41		out.push_str(v as &str);42	}43	out44}4546const fn format_empty_str(str: &str) -> &str {47	if str.is_empty() {48		"\"\" (empty string)"49	} else {50		str51	}52}5354pub(crate) fn suggest_object_fields(v: &ObjValue, key: IStr) -> Vec<IStr> {55	let mut heap = Vec::new();56	for field in v.fields_ex(57		true,58		#[cfg(feature = "exp-preserve-order")]59		false,60	) {61		let conf = strsim::jaro_winkler(field.as_str(), key.as_str());62		if conf < 0.8 {63			continue;64		}65		assert!(field.as_str() != key.as_str(), "looks like string pooling failure, please write any info regarding this crash to https://github.com/CertainLach/jrsonnet/issues/113, thanks!");6667		heap.push((conf, field));68	}69	heap.sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap_or(Ordering::Equal));70	heap.into_iter().map(|v| v.1).collect()71}7273/// Possible errors74#[allow(missing_docs)]75#[derive(Error, Debug, Clone, Trace)]76#[non_exhaustive]77pub enum ErrorKind {78	#[error("intrinsic not found: {0}")]79	IntrinsicNotFound(IStr),8081	#[error("operator {0} does not operate on type {1}")]82	UnaryOperatorDoesNotOperateOnType(UnaryOpType, ValType),83	#[error("binary operation {1} {0} {2} is not implemented")]84	BinaryOperatorDoesNotOperateOnValues(BinaryOpType, ValType, ValType),8586	#[error("self/super/$ are only usable inside objects")]87	CantUseSelfSupOutsideOfObject,88	#[error("no super found")]89	NoSuperFound,9091	#[error("for loop can only iterate over arrays")]92	InComprehensionCanOnlyIterateOverArray,9394	#[error("array out of bounds: {0} is not within [0,{1})")]95	ArrayBoundsError(isize, usize),96	#[error("string out of bounds: {0} is not within [0,{1})")]97	StringBoundsError(usize, usize),9899	#[error("assert failed: {}", format_empty_str(.0))]100	AssertionFailed(IStr),101102	#[error("local is not defined: {0}{found}", found = format_found(.1, "local"))]103	VariableIsNotDefined(IStr, Vec<IStr>),104	#[error("duplicate local var: {0}")]105	DuplicateLocalVar(IStr),106107	#[error("type mismatch: expected {expected}, got {2} {0}", expected = .1.iter().map(|e| format!("{e}")).collect::<Vec<_>>().join(", "))]108	TypeMismatch(&'static str, Vec<ValType>, ValType),109	#[error("no such field: {}{}", format_empty_str(.0), format_found(.1, "field"))]110	NoSuchField(IStr, Vec<IStr>),111112	#[error("only functions can be called, got {0}")]113	OnlyFunctionsCanBeCalledGot(ValType),114	#[error("parameter {0} is not defined")]115	UnknownFunctionParameter(IStr),116	#[error("argument {0} is already bound")]117	BindingParameterASecondTime(IStr),118	#[error("too many args, function has {0}\nFunction has the following signature: {1}")]119	TooManyArgsFunctionHas(usize, FunctionSignature),120	#[error("function argument is not passed: {0}\nFunction has the following signature: {1}")]121	FunctionParameterNotBoundInCall(ParamName, FunctionSignature),122123	#[error("external variable is not defined: {0}")]124	UndefinedExternalVariable(IStr),125126	#[error("field name should be string, got {0}")]127	FieldMustBeStringGot(ValType),128	#[error("duplicate field name: {}", format_empty_str(.0))]129	DuplicateFieldName(IStr),130131	#[error("attempted to index array with string {}", format_empty_str(.0))]132	AttemptedIndexAnArrayWithString(IStr),133	#[error("{0} index type should be {1}, got {2}")]134	ValueIndexMustBeTypeGot(ValType, ValType, ValType),135	#[error("cant index into {0}")]136	CantIndexInto(ValType),137	#[error("{0} is not indexable")]138	ValueIsNotIndexable(ValType),139140	#[error("super can't be used standalone")]141	StandaloneSuper,142143	#[error("can't resolve {1} from {0}")]144	ImportFileNotFound(SourcePath, ResolvePathOwned),145	#[error("resolved file not found: {:?}", .0)]146	ResolvedFileNotFound(SourcePath),147	#[error("can't import {0}: is a directory")]148	ImportIsADirectory(SourcePath),149	#[error("imported file is not valid utf-8: {0:?}")]150	ImportBadFileUtf8(SourcePath),151	#[error("import io error: {0}")]152	ImportIo(String),153	#[error("tried to import {1} from {0}, but imports are not supported")]154	ImportNotSupported(SourcePath, ResolvePathOwned),155	#[error("can't import from virtual file")]156	CantImportFromVirtualFile,157	#[error(158		"syntax error: {}",159		// Peg has no fancier way to handle critical parsing errors https://github.com/kevinmehall/rust-peg/issues/225160		{.error.expected.tokens().find(|t| t.starts_with("!!!")).map_or_else(|| {161			format!(162				"expected {}, got {:?}",163				.error.expected,164				.path.code().chars().nth(error.location.offset)165				.map_or_else(|| "EOF".into(), |c| c.to_string())166			)167		}, |v| v[3..].into())}168	)]169	ImportSyntaxError {170		path: Source,171		#[trace(skip)]172		error: Box<jrsonnet_parser::ParseError>,173	},174175	#[error("runtime error: {}", format_empty_str(.0))]176	RuntimeError(IStr),177	#[error("stack overflow, try to reduce recursion, or set --max-stack to bigger value")]178	StackOverflow,179	#[error("infinite recursion detected")]180	InfiniteRecursionDetected,181	#[error("tried to index by fractional value")]182	FractionalIndex,183	#[error("attempted to divide by zero")]184	DivisionByZero,185186	#[error("string manifest output is not an string")]187	StringManifestOutputIsNotAString,188	#[error("stream manifest output is not an array")]189	StreamManifestOutputIsNotAArray,190	#[error("multi manifest output is not an object")]191	MultiManifestOutputIsNotAObject,192193	#[error("cant recurse stream manifest")]194	StreamManifestOutputCannotBeRecursed,195	#[error("stream manifest output cannot consist of raw strings")]196	StreamManifestCannotNestString,197198	#[error("{}", format_empty_str(.0))]199	ImportCallbackError(String),200	#[error("invalid unicode codepoint: {0}")]201	InvalidUnicodeCodepointGot(u32),202203	#[error("convert num value: {0}")]204	ConvertNumValue(#[from] ConvertNumValueError),205206	#[error("format error: {0}")]207	Format(#[from] FormatError),208	#[error("type error: {0}")]209	TypeError(TypeLocError),210211	#[cfg(feature = "anyhow-error")]212	#[error(transparent)]213	Other(#[trace(skip)] std::rc::Rc<anyhow::Error>),214}215216#[cfg(feature = "anyhow-error")]217impl From<anyhow::Error> for Error {218	fn from(e: anyhow::Error) -> Self {219		Self::new(ErrorKind::Other(std::rc::Rc::new(e)))220	}221}222223impl From<ErrorKind> for Error {224	fn from(e: ErrorKind) -> Self {225		Self::new(e)226	}227}228229impl From<Infallible> for Error {230	fn from(_value: Infallible) -> Self {231		unreachable!()232	}233}234235/// Single stack trace frame236#[derive(Clone, Debug, Trace)]237pub struct StackTraceElement {238	/// Source of this frame239	/// Some frames only act as description, without attached source240	pub location: Option<Span>,241	/// Frame description242	pub desc: String,243}244#[derive(Debug, Clone, Trace)]245pub struct StackTrace(pub Vec<StackTraceElement>);246247#[derive(Clone, Trace)]248pub struct Error(Box<(ErrorKind, StackTrace)>);249impl Error {250	pub fn new(e: ErrorKind) -> Self {251		Self(Box::new((e, StackTrace(vec![]))))252	}253254	pub const fn error(&self) -> &ErrorKind {255		&(self.0).0256	}257	pub fn error_mut(&mut self) -> &mut ErrorKind {258		&mut (self.0).0259	}260	pub const fn trace(&self) -> &StackTrace {261		&(self.0).1262	}263	pub fn trace_mut(&mut self) -> &mut StackTrace {264		&mut (self.0).1265	}266}267impl fmt::Display for Error {268	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {269		writeln!(f, "{}", self.0 .0)?;270		for el in &self.0 .1 .0 {271			write!(f, "\t{}", el.desc)?;272			if let Some(loc) = &el.location {273				write!(f, "at {}", loc.0 .0 .0)?;274				loc.0.map_source_locations(&[loc.1, loc.2]);275			}276			writeln!(f)?;277		}278		Ok(())279	}280}281impl fmt::Debug for Error {282	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {283		f.debug_tuple("LocError").field(&self.0).finish()284	}285}286impl std::error::Error for Error {}287288pub trait ErrorSource {289	fn to_location(self) -> Option<Span>;290}291impl<T: Acyclic> ErrorSource for &Spanned<T> {292	fn to_location(self) -> Option<Span> {293		Some(self.span())294	}295}296impl ErrorSource for &Span {297	fn to_location(self) -> Option<Span> {298		Some(self.clone())299	}300}301impl ErrorSource for CallLocation<'_> {302	fn to_location(self) -> Option<Span> {303		self.0.cloned()304	}305}306307pub type Result<V, E = Error> = std::result::Result<V, E>;308pub trait ResultExt: Sized {309	#[must_use]310	fn with_description<O: Into<String>>(self, msg: impl FnOnce() -> O) -> Self;311	#[must_use]312	fn description(self, msg: &str) -> Self {313		self.with_description(|| msg)314	}315316	#[must_use]317	fn with_description_src<O: Into<String>>(318		self,319		src: impl ErrorSource,320		msg: impl FnOnce() -> O,321	) -> Self;322	#[must_use]323	fn description_src(self, src: impl ErrorSource, msg: &str) -> Self {324		self.with_description_src(src, || msg)325	}326}327impl<T> ResultExt for Result<T, Error> {328	fn with_description<O: Into<String>>(mut self, msg: impl FnOnce() -> O) -> Self {329		if let Err(e) = &mut self {330			let trace = e.trace_mut();331			trace.0.push(StackTraceElement {332				location: None,333				desc: msg().into(),334			});335		}336		self337	}338339	fn with_description_src<O: Into<String>>(340		mut self,341		src: impl ErrorSource,342		msg: impl FnOnce() -> O,343	) -> Self {344		if let Err(e) = &mut self {345			let trace = e.trace_mut();346			trace.0.push(StackTraceElement {347				location: src.to_location(),348				desc: msg().into(),349			});350		}351		self352	}353}354355#[macro_export]356macro_rules! bail {357	($w:ident$(::$i:ident)*$(($($tt:tt)*))?) => {358		return Err($w$(::$i)*$(($($tt)*))?.into())359	};360	($w:ident$(::$i:ident)*$({$($tt:tt)*})?) => {361		return Err($w$(::$i)*$({$($tt)*})?.into())362	};363	($l:literal$(, $($tt:tt)*)?) => {364		return Err($crate::error::ErrorKind::RuntimeError($crate::jrsonnet_macros::format_istr!($l$(, $($tt)*)?)).into())365	};366}367368#[macro_export]369macro_rules! runtime_error {370	($l:literal$(, $($tt:tt)*)?) => {371		$crate::error::Error::from($crate::error::ErrorKind::RuntimeError($crate::jrsonnet_macros::format_istr!($l$(, $($tt)*)?)))372	};373}