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.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/evaluate.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate.rs
@@ -3,7 +3,7 @@
FuncDesc, FuncVal, FutureWrapper, LazyBinding, LazyVal, LazyValValue, ObjMember, ObjValue,
ObjectAssertion, Result, Val,
};
-use gc::{custom_trace, Finalize, Gc, Trace};
+use jrsonnet_gc::{Gc, Trace};
use jrsonnet_interner::IStr;
use jrsonnet_parser::{
ArgsDesc, AssertStmt, BinaryOpType, BindSpec, CompSpec, Expr, ExprLocation, FieldMember,
@@ -22,21 +22,14 @@
if let Some(params) = &b.params {
let params = params.clone();
+ #[derive(Trace)]
+ #[trivially_drop]
struct LazyMethodBinding {
context_creator: FutureWrapper<Context>,
name: IStr,
params: ParamsDesc,
value: LocExpr,
}
- impl Finalize for LazyMethodBinding {}
- unsafe impl Trace for LazyMethodBinding {
- custom_trace!(this, {
- mark(&this.context_creator);
- mark(&this.name);
- mark(&this.params);
- mark(&this.value);
- });
- }
impl LazyValValue for LazyMethodBinding {
fn get(self: Box<Self>) -> Result<Val> {
Ok(evaluate_method(
@@ -55,19 +48,13 @@
value: b.value.clone(),
}))
} else {
+ #[derive(Trace)]
+ #[trivially_drop]
struct LazyNamedBinding {
context_creator: FutureWrapper<Context>,
name: IStr,
value: LocExpr,
}
- impl Finalize for LazyNamedBinding {}
- unsafe impl Trace for LazyNamedBinding {
- custom_trace!(this, {
- mark(&this.context_creator);
- mark(&this.name);
- mark(&this.value);
- });
- }
impl LazyValValue for LazyNamedBinding {
fn get(self: Box<Self>) -> Result<Val> {
evaluate_named(self.context_creator.unwrap(), &self.value, self.name)
@@ -86,6 +73,8 @@
if let Some(params) = &b.params {
let params = params.clone();
+ #[derive(Trace)]
+ #[trivially_drop]
struct BindableMethodLazyVal {
this: Option<ObjValue>,
super_obj: Option<ObjValue>,
@@ -94,17 +83,6 @@
name: IStr,
params: ParamsDesc,
value: LocExpr,
- }
- impl Finalize for BindableMethodLazyVal {}
- unsafe impl Trace for BindableMethodLazyVal {
- custom_trace!(this, {
- mark(&this.this);
- mark(&this.super_obj);
- mark(&this.context_creator);
- mark(&this.name);
- mark(&this.params);
- mark(&this.value);
- });
}
impl LazyValValue for BindableMethodLazyVal {
fn get(self: Box<Self>) -> Result<Val> {
@@ -117,7 +95,8 @@
}
}
- #[derive(Trace, Finalize)]
+ #[derive(Trace)]
+ #[trivially_drop]
struct BindableMethod {
context_creator: ContextCreator,
name: IStr,
@@ -148,6 +127,8 @@
}))),
)
} else {
+ #[derive(Trace)]
+ #[trivially_drop]
struct BindableNamedLazyVal {
this: Option<ObjValue>,
super_obj: Option<ObjValue>,
@@ -156,16 +137,6 @@
name: IStr,
value: LocExpr,
}
- impl Finalize for BindableNamedLazyVal {}
- unsafe impl Trace for BindableNamedLazyVal {
- custom_trace!(this, {
- mark(&this.this);
- mark(&this.super_obj);
- mark(&this.context_creator);
- mark(&this.name);
- mark(&this.value);
- });
- }
impl LazyValValue for BindableNamedLazyVal {
fn get(self: Box<Self>) -> Result<Val> {
evaluate_named(
@@ -176,7 +147,8 @@
}
}
- #[derive(Trace, Finalize)]
+ #[derive(Trace)]
+ #[trivially_drop]
struct BindableNamed {
context_creator: ContextCreator,
name: IStr,
@@ -414,7 +386,8 @@
}
let name = name.unwrap();
- #[derive(Trace, Finalize)]
+ #[derive(Trace)]
+ #[trivially_drop]
struct ObjMemberBinding {
context_creator: ContextCreator,
value: LocExpr,
@@ -458,7 +431,8 @@
continue;
}
let name = name.unwrap();
- #[derive(Trace, Finalize)]
+ #[derive(Trace)]
+ #[trivially_drop]
struct ObjMemberBinding {
context_creator: ContextCreator,
value: LocExpr,
@@ -496,16 +470,11 @@
}
Member::BindStmt(_) => {}
Member::AssertStmt(stmt) => {
+ #[derive(Trace)]
+ #[trivially_drop]
struct ObjectAssert {
context_creator: ContextCreator,
assert: AssertStmt,
- }
- impl Finalize for ObjectAssert {}
- unsafe impl Trace for ObjectAssert {
- custom_trace!(this, {
- mark(&this.context_creator);
- mark(&this.assert);
- });
}
impl ObjectAssertion for ObjectAssert {
fn run(
@@ -558,7 +527,8 @@
match key {
Val::Null => {}
Val::Str(n) => {
- #[derive(Trace, Finalize)]
+ #[derive(Trace)]
+ #[trivially_drop]
struct ObjCompBinding {
context: Context,
value: LocExpr,
@@ -768,16 +738,11 @@
let mut out = Vec::with_capacity(items.len());
for item in items {
// TODO: Implement ArrValue::Lazy with same context for every element?
+ #[derive(Trace)]
+ #[trivially_drop]
struct ArrayElement {
context: Context,
item: LocExpr,
- }
- impl Finalize for ArrayElement {}
- unsafe impl Trace for ArrayElement {
- custom_trace!(this, {
- mark(&this.context);
- mark(&this.item);
- });
}
impl LazyValValue for ArrayElement {
fn get(self: Box<Self>) -> Result<Val> {
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.rsdiffbeforeafterboth1#![allow(clippy::redundant_closure_call)]23use gc::{unsafe_empty_trace, Finalize, Trace};4use std::fmt::Display;56#[macro_export]7macro_rules! ty {8 ((Array<number>)) => {{9 $crate::ComplexValType::ArrayRef(&$crate::ComplexValType::Simple($crate::ValType::Num))10 }};11 (array) => {12 $crate::ComplexValType::Simple($crate::ValType::Arr)13 };14 (boolean) => {15 $crate::ComplexValType::Simple($crate::ValType::Bool)16 };17 (null) => {18 $crate::ComplexValType::Simple($crate::ValType::Null)19 };20 (string) => {21 $crate::ComplexValType::Simple($crate::ValType::Str)22 };23 (char) => {24 $crate::ComplexValType::Char25 };26 (number) => {27 $crate::ComplexValType::Simple($crate::ValType::Num)28 };29 (BoundedNumber<($min:expr), ($max:expr)>) => {{30 $crate::ComplexValType::BoundedNumber($min, $max)31 }};32 (object) => {33 $crate::ComplexValType::Simple($crate::ValType::Obj)34 };35 (any) => {36 $crate::ComplexValType::Any37 };38 (function) => {39 $crate::ComplexValType::Simple($crate::ValType::Func)40 };41 (($($a:tt) |+)) => {{42 static CONTENTS: &'static [$crate::ComplexValType] = &[43 $(ty!($a)),+44 ];45 $crate::ComplexValType::UnionRef(CONTENTS)46 }};47 (($($a:tt) &+)) => {{48 static CONTENTS: &'static [$crate::ComplexValType] = &[49 $(ty!($a)),+50 ];51 $crate::ComplexValType::SumRef(CONTENTS)52 }};53}5455#[test]56fn test() {57 assert_eq!(58 ty!((Array<number>)),59 ComplexValType::ArrayRef(&ComplexValType::Simple(ValType::Num))60 );61 assert_eq!(ty!(array), ComplexValType::Simple(ValType::Arr));62 assert_eq!(ty!(any), ComplexValType::Any);63 assert_eq!(64 ty!((string | number)),65 ComplexValType::UnionRef(&[66 ComplexValType::Simple(ValType::Str),67 ComplexValType::Simple(ValType::Num)68 ])69 );70 assert_eq!(71 format!("{}", ty!(((string & number) | (object & null)))),72 "string & number | object & null"73 );74 assert_eq!(format!("{}", ty!((string | array))), "string | array");75 assert_eq!(76 format!("{}", ty!(((string & number) | array))),77 "string & number | array"78 );79}8081#[derive(Debug, Clone, Copy, PartialEq, Eq)]82pub enum ValType {83 Bool,84 Null,85 Str,86 Num,87 Arr,88 Obj,89 Func,90}91impl Finalize for ValType {}92unsafe impl Trace for ValType {93 unsafe_empty_trace!();94}9596impl ValType {97 pub const fn name(&self) -> &'static str {98 use ValType::*;99 match self {100 Bool => "boolean",101 Null => "null",102 Str => "string",103 Num => "number",104 Arr => "array",105 Obj => "object",106 Func => "function",107 }108 }109}110111impl Display for ValType {112 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {113 write!(f, "{}", self.name())114 }115}116117#[derive(Debug, Clone, PartialEq)]118pub enum ComplexValType {119 Any,120 Char,121 Simple(ValType),122 BoundedNumber(Option<f64>, Option<f64>),123 Array(Box<ComplexValType>),124 ArrayRef(&'static ComplexValType),125 ObjectRef(&'static [(&'static str, ComplexValType)]),126 Union(Vec<ComplexValType>),127 UnionRef(&'static [ComplexValType]),128 Sum(Vec<ComplexValType>),129 SumRef(&'static [ComplexValType]),130}131impl Finalize for ComplexValType {}132unsafe impl Trace for ComplexValType {133 unsafe_empty_trace!();134}135136impl From<ValType> for ComplexValType {137 fn from(s: ValType) -> Self {138 Self::Simple(s)139 }140}141142fn write_union(143 f: &mut std::fmt::Formatter<'_>,144 is_union: bool,145 union: &[ComplexValType],146) -> std::fmt::Result {147 for (i, v) in union.iter().enumerate() {148 let should_add_braces =149 matches!(v, ComplexValType::UnionRef(_) | ComplexValType::Union(_) if !is_union);150 if i != 0 {151 write!(f, " {} ", if is_union { '|' } else { '&' })?;152 }153 if should_add_braces {154 write!(f, "(")?;155 }156 write!(f, "{}", v)?;157 if should_add_braces {158 write!(f, ")")?;159 }160 }161 Ok(())162}163164fn print_array(a: &ComplexValType, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {165 if *a == ComplexValType::Any {166 write!(f, "array")?167 } else {168 write!(f, "Array<{}>", a)?169 }170 Ok(())171}172173impl Display for ComplexValType {174 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {175 match self {176 ComplexValType::Any => write!(f, "any")?,177 ComplexValType::Simple(s) => write!(f, "{}", s)?,178 ComplexValType::Char => write!(f, "char")?,179 ComplexValType::BoundedNumber(a, b) => write!(180 f,181 "BoundedNumber<{}, {}>",182 a.map(|e| e.to_string()).unwrap_or_else(|| "".into()),183 b.map(|e| e.to_string()).unwrap_or_else(|| "".into())184 )?,185 ComplexValType::ArrayRef(a) => print_array(a, f)?,186 ComplexValType::Array(a) => print_array(a, f)?,187 ComplexValType::ObjectRef(fields) => {188 write!(f, "{{")?;189 for (i, (k, v)) in fields.iter().enumerate() {190 if i != 0 {191 write!(f, ", ")?;192 }193 write!(f, "{}: {}", k, v)?;194 }195 write!(f, "}}")?;196 }197 ComplexValType::Union(v) => write_union(f, true, v)?,198 ComplexValType::UnionRef(v) => write_union(f, true, v)?,199 ComplexValType::Sum(v) => write_union(f, false, v)?,200 ComplexValType::SumRef(v) => write_union(f, false, v)?,201 };202 Ok(())203 }204}205206peg::parser! {207pub grammar parser() for str {208 rule number() -> f64209 = n:$(['0'..='9']+) { n.parse().unwrap() }210211 rule any_ty() -> ComplexValType = "any" { ComplexValType::Any }212 rule char_ty() -> ComplexValType = "character" { ComplexValType::Char }213 rule bool_ty() -> ComplexValType = "boolean" { ComplexValType::Simple(ValType::Bool) }214 rule null_ty() -> ComplexValType = "null" { ComplexValType::Simple(ValType::Null) }215 rule str_ty() -> ComplexValType = "string" { ComplexValType::Simple(ValType::Str) }216 rule num_ty() -> ComplexValType = "number" { ComplexValType::Simple(ValType::Num) }217 rule simple_array_ty() -> ComplexValType = "array" { ComplexValType::Simple(ValType::Arr) }218 rule simple_object_ty() -> ComplexValType = "object" { ComplexValType::Simple(ValType::Obj) }219 rule simple_function_ty() -> ComplexValType = "function" { ComplexValType::Simple(ValType::Func) }220221 rule array_ty() -> ComplexValType222 = "Array<" t:ty() ">" { ComplexValType::Array(Box::new(t)) }223224 rule bounded_number_ty() -> ComplexValType225 = "BoundedNumber<" a:number() ", " b:number() ">" { ComplexValType::BoundedNumber(Some(a), Some(b)) }226227 rule ty_basic() -> ComplexValType228 = any_ty()229 / char_ty()230 / bool_ty()231 / null_ty()232 / str_ty()233 / num_ty()234 / simple_array_ty()235 / simple_object_ty()236 / simple_function_ty()237 / array_ty()238 / bounded_number_ty()239240 pub rule ty() -> ComplexValType241 = precedence! {242 a:(@) " | " b:@ {243 match a {244 ComplexValType::Union(mut a) => {245 a.push(b);246 ComplexValType::Union(a)247 }248 _ => ComplexValType::Union(vec![a, b]),249 }250 }251 --252 a:(@) " & " b:@ {253 match a {254 ComplexValType::Sum(mut a) => {255 a.push(b);256 ComplexValType::Sum(a)257 }258 _ => ComplexValType::Sum(vec![a, b]),259 }260 }261 --262 "(" t:ty() ")" { t }263 t:ty_basic() { t }264 }265}266}267268#[cfg(test)]269pub mod tests {270 use super::parser;271272 #[test]273 fn precedence() {274 assert_eq!(275 parser::ty("(any & any) | (any | any) & any")276 .unwrap()277 .to_string(),278 "any & any | (any | any) & any"279 );280 }281282 #[test]283 fn array() {284 assert_eq!(parser::ty("Array<any>").unwrap().to_string(), "array");285 assert_eq!(286 parser::ty("Array<number>").unwrap().to_string(),287 "Array<number>"288 );289 }290 #[test]291 fn bounded_number() {292 assert_eq!(293 parser::ty("BoundedNumber<1, 2>").unwrap().to_string(),294 "BoundedNumber<1, 2>"295 );296 }297}1#![allow(clippy::redundant_closure_call)]23use jrsonnet_gc::Trace;4use std::fmt::Display;56#[macro_export]7macro_rules! ty {8 ((Array<number>)) => {{9 $crate::ComplexValType::ArrayRef(&$crate::ComplexValType::Simple($crate::ValType::Num))10 }};11 (array) => {12 $crate::ComplexValType::Simple($crate::ValType::Arr)13 };14 (boolean) => {15 $crate::ComplexValType::Simple($crate::ValType::Bool)16 };17 (null) => {18 $crate::ComplexValType::Simple($crate::ValType::Null)19 };20 (string) => {21 $crate::ComplexValType::Simple($crate::ValType::Str)22 };23 (char) => {24 $crate::ComplexValType::Char25 };26 (number) => {27 $crate::ComplexValType::Simple($crate::ValType::Num)28 };29 (BoundedNumber<($min:expr), ($max:expr)>) => {{30 $crate::ComplexValType::BoundedNumber($min, $max)31 }};32 (object) => {33 $crate::ComplexValType::Simple($crate::ValType::Obj)34 };35 (any) => {36 $crate::ComplexValType::Any37 };38 (function) => {39 $crate::ComplexValType::Simple($crate::ValType::Func)40 };41 (($($a:tt) |+)) => {{42 static CONTENTS: &'static [$crate::ComplexValType] = &[43 $(ty!($a)),+44 ];45 $crate::ComplexValType::UnionRef(CONTENTS)46 }};47 (($($a:tt) &+)) => {{48 static CONTENTS: &'static [$crate::ComplexValType] = &[49 $(ty!($a)),+50 ];51 $crate::ComplexValType::SumRef(CONTENTS)52 }};53}5455#[test]56fn test() {57 assert_eq!(58 ty!((Array<number>)),59 ComplexValType::ArrayRef(&ComplexValType::Simple(ValType::Num))60 );61 assert_eq!(ty!(array), ComplexValType::Simple(ValType::Arr));62 assert_eq!(ty!(any), ComplexValType::Any);63 assert_eq!(64 ty!((string | number)),65 ComplexValType::UnionRef(&[66 ComplexValType::Simple(ValType::Str),67 ComplexValType::Simple(ValType::Num)68 ])69 );70 assert_eq!(71 format!("{}", ty!(((string & number) | (object & null)))),72 "string & number | object & null"73 );74 assert_eq!(format!("{}", ty!((string | array))), "string | array");75 assert_eq!(76 format!("{}", ty!(((string & number) | array))),77 "string & number | array"78 );79}8081#[derive(Debug, Clone, Copy, PartialEq, Eq, Trace)]82#[trivially_drop]83pub enum ValType {84 Bool,85 Null,86 Str,87 Num,88 Arr,89 Obj,90 Func,91}9293impl ValType {94 pub const fn name(&self) -> &'static str {95 use ValType::*;96 match self {97 Bool => "boolean",98 Null => "null",99 Str => "string",100 Num => "number",101 Arr => "array",102 Obj => "object",103 Func => "function",104 }105 }106}107108impl Display for ValType {109 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {110 write!(f, "{}", self.name())111 }112}113114#[derive(Debug, Clone, PartialEq, Trace)]115#[trivially_drop]116pub enum ComplexValType {117 Any,118 Char,119 Simple(ValType),120 BoundedNumber(Option<f64>, Option<f64>),121 Array(Box<ComplexValType>),122 ArrayRef(&'static ComplexValType),123 ObjectRef(&'static [(&'static str, ComplexValType)]),124 Union(Vec<ComplexValType>),125 UnionRef(&'static [ComplexValType]),126 Sum(Vec<ComplexValType>),127 SumRef(&'static [ComplexValType]),128}129130impl From<ValType> for ComplexValType {131 fn from(s: ValType) -> Self {132 Self::Simple(s)133 }134}135136fn write_union(137 f: &mut std::fmt::Formatter<'_>,138 is_union: bool,139 union: &[ComplexValType],140) -> std::fmt::Result {141 for (i, v) in union.iter().enumerate() {142 let should_add_braces =143 matches!(v, ComplexValType::UnionRef(_) | ComplexValType::Union(_) if !is_union);144 if i != 0 {145 write!(f, " {} ", if is_union { '|' } else { '&' })?;146 }147 if should_add_braces {148 write!(f, "(")?;149 }150 write!(f, "{}", v)?;151 if should_add_braces {152 write!(f, ")")?;153 }154 }155 Ok(())156}157158fn print_array(a: &ComplexValType, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {159 if *a == ComplexValType::Any {160 write!(f, "array")?161 } else {162 write!(f, "Array<{}>", a)?163 }164 Ok(())165}166167impl Display for ComplexValType {168 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {169 match self {170 ComplexValType::Any => write!(f, "any")?,171 ComplexValType::Simple(s) => write!(f, "{}", s)?,172 ComplexValType::Char => write!(f, "char")?,173 ComplexValType::BoundedNumber(a, b) => write!(174 f,175 "BoundedNumber<{}, {}>",176 a.map(|e| e.to_string()).unwrap_or_else(|| "".into()),177 b.map(|e| e.to_string()).unwrap_or_else(|| "".into())178 )?,179 ComplexValType::ArrayRef(a) => print_array(a, f)?,180 ComplexValType::Array(a) => print_array(a, f)?,181 ComplexValType::ObjectRef(fields) => {182 write!(f, "{{")?;183 for (i, (k, v)) in fields.iter().enumerate() {184 if i != 0 {185 write!(f, ", ")?;186 }187 write!(f, "{}: {}", k, v)?;188 }189 write!(f, "}}")?;190 }191 ComplexValType::Union(v) => write_union(f, true, v)?,192 ComplexValType::UnionRef(v) => write_union(f, true, v)?,193 ComplexValType::Sum(v) => write_union(f, false, v)?,194 ComplexValType::SumRef(v) => write_union(f, false, v)?,195 };196 Ok(())197 }198}199200peg::parser! {201pub grammar parser() for str {202 rule number() -> f64203 = n:$(['0'..='9']+) { n.parse().unwrap() }204205 rule any_ty() -> ComplexValType = "any" { ComplexValType::Any }206 rule char_ty() -> ComplexValType = "character" { ComplexValType::Char }207 rule bool_ty() -> ComplexValType = "boolean" { ComplexValType::Simple(ValType::Bool) }208 rule null_ty() -> ComplexValType = "null" { ComplexValType::Simple(ValType::Null) }209 rule str_ty() -> ComplexValType = "string" { ComplexValType::Simple(ValType::Str) }210 rule num_ty() -> ComplexValType = "number" { ComplexValType::Simple(ValType::Num) }211 rule simple_array_ty() -> ComplexValType = "array" { ComplexValType::Simple(ValType::Arr) }212 rule simple_object_ty() -> ComplexValType = "object" { ComplexValType::Simple(ValType::Obj) }213 rule simple_function_ty() -> ComplexValType = "function" { ComplexValType::Simple(ValType::Func) }214215 rule array_ty() -> ComplexValType216 = "Array<" t:ty() ">" { ComplexValType::Array(Box::new(t)) }217218 rule bounded_number_ty() -> ComplexValType219 = "BoundedNumber<" a:number() ", " b:number() ">" { ComplexValType::BoundedNumber(Some(a), Some(b)) }220221 rule ty_basic() -> ComplexValType222 = any_ty()223 / char_ty()224 / bool_ty()225 / null_ty()226 / str_ty()227 / num_ty()228 / simple_array_ty()229 / simple_object_ty()230 / simple_function_ty()231 / array_ty()232 / bounded_number_ty()233234 pub rule ty() -> ComplexValType235 = precedence! {236 a:(@) " | " b:@ {237 match a {238 ComplexValType::Union(mut a) => {239 a.push(b);240 ComplexValType::Union(a)241 }242 _ => ComplexValType::Union(vec![a, b]),243 }244 }245 --246 a:(@) " & " b:@ {247 match a {248 ComplexValType::Sum(mut a) => {249 a.push(b);250 ComplexValType::Sum(a)251 }252 _ => ComplexValType::Sum(vec![a, b]),253 }254 }255 --256 "(" t:ty() ")" { t }257 t:ty_basic() { t }258 }259}260}261262#[cfg(test)]263pub mod tests {264 use super::parser;265266 #[test]267 fn precedence() {268 assert_eq!(269 parser::ty("(any & any) | (any | any) & any")270 .unwrap()271 .to_string(),272 "any & any | (any | any) & any"273 );274 }275276 #[test]277 fn array() {278 assert_eq!(parser::ty("Array<any>").unwrap().to_string(), "array");279 assert_eq!(280 parser::ty("Array<number>").unwrap().to_string(),281 "Array<number>"282 );283 }284 #[test]285 fn bounded_number() {286 assert_eq!(287 parser::ty("BoundedNumber<1, 2>").unwrap().to_string(),288 "BoundedNumber<1, 2>"289 );290 }291}