difftreelog
refactor unified ContextBuilder
in: master
17 files changed
Cargo.lockdiffbeforeafterboth--- a/Cargo.lock
+++ b/Cargo.lock
@@ -699,6 +699,7 @@
"bitmaps",
"rand_core 0.6.4",
"rand_xoshiro",
+ "refpool",
"sized-chunks",
"typenum",
"version_check",
@@ -861,9 +862,9 @@
[[package]]
name = "jrsonnet-gcmodule"
-version = "0.4.3"
+version = "0.4.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "8a6a63a6e55ba82764e483d7f8a181f25db95a8f25da8ae6520e95a5fe39c6a6"
+checksum = "21dd97b40cbfb2043094219f95d96519858ba1aee4e8260eb048a1774832a517"
dependencies = [
"im-rc",
"jrsonnet-gcmodule-derive",
@@ -871,9 +872,9 @@
[[package]]
name = "jrsonnet-gcmodule-derive"
-version = "0.4.3"
+version = "0.4.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "095fe3c4c0acf32de80205a8a479ef63c216b9efb0024dec9eb7fe1c5ef1f1a1"
+checksum = "ede3d0445c2a7d7adab0a3cc33bdb33df78ffebebc21a2848c221526cb1795d4"
dependencies = [
"proc-macro2",
"quote",
@@ -1420,6 +1421,12 @@
]
[[package]]
+name = "refpool"
+version = "0.4.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "369e86b80fa7dc8c561dd9613a5bf25c59d2d3073cd66c47fd9e39802f0ecb58"
+
+[[package]]
name = "regex"
version = "1.12.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -1633,6 +1640,7 @@
checksum = "16d69225bde7a69b235da73377861095455d298f2b970996eec25ddbb42b3d1e"
dependencies = [
"bitmaps",
+ "refpool",
"typenum",
]
@@ -1738,6 +1746,7 @@
"jrsonnet-evaluator",
"jrsonnet-gcmodule",
"jrsonnet-stdlib",
+ "mimallocator",
"serde",
"serde_json",
]
Cargo.tomldiffbeforeafterboth--- a/Cargo.toml
+++ b/Cargo.toml
@@ -22,7 +22,7 @@
jrsonnet-cli = { path = "./crates/jrsonnet-cli", version = "0.5.0-pre98" }
jrsonnet-types = { path = "./crates/jrsonnet-types", version = "0.5.0-pre98" }
jrsonnet-formatter = { path = "./crates/jrsonnet-formatter", version = "0.5.0-pre98" }
-jrsonnet-gcmodule = { version = "0.4.3", features = ["im-rc"] }
+jrsonnet-gcmodule = { version = "0.4.4", features = ["im-rc"] }
# Diagnostics.
# hi-doc is my library, which handles text formatting very well, but isn't polished enough yet
# Previous implementation was based on annotate-snippets, which I don't like for many reasons.
cmds/jrsonnet/src/main.rsdiffbeforeafterboth--- a/cmds/jrsonnet/src/main.rs
+++ b/cmds/jrsonnet/src/main.rs
@@ -200,7 +200,7 @@
val = s.evaluate_snippet_with(
"<exp_apply>".to_owned(),
&apply,
- InitialUnderscore(Thunk::evaluated(val)),
+ &InitialUnderscore(Thunk::evaluated(val)),
)?;
}
crates/jrsonnet-evaluator/Cargo.tomldiffbeforeafterboth--- a/crates/jrsonnet-evaluator/Cargo.toml
+++ b/crates/jrsonnet-evaluator/Cargo.toml
@@ -76,7 +76,7 @@
"Hash",
"PartialEq",
] }
-im-rc = "15.1.0"
+im-rc = { version = "15.1.0", features = ["pool"] }
[build-dependencies]
rustversion = "1.0.22"
crates/jrsonnet-evaluator/src/ctx.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/ctx.rs
+++ b/crates/jrsonnet-evaluator/src/ctx.rs
@@ -3,11 +3,11 @@
use educe::Educe;
use jrsonnet_gcmodule::{Cc, Trace};
use jrsonnet_interner::IStr;
-use rustc_hash::FxHashMap;
+use rustc_hash::{FxHashMap, FxHashSet};
use crate::{
- ObjValue, Pending, Result, SupThis, Thunk, Val, error::ErrorKind::*, gc::WithCapacityExt as _,
- map::LayeredHashMap,
+ ObjValue, Pending, Result, SupThis, Thunk, Val, bail, error::ErrorKind::*,
+ gc::WithCapacityExt as _,
};
/// Context keeps information about current lexical code location
///
@@ -20,7 +20,9 @@
struct ContextInternal {
dollar: Option<ObjValue>,
sup_this: Option<SupThis>,
- bindings: LayeredHashMap,
+ bindings: FxHashMap<IStr, Thunk<Val>>,
+
+ branch_point: Option<Context>,
}
impl Context {
pub fn new_future() -> Pending<Self> {
@@ -71,14 +73,18 @@
return Ok(val);
}
+ if let Some(branch_point) = &self.0.branch_point {
+ return branch_point.binding(name);
+ }
+
let mut heap = Vec::new();
- self.0.bindings.clone().iter_keys(|k| {
- let conf = strsim::jaro_winkler(&k as &str, &name as &str);
+ for k in self.0.bindings.keys() {
+ let conf = strsim::jaro_winkler(k as &str, &name as &str);
if conf < 0.8 {
- return;
+ continue;
}
- heap.push((conf, k));
- });
+ heap.push((conf, k.clone()));
+ }
heap.sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap_or(Ordering::Equal));
bail!(VariableIsNotDefined(
@@ -98,103 +104,91 @@
}
#[must_use]
- pub fn with_var(self, name: impl Into<IStr>, value: Val) -> Self {
- let mut new_bindings = FxHashMap::with_capacity(1);
- new_bindings.insert(name.into(), Thunk::evaluated(value));
- self.extend_bindings(new_bindings)
- }
-
- #[must_use]
- pub fn extend_bindings_sup_this(
- self,
- new_bindings: FxHashMap<IStr, Thunk<Val>>,
- sup_this: SupThis,
- ) -> Self {
- let ctx = &self;
- let dollar = ctx
- .0
- .dollar
- .clone()
- .or_else(|| Some(sup_this.this().clone()));
- let bindings = if new_bindings.is_empty() {
- ctx.0.bindings.clone()
+ pub fn branch_point(self) -> Self {
+ if self.0.bindings.is_empty() {
+ self
} else {
- ctx.0.bindings.clone().extend(new_bindings)
- };
- Self(Cc::new(ContextInternal {
- dollar,
- sup_this: Some(sup_this),
- bindings,
- }))
- }
- #[must_use]
- pub fn extend_bindings(self, new_bindings: FxHashMap<IStr, Thunk<Val>>) -> Self {
- if new_bindings.is_empty() {
- return self;
+ ContextBuilder::extend(self).build()
}
- let ctx = &self;
- let bindings = if new_bindings.is_empty() {
- ctx.0.bindings.clone()
- } else {
- ctx.0.bindings.clone().extend(new_bindings)
- };
- Self(Cc::new(ContextInternal {
- dollar: ctx.0.dollar.clone(),
- sup_this: ctx.0.sup_this.clone(),
- bindings,
- }))
}
}
-#[derive(Default)]
+#[derive(Clone)]
pub struct ContextBuilder {
+ dollar: Option<ObjValue>,
+ sup_this: Option<SupThis>,
bindings: FxHashMap<IStr, Thunk<Val>>,
- extend: Option<Context>,
+ filled: FxHashSet<IStr>,
+ branch_point: Option<Context>,
}
impl ContextBuilder {
pub fn new() -> Self {
- Self::with_capacity(0)
+ Self {
+ dollar: None,
+ sup_this: None,
+ bindings: FxHashMap::new(),
+ filled: FxHashSet::new(),
+ branch_point: None,
+ }
}
- pub fn with_capacity(capacity: usize) -> Self {
+ pub fn extend_fast(parent: Context) -> Self {
Self {
- bindings: FxHashMap::with_capacity(capacity),
- extend: None,
+ dollar: parent.0.dollar.clone(),
+ sup_this: parent.0.sup_this.clone(),
+ bindings: parent.0.bindings.clone(),
+ filled: FxHashSet::new(),
+ branch_point: parent.0.branch_point.clone(),
}
}
pub fn extend(parent: Context) -> Self {
Self {
+ dollar: parent.0.dollar.clone(),
+ sup_this: parent.0.sup_this.clone(),
bindings: FxHashMap::new(),
- extend: Some(parent),
+ filled: FxHashSet::new(),
+ branch_point: Some(parent.clone()),
}
}
- /// # Panics
- ///
- /// If `name` is already bound. Makes no sense to bind same local multiple times,
- /// unless it is separate context layers.
- pub fn bind(&mut self, name: impl Into<IStr>, value: Thunk<Val>) -> &mut Self {
- let old = self.bindings.insert(name.into(), value);
- assert!(old.is_none(), "variable bound twice in single context call");
+ pub fn bind(&mut self, name: impl Into<IStr>, value: Thunk<Val>) {
+ let _ = self.bindings.insert(name.into(), value);
+ }
+ /// After commit, binds would shadow the previous declarations
+ #[must_use]
+ pub fn commit(mut self) -> Self {
+ self.filled.clear();
self
}
- pub fn binds(&mut self, bindings: FxHashMap<IStr, Thunk<Val>>) -> &mut Self {
- for (k, v) in bindings {
- self.bind(k, v);
+ pub fn try_bind(&mut self, name: impl Into<IStr>, value: Thunk<Val>) -> Result<()> {
+ let name = name.into();
+ if !self.filled.insert(name.clone()) {
+ bail!(DuplicateLocalVar(name))
}
- self
+ self.bind(name, value);
+ Ok(())
}
pub fn build(self) -> Context {
- if let Some(parent) = self.extend {
- parent.extend_bindings(self.bindings)
- } else {
- Context(Cc::new(ContextInternal {
- bindings: LayeredHashMap::new(self.bindings),
- dollar: None,
- sup_this: None,
- }))
+ Context(Cc::new(ContextInternal {
+ dollar: self.dollar,
+ sup_this: self.sup_this,
+ bindings: self.bindings,
+ branch_point: self.branch_point,
+ }))
+ }
+ pub fn build_sup_this(mut self, st: SupThis) -> Context {
+ if self.dollar.is_none() {
+ self.dollar = Some(st.this().clone());
}
+ self.sup_this = Some(st);
+ self.build()
+ }
+}
+
+impl Default for ContextBuilder {
+ fn default() -> Self {
+ Self::new()
}
}
crates/jrsonnet-evaluator/src/error.rsdiffbeforeafterboth1use std::{cmp::Ordering, convert::Infallible, fmt};23use jrsonnet_gcmodule::{Acyclic, Trace};4use jrsonnet_interner::IStr;5use jrsonnet_ir::{BinaryOpType, Source, SourcePath, Span, Spanned, UnaryOpType};6use jrsonnet_types::ValType;7use thiserror::Error;89use crate::{10 ObjValue, ResolvePathOwned,11 function::{CallLocation, FunctionSignature, ParamName},12 stdlib::format::FormatError,13 typed::TypeLocError,14 val::ConvertNumValueError,15};1617#[derive(Debug, Clone)]18pub struct SyntaxError {19 pub message: String,20 pub location: (u32, u32),21}22impl fmt::Display for SyntaxError {23 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {24 write!(f, "{}", self.message)25 }26}2728pub(crate) fn format_found(list: &[IStr], what: &str) -> String {29 if list.is_empty() {30 return String::new();31 }32 let mut out = String::new();33 out.push_str("\nThere ");34 if list.len() > 1 {35 out.push_str("are ");36 } else {37 out.push_str("is a ");38 }39 out.push_str(what);40 if list.len() > 1 {41 out.push('s');42 }43 out.push_str(" with similar name");44 if list.len() > 1 {45 out.push('s');46 }47 out.push_str(" present: ");48 for (i, v) in list.iter().enumerate() {49 if i != 0 {50 out.push_str(", ");51 }52 out.push_str(v as &str);53 }54 out55}5657const fn format_empty_str(str: &str) -> &str {58 if str.is_empty() {59 "\"\" (empty string)"60 } else {61 str62 }63}6465pub(crate) fn suggest_object_fields(v: &ObjValue, key: IStr) -> Vec<IStr> {66 let mut heap = Vec::new();67 for field in v.fields_ex(68 true,69 #[cfg(feature = "exp-preserve-order")]70 false,71 ) {72 let conf = strsim::jaro_winkler(field.as_str(), key.as_str());73 if conf < 0.8 {74 continue;75 }76 assert!(77 field.as_str() != key.as_str(),78 "looks like string pooling failure, please write any info regarding this crash to https://github.com/CertainLach/jrsonnet/issues/113, thanks!"79 );8081 heap.push((conf, field));82 }83 heap.sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap_or(Ordering::Equal));84 heap.into_iter().map(|v| v.1).collect()85}8687/// Possible errors88#[allow(missing_docs)]89#[derive(Error, Debug, Clone, Trace)]90#[non_exhaustive]91pub enum ErrorKind {92 #[error("intrinsic not found: {0}")]93 IntrinsicNotFound(IStr),9495 #[error("operator {0} does not operate on type {1}")]96 UnaryOperatorDoesNotOperateOnType(UnaryOpType, ValType),97 #[error("binary operation {1} {0} {2} is not implemented")]98 BinaryOperatorDoesNotOperateOnValues(BinaryOpType, ValType, ValType),99100 #[error("self/super/$ are only usable inside objects")]101 CantUseSelfSupOutsideOfObject,102 #[error("no super found")]103 NoSuperFound,104105 #[error("for loop can only iterate over arrays")]106 InComprehensionCanOnlyIterateOverArray,107108 #[error("array out of bounds: {0} is not within [0,{1})")]109 ArrayBoundsError(isize, usize),110 #[error("string out of bounds: {0} is not within [0,{1})")]111 StringBoundsError(usize, usize),112113 #[error("assert failed: {}", format_empty_str(.0))]114 AssertionFailed(IStr),115116 #[error("local is not defined: {0}{found}", found = format_found(.1, "local"))]117 VariableIsNotDefined(IStr, Vec<IStr>),118 #[error("duplicate local var: {0}")]119 DuplicateLocalVar(IStr),120121 #[error("type mismatch: expected {expected}, got {2} {0}", expected = .1.iter().map(|e| format!("{e}")).collect::<Vec<_>>().join(", "))]122 TypeMismatch(&'static str, Vec<ValType>, ValType),123 #[error("no such field: {}{}", format_empty_str(.0), format_found(.1, "field"))]124 NoSuchField(IStr, Vec<IStr>),125126 #[error("only functions can be called, got {0}")]127 OnlyFunctionsCanBeCalledGot(ValType),128 #[error("parameter {0} is not defined")]129 UnknownFunctionParameter(IStr),130 #[error("argument {0} is already bound")]131 BindingParameterASecondTime(IStr),132 #[error("too many args, function has {0}\nFunction has the following signature: {1}")]133 TooManyArgsFunctionHas(usize, FunctionSignature),134 #[error("function argument is not passed: {0}\nFunction has the following signature: {1}")]135 FunctionParameterNotBoundInCall(ParamName, FunctionSignature),136137 #[error("external variable is not defined: {0}")]138 UndefinedExternalVariable(IStr),139140 #[error("field name should be string, got {0}")]141 FieldMustBeStringGot(ValType),142 #[error("duplicate field name: {}", format_empty_str(.0))]143 DuplicateFieldName(IStr),144145 #[error("attempted to index array with string {}", format_empty_str(.0))]146 AttemptedIndexAnArrayWithString(IStr),147 #[error("{0} index type should be {1}, got {2}")]148 ValueIndexMustBeTypeGot(ValType, ValType, ValType),149 #[error("cant index into {0}")]150 CantIndexInto(ValType),151 #[error("{0} is not indexable")]152 ValueIsNotIndexable(ValType),153154 #[error("super can't be used standalone")]155 StandaloneSuper,156157 #[error("can't resolve {1} from {0}")]158 ImportFileNotFound(SourcePath, ResolvePathOwned),159 #[error("resolved file not found: {:?}", .0)]160 ResolvedFileNotFound(SourcePath),161 #[error("can't import {0}: is a directory")]162 ImportIsADirectory(SourcePath),163 #[error("imported file is not valid utf-8: {0:?}")]164 ImportBadFileUtf8(SourcePath),165 #[error("import io error: {0}")]166 ImportIo(String),167 #[error("tried to import {1} from {0}, but imports are not supported")]168 ImportNotSupported(SourcePath, ResolvePathOwned),169 #[error("can't import from virtual file")]170 CantImportFromVirtualFile,171 #[error("syntax error: {error}")]172 ImportSyntaxError {173 path: Source,174 #[trace(skip)]175 error: Box<SyntaxError>,176 },177178 #[error("runtime error: {}", format_empty_str(.0))]179 RuntimeError(IStr),180 #[error("stack overflow, try to reduce recursion, or set --max-stack to bigger value")]181 StackOverflow,182 #[error("infinite recursion detected")]183 InfiniteRecursionDetected,184 #[error("tried to index by fractional value")]185 FractionalIndex,186 #[error("attempted to divide by zero")]187 DivisionByZero,188189 #[error("string manifest output is not an string")]190 StringManifestOutputIsNotAString,191 #[error("stream manifest output is not an array")]192 StreamManifestOutputIsNotAArray,193 #[error("multi manifest output is not an object")]194 MultiManifestOutputIsNotAObject,195196 #[error("cant recurse stream manifest")]197 StreamManifestOutputCannotBeRecursed,198 #[error("stream manifest output cannot consist of raw strings")]199 StreamManifestCannotNestString,200201 #[error("{}", format_empty_str(.0))]202 ImportCallbackError(String),203 #[error("invalid unicode codepoint: {0}")]204 InvalidUnicodeCodepointGot(u32),205206 #[error("convert num value: {0}")]207 ConvertNumValue(#[from] ConvertNumValueError),208209 #[error("format error: {0}")]210 Format(#[from] FormatError),211 #[error("type error: {0}")]212 TypeError(TypeLocError),213214 #[cfg(feature = "anyhow-error")]215 #[error(transparent)]216 Other(#[trace(skip)] std::rc::Rc<anyhow::Error>),217}218219#[cfg(feature = "anyhow-error")]220impl From<anyhow::Error> for Error {221 fn from(e: anyhow::Error) -> Self {222 Self::new(ErrorKind::Other(std::rc::Rc::new(e)))223 }224}225226impl From<ErrorKind> for Error {227 fn from(e: ErrorKind) -> Self {228 Self::new(e)229 }230}231232impl From<Infallible> for Error {233 fn from(_value: Infallible) -> Self {234 unreachable!()235 }236}237238/// Single stack trace frame239#[derive(Clone, Debug, Trace)]240pub struct StackTraceElement {241 /// Source of this frame242 /// Some frames only act as description, without attached source243 pub location: Option<Span>,244 /// Frame description245 pub desc: String,246}247#[derive(Debug, Clone, Trace)]248pub struct StackTrace(pub Vec<StackTraceElement>);249250#[derive(Clone, Trace)]251pub struct Error(Box<(ErrorKind, StackTrace)>);252impl Error {253 pub fn new(e: ErrorKind) -> Self {254 Self(Box::new((e, StackTrace(vec![]))))255 }256257 pub const fn error(&self) -> &ErrorKind {258 &(self.0).0259 }260 pub fn error_mut(&mut self) -> &mut ErrorKind {261 &mut (self.0).0262 }263 pub const fn trace(&self) -> &StackTrace {264 &(self.0).1265 }266 pub fn trace_mut(&mut self) -> &mut StackTrace {267 &mut (self.0).1268 }269}270impl fmt::Display for Error {271 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {272 writeln!(f, "{}", self.0.0)?;273 for el in &self.0.1.0 {274 write!(f, "\t{}", el.desc)?;275 if let Some(loc) = &el.location {276 write!(f, "at {}", loc.0.0.0)?;277 loc.0.map_source_locations(&[loc.1, loc.2]);278 }279 writeln!(f)?;280 }281 Ok(())282 }283}284impl fmt::Debug for Error {285 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {286 f.debug_tuple("LocError").field(&self.0).finish()287 }288}289impl std::error::Error for Error {}290291pub trait ErrorSource {292 fn to_location(self) -> Option<Span>;293}294impl<T: Acyclic> ErrorSource for &Spanned<T> {295 fn to_location(self) -> Option<Span> {296 Some(self.span.clone())297 }298}299impl ErrorSource for &Span {300 fn to_location(self) -> Option<Span> {301 Some(self.clone())302 }303}304impl ErrorSource for CallLocation<'_> {305 fn to_location(self) -> Option<Span> {306 self.0.cloned()307 }308}309310pub type Result<V, E = Error> = std::result::Result<V, E>;311pub trait ResultExt: Sized {312 #[must_use]313 fn with_description<O: Into<String>>(self, msg: impl FnOnce() -> O) -> Self;314 #[must_use]315 fn description(self, msg: &str) -> Self {316 self.with_description(|| msg)317 }318319 #[must_use]320 fn with_description_src<O: Into<String>>(321 self,322 src: impl ErrorSource,323 msg: impl FnOnce() -> O,324 ) -> Self;325 #[must_use]326 fn description_src(self, src: impl ErrorSource, msg: &str) -> Self {327 self.with_description_src(src, || msg)328 }329}330impl<T> ResultExt for Result<T, Error> {331 fn with_description<O: Into<String>>(mut self, msg: impl FnOnce() -> O) -> Self {332 if let Err(e) = &mut self {333 let trace = e.trace_mut();334 trace.0.push(StackTraceElement {335 location: None,336 desc: msg().into(),337 });338 }339 self340 }341342 fn with_description_src<O: Into<String>>(343 mut self,344 src: impl ErrorSource,345 msg: impl FnOnce() -> O,346 ) -> Self {347 if let Err(e) = &mut self {348 let trace = e.trace_mut();349 trace.0.push(StackTraceElement {350 location: src.to_location(),351 desc: msg().into(),352 });353 }354 self355 }356}357358#[macro_export]359macro_rules! bail {360 ($w:ident$(::$i:ident)*$(($($tt:tt)*))?) => {361 return Err($w$(::$i)*$(($($tt)*))?.into())362 };363 ($w:ident$(::$i:ident)*$({$($tt:tt)*})?) => {364 return Err($w$(::$i)*$({$($tt)*})?.into())365 };366 ($l:literal$(, $($tt:tt)*)?) => {367 return Err($crate::error::ErrorKind::RuntimeError($crate::jrsonnet_macros::format_istr!($l$(, $($tt)*)?)).into())368 };369}370371#[macro_export]372macro_rules! runtime_error {373 ($l:literal$(, $($tt:tt)*)?) => {374 $crate::error::Error::from($crate::error::ErrorKind::RuntimeError($crate::jrsonnet_macros::format_istr!($l$(, $($tt)*)?)))375 };376}crates/jrsonnet-evaluator/src/evaluate/destructure.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/evaluate/destructure.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/destructure.rs
@@ -1,30 +1,23 @@
-use std::{collections::HashMap, hash::BuildHasher};
-
-use jrsonnet_interner::IStr;
use jrsonnet_ir::{BindSpec, Destruct};
#[cfg(feature = "exp-preserve-order")]
use crate::evaluate;
use crate::{
- Context, Pending, Thunk, Val, bail,
- error::{ErrorKind::*, Result},
- evaluate_method, evaluate_named_param,
+ Context, ContextBuilder, Pending, Thunk, Val, error::Result, evaluate_method,
+ evaluate_named_param,
};
#[allow(clippy::too_many_lines)]
#[allow(unused_variables)]
-pub fn destruct<H: BuildHasher>(
+pub fn destruct(
d: &Destruct,
parent: Thunk<Val>,
fctx: Pending<Context>,
- new_bindings: &mut HashMap<IStr, Thunk<Val>, H>,
+ new_bindings: &mut ContextBuilder,
) -> Result<()> {
match d {
Destruct::Full(v) => {
- let old = new_bindings.insert(v.clone(), parent);
- if old.is_some() {
- bail!(DuplicateLocalVar(v.clone()))
- }
+ new_bindings.try_bind(v.clone(), parent)?;
}
#[cfg(feature = "exp-destruct")]
Destruct::Skip => {}
@@ -187,10 +180,10 @@
Ok(())
}
-pub fn evaluate_dest<H: BuildHasher>(
+pub fn evaluate_dest(
d: &BindSpec,
fctx: Pending<Context>,
- new_bindings: &mut HashMap<IStr, Thunk<Val>, H>,
+ new_bindings: &mut ContextBuilder,
) -> Result<()> {
match d {
BindSpec::Field { into, value } => {
@@ -210,13 +203,10 @@
let params = params.clone();
let name = name.clone();
let value = value.clone();
- let old = new_bindings.insert(name.clone(), {
- let name = name.clone();
- Thunk!(move || Ok(evaluate_method(fctx.unwrap(), name, params, value)))
- });
- if old.is_some() {
- bail!(DuplicateLocalVar(name))
- }
+ new_bindings.try_bind(
+ name.clone(),
+ Thunk!(move || Ok(evaluate_method(fctx.unwrap(), name, params, value))),
+ )?;
}
}
Ok(())
crates/jrsonnet-evaluator/src/evaluate/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/evaluate/mod.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/mod.rs
@@ -8,19 +8,17 @@
function::ParamName,
};
use jrsonnet_types::ValType;
-use rustc_hash::FxHashMap;
use self::destructure::destruct;
use crate::{
- Context, Error, ObjValue, ObjValueBuilder, ObjectAssertion, Pending, Result, ResultExt,
- SupThis, Unbound, Val,
+ Context, ContextBuilder, Error, ObjValue, ObjValueBuilder, ObjectAssertion, Pending, Result,
+ ResultExt, SupThis, Unbound, Val,
arr::ArrValue,
bail,
destructure::evaluate_dest,
error::{ErrorKind::*, suggest_object_fields},
evaluate::operator::{evaluate_binary_op_special, evaluate_unary_op},
function::{CallLocation, FuncDesc, FuncVal, PreparedFuncVal},
- gc::WithCapacityExt as _,
in_frame,
typed::{FromUntyped, IntoUntyped as _, Typed},
val::{CachedUnbound, IndexableVal, NumValue, StrValue, Thunk},
@@ -130,9 +128,9 @@
guaranteed_reserve = guaranteed_reserve.max(1) * list.len();
for (i, item) in list.iter_lazy().enumerate() {
let fctx = Pending::new();
- let mut new_bindings = FxHashMap::with_capacity(into.binds_len());
- destruct(into, item, fctx.clone(), &mut new_bindings)?;
- let ctx = ctx.clone().extend_bindings(new_bindings).into_future(fctx);
+ let mut ctx = ContextBuilder::extend_fast(ctx.clone());
+ destruct(into, item, fctx.clone(), &mut ctx)?;
+ let ctx = ctx.build().into_future(fctx);
let specs = &specs[1..];
evaluate_comp(
@@ -179,6 +177,7 @@
}
fn evaluate_arr_comp(ctx: Context, expr: &Rc<Expr>, comp_specs: &[CompSpec]) -> Result<ArrValue> {
+ let ctx = ctx.branch_point();
'eager: {
let mut out = Vec::new();
@@ -225,17 +224,13 @@
fn bind(&self, sup_this: SupThis) -> Result<Context> {
let fctx = Context::new_future();
- let mut new_bindings =
- FxHashMap::with_capacity(self.locals.iter().map(BindSpec::binds_len).sum());
+ let ctx = self.fctx.clone();
+ let mut ctx = ContextBuilder::extend(ctx);
for b in self.locals.iter() {
- evaluate_dest(b, fctx.clone(), &mut new_bindings)?;
+ evaluate_dest(b, fctx.clone(), &mut ctx)?;
}
- let ctx = self.fctx.clone();
-
- let ctx = ctx
- .extend_bindings_sup_this(new_bindings, sup_this)
- .into_future(fctx);
+ let ctx = ctx.build_sup_this(sup_this).into_future(fctx);
Ok(ctx)
}
@@ -332,10 +327,7 @@
impl Unbound for DirectUnbound {
type Bound = Context;
fn bind(&self, sup_this: SupThis) -> Result<Context> {
- Ok(self
- .0
- .clone()
- .extend_bindings_sup_this(FxHashMap::new(), sup_this))
+ Ok(ContextBuilder::extend(self.0.clone()).build_sup_this(sup_this))
}
}
@@ -408,12 +400,17 @@
builder.with_super(super_obj);
}
let locals = obj.locals.clone();
- evaluate_comp(ctx, &obj.compspecs, 0, &mut |ctx, reserve| {
- let uctx = evaluate_object_locals(ctx.clone(), locals.clone());
- builder.reserve_fields(reserve);
+ evaluate_comp(
+ ctx.branch_point(),
+ &obj.compspecs,
+ 0,
+ &mut |ctx, reserve| {
+ let uctx = evaluate_object_locals(ctx.clone(), locals.clone());
+ builder.reserve_fields(reserve);
- evaluate_field_member(&mut builder, ctx, uctx, &obj.field)
- })?;
+ evaluate_field_member(&mut builder, ctx, uctx, &obj.field)
+ },
+ )?;
builder.build()
}
@@ -684,13 +681,12 @@
Ok(indexable)
})?,
LocalExpr(bindings, returned) => {
- let mut new_bindings: FxHashMap<IStr, Thunk<Val>> =
- FxHashMap::with_capacity(bindings.iter().map(BindSpec::binds_len).sum());
let fctx = Context::new_future();
+ let mut ctx = ContextBuilder::extend(ctx);
for b in bindings {
- evaluate_dest(b, fctx.clone(), &mut new_bindings)?;
+ evaluate_dest(b, fctx.clone(), &mut ctx)?;
}
- let ctx = ctx.extend_bindings(new_bindings).into_future(fctx);
+ let ctx = ctx.build().into_future(fctx);
evaluate(ctx, returned)?
}
Arr(items) => {
crates/jrsonnet-evaluator/src/function/parse.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/function/parse.rs
+++ b/crates/jrsonnet-evaluator/src/function/parse.rs
@@ -1,12 +1,10 @@
use jrsonnet_ir::ExprParams;
-use rustc_hash::FxHashMap;
use crate::{
- Context, Thunk,
+ Context, ContextBuilder, Thunk,
destructure::destruct,
error::{ErrorKind::*, Result},
evaluate_named_param,
- gc::WithCapacityExt as _,
};
/// Creates Context, which has all argument default values applied
@@ -14,7 +12,7 @@
pub fn parse_default_function_call(body_ctx: Context, params: &ExprParams) -> Result<Context> {
let fctx = Context::new_future();
- let mut bindings = FxHashMap::with_capacity(params.binds_len());
+ let mut ctx = ContextBuilder::extend(body_ctx);
for param in params.exprs.iter() {
if let Some(v) = ¶m.default {
@@ -27,7 +25,7 @@
Thunk!(move || evaluate_named_param(ctx.unwrap(), &value, name))
},
fctx.clone(),
- &mut bindings,
+ &mut ctx,
)?;
} else {
destruct(
@@ -42,10 +40,10 @@
.into()))
},
fctx.clone(),
- &mut bindings,
+ &mut ctx,
)?;
}
}
- Ok(body_ctx.extend_bindings(bindings).into_future(fctx))
+ Ok(ctx.build().into_future(fctx))
}
crates/jrsonnet-evaluator/src/function/prepared.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/function/prepared.rs
+++ b/crates/jrsonnet-evaluator/src/function/prepared.rs
@@ -2,12 +2,12 @@
use jrsonnet_gcmodule::{Acyclic, Trace};
use jrsonnet_ir::{ExprParams, IStr, function::FunctionSignature};
-use rustc_hash::{FxHashMap, FxHashSet};
+use rustc_hash::FxHashSet;
use super::{CallLocation, FuncVal};
use crate::{
Context, ContextBuilder, Pending, Result, Thunk, Val, bail, destructure::destruct,
- error::ErrorKind::*, evaluate_named_param, gc::WithCapacityExt,
+ error::ErrorKind::*, evaluate_named_param,
};
#[derive(Debug, Trace, Clone)]
@@ -118,7 +118,7 @@
unnamed: &[Thunk<Val>],
named: &[Thunk<Val>],
) -> Result<Context> {
- let mut passed_args = FxHashMap::with_capacity(params.binds_len());
+ let mut ctx = ContextBuilder::extend(body_ctx);
let destruct_ctx = Pending::new();
@@ -127,7 +127,7 @@
¶ms.exprs[param_idx].destruct,
unnamed.clone(),
destruct_ctx.clone(),
- &mut passed_args,
+ &mut ctx,
)?;
}
@@ -136,18 +136,16 @@
¶ms.exprs[param_idx].destruct,
named[arg_idx].clone(),
destruct_ctx.clone(),
- &mut passed_args,
+ &mut ctx,
)?;
}
if prepared.defaults.is_empty() {
- let body_ctx = body_ctx
- .extend_bindings(passed_args)
- .into_future(destruct_ctx);
+ let body_ctx = ctx.build().into_future(destruct_ctx);
Ok(body_ctx)
} else {
let fctx = Context::new_future();
- let mut defaults = FxHashMap::with_capacity(params.binds_len() - passed_args.len());
+ let mut ctx = ctx.commit();
for param_idx in prepared.defaults.iter().copied() {
// let param = params.0.rc_idx(param_idx);
destruct(
@@ -163,13 +161,10 @@
})
},
fctx.clone(),
- &mut defaults,
+ &mut ctx,
)?;
}
- let mut ctx = ContextBuilder::extend(body_ctx);
- ctx.binds(passed_args);
- ctx.binds(defaults);
Ok(ctx.build().into_future(fctx).into_future(destruct_ctx))
}
}
crates/jrsonnet-evaluator/src/gc.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/gc.rs
+++ b/crates/jrsonnet-evaluator/src/gc.rs
@@ -31,3 +31,5 @@
}
pub fn assert_trace<T: Trace>(_v: &T) {}
+
+pub type ImHashMap<K, V> = im_rc::HashMap<K, V, FxBuildHasher>;
crates/jrsonnet-evaluator/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/lib.rs
+++ b/crates/jrsonnet-evaluator/src/lib.rs
@@ -15,7 +15,6 @@
mod import;
mod integrations;
pub mod manifest;
-mod map;
mod obj;
pub mod stack;
pub mod stdlib;
@@ -162,19 +161,7 @@
/// During import, this trait will be called to create initial context for file.
/// It may initialize global variables, stdlib for example.
-pub trait ContextInitializer: Trace {
- /// For which size the builder should be preallocated
- fn reserve_vars(&self) -> usize {
- 0
- }
- /// Initialize default file context.
- /// Has default implementation, which calls `populate`.
- /// Prefer to always implement `populate` instead.
- fn initialize(&self, for_file: Source) -> Context {
- let mut builder = ContextBuilder::with_capacity(self.reserve_vars());
- self.populate(for_file, &mut builder);
- builder.build()
- }
+pub trait ContextInitializer {
/// For composability: extend builder. May panic if this initialization is not supported,
/// and the context may only be created via `initialize`.
fn populate(&self, for_file: Source, builder: &mut ContextBuilder);
@@ -182,6 +169,18 @@
/// jrsonnet by itself doesn't use this method, it is allowed for it to panic.
fn as_any(&self) -> &dyn Any;
}
+impl<T> ContextInitializer for &T
+where
+ T: ContextInitializer,
+{
+ fn populate(&self, for_file: Source, builder: &mut ContextBuilder) {
+ (*self).populate(for_file, builder);
+ }
+
+ fn as_any(&self) -> &dyn Any {
+ (*self).as_any()
+ }
+}
/// Context initializer which adds nothing.
impl ContextInitializer for () {
@@ -193,16 +192,8 @@
impl<T> ContextInitializer for Option<T>
where
- T: ContextInitializer,
+ T: ContextInitializer + 'static,
{
- fn initialize(&self, for_file: Source) -> Context {
- if let Some(ctx) = self {
- ctx.initialize(for_file)
- } else {
- ().initialize(for_file)
- }
- }
-
fn populate(&self, for_file: Source, builder: &mut ContextBuilder) {
if let Some(ctx) = self {
ctx.populate(for_file, builder);
@@ -218,12 +209,6 @@
($($gen:ident)*) => {
#[allow(non_snake_case)]
impl<$($gen: ContextInitializer + Trace,)*> ContextInitializer for ($($gen,)*) {
- fn reserve_vars(&self) -> usize {
- let mut out = 0;
- let ($($gen,)*) = self;
- $(out += $gen.reserve_vars();)*
- out
- }
fn populate(&self, for_file: Source, builder: &mut ContextBuilder) {
let ($($gen,)*) = self;
$($gen.populate(for_file.clone(), builder);)*
@@ -453,19 +438,17 @@
/// Creates context with all passed global variables
pub fn create_default_context(&self, source: Source) -> Context {
- self.context_initializer().initialize(source)
+ self.create_default_context_with(source, &())
}
/// Creates context with all passed global variables, calling custom modifier
pub fn create_default_context_with(
&self,
source: Source,
- context_initializer: impl ContextInitializer,
+ context_initializer: &dyn ContextInitializer,
) -> Context {
let default_initializer = self.context_initializer();
- let mut builder = ContextBuilder::with_capacity(
- default_initializer.reserve_vars() + context_initializer.reserve_vars(),
- );
+ let mut builder = ContextBuilder::new();
default_initializer.populate(source.clone(), &mut builder);
context_initializer.populate(source, &mut builder);
@@ -516,20 +499,14 @@
impl State {
/// Parses and evaluates the given snippet
pub fn evaluate_snippet(&self, name: impl Into<IStr>, code: impl Into<IStr>) -> Result<Val> {
- let code = code.into();
- let source = Source::new_virtual(name.into(), code.clone());
- let parsed = parse_jsonnet(&code, source.clone()).map_err(|e| ImportSyntaxError {
- path: source.clone(),
- error: Box::new(e),
- })?;
- evaluate(self.create_default_context(source), &parsed)
+ self.evaluate_snippet_with(name, code, &())
}
/// Parses and evaluates the given snippet with custom context modifier
pub fn evaluate_snippet_with(
&self,
name: impl Into<IStr>,
code: impl Into<IStr>,
- context_initializer: impl ContextInitializer,
+ context_initializer: &dyn ContextInitializer,
) -> Result<Val> {
let code = code.into();
let source = Source::new_virtual(name.into(), code.clone());
@@ -587,7 +564,7 @@
}
pub fn context_initializer(
&mut self,
- context_initializer: impl ContextInitializer,
+ context_initializer: impl ContextInitializer + Trace,
) -> &mut Self {
let _ = self
.context_initializer
crates/jrsonnet-evaluator/src/manifest.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/manifest.rs
+++ b/crates/jrsonnet-evaluator/src/manifest.rs
@@ -1,4 +1,4 @@
-use std::{borrow::Cow, fmt::Write, ptr};
+use std::{borrow::Cow, fmt::Write, hint::black_box, ptr};
use crate::{Result, ResultExt, Val, bail, in_description_frame};
@@ -44,6 +44,45 @@
}
}
+pub struct BlackBoxFormat;
+impl ManifestFormat for BlackBoxFormat {
+ #[allow(clippy::only_used_in_recursion)]
+ fn manifest_buf(&self, val: Val, buf: &mut String) -> Result<()> {
+ match val {
+ Val::Bool(v) => {
+ black_box(v);
+ }
+ val @ Val::Null => {
+ black_box(val);
+ }
+ Val::Str(str_value) => {
+ black_box(format!("{str_value}"));
+ }
+ Val::Num(num_value) => {
+ black_box(num_value);
+ }
+ Val::Arr(arr_value) => {
+ for ele in arr_value.iter() {
+ let ele = ele?;
+ self.manifest_buf(ele, buf)?;
+ }
+ }
+ Val::Obj(obj_value) => {
+ for (name, value) in obj_value.iter() {
+ black_box(name);
+ let value = value?;
+ self.manifest_buf(value, buf)?;
+ }
+ }
+ Val::Func(func_val) => {
+ black_box(func_val);
+ bail!("tried to manifest function")
+ }
+ }
+ Ok(())
+ }
+}
+
#[derive(PartialEq, Eq, Clone, Copy)]
enum JsonFormatting {
// Applied in manifestification
@@ -66,7 +105,6 @@
preserve_order: bool,
#[cfg(feature = "exp-bigint")]
preserve_bigints: bool,
- debug_truncate_strings: Option<usize>,
}
impl<'s> JsonFormat<'s> {
@@ -81,7 +119,6 @@
preserve_order,
#[cfg(feature = "exp-bigint")]
preserve_bigints: false,
- debug_truncate_strings: None,
}
}
/// Same format as std.toString, except does not keeps top-level string as-is
@@ -96,7 +133,6 @@
preserve_order: false,
#[cfg(feature = "exp-bigint")]
preserve_bigints: false,
- debug_truncate_strings: None,
}
}
pub fn std_to_json(
@@ -114,7 +150,6 @@
preserve_order,
#[cfg(feature = "exp-bigint")]
preserve_bigints: false,
- debug_truncate_strings: None,
}
}
// Same format as CLI manifestification
@@ -137,7 +172,6 @@
preserve_order,
#[cfg(feature = "exp-bigint")]
preserve_bigints: false,
- debug_truncate_strings: None,
}
}
// Same format as CLI manifestification
@@ -151,7 +185,6 @@
preserve_order: true,
#[cfg(feature = "exp-bigint")]
preserve_bigints: true,
- debug_truncate_strings: Some(256),
}
}
}
@@ -166,7 +199,6 @@
preserve_order: false,
#[cfg(feature = "exp-bigint")]
preserve_bigints: false,
- debug_truncate_strings: None,
}
}
}
@@ -197,18 +229,12 @@
}
Val::Null => buf.push_str("null"),
Val::Str(s) => {
- let flat = s.clone().into_flat();
- if let Some(truncate) = options.debug_truncate_strings {
- if flat.len() > truncate {
- let (start, end) = flat.split_at(truncate / 2);
- let (_, end) = end.split_at(end.len() - truncate / 2);
- escape_string_json_buf(&format!("{start}..{end}"), buf);
- } else {
- escape_string_json_buf(&flat, buf);
- }
- } else {
- escape_string_json_buf(&flat, buf);
- }
+ buf.reserve(2 + s.len());
+ buf.push('"');
+ s.chunks(&mut |c| {
+ escape_string_json_buf_raw(c, buf);
+ });
+ buf.push('"');
}
Val::Num(n) => write!(buf, "{n}").unwrap(),
#[cfg(feature = "exp-bigint")]
@@ -476,15 +502,15 @@
];
pub fn escape_string_json_buf(value: &str, buf: &mut String) {
+ buf.reserve_exact(value.len() + 2);
+ escape_string_json_buf_raw(value, buf);
+}
+
+fn escape_string_json_buf_raw(value: &str, buf: &mut String) {
// Safety: we only write correct utf-8 in this function
let buf: &mut Vec<u8> = unsafe { &mut *ptr::from_mut(buf).cast::<Vec<u8>>() };
let bytes = value.as_bytes();
-
- // Perfect for ascii strings, removes any reallocations
- buf.reserve(value.len() + 2);
- buf.push(b'"');
-
let mut start = 0;
for (i, &byte) in bytes.iter().enumerate() {
@@ -519,10 +545,8 @@
}
if start == bytes.len() {
- buf.push(b'"');
return;
}
buf.extend_from_slice(&bytes[start..]);
- buf.push(b'"');
}
crates/jrsonnet-evaluator/src/map.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/map.rs
+++ /dev/null
@@ -1,67 +0,0 @@
-use jrsonnet_gcmodule::{Cc, Trace};
-use jrsonnet_interner::IStr;
-use rustc_hash::FxHashMap;
-
-use crate::{Thunk, Val, gc::WithCapacityExt as _};
-
-#[derive(Trace, Debug)]
-#[trace(tracking(force))]
-pub struct LayeredHashMapInternals {
- parent: Option<LayeredHashMap>,
- current: FxHashMap<IStr, Thunk<Val>>,
-}
-
-#[derive(Trace, Debug)]
-pub struct LayeredHashMap(Cc<LayeredHashMapInternals>);
-
-impl LayeredHashMap {
- pub fn iter_keys(self, mut handler: impl FnMut(IStr)) {
- for k in self.0.current.keys() {
- handler(k.clone());
- }
- if let Some(parent) = self.0.parent.clone() {
- parent.iter_keys(handler);
- }
- }
-
- pub(crate) fn new(layer: FxHashMap<IStr, Thunk<Val>>) -> Self {
- Self(Cc::new(LayeredHashMapInternals {
- parent: None,
- current: layer,
- }))
- }
-
- pub fn extend(self, new_layer: FxHashMap<IStr, Thunk<Val>>) -> Self {
- Self(Cc::new(LayeredHashMapInternals {
- parent: Some(self),
- current: new_layer,
- }))
- }
-
- pub fn get(&self, key: &IStr) -> Option<&Thunk<Val>> {
- (self.0)
- .current
- .get(key)
- .or_else(|| self.0.parent.as_ref().and_then(|p| p.get(key)))
- }
-
- pub fn contains_key(&self, key: &IStr) -> bool {
- (self.0).current.contains_key(key)
- || self.0.parent.as_ref().is_some_and(|p| p.contains_key(key))
- }
-}
-
-impl Clone for LayeredHashMap {
- fn clone(&self) -> Self {
- Self(self.0.clone())
- }
-}
-
-impl Default for LayeredHashMap {
- fn default() -> Self {
- Self(Cc::new(LayeredHashMapInternals {
- parent: None,
- current: FxHashMap::new(),
- }))
- }
-}
crates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/val.rs
+++ b/crates/jrsonnet-evaluator/src/val.rs
@@ -355,8 +355,19 @@
Self::Tree(Rc::new((a, b, len)))
}
}
+ pub fn chunks(&self, c: &mut impl FnMut(&IStr)) {
+ fn write_buf(s: &StrValue, c: &mut impl FnMut(&IStr)) {
+ match s {
+ StrValue::Flat(f) => c(f),
+ StrValue::Tree(t) => {
+ write_buf(&t.0, c);
+ write_buf(&t.1, c);
+ }
+ }
+ }
+ write_buf(self, c);
+ }
pub fn into_flat(&self) -> IStr {
- #[cold]
fn write_buf(s: &StrValue, out: &mut String) {
match s {
StrValue::Flat(f) => out.push_str(f),
crates/jrsonnet-stdlib/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/lib.rs
+++ b/crates/jrsonnet-stdlib/src/lib.rs
@@ -545,9 +545,6 @@
}
}
impl jrsonnet_evaluator::ContextInitializer for ContextInitializer {
- fn reserve_vars(&self) -> usize {
- 1
- }
fn populate(&self, source: Source, builder: &mut ContextBuilder) {
let mut std = ObjValueBuilder::new();
std.with_super(self.stdlib_obj.clone());
tests/Cargo.tomldiffbeforeafterboth--- a/tests/Cargo.toml
+++ b/tests/Cargo.toml
@@ -18,6 +18,7 @@
jrsonnet-evaluator.workspace = true
jrsonnet-gcmodule.workspace = true
jrsonnet-stdlib.workspace = true
+mimallocator.workspace = true
serde.workspace = true
serde_json.workspace = true