difftreelog
feat unify Arg and Typed handling for Thunk
in: master
8 files changed
crates/jrsonnet-evaluator/src/ctx.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/ctx.rs
+++ b/crates/jrsonnet-evaluator/src/ctx.rs
@@ -81,7 +81,7 @@
#[must_use]
pub fn into_future(self, ctx: Pending<Self>) -> Self {
{
- ctx.0.borrow_mut().replace(self);
+ ctx.clone().fill(self);
}
ctx.unwrap()
}
crates/jrsonnet-evaluator/src/dynamic.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/dynamic.rs
+++ b/crates/jrsonnet-evaluator/src/dynamic.rs
@@ -1,29 +1,49 @@
-use std::cell::RefCell;
+use std::cell::OnceCell;
use jrsonnet_gcmodule::{Cc, Trace};
+use crate::{error::ErrorKind::InfiniteRecursionDetected, throw, val::ThunkValue, Result, Thunk};
+
// TODO: Replace with OnceCell once in std
#[derive(Clone, Trace)]
-pub struct Pending<V: Trace + 'static>(pub Cc<RefCell<Option<V>>>);
+pub struct Pending<V: Trace + 'static>(pub Cc<OnceCell<V>>);
impl<T: Trace + 'static> Pending<T> {
pub fn new() -> Self {
- Self(Cc::new(RefCell::new(None)))
+ Self(Cc::new(OnceCell::new()))
}
pub fn new_filled(v: T) -> Self {
- Self(Cc::new(RefCell::new(Some(v))))
+ let cell = OnceCell::new();
+ let _ = cell.set(v);
+ Self(Cc::new(cell))
}
/// # Panics
/// If wrapper is filled already
pub fn fill(self, value: T) {
- assert!(self.0.borrow().is_none(), "wrapper is filled already");
- self.0.borrow_mut().replace(value);
+ self.0
+ .set(value)
+ .map_err(|_| ())
+ .expect("wrapper is filled already")
}
}
impl<T: Clone + Trace + 'static> Pending<T> {
/// # Panics
/// If wrapper is not yet filled
pub fn unwrap(&self) -> T {
- self.0.borrow().as_ref().cloned().unwrap()
+ self.0.get().cloned().expect("pending was not filled")
+ }
+ pub fn try_get(&self) -> Option<T> {
+ self.0.get().cloned()
+ }
+}
+
+impl<T: Trace + Clone> ThunkValue for Pending<T> {
+ type Output = T;
+
+ fn get(self: Box<Self>) -> Result<Self::Output> {
+ let Some(value) = self.0.get() else {
+ throw!(InfiniteRecursionDetected);
+ };
+ Ok(value.clone())
}
}
@@ -32,3 +52,9 @@
Self::new()
}
}
+
+impl<T: Trace + Clone> Into<Thunk<T>> for Pending<T> {
+ fn into(self) -> Thunk<T> {
+ Thunk::new(self)
+ }
+}
crates/jrsonnet-evaluator/src/function/arglike.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/function/arglike.rs
+++ b/crates/jrsonnet-evaluator/src/function/arglike.rs
@@ -48,28 +48,22 @@
where
T: Typed + Clone,
{
- fn evaluate_arg(&self, _ctx: Context, _tailstrict: bool) -> Result<Thunk<Val>> {
+ fn evaluate_arg(&self, _ctx: Context, tailstrict: bool) -> Result<Thunk<Val>> {
+ if T::provides_lazy() && !tailstrict {
+ return Ok(T::into_lazy_untyped(self.clone()));
+ }
let val = T::into_untyped(self.clone())?;
Ok(Thunk::evaluated(val))
}
}
impl<T> OptionalContext for T where T: Typed + Clone {}
-impl ArgLike for Thunk<Val> {
- fn evaluate_arg(&self, _ctx: Context, tailstrict: bool) -> Result<Thunk<Val>> {
- if tailstrict {
- self.force()?;
- }
- Ok(self.clone())
- }
-}
-impl OptionalContext for Thunk<Val> {}
-
#[derive(Clone, Trace)]
pub enum TlaArg {
String(IStr),
Code(LocExpr),
Val(Val),
+ Lazy(Thunk<Val>),
}
impl ArgLike for TlaArg {
fn evaluate_arg(&self, ctx: Context, tailstrict: bool) -> Result<Thunk<Val>> {
@@ -84,6 +78,7 @@
})
}),
TlaArg::Val(val) => Ok(Thunk::evaluated(val.clone())),
+ TlaArg::Lazy(lazy) => Ok(lazy.clone()),
}
}
}
crates/jrsonnet-evaluator/src/obj.rsdiffbeforeafterboth1use std::{2 cell::RefCell,3 fmt::Debug,4 hash::{Hash, Hasher},5 ptr::addr_of,6};78use jrsonnet_gcmodule::{Cc, Trace, Weak};9use jrsonnet_interner::IStr;10use jrsonnet_parser::{ExprLocation, Visibility};11use rustc_hash::FxHashMap;1213use crate::{14 error::{Error, ErrorKind::*},15 function::CallLocation,16 gc::{GcHashMap, GcHashSet, TraceBox},17 operator::evaluate_add_op,18 tb, throw, MaybeUnbound, Result, State, Thunk, Unbound, Val,19};2021#[cfg(not(feature = "exp-preserve-order"))]22mod ordering {23 #![allow(24 // This module works as stub for preserve-order feature25 clippy::unused_self,26 )]2728 use jrsonnet_gcmodule::Trace;2930 #[derive(Clone, Copy, Default, Debug, Trace)]31 pub struct FieldIndex(());32 impl FieldIndex {33 pub const fn next(self) -> Self {34 Self(())35 }36 }3738 #[derive(Clone, Copy, Default, Debug, Trace)]39 pub struct SuperDepth(());40 impl SuperDepth {41 pub const fn deeper(self) -> Self {42 Self(())43 }44 }4546 #[derive(Clone, Copy)]47 pub struct FieldSortKey(());48 impl FieldSortKey {49 pub const fn new(_: SuperDepth, _: FieldIndex) -> Self {50 Self(())51 }52 }53}5455#[cfg(feature = "exp-preserve-order")]56mod ordering {57 use std::cmp::{Ordering, Reverse};5859 use jrsonnet_gcmodule::Trace;6061 #[derive(Clone, Copy, Default, Debug, Trace, PartialEq, Eq, PartialOrd, Ord)]62 pub struct FieldIndex(u32);63 impl FieldIndex {64 pub fn next(self) -> Self {65 Self(self.0 + 1)66 }67 }6869 #[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Debug)]70 pub struct SuperDepth(u32);71 impl SuperDepth {72 pub fn deeper(self) -> Self {73 Self(self.0 + 1)74 }75 }7677 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]78 pub struct FieldSortKey(Reverse<SuperDepth>, FieldIndex);79 impl FieldSortKey {80 pub fn new(depth: SuperDepth, index: FieldIndex) -> Self {81 Self(Reverse(depth), index)82 }83 pub fn collide(self, other: Self) -> Self {84 match self.0 .0.cmp(&other.0 .0) {85 Ordering::Greater => self,86 Ordering::Less => other,87 Ordering::Equal => unreachable!("object can't have two fields with the same name"),88 }89 }90 }91}9293use ordering::*;9495#[allow(clippy::module_name_repetitions)]96#[derive(Debug, Trace)]97pub struct ObjMember {98 pub add: bool,99 pub visibility: Visibility,100 original_index: FieldIndex,101 pub invoke: MaybeUnbound,102 pub location: Option<ExprLocation>,103}104105pub trait ObjectAssertion: Trace {106 fn run(&self, super_obj: Option<ObjValue>, this: Option<ObjValue>) -> Result<()>;107}108109// Field => This110111#[derive(Trace)]112enum CacheValue {113 Cached(Val),114 NotFound,115 Pending,116 Errored(Error),117}118119#[allow(clippy::module_name_repetitions)]120#[derive(Trace)]121#[trace(tracking(force))]122pub struct ObjValueInternals {123 sup: Option<ObjValue>,124 this: Option<ObjValue>,125126 assertions: Cc<Vec<TraceBox<dyn ObjectAssertion>>>,127 assertions_ran: RefCell<GcHashSet<ObjValue>>,128 this_entries: Cc<GcHashMap<IStr, ObjMember>>,129 value_cache: RefCell<GcHashMap<(IStr, Option<WeakObjValue>), CacheValue>>,130}131132#[derive(Clone, Trace)]133pub struct WeakObjValue(#[trace(skip)] pub(crate) Weak<ObjValueInternals>);134135impl PartialEq for WeakObjValue {136 fn eq(&self, other: &Self) -> bool {137 Weak::ptr_eq(&self.0, &other.0)138 }139}140141impl Eq for WeakObjValue {}142impl Hash for WeakObjValue {143 fn hash<H: Hasher>(&self, hasher: &mut H) {144 // Safety: usize is POD145 let addr = unsafe { *std::ptr::addr_of!(self.0).cast() };146 hasher.write_usize(addr);147 }148}149150#[allow(clippy::module_name_repetitions)]151#[derive(Clone, Trace)]152pub struct ObjValue(pub(crate) Cc<ObjValueInternals>);153impl Debug for ObjValue {154 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {155 if let Some(super_obj) = self.0.sup.as_ref() {156 if f.alternate() {157 write!(f, "{super_obj:#?}")?;158 } else {159 write!(f, "{super_obj:?}")?;160 }161 write!(f, " + ")?;162 }163 let mut debug = f.debug_struct("ObjValue");164 for (name, member) in self.0.this_entries.iter() {165 debug.field(name, member);166 }167 debug.finish_non_exhaustive()168 }169}170171impl ObjValue {172 pub fn new(173 sup: Option<Self>,174 this_entries: Cc<GcHashMap<IStr, ObjMember>>,175 assertions: Cc<Vec<TraceBox<dyn ObjectAssertion>>>,176 ) -> Self {177 Self(Cc::new(ObjValueInternals {178 sup,179 this: None,180 assertions,181 assertions_ran: RefCell::new(GcHashSet::new()),182 this_entries,183 value_cache: RefCell::new(GcHashMap::new()),184 }))185 }186 pub fn new_empty() -> Self {187 Self::new(None, Cc::new(GcHashMap::new()), Cc::new(Vec::new()))188 }189 pub fn builder() -> ObjValueBuilder {190 ObjValueBuilder::new()191 }192 pub fn builder_with_capacity(capacity: usize) -> ObjValueBuilder {193 ObjValueBuilder::with_capacity(capacity)194 }195 #[must_use]196 pub fn extend_from(&self, sup: Self) -> Self {197 match &self.0.sup {198 None => Self::new(199 Some(sup),200 self.0.this_entries.clone(),201 self.0.assertions.clone(),202 ),203 Some(v) => Self::new(204 Some(v.extend_from(sup)),205 self.0.this_entries.clone(),206 self.0.assertions.clone(),207 ),208 }209 }210 pub(crate) fn extend_with_raw_member(self, key: IStr, value: ObjMember) -> Self {211 let mut new = GcHashMap::with_capacity(1);212 new.insert(key, value);213 Self::new(Some(self), Cc::new(new), Cc::new(Vec::new()))214 }215 pub fn extend_field(&mut self, name: IStr) -> ObjMemberBuilder<ExtendBuilder<'_>> {216 ObjMemberBuilder::new(ExtendBuilder(self), name, FieldIndex::default())217 }218219 #[must_use]220 pub fn with_this(&self, this: Self) -> Self {221 Self(Cc::new(ObjValueInternals {222 sup: self.0.sup.clone(),223 assertions: self.0.assertions.clone(),224 assertions_ran: RefCell::new(GcHashSet::new()),225 this: Some(this),226 this_entries: self.0.this_entries.clone(),227 value_cache: RefCell::new(GcHashMap::new()),228 }))229 }230231 pub fn len(&self) -> usize {232 self.fields_visibility()233 .into_iter()234 .filter(|(_, (visible, _))| *visible)235 .count()236 }237238 pub fn is_empty(&self) -> bool {239 if !self.0.this_entries.is_empty() {240 return false;241 }242 self.0.sup.as_ref().map_or(true, Self::is_empty)243 }244245 /// Run callback for every field found in object246 ///247 /// Returns true if ended prematurely248 pub(crate) fn enum_fields(249 &self,250 depth: SuperDepth,251 handler: &mut impl FnMut(SuperDepth, &IStr, &ObjMember) -> bool,252 ) -> bool {253 if let Some(s) = &self.0.sup {254 if s.enum_fields(depth.deeper(), handler) {255 return true;256 }257 }258 for (name, member) in self.0.this_entries.iter() {259 if handler(depth, name, member) {260 return true;261 }262 }263 false264 }265266 pub fn fields_visibility(&self) -> FxHashMap<IStr, (bool, FieldSortKey)> {267 let mut out = FxHashMap::default();268 self.enum_fields(SuperDepth::default(), &mut |depth, name, member| {269 let new_sort_key = FieldSortKey::new(depth, member.original_index);270 let entry = out.entry(name.clone());271 let (visible, _) = entry.or_insert((true, new_sort_key));272 match member.visibility {273 Visibility::Normal => {}274 Visibility::Hidden => {275 *visible = false;276 }277 Visibility::Unhide => {278 *visible = true;279 }280 };281 false282 });283 out284 }285 pub fn fields_ex(286 &self,287 include_hidden: bool,288 #[cfg(feature = "exp-preserve-order")] preserve_order: bool,289 ) -> Vec<IStr> {290 #[cfg(feature = "exp-preserve-order")]291 if preserve_order {292 let (mut fields, mut keys): (Vec<_>, Vec<_>) = self293 .fields_visibility()294 .into_iter()295 .filter(|(_, (visible, _))| include_hidden || *visible)296 .enumerate()297 .map(|(idx, (k, (_, sk)))| (k, (sk, idx)))298 .unzip();299 keys.sort_unstable_by_key(|v| v.0);300 // Reorder in-place by resulting indexes301 for i in 0..fields.len() {302 let x = fields[i].clone();303 let mut j = i;304 loop {305 let k = keys[j].1;306 keys[j].1 = j;307 if k == i {308 break;309 }310 fields[j] = fields[k].clone();311 j = k;312 }313 fields[j] = x;314 }315 return fields;316 }317318 let mut fields: Vec<_> = self319 .fields_visibility()320 .into_iter()321 .filter(|(_, (visible, _))| include_hidden || *visible)322 .map(|(k, _)| k)323 .collect();324 fields.sort_unstable();325 fields326 }327 pub fn fields(&self, #[cfg(feature = "exp-preserve-order")] preserve_order: bool) -> Vec<IStr> {328 self.fields_ex(329 false,330 #[cfg(feature = "exp-preserve-order")]331 preserve_order,332 )333 }334335 pub fn field_visibility(&self, name: IStr) -> Option<Visibility> {336 if let Some(m) = self.0.this_entries.get(&name) {337 Some(match &m.visibility {338 Visibility::Normal => self339 .0340 .sup341 .as_ref()342 .and_then(|super_obj| super_obj.field_visibility(name))343 .unwrap_or(Visibility::Normal),344 v => *v,345 })346 } else if let Some(super_obj) = &self.0.sup {347 super_obj.field_visibility(name)348 } else {349 None350 }351 }352353 fn has_field_include_hidden(&self, name: IStr) -> bool {354 if self.0.this_entries.contains_key(&name) {355 true356 } else if let Some(super_obj) = &self.0.sup {357 super_obj.has_field_include_hidden(name)358 } else {359 false360 }361 }362363 pub fn has_field_ex(&self, name: IStr, include_hidden: bool) -> bool {364 if include_hidden {365 self.has_field_include_hidden(name)366 } else {367 self.has_field(name)368 }369 }370 pub fn has_field(&self, name: IStr) -> bool {371 self.field_visibility(name)372 .map_or(false, |v| v.is_visible())373 }374375 pub fn iter(376 &self,377 #[cfg(feature = "exp-preserve-order")] preserve_order: bool,378 ) -> impl Iterator<Item = (IStr, Result<Val>)> + '_ {379 let fields = self.fields(380 #[cfg(feature = "exp-preserve-order")]381 preserve_order,382 );383 fields.into_iter().map(|field| {384 (385 field.clone(),386 self.get(field)387 .map(|opt| opt.expect("iterating over keys, field exists")),388 )389 })390 }391392 pub fn get(&self, key: IStr) -> Result<Option<Val>> {393 self.run_assertions()?;394 let cache_key = (key.clone(), None);395 if let Some(v) = self.0.value_cache.borrow().get(&cache_key) {396 return Ok(match v {397 CacheValue::Cached(v) => Some(v.clone()),398 CacheValue::NotFound => None,399 CacheValue::Pending => throw!(InfiniteRecursionDetected),400 CacheValue::Errored(e) => return Err(e.clone()),401 });402 }403 self.0404 .value_cache405 .borrow_mut()406 .insert(cache_key.clone(), CacheValue::Pending);407 let value = self408 .get_raw(key, self.0.this.clone().unwrap_or_else(|| self.clone()))409 .map_err(|e| {410 self.0411 .value_cache412 .borrow_mut()413 .insert(cache_key.clone(), CacheValue::Errored(e.clone()));414 e415 })?;416 self.0.value_cache.borrow_mut().insert(417 cache_key,418 value419 .as_ref()420 .map_or(CacheValue::NotFound, |v| CacheValue::Cached(v.clone())),421 );422 Ok(value)423 }424 pub fn get_for(&self, key: IStr, this: Self) -> Result<Option<Val>> {425 self.run_assertions()?;426 let cache_key = (key.clone(), Some(this.clone().downgrade()));427 if let Some(v) = self.0.value_cache.borrow().get(&cache_key) {428 return Ok(match v {429 CacheValue::Cached(v) => Some(v.clone()),430 CacheValue::NotFound => None,431 CacheValue::Pending => throw!(InfiniteRecursionDetected),432 CacheValue::Errored(e) => return Err(e.clone()),433 });434 }435 self.0436 .value_cache437 .borrow_mut()438 .insert(cache_key.clone(), CacheValue::Pending);439 let value = self.get_raw(key, this).map_err(|e| {440 self.0441 .value_cache442 .borrow_mut()443 .insert(cache_key.clone(), CacheValue::Errored(e.clone()));444 e445 })?;446 self.0.value_cache.borrow_mut().insert(447 cache_key,448 value449 .as_ref()450 .map_or(CacheValue::NotFound, |v| CacheValue::Cached(v.clone())),451 );452 Ok(value)453 }454455 fn get_raw(&self, key: IStr, real_this: Self) -> Result<Option<Val>> {456 match (self.0.this_entries.get(&key), &self.0.sup) {457 (Some(k), None) => Ok(Some(self.evaluate_this(k, real_this)?)),458 (Some(k), Some(super_obj)) => {459 let our = self.evaluate_this(k, real_this.clone())?;460 if k.add {461 super_obj462 .get_raw(key, real_this)?463 .map_or(Ok(Some(our.clone())), |v| {464 Ok(Some(evaluate_add_op(&v, &our)?))465 })466 } else {467 Ok(Some(our))468 }469 }470 (None, Some(super_obj)) => super_obj.get_raw(key, real_this),471 (None, None) => Ok(None),472 }473 }474 fn evaluate_this(&self, v: &ObjMember, real_this: Self) -> Result<Val> {475 v.invoke.evaluate(self.0.sup.clone(), Some(real_this))476 }477478 fn run_assertions_raw(&self, real_this: &Self) -> Result<()> {479 if self.0.assertions.is_empty() {480 if let Some(super_obj) = &self.0.sup {481 super_obj.run_assertions_raw(real_this)?;482 }483 return Ok(());484 }485 if self.0.assertions_ran.borrow_mut().insert(real_this.clone()) {486 for assertion in self.0.assertions.iter() {487 if let Err(e) = assertion.run(self.0.sup.clone(), Some(real_this.clone())) {488 self.0.assertions_ran.borrow_mut().remove(real_this);489 return Err(e);490 }491 }492 if let Some(super_obj) = &self.0.sup {493 super_obj.run_assertions_raw(real_this)?;494 }495 }496 Ok(())497 }498 pub fn run_assertions(&self) -> Result<()> {499 self.run_assertions_raw(self)500 }501502 pub fn ptr_eq(a: &Self, b: &Self) -> bool {503 Cc::ptr_eq(&a.0, &b.0)504 }505 pub fn downgrade(self) -> WeakObjValue {506 WeakObjValue(self.0.downgrade())507 }508}509510impl PartialEq for ObjValue {511 fn eq(&self, other: &Self) -> bool {512 Cc::ptr_eq(&self.0, &other.0)513 }514}515516impl Eq for ObjValue {}517impl Hash for ObjValue {518 fn hash<H: Hasher>(&self, hasher: &mut H) {519 hasher.write_usize(addr_of!(*self.0) as usize);520 }521}522523#[allow(clippy::module_name_repetitions)]524pub struct ObjValueBuilder {525 sup: Option<ObjValue>,526 map: GcHashMap<IStr, ObjMember>,527 assertions: Vec<TraceBox<dyn ObjectAssertion>>,528 next_field_index: FieldIndex,529}530impl ObjValueBuilder {531 pub fn new() -> Self {532 Self::with_capacity(0)533 }534 pub fn with_capacity(capacity: usize) -> Self {535 Self {536 sup: None,537 map: GcHashMap::with_capacity(capacity),538 assertions: Vec::new(),539 next_field_index: FieldIndex::default(),540 }541 }542 pub fn reserve_asserts(&mut self, capacity: usize) -> &mut Self {543 self.assertions.reserve_exact(capacity);544 self545 }546 pub fn with_super(&mut self, super_obj: ObjValue) -> &mut Self {547 self.sup = Some(super_obj);548 self549 }550551 pub fn assert(&mut self, assertion: impl ObjectAssertion + 'static) -> &mut Self {552 self.assertions.push(tb!(assertion));553 self554 }555 pub fn member(&mut self, name: IStr) -> ObjMemberBuilder<ValueBuilder<'_>> {556 let field_index = self.next_field_index;557 self.next_field_index = self.next_field_index.next();558 ObjMemberBuilder::new(ValueBuilder(self), name, field_index)559 }560561 pub fn build(self) -> ObjValue {562 ObjValue::new(self.sup, Cc::new(self.map), Cc::new(self.assertions))563 }564}565impl Default for ObjValueBuilder {566 fn default() -> Self {567 Self::with_capacity(0)568 }569}570571#[allow(clippy::module_name_repetitions)]572#[must_use = "value not added unless binding() was called"]573pub struct ObjMemberBuilder<Kind> {574 kind: Kind,575 name: IStr,576 add: bool,577 visibility: Visibility,578 original_index: FieldIndex,579 location: Option<ExprLocation>,580}581582#[allow(clippy::missing_const_for_fn)]583impl<Kind> ObjMemberBuilder<Kind> {584 pub(crate) fn new(kind: Kind, name: IStr, original_index: FieldIndex) -> Self {585 Self {586 kind,587 name,588 original_index,589 add: false,590 visibility: Visibility::Normal,591 location: None,592 }593 }594595 pub const fn with_add(mut self, add: bool) -> Self {596 self.add = add;597 self598 }599 pub fn add(self) -> Self {600 self.with_add(true)601 }602 pub fn with_visibility(mut self, visibility: Visibility) -> Self {603 self.visibility = visibility;604 self605 }606 pub fn hide(self) -> Self {607 self.with_visibility(Visibility::Hidden)608 }609 pub fn with_location(mut self, location: ExprLocation) -> Self {610 self.location = Some(location);611 self612 }613 fn build_member(self, binding: MaybeUnbound) -> (Kind, IStr, ObjMember) {614 (615 self.kind,616 self.name,617 ObjMember {618 add: self.add,619 visibility: self.visibility,620 original_index: self.original_index,621 invoke: binding,622 location: self.location,623 },624 )625 }626}627628pub struct ValueBuilder<'v>(&'v mut ObjValueBuilder);629impl ObjMemberBuilder<ValueBuilder<'_>> {630 /// Inserts value, replacing if it is already defined631 pub fn value_unchecked(self, value: Val) {632 let (receiver, name, member) =633 self.build_member(MaybeUnbound::Bound(Thunk::evaluated(value)));634 let entry = receiver.0.map.entry(name);635 entry.insert(member);636 }637638 pub fn value(self, value: Val) -> Result<()> {639 self.thunk(Thunk::evaluated(value))640 }641 pub fn thunk(self, value: Thunk<Val>) -> Result<()> {642 self.binding(MaybeUnbound::Bound(value))643 }644 pub fn bindable(self, bindable: impl Unbound<Bound = Val>) -> Result<()> {645 self.binding(MaybeUnbound::Unbound(Cc::new(tb!(bindable))))646 }647 pub fn binding(self, binding: MaybeUnbound) -> Result<()> {648 let (receiver, name, member) = self.build_member(binding);649 let location = member.location.clone();650 let old = receiver.0.map.insert(name.clone(), member);651 if old.is_some() {652 State::push(653 CallLocation(location.as_ref()),654 || format!("field <{}> initializtion", name.clone()),655 || throw!(DuplicateFieldName(name.clone())),656 )?;657 }658 Ok(())659 }660}661662pub struct ExtendBuilder<'v>(&'v mut ObjValue);663impl ObjMemberBuilder<ExtendBuilder<'_>> {664 pub fn value(self, value: Val) {665 self.binding(MaybeUnbound::Bound(Thunk::evaluated(value)));666 }667 pub fn bindable(self, bindable: TraceBox<dyn Unbound<Bound = Val>>) {668 self.binding(MaybeUnbound::Unbound(Cc::new(bindable)));669 }670 pub fn binding(self, binding: MaybeUnbound) {671 let (receiver, name, member) = self.build_member(binding);672 let new = receiver.0.clone();673 *receiver.0 = new.extend_with_raw_member(name, member);674 }675}1use std::{2 cell::RefCell,3 fmt::Debug,4 hash::{Hash, Hasher},5 ptr::addr_of,6};78use jrsonnet_gcmodule::{Cc, Trace, Weak};9use jrsonnet_interner::IStr;10use jrsonnet_parser::{ExprLocation, Visibility};11use rustc_hash::FxHashMap;1213use crate::{14 error::{Error, ErrorKind::*},15 function::CallLocation,16 gc::{GcHashMap, GcHashSet, TraceBox},17 operator::evaluate_add_op,18 tb, throw,19 val::ThunkValue,20 MaybeUnbound, Result, State, Thunk, Unbound, Val,21};2223#[cfg(not(feature = "exp-preserve-order"))]24mod ordering {25 #![allow(26 // This module works as stub for preserve-order feature27 clippy::unused_self,28 )]2930 use jrsonnet_gcmodule::Trace;3132 #[derive(Clone, Copy, Default, Debug, Trace)]33 pub struct FieldIndex(());34 impl FieldIndex {35 pub const fn next(self) -> Self {36 Self(())37 }38 }3940 #[derive(Clone, Copy, Default, Debug, Trace)]41 pub struct SuperDepth(());42 impl SuperDepth {43 pub const fn deeper(self) -> Self {44 Self(())45 }46 }4748 #[derive(Clone, Copy)]49 pub struct FieldSortKey(());50 impl FieldSortKey {51 pub const fn new(_: SuperDepth, _: FieldIndex) -> Self {52 Self(())53 }54 }55}5657#[cfg(feature = "exp-preserve-order")]58mod ordering {59 use std::cmp::{Ordering, Reverse};6061 use jrsonnet_gcmodule::Trace;6263 #[derive(Clone, Copy, Default, Debug, Trace, PartialEq, Eq, PartialOrd, Ord)]64 pub struct FieldIndex(u32);65 impl FieldIndex {66 pub fn next(self) -> Self {67 Self(self.0 + 1)68 }69 }7071 #[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Debug)]72 pub struct SuperDepth(u32);73 impl SuperDepth {74 pub fn deeper(self) -> Self {75 Self(self.0 + 1)76 }77 }7879 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]80 pub struct FieldSortKey(Reverse<SuperDepth>, FieldIndex);81 impl FieldSortKey {82 pub fn new(depth: SuperDepth, index: FieldIndex) -> Self {83 Self(Reverse(depth), index)84 }85 pub fn collide(self, other: Self) -> Self {86 match self.0 .0.cmp(&other.0 .0) {87 Ordering::Greater => self,88 Ordering::Less => other,89 Ordering::Equal => unreachable!("object can't have two fields with the same name"),90 }91 }92 }93}9495use ordering::*;9697#[allow(clippy::module_name_repetitions)]98#[derive(Debug, Trace)]99pub struct ObjMember {100 pub add: bool,101 pub visibility: Visibility,102 original_index: FieldIndex,103 pub invoke: MaybeUnbound,104 pub location: Option<ExprLocation>,105}106107pub trait ObjectAssertion: Trace {108 fn run(&self, super_obj: Option<ObjValue>, this: Option<ObjValue>) -> Result<()>;109}110111// Field => This112113#[derive(Trace)]114enum CacheValue {115 Cached(Val),116 NotFound,117 Pending,118 Errored(Error),119}120121#[allow(clippy::module_name_repetitions)]122#[derive(Trace)]123#[trace(tracking(force))]124pub struct ObjValueInternals {125 sup: Option<ObjValue>,126 this: Option<ObjValue>,127128 assertions: Cc<Vec<TraceBox<dyn ObjectAssertion>>>,129 assertions_ran: RefCell<GcHashSet<ObjValue>>,130 this_entries: Cc<GcHashMap<IStr, ObjMember>>,131 value_cache: RefCell<GcHashMap<(IStr, Option<WeakObjValue>), CacheValue>>,132}133134#[derive(Clone, Trace)]135pub struct WeakObjValue(#[trace(skip)] pub(crate) Weak<ObjValueInternals>);136137impl PartialEq for WeakObjValue {138 fn eq(&self, other: &Self) -> bool {139 Weak::ptr_eq(&self.0, &other.0)140 }141}142143impl Eq for WeakObjValue {}144impl Hash for WeakObjValue {145 fn hash<H: Hasher>(&self, hasher: &mut H) {146 // Safety: usize is POD147 let addr = unsafe { *std::ptr::addr_of!(self.0).cast() };148 hasher.write_usize(addr);149 }150}151152#[allow(clippy::module_name_repetitions)]153#[derive(Clone, Trace)]154pub struct ObjValue(pub(crate) Cc<ObjValueInternals>);155impl Debug for ObjValue {156 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {157 if let Some(super_obj) = self.0.sup.as_ref() {158 if f.alternate() {159 write!(f, "{super_obj:#?}")?;160 } else {161 write!(f, "{super_obj:?}")?;162 }163 write!(f, " + ")?;164 }165 let mut debug = f.debug_struct("ObjValue");166 for (name, member) in self.0.this_entries.iter() {167 debug.field(name, member);168 }169 debug.finish_non_exhaustive()170 }171}172173impl ObjValue {174 pub fn new(175 sup: Option<Self>,176 this_entries: Cc<GcHashMap<IStr, ObjMember>>,177 assertions: Cc<Vec<TraceBox<dyn ObjectAssertion>>>,178 ) -> Self {179 Self(Cc::new(ObjValueInternals {180 sup,181 this: None,182 assertions,183 assertions_ran: RefCell::new(GcHashSet::new()),184 this_entries,185 value_cache: RefCell::new(GcHashMap::new()),186 }))187 }188 pub fn new_empty() -> Self {189 Self::new(None, Cc::new(GcHashMap::new()), Cc::new(Vec::new()))190 }191 pub fn builder() -> ObjValueBuilder {192 ObjValueBuilder::new()193 }194 pub fn builder_with_capacity(capacity: usize) -> ObjValueBuilder {195 ObjValueBuilder::with_capacity(capacity)196 }197 #[must_use]198 pub fn extend_from(&self, sup: Self) -> Self {199 match &self.0.sup {200 None => Self::new(201 Some(sup),202 self.0.this_entries.clone(),203 self.0.assertions.clone(),204 ),205 Some(v) => Self::new(206 Some(v.extend_from(sup)),207 self.0.this_entries.clone(),208 self.0.assertions.clone(),209 ),210 }211 }212 pub(crate) fn extend_with_raw_member(self, key: IStr, value: ObjMember) -> Self {213 let mut new = GcHashMap::with_capacity(1);214 new.insert(key, value);215 Self::new(Some(self), Cc::new(new), Cc::new(Vec::new()))216 }217 pub fn extend_field(&mut self, name: IStr) -> ObjMemberBuilder<ExtendBuilder<'_>> {218 ObjMemberBuilder::new(ExtendBuilder(self), name, FieldIndex::default())219 }220221 #[must_use]222 pub fn with_this(&self, this: Self) -> Self {223 Self(Cc::new(ObjValueInternals {224 sup: self.0.sup.clone(),225 assertions: self.0.assertions.clone(),226 assertions_ran: RefCell::new(GcHashSet::new()),227 this: Some(this),228 this_entries: self.0.this_entries.clone(),229 value_cache: RefCell::new(GcHashMap::new()),230 }))231 }232233 pub fn len(&self) -> usize {234 self.fields_visibility()235 .into_iter()236 .filter(|(_, (visible, _))| *visible)237 .count()238 }239240 pub fn is_empty(&self) -> bool {241 if !self.0.this_entries.is_empty() {242 return false;243 }244 self.0.sup.as_ref().map_or(true, Self::is_empty)245 }246247 /// Run callback for every field found in object248 ///249 /// Returns true if ended prematurely250 pub(crate) fn enum_fields(251 &self,252 depth: SuperDepth,253 handler: &mut impl FnMut(SuperDepth, &IStr, &ObjMember) -> bool,254 ) -> bool {255 if let Some(s) = &self.0.sup {256 if s.enum_fields(depth.deeper(), handler) {257 return true;258 }259 }260 for (name, member) in self.0.this_entries.iter() {261 if handler(depth, name, member) {262 return true;263 }264 }265 false266 }267268 pub fn fields_visibility(&self) -> FxHashMap<IStr, (bool, FieldSortKey)> {269 let mut out = FxHashMap::default();270 self.enum_fields(SuperDepth::default(), &mut |depth, name, member| {271 let new_sort_key = FieldSortKey::new(depth, member.original_index);272 let entry = out.entry(name.clone());273 let (visible, _) = entry.or_insert((true, new_sort_key));274 match member.visibility {275 Visibility::Normal => {}276 Visibility::Hidden => {277 *visible = false;278 }279 Visibility::Unhide => {280 *visible = true;281 }282 };283 false284 });285 out286 }287 pub fn fields_ex(288 &self,289 include_hidden: bool,290 #[cfg(feature = "exp-preserve-order")] preserve_order: bool,291 ) -> Vec<IStr> {292 #[cfg(feature = "exp-preserve-order")]293 if preserve_order {294 let (mut fields, mut keys): (Vec<_>, Vec<_>) = self295 .fields_visibility()296 .into_iter()297 .filter(|(_, (visible, _))| include_hidden || *visible)298 .enumerate()299 .map(|(idx, (k, (_, sk)))| (k, (sk, idx)))300 .unzip();301 keys.sort_unstable_by_key(|v| v.0);302 // Reorder in-place by resulting indexes303 for i in 0..fields.len() {304 let x = fields[i].clone();305 let mut j = i;306 loop {307 let k = keys[j].1;308 keys[j].1 = j;309 if k == i {310 break;311 }312 fields[j] = fields[k].clone();313 j = k;314 }315 fields[j] = x;316 }317 return fields;318 }319320 let mut fields: Vec<_> = self321 .fields_visibility()322 .into_iter()323 .filter(|(_, (visible, _))| include_hidden || *visible)324 .map(|(k, _)| k)325 .collect();326 fields.sort_unstable();327 fields328 }329 pub fn fields(&self, #[cfg(feature = "exp-preserve-order")] preserve_order: bool) -> Vec<IStr> {330 self.fields_ex(331 false,332 #[cfg(feature = "exp-preserve-order")]333 preserve_order,334 )335 }336337 pub fn field_visibility(&self, name: IStr) -> Option<Visibility> {338 if let Some(m) = self.0.this_entries.get(&name) {339 Some(match &m.visibility {340 Visibility::Normal => self341 .0342 .sup343 .as_ref()344 .and_then(|super_obj| super_obj.field_visibility(name))345 .unwrap_or(Visibility::Normal),346 v => *v,347 })348 } else if let Some(super_obj) = &self.0.sup {349 super_obj.field_visibility(name)350 } else {351 None352 }353 }354355 fn has_field_include_hidden(&self, name: IStr) -> bool {356 if self.0.this_entries.contains_key(&name) {357 true358 } else if let Some(super_obj) = &self.0.sup {359 super_obj.has_field_include_hidden(name)360 } else {361 false362 }363 }364365 pub fn has_field_ex(&self, name: IStr, include_hidden: bool) -> bool {366 if include_hidden {367 self.has_field_include_hidden(name)368 } else {369 self.has_field(name)370 }371 }372 pub fn has_field(&self, name: IStr) -> bool {373 self.field_visibility(name)374 .map_or(false, |v| v.is_visible())375 }376377 pub fn iter(378 &self,379 #[cfg(feature = "exp-preserve-order")] preserve_order: bool,380 ) -> impl Iterator<Item = (IStr, Result<Val>)> + '_ {381 let fields = self.fields(382 #[cfg(feature = "exp-preserve-order")]383 preserve_order,384 );385 fields.into_iter().map(|field| {386 (387 field.clone(),388 self.get(field)389 .map(|opt| opt.expect("iterating over keys, field exists")),390 )391 })392 }393394 pub fn get(&self, key: IStr) -> Result<Option<Val>> {395 self.run_assertions()?;396 let cache_key = (key.clone(), None);397 if let Some(v) = self.0.value_cache.borrow().get(&cache_key) {398 return Ok(match v {399 CacheValue::Cached(v) => Some(v.clone()),400 CacheValue::NotFound => None,401 CacheValue::Pending => throw!(InfiniteRecursionDetected),402 CacheValue::Errored(e) => return Err(e.clone()),403 });404 }405 self.0406 .value_cache407 .borrow_mut()408 .insert(cache_key.clone(), CacheValue::Pending);409 let value = self410 .get_raw(key, self.0.this.clone().unwrap_or_else(|| self.clone()))411 .map_err(|e| {412 self.0413 .value_cache414 .borrow_mut()415 .insert(cache_key.clone(), CacheValue::Errored(e.clone()));416 e417 })?;418 self.0.value_cache.borrow_mut().insert(419 cache_key,420 value421 .as_ref()422 .map_or(CacheValue::NotFound, |v| CacheValue::Cached(v.clone())),423 );424 Ok(value)425 }426 pub fn get_for(&self, key: IStr, this: Self) -> Result<Option<Val>> {427 self.run_assertions()?;428 let cache_key = (key.clone(), Some(this.clone().downgrade()));429 if let Some(v) = self.0.value_cache.borrow().get(&cache_key) {430 return Ok(match v {431 CacheValue::Cached(v) => Some(v.clone()),432 CacheValue::NotFound => None,433 CacheValue::Pending => throw!(InfiniteRecursionDetected),434 CacheValue::Errored(e) => return Err(e.clone()),435 });436 }437 self.0438 .value_cache439 .borrow_mut()440 .insert(cache_key.clone(), CacheValue::Pending);441 let value = self.get_raw(key, this).map_err(|e| {442 self.0443 .value_cache444 .borrow_mut()445 .insert(cache_key.clone(), CacheValue::Errored(e.clone()));446 e447 })?;448 self.0.value_cache.borrow_mut().insert(449 cache_key,450 value451 .as_ref()452 .map_or(CacheValue::NotFound, |v| CacheValue::Cached(v.clone())),453 );454 Ok(value)455 }456457 fn get_raw(&self, key: IStr, real_this: Self) -> Result<Option<Val>> {458 match (self.0.this_entries.get(&key), &self.0.sup) {459 (Some(k), None) => Ok(Some(self.evaluate_this(k, real_this)?)),460 (Some(k), Some(super_obj)) => {461 let our = self.evaluate_this(k, real_this.clone())?;462 if k.add {463 super_obj464 .get_raw(key, real_this)?465 .map_or(Ok(Some(our.clone())), |v| {466 Ok(Some(evaluate_add_op(&v, &our)?))467 })468 } else {469 Ok(Some(our))470 }471 }472 (None, Some(super_obj)) => super_obj.get_raw(key, real_this),473 (None, None) => Ok(None),474 }475 }476 fn evaluate_this(&self, v: &ObjMember, real_this: Self) -> Result<Val> {477 v.invoke.evaluate(self.0.sup.clone(), Some(real_this))478 }479480 fn run_assertions_raw(&self, real_this: &Self) -> Result<()> {481 if self.0.assertions.is_empty() {482 if let Some(super_obj) = &self.0.sup {483 super_obj.run_assertions_raw(real_this)?;484 }485 return Ok(());486 }487 if self.0.assertions_ran.borrow_mut().insert(real_this.clone()) {488 for assertion in self.0.assertions.iter() {489 if let Err(e) = assertion.run(self.0.sup.clone(), Some(real_this.clone())) {490 self.0.assertions_ran.borrow_mut().remove(real_this);491 return Err(e);492 }493 }494 if let Some(super_obj) = &self.0.sup {495 super_obj.run_assertions_raw(real_this)?;496 }497 }498 Ok(())499 }500 pub fn run_assertions(&self) -> Result<()> {501 self.run_assertions_raw(self)502 }503504 pub fn ptr_eq(a: &Self, b: &Self) -> bool {505 Cc::ptr_eq(&a.0, &b.0)506 }507 pub fn downgrade(self) -> WeakObjValue {508 WeakObjValue(self.0.downgrade())509 }510}511512impl PartialEq for ObjValue {513 fn eq(&self, other: &Self) -> bool {514 Cc::ptr_eq(&self.0, &other.0)515 }516}517518impl Eq for ObjValue {}519impl Hash for ObjValue {520 fn hash<H: Hasher>(&self, hasher: &mut H) {521 hasher.write_usize(addr_of!(*self.0) as usize);522 }523}524525#[allow(clippy::module_name_repetitions)]526pub struct ObjValueBuilder {527 sup: Option<ObjValue>,528 map: GcHashMap<IStr, ObjMember>,529 assertions: Vec<TraceBox<dyn ObjectAssertion>>,530 next_field_index: FieldIndex,531}532impl ObjValueBuilder {533 pub fn new() -> Self {534 Self::with_capacity(0)535 }536 pub fn with_capacity(capacity: usize) -> Self {537 Self {538 sup: None,539 map: GcHashMap::with_capacity(capacity),540 assertions: Vec::new(),541 next_field_index: FieldIndex::default(),542 }543 }544 pub fn reserve_asserts(&mut self, capacity: usize) -> &mut Self {545 self.assertions.reserve_exact(capacity);546 self547 }548 pub fn with_super(&mut self, super_obj: ObjValue) -> &mut Self {549 self.sup = Some(super_obj);550 self551 }552553 pub fn assert(&mut self, assertion: impl ObjectAssertion + 'static) -> &mut Self {554 self.assertions.push(tb!(assertion));555 self556 }557 pub fn member(&mut self, name: IStr) -> ObjMemberBuilder<ValueBuilder<'_>> {558 let field_index = self.next_field_index;559 self.next_field_index = self.next_field_index.next();560 ObjMemberBuilder::new(ValueBuilder(self), name, field_index)561 }562563 pub fn build(self) -> ObjValue {564 ObjValue::new(self.sup, Cc::new(self.map), Cc::new(self.assertions))565 }566}567impl Default for ObjValueBuilder {568 fn default() -> Self {569 Self::with_capacity(0)570 }571}572573#[allow(clippy::module_name_repetitions)]574#[must_use = "value not added unless binding() was called"]575pub struct ObjMemberBuilder<Kind> {576 kind: Kind,577 name: IStr,578 add: bool,579 visibility: Visibility,580 original_index: FieldIndex,581 location: Option<ExprLocation>,582}583584#[allow(clippy::missing_const_for_fn)]585impl<Kind> ObjMemberBuilder<Kind> {586 pub(crate) fn new(kind: Kind, name: IStr, original_index: FieldIndex) -> Self {587 Self {588 kind,589 name,590 original_index,591 add: false,592 visibility: Visibility::Normal,593 location: None,594 }595 }596597 pub const fn with_add(mut self, add: bool) -> Self {598 self.add = add;599 self600 }601 pub fn add(self) -> Self {602 self.with_add(true)603 }604 pub fn with_visibility(mut self, visibility: Visibility) -> Self {605 self.visibility = visibility;606 self607 }608 pub fn hide(self) -> Self {609 self.with_visibility(Visibility::Hidden)610 }611 pub fn with_location(mut self, location: ExprLocation) -> Self {612 self.location = Some(location);613 self614 }615 fn build_member(self, binding: MaybeUnbound) -> (Kind, IStr, ObjMember) {616 (617 self.kind,618 self.name,619 ObjMember {620 add: self.add,621 visibility: self.visibility,622 original_index: self.original_index,623 invoke: binding,624 location: self.location,625 },626 )627 }628}629630pub struct ValueBuilder<'v>(&'v mut ObjValueBuilder);631impl ObjMemberBuilder<ValueBuilder<'_>> {632 /// Inserts value, replacing if it is already defined633 pub fn value_unchecked(self, value: Val) {634 let (receiver, name, member) =635 self.build_member(MaybeUnbound::Bound(Thunk::evaluated(value)));636 let entry = receiver.0.map.entry(name);637 entry.insert(member);638 }639640 pub fn value(self, value: Val) -> Result<()> {641 self.thunk(Thunk::evaluated(value))642 }643 pub fn thunk(self, value: Thunk<Val>) -> Result<()> {644 self.binding(MaybeUnbound::Bound(value))645 }646 pub fn bindable(self, bindable: impl Unbound<Bound = Val>) -> Result<()> {647 self.binding(MaybeUnbound::Unbound(Cc::new(tb!(bindable))))648 }649 pub fn binding(self, binding: MaybeUnbound) -> Result<()> {650 let (receiver, name, member) = self.build_member(binding);651 let location = member.location.clone();652 let old = receiver.0.map.insert(name.clone(), member);653 if old.is_some() {654 State::push(655 CallLocation(location.as_ref()),656 || format!("field <{}> initializtion", name.clone()),657 || throw!(DuplicateFieldName(name.clone())),658 )?;659 }660 Ok(())661 }662}663664pub struct ExtendBuilder<'v>(&'v mut ObjValue);665impl ObjMemberBuilder<ExtendBuilder<'_>> {666 pub fn value(self, value: Val) {667 self.binding(MaybeUnbound::Bound(Thunk::evaluated(value)));668 }669 pub fn bindable(self, bindable: TraceBox<dyn Unbound<Bound = Val>>) {670 self.binding(MaybeUnbound::Unbound(Cc::new(bindable)));671 }672 pub fn binding(self, binding: MaybeUnbound) {673 let (receiver, name, member) = self.build_member(binding);674 let new = receiver.0.clone();675 *receiver.0 = new.extend_with_raw_member(name, member);676 }677}crates/jrsonnet-evaluator/src/typed/conversions.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/typed/conversions.rs
+++ b/crates/jrsonnet-evaluator/src/typed/conversions.rs
@@ -1,6 +1,6 @@
-use std::ops::Deref;
+use std::{collections::BTreeMap, marker::PhantomData, ops::Deref};
-use jrsonnet_gcmodule::Cc;
+use jrsonnet_gcmodule::{Cc, Trace};
use jrsonnet_interner::{IBytes, IStr};
pub use jrsonnet_macros::Typed;
use jrsonnet_types::{ComplexValType, ValType};
@@ -11,10 +11,28 @@
function::{native::NativeDesc, FuncDesc, FuncVal},
throw,
typed::CheckType,
- val::{IndexableVal, StrValue},
- ObjValue, ObjValueBuilder, Val,
+ val::{IndexableVal, StrValue, ThunkMapper},
+ ObjValue, ObjValueBuilder, Thunk, Val,
};
+#[derive(Trace)]
+struct FromUntyped<K: Trace>(PhantomData<fn() -> K>);
+impl<K> ThunkMapper<Val> for FromUntyped<K>
+where
+ K: Typed + Trace,
+{
+ type Output = K;
+
+ fn map(self, from: Val) -> Result<Self::Output> {
+ K::from_untyped(from)
+ }
+}
+impl<K: Trace> Default for FromUntyped<K> {
+ fn default() -> Self {
+ Self(PhantomData)
+ }
+}
+
pub trait TypedObj: Typed {
fn serialize(self, out: &mut ObjValueBuilder) -> Result<()>;
fn parse(obj: &ObjValue) -> Result<Self>;
@@ -28,8 +46,24 @@
pub trait Typed: Sized {
const TYPE: &'static ComplexValType;
fn into_untyped(typed: Self) -> Result<Val>;
+ fn into_lazy_untyped(typed: Self) -> Thunk<Val> {
+ Thunk::from(Self::into_untyped(typed))
+ }
fn from_untyped(untyped: Val) -> Result<Self>;
+ fn from_lazy_untyped(lazy: Thunk<Val>) -> Result<Self> {
+ Self::from_untyped(lazy.evaluate()?)
+ }
+
+ // Whatever caller should use `into_lazy_untyped` instead of `into_untyped`
+ fn provides_lazy() -> bool {
+ false
+ }
+ // Whatever caller should use `from_lazy_untyped` instead of `from_untyped` when possible
+ fn wants_lazy() -> bool {
+ false
+ }
+
/// Hack to make builtins be able to return non-result values, and make macros able to convert those values to result
/// This method returns identity in impl Typed for Result, and should not be overriden
#[doc(hidden)]
@@ -39,6 +73,54 @@
}
}
+impl<T> Typed for Thunk<T>
+where
+ T: Typed + Trace + Clone,
+{
+ const TYPE: &'static ComplexValType = &ComplexValType::Lazy(T::TYPE);
+
+ fn into_untyped(typed: Self) -> Result<Val> {
+ T::into_untyped(typed.evaluate()?)
+ }
+
+ fn from_untyped(untyped: Val) -> Result<Self> {
+ Self::from_lazy_untyped(Thunk::evaluated(untyped))
+ }
+
+ fn provides_lazy() -> bool {
+ true
+ }
+
+ fn into_lazy_untyped(inner: Self) -> Thunk<Val> {
+ #[derive(Trace)]
+ struct IntoUntyped<K: Trace>(PhantomData<fn() -> K>);
+ impl<K> ThunkMapper<K> for IntoUntyped<K>
+ where
+ K: Typed + Trace,
+ {
+ type Output = Val;
+
+ fn map(self, from: K) -> Result<Self::Output> {
+ K::into_untyped(from)
+ }
+ }
+ impl<K: Trace> Default for IntoUntyped<K> {
+ fn default() -> Self {
+ Self(PhantomData)
+ }
+ }
+ inner.map(<IntoUntyped<T>>::default())
+ }
+
+ fn wants_lazy() -> bool {
+ true
+ }
+
+ fn from_lazy_untyped(inner: Thunk<Val>) -> Result<Self> {
+ Ok(inner.map(<FromUntyped<T>>::default()))
+ }
+}
+
const MAX_SAFE_INTEGER: f64 = ((1u64 << (f64::MANTISSA_DIGITS + 1)) - 1) as f64;
macro_rules! impl_int {
crates/jrsonnet-evaluator/src/typed/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/typed/mod.rs
+++ b/crates/jrsonnet-evaluator/src/typed/mod.rs
@@ -252,6 +252,7 @@
}
Ok(())
}
+ Self::Lazy(_lazy) => Ok(()),
}
}
}
crates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/val.rs
+++ b/crates/jrsonnet-evaluator/src/val.rs
@@ -88,6 +88,54 @@
}
}
+pub trait ThunkMapper<Input>: Trace {
+ type Output;
+ fn map(self, from: Input) -> Result<Self::Output>;
+}
+impl<Input> Thunk<Input>
+where
+ Input: Trace + Clone,
+{
+ pub fn map<M>(self, mapper: M) -> Thunk<M::Output>
+ where
+ M: ThunkMapper<Input>,
+ M::Output: Trace,
+ {
+ #[derive(Trace)]
+ struct Mapped<Input: Trace, Mapper: Trace> {
+ inner: Thunk<Input>,
+ mapper: Mapper,
+ }
+ impl<Input, Mapper> ThunkValue for Mapped<Input, Mapper>
+ where
+ Input: Trace + Clone,
+ Mapper: ThunkMapper<Input>,
+ {
+ type Output = Mapper::Output;
+
+ fn get(self: Box<Self>) -> Result<Self::Output> {
+ let value = self.inner.evaluate()?;
+ let mapped = self.mapper.map(value)?;
+ Ok(mapped)
+ }
+ }
+
+ Thunk::new(Mapped::<Input, M> {
+ inner: self,
+ mapper,
+ })
+ }
+}
+
+impl<T: Trace> From<Result<T>> for Thunk<T> {
+ fn from(value: Result<T>) -> Self {
+ match value {
+ Ok(o) => Self::evaluated(o),
+ Err(e) => Self::errored(e),
+ }
+ }
+}
+
type CacheKey = (Option<WeakObjValue>, Option<WeakObjValue>);
#[derive(Trace, Clone)]
@@ -272,6 +320,11 @@
Self::Flat(value.into())
}
}
+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 {
crates/jrsonnet-types/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-types/src/lib.rs
+++ b/crates/jrsonnet-types/src/lib.rs
@@ -128,10 +128,12 @@
Array(Box<ComplexValType>),
ArrayRef(&'static ComplexValType),
ObjectRef(&'static [(&'static str, &'static ComplexValType)]),
+ AttrsOf(&'static ComplexValType),
Union(Vec<ComplexValType>),
UnionRef(&'static [&'static ComplexValType]),
Sum(Vec<ComplexValType>),
SumRef(&'static [&'static ComplexValType]),
+ Lazy(&'static ComplexValType),
}
impl From<ValType> for ComplexValType {
@@ -195,10 +197,18 @@
}
write!(f, "}}")?;
}
+ ComplexValType::AttrsOf(a) => {
+ if matches!(a, ComplexValType::Any) {
+ write!(f, "object")?;
+ } else {
+ write!(f, "AttrsOf<{a}>")?;
+ }
+ }
ComplexValType::Union(v) => write_union(f, true, v.iter())?,
ComplexValType::UnionRef(v) => write_union(f, true, v.iter().copied())?,
ComplexValType::Sum(v) => write_union(f, false, v.iter())?,
ComplexValType::SumRef(v) => write_union(f, false, v.iter().copied())?,
+ ComplexValType::Lazy(lazy) => write!(f, "Lazy<{lazy}>")?,
};
Ok(())
}