difftreelog
refactor move push_frame out of State struct
in: master
14 files changed
crates/jrsonnet-evaluator/src/evaluate/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/evaluate/mod.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/mod.rs
@@ -16,10 +16,11 @@
error::{suggest_object_fields, ErrorKind::*},
evaluate::operator::{evaluate_add_op, evaluate_binary_op_special, evaluate_unary_op},
function::{CallLocation, FuncDesc, FuncVal},
+ in_frame,
typed::Typed,
val::{CachedUnbound, IndexableVal, NumValue, StrValue, Thunk, ThunkValue},
Context, Error, GcHashMap, ObjValue, ObjValueBuilder, ObjectAssertion, Pending, Result,
- ResultExt, State, Unbound, Val,
+ ResultExt, Unbound, Val,
};
pub mod destructure;
pub mod operator;
@@ -71,7 +72,7 @@
pub fn evaluate_field_name(ctx: Context, field_name: &FieldName) -> Result<Option<IStr>> {
Ok(match field_name {
FieldName::Fixed(n) => Some(n.clone()),
- FieldName::Dyn(expr) => State::push(
+ FieldName::Dyn(expr) => in_frame(
CallLocation::new(&expr.span()),
|| "evaluating field name".to_string(),
|| {
@@ -374,7 +375,7 @@
if tailstrict {
body()?
} else {
- State::push(loc, || format!("function <{}> call", f.name()), body)?
+ in_frame(loc, || format!("function <{}> call", f.name()), body)?
}
}
v => bail!(OnlyFunctionsCanBeCalledGot(v.value_type())),
@@ -384,13 +385,13 @@
pub fn evaluate_assert(ctx: Context, assertion: &AssertStmt) -> Result<()> {
let value = &assertion.0;
let msg = &assertion.1;
- let assertion_result = State::push(
+ let assertion_result = in_frame(
CallLocation::new(&value.span()),
|| "assertion condition".to_owned(),
|| bool::from_untyped(evaluate(ctx.clone(), value)?),
)?;
if !assertion_result {
- State::push(
+ in_frame(
CallLocation::new(&value.span()),
|| "assertion failure".to_owned(),
|| {
@@ -457,7 +458,7 @@
}
BinaryOp(v1, o, v2) => evaluate_binary_op_special(ctx, v1, *o, v2)?,
UnaryOp(o, v) => evaluate_unary_op(*o, &evaluate(ctx, v)?)?,
- Var(name) => State::push(
+ Var(name) => in_frame(
CallLocation::new(&loc),
|| format!("variable <{name}> access"),
|| ctx.binding(name.clone())?.evaluate(),
@@ -645,7 +646,7 @@
evaluate_assert(ctx.clone(), assert)?;
evaluate(ctx, returned)?
}
- ErrorStmt(e) => State::push(
+ ErrorStmt(e) => in_frame(
CallLocation::new(&loc),
|| "error statement".to_owned(),
|| bail!(RuntimeError(evaluate(ctx, e)?.to_string()?,)),
@@ -655,7 +656,7 @@
cond_then,
cond_else,
} => {
- if State::push(
+ if in_frame(
CallLocation::new(&loc),
|| "if condition".to_owned(),
|| bool::from_untyped(evaluate(ctx.clone(), &cond.0)?),
@@ -676,7 +677,7 @@
desc: &'static str,
) -> Result<Option<T>> {
if let Some(value) = expr {
- Ok(Some(State::push(
+ Ok(Some(in_frame(
loc,
|| format!("slice {desc}"),
|| T::from_untyped(evaluate(ctx.clone(), value)?),
@@ -703,7 +704,7 @@
let s = ctx.state();
let resolved_path = s.resolve_from(tmp.source_path(), path as &str)?;
match i {
- Import(_) => State::push(
+ Import(_) => in_frame(
CallLocation::new(&loc),
|| format!("import {:?}", path.clone()),
|| s.import_resolved(resolved_path),
crates/jrsonnet-evaluator/src/import.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/import.rs
+++ b/crates/jrsonnet-evaluator/src/import.rs
@@ -1,6 +1,5 @@
use std::{
any::Any,
- cell::RefCell,
env::current_dir,
fs,
io::{ErrorKind, Read},
@@ -41,8 +40,10 @@
/// this cannot be resolved using associated type, as evaluator uses object instead of generic for [`ImportResolver`]
fn load_file_contents(&self, resolved: &SourcePath) -> Result<Vec<u8>>;
- /// For downcasts
+ // For downcasts, will be removed after trait_upcasting_coercion
+ // stabilization.
fn as_any(&self) -> &dyn Any;
+ fn as_any_mut(&mut self) -> &mut dyn Any;
}
/// Dummy resolver, can't resolve/load any file
@@ -56,6 +57,9 @@
fn as_any(&self) -> &dyn Any {
self
}
+ fn as_any_mut(&mut self) -> &mut dyn Any {
+ self
+ }
}
#[allow(clippy::use_self)]
impl Default for Box<dyn ImportResolver> {
@@ -69,17 +73,15 @@
pub struct FileImportResolver {
/// Library directories to search for file.
/// Referred to as `jpath` in original jsonnet implementation.
- library_paths: RefCell<Vec<PathBuf>>,
+ library_paths: Vec<PathBuf>,
}
impl FileImportResolver {
- pub fn new(jpath: Vec<PathBuf>) -> Self {
- Self {
- library_paths: RefCell::new(jpath),
- }
+ pub fn new(library_paths: Vec<PathBuf>) -> Self {
+ Self { library_paths }
}
/// Dynamically add new jpath, used by bindings
- pub fn add_jpath(&self, path: PathBuf) {
- self.library_paths.borrow_mut().push(path);
+ pub fn add_jpath(&mut self, path: PathBuf) {
+ self.library_paths.push(path);
}
}
@@ -132,7 +134,7 @@
if let Some(direct) = check_path(&direct)? {
return Ok(direct);
}
- for library_path in self.library_paths.borrow().iter() {
+ for library_path in &self.library_paths {
let mut cloned = library_path.clone();
cloned.push(path);
if let Some(cloned) = check_path(&cloned)? {
@@ -165,11 +167,15 @@
Ok(out)
}
+ fn resolve_from_default(&self, path: &str) -> Result<SourcePath> {
+ self.resolve_from(&SourcePath::default(), path)
+ }
+
fn as_any(&self) -> &dyn Any {
self
}
- fn resolve_from_default(&self, path: &str) -> Result<SourcePath> {
- self.resolve_from(&SourcePath::default(), path)
+ fn as_any_mut(&mut self) -> &mut dyn Any {
+ self
}
}
crates/jrsonnet-evaluator/src/integrations/serde.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/integrations/serde.rs
+++ b/crates/jrsonnet-evaluator/src/integrations/serde.rs
@@ -11,8 +11,8 @@
};
use crate::{
- arr::ArrValue, runtime_error, val::NumValue, Error as JrError, ObjValue, ObjValueBuilder,
- Result, State, Val,
+ arr::ArrValue, in_description_frame, runtime_error, val::NumValue, Error as JrError, ObjValue,
+ ObjValueBuilder, Result, Val,
};
impl<'de> Deserialize<'de> for Val {
@@ -173,8 +173,7 @@
let mut seq = serializer.serialize_seq(Some(arr.len()))?;
for (i, element) in arr.iter().enumerate() {
let mut serde_error = None;
- // TODO: rewrite using try{} after stabilization
- State::push_description(
+ in_description_frame(
|| format!("array index [{i}]"),
|| {
let e = element?;
@@ -199,7 +198,7 @@
) {
let mut serde_error = None;
// TODO: rewrite using try{} after stabilization
- State::push_description(
+ in_description_frame(
|| format!("object field {field:?}"),
|| {
let v = value?;
crates/jrsonnet-evaluator/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/lib.rs
+++ b/crates/jrsonnet-evaluator/src/lib.rs
@@ -45,7 +45,7 @@
#[doc(hidden)]
pub use jrsonnet_macros;
pub use jrsonnet_parser as parser;
-use jrsonnet_parser::{LocExpr, ParserSettings, Source, SourcePath, Span};
+use jrsonnet_parser::{LocExpr, ParserSettings, Source, SourcePath};
pub use obj::*;
use stack::check_depth;
pub use tla::apply_tla;
@@ -376,38 +376,6 @@
context_initializer.populate(source, &mut builder);
builder.build()
- }
-
- /// Executes code creating a new stack frame
- pub fn push<T>(
- e: CallLocation<'_>,
- frame_desc: impl FnOnce() -> String,
- f: impl FnOnce() -> Result<T>,
- ) -> Result<T> {
- let _guard = check_depth()?;
-
- f().with_description_src(e, frame_desc)
- }
-
- /// Executes code creating a new stack frame
- pub fn push_val(
- &self,
- e: &Span,
- frame_desc: impl FnOnce() -> String,
- f: impl FnOnce() -> Result<Val>,
- ) -> Result<Val> {
- let _guard = check_depth()?;
-
- f().with_description_src(e, frame_desc)
- }
- /// Executes code creating a new stack frame
- pub fn push_description<T>(
- frame_desc: impl FnOnce() -> String,
- f: impl FnOnce() -> Result<T>,
- ) -> Result<T> {
- let _guard = check_depth()?;
-
- f().with_description(frame_desc)
}
}
@@ -417,6 +385,26 @@
self.0.file_cache.borrow_mut()
}
}
+/// Executes code creating a new stack frame, to be replaced with try{}
+pub fn in_frame<T>(
+ e: CallLocation<'_>,
+ frame_desc: impl FnOnce() -> String,
+ f: impl FnOnce() -> Result<T>,
+) -> Result<T> {
+ let _guard = check_depth()?;
+
+ f().with_description_src(e, frame_desc)
+}
+
+/// Executes code creating a new stack frame, to be replaced with try{}
+pub fn in_description_frame<T>(
+ frame_desc: impl FnOnce() -> String,
+ f: impl FnOnce() -> Result<T>,
+) -> Result<T> {
+ let _guard = check_depth()?;
+
+ f().with_description(frame_desc)
+}
#[derive(Trace)]
pub struct InitialUnderscore(pub Thunk<Val>);
crates/jrsonnet-evaluator/src/manifest.rsdiffbeforeafterboth1use std::{borrow::Cow, fmt::Write, ptr};23use crate::{bail, Result, ResultExt, State, Val};45pub trait ManifestFormat {6 fn manifest_buf(&self, val: Val, buf: &mut String) -> Result<()>;7 fn manifest(&self, val: Val) -> Result<String> {8 let mut out = String::new();9 self.manifest_buf(val, &mut out)?;10 Ok(out)11 }12 /// When outputing to file, is it safe to append a trailing newline (I.e newline won't change13 /// the meaning).14 ///15 /// Default implementation returns `true`16 fn file_trailing_newline(&self) -> bool {17 true18 }19}20impl<T> ManifestFormat for Box<T>21where22 T: ManifestFormat + ?Sized,23{24 fn manifest_buf(&self, val: Val, buf: &mut String) -> Result<()> {25 let inner = &**self;26 inner.manifest_buf(val, buf)27 }28 fn file_trailing_newline(&self) -> bool {29 let inner = &**self;30 inner.file_trailing_newline()31 }32}33impl<T> ManifestFormat for &'_ T34where35 T: ManifestFormat + ?Sized,36{37 fn manifest_buf(&self, val: Val, buf: &mut String) -> Result<()> {38 let inner = &**self;39 inner.manifest_buf(val, buf)40 }41 fn file_trailing_newline(&self) -> bool {42 let inner = &**self;43 inner.file_trailing_newline()44 }45}4647#[derive(PartialEq, Eq, Clone, Copy)]48enum JsonFormatting {49 // Applied in manifestification50 Manifest,51 /// Used for std.manifestJson52 /// Empty array/objects extends to "[\n\n]" instead of "[ ]" as in manifest53 Std,54 /// No line breaks, used in `obj+''`55 ToString,56 /// Minified json57 Minify,58}5960pub struct JsonFormat<'s> {61 padding: Cow<'s, str>,62 mtype: JsonFormatting,63 newline: &'s str,64 key_val_sep: &'s str,65 #[cfg(feature = "exp-preserve-order")]66 preserve_order: bool,67 #[cfg(feature = "exp-bigint")]68 preserve_bigints: bool,69 debug_truncate_strings: Option<usize>,70}7172impl<'s> JsonFormat<'s> {73 // Minifying format74 pub fn minify(#[cfg(feature = "exp-preserve-order")] preserve_order: bool) -> Self {75 Self {76 padding: Cow::Borrowed(""),77 mtype: JsonFormatting::Minify,78 newline: "\n",79 key_val_sep: ":",80 #[cfg(feature = "exp-preserve-order")]81 preserve_order,82 #[cfg(feature = "exp-bigint")]83 preserve_bigints: false,84 debug_truncate_strings: None,85 }86 }87 /// Same format as std.toString, except does not keeps top-level string as-is88 /// To avoid confusion, the format is private in jrsonnet, use [`ToStringFormat`] instead89 const fn std_to_string_helper() -> Self {90 Self {91 padding: Cow::Borrowed(""),92 mtype: JsonFormatting::ToString,93 newline: "\n",94 key_val_sep: ": ",95 #[cfg(feature = "exp-preserve-order")]96 preserve_order: false,97 #[cfg(feature = "exp-bigint")]98 preserve_bigints: false,99 debug_truncate_strings: None,100 }101 }102 pub fn std_to_json(103 padding: String,104 newline: &'s str,105 key_val_sep: &'s str,106 #[cfg(feature = "exp-preserve-order")] preserve_order: bool,107 ) -> Self {108 Self {109 padding: Cow::Owned(padding),110 mtype: JsonFormatting::Std,111 newline,112 key_val_sep,113 #[cfg(feature = "exp-preserve-order")]114 preserve_order,115 #[cfg(feature = "exp-bigint")]116 preserve_bigints: false,117 debug_truncate_strings: None,118 }119 }120 // Same format as CLI manifestification121 pub fn cli(122 padding: usize,123 #[cfg(feature = "exp-preserve-order")] preserve_order: bool,124 ) -> Self {125 if padding == 0 {126 return Self::minify(127 #[cfg(feature = "exp-preserve-order")]128 preserve_order,129 );130 }131 Self {132 padding: Cow::Owned(" ".repeat(padding)),133 mtype: JsonFormatting::Manifest,134 newline: "\n",135 key_val_sep: ": ",136 #[cfg(feature = "exp-preserve-order")]137 preserve_order,138 #[cfg(feature = "exp-bigint")]139 preserve_bigints: false,140 debug_truncate_strings: None,141 }142 }143 // Same format as CLI manifestification144 pub fn debug() -> Self {145 Self {146 padding: Cow::Borrowed(" "),147 mtype: JsonFormatting::Manifest,148 newline: "\n",149 key_val_sep: ": ",150 #[cfg(feature = "exp-preserve-order")]151 preserve_order: true,152 #[cfg(feature = "exp-bigint")]153 preserve_bigints: true,154 debug_truncate_strings: Some(256),155 }156 }157}158impl Default for JsonFormat<'static> {159 fn default() -> Self {160 Self {161 padding: Cow::Borrowed(" "),162 mtype: JsonFormatting::Manifest,163 newline: "\n",164 key_val_sep: ": ",165 #[cfg(feature = "exp-preserve-order")]166 preserve_order: false,167 #[cfg(feature = "exp-bigint")]168 preserve_bigints: false,169 debug_truncate_strings: None,170 }171 }172}173174pub fn manifest_json_ex(val: &Val, options: &JsonFormat<'_>) -> Result<String> {175 let mut out = String::new();176 manifest_json_ex_buf(val, &mut out, &mut String::new(), options)?;177 Ok(out)178}179180#[allow(clippy::too_many_lines)]181fn manifest_json_ex_buf(182 val: &Val,183 buf: &mut String,184 cur_padding: &mut String,185 options: &JsonFormat<'_>,186) -> Result<()> {187 use JsonFormatting::*;188189 let mtype = options.mtype;190 match val {191 Val::Bool(v) => {192 if *v {193 buf.push_str("true");194 } else {195 buf.push_str("false");196 }197 }198 Val::Null => buf.push_str("null"),199 Val::Str(s) => {200 let flat = s.clone().into_flat();201 if let Some(truncate) = options.debug_truncate_strings {202 if flat.len() > truncate {203 let (start, end) = flat.split_at(truncate / 2);204 let (_, end) = end.split_at(end.len() - truncate / 2);205 escape_string_json_buf(&format!("{start}..{end}"), buf);206 } else {207 escape_string_json_buf(&flat, buf);208 }209 } else {210 escape_string_json_buf(&flat, buf);211 }212 }213 Val::Num(n) => write!(buf, "{n}").unwrap(),214 #[cfg(feature = "exp-bigint")]215 Val::BigInt(n) => {216 if options.preserve_bigints {217 write!(buf, "{n}").unwrap();218 } else {219 write!(buf, "{:?}", n.to_string()).unwrap();220 }221 }222 Val::Arr(items) => {223 buf.push('[');224225 let old_len = cur_padding.len();226 cur_padding.push_str(&options.padding);227228 let mut had_items = false;229 for (i, item) in items.iter().enumerate() {230 had_items = true;231 let item = item.with_description(|| format!("elem <{i}> evaluation"))?;232233 if i != 0 {234 buf.push(',');235 }236 match mtype {237 Manifest | Std => {238 buf.push_str(options.newline);239 buf.push_str(cur_padding);240 }241 ToString if i != 0 => buf.push(' '),242 Minify | ToString => {}243 };244245 State::push_description(246 || format!("elem <{i}> manifestification"),247 || manifest_json_ex_buf(&item, buf, cur_padding, options),248 )?;249 }250251 cur_padding.truncate(old_len);252253 match mtype {254 Manifest | ToString if !had_items => {255 // Empty array as "[ ]"256 buf.push(' ');257 }258 Manifest => {259 buf.push_str(options.newline);260 buf.push_str(cur_padding);261 }262 Std => {263 if !had_items {264 // Stdlib formats empty array as "[\n\n]"265 buf.push_str(options.newline);266 }267 buf.push_str(options.newline);268 buf.push_str(cur_padding);269 }270 Minify | ToString => {}271 }272273 buf.push(']');274 }275 Val::Obj(obj) => {276 obj.run_assertions()?;277 buf.push('{');278279 let old_len = cur_padding.len();280 cur_padding.push_str(&options.padding);281282 let mut had_fields = false;283 for (i, (key, value)) in obj284 .iter(285 #[cfg(feature = "exp-preserve-order")]286 options.preserve_order,287 )288 .enumerate()289 {290 had_fields = true;291 let value = value.with_description(|| format!("field <{key}> evaluation"))?;292293 if i != 0 {294 buf.push(',');295 }296 match mtype {297 Manifest | Std => {298 buf.push_str(options.newline);299 buf.push_str(cur_padding);300 }301 ToString if i != 0 => buf.push(' '),302 Minify | ToString => {}303 }304305 escape_string_json_buf(&key, buf);306 buf.push_str(options.key_val_sep);307 State::push_description(308 || format!("field <{key}> manifestification"),309 || manifest_json_ex_buf(&value, buf, cur_padding, options),310 )?;311 }312313 cur_padding.truncate(old_len);314315 match mtype {316 Manifest | ToString if !had_fields => {317 // Empty object as "{ }"318 buf.push(' ');319 }320 Manifest => {321 buf.push_str(options.newline);322 buf.push_str(cur_padding);323 }324 Std => {325 if !had_fields {326 // Stdlib formats empty object as "{\n\n}"327 buf.push_str(options.newline);328 }329 buf.push_str(options.newline);330 buf.push_str(cur_padding);331 }332 Minify | ToString => {}333 }334335 buf.push('}');336 }337 Val::Func(_) => bail!("tried to manifest function"),338 };339 Ok(())340}341342impl ManifestFormat for JsonFormat<'_> {343 fn manifest_buf(&self, val: Val, buf: &mut String) -> Result<()> {344 manifest_json_ex_buf(&val, buf, &mut String::new(), self)345 }346}347348/// Same as [`JsonFormat`] with pre-set options, but top-level string is serialized as-is,349/// without quoting.350pub struct ToStringFormat;351impl ManifestFormat for ToStringFormat {352 fn manifest_buf(&self, val: Val, out: &mut String) -> Result<()> {353 const JSON_TO_STRING: JsonFormat = JsonFormat::std_to_string_helper();354 if let Some(str) = val.as_str() {355 out.push_str(&str);356 return Ok(());357 }358 JSON_TO_STRING.manifest_buf(val, out)359 }360 fn file_trailing_newline(&self) -> bool {361 false362 }363}364pub struct StringFormat;365impl ManifestFormat for StringFormat {366 fn manifest_buf(&self, val: Val, out: &mut String) -> Result<()> {367 let Val::Str(s) = val else {368 bail!(369 "output should be string for string manifest format, got {}",370 val.value_type()371 )372 };373 write!(out, "{s}").unwrap();374 Ok(())375 }376 fn file_trailing_newline(&self) -> bool {377 false378 }379}380381pub struct YamlStreamFormat<I> {382 inner: I,383 c_document_end: bool,384 end_newline: bool,385}386impl<I> YamlStreamFormat<I> {387 pub fn std_yaml_stream(inner: I, c_document_end: bool) -> Self {388 Self {389 inner,390 c_document_end,391 // Stdlib format always inserts useless newline at the end392 end_newline: true,393 }394 }395 pub fn cli(inner: I) -> Self {396 Self {397 inner,398 c_document_end: true,399 end_newline: false,400 }401 }402}403impl<I: ManifestFormat> ManifestFormat for YamlStreamFormat<I> {404 fn manifest_buf(&self, val: Val, out: &mut String) -> Result<()> {405 let Val::Arr(arr) = val else {406 bail!(407 "output should be array for yaml stream format, got {}",408 val.value_type()409 )410 };411 if !arr.is_empty() {412 for (i, v) in arr.iter().enumerate() {413 let v = v.with_description(|| format!("elem <{i}> evaluation"))?;414 out.push_str("---\n");415 State::push_description(416 || format!("elem <{i}> manifestification"),417 || self.inner.manifest_buf(v, out),418 )?;419 out.push('\n');420 }421 }422 if self.c_document_end {423 out.push_str("...");424 }425 if self.end_newline {426 out.push('\n');427 }428 Ok(())429 }430}431432pub fn escape_string_json(s: &str) -> String {433 let mut buf = String::new();434 escape_string_json_buf(s, &mut buf);435 buf436}437438// Json string encoding was borrowed from https://github.com/serde-rs/json439440const BB: u8 = b'b'; // \x08441const TT: u8 = b't'; // \x09442const NN: u8 = b'n'; // \x0A443const FF: u8 = b'f'; // \x0C444const RR: u8 = b'r'; // \x0D445const QU: u8 = b'"'; // \x22446const BS: u8 = b'\\'; // \x5C447const UU: u8 = b'u'; // \x00...\x1F except the ones above448const __: u8 = 0;449450// Lookup table of escape sequences. A value of b'x' at index i means that byte451// i is escaped as "\x" in JSON. A value of 0 means that byte i is not escaped.452static ESCAPE: [u8; 256] = [453 // 1 2 3 4 5 6 7 8 9 A B C D E F454 UU, UU, UU, UU, UU, UU, UU, UU, BB, TT, NN, UU, FF, RR, UU, UU, // 0455 UU, UU, UU, UU, UU, UU, UU, UU, UU, UU, UU, UU, UU, UU, UU, UU, // 1456 __, __, QU, __, __, __, __, __, __, __, __, __, __, __, __, __, // 2457 __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // 3458 __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // 4459 __, __, __, __, __, __, __, __, __, __, __, __, BS, __, __, __, // 5460 __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // 6461 __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // 7462 __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // 8463 __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // 9464 __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // A465 __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // B466 __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // C467 __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // D468 __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // E469 __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // F470];471472pub fn escape_string_json_buf(value: &str, buf: &mut String) {473 // Safety: we only write correct utf-8 in this function474 let buf: &mut Vec<u8> = unsafe { &mut *ptr::from_mut(buf).cast::<Vec<u8>>() };475 let bytes = value.as_bytes();476477 // Perfect for ascii strings, removes any reallocations478 buf.reserve(value.len() + 2);479480 buf.push(b'"');481482 let mut start = 0;483484 for (i, &byte) in bytes.iter().enumerate() {485 let escape = ESCAPE[byte as usize];486 if escape == __ {487 continue;488 }489490 if start < i {491 buf.extend_from_slice(&bytes[start..i]);492 }493 start = i + 1;494495 match escape {496 self::BB | self::TT | self::NN | self::FF | self::RR | self::QU | self::BS => {497 buf.extend_from_slice(&[b'\\', escape]);498 }499 self::UU => {500 static HEX_DIGITS: [u8; 16] = *b"0123456789abcdef";501 let bytes = &[502 b'\\',503 b'u',504 b'0',505 b'0',506 HEX_DIGITS[(byte >> 4) as usize],507 HEX_DIGITS[(byte & 0xF) as usize],508 ];509 buf.extend_from_slice(bytes);510 }511 _ => unreachable!(),512 }513 }514515 if start == bytes.len() {516 buf.push(b'"');517 return;518 }519520 buf.extend_from_slice(&bytes[start..]);521 buf.push(b'"');522}crates/jrsonnet-evaluator/src/obj.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/obj.rs
+++ b/crates/jrsonnet-evaluator/src/obj.rs
@@ -17,10 +17,11 @@
error::{suggest_object_fields, Error, ErrorKind::*},
function::{CallLocation, FuncVal},
gc::{GcHashMap, GcHashSet, TraceBox},
+ in_frame,
operator::evaluate_add_op,
tb,
val::{ArrValue, ThunkValue},
- MaybeUnbound, Result, State, Thunk, Unbound, Val,
+ MaybeUnbound, Result, Thunk, Unbound, Val,
};
#[cfg(not(feature = "exp-preserve-order"))]
@@ -969,7 +970,7 @@
let location = member.location.clone();
let old = receiver.0.map.insert(name.clone(), member);
if old.is_some() {
- State::push(
+ in_frame(
CallLocation(location.as_ref()),
|| format!("field <{}> initializtion", name.clone()),
|| bail!(DuplicateFieldName(name.clone())),
crates/jrsonnet-evaluator/src/stdlib/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/stdlib/mod.rs
+++ b/crates/jrsonnet-evaluator/src/stdlib/mod.rs
@@ -3,12 +3,12 @@
use format::{format_arr, format_obj};
-use crate::{function::CallLocation, Result, State, Val};
+use crate::{function::CallLocation, in_frame, Result, Val};
pub mod format;
pub fn std_format(str: &str, vals: Val) -> Result<String> {
- State::push(
+ in_frame(
CallLocation::native(),
|| format!("std.format of {str}"),
|| {
crates/jrsonnet-evaluator/src/tla.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/tla.rs
+++ b/crates/jrsonnet-evaluator/src/tla.rs
@@ -3,12 +3,12 @@
use crate::{
function::{ArgsLike, CallLocation},
- Result, State, Val,
+ in_description_frame, Result, State, Val,
};
pub fn apply_tla<A: ArgsLike>(s: State, args: &A, val: Val) -> Result<Val> {
Ok(if let Val::Func(func) = val {
- State::push_description(
+ in_description_frame(
|| "during TLA call".to_owned(),
|| {
func.evaluate(
crates/jrsonnet-evaluator/src/typed/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/typed/mod.rs
+++ b/crates/jrsonnet-evaluator/src/typed/mod.rs
@@ -8,7 +8,7 @@
use crate::{
error::{Error, ErrorKind, Result},
- State, Val,
+ in_description_frame, Val,
};
#[derive(Debug, Error, Clone, Trace)]
@@ -89,7 +89,7 @@
path: impl Fn() -> ValuePathItem,
item: impl Fn() -> Result<()>,
) -> Result<()> {
- State::push_description(error_reason, || match item() {
+ in_description_frame(error_reason, || match item() {
Ok(()) => Ok(()),
Err(mut e) => {
if let ErrorKind::TypeError(e) = &mut e.error_mut() {
crates/jrsonnet-interner/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-interner/src/lib.rs
+++ b/crates/jrsonnet-interner/src/lib.rs
@@ -235,6 +235,7 @@
use crate::{PoolMap, POOL};
+ /// Type-erased interned string pool
pub enum PoolState {}
/// Dump current interned string pool, to be restored by
crates/jrsonnet-macros/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-macros/src/lib.rs
+++ b/crates/jrsonnet-macros/src/lib.rs
@@ -290,7 +290,7 @@
cfg_attrs,
} => {
let name = name.as_ref().map_or("<unnamed>", String::as_str);
- let eval = quote! {jrsonnet_evaluator::State::push_description(
+ let eval = quote! {jrsonnet_evaluator::in_description_frame(
|| format!("argument <{}> evaluation", #name),
|| <#ty>::from_untyped(value.evaluate()?),
)?};
crates/jrsonnet-stdlib/src/manifest/toml.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/manifest/toml.rs
+++ b/crates/jrsonnet-stdlib/src/manifest/toml.rs
@@ -1,10 +1,10 @@
use std::borrow::Cow;
use jrsonnet_evaluator::{
- bail,
+ bail, in_description_frame,
manifest::{escape_string_json_buf, ManifestFormat},
val::ArrValue,
- IStr, ObjValue, Result, ResultExt, State, Val,
+ IStr, ObjValue, Result, ResultExt, Val,
};
pub struct TomlFormat<'s> {
@@ -124,7 +124,7 @@
buf.push_str(&options.padding);
}
- State::push_description(
+ in_description_frame(
|| format!("elem <{i}> manifestification"),
|| manifest_value(&e, true, buf, "", options),
)?;
@@ -161,7 +161,7 @@
escape_key_toml_buf(&k, buf);
buf.push_str(" = ");
- State::push_description(
+ in_description_frame(
|| format!("field <{k}> manifestification"),
|| manifest_value(&v, true, buf, "", options),
)?;
crates/jrsonnet-stdlib/src/manifest/xml.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/manifest/xml.rs
+++ b/crates/jrsonnet-stdlib/src/manifest/xml.rs
@@ -1,9 +1,9 @@
use jrsonnet_evaluator::{
- bail,
+ bail, in_description_frame,
manifest::{ManifestFormat, ToStringFormat},
typed::{ComplexValType, Either2, Typed, ValType},
val::ArrValue,
- Either, ObjValue, Result, ResultExt, State, Val,
+ Either, ObjValue, Result, ResultExt, Val,
};
pub struct XmlJsonmlFormat {
@@ -70,7 +70,7 @@
Ok(Self::Tag {
tag,
attrs,
- children: State::push_description(
+ children: in_description_frame(
|| "parsing children".to_owned(),
|| {
Typed::from_untyped(Val::Arr(arr.slice(
crates/jrsonnet-stdlib/src/manifest/yaml.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/manifest/yaml.rs
+++ b/crates/jrsonnet-stdlib/src/manifest/yaml.rs
@@ -1,9 +1,9 @@
use std::{borrow::Cow, fmt::Write};
use jrsonnet_evaluator::{
- bail,
+ bail, in_description_frame,
manifest::{escape_string_json_buf, ManifestFormat},
- Result, ResultExt, State, Val,
+ Result, ResultExt, Val,
};
pub struct YamlFormat<'s> {
@@ -178,7 +178,7 @@
if extra_padding {
cur_padding.push_str(&options.padding);
}
- State::push_description(
+ in_description_frame(
|| format!("elem <{i}> manifestification"),
|| manifest_yaml_ex_buf(&item, buf, cur_padding, options),
)?;
@@ -225,7 +225,7 @@
}
_ => buf.push(' '),
}
- State::push_description(
+ in_description_frame(
|| format!("field <{key}> manifestification"),
|| manifest_yaml_ex_buf(&value, buf, cur_padding, options),
)?;