difftreelog
refactor reduce boilerplate by automatic conversions
in: master
29 files changed
bindings/jsonnet/src/native.rsdiffbeforeafterboth--- a/bindings/jsonnet/src/native.rs
+++ b/bindings/jsonnet/src/native.rs
@@ -69,10 +69,7 @@
ctx: *const c_void,
mut raw_params: *const *const c_char,
) {
- let name = CStr::from_ptr(name)
- .to_str()
- .expect("name is not utf-8")
- .into();
+ let name = CStr::from_ptr(name).to_str().expect("name is not utf-8");
let mut params = Vec::new();
loop {
if (*raw_params).is_null() {
bindings/jsonnet/src/val_make.rsdiffbeforeafterboth--- a/bindings/jsonnet/src/val_make.rs
+++ b/bindings/jsonnet/src/val_make.rs
@@ -5,10 +5,7 @@
os::raw::{c_char, c_double, c_int},
};
-use jrsonnet_evaluator::{
- val::{ArrValue, StrValue},
- ObjValue, Val,
-};
+use jrsonnet_evaluator::{val::ArrValue, ObjValue, Val};
use crate::VM;
@@ -21,7 +18,7 @@
pub unsafe extern "C" fn jsonnet_json_make_string(_vm: &VM, val: *const c_char) -> *mut Val {
let val = CStr::from_ptr(val);
let val = val.to_str().expect("string is not utf-8");
- Box::into_raw(Box::new(Val::Str(StrValue::Flat(val.into()))))
+ Box::into_raw(Box::new(Val::string(val)))
}
/// Convert the given double to a `JsonnetJsonValue`.
bindings/jsonnet/src/val_modify.rsdiffbeforeafterboth--- a/bindings/jsonnet/src/val_modify.rs
+++ b/bindings/jsonnet/src/val_modify.rs
@@ -5,7 +5,6 @@
use std::{ffi::CStr, os::raw::c_char};
use jrsonnet_evaluator::{val::ArrValue, Thunk, Val};
-use jrsonnet_gcmodule::Cc;
use crate::VM;
crates/jrsonnet-cli/src/stdlib.rsdiffbeforeafterboth--- a/crates/jrsonnet-cli/src/stdlib.rs
+++ b/crates/jrsonnet-cli/src/stdlib.rs
@@ -1,7 +1,7 @@
use std::{fs::read_to_string, str::FromStr};
use clap::Parser;
-use jrsonnet_evaluator::{error::Result, trace::PathResolver, State};
+use jrsonnet_evaluator::{trace::PathResolver, Result, State};
use jrsonnet_stdlib::ContextInitializer;
#[derive(Clone)]
crates/jrsonnet-evaluator/src/arr/spec.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/arr/spec.rs
+++ b/crates/jrsonnet-evaluator/src/arr/spec.rs
@@ -6,12 +6,8 @@
use super::ArrValue;
use crate::{
- error::ErrorKind::InfiniteRecursionDetected,
- evaluate,
- function::FuncVal,
- typed::Typed,
- val::{StrValue, ThunkValue},
- Context, Error, ObjValue, Result, Thunk, Val,
+ error::ErrorKind::InfiniteRecursionDetected, evaluate, function::FuncVal, typed::Typed,
+ val::ThunkValue, Context, Error, ObjValue, Result, Thunk, Val,
};
pub trait ArrayLike: Any + Trace + Debug {
@@ -101,9 +97,7 @@
}
fn get_cheap(&self, index: usize) -> Option<Val> {
- self.0
- .get(index)
- .map(|v| Val::Str(StrValue::Flat(IStr::from(*v))))
+ self.0.get(index).map(|v| Val::string(*v))
}
fn is_cheap(&self) -> bool {
true
crates/jrsonnet-evaluator/src/ctx.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/ctx.rs
+++ b/crates/jrsonnet-evaluator/src/ctx.rs
@@ -87,9 +87,9 @@
}
#[must_use]
- pub fn with_var(self, name: IStr, value: Val) -> Self {
+ pub fn with_var(self, name: impl Into<IStr>, value: Val) -> Self {
let mut new_bindings = GcHashMap::with_capacity(1);
- new_bindings.insert(name, Thunk::evaluated(value));
+ new_bindings.insert(name.into(), Thunk::evaluated(value));
self.extend(new_bindings, None, None, None)
}
@@ -161,8 +161,8 @@
}
/// # Panics
/// If `name` is already bound
- pub fn bind(&mut self, name: IStr, value: Thunk<Val>) -> &mut Self {
- let old = self.bindings.insert(name, value);
+ pub fn bind(&mut self, name: impl Into<IStr>, value: Thunk<Val>) -> &mut Self {
+ let old = self.bindings.insert(name.into(), value);
assert!(old.is_none(), "variable bound twice in single context call");
self
}
crates/jrsonnet-evaluator/src/dynamic.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/dynamic.rs
+++ b/crates/jrsonnet-evaluator/src/dynamic.rs
@@ -52,9 +52,3 @@
Self::new()
}
}
-
-impl<T: Trace + Clone> From<Pending<T>> for Thunk<T> {
- fn from(value: Pending<T>) -> Self {
- Self::new(value)
- }
-}
crates/jrsonnet-evaluator/src/evaluate/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/evaluate/mod.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/mod.rs
@@ -36,7 +36,7 @@
}
}
Some(match &*expr.0 {
- Expr::Str(s) => Val::Str(StrValue::Flat(s.clone())),
+ Expr::Str(s) => Val::string(s.clone()),
Expr::Num(n) => Val::Num(*n),
Expr::Literal(LiteralType::False) => Val::Bool(false),
Expr::Literal(LiteralType::True) => Val::Bool(true),
@@ -135,7 +135,7 @@
let fctx = Pending::new();
let mut new_bindings = GcHashMap::with_capacity(var.capacity_hint());
let value = Thunk::evaluated(Val::Arr(ArrValue::lazy(vec![
- Thunk::evaluated(Val::Str(StrValue::Flat(field.clone()))),
+ Thunk::evaluated(Val::string(field.clone())),
Thunk::new(ObjectFieldThunk {
field: field.clone(),
obj: obj.clone(),
@@ -226,7 +226,7 @@
}
builder
- .member(name.clone())
+ .field(name.clone())
.with_add(*plus)
.with_visibility(*visibility)
.with_location(value.1.clone())
@@ -262,7 +262,7 @@
}
builder
- .member(name.clone())
+ .field(name.clone())
.with_visibility(*visibility)
.with_location(value.1.clone())
.bindable(UnboundMethod {
@@ -437,7 +437,7 @@
Literal(LiteralType::False) => Val::Bool(false),
Literal(LiteralType::Null) => Val::Null,
Parened(e) => evaluate(ctx, e)?,
- Str(v) => Val::Str(StrValue::Flat(v.clone())),
+ Str(v) => Val::string(v.clone()),
Num(v) => Val::new_checked_num(*v)?,
BinaryOp(v1, o, v2) => evaluate_binary_op_special(ctx, v1, *o, v2)?,
UnaryOp(o, v) => evaluate_unary_op(*o, &evaluate(ctx, v)?)?,
@@ -672,7 +672,7 @@
|| format!("import {:?}", path.clone()),
|| s.import_resolved(resolved_path),
)?,
- ImportStr(_) => Val::Str(StrValue::Flat(s.import_resolved_str(resolved_path)?)),
+ ImportStr(_) => Val::string(s.import_resolved_str(resolved_path)?),
ImportBin(_) => Val::Arr(ArrValue::bytes(s.import_resolved_bin(resolved_path)?)),
_ => unreachable!(),
}
crates/jrsonnet-evaluator/src/evaluate/operator.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/evaluate/operator.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/operator.rs
@@ -30,18 +30,12 @@
Ok(match (a, b) {
(Str(v1), Str(v2)) => Str(StrValue::concat(v1.clone(), v2.clone())),
- (Num(a), Str(b)) => Str(StrValue::Flat(format!("{a}{b}").into())),
- (Str(a), Num(b)) => Str(StrValue::Flat(format!("{a}{b}").into())),
+ (Num(a), Str(b)) => Val::string(format!("{a}{b}")),
+ (Str(a), Num(b)) => Val::string(format!("{a}{b}")),
- (Str(a), o) | (o, Str(a)) if a.is_empty() => {
- Val::Str(StrValue::Flat(o.clone().to_string()?))
- }
- (Str(a), o) => Str(StrValue::Flat(
- format!("{a}{}", o.clone().to_string()?).into(),
- )),
- (o, Str(a)) => Str(StrValue::Flat(
- format!("{}{a}", o.clone().to_string()?).into(),
- )),
+ (Str(a), o) | (o, Str(a)) if a.is_empty() => Val::string(o.clone().to_string()?),
+ (Str(a), o) => Val::string(format!("{a}{}", o.clone().to_string()?)),
+ (o, Str(a)) => Val::string(format!("{}{a}", o.clone().to_string()?)),
(Obj(v1), Obj(v2)) => Obj(v2.extend_from(v1.clone())),
(Arr(a), Arr(b)) => Val::Arr(ArrValue::extended(a.clone(), b.clone())),
@@ -149,7 +143,7 @@
(Str(a), In, Obj(obj)) => Bool(obj.has_field_ex(a.clone().into_flat(), true)),
(a, Mod, b) => evaluate_mod_op(a, b)?,
- (Str(v1), Mul, Num(v2)) => Str(StrValue::Flat(v1.to_string().repeat(*v2 as usize).into())),
+ (Str(v1), Mul, Num(v2)) => Val::string(v1.to_string().repeat(*v2 as usize)),
// Bool X Bool
(Bool(a), And, Bool(b)) => Bool(*a && *b),
crates/jrsonnet-evaluator/src/function/arglike.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/function/arglike.rs
+++ b/crates/jrsonnet-evaluator/src/function/arglike.rs
@@ -61,7 +61,7 @@
impl ArgLike for TlaArg {
fn evaluate_arg(&self, ctx: Context, tailstrict: bool) -> Result<Thunk<Val>> {
match self {
- TlaArg::String(s) => Ok(Thunk::evaluated(Val::Str(StrValue::Flat(s.clone())))),
+ TlaArg::String(s) => Ok(Thunk::evaluated(Val::string(s.clone()))),
TlaArg::Code(code) => Ok(if tailstrict {
Thunk::evaluated(evaluate(ctx, code)?)
} else {
crates/jrsonnet-evaluator/src/function/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/function/mod.rs
+++ b/crates/jrsonnet-evaluator/src/function/mod.rs
@@ -12,7 +12,10 @@
native::NativeDesc,
parse::{parse_default_function_call, parse_function_call},
};
-use crate::{evaluate, evaluate_trivial, gc::TraceBox, tb, Context, ContextBuilder, Result, Val};
+use crate::{
+ evaluate, evaluate_trivial, gc::TraceBox, tb, Context, ContextBuilder, Result,
+ Val,
+};
pub mod arglike;
pub mod builtin;
@@ -124,6 +127,9 @@
pub fn builtin(builtin: impl Builtin) -> Self {
Self::Builtin(Cc::new(tb!(builtin)))
}
+ pub fn static_builtin(static_builtin: &'static dyn StaticBuiltin) -> Self {
+ Self::StaticBuiltin(static_builtin)
+ }
pub fn params(&self) -> Vec<BuiltinParam> {
match self {
@@ -239,3 +245,17 @@
}
}
}
+
+impl<T> From<T> for FuncVal
+where
+ T: Builtin,
+{
+ fn from(value: T) -> Self {
+ Self::builtin(value)
+ }
+}
+impl From<&'static dyn StaticBuiltin> for FuncVal {
+ fn from(value: &'static dyn StaticBuiltin) -> Self {
+ Self::static_builtin(value)
+ }
+}
crates/jrsonnet-evaluator/src/function/native.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/function/native.rs
+++ b/crates/jrsonnet-evaluator/src/function/native.rs
@@ -2,7 +2,7 @@
arglike::{ArgLike, OptionalContext},
FuncVal,
};
-use crate::{error::Result, typed::Typed};
+use crate::{typed::Typed, Result};
pub trait NativeDesc {
type Value;
crates/jrsonnet-evaluator/src/gc.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/gc.rs
+++ b/crates/jrsonnet-evaluator/src/gc.rs
@@ -117,9 +117,7 @@
}
#[derive(Debug)]
-pub struct GcHashMap<K, V>(
- pub HashMap<K, V, BuildHasherDefault<FxHasher>>
-);
+pub struct GcHashMap<K, V>(pub HashMap<K, V, BuildHasherDefault<FxHasher>>);
impl<K, V> GcHashMap<K, V> {
pub fn new() -> Self {
Self(HashMap::default())
crates/jrsonnet-evaluator/src/integrations/serde.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/integrations/serde.rs
+++ b/crates/jrsonnet-evaluator/src/integrations/serde.rs
@@ -11,10 +11,8 @@
};
use crate::{
- arr::ArrValue,
- error::{Error as JrError, ErrorKind, Result},
- val::StrValue,
- ObjValue, ObjValueBuilder, State, Val,
+ arr::ArrValue, runtime_error, Error as JrError, ObjValue, ObjValueBuilder,
+ Result, State, Val,
};
impl<'de> Deserialize<'de> for Val {
@@ -57,7 +55,7 @@
where
E: serde::de::Error,
{
- Ok(Val::Str(StrValue::Flat(v.into())))
+ Ok(Val::string(v))
}
// visit_num! {
@@ -138,7 +136,7 @@
while let Some((k, v)) = map.next_entry::<Cow<'de, str>, Val>()? {
// Jsonnet ignores duplicate keys
- out.member(k.into()).value_unchecked(v);
+ out.field(k).value(v);
}
Ok(Val::Obj(out.build()))
@@ -264,7 +262,7 @@
let inner = Val::Arr(ArrValue::eager(self.data));
if let Some(variant) = self.variant {
let mut out = ObjValue::builder_with_capacity(1);
- out.member(variant).value_unchecked(inner);
+ out.field(variant).value(inner);
Ok(Val::Obj(out.build()))
} else {
Ok(inner)
@@ -365,7 +363,7 @@
{
let key = self.key.take().expect("no serialize_key called");
let value = value.serialize(IntoValSerializer)?;
- self.data.member(key).value(value)?;
+ self.data.field(key).try_value(value)?;
Ok(())
}
@@ -378,7 +376,7 @@
let key = key.serialize(IntoValSerializer)?;
let key = key.to_string()?;
let value = value.serialize(IntoValSerializer)?;
- self.data.member(key).value(value)?;
+ self.data.field(key).try_value(value)?;
Ok(())
}
@@ -386,7 +384,7 @@
let inner = Val::Obj(self.data.build());
if let Some(variant) = self.variant {
let mut out = ObjValue::builder_with_capacity(1);
- out.member(variant).value_unchecked(inner);
+ out.field(variant).value(inner);
Ok(Val::Obj(out.build()))
} else {
Ok(inner)
@@ -550,7 +548,7 @@
{
let mut out = ObjValue::builder_with_capacity(1);
let value = value.serialize(self)?;
- out.member(variant.into()).value_unchecked(value);
+ out.field(variant).value(value);
Ok(Val::Obj(out.build()))
}
crates/jrsonnet-evaluator/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/lib.rs
+++ b/crates/jrsonnet-evaluator/src/lib.rs
@@ -498,7 +498,7 @@
pub struct InitialUnderscore(pub Thunk<Val>);
impl ContextInitializer for InitialUnderscore {
fn populate(&self, _for_file: Source, builder: &mut ContextBuilder) {
- builder.bind("_".into(), self.0.clone());
+ builder.bind("_", self.0.clone());
}
fn as_any(&self) -> &dyn Any {
crates/jrsonnet-evaluator/src/manifest.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/manifest.rs
+++ b/crates/jrsonnet-evaluator/src/manifest.rs
@@ -174,11 +174,13 @@
Val::Str(s) => escape_string_json_buf(&s.clone().into_flat(), buf),
Val::Num(n) => write!(buf, "{n}").unwrap(),
#[cfg(feature = "exp-bigint")]
- Val::BigInt(n) => if options.preserve_bigints {
- write!(buf, "{n}").unwrap()
- } else {
- write!(buf, "{:?}", n.to_string()).unwrap()
- },
+ Val::BigInt(n) => {
+ if options.preserve_bigints {
+ write!(buf, "{n}").unwrap()
+ } else {
+ write!(buf, "{:?}", n.to_string()).unwrap()
+ }
+ }
Val::Arr(items) => {
buf.push('[');
if !items.is_empty() {
crates/jrsonnet-evaluator/src/obj.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/obj.rs
+++ b/crates/jrsonnet-evaluator/src/obj.rs
@@ -15,7 +15,7 @@
arr::{PickObjectKeyValues, PickObjectValues},
bail,
error::{suggest_object_fields, Error, ErrorKind::*},
- function::CallLocation,
+ function::{CallLocation, FuncVal},
gc::{GcHashMap, GcHashSet, TraceBox},
operator::evaluate_add_op,
tb,
@@ -345,7 +345,7 @@
pub(crate) fn extend_with_raw_member(self, key: IStr, value: ObjMember) -> Self {
let mut out = ObjValueBuilder::with_capacity(1);
out.with_super(self);
- let mut member = out.member(key);
+ let mut member = out.field(key);
if value.flags.add() {
member = member.add()
}
@@ -848,11 +848,27 @@
self.assertions.push(tb!(assertion));
self
}
- pub fn member(&mut self, name: IStr) -> ObjMemberBuilder<ValueBuilder<'_>> {
+ pub fn field(&mut self, name: impl Into<IStr>) -> ObjMemberBuilder<ValueBuilder<'_>> {
let field_index = self.next_field_index;
self.next_field_index = self.next_field_index.next();
- ObjMemberBuilder::new(ValueBuilder(self), name, field_index)
+ ObjMemberBuilder::new(ValueBuilder(self), name.into(), field_index)
}
+ /// Preset for common method definiton pattern:
+ /// Create a hidden field with the function value.
+ ///
+ /// `.field(name).hide().value(Val::function(value))`
+ pub fn method(&mut self, name: impl Into<IStr>, value: impl Into<FuncVal>) -> &mut Self {
+ self.field(name).hide().value(Val::Func(value.into()));
+ self
+ }
+ pub fn try_method(
+ &mut self,
+ name: impl Into<IStr>,
+ value: impl Into<FuncVal>,
+ ) -> Result<&mut Self> {
+ self.field(name).hide().try_value(Val::Func(value.into()))?;
+ Ok(self)
+ }
pub fn build(self) -> ObjValue {
if self.sup.is_none() && self.map.is_empty() && self.assertions.is_empty() {
@@ -930,18 +946,19 @@
pub struct ValueBuilder<'v>(&'v mut ObjValueBuilder);
impl ObjMemberBuilder<ValueBuilder<'_>> {
/// Inserts value, replacing if it is already defined
- pub fn value_unchecked(self, value: Val) {
+ pub fn value(self, value: impl Into<Val>) {
let (receiver, name, member) =
- self.build_member(MaybeUnbound::Bound(Thunk::evaluated(value)));
+ self.build_member(MaybeUnbound::Bound(Thunk::evaluated(value.into())));
let entry = receiver.0.map.entry(name);
entry.insert(member);
}
- pub fn value(self, value: Val) -> Result<()> {
- self.thunk(Thunk::evaluated(value))
+ /// Tries to insert value, returns an error if it was already defined
+ pub fn try_value(self, value: impl Into<Val>) -> Result<()> {
+ self.thunk(Thunk::evaluated(value.into()))
}
- pub fn thunk(self, value: Thunk<Val>) -> Result<()> {
- self.binding(MaybeUnbound::Bound(value))
+ pub fn thunk(self, value: impl Into<Thunk<Val>>) -> Result<()> {
+ self.binding(MaybeUnbound::Bound(value.into()))
}
pub fn bindable(self, bindable: impl Unbound<Bound = Val>) -> Result<()> {
self.binding(MaybeUnbound::Unbound(Cc::new(tb!(bindable))))
@@ -963,8 +980,8 @@
pub struct ExtendBuilder<'v>(&'v mut ObjValue);
impl ObjMemberBuilder<ExtendBuilder<'_>> {
- pub fn value(self, value: Val) {
- self.binding(MaybeUnbound::Bound(Thunk::evaluated(value)));
+ pub fn value(self, value: impl Into<Val>) {
+ self.binding(MaybeUnbound::Bound(Thunk::evaluated(value.into())));
}
pub fn bindable(self, bindable: TraceBox<dyn Unbound<Bound = Val>>) {
self.binding(MaybeUnbound::Unbound(Cc::new(bindable)));
crates/jrsonnet-evaluator/src/typed/conversions.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/typed/conversions.rs
+++ b/crates/jrsonnet-evaluator/src/typed/conversions.rs
@@ -276,7 +276,7 @@
const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Str);
fn into_untyped(value: Self) -> Result<Val> {
- Ok(Val::Str(StrValue::Flat(value)))
+ Ok(Val::string(value))
}
fn from_untyped(value: Val) -> Result<Self> {
@@ -292,7 +292,7 @@
const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Str);
fn into_untyped(value: Self) -> Result<Val> {
- Ok(Val::Str(StrValue::Flat(value.into())))
+ Ok(Val::string(value))
}
fn from_untyped(value: Val) -> Result<Self> {
@@ -308,7 +308,7 @@
const TYPE: &'static ComplexValType = &ComplexValType::Char;
fn into_untyped(value: Self) -> Result<Val> {
- Ok(Val::Str(StrValue::Flat(value.to_string().into())))
+ Ok(Val::string(value))
}
fn from_untyped(value: Val) -> Result<Self> {
@@ -356,7 +356,7 @@
bail!("map key should serialize to string");
};
let value = V::into_untyped(v)?;
- out.member(key).value_unchecked(value);
+ out.field(key).value(value);
}
Ok(Val::Obj(out.build()))
}
@@ -611,7 +611,7 @@
fn into_untyped(value: Self) -> Result<Val> {
match value {
- IndexableVal::Str(s) => Ok(Val::Str(StrValue::Flat(s))),
+ IndexableVal::Str(s) => Ok(Val::string(s)),
IndexableVal::Arr(a) => Ok(Val::Arr(a)),
}
}
crates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/val.rs
+++ b/crates/jrsonnet-evaluator/src/val.rs
@@ -142,6 +142,14 @@
}
}
}
+impl<T, V: Trace> From<T> for Thunk<V>
+where
+ T: ThunkValue<Output = V>,
+{
+ fn from(value: T) -> Self {
+ Thunk::new(value)
+ }
+}
impl<T: Trace + Default> Default for Thunk<T> {
fn default() -> Self {
@@ -323,21 +331,14 @@
}
}
}
-impl From<&str> for StrValue {
- fn from(value: &str) -> Self {
- Self::Flat(value.into())
- }
-}
-impl From<String> for StrValue {
- fn from(value: String) -> Self {
- Self::Flat(value.into())
+impl<T> From<T> for StrValue
+where
+ IStr: From<T>,
+{
+ fn from(value: T) -> Self {
+ Self::Flat(IStr::from(value))
}
}
-impl From<IStr> for StrValue {
- fn from(value: IStr) -> Self {
- Self::Flat(value)
- }
-}
impl Display for StrValue {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
@@ -401,7 +402,7 @@
impl From<IndexableVal> for Val {
fn from(v: IndexableVal) -> Self {
match v {
- IndexableVal::Str(s) => Self::Str(StrValue::Flat(s)),
+ IndexableVal::Str(s) => Self::string(s),
IndexableVal::Arr(a) => Self::Arr(a),
}
}
@@ -499,6 +500,34 @@
_ => bail!(ValueIsNotIndexable(self.value_type())),
})
}
+
+ pub fn function(function: impl Into<FuncVal>) -> Self {
+ Self::Func(function.into())
+ }
+ pub fn string(string: impl Into<StrValue>) -> Self {
+ Self::Str(string.into())
+ }
+}
+
+impl From<IStr> for Val {
+ fn from(value: IStr) -> Self {
+ Self::string(value)
+ }
+}
+impl From<String> for Val {
+ fn from(value: String) -> Self {
+ Self::string(value)
+ }
+}
+impl From<&str> for Val {
+ fn from(value: &str) -> Self {
+ Self::string(value)
+ }
+}
+impl From<ObjValue> for Val {
+ fn from(value: ObjValue) -> Self {
+ Self::Obj(value)
+ }
}
const fn is_function_like(val: &Val) -> bool {
crates/jrsonnet-macros/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-macros/src/lib.rs
+++ b/crates/jrsonnet-macros/src/lib.rs
@@ -567,18 +567,18 @@
if self.is_option {
quote! {
if let Some(value) = self.#ident {
- out.member(#name.into())
+ out.field(#name)
#hide
#add
- .value(<#ty as Typed>::into_untyped(value)?)?;
+ .try_value(<#ty as Typed>::into_untyped(value)?)?;
}
}
} else {
quote! {
- out.member(#name.into())
+ out.field(#name)
#hide
#add
- .value(<#ty as Typed>::into_untyped(self.#ident)?)?;
+ .try_value(<#ty as Typed>::into_untyped(self.#ident)?)?;
}
}
} else if self.is_option {
crates/jrsonnet-stdlib/src/arrays.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/arrays.rs
+++ b/crates/jrsonnet-stdlib/src/arrays.rs
@@ -36,7 +36,7 @@
#[builtin]
pub fn builtin_repeat(what: Either![IStr, ArrValue], count: usize) -> Result<Val> {
Ok(match what {
- Either2::A(s) => Val::Str(StrValue::Flat(s.repeat(count).into())),
+ Either2::A(s) => Val::string(s.repeat(count)),
Either2::B(arr) => Val::Arr(
ArrValue::repeated(arr, count)
.ok_or_else(|| runtime_error!("repeated length overflow"))?,
crates/jrsonnet-stdlib/src/lib.rsdiffbeforeafterboth1use std::{2 cell::{Ref, RefCell, RefMut},3 collections::HashMap,4 rc::Rc,5};67use jrsonnet_evaluator::{8 error::{ErrorKind::*, Result},9 function::{builtin::Builtin, CallLocation, FuncVal, TlaArg},10 gc::TraceBox,11 tb,12 trace::PathResolver,13 ContextBuilder, IStr, ObjValue, ObjValueBuilder, State, Thunk, Val,14};15use jrsonnet_gcmodule::{Cc, Trace};16use jrsonnet_parser::Source;1718mod expr;19mod types;20pub use types::*;21mod arrays;22pub use arrays::*;23mod math;24pub use math::*;25mod operator;26pub use operator::*;27mod sort;28pub use sort::*;29mod hash;30pub use hash::*;31mod encoding;32pub use encoding::*;33mod objects;34pub use objects::*;35mod manifest;36pub use manifest::*;37mod parse;38pub use parse::*;39mod strings;40pub use strings::*;41mod misc;42pub use misc::*;43mod sets;44pub use sets::*;45mod compat;46pub use compat::*;4748pub fn stdlib_uncached(settings: Rc<RefCell<Settings>>) -> ObjValue {49 let mut builder = ObjValueBuilder::new();5051 let expr = expr::stdlib_expr();52 let eval = jrsonnet_evaluator::evaluate(ContextBuilder::dangerous_empty_state().build(), &expr)53 .expect("stdlib.jsonnet should have no errors")54 .as_obj()55 .expect("stdlib.jsonnet should evaluate to object");5657 builder.with_super(eval);5859 for (name, builtin) in [60 // Types61 ("type", builtin_type::INST),62 ("isString", builtin_is_string::INST),63 ("isNumber", builtin_is_number::INST),64 ("isBoolean", builtin_is_boolean::INST),65 ("isObject", builtin_is_object::INST),66 ("isArray", builtin_is_array::INST),67 ("isFunction", builtin_is_function::INST),68 // Arrays69 ("makeArray", builtin_make_array::INST),70 ("repeat", builtin_repeat::INST),71 ("slice", builtin_slice::INST),72 ("map", builtin_map::INST),73 ("flatMap", builtin_flatmap::INST),74 ("filter", builtin_filter::INST),75 ("foldl", builtin_foldl::INST),76 ("foldr", builtin_foldr::INST),77 ("range", builtin_range::INST),78 ("join", builtin_join::INST),79 ("reverse", builtin_reverse::INST),80 ("any", builtin_any::INST),81 ("all", builtin_all::INST),82 ("member", builtin_member::INST),83 ("contains", builtin_contains::INST),84 ("count", builtin_count::INST),85 ("avg", builtin_avg::INST),86 ("removeAt", builtin_remove_at::INST),87 ("remove", builtin_remove::INST),88 // Math89 ("abs", builtin_abs::INST),90 ("sign", builtin_sign::INST),91 ("max", builtin_max::INST),92 ("min", builtin_min::INST),93 ("sum", builtin_sum::INST),94 ("modulo", builtin_modulo::INST),95 ("floor", builtin_floor::INST),96 ("ceil", builtin_ceil::INST),97 ("log", builtin_log::INST),98 ("pow", builtin_pow::INST),99 ("sqrt", builtin_sqrt::INST),100 ("sin", builtin_sin::INST),101 ("cos", builtin_cos::INST),102 ("tan", builtin_tan::INST),103 ("asin", builtin_asin::INST),104 ("acos", builtin_acos::INST),105 ("atan", builtin_atan::INST),106 ("exp", builtin_exp::INST),107 ("mantissa", builtin_mantissa::INST),108 ("exponent", builtin_exponent::INST),109 ("round", builtin_round::INST),110 ("isEven", builtin_is_even::INST),111 ("isOdd", builtin_is_odd::INST),112 ("isInteger", builtin_is_integer::INST),113 ("isDecimal", builtin_is_decimal::INST),114 // Operator115 ("mod", builtin_mod::INST),116 ("primitiveEquals", builtin_primitive_equals::INST),117 ("equals", builtin_equals::INST),118 ("xor", builtin_xor::INST),119 ("xnor", builtin_xnor::INST),120 ("format", builtin_format::INST),121 // Sort122 ("sort", builtin_sort::INST),123 ("uniq", builtin_uniq::INST),124 ("set", builtin_set::INST),125 ("minArray", builtin_min_array::INST),126 ("maxArray", builtin_max_array::INST),127 // Hash128 ("md5", builtin_md5::INST),129 ("sha1", builtin_sha1::INST),130 ("sha256", builtin_sha256::INST),131 ("sha512", builtin_sha512::INST),132 ("sha3", builtin_sha3::INST),133 // Encoding134 ("encodeUTF8", builtin_encode_utf8::INST),135 ("decodeUTF8", builtin_decode_utf8::INST),136 ("base64", builtin_base64::INST),137 ("base64Decode", builtin_base64_decode::INST),138 ("base64DecodeBytes", builtin_base64_decode_bytes::INST),139 // Objects140 ("objectFieldsEx", builtin_object_fields_ex::INST),141 ("objectValues", builtin_object_values::INST),142 ("objectValuesAll", builtin_object_values_all::INST),143 ("objectKeysValues", builtin_object_keys_values::INST),144 ("objectKeysValuesAll", builtin_object_keys_values_all::INST),145 ("objectHasEx", builtin_object_has_ex::INST),146 ("objectRemoveKey", builtin_object_remove_key::INST),147 // Manifest148 ("escapeStringJson", builtin_escape_string_json::INST),149 ("manifestJsonEx", builtin_manifest_json_ex::INST),150 ("manifestYamlDoc", builtin_manifest_yaml_doc::INST),151 ("manifestTomlEx", builtin_manifest_toml_ex::INST),152 // Parsing153 ("parseJson", builtin_parse_json::INST),154 ("parseYaml", builtin_parse_yaml::INST),155 // Strings156 ("codepoint", builtin_codepoint::INST),157 ("substr", builtin_substr::INST),158 ("char", builtin_char::INST),159 ("strReplace", builtin_str_replace::INST),160 ("isEmpty", builtin_is_empty::INST),161 ("equalsIgnoreCase", builtin_equals_ignore_case::INST),162 ("splitLimit", builtin_splitlimit::INST),163 ("asciiUpper", builtin_ascii_upper::INST),164 ("asciiLower", builtin_ascii_lower::INST),165 ("findSubstr", builtin_find_substr::INST),166 ("parseInt", builtin_parse_int::INST),167 #[cfg(feature = "exp-bigint")]168 ("bigint", builtin_bigint::INST),169 ("parseOctal", builtin_parse_octal::INST),170 ("parseHex", builtin_parse_hex::INST),171 // Misc172 ("length", builtin_length::INST),173 ("startsWith", builtin_starts_with::INST),174 ("endsWith", builtin_ends_with::INST),175 // Sets176 ("setMember", builtin_set_member::INST),177 ("setInter", builtin_set_inter::INST),178 ("setDiff", builtin_set_diff::INST),179 // Compat180 ("__compare", builtin___compare::INST),181 ]182 .iter()183 .cloned()184 {185 builder186 .member(name.into())187 .hide()188 .value(Val::Func(FuncVal::StaticBuiltin(builtin)))189 .expect("no conflict");190 }191192 builder193 .member("extVar".into())194 .hide()195 .value(Val::Func(FuncVal::builtin(builtin_ext_var {196 settings: settings.clone(),197 })))198 .expect("no conflict");199 builder200 .member("native".into())201 .hide()202 .value(Val::Func(FuncVal::builtin(builtin_native {203 settings: settings.clone(),204 })))205 .expect("no conflict");206 builder207 .member("trace".into())208 .hide()209 .value(Val::Func(FuncVal::builtin(builtin_trace { settings })))210 .expect("no conflict");211212 builder213 .member("id".into())214 .hide()215 .value(Val::Func(FuncVal::Id))216 .expect("no conflict");217218 builder.build()219}220221pub trait TracePrinter {222 fn print_trace(&self, loc: CallLocation, value: IStr);223}224225pub struct StdTracePrinter {226 resolver: PathResolver,227}228impl StdTracePrinter {229 pub fn new(resolver: PathResolver) -> Self {230 Self { resolver }231 }232}233impl TracePrinter for StdTracePrinter {234 fn print_trace(&self, loc: CallLocation, value: IStr) {235 eprint!("TRACE:");236 if let Some(loc) = loc.0 {237 let locs = loc.0.map_source_locations(&[loc.1]);238 eprint!(239 " {}:{}",240 match loc.0.source_path().path() {241 Some(p) => self.resolver.resolve(p),242 None => loc.0.source_path().to_string(),243 },244 locs[0].line245 );246 }247 eprintln!(" {value}");248 }249}250251pub struct Settings {252 /// Used for `std.extVar`253 pub ext_vars: HashMap<IStr, TlaArg>,254 /// Used for `std.native`255 pub ext_natives: HashMap<IStr, Cc<TraceBox<dyn Builtin>>>,256 /// Used for `std.trace`257 pub trace_printer: Box<dyn TracePrinter>,258 /// Used for `std.thisFile`259 pub path_resolver: PathResolver,260}261262fn extvar_source(name: &str, code: impl Into<IStr>) -> Source {263 let source_name = format!("<extvar:{name}>");264 Source::new_virtual(source_name.into(), code.into())265}266267#[derive(Trace, Clone)]268pub struct ContextInitializer {269 /// When we don't need to support legacy-this-file, we can reuse same context for all files270 #[cfg(not(feature = "legacy-this-file"))]271 context: jrsonnet_evaluator::Context,272 /// For `populate`273 #[cfg(not(feature = "legacy-this-file"))]274 stdlib_thunk: Thunk<Val>,275 /// Otherwise, we can only keep first stdlib layer, and then stack thisFile on top of it276 #[cfg(feature = "legacy-this-file")]277 stdlib_obj: ObjValue,278 settings: Rc<RefCell<Settings>>,279}280impl ContextInitializer {281 pub fn new(_s: State, resolver: PathResolver) -> Self {282 let settings = Settings {283 ext_vars: Default::default(),284 ext_natives: Default::default(),285 trace_printer: Box::new(StdTracePrinter::new(resolver.clone())),286 path_resolver: resolver,287 };288 let settings = Rc::new(RefCell::new(settings));289 let stdlib_obj = stdlib_uncached(settings.clone());290 #[cfg(not(feature = "legacy-this-file"))]291 let stdlib_thunk = Thunk::evaluated(Val::Obj(stdlib_obj));292 Self {293 #[cfg(not(feature = "legacy-this-file"))]294 context: {295 let mut context = ContextBuilder::with_capacity(_s, 1);296 context.bind("std".into(), stdlib_thunk.clone());297 context.build()298 },299 #[cfg(not(feature = "legacy-this-file"))]300 stdlib_thunk,301 #[cfg(feature = "legacy-this-file")]302 stdlib_obj,303 settings,304 }305 }306 pub fn settings(&self) -> Ref<Settings> {307 self.settings.borrow()308 }309 pub fn settings_mut(&self) -> RefMut<Settings> {310 self.settings.borrow_mut()311 }312 pub fn add_ext_var(&self, name: IStr, value: Val) {313 self.settings_mut()314 .ext_vars315 .insert(name, TlaArg::Val(value));316 }317 pub fn add_ext_str(&self, name: IStr, value: IStr) {318 self.settings_mut()319 .ext_vars320 .insert(name, TlaArg::String(value));321 }322 pub fn add_ext_code(&self, name: &str, code: impl Into<IStr>) -> Result<()> {323 let code = code.into();324 let source = extvar_source(name, code.clone());325 let parsed = jrsonnet_parser::parse(326 &code,327 &jrsonnet_parser::ParserSettings {328 source: source.clone(),329 },330 )331 .map_err(|e| ImportSyntaxError {332 path: source,333 error: Box::new(e),334 })?;335 // self.data_mut().volatile_files.insert(source_name, code);336 self.settings_mut()337 .ext_vars338 .insert(name.into(), TlaArg::Code(parsed));339 Ok(())340 }341 pub fn add_native(&self, name: IStr, cb: impl Builtin) {342 self.settings_mut()343 .ext_natives344 .insert(name, Cc::new(tb!(cb)));345 }346}347impl jrsonnet_evaluator::ContextInitializer for ContextInitializer {348 fn reserve_vars(&self) -> usize {349 1350 }351 #[cfg(not(feature = "legacy-this-file"))]352 fn initialize(&self, _s: State, _source: Source) -> jrsonnet_evaluator::Context {353 self.context.clone()354 }355 #[cfg(not(feature = "legacy-this-file"))]356 fn populate(&self, _for_file: Source, builder: &mut ContextBuilder) {357 builder.bind("std".into(), self.stdlib_thunk.clone());358 }359 #[cfg(feature = "legacy-this-file")]360 fn populate(&self, source: Source, builder: &mut ContextBuilder) {361 use jrsonnet_evaluator::val::StrValue;362363 let mut std = ObjValueBuilder::new();364 std.with_super(self.stdlib_obj.clone());365 std.member("thisFile".into())366 .hide()367 .value(Val::Str(StrValue::Flat(368 match source.source_path().path() {369 Some(p) => self.settings().path_resolver.resolve(p).into(),370 None => source.source_path().to_string().into(),371 },372 )))373 .expect("this object builder is empty");374 let stdlib_with_this_file = std.build();375376 builder.bind(377 "std".into(),378 Thunk::evaluated(Val::Obj(stdlib_with_this_file)),379 );380 }381 fn as_any(&self) -> &dyn std::any::Any {382 self383 }384}385386pub trait StateExt {387 /// This method was previously implemented in jrsonnet-evaluator itself388 fn with_stdlib(&self);389}390391impl StateExt for State {392 fn with_stdlib(&self) {393 let initializer = ContextInitializer::new(self.clone(), PathResolver::new_cwd_fallback());394 self.settings_mut().context_initializer = tb!(initializer)395 }396}1use std::{2 cell::{Ref, RefCell, RefMut},3 collections::HashMap,4 rc::Rc,5};67use jrsonnet_evaluator::{8 error::{ErrorKind::*, Result},9 function::{CallLocation, FuncVal, TlaArg},10 tb,11 trace::PathResolver,12 ContextBuilder, IStr, ObjValue, ObjValueBuilder, State, Thunk, Val,13};14use jrsonnet_gcmodule::Trace;15use jrsonnet_parser::Source;1617mod expr;18mod types;19pub use types::*;20mod arrays;21pub use arrays::*;22mod math;23pub use math::*;24mod operator;25pub use operator::*;26mod sort;27pub use sort::*;28mod hash;29pub use hash::*;30mod encoding;31pub use encoding::*;32mod objects;33pub use objects::*;34mod manifest;35pub use manifest::*;36mod parse;37pub use parse::*;38mod strings;39pub use strings::*;40mod misc;41pub use misc::*;42mod sets;43pub use sets::*;44mod compat;45pub use compat::*;4647pub fn stdlib_uncached(settings: Rc<RefCell<Settings>>) -> ObjValue {48 let mut builder = ObjValueBuilder::new();4950 let expr = expr::stdlib_expr();51 let eval = jrsonnet_evaluator::evaluate(ContextBuilder::dangerous_empty_state().build(), &expr)52 .expect("stdlib.jsonnet should have no errors")53 .as_obj()54 .expect("stdlib.jsonnet should evaluate to object");5556 builder.with_super(eval);5758 for (name, builtin) in [59 // Types60 ("type", builtin_type::INST),61 ("isString", builtin_is_string::INST),62 ("isNumber", builtin_is_number::INST),63 ("isBoolean", builtin_is_boolean::INST),64 ("isObject", builtin_is_object::INST),65 ("isArray", builtin_is_array::INST),66 ("isFunction", builtin_is_function::INST),67 // Arrays68 ("makeArray", builtin_make_array::INST),69 ("repeat", builtin_repeat::INST),70 ("slice", builtin_slice::INST),71 ("map", builtin_map::INST),72 ("flatMap", builtin_flatmap::INST),73 ("filter", builtin_filter::INST),74 ("foldl", builtin_foldl::INST),75 ("foldr", builtin_foldr::INST),76 ("range", builtin_range::INST),77 ("join", builtin_join::INST),78 ("reverse", builtin_reverse::INST),79 ("any", builtin_any::INST),80 ("all", builtin_all::INST),81 ("member", builtin_member::INST),82 ("contains", builtin_contains::INST),83 ("count", builtin_count::INST),84 ("avg", builtin_avg::INST),85 ("removeAt", builtin_remove_at::INST),86 ("remove", builtin_remove::INST),87 // Math88 ("abs", builtin_abs::INST),89 ("sign", builtin_sign::INST),90 ("max", builtin_max::INST),91 ("min", builtin_min::INST),92 ("sum", builtin_sum::INST),93 ("modulo", builtin_modulo::INST),94 ("floor", builtin_floor::INST),95 ("ceil", builtin_ceil::INST),96 ("log", builtin_log::INST),97 ("pow", builtin_pow::INST),98 ("sqrt", builtin_sqrt::INST),99 ("sin", builtin_sin::INST),100 ("cos", builtin_cos::INST),101 ("tan", builtin_tan::INST),102 ("asin", builtin_asin::INST),103 ("acos", builtin_acos::INST),104 ("atan", builtin_atan::INST),105 ("exp", builtin_exp::INST),106 ("mantissa", builtin_mantissa::INST),107 ("exponent", builtin_exponent::INST),108 ("round", builtin_round::INST),109 ("isEven", builtin_is_even::INST),110 ("isOdd", builtin_is_odd::INST),111 ("isInteger", builtin_is_integer::INST),112 ("isDecimal", builtin_is_decimal::INST),113 // Operator114 ("mod", builtin_mod::INST),115 ("primitiveEquals", builtin_primitive_equals::INST),116 ("equals", builtin_equals::INST),117 ("xor", builtin_xor::INST),118 ("xnor", builtin_xnor::INST),119 ("format", builtin_format::INST),120 // Sort121 ("sort", builtin_sort::INST),122 ("uniq", builtin_uniq::INST),123 ("set", builtin_set::INST),124 ("minArray", builtin_min_array::INST),125 ("maxArray", builtin_max_array::INST),126 // Hash127 ("md5", builtin_md5::INST),128 ("sha1", builtin_sha1::INST),129 ("sha256", builtin_sha256::INST),130 ("sha512", builtin_sha512::INST),131 ("sha3", builtin_sha3::INST),132 // Encoding133 ("encodeUTF8", builtin_encode_utf8::INST),134 ("decodeUTF8", builtin_decode_utf8::INST),135 ("base64", builtin_base64::INST),136 ("base64Decode", builtin_base64_decode::INST),137 ("base64DecodeBytes", builtin_base64_decode_bytes::INST),138 // Objects139 ("objectFieldsEx", builtin_object_fields_ex::INST),140 ("objectValues", builtin_object_values::INST),141 ("objectValuesAll", builtin_object_values_all::INST),142 ("objectKeysValues", builtin_object_keys_values::INST),143 ("objectKeysValuesAll", builtin_object_keys_values_all::INST),144 ("objectHasEx", builtin_object_has_ex::INST),145 ("objectRemoveKey", builtin_object_remove_key::INST),146 // Manifest147 ("escapeStringJson", builtin_escape_string_json::INST),148 ("manifestJsonEx", builtin_manifest_json_ex::INST),149 ("manifestYamlDoc", builtin_manifest_yaml_doc::INST),150 ("manifestTomlEx", builtin_manifest_toml_ex::INST),151 // Parsing152 ("parseJson", builtin_parse_json::INST),153 ("parseYaml", builtin_parse_yaml::INST),154 // Strings155 ("codepoint", builtin_codepoint::INST),156 ("substr", builtin_substr::INST),157 ("char", builtin_char::INST),158 ("strReplace", builtin_str_replace::INST),159 ("isEmpty", builtin_is_empty::INST),160 ("equalsIgnoreCase", builtin_equals_ignore_case::INST),161 ("splitLimit", builtin_splitlimit::INST),162 ("asciiUpper", builtin_ascii_upper::INST),163 ("asciiLower", builtin_ascii_lower::INST),164 ("findSubstr", builtin_find_substr::INST),165 ("parseInt", builtin_parse_int::INST),166 #[cfg(feature = "exp-bigint")]167 ("bigint", builtin_bigint::INST),168 ("parseOctal", builtin_parse_octal::INST),169 ("parseHex", builtin_parse_hex::INST),170 // Misc171 ("length", builtin_length::INST),172 ("startsWith", builtin_starts_with::INST),173 ("endsWith", builtin_ends_with::INST),174 // Sets175 ("setMember", builtin_set_member::INST),176 ("setInter", builtin_set_inter::INST),177 ("setDiff", builtin_set_diff::INST),178 // Compat179 ("__compare", builtin___compare::INST),180 ]181 .iter()182 .cloned()183 {184 builder.method(name, builtin);185 }186187 builder.method(188 "extVar",189 builtin_ext_var {190 settings: settings.clone(),191 },192 );193 builder.method(194 "native",195 builtin_native {196 settings: settings.clone(),197 },198 );199 builder.method("trace", builtin_trace { settings });200201 builder.method("id", FuncVal::Id);202203 builder.build()204}205206pub trait TracePrinter {207 fn print_trace(&self, loc: CallLocation, value: IStr);208}209210pub struct StdTracePrinter {211 resolver: PathResolver,212}213impl StdTracePrinter {214 pub fn new(resolver: PathResolver) -> Self {215 Self { resolver }216 }217}218impl TracePrinter for StdTracePrinter {219 fn print_trace(&self, loc: CallLocation, value: IStr) {220 eprint!("TRACE:");221 if let Some(loc) = loc.0 {222 let locs = loc.0.map_source_locations(&[loc.1]);223 eprint!(224 " {}:{}",225 match loc.0.source_path().path() {226 Some(p) => self.resolver.resolve(p),227 None => loc.0.source_path().to_string(),228 },229 locs[0].line230 );231 }232 eprintln!(" {value}");233 }234}235236pub struct Settings {237 /// Used for `std.extVar`238 pub ext_vars: HashMap<IStr, TlaArg>,239 /// Used for `std.native`240 pub ext_natives: HashMap<IStr, Cc<TraceBox<dyn Builtin>>>,241 /// Used for `std.trace`242 pub trace_printer: Box<dyn TracePrinter>,243 /// Used for `std.thisFile`244 pub path_resolver: PathResolver,245}246247fn extvar_source(name: &str, code: impl Into<IStr>) -> Source {248 let source_name = format!("<extvar:{name}>");249 Source::new_virtual(source_name.into(), code.into())250}251252#[derive(Trace, Clone)]253pub struct ContextInitializer {254 /// When we don't need to support legacy-this-file, we can reuse same context for all files255 #[cfg(not(feature = "legacy-this-file"))]256 context: jrsonnet_evaluator::Context,257 /// For `populate`258 #[cfg(not(feature = "legacy-this-file"))]259 stdlib_thunk: Thunk<Val>,260 /// Otherwise, we can only keep first stdlib layer, and then stack thisFile on top of it261 #[cfg(feature = "legacy-this-file")]262 stdlib_obj: ObjValue,263 settings: Rc<RefCell<Settings>>,264}265impl ContextInitializer {266 pub fn new(_s: State, resolver: PathResolver) -> Self {267 let settings = Settings {268 ext_vars: Default::default(),269 ext_natives: Default::default(),270 trace_printer: Box::new(StdTracePrinter::new(resolver.clone())),271 path_resolver: resolver,272 };273 let settings = Rc::new(RefCell::new(settings));274 let stdlib_obj = stdlib_uncached(settings.clone());275 #[cfg(not(feature = "legacy-this-file"))]276 let stdlib_thunk = Thunk::evaluated(Val::Obj(stdlib_obj));277 Self {278 #[cfg(not(feature = "legacy-this-file"))]279 context: {280 let mut context = ContextBuilder::with_capacity(_s, 1);281 context.bind("std", stdlib_thunk.clone());282 context.build()283 },284 #[cfg(not(feature = "legacy-this-file"))]285 stdlib_thunk,286 #[cfg(feature = "legacy-this-file")]287 stdlib_obj,288 settings,289 }290 }291 pub fn settings(&self) -> Ref<Settings> {292 self.settings.borrow()293 }294 pub fn settings_mut(&self) -> RefMut<Settings> {295 self.settings.borrow_mut()296 }297 pub fn add_ext_var(&self, name: IStr, value: Val) {298 self.settings_mut()299 .ext_vars300 .insert(name, TlaArg::Val(value));301 }302 pub fn add_ext_str(&self, name: IStr, value: IStr) {303 self.settings_mut()304 .ext_vars305 .insert(name, TlaArg::String(value));306 }307 pub fn add_ext_code(&self, name: &str, code: impl Into<IStr>) -> Result<()> {308 let code = code.into();309 let source = extvar_source(name, code.clone());310 let parsed = jrsonnet_parser::parse(311 &code,312 &jrsonnet_parser::ParserSettings {313 source: source.clone(),314 },315 )316 .map_err(|e| ImportSyntaxError {317 path: source,318 error: Box::new(e),319 })?;320 // self.data_mut().volatile_files.insert(source_name, code);321 self.settings_mut()322 .ext_vars323 .insert(name.into(), TlaArg::Code(parsed));324 Ok(())325 }326 pub fn add_native(&self, name: impl Into<IStr>, cb: impl Into<FuncVal>) {327 self.settings_mut()328 .ext_natives329 .insert(name.into(), cb.into());330 }331}332impl jrsonnet_evaluator::ContextInitializer for ContextInitializer {333 fn reserve_vars(&self) -> usize {334 1335 }336 #[cfg(not(feature = "legacy-this-file"))]337 fn initialize(&self, _s: State, _source: Source) -> jrsonnet_evaluator::Context {338 self.context.clone()339 }340 #[cfg(not(feature = "legacy-this-file"))]341 fn populate(&self, _for_file: Source, builder: &mut ContextBuilder) {342 builder.bind("std", self.stdlib_thunk.clone());343 }344 #[cfg(feature = "legacy-this-file")]345 fn populate(&self, source: Source, builder: &mut ContextBuilder) {346 use jrsonnet_evaluator::val::StrValue;347348 let mut std = ObjValueBuilder::new();349 std.with_super(self.stdlib_obj.clone());350 std.field("thisFile".into())351 .hide()352 .value(Val::string(353 match source.source_path().path() {354 Some(p) => self.settings().path_resolver.resolve(p).into(),355 None => source.source_path().to_string().into(),356 },357 ))358 .expect("this object builder is empty");359 let stdlib_with_this_file = std.build();360361 builder.bind(362 "std".into(),363 Thunk::evaluated(Val::Obj(stdlib_with_this_file)),364 );365 }366 fn as_any(&self) -> &dyn std::any::Any {367 self368 }369}370371pub trait StateExt {372 /// This method was previously implemented in jrsonnet-evaluator itself373 fn with_stdlib(&self);374}375376impl StateExt for State {377 fn with_stdlib(&self) {378 let initializer = ContextInitializer::new(self.clone(), PathResolver::new_cwd_fallback());379 self.settings_mut().context_initializer = tb!(initializer)380 }381}crates/jrsonnet-stdlib/src/misc.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/misc.rs
+++ b/crates/jrsonnet-stdlib/src/misc.rs
@@ -47,7 +47,7 @@
.ext_natives
.get(&x)
.cloned()
- .map_or(Val::Null, |v| Val::Func(FuncVal::Builtin(v)))
+ .map_or(Val::Null, |v| Val::Func(v))
}
#[builtin(fields(
crates/jrsonnet-stdlib/src/objects.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/objects.rs
+++ b/crates/jrsonnet-stdlib/src/objects.rs
@@ -122,7 +122,7 @@
if k == key {
continue;
}
- new_obj.member(k).value_unchecked(v.unwrap())
+ new_obj.field(k).value(v.unwrap())
}
new_obj.build()
crates/jrsonnet-stdlib/src/operator.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/operator.rs
+++ b/crates/jrsonnet-stdlib/src/operator.rs
@@ -16,7 +16,7 @@
evaluate_mod_op(
&match a {
A(v) => Val::Num(v),
- B(s) => Val::Str(StrValue::Flat(s)),
+ B(s) => Val::string(s),
},
&b,
)
crates/jrsonnet-stdlib/src/sets.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/sets.rs
+++ b/crates/jrsonnet-stdlib/src/sets.rs
@@ -1,11 +1,10 @@
use std::cmp::Ordering;
use jrsonnet_evaluator::{
- error::Result,
function::{builtin, FuncVal},
operator::evaluate_compare_op,
val::ArrValue,
- Thunk, Val,
+ Result, Thunk, Val,
};
use jrsonnet_parser::BinaryOpType;
@@ -108,7 +107,7 @@
}
};
}
- while let Some(ac) = &ak {
+ while let Some(_ac) = &ak {
// In a, but not in b
out.push(av.clone().expect("ak != None"));
av = a.next();
crates/jrsonnet-stdlib/src/strings.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/strings.rs
+++ b/crates/jrsonnet-stdlib/src/strings.rs
@@ -3,7 +3,7 @@
error::{ErrorKind::*, Result},
function::builtin,
typed::{Either2, M1},
- val::{ArrValue, StrValue},
+ val::ArrValue,
Either, IStr, Val,
};
@@ -41,14 +41,8 @@
pub fn builtin_splitlimit(str: IStr, c: IStr, maxsplits: Either![usize, M1]) -> ArrValue {
use Either2::*;
match maxsplits {
- A(n) => str
- .splitn(n + 1, &c as &str)
- .map(|s| Val::Str(StrValue::Flat(s.into())))
- .collect(),
- B(_) => str
- .split(&c as &str)
- .map(|s| Val::Str(StrValue::Flat(s.into())))
- .collect(),
+ A(n) => str.splitn(n + 1, &c as &str).map(Val::string).collect(),
+ B(_) => str.split(&c as &str).map(Val::string).collect(),
}
}
tests/tests/builtin.rsdiffbeforeafterboth--- a/tests/tests/builtin.rs
+++ b/tests/tests/builtin.rs
@@ -36,7 +36,7 @@
s.with_stdlib();
s.add_global(
"nativeAdd".into(),
- Thunk::evaluated(Val::Func(FuncVal::StaticBuiltin(native_add::INST))),
+ Thunk::evaluated(Val::function(native_add::INST)),
);
let v = s.evaluate_snippet(
@@ -69,7 +69,7 @@
s.with_stdlib();
s.add_global(
"curryAdd".into(),
- Thunk::evaluated(Val::Func(FuncVal::StaticBuiltin(curry_add::INST))),
+ Thunk::evaluated(Val::function(curry_add::INST)),
);
let v = s.evaluate_snippet(
tests/tests/common.rsdiffbeforeafterboth--- a/tests/tests/common.rs
+++ b/tests/tests/common.rs
@@ -77,12 +77,8 @@
#[allow(dead_code)]
pub fn with_test(s: &State) {
let mut bobj = ObjValueBuilder::new();
- bobj.member("assertThrow".into())
- .hide()
- .value_unchecked(Val::Func(FuncVal::StaticBuiltin(assert_throw::INST)));
- bobj.member("paramNames".into())
- .hide()
- .value_unchecked(Val::Func(FuncVal::StaticBuiltin(param_names::INST)));
+ bobj.method("assertThrow", assert_throw::INST);
+ bobj.method("paramNames", param_names::INST);
s.add_global("test".into(), Thunk::evaluated(Val::Obj(bobj.build())))
}