difftreelog
feat OOP-aware objectRemoveKey
in: master
17 files changed
bindings/jsonnet/src/val_make.rsdiffbeforeafterboth--- a/bindings/jsonnet/src/val_make.rs
+++ b/bindings/jsonnet/src/val_make.rs
@@ -56,5 +56,5 @@
/// Make a `JsonnetJsonValue` representing an object.
#[no_mangle]
pub extern "C" fn jsonnet_json_make_object(_vm: &VM) -> *mut Val {
- Box::into_raw(Box::new(Val::Obj(ObjValue::new_empty())))
+ Box::into_raw(Box::new(Val::Obj(ObjValue::empty())))
}
crates/jrsonnet-cli/src/tla.rsdiffbeforeafterboth--- a/crates/jrsonnet-cli/src/tla.rs
+++ b/crates/jrsonnet-cli/src/tla.rs
@@ -1,5 +1,7 @@
use clap::Parser;
-use jrsonnet_evaluator::{IStr, error::Result, function::TlaArg, gc::WithCapacityExt as _, rustc_hash::FxHashMap};
+use jrsonnet_evaluator::{
+ error::Result, function::TlaArg, gc::WithCapacityExt as _, rustc_hash::FxHashMap, IStr,
+};
use crate::{ExtFile, ExtStr};
crates/jrsonnet-evaluator/src/dynamic.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/dynamic.rs
+++ b/crates/jrsonnet-evaluator/src/dynamic.rs
@@ -1,5 +1,4 @@
-use std::ptr::addr_of;
-use std::{cell::OnceCell, hash::Hasher};
+use std::{cell::OnceCell, hash::Hasher, ptr::addr_of};
use educe::Educe;
use jrsonnet_gcmodule::{Cc, Trace};
crates/jrsonnet-evaluator/src/evaluate/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/evaluate/mod.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/mod.rs
@@ -11,7 +11,18 @@
use self::destructure::destruct;
use crate::{
- Context, Error, ObjValue, ObjValueBuilder, ObjectAssertion, Pending, Result, ResultExt, SupThis, Unbound, Val, arr::ArrValue, bail, destructure::evaluate_dest, error::{ErrorKind::*, suggest_object_fields}, evaluate::operator::{evaluate_add_op, evaluate_binary_op_special, evaluate_unary_op}, function::{CallLocation, FuncDesc, FuncVal}, gc::WithCapacityExt as _, in_frame, typed::Typed, val::{CachedUnbound, IndexableVal, NumValue, StrValue, Thunk}, with_state
+ arr::ArrValue,
+ bail,
+ destructure::evaluate_dest,
+ error::{suggest_object_fields, ErrorKind::*},
+ evaluate::operator::{evaluate_add_op, evaluate_binary_op_special, evaluate_unary_op},
+ function::{CallLocation, FuncDesc, FuncVal},
+ gc::WithCapacityExt as _,
+ in_frame,
+ typed::Typed,
+ val::{CachedUnbound, IndexableVal, NumValue, StrValue, Thunk},
+ with_state, Context, Error, ObjValue, ObjValueBuilder, ObjectAssertion, Pending, Result,
+ ResultExt, SupThis, Unbound, Val,
};
pub mod destructure;
pub mod operator;
@@ -137,10 +148,7 @@
)),
])));
destruct(var, value, fctx.clone(), &mut new_bindings)?;
- let ctx = ctx
- .clone()
- .extend(new_bindings, None, None, None)
- .into_future(fctx);
+ let ctx = ctx.clone().extend_bindings(new_bindings).into_future(fctx);
evaluate_comp(ctx, &specs[1..], callback)?;
}
crates/jrsonnet-evaluator/src/lib.rsdiffbeforeafterboth1//! jsonnet interpreter implementation2#![cfg_attr(nightly, feature(thread_local, type_alias_impl_trait))]34// For jrsonnet-macros5extern crate self as jrsonnet_evaluator;67mod arr;8pub mod async_import;9mod ctx;10mod dynamic;11pub mod error;12mod evaluate;13pub mod function;14pub mod gc;15mod import;16mod integrations;17pub mod manifest;18mod map;19mod obj;20pub mod stack;21pub mod stdlib;22mod tla;23pub mod trace;24pub mod typed;25pub mod val;2627use std::{28 any::Any,29 cell::{RefCell, RefMut},30 collections::hash_map::Entry,31 clone::Clone,32 fmt::{self, Debug},33 rc::Rc,34 marker::PhantomData,35};3637pub use ctx::*;38pub use dynamic::*;39pub use error::{Error, ErrorKind::*, Result, ResultExt};40pub use evaluate::*;41use function::CallLocation;42pub use import::*;43use jrsonnet_gcmodule::{cc_dyn, Cc, Trace};44pub use jrsonnet_interner::{IBytes, IStr};45#[doc(hidden)]46pub use jrsonnet_macros;47pub use jrsonnet_parser as parser;48use jrsonnet_parser::{LocExpr, ParserSettings, Source, SourcePath};49pub use obj::*;50pub use rustc_hash;51use rustc_hash::FxHashMap;52use stack::check_depth;53pub use tla::apply_tla;54pub use val::{Thunk, Val};5556use crate::gc::WithCapacityExt as _;5758cc_dyn!(59 #[derive(Clone)]60 CcUnbound<V>,61 Unbound<Bound = V>62);6364/// Thunk without bound `super`/`this`65/// object inheritance may be overriden multiple times, and will be fixed only on field read66pub trait Unbound: Trace {67 /// Type of value after object context is bound68 type Bound;69 /// Create value bound to specified object context70 fn bind(&self, sup_this: SupThis) -> Result<Self::Bound>;71}7273/// Object fields may, or may not depend on `this`/`super`, this enum allows cheaper reuse of object-independent fields for native code74/// Standard jsonnet fields are always unbound75#[derive(Clone, Trace)]76pub enum MaybeUnbound {77 /// Value needs to be bound to `this`/`super`78 Unbound(CcUnbound<Val>),79 /// Value is object-independent80 Bound(Thunk<Val>),81}8283impl Debug for MaybeUnbound {84 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {85 write!(f, "MaybeUnbound")86 }87}88impl MaybeUnbound {89 /// Attach object context to value, if required90 pub fn evaluate(&self, sup_this: SupThis) -> Result<Val> {91 match self {92 Self::Unbound(v) => v.0.bind(sup_this),93 Self::Bound(v) => Ok(v.evaluate()?),94 }95 }96}9798cc_dyn!(CcContextInitializer, ContextInitializer);99100/// During import, this trait will be called to create initial context for file.101/// It may initialize global variables, stdlib for example.102pub trait ContextInitializer: Trace {103 /// For which size the builder should be preallocated104 fn reserve_vars(&self) -> usize {105 0106 }107 /// Initialize default file context.108 /// Has default implementation, which calls `populate`.109 /// Prefer to always implement `populate` instead.110 fn initialize(&self, for_file: Source) -> Context {111 let mut builder = ContextBuilder::with_capacity(self.reserve_vars());112 self.populate(for_file, &mut builder);113 builder.build()114 }115 /// For composability: extend builder. May panic if this initialization is not supported,116 /// and the context may only be created via `initialize`.117 fn populate(&self, for_file: Source, builder: &mut ContextBuilder);118 /// Allows upcasting from abstract to concrete context initializer.119 /// jrsonnet by itself doesn't use this method, it is allowed for it to panic.120 fn as_any(&self) -> &dyn Any;121}122123/// Context initializer which adds nothing.124impl ContextInitializer for () {125 fn populate(&self, _for_file: Source, _builder: &mut ContextBuilder) {}126 fn as_any(&self) -> &dyn Any {127 self128 }129}130131impl<T> ContextInitializer for Option<T>132where133 T: ContextInitializer,134{135 fn initialize(&self, for_file: Source) -> Context {136 if let Some(ctx) = self {137 ctx.initialize(for_file)138 } else {139 ().initialize(for_file)140 }141 }142143 fn populate(&self, for_file: Source, builder: &mut ContextBuilder) {144 if let Some(ctx) = self {145 ctx.populate(for_file, builder);146 }147 }148149 fn as_any(&self) -> &dyn Any {150 self151 }152}153154macro_rules! impl_context_initializer {155 ($($gen:ident)*) => {156 #[allow(non_snake_case)]157 impl<$($gen: ContextInitializer + Trace,)*> ContextInitializer for ($($gen,)*) {158 fn reserve_vars(&self) -> usize {159 let mut out = 0;160 let ($($gen,)*) = self;161 $(out += $gen.reserve_vars();)*162 out163 }164 fn populate(&self, for_file: Source, builder: &mut ContextBuilder) {165 let ($($gen,)*) = self;166 $($gen.populate(for_file.clone(), builder);)*167 }168 fn as_any(&self) -> &dyn Any {169 self170 }171 }172 };173 ($($cur:ident)* @ $c:ident $($rest:ident)*) => {174 impl_context_initializer!($($cur)*);175 impl_context_initializer!($($cur)* $c @ $($rest)*);176 };177 ($($cur:ident)* @) => {178 impl_context_initializer!($($cur)*);179 }180}181impl_context_initializer! {182 A @ B C D E F G183}184185#[derive(Trace)]186struct FileData {187 string: Option<IStr>,188 bytes: Option<IBytes>,189 parsed: Option<LocExpr>,190 evaluated: Option<Val>,191192 evaluating: bool,193}194impl FileData {195 fn new_string(data: IStr) -> Self {196 Self {197 string: Some(data),198 bytes: None,199 parsed: None,200 evaluated: None,201 evaluating: false,202 }203 }204 fn new_bytes(data: IBytes) -> Self {205 Self {206 string: None,207 bytes: Some(data),208 parsed: None,209 evaluated: None,210 evaluating: false,211 }212 }213 pub(crate) fn get_string(&mut self) -> Option<IStr> {214 if self.string.is_none() {215 self.string = Some(216 self.bytes217 .as_ref()218 .expect("either string or bytes should be set")219 .clone()220 .cast_str()?,221 );222 }223 Some(self.string.clone().expect("just set"))224 }225}226227#[derive(Trace)]228pub struct EvaluationStateInternals {229 /// Internal state230 file_cache: RefCell<FxHashMap<SourcePath, FileData>>,231 /// Context initializer, which will be used for imports and everything232 /// [`NoopContextInitializer`] is used by default, most likely you want to have `jrsonnet-stdlib`233 context_initializer: CcContextInitializer,234 /// Used to resolve file locations/contents235 import_resolver: Rc<dyn ImportResolver>,236}237238/// Maintains stack trace and import resolution239#[derive(Clone, Trace)]240pub struct State(Cc<EvaluationStateInternals>);241242thread_local! {243 pub static DEFAULT_STATE: State = State::builder().build();244 pub static STATE: RefCell<Option<State>> = const {RefCell::new(None)};245}246pub struct StateEnterGuard(PhantomData<()>);247impl Drop for StateEnterGuard {248 fn drop(&mut self) {249 STATE.with_borrow_mut(|v| *v = None);250 }251}252253pub fn with_state<V>(v: impl FnOnce(State) -> V) -> V {254 if let Some(state) = STATE.with_borrow(Clone::clone) {255 v(state)256 } else {257 let s = DEFAULT_STATE.with(Clone::clone);258 v(s)259 }260}261262impl State {263 pub fn enter(&self) -> StateEnterGuard {264 self.try_enter().expect("entered state already exists")265 }266 pub fn try_enter(&self) -> Option<StateEnterGuard> {267 STATE.with_borrow_mut(|v| {268 if v.is_none() {269 *v = Some(self.clone());270 Some(StateEnterGuard(PhantomData))271 } else {272 None273 }274 })275 }276 /// Should only be called with path retrieved from [`resolve_path`], may panic otherwise277 pub fn import_resolved_str(&self, path: SourcePath) -> Result<IStr> {278 let mut file_cache = self.file_cache();279 let mut file = file_cache.entry(path.clone());280281 let file = match file {282 Entry::Occupied(ref mut d) => d.get_mut(),283 Entry::Vacant(v) => {284 let data = self.import_resolver().load_file_contents(&path)?;285 v.insert(FileData::new_string(286 std::str::from_utf8(&data)287 .map_err(|_| ImportBadFileUtf8(path.clone()))?288 .into(),289 ))290 }291 };292 Ok(file293 .get_string()294 .ok_or_else(|| ImportBadFileUtf8(path.clone()))?)295 }296 /// Should only be called with path retrieved from [`resolve_path`], may panic otherwise297 pub fn import_resolved_bin(&self, path: SourcePath) -> Result<IBytes> {298 let mut file_cache = self.file_cache();299 let mut file = file_cache.entry(path.clone());300301 let file = match file {302 Entry::Occupied(ref mut d) => d.get_mut(),303 Entry::Vacant(v) => {304 let data = self.import_resolver().load_file_contents(&path)?;305 v.insert(FileData::new_bytes(data.as_slice().into()))306 }307 };308 if let Some(str) = &file.bytes {309 return Ok(str.clone());310 }311 if file.bytes.is_none() {312 file.bytes = Some(313 file.string314 .as_ref()315 .expect("either string or bytes should be set")316 .clone()317 .cast_bytes(),318 );319 }320 Ok(file.bytes.as_ref().expect("just set").clone())321 }322 /// Should only be called with path retrieved from [`resolve_path`], may panic otherwise323 pub fn import_resolved(&self, path: SourcePath) -> Result<Val> {324 let mut file_cache = self.file_cache();325 let mut file = file_cache.entry(path.clone());326327 let file = match file {328 Entry::Occupied(ref mut d) => d.get_mut(),329 Entry::Vacant(v) => {330 let data = self.import_resolver().load_file_contents(&path)?;331 v.insert(FileData::new_string(332 std::str::from_utf8(&data)333 .map_err(|_| ImportBadFileUtf8(path.clone()))?334 .into(),335 ))336 }337 };338 if let Some(val) = &file.evaluated {339 return Ok(val.clone());340 }341 let code = file342 .get_string()343 .ok_or_else(|| ImportBadFileUtf8(path.clone()))?;344 let file_name = Source::new(path.clone(), code.clone());345 if file.parsed.is_none() {346 file.parsed = Some(347 jrsonnet_parser::parse(348 &code,349 &ParserSettings {350 source: file_name.clone(),351 },352 )353 .map_err(|e| ImportSyntaxError {354 path: file_name.clone(),355 error: Box::new(e),356 })?,357 );358 }359 let parsed = file.parsed.as_ref().expect("just set").clone();360 if file.evaluating {361 bail!(InfiniteRecursionDetected)362 }363 file.evaluating = true;364 // Dropping file cache guard here, as evaluation may use this map too365 drop(file_cache);366 let res = evaluate(self.create_default_context(file_name), &parsed);367368 let mut file_cache = self.file_cache();369 let mut file = file_cache.entry(path.clone());370371 let Entry::Occupied(file) = &mut file else {372 unreachable!("this file was just here")373 };374 let file = file.get_mut();375 file.evaluating = false;376 match res {377 Ok(v) => {378 file.evaluated = Some(v.clone());379 Ok(v)380 }381 Err(e) => Err(e),382 }383 }384385 /// Has same semantics as `import 'path'` called from `from` file386 pub fn import_from(&self, from: &SourcePath, path: impl AsPathLike) -> Result<Val> {387 let resolved = self.resolve_from(from, &path)?;388 self.import_resolved(resolved)389 }390 pub fn import(&self, path: impl AsPathLike) -> Result<Val> {391 let resolved = self.resolve_from_default(&path)?;392 self.import_resolved(resolved)393 }394395 /// Creates context with all passed global variables396 pub fn create_default_context(&self, source: Source) -> Context {397 self.context_initializer().initialize(source)398 }399400 /// Creates context with all passed global variables, calling custom modifier401 pub fn create_default_context_with(402 &self,403 source: Source,404 context_initializer: impl ContextInitializer,405 ) -> Context {406 let default_initializer = self.context_initializer();407 let mut builder = ContextBuilder::with_capacity(408 default_initializer.reserve_vars() + context_initializer.reserve_vars(),409 );410 default_initializer.populate(source.clone(), &mut builder);411 context_initializer.populate(source, &mut builder);412413 builder.build()414 }415}416417/// Internals418impl State {419 fn file_cache(&self) -> RefMut<'_, FxHashMap<SourcePath, FileData>> {420 self.0.file_cache.borrow_mut()421 }422}423/// Executes code creating a new stack frame, to be replaced with try{}424pub fn in_frame<T>(425 e: CallLocation<'_>,426 frame_desc: impl FnOnce() -> String,427 f: impl FnOnce() -> Result<T>,428) -> Result<T> {429 let _guard = check_depth()?;430431 f().with_description_src(e, frame_desc)432}433434/// Executes code creating a new stack frame, to be replaced with try{}435pub fn in_description_frame<T>(436 frame_desc: impl FnOnce() -> String,437 f: impl FnOnce() -> Result<T>,438) -> Result<T> {439 let _guard = check_depth()?;440441 f().with_description(frame_desc)442}443444#[derive(Trace)]445pub struct InitialUnderscore(pub Thunk<Val>);446impl ContextInitializer for InitialUnderscore {447 fn populate(&self, _for_file: Source, builder: &mut ContextBuilder) {448 builder.bind("_", self.0.clone());449 }450451 fn as_any(&self) -> &dyn Any {452 self453 }454}455456/// Raw methods evaluate passed values but don't perform TLA execution457impl State {458 /// Parses and evaluates the given snippet459 pub fn evaluate_snippet(&self, name: impl Into<IStr>, code: impl Into<IStr>) -> Result<Val> {460 let code = code.into();461 let source = Source::new_virtual(name.into(), code.clone());462 let parsed = jrsonnet_parser::parse(463 &code,464 &ParserSettings {465 source: source.clone(),466 },467 )468 .map_err(|e| ImportSyntaxError {469 path: source.clone(),470 error: Box::new(e),471 })?;472 evaluate(self.create_default_context(source), &parsed)473 }474 /// Parses and evaluates the given snippet with custom context modifier475 pub fn evaluate_snippet_with(476 &self,477 name: impl Into<IStr>,478 code: impl Into<IStr>,479 context_initializer: impl ContextInitializer,480 ) -> Result<Val> {481 let code = code.into();482 let source = Source::new_virtual(name.into(), code.clone());483 let parsed = jrsonnet_parser::parse(484 &code,485 &ParserSettings {486 source: source.clone(),487 },488 )489 .map_err(|e| ImportSyntaxError {490 path: source.clone(),491 error: Box::new(e),492 })?;493 evaluate(494 self.create_default_context_with(source, context_initializer),495 &parsed,496 )497 }498}499500/// Settings utilities501impl State {502 // Only panics in case of [`ImportResolver`] contract violation503 #[allow(clippy::missing_panics_doc)]504 pub fn resolve_from(&self, from: &SourcePath, path: &dyn AsPathLike) -> Result<SourcePath> {505 self.import_resolver().resolve_from(from, path)506 }507 #[allow(clippy::missing_panics_doc)]508 pub fn resolve_from_default(&self, path: &dyn AsPathLike) -> Result<SourcePath> {509 self.import_resolver().resolve_from_default(path)510 }511 pub fn import_resolver(&self) -> &dyn ImportResolver {512 &*self.0.import_resolver513 }514 pub fn context_initializer(&self) -> &dyn ContextInitializer {515 &*self.0.context_initializer.0516 }517}518519impl State {520 pub fn builder() -> StateBuilder {521 StateBuilder::default()522 }523}524525impl Default for State {526 fn default() -> Self {527 Self::builder().build()528 }529}530531#[derive(Default)]532pub struct StateBuilder {533 import_resolver: Option<Rc<dyn ImportResolver>>,534 context_initializer: Option<CcContextInitializer>,535}536impl StateBuilder {537 pub fn import_resolver(&mut self, import_resolver: impl ImportResolver) -> &mut Self {538 let _ = self.import_resolver.insert(Rc::new(import_resolver));539 self540 }541 pub fn context_initializer(542 &mut self,543 context_initializer: impl ContextInitializer,544 ) -> &mut Self {545 let _ = self546 .context_initializer547 .insert(CcContextInitializer::new(context_initializer));548 self549 }550 pub fn build(mut self) -> State {551 State(Cc::new(EvaluationStateInternals {552 file_cache: RefCell::new(FxHashMap::new()),553 context_initializer: self554 .context_initializer555 .take()556 .unwrap_or_else(|| CcContextInitializer::new(())),557 import_resolver: self558 .import_resolver559 .take()560 .unwrap_or_else(|| Rc::new(DummyImportResolver)),561 }))562 }563}1//! jsonnet interpreter implementation2#![cfg_attr(nightly, feature(thread_local, type_alias_impl_trait))]34// For jrsonnet-macros5extern crate self as jrsonnet_evaluator;67mod arr;8pub mod async_import;9mod ctx;10mod dynamic;11pub mod error;12mod evaluate;13pub mod function;14pub mod gc;15mod import;16mod integrations;17pub mod manifest;18mod map;19mod obj;20pub mod stack;21pub mod stdlib;22mod tla;23pub mod trace;24pub mod typed;25pub mod val;2627use std::{28 any::Any,29 cell::{RefCell, RefMut},30 clone::Clone,31 collections::hash_map::Entry,32 fmt::{self, Debug},33 marker::PhantomData,34 rc::Rc,35};3637pub use ctx::*;38pub use dynamic::*;39pub use error::{Error, ErrorKind::*, Result, ResultExt};40pub use evaluate::*;41use function::CallLocation;42pub use import::*;43use jrsonnet_gcmodule::{cc_dyn, Cc, Trace};44pub use jrsonnet_interner::{IBytes, IStr};45#[doc(hidden)]46pub use jrsonnet_macros;47pub use jrsonnet_parser as parser;48use jrsonnet_parser::{LocExpr, ParserSettings, Source, SourcePath};49pub use obj::*;50pub use rustc_hash;51use rustc_hash::FxHashMap;52use stack::check_depth;53pub use tla::apply_tla;54pub use val::{Thunk, Val};5556use crate::gc::WithCapacityExt as _;5758cc_dyn!(59 #[derive(Clone)]60 CcUnbound<V>,61 Unbound<Bound = V>62);6364/// Thunk without bound `super`/`this`65/// object inheritance may be overriden multiple times, and will be fixed only on field read66pub trait Unbound: Trace {67 /// Type of value after object context is bound68 type Bound;69 /// Create value bound to specified object context70 fn bind(&self, sup_this: SupThis) -> Result<Self::Bound>;71}7273/// Object fields may, or may not depend on `this`/`super`, this enum allows cheaper reuse of object-independent fields for native code74/// Standard jsonnet fields are always unbound75#[derive(Clone, Trace)]76pub enum MaybeUnbound {77 /// Value needs to be bound to `this`/`super`78 Unbound(CcUnbound<Val>),79 /// Value is object-independent80 Bound(Thunk<Val>),81}8283impl Debug for MaybeUnbound {84 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {85 write!(f, "MaybeUnbound")86 }87}88impl MaybeUnbound {89 /// Attach object context to value, if required90 pub fn evaluate(&self, sup_this: SupThis) -> Result<Val> {91 match self {92 Self::Unbound(v) => v.0.bind(sup_this),93 Self::Bound(v) => Ok(v.evaluate()?),94 }95 }96}9798cc_dyn!(CcContextInitializer, ContextInitializer);99100/// During import, this trait will be called to create initial context for file.101/// It may initialize global variables, stdlib for example.102pub trait ContextInitializer: Trace {103 /// For which size the builder should be preallocated104 fn reserve_vars(&self) -> usize {105 0106 }107 /// Initialize default file context.108 /// Has default implementation, which calls `populate`.109 /// Prefer to always implement `populate` instead.110 fn initialize(&self, for_file: Source) -> Context {111 let mut builder = ContextBuilder::with_capacity(self.reserve_vars());112 self.populate(for_file, &mut builder);113 builder.build()114 }115 /// For composability: extend builder. May panic if this initialization is not supported,116 /// and the context may only be created via `initialize`.117 fn populate(&self, for_file: Source, builder: &mut ContextBuilder);118 /// Allows upcasting from abstract to concrete context initializer.119 /// jrsonnet by itself doesn't use this method, it is allowed for it to panic.120 fn as_any(&self) -> &dyn Any;121}122123/// Context initializer which adds nothing.124impl ContextInitializer for () {125 fn populate(&self, _for_file: Source, _builder: &mut ContextBuilder) {}126 fn as_any(&self) -> &dyn Any {127 self128 }129}130131impl<T> ContextInitializer for Option<T>132where133 T: ContextInitializer,134{135 fn initialize(&self, for_file: Source) -> Context {136 if let Some(ctx) = self {137 ctx.initialize(for_file)138 } else {139 ().initialize(for_file)140 }141 }142143 fn populate(&self, for_file: Source, builder: &mut ContextBuilder) {144 if let Some(ctx) = self {145 ctx.populate(for_file, builder);146 }147 }148149 fn as_any(&self) -> &dyn Any {150 self151 }152}153154macro_rules! impl_context_initializer {155 ($($gen:ident)*) => {156 #[allow(non_snake_case)]157 impl<$($gen: ContextInitializer + Trace,)*> ContextInitializer for ($($gen,)*) {158 fn reserve_vars(&self) -> usize {159 let mut out = 0;160 let ($($gen,)*) = self;161 $(out += $gen.reserve_vars();)*162 out163 }164 fn populate(&self, for_file: Source, builder: &mut ContextBuilder) {165 let ($($gen,)*) = self;166 $($gen.populate(for_file.clone(), builder);)*167 }168 fn as_any(&self) -> &dyn Any {169 self170 }171 }172 };173 ($($cur:ident)* @ $c:ident $($rest:ident)*) => {174 impl_context_initializer!($($cur)*);175 impl_context_initializer!($($cur)* $c @ $($rest)*);176 };177 ($($cur:ident)* @) => {178 impl_context_initializer!($($cur)*);179 }180}181impl_context_initializer! {182 A @ B C D E F G183}184185#[derive(Trace)]186struct FileData {187 string: Option<IStr>,188 bytes: Option<IBytes>,189 parsed: Option<LocExpr>,190 evaluated: Option<Val>,191192 evaluating: bool,193}194impl FileData {195 fn new_string(data: IStr) -> Self {196 Self {197 string: Some(data),198 bytes: None,199 parsed: None,200 evaluated: None,201 evaluating: false,202 }203 }204 fn new_bytes(data: IBytes) -> Self {205 Self {206 string: None,207 bytes: Some(data),208 parsed: None,209 evaluated: None,210 evaluating: false,211 }212 }213 pub(crate) fn get_string(&mut self) -> Option<IStr> {214 if self.string.is_none() {215 self.string = Some(216 self.bytes217 .as_ref()218 .expect("either string or bytes should be set")219 .clone()220 .cast_str()?,221 );222 }223 Some(self.string.clone().expect("just set"))224 }225}226227#[derive(Trace)]228pub struct EvaluationStateInternals {229 /// Internal state230 file_cache: RefCell<FxHashMap<SourcePath, FileData>>,231 /// Context initializer, which will be used for imports and everything232 /// [`NoopContextInitializer`] is used by default, most likely you want to have `jrsonnet-stdlib`233 context_initializer: CcContextInitializer,234 /// Used to resolve file locations/contents235 import_resolver: Rc<dyn ImportResolver>,236}237238/// Maintains stack trace and import resolution239#[derive(Clone, Trace)]240pub struct State(Cc<EvaluationStateInternals>);241242thread_local! {243 pub static DEFAULT_STATE: State = State::builder().build();244 pub static STATE: RefCell<Option<State>> = const {RefCell::new(None)};245}246pub struct StateEnterGuard(PhantomData<()>);247impl Drop for StateEnterGuard {248 fn drop(&mut self) {249 STATE.with_borrow_mut(|v| *v = None);250 }251}252253pub fn with_state<V>(v: impl FnOnce(State) -> V) -> V {254 if let Some(state) = STATE.with_borrow(Clone::clone) {255 v(state)256 } else {257 let s = DEFAULT_STATE.with(Clone::clone);258 v(s)259 }260}261262impl State {263 pub fn enter(&self) -> StateEnterGuard {264 self.try_enter().expect("entered state already exists")265 }266 pub fn try_enter(&self) -> Option<StateEnterGuard> {267 STATE.with_borrow_mut(|v| {268 if v.is_none() {269 *v = Some(self.clone());270 Some(StateEnterGuard(PhantomData))271 } else {272 None273 }274 })275 }276 /// Should only be called with path retrieved from [`resolve_path`], may panic otherwise277 pub fn import_resolved_str(&self, path: SourcePath) -> Result<IStr> {278 let mut file_cache = self.file_cache();279 let mut file = file_cache.entry(path.clone());280281 let file = match file {282 Entry::Occupied(ref mut d) => d.get_mut(),283 Entry::Vacant(v) => {284 let data = self.import_resolver().load_file_contents(&path)?;285 v.insert(FileData::new_string(286 std::str::from_utf8(&data)287 .map_err(|_| ImportBadFileUtf8(path.clone()))?288 .into(),289 ))290 }291 };292 Ok(file293 .get_string()294 .ok_or_else(|| ImportBadFileUtf8(path.clone()))?)295 }296 /// Should only be called with path retrieved from [`resolve_path`], may panic otherwise297 pub fn import_resolved_bin(&self, path: SourcePath) -> Result<IBytes> {298 let mut file_cache = self.file_cache();299 let mut file = file_cache.entry(path.clone());300301 let file = match file {302 Entry::Occupied(ref mut d) => d.get_mut(),303 Entry::Vacant(v) => {304 let data = self.import_resolver().load_file_contents(&path)?;305 v.insert(FileData::new_bytes(data.as_slice().into()))306 }307 };308 if let Some(str) = &file.bytes {309 return Ok(str.clone());310 }311 if file.bytes.is_none() {312 file.bytes = Some(313 file.string314 .as_ref()315 .expect("either string or bytes should be set")316 .clone()317 .cast_bytes(),318 );319 }320 Ok(file.bytes.as_ref().expect("just set").clone())321 }322 /// Should only be called with path retrieved from [`resolve_path`], may panic otherwise323 pub fn import_resolved(&self, path: SourcePath) -> Result<Val> {324 let mut file_cache = self.file_cache();325 let mut file = file_cache.entry(path.clone());326327 let file = match file {328 Entry::Occupied(ref mut d) => d.get_mut(),329 Entry::Vacant(v) => {330 let data = self.import_resolver().load_file_contents(&path)?;331 v.insert(FileData::new_string(332 std::str::from_utf8(&data)333 .map_err(|_| ImportBadFileUtf8(path.clone()))?334 .into(),335 ))336 }337 };338 if let Some(val) = &file.evaluated {339 return Ok(val.clone());340 }341 let code = file342 .get_string()343 .ok_or_else(|| ImportBadFileUtf8(path.clone()))?;344 let file_name = Source::new(path.clone(), code.clone());345 if file.parsed.is_none() {346 file.parsed = Some(347 jrsonnet_parser::parse(348 &code,349 &ParserSettings {350 source: file_name.clone(),351 },352 )353 .map_err(|e| ImportSyntaxError {354 path: file_name.clone(),355 error: Box::new(e),356 })?,357 );358 }359 let parsed = file.parsed.as_ref().expect("just set").clone();360 if file.evaluating {361 bail!(InfiniteRecursionDetected)362 }363 file.evaluating = true;364 // Dropping file cache guard here, as evaluation may use this map too365 drop(file_cache);366 let res = evaluate(self.create_default_context(file_name), &parsed);367368 let mut file_cache = self.file_cache();369 let mut file = file_cache.entry(path.clone());370371 let Entry::Occupied(file) = &mut file else {372 unreachable!("this file was just here")373 };374 let file = file.get_mut();375 file.evaluating = false;376 match res {377 Ok(v) => {378 file.evaluated = Some(v.clone());379 Ok(v)380 }381 Err(e) => Err(e),382 }383 }384385 /// Has same semantics as `import 'path'` called from `from` file386 pub fn import_from(&self, from: &SourcePath, path: impl AsPathLike) -> Result<Val> {387 let resolved = self.resolve_from(from, &path)?;388 self.import_resolved(resolved)389 }390 pub fn import(&self, path: impl AsPathLike) -> Result<Val> {391 let resolved = self.resolve_from_default(&path)?;392 self.import_resolved(resolved)393 }394395 /// Creates context with all passed global variables396 pub fn create_default_context(&self, source: Source) -> Context {397 self.context_initializer().initialize(source)398 }399400 /// Creates context with all passed global variables, calling custom modifier401 pub fn create_default_context_with(402 &self,403 source: Source,404 context_initializer: impl ContextInitializer,405 ) -> Context {406 let default_initializer = self.context_initializer();407 let mut builder = ContextBuilder::with_capacity(408 default_initializer.reserve_vars() + context_initializer.reserve_vars(),409 );410 default_initializer.populate(source.clone(), &mut builder);411 context_initializer.populate(source, &mut builder);412413 builder.build()414 }415}416417/// Internals418impl State {419 fn file_cache(&self) -> RefMut<'_, FxHashMap<SourcePath, FileData>> {420 self.0.file_cache.borrow_mut()421 }422}423/// Executes code creating a new stack frame, to be replaced with try{}424pub fn in_frame<T>(425 e: CallLocation<'_>,426 frame_desc: impl FnOnce() -> String,427 f: impl FnOnce() -> Result<T>,428) -> Result<T> {429 let _guard = check_depth()?;430431 f().with_description_src(e, frame_desc)432}433434/// Executes code creating a new stack frame, to be replaced with try{}435pub fn in_description_frame<T>(436 frame_desc: impl FnOnce() -> String,437 f: impl FnOnce() -> Result<T>,438) -> Result<T> {439 let _guard = check_depth()?;440441 f().with_description(frame_desc)442}443444#[derive(Trace)]445pub struct InitialUnderscore(pub Thunk<Val>);446impl ContextInitializer for InitialUnderscore {447 fn populate(&self, _for_file: Source, builder: &mut ContextBuilder) {448 builder.bind("_", self.0.clone());449 }450451 fn as_any(&self) -> &dyn Any {452 self453 }454}455456/// Raw methods evaluate passed values but don't perform TLA execution457impl State {458 /// Parses and evaluates the given snippet459 pub fn evaluate_snippet(&self, name: impl Into<IStr>, code: impl Into<IStr>) -> Result<Val> {460 let code = code.into();461 let source = Source::new_virtual(name.into(), code.clone());462 let parsed = jrsonnet_parser::parse(463 &code,464 &ParserSettings {465 source: source.clone(),466 },467 )468 .map_err(|e| ImportSyntaxError {469 path: source.clone(),470 error: Box::new(e),471 })?;472 evaluate(self.create_default_context(source), &parsed)473 }474 /// Parses and evaluates the given snippet with custom context modifier475 pub fn evaluate_snippet_with(476 &self,477 name: impl Into<IStr>,478 code: impl Into<IStr>,479 context_initializer: impl ContextInitializer,480 ) -> Result<Val> {481 let code = code.into();482 let source = Source::new_virtual(name.into(), code.clone());483 let parsed = jrsonnet_parser::parse(484 &code,485 &ParserSettings {486 source: source.clone(),487 },488 )489 .map_err(|e| ImportSyntaxError {490 path: source.clone(),491 error: Box::new(e),492 })?;493 evaluate(494 self.create_default_context_with(source, context_initializer),495 &parsed,496 )497 }498}499500/// Settings utilities501impl State {502 // Only panics in case of [`ImportResolver`] contract violation503 #[allow(clippy::missing_panics_doc)]504 pub fn resolve_from(&self, from: &SourcePath, path: &dyn AsPathLike) -> Result<SourcePath> {505 self.import_resolver().resolve_from(from, path)506 }507 #[allow(clippy::missing_panics_doc)]508 pub fn resolve_from_default(&self, path: &dyn AsPathLike) -> Result<SourcePath> {509 self.import_resolver().resolve_from_default(path)510 }511 pub fn import_resolver(&self) -> &dyn ImportResolver {512 &*self.0.import_resolver513 }514 pub fn context_initializer(&self) -> &dyn ContextInitializer {515 &*self.0.context_initializer.0516 }517}518519impl State {520 pub fn builder() -> StateBuilder {521 StateBuilder::default()522 }523}524525impl Default for State {526 fn default() -> Self {527 Self::builder().build()528 }529}530531#[derive(Default)]532pub struct StateBuilder {533 import_resolver: Option<Rc<dyn ImportResolver>>,534 context_initializer: Option<CcContextInitializer>,535}536impl StateBuilder {537 pub fn import_resolver(&mut self, import_resolver: impl ImportResolver) -> &mut Self {538 let _ = self.import_resolver.insert(Rc::new(import_resolver));539 self540 }541 pub fn context_initializer(542 &mut self,543 context_initializer: impl ContextInitializer,544 ) -> &mut Self {545 let _ = self546 .context_initializer547 .insert(CcContextInitializer::new(context_initializer));548 self549 }550 pub fn build(mut self) -> State {551 State(Cc::new(EvaluationStateInternals {552 file_cache: RefCell::new(FxHashMap::new()),553 context_initializer: self554 .context_initializer555 .take()556 .unwrap_or_else(|| CcContextInitializer::new(())),557 import_resolver: self558 .import_resolver559 .take()560 .unwrap_or_else(|| Rc::new(DummyImportResolver)),561 }))562 }563}crates/jrsonnet-evaluator/src/obj.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/obj.rs
+++ b/crates/jrsonnet-evaluator/src/obj.rs
@@ -4,10 +4,12 @@
collections::hash_map::Entry,
fmt::{self, Debug},
hash::{Hash, Hasher},
+ mem,
+ ops::ControlFlow,
};
use educe::Educe;
-use jrsonnet_gcmodule::{cc_dyn, Cc, Trace, Weak};
+use jrsonnet_gcmodule::{cc_dyn, Acyclic, Cc, Trace, Weak};
use jrsonnet_interner::IStr;
use jrsonnet_parser::{Span, Visibility};
use rustc_hash::{FxHashMap, FxHashSet};
@@ -74,7 +76,7 @@
pub struct SuperDepth(u32);
impl SuperDepth {
pub(super) fn deepen(&mut self) {
- *self.0 += 1
+ self.0 += 1
}
}
@@ -151,31 +153,56 @@
}
#[allow(clippy::module_name_repetitions)]
-#[derive(Trace)]
+#[derive(Trace, Default)]
#[trace(tracking(force))]
pub struct OopObject {
- // this: Option<ObjValue>,
- assertions: Cc<Vec<CcObjectAssertion>>,
- this_entries: Cc<FxHashMap<IStr, ObjMember>>,
- value_cache: RefCell<FxHashMap<(IStr, Option<WeakObjValue>), CacheValue>>,
+ assertions: Vec<CcObjectAssertion>,
+ this_entries: FxHashMap<IStr, ObjMember>,
}
impl Debug for OopObject {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("OopObject")
- // .field("assertions", &self.assertions)
- // .field("assertions_ran", &self.assertions_ran)
.field("this_entries", &self.this_entries)
- // .field("value_cache", &self.value_cache)
.finish_non_exhaustive()
}
}
+impl OopObject {
+ fn is_empty(&self) -> bool {
+ self.assertions.is_empty() && self.this_entries.is_empty()
+ }
+}
-type EnumFieldsHandler<'a> = dyn FnMut(SuperDepth, FieldIndex, IStr, Visibility) -> bool + 'a;
+type EnumFieldsHandler<'a> =
+ dyn FnMut(SuperDepth, FieldIndex, IStr, EnumFields) -> ControlFlow<()> + 'a;
+pub enum EnumFields {
+ Normal(Visibility),
+ Omit,
+}
+
#[derive(Trace, Clone)]
-pub enum ValueProcess {
- None,
- SuperPlus,
+pub enum GetFor {
+ // Return value
+ Final(Val),
+ // Continue iterating over cores, add current value to sum stack
+ SuperPlus(Val),
+ // Ignore the field value, stop at this layer instead
+ Omit,
+ NotFound,
+}
+
+#[derive(Acyclic, Clone)]
+pub enum FieldVisibility {
+ Found(Visibility),
+ Omit,
+ NotFound,
+}
+
+#[derive(Acyclic, Clone)]
+pub enum HasFieldIncludeHidden {
+ Exists,
+ NotFound,
+ Omit,
}
pub trait ObjectCore: Trace + Any + Debug {
@@ -186,13 +213,12 @@
handler: &mut EnumFieldsHandler<'_>,
) -> bool;
- fn has_field_include_hidden(&self, name: IStr) -> bool;
+ fn has_field_include_hidden_core(&self, name: IStr) -> HasFieldIncludeHidden;
- fn get_for(&self, key: IStr, sup_this: SupThis) -> Result<Option<(Val, ValueProcess)>>;
- // fn get_for_uncached(&self, key: IStr, this: ObjValue) -> Result<Option<(Val, ValueProcess)>>;
- fn field_visibility(&self, field: IStr) -> Option<Visibility>;
+ fn get_for_core(&self, key: IStr, sup_this: SupThis) -> Result<GetFor>;
+ fn field_visibility_core(&self, field: IStr) -> FieldVisibility;
- fn run_assertions_raw(&self, sup_this: SupThis) -> Result<()>;
+ fn run_assertions_core(&self, sup_this: SupThis) -> Result<()>;
}
#[derive(Clone, Trace)]
@@ -220,13 +246,13 @@
cc_dyn!(
#[derive(Clone, Debug)]
- ObjCore, ObjectCore,
+ CcObjectCore, ObjectCore,
pub fn new() {...}
);
#[derive(Trace, Educe)]
#[educe(Debug)]
struct ObjValueInner {
- cores: Vec<ObjCore>,
+ cores: Vec<CcObjectCore>,
assertions_ran: Cell<bool>,
value_cache: RefCell<FxHashMap<(IStr, CoreIdx), CacheValue>>,
}
@@ -251,6 +277,14 @@
});
}
+thread_local! {
+ static EMPTY_OBJ: ObjValue = ObjValue(Cc::new(ObjValueInner {
+ cores: vec![],
+ assertions_ran: Cell::new(true),
+ value_cache: Default::default(),
+ }))
+}
+
#[allow(clippy::module_name_repetitions)]
#[derive(Clone, Trace, Debug, Educe)]
#[educe(PartialEq, Hash, Eq)]
@@ -258,6 +292,15 @@
#[educe(PartialEq(method(Cc::ptr_eq)), Hash(method(identity_hash)))] Cc<ObjValueInner>,
);
+impl ObjValue {
+ pub fn empty() -> Self {
+ EMPTY_OBJ.with(|v| v.clone())
+ }
+ pub fn is_empty(&self) -> bool {
+ self.0.cores.is_empty() || self.len() == 0
+ }
+}
+
#[derive(Trace, Debug)]
struct StandaloneSuperCore {
sup: CoreIdx,
@@ -269,53 +312,77 @@
super_depth: &mut SuperDepth,
handler: &mut EnumFieldsHandler<'_>,
) -> bool {
- self.this
- .enum_fields_internal(super_depth, handler, self.sup)
+ self.this.enum_fields_idx(super_depth, handler, self.sup)
}
- fn has_field_include_hidden(&self, name: IStr) -> bool {
- self.this.has_field_include_hidden_idx(name, self.sup)
+ fn has_field_include_hidden_core(&self, name: IStr) -> HasFieldIncludeHidden {
+ if self.this.has_field_include_hidden_idx(name, self.sup) {
+ HasFieldIncludeHidden::Exists
+ } else {
+ HasFieldIncludeHidden::NotFound
+ }
}
- fn get_for(&self, key: IStr, _sup_this: SupThis) -> Result<Option<(Val, ValueProcess)>> {
+ fn get_for_core(&self, key: IStr, _sup_this: SupThis) -> Result<GetFor> {
let v = self.this.get_idx(key, self.sup)?;
- Ok(v.map(|v| (v, ValueProcess::None)))
+ Ok(v.map_or(GetFor::NotFound, |v| GetFor::Final(v)))
}
- fn field_visibility(&self, field: IStr) -> Option<Visibility> {
- self.this.field_visibility_idx(field, self.sup)
+ fn field_visibility_core(&self, field: IStr) -> FieldVisibility {
+ match self.this.field_visibility_idx(field, self.sup) {
+ Some(c) => FieldVisibility::Found(c),
+ None => FieldVisibility::NotFound,
+ }
}
- fn run_assertions_raw(&self, _sup_this: SupThis) -> Result<()> {
+ fn run_assertions_core(&self, _sup_this: SupThis) -> Result<()> {
self.this.run_assertions()
}
}
-#[derive(Debug, Trace)]
-struct EmptyObject;
-impl ObjectCore for EmptyObject {
+#[derive(Debug, Acyclic)]
+struct OmitFieldsCore {
+ omit: FxHashSet<IStr>,
+}
+impl ObjectCore for OmitFieldsCore {
fn enum_fields_core(
&self,
- _super_depth: &mut SuperDepth,
- _handler: &mut EnumFieldsHandler<'_>,
+ super_depth: &mut SuperDepth,
+ handler: &mut EnumFieldsHandler<'_>,
) -> bool {
+ let mut fi = FieldIndex::default();
+ for f in &self.omit {
+ if let ControlFlow::Break(()) = handler(*super_depth, fi, f.clone(), EnumFields::Omit) {
+ return false;
+ }
+ fi = fi.next();
+ }
true
}
- fn has_field_include_hidden(&self, _name: IStr) -> bool {
- false
+ fn has_field_include_hidden_core(&self, name: IStr) -> HasFieldIncludeHidden {
+ if self.omit.contains(&name) {
+ return HasFieldIncludeHidden::Omit;
+ }
+ HasFieldIncludeHidden::NotFound
}
- fn get_for(&self, _key: IStr, _sup_this: SupThis) -> Result<Option<(Val, ValueProcess)>> {
- Ok(None)
+ fn get_for_core(&self, key: IStr, _sup_this: SupThis) -> Result<GetFor> {
+ if self.omit.contains(&key) {
+ return Ok(GetFor::Omit);
+ }
+ Ok(GetFor::NotFound)
}
- fn run_assertions_raw(&self, _sup_this: SupThis) -> Result<()> {
- Ok(())
+ fn field_visibility_core(&self, field: IStr) -> FieldVisibility {
+ if self.omit.contains(&field) {
+ return FieldVisibility::Omit;
+ }
+ FieldVisibility::NotFound
}
- fn field_visibility(&self, _field: IStr) -> Option<Visibility> {
- None
+ fn run_assertions_core(&self, _sup_this: SupThis) -> Result<()> {
+ Ok(())
}
}
@@ -363,10 +430,12 @@
if !self.sup.super_exists() {
bail!(NoSuperFound)
}
- Ok(ObjValue::new(StandaloneSuperCore {
+ let mut out = ObjValue::builder();
+ out.reserve_cores(1).extend_with_core(StandaloneSuperCore {
sup: self.sup,
this: self.this.clone(),
- }))
+ });
+ Ok(out.build())
}
pub fn this(&self) -> &ObjValue {
&self.this
@@ -385,16 +454,6 @@
}
impl ObjValue {
- pub fn new(v: impl ObjectCore) -> Self {
- Self(Cc::new(ObjValueInner {
- cores: vec![ObjCore::new(v)],
- assertions_ran: Cell::new(false),
- value_cache: RefCell::new(FxHashMap::new()),
- }))
- }
- pub fn new_empty() -> Self {
- Self::new(EmptyObject)
- }
pub fn builder() -> ObjValueBuilder {
ObjValueBuilder::new()
}
@@ -420,6 +479,12 @@
ObjMemberBuilder::new(ExtendBuilder(self), name, FieldIndex::default())
}
+ pub fn extend(&mut self) -> ObjValueBuilder {
+ let mut out = ObjValueBuilder::new();
+ out.with_super(self.clone());
+ out
+ }
+
#[must_use]
pub fn extend_from(&self, sup: Self) -> Self {
let mut cores = sup.0.cores.clone();
@@ -442,16 +507,13 @@
.filter(|(_, (visible, _))| *visible)
.count()
}
- pub fn is_empty(&self) -> bool {
- self.len() == 0
- }
/// For each field, calls callback.
/// If callback returns false - ends iteration prematurely.
///
/// Returns false if ended prematurely
pub fn enum_fields(&self, handler: &mut EnumFieldsHandler<'_>) -> bool {
let mut super_depth = SuperDepth::default();
- self.enum_fields_internal(
+ self.enum_fields_idx(
&mut super_depth,
handler,
CoreIdx {
@@ -459,7 +521,7 @@
},
)
}
- fn enum_fields_internal(
+ fn enum_fields_idx(
&self,
super_depth: &mut SuperDepth,
handler: &mut EnumFieldsHandler<'_>,
@@ -483,10 +545,14 @@
)
}
fn has_field_include_hidden_idx(&self, name: IStr, core: CoreIdx) -> bool {
- self.0.cores[..core.idx]
- .iter()
- .rev()
- .any(|v| v.0.has_field_include_hidden(name.clone()))
+ for ele in self.0.cores[..core.idx].iter().rev() {
+ match ele.0.has_field_include_hidden_core(name.clone()) {
+ HasFieldIncludeHidden::Exists => return true,
+ HasFieldIncludeHidden::NotFound => {}
+ HasFieldIncludeHidden::Omit => break,
+ }
+ }
+ false
}
pub fn has_field(&self, name: IStr) -> bool {
match self.field_visibility(name) {
@@ -544,16 +610,20 @@
sup: CoreIdx { idx: sup },
this: self.clone(),
};
- if let Some((val, proc)) = core.0.get_for(key.clone(), sup_this)? {
- match proc {
- ValueProcess::None if add_stack.is_empty() => return Ok(Some(val)),
- ValueProcess::None => {
- add_stack.push(val);
- break;
- }
- ValueProcess::SuperPlus => {
- add_stack.push(val);
- }
+ match core.0.get_for_core(key.clone(), sup_this)? {
+ GetFor::Final(val) if add_stack.is_empty() => return Ok(Some(val)),
+ GetFor::Final(val) => {
+ add_stack.push(val);
+ break;
+ }
+ GetFor::SuperPlus(val) => {
+ add_stack.push(val);
+ }
+ GetFor::Omit => {
+ break;
+ }
+ GetFor::NotFound => {
+ continue;
}
}
}
@@ -594,11 +664,14 @@
fn field_visibility_idx(&self, field: IStr, core: CoreIdx) -> Option<Visibility> {
let mut exists = false;
for ele in self.0.cores[..core.idx].iter().rev() {
- let vis = ele.0.field_visibility(field.clone());
+ let vis = ele.0.field_visibility_core(field.clone());
match vis {
- Some(Visibility::Unhide | Visibility::Hidden) => return vis,
- Some(Visibility::Normal) => exists = true,
- None => {}
+ FieldVisibility::Found(vis @ (Visibility::Unhide | Visibility::Hidden)) => {
+ return Some(vis)
+ }
+ FieldVisibility::Found(Visibility::Normal) => exists = true,
+ FieldVisibility::NotFound => {}
+ FieldVisibility::Omit => break,
}
}
exists.then_some(Visibility::Normal)
@@ -616,7 +689,7 @@
sup: CoreIdx { idx },
this: self.clone(),
};
- ele.0.run_assertions_raw(sup_this).inspect_err(|_e| {
+ ele.0.run_assertions_core(sup_this).inspect_err(|_e| {
finish_asserting(self);
})?;
}
@@ -664,17 +737,24 @@
self.enum_fields(&mut |depth, index, name, visibility| {
let new_sort_key = FieldSortKey::new(depth, index);
let entry = out.entry(name);
+ if matches!(visibility, EnumFields::Omit) {
+ if let Entry::Occupied(v) = entry {
+ v.remove();
+ }
+ return ControlFlow::Continue(());
+ }
let (visible, _) = entry.or_insert((true, new_sort_key));
match visibility {
- Visibility::Normal => {}
- Visibility::Hidden => {
+ EnumFields::Omit => unreachable!(),
+ EnumFields::Normal(Visibility::Normal) => {}
+ EnumFields::Normal(Visibility::Hidden) => {
*visible = false;
}
- Visibility::Unhide => {
+ EnumFields::Normal(Visibility::Unhide) => {
*visible = true;
}
};
- false
+ return ControlFlow::Continue(());
});
out
}
@@ -776,12 +856,11 @@
impl OopObject {
pub fn new(
- this_entries: Cc<FxHashMap<IStr, ObjMember>>,
- assertions: Cc<Vec<CcObjectAssertion>>,
+ this_entries: FxHashMap<IStr, ObjMember>,
+ assertions: Vec<CcObjectAssertion>,
) -> Self {
Self {
this_entries,
- value_cache: RefCell::new(FxHashMap::new()),
assertions,
}
}
@@ -794,11 +873,14 @@
handler: &mut EnumFieldsHandler<'_>,
) -> bool {
for (name, member) in self.this_entries.iter() {
- if handler(
- *super_depth,
- member.original_index,
- name.clone(),
- member.flags.visibility(),
+ if matches!(
+ handler(
+ *super_depth,
+ member.original_index,
+ name.clone(),
+ EnumFields::Normal(member.flags.visibility()),
+ ),
+ ControlFlow::Break(())
) {
return false;
}
@@ -806,28 +888,35 @@
true
}
- fn has_field_include_hidden(&self, name: IStr) -> bool {
- self.this_entries.contains_key(&name)
+ fn has_field_include_hidden_core(&self, name: IStr) -> HasFieldIncludeHidden {
+ if self.this_entries.contains_key(&name) {
+ HasFieldIncludeHidden::Exists
+ } else {
+ HasFieldIncludeHidden::NotFound
+ }
}
- fn get_for(&self, key: IStr, sup_this: SupThis) -> Result<Option<(Val, ValueProcess)>> {
+ fn get_for_core(&self, key: IStr, sup_this: SupThis) -> Result<GetFor> {
match self.this_entries.get(&key) {
- Some(k) => Ok(Some((
- k.invoke.evaluate(sup_this)?,
- if k.flags.add() {
- ValueProcess::SuperPlus
+ Some(k) => {
+ let v = k.invoke.evaluate(sup_this)?;
+ Ok(if k.flags.add() {
+ GetFor::SuperPlus(v)
} else {
- ValueProcess::None
- },
- ))),
- None => Ok(None),
+ GetFor::Final(v)
+ })
+ }
+ None => Ok(GetFor::NotFound),
}
}
- fn field_visibility(&self, name: IStr) -> Option<Visibility> {
- Some(self.this_entries.get(&name)?.flags.visibility())
+ fn field_visibility_core(&self, name: IStr) -> FieldVisibility {
+ match self.this_entries.get(&name) {
+ Some(f) => FieldVisibility::Found(f.flags.visibility()),
+ None => FieldVisibility::NotFound,
+ }
}
- fn run_assertions_raw(&self, sup_this: SupThis) -> Result<()> {
+ fn run_assertions_core(&self, sup_this: SupThis) -> Result<()> {
if self.assertions.is_empty() {
return Ok(());
}
@@ -840,9 +929,9 @@
#[allow(clippy::module_name_repetitions)]
pub struct ObjValueBuilder {
- sup: Option<ObjValue>,
- map: FxHashMap<IStr, ObjMember>,
- assertions: Vec<CcObjectAssertion>,
+ sup: Vec<CcObjectCore>,
+
+ new: OopObject,
next_field_index: FieldIndex,
}
impl ObjValueBuilder {
@@ -851,23 +940,29 @@
}
pub fn with_capacity(capacity: usize) -> Self {
Self {
- sup: None,
- map: FxHashMap::with_capacity(capacity),
- assertions: Vec::new(),
+ sup: vec![],
+ new: OopObject {
+ assertions: vec![],
+ this_entries: FxHashMap::with_capacity(capacity),
+ },
next_field_index: FieldIndex::default(),
}
}
+ pub fn reserve_cores(&mut self, capacity: usize) -> &mut Self {
+ self.sup.reserve_exact(capacity);
+ self
+ }
pub fn reserve_asserts(&mut self, capacity: usize) -> &mut Self {
- self.assertions.reserve_exact(capacity);
+ self.new.assertions.reserve_exact(capacity);
self
}
pub fn with_super(&mut self, super_obj: ObjValue) -> &mut Self {
- self.sup = Some(super_obj);
+ self.sup = super_obj.0.cores.clone();
self
}
pub fn assert(&mut self, assertion: impl ObjectAssertion + 'static) -> &mut Self {
- self.assertions.push(CcObjectAssertion::new(assertion));
+ self.new.assertions.push(CcObjectAssertion::new(assertion));
self
}
pub fn field(&mut self, name: impl Into<IStr>) -> ObjMemberBuilder<ValueBuilder<'_>> {
@@ -892,12 +987,33 @@
Ok(self)
}
- pub fn build(self) -> ObjValue {
- if self.sup.is_none() && self.map.is_empty() && self.assertions.is_empty() {
- return ObjValue::new_empty();
+ pub fn extend_with_core(&mut self, core: impl ObjectCore) {
+ self.commit();
+ self.sup.push(CcObjectCore::new(core));
+ }
+
+ fn commit(&mut self) {
+ if !self.new.is_empty() {
+ self.sup.push(CcObjectCore::new(mem::take(&mut self.new)));
+ }
+ self.next_field_index = FieldIndex::default();
+ }
+
+ pub fn with_fields_omitted(&mut self, omit: FxHashSet<IStr>) {
+ self.commit();
+ self.sup.push(CcObjectCore::new(OmitFieldsCore { omit }));
+ }
+
+ pub fn build(mut self) -> ObjValue {
+ self.commit();
+ if self.sup.is_empty() {
+ return ObjValue::empty();
}
- let res = ObjValue::new(OopObject::new(Cc::new(self.map), Cc::new(self.assertions)));
- self.sup.map(|sup| res.extend_from(sup)).unwrap_or(res)
+ ObjValue(Cc::new(ObjValueInner {
+ cores: self.sup,
+ assertions_ran: Cell::new(false),
+ value_cache: Default::default(),
+ }))
}
}
impl Default for ObjValueBuilder {
@@ -968,7 +1084,7 @@
pub fn value(self, value: impl Into<Val>) {
let (receiver, name, member) =
self.build_member(MaybeUnbound::Bound(Thunk::evaluated(value.into())));
- let entry = receiver.0.map.entry(name);
+ let entry = receiver.0.new.this_entries.entry(name);
entry.insert_entry(member);
}
@@ -985,7 +1101,7 @@
pub fn binding(self, binding: MaybeUnbound) -> Result<()> {
let (receiver, name, member) = self.build_member(binding);
let location = member.location.clone();
- let old = receiver.0.map.insert(name.clone(), member);
+ let old = receiver.0.new.this_entries.insert(name.clone(), member);
if old.is_some() {
in_frame(
CallLocation(location.as_ref()),
crates/jrsonnet-stdlib/src/manifest/xml.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/manifest/xml.rs
+++ b/crates/jrsonnet-stdlib/src/manifest/xml.rs
@@ -62,10 +62,10 @@
if let Val::Obj(attrs) = maybe_attrs {
(true, attrs)
} else {
- (false, ObjValue::new_empty())
+ (false, ObjValue::empty())
}
} else {
- (false, ObjValue::new_empty())
+ (false, ObjValue::empty())
};
Ok(Self::Tag {
tag,
crates/jrsonnet-stdlib/src/misc.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/misc.rs
+++ b/crates/jrsonnet-stdlib/src/misc.rs
@@ -172,7 +172,7 @@
let Some(patch) = patch.as_obj() else {
return Ok(patch);
};
- let target = target.as_obj().unwrap_or_else(|| ObjValue::new_empty());
+ let target = target.as_obj().unwrap_or_else(|| ObjValue::empty());
let target_fields = target
.fields(
// FIXME: Makes no sense to preserve order for BTreeSet, it would be better to use IndexSet here?
crates/jrsonnet-stdlib/src/objects.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/objects.rs
+++ b/crates/jrsonnet-stdlib/src/objects.rs
@@ -1,8 +1,9 @@
use jrsonnet_evaluator::{
function::builtin,
+ gc::WithCapacityExt,
rustc_hash::FxHashSet,
val::{ArrValue, Val},
- IStr, MaybeUnbound, ObjValue, ObjValueBuilder, Thunk,
+ IStr, ObjValue, ObjValueBuilder,
};
#[builtin]
@@ -156,43 +157,11 @@
}
#[builtin]
-pub fn builtin_object_remove_key(
- obj: ObjValue,
- key: IStr,
-
- // Standard implementation uses std.objectFields without such argument, we can't
- // assume order preservation should always be enabled/disabled
- #[default(false)]
- #[cfg(feature = "exp-preserve-order")]
- preserve_order: bool,
-) -> ObjValue {
- let mut new_obj = ObjValueBuilder::with_capacity(obj.len() - 1);
- let all_fields = obj.fields_ex(
- true,
- #[cfg(feature = "exp-preserve-order")]
- preserve_order,
- );
- let visible_fields = obj
- .fields_ex(
- false,
- #[cfg(feature = "exp-preserve-order")]
- preserve_order,
- )
- .into_iter()
- .collect::<FxHashSet<_>>();
-
- for field in &all_fields {
- if *field == key {
- continue;
- }
- let mut b = new_obj.field(field.clone());
- if !visible_fields.contains(&field) {
- b = b.hide();
- }
- let _ = b.binding(MaybeUnbound::Bound(Thunk::result(
- obj.get(field.clone()).transpose().expect("field exists"),
- )));
- }
+pub fn builtin_object_remove_key(obj: ObjValue, key: IStr) -> ObjValue {
+ let mut omit = FxHashSet::with_capacity(1);
+ omit.insert(key);
- new_obj.build()
+ let mut out = ObjValueBuilder::new();
+ out.with_super(obj).with_fields_omitted(omit);
+ out.build()
}
tests/tests/as_native.rsdiffbeforeafterboth--- a/tests/tests/as_native.rs
+++ b/tests/tests/as_native.rs
@@ -1,4 +1,4 @@
-use jrsonnet_evaluator::{trace::PathResolver, FileImportResolver, Result, State};
+use jrsonnet_evaluator::{FileImportResolver, Result, State, trace::PathResolver};
use jrsonnet_stdlib::ContextInitializer;
mod common;
tests/tests/builtin.rsdiffbeforeafterboth--- a/tests/tests/builtin.rs
+++ b/tests/tests/builtin.rs
@@ -1,11 +1,11 @@
mod common;
use jrsonnet_evaluator::{
- function::{builtin, builtin::Builtin, CallLocation, FuncVal},
+ ContextBuilder, ContextInitializer, FileImportResolver, Result, State, Thunk, Val,
+ function::{CallLocation, FuncVal, builtin, builtin::Builtin},
parser::Source,
trace::PathResolver,
typed::Typed,
- ContextBuilder, ContextInitializer, FileImportResolver, Result, State, Thunk, Val,
};
use jrsonnet_gcmodule::Trace;
use jrsonnet_stdlib::ContextInitializer as StdContextInitializer;
@@ -18,11 +18,8 @@
#[test]
fn basic_function() -> Result<()> {
let a: a = a {};
- let v = u32::from_untyped(a.call(
- ContextBuilder::new().build(),
- CallLocation::native(),
- &(),
- )?)?;
+ let v =
+ u32::from_untyped(a.call(ContextBuilder::new().build(), CallLocation::native(), &())?)?;
ensure_eq!(v, 1);
Ok(())
tests/tests/common.rsdiffbeforeafterboth--- a/tests/tests/common.rs
+++ b/tests/tests/common.rs
@@ -1,8 +1,8 @@
use jrsonnet_evaluator::{
+ ContextBuilder, ContextInitializer as ContextInitializerT, ObjValueBuilder, Result, Thunk, Val,
bail,
- function::{builtin, FuncVal},
+ function::{FuncVal, builtin},
parser::Source,
- ContextBuilder, ContextInitializer as ContextInitializerT, ObjValueBuilder, Result, Thunk, Val,
};
use jrsonnet_gcmodule::Trace;
tests/tests/golden.rsdiffbeforeafterboth--- a/tests/tests/golden.rs
+++ b/tests/tests/golden.rs
@@ -4,9 +4,9 @@
};
use jrsonnet_evaluator::{
+ FileImportResolver, State,
manifest::JsonFormat,
trace::{CompactFormat, PathResolver, TraceFormat},
- FileImportResolver, State,
};
use jrsonnet_stdlib::ContextInitializer;
mod common;
tests/tests/sanity.rsdiffbeforeafterboth--- a/tests/tests/sanity.rs
+++ b/tests/tests/sanity.rs
@@ -1,7 +1,6 @@
use jrsonnet_evaluator::{
- bail,
+ FileImportResolver, Result, State, Val, bail,
trace::{CompactFormat, PathResolver, TraceFormat},
- FileImportResolver, Result, State, Val,
};
use jrsonnet_stdlib::ContextInitializer;
tests/tests/std_native.rsdiffbeforeafterboth--- a/tests/tests/std_native.rs
+++ b/tests/tests/std_native.rs
@@ -1,4 +1,4 @@
-use jrsonnet_evaluator::{function::builtin, trace::PathResolver, State};
+use jrsonnet_evaluator::{State, function::builtin, trace::PathResolver};
use jrsonnet_stdlib::ContextInitializer;
#[builtin]
@@ -14,9 +14,11 @@
state.context_initializer(std);
let state = state.build();
- assert!(state
- .evaluate_snippet("test", "std.native('example')(1, 3) == 4")
- .unwrap()
- .as_bool()
- .expect("boolean output"));
+ assert!(
+ state
+ .evaluate_snippet("test", "std.native('example')(1, 3) == 4")
+ .unwrap()
+ .as_bool()
+ .expect("boolean output")
+ );
}
tests/tests/suite.rsdiffbeforeafterboth--- a/tests/tests/suite.rs
+++ b/tests/tests/suite.rs
@@ -4,8 +4,8 @@
};
use jrsonnet_evaluator::{
+ FileImportResolver, State, Val,
trace::{CompactFormat, PathResolver, TraceFormat},
- FileImportResolver, State, Val,
};
use jrsonnet_stdlib::ContextInitializer;
tests/tests/typed_obj.rsdiffbeforeafterboth--- a/tests/tests/typed_obj.rs
+++ b/tests/tests/typed_obj.rs
@@ -2,7 +2,7 @@
use std::fmt::Debug;
-use jrsonnet_evaluator::{trace::PathResolver, typed::Typed, Result, State};
+use jrsonnet_evaluator::{Result, State, trace::PathResolver, typed::Typed};
use jrsonnet_stdlib::ContextInitializer;
#[derive(Clone, Typed, PartialEq, Debug)]