git.delta.rocks / jrsonnet / refs/commits / 64f3674f18c4

difftreelog

perf specialize super.field gets

Yaroslav Bolyukin2022-11-20parent: #30b370e.patch.diff
in: master

4 files changed

modifiedcmds/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)?;
modifiedcrates/jrsonnet-cli/src/lib.rsdiffbeforeafterboth
before · crates/jrsonnet-cli/src/lib.rs
1mod manifest;2mod stdlib;3mod tla;4mod trace;56use std::{env, marker::PhantomData, path::PathBuf};78use clap::Parser;9use jrsonnet_evaluator::{10	error::Result, stack::StackDepthLimitOverrideGuard, FileImportResolver, State,11};12use jrsonnet_gcmodule::with_thread_object_space;13pub use manifest::*;14pub use stdlib::*;15pub use tla::*;16pub use trace::*;1718pub trait ConfigureState {19	type Guards;2021	fn configure(&self, s: &State) -> Result<Self::Guards>;22}2324#[derive(Parser)]25#[clap(next_help_heading = "INPUT")]26pub struct InputOpts {27	/// Treat input as code, evaluate them instead of reading file28	#[clap(long, short = 'e')]29	pub exec: bool,3031	/// Path to the file to be compiled if `--evaluate` is unset, otherwise code itself32	pub input: String,33}3435#[derive(Parser)]36#[clap(next_help_heading = "OPTIONS")]37pub struct MiscOpts {38	/// Maximal allowed number of stack frames,39	/// stack overflow error will be raised if this number gets exceeded.40	#[clap(long, short = 's', default_value = "200")]41	max_stack: usize,4243	/// Library search dirs. (right-most wins)44	/// Any not found `imported` file will be searched in these.45	/// This can also be specified via `JSONNET_PATH` variable,46	/// which should contain a colon-separated (semicolon-separated on Windows) list of directories.47	#[clap(long, short = 'J')]48	jpath: Vec<PathBuf>,49}50impl ConfigureState for MiscOpts {51	type Guards = StackDepthLimitOverrideGuard;52	fn configure(&self, s: &State) -> Result<Self::Guards> {53		let mut library_paths = self.jpath.clone();54		library_paths.reverse();55		if let Some(path) = env::var_os("JSONNET_PATH") {56			library_paths.extend(env::split_paths(path.as_os_str()));57		}5859		s.set_import_resolver(Box::new(FileImportResolver::new(library_paths)));6061		let _depth_limit = jrsonnet_evaluator::stack::limit_stack_depth(self.max_stack);62		Ok(_depth_limit)63	}64}6566/// General configuration of jsonnet67#[derive(Parser)]68#[clap(name = "jrsonnet", version, author)]69pub struct GeneralOpts {70	#[clap(flatten)]71	misc: MiscOpts,7273	#[clap(flatten)]74	tla: TlaOpts,75	#[clap(flatten)]76	std: StdOpts,7778	#[clap(flatten)]79	gc: GcOpts,80}8182impl ConfigureState for GeneralOpts {83	type Guards = (84		<MiscOpts as ConfigureState>::Guards,85		<TlaOpts as ConfigureState>::Guards,86		<GcOpts as ConfigureState>::Guards,87	);88	fn configure(&self, s: &State) -> Result<Self::Guards> {89		// Configure trace first, because tla-code/ext-code can throw90		let misc_guards = self.misc.configure(s)?;91		let tla_guards = self.tla.configure(s)?;92		self.std.configure(s)?;93		let gc_guards = self.gc.configure(s)?;94		Ok((misc_guards, tla_guards, gc_guards))95	}96}9798#[derive(Parser)]99#[clap(next_help_heading = "GARBAGE COLLECTION")]100pub struct GcOpts {101	/// Do not skip gc on exit102	#[clap(long)]103	gc_collect_on_exit: bool,104	/// Print gc stats before exit105	#[clap(long)]106	gc_print_stats: bool,107	/// Force garbage collection before printing stats108	/// Useful for checking for memory leaks109	/// Does nothing useless --gc-print-stats is specified110	#[clap(long)]111	gc_collect_before_printing_stats: bool,112}113impl ConfigureState for GcOpts {114	type Guards = (Option<GcStatsPrinter>, Option<LeakSpace>);115116	fn configure(&self, _s: &State) -> Result<Self::Guards> {117		// Constructed structs have side-effects in Drop impl118		#[allow(clippy::unnecessary_lazy_evaluations)]119		Ok((120			self.gc_print_stats.then(|| GcStatsPrinter {121				collect_before_printing_stats: self.gc_collect_before_printing_stats,122			}),123			(!self.gc_collect_on_exit).then(|| LeakSpace(PhantomData)),124		))125	}126}127128pub struct LeakSpace(PhantomData<()>);129130impl Drop for LeakSpace {131	fn drop(&mut self) {132		with_thread_object_space(|s| s.leak())133	}134}135136pub struct GcStatsPrinter {137	collect_before_printing_stats: bool,138}139impl Drop for GcStatsPrinter {140	fn drop(&mut self) {141		eprintln!("=== GC STATS ===");142		if self.collect_before_printing_stats {143			let collected = jrsonnet_gcmodule::collect_thread_cycles();144			eprintln!("Collected: {}", collected);145		}146		eprintln!("Tracked: {}", jrsonnet_gcmodule::count_thread_tracked())147	}148}
after · crates/jrsonnet-cli/src/lib.rs
1mod 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}
modifiedcrates/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),
modifiedcrates/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())),