difftreelog
Merge pull request #45 from CertainLach/gc-v2
in: master
Implement tracing Gc with rust-gc
35 files changed
Cargo.lockdiffbeforeafterboth--- a/Cargo.lock
+++ b/Cargo.lock
@@ -100,12 +100,6 @@
]
[[package]]
-name = "closure"
-version = "0.3.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d6173fd61b610d15a7566dd7b7620775627441c4ab9dac8906e17cb93a24b782"
-
-[[package]]
name = "hashbrown"
version = "0.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -164,6 +158,7 @@
dependencies = [
"clap",
"jrsonnet-evaluator",
+ "jrsonnet-gc",
"jrsonnet-parser",
]
@@ -175,7 +170,7 @@
"anyhow",
"base64",
"bincode",
- "closure",
+ "jrsonnet-gc",
"jrsonnet-interner",
"jrsonnet-parser",
"jrsonnet-stdlib",
@@ -189,9 +184,31 @@
]
[[package]]
+name = "jrsonnet-gc"
+version = "0.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "68da8bc2f00117b1373bb8877af03b1d391e4c4800e6585d7279e5b99c919dde"
+dependencies = [
+ "jrsonnet-gc-derive",
+]
+
+[[package]]
+name = "jrsonnet-gc-derive"
+version = "0.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "adcba9c387b64b054f06cc4d724905296e21edeeb7506847f3299117a2d92d12"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+ "synstructure",
+]
+
+[[package]]
name = "jrsonnet-interner"
version = "0.3.8"
dependencies = [
+ "jrsonnet-gc",
"rustc-hash",
"serde",
]
@@ -200,6 +217,7 @@
name = "jrsonnet-parser"
version = "0.3.8"
dependencies = [
+ "jrsonnet-gc",
"jrsonnet-interner",
"jrsonnet-stdlib",
"peg",
@@ -215,6 +233,7 @@
name = "jrsonnet-types"
version = "0.3.8"
dependencies = [
+ "jrsonnet-gc",
"peg",
]
@@ -223,6 +242,7 @@
version = "0.3.8"
dependencies = [
"jrsonnet-evaluator",
+ "jrsonnet-gc",
"jrsonnet-parser",
]
@@ -405,6 +425,18 @@
]
[[package]]
+name = "synstructure"
+version = "0.12.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b834f2d66f734cb897113e34aaff2f1ab4719ca946f9a7358dba8f8064148701"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+ "unicode-xid",
+]
+
+[[package]]
name = "termcolor"
version = "1.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
bindings/jsonnet/Cargo.tomldiffbeforeafterboth--- a/bindings/jsonnet/Cargo.toml
+++ b/bindings/jsonnet/Cargo.toml
@@ -10,6 +10,7 @@
[dependencies]
jrsonnet-evaluator = { path = "../../crates/jrsonnet-evaluator", version = "0.3.8" }
jrsonnet-parser = { path = "../../crates/jrsonnet-parser", version = "0.3.8" }
+jrsonnet-gc = { version = "0.4.2", features = ["derive"] }
[lib]
crate-type = ["cdylib"]
bindings/jsonnet/src/native.rsdiffbeforeafterboth--- a/bindings/jsonnet/src/native.rs
+++ b/bindings/jsonnet/src/native.rs
@@ -1,8 +1,14 @@
-use jrsonnet_evaluator::{error::Error, native::NativeCallback, EvaluationState, Val};
+use jrsonnet_evaluator::{
+ error::{Error, LocError},
+ native::{NativeCallback, NativeCallbackHandler},
+ EvaluationState, Val,
+};
+use jrsonnet_gc::{unsafe_empty_trace, Finalize, Gc, Trace};
use jrsonnet_parser::{Param, ParamsDesc};
use std::{
ffi::{c_void, CStr},
os::raw::{c_char, c_int},
+ path::Path,
rc::Rc,
};
@@ -12,6 +18,39 @@
success: *mut c_int,
) -> *mut Val;
+struct JsonnetNativeCallbackHandler {
+ ctx: *const c_void,
+ cb: JsonnetNativeCallback,
+}
+impl Finalize for JsonnetNativeCallbackHandler {}
+unsafe impl Trace for JsonnetNativeCallbackHandler {
+ unsafe_empty_trace!();
+}
+impl NativeCallbackHandler for JsonnetNativeCallbackHandler {
+ fn call(&self, _from: Option<Rc<Path>>, args: &[Val]) -> Result<Val, LocError> {
+ let mut n_args = Vec::new();
+ for a in args {
+ n_args.push(Some(Box::new(a.clone())));
+ }
+ n_args.push(None);
+ let mut success = 1;
+ let v = unsafe {
+ (self.cb)(
+ self.ctx,
+ &n_args as *const _ as *const *const Val,
+ &mut success,
+ )
+ };
+ let v = unsafe { *Box::from_raw(v) };
+ if success == 1 {
+ Ok(v)
+ } else {
+ let e = v.try_cast_str("native error").expect("error msg");
+ Err(Error::RuntimeError(e).into())
+ }
+ }
+}
+
/// # Safety
#[no_mangle]
pub unsafe extern "C" fn jsonnet_native_callback(
@@ -35,21 +74,9 @@
vm.add_native(
name,
- Rc::new(NativeCallback::new(params, move |_caller, args| {
- let mut n_args = Vec::new();
- for a in args {
- n_args.push(Some(Box::new(a.clone())));
- }
- n_args.push(None);
- let mut success = 1;
- let v = cb(ctx, &n_args as *const _ as *const *const Val, &mut success);
- let v = *Box::from_raw(v);
- if success == 1 {
- Ok(v)
- } else {
- let e = v.try_cast_str("native error").expect("error msg");
- Err(Error::RuntimeError(e).into())
- }
- })),
+ Gc::new(NativeCallback::new(
+ params,
+ Box::new(JsonnetNativeCallbackHandler { ctx, cb }),
+ )),
)
}
bindings/jsonnet/src/val_make.rsdiffbeforeafterboth--- a/bindings/jsonnet/src/val_make.rs
+++ b/bindings/jsonnet/src/val_make.rs
@@ -1,10 +1,10 @@
//! Create values in VM
use jrsonnet_evaluator::{ArrValue, EvaluationState, ObjValue, Val};
+use jrsonnet_gc::Gc;
use std::{
ffi::CStr,
os::raw::{c_char, c_double, c_int},
- rc::Rc,
};
/// # Safety
@@ -38,7 +38,7 @@
#[no_mangle]
pub extern "C" fn jsonnet_json_make_array(_vm: &EvaluationState) -> *mut Val {
- Box::into_raw(Box::new(Val::Arr(ArrValue::Eager(Rc::new(Vec::new())))))
+ Box::into_raw(Box::new(Val::Arr(ArrValue::Eager(Gc::new(Vec::new())))))
}
#[no_mangle]
bindings/jsonnet/src/val_modify.rsdiffbeforeafterboth--- a/bindings/jsonnet/src/val_modify.rs
+++ b/bindings/jsonnet/src/val_modify.rs
@@ -3,8 +3,9 @@
//! In jrsonnet every value is immutable, and this code is probally broken
use jrsonnet_evaluator::{ArrValue, EvaluationState, LazyBinding, LazyVal, ObjMember, Val};
+use jrsonnet_gc::Gc;
use jrsonnet_parser::Visibility;
-use std::{ffi::CStr, os::raw::c_char, rc::Rc};
+use std::{ffi::CStr, os::raw::c_char};
/// # Safety
///
@@ -22,7 +23,7 @@
new.push(item);
}
new.push(LazyVal::new_resolved(val.clone()));
- *arr = Val::Arr(ArrValue::Lazy(Rc::new(new)));
+ *arr = Val::Arr(ArrValue::Lazy(Gc::new(new)));
}
_ => panic!("should receive array"),
}
cmds/jrsonnet/Cargo.tomldiffbeforeafterboth--- a/cmds/jrsonnet/Cargo.toml
+++ b/cmds/jrsonnet/Cargo.toml
@@ -8,15 +8,14 @@
publish = false
[features]
-default = []
+default = ["mimalloc"]
# Use mimalloc as allocator
-mimalloc = []
+mimalloc = ["mimallocator"]
[dependencies]
jrsonnet-evaluator = { path = "../../crates/jrsonnet-evaluator", version = "0.3.8" }
jrsonnet-parser = { path = "../../crates/jrsonnet-parser", version = "0.3.8" }
jrsonnet-cli = { path = "../../crates/jrsonnet-cli", version = "0.3.8" }
-# TODO: Fix mimalloc compile errors, and use them
mimallocator = { version = "0.1.3", optional = true }
thiserror = "1.0"
cmds/jrsonnet/src/main.rsdiffbeforeafterboth--- a/cmds/jrsonnet/src/main.rs
+++ b/cmds/jrsonnet/src/main.rs
@@ -1,5 +1,5 @@
use clap::{AppSettings, Clap, IntoApp};
-use jrsonnet_cli::{ConfigureState, GeneralOpts, InputOpts, ManifestOpts, OutputOpts};
+use jrsonnet_cli::{ConfigureState, GcOpts, GeneralOpts, InputOpts, ManifestOpts, OutputOpts};
use jrsonnet_evaluator::{error::LocError, EvaluationState, ManifestFormat};
use std::{
fs::{create_dir_all, File},
@@ -61,6 +61,8 @@
output: OutputOpts,
#[clap(flatten)]
debug: DebugOpts,
+ #[clap(flatten)]
+ gc: GcOpts,
}
fn main() {
@@ -114,6 +116,7 @@
}
fn main_catch(opts: Opts) -> bool {
+ let _printer = opts.gc.stats_printer();
let state = EvaluationState::default();
if let Err(e) = main_real(&state, opts) {
if let Error::Evaluation(e) = e {
@@ -127,6 +130,7 @@
}
fn main_real(state: &EvaluationState, opts: Opts) -> Result<(), Error> {
+ opts.gc.configure_global();
opts.general.configure(&state)?;
opts.manifest.configure(&state)?;
crates/jrsonnet-cli/Cargo.tomldiffbeforeafterboth--- a/crates/jrsonnet-cli/Cargo.toml
+++ b/crates/jrsonnet-cli/Cargo.toml
@@ -10,6 +10,7 @@
[dependencies]
jrsonnet-evaluator = { path = "../../crates/jrsonnet-evaluator", version = "0.3.6", features = ["explaining-traces"] }
jrsonnet-parser = { path = "../../crates/jrsonnet-parser", version = "0.3.6" }
+jrsonnet-gc = { version = "0.4.2", features = ["derive", "unstable-config", "unstable-stats"] }
[dependencies.clap]
git = "https://github.com/clap-rs/clap"
crates/jrsonnet-cli/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-cli/src/lib.rs
+++ b/crates/jrsonnet-cli/src/lib.rs
@@ -95,3 +95,55 @@
Ok(())
}
}
+
+#[derive(Clap)]
+#[clap(help_heading = "GARBAGE COLLECTION")]
+pub struct GcOpts {
+ /// Min bytes allocated to start garbage collection
+ #[clap(long, default_value = "20000000")]
+ gc_initial_threshold: usize,
+ /// How much heap should grow after unsuccessful garbage collection
+ #[clap(long)]
+ gc_used_space_ratio: Option<f64>,
+ /// Do not skip gc on exit
+ #[clap(long)]
+ gc_collect_on_exit: bool,
+ /// Print gc stats before exit
+ #[clap(long)]
+ gc_print_stats: bool,
+ /// Force garbage collection before printing stats
+ /// Useful for checking for memory leaks
+ /// Does nothing useless --gc-print-stats is specified
+ #[clap(long)]
+ gc_collect_before_printing_stats: bool,
+}
+impl GcOpts {
+ pub fn stats_printer(&self) -> Option<GcStatsPrinter> {
+ self.gc_print_stats
+ .then(|| GcStatsPrinter(self.gc_collect_before_printing_stats))
+ }
+ pub fn configure_global(&self) {
+ jrsonnet_gc::configure(|config| {
+ config.leak_on_drop = !self.gc_collect_on_exit;
+ config.threshold = self.gc_initial_threshold;
+ if let Some(used_space_ratio) = self.gc_used_space_ratio {
+ config.used_space_ratio = used_space_ratio;
+ }
+ });
+ }
+}
+pub struct GcStatsPrinter(bool);
+impl Drop for GcStatsPrinter {
+ fn drop(&mut self) {
+ if self.0 {
+ jrsonnet_gc::force_collect()
+ }
+ eprintln!("=== GC STATS ===");
+ jrsonnet_gc::configure(|c| {
+ eprintln!("Final threshold: {:?}", c.threshold);
+ });
+ let stats = jrsonnet_gc::stats();
+ eprintln!("Collections performed: {}", stats.collections_performed);
+ eprintln!("Bytes still allocated: {}", stats.bytes_allocated);
+ }
+}
crates/jrsonnet-evaluator/Cargo.tomldiffbeforeafterboth--- a/crates/jrsonnet-evaluator/Cargo.toml
+++ b/crates/jrsonnet-evaluator/Cargo.toml
@@ -30,13 +30,12 @@
jrsonnet-types = { path = "../jrsonnet-types", version = "0.3.8" }
pathdiff = "0.2.0"
-closure = "0.3.0"
-
md5 = "0.7.0"
base64 = "0.13.0"
rustc-hash = "1.1.0"
thiserror = "1.0"
+jrsonnet-gc = { version = "0.4.2", features = ["derive"] }
[dependencies.anyhow]
version = "1.0"
crates/jrsonnet-evaluator/README.mddiffbeforeafterboth--- a/crates/jrsonnet-evaluator/README.md
+++ b/crates/jrsonnet-evaluator/README.md
@@ -6,9 +6,6 @@
jsonnet stdlib is embedded into evaluator, but there is different modes for this:
-- `codegenerated-stdlib`
- - generates source code for reproducing stdlib AST ([Example](https://gist.githubusercontent.com/CertainLach/7b3149df556f3406f5e9368aaa9f32ec/raw/0c80d8ab9aa7b9288c6219a2779cb2ab37287669/a.rs))
- - fastest on interpretation, slowest on compilation (it takes more than 5 minutes to optimize them by llvm)
- `serialized-stdlib`
- serializes standard library AST using serde
- slower than `codegenerated-stdlib` at runtime, but have no compilation speed penality
@@ -23,8 +20,6 @@
Can also be run via `cargo bench`
```markdown
-# codegenerated-stdlib
-test tests::bench_codegen ... bench: 401,696 ns/iter (+/- 38,521)
# serialized-stdlib
test tests::bench_serialize ... bench: 1,763,999 ns/iter (+/- 76,211)
# none
@@ -34,7 +29,3 @@
## Intrinsics
Some functions from stdlib are implemented as intrinsics
-
-### Intrinsic handling
-
-If indexed jsonnet object has field '__intrinsic_namespace__' of type 'string', then any not found field/method is resolved as `Val::Intrinsic(__intrinsic_namespace__, name)`
crates/jrsonnet-evaluator/src/builtin/format.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/builtin/format.rs
+++ b/crates/jrsonnet-evaluator/src/builtin/format.rs
@@ -2,11 +2,13 @@
#![allow(clippy::too_many_arguments)]
use crate::{error::Error::*, throw, LocError, ObjValue, Result, Val};
+use jrsonnet_gc::Trace;
use jrsonnet_interner::IStr;
use jrsonnet_types::ValType;
use thiserror::Error;
-#[derive(Debug, Clone, Error)]
+#[derive(Debug, Clone, Error, Trace)]
+#[trivially_drop]
pub enum FormatError {
#[error("truncated format code")]
TruncatedFormatCode,
crates/jrsonnet-evaluator/src/builtin/manifest.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/builtin/manifest.rs
+++ b/crates/jrsonnet-evaluator/src/builtin/manifest.rs
@@ -126,6 +126,7 @@
buf.push('}');
}
Val::Func(_) => throw!(RuntimeError("tried to manifest function".into())),
+ Val::DebugGcTraceValue(v) => manifest_json_ex_buf(&v.value, buf, cur_padding, options)?,
};
Ok(())
}
crates/jrsonnet-evaluator/src/builtin/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/builtin/mod.rs
+++ b/crates/jrsonnet-evaluator/src/builtin/mod.rs
@@ -1,10 +1,11 @@
use crate::{
equals,
error::{Error::*, Result},
- parse_args, primitive_equals, push, throw, with_state, ArrValue, Context, EvaluationState,
- FuncVal, LazyVal, Val,
+ parse_args, primitive_equals, push, throw, with_state, ArrValue, Context, DebugGcTraceValue,
+ EvaluationState, FuncVal, LazyVal, Val,
};
use format::{format_arr, format_obj};
+use jrsonnet_gc::Gc;
use jrsonnet_interner::IStr;
use jrsonnet_parser::{ArgsDesc, BinaryOpType, ExprLocation};
use jrsonnet_types::ty;
@@ -68,6 +69,8 @@
("md5".into(), builtin_md5),
("base64".into(), builtin_base64),
("trace".into(), builtin_trace),
+ ("gc".into(), builtin_gc),
+ ("gcTrace".into(), builtin_gc_trace),
("join".into(), builtin_join),
("escapeStringJson".into(), builtin_escape_string_json),
("manifestJsonEx".into(), builtin_manifest_json_ex),
@@ -301,7 +304,7 @@
parse_args!(context, "native", args, 1, [
0, x: ty!(string) => Val::Str;
], {
- Ok(with_state(|s| s.settings().ext_natives.get(&x).cloned()).map(|v| Val::Func(Rc::new(FuncVal::NativeExt(x.clone(), v)))).ok_or(UndefinedExternalFunction(x))?)
+ Ok(with_state(|s| s.settings().ext_natives.get(&x).cloned()).map(|v| Val::Func(Gc::new(FuncVal::NativeExt(x.clone(), v)))).ok_or(UndefinedExternalFunction(x))?)
})
}
@@ -446,6 +449,27 @@
})
}
+fn builtin_gc(context: Context, _loc: Option<&ExprLocation>, args: &ArgsDesc) -> Result<Val> {
+ parse_args!(context, "gc", args, 1, [
+ 0, rest: ty!(any);
+ ], {
+ println!("GC start");
+ jrsonnet_gc::force_collect();
+ println!("GC done");
+
+ Ok(rest)
+ })
+}
+
+fn builtin_gc_trace(context: Context, _loc: Option<&ExprLocation>, args: &ArgsDesc) -> Result<Val> {
+ parse_args!(context, "gcTrace", args, 2, [
+ 0, name: ty!(string) => Val::Str;
+ 1, rest: ty!(any);
+ ], {
+ Ok(DebugGcTraceValue::create(name, rest))
+ })
+}
+
fn builtin_base64(context: Context, _loc: Option<&ExprLocation>, args: &ArgsDesc) -> Result<Val> {
parse_args!(context, "base64", args, 1, [
0, input: ty!((string | (Array<number>)));
crates/jrsonnet-evaluator/src/builtin/sort.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/builtin/sort.rs
+++ b/crates/jrsonnet-evaluator/src/builtin/sort.rs
@@ -2,9 +2,9 @@
error::{Error, LocError, Result},
throw, Context, FuncVal, Val,
};
-use std::rc::Rc;
+use jrsonnet_gc::{Finalize, Gc, Trace};
-#[derive(Debug, Clone, thiserror::Error)]
+#[derive(Debug, Clone, thiserror::Error, Trace, Finalize)]
pub enum SortError {
#[error("sort key should be string or number")]
SortKeyShouldBeStringOrNumber,
@@ -59,13 +59,13 @@
Ok(sort_type)
}
-pub fn sort(ctx: Context, mut values: Rc<Vec<Val>>, key_getter: &FuncVal) -> Result<Rc<Vec<Val>>> {
+pub fn sort(ctx: Context, values: Gc<Vec<Val>>, key_getter: &FuncVal) -> Result<Gc<Vec<Val>>> {
if values.len() <= 1 {
return Ok(values);
}
if key_getter.is_ident() {
- let mvalues = Rc::make_mut(&mut values);
- let sort_type = get_sort_type(mvalues, |k| k)?;
+ let mut mvalues = (*values).clone();
+ let sort_type = get_sort_type(&mut mvalues, |k| k)?;
match sort_type {
SortKeyType::Number => mvalues.sort_by_key(|v| match v {
Val::Num(n) => NonNaNf64(*n),
@@ -77,7 +77,7 @@
}),
SortKeyType::Unknown => unreachable!(),
};
- Ok(values)
+ Ok(Gc::new(mvalues))
} else {
let mut vk = Vec::with_capacity(values.len());
for value in values.iter() {
@@ -98,6 +98,6 @@
}),
SortKeyType::Unknown => unreachable!(),
};
- Ok(Rc::new(vk.into_iter().map(|v| v.0).collect()))
+ Ok(Gc::new(vk.into_iter().map(|v| v.0).collect()))
}
}
crates/jrsonnet-evaluator/src/ctx.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/ctx.rs
+++ b/crates/jrsonnet-evaluator/src/ctx.rs
@@ -1,13 +1,15 @@
use crate::{
- error::Error::*, map::LayeredHashMap, resolved_lazy_val, FutureWrapper, LazyBinding, LazyVal,
- ObjValue, Result, Val,
+ error::Error::*, map::LayeredHashMap, FutureWrapper, LazyBinding, LazyVal, ObjValue, Result,
+ Val,
};
+use jrsonnet_gc::{Gc, Trace};
use jrsonnet_interner::IStr;
use rustc_hash::FxHashMap;
+use std::fmt::Debug;
use std::hash::BuildHasherDefault;
-use std::{fmt::Debug, rc::Rc};
-#[derive(Clone)]
+#[derive(Clone, Trace)]
+#[trivially_drop]
pub struct ContextCreator(pub Context, pub FutureWrapper<FxHashMap<IStr, LazyBinding>>);
impl ContextCreator {
pub fn create(&self, this: Option<ObjValue>, super_obj: Option<ObjValue>) -> Result<Context> {
@@ -20,23 +22,23 @@
}
}
+#[derive(Trace)]
+#[trivially_drop]
struct ContextInternals {
dollar: Option<ObjValue>,
this: Option<ObjValue>,
super_obj: Option<ObjValue>,
- bindings: LayeredHashMap<LazyVal>,
+ bindings: LayeredHashMap,
}
impl Debug for ContextInternals {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- f.debug_struct("Context")
- .field("this", &self.this.as_ref().map(|e| Rc::as_ptr(&e.0)))
- .field("bindings", &self.bindings)
- .finish()
+ f.debug_struct("Context").finish()
}
}
-#[derive(Debug, Clone)]
-pub struct Context(Rc<ContextInternals>);
+#[derive(Debug, Clone, Trace)]
+#[trivially_drop]
+pub struct Context(Gc<ContextInternals>);
impl Context {
pub fn new_future() -> FutureWrapper<Self> {
FutureWrapper::new()
@@ -55,7 +57,7 @@
}
pub fn new() -> Self {
- Self(Rc::new(ContextInternals {
+ Self(Gc::new(ContextInternals {
dollar: None,
this: None,
super_obj: None,
@@ -81,7 +83,7 @@
pub fn with_var(self, name: IStr, value: Val) -> Self {
let mut new_bindings =
FxHashMap::with_capacity_and_hasher(1, BuildHasherDefault::default());
- new_bindings.insert(name, resolved_lazy_val!(value));
+ new_bindings.insert(name, LazyVal::new_resolved(value));
self.extend(new_bindings, None, None, None)
}
@@ -96,40 +98,21 @@
new_this: Option<ObjValue>,
new_super_obj: Option<ObjValue>,
) -> Self {
- match Rc::try_unwrap(self.0) {
- Ok(mut ctx) => {
- // Extended context aren't used by anything else, we can freely mutate it without cloning
- if let Some(dollar) = new_dollar {
- ctx.dollar = Some(dollar);
- }
- if let Some(this) = new_this {
- ctx.this = Some(this);
- }
- if let Some(super_obj) = new_super_obj {
- ctx.super_obj = Some(super_obj);
- }
- if !new_bindings.is_empty() {
- ctx.bindings = ctx.bindings.extend(new_bindings);
- }
- Self(Rc::new(ctx))
- }
- Err(ctx) => {
- let dollar = new_dollar.or_else(|| ctx.dollar.clone());
- let this = new_this.or_else(|| ctx.this.clone());
- let super_obj = new_super_obj.or_else(|| ctx.super_obj.clone());
- let bindings = if new_bindings.is_empty() {
- ctx.bindings.clone()
- } else {
- ctx.bindings.clone().extend(new_bindings)
- };
- Self(Rc::new(ContextInternals {
- dollar,
- this,
- super_obj,
- bindings,
- }))
- }
- }
+ let ctx = &self.0;
+ let dollar = new_dollar.or_else(|| ctx.dollar.clone());
+ let this = new_this.or_else(|| ctx.this.clone());
+ let super_obj = new_super_obj.or_else(|| ctx.super_obj.clone());
+ let bindings = if new_bindings.is_empty() {
+ ctx.bindings.clone()
+ } else {
+ ctx.bindings.clone().extend(new_bindings)
+ };
+ Self(Gc::new(ContextInternals {
+ dollar,
+ this,
+ super_obj,
+ bindings,
+ }))
}
pub fn extend_bound(self, new_bindings: FxHashMap<IStr, LazyVal>) -> Self {
let new_this = self.0.this.clone();
@@ -166,22 +149,6 @@
impl PartialEq for Context {
fn eq(&self, other: &Self) -> bool {
- Rc::ptr_eq(&self.0, &other.0)
- }
-}
-
-#[cfg(feature = "unstable")]
-#[derive(Debug, Clone)]
-pub struct WeakContext(std::rc::Weak<ContextInternals>);
-#[cfg(feature = "unstable")]
-impl WeakContext {
- pub fn upgrade(&self) -> Context {
- Context(self.0.upgrade().expect("context is removed"))
- }
-}
-#[cfg(feature = "unstable")]
-impl PartialEq for WeakContext {
- fn eq(&self, other: &Self) -> bool {
- self.0.ptr_eq(&other.0)
+ Gc::ptr_eq(&self.0, &other.0)
}
}
crates/jrsonnet-evaluator/src/dynamic.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/dynamic.rs
+++ b/crates/jrsonnet-evaluator/src/dynamic.rs
@@ -1,23 +1,24 @@
-use std::{cell::RefCell, rc::Rc};
+use jrsonnet_gc::{Gc, GcCell, Trace};
-#[derive(Clone)]
-pub struct FutureWrapper<V>(pub Rc<RefCell<Option<V>>>);
-impl<T> FutureWrapper<T> {
+#[derive(Clone, Trace)]
+#[trivially_drop]
+pub struct FutureWrapper<V: Trace + 'static>(pub Gc<GcCell<Option<V>>>);
+impl<T: Trace + 'static> FutureWrapper<T> {
pub fn new() -> Self {
- Self(Rc::new(RefCell::new(None)))
+ Self(Gc::new(GcCell::new(None)))
}
pub fn fill(self, value: T) {
assert!(self.0.borrow().is_none(), "wrapper is filled already");
self.0.borrow_mut().replace(value);
}
}
-impl<T: Clone> FutureWrapper<T> {
+impl<T: Clone + Trace + 'static> FutureWrapper<T> {
pub fn unwrap(&self) -> T {
self.0.borrow().as_ref().cloned().unwrap()
}
}
-impl<T> Default for FutureWrapper<T> {
+impl<T: Trace + 'static> Default for FutureWrapper<T> {
fn default() -> Self {
Self::new()
}
crates/jrsonnet-evaluator/src/error.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/error.rs
+++ b/crates/jrsonnet-evaluator/src/error.rs
@@ -2,6 +2,7 @@
builtin::{format::FormatError, sort::SortError},
typed::TypeLocError,
};
+use jrsonnet_gc::Trace;
use jrsonnet_interner::IStr;
use jrsonnet_parser::{BinaryOpType, ExprLocation, UnaryOpType};
use jrsonnet_types::ValType;
@@ -11,7 +12,8 @@
};
use thiserror::Error;
-#[derive(Error, Debug, Clone)]
+#[derive(Error, Debug, Clone, Trace)]
+#[trivially_drop]
pub enum Error {
#[error("intrinsic not found: {0}")]
IntrinsicNotFound(IStr),
@@ -91,6 +93,7 @@
ImportSyntaxError {
path: Rc<Path>,
source_code: IStr,
+ #[unsafe_ignore_trace]
error: Box<jrsonnet_parser::ParseError>,
},
@@ -98,6 +101,8 @@
RuntimeError(IStr),
#[error("stack overflow, try to reduce recursion, or set --max-stack to bigger value")]
StackOverflow,
+ #[error("infinite recursion detected")]
+ RecursiveLazyValueEvaluation,
#[error("tried to index by fractional value")]
FractionalIndex,
#[error("attempted to divide by zero")]
@@ -145,15 +150,18 @@
}
}
-#[derive(Clone, Debug)]
+#[derive(Clone, Debug, Trace)]
+#[trivially_drop]
pub struct StackTraceElement {
pub location: Option<ExprLocation>,
pub desc: String,
}
-#[derive(Debug, Clone)]
+#[derive(Debug, Clone, Trace)]
+#[trivially_drop]
pub struct StackTrace(pub Vec<StackTraceElement>);
-#[derive(Debug, Clone)]
+#[derive(Debug, Clone, Trace)]
+#[trivially_drop]
pub struct LocError(Box<(Error, StackTrace)>);
impl LocError {
pub fn new(e: Error) -> Self {
crates/jrsonnet-evaluator/src/evaluate.rsdiffbeforeafterboth1use crate::{2 equals, error::Error::*, lazy_val, push, throw, with_state, ArrValue, Context, ContextCreator,3 FuncDesc, FuncVal, FutureWrapper, LazyBinding, LazyVal, ObjMember, ObjValue, Result, Val,4};5use closure::closure;6use jrsonnet_interner::IStr;7use jrsonnet_parser::{8 ArgsDesc, AssertStmt, BinaryOpType, BindSpec, CompSpec, Expr, ExprLocation, FieldMember,9 ForSpecData, IfSpecData, LiteralType, LocExpr, Member, ObjBody, ParamsDesc, UnaryOpType,10 Visibility,11};12use jrsonnet_types::ValType;13use rustc_hash::{FxHashMap, FxHasher};14use std::{collections::HashMap, hash::BuildHasherDefault, rc::Rc};1516pub fn evaluate_binding_in_future(17 b: &BindSpec,18 context_creator: FutureWrapper<Context>,19) -> LazyVal {20 let b = b.clone();21 if let Some(params) = &b.params {22 let params = params.clone();23 LazyVal::new(Box::new(move || {24 Ok(evaluate_method(25 context_creator.unwrap(),26 b.name.clone(),27 params.clone(),28 b.value.clone(),29 ))30 }))31 } else {32 LazyVal::new(Box::new(move || {33 evaluate_named(context_creator.unwrap(), &b.value, b.name.clone())34 }))35 }36}3738pub fn evaluate_binding(b: &BindSpec, context_creator: ContextCreator) -> (IStr, LazyBinding) {39 let b = b.clone();40 if let Some(params) = &b.params {41 let params = params.clone();42 (43 b.name.clone(),44 LazyBinding::Bindable(Rc::new(move |this, super_obj| {45 Ok(lazy_val!(46 closure!(clone b, clone params, clone context_creator, || Ok(evaluate_method(47 context_creator.create(this.clone(), super_obj.clone())?,48 b.name.clone(),49 params.clone(),50 b.value.clone(),51 )))52 ))53 })),54 )55 } else {56 (57 b.name.clone(),58 LazyBinding::Bindable(Rc::new(move |this, super_obj| {59 Ok(lazy_val!(closure!(clone context_creator, clone b, ||60 evaluate_named(61 context_creator.create(this.clone(), super_obj.clone())?,62 &b.value,63 b.name.clone()64 )65 )))66 })),67 )68 }69}7071pub fn evaluate_method(ctx: Context, name: IStr, params: ParamsDesc, body: LocExpr) -> Val {72 Val::Func(Rc::new(FuncVal::Normal(FuncDesc {73 name,74 ctx,75 params,76 body,77 })))78}7980pub fn evaluate_field_name(81 context: Context,82 field_name: &jrsonnet_parser::FieldName,83) -> Result<Option<IStr>> {84 Ok(match field_name {85 jrsonnet_parser::FieldName::Fixed(n) => Some(n.clone()),86 jrsonnet_parser::FieldName::Dyn(expr) => {87 let value = evaluate(context, expr)?;88 if matches!(value, Val::Null) {89 None90 } else {91 Some(value.try_cast_str("dynamic field name")?)92 }93 }94 })95}9697pub fn evaluate_unary_op(op: UnaryOpType, b: &Val) -> Result<Val> {98 Ok(match (op, b) {99 (UnaryOpType::Not, Val::Bool(v)) => Val::Bool(!v),100 (UnaryOpType::Minus, Val::Num(n)) => Val::Num(-*n),101 (UnaryOpType::BitNot, Val::Num(n)) => Val::Num(!(*n as i32) as f64),102 (op, o) => throw!(UnaryOperatorDoesNotOperateOnType(op, o.value_type())),103 })104}105106pub fn evaluate_add_op(a: &Val, b: &Val) -> Result<Val> {107 Ok(match (a, b) {108 (Val::Str(v1), Val::Str(v2)) => Val::Str(((**v1).to_owned() + v2).into()),109110 // Can't use generic json serialization way, because it depends on number to string concatenation (std.jsonnet:890)111 (Val::Num(n), Val::Str(o)) => Val::Str(format!("{}{}", n, o).into()),112 (Val::Str(o), Val::Num(n)) => Val::Str(format!("{}{}", o, n).into()),113114 (Val::Str(s), o) => Val::Str(format!("{}{}", s, o.clone().to_string()?).into()),115 (o, Val::Str(s)) => Val::Str(format!("{}{}", o.clone().to_string()?, s).into()),116117 (Val::Obj(v1), Val::Obj(v2)) => Val::Obj(v2.extend_from(v1.clone())),118 (Val::Arr(a), Val::Arr(b)) => {119 let mut out = Vec::with_capacity(a.len() + b.len());120 out.extend(a.iter_lazy());121 out.extend(b.iter_lazy());122 Val::Arr(out.into())123 }124 (Val::Num(v1), Val::Num(v2)) => Val::new_checked_num(v1 + v2)?,125 _ => throw!(BinaryOperatorDoesNotOperateOnValues(126 BinaryOpType::Add,127 a.value_type(),128 b.value_type(),129 )),130 })131}132133pub fn evaluate_binary_op_special(134 context: Context,135 a: &LocExpr,136 op: BinaryOpType,137 b: &LocExpr,138) -> Result<Val> {139 Ok(match (evaluate(context.clone(), a)?, op, b) {140 (Val::Bool(true), BinaryOpType::Or, _o) => Val::Bool(true),141 (Val::Bool(false), BinaryOpType::And, _o) => Val::Bool(false),142 (a, op, eb) => evaluate_binary_op_normal(&a, op, &evaluate(context, eb)?)?,143 })144}145146pub fn evaluate_binary_op_normal(a: &Val, op: BinaryOpType, b: &Val) -> Result<Val> {147 Ok(match (a, op, b) {148 (a, BinaryOpType::Add, b) => evaluate_add_op(a, b)?,149150 (a, BinaryOpType::Eq, b) => Val::Bool(equals(a, b)?),151 (a, BinaryOpType::Neq, b) => Val::Bool(!equals(a, b)?),152153 (Val::Str(v1), BinaryOpType::Mul, Val::Num(v2)) => Val::Str(v1.repeat(*v2 as usize).into()),154155 // Bool X Bool156 (Val::Bool(a), BinaryOpType::And, Val::Bool(b)) => Val::Bool(*a && *b),157 (Val::Bool(a), BinaryOpType::Or, Val::Bool(b)) => Val::Bool(*a || *b),158159 // Str X Str160 (Val::Str(v1), BinaryOpType::Lt, Val::Str(v2)) => Val::Bool(v1 < v2),161 (Val::Str(v1), BinaryOpType::Gt, Val::Str(v2)) => Val::Bool(v1 > v2),162 (Val::Str(v1), BinaryOpType::Lte, Val::Str(v2)) => Val::Bool(v1 <= v2),163 (Val::Str(v1), BinaryOpType::Gte, Val::Str(v2)) => Val::Bool(v1 >= v2),164165 // Num X Num166 (Val::Num(v1), BinaryOpType::Mul, Val::Num(v2)) => Val::new_checked_num(v1 * v2)?,167 (Val::Num(v1), BinaryOpType::Div, Val::Num(v2)) => {168 if *v2 <= f64::EPSILON {169 throw!(DivisionByZero)170 }171 Val::new_checked_num(v1 / v2)?172 }173174 (Val::Num(v1), BinaryOpType::Sub, Val::Num(v2)) => Val::new_checked_num(v1 - v2)?,175176 (Val::Num(v1), BinaryOpType::Lt, Val::Num(v2)) => Val::Bool(v1 < v2),177 (Val::Num(v1), BinaryOpType::Gt, Val::Num(v2)) => Val::Bool(v1 > v2),178 (Val::Num(v1), BinaryOpType::Lte, Val::Num(v2)) => Val::Bool(v1 <= v2),179 (Val::Num(v1), BinaryOpType::Gte, Val::Num(v2)) => Val::Bool(v1 >= v2),180181 (Val::Num(v1), BinaryOpType::BitAnd, Val::Num(v2)) => {182 Val::Num(((*v1 as i32) & (*v2 as i32)) as f64)183 }184 (Val::Num(v1), BinaryOpType::BitOr, Val::Num(v2)) => {185 Val::Num(((*v1 as i32) | (*v2 as i32)) as f64)186 }187 (Val::Num(v1), BinaryOpType::BitXor, Val::Num(v2)) => {188 Val::Num(((*v1 as i32) ^ (*v2 as i32)) as f64)189 }190 (Val::Num(v1), BinaryOpType::Lhs, Val::Num(v2)) => {191 if *v2 < 0.0 {192 throw!(RuntimeError("shift by negative exponent".into()))193 }194 Val::Num(((*v1 as i32) << (*v2 as i32)) as f64)195 }196 (Val::Num(v1), BinaryOpType::Rhs, Val::Num(v2)) => {197 if *v2 < 0.0 {198 throw!(RuntimeError("shift by negative exponent".into()))199 }200 Val::Num(((*v1 as i32) >> (*v2 as i32)) as f64)201 }202203 _ => throw!(BinaryOperatorDoesNotOperateOnValues(204 op,205 a.value_type(),206 b.value_type(),207 )),208 })209}210211pub fn evaluate_comp(212 context: Context,213 specs: &[CompSpec],214 callback: &mut impl FnMut(Context) -> Result<()>,215) -> Result<()> {216 match specs.get(0) {217 None => callback(context)?,218 Some(CompSpec::IfSpec(IfSpecData(cond))) => {219 if evaluate(context.clone(), cond)?.try_cast_bool("if spec")? {220 evaluate_comp(context, &specs[1..], callback)?221 }222 }223 Some(CompSpec::ForSpec(ForSpecData(var, expr))) => match evaluate(context.clone(), expr)? {224 Val::Arr(list) => {225 for item in list.iter() {226 evaluate_comp(227 context.clone().with_var(var.clone(), item?.clone()),228 &specs[1..],229 callback,230 )?231 }232 }233 _ => throw!(InComprehensionCanOnlyIterateOverArray),234 },235 }236 Ok(())237}238239pub fn evaluate_member_list_object(context: Context, members: &[Member]) -> Result<ObjValue> {240 let new_bindings = FutureWrapper::new();241 let future_this = FutureWrapper::new();242 let context_creator = ContextCreator(context.clone(), new_bindings.clone());243 {244 let mut bindings: FxHashMap<IStr, LazyBinding> =245 FxHashMap::with_capacity_and_hasher(members.len(), BuildHasherDefault::default());246 for (n, b) in members247 .iter()248 .filter_map(|m| match m {249 Member::BindStmt(b) => Some(b.clone()),250 _ => None,251 })252 .map(|b| evaluate_binding(&b, context_creator.clone()))253 {254 bindings.insert(n, b);255 }256 new_bindings.fill(bindings);257 }258259 let mut new_members = FxHashMap::default();260 let mut assertions = Vec::new();261 for member in members.iter() {262 match member {263 Member::Field(FieldMember {264 name,265 plus,266 params: None,267 visibility,268 value,269 }) => {270 let name = evaluate_field_name(context.clone(), name)?;271 if name.is_none() {272 continue;273 }274 let name = name.unwrap();275 new_members.insert(276 name.clone(),277 ObjMember {278 add: *plus,279 visibility: *visibility,280 invoke: LazyBinding::Bindable(Rc::new(281 closure!(clone name, clone value, clone context_creator, |this, super_obj| {282 Ok(LazyVal::new_resolved(evaluate_named(283 context_creator.create(this, super_obj)?,284 &value,285 name.clone(),286 )?))287 }),288 )),289 location: value.1.clone(),290 },291 );292 }293 Member::Field(FieldMember {294 name,295 params: Some(params),296 value,297 ..298 }) => {299 let name = evaluate_field_name(context.clone(), name)?;300 if name.is_none() {301 continue;302 }303 let name = name.unwrap();304 new_members.insert(305 name.clone(),306 ObjMember {307 add: false,308 visibility: Visibility::Hidden,309 invoke: LazyBinding::Bindable(Rc::new(310 closure!(clone value, clone context_creator, clone params, clone name, |this, super_obj| {311 // TODO: Assert312 Ok(LazyVal::new_resolved(evaluate_method(313 context_creator.create(this, super_obj)?,314 name.clone(),315 params.clone(),316 value.clone(),317 )))318 }),319 )),320 location: value.1.clone(),321 },322 );323 }324 Member::BindStmt(_) => {}325 Member::AssertStmt(stmt) => {326 assertions.push(stmt.clone());327 }328 }329 }330 let this = ObjValue::new(context, None, Rc::new(new_members), Rc::new(assertions));331 future_this.fill(this.clone());332 Ok(this)333}334335pub fn evaluate_object(context: Context, object: &ObjBody) -> Result<ObjValue> {336 Ok(match object {337 ObjBody::MemberList(members) => evaluate_member_list_object(context, members)?,338 ObjBody::ObjComp(obj) => {339 let future_this = FutureWrapper::new();340 let mut new_members = FxHashMap::default();341 evaluate_comp(context.clone(), &obj.compspecs, &mut |ctx| {342 let new_bindings = FutureWrapper::new();343 let context_creator = ContextCreator(context.clone(), new_bindings.clone());344 let mut bindings: FxHashMap<IStr, LazyBinding> =345 FxHashMap::with_capacity_and_hasher(346 obj.pre_locals.len() + obj.post_locals.len(),347 BuildHasherDefault::default(),348 );349 for (n, b) in obj350 .pre_locals351 .iter()352 .chain(obj.post_locals.iter())353 .map(|b| evaluate_binding(b, context_creator.clone()))354 {355 bindings.insert(n, b);356 }357 new_bindings.fill(bindings.clone());358 let ctx = ctx.extend_unbound(bindings, None, None, None)?;359 let key = evaluate(ctx.clone(), &obj.key)?;360361 match key {362 Val::Null => {}363 Val::Str(n) => {364 new_members.insert(365 n,366 ObjMember {367 add: false,368 visibility: Visibility::Normal,369 invoke: LazyBinding::Bindable(Rc::new(370 closure!(clone ctx, clone obj.value, |this, _super_obj| {371 Ok(LazyVal::new_resolved(evaluate(ctx.clone().extend(FxHashMap::default(), None, this, None), &value)?))372 }),373 )),374 location: obj.value.1.clone(),375 },376 );377 }378 v => throw!(FieldMustBeStringGot(v.value_type())),379 }380381 Ok(())382 })?;383384 let this = ObjValue::new(context, None, Rc::new(new_members), Rc::new(Vec::new()));385 future_this.fill(this.clone());386 this387 }388 })389}390391pub fn evaluate_apply(392 context: Context,393 value: &LocExpr,394 args: &ArgsDesc,395 loc: Option<&ExprLocation>,396 tailstrict: bool,397) -> Result<Val> {398 let value = evaluate(context.clone(), value)?;399 Ok(match value {400 Val::Func(f) => {401 let body = || f.evaluate(context, loc, args, tailstrict);402 if tailstrict {403 body()?404 } else {405 push(loc, || format!("function <{}> call", f.name()), body)?406 }407 }408 v => throw!(OnlyFunctionsCanBeCalledGot(v.value_type())),409 })410}411412pub fn evaluate_assert(context: Context, assertion: &AssertStmt) -> Result<()> {413 let value = &assertion.0;414 let msg = &assertion.1;415 let assertion_result = push(416 value.1.as_ref(),417 || "assertion condition".to_owned(),418 || {419 evaluate(context.clone(), value)?420 .try_cast_bool("assertion condition should be of type `boolean`")421 },422 )?;423 if !assertion_result {424 push(425 value.1.as_ref(),426 || "assertion failure".to_owned(),427 || {428 if let Some(msg) = msg {429 throw!(AssertionFailed(evaluate(context, msg)?.to_string()?));430 } else {431 throw!(AssertionFailed(Val::Null.to_string()?));432 }433 },434 )?435 }436 Ok(())437}438439pub fn evaluate_named(context: Context, lexpr: &LocExpr, name: IStr) -> Result<Val> {440 use Expr::*;441 let LocExpr(expr, _loc) = lexpr;442 Ok(match &**expr {443 Function(params, body) => evaluate_method(context, name, params.clone(), body.clone()),444 _ => evaluate(context, lexpr)?,445 })446}447448pub fn evaluate(context: Context, expr: &LocExpr) -> Result<Val> {449 use Expr::*;450 let LocExpr(expr, loc) = expr;451 Ok(match &**expr {452 Literal(LiteralType::This) => {453 Val::Obj(context.this().clone().ok_or(CantUseSelfOutsideOfObject)?)454 }455 Literal(LiteralType::Super) => Val::Obj(456 context457 .super_obj()458 .clone()459 .ok_or(NoSuperFound)?460 .with_this(context.this().clone().unwrap()),461 ),462 Literal(LiteralType::Dollar) => {463 Val::Obj(context.dollar().clone().ok_or(NoTopLevelObjectFound)?)464 }465 Literal(LiteralType::True) => Val::Bool(true),466 Literal(LiteralType::False) => Val::Bool(false),467 Literal(LiteralType::Null) => Val::Null,468 Parened(e) => evaluate(context, e)?,469 Str(v) => Val::Str(v.clone()),470 Num(v) => Val::new_checked_num(*v)?,471 BinaryOp(v1, o, v2) => evaluate_binary_op_special(context, v1, *o, v2)?,472 UnaryOp(o, v) => evaluate_unary_op(*o, &evaluate(context, v)?)?,473 Var(name) => push(474 loc.as_ref(),475 || format!("variable <{}>", name),476 || context.binding(name.clone())?.evaluate(),477 )?,478 Index(value, index) => {479 match (evaluate(context.clone(), value)?, evaluate(context, index)?) {480 (Val::Obj(v), Val::Str(s)) => {481 let sn = s.clone();482 push(483 loc.as_ref(),484 || format!("field <{}> access", sn),485 || {486 if let Some(v) = v.get(s.clone())? {487 Ok(v)488 } else if v.get("__intrinsic_namespace__".into())?.is_some() {489 Ok(Val::Func(Rc::new(FuncVal::Intrinsic(s))))490 } else {491 throw!(NoSuchField(s))492 }493 },494 )?495 }496 (Val::Obj(_), n) => throw!(ValueIndexMustBeTypeGot(497 ValType::Obj,498 ValType::Str,499 n.value_type(),500 )),501502 (Val::Arr(v), Val::Num(n)) => {503 if n.fract() > f64::EPSILON {504 throw!(FractionalIndex)505 }506 v.get(n as usize)?507 .ok_or_else(|| ArrayBoundsError(n as usize, v.len()))?508 }509 (Val::Arr(_), Val::Str(n)) => throw!(AttemptedIndexAnArrayWithString(n)),510 (Val::Arr(_), n) => throw!(ValueIndexMustBeTypeGot(511 ValType::Arr,512 ValType::Num,513 n.value_type(),514 )),515516 (Val::Str(s), Val::Num(n)) => Val::Str(517 s.chars()518 .skip(n as usize)519 .take(1)520 .collect::<String>()521 .into(),522 ),523 (Val::Str(_), n) => throw!(ValueIndexMustBeTypeGot(524 ValType::Str,525 ValType::Num,526 n.value_type(),527 )),528529 (v, _) => throw!(CantIndexInto(v.value_type())),530 }531 }532 LocalExpr(bindings, returned) => {533 let mut new_bindings: FxHashMap<IStr, LazyVal> = HashMap::with_capacity_and_hasher(534 bindings.len(),535 BuildHasherDefault::<FxHasher>::default(),536 );537 let future_context = Context::new_future();538 for b in bindings {539 new_bindings.insert(540 b.name.clone(),541 evaluate_binding_in_future(b, future_context.clone()),542 );543 }544 let context = context545 .extend_bound(new_bindings)546 .into_future(future_context);547 evaluate(context, &returned.clone())?548 }549 Arr(items) => {550 let mut out = Vec::with_capacity(items.len());551 for item in items {552 out.push(LazyVal::new(Box::new(553 closure!(clone context, clone item, || {554 evaluate(context.clone(), &item)555 }),556 )));557 }558 Val::Arr(out.into())559 }560 ArrComp(expr, comp_specs) => {561 let mut out = Vec::new();562 evaluate_comp(context, comp_specs, &mut |ctx| {563 out.push(evaluate(ctx, expr)?);564 Ok(())565 })?;566 Val::Arr(ArrValue::Eager(Rc::new(out)))567 }568 Obj(body) => Val::Obj(evaluate_object(context, body)?),569 ObjExtend(s, t) => evaluate_add_op(570 &evaluate(context.clone(), s)?,571 &Val::Obj(evaluate_object(context, t)?),572 )?,573 Apply(value, args, tailstrict) => {574 evaluate_apply(context, value, args, loc.as_ref(), *tailstrict)?575 }576 Function(params, body) => {577 evaluate_method(context, "anonymous".into(), params.clone(), body.clone())578 }579 Intrinsic(name) => Val::Func(Rc::new(FuncVal::Intrinsic(name.clone()))),580 AssertExpr(assert, returned) => {581 evaluate_assert(context.clone(), assert)?;582 evaluate(context, returned)?583 }584 ErrorStmt(e) => push(585 loc.as_ref(),586 || "error statement".to_owned(),587 || {588 throw!(RuntimeError(589 evaluate(context, e)?.try_cast_str("error text should be of type `string`")?,590 ))591 },592 )?,593 IfElse {594 cond,595 cond_then,596 cond_else,597 } => {598 if push(599 loc.as_ref(),600 || "if condition".to_owned(),601 || evaluate(context.clone(), &cond.0)?.try_cast_bool("in if condition"),602 )? {603 evaluate(context, cond_then)?604 } else {605 match cond_else {606 Some(v) => evaluate(context, v)?,607 None => Val::Null,608 }609 }610 }611 Import(path) => {612 let tmp = loc613 .clone()614 .expect("imports cannot be used without loc_data")615 .0;616 let mut import_location = tmp.to_path_buf();617 import_location.pop();618 push(619 loc.as_ref(),620 || format!("import {:?}", path),621 || with_state(|s| s.import_file(&import_location, path)),622 )?623 }624 ImportStr(path) => {625 let tmp = loc626 .clone()627 .expect("imports cannot be used without loc_data")628 .0;629 let mut import_location = tmp.to_path_buf();630 import_location.pop();631 Val::Str(with_state(|s| s.import_file_str(&import_location, path))?)632 }633 })634}1use crate::{2 equals, error::Error::*, push, throw, with_state, ArrValue, Bindable, Context, ContextCreator,3 FuncDesc, FuncVal, FutureWrapper, LazyBinding, LazyVal, LazyValValue, ObjMember, ObjValue,4 ObjectAssertion, Result, Val,5};6use jrsonnet_gc::{Gc, Trace};7use jrsonnet_interner::IStr;8use jrsonnet_parser::{9 ArgsDesc, AssertStmt, BinaryOpType, BindSpec, CompSpec, Expr, ExprLocation, FieldMember,10 ForSpecData, IfSpecData, LiteralType, LocExpr, Member, ObjBody, ParamsDesc, UnaryOpType,11 Visibility,12};13use jrsonnet_types::ValType;14use rustc_hash::{FxHashMap, FxHasher};15use std::{collections::HashMap, hash::BuildHasherDefault};1617pub fn evaluate_binding_in_future(18 b: &BindSpec,19 context_creator: FutureWrapper<Context>,20) -> LazyVal {21 let b = b.clone();22 if let Some(params) = &b.params {23 let params = params.clone();2425 #[derive(Trace)]26 #[trivially_drop]27 struct LazyMethodBinding {28 context_creator: FutureWrapper<Context>,29 name: IStr,30 params: ParamsDesc,31 value: LocExpr,32 }33 impl LazyValValue for LazyMethodBinding {34 fn get(self: Box<Self>) -> Result<Val> {35 Ok(evaluate_method(36 self.context_creator.unwrap(),37 self.name,38 self.params,39 self.value,40 ))41 }42 }4344 LazyVal::new(Box::new(LazyMethodBinding {45 context_creator,46 name: b.name.clone(),47 params,48 value: b.value.clone(),49 }))50 } else {51 #[derive(Trace)]52 #[trivially_drop]53 struct LazyNamedBinding {54 context_creator: FutureWrapper<Context>,55 name: IStr,56 value: LocExpr,57 }58 impl LazyValValue for LazyNamedBinding {59 fn get(self: Box<Self>) -> Result<Val> {60 evaluate_named(self.context_creator.unwrap(), &self.value, self.name)61 }62 }63 LazyVal::new(Box::new(LazyNamedBinding {64 context_creator,65 name: b.name.clone(),66 value: b.value,67 }))68 }69}7071pub fn evaluate_binding(b: &BindSpec, context_creator: ContextCreator) -> (IStr, LazyBinding) {72 let b = b.clone();73 if let Some(params) = &b.params {74 let params = params.clone();7576 #[derive(Trace)]77 #[trivially_drop]78 struct BindableMethodLazyVal {79 this: Option<ObjValue>,80 super_obj: Option<ObjValue>,8182 context_creator: ContextCreator,83 name: IStr,84 params: ParamsDesc,85 value: LocExpr,86 }87 impl LazyValValue for BindableMethodLazyVal {88 fn get(self: Box<Self>) -> Result<Val> {89 Ok(evaluate_method(90 self.context_creator.create(self.this, self.super_obj)?,91 self.name,92 self.params,93 self.value,94 ))95 }96 }9798 #[derive(Trace)]99 #[trivially_drop]100 struct BindableMethod {101 context_creator: ContextCreator,102 name: IStr,103 params: ParamsDesc,104 value: LocExpr,105 }106 impl Bindable for BindableMethod {107 fn bind(&self, this: Option<ObjValue>, super_obj: Option<ObjValue>) -> Result<LazyVal> {108 Ok(LazyVal::new(Box::new(BindableMethodLazyVal {109 this,110 super_obj,111112 context_creator: self.context_creator.clone(),113 name: self.name.clone(),114 params: self.params.clone(),115 value: self.value.clone(),116 })))117 }118 }119120 (121 b.name.clone(),122 LazyBinding::Bindable(Gc::new(Box::new(BindableMethod {123 context_creator,124 name: b.name.clone(),125 params,126 value: b.value.clone(),127 }))),128 )129 } else {130 #[derive(Trace)]131 #[trivially_drop]132 struct BindableNamedLazyVal {133 this: Option<ObjValue>,134 super_obj: Option<ObjValue>,135136 context_creator: ContextCreator,137 name: IStr,138 value: LocExpr,139 }140 impl LazyValValue for BindableNamedLazyVal {141 fn get(self: Box<Self>) -> Result<Val> {142 evaluate_named(143 self.context_creator.create(self.this, self.super_obj)?,144 &self.value,145 self.name,146 )147 }148 }149150 #[derive(Trace)]151 #[trivially_drop]152 struct BindableNamed {153 context_creator: ContextCreator,154 name: IStr,155 value: LocExpr,156 }157 impl Bindable for BindableNamed {158 fn bind(&self, this: Option<ObjValue>, super_obj: Option<ObjValue>) -> Result<LazyVal> {159 Ok(LazyVal::new(Box::new(BindableNamedLazyVal {160 this,161 super_obj,162163 context_creator: self.context_creator.clone(),164 name: self.name.clone(),165 value: self.value.clone(),166 })))167 }168 }169170 (171 b.name.clone(),172 LazyBinding::Bindable(Gc::new(Box::new(BindableNamed {173 context_creator,174 name: b.name.clone(),175 value: b.value.clone(),176 }))),177 )178 }179}180181pub fn evaluate_method(ctx: Context, name: IStr, params: ParamsDesc, body: LocExpr) -> Val {182 Val::Func(Gc::new(FuncVal::Normal(FuncDesc {183 name,184 ctx,185 params,186 body,187 })))188}189190pub fn evaluate_field_name(191 context: Context,192 field_name: &jrsonnet_parser::FieldName,193) -> Result<Option<IStr>> {194 Ok(match field_name {195 jrsonnet_parser::FieldName::Fixed(n) => Some(n.clone()),196 jrsonnet_parser::FieldName::Dyn(expr) => {197 let value = evaluate(context, expr)?;198 if matches!(value, Val::Null) {199 None200 } else {201 Some(value.try_cast_str("dynamic field name")?)202 }203 }204 })205}206207pub fn evaluate_unary_op(op: UnaryOpType, b: &Val) -> Result<Val> {208 Ok(match (op, b) {209 (UnaryOpType::Not, Val::Bool(v)) => Val::Bool(!v),210 (UnaryOpType::Minus, Val::Num(n)) => Val::Num(-*n),211 (UnaryOpType::BitNot, Val::Num(n)) => Val::Num(!(*n as i32) as f64),212 (op, o) => throw!(UnaryOperatorDoesNotOperateOnType(op, o.value_type())),213 })214}215216pub fn evaluate_add_op(a: &Val, b: &Val) -> Result<Val> {217 Ok(match (a, b) {218 (Val::DebugGcTraceValue(v1), Val::DebugGcTraceValue(v2)) => {219 evaluate_add_op(&v1.value, &v2.value)?220 }221 (Val::Str(v1), Val::Str(v2)) => Val::Str(((**v1).to_owned() + v2).into()),222223 // Can't use generic json serialization way, because it depends on number to string concatenation (std.jsonnet:890)224 (Val::Num(n), Val::Str(o)) => Val::Str(format!("{}{}", n, o).into()),225 (Val::Str(o), Val::Num(n)) => Val::Str(format!("{}{}", o, n).into()),226227 (Val::Str(s), o) => Val::Str(format!("{}{}", s, o.clone().to_string()?).into()),228 (o, Val::Str(s)) => Val::Str(format!("{}{}", o.clone().to_string()?, s).into()),229230 (Val::Obj(v1), Val::Obj(v2)) => Val::Obj(v2.extend_from(v1.clone())),231 (Val::Arr(a), Val::Arr(b)) => {232 let mut out = Vec::with_capacity(a.len() + b.len());233 out.extend(a.iter_lazy());234 out.extend(b.iter_lazy());235 Val::Arr(out.into())236 }237 (Val::Num(v1), Val::Num(v2)) => Val::new_checked_num(v1 + v2)?,238 _ => throw!(BinaryOperatorDoesNotOperateOnValues(239 BinaryOpType::Add,240 a.value_type(),241 b.value_type(),242 )),243 })244}245246pub fn evaluate_binary_op_special(247 context: Context,248 a: &LocExpr,249 op: BinaryOpType,250 b: &LocExpr,251) -> Result<Val> {252 Ok(match (evaluate(context.clone(), a)?, op, b) {253 (Val::Bool(true), BinaryOpType::Or, _o) => Val::Bool(true),254 (Val::Bool(false), BinaryOpType::And, _o) => Val::Bool(false),255 (a, op, eb) => evaluate_binary_op_normal(&a, op, &evaluate(context, eb)?)?,256 })257}258259pub fn evaluate_binary_op_normal(a: &Val, op: BinaryOpType, b: &Val) -> Result<Val> {260 Ok(match (a, op, b) {261 (a, BinaryOpType::Add, b) => evaluate_add_op(a, b)?,262263 (a, BinaryOpType::Eq, b) => Val::Bool(equals(a, b)?),264 (a, BinaryOpType::Neq, b) => Val::Bool(!equals(a, b)?),265266 (Val::Str(v1), BinaryOpType::Mul, Val::Num(v2)) => Val::Str(v1.repeat(*v2 as usize).into()),267268 // Bool X Bool269 (Val::Bool(a), BinaryOpType::And, Val::Bool(b)) => Val::Bool(*a && *b),270 (Val::Bool(a), BinaryOpType::Or, Val::Bool(b)) => Val::Bool(*a || *b),271272 // Str X Str273 (Val::Str(v1), BinaryOpType::Lt, Val::Str(v2)) => Val::Bool(v1 < v2),274 (Val::Str(v1), BinaryOpType::Gt, Val::Str(v2)) => Val::Bool(v1 > v2),275 (Val::Str(v1), BinaryOpType::Lte, Val::Str(v2)) => Val::Bool(v1 <= v2),276 (Val::Str(v1), BinaryOpType::Gte, Val::Str(v2)) => Val::Bool(v1 >= v2),277278 // Num X Num279 (Val::Num(v1), BinaryOpType::Mul, Val::Num(v2)) => Val::new_checked_num(v1 * v2)?,280 (Val::Num(v1), BinaryOpType::Div, Val::Num(v2)) => {281 if *v2 <= f64::EPSILON {282 throw!(DivisionByZero)283 }284 Val::new_checked_num(v1 / v2)?285 }286287 (Val::Num(v1), BinaryOpType::Sub, Val::Num(v2)) => Val::new_checked_num(v1 - v2)?,288289 (Val::Num(v1), BinaryOpType::Lt, Val::Num(v2)) => Val::Bool(v1 < v2),290 (Val::Num(v1), BinaryOpType::Gt, Val::Num(v2)) => Val::Bool(v1 > v2),291 (Val::Num(v1), BinaryOpType::Lte, Val::Num(v2)) => Val::Bool(v1 <= v2),292 (Val::Num(v1), BinaryOpType::Gte, Val::Num(v2)) => Val::Bool(v1 >= v2),293294 (Val::Num(v1), BinaryOpType::BitAnd, Val::Num(v2)) => {295 Val::Num(((*v1 as i32) & (*v2 as i32)) as f64)296 }297 (Val::Num(v1), BinaryOpType::BitOr, Val::Num(v2)) => {298 Val::Num(((*v1 as i32) | (*v2 as i32)) as f64)299 }300 (Val::Num(v1), BinaryOpType::BitXor, Val::Num(v2)) => {301 Val::Num(((*v1 as i32) ^ (*v2 as i32)) as f64)302 }303 (Val::Num(v1), BinaryOpType::Lhs, Val::Num(v2)) => {304 if *v2 < 0.0 {305 throw!(RuntimeError("shift by negative exponent".into()))306 }307 Val::Num(((*v1 as i32) << (*v2 as i32)) as f64)308 }309 (Val::Num(v1), BinaryOpType::Rhs, Val::Num(v2)) => {310 if *v2 < 0.0 {311 throw!(RuntimeError("shift by negative exponent".into()))312 }313 Val::Num(((*v1 as i32) >> (*v2 as i32)) as f64)314 }315316 _ => throw!(BinaryOperatorDoesNotOperateOnValues(317 op,318 a.value_type(),319 b.value_type(),320 )),321 })322}323324pub fn evaluate_comp(325 context: Context,326 specs: &[CompSpec],327 callback: &mut impl FnMut(Context) -> Result<()>,328) -> Result<()> {329 match specs.get(0) {330 None => callback(context)?,331 Some(CompSpec::IfSpec(IfSpecData(cond))) => {332 if evaluate(context.clone(), cond)?.try_cast_bool("if spec")? {333 evaluate_comp(context, &specs[1..], callback)?334 }335 }336 Some(CompSpec::ForSpec(ForSpecData(var, expr))) => match evaluate(context.clone(), expr)? {337 Val::Arr(list) => {338 for item in list.iter() {339 evaluate_comp(340 context.clone().with_var(var.clone(), item?.clone()),341 &specs[1..],342 callback,343 )?344 }345 }346 _ => throw!(InComprehensionCanOnlyIterateOverArray),347 },348 }349 Ok(())350}351352pub fn evaluate_member_list_object(context: Context, members: &[Member]) -> Result<ObjValue> {353 let new_bindings = FutureWrapper::new();354 let future_this = FutureWrapper::new();355 let context_creator = ContextCreator(context.clone(), new_bindings.clone());356 {357 let mut bindings: FxHashMap<IStr, LazyBinding> =358 FxHashMap::with_capacity_and_hasher(members.len(), BuildHasherDefault::default());359 for (n, b) in members360 .iter()361 .filter_map(|m| match m {362 Member::BindStmt(b) => Some(b.clone()),363 _ => None,364 })365 .map(|b| evaluate_binding(&b, context_creator.clone()))366 {367 bindings.insert(n, b);368 }369 new_bindings.fill(bindings);370 }371372 let mut new_members = FxHashMap::default();373 let mut assertions: Vec<Box<dyn ObjectAssertion>> = Vec::new();374 for member in members.iter() {375 match member {376 Member::Field(FieldMember {377 name,378 plus,379 params: None,380 visibility,381 value,382 }) => {383 let name = evaluate_field_name(context.clone(), name)?;384 if name.is_none() {385 continue;386 }387 let name = name.unwrap();388389 #[derive(Trace)]390 #[trivially_drop]391 struct ObjMemberBinding {392 context_creator: ContextCreator,393 value: LocExpr,394 name: IStr,395 }396 impl Bindable for ObjMemberBinding {397 fn bind(398 &self,399 this: Option<ObjValue>,400 super_obj: Option<ObjValue>,401 ) -> Result<LazyVal> {402 Ok(LazyVal::new_resolved(evaluate_named(403 self.context_creator.create(this, super_obj)?,404 &self.value,405 self.name.clone(),406 )?))407 }408 }409 new_members.insert(410 name.clone(),411 ObjMember {412 add: *plus,413 visibility: *visibility,414 invoke: LazyBinding::Bindable(Gc::new(Box::new(ObjMemberBinding {415 context_creator: context_creator.clone(),416 value: value.clone(),417 name,418 }))),419 location: value.1.clone(),420 },421 );422 }423 Member::Field(FieldMember {424 name,425 params: Some(params),426 value,427 ..428 }) => {429 let name = evaluate_field_name(context.clone(), name)?;430 if name.is_none() {431 continue;432 }433 let name = name.unwrap();434 #[derive(Trace)]435 #[trivially_drop]436 struct ObjMemberBinding {437 context_creator: ContextCreator,438 value: LocExpr,439 params: ParamsDesc,440 name: IStr,441 }442 impl Bindable for ObjMemberBinding {443 fn bind(444 &self,445 this: Option<ObjValue>,446 super_obj: Option<ObjValue>,447 ) -> Result<LazyVal> {448 Ok(LazyVal::new_resolved(evaluate_method(449 self.context_creator.create(this, super_obj)?,450 self.name.clone(),451 self.params.clone(),452 self.value.clone(),453 )))454 }455 }456 new_members.insert(457 name.clone(),458 ObjMember {459 add: false,460 visibility: Visibility::Hidden,461 invoke: LazyBinding::Bindable(Gc::new(Box::new(ObjMemberBinding {462 context_creator: context_creator.clone(),463 value: value.clone(),464 params: params.clone(),465 name,466 }))),467 location: value.1.clone(),468 },469 );470 }471 Member::BindStmt(_) => {}472 Member::AssertStmt(stmt) => {473 #[derive(Trace)]474 #[trivially_drop]475 struct ObjectAssert {476 context_creator: ContextCreator,477 assert: AssertStmt,478 }479 impl ObjectAssertion for ObjectAssert {480 fn run(481 &self,482 this: Option<ObjValue>,483 super_obj: Option<ObjValue>,484 ) -> Result<()> {485 let ctx = self.context_creator.create(this, super_obj)?;486 evaluate_assert(ctx, &self.assert)487 }488 }489 assertions.push(Box::new(ObjectAssert {490 context_creator: context_creator.clone(),491 assert: stmt.clone(),492 }));493 }494 }495 }496 let this = ObjValue::new(None, Gc::new(new_members), Gc::new(assertions));497 future_this.fill(this.clone());498 Ok(this)499}500501pub fn evaluate_object(context: Context, object: &ObjBody) -> Result<ObjValue> {502 Ok(match object {503 ObjBody::MemberList(members) => evaluate_member_list_object(context, members)?,504 ObjBody::ObjComp(obj) => {505 let future_this = FutureWrapper::new();506 let mut new_members = FxHashMap::default();507 evaluate_comp(context.clone(), &obj.compspecs, &mut |ctx| {508 let new_bindings = FutureWrapper::new();509 let context_creator = ContextCreator(context.clone(), new_bindings.clone());510 let mut bindings: FxHashMap<IStr, LazyBinding> =511 FxHashMap::with_capacity_and_hasher(512 obj.pre_locals.len() + obj.post_locals.len(),513 BuildHasherDefault::default(),514 );515 for (n, b) in obj516 .pre_locals517 .iter()518 .chain(obj.post_locals.iter())519 .map(|b| evaluate_binding(b, context_creator.clone()))520 {521 bindings.insert(n, b);522 }523 new_bindings.fill(bindings.clone());524 let ctx = ctx.extend_unbound(bindings, None, None, None)?;525 let key = evaluate(ctx.clone(), &obj.key)?;526527 match key {528 Val::Null => {}529 Val::Str(n) => {530 #[derive(Trace)]531 #[trivially_drop]532 struct ObjCompBinding {533 context: Context,534 value: LocExpr,535 }536 impl Bindable for ObjCompBinding {537 fn bind(538 &self,539 this: Option<ObjValue>,540 _super_obj: Option<ObjValue>,541 ) -> Result<LazyVal> {542 Ok(LazyVal::new_resolved(evaluate(543 self.context.clone().extend(544 FxHashMap::default(),545 None,546 this,547 None,548 ),549 &self.value,550 )?))551 }552 }553 new_members.insert(554 n,555 ObjMember {556 add: false,557 visibility: Visibility::Normal,558 invoke: LazyBinding::Bindable(Gc::new(Box::new(ObjCompBinding {559 context: ctx,560 value: obj.value.clone(),561 }))),562 location: obj.value.1.clone(),563 },564 );565 }566 v => throw!(FieldMustBeStringGot(v.value_type())),567 }568569 Ok(())570 })?;571572 let this = ObjValue::new(None, Gc::new(new_members), Gc::new(Vec::new()));573 future_this.fill(this.clone());574 this575 }576 })577}578579pub fn evaluate_apply(580 context: Context,581 value: &LocExpr,582 args: &ArgsDesc,583 loc: Option<&ExprLocation>,584 tailstrict: bool,585) -> Result<Val> {586 let value = evaluate(context.clone(), value)?;587 Ok(match value {588 Val::Func(f) => {589 let body = || f.evaluate(context, loc, args, tailstrict);590 if tailstrict {591 body()?592 } else {593 push(loc, || format!("function <{}> call", f.name()), body)?594 }595 }596 v => throw!(OnlyFunctionsCanBeCalledGot(v.value_type())),597 })598}599600pub fn evaluate_assert(context: Context, assertion: &AssertStmt) -> Result<()> {601 let value = &assertion.0;602 let msg = &assertion.1;603 let assertion_result = push(604 value.1.as_ref(),605 || "assertion condition".to_owned(),606 || {607 evaluate(context.clone(), value)?608 .try_cast_bool("assertion condition should be of type `boolean`")609 },610 )?;611 if !assertion_result {612 push(613 value.1.as_ref(),614 || "assertion failure".to_owned(),615 || {616 if let Some(msg) = msg {617 throw!(AssertionFailed(evaluate(context, msg)?.to_string()?));618 } else {619 throw!(AssertionFailed(Val::Null.to_string()?));620 }621 },622 )?623 }624 Ok(())625}626627pub fn evaluate_named(context: Context, lexpr: &LocExpr, name: IStr) -> Result<Val> {628 use Expr::*;629 let LocExpr(expr, _loc) = lexpr;630 Ok(match &**expr {631 Function(params, body) => evaluate_method(context, name, params.clone(), body.clone()),632 _ => evaluate(context, lexpr)?,633 })634}635636pub fn evaluate(context: Context, expr: &LocExpr) -> Result<Val> {637 use Expr::*;638 let LocExpr(expr, loc) = expr;639 Ok(match &**expr {640 Literal(LiteralType::This) => {641 Val::Obj(context.this().clone().ok_or(CantUseSelfOutsideOfObject)?)642 }643 Literal(LiteralType::Super) => Val::Obj(644 context645 .super_obj()646 .clone()647 .ok_or(NoSuperFound)?648 .with_this(context.this().clone().unwrap()),649 ),650 Literal(LiteralType::Dollar) => {651 Val::Obj(context.dollar().clone().ok_or(NoTopLevelObjectFound)?)652 }653 Literal(LiteralType::True) => Val::Bool(true),654 Literal(LiteralType::False) => Val::Bool(false),655 Literal(LiteralType::Null) => Val::Null,656 Parened(e) => evaluate(context, e)?,657 Str(v) => Val::Str(v.clone()),658 Num(v) => Val::new_checked_num(*v)?,659 BinaryOp(v1, o, v2) => evaluate_binary_op_special(context, v1, *o, v2)?,660 UnaryOp(o, v) => evaluate_unary_op(*o, &evaluate(context, v)?)?,661 Var(name) => push(662 loc.as_ref(),663 || format!("variable <{}>", name),664 || context.binding(name.clone())?.evaluate(),665 )?,666 Index(value, index) => {667 match (evaluate(context.clone(), value)?, evaluate(context, index)?) {668 (Val::Obj(v), Val::Str(s)) => {669 let sn = s.clone();670 push(671 loc.as_ref(),672 || format!("field <{}> access", sn),673 || {674 if let Some(v) = v.get(s.clone())? {675 Ok(v)676 } else if v.get("__intrinsic_namespace__".into())?.is_some() {677 Ok(Val::Func(Gc::new(FuncVal::Intrinsic(s))))678 } else {679 throw!(NoSuchField(s))680 }681 },682 )?683 }684 (Val::Obj(_), n) => throw!(ValueIndexMustBeTypeGot(685 ValType::Obj,686 ValType::Str,687 n.value_type(),688 )),689690 (Val::Arr(v), Val::Num(n)) => {691 if n.fract() > f64::EPSILON {692 throw!(FractionalIndex)693 }694 v.get(n as usize)?695 .ok_or_else(|| ArrayBoundsError(n as usize, v.len()))?696 }697 (Val::Arr(_), Val::Str(n)) => throw!(AttemptedIndexAnArrayWithString(n)),698 (Val::Arr(_), n) => throw!(ValueIndexMustBeTypeGot(699 ValType::Arr,700 ValType::Num,701 n.value_type(),702 )),703704 (Val::Str(s), Val::Num(n)) => Val::Str(705 s.chars()706 .skip(n as usize)707 .take(1)708 .collect::<String>()709 .into(),710 ),711 (Val::Str(_), n) => throw!(ValueIndexMustBeTypeGot(712 ValType::Str,713 ValType::Num,714 n.value_type(),715 )),716717 (v, _) => throw!(CantIndexInto(v.value_type())),718 }719 }720 LocalExpr(bindings, returned) => {721 let mut new_bindings: FxHashMap<IStr, LazyVal> = HashMap::with_capacity_and_hasher(722 bindings.len(),723 BuildHasherDefault::<FxHasher>::default(),724 );725 let future_context = Context::new_future();726 for b in bindings {727 new_bindings.insert(728 b.name.clone(),729 evaluate_binding_in_future(b, future_context.clone()),730 );731 }732 let context = context733 .extend_bound(new_bindings)734 .into_future(future_context);735 evaluate(context, &returned.clone())?736 }737 Arr(items) => {738 let mut out = Vec::with_capacity(items.len());739 for item in items {740 // TODO: Implement ArrValue::Lazy with same context for every element?741 #[derive(Trace)]742 #[trivially_drop]743 struct ArrayElement {744 context: Context,745 item: LocExpr,746 }747 impl LazyValValue for ArrayElement {748 fn get(self: Box<Self>) -> Result<Val> {749 evaluate(self.context, &self.item)750 }751 }752 out.push(LazyVal::new(Box::new(ArrayElement {753 context: context.clone(),754 item: item.clone(),755 })));756 }757 Val::Arr(out.into())758 }759 ArrComp(expr, comp_specs) => {760 let mut out = Vec::new();761 evaluate_comp(context, comp_specs, &mut |ctx| {762 out.push(evaluate(ctx, expr)?);763 Ok(())764 })?;765 Val::Arr(ArrValue::Eager(Gc::new(out)))766 }767 Obj(body) => Val::Obj(evaluate_object(context, body)?),768 ObjExtend(s, t) => evaluate_add_op(769 &evaluate(context.clone(), s)?,770 &Val::Obj(evaluate_object(context, t)?),771 )?,772 Apply(value, args, tailstrict) => {773 evaluate_apply(context, value, args, loc.as_ref(), *tailstrict)?774 }775 Function(params, body) => {776 evaluate_method(context, "anonymous".into(), params.clone(), body.clone())777 }778 Intrinsic(name) => Val::Func(Gc::new(FuncVal::Intrinsic(name.clone()))),779 AssertExpr(assert, returned) => {780 evaluate_assert(context.clone(), assert)?;781 evaluate(context, returned)?782 }783 ErrorStmt(e) => push(784 loc.as_ref(),785 || "error statement".to_owned(),786 || {787 throw!(RuntimeError(788 evaluate(context, e)?.try_cast_str("error text should be of type `string`")?,789 ))790 },791 )?,792 IfElse {793 cond,794 cond_then,795 cond_else,796 } => {797 if push(798 loc.as_ref(),799 || "if condition".to_owned(),800 || evaluate(context.clone(), &cond.0)?.try_cast_bool("in if condition"),801 )? {802 evaluate(context, cond_then)?803 } else {804 match cond_else {805 Some(v) => evaluate(context, v)?,806 None => Val::Null,807 }808 }809 }810 Import(path) => {811 let tmp = loc812 .clone()813 .expect("imports cannot be used without loc_data")814 .0;815 let mut import_location = tmp.to_path_buf();816 import_location.pop();817 push(818 loc.as_ref(),819 || format!("import {:?}", path),820 || with_state(|s| s.import_file(&import_location, path)),821 )?822 }823 ImportStr(path) => {824 let tmp = loc825 .clone()826 .expect("imports cannot be used without loc_data")827 .0;828 let mut import_location = tmp.to_path_buf();829 import_location.pop();830 Val::Str(with_state(|s| s.import_file_str(&import_location, path))?)831 }832 })833}crates/jrsonnet-evaluator/src/function.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/function.rs
+++ b/crates/jrsonnet-evaluator/src/function.rs
@@ -1,7 +1,7 @@
-use crate::{error::Error::*, evaluate, lazy_val, resolved_lazy_val, throw, Context, Result, Val};
-use closure::closure;
+use crate::{error::Error::*, evaluate, throw, Context, LazyVal, LazyValValue, Result, Val};
+use jrsonnet_gc::Trace;
use jrsonnet_interner::IStr;
-use jrsonnet_parser::{ArgsDesc, ParamsDesc};
+use jrsonnet_parser::{ArgsDesc, LocExpr, ParamsDesc};
use rustc_hash::FxHashMap;
use std::{collections::HashMap, hash::BuildHasherDefault};
@@ -53,9 +53,24 @@
throw!(FunctionParameterNotBoundInCall(p.0.clone()));
};
let val = if tailstrict {
- resolved_lazy_val!(evaluate(ctx, expr)?)
+ LazyVal::new_resolved(evaluate(ctx, expr)?)
} else {
- lazy_val!(closure!(clone ctx, clone expr, ||evaluate(ctx.clone(), &expr)))
+ #[derive(Trace)]
+ #[trivially_drop]
+ struct EvaluateLazyVal {
+ context: Context,
+ expr: LocExpr,
+ }
+ impl LazyValValue for EvaluateLazyVal {
+ fn get(self: Box<Self>) -> Result<Val> {
+ evaluate(self.context, &self.expr)
+ }
+ }
+
+ LazyVal::new(Box::new(EvaluateLazyVal {
+ context: ctx.clone(),
+ expr: expr.clone(),
+ }))
};
out.insert(p.0.clone(), val);
}
@@ -89,19 +104,31 @@
// Fill defaults
for (id, p) in params.iter().enumerate() {
let val = if let Some(arg) = positioned_args[id].take() {
- resolved_lazy_val!(arg)
+ LazyVal::new_resolved(arg)
} else if let Some(default) = &p.1 {
if tailstrict {
- resolved_lazy_val!(evaluate(
+ LazyVal::new_resolved(evaluate(
body_ctx.clone().expect(NO_DEFAULT_CONTEXT),
- default
+ default,
)?)
} else {
let body_ctx = body_ctx.clone();
let default = default.clone();
- lazy_val!(move || {
- evaluate(body_ctx.clone().expect(NO_DEFAULT_CONTEXT), &default)
- })
+ #[derive(Trace)]
+ #[trivially_drop]
+ struct EvaluateLazyVal {
+ body_ctx: Option<Context>,
+ default: LocExpr,
+ }
+ impl LazyValValue for EvaluateLazyVal {
+ fn get(self: Box<Self>) -> Result<Val> {
+ evaluate(
+ self.body_ctx.clone().expect(NO_DEFAULT_CONTEXT),
+ &self.default,
+ )
+ }
+ }
+ LazyVal::new(Box::new(EvaluateLazyVal { body_ctx, default }))
}
} else {
throw!(FunctionParameterNotBoundInCall(p.0.clone()));
@@ -135,7 +162,7 @@
} else {
throw!(FunctionParameterNotBoundInCall(p.0.clone()));
};
- out.insert(p.0.clone(), resolved_lazy_val!(val));
+ out.insert(p.0.clone(), LazyVal::new_resolved(val));
}
Ok(body_ctx.unwrap_or(ctx).extend(out, None, None, None))
crates/jrsonnet-evaluator/src/integrations/serde.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/integrations/serde.rs
+++ b/crates/jrsonnet-evaluator/src/integrations/serde.rs
@@ -1,7 +1,8 @@
use crate::{
error::{Error::*, LocError, Result},
- throw, Context, LazyBinding, LazyVal, ObjMember, ObjValue, Val,
+ throw, LazyBinding, LazyVal, ObjMember, ObjValue, Val,
};
+use jrsonnet_gc::Gc;
use jrsonnet_parser::Visibility;
use rustc_hash::FxHasher;
use serde_json::{Map, Number, Value};
@@ -9,7 +10,6 @@
collections::HashMap,
convert::{TryFrom, TryInto},
hash::BuildHasherDefault,
- rc::Rc,
};
impl TryFrom<&Val> for Value {
@@ -42,6 +42,7 @@
Self::Object(out)
}
Val::Func(_) => throw!(RuntimeError("tried to manifest function".into())),
+ Val::DebugGcTraceValue(v) => Self::try_from(&*v.value as &Val)?,
})
}
}
@@ -76,12 +77,7 @@
},
);
}
- Self::Obj(ObjValue::new(
- Context::new(),
- None,
- Rc::new(entries),
- Rc::new(Vec::new()),
- ))
+ Self::Obj(ObjValue::new(None, Gc::new(entries), Gc::new(Vec::new())))
}
}
}
crates/jrsonnet-evaluator/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/lib.rs
+++ b/crates/jrsonnet-evaluator/src/lib.rs
@@ -26,6 +26,8 @@
pub use evaluate::*;
pub use function::parse_function_call;
pub use import::*;
+use jrsonnet_gc::{Finalize, Gc, Trace};
+pub use jrsonnet_interner::IStr;
use jrsonnet_parser::*;
use native::NativeCallback;
pub use obj::*;
@@ -41,13 +43,12 @@
use trace::{offset_to_location, CodeLocation, CompactFormat, TraceFormat};
pub use val::*;
-// Re-exports
-pub use jrsonnet_interner::IStr;
-
-type BindableFn = dyn Fn(Option<ObjValue>, Option<ObjValue>) -> Result<LazyVal>;
-#[derive(Clone)]
+pub trait Bindable: Trace {
+ fn bind(&self, this: Option<ObjValue>, super_obj: Option<ObjValue>) -> Result<LazyVal>;
+}
+#[derive(Trace, Finalize, Clone)]
pub enum LazyBinding {
- Bindable(Rc<BindableFn>),
+ Bindable(Gc<Box<dyn Bindable>>),
Bound(LazyVal),
}
@@ -59,7 +60,7 @@
impl LazyBinding {
pub fn evaluate(&self, this: Option<ObjValue>, super_obj: Option<ObjValue>) -> Result<LazyVal> {
match self {
- Self::Bindable(v) => v(this, super_obj),
+ Self::Bindable(v) => v.bind(this, super_obj),
Self::Bound(v) => Ok(v.clone()),
}
}
@@ -73,7 +74,7 @@
/// Used for s`td.extVar`
pub ext_vars: HashMap<IStr, Val>,
/// Used for ext.native
- pub ext_natives: HashMap<IStr, Rc<NativeCallback>>,
+ pub ext_natives: HashMap<IStr, Gc<NativeCallback>>,
/// TLA vars
pub tla_vars: HashMap<IStr, Val>,
/// Global variables are inserted in default context
@@ -272,7 +273,7 @@
let mut new_bindings: FxHashMap<IStr, LazyVal> =
FxHashMap::with_capacity_and_hasher(globals.len(), BuildHasherDefault::default());
for (name, value) in globals.iter() {
- new_bindings.insert(name.clone(), resolved_lazy_val!(value.clone()));
+ new_bindings.insert(name.clone(), LazyVal::new_resolved(value.clone()));
}
Context::new().extend_bound(new_bindings)
}
@@ -451,7 +452,7 @@
self.settings_mut().import_resolver = resolver;
}
- pub fn add_native(&self, name: IStr, cb: Rc<NativeCallback>) {
+ pub fn add_native(&self, name: IStr, cb: Gc<NativeCallback>) {
self.settings_mut().ext_natives.insert(name, cb);
}
@@ -487,7 +488,10 @@
#[cfg(test)]
pub mod tests {
use super::Val;
- use crate::{error::Error::*, primitive_equals, EvaluationState};
+ use crate::{
+ error::Error::*, native::NativeCallbackHandler, primitive_equals, EvaluationState,
+ };
+ use jrsonnet_gc::{Finalize, Gc, Trace};
use jrsonnet_interner::IStr;
use jrsonnet_parser::*;
use std::{
@@ -919,23 +923,29 @@
let evaluator = EvaluationState::default();
evaluator.with_stdlib();
+
+ #[derive(Trace, Finalize)]
+ struct NativeAdd;
+ impl NativeCallbackHandler for NativeAdd {
+ fn call(&self, from: Option<Rc<Path>>, args: &[Val]) -> crate::error::Result<Val> {
+ assert_eq!(
+ &from.unwrap() as &Path,
+ &PathBuf::from("native_caller.jsonnet")
+ );
+ match (&args[0], &args[1]) {
+ (Val::Num(a), Val::Num(b)) => Ok(Val::Num(a + b)),
+ (_, _) => unreachable!(),
+ }
+ }
+ }
evaluator.settings_mut().ext_natives.insert(
"native_add".into(),
- Rc::new(NativeCallback::new(
+ Gc::new(NativeCallback::new(
ParamsDesc(Rc::new(vec![
Param("a".into(), None),
Param("b".into(), None),
])),
- |caller, args| {
- assert_eq!(
- &caller.unwrap() as &Path,
- &PathBuf::from("native_caller.jsonnet")
- );
- match (&args[0], &args[1]) {
- (Val::Num(a), Val::Num(b)) => Ok(Val::Num(a + b)),
- (_, _) => unreachable!(),
- }
- },
+ Box::new(NativeAdd),
)),
);
evaluator.evaluate_snippet_raw(
crates/jrsonnet-evaluator/src/map.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/map.rs
+++ b/crates/jrsonnet-evaluator/src/map.rs
@@ -1,31 +1,29 @@
+use jrsonnet_gc::{Gc, Trace};
use jrsonnet_interner::IStr;
use rustc_hash::FxHashMap;
-use std::rc::Rc;
-#[derive(Default, Debug)]
-struct LayeredHashMapInternals<V> {
- parent: Option<LayeredHashMap<V>>,
- current: FxHashMap<IStr, V>,
+use crate::LazyVal;
+
+#[derive(Trace)]
+#[trivially_drop]
+pub struct LayeredHashMapInternals {
+ parent: Option<LayeredHashMap>,
+ current: FxHashMap<IStr, LazyVal>,
}
-#[derive(Debug)]
-pub struct LayeredHashMap<V>(Rc<LayeredHashMapInternals<V>>);
+#[derive(Trace)]
+#[trivially_drop]
+pub struct LayeredHashMap(Gc<LayeredHashMapInternals>);
-impl<V> LayeredHashMap<V> {
- pub fn extend(self, new_layer: FxHashMap<IStr, V>) -> Self {
- match Rc::try_unwrap(self.0) {
- Ok(mut map) => {
- map.current.extend(new_layer);
- Self(Rc::new(map))
- }
- Err(this) => Self(Rc::new(LayeredHashMapInternals {
- parent: Some(Self(this)),
- current: new_layer,
- })),
- }
+impl LayeredHashMap {
+ pub fn extend(self, new_layer: FxHashMap<IStr, LazyVal>) -> Self {
+ Self(Gc::new(LayeredHashMapInternals {
+ parent: Some(self),
+ current: new_layer,
+ }))
}
- pub fn get(&self, key: &IStr) -> Option<&V> {
+ pub fn get(&self, key: &IStr) -> Option<&LazyVal> {
(self.0)
.current
.get(key)
@@ -33,15 +31,15 @@
}
}
-impl<V> Clone for LayeredHashMap<V> {
+impl Clone for LayeredHashMap {
fn clone(&self) -> Self {
Self(self.0.clone())
}
}
-impl<V> Default for LayeredHashMap<V> {
+impl Default for LayeredHashMap {
fn default() -> Self {
- Self(Rc::new(LayeredHashMapInternals {
+ Self(Gc::new(LayeredHashMapInternals {
parent: None,
current: FxHashMap::default(),
}))
crates/jrsonnet-evaluator/src/native.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/native.rs
+++ b/crates/jrsonnet-evaluator/src/native.rs
@@ -1,27 +1,28 @@
#![allow(clippy::type_complexity)]
use crate::{error::Result, Val};
+use jrsonnet_gc::Trace;
use jrsonnet_parser::ParamsDesc;
use std::fmt::Debug;
use std::path::Path;
use std::rc::Rc;
+pub trait NativeCallbackHandler: Trace {
+ fn call(&self, from: Option<Rc<Path>>, args: &[Val]) -> Result<Val>;
+}
+
+#[derive(Trace)]
+#[trivially_drop]
pub struct NativeCallback {
pub params: ParamsDesc,
- handler: Box<dyn Fn(Option<Rc<Path>>, &[Val]) -> Result<Val>>,
+ handler: Box<dyn NativeCallbackHandler>,
}
impl NativeCallback {
- pub fn new(
- params: ParamsDesc,
- handler: impl Fn(Option<Rc<Path>>, &[Val]) -> Result<Val> + 'static,
- ) -> Self {
- Self {
- params,
- handler: Box::new(handler),
- }
+ pub fn new(params: ParamsDesc, handler: Box<dyn NativeCallbackHandler>) -> Self {
+ Self { params, handler }
}
pub fn call(&self, caller: Option<Rc<Path>>, args: &[Val]) -> Result<Val> {
- (self.handler)(caller, args)
+ self.handler.call(caller, args)
}
}
impl Debug for NativeCallback {
crates/jrsonnet-evaluator/src/obj.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/obj.rs
+++ b/crates/jrsonnet-evaluator/src/obj.rs
@@ -1,11 +1,13 @@
-use crate::{evaluate_add_op, evaluate_assert, Context, LazyBinding, Result, Val};
+use crate::{evaluate_add_op, LazyBinding, Result, Val};
+use jrsonnet_gc::{Gc, GcCell, Trace};
use jrsonnet_interner::IStr;
-use jrsonnet_parser::{AssertStmt, ExprLocation, Visibility};
+use jrsonnet_parser::{ExprLocation, Visibility};
use rustc_hash::{FxHashMap, FxHashSet};
use std::hash::{Hash, Hasher};
-use std::{cell::RefCell, fmt::Debug, hash::BuildHasherDefault, rc::Rc};
+use std::{fmt::Debug, hash::BuildHasherDefault};
-#[derive(Debug)]
+#[derive(Debug, Trace)]
+#[trivially_drop]
pub struct ObjMember {
pub add: bool,
pub visibility: Visibility,
@@ -13,21 +15,26 @@
pub location: Option<ExprLocation>,
}
+pub trait ObjectAssertion: Trace {
+ fn run(&self, this: Option<ObjValue>, super_obj: Option<ObjValue>) -> Result<()>;
+}
+
// Field => This
type CacheKey = (IStr, ObjValue);
-#[derive(Debug)]
+#[derive(Trace)]
+#[trivially_drop]
pub struct ObjValueInternals {
- context: Context,
super_obj: Option<ObjValue>,
- assertions: Rc<Vec<AssertStmt>>,
- assertions_ran: RefCell<FxHashSet<ObjValue>>,
+ assertions: Gc<Vec<Box<dyn ObjectAssertion>>>,
+ assertions_ran: GcCell<FxHashSet<ObjValue>>,
this_obj: Option<ObjValue>,
- this_entries: Rc<FxHashMap<IStr, ObjMember>>,
- value_cache: RefCell<FxHashMap<CacheKey, Option<Val>>>,
+ this_entries: Gc<FxHashMap<IStr, ObjMember>>,
+ value_cache: GcCell<FxHashMap<CacheKey, Option<Val>>>,
}
-#[derive(Clone)]
-pub struct ObjValue(pub(crate) Rc<ObjValueInternals>);
+#[derive(Clone, Trace)]
+#[trivially_drop]
+pub struct ObjValue(pub(crate) Gc<ObjValueInternals>);
impl Debug for ObjValue {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
if let Some(super_obj) = self.0.super_obj.as_ref() {
@@ -55,39 +62,30 @@
impl ObjValue {
pub fn new(
- context: Context,
super_obj: Option<Self>,
- this_entries: Rc<FxHashMap<IStr, ObjMember>>,
- assertions: Rc<Vec<AssertStmt>>,
+ this_entries: Gc<FxHashMap<IStr, ObjMember>>,
+ assertions: Gc<Vec<Box<dyn ObjectAssertion>>>,
) -> Self {
- Self(Rc::new(ObjValueInternals {
- context,
+ Self(Gc::new(ObjValueInternals {
super_obj,
assertions,
- assertions_ran: RefCell::new(FxHashSet::default()),
+ assertions_ran: GcCell::new(FxHashSet::default()),
this_obj: None,
this_entries,
- value_cache: RefCell::new(FxHashMap::default()),
+ value_cache: GcCell::new(FxHashMap::default()),
}))
}
pub fn new_empty() -> Self {
- Self::new(
- Context::new(),
- None,
- Rc::new(FxHashMap::default()),
- Rc::new(Vec::new()),
- )
+ Self::new(None, Gc::new(FxHashMap::default()), Gc::new(Vec::new()))
}
pub fn extend_from(&self, super_obj: Self) -> Self {
match &self.0.super_obj {
None => Self::new(
- self.0.context.clone(),
Some(super_obj),
self.0.this_entries.clone(),
self.0.assertions.clone(),
),
Some(v) => Self::new(
- self.0.context.clone(),
Some(v.extend_from(super_obj)),
self.0.this_entries.clone(),
self.0.assertions.clone(),
@@ -95,14 +93,13 @@
}
}
pub fn with_this(&self, this_obj: Self) -> Self {
- Self(Rc::new(ObjValueInternals {
- context: self.0.context.clone(),
+ Self(Gc::new(ObjValueInternals {
super_obj: self.0.super_obj.clone(),
assertions: self.0.assertions.clone(),
- assertions_ran: RefCell::new(FxHashSet::default()),
+ assertions_ran: GcCell::new(FxHashSet::default()),
this_obj: Some(this_obj),
this_entries: self.0.this_entries.clone(),
- value_cache: RefCell::new(FxHashMap::default()),
+ value_cache: GcCell::new(FxHashMap::default()),
}))
}
@@ -203,12 +200,7 @@
pub fn extend_with_field(self, key: IStr, value: ObjMember) -> Self {
let mut new = FxHashMap::with_capacity_and_hasher(1, BuildHasherDefault::default());
new.insert(key, value);
- Self::new(
- Context::new(),
- Some(self),
- Rc::new(new),
- Rc::new(Vec::new()),
- )
+ Self::new(Some(self), Gc::new(new), Gc::new(Vec::new()))
}
fn get_raw(&self, key: IStr, real_this: Option<&Self>) -> Result<Option<Val>> {
@@ -249,13 +241,7 @@
fn run_assertions_raw(&self, real_this: &Self) -> Result<()> {
if self.0.assertions_ran.borrow_mut().insert(real_this.clone()) {
for assertion in self.0.assertions.iter() {
- if let Err(e) = evaluate_assert(
- self.0
- .context
- .clone()
- .with_this_super(real_this.clone(), self.0.super_obj.clone()),
- assertion,
- ) {
+ if let Err(e) = assertion.run(Some(real_this.clone()), self.0.super_obj.clone()) {
self.0.assertions_ran.borrow_mut().remove(real_this);
return Err(e);
}
@@ -271,19 +257,19 @@
}
pub fn ptr_eq(a: &Self, b: &Self) -> bool {
- Rc::ptr_eq(&a.0, &b.0)
+ Gc::ptr_eq(&a.0, &b.0)
}
}
impl PartialEq for ObjValue {
fn eq(&self, other: &Self) -> bool {
- Rc::ptr_eq(&self.0, &other.0)
+ Gc::ptr_eq(&self.0, &other.0)
}
}
impl Eq for ObjValue {}
impl Hash for ObjValue {
- fn hash<H: Hasher>(&self, state: &mut H) {
- state.write_usize(Rc::as_ptr(&self.0) as usize)
+ fn hash<H: Hasher>(&self, hasher: &mut H) {
+ hasher.write_usize(&*self.0 as *const _ as usize)
}
}
crates/jrsonnet-evaluator/src/typed.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/typed.rs
+++ b/crates/jrsonnet-evaluator/src/typed.rs
@@ -4,6 +4,7 @@
error::{Error, LocError, Result},
push, Val,
};
+use jrsonnet_gc::Trace;
use jrsonnet_parser::ExprLocation;
use jrsonnet_types::{ComplexValType, ValType};
use thiserror::Error;
@@ -20,7 +21,8 @@
}};
}
-#[derive(Debug, Error, Clone)]
+#[derive(Debug, Error, Clone, Trace)]
+#[trivially_drop]
pub enum TypeError {
#[error("expected {0}, got {1}")]
ExpectedGot(ComplexValType, ValType),
@@ -37,7 +39,8 @@
}
}
-#[derive(Debug, Clone)]
+#[derive(Debug, Clone, Trace)]
+#[trivially_drop]
pub struct TypeLocError(Box<TypeError>, ValuePathStack);
impl From<TypeError> for TypeLocError {
fn from(e: TypeError) -> Self {
@@ -59,7 +62,8 @@
}
}
-#[derive(Debug, Clone)]
+#[derive(Debug, Clone, Trace)]
+#[trivially_drop]
pub struct TypeLocErrorList(Vec<TypeLocError>);
impl Display for TypeLocErrorList {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
@@ -122,7 +126,8 @@
}
}
-#[derive(Clone, Debug)]
+#[derive(Clone, Debug, Trace)]
+#[trivially_drop]
enum ValuePathItem {
Field(Rc<str>),
Index(u64),
@@ -137,7 +142,8 @@
}
}
-#[derive(Clone, Debug)]
+#[derive(Clone, Debug, Trace)]
+#[trivially_drop]
struct ValuePathStack(Vec<ValuePathItem>);
impl Display for ValuePathStack {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
crates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/val.rs
+++ b/crates/jrsonnet-evaluator/src/val.rs
@@ -3,52 +3,67 @@
call_builtin,
manifest::{manifest_json_ex, ManifestJsonOptions, ManifestType},
},
- error::Error::*,
+ error::{Error::*, LocError},
evaluate,
function::{parse_function_call, parse_function_call_map, place_args},
native::NativeCallback,
throw, with_state, Context, ObjValue, Result,
};
+use jrsonnet_gc::{Finalize, Gc, GcCell, Trace};
use jrsonnet_interner::IStr;
use jrsonnet_parser::{el, Arg, ArgsDesc, Expr, ExprLocation, LiteralType, LocExpr, ParamsDesc};
use jrsonnet_types::ValType;
-use std::{cell::RefCell, collections::HashMap, fmt::Debug, rc::Rc};
+use std::{collections::HashMap, fmt::Debug, rc::Rc};
+pub trait LazyValValue: Trace {
+ fn get(self: Box<Self>) -> Result<Val>;
+}
+
+#[derive(Trace)]
+#[trivially_drop]
enum LazyValInternals {
Computed(Val),
- Waiting(Box<dyn Fn() -> Result<Val>>),
+ Errored(LocError),
+ Waiting(Box<dyn LazyValValue>),
+ Pending,
}
-#[derive(Clone)]
-pub struct LazyVal(Rc<RefCell<LazyValInternals>>);
+
+#[derive(Clone, Trace)]
+#[trivially_drop]
+pub struct LazyVal(Gc<GcCell<LazyValInternals>>);
impl LazyVal {
- pub fn new(f: Box<dyn Fn() -> Result<Val>>) -> Self {
- Self(Rc::new(RefCell::new(LazyValInternals::Waiting(f))))
+ pub fn new(f: Box<dyn LazyValValue>) -> Self {
+ Self(Gc::new(GcCell::new(LazyValInternals::Waiting(f))))
}
pub fn new_resolved(val: Val) -> Self {
- Self(Rc::new(RefCell::new(LazyValInternals::Computed(val))))
+ Self(Gc::new(GcCell::new(LazyValInternals::Computed(val))))
}
pub fn evaluate(&self) -> Result<Val> {
- let new_value = match &*self.0.borrow() {
+ match &*self.0.borrow() {
LazyValInternals::Computed(v) => return Ok(v.clone()),
- LazyValInternals::Waiting(f) => f()?,
+ LazyValInternals::Errored(e) => return Err(e.clone()),
+ LazyValInternals::Pending => return Err(RecursiveLazyValueEvaluation.into()),
+ _ => (),
+ };
+ let value = if let LazyValInternals::Waiting(value) =
+ std::mem::replace(&mut *self.0.borrow_mut(), LazyValInternals::Pending)
+ {
+ value
+ } else {
+ unreachable!()
+ };
+ let new_value = match value.get() {
+ Ok(v) => v,
+ Err(e) => {
+ *self.0.borrow_mut() = LazyValInternals::Errored(e.clone());
+ return Err(e);
+ }
};
*self.0.borrow_mut() = LazyValInternals::Computed(new_value.clone());
Ok(new_value)
}
}
-#[macro_export]
-macro_rules! lazy_val {
- ($f: expr) => {
- $crate::LazyVal::new(Box::new($f))
- };
-}
-#[macro_export]
-macro_rules! resolved_lazy_val {
- ($f: expr) => {
- $crate::LazyVal::new_resolved($f)
- };
-}
impl Debug for LazyVal {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Lazy")
@@ -56,11 +71,12 @@
}
impl PartialEq for LazyVal {
fn eq(&self, other: &Self) -> bool {
- Rc::ptr_eq(&self.0, &other.0)
+ Gc::ptr_eq(&self.0, &other.0)
}
}
-#[derive(Debug, PartialEq)]
+#[derive(Debug, PartialEq, Trace)]
+#[trivially_drop]
pub struct FuncDesc {
pub name: IStr,
pub ctx: Context,
@@ -68,14 +84,15 @@
pub body: LocExpr,
}
-#[derive(Debug)]
+#[derive(Debug, Trace)]
+#[trivially_drop]
pub enum FuncVal {
/// Plain function implemented in jsonnet
Normal(FuncDesc),
/// Standard library function
Intrinsic(IStr),
/// Library functions implemented in native
- NativeExt(IStr, Rc<NativeCallback>),
+ NativeExt(IStr, Gc<NativeCallback>),
}
impl PartialEq for FuncVal {
@@ -172,15 +189,16 @@
String,
}
-#[derive(Debug, Clone)]
+#[derive(Debug, Clone, Trace)]
+#[trivially_drop]
pub enum ArrValue {
- Lazy(Rc<Vec<LazyVal>>),
- Eager(Rc<Vec<Val>>),
+ Lazy(Gc<Vec<LazyVal>>),
+ Eager(Gc<Vec<Val>>),
Extended(Box<(Self, Self)>),
}
impl ArrValue {
pub fn new_eager() -> Self {
- Self::Eager(Rc::new(Vec::new()))
+ Self::Eager(Gc::new(Vec::new()))
}
pub fn len(&self) -> usize {
@@ -231,14 +249,14 @@
}
}
- pub fn evaluated(&self) -> Result<Rc<Vec<Val>>> {
+ pub fn evaluated(&self) -> Result<Gc<Vec<Val>>> {
Ok(match self {
Self::Lazy(vec) => {
let mut out = Vec::with_capacity(vec.len());
for item in vec.iter() {
out.push(item.evaluate()?);
}
- Rc::new(out)
+ Gc::new(out)
}
Self::Eager(vec) => vec.clone(),
Self::Extended(_v) => {
@@ -246,7 +264,7 @@
for item in self.iter() {
out.push(item?);
}
- Rc::new(out)
+ Gc::new(out)
}
})
}
@@ -272,12 +290,12 @@
Self::Lazy(vec) => {
let mut out = (&vec as &Vec<_>).clone();
out.reverse();
- Self::Lazy(Rc::new(out))
+ Self::Lazy(Gc::new(out))
}
Self::Eager(vec) => {
let mut out = (&vec as &Vec<_>).clone();
out.reverse();
- Self::Eager(Rc::new(out))
+ Self::Eager(Gc::new(out))
}
Self::Extended(b) => Self::Extended(Box::new((b.1.reversed(), b.0.reversed()))),
}
@@ -290,7 +308,7 @@
out.push(mapper(value?)?);
}
- Ok(Self::Eager(Rc::new(out)))
+ Ok(Self::Eager(Gc::new(out)))
}
pub fn filter(self, filter: impl Fn(&Val) -> Result<bool>) -> Result<Self> {
@@ -303,13 +321,13 @@
}
}
- Ok(Self::Eager(Rc::new(out)))
+ Ok(Self::Eager(Gc::new(out)))
}
pub fn ptr_eq(a: &Self, b: &Self) -> bool {
match (a, b) {
- (Self::Lazy(a), Self::Lazy(b)) => Rc::ptr_eq(a, b),
- (Self::Eager(a), Self::Eager(b)) => Rc::ptr_eq(a, b),
+ (Self::Lazy(a), Self::Lazy(b)) => Gc::ptr_eq(a, b),
+ (Self::Eager(a), Self::Eager(b)) => Gc::ptr_eq(a, b),
_ => false,
}
}
@@ -317,17 +335,77 @@
impl From<Vec<LazyVal>> for ArrValue {
fn from(v: Vec<LazyVal>) -> Self {
- Self::Lazy(Rc::new(v))
+ Self::Lazy(Gc::new(v))
}
}
impl From<Vec<Val>> for ArrValue {
fn from(v: Vec<Val>) -> Self {
- Self::Eager(Rc::new(v))
+ Self::Eager(Gc::new(v))
+ }
+}
+
+#[derive(Debug)]
+pub struct DebugGcTraceValue {
+ name: IStr,
+ pub value: Box<Val>,
+}
+impl DebugGcTraceValue {
+ fn print(&self, action: &str) {
+ println!("{} {}#{:?}", action, self.name, &*self.value as *const _)
+ }
+}
+impl Finalize for DebugGcTraceValue {
+ fn finalize(&self) {
+ self.print("Garbage-collecting")
+ }
+}
+impl Drop for DebugGcTraceValue {
+ fn drop(&mut self) {
+ self.print("Garbage-collected")
+ }
+}
+unsafe impl Trace for DebugGcTraceValue {
+ unsafe fn trace(&self) {
+ self.print("Traced");
+ self.value.trace()
+ }
+ unsafe fn root(&self) {
+ self.print("Rooted");
+ self.value.root()
+ }
+ unsafe fn unroot(&self) {
+ self.print("Unrooted");
+ self.value.unroot()
+ }
+ fn finalize_glue(&self) {
+ Finalize::finalize(self)
+ }
+}
+impl Clone for DebugGcTraceValue {
+ fn clone(&self) -> Self {
+ self.print("Cloned");
+ let value = Self {
+ name: self.name.clone(),
+ value: self.value.clone(),
+ };
+ value.print("I'm clone");
+ value
}
}
+impl DebugGcTraceValue {
+ pub fn create(name: IStr, value: Val) -> Val {
+ let value = Self {
+ name,
+ value: Box::new(value),
+ };
+ value.print("Constructed");
+ Val::DebugGcTraceValue(value)
+ }
+}
-#[derive(Debug, Clone)]
+#[derive(Debug, Clone, Trace)]
+#[trivially_drop]
pub enum Val {
Bool(bool),
Null,
@@ -335,7 +413,8 @@
Num(f64),
Arr(ArrValue),
Obj(ObjValue),
- Func(Rc<FuncVal>),
+ Func(Gc<FuncVal>),
+ DebugGcTraceValue(DebugGcTraceValue),
}
macro_rules! matches_unwrap {
@@ -368,7 +447,7 @@
pub fn unwrap_num(self) -> Result<f64> {
Ok(matches_unwrap!(self, Self::Num(v), v))
}
- pub fn unwrap_func(self) -> Result<Rc<FuncVal>> {
+ pub fn unwrap_func(self) -> Result<Gc<FuncVal>> {
Ok(matches_unwrap!(self, Self::Func(v), v))
}
pub fn try_cast_bool(self, context: &'static str) -> Result<bool> {
@@ -392,6 +471,7 @@
Self::Bool(_) => ValType::Bool,
Self::Null => ValType::Null,
Self::Func(..) => ValType::Func,
+ Self::DebugGcTraceValue(v) => v.value.value_type(),
}
}
crates/jrsonnet-interner/Cargo.tomldiffbeforeafterboth--- a/crates/jrsonnet-interner/Cargo.toml
+++ b/crates/jrsonnet-interner/Cargo.toml
@@ -9,3 +9,4 @@
[dependencies]
serde = { version = "1.0" }
rustc-hash = "1.1.0"
+jrsonnet-gc = { version = "0.4.2", features = ["derive"] }
crates/jrsonnet-interner/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-interner/src/lib.rs
+++ b/crates/jrsonnet-interner/src/lib.rs
@@ -1,3 +1,4 @@
+use jrsonnet_gc::{unsafe_empty_trace, Finalize, Trace};
use rustc_hash::FxHashMap;
use serde::{Deserialize, Serialize};
use std::{
@@ -10,6 +11,10 @@
#[derive(Clone, PartialOrd, Ord, Eq)]
pub struct IStr(Rc<str>);
+impl Finalize for IStr {}
+unsafe impl Trace for IStr {
+ unsafe_empty_trace!();
+}
impl Deref for IStr {
type Target = str;
crates/jrsonnet-parser/Cargo.tomldiffbeforeafterboth--- a/crates/jrsonnet-parser/Cargo.toml
+++ b/crates/jrsonnet-parser/Cargo.toml
@@ -18,6 +18,7 @@
unescape = "0.1.0"
serde = { version = "1.0", features = ["derive", "rc"], optional = true }
+jrsonnet-gc = { version = "0.4.2", features = ["derive"] }
[dev-dependencies]
jrsonnet-stdlib = { path = "../jrsonnet-stdlib", version = "0.3.8" }
crates/jrsonnet-parser/src/expr.rsdiffbeforeafterboth--- a/crates/jrsonnet-parser/src/expr.rs
+++ b/crates/jrsonnet-parser/src/expr.rs
@@ -1,3 +1,4 @@
+use jrsonnet_gc::{unsafe_empty_trace, Finalize, Trace};
use jrsonnet_interner::IStr;
#[cfg(feature = "deserialize")]
use serde::Deserialize;
@@ -12,7 +13,8 @@
#[cfg_attr(feature = "serialize", derive(Serialize))]
#[cfg_attr(feature = "deserialize", derive(Deserialize))]
-#[derive(Debug, PartialEq)]
+#[derive(Debug, PartialEq, Trace)]
+#[trivially_drop]
pub enum FieldName {
/// {fixed: 2}
Fixed(IStr),
@@ -22,7 +24,8 @@
#[cfg_attr(feature = "serialize", derive(Serialize))]
#[cfg_attr(feature = "deserialize", derive(Deserialize))]
-#[derive(Debug, Clone, Copy, PartialEq)]
+#[derive(Debug, Clone, Copy, PartialEq, Trace)]
+#[trivially_drop]
pub enum Visibility {
/// :
Normal,
@@ -40,12 +43,14 @@
#[cfg_attr(feature = "serialize", derive(Serialize))]
#[cfg_attr(feature = "deserialize", derive(Deserialize))]
-#[derive(Clone, Debug, PartialEq)]
+#[derive(Clone, Debug, PartialEq, Trace)]
+#[trivially_drop]
pub struct AssertStmt(pub LocExpr, pub Option<LocExpr>);
#[cfg_attr(feature = "serialize", derive(Serialize))]
#[cfg_attr(feature = "deserialize", derive(Deserialize))]
-#[derive(Debug, PartialEq)]
+#[derive(Debug, PartialEq, Trace)]
+#[trivially_drop]
pub struct FieldMember {
pub name: FieldName,
pub plus: bool,
@@ -56,7 +61,8 @@
#[cfg_attr(feature = "serialize", derive(Serialize))]
#[cfg_attr(feature = "deserialize", derive(Deserialize))]
-#[derive(Debug, PartialEq)]
+#[derive(Debug, PartialEq, Trace)]
+#[trivially_drop]
pub enum Member {
Field(FieldMember),
BindStmt(BindSpec),
@@ -65,13 +71,15 @@
#[cfg_attr(feature = "serialize", derive(Serialize))]
#[cfg_attr(feature = "deserialize", derive(Deserialize))]
-#[derive(Debug, Clone, Copy, PartialEq)]
+#[derive(Debug, Clone, Copy, PartialEq, Trace)]
+#[trivially_drop]
pub enum UnaryOpType {
Plus,
Minus,
BitNot,
Not,
}
+
impl Display for UnaryOpType {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
use UnaryOpType::*;
@@ -90,7 +98,8 @@
#[cfg_attr(feature = "serialize", derive(Serialize))]
#[cfg_attr(feature = "deserialize", derive(Deserialize))]
-#[derive(Debug, Clone, Copy, PartialEq)]
+#[derive(Debug, Clone, Copy, PartialEq, Trace)]
+#[trivially_drop]
pub enum BinaryOpType {
Mul,
Div,
@@ -119,6 +128,7 @@
And,
Or,
}
+
impl Display for BinaryOpType {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
use BinaryOpType::*;
@@ -152,7 +162,8 @@
/// name, default value
#[cfg_attr(feature = "serialize", derive(Serialize))]
#[cfg_attr(feature = "deserialize", derive(Deserialize))]
-#[derive(Debug, PartialEq)]
+#[derive(Debug, PartialEq, Trace)]
+#[trivially_drop]
pub struct Param(pub IStr, pub Option<LocExpr>);
/// Defined function parameters
@@ -160,6 +171,14 @@
#[cfg_attr(feature = "deserialize", derive(Deserialize))]
#[derive(Debug, Clone, PartialEq)]
pub struct ParamsDesc(pub Rc<Vec<Param>>);
+
+/// Safety:
+/// AST is acyclic, and there should be no gc pointers
+unsafe impl Trace for ParamsDesc {
+ unsafe_empty_trace!();
+}
+impl Finalize for ParamsDesc {}
+
impl Deref for ParamsDesc {
type Target = Vec<Param>;
fn deref(&self) -> &Self::Target {
@@ -169,13 +188,16 @@
#[cfg_attr(feature = "serialize", derive(Serialize))]
#[cfg_attr(feature = "deserialize", derive(Deserialize))]
-#[derive(Debug, PartialEq)]
+#[derive(Debug, PartialEq, Trace)]
+#[trivially_drop]
pub struct Arg(pub Option<String>, pub LocExpr);
#[cfg_attr(feature = "serialize", derive(Serialize))]
#[cfg_attr(feature = "deserialize", derive(Deserialize))]
-#[derive(Debug, PartialEq)]
+#[derive(Debug, PartialEq, Trace)]
+#[trivially_drop]
pub struct ArgsDesc(pub Vec<Arg>);
+
impl Deref for ArgsDesc {
type Target = Vec<Arg>;
fn deref(&self) -> &Self::Target {
@@ -185,7 +207,8 @@
#[cfg_attr(feature = "serialize", derive(Serialize))]
#[cfg_attr(feature = "deserialize", derive(Deserialize))]
-#[derive(Debug, Clone, PartialEq)]
+#[derive(Debug, Clone, PartialEq, Trace)]
+#[trivially_drop]
pub struct BindSpec {
pub name: IStr,
pub params: Option<ParamsDesc>,
@@ -194,17 +217,20 @@
#[cfg_attr(feature = "serialize", derive(Serialize))]
#[cfg_attr(feature = "deserialize", derive(Deserialize))]
-#[derive(Debug, PartialEq)]
+#[derive(Debug, PartialEq, Trace)]
+#[trivially_drop]
pub struct IfSpecData(pub LocExpr);
#[cfg_attr(feature = "serialize", derive(Serialize))]
#[cfg_attr(feature = "deserialize", derive(Deserialize))]
-#[derive(Debug, PartialEq)]
+#[derive(Debug, PartialEq, Trace)]
+#[trivially_drop]
pub struct ForSpecData(pub IStr, pub LocExpr);
#[cfg_attr(feature = "serialize", derive(Serialize))]
#[cfg_attr(feature = "deserialize", derive(Deserialize))]
-#[derive(Debug, PartialEq)]
+#[derive(Debug, PartialEq, Trace)]
+#[trivially_drop]
pub enum CompSpec {
IfSpec(IfSpecData),
ForSpec(ForSpecData),
@@ -212,7 +238,8 @@
#[cfg_attr(feature = "serialize", derive(Serialize))]
#[cfg_attr(feature = "deserialize", derive(Deserialize))]
-#[derive(Debug, PartialEq)]
+#[derive(Debug, PartialEq, Trace)]
+#[trivially_drop]
pub struct ObjComp {
pub pre_locals: Vec<BindSpec>,
pub key: LocExpr,
@@ -223,7 +250,8 @@
#[cfg_attr(feature = "serialize", derive(Serialize))]
#[cfg_attr(feature = "deserialize", derive(Deserialize))]
-#[derive(Debug, PartialEq)]
+#[derive(Debug, PartialEq, Trace)]
+#[trivially_drop]
pub enum ObjBody {
MemberList(Vec<Member>),
ObjComp(ObjComp),
@@ -231,7 +259,8 @@
#[cfg_attr(feature = "serialize", derive(Serialize))]
#[cfg_attr(feature = "deserialize", derive(Deserialize))]
-#[derive(Debug, PartialEq, Clone, Copy)]
+#[derive(Debug, PartialEq, Clone, Copy, Trace)]
+#[trivially_drop]
pub enum LiteralType {
This,
Super,
@@ -241,7 +270,8 @@
False,
}
-#[derive(Debug, PartialEq)]
+#[derive(Debug, PartialEq, Trace)]
+#[trivially_drop]
pub struct SliceDesc {
pub start: Option<LocExpr>,
pub end: Option<LocExpr>,
@@ -251,7 +281,8 @@
/// Syntax base
#[cfg_attr(feature = "serialize", derive(Serialize))]
#[cfg_attr(feature = "deserialize", derive(Deserialize))]
-#[derive(Debug, PartialEq)]
+#[derive(Debug, PartialEq, Trace)]
+#[trivially_drop]
pub enum Expr {
Literal(LiteralType),
@@ -319,8 +350,10 @@
/// file, begin offset, end offset
#[cfg_attr(feature = "serialize", derive(Serialize))]
#[cfg_attr(feature = "deserialize", derive(Deserialize))]
-#[derive(Clone, PartialEq)]
+#[derive(Clone, PartialEq, Trace)]
+#[trivially_drop]
pub struct ExprLocation(pub Rc<Path>, pub usize, pub usize);
+
impl Debug for ExprLocation {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{:?}:{:?}-{:?}", self.0, self.1, self.2)
@@ -332,6 +365,13 @@
#[cfg_attr(feature = "deserialize", derive(Deserialize))]
#[derive(Clone, PartialEq)]
pub struct LocExpr(pub Rc<Expr>, pub Option<ExprLocation>);
+/// Safety:
+/// AST is acyclic, and there should be no gc pointers
+unsafe impl Trace for LocExpr {
+ unsafe_empty_trace!();
+}
+impl Finalize for LocExpr {}
+
impl Debug for LocExpr {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
if f.alternate() {
crates/jrsonnet-types/Cargo.tomldiffbeforeafterboth--- a/crates/jrsonnet-types/Cargo.toml
+++ b/crates/jrsonnet-types/Cargo.toml
@@ -8,3 +8,4 @@
[dependencies]
peg = "0.7.0"
+jrsonnet-gc = { version = "0.4.2", features = ["derive"] }
crates/jrsonnet-types/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-types/src/lib.rs
+++ b/crates/jrsonnet-types/src/lib.rs
@@ -1,5 +1,6 @@
#![allow(clippy::redundant_closure_call)]
+use jrsonnet_gc::Trace;
use std::fmt::Display;
#[macro_export]
@@ -77,7 +78,8 @@
);
}
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Trace)]
+#[trivially_drop]
pub enum ValType {
Bool,
Null,
@@ -109,7 +111,8 @@
}
}
-#[derive(Debug, Clone, PartialEq)]
+#[derive(Debug, Clone, PartialEq, Trace)]
+#[trivially_drop]
pub enum ComplexValType {
Any,
Char,
@@ -123,6 +126,7 @@
Sum(Vec<ComplexValType>),
SumRef(&'static [ComplexValType]),
}
+
impl From<ValType> for ComplexValType {
fn from(s: ValType) -> Self {
Self::Simple(s)
flake.lockdiffbeforeafterboth--- a/flake.lock
+++ b/flake.lock
@@ -2,11 +2,11 @@
"nodes": {
"flake-utils": {
"locked": {
- "lastModified": 1614513358,
- "narHash": "sha256-LakhOx3S1dRjnh0b5Dg3mbZyH0ToC9I8Y2wKSkBaTzU=",
+ "lastModified": 1623875721,
+ "narHash": "sha256-A8BU7bjS5GirpAUv4QA+QnJ4CceLHkcXdRp4xITDB0s=",
"owner": "numtide",
"repo": "flake-utils",
- "rev": "5466c5bbece17adaab2d82fae80b46e807611bf3",
+ "rev": "f7e004a55b120c02ecb6219596820fcd32ca8772",
"type": "github"
},
"original": {
@@ -17,11 +17,11 @@
},
"nixpkgs": {
"locked": {
- "lastModified": 1615532953,
- "narHash": "sha256-SWpaGjrp/INzorEqMz3HLi6Uuk9I0KAn4YS8B4n3q5g=",
+ "lastModified": 1625281901,
+ "narHash": "sha256-DkZDtTIPzhXATqIps2ifNFpnI+PTcfMYdcrx/oFm00Q=",
"owner": "NixOS",
"repo": "nixpkgs",
- "rev": "916ee862e87ac5ee2439f2fb7856386b4dc906ae",
+ "rev": "09c38c29f2c719cd76ca17a596c2fdac9e186ceb",
"type": "github"
},
"original": {
flake.nixdiffbeforeafterboth--- a/flake.nix
+++ b/flake.nix
@@ -12,7 +12,7 @@
pname = "jrsonnet";
version = "0.1.0";
src = self;
- cargoSha256 = "sha256-6VhaQi3L2LWzR0cq7oRG81MDbrKJbzSNPcvYSoQ5ISo=";
+ cargoSha256 = "sha256-cez8pJ/uwj+PHAPQwpSB4CKaxcP8Uvv8xguOrVXR2xE=";
};
in {
defaultPackage = jrsonnet;