difftreelog
feat implement argument parsing with proc macro
in: master
17 files changed
bindings/jsonnet/src/import.rsdiffbeforeafterboth--- a/bindings/jsonnet/src/import.rs
+++ b/bindings/jsonnet/src/import.rs
@@ -49,8 +49,8 @@
};
// Release memory occipied by arguments passed
unsafe {
- CString::from_raw(base);
- CString::from_raw(rel);
+ let _ = CString::from_raw(base);
+ let _ = CString::from_raw(rel);
}
let result_raw = unsafe { CStr::from_ptr(result_ptr) };
let result_str = result_raw.to_str().unwrap();
@@ -64,7 +64,7 @@
let found_here_raw = unsafe { CStr::from_ptr(found_here) };
let found_here_buf = PathBuf::from(found_here_raw.to_str().unwrap());
unsafe {
- CString::from_raw(found_here);
+ let _ = CString::from_raw(found_here);
}
let mut out = self.out.borrow_mut();
bindings/jsonnet/src/native.rsdiffbeforeafterboth--- a/bindings/jsonnet/src/native.rs
+++ b/bindings/jsonnet/src/native.rs
@@ -3,10 +3,11 @@
error::{Error, LocError},
gc::TraceBox,
native::{NativeCallback, NativeCallbackHandler},
- EvaluationState, Val,
+ EvaluationState, IStr, Val,
};
use jrsonnet_parser::{Param, ParamsDesc};
use std::{
+ convert::TryFrom,
ffi::{c_void, CStr},
os::raw::{c_char, c_int},
path::Path,
@@ -45,7 +46,7 @@
if success == 1 {
Ok(v)
} else {
- let e = v.try_cast_str("native error").expect("error msg");
+ let e = IStr::try_from(v).expect("error msg");
Err(Error::RuntimeError(e).into())
}
}
crates/jrsonnet-evaluator/Cargo.tomldiffbeforeafterboth--- a/crates/jrsonnet-evaluator/Cargo.toml
+++ b/crates/jrsonnet-evaluator/Cargo.toml
@@ -23,6 +23,7 @@
jrsonnet-parser = { path = "../jrsonnet-parser", version = "0.4.2" }
jrsonnet-stdlib = { path = "../jrsonnet-stdlib", version = "0.4.2" }
jrsonnet-types = { path = "../jrsonnet-types", version = "0.4.2" }
+jrsonnet-macros = { path = "../jrsonnet-macros", version = "0.4.2" }
pathdiff = "0.2.0"
md5 = "0.7.0"
crates/jrsonnet-evaluator/src/builtin/format.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/builtin/format.rs
+++ b/crates/jrsonnet-evaluator/src/builtin/format.rs
@@ -5,6 +5,7 @@
use gcmodule::Trace;
use jrsonnet_interner::IStr;
use jrsonnet_types::ValType;
+use std::convert::TryFrom;
use thiserror::Error;
#[derive(Debug, Clone, Error, Trace)]
@@ -484,7 +485,7 @@
match code.convtype {
ConvTypeV::String => tmp_out.push_str(&value.clone().to_string()?),
ConvTypeV::Decimal => {
- let value = value.clone().try_cast_num("%d/%u/%i requires number")?;
+ let value = f64::try_from(value.clone())?;
render_decimal(
&mut tmp_out,
value as i64,
@@ -495,7 +496,7 @@
);
}
ConvTypeV::Octal => {
- let value = value.clone().try_cast_num("%o requires number")?;
+ let value = f64::try_from(value.clone())?;
render_octal(
&mut tmp_out,
value as i64,
@@ -507,7 +508,7 @@
);
}
ConvTypeV::Hexadecimal => {
- let value = value.clone().try_cast_num("%x/%X requires number")?;
+ let value = f64::try_from(value.clone())?;
render_hexadecimal(
&mut tmp_out,
value as i64,
@@ -520,7 +521,7 @@
);
}
ConvTypeV::Scientific => {
- let value = value.clone().try_cast_num("%e/%E requires number")?;
+ let value = f64::try_from(value.clone())?;
render_float_sci(
&mut tmp_out,
value,
@@ -534,7 +535,7 @@
);
}
ConvTypeV::Float => {
- let value = value.clone().try_cast_num("%e/%E requires number")?;
+ let value = f64::try_from(value.clone())?;
render_float(
&mut tmp_out,
value,
@@ -547,7 +548,7 @@
);
}
ConvTypeV::Shorter => {
- let value = value.clone().try_cast_num("%g/%G requires number")?;
+ let value = f64::try_from(value.clone())?;
let exponent = value.log10().floor();
if exponent < -4.0 || exponent >= fpprec as f64 {
render_float_sci(
@@ -633,7 +634,7 @@
}
let value = &values[0];
values = &values[1..];
- value.clone().try_cast_num("field width")? as usize
+ usize::try_from(value.clone())?
}
Width::Fixed(n) => n,
};
@@ -644,7 +645,7 @@
}
let value = &values[0];
values = &values[1..];
- Some(value.clone().try_cast_num("field precision")? as usize)
+ Some(usize::try_from(value.clone())?)
}
Some(Width::Fixed(n)) => Some(n),
None => None,
crates/jrsonnet-evaluator/src/builtin/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/builtin/mod.rs
+++ b/crates/jrsonnet-evaluator/src/builtin/mod.rs
@@ -1,10 +1,12 @@
+use crate::typed::{Any, Either, Null, PositiveF64, VecVal, M1};
+use crate::{self as jrsonnet_evaluator, ObjValue};
use crate::{
builtin::manifest::{manifest_yaml_ex, ManifestYamlOptions},
equals,
error::{Error::*, Result},
operator::evaluate_mod_op,
parse_args, primitive_equals, push_frame, throw, with_state, ArrValue, Context, FuncVal,
- IndexableVal, LazyVal, Val,
+ IndexableVal, Val,
};
use format::{format_arr, format_obj};
use gcmodule::Cc;
@@ -13,7 +15,12 @@
use jrsonnet_types::ty;
use serde::Deserialize;
use serde_yaml::DeserializingQuirks;
-use std::{collections::HashMap, convert::TryFrom, path::PathBuf, rc::Rc};
+use std::{
+ collections::HashMap,
+ convert::{TryFrom, TryInto},
+ path::PathBuf,
+ rc::Rc,
+};
pub mod stdlib;
pub use stdlib::*;
@@ -24,15 +31,15 @@
pub mod manifest;
pub mod sort;
-pub fn std_format(str: IStr, vals: Val) -> Result<Val> {
+pub fn std_format(str: IStr, vals: Val) -> Result<String> {
push_frame(
&ExprLocation(Rc::from(PathBuf::from("std.jsonnet")), 0, 0),
|| format!("std.format of {}", str),
|| {
Ok(match vals {
- Val::Arr(vals) => Val::Str(format_arr(&str, &vals.evaluated()?)?.into()),
- Val::Obj(obj) => Val::Str(format_obj(&str, &obj)?.into()),
- o => Val::Str(format_arr(&str, &[o])?.into()),
+ Val::Arr(vals) => format_arr(&str, &vals.evaluated()?)?,
+ Val::Obj(obj) => format_obj(&str, &obj)?,
+ o => format_arr(&str, &[o])?,
})
},
)
@@ -139,265 +146,177 @@
};
}
-fn builtin_length(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "length", args, 1, [
- 0, x: ty!((string | object | array));
- ], {
- Ok(match x {
- Val::Str(n) => Val::Num(n.chars().count() as f64),
- Val::Arr(a) => Val::Num(a.len() as f64),
- Val::Obj(o) => Val::Num(
- o.fields_visibility()
- .into_iter()
- .filter(|(_k, v)| *v)
- .count() as f64,
- ),
- _ => unreachable!(),
- })
+#[jrsonnet_macros::builtin]
+fn builtin_length(x: Either<IStr, Either<VecVal, ObjValue>>) -> Result<usize> {
+ Ok(match x {
+ Either::Left(x) => x.len(),
+ Either::Right(Either::Left(x)) => x.0.len(),
+ Either::Right(Either::Right(x)) => x
+ .fields_visibility()
+ .into_iter()
+ .filter(|(_k, v)| *v)
+ .count(),
})
}
-fn builtin_type(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "type", args, 1, [
- 0, x: ty!(any);
- ], {
- Ok(Val::Str(x.value_type().name().into()))
- })
+#[jrsonnet_macros::builtin]
+fn builtin_type(x: Any) -> Result<IStr> {
+ Ok(x.0.value_type().name().into())
}
-fn builtin_make_array(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "makeArray", args, 2, [
- 0, sz: ty!(BoundedNumber<(Some(0.0)), (None)>) => Val::Num;
- 1, func: ty!(function) => Val::Func;
- ], {
- let mut out = Vec::with_capacity(sz as usize);
- for i in 0..sz as usize {
- out.push(LazyVal::new_resolved(func.evaluate_values(
- context.clone(),
- &[Val::Num(i as f64)]
- )?))
- }
- Ok(Val::Arr(out.into()))
- })
+#[jrsonnet_macros::builtin]
+fn builtin_make_array(sz: usize, func: Cc<FuncVal>) -> Result<VecVal> {
+ let mut out = Vec::with_capacity(sz);
+ for i in 0..sz {
+ out.push(func.evaluate_values(&[Val::Num(i as f64)])?)
+ }
+ Ok(VecVal(out))
}
-fn builtin_codepoint(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "codepoint", args, 1, [
- 0, str: ty!(char) => Val::Str;
- ], {
- Ok(Val::Num(str.chars().next().unwrap() as u32 as f64))
- })
+#[jrsonnet_macros::builtin]
+const fn builtin_codepoint(str: char) -> Result<u32> {
+ Ok(str as u32)
}
-fn builtin_object_fields_ex(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "objectFieldsEx", args, 2, [
- 0, obj: ty!(object) => Val::Obj;
- 1, inc_hidden: ty!(boolean) => Val::Bool;
- ], {
- let out = obj.fields_ex(inc_hidden);
- Ok(Val::Arr(out.into_iter().map(Val::Str).collect::<Vec<_>>().into()))
- })
+#[jrsonnet_macros::builtin]
+fn builtin_object_fields_ex(obj: ObjValue, inc_hidden: bool) -> Result<VecVal> {
+ let out = obj.fields_ex(inc_hidden);
+ Ok(VecVal(out.into_iter().map(Val::Str).collect::<Vec<_>>()))
}
-fn builtin_object_has_ex(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "objectHasEx", args, 3, [
- 0, obj: ty!(object) => Val::Obj;
- 1, f: ty!(string) => Val::Str;
- 2, inc_hidden: ty!(boolean) => Val::Bool;
- ], {
- Ok(Val::Bool(obj.has_field_ex(f, inc_hidden)))
- })
+#[jrsonnet_macros::builtin]
+fn builtin_object_has_ex(obj: ObjValue, f: IStr, inc_hidden: bool) -> Result<bool> {
+ Ok(obj.has_field_ex(f, inc_hidden))
}
-fn builtin_parse_json(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "parseJson", args, 1, [
- 0, s: ty!(string) => Val::Str;
- ], {
- let value: serde_json::Value = serde_json::from_str(&s).map_err(|e| RuntimeError(format!("failed to parse json: {}", e).into()))?;
- Ok(Val::try_from(&value)?)
- })
+#[jrsonnet_macros::builtin]
+fn builtin_parse_json(s: IStr) -> Result<Any> {
+ let value: serde_json::Value = serde_json::from_str(&s)
+ .map_err(|e| RuntimeError(format!("failed to parse json: {}", e).into()))?;
+ Ok(Any(Val::try_from(&value)?))
}
-fn builtin_parse_yaml(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "parseYaml", args, 1, [
- 0, s: ty!(string) => Val::Str;
- ], {
- let value = serde_yaml::Deserializer::from_str_with_quirks(&s, DeserializingQuirks { old_octals: true });
- let mut out = vec![];
- for item in value {
- let value = serde_json::Value::deserialize(item)
- .map_err(|e| RuntimeError(format!("failed to parse yaml: {}", e).into()))?;
- let val = Val::try_from(&value)?;
- out.push(val);
- }
- if out.is_empty() {
- Ok(Val::Null)
- } else if out.len() == 1 {
- Ok(out.into_iter().next().unwrap())
- } else {
- Ok(Val::Arr(out.into()))
- }
- })
+#[jrsonnet_macros::builtin]
+fn builtin_parse_yaml(s: IStr) -> Result<Any> {
+ let value = serde_yaml::Deserializer::from_str_with_quirks(
+ &s,
+ DeserializingQuirks { old_octals: true },
+ );
+ let mut out = vec![];
+ for item in value {
+ let value = serde_json::Value::deserialize(item)
+ .map_err(|e| RuntimeError(format!("failed to parse yaml: {}", e).into()))?;
+ let val = Val::try_from(&value)?;
+ out.push(val);
+ }
+ Ok(Any(if out.is_empty() {
+ Val::Null
+ } else if out.len() == 1 {
+ out.into_iter().next().unwrap()
+ } else {
+ Val::Arr(out.into())
+ }))
}
-fn builtin_slice(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "slice", args, 4, [
- 0, indexable: ty!((string | array));
- 1, index: ty!((number | null));
- 2, end: ty!((number | null));
- 3, step: ty!((number | null));
- ], {
- std_slice(
- indexable.into_indexable()?,
- index.try_cast_nullable_num("index")?.map(|v| v as usize),
- end.try_cast_nullable_num("end")?.map(|v| v as usize),
- step.try_cast_nullable_num("step")?.map(|v| v as usize),
- )
- })
+#[jrsonnet_macros::builtin]
+fn builtin_slice(
+ indexable: IndexableVal,
+ index: Either<usize, Null>,
+ end: Either<usize, Null>,
+ step: Either<usize, Null>,
+) -> Result<Any> {
+ std_slice(indexable, index.left(), end.left(), step.left()).map(Any)
}
-fn builtin_substr(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "substr", args, 3, [
- 0, str: ty!(string) => Val::Str;
- 1, from: ty!(BoundedNumber<(Some(0.0)), (None)>) => Val::Num;
- 2, len: ty!(BoundedNumber<(Some(0.0)), (None)>) => Val::Num;
- ], {
- let out: String = str.chars().skip(from as usize).take(len as usize).collect();
- Ok(Val::Str(out.into()))
- })
+#[jrsonnet_macros::builtin]
+fn builtin_substr(str: IStr, from: usize, len: usize) -> Result<String> {
+ Ok(str.chars().skip(from as usize).take(len as usize).collect())
}
-fn builtin_primitive_equals(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "primitiveEquals", args, 2, [
- 0, a: ty!(any);
- 1, b: ty!(any);
- ], {
- Ok(Val::Bool(primitive_equals(&a, &b)?))
- })
+#[jrsonnet_macros::builtin]
+fn builtin_primitive_equals(a: Any, b: Any) -> Result<bool> {
+ primitive_equals(&a.0, &b.0)
}
-fn builtin_equals(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "equals", args, 2, [
- 0, a: ty!(any);
- 1, b: ty!(any);
- ], {
- Ok(Val::Bool(equals(&a, &b)?))
- })
+#[jrsonnet_macros::builtin]
+fn builtin_equals(a: Any, b: Any) -> Result<bool> {
+ equals(&a.0, &b.0)
}
-fn builtin_modulo(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "modulo", args, 2, [
- 0, a: ty!(number) => Val::Num;
- 1, b: ty!(number) => Val::Num;
- ], {
- Ok(Val::Num(a % b))
- })
+#[jrsonnet_macros::builtin]
+fn builtin_modulo(a: f64, b: f64) -> Result<f64> {
+ Ok(a % b)
}
-fn builtin_mod(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "mod", args, 2, [
- 0, a: ty!((number | string));
- 1, b: ty!(any);
- ], {
- evaluate_mod_op(&a, &b)
- })
+#[jrsonnet_macros::builtin]
+fn builtin_mod(a: Either<f64, IStr>, b: Any) -> Result<Any> {
+ Ok(Any(evaluate_mod_op(
+ &match a {
+ Either::Left(v) => Val::Num(v),
+ Either::Right(s) => Val::Str(s),
+ },
+ &b.0,
+ )?))
}
-fn builtin_floor(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "floor", args, 1, [
- 0, x: ty!(number) => Val::Num;
- ], {
- Ok(Val::Num(x.floor()))
- })
+#[jrsonnet_macros::builtin]
+fn builtin_floor(x: f64) -> Result<f64> {
+ Ok(x.floor())
}
-fn builtin_ceil(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "ceil", args, 1, [
- 0, x: ty!(number) => Val::Num;
- ], {
- Ok(Val::Num(x.ceil()))
- })
+#[jrsonnet_macros::builtin]
+fn builtin_ceil(x: f64) -> Result<f64> {
+ Ok(x.ceil())
}
-fn builtin_log(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "log", args, 1, [
- 0, n: ty!(number) => Val::Num;
- ], {
- Ok(Val::Num(n.ln()))
- })
+#[jrsonnet_macros::builtin]
+fn builtin_log(n: f64) -> Result<f64> {
+ Ok(n.ln())
}
-fn builtin_pow(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "pow", args, 2, [
- 0, x: ty!(number) => Val::Num;
- 1, n: ty!(number) => Val::Num;
- ], {
- Ok(Val::Num(x.powf(n)))
- })
+#[jrsonnet_macros::builtin]
+fn builtin_pow(x: f64, n: f64) -> Result<f64> {
+ Ok(x.powf(n))
}
-fn builtin_sqrt(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "sqrt", args, 1, [
- 0, x: ty!(BoundedNumber<(Some(0.0)), (None)>) => Val::Num;
- ], {
- Ok(Val::Num(x.sqrt()))
- })
+#[jrsonnet_macros::builtin]
+fn builtin_sqrt(x: PositiveF64) -> Result<f64> {
+ Ok(x.0.sqrt())
}
-fn builtin_sin(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "sin", args, 1, [
- 0, x: ty!(number) => Val::Num;
- ], {
- Ok(Val::Num(x.sin()))
- })
+#[jrsonnet_macros::builtin]
+fn builtin_sin(x: f64) -> Result<f64> {
+ Ok(x.sin())
}
-fn builtin_cos(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "cos", args, 1, [
- 0, x: ty!(number) => Val::Num;
- ], {
- Ok(Val::Num(x.cos()))
- })
+#[jrsonnet_macros::builtin]
+fn builtin_cos(x: f64) -> Result<f64> {
+ Ok(x.cos())
}
-fn builtin_tan(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "tan", args, 1, [
- 0, x: ty!(number) => Val::Num;
- ], {
- Ok(Val::Num(x.tan()))
- })
+#[jrsonnet_macros::builtin]
+fn builtin_tan(x: f64) -> Result<f64> {
+ Ok(x.tan())
}
-fn builtin_asin(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "asin", args, 1, [
- 0, x: ty!(number) => Val::Num;
- ], {
- Ok(Val::Num(x.asin()))
- })
+#[jrsonnet_macros::builtin]
+fn builtin_asin(x: f64) -> Result<f64> {
+ Ok(x.asin())
}
-fn builtin_acos(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "acos", args, 1, [
- 0, x: ty!(number) => Val::Num;
- ], {
- Ok(Val::Num(x.acos()))
- })
+#[jrsonnet_macros::builtin]
+fn builtin_acos(x: f64) -> Result<f64> {
+ Ok(x.acos())
}
-fn builtin_atan(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "atan", args, 1, [
- 0, x: ty!(number) => Val::Num;
- ], {
- Ok(Val::Num(x.atan()))
- })
+#[jrsonnet_macros::builtin]
+fn builtin_atan(x: f64) -> Result<f64> {
+ Ok(x.atan())
}
-fn builtin_exp(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "exp", args, 1, [
- 0, x: ty!(number) => Val::Num;
- ], {
- Ok(Val::Num(x.exp()))
- })
+#[jrsonnet_macros::builtin]
+fn builtin_exp(x: f64) -> Result<f64> {
+ Ok(x.exp())
}
fn frexp(s: f64) -> (f64, i16) {
@@ -411,198 +330,140 @@
}
}
-fn builtin_mantissa(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "mantissa", args, 1, [
- 0, x: ty!(number) => Val::Num;
- ], {
- Ok(Val::Num(frexp(x).0))
- })
+#[jrsonnet_macros::builtin]
+fn builtin_mantissa(x: f64) -> Result<f64> {
+ Ok(frexp(x).0)
}
-fn builtin_exponent(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "exponent", args, 1, [
- 0, x: ty!(number) => Val::Num;
- ], {
- Ok(Val::Num(frexp(x).1.into()))
- })
+#[jrsonnet_macros::builtin]
+fn builtin_exponent(x: f64) -> Result<i16> {
+ Ok(frexp(x).1)
}
-fn builtin_ext_var(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "extVar", args, 1, [
- 0, x: ty!(string) => Val::Str;
- ], {
- Ok(with_state(|s| s.settings().ext_vars.get(&x).cloned()).ok_or(UndefinedExternalVariable(x))?)
- })
+#[jrsonnet_macros::builtin]
+fn builtin_ext_var(x: IStr) -> Result<Any> {
+ Ok(Any(with_state(|s| s.settings().ext_vars.get(&x).cloned())
+ .ok_or(UndefinedExternalVariable(x))?))
}
-fn builtin_native(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "native", args, 1, [
- 0, x: ty!(string) => Val::Str;
- ], {
- Ok(with_state(|s| s.settings().ext_natives.get(&x).cloned()).map(|v| Val::Func(Cc::new(FuncVal::NativeExt(x.clone(), v)))).ok_or(UndefinedExternalFunction(x))?)
- })
+#[jrsonnet_macros::builtin]
+fn builtin_native(name: IStr) -> Result<Cc<FuncVal>> {
+ Ok(with_state(|s| s.settings().ext_natives.get(&name).cloned())
+ .map(|v| Cc::new(FuncVal::NativeExt(name.clone(), v)))
+ .ok_or(UndefinedExternalFunction(name))?)
}
-fn builtin_filter(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "filter", args, 2, [
- 0, func: ty!(function) => Val::Func;
- 1, arr: ty!(array) => Val::Arr;
- ], {
- Ok(Val::Arr(arr.filter(|val| func
- .evaluate_values(context.clone(), &[val.clone()])?
- .try_cast_bool("filter predicate"))?))
- })
+#[jrsonnet_macros::builtin]
+fn builtin_filter(func: Cc<FuncVal>, arr: ArrValue) -> Result<ArrValue> {
+ arr.filter(|val| bool::try_from(func.evaluate_values(&[val.clone()])?))
}
-fn builtin_map(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "map", args, 2, [
- 0, func: ty!(function) => Val::Func;
- 1, arr: ty!(array) => Val::Arr;
- ], {
- Ok(Val::Arr(arr.map(|val| func
- .evaluate_values(context.clone(), &[val]))?))
- })
+#[jrsonnet_macros::builtin]
+fn builtin_map(func: Cc<FuncVal>, arr: ArrValue) -> Result<ArrValue> {
+ arr.map(|val| func.evaluate_values(&[val]))
}
-fn builtin_flatmap(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "flatMap", args, 2, [
- 0, func: ty!(function) => Val::Func;
- 1, arr: ty!((array | string));
- ], {
- match arr {
- Val::Str(s) => {
- let mut out = String::new();
- for c in s.chars() {
- match func.evaluate_values(context.clone(), &[Val::Str(c.to_string().into())])? {
- Val::Str(o) => out.push_str(&o),
- _ => throw!(RuntimeError("in std.join all items should be strings".into())),
- };
- }
- Ok(Val::Str(out.into()))
- },
- Val::Arr(a) => {
- let mut out = Vec::new();
- for el in a.iter() {
- let el = el?;
- match func.evaluate_values(context.clone(), &[el])? {
- Val::Arr(o) => for oe in o.iter() {
+#[jrsonnet_macros::builtin]
+fn builtin_flatmap(func: Cc<FuncVal>, arr: IndexableVal) -> Result<IndexableVal> {
+ match arr {
+ IndexableVal::Str(s) => {
+ let mut out = String::new();
+ for c in s.chars() {
+ match func.evaluate_values(&[Val::Str(c.to_string().into())])? {
+ Val::Str(o) => out.push_str(&o),
+ _ => throw!(RuntimeError(
+ "in std.join all items should be strings".into()
+ )),
+ };
+ }
+ Ok(IndexableVal::Str(out.into()))
+ }
+ IndexableVal::Arr(a) => {
+ let mut out = Vec::new();
+ for el in a.iter() {
+ let el = el?;
+ match func.evaluate_values(&[el])? {
+ Val::Arr(o) => {
+ for oe in o.iter() {
out.push(oe?)
- },
- _ => throw!(RuntimeError("in std.join all items should be arrays".into())),
- };
- }
- Ok(Val::Arr(out.into()))
- },
- _ => unreachable!(),
+ }
+ }
+ _ => throw!(RuntimeError(
+ "in std.join all items should be arrays".into()
+ )),
+ };
+ }
+ Ok(IndexableVal::Arr(out.into()))
}
- })
+ }
}
-fn builtin_foldl(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "foldl", args, 3, [
- 0, func: ty!(function) => Val::Func;
- 1, arr: ty!(array) => Val::Arr;
- 2, init: ty!(any);
- ], {
- let mut acc = init;
- for i in arr.iter() {
- acc = func.evaluate_values(context.clone(), &[acc, i?])?;
- }
- Ok(acc)
- })
+#[jrsonnet_macros::builtin]
+fn builtin_foldl(func: Cc<FuncVal>, arr: ArrValue, init: Any) -> Result<Any> {
+ let mut acc = init.0;
+ for i in arr.iter() {
+ acc = func.evaluate_values(&[acc, i?])?;
+ }
+ Ok(Any(acc))
}
-fn builtin_foldr(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "foldr", args, 3, [
- 0, func: ty!(function) => Val::Func;
- 1, arr: ty!(array) => Val::Arr;
- 2, init: ty!(any);
- ], {
- let mut acc = init;
- for i in arr.iter().rev() {
- acc = func.evaluate_values(context.clone(), &[i?, acc])?;
- }
- Ok(acc)
- })
+#[jrsonnet_macros::builtin]
+fn builtin_foldr(func: Cc<FuncVal>, arr: ArrValue, init: Any) -> Result<Any> {
+ let mut acc = init.0;
+ for i in arr.iter().rev() {
+ acc = func.evaluate_values(&[i?, acc])?;
+ }
+ Ok(Any(acc))
}
+#[jrsonnet_macros::builtin]
#[allow(non_snake_case)]
-fn builtin_sort_impl(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "sort", args, 2, [
- 0, arr: ty!(array) => Val::Arr;
- 1, keyF: ty!(function) => Val::Func;
- ], {
- if arr.len() <= 1 {
- return Ok(Val::Arr(arr))
- }
- Ok(Val::Arr(ArrValue::Eager(sort::sort(context, arr.evaluated()?, &keyF)?)))
- })
+fn builtin_sort_impl(arr: ArrValue, keyF: Cc<FuncVal>) -> Result<ArrValue> {
+ if arr.len() <= 1 {
+ return Ok(arr);
+ }
+ Ok(ArrValue::Eager(sort::sort(arr.evaluated()?, &keyF)?))
}
-fn builtin_format(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "format", args, 2, [
- 0, str: ty!(string) => Val::Str;
- 1, vals: ty!(any)
- ], {
- std_format(str, vals)
- })
+#[jrsonnet_macros::builtin]
+fn builtin_format(str: IStr, vals: Any) -> Result<String> {
+ std_format(str, vals.0)
}
-fn builtin_range(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "range", args, 2, [
- 0, from: ty!(number) => Val::Num;
- 1, to: ty!(number) => Val::Num;
- ], {
- if to < from {
- return Ok(Val::Arr(ArrValue::new_eager()))
- }
- let mut out = Vec::with_capacity((1+to as usize-from as usize).max(0));
- for i in from as usize..=to as usize {
- out.push(Val::Num(i as f64));
- }
- Ok(Val::Arr(out.into()))
- })
+#[jrsonnet_macros::builtin]
+fn builtin_range(from: i32, to: i32) -> Result<VecVal> {
+ if to < from {
+ return Ok(VecVal(Vec::new()));
+ }
+ let mut out = Vec::with_capacity((1 + to as usize - from as usize).max(0));
+ for i in from as usize..=to as usize {
+ out.push(Val::Num(i as f64));
+ }
+ Ok(VecVal(out))
}
-fn builtin_char(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "char", args, 1, [
- 0, n: ty!(number) => Val::Num;
- ], {
- let mut out = String::new();
- out.push(std::char::from_u32(n as u32).ok_or_else(||
- InvalidUnicodeCodepointGot(n as u32)
- )?);
- Ok(Val::Str(out.into()))
- })
+#[jrsonnet_macros::builtin]
+fn builtin_char(n: u32) -> Result<char> {
+ Ok(std::char::from_u32(n as u32).ok_or_else(|| InvalidUnicodeCodepointGot(n as u32))?)
}
-fn builtin_encode_utf8(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "encodeUTF8", args, 1, [
- 0, str: ty!(string) => Val::Str;
- ], {
- Ok(Val::Arr((str.bytes().map(|b| Val::Num(b as f64)).collect::<Vec<Val>>()).into()))
- })
+#[jrsonnet_macros::builtin]
+fn builtin_encode_utf8(str: IStr) -> Result<VecVal> {
+ Ok(VecVal(
+ str.bytes()
+ .map(|b| Val::Num(b as f64))
+ .collect::<Vec<Val>>(),
+ ))
}
-fn builtin_decode_utf8(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "decodeUTF8", args, 1, [
- 0, arr: ty!((Array<ubyte>)) => Val::Arr;
- ], {
- let data: Result<Vec<u8>> = arr.iter().map(|v| v.map(|v| match v{
- Val::Num(n) => n as u8,
- _ => unreachable!(),
- })).collect();
- let data = data?;
- Ok(Val::Str(String::from_utf8(data).map_err(|_| RuntimeError("bad utf8".into()))?.into()))
- })
+#[jrsonnet_macros::builtin]
+fn builtin_decode_utf8(arr: Vec<u8>) -> Result<String> {
+ Ok(String::from_utf8(arr).map_err(|_| RuntimeError("bad utf8".into()))?)
}
-fn builtin_md5(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "md5", args, 1, [
- 0, str: ty!(string) => Val::Str;
- ], {
- Ok(Val::Str(format!("{:x}", md5::compute(&str.as_bytes())).into()))
- })
+#[jrsonnet_macros::builtin]
+fn builtin_md5(str: IStr) -> Result<String> {
+ Ok(format!("{:x}", md5::compute(&str.as_bytes())))
}
fn builtin_trace(context: Context, loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
@@ -620,251 +481,174 @@
})
}
-fn builtin_base64(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "base64", args, 1, [
- 0, input: ty!((string | (Array<number>)));
- ], {
- Ok(Val::Str(match input {
- Val::Str(s) => {
- base64::encode(s.bytes().collect::<Vec<_>>()).into()
- },
- Val::Arr(a) => {
- base64::encode(a.iter().map(|v| {
- Ok(v?.unwrap_num()? as u8)
- }).collect::<Result<Vec<_>>>()?).into()
- },
- _ => unreachable!()
- }))
+#[jrsonnet_macros::builtin]
+fn builtin_base64(input: Either<Vec<u8>, IStr>) -> Result<String> {
+ Ok(match input {
+ Either::Left(a) => base64::encode(a),
+ Either::Right(l) => base64::encode(l.bytes().collect::<Vec<_>>()),
})
}
-fn builtin_base64_decode_bytes(
- context: Context,
- _loc: &ExprLocation,
- args: &ArgsDesc,
-) -> Result<Val> {
- parse_args!(context, "base64DecodeBytes", args, 1, [
- 0, input: ty!(string) => Val::Str;
- ], {
- Ok(Val::Arr(
- base64::decode(&input.as_bytes())
- .map_err(|_| RuntimeError("bad base64".into()))?
- .iter()
- .map(|v| Val::Num(*v as f64)).collect::<Vec<_>>().into()
- ))
- })
+#[jrsonnet_macros::builtin]
+fn builtin_base64_decode_bytes(input: IStr) -> Result<Vec<u8>> {
+ Ok(base64::decode(&input.as_bytes()).map_err(|_| RuntimeError("bad base64".into()))?)
}
-fn builtin_base64_decode(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "base64Decode", args, 1, [
- 0, input: ty!(string) => Val::Str;
- ], {
- Ok(Val::Str(
- String::from_utf8(base64::decode(&input.as_bytes())
- .map_err(|_| RuntimeError("bad base64".into()))?)
- .map_err(|_| RuntimeError("bad utf8".into()))?.into()
- ))
- })
+#[jrsonnet_macros::builtin]
+fn builtin_base64_decode(input: IStr) -> Result<String> {
+ let bytes = base64::decode(&input.as_bytes()).map_err(|_| RuntimeError("bad base64".into()))?;
+ Ok(String::from_utf8(bytes).map_err(|_| RuntimeError("bad utf8".into()))?)
}
-fn builtin_join(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "join", args, 2, [
- 0, sep: ty!((string | array));
- 1, arr: ty!(array) => Val::Arr;
- ], {
- Ok(match sep {
- Val::Arr(joiner_items) => {
- let mut out = Vec::new();
+#[jrsonnet_macros::builtin]
+fn builtin_join(sep: IndexableVal, arr: ArrValue) -> Result<IndexableVal> {
+ Ok(match sep {
+ IndexableVal::Arr(joiner_items) => {
+ let mut out = Vec::new();
- let mut first = true;
- for item in arr.iter() {
- let item = item?.clone();
- if let Val::Arr(items) = item {
- if !first {
- out.reserve(joiner_items.len());
- // TODO: extend
- for item in joiner_items.iter() {
- out.push(item?);
- }
- }
- first = false;
- out.reserve(items.len());
+ let mut first = true;
+ for item in arr.iter() {
+ let item = item?.clone();
+ if let Val::Arr(items) = item {
+ if !first {
+ out.reserve(joiner_items.len());
// TODO: extend
- for item in items.iter() {
+ for item in joiner_items.iter() {
out.push(item?);
}
- } else {
- throw!(RuntimeError("in std.join all items should be arrays".into()));
}
+ first = false;
+ out.reserve(items.len());
+ // TODO: extend
+ for item in items.iter() {
+ out.push(item?);
+ }
+ } else {
+ throw!(RuntimeError(
+ "in std.join all items should be arrays".into()
+ ));
}
+ }
- Val::Arr(out.into())
- },
- Val::Str(sep) => {
- let mut out = String::new();
+ IndexableVal::Arr(out.into())
+ }
+ IndexableVal::Str(sep) => {
+ let mut out = String::new();
- let mut first = true;
- for item in arr.iter() {
- let item = item?.clone();
- if let Val::Str(item) = item {
- if !first {
- out += &sep;
- }
- first = false;
- out += &item;
- } else {
- throw!(RuntimeError("in std.join all items should be strings".into()));
+ let mut first = true;
+ for item in arr.iter() {
+ let item = item?.clone();
+ if let Val::Str(item) = item {
+ if !first {
+ out += &sep;
}
+ first = false;
+ out += &item;
+ } else {
+ throw!(RuntimeError(
+ "in std.join all items should be strings".into()
+ ));
}
+ }
- Val::Str(out.into())
- },
- _ => unreachable!()
- })
+ IndexableVal::Str(out.into())
+ }
})
}
-fn builtin_escape_string_json(
- context: Context,
- _loc: &ExprLocation,
- args: &ArgsDesc,
-) -> Result<Val> {
- parse_args!(context, "escapeStringJson", args, 1, [
- 0, str_: ty!(string) => Val::Str;
- ], {
- Ok(Val::Str(escape_string_json(&str_).into()))
- })
+#[jrsonnet_macros::builtin]
+fn builtin_escape_string_json(str_: IStr) -> Result<String> {
+ Ok(escape_string_json(&str_))
}
-fn builtin_manifest_json_ex(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "manifestJsonEx", args, 2, [
- 0, value: ty!(any);
- 1, indent: ty!(string) => Val::Str;
- ], {
- Ok(Val::Str(manifest_json_ex(&value, &ManifestJsonOptions {
+#[jrsonnet_macros::builtin]
+fn builtin_manifest_json_ex(value: Any, indent: IStr) -> Result<String> {
+ manifest_json_ex(
+ &value.0,
+ &ManifestJsonOptions {
padding: &indent,
mtype: ManifestType::Std,
- })?.into()))
- })
+ },
+ )
}
+#[jrsonnet_macros::builtin]
fn builtin_manifest_yaml_doc(
- context: Context,
- _loc: &ExprLocation,
- args: &ArgsDesc,
-) -> Result<Val> {
- parse_args!(context, "manifestYamlDoc", args, 3, [
- 0, value: ty!(any);
- 1, indent_array_in_object: ty!(boolean) => Val::Bool;
- 2, quote_keys: ty!(boolean) => Val::Bool;
- ], {
- Ok(Val::Str(manifest_yaml_ex(&value, &ManifestYamlOptions {
+ value: Any,
+ indent_array_in_object: bool,
+ quote_keys: bool,
+) -> Result<String> {
+ manifest_yaml_ex(
+ &value.0,
+ &ManifestYamlOptions {
padding: " ",
arr_element_padding: if indent_array_in_object { " " } else { "" },
quote_keys,
- })?.into()))
- })
+ },
+ )
}
-fn builtin_reverse(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "reverse", args, 1, [
- 0, value: ty!(array) => Val::Arr;
- ], {
- Ok(Val::Arr(value.reversed()))
- })
+#[jrsonnet_macros::builtin]
+fn builtin_reverse(value: ArrValue) -> Result<ArrValue> {
+ Ok(value.reversed())
}
-fn builtin_id(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "id", args, 1, [
- 0, v: ty!(any);
- ], {
- Ok(v)
- })
+#[jrsonnet_macros::builtin]
+const fn builtin_id(v: Any) -> Result<Any> {
+ Ok(v)
}
-fn builtin_str_replace(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "strReplace", args, 3, [
- 0, str: ty!(string) => Val::Str;
- 1, from: ty!(string) => Val::Str;
- 2, to: ty!(string) => Val::Str;
- ], {
- Ok(Val::Str(str.replace(&from as &str, &to as &str).into()))
- })
+#[jrsonnet_macros::builtin]
+fn builtin_str_replace(str: String, from: IStr, to: IStr) -> Result<String> {
+ Ok(str.replace(&from as &str, &to as &str))
}
-
-fn builtin_splitlimit(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "splitLimit", args, 3, [
- 0, str: ty!(string) => Val::Str;
- 1, c: ty!(char) => Val::Str;
- 2, maxsplits: ty!(number) => Val::Num;
- ], {
- let maxsplits = maxsplits as isize;
- let c = c.chars().next().unwrap();
- let out: Vec<Val> = if maxsplits == -1 {
- str.split(c).map(|s| Val::Str(s.into())).collect()
- } else {
- str.splitn(maxsplits as usize + 1, c).map(|s| Val::Str(s.into())).collect()
- };
-
- Ok(Val::Arr(out.into()))
- })
+#[jrsonnet_macros::builtin]
+fn builtin_splitlimit(str: IStr, c: char, maxsplits: Either<usize, M1>) -> Result<VecVal> {
+ Ok(VecVal(match maxsplits {
+ Either::Left(n) => str.splitn(n + 1, c).map(|s| Val::Str(s.into())).collect(),
+ Either::Right(_) => str.split(c).map(|s| Val::Str(s.into())).collect(),
+ }))
}
-fn builtin_ascii_upper(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "asciiUpper", args, 1, [
- 0, str: ty!(string) => Val::Str;
- ], {
- Ok(Val::Str(str.to_ascii_uppercase().into()))
- })
+#[jrsonnet_macros::builtin]
+fn builtin_ascii_upper(str: IStr) -> Result<String> {
+ Ok(str.to_ascii_uppercase())
}
-fn builtin_ascii_lower(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "asciiLower", args, 1, [
- 0, str: ty!(string) => Val::Str;
- ], {
- Ok(Val::Str(str.to_ascii_lowercase().into()))
- })
+#[jrsonnet_macros::builtin]
+fn builtin_ascii_lower(str: IStr) -> Result<String> {
+ Ok(str.to_ascii_lowercase())
}
-fn builtin_member(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "member", args, 2, [
- 0, arr: ty!((array | string));
- 1, x: ty!(any);
- ], {
- match arr {
- Val::Str(s) => {
- let x = x.try_cast_str("x should be string")?;
- Ok(Val::Bool(!x.is_empty() && s.contains(&*x)))
- }
- Val::Arr(a) => {
- for item in a.iter() {
- let item = item?;
- if equals(&item, &x)? {
- return Ok(Val::Bool(true));
- }
+#[jrsonnet_macros::builtin]
+fn builtin_member(arr: IndexableVal, x: Any) -> Result<bool> {
+ match arr {
+ IndexableVal::Str(s) => {
+ let x: IStr = IStr::try_from(x.0)?;
+ Ok(!x.is_empty() && s.contains(&*x))
+ }
+ IndexableVal::Arr(a) => {
+ for item in a.iter() {
+ let item = item?;
+ if equals(&item, &x.0)? {
+ return Ok(true);
}
- Ok(Val::Bool(false))
}
- _ => unreachable!(),
+ Ok(false)
}
- })
+ }
}
-fn builtin_count(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "count", args, 2, [
- 0, arr: ty!(array) => Val::Arr;
- 1, x: ty!(any);
- ], {
- let mut count = 0;
- for item in arr.iter() {
- let item = item?;
- if equals(&item, &x)? {
- count += 1;
- }
+#[jrsonnet_macros::builtin]
+fn builtin_count(arr: Vec<Any>, v: Any) -> Result<usize> {
+ let mut count = 0;
+ for item in arr.iter() {
+ if equals(&item.0, &v.0)? {
+ count += 1;
}
- Ok(Val::Num(count as f64))
- })
+ }
+ Ok(count)
}
pub fn call_builtin(
crates/jrsonnet-evaluator/src/builtin/sort.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/builtin/sort.rs
+++ b/crates/jrsonnet-evaluator/src/builtin/sort.rs
@@ -1,6 +1,6 @@
use crate::{
error::{Error, LocError, Result},
- throw, Context, FuncVal, Val,
+ throw, FuncVal, Val,
};
use gcmodule::{Cc, Trace};
@@ -59,7 +59,7 @@
Ok(sort_type)
}
-pub fn sort(ctx: Context, values: Cc<Vec<Val>>, key_getter: &FuncVal) -> Result<Cc<Vec<Val>>> {
+pub fn sort(values: Cc<Vec<Val>>, key_getter: &FuncVal) -> Result<Cc<Vec<Val>>> {
if values.len() <= 1 {
return Ok(values);
}
@@ -81,10 +81,7 @@
} else {
let mut vk = Vec::with_capacity(values.len());
for value in values.iter() {
- vk.push((
- value.clone(),
- key_getter.evaluate_values(ctx.clone(), &[value.clone()])?,
- ));
+ vk.push((value.clone(), key_getter.evaluate_values(&[value.clone()])?));
}
let sort_type = get_sort_type(&mut vk, |v| &mut v.1)?;
match sort_type {
crates/jrsonnet-evaluator/src/evaluate/mod.rsdiffbeforeafterboth1use crate::{2 builtin::std_slice,3 error::Error::*,4 evaluate::operator::{evaluate_add_op, evaluate_binary_op_special, evaluate_unary_op},5 gc::TraceBox,6 push_frame, throw, with_state, ArrValue, Bindable, Context, ContextCreator, FuncDesc, FuncVal,7 FutureWrapper, GcHashMap, LazyBinding, LazyVal, LazyValValue, ObjValue, ObjValueBuilder,8 ObjectAssertion, Result, Val,9};10use gcmodule::{Cc, Trace};11use jrsonnet_interner::IStr;12use jrsonnet_parser::{13 ArgsDesc, AssertStmt, BindSpec, CompSpec, Expr, ExprLocation, FieldMember, ForSpecData,14 IfSpecData, LiteralType, LocExpr, Member, ObjBody, ParamsDesc,15};16use jrsonnet_types::ValType;17pub mod operator;1819pub fn evaluate_binding_in_future(20 b: &BindSpec,21 context_creator: FutureWrapper<Context>,22) -> LazyVal {23 let b = b.clone();24 if let Some(params) = &b.params {25 let params = params.clone();2627 #[derive(Trace)]28 struct LazyMethodBinding {29 context_creator: FutureWrapper<Context>,30 name: IStr,31 params: ParamsDesc,32 value: LocExpr,33 }34 impl LazyValValue for LazyMethodBinding {35 fn get(self: Box<Self>) -> Result<Val> {36 Ok(evaluate_method(37 self.context_creator.unwrap(),38 self.name,39 self.params,40 self.value,41 ))42 }43 }4445 LazyVal::new(TraceBox(Box::new(LazyMethodBinding {46 context_creator,47 name: b.name.clone(),48 params,49 value: b.value.clone(),50 })))51 } else {52 #[derive(Trace)]53 struct LazyNamedBinding {54 context_creator: FutureWrapper<Context>,55 name: IStr,56 value: LocExpr,57 }58 impl LazyValValue for LazyNamedBinding {59 fn get(self: Box<Self>) -> Result<Val> {60 evaluate_named(self.context_creator.unwrap(), &self.value, self.name)61 }62 }63 LazyVal::new(TraceBox(Box::new(LazyNamedBinding {64 context_creator,65 name: b.name.clone(),66 value: b.value,67 })))68 }69}7071pub fn evaluate_binding(b: &BindSpec, context_creator: ContextCreator) -> (IStr, LazyBinding) {72 let b = b.clone();73 if let Some(params) = &b.params {74 let params = params.clone();7576 #[derive(Trace)]77 struct BindableMethodLazyVal {78 this: Option<ObjValue>,79 super_obj: Option<ObjValue>,8081 context_creator: ContextCreator,82 name: IStr,83 params: ParamsDesc,84 value: LocExpr,85 }86 impl LazyValValue for BindableMethodLazyVal {87 fn get(self: Box<Self>) -> Result<Val> {88 Ok(evaluate_method(89 self.context_creator.create(self.this, self.super_obj)?,90 self.name,91 self.params,92 self.value,93 ))94 }95 }9697 #[derive(Trace)]98 struct BindableMethod {99 context_creator: ContextCreator,100 name: IStr,101 params: ParamsDesc,102 value: LocExpr,103 }104 impl Bindable for BindableMethod {105 fn bind(&self, this: Option<ObjValue>, super_obj: Option<ObjValue>) -> Result<LazyVal> {106 Ok(LazyVal::new(TraceBox(Box::new(BindableMethodLazyVal {107 this,108 super_obj,109110 context_creator: self.context_creator.clone(),111 name: self.name.clone(),112 params: self.params.clone(),113 value: self.value.clone(),114 }))))115 }116 }117118 (119 b.name.clone(),120 LazyBinding::Bindable(Cc::new(TraceBox(Box::new(BindableMethod {121 context_creator,122 name: b.name.clone(),123 params,124 value: b.value.clone(),125 })))),126 )127 } else {128 #[derive(Trace)]129 struct BindableNamedLazyVal {130 this: Option<ObjValue>,131 super_obj: Option<ObjValue>,132133 context_creator: ContextCreator,134 name: IStr,135 value: LocExpr,136 }137 impl LazyValValue for BindableNamedLazyVal {138 fn get(self: Box<Self>) -> Result<Val> {139 evaluate_named(140 self.context_creator.create(self.this, self.super_obj)?,141 &self.value,142 self.name,143 )144 }145 }146147 #[derive(Trace)]148 struct BindableNamed {149 context_creator: ContextCreator,150 name: IStr,151 value: LocExpr,152 }153 impl Bindable for BindableNamed {154 fn bind(&self, this: Option<ObjValue>, super_obj: Option<ObjValue>) -> Result<LazyVal> {155 Ok(LazyVal::new(TraceBox(Box::new(BindableNamedLazyVal {156 this,157 super_obj,158159 context_creator: self.context_creator.clone(),160 name: self.name.clone(),161 value: self.value.clone(),162 }))))163 }164 }165166 (167 b.name.clone(),168 LazyBinding::Bindable(Cc::new(TraceBox(Box::new(BindableNamed {169 context_creator,170 name: b.name.clone(),171 value: b.value.clone(),172 })))),173 )174 }175}176177pub fn evaluate_method(ctx: Context, name: IStr, params: ParamsDesc, body: LocExpr) -> Val {178 Val::Func(Cc::new(FuncVal::Normal(FuncDesc {179 name,180 ctx,181 params,182 body,183 })))184}185186pub fn evaluate_field_name(187 context: Context,188 field_name: &jrsonnet_parser::FieldName,189) -> Result<Option<IStr>> {190 Ok(match field_name {191 jrsonnet_parser::FieldName::Fixed(n) => Some(n.clone()),192 jrsonnet_parser::FieldName::Dyn(expr) => {193 let value = evaluate(context, expr)?;194 if matches!(value, Val::Null) {195 None196 } else {197 Some(value.try_cast_str("dynamic field name")?)198 }199 }200 })201}202203pub fn evaluate_comp(204 context: Context,205 specs: &[CompSpec],206 callback: &mut impl FnMut(Context) -> Result<()>,207) -> Result<()> {208 match specs.get(0) {209 None => callback(context)?,210 Some(CompSpec::IfSpec(IfSpecData(cond))) => {211 if evaluate(context.clone(), cond)?.try_cast_bool("if spec")? {212 evaluate_comp(context, &specs[1..], callback)?213 }214 }215 Some(CompSpec::ForSpec(ForSpecData(var, expr))) => match evaluate(context.clone(), expr)? {216 Val::Arr(list) => {217 for item in list.iter() {218 evaluate_comp(219 context.clone().with_var(var.clone(), item?.clone()),220 &specs[1..],221 callback,222 )?223 }224 }225 _ => throw!(InComprehensionCanOnlyIterateOverArray),226 },227 }228 Ok(())229}230231pub fn evaluate_member_list_object(context: Context, members: &[Member]) -> Result<ObjValue> {232 let new_bindings = FutureWrapper::new();233 let future_this = FutureWrapper::new();234 let context_creator = ContextCreator(context.clone(), new_bindings.clone());235 {236 let mut bindings: GcHashMap<IStr, LazyBinding> = GcHashMap::with_capacity(members.len());237 for (n, b) in members238 .iter()239 .filter_map(|m| match m {240 Member::BindStmt(b) => Some(b.clone()),241 _ => None,242 })243 .map(|b| evaluate_binding(&b, context_creator.clone()))244 {245 bindings.insert(n, b);246 }247 new_bindings.fill(bindings);248 }249250 let mut builder = ObjValueBuilder::new();251 for member in members.iter() {252 match member {253 Member::Field(FieldMember {254 name,255 plus,256 params: None,257 visibility,258 value,259 }) => {260 let name = evaluate_field_name(context.clone(), name)?;261 if name.is_none() {262 continue;263 }264 let name = name.unwrap();265266 #[derive(Trace)]267 struct ObjMemberBinding {268 context_creator: ContextCreator,269 value: LocExpr,270 name: IStr,271 }272 impl Bindable for ObjMemberBinding {273 fn bind(274 &self,275 this: Option<ObjValue>,276 super_obj: Option<ObjValue>,277 ) -> Result<LazyVal> {278 Ok(LazyVal::new_resolved(evaluate_named(279 self.context_creator.create(this, super_obj)?,280 &self.value,281 self.name.clone(),282 )?))283 }284 }285 builder286 .member(name.clone())287 .with_add(*plus)288 .with_visibility(*visibility)289 .with_location(value.1.clone())290 .bindable(TraceBox(Box::new(ObjMemberBinding {291 context_creator: context_creator.clone(),292 value: value.clone(),293 name,294 })));295 }296 Member::Field(FieldMember {297 name,298 params: Some(params),299 value,300 ..301 }) => {302 let name = evaluate_field_name(context.clone(), name)?;303 if name.is_none() {304 continue;305 }306 let name = name.unwrap();307 #[derive(Trace)]308 struct ObjMemberBinding {309 context_creator: ContextCreator,310 value: LocExpr,311 params: ParamsDesc,312 name: IStr,313 }314 impl Bindable for ObjMemberBinding {315 fn bind(316 &self,317 this: Option<ObjValue>,318 super_obj: Option<ObjValue>,319 ) -> Result<LazyVal> {320 Ok(LazyVal::new_resolved(evaluate_method(321 self.context_creator.create(this, super_obj)?,322 self.name.clone(),323 self.params.clone(),324 self.value.clone(),325 )))326 }327 }328 builder329 .member(name.clone())330 .hide()331 .with_location(value.1.clone())332 .bindable(TraceBox(Box::new(ObjMemberBinding {333 context_creator: context_creator.clone(),334 value: value.clone(),335 params: params.clone(),336 name,337 })));338 }339 Member::BindStmt(_) => {}340 Member::AssertStmt(stmt) => {341 #[derive(Trace)]342 struct ObjectAssert {343 context_creator: ContextCreator,344 assert: AssertStmt,345 }346 impl ObjectAssertion for ObjectAssert {347 fn run(348 &self,349 this: Option<ObjValue>,350 super_obj: Option<ObjValue>,351 ) -> Result<()> {352 let ctx = self.context_creator.create(this, super_obj)?;353 evaluate_assert(ctx, &self.assert)354 }355 }356 builder.assert(TraceBox(Box::new(ObjectAssert {357 context_creator: context_creator.clone(),358 assert: stmt.clone(),359 })));360 }361 }362 }363 let this = builder.build();364 future_this.fill(this.clone());365 Ok(this)366}367368pub fn evaluate_object(context: Context, object: &ObjBody) -> Result<ObjValue> {369 Ok(match object {370 ObjBody::MemberList(members) => evaluate_member_list_object(context, members)?,371 ObjBody::ObjComp(obj) => {372 let future_this = FutureWrapper::new();373 let mut builder = ObjValueBuilder::new();374 evaluate_comp(context.clone(), &obj.compspecs, &mut |ctx| {375 let new_bindings = FutureWrapper::new();376 let context_creator = ContextCreator(context.clone(), new_bindings.clone());377 let mut bindings: GcHashMap<IStr, LazyBinding> =378 GcHashMap::with_capacity(obj.pre_locals.len() + obj.post_locals.len());379 for (n, b) in obj380 .pre_locals381 .iter()382 .chain(obj.post_locals.iter())383 .map(|b| evaluate_binding(b, context_creator.clone()))384 {385 bindings.insert(n, b);386 }387 new_bindings.fill(bindings.clone());388 let ctx = ctx.extend_unbound(bindings, None, None, None)?;389 let key = evaluate(ctx.clone(), &obj.key)?;390391 match key {392 Val::Null => {}393 Val::Str(n) => {394 #[derive(Trace)]395 struct ObjCompBinding {396 context: Context,397 value: LocExpr,398 }399 impl Bindable for ObjCompBinding {400 fn bind(401 &self,402 this: Option<ObjValue>,403 _super_obj: Option<ObjValue>,404 ) -> Result<LazyVal> {405 Ok(LazyVal::new_resolved(evaluate(406 self.context407 .clone()408 .extend(GcHashMap::new(), None, this, None),409 &self.value,410 )?))411 }412 }413 builder414 .member(n)415 .with_location(obj.value.1.clone())416 .with_add(obj.plus)417 .bindable(TraceBox(Box::new(ObjCompBinding {418 context: ctx,419 value: obj.value.clone(),420 })));421 }422 v => throw!(FieldMustBeStringGot(v.value_type())),423 }424425 Ok(())426 })?;427428 let this = builder.build();429 future_this.fill(this.clone());430 this431 }432 })433}434435pub fn evaluate_apply(436 context: Context,437 value: &LocExpr,438 args: &ArgsDesc,439 loc: &ExprLocation,440 tailstrict: bool,441) -> Result<Val> {442 let value = evaluate(context.clone(), value)?;443 Ok(match value {444 Val::Func(f) => {445 let body = || f.evaluate(context, loc, args, tailstrict);446 if tailstrict {447 body()?448 } else {449 push_frame(loc, || format!("function <{}> call", f.name()), body)?450 }451 }452 v => throw!(OnlyFunctionsCanBeCalledGot(v.value_type())),453 })454}455456pub fn evaluate_assert(context: Context, assertion: &AssertStmt) -> Result<()> {457 let value = &assertion.0;458 let msg = &assertion.1;459 let assertion_result = push_frame(460 &value.1,461 || "assertion condition".to_owned(),462 || {463 evaluate(context.clone(), value)?464 .try_cast_bool("assertion condition should be of type `boolean`")465 },466 )?;467 if !assertion_result {468 push_frame(469 &value.1,470 || "assertion failure".to_owned(),471 || {472 if let Some(msg) = msg {473 throw!(AssertionFailed(evaluate(context, msg)?.to_string()?));474 } else {475 throw!(AssertionFailed(Val::Null.to_string()?));476 }477 },478 )?479 }480 Ok(())481}482483pub fn evaluate_named(context: Context, lexpr: &LocExpr, name: IStr) -> Result<Val> {484 use Expr::*;485 let LocExpr(expr, _loc) = lexpr;486 Ok(match &**expr {487 Function(params, body) => evaluate_method(context, name, params.clone(), body.clone()),488 _ => evaluate(context, lexpr)?,489 })490}491492pub fn evaluate(context: Context, expr: &LocExpr) -> Result<Val> {493 use Expr::*;494 let LocExpr(expr, loc) = expr;495 // let bp = with_state(|s| s.0.stop_at.borrow().clone());496 Ok(match &**expr {497 Literal(LiteralType::This) => {498 Val::Obj(context.this().clone().ok_or(CantUseSelfOutsideOfObject)?)499 }500 Literal(LiteralType::Super) => Val::Obj(501 context502 .super_obj()503 .clone()504 .ok_or(NoSuperFound)?505 .with_this(context.this().clone().unwrap()),506 ),507 Literal(LiteralType::Dollar) => {508 Val::Obj(context.dollar().clone().ok_or(NoTopLevelObjectFound)?)509 }510 Literal(LiteralType::True) => Val::Bool(true),511 Literal(LiteralType::False) => Val::Bool(false),512 Literal(LiteralType::Null) => Val::Null,513 Parened(e) => evaluate(context, e)?,514 Str(v) => Val::Str(v.clone()),515 Num(v) => Val::new_checked_num(*v)?,516 BinaryOp(v1, o, v2) => evaluate_binary_op_special(context, v1, *o, v2)?,517 UnaryOp(o, v) => evaluate_unary_op(*o, &evaluate(context, v)?)?,518 Var(name) => push_frame(519 loc,520 || format!("variable <{}> access", name),521 || context.binding(name.clone())?.evaluate(),522 )?,523 Index(value, index) => {524 match (evaluate(context.clone(), value)?, evaluate(context, index)?) {525 (Val::Obj(v), Val::Str(s)) => {526 let sn = s.clone();527 push_frame(528 loc,529 || format!("field <{}> access", sn),530 || {531 if let Some(v) = v.get(s.clone())? {532 Ok(v)533 } else {534 throw!(NoSuchField(s))535 }536 },537 )?538 }539 (Val::Obj(_), n) => throw!(ValueIndexMustBeTypeGot(540 ValType::Obj,541 ValType::Str,542 n.value_type(),543 )),544545 (Val::Arr(v), Val::Num(n)) => {546 if n.fract() > f64::EPSILON {547 throw!(FractionalIndex)548 }549 v.get(n as usize)?550 .ok_or_else(|| ArrayBoundsError(n as usize, v.len()))?551 }552 (Val::Arr(_), Val::Str(n)) => throw!(AttemptedIndexAnArrayWithString(n)),553 (Val::Arr(_), n) => throw!(ValueIndexMustBeTypeGot(554 ValType::Arr,555 ValType::Num,556 n.value_type(),557 )),558559 (Val::Str(s), Val::Num(n)) => Val::Str(560 s.chars()561 .skip(n as usize)562 .take(1)563 .collect::<String>()564 .into(),565 ),566 (Val::Str(_), n) => throw!(ValueIndexMustBeTypeGot(567 ValType::Str,568 ValType::Num,569 n.value_type(),570 )),571572 (v, _) => throw!(CantIndexInto(v.value_type())),573 }574 }575 LocalExpr(bindings, returned) => {576 let mut new_bindings: GcHashMap<IStr, LazyVal> =577 GcHashMap::with_capacity(bindings.len());578 let future_context = Context::new_future();579 for b in bindings {580 new_bindings.insert(581 b.name.clone(),582 evaluate_binding_in_future(b, future_context.clone()),583 );584 }585 let context = context586 .extend_bound(new_bindings)587 .into_future(future_context);588 evaluate(context, &returned.clone())?589 }590 Arr(items) => {591 let mut out = Vec::with_capacity(items.len());592 for item in items {593 // TODO: Implement ArrValue::Lazy with same context for every element?594 #[derive(Trace)]595 struct ArrayElement {596 context: Context,597 item: LocExpr,598 }599 impl LazyValValue for ArrayElement {600 fn get(self: Box<Self>) -> Result<Val> {601 evaluate(self.context, &self.item)602 }603 }604 out.push(LazyVal::new(TraceBox(Box::new(ArrayElement {605 context: context.clone(),606 item: item.clone(),607 }))));608 }609 Val::Arr(out.into())610 }611 ArrComp(expr, comp_specs) => {612 let mut out = Vec::new();613 evaluate_comp(context, comp_specs, &mut |ctx| {614 out.push(evaluate(ctx, expr)?);615 Ok(())616 })?;617 Val::Arr(ArrValue::Eager(Cc::new(out)))618 }619 Obj(body) => Val::Obj(evaluate_object(context, body)?),620 ObjExtend(s, t) => evaluate_add_op(621 &evaluate(context.clone(), s)?,622 &Val::Obj(evaluate_object(context, t)?),623 )?,624 Apply(value, args, tailstrict) => evaluate_apply(context, value, args, loc, *tailstrict)?,625 Function(params, body) => {626 evaluate_method(context, "anonymous".into(), params.clone(), body.clone())627 }628 Intrinsic(name) => Val::Func(Cc::new(FuncVal::Intrinsic(name.clone()))),629 AssertExpr(assert, returned) => {630 evaluate_assert(context.clone(), assert)?;631 evaluate(context, returned)?632 }633 ErrorStmt(e) => push_frame(634 loc,635 || "error statement".to_owned(),636 || {637 throw!(RuntimeError(638 evaluate(context, e)?.try_cast_str("error text should be of type `string`")?,639 ))640 },641 )?,642 IfElse {643 cond,644 cond_then,645 cond_else,646 } => {647 if push_frame(648 loc,649 || "if condition".to_owned(),650 || evaluate(context.clone(), &cond.0)?.try_cast_bool("in if condition"),651 )? {652 evaluate(context, cond_then)?653 } else {654 match cond_else {655 Some(v) => evaluate(context, v)?,656 None => Val::Null,657 }658 }659 }660 Slice(value, desc) => {661 let indexable = evaluate(context.clone(), value)?;662663 fn parse_num(664 context: &Context,665 expr: Option<&LocExpr>,666 desc: &'static str,667 ) -> Result<Option<usize>> {668 Ok(match expr {669 Some(s) => evaluate(context.clone(), s)?670 .try_cast_nullable_num(desc)?671 .map(|v| v as usize),672 None => None,673 })674 }675676 let start = parse_num(&context, desc.start.as_ref(), "start")?;677 let end = parse_num(&context, desc.end.as_ref(), "end")?;678 let step = parse_num(&context, desc.step.as_ref(), "step")?;679680 std_slice(indexable.into_indexable()?, start, end, step)?681 }682 Import(path) => {683 let tmp = loc.clone().0;684 let mut import_location = tmp.to_path_buf();685 import_location.pop();686 push_frame(687 loc,688 || format!("import {:?}", path),689 || with_state(|s| s.import_file(&import_location, path)),690 )?691 }692 ImportStr(path) => {693 let tmp = loc.clone().0;694 let mut import_location = tmp.to_path_buf();695 import_location.pop();696 Val::Str(with_state(|s| s.import_file_str(&import_location, path))?)697 }698 })699}1use std::convert::TryFrom;23use crate::{4 builtin::std_slice,5 error::Error::*,6 evaluate::operator::{evaluate_add_op, evaluate_binary_op_special, evaluate_unary_op},7 gc::TraceBox,8 push_frame, throw, with_state, ArrValue, Bindable, Context, ContextCreator, FuncDesc, FuncVal,9 FutureWrapper, GcHashMap, LazyBinding, LazyVal, LazyValValue, ObjValue, ObjValueBuilder,10 ObjectAssertion, Result, Val,11};12use gcmodule::{Cc, Trace};13use jrsonnet_interner::IStr;14use jrsonnet_parser::{15 ArgsDesc, AssertStmt, BindSpec, CompSpec, Expr, ExprLocation, FieldMember, ForSpecData,16 IfSpecData, LiteralType, LocExpr, Member, ObjBody, ParamsDesc,17};18use jrsonnet_types::ValType;19pub mod operator;2021pub fn evaluate_binding_in_future(22 b: &BindSpec,23 context_creator: FutureWrapper<Context>,24) -> LazyVal {25 let b = b.clone();26 if let Some(params) = &b.params {27 let params = params.clone();2829 #[derive(Trace)]30 struct LazyMethodBinding {31 context_creator: FutureWrapper<Context>,32 name: IStr,33 params: ParamsDesc,34 value: LocExpr,35 }36 impl LazyValValue for LazyMethodBinding {37 fn get(self: Box<Self>) -> Result<Val> {38 Ok(evaluate_method(39 self.context_creator.unwrap(),40 self.name,41 self.params,42 self.value,43 ))44 }45 }4647 LazyVal::new(TraceBox(Box::new(LazyMethodBinding {48 context_creator,49 name: b.name.clone(),50 params,51 value: b.value.clone(),52 })))53 } else {54 #[derive(Trace)]55 struct LazyNamedBinding {56 context_creator: FutureWrapper<Context>,57 name: IStr,58 value: LocExpr,59 }60 impl LazyValValue for LazyNamedBinding {61 fn get(self: Box<Self>) -> Result<Val> {62 evaluate_named(self.context_creator.unwrap(), &self.value, self.name)63 }64 }65 LazyVal::new(TraceBox(Box::new(LazyNamedBinding {66 context_creator,67 name: b.name.clone(),68 value: b.value,69 })))70 }71}7273pub fn evaluate_binding(b: &BindSpec, context_creator: ContextCreator) -> (IStr, LazyBinding) {74 let b = b.clone();75 if let Some(params) = &b.params {76 let params = params.clone();7778 #[derive(Trace)]79 struct BindableMethodLazyVal {80 this: Option<ObjValue>,81 super_obj: Option<ObjValue>,8283 context_creator: ContextCreator,84 name: IStr,85 params: ParamsDesc,86 value: LocExpr,87 }88 impl LazyValValue for BindableMethodLazyVal {89 fn get(self: Box<Self>) -> Result<Val> {90 Ok(evaluate_method(91 self.context_creator.create(self.this, self.super_obj)?,92 self.name,93 self.params,94 self.value,95 ))96 }97 }9899 #[derive(Trace)]100 struct BindableMethod {101 context_creator: ContextCreator,102 name: IStr,103 params: ParamsDesc,104 value: LocExpr,105 }106 impl Bindable for BindableMethod {107 fn bind(&self, this: Option<ObjValue>, super_obj: Option<ObjValue>) -> Result<LazyVal> {108 Ok(LazyVal::new(TraceBox(Box::new(BindableMethodLazyVal {109 this,110 super_obj,111112 context_creator: self.context_creator.clone(),113 name: self.name.clone(),114 params: self.params.clone(),115 value: self.value.clone(),116 }))))117 }118 }119120 (121 b.name.clone(),122 LazyBinding::Bindable(Cc::new(TraceBox(Box::new(BindableMethod {123 context_creator,124 name: b.name.clone(),125 params,126 value: b.value.clone(),127 })))),128 )129 } else {130 #[derive(Trace)]131 struct BindableNamedLazyVal {132 this: Option<ObjValue>,133 super_obj: Option<ObjValue>,134135 context_creator: ContextCreator,136 name: IStr,137 value: LocExpr,138 }139 impl LazyValValue for BindableNamedLazyVal {140 fn get(self: Box<Self>) -> Result<Val> {141 evaluate_named(142 self.context_creator.create(self.this, self.super_obj)?,143 &self.value,144 self.name,145 )146 }147 }148149 #[derive(Trace)]150 struct BindableNamed {151 context_creator: ContextCreator,152 name: IStr,153 value: LocExpr,154 }155 impl Bindable for BindableNamed {156 fn bind(&self, this: Option<ObjValue>, super_obj: Option<ObjValue>) -> Result<LazyVal> {157 Ok(LazyVal::new(TraceBox(Box::new(BindableNamedLazyVal {158 this,159 super_obj,160161 context_creator: self.context_creator.clone(),162 name: self.name.clone(),163 value: self.value.clone(),164 }))))165 }166 }167168 (169 b.name.clone(),170 LazyBinding::Bindable(Cc::new(TraceBox(Box::new(BindableNamed {171 context_creator,172 name: b.name.clone(),173 value: b.value.clone(),174 })))),175 )176 }177}178179pub fn evaluate_method(ctx: Context, name: IStr, params: ParamsDesc, body: LocExpr) -> Val {180 Val::Func(Cc::new(FuncVal::Normal(FuncDesc {181 name,182 ctx,183 params,184 body,185 })))186}187188pub fn evaluate_field_name(189 context: Context,190 field_name: &jrsonnet_parser::FieldName,191) -> Result<Option<IStr>> {192 Ok(match field_name {193 jrsonnet_parser::FieldName::Fixed(n) => Some(n.clone()),194 jrsonnet_parser::FieldName::Dyn(expr) => push_frame(195 &expr.1,196 || "evaluating field name".to_string(),197 || {198 let value = evaluate(context, expr)?;199 if matches!(value, Val::Null) {200 Ok(None)201 } else {202 Ok(Some(IStr::try_from(value)?))203 }204 },205 )?,206 })207}208209pub fn evaluate_comp(210 context: Context,211 specs: &[CompSpec],212 callback: &mut impl FnMut(Context) -> Result<()>,213) -> Result<()> {214 match specs.get(0) {215 None => callback(context)?,216 Some(CompSpec::IfSpec(IfSpecData(cond))) => {217 if bool::try_from(evaluate(context.clone(), cond)?)? {218 evaluate_comp(context, &specs[1..], callback)?219 }220 }221 Some(CompSpec::ForSpec(ForSpecData(var, expr))) => match evaluate(context.clone(), expr)? {222 Val::Arr(list) => {223 for item in list.iter() {224 evaluate_comp(225 context.clone().with_var(var.clone(), item?.clone()),226 &specs[1..],227 callback,228 )?229 }230 }231 _ => throw!(InComprehensionCanOnlyIterateOverArray),232 },233 }234 Ok(())235}236237pub fn evaluate_member_list_object(context: Context, members: &[Member]) -> Result<ObjValue> {238 let new_bindings = FutureWrapper::new();239 let future_this = FutureWrapper::new();240 let context_creator = ContextCreator(context.clone(), new_bindings.clone());241 {242 let mut bindings: GcHashMap<IStr, LazyBinding> = GcHashMap::with_capacity(members.len());243 for (n, b) in members244 .iter()245 .filter_map(|m| match m {246 Member::BindStmt(b) => Some(b.clone()),247 _ => None,248 })249 .map(|b| evaluate_binding(&b, context_creator.clone()))250 {251 bindings.insert(n, b);252 }253 new_bindings.fill(bindings);254 }255256 let mut builder = ObjValueBuilder::new();257 for member in members.iter() {258 match member {259 Member::Field(FieldMember {260 name,261 plus,262 params: None,263 visibility,264 value,265 }) => {266 let name = evaluate_field_name(context.clone(), name)?;267 if name.is_none() {268 continue;269 }270 let name = name.unwrap();271272 #[derive(Trace)]273 struct ObjMemberBinding {274 context_creator: ContextCreator,275 value: LocExpr,276 name: IStr,277 }278 impl Bindable for ObjMemberBinding {279 fn bind(280 &self,281 this: Option<ObjValue>,282 super_obj: Option<ObjValue>,283 ) -> Result<LazyVal> {284 Ok(LazyVal::new_resolved(evaluate_named(285 self.context_creator.create(this, super_obj)?,286 &self.value,287 self.name.clone(),288 )?))289 }290 }291 builder292 .member(name.clone())293 .with_add(*plus)294 .with_visibility(*visibility)295 .with_location(value.1.clone())296 .bindable(TraceBox(Box::new(ObjMemberBinding {297 context_creator: context_creator.clone(),298 value: value.clone(),299 name,300 })));301 }302 Member::Field(FieldMember {303 name,304 params: Some(params),305 value,306 ..307 }) => {308 let name = evaluate_field_name(context.clone(), name)?;309 if name.is_none() {310 continue;311 }312 let name = name.unwrap();313 #[derive(Trace)]314 struct ObjMemberBinding {315 context_creator: ContextCreator,316 value: LocExpr,317 params: ParamsDesc,318 name: IStr,319 }320 impl Bindable for ObjMemberBinding {321 fn bind(322 &self,323 this: Option<ObjValue>,324 super_obj: Option<ObjValue>,325 ) -> Result<LazyVal> {326 Ok(LazyVal::new_resolved(evaluate_method(327 self.context_creator.create(this, super_obj)?,328 self.name.clone(),329 self.params.clone(),330 self.value.clone(),331 )))332 }333 }334 builder335 .member(name.clone())336 .hide()337 .with_location(value.1.clone())338 .bindable(TraceBox(Box::new(ObjMemberBinding {339 context_creator: context_creator.clone(),340 value: value.clone(),341 params: params.clone(),342 name,343 })));344 }345 Member::BindStmt(_) => {}346 Member::AssertStmt(stmt) => {347 #[derive(Trace)]348 struct ObjectAssert {349 context_creator: ContextCreator,350 assert: AssertStmt,351 }352 impl ObjectAssertion for ObjectAssert {353 fn run(354 &self,355 this: Option<ObjValue>,356 super_obj: Option<ObjValue>,357 ) -> Result<()> {358 let ctx = self.context_creator.create(this, super_obj)?;359 evaluate_assert(ctx, &self.assert)360 }361 }362 builder.assert(TraceBox(Box::new(ObjectAssert {363 context_creator: context_creator.clone(),364 assert: stmt.clone(),365 })));366 }367 }368 }369 let this = builder.build();370 future_this.fill(this.clone());371 Ok(this)372}373374pub fn evaluate_object(context: Context, object: &ObjBody) -> Result<ObjValue> {375 Ok(match object {376 ObjBody::MemberList(members) => evaluate_member_list_object(context, members)?,377 ObjBody::ObjComp(obj) => {378 let future_this = FutureWrapper::new();379 let mut builder = ObjValueBuilder::new();380 evaluate_comp(context.clone(), &obj.compspecs, &mut |ctx| {381 let new_bindings = FutureWrapper::new();382 let context_creator = ContextCreator(context.clone(), new_bindings.clone());383 let mut bindings: GcHashMap<IStr, LazyBinding> =384 GcHashMap::with_capacity(obj.pre_locals.len() + obj.post_locals.len());385 for (n, b) in obj386 .pre_locals387 .iter()388 .chain(obj.post_locals.iter())389 .map(|b| evaluate_binding(b, context_creator.clone()))390 {391 bindings.insert(n, b);392 }393 new_bindings.fill(bindings.clone());394 let ctx = ctx.extend_unbound(bindings, None, None, None)?;395 let key = evaluate(ctx.clone(), &obj.key)?;396397 match key {398 Val::Null => {}399 Val::Str(n) => {400 #[derive(Trace)]401 struct ObjCompBinding {402 context: Context,403 value: LocExpr,404 }405 impl Bindable for ObjCompBinding {406 fn bind(407 &self,408 this: Option<ObjValue>,409 _super_obj: Option<ObjValue>,410 ) -> Result<LazyVal> {411 Ok(LazyVal::new_resolved(evaluate(412 self.context413 .clone()414 .extend(GcHashMap::new(), None, this, None),415 &self.value,416 )?))417 }418 }419 builder420 .member(n)421 .with_location(obj.value.1.clone())422 .with_add(obj.plus)423 .bindable(TraceBox(Box::new(ObjCompBinding {424 context: ctx,425 value: obj.value.clone(),426 })));427 }428 v => throw!(FieldMustBeStringGot(v.value_type())),429 }430431 Ok(())432 })?;433434 let this = builder.build();435 future_this.fill(this.clone());436 this437 }438 })439}440441pub fn evaluate_apply(442 context: Context,443 value: &LocExpr,444 args: &ArgsDesc,445 loc: &ExprLocation,446 tailstrict: bool,447) -> Result<Val> {448 let value = evaluate(context.clone(), value)?;449 Ok(match value {450 Val::Func(f) => {451 let body = || f.evaluate(context, loc, args, tailstrict);452 if tailstrict {453 body()?454 } else {455 push_frame(loc, || format!("function <{}> call", f.name()), body)?456 }457 }458 v => throw!(OnlyFunctionsCanBeCalledGot(v.value_type())),459 })460}461462pub fn evaluate_assert(context: Context, assertion: &AssertStmt) -> Result<()> {463 let value = &assertion.0;464 let msg = &assertion.1;465 let assertion_result = push_frame(466 &value.1,467 || "assertion condition".to_owned(),468 || bool::try_from(evaluate(context.clone(), value)?),469 )?;470 if !assertion_result {471 push_frame(472 &value.1,473 || "assertion failure".to_owned(),474 || {475 if let Some(msg) = msg {476 throw!(AssertionFailed(evaluate(context, msg)?.to_string()?));477 } else {478 throw!(AssertionFailed(Val::Null.to_string()?));479 }480 },481 )?482 }483 Ok(())484}485486pub fn evaluate_named(context: Context, lexpr: &LocExpr, name: IStr) -> Result<Val> {487 use Expr::*;488 let LocExpr(expr, _loc) = lexpr;489 Ok(match &**expr {490 Function(params, body) => evaluate_method(context, name, params.clone(), body.clone()),491 _ => evaluate(context, lexpr)?,492 })493}494495pub fn evaluate(context: Context, expr: &LocExpr) -> Result<Val> {496 use Expr::*;497 let LocExpr(expr, loc) = expr;498 // let bp = with_state(|s| s.0.stop_at.borrow().clone());499 Ok(match &**expr {500 Literal(LiteralType::This) => {501 Val::Obj(context.this().clone().ok_or(CantUseSelfOutsideOfObject)?)502 }503 Literal(LiteralType::Super) => Val::Obj(504 context505 .super_obj()506 .clone()507 .ok_or(NoSuperFound)?508 .with_this(context.this().clone().unwrap()),509 ),510 Literal(LiteralType::Dollar) => {511 Val::Obj(context.dollar().clone().ok_or(NoTopLevelObjectFound)?)512 }513 Literal(LiteralType::True) => Val::Bool(true),514 Literal(LiteralType::False) => Val::Bool(false),515 Literal(LiteralType::Null) => Val::Null,516 Parened(e) => evaluate(context, e)?,517 Str(v) => Val::Str(v.clone()),518 Num(v) => Val::new_checked_num(*v)?,519 BinaryOp(v1, o, v2) => evaluate_binary_op_special(context, v1, *o, v2)?,520 UnaryOp(o, v) => evaluate_unary_op(*o, &evaluate(context, v)?)?,521 Var(name) => push_frame(522 loc,523 || format!("variable <{}> access", name),524 || context.binding(name.clone())?.evaluate(),525 )?,526 Index(value, index) => {527 match (evaluate(context.clone(), value)?, evaluate(context, index)?) {528 (Val::Obj(v), Val::Str(s)) => {529 let sn = s.clone();530 push_frame(531 loc,532 || format!("field <{}> access", sn),533 || {534 if let Some(v) = v.get(s.clone())? {535 Ok(v)536 } else {537 throw!(NoSuchField(s))538 }539 },540 )?541 }542 (Val::Obj(_), n) => throw!(ValueIndexMustBeTypeGot(543 ValType::Obj,544 ValType::Str,545 n.value_type(),546 )),547548 (Val::Arr(v), Val::Num(n)) => {549 if n.fract() > f64::EPSILON {550 throw!(FractionalIndex)551 }552 v.get(n as usize)?553 .ok_or_else(|| ArrayBoundsError(n as usize, v.len()))?554 }555 (Val::Arr(_), Val::Str(n)) => throw!(AttemptedIndexAnArrayWithString(n)),556 (Val::Arr(_), n) => throw!(ValueIndexMustBeTypeGot(557 ValType::Arr,558 ValType::Num,559 n.value_type(),560 )),561562 (Val::Str(s), Val::Num(n)) => Val::Str(563 s.chars()564 .skip(n as usize)565 .take(1)566 .collect::<String>()567 .into(),568 ),569 (Val::Str(_), n) => throw!(ValueIndexMustBeTypeGot(570 ValType::Str,571 ValType::Num,572 n.value_type(),573 )),574575 (v, _) => throw!(CantIndexInto(v.value_type())),576 }577 }578 LocalExpr(bindings, returned) => {579 let mut new_bindings: GcHashMap<IStr, LazyVal> =580 GcHashMap::with_capacity(bindings.len());581 let future_context = Context::new_future();582 for b in bindings {583 new_bindings.insert(584 b.name.clone(),585 evaluate_binding_in_future(b, future_context.clone()),586 );587 }588 let context = context589 .extend_bound(new_bindings)590 .into_future(future_context);591 evaluate(context, &returned.clone())?592 }593 Arr(items) => {594 let mut out = Vec::with_capacity(items.len());595 for item in items {596 // TODO: Implement ArrValue::Lazy with same context for every element?597 #[derive(Trace)]598 struct ArrayElement {599 context: Context,600 item: LocExpr,601 }602 impl LazyValValue for ArrayElement {603 fn get(self: Box<Self>) -> Result<Val> {604 evaluate(self.context, &self.item)605 }606 }607 out.push(LazyVal::new(TraceBox(Box::new(ArrayElement {608 context: context.clone(),609 item: item.clone(),610 }))));611 }612 Val::Arr(out.into())613 }614 ArrComp(expr, comp_specs) => {615 let mut out = Vec::new();616 evaluate_comp(context, comp_specs, &mut |ctx| {617 out.push(evaluate(ctx, expr)?);618 Ok(())619 })?;620 Val::Arr(ArrValue::Eager(Cc::new(out)))621 }622 Obj(body) => Val::Obj(evaluate_object(context, body)?),623 ObjExtend(s, t) => evaluate_add_op(624 &evaluate(context.clone(), s)?,625 &Val::Obj(evaluate_object(context, t)?),626 )?,627 Apply(value, args, tailstrict) => evaluate_apply(context, value, args, loc, *tailstrict)?,628 Function(params, body) => {629 evaluate_method(context, "anonymous".into(), params.clone(), body.clone())630 }631 Intrinsic(name) => Val::Func(Cc::new(FuncVal::Intrinsic(name.clone()))),632 AssertExpr(assert, returned) => {633 evaluate_assert(context.clone(), assert)?;634 evaluate(context, returned)?635 }636 ErrorStmt(e) => push_frame(637 loc,638 || "error statement".to_owned(),639 || throw!(RuntimeError(IStr::try_from(evaluate(context, e)?)?,)),640 )?,641 IfElse {642 cond,643 cond_then,644 cond_else,645 } => {646 if push_frame(647 loc,648 || "if condition".to_owned(),649 || bool::try_from(evaluate(context.clone(), &cond.0)?),650 )? {651 evaluate(context, cond_then)?652 } else {653 match cond_else {654 Some(v) => evaluate(context, v)?,655 None => Val::Null,656 }657 }658 }659 Slice(value, desc) => {660 let indexable = evaluate(context.clone(), value)?;661662 fn parse_num(663 context: &Context,664 expr: Option<&LocExpr>,665 desc: &'static str,666 ) -> Result<Option<usize>> {667 Ok(match expr {668 Some(s) => evaluate(context.clone(), s)?669 .try_cast_nullable_num(desc)?670 .map(|v| v as usize),671 None => None,672 })673 }674675 let start = parse_num(&context, desc.start.as_ref(), "start")?;676 let end = parse_num(&context, desc.end.as_ref(), "end")?;677 let step = parse_num(&context, desc.step.as_ref(), "step")?;678679 std_slice(indexable.into_indexable()?, start, end, step)?680 }681 Import(path) => {682 let tmp = loc.clone().0;683 let mut import_location = tmp.to_path_buf();684 import_location.pop();685 push_frame(686 loc,687 || format!("import {:?}", path),688 || with_state(|s| s.import_file(&import_location, path)),689 )?690 }691 ImportStr(path) => {692 let tmp = loc.clone().0;693 let mut import_location = tmp.to_path_buf();694 import_location.pop();695 Val::Str(with_state(|s| s.import_file_str(&import_location, path))?)696 }697 })698}crates/jrsonnet-evaluator/src/evaluate/operator.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/evaluate/operator.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/operator.rs
@@ -1,3 +1,5 @@
+use std::convert::TryInto;
+
use crate::builtin::std_format;
use crate::{equals, evaluate, Context, Val};
use crate::{error::Error::*, throw, Result};
@@ -46,7 +48,7 @@
use Val::*;
match (a, b) {
(Num(a), Num(b)) => Ok(Num(a % b)),
- (Str(str), vals) => std_format(str.clone(), vals.clone()),
+ (Str(str), vals) => std_format(str.clone(), vals.clone())?.try_into(),
(a, b) => throw!(BinaryOperatorDoesNotOperateOnValues(
BinaryOpType::Mod,
a.value_type(),
crates/jrsonnet-evaluator/src/function.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/function.rs
+++ b/crates/jrsonnet-evaluator/src/function.rs
@@ -141,6 +141,93 @@
}
}
+#[derive(Clone, Copy)]
+pub struct BuiltinParam {
+ pub name: &'static str,
+ pub has_default: bool,
+}
+
+/// You shouldn't probally use this function, use jrsonnet_macros::builtin instead
+///
+/// ## Parameters
+/// * `ctx`: used for passed argument expressions' execution and for body execution (if `body_ctx` is not set)
+/// * `params`: function parameters' definition
+/// * `args`: passed function arguments
+/// * `tailstrict`: if set to `true` function arguments are eagerly executed, otherwise - lazily
+pub fn parse_builtin_call<'k>(
+ ctx: Context,
+ params: &'static [BuiltinParam],
+ args: &'k ArgsDesc,
+ tailstrict: bool,
+) -> Result<GcHashMap<&'k str, LazyVal>> {
+ let mut passed_args = GcHashMap::with_capacity(params.len());
+ if args.unnamed.len() > params.len() {
+ throw!(TooManyArgsFunctionHas(params.len()))
+ }
+
+ let mut filled_args = 0;
+
+ for (id, arg) in args.unnamed.iter().enumerate() {
+ let name = params[id].name;
+ passed_args.insert(
+ name,
+ if tailstrict {
+ LazyVal::new_resolved(evaluate(ctx.clone(), arg)?)
+ } else {
+ LazyVal::new(TraceBox(Box::new(EvaluateLazyVal {
+ context: ctx.clone(),
+ expr: arg.clone(),
+ })))
+ },
+ );
+ filled_args += 1;
+ }
+
+ for (name, value) in args.named.iter() {
+ // FIXME: O(n) for arg existence check
+ if !params.iter().any(|p| p.name == name as &str) {
+ throw!(UnknownFunctionParameter((name as &str).to_owned()));
+ }
+ if passed_args
+ .insert(
+ name,
+ if tailstrict {
+ LazyVal::new_resolved(evaluate(ctx.clone(), value)?)
+ } else {
+ LazyVal::new(TraceBox(Box::new(EvaluateLazyVal {
+ context: ctx.clone(),
+ expr: value.clone(),
+ })))
+ },
+ )
+ .is_some()
+ {
+ throw!(BindingParameterASecondTime(name.clone()));
+ }
+ filled_args += 1;
+ }
+
+ if filled_args < params.len() {
+ for param in params.iter().filter(|p| p.has_default) {
+ if passed_args.contains_key(¶m.name) {
+ continue;
+ }
+ filled_args += 1;
+ }
+
+ // Some args still wasn't filled
+ if filled_args != params.len() {
+ for param in params.iter().skip(args.unnamed.len()) {
+ if !args.named.iter().any(|a| &a.0 as &str == param.name) {
+ throw!(FunctionParameterNotBoundInCall(param.name.into()));
+ }
+ }
+ unreachable!();
+ }
+ }
+ Ok(passed_args)
+}
+
pub fn parse_function_call_map(
ctx: Context,
body_ctx: Option<Context>,
@@ -201,12 +288,7 @@
Ok(body_ctx.unwrap_or(ctx).extend(out, None, None, None))
}
-pub fn place_args(
- ctx: Context,
- body_ctx: Option<Context>,
- params: &ParamsDesc,
- args: &[Val],
-) -> Result<Context> {
+pub fn place_args(body_ctx: Context, params: &ParamsDesc, args: &[Val]) -> Result<Context> {
let mut out = GcHashMap::with_capacity(params.len());
let mut positioned_args = vec![None; params.0.len()];
for (id, arg) in args.iter().enumerate() {
@@ -220,14 +302,14 @@
let val = if let Some(arg) = &positioned_args[id] {
(*arg).clone()
} else if let Some(default) = &p.1 {
- evaluate(ctx.clone(), default)?
+ evaluate(body_ctx.clone(), default)?
} else {
throw!(FunctionParameterNotBoundInCall(p.0.clone()));
};
out.insert(p.0.clone(), LazyVal::new_resolved(val));
}
- Ok(body_ctx.unwrap_or(ctx).extend(out, None, None, None))
+ Ok(body_ctx.extend(out, None, None, None))
}
#[macro_export]
crates/jrsonnet-evaluator/src/trace/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/trace/mod.rs
+++ b/crates/jrsonnet-evaluator/src/trace/mod.rs
@@ -122,6 +122,7 @@
.map(|el| &el.location)
.map(|location| {
use std::fmt::Write;
+ #[allow(clippy::option_if_let_else)]
if let Some(location) = location {
let mut resolved_path = self.resolver.resolve(&location.0);
// TODO: Process all trace elements first
crates/jrsonnet-evaluator/src/typed.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/typed.rs
+++ /dev/null
@@ -1,265 +0,0 @@
-use std::{fmt::Display, rc::Rc};
-
-use crate::{
- error::{Error, LocError, Result},
- push_description_frame, Val,
-};
-use gcmodule::Trace;
-use jrsonnet_types::{ComplexValType, ValType};
-use thiserror::Error;
-
-#[macro_export]
-macro_rules! unwrap_type {
- ($desc: expr, $value: expr, $typ: expr => $match: path) => {{
- use $crate::{push_stack_frame, typed::CheckType};
- push_stack_frame(None, $desc, || Ok($typ.check(&$value)?))?;
- match $value {
- $match(v) => v,
- _ => unreachable!(),
- }
- }};
-}
-
-#[derive(Debug, Error, Clone, Trace)]
-pub enum TypeError {
- #[error("expected {0}, got {1}")]
- ExpectedGot(ComplexValType, ValType),
- #[error("missing property {0} from {1:?}")]
- MissingProperty(#[skip_trace] Rc<str>, ComplexValType),
- #[error("every failed from {0}:\n{1}")]
- UnionFailed(ComplexValType, TypeLocErrorList),
- #[error(
- "number out of bounds: {0} not in {}..{}",
- .1.map(|v|v.to_string()).unwrap_or_else(|| "".to_owned()),
- .2.map(|v|v.to_string()).unwrap_or_else(|| "".to_owned()),
- )]
- BoundsFailed(f64, Option<f64>, Option<f64>),
-}
-impl From<TypeError> for LocError {
- fn from(e: TypeError) -> Self {
- Error::TypeError(e.into()).into()
- }
-}
-
-#[derive(Debug, Clone, Trace)]
-pub struct TypeLocError(Box<TypeError>, ValuePathStack);
-impl From<TypeError> for TypeLocError {
- fn from(e: TypeError) -> Self {
- Self(Box::new(e), ValuePathStack(Vec::new()))
- }
-}
-impl From<TypeLocError> for LocError {
- fn from(e: TypeLocError) -> Self {
- Error::TypeError(e).into()
- }
-}
-impl Display for TypeLocError {
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- write!(f, "{}", self.0)?;
- if !(self.1).0.is_empty() {
- write!(f, " at {}", self.1)?;
- }
- Ok(())
- }
-}
-
-#[derive(Debug, Clone, Trace)]
-pub struct TypeLocErrorList(Vec<TypeLocError>);
-impl Display for TypeLocErrorList {
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- use std::fmt::Write;
- let mut out = String::new();
- for (i, err) in self.0.iter().enumerate() {
- if i != 0 {
- writeln!(f)?;
- }
- out.clear();
- write!(out, "{}", err)?;
-
- for (i, line) in out.lines().enumerate() {
- if line.trim().is_empty() {
- continue;
- }
- if i != 0 {
- writeln!(f)?;
- write!(f, " ")?;
- } else {
- write!(f, " - ")?;
- }
- write!(f, "{}", line)?;
- }
- }
- Ok(())
- }
-}
-
-fn push_type_description(
- error_reason: impl Fn() -> String,
- path: impl Fn() -> ValuePathItem,
- item: impl Fn() -> Result<()>,
-) -> Result<()> {
- push_description_frame(error_reason, || match item() {
- Ok(_) => Ok(()),
- Err(mut e) => {
- if let Error::TypeError(e) = &mut e.error_mut() {
- (e.1).0.push(path())
- }
- Err(e)
- }
- })
-}
-
-// TODO: check_fast for fast path of union type checking
-pub trait CheckType {
- fn check(&self, value: &Val) -> Result<()>;
-}
-
-impl CheckType for ValType {
- fn check(&self, value: &Val) -> Result<()> {
- let got = value.value_type();
- if got != *self {
- let loc_error: TypeLocError = TypeError::ExpectedGot((*self).into(), got).into();
- return Err(loc_error.into());
- }
- Ok(())
- }
-}
-
-#[derive(Clone, Debug, Trace)]
-enum ValuePathItem {
- Field(#[skip_trace] Rc<str>),
- Index(u64),
-}
-impl Display for ValuePathItem {
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- match self {
- Self::Field(name) => write!(f, ".{}", name)?,
- Self::Index(idx) => write!(f, "[{}]", idx)?,
- }
- Ok(())
- }
-}
-
-#[derive(Clone, Debug, Trace)]
-struct ValuePathStack(Vec<ValuePathItem>);
-impl Display for ValuePathStack {
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- write!(f, "self")?;
- for elem in self.0.iter().rev() {
- write!(f, "{}", elem)?;
- }
- Ok(())
- }
-}
-
-impl CheckType for ComplexValType {
- fn check(&self, value: &Val) -> Result<()> {
- match self {
- Self::Any => Ok(()),
- Self::Simple(s) => s.check(value),
- Self::Char => match value {
- Val::Str(s) if s.len() == 1 || s.chars().count() == 1 => Ok(()),
- v => Err(TypeError::ExpectedGot(self.clone(), v.value_type()).into()),
- },
- Self::BoundedNumber(from, to) => {
- if let Val::Num(n) = value {
- if from.map(|from| from > *n).unwrap_or(false)
- || to.map(|to| to <= *n).unwrap_or(false)
- {
- return Err(TypeError::BoundsFailed(*n, *from, *to).into());
- }
- Ok(())
- } else {
- Err(TypeError::ExpectedGot(self.clone(), value.value_type()).into())
- }
- }
- Self::Array(elem_type) => match value {
- Val::Arr(a) => {
- for (i, item) in a.iter().enumerate() {
- push_type_description(
- || format!("array index {}", i),
- || ValuePathItem::Index(i as u64),
- || elem_type.check(&item.clone()?),
- )?;
- }
- Ok(())
- }
- v => Err(TypeError::ExpectedGot(self.clone(), v.value_type()).into()),
- },
- Self::ArrayRef(elem_type) => match value {
- Val::Arr(a) => {
- for (i, item) in a.iter().enumerate() {
- push_type_description(
- || format!("array index {}", i),
- || ValuePathItem::Index(i as u64),
- || elem_type.check(&item.clone()?),
- )?;
- }
- Ok(())
- }
- v => Err(TypeError::ExpectedGot(self.clone(), v.value_type()).into()),
- },
- Self::ObjectRef(elems) => match value {
- Val::Obj(obj) => {
- for (k, v) in elems.iter() {
- if let Some(got_v) = obj.get((*k).into())? {
- push_type_description(
- || format!("property {}", k),
- || ValuePathItem::Field((*k).into()),
- || v.check(&got_v),
- )?
- } else {
- return Err(
- TypeError::MissingProperty((*k).into(), self.clone()).into()
- );
- }
- }
- Ok(())
- }
- v => Err(TypeError::ExpectedGot(self.clone(), v.value_type()).into()),
- },
- Self::Union(types) => {
- let mut errors = Vec::new();
- for ty in types.iter() {
- match ty.check(value) {
- Ok(()) => {
- return Ok(());
- }
- Err(e) => match e.error() {
- Error::TypeError(e) => errors.push(e.clone()),
- _ => return Err(e),
- },
- }
- }
- Err(TypeError::UnionFailed(self.clone(), TypeLocErrorList(errors)).into())
- }
- Self::UnionRef(types) => {
- let mut errors = Vec::new();
- for ty in types.iter() {
- match ty.check(value) {
- Ok(()) => {
- return Ok(());
- }
- Err(e) => match e.error() {
- Error::TypeError(e) => errors.push(e.clone()),
- _ => return Err(e),
- },
- }
- }
- Err(TypeError::UnionFailed(self.clone(), TypeLocErrorList(errors)).into())
- }
- Self::Sum(types) => {
- for ty in types.iter() {
- ty.check(value)?
- }
- Ok(())
- }
- Self::SumRef(types) => {
- for ty in types.iter() {
- ty.check(value)?
- }
- Ok(())
- }
- }
- }
-}
crates/jrsonnet-evaluator/src/typed/conversions.rsdiffbeforeafterboth--- /dev/null
+++ b/crates/jrsonnet-evaluator/src/typed/conversions.rs
@@ -0,0 +1,508 @@
+use std::convert::{TryFrom, TryInto};
+
+use gcmodule::Cc;
+use jrsonnet_interner::IStr;
+use jrsonnet_types::{ComplexValType, ValType};
+
+use crate::{
+ error::{Error::*, LocError, Result},
+ throw,
+ typed::CheckType,
+ ArrValue, FuncVal, IndexableVal, ObjValue, Val,
+};
+
+pub trait Typed: TryFrom<Val, Error = LocError> + TryInto<Val, Error = LocError> {
+ const TYPE: &'static ComplexValType;
+}
+
+macro_rules! impl_int {
+ ($($ty:ty)*) => {$(
+ impl Typed for $ty {
+ const TYPE: &'static ComplexValType =
+ &ComplexValType::BoundedNumber(Some(<$ty>::MIN as f64), Some(<$ty>::MAX as f64));
+ }
+ impl TryFrom<Val> for $ty {
+ type Error = LocError;
+
+ fn try_from(value: Val) -> Result<Self> {
+ <Self as Typed>::TYPE.check(&value)?;
+ match value {
+ Val::Num(n) => {
+ if n.trunc() != n {
+ throw!(RuntimeError(
+ format!(
+ "cannot convert number with fractional part to {}",
+ stringify!($ty)
+ )
+ .into()
+ ))
+ }
+ Ok(n as $ty)
+ }
+ _ => unreachable!(),
+ }
+ }
+ }
+ impl TryFrom<$ty> for Val {
+ type Error = LocError;
+
+ fn try_from(value: $ty) -> Result<Self> {
+ Ok(Self::Num(value as f64))
+ }
+ }
+ )*};
+}
+
+impl_int!(i8 u8 i16 u16 i32 u32);
+
+impl Typed for f64 {
+ const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Num);
+}
+impl TryFrom<Val> for f64 {
+ type Error = LocError;
+
+ fn try_from(value: Val) -> Result<Self> {
+ <Self as Typed>::TYPE.check(&value)?;
+ match value {
+ Val::Num(n) => Ok(n),
+ _ => unreachable!(),
+ }
+ }
+}
+impl TryFrom<f64> for Val {
+ type Error = LocError;
+
+ fn try_from(value: f64) -> Result<Self> {
+ Ok(Self::Num(value))
+ }
+}
+
+pub struct PositiveF64(pub f64);
+impl Typed for PositiveF64 {
+ const TYPE: &'static ComplexValType = &ComplexValType::BoundedNumber(Some(0.0), None);
+}
+impl TryFrom<Val> for PositiveF64 {
+ type Error = LocError;
+
+ fn try_from(value: Val) -> Result<Self> {
+ <Self as Typed>::TYPE.check(&value)?;
+ match value {
+ Val::Num(n) => Ok(Self(n)),
+ _ => unreachable!(),
+ }
+ }
+}
+impl TryFrom<PositiveF64> for Val {
+ type Error = LocError;
+
+ fn try_from(value: PositiveF64) -> Result<Self> {
+ Ok(Self::Num(value.0))
+ }
+}
+
+impl Typed for usize {
+ // It is possible to store 54 bits of precision in f64, but leaving u32::MAX here for compatibility
+ const TYPE: &'static ComplexValType =
+ &ComplexValType::BoundedNumber(Some(0.0), Some(4294967295.0));
+}
+impl TryFrom<Val> for usize {
+ type Error = LocError;
+
+ fn try_from(value: Val) -> Result<Self> {
+ <Self as Typed>::TYPE.check(&value)?;
+ match value {
+ Val::Num(n) => {
+ if n.trunc() != n {
+ throw!(RuntimeError(
+ "cannot convert number with fractional part to usize".into()
+ ))
+ }
+ Ok(n as Self)
+ }
+ _ => unreachable!(),
+ }
+ }
+}
+impl TryFrom<usize> for Val {
+ type Error = LocError;
+
+ fn try_from(value: usize) -> Result<Self> {
+ if value > u32::MAX as usize {
+ throw!(RuntimeError("number is too large".into()))
+ }
+ Ok(Self::Num(value as f64))
+ }
+}
+
+impl Typed for IStr {
+ const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Str);
+}
+impl TryFrom<Val> for IStr {
+ type Error = LocError;
+
+ fn try_from(value: Val) -> Result<Self> {
+ <Self as Typed>::TYPE.check(&value)?;
+ match value {
+ Val::Str(s) => Ok(s),
+ _ => unreachable!(),
+ }
+ }
+}
+impl TryFrom<IStr> for Val {
+ type Error = LocError;
+
+ fn try_from(value: IStr) -> Result<Self> {
+ Ok(Self::Str(value))
+ }
+}
+
+impl Typed for String {
+ const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Str);
+}
+impl TryFrom<Val> for String {
+ type Error = LocError;
+
+ fn try_from(value: Val) -> Result<Self> {
+ <Self as Typed>::TYPE.check(&value)?;
+ match value {
+ Val::Str(s) => Ok(s.to_string()),
+ _ => unreachable!(),
+ }
+ }
+}
+impl TryFrom<String> for Val {
+ type Error = LocError;
+
+ fn try_from(value: String) -> Result<Self> {
+ Ok(Self::Str(value.into()))
+ }
+}
+
+impl Typed for char {
+ const TYPE: &'static ComplexValType = &ComplexValType::Char;
+}
+impl TryFrom<Val> for char {
+ type Error = LocError;
+
+ fn try_from(value: Val) -> Result<Self> {
+ <Self as Typed>::TYPE.check(&value)?;
+ match value {
+ Val::Str(s) => Ok(s.chars().next().unwrap()),
+ _ => unreachable!(),
+ }
+ }
+}
+impl TryFrom<char> for Val {
+ type Error = LocError;
+
+ fn try_from(value: char) -> Result<Self> {
+ Ok(Self::Str(value.to_string().into()))
+ }
+}
+
+impl<T> Typed for Vec<T>
+where
+ T: Typed,
+ T: TryFrom<Val, Error = LocError>,
+ T: TryInto<Val, Error = LocError>,
+{
+ const TYPE: &'static ComplexValType = &ComplexValType::ArrayRef(T::TYPE);
+}
+impl<T> TryFrom<Val> for Vec<T>
+where
+ T: Typed,
+ T: TryFrom<Val, Error = LocError>,
+ T: TryInto<Val, Error = LocError>,
+{
+ type Error = LocError;
+
+ fn try_from(value: Val) -> Result<Self> {
+ <Self as Typed>::TYPE.check(&value)?;
+ match value {
+ Val::Arr(a) => {
+ let mut o = Self::with_capacity(a.len());
+ for i in a.iter() {
+ o.push(T::try_from(i?)?);
+ }
+ Ok(o)
+ }
+ _ => unreachable!(),
+ }
+ }
+}
+impl<T> TryFrom<Vec<T>> for Val
+where
+ T: Typed,
+ T: TryFrom<Self, Error = LocError>,
+ T: TryInto<Self, Error = LocError>,
+{
+ type Error = LocError;
+
+ fn try_from(value: Vec<T>) -> Result<Self> {
+ let mut o = Vec::with_capacity(value.len());
+ for i in value {
+ o.push(i.try_into()?);
+ }
+ Ok(Self::Arr(o.into()))
+ }
+}
+
+/// To be used in Vec<Any>
+/// Regular Val can't be used here, because it has wrong TryFrom::Error type
+pub struct Any(pub Val);
+
+impl Typed for Any {
+ const TYPE: &'static ComplexValType = &ComplexValType::Any;
+}
+impl TryFrom<Val> for Any {
+ type Error = LocError;
+
+ fn try_from(value: Val) -> Result<Self> {
+ Ok(Self(value))
+ }
+}
+impl TryFrom<Any> for Val {
+ type Error = LocError;
+
+ fn try_from(value: Any) -> Result<Self> {
+ Ok(value.0)
+ }
+}
+
+/// Specialization, provides faster TryFrom<VecVal> for Val
+pub struct VecVal(pub Vec<Val>);
+
+impl Typed for VecVal {
+ const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Arr);
+}
+impl TryFrom<Val> for VecVal {
+ type Error = LocError;
+
+ fn try_from(value: Val) -> Result<Self> {
+ <Self as Typed>::TYPE.check(&value)?;
+ match value {
+ Val::Arr(a) => Ok(Self(a.evaluated()?.to_vec())),
+ _ => unreachable!(),
+ }
+ }
+}
+impl TryFrom<VecVal> for Val {
+ type Error = LocError;
+
+ fn try_from(value: VecVal) -> Result<Self> {
+ Ok(Self::Arr(value.0.into()))
+ }
+}
+
+pub struct M1;
+impl Typed for M1 {
+ const TYPE: &'static ComplexValType = &ComplexValType::BoundedNumber(Some(-1.0), Some(-1.0));
+}
+impl TryFrom<Val> for M1 {
+ type Error = LocError;
+
+ fn try_from(value: Val) -> Result<Self> {
+ <Self as Typed>::TYPE.check(&value)?;
+ Ok(Self)
+ }
+}
+impl TryFrom<M1> for Val {
+ type Error = LocError;
+
+ fn try_from(_: M1) -> Result<Self> {
+ Ok(Self::Num(-1.0))
+ }
+}
+
+pub enum Either<A, B> {
+ Left(A),
+ Right(B),
+}
+
+impl<A, B> Either<A, B> {
+ pub fn to_left(self, f: impl FnOnce(B) -> A) -> A {
+ match self {
+ Either::Left(l) => l,
+ Either::Right(r) => f(r),
+ }
+ }
+ #[allow(clippy::missing_const_for_fn)]
+ pub fn left(self) -> Option<A> {
+ match self {
+ Either::Left(a) => Some(a),
+ Either::Right(_) => None,
+ }
+ }
+}
+
+impl<A, B> Typed for Either<A, B>
+where
+ A: Typed,
+ B: Typed,
+{
+ const TYPE: &'static ComplexValType = &ComplexValType::UnionRef(&[A::TYPE, B::TYPE]);
+}
+impl<A, B> TryFrom<Val> for Either<A, B>
+where
+ A: Typed,
+ B: Typed,
+{
+ type Error = LocError;
+
+ fn try_from(value: Val) -> Result<Self> {
+ if A::TYPE.check(&value).is_ok() {
+ A::try_from(value).map(Self::Left)
+ } else if B::TYPE.check(&value).is_ok() {
+ B::try_from(value).map(Self::Right)
+ } else {
+ <Self as Typed>::TYPE.check(&value)?;
+ unreachable!()
+ }
+ }
+}
+impl<A, B> TryFrom<Either<A, B>> for Val
+where
+ A: Typed,
+ B: Typed,
+{
+ type Error = LocError;
+
+ fn try_from(value: Either<A, B>) -> Result<Self> {
+ match value {
+ Either::Left(a) => a.try_into(),
+ Either::Right(b) => b.try_into(),
+ }
+ }
+}
+
+impl Typed for ArrValue {
+ const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Arr);
+}
+impl TryFrom<Val> for ArrValue {
+ type Error = LocError;
+
+ fn try_from(value: Val) -> Result<Self> {
+ <Self as Typed>::TYPE.check(&value)?;
+ match value {
+ Val::Arr(a) => Ok(a),
+ _ => unreachable!(),
+ }
+ }
+}
+impl TryFrom<ArrValue> for Val {
+ type Error = LocError;
+
+ fn try_from(value: ArrValue) -> Result<Self> {
+ Ok(Self::Arr(value))
+ }
+}
+
+impl Typed for Cc<FuncVal> {
+ const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Func);
+}
+impl TryFrom<Val> for Cc<FuncVal> {
+ type Error = LocError;
+
+ fn try_from(value: Val) -> Result<Self> {
+ <Self as Typed>::TYPE.check(&value)?;
+ match value {
+ Val::Func(a) => Ok(a),
+ _ => unreachable!(),
+ }
+ }
+}
+impl TryFrom<Cc<FuncVal>> for Val {
+ type Error = LocError;
+
+ fn try_from(value: Cc<FuncVal>) -> Result<Self> {
+ Ok(Self::Func(value))
+ }
+}
+impl Typed for ObjValue {
+ const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Obj);
+}
+impl TryFrom<Val> for ObjValue {
+ type Error = LocError;
+
+ fn try_from(value: Val) -> Result<Self> {
+ <Self as Typed>::TYPE.check(&value)?;
+ match value {
+ Val::Obj(a) => Ok(a),
+ _ => unreachable!(),
+ }
+ }
+}
+impl TryFrom<ObjValue> for Val {
+ type Error = LocError;
+
+ fn try_from(value: ObjValue) -> Result<Self> {
+ Ok(Self::Obj(value))
+ }
+}
+
+impl Typed for bool {
+ const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Bool);
+}
+impl TryFrom<Val> for bool {
+ type Error = LocError;
+
+ fn try_from(value: Val) -> Result<Self> {
+ <Self as Typed>::TYPE.check(&value)?;
+ match value {
+ Val::Bool(a) => Ok(a),
+ _ => unreachable!(),
+ }
+ }
+}
+impl TryFrom<bool> for Val {
+ type Error = LocError;
+
+ fn try_from(value: bool) -> Result<Self> {
+ Ok(Self::Bool(value))
+ }
+}
+
+impl Typed for IndexableVal {
+ const TYPE: &'static ComplexValType = &ComplexValType::UnionRef(&[
+ &ComplexValType::Simple(ValType::Arr),
+ &ComplexValType::Simple(ValType::Str),
+ ]);
+}
+impl TryFrom<Val> for IndexableVal {
+ type Error = LocError;
+
+ fn try_from(value: Val) -> Result<Self> {
+ <Self as Typed>::TYPE.check(&value)?;
+ value.into_indexable()
+ }
+}
+impl TryFrom<IndexableVal> for Val {
+ type Error = LocError;
+
+ fn try_from(value: IndexableVal) -> Result<Self> {
+ match value {
+ IndexableVal::Str(s) => Ok(Self::Str(s)),
+ IndexableVal::Arr(a) => Ok(Self::Arr(a)),
+ }
+ }
+}
+
+pub struct Null;
+impl Typed for Null {
+ const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Null);
+}
+impl TryFrom<Val> for Null {
+ type Error = LocError;
+
+ fn try_from(value: Val) -> Result<Self> {
+ <Self as Typed>::TYPE.check(&value)?;
+ Ok(Self)
+ }
+}
+impl TryFrom<Null> for Val {
+ type Error = LocError;
+
+ fn try_from(_: Null) -> Result<Self> {
+ Ok(Self::Null)
+ }
+}
crates/jrsonnet-evaluator/src/typed/mod.rsdiffbeforeafterboth--- /dev/null
+++ b/crates/jrsonnet-evaluator/src/typed/mod.rs
@@ -0,0 +1,268 @@
+use std::{fmt::Display, rc::Rc};
+
+mod conversions;
+pub use conversions::*;
+
+use crate::{
+ error::{Error, LocError, Result},
+ push_description_frame, Val,
+};
+use gcmodule::Trace;
+use jrsonnet_types::{ComplexValType, ValType};
+use thiserror::Error;
+
+#[macro_export]
+macro_rules! unwrap_type {
+ ($desc: expr, $value: expr, $typ: expr => $match: path) => {{
+ use $crate::{push_stack_frame, typed::CheckType};
+ push_stack_frame(None, $desc, || Ok($typ.check(&$value)?))?;
+ match $value {
+ $match(v) => v,
+ _ => unreachable!(),
+ }
+ }};
+}
+
+#[derive(Debug, Error, Clone, Trace)]
+pub enum TypeError {
+ #[error("expected {0}, got {1}")]
+ ExpectedGot(ComplexValType, ValType),
+ #[error("missing property {0} from {1:?}")]
+ MissingProperty(#[skip_trace] Rc<str>, ComplexValType),
+ #[error("every failed from {0}:\n{1}")]
+ UnionFailed(ComplexValType, TypeLocErrorList),
+ #[error(
+ "number out of bounds: {0} not in {}..{}",
+ .1.map(|v|v.to_string()).unwrap_or_else(|| "".to_owned()),
+ .2.map(|v|v.to_string()).unwrap_or_else(|| "".to_owned()),
+ )]
+ BoundsFailed(f64, Option<f64>, Option<f64>),
+}
+impl From<TypeError> for LocError {
+ fn from(e: TypeError) -> Self {
+ Error::TypeError(e.into()).into()
+ }
+}
+
+#[derive(Debug, Clone, Trace)]
+pub struct TypeLocError(Box<TypeError>, ValuePathStack);
+impl From<TypeError> for TypeLocError {
+ fn from(e: TypeError) -> Self {
+ Self(Box::new(e), ValuePathStack(Vec::new()))
+ }
+}
+impl From<TypeLocError> for LocError {
+ fn from(e: TypeLocError) -> Self {
+ Error::TypeError(e).into()
+ }
+}
+impl Display for TypeLocError {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ write!(f, "{}", self.0)?;
+ if !(self.1).0.is_empty() {
+ write!(f, " at {}", self.1)?;
+ }
+ Ok(())
+ }
+}
+
+#[derive(Debug, Clone, Trace)]
+pub struct TypeLocErrorList(Vec<TypeLocError>);
+impl Display for TypeLocErrorList {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ use std::fmt::Write;
+ let mut out = String::new();
+ for (i, err) in self.0.iter().enumerate() {
+ if i != 0 {
+ writeln!(f)?;
+ }
+ out.clear();
+ write!(out, "{}", err)?;
+
+ for (i, line) in out.lines().enumerate() {
+ if line.trim().is_empty() {
+ continue;
+ }
+ if i != 0 {
+ writeln!(f)?;
+ write!(f, " ")?;
+ } else {
+ write!(f, " - ")?;
+ }
+ write!(f, "{}", line)?;
+ }
+ }
+ Ok(())
+ }
+}
+
+fn push_type_description(
+ error_reason: impl Fn() -> String,
+ path: impl Fn() -> ValuePathItem,
+ item: impl Fn() -> Result<()>,
+) -> Result<()> {
+ push_description_frame(error_reason, || match item() {
+ Ok(_) => Ok(()),
+ Err(mut e) => {
+ if let Error::TypeError(e) = &mut e.error_mut() {
+ (e.1).0.push(path())
+ }
+ Err(e)
+ }
+ })
+}
+
+// TODO: check_fast for fast path of union type checking
+pub trait CheckType {
+ fn check(&self, value: &Val) -> Result<()>;
+}
+
+impl CheckType for ValType {
+ fn check(&self, value: &Val) -> Result<()> {
+ let got = value.value_type();
+ if got != *self {
+ let loc_error: TypeLocError = TypeError::ExpectedGot((*self).into(), got).into();
+ return Err(loc_error.into());
+ }
+ Ok(())
+ }
+}
+
+#[derive(Clone, Debug, Trace)]
+enum ValuePathItem {
+ Field(#[skip_trace] Rc<str>),
+ Index(u64),
+}
+impl Display for ValuePathItem {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ match self {
+ Self::Field(name) => write!(f, ".{}", name)?,
+ Self::Index(idx) => write!(f, "[{}]", idx)?,
+ }
+ Ok(())
+ }
+}
+
+#[derive(Clone, Debug, Trace)]
+struct ValuePathStack(Vec<ValuePathItem>);
+impl Display for ValuePathStack {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ write!(f, "self")?;
+ for elem in self.0.iter().rev() {
+ write!(f, "{}", elem)?;
+ }
+ Ok(())
+ }
+}
+
+impl CheckType for ComplexValType {
+ fn check(&self, value: &Val) -> Result<()> {
+ match self {
+ Self::Any => Ok(()),
+ Self::Simple(s) => s.check(value),
+ Self::Char => match value {
+ Val::Str(s) if s.len() == 1 || s.chars().count() == 1 => Ok(()),
+ v => Err(TypeError::ExpectedGot(self.clone(), v.value_type()).into()),
+ },
+ Self::BoundedNumber(from, to) => {
+ if let Val::Num(n) = value {
+ if from.map(|from| from > *n).unwrap_or(false)
+ || to.map(|to| to < *n).unwrap_or(false)
+ {
+ return Err(TypeError::BoundsFailed(*n, *from, *to).into());
+ }
+ Ok(())
+ } else {
+ Err(TypeError::ExpectedGot(self.clone(), value.value_type()).into())
+ }
+ }
+ Self::Array(elem_type) => match value {
+ Val::Arr(a) => {
+ for (i, item) in a.iter().enumerate() {
+ push_type_description(
+ || format!("array index {}", i),
+ || ValuePathItem::Index(i as u64),
+ || elem_type.check(&item.clone()?),
+ )?;
+ }
+ Ok(())
+ }
+ v => Err(TypeError::ExpectedGot(self.clone(), v.value_type()).into()),
+ },
+ Self::ArrayRef(elem_type) => match value {
+ Val::Arr(a) => {
+ for (i, item) in a.iter().enumerate() {
+ push_type_description(
+ || format!("array index {}", i),
+ || ValuePathItem::Index(i as u64),
+ || elem_type.check(&item.clone()?),
+ )?;
+ }
+ Ok(())
+ }
+ v => Err(TypeError::ExpectedGot(self.clone(), v.value_type()).into()),
+ },
+ Self::ObjectRef(elems) => match value {
+ Val::Obj(obj) => {
+ for (k, v) in elems.iter() {
+ if let Some(got_v) = obj.get((*k).into())? {
+ push_type_description(
+ || format!("property {}", k),
+ || ValuePathItem::Field((*k).into()),
+ || v.check(&got_v),
+ )?
+ } else {
+ return Err(
+ TypeError::MissingProperty((*k).into(), self.clone()).into()
+ );
+ }
+ }
+ Ok(())
+ }
+ v => Err(TypeError::ExpectedGot(self.clone(), v.value_type()).into()),
+ },
+ Self::Union(types) => {
+ let mut errors = Vec::new();
+ for ty in types.iter() {
+ match ty.check(value) {
+ Ok(()) => {
+ return Ok(());
+ }
+ Err(e) => match e.error() {
+ Error::TypeError(e) => errors.push(e.clone()),
+ _ => return Err(e),
+ },
+ }
+ }
+ Err(TypeError::UnionFailed(self.clone(), TypeLocErrorList(errors)).into())
+ }
+ Self::UnionRef(types) => {
+ let mut errors = Vec::new();
+ for ty in types.iter() {
+ match ty.check(value) {
+ Ok(()) => {
+ return Ok(());
+ }
+ Err(e) => match e.error() {
+ Error::TypeError(e) => errors.push(e.clone()),
+ _ => return Err(e),
+ },
+ }
+ }
+ Err(TypeError::UnionFailed(self.clone(), TypeLocErrorList(errors)).into())
+ }
+ Self::Sum(types) => {
+ for ty in types.iter() {
+ ty.check(value)?
+ }
+ Ok(())
+ }
+ Self::SumRef(types) => {
+ for ty in types.iter() {
+ ty.check(value)?
+ }
+ Ok(())
+ }
+ }
+ }
+}
crates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/val.rs
+++ b/crates/jrsonnet-evaluator/src/val.rs
@@ -170,10 +170,10 @@
}
}
- pub fn evaluate_values(&self, call_ctx: Context, args: &[Val]) -> Result<Val> {
+ pub fn evaluate_values(&self, args: &[Val]) -> Result<Val> {
match self {
Self::Normal(func) => {
- let ctx = place_args(call_ctx, Some(func.ctx.clone()), &func.params, args)?;
+ let ctx = place_args(func.ctx.clone(), &func.params, args)?;
evaluate(ctx, &func.body)
}
Self::Intrinsic(_) => todo!(),
@@ -363,14 +363,6 @@
Func(Cc<FuncVal>),
}
-macro_rules! matches_unwrap {
- ($e: expr, $p: pat, $r: expr) => {
- match $e {
- $p => $r,
- _ => panic!("no match"),
- }
- };
-}
impl Val {
/// Creates `Val::Num` after checking for numeric overflow.
/// As numbers are `f64`, we can just check for their finity.
@@ -382,38 +374,6 @@
}
}
- pub fn assert_type(&self, context: &'static str, val_type: ValType) -> Result<()> {
- let this_type = self.value_type();
- if this_type != val_type {
- throw!(TypeMismatch(context, vec![val_type], this_type))
- } else {
- Ok(())
- }
- }
- pub fn unwrap_num(self) -> Result<f64> {
- Ok(matches_unwrap!(self, Self::Num(v), v))
- }
- pub fn unwrap_str(self) -> Result<IStr> {
- Ok(matches_unwrap!(self, Self::Str(v), v))
- }
- pub fn unwrap_arr(self) -> Result<ArrValue> {
- Ok(matches_unwrap!(self, Self::Arr(v), v))
- }
- pub fn unwrap_func(self) -> Result<Cc<FuncVal>> {
- Ok(matches_unwrap!(self, Self::Func(v), v))
- }
- pub fn try_cast_bool(self, context: &'static str) -> Result<bool> {
- self.assert_type(context, ValType::Bool)?;
- Ok(matches_unwrap!(self, Self::Bool(v), v))
- }
- pub fn try_cast_str(self, context: &'static str) -> Result<IStr> {
- self.assert_type(context, ValType::Str)?;
- Ok(matches_unwrap!(self, Self::Str(v), v))
- }
- pub fn try_cast_num(self, context: &'static str) -> Result<f64> {
- self.assert_type(context, ValType::Num)?;
- self.unwrap_num()
- }
pub fn try_cast_nullable_num(self, context: &'static str) -> Result<Option<f64>> {
Ok(match self {
Val::Null => None,
crates/jrsonnet-macros/Cargo.tomldiffbeforeafterboth--- /dev/null
+++ b/crates/jrsonnet-macros/Cargo.toml
@@ -0,0 +1,12 @@
+[package]
+name = "jrsonnet-macros"
+version = "0.4.2"
+edition = "2021"
+
+[lib]
+proc-macro = true
+
+[dependencies]
+proc-macro2 = "1.0.32"
+quote = "1.0.10"
+syn = { version = "1.0.82", features = ["full"] }
crates/jrsonnet-macros/src/lib.rsdiffbeforeafterboth--- /dev/null
+++ b/crates/jrsonnet-macros/src/lib.rs
@@ -0,0 +1,87 @@
+use proc_macro2::Span;
+use quote::quote;
+use syn::{parse_macro_input, FnArg, Ident, ItemFn, Pat};
+
+#[proc_macro_attribute]
+pub fn builtin(
+ _attr: proc_macro::TokenStream,
+ item: proc_macro::TokenStream,
+) -> proc_macro::TokenStream {
+ // syn::ItemFn::parse(input)
+ let fun: ItemFn = parse_macro_input!(item);
+
+ let inner_name = Ident::new("inner", Span::call_site());
+ let mut inner_fun = fun.clone();
+ inner_fun.sig.ident = inner_name.clone();
+ let result = match fun.sig.output {
+ syn::ReturnType::Default => panic!("builtin should return something"),
+ syn::ReturnType::Type(_, ty) => ty,
+ };
+
+ let params = fun
+ .sig
+ .inputs
+ .iter()
+ .map(|i| match i {
+ FnArg::Receiver(_) => unreachable!(),
+ FnArg::Typed(t) => t,
+ })
+ .map(|t| {
+ let ident = match &t.pat as &Pat {
+ Pat::Ident(i) => i.ident.to_string(),
+ _ => panic!("only idents supported yet"),
+ };
+ // TODO: Check if ty == Option<_>
+ let optional = false;
+ quote! {
+ BuiltinParam {
+ name: #ident,
+ has_default: #optional,
+ }
+ }
+ });
+
+ let args = fun
+ .sig
+ .inputs
+ .iter()
+ .map(|i| match i {
+ FnArg::Receiver(_) => unreachable!(),
+ FnArg::Typed(t) => t,
+ })
+ .map(|t| {
+ let ident = match &t.pat as &Pat {
+ Pat::Ident(i) => i.ident.to_string(),
+ _ => panic!("only idents supported yet"),
+ };
+ let ty = &t.ty;
+ quote! {{
+ let value = parsed.get(#ident).unwrap();
+
+ jrsonnet_evaluator::push_description_frame(
+ || format!("argument <{}> evaluation", #ident),
+ || <#ty>::try_from(value.evaluate()?),
+ )?
+ }}
+ });
+
+ let attrs = &fun.attrs;
+ let vis = &fun.vis;
+ let name = &fun.sig.ident;
+ (quote! {
+ #(#attrs)*
+ #vis fn #name(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
+ #inner_fun
+ use jrsonnet_evaluator::function::BuiltinParam;
+ const PARAMS: &'static [BuiltinParam] = &[
+ #(#params),*
+ ];
+ let parsed = jrsonnet_evaluator::function::parse_builtin_call(context, &PARAMS, args, false)?;
+
+ let result: #result = #inner_name(#(#args),*);
+ let result = result?;
+ result.try_into()
+ }
+ })
+ .into()
+}
crates/jrsonnet-types/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-types/src/lib.rs
+++ b/crates/jrsonnet-types/src/lib.rs
@@ -42,14 +42,14 @@
$crate::ComplexValType::Simple($crate::ValType::Func)
};
(($($a:tt) |+)) => {{
- static CONTENTS: &'static [$crate::ComplexValType] = &[
- $(ty!($a)),+
+ static CONTENTS: &'static [&'static $crate::ComplexValType] = &[
+ $(&ty!($a)),+
];
$crate::ComplexValType::UnionRef(CONTENTS)
}};
(($($a:tt) &+)) => {{
- static CONTENTS: &'static [$crate::ComplexValType] = &[
- $(ty!($a)),+
+ static CONTENTS: &'static [&'static $crate::ComplexValType] = &[
+ $(&ty!($a)),+
];
$crate::ComplexValType::SumRef(CONTENTS)
}};
@@ -66,8 +66,8 @@
assert_eq!(
ty!((string | number)),
ComplexValType::UnionRef(&[
- ComplexValType::Simple(ValType::Str),
- ComplexValType::Simple(ValType::Num)
+ &ComplexValType::Simple(ValType::Str),
+ &ComplexValType::Simple(ValType::Num)
])
);
assert_eq!(
@@ -124,9 +124,9 @@
ArrayRef(&'static ComplexValType),
ObjectRef(&'static [(&'static str, ComplexValType)]),
Union(Vec<ComplexValType>),
- UnionRef(&'static [ComplexValType]),
+ UnionRef(&'static [&'static ComplexValType]),
Sum(Vec<ComplexValType>),
- SumRef(&'static [ComplexValType]),
+ SumRef(&'static [&'static ComplexValType]),
}
impl From<ValType> for ComplexValType {
@@ -135,12 +135,12 @@
}
}
-fn write_union(
+fn write_union<'i>(
f: &mut std::fmt::Formatter<'_>,
is_union: bool,
- union: &[ComplexValType],
+ union: impl Iterator<Item = &'i ComplexValType>,
) -> std::fmt::Result {
- for (i, v) in union.iter().enumerate() {
+ for (i, v) in union.enumerate() {
let should_add_braces =
matches!(v, ComplexValType::UnionRef(_) | ComplexValType::Union(_) if !is_union);
if i != 0 {
@@ -190,10 +190,10 @@
}
write!(f, "}}")?;
}
- ComplexValType::Union(v) => write_union(f, true, v)?,
- ComplexValType::UnionRef(v) => write_union(f, true, v)?,
- ComplexValType::Sum(v) => write_union(f, false, v)?,
- ComplexValType::SumRef(v) => write_union(f, false, v)?,
+ ComplexValType::Union(v) => write_union(f, true, v.iter())?,
+ ComplexValType::UnionRef(v) => write_union(f, true, v.iter().map(|v| *v))?,
+ ComplexValType::Sum(v) => write_union(f, false, v.iter())?,
+ ComplexValType::SumRef(v) => write_union(f, false, v.iter().map(|v| *v))?,
};
Ok(())
}