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

difftreelog

source

crates/jrsonnet-evaluator/src/error.rs5.8 KiBsourcehistory
1use std::{2	fmt::Debug,3	path::{Path, PathBuf},4	rc::Rc,5};67use gcmodule::Trace;8use jrsonnet_interner::IStr;9use jrsonnet_parser::{BinaryOpType, ExprLocation, UnaryOpType};10use jrsonnet_types::ValType;11use thiserror::Error;1213use crate::{14	builtin::{format::FormatError, sort::SortError},15	typed::TypeLocError,16};1718#[derive(Error, Debug, Clone, Trace)]19pub enum Error {20	#[error("intrinsic not found: {0}")]21	IntrinsicNotFound(IStr),2223	#[error("operator {0} does not operate on type {1}")]24	UnaryOperatorDoesNotOperateOnType(UnaryOpType, ValType),25	#[error("binary operation {1} {0} {2} is not implemented")]26	BinaryOperatorDoesNotOperateOnValues(BinaryOpType, ValType, ValType),2728	#[error("no top level object in this context")]29	NoTopLevelObjectFound,30	#[error("self is only usable inside objects")]31	CantUseSelfOutsideOfObject,32	#[error("no super found")]33	NoSuperFound,3435	#[error("for loop can only iterate over arrays")]36	InComprehensionCanOnlyIterateOverArray,3738	#[error("array out of bounds: {0} is not within [0,{1})")]39	ArrayBoundsError(usize, usize),40	#[error("string out of bounds: {0} is not within [0,{1})")]41	StringBoundsError(usize, usize),4243	#[error("assert failed: {0}")]44	AssertionFailed(IStr),4546	#[error("variable is not defined: {0}")]47	VariableIsNotDefined(IStr),48	#[error("type mismatch: expected {}, got {2} {0}", .1.iter().map(|e| format!("{}", e)).collect::<Vec<_>>().join(", "))]49	TypeMismatch(&'static str, Vec<ValType>, ValType),50	#[error("no such field: {0}")]51	NoSuchField(IStr),5253	#[error("only functions can be called, got {0}")]54	OnlyFunctionsCanBeCalledGot(ValType),55	#[error("parameter {0} is not defined")]56	UnknownFunctionParameter(String),57	#[error("argument {0} is already bound")]58	BindingParameterASecondTime(IStr),59	#[error("too many args, function has {0}")]60	TooManyArgsFunctionHas(usize),61	#[error("function argument is not passed: {0}")]62	FunctionParameterNotBoundInCall(IStr),6364	#[error("external variable is not defined: {0}")]65	UndefinedExternalVariable(IStr),66	#[error("native is not defined: {0}")]67	UndefinedExternalFunction(IStr),6869	#[error("field name should be string, got {0}")]70	FieldMustBeStringGot(ValType),71	#[error("duplicate field name: {0}")]72	DuplicateFieldName(IStr),7374	#[error("attempted to index array with string {0}")]75	AttemptedIndexAnArrayWithString(IStr),76	#[error("{0} index type should be {1}, got {2}")]77	ValueIndexMustBeTypeGot(ValType, ValType, ValType),78	#[error("cant index into {0}")]79	CantIndexInto(ValType),80	#[error("{0} is not indexable")]81	ValueIsNotIndexable(ValType),8283	#[error("super can't be used standalone")]84	StandaloneSuper,8586	#[error("can't resolve {1} from {0}")]87	ImportFileNotFound(PathBuf, PathBuf),88	#[error("resolved file not found: {0}")]89	ResolvedFileNotFound(PathBuf),90	#[error("imported file is not valid utf-8: {0:?}")]91	ImportBadFileUtf8(PathBuf),92	#[error("import io error: {0}")]93	ImportIo(String),94	#[error("tried to import {1} from {0}, but imports is not supported")]95	ImportNotSupported(PathBuf, PathBuf),96	#[error(97		"syntax error: expected {}, got {:?}",98		.error.expected,99		.source_code.chars().nth(error.location.offset).map(|c| c.to_string()).unwrap_or_else(|| "EOF".into())100	)]101	ImportSyntaxError {102		#[skip_trace]103		path: Rc<Path>,104		source_code: IStr,105		#[skip_trace]106		error: Box<jrsonnet_parser::ParseError>,107	},108109	#[error("runtime error: {0}")]110	RuntimeError(IStr),111	#[error("stack overflow, try to reduce recursion, or set --max-stack to bigger value")]112	StackOverflow,113	#[error("infinite recursion detected")]114	InfiniteRecursionDetected,115	#[error("tried to index by fractional value")]116	FractionalIndex,117	#[error("attempted to divide by zero")]118	DivisionByZero,119120	#[error("string manifest output is not an string")]121	StringManifestOutputIsNotAString,122	#[error("stream manifest output is not an array")]123	StreamManifestOutputIsNotAArray,124	#[error("multi manifest output is not an object")]125	MultiManifestOutputIsNotAObject,126127	#[error("cant recurse stream manifest")]128	StreamManifestOutputCannotBeRecursed,129	#[error("stream manifest output cannot consist of raw strings")]130	StreamManifestCannotNestString,131132	#[error("{0}")]133	ImportCallbackError(String),134	#[error("invalid unicode codepoint: {0}")]135	InvalidUnicodeCodepointGot(u32),136137	#[error("format error: {0}")]138	Format(#[from] FormatError),139	#[error("type error: {0}")]140	TypeError(TypeLocError),141	#[error("sort error: {0}")]142	Sort(#[from] SortError),143144	#[cfg(feature = "anyhow-error")]145	#[error(transparent)]146	Other(Rc<anyhow::Error>),147}148149#[cfg(feature = "anyhow-error")]150impl From<anyhow::Error> for LocError {151	fn from(e: anyhow::Error) -> Self {152		Self::new(Error::Other(Rc::new(e)))153	}154}155156impl From<Error> for LocError {157	fn from(e: Error) -> Self {158		Self::new(e)159	}160}161162#[derive(Clone, Debug, Trace)]163pub struct StackTraceElement {164	pub location: Option<ExprLocation>,165	pub desc: String,166}167#[derive(Debug, Clone, Trace)]168pub struct StackTrace(pub Vec<StackTraceElement>);169170#[derive(Clone, Trace)]171pub struct LocError(Box<(Error, StackTrace)>);172impl LocError {173	pub fn new(e: Error) -> Self {174		Self(Box::new((e, StackTrace(vec![]))))175	}176177	pub const fn error(&self) -> &Error {178		&(self.0).0179	}180	pub fn error_mut(&mut self) -> &mut Error {181		&mut (self.0).0182	}183	pub const fn trace(&self) -> &StackTrace {184		&(self.0).1185	}186	pub fn trace_mut(&mut self) -> &mut StackTrace {187		&mut (self.0).1188	}189}190impl Debug for LocError {191	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {192		writeln!(f, "{}", self.0 .0)?;193		for el in self.0 .1 .0.iter() {194			writeln!(f, "\t{:?}", el)?;195		}196		Ok(())197	}198}199200pub type Result<V, E = LocError> = std::result::Result<V, E>;201202#[macro_export]203macro_rules! throw {204	($e: expr) => {205		return Err($e.into())206	};207}208209#[macro_export]210macro_rules! throw_runtime {211	($($tt:tt)*) => {212		return Err($crate::error::Error::RuntimeError(format!($($tt)*).into()).into())213	};214}