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

difftreelog

source

crates/jrsonnet-evaluator/src/error.rs7.6 KiBsourcehistory
1use std::{fmt::Debug, path::PathBuf};23use jrsonnet_gcmodule::Trace;4use jrsonnet_interner::IStr;5use jrsonnet_parser::{BinaryOpType, ExprLocation, Source, SourcePath, UnaryOpType};6use jrsonnet_types::ValType;7use thiserror::Error;89use crate::{stdlib::format::FormatError, typed::TypeLocError};1011fn format_found(list: &[IStr], what: &str) -> String {12	if list.is_empty() {13		return String::new();14	}15	let mut out = String::new();16	out.push_str("\nThere is ");17	out.push_str(what);18	if list.len() > 1 {19		out.push('s');20	}21	out.push_str(" with similar name");22	if list.len() > 1 {23		out.push('s');24	}25	out.push_str(" present: ");26	for (i, v) in list.iter().enumerate() {27		if i != 0 {28			out.push_str(", ");29		}30		out.push_str(v as &str);31	}32	out33}3435fn format_signature(sig: &FunctionSignature) -> String {36	let mut out = String::new();37	out.push_str("\nFunction has the following signature: ");38	out.push('(');39	if sig.is_empty() {40		out.push_str("/*no arguments*/");41	} else {42		for (i, (name, has_default)) in sig.iter().enumerate() {43			if i != 0 {44				out.push_str(", ");45			}46			if let Some(name) = name {47				out.push_str(name);48			} else {49				out.push_str("<unnamed>");50			}51			if *has_default {52				out.push_str(" = <default>");53			}54		}55	}56	out.push(')');57	out58}5960const fn format_empty_str(str: &str) -> &str {61	if str.is_empty() {62		"\"\" (empty string)"63	} else {64		str65	}66}6768type FunctionSignature = Vec<(Option<IStr>, bool)>;6970/// Possible errors71#[allow(missing_docs)]72#[derive(Error, Debug, Clone, Trace)]73#[non_exhaustive]74pub enum Error {75	#[error("intrinsic not found: {0}")]76	IntrinsicNotFound(IStr),7778	#[error("operator {0} does not operate on type {1}")]79	UnaryOperatorDoesNotOperateOnType(UnaryOpType, ValType),80	#[error("binary operation {1} {0} {2} is not implemented")]81	BinaryOperatorDoesNotOperateOnValues(BinaryOpType, ValType, ValType),8283	#[error("no top level object in this context")]84	NoTopLevelObjectFound,85	#[error("self is only usable inside objects")]86	CantUseSelfOutsideOfObject,87	#[error("no super found")]88	NoSuperFound,8990	#[error("for loop can only iterate over arrays")]91	InComprehensionCanOnlyIterateOverArray,9293	#[error("array out of bounds: {0} is not within [0,{1})")]94	ArrayBoundsError(usize, usize),95	#[error("string out of bounds: {0} is not within [0,{1})")]96	StringBoundsError(usize, usize),9798	#[error("assert failed: {}", format_empty_str(.0))]99	AssertionFailed(IStr),100101	#[error("variable is not defined: {0}{}", format_found(.1, "variable"))]102	VariableIsNotDefined(IStr, Vec<IStr>),103	#[error("duplicate local var: {0}")]104	DuplicateLocalVar(IStr),105106	#[error("type mismatch: expected {}, got {2} {0}", .1.iter().map(|e| format!("{e}")).collect::<Vec<_>>().join(", "))]107	TypeMismatch(&'static str, Vec<ValType>, ValType),108	#[error("no such field: {}{}", format_empty_str(.0), format_found(.1, "field"))]109	NoSuchField(IStr, Vec<IStr>),110111	#[error("only functions can be called, got {0}")]112	OnlyFunctionsCanBeCalledGot(ValType),113	#[error("parameter {0} is not defined")]114	UnknownFunctionParameter(String),115	#[error("argument {0} is already bound")]116	BindingParameterASecondTime(IStr),117	#[error("too many args, function has {0}{}", format_signature(.1))]118	TooManyArgsFunctionHas(usize, FunctionSignature),119	#[error("function argument is not passed: {}{}", .0.as_ref().map_or("<unnamed>", IStr::as_str), format_signature(.1))]120	FunctionParameterNotBoundInCall(Option<IStr>, FunctionSignature),121122	#[error("external variable is not defined: {0}")]123	UndefinedExternalVariable(IStr),124125	#[error("field name should be string, got {0}")]126	FieldMustBeStringGot(ValType),127	#[error("duplicate field name: {}", format_empty_str(.0))]128	DuplicateFieldName(IStr),129130	#[error("attempted to index array with string {}", format_empty_str(.0))]131	AttemptedIndexAnArrayWithString(IStr),132	#[error("{0} index type should be {1}, got {2}")]133	ValueIndexMustBeTypeGot(ValType, ValType, ValType),134	#[error("cant index into {0}")]135	CantIndexInto(ValType),136	#[error("{0} is not indexable")]137	ValueIsNotIndexable(ValType),138139	#[error("super can't be used standalone")]140	StandaloneSuper,141142	#[error("can't resolve {1} from {0}")]143	ImportFileNotFound(SourcePath, String),144	#[error("can't resolve absolute {0}")]145	AbsoluteImportFileNotFound(PathBuf),146	#[error("resolved file not found: {:?}", .0)]147	ResolvedFileNotFound(SourcePath),148	#[error("can't import {0}: is a directory")]149	ImportIsADirectory(SourcePath),150	#[error("imported file is not valid utf-8: {0:?}")]151	ImportBadFileUtf8(SourcePath),152	#[error("import io error: {0}")]153	ImportIo(String),154	#[error("tried to import {1} from {0}, but imports are not supported")]155	ImportNotSupported(SourcePath, String),156	#[error("tried to import {0}, but absolute imports are not supported")]157	AbsoluteImportNotSupported(PathBuf),158	#[error("can't import from virtual file")]159	CantImportFromVirtualFile,160	#[error(161		"syntax error: expected {}, got {:?}",162		.error.expected,163		.path.code().chars().nth(error.location.offset)164		.map_or_else(|| "EOF".into(), |c| c.to_string())165	)]166	ImportSyntaxError {167		path: Source,168		#[trace(skip)]169		error: Box<jrsonnet_parser::ParseError>,170	},171172	#[error("runtime error: {}", format_empty_str(.0))]173	RuntimeError(IStr),174	#[error("stack overflow, try to reduce recursion, or set --max-stack to bigger value")]175	StackOverflow,176	#[error("infinite recursion detected")]177	InfiniteRecursionDetected,178	#[error("tried to index by fractional value")]179	FractionalIndex,180	#[error("attempted to divide by zero")]181	DivisionByZero,182183	#[error("string manifest output is not an string")]184	StringManifestOutputIsNotAString,185	#[error("stream manifest output is not an array")]186	StreamManifestOutputIsNotAArray,187	#[error("multi manifest output is not an object")]188	MultiManifestOutputIsNotAObject,189190	#[error("cant recurse stream manifest")]191	StreamManifestOutputCannotBeRecursed,192	#[error("stream manifest output cannot consist of raw strings")]193	StreamManifestCannotNestString,194195	#[error("{}", format_empty_str(.0))]196	ImportCallbackError(String),197	#[error("invalid unicode codepoint: {0}")]198	InvalidUnicodeCodepointGot(u32),199200	#[error("format error: {0}")]201	Format(#[from] FormatError),202	#[error("type error: {0}")]203	TypeError(TypeLocError),204205	#[cfg(feature = "anyhow-error")]206	#[error(transparent)]207	Other(Rc<anyhow::Error>),208}209210#[cfg(feature = "anyhow-error")]211impl From<anyhow::Error> for LocError {212	fn from(e: anyhow::Error) -> Self {213		Self::new(Error::Other(Rc::new(e)))214	}215}216217impl From<Error> for LocError {218	fn from(e: Error) -> Self {219		Self::new(e)220	}221}222223/// Single stack trace frame224#[derive(Clone, Debug, Trace)]225pub struct StackTraceElement {226	/// Source of this frame227	/// Some frames only act as description, without attached source228	pub location: Option<ExprLocation>,229	/// Frame description230	pub desc: String,231}232#[derive(Debug, Clone, Trace)]233pub struct StackTrace(pub Vec<StackTraceElement>);234235#[derive(Clone, Trace)]236pub struct LocError(Box<(Error, StackTrace)>);237impl LocError {238	pub fn new(e: Error) -> Self {239		Self(Box::new((e, StackTrace(vec![]))))240	}241242	pub const fn error(&self) -> &Error {243		&(self.0).0244	}245	pub fn error_mut(&mut self) -> &mut Error {246		&mut (self.0).0247	}248	pub const fn trace(&self) -> &StackTrace {249		&(self.0).1250	}251	pub fn trace_mut(&mut self) -> &mut StackTrace {252		&mut (self.0).1253	}254}255impl Debug for LocError {256	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {257		writeln!(f, "{}", self.0 .0)?;258		for el in &self.0 .1 .0 {259			writeln!(f, "\t{el:?}")?;260		}261		Ok(())262	}263}264265pub type Result<V, E = LocError> = std::result::Result<V, E>;266267#[macro_export]268macro_rules! throw {269	($e: expr) => {270		return Err($e.into())271	};272}273274#[macro_export]275macro_rules! throw_runtime {276	($($tt:tt)*) => {277		return Err($crate::error::Error::RuntimeError(format!($($tt)*).into()).into())278	};279}