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.rsdiffbeforeafterboth1use std::borrow::Cow;23use jrsonnet_interner::IStr;4use serde::{5 de::{self, Visitor},6 ser::{7 Error, SerializeMap, SerializeSeq, SerializeStruct, SerializeStructVariant, SerializeTuple,8 SerializeTupleStruct, SerializeTupleVariant,9 },10 Deserialize, Serialize, Serializer,11};1213use crate::{14 arr::ArrValue, runtime_error, val::NumValue, Error as JrError, ObjValue, ObjValueBuilder,15 Result, State, Val,16};1718impl<'de> Deserialize<'de> for Val {19 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>20 where21 D: serde::Deserializer<'de>,22 {23 struct ValVisitor;2425 // macro_rules! visit_num {26 // ($($method:ident => $ty:ty),* $(,)?) => {$(27 // fn $method<E>(self, v: $ty) -> Result<Self::Value, E>28 // where29 // E: serde::de::Error,30 // {31 // Ok(Val::Num(f64::from(v)))32 // }33 // )*};34 // }3536 impl<'de> Visitor<'de> for ValVisitor {37 type Value = Val;3839 fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E>40 where41 E: de::Error,42 {43 Ok(Val::Bool(v))44 }45 fn visit_f64<E>(self, v: f64) -> Result<Self::Value, E>46 where47 E: de::Error,48 {49 Ok(Val::Num(NumValue::new(v).ok_or_else(|| {50 E::custom("only finite numbers are supported")51 })?))52 }53 fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>54 where55 E: de::Error,56 {57 Ok(Val::string(v))58 }5960 // visit_num! {61 // visit_i8 => i8,62 // visit_i16 => i16,63 // visit_i32 => i32,64 // visit_u8 => u8,65 // visit_u16 => u16,66 // visit_u32 => u32,67 // }68 fn visit_i64<E>(self, v: i64) -> Result<Self::Value, E>69 where70 E: de::Error,71 {72 Ok(Val::Num(NumValue::new(v as f64).expect("no overflow")))73 }74 fn visit_u64<E>(self, v: u64) -> Result<Self::Value, E>75 where76 E: de::Error,77 {78 Ok(Val::Num(NumValue::new(v as f64).expect("no overflow")))79 }8081 fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>82 where83 E: de::Error,84 {85 Ok(Val::Arr(ArrValue::bytes(v.into())))86 }8788 fn visit_none<E>(self) -> Result<Self::Value, E>89 where90 E: de::Error,91 {92 Ok(Val::Null)93 }94 fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error>95 where96 D: serde::Deserializer<'de>,97 {98 deserializer.deserialize_any(self)99 }100101 fn visit_unit<E>(self) -> Result<Self::Value, E>102 where103 E: de::Error,104 {105 Ok(Val::Null)106 }107108 fn visit_newtype_struct<D>(self, deserializer: D) -> Result<Self::Value, D::Error>109 where110 D: serde::Deserializer<'de>,111 {112 deserializer.deserialize_any(self)113 }114115 fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>116 where117 A: de::SeqAccess<'de>,118 {119 let mut out = seq.size_hint().map_or_else(Vec::new, Vec::with_capacity);120121 while let Some(val) = seq.next_element::<Val>()? {122 out.push(val);123 }124125 Ok(Val::Arr(ArrValue::eager(out)))126 }127128 fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>129 where130 A: de::MapAccess<'de>,131 {132 let mut out = map133 .size_hint()134 .map_or_else(ObjValueBuilder::new, ObjValueBuilder::with_capacity);135136 while let Some((k, v)) = map.next_entry::<Cow<'de, str>, Val>()? {137 // Jsonnet ignores duplicate keys138 out.field(k).value(v);139 }140141 Ok(Val::Obj(out.build()))142 }143144 fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {145 write!(formatter, "any valid jsonnet value")146 }147 }148 deserializer.deserialize_any(ValVisitor)149 }150}151152impl Serialize for Val {153 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>154 where155 S: serde::Serializer,156 {157 match self {158 Self::Bool(v) => serializer.serialize_bool(*v),159 Self::Null => serializer.serialize_none(),160 Self::Str(s) => serializer.serialize_str(&s.clone().into_flat()),161 Self::Num(n) => {162 let n = n.get();163 if n.fract() == 0.0 {164 let n = n as i64;165 serializer.serialize_i64(n)166 } else {167 serializer.serialize_f64(n)168 }169 }170 #[cfg(feature = "exp-bigint")]171 Self::BigInt(b) => b.serialize(serializer),172 Self::Arr(arr) => {173 let mut seq = serializer.serialize_seq(Some(arr.len()))?;174 for (i, element) in arr.iter().enumerate() {175 let mut serde_error = None;176 // TODO: rewrite using try{} after stabilization177 State::push_description(178 || format!("array index [{i}]"),179 || {180 let e = element?;181 if let Err(e) = seq.serialize_element(&e) {182 serde_error = Some(e);183 }184 Ok(())185 },186 )187 .map_err(|e| S::Error::custom(e.to_string()))?;188 if let Some(e) = serde_error {189 return Err(e);190 }191 }192 seq.end()193 }194 Self::Obj(obj) => {195 let mut map = serializer.serialize_map(Some(obj.len()))?;196 for (field, value) in obj.iter(197 #[cfg(feature = "exp-preserve-order")]198 true,199 ) {200 let mut serde_error = None;201 // TODO: rewrite using try{} after stabilization202 State::push_description(203 || format!("object field {field:?}"),204 || {205 let v = value?;206 if let Err(e) = map.serialize_entry(field.as_str(), &v) {207 serde_error = Some(e);208 }209 Ok(())210 },211 )212 .map_err(|e| S::Error::custom(e.to_string()))?;213 if let Some(e) = serde_error {214 return Err(e);215 }216 }217 map.end()218 }219 Self::Func(_) => Err(S::Error::custom("tried to manifest function")),220 }221 }222}223224struct IntoVecValSerializer {225 variant: Option<IStr>,226 data: Vec<Val>,227}228impl IntoVecValSerializer {229 fn new() -> Self {230 Self {231 variant: None,232 data: Vec::new(),233 }234 }235 fn with_capacity(capacity: usize) -> Self {236 Self {237 variant: None,238 data: Vec::with_capacity(capacity),239 }240 }241 fn variant_with_capacity(variant: impl Into<IStr>, capacity: usize) -> Self {242 Self {243 variant: Some(variant.into()),244 data: Vec::with_capacity(capacity),245 }246 }247}248impl SerializeSeq for IntoVecValSerializer {249 type Ok = Val;250 type Error = JrError;251252 fn serialize_element<T>(&mut self, value: &T) -> Result<()>253 where254 T: ?Sized + Serialize,255 {256 let value = value.serialize(IntoValSerializer)?;257 self.data.push(value);258 Ok(())259 }260261 fn end(self) -> Result<Val> {262 let inner = Val::Arr(ArrValue::eager(self.data));263 if let Some(variant) = self.variant {264 let mut out = ObjValue::builder_with_capacity(1);265 out.field(variant).value(inner);266 Ok(Val::Obj(out.build()))267 } else {268 Ok(inner)269 }270 }271}272impl SerializeTuple for IntoVecValSerializer {273 type Ok = Val;274 type Error = JrError;275276 fn serialize_element<T>(&mut self, value: &T) -> Result<()>277 where278 T: ?Sized + Serialize,279 {280 SerializeSeq::serialize_element(self, value)281 }282283 fn end(self) -> Result<Val> {284 SerializeSeq::end(self)285 }286}287impl SerializeTupleVariant for IntoVecValSerializer {288 type Ok = Val;289 type Error = JrError;290291 fn serialize_field<T>(&mut self, value: &T) -> Result<()>292 where293 T: ?Sized + Serialize,294 {295 SerializeSeq::serialize_element(self, value)296 }297298 fn end(self) -> Result<Val> {299 SerializeSeq::end(self)300 }301}302impl SerializeTupleStruct for IntoVecValSerializer {303 type Ok = Val;304 type Error = JrError;305306 fn serialize_field<T>(&mut self, value: &T) -> Result<()>307 where308 T: ?Sized + Serialize,309 {310 SerializeSeq::serialize_element(self, value)311 }312313 fn end(self) -> Result<Val> {314 SerializeSeq::end(self)315 }316}317318struct IntoObjValueSerializer {319 variant: Option<IStr>,320 data: ObjValueBuilder,321 key: Option<IStr>,322}323impl IntoObjValueSerializer {324 fn new() -> Self {325 Self {326 variant: None,327 data: ObjValue::builder(),328 key: None,329 }330 }331 fn with_capacity(capacity: usize) -> Self {332 Self {333 variant: None,334 data: ObjValue::builder_with_capacity(capacity),335 key: None,336 }337 }338 fn variant_with_capacity(variant: impl Into<IStr>, capacity: usize) -> Self {339 Self {340 variant: Some(variant.into()),341 data: ObjValue::builder_with_capacity(capacity),342 key: None,343 }344 }345}346impl SerializeMap for IntoObjValueSerializer {347 type Ok = Val;348 type Error = JrError;349350 fn serialize_key<T>(&mut self, key: &T) -> Result<()>351 where352 T: ?Sized + Serialize,353 {354 let key = key.serialize(IntoValSerializer)?;355 let key = key.to_string()?;356 self.key = Some(key);357 Ok(())358 }359360 fn serialize_value<T>(&mut self, value: &T) -> Result<()>361 where362 T: ?Sized + Serialize,363 {364 let key = self.key.take().expect("no serialize_key called");365 let value = value.serialize(IntoValSerializer)?;366 self.data.field(key).try_value(value)?;367 Ok(())368 }369370 // TODO: serialize_key/serialize_value371 fn serialize_entry<K, V>(&mut self, key: &K, value: &V) -> Result<()>372 where373 K: ?Sized + Serialize,374 V: ?Sized + Serialize,375 {376 let key = key.serialize(IntoValSerializer)?;377 let key = key.to_string()?;378 let value = value.serialize(IntoValSerializer)?;379 self.data.field(key).try_value(value)?;380 Ok(())381 }382383 fn end(self) -> Result<Val> {384 let inner = Val::Obj(self.data.build());385 if let Some(variant) = self.variant {386 let mut out = ObjValue::builder_with_capacity(1);387 out.field(variant).value(inner);388 Ok(Val::Obj(out.build()))389 } else {390 Ok(inner)391 }392 }393}394impl SerializeStruct for IntoObjValueSerializer {395 type Ok = Val;396 type Error = JrError;397398 fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<()>399 where400 T: ?Sized + Serialize,401 {402 SerializeMap::serialize_entry(self, key, value)?;403 Ok(())404 }405406 fn end(self) -> Result<Val> {407 SerializeMap::end(self)408 }409}410impl SerializeStructVariant for IntoObjValueSerializer {411 type Ok = Val;412413 type Error = JrError;414415 fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<()>416 where417 T: ?Sized + Serialize,418 {419 SerializeMap::serialize_entry(self, key, value)?;420 Ok(())421 }422423 fn end(self) -> Result<Val> {424 SerializeMap::end(self)425 }426}427428struct IntoValSerializer;429impl Serializer for IntoValSerializer {430 type Ok = Val;431432 type Error = JrError;433434 type SerializeSeq = IntoVecValSerializer;435436 type SerializeTuple = IntoVecValSerializer;437438 type SerializeTupleStruct = IntoVecValSerializer;439440 type SerializeTupleVariant = IntoVecValSerializer;441442 type SerializeMap = IntoObjValueSerializer;443444 type SerializeStruct = IntoObjValueSerializer;445446 type SerializeStructVariant = IntoObjValueSerializer;447448 fn serialize_bool(self, v: bool) -> Result<Val> {449 Ok(Val::Bool(v))450 }451452 fn serialize_i8(self, v: i8) -> Result<Val> {453 Ok(Val::Num(v.into()))454 }455456 fn serialize_i16(self, v: i16) -> Result<Val> {457 Ok(Val::Num(v.into()))458 }459460 fn serialize_i32(self, v: i32) -> Result<Val> {461 Ok(Val::Num(v.into()))462 }463464 fn serialize_i64(self, v: i64) -> Result<Val> {465 Ok(Val::Str(v.to_string().into()))466 }467468 fn serialize_u8(self, v: u8) -> Result<Val> {469 Ok(Val::Num(v.into()))470 }471472 fn serialize_u16(self, v: u16) -> Result<Val> {473 Ok(Val::Num(v.into()))474 }475476 fn serialize_u32(self, v: u32) -> Result<Val> {477 Ok(Val::Num(v.into()))478 }479480 fn serialize_u64(self, v: u64) -> Result<Val> {481 Ok(Val::Str(v.to_string().into()))482 }483484 fn serialize_f32(self, v: f32) -> Result<Val> {485 Ok(Val::try_num(f64::from(v))?)486 }487488 fn serialize_f64(self, v: f64) -> Result<Val> {489 Ok(Val::try_num(v)?)490 }491492 fn serialize_char(self, v: char) -> Result<Val> {493 Ok(Val::Str(v.to_string().into()))494 }495496 fn serialize_str(self, v: &str) -> Result<Val> {497 Ok(Val::Str(v.into()))498 }499500 fn serialize_bytes(self, v: &[u8]) -> Result<Val> {501 Ok(Val::Arr(ArrValue::bytes(v.into())))502 }503504 fn serialize_none(self) -> Result<Val> {505 Ok(Val::Null)506 }507508 fn serialize_some<T>(self, value: &T) -> Result<Val>509 where510 T: ?Sized + Serialize,511 {512 value.serialize(self)513 }514515 fn serialize_unit(self) -> Result<Val> {516 Ok(Val::Null)517 }518519 fn serialize_unit_struct(self, _name: &'static str) -> Result<Val> {520 Ok(Val::Null)521 }522523 fn serialize_unit_variant(524 self,525 _name: &'static str,526 _variant_index: u32,527 variant: &'static str,528 ) -> Result<Val> {529 Ok(Val::Str(variant.into()))530 }531532 fn serialize_newtype_struct<T>(self, _name: &'static str, value: &T) -> Result<Val>533 where534 T: ?Sized + Serialize,535 {536 value.serialize(self)537 }538539 fn serialize_newtype_variant<T>(540 self,541 _name: &'static str,542 _variant_index: u32,543 variant: &'static str,544 value: &T,545 ) -> Result<Val>546 where547 T: ?Sized + Serialize,548 {549 let mut out = ObjValue::builder_with_capacity(1);550 let value = value.serialize(self)?;551 out.field(variant).value(value);552 Ok(Val::Obj(out.build()))553 }554555 fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, Self::Error> {556 Ok(len.map_or_else(557 IntoVecValSerializer::new,558 IntoVecValSerializer::with_capacity,559 ))560 }561562 fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple, Self::Error> {563 Ok(IntoVecValSerializer::with_capacity(len))564 }565566 fn serialize_tuple_struct(567 self,568 _name: &'static str,569 len: usize,570 ) -> Result<Self::SerializeTupleStruct, Self::Error> {571 Ok(IntoVecValSerializer::with_capacity(len))572 }573574 fn serialize_tuple_variant(575 self,576 _name: &'static str,577 _variant_index: u32,578 variant: &'static str,579 len: usize,580 ) -> Result<Self::SerializeTupleVariant, Self::Error> {581 Ok(IntoVecValSerializer::variant_with_capacity(variant, len))582 }583584 fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap, Self::Error> {585 Ok(len.map_or_else(586 IntoObjValueSerializer::new,587 IntoObjValueSerializer::with_capacity,588 ))589 }590591 fn serialize_struct(592 self,593 _name: &'static str,594 len: usize,595 ) -> Result<Self::SerializeStruct, Self::Error> {596 Ok(IntoObjValueSerializer::with_capacity(len))597 }598599 fn serialize_struct_variant(600 self,601 _name: &'static str,602 _variant_index: u32,603 variant: &'static str,604 len: usize,605 ) -> Result<Self::SerializeStructVariant, Self::Error> {606 Ok(IntoObjValueSerializer::variant_with_capacity(variant, len))607 }608}609610impl Val {611 pub fn from_serde(v: impl Serialize) -> Result<Self, JrError> {612 v.serialize(IntoValSerializer)613 }614}615616impl serde::ser::Error for JrError {617 fn custom<T>(msg: T) -> Self618 where619 T: std::fmt::Display,620 {621 runtime_error!("serde: {msg}")622 }623}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.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/manifest.rs
+++ b/crates/jrsonnet-evaluator/src/manifest.rs
@@ -1,6 +1,6 @@
use std::{borrow::Cow, fmt::Write, ptr};
-use crate::{bail, Result, ResultExt, State, Val};
+use crate::{bail, in_description_frame, Result, ResultExt, Val};
pub trait ManifestFormat {
fn manifest_buf(&self, val: Val, buf: &mut String) -> Result<()>;
@@ -242,7 +242,7 @@
Minify | ToString => {}
};
- State::push_description(
+ in_description_frame(
|| format!("elem <{i}> manifestification"),
|| manifest_json_ex_buf(&item, buf, cur_padding, options),
)?;
@@ -304,7 +304,7 @@
escape_string_json_buf(&key, buf);
buf.push_str(options.key_val_sep);
- State::push_description(
+ in_description_frame(
|| format!("field <{key}> manifestification"),
|| manifest_json_ex_buf(&value, buf, cur_padding, options),
)?;
@@ -412,7 +412,7 @@
for (i, v) in arr.iter().enumerate() {
let v = v.with_description(|| format!("elem <{i}> evaluation"))?;
out.push_str("---\n");
- State::push_description(
+ in_description_frame(
|| format!("elem <{i}> manifestification"),
|| self.inner.manifest_buf(v, out),
)?;
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),
)?;