difftreelog
style fix clippy warnings
in: master
3 files changed
crates/jrsonnet-evaluator/src/gc.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/gc.rs
+++ b/crates/jrsonnet-evaluator/src/gc.rs
@@ -18,7 +18,7 @@
}
fn is_type_tracked() -> bool {
- return true;
+ true
}
}
@@ -101,6 +101,11 @@
&mut self.0
}
}
+impl<V> Default for GcHashSet<V> {
+ fn default() -> Self {
+ Self::new()
+ }
+}
#[derive(Clone)]
pub struct GcHashMap<K, V>(pub FxHashMap<K, V>);
@@ -139,3 +144,8 @@
&mut self.0
}
}
+impl<K, V> Default for GcHashMap<K, V> {
+ fn default() -> Self {
+ Self::new()
+ }
+}
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)]78mod builtin;9mod ctx;10mod dynamic;11pub mod error;12mod evaluate;13mod function;14mod import;15mod integrations;16mod map;17pub mod native;18mod obj;19pub mod trace;20pub mod typed;21mod val;2223pub use ctx::*;24pub use dynamic::*;25use error::{Error::*, LocError, Result, StackTraceElement};26pub use evaluate::*;27pub use function::parse_function_call;28use gc::{GcHashMap, TraceBox};29use gcmodule::{Cc, Trace};30pub use import::*;31pub use jrsonnet_interner::IStr;32use jrsonnet_parser::*;33use native::NativeCallback;34pub use obj::*;35use std::{36 cell::{Ref, RefCell, RefMut},37 collections::HashMap,38 fmt::Debug,39 path::{Path, PathBuf},40 rc::Rc,41};42use trace::{location_to_offset, offset_to_location, CodeLocation, CompactFormat, TraceFormat};43pub use val::*;44pub mod gc;4546pub trait Bindable: Trace + 'static {47 fn bind(&self, this: Option<ObjValue>, super_obj: Option<ObjValue>) -> Result<LazyVal>;48}4950#[derive(Clone, Trace)]51pub enum LazyBinding {52 Bindable(Cc<TraceBox<dyn Bindable>>),53 Bound(LazyVal),54}5556impl Debug for LazyBinding {57 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {58 write!(f, "LazyBinding")59 }60}61impl LazyBinding {62 pub fn evaluate(&self, this: Option<ObjValue>, super_obj: Option<ObjValue>) -> Result<LazyVal> {63 match self {64 Self::Bindable(v) => v.bind(this, super_obj),65 Self::Bound(v) => Ok(v.clone()),66 }67 }68}6970pub struct EvaluationSettings {71 /// Limits recursion by limiting the number of stack frames72 pub max_stack: usize,73 /// Limits amount of stack trace items preserved74 pub max_trace: usize,75 /// Used for s`td.extVar`76 pub ext_vars: HashMap<IStr, Val>,77 /// Used for ext.native78 pub ext_natives: HashMap<IStr, Cc<NativeCallback>>,79 /// TLA vars80 pub tla_vars: HashMap<IStr, Val>,81 /// Global variables are inserted in default context82 pub globals: HashMap<IStr, Val>,83 /// Used to resolve file locations/contents84 pub import_resolver: Box<dyn ImportResolver>,85 /// Used in manifestification functions86 pub manifest_format: ManifestFormat,87 /// Used for bindings88 pub trace_format: Box<dyn TraceFormat>,89}90impl Default for EvaluationSettings {91 fn default() -> Self {92 Self {93 max_stack: 200,94 max_trace: 20,95 globals: Default::default(),96 ext_vars: Default::default(),97 ext_natives: Default::default(),98 tla_vars: Default::default(),99 import_resolver: Box::new(DummyImportResolver),100 manifest_format: ManifestFormat::Json(4),101 trace_format: Box::new(CompactFormat {102 padding: 4,103 resolver: trace::PathResolver::Absolute,104 }),105 }106 }107}108109#[derive(Default)]110struct EvaluationData {111 /// Used for stack overflow detection, stacktrace is populated on unwind112 stack_depth: usize,113 /// Updated every time stack entry is popt114 stack_generation: usize,115116 breakpoints: Breakpoints,117 /// Contains file source codes and evaluation results for imports and pretty-printed stacktraces118 files: HashMap<Rc<Path>, FileData>,119 str_files: HashMap<Rc<Path>, IStr>,120}121122pub struct FileData {123 source_code: IStr,124 parsed: LocExpr,125 evaluated: Option<Val>,126}127128pub struct Breakpoint {129 loc: ExprLocation,130 collected: RefCell<HashMap<usize, (usize, Vec<Result<Val>>)>>,131}132#[derive(Default)]133struct Breakpoints(Vec<Rc<Breakpoint>>);134impl Breakpoints {135 fn insert(136 &self,137 stack_depth: usize,138 stack_generation: usize,139 loc: &ExprLocation,140 result: Result<Val>,141 ) -> Result<Val> {142 if self.0.is_empty() {143 return result;144 }145 for item in self.0.iter() {146 if item.loc.belongs_to(loc) {147 let mut collected = item.collected.borrow_mut();148 let (depth, vals) = collected.entry(stack_generation).or_default();149 if stack_depth > *depth {150 vals.clear();151 }152 vals.push(result.clone());153 }154 }155 result156 }157}158159#[derive(Default)]160pub struct EvaluationStateInternals {161 /// Internal state162 data: RefCell<EvaluationData>,163 /// Settings, safe to change at runtime164 settings: RefCell<EvaluationSettings>,165}166167thread_local! {168 /// Contains the state for a currently executed file.169 /// Global state is fine here.170 pub(crate) static EVAL_STATE: RefCell<Option<EvaluationState>> = RefCell::new(None)171}172pub(crate) fn with_state<T>(f: impl FnOnce(&EvaluationState) -> T) -> T {173 EVAL_STATE.with(|s| f(s.borrow().as_ref().unwrap()))174}175pub(crate) fn push_frame<T>(176 e: &ExprLocation,177 frame_desc: impl FnOnce() -> String,178 f: impl FnOnce() -> Result<T>,179) -> Result<T> {180 with_state(|s| s.push(e, frame_desc, f))181}182183#[allow(dead_code)]184pub(crate) fn push_val_frame(185 e: &ExprLocation,186 frame_desc: impl FnOnce() -> String,187 f: impl FnOnce() -> Result<Val>,188) -> Result<Val> {189 with_state(|s| s.push_val(e, frame_desc, f))190}191#[allow(dead_code)]192pub(crate) fn push_description_frame<T>(193 frame_desc: impl FnOnce() -> String,194 f: impl FnOnce() -> Result<T>,195) -> Result<T> {196 with_state(|s| s.push_description(frame_desc, f))197}198199/// Maintains stack trace and import resolution200#[derive(Default, Clone)]201pub struct EvaluationState(Rc<EvaluationStateInternals>);202203impl EvaluationState {204 /// Parses and adds file as loaded205 pub fn add_file(&self, path: Rc<Path>, source_code: IStr) -> Result<()> {206 self.add_parsed_file(207 path.clone(),208 source_code.clone(),209 parse(210 &source_code,211 &ParserSettings {212 file_name: path.clone(),213 },214 )215 .map_err(|error| ImportSyntaxError {216 error: Box::new(error),217 path: path.to_owned(),218 source_code,219 })?,220 )?;221222 Ok(())223 }224225 pub fn reset_evaluation_state(&self, name: &Path) {226 self.data_mut()227 .files228 .get_mut(name)229 .unwrap()230 .evaluated231 .take();232 }233234 /// Adds file by source code and parsed expr235 pub fn add_parsed_file(236 &self,237 name: Rc<Path>,238 source_code: IStr,239 parsed: LocExpr,240 ) -> Result<()> {241 self.data_mut().files.insert(242 name,243 FileData {244 source_code,245 parsed,246 evaluated: None,247 },248 );249250 Ok(())251 }252 pub fn get_source(&self, name: &Path) -> Option<IStr> {253 let ro_map = &self.data().files;254 ro_map.get(name).map(|value| value.source_code.clone())255 }256 pub fn map_source_locations(&self, file: &Path, locs: &[usize]) -> Vec<CodeLocation> {257 offset_to_location(&self.get_source(file).unwrap_or("".into()), locs)258 }259 pub fn map_from_source_location(260 &self,261 file: &Path,262 line: usize,263 column: usize,264 ) -> Option<usize> {265 location_to_offset(&self.get_source(file).unwrap(), line, column)266 }267 pub fn import_file(&self, from: &Path, path: &Path) -> Result<Val> {268 let file_path = self.resolve_file(from, path)?;269 {270 let data = self.data();271 let files = &data.files;272 if files.contains_key(&file_path as &Path) {273 drop(data);274 return self.evaluate_loaded_file_raw(&file_path);275 }276 }277 let contents = self.load_file_contents(&file_path)?;278 self.add_file(file_path.clone(), contents)?;279 self.evaluate_loaded_file_raw(&file_path)280 }281 pub(crate) fn import_file_str(&self, from: &Path, path: &Path) -> Result<IStr> {282 let path = self.resolve_file(from, path)?;283 if !self.data().str_files.contains_key(&path) {284 let file_str = self.load_file_contents(&path)?;285 self.data_mut().str_files.insert(path.clone(), file_str);286 }287 Ok(self.data().str_files.get(&path).cloned().unwrap())288 }289290 fn evaluate_loaded_file_raw(&self, name: &Path) -> Result<Val> {291 let expr: LocExpr = {292 let ro_map = &self.data().files;293 let value = ro_map294 .get(name)295 .unwrap_or_else(|| panic!("file not added: {:?}", name));296 if let Some(ref evaluated) = value.evaluated {297 return Ok(evaluated.clone());298 }299 value.parsed.clone()300 };301 let value = evaluate(self.create_default_context(), &expr)?;302 {303 self.data_mut()304 .files305 .get_mut(name)306 .unwrap()307 .evaluated308 .replace(value.clone());309 }310 Ok(value)311 }312313 /// Adds standard library global variable (std) to this evaluator314 pub fn with_stdlib(&self) -> &Self {315 use jrsonnet_stdlib::STDLIB_STR;316 let std_path: Rc<Path> = PathBuf::from("std.jsonnet").into();317 self.run_in_state(|| {318 self.add_parsed_file(319 std_path.clone(),320 STDLIB_STR.to_owned().into(),321 builtin::get_parsed_stdlib(),322 )323 .unwrap();324 let val = self.evaluate_loaded_file_raw(&std_path).unwrap();325 self.settings_mut().globals.insert("std".into(), val);326 });327 self328 }329330 /// Creates context with all passed global variables331 pub fn create_default_context(&self) -> Context {332 let globals = &self.settings().globals;333 let mut new_bindings = GcHashMap::with_capacity(globals.len());334 for (name, value) in globals.iter() {335 new_bindings.insert(name.clone(), LazyVal::new_resolved(value.clone()));336 }337 Context::new().extend_bound(new_bindings)338 }339340 /// Executes code creating a new stack frame341 pub fn push<T>(342 &self,343 e: &ExprLocation,344 frame_desc: impl FnOnce() -> String,345 f: impl FnOnce() -> Result<T>,346 ) -> Result<T> {347 {348 let mut data = self.data_mut();349 let stack_depth = &mut data.stack_depth;350 if *stack_depth > self.max_stack() {351 // Error creation uses data, so i drop guard here352 drop(data);353 throw!(StackOverflow);354 } else {355 *stack_depth += 1;356 }357 }358 let result = f();359 {360 let mut data = self.data_mut();361 data.stack_depth -= 1;362 data.stack_generation += 1;363 }364 if let Err(mut err) = result {365 err.trace_mut().0.push(StackTraceElement {366 location: Some(e.clone()),367 desc: frame_desc(),368 });369 return Err(err);370 }371 result372 }373374 /// Executes code creating a new stack frame375 pub fn push_val(376 &self,377 e: &ExprLocation,378 frame_desc: impl FnOnce() -> String,379 f: impl FnOnce() -> Result<Val>,380 ) -> Result<Val> {381 {382 let mut data = self.data_mut();383 let stack_depth = &mut data.stack_depth;384 if *stack_depth > self.max_stack() {385 // Error creation uses data, so i drop guard here386 drop(data);387 throw!(StackOverflow);388 } else {389 *stack_depth += 1;390 }391 }392 let mut result = f();393 {394 let mut data = self.data_mut();395 data.stack_depth -= 1;396 data.stack_generation += 1;397 result = data398 .breakpoints399 .insert(data.stack_depth, data.stack_generation, &e, result);400 }401 if let Err(mut err) = result {402 err.trace_mut().0.push(StackTraceElement {403 location: Some(e.clone()),404 desc: frame_desc(),405 });406 return Err(err);407 }408 result409 }410 /// Executes code creating a new stack frame411 pub fn push_description<T>(412 &self,413 frame_desc: impl FnOnce() -> String,414 f: impl FnOnce() -> Result<T>,415 ) -> Result<T> {416 {417 let mut data = self.data_mut();418 let stack_depth = &mut data.stack_depth;419 if *stack_depth > self.max_stack() {420 // Error creation uses data, so i drop guard here421 drop(data);422 throw!(StackOverflow);423 } else {424 *stack_depth += 1;425 }426 }427 let result = f();428 {429 let mut data = self.data_mut();430 data.stack_depth -= 1;431 data.stack_generation += 1;432 }433 if let Err(mut err) = result {434 err.trace_mut().0.push(StackTraceElement {435 location: None,436 desc: frame_desc(),437 });438 return Err(err);439 }440 result441 }442443 /// Runs passed function in state (required if function needs to modify stack trace)444 pub fn run_in_state<T>(&self, f: impl FnOnce() -> T) -> T {445 EVAL_STATE.with(|v| {446 let has_state = v.borrow().is_some();447 if !has_state {448 v.borrow_mut().replace(self.clone());449 }450 let result = f();451 if !has_state {452 v.borrow_mut().take();453 }454 result455 })456 }457 pub fn run_in_state_with_breakpoint(458 &self,459 bp: Rc<Breakpoint>,460 f: impl FnOnce() -> Result<()>,461 ) -> Result<()> {462 {463 let mut data = self.data_mut();464 data.breakpoints.0.push(bp);465 }466467 let result = self.run_in_state(f);468469 {470 let mut data = self.data_mut();471 data.breakpoints.0.pop();472 }473474 result475 }476477 pub fn stringify_err(&self, e: &LocError) -> String {478 let mut out = String::new();479 self.settings()480 .trace_format481 .write_trace(&mut out, self, e)482 .unwrap();483 out484 }485486 pub fn manifest(&self, val: Val) -> Result<IStr> {487 self.run_in_state(|| {488 push_description_frame(489 || format!("manifestification"),490 || val.manifest(&self.manifest_format()),491 )492 })493 }494 pub fn manifest_multi(&self, val: Val) -> Result<Vec<(IStr, IStr)>> {495 self.run_in_state(|| val.manifest_multi(&self.manifest_format()))496 }497 pub fn manifest_stream(&self, val: Val) -> Result<Vec<IStr>> {498 self.run_in_state(|| val.manifest_stream(&self.manifest_format()))499 }500501 /// If passed value is function then call with set TLA502 pub fn with_tla(&self, val: Val) -> Result<Val> {503 self.run_in_state(|| {504 Ok(match val {505 Val::Func(func) => push_description_frame(506 || "during TLA call".to_owned(),507 || {508 func.evaluate_map(509 self.create_default_context(),510 &self.settings().tla_vars,511 true,512 )513 },514 )?,515 v => v,516 })517 })518 }519}520521/// Internals522impl EvaluationState {523 fn data(&self) -> Ref<EvaluationData> {524 self.0.data.borrow()525 }526 fn data_mut(&self) -> RefMut<EvaluationData> {527 self.0.data.borrow_mut()528 }529 pub fn settings(&self) -> Ref<EvaluationSettings> {530 self.0.settings.borrow()531 }532 pub fn settings_mut(&self) -> RefMut<EvaluationSettings> {533 self.0.settings.borrow_mut()534 }535}536537/// Raw methods evaluate passed values but don't perform TLA execution538impl EvaluationState {539 pub fn evaluate_file_raw(&self, name: &Path) -> Result<Val> {540 self.run_in_state(|| self.import_file(&std::env::current_dir().expect("cwd"), name))541 }542 pub fn evaluate_file_raw_nocwd(&self, name: &Path) -> Result<Val> {543 self.run_in_state(|| self.import_file(&PathBuf::from("."), name))544 }545 /// Parses and evaluates the given snippet546 pub fn evaluate_snippet_raw(&self, source: Rc<Path>, code: IStr) -> Result<Val> {547 let parsed = parse(548 &code,549 &ParserSettings {550 file_name: source.clone(),551 },552 )553 .map_err(|e| ImportSyntaxError {554 path: source.clone(),555 source_code: code.clone(),556 error: Box::new(e),557 })?;558 self.add_parsed_file(source, code, parsed.clone())?;559 self.evaluate_expr_raw(parsed)560 }561 /// Evaluates the parsed expression562 pub fn evaluate_expr_raw(&self, code: LocExpr) -> Result<Val> {563 self.run_in_state(|| evaluate(self.create_default_context(), &code))564 }565}566567/// Settings utilities568impl EvaluationState {569 pub fn add_ext_var(&self, name: IStr, value: Val) {570 self.settings_mut().ext_vars.insert(name, value);571 }572 pub fn add_ext_str(&self, name: IStr, value: IStr) {573 self.add_ext_var(name, Val::Str(value));574 }575 pub fn add_ext_code(&self, name: IStr, code: IStr) -> Result<()> {576 let value =577 self.evaluate_snippet_raw(PathBuf::from(format!("ext_code {}", name)).into(), code)?;578 self.add_ext_var(name, value);579 Ok(())580 }581582 pub fn add_tla(&self, name: IStr, value: Val) {583 self.settings_mut().tla_vars.insert(name, value);584 }585 pub fn add_tla_str(&self, name: IStr, value: IStr) {586 self.add_tla(name, Val::Str(value));587 }588 pub fn add_tla_code(&self, name: IStr, code: IStr) -> Result<()> {589 let value =590 self.evaluate_snippet_raw(PathBuf::from(format!("tla_code {}", name)).into(), code)?;591 self.add_tla(name, value);592 Ok(())593 }594595 pub fn resolve_file(&self, from: &Path, path: &Path) -> Result<Rc<Path>> {596 self.settings().import_resolver.resolve_file(from, path)597 }598 pub fn load_file_contents(&self, path: &Path) -> Result<IStr> {599 self.settings().import_resolver.load_file_contents(path)600 }601602 pub fn import_resolver(&self) -> Ref<dyn ImportResolver> {603 Ref::map(self.settings(), |s| &*s.import_resolver)604 }605 pub fn set_import_resolver(&self, resolver: Box<dyn ImportResolver>) {606 self.settings_mut().import_resolver = resolver;607 }608609 pub fn add_native(&self, name: IStr, cb: Cc<NativeCallback>) {610 self.settings_mut().ext_natives.insert(name, cb);611 }612613 pub fn manifest_format(&self) -> ManifestFormat {614 self.settings().manifest_format.clone()615 }616 pub fn set_manifest_format(&self, format: ManifestFormat) {617 self.settings_mut().manifest_format = format;618 }619620 pub fn trace_format(&self) -> Ref<dyn TraceFormat> {621 Ref::map(self.settings(), |s| &*s.trace_format)622 }623 pub fn set_trace_format(&self, format: Box<dyn TraceFormat>) {624 self.settings_mut().trace_format = format;625 }626627 pub fn max_trace(&self) -> usize {628 self.settings().max_trace629 }630 pub fn set_max_trace(&self, trace: usize) {631 self.settings_mut().max_trace = trace;632 }633634 pub fn max_stack(&self) -> usize {635 self.settings().max_stack636 }637 pub fn set_max_stack(&self, trace: usize) {638 self.settings_mut().max_stack = trace;639 }640}641642pub fn cc_ptr_eq<T>(a: &Cc<T>, b: &Cc<T>) -> bool {643 let a = &a as &T;644 let b = &b as &T;645 std::ptr::eq(a, b)646}647648#[cfg(test)]649pub mod tests {650 use super::Val;651 use crate::{652 error::Error::*, gc::TraceBox, native::NativeCallbackHandler, primitive_equals,653 EvaluationState,654 };655 use gcmodule::{Cc, Trace};656 use jrsonnet_interner::IStr;657 use jrsonnet_parser::*;658 use std::{659 path::{Path, PathBuf},660 rc::Rc,661 };662663 #[test]664 #[should_panic]665 fn eval_state_stacktrace() {666 let state = EvaluationState::default();667 state.run_in_state(|| {668 state669 .push(670 &ExprLocation(PathBuf::from("test1.jsonnet").into(), 10, 20),671 || "outer".to_owned(),672 || {673 state.push(674 &ExprLocation(PathBuf::from("test2.jsonnet").into(), 30, 40),675 || "inner".to_owned(),676 || Err(RuntimeError("".into()).into()),677 )?;678 Ok(Val::Null)679 },680 )681 .unwrap();682 });683 }684685 #[test]686 fn eval_state_standard() {687 let state = EvaluationState::default();688 state.with_stdlib();689 assert!(primitive_equals(690 &state691 .evaluate_snippet_raw(692 PathBuf::from("raw.jsonnet").into(),693 r#"std.assertEqual(std.base64("test"), "dGVzdA==")"#.into()694 )695 .unwrap(),696 &Val::Bool(true),697 )698 .unwrap());699 }700701 macro_rules! eval {702 ($str: expr) => {703 EvaluationState::default()704 .with_stdlib()705 .evaluate_snippet_raw(PathBuf::from("raw.jsonnet").into(), $str.into())706 .unwrap()707 };708 }709 macro_rules! eval_json {710 ($str: expr) => {{711 let evaluator = EvaluationState::default();712 evaluator.with_stdlib();713 evaluator.run_in_state(|| {714 evaluator715 .evaluate_snippet_raw(PathBuf::from("raw.jsonnet").into(), $str.into())716 .unwrap()717 .to_json(0)718 .unwrap()719 .replace("\n", "")720 })721 }};722 }723724 /// Asserts given code returns `true`725 macro_rules! assert_eval {726 ($str: expr) => {727 assert!(primitive_equals(&eval!($str), &Val::Bool(true)).unwrap())728 };729 }730731 /// Asserts given code returns `false`732 macro_rules! assert_eval_neg {733 ($str: expr) => {734 assert!(primitive_equals(&eval!($str), &Val::Bool(false)).unwrap())735 };736 }737 macro_rules! assert_json {738 ($str: expr, $out: expr) => {739 assert_eq!(eval_json!($str), $out.replace("\t", ""))740 };741 }742743 /// Sanity checking, before trusting to another tests744 #[test]745 fn equality_operator() {746 assert_eval!("2 == 2");747 assert_eval_neg!("2 != 2");748 assert_eval!("2 != 3");749 assert_eval_neg!("2 == 3");750 assert_eval!("'Hello' == 'Hello'");751 assert_eval_neg!("'Hello' != 'Hello'");752 assert_eval!("'Hello' != 'World'");753 assert_eval_neg!("'Hello' == 'World'");754 }755756 #[test]757 fn math_evaluation() {758 assert_eval!("2 + 2 * 2 == 6");759 assert_eval!("3 + (2 + 2 * 2) == 9");760 }761762 #[test]763 fn string_concat() {764 assert_eval!("'Hello' + 'World' == 'HelloWorld'");765 assert_eval!("'Hello' * 3 == 'HelloHelloHello'");766 assert_eval!("'Hello' + 'World' * 3 == 'HelloWorldWorldWorld'");767 }768769 #[test]770 fn faster_join() {771 assert_eval!("std.join([0,0], [[1,2],[3,4],[5,6]]) == [1,2,0,0,3,4,0,0,5,6]");772 assert_eval!("std.join(',', ['1','2','3','4']) == '1,2,3,4'");773 }774775 #[test]776 fn function_contexts() {777 assert_eval!(778 r#"779 local k = {780 t(name = self.h): [self.h, name],781 h: 3,782 };783 local f = {784 t: k.t(),785 h: 4,786 };787 f.t[0] == f.t[1]788 "#789 );790 }791792 #[test]793 fn local() {794 assert_eval!("local a = 2; local b = 3; a + b == 5");795 assert_eval!("local a = 1, b = a + 1; a + b == 3");796 assert_eval!("local a = 1; local a = 2; a == 2");797 }798799 #[test]800 fn object_lazyness() {801 assert_json!("local a = {a:error 'test'}; {}", r#"{}"#);802 }803804 #[test]805 fn object_inheritance() {806 assert_json!("{a: self.b} + {b:3}", r#"{"a": 3,"b": 3}"#);807 }808809 #[test]810 fn object_assertion_success() {811 eval!("{assert \"a\" in self} + {a:2}");812 }813814 #[test]815 fn object_assertion_error() {816 eval!("{assert \"a\" in self}");817 }818819 #[test]820 fn lazy_args() {821 eval!("local test(a) = 2; test(error '3')");822 }823824 #[test]825 #[should_panic]826 fn tailstrict_args() {827 eval!("local test(a) = 2; test(error '3') tailstrict");828 }829830 #[test]831 #[should_panic]832 fn no_binding_error() {833 eval!("a");834 }835836 #[test]837 fn test_object() {838 assert_json!("{a:2}", r#"{"a": 2}"#);839 assert_json!("{a:2+2}", r#"{"a": 4}"#);840 assert_json!("{a:2}+{b:2}", r#"{"a": 2,"b": 2}"#);841 assert_json!("{b:3}+{b:2}", r#"{"b": 2}"#);842 assert_json!("{b:3}+{b+:2}", r#"{"b": 5}"#);843 assert_json!("local test='a'; {[test]:2}", r#"{"a": 2}"#);844 assert_json!(845 r#"846 {847 name: "Alice",848 welcome: "Hello " + self.name + "!",849 }850 "#,851 r#"{"name": "Alice","welcome": "Hello Alice!"}"#852 );853 assert_json!(854 r#"855 {856 name: "Alice",857 welcome: "Hello " + self.name + "!",858 } + {859 name: "Bob"860 }861 "#,862 r#"{"name": "Bob","welcome": "Hello Bob!"}"#863 );864 }865866 #[test]867 fn functions() {868 assert_json!(r#"local a = function(b, c = 2) b + c; a(2)"#, "4");869 assert_json!(870 r#"local a = function(b, c = "Dear") b + c + d, d = "World"; a("Hello")"#,871 r#""HelloDearWorld""#872 );873 }874875 #[test]876 fn local_methods() {877 assert_json!(r#"local a(b, c = 2) = b + c; a(2)"#, "4");878 assert_json!(879 r#"local a(b, c = "Dear") = b + c + d, d = "World"; a("Hello")"#,880 r#""HelloDearWorld""#881 );882 }883884 #[test]885 fn object_locals() {886 assert_json!(r#"{local a = 3, b: a}"#, r#"{"b": 3}"#);887 assert_json!(r#"{local a = 3, local c = a, b: c}"#, r#"{"b": 3}"#);888 assert_json!(889 r#"{local a = function (b) {[b]:4}, test: a("test")}"#,890 r#"{"test": {"test": 4}}"#891 );892 }893894 #[test]895 fn object_comp() {896 assert_json!(897 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}"#,898 "{\"h1_2\": \"0a\",\"h1_3\": \"0a\",\"h1_4\": \"0a\",\"h2_3\": \"a1\",\"h2_4\": \"a1\",\"h3_2\": \"0a\",\"h3_4\": \"a1\"}"899 )900 }901902 #[test]903 fn direct_self() {904 println!(905 "{:#?}",906 eval!(907 r#"908 {909 local me = self,910 a: 3,911 b(): me.a,912 }913 "#914 )915 );916 }917918 #[test]919 fn indirect_self() {920 // `self` assigned to `me` was lost when being921 // referenced from field922 eval!(923 r#"{924 local me = self,925 a: 3,926 b: me.a,927 }.b"#928 );929 }930931 // We can't trust other tests (And official jsonnet testsuite), if assert is not working correctly932 #[test]933 fn std_assert_ok() {934 eval!("std.assertEqual(4.5 << 2, 16)");935 }936937 #[test]938 #[should_panic]939 fn std_assert_failure() {940 eval!("std.assertEqual(4.5 << 2, 15)");941 }942943 #[test]944 fn string_is_string() {945 assert!(primitive_equals(946 &eval!("local arr = 'hello'; (!std.isArray(arr)) && (!std.isString(arr))"),947 &Val::Bool(false),948 )949 .unwrap());950 }951952 #[test]953 fn base64_works() {954 assert_json!(r#"std.base64("test")"#, r#""dGVzdA==""#);955 }956957 #[test]958 fn utf8_chars() {959 assert_json!(960 r#"local c="😎";{c:std.codepoint(c),l:std.length(c)}"#,961 r#"{"c": 128526,"l": 1}"#962 )963 }964965 #[test]966 fn json() {967 assert_json!(968 r#"std.manifestJsonEx({a:3, b:4, c:6},"")"#,969 r#""{\n\"a\": 3,\n\"b\": 4,\n\"c\": 6\n}""#970 );971 }972973 #[test]974 fn parse_json() {975 assert_json!(976 r#"std.parseJson('{"a": -1,"b": 1,"c": 3.141,"d": []}')"#,977 r#"{"a": -1,"b": 1,"c": 3.141,"d": []}"#978 );979 // TODO: this should in fact fail as is no proper JSON syntax980 assert_json!(981 r#"std.parseJson("{a:-1, b:1, c:3.141, d:[]}")"#,982 r#"{"a": -1,"b": 1,"c": 3.141,"d": []}"#983 );984 // TODO: this is also no valid JSON985 assert_json!(r#"std.parseJson('local x = 2; x * x')"#, r#"4"#);986 }987988 #[test]989 fn test() {990 assert_json!(991 r#"[[a, b] for a in [1,2,3] for b in [4,5,6]]"#,992 "[[1,4],[1,5],[1,6],[2,4],[2,5],[2,6],[3,4],[3,5],[3,6]]"993 );994 }995996 #[test]997 fn sjsonnet() {998 eval!(999 r#"1000 local x0 = {k: 1};1001 local x1 = {k: x0.k + x0.k};1002 local x2 = {k: x1.k + x1.k};1003 local x3 = {k: x2.k + x2.k};1004 local x4 = {k: x3.k + x3.k};1005 local x5 = {k: x4.k + x4.k};1006 local x6 = {k: x5.k + x5.k};1007 local x7 = {k: x6.k + x6.k};1008 local x8 = {k: x7.k + x7.k};1009 local x9 = {k: x8.k + x8.k};1010 local x10 = {k: x9.k + x9.k};1011 local x11 = {k: x10.k + x10.k};1012 local x12 = {k: x11.k + x11.k};1013 local x13 = {k: x12.k + x12.k};1014 local x14 = {k: x13.k + x13.k};1015 local x15 = {k: x14.k + x14.k};1016 local x16 = {k: x15.k + x15.k};1017 local x17 = {k: x16.k + x16.k};1018 local x18 = {k: x17.k + x17.k};1019 local x19 = {k: x18.k + x18.k};1020 local x20 = {k: x19.k + x19.k};1021 local x21 = {k: x20.k + x20.k};1022 x21.k1023 "#1024 );1025 }10261027 // This test is commented out by default, because of huge compilation slowdown1028 // #[bench]1029 // fn bench_codegen(b: &mut Bencher) {1030 // b.iter(|| {1031 // #[allow(clippy::all)]1032 // let stdlib = {1033 // use jrsonnet_parser::*;1034 // include!(concat!(env!("OUT_DIR"), "/stdlib.rs"))1035 // };1036 // stdlib1037 // })1038 // }10391040 /*1041 #[bench]1042 fn bench_serialize(b: &mut Bencher) {1043 b.iter(|| {1044 bincode::deserialize::<jrsonnet_parser::LocExpr>(include_bytes!(concat!(1045 env!("OUT_DIR"),1046 "/stdlib.bincode"1047 )))1048 .expect("deserialize stdlib")1049 })1050 }10511052 #[bench]1053 fn bench_parse(b: &mut Bencher) {1054 b.iter(|| {1055 jrsonnet_parser::parse(1056 jrsonnet_stdlib::STDLIB_STR,1057 &jrsonnet_parser::ParserSettings {1058 loc_data: true,1059 file_name: Rc::new(PathBuf::from("std.jsonnet")),1060 },1061 )1062 })1063 }1064 */10651066 #[test]1067 fn equality() {1068 println!(1069 "{:?}",1070 jrsonnet_parser::parse(1071 "{ x: 1, y: 2 } == { x: 1, y: 2 }",1072 &ParserSettings {1073 file_name: PathBuf::from("equality").into(),1074 }1075 )1076 );1077 assert_eval!("{ x: 1, y: 2 } == { x: 1, y: 2 }")1078 }10791080 #[test]1081 fn native_ext() -> crate::error::Result<()> {1082 use super::native::NativeCallback;1083 let evaluator = EvaluationState::default();10841085 evaluator.with_stdlib();10861087 #[derive(Trace)]1088 struct NativeAdd;1089 impl NativeCallbackHandler for NativeAdd {1090 fn call(&self, from: Rc<Path>, args: &[Val]) -> crate::error::Result<Val> {1091 assert_eq!(&from as &Path, &PathBuf::from("native_caller.jsonnet"));1092 match (&args[0], &args[1]) {1093 (Val::Num(a), Val::Num(b)) => Ok(Val::Num(a + b)),1094 (_, _) => unreachable!(),1095 }1096 }1097 }1098 evaluator.settings_mut().ext_natives.insert(1099 "native_add".into(),1100 Cc::new(NativeCallback::new(1101 ParamsDesc(Rc::new(vec![1102 Param("a".into(), None),1103 Param("b".into(), None),1104 ])),1105 TraceBox(Box::new(NativeAdd)),1106 )),1107 );1108 evaluator.evaluate_snippet_raw(1109 PathBuf::from("native_caller.jsonnet").into(),1110 "std.assertEqual(std.native(\"native_add\")(1, 2), 3)".into(),1111 )?;1112 Ok(())1113 }11141115 #[test]1116 fn constant_intrinsic() -> crate::error::Result<()> {1117 assert_eval!(1118 "local std2 = std; local std = std2 { primitiveEquals(a, b):: false }; 1 == 1"1119 );1120 Ok(())1121 }11221123 #[test]1124 fn standalone_super() -> crate::error::Result<()> {1125 assert_eval!(1126 r#"1127 local obj = {1128 a: 1,1129 b: 2,1130 c: 3,1131 };1132 local test = obj + {1133 fields: std.objectFields(super),1134 d: 5,1135 };1136 test.fields == ['a', 'b', 'c']1137 "#1138 );1139 Ok(())1140 }11411142 #[test]1143 fn comp_self() -> crate::error::Result<()> {1144 assert_eval!(1145 r#"1146 std.objectFields({1147 a:{1148 [name]: name for name in std.objectFields(self)1149 },1150 b: 2,1151 c: 3,1152 }.a) == ['a', 'b', 'c']1153 "#1154 );11551156 Ok(())1157 }11581159 struct TestImportResolver(IStr);1160 impl crate::import::ImportResolver for TestImportResolver {1161 fn resolve_file(&self, _: &Path, _: &Path) -> crate::error::Result<Rc<Path>> {1162 Ok(PathBuf::from("/test").into())1163 }11641165 fn load_file_contents(&self, _: &Path) -> crate::error::Result<IStr> {1166 Ok(self.0.clone())1167 }11681169 unsafe fn as_any(&self) -> &dyn std::any::Any {1170 panic!()1171 }1172 }11731174 #[test]1175 fn issue_23() {1176 let state = EvaluationState::default();1177 state.set_import_resolver(Box::new(TestImportResolver(r#"import "/test""#.into())));1178 let _ = state.evaluate_file_raw(&PathBuf::from("/test"));1179 }11801181 #[test]1182 fn issue_40() {1183 let state = EvaluationState::default();1184 state.with_stdlib();11851186 let error = state1187 .evaluate_snippet_raw(1188 PathBuf::from("issue40.jsonnet").into(),1189 r#"1190 local conf = {1191 n: ""1192 };11931194 local result = conf + {1195 assert std.isNumber(self.n): "is number"1196 };11971198 std.manifestJsonEx(result, "")1199 "#1200 .into(),1201 )1202 .unwrap_err();1203 assert_eq!(error.error().to_string(), "assert failed: is number");1204 }12051206 #[test]1207 fn test_ascii_upper_lower() {1208 assert_eval!(r#"std.assertEqual(std.asciiUpper("aBc😀"), "ABC😀")"#);1209 assert_eval!(r#"std.assertEqual(std.asciiLower("aBc😀"), "abc😀")"#);1210 }12111212 #[test]1213 fn test_member() {1214 assert_eval!(r#"!std.member("", "")"#);1215 assert_eval!(r#"std.member("abc", "a")"#);1216 assert_eval!(r#"!std.member("abc", "d")"#);1217 assert_eval!(r#"!std.member([], "")"#);1218 assert_eval!(r#"std.member(["a", "b", "c"], "a")"#);1219 assert_eval!(r#"!std.member(["a", "b", "c"], "d")"#);1220 }12211222 #[test]1223 fn test_count() {1224 assert_eval!(r#"std.assertEqual(std.count([], ""), 0)"#);1225 assert_eval!(r#"std.assertEqual(std.count(["a", "b", "a"], "d"), 0)"#);1226 assert_eval!(r#"std.assertEqual(std.count(["a", "b", "a"], "a"), 2)"#);1227 }1228}1#![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)]78mod builtin;9mod ctx;10mod dynamic;11pub mod error;12mod evaluate;13mod function;14mod import;15mod integrations;16mod map;17pub mod native;18mod obj;19pub mod trace;20pub mod typed;21mod val;2223pub use ctx::*;24pub use dynamic::*;25use error::{Error::*, LocError, Result, StackTraceElement};26pub use evaluate::*;27pub use function::parse_function_call;28use gc::{GcHashMap, TraceBox};29use gcmodule::{Cc, Trace};30pub use import::*;31pub use jrsonnet_interner::IStr;32use jrsonnet_parser::*;33use native::NativeCallback;34pub use obj::*;35use std::{36 cell::{Ref, RefCell, RefMut},37 collections::HashMap,38 fmt::Debug,39 path::{Path, PathBuf},40 rc::Rc,41};42use trace::{location_to_offset, offset_to_location, CodeLocation, CompactFormat, TraceFormat};43pub use val::*;44pub mod gc;4546pub trait Bindable: Trace + 'static {47 fn bind(&self, this: Option<ObjValue>, super_obj: Option<ObjValue>) -> Result<LazyVal>;48}4950#[derive(Clone, Trace)]51pub enum LazyBinding {52 Bindable(Cc<TraceBox<dyn Bindable>>),53 Bound(LazyVal),54}5556impl Debug for LazyBinding {57 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {58 write!(f, "LazyBinding")59 }60}61impl LazyBinding {62 pub fn evaluate(&self, this: Option<ObjValue>, super_obj: Option<ObjValue>) -> Result<LazyVal> {63 match self {64 Self::Bindable(v) => v.bind(this, super_obj),65 Self::Bound(v) => Ok(v.clone()),66 }67 }68}6970pub struct EvaluationSettings {71 /// Limits recursion by limiting the number of stack frames72 pub max_stack: usize,73 /// Limits amount of stack trace items preserved74 pub max_trace: usize,75 /// Used for s`td.extVar`76 pub ext_vars: HashMap<IStr, Val>,77 /// Used for ext.native78 pub ext_natives: HashMap<IStr, Cc<NativeCallback>>,79 /// TLA vars80 pub tla_vars: HashMap<IStr, Val>,81 /// Global variables are inserted in default context82 pub globals: HashMap<IStr, Val>,83 /// Used to resolve file locations/contents84 pub import_resolver: Box<dyn ImportResolver>,85 /// Used in manifestification functions86 pub manifest_format: ManifestFormat,87 /// Used for bindings88 pub trace_format: Box<dyn TraceFormat>,89}90impl Default for EvaluationSettings {91 fn default() -> Self {92 Self {93 max_stack: 200,94 max_trace: 20,95 globals: Default::default(),96 ext_vars: Default::default(),97 ext_natives: Default::default(),98 tla_vars: Default::default(),99 import_resolver: Box::new(DummyImportResolver),100 manifest_format: ManifestFormat::Json(4),101 trace_format: Box::new(CompactFormat {102 padding: 4,103 resolver: trace::PathResolver::Absolute,104 }),105 }106 }107}108109#[derive(Default)]110struct EvaluationData {111 /// Used for stack overflow detection, stacktrace is populated on unwind112 stack_depth: usize,113 /// Updated every time stack entry is popt114 stack_generation: usize,115116 breakpoints: Breakpoints,117 /// Contains file source codes and evaluation results for imports and pretty-printed stacktraces118 files: HashMap<Rc<Path>, FileData>,119 str_files: HashMap<Rc<Path>, IStr>,120}121122pub struct FileData {123 source_code: IStr,124 parsed: LocExpr,125 evaluated: Option<Val>,126}127128#[allow(clippy::type_complexity)]129pub struct Breakpoint {130 loc: ExprLocation,131 collected: RefCell<HashMap<usize, (usize, Vec<Result<Val>>)>>,132}133#[derive(Default)]134struct Breakpoints(Vec<Rc<Breakpoint>>);135impl Breakpoints {136 fn insert(137 &self,138 stack_depth: usize,139 stack_generation: usize,140 loc: &ExprLocation,141 result: Result<Val>,142 ) -> Result<Val> {143 if self.0.is_empty() {144 return result;145 }146 for item in self.0.iter() {147 if item.loc.belongs_to(loc) {148 let mut collected = item.collected.borrow_mut();149 let (depth, vals) = collected.entry(stack_generation).or_default();150 if stack_depth > *depth {151 vals.clear();152 }153 vals.push(result.clone());154 }155 }156 result157 }158}159160#[derive(Default)]161pub struct EvaluationStateInternals {162 /// Internal state163 data: RefCell<EvaluationData>,164 /// Settings, safe to change at runtime165 settings: RefCell<EvaluationSettings>,166}167168thread_local! {169 /// Contains the state for a currently executed file.170 /// Global state is fine here.171 pub(crate) static EVAL_STATE: RefCell<Option<EvaluationState>> = RefCell::new(None)172}173pub(crate) fn with_state<T>(f: impl FnOnce(&EvaluationState) -> T) -> T {174 EVAL_STATE.with(|s| f(s.borrow().as_ref().unwrap()))175}176pub(crate) fn push_frame<T>(177 e: &ExprLocation,178 frame_desc: impl FnOnce() -> String,179 f: impl FnOnce() -> Result<T>,180) -> Result<T> {181 with_state(|s| s.push(e, frame_desc, f))182}183184#[allow(dead_code)]185pub(crate) fn push_val_frame(186 e: &ExprLocation,187 frame_desc: impl FnOnce() -> String,188 f: impl FnOnce() -> Result<Val>,189) -> Result<Val> {190 with_state(|s| s.push_val(e, frame_desc, f))191}192#[allow(dead_code)]193pub(crate) fn push_description_frame<T>(194 frame_desc: impl FnOnce() -> String,195 f: impl FnOnce() -> Result<T>,196) -> Result<T> {197 with_state(|s| s.push_description(frame_desc, f))198}199200/// Maintains stack trace and import resolution201#[derive(Default, Clone)]202pub struct EvaluationState(Rc<EvaluationStateInternals>);203204impl EvaluationState {205 /// Parses and adds file as loaded206 pub fn add_file(&self, path: Rc<Path>, source_code: IStr) -> Result<()> {207 self.add_parsed_file(208 path.clone(),209 source_code.clone(),210 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,220 })?,221 )?;222223 Ok(())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: &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: Some(e.clone()),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_map(510 self.create_default_context(),511 &self.settings().tla_vars,512 true,513 )514 },515 )?,516 v => v,517 })518 })519 }520}521522/// Internals523impl EvaluationState {524 fn data(&self) -> Ref<EvaluationData> {525 self.0.data.borrow()526 }527 fn data_mut(&self) -> RefMut<EvaluationData> {528 self.0.data.borrow_mut()529 }530 pub fn settings(&self) -> Ref<EvaluationSettings> {531 self.0.settings.borrow()532 }533 pub fn settings_mut(&self) -> RefMut<EvaluationSettings> {534 self.0.settings.borrow_mut()535 }536}537538/// Raw methods evaluate passed values but don't perform TLA execution539impl EvaluationState {540 pub fn evaluate_file_raw(&self, name: &Path) -> Result<Val> {541 self.run_in_state(|| self.import_file(&std::env::current_dir().expect("cwd"), name))542 }543 pub fn evaluate_file_raw_nocwd(&self, name: &Path) -> Result<Val> {544 self.run_in_state(|| self.import_file(&PathBuf::from("."), name))545 }546 /// Parses and evaluates the given snippet547 pub fn evaluate_snippet_raw(&self, source: Rc<Path>, code: IStr) -> Result<Val> {548 let parsed = parse(549 &code,550 &ParserSettings {551 file_name: source.clone(),552 },553 )554 .map_err(|e| ImportSyntaxError {555 path: source.clone(),556 source_code: code.clone(),557 error: Box::new(e),558 })?;559 self.add_parsed_file(source, code, parsed.clone())?;560 self.evaluate_expr_raw(parsed)561 }562 /// Evaluates the parsed expression563 pub fn evaluate_expr_raw(&self, code: LocExpr) -> Result<Val> {564 self.run_in_state(|| evaluate(self.create_default_context(), &code))565 }566}567568/// Settings utilities569impl EvaluationState {570 pub fn add_ext_var(&self, name: IStr, value: Val) {571 self.settings_mut().ext_vars.insert(name, value);572 }573 pub fn add_ext_str(&self, name: IStr, value: IStr) {574 self.add_ext_var(name, Val::Str(value));575 }576 pub fn add_ext_code(&self, name: IStr, code: IStr) -> Result<()> {577 let value =578 self.evaluate_snippet_raw(PathBuf::from(format!("ext_code {}", name)).into(), code)?;579 self.add_ext_var(name, value);580 Ok(())581 }582583 pub fn add_tla(&self, name: IStr, value: Val) {584 self.settings_mut().tla_vars.insert(name, value);585 }586 pub fn add_tla_str(&self, name: IStr, value: IStr) {587 self.add_tla(name, Val::Str(value));588 }589 pub fn add_tla_code(&self, name: IStr, code: IStr) -> Result<()> {590 let value =591 self.evaluate_snippet_raw(PathBuf::from(format!("tla_code {}", name)).into(), code)?;592 self.add_tla(name, value);593 Ok(())594 }595596 pub fn resolve_file(&self, from: &Path, path: &Path) -> Result<Rc<Path>> {597 self.settings().import_resolver.resolve_file(from, path)598 }599 pub fn load_file_contents(&self, path: &Path) -> Result<IStr> {600 self.settings().import_resolver.load_file_contents(path)601 }602603 pub fn import_resolver(&self) -> Ref<dyn ImportResolver> {604 Ref::map(self.settings(), |s| &*s.import_resolver)605 }606 pub fn set_import_resolver(&self, resolver: Box<dyn ImportResolver>) {607 self.settings_mut().import_resolver = resolver;608 }609610 pub fn add_native(&self, name: IStr, cb: Cc<NativeCallback>) {611 self.settings_mut().ext_natives.insert(name, cb);612 }613614 pub fn manifest_format(&self) -> ManifestFormat {615 self.settings().manifest_format.clone()616 }617 pub fn set_manifest_format(&self, format: ManifestFormat) {618 self.settings_mut().manifest_format = format;619 }620621 pub fn trace_format(&self) -> Ref<dyn TraceFormat> {622 Ref::map(self.settings(), |s| &*s.trace_format)623 }624 pub fn set_trace_format(&self, format: Box<dyn TraceFormat>) {625 self.settings_mut().trace_format = format;626 }627628 pub fn max_trace(&self) -> usize {629 self.settings().max_trace630 }631 pub fn set_max_trace(&self, trace: usize) {632 self.settings_mut().max_trace = trace;633 }634635 pub fn max_stack(&self) -> usize {636 self.settings().max_stack637 }638 pub fn set_max_stack(&self, trace: usize) {639 self.settings_mut().max_stack = trace;640 }641}642643pub fn cc_ptr_eq<T>(a: &Cc<T>, b: &Cc<T>) -> bool {644 let a = a as &T;645 let b = b as &T;646 std::ptr::eq(a, b)647}648649#[cfg(test)]650pub mod tests {651 use super::Val;652 use crate::{653 error::Error::*, gc::TraceBox, native::NativeCallbackHandler, primitive_equals,654 EvaluationState,655 };656 use gcmodule::{Cc, Trace};657 use jrsonnet_interner::IStr;658 use jrsonnet_parser::*;659 use std::{660 path::{Path, PathBuf},661 rc::Rc,662 };663664 #[test]665 #[should_panic]666 fn eval_state_stacktrace() {667 let state = EvaluationState::default();668 state.run_in_state(|| {669 state670 .push(671 &ExprLocation(PathBuf::from("test1.jsonnet").into(), 10, 20),672 || "outer".to_owned(),673 || {674 state.push(675 &ExprLocation(PathBuf::from("test2.jsonnet").into(), 30, 40),676 || "inner".to_owned(),677 || Err(RuntimeError("".into()).into()),678 )?;679 Ok(Val::Null)680 },681 )682 .unwrap();683 });684 }685686 #[test]687 fn eval_state_standard() {688 let state = EvaluationState::default();689 state.with_stdlib();690 assert!(primitive_equals(691 &state692 .evaluate_snippet_raw(693 PathBuf::from("raw.jsonnet").into(),694 r#"std.assertEqual(std.base64("test"), "dGVzdA==")"#.into()695 )696 .unwrap(),697 &Val::Bool(true),698 )699 .unwrap());700 }701702 macro_rules! eval {703 ($str: expr) => {704 EvaluationState::default()705 .with_stdlib()706 .evaluate_snippet_raw(PathBuf::from("raw.jsonnet").into(), $str.into())707 .unwrap()708 };709 }710 macro_rules! eval_json {711 ($str: expr) => {{712 let evaluator = EvaluationState::default();713 evaluator.with_stdlib();714 evaluator.run_in_state(|| {715 evaluator716 .evaluate_snippet_raw(PathBuf::from("raw.jsonnet").into(), $str.into())717 .unwrap()718 .to_json(0)719 .unwrap()720 .replace("\n", "")721 })722 }};723 }724725 /// Asserts given code returns `true`726 macro_rules! assert_eval {727 ($str: expr) => {728 assert!(primitive_equals(&eval!($str), &Val::Bool(true)).unwrap())729 };730 }731732 /// Asserts given code returns `false`733 macro_rules! assert_eval_neg {734 ($str: expr) => {735 assert!(primitive_equals(&eval!($str), &Val::Bool(false)).unwrap())736 };737 }738 macro_rules! assert_json {739 ($str: expr, $out: expr) => {740 assert_eq!(eval_json!($str), $out.replace("\t", ""))741 };742 }743744 /// Sanity checking, before trusting to another tests745 #[test]746 fn equality_operator() {747 assert_eval!("2 == 2");748 assert_eval_neg!("2 != 2");749 assert_eval!("2 != 3");750 assert_eval_neg!("2 == 3");751 assert_eval!("'Hello' == 'Hello'");752 assert_eval_neg!("'Hello' != 'Hello'");753 assert_eval!("'Hello' != 'World'");754 assert_eval_neg!("'Hello' == 'World'");755 }756757 #[test]758 fn math_evaluation() {759 assert_eval!("2 + 2 * 2 == 6");760 assert_eval!("3 + (2 + 2 * 2) == 9");761 }762763 #[test]764 fn string_concat() {765 assert_eval!("'Hello' + 'World' == 'HelloWorld'");766 assert_eval!("'Hello' * 3 == 'HelloHelloHello'");767 assert_eval!("'Hello' + 'World' * 3 == 'HelloWorldWorldWorld'");768 }769770 #[test]771 fn faster_join() {772 assert_eval!("std.join([0,0], [[1,2],[3,4],[5,6]]) == [1,2,0,0,3,4,0,0,5,6]");773 assert_eval!("std.join(',', ['1','2','3','4']) == '1,2,3,4'");774 }775776 #[test]777 fn function_contexts() {778 assert_eval!(779 r#"780 local k = {781 t(name = self.h): [self.h, name],782 h: 3,783 };784 local f = {785 t: k.t(),786 h: 4,787 };788 f.t[0] == f.t[1]789 "#790 );791 }792793 #[test]794 fn local() {795 assert_eval!("local a = 2; local b = 3; a + b == 5");796 assert_eval!("local a = 1, b = a + 1; a + b == 3");797 assert_eval!("local a = 1; local a = 2; a == 2");798 }799800 #[test]801 fn object_lazyness() {802 assert_json!("local a = {a:error 'test'}; {}", r#"{}"#);803 }804805 #[test]806 fn object_inheritance() {807 assert_json!("{a: self.b} + {b:3}", r#"{"a": 3,"b": 3}"#);808 }809810 #[test]811 fn object_assertion_success() {812 eval!("{assert \"a\" in self} + {a:2}");813 }814815 #[test]816 fn object_assertion_error() {817 eval!("{assert \"a\" in self}");818 }819820 #[test]821 fn lazy_args() {822 eval!("local test(a) = 2; test(error '3')");823 }824825 #[test]826 #[should_panic]827 fn tailstrict_args() {828 eval!("local test(a) = 2; test(error '3') tailstrict");829 }830831 #[test]832 #[should_panic]833 fn no_binding_error() {834 eval!("a");835 }836837 #[test]838 fn test_object() {839 assert_json!("{a:2}", r#"{"a": 2}"#);840 assert_json!("{a:2+2}", r#"{"a": 4}"#);841 assert_json!("{a:2}+{b:2}", r#"{"a": 2,"b": 2}"#);842 assert_json!("{b:3}+{b:2}", r#"{"b": 2}"#);843 assert_json!("{b:3}+{b+:2}", r#"{"b": 5}"#);844 assert_json!("local test='a'; {[test]:2}", r#"{"a": 2}"#);845 assert_json!(846 r#"847 {848 name: "Alice",849 welcome: "Hello " + self.name + "!",850 }851 "#,852 r#"{"name": "Alice","welcome": "Hello Alice!"}"#853 );854 assert_json!(855 r#"856 {857 name: "Alice",858 welcome: "Hello " + self.name + "!",859 } + {860 name: "Bob"861 }862 "#,863 r#"{"name": "Bob","welcome": "Hello Bob!"}"#864 );865 }866867 #[test]868 fn functions() {869 assert_json!(r#"local a = function(b, c = 2) b + c; a(2)"#, "4");870 assert_json!(871 r#"local a = function(b, c = "Dear") b + c + d, d = "World"; a("Hello")"#,872 r#""HelloDearWorld""#873 );874 }875876 #[test]877 fn local_methods() {878 assert_json!(r#"local a(b, c = 2) = b + c; a(2)"#, "4");879 assert_json!(880 r#"local a(b, c = "Dear") = b + c + d, d = "World"; a("Hello")"#,881 r#""HelloDearWorld""#882 );883 }884885 #[test]886 fn object_locals() {887 assert_json!(r#"{local a = 3, b: a}"#, r#"{"b": 3}"#);888 assert_json!(r#"{local a = 3, local c = a, b: c}"#, r#"{"b": 3}"#);889 assert_json!(890 r#"{local a = function (b) {[b]:4}, test: a("test")}"#,891 r#"{"test": {"test": 4}}"#892 );893 }894895 #[test]896 fn object_comp() {897 assert_json!(898 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}"#,899 "{\"h1_2\": \"0a\",\"h1_3\": \"0a\",\"h1_4\": \"0a\",\"h2_3\": \"a1\",\"h2_4\": \"a1\",\"h3_2\": \"0a\",\"h3_4\": \"a1\"}"900 )901 }902903 #[test]904 fn direct_self() {905 println!(906 "{:#?}",907 eval!(908 r#"909 {910 local me = self,911 a: 3,912 b(): me.a,913 }914 "#915 )916 );917 }918919 #[test]920 fn indirect_self() {921 // `self` assigned to `me` was lost when being922 // referenced from field923 eval!(924 r#"{925 local me = self,926 a: 3,927 b: me.a,928 }.b"#929 );930 }931932 // We can't trust other tests (And official jsonnet testsuite), if assert is not working correctly933 #[test]934 fn std_assert_ok() {935 eval!("std.assertEqual(4.5 << 2, 16)");936 }937938 #[test]939 #[should_panic]940 fn std_assert_failure() {941 eval!("std.assertEqual(4.5 << 2, 15)");942 }943944 #[test]945 fn string_is_string() {946 assert!(primitive_equals(947 &eval!("local arr = 'hello'; (!std.isArray(arr)) && (!std.isString(arr))"),948 &Val::Bool(false),949 )950 .unwrap());951 }952953 #[test]954 fn base64_works() {955 assert_json!(r#"std.base64("test")"#, r#""dGVzdA==""#);956 }957958 #[test]959 fn utf8_chars() {960 assert_json!(961 r#"local c="😎";{c:std.codepoint(c),l:std.length(c)}"#,962 r#"{"c": 128526,"l": 1}"#963 )964 }965966 #[test]967 fn json() {968 assert_json!(969 r#"std.manifestJsonEx({a:3, b:4, c:6},"")"#,970 r#""{\n\"a\": 3,\n\"b\": 4,\n\"c\": 6\n}""#971 );972 }973974 #[test]975 fn parse_json() {976 assert_json!(977 r#"std.parseJson('{"a": -1,"b": 1,"c": 3.141,"d": []}')"#,978 r#"{"a": -1,"b": 1,"c": 3.141,"d": []}"#979 );980 // TODO: this should in fact fail as is no proper JSON syntax981 assert_json!(982 r#"std.parseJson("{a:-1, b:1, c:3.141, d:[]}")"#,983 r#"{"a": -1,"b": 1,"c": 3.141,"d": []}"#984 );985 // TODO: this is also no valid JSON986 assert_json!(r#"std.parseJson('local x = 2; x * x')"#, r#"4"#);987 }988989 #[test]990 fn test() {991 assert_json!(992 r#"[[a, b] for a in [1,2,3] for b in [4,5,6]]"#,993 "[[1,4],[1,5],[1,6],[2,4],[2,5],[2,6],[3,4],[3,5],[3,6]]"994 );995 }996997 #[test]998 fn sjsonnet() {999 eval!(1000 r#"1001 local x0 = {k: 1};1002 local x1 = {k: x0.k + x0.k};1003 local x2 = {k: x1.k + x1.k};1004 local x3 = {k: x2.k + x2.k};1005 local x4 = {k: x3.k + x3.k};1006 local x5 = {k: x4.k + x4.k};1007 local x6 = {k: x5.k + x5.k};1008 local x7 = {k: x6.k + x6.k};1009 local x8 = {k: x7.k + x7.k};1010 local x9 = {k: x8.k + x8.k};1011 local x10 = {k: x9.k + x9.k};1012 local x11 = {k: x10.k + x10.k};1013 local x12 = {k: x11.k + x11.k};1014 local x13 = {k: x12.k + x12.k};1015 local x14 = {k: x13.k + x13.k};1016 local x15 = {k: x14.k + x14.k};1017 local x16 = {k: x15.k + x15.k};1018 local x17 = {k: x16.k + x16.k};1019 local x18 = {k: x17.k + x17.k};1020 local x19 = {k: x18.k + x18.k};1021 local x20 = {k: x19.k + x19.k};1022 local x21 = {k: x20.k + x20.k};1023 x21.k1024 "#1025 );1026 }10271028 // This test is commented out by default, because of huge compilation slowdown1029 // #[bench]1030 // fn bench_codegen(b: &mut Bencher) {1031 // b.iter(|| {1032 // #[allow(clippy::all)]1033 // let stdlib = {1034 // use jrsonnet_parser::*;1035 // include!(concat!(env!("OUT_DIR"), "/stdlib.rs"))1036 // };1037 // stdlib1038 // })1039 // }10401041 /*1042 #[bench]1043 fn bench_serialize(b: &mut Bencher) {1044 b.iter(|| {1045 bincode::deserialize::<jrsonnet_parser::LocExpr>(include_bytes!(concat!(1046 env!("OUT_DIR"),1047 "/stdlib.bincode"1048 )))1049 .expect("deserialize stdlib")1050 })1051 }10521053 #[bench]1054 fn bench_parse(b: &mut Bencher) {1055 b.iter(|| {1056 jrsonnet_parser::parse(1057 jrsonnet_stdlib::STDLIB_STR,1058 &jrsonnet_parser::ParserSettings {1059 loc_data: true,1060 file_name: Rc::new(PathBuf::from("std.jsonnet")),1061 },1062 )1063 })1064 }1065 */10661067 #[test]1068 fn equality() {1069 println!(1070 "{:?}",1071 jrsonnet_parser::parse(1072 "{ x: 1, y: 2 } == { x: 1, y: 2 }",1073 &ParserSettings {1074 file_name: PathBuf::from("equality").into(),1075 }1076 )1077 );1078 assert_eval!("{ x: 1, y: 2 } == { x: 1, y: 2 }")1079 }10801081 #[test]1082 fn native_ext() -> crate::error::Result<()> {1083 use super::native::NativeCallback;1084 let evaluator = EvaluationState::default();10851086 evaluator.with_stdlib();10871088 #[derive(Trace)]1089 struct NativeAdd;1090 impl NativeCallbackHandler for NativeAdd {1091 fn call(&self, from: Rc<Path>, args: &[Val]) -> crate::error::Result<Val> {1092 assert_eq!(&from as &Path, &PathBuf::from("native_caller.jsonnet"));1093 match (&args[0], &args[1]) {1094 (Val::Num(a), Val::Num(b)) => Ok(Val::Num(a + b)),1095 (_, _) => unreachable!(),1096 }1097 }1098 }1099 evaluator.settings_mut().ext_natives.insert(1100 "native_add".into(),1101 Cc::new(NativeCallback::new(1102 ParamsDesc(Rc::new(vec![1103 Param("a".into(), None),1104 Param("b".into(), None),1105 ])),1106 TraceBox(Box::new(NativeAdd)),1107 )),1108 );1109 evaluator.evaluate_snippet_raw(1110 PathBuf::from("native_caller.jsonnet").into(),1111 "std.assertEqual(std.native(\"native_add\")(1, 2), 3)".into(),1112 )?;1113 Ok(())1114 }11151116 #[test]1117 fn constant_intrinsic() -> crate::error::Result<()> {1118 assert_eval!(1119 "local std2 = std; local std = std2 { primitiveEquals(a, b):: false }; 1 == 1"1120 );1121 Ok(())1122 }11231124 #[test]1125 fn standalone_super() -> crate::error::Result<()> {1126 assert_eval!(1127 r#"1128 local obj = {1129 a: 1,1130 b: 2,1131 c: 3,1132 };1133 local test = obj + {1134 fields: std.objectFields(super),1135 d: 5,1136 };1137 test.fields == ['a', 'b', 'c']1138 "#1139 );1140 Ok(())1141 }11421143 #[test]1144 fn comp_self() -> crate::error::Result<()> {1145 assert_eval!(1146 r#"1147 std.objectFields({1148 a:{1149 [name]: name for name in std.objectFields(self)1150 },1151 b: 2,1152 c: 3,1153 }.a) == ['a', 'b', 'c']1154 "#1155 );11561157 Ok(())1158 }11591160 struct TestImportResolver(IStr);1161 impl crate::import::ImportResolver for TestImportResolver {1162 fn resolve_file(&self, _: &Path, _: &Path) -> crate::error::Result<Rc<Path>> {1163 Ok(PathBuf::from("/test").into())1164 }11651166 fn load_file_contents(&self, _: &Path) -> crate::error::Result<IStr> {1167 Ok(self.0.clone())1168 }11691170 unsafe fn as_any(&self) -> &dyn std::any::Any {1171 panic!()1172 }1173 }11741175 #[test]1176 fn issue_23() {1177 let state = EvaluationState::default();1178 state.set_import_resolver(Box::new(TestImportResolver(r#"import "/test""#.into())));1179 let _ = state.evaluate_file_raw(&PathBuf::from("/test"));1180 }11811182 #[test]1183 fn issue_40() {1184 let state = EvaluationState::default();1185 state.with_stdlib();11861187 let error = state1188 .evaluate_snippet_raw(1189 PathBuf::from("issue40.jsonnet").into(),1190 r#"1191 local conf = {1192 n: ""1193 };11941195 local result = conf + {1196 assert std.isNumber(self.n): "is number"1197 };11981199 std.manifestJsonEx(result, "")1200 "#1201 .into(),1202 )1203 .unwrap_err();1204 assert_eq!(error.error().to_string(), "assert failed: is number");1205 }12061207 #[test]1208 fn test_ascii_upper_lower() {1209 assert_eval!(r#"std.assertEqual(std.asciiUpper("aBc😀"), "ABC😀")"#);1210 assert_eval!(r#"std.assertEqual(std.asciiLower("aBc😀"), "abc😀")"#);1211 }12121213 #[test]1214 fn test_member() {1215 assert_eval!(r#"!std.member("", "")"#);1216 assert_eval!(r#"std.member("abc", "a")"#);1217 assert_eval!(r#"!std.member("abc", "d")"#);1218 assert_eval!(r#"!std.member([], "")"#);1219 assert_eval!(r#"std.member(["a", "b", "c"], "a")"#);1220 assert_eval!(r#"!std.member(["a", "b", "c"], "d")"#);1221 }12221223 #[test]1224 fn test_count() {1225 assert_eval!(r#"std.assertEqual(std.count([], ""), 0)"#);1226 assert_eval!(r#"std.assertEqual(std.count(["a", "b", "a"], "d"), 0)"#);1227 assert_eval!(r#"std.assertEqual(std.count(["a", "b", "a"], "a"), 2)"#);1228 }1229}crates/jrsonnet-evaluator/src/obj.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/obj.rs
+++ b/crates/jrsonnet-evaluator/src/obj.rs
@@ -123,7 +123,7 @@
}
}
for (name, member) in self.0.this_entries.iter() {
- if handler(name, &member) {
+ if handler(name, member) {
return true;
}
}