difftreelog
refactor! implement stack size limit using thread local
in: master
18 files changed
bindings/jsonnet/src/lib.rsdiffbeforeafterboth--- a/bindings/jsonnet/src/lib.rs
+++ b/bindings/jsonnet/src/lib.rs
@@ -85,8 +85,8 @@
/// Set the maximum stack depth.
#[no_mangle]
-pub extern "C" fn jsonnet_max_stack(vm: &State, v: c_uint) {
- vm.settings_mut().max_stack = v as usize;
+pub extern "C" fn jsonnet_max_stack(_vm: &State, _v: c_uint) {
+ todo!()
}
/// Set the number of objects required before a garbage collection cycle is allowed.
cmds/jrsonnet/src/main.rsdiffbeforeafterboth--- a/cmds/jrsonnet/src/main.rs
+++ b/cmds/jrsonnet/src/main.rs
@@ -5,7 +5,7 @@
use clap::{AppSettings, IntoApp, Parser};
use clap_complete::Shell;
-use jrsonnet_cli::{ConfigureState, GcOpts, GeneralOpts, ManifestOpts, OutputOpts};
+use jrsonnet_cli::{ConfigureState, GeneralOpts, ManifestOpts, OutputOpts};
use jrsonnet_evaluator::{error::LocError, State};
#[cfg(feature = "mimalloc")]
@@ -60,8 +60,6 @@
output: OutputOpts,
#[clap(flatten)]
debug: DebugOpts,
- #[clap(flatten)]
- gc: GcOpts,
}
fn main() {
@@ -113,7 +111,6 @@
}
fn main_catch(opts: Opts) -> bool {
- let _printer = opts.gc.stats_printer();
let s = State::default();
if let Err(e) = main_real(&s, opts) {
if let Error::Evaluation(e) = e {
@@ -127,7 +124,7 @@
}
fn main_real(s: &State, opts: Opts) -> Result<(), Error> {
- opts.general.configure(s)?;
+ let _guards = opts.general.configure(s)?;
opts.manifest.configure(s)?;
let input = opts.input.input.ok_or(Error::MissingInputArgument)?;
crates/jrsonnet-cli/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-cli/src/lib.rs
+++ b/crates/jrsonnet-cli/src/lib.rs
@@ -3,10 +3,12 @@
mod tla;
mod trace;
-use std::{env, path::PathBuf};
+use std::{env, marker::PhantomData, path::PathBuf};
use clap::Parser;
-use jrsonnet_evaluator::{error::Result, FileImportResolver, State};
+use jrsonnet_evaluator::{
+ error::Result, stack::StackDepthLimitOverrideGuard, FileImportResolver, State,
+};
use jrsonnet_gcmodule::with_thread_object_space;
pub use manifest::*;
pub use stdlib::*;
@@ -14,7 +16,9 @@
pub use trace::*;
pub trait ConfigureState {
- fn configure(&self, s: &State) -> Result<()>;
+ type Guards;
+
+ fn configure(&self, s: &State) -> Result<Self::Guards>;
}
#[derive(Parser)]
@@ -44,7 +48,8 @@
jpath: Vec<PathBuf>,
}
impl ConfigureState for MiscOpts {
- fn configure(&self, s: &State) -> Result<()> {
+ type Guards = StackDepthLimitOverrideGuard;
+ fn configure(&self, s: &State) -> Result<Self::Guards> {
let mut library_paths = self.jpath.clone();
library_paths.reverse();
if let Some(path) = env::var_os("JSONNET_PATH") {
@@ -53,8 +58,8 @@
s.set_import_resolver(Box::new(FileImportResolver::new(library_paths)));
- s.set_max_stack(self.max_stack);
- Ok(())
+ let _depth_limit = jrsonnet_evaluator::stack::limit_stack_depth(self.max_stack);
+ Ok(_depth_limit)
}
}
@@ -72,16 +77,24 @@
#[clap(flatten)]
trace: TraceOpts,
+
+ #[clap(flatten)]
+ gc: GcOpts,
}
impl ConfigureState for GeneralOpts {
- fn configure(&self, s: &State) -> Result<()> {
+ type Guards = (
+ <MiscOpts as ConfigureState>::Guards,
+ <GcOpts as ConfigureState>::Guards,
+ );
+ fn configure(&self, s: &State) -> Result<Self::Guards> {
// Configure trace first, because tla-code/ext-code can throw
self.trace.configure(s)?;
- self.misc.configure(s)?;
+ let misc_guards = self.misc.configure(s)?;
self.tla.configure(s)?;
self.std.configure(s)?;
- Ok(())
+ let gc_guards = self.gc.configure(s)?;
+ Ok((misc_guards, gc_guards))
}
}
@@ -100,20 +113,22 @@
#[clap(long)]
gc_collect_before_printing_stats: bool,
}
-impl GcOpts {
- pub fn stats_printer(&self) -> (Option<GcStatsPrinter>, Option<LeakSpace>) {
+impl ConfigureState for GcOpts {
+ type Guards = (Option<GcStatsPrinter>, Option<LeakSpace>);
+
+ fn configure(&self, _s: &State) -> Result<Self::Guards> {
// Constructed structs have side-effects in Drop impl
#[allow(clippy::unnecessary_lazy_evaluations)]
- (
+ Ok((
self.gc_print_stats.then(|| GcStatsPrinter {
collect_before_printing_stats: self.gc_collect_before_printing_stats,
}),
- (!self.gc_collect_on_exit).then(|| LeakSpace {}),
- )
+ (!self.gc_collect_on_exit).then(|| LeakSpace(PhantomData)),
+ ))
}
}
-pub struct LeakSpace {}
+pub struct LeakSpace(PhantomData<()>);
impl Drop for LeakSpace {
fn drop(&mut self) {
crates/jrsonnet-cli/src/manifest.rsdiffbeforeafterboth--- a/crates/jrsonnet-cli/src/manifest.rs
+++ b/crates/jrsonnet-cli/src/manifest.rs
@@ -47,6 +47,7 @@
exp_preserve_order: bool,
}
impl ConfigureState for ManifestOpts {
+ type Guards = ();
fn configure(&self, s: &State) -> Result<()> {
if self.string {
s.set_manifest_format(ManifestFormat::String);
crates/jrsonnet-cli/src/stdlib.rsdiffbeforeafterboth--- a/crates/jrsonnet-cli/src/stdlib.rs
+++ b/crates/jrsonnet-cli/src/stdlib.rs
@@ -106,6 +106,7 @@
ext_code_file: Vec<ExtFile>,
}
impl ConfigureState for StdOpts {
+ type Guards = ();
fn configure(&self, s: &State) -> Result<()> {
if self.no_stdlib {
return Ok(());
crates/jrsonnet-cli/src/tla.rsdiffbeforeafterboth--- a/crates/jrsonnet-cli/src/tla.rs
+++ b/crates/jrsonnet-cli/src/tla.rs
@@ -47,6 +47,7 @@
tla_code_file: Vec<ExtFile>,
}
impl ConfigureState for TLAOpts {
+ type Guards = ();
fn configure(&self, s: &State) -> Result<()> {
for tla in self.tla_str.iter() {
s.add_tla_str((&tla.name as &str).into(), (&tla.value as &str).into());
crates/jrsonnet-cli/src/trace.rsdiffbeforeafterboth--- a/crates/jrsonnet-cli/src/trace.rs
+++ b/crates/jrsonnet-cli/src/trace.rs
@@ -41,6 +41,7 @@
max_trace: usize,
}
impl ConfigureState for TraceOpts {
+ type Guards = ();
fn configure(&self, s: &State) -> Result<()> {
let resolver = PathResolver::new_cwd_fallback();
match self
crates/jrsonnet-evaluator/Cargo.tomldiffbeforeafterboth--- a/crates/jrsonnet-evaluator/Cargo.toml
+++ b/crates/jrsonnet-evaluator/Cargo.toml
@@ -20,8 +20,8 @@
exp-preserve-order = []
# Implements field destructuring
exp-destruct = ["jrsonnet-parser/exp-destruct"]
-# Provide Typed for conversions to/from serde_json::Value type
-serde_json = ["dep:serde_json"]
+# Improves performance, and implements some useful things using nightly-only features
+nightly = []
[dependencies]
jrsonnet-interner = { path = "../jrsonnet-interner", version = "0.4.2" }
crates/jrsonnet-evaluator/src/error.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/error.rs
+++ b/crates/jrsonnet-evaluator/src/error.rs
@@ -2,11 +2,11 @@
use jrsonnet_gcmodule::Trace;
use jrsonnet_interner::IStr;
-use jrsonnet_parser::{BinaryOpType, ExprLocation, Source, SourcePath, UnaryOpType};
+use jrsonnet_parser::{BinaryOpType, ExprLocation, LocExpr, Source, SourcePath, UnaryOpType};
use jrsonnet_types::ValType;
use thiserror::Error;
-use crate::{stdlib::format::FormatError, typed::TypeLocError};
+use crate::{function::CallLocation, stdlib::format::FormatError, typed::TypeLocError};
fn format_found(list: &[IStr], what: &str) -> String {
if list.is_empty() {
@@ -262,7 +262,72 @@
}
}
+pub trait ErrorSource {
+ fn to_location(self) -> Option<ExprLocation>;
+}
+impl ErrorSource for &LocExpr {
+ fn to_location(self) -> Option<ExprLocation> {
+ Some(self.1.clone())
+ }
+}
+impl ErrorSource for &ExprLocation {
+ fn to_location(self) -> Option<ExprLocation> {
+ Some(self.clone())
+ }
+}
+impl ErrorSource for CallLocation<'_> {
+ fn to_location(self) -> Option<ExprLocation> {
+ self.0.cloned()
+ }
+}
+
pub type Result<V, E = LocError> = std::result::Result<V, E>;
+pub trait ResultExt: Sized {
+ #[must_use]
+ fn with_description<O: Into<String>>(self, msg: impl FnOnce() -> O) -> Self;
+ #[must_use]
+ fn description(self, msg: &str) -> Self {
+ self.with_description(|| msg)
+ }
+
+ #[must_use]
+ fn with_description_src<O: Into<String>>(
+ self,
+ src: impl ErrorSource,
+ msg: impl FnOnce() -> O,
+ ) -> Self;
+ #[must_use]
+ fn description_src(self, src: impl ErrorSource, msg: &str) -> Self {
+ self.with_description_src(src, || msg)
+ }
+}
+impl<T> ResultExt for Result<T, LocError> {
+ fn with_description<O: Into<String>>(mut self, msg: impl FnOnce() -> O) -> Self {
+ if let Err(e) = &mut self {
+ let trace = e.trace_mut();
+ trace.0.push(StackTraceElement {
+ location: None,
+ desc: msg().into(),
+ });
+ }
+ self
+ }
+
+ fn with_description_src<O: Into<String>>(
+ mut self,
+ src: impl ErrorSource,
+ msg: impl FnOnce() -> O,
+ ) -> Self {
+ if let Err(e) = &mut self {
+ let trace = e.trace_mut();
+ trace.0.push(StackTraceElement {
+ location: src.to_location(),
+ desc: msg().into(),
+ });
+ }
+ self
+ }
+}
#[macro_export]
macro_rules! throw {
crates/jrsonnet-evaluator/src/evaluate/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/evaluate/mod.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/mod.rs
@@ -34,7 +34,7 @@
pub fn evaluate_field_name(s: State, ctx: Context, field_name: &FieldName) -> Result<Option<IStr>> {
Ok(match field_name {
FieldName::Fixed(n) => Some(n.clone()),
- FieldName::Dyn(expr) => s.push(
+ FieldName::Dyn(expr) => State::push(
CallLocation::new(&expr.1),
|| "evaluating field name".to_string(),
|| {
@@ -184,14 +184,11 @@
.with_add(*plus)
.with_visibility(*visibility)
.with_location(value.1.clone())
- .bindable(
- s.clone(),
- tb!(UnboundValue {
- uctx: uctx.clone(),
- value: value.clone(),
- name: name.clone()
- }),
- )?;
+ .bindable(tb!(UnboundValue {
+ uctx: uctx.clone(),
+ value: value.clone(),
+ name: name.clone()
+ }))?;
}
Member::Field(FieldMember {
name,
@@ -233,15 +230,12 @@
.member(name.clone())
.hide()
.with_location(value.1.clone())
- .bindable(
- s.clone(),
- tb!(UnboundMethod {
- uctx: uctx.clone(),
- value: value.clone(),
- params: params.clone(),
- name: name.clone()
- }),
- )?;
+ .bindable(tb!(UnboundMethod {
+ uctx: uctx.clone(),
+ value: value.clone(),
+ params: params.clone(),
+ name: name.clone()
+ }))?;
}
Member::BindStmt(_) => {}
Member::AssertStmt(stmt) => {
@@ -324,13 +318,10 @@
.member(n)
.with_location(obj.value.1.clone())
.with_add(obj.plus)
- .bindable(
- s.clone(),
- tb!(UnboundValue {
- uctx,
- value: obj.value.clone(),
- }),
- )?;
+ .bindable(tb!(UnboundValue {
+ uctx,
+ value: obj.value.clone(),
+ }))?;
}
v => throw!(FieldMustBeStringGot(v.value_type())),
}
@@ -364,7 +355,7 @@
if tailstrict {
body()?
} else {
- s.push(loc, || format!("function <{}> call", f.name()), body)?
+ State::push(loc, || format!("function <{}> call", f.name()), body)?
}
}
v => throw!(OnlyFunctionsCanBeCalledGot(v.value_type())),
@@ -374,13 +365,13 @@
pub fn evaluate_assert(s: State, ctx: Context, assertion: &AssertStmt) -> Result<()> {
let value = &assertion.0;
let msg = &assertion.1;
- let assertion_result = s.push(
+ let assertion_result = State::push(
CallLocation::new(&value.1),
|| "assertion condition".to_owned(),
|| bool::from_untyped(evaluate(s.clone(), ctx.clone(), value)?, s.clone()),
)?;
if !assertion_result {
- s.push(
+ State::push(
CallLocation::new(&value.1),
|| "assertion failure".to_owned(),
|| {
@@ -432,7 +423,7 @@
Num(v) => Val::new_checked_num(*v)?,
BinaryOp(v1, o, v2) => evaluate_binary_op_special(s, ctx, v1, *o, v2)?,
UnaryOp(o, v) => evaluate_unary_op(*o, &evaluate(s, ctx, v)?)?,
- Var(name) => s.push(
+ Var(name) => State::push(
CallLocation::new(loc),
|| format!("variable <{name}> access"),
|| ctx.binding(name.clone())?.evaluate(s.clone()),
@@ -442,7 +433,7 @@
evaluate(s.clone(), ctx.clone(), value)?,
evaluate(s.clone(), ctx, index)?,
) {
- (Val::Obj(v), Val::Str(key)) => s.push(
+ (Val::Obj(v), Val::Str(key)) => State::push(
CallLocation::new(loc),
|| format!("field <{key}> access"),
|| match v.get(s.clone(), key.clone()) {
@@ -571,7 +562,7 @@
evaluate_assert(s.clone(), ctx.clone(), assert)?;
evaluate(s, ctx, returned)?
}
- ErrorStmt(e) => s.push(
+ ErrorStmt(e) => State::push(
CallLocation::new(loc),
|| "error statement".to_owned(),
|| {
@@ -585,7 +576,7 @@
cond_then,
cond_else,
} => {
- if s.push(
+ if State::push(
CallLocation::new(loc),
|| "if condition".to_owned(),
|| bool::from_untyped(evaluate(s.clone(), ctx.clone(), &cond.0)?, s.clone()),
@@ -607,7 +598,7 @@
desc: &'static str,
) -> Result<Option<T>> {
if let Some(value) = expr {
- Ok(Some(s.push(
+ Ok(Some(State::push(
loc,
|| format!("slice {desc}"),
|| T::from_untyped(evaluate(s.clone(), ctx.clone(), value)?, s.clone()),
@@ -630,7 +621,7 @@
let tmp = loc.clone().0;
let resolved_path = s.resolve_from(tmp.source_path(), path as &str)?;
match i {
- Import(_) => s.push(
+ Import(_) => State::push(
CallLocation::new(loc),
|| format!("import {:?}", path.clone()),
|| s.import_resolved(resolved_path),
crates/jrsonnet-evaluator/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/lib.rs
+++ b/crates/jrsonnet-evaluator/src/lib.rs
@@ -1,5 +1,5 @@
//! jsonnet interpreter implementation
-
+#![cfg_attr(feature = "nightly", feature(thread_local))]
#![deny(unsafe_op_in_unsafe_fn)]
#![warn(
clippy::all,
@@ -51,6 +51,7 @@
mod integrations;
mod map;
mod obj;
+pub mod stack;
pub mod stdlib;
pub mod trace;
pub mod typed;
@@ -67,7 +68,7 @@
pub use ctx::*;
pub use dynamic::*;
-use error::{Error::*, LocError, Result, StackTraceElement};
+use error::{Error::*, LocError, Result, ResultExt};
pub use evaluate::*;
use function::{CallLocation, TlaArg};
use gc::{GcHashMap, TraceBox};
@@ -78,6 +79,7 @@
pub use jrsonnet_parser as parser;
use jrsonnet_parser::*;
pub use obj::*;
+use stack::check_depth;
use trace::{CompactFormat, TraceFormat};
pub use val::{ManifestFormat, Thunk, Val};
@@ -143,8 +145,6 @@
/// Dynamically reconfigurable evaluation settings
pub struct EvaluationSettings {
- /// Limits recursion by limiting the number of stack frames
- pub max_stack: usize,
/// Limits amount of stack trace items preserved
pub max_trace: usize,
/// TLA vars
@@ -162,7 +162,6 @@
impl Default for EvaluationSettings {
fn default() -> Self {
Self {
- max_stack: 200,
max_trace: 20,
context_initializer: Box::new(DummyContextInitializer),
tla_vars: HashMap::default(),
@@ -179,19 +178,7 @@
}
}
}
-
-#[derive(Default)]
-struct EvaluationData {
- /// Used for stack overflow detection, stacktrace is populated on unwind
- stack_depth: usize,
- /// Updated every time stack entry is popt
- stack_generation: usize,
- breakpoints: Breakpoints,
-
- /// Contains file source codes and evaluation results for imports and pretty-printed stacktraces
- files: GcHashMap<SourcePath, FileData>,
-}
struct FileData {
string: Option<IStr>,
bytes: Option<IBytes>,
@@ -217,46 +204,14 @@
parsed: None,
evaluated: None,
evaluating: false,
- }
- }
-}
-
-#[allow(clippy::type_complexity)]
-pub struct Breakpoint {
- loc: ExprLocation,
- collected: RefCell<HashMap<usize, (usize, Vec<Result<Val>>)>>,
-}
-#[derive(Default)]
-struct Breakpoints(Vec<Rc<Breakpoint>>);
-impl Breakpoints {
- fn insert(
- &self,
- stack_depth: usize,
- stack_generation: usize,
- loc: &ExprLocation,
- result: Result<Val>,
- ) -> Result<Val> {
- if self.0.is_empty() {
- return result;
- }
- for item in &self.0 {
- if item.loc.belongs_to(loc) {
- let mut collected = item.collected.borrow_mut();
- let (depth, vals) = collected.entry(stack_generation).or_default();
- if stack_depth > *depth {
- vals.clear();
- }
- vals.push(result.clone());
- }
}
- result
}
}
#[derive(Default)]
pub struct EvaluationStateInternals {
/// Internal state
- data: RefCell<EvaluationData>,
+ file_cache: RefCell<GcHashMap<SourcePath, FileData>>,
/// Settings, safe to change at runtime
settings: RefCell<EvaluationSettings>,
}
@@ -268,8 +223,8 @@
impl State {
/// Should only be called with path retrieved from [`resolve_path`], may panic otherwise
pub fn import_resolved_str(&self, path: SourcePath) -> Result<IStr> {
- let mut data = self.data_mut();
- let mut file = data.files.raw_entry_mut().from_key(&path);
+ let mut file_cache = self.file_cache();
+ let mut file = file_cache.raw_entry_mut().from_key(&path);
let file = match file {
RawEntryMut::Occupied(ref mut d) => d.get_mut(),
@@ -303,8 +258,8 @@
}
/// Should only be called with path retrieved from [`resolve_path`], may panic otherwise
pub fn import_resolved_bin(&self, path: SourcePath) -> Result<IBytes> {
- let mut data = self.data_mut();
- let mut file = data.files.raw_entry_mut().from_key(&path);
+ let mut file_cache = self.file_cache();
+ let mut file = file_cache.raw_entry_mut().from_key(&path);
let file = match file {
RawEntryMut::Occupied(ref mut d) => d.get_mut(),
@@ -330,8 +285,8 @@
}
/// Should only be called with path retrieved from [`resolve_path`], may panic otherwise
pub fn import_resolved(&self, path: SourcePath) -> Result<Val> {
- let mut data = self.data_mut();
- let mut file = data.files.raw_entry_mut().from_key(&path);
+ let mut file_cache = self.file_cache();
+ let mut file = file_cache.raw_entry_mut().from_key(&path);
let file = match file {
RawEntryMut::Occupied(ref mut d) => d.get_mut(),
@@ -383,16 +338,16 @@
throw!(InfiniteRecursionDetected)
}
file.evaluating = true;
- // Dropping file here, as it borrows data, which may be used in evaluation
- drop(data);
+ // Dropping file cache guard here, as evaluation may use this map too
+ drop(file_cache);
let res = evaluate(
self.clone(),
self.create_default_context(file_name),
&parsed,
);
- let mut data = self.data_mut();
- let mut file = data.files.raw_entry_mut().from_key(&path);
+ let mut file_cache = self.file_cache();
+ let mut file = file_cache.raw_entry_mut().from_key(&path);
let file = match file {
RawEntryMut::Occupied(ref mut d) => d.get_mut(),
@@ -426,35 +381,13 @@
/// Executes code creating a new stack frame
pub fn push<T>(
- &self,
e: CallLocation<'_>,
frame_desc: impl FnOnce() -> String,
f: impl FnOnce() -> Result<T>,
) -> Result<T> {
- {
- let mut data = self.data_mut();
- let stack_depth = &mut data.stack_depth;
- if *stack_depth > self.max_stack() {
- // Error creation uses data, so i drop guard here
- drop(data);
- throw!(StackOverflow);
- }
- *stack_depth += 1;
- }
- let result = f();
- {
- let mut data = self.data_mut();
- data.stack_depth -= 1;
- data.stack_generation += 1;
- }
- if let Err(mut err) = result {
- err.trace_mut().0.push(StackTraceElement {
- location: e.0.cloned(),
- desc: frame_desc(),
- });
- return Err(err);
- }
- result
+ let _guard = check_depth()?;
+
+ f().with_description_src(e, frame_desc)
}
/// Executes code creating a new stack frame
@@ -464,64 +397,18 @@
frame_desc: impl FnOnce() -> String,
f: impl FnOnce() -> Result<Val>,
) -> Result<Val> {
- {
- let mut data = self.data_mut();
- let stack_depth = &mut data.stack_depth;
- if *stack_depth > self.max_stack() {
- // Error creation uses data, so i drop guard here
- drop(data);
- throw!(StackOverflow);
- }
- *stack_depth += 1;
- }
- let mut result = f();
- {
- let mut data = self.data_mut();
- data.stack_depth -= 1;
- data.stack_generation += 1;
- result = data
- .breakpoints
- .insert(data.stack_depth, data.stack_generation, e, result);
- }
- if let Err(mut err) = result {
- err.trace_mut().0.push(StackTraceElement {
- location: Some(e.clone()),
- desc: frame_desc(),
- });
- return Err(err);
- }
- result
+ let _guard = check_depth()?;
+
+ f().with_description_src(e, frame_desc)
}
/// Executes code creating a new stack frame
pub fn push_description<T>(
- &self,
frame_desc: impl FnOnce() -> String,
f: impl FnOnce() -> Result<T>,
) -> Result<T> {
- {
- let mut data = self.data_mut();
- let stack_depth = &mut data.stack_depth;
- if *stack_depth > self.max_stack() {
- // Error creation uses data, so i drop guard here
- drop(data);
- throw!(StackOverflow);
- }
- *stack_depth += 1;
- }
- let result = f();
- {
- let mut data = self.data_mut();
- data.stack_depth -= 1;
- data.stack_generation += 1;
- }
- if let Err(mut err) = result {
- err.trace_mut().0.push(StackTraceElement {
- location: None,
- desc: frame_desc(),
- });
- return Err(err);
- }
- result
+ let _guard = check_depth()?;
+
+ f().with_description(frame_desc)
}
/// # Panics
@@ -536,7 +423,7 @@
}
pub fn manifest(&self, val: Val) -> Result<IStr> {
- self.push_description(
+ Self::push_description(
|| "manifestification".to_string(),
|| val.manifest(self.clone(), &self.manifest_format()),
)
@@ -551,7 +438,7 @@
/// If passed value is function then call with set TLA
pub fn with_tla(&self, val: Val) -> Result<Val> {
Ok(match val {
- Val::Func(func) => self.push_description(
+ Val::Func(func) => State::push_description(
|| "during TLA call".to_owned(),
|| {
func.evaluate(
@@ -573,8 +460,8 @@
/// Internals
impl State {
- fn data_mut(&self) -> RefMut<'_, EvaluationData> {
- self.0.data.borrow_mut()
+ fn file_cache(&self) -> RefMut<'_, GcHashMap<SourcePath, FileData>> {
+ self.0.file_cache.borrow_mut()
}
pub fn settings(&self) -> Ref<'_, EvaluationSettings> {
self.0.settings.borrow()
@@ -675,12 +562,5 @@
}
pub fn set_max_trace(&self, trace: usize) {
self.settings_mut().max_trace = trace;
- }
-
- pub fn max_stack(&self) -> usize {
- self.settings().max_stack
- }
- pub fn set_max_stack(&self, trace: usize) {
- self.settings_mut().max_stack = trace;
}
}
crates/jrsonnet-evaluator/src/obj.rsdiffbeforeafterboth1use std::{2 cell::RefCell,3 fmt::Debug,4 hash::{Hash, Hasher},5 ptr::addr_of,6};78use jrsonnet_gcmodule::{Cc, Trace, Weak};9use jrsonnet_interner::IStr;10use jrsonnet_parser::{ExprLocation, Visibility};11use rustc_hash::FxHashMap;1213use crate::{14 error::{Error::*, LocError},15 function::CallLocation,16 gc::{GcHashMap, GcHashSet, TraceBox},17 operator::evaluate_add_op,18 throw, MaybeUnbound, Result, State, Thunk, Unbound, Val,19};2021#[cfg(not(feature = "exp-preserve-order"))]22mod ordering {23 #![allow(24 // This module works as stub for preserve-order feature25 clippy::unused_self,26 )]2728 use jrsonnet_gcmodule::Trace;2930 #[derive(Clone, Copy, Default, Debug, Trace)]31 pub struct FieldIndex;32 impl FieldIndex {33 pub const fn next(self) -> Self {34 Self35 }36 }3738 #[derive(Clone, Copy, Default, Debug, Trace)]39 pub struct SuperDepth;40 impl SuperDepth {41 pub const fn deeper(self) -> Self {42 Self43 }44 }4546 #[derive(Clone, Copy)]47 pub struct FieldSortKey;48 impl FieldSortKey {49 pub const fn new(_: SuperDepth, _: FieldIndex) -> Self {50 Self51 }52 }53}5455#[cfg(feature = "exp-preserve-order")]56mod ordering {57 use std::cmp::Reverse;5859 use jrsonnet_gcmodule::Trace;6061 #[derive(Clone, Copy, Default, Debug, Trace, PartialEq, Eq, PartialOrd, Ord)]62 pub struct FieldIndex(u32);63 impl FieldIndex {64 pub fn next(self) -> Self {65 Self(self.0 + 1)66 }67 }6869 #[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Debug)]70 pub struct SuperDepth(u32);71 impl SuperDepth {72 pub fn deeper(self) -> Self {73 Self(self.0 + 1)74 }75 }7677 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]78 pub struct FieldSortKey(Reverse<SuperDepth>, FieldIndex);79 impl FieldSortKey {80 pub fn new(depth: SuperDepth, index: FieldIndex) -> Self {81 Self(Reverse(depth), index)82 }83 pub fn collide(self, other: Self) -> Self {84 if self.0 .0 > other.0 .0 {85 self86 } else if self.0 .0 < other.0 .0 {87 other88 } else {89 unreachable!("object can't have two fields with same name")90 }91 }92 }93}9495use ordering::*;9697#[allow(clippy::module_name_repetitions)]98#[derive(Debug, Trace)]99pub struct ObjMember {100 pub add: bool,101 pub visibility: Visibility,102 original_index: FieldIndex,103 pub invoke: MaybeUnbound,104 pub location: Option<ExprLocation>,105}106107pub trait ObjectAssertion: Trace {108 fn run(&self, s: State, super_obj: Option<ObjValue>, this: Option<ObjValue>) -> Result<()>;109}110111// Field => This112113#[derive(Trace)]114enum CacheValue {115 Cached(Val),116 NotFound,117 Pending,118 Errored(LocError),119}120121#[allow(clippy::module_name_repetitions)]122#[derive(Trace)]123#[trace(tracking(force))]124pub struct ObjValueInternals {125 sup: Option<ObjValue>,126 this: Option<ObjValue>,127128 assertions: Cc<Vec<TraceBox<dyn ObjectAssertion>>>,129 assertions_ran: RefCell<GcHashSet<ObjValue>>,130 this_entries: Cc<GcHashMap<IStr, ObjMember>>,131 value_cache: RefCell<GcHashMap<IStr, CacheValue>>,132}133134#[derive(Clone, Trace)]135pub struct WeakObjValue(#[trace(skip)] pub(crate) Weak<ObjValueInternals>);136137impl PartialEq for WeakObjValue {138 fn eq(&self, other: &Self) -> bool {139 Weak::ptr_eq(&self.0, &other.0)140 }141}142143impl Eq for WeakObjValue {}144impl Hash for WeakObjValue {145 fn hash<H: Hasher>(&self, hasher: &mut H) {146 // Safety: usize is POD147 let addr = unsafe { *std::ptr::addr_of!(self.0).cast() };148 hasher.write_usize(addr);149 }150}151152#[allow(clippy::module_name_repetitions)]153#[derive(Clone, Trace)]154pub struct ObjValue(pub(crate) Cc<ObjValueInternals>);155impl Debug for ObjValue {156 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {157 if let Some(super_obj) = self.0.sup.as_ref() {158 if f.alternate() {159 write!(f, "{super_obj:#?}")?;160 } else {161 write!(f, "{super_obj:?}")?;162 }163 write!(f, " + ")?;164 }165 let mut debug = f.debug_struct("ObjValue");166 for (name, member) in self.0.this_entries.iter() {167 debug.field(name, member);168 }169 debug.finish_non_exhaustive()170 }171}172173impl ObjValue {174 pub fn new(175 sup: Option<Self>,176 this_entries: Cc<GcHashMap<IStr, ObjMember>>,177 assertions: Cc<Vec<TraceBox<dyn ObjectAssertion>>>,178 ) -> Self {179 Self(Cc::new(ObjValueInternals {180 sup,181 this: None,182 assertions,183 assertions_ran: RefCell::new(GcHashSet::new()),184 this_entries,185 value_cache: RefCell::new(GcHashMap::new()),186 }))187 }188 pub fn new_empty() -> Self {189 Self::new(None, Cc::new(GcHashMap::new()), Cc::new(Vec::new()))190 }191 #[must_use]192 pub fn extend_from(&self, sup: Self) -> Self {193 match &self.0.sup {194 None => Self::new(195 Some(sup),196 self.0.this_entries.clone(),197 self.0.assertions.clone(),198 ),199 Some(v) => Self::new(200 Some(v.extend_from(sup)),201 self.0.this_entries.clone(),202 self.0.assertions.clone(),203 ),204 }205 }206 pub(crate) fn extend_with_raw_member(self, key: IStr, value: ObjMember) -> Self {207 let mut new = GcHashMap::with_capacity(1);208 new.insert(key, value);209 Self::new(Some(self), Cc::new(new), Cc::new(Vec::new()))210 }211 pub fn extend_field(&mut self, name: IStr) -> ObjMemberBuilder<ExtendBuilder<'_>> {212 ObjMemberBuilder::new(ExtendBuilder(self), name, FieldIndex::default())213 }214215 #[must_use]216 pub fn with_this(&self, this: Self) -> Self {217 Self(Cc::new(ObjValueInternals {218 sup: self.0.sup.clone(),219 assertions: self.0.assertions.clone(),220 assertions_ran: RefCell::new(GcHashSet::new()),221 this: Some(this),222 this_entries: self.0.this_entries.clone(),223 value_cache: RefCell::new(GcHashMap::new()),224 }))225 }226227 pub fn len(&self) -> usize {228 self.fields_visibility()229 .into_iter()230 .filter(|(_, (visible, _))| *visible)231 .count()232 }233234 pub fn is_empty(&self) -> bool {235 if !self.0.this_entries.is_empty() {236 return false;237 }238 self.0.sup.as_ref().map_or(true, Self::is_empty)239 }240241 /// Run callback for every field found in object242 ///243 /// Returns true if ended prematurely244 pub(crate) fn enum_fields(245 &self,246 depth: SuperDepth,247 handler: &mut impl FnMut(SuperDepth, &IStr, &ObjMember) -> bool,248 ) -> bool {249 if let Some(s) = &self.0.sup {250 if s.enum_fields(depth.deeper(), handler) {251 return true;252 }253 }254 for (name, member) in self.0.this_entries.iter() {255 if handler(depth, name, member) {256 return true;257 }258 }259 false260 }261262 pub fn fields_visibility(&self) -> FxHashMap<IStr, (bool, FieldSortKey)> {263 let mut out = FxHashMap::default();264 self.enum_fields(SuperDepth::default(), &mut |depth, name, member| {265 let new_sort_key = FieldSortKey::new(depth, member.original_index);266 let entry = out.entry(name.clone());267 let (visible, _) = entry.or_insert((true, new_sort_key));268 match member.visibility {269 Visibility::Normal => {}270 Visibility::Hidden => {271 *visible = false;272 }273 Visibility::Unhide => {274 *visible = true;275 }276 };277 false278 });279 out280 }281 pub fn fields_ex(282 &self,283 include_hidden: bool,284 #[cfg(feature = "exp-preserve-order")] preserve_order: bool,285 ) -> Vec<IStr> {286 #[cfg(feature = "exp-preserve-order")]287 if preserve_order {288 let (mut fields, mut keys): (Vec<_>, Vec<_>) = self289 .fields_visibility()290 .into_iter()291 .filter(|(_, (visible, _))| include_hidden || *visible)292 .enumerate()293 .map(|(idx, (k, (_, sk)))| (k, (sk, idx)))294 .unzip();295 keys.sort_unstable_by_key(|v| v.0);296 // Reorder in-place by resulting indexes297 for i in 0..fields.len() {298 let x = fields[i].clone();299 let mut j = i;300 loop {301 let k = keys[j].1;302 keys[j].1 = j;303 if k == i {304 break;305 }306 fields[j] = fields[k].clone();307 j = k308 }309 fields[j] = x;310 }311 return fields;312 }313314 let mut fields: Vec<_> = self315 .fields_visibility()316 .into_iter()317 .filter(|(_, (visible, _))| include_hidden || *visible)318 .map(|(k, _)| k)319 .collect();320 fields.sort_unstable();321 fields322 }323 pub fn fields(&self, #[cfg(feature = "exp-preserve-order")] preserve_order: bool) -> Vec<IStr> {324 self.fields_ex(325 false,326 #[cfg(feature = "exp-preserve-order")]327 preserve_order,328 )329 }330331 pub fn field_visibility(&self, name: IStr) -> Option<Visibility> {332 if let Some(m) = self.0.this_entries.get(&name) {333 Some(match &m.visibility {334 Visibility::Normal => self335 .0336 .sup337 .as_ref()338 .and_then(|super_obj| super_obj.field_visibility(name))339 .unwrap_or(Visibility::Normal),340 v => *v,341 })342 } else if let Some(super_obj) = &self.0.sup {343 super_obj.field_visibility(name)344 } else {345 None346 }347 }348349 fn has_field_include_hidden(&self, name: IStr) -> bool {350 if self.0.this_entries.contains_key(&name) {351 true352 } else if let Some(super_obj) = &self.0.sup {353 super_obj.has_field_include_hidden(name)354 } else {355 false356 }357 }358359 pub fn has_field_ex(&self, name: IStr, include_hidden: bool) -> bool {360 if include_hidden {361 self.has_field_include_hidden(name)362 } else {363 self.has_field(name)364 }365 }366 pub fn has_field(&self, name: IStr) -> bool {367 self.field_visibility(name)368 .map_or(false, |v| v.is_visible())369 }370371 pub fn get(&self, s: State, key: IStr) -> Result<Option<Val>> {372 self.run_assertions(s.clone())?;373 if let Some(v) = self.0.value_cache.borrow().get(&key) {374 return Ok(match v {375 CacheValue::Cached(v) => Some(v.clone()),376 CacheValue::NotFound => None,377 CacheValue::Pending => throw!(InfiniteRecursionDetected),378 CacheValue::Errored(e) => return Err(e.clone()),379 });380 }381 self.0382 .value_cache383 .borrow_mut()384 .insert(key.clone(), CacheValue::Pending);385 let value = self386 .get_raw(387 s,388 key.clone(),389 self.0.this.clone().unwrap_or_else(|| self.clone()),390 )391 .map_err(|e| {392 self.0393 .value_cache394 .borrow_mut()395 .insert(key.clone(), CacheValue::Errored(e.clone()));396 e397 })?;398 self.0.value_cache.borrow_mut().insert(399 key,400 value401 .as_ref()402 .map_or(CacheValue::NotFound, |v| CacheValue::Cached(v.clone())),403 );404 Ok(value)405 }406407 fn get_raw(&self, s: State, key: IStr, real_this: Self) -> Result<Option<Val>> {408 match (self.0.this_entries.get(&key), &self.0.sup) {409 (Some(k), None) => Ok(Some(self.evaluate_this(s, k, real_this)?)),410 (Some(k), Some(super_obj)) => {411 let our = self.evaluate_this(s.clone(), k, real_this.clone())?;412 if k.add {413 super_obj414 .get_raw(s.clone(), key, real_this)?415 .map_or(Ok(Some(our.clone())), |v| {416 Ok(Some(evaluate_add_op(s.clone(), &v, &our)?))417 })418 } else {419 Ok(Some(our))420 }421 }422 (None, Some(super_obj)) => super_obj.get_raw(s, key, real_this),423 (None, None) => Ok(None),424 }425 }426 fn evaluate_this(&self, s: State, v: &ObjMember, real_this: Self) -> Result<Val> {427 v.invoke428 .evaluate(s.clone(), self.0.sup.clone(), Some(real_this))?429 .evaluate(s)430 }431432 fn run_assertions_raw(&self, s: State, real_this: &Self) -> Result<()> {433 if self.0.assertions_ran.borrow_mut().insert(real_this.clone()) {434 for assertion in self.0.assertions.iter() {435 if let Err(e) =436 assertion.run(s.clone(), self.0.sup.clone(), Some(real_this.clone()))437 {438 self.0.assertions_ran.borrow_mut().remove(real_this);439 return Err(e);440 }441 }442 if let Some(super_obj) = &self.0.sup {443 super_obj.run_assertions_raw(s, real_this)?;444 }445 }446 Ok(())447 }448 pub fn run_assertions(&self, s: State) -> Result<()> {449 self.run_assertions_raw(s, self)450 }451452 pub fn ptr_eq(a: &Self, b: &Self) -> bool {453 Cc::ptr_eq(&a.0, &b.0)454 }455 pub fn downgrade(self) -> WeakObjValue {456 WeakObjValue(self.0.downgrade())457 }458}459460impl PartialEq for ObjValue {461 fn eq(&self, other: &Self) -> bool {462 Cc::ptr_eq(&self.0, &other.0)463 }464}465466impl Eq for ObjValue {}467impl Hash for ObjValue {468 fn hash<H: Hasher>(&self, hasher: &mut H) {469 hasher.write_usize(addr_of!(*self.0) as usize);470 }471}472473#[allow(clippy::module_name_repetitions)]474pub struct ObjValueBuilder {475 sup: Option<ObjValue>,476 map: GcHashMap<IStr, ObjMember>,477 assertions: Vec<TraceBox<dyn ObjectAssertion>>,478 next_field_index: FieldIndex,479}480impl ObjValueBuilder {481 pub fn new() -> Self {482 Self::with_capacity(0)483 }484 pub fn with_capacity(capacity: usize) -> Self {485 Self {486 sup: None,487 map: GcHashMap::with_capacity(capacity),488 assertions: Vec::new(),489 next_field_index: FieldIndex::default(),490 }491 }492 pub fn reserve_asserts(&mut self, capacity: usize) -> &mut Self {493 self.assertions.reserve_exact(capacity);494 self495 }496 pub fn with_super(&mut self, super_obj: ObjValue) -> &mut Self {497 self.sup = Some(super_obj);498 self499 }500501 pub fn assert(&mut self, assertion: TraceBox<dyn ObjectAssertion>) -> &mut Self {502 self.assertions.push(assertion);503 self504 }505 pub fn member(&mut self, name: IStr) -> ObjMemberBuilder<ValueBuilder<'_>> {506 let field_index = self.next_field_index;507 self.next_field_index = self.next_field_index.next();508 ObjMemberBuilder::new(ValueBuilder(self), name, field_index)509 }510511 pub fn build(self) -> ObjValue {512 ObjValue::new(self.sup, Cc::new(self.map), Cc::new(self.assertions))513 }514}515impl Default for ObjValueBuilder {516 fn default() -> Self {517 Self::with_capacity(0)518 }519}520521#[allow(clippy::module_name_repetitions)]522#[must_use = "value not added unless binding() was called"]523pub struct ObjMemberBuilder<Kind> {524 kind: Kind,525 name: IStr,526 add: bool,527 visibility: Visibility,528 original_index: FieldIndex,529 location: Option<ExprLocation>,530}531532#[allow(clippy::missing_const_for_fn)]533impl<Kind> ObjMemberBuilder<Kind> {534 pub(crate) fn new(kind: Kind, name: IStr, original_index: FieldIndex) -> Self {535 Self {536 kind,537 name,538 original_index,539 add: false,540 visibility: Visibility::Normal,541 location: None,542 }543 }544545 pub const fn with_add(mut self, add: bool) -> Self {546 self.add = add;547 self548 }549 pub fn add(self) -> Self {550 self.with_add(true)551 }552 pub fn with_visibility(mut self, visibility: Visibility) -> Self {553 self.visibility = visibility;554 self555 }556 pub fn hide(self) -> Self {557 self.with_visibility(Visibility::Hidden)558 }559 pub fn with_location(mut self, location: ExprLocation) -> Self {560 self.location = Some(location);561 self562 }563 fn build_member(self, binding: MaybeUnbound) -> (Kind, IStr, ObjMember) {564 (565 self.kind,566 self.name,567 ObjMember {568 add: self.add,569 visibility: self.visibility,570 original_index: self.original_index,571 invoke: binding,572 location: self.location,573 },574 )575 }576}577578pub struct ValueBuilder<'v>(&'v mut ObjValueBuilder);579impl ObjMemberBuilder<ValueBuilder<'_>> {580 pub fn value(self, s: State, value: Val) -> Result<()> {581 self.binding(s, MaybeUnbound::Bound(Thunk::evaluated(value)))582 }583 pub fn bindable(584 self,585 s: State,586 bindable: TraceBox<dyn Unbound<Bound = Thunk<Val>>>,587 ) -> Result<()> {588 self.binding(s, MaybeUnbound::Unbound(Cc::new(bindable)))589 }590 pub fn binding(self, s: State, binding: MaybeUnbound) -> Result<()> {591 let (receiver, name, member) = self.build_member(binding);592 let location = member.location.clone();593 let old = receiver.0.map.insert(name.clone(), member);594 if old.is_some() {595 s.push(596 CallLocation(location.as_ref()),597 || format!("field <{}> initializtion", name.clone()),598 || throw!(DuplicateFieldName(name.clone())),599 )?;600 }601 Ok(())602 }603}604605pub struct ExtendBuilder<'v>(&'v mut ObjValue);606impl ObjMemberBuilder<ExtendBuilder<'_>> {607 pub fn value(self, value: Val) {608 self.binding(MaybeUnbound::Bound(Thunk::evaluated(value)));609 }610 pub fn bindable(self, bindable: TraceBox<dyn Unbound<Bound = Thunk<Val>>>) {611 self.binding(MaybeUnbound::Unbound(Cc::new(bindable)));612 }613 pub fn binding(self, binding: MaybeUnbound) {614 let (receiver, name, member) = self.build_member(binding);615 let new = receiver.0.clone();616 *receiver.0 = new.extend_with_raw_member(name, member);617 }618}crates/jrsonnet-evaluator/src/stack.rsdiffbeforeafterboth--- /dev/null
+++ b/crates/jrsonnet-evaluator/src/stack.rs
@@ -0,0 +1,109 @@
+use std::{cell::Cell, marker::PhantomData};
+
+use crate::error::{Error, LocError};
+
+struct StackLimit {
+ max_stack_size: Cell<usize>,
+ current_depth: Cell<usize>,
+}
+
+#[cfg(feature = "nightly")]
+#[thread_local]
+static STACK_LIMIT: StackLimit = StackLimit {
+ max_stack_size: Cell::new(200),
+ current_depth: Cell::new(0),
+};
+#[cfg(not(feature = "nightly"))]
+thread_local! {
+ static STACK_LIMIT: StackLimit = StackLimit {
+ max_stack_size: Cell::new(200),
+ current_depth: Cell::new(0),
+ };
+}
+
+pub struct StackOverflowError;
+impl From<StackOverflowError> for Error {
+ fn from(_: StackOverflowError) -> Self {
+ Error::StackOverflow
+ }
+}
+impl From<StackOverflowError> for LocError {
+ fn from(_: StackOverflowError) -> Self {
+ Error::StackOverflow.into()
+ }
+}
+
+/// Used to implement stack depth limitation
+pub struct StackDepthGuard(PhantomData<()>);
+impl Drop for StackDepthGuard {
+ #[cfg(feature = "nightly")]
+ fn drop(&mut self) {
+ STACK_LIMIT
+ .current_depth
+ .set(STACK_LIMIT.current_depth.get() - 1)
+ }
+ #[cfg(not(feature = "nightly"))]
+ fn drop(&mut self) {
+ STACK_LIMIT.with(|limit| limit.current_depth.set(limit.current_depth.get() - 1));
+ }
+}
+
+// #[cfg(feature = "nightly")]
+pub fn check_depth() -> Result<StackDepthGuard, StackOverflowError> {
+ fn internal(limit: &StackLimit) -> Result<StackDepthGuard, StackOverflowError> {
+ let current = limit.current_depth.get();
+ if current < limit.max_stack_size.get() {
+ limit.current_depth.set(current + 1);
+ Ok(StackDepthGuard(PhantomData))
+ } else {
+ Err(StackOverflowError)
+ }
+ }
+ #[cfg(feature = "nightly")]
+ {
+ internal(&STACK_LIMIT)
+ }
+ #[cfg(not(feature = "nightly"))]
+ {
+ STACK_LIMIT.with(internal)
+ }
+}
+
+pub struct StackDepthLimitOverrideGuard {
+ old_limit: usize,
+}
+impl Drop for StackDepthLimitOverrideGuard {
+ #[cfg(feature = "nightly")]
+ fn drop(&mut self) {
+ STACK_LIMIT.max_stack_size.set(self.old_limit)
+ }
+ #[cfg(not(feature = "nightly"))]
+ fn drop(&mut self) {
+ STACK_LIMIT.with(|limit| limit.max_stack_size.set(self.old_limit));
+ }
+}
+
+pub fn limit_stack_depth(depth_limit: usize) -> StackDepthLimitOverrideGuard {
+ fn internal(limit: &StackLimit, depth_limit: usize) -> StackDepthLimitOverrideGuard {
+ let old_limit = limit.max_stack_size.get();
+ let current_depth = limit.current_depth.get();
+
+ limit.max_stack_size.set(current_depth + depth_limit);
+ StackDepthLimitOverrideGuard { old_limit }
+ }
+ #[cfg(feature = "nightly")]
+ {
+ internal(&STACK_LIMIT, depth_limit)
+ }
+ #[cfg(not(feature = "nightly"))]
+ {
+ STACK_LIMIT.with(|limit| internal(limit, depth_limit))
+ }
+}
+
+/// Like [`limit_stack_depth`], but set depth is not guarded, and will be kept
+///
+/// Used to implement `set_max_stack` in C api, prefer to use [`limit_stack_depth`] instead
+pub fn set_stack_depth_limit(depth_limit: usize) {
+ std::mem::forget(limit_stack_depth(depth_limit));
+}
crates/jrsonnet-evaluator/src/stdlib/manifest.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/stdlib/manifest.rs
+++ b/crates/jrsonnet-evaluator/src/stdlib/manifest.rs
@@ -111,7 +111,7 @@
buf.push_str(cur_padding);
escape_string_json_buf(&field, buf);
buf.push_str(options.key_val_sep);
- s.push_description(
+ State::push_description(
|| format!("field <{}> manifestification", field.clone()),
|| {
let value = obj.get(s.clone(), field.clone())?.unwrap();
crates/jrsonnet-evaluator/src/stdlib/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/stdlib/mod.rs
+++ b/crates/jrsonnet-evaluator/src/stdlib/mod.rs
@@ -10,7 +10,7 @@
pub mod manifest;
pub fn std_format(s: State, str: IStr, vals: Val) -> Result<String> {
- s.push(
+ State::push(
CallLocation::native(),
|| format!("std.format of {str}"),
|| {
crates/jrsonnet-evaluator/src/typed/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/typed/mod.rs
+++ b/crates/jrsonnet-evaluator/src/typed/mod.rs
@@ -85,12 +85,11 @@
}
fn push_type_description(
- s: State,
error_reason: impl Fn() -> String,
path: impl Fn() -> ValuePathItem,
item: impl Fn() -> Result<()>,
) -> Result<()> {
- s.push_description(error_reason, || match item() {
+ State::push_description(error_reason, || match item() {
Ok(_) => Ok(()),
Err(mut e) => {
if let Error::TypeError(e) = &mut e.error_mut() {
@@ -170,7 +169,6 @@
Val::Arr(a) => {
for (i, item) in a.iter(s.clone()).enumerate() {
push_type_description(
- s.clone(),
|| format!("array index {i}"),
|| ValuePathItem::Index(i as u64),
|| elem_type.check(s.clone(), &item.clone()?),
@@ -184,7 +182,6 @@
Val::Arr(a) => {
for (i, item) in a.iter(s.clone()).enumerate() {
push_type_description(
- s.clone(),
|| format!("array index {i}"),
|| ValuePathItem::Index(i as u64),
|| elem_type.check(s.clone(), &item.clone()?),
@@ -199,7 +196,6 @@
for (k, v) in elems.iter() {
if let Some(got_v) = obj.get(s.clone(), (*k).into())? {
push_type_description(
- s.clone(),
|| format!("property {k}"),
|| ValuePathItem::Field((*k).into()),
|| v.check(s.clone(), &got_v),
crates/jrsonnet-macros/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-macros/src/lib.rs
+++ b/crates/jrsonnet-macros/src/lib.rs
@@ -299,7 +299,7 @@
cfg_attrs,
} => {
let name = name.as_ref().map(|v| v.as_str()).unwrap_or("<unnamed>");
- let eval = quote! {s.push_description(
+ let eval = quote! {jrsonnet_evaluator::State::push_description(
|| format!("argument <{}> evaluation", #name),
|| <#ty>::from_untyped(value.evaluate(s.clone())?, s.clone()),
)?};
crates/jrsonnet-stdlib/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/lib.rs
+++ b/crates/jrsonnet-stdlib/src/lib.rs
@@ -137,43 +137,36 @@
builder
.member(name.into())
.hide()
- .value(s.clone(), Val::Func(FuncVal::StaticBuiltin(builtin)))
+ .value(Val::Func(FuncVal::StaticBuiltin(builtin)))
.expect("no conflict");
}
builder
.member("extVar".into())
.hide()
- .value(
- s.clone(),
- Val::Func(FuncVal::Builtin(Cc::new(tb!(builtin_ext_var {
- settings: settings.clone()
- })))),
- )
+ .value(Val::Func(FuncVal::Builtin(Cc::new(tb!(builtin_ext_var {
+ settings: settings.clone()
+ })))))
.expect("no conflict");
builder
.member("native".into())
.hide()
- .value(
- s.clone(),
- Val::Func(FuncVal::Builtin(Cc::new(tb!(builtin_native {
- settings: settings.clone()
- })))),
- )
+ .value(Val::Func(FuncVal::Builtin(Cc::new(tb!(builtin_native {
+ settings: settings.clone()
+ })))))
.expect("no conflict");
builder
.member("trace".into())
.hide()
- .value(
- s.clone(),
- Val::Func(FuncVal::Builtin(Cc::new(tb!(builtin_trace { settings })))),
- )
+ .value(Val::Func(FuncVal::Builtin(Cc::new(tb!(builtin_trace {
+ settings
+ })))))
.expect("no conflict");
builder
.member("id".into())
.hide()
- .value(s, Val::Func(FuncVal::Id))
+ .value(Val::Func(FuncVal::Id))
.expect("no conflict");
builder.build()