difftreelog
refactor better rebinding handling
in: master
15 files changed
crates/jrsonnet-evaluator/src/ctx.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/ctx.rs
+++ b/crates/jrsonnet-evaluator/src/ctx.rs
@@ -4,34 +4,15 @@
use jrsonnet_interner::IStr;
use crate::{
- cc_ptr_eq, error::Error::*, gc::GcHashMap, map::LayeredHashMap, LazyBinding, ObjValue, Pending,
- Result, State, Thunk, Val,
+ cc_ptr_eq, error::Error::*, gc::GcHashMap, map::LayeredHashMap, ObjValue, Pending, Result,
+ Thunk, Val,
};
-#[derive(Clone, Trace)]
-pub struct ContextCreator(pub Context, pub Pending<GcHashMap<IStr, LazyBinding>>);
-impl ContextCreator {
- pub fn create(
- &self,
- s: State,
- this: Option<ObjValue>,
- super_obj: Option<ObjValue>,
- ) -> Result<Context> {
- self.0.clone().extend_unbound(
- s,
- self.1.clone().unwrap(),
- self.0.dollar().clone().or_else(|| this.clone()),
- this,
- super_obj,
- )
- }
-}
-
#[derive(Trace)]
struct ContextInternals {
dollar: Option<ObjValue>,
+ sup: Option<ObjValue>,
this: Option<ObjValue>,
- super_obj: Option<ObjValue>,
bindings: LayeredHashMap,
}
impl Debug for ContextInternals {
@@ -56,14 +37,14 @@
}
pub fn super_obj(&self) -> &Option<ObjValue> {
- &self.0.super_obj
+ &self.0.sup
}
pub fn new() -> Self {
Self(Cc::new(ContextInternals {
dollar: None,
this: None,
- super_obj: None,
+ sup: None,
bindings: LayeredHashMap::default(),
}))
}
@@ -92,11 +73,6 @@
let mut new_bindings = GcHashMap::with_capacity(1);
new_bindings.insert(name, Thunk::evaluated(value));
self.extend(new_bindings, None, None, None)
- }
-
- #[must_use]
- pub fn with_this_super(self, new_this: ObjValue, new_super_obj: Option<ObjValue>) -> Self {
- self.extend(GcHashMap::new(), None, Some(new_this), new_super_obj)
}
#[must_use]
@@ -104,13 +80,13 @@
self,
new_bindings: GcHashMap<IStr, Thunk<Val>>,
new_dollar: Option<ObjValue>,
+ new_sup: Option<ObjValue>,
new_this: Option<ObjValue>,
- new_super_obj: Option<ObjValue>,
) -> Self {
let ctx = &self.0;
let dollar = new_dollar.or_else(|| ctx.dollar.clone());
let this = new_this.or_else(|| ctx.this.clone());
- let super_obj = new_super_obj.or_else(|| ctx.super_obj.clone());
+ let sup = new_sup.or_else(|| ctx.sup.clone());
let bindings = if new_bindings.is_empty() {
ctx.bindings.clone()
} else {
@@ -118,32 +94,10 @@
};
Self(Cc::new(ContextInternals {
dollar,
+ sup,
this,
- super_obj,
bindings,
}))
- }
- #[must_use]
- pub fn extend_bound(self, new_bindings: GcHashMap<IStr, Thunk<Val>>) -> Self {
- let new_this = self.0.this.clone();
- let new_super_obj = self.0.super_obj.clone();
- self.extend(new_bindings, None, new_this, new_super_obj)
- }
- pub fn extend_unbound(
- self,
- s: State,
- new_bindings: GcHashMap<IStr, LazyBinding>,
- new_dollar: Option<ObjValue>,
- new_this: Option<ObjValue>,
- new_super_obj: Option<ObjValue>,
- ) -> Result<Self> {
- let this = new_this.or_else(|| self.0.this.clone());
- let super_obj = new_super_obj.or_else(|| self.0.super_obj.clone());
- let mut new = GcHashMap::with_capacity(new_bindings.len());
- for (k, v) in new_bindings.0 {
- new.insert(k, v.evaluate(s.clone(), this.clone(), super_obj.clone())?);
- }
- Ok(self.extend(new, new_dollar, this, super_obj))
}
}
crates/jrsonnet-evaluator/src/evaluate/destructure.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/evaluate/destructure.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/destructure.rs
@@ -11,12 +11,13 @@
Context, Pending, State, Thunk, Val,
};
+#[allow(clippy::too_many_lines)]
fn destruct(
d: &Destruct,
parent: Thunk<Val>,
new_bindings: &mut GcHashMap<IStr, Thunk<Val>>,
) -> Result<()> {
- Ok(match d {
+ match d {
Destruct::Full(v) => {
let old = new_bindings.insert(v.clone(), parent);
if old.is_some() {
@@ -157,8 +158,6 @@
}
#[cfg(feature = "exp-destruct")]
Destruct::Object { fields, rest } => {
- use jrsonnet_parser::DestructRest;
-
use crate::{obj::ObjValue, throw_runtime};
#[derive(Trace)]
@@ -223,7 +222,8 @@
}
}
}
- })
+ }
+ Ok(())
}
pub fn evaluate_dest(
crates/jrsonnet-evaluator/src/evaluate/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/evaluate/mod.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/mod.rs
@@ -1,7 +1,9 @@
+use std::rc::Rc;
+
use gcmodule::{Cc, Trace};
use jrsonnet_interner::IStr;
use jrsonnet_parser::{
- ArgsDesc, AssertStmt, BindSpec, CompSpec, Destruct, Expr, FieldMember, ForSpecData, IfSpecData,
+ ArgsDesc, AssertStmt, BindSpec, CompSpec, Expr, FieldMember, ForSpecData, IfSpecData,
LiteralType, LocExpr, Member, ObjBody, ParamsDesc,
};
use jrsonnet_types::ValType;
@@ -14,147 +16,13 @@
stdlib::{std_slice, BUILTINS},
tb, throw,
typed::Typed,
- val::{ArrValue, Thunk, ThunkValue},
- Bindable, Context, ContextCreator, GcHashMap, LazyBinding, ObjValue, ObjValueBuilder,
- ObjectAssertion, Pending, Result, State, Val,
+ val::{ArrValue, CachedBindable, Thunk, ThunkValue},
+ Bindable, Context, GcHashMap, ObjValue, ObjValueBuilder, ObjectAssertion, Pending, Result,
+ State, Val,
};
pub mod destructure;
pub mod operator;
-
-#[allow(clippy::too_many_lines)]
-pub fn evaluate_binding(b: BindSpec, cctx: ContextCreator) -> Result<(IStr, LazyBinding)> {
- match b {
- BindSpec::Field {
- into: Destruct::Full(name),
- value,
- } => {
- #[derive(Trace)]
- struct BindableNamedThunk {
- this: Option<ObjValue>,
- super_obj: Option<ObjValue>,
-
- cctx: ContextCreator,
- name: IStr,
- value: LocExpr,
- }
- impl ThunkValue for BindableNamedThunk {
- type Output = Val;
- fn get(self: Box<Self>, s: State) -> Result<Val> {
- evaluate_named(
- s.clone(),
- self.cctx.create(s, self.this, self.super_obj)?,
- &self.value,
- self.name,
- )
- }
- }
-
- #[derive(Trace)]
- struct BindableNamed {
- cctx: ContextCreator,
- name: IStr,
- value: LocExpr,
- }
- impl Bindable for BindableNamed {
- fn bind(
- &self,
- _: State,
- this: Option<ObjValue>,
- super_obj: Option<ObjValue>,
- ) -> Result<Thunk<Val>> {
- Ok(Thunk::new(tb!(BindableNamedThunk {
- this,
- super_obj,
- cctx: self.cctx.clone(),
- name: self.name.clone(),
- value: self.value.clone(),
- })))
- }
- }
-
- Ok((
- name.clone(),
- LazyBinding::Bindable(Cc::new(tb!(BindableNamed {
- cctx,
- name: name.clone(),
- value: value.clone(),
- }))),
- ))
- }
- #[cfg(feature = "exp-destruct")]
- BindSpec::Field { into: _, .. } => {
- use crate::throw_runtime;
- throw_runtime!("destructuring is not yet supported here")
- }
- BindSpec::Function {
- name,
- params,
- value,
- } => {
- #[derive(Trace)]
- struct BindableMethodThunk {
- this: Option<ObjValue>,
- super_obj: Option<ObjValue>,
-
- cctx: ContextCreator,
- name: IStr,
- params: ParamsDesc,
- value: LocExpr,
- }
- impl ThunkValue for BindableMethodThunk {
- type Output = Val;
- fn get(self: Box<Self>, s: State) -> Result<Val> {
- Ok(evaluate_method(
- self.cctx.create(s, self.this, self.super_obj)?,
- self.name,
- self.params,
- self.value,
- ))
- }
- }
-
- #[derive(Trace)]
- struct BindableMethod {
- cctx: ContextCreator,
- name: IStr,
- params: ParamsDesc,
- value: LocExpr,
- }
- impl Bindable for BindableMethod {
- fn bind(
- &self,
- _: State,
- this: Option<ObjValue>,
- super_obj: Option<ObjValue>,
- ) -> Result<Thunk<Val>> {
- Ok(Thunk::<Val>::new(tb!(BindableMethodThunk {
- this,
- super_obj,
-
- cctx: self.cctx.clone(),
- name: self.name.clone(),
- params: self.params.clone(),
- value: self.value.clone(),
- })))
- }
- }
-
- let params = params.clone();
-
- Ok((
- name.clone(),
- LazyBinding::Bindable(Cc::new(tb!(BindableMethod {
- cctx,
- name: name.clone(),
- params,
- value,
- }))),
- ))
- }
- }
-}
-
pub fn evaluate_method(ctx: Context, name: IStr, params: ParamsDesc, body: LocExpr) -> Val {
Val::Func(FuncVal::Normal(Cc::new(FuncDesc {
name,
@@ -218,28 +86,65 @@
Ok(())
}
+trait CloneableBindable<T>: Bindable<Bound = T> + Clone {}
+
+fn evaluate_object_locals(
+ fctx: Pending<Context>,
+ locals: Rc<Vec<BindSpec>>,
+) -> impl CloneableBindable<Context> {
+ #[derive(Trace, Clone)]
+ struct WithObjectLocals {
+ fctx: Pending<Context>,
+ locals: Rc<Vec<BindSpec>>,
+ }
+ impl CloneableBindable<Context> for WithObjectLocals {}
+ impl Bindable for WithObjectLocals {
+ type Bound = Context;
+
+ fn bind(
+ &self,
+ _s: State,
+ sup: Option<ObjValue>,
+ this: Option<ObjValue>,
+ ) -> Result<Context> {
+ let fctx = Context::new_future();
+ let mut new_bindings = GcHashMap::new();
+ for b in self.locals.iter() {
+ evaluate_dest(b, fctx.clone(), &mut new_bindings)?;
+ }
+
+ let ctx = self.fctx.unwrap();
+ let new_dollar = ctx.dollar().clone().or_else(|| this.clone());
+
+ let ctx = ctx
+ .extend(new_bindings, new_dollar, sup, this)
+ .into_future(fctx);
+
+ Ok(ctx)
+ }
+ }
+
+ WithObjectLocals { fctx, locals }
+}
+
#[allow(clippy::too_many_lines)]
pub fn evaluate_member_list_object(s: State, ctx: Context, members: &[Member]) -> Result<ObjValue> {
- let new_bindings = Pending::new();
- let future_this = Pending::new();
- let cctx = ContextCreator(ctx.clone(), new_bindings.clone());
- {
- let mut bindings: GcHashMap<IStr, LazyBinding> = GcHashMap::with_capacity(members.len());
- for r in members
+ let mut builder = ObjValueBuilder::new();
+ let locals = Rc::new(
+ members
.iter()
.filter_map(|m| match m {
- Member::BindStmt(b) => Some(b.clone()),
+ Member::BindStmt(bind) => Some(bind.clone()),
_ => None,
})
- .map(|b| evaluate_binding(b.clone(), cctx.clone()))
- {
- let (n, b) = r?;
- bindings.insert(n, b);
- }
- new_bindings.fill(bindings);
- }
+ .collect::<Vec<_>>(),
+ );
+
+ let fctx = Context::new_future();
+
+ // We have single context for all fields, so we can cache binds
+ let uctx = CachedBindable::new(evaluate_object_locals(fctx.clone(), locals));
- let mut builder = ObjValueBuilder::new();
for member in members.iter() {
match member {
Member::Field(FieldMember {
@@ -250,21 +155,22 @@
value,
}) => {
#[derive(Trace)]
- struct ObjMemberBinding {
- cctx: ContextCreator,
+ struct ObjMemberBinding<B> {
+ uctx: B,
value: LocExpr,
name: IStr,
}
- impl Bindable for ObjMemberBinding {
+ impl<B: Bindable<Bound = Context>> Bindable for ObjMemberBinding<B> {
+ type Bound = Thunk<Val>;
fn bind(
&self,
s: State,
+ sup: Option<ObjValue>,
this: Option<ObjValue>,
- super_obj: Option<ObjValue>,
) -> Result<Thunk<Val>> {
Ok(Thunk::evaluated(evaluate_named(
s.clone(),
- self.cctx.create(s, this, super_obj)?,
+ self.uctx.bind(s, sup, this)?,
&self.value,
self.name.clone(),
)?))
@@ -286,9 +192,9 @@
.bindable(
s.clone(),
tb!(ObjMemberBinding {
- cctx: cctx.clone(),
+ uctx: uctx.clone(),
value: value.clone(),
- name,
+ name: name.clone()
}),
)?;
}
@@ -299,21 +205,22 @@
..
}) => {
#[derive(Trace)]
- struct ObjMemberBinding {
- cctx: ContextCreator,
+ struct ObjMemberBinding<B> {
+ uctx: B,
value: LocExpr,
params: ParamsDesc,
name: IStr,
}
- impl Bindable for ObjMemberBinding {
+ impl<B: Bindable<Bound = Context>> Bindable for ObjMemberBinding<B> {
+ type Bound = Thunk<Val>;
fn bind(
&self,
s: State,
+ sup: Option<ObjValue>,
this: Option<ObjValue>,
- super_obj: Option<ObjValue>,
) -> Result<Thunk<Val>> {
Ok(Thunk::evaluated(evaluate_method(
- self.cctx.create(s, this, super_obj)?,
+ self.uctx.bind(s, sup, this)?,
self.name.clone(),
self.params.clone(),
self.value.clone(),
@@ -334,40 +241,42 @@
.bindable(
s.clone(),
tb!(ObjMemberBinding {
- cctx: cctx.clone(),
+ uctx: uctx.clone(),
value: value.clone(),
params: params.clone(),
- name,
+ name: name.clone()
}),
)?;
}
Member::BindStmt(_) => {}
Member::AssertStmt(stmt) => {
#[derive(Trace)]
- struct ObjectAssert {
- cctx: ContextCreator,
+ struct ObjectAssert<B> {
+ uctx: B,
assert: AssertStmt,
}
- impl ObjectAssertion for ObjectAssert {
+ impl<B: Bindable<Bound = Context>> ObjectAssertion for ObjectAssert<B> {
fn run(
&self,
s: State,
+ sup: Option<ObjValue>,
this: Option<ObjValue>,
- super_obj: Option<ObjValue>,
) -> Result<()> {
- let ctx = self.cctx.create(s.clone(), this, super_obj)?;
+ let ctx = self.uctx.bind(s.clone(), sup, this)?;
evaluate_assert(s, ctx, &self.assert)
}
}
builder.assert(tb!(ObjectAssert {
- cctx: cctx.clone(),
+ uctx: uctx.clone(),
assert: stmt.clone(),
}));
}
}
}
let this = builder.build();
- future_this.fill(this.clone());
+ let _ctx = ctx
+ .extend(GcHashMap::new(), None, None, Some(this.clone()))
+ .into_future(fctx);
Ok(this)
}
@@ -375,44 +284,45 @@
Ok(match object {
ObjBody::MemberList(members) => evaluate_member_list_object(s, ctx, members)?,
ObjBody::ObjComp(obj) => {
- let future_this = Pending::new();
let mut builder = ObjValueBuilder::new();
- evaluate_comp(s.clone(), ctx, &obj.compspecs, &mut |ctx| {
- let new_bindings = Pending::new();
- let cctx = ContextCreator(ctx.clone(), new_bindings.clone());
- let mut bindings: GcHashMap<IStr, LazyBinding> =
- GcHashMap::with_capacity(obj.pre_locals.len() + obj.post_locals.len());
- for r in obj
- .pre_locals
+ let locals = Rc::new(
+ obj.pre_locals
.iter()
.chain(obj.post_locals.iter())
- .map(|b| evaluate_binding(b.clone(), cctx.clone()))
- {
- let (n, b) = r?;
- bindings.insert(n, b);
- }
- new_bindings.fill(bindings.clone());
- let ctx = ctx.extend_unbound(s.clone(), bindings, None, None, None)?;
+ .cloned()
+ .collect::<Vec<_>>(),
+ );
+ let mut ctxs = vec![];
+ evaluate_comp(s.clone(), ctx, &obj.compspecs, &mut |ctx| {
let key = evaluate(s.clone(), ctx.clone(), &obj.key)?;
+ let fctx = Context::new_future();
+ ctxs.push((ctx, fctx.clone()));
+ let uctx = evaluate_object_locals(fctx, locals.clone());
match key {
Val::Null => {}
Val::Str(n) => {
#[derive(Trace)]
- struct ObjCompBinding {
- ctx: Context,
+ struct ObjCompBinding<B> {
+ uctx: B,
value: LocExpr,
}
- impl Bindable for ObjCompBinding {
+ impl<B: Bindable<Bound = Context>> Bindable for ObjCompBinding<B> {
+ type Bound = Thunk<Val>;
fn bind(
&self,
s: State,
+ sup: Option<ObjValue>,
this: Option<ObjValue>,
- _super_obj: Option<ObjValue>,
) -> Result<Thunk<Val>> {
Ok(Thunk::evaluated(evaluate(
- s,
- self.ctx.clone().extend(GcHashMap::new(), None, this, None),
+ s.clone(),
+ self.uctx.bind(s, sup, this.clone())?.extend(
+ GcHashMap::new(),
+ None,
+ None,
+ this,
+ ),
&self.value,
)?))
}
@@ -424,7 +334,7 @@
.bindable(
s.clone(),
tb!(ObjCompBinding {
- ctx,
+ uctx,
value: obj.value.clone(),
}),
)?;
@@ -436,7 +346,11 @@
})?;
let this = builder.build();
- future_this.fill(this.clone());
+ for (ctx, fctx) in ctxs {
+ let _ctx = ctx
+ .extend(GcHashMap::new(), None, None, Some(this.clone()))
+ .into_future(fctx);
+ }
this
}
})
@@ -596,7 +510,7 @@
for b in bindings {
evaluate_dest(b, fctx.clone(), &mut new_bindings)?;
}
- let ctx = ctx.extend_bound(new_bindings).into_future(fctx);
+ let ctx = ctx.extend(new_bindings, None, None, None).into_future(fctx);
evaluate(s, ctx, &returned.clone())?
}
Arr(items) => {
crates/jrsonnet-evaluator/src/function/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/function/mod.rs
+++ b/crates/jrsonnet-evaluator/src/function/mod.rs
@@ -139,11 +139,12 @@
) -> Result<Val> {
match self {
Self::Id => {
+ #[allow(clippy::unnecessary_wraps)]
#[builtin]
- fn builtin_id(v: Any) -> Result<Any> {
+ const fn builtin_id(v: Any) -> Result<Any> {
Ok(v)
}
- static ID: &'static builtin_id = &builtin_id {};
+ static ID: &builtin_id = &builtin_id {};
ID.call(s, call_ctx, loc, args)
}
@@ -159,10 +160,10 @@
self.evaluate(s, Context::default(), CallLocation::native(), args, true)
}
- pub fn is_identity(&self) -> bool {
+ pub const fn is_identity(&self) -> bool {
matches!(self, Self::Id)
}
- pub fn identity() -> Self {
+ pub const fn identity() -> Self {
Self::Id
}
}
crates/jrsonnet-evaluator/src/function/parse.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/function/parse.rs
+++ b/crates/jrsonnet-evaluator/src/function/parse.rs
@@ -111,7 +111,7 @@
Ok(body_ctx
.extend(passed_args, None, None, None)
- .extend_bound(defaults)
+ .extend(defaults, None, None, None)
.into_future(fctx))
} else {
let body_ctx = body_ctx.extend(passed_args, None, None, None);
crates/jrsonnet-evaluator/src/gc.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/gc.rs
+++ b/crates/jrsonnet-evaluator/src/gc.rs
@@ -10,7 +10,7 @@
use rustc_hash::{FxHashMap, FxHashSet};
/// Replacement for box, which assumes that the underlying type is [`Trace`]
-/// Used in places, where Cc<dyn Trait> should be used instead, but it can't, because CoerceUnsiced is not stable
+/// Used in places, where `Cc<dyn Trait>` should be used instead, but it can't, because `CoerceUnsiced` is not stable
#[derive(Debug, Clone)]
pub struct TraceBox<T: ?Sized>(pub Box<T>);
#[macro_export]
crates/jrsonnet-evaluator/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/lib.rs
+++ b/crates/jrsonnet-evaluator/src/lib.rs
@@ -61,17 +61,13 @@
pub use val::{ManifestFormat, Thunk, Val};
pub trait Bindable: Trace + 'static {
- fn bind(
- &self,
- s: State,
- this: Option<ObjValue>,
- super_obj: Option<ObjValue>,
- ) -> Result<Thunk<Val>>;
+ type Bound;
+ fn bind(&self, s: State, sup: Option<ObjValue>, this: Option<ObjValue>) -> Result<Self::Bound>;
}
#[derive(Clone, Trace)]
pub enum LazyBinding {
- Bindable(Cc<TraceBox<dyn Bindable>>),
+ Bindable(Cc<TraceBox<dyn Bindable<Bound = Thunk<Val>>>>),
Bound(Thunk<Val>),
}
@@ -84,11 +80,11 @@
pub fn evaluate(
&self,
s: State,
+ sup: Option<ObjValue>,
this: Option<ObjValue>,
- super_obj: Option<ObjValue>,
) -> Result<Thunk<Val>> {
match self {
- Self::Bindable(v) => v.bind(s, this, super_obj),
+ Self::Bindable(v) => v.bind(s, sup, this),
Self::Bound(v) => Ok(v.clone()),
}
}
@@ -345,7 +341,7 @@
for (name, value) in globals.iter() {
new_bindings.insert(name.clone(), Thunk::evaluated(value.clone()));
}
- Context::new().extend_bound(new_bindings)
+ Context::new().extend(new_bindings, None, None, None)
}
/// Executes code creating a new stack frame
crates/jrsonnet-evaluator/src/obj.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/obj.rs
+++ b/crates/jrsonnet-evaluator/src/obj.rs
@@ -106,7 +106,7 @@
}
pub trait ObjectAssertion: Trace {
- fn run(&self, s: State, this: Option<ObjValue>, super_obj: Option<ObjValue>) -> Result<()>;
+ fn run(&self, s: State, super_obj: Option<ObjValue>, this: Option<ObjValue>) -> Result<()>;
}
// Field => This
@@ -124,10 +124,11 @@
#[derive(Trace)]
#[force_tracking]
pub struct ObjValueInternals {
- super_obj: Option<ObjValue>,
+ sup: Option<ObjValue>,
+ this: Option<ObjValue>,
+
assertions: Cc<Vec<TraceBox<dyn ObjectAssertion>>>,
assertions_ran: RefCell<GcHashSet<ObjValue>>,
- this_obj: Option<ObjValue>,
this_entries: Cc<GcHashMap<IStr, ObjMember>>,
value_cache: RefCell<GcHashMap<CacheKey, CacheValue>>,
}
@@ -153,7 +154,7 @@
pub struct ObjValue(pub(crate) Cc<ObjValueInternals>);
impl Debug for ObjValue {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- if let Some(super_obj) = self.0.super_obj.as_ref() {
+ if let Some(super_obj) = self.0.sup.as_ref() {
if f.alternate() {
write!(f, "{:#?}", super_obj)?;
} else {
@@ -171,15 +172,15 @@
impl ObjValue {
pub fn new(
- super_obj: Option<Self>,
+ sup: Option<Self>,
this_entries: Cc<GcHashMap<IStr, ObjMember>>,
assertions: Cc<Vec<TraceBox<dyn ObjectAssertion>>>,
) -> Self {
Self(Cc::new(ObjValueInternals {
- super_obj,
+ sup,
+ this: None,
assertions,
assertions_ran: RefCell::new(GcHashSet::new()),
- this_obj: None,
this_entries,
value_cache: RefCell::new(GcHashMap::new()),
}))
@@ -188,15 +189,15 @@
Self::new(None, Cc::new(GcHashMap::new()), Cc::new(Vec::new()))
}
#[must_use]
- pub fn extend_from(&self, super_obj: Self) -> Self {
- match &self.0.super_obj {
+ pub fn extend_from(&self, sup: Self) -> Self {
+ match &self.0.sup {
None => Self::new(
- Some(super_obj),
+ Some(sup),
self.0.this_entries.clone(),
self.0.assertions.clone(),
),
Some(v) => Self::new(
- Some(v.extend_from(super_obj)),
+ Some(v.extend_from(sup)),
self.0.this_entries.clone(),
self.0.assertions.clone(),
),
@@ -212,12 +213,12 @@
}
#[must_use]
- pub fn with_this(&self, this_obj: Self) -> Self {
+ pub fn with_this(&self, this: Self) -> Self {
Self(Cc::new(ObjValueInternals {
- super_obj: self.0.super_obj.clone(),
+ sup: self.0.sup.clone(),
assertions: self.0.assertions.clone(),
assertions_ran: RefCell::new(GcHashSet::new()),
- this_obj: Some(this_obj),
+ this: Some(this),
this_entries: self.0.this_entries.clone(),
value_cache: RefCell::new(GcHashMap::new()),
}))
@@ -234,7 +235,7 @@
if !self.0.this_entries.is_empty() {
return false;
}
- self.0.super_obj.as_ref().map_or(true, Self::is_empty)
+ self.0.sup.as_ref().map_or(true, Self::is_empty)
}
/// Run callback for every field found in object
@@ -243,7 +244,7 @@
depth: SuperDepth,
handler: &mut impl FnMut(SuperDepth, &IStr, &ObjMember) -> bool,
) -> bool {
- if let Some(s) = &self.0.super_obj {
+ if let Some(s) = &self.0.sup {
if s.enum_fields(depth.deeper(), handler) {
return true;
}
@@ -332,13 +333,13 @@
Some(match &m.visibility {
Visibility::Normal => self
.0
- .super_obj
+ .sup
.as_ref()
.and_then(|super_obj| super_obj.field_visibility(name))
.unwrap_or(Visibility::Normal),
v => *v,
})
- } else if let Some(super_obj) = &self.0.super_obj {
+ } else if let Some(super_obj) = &self.0.sup {
super_obj.field_visibility(name)
} else {
None
@@ -348,7 +349,7 @@
fn has_field_include_hidden(&self, name: IStr) -> bool {
if self.0.this_entries.contains_key(&name) {
true
- } else if let Some(super_obj) = &self.0.super_obj {
+ } else if let Some(super_obj) = &self.0.sup {
super_obj.has_field_include_hidden(name)
} else {
false
@@ -369,13 +370,12 @@
pub fn get(&self, s: State, key: IStr) -> Result<Option<Val>> {
self.run_assertions(s.clone())?;
- self.get_raw(s, key, self.0.this_obj.as_ref())
+ self.get_raw(s, key, self.0.this.clone().unwrap_or_else(|| self.clone()))
}
// pub fn extend_with(self, key: )
- fn get_raw(&self, s: State, key: IStr, real_this: Option<&Self>) -> Result<Option<Val>> {
- let real_this = real_this.unwrap_or(self);
+ fn get_raw(&self, s: State, key: IStr, real_this: Self) -> Result<Option<Val>> {
let cache_key = (key.clone(), WeakObjValue(real_this.0.downgrade()));
if let Some(v) = self.0.value_cache.borrow().get(&cache_key) {
@@ -397,17 +397,17 @@
.insert(cache_key.clone(), CacheValue::Errored(e.clone()));
e
};
- let value = match (self.0.this_entries.get(&key), &self.0.super_obj) {
+ let value = match (self.0.this_entries.get(&key), &self.0.sup) {
(Some(k), None) => Ok(Some(
self.evaluate_this(s, k, real_this).map_err(fill_error)?,
)),
(Some(k), Some(super_obj)) => {
let our = self
- .evaluate_this(s.clone(), k, real_this)
+ .evaluate_this(s.clone(), k, real_this.clone())
.map_err(fill_error)?;
if k.add {
super_obj
- .get_raw(s.clone(), key, Some(real_this))
+ .get_raw(s.clone(), key, real_this)
.map_err(fill_error)?
.map_or(Ok(Some(our.clone())), |v| {
Ok(Some(evaluate_add_op(s.clone(), &v, &our)?))
@@ -416,7 +416,7 @@
Ok(Some(our))
}
}
- (None, Some(super_obj)) => super_obj.get_raw(s, key, Some(real_this)),
+ (None, Some(super_obj)) => super_obj.get_raw(s, key, real_this),
(None, None) => Ok(None),
}
.map_err(fill_error)?;
@@ -429,9 +429,9 @@
);
Ok(value)
}
- fn evaluate_this(&self, s: State, v: &ObjMember, real_this: &Self) -> Result<Val> {
+ fn evaluate_this(&self, s: State, v: &ObjMember, real_this: Self) -> Result<Val> {
v.invoke
- .evaluate(s.clone(), Some(real_this.clone()), self.0.super_obj.clone())?
+ .evaluate(s.clone(), self.0.sup.clone(), Some(real_this))?
.evaluate(s)
}
@@ -439,13 +439,13 @@
if self.0.assertions_ran.borrow_mut().insert(real_this.clone()) {
for assertion in self.0.assertions.iter() {
if let Err(e) =
- assertion.run(s.clone(), Some(real_this.clone()), self.0.super_obj.clone())
+ assertion.run(s.clone(), self.0.sup.clone(), Some(real_this.clone()))
{
self.0.assertions_ran.borrow_mut().remove(real_this);
return Err(e);
}
}
- if let Some(super_obj) = &self.0.super_obj {
+ if let Some(super_obj) = &self.0.sup {
super_obj.run_assertions_raw(s, real_this)?;
}
}
@@ -458,6 +458,9 @@
pub fn ptr_eq(a: &Self, b: &Self) -> bool {
cc_ptr_eq(&a.0, &b.0)
}
+ pub fn downgrade(self) -> WeakObjValue {
+ WeakObjValue(self.0.downgrade())
+ }
}
impl PartialEq for ObjValue {
@@ -475,7 +478,7 @@
#[allow(clippy::module_name_repetitions)]
pub struct ObjValueBuilder {
- super_obj: Option<ObjValue>,
+ sup: Option<ObjValue>,
map: GcHashMap<IStr, ObjMember>,
assertions: Vec<TraceBox<dyn ObjectAssertion>>,
next_field_index: FieldIndex,
@@ -486,7 +489,7 @@
}
pub fn with_capacity(capacity: usize) -> Self {
Self {
- super_obj: None,
+ sup: None,
map: GcHashMap::with_capacity(capacity),
assertions: Vec::new(),
next_field_index: FieldIndex::default(),
@@ -497,7 +500,7 @@
self
}
pub fn with_super(&mut self, super_obj: ObjValue) -> &mut Self {
- self.super_obj = Some(super_obj);
+ self.sup = Some(super_obj);
self
}
@@ -512,7 +515,7 @@
}
pub fn build(self) -> ObjValue {
- ObjValue::new(self.super_obj, Cc::new(self.map), Cc::new(self.assertions))
+ ObjValue::new(self.sup, Cc::new(self.map), Cc::new(self.assertions))
}
}
impl Default for ObjValueBuilder {
@@ -583,7 +586,11 @@
pub fn value(self, s: State, value: Val) -> Result<()> {
self.binding(s, LazyBinding::Bound(Thunk::evaluated(value)))
}
- pub fn bindable(self, s: State, bindable: TraceBox<dyn Bindable>) -> Result<()> {
+ pub fn bindable(
+ self,
+ s: State,
+ bindable: TraceBox<dyn Bindable<Bound = Thunk<Val>>>,
+ ) -> Result<()> {
self.binding(s, LazyBinding::Bindable(Cc::new(bindable)))
}
pub fn binding(self, s: State, binding: LazyBinding) -> Result<()> {
@@ -606,7 +613,7 @@
pub fn value(self, value: Val) {
self.binding(LazyBinding::Bound(Thunk::evaluated(value)));
}
- pub fn bindable(self, bindable: TraceBox<dyn Bindable>) {
+ pub fn bindable(self, bindable: TraceBox<dyn Bindable<Bound = Thunk<Val>>>) {
self.binding(LazyBinding::Bindable(Cc::new(bindable)));
}
pub fn binding(self, binding: LazyBinding) {
crates/jrsonnet-evaluator/src/stdlib/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/stdlib/mod.rs
+++ b/crates/jrsonnet-evaluator/src/stdlib/mod.rs
@@ -466,7 +466,7 @@
Ok(ArrValue::Eager(sort::sort(
s.clone(),
arr.evaluated(s)?,
- keyF.unwrap_or(FuncVal::identity()),
+ keyF.unwrap_or_else(FuncVal::identity),
)?))
}
crates/jrsonnet-evaluator/src/stdlib/sort.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/stdlib/sort.rs
+++ b/crates/jrsonnet-evaluator/src/stdlib/sort.rs
@@ -68,7 +68,23 @@
if values.len() <= 1 {
return Ok(values);
}
- if !key_getter.is_identity() {
+ if key_getter.is_identity() {
+ // Fast path, identity key getter
+ let mut values = (*values).clone();
+ let sort_type = get_sort_type(&mut values, |k| k)?;
+ match sort_type {
+ SortKeyType::Number => values.sort_unstable_by_key(|v| match v {
+ Val::Num(n) => NonNaNf64(*n),
+ _ => unreachable!(),
+ }),
+ SortKeyType::String => values.sort_unstable_by_key(|v| match v {
+ Val::Str(s) => s.clone(),
+ _ => unreachable!(),
+ }),
+ SortKeyType::Unknown => unreachable!(),
+ };
+ Ok(Cc::new(values))
+ } else {
// Slow path, user provided key getter
let mut vk = Vec::with_capacity(values.len());
for value in values.iter() {
@@ -90,21 +106,5 @@
SortKeyType::Unknown => unreachable!(),
};
Ok(Cc::new(vk.into_iter().map(|v| v.0).collect()))
- } else {
- // Fast path, identity key getter
- let mut values = (*values).clone();
- let sort_type = get_sort_type(&mut values, |k| k)?;
- match sort_type {
- SortKeyType::Number => values.sort_unstable_by_key(|v| match v {
- Val::Num(n) => NonNaNf64(*n),
- _ => unreachable!(),
- }),
- SortKeyType::String => values.sort_unstable_by_key(|v| match v {
- Val::Str(s) => s.clone(),
- _ => unreachable!(),
- }),
- SortKeyType::Unknown => unreachable!(),
- };
- Ok(Cc::new(values))
}
}
crates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth1use std::{cell::RefCell, fmt::Debug, rc::Rc};23use gcmodule::{Cc, Trace};4use jrsonnet_interner::IStr;5use jrsonnet_types::ValType;67use crate::{8 cc_ptr_eq,9 error::{Error::*, LocError},10 function::FuncVal,11 gc::TraceBox,12 stdlib::manifest::{13 manifest_json_ex, manifest_yaml_ex, ManifestJsonOptions, ManifestType, ManifestYamlOptions,14 },15 throw, ObjValue, Result, State,16};1718pub trait ThunkValue: Trace {19 type Output;20 fn get(self: Box<Self>, s: State) -> Result<Self::Output>;21}2223#[derive(Trace)]24enum ThunkInner<T> {25 Computed(T),26 Errored(LocError),27 Waiting(TraceBox<dyn ThunkValue<Output = T>>),28 Pending,29}3031#[allow(clippy::module_name_repetitions)]32#[derive(Clone, Trace)]33pub struct Thunk<T>(Cc<RefCell<ThunkInner<T>>>);34impl<T> Thunk<T>35where36 T: Clone + Trace,37{38 pub fn new(f: TraceBox<dyn ThunkValue<Output = T>>) -> Self {39 Self(Cc::new(RefCell::new(ThunkInner::Waiting(f))))40 }41 pub fn evaluated(val: T) -> Self {42 Self(Cc::new(RefCell::new(ThunkInner::Computed(val))))43 }44 pub fn force(&self, s: State) -> Result<()> {45 self.evaluate(s)?;46 Ok(())47 }48 pub fn evaluate(&self, s: State) -> Result<T> {49 match &*self.0.borrow() {50 ThunkInner::Computed(v) => return Ok(v.clone()),51 ThunkInner::Errored(e) => return Err(e.clone()),52 ThunkInner::Pending => return Err(InfiniteRecursionDetected.into()),53 ThunkInner::Waiting(..) => (),54 };55 let value = if let ThunkInner::Waiting(value) =56 std::mem::replace(&mut *self.0.borrow_mut(), ThunkInner::Pending)57 {58 value59 } else {60 unreachable!()61 };62 let new_value = match value.0.get(s) {63 Ok(v) => v,64 Err(e) => {65 *self.0.borrow_mut() = ThunkInner::Errored(e.clone());66 return Err(e);67 }68 };69 *self.0.borrow_mut() = ThunkInner::Computed(new_value.clone());70 Ok(new_value)71 }72}7374impl<T: Debug> Debug for Thunk<T> {75 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {76 write!(f, "Lazy")77 }78}79impl<T> PartialEq for Thunk<T> {80 fn eq(&self, other: &Self) -> bool {81 cc_ptr_eq(&self.0, &other.0)82 }83}8485#[derive(Clone)]86pub enum ManifestFormat {87 YamlStream(Box<ManifestFormat>),88 Yaml {89 padding: usize,90 #[cfg(feature = "exp-preserve-order")]91 preserve_order: bool,92 },93 Json {94 padding: usize,95 #[cfg(feature = "exp-preserve-order")]96 preserve_order: bool,97 },98 ToString,99 String,100}101impl ManifestFormat {102 #[cfg(feature = "exp-preserve-order")]103 fn preserve_order(&self) -> bool {104 match self {105 ManifestFormat::YamlStream(s) => s.preserve_order(),106 ManifestFormat::Yaml { preserve_order, .. } => *preserve_order,107 ManifestFormat::Json { preserve_order, .. } => *preserve_order,108 ManifestFormat::ToString => false,109 ManifestFormat::String => false,110 }111 }112}113114#[derive(Debug, Clone, Trace)]115pub struct Slice {116 pub(crate) inner: ArrValue,117 pub(crate) from: u32,118 pub(crate) to: u32,119 pub(crate) step: u32,120}121impl Slice {122 const fn from(&self) -> usize {123 self.from as usize124 }125 const fn to(&self) -> usize {126 self.to as usize127 }128 const fn step(&self) -> usize {129 self.step as usize130 }131 const fn len(&self) -> usize {132 // TODO: use div_ceil133 let diff = self.to() - self.from();134 let rem = diff % self.step();135 let div = diff / self.step();136137 if rem == 0 {138 div139 } else {140 div + 1141 }142 }143}144145#[derive(Debug, Clone, Trace)]146#[force_tracking]147pub enum ArrValue {148 Bytes(#[skip_trace] Rc<[u8]>),149 Lazy(Cc<Vec<Thunk<Val>>>),150 Eager(Cc<Vec<Val>>),151 Extended(Box<(Self, Self)>),152 Range(i32, i32),153 Slice(Box<Slice>),154 Reversed(Box<Self>),155}156impl ArrValue {157 pub fn new_eager() -> Self {158 Self::Eager(Cc::new(Vec::new()))159 }160161 /// # Panics162 /// If a > b163 pub fn new_range(a: i32, b: i32) -> Self {164 assert!(a <= b);165 Self::Range(a, b)166 }167168 /// # Panics169 /// If passed numbers are incorrect170 #[must_use]171 pub fn slice(self, from: Option<usize>, to: Option<usize>, step: Option<usize>) -> Self {172 let len = self.len();173 let from = from.unwrap_or(0);174 let to = to.unwrap_or(len).min(len);175 let step = step.unwrap_or(1);176 assert!(from < to);177 assert!(step > 0);178179 Self::Slice(Box::new(Slice {180 inner: self,181 from: from as u32,182 to: to as u32,183 step: step as u32,184 }))185 }186187 pub fn len(&self) -> usize {188 match self {189 Self::Bytes(i) => i.len(),190 Self::Lazy(l) => l.len(),191 Self::Eager(e) => e.len(),192 Self::Extended(v) => v.0.len() + v.1.len(),193 Self::Range(a, b) => a.abs_diff(*b) as usize + 1,194 Self::Reversed(i) => i.len(),195 Self::Slice(s) => s.len(),196 }197 }198199 pub fn is_empty(&self) -> bool {200 self.len() == 0201 }202203 pub fn get(&self, s: State, index: usize) -> Result<Option<Val>> {204 match self {205 Self::Bytes(i) => i206 .get(index)207 .map_or(Ok(None), |v| Ok(Some(Val::Num(f64::from(*v))))),208 Self::Lazy(vec) => {209 if let Some(v) = vec.get(index) {210 Ok(Some(v.evaluate(s)?))211 } else {212 Ok(None)213 }214 }215 Self::Eager(vec) => Ok(vec.get(index).cloned()),216 Self::Extended(v) => {217 let a_len = v.0.len();218 if a_len > index {219 v.0.get(s, index)220 } else {221 v.1.get(s, index - a_len)222 }223 }224 Self::Range(a, _) => {225 if index >= self.len() {226 return Ok(None);227 }228 Ok(Some(Val::Num(((*a as isize) + index as isize) as f64)))229 }230 Self::Reversed(v) => {231 let len = v.len();232 if index >= len {233 return Ok(None);234 }235 v.get(s, len - index - 1)236 }237 Self::Slice(v) => {238 let index = v.from() + index * v.step();239 if index >= v.to() {240 return Ok(None);241 }242 v.inner.get(s, index as usize)243 }244 }245 }246247 pub fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {248 match self {249 Self::Bytes(i) => i250 .get(index)251 .map(|b| Thunk::evaluated(Val::Num(f64::from(*b)))),252 Self::Lazy(vec) => vec.get(index).cloned(),253 Self::Eager(vec) => vec.get(index).cloned().map(Thunk::evaluated),254 Self::Extended(v) => {255 let a_len = v.0.len();256 if a_len > index {257 v.0.get_lazy(index)258 } else {259 v.1.get_lazy(index - a_len)260 }261 }262 Self::Range(a, _) => {263 if index >= self.len() {264 return None;265 }266 Some(Thunk::evaluated(Val::Num(267 ((*a as isize) + index as isize) as f64,268 )))269 }270 Self::Reversed(v) => {271 let len = v.len();272 if index >= len {273 return None;274 }275 v.get_lazy(len - index - 1)276 }277 Self::Slice(s) => {278 let index = s.from() + index * s.step();279 if index >= s.to() {280 return None;281 }282 s.inner.get_lazy(index as usize)283 }284 }285 }286287 pub fn evaluated(&self, s: State) -> Result<Cc<Vec<Val>>> {288 Ok(match self {289 Self::Bytes(i) => {290 let mut out = Vec::with_capacity(i.len());291 for v in i.iter() {292 out.push(Val::Num(f64::from(*v)));293 }294 Cc::new(out)295 }296 Self::Lazy(vec) => {297 let mut out = Vec::with_capacity(vec.len());298 for item in vec.iter() {299 out.push(item.evaluate(s.clone())?);300 }301 Cc::new(out)302 }303 Self::Eager(vec) => vec.clone(),304 Self::Extended(_v) => {305 let mut out = Vec::with_capacity(self.len());306 for item in self.iter(s) {307 out.push(item?);308 }309 Cc::new(out)310 }311 Self::Range(a, b) => {312 let mut out = Vec::with_capacity(self.len());313 for i in *a..*b {314 out.push(Val::Num(f64::from(i)));315 }316 Cc::new(out)317 }318 Self::Reversed(r) => {319 let mut r = r.evaluated(s)?;320 Cc::update_with(&mut r, |v| v.reverse());321 r322 }323 Self::Slice(v) => {324 let mut out = Vec::with_capacity(v.inner.len());325 for v in v326 .inner327 .iter_lazy()328 .skip(v.from())329 .take(v.to() - v.from())330 .step_by(v.step())331 {332 out.push(v.evaluate(s.clone())?);333 }334 Cc::new(out)335 }336 })337 }338339 pub fn iter(&self, s: State) -> impl DoubleEndedIterator<Item = Result<Val>> + '_ {340 (0..self.len()).map(move |idx| match self {341 Self::Bytes(b) => Ok(Val::Num(f64::from(b[idx]))),342 Self::Lazy(l) => l[idx].evaluate(s.clone()),343 Self::Eager(e) => Ok(e[idx].clone()),344 Self::Extended(..) | Self::Range(..) | Self::Reversed(..) | Self::Slice(..) => {345 self.get(s.clone(), idx).map(|e| e.expect("idx < len"))346 }347 })348 }349350 pub fn iter_lazy(&self) -> impl DoubleEndedIterator<Item = Thunk<Val>> + '_ {351 (0..self.len()).map(move |idx| match self {352 Self::Bytes(b) => Thunk::evaluated(Val::Num(f64::from(b[idx]))),353 Self::Lazy(l) => l[idx].clone(),354 Self::Eager(e) => Thunk::evaluated(e[idx].clone()),355 Self::Slice(..) | Self::Extended(..) | Self::Range(..) | Self::Reversed(..) => {356 self.get_lazy(idx).expect("idx < len")357 }358 })359 }360361 #[must_use]362 pub fn reversed(self) -> Self {363 Self::Reversed(Box::new(self))364 }365366 pub fn map(self, s: State, mapper: impl Fn(Val) -> Result<Val>) -> Result<Self> {367 let mut out = Vec::with_capacity(self.len());368369 for value in self.iter(s) {370 out.push(mapper(value?)?);371 }372373 Ok(Self::Eager(Cc::new(out)))374 }375376 pub fn filter(self, s: State, filter: impl Fn(&Val) -> Result<bool>) -> Result<Self> {377 let mut out = Vec::with_capacity(self.len());378379 for value in self.iter(s) {380 let value = value?;381 if filter(&value)? {382 out.push(value);383 }384 }385386 Ok(Self::Eager(Cc::new(out)))387 }388389 pub fn ptr_eq(a: &Self, b: &Self) -> bool {390 match (a, b) {391 (Self::Lazy(a), Self::Lazy(b)) => cc_ptr_eq(a, b),392 (Self::Eager(a), Self::Eager(b)) => cc_ptr_eq(a, b),393 _ => false,394 }395 }396}397398impl From<Vec<Thunk<Val>>> for ArrValue {399 fn from(v: Vec<Thunk<Val>>) -> Self {400 Self::Lazy(Cc::new(v))401 }402}403404impl From<Vec<Val>> for ArrValue {405 fn from(v: Vec<Val>) -> Self {406 Self::Eager(Cc::new(v))407 }408}409410#[allow(clippy::module_name_repetitions)]411pub enum IndexableVal {412 Str(IStr),413 Arr(ArrValue),414}415416#[derive(Debug, Clone, Trace)]417pub enum Val {418 Bool(bool),419 Null,420 Str(IStr),421 Num(f64),422 Arr(ArrValue),423 Obj(ObjValue),424 Func(FuncVal),425}426427impl Val {428 pub const fn as_bool(&self) -> Option<bool> {429 match self {430 Val::Bool(v) => Some(*v),431 _ => None,432 }433 }434 pub const fn as_null(&self) -> Option<()> {435 match self {436 Val::Null => Some(()),437 _ => None,438 }439 }440 pub fn as_str(&self) -> Option<IStr> {441 match self {442 Val::Str(s) => Some(s.clone()),443 _ => None,444 }445 }446 pub const fn as_num(&self) -> Option<f64> {447 match self {448 Val::Num(n) => Some(*n),449 _ => None,450 }451 }452 pub fn as_arr(&self) -> Option<ArrValue> {453 match self {454 Val::Arr(a) => Some(a.clone()),455 _ => None,456 }457 }458 pub fn as_obj(&self) -> Option<ObjValue> {459 match self {460 Val::Obj(o) => Some(o.clone()),461 _ => None,462 }463 }464 pub fn as_func(&self) -> Option<FuncVal> {465 match self {466 Val::Func(f) => Some(f.clone()),467 _ => None,468 }469 }470471 /// Creates `Val::Num` after checking for numeric overflow.472 /// As numbers are `f64`, we can just check for their finity.473 pub fn new_checked_num(num: f64) -> Result<Self> {474 if num.is_finite() {475 Ok(Self::Num(num))476 } else {477 throw!(RuntimeError("overflow".into()))478 }479 }480481 pub const fn value_type(&self) -> ValType {482 match self {483 Self::Str(..) => ValType::Str,484 Self::Num(..) => ValType::Num,485 Self::Arr(..) => ValType::Arr,486 Self::Obj(..) => ValType::Obj,487 Self::Bool(_) => ValType::Bool,488 Self::Null => ValType::Null,489 Self::Func(..) => ValType::Func,490 }491 }492493 pub fn to_string(&self, s: State) -> Result<IStr> {494 Ok(match self {495 Self::Bool(true) => "true".into(),496 Self::Bool(false) => "false".into(),497 Self::Null => "null".into(),498 Self::Str(s) => s.clone(),499 v => manifest_json_ex(500 s,501 v,502 &ManifestJsonOptions {503 padding: "",504 mtype: ManifestType::ToString,505 newline: "\n",506 key_val_sep: ": ",507 #[cfg(feature = "exp-preserve-order")]508 preserve_order: false,509 },510 )?511 .into(),512 })513 }514515 /// Expects value to be object, outputs (key, manifested value) pairs516 pub fn manifest_multi(&self, s: State, ty: &ManifestFormat) -> Result<Vec<(IStr, IStr)>> {517 let obj = match self {518 Self::Obj(obj) => obj,519 _ => throw!(MultiManifestOutputIsNotAObject),520 };521 let keys = obj.fields(522 #[cfg(feature = "exp-preserve-order")]523 ty.preserve_order(),524 );525 let mut out = Vec::with_capacity(keys.len());526 for key in keys {527 let value = obj528 .get(s.clone(), key.clone())?529 .expect("item in object")530 .manifest(s.clone(), ty)?;531 out.push((key, value));532 }533 Ok(out)534 }535536 /// Expects value to be array, outputs manifested values537 pub fn manifest_stream(&self, s: State, ty: &ManifestFormat) -> Result<Vec<IStr>> {538 let arr = match self {539 Self::Arr(a) => a,540 _ => throw!(StreamManifestOutputIsNotAArray),541 };542 let mut out = Vec::with_capacity(arr.len());543 for i in arr.iter(s.clone()) {544 out.push(i?.manifest(s.clone(), ty)?);545 }546 Ok(out)547 }548549 pub fn manifest(&self, s: State, ty: &ManifestFormat) -> Result<IStr> {550 Ok(match ty {551 ManifestFormat::YamlStream(format) => {552 let arr = match self {553 Self::Arr(a) => a,554 _ => throw!(StreamManifestOutputIsNotAArray),555 };556 let mut out = String::new();557558 match format as &ManifestFormat {559 ManifestFormat::YamlStream(_) => throw!(StreamManifestOutputCannotBeRecursed),560 ManifestFormat::String => throw!(StreamManifestCannotNestString),561 _ => {}562 };563564 if !arr.is_empty() {565 for v in arr.iter(s.clone()) {566 out.push_str("---\n");567 out.push_str(&v?.manifest(s.clone(), format)?);568 out.push('\n');569 }570 out.push_str("...");571 }572573 out.into()574 }575 ManifestFormat::Yaml {576 padding,577 #[cfg(feature = "exp-preserve-order")]578 preserve_order,579 } => self.to_yaml(580 s,581 *padding,582 #[cfg(feature = "exp-preserve-order")]583 *preserve_order,584 )?,585 ManifestFormat::Json {586 padding,587 #[cfg(feature = "exp-preserve-order")]588 preserve_order,589 } => self.to_json(590 s,591 *padding,592 #[cfg(feature = "exp-preserve-order")]593 *preserve_order,594 )?,595 ManifestFormat::ToString => self.to_string(s)?,596 ManifestFormat::String => match self {597 Self::Str(s) => s.clone(),598 _ => throw!(StringManifestOutputIsNotAString),599 },600 })601 }602603 /// For manifestification604 pub fn to_json(605 &self,606 s: State,607 padding: usize,608 #[cfg(feature = "exp-preserve-order")] preserve_order: bool,609 ) -> Result<IStr> {610 manifest_json_ex(611 s,612 self,613 &ManifestJsonOptions {614 padding: &" ".repeat(padding),615 mtype: if padding == 0 {616 ManifestType::Minify617 } else {618 ManifestType::Manifest619 },620 newline: "\n",621 key_val_sep: ": ",622 #[cfg(feature = "exp-preserve-order")]623 preserve_order,624 },625 )626 .map(Into::into)627 }628629 /// Calls `std.manifestJson`630 pub fn to_std_json(631 &self,632 s: State,633 padding: usize,634 #[cfg(feature = "exp-preserve-order")] preserve_order: bool,635 ) -> Result<Rc<str>> {636 manifest_json_ex(637 s,638 self,639 &ManifestJsonOptions {640 padding: &" ".repeat(padding),641 mtype: ManifestType::Std,642 newline: "\n",643 key_val_sep: ": ",644 #[cfg(feature = "exp-preserve-order")]645 preserve_order,646 },647 )648 .map(Into::into)649 }650651 pub fn to_yaml(652 &self,653 s: State,654 padding: usize,655 #[cfg(feature = "exp-preserve-order")] preserve_order: bool,656 ) -> Result<IStr> {657 let padding = &" ".repeat(padding);658 manifest_yaml_ex(659 s,660 self,661 &ManifestYamlOptions {662 padding,663 arr_element_padding: padding,664 quote_keys: false,665 #[cfg(feature = "exp-preserve-order")]666 preserve_order,667 },668 )669 .map(Into::into)670 }671 pub fn into_indexable(self) -> Result<IndexableVal> {672 Ok(match self {673 Val::Str(s) => IndexableVal::Str(s),674 Val::Arr(arr) => IndexableVal::Arr(arr),675 _ => throw!(ValueIsNotIndexable(self.value_type())),676 })677 }678}679680const fn is_function_like(val: &Val) -> bool {681 matches!(val, Val::Func(_))682}683684/// Native implementation of `std.primitiveEquals`685pub fn primitive_equals(val_a: &Val, val_b: &Val) -> Result<bool> {686 Ok(match (val_a, val_b) {687 (Val::Bool(a), Val::Bool(b)) => a == b,688 (Val::Null, Val::Null) => true,689 (Val::Str(a), Val::Str(b)) => a == b,690 (Val::Num(a), Val::Num(b)) => (a - b).abs() <= f64::EPSILON,691 (Val::Arr(_), Val::Arr(_)) => throw!(RuntimeError(692 "primitiveEquals operates on primitive types, got array".into(),693 )),694 (Val::Obj(_), Val::Obj(_)) => throw!(RuntimeError(695 "primitiveEquals operates on primitive types, got object".into(),696 )),697 (a, b) if is_function_like(a) && is_function_like(b) => {698 throw!(RuntimeError("cannot test equality of functions".into()))699 }700 (_, _) => false,701 })702}703704/// Native implementation of `std.equals`705pub fn equals(s: State, val_a: &Val, val_b: &Val) -> Result<bool> {706 if val_a.value_type() != val_b.value_type() {707 return Ok(false);708 }709 match (val_a, val_b) {710 (Val::Arr(a), Val::Arr(b)) => {711 if ArrValue::ptr_eq(a, b) {712 return Ok(true);713 }714 if a.len() != b.len() {715 return Ok(false);716 }717 for (a, b) in a.iter(s.clone()).zip(b.iter(s.clone())) {718 if !equals(s.clone(), &a?, &b?)? {719 return Ok(false);720 }721 }722 Ok(true)723 }724 (Val::Obj(a), Val::Obj(b)) => {725 if ObjValue::ptr_eq(a, b) {726 return Ok(true);727 }728 let fields = a.fields(729 #[cfg(feature = "exp-preserve-order")]730 false,731 );732 if fields733 != b.fields(734 #[cfg(feature = "exp-preserve-order")]735 false,736 ) {737 return Ok(false);738 }739 for field in fields {740 if !equals(741 s.clone(),742 &a.get(s.clone(), field.clone())?.expect("field exists"),743 &b.get(s.clone(), field)?.expect("field exists"),744 )? {745 return Ok(false);746 }747 }748 Ok(true)749 }750 (a, b) => Ok(primitive_equals(a, b)?),751 }752}1use std::{cell::RefCell, fmt::Debug, rc::Rc};23use gcmodule::{Cc, Trace};4use jrsonnet_interner::IStr;5use jrsonnet_types::ValType;67use crate::{8 cc_ptr_eq,9 error::{Error::*, LocError},10 function::FuncVal,11 gc::{GcHashMap, TraceBox},12 stdlib::manifest::{13 manifest_json_ex, manifest_yaml_ex, ManifestJsonOptions, ManifestType, ManifestYamlOptions,14 },15 throw, Bindable, ObjValue, Result, State, WeakObjValue,16};1718pub trait ThunkValue: Trace {19 type Output;20 fn get(self: Box<Self>, s: State) -> Result<Self::Output>;21}2223#[derive(Trace)]24enum ThunkInner<T> {25 Computed(T),26 Errored(LocError),27 Waiting(TraceBox<dyn ThunkValue<Output = T>>),28 Pending,29}3031#[allow(clippy::module_name_repetitions)]32#[derive(Clone, Trace)]33pub struct Thunk<T>(Cc<RefCell<ThunkInner<T>>>);34impl<T> Thunk<T>35where36 T: Clone + Trace,37{38 pub fn new(f: TraceBox<dyn ThunkValue<Output = T>>) -> Self {39 Self(Cc::new(RefCell::new(ThunkInner::Waiting(f))))40 }41 pub fn evaluated(val: T) -> Self {42 Self(Cc::new(RefCell::new(ThunkInner::Computed(val))))43 }44 pub fn force(&self, s: State) -> Result<()> {45 self.evaluate(s)?;46 Ok(())47 }48 pub fn evaluate(&self, s: State) -> Result<T> {49 match &*self.0.borrow() {50 ThunkInner::Computed(v) => return Ok(v.clone()),51 ThunkInner::Errored(e) => return Err(e.clone()),52 ThunkInner::Pending => return Err(InfiniteRecursionDetected.into()),53 ThunkInner::Waiting(..) => (),54 };55 let value = if let ThunkInner::Waiting(value) =56 std::mem::replace(&mut *self.0.borrow_mut(), ThunkInner::Pending)57 {58 value59 } else {60 unreachable!()61 };62 let new_value = match value.0.get(s) {63 Ok(v) => v,64 Err(e) => {65 *self.0.borrow_mut() = ThunkInner::Errored(e.clone());66 return Err(e);67 }68 };69 *self.0.borrow_mut() = ThunkInner::Computed(new_value.clone());70 Ok(new_value)71 }72}7374type CacheKey = (Option<WeakObjValue>, Option<WeakObjValue>);7576#[derive(Trace, Clone)]77pub struct CachedBindable<I, T>78where79 I: Bindable<Bound = T>,80{81 cache: Cc<RefCell<GcHashMap<CacheKey, T>>>,82 value: I,83}84impl<I: Bindable<Bound = T>, T: Trace> CachedBindable<I, T> {85 pub fn new(value: I) -> Self {86 Self {87 cache: Cc::new(RefCell::new(GcHashMap::new())),88 value,89 }90 }91}92impl<I: Bindable<Bound = T>, T: Clone + Trace> Bindable for CachedBindable<I, T> {93 type Bound = T;94 fn bind(&self, s: State, sup: Option<ObjValue>, this: Option<ObjValue>) -> Result<T> {95 let cache_key = (96 sup.as_ref().map(|s| s.clone().downgrade()),97 this.as_ref().map(|t| t.clone().downgrade()),98 );99 {100 if let Some(t) = self.cache.borrow().get(&cache_key) {101 return Ok(t.clone());102 }103 }104 let bound = self.value.bind(s, sup, this)?;105106 {107 let mut cache = self.cache.borrow_mut();108 cache.insert(cache_key, bound.clone());109 }110111 Ok(bound)112 }113}114115impl<T: Debug> Debug for Thunk<T> {116 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {117 write!(f, "Lazy")118 }119}120impl<T> PartialEq for Thunk<T> {121 fn eq(&self, other: &Self) -> bool {122 cc_ptr_eq(&self.0, &other.0)123 }124}125126#[derive(Clone)]127pub enum ManifestFormat {128 YamlStream(Box<ManifestFormat>),129 Yaml {130 padding: usize,131 #[cfg(feature = "exp-preserve-order")]132 preserve_order: bool,133 },134 Json {135 padding: usize,136 #[cfg(feature = "exp-preserve-order")]137 preserve_order: bool,138 },139 ToString,140 String,141}142impl ManifestFormat {143 #[cfg(feature = "exp-preserve-order")]144 fn preserve_order(&self) -> bool {145 match self {146 ManifestFormat::YamlStream(s) => s.preserve_order(),147 ManifestFormat::Yaml { preserve_order, .. } => *preserve_order,148 ManifestFormat::Json { preserve_order, .. } => *preserve_order,149 ManifestFormat::ToString => false,150 ManifestFormat::String => false,151 }152 }153}154155#[derive(Debug, Clone, Trace)]156pub struct Slice {157 pub(crate) inner: ArrValue,158 pub(crate) from: u32,159 pub(crate) to: u32,160 pub(crate) step: u32,161}162impl Slice {163 const fn from(&self) -> usize {164 self.from as usize165 }166 const fn to(&self) -> usize {167 self.to as usize168 }169 const fn step(&self) -> usize {170 self.step as usize171 }172 const fn len(&self) -> usize {173 // TODO: use div_ceil174 let diff = self.to() - self.from();175 let rem = diff % self.step();176 let div = diff / self.step();177178 if rem == 0 {179 div180 } else {181 div + 1182 }183 }184}185186#[derive(Debug, Clone, Trace)]187#[force_tracking]188pub enum ArrValue {189 Bytes(#[skip_trace] Rc<[u8]>),190 Lazy(Cc<Vec<Thunk<Val>>>),191 Eager(Cc<Vec<Val>>),192 Extended(Box<(Self, Self)>),193 Range(i32, i32),194 Slice(Box<Slice>),195 Reversed(Box<Self>),196}197impl ArrValue {198 pub fn new_eager() -> Self {199 Self::Eager(Cc::new(Vec::new()))200 }201202 /// # Panics203 /// If a > b204 pub fn new_range(a: i32, b: i32) -> Self {205 assert!(a <= b);206 Self::Range(a, b)207 }208209 /// # Panics210 /// If passed numbers are incorrect211 #[must_use]212 pub fn slice(self, from: Option<usize>, to: Option<usize>, step: Option<usize>) -> Self {213 let len = self.len();214 let from = from.unwrap_or(0);215 let to = to.unwrap_or(len).min(len);216 let step = step.unwrap_or(1);217 assert!(from < to);218 assert!(step > 0);219220 Self::Slice(Box::new(Slice {221 inner: self,222 from: from as u32,223 to: to as u32,224 step: step as u32,225 }))226 }227228 pub fn len(&self) -> usize {229 match self {230 Self::Bytes(i) => i.len(),231 Self::Lazy(l) => l.len(),232 Self::Eager(e) => e.len(),233 Self::Extended(v) => v.0.len() + v.1.len(),234 Self::Range(a, b) => a.abs_diff(*b) as usize + 1,235 Self::Reversed(i) => i.len(),236 Self::Slice(s) => s.len(),237 }238 }239240 pub fn is_empty(&self) -> bool {241 self.len() == 0242 }243244 pub fn get(&self, s: State, index: usize) -> Result<Option<Val>> {245 match self {246 Self::Bytes(i) => i247 .get(index)248 .map_or(Ok(None), |v| Ok(Some(Val::Num(f64::from(*v))))),249 Self::Lazy(vec) => {250 if let Some(v) = vec.get(index) {251 Ok(Some(v.evaluate(s)?))252 } else {253 Ok(None)254 }255 }256 Self::Eager(vec) => Ok(vec.get(index).cloned()),257 Self::Extended(v) => {258 let a_len = v.0.len();259 if a_len > index {260 v.0.get(s, index)261 } else {262 v.1.get(s, index - a_len)263 }264 }265 Self::Range(a, _) => {266 if index >= self.len() {267 return Ok(None);268 }269 Ok(Some(Val::Num(((*a as isize) + index as isize) as f64)))270 }271 Self::Reversed(v) => {272 let len = v.len();273 if index >= len {274 return Ok(None);275 }276 v.get(s, len - index - 1)277 }278 Self::Slice(v) => {279 let index = v.from() + index * v.step();280 if index >= v.to() {281 return Ok(None);282 }283 v.inner.get(s, index as usize)284 }285 }286 }287288 pub fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {289 match self {290 Self::Bytes(i) => i291 .get(index)292 .map(|b| Thunk::evaluated(Val::Num(f64::from(*b)))),293 Self::Lazy(vec) => vec.get(index).cloned(),294 Self::Eager(vec) => vec.get(index).cloned().map(Thunk::evaluated),295 Self::Extended(v) => {296 let a_len = v.0.len();297 if a_len > index {298 v.0.get_lazy(index)299 } else {300 v.1.get_lazy(index - a_len)301 }302 }303 Self::Range(a, _) => {304 if index >= self.len() {305 return None;306 }307 Some(Thunk::evaluated(Val::Num(308 ((*a as isize) + index as isize) as f64,309 )))310 }311 Self::Reversed(v) => {312 let len = v.len();313 if index >= len {314 return None;315 }316 v.get_lazy(len - index - 1)317 }318 Self::Slice(s) => {319 let index = s.from() + index * s.step();320 if index >= s.to() {321 return None;322 }323 s.inner.get_lazy(index as usize)324 }325 }326 }327328 pub fn evaluated(&self, s: State) -> Result<Cc<Vec<Val>>> {329 Ok(match self {330 Self::Bytes(i) => {331 let mut out = Vec::with_capacity(i.len());332 for v in i.iter() {333 out.push(Val::Num(f64::from(*v)));334 }335 Cc::new(out)336 }337 Self::Lazy(vec) => {338 let mut out = Vec::with_capacity(vec.len());339 for item in vec.iter() {340 out.push(item.evaluate(s.clone())?);341 }342 Cc::new(out)343 }344 Self::Eager(vec) => vec.clone(),345 Self::Extended(_v) => {346 let mut out = Vec::with_capacity(self.len());347 for item in self.iter(s) {348 out.push(item?);349 }350 Cc::new(out)351 }352 Self::Range(a, b) => {353 let mut out = Vec::with_capacity(self.len());354 for i in *a..*b {355 out.push(Val::Num(f64::from(i)));356 }357 Cc::new(out)358 }359 Self::Reversed(r) => {360 let mut r = r.evaluated(s)?;361 Cc::update_with(&mut r, |v| v.reverse());362 r363 }364 Self::Slice(v) => {365 let mut out = Vec::with_capacity(v.inner.len());366 for v in v367 .inner368 .iter_lazy()369 .skip(v.from())370 .take(v.to() - v.from())371 .step_by(v.step())372 {373 out.push(v.evaluate(s.clone())?);374 }375 Cc::new(out)376 }377 })378 }379380 pub fn iter(&self, s: State) -> impl DoubleEndedIterator<Item = Result<Val>> + '_ {381 (0..self.len()).map(move |idx| match self {382 Self::Bytes(b) => Ok(Val::Num(f64::from(b[idx]))),383 Self::Lazy(l) => l[idx].evaluate(s.clone()),384 Self::Eager(e) => Ok(e[idx].clone()),385 Self::Extended(..) | Self::Range(..) | Self::Reversed(..) | Self::Slice(..) => {386 self.get(s.clone(), idx).map(|e| e.expect("idx < len"))387 }388 })389 }390391 pub fn iter_lazy(&self) -> impl DoubleEndedIterator<Item = Thunk<Val>> + '_ {392 (0..self.len()).map(move |idx| match self {393 Self::Bytes(b) => Thunk::evaluated(Val::Num(f64::from(b[idx]))),394 Self::Lazy(l) => l[idx].clone(),395 Self::Eager(e) => Thunk::evaluated(e[idx].clone()),396 Self::Slice(..) | Self::Extended(..) | Self::Range(..) | Self::Reversed(..) => {397 self.get_lazy(idx).expect("idx < len")398 }399 })400 }401402 #[must_use]403 pub fn reversed(self) -> Self {404 Self::Reversed(Box::new(self))405 }406407 pub fn map(self, s: State, mapper: impl Fn(Val) -> Result<Val>) -> Result<Self> {408 let mut out = Vec::with_capacity(self.len());409410 for value in self.iter(s) {411 out.push(mapper(value?)?);412 }413414 Ok(Self::Eager(Cc::new(out)))415 }416417 pub fn filter(self, s: State, filter: impl Fn(&Val) -> Result<bool>) -> Result<Self> {418 let mut out = Vec::with_capacity(self.len());419420 for value in self.iter(s) {421 let value = value?;422 if filter(&value)? {423 out.push(value);424 }425 }426427 Ok(Self::Eager(Cc::new(out)))428 }429430 pub fn ptr_eq(a: &Self, b: &Self) -> bool {431 match (a, b) {432 (Self::Lazy(a), Self::Lazy(b)) => cc_ptr_eq(a, b),433 (Self::Eager(a), Self::Eager(b)) => cc_ptr_eq(a, b),434 _ => false,435 }436 }437}438439impl From<Vec<Thunk<Val>>> for ArrValue {440 fn from(v: Vec<Thunk<Val>>) -> Self {441 Self::Lazy(Cc::new(v))442 }443}444445impl From<Vec<Val>> for ArrValue {446 fn from(v: Vec<Val>) -> Self {447 Self::Eager(Cc::new(v))448 }449}450451#[allow(clippy::module_name_repetitions)]452pub enum IndexableVal {453 Str(IStr),454 Arr(ArrValue),455}456457#[derive(Debug, Clone, Trace)]458pub enum Val {459 Bool(bool),460 Null,461 Str(IStr),462 Num(f64),463 Arr(ArrValue),464 Obj(ObjValue),465 Func(FuncVal),466}467468impl Val {469 pub const fn as_bool(&self) -> Option<bool> {470 match self {471 Val::Bool(v) => Some(*v),472 _ => None,473 }474 }475 pub const fn as_null(&self) -> Option<()> {476 match self {477 Val::Null => Some(()),478 _ => None,479 }480 }481 pub fn as_str(&self) -> Option<IStr> {482 match self {483 Val::Str(s) => Some(s.clone()),484 _ => None,485 }486 }487 pub const fn as_num(&self) -> Option<f64> {488 match self {489 Val::Num(n) => Some(*n),490 _ => None,491 }492 }493 pub fn as_arr(&self) -> Option<ArrValue> {494 match self {495 Val::Arr(a) => Some(a.clone()),496 _ => None,497 }498 }499 pub fn as_obj(&self) -> Option<ObjValue> {500 match self {501 Val::Obj(o) => Some(o.clone()),502 _ => None,503 }504 }505 pub fn as_func(&self) -> Option<FuncVal> {506 match self {507 Val::Func(f) => Some(f.clone()),508 _ => None,509 }510 }511512 /// Creates `Val::Num` after checking for numeric overflow.513 /// As numbers are `f64`, we can just check for their finity.514 pub fn new_checked_num(num: f64) -> Result<Self> {515 if num.is_finite() {516 Ok(Self::Num(num))517 } else {518 throw!(RuntimeError("overflow".into()))519 }520 }521522 pub const fn value_type(&self) -> ValType {523 match self {524 Self::Str(..) => ValType::Str,525 Self::Num(..) => ValType::Num,526 Self::Arr(..) => ValType::Arr,527 Self::Obj(..) => ValType::Obj,528 Self::Bool(_) => ValType::Bool,529 Self::Null => ValType::Null,530 Self::Func(..) => ValType::Func,531 }532 }533534 pub fn to_string(&self, s: State) -> Result<IStr> {535 Ok(match self {536 Self::Bool(true) => "true".into(),537 Self::Bool(false) => "false".into(),538 Self::Null => "null".into(),539 Self::Str(s) => s.clone(),540 v => manifest_json_ex(541 s,542 v,543 &ManifestJsonOptions {544 padding: "",545 mtype: ManifestType::ToString,546 newline: "\n",547 key_val_sep: ": ",548 #[cfg(feature = "exp-preserve-order")]549 preserve_order: false,550 },551 )?552 .into(),553 })554 }555556 /// Expects value to be object, outputs (key, manifested value) pairs557 pub fn manifest_multi(&self, s: State, ty: &ManifestFormat) -> Result<Vec<(IStr, IStr)>> {558 let obj = match self {559 Self::Obj(obj) => obj,560 _ => throw!(MultiManifestOutputIsNotAObject),561 };562 let keys = obj.fields(563 #[cfg(feature = "exp-preserve-order")]564 ty.preserve_order(),565 );566 let mut out = Vec::with_capacity(keys.len());567 for key in keys {568 let value = obj569 .get(s.clone(), key.clone())?570 .expect("item in object")571 .manifest(s.clone(), ty)?;572 out.push((key, value));573 }574 Ok(out)575 }576577 /// Expects value to be array, outputs manifested values578 pub fn manifest_stream(&self, s: State, ty: &ManifestFormat) -> Result<Vec<IStr>> {579 let arr = match self {580 Self::Arr(a) => a,581 _ => throw!(StreamManifestOutputIsNotAArray),582 };583 let mut out = Vec::with_capacity(arr.len());584 for i in arr.iter(s.clone()) {585 out.push(i?.manifest(s.clone(), ty)?);586 }587 Ok(out)588 }589590 pub fn manifest(&self, s: State, ty: &ManifestFormat) -> Result<IStr> {591 Ok(match ty {592 ManifestFormat::YamlStream(format) => {593 let arr = match self {594 Self::Arr(a) => a,595 _ => throw!(StreamManifestOutputIsNotAArray),596 };597 let mut out = String::new();598599 match format as &ManifestFormat {600 ManifestFormat::YamlStream(_) => throw!(StreamManifestOutputCannotBeRecursed),601 ManifestFormat::String => throw!(StreamManifestCannotNestString),602 _ => {}603 };604605 if !arr.is_empty() {606 for v in arr.iter(s.clone()) {607 out.push_str("---\n");608 out.push_str(&v?.manifest(s.clone(), format)?);609 out.push('\n');610 }611 out.push_str("...");612 }613614 out.into()615 }616 ManifestFormat::Yaml {617 padding,618 #[cfg(feature = "exp-preserve-order")]619 preserve_order,620 } => self.to_yaml(621 s,622 *padding,623 #[cfg(feature = "exp-preserve-order")]624 *preserve_order,625 )?,626 ManifestFormat::Json {627 padding,628 #[cfg(feature = "exp-preserve-order")]629 preserve_order,630 } => self.to_json(631 s,632 *padding,633 #[cfg(feature = "exp-preserve-order")]634 *preserve_order,635 )?,636 ManifestFormat::ToString => self.to_string(s)?,637 ManifestFormat::String => match self {638 Self::Str(s) => s.clone(),639 _ => throw!(StringManifestOutputIsNotAString),640 },641 })642 }643644 /// For manifestification645 pub fn to_json(646 &self,647 s: State,648 padding: usize,649 #[cfg(feature = "exp-preserve-order")] preserve_order: bool,650 ) -> Result<IStr> {651 manifest_json_ex(652 s,653 self,654 &ManifestJsonOptions {655 padding: &" ".repeat(padding),656 mtype: if padding == 0 {657 ManifestType::Minify658 } else {659 ManifestType::Manifest660 },661 newline: "\n",662 key_val_sep: ": ",663 #[cfg(feature = "exp-preserve-order")]664 preserve_order,665 },666 )667 .map(Into::into)668 }669670 /// Calls `std.manifestJson`671 pub fn to_std_json(672 &self,673 s: State,674 padding: usize,675 #[cfg(feature = "exp-preserve-order")] preserve_order: bool,676 ) -> Result<Rc<str>> {677 manifest_json_ex(678 s,679 self,680 &ManifestJsonOptions {681 padding: &" ".repeat(padding),682 mtype: ManifestType::Std,683 newline: "\n",684 key_val_sep: ": ",685 #[cfg(feature = "exp-preserve-order")]686 preserve_order,687 },688 )689 .map(Into::into)690 }691692 pub fn to_yaml(693 &self,694 s: State,695 padding: usize,696 #[cfg(feature = "exp-preserve-order")] preserve_order: bool,697 ) -> Result<IStr> {698 let padding = &" ".repeat(padding);699 manifest_yaml_ex(700 s,701 self,702 &ManifestYamlOptions {703 padding,704 arr_element_padding: padding,705 quote_keys: false,706 #[cfg(feature = "exp-preserve-order")]707 preserve_order,708 },709 )710 .map(Into::into)711 }712 pub fn into_indexable(self) -> Result<IndexableVal> {713 Ok(match self {714 Val::Str(s) => IndexableVal::Str(s),715 Val::Arr(arr) => IndexableVal::Arr(arr),716 _ => throw!(ValueIsNotIndexable(self.value_type())),717 })718 }719}720721const fn is_function_like(val: &Val) -> bool {722 matches!(val, Val::Func(_))723}724725/// Native implementation of `std.primitiveEquals`726pub fn primitive_equals(val_a: &Val, val_b: &Val) -> Result<bool> {727 Ok(match (val_a, val_b) {728 (Val::Bool(a), Val::Bool(b)) => a == b,729 (Val::Null, Val::Null) => true,730 (Val::Str(a), Val::Str(b)) => a == b,731 (Val::Num(a), Val::Num(b)) => (a - b).abs() <= f64::EPSILON,732 (Val::Arr(_), Val::Arr(_)) => throw!(RuntimeError(733 "primitiveEquals operates on primitive types, got array".into(),734 )),735 (Val::Obj(_), Val::Obj(_)) => throw!(RuntimeError(736 "primitiveEquals operates on primitive types, got object".into(),737 )),738 (a, b) if is_function_like(a) && is_function_like(b) => {739 throw!(RuntimeError("cannot test equality of functions".into()))740 }741 (_, _) => false,742 })743}744745/// Native implementation of `std.equals`746pub fn equals(s: State, val_a: &Val, val_b: &Val) -> Result<bool> {747 if val_a.value_type() != val_b.value_type() {748 return Ok(false);749 }750 match (val_a, val_b) {751 (Val::Arr(a), Val::Arr(b)) => {752 if ArrValue::ptr_eq(a, b) {753 return Ok(true);754 }755 if a.len() != b.len() {756 return Ok(false);757 }758 for (a, b) in a.iter(s.clone()).zip(b.iter(s.clone())) {759 if !equals(s.clone(), &a?, &b?)? {760 return Ok(false);761 }762 }763 Ok(true)764 }765 (Val::Obj(a), Val::Obj(b)) => {766 if ObjValue::ptr_eq(a, b) {767 return Ok(true);768 }769 let fields = a.fields(770 #[cfg(feature = "exp-preserve-order")]771 false,772 );773 if fields774 != b.fields(775 #[cfg(feature = "exp-preserve-order")]776 false,777 ) {778 return Ok(false);779 }780 for field in fields {781 if !equals(782 s.clone(),783 &a.get(s.clone(), field.clone())?.expect("field exists"),784 &b.get(s.clone(), field)?.expect("field exists"),785 )? {786 return Ok(false);787 }788 }789 Ok(true)790 }791 (a, b) => Ok(primitive_equals(a, b)?),792 }793}crates/jrsonnet-evaluator/tests/builtin.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/tests/builtin.rs
+++ b/crates/jrsonnet-evaluator/tests/builtin.rs
@@ -6,7 +6,6 @@
use jrsonnet_evaluator::{
error::Result,
function::{builtin, builtin::Builtin, CallLocation, FuncVal},
- gc::TraceBox,
tb,
typed::Typed,
State, Val,
crates/jrsonnet-evaluator/tests/common.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/tests/common.rs
+++ b/crates/jrsonnet-evaluator/tests/common.rs
@@ -30,8 +30,18 @@
if !::jrsonnet_evaluator::val::equals($s.clone(), &$a.clone(), &$b.clone())? {
::jrsonnet_evaluator::throw_runtime!(
"assertion failed: a != b\na={:#?}\nb={:#?}",
- $a.to_json($s.clone(), 2)?,
- $b.to_json($s.clone(), 2)?,
+ $a.to_json(
+ $s.clone(),
+ 2,
+ #[cfg(feature = "exp-preserve-order")]
+ false
+ )?,
+ $b.to_json(
+ $s.clone(),
+ 2,
+ #[cfg(feature = "exp-preserve-order")]
+ false
+ )?,
)
}
}};
crates/jrsonnet-evaluator/tests/golden.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/tests/golden.rs
+++ b/crates/jrsonnet-evaluator/tests/golden.rs
@@ -24,7 +24,12 @@
Ok(v) => v,
Err(e) => return s.stringify_err(&e),
};
- match v.to_json(s.clone(), 3) {
+ match v.to_json(
+ s.clone(),
+ 3,
+ #[cfg(feature = "exp-preserve-order")]
+ false,
+ ) {
Ok(v) => v.to_string(),
Err(e) => s.stringify_err(&e),
}
crates/jrsonnet-parser/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-parser/src/lib.rs
+++ b/crates/jrsonnet-parser/src/lib.rs
@@ -165,7 +165,7 @@
/ string_block() } / expected!("<string>")
pub rule field_name(s: &ParserSettings) -> expr::FieldName
- = name:id() {expr::FieldName::Fixed(name.into())}
+ = name:id() {expr::FieldName::Fixed(name)}
/ name:string() {expr::FieldName::Fixed(name.into())}
/ "[" _ expr:expr(s) _ "]" {expr::FieldName::Dyn(expr)}
pub rule visibility() -> expr::Visibility