difftreelog
refactor error helpers
in: master
38 files changed
bindings/jsonnet/src/import.rsdiffbeforeafterboth--- a/bindings/jsonnet/src/import.rs
+++ b/bindings/jsonnet/src/import.rs
@@ -13,8 +13,9 @@
};
use jrsonnet_evaluator::{
+ bail,
error::{ErrorKind::*, Result},
- throw, FileImportResolver, ImportResolver,
+ FileImportResolver, ImportResolver,
};
use jrsonnet_gcmodule::Trace;
use jrsonnet_parser::{SourceDirectory, SourceFile, SourcePath};
@@ -80,7 +81,7 @@
assert!(success == 0 || success == 1);
if success == 0 {
let result = String::from_utf8(buf_intern).expect("error should be valid string");
- throw!(ImportCallbackError(result));
+ bail!(ImportCallbackError(result));
}
let found_here_raw = unsafe { CStr::from_ptr(found_here) };
bindings/jsonnet/src/lib.rsdiffbeforeafterboth--- a/bindings/jsonnet/src/lib.rs
+++ b/bindings/jsonnet/src/lib.rs
@@ -19,12 +19,12 @@
};
use jrsonnet_evaluator::{
- apply_tla,
+ apply_tla, bail,
function::TlaArg,
gc::GcHashMap,
manifest::{JsonFormat, ManifestFormat, ToStringFormat},
stack::set_stack_depth_limit,
- tb, throw,
+ tb,
trace::{CompactFormat, PathResolver, TraceFormat},
FileImportResolver, IStr, Result, State, Val,
};
@@ -249,7 +249,7 @@
fn val_to_multi(val: Val, format: &dyn ManifestFormat) -> Result<Vec<(IStr, IStr)>> {
let Val::Obj(val) = val else {
- throw!("expected object as multi output")
+ bail!("expected object as multi output")
};
let mut out = Vec::new();
for (k, v) in val.iter(
@@ -336,7 +336,7 @@
fn val_to_stream(val: Val, format: &dyn ManifestFormat) -> Result<Vec<IStr>> {
let Val::Arr(val) = val else {
- throw!("expected array as stream output")
+ bail!("expected array as stream output")
};
let mut out = Vec::new();
for item in val.iter() {
cmds/jrsonnet/src/main.rsdiffbeforeafterboth--- a/cmds/jrsonnet/src/main.rs
+++ b/cmds/jrsonnet/src/main.rs
@@ -7,9 +7,9 @@
use clap_complete::Shell;
use jrsonnet_cli::{GcOpts, ManifestOpts, MiscOpts, OutputOpts, StdOpts, TlaOpts, TraceOpts};
use jrsonnet_evaluator::{
- apply_tla,
+ apply_tla, bail,
error::{Error as JrError, ErrorKind},
- throw, ResultExt, State, Val,
+ ResultExt, State, Val,
};
#[cfg(feature = "mimalloc")]
@@ -208,7 +208,7 @@
create_dir_all(dir)?;
}
let Val::Obj(obj) = val else {
- throw!(
+ bail!(
"value should be object for --multi manifest, got {}",
val.value_type()
)
crates/jrsonnet-evaluator/src/ctx.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/ctx.rs
+++ b/crates/jrsonnet-evaluator/src/ctx.rs
@@ -54,7 +54,7 @@
pub fn binding(&self, name: IStr) -> Result<Thunk<Val>> {
use std::cmp::Ordering;
- use crate::throw;
+ use crate::bail;
if let Some(val) = self.0.bindings.get(&name).cloned() {
return Ok(val);
@@ -70,7 +70,7 @@
});
heap.sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap_or(Ordering::Equal));
- throw!(VariableIsNotDefined(
+ bail!(VariableIsNotDefined(
name,
heap.into_iter().map(|(_, k)| k).collect()
))
crates/jrsonnet-evaluator/src/dynamic.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/dynamic.rs
+++ b/crates/jrsonnet-evaluator/src/dynamic.rs
@@ -2,7 +2,7 @@
use jrsonnet_gcmodule::{Cc, Trace};
-use crate::{error::ErrorKind::InfiniteRecursionDetected, throw, val::ThunkValue, Result, Thunk};
+use crate::{bail, error::ErrorKind::InfiniteRecursionDetected, val::ThunkValue, Result};
// TODO: Replace with OnceCell once in std
#[derive(Clone, Trace)]
@@ -41,7 +41,7 @@
fn get(self: Box<Self>) -> Result<Self::Output> {
let Some(value) = self.0.get() else {
- throw!(InfiniteRecursionDetected);
+ bail!(InfiniteRecursionDetected);
};
Ok(value.clone())
}
crates/jrsonnet-evaluator/src/error.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/error.rs
+++ b/crates/jrsonnet-evaluator/src/error.rs
@@ -370,17 +370,21 @@
}
#[macro_export]
-macro_rules! throw {
+macro_rules! bail {
($w:ident$(::$i:ident)*$(($($tt:tt)*))?) => {
return Err($w$(::$i)*$(($($tt)*))?.into())
};
($w:ident$(::$i:ident)*$({$($tt:tt)*})?) => {
return Err($w$(::$i)*$({$($tt)*})?.into())
};
- ($l:literal) => {
- return Err($crate::error::ErrorKind::RuntimeError($l.into()).into())
+ ($l:literal$(, $($tt:tt)*)?) => {
+ return Err($crate::error::ErrorKind::RuntimeError(format!($l$(, $($tt)*)?).into()).into())
};
- ($l:literal, $($tt:tt)*) => {
- return Err($crate::error::ErrorKind::RuntimeError(format!($l, $($tt)*).into()).into())
+}
+
+#[macro_export]
+macro_rules! runtime_error {
+ ($l:literal$(, $($tt:tt)*)?) => {
+ $crate::error::Error::from($crate::error::ErrorKind::RuntimeError(format!($l$(, $($tt)*)?).into()))
};
}
crates/jrsonnet-evaluator/src/evaluate/destructure.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/evaluate/destructure.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/destructure.rs
@@ -3,10 +3,10 @@
use jrsonnet_parser::{BindSpec, Destruct, LocExpr, ParamsDesc};
use crate::{
+ bail,
error::{ErrorKind::*, Result},
evaluate, evaluate_method, evaluate_named,
gc::GcHashMap,
- throw,
val::ThunkValue,
Context, Pending, Thunk, Val,
};
@@ -23,7 +23,7 @@
Destruct::Full(v) => {
let old = new_bindings.insert(v.clone(), parent);
if old.is_some() {
- throw!(DuplicateLocalVar(v.clone()))
+ bail!(DuplicateLocalVar(v.clone()))
}
}
#[cfg(feature = "exp-destruct")]
@@ -46,14 +46,14 @@
fn get(self: Box<Self>) -> Result<Self::Output> {
let v = self.parent.evaluate()?;
let Val::Arr(arr) = v else {
- throw!("expected array");
+ bail!("expected array");
};
if !self.has_rest {
if arr.len() != self.min_len {
- throw!("expected {} elements, got {}", self.min_len, arr.len())
+ bail!("expected {} elements, got {}", self.min_len, arr.len())
}
} else if arr.len() < self.min_len {
- throw!(
+ bail!(
"expected at least {} elements, but array was only {}",
self.min_len,
arr.len()
@@ -178,17 +178,17 @@
fn get(self: Box<Self>) -> Result<Self::Output> {
let v = self.parent.evaluate()?;
let Val::Obj(obj) = v else {
- throw!("expected object");
+ bail!("expected object");
};
for field in &self.field_names {
if !obj.has_field_ex(field.clone(), true) {
- throw!("missing field: {}", field);
+ bail!("missing field: {field}");
}
}
if !self.has_rest {
let len = obj.len();
if len != self.field_names.len() {
- throw!("too many fields, and rest not found");
+ bail!("too many fields, and rest not found");
}
}
Ok(obj)
@@ -310,7 +310,7 @@
}),
);
if old.is_some() {
- throw!(DuplicateLocalVar(name.clone()))
+ bail!(DuplicateLocalVar(name.clone()))
}
}
}
crates/jrsonnet-evaluator/src/evaluate/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/evaluate/mod.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/mod.rs
@@ -11,11 +11,11 @@
use self::destructure::destruct;
use crate::{
arr::ArrValue,
+ bail,
destructure::evaluate_dest,
error::{suggest_object_fields, ErrorKind::*},
evaluate::operator::{evaluate_add_op, evaluate_binary_op_special, evaluate_unary_op},
function::{CallLocation, FuncDesc, FuncVal},
- throw,
typed::Typed,
val::{CachedUnbound, IndexableVal, StrValue, Thunk, ThunkValue},
Context, GcHashMap, ObjValue, ObjValueBuilder, ObjectAssertion, Pending, Result, ResultExt,
@@ -150,7 +150,7 @@
evaluate_comp(ctx, &specs[1..], callback)?;
}
}
- _ => throw!(InComprehensionCanOnlyIterateOverArray),
+ _ => bail!(InComprehensionCanOnlyIterateOverArray),
},
}
Ok(())
@@ -375,7 +375,7 @@
State::push(loc, || format!("function <{}> call", f.name()), body)?
}
}
- v => throw!(OnlyFunctionsCanBeCalledGot(v.value_type())),
+ v => bail!(OnlyFunctionsCanBeCalledGot(v.value_type())),
})
}
@@ -393,9 +393,9 @@
|| "assertion failure".to_owned(),
|| {
if let Some(msg) = msg {
- throw!(AssertionFailed(evaluate(ctx, msg)?.to_string()?));
+ bail!(AssertionFailed(evaluate(ctx, msg)?.to_string()?));
}
- throw!(AssertionFailed(Val::Null.to_string()?));
+ bail!(AssertionFailed(Val::Null.to_string()?));
},
)?;
}
@@ -457,12 +457,12 @@
if part.null_coaelse {
return Ok(Val::Null);
}
- throw!(NoSuperFound)
+ bail!(NoSuperFound)
};
let name = evaluate(ctx.clone(), &part.value)?;
let Val::Str(name) = name else {
- throw!(ValueIndexMustBeTypeGot(
+ bail!(ValueIndexMustBeTypeGot(
ValType::Obj,
ValType::Str,
name.value_type(),
@@ -483,7 +483,7 @@
None => {
let suggestions = suggest_object_fields(super_obj, name.clone());
- throw!(NoSuchField(name, suggestions))
+ bail!(NoSuchField(name, suggestions))
}
}
}
@@ -502,25 +502,25 @@
None => {
let suggestions = suggest_object_fields(&v, key.clone().into_flat());
- throw!(NoSuchField(key.clone().into_flat(), suggestions))
+ bail!(NoSuchField(key.clone().into_flat(), suggestions))
}
},
- (Val::Obj(_), n) => throw!(ValueIndexMustBeTypeGot(
+ (Val::Obj(_), n) => bail!(ValueIndexMustBeTypeGot(
ValType::Obj,
ValType::Str,
n.value_type(),
)),
(Val::Arr(v), Val::Num(n)) => {
if n.fract() > f64::EPSILON {
- throw!(FractionalIndex)
+ bail!(FractionalIndex)
}
v.get(n as usize)?
.ok_or_else(|| ArrayBoundsError(n as usize, v.len()))?
}
(Val::Arr(_), Val::Str(n)) => {
- throw!(AttemptedIndexAnArrayWithString(n.into_flat()))
+ bail!(AttemptedIndexAnArrayWithString(n.into_flat()))
}
- (Val::Arr(_), n) => throw!(ValueIndexMustBeTypeGot(
+ (Val::Arr(_), n) => bail!(ValueIndexMustBeTypeGot(
ValType::Arr,
ValType::Num,
n.value_type(),
@@ -537,18 +537,18 @@
.into();
if v.is_empty() {
let size = s.into_flat().chars().count();
- throw!(StringBoundsError(n as usize, size))
+ bail!(StringBoundsError(n as usize, size))
}
StrValue::Flat(v)
}),
- (Val::Str(_), n) => throw!(ValueIndexMustBeTypeGot(
+ (Val::Str(_), n) => bail!(ValueIndexMustBeTypeGot(
ValType::Str,
ValType::Num,
n.value_type(),
)),
#[cfg(feature = "exp-null-coaelse")]
(Val::Null, _) if part.null_coaelse => return Ok(Val::Null),
- (v, _) => throw!(CantIndexInto(v.value_type())),
+ (v, _) => bail!(CantIndexInto(v.value_type())),
};
}
indexable
@@ -612,7 +612,7 @@
ErrorStmt(e) => State::push(
CallLocation::new(loc),
|| "error statement".to_owned(),
- || throw!(RuntimeError(evaluate(ctx, e)?.to_string()?,)),
+ || bail!(RuntimeError(evaluate(ctx, e)?.to_string()?,)),
)?,
IfElse {
cond,
@@ -661,7 +661,7 @@
}
i @ (Import(path) | ImportStr(path) | ImportBin(path)) => {
let Expr::Str(path) = &*path.0 else {
- throw!("computed imports are not supported")
+ bail!("computed imports are not supported")
};
let tmp = loc.clone().0;
let s = ctx.state();
crates/jrsonnet-evaluator/src/evaluate/operator.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/evaluate/operator.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/operator.rs
@@ -4,10 +4,10 @@
use crate::{
arr::ArrValue,
+ bail,
error::ErrorKind::*,
evaluate,
stdlib::std_format,
- throw,
typed::Typed,
val::{equals, StrValue},
Context, Result, Val,
@@ -21,7 +21,7 @@
(Minus, Num(n)) => Num(-*n),
(Not, Bool(v)) => Bool(!v),
(BitNot, Num(n)) => Num(!(*n as i64) as f64),
- (op, o) => throw!(UnaryOperatorDoesNotOperateOnType(op, o.value_type())),
+ (op, o) => bail!(UnaryOperatorDoesNotOperateOnType(op, o.value_type())),
})
}
@@ -49,7 +49,7 @@
(Num(v1), Num(v2)) => Val::new_checked_num(v1 + v2)?,
#[cfg(feature = "exp-bigint")]
(BigInt(a), BigInt(b)) => BigInt(Box::new((&**a).clone() + (&**b).clone())),
- _ => throw!(BinaryOperatorDoesNotOperateOnValues(
+ _ => bail!(BinaryOperatorDoesNotOperateOnValues(
BinaryOpType::Add,
a.value_type(),
b.value_type(),
@@ -62,14 +62,14 @@
match (a, b) {
(Num(a), Num(b)) => {
if *b == 0.0 {
- throw!(DivisionByZero)
+ bail!(DivisionByZero)
}
Ok(Num(a % b))
}
(Str(str), vals) => {
String::into_untyped(std_format(&str.clone().into_flat(), vals.clone())?)
}
- (a, b) => throw!(BinaryOperatorDoesNotOperateOnValues(
+ (a, b) => bail!(BinaryOperatorDoesNotOperateOnValues(
BinaryOpType::Mod,
a.value_type(),
b.value_type()
@@ -124,7 +124,7 @@
}
a.len().cmp(&b.len())
}
- (_, _) => throw!(BinaryOperatorDoesNotOperateOnValues(
+ (_, _) => bail!(BinaryOperatorDoesNotOperateOnValues(
op,
a.value_type(),
b.value_type()
@@ -159,7 +159,7 @@
(Num(v1), Mul, Num(v2)) => Val::new_checked_num(v1 * v2)?,
(Num(v1), Div, Num(v2)) => {
if *v2 == 0.0 {
- throw!(DivisionByZero)
+ bail!(DivisionByZero)
}
Val::new_checked_num(v1 / v2)?
}
@@ -171,14 +171,14 @@
(Num(v1), BitXor, Num(v2)) => Num((*v1 as i64 ^ *v2 as i64) as f64),
(Num(v1), Lhs, Num(v2)) => {
if *v2 < 0.0 {
- throw!("shift by negative exponent")
+ bail!("shift by negative exponent")
}
let exp = ((*v2 as i64) & 63) as u32;
Num((*v1 as i64).wrapping_shl(exp) as f64)
}
(Num(v1), Rhs, Num(v2)) => {
if *v2 < 0.0 {
- throw!("shift by negative exponent")
+ bail!("shift by negative exponent")
}
let exp = ((*v2 as i64) & 63) as u32;
Num((*v1 as i64).wrapping_shr(exp) as f64)
@@ -190,7 +190,7 @@
#[cfg(feature = "exp-bigint")]
(BigInt(a), Sub, BigInt(b)) => BigInt(Box::new((&**a).clone() - (&**b).clone())),
- _ => throw!(BinaryOperatorDoesNotOperateOnValues(
+ _ => bail!(BinaryOperatorDoesNotOperateOnValues(
op,
a.value_type(),
b.value_type(),
crates/jrsonnet-evaluator/src/function/arglike.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/function/arglike.rs
+++ b/crates/jrsonnet-evaluator/src/function/arglike.rs
@@ -3,14 +3,7 @@
use jrsonnet_interner::IStr;
use jrsonnet_parser::{ArgsDesc, LocExpr};
-use crate::{
- error::Result,
- evaluate,
- gc::GcHashMap,
- typed::Typed,
- val::{StrValue, ThunkValue},
- Context, Thunk, Val,
-};
+use crate::{evaluate, gc::GcHashMap, typed::Typed, val::ThunkValue, Context, Result, Thunk, Val};
/// Marker for arguments, which can be evaluated with context set to None
pub trait OptionalContext {}
crates/jrsonnet-evaluator/src/function/builtin.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/function/builtin.rs
+++ b/crates/jrsonnet-evaluator/src/function/builtin.rs
@@ -4,7 +4,7 @@
use jrsonnet_interner::IStr;
use super::{arglike::ArgsLike, parse::parse_builtin_call, CallLocation};
-use crate::{error::Result, gc::TraceBox, tb, Context, Val};
+use crate::{gc::TraceBox, tb, Context, Result, Val};
/// Can't have str | IStr, because constant BuiltinParam causes
/// E0492: constant functions cannot refer to interior mutable data
crates/jrsonnet-evaluator/src/function/parse.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/function/parse.rs
+++ b/crates/jrsonnet-evaluator/src/function/parse.rs
@@ -6,11 +6,11 @@
use super::{arglike::ArgsLike, builtin::BuiltinParam};
use crate::{
+ bail,
destructure::destruct,
error::{ErrorKind::*, Result},
evaluate_named,
gc::GcHashMap,
- throw,
val::ThunkValue,
Context, Pending, Thunk, Val,
};
@@ -47,7 +47,7 @@
let mut passed_args =
GcHashMap::with_capacity(params.iter().map(|p| p.0.capacity_hint()).sum());
if args.unnamed_len() > params.len() {
- throw!(TooManyArgsFunctionHas(
+ bail!(TooManyArgsFunctionHas(
params.len(),
params.iter().map(|p| (p.0.name(), p.1.is_some())).collect()
))
@@ -71,10 +71,10 @@
args.named_iter(ctx, tailstrict, &mut |name, value| {
// FIXME: O(n) for arg existence check
if !params.iter().any(|p| p.0.name().as_ref() == Some(name)) {
- throw!(UnknownFunctionParameter((name as &str).to_owned()));
+ bail!(UnknownFunctionParameter((name as &str).to_owned()));
}
if passed_args.insert(name.clone(), value).is_some() {
- throw!(BindingParameterASecondTime(name.clone()));
+ bail!(BindingParameterASecondTime(name.clone()));
}
filled_named += 1;
Ok(())
@@ -125,7 +125,7 @@
}
});
if !found {
- throw!(FunctionParameterNotBoundInCall(
+ bail!(FunctionParameterNotBoundInCall(
param.0.clone().name(),
params.iter().map(|p| (p.0.name(), p.1.is_some())).collect()
));
@@ -159,7 +159,7 @@
) -> Result<Vec<Option<Thunk<Val>>>> {
let mut passed_args: Vec<Option<Thunk<Val>>> = vec![None; params.len()];
if args.unnamed_len() > params.len() {
- throw!(TooManyArgsFunctionHas(
+ bail!(TooManyArgsFunctionHas(
params.len(),
params
.iter()
@@ -183,7 +183,7 @@
.position(|p| p.name() == name)
.ok_or_else(|| UnknownFunctionParameter((name as &str).to_owned()))?;
if replace(&mut passed_args[id], Some(arg)).is_some() {
- throw!(BindingParameterASecondTime(name.clone()));
+ bail!(BindingParameterASecondTime(name.clone()));
}
filled_args += 1;
Ok(())
@@ -207,7 +207,7 @@
}
});
if !found {
- throw!(FunctionParameterNotBoundInCall(
+ bail!(FunctionParameterNotBoundInCall(
param.name().as_str().map(IStr::from),
params
.iter()
crates/jrsonnet-evaluator/src/import.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/import.rs
+++ b/crates/jrsonnet-evaluator/src/import.rs
@@ -12,8 +12,8 @@
use jrsonnet_parser::{SourceDirectory, SourceFile, SourcePath};
use crate::{
+ bail,
error::{ErrorKind::*, Result},
- throw,
};
/// Implements file resolution logic for `import` and `importStr`
@@ -25,14 +25,14 @@
/// `from` should only be returned from [`ImportResolver::resolve`], or from other defined file, any other value
/// may result in panic
fn resolve_from(&self, from: &SourcePath, path: &str) -> Result<SourcePath> {
- throw!(ImportNotSupported(from.clone(), path.into()))
+ bail!(ImportNotSupported(from.clone(), path.into()))
}
fn resolve_from_default(&self, path: &str) -> Result<SourcePath> {
self.resolve_from(&SourcePath::default(), path)
}
/// Resolves absolute path, doesn't supports jpath and other fancy things
fn resolve(&self, path: &Path) -> Result<SourcePath> {
- throw!(AbsoluteImportNotSupported(path.to_owned()))
+ bail!(AbsoluteImportNotSupported(path.to_owned()))
}
/// Load resolved file
@@ -110,16 +110,16 @@
)));
}
}
- throw!(ImportFileNotFound(from.clone(), path.to_owned()))
+ bail!(ImportFileNotFound(from.clone(), path.to_owned()))
}
}
fn resolve(&self, path: &Path) -> Result<SourcePath> {
let meta = match fs::metadata(path) {
Ok(v) => v,
Err(e) if e.kind() == ErrorKind::NotFound => {
- throw!(AbsoluteImportFileNotFound(path.to_owned()))
+ bail!(AbsoluteImportFileNotFound(path.to_owned()))
}
- Err(e) => throw!(ImportIo(e.to_string())),
+ Err(e) => bail!(ImportIo(e.to_string())),
};
if meta.is_file() {
Ok(SourcePath::new(SourceFile::new(
@@ -138,7 +138,7 @@
let path = if let Some(f) = id.downcast_ref::<SourceFile>() {
f.path()
} else if id.downcast_ref::<SourceDirectory>().is_some() || id.is_default() {
- throw!(ImportIsADirectory(id.clone()))
+ bail!(ImportIsADirectory(id.clone()))
} else {
unreachable!("other types are not supported in resolve");
};
crates/jrsonnet-evaluator/src/integrations/serde.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/integrations/serde.rs
+++ b/crates/jrsonnet-evaluator/src/integrations/serde.rs
@@ -620,6 +620,6 @@
where
T: std::fmt::Display,
{
- JrError::new(ErrorKind::RuntimeError(format!("serde: {msg}").into()))
+ runtime_error!("serde: {msg}")
}
}
crates/jrsonnet-evaluator/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/lib.rs
+++ b/crates/jrsonnet-evaluator/src/lib.rs
@@ -354,7 +354,7 @@
}
let parsed = file.parsed.as_ref().expect("just set").clone();
if file.evaluating {
- throw!(InfiniteRecursionDetected)
+ bail!(InfiniteRecursionDetected)
}
file.evaluating = true;
// Dropping file cache guard here, as evaluation may use this map too
crates/jrsonnet-evaluator/src/manifest.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/manifest.rs
+++ b/crates/jrsonnet-evaluator/src/manifest.rs
@@ -1,9 +1,6 @@
use std::{borrow::Cow, fmt::Write};
-use crate::{
- error::{ErrorKind::*, Result},
- throw, State, Val,
-};
+use crate::{bail, Result, State, Val};
pub trait ManifestFormat {
fn manifest_buf(&self, val: Val, buf: &mut String) -> Result<()>;
@@ -268,7 +265,7 @@
}
buf.push('}');
}
- Val::Func(_) => throw!(RuntimeError("tried to manifest function".into())),
+ Val::Func(_) => bail!("tried to manifest function"),
};
Ok(())
}
@@ -292,7 +289,7 @@
impl ManifestFormat for StringFormat {
fn manifest_buf(&self, val: Val, out: &mut String) -> Result<()> {
let Val::Str(s) = val else {
- throw!(
+ bail!(
"output should be string for string manifest format, got {}",
val.value_type()
)
@@ -309,7 +306,7 @@
impl<I: ManifestFormat> ManifestFormat for YamlStreamFormat<I> {
fn manifest_buf(&self, val: Val, out: &mut String) -> Result<()> {
let Val::Arr(arr) = val else {
- throw!(
+ bail!(
"output should be array for yaml stream format, got {}",
val.value_type()
)
crates/jrsonnet-evaluator/src/obj.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/obj.rs
+++ b/crates/jrsonnet-evaluator/src/obj.rs
@@ -13,11 +13,12 @@
use crate::{
arr::{PickObjectKeyValues, PickObjectValues},
+ bail,
error::{suggest_object_fields, Error, ErrorKind::*},
function::CallLocation,
gc::{GcHashMap, GcHashSet, TraceBox},
operator::evaluate_add_op,
- tb, throw,
+ tb,
val::{ArrValue, ThunkValue},
MaybeUnbound, Result, State, Thunk, Unbound, Val,
};
@@ -404,7 +405,7 @@
pub fn get_or_bail(&self, key: IStr) -> Result<Val> {
let Some(value) = self.get(key.clone())? else {
let suggestions = suggest_object_fields(self, key.clone());
- throw!(NoSuchField(key, suggestions))
+ bail!(NoSuchField(key, suggestions))
};
Ok(value)
}
@@ -723,7 +724,7 @@
return Ok(match v {
CacheValue::Cached(v) => Some(v.clone()),
CacheValue::NotFound => None,
- CacheValue::Pending => throw!(InfiniteRecursionDetected),
+ CacheValue::Pending => bail!(InfiniteRecursionDetected),
CacheValue::Errored(e) => return Err(e.clone()),
});
}
@@ -953,7 +954,7 @@
State::push(
CallLocation(location.as_ref()),
|| format!("field <{}> initializtion", name.clone()),
- || throw!(DuplicateFieldName(name.clone())),
+ || bail!(DuplicateFieldName(name.clone())),
)?;
}
Ok(())
crates/jrsonnet-evaluator/src/stdlib/format.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/stdlib/format.rs
+++ b/crates/jrsonnet-evaluator/src/stdlib/format.rs
@@ -7,8 +7,8 @@
use thiserror::Error;
use crate::{
+ bail,
error::{format_found, suggest_object_fields, ErrorKind::*},
- throw,
typed::Typed,
Error, ObjValue, Result, Val,
};
@@ -611,12 +611,12 @@
Val::Str(s) => {
let s = s.into_flat();
if s.chars().count() != 1 {
- throw!("%c expected 1 char string, got {}", s.chars().count(),);
+ bail!("%c expected 1 char string, got {}", s.chars().count());
}
tmp_out.push_str(&s);
}
_ => {
- throw!(TypeMismatch(
+ bail!(TypeMismatch(
"%c requires number/string",
vec![ValType::Num, ValType::Str],
value.value_type(),
@@ -657,7 +657,7 @@
let width = match c.width {
Width::Star => {
if values.is_empty() {
- throw!(NotEnoughValues);
+ bail!(NotEnoughValues);
}
let value = &values[0];
values = &values[1..];
@@ -668,7 +668,7 @@
let precision = match c.precision {
Some(Width::Star) => {
if values.is_empty() {
- throw!(NotEnoughValues);
+ bail!(NotEnoughValues);
}
let value = &values[0];
values = &values[1..];
@@ -683,7 +683,7 @@
&Val::Null
} else {
if values.is_empty() {
- throw!(NotEnoughValues);
+ bail!(NotEnoughValues);
}
let value = &values[0];
values = &values[1..];
@@ -696,7 +696,7 @@
}
if !values.is_empty() {
- throw!(
+ bail!(
"too many values to format, expected {value_count}, got {}",
value_count + values.len()
)
@@ -717,7 +717,7 @@
let current = &field[name_offset..end_offset];
let full = &field[..name_offset];
let found = Box::new(suggest_object_fields(&obj, current.into()));
- throw!(SubfieldNotFound {
+ bail!(SubfieldNotFound {
current: current.into(),
full: full.into(),
found,
@@ -726,7 +726,7 @@
} else {
// No underflow may happen, initially we always start with an object
let subfield = &field[..name_offset - 1];
- throw!(SubfieldDidntYieldAnObject(
+ bail!(SubfieldDidntYieldAnObject(
subfield.into(),
current.value_type()
));
@@ -750,13 +750,13 @@
let f: IStr = c.mkey.into();
let width = match c.width {
Width::Star => {
- throw!(CannotUseStarWidthWithObject);
+ bail!(CannotUseStarWidthWithObject);
}
Width::Fixed(n) => n,
};
let precision = match c.precision {
Some(Width::Star) => {
- throw!(CannotUseStarWidthWithObject);
+ bail!(CannotUseStarWidthWithObject);
}
Some(Width::Fixed(n)) => Some(n),
None => None,
@@ -766,7 +766,7 @@
Val::Null
} else {
if f.is_empty() {
- throw!(MappingKeysRequired);
+ bail!(MappingKeysRequired);
}
if let Some(v) = values.get(f.clone())? {
v
crates/jrsonnet-evaluator/src/stdlib/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/stdlib/mod.rs
+++ b/crates/jrsonnet-evaluator/src/stdlib/mod.rs
@@ -3,7 +3,7 @@
use format::{format_arr, format_obj};
-use crate::{error::Result, function::CallLocation, State, Val};
+use crate::{function::CallLocation, Result, State, Val};
pub mod format;
crates/jrsonnet-evaluator/src/typed/conversions.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/typed/conversions.rs
+++ b/crates/jrsonnet-evaluator/src/typed/conversions.rs
@@ -7,12 +7,11 @@
use crate::{
arr::{ArrValue, BytesArray},
- error::Result,
+ bail,
function::{native::NativeDesc, FuncDesc, FuncVal},
- throw,
typed::CheckType,
- val::{IndexableVal, StrValue, ThunkMapper},
- ObjValue, ObjValueBuilder, Thunk, Val,
+ val::{IndexableVal, ThunkMapper},
+ ObjValue, ObjValueBuilder, Result, Thunk, Val,
};
#[derive(Trace)]
@@ -134,7 +133,7 @@
Val::Num(n) => {
#[allow(clippy::float_cmp)]
if n.trunc() != n {
- throw!(
+ bail!(
"cannot convert number with fractional part to {}",
stringify!($ty)
)
@@ -189,7 +188,7 @@
Val::Num(n) => {
#[allow(clippy::float_cmp)]
if n.trunc() != n {
- throw!(
+ bail!(
"cannot convert number with fractional part to {}",
stringify!($ty)
)
@@ -253,7 +252,7 @@
fn into_untyped(value: Self) -> Result<Val> {
if value > MAX_SAFE_INTEGER as Self {
- throw!("number is too large")
+ bail!("number is too large")
}
Ok(Val::Num(value as f64))
}
@@ -264,7 +263,7 @@
Val::Num(n) => {
#[allow(clippy::float_cmp)]
if n.trunc() != n {
- throw!("cannot convert number with fractional part to usize")
+ bail!("cannot convert number with fractional part to usize")
}
Ok(n as Self)
}
@@ -354,7 +353,7 @@
let mut out = ObjValueBuilder::with_capacity(typed.len());
for (k, v) in typed {
let Some(key) = K::into_untyped(k)?.as_str() else {
- throw!("map key should serialize to string");
+ bail!("map key should serialize to string");
};
let value = V::into_untyped(v)?;
out.member(key).value_unchecked(value);
@@ -567,7 +566,7 @@
<Self as Typed>::TYPE.check(&value)?;
match value {
Val::Func(FuncVal::Normal(desc)) => Ok(desc),
- Val::Func(_) => throw!("expected normal function, not builtin"),
+ Val::Func(_) => bail!("expected normal function, not builtin"),
_ => unreachable!(),
}
}
@@ -649,7 +648,7 @@
const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Func);
fn into_untyped(_typed: Self) -> Result<Val> {
- throw!("can only convert functions from jsonnet to native")
+ bail!("can only convert functions from jsonnet to native")
}
fn from_untyped(untyped: Val) -> Result<Self> {
crates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth1use std::{2 cell::RefCell,3 fmt::{self, Debug, Display},4 mem::replace,5 rc::Rc,6};78use jrsonnet_gcmodule::{Cc, Trace};9use jrsonnet_interner::IStr;10use jrsonnet_types::ValType;1112pub use crate::arr::{ArrValue, ArrayLike};13use crate::{14 error::{Error, ErrorKind::*},15 function::FuncVal,16 gc::{GcHashMap, TraceBox},17 manifest::{ManifestFormat, ToStringFormat},18 tb, throw,19 typed::BoundedUsize,20 ObjValue, Result, Unbound, WeakObjValue,21};2223pub trait ThunkValue: Trace {24 type Output;25 fn get(self: Box<Self>) -> Result<Self::Output>;26}2728#[derive(Trace)]29enum ThunkInner<T: Trace> {30 Computed(T),31 Errored(Error),32 Waiting(TraceBox<dyn ThunkValue<Output = T>>),33 Pending,34}3536/// Lazily evaluated value37#[allow(clippy::module_name_repetitions)]38#[derive(Clone, Trace)]39pub struct Thunk<T: Trace>(Cc<RefCell<ThunkInner<T>>>);4041impl<T: Trace> Thunk<T> {42 pub fn evaluated(val: T) -> Self {43 Self(Cc::new(RefCell::new(ThunkInner::Computed(val))))44 }45 pub fn new(f: impl ThunkValue<Output = T> + 'static) -> Self {46 Self(Cc::new(RefCell::new(ThunkInner::Waiting(tb!(f)))))47 }48 pub fn errored(e: Error) -> Self {49 Self(Cc::new(RefCell::new(ThunkInner::Errored(e))))50 }51 pub fn result(res: Result<T, Error>) -> Self {52 match res {53 Ok(o) => Self::evaluated(o),54 Err(e) => Self::errored(e),55 }56 }57}5859impl<T> Thunk<T>60where61 T: Clone + Trace,62{63 pub fn force(&self) -> Result<()> {64 self.evaluate()?;65 Ok(())66 }6768 /// Evaluate thunk, or return cached value69 ///70 /// # Errors71 ///72 /// - Lazy value evaluation returned error73 /// - This method was called during inner value evaluation74 pub fn evaluate(&self) -> Result<T> {75 match &*self.0.borrow() {76 ThunkInner::Computed(v) => return Ok(v.clone()),77 ThunkInner::Errored(e) => return Err(e.clone()),78 ThunkInner::Pending => return Err(InfiniteRecursionDetected.into()),79 ThunkInner::Waiting(..) => (),80 };81 let ThunkInner::Waiting(value) = replace(&mut *self.0.borrow_mut(), ThunkInner::Pending)82 else {83 unreachable!();84 };85 let new_value = match value.0.get() {86 Ok(v) => v,87 Err(e) => {88 *self.0.borrow_mut() = ThunkInner::Errored(e.clone());89 return Err(e);90 }91 };92 *self.0.borrow_mut() = ThunkInner::Computed(new_value.clone());93 Ok(new_value)94 }95}9697pub trait ThunkMapper<Input>: Trace {98 type Output;99 fn map(self, from: Input) -> Result<Self::Output>;100}101impl<Input> Thunk<Input>102where103 Input: Trace + Clone,104{105 pub fn map<M>(self, mapper: M) -> Thunk<M::Output>106 where107 M: ThunkMapper<Input>,108 M::Output: Trace,109 {110 #[derive(Trace)]111 struct Mapped<Input: Trace, Mapper: Trace> {112 inner: Thunk<Input>,113 mapper: Mapper,114 }115 impl<Input, Mapper> ThunkValue for Mapped<Input, Mapper>116 where117 Input: Trace + Clone,118 Mapper: ThunkMapper<Input>,119 {120 type Output = Mapper::Output;121122 fn get(self: Box<Self>) -> Result<Self::Output> {123 let value = self.inner.evaluate()?;124 let mapped = self.mapper.map(value)?;125 Ok(mapped)126 }127 }128129 Thunk::new(Mapped::<Input, M> {130 inner: self,131 mapper,132 })133 }134}135136impl<T: Trace> From<Result<T>> for Thunk<T> {137 fn from(value: Result<T>) -> Self {138 match value {139 Ok(o) => Self::evaluated(o),140 Err(e) => Self::errored(e),141 }142 }143}144145impl<T: Trace + Default> Default for Thunk<T> {146 fn default() -> Self {147 Self::evaluated(T::default())148 }149}150151type CacheKey = (Option<WeakObjValue>, Option<WeakObjValue>);152153#[derive(Trace, Clone)]154pub struct CachedUnbound<I, T>155where156 I: Unbound<Bound = T>,157 T: Trace,158{159 cache: Cc<RefCell<GcHashMap<CacheKey, T>>>,160 value: I,161}162impl<I: Unbound<Bound = T>, T: Trace> CachedUnbound<I, T> {163 pub fn new(value: I) -> Self {164 Self {165 cache: Cc::new(RefCell::new(GcHashMap::new())),166 value,167 }168 }169}170impl<I: Unbound<Bound = T>, T: Clone + Trace> Unbound for CachedUnbound<I, T> {171 type Bound = T;172 fn bind(&self, sup: Option<ObjValue>, this: Option<ObjValue>) -> Result<T> {173 let cache_key = (174 sup.as_ref().map(|s| s.clone().downgrade()),175 this.as_ref().map(|t| t.clone().downgrade()),176 );177 {178 if let Some(t) = self.cache.borrow().get(&cache_key) {179 return Ok(t.clone());180 }181 }182 let bound = self.value.bind(sup, this)?;183184 {185 let mut cache = self.cache.borrow_mut();186 cache.insert(cache_key, bound.clone());187 }188189 Ok(bound)190 }191}192193impl<T: Debug + Trace> Debug for Thunk<T> {194 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {195 write!(f, "Lazy")196 }197}198impl<T: Trace> PartialEq for Thunk<T> {199 fn eq(&self, other: &Self) -> bool {200 Cc::ptr_eq(&self.0, &other.0)201 }202}203204/// Represents a Jsonnet value, which can be sliced or indexed (string or array).205#[allow(clippy::module_name_repetitions)]206pub enum IndexableVal {207 /// String.208 Str(IStr),209 /// Array.210 Arr(ArrValue),211}212impl IndexableVal {213 pub fn to_array(self) -> ArrValue {214 match self {215 IndexableVal::Str(s) => ArrValue::chars(s.chars()),216 IndexableVal::Arr(arr) => arr,217 }218 }219 /// Slice the value.220 ///221 /// # Implementation222 ///223 /// For strings, will create a copy of specified interval.224 ///225 /// For arrays, nothing will be copied on this call, instead [`ArrValue::Slice`] view will be returned.226 pub fn slice(227 self,228 index: Option<BoundedUsize<0, { i32::MAX as usize }>>,229 end: Option<BoundedUsize<0, { i32::MAX as usize }>>,230 step: Option<BoundedUsize<1, { i32::MAX as usize }>>,231 ) -> Result<Self> {232 match &self {233 IndexableVal::Str(s) => {234 let index = index.as_deref().copied().unwrap_or(0);235 let end = end.as_deref().copied().unwrap_or(usize::MAX);236 let step = step.as_deref().copied().unwrap_or(1);237238 if index >= end {239 return Ok(Self::Str("".into()));240 }241242 Ok(Self::Str(243 (s.chars()244 .skip(index)245 .take(end - index)246 .step_by(step)247 .collect::<String>())248 .into(),249 ))250 }251 IndexableVal::Arr(arr) => {252 let index = index.as_deref().copied().unwrap_or(0);253 let end = end.as_deref().copied().unwrap_or(usize::MAX).min(arr.len());254 let step = step.as_deref().copied().unwrap_or(1);255256 if index >= end {257 return Ok(Self::Arr(ArrValue::empty()));258 }259260 Ok(Self::Arr(261 arr.clone()262 .slice(Some(index), Some(end), Some(step))263 .expect("arguments checked"),264 ))265 }266 }267 }268}269270#[derive(Debug, Clone, Trace)]271pub enum StrValue {272 Flat(IStr),273 Tree(Rc<(StrValue, StrValue, usize)>),274}275impl StrValue {276 pub fn concat(a: StrValue, b: StrValue) -> Self {277 // TODO: benchmark for an optimal value, currently just a arbitrary choice278 const STRING_EXTEND_THRESHOLD: usize = 100;279280 if a.is_empty() {281 b282 } else if b.is_empty() {283 a284 } else if a.len() + b.len() < STRING_EXTEND_THRESHOLD {285 Self::Flat(format!("{a}{b}").into())286 } else {287 let len = a.len() + b.len();288 Self::Tree(Rc::new((a, b, len)))289 }290 }291 pub fn into_flat(self) -> IStr {292 #[cold]293 fn write_buf(s: &StrValue, out: &mut String) {294 match s {295 StrValue::Flat(f) => out.push_str(f),296 StrValue::Tree(t) => {297 write_buf(&t.0, out);298 write_buf(&t.1, out);299 }300 }301 }302 match self {303 StrValue::Flat(f) => f,304 StrValue::Tree(_) => {305 let mut buf = String::with_capacity(self.len());306 write_buf(&self, &mut buf);307 buf.into()308 }309 }310 }311 pub fn len(&self) -> usize {312 match self {313 StrValue::Flat(v) => v.len(),314 StrValue::Tree(t) => t.2,315 }316 }317 pub fn is_empty(&self) -> bool {318 match self {319 Self::Flat(v) => v.is_empty(),320 // Can't create non-flat empty string321 Self::Tree(_) => false,322 }323 }324}325impl From<&str> for StrValue {326 fn from(value: &str) -> Self {327 Self::Flat(value.into())328 }329}330impl From<String> for StrValue {331 fn from(value: String) -> Self {332 Self::Flat(value.into())333 }334}335impl From<IStr> for StrValue {336 fn from(value: IStr) -> Self {337 Self::Flat(value)338 }339}340impl Display for StrValue {341 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {342 match self {343 StrValue::Flat(v) => write!(f, "{v}"),344 StrValue::Tree(t) => {345 write!(f, "{}", t.0)?;346 write!(f, "{}", t.1)347 }348 }349 }350}351impl PartialEq for StrValue {352 fn eq(&self, other: &Self) -> bool {353 let a = self.clone().into_flat();354 let b = other.clone().into_flat();355 a == b356 }357}358impl Eq for StrValue {}359impl PartialOrd for StrValue {360 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {361 Some(self.cmp(other))362 }363}364impl Ord for StrValue {365 fn cmp(&self, other: &Self) -> std::cmp::Ordering {366 let a = self.clone().into_flat();367 let b = other.clone().into_flat();368 a.cmp(&b)369 }370}371372/// Represents any valid Jsonnet value.373#[derive(Debug, Clone, Trace, Default)]374pub enum Val {375 /// Represents a Jsonnet boolean.376 Bool(bool),377 /// Represents a Jsonnet null value.378 #[default]379 Null,380 /// Represents a Jsonnet string.381 Str(StrValue),382 /// Represents a Jsonnet number.383 /// Should be finite, and not NaN384 /// This restriction isn't enforced by enum, as enum field can't be marked as private385 Num(f64),386 /// Experimental bigint387 #[cfg(feature = "exp-bigint")]388 BigInt(#[trace(skip)] Box<num_bigint::BigInt>),389 /// Represents a Jsonnet array.390 Arr(ArrValue),391 /// Represents a Jsonnet object.392 Obj(ObjValue),393 /// Represents a Jsonnet function.394 Func(FuncVal),395}396397#[cfg(target_pointer_width = "64")]398static_assertions::assert_eq_size!(Val, [u8; 24]);399400impl From<IndexableVal> for Val {401 fn from(v: IndexableVal) -> Self {402 match v {403 IndexableVal::Str(s) => Self::Str(StrValue::Flat(s)),404 IndexableVal::Arr(a) => Self::Arr(a),405 }406 }407}408409impl Val {410 pub const fn as_bool(&self) -> Option<bool> {411 match self {412 Self::Bool(v) => Some(*v),413 _ => None,414 }415 }416 pub const fn as_null(&self) -> Option<()> {417 match self {418 Self::Null => Some(()),419 _ => None,420 }421 }422 pub fn as_str(&self) -> Option<IStr> {423 match self {424 Self::Str(s) => Some(s.clone().into_flat()),425 _ => None,426 }427 }428 pub const fn as_num(&self) -> Option<f64> {429 match self {430 Self::Num(n) => Some(*n),431 _ => None,432 }433 }434 pub fn as_arr(&self) -> Option<ArrValue> {435 match self {436 Self::Arr(a) => Some(a.clone()),437 _ => None,438 }439 }440 pub fn as_obj(&self) -> Option<ObjValue> {441 match self {442 Self::Obj(o) => Some(o.clone()),443 _ => None,444 }445 }446 pub fn as_func(&self) -> Option<FuncVal> {447 match self {448 Self::Func(f) => Some(f.clone()),449 _ => None,450 }451 }452453 /// Creates `Val::Num` after checking for numeric overflow.454 /// As numbers are `f64`, we can just check for their finity.455 pub fn new_checked_num(num: f64) -> Result<Self> {456 if num.is_finite() {457 Ok(Self::Num(num))458 } else {459 throw!("overflow")460 }461 }462463 pub const fn value_type(&self) -> ValType {464 match self {465 Self::Str(..) => ValType::Str,466 Self::Num(..) => ValType::Num,467 #[cfg(feature = "exp-bigint")]468 Self::BigInt(..) => ValType::BigInt,469 Self::Arr(..) => ValType::Arr,470 Self::Obj(..) => ValType::Obj,471 Self::Bool(_) => ValType::Bool,472 Self::Null => ValType::Null,473 Self::Func(..) => ValType::Func,474 }475 }476477 pub fn manifest(&self, format: impl ManifestFormat) -> Result<String> {478 fn manifest_dyn(val: &Val, manifest: &dyn ManifestFormat) -> Result<String> {479 manifest.manifest(val.clone())480 }481 manifest_dyn(self, &format)482 }483484 pub fn to_string(&self) -> Result<IStr> {485 Ok(match self {486 Self::Bool(true) => "true".into(),487 Self::Bool(false) => "false".into(),488 Self::Null => "null".into(),489 Self::Str(s) => s.clone().into_flat(),490 _ => self.manifest(ToStringFormat).map(IStr::from)?,491 })492 }493494 pub fn into_indexable(self) -> Result<IndexableVal> {495 Ok(match self {496 Val::Str(s) => IndexableVal::Str(s.into_flat()),497 Val::Arr(arr) => IndexableVal::Arr(arr),498 _ => throw!(ValueIsNotIndexable(self.value_type())),499 })500 }501}502503const fn is_function_like(val: &Val) -> bool {504 matches!(val, Val::Func(_))505}506507/// Native implementation of `std.primitiveEquals`508pub fn primitive_equals(val_a: &Val, val_b: &Val) -> Result<bool> {509 Ok(match (val_a, val_b) {510 (Val::Bool(a), Val::Bool(b)) => a == b,511 (Val::Null, Val::Null) => true,512 (Val::Str(a), Val::Str(b)) => a == b,513 (Val::Num(a), Val::Num(b)) => (a - b).abs() <= f64::EPSILON,514 #[cfg(feature = "exp-bigint")]515 (Val::BigInt(a), Val::BigInt(b)) => a == b,516 (Val::Arr(_), Val::Arr(_)) => {517 throw!("primitiveEquals operates on primitive types, got array")518 }519 (Val::Obj(_), Val::Obj(_)) => {520 throw!("primitiveEquals operates on primitive types, got object")521 }522 (a, b) if is_function_like(a) && is_function_like(b) => {523 throw!("cannot test equality of functions")524 }525 (_, _) => false,526 })527}528529/// Native implementation of `std.equals`530pub fn equals(val_a: &Val, val_b: &Val) -> Result<bool> {531 if val_a.value_type() != val_b.value_type() {532 return Ok(false);533 }534 match (val_a, val_b) {535 (Val::Arr(a), Val::Arr(b)) => {536 if ArrValue::ptr_eq(a, b) {537 return Ok(true);538 }539 if a.len() != b.len() {540 return Ok(false);541 }542 for (a, b) in a.iter().zip(b.iter()) {543 if !equals(&a?, &b?)? {544 return Ok(false);545 }546 }547 Ok(true)548 }549 (Val::Obj(a), Val::Obj(b)) => {550 if ObjValue::ptr_eq(a, b) {551 return Ok(true);552 }553 let fields = a.fields(554 #[cfg(feature = "exp-preserve-order")]555 false,556 );557 if fields558 != b.fields(559 #[cfg(feature = "exp-preserve-order")]560 false,561 ) {562 return Ok(false);563 }564 for field in fields {565 if !equals(566 &a.get(field.clone())?.expect("field exists"),567 &b.get(field)?.expect("field exists"),568 )? {569 return Ok(false);570 }571 }572 Ok(true)573 }574 (a, b) => Ok(primitive_equals(a, b)?),575 }576}1use std::{2 cell::RefCell,3 fmt::{self, Debug, Display},4 mem::replace,5 rc::Rc,6};78use jrsonnet_gcmodule::{Cc, Trace};9use jrsonnet_interner::IStr;10use jrsonnet_types::ValType;1112pub use crate::arr::{ArrValue, ArrayLike};13use crate::{14 bail,15 error::{Error, ErrorKind::*},16 function::FuncVal,17 gc::{GcHashMap, TraceBox},18 manifest::{ManifestFormat, ToStringFormat},19 tb,20 typed::BoundedUsize,21 ObjValue, Result, Unbound, WeakObjValue,22};2324pub trait ThunkValue: Trace {25 type Output;26 fn get(self: Box<Self>) -> Result<Self::Output>;27}2829#[derive(Trace)]30enum ThunkInner<T: Trace> {31 Computed(T),32 Errored(Error),33 Waiting(TraceBox<dyn ThunkValue<Output = T>>),34 Pending,35}3637/// Lazily evaluated value38#[allow(clippy::module_name_repetitions)]39#[derive(Clone, Trace)]40pub struct Thunk<T: Trace>(Cc<RefCell<ThunkInner<T>>>);4142impl<T: Trace> Thunk<T> {43 pub fn evaluated(val: T) -> Self {44 Self(Cc::new(RefCell::new(ThunkInner::Computed(val))))45 }46 pub fn new(f: impl ThunkValue<Output = T> + 'static) -> Self {47 Self(Cc::new(RefCell::new(ThunkInner::Waiting(tb!(f)))))48 }49 pub fn errored(e: Error) -> Self {50 Self(Cc::new(RefCell::new(ThunkInner::Errored(e))))51 }52 pub fn result(res: Result<T, Error>) -> Self {53 match res {54 Ok(o) => Self::evaluated(o),55 Err(e) => Self::errored(e),56 }57 }58}5960impl<T> Thunk<T>61where62 T: Clone + Trace,63{64 pub fn force(&self) -> Result<()> {65 self.evaluate()?;66 Ok(())67 }6869 /// Evaluate thunk, or return cached value70 ///71 /// # Errors72 ///73 /// - Lazy value evaluation returned error74 /// - This method was called during inner value evaluation75 pub fn evaluate(&self) -> Result<T> {76 match &*self.0.borrow() {77 ThunkInner::Computed(v) => return Ok(v.clone()),78 ThunkInner::Errored(e) => return Err(e.clone()),79 ThunkInner::Pending => return Err(InfiniteRecursionDetected.into()),80 ThunkInner::Waiting(..) => (),81 };82 let ThunkInner::Waiting(value) = replace(&mut *self.0.borrow_mut(), ThunkInner::Pending)83 else {84 unreachable!();85 };86 let new_value = match value.0.get() {87 Ok(v) => v,88 Err(e) => {89 *self.0.borrow_mut() = ThunkInner::Errored(e.clone());90 return Err(e);91 }92 };93 *self.0.borrow_mut() = ThunkInner::Computed(new_value.clone());94 Ok(new_value)95 }96}9798pub trait ThunkMapper<Input>: Trace {99 type Output;100 fn map(self, from: Input) -> Result<Self::Output>;101}102impl<Input> Thunk<Input>103where104 Input: Trace + Clone,105{106 pub fn map<M>(self, mapper: M) -> Thunk<M::Output>107 where108 M: ThunkMapper<Input>,109 M::Output: Trace,110 {111 #[derive(Trace)]112 struct Mapped<Input: Trace, Mapper: Trace> {113 inner: Thunk<Input>,114 mapper: Mapper,115 }116 impl<Input, Mapper> ThunkValue for Mapped<Input, Mapper>117 where118 Input: Trace + Clone,119 Mapper: ThunkMapper<Input>,120 {121 type Output = Mapper::Output;122123 fn get(self: Box<Self>) -> Result<Self::Output> {124 let value = self.inner.evaluate()?;125 let mapped = self.mapper.map(value)?;126 Ok(mapped)127 }128 }129130 Thunk::new(Mapped::<Input, M> {131 inner: self,132 mapper,133 })134 }135}136137impl<T: Trace> From<Result<T>> for Thunk<T> {138 fn from(value: Result<T>) -> Self {139 match value {140 Ok(o) => Self::evaluated(o),141 Err(e) => Self::errored(e),142 }143 }144}145146impl<T: Trace + Default> Default for Thunk<T> {147 fn default() -> Self {148 Self::evaluated(T::default())149 }150}151152type CacheKey = (Option<WeakObjValue>, Option<WeakObjValue>);153154#[derive(Trace, Clone)]155pub struct CachedUnbound<I, T>156where157 I: Unbound<Bound = T>,158 T: Trace,159{160 cache: Cc<RefCell<GcHashMap<CacheKey, T>>>,161 value: I,162}163impl<I: Unbound<Bound = T>, T: Trace> CachedUnbound<I, T> {164 pub fn new(value: I) -> Self {165 Self {166 cache: Cc::new(RefCell::new(GcHashMap::new())),167 value,168 }169 }170}171impl<I: Unbound<Bound = T>, T: Clone + Trace> Unbound for CachedUnbound<I, T> {172 type Bound = T;173 fn bind(&self, sup: Option<ObjValue>, this: Option<ObjValue>) -> Result<T> {174 let cache_key = (175 sup.as_ref().map(|s| s.clone().downgrade()),176 this.as_ref().map(|t| t.clone().downgrade()),177 );178 {179 if let Some(t) = self.cache.borrow().get(&cache_key) {180 return Ok(t.clone());181 }182 }183 let bound = self.value.bind(sup, this)?;184185 {186 let mut cache = self.cache.borrow_mut();187 cache.insert(cache_key, bound.clone());188 }189190 Ok(bound)191 }192}193194impl<T: Debug + Trace> Debug for Thunk<T> {195 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {196 write!(f, "Lazy")197 }198}199impl<T: Trace> PartialEq for Thunk<T> {200 fn eq(&self, other: &Self) -> bool {201 Cc::ptr_eq(&self.0, &other.0)202 }203}204205/// Represents a Jsonnet value, which can be sliced or indexed (string or array).206#[allow(clippy::module_name_repetitions)]207pub enum IndexableVal {208 /// String.209 Str(IStr),210 /// Array.211 Arr(ArrValue),212}213impl IndexableVal {214 pub fn to_array(self) -> ArrValue {215 match self {216 IndexableVal::Str(s) => ArrValue::chars(s.chars()),217 IndexableVal::Arr(arr) => arr,218 }219 }220 /// Slice the value.221 ///222 /// # Implementation223 ///224 /// For strings, will create a copy of specified interval.225 ///226 /// For arrays, nothing will be copied on this call, instead [`ArrValue::Slice`] view will be returned.227 pub fn slice(228 self,229 index: Option<BoundedUsize<0, { i32::MAX as usize }>>,230 end: Option<BoundedUsize<0, { i32::MAX as usize }>>,231 step: Option<BoundedUsize<1, { i32::MAX as usize }>>,232 ) -> Result<Self> {233 match &self {234 IndexableVal::Str(s) => {235 let index = index.as_deref().copied().unwrap_or(0);236 let end = end.as_deref().copied().unwrap_or(usize::MAX);237 let step = step.as_deref().copied().unwrap_or(1);238239 if index >= end {240 return Ok(Self::Str("".into()));241 }242243 Ok(Self::Str(244 (s.chars()245 .skip(index)246 .take(end - index)247 .step_by(step)248 .collect::<String>())249 .into(),250 ))251 }252 IndexableVal::Arr(arr) => {253 let index = index.as_deref().copied().unwrap_or(0);254 let end = end.as_deref().copied().unwrap_or(usize::MAX).min(arr.len());255 let step = step.as_deref().copied().unwrap_or(1);256257 if index >= end {258 return Ok(Self::Arr(ArrValue::empty()));259 }260261 Ok(Self::Arr(262 arr.clone()263 .slice(Some(index), Some(end), Some(step))264 .expect("arguments checked"),265 ))266 }267 }268 }269}270271#[derive(Debug, Clone, Trace)]272pub enum StrValue {273 Flat(IStr),274 Tree(Rc<(StrValue, StrValue, usize)>),275}276impl StrValue {277 pub fn concat(a: StrValue, b: StrValue) -> Self {278 // TODO: benchmark for an optimal value, currently just a arbitrary choice279 const STRING_EXTEND_THRESHOLD: usize = 100;280281 if a.is_empty() {282 b283 } else if b.is_empty() {284 a285 } else if a.len() + b.len() < STRING_EXTEND_THRESHOLD {286 Self::Flat(format!("{a}{b}").into())287 } else {288 let len = a.len() + b.len();289 Self::Tree(Rc::new((a, b, len)))290 }291 }292 pub fn into_flat(self) -> IStr {293 #[cold]294 fn write_buf(s: &StrValue, out: &mut String) {295 match s {296 StrValue::Flat(f) => out.push_str(f),297 StrValue::Tree(t) => {298 write_buf(&t.0, out);299 write_buf(&t.1, out);300 }301 }302 }303 match self {304 StrValue::Flat(f) => f,305 StrValue::Tree(_) => {306 let mut buf = String::with_capacity(self.len());307 write_buf(&self, &mut buf);308 buf.into()309 }310 }311 }312 pub fn len(&self) -> usize {313 match self {314 StrValue::Flat(v) => v.len(),315 StrValue::Tree(t) => t.2,316 }317 }318 pub fn is_empty(&self) -> bool {319 match self {320 Self::Flat(v) => v.is_empty(),321 // Can't create non-flat empty string322 Self::Tree(_) => false,323 }324 }325}326impl From<&str> for StrValue {327 fn from(value: &str) -> Self {328 Self::Flat(value.into())329 }330}331impl From<String> for StrValue {332 fn from(value: String) -> Self {333 Self::Flat(value.into())334 }335}336impl From<IStr> for StrValue {337 fn from(value: IStr) -> Self {338 Self::Flat(value)339 }340}341impl Display for StrValue {342 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {343 match self {344 StrValue::Flat(v) => write!(f, "{v}"),345 StrValue::Tree(t) => {346 write!(f, "{}", t.0)?;347 write!(f, "{}", t.1)348 }349 }350 }351}352impl PartialEq for StrValue {353 fn eq(&self, other: &Self) -> bool {354 let a = self.clone().into_flat();355 let b = other.clone().into_flat();356 a == b357 }358}359impl Eq for StrValue {}360impl PartialOrd for StrValue {361 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {362 Some(self.cmp(other))363 }364}365impl Ord for StrValue {366 fn cmp(&self, other: &Self) -> std::cmp::Ordering {367 let a = self.clone().into_flat();368 let b = other.clone().into_flat();369 a.cmp(&b)370 }371}372373/// Represents any valid Jsonnet value.374#[derive(Debug, Clone, Trace, Default)]375pub enum Val {376 /// Represents a Jsonnet boolean.377 Bool(bool),378 /// Represents a Jsonnet null value.379 #[default]380 Null,381 /// Represents a Jsonnet string.382 Str(StrValue),383 /// Represents a Jsonnet number.384 /// Should be finite, and not NaN385 /// This restriction isn't enforced by enum, as enum field can't be marked as private386 Num(f64),387 /// Experimental bigint388 #[cfg(feature = "exp-bigint")]389 BigInt(#[trace(skip)] Box<num_bigint::BigInt>),390 /// Represents a Jsonnet array.391 Arr(ArrValue),392 /// Represents a Jsonnet object.393 Obj(ObjValue),394 /// Represents a Jsonnet function.395 Func(FuncVal),396}397398#[cfg(target_pointer_width = "64")]399static_assertions::assert_eq_size!(Val, [u8; 24]);400401impl From<IndexableVal> for Val {402 fn from(v: IndexableVal) -> Self {403 match v {404 IndexableVal::Str(s) => Self::Str(StrValue::Flat(s)),405 IndexableVal::Arr(a) => Self::Arr(a),406 }407 }408}409410impl Val {411 pub const fn as_bool(&self) -> Option<bool> {412 match self {413 Self::Bool(v) => Some(*v),414 _ => None,415 }416 }417 pub const fn as_null(&self) -> Option<()> {418 match self {419 Self::Null => Some(()),420 _ => None,421 }422 }423 pub fn as_str(&self) -> Option<IStr> {424 match self {425 Self::Str(s) => Some(s.clone().into_flat()),426 _ => None,427 }428 }429 pub const fn as_num(&self) -> Option<f64> {430 match self {431 Self::Num(n) => Some(*n),432 _ => None,433 }434 }435 pub fn as_arr(&self) -> Option<ArrValue> {436 match self {437 Self::Arr(a) => Some(a.clone()),438 _ => None,439 }440 }441 pub fn as_obj(&self) -> Option<ObjValue> {442 match self {443 Self::Obj(o) => Some(o.clone()),444 _ => None,445 }446 }447 pub fn as_func(&self) -> Option<FuncVal> {448 match self {449 Self::Func(f) => Some(f.clone()),450 _ => None,451 }452 }453454 /// Creates `Val::Num` after checking for numeric overflow.455 /// As numbers are `f64`, we can just check for their finity.456 pub fn new_checked_num(num: f64) -> Result<Self> {457 if num.is_finite() {458 Ok(Self::Num(num))459 } else {460 bail!("overflow")461 }462 }463464 pub const fn value_type(&self) -> ValType {465 match self {466 Self::Str(..) => ValType::Str,467 Self::Num(..) => ValType::Num,468 #[cfg(feature = "exp-bigint")]469 Self::BigInt(..) => ValType::BigInt,470 Self::Arr(..) => ValType::Arr,471 Self::Obj(..) => ValType::Obj,472 Self::Bool(_) => ValType::Bool,473 Self::Null => ValType::Null,474 Self::Func(..) => ValType::Func,475 }476 }477478 pub fn manifest(&self, format: impl ManifestFormat) -> Result<String> {479 fn manifest_dyn(val: &Val, manifest: &dyn ManifestFormat) -> Result<String> {480 manifest.manifest(val.clone())481 }482 manifest_dyn(self, &format)483 }484485 pub fn to_string(&self) -> Result<IStr> {486 Ok(match self {487 Self::Bool(true) => "true".into(),488 Self::Bool(false) => "false".into(),489 Self::Null => "null".into(),490 Self::Str(s) => s.clone().into_flat(),491 _ => self.manifest(ToStringFormat).map(IStr::from)?,492 })493 }494495 pub fn into_indexable(self) -> Result<IndexableVal> {496 Ok(match self {497 Val::Str(s) => IndexableVal::Str(s.into_flat()),498 Val::Arr(arr) => IndexableVal::Arr(arr),499 _ => bail!(ValueIsNotIndexable(self.value_type())),500 })501 }502}503504const fn is_function_like(val: &Val) -> bool {505 matches!(val, Val::Func(_))506}507508/// Native implementation of `std.primitiveEquals`509pub fn primitive_equals(val_a: &Val, val_b: &Val) -> Result<bool> {510 Ok(match (val_a, val_b) {511 (Val::Bool(a), Val::Bool(b)) => a == b,512 (Val::Null, Val::Null) => true,513 (Val::Str(a), Val::Str(b)) => a == b,514 (Val::Num(a), Val::Num(b)) => (a - b).abs() <= f64::EPSILON,515 #[cfg(feature = "exp-bigint")]516 (Val::BigInt(a), Val::BigInt(b)) => a == b,517 (Val::Arr(_), Val::Arr(_)) => {518 bail!("primitiveEquals operates on primitive types, got array")519 }520 (Val::Obj(_), Val::Obj(_)) => {521 bail!("primitiveEquals operates on primitive types, got object")522 }523 (a, b) if is_function_like(a) && is_function_like(b) => {524 bail!("cannot test equality of functions")525 }526 (_, _) => false,527 })528}529530/// Native implementation of `std.equals`531pub fn equals(val_a: &Val, val_b: &Val) -> Result<bool> {532 if val_a.value_type() != val_b.value_type() {533 return Ok(false);534 }535 match (val_a, val_b) {536 (Val::Arr(a), Val::Arr(b)) => {537 if ArrValue::ptr_eq(a, b) {538 return Ok(true);539 }540 if a.len() != b.len() {541 return Ok(false);542 }543 for (a, b) in a.iter().zip(b.iter()) {544 if !equals(&a?, &b?)? {545 return Ok(false);546 }547 }548 Ok(true)549 }550 (Val::Obj(a), Val::Obj(b)) => {551 if ObjValue::ptr_eq(a, b) {552 return Ok(true);553 }554 let fields = a.fields(555 #[cfg(feature = "exp-preserve-order")]556 false,557 );558 if fields559 != b.fields(560 #[cfg(feature = "exp-preserve-order")]561 false,562 ) {563 return Ok(false);564 }565 for field in fields {566 if !equals(567 &a.get(field.clone())?.expect("field exists"),568 &b.get(field)?.expect("field exists"),569 )? {570 return Ok(false);571 }572 }573 Ok(true)574 }575 (a, b) => Ok(primitive_equals(a, b)?),576 }577}crates/jrsonnet-macros/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-macros/src/lib.rs
+++ b/crates/jrsonnet-macros/src/lib.rs
@@ -356,7 +356,7 @@
use ::jrsonnet_evaluator::{
State, Val,
function::{builtin::{Builtin, StaticBuiltin, BuiltinParam, ParamName}, CallLocation, ArgsLike, parse::parse_builtin_call},
- error::Result, Context, typed::Typed,
+ Result, Context, typed::Typed,
parser::ExprLocation,
};
const PARAMS: &'static [BuiltinParam] = &[
crates/jrsonnet-stdlib/src/arrays.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/arrays.rs
+++ b/crates/jrsonnet-stdlib/src/arrays.rs
@@ -1,19 +1,19 @@
#![allow(non_snake_case)]
use jrsonnet_evaluator::{
- error::{ErrorKind::RuntimeError, Result},
+ bail,
function::{builtin, FuncVal},
- throw,
+ runtime_error,
typed::{BoundedI32, BoundedUsize, Either2, NativeFn, Typed},
- val::{equals, ArrValue, IndexableVal, StrValue},
- Either, IStr, Thunk, Val,
+ val::{equals, ArrValue, IndexableVal},
+ Either, IStr, Result, Thunk, Val,
};
pub(crate) fn eval_on_empty(on_empty: Option<Thunk<Val>>) -> Result<Val> {
if let Some(on_empty) = on_empty {
on_empty.evaluate()
} else {
- throw!("expected non-empty array")
+ bail!("expected non-empty array")
}
}
@@ -39,7 +39,7 @@
Either2::A(s) => Val::Str(StrValue::Flat(s.repeat(count).into())),
Either2::B(arr) => Val::Arr(
ArrValue::repeated(arr, count)
- .ok_or_else(|| RuntimeError("repeated length overflow".into()))?,
+ .ok_or_else(|| runtime_error!("repeated length overflow"))?,
),
})
}
@@ -73,7 +73,7 @@
match func(Either2::A(c.to_string()))? {
Val::Str(o) => write!(out, "{o}").unwrap(),
Val::Null => continue,
- _ => throw!("in std.join all items should be strings"),
+ _ => bail!("in std.join all items should be strings"),
};
}
Ok(IndexableVal::Str(out.into()))
@@ -89,7 +89,7 @@
}
}
Val::Null => continue,
- _ => throw!("in std.join all items should be arrays"),
+ _ => bail!("in std.join all items should be arrays"),
};
}
Ok(IndexableVal::Arr(out.into()))
@@ -154,7 +154,7 @@
} else if matches!(item, Val::Null) {
continue;
} else {
- throw!("in std.join all items should be arrays");
+ bail!("in std.join all items should be arrays");
}
}
@@ -175,7 +175,7 @@
} else if matches!(item, Val::Null) {
continue;
} else {
- throw!("in std.join all items should be strings");
+ bail!("in std.join all items should be strings");
}
}
crates/jrsonnet-stdlib/src/compat.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/compat.rs
+++ b/crates/jrsonnet-stdlib/src/compat.rs
@@ -1,6 +1,6 @@
use std::cmp::Ordering;
-use jrsonnet_evaluator::{error::Result, function::builtin, operator::evaluate_compare_op, Val};
+use jrsonnet_evaluator::{function::builtin, operator::evaluate_compare_op, Result, Val};
#[builtin]
#[allow(non_snake_case)]
crates/jrsonnet-stdlib/src/encoding.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/encoding.rs
+++ b/crates/jrsonnet-stdlib/src/encoding.rs
@@ -1,9 +1,9 @@
use base64::{engine::general_purpose::STANDARD, Engine};
use jrsonnet_evaluator::{
- error::{ErrorKind::RuntimeError, Result},
function::builtin,
+ runtime_error,
typed::{Either, Either2},
- IBytes, IStr,
+ IBytes, IStr, Result,
};
#[builtin]
@@ -13,9 +13,7 @@
#[builtin]
pub fn builtin_decode_utf8(arr: IBytes) -> Result<IStr> {
- Ok(arr
- .cast_str()
- .ok_or_else(|| RuntimeError("bad utf8".into()))?)
+ arr.cast_str().ok_or_else(|| runtime_error!("bad utf8"))
}
#[builtin]
@@ -31,7 +29,7 @@
pub fn builtin_base64_decode_bytes(str: IStr) -> Result<IBytes> {
Ok(STANDARD
.decode(str.as_bytes())
- .map_err(|e| RuntimeError(format!("invalid base64: {e}").into()))?
+ .map_err(|e| runtime_error!("invalid base64: {e}"))?
.as_slice()
.into())
}
@@ -40,6 +38,6 @@
pub fn builtin_base64_decode(str: IStr) -> Result<String> {
let bytes = STANDARD
.decode(str.as_bytes())
- .map_err(|e| RuntimeError(format!("invalid base64: {e}").into()))?;
- Ok(String::from_utf8(bytes).map_err(|_| RuntimeError("bad utf8".into()))?)
+ .map_err(|e| runtime_error!("invalid base64: {e}"))?;
+ Ok(String::from_utf8(bytes).map_err(|_| runtime_error!("bad utf8"))?)
}
crates/jrsonnet-stdlib/src/manifest/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/manifest/mod.rs
+++ b/crates/jrsonnet-stdlib/src/manifest/mod.rs
@@ -2,10 +2,9 @@
mod yaml;
use jrsonnet_evaluator::{
- error::Result,
function::builtin,
manifest::{escape_string_json, JsonFormat},
- IStr, ObjValue, Val,
+ IStr, ObjValue, Result, Val,
};
pub use toml::TomlFormat;
pub use yaml::YamlFormat;
crates/jrsonnet-stdlib/src/manifest/toml.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/manifest/toml.rs
+++ b/crates/jrsonnet-stdlib/src/manifest/toml.rs
@@ -1,8 +1,8 @@
use std::borrow::Cow;
use jrsonnet_evaluator::{
+ bail,
manifest::{escape_string_json_buf, ManifestFormat},
- throw,
val::ArrValue,
IStr, ObjValue, Result, Val,
};
@@ -157,10 +157,10 @@
buf.push_str(" }");
}
Val::Null => {
- throw!("tried to manifest null")
+ bail!("tried to manifest null")
}
Val::Func(_) => {
- throw!("tried to manifest function")
+ bail!("tried to manifest function")
}
}
Ok(())
@@ -290,7 +290,7 @@
Val::Obj(obj) => {
manifest_table_internal(&obj, &mut Vec::new(), buf, &mut String::new(), self)
}
- _ => throw!("toml body should be object"),
+ _ => bail!("toml body should be object"),
}
}
}
crates/jrsonnet-stdlib/src/manifest/yaml.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/manifest/yaml.rs
+++ b/crates/jrsonnet-stdlib/src/manifest/yaml.rs
@@ -1,8 +1,9 @@
use std::{borrow::Cow, fmt::Write};
use jrsonnet_evaluator::{
+ bail,
manifest::{escape_string_json_buf, ManifestFormat},
- throw, Result, Val,
+ Result, Val,
};
pub struct YamlFormat<'s> {
@@ -219,7 +220,7 @@
}
}
}
- Val::Func(_) => throw!("tried to manifest function"),
+ Val::Func(_) => bail!("tried to manifest function"),
}
Ok(())
}
crates/jrsonnet-stdlib/src/misc.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/misc.rs
+++ b/crates/jrsonnet-stdlib/src/misc.rs
@@ -1,10 +1,10 @@
use std::{cell::RefCell, rc::Rc};
use jrsonnet_evaluator::{
+ bail,
error::{ErrorKind::*, Result},
function::{builtin, ArgLike, CallLocation, FuncVal},
manifest::JsonFormat,
- throw,
typed::{Either2, Either4},
val::{equals, ArrValue},
Context, Either, IStr, ObjValue, Thunk, Val,
@@ -103,7 +103,7 @@
true
}
}
- _ => throw!("both arguments should be of the same type"),
+ _ => bail!("both arguments should be of the same type"),
})
}
@@ -129,6 +129,6 @@
true
}
}
- _ => throw!("both arguments should be of the same type"),
+ _ => bail!("both arguments should be of the same type"),
})
}
crates/jrsonnet-stdlib/src/operator.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/operator.rs
+++ b/crates/jrsonnet-stdlib/src/operator.rs
@@ -2,13 +2,12 @@
//! However, in our case we instead implement them in native, and implement native functions on top of core for backwards compatibility
use jrsonnet_evaluator::{
- error::Result,
function::builtin,
operator::evaluate_mod_op,
stdlib::std_format,
typed::{Either, Either2},
- val::{equals, primitive_equals, StrValue},
- IStr, Val,
+ val::{equals, primitive_equals},
+ IStr, Result, Val,
};
#[builtin]
crates/jrsonnet-stdlib/src/parse.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/parse.rs
+++ b/crates/jrsonnet-stdlib/src/parse.rs
@@ -1,14 +1,10 @@
-use jrsonnet_evaluator::{
- error::{ErrorKind::RuntimeError, Result},
- function::builtin,
- IStr, Val,
-};
+use jrsonnet_evaluator::{function::builtin, runtime_error, IStr, Result, Val};
use serde::Deserialize;
#[builtin]
pub fn builtin_parse_json(str: IStr) -> Result<Val> {
- let value: Val = serde_json::from_str(&str)
- .map_err(|e| RuntimeError(format!("failed to parse json: {e}").into()))?;
+ let value: Val =
+ serde_json::from_str(&str).map_err(|e| runtime_error!("failed to parse json: {e}"))?;
Ok(value)
}
@@ -21,8 +17,8 @@
);
let mut out = vec![];
for item in value {
- let val = Val::deserialize(item)
- .map_err(|e| RuntimeError(format!("failed to parse yaml: {e}").into()))?;
+ let val =
+ Val::deserialize(item).map_err(|e| runtime_error!("failed to parse yaml: {e}"))?;
out.push(val);
}
Ok(if out.is_empty() {
crates/jrsonnet-stdlib/src/sort.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/sort.rs
+++ b/crates/jrsonnet-stdlib/src/sort.rs
@@ -3,12 +3,11 @@
use std::cmp::Ordering;
use jrsonnet_evaluator::{
- error::Result,
+ bail,
function::{builtin, FuncVal},
operator::evaluate_compare_op,
- throw,
val::{equals, ArrValue},
- Thunk, Val,
+ Result, Thunk, Val,
};
use jrsonnet_parser::BinaryOpType;
@@ -44,7 +43,7 @@
(Val::Num(_), SortKeyType::Unknown) => sort_type = SortKeyType::Number,
(Val::Str(_), SortKeyType::String) | (Val::Num(_), SortKeyType::Number) => {}
(Val::Str(_) | Val::Num(_), _) => {
- throw!("sort elements should have the same types")
+ bail!("sort elements should have the same types")
}
_ => {}
}
crates/jrsonnet-stdlib/src/strings.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/strings.rs
+++ b/crates/jrsonnet-stdlib/src/strings.rs
@@ -1,7 +1,7 @@
use jrsonnet_evaluator::{
+ bail,
error::{ErrorKind::*, Result},
function::builtin,
- throw,
typed::{Either2, M1},
val::{ArrValue, StrValue},
Either, IStr, Val,
@@ -91,13 +91,13 @@
pub fn builtin_parse_int(str: IStr) -> Result<f64> {
if let Some(raw) = str.strip_prefix('-') {
if raw.is_empty() {
- throw!("integer only consists of a minus")
+ bail!("integer only consists of a minus")
}
parse_nat::<10>(raw).map(|value| -value)
} else {
if str.is_empty() {
- throw!("empty integer")
+ bail!("empty integer")
}
parse_nat::<10>(str.as_str())
@@ -107,7 +107,7 @@
#[builtin]
pub fn builtin_parse_octal(str: IStr) -> Result<f64> {
if str.is_empty() {
- throw!("empty octal integer");
+ bail!("empty octal integer");
}
parse_nat::<8>(str.as_str())
@@ -116,7 +116,7 @@
#[builtin]
pub fn builtin_parse_hex(str: IStr) -> Result<f64> {
if str.is_empty() {
- throw!("empty hexadecimal integer");
+ bail!("empty hexadecimal integer");
}
parse_nat::<16>(str.as_str())
@@ -156,7 +156,7 @@
if digit < BASE {
Ok(base * aggregate + digit as f64)
} else {
- throw!("{raw:?} is not a base {BASE} integer",);
+ bail!("{raw:?} is not a base {BASE} integer");
}
})
}
@@ -164,13 +164,14 @@
#[cfg(feature = "exp-bigint")]
#[builtin]
pub fn builtin_bigint(v: Either![f64, IStr]) -> Result<Val> {
+ use jrsonnet_evaluator::runtime_error;
use Either2::*;
Ok(match v {
A(a) => Val::BigInt(Box::new((a as i64).into())),
B(b) => Val::BigInt(Box::new(
b.as_str()
.parse()
- .map_err(|e| RuntimeError(format!("bad bigint: {e}").into()))?,
+ .map_err(|e| runtime_error!("bad bigint: {e}"))?,
)),
})
}
tests/tests/as_native.rsdiffbeforeafterboth--- a/tests/tests/as_native.rs
+++ b/tests/tests/as_native.rs
@@ -1,4 +1,4 @@
-use jrsonnet_evaluator::{error::Result, State};
+use jrsonnet_evaluator::{Result, State};
use jrsonnet_stdlib::StateExt;
mod common;
tests/tests/builtin.rsdiffbeforeafterboth--- a/tests/tests/builtin.rs
+++ b/tests/tests/builtin.rs
@@ -1,10 +1,9 @@
mod common;
use jrsonnet_evaluator::{
- error::Result,
function::{builtin, builtin::Builtin, CallLocation, FuncVal},
typed::Typed,
- ContextBuilder, State, Thunk, Val,
+ ContextBuilder, Result, State, Thunk, Val,
};
use jrsonnet_stdlib::StateExt;
tests/tests/common.rsdiffbeforeafterboth--- a/tests/tests/common.rs
+++ b/tests/tests/common.rs
@@ -1,7 +1,7 @@
use jrsonnet_evaluator::{
- error::Result,
+ bail,
function::{builtin, FuncVal},
- throw, ObjValueBuilder, State, Thunk, Val,
+ ObjValueBuilder, Result, State, Thunk, Val,
};
#[macro_export]
@@ -10,7 +10,7 @@
let a = &$a;
let b = &$b;
if a != b {
- ::jrsonnet_evaluator::throw!("assertion failed: a != b\na={:#?}\nb={:#?}", a, b)
+ ::jrsonnet_evaluator::bail!("assertion failed: a != b\na={a:#?}\nb={b:#?}")
}
}};
}
@@ -19,7 +19,7 @@
macro_rules! ensure {
($v:expr $(,)?) => {
if !$v {
- ::jrsonnet_evaluator::throw!("assertion failed: {}", stringify!($v))
+ ::jrsonnet_evaluator::bail!("assertion failed: {}", stringify!($v))
}
};
}
@@ -29,7 +29,7 @@
($a:expr, $b:expr) => {{
if !::jrsonnet_evaluator::val::equals(&$a.clone(), &$b.clone())? {
use ::jrsonnet_evaluator::manifest::JsonFormat;
- ::jrsonnet_evaluator::throw!(
+ ::jrsonnet_evaluator::bail!(
"assertion failed: a != b\na={:#?}\nb={:#?}",
$a.manifest(JsonFormat::default())?,
$b.manifest(JsonFormat::default())?,
@@ -42,7 +42,7 @@
fn assert_throw(lazy: Thunk<Val>, message: String) -> Result<bool> {
match lazy.evaluate() {
Ok(_) => {
- throw!("expected argument to throw on evaluation, but it returned instead")
+ bail!("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,8 +1,7 @@
use jrsonnet_evaluator::{
- error::Result,
- throw,
+ bail,
trace::{CompactFormat, TraceFormat},
- State, Val,
+ Result, State, Val,
};
use jrsonnet_stdlib::StateExt;
@@ -29,14 +28,14 @@
{
let Err(e) = s.evaluate_snippet("snip".to_owned(), "assert 1 == 2: 'fail'; null") else {
- throw!("assertion should fail");
+ bail!("assertion should fail");
};
let e = trace_format.format(&e).unwrap();
ensure!(e.starts_with("assert failed: fail\n"));
}
{
let Err(e) = s.evaluate_snippet("snip".to_owned(), "std.assertEqual(1, 2)") else {
- throw!("assertion should fail")
+ bail!("assertion should fail")
};
let e = trace_format.format(&e).unwrap();
ensure!(e.starts_with("runtime error: Assertion failed. 1 != 2"))
tests/tests/typed_obj.rsdiffbeforeafterboth--- a/tests/tests/typed_obj.rs
+++ b/tests/tests/typed_obj.rs
@@ -2,7 +2,7 @@
use std::fmt::Debug;
-use jrsonnet_evaluator::{error::Result, typed::Typed, State};
+use jrsonnet_evaluator::{typed::Typed, Result, State};
use jrsonnet_stdlib::StateExt;
#[derive(Clone, Typed, PartialEq, Debug)]