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.rsdiffbeforeafterboth1use std::{collections::BTreeMap, marker::PhantomData, ops::Deref};23use jrsonnet_gcmodule::{Cc, Trace};4use jrsonnet_interner::{IBytes, IStr};5pub use jrsonnet_macros::Typed;6use jrsonnet_types::{ComplexValType, ValType};78use crate::{9 arr::{ArrValue, BytesArray},10 error::Result,11 function::{native::NativeDesc, FuncDesc, FuncVal},12 throw,13 typed::CheckType,14 val::{IndexableVal, StrValue, ThunkMapper},15 ObjValue, ObjValueBuilder, Thunk, Val,16};1718#[derive(Trace)]19struct FromUntyped<K: Trace>(PhantomData<fn() -> K>);20impl<K> ThunkMapper<Val> for FromUntyped<K>21where22 K: Typed + Trace,23{24 type Output = K;2526 fn map(self, from: Val) -> Result<Self::Output> {27 K::from_untyped(from)28 }29}30impl<K: Trace> Default for FromUntyped<K> {31 fn default() -> Self {32 Self(PhantomData)33 }34}3536pub trait TypedObj: Typed {37 fn serialize(self, out: &mut ObjValueBuilder) -> Result<()>;38 fn parse(obj: &ObjValue) -> Result<Self>;39 fn into_object(self) -> Result<ObjValue> {40 let mut builder = ObjValueBuilder::new();41 self.serialize(&mut builder)?;42 Ok(builder.build())43 }44}4546pub trait Typed: Sized {47 const TYPE: &'static ComplexValType;48 fn into_untyped(typed: Self) -> Result<Val>;49 fn into_lazy_untyped(typed: Self) -> Thunk<Val> {50 Thunk::from(Self::into_untyped(typed))51 }52 fn from_untyped(untyped: Val) -> Result<Self>;53 fn from_lazy_untyped(lazy: Thunk<Val>) -> Result<Self> {54 Self::from_untyped(lazy.evaluate()?)55 }5657 // Whatever caller should use `into_lazy_untyped` instead of `into_untyped`58 fn provides_lazy() -> bool {59 false60 }6162 // Whatever caller should use `from_lazy_untyped` instead of `from_untyped` when possible63 fn wants_lazy() -> bool {64 false65 }6667 /// Hack to make builtins be able to return non-result values, and make macros able to convert those values to result68 /// This method returns identity in impl Typed for Result, and should not be overriden69 #[doc(hidden)]70 fn into_result(typed: Self) -> Result<Val> {71 let value = Self::into_untyped(typed)?;72 Ok(value)73 }74}7576impl<T> Typed for Thunk<T>77where78 T: Typed + Trace + Clone,79{80 const TYPE: &'static ComplexValType = &ComplexValType::Lazy(T::TYPE);8182 fn into_untyped(typed: Self) -> Result<Val> {83 T::into_untyped(typed.evaluate()?)84 }8586 fn from_untyped(untyped: Val) -> Result<Self> {87 Self::from_lazy_untyped(Thunk::evaluated(untyped))88 }8990 fn provides_lazy() -> bool {91 true92 }9394 fn into_lazy_untyped(inner: Self) -> Thunk<Val> {95 #[derive(Trace)]96 struct IntoUntyped<K: Trace>(PhantomData<fn() -> K>);97 impl<K> ThunkMapper<K> for IntoUntyped<K>98 where99 K: Typed + Trace,100 {101 type Output = Val;102103 fn map(self, from: K) -> Result<Self::Output> {104 K::into_untyped(from)105 }106 }107 impl<K: Trace> Default for IntoUntyped<K> {108 fn default() -> Self {109 Self(PhantomData)110 }111 }112 inner.map(<IntoUntyped<T>>::default())113 }114115 fn wants_lazy() -> bool {116 true117 }118119 fn from_lazy_untyped(inner: Thunk<Val>) -> Result<Self> {120 Ok(inner.map(<FromUntyped<T>>::default()))121 }122}123124const MAX_SAFE_INTEGER: f64 = ((1u64 << (f64::MANTISSA_DIGITS + 1)) - 1) as f64;125126macro_rules! impl_int {127 ($($ty:ty)*) => {$(128 impl Typed for $ty {129 const TYPE: &'static ComplexValType =130 &ComplexValType::BoundedNumber(Some(Self::MIN as f64), Some(Self::MAX as f64));131 fn from_untyped(value: Val) -> Result<Self> {132 <Self as Typed>::TYPE.check(&value)?;133 match value {134 Val::Num(n) => {135 #[allow(clippy::float_cmp)]136 if n.trunc() != n {137 throw!(138 "cannot convert number with fractional part to {}",139 stringify!($ty)140 )141 }142 Ok(n as Self)143 }144 _ => unreachable!(),145 }146 }147 fn into_untyped(value: Self) -> Result<Val> {148 Ok(Val::Num(value as f64))149 }150 }151 )*};152}153154impl_int!(i8 u8 i16 u16 i32 u32);155156macro_rules! impl_bounded_int {157 ($($name:ident = $ty:ty)*) => {$(158 #[derive(Clone, Copy)]159 pub struct $name<const MIN: $ty, const MAX: $ty>($ty);160 impl<const MIN: $ty, const MAX: $ty> $name<MIN, MAX> {161 pub const fn new(value: $ty) -> Option<$name<MIN, MAX>> {162 if value >= MIN && value <= MAX {163 Some(Self(value))164 } else {165 None166 }167 }168 pub const fn value(self) -> $ty {169 self.0170 }171 }172 impl<const MIN: $ty, const MAX: $ty> Deref for $name<MIN, MAX> {173 type Target = $ty;174 fn deref(&self) -> &Self::Target {175 &self.0176 }177 }178179 impl<const MIN: $ty, const MAX: $ty> Typed for $name<MIN, MAX> {180 const TYPE: &'static ComplexValType =181 &ComplexValType::BoundedNumber(182 Some(MIN as f64),183 Some(MAX as f64),184 );185186 fn from_untyped(value: Val) -> Result<Self> {187 <Self as Typed>::TYPE.check(&value)?;188 match value {189 Val::Num(n) => {190 #[allow(clippy::float_cmp)]191 if n.trunc() != n {192 throw!(193 "cannot convert number with fractional part to {}",194 stringify!($ty)195 )196 }197 Ok(Self(n as $ty))198 }199 _ => unreachable!(),200 }201 }202203 fn into_untyped(value: Self) -> Result<Val> {204 Ok(Val::Num(value.0 as f64))205 }206 }207 )*};208}209210impl_bounded_int!(211 BoundedI8 = i8212 BoundedI16 = i16213 BoundedI32 = i32214 BoundedI64 = i64215 BoundedUsize = usize216);217218impl Typed for f64 {219 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Num);220221 fn into_untyped(value: Self) -> Result<Val> {222 Ok(Val::Num(value))223 }224225 fn from_untyped(value: Val) -> Result<Self> {226 <Self as Typed>::TYPE.check(&value)?;227 match value {228 Val::Num(n) => Ok(n),229 _ => unreachable!(),230 }231 }232}233234pub struct PositiveF64(pub f64);235impl Typed for PositiveF64 {236 const TYPE: &'static ComplexValType = &ComplexValType::BoundedNumber(Some(0.0), None);237238 fn into_untyped(value: Self) -> Result<Val> {239 Ok(Val::Num(value.0))240 }241242 fn from_untyped(value: Val) -> Result<Self> {243 <Self as Typed>::TYPE.check(&value)?;244 match value {245 Val::Num(n) => Ok(Self(n)),246 _ => unreachable!(),247 }248 }249}250impl Typed for usize {251 const TYPE: &'static ComplexValType =252 &ComplexValType::BoundedNumber(Some(0.0), Some(MAX_SAFE_INTEGER));253254 fn into_untyped(value: Self) -> Result<Val> {255 if value > MAX_SAFE_INTEGER as Self {256 throw!("number is too large")257 }258 Ok(Val::Num(value as f64))259 }260261 fn from_untyped(value: Val) -> Result<Self> {262 <Self as Typed>::TYPE.check(&value)?;263 match value {264 Val::Num(n) => {265 #[allow(clippy::float_cmp)]266 if n.trunc() != n {267 throw!("cannot convert number with fractional part to usize")268 }269 Ok(n as Self)270 }271 _ => unreachable!(),272 }273 }274}275276impl Typed for IStr {277 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Str);278279 fn into_untyped(value: Self) -> Result<Val> {280 Ok(Val::Str(StrValue::Flat(value)))281 }282283 fn from_untyped(value: Val) -> Result<Self> {284 <Self as Typed>::TYPE.check(&value)?;285 match value {286 Val::Str(s) => Ok(s.into_flat()),287 _ => unreachable!(),288 }289 }290}291292impl Typed for String {293 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Str);294295 fn into_untyped(value: Self) -> Result<Val> {296 Ok(Val::Str(StrValue::Flat(value.into())))297 }298299 fn from_untyped(value: Val) -> Result<Self> {300 <Self as Typed>::TYPE.check(&value)?;301 match value {302 Val::Str(s) => Ok(s.to_string()),303 _ => unreachable!(),304 }305 }306}307308impl Typed for char {309 const TYPE: &'static ComplexValType = &ComplexValType::Char;310311 fn into_untyped(value: Self) -> Result<Val> {312 Ok(Val::Str(StrValue::Flat(value.to_string().into())))313 }314315 fn from_untyped(value: Val) -> Result<Self> {316 <Self as Typed>::TYPE.check(&value)?;317 match value {318 Val::Str(s) => Ok(s.into_flat().chars().next().unwrap()),319 _ => unreachable!(),320 }321 }322}323324impl<T> Typed for Vec<T>325where326 T: Typed,327{328 const TYPE: &'static ComplexValType = &ComplexValType::ArrayRef(T::TYPE);329330 fn into_untyped(value: Self) -> Result<Val> {331 Ok(Val::Arr(332 value333 .into_iter()334 .map(T::into_untyped)335 .collect::<Result<ArrValue>>()?,336 ))337 }338339 fn from_untyped(value: Val) -> Result<Self> {340 let Val::Arr(a) = value else {341 <Self as Typed>::TYPE.check(&value)?;342 unreachable!("typecheck should fail")343 };344 a.iter()345 .map(|r| r.and_then(T::from_untyped))346 .collect::<Result<Vec<T>>>()347 }348}349350impl<K: Typed + Ord, V: Typed> Typed for BTreeMap<K, V> {351 const TYPE: &'static ComplexValType = &ComplexValType::AttrsOf(V::TYPE);352353 fn into_untyped(typed: Self) -> Result<Val> {354 let mut out = ObjValueBuilder::with_capacity(typed.len());355 for (k, v) in typed {356 let Some(key) = K::into_untyped(k)?.as_str() else {357 throw!("map key should serialize to string");358 };359 let value = V::into_untyped(v)?;360 out.member(key).value_unchecked(value);361 }362 Ok(Val::Obj(out.build()))363 }364365 fn from_untyped(value: Val) -> Result<Self> {366 Self::TYPE.check(&value)?;367 let obj = value.as_obj().expect("typecheck should fail");368369 let mut out = BTreeMap::new();370 if V::wants_lazy() {371 for key in obj.fields_ex(372 false,373 #[cfg(feature = "exp-preserve-order")]374 false,375 ) {376 let value = obj.get_lazy(key.clone()).expect("field exists");377 let value = V::from_lazy_untyped(value)?;378 let key = K::from_untyped(Val::Str(key.into()))?;379 let _ = out.insert(key, value);380 }381 } else {382 for (key, value) in obj.iter(383 #[cfg(feature = "exp-preserve-order")]384 false,385 ) {386 let key = K::from_untyped(Val::Str(key.into()))?;387 let value = V::from_untyped(value?)?;388 let _ = out.insert(key, value);389 }390 }391 Ok(out)392 }393}394395impl Typed for Val {396 const TYPE: &'static ComplexValType = &ComplexValType::Any;397398 fn into_untyped(typed: Self) -> Result<Val> {399 Ok(typed)400 }401 fn from_untyped(untyped: Val) -> Result<Self> {402 Ok(untyped)403 }404}405406// Hack407#[doc(hidden)]408impl<T> Typed for Result<T>409where410 T: Typed,411{412 const TYPE: &'static ComplexValType = &ComplexValType::Any;413414 fn into_untyped(_typed: Self) -> Result<Val> {415 panic!("do not use this conversion")416 }417418 fn from_untyped(_untyped: Val) -> Result<Self> {419 panic!("do not use this conversion")420 }421422 fn into_result(typed: Self) -> Result<Val> {423 typed.map(T::into_untyped)?424 }425}426427/// Specialization428impl Typed for IBytes {429 const TYPE: &'static ComplexValType =430 &ComplexValType::ArrayRef(&ComplexValType::BoundedNumber(Some(0.0), Some(255.0)));431432 fn into_untyped(value: Self) -> Result<Val> {433 Ok(Val::Arr(ArrValue::bytes(value)))434 }435436 fn from_untyped(value: Val) -> Result<Self> {437 match &value {438 Val::Arr(a) => {439 if let Some(bytes) = a.as_any().downcast_ref::<BytesArray>() {440 return Ok(bytes.0.as_slice().into());441 };442 <Self as Typed>::TYPE.check(&value)?;443 // Any::downcast_ref::<ByteArray>(&a);444 let mut out = Vec::with_capacity(a.len());445 for e in a.iter() {446 let r = e?;447 out.push(u8::from_untyped(r)?);448 }449 Ok(out.as_slice().into())450 }451 _ => {452 <Self as Typed>::TYPE.check(&value)?;453 unreachable!()454 }455 }456 }457}458459pub struct M1;460impl Typed for M1 {461 const TYPE: &'static ComplexValType = &ComplexValType::BoundedNumber(Some(-1.0), Some(-1.0));462463 fn into_untyped(_: Self) -> Result<Val> {464 Ok(Val::Num(-1.0))465 }466467 fn from_untyped(value: Val) -> Result<Self> {468 <Self as Typed>::TYPE.check(&value)?;469 Ok(Self)470 }471}472473macro_rules! decl_either {474 ($($name: ident, $($id: ident)*);*) => {$(475 #[derive(Clone)]476 pub enum $name<$($id),*> {477 $($id($id)),*478 }479 impl<$($id),*> Typed for $name<$($id),*>480 where481 $($id: Typed,)*482 {483 const TYPE: &'static ComplexValType = &ComplexValType::UnionRef(&[$($id::TYPE),*]);484485 fn into_untyped(value: Self) -> Result<Val> {486 match value {$(487 $name::$id(v) => $id::into_untyped(v)488 ),*}489 }490491 fn from_untyped(value: Val) -> Result<Self> {492 $(493 if $id::TYPE.check(&value).is_ok() {494 $id::from_untyped(value).map(Self::$id)495 } else496 )* {497 <Self as Typed>::TYPE.check(&value)?;498 unreachable!()499 }500 }501 }502 )*}503}504decl_either!(505 Either1, A;506 Either2, A B;507 Either3, A B C;508 Either4, A B C D;509 Either5, A B C D E;510 Either6, A B C D E F;511 Either7, A B C D E F G512);513#[macro_export]514macro_rules! Either {515 ($a:ty) => {Either1<$a>};516 ($a:ty, $b:ty) => {Either2<$a, $b>};517 ($a:ty, $b:ty, $c:ty) => {Either3<$a, $b, $c>};518 ($a:ty, $b:ty, $c:ty, $d:ty) => {Either4<$a, $b, $c, $d>};519 ($a:ty, $b:ty, $c:ty, $d:ty, $e:ty) => {Either5<$a, $b, $c, $d, $e>};520 ($a:ty, $b:ty, $c:ty, $d:ty, $e:ty, $f:ty) => {Either6<$a, $b, $c, $d, $e, $f>};521 ($a:ty, $b:ty, $c:ty, $d:ty, $e:ty, $f:ty, $g:ty) => {Either7<$a, $b, $c, $d, $e, $f, $g>};522}523pub use Either;524525pub type MyType = Either![u32, f64, String];526527impl Typed for ArrValue {528 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Arr);529530 fn into_untyped(value: Self) -> Result<Val> {531 Ok(Val::Arr(value))532 }533534 fn from_untyped(value: Val) -> Result<Self> {535 <Self as Typed>::TYPE.check(&value)?;536 match value {537 Val::Arr(a) => Ok(a),538 _ => unreachable!(),539 }540 }541}542543impl Typed for FuncVal {544 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Func);545546 fn into_untyped(value: Self) -> Result<Val> {547 Ok(Val::Func(value))548 }549550 fn from_untyped(value: Val) -> Result<Self> {551 <Self as Typed>::TYPE.check(&value)?;552 match value {553 Val::Func(a) => Ok(a),554 _ => unreachable!(),555 }556 }557}558559impl Typed for Cc<FuncDesc> {560 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Func);561562 fn into_untyped(value: Self) -> Result<Val> {563 Ok(Val::Func(FuncVal::Normal(value)))564 }565566 fn from_untyped(value: Val) -> Result<Self> {567 <Self as Typed>::TYPE.check(&value)?;568 match value {569 Val::Func(FuncVal::Normal(desc)) => Ok(desc),570 Val::Func(_) => throw!("expected normal function, not builtin"),571 _ => unreachable!(),572 }573 }574}575576impl Typed for ObjValue {577 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Obj);578579 fn into_untyped(value: Self) -> Result<Val> {580 Ok(Val::Obj(value))581 }582583 fn from_untyped(value: Val) -> Result<Self> {584 <Self as Typed>::TYPE.check(&value)?;585 match value {586 Val::Obj(a) => Ok(a),587 _ => unreachable!(),588 }589 }590}591592impl Typed for bool {593 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Bool);594595 fn into_untyped(value: Self) -> Result<Val> {596 Ok(Val::Bool(value))597 }598599 fn from_untyped(value: Val) -> Result<Self> {600 <Self as Typed>::TYPE.check(&value)?;601 match value {602 Val::Bool(a) => Ok(a),603 _ => unreachable!(),604 }605 }606}607impl Typed for IndexableVal {608 const TYPE: &'static ComplexValType = &ComplexValType::UnionRef(&[609 &ComplexValType::Simple(ValType::Arr),610 &ComplexValType::Simple(ValType::Str),611 ]);612613 fn into_untyped(value: Self) -> Result<Val> {614 match value {615 IndexableVal::Str(s) => Ok(Val::Str(StrValue::Flat(s))),616 IndexableVal::Arr(a) => Ok(Val::Arr(a)),617 }618 }619620 fn from_untyped(value: Val) -> Result<Self> {621 <Self as Typed>::TYPE.check(&value)?;622 value.into_indexable()623 }624}625626pub struct Null;627impl Typed for Null {628 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Null);629630 fn into_untyped(_: Self) -> Result<Val> {631 Ok(Val::Null)632 }633634 fn from_untyped(value: Val) -> Result<Self> {635 <Self as Typed>::TYPE.check(&value)?;636 Ok(Self)637 }638}639640pub struct NativeFn<D: NativeDesc>(D::Value);641impl<D: NativeDesc> Deref for NativeFn<D> {642 type Target = D::Value;643644 fn deref(&self) -> &Self::Target {645 &self.0646 }647}648impl<D: NativeDesc> Typed for NativeFn<D> {649 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Func);650651 fn into_untyped(_typed: Self) -> Result<Val> {652 throw!("can only convert functions from jsonnet to native")653 }654655 fn from_untyped(untyped: Val) -> Result<Self> {656 Ok(Self(657 untyped658 .as_func()659 .expect("shape is checked")660 .into_native::<D>(),661 ))662 }663}1use std::{collections::BTreeMap, marker::PhantomData, ops::Deref};23use jrsonnet_gcmodule::{Cc, Trace};4use jrsonnet_interner::{IBytes, IStr};5pub use jrsonnet_macros::Typed;6use jrsonnet_types::{ComplexValType, ValType};78use crate::{9 arr::{ArrValue, BytesArray},10 bail,11 function::{native::NativeDesc, FuncDesc, FuncVal},12 typed::CheckType,13 val::{IndexableVal, ThunkMapper},14 ObjValue, ObjValueBuilder, Result, Thunk, Val,15};1617#[derive(Trace)]18struct FromUntyped<K: Trace>(PhantomData<fn() -> K>);19impl<K> ThunkMapper<Val> for FromUntyped<K>20where21 K: Typed + Trace,22{23 type Output = K;2425 fn map(self, from: Val) -> Result<Self::Output> {26 K::from_untyped(from)27 }28}29impl<K: Trace> Default for FromUntyped<K> {30 fn default() -> Self {31 Self(PhantomData)32 }33}3435pub trait TypedObj: Typed {36 fn serialize(self, out: &mut ObjValueBuilder) -> Result<()>;37 fn parse(obj: &ObjValue) -> Result<Self>;38 fn into_object(self) -> Result<ObjValue> {39 let mut builder = ObjValueBuilder::new();40 self.serialize(&mut builder)?;41 Ok(builder.build())42 }43}4445pub trait Typed: Sized {46 const TYPE: &'static ComplexValType;47 fn into_untyped(typed: Self) -> Result<Val>;48 fn into_lazy_untyped(typed: Self) -> Thunk<Val> {49 Thunk::from(Self::into_untyped(typed))50 }51 fn from_untyped(untyped: Val) -> Result<Self>;52 fn from_lazy_untyped(lazy: Thunk<Val>) -> Result<Self> {53 Self::from_untyped(lazy.evaluate()?)54 }5556 // Whatever caller should use `into_lazy_untyped` instead of `into_untyped`57 fn provides_lazy() -> bool {58 false59 }6061 // Whatever caller should use `from_lazy_untyped` instead of `from_untyped` when possible62 fn wants_lazy() -> bool {63 false64 }6566 /// Hack to make builtins be able to return non-result values, and make macros able to convert those values to result67 /// This method returns identity in impl Typed for Result, and should not be overriden68 #[doc(hidden)]69 fn into_result(typed: Self) -> Result<Val> {70 let value = Self::into_untyped(typed)?;71 Ok(value)72 }73}7475impl<T> Typed for Thunk<T>76where77 T: Typed + Trace + Clone,78{79 const TYPE: &'static ComplexValType = &ComplexValType::Lazy(T::TYPE);8081 fn into_untyped(typed: Self) -> Result<Val> {82 T::into_untyped(typed.evaluate()?)83 }8485 fn from_untyped(untyped: Val) -> Result<Self> {86 Self::from_lazy_untyped(Thunk::evaluated(untyped))87 }8889 fn provides_lazy() -> bool {90 true91 }9293 fn into_lazy_untyped(inner: Self) -> Thunk<Val> {94 #[derive(Trace)]95 struct IntoUntyped<K: Trace>(PhantomData<fn() -> K>);96 impl<K> ThunkMapper<K> for IntoUntyped<K>97 where98 K: Typed + Trace,99 {100 type Output = Val;101102 fn map(self, from: K) -> Result<Self::Output> {103 K::into_untyped(from)104 }105 }106 impl<K: Trace> Default for IntoUntyped<K> {107 fn default() -> Self {108 Self(PhantomData)109 }110 }111 inner.map(<IntoUntyped<T>>::default())112 }113114 fn wants_lazy() -> bool {115 true116 }117118 fn from_lazy_untyped(inner: Thunk<Val>) -> Result<Self> {119 Ok(inner.map(<FromUntyped<T>>::default()))120 }121}122123const MAX_SAFE_INTEGER: f64 = ((1u64 << (f64::MANTISSA_DIGITS + 1)) - 1) as f64;124125macro_rules! impl_int {126 ($($ty:ty)*) => {$(127 impl Typed for $ty {128 const TYPE: &'static ComplexValType =129 &ComplexValType::BoundedNumber(Some(Self::MIN as f64), Some(Self::MAX as f64));130 fn from_untyped(value: Val) -> Result<Self> {131 <Self as Typed>::TYPE.check(&value)?;132 match value {133 Val::Num(n) => {134 #[allow(clippy::float_cmp)]135 if n.trunc() != n {136 bail!(137 "cannot convert number with fractional part to {}",138 stringify!($ty)139 )140 }141 Ok(n as Self)142 }143 _ => unreachable!(),144 }145 }146 fn into_untyped(value: Self) -> Result<Val> {147 Ok(Val::Num(value as f64))148 }149 }150 )*};151}152153impl_int!(i8 u8 i16 u16 i32 u32);154155macro_rules! impl_bounded_int {156 ($($name:ident = $ty:ty)*) => {$(157 #[derive(Clone, Copy)]158 pub struct $name<const MIN: $ty, const MAX: $ty>($ty);159 impl<const MIN: $ty, const MAX: $ty> $name<MIN, MAX> {160 pub const fn new(value: $ty) -> Option<$name<MIN, MAX>> {161 if value >= MIN && value <= MAX {162 Some(Self(value))163 } else {164 None165 }166 }167 pub const fn value(self) -> $ty {168 self.0169 }170 }171 impl<const MIN: $ty, const MAX: $ty> Deref for $name<MIN, MAX> {172 type Target = $ty;173 fn deref(&self) -> &Self::Target {174 &self.0175 }176 }177178 impl<const MIN: $ty, const MAX: $ty> Typed for $name<MIN, MAX> {179 const TYPE: &'static ComplexValType =180 &ComplexValType::BoundedNumber(181 Some(MIN as f64),182 Some(MAX as f64),183 );184185 fn from_untyped(value: Val) -> Result<Self> {186 <Self as Typed>::TYPE.check(&value)?;187 match value {188 Val::Num(n) => {189 #[allow(clippy::float_cmp)]190 if n.trunc() != n {191 bail!(192 "cannot convert number with fractional part to {}",193 stringify!($ty)194 )195 }196 Ok(Self(n as $ty))197 }198 _ => unreachable!(),199 }200 }201202 fn into_untyped(value: Self) -> Result<Val> {203 Ok(Val::Num(value.0 as f64))204 }205 }206 )*};207}208209impl_bounded_int!(210 BoundedI8 = i8211 BoundedI16 = i16212 BoundedI32 = i32213 BoundedI64 = i64214 BoundedUsize = usize215);216217impl Typed for f64 {218 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Num);219220 fn into_untyped(value: Self) -> Result<Val> {221 Ok(Val::Num(value))222 }223224 fn from_untyped(value: Val) -> Result<Self> {225 <Self as Typed>::TYPE.check(&value)?;226 match value {227 Val::Num(n) => Ok(n),228 _ => unreachable!(),229 }230 }231}232233pub struct PositiveF64(pub f64);234impl Typed for PositiveF64 {235 const TYPE: &'static ComplexValType = &ComplexValType::BoundedNumber(Some(0.0), None);236237 fn into_untyped(value: Self) -> Result<Val> {238 Ok(Val::Num(value.0))239 }240241 fn from_untyped(value: Val) -> Result<Self> {242 <Self as Typed>::TYPE.check(&value)?;243 match value {244 Val::Num(n) => Ok(Self(n)),245 _ => unreachable!(),246 }247 }248}249impl Typed for usize {250 const TYPE: &'static ComplexValType =251 &ComplexValType::BoundedNumber(Some(0.0), Some(MAX_SAFE_INTEGER));252253 fn into_untyped(value: Self) -> Result<Val> {254 if value > MAX_SAFE_INTEGER as Self {255 bail!("number is too large")256 }257 Ok(Val::Num(value as f64))258 }259260 fn from_untyped(value: Val) -> Result<Self> {261 <Self as Typed>::TYPE.check(&value)?;262 match value {263 Val::Num(n) => {264 #[allow(clippy::float_cmp)]265 if n.trunc() != n {266 bail!("cannot convert number with fractional part to usize")267 }268 Ok(n as Self)269 }270 _ => unreachable!(),271 }272 }273}274275impl Typed for IStr {276 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Str);277278 fn into_untyped(value: Self) -> Result<Val> {279 Ok(Val::Str(StrValue::Flat(value)))280 }281282 fn from_untyped(value: Val) -> Result<Self> {283 <Self as Typed>::TYPE.check(&value)?;284 match value {285 Val::Str(s) => Ok(s.into_flat()),286 _ => unreachable!(),287 }288 }289}290291impl Typed for String {292 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Str);293294 fn into_untyped(value: Self) -> Result<Val> {295 Ok(Val::Str(StrValue::Flat(value.into())))296 }297298 fn from_untyped(value: Val) -> Result<Self> {299 <Self as Typed>::TYPE.check(&value)?;300 match value {301 Val::Str(s) => Ok(s.to_string()),302 _ => unreachable!(),303 }304 }305}306307impl Typed for char {308 const TYPE: &'static ComplexValType = &ComplexValType::Char;309310 fn into_untyped(value: Self) -> Result<Val> {311 Ok(Val::Str(StrValue::Flat(value.to_string().into())))312 }313314 fn from_untyped(value: Val) -> Result<Self> {315 <Self as Typed>::TYPE.check(&value)?;316 match value {317 Val::Str(s) => Ok(s.into_flat().chars().next().unwrap()),318 _ => unreachable!(),319 }320 }321}322323impl<T> Typed for Vec<T>324where325 T: Typed,326{327 const TYPE: &'static ComplexValType = &ComplexValType::ArrayRef(T::TYPE);328329 fn into_untyped(value: Self) -> Result<Val> {330 Ok(Val::Arr(331 value332 .into_iter()333 .map(T::into_untyped)334 .collect::<Result<ArrValue>>()?,335 ))336 }337338 fn from_untyped(value: Val) -> Result<Self> {339 let Val::Arr(a) = value else {340 <Self as Typed>::TYPE.check(&value)?;341 unreachable!("typecheck should fail")342 };343 a.iter()344 .map(|r| r.and_then(T::from_untyped))345 .collect::<Result<Vec<T>>>()346 }347}348349impl<K: Typed + Ord, V: Typed> Typed for BTreeMap<K, V> {350 const TYPE: &'static ComplexValType = &ComplexValType::AttrsOf(V::TYPE);351352 fn into_untyped(typed: Self) -> Result<Val> {353 let mut out = ObjValueBuilder::with_capacity(typed.len());354 for (k, v) in typed {355 let Some(key) = K::into_untyped(k)?.as_str() else {356 bail!("map key should serialize to string");357 };358 let value = V::into_untyped(v)?;359 out.member(key).value_unchecked(value);360 }361 Ok(Val::Obj(out.build()))362 }363364 fn from_untyped(value: Val) -> Result<Self> {365 Self::TYPE.check(&value)?;366 let obj = value.as_obj().expect("typecheck should fail");367368 let mut out = BTreeMap::new();369 if V::wants_lazy() {370 for key in obj.fields_ex(371 false,372 #[cfg(feature = "exp-preserve-order")]373 false,374 ) {375 let value = obj.get_lazy(key.clone()).expect("field exists");376 let value = V::from_lazy_untyped(value)?;377 let key = K::from_untyped(Val::Str(key.into()))?;378 let _ = out.insert(key, value);379 }380 } else {381 for (key, value) in obj.iter(382 #[cfg(feature = "exp-preserve-order")]383 false,384 ) {385 let key = K::from_untyped(Val::Str(key.into()))?;386 let value = V::from_untyped(value?)?;387 let _ = out.insert(key, value);388 }389 }390 Ok(out)391 }392}393394impl Typed for Val {395 const TYPE: &'static ComplexValType = &ComplexValType::Any;396397 fn into_untyped(typed: Self) -> Result<Val> {398 Ok(typed)399 }400 fn from_untyped(untyped: Val) -> Result<Self> {401 Ok(untyped)402 }403}404405// Hack406#[doc(hidden)]407impl<T> Typed for Result<T>408where409 T: Typed,410{411 const TYPE: &'static ComplexValType = &ComplexValType::Any;412413 fn into_untyped(_typed: Self) -> Result<Val> {414 panic!("do not use this conversion")415 }416417 fn from_untyped(_untyped: Val) -> Result<Self> {418 panic!("do not use this conversion")419 }420421 fn into_result(typed: Self) -> Result<Val> {422 typed.map(T::into_untyped)?423 }424}425426/// Specialization427impl Typed for IBytes {428 const TYPE: &'static ComplexValType =429 &ComplexValType::ArrayRef(&ComplexValType::BoundedNumber(Some(0.0), Some(255.0)));430431 fn into_untyped(value: Self) -> Result<Val> {432 Ok(Val::Arr(ArrValue::bytes(value)))433 }434435 fn from_untyped(value: Val) -> Result<Self> {436 match &value {437 Val::Arr(a) => {438 if let Some(bytes) = a.as_any().downcast_ref::<BytesArray>() {439 return Ok(bytes.0.as_slice().into());440 };441 <Self as Typed>::TYPE.check(&value)?;442 // Any::downcast_ref::<ByteArray>(&a);443 let mut out = Vec::with_capacity(a.len());444 for e in a.iter() {445 let r = e?;446 out.push(u8::from_untyped(r)?);447 }448 Ok(out.as_slice().into())449 }450 _ => {451 <Self as Typed>::TYPE.check(&value)?;452 unreachable!()453 }454 }455 }456}457458pub struct M1;459impl Typed for M1 {460 const TYPE: &'static ComplexValType = &ComplexValType::BoundedNumber(Some(-1.0), Some(-1.0));461462 fn into_untyped(_: Self) -> Result<Val> {463 Ok(Val::Num(-1.0))464 }465466 fn from_untyped(value: Val) -> Result<Self> {467 <Self as Typed>::TYPE.check(&value)?;468 Ok(Self)469 }470}471472macro_rules! decl_either {473 ($($name: ident, $($id: ident)*);*) => {$(474 #[derive(Clone)]475 pub enum $name<$($id),*> {476 $($id($id)),*477 }478 impl<$($id),*> Typed for $name<$($id),*>479 where480 $($id: Typed,)*481 {482 const TYPE: &'static ComplexValType = &ComplexValType::UnionRef(&[$($id::TYPE),*]);483484 fn into_untyped(value: Self) -> Result<Val> {485 match value {$(486 $name::$id(v) => $id::into_untyped(v)487 ),*}488 }489490 fn from_untyped(value: Val) -> Result<Self> {491 $(492 if $id::TYPE.check(&value).is_ok() {493 $id::from_untyped(value).map(Self::$id)494 } else495 )* {496 <Self as Typed>::TYPE.check(&value)?;497 unreachable!()498 }499 }500 }501 )*}502}503decl_either!(504 Either1, A;505 Either2, A B;506 Either3, A B C;507 Either4, A B C D;508 Either5, A B C D E;509 Either6, A B C D E F;510 Either7, A B C D E F G511);512#[macro_export]513macro_rules! Either {514 ($a:ty) => {Either1<$a>};515 ($a:ty, $b:ty) => {Either2<$a, $b>};516 ($a:ty, $b:ty, $c:ty) => {Either3<$a, $b, $c>};517 ($a:ty, $b:ty, $c:ty, $d:ty) => {Either4<$a, $b, $c, $d>};518 ($a:ty, $b:ty, $c:ty, $d:ty, $e:ty) => {Either5<$a, $b, $c, $d, $e>};519 ($a:ty, $b:ty, $c:ty, $d:ty, $e:ty, $f:ty) => {Either6<$a, $b, $c, $d, $e, $f>};520 ($a:ty, $b:ty, $c:ty, $d:ty, $e:ty, $f:ty, $g:ty) => {Either7<$a, $b, $c, $d, $e, $f, $g>};521}522pub use Either;523524pub type MyType = Either![u32, f64, String];525526impl Typed for ArrValue {527 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Arr);528529 fn into_untyped(value: Self) -> Result<Val> {530 Ok(Val::Arr(value))531 }532533 fn from_untyped(value: Val) -> Result<Self> {534 <Self as Typed>::TYPE.check(&value)?;535 match value {536 Val::Arr(a) => Ok(a),537 _ => unreachable!(),538 }539 }540}541542impl Typed for FuncVal {543 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Func);544545 fn into_untyped(value: Self) -> Result<Val> {546 Ok(Val::Func(value))547 }548549 fn from_untyped(value: Val) -> Result<Self> {550 <Self as Typed>::TYPE.check(&value)?;551 match value {552 Val::Func(a) => Ok(a),553 _ => unreachable!(),554 }555 }556}557558impl Typed for Cc<FuncDesc> {559 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Func);560561 fn into_untyped(value: Self) -> Result<Val> {562 Ok(Val::Func(FuncVal::Normal(value)))563 }564565 fn from_untyped(value: Val) -> Result<Self> {566 <Self as Typed>::TYPE.check(&value)?;567 match value {568 Val::Func(FuncVal::Normal(desc)) => Ok(desc),569 Val::Func(_) => bail!("expected normal function, not builtin"),570 _ => unreachable!(),571 }572 }573}574575impl Typed for ObjValue {576 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Obj);577578 fn into_untyped(value: Self) -> Result<Val> {579 Ok(Val::Obj(value))580 }581582 fn from_untyped(value: Val) -> Result<Self> {583 <Self as Typed>::TYPE.check(&value)?;584 match value {585 Val::Obj(a) => Ok(a),586 _ => unreachable!(),587 }588 }589}590591impl Typed for bool {592 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Bool);593594 fn into_untyped(value: Self) -> Result<Val> {595 Ok(Val::Bool(value))596 }597598 fn from_untyped(value: Val) -> Result<Self> {599 <Self as Typed>::TYPE.check(&value)?;600 match value {601 Val::Bool(a) => Ok(a),602 _ => unreachable!(),603 }604 }605}606impl Typed for IndexableVal {607 const TYPE: &'static ComplexValType = &ComplexValType::UnionRef(&[608 &ComplexValType::Simple(ValType::Arr),609 &ComplexValType::Simple(ValType::Str),610 ]);611612 fn into_untyped(value: Self) -> Result<Val> {613 match value {614 IndexableVal::Str(s) => Ok(Val::Str(StrValue::Flat(s))),615 IndexableVal::Arr(a) => Ok(Val::Arr(a)),616 }617 }618619 fn from_untyped(value: Val) -> Result<Self> {620 <Self as Typed>::TYPE.check(&value)?;621 value.into_indexable()622 }623}624625pub struct Null;626impl Typed for Null {627 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Null);628629 fn into_untyped(_: Self) -> Result<Val> {630 Ok(Val::Null)631 }632633 fn from_untyped(value: Val) -> Result<Self> {634 <Self as Typed>::TYPE.check(&value)?;635 Ok(Self)636 }637}638639pub struct NativeFn<D: NativeDesc>(D::Value);640impl<D: NativeDesc> Deref for NativeFn<D> {641 type Target = D::Value;642643 fn deref(&self) -> &Self::Target {644 &self.0645 }646}647impl<D: NativeDesc> Typed for NativeFn<D> {648 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Func);649650 fn into_untyped(_typed: Self) -> Result<Val> {651 bail!("can only convert functions from jsonnet to native")652 }653654 fn from_untyped(untyped: Val) -> Result<Self> {655 Ok(Self(656 untyped657 .as_func()658 .expect("shape is checked")659 .into_native::<D>(),660 ))661 }662}crates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/val.rs
+++ b/crates/jrsonnet-evaluator/src/val.rs
@@ -11,11 +11,12 @@
pub use crate::arr::{ArrValue, ArrayLike};
use crate::{
+ bail,
error::{Error, ErrorKind::*},
function::FuncVal,
gc::{GcHashMap, TraceBox},
manifest::{ManifestFormat, ToStringFormat},
- tb, throw,
+ tb,
typed::BoundedUsize,
ObjValue, Result, Unbound, WeakObjValue,
};
@@ -456,7 +457,7 @@
if num.is_finite() {
Ok(Self::Num(num))
} else {
- throw!("overflow")
+ bail!("overflow")
}
}
@@ -495,7 +496,7 @@
Ok(match self {
Val::Str(s) => IndexableVal::Str(s.into_flat()),
Val::Arr(arr) => IndexableVal::Arr(arr),
- _ => throw!(ValueIsNotIndexable(self.value_type())),
+ _ => bail!(ValueIsNotIndexable(self.value_type())),
})
}
}
@@ -514,13 +515,13 @@
#[cfg(feature = "exp-bigint")]
(Val::BigInt(a), Val::BigInt(b)) => a == b,
(Val::Arr(_), Val::Arr(_)) => {
- throw!("primitiveEquals operates on primitive types, got array")
+ bail!("primitiveEquals operates on primitive types, got array")
}
(Val::Obj(_), Val::Obj(_)) => {
- throw!("primitiveEquals operates on primitive types, got object")
+ bail!("primitiveEquals operates on primitive types, got object")
}
(a, b) if is_function_like(a) && is_function_like(b) => {
- throw!("cannot test equality of functions")
+ bail!("cannot test equality of functions")
}
(_, _) => false,
})
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)]