difftreelog
refactor unify throw & throw_runtime
in: master
13 files changed
crates/jrsonnet-evaluator/src/error.rsdiffbeforeafterboth1use 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}crates/jrsonnet-evaluator/src/evaluate/destructure.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/evaluate/destructure.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/destructure.rs
@@ -32,7 +32,7 @@
Destruct::Array { start, rest, end } => {
use jrsonnet_parser::DestructRest;
- use crate::{throw_runtime, val::ArrValue};
+ use crate::{throw, val::ArrValue};
#[derive(Trace)]
struct DataThunk {
@@ -47,14 +47,14 @@
let v = self.parent.evaluate(s)?;
let arr = match v {
Val::Arr(a) => a,
- _ => throw_runtime!("expected array"),
+ _ => throw!("expected array"),
};
if !self.has_rest {
if arr.len() != self.min_len {
- throw_runtime!("expected {} elements, got {}", self.min_len, arr.len())
+ throw!("expected {} elements, got {}", self.min_len, arr.len())
}
} else if arr.len() < self.min_len {
- throw_runtime!(
+ throw!(
"expected at least {} elements, but array was only {}",
self.min_len,
arr.len()
@@ -163,7 +163,7 @@
}
#[cfg(feature = "exp-destruct")]
Destruct::Object { fields, rest } => {
- use crate::{obj::ObjValue, throw_runtime};
+ use crate::{obj::ObjValue, throw};
#[derive(Trace)]
struct DataThunk {
@@ -178,17 +178,17 @@
let v = self.parent.evaluate(s)?;
let obj = match v {
Val::Obj(o) => o,
- _ => throw_runtime!("expected object"),
+ _ => throw!("expected object"),
};
for field in &self.field_names {
if !obj.has_field_ex(field.clone(), true) {
- throw_runtime!("missing field: {}", field);
+ throw!("missing field: {}", field);
}
}
if !self.has_rest {
let len = obj.len();
if len != self.field_names.len() {
- throw_runtime!("too many fields, and rest not found");
+ throw!("too many fields, and rest not found");
}
}
Ok(obj)
crates/jrsonnet-evaluator/src/evaluate/operator.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/evaluate/operator.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/operator.rs
@@ -150,13 +150,13 @@
(Num(v1), BitXor, Num(v2)) => Num(f64::from((*v1 as i32) ^ (*v2 as i32))),
(Num(v1), Lhs, Num(v2)) => {
if *v2 < 0.0 {
- throw!(RuntimeError("shift by negative exponent".into()))
+ throw!("shift by negative exponent")
}
Num(f64::from((*v1 as i32) << (*v2 as i32)))
}
(Num(v1), Rhs, Num(v2)) => {
if *v2 < 0.0 {
- throw!(RuntimeError("shift by negative exponent".into()))
+ throw!("shift by negative exponent")
}
Num(f64::from((*v1 as i32) >> (*v2 as i32)))
}
crates/jrsonnet-evaluator/src/integrations/serde.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/integrations/serde.rs
+++ b/crates/jrsonnet-evaluator/src/integrations/serde.rs
@@ -72,7 +72,7 @@
}
Self::Object(out)
}
- Val::Func(_) => throw!(RuntimeError("tried to manifest function".into())),
+ Val::Func(_) => throw!("tried to manifest function"),
})
}
}
crates/jrsonnet-evaluator/src/stdlib/format.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/stdlib/format.rs
+++ b/crates/jrsonnet-evaluator/src/stdlib/format.rs
@@ -591,9 +591,7 @@
),
Val::Str(s) => {
if s.chars().count() != 1 {
- throw!(RuntimeError(
- format!("%c expected 1 char string, got {}", s.chars().count()).into(),
- ));
+ throw!("%c expected 1 char string, got {}", s.chars().count(),);
}
tmp_out.push_str(&s);
}
crates/jrsonnet-evaluator/src/stdlib/manifest.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/stdlib/manifest.rs
+++ b/crates/jrsonnet-evaluator/src/stdlib/manifest.rs
@@ -341,7 +341,7 @@
}
}
}
- Val::Func(_) => throw!(RuntimeError("tried to manifest function".into())),
+ Val::Func(_) => throw!("tried to manifest function"),
}
Ok(())
}
crates/jrsonnet-evaluator/src/typed/conversions.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/typed/conversions.rs
+++ b/crates/jrsonnet-evaluator/src/typed/conversions.rs
@@ -6,7 +6,7 @@
use jrsonnet_types::{ComplexValType, ValType};
use crate::{
- error::{Error::*, Result},
+ error::Result,
function::{FuncDesc, FuncVal},
throw,
typed::CheckType,
@@ -41,13 +41,10 @@
Val::Num(n) => {
#[allow(clippy::float_cmp)]
if n.trunc() != n {
- throw!(RuntimeError(
- format!(
- "cannot convert number with fractional part to {}",
- stringify!($ty)
- )
- .into()
- ))
+ throw!(
+ "cannot convert number with fractional part to {}",
+ stringify!($ty)
+ )
}
Ok(n as Self)
}
@@ -99,13 +96,10 @@
Val::Num(n) => {
#[allow(clippy::float_cmp)]
if n.trunc() != n {
- throw!(RuntimeError(
- format!(
- "cannot convert number with fractional part to {}",
- stringify!($ty)
- )
- .into()
- ))
+ throw!(
+ "cannot convert number with fractional part to {}",
+ stringify!($ty)
+ )
}
Ok(Self(n as $ty))
}
@@ -167,7 +161,7 @@
fn into_untyped(value: Self, _: State) -> Result<Val> {
if value > u32::MAX as Self {
- throw!(RuntimeError("number is too large".into()))
+ throw!("number is too large")
}
Ok(Val::Num(value as f64))
}
@@ -178,9 +172,7 @@
Val::Num(n) => {
#[allow(clippy::float_cmp)]
if n.trunc() != n {
- throw!(RuntimeError(
- "cannot convert number with fractional part to usize".into()
- ))
+ throw!("cannot convert number with fractional part to usize")
}
Ok(n as Self)
}
@@ -440,7 +432,7 @@
<Self as Typed>::TYPE.check(s, &value)?;
match value {
Val::Func(FuncVal::Normal(desc)) => Ok(desc),
- Val::Func(_) => throw!(RuntimeError("expected normal function, not builtin".into())),
+ Val::Func(_) => throw!("expected normal function, not builtin"),
_ => unreachable!(),
}
}
crates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/val.rs
+++ b/crates/jrsonnet-evaluator/src/val.rs
@@ -629,7 +629,7 @@
if num.is_finite() {
Ok(Self::Num(num))
} else {
- throw!(RuntimeError("overflow".into()))
+ throw!("overflow")
}
}
@@ -843,14 +843,14 @@
(Val::Null, Val::Null) => true,
(Val::Str(a), Val::Str(b)) => a == b,
(Val::Num(a), Val::Num(b)) => (a - b).abs() <= f64::EPSILON,
- (Val::Arr(_), Val::Arr(_)) => throw!(RuntimeError(
- "primitiveEquals operates on primitive types, got array".into(),
- )),
- (Val::Obj(_), Val::Obj(_)) => throw!(RuntimeError(
- "primitiveEquals operates on primitive types, got object".into(),
- )),
+ (Val::Arr(_), Val::Arr(_)) => {
+ throw!("primitiveEquals operates on primitive types, got array")
+ }
+ (Val::Obj(_), Val::Obj(_)) => {
+ throw!("primitiveEquals operates on primitive types, got object")
+ }
(a, b) if is_function_like(a) && is_function_like(b) => {
- throw!(RuntimeError("cannot test equality of functions".into()))
+ throw!("cannot test equality of functions")
}
(_, _) => false,
})
crates/jrsonnet-stdlib/src/arrays.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/arrays.rs
+++ b/crates/jrsonnet-stdlib/src/arrays.rs
@@ -1,7 +1,7 @@
use jrsonnet_evaluator::{
error::Result,
function::{builtin, FuncVal},
- throw_runtime,
+ throw,
typed::{Any, BoundedUsize, Typed, VecVal},
val::{equals, ArrValue, IndexableVal},
IStr, State, Val,
@@ -43,7 +43,7 @@
match func.evaluate_simple(s.clone(), &(c.to_string(),))? {
Val::Str(o) => out.push_str(&o),
Val::Null => continue,
- _ => throw_runtime!("in std.join all items should be strings"),
+ _ => throw!("in std.join all items should be strings"),
};
}
Ok(IndexableVal::Str(out.into()))
@@ -59,7 +59,7 @@
}
}
Val::Null => continue,
- _ => throw_runtime!("in std.join all items should be arrays"),
+ _ => throw!("in std.join all items should be arrays"),
};
}
Ok(IndexableVal::Arr(out.into()))
@@ -128,7 +128,7 @@
} else if matches!(item, Val::Null) {
continue;
} else {
- throw_runtime!("in std.join all items should be arrays");
+ throw!("in std.join all items should be arrays");
}
}
@@ -149,7 +149,7 @@
} else if matches!(item, Val::Null) {
continue;
} else {
- throw_runtime!("in std.join all items should be strings");
+ throw!("in std.join all items should be strings");
}
}
crates/jrsonnet-stdlib/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/lib.rs
+++ b/crates/jrsonnet-stdlib/src/lib.rs
@@ -8,7 +8,7 @@
error::{Error::*, Result},
function::{builtin::Builtin, ArgLike, CallLocation, FuncVal, TlaArg},
gc::{GcHashMap, TraceBox},
- tb, throw_runtime,
+ tb, throw,
trace::PathResolver,
typed::{Any, Either, Either2, Either4, VecVal, M1},
val::{equals, ArrValue},
@@ -500,7 +500,7 @@
true
}
}
- _ => throw_runtime!("both arguments should be of the same type"),
+ _ => throw!("both arguments should be of the same type"),
})
}
@@ -534,7 +534,7 @@
true
}
}
- _ => throw_runtime!("both arguments should be of the same type"),
+ _ => throw!("both arguments should be of the same type"),
})
}
crates/jrsonnet-stdlib/src/sort.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/sort.rs
+++ b/crates/jrsonnet-stdlib/src/sort.rs
@@ -1,7 +1,7 @@
use jrsonnet_evaluator::{
error::Result,
function::{builtin, FuncVal},
- throw_runtime,
+ throw,
typed::Any,
val::ArrValue,
State, Val,
@@ -41,9 +41,9 @@
(Val::Num(_), SortKeyType::Unknown) => sort_type = SortKeyType::Number,
(Val::Str(_), SortKeyType::String) | (Val::Num(_), SortKeyType::Number) => {}
(Val::Str(_) | Val::Num(_), _) => {
- throw_runtime!("sort elements should have the same types")
+ throw!("sort elements should have the same types")
}
- _ => throw_runtime!("sort key should either be a string or a number"),
+ _ => throw!("sort key should either be a string or a number"),
}
}
Ok(sort_type)
tests/tests/common.rsdiffbeforeafterboth--- a/tests/tests/common.rs
+++ b/tests/tests/common.rs
@@ -1,7 +1,7 @@
use jrsonnet_evaluator::{
error::Result,
function::{builtin, FuncVal},
- throw_runtime, ObjValueBuilder, State, Thunk, Val,
+ throw, ObjValueBuilder, State, Thunk, Val,
};
use jrsonnet_stdlib::StateExt;
@@ -11,7 +11,7 @@
let a = &$a;
let b = &$b;
if a != b {
- ::jrsonnet_evaluator::throw_runtime!("assertion failed: a != b\na={:#?}\nb={:#?}", a, b)
+ ::jrsonnet_evaluator::throw!("assertion failed: a != b\na={:#?}\nb={:#?}", a, b)
}
}};
}
@@ -20,7 +20,7 @@
macro_rules! ensure {
($v:expr $(,)?) => {
if !$v {
- ::jrsonnet_evaluator::throw_runtime!("assertion failed: {}", stringify!($v))
+ ::jrsonnet_evaluator::throw!("assertion failed: {}", stringify!($v))
}
};
}
@@ -29,7 +29,7 @@
macro_rules! ensure_val_eq {
($s:expr, $a:expr, $b:expr) => {{
if !::jrsonnet_evaluator::val::equals($s.clone(), &$a.clone(), &$b.clone())? {
- ::jrsonnet_evaluator::throw_runtime!(
+ ::jrsonnet_evaluator::throw!(
"assertion failed: a != b\na={:#?}\nb={:#?}",
$a.to_json(
$s.clone(),
@@ -52,7 +52,7 @@
fn assert_throw(s: State, lazy: Thunk<Val>, message: String) -> Result<bool> {
match lazy.evaluate(s) {
Ok(_) => {
- throw_runtime!("expected argument to throw on evaluation, but it returned instead")
+ throw!("expected argument to throw on evaluation, but it returned instead")
}
Err(e) => {
let error = format!("{}", e.error());
tests/tests/sanity.rsdiffbeforeafterboth--- a/tests/tests/sanity.rs
+++ b/tests/tests/sanity.rs
@@ -1,4 +1,4 @@
-use jrsonnet_evaluator::{error::Result, throw_runtime, State, Val};
+use jrsonnet_evaluator::{error::Result, throw, State, Val};
use jrsonnet_stdlib::StateExt;
mod common;
@@ -23,7 +23,7 @@
{
let e = match s.evaluate_snippet("snip".to_owned(), "assert 1 == 2: 'fail'; null") {
- Ok(_) => throw_runtime!("assertion should fail"),
+ Ok(_) => throw!("assertion should fail"),
Err(e) => e,
};
let e = s.stringify_err(&e);
@@ -31,7 +31,7 @@
}
{
let e = match s.evaluate_snippet("snip".to_owned(), "std.assertEqual(1, 2)") {
- Ok(_) => throw_runtime!("assertion should fail"),
+ Ok(_) => throw!("assertion should fail"),
Err(e) => e,
};
let e = s.stringify_err(&e);