difftreelog
perf specialize super.field gets
in: master
4 files changed
cmds/jrsonnet/src/main.rsdiffbeforeafterboth--- a/cmds/jrsonnet/src/main.rs
+++ b/cmds/jrsonnet/src/main.rs
@@ -139,7 +139,7 @@
}
fn main_real(s: &State, opts: Opts) -> Result<(), Error> {
- let (_stack_guard, tla, _gc_guard) = opts.general.configure(s)?;
+ let (tla, _gc_guard) = opts.general.configure(s)?;
let manifest_format = opts.manifest.configure(s)?;
let input = opts.input.input.ok_or(Error::MissingInputArgument)?;
crates/jrsonnet-cli/src/lib.rsdiffbeforeafterboth1mod manifest;2mod stdlib;3mod tla;4mod trace;56use std::{env, marker::PhantomData, path::PathBuf};78use clap::Parser;9use jrsonnet_evaluator::{error::Result, stack::set_stack_depth_limit, FileImportResolver, State};10use jrsonnet_gcmodule::with_thread_object_space;11pub use manifest::*;12pub use stdlib::*;13pub use tla::*;14pub use trace::*;1516pub trait ConfigureState {17 type Guards;1819 fn configure(&self, s: &State) -> Result<Self::Guards>;20}2122#[derive(Parser)]23#[clap(next_help_heading = "INPUT")]24pub struct InputOpts {25 /// Treat input as code, evaluate them instead of reading file26 #[clap(long, short = 'e')]27 pub exec: bool,2829 /// Path to the file to be compiled if `--evaluate` is unset, otherwise code itself30 pub input: String,31}3233#[derive(Parser)]34#[clap(next_help_heading = "OPTIONS")]35pub struct MiscOpts {36 /// Maximal allowed number of stack frames,37 /// stack overflow error will be raised if this number gets exceeded.38 #[clap(long, short = 's', default_value = "200")]39 max_stack: usize,4041 /// Library search dirs. (right-most wins)42 /// Any not found `imported` file will be searched in these.43 /// This can also be specified via `JSONNET_PATH` variable,44 /// which should contain a colon-separated (semicolon-separated on Windows) list of directories.45 #[clap(long, short = 'J')]46 jpath: Vec<PathBuf>,47}48impl ConfigureState for MiscOpts {49 type Guards = ();50 fn configure(&self, s: &State) -> Result<Self::Guards> {51 let mut library_paths = self.jpath.clone();52 library_paths.reverse();53 if let Some(path) = env::var_os("JSONNET_PATH") {54 library_paths.extend(env::split_paths(path.as_os_str()));55 }5657 s.set_import_resolver(Box::new(FileImportResolver::new(library_paths)));5859 set_stack_depth_limit(self.max_stack);60 Ok(())61 }62}6364/// General configuration of jsonnet65#[derive(Parser)]66#[clap(name = "jrsonnet", version, author)]67pub struct GeneralOpts {68 #[clap(flatten)]69 misc: MiscOpts,7071 #[clap(flatten)]72 tla: TlaOpts,73 #[clap(flatten)]74 std: StdOpts,7576 #[clap(flatten)]77 gc: GcOpts,78}7980impl ConfigureState for GeneralOpts {81 type Guards = (82 <TlaOpts as ConfigureState>::Guards,83 <GcOpts as ConfigureState>::Guards,84 );85 fn configure(&self, s: &State) -> Result<Self::Guards> {86 // Configure trace first, because tla-code/ext-code can throw87 self.misc.configure(s)?;88 let tla_guards = self.tla.configure(s)?;89 self.std.configure(s)?;90 let gc_guards = self.gc.configure(s)?;91 Ok((tla_guards, gc_guards))92 }93}9495#[derive(Parser)]96#[clap(next_help_heading = "GARBAGE COLLECTION")]97pub struct GcOpts {98 /// Do not skip gc on exit99 #[clap(long)]100 gc_collect_on_exit: bool,101 /// Print gc stats before exit102 #[clap(long)]103 gc_print_stats: bool,104 /// Force garbage collection before printing stats105 /// Useful for checking for memory leaks106 /// Does nothing useless --gc-print-stats is specified107 #[clap(long)]108 gc_collect_before_printing_stats: bool,109}110impl ConfigureState for GcOpts {111 type Guards = (Option<GcStatsPrinter>, Option<LeakSpace>);112113 fn configure(&self, _s: &State) -> Result<Self::Guards> {114 // Constructed structs have side-effects in Drop impl115 #[allow(clippy::unnecessary_lazy_evaluations)]116 Ok((117 self.gc_print_stats.then(|| GcStatsPrinter {118 collect_before_printing_stats: self.gc_collect_before_printing_stats,119 }),120 (!self.gc_collect_on_exit).then(|| LeakSpace(PhantomData)),121 ))122 }123}124125pub struct LeakSpace(PhantomData<()>);126127impl Drop for LeakSpace {128 fn drop(&mut self) {129 with_thread_object_space(|s| s.leak())130 }131}132133pub struct GcStatsPrinter {134 collect_before_printing_stats: bool,135}136impl Drop for GcStatsPrinter {137 fn drop(&mut self) {138 eprintln!("=== GC STATS ===");139 if self.collect_before_printing_stats {140 let collected = jrsonnet_gcmodule::collect_thread_cycles();141 eprintln!("Collected: {}", collected);142 }143 eprintln!("Tracked: {}", jrsonnet_gcmodule::count_thread_tracked())144 }145}crates/jrsonnet-evaluator/src/evaluate/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/evaluate/mod.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/mod.rs
@@ -389,7 +389,7 @@
ctx.super_obj().clone().ok_or(NoSuperFound)?.with_this(
ctx.this()
.clone()
- .expect("if super exists - then this should to"),
+ .expect("if super exists - then this should too"),
),
),
Literal(LiteralType::Dollar) => {
@@ -408,6 +408,21 @@
|| format!("variable <{name}> access"),
|| ctx.binding(name.clone())?.evaluate(),
)?,
+ Index(LocExpr(v, _), index) if matches!(&**v, Expr::Literal(LiteralType::Super)) => {
+ let name = evaluate(ctx.clone(), index)?;
+ let Val::Str(name) = name else {
+ throw!(ValueIndexMustBeTypeGot(
+ ValType::Obj,
+ ValType::Str,
+ name.value_type(),
+ ))
+ };
+ ctx.super_obj()
+ .clone()
+ .expect("no super found")
+ .get_for(name, ctx.this().clone().expect("no this found"))?
+ .expect("value not found")
+ }
Index(value, index) => match (evaluate(ctx.clone(), value)?, evaluate(ctx, index)?) {
(Val::Obj(v), Val::Str(key)) => State::push(
CallLocation::new(loc),
crates/jrsonnet-evaluator/src/obj.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/obj.rs
+++ b/crates/jrsonnet-evaluator/src/obj.rs
@@ -128,7 +128,7 @@
assertions: Cc<Vec<TraceBox<dyn ObjectAssertion>>>,
assertions_ran: RefCell<GcHashSet<ObjValue>>,
this_entries: Cc<GcHashMap<IStr, ObjMember>>,
- value_cache: RefCell<GcHashMap<IStr, CacheValue>>,
+ value_cache: RefCell<GcHashMap<(IStr, Option<WeakObjValue>), CacheValue>>,
}
#[derive(Clone, Trace)]
@@ -387,7 +387,8 @@
pub fn get(&self, key: IStr) -> Result<Option<Val>> {
self.run_assertions()?;
- if let Some(v) = self.0.value_cache.borrow().get(&key) {
+ let cache_key = (key.clone(), None);
+ if let Some(v) = self.0.value_cache.borrow().get(&cache_key) {
return Ok(match v {
CacheValue::Cached(v) => Some(v.clone()),
CacheValue::NotFound => None,
@@ -398,21 +399,48 @@
self.0
.value_cache
.borrow_mut()
- .insert(key.clone(), CacheValue::Pending);
+ .insert(cache_key.clone(), CacheValue::Pending);
let value = self
- .get_raw(
- key.clone(),
- self.0.this.clone().unwrap_or_else(|| self.clone()),
- )
+ .get_raw(key, self.0.this.clone().unwrap_or_else(|| self.clone()))
.map_err(|e| {
self.0
.value_cache
.borrow_mut()
- .insert(key.clone(), CacheValue::Errored(e.clone()));
+ .insert(cache_key.clone(), CacheValue::Errored(e.clone()));
e
})?;
self.0.value_cache.borrow_mut().insert(
- key,
+ cache_key,
+ value
+ .as_ref()
+ .map_or(CacheValue::NotFound, |v| CacheValue::Cached(v.clone())),
+ );
+ Ok(value)
+ }
+ pub fn get_for(&self, key: IStr, this: Self) -> Result<Option<Val>> {
+ self.run_assertions()?;
+ let cache_key = (key.clone(), Some(this.clone().downgrade()));
+ if let Some(v) = self.0.value_cache.borrow().get(&cache_key) {
+ return Ok(match v {
+ CacheValue::Cached(v) => Some(v.clone()),
+ CacheValue::NotFound => None,
+ CacheValue::Pending => throw!(InfiniteRecursionDetected),
+ CacheValue::Errored(e) => return Err(e.clone()),
+ });
+ }
+ self.0
+ .value_cache
+ .borrow_mut()
+ .insert(cache_key.clone(), CacheValue::Pending);
+ let value = self.get_raw(key, this).map_err(|e| {
+ self.0
+ .value_cache
+ .borrow_mut()
+ .insert(cache_key.clone(), CacheValue::Errored(e.clone()));
+ e
+ })?;
+ self.0.value_cache.borrow_mut().insert(
+ cache_key,
value
.as_ref()
.map_or(CacheValue::NotFound, |v| CacheValue::Cached(v.clone())),