difftreelog
perf use weak objvalue as cache key
in: master
4 files changed
crates/jrsonnet-evaluator/Cargo.tomldiffbeforeafterboth--- a/crates/jrsonnet-evaluator/Cargo.toml
+++ b/crates/jrsonnet-evaluator/Cargo.toml
@@ -15,9 +15,6 @@
# Allows library authors to throw custom errors
anyhow-error = ["anyhow"]
-# Unlocks extra features, but works only on unstable
-unstable = []
-
[dependencies]
jrsonnet-interner = { path = "../jrsonnet-interner", version = "0.4.2" }
jrsonnet-parser = { path = "../jrsonnet-parser", version = "0.4.2" }
crates/jrsonnet-evaluator/src/ctx.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/ctx.rs
+++ b/crates/jrsonnet-evaluator/src/ctx.rs
@@ -133,10 +133,6 @@
}
Ok(self.extend(new, new_dollar, this, super_obj))
}
- #[cfg(feature = "unstable")]
- pub fn into_weak(self) -> WeakContext {
- WeakContext(Rc::downgrade(&self.0))
- }
}
impl Default for Context {
crates/jrsonnet-evaluator/src/lib.rsdiffbeforeafterboth1#![cfg_attr(feature = "unstable", feature(stmt_expr_attributes))]2#![warn(clippy::all, clippy::nursery)]3#![allow(4 macro_expanded_macro_exports_accessed_by_absolute_paths,5 clippy::ptr_arg6)]78// For jrsonnet-macros9extern crate self as jrsonnet_evaluator;1011mod builtin;12mod ctx;13mod dynamic;14pub mod error;15mod evaluate;16pub mod function;17mod import;18mod integrations;19mod map;20pub mod native;21mod obj;22pub mod trace;23pub mod typed;24mod val;2526pub use jrsonnet_parser as parser;2728pub use ctx::*;29pub use dynamic::*;30use error::{Error::*, LocError, Result, StackTraceElement};31pub use evaluate::*;32use function::{Builtin, TlaArg};33use gc::{GcHashMap, TraceBox};34use gcmodule::{Cc, Trace};35pub use import::*;36pub use jrsonnet_interner::IStr;37use jrsonnet_parser::*;38pub use obj::*;39use std::{40 cell::{Ref, RefCell, RefMut},41 collections::HashMap,42 fmt::Debug,43 path::{Path, PathBuf},44 rc::Rc,45};46use trace::{location_to_offset, offset_to_location, CodeLocation, CompactFormat, TraceFormat};47pub use val::*;48pub mod gc;4950pub trait Bindable: Trace + 'static {51 fn bind(&self, this: Option<ObjValue>, super_obj: Option<ObjValue>) -> Result<LazyVal>;52}5354#[derive(Clone, Trace)]55pub enum LazyBinding {56 Bindable(Cc<TraceBox<dyn Bindable>>),57 Bound(LazyVal),58}5960impl Debug for LazyBinding {61 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {62 write!(f, "LazyBinding")63 }64}65impl LazyBinding {66 pub fn evaluate(&self, this: Option<ObjValue>, super_obj: Option<ObjValue>) -> Result<LazyVal> {67 match self {68 Self::Bindable(v) => v.bind(this, super_obj),69 Self::Bound(v) => Ok(v.clone()),70 }71 }72}7374pub struct EvaluationSettings {75 /// Limits recursion by limiting the number of stack frames76 pub max_stack: usize,77 /// Limits amount of stack trace items preserved78 pub max_trace: usize,79 /// Used for s`td.extVar`80 pub ext_vars: HashMap<IStr, Val>,81 /// Used for ext.native82 pub ext_natives: HashMap<IStr, Cc<TraceBox<dyn Builtin>>>,83 /// TLA vars84 pub tla_vars: HashMap<IStr, TlaArg>,85 /// Global variables are inserted in default context86 pub globals: HashMap<IStr, Val>,87 /// Used to resolve file locations/contents88 pub import_resolver: Box<dyn ImportResolver>,89 /// Used in manifestification functions90 pub manifest_format: ManifestFormat,91 /// Used for bindings92 pub trace_format: Box<dyn TraceFormat>,93}94impl Default for EvaluationSettings {95 fn default() -> Self {96 Self {97 max_stack: 200,98 max_trace: 20,99 globals: Default::default(),100 ext_vars: Default::default(),101 ext_natives: Default::default(),102 tla_vars: Default::default(),103 import_resolver: Box::new(DummyImportResolver),104 manifest_format: ManifestFormat::Json(4),105 trace_format: Box::new(CompactFormat {106 padding: 4,107 resolver: trace::PathResolver::Absolute,108 }),109 }110 }111}112113#[derive(Default)]114struct EvaluationData {115 /// Used for stack overflow detection, stacktrace is populated on unwind116 stack_depth: usize,117 /// Updated every time stack entry is popt118 stack_generation: usize,119120 breakpoints: Breakpoints,121 /// Contains file source codes and evaluation results for imports and pretty-printed stacktraces122 files: HashMap<Rc<Path>, FileData>,123 str_files: HashMap<Rc<Path>, IStr>,124}125126pub struct FileData {127 source_code: IStr,128 parsed: LocExpr,129 evaluated: Option<Val>,130}131132#[allow(clippy::type_complexity)]133pub struct Breakpoint {134 loc: ExprLocation,135 collected: RefCell<HashMap<usize, (usize, Vec<Result<Val>>)>>,136}137#[derive(Default)]138struct Breakpoints(Vec<Rc<Breakpoint>>);139impl Breakpoints {140 fn insert(141 &self,142 stack_depth: usize,143 stack_generation: usize,144 loc: &ExprLocation,145 result: Result<Val>,146 ) -> Result<Val> {147 if self.0.is_empty() {148 return result;149 }150 for item in self.0.iter() {151 if item.loc.belongs_to(loc) {152 let mut collected = item.collected.borrow_mut();153 let (depth, vals) = collected.entry(stack_generation).or_default();154 if stack_depth > *depth {155 vals.clear();156 }157 vals.push(result.clone());158 }159 }160 result161 }162}163164#[derive(Default)]165pub struct EvaluationStateInternals {166 /// Internal state167 data: RefCell<EvaluationData>,168 /// Settings, safe to change at runtime169 settings: RefCell<EvaluationSettings>,170}171172thread_local! {173 /// Contains the state for a currently executed file.174 /// Global state is fine here.175 pub(crate) static EVAL_STATE: RefCell<Option<EvaluationState>> = RefCell::new(None)176}177pub(crate) fn with_state<T>(f: impl FnOnce(&EvaluationState) -> T) -> T {178 EVAL_STATE.with(|s| f(s.borrow().as_ref().unwrap()))179}180pub fn push_frame<T>(181 e: Option<&ExprLocation>,182 frame_desc: impl FnOnce() -> String,183 f: impl FnOnce() -> Result<T>,184) -> Result<T> {185 with_state(|s| s.push(e, frame_desc, f))186}187188#[allow(dead_code)]189pub fn push_val_frame(190 e: &ExprLocation,191 frame_desc: impl FnOnce() -> String,192 f: impl FnOnce() -> Result<Val>,193) -> Result<Val> {194 with_state(|s| s.push_val(e, frame_desc, f))195}196#[allow(dead_code)]197pub fn push_description_frame<T>(198 frame_desc: impl FnOnce() -> String,199 f: impl FnOnce() -> Result<T>,200) -> Result<T> {201 with_state(|s| s.push_description(frame_desc, f))202}203204/// Maintains stack trace and import resolution205#[derive(Default, Clone)]206pub struct EvaluationState(Rc<EvaluationStateInternals>);207208impl EvaluationState {209 /// Parses and adds file as loaded210 pub fn add_file(&self, path: Rc<Path>, source_code: IStr) -> Result<LocExpr> {211 let parsed = parse(212 &source_code,213 &ParserSettings {214 file_name: path.clone(),215 },216 )217 .map_err(|error| ImportSyntaxError {218 error: Box::new(error),219 path: path.to_owned(),220 source_code: source_code.clone(),221 })?;222 self.add_parsed_file(path, source_code, parsed.clone())?;223224 Ok(parsed)225 }226227 pub fn reset_evaluation_state(&self, name: &Path) {228 self.data_mut()229 .files230 .get_mut(name)231 .unwrap()232 .evaluated233 .take();234 }235236 /// Adds file by source code and parsed expr237 pub fn add_parsed_file(238 &self,239 name: Rc<Path>,240 source_code: IStr,241 parsed: LocExpr,242 ) -> Result<()> {243 self.data_mut().files.insert(244 name,245 FileData {246 source_code,247 parsed,248 evaluated: None,249 },250 );251252 Ok(())253 }254 pub fn get_source(&self, name: &Path) -> Option<IStr> {255 let ro_map = &self.data().files;256 ro_map.get(name).map(|value| value.source_code.clone())257 }258 pub fn map_source_locations(&self, file: &Path, locs: &[usize]) -> Vec<CodeLocation> {259 offset_to_location(&self.get_source(file).unwrap_or_else(|| "".into()), locs)260 }261 pub fn map_from_source_location(262 &self,263 file: &Path,264 line: usize,265 column: usize,266 ) -> Option<usize> {267 location_to_offset(&self.get_source(file).unwrap(), line, column)268 }269 pub fn import_file(&self, from: &Path, path: &Path) -> Result<Val> {270 let file_path = self.resolve_file(from, path)?;271 {272 let data = self.data();273 let files = &data.files;274 if files.contains_key(&file_path as &Path) {275 drop(data);276 return self.evaluate_loaded_file_raw(&file_path);277 }278 }279 let contents = self.load_file_contents(&file_path)?;280 self.add_file(file_path.clone(), contents)?;281 self.evaluate_loaded_file_raw(&file_path)282 }283 pub(crate) fn import_file_str(&self, from: &Path, path: &Path) -> Result<IStr> {284 let path = self.resolve_file(from, path)?;285 if !self.data().str_files.contains_key(&path) {286 let file_str = self.load_file_contents(&path)?;287 self.data_mut().str_files.insert(path.clone(), file_str);288 }289 Ok(self.data().str_files.get(&path).cloned().unwrap())290 }291292 fn evaluate_loaded_file_raw(&self, name: &Path) -> Result<Val> {293 let expr: LocExpr = {294 let ro_map = &self.data().files;295 let value = ro_map296 .get(name)297 .unwrap_or_else(|| panic!("file not added: {:?}", name));298 if let Some(ref evaluated) = value.evaluated {299 return Ok(evaluated.clone());300 }301 value.parsed.clone()302 };303 let value = evaluate(self.create_default_context(), &expr)?;304 {305 self.data_mut()306 .files307 .get_mut(name)308 .unwrap()309 .evaluated310 .replace(value.clone());311 }312 Ok(value)313 }314315 /// Adds standard library global variable (std) to this evaluator316 pub fn with_stdlib(&self) -> &Self {317 use jrsonnet_stdlib::STDLIB_STR;318 let std_path: Rc<Path> = PathBuf::from("std.jsonnet").into();319 self.run_in_state(|| {320 self.add_parsed_file(321 std_path.clone(),322 STDLIB_STR.to_owned().into(),323 builtin::get_parsed_stdlib(),324 )325 .unwrap();326 let val = self.evaluate_loaded_file_raw(&std_path).unwrap();327 self.settings_mut().globals.insert("std".into(), val);328 });329 self330 }331332 /// Creates context with all passed global variables333 pub fn create_default_context(&self) -> Context {334 let globals = &self.settings().globals;335 let mut new_bindings = GcHashMap::with_capacity(globals.len());336 for (name, value) in globals.iter() {337 new_bindings.insert(name.clone(), LazyVal::new_resolved(value.clone()));338 }339 Context::new().extend_bound(new_bindings)340 }341342 /// Executes code creating a new stack frame343 pub fn push<T>(344 &self,345 e: Option<&ExprLocation>,346 frame_desc: impl FnOnce() -> String,347 f: impl FnOnce() -> Result<T>,348 ) -> Result<T> {349 {350 let mut data = self.data_mut();351 let stack_depth = &mut data.stack_depth;352 if *stack_depth > self.max_stack() {353 // Error creation uses data, so i drop guard here354 drop(data);355 throw!(StackOverflow);356 } else {357 *stack_depth += 1;358 }359 }360 let result = f();361 {362 let mut data = self.data_mut();363 data.stack_depth -= 1;364 data.stack_generation += 1;365 }366 if let Err(mut err) = result {367 err.trace_mut().0.push(StackTraceElement {368 location: e.cloned(),369 desc: frame_desc(),370 });371 return Err(err);372 }373 result374 }375376 /// Executes code creating a new stack frame377 pub fn push_val(378 &self,379 e: &ExprLocation,380 frame_desc: impl FnOnce() -> String,381 f: impl FnOnce() -> Result<Val>,382 ) -> Result<Val> {383 {384 let mut data = self.data_mut();385 let stack_depth = &mut data.stack_depth;386 if *stack_depth > self.max_stack() {387 // Error creation uses data, so i drop guard here388 drop(data);389 throw!(StackOverflow);390 } else {391 *stack_depth += 1;392 }393 }394 let mut result = f();395 {396 let mut data = self.data_mut();397 data.stack_depth -= 1;398 data.stack_generation += 1;399 result = data400 .breakpoints401 .insert(data.stack_depth, data.stack_generation, e, result);402 }403 if let Err(mut err) = result {404 err.trace_mut().0.push(StackTraceElement {405 location: Some(e.clone()),406 desc: frame_desc(),407 });408 return Err(err);409 }410 result411 }412 /// Executes code creating a new stack frame413 pub fn push_description<T>(414 &self,415 frame_desc: impl FnOnce() -> String,416 f: impl FnOnce() -> Result<T>,417 ) -> Result<T> {418 {419 let mut data = self.data_mut();420 let stack_depth = &mut data.stack_depth;421 if *stack_depth > self.max_stack() {422 // Error creation uses data, so i drop guard here423 drop(data);424 throw!(StackOverflow);425 } else {426 *stack_depth += 1;427 }428 }429 let result = f();430 {431 let mut data = self.data_mut();432 data.stack_depth -= 1;433 data.stack_generation += 1;434 }435 if let Err(mut err) = result {436 err.trace_mut().0.push(StackTraceElement {437 location: None,438 desc: frame_desc(),439 });440 return Err(err);441 }442 result443 }444445 /// Runs passed function in state (required if function needs to modify stack trace)446 pub fn run_in_state<T>(&self, f: impl FnOnce() -> T) -> T {447 EVAL_STATE.with(|v| {448 let has_state = v.borrow().is_some();449 if !has_state {450 v.borrow_mut().replace(self.clone());451 }452 let result = f();453 if !has_state {454 v.borrow_mut().take();455 }456 result457 })458 }459 pub fn run_in_state_with_breakpoint(460 &self,461 bp: Rc<Breakpoint>,462 f: impl FnOnce() -> Result<()>,463 ) -> Result<()> {464 {465 let mut data = self.data_mut();466 data.breakpoints.0.push(bp);467 }468469 let result = self.run_in_state(f);470471 {472 let mut data = self.data_mut();473 data.breakpoints.0.pop();474 }475476 result477 }478479 pub fn stringify_err(&self, e: &LocError) -> String {480 let mut out = String::new();481 self.settings()482 .trace_format483 .write_trace(&mut out, self, e)484 .unwrap();485 out486 }487488 pub fn manifest(&self, val: Val) -> Result<IStr> {489 self.run_in_state(|| {490 push_description_frame(491 || "manifestification".to_string(),492 || val.manifest(&self.manifest_format()),493 )494 })495 }496 pub fn manifest_multi(&self, val: Val) -> Result<Vec<(IStr, IStr)>> {497 self.run_in_state(|| val.manifest_multi(&self.manifest_format()))498 }499 pub fn manifest_stream(&self, val: Val) -> Result<Vec<IStr>> {500 self.run_in_state(|| val.manifest_stream(&self.manifest_format()))501 }502503 /// If passed value is function then call with set TLA504 pub fn with_tla(&self, val: Val) -> Result<Val> {505 self.run_in_state(|| {506 Ok(match val {507 Val::Func(func) => push_description_frame(508 || "during TLA call".to_owned(),509 || {510 func.evaluate(511 self.create_default_context(),512 None,513 &self.settings().tla_vars,514 true,515 )516 },517 )?,518 v => v,519 })520 })521 }522}523524/// Internals525impl EvaluationState {526 fn data(&self) -> Ref<EvaluationData> {527 self.0.data.borrow()528 }529 fn data_mut(&self) -> RefMut<EvaluationData> {530 self.0.data.borrow_mut()531 }532 pub fn settings(&self) -> Ref<EvaluationSettings> {533 self.0.settings.borrow()534 }535 pub fn settings_mut(&self) -> RefMut<EvaluationSettings> {536 self.0.settings.borrow_mut()537 }538}539540/// Raw methods evaluate passed values but don't perform TLA execution541impl EvaluationState {542 pub fn evaluate_file_raw(&self, name: &Path) -> Result<Val> {543 self.run_in_state(|| self.import_file(&std::env::current_dir().expect("cwd"), name))544 }545 pub fn evaluate_file_raw_nocwd(&self, name: &Path) -> Result<Val> {546 self.run_in_state(|| self.import_file(&PathBuf::from("."), name))547 }548 /// Parses and evaluates the given snippet549 pub fn evaluate_snippet_raw(&self, source: Rc<Path>, code: IStr) -> Result<Val> {550 let parsed = parse(551 &code,552 &ParserSettings {553 file_name: source.clone(),554 },555 )556 .map_err(|e| ImportSyntaxError {557 path: source.clone(),558 source_code: code.clone(),559 error: Box::new(e),560 })?;561 self.add_parsed_file(source, code, parsed.clone())?;562 self.evaluate_expr_raw(parsed)563 }564 /// Evaluates the parsed expression565 pub fn evaluate_expr_raw(&self, code: LocExpr) -> Result<Val> {566 self.run_in_state(|| evaluate(self.create_default_context(), &code))567 }568}569570/// Settings utilities571impl EvaluationState {572 pub fn add_ext_var(&self, name: IStr, value: Val) {573 self.settings_mut().ext_vars.insert(name, value);574 }575 pub fn add_ext_str(&self, name: IStr, value: IStr) {576 self.add_ext_var(name, Val::Str(value));577 }578 pub fn add_ext_code(&self, name: IStr, code: IStr) -> Result<()> {579 let value =580 self.evaluate_snippet_raw(PathBuf::from(format!("ext_code {}", name)).into(), code)?;581 self.add_ext_var(name, value);582 Ok(())583 }584585 pub fn add_tla(&self, name: IStr, value: Val) {586 self.settings_mut()587 .tla_vars588 .insert(name, TlaArg::Val(value));589 }590 pub fn add_tla_str(&self, name: IStr, value: IStr) {591 self.settings_mut()592 .tla_vars593 .insert(name, TlaArg::String(value));594 }595 pub fn add_tla_code(&self, name: IStr, code: IStr) -> Result<()> {596 let parsed = self.add_file(PathBuf::from(format!("tla_code {}", name)).into(), code)?;597 self.settings_mut()598 .tla_vars599 .insert(name, TlaArg::Code(parsed));600 Ok(())601 }602603 pub fn resolve_file(&self, from: &Path, path: &Path) -> Result<Rc<Path>> {604 self.settings().import_resolver.resolve_file(from, path)605 }606 pub fn load_file_contents(&self, path: &Path) -> Result<IStr> {607 self.settings().import_resolver.load_file_contents(path)608 }609610 pub fn import_resolver(&self) -> Ref<dyn ImportResolver> {611 Ref::map(self.settings(), |s| &*s.import_resolver)612 }613 pub fn set_import_resolver(&self, resolver: Box<dyn ImportResolver>) {614 self.settings_mut().import_resolver = resolver;615 }616617 pub fn add_native(&self, name: IStr, cb: Cc<TraceBox<dyn Builtin>>) {618 self.settings_mut().ext_natives.insert(name, cb);619 }620621 pub fn manifest_format(&self) -> ManifestFormat {622 self.settings().manifest_format.clone()623 }624 pub fn set_manifest_format(&self, format: ManifestFormat) {625 self.settings_mut().manifest_format = format;626 }627628 pub fn trace_format(&self) -> Ref<dyn TraceFormat> {629 Ref::map(self.settings(), |s| &*s.trace_format)630 }631 pub fn set_trace_format(&self, format: Box<dyn TraceFormat>) {632 self.settings_mut().trace_format = format;633 }634635 pub fn max_trace(&self) -> usize {636 self.settings().max_trace637 }638 pub fn set_max_trace(&self, trace: usize) {639 self.settings_mut().max_trace = trace;640 }641642 pub fn max_stack(&self) -> usize {643 self.settings().max_stack644 }645 pub fn set_max_stack(&self, trace: usize) {646 self.settings_mut().max_stack = trace;647 }648}649650pub fn cc_ptr_eq<T>(a: &Cc<T>, b: &Cc<T>) -> bool {651 let a = a as &T;652 let b = b as &T;653 std::ptr::eq(a, b)654}655656#[cfg(test)]657pub mod tests {658 use super::Val;659 use crate::{660 error::Error::*, function::BuiltinParam, gc::TraceBox, native::NativeCallbackHandler,661 primitive_equals, EvaluationState,662 };663 use gcmodule::{Cc, Trace};664 use jrsonnet_interner::IStr;665 use jrsonnet_parser::*;666 use std::{667 path::{Path, PathBuf},668 rc::Rc,669 };670671 #[test]672 #[should_panic]673 fn eval_state_stacktrace() {674 let state = EvaluationState::default();675 state.run_in_state(|| {676 state677 .push(678 Some(&ExprLocation(PathBuf::from("test1.jsonnet").into(), 10, 20)),679 || "outer".to_owned(),680 || {681 state.push(682 Some(&ExprLocation(PathBuf::from("test2.jsonnet").into(), 30, 40)),683 || "inner".to_owned(),684 || Err(RuntimeError("".into()).into()),685 )?;686 Ok(Val::Null)687 },688 )689 .unwrap();690 });691 }692693 #[test]694 fn eval_state_standard() {695 let state = EvaluationState::default();696 state.with_stdlib();697 assert!(primitive_equals(698 &state699 .evaluate_snippet_raw(700 PathBuf::from("raw.jsonnet").into(),701 r#"std.assertEqual(std.base64("test"), "dGVzdA==")"#.into()702 )703 .unwrap(),704 &Val::Bool(true),705 )706 .unwrap());707 }708709 macro_rules! eval {710 ($str: expr) => {711 EvaluationState::default()712 .with_stdlib()713 .evaluate_snippet_raw(PathBuf::from("raw.jsonnet").into(), $str.into())714 .unwrap()715 };716 }717 macro_rules! eval_json {718 ($str: expr) => {{719 let evaluator = EvaluationState::default();720 evaluator.with_stdlib();721 evaluator.run_in_state(|| {722 evaluator723 .evaluate_snippet_raw(PathBuf::from("raw.jsonnet").into(), $str.into())724 .unwrap()725 .to_json(0)726 .unwrap()727 .replace("\n", "")728 })729 }};730 }731732 /// Asserts given code returns `true`733 macro_rules! assert_eval {734 ($str: expr) => {735 assert!(primitive_equals(&eval!($str), &Val::Bool(true)).unwrap())736 };737 }738739 /// Asserts given code returns `false`740 macro_rules! assert_eval_neg {741 ($str: expr) => {742 assert!(primitive_equals(&eval!($str), &Val::Bool(false)).unwrap())743 };744 }745 macro_rules! assert_json {746 ($str: expr, $out: expr) => {747 assert_eq!(eval_json!($str), $out.replace("\t", ""))748 };749 }750751 /// Sanity checking, before trusting to another tests752 #[test]753 fn equality_operator() {754 assert_eval!("2 == 2");755 assert_eval_neg!("2 != 2");756 assert_eval!("2 != 3");757 assert_eval_neg!("2 == 3");758 assert_eval!("'Hello' == 'Hello'");759 assert_eval_neg!("'Hello' != 'Hello'");760 assert_eval!("'Hello' != 'World'");761 assert_eval_neg!("'Hello' == 'World'");762 }763764 #[test]765 fn math_evaluation() {766 assert_eval!("2 + 2 * 2 == 6");767 assert_eval!("3 + (2 + 2 * 2) == 9");768 }769770 #[test]771 fn string_concat() {772 assert_eval!("'Hello' + 'World' == 'HelloWorld'");773 assert_eval!("'Hello' * 3 == 'HelloHelloHello'");774 assert_eval!("'Hello' + 'World' * 3 == 'HelloWorldWorldWorld'");775 }776777 #[test]778 fn faster_join() {779 assert_eval!("std.join([0,0], [[1,2],[3,4],[5,6]]) == [1,2,0,0,3,4,0,0,5,6]");780 assert_eval!("std.join(',', ['1','2','3','4']) == '1,2,3,4'");781 }782783 #[test]784 fn function_contexts() {785 assert_eval!(786 r#"787 local k = {788 t(name = self.h): [self.h, name],789 h: 3,790 };791 local f = {792 t: k.t(),793 h: 4,794 };795 f.t[0] == f.t[1]796 "#797 );798 }799800 #[test]801 fn local() {802 assert_eval!("local a = 2; local b = 3; a + b == 5");803 assert_eval!("local a = 1, b = a + 1; a + b == 3");804 assert_eval!("local a = 1; local a = 2; a == 2");805 }806807 #[test]808 fn object_lazyness() {809 assert_json!("local a = {a:error 'test'}; {}", r#"{}"#);810 }811812 #[test]813 fn object_inheritance() {814 assert_json!("{a: self.b} + {b:3}", r#"{"a": 3,"b": 3}"#);815 }816817 #[test]818 fn object_assertion_success() {819 eval!("{assert \"a\" in self} + {a:2}");820 }821822 #[test]823 fn object_assertion_error() {824 eval!("{assert \"a\" in self}");825 }826827 #[test]828 fn lazy_args() {829 eval!("local test(a) = 2; test(error '3')");830 }831832 #[test]833 #[should_panic]834 fn tailstrict_args() {835 eval!("local test(a) = 2; test(error '3') tailstrict");836 }837838 #[test]839 #[should_panic]840 fn no_binding_error() {841 eval!("a");842 }843844 #[test]845 fn test_object() {846 assert_json!("{a:2}", r#"{"a": 2}"#);847 assert_json!("{a:2+2}", r#"{"a": 4}"#);848 assert_json!("{a:2}+{b:2}", r#"{"a": 2,"b": 2}"#);849 assert_json!("{b:3}+{b:2}", r#"{"b": 2}"#);850 assert_json!("{b:3}+{b+:2}", r#"{"b": 5}"#);851 assert_json!("local test='a'; {[test]:2}", r#"{"a": 2}"#);852 assert_json!(853 r#"854 {855 name: "Alice",856 welcome: "Hello " + self.name + "!",857 }858 "#,859 r#"{"name": "Alice","welcome": "Hello Alice!"}"#860 );861 assert_json!(862 r#"863 {864 name: "Alice",865 welcome: "Hello " + self.name + "!",866 } + {867 name: "Bob"868 }869 "#,870 r#"{"name": "Bob","welcome": "Hello Bob!"}"#871 );872 }873874 #[test]875 fn functions() {876 assert_json!(r#"local a = function(b, c = 2) b + c; a(2)"#, "4");877 assert_json!(878 r#"local a = function(b, c = "Dear") b + c + d, d = "World"; a("Hello")"#,879 r#""HelloDearWorld""#880 );881 }882883 #[test]884 fn local_methods() {885 assert_json!(r#"local a(b, c = 2) = b + c; a(2)"#, "4");886 assert_json!(887 r#"local a(b, c = "Dear") = b + c + d, d = "World"; a("Hello")"#,888 r#""HelloDearWorld""#889 );890 }891892 #[test]893 fn object_locals() {894 assert_json!(r#"{local a = 3, b: a}"#, r#"{"b": 3}"#);895 assert_json!(r#"{local a = 3, local c = a, b: c}"#, r#"{"b": 3}"#);896 assert_json!(897 r#"{local a = function (b) {[b]:4}, test: a("test")}"#,898 r#"{"test": {"test": 4}}"#899 );900 }901902 #[test]903 fn object_comp() {904 assert_json!(905 r#"{local t = "a", ["h"+i+"_"+z]: if "h"+(i-1)+"_"+z in self then t+1 else 0+t for i in [1,2,3] for z in [2,3,4] if z != i}"#,906 "{\"h1_2\": \"0a\",\"h1_3\": \"0a\",\"h1_4\": \"0a\",\"h2_3\": \"a1\",\"h2_4\": \"a1\",\"h3_2\": \"0a\",\"h3_4\": \"a1\"}"907 )908 }909910 #[test]911 fn direct_self() {912 println!(913 "{:#?}",914 eval!(915 r#"916 {917 local me = self,918 a: 3,919 b(): me.a,920 }921 "#922 )923 );924 }925926 #[test]927 fn indirect_self() {928 // `self` assigned to `me` was lost when being929 // referenced from field930 eval!(931 r#"{932 local me = self,933 a: 3,934 b: me.a,935 }.b"#936 );937 }938939 // We can't trust other tests (And official jsonnet testsuite), if assert is not working correctly940 #[test]941 fn std_assert_ok() {942 eval!("std.assertEqual(4.5 << 2, 16)");943 }944945 #[test]946 #[should_panic]947 fn std_assert_failure() {948 eval!("std.assertEqual(4.5 << 2, 15)");949 }950951 #[test]952 fn string_is_string() {953 assert!(primitive_equals(954 &eval!("local arr = 'hello'; (!std.isArray(arr)) && (!std.isString(arr))"),955 &Val::Bool(false),956 )957 .unwrap());958 }959960 #[test]961 fn base64_works() {962 assert_json!(r#"std.base64("test")"#, r#""dGVzdA==""#);963 }964965 #[test]966 fn utf8_chars() {967 assert_json!(968 r#"local c="😎";{c:std.codepoint(c),l:std.length(c)}"#,969 r#"{"c": 128526,"l": 1}"#970 )971 }972973 #[test]974 fn json() {975 assert_json!(976 r#"std.manifestJsonEx({a:3, b:4, c:6},"")"#,977 r#""{\n\"a\": 3,\n\"b\": 4,\n\"c\": 6\n}""#978 );979 }980981 #[test]982 fn json_minified() {983 assert_json!(984 r#"std.manifestJsonMinified({a:3, b:4, c:6})"#,985 r#""{\"a\":3,\"b\":4,\"c\":6}""#986 );987 }988989 #[test]990 fn parse_json() {991 assert_json!(992 r#"std.parseJson('{"a": -1,"b": 1,"c": 3.141,"d": []}')"#,993 r#"{"a": -1,"b": 1,"c": 3.141,"d": []}"#994 );995 }996997 #[test]998 fn test() {999 assert_json!(1000 r#"[[a, b] for a in [1,2,3] for b in [4,5,6]]"#,1001 "[[1,4],[1,5],[1,6],[2,4],[2,5],[2,6],[3,4],[3,5],[3,6]]"1002 );1003 }10041005 #[test]1006 fn sjsonnet() {1007 eval!(1008 r#"1009 local x0 = {k: 1};1010 local x1 = {k: x0.k + x0.k};1011 local x2 = {k: x1.k + x1.k};1012 local x3 = {k: x2.k + x2.k};1013 local x4 = {k: x3.k + x3.k};1014 local x5 = {k: x4.k + x4.k};1015 local x6 = {k: x5.k + x5.k};1016 local x7 = {k: x6.k + x6.k};1017 local x8 = {k: x7.k + x7.k};1018 local x9 = {k: x8.k + x8.k};1019 local x10 = {k: x9.k + x9.k};1020 local x11 = {k: x10.k + x10.k};1021 local x12 = {k: x11.k + x11.k};1022 local x13 = {k: x12.k + x12.k};1023 local x14 = {k: x13.k + x13.k};1024 local x15 = {k: x14.k + x14.k};1025 local x16 = {k: x15.k + x15.k};1026 local x17 = {k: x16.k + x16.k};1027 local x18 = {k: x17.k + x17.k};1028 local x19 = {k: x18.k + x18.k};1029 local x20 = {k: x19.k + x19.k};1030 local x21 = {k: x20.k + x20.k};1031 x21.k1032 "#1033 );1034 }10351036 // This test is commented out by default, because of huge compilation slowdown1037 // #[bench]1038 // fn bench_codegen(b: &mut Bencher) {1039 // b.iter(|| {1040 // #[allow(clippy::all)]1041 // let stdlib = {1042 // use jrsonnet_parser::*;1043 // include!(concat!(env!("OUT_DIR"), "/stdlib.rs"))1044 // };1045 // stdlib1046 // })1047 // }10481049 /*1050 #[bench]1051 fn bench_serialize(b: &mut Bencher) {1052 b.iter(|| {1053 bincode::deserialize::<jrsonnet_parser::LocExpr>(include_bytes!(concat!(1054 env!("OUT_DIR"),1055 "/stdlib.bincode"1056 )))1057 .expect("deserialize stdlib")1058 })1059 }10601061 #[bench]1062 fn bench_parse(b: &mut Bencher) {1063 b.iter(|| {1064 jrsonnet_parser::parse(1065 jrsonnet_stdlib::STDLIB_STR,1066 &jrsonnet_parser::ParserSettings {1067 loc_data: true,1068 file_name: Rc::new(PathBuf::from("std.jsonnet")),1069 },1070 )1071 })1072 }1073 */10741075 #[test]1076 fn equality() {1077 println!(1078 "{:?}",1079 jrsonnet_parser::parse(1080 "{ x: 1, y: 2 } == { x: 1, y: 2 }",1081 &ParserSettings {1082 file_name: PathBuf::from("equality").into(),1083 }1084 )1085 );1086 assert_eval!("{ x: 1, y: 2 } == { x: 1, y: 2 }")1087 }10881089 #[test]1090 fn native_ext() -> crate::error::Result<()> {1091 use super::native::NativeCallback;1092 let evaluator = EvaluationState::default();10931094 evaluator.with_stdlib();10951096 #[derive(Trace)]1097 struct NativeAdd;1098 impl NativeCallbackHandler for NativeAdd {1099 fn call(&self, from: Option<Rc<Path>>, args: &[Val]) -> crate::error::Result<Val> {1100 assert_eq!(1101 &from.unwrap() as &Path,1102 &PathBuf::from("native_caller.jsonnet")1103 );1104 match (&args[0], &args[1]) {1105 (Val::Num(a), Val::Num(b)) => Ok(Val::Num(a + b)),1106 (_, _) => unreachable!(),1107 }1108 }1109 }1110 evaluator.settings_mut().ext_natives.insert(1111 "native_add".into(),1112 #[allow(deprecated)]1113 Cc::new(TraceBox(Box::new(NativeCallback::new(1114 vec![1115 BuiltinParam {1116 name: "a".into(),1117 has_default: false,1118 },1119 BuiltinParam {1120 name: "b".into(),1121 has_default: false,1122 },1123 ],1124 TraceBox(Box::new(NativeAdd)),1125 )))),1126 );1127 evaluator.evaluate_snippet_raw(1128 PathBuf::from("native_caller.jsonnet").into(),1129 "std.assertEqual(std.native(\"native_add\")(1, 2), 3)".into(),1130 )?;1131 Ok(())1132 }11331134 #[test]1135 fn constant_intrinsic() -> crate::error::Result<()> {1136 assert_eval!(1137 "local std2 = std; local std = std2 { primitiveEquals(a, b):: false }; 1 == 1"1138 );1139 Ok(())1140 }11411142 #[test]1143 fn standalone_super() -> crate::error::Result<()> {1144 assert_eval!(1145 r#"1146 local obj = {1147 a: 1,1148 b: 2,1149 c: 3,1150 };1151 local test = obj + {1152 fields: std.objectFields(super),1153 d: 5,1154 };1155 test.fields == ['a', 'b', 'c']1156 "#1157 );1158 Ok(())1159 }11601161 #[test]1162 fn comp_self() -> crate::error::Result<()> {1163 assert_eval!(1164 r#"1165 std.objectFields({1166 a:{1167 [name]: name for name in std.objectFields(self)1168 },1169 b: 2,1170 c: 3,1171 }.a) == ['a', 'b', 'c']1172 "#1173 );11741175 Ok(())1176 }11771178 struct TestImportResolver(IStr);1179 impl crate::import::ImportResolver for TestImportResolver {1180 fn resolve_file(&self, _: &Path, _: &Path) -> crate::error::Result<Rc<Path>> {1181 Ok(PathBuf::from("/test").into())1182 }11831184 fn load_file_contents(&self, _: &Path) -> crate::error::Result<IStr> {1185 Ok(self.0.clone())1186 }11871188 unsafe fn as_any(&self) -> &dyn std::any::Any {1189 panic!()1190 }1191 }11921193 #[test]1194 fn issue_23() {1195 let state = EvaluationState::default();1196 state.set_import_resolver(Box::new(TestImportResolver(r#"import "/test""#.into())));1197 let _ = state.evaluate_file_raw(&PathBuf::from("/test"));1198 }11991200 #[test]1201 fn issue_40() {1202 let state = EvaluationState::default();1203 state.with_stdlib();12041205 let error = state1206 .evaluate_snippet_raw(1207 PathBuf::from("issue40.jsonnet").into(),1208 r#"1209 local conf = {1210 n: ""1211 };12121213 local result = conf + {1214 assert std.isNumber(self.n): "is number"1215 };12161217 std.manifestJsonEx(result, "")1218 "#1219 .into(),1220 )1221 .unwrap_err();1222 assert_eq!(error.error().to_string(), "assert failed: is number");1223 }12241225 #[test]1226 fn test_ascii_upper_lower() {1227 assert_eval!(r#"std.assertEqual(std.asciiUpper("aBc😀"), "ABC😀")"#);1228 assert_eval!(r#"std.assertEqual(std.asciiLower("aBc😀"), "abc😀")"#);1229 }12301231 #[test]1232 fn test_member() {1233 assert_eval!(r#"!std.member("", "")"#);1234 assert_eval!(r#"std.member("abc", "a")"#);1235 assert_eval!(r#"!std.member("abc", "d")"#);1236 assert_eval!(r#"!std.member([], "")"#);1237 assert_eval!(r#"std.member(["a", "b", "c"], "a")"#);1238 assert_eval!(r#"!std.member(["a", "b", "c"], "d")"#);1239 }12401241 #[test]1242 fn test_count() {1243 assert_eval!(r#"std.assertEqual(std.count([], ""), 0)"#);1244 assert_eval!(r#"std.assertEqual(std.count(["a", "b", "a"], "d"), 0)"#);1245 assert_eval!(r#"std.assertEqual(std.count(["a", "b", "a"], "a"), 2)"#);1246 }1247}1#![warn(clippy::all, clippy::nursery)]2#![allow(3 macro_expanded_macro_exports_accessed_by_absolute_paths,4 clippy::ptr_arg5)]67// For jrsonnet-macros8extern crate self as jrsonnet_evaluator;910mod builtin;11mod ctx;12mod dynamic;13pub mod error;14mod evaluate;15pub mod function;16mod import;17mod integrations;18mod map;19pub mod native;20mod obj;21pub mod trace;22pub mod typed;23mod val;2425pub use jrsonnet_parser as parser;2627pub use ctx::*;28pub use dynamic::*;29use error::{Error::*, LocError, Result, StackTraceElement};30pub use evaluate::*;31use function::{Builtin, TlaArg};32use gc::{GcHashMap, TraceBox};33use gcmodule::{Cc, Trace, Weak};34pub use import::*;35pub use jrsonnet_interner::IStr;36use jrsonnet_parser::*;37pub use obj::*;38use std::{39 cell::{Ref, RefCell, RefMut},40 collections::HashMap,41 fmt::Debug,42 path::{Path, PathBuf},43 rc::Rc,44};45use trace::{location_to_offset, offset_to_location, CodeLocation, CompactFormat, TraceFormat};46pub use val::*;47pub mod gc;4849pub trait Bindable: Trace + 'static {50 fn bind(&self, this: Option<ObjValue>, super_obj: Option<ObjValue>) -> Result<LazyVal>;51}5253#[derive(Clone, Trace)]54pub enum LazyBinding {55 Bindable(Cc<TraceBox<dyn Bindable>>),56 Bound(LazyVal),57}5859impl Debug for LazyBinding {60 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {61 write!(f, "LazyBinding")62 }63}64impl LazyBinding {65 pub fn evaluate(&self, this: Option<ObjValue>, super_obj: Option<ObjValue>) -> Result<LazyVal> {66 match self {67 Self::Bindable(v) => v.bind(this, super_obj),68 Self::Bound(v) => Ok(v.clone()),69 }70 }71}7273pub struct EvaluationSettings {74 /// Limits recursion by limiting the number of stack frames75 pub max_stack: usize,76 /// Limits amount of stack trace items preserved77 pub max_trace: usize,78 /// Used for s`td.extVar`79 pub ext_vars: HashMap<IStr, Val>,80 /// Used for ext.native81 pub ext_natives: HashMap<IStr, Cc<TraceBox<dyn Builtin>>>,82 /// TLA vars83 pub tla_vars: HashMap<IStr, TlaArg>,84 /// Global variables are inserted in default context85 pub globals: HashMap<IStr, Val>,86 /// Used to resolve file locations/contents87 pub import_resolver: Box<dyn ImportResolver>,88 /// Used in manifestification functions89 pub manifest_format: ManifestFormat,90 /// Used for bindings91 pub trace_format: Box<dyn TraceFormat>,92}93impl Default for EvaluationSettings {94 fn default() -> Self {95 Self {96 max_stack: 200,97 max_trace: 20,98 globals: Default::default(),99 ext_vars: Default::default(),100 ext_natives: Default::default(),101 tla_vars: Default::default(),102 import_resolver: Box::new(DummyImportResolver),103 manifest_format: ManifestFormat::Json(4),104 trace_format: Box::new(CompactFormat {105 padding: 4,106 resolver: trace::PathResolver::Absolute,107 }),108 }109 }110}111112#[derive(Default)]113struct EvaluationData {114 /// Used for stack overflow detection, stacktrace is populated on unwind115 stack_depth: usize,116 /// Updated every time stack entry is popt117 stack_generation: usize,118119 breakpoints: Breakpoints,120 /// Contains file source codes and evaluation results for imports and pretty-printed stacktraces121 files: HashMap<Rc<Path>, FileData>,122 str_files: HashMap<Rc<Path>, IStr>,123}124125pub struct FileData {126 source_code: IStr,127 parsed: LocExpr,128 evaluated: Option<Val>,129}130131#[allow(clippy::type_complexity)]132pub struct Breakpoint {133 loc: ExprLocation,134 collected: RefCell<HashMap<usize, (usize, Vec<Result<Val>>)>>,135}136#[derive(Default)]137struct Breakpoints(Vec<Rc<Breakpoint>>);138impl Breakpoints {139 fn insert(140 &self,141 stack_depth: usize,142 stack_generation: usize,143 loc: &ExprLocation,144 result: Result<Val>,145 ) -> Result<Val> {146 if self.0.is_empty() {147 return result;148 }149 for item in self.0.iter() {150 if item.loc.belongs_to(loc) {151 let mut collected = item.collected.borrow_mut();152 let (depth, vals) = collected.entry(stack_generation).or_default();153 if stack_depth > *depth {154 vals.clear();155 }156 vals.push(result.clone());157 }158 }159 result160 }161}162163#[derive(Default)]164pub struct EvaluationStateInternals {165 /// Internal state166 data: RefCell<EvaluationData>,167 /// Settings, safe to change at runtime168 settings: RefCell<EvaluationSettings>,169}170171thread_local! {172 /// Contains the state for a currently executed file.173 /// Global state is fine here.174 pub(crate) static EVAL_STATE: RefCell<Option<EvaluationState>> = RefCell::new(None)175}176pub(crate) fn with_state<T>(f: impl FnOnce(&EvaluationState) -> T) -> T {177 EVAL_STATE.with(|s| f(s.borrow().as_ref().unwrap()))178}179pub fn push_frame<T>(180 e: Option<&ExprLocation>,181 frame_desc: impl FnOnce() -> String,182 f: impl FnOnce() -> Result<T>,183) -> Result<T> {184 with_state(|s| s.push(e, frame_desc, f))185}186187#[allow(dead_code)]188pub fn push_val_frame(189 e: &ExprLocation,190 frame_desc: impl FnOnce() -> String,191 f: impl FnOnce() -> Result<Val>,192) -> Result<Val> {193 with_state(|s| s.push_val(e, frame_desc, f))194}195#[allow(dead_code)]196pub fn push_description_frame<T>(197 frame_desc: impl FnOnce() -> String,198 f: impl FnOnce() -> Result<T>,199) -> Result<T> {200 with_state(|s| s.push_description(frame_desc, f))201}202203/// Maintains stack trace and import resolution204#[derive(Default, Clone)]205pub struct EvaluationState(Rc<EvaluationStateInternals>);206207impl EvaluationState {208 /// Parses and adds file as loaded209 pub fn add_file(&self, path: Rc<Path>, source_code: IStr) -> Result<LocExpr> {210 let parsed = parse(211 &source_code,212 &ParserSettings {213 file_name: path.clone(),214 },215 )216 .map_err(|error| ImportSyntaxError {217 error: Box::new(error),218 path: path.to_owned(),219 source_code: source_code.clone(),220 })?;221 self.add_parsed_file(path, source_code, parsed.clone())?;222223 Ok(parsed)224 }225226 pub fn reset_evaluation_state(&self, name: &Path) {227 self.data_mut()228 .files229 .get_mut(name)230 .unwrap()231 .evaluated232 .take();233 }234235 /// Adds file by source code and parsed expr236 pub fn add_parsed_file(237 &self,238 name: Rc<Path>,239 source_code: IStr,240 parsed: LocExpr,241 ) -> Result<()> {242 self.data_mut().files.insert(243 name,244 FileData {245 source_code,246 parsed,247 evaluated: None,248 },249 );250251 Ok(())252 }253 pub fn get_source(&self, name: &Path) -> Option<IStr> {254 let ro_map = &self.data().files;255 ro_map.get(name).map(|value| value.source_code.clone())256 }257 pub fn map_source_locations(&self, file: &Path, locs: &[usize]) -> Vec<CodeLocation> {258 offset_to_location(&self.get_source(file).unwrap_or_else(|| "".into()), locs)259 }260 pub fn map_from_source_location(261 &self,262 file: &Path,263 line: usize,264 column: usize,265 ) -> Option<usize> {266 location_to_offset(&self.get_source(file).unwrap(), line, column)267 }268 pub fn import_file(&self, from: &Path, path: &Path) -> Result<Val> {269 let file_path = self.resolve_file(from, path)?;270 {271 let data = self.data();272 let files = &data.files;273 if files.contains_key(&file_path as &Path) {274 drop(data);275 return self.evaluate_loaded_file_raw(&file_path);276 }277 }278 let contents = self.load_file_contents(&file_path)?;279 self.add_file(file_path.clone(), contents)?;280 self.evaluate_loaded_file_raw(&file_path)281 }282 pub(crate) fn import_file_str(&self, from: &Path, path: &Path) -> Result<IStr> {283 let path = self.resolve_file(from, path)?;284 if !self.data().str_files.contains_key(&path) {285 let file_str = self.load_file_contents(&path)?;286 self.data_mut().str_files.insert(path.clone(), file_str);287 }288 Ok(self.data().str_files.get(&path).cloned().unwrap())289 }290291 fn evaluate_loaded_file_raw(&self, name: &Path) -> Result<Val> {292 let expr: LocExpr = {293 let ro_map = &self.data().files;294 let value = ro_map295 .get(name)296 .unwrap_or_else(|| panic!("file not added: {:?}", name));297 if let Some(ref evaluated) = value.evaluated {298 return Ok(evaluated.clone());299 }300 value.parsed.clone()301 };302 let value = evaluate(self.create_default_context(), &expr)?;303 {304 self.data_mut()305 .files306 .get_mut(name)307 .unwrap()308 .evaluated309 .replace(value.clone());310 }311 Ok(value)312 }313314 /// Adds standard library global variable (std) to this evaluator315 pub fn with_stdlib(&self) -> &Self {316 use jrsonnet_stdlib::STDLIB_STR;317 let std_path: Rc<Path> = PathBuf::from("std.jsonnet").into();318 self.run_in_state(|| {319 self.add_parsed_file(320 std_path.clone(),321 STDLIB_STR.to_owned().into(),322 builtin::get_parsed_stdlib(),323 )324 .unwrap();325 let val = self.evaluate_loaded_file_raw(&std_path).unwrap();326 self.settings_mut().globals.insert("std".into(), val);327 });328 self329 }330331 /// Creates context with all passed global variables332 pub fn create_default_context(&self) -> Context {333 let globals = &self.settings().globals;334 let mut new_bindings = GcHashMap::with_capacity(globals.len());335 for (name, value) in globals.iter() {336 new_bindings.insert(name.clone(), LazyVal::new_resolved(value.clone()));337 }338 Context::new().extend_bound(new_bindings)339 }340341 /// Executes code creating a new stack frame342 pub fn push<T>(343 &self,344 e: Option<&ExprLocation>,345 frame_desc: impl FnOnce() -> String,346 f: impl FnOnce() -> Result<T>,347 ) -> Result<T> {348 {349 let mut data = self.data_mut();350 let stack_depth = &mut data.stack_depth;351 if *stack_depth > self.max_stack() {352 // Error creation uses data, so i drop guard here353 drop(data);354 throw!(StackOverflow);355 } else {356 *stack_depth += 1;357 }358 }359 let result = f();360 {361 let mut data = self.data_mut();362 data.stack_depth -= 1;363 data.stack_generation += 1;364 }365 if let Err(mut err) = result {366 err.trace_mut().0.push(StackTraceElement {367 location: e.cloned(),368 desc: frame_desc(),369 });370 return Err(err);371 }372 result373 }374375 /// Executes code creating a new stack frame376 pub fn push_val(377 &self,378 e: &ExprLocation,379 frame_desc: impl FnOnce() -> String,380 f: impl FnOnce() -> Result<Val>,381 ) -> Result<Val> {382 {383 let mut data = self.data_mut();384 let stack_depth = &mut data.stack_depth;385 if *stack_depth > self.max_stack() {386 // Error creation uses data, so i drop guard here387 drop(data);388 throw!(StackOverflow);389 } else {390 *stack_depth += 1;391 }392 }393 let mut result = f();394 {395 let mut data = self.data_mut();396 data.stack_depth -= 1;397 data.stack_generation += 1;398 result = data399 .breakpoints400 .insert(data.stack_depth, data.stack_generation, e, result);401 }402 if let Err(mut err) = result {403 err.trace_mut().0.push(StackTraceElement {404 location: Some(e.clone()),405 desc: frame_desc(),406 });407 return Err(err);408 }409 result410 }411 /// Executes code creating a new stack frame412 pub fn push_description<T>(413 &self,414 frame_desc: impl FnOnce() -> String,415 f: impl FnOnce() -> Result<T>,416 ) -> Result<T> {417 {418 let mut data = self.data_mut();419 let stack_depth = &mut data.stack_depth;420 if *stack_depth > self.max_stack() {421 // Error creation uses data, so i drop guard here422 drop(data);423 throw!(StackOverflow);424 } else {425 *stack_depth += 1;426 }427 }428 let result = f();429 {430 let mut data = self.data_mut();431 data.stack_depth -= 1;432 data.stack_generation += 1;433 }434 if let Err(mut err) = result {435 err.trace_mut().0.push(StackTraceElement {436 location: None,437 desc: frame_desc(),438 });439 return Err(err);440 }441 result442 }443444 /// Runs passed function in state (required if function needs to modify stack trace)445 pub fn run_in_state<T>(&self, f: impl FnOnce() -> T) -> T {446 EVAL_STATE.with(|v| {447 let has_state = v.borrow().is_some();448 if !has_state {449 v.borrow_mut().replace(self.clone());450 }451 let result = f();452 if !has_state {453 v.borrow_mut().take();454 }455 result456 })457 }458 pub fn run_in_state_with_breakpoint(459 &self,460 bp: Rc<Breakpoint>,461 f: impl FnOnce() -> Result<()>,462 ) -> Result<()> {463 {464 let mut data = self.data_mut();465 data.breakpoints.0.push(bp);466 }467468 let result = self.run_in_state(f);469470 {471 let mut data = self.data_mut();472 data.breakpoints.0.pop();473 }474475 result476 }477478 pub fn stringify_err(&self, e: &LocError) -> String {479 let mut out = String::new();480 self.settings()481 .trace_format482 .write_trace(&mut out, self, e)483 .unwrap();484 out485 }486487 pub fn manifest(&self, val: Val) -> Result<IStr> {488 self.run_in_state(|| {489 push_description_frame(490 || "manifestification".to_string(),491 || val.manifest(&self.manifest_format()),492 )493 })494 }495 pub fn manifest_multi(&self, val: Val) -> Result<Vec<(IStr, IStr)>> {496 self.run_in_state(|| val.manifest_multi(&self.manifest_format()))497 }498 pub fn manifest_stream(&self, val: Val) -> Result<Vec<IStr>> {499 self.run_in_state(|| val.manifest_stream(&self.manifest_format()))500 }501502 /// If passed value is function then call with set TLA503 pub fn with_tla(&self, val: Val) -> Result<Val> {504 self.run_in_state(|| {505 Ok(match val {506 Val::Func(func) => push_description_frame(507 || "during TLA call".to_owned(),508 || {509 func.evaluate(510 self.create_default_context(),511 None,512 &self.settings().tla_vars,513 true,514 )515 },516 )?,517 v => v,518 })519 })520 }521}522523/// Internals524impl EvaluationState {525 fn data(&self) -> Ref<EvaluationData> {526 self.0.data.borrow()527 }528 fn data_mut(&self) -> RefMut<EvaluationData> {529 self.0.data.borrow_mut()530 }531 pub fn settings(&self) -> Ref<EvaluationSettings> {532 self.0.settings.borrow()533 }534 pub fn settings_mut(&self) -> RefMut<EvaluationSettings> {535 self.0.settings.borrow_mut()536 }537}538539/// Raw methods evaluate passed values but don't perform TLA execution540impl EvaluationState {541 pub fn evaluate_file_raw(&self, name: &Path) -> Result<Val> {542 self.run_in_state(|| self.import_file(&std::env::current_dir().expect("cwd"), name))543 }544 pub fn evaluate_file_raw_nocwd(&self, name: &Path) -> Result<Val> {545 self.run_in_state(|| self.import_file(&PathBuf::from("."), name))546 }547 /// Parses and evaluates the given snippet548 pub fn evaluate_snippet_raw(&self, source: Rc<Path>, code: IStr) -> Result<Val> {549 let parsed = parse(550 &code,551 &ParserSettings {552 file_name: source.clone(),553 },554 )555 .map_err(|e| ImportSyntaxError {556 path: source.clone(),557 source_code: code.clone(),558 error: Box::new(e),559 })?;560 self.add_parsed_file(source, code, parsed.clone())?;561 self.evaluate_expr_raw(parsed)562 }563 /// Evaluates the parsed expression564 pub fn evaluate_expr_raw(&self, code: LocExpr) -> Result<Val> {565 self.run_in_state(|| evaluate(self.create_default_context(), &code))566 }567}568569/// Settings utilities570impl EvaluationState {571 pub fn add_ext_var(&self, name: IStr, value: Val) {572 self.settings_mut().ext_vars.insert(name, value);573 }574 pub fn add_ext_str(&self, name: IStr, value: IStr) {575 self.add_ext_var(name, Val::Str(value));576 }577 pub fn add_ext_code(&self, name: IStr, code: IStr) -> Result<()> {578 let value =579 self.evaluate_snippet_raw(PathBuf::from(format!("ext_code {}", name)).into(), code)?;580 self.add_ext_var(name, value);581 Ok(())582 }583584 pub fn add_tla(&self, name: IStr, value: Val) {585 self.settings_mut()586 .tla_vars587 .insert(name, TlaArg::Val(value));588 }589 pub fn add_tla_str(&self, name: IStr, value: IStr) {590 self.settings_mut()591 .tla_vars592 .insert(name, TlaArg::String(value));593 }594 pub fn add_tla_code(&self, name: IStr, code: IStr) -> Result<()> {595 let parsed = self.add_file(PathBuf::from(format!("tla_code {}", name)).into(), code)?;596 self.settings_mut()597 .tla_vars598 .insert(name, TlaArg::Code(parsed));599 Ok(())600 }601602 pub fn resolve_file(&self, from: &Path, path: &Path) -> Result<Rc<Path>> {603 self.settings().import_resolver.resolve_file(from, path)604 }605 pub fn load_file_contents(&self, path: &Path) -> Result<IStr> {606 self.settings().import_resolver.load_file_contents(path)607 }608609 pub fn import_resolver(&self) -> Ref<dyn ImportResolver> {610 Ref::map(self.settings(), |s| &*s.import_resolver)611 }612 pub fn set_import_resolver(&self, resolver: Box<dyn ImportResolver>) {613 self.settings_mut().import_resolver = resolver;614 }615616 pub fn add_native(&self, name: IStr, cb: Cc<TraceBox<dyn Builtin>>) {617 self.settings_mut().ext_natives.insert(name, cb);618 }619620 pub fn manifest_format(&self) -> ManifestFormat {621 self.settings().manifest_format.clone()622 }623 pub fn set_manifest_format(&self, format: ManifestFormat) {624 self.settings_mut().manifest_format = format;625 }626627 pub fn trace_format(&self) -> Ref<dyn TraceFormat> {628 Ref::map(self.settings(), |s| &*s.trace_format)629 }630 pub fn set_trace_format(&self, format: Box<dyn TraceFormat>) {631 self.settings_mut().trace_format = format;632 }633634 pub fn max_trace(&self) -> usize {635 self.settings().max_trace636 }637 pub fn set_max_trace(&self, trace: usize) {638 self.settings_mut().max_trace = trace;639 }640641 pub fn max_stack(&self) -> usize {642 self.settings().max_stack643 }644 pub fn set_max_stack(&self, trace: usize) {645 self.settings_mut().max_stack = trace;646 }647}648649pub fn cc_ptr_eq<T>(a: &Cc<T>, b: &Cc<T>) -> bool {650 let a = a as &T;651 let b = b as &T;652 std::ptr::eq(a, b)653}654655fn weak_raw<T>(a: Weak<T>) -> *const () {656 unsafe { std::mem::transmute(a) }657}658fn weak_ptr_eq<T>(a: Weak<T>, b: Weak<T>) -> bool {659 std::ptr::eq(weak_raw(a), weak_raw(b))660}661662#[test]663fn weak_unsafe() {664 let a = Cc::new(1);665 let b = Cc::new(2);666667 let aw1 = a.clone().downgrade();668 let aw2 = a.clone().downgrade();669 let aw3 = a.clone().downgrade();670671 let bw = b.clone().downgrade();672673 assert!(weak_ptr_eq(aw1, aw2));674 assert!(!weak_ptr_eq(aw3, bw));675}676677#[cfg(test)]678pub mod tests {679 use super::Val;680 use crate::{681 error::Error::*, function::BuiltinParam, gc::TraceBox, native::NativeCallbackHandler,682 primitive_equals, EvaluationState,683 };684 use gcmodule::{Cc, Trace};685 use jrsonnet_interner::IStr;686 use jrsonnet_parser::*;687 use std::{688 path::{Path, PathBuf},689 rc::Rc,690 };691692 #[test]693 #[should_panic]694 fn eval_state_stacktrace() {695 let state = EvaluationState::default();696 state.run_in_state(|| {697 state698 .push(699 Some(&ExprLocation(PathBuf::from("test1.jsonnet").into(), 10, 20)),700 || "outer".to_owned(),701 || {702 state.push(703 Some(&ExprLocation(PathBuf::from("test2.jsonnet").into(), 30, 40)),704 || "inner".to_owned(),705 || Err(RuntimeError("".into()).into()),706 )?;707 Ok(Val::Null)708 },709 )710 .unwrap();711 });712 }713714 #[test]715 fn eval_state_standard() {716 let state = EvaluationState::default();717 state.with_stdlib();718 assert!(primitive_equals(719 &state720 .evaluate_snippet_raw(721 PathBuf::from("raw.jsonnet").into(),722 r#"std.assertEqual(std.base64("test"), "dGVzdA==")"#.into()723 )724 .unwrap(),725 &Val::Bool(true),726 )727 .unwrap());728 }729730 macro_rules! eval {731 ($str: expr) => {732 EvaluationState::default()733 .with_stdlib()734 .evaluate_snippet_raw(PathBuf::from("raw.jsonnet").into(), $str.into())735 .unwrap()736 };737 }738 macro_rules! eval_json {739 ($str: expr) => {{740 let evaluator = EvaluationState::default();741 evaluator.with_stdlib();742 evaluator.run_in_state(|| {743 evaluator744 .evaluate_snippet_raw(PathBuf::from("raw.jsonnet").into(), $str.into())745 .unwrap()746 .to_json(0)747 .unwrap()748 .replace("\n", "")749 })750 }};751 }752753 /// Asserts given code returns `true`754 macro_rules! assert_eval {755 ($str: expr) => {756 assert!(primitive_equals(&eval!($str), &Val::Bool(true)).unwrap())757 };758 }759760 /// Asserts given code returns `false`761 macro_rules! assert_eval_neg {762 ($str: expr) => {763 assert!(primitive_equals(&eval!($str), &Val::Bool(false)).unwrap())764 };765 }766 macro_rules! assert_json {767 ($str: expr, $out: expr) => {768 assert_eq!(eval_json!($str), $out.replace("\t", ""))769 };770 }771772 /// Sanity checking, before trusting to another tests773 #[test]774 fn equality_operator() {775 assert_eval!("2 == 2");776 assert_eval_neg!("2 != 2");777 assert_eval!("2 != 3");778 assert_eval_neg!("2 == 3");779 assert_eval!("'Hello' == 'Hello'");780 assert_eval_neg!("'Hello' != 'Hello'");781 assert_eval!("'Hello' != 'World'");782 assert_eval_neg!("'Hello' == 'World'");783 }784785 #[test]786 fn math_evaluation() {787 assert_eval!("2 + 2 * 2 == 6");788 assert_eval!("3 + (2 + 2 * 2) == 9");789 }790791 #[test]792 fn string_concat() {793 assert_eval!("'Hello' + 'World' == 'HelloWorld'");794 assert_eval!("'Hello' * 3 == 'HelloHelloHello'");795 assert_eval!("'Hello' + 'World' * 3 == 'HelloWorldWorldWorld'");796 }797798 #[test]799 fn faster_join() {800 assert_eval!("std.join([0,0], [[1,2],[3,4],[5,6]]) == [1,2,0,0,3,4,0,0,5,6]");801 assert_eval!("std.join(',', ['1','2','3','4']) == '1,2,3,4'");802 }803804 #[test]805 fn function_contexts() {806 assert_eval!(807 r#"808 local k = {809 t(name = self.h): [self.h, name],810 h: 3,811 };812 local f = {813 t: k.t(),814 h: 4,815 };816 f.t[0] == f.t[1]817 "#818 );819 }820821 #[test]822 fn local() {823 assert_eval!("local a = 2; local b = 3; a + b == 5");824 assert_eval!("local a = 1, b = a + 1; a + b == 3");825 assert_eval!("local a = 1; local a = 2; a == 2");826 }827828 #[test]829 fn object_lazyness() {830 assert_json!("local a = {a:error 'test'}; {}", r#"{}"#);831 }832833 #[test]834 fn object_inheritance() {835 assert_json!("{a: self.b} + {b:3}", r#"{"a": 3,"b": 3}"#);836 }837838 #[test]839 fn object_assertion_success() {840 eval!("{assert \"a\" in self} + {a:2}");841 }842843 #[test]844 fn object_assertion_error() {845 eval!("{assert \"a\" in self}");846 }847848 #[test]849 fn lazy_args() {850 eval!("local test(a) = 2; test(error '3')");851 }852853 #[test]854 #[should_panic]855 fn tailstrict_args() {856 eval!("local test(a) = 2; test(error '3') tailstrict");857 }858859 #[test]860 #[should_panic]861 fn no_binding_error() {862 eval!("a");863 }864865 #[test]866 fn test_object() {867 assert_json!("{a:2}", r#"{"a": 2}"#);868 assert_json!("{a:2+2}", r#"{"a": 4}"#);869 assert_json!("{a:2}+{b:2}", r#"{"a": 2,"b": 2}"#);870 assert_json!("{b:3}+{b:2}", r#"{"b": 2}"#);871 assert_json!("{b:3}+{b+:2}", r#"{"b": 5}"#);872 assert_json!("local test='a'; {[test]:2}", r#"{"a": 2}"#);873 assert_json!(874 r#"875 {876 name: "Alice",877 welcome: "Hello " + self.name + "!",878 }879 "#,880 r#"{"name": "Alice","welcome": "Hello Alice!"}"#881 );882 assert_json!(883 r#"884 {885 name: "Alice",886 welcome: "Hello " + self.name + "!",887 } + {888 name: "Bob"889 }890 "#,891 r#"{"name": "Bob","welcome": "Hello Bob!"}"#892 );893 }894895 #[test]896 fn functions() {897 assert_json!(r#"local a = function(b, c = 2) b + c; a(2)"#, "4");898 assert_json!(899 r#"local a = function(b, c = "Dear") b + c + d, d = "World"; a("Hello")"#,900 r#""HelloDearWorld""#901 );902 }903904 #[test]905 fn local_methods() {906 assert_json!(r#"local a(b, c = 2) = b + c; a(2)"#, "4");907 assert_json!(908 r#"local a(b, c = "Dear") = b + c + d, d = "World"; a("Hello")"#,909 r#""HelloDearWorld""#910 );911 }912913 #[test]914 fn object_locals() {915 assert_json!(r#"{local a = 3, b: a}"#, r#"{"b": 3}"#);916 assert_json!(r#"{local a = 3, local c = a, b: c}"#, r#"{"b": 3}"#);917 assert_json!(918 r#"{local a = function (b) {[b]:4}, test: a("test")}"#,919 r#"{"test": {"test": 4}}"#920 );921 }922923 #[test]924 fn object_comp() {925 assert_json!(926 r#"{local t = "a", ["h"+i+"_"+z]: if "h"+(i-1)+"_"+z in self then t+1 else 0+t for i in [1,2,3] for z in [2,3,4] if z != i}"#,927 "{\"h1_2\": \"0a\",\"h1_3\": \"0a\",\"h1_4\": \"0a\",\"h2_3\": \"a1\",\"h2_4\": \"a1\",\"h3_2\": \"0a\",\"h3_4\": \"a1\"}"928 )929 }930931 #[test]932 fn direct_self() {933 println!(934 "{:#?}",935 eval!(936 r#"937 {938 local me = self,939 a: 3,940 b(): me.a,941 }942 "#943 )944 );945 }946947 #[test]948 fn indirect_self() {949 // `self` assigned to `me` was lost when being950 // referenced from field951 eval!(952 r#"{953 local me = self,954 a: 3,955 b: me.a,956 }.b"#957 );958 }959960 // We can't trust other tests (And official jsonnet testsuite), if assert is not working correctly961 #[test]962 fn std_assert_ok() {963 eval!("std.assertEqual(4.5 << 2, 16)");964 }965966 #[test]967 #[should_panic]968 fn std_assert_failure() {969 eval!("std.assertEqual(4.5 << 2, 15)");970 }971972 #[test]973 fn string_is_string() {974 assert!(primitive_equals(975 &eval!("local arr = 'hello'; (!std.isArray(arr)) && (!std.isString(arr))"),976 &Val::Bool(false),977 )978 .unwrap());979 }980981 #[test]982 fn base64_works() {983 assert_json!(r#"std.base64("test")"#, r#""dGVzdA==""#);984 }985986 #[test]987 fn utf8_chars() {988 assert_json!(989 r#"local c="😎";{c:std.codepoint(c),l:std.length(c)}"#,990 r#"{"c": 128526,"l": 1}"#991 )992 }993994 #[test]995 fn json() {996 assert_json!(997 r#"std.manifestJsonEx({a:3, b:4, c:6},"")"#,998 r#""{\n\"a\": 3,\n\"b\": 4,\n\"c\": 6\n}""#999 );1000 }10011002 #[test]1003 fn json_minified() {1004 assert_json!(1005 r#"std.manifestJsonMinified({a:3, b:4, c:6})"#,1006 r#""{\"a\":3,\"b\":4,\"c\":6}""#1007 );1008 }10091010 #[test]1011 fn parse_json() {1012 assert_json!(1013 r#"std.parseJson('{"a": -1,"b": 1,"c": 3.141,"d": []}')"#,1014 r#"{"a": -1,"b": 1,"c": 3.141,"d": []}"#1015 );1016 }10171018 #[test]1019 fn test() {1020 assert_json!(1021 r#"[[a, b] for a in [1,2,3] for b in [4,5,6]]"#,1022 "[[1,4],[1,5],[1,6],[2,4],[2,5],[2,6],[3,4],[3,5],[3,6]]"1023 );1024 }10251026 #[test]1027 fn sjsonnet() {1028 eval!(1029 r#"1030 local x0 = {k: 1};1031 local x1 = {k: x0.k + x0.k};1032 local x2 = {k: x1.k + x1.k};1033 local x3 = {k: x2.k + x2.k};1034 local x4 = {k: x3.k + x3.k};1035 local x5 = {k: x4.k + x4.k};1036 local x6 = {k: x5.k + x5.k};1037 local x7 = {k: x6.k + x6.k};1038 local x8 = {k: x7.k + x7.k};1039 local x9 = {k: x8.k + x8.k};1040 local x10 = {k: x9.k + x9.k};1041 local x11 = {k: x10.k + x10.k};1042 local x12 = {k: x11.k + x11.k};1043 local x13 = {k: x12.k + x12.k};1044 local x14 = {k: x13.k + x13.k};1045 local x15 = {k: x14.k + x14.k};1046 local x16 = {k: x15.k + x15.k};1047 local x17 = {k: x16.k + x16.k};1048 local x18 = {k: x17.k + x17.k};1049 local x19 = {k: x18.k + x18.k};1050 local x20 = {k: x19.k + x19.k};1051 local x21 = {k: x20.k + x20.k};1052 x21.k1053 "#1054 );1055 }10561057 // This test is commented out by default, because of huge compilation slowdown1058 // #[bench]1059 // fn bench_codegen(b: &mut Bencher) {1060 // b.iter(|| {1061 // #[allow(clippy::all)]1062 // let stdlib = {1063 // use jrsonnet_parser::*;1064 // include!(concat!(env!("OUT_DIR"), "/stdlib.rs"))1065 // };1066 // stdlib1067 // })1068 // }10691070 /*1071 #[bench]1072 fn bench_serialize(b: &mut Bencher) {1073 b.iter(|| {1074 bincode::deserialize::<jrsonnet_parser::LocExpr>(include_bytes!(concat!(1075 env!("OUT_DIR"),1076 "/stdlib.bincode"1077 )))1078 .expect("deserialize stdlib")1079 })1080 }10811082 #[bench]1083 fn bench_parse(b: &mut Bencher) {1084 b.iter(|| {1085 jrsonnet_parser::parse(1086 jrsonnet_stdlib::STDLIB_STR,1087 &jrsonnet_parser::ParserSettings {1088 loc_data: true,1089 file_name: Rc::new(PathBuf::from("std.jsonnet")),1090 },1091 )1092 })1093 }1094 */10951096 #[test]1097 fn equality() {1098 println!(1099 "{:?}",1100 jrsonnet_parser::parse(1101 "{ x: 1, y: 2 } == { x: 1, y: 2 }",1102 &ParserSettings {1103 file_name: PathBuf::from("equality").into(),1104 }1105 )1106 );1107 assert_eval!("{ x: 1, y: 2 } == { x: 1, y: 2 }")1108 }11091110 #[test]1111 fn native_ext() -> crate::error::Result<()> {1112 use super::native::NativeCallback;1113 let evaluator = EvaluationState::default();11141115 evaluator.with_stdlib();11161117 #[derive(Trace)]1118 struct NativeAdd;1119 impl NativeCallbackHandler for NativeAdd {1120 fn call(&self, from: Option<Rc<Path>>, args: &[Val]) -> crate::error::Result<Val> {1121 assert_eq!(1122 &from.unwrap() as &Path,1123 &PathBuf::from("native_caller.jsonnet")1124 );1125 match (&args[0], &args[1]) {1126 (Val::Num(a), Val::Num(b)) => Ok(Val::Num(a + b)),1127 (_, _) => unreachable!(),1128 }1129 }1130 }1131 evaluator.settings_mut().ext_natives.insert(1132 "native_add".into(),1133 #[allow(deprecated)]1134 Cc::new(TraceBox(Box::new(NativeCallback::new(1135 vec![1136 BuiltinParam {1137 name: "a".into(),1138 has_default: false,1139 },1140 BuiltinParam {1141 name: "b".into(),1142 has_default: false,1143 },1144 ],1145 TraceBox(Box::new(NativeAdd)),1146 )))),1147 );1148 evaluator.evaluate_snippet_raw(1149 PathBuf::from("native_caller.jsonnet").into(),1150 "std.assertEqual(std.native(\"native_add\")(1, 2), 3)".into(),1151 )?;1152 Ok(())1153 }11541155 #[test]1156 fn constant_intrinsic() -> crate::error::Result<()> {1157 assert_eval!(1158 "local std2 = std; local std = std2 { primitiveEquals(a, b):: false }; 1 == 1"1159 );1160 Ok(())1161 }11621163 #[test]1164 fn standalone_super() -> crate::error::Result<()> {1165 assert_eval!(1166 r#"1167 local obj = {1168 a: 1,1169 b: 2,1170 c: 3,1171 };1172 local test = obj + {1173 fields: std.objectFields(super),1174 d: 5,1175 };1176 test.fields == ['a', 'b', 'c']1177 "#1178 );1179 Ok(())1180 }11811182 #[test]1183 fn comp_self() -> crate::error::Result<()> {1184 assert_eval!(1185 r#"1186 std.objectFields({1187 a:{1188 [name]: name for name in std.objectFields(self)1189 },1190 b: 2,1191 c: 3,1192 }.a) == ['a', 'b', 'c']1193 "#1194 );11951196 Ok(())1197 }11981199 struct TestImportResolver(IStr);1200 impl crate::import::ImportResolver for TestImportResolver {1201 fn resolve_file(&self, _: &Path, _: &Path) -> crate::error::Result<Rc<Path>> {1202 Ok(PathBuf::from("/test").into())1203 }12041205 fn load_file_contents(&self, _: &Path) -> crate::error::Result<IStr> {1206 Ok(self.0.clone())1207 }12081209 unsafe fn as_any(&self) -> &dyn std::any::Any {1210 panic!()1211 }1212 }12131214 #[test]1215 fn issue_23() {1216 let state = EvaluationState::default();1217 state.set_import_resolver(Box::new(TestImportResolver(r#"import "/test""#.into())));1218 let _ = state.evaluate_file_raw(&PathBuf::from("/test"));1219 }12201221 #[test]1222 fn issue_40() {1223 let state = EvaluationState::default();1224 state.with_stdlib();12251226 let error = state1227 .evaluate_snippet_raw(1228 PathBuf::from("issue40.jsonnet").into(),1229 r#"1230 local conf = {1231 n: ""1232 };12331234 local result = conf + {1235 assert std.isNumber(self.n): "is number"1236 };12371238 std.manifestJsonEx(result, "")1239 "#1240 .into(),1241 )1242 .unwrap_err();1243 assert_eq!(error.error().to_string(), "assert failed: is number");1244 }12451246 #[test]1247 fn test_ascii_upper_lower() {1248 assert_eval!(r#"std.assertEqual(std.asciiUpper("aBc😀"), "ABC😀")"#);1249 assert_eval!(r#"std.assertEqual(std.asciiLower("aBc😀"), "abc😀")"#);1250 }12511252 #[test]1253 fn test_member() {1254 assert_eval!(r#"!std.member("", "")"#);1255 assert_eval!(r#"std.member("abc", "a")"#);1256 assert_eval!(r#"!std.member("abc", "d")"#);1257 assert_eval!(r#"!std.member([], "")"#);1258 assert_eval!(r#"std.member(["a", "b", "c"], "a")"#);1259 assert_eval!(r#"!std.member(["a", "b", "c"], "d")"#);1260 }12611262 #[test]1263 fn test_count() {1264 assert_eval!(r#"std.assertEqual(std.count([], ""), 0)"#);1265 assert_eval!(r#"std.assertEqual(std.count(["a", "b", "a"], "d"), 0)"#);1266 assert_eval!(r#"std.assertEqual(std.count(["a", "b", "a"], "a"), 2)"#);1267 }1268}crates/jrsonnet-evaluator/src/obj.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/obj.rs
+++ b/crates/jrsonnet-evaluator/src/obj.rs
@@ -1,7 +1,7 @@
use crate::gc::{GcHashMap, GcHashSet, TraceBox};
use crate::operator::evaluate_add_op;
-use crate::{cc_ptr_eq, Bindable, LazyBinding, LazyVal, Result, Val};
-use gcmodule::{Cc, Trace};
+use crate::{cc_ptr_eq, weak_ptr_eq, weak_raw, Bindable, LazyBinding, LazyVal, Result, Val};
+use gcmodule::{Cc, Trace, Weak};
use jrsonnet_interner::IStr;
use jrsonnet_parser::{ExprLocation, Visibility};
use rustc_hash::FxHashMap;
@@ -22,7 +22,7 @@
}
// Field => This
-type CacheKey = (IStr, ObjValue);
+type CacheKey = (IStr, WeakObjValue);
#[derive(Trace)]
#[force_tracking]
pub struct ObjValueInternals {
@@ -35,6 +35,22 @@
}
#[derive(Clone, Trace)]
+pub struct WeakObjValue(#[skip_trace] pub(crate) Weak<ObjValueInternals>);
+
+impl PartialEq for WeakObjValue {
+ fn eq(&self, other: &Self) -> bool {
+ weak_ptr_eq(self.0.clone(), other.0.clone())
+ }
+}
+
+impl Eq for WeakObjValue {}
+impl Hash for WeakObjValue {
+ fn hash<H: Hasher>(&self, hasher: &mut H) {
+ hasher.write_usize(weak_raw(self.0.clone()) as usize)
+ }
+}
+
+#[derive(Clone, Trace)]
pub struct ObjValue(pub(crate) Cc<ObjValueInternals>);
impl Debug for ObjValue {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
@@ -50,14 +66,7 @@
for (name, member) in self.0.this_entries.iter() {
debug.field(name, member);
}
- #[cfg(feature = "unstable")]
- {
- debug.finish_non_exhaustive()
- }
- #[cfg(not(feature = "unstable"))]
- {
- debug.finish()
- }
+ debug.finish_non_exhaustive()
}
}
@@ -217,7 +226,7 @@
fn get_raw(&self, key: IStr, real_this: Option<&Self>) -> Result<Option<Val>> {
let real_this = real_this.unwrap_or(self);
- let cache_key = (key.clone(), real_this.clone());
+ let cache_key = (key.clone(), WeakObjValue(real_this.0.downgrade()));
if let Some(v) = self.0.value_cache.borrow().get(&cache_key) {
return Ok(v.clone());