jrsonnet_evaluator/
error.rs

1use crate::{
2	builtin::{format::FormatError, sort::SortError},
3	typed::TypeLocError,
4};
5use jrsonnet_gc::Trace;
6use jrsonnet_interner::IStr;
7use jrsonnet_parser::{BinaryOpType, ExprLocation, UnaryOpType};
8use jrsonnet_types::ValType;
9use std::{
10	path::{Path, PathBuf},
11	rc::Rc,
12};
13use thiserror::Error;
14
15#[derive(Error, Debug, Clone, Trace)]
16#[trivially_drop]
17pub enum Error {
18	#[error("intrinsic not found: {0}")]
19	IntrinsicNotFound(IStr),
20	#[error("argument reordering in intrisics not supported yet")]
21	IntrinsicArgumentReorderingIsNotSupportedYet,
22
23	#[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),
27
28	#[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,
34
35	#[error("for loop can only iterate over arrays")]
36	InComprehensionCanOnlyIterateOverArray,
37
38	#[error("array out of bounds: {0} is not within [0,{1})")]
39	ArrayBoundsError(usize, usize),
40
41	#[error("assert failed: {0}")]
42	AssertionFailed(IStr),
43
44	#[error("variable is not defined: {0}")]
45	VariableIsNotDefined(IStr),
46	#[error("type mismatch: expected {}, got {2} {0}", .1.iter().map(|e| format!("{}", e)).collect::<Vec<_>>().join(", "))]
47	TypeMismatch(&'static str, Vec<ValType>, ValType),
48	#[error("no such field: {0}")]
49	NoSuchField(IStr),
50
51	#[error("only functions can be called, got {0}")]
52	OnlyFunctionsCanBeCalledGot(ValType),
53	#[error("parameter {0} is not defined")]
54	UnknownFunctionParameter(String),
55	#[error("argument {0} is already bound")]
56	BindingParameterASecondTime(IStr),
57	#[error("too many args, function has {0}")]
58	TooManyArgsFunctionHas(usize),
59	#[error("founction argument is not passed: {0}")]
60	FunctionParameterNotBoundInCall(IStr),
61
62	#[error("external variable is not defined: {0}")]
63	UndefinedExternalVariable(IStr),
64	#[error("native is not defined: {0}")]
65	UndefinedExternalFunction(IStr),
66
67	#[error("field name should be string, got {0}")]
68	FieldMustBeStringGot(ValType),
69
70	#[error("attempted to index array with string {0}")]
71	AttemptedIndexAnArrayWithString(IStr),
72	#[error("{0} index type should be {1}, got {2}")]
73	ValueIndexMustBeTypeGot(ValType, ValType, ValType),
74	#[error("cant index into {0}")]
75	CantIndexInto(ValType),
76	#[error("{0} is not indexable")]
77	ValueIsNotIndexable(ValType),
78
79	#[error("super can't be used standalone")]
80	StandaloneSuper,
81
82	#[error("can't resolve {1} from {0}")]
83	ImportFileNotFound(PathBuf, PathBuf),
84	#[error("resolved file not found: {0}")]
85	ResolvedFileNotFound(PathBuf),
86	#[error("imported file is not valid utf-8: {0:?}")]
87	ImportBadFileUtf8(PathBuf),
88	#[error("tried to import {1} from {0}, but imports is not supported")]
89	ImportNotSupported(PathBuf, PathBuf),
90	#[error(
91		"syntax error, expected one of {}, got {:?}",
92		.error.expected,
93		.source_code.chars().nth(error.location.offset).map(|c| c.to_string()).unwrap_or_else(|| "EOF".into())
94	)]
95	ImportSyntaxError {
96		path: Rc<Path>,
97		source_code: IStr,
98		#[unsafe_ignore_trace]
99		error: Box<jrsonnet_parser::ParseError>,
100	},
101
102	#[error("runtime error: {0}")]
103	RuntimeError(IStr),
104	#[error("stack overflow, try to reduce recursion, or set --max-stack to bigger value")]
105	StackOverflow,
106	#[error("infinite recursion detected")]
107	RecursiveLazyValueEvaluation,
108	#[error("tried to index by fractional value")]
109	FractionalIndex,
110	#[error("attempted to divide by zero")]
111	DivisionByZero,
112
113	#[error("string manifest output is not an string")]
114	StringManifestOutputIsNotAString,
115	#[error("stream manifest output is not an array")]
116	StreamManifestOutputIsNotAArray,
117	#[error("multi manifest output is not an object")]
118	MultiManifestOutputIsNotAObject,
119
120	#[error("cant recurse stream manifest")]
121	StreamManifestOutputCannotBeRecursed,
122	#[error("stream manifest output cannot consist of raw strings")]
123	StreamManifestCannotNestString,
124
125	#[error("{0}")]
126	ImportCallbackError(String),
127	#[error("invalid unicode codepoint: {0}")]
128	InvalidUnicodeCodepointGot(u32),
129
130	#[error("format error: {0}")]
131	Format(#[from] FormatError),
132	#[error("type error: {0}")]
133	TypeError(TypeLocError),
134	#[error("sort error: {0}")]
135	Sort(#[from] SortError),
136
137	#[cfg(feature = "anyhow-error")]
138	#[error(transparent)]
139	Other(Rc<anyhow::Error>),
140}
141
142#[cfg(feature = "anyhow-error")]
143impl From<anyhow::Error> for LocError {
144	fn from(e: anyhow::Error) -> Self {
145		Self::new(Error::Other(Rc::new(e)))
146	}
147}
148
149impl From<Error> for LocError {
150	fn from(e: Error) -> Self {
151		Self::new(e)
152	}
153}
154
155#[derive(Clone, Debug, Trace)]
156#[trivially_drop]
157pub struct StackTraceElement {
158	pub location: Option<ExprLocation>,
159	pub desc: String,
160}
161#[derive(Debug, Clone, Trace)]
162#[trivially_drop]
163pub struct StackTrace(pub Vec<StackTraceElement>);
164
165#[derive(Debug, Clone, Trace)]
166#[trivially_drop]
167pub struct LocError(Box<(Error, StackTrace)>);
168impl LocError {
169	pub fn new(e: Error) -> Self {
170		Self(Box::new((e, StackTrace(vec![]))))
171	}
172
173	pub const fn error(&self) -> &Error {
174		&(self.0).0
175	}
176	pub fn error_mut(&mut self) -> &mut Error {
177		&mut (self.0).0
178	}
179	pub const fn trace(&self) -> &StackTrace {
180		&(self.0).1
181	}
182	pub fn trace_mut(&mut self) -> &mut StackTrace {
183		&mut (self.0).1
184	}
185}
186
187pub type Result<V> = std::result::Result<V, LocError>;
188
189#[macro_export]
190macro_rules! throw {
191	($e: expr) => {
192		return Err($e.into());
193	};
194}