difftreelog
refactor move push_frame out of State struct
in: master
14 files changed
crates/jrsonnet-evaluator/src/evaluate/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/evaluate/mod.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/mod.rs
@@ -16,10 +16,11 @@
error::{suggest_object_fields, ErrorKind::*},
evaluate::operator::{evaluate_add_op, evaluate_binary_op_special, evaluate_unary_op},
function::{CallLocation, FuncDesc, FuncVal},
+ in_frame,
typed::Typed,
val::{CachedUnbound, IndexableVal, NumValue, StrValue, Thunk, ThunkValue},
Context, Error, GcHashMap, ObjValue, ObjValueBuilder, ObjectAssertion, Pending, Result,
- ResultExt, State, Unbound, Val,
+ ResultExt, Unbound, Val,
};
pub mod destructure;
pub mod operator;
@@ -71,7 +72,7 @@
pub fn evaluate_field_name(ctx: Context, field_name: &FieldName) -> Result<Option<IStr>> {
Ok(match field_name {
FieldName::Fixed(n) => Some(n.clone()),
- FieldName::Dyn(expr) => State::push(
+ FieldName::Dyn(expr) => in_frame(
CallLocation::new(&expr.span()),
|| "evaluating field name".to_string(),
|| {
@@ -374,7 +375,7 @@
if tailstrict {
body()?
} else {
- State::push(loc, || format!("function <{}> call", f.name()), body)?
+ in_frame(loc, || format!("function <{}> call", f.name()), body)?
}
}
v => bail!(OnlyFunctionsCanBeCalledGot(v.value_type())),
@@ -384,13 +385,13 @@
pub fn evaluate_assert(ctx: Context, assertion: &AssertStmt) -> Result<()> {
let value = &assertion.0;
let msg = &assertion.1;
- let assertion_result = State::push(
+ let assertion_result = in_frame(
CallLocation::new(&value.span()),
|| "assertion condition".to_owned(),
|| bool::from_untyped(evaluate(ctx.clone(), value)?),
)?;
if !assertion_result {
- State::push(
+ in_frame(
CallLocation::new(&value.span()),
|| "assertion failure".to_owned(),
|| {
@@ -457,7 +458,7 @@
}
BinaryOp(v1, o, v2) => evaluate_binary_op_special(ctx, v1, *o, v2)?,
UnaryOp(o, v) => evaluate_unary_op(*o, &evaluate(ctx, v)?)?,
- Var(name) => State::push(
+ Var(name) => in_frame(
CallLocation::new(&loc),
|| format!("variable <{name}> access"),
|| ctx.binding(name.clone())?.evaluate(),
@@ -645,7 +646,7 @@
evaluate_assert(ctx.clone(), assert)?;
evaluate(ctx, returned)?
}
- ErrorStmt(e) => State::push(
+ ErrorStmt(e) => in_frame(
CallLocation::new(&loc),
|| "error statement".to_owned(),
|| bail!(RuntimeError(evaluate(ctx, e)?.to_string()?,)),
@@ -655,7 +656,7 @@
cond_then,
cond_else,
} => {
- if State::push(
+ if in_frame(
CallLocation::new(&loc),
|| "if condition".to_owned(),
|| bool::from_untyped(evaluate(ctx.clone(), &cond.0)?),
@@ -676,7 +677,7 @@
desc: &'static str,
) -> Result<Option<T>> {
if let Some(value) = expr {
- Ok(Some(State::push(
+ Ok(Some(in_frame(
loc,
|| format!("slice {desc}"),
|| T::from_untyped(evaluate(ctx.clone(), value)?),
@@ -703,7 +704,7 @@
let s = ctx.state();
let resolved_path = s.resolve_from(tmp.source_path(), path as &str)?;
match i {
- Import(_) => State::push(
+ Import(_) => in_frame(
CallLocation::new(&loc),
|| format!("import {:?}", path.clone()),
|| s.import_resolved(resolved_path),
crates/jrsonnet-evaluator/src/import.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/import.rs
+++ b/crates/jrsonnet-evaluator/src/import.rs
@@ -1,6 +1,5 @@
use std::{
any::Any,
- cell::RefCell,
env::current_dir,
fs,
io::{ErrorKind, Read},
@@ -41,8 +40,10 @@
/// this cannot be resolved using associated type, as evaluator uses object instead of generic for [`ImportResolver`]
fn load_file_contents(&self, resolved: &SourcePath) -> Result<Vec<u8>>;
- /// For downcasts
+ // For downcasts, will be removed after trait_upcasting_coercion
+ // stabilization.
fn as_any(&self) -> &dyn Any;
+ fn as_any_mut(&mut self) -> &mut dyn Any;
}
/// Dummy resolver, can't resolve/load any file
@@ -56,6 +57,9 @@
fn as_any(&self) -> &dyn Any {
self
}
+ fn as_any_mut(&mut self) -> &mut dyn Any {
+ self
+ }
}
#[allow(clippy::use_self)]
impl Default for Box<dyn ImportResolver> {
@@ -69,17 +73,15 @@
pub struct FileImportResolver {
/// Library directories to search for file.
/// Referred to as `jpath` in original jsonnet implementation.
- library_paths: RefCell<Vec<PathBuf>>,
+ library_paths: Vec<PathBuf>,
}
impl FileImportResolver {
- pub fn new(jpath: Vec<PathBuf>) -> Self {
- Self {
- library_paths: RefCell::new(jpath),
- }
+ pub fn new(library_paths: Vec<PathBuf>) -> Self {
+ Self { library_paths }
}
/// Dynamically add new jpath, used by bindings
- pub fn add_jpath(&self, path: PathBuf) {
- self.library_paths.borrow_mut().push(path);
+ pub fn add_jpath(&mut self, path: PathBuf) {
+ self.library_paths.push(path);
}
}
@@ -132,7 +134,7 @@
if let Some(direct) = check_path(&direct)? {
return Ok(direct);
}
- for library_path in self.library_paths.borrow().iter() {
+ for library_path in &self.library_paths {
let mut cloned = library_path.clone();
cloned.push(path);
if let Some(cloned) = check_path(&cloned)? {
@@ -165,11 +167,15 @@
Ok(out)
}
+ fn resolve_from_default(&self, path: &str) -> Result<SourcePath> {
+ self.resolve_from(&SourcePath::default(), path)
+ }
+
fn as_any(&self) -> &dyn Any {
self
}
- fn resolve_from_default(&self, path: &str) -> Result<SourcePath> {
- self.resolve_from(&SourcePath::default(), path)
+ fn as_any_mut(&mut self) -> &mut dyn Any {
+ self
}
}
crates/jrsonnet-evaluator/src/integrations/serde.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/integrations/serde.rs
+++ b/crates/jrsonnet-evaluator/src/integrations/serde.rs
@@ -11,8 +11,8 @@
};
use crate::{
- arr::ArrValue, runtime_error, val::NumValue, Error as JrError, ObjValue, ObjValueBuilder,
- Result, State, Val,
+ arr::ArrValue, in_description_frame, runtime_error, val::NumValue, Error as JrError, ObjValue,
+ ObjValueBuilder, Result, Val,
};
impl<'de> Deserialize<'de> for Val {
@@ -173,8 +173,7 @@
let mut seq = serializer.serialize_seq(Some(arr.len()))?;
for (i, element) in arr.iter().enumerate() {
let mut serde_error = None;
- // TODO: rewrite using try{} after stabilization
- State::push_description(
+ in_description_frame(
|| format!("array index [{i}]"),
|| {
let e = element?;
@@ -199,7 +198,7 @@
) {
let mut serde_error = None;
// TODO: rewrite using try{} after stabilization
- State::push_description(
+ in_description_frame(
|| format!("object field {field:?}"),
|| {
let v = value?;
crates/jrsonnet-evaluator/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/lib.rs
+++ b/crates/jrsonnet-evaluator/src/lib.rs
@@ -45,7 +45,7 @@
#[doc(hidden)]
pub use jrsonnet_macros;
pub use jrsonnet_parser as parser;
-use jrsonnet_parser::{LocExpr, ParserSettings, Source, SourcePath, Span};
+use jrsonnet_parser::{LocExpr, ParserSettings, Source, SourcePath};
pub use obj::*;
use stack::check_depth;
pub use tla::apply_tla;
@@ -376,38 +376,6 @@
context_initializer.populate(source, &mut builder);
builder.build()
- }
-
- /// Executes code creating a new stack frame
- pub fn push<T>(
- e: CallLocation<'_>,
- frame_desc: impl FnOnce() -> String,
- f: impl FnOnce() -> Result<T>,
- ) -> Result<T> {
- let _guard = check_depth()?;
-
- f().with_description_src(e, frame_desc)
- }
-
- /// Executes code creating a new stack frame
- pub fn push_val(
- &self,
- e: &Span,
- frame_desc: impl FnOnce() -> String,
- f: impl FnOnce() -> Result<Val>,
- ) -> Result<Val> {
- let _guard = check_depth()?;
-
- f().with_description_src(e, frame_desc)
- }
- /// Executes code creating a new stack frame
- pub fn push_description<T>(
- frame_desc: impl FnOnce() -> String,
- f: impl FnOnce() -> Result<T>,
- ) -> Result<T> {
- let _guard = check_depth()?;
-
- f().with_description(frame_desc)
}
}
@@ -417,6 +385,26 @@
self.0.file_cache.borrow_mut()
}
}
+/// Executes code creating a new stack frame, to be replaced with try{}
+pub fn in_frame<T>(
+ e: CallLocation<'_>,
+ frame_desc: impl FnOnce() -> String,
+ f: impl FnOnce() -> Result<T>,
+) -> Result<T> {
+ let _guard = check_depth()?;
+
+ f().with_description_src(e, frame_desc)
+}
+
+/// Executes code creating a new stack frame, to be replaced with try{}
+pub fn in_description_frame<T>(
+ frame_desc: impl FnOnce() -> String,
+ f: impl FnOnce() -> Result<T>,
+) -> Result<T> {
+ let _guard = check_depth()?;
+
+ f().with_description(frame_desc)
+}
#[derive(Trace)]
pub struct InitialUnderscore(pub Thunk<Val>);
crates/jrsonnet-evaluator/src/manifest.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/manifest.rs
+++ b/crates/jrsonnet-evaluator/src/manifest.rs
@@ -1,6 +1,6 @@
use std::{borrow::Cow, fmt::Write, ptr};
-use crate::{bail, Result, ResultExt, State, Val};
+use crate::{bail, in_description_frame, Result, ResultExt, Val};
pub trait ManifestFormat {
fn manifest_buf(&self, val: Val, buf: &mut String) -> Result<()>;
@@ -242,7 +242,7 @@
Minify | ToString => {}
};
- State::push_description(
+ in_description_frame(
|| format!("elem <{i}> manifestification"),
|| manifest_json_ex_buf(&item, buf, cur_padding, options),
)?;
@@ -304,7 +304,7 @@
escape_string_json_buf(&key, buf);
buf.push_str(options.key_val_sep);
- State::push_description(
+ in_description_frame(
|| format!("field <{key}> manifestification"),
|| manifest_json_ex_buf(&value, buf, cur_padding, options),
)?;
@@ -412,7 +412,7 @@
for (i, v) in arr.iter().enumerate() {
let v = v.with_description(|| format!("elem <{i}> evaluation"))?;
out.push_str("---\n");
- State::push_description(
+ in_description_frame(
|| format!("elem <{i}> manifestification"),
|| self.inner.manifest_buf(v, out),
)?;
crates/jrsonnet-evaluator/src/obj.rsdiffbeforeafterboth1use std::{2 any::Any,3 cell::RefCell,4 fmt::Debug,5 hash::{Hash, Hasher},6 ptr::addr_of,7};89use jrsonnet_gcmodule::{Cc, Trace, Weak};10use jrsonnet_interner::IStr;11use jrsonnet_parser::{Span, Visibility};12use rustc_hash::FxHashMap;1314use crate::{15 arr::{PickObjectKeyValues, PickObjectValues},16 bail,17 error::{suggest_object_fields, Error, ErrorKind::*},18 function::{CallLocation, FuncVal},19 gc::{GcHashMap, GcHashSet, TraceBox},20 operator::evaluate_add_op,21 tb,22 val::{ArrValue, ThunkValue},23 MaybeUnbound, Result, State, Thunk, Unbound, Val,24};2526#[cfg(not(feature = "exp-preserve-order"))]27mod ordering {28 #![allow(29 // This module works as stub for preserve-order feature30 clippy::unused_self,31 )]3233 use jrsonnet_gcmodule::Trace;3435 #[derive(Clone, Copy, Default, Debug, Trace)]36 pub struct FieldIndex(());37 impl FieldIndex {38 pub const fn next(self) -> Self {39 Self(())40 }41 }4243 #[derive(Clone, Copy, Default, Debug, Trace)]44 pub struct SuperDepth(());45 impl SuperDepth {46 pub const fn deeper(self) -> Self {47 Self(())48 }49 }5051 #[derive(Clone, Copy)]52 pub struct FieldSortKey(());53 impl FieldSortKey {54 pub const fn new(_: SuperDepth, _: FieldIndex) -> Self {55 Self(())56 }57 }58}5960#[cfg(feature = "exp-preserve-order")]61mod ordering {62 use std::cmp::Reverse;6364 use jrsonnet_gcmodule::Trace;6566 #[derive(Clone, Copy, Default, Debug, Trace, PartialEq, Eq, PartialOrd, Ord)]67 pub struct FieldIndex(u32);68 impl FieldIndex {69 pub fn next(self) -> Self {70 Self(self.0 + 1)71 }72 }7374 #[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Debug)]75 pub struct SuperDepth(u32);76 impl SuperDepth {77 pub fn deeper(self) -> Self {78 Self(self.0 + 1)79 }80 }8182 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]83 pub struct FieldSortKey(Reverse<SuperDepth>, FieldIndex);84 impl FieldSortKey {85 pub fn new(depth: SuperDepth, index: FieldIndex) -> Self {86 Self(Reverse(depth), index)87 }88 }89}9091use ordering::{FieldIndex, FieldSortKey, SuperDepth};9293// 0 - add94// 12 - visibility95#[derive(Clone, Copy)]96pub struct ObjFieldFlags(u8);97impl ObjFieldFlags {98 fn new(add: bool, visibility: Visibility) -> Self {99 let mut v = 0;100 if add {101 v |= 1;102 }103 v |= match visibility {104 Visibility::Normal => 0b000,105 Visibility::Hidden => 0b010,106 Visibility::Unhide => 0b100,107 };108 Self(v)109 }110 pub fn add(&self) -> bool {111 self.0 & 1 != 0112 }113 pub fn visibility(&self) -> Visibility {114 match (self.0 & 0b110) >> 1 {115 0b00 => Visibility::Normal,116 0b01 => Visibility::Hidden,117 0b10 => Visibility::Unhide,118 _ => unreachable!(),119 }120 }121}122impl Debug for ObjFieldFlags {123 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {124 f.debug_struct("ObjFieldFlags")125 .field("add", &self.add())126 .field("visibility", &self.visibility())127 .finish()128 }129}130131#[allow(clippy::module_name_repetitions)]132#[derive(Debug, Trace)]133pub struct ObjMember {134 #[trace(skip)]135 flags: ObjFieldFlags,136 original_index: FieldIndex,137 pub invoke: MaybeUnbound,138 pub location: Option<Span>,139}140141pub trait ObjectAssertion: Trace {142 fn run(&self, super_obj: Option<ObjValue>, this: Option<ObjValue>) -> Result<()>;143}144145// Field => This146147#[derive(Trace)]148enum CacheValue {149 Cached(Val),150 NotFound,151 Pending,152 Errored(Error),153}154155#[allow(clippy::module_name_repetitions)]156#[derive(Trace)]157#[trace(tracking(force))]158pub struct OopObject {159 sup: Option<ObjValue>,160 // this: Option<ObjValue>,161 assertions: Cc<Vec<TraceBox<dyn ObjectAssertion>>>,162 assertions_ran: RefCell<GcHashSet<ObjValue>>,163 this_entries: Cc<GcHashMap<IStr, ObjMember>>,164 value_cache: RefCell<GcHashMap<(IStr, Option<WeakObjValue>), CacheValue>>,165}166impl Debug for OopObject {167 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {168 f.debug_struct("OopObject")169 .field("sup", &self.sup)170 // .field("assertions", &self.assertions)171 // .field("assertions_ran", &self.assertions_ran)172 .field("this_entries", &self.this_entries)173 // .field("value_cache", &self.value_cache)174 .finish_non_exhaustive()175 }176}177178type EnumFieldsHandler<'a> = dyn FnMut(SuperDepth, FieldIndex, IStr, Visibility) -> bool + 'a;179180pub trait ObjectLike: Trace + Any + Debug {181 fn extend_from(&self, sup: ObjValue) -> ObjValue;182 /// When using standalone super in object, `this.super_obj.with_this(this)` is executed183 fn with_this(&self, me: ObjValue, this: ObjValue) -> ObjValue {184 ObjValue::new(ThisOverride { inner: me, this })185 }186 fn this(&self) -> Option<ObjValue> {187 None188 }189 fn len(&self) -> usize;190 fn is_empty(&self) -> bool;191 // If callback returns false, iteration stops192 fn enum_fields(&self, depth: SuperDepth, handler: &mut EnumFieldsHandler<'_>) -> bool;193194 fn has_field_include_hidden(&self, name: IStr) -> bool;195 fn has_field(&self, name: IStr) -> bool;196197 fn get_for(&self, key: IStr, this: ObjValue) -> Result<Option<Val>>;198 fn get_for_uncached(&self, key: IStr, this: ObjValue) -> Result<Option<Val>>;199 fn field_visibility(&self, field: IStr) -> Option<Visibility>;200201 fn run_assertions_raw(&self, this: ObjValue) -> Result<()>;202}203204#[derive(Clone, Trace)]205pub struct WeakObjValue(#[trace(skip)] pub(crate) Weak<TraceBox<dyn ObjectLike>>);206207impl PartialEq for WeakObjValue {208 fn eq(&self, other: &Self) -> bool {209 Weak::ptr_eq(&self.0, &other.0)210 }211}212213impl Eq for WeakObjValue {}214impl Hash for WeakObjValue {215 fn hash<H: Hasher>(&self, hasher: &mut H) {216 // Safety: usize is POD217 let addr = unsafe { *std::ptr::addr_of!(self.0).cast() };218 hasher.write_usize(addr);219 }220}221222#[allow(clippy::module_name_repetitions)]223#[derive(Clone, Trace, Debug)]224pub struct ObjValue(pub(crate) Cc<TraceBox<dyn ObjectLike>>);225226#[derive(Debug, Trace)]227struct EmptyObject;228impl ObjectLike for EmptyObject {229 fn extend_from(&self, sup: ObjValue) -> ObjValue {230 // obj + {} == obj231 sup232 }233234 fn this(&self) -> Option<ObjValue> {235 None236 }237238 fn len(&self) -> usize {239 0240 }241242 fn is_empty(&self) -> bool {243 true244 }245246 fn enum_fields(&self, _depth: SuperDepth, _handler: &mut EnumFieldsHandler<'_>) -> bool {247 false248 }249250 fn has_field_include_hidden(&self, _name: IStr) -> bool {251 false252 }253254 fn has_field(&self, _name: IStr) -> bool {255 false256 }257258 fn get_for(&self, _key: IStr, _this: ObjValue) -> Result<Option<Val>> {259 Ok(None)260 }261 fn get_for_uncached(&self, _key: IStr, _this: ObjValue) -> Result<Option<Val>> {262 Ok(None)263 }264265 fn run_assertions_raw(&self, _this: ObjValue) -> Result<()> {266 Ok(())267 }268269 fn field_visibility(&self, _field: IStr) -> Option<Visibility> {270 None271 }272}273274#[derive(Trace, Debug)]275struct ThisOverride {276 inner: ObjValue,277 this: ObjValue,278}279impl ObjectLike for ThisOverride {280 fn with_this(&self, _me: ObjValue, this: ObjValue) -> ObjValue {281 ObjValue::new(Self {282 inner: self.inner.clone(),283 this,284 })285 }286287 fn extend_from(&self, sup: ObjValue) -> ObjValue {288 self.inner.extend_from(sup).with_this(self.this.clone())289 }290291 fn this(&self) -> Option<ObjValue> {292 Some(self.this.clone())293 }294295 fn len(&self) -> usize {296 self.inner.len()297 }298299 fn is_empty(&self) -> bool {300 self.inner.is_empty()301 }302303 fn enum_fields(&self, depth: SuperDepth, handler: &mut EnumFieldsHandler<'_>) -> bool {304 self.inner.enum_fields(depth, handler)305 }306307 fn has_field_include_hidden(&self, name: IStr) -> bool {308 self.inner.has_field_include_hidden(name)309 }310311 fn has_field(&self, name: IStr) -> bool {312 self.inner.has_field(name)313 }314315 fn get_for(&self, key: IStr, this: ObjValue) -> Result<Option<Val>> {316 self.inner.get_for(key, this)317 }318319 fn get_for_uncached(&self, key: IStr, this: ObjValue) -> Result<Option<Val>> {320 self.inner.get_raw(key, this)321 }322323 fn field_visibility(&self, field: IStr) -> Option<Visibility> {324 self.inner.field_visibility(field)325 }326327 fn run_assertions_raw(&self, this: ObjValue) -> Result<()> {328 self.inner.run_assertions_raw(this)329 }330}331332impl ObjValue {333 pub fn new(v: impl ObjectLike) -> Self {334 Self(Cc::new(tb!(v)))335 }336 pub fn new_empty() -> Self {337 Self::new(EmptyObject)338 }339 pub fn builder() -> ObjValueBuilder {340 ObjValueBuilder::new()341 }342 pub fn builder_with_capacity(capacity: usize) -> ObjValueBuilder {343 ObjValueBuilder::with_capacity(capacity)344 }345 pub(crate) fn extend_with_raw_member(self, key: IStr, value: ObjMember) -> Self {346 let mut out = ObjValueBuilder::with_capacity(1);347 out.with_super(self);348 let mut member = out.field(key);349 if value.flags.add() {350 member = member.add();351 }352 if let Some(loc) = value.location {353 member = member.with_location(loc);354 }355 let _ = member356 .with_visibility(value.flags.visibility())357 .binding(value.invoke);358 out.build()359 }360 pub fn extend_field(&mut self, name: IStr) -> ObjMemberBuilder<ExtendBuilder<'_>> {361 ObjMemberBuilder::new(ExtendBuilder(self), name, FieldIndex::default())362 }363364 #[must_use]365 pub fn extend_from(&self, sup: Self) -> Self {366 self.0.extend_from(sup)367 }368 #[must_use]369 pub fn with_this(&self, this: Self) -> Self {370 self.0.with_this(self.clone(), this)371 }372 pub fn len(&self) -> usize {373 self.0.len()374 }375 pub fn is_empty(&self) -> bool {376 self.0.is_empty()377 }378 pub fn enum_fields(&self, depth: SuperDepth, handler: &mut EnumFieldsHandler<'_>) -> bool {379 self.0.enum_fields(depth, handler)380 }381382 pub fn has_field_include_hidden(&self, name: IStr) -> bool {383 self.0.has_field_include_hidden(name)384 }385 pub fn has_field(&self, name: IStr) -> bool {386 self.0.has_field(name)387 }388 pub fn has_field_ex(&self, name: IStr, include_hidden: bool) -> bool {389 if include_hidden {390 self.has_field_include_hidden(name)391 } else {392 self.has_field(name)393 }394 }395396 pub fn get(&self, key: IStr) -> Result<Option<Val>> {397 self.run_assertions()?;398 self.get_for(key, self.0.this().unwrap_or_else(|| self.clone()))399 }400401 pub fn get_for(&self, key: IStr, this: Self) -> Result<Option<Val>> {402 self.0.get_for(key, this)403 }404405 pub fn get_or_bail(&self, key: IStr) -> Result<Val> {406 let Some(value) = self.get(key.clone())? else {407 let suggestions = suggest_object_fields(self, key.clone());408 bail!(NoSuchField(key, suggestions))409 };410 Ok(value)411 }412413 fn get_raw(&self, key: IStr, this: Self) -> Result<Option<Val>> {414 self.0.get_for_uncached(key, this)415 }416417 fn field_visibility(&self, field: IStr) -> Option<Visibility> {418 self.0.field_visibility(field)419 }420421 pub fn run_assertions(&self) -> Result<()> {422 // FIXME: Should it use `self.0.this()` in case of standalone super?423 self.run_assertions_raw(self.clone())424 }425 fn run_assertions_raw(&self, this: Self) -> Result<()> {426 self.0.run_assertions_raw(this)427 }428429 pub fn iter(430 &self,431 #[cfg(feature = "exp-preserve-order")] preserve_order: bool,432 ) -> impl Iterator<Item = (IStr, Result<Val>)> + '_ {433 let fields = self.fields(434 #[cfg(feature = "exp-preserve-order")]435 preserve_order,436 );437 fields.into_iter().map(|field| {438 (439 field.clone(),440 self.get(field)441 .map(|opt| opt.expect("iterating over keys, field exists")),442 )443 })444 }445 pub fn get_lazy(&self, key: IStr) -> Option<Thunk<Val>> {446 #[derive(Trace)]447 struct ThunkGet {448 obj: ObjValue,449 key: IStr,450 }451 impl ThunkValue for ThunkGet {452 type Output = Val;453454 fn get(self: Box<Self>) -> Result<Self::Output> {455 Ok(self.obj.get(self.key)?.expect("field exists"))456 }457 }458459 if !self.has_field_ex(key.clone(), true) {460 return None;461 }462 Some(Thunk::new(ThunkGet {463 obj: self.clone(),464 key,465 }))466 }467 pub fn get_lazy_or_bail(&self, key: IStr) -> Thunk<Val> {468 #[derive(Trace)]469 struct ThunkGet {470 obj: ObjValue,471 key: IStr,472 }473 impl ThunkValue for ThunkGet {474 type Output = Val;475476 fn get(self: Box<Self>) -> Result<Self::Output> {477 self.obj.get_or_bail(self.key)478 }479 }480481 Thunk::new(ThunkGet {482 obj: self.clone(),483 key,484 })485 }486 pub fn ptr_eq(a: &Self, b: &Self) -> bool {487 Cc::ptr_eq(&a.0, &b.0)488 }489 pub fn downgrade(self) -> WeakObjValue {490 WeakObjValue(self.0.downgrade())491 }492 fn fields_visibility(&self) -> FxHashMap<IStr, (bool, FieldSortKey)> {493 let mut out = FxHashMap::default();494 self.enum_fields(495 SuperDepth::default(),496 &mut |depth, index, name, visibility| {497 let new_sort_key = FieldSortKey::new(depth, index);498 let entry = out.entry(name);499 let (visible, _) = entry.or_insert((true, new_sort_key));500 match visibility {501 Visibility::Normal => {}502 Visibility::Hidden => {503 *visible = false;504 }505 Visibility::Unhide => {506 *visible = true;507 }508 };509 false510 },511 );512 out513 }514 pub fn fields_ex(515 &self,516 include_hidden: bool,517 #[cfg(feature = "exp-preserve-order")] preserve_order: bool,518 ) -> Vec<IStr> {519 #[cfg(feature = "exp-preserve-order")]520 if preserve_order {521 let (mut fields, mut keys): (Vec<_>, Vec<_>) = self522 .fields_visibility()523 .into_iter()524 .filter(|(_, (visible, _))| include_hidden || *visible)525 .enumerate()526 .map(|(idx, (k, (_, sk)))| (k, (sk, idx)))527 .unzip();528 keys.sort_unstable_by_key(|v| v.0);529 // Reorder in-place by resulting indexes530 for i in 0..fields.len() {531 let x = fields[i].clone();532 let mut j = i;533 loop {534 let k = keys[j].1;535 keys[j].1 = j;536 if k == i {537 break;538 }539 fields[j] = fields[k].clone();540 j = k;541 }542 fields[j] = x;543 }544 return fields;545 }546547 let mut fields: Vec<_> = self548 .fields_visibility()549 .into_iter()550 .filter(|(_, (visible, _))| include_hidden || *visible)551 .map(|(k, _)| k)552 .collect();553 fields.sort_unstable();554 fields555 }556 pub fn fields(&self, #[cfg(feature = "exp-preserve-order")] preserve_order: bool) -> Vec<IStr> {557 self.fields_ex(558 false,559 #[cfg(feature = "exp-preserve-order")]560 preserve_order,561 )562 }563 pub fn values_ex(564 &self,565 include_hidden: bool,566 #[cfg(feature = "exp-preserve-order")] preserve_order: bool,567 ) -> ArrValue {568 ArrValue::new(PickObjectValues::new(569 self.clone(),570 self.fields_ex(571 include_hidden,572 #[cfg(feature = "exp-preserve-order")]573 preserve_order,574 ),575 ))576 }577 pub fn values(&self, #[cfg(feature = "exp-preserve-order")] preserve_order: bool) -> ArrValue {578 self.values_ex(579 false,580 #[cfg(feature = "exp-preserve-order")]581 preserve_order,582 )583 }584 pub fn key_values_ex(585 &self,586 include_hidden: bool,587 #[cfg(feature = "exp-preserve-order")] preserve_order: bool,588 ) -> ArrValue {589 ArrValue::new(PickObjectKeyValues::new(590 self.clone(),591 self.fields_ex(592 include_hidden,593 #[cfg(feature = "exp-preserve-order")]594 preserve_order,595 ),596 ))597 }598 pub fn key_values(599 &self,600 #[cfg(feature = "exp-preserve-order")] preserve_order: bool,601 ) -> ArrValue {602 self.key_values_ex(603 false,604 #[cfg(feature = "exp-preserve-order")]605 preserve_order,606 )607 }608}609610impl OopObject {611 pub fn new(612 sup: Option<ObjValue>,613 this_entries: Cc<GcHashMap<IStr, ObjMember>>,614 assertions: Cc<Vec<TraceBox<dyn ObjectAssertion>>>,615 ) -> Self {616 Self {617 sup,618 // this: None,619 assertions,620 assertions_ran: RefCell::new(GcHashSet::new()),621 this_entries,622 value_cache: RefCell::new(GcHashMap::new()),623 }624 }625626 fn evaluate_this(&self, v: &ObjMember, real_this: ObjValue) -> Result<Val> {627 v.invoke.evaluate(self.sup.clone(), Some(real_this))628 }629630 // FIXME: Duplication between ObjValue and OopObject631 fn fields_visibility(&self) -> FxHashMap<IStr, (bool, FieldSortKey)> {632 let mut out = FxHashMap::default();633 self.enum_fields(634 SuperDepth::default(),635 &mut |depth, index, name, visibility| {636 let new_sort_key = FieldSortKey::new(depth, index);637 let entry = out.entry(name);638 let (visible, _) = entry.or_insert((true, new_sort_key));639 match visibility {640 Visibility::Normal => {}641 Visibility::Hidden => {642 *visible = false;643 }644 Visibility::Unhide => {645 *visible = true;646 }647 };648 false649 },650 );651 out652 }653}654655impl ObjectLike for OopObject {656 fn extend_from(&self, sup: ObjValue) -> ObjValue {657 ObjValue::new(match &self.sup {658 None => Self::new(659 Some(sup),660 self.this_entries.clone(),661 self.assertions.clone(),662 ),663 Some(v) => Self::new(664 Some(v.extend_from(sup)),665 self.this_entries.clone(),666 self.assertions.clone(),667 ),668 })669 }670671 fn len(&self) -> usize {672 // Maybe it will be better to not compute sort key here?673 self.fields_visibility()674 .into_iter()675 .filter(|(_, (visible, _))| *visible)676 .count()677 }678679 /// Returns false only if there is any visible entry.680 ///681 /// Note that object with hidden fields `{a:: 1}` will be reported as empty here.682 fn is_empty(&self) -> bool {683 self.len() == 0684 }685686 /// Run callback for every field found in object687 ///688 /// Returns true if ended prematurely689 fn enum_fields(&self, depth: SuperDepth, handler: &mut EnumFieldsHandler<'_>) -> bool {690 if let Some(s) = &self.sup {691 if s.enum_fields(depth.deeper(), handler) {692 return true;693 }694 }695 for (name, member) in self.this_entries.iter() {696 if handler(697 depth,698 member.original_index,699 name.clone(),700 member.flags.visibility(),701 ) {702 return true;703 }704 }705 false706 }707708 fn has_field_include_hidden(&self, name: IStr) -> bool {709 if self.this_entries.contains_key(&name) {710 true711 } else if let Some(super_obj) = &self.sup {712 super_obj.has_field_include_hidden(name)713 } else {714 false715 }716 }717 fn has_field(&self, name: IStr) -> bool {718 self.field_visibility(name)719 .map_or(false, |v| v.is_visible())720 }721722 fn get_for(&self, key: IStr, this: ObjValue) -> Result<Option<Val>> {723 let cache_key = (key.clone(), Some(this.clone().downgrade()));724 if let Some(v) = self.value_cache.borrow().get(&cache_key) {725 return Ok(match v {726 CacheValue::Cached(v) => Some(v.clone()),727 CacheValue::NotFound => None,728 CacheValue::Pending => bail!(InfiniteRecursionDetected),729 CacheValue::Errored(e) => return Err(e.clone()),730 });731 }732 self.value_cache733 .borrow_mut()734 .insert(cache_key.clone(), CacheValue::Pending);735 let value = self.get_for_uncached(key, this).map_err(|e| {736 self.value_cache737 .borrow_mut()738 .insert(cache_key.clone(), CacheValue::Errored(e.clone()));739 e740 })?;741 self.value_cache.borrow_mut().insert(742 cache_key,743 value744 .as_ref()745 .map_or(CacheValue::NotFound, |v| CacheValue::Cached(v.clone())),746 );747 Ok(value)748 }749 fn get_for_uncached(&self, key: IStr, real_this: ObjValue) -> Result<Option<Val>> {750 match (self.this_entries.get(&key), &self.sup) {751 (Some(k), None) => Ok(Some(self.evaluate_this(k, real_this)?)),752 (Some(k), Some(super_obj)) => {753 let our = self.evaluate_this(k, real_this.clone())?;754 if k.flags.add() {755 super_obj756 .get_raw(key, real_this)?757 .map_or(Ok(Some(our.clone())), |v| {758 Ok(Some(evaluate_add_op(&v, &our)?))759 })760 } else {761 Ok(Some(our))762 }763 }764 (None, Some(super_obj)) => super_obj.get_raw(key, real_this),765 (None, None) => Ok(None),766 }767 }768 fn field_visibility(&self, name: IStr) -> Option<Visibility> {769 if let Some(m) = self.this_entries.get(&name) {770 Some(match &m.flags.visibility() {771 Visibility::Normal => self772 .sup773 .as_ref()774 .and_then(|super_obj| super_obj.field_visibility(name))775 .unwrap_or(Visibility::Normal),776 v => *v,777 })778 } else if let Some(super_obj) = &self.sup {779 super_obj.field_visibility(name)780 } else {781 None782 }783 }784785 fn run_assertions_raw(&self, real_this: ObjValue) -> Result<()> {786 if self.assertions.is_empty() {787 if let Some(super_obj) = &self.sup {788 super_obj.run_assertions_raw(real_this)?;789 }790 return Ok(());791 }792 if self.assertions_ran.borrow_mut().insert(real_this.clone()) {793 for assertion in self.assertions.iter() {794 if let Err(e) = assertion.run(self.sup.clone(), Some(real_this.clone())) {795 self.assertions_ran.borrow_mut().remove(&real_this);796 return Err(e);797 }798 }799 if let Some(super_obj) = &self.sup {800 super_obj.run_assertions_raw(real_this)?;801 }802 }803 Ok(())804 }805}806807impl PartialEq for ObjValue {808 fn eq(&self, other: &Self) -> bool {809 Cc::ptr_eq(&self.0, &other.0)810 }811}812813impl Eq for ObjValue {}814impl Hash for ObjValue {815 fn hash<H: Hasher>(&self, hasher: &mut H) {816 hasher.write_usize(addr_of!(*self.0) as usize);817 }818}819820#[allow(clippy::module_name_repetitions)]821pub struct ObjValueBuilder {822 sup: Option<ObjValue>,823 map: GcHashMap<IStr, ObjMember>,824 assertions: Vec<TraceBox<dyn ObjectAssertion>>,825 next_field_index: FieldIndex,826}827impl ObjValueBuilder {828 pub fn new() -> Self {829 Self::with_capacity(0)830 }831 pub fn with_capacity(capacity: usize) -> Self {832 Self {833 sup: None,834 map: GcHashMap::with_capacity(capacity),835 assertions: Vec::new(),836 next_field_index: FieldIndex::default(),837 }838 }839 pub fn reserve_asserts(&mut self, capacity: usize) -> &mut Self {840 self.assertions.reserve_exact(capacity);841 self842 }843 pub fn with_super(&mut self, super_obj: ObjValue) -> &mut Self {844 self.sup = Some(super_obj);845 self846 }847848 pub fn assert(&mut self, assertion: impl ObjectAssertion + 'static) -> &mut Self {849 self.assertions.push(tb!(assertion));850 self851 }852 pub fn field(&mut self, name: impl Into<IStr>) -> ObjMemberBuilder<ValueBuilder<'_>> {853 let field_index = self.next_field_index;854 self.next_field_index = self.next_field_index.next();855 ObjMemberBuilder::new(ValueBuilder(self), name.into(), field_index)856 }857 /// Preset for common method definiton pattern:858 /// Create a hidden field with the function value.859 ///860 /// `.field(name).hide().value(Val::function(value))`861 pub fn method(&mut self, name: impl Into<IStr>, value: impl Into<FuncVal>) -> &mut Self {862 self.field(name).hide().value(Val::Func(value.into()));863 self864 }865 pub fn try_method(866 &mut self,867 name: impl Into<IStr>,868 value: impl Into<FuncVal>,869 ) -> Result<&mut Self> {870 self.field(name).hide().try_value(Val::Func(value.into()))?;871 Ok(self)872 }873874 pub fn build(self) -> ObjValue {875 if self.sup.is_none() && self.map.is_empty() && self.assertions.is_empty() {876 return ObjValue::new_empty();877 }878 ObjValue::new(OopObject::new(879 self.sup,880 Cc::new(self.map),881 Cc::new(self.assertions),882 ))883 }884}885impl Default for ObjValueBuilder {886 fn default() -> Self {887 Self::with_capacity(0)888 }889}890891#[allow(clippy::module_name_repetitions)]892#[must_use = "value not added unless binding() was called"]893pub struct ObjMemberBuilder<Kind> {894 kind: Kind,895 name: IStr,896 add: bool,897 visibility: Visibility,898 original_index: FieldIndex,899 location: Option<Span>,900}901902#[allow(clippy::missing_const_for_fn)]903impl<Kind> ObjMemberBuilder<Kind> {904 pub(crate) fn new(kind: Kind, name: IStr, original_index: FieldIndex) -> Self {905 Self {906 kind,907 name,908 original_index,909 add: false,910 visibility: Visibility::Normal,911 location: None,912 }913 }914915 pub const fn with_add(mut self, add: bool) -> Self {916 self.add = add;917 self918 }919 pub fn add(self) -> Self {920 self.with_add(true)921 }922 pub fn with_visibility(mut self, visibility: Visibility) -> Self {923 self.visibility = visibility;924 self925 }926 pub fn hide(self) -> Self {927 self.with_visibility(Visibility::Hidden)928 }929 pub fn with_location(mut self, location: Span) -> Self {930 self.location = Some(location);931 self932 }933 fn build_member(self, binding: MaybeUnbound) -> (Kind, IStr, ObjMember) {934 (935 self.kind,936 self.name,937 ObjMember {938 flags: ObjFieldFlags::new(self.add, self.visibility),939 original_index: self.original_index,940 invoke: binding,941 location: self.location,942 },943 )944 }945}946947pub struct ValueBuilder<'v>(&'v mut ObjValueBuilder);948impl ObjMemberBuilder<ValueBuilder<'_>> {949 /// Inserts value, replacing if it is already defined950 pub fn value(self, value: impl Into<Val>) {951 let (receiver, name, member) =952 self.build_member(MaybeUnbound::Bound(Thunk::evaluated(value.into())));953 let entry = receiver.0.map.entry(name);954 entry.insert(member);955 }956957 /// Tries to insert value, returns an error if it was already defined958 pub fn try_value(self, value: impl Into<Val>) -> Result<()> {959 self.thunk(Thunk::evaluated(value.into()))960 }961 pub fn thunk(self, value: impl Into<Thunk<Val>>) -> Result<()> {962 self.binding(MaybeUnbound::Bound(value.into()))963 }964 pub fn bindable(self, bindable: impl Unbound<Bound = Val>) -> Result<()> {965 self.binding(MaybeUnbound::Unbound(Cc::new(tb!(bindable))))966 }967 pub fn binding(self, binding: MaybeUnbound) -> Result<()> {968 let (receiver, name, member) = self.build_member(binding);969 let location = member.location.clone();970 let old = receiver.0.map.insert(name.clone(), member);971 if old.is_some() {972 State::push(973 CallLocation(location.as_ref()),974 || format!("field <{}> initializtion", name.clone()),975 || bail!(DuplicateFieldName(name.clone())),976 )?;977 }978 Ok(())979 }980}981982pub struct ExtendBuilder<'v>(&'v mut ObjValue);983impl ObjMemberBuilder<ExtendBuilder<'_>> {984 pub fn value(self, value: impl Into<Val>) {985 self.binding(MaybeUnbound::Bound(Thunk::evaluated(value.into())));986 }987 pub fn bindable(self, bindable: TraceBox<dyn Unbound<Bound = Val>>) {988 self.binding(MaybeUnbound::Unbound(Cc::new(bindable)));989 }990 pub fn binding(self, binding: MaybeUnbound) {991 let (receiver, name, member) = self.build_member(binding);992 let new = receiver.0.clone();993 *receiver.0 = new.extend_with_raw_member(name, member);994 }995}1use std::{2 any::Any,3 cell::RefCell,4 fmt::Debug,5 hash::{Hash, Hasher},6 ptr::addr_of,7};89use jrsonnet_gcmodule::{Cc, Trace, Weak};10use jrsonnet_interner::IStr;11use jrsonnet_parser::{Span, Visibility};12use rustc_hash::FxHashMap;1314use crate::{15 arr::{PickObjectKeyValues, PickObjectValues},16 bail,17 error::{suggest_object_fields, Error, ErrorKind::*},18 function::{CallLocation, FuncVal},19 gc::{GcHashMap, GcHashSet, TraceBox},20 in_frame,21 operator::evaluate_add_op,22 tb,23 val::{ArrValue, ThunkValue},24 MaybeUnbound, Result, Thunk, Unbound, Val,25};2627#[cfg(not(feature = "exp-preserve-order"))]28mod ordering {29 #![allow(30 // This module works as stub for preserve-order feature31 clippy::unused_self,32 )]3334 use jrsonnet_gcmodule::Trace;3536 #[derive(Clone, Copy, Default, Debug, Trace)]37 pub struct FieldIndex(());38 impl FieldIndex {39 pub const fn next(self) -> Self {40 Self(())41 }42 }4344 #[derive(Clone, Copy, Default, Debug, Trace)]45 pub struct SuperDepth(());46 impl SuperDepth {47 pub const fn deeper(self) -> Self {48 Self(())49 }50 }5152 #[derive(Clone, Copy)]53 pub struct FieldSortKey(());54 impl FieldSortKey {55 pub const fn new(_: SuperDepth, _: FieldIndex) -> Self {56 Self(())57 }58 }59}6061#[cfg(feature = "exp-preserve-order")]62mod ordering {63 use std::cmp::Reverse;6465 use jrsonnet_gcmodule::Trace;6667 #[derive(Clone, Copy, Default, Debug, Trace, PartialEq, Eq, PartialOrd, Ord)]68 pub struct FieldIndex(u32);69 impl FieldIndex {70 pub fn next(self) -> Self {71 Self(self.0 + 1)72 }73 }7475 #[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Debug)]76 pub struct SuperDepth(u32);77 impl SuperDepth {78 pub fn deeper(self) -> Self {79 Self(self.0 + 1)80 }81 }8283 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]84 pub struct FieldSortKey(Reverse<SuperDepth>, FieldIndex);85 impl FieldSortKey {86 pub fn new(depth: SuperDepth, index: FieldIndex) -> Self {87 Self(Reverse(depth), index)88 }89 }90}9192use ordering::{FieldIndex, FieldSortKey, SuperDepth};9394// 0 - add95// 12 - visibility96#[derive(Clone, Copy)]97pub struct ObjFieldFlags(u8);98impl ObjFieldFlags {99 fn new(add: bool, visibility: Visibility) -> Self {100 let mut v = 0;101 if add {102 v |= 1;103 }104 v |= match visibility {105 Visibility::Normal => 0b000,106 Visibility::Hidden => 0b010,107 Visibility::Unhide => 0b100,108 };109 Self(v)110 }111 pub fn add(&self) -> bool {112 self.0 & 1 != 0113 }114 pub fn visibility(&self) -> Visibility {115 match (self.0 & 0b110) >> 1 {116 0b00 => Visibility::Normal,117 0b01 => Visibility::Hidden,118 0b10 => Visibility::Unhide,119 _ => unreachable!(),120 }121 }122}123impl Debug for ObjFieldFlags {124 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {125 f.debug_struct("ObjFieldFlags")126 .field("add", &self.add())127 .field("visibility", &self.visibility())128 .finish()129 }130}131132#[allow(clippy::module_name_repetitions)]133#[derive(Debug, Trace)]134pub struct ObjMember {135 #[trace(skip)]136 flags: ObjFieldFlags,137 original_index: FieldIndex,138 pub invoke: MaybeUnbound,139 pub location: Option<Span>,140}141142pub trait ObjectAssertion: Trace {143 fn run(&self, super_obj: Option<ObjValue>, this: Option<ObjValue>) -> Result<()>;144}145146// Field => This147148#[derive(Trace)]149enum CacheValue {150 Cached(Val),151 NotFound,152 Pending,153 Errored(Error),154}155156#[allow(clippy::module_name_repetitions)]157#[derive(Trace)]158#[trace(tracking(force))]159pub struct OopObject {160 sup: Option<ObjValue>,161 // this: Option<ObjValue>,162 assertions: Cc<Vec<TraceBox<dyn ObjectAssertion>>>,163 assertions_ran: RefCell<GcHashSet<ObjValue>>,164 this_entries: Cc<GcHashMap<IStr, ObjMember>>,165 value_cache: RefCell<GcHashMap<(IStr, Option<WeakObjValue>), CacheValue>>,166}167impl Debug for OopObject {168 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {169 f.debug_struct("OopObject")170 .field("sup", &self.sup)171 // .field("assertions", &self.assertions)172 // .field("assertions_ran", &self.assertions_ran)173 .field("this_entries", &self.this_entries)174 // .field("value_cache", &self.value_cache)175 .finish_non_exhaustive()176 }177}178179type EnumFieldsHandler<'a> = dyn FnMut(SuperDepth, FieldIndex, IStr, Visibility) -> bool + 'a;180181pub trait ObjectLike: Trace + Any + Debug {182 fn extend_from(&self, sup: ObjValue) -> ObjValue;183 /// When using standalone super in object, `this.super_obj.with_this(this)` is executed184 fn with_this(&self, me: ObjValue, this: ObjValue) -> ObjValue {185 ObjValue::new(ThisOverride { inner: me, this })186 }187 fn this(&self) -> Option<ObjValue> {188 None189 }190 fn len(&self) -> usize;191 fn is_empty(&self) -> bool;192 // If callback returns false, iteration stops193 fn enum_fields(&self, depth: SuperDepth, handler: &mut EnumFieldsHandler<'_>) -> bool;194195 fn has_field_include_hidden(&self, name: IStr) -> bool;196 fn has_field(&self, name: IStr) -> bool;197198 fn get_for(&self, key: IStr, this: ObjValue) -> Result<Option<Val>>;199 fn get_for_uncached(&self, key: IStr, this: ObjValue) -> Result<Option<Val>>;200 fn field_visibility(&self, field: IStr) -> Option<Visibility>;201202 fn run_assertions_raw(&self, this: ObjValue) -> Result<()>;203}204205#[derive(Clone, Trace)]206pub struct WeakObjValue(#[trace(skip)] pub(crate) Weak<TraceBox<dyn ObjectLike>>);207208impl PartialEq for WeakObjValue {209 fn eq(&self, other: &Self) -> bool {210 Weak::ptr_eq(&self.0, &other.0)211 }212}213214impl Eq for WeakObjValue {}215impl Hash for WeakObjValue {216 fn hash<H: Hasher>(&self, hasher: &mut H) {217 // Safety: usize is POD218 let addr = unsafe { *std::ptr::addr_of!(self.0).cast() };219 hasher.write_usize(addr);220 }221}222223#[allow(clippy::module_name_repetitions)]224#[derive(Clone, Trace, Debug)]225pub struct ObjValue(pub(crate) Cc<TraceBox<dyn ObjectLike>>);226227#[derive(Debug, Trace)]228struct EmptyObject;229impl ObjectLike for EmptyObject {230 fn extend_from(&self, sup: ObjValue) -> ObjValue {231 // obj + {} == obj232 sup233 }234235 fn this(&self) -> Option<ObjValue> {236 None237 }238239 fn len(&self) -> usize {240 0241 }242243 fn is_empty(&self) -> bool {244 true245 }246247 fn enum_fields(&self, _depth: SuperDepth, _handler: &mut EnumFieldsHandler<'_>) -> bool {248 false249 }250251 fn has_field_include_hidden(&self, _name: IStr) -> bool {252 false253 }254255 fn has_field(&self, _name: IStr) -> bool {256 false257 }258259 fn get_for(&self, _key: IStr, _this: ObjValue) -> Result<Option<Val>> {260 Ok(None)261 }262 fn get_for_uncached(&self, _key: IStr, _this: ObjValue) -> Result<Option<Val>> {263 Ok(None)264 }265266 fn run_assertions_raw(&self, _this: ObjValue) -> Result<()> {267 Ok(())268 }269270 fn field_visibility(&self, _field: IStr) -> Option<Visibility> {271 None272 }273}274275#[derive(Trace, Debug)]276struct ThisOverride {277 inner: ObjValue,278 this: ObjValue,279}280impl ObjectLike for ThisOverride {281 fn with_this(&self, _me: ObjValue, this: ObjValue) -> ObjValue {282 ObjValue::new(Self {283 inner: self.inner.clone(),284 this,285 })286 }287288 fn extend_from(&self, sup: ObjValue) -> ObjValue {289 self.inner.extend_from(sup).with_this(self.this.clone())290 }291292 fn this(&self) -> Option<ObjValue> {293 Some(self.this.clone())294 }295296 fn len(&self) -> usize {297 self.inner.len()298 }299300 fn is_empty(&self) -> bool {301 self.inner.is_empty()302 }303304 fn enum_fields(&self, depth: SuperDepth, handler: &mut EnumFieldsHandler<'_>) -> bool {305 self.inner.enum_fields(depth, handler)306 }307308 fn has_field_include_hidden(&self, name: IStr) -> bool {309 self.inner.has_field_include_hidden(name)310 }311312 fn has_field(&self, name: IStr) -> bool {313 self.inner.has_field(name)314 }315316 fn get_for(&self, key: IStr, this: ObjValue) -> Result<Option<Val>> {317 self.inner.get_for(key, this)318 }319320 fn get_for_uncached(&self, key: IStr, this: ObjValue) -> Result<Option<Val>> {321 self.inner.get_raw(key, this)322 }323324 fn field_visibility(&self, field: IStr) -> Option<Visibility> {325 self.inner.field_visibility(field)326 }327328 fn run_assertions_raw(&self, this: ObjValue) -> Result<()> {329 self.inner.run_assertions_raw(this)330 }331}332333impl ObjValue {334 pub fn new(v: impl ObjectLike) -> Self {335 Self(Cc::new(tb!(v)))336 }337 pub fn new_empty() -> Self {338 Self::new(EmptyObject)339 }340 pub fn builder() -> ObjValueBuilder {341 ObjValueBuilder::new()342 }343 pub fn builder_with_capacity(capacity: usize) -> ObjValueBuilder {344 ObjValueBuilder::with_capacity(capacity)345 }346 pub(crate) fn extend_with_raw_member(self, key: IStr, value: ObjMember) -> Self {347 let mut out = ObjValueBuilder::with_capacity(1);348 out.with_super(self);349 let mut member = out.field(key);350 if value.flags.add() {351 member = member.add();352 }353 if let Some(loc) = value.location {354 member = member.with_location(loc);355 }356 let _ = member357 .with_visibility(value.flags.visibility())358 .binding(value.invoke);359 out.build()360 }361 pub fn extend_field(&mut self, name: IStr) -> ObjMemberBuilder<ExtendBuilder<'_>> {362 ObjMemberBuilder::new(ExtendBuilder(self), name, FieldIndex::default())363 }364365 #[must_use]366 pub fn extend_from(&self, sup: Self) -> Self {367 self.0.extend_from(sup)368 }369 #[must_use]370 pub fn with_this(&self, this: Self) -> Self {371 self.0.with_this(self.clone(), this)372 }373 pub fn len(&self) -> usize {374 self.0.len()375 }376 pub fn is_empty(&self) -> bool {377 self.0.is_empty()378 }379 pub fn enum_fields(&self, depth: SuperDepth, handler: &mut EnumFieldsHandler<'_>) -> bool {380 self.0.enum_fields(depth, handler)381 }382383 pub fn has_field_include_hidden(&self, name: IStr) -> bool {384 self.0.has_field_include_hidden(name)385 }386 pub fn has_field(&self, name: IStr) -> bool {387 self.0.has_field(name)388 }389 pub fn has_field_ex(&self, name: IStr, include_hidden: bool) -> bool {390 if include_hidden {391 self.has_field_include_hidden(name)392 } else {393 self.has_field(name)394 }395 }396397 pub fn get(&self, key: IStr) -> Result<Option<Val>> {398 self.run_assertions()?;399 self.get_for(key, self.0.this().unwrap_or_else(|| self.clone()))400 }401402 pub fn get_for(&self, key: IStr, this: Self) -> Result<Option<Val>> {403 self.0.get_for(key, this)404 }405406 pub fn get_or_bail(&self, key: IStr) -> Result<Val> {407 let Some(value) = self.get(key.clone())? else {408 let suggestions = suggest_object_fields(self, key.clone());409 bail!(NoSuchField(key, suggestions))410 };411 Ok(value)412 }413414 fn get_raw(&self, key: IStr, this: Self) -> Result<Option<Val>> {415 self.0.get_for_uncached(key, this)416 }417418 fn field_visibility(&self, field: IStr) -> Option<Visibility> {419 self.0.field_visibility(field)420 }421422 pub fn run_assertions(&self) -> Result<()> {423 // FIXME: Should it use `self.0.this()` in case of standalone super?424 self.run_assertions_raw(self.clone())425 }426 fn run_assertions_raw(&self, this: Self) -> Result<()> {427 self.0.run_assertions_raw(this)428 }429430 pub fn iter(431 &self,432 #[cfg(feature = "exp-preserve-order")] preserve_order: bool,433 ) -> impl Iterator<Item = (IStr, Result<Val>)> + '_ {434 let fields = self.fields(435 #[cfg(feature = "exp-preserve-order")]436 preserve_order,437 );438 fields.into_iter().map(|field| {439 (440 field.clone(),441 self.get(field)442 .map(|opt| opt.expect("iterating over keys, field exists")),443 )444 })445 }446 pub fn get_lazy(&self, key: IStr) -> Option<Thunk<Val>> {447 #[derive(Trace)]448 struct ThunkGet {449 obj: ObjValue,450 key: IStr,451 }452 impl ThunkValue for ThunkGet {453 type Output = Val;454455 fn get(self: Box<Self>) -> Result<Self::Output> {456 Ok(self.obj.get(self.key)?.expect("field exists"))457 }458 }459460 if !self.has_field_ex(key.clone(), true) {461 return None;462 }463 Some(Thunk::new(ThunkGet {464 obj: self.clone(),465 key,466 }))467 }468 pub fn get_lazy_or_bail(&self, key: IStr) -> Thunk<Val> {469 #[derive(Trace)]470 struct ThunkGet {471 obj: ObjValue,472 key: IStr,473 }474 impl ThunkValue for ThunkGet {475 type Output = Val;476477 fn get(self: Box<Self>) -> Result<Self::Output> {478 self.obj.get_or_bail(self.key)479 }480 }481482 Thunk::new(ThunkGet {483 obj: self.clone(),484 key,485 })486 }487 pub fn ptr_eq(a: &Self, b: &Self) -> bool {488 Cc::ptr_eq(&a.0, &b.0)489 }490 pub fn downgrade(self) -> WeakObjValue {491 WeakObjValue(self.0.downgrade())492 }493 fn fields_visibility(&self) -> FxHashMap<IStr, (bool, FieldSortKey)> {494 let mut out = FxHashMap::default();495 self.enum_fields(496 SuperDepth::default(),497 &mut |depth, index, name, visibility| {498 let new_sort_key = FieldSortKey::new(depth, index);499 let entry = out.entry(name);500 let (visible, _) = entry.or_insert((true, new_sort_key));501 match visibility {502 Visibility::Normal => {}503 Visibility::Hidden => {504 *visible = false;505 }506 Visibility::Unhide => {507 *visible = true;508 }509 };510 false511 },512 );513 out514 }515 pub fn fields_ex(516 &self,517 include_hidden: bool,518 #[cfg(feature = "exp-preserve-order")] preserve_order: bool,519 ) -> Vec<IStr> {520 #[cfg(feature = "exp-preserve-order")]521 if preserve_order {522 let (mut fields, mut keys): (Vec<_>, Vec<_>) = self523 .fields_visibility()524 .into_iter()525 .filter(|(_, (visible, _))| include_hidden || *visible)526 .enumerate()527 .map(|(idx, (k, (_, sk)))| (k, (sk, idx)))528 .unzip();529 keys.sort_unstable_by_key(|v| v.0);530 // Reorder in-place by resulting indexes531 for i in 0..fields.len() {532 let x = fields[i].clone();533 let mut j = i;534 loop {535 let k = keys[j].1;536 keys[j].1 = j;537 if k == i {538 break;539 }540 fields[j] = fields[k].clone();541 j = k;542 }543 fields[j] = x;544 }545 return fields;546 }547548 let mut fields: Vec<_> = self549 .fields_visibility()550 .into_iter()551 .filter(|(_, (visible, _))| include_hidden || *visible)552 .map(|(k, _)| k)553 .collect();554 fields.sort_unstable();555 fields556 }557 pub fn fields(&self, #[cfg(feature = "exp-preserve-order")] preserve_order: bool) -> Vec<IStr> {558 self.fields_ex(559 false,560 #[cfg(feature = "exp-preserve-order")]561 preserve_order,562 )563 }564 pub fn values_ex(565 &self,566 include_hidden: bool,567 #[cfg(feature = "exp-preserve-order")] preserve_order: bool,568 ) -> ArrValue {569 ArrValue::new(PickObjectValues::new(570 self.clone(),571 self.fields_ex(572 include_hidden,573 #[cfg(feature = "exp-preserve-order")]574 preserve_order,575 ),576 ))577 }578 pub fn values(&self, #[cfg(feature = "exp-preserve-order")] preserve_order: bool) -> ArrValue {579 self.values_ex(580 false,581 #[cfg(feature = "exp-preserve-order")]582 preserve_order,583 )584 }585 pub fn key_values_ex(586 &self,587 include_hidden: bool,588 #[cfg(feature = "exp-preserve-order")] preserve_order: bool,589 ) -> ArrValue {590 ArrValue::new(PickObjectKeyValues::new(591 self.clone(),592 self.fields_ex(593 include_hidden,594 #[cfg(feature = "exp-preserve-order")]595 preserve_order,596 ),597 ))598 }599 pub fn key_values(600 &self,601 #[cfg(feature = "exp-preserve-order")] preserve_order: bool,602 ) -> ArrValue {603 self.key_values_ex(604 false,605 #[cfg(feature = "exp-preserve-order")]606 preserve_order,607 )608 }609}610611impl OopObject {612 pub fn new(613 sup: Option<ObjValue>,614 this_entries: Cc<GcHashMap<IStr, ObjMember>>,615 assertions: Cc<Vec<TraceBox<dyn ObjectAssertion>>>,616 ) -> Self {617 Self {618 sup,619 // this: None,620 assertions,621 assertions_ran: RefCell::new(GcHashSet::new()),622 this_entries,623 value_cache: RefCell::new(GcHashMap::new()),624 }625 }626627 fn evaluate_this(&self, v: &ObjMember, real_this: ObjValue) -> Result<Val> {628 v.invoke.evaluate(self.sup.clone(), Some(real_this))629 }630631 // FIXME: Duplication between ObjValue and OopObject632 fn fields_visibility(&self) -> FxHashMap<IStr, (bool, FieldSortKey)> {633 let mut out = FxHashMap::default();634 self.enum_fields(635 SuperDepth::default(),636 &mut |depth, index, name, visibility| {637 let new_sort_key = FieldSortKey::new(depth, index);638 let entry = out.entry(name);639 let (visible, _) = entry.or_insert((true, new_sort_key));640 match visibility {641 Visibility::Normal => {}642 Visibility::Hidden => {643 *visible = false;644 }645 Visibility::Unhide => {646 *visible = true;647 }648 };649 false650 },651 );652 out653 }654}655656impl ObjectLike for OopObject {657 fn extend_from(&self, sup: ObjValue) -> ObjValue {658 ObjValue::new(match &self.sup {659 None => Self::new(660 Some(sup),661 self.this_entries.clone(),662 self.assertions.clone(),663 ),664 Some(v) => Self::new(665 Some(v.extend_from(sup)),666 self.this_entries.clone(),667 self.assertions.clone(),668 ),669 })670 }671672 fn len(&self) -> usize {673 // Maybe it will be better to not compute sort key here?674 self.fields_visibility()675 .into_iter()676 .filter(|(_, (visible, _))| *visible)677 .count()678 }679680 /// Returns false only if there is any visible entry.681 ///682 /// Note that object with hidden fields `{a:: 1}` will be reported as empty here.683 fn is_empty(&self) -> bool {684 self.len() == 0685 }686687 /// Run callback for every field found in object688 ///689 /// Returns true if ended prematurely690 fn enum_fields(&self, depth: SuperDepth, handler: &mut EnumFieldsHandler<'_>) -> bool {691 if let Some(s) = &self.sup {692 if s.enum_fields(depth.deeper(), handler) {693 return true;694 }695 }696 for (name, member) in self.this_entries.iter() {697 if handler(698 depth,699 member.original_index,700 name.clone(),701 member.flags.visibility(),702 ) {703 return true;704 }705 }706 false707 }708709 fn has_field_include_hidden(&self, name: IStr) -> bool {710 if self.this_entries.contains_key(&name) {711 true712 } else if let Some(super_obj) = &self.sup {713 super_obj.has_field_include_hidden(name)714 } else {715 false716 }717 }718 fn has_field(&self, name: IStr) -> bool {719 self.field_visibility(name)720 .map_or(false, |v| v.is_visible())721 }722723 fn get_for(&self, key: IStr, this: ObjValue) -> Result<Option<Val>> {724 let cache_key = (key.clone(), Some(this.clone().downgrade()));725 if let Some(v) = self.value_cache.borrow().get(&cache_key) {726 return Ok(match v {727 CacheValue::Cached(v) => Some(v.clone()),728 CacheValue::NotFound => None,729 CacheValue::Pending => bail!(InfiniteRecursionDetected),730 CacheValue::Errored(e) => return Err(e.clone()),731 });732 }733 self.value_cache734 .borrow_mut()735 .insert(cache_key.clone(), CacheValue::Pending);736 let value = self.get_for_uncached(key, this).map_err(|e| {737 self.value_cache738 .borrow_mut()739 .insert(cache_key.clone(), CacheValue::Errored(e.clone()));740 e741 })?;742 self.value_cache.borrow_mut().insert(743 cache_key,744 value745 .as_ref()746 .map_or(CacheValue::NotFound, |v| CacheValue::Cached(v.clone())),747 );748 Ok(value)749 }750 fn get_for_uncached(&self, key: IStr, real_this: ObjValue) -> Result<Option<Val>> {751 match (self.this_entries.get(&key), &self.sup) {752 (Some(k), None) => Ok(Some(self.evaluate_this(k, real_this)?)),753 (Some(k), Some(super_obj)) => {754 let our = self.evaluate_this(k, real_this.clone())?;755 if k.flags.add() {756 super_obj757 .get_raw(key, real_this)?758 .map_or(Ok(Some(our.clone())), |v| {759 Ok(Some(evaluate_add_op(&v, &our)?))760 })761 } else {762 Ok(Some(our))763 }764 }765 (None, Some(super_obj)) => super_obj.get_raw(key, real_this),766 (None, None) => Ok(None),767 }768 }769 fn field_visibility(&self, name: IStr) -> Option<Visibility> {770 if let Some(m) = self.this_entries.get(&name) {771 Some(match &m.flags.visibility() {772 Visibility::Normal => self773 .sup774 .as_ref()775 .and_then(|super_obj| super_obj.field_visibility(name))776 .unwrap_or(Visibility::Normal),777 v => *v,778 })779 } else if let Some(super_obj) = &self.sup {780 super_obj.field_visibility(name)781 } else {782 None783 }784 }785786 fn run_assertions_raw(&self, real_this: ObjValue) -> Result<()> {787 if self.assertions.is_empty() {788 if let Some(super_obj) = &self.sup {789 super_obj.run_assertions_raw(real_this)?;790 }791 return Ok(());792 }793 if self.assertions_ran.borrow_mut().insert(real_this.clone()) {794 for assertion in self.assertions.iter() {795 if let Err(e) = assertion.run(self.sup.clone(), Some(real_this.clone())) {796 self.assertions_ran.borrow_mut().remove(&real_this);797 return Err(e);798 }799 }800 if let Some(super_obj) = &self.sup {801 super_obj.run_assertions_raw(real_this)?;802 }803 }804 Ok(())805 }806}807808impl PartialEq for ObjValue {809 fn eq(&self, other: &Self) -> bool {810 Cc::ptr_eq(&self.0, &other.0)811 }812}813814impl Eq for ObjValue {}815impl Hash for ObjValue {816 fn hash<H: Hasher>(&self, hasher: &mut H) {817 hasher.write_usize(addr_of!(*self.0) as usize);818 }819}820821#[allow(clippy::module_name_repetitions)]822pub struct ObjValueBuilder {823 sup: Option<ObjValue>,824 map: GcHashMap<IStr, ObjMember>,825 assertions: Vec<TraceBox<dyn ObjectAssertion>>,826 next_field_index: FieldIndex,827}828impl ObjValueBuilder {829 pub fn new() -> Self {830 Self::with_capacity(0)831 }832 pub fn with_capacity(capacity: usize) -> Self {833 Self {834 sup: None,835 map: GcHashMap::with_capacity(capacity),836 assertions: Vec::new(),837 next_field_index: FieldIndex::default(),838 }839 }840 pub fn reserve_asserts(&mut self, capacity: usize) -> &mut Self {841 self.assertions.reserve_exact(capacity);842 self843 }844 pub fn with_super(&mut self, super_obj: ObjValue) -> &mut Self {845 self.sup = Some(super_obj);846 self847 }848849 pub fn assert(&mut self, assertion: impl ObjectAssertion + 'static) -> &mut Self {850 self.assertions.push(tb!(assertion));851 self852 }853 pub fn field(&mut self, name: impl Into<IStr>) -> ObjMemberBuilder<ValueBuilder<'_>> {854 let field_index = self.next_field_index;855 self.next_field_index = self.next_field_index.next();856 ObjMemberBuilder::new(ValueBuilder(self), name.into(), field_index)857 }858 /// Preset for common method definiton pattern:859 /// Create a hidden field with the function value.860 ///861 /// `.field(name).hide().value(Val::function(value))`862 pub fn method(&mut self, name: impl Into<IStr>, value: impl Into<FuncVal>) -> &mut Self {863 self.field(name).hide().value(Val::Func(value.into()));864 self865 }866 pub fn try_method(867 &mut self,868 name: impl Into<IStr>,869 value: impl Into<FuncVal>,870 ) -> Result<&mut Self> {871 self.field(name).hide().try_value(Val::Func(value.into()))?;872 Ok(self)873 }874875 pub fn build(self) -> ObjValue {876 if self.sup.is_none() && self.map.is_empty() && self.assertions.is_empty() {877 return ObjValue::new_empty();878 }879 ObjValue::new(OopObject::new(880 self.sup,881 Cc::new(self.map),882 Cc::new(self.assertions),883 ))884 }885}886impl Default for ObjValueBuilder {887 fn default() -> Self {888 Self::with_capacity(0)889 }890}891892#[allow(clippy::module_name_repetitions)]893#[must_use = "value not added unless binding() was called"]894pub struct ObjMemberBuilder<Kind> {895 kind: Kind,896 name: IStr,897 add: bool,898 visibility: Visibility,899 original_index: FieldIndex,900 location: Option<Span>,901}902903#[allow(clippy::missing_const_for_fn)]904impl<Kind> ObjMemberBuilder<Kind> {905 pub(crate) fn new(kind: Kind, name: IStr, original_index: FieldIndex) -> Self {906 Self {907 kind,908 name,909 original_index,910 add: false,911 visibility: Visibility::Normal,912 location: None,913 }914 }915916 pub const fn with_add(mut self, add: bool) -> Self {917 self.add = add;918 self919 }920 pub fn add(self) -> Self {921 self.with_add(true)922 }923 pub fn with_visibility(mut self, visibility: Visibility) -> Self {924 self.visibility = visibility;925 self926 }927 pub fn hide(self) -> Self {928 self.with_visibility(Visibility::Hidden)929 }930 pub fn with_location(mut self, location: Span) -> Self {931 self.location = Some(location);932 self933 }934 fn build_member(self, binding: MaybeUnbound) -> (Kind, IStr, ObjMember) {935 (936 self.kind,937 self.name,938 ObjMember {939 flags: ObjFieldFlags::new(self.add, self.visibility),940 original_index: self.original_index,941 invoke: binding,942 location: self.location,943 },944 )945 }946}947948pub struct ValueBuilder<'v>(&'v mut ObjValueBuilder);949impl ObjMemberBuilder<ValueBuilder<'_>> {950 /// Inserts value, replacing if it is already defined951 pub fn value(self, value: impl Into<Val>) {952 let (receiver, name, member) =953 self.build_member(MaybeUnbound::Bound(Thunk::evaluated(value.into())));954 let entry = receiver.0.map.entry(name);955 entry.insert(member);956 }957958 /// Tries to insert value, returns an error if it was already defined959 pub fn try_value(self, value: impl Into<Val>) -> Result<()> {960 self.thunk(Thunk::evaluated(value.into()))961 }962 pub fn thunk(self, value: impl Into<Thunk<Val>>) -> Result<()> {963 self.binding(MaybeUnbound::Bound(value.into()))964 }965 pub fn bindable(self, bindable: impl Unbound<Bound = Val>) -> Result<()> {966 self.binding(MaybeUnbound::Unbound(Cc::new(tb!(bindable))))967 }968 pub fn binding(self, binding: MaybeUnbound) -> Result<()> {969 let (receiver, name, member) = self.build_member(binding);970 let location = member.location.clone();971 let old = receiver.0.map.insert(name.clone(), member);972 if old.is_some() {973 in_frame(974 CallLocation(location.as_ref()),975 || format!("field <{}> initializtion", name.clone()),976 || bail!(DuplicateFieldName(name.clone())),977 )?;978 }979 Ok(())980 }981}982983pub struct ExtendBuilder<'v>(&'v mut ObjValue);984impl ObjMemberBuilder<ExtendBuilder<'_>> {985 pub fn value(self, value: impl Into<Val>) {986 self.binding(MaybeUnbound::Bound(Thunk::evaluated(value.into())));987 }988 pub fn bindable(self, bindable: TraceBox<dyn Unbound<Bound = Val>>) {989 self.binding(MaybeUnbound::Unbound(Cc::new(bindable)));990 }991 pub fn binding(self, binding: MaybeUnbound) {992 let (receiver, name, member) = self.build_member(binding);993 let new = receiver.0.clone();994 *receiver.0 = new.extend_with_raw_member(name, member);995 }996}crates/jrsonnet-evaluator/src/stdlib/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/stdlib/mod.rs
+++ b/crates/jrsonnet-evaluator/src/stdlib/mod.rs
@@ -3,12 +3,12 @@
use format::{format_arr, format_obj};
-use crate::{function::CallLocation, Result, State, Val};
+use crate::{function::CallLocation, in_frame, Result, Val};
pub mod format;
pub fn std_format(str: &str, vals: Val) -> Result<String> {
- State::push(
+ in_frame(
CallLocation::native(),
|| format!("std.format of {str}"),
|| {
crates/jrsonnet-evaluator/src/tla.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/tla.rs
+++ b/crates/jrsonnet-evaluator/src/tla.rs
@@ -3,12 +3,12 @@
use crate::{
function::{ArgsLike, CallLocation},
- Result, State, Val,
+ in_description_frame, Result, State, Val,
};
pub fn apply_tla<A: ArgsLike>(s: State, args: &A, val: Val) -> Result<Val> {
Ok(if let Val::Func(func) = val {
- State::push_description(
+ in_description_frame(
|| "during TLA call".to_owned(),
|| {
func.evaluate(
crates/jrsonnet-evaluator/src/typed/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/typed/mod.rs
+++ b/crates/jrsonnet-evaluator/src/typed/mod.rs
@@ -8,7 +8,7 @@
use crate::{
error::{Error, ErrorKind, Result},
- State, Val,
+ in_description_frame, Val,
};
#[derive(Debug, Error, Clone, Trace)]
@@ -89,7 +89,7 @@
path: impl Fn() -> ValuePathItem,
item: impl Fn() -> Result<()>,
) -> Result<()> {
- State::push_description(error_reason, || match item() {
+ in_description_frame(error_reason, || match item() {
Ok(()) => Ok(()),
Err(mut e) => {
if let ErrorKind::TypeError(e) = &mut e.error_mut() {
crates/jrsonnet-interner/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-interner/src/lib.rs
+++ b/crates/jrsonnet-interner/src/lib.rs
@@ -235,6 +235,7 @@
use crate::{PoolMap, POOL};
+ /// Type-erased interned string pool
pub enum PoolState {}
/// Dump current interned string pool, to be restored by
crates/jrsonnet-macros/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-macros/src/lib.rs
+++ b/crates/jrsonnet-macros/src/lib.rs
@@ -290,7 +290,7 @@
cfg_attrs,
} => {
let name = name.as_ref().map_or("<unnamed>", String::as_str);
- let eval = quote! {jrsonnet_evaluator::State::push_description(
+ let eval = quote! {jrsonnet_evaluator::in_description_frame(
|| format!("argument <{}> evaluation", #name),
|| <#ty>::from_untyped(value.evaluate()?),
)?};
crates/jrsonnet-stdlib/src/manifest/toml.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/manifest/toml.rs
+++ b/crates/jrsonnet-stdlib/src/manifest/toml.rs
@@ -1,10 +1,10 @@
use std::borrow::Cow;
use jrsonnet_evaluator::{
- bail,
+ bail, in_description_frame,
manifest::{escape_string_json_buf, ManifestFormat},
val::ArrValue,
- IStr, ObjValue, Result, ResultExt, State, Val,
+ IStr, ObjValue, Result, ResultExt, Val,
};
pub struct TomlFormat<'s> {
@@ -124,7 +124,7 @@
buf.push_str(&options.padding);
}
- State::push_description(
+ in_description_frame(
|| format!("elem <{i}> manifestification"),
|| manifest_value(&e, true, buf, "", options),
)?;
@@ -161,7 +161,7 @@
escape_key_toml_buf(&k, buf);
buf.push_str(" = ");
- State::push_description(
+ in_description_frame(
|| format!("field <{k}> manifestification"),
|| manifest_value(&v, true, buf, "", options),
)?;
crates/jrsonnet-stdlib/src/manifest/xml.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/manifest/xml.rs
+++ b/crates/jrsonnet-stdlib/src/manifest/xml.rs
@@ -1,9 +1,9 @@
use jrsonnet_evaluator::{
- bail,
+ bail, in_description_frame,
manifest::{ManifestFormat, ToStringFormat},
typed::{ComplexValType, Either2, Typed, ValType},
val::ArrValue,
- Either, ObjValue, Result, ResultExt, State, Val,
+ Either, ObjValue, Result, ResultExt, Val,
};
pub struct XmlJsonmlFormat {
@@ -70,7 +70,7 @@
Ok(Self::Tag {
tag,
attrs,
- children: State::push_description(
+ children: in_description_frame(
|| "parsing children".to_owned(),
|| {
Typed::from_untyped(Val::Arr(arr.slice(
crates/jrsonnet-stdlib/src/manifest/yaml.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/manifest/yaml.rs
+++ b/crates/jrsonnet-stdlib/src/manifest/yaml.rs
@@ -1,9 +1,9 @@
use std::{borrow::Cow, fmt::Write};
use jrsonnet_evaluator::{
- bail,
+ bail, in_description_frame,
manifest::{escape_string_json_buf, ManifestFormat},
- Result, ResultExt, State, Val,
+ Result, ResultExt, Val,
};
pub struct YamlFormat<'s> {
@@ -178,7 +178,7 @@
if extra_padding {
cur_padding.push_str(&options.padding);
}
- State::push_description(
+ in_description_frame(
|| format!("elem <{i}> manifestification"),
|| manifest_yaml_ex_buf(&item, buf, cur_padding, options),
)?;
@@ -225,7 +225,7 @@
}
_ => buf.push(' '),
}
- State::push_description(
+ in_description_frame(
|| format!("field <{key}> manifestification"),
|| manifest_yaml_ex_buf(&value, buf, cur_padding, options),
)?;