git.delta.rocks / jrsonnet / refs/commits / 96da6f397b93

difftreelog

source

crates/jrsonnet-evaluator/src/error.rs6.0 KiBsourcehistory
1use std::{fmt::Debug, path::PathBuf};23use 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};1314#[derive(Error, Debug, Clone, Trace)]15pub enum Error {16	#[error("intrinsic not found: {0}")]17	IntrinsicNotFound(IStr),1819	#[error("operator {0} does not operate on type {1}")]20	UnaryOperatorDoesNotOperateOnType(UnaryOpType, ValType),21	#[error("binary operation {1} {0} {2} is not implemented")]22	BinaryOperatorDoesNotOperateOnValues(BinaryOpType, ValType, ValType),2324	#[error("no top level object in this context")]25	NoTopLevelObjectFound,26	#[error("self is only usable inside objects")]27	CantUseSelfOutsideOfObject,28	#[error("no super found")]29	NoSuperFound,3031	#[error("for loop can only iterate over arrays")]32	InComprehensionCanOnlyIterateOverArray,3334	#[error("array out of bounds: {0} is not within [0,{1})")]35	ArrayBoundsError(usize, usize),36	#[error("string out of bounds: {0} is not within [0,{1})")]37	StringBoundsError(usize, usize),3839	#[error("assert failed: {0}")]40	AssertionFailed(IStr),4142	#[error("variable is not defined: {0}")]43	VariableIsNotDefined(IStr),44	#[error("duplicate local var: {0}")]45	DuplicateLocalVar(IStr),4647	#[error("type mismatch: expected {}, got {2} {0}", .1.iter().map(|e| format!("{}", e)).collect::<Vec<_>>().join(", "))]48	TypeMismatch(&'static str, Vec<ValType>, ValType),49	#[error("no such field: {0}")]50	NoSuchField(IStr),5152	#[error("only functions can be called, got {0}")]53	OnlyFunctionsCanBeCalledGot(ValType),54	#[error("parameter {0} is not defined")]55	UnknownFunctionParameter(String),56	#[error("argument {0} is already bound")]57	BindingParameterASecondTime(IStr),58	#[error("too many args, function has {0}")]59	TooManyArgsFunctionHas(usize),60	#[error("function argument is not passed: {0}")]61	FunctionParameterNotBoundInCall(IStr),6263	#[error("external variable is not defined: {0}")]64	UndefinedExternalVariable(IStr),6566	#[error("field name should be string, got {0}")]67	FieldMustBeStringGot(ValType),68	#[error("duplicate field name: {0}")]69	DuplicateFieldName(IStr),7071	#[error("attempted to index array with string {0}")]72	AttemptedIndexAnArrayWithString(IStr),73	#[error("{0} index type should be {1}, got {2}")]74	ValueIndexMustBeTypeGot(ValType, ValType, ValType),75	#[error("cant index into {0}")]76	CantIndexInto(ValType),77	#[error("{0} is not indexable")]78	ValueIsNotIndexable(ValType),7980	#[error("super can't be used standalone")]81	StandaloneSuper,8283	#[error("can't resolve {1} from {0}")]84	ImportFileNotFound(PathBuf, String),85	#[error("resolved file not found: {0}")]86	ResolvedFileNotFound(PathBuf),87	#[error("imported file is not valid utf-8: {0:?}")]88	ImportBadFileUtf8(PathBuf),89	#[error("import io error: {0}")]90	ImportIo(String),91	#[error("tried to import {1} from {0}, but imports is not supported")]92	ImportNotSupported(PathBuf, PathBuf),93	#[error("can't import from virtual file")]94	CantImportFromVirtualFile,95	#[error(96		"syntax error: expected {}, got {:?}",97		.error.expected,98		.source_code.chars().nth(error.location.offset)99		.map_or_else(|| "EOF".into(), |c| c.to_string())100	)]101	ImportSyntaxError {102		path: Source,103		source_code: IStr,104		#[skip_trace]105		error: Box<jrsonnet_parser::ParseError>,106	},107108	#[error("runtime error: {0}")]109	RuntimeError(IStr),110	#[error("stack overflow, try to reduce recursion, or set --max-stack to bigger value")]111	StackOverflow,112	#[error("infinite recursion detected")]113	InfiniteRecursionDetected,114	#[error("tried to index by fractional value")]115	FractionalIndex,116	#[error("attempted to divide by zero")]117	DivisionByZero,118119	#[error("string manifest output is not an string")]120	StringManifestOutputIsNotAString,121	#[error("stream manifest output is not an array")]122	StreamManifestOutputIsNotAArray,123	#[error("multi manifest output is not an object")]124	MultiManifestOutputIsNotAObject,125126	#[error("cant recurse stream manifest")]127	StreamManifestOutputCannotBeRecursed,128	#[error("stream manifest output cannot consist of raw strings")]129	StreamManifestCannotNestString,130131	#[error("{0}")]132	ImportCallbackError(String),133	#[error("invalid unicode codepoint: {0}")]134	InvalidUnicodeCodepointGot(u32),135136	#[error("format error: {0}")]137	Format(#[from] FormatError),138	#[error("type error: {0}")]139	TypeError(TypeLocError),140	#[error("sort error: {0}")]141	Sort(#[from] SortError),142143	/// Thrown as error, as this is legacy feature, and error here144	/// is acceptable for defeating object field cache145	#[error("should not reach outside: std.thisFile")]146	MagicThisFileUsed,147148	#[cfg(feature = "anyhow-error")]149	#[error(transparent)]150	Other(Rc<anyhow::Error>),151}152153#[cfg(feature = "anyhow-error")]154impl From<anyhow::Error> for LocError {155	fn from(e: anyhow::Error) -> Self {156		Self::new(Error::Other(Rc::new(e)))157	}158}159160impl From<Error> for LocError {161	fn from(e: Error) -> Self {162		Self::new(e)163	}164}165166#[derive(Clone, Debug, Trace)]167pub struct StackTraceElement {168	pub location: Option<ExprLocation>,169	pub desc: String,170}171#[derive(Debug, Clone, Trace)]172pub struct StackTrace(pub Vec<StackTraceElement>);173174#[derive(Clone, Trace)]175pub struct LocError(Box<(Error, StackTrace)>);176impl LocError {177	pub fn new(e: Error) -> Self {178		Self(Box::new((e, StackTrace(vec![]))))179	}180181	pub const fn error(&self) -> &Error {182		&(self.0).0183	}184	pub fn error_mut(&mut self) -> &mut Error {185		&mut (self.0).0186	}187	pub const fn trace(&self) -> &StackTrace {188		&(self.0).1189	}190	pub fn trace_mut(&mut self) -> &mut StackTrace {191		&mut (self.0).1192	}193}194impl Debug for LocError {195	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {196		writeln!(f, "{}", self.0 .0)?;197		for el in &self.0 .1 .0 {198			writeln!(f, "\t{:?}", el)?;199		}200		Ok(())201	}202}203204pub type Result<V, E = LocError> = std::result::Result<V, E>;205206#[macro_export]207macro_rules! throw {208	($e: expr) => {209		return Err($e.into())210	};211}212213#[macro_export]214macro_rules! throw_runtime {215	($($tt:tt)*) => {216		return Err($crate::error::Error::RuntimeError(format!($($tt)*).into()).into())217	};218}