difftreelog
refactor move push_frame out of State struct
in: master
14 files changed
crates/jrsonnet-evaluator/src/evaluate/mod.rsdiffbeforeafterboth16 error::{suggest_object_fields, ErrorKind::*},16 error::{suggest_object_fields, ErrorKind::*},17 evaluate::operator::{evaluate_add_op, evaluate_binary_op_special, evaluate_unary_op},17 evaluate::operator::{evaluate_add_op, evaluate_binary_op_special, evaluate_unary_op},18 function::{CallLocation, FuncDesc, FuncVal},18 function::{CallLocation, FuncDesc, FuncVal},19 in_frame,19 typed::Typed,20 typed::Typed,20 val::{CachedUnbound, IndexableVal, NumValue, StrValue, Thunk, ThunkValue},21 val::{CachedUnbound, IndexableVal, NumValue, StrValue, Thunk, ThunkValue},21 Context, Error, GcHashMap, ObjValue, ObjValueBuilder, ObjectAssertion, Pending, Result,22 Context, Error, GcHashMap, ObjValue, ObjValueBuilder, ObjectAssertion, Pending, Result,22 ResultExt, State, Unbound, Val,23 ResultExt, Unbound, Val,23};24};24pub mod destructure;25pub mod destructure;25pub mod operator;26pub mod operator;71pub fn evaluate_field_name(ctx: Context, field_name: &FieldName) -> Result<Option<IStr>> {72pub fn evaluate_field_name(ctx: Context, field_name: &FieldName) -> Result<Option<IStr>> {72 Ok(match field_name {73 Ok(match field_name {73 FieldName::Fixed(n) => Some(n.clone()),74 FieldName::Fixed(n) => Some(n.clone()),74 FieldName::Dyn(expr) => State::push(75 FieldName::Dyn(expr) => in_frame(75 CallLocation::new(&expr.span()),76 CallLocation::new(&expr.span()),76 || "evaluating field name".to_string(),77 || "evaluating field name".to_string(),77 || {78 || {374 if tailstrict {375 if tailstrict {375 body()?376 body()?376 } else {377 } else {377 State::push(loc, || format!("function <{}> call", f.name()), body)?378 in_frame(loc, || format!("function <{}> call", f.name()), body)?378 }379 }379 }380 }380 v => bail!(OnlyFunctionsCanBeCalledGot(v.value_type())),381 v => bail!(OnlyFunctionsCanBeCalledGot(v.value_type())),384pub fn evaluate_assert(ctx: Context, assertion: &AssertStmt) -> Result<()> {385pub fn evaluate_assert(ctx: Context, assertion: &AssertStmt) -> Result<()> {385 let value = &assertion.0;386 let value = &assertion.0;386 let msg = &assertion.1;387 let msg = &assertion.1;387 let assertion_result = State::push(388 let assertion_result = in_frame(388 CallLocation::new(&value.span()),389 CallLocation::new(&value.span()),389 || "assertion condition".to_owned(),390 || "assertion condition".to_owned(),390 || bool::from_untyped(evaluate(ctx.clone(), value)?),391 || bool::from_untyped(evaluate(ctx.clone(), value)?),391 )?;392 )?;392 if !assertion_result {393 if !assertion_result {393 State::push(394 in_frame(394 CallLocation::new(&value.span()),395 CallLocation::new(&value.span()),395 || "assertion failure".to_owned(),396 || "assertion failure".to_owned(),396 || {397 || {457 }458 }458 BinaryOp(v1, o, v2) => evaluate_binary_op_special(ctx, v1, *o, v2)?,459 BinaryOp(v1, o, v2) => evaluate_binary_op_special(ctx, v1, *o, v2)?,459 UnaryOp(o, v) => evaluate_unary_op(*o, &evaluate(ctx, v)?)?,460 UnaryOp(o, v) => evaluate_unary_op(*o, &evaluate(ctx, v)?)?,460 Var(name) => State::push(461 Var(name) => in_frame(461 CallLocation::new(&loc),462 CallLocation::new(&loc),462 || format!("variable <{name}> access"),463 || format!("variable <{name}> access"),463 || ctx.binding(name.clone())?.evaluate(),464 || ctx.binding(name.clone())?.evaluate(),645 evaluate_assert(ctx.clone(), assert)?;646 evaluate_assert(ctx.clone(), assert)?;646 evaluate(ctx, returned)?647 evaluate(ctx, returned)?647 }648 }648 ErrorStmt(e) => State::push(649 ErrorStmt(e) => in_frame(649 CallLocation::new(&loc),650 CallLocation::new(&loc),650 || "error statement".to_owned(),651 || "error statement".to_owned(),651 || bail!(RuntimeError(evaluate(ctx, e)?.to_string()?,)),652 || bail!(RuntimeError(evaluate(ctx, e)?.to_string()?,)),655 cond_then,656 cond_then,656 cond_else,657 cond_else,657 } => {658 } => {658 if State::push(659 if in_frame(659 CallLocation::new(&loc),660 CallLocation::new(&loc),660 || "if condition".to_owned(),661 || "if condition".to_owned(),661 || bool::from_untyped(evaluate(ctx.clone(), &cond.0)?),662 || bool::from_untyped(evaluate(ctx.clone(), &cond.0)?),676 desc: &'static str,677 desc: &'static str,677 ) -> Result<Option<T>> {678 ) -> Result<Option<T>> {678 if let Some(value) = expr {679 if let Some(value) = expr {679 Ok(Some(State::push(680 Ok(Some(in_frame(680 loc,681 loc,681 || format!("slice {desc}"),682 || format!("slice {desc}"),682 || T::from_untyped(evaluate(ctx.clone(), value)?),683 || T::from_untyped(evaluate(ctx.clone(), value)?),703 let s = ctx.state();704 let s = ctx.state();704 let resolved_path = s.resolve_from(tmp.source_path(), path as &str)?;705 let resolved_path = s.resolve_from(tmp.source_path(), path as &str)?;705 match i {706 match i {706 Import(_) => State::push(707 Import(_) => in_frame(707 CallLocation::new(&loc),708 CallLocation::new(&loc),708 || format!("import {:?}", path.clone()),709 || format!("import {:?}", path.clone()),709 || s.import_resolved(resolved_path),710 || s.import_resolved(resolved_path),crates/jrsonnet-evaluator/src/import.rsdiffbeforeafterboth1use std::{1use std::{2 any::Any,2 any::Any,3 cell::RefCell,4 env::current_dir,3 env::current_dir,5 fs,4 fs,6 io::{ErrorKind, Read},5 io::{ErrorKind, Read},41 /// this cannot be resolved using associated type, as evaluator uses object instead of generic for [`ImportResolver`]40 /// this cannot be resolved using associated type, as evaluator uses object instead of generic for [`ImportResolver`]42 fn load_file_contents(&self, resolved: &SourcePath) -> Result<Vec<u8>>;41 fn load_file_contents(&self, resolved: &SourcePath) -> Result<Vec<u8>>;434244 /// For downcasts43 // For downcasts, will be removed after trait_upcasting_coercion44 // stabilization.45 fn as_any(&self) -> &dyn Any;45 fn as_any(&self) -> &dyn Any;46 fn as_any_mut(&mut self) -> &mut dyn Any;46}47}474848/// Dummy resolver, can't resolve/load any file49/// Dummy resolver, can't resolve/load any file56 fn as_any(&self) -> &dyn Any {57 fn as_any(&self) -> &dyn Any {57 self58 self58 }59 }60 fn as_any_mut(&mut self) -> &mut dyn Any {61 self62 }59}63}60#[allow(clippy::use_self)]64#[allow(clippy::use_self)]61impl Default for Box<dyn ImportResolver> {65impl Default for Box<dyn ImportResolver> {69pub struct FileImportResolver {73pub struct FileImportResolver {70 /// Library directories to search for file.74 /// Library directories to search for file.71 /// Referred to as `jpath` in original jsonnet implementation.75 /// Referred to as `jpath` in original jsonnet implementation.72 library_paths: RefCell<Vec<PathBuf>>,76 library_paths: Vec<PathBuf>,73}77}74impl FileImportResolver {78impl FileImportResolver {75 pub fn new(jpath: Vec<PathBuf>) -> Self {79 pub fn new(library_paths: Vec<PathBuf>) -> Self {76 Self {80 Self { library_paths }77 library_paths: RefCell::new(jpath),78 }79 }81 }80 /// Dynamically add new jpath, used by bindings82 /// Dynamically add new jpath, used by bindings81 pub fn add_jpath(&self, path: PathBuf) {83 pub fn add_jpath(&mut self, path: PathBuf) {82 self.library_paths.borrow_mut().push(path);84 self.library_paths.push(path);83 }85 }84}86}8587132 if let Some(direct) = check_path(&direct)? {134 if let Some(direct) = check_path(&direct)? {133 return Ok(direct);135 return Ok(direct);134 }136 }135 for library_path in self.library_paths.borrow().iter() {137 for library_path in &self.library_paths {136 let mut cloned = library_path.clone();138 let mut cloned = library_path.clone();137 cloned.push(path);139 cloned.push(path);138 if let Some(cloned) = check_path(&cloned)? {140 if let Some(cloned) = check_path(&cloned)? {165 Ok(out)167 Ok(out)166 }168 }169170 fn resolve_from_default(&self, path: &str) -> Result<SourcePath> {171 self.resolve_from(&SourcePath::default(), path)172 }167173168 fn as_any(&self) -> &dyn Any {174 fn as_any(&self) -> &dyn Any {169 self175 self170 }176 }171177172 fn resolve_from_default(&self, path: &str) -> Result<SourcePath> {178 fn as_any_mut(&mut self) -> &mut dyn Any {173 self.resolve_from(&SourcePath::default(), path)179 self174 }180 }175}181}176182crates/jrsonnet-evaluator/src/integrations/serde.rsdiffbeforeafterboth11};11};121213use crate::{13use crate::{14 arr::ArrValue, runtime_error, val::NumValue, Error as JrError, ObjValue, ObjValueBuilder,14 arr::ArrValue, in_description_frame, runtime_error, val::NumValue, Error as JrError, ObjValue,15 Result, State, Val,15 ObjValueBuilder, Result, Val,16};16};171718impl<'de> Deserialize<'de> for Val {18impl<'de> Deserialize<'de> for Val {173 let mut seq = serializer.serialize_seq(Some(arr.len()))?;173 let mut seq = serializer.serialize_seq(Some(arr.len()))?;174 for (i, element) in arr.iter().enumerate() {174 for (i, element) in arr.iter().enumerate() {175 let mut serde_error = None;175 let mut serde_error = None;176 // TODO: rewrite using try{} after stabilization177 State::push_description(176 in_description_frame(178 || format!("array index [{i}]"),177 || format!("array index [{i}]"),179 || {178 || {180 let e = element?;179 let e = element?;199 ) {198 ) {200 let mut serde_error = None;199 let mut serde_error = None;201 // TODO: rewrite using try{} after stabilization200 // TODO: rewrite using try{} after stabilization202 State::push_description(201 in_description_frame(203 || format!("object field {field:?}"),202 || format!("object field {field:?}"),204 || {203 || {205 let v = value?;204 let v = value?;crates/jrsonnet-evaluator/src/lib.rsdiffbeforeafterboth45#[doc(hidden)]45#[doc(hidden)]46pub use jrsonnet_macros;46pub use jrsonnet_macros;47pub use jrsonnet_parser as parser;47pub use jrsonnet_parser as parser;48use jrsonnet_parser::{LocExpr, ParserSettings, Source, SourcePath, Span};48use jrsonnet_parser::{LocExpr, ParserSettings, Source, SourcePath};49pub use obj::*;49pub use obj::*;50use stack::check_depth;50use stack::check_depth;51pub use tla::apply_tla;51pub use tla::apply_tla;378 builder.build()378 builder.build()379 }379 }380381 /// Executes code creating a new stack frame382 pub fn push<T>(383 e: CallLocation<'_>,384 frame_desc: impl FnOnce() -> String,385 f: impl FnOnce() -> Result<T>,386 ) -> Result<T> {387 let _guard = check_depth()?;388389 f().with_description_src(e, frame_desc)390 }391392 /// Executes code creating a new stack frame393 pub fn push_val(394 &self,395 e: &Span,396 frame_desc: impl FnOnce() -> String,397 f: impl FnOnce() -> Result<Val>,398 ) -> Result<Val> {399 let _guard = check_depth()?;400401 f().with_description_src(e, frame_desc)402 }403 /// Executes code creating a new stack frame404 pub fn push_description<T>(405 frame_desc: impl FnOnce() -> String,406 f: impl FnOnce() -> Result<T>,407 ) -> Result<T> {408 let _guard = check_depth()?;409410 f().with_description(frame_desc)411 }412}380}413381414/// Internals382/// Internals417 self.0.file_cache.borrow_mut()385 self.0.file_cache.borrow_mut()418 }386 }419}387}388/// Executes code creating a new stack frame, to be replaced with try{}389pub fn in_frame<T>(390 e: CallLocation<'_>,391 frame_desc: impl FnOnce() -> String,392 f: impl FnOnce() -> Result<T>,393) -> Result<T> {394 let _guard = check_depth()?;395396 f().with_description_src(e, frame_desc)397}398399/// Executes code creating a new stack frame, to be replaced with try{}400pub fn in_description_frame<T>(401 frame_desc: impl FnOnce() -> String,402 f: impl FnOnce() -> Result<T>,403) -> Result<T> {404 let _guard = check_depth()?;405406 f().with_description(frame_desc)407}420408421#[derive(Trace)]409#[derive(Trace)]422pub struct InitialUnderscore(pub Thunk<Val>);410pub struct InitialUnderscore(pub Thunk<Val>);crates/jrsonnet-evaluator/src/manifest.rsdiffbeforeafterboth1use std::{borrow::Cow, fmt::Write, ptr};1use std::{borrow::Cow, fmt::Write, ptr};223use crate::{bail, Result, ResultExt, State, Val};3use crate::{bail, in_description_frame, Result, ResultExt, Val};445pub trait ManifestFormat {5pub trait ManifestFormat {6 fn manifest_buf(&self, val: Val, buf: &mut String) -> Result<()>;6 fn manifest_buf(&self, val: Val, buf: &mut String) -> Result<()>;242 Minify | ToString => {}242 Minify | ToString => {}243 };243 };244244245 State::push_description(245 in_description_frame(246 || format!("elem <{i}> manifestification"),246 || format!("elem <{i}> manifestification"),247 || manifest_json_ex_buf(&item, buf, cur_padding, options),247 || manifest_json_ex_buf(&item, buf, cur_padding, options),248 )?;248 )?;304304305 escape_string_json_buf(&key, buf);305 escape_string_json_buf(&key, buf);306 buf.push_str(options.key_val_sep);306 buf.push_str(options.key_val_sep);307 State::push_description(307 in_description_frame(308 || format!("field <{key}> manifestification"),308 || format!("field <{key}> manifestification"),309 || manifest_json_ex_buf(&value, buf, cur_padding, options),309 || manifest_json_ex_buf(&value, buf, cur_padding, options),310 )?;310 )?;412 for (i, v) in arr.iter().enumerate() {412 for (i, v) in arr.iter().enumerate() {413 let v = v.with_description(|| format!("elem <{i}> evaluation"))?;413 let v = v.with_description(|| format!("elem <{i}> evaluation"))?;414 out.push_str("---\n");414 out.push_str("---\n");415 State::push_description(415 in_description_frame(416 || format!("elem <{i}> manifestification"),416 || format!("elem <{i}> manifestification"),417 || self.inner.manifest_buf(v, out),417 || self.inner.manifest_buf(v, out),418 )?;418 )?;crates/jrsonnet-evaluator/src/obj.rsdiffbeforeafterboth17 error::{suggest_object_fields, Error, ErrorKind::*},17 error::{suggest_object_fields, Error, ErrorKind::*},18 function::{CallLocation, FuncVal},18 function::{CallLocation, FuncVal},19 gc::{GcHashMap, GcHashSet, TraceBox},19 gc::{GcHashMap, GcHashSet, TraceBox},20 in_frame,20 operator::evaluate_add_op,21 operator::evaluate_add_op,21 tb,22 tb,22 val::{ArrValue, ThunkValue},23 val::{ArrValue, ThunkValue},23 MaybeUnbound, Result, State, Thunk, Unbound, Val,24 MaybeUnbound, Result, Thunk, Unbound, Val,24};25};252626#[cfg(not(feature = "exp-preserve-order"))]27#[cfg(not(feature = "exp-preserve-order"))]969 let location = member.location.clone();970 let location = member.location.clone();970 let old = receiver.0.map.insert(name.clone(), member);971 let old = receiver.0.map.insert(name.clone(), member);971 if old.is_some() {972 if old.is_some() {972 State::push(973 in_frame(973 CallLocation(location.as_ref()),974 CallLocation(location.as_ref()),974 || format!("field <{}> initializtion", name.clone()),975 || format!("field <{}> initializtion", name.clone()),975 || bail!(DuplicateFieldName(name.clone())),976 || bail!(DuplicateFieldName(name.clone())),crates/jrsonnet-evaluator/src/stdlib/mod.rsdiffbeforeafterboth334use format::{format_arr, format_obj};4use format::{format_arr, format_obj};556use crate::{function::CallLocation, Result, State, Val};6use crate::{function::CallLocation, in_frame, Result, Val};778pub mod format;8pub mod format;9910pub fn std_format(str: &str, vals: Val) -> Result<String> {10pub fn std_format(str: &str, vals: Val) -> Result<String> {11 State::push(11 in_frame(12 CallLocation::native(),12 CallLocation::native(),13 || format!("std.format of {str}"),13 || format!("std.format of {str}"),14 || {14 || {crates/jrsonnet-evaluator/src/tla.rsdiffbeforeafterboth334use crate::{4use crate::{5 function::{ArgsLike, CallLocation},5 function::{ArgsLike, CallLocation},6 Result, State, Val,6 in_description_frame, Result, State, Val,7};7};889pub fn apply_tla<A: ArgsLike>(s: State, args: &A, val: Val) -> Result<Val> {9pub fn apply_tla<A: ArgsLike>(s: State, args: &A, val: Val) -> Result<Val> {10 Ok(if let Val::Func(func) = val {10 Ok(if let Val::Func(func) = val {11 State::push_description(11 in_description_frame(12 || "during TLA call".to_owned(),12 || "during TLA call".to_owned(),13 || {13 || {14 func.evaluate(14 func.evaluate(crates/jrsonnet-evaluator/src/typed/mod.rsdiffbeforeafterboth889use crate::{9use crate::{10 error::{Error, ErrorKind, Result},10 error::{Error, ErrorKind, Result},11 State, Val,11 in_description_frame, Val,12};12};131314#[derive(Debug, Error, Clone, Trace)]14#[derive(Debug, Error, Clone, Trace)]89 path: impl Fn() -> ValuePathItem,89 path: impl Fn() -> ValuePathItem,90 item: impl Fn() -> Result<()>,90 item: impl Fn() -> Result<()>,91) -> Result<()> {91) -> Result<()> {92 State::push_description(error_reason, || match item() {92 in_description_frame(error_reason, || match item() {93 Ok(()) => Ok(()),93 Ok(()) => Ok(()),94 Err(mut e) => {94 Err(mut e) => {95 if let ErrorKind::TypeError(e) = &mut e.error_mut() {95 if let ErrorKind::TypeError(e) = &mut e.error_mut() {crates/jrsonnet-interner/src/lib.rsdiffbeforeafterboth235235236 use crate::{PoolMap, POOL};236 use crate::{PoolMap, POOL};237237238 /// Type-erased interned string pool238 pub enum PoolState {}239 pub enum PoolState {}239240240 /// Dump current interned string pool, to be restored by241 /// Dump current interned string pool, to be restored bycrates/jrsonnet-macros/src/lib.rsdiffbeforeafterboth290 cfg_attrs,290 cfg_attrs,291 } => {291 } => {292 let name = name.as_ref().map_or("<unnamed>", String::as_str);292 let name = name.as_ref().map_or("<unnamed>", String::as_str);293 let eval = quote! {jrsonnet_evaluator::State::push_description(293 let eval = quote! {jrsonnet_evaluator::in_description_frame(294 || format!("argument <{}> evaluation", #name),294 || format!("argument <{}> evaluation", #name),295 || <#ty>::from_untyped(value.evaluate()?),295 || <#ty>::from_untyped(value.evaluate()?),296 )?};296 )?};crates/jrsonnet-stdlib/src/manifest/toml.rsdiffbeforeafterboth1use std::borrow::Cow;1use std::borrow::Cow;223use jrsonnet_evaluator::{3use jrsonnet_evaluator::{4 bail,4 bail, in_description_frame,5 manifest::{escape_string_json_buf, ManifestFormat},5 manifest::{escape_string_json_buf, ManifestFormat},6 val::ArrValue,6 val::ArrValue,7 IStr, ObjValue, Result, ResultExt, State, Val,7 IStr, ObjValue, Result, ResultExt, Val,8};8};9910pub struct TomlFormat<'s> {10pub struct TomlFormat<'s> {124 buf.push_str(&options.padding);124 buf.push_str(&options.padding);125 }125 }126126127 State::push_description(127 in_description_frame(128 || format!("elem <{i}> manifestification"),128 || format!("elem <{i}> manifestification"),129 || manifest_value(&e, true, buf, "", options),129 || manifest_value(&e, true, buf, "", options),130 )?;130 )?;161161162 escape_key_toml_buf(&k, buf);162 escape_key_toml_buf(&k, buf);163 buf.push_str(" = ");163 buf.push_str(" = ");164 State::push_description(164 in_description_frame(165 || format!("field <{k}> manifestification"),165 || format!("field <{k}> manifestification"),166 || manifest_value(&v, true, buf, "", options),166 || manifest_value(&v, true, buf, "", options),167 )?;167 )?;crates/jrsonnet-stdlib/src/manifest/xml.rsdiffbeforeafterboth1use jrsonnet_evaluator::{1use jrsonnet_evaluator::{2 bail,2 bail, in_description_frame,3 manifest::{ManifestFormat, ToStringFormat},3 manifest::{ManifestFormat, ToStringFormat},4 typed::{ComplexValType, Either2, Typed, ValType},4 typed::{ComplexValType, Either2, Typed, ValType},5 val::ArrValue,5 val::ArrValue,6 Either, ObjValue, Result, ResultExt, State, Val,6 Either, ObjValue, Result, ResultExt, Val,7};7};889pub struct XmlJsonmlFormat {9pub struct XmlJsonmlFormat {70 Ok(Self::Tag {70 Ok(Self::Tag {71 tag,71 tag,72 attrs,72 attrs,73 children: State::push_description(73 children: in_description_frame(74 || "parsing children".to_owned(),74 || "parsing children".to_owned(),75 || {75 || {76 Typed::from_untyped(Val::Arr(arr.slice(76 Typed::from_untyped(Val::Arr(arr.slice(crates/jrsonnet-stdlib/src/manifest/yaml.rsdiffbeforeafterboth1use std::{borrow::Cow, fmt::Write};1use std::{borrow::Cow, fmt::Write};223use jrsonnet_evaluator::{3use jrsonnet_evaluator::{4 bail,4 bail, in_description_frame,5 manifest::{escape_string_json_buf, ManifestFormat},5 manifest::{escape_string_json_buf, ManifestFormat},6 Result, ResultExt, State, Val,6 Result, ResultExt, Val,7};7};889pub struct YamlFormat<'s> {9pub struct YamlFormat<'s> {178 if extra_padding {178 if extra_padding {179 cur_padding.push_str(&options.padding);179 cur_padding.push_str(&options.padding);180 }180 }181 State::push_description(181 in_description_frame(182 || format!("elem <{i}> manifestification"),182 || format!("elem <{i}> manifestification"),183 || manifest_yaml_ex_buf(&item, buf, cur_padding, options),183 || manifest_yaml_ex_buf(&item, buf, cur_padding, options),184 )?;184 )?;225 }225 }226 _ => buf.push(' '),226 _ => buf.push(' '),227 }227 }228 State::push_description(228 in_description_frame(229 || format!("field <{key}> manifestification"),229 || format!("field <{key}> manifestification"),230 || manifest_yaml_ex_buf(&value, buf, cur_padding, options),230 || manifest_yaml_ex_buf(&value, buf, cur_padding, options),231 )?;231 )?;