difftreelog
refactor switch to jrsonnet-gc
in: master
27 files changed
Cargo.lockdiffbeforeafterboth--- a/Cargo.lock
+++ b/Cargo.lock
@@ -100,27 +100,6 @@
]
[[package]]
-name = "gc"
-version = "0.4.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "3edaac0f5832202ebc99520cb77c932248010c4645d20be1dc62d6579f5b3752"
-dependencies = [
- "gc_derive",
-]
-
-[[package]]
-name = "gc_derive"
-version = "0.4.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "60df8444f094ff7885631d80e78eb7d88c3c2361a98daaabb06256e4500db941"
-dependencies = [
- "proc-macro2",
- "quote",
- "syn",
- "synstructure",
-]
-
-[[package]]
name = "hashbrown"
version = "0.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -190,7 +169,7 @@
"anyhow",
"base64",
"bincode",
- "gc",
+ "jrsonnet-gc",
"jrsonnet-interner",
"jrsonnet-parser",
"jrsonnet-stdlib",
@@ -204,10 +183,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 = [
- "gc",
+ "jrsonnet-gc",
"rustc-hash",
"serde",
]
@@ -216,7 +216,7 @@
name = "jrsonnet-parser"
version = "0.3.8"
dependencies = [
- "gc",
+ "jrsonnet-gc",
"jrsonnet-interner",
"jrsonnet-stdlib",
"peg",
@@ -232,7 +232,7 @@
name = "jrsonnet-types"
version = "0.3.8"
dependencies = [
- "gc",
+ "jrsonnet-gc",
"peg",
]
@@ -240,8 +240,8 @@
name = "jsonnet"
version = "0.3.8"
dependencies = [
- "gc",
"jrsonnet-evaluator",
+ "jrsonnet-gc",
"jrsonnet-parser",
]
bindings/jsonnet/Cargo.tomldiffbeforeafterboth--- a/bindings/jsonnet/Cargo.toml
+++ b/bindings/jsonnet/Cargo.toml
@@ -10,7 +10,7 @@
[dependencies]
jrsonnet-evaluator = { path = "../../crates/jrsonnet-evaluator", version = "0.3.8" }
jrsonnet-parser = { path = "../../crates/jrsonnet-parser", version = "0.3.8" }
-gc = { version = "0.4.1", features = ["derive"] }
+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,9 +1,9 @@
-use gc::{unsafe_empty_trace, Finalize, Gc, Trace};
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},
bindings/jsonnet/src/val_make.rsdiffbeforeafterboth--- a/bindings/jsonnet/src/val_make.rs
+++ b/bindings/jsonnet/src/val_make.rs
@@ -1,7 +1,7 @@
//! Create values in VM
-use gc::Gc;
use jrsonnet_evaluator::{ArrValue, EvaluationState, ObjValue, Val};
+use jrsonnet_gc::Gc;
use std::{
ffi::CStr,
os::raw::{c_char, c_double, c_int},
bindings/jsonnet/src/val_modify.rsdiffbeforeafterboth--- a/bindings/jsonnet/src/val_modify.rs
+++ b/bindings/jsonnet/src/val_modify.rs
@@ -2,8 +2,8 @@
//! Only tested with variables, which haven't altered by code before appearing here
//! In jrsonnet every value is immutable, and this code is probally broken
-use gc::Gc;
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};
crates/jrsonnet-evaluator/Cargo.tomldiffbeforeafterboth--- a/crates/jrsonnet-evaluator/Cargo.toml
+++ b/crates/jrsonnet-evaluator/Cargo.toml
@@ -35,7 +35,7 @@
rustc-hash = "1.1.0"
thiserror = "1.0"
-gc = { version = "0.4.1", features = ["derive"] }
+jrsonnet-gc = { version = "0.4.2", features = ["derive"] }
[dependencies.anyhow]
version = "1.0"
crates/jrsonnet-evaluator/src/builtin/format.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/builtin/format.rs
+++ b/crates/jrsonnet-evaluator/src/builtin/format.rs
@@ -2,12 +2,13 @@
#![allow(clippy::too_many_arguments)]
use crate::{error::Error::*, throw, LocError, ObjValue, Result, Val};
-use gc::{Finalize, Trace};
+use jrsonnet_gc::Trace;
use jrsonnet_interner::IStr;
use jrsonnet_types::ValType;
use thiserror::Error;
-#[derive(Debug, Clone, Error, Trace, Finalize)]
+#[derive(Debug, Clone, Error, Trace)]
+#[trivially_drop]
pub enum FormatError {
#[error("truncated format code")]
TruncatedFormatCode,
crates/jrsonnet-evaluator/src/builtin/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/builtin/mod.rs
+++ b/crates/jrsonnet-evaluator/src/builtin/mod.rs
@@ -5,7 +5,7 @@
EvaluationState, FuncVal, LazyVal, Val,
};
use format::{format_arr, format_obj};
-use gc::Gc;
+use jrsonnet_gc::Gc;
use jrsonnet_interner::IStr;
use jrsonnet_parser::{ArgsDesc, BinaryOpType, ExprLocation};
use jrsonnet_types::ty;
@@ -454,7 +454,7 @@
0, rest: ty!(any);
], {
println!("GC start");
- gc::force_collect();
+ jrsonnet_gc::force_collect();
println!("GC done");
Ok(rest)
crates/jrsonnet-evaluator/src/builtin/sort.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/builtin/sort.rs
+++ b/crates/jrsonnet-evaluator/src/builtin/sort.rs
@@ -2,7 +2,7 @@
error::{Error, LocError, Result},
throw, Context, FuncVal, Val,
};
-use gc::{Finalize, Gc, Trace};
+use jrsonnet_gc::{Finalize, Gc, Trace};
#[derive(Debug, Clone, thiserror::Error, Trace, Finalize)]
pub enum SortError {
crates/jrsonnet-evaluator/src/ctx.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/ctx.rs
+++ b/crates/jrsonnet-evaluator/src/ctx.rs
@@ -2,13 +2,14 @@
error::Error::*, map::LayeredHashMap, FutureWrapper, LazyBinding, LazyVal, ObjValue, Result,
Val,
};
-use gc::{Finalize, Gc, Trace};
+use jrsonnet_gc::{Gc, Trace};
use jrsonnet_interner::IStr;
use rustc_hash::FxHashMap;
use std::fmt::Debug;
use std::hash::BuildHasherDefault;
-#[derive(Clone, Trace, Finalize)]
+#[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> {
@@ -21,12 +22,13 @@
}
}
-#[derive(Trace, Finalize)]
+#[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 {
@@ -34,7 +36,8 @@
}
}
-#[derive(Debug, Clone, Trace, Finalize)]
+#[derive(Debug, Clone, Trace)]
+#[trivially_drop]
pub struct Context(Gc<ContextInternals>);
impl Context {
pub fn new_future() -> FutureWrapper<Self> {
crates/jrsonnet-evaluator/src/dynamic.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/dynamic.rs
+++ b/crates/jrsonnet-evaluator/src/dynamic.rs
@@ -1,6 +1,7 @@
-use gc::{Finalize, Gc, GcCell, Trace};
+use jrsonnet_gc::{Gc, GcCell, Trace};
-#[derive(Clone, Trace, Finalize)]
+#[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 {
crates/jrsonnet-evaluator/src/error.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/error.rs
+++ b/crates/jrsonnet-evaluator/src/error.rs
@@ -2,7 +2,7 @@
builtin::{format::FormatError, sort::SortError},
typed::TypeLocError,
};
-use gc::{Finalize, Trace};
+use jrsonnet_gc::Trace;
use jrsonnet_interner::IStr;
use jrsonnet_parser::{BinaryOpType, ExprLocation, UnaryOpType};
use jrsonnet_types::ValType;
@@ -12,7 +12,8 @@
};
use thiserror::Error;
-#[derive(Error, Debug, Clone, Trace, Finalize)]
+#[derive(Error, Debug, Clone, Trace)]
+#[trivially_drop]
pub enum Error {
#[error("intrinsic not found: {0}")]
IntrinsicNotFound(IStr),
@@ -149,15 +150,18 @@
}
}
-#[derive(Clone, Debug, Trace, Finalize)]
+#[derive(Clone, Debug, Trace)]
+#[trivially_drop]
pub struct StackTraceElement {
pub location: Option<ExprLocation>,
pub desc: String,
}
-#[derive(Debug, Clone, Trace, Finalize)]
+#[derive(Debug, Clone, Trace)]
+#[trivially_drop]
pub struct StackTrace(pub Vec<StackTraceElement>);
-#[derive(Debug, Clone, Trace, Finalize)]
+#[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::*, push, throw, with_state, ArrValue, Bindable, Context, ContextCreator,3 FuncDesc, FuncVal, FutureWrapper, LazyBinding, LazyVal, LazyValValue, ObjMember, ObjValue,4 ObjectAssertion, Result, Val,5};6use gc::{custom_trace, Finalize, 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 struct LazyMethodBinding {26 context_creator: FutureWrapper<Context>,27 name: IStr,28 params: ParamsDesc,29 value: LocExpr,30 }31 impl Finalize for LazyMethodBinding {}32 unsafe impl Trace for LazyMethodBinding {33 custom_trace!(this, {34 mark(&this.context_creator);35 mark(&this.name);36 mark(&this.params);37 mark(&this.value);38 });39 }40 impl LazyValValue for LazyMethodBinding {41 fn get(self: Box<Self>) -> Result<Val> {42 Ok(evaluate_method(43 self.context_creator.unwrap(),44 self.name,45 self.params,46 self.value,47 ))48 }49 }5051 LazyVal::new(Box::new(LazyMethodBinding {52 context_creator,53 name: b.name.clone(),54 params,55 value: b.value.clone(),56 }))57 } else {58 struct LazyNamedBinding {59 context_creator: FutureWrapper<Context>,60 name: IStr,61 value: LocExpr,62 }63 impl Finalize for LazyNamedBinding {}64 unsafe impl Trace for LazyNamedBinding {65 custom_trace!(this, {66 mark(&this.context_creator);67 mark(&this.name);68 mark(&this.value);69 });70 }71 impl LazyValValue for LazyNamedBinding {72 fn get(self: Box<Self>) -> Result<Val> {73 evaluate_named(self.context_creator.unwrap(), &self.value, self.name)74 }75 }76 LazyVal::new(Box::new(LazyNamedBinding {77 context_creator,78 name: b.name.clone(),79 value: b.value,80 }))81 }82}8384pub fn evaluate_binding(b: &BindSpec, context_creator: ContextCreator) -> (IStr, LazyBinding) {85 let b = b.clone();86 if let Some(params) = &b.params {87 let params = params.clone();8889 struct BindableMethodLazyVal {90 this: Option<ObjValue>,91 super_obj: Option<ObjValue>,9293 context_creator: ContextCreator,94 name: IStr,95 params: ParamsDesc,96 value: LocExpr,97 }98 impl Finalize for BindableMethodLazyVal {}99 unsafe impl Trace for BindableMethodLazyVal {100 custom_trace!(this, {101 mark(&this.this);102 mark(&this.super_obj);103 mark(&this.context_creator);104 mark(&this.name);105 mark(&this.params);106 mark(&this.value);107 });108 }109 impl LazyValValue for BindableMethodLazyVal {110 fn get(self: Box<Self>) -> Result<Val> {111 Ok(evaluate_method(112 self.context_creator.create(self.this, self.super_obj)?,113 self.name,114 self.params,115 self.value,116 ))117 }118 }119120 #[derive(Trace, Finalize)]121 struct BindableMethod {122 context_creator: ContextCreator,123 name: IStr,124 params: ParamsDesc,125 value: LocExpr,126 }127 impl Bindable for BindableMethod {128 fn bind(&self, this: Option<ObjValue>, super_obj: Option<ObjValue>) -> Result<LazyVal> {129 Ok(LazyVal::new(Box::new(BindableMethodLazyVal {130 this,131 super_obj,132133 context_creator: self.context_creator.clone(),134 name: self.name.clone(),135 params: self.params.clone(),136 value: self.value.clone(),137 })))138 }139 }140141 (142 b.name.clone(),143 LazyBinding::Bindable(Gc::new(Box::new(BindableMethod {144 context_creator,145 name: b.name.clone(),146 params,147 value: b.value.clone(),148 }))),149 )150 } else {151 struct BindableNamedLazyVal {152 this: Option<ObjValue>,153 super_obj: Option<ObjValue>,154155 context_creator: ContextCreator,156 name: IStr,157 value: LocExpr,158 }159 impl Finalize for BindableNamedLazyVal {}160 unsafe impl Trace for BindableNamedLazyVal {161 custom_trace!(this, {162 mark(&this.this);163 mark(&this.super_obj);164 mark(&this.context_creator);165 mark(&this.name);166 mark(&this.value);167 });168 }169 impl LazyValValue for BindableNamedLazyVal {170 fn get(self: Box<Self>) -> Result<Val> {171 evaluate_named(172 self.context_creator.create(self.this, self.super_obj)?,173 &self.value,174 self.name,175 )176 }177 }178179 #[derive(Trace, Finalize)]180 struct BindableNamed {181 context_creator: ContextCreator,182 name: IStr,183 value: LocExpr,184 }185 impl Bindable for BindableNamed {186 fn bind(&self, this: Option<ObjValue>, super_obj: Option<ObjValue>) -> Result<LazyVal> {187 Ok(LazyVal::new(Box::new(BindableNamedLazyVal {188 this,189 super_obj,190191 context_creator: self.context_creator.clone(),192 name: self.name.clone(),193 value: self.value.clone(),194 })))195 }196 }197198 (199 b.name.clone(),200 LazyBinding::Bindable(Gc::new(Box::new(BindableNamed {201 context_creator,202 name: b.name.clone(),203 value: b.value.clone(),204 }))),205 )206 }207}208209pub fn evaluate_method(ctx: Context, name: IStr, params: ParamsDesc, body: LocExpr) -> Val {210 Val::Func(Gc::new(FuncVal::Normal(FuncDesc {211 name,212 ctx,213 params,214 body,215 })))216}217218pub fn evaluate_field_name(219 context: Context,220 field_name: &jrsonnet_parser::FieldName,221) -> Result<Option<IStr>> {222 Ok(match field_name {223 jrsonnet_parser::FieldName::Fixed(n) => Some(n.clone()),224 jrsonnet_parser::FieldName::Dyn(expr) => {225 let value = evaluate(context, expr)?;226 if matches!(value, Val::Null) {227 None228 } else {229 Some(value.try_cast_str("dynamic field name")?)230 }231 }232 })233}234235pub fn evaluate_unary_op(op: UnaryOpType, b: &Val) -> Result<Val> {236 Ok(match (op, b) {237 (UnaryOpType::Not, Val::Bool(v)) => Val::Bool(!v),238 (UnaryOpType::Minus, Val::Num(n)) => Val::Num(-*n),239 (UnaryOpType::BitNot, Val::Num(n)) => Val::Num(!(*n as i32) as f64),240 (op, o) => throw!(UnaryOperatorDoesNotOperateOnType(op, o.value_type())),241 })242}243244pub fn evaluate_add_op(a: &Val, b: &Val) -> Result<Val> {245 Ok(match (a, b) {246 (Val::DebugGcTraceValue(v1), Val::DebugGcTraceValue(v2)) => {247 evaluate_add_op(&v1.value, &v2.value)?248 }249 (Val::Str(v1), Val::Str(v2)) => Val::Str(((**v1).to_owned() + v2).into()),250251 // Can't use generic json serialization way, because it depends on number to string concatenation (std.jsonnet:890)252 (Val::Num(n), Val::Str(o)) => Val::Str(format!("{}{}", n, o).into()),253 (Val::Str(o), Val::Num(n)) => Val::Str(format!("{}{}", o, n).into()),254255 (Val::Str(s), o) => Val::Str(format!("{}{}", s, o.clone().to_string()?).into()),256 (o, Val::Str(s)) => Val::Str(format!("{}{}", o.clone().to_string()?, s).into()),257258 (Val::Obj(v1), Val::Obj(v2)) => Val::Obj(v2.extend_from(v1.clone())),259 (Val::Arr(a), Val::Arr(b)) => {260 let mut out = Vec::with_capacity(a.len() + b.len());261 out.extend(a.iter_lazy());262 out.extend(b.iter_lazy());263 Val::Arr(out.into())264 }265 (Val::Num(v1), Val::Num(v2)) => Val::new_checked_num(v1 + v2)?,266 _ => throw!(BinaryOperatorDoesNotOperateOnValues(267 BinaryOpType::Add,268 a.value_type(),269 b.value_type(),270 )),271 })272}273274pub fn evaluate_binary_op_special(275 context: Context,276 a: &LocExpr,277 op: BinaryOpType,278 b: &LocExpr,279) -> Result<Val> {280 Ok(match (evaluate(context.clone(), a)?, op, b) {281 (Val::Bool(true), BinaryOpType::Or, _o) => Val::Bool(true),282 (Val::Bool(false), BinaryOpType::And, _o) => Val::Bool(false),283 (a, op, eb) => evaluate_binary_op_normal(&a, op, &evaluate(context, eb)?)?,284 })285}286287pub fn evaluate_binary_op_normal(a: &Val, op: BinaryOpType, b: &Val) -> Result<Val> {288 Ok(match (a, op, b) {289 (a, BinaryOpType::Add, b) => evaluate_add_op(a, b)?,290291 (a, BinaryOpType::Eq, b) => Val::Bool(equals(a, b)?),292 (a, BinaryOpType::Neq, b) => Val::Bool(!equals(a, b)?),293294 (Val::Str(v1), BinaryOpType::Mul, Val::Num(v2)) => Val::Str(v1.repeat(*v2 as usize).into()),295296 // Bool X Bool297 (Val::Bool(a), BinaryOpType::And, Val::Bool(b)) => Val::Bool(*a && *b),298 (Val::Bool(a), BinaryOpType::Or, Val::Bool(b)) => Val::Bool(*a || *b),299300 // Str X Str301 (Val::Str(v1), BinaryOpType::Lt, Val::Str(v2)) => Val::Bool(v1 < v2),302 (Val::Str(v1), BinaryOpType::Gt, Val::Str(v2)) => Val::Bool(v1 > v2),303 (Val::Str(v1), BinaryOpType::Lte, Val::Str(v2)) => Val::Bool(v1 <= v2),304 (Val::Str(v1), BinaryOpType::Gte, Val::Str(v2)) => Val::Bool(v1 >= v2),305306 // Num X Num307 (Val::Num(v1), BinaryOpType::Mul, Val::Num(v2)) => Val::new_checked_num(v1 * v2)?,308 (Val::Num(v1), BinaryOpType::Div, Val::Num(v2)) => {309 if *v2 <= f64::EPSILON {310 throw!(DivisionByZero)311 }312 Val::new_checked_num(v1 / v2)?313 }314315 (Val::Num(v1), BinaryOpType::Sub, Val::Num(v2)) => Val::new_checked_num(v1 - v2)?,316317 (Val::Num(v1), BinaryOpType::Lt, Val::Num(v2)) => Val::Bool(v1 < v2),318 (Val::Num(v1), BinaryOpType::Gt, Val::Num(v2)) => Val::Bool(v1 > v2),319 (Val::Num(v1), BinaryOpType::Lte, Val::Num(v2)) => Val::Bool(v1 <= v2),320 (Val::Num(v1), BinaryOpType::Gte, Val::Num(v2)) => Val::Bool(v1 >= v2),321322 (Val::Num(v1), BinaryOpType::BitAnd, Val::Num(v2)) => {323 Val::Num(((*v1 as i32) & (*v2 as i32)) as f64)324 }325 (Val::Num(v1), BinaryOpType::BitOr, Val::Num(v2)) => {326 Val::Num(((*v1 as i32) | (*v2 as i32)) as f64)327 }328 (Val::Num(v1), BinaryOpType::BitXor, Val::Num(v2)) => {329 Val::Num(((*v1 as i32) ^ (*v2 as i32)) as f64)330 }331 (Val::Num(v1), BinaryOpType::Lhs, Val::Num(v2)) => {332 if *v2 < 0.0 {333 throw!(RuntimeError("shift by negative exponent".into()))334 }335 Val::Num(((*v1 as i32) << (*v2 as i32)) as f64)336 }337 (Val::Num(v1), BinaryOpType::Rhs, Val::Num(v2)) => {338 if *v2 < 0.0 {339 throw!(RuntimeError("shift by negative exponent".into()))340 }341 Val::Num(((*v1 as i32) >> (*v2 as i32)) as f64)342 }343344 _ => throw!(BinaryOperatorDoesNotOperateOnValues(345 op,346 a.value_type(),347 b.value_type(),348 )),349 })350}351352pub fn evaluate_comp(353 context: Context,354 specs: &[CompSpec],355 callback: &mut impl FnMut(Context) -> Result<()>,356) -> Result<()> {357 match specs.get(0) {358 None => callback(context)?,359 Some(CompSpec::IfSpec(IfSpecData(cond))) => {360 if evaluate(context.clone(), cond)?.try_cast_bool("if spec")? {361 evaluate_comp(context, &specs[1..], callback)?362 }363 }364 Some(CompSpec::ForSpec(ForSpecData(var, expr))) => match evaluate(context.clone(), expr)? {365 Val::Arr(list) => {366 for item in list.iter() {367 evaluate_comp(368 context.clone().with_var(var.clone(), item?.clone()),369 &specs[1..],370 callback,371 )?372 }373 }374 _ => throw!(InComprehensionCanOnlyIterateOverArray),375 },376 }377 Ok(())378}379380pub fn evaluate_member_list_object(context: Context, members: &[Member]) -> Result<ObjValue> {381 let new_bindings = FutureWrapper::new();382 let future_this = FutureWrapper::new();383 let context_creator = ContextCreator(context.clone(), new_bindings.clone());384 {385 let mut bindings: FxHashMap<IStr, LazyBinding> =386 FxHashMap::with_capacity_and_hasher(members.len(), BuildHasherDefault::default());387 for (n, b) in members388 .iter()389 .filter_map(|m| match m {390 Member::BindStmt(b) => Some(b.clone()),391 _ => None,392 })393 .map(|b| evaluate_binding(&b, context_creator.clone()))394 {395 bindings.insert(n, b);396 }397 new_bindings.fill(bindings);398 }399400 let mut new_members = FxHashMap::default();401 let mut assertions: Vec<Box<dyn ObjectAssertion>> = Vec::new();402 for member in members.iter() {403 match member {404 Member::Field(FieldMember {405 name,406 plus,407 params: None,408 visibility,409 value,410 }) => {411 let name = evaluate_field_name(context.clone(), name)?;412 if name.is_none() {413 continue;414 }415 let name = name.unwrap();416417 #[derive(Trace, Finalize)]418 struct ObjMemberBinding {419 context_creator: ContextCreator,420 value: LocExpr,421 name: IStr,422 }423 impl Bindable for ObjMemberBinding {424 fn bind(425 &self,426 this: Option<ObjValue>,427 super_obj: Option<ObjValue>,428 ) -> Result<LazyVal> {429 Ok(LazyVal::new_resolved(evaluate_named(430 self.context_creator.create(this, super_obj)?,431 &self.value,432 self.name.clone(),433 )?))434 }435 }436 new_members.insert(437 name.clone(),438 ObjMember {439 add: *plus,440 visibility: *visibility,441 invoke: LazyBinding::Bindable(Gc::new(Box::new(ObjMemberBinding {442 context_creator: context_creator.clone(),443 value: value.clone(),444 name,445 }))),446 location: value.1.clone(),447 },448 );449 }450 Member::Field(FieldMember {451 name,452 params: Some(params),453 value,454 ..455 }) => {456 let name = evaluate_field_name(context.clone(), name)?;457 if name.is_none() {458 continue;459 }460 let name = name.unwrap();461 #[derive(Trace, Finalize)]462 struct ObjMemberBinding {463 context_creator: ContextCreator,464 value: LocExpr,465 params: ParamsDesc,466 name: IStr,467 }468 impl Bindable for ObjMemberBinding {469 fn bind(470 &self,471 this: Option<ObjValue>,472 super_obj: Option<ObjValue>,473 ) -> Result<LazyVal> {474 Ok(LazyVal::new_resolved(evaluate_method(475 self.context_creator.create(this, super_obj)?,476 self.name.clone(),477 self.params.clone(),478 self.value.clone(),479 )))480 }481 }482 new_members.insert(483 name.clone(),484 ObjMember {485 add: false,486 visibility: Visibility::Hidden,487 invoke: LazyBinding::Bindable(Gc::new(Box::new(ObjMemberBinding {488 context_creator: context_creator.clone(),489 value: value.clone(),490 params: params.clone(),491 name,492 }))),493 location: value.1.clone(),494 },495 );496 }497 Member::BindStmt(_) => {}498 Member::AssertStmt(stmt) => {499 struct ObjectAssert {500 context_creator: ContextCreator,501 assert: AssertStmt,502 }503 impl Finalize for ObjectAssert {}504 unsafe impl Trace for ObjectAssert {505 custom_trace!(this, {506 mark(&this.context_creator);507 mark(&this.assert);508 });509 }510 impl ObjectAssertion for ObjectAssert {511 fn run(512 &self,513 this: Option<ObjValue>,514 super_obj: Option<ObjValue>,515 ) -> Result<()> {516 let ctx = self.context_creator.create(this, super_obj)?;517 evaluate_assert(ctx, &self.assert)518 }519 }520 assertions.push(Box::new(ObjectAssert {521 context_creator: context_creator.clone(),522 assert: stmt.clone(),523 }));524 }525 }526 }527 let this = ObjValue::new(None, Gc::new(new_members), Gc::new(assertions));528 future_this.fill(this.clone());529 Ok(this)530}531532pub fn evaluate_object(context: Context, object: &ObjBody) -> Result<ObjValue> {533 Ok(match object {534 ObjBody::MemberList(members) => evaluate_member_list_object(context, members)?,535 ObjBody::ObjComp(obj) => {536 let future_this = FutureWrapper::new();537 let mut new_members = FxHashMap::default();538 evaluate_comp(context.clone(), &obj.compspecs, &mut |ctx| {539 let new_bindings = FutureWrapper::new();540 let context_creator = ContextCreator(context.clone(), new_bindings.clone());541 let mut bindings: FxHashMap<IStr, LazyBinding> =542 FxHashMap::with_capacity_and_hasher(543 obj.pre_locals.len() + obj.post_locals.len(),544 BuildHasherDefault::default(),545 );546 for (n, b) in obj547 .pre_locals548 .iter()549 .chain(obj.post_locals.iter())550 .map(|b| evaluate_binding(b, context_creator.clone()))551 {552 bindings.insert(n, b);553 }554 new_bindings.fill(bindings.clone());555 let ctx = ctx.extend_unbound(bindings, None, None, None)?;556 let key = evaluate(ctx.clone(), &obj.key)?;557558 match key {559 Val::Null => {}560 Val::Str(n) => {561 #[derive(Trace, Finalize)]562 struct ObjCompBinding {563 context: Context,564 value: LocExpr,565 }566 impl Bindable for ObjCompBinding {567 fn bind(568 &self,569 this: Option<ObjValue>,570 _super_obj: Option<ObjValue>,571 ) -> Result<LazyVal> {572 Ok(LazyVal::new_resolved(evaluate(573 self.context.clone().extend(574 FxHashMap::default(),575 None,576 this,577 None,578 ),579 &self.value,580 )?))581 }582 }583 new_members.insert(584 n,585 ObjMember {586 add: false,587 visibility: Visibility::Normal,588 invoke: LazyBinding::Bindable(Gc::new(Box::new(ObjCompBinding {589 context: ctx,590 value: obj.value.clone(),591 }))),592 location: obj.value.1.clone(),593 },594 );595 }596 v => throw!(FieldMustBeStringGot(v.value_type())),597 }598599 Ok(())600 })?;601602 let this = ObjValue::new(None, Gc::new(new_members), Gc::new(Vec::new()));603 future_this.fill(this.clone());604 this605 }606 })607}608609pub fn evaluate_apply(610 context: Context,611 value: &LocExpr,612 args: &ArgsDesc,613 loc: Option<&ExprLocation>,614 tailstrict: bool,615) -> Result<Val> {616 let value = evaluate(context.clone(), value)?;617 Ok(match value {618 Val::Func(f) => {619 let body = || f.evaluate(context, loc, args, tailstrict);620 if tailstrict {621 body()?622 } else {623 push(loc, || format!("function <{}> call", f.name()), body)?624 }625 }626 v => throw!(OnlyFunctionsCanBeCalledGot(v.value_type())),627 })628}629630pub fn evaluate_assert(context: Context, assertion: &AssertStmt) -> Result<()> {631 let value = &assertion.0;632 let msg = &assertion.1;633 let assertion_result = push(634 value.1.as_ref(),635 || "assertion condition".to_owned(),636 || {637 evaluate(context.clone(), value)?638 .try_cast_bool("assertion condition should be of type `boolean`")639 },640 )?;641 if !assertion_result {642 push(643 value.1.as_ref(),644 || "assertion failure".to_owned(),645 || {646 if let Some(msg) = msg {647 throw!(AssertionFailed(evaluate(context, msg)?.to_string()?));648 } else {649 throw!(AssertionFailed(Val::Null.to_string()?));650 }651 },652 )?653 }654 Ok(())655}656657pub fn evaluate_named(context: Context, lexpr: &LocExpr, name: IStr) -> Result<Val> {658 use Expr::*;659 let LocExpr(expr, _loc) = lexpr;660 Ok(match &**expr {661 Function(params, body) => evaluate_method(context, name, params.clone(), body.clone()),662 _ => evaluate(context, lexpr)?,663 })664}665666pub fn evaluate(context: Context, expr: &LocExpr) -> Result<Val> {667 use Expr::*;668 let LocExpr(expr, loc) = expr;669 Ok(match &**expr {670 Literal(LiteralType::This) => {671 Val::Obj(context.this().clone().ok_or(CantUseSelfOutsideOfObject)?)672 }673 Literal(LiteralType::Super) => Val::Obj(674 context675 .super_obj()676 .clone()677 .ok_or(NoSuperFound)?678 .with_this(context.this().clone().unwrap()),679 ),680 Literal(LiteralType::Dollar) => {681 Val::Obj(context.dollar().clone().ok_or(NoTopLevelObjectFound)?)682 }683 Literal(LiteralType::True) => Val::Bool(true),684 Literal(LiteralType::False) => Val::Bool(false),685 Literal(LiteralType::Null) => Val::Null,686 Parened(e) => evaluate(context, e)?,687 Str(v) => Val::Str(v.clone()),688 Num(v) => Val::new_checked_num(*v)?,689 BinaryOp(v1, o, v2) => evaluate_binary_op_special(context, v1, *o, v2)?,690 UnaryOp(o, v) => evaluate_unary_op(*o, &evaluate(context, v)?)?,691 Var(name) => push(692 loc.as_ref(),693 || format!("variable <{}>", name),694 || context.binding(name.clone())?.evaluate(),695 )?,696 Index(value, index) => {697 match (evaluate(context.clone(), value)?, evaluate(context, index)?) {698 (Val::Obj(v), Val::Str(s)) => {699 let sn = s.clone();700 push(701 loc.as_ref(),702 || format!("field <{}> access", sn),703 || {704 if let Some(v) = v.get(s.clone())? {705 Ok(v)706 } else if v.get("__intrinsic_namespace__".into())?.is_some() {707 Ok(Val::Func(Gc::new(FuncVal::Intrinsic(s))))708 } else {709 throw!(NoSuchField(s))710 }711 },712 )?713 }714 (Val::Obj(_), n) => throw!(ValueIndexMustBeTypeGot(715 ValType::Obj,716 ValType::Str,717 n.value_type(),718 )),719720 (Val::Arr(v), Val::Num(n)) => {721 if n.fract() > f64::EPSILON {722 throw!(FractionalIndex)723 }724 v.get(n as usize)?725 .ok_or_else(|| ArrayBoundsError(n as usize, v.len()))?726 }727 (Val::Arr(_), Val::Str(n)) => throw!(AttemptedIndexAnArrayWithString(n)),728 (Val::Arr(_), n) => throw!(ValueIndexMustBeTypeGot(729 ValType::Arr,730 ValType::Num,731 n.value_type(),732 )),733734 (Val::Str(s), Val::Num(n)) => Val::Str(735 s.chars()736 .skip(n as usize)737 .take(1)738 .collect::<String>()739 .into(),740 ),741 (Val::Str(_), n) => throw!(ValueIndexMustBeTypeGot(742 ValType::Str,743 ValType::Num,744 n.value_type(),745 )),746747 (v, _) => throw!(CantIndexInto(v.value_type())),748 }749 }750 LocalExpr(bindings, returned) => {751 let mut new_bindings: FxHashMap<IStr, LazyVal> = HashMap::with_capacity_and_hasher(752 bindings.len(),753 BuildHasherDefault::<FxHasher>::default(),754 );755 let future_context = Context::new_future();756 for b in bindings {757 new_bindings.insert(758 b.name.clone(),759 evaluate_binding_in_future(b, future_context.clone()),760 );761 }762 let context = context763 .extend_bound(new_bindings)764 .into_future(future_context);765 evaluate(context, &returned.clone())?766 }767 Arr(items) => {768 let mut out = Vec::with_capacity(items.len());769 for item in items {770 // TODO: Implement ArrValue::Lazy with same context for every element?771 struct ArrayElement {772 context: Context,773 item: LocExpr,774 }775 impl Finalize for ArrayElement {}776 unsafe impl Trace for ArrayElement {777 custom_trace!(this, {778 mark(&this.context);779 mark(&this.item);780 });781 }782 impl LazyValValue for ArrayElement {783 fn get(self: Box<Self>) -> Result<Val> {784 evaluate(self.context, &self.item)785 }786 }787 out.push(LazyVal::new(Box::new(ArrayElement {788 context: context.clone(),789 item: item.clone(),790 })));791 }792 Val::Arr(out.into())793 }794 ArrComp(expr, comp_specs) => {795 let mut out = Vec::new();796 evaluate_comp(context, comp_specs, &mut |ctx| {797 out.push(evaluate(ctx, expr)?);798 Ok(())799 })?;800 Val::Arr(ArrValue::Eager(Gc::new(out)))801 }802 Obj(body) => Val::Obj(evaluate_object(context, body)?),803 ObjExtend(s, t) => evaluate_add_op(804 &evaluate(context.clone(), s)?,805 &Val::Obj(evaluate_object(context, t)?),806 )?,807 Apply(value, args, tailstrict) => {808 evaluate_apply(context, value, args, loc.as_ref(), *tailstrict)?809 }810 Function(params, body) => {811 evaluate_method(context, "anonymous".into(), params.clone(), body.clone())812 }813 Intrinsic(name) => Val::Func(Gc::new(FuncVal::Intrinsic(name.clone()))),814 AssertExpr(assert, returned) => {815 evaluate_assert(context.clone(), assert)?;816 evaluate(context, returned)?817 }818 ErrorStmt(e) => push(819 loc.as_ref(),820 || "error statement".to_owned(),821 || {822 throw!(RuntimeError(823 evaluate(context, e)?.try_cast_str("error text should be of type `string`")?,824 ))825 },826 )?,827 IfElse {828 cond,829 cond_then,830 cond_else,831 } => {832 if push(833 loc.as_ref(),834 || "if condition".to_owned(),835 || evaluate(context.clone(), &cond.0)?.try_cast_bool("in if condition"),836 )? {837 evaluate(context, cond_then)?838 } else {839 match cond_else {840 Some(v) => evaluate(context, v)?,841 None => Val::Null,842 }843 }844 }845 Import(path) => {846 let tmp = loc847 .clone()848 .expect("imports cannot be used without loc_data")849 .0;850 let mut import_location = tmp.to_path_buf();851 import_location.pop();852 push(853 loc.as_ref(),854 || format!("import {:?}", path),855 || with_state(|s| s.import_file(&import_location, path)),856 )?857 }858 ImportStr(path) => {859 let tmp = loc860 .clone()861 .expect("imports cannot be used without loc_data")862 .0;863 let mut import_location = tmp.to_path_buf();864 import_location.pop();865 Val::Str(with_state(|s| s.import_file_str(&import_location, path))?)866 }867 })868}crates/jrsonnet-evaluator/src/function.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/function.rs
+++ b/crates/jrsonnet-evaluator/src/function.rs
@@ -1,5 +1,5 @@
use crate::{error::Error::*, evaluate, throw, Context, LazyVal, LazyValValue, Result, Val};
-use gc::{custom_trace, Finalize, Trace};
+use jrsonnet_gc::Trace;
use jrsonnet_interner::IStr;
use jrsonnet_parser::{ArgsDesc, LocExpr, ParamsDesc};
use rustc_hash::FxHashMap;
@@ -55,16 +55,11 @@
let val = if tailstrict {
LazyVal::new_resolved(evaluate(ctx, expr)?)
} else {
+ #[derive(Trace)]
+ #[trivially_drop]
struct EvaluateLazyVal {
context: Context,
expr: LocExpr,
- }
- impl Finalize for EvaluateLazyVal {}
- unsafe impl Trace for EvaluateLazyVal {
- custom_trace!(this, {
- mark(&this.context);
- mark(&this.expr);
- });
}
impl LazyValValue for EvaluateLazyVal {
fn get(self: Box<Self>) -> Result<Val> {
@@ -119,7 +114,8 @@
} else {
let body_ctx = body_ctx.clone();
let default = default.clone();
- #[derive(Trace, Finalize)]
+ #[derive(Trace)]
+ #[trivially_drop]
struct EvaluateLazyVal {
body_ctx: Option<Context>,
default: LocExpr,
crates/jrsonnet-evaluator/src/integrations/serde.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/integrations/serde.rs
+++ b/crates/jrsonnet-evaluator/src/integrations/serde.rs
@@ -2,7 +2,7 @@
error::{Error::*, LocError, Result},
throw, LazyBinding, LazyVal, ObjMember, ObjValue, Val,
};
-use gc::Gc;
+use jrsonnet_gc::Gc;
use jrsonnet_parser::Visibility;
use rustc_hash::FxHasher;
use serde_json::{Map, Number, Value};
crates/jrsonnet-evaluator/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/lib.rs
+++ b/crates/jrsonnet-evaluator/src/lib.rs
@@ -25,8 +25,8 @@
use error::{Error::*, LocError, Result, StackTraceElement};
pub use evaluate::*;
pub use function::parse_function_call;
-use gc::{Finalize, Gc, Trace};
pub use import::*;
+use jrsonnet_gc::{Finalize, Gc, Trace};
pub use jrsonnet_interner::IStr;
use jrsonnet_parser::*;
use native::NativeCallback;
crates/jrsonnet-evaluator/src/map.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/map.rs
+++ b/crates/jrsonnet-evaluator/src/map.rs
@@ -1,32 +1,29 @@
-use gc::{Finalize, Gc, Trace};
+use jrsonnet_gc::{Gc, Trace};
use jrsonnet_interner::IStr;
use rustc_hash::FxHashMap;
-pub struct LayeredHashMapInternals<V: Trace + Finalize + 'static> {
- parent: Option<LayeredHashMap<V>>,
- current: FxHashMap<IStr, V>,
-}
+use crate::LazyVal;
-unsafe impl<V: Trace + Finalize + 'static> Trace for LayeredHashMapInternals<V> {
- gc::custom_trace!(this, {
- mark(&this.parent);
- mark(&this.current);
- });
+#[derive(Trace)]
+#[trivially_drop]
+pub struct LayeredHashMapInternals {
+ parent: Option<LayeredHashMap>,
+ current: FxHashMap<IStr, LazyVal>,
}
-impl<V: Trace + Finalize + 'static> Finalize for LayeredHashMapInternals<V> {}
-#[derive(Trace, Finalize)]
-pub struct LayeredHashMap<V: Trace + Finalize + 'static>(Gc<LayeredHashMapInternals<V>>);
+#[derive(Trace)]
+#[trivially_drop]
+pub struct LayeredHashMap(Gc<LayeredHashMapInternals>);
-impl<V: Trace + 'static> LayeredHashMap<V> {
- pub fn extend(self, new_layer: FxHashMap<IStr, V>) -> Self {
+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)
@@ -34,13 +31,13 @@
}
}
-impl<V: Trace + 'static> Clone for LayeredHashMap<V> {
+impl Clone for LayeredHashMap {
fn clone(&self) -> Self {
Self(self.0.clone())
}
}
-impl<V: Trace + 'static> Default for LayeredHashMap<V> {
+impl Default for LayeredHashMap {
fn default() -> Self {
Self(Gc::new(LayeredHashMapInternals {
parent: None,
crates/jrsonnet-evaluator/src/native.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/native.rs
+++ b/crates/jrsonnet-evaluator/src/native.rs
@@ -1,7 +1,7 @@
#![allow(clippy::type_complexity)]
use crate::{error::Result, Val};
-use gc::{Finalize, Trace};
+use jrsonnet_gc::Trace;
use jrsonnet_parser::ParamsDesc;
use std::fmt::Debug;
use std::path::Path;
@@ -11,7 +11,8 @@
fn call(&self, from: Option<Rc<Path>>, args: &[Val]) -> Result<Val>;
}
-#[derive(Trace, Finalize)]
+#[derive(Trace)]
+#[trivially_drop]
pub struct NativeCallback {
pub params: ParamsDesc,
handler: Box<dyn NativeCallbackHandler>,
crates/jrsonnet-evaluator/src/obj.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/obj.rs
+++ b/crates/jrsonnet-evaluator/src/obj.rs
@@ -1,12 +1,13 @@
use crate::{evaluate_add_op, LazyBinding, Result, Val};
-use gc::{Finalize, Gc, GcCell, Trace};
+use jrsonnet_gc::{Gc, GcCell, Trace};
use jrsonnet_interner::IStr;
use jrsonnet_parser::{ExprLocation, Visibility};
use rustc_hash::{FxHashMap, FxHashSet};
use std::hash::{Hash, Hasher};
use std::{fmt::Debug, hash::BuildHasherDefault};
-#[derive(Debug, Trace, Finalize)]
+#[derive(Debug, Trace)]
+#[trivially_drop]
pub struct ObjMember {
pub add: bool,
pub visibility: Visibility,
@@ -20,7 +21,8 @@
// Field => This
type CacheKey = (IStr, ObjValue);
-#[derive(Trace, Finalize)]
+#[derive(Trace)]
+#[trivially_drop]
pub struct ObjValueInternals {
super_obj: Option<ObjValue>,
assertions: Gc<Vec<Box<dyn ObjectAssertion>>>,
@@ -30,7 +32,8 @@
value_cache: GcCell<FxHashMap<CacheKey, Option<Val>>>,
}
-#[derive(Clone, Trace, Finalize)]
+#[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 {
crates/jrsonnet-evaluator/src/typed.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/typed.rs
+++ b/crates/jrsonnet-evaluator/src/typed.rs
@@ -4,7 +4,7 @@
error::{Error, LocError, Result},
push, Val,
};
-use gc::{Finalize, Trace};
+use jrsonnet_gc::Trace;
use jrsonnet_parser::ExprLocation;
use jrsonnet_types::{ComplexValType, ValType};
use thiserror::Error;
@@ -21,7 +21,8 @@
}};
}
-#[derive(Debug, Error, Clone, Trace, Finalize)]
+#[derive(Debug, Error, Clone, Trace)]
+#[trivially_drop]
pub enum TypeError {
#[error("expected {0}, got {1}")]
ExpectedGot(ComplexValType, ValType),
@@ -38,7 +39,8 @@
}
}
-#[derive(Debug, Clone, Trace, Finalize)]
+#[derive(Debug, Clone, Trace)]
+#[trivially_drop]
pub struct TypeLocError(Box<TypeError>, ValuePathStack);
impl From<TypeError> for TypeLocError {
fn from(e: TypeError) -> Self {
@@ -60,7 +62,8 @@
}
}
-#[derive(Debug, Clone, Trace, Finalize)]
+#[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 {
@@ -123,7 +126,8 @@
}
}
-#[derive(Clone, Debug, Trace, Finalize)]
+#[derive(Clone, Debug, Trace)]
+#[trivially_drop]
enum ValuePathItem {
Field(Rc<str>),
Index(u64),
@@ -138,7 +142,8 @@
}
}
-#[derive(Clone, Debug, Trace, Finalize)]
+#[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
@@ -9,7 +9,7 @@
native::NativeCallback,
throw, with_state, Context, ObjValue, Result,
};
-use gc::{custom_trace, Finalize, Gc, GcCell, Trace};
+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;
@@ -19,25 +19,17 @@
fn get(self: Box<Self>) -> Result<Val>;
}
+#[derive(Trace)]
+#[trivially_drop]
enum LazyValInternals {
Computed(Val),
Errored(LocError),
Waiting(Box<dyn LazyValValue>),
Pending,
-}
-impl Finalize for LazyValInternals {}
-unsafe impl Trace for LazyValInternals {
- custom_trace!(this, {
- match &this {
- LazyValInternals::Computed(v) => mark(v),
- LazyValInternals::Errored(e) => mark(e),
- LazyValInternals::Waiting(w) => mark(w),
- LazyValInternals::Pending => {}
- }
- });
}
-#[derive(Clone, Trace, Finalize)]
+#[derive(Clone, Trace)]
+#[trivially_drop]
pub struct LazyVal(Gc<GcCell<LazyValInternals>>);
impl LazyVal {
pub fn new(f: Box<dyn LazyValValue>) -> Self {
@@ -83,7 +75,8 @@
}
}
-#[derive(Debug, PartialEq, Trace, Finalize)]
+#[derive(Debug, PartialEq, Trace)]
+#[trivially_drop]
pub struct FuncDesc {
pub name: IStr,
pub ctx: Context,
@@ -91,7 +84,8 @@
pub body: LocExpr,
}
-#[derive(Debug, Trace, Finalize)]
+#[derive(Debug, Trace)]
+#[trivially_drop]
pub enum FuncVal {
/// Plain function implemented in jsonnet
Normal(FuncDesc),
@@ -195,22 +189,13 @@
String,
}
-#[derive(Debug, Clone)]
+#[derive(Debug, Clone, Trace)]
+#[trivially_drop]
pub enum ArrValue {
Lazy(Gc<Vec<LazyVal>>),
Eager(Gc<Vec<Val>>),
Extended(Box<(Self, Self)>),
}
-impl Finalize for ArrValue {}
-unsafe impl Trace for ArrValue {
- custom_trace!(this, {
- match &this {
- ArrValue::Lazy(l) => mark(l),
- ArrValue::Eager(e) => mark(e),
- ArrValue::Extended(x) => mark(x),
- }
- });
-}
impl ArrValue {
pub fn new_eager() -> Self {
Self::Eager(Gc::new(Vec::new()))
@@ -419,7 +404,8 @@
}
}
-#[derive(Debug, Clone)]
+#[derive(Debug, Clone, Trace)]
+#[trivially_drop]
pub enum Val {
Bool(bool),
Null,
@@ -429,21 +415,6 @@
Obj(ObjValue),
Func(Gc<FuncVal>),
DebugGcTraceValue(DebugGcTraceValue),
-}
-impl Finalize for Val {}
-unsafe impl Trace for Val {
- custom_trace!(this, {
- match &this {
- Val::Bool(_) => {}
- Val::Null => {}
- Val::Str(_) => {}
- Val::Num(_) => {}
- Val::Arr(a) => mark(a),
- Val::Obj(o) => mark(o),
- Val::Func(f) => mark(f),
- Val::DebugGcTraceValue(v) => mark(v),
- }
- });
}
macro_rules! matches_unwrap {
crates/jrsonnet-interner/Cargo.tomldiffbeforeafterboth--- a/crates/jrsonnet-interner/Cargo.toml
+++ b/crates/jrsonnet-interner/Cargo.toml
@@ -9,4 +9,4 @@
[dependencies]
serde = { version = "1.0" }
rustc-hash = "1.1.0"
-gc = { version = "0.4.1", features = ["derive"] }
+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,4 +1,4 @@
-use gc::{unsafe_empty_trace, Finalize, Trace};
+use jrsonnet_gc::{unsafe_empty_trace, Finalize, Trace};
use rustc_hash::FxHashMap;
use serde::{Deserialize, Serialize};
use std::{
crates/jrsonnet-parser/Cargo.tomldiffbeforeafterboth--- a/crates/jrsonnet-parser/Cargo.toml
+++ b/crates/jrsonnet-parser/Cargo.toml
@@ -18,7 +18,7 @@
unescape = "0.1.0"
serde = { version = "1.0", features = ["derive", "rc"], optional = true }
-gc = { version = "0.4.1", features = ["derive"] }
+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,4 +1,4 @@
-use gc::{unsafe_empty_trace, Finalize, Trace};
+use jrsonnet_gc::{unsafe_empty_trace, Finalize, Trace};
use jrsonnet_interner::IStr;
#[cfg(feature = "deserialize")]
use serde::Deserialize;
@@ -13,21 +13,19 @@
#[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),
/// {["dyn"+"amic"]: 3}
Dyn(LocExpr),
}
-impl Finalize for FieldName {}
-unsafe impl Trace for FieldName {
- unsafe_empty_trace!();
-}
#[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,
@@ -36,10 +34,6 @@
/// :::
Unhide,
}
-impl Finalize for Visibility {}
-unsafe impl Trace for Visibility {
- unsafe_empty_trace!();
-}
impl Visibility {
pub fn is_visible(&self) -> bool {
@@ -49,16 +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>);
-impl Finalize for AssertStmt {}
-unsafe impl Trace for AssertStmt {
- unsafe_empty_trace!();
-}
#[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,
@@ -66,36 +58,26 @@
pub visibility: Visibility,
pub value: LocExpr,
}
-impl Finalize for FieldMember {}
-unsafe impl Trace for FieldMember {
- unsafe_empty_trace!();
-}
#[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),
AssertStmt(AssertStmt),
}
-impl Finalize for Member {}
-unsafe impl Trace for Member {
- unsafe_empty_trace!();
-}
#[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 Finalize for UnaryOpType {}
-unsafe impl Trace for UnaryOpType {
- unsafe_empty_trace!();
}
impl Display for UnaryOpType {
@@ -116,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,
@@ -145,10 +128,6 @@
And,
Or,
}
-impl Finalize for BinaryOpType {}
-unsafe impl Trace for BinaryOpType {
- unsafe_empty_trace!();
-}
impl Display for BinaryOpType {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
@@ -183,22 +162,22 @@
/// 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>);
-impl Finalize for Param {}
-unsafe impl Trace for Param {
- unsafe_empty_trace!();
-}
/// Defined function parameters
#[cfg_attr(feature = "serialize", derive(Serialize))]
#[cfg_attr(feature = "deserialize", derive(Deserialize))]
#[derive(Debug, Clone, PartialEq)]
pub struct ParamsDesc(pub Rc<Vec<Param>>);
-impl Finalize for ParamsDesc {}
+
+/// 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>;
@@ -209,21 +188,15 @@
#[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);
-impl Finalize for Arg {}
-unsafe impl Trace for Arg {
- unsafe_empty_trace!();
-}
#[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 Finalize for ArgsDesc {}
-unsafe impl Trace for ArgsDesc {
- unsafe_empty_trace!();
-}
impl Deref for ArgsDesc {
type Target = Vec<Arg>;
@@ -234,50 +207,39 @@
#[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>,
pub value: LocExpr,
-}
-impl Finalize for BindSpec {}
-unsafe impl Trace for BindSpec {
- unsafe_empty_trace!();
}
#[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);
-impl Finalize for IfSpecData {}
-unsafe impl Trace for IfSpecData {
- unsafe_empty_trace!();
-}
#[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);
-impl Finalize for ForSpecData {}
-unsafe impl Trace for ForSpecData {
- unsafe_empty_trace!();
-}
#[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),
-}
-impl Finalize for CompSpec {}
-unsafe impl Trace for CompSpec {
- unsafe_empty_trace!();
}
#[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,
@@ -285,26 +247,20 @@
pub post_locals: Vec<BindSpec>,
pub compspecs: Vec<CompSpec>,
}
-impl Finalize for ObjComp {}
-unsafe impl Trace for ObjComp {
- unsafe_empty_trace!();
-}
#[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),
-}
-impl Finalize for ObjBody {}
-unsafe impl Trace for ObjBody {
- unsafe_empty_trace!();
}
#[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,
@@ -313,26 +269,20 @@
True,
False,
}
-impl Finalize for LiteralType {}
-unsafe impl Trace for LiteralType {
- unsafe_empty_trace!();
-}
-#[derive(Debug, PartialEq)]
+#[derive(Debug, PartialEq, Trace)]
+#[trivially_drop]
pub struct SliceDesc {
pub start: Option<LocExpr>,
pub end: Option<LocExpr>,
pub step: Option<LocExpr>,
-}
-impl Finalize for SliceDesc {}
-unsafe impl Trace for SliceDesc {
- unsafe_empty_trace!();
}
/// 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),
@@ -396,20 +346,13 @@
cond_else: Option<LocExpr>,
},
}
-impl Finalize for Expr {}
-unsafe impl Trace for Expr {
- unsafe_empty_trace!();
-}
/// 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 Finalize for ExprLocation {}
-unsafe impl Trace for ExprLocation {
- unsafe_empty_trace!();
-}
impl Debug for ExprLocation {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
@@ -422,10 +365,12 @@
#[cfg_attr(feature = "deserialize", derive(Deserialize))]
#[derive(Clone, PartialEq)]
pub struct LocExpr(pub Rc<Expr>, pub Option<ExprLocation>);
-impl Finalize for LocExpr {}
+/// 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 {
crates/jrsonnet-types/Cargo.tomldiffbeforeafterboth--- a/crates/jrsonnet-types/Cargo.toml
+++ b/crates/jrsonnet-types/Cargo.toml
@@ -8,4 +8,4 @@
[dependencies]
peg = "0.7.0"
-gc = { version = "0.4.1", features = ["derive"] }
+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,6 +1,6 @@
#![allow(clippy::redundant_closure_call)]
-use gc::{unsafe_empty_trace, Finalize, Trace};
+use jrsonnet_gc::Trace;
use std::fmt::Display;
#[macro_export]
@@ -78,7 +78,8 @@
);
}
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Trace)]
+#[trivially_drop]
pub enum ValType {
Bool,
Null,
@@ -87,10 +88,6 @@
Arr,
Obj,
Func,
-}
-impl Finalize for ValType {}
-unsafe impl Trace for ValType {
- unsafe_empty_trace!();
}
impl ValType {
@@ -114,7 +111,8 @@
}
}
-#[derive(Debug, Clone, PartialEq)]
+#[derive(Debug, Clone, PartialEq, Trace)]
+#[trivially_drop]
pub enum ComplexValType {
Any,
Char,
@@ -127,10 +125,6 @@
UnionRef(&'static [ComplexValType]),
Sum(Vec<ComplexValType>),
SumRef(&'static [ComplexValType]),
-}
-impl Finalize for ComplexValType {}
-unsafe impl Trace for ComplexValType {
- unsafe_empty_trace!();
}
impl From<ValType> for ComplexValType {