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

difftreelog

source

crates/jrsonnet-evaluator/src/error.rs11.0 KiBsourcehistory
1use std::{2	cmp::Ordering,3	convert::Infallible,4	fmt::{Debug, Display},5};67use jrsonnet_gcmodule::{Acyclic, Trace};8use jrsonnet_interner::IStr;9use jrsonnet_parser::{BinaryOpType, Source, SourcePath, Span, Spanned, UnaryOpType};10use jrsonnet_types::ValType;11use thiserror::Error;1213use crate::{14	function::{builtin::ParamDefault, CallLocation},15	stdlib::format::FormatError,16	typed::TypeLocError,17	val::ConvertNumValueError,18	ObjValue, ResolvePathOwned,19};2021pub(crate) fn format_found(list: &[IStr], what: &str) -> String {22	if list.is_empty() {23		return String::new();24	}25	let mut out = String::new();26	out.push_str("\nThere ");27	if list.len() > 1 {28		out.push_str("are ");29	} else {30		out.push_str("is a ");31	}32	out.push_str(what);33	if list.len() > 1 {34		out.push('s');35	}36	out.push_str(" with similar name");37	if list.len() > 1 {38		out.push('s');39	}40	out.push_str(" present: ");41	for (i, v) in list.iter().enumerate() {42		if i != 0 {43			out.push_str(", ");44		}45		out.push_str(v as &str);46	}47	out48}4950fn format_signature(sig: &FunctionSignature) -> String {51	let mut out = String::new();52	out.push_str("\nFunction has the following signature: ");53	out.push('(');54	if sig.is_empty() {55		out.push_str("/*no arguments*/");56	} else {57		for (i, (name, default)) in sig.iter().enumerate() {58			if i != 0 {59				out.push_str(", ");60			}61			if let Some(name) = name {62				out.push_str(name);63			} else {64				out.push_str("<unnamed>");65			}66			match default {67				ParamDefault::None => {}68				ParamDefault::Exists => out.push_str(" = <default>"),69				ParamDefault::Literal(lit) => {70					out.push_str(" = ");71					out.push_str(lit);72				}73			}74		}75	}76	out.push(')');77	out78}7980const fn format_empty_str(str: &str) -> &str {81	if str.is_empty() {82		"\"\" (empty string)"83	} else {84		str85	}86}8788pub(crate) fn suggest_object_fields(v: &ObjValue, key: IStr) -> Vec<IStr> {89	let mut heap = Vec::new();90	for field in v.fields_ex(91		true,92		#[cfg(feature = "exp-preserve-order")]93		false,94	) {95		let conf = strsim::jaro_winkler(field.as_str(), key.as_str());96		if conf < 0.8 {97			continue;98		}99		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!");100101		heap.push((conf, field));102	}103	heap.sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap_or(Ordering::Equal));104	heap.into_iter().map(|v| v.1).collect()105}106107type FunctionSignature = Vec<(Option<IStr>, ParamDefault)>;108109/// Possible errors110#[allow(missing_docs)]111#[derive(Error, Debug, Clone, Trace)]112#[non_exhaustive]113pub enum ErrorKind {114	#[error("intrinsic not found: {0}")]115	IntrinsicNotFound(IStr),116117	#[error("operator {0} does not operate on type {1}")]118	UnaryOperatorDoesNotOperateOnType(UnaryOpType, ValType),119	#[error("binary operation {1} {0} {2} is not implemented")]120	BinaryOperatorDoesNotOperateOnValues(BinaryOpType, ValType, ValType),121122	#[error("self/super/$ are only usable inside objects")]123	CantUseSelfSupOutsideOfObject,124	#[error("no super found")]125	NoSuperFound,126127	#[error("for loop can only iterate over arrays")]128	InComprehensionCanOnlyIterateOverArray,129130	#[error("array out of bounds: {0} is not within [0,{1})")]131	ArrayBoundsError(isize, usize),132	#[error("string out of bounds: {0} is not within [0,{1})")]133	StringBoundsError(usize, usize),134135	#[error("assert failed: {}", format_empty_str(.0))]136	AssertionFailed(IStr),137138	#[error("local is not defined: {0}{found}", found = format_found(.1, "local"))]139	VariableIsNotDefined(IStr, Vec<IStr>),140	#[error("duplicate local var: {0}")]141	DuplicateLocalVar(IStr),142143	#[error("type mismatch: expected {expected}, got {2} {0}", expected = .1.iter().map(|e| format!("{e}")).collect::<Vec<_>>().join(", "))]144	TypeMismatch(&'static str, Vec<ValType>, ValType),145	#[error("no such field: {}{}", format_empty_str(.0), format_found(.1, "field"))]146	NoSuchField(IStr, Vec<IStr>),147148	#[error("only functions can be called, got {0}")]149	OnlyFunctionsCanBeCalledGot(ValType),150	#[error("parameter {0} is not defined")]151	UnknownFunctionParameter(String),152	#[error("argument {0} is already bound")]153	BindingParameterASecondTime(IStr),154	#[error("too many args, function has {0}{sig}", sig = format_signature(.1))]155	TooManyArgsFunctionHas(usize, FunctionSignature),156	#[error("function argument is not passed: {}{}", .0.as_ref().map_or("<unnamed>", IStr::as_str), format_signature(.1))]157	FunctionParameterNotBoundInCall(Option<IStr>, FunctionSignature),158159	#[error("external variable is not defined: {0}")]160	UndefinedExternalVariable(IStr),161162	#[error("field name should be string, got {0}")]163	FieldMustBeStringGot(ValType),164	#[error("duplicate field name: {}", format_empty_str(.0))]165	DuplicateFieldName(IStr),166167	#[error("attempted to index array with string {}", format_empty_str(.0))]168	AttemptedIndexAnArrayWithString(IStr),169	#[error("{0} index type should be {1}, got {2}")]170	ValueIndexMustBeTypeGot(ValType, ValType, ValType),171	#[error("cant index into {0}")]172	CantIndexInto(ValType),173	#[error("{0} is not indexable")]174	ValueIsNotIndexable(ValType),175176	#[error("super can't be used standalone")]177	StandaloneSuper,178179	#[error("can't resolve {1} from {0}")]180	ImportFileNotFound(SourcePath, ResolvePathOwned),181	#[error("resolved file not found: {:?}", .0)]182	ResolvedFileNotFound(SourcePath),183	#[error("can't import {0}: is a directory")]184	ImportIsADirectory(SourcePath),185	#[error("imported file is not valid utf-8: {0:?}")]186	ImportBadFileUtf8(SourcePath),187	#[error("import io error: {0}")]188	ImportIo(String),189	#[error("tried to import {1} from {0}, but imports are not supported")]190	ImportNotSupported(SourcePath, ResolvePathOwned),191	#[error("can't import from virtual file")]192	CantImportFromVirtualFile,193	#[error(194		"syntax error: {}",195		// Peg has no fancier way to handle critical parsing errors https://github.com/kevinmehall/rust-peg/issues/225196		{.error.expected.tokens().find(|t| t.starts_with("!!!")).map_or_else(|| {197			format!(198				"expected {}, got {:?}",199				.error.expected,200				.path.code().chars().nth(error.location.offset)201				.map_or_else(|| "EOF".into(), |c| c.to_string())202			)203		}, |v| v[3..].into())}204	)]205	ImportSyntaxError {206		path: Source,207		#[trace(skip)]208		error: Box<jrsonnet_parser::ParseError>,209	},210211	#[error("runtime error: {}", format_empty_str(.0))]212	RuntimeError(IStr),213	#[error("stack overflow, try to reduce recursion, or set --max-stack to bigger value")]214	StackOverflow,215	#[error("infinite recursion detected")]216	InfiniteRecursionDetected,217	#[error("tried to index by fractional value")]218	FractionalIndex,219	#[error("attempted to divide by zero")]220	DivisionByZero,221222	#[error("string manifest output is not an string")]223	StringManifestOutputIsNotAString,224	#[error("stream manifest output is not an array")]225	StreamManifestOutputIsNotAArray,226	#[error("multi manifest output is not an object")]227	MultiManifestOutputIsNotAObject,228229	#[error("cant recurse stream manifest")]230	StreamManifestOutputCannotBeRecursed,231	#[error("stream manifest output cannot consist of raw strings")]232	StreamManifestCannotNestString,233234	#[error("{}", format_empty_str(.0))]235	ImportCallbackError(String),236	#[error("invalid unicode codepoint: {0}")]237	InvalidUnicodeCodepointGot(u32),238239	#[error("convert num value: {0}")]240	ConvertNumValue(#[from] ConvertNumValueError),241242	#[error("format error: {0}")]243	Format(#[from] FormatError),244	#[error("type error: {0}")]245	TypeError(TypeLocError),246247	#[cfg(feature = "anyhow-error")]248	#[error(transparent)]249	Other(#[trace(skip)] std::rc::Rc<anyhow::Error>),250}251252#[cfg(feature = "anyhow-error")]253impl From<anyhow::Error> for Error {254	fn from(e: anyhow::Error) -> Self {255		Self::new(ErrorKind::Other(std::rc::Rc::new(e)))256	}257}258259impl From<ErrorKind> for Error {260	fn from(e: ErrorKind) -> Self {261		Self::new(e)262	}263}264265impl From<Infallible> for Error {266	fn from(_value: Infallible) -> Self {267		unreachable!()268	}269}270271/// Single stack trace frame272#[derive(Clone, Debug, Trace)]273pub struct StackTraceElement {274	/// Source of this frame275	/// Some frames only act as description, without attached source276	pub location: Option<Span>,277	/// Frame description278	pub desc: String,279}280#[derive(Debug, Clone, Trace)]281pub struct StackTrace(pub Vec<StackTraceElement>);282283#[derive(Clone, Trace)]284pub struct Error(Box<(ErrorKind, StackTrace)>);285impl Error {286	pub fn new(e: ErrorKind) -> Self {287		Self(Box::new((e, StackTrace(vec![]))))288	}289290	pub const fn error(&self) -> &ErrorKind {291		&(self.0).0292	}293	pub fn error_mut(&mut self) -> &mut ErrorKind {294		&mut (self.0).0295	}296	pub const fn trace(&self) -> &StackTrace {297		&(self.0).1298	}299	pub fn trace_mut(&mut self) -> &mut StackTrace {300		&mut (self.0).1301	}302}303impl Display for Error {304	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {305		writeln!(f, "{}", self.0 .0)?;306		for el in &self.0 .1 .0 {307			write!(f, "\t{}", el.desc)?;308			if let Some(loc) = &el.location {309				write!(f, "at {}", loc.0 .0 .0)?;310				loc.0.map_source_locations(&[loc.1, loc.2]);311			}312			writeln!(f)?;313		}314		Ok(())315	}316}317impl Debug for Error {318	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {319		f.debug_tuple("LocError").field(&self.0).finish()320	}321}322impl std::error::Error for Error {}323324pub trait ErrorSource {325	fn to_location(self) -> Option<Span>;326}327impl<T: Acyclic> ErrorSource for &Spanned<T> {328	fn to_location(self) -> Option<Span> {329		Some(self.span())330	}331}332impl ErrorSource for &Span {333	fn to_location(self) -> Option<Span> {334		Some(self.clone())335	}336}337impl ErrorSource for CallLocation<'_> {338	fn to_location(self) -> Option<Span> {339		self.0.cloned()340	}341}342343pub type Result<V, E = Error> = std::result::Result<V, E>;344pub trait ResultExt: Sized {345	#[must_use]346	fn with_description<O: Into<String>>(self, msg: impl FnOnce() -> O) -> Self;347	#[must_use]348	fn description(self, msg: &str) -> Self {349		self.with_description(|| msg)350	}351352	#[must_use]353	fn with_description_src<O: Into<String>>(354		self,355		src: impl ErrorSource,356		msg: impl FnOnce() -> O,357	) -> Self;358	#[must_use]359	fn description_src(self, src: impl ErrorSource, msg: &str) -> Self {360		self.with_description_src(src, || msg)361	}362}363impl<T> ResultExt for Result<T, Error> {364	fn with_description<O: Into<String>>(mut self, msg: impl FnOnce() -> O) -> Self {365		if let Err(e) = &mut self {366			let trace = e.trace_mut();367			trace.0.push(StackTraceElement {368				location: None,369				desc: msg().into(),370			});371		}372		self373	}374375	fn with_description_src<O: Into<String>>(376		mut self,377		src: impl ErrorSource,378		msg: impl FnOnce() -> O,379	) -> Self {380		if let Err(e) = &mut self {381			let trace = e.trace_mut();382			trace.0.push(StackTraceElement {383				location: src.to_location(),384				desc: msg().into(),385			});386		}387		self388	}389}390391#[macro_export]392macro_rules! bail {393	($w:ident$(::$i:ident)*$(($($tt:tt)*))?) => {394		return Err($w$(::$i)*$(($($tt)*))?.into())395	};396	($w:ident$(::$i:ident)*$({$($tt:tt)*})?) => {397		return Err($w$(::$i)*$({$($tt)*})?.into())398	};399	($l:literal$(, $($tt:tt)*)?) => {400		return Err($crate::error::ErrorKind::RuntimeError($crate::jrsonnet_macros::format_istr!($l$(, $($tt)*)?)).into())401	};402}403404#[macro_export]405macro_rules! runtime_error {406	($l:literal$(, $($tt:tt)*)?) => {407		$crate::error::Error::from($crate::error::ErrorKind::RuntimeError($crate::jrsonnet_macros::format_istr!($l$(, $($tt)*)?)))408	};409}