difftreelog
refactor move state to global
in: master
9 files changed
bindings/jsonnet/src/lib.rsdiffbeforeafterboth--- a/bindings/jsonnet/src/lib.rs
+++ b/bindings/jsonnet/src/lib.rs
@@ -247,7 +247,7 @@
match vm
.state
.import(filename)
- .and_then(|val| apply_tla(vm.state.clone(), &vm.tla_args, val))
+ .and_then(|val| apply_tla(&vm.tla_args, val))
.and_then(|val| val.manifest(&vm.manifest_format))
{
Ok(v) => {
@@ -282,7 +282,7 @@
match vm
.state
.evaluate_snippet(filename.to_str().unwrap(), snippet.to_str().unwrap())
- .and_then(|val| apply_tla(vm.state.clone(), &vm.tla_args, val))
+ .and_then(|val| apply_tla(&vm.tla_args, val))
.and_then(|val| val.manifest(&vm.manifest_format))
{
Ok(v) => {
@@ -340,7 +340,7 @@
match vm
.state
.import(filename)
- .and_then(|val| apply_tla(vm.state.clone(), &vm.tla_args, val))
+ .and_then(|val| apply_tla(&vm.tla_args, val))
.and_then(|val| val_to_multi(val, &vm.manifest_format))
{
Ok(v) => {
@@ -369,7 +369,7 @@
match vm
.state
.evaluate_snippet(filename.to_str().unwrap(), snippet.to_str().unwrap())
- .and_then(|val| apply_tla(vm.state.clone(), &vm.tla_args, val))
+ .and_then(|val| apply_tla(&vm.tla_args, val))
.and_then(|val| val_to_multi(val, &vm.manifest_format))
{
Ok(v) => {
@@ -422,7 +422,7 @@
match vm
.state
.import(filename)
- .and_then(|val| apply_tla(vm.state.clone(), &vm.tla_args, val))
+ .and_then(|val| apply_tla(&vm.tla_args, val))
.and_then(|val| val_to_stream(val, &vm.manifest_format))
{
Ok(v) => {
@@ -451,7 +451,7 @@
match vm
.state
.evaluate_snippet(filename.to_str().unwrap(), snippet.to_str().unwrap())
- .and_then(|val| apply_tla(vm.state.clone(), &vm.tla_args, val))
+ .and_then(|val| apply_tla(&vm.tla_args, val))
.and_then(|val| val_to_stream(val, &vm.manifest_format))
{
Ok(v) => {
cmds/jrsonnet/src/main.rsdiffbeforeafterboth--- a/cmds/jrsonnet/src/main.rs
+++ b/cmds/jrsonnet/src/main.rs
@@ -173,6 +173,7 @@
let mut s = State::builder();
s.import_resolver(import_resolver).context_initializer(std);
let s = s.build();
+ let _s = s.enter();
let input = opts.input.input.ok_or(Error::MissingInputArgument)?;
let val = if opts.input.exec {
@@ -192,7 +193,7 @@
unused_mut,
clippy::redundant_clone,
)]
- let mut val = apply_tla(s.clone(), &tla, val)?;
+ let mut val = apply_tla(&tla, val)?;
#[cfg(feature = "exp-apply")]
for apply in opts.input.exp_apply {
crates/jrsonnet-evaluator/src/ctx.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/ctx.rs
+++ b/crates/jrsonnet-evaluator/src/ctx.rs
@@ -6,12 +6,11 @@
use crate::{
error::ErrorKind::*, gc::WithCapacityExt as _, map::LayeredHashMap, ObjValue, Pending, Result,
- State, Thunk, Val,
+ Thunk, Val,
};
#[derive(Trace)]
struct ContextInternals {
- state: Option<State>,
dollar: Option<ObjValue>,
sup: Option<ObjValue>,
this: Option<ObjValue>,
@@ -33,13 +32,6 @@
Pending::new()
}
- pub fn state(&self) -> &State {
- self.0
- .state
- .as_ref()
- .expect("used state from dummy context")
- }
-
pub fn dollar(&self) -> Option<&ObjValue> {
self.0.dollar.as_ref()
}
@@ -112,7 +104,6 @@
ctx.bindings.clone().extend(new_bindings)
};
Self(Cc::new(ContextInternals {
- state: ctx.state.clone(),
dollar,
sup,
this,
@@ -128,34 +119,22 @@
}
pub struct ContextBuilder {
- state: Option<State>,
bindings: FxHashMap<IStr, Thunk<Val>>,
extend: Option<Context>,
}
impl ContextBuilder {
- /// # Panics
- /// Panics aren't directly caused by this function, but if state from resulting context is used
- pub fn dangerous_empty_state() -> Self {
- Self {
- state: None,
- bindings: FxHashMap::new(),
- extend: None,
- }
+ pub fn new() -> Self {
+ Self::with_capacity(0)
}
- pub fn new(state: State) -> Self {
- Self::with_capacity(state, 0)
- }
- pub fn with_capacity(state: State, capacity: usize) -> Self {
+ pub fn with_capacity(capacity: usize) -> Self {
Self {
- state: Some(state),
bindings: FxHashMap::with_capacity(capacity),
extend: None,
}
}
pub fn extend(parent: Context) -> Self {
Self {
- state: parent.0.state.clone(),
bindings: FxHashMap::new(),
extend: Some(parent),
}
@@ -173,7 +152,6 @@
parent.extend(self.bindings, None, None, None)
} else {
Context(Cc::new(ContextInternals {
- state: self.state,
bindings: LayeredHashMap::new(self.bindings),
dollar: None,
sup: None,
crates/jrsonnet-evaluator/src/function/arglike.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/function/arglike.rs
+++ b/crates/jrsonnet-evaluator/src/function/arglike.rs
@@ -4,7 +4,7 @@
use jrsonnet_interner::IStr;
use jrsonnet_parser::{ArgsDesc, LocExpr, SourceFifo, SourcePath};
-use crate::{evaluate, typed::Typed, Context, Result, Thunk, Val};
+use crate::{evaluate, typed::Typed, with_state, Context, Result, Thunk, Val};
/// Marker for arguments, which can be evaluated with context set to None
pub trait OptionalContext {}
@@ -47,28 +47,59 @@
ImportStr(String),
InlineCode(String),
}
-impl ArgLike for TlaArg {
- fn evaluate_arg(&self, ctx: Context, _tailstrict: bool) -> Result<Thunk<Val>> {
+impl TlaArg {
+ pub fn evaluate_tailstrict(&self) -> Result<Val> {
match self {
+ Self::String(s) => Ok(Val::string(s.clone())),
+ Self::Val(val) => Ok(val.clone()),
+ Self::Lazy(lazy) => Ok(lazy.evaluate()?),
+ Self::Import(p) => with_state(|s| {
+ let resolved = s.resolve_from_default(&p.as_str())?;
+ s.import_resolved(resolved)
+ }),
+ Self::ImportStr(p) => with_state(|s| {
+ let resolved = s.resolve_from_default(&p.as_str())?;
+ s.import_resolved_str(resolved).map(Val::string)
+ }),
+ Self::InlineCode(p) => with_state(|s| {
+ let resolved =
+ SourcePath::new(SourceFifo("<inline code>".to_owned(), p.as_bytes().into()));
+ s.import_resolved(resolved)
+ }),
+ }
+ }
+ pub fn evaluate(&self) -> Result<Thunk<Val>> {
+ match self {
Self::String(s) => Ok(Thunk::evaluated(Val::string(s.clone()))),
Self::Val(val) => Ok(Thunk::evaluated(val.clone())),
Self::Lazy(lazy) => Ok(lazy.clone()),
- Self::Import(p) => {
- let resolved = ctx.state().resolve_from_default(&p.as_str())?;
- Ok(Thunk!(move || ctx.state().import_resolved(resolved)))
- }
- Self::ImportStr(p) => {
- let resolved = ctx.state().resolve_from_default(&p.as_str())?;
- Ok(Thunk!(move || ctx
- .state()
+ Self::Import(p) => with_state(|s| {
+ let resolved = s.resolve_from_default(&p.as_str())?;
+ Ok(Thunk!(move || s.import_resolved(resolved)))
+ }),
+ Self::ImportStr(p) => with_state(|s| {
+ let resolved = s.resolve_from_default(&p.as_str())?;
+ Ok(Thunk!(move || s
.import_resolved_str(resolved)
.map(Val::string)))
- }
- Self::InlineCode(p) => {
+ }),
+ Self::InlineCode(p) => with_state(|s| {
let resolved =
SourcePath::new(SourceFifo("<inline code>".to_owned(), p.as_bytes().into()));
- Ok(Thunk!(move || ctx.state().import_resolved(resolved)))
- }
+ Ok(Thunk!(move || s.import_resolved(resolved)))
+ }),
+ }
+ }
+}
+
+// TODO: Is this implementation really required, as there is no Context to use?
+// Maybe something a bit stricter is possible to add, especially with precompiled calls?
+impl ArgLike for TlaArg {
+ fn evaluate_arg(&self, _ctx: Context, tailstrict: bool) -> Result<Thunk<Val>> {
+ if tailstrict {
+ self.evaluate_tailstrict().map(Thunk::evaluated)
+ } else {
+ self.evaluate()
}
}
}
crates/jrsonnet-evaluator/src/function/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/function/mod.rs
+++ b/crates/jrsonnet-evaluator/src/function/mod.rs
@@ -207,7 +207,7 @@
tailstrict: bool,
) -> Result<Val> {
self.evaluate(
- ContextBuilder::dangerous_empty_state().build(),
+ ContextBuilder::new().build(),
CallLocation::native(),
args,
tailstrict,
crates/jrsonnet-evaluator/src/tla.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/tla.rs
+++ b/crates/jrsonnet-evaluator/src/tla.rs
@@ -1,21 +1,24 @@
use jrsonnet_interner::IStr;
use jrsonnet_parser::Source;
+use rustc_hash::FxHashMap;
use crate::{
- function::{ArgsLike, CallLocation},
- in_description_frame, Result, State, Val,
+ function::{CallLocation, TlaArg},
+ in_description_frame, with_state, Result, Val,
};
-pub fn apply_tla<A: ArgsLike>(s: State, args: &A, val: Val) -> Result<Val> {
+pub fn apply_tla(args: &FxHashMap<IStr, TlaArg>, val: Val) -> Result<Val> {
Ok(if let Val::Func(func) = val {
in_description_frame(
|| "during TLA call".to_owned(),
|| {
func.evaluate(
- s.create_default_context(Source::new_virtual(
- "<top-level-arg>".into(),
- IStr::empty(),
- )),
+ with_state(|s| {
+ s.create_default_context(Source::new_virtual(
+ "<top-level-arg>".into(),
+ IStr::empty(),
+ ))
+ }),
CallLocation::native(),
args,
false,
crates/jrsonnet-stdlib/src/lib.rsdiffbeforeafterboth1#![allow(clippy::similar_names)]23use std::{4 cell::{Ref, RefCell, RefMut},5 collections::HashMap,6 f64,7 rc::Rc,8};910pub use arrays::*;11pub use compat::*;12pub use encoding::*;13pub use hash::*;14use jrsonnet_evaluator::{15 error::Result,16 function::{CallLocation, FuncVal, TlaArg},17 trace::PathResolver,18 val::NumValue,19 ContextBuilder, IStr, ObjValue, ObjValueBuilder, Thunk, Val,20};21use jrsonnet_gcmodule::{Acyclic, Cc, Trace};22use jrsonnet_parser::Source;23pub use manifest::*;24pub use math::*;25pub use misc::*;26pub use objects::*;27pub use operator::*;28pub use parse::*;29pub use sets::*;30pub use sort::*;31pub use strings::*;32pub use types::*;3334#[cfg(feature = "exp-regex")]35pub use crate::regex::*;3637mod arrays;38mod compat;39mod encoding;40mod hash;41mod manifest;42mod math;43mod misc;44mod objects;45mod operator;46mod parse;47#[cfg(feature = "exp-regex")]48mod regex;49mod sets;50mod sort;51mod strings;52mod types;5354#[allow(clippy::too_many_lines)]55pub fn stdlib_uncached(settings: Cc<RefCell<Settings>>) -> ObjValue {56 let mut builder = ObjValueBuilder::new();5758 // FIXME: Use PHF59 for (name, builtin) in [60 // Types61 ("type", builtin_type::INST),62 ("isString", builtin_is_string::INST),63 ("isNumber", builtin_is_number::INST),64 ("isBoolean", builtin_is_boolean::INST),65 ("isObject", builtin_is_object::INST),66 ("isArray", builtin_is_array::INST),67 ("isFunction", builtin_is_function::INST),68 ("isNull", builtin_is_null::INST),69 // Arrays70 ("makeArray", builtin_make_array::INST),71 ("repeat", builtin_repeat::INST),72 ("slice", builtin_slice::INST),73 ("map", builtin_map::INST),74 ("mapWithIndex", builtin_map_with_index::INST),75 ("mapWithKey", builtin_map_with_key::INST),76 ("flatMap", builtin_flatmap::INST),77 ("filter", builtin_filter::INST),78 ("foldl", builtin_foldl::INST),79 ("foldr", builtin_foldr::INST),80 ("range", builtin_range::INST),81 ("join", builtin_join::INST),82 ("lines", builtin_lines::INST),83 ("resolvePath", builtin_resolve_path::INST),84 ("deepJoin", builtin_deep_join::INST),85 ("reverse", builtin_reverse::INST),86 ("any", builtin_any::INST),87 ("all", builtin_all::INST),88 ("member", builtin_member::INST),89 ("find", builtin_find::INST),90 ("contains", builtin_contains::INST),91 ("count", builtin_count::INST),92 ("avg", builtin_avg::INST),93 ("removeAt", builtin_remove_at::INST),94 ("remove", builtin_remove::INST),95 ("flattenArrays", builtin_flatten_arrays::INST),96 ("flattenDeepArray", builtin_flatten_deep_array::INST),97 ("prune", builtin_prune::INST),98 ("filterMap", builtin_filter_map::INST),99 // Math100 ("abs", builtin_abs::INST),101 ("sign", builtin_sign::INST),102 ("max", builtin_max::INST),103 ("min", builtin_min::INST),104 ("clamp", builtin_clamp::INST),105 ("sum", builtin_sum::INST),106 ("modulo", builtin_modulo::INST),107 ("floor", builtin_floor::INST),108 ("ceil", builtin_ceil::INST),109 ("log", builtin_log::INST),110 ("log2", builtin_log2::INST),111 ("log10", builtin_log10::INST),112 ("pow", builtin_pow::INST),113 ("sqrt", builtin_sqrt::INST),114 ("sin", builtin_sin::INST),115 ("cos", builtin_cos::INST),116 ("tan", builtin_tan::INST),117 ("asin", builtin_asin::INST),118 ("acos", builtin_acos::INST),119 ("atan", builtin_atan::INST),120 ("atan2", builtin_atan2::INST),121 ("exp", builtin_exp::INST),122 ("mantissa", builtin_mantissa::INST),123 ("exponent", builtin_exponent::INST),124 ("round", builtin_round::INST),125 ("isEven", builtin_is_even::INST),126 ("isOdd", builtin_is_odd::INST),127 ("isInteger", builtin_is_integer::INST),128 ("isDecimal", builtin_is_decimal::INST),129 ("deg2rad", builtin_deg2rad::INST),130 ("rad2deg", builtin_rad2deg::INST),131 ("hypot", builtin_hypot::INST),132 // Operator133 ("mod", builtin_mod::INST),134 ("primitiveEquals", builtin_primitive_equals::INST),135 ("equals", builtin_equals::INST),136 ("xor", builtin_xor::INST),137 ("xnor", builtin_xnor::INST),138 ("format", builtin_format::INST),139 // Sort140 ("sort", builtin_sort::INST),141 ("uniq", builtin_uniq::INST),142 ("set", builtin_set::INST),143 ("minArray", builtin_min_array::INST),144 ("maxArray", builtin_max_array::INST),145 // Hash146 ("md5", builtin_md5::INST),147 ("sha1", builtin_sha1::INST),148 ("sha256", builtin_sha256::INST),149 ("sha512", builtin_sha512::INST),150 ("sha3", builtin_sha3::INST),151 // Encoding152 ("encodeUTF8", builtin_encode_utf8::INST),153 ("decodeUTF8", builtin_decode_utf8::INST),154 ("base64", builtin_base64::INST),155 ("base64Decode", builtin_base64_decode::INST),156 ("base64DecodeBytes", builtin_base64_decode_bytes::INST),157 // Objects158 ("objectFieldsEx", builtin_object_fields_ex::INST),159 ("objectFields", builtin_object_fields::INST),160 ("objectFieldsAll", builtin_object_fields_all::INST),161 ("objectValues", builtin_object_values::INST),162 ("objectValuesAll", builtin_object_values_all::INST),163 ("objectKeysValues", builtin_object_keys_values::INST),164 ("objectKeysValuesAll", builtin_object_keys_values_all::INST),165 ("objectHasEx", builtin_object_has_ex::INST),166 ("objectHas", builtin_object_has::INST),167 ("objectHasAll", builtin_object_has_all::INST),168 ("objectRemoveKey", builtin_object_remove_key::INST),169 // Manifest170 ("escapeStringJson", builtin_escape_string_json::INST),171 ("escapeStringPython", builtin_escape_string_python::INST),172 ("escapeStringXML", builtin_escape_string_xml::INST),173 ("manifestJsonEx", builtin_manifest_json_ex::INST),174 ("manifestJson", builtin_manifest_json::INST),175 ("manifestJsonMinified", builtin_manifest_json_minified::INST),176 ("manifestYamlDoc", builtin_manifest_yaml_doc::INST),177 ("manifestYamlStream", builtin_manifest_yaml_stream::INST),178 ("manifestTomlEx", builtin_manifest_toml_ex::INST),179 ("manifestToml", builtin_manifest_toml::INST),180 ("toString", builtin_to_string::INST),181 ("manifestPython", builtin_manifest_python::INST),182 ("manifestPythonVars", builtin_manifest_python_vars::INST),183 ("manifestXmlJsonml", builtin_manifest_xml_jsonml::INST),184 ("manifestIni", builtin_manifest_ini::INST),185 // Parse186 ("parseJson", builtin_parse_json::INST),187 ("parseYaml", builtin_parse_yaml::INST),188 // Strings189 ("codepoint", builtin_codepoint::INST),190 ("substr", builtin_substr::INST),191 ("char", builtin_char::INST),192 ("strReplace", builtin_str_replace::INST),193 ("escapeStringBash", builtin_escape_string_bash::INST),194 ("escapeStringDollars", builtin_escape_string_dollars::INST),195 ("isEmpty", builtin_is_empty::INST),196 ("equalsIgnoreCase", builtin_equals_ignore_case::INST),197 ("splitLimit", builtin_splitlimit::INST),198 ("splitLimitR", builtin_splitlimitr::INST),199 ("split", builtin_split::INST),200 ("asciiUpper", builtin_ascii_upper::INST),201 ("asciiLower", builtin_ascii_lower::INST),202 ("findSubstr", builtin_find_substr::INST),203 ("parseInt", builtin_parse_int::INST),204 #[cfg(feature = "exp-bigint")]205 ("bigint", builtin_bigint::INST),206 ("parseOctal", builtin_parse_octal::INST),207 ("parseHex", builtin_parse_hex::INST),208 ("stringChars", builtin_string_chars::INST),209 ("lstripChars", builtin_lstrip_chars::INST),210 ("rstripChars", builtin_rstrip_chars::INST),211 ("stripChars", builtin_strip_chars::INST),212 ("trim", builtin_trim::INST),213 // Misc214 ("length", builtin_length::INST),215 ("get", builtin_get::INST),216 ("startsWith", builtin_starts_with::INST),217 ("endsWith", builtin_ends_with::INST),218 ("assertEqual", builtin_assert_equal::INST),219 ("mergePatch", builtin_merge_patch::INST),220 // Sets221 ("setMember", builtin_set_member::INST),222 ("setInter", builtin_set_inter::INST),223 ("setDiff", builtin_set_diff::INST),224 ("setUnion", builtin_set_union::INST),225 // Regex226 #[cfg(feature = "exp-regex")]227 ("regexQuoteMeta", builtin_regex_quote_meta::INST),228 // Compat229 ("__compare", builtin___compare::INST),230 ("__compare_array", builtin___compare_array::INST),231 ("__array_less", builtin___array_less::INST),232 ("__array_greater", builtin___array_greater::INST),233 ("__array_less_or_equal", builtin___array_less_or_equal::INST),234 (235 "__array_greater_or_equal",236 builtin___array_greater_or_equal::INST,237 ),238 ]239 .iter()240 .copied()241 {242 builder.method(name, builtin);243 }244245 builder.method(246 "extVar",247 builtin_ext_var {248 settings: settings.clone(),249 },250 );251 builder.method(252 "native",253 builtin_native {254 settings: settings.clone(),255 },256 );257 builder.method("trace", builtin_trace { settings });258 builder.method("id", FuncVal::Id);259260 builder.field("pi").hide().value(Val::Num(261 NumValue::new(f64::consts::PI).expect("pi is finite"),262 ));263264 #[cfg(feature = "exp-regex")]265 {266 // Regex267 let regex_cache = RegexCache::default();268 builder.method(269 "regexFullMatch",270 builtin_regex_full_match {271 cache: regex_cache.clone(),272 },273 );274 builder.method(275 "regexPartialMatch",276 builtin_regex_partial_match {277 cache: regex_cache.clone(),278 },279 );280 builder.method(281 "regexReplace",282 builtin_regex_replace {283 cache: regex_cache.clone(),284 },285 );286 builder.method(287 "regexGlobalReplace",288 builtin_regex_global_replace { cache: regex_cache },289 );290 };291292 builder.build()293}294295pub trait TracePrinter: Acyclic {296 fn print_trace(&self, loc: CallLocation, value: IStr);297}298299#[derive(Acyclic)]300pub struct StdTracePrinter {301 resolver: PathResolver,302}303impl StdTracePrinter {304 pub fn new(resolver: PathResolver) -> Self {305 Self { resolver }306 }307}308impl TracePrinter for StdTracePrinter {309 fn print_trace(&self, loc: CallLocation, value: IStr) {310 eprint!("TRACE:");311 if let Some(loc) = loc.0 {312 let locs = loc.0.map_source_locations(&[loc.1]);313 eprint!(314 " {}:{}",315 loc.0.source_path().path().map_or_else(316 || loc.0.source_path().to_string(),317 |p| self.resolver.resolve(p)318 ),319 locs[0].line320 );321 }322 eprintln!(" {value}");323 }324}325326#[derive(Clone, Trace)]327pub struct Settings {328 /// Used for `std.extVar`329 pub ext_vars: HashMap<IStr, TlaArg>,330 /// Used for `std.native`331 pub ext_natives: HashMap<IStr, FuncVal>,332 /// Used for `std.trace`333 pub trace_printer: Rc<dyn TracePrinter>,334 /// Used for `std.thisFile`335 pub path_resolver: PathResolver,336}337338fn extvar_source(name: &str, code: impl Into<IStr>) -> Source {339 let source_name = format!("<extvar:{name}>");340 Source::new_virtual(source_name.into(), code.into())341}342343#[derive(Trace, Clone)]344pub struct ContextInitializer {345 /// std without applied thisFile overlay346 stdlib_obj: ObjValue,347 settings: Cc<RefCell<Settings>>,348}349impl ContextInitializer {350 pub fn new(resolver: PathResolver) -> Self {351 let settings = Settings {352 ext_vars: HashMap::new(),353 ext_natives: HashMap::new(),354 trace_printer: Rc::new(StdTracePrinter::new(resolver.clone())),355 path_resolver: resolver,356 };357 let settings = Cc::new(RefCell::new(settings));358 let stdlib_obj = stdlib_uncached(settings.clone());359 Self {360 stdlib_obj,361 settings,362 }363 }364 pub fn settings(&self) -> Ref<'_, Settings> {365 self.settings.borrow()366 }367 pub fn settings_mut(&self) -> RefMut<'_, Settings> {368 self.settings.borrow_mut()369 }370 pub fn add_ext_var(&self, name: IStr, value: Val) {371 self.settings_mut()372 .ext_vars373 .insert(name, TlaArg::Val(value));374 }375 pub fn add_ext_str(&self, name: IStr, value: IStr) {376 self.settings_mut()377 .ext_vars378 .insert(name, TlaArg::String(value));379 }380 pub fn add_ext_code(&self, name: &str, code: impl AsRef<str>) -> Result<()> {381 // self.data_mut().volatile_files.insert(source_name, code);382 self.settings_mut()383 .ext_vars384 .insert(name.into(), TlaArg::InlineCode(code.as_ref().to_owned()));385 Ok(())386 }387 pub fn add_native(&self, name: impl Into<IStr>, cb: impl Into<FuncVal>) {388 self.settings_mut()389 .ext_natives390 .insert(name.into(), cb.into());391 }392}393impl jrsonnet_evaluator::ContextInitializer for ContextInitializer {394 fn reserve_vars(&self) -> usize {395 1396 }397 fn populate(&self, source: Source, builder: &mut ContextBuilder) {398 let mut std = ObjValueBuilder::new();399 std.with_super(self.stdlib_obj.clone());400 std.field("thisFile").hide().value({401 let source_path = source.source_path();402 source_path.path().map_or_else(403 || source_path.to_string(),404 |p| self.settings().path_resolver.resolve(p),405 )406 });407 let stdlib_with_this_file = std.build();408409 builder.bind("std", Thunk::evaluated(Val::Obj(stdlib_with_this_file)));410 }411 fn as_any(&self) -> &dyn std::any::Any {412 self413 }414}crates/jrsonnet-stdlib/src/misc.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/misc.rs
+++ b/crates/jrsonnet-stdlib/src/misc.rs
@@ -3,15 +3,15 @@
use jrsonnet_evaluator::{
bail,
error::{ErrorKind::*, Result},
- function::{builtin, ArgLike, CallLocation, FuncVal},
+ function::{builtin, CallLocation, FuncVal},
manifest::JsonFormat,
typed::{Either2, Either4},
val::{equals, ArrValue},
- Context, Either, IStr, ObjValue, ObjValueBuilder, ResultExt, Thunk, Val,
+ Either, IStr, ObjValue, ObjValueBuilder, ResultExt, Thunk, Val,
};
use jrsonnet_gcmodule::Cc;
-use crate::{extvar_source, Settings};
+use crate::Settings;
#[builtin]
pub fn builtin_length(x: Either![IStr, ArrValue, ObjValue, FuncVal]) -> usize {
@@ -50,16 +50,14 @@
#[builtin(fields(
settings: Cc<RefCell<Settings>>,
))]
-pub fn builtin_ext_var(this: &builtin_ext_var, ctx: Context, x: IStr) -> Result<Val> {
- let ctx = ctx.state().create_default_context(extvar_source(&x, ""));
+pub fn builtin_ext_var(this: &builtin_ext_var, x: IStr) -> Result<Val> {
this.settings
.borrow()
.ext_vars
.get(&x)
.cloned()
.ok_or_else(|| UndefinedExternalVariable(x))?
- .evaluate_arg(ctx, true)?
- .evaluate()
+ .evaluate_tailstrict()
}
#[builtin(fields(
tests/tests/builtin.rsdiffbeforeafterboth--- a/tests/tests/builtin.rs
+++ b/tests/tests/builtin.rs
@@ -19,7 +19,7 @@
fn basic_function() -> Result<()> {
let a: a = a {};
let v = u32::from_untyped(a.call(
- ContextBuilder::dangerous_empty_state().build(),
+ ContextBuilder::new().build(),
CallLocation::native(),
&(),
)?)?;