git.delta.rocks / jrsonnet / refs/commits / ce2d8d503b4a

difftreelog

Merge pull request #19 from CertainLach/std-intrinsic

Yaroslav Bulyukin2020-10-20parents: #7e00c7d #0a096fe.patch.diff
in: master
Prevent changing meaning of std in desugared expressions

7 files changed

modifiedcrates/jrsonnet-evaluator/src/builtin/mod.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/builtin/mod.rs
+++ b/crates/jrsonnet-evaluator/src/builtin/mod.rs
@@ -20,13 +20,12 @@
 pub fn call_builtin(
 	context: Context,
 	loc: &Option<ExprLocation>,
-	ns: &str,
 	name: &str,
 	args: &ArgsDesc,
 ) -> Result<Val> {
-	Ok(match (ns, name as &str) {
+	Ok(match name as &str {
 		// arr/string/function
-		("std", "length") => parse_args!(context, "std.length", args, 1, [
+		"length" => parse_args!(context, "std.length", args, 1, [
 			0, x: [Val::Str|Val::Arr|Val::Obj], vec![ValType::Str, ValType::Arr, ValType::Obj];
 		], {
 			Ok(match x {
@@ -42,13 +41,13 @@
 			})
 		})?,
 		// any
-		("std", "type") => parse_args!(context, "std.type", args, 1, [
+		"type" => parse_args!(context, "std.type", args, 1, [
 			0, x, vec![];
 		], {
 			Ok(Val::Str(x.value_type()?.name().into()))
 		})?,
 		// length, idx=>any
-		("std", "makeArray") => parse_args!(context, "std.makeArray", args, 2, [
+		"makeArray" => parse_args!(context, "std.makeArray", args, 2, [
 			0, sz: [Val::Num]!!Val::Num, vec![ValType::Num];
 			1, func: [Val::Func]!!Val::Func, vec![ValType::Func];
 		], {
@@ -65,7 +64,7 @@
 			Ok(Val::Arr(Rc::new(out)))
 		})?,
 		// string
-		("std", "codepoint") => parse_args!(context, "std.codepoint", args, 1, [
+		"codepoint" => parse_args!(context, "std.codepoint", args, 1, [
 			0, str: [Val::Str]!!Val::Str, vec![ValType::Str];
 		], {
 			assert!(
@@ -75,7 +74,7 @@
 			Ok(Val::Num(str.chars().take(1).next().unwrap() as u32 as f64))
 		})?,
 		// object, includeHidden
-		("std", "objectFieldsEx") => parse_args!(context, "std.objectFieldsEx",args, 2, [
+		"objectFieldsEx" => parse_args!(context, "std.objectFieldsEx",args, 2, [
 			0, obj: [Val::Obj]!!Val::Obj, vec![ValType::Obj];
 			1, inc_hidden: [Val::Bool]!!Val::Bool, vec![ValType::Bool];
 		], {
@@ -88,7 +87,7 @@
 			Ok(Val::Arr(Rc::new(out.into_iter().map(Val::Str).collect())))
 		})?,
 		// object, field, includeHidden
-		("std", "objectHasEx") => parse_args!(context, "std.objectHasEx", args, 3, [
+		"objectHasEx" => parse_args!(context, "std.objectHasEx", args, 3, [
 			0, obj: [Val::Obj]!!Val::Obj, vec![ValType::Obj];
 			1, f: [Val::Str]!!Val::Str, vec![ValType::Str];
 			2, inc_hidden: [Val::Bool]!!Val::Bool, vec![ValType::Bool];
@@ -100,36 +99,36 @@
 					.any(|(k, _v)| *k == *f),
 			))
 		})?,
-		("std", "primitiveEquals") => parse_args!(context, "std.primitiveEquals", args, 2, [
+		"primitiveEquals" => parse_args!(context, "std.primitiveEquals", args, 2, [
 			0, a, vec![];
 			1, b, vec![];
 		], {
 			Ok(Val::Bool(primitive_equals(&a, &b)?))
 		})?,
 		// faster
-		("std", "equals") => parse_args!(context, "std.equals", args, 2, [
+		"equals" => parse_args!(context, "std.equals", args, 2, [
 			0, a, vec![];
 			1, b, vec![];
 		], {
 			Ok(Val::Bool(equals(&a, &b)?))
 		})?,
-		("std", "modulo") => parse_args!(context, "std.modulo", args, 2, [
+		"modulo" => parse_args!(context, "std.modulo", args, 2, [
 			0, a: [Val::Num]!!Val::Num, vec![ValType::Num];
 			1, b: [Val::Num]!!Val::Num, vec![ValType::Num];
 		], {
 			Ok(Val::Num(a % b))
 		})?,
-		("std", "floor") => parse_args!(context, "std.floor", args, 1, [
+		"floor" => parse_args!(context, "std.floor", args, 1, [
 			0, x: [Val::Num]!!Val::Num, vec![ValType::Num];
 		], {
 			Ok(Val::Num(x.floor()))
 		})?,
-		("std", "log") => parse_args!(context, "std.log", args, 2, [
+		"log" => parse_args!(context, "std.log", args, 2, [
 			0, n: [Val::Num]!!Val::Num, vec![ValType::Num];
 		], {
 			Ok(Val::Num(n.ln()))
 		})?,
-		("std", "trace") => parse_args!(context, "std.trace", args, 2, [
+		"trace" => parse_args!(context, "std.trace", args, 2, [
 			0, str: [Val::Str]!!Val::Str, vec![ValType::Str];
 			1, rest, vec![];
 		], {
@@ -143,27 +142,27 @@
 			eprintln!(" {}", str);
 			Ok(rest)
 		})?,
-		("std", "pow") => parse_args!(context, "std.modulo", args, 2, [
+		"pow" => parse_args!(context, "std.modulo", args, 2, [
 			0, x: [Val::Num]!!Val::Num, vec![ValType::Num];
 			1, n: [Val::Num]!!Val::Num, vec![ValType::Num];
 		], {
 			Ok(Val::Num(x.powf(n)))
 		})?,
-		("std", "extVar") => parse_args!(context, "std.extVar", args, 1, [
+		"extVar" => parse_args!(context, "std.extVar", args, 1, [
 			0, x: [Val::Str]!!Val::Str, vec![ValType::Str];
 		], {
 			Ok(with_state(|s| s.settings().ext_vars.get(&x).cloned()).ok_or_else(
 				|| UndefinedExternalVariable(x),
 			)?)
 		})?,
-		("std", "native") => parse_args!(context, "std.native", args, 1, [
+		"native" => parse_args!(context, "std.native", args, 1, [
 			0, x: [Val::Str]!!Val::Str, vec![ValType::Str];
 		], {
 			Ok(with_state(|s| s.settings().ext_natives.get(&x).cloned()).map(|v| Val::Func(Rc::new(FuncVal::NativeExt(x.clone(), v)))).ok_or_else(
 				|| UndefinedExternalFunction(x),
 			)?)
 		})?,
-		("std", "filter") => parse_args!(context, "std.filter", args, 2, [
+		"filter" => parse_args!(context, "std.filter", args, 2, [
 			0, func: [Val::Func]!!Val::Func, vec![ValType::Func];
 			1, arr: [Val::Arr]!!Val::Arr, vec![ValType::Arr];
 		], {
@@ -181,7 +180,7 @@
 			)))
 		})?,
 		// faster
-		("std", "foldl") => parse_args!(context, "std.foldl", args, 3, [
+		"foldl" => parse_args!(context, "std.foldl", args, 3, [
 			0, func: [Val::Func]!!Val::Func, vec![ValType::Func];
 			1, arr: [Val::Arr]!!Val::Arr, vec![ValType::Arr];
 			2, init, vec![];
@@ -193,7 +192,7 @@
 			Ok(acc)
 		})?,
 		// faster
-		("std", "foldr") => parse_args!(context, "std.foldr", args, 3, [
+		"foldr" => parse_args!(context, "std.foldr", args, 3, [
 			0, func: [Val::Func]!!Val::Func, vec![ValType::Func];
 			1, arr: [Val::Arr]!!Val::Arr, vec![ValType::Arr];
 			2, init, vec![];
@@ -206,7 +205,7 @@
 		})?,
 		// faster
 		#[allow(non_snake_case)]
-		("std", "sortImpl") => parse_args!(context, "std.sort", args, 2, [
+		"sortImpl" => parse_args!(context, "std.sort", args, 2, [
 			0, arr: [Val::Arr]!!Val::Arr, vec![ValType::Arr];
 			1, keyF: [Val::Func]!!Val::Func, vec![ValType::Func];
 		], {
@@ -216,7 +215,7 @@
 			Ok(Val::Arr(sort::sort(context, arr, &keyF)?))
 		})?,
 		// faster
-		("std", "format") => parse_args!(context, "std.format", args, 2, [
+		"format" => parse_args!(context, "std.format", args, 2, [
 			0, str: [Val::Str]!!Val::Str, vec![ValType::Str];
 			1, vals, vec![]
 		], {
@@ -229,7 +228,7 @@
 			})
 		})?,
 		// faster
-		("std", "range") => parse_args!(context, "std.range", args, 2, [
+		"range" => parse_args!(context, "std.range", args, 2, [
 			0, from: [Val::Num]!!Val::Num, vec![ValType::Num];
 			1, to: [Val::Num]!!Val::Num, vec![ValType::Num];
 		], {
@@ -239,7 +238,7 @@
 			}
 			Ok(Val::Arr(Rc::new(out)))
 		})?,
-		("std", "char") => parse_args!(context, "std.char", args, 1, [
+		"char" => parse_args!(context, "std.char", args, 1, [
 			0, n: [Val::Num]!!Val::Num, vec![ValType::Num];
 		], {
 			let mut out = String::new();
@@ -248,18 +247,18 @@
 			)?);
 			Ok(Val::Str(out.into()))
 		})?,
-		("std", "encodeUTF8") => parse_args!(context, "std.encodeUtf8", args, 1, [
+		"encodeUTF8" => parse_args!(context, "std.encodeUtf8", args, 1, [
 			0, str: [Val::Str]!!Val::Str, vec![ValType::Str];
 		], {
 			Ok(Val::Arr(Rc::new(str.bytes().map(|b| Val::Num(b as f64)).collect())))
 		})?,
-		("std", "md5") => parse_args!(context, "std.md5", args, 1, [
+		"md5" => parse_args!(context, "std.md5", args, 1, [
 			0, str: [Val::Str]!!Val::Str, vec![ValType::Str];
 		], {
 			Ok(Val::Str(format!("{:x}", md5::compute(&str.as_bytes())).into()))
 		})?,
 		// faster
-		("std", "base64") => parse_args!(context, "std.base64", args, 1, [
+		"base64" => parse_args!(context, "std.base64", args, 1, [
 			0, input: [Val::Str | Val::Arr], vec![ValType::Arr, ValType::Str];
 		], {
 			Ok(Val::Str(match input {
@@ -275,7 +274,7 @@
 			}))
 		})?,
 		// faster
-		("std", "join") => parse_args!(context, "std.join", args, 2, [
+		"join" => parse_args!(context, "std.join", args, 2, [
 			0, sep: [Val::Str|Val::Arr], vec![ValType::Str, ValType::Arr];
 			1, arr: [Val::Arr]!!Val::Arr, vec![ValType::Arr];
 		], {
@@ -322,13 +321,13 @@
 			})
 		})?,
 		// Faster
-		("std", "escapeStringJson") => parse_args!(context, "std.escapeStringJson", args, 1, [
+		"escapeStringJson" => parse_args!(context, "std.escapeStringJson", args, 1, [
 			0, str_: [Val::Str]!!Val::Str, vec![ValType::Str];
 		], {
 			Ok(Val::Str(escape_string_json(&str_).into()))
 		})?,
 		// Faster
-		("std", "manifestJsonEx") => parse_args!(context, "std.manifestJsonEx", args, 2, [
+		"manifestJsonEx" => parse_args!(context, "std.manifestJsonEx", args, 2, [
 			0, value, vec![];
 			1, indent: [Val::Str]!!Val::Str, vec![ValType::Str];
 		], {
@@ -338,18 +337,18 @@
 			})?.into()))
 		})?,
 		// Faster
-		("std", "reverse") => parse_args!(context, "std.reverse", args, 1, [
+		"reverse" => parse_args!(context, "std.reverse", args, 1, [
 			0, arr: [Val::Arr]!!Val::Arr, vec![ValType::Arr];
 		], {
 			let mut marr = arr;
 			Rc::make_mut(&mut marr).reverse();
 			Ok(Val::Arr(marr))
 		})?,
-		("std", "id") => parse_args!(context, "std.id", args, 1, [
+		"id" => parse_args!(context, "std.id", args, 1, [
 			0, v, vec![];
 		], {
 			Ok(v)
 		})?,
-		(ns, name) => throw!(IntrinsicNotFound(ns.into(), name.into())),
+		name => throw!(IntrinsicNotFound(name.into())),
 	})
 }
modifiedcrates/jrsonnet-evaluator/src/error.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/error.rs
+++ b/crates/jrsonnet-evaluator/src/error.rs
@@ -8,8 +8,8 @@
 
 #[derive(Error, Debug, Clone)]
 pub enum Error {
-	#[error("intrinsic not found: {0}.{1}")]
-	IntrinsicNotFound(Rc<str>, Rc<str>),
+	#[error("intrinsic not found: {0}")]
+	IntrinsicNotFound(Rc<str>),
 	#[error("argument reordering in intrisics not supported yet")]
 	IntrinsicArgumentReorderingIsNotSupportedYet,
 
modifiedcrates/jrsonnet-evaluator/src/evaluate.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/evaluate.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate.rs
@@ -466,10 +466,8 @@
 						|| {
 							if let Some(v) = v.get(s.clone())? {
 								Ok(v.unwrap_if_lazy()?)
-							} else if let Some(Val::Str(n)) =
-								v.get("__intrinsic_namespace__".into())?
-							{
-								Ok(Val::Func(Rc::new(FuncVal::Intrinsic(n, s))))
+							} else if v.get("__intrinsic_namespace__".into())?.is_some() {
+								Ok(Val::Func(Rc::new(FuncVal::Intrinsic(s))))
 							} else {
 								throw!(NoSuchField(s))
 							}
@@ -558,6 +556,7 @@
 		Function(params, body) => {
 			evaluate_method(context, "anonymous".into(), params.clone(), body.clone())
 		}
+		Intrinsic(name) => Val::Func(Rc::new(FuncVal::Intrinsic(name.clone()))),
 		AssertExpr(AssertStmt(value, msg), returned) => {
 			let assertion_result = push(
 				&value.1,
modifiedcrates/jrsonnet-evaluator/src/lib.rsdiffbeforeafterboth
before · crates/jrsonnet-evaluator/src/lib.rs
1#![cfg_attr(feature = "unstable", feature(stmt_expr_attributes))]2#![allow(macro_expanded_macro_exports_accessed_by_absolute_paths)]3#![warn(clippy::all, clippy::nursery)]45mod builtin;6mod ctx;7mod dynamic;8pub mod error;9mod evaluate;10mod function;11mod import;12mod integrations;13mod map;14pub mod native;15mod obj;16pub mod trace;17mod val;1819pub use ctx::*;20pub use dynamic::*;21use error::{Error::*, LocError, Result, StackTraceElement};22pub use evaluate::*;23pub use function::parse_function_call;24pub use import::*;25use jrsonnet_parser::*;26use native::NativeCallback;27pub use obj::*;28use std::{29	cell::{Ref, RefCell, RefMut},30	collections::HashMap,31	fmt::Debug,32	path::PathBuf,33	rc::Rc,34};35use trace::{offset_to_location, CodeLocation, CompactFormat, TraceFormat};36pub use val::*;3738type BindableFn = dyn Fn(Option<ObjValue>, Option<ObjValue>) -> Result<LazyVal>;39#[derive(Clone)]40pub enum LazyBinding {41	Bindable(Rc<BindableFn>),42	Bound(LazyVal),43}4445impl Debug for LazyBinding {46	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {47		write!(f, "LazyBinding")48	}49}50impl LazyBinding {51	pub fn evaluate(&self, this: Option<ObjValue>, super_obj: Option<ObjValue>) -> Result<LazyVal> {52		match self {53			Self::Bindable(v) => v(this, super_obj),54			Self::Bound(v) => Ok(v.clone()),55		}56	}57}5859pub struct EvaluationSettings {60	/// Limits recursion by limiting the number of stack frames61	pub max_stack: usize,62	/// Limits amount of stack trace items preserved63	pub max_trace: usize,64	/// Used for s`td.extVar`65	pub ext_vars: HashMap<Rc<str>, Val>,66	/// Used for ext.native67	pub ext_natives: HashMap<Rc<str>, Rc<NativeCallback>>,68	/// TLA vars69	pub tla_vars: HashMap<Rc<str>, Val>,70	/// Global variables are inserted in default context71	pub globals: HashMap<Rc<str>, Val>,72	/// Used to resolve file locations/contents73	pub import_resolver: Box<dyn ImportResolver>,74	/// Used in manifestification functions75	pub manifest_format: ManifestFormat,76	/// Used for bindings77	pub trace_format: Box<dyn TraceFormat>,78}79impl Default for EvaluationSettings {80	fn default() -> Self {81		Self {82			max_stack: 200,83			max_trace: 20,84			globals: Default::default(),85			ext_vars: Default::default(),86			ext_natives: Default::default(),87			tla_vars: Default::default(),88			import_resolver: Box::new(DummyImportResolver),89			manifest_format: ManifestFormat::Json(4),90			trace_format: Box::new(CompactFormat {91				padding: 4,92				resolver: trace::PathResolver::Absolute,93			}),94		}95	}96}9798#[derive(Default)]99struct EvaluationData {100	/// Used for stack overflow detection, stacktrace is populated on unwind101	stack_depth: usize,102	/// Contains file source codes and evaluation results for imports and pretty-printed stacktraces103	files: HashMap<Rc<PathBuf>, FileData>,104	str_files: HashMap<Rc<PathBuf>, Rc<str>>,105}106107pub struct FileData {108	source_code: Rc<str>,109	parsed: LocExpr,110	evaluated: Option<Val>,111}112#[derive(Default)]113pub struct EvaluationStateInternals {114	/// Internal state115	data: RefCell<EvaluationData>,116	/// Settings, safe to change at runtime117	settings: RefCell<EvaluationSettings>,118}119120thread_local! {121	/// Contains the state for a currently executed file.122	/// Global state is fine here.123	pub(crate) static EVAL_STATE: RefCell<Option<EvaluationState>> = RefCell::new(None)124}125pub(crate) fn with_state<T>(f: impl FnOnce(&EvaluationState) -> T) -> T {126	EVAL_STATE.with(|s| f(s.borrow().as_ref().unwrap()))127}128pub(crate) fn push<T>(129	e: &Option<ExprLocation>,130	frame_desc: impl FnOnce() -> String,131	f: impl FnOnce() -> Result<T>,132) -> Result<T> {133	if let Some(v) = e {134		with_state(|s| s.push(v, frame_desc, f))135	} else {136		f()137	}138}139140/// Maintains stack trace and import resolution141#[derive(Default, Clone)]142pub struct EvaluationState(Rc<EvaluationStateInternals>);143144impl EvaluationState {145	/// Parses and adds file as loaded146	pub fn add_file(&self, path: Rc<PathBuf>, source_code: Rc<str>) -> Result<()> {147		self.add_parsed_file(148			path.clone(),149			source_code.clone(),150			parse(151				&source_code,152				&ParserSettings {153					file_name: path.clone(),154					loc_data: true,155				},156			)157			.map_err(|error| ImportSyntaxError {158				error: Box::new(error),159				path,160				source_code,161			})?,162		)?;163164		Ok(())165	}166167	/// Adds file by source code and parsed expr168	pub fn add_parsed_file(169		&self,170		name: Rc<PathBuf>,171		source_code: Rc<str>,172		parsed: LocExpr,173	) -> Result<()> {174		self.data_mut().files.insert(175			name,176			FileData {177				source_code,178				parsed,179				evaluated: None,180			},181		);182183		Ok(())184	}185	pub fn get_source(&self, name: &PathBuf) -> Option<Rc<str>> {186		let ro_map = &self.data().files;187		ro_map.get(name).map(|value| value.source_code.clone())188	}189	pub fn map_source_locations(&self, file: &PathBuf, locs: &[usize]) -> Vec<CodeLocation> {190		offset_to_location(&self.get_source(file).unwrap(), locs)191	}192193	pub(crate) fn import_file(&self, from: &PathBuf, path: &PathBuf) -> Result<Val> {194		let file_path = self.resolve_file(from, path)?;195		{196			let files = &self.data().files;197			if files.contains_key(&file_path) {198				return self.evaluate_loaded_file_raw(&file_path);199			}200		}201		let contents = self.load_file_contents(&file_path)?;202		self.add_file(file_path.clone(), contents)?;203		self.evaluate_loaded_file_raw(&file_path)204	}205	pub(crate) fn import_file_str(&self, from: &PathBuf, path: &PathBuf) -> Result<Rc<str>> {206		let path = self.resolve_file(from, path)?;207		if !self.data().str_files.contains_key(&path) {208			let file_str = self.load_file_contents(&path)?;209			self.data_mut().str_files.insert(path.clone(), file_str);210		}211		Ok(self.data().str_files.get(&path).cloned().unwrap())212	}213214	fn evaluate_loaded_file_raw(&self, name: &PathBuf) -> Result<Val> {215		let expr: LocExpr = {216			let ro_map = &self.data().files;217			let value = ro_map218				.get(name)219				.unwrap_or_else(|| panic!("file not added: {:?}", name));220			if let Some(ref evaluated) = value.evaluated {221				return Ok(evaluated.clone());222			}223			value.parsed.clone()224		};225		let value = evaluate(self.create_default_context()?, &expr)?;226		{227			self.data_mut()228				.files229				.get_mut(name)230				.unwrap()231				.evaluated232				.replace(value.clone());233		}234		Ok(value)235	}236237	/// Adds standard library global variable (std) to this evaluator238	pub fn with_stdlib(&self) -> &Self {239		use jrsonnet_stdlib::STDLIB_STR;240		let std_path = Rc::new(PathBuf::from("std.jsonnet"));241		self.run_in_state(|| {242			self.add_parsed_file(243				std_path.clone(),244				STDLIB_STR.to_owned().into(),245				builtin::get_parsed_stdlib(),246			)247			.unwrap();248			let val = self.evaluate_loaded_file_raw(&std_path).unwrap();249			self.settings_mut().globals.insert("std".into(), val);250		});251		self252	}253254	/// Creates context with all passed global variables255	pub fn create_default_context(&self) -> Result<Context> {256		let globals = &self.settings().globals;257		let mut new_bindings: HashMap<Rc<str>, LazyBinding> = HashMap::new();258		for (name, value) in globals.iter() {259			new_bindings.insert(260				name.clone(),261				LazyBinding::Bound(resolved_lazy_val!(value.clone())),262			);263		}264		Context::new().extend_unbound(new_bindings, None, None, None)265	}266267	/// Executes code creating a new stack frame268	pub fn push<T>(269		&self,270		e: &ExprLocation,271		frame_desc: impl FnOnce() -> String,272		f: impl FnOnce() -> Result<T>,273	) -> Result<T> {274		{275			let mut data = self.data_mut();276			let stack_depth = &mut data.stack_depth;277			if *stack_depth > self.max_stack() {278				// Error creation uses data, so i drop guard here279				drop(data);280				throw!(StackOverflow);281			} else {282				*stack_depth += 1;283			}284		}285		let result = f();286		self.data_mut().stack_depth -= 1;287		if let Err(mut err) = result {288			err.trace_mut().0.push(StackTraceElement {289				location: e.clone(),290				desc: frame_desc(),291			});292			return Err(err);293		}294		result295	}296297	/// Runs passed function in state (required if function needs to modify stack trace)298	pub fn run_in_state<T>(&self, f: impl FnOnce() -> T) -> T {299		EVAL_STATE.with(|v| {300			let has_state = v.borrow().is_some();301			if !has_state {302				v.borrow_mut().replace(self.clone());303			}304			let result = f();305			if !has_state {306				v.borrow_mut().take();307			}308			result309		})310	}311312	pub fn stringify_err(&self, e: &LocError) -> String {313		let mut out = String::new();314		self.settings()315			.trace_format316			.write_trace(&mut out, self, e)317			.unwrap();318		out319	}320321	pub fn manifest(&self, val: Val) -> Result<Rc<str>> {322		self.run_in_state(|| val.manifest(&self.manifest_format()))323	}324	pub fn manifest_multi(&self, val: Val) -> Result<Vec<(Rc<str>, Rc<str>)>> {325		self.run_in_state(|| val.manifest_multi(&self.manifest_format()))326	}327	pub fn manifest_stream(&self, val: Val) -> Result<Vec<Rc<str>>> {328		self.run_in_state(|| val.manifest_stream(&self.manifest_format()))329	}330331	/// If passed value is function then call with set TLA332	pub fn with_tla(&self, val: Val) -> Result<Val> {333		self.run_in_state(|| {334			Ok(match val {335				Val::Func(func) => func.evaluate_map(336					self.create_default_context()?,337					&self.settings().tla_vars,338					true,339				)?,340				v => v,341			})342		})343	}344}345346/// Internals347impl EvaluationState {348	fn data(&self) -> Ref<EvaluationData> {349		self.0.data.borrow()350	}351	fn data_mut(&self) -> RefMut<EvaluationData> {352		self.0.data.borrow_mut()353	}354	pub fn settings(&self) -> Ref<EvaluationSettings> {355		self.0.settings.borrow()356	}357	pub fn settings_mut(&self) -> RefMut<EvaluationSettings> {358		self.0.settings.borrow_mut()359	}360}361362/// Raw methods evaluate passed values but don't perform TLA execution363impl EvaluationState {364	pub fn evaluate_file_raw(&self, name: &PathBuf) -> Result<Val> {365		self.run_in_state(|| self.import_file(&std::env::current_dir().expect("cwd"), name))366	}367	pub fn evaluate_file_raw_nocwd(&self, name: &PathBuf) -> Result<Val> {368		self.run_in_state(|| self.import_file(&PathBuf::from("."), name))369	}370	/// Parses and evaluates the given snippet371	pub fn evaluate_snippet_raw(&self, source: Rc<PathBuf>, code: Rc<str>) -> Result<Val> {372		let parsed = parse(373			&code,374			&ParserSettings {375				file_name: source.clone(),376				loc_data: true,377			},378		)379		.unwrap();380		self.add_parsed_file(source, code, parsed.clone())?;381		self.evaluate_expr_raw(parsed)382	}383	/// Evaluates the parsed expression384	pub fn evaluate_expr_raw(&self, code: LocExpr) -> Result<Val> {385		self.run_in_state(|| evaluate(self.create_default_context()?, &code))386	}387}388389/// Settings utilities390impl EvaluationState {391	pub fn add_ext_var(&self, name: Rc<str>, value: Val) {392		self.settings_mut().ext_vars.insert(name, value);393	}394	pub fn add_ext_str(&self, name: Rc<str>, value: Rc<str>) {395		self.add_ext_var(name, Val::Str(value));396	}397	pub fn add_ext_code(&self, name: Rc<str>, code: Rc<str>) -> Result<()> {398		let value =399			self.evaluate_snippet_raw(Rc::new(PathBuf::from(format!("ext_code {}", name))), code)?;400		self.add_ext_var(name, value);401		Ok(())402	}403404	pub fn add_tla(&self, name: Rc<str>, value: Val) {405		self.settings_mut().tla_vars.insert(name, value);406	}407	pub fn add_tla_str(&self, name: Rc<str>, value: Rc<str>) {408		self.add_tla(name, Val::Str(value));409	}410	pub fn add_tla_code(&self, name: Rc<str>, code: Rc<str>) -> Result<()> {411		let value =412			self.evaluate_snippet_raw(Rc::new(PathBuf::from(format!("tla_code {}", name))), code)?;413		self.add_tla(name, value);414		Ok(())415	}416417	pub fn resolve_file(&self, from: &PathBuf, path: &PathBuf) -> Result<Rc<PathBuf>> {418		Ok(self.settings().import_resolver.resolve_file(from, path)?)419	}420	pub fn load_file_contents(&self, path: &PathBuf) -> Result<Rc<str>> {421		Ok(self.settings().import_resolver.load_file_contents(path)?)422	}423424	pub fn import_resolver(&self) -> Ref<dyn ImportResolver> {425		Ref::map(self.settings(), |s| &*s.import_resolver)426	}427	pub fn set_import_resolver(&self, resolver: Box<dyn ImportResolver>) {428		self.settings_mut().import_resolver = resolver;429	}430431	pub fn add_native(&self, name: Rc<str>, cb: Rc<NativeCallback>) {432		self.settings_mut().ext_natives.insert(name, cb);433	}434435	pub fn manifest_format(&self) -> ManifestFormat {436		self.settings().manifest_format.clone()437	}438	pub fn set_manifest_format(&self, format: ManifestFormat) {439		self.settings_mut().manifest_format = format;440	}441442	pub fn trace_format(&self) -> Ref<dyn TraceFormat> {443		Ref::map(self.settings(), |s| &*s.trace_format)444	}445	pub fn set_trace_format(&self, format: Box<dyn TraceFormat>) {446		self.settings_mut().trace_format = format;447	}448449	pub fn max_trace(&self) -> usize {450		self.settings().max_trace451	}452	pub fn set_max_trace(&self, trace: usize) {453		self.settings_mut().max_trace = trace;454	}455456	pub fn max_stack(&self) -> usize {457		self.settings().max_stack458	}459	pub fn set_max_stack(&self, trace: usize) {460		self.settings_mut().max_stack = trace;461	}462}463464#[cfg(test)]465pub mod tests {466	use super::Val;467	use crate::{error::Error::*, primitive_equals, EvaluationState};468	use jrsonnet_parser::*;469	use std::{path::PathBuf, rc::Rc};470471	#[test]472	#[should_panic]473	fn eval_state_stacktrace() {474		let state = EvaluationState::default();475		state.run_in_state(|| {476			state477				.push(478					&ExprLocation(Rc::new(PathBuf::from("test1.jsonnet")), 10, 20),479					|| "outer".to_owned(),480					|| {481						state.push(482							&ExprLocation(Rc::new(PathBuf::from("test2.jsonnet")), 30, 40),483							|| "inner".to_owned(),484							|| Err(RuntimeError("".into()).into()),485						)?;486						Ok(())487					},488				)489				.unwrap();490		});491	}492493	#[test]494	fn eval_state_standard() {495		let state = EvaluationState::default();496		state.with_stdlib();497		assert!(primitive_equals(498			&state499				.evaluate_snippet_raw(500					Rc::new(PathBuf::from("raw.jsonnet")),501					r#"std.assertEqual(std.base64("test"), "dGVzdA==")"#.into()502				)503				.unwrap(),504			&Val::Bool(true),505		)506		.unwrap());507	}508509	macro_rules! eval {510		($str: expr) => {511			EvaluationState::default()512				.with_stdlib()513				.evaluate_snippet_raw(Rc::new(PathBuf::from("raw.jsonnet")), $str.into())514				.unwrap()515		};516	}517	macro_rules! eval_json {518		($str: expr) => {{519			let evaluator = EvaluationState::default();520			evaluator.with_stdlib();521			evaluator.run_in_state(|| {522				evaluator523					.evaluate_snippet_raw(Rc::new(PathBuf::from("raw.jsonnet")), $str.into())524					.unwrap()525					.to_json(0)526					.unwrap()527					.replace("\n", "")528				})529			}};530	}531532	/// Asserts given code returns `true`533	macro_rules! assert_eval {534		($str: expr) => {535			assert!(primitive_equals(&eval!($str), &Val::Bool(true)).unwrap())536		};537	}538539	/// Asserts given code returns `false`540	macro_rules! assert_eval_neg {541		($str: expr) => {542			assert!(primitive_equals(&eval!($str), &Val::Bool(false)).unwrap())543		};544	}545	macro_rules! assert_json {546		($str: expr, $out: expr) => {547			assert_eq!(eval_json!($str), $out.replace("\t", ""))548		};549	}550551	/// Sanity checking, before trusting to another tests552	#[test]553	fn equality_operator() {554		assert_eval!("2 == 2");555		assert_eval_neg!("2 != 2");556		assert_eval!("2 != 3");557		assert_eval_neg!("2 == 3");558		assert_eval!("'Hello' == 'Hello'");559		assert_eval_neg!("'Hello' != 'Hello'");560		assert_eval!("'Hello' != 'World'");561		assert_eval_neg!("'Hello' == 'World'");562	}563564	#[test]565	fn math_evaluation() {566		assert_eval!("2 + 2 * 2 == 6");567		assert_eval!("3 + (2 + 2 * 2) == 9");568	}569570	#[test]571	fn string_concat() {572		assert_eval!("'Hello' + 'World' == 'HelloWorld'");573		assert_eval!("'Hello' * 3 == 'HelloHelloHello'");574		assert_eval!("'Hello' + 'World' * 3 == 'HelloWorldWorldWorld'");575	}576577	#[test]578	fn faster_join() {579		assert_eval!("std.join([0,0], [[1,2],[3,4],[5,6]]) == [1,2,0,0,3,4,0,0,5,6]");580		assert_eval!("std.join(',', ['1','2','3','4']) == '1,2,3,4'");581	}582583	#[test]584	fn function_contexts() {585		assert_eval!(586			r#"587				local k = {588					t(name = self.h): [self.h, name],589					h: 3,590				};591				local f = {592					t: k.t(),593					h: 4,594				};595				f.t[0] == f.t[1]596			"#597		);598	}599600	#[test]601	fn local() {602		assert_eval!("local a = 2; local b = 3; a + b == 5");603		assert_eval!("local a = 1, b = a + 1; a + b == 3");604		assert_eval!("local a = 1; local a = 2; a == 2");605	}606607	#[test]608	fn object_lazyness() {609		assert_json!("local a = {a:error 'test'}; {}", r#"{}"#);610	}611612	#[test]613	fn object_inheritance() {614		assert_json!("{a: self.b} + {b:3}", r#"{"a": 3,"b": 3}"#);615	}616617	#[test]618	fn object_assertion_success() {619		eval!("{assert \"a\" in self} + {a:2}");620	}621622	#[test]623	fn object_assertion_error() {624		eval!("{assert \"a\" in self}");625	}626627	#[test]628	fn lazy_args() {629		eval!("local test(a) = 2; test(error '3')");630	}631632	#[test]633	#[should_panic]634	fn tailstrict_args() {635		eval!("local test(a) = 2; test(error '3') tailstrict");636	}637638	#[test]639	#[should_panic]640	fn no_binding_error() {641		eval!("a");642	}643644	#[test]645	fn test_object() {646		assert_json!("{a:2}", r#"{"a": 2}"#);647		assert_json!("{a:2+2}", r#"{"a": 4}"#);648		assert_json!("{a:2}+{b:2}", r#"{"a": 2,"b": 2}"#);649		assert_json!("{b:3}+{b:2}", r#"{"b": 2}"#);650		assert_json!("{b:3}+{b+:2}", r#"{"b": 5}"#);651		assert_json!("local test='a'; {[test]:2}", r#"{"a": 2}"#);652		assert_json!(653			r#"654				{655					name: "Alice",656					welcome: "Hello " + self.name + "!",657				}658			"#,659			r#"{"name": "Alice","welcome": "Hello Alice!"}"#660		);661		assert_json!(662			r#"663				{664					name: "Alice",665					welcome: "Hello " + self.name + "!",666				} + {667					name: "Bob"668				}669			"#,670			r#"{"name": "Bob","welcome": "Hello Bob!"}"#671		);672	}673674	#[test]675	fn functions() {676		assert_json!(r#"local a = function(b, c = 2) b + c; a(2)"#, "4");677		assert_json!(678			r#"local a = function(b, c = "Dear") b + c + d, d = "World"; a("Hello")"#,679			r#""HelloDearWorld""#680		);681	}682683	#[test]684	fn local_methods() {685		assert_json!(r#"local a(b, c = 2) = b + c; a(2)"#, "4");686		assert_json!(687			r#"local a(b, c = "Dear") = b + c + d, d = "World"; a("Hello")"#,688			r#""HelloDearWorld""#689		);690	}691692	#[test]693	fn object_locals() {694		assert_json!(r#"{local a = 3, b: a}"#, r#"{"b": 3}"#);695		assert_json!(r#"{local a = 3, local c = a, b: c}"#, r#"{"b": 3}"#);696		assert_json!(697			r#"{local a = function (b) {[b]:4}, test: a("test")}"#,698			r#"{"test": {"test": 4}}"#699		);700	}701702	#[test]703	fn object_comp() {704		assert_json!(705			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}"#,706			"{\"h1_2\": \"0a\",\"h1_3\": \"0a\",\"h1_4\": \"0a\",\"h2_3\": \"a1\",\"h2_4\": \"a1\",\"h3_2\": \"0a\",\"h3_4\": \"a1\"}"707		)708	}709710	#[test]711	fn direct_self() {712		println!(713			"{:#?}",714			eval!(715				r#"716					{717						local me = self,718						a: 3,719						b(): me.a,720					}721				"#722			)723		);724	}725726	#[test]727	fn indirect_self() {728		// `self` assigned to `me` was lost when being729		// referenced from field730		eval!(731			r#"{732				local me = self,733				a: 3,734				b: me.a,735			}.b"#736		);737	}738739	// We can't trust other tests (And official jsonnet testsuite), if assert is not working correctly740	#[test]741	fn std_assert_ok() {742		eval!("std.assertEqual(4.5 << 2, 16)");743	}744745	#[test]746	#[should_panic]747	fn std_assert_failure() {748		eval!("std.assertEqual(4.5 << 2, 15)");749	}750751	#[test]752	fn string_is_string() {753		assert!(primitive_equals(754			&eval!("local arr = 'hello'; (!std.isArray(arr)) && (!std.isString(arr))"),755			&Val::Bool(false),756		)757		.unwrap());758	}759760	#[test]761	fn base64_works() {762		assert_json!(r#"std.base64("test")"#, r#""dGVzdA==""#);763	}764765	#[test]766	fn utf8_chars() {767		assert_json!(768			r#"local c="😎";{c:std.codepoint(c),l:std.length(c)}"#,769			r#"{"c": 128526,"l": 1}"#770		)771	}772773	#[test]774	fn json() {775		assert_json!(776			r#"std.manifestJsonEx({a:3, b:4, c:6},"")"#,777			r#""{\n\"a\": 3,\n\"b\": 4,\n\"c\": 6\n}""#778		);779	}780781	#[test]782	fn test() {783		assert_json!(784			r#"[[a, b] for a in [1,2,3] for b in [4,5,6]]"#,785			"[[1,4],[1,5],[1,6],[2,4],[2,5],[2,6],[3,4],[3,5],[3,6]]"786		);787	}788789	#[test]790	fn sjsonnet() {791		eval!(792			r#"793			local x0 = {k: 1};794			local x1 = {k: x0.k + x0.k};795			local x2 = {k: x1.k + x1.k};796			local x3 = {k: x2.k + x2.k};797			local x4 = {k: x3.k + x3.k};798			local x5 = {k: x4.k + x4.k};799			local x6 = {k: x5.k + x5.k};800			local x7 = {k: x6.k + x6.k};801			local x8 = {k: x7.k + x7.k};802			local x9 = {k: x8.k + x8.k};803			local x10 = {k: x9.k + x9.k};804			local x11 = {k: x10.k + x10.k};805			local x12 = {k: x11.k + x11.k};806			local x13 = {k: x12.k + x12.k};807			local x14 = {k: x13.k + x13.k};808			local x15 = {k: x14.k + x14.k};809			local x16 = {k: x15.k + x15.k};810			local x17 = {k: x16.k + x16.k};811			local x18 = {k: x17.k + x17.k};812			local x19 = {k: x18.k + x18.k};813			local x20 = {k: x19.k + x19.k};814			local x21 = {k: x20.k + x20.k};815			x21.k816		"#817		);818	}819820	// This test is commented out by default, because of huge compilation slowdown821	// #[bench]822	// fn bench_codegen(b: &mut Bencher) {823	// 	b.iter(|| {824	// 		#[allow(clippy::all)]825	// 		let stdlib = {826	// 			use jrsonnet_parser::*;827	// 			include!(concat!(env!("OUT_DIR"), "/stdlib.rs"))828	// 		};829	// 		stdlib830	// 	})831	// }832833	/*834	#[bench]835	fn bench_serialize(b: &mut Bencher) {836		b.iter(|| {837			bincode::deserialize::<jrsonnet_parser::LocExpr>(include_bytes!(concat!(838				env!("OUT_DIR"),839				"/stdlib.bincode"840			)))841			.expect("deserialize stdlib")842		})843	}844845	#[bench]846	fn bench_parse(b: &mut Bencher) {847		b.iter(|| {848			jrsonnet_parser::parse(849				jrsonnet_stdlib::STDLIB_STR,850				&jrsonnet_parser::ParserSettings {851					loc_data: true,852					file_name: Rc::new(PathBuf::from("std.jsonnet")),853				},854			)855		})856	}857	*/858859	#[test]860	fn equality() {861		println!(862			"{:?}",863			jrsonnet_parser::parse(864				"{ x: 1, y: 2 } == { x: 1, y: 2 }",865				&ParserSettings::default()866			)867		);868		assert_eval!("{ x: 1, y: 2 } == { x: 1, y: 2 }")869	}870871	#[test]872	fn native_ext() -> crate::error::Result<()> {873		use super::native::NativeCallback;874		let evaluator = EvaluationState::default();875876		evaluator.with_stdlib();877		evaluator.settings_mut().ext_natives.insert(878			"native_add".into(),879			Rc::new(NativeCallback::new(880				ParamsDesc(Rc::new(vec![881					Param("a".into(), None),882					Param("b".into(), None),883				])),884				|args| match (&args[0], &args[1]) {885					(Val::Num(a), Val::Num(b)) => Ok(Val::Num(a + b)),886					(_, _) => todo!(),887				},888			)),889		);890		evaluator.evaluate_snippet_raw(891			Rc::new(PathBuf::from("test.jsonnet")),892			"std.assertEqual(std.native(\"native_add\")(1, 2), 3)".into(),893		)?;894		Ok(())895	}896}
after · crates/jrsonnet-evaluator/src/lib.rs
1#![cfg_attr(feature = "unstable", feature(stmt_expr_attributes))]2#![allow(macro_expanded_macro_exports_accessed_by_absolute_paths)]3#![warn(clippy::all, clippy::nursery)]45mod builtin;6mod ctx;7mod dynamic;8pub mod error;9mod evaluate;10mod function;11mod import;12mod integrations;13mod map;14pub mod native;15mod obj;16pub mod trace;17mod val;1819pub use ctx::*;20pub use dynamic::*;21use error::{Error::*, LocError, Result, StackTraceElement};22pub use evaluate::*;23pub use function::parse_function_call;24pub use import::*;25use jrsonnet_parser::*;26use native::NativeCallback;27pub use obj::*;28use std::{29	cell::{Ref, RefCell, RefMut},30	collections::HashMap,31	fmt::Debug,32	path::PathBuf,33	rc::Rc,34};35use trace::{offset_to_location, CodeLocation, CompactFormat, TraceFormat};36pub use val::*;3738type BindableFn = dyn Fn(Option<ObjValue>, Option<ObjValue>) -> Result<LazyVal>;39#[derive(Clone)]40pub enum LazyBinding {41	Bindable(Rc<BindableFn>),42	Bound(LazyVal),43}4445impl Debug for LazyBinding {46	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {47		write!(f, "LazyBinding")48	}49}50impl LazyBinding {51	pub fn evaluate(&self, this: Option<ObjValue>, super_obj: Option<ObjValue>) -> Result<LazyVal> {52		match self {53			Self::Bindable(v) => v(this, super_obj),54			Self::Bound(v) => Ok(v.clone()),55		}56	}57}5859pub struct EvaluationSettings {60	/// Limits recursion by limiting the number of stack frames61	pub max_stack: usize,62	/// Limits amount of stack trace items preserved63	pub max_trace: usize,64	/// Used for s`td.extVar`65	pub ext_vars: HashMap<Rc<str>, Val>,66	/// Used for ext.native67	pub ext_natives: HashMap<Rc<str>, Rc<NativeCallback>>,68	/// TLA vars69	pub tla_vars: HashMap<Rc<str>, Val>,70	/// Global variables are inserted in default context71	pub globals: HashMap<Rc<str>, Val>,72	/// Used to resolve file locations/contents73	pub import_resolver: Box<dyn ImportResolver>,74	/// Used in manifestification functions75	pub manifest_format: ManifestFormat,76	/// Used for bindings77	pub trace_format: Box<dyn TraceFormat>,78}79impl Default for EvaluationSettings {80	fn default() -> Self {81		Self {82			max_stack: 200,83			max_trace: 20,84			globals: Default::default(),85			ext_vars: Default::default(),86			ext_natives: Default::default(),87			tla_vars: Default::default(),88			import_resolver: Box::new(DummyImportResolver),89			manifest_format: ManifestFormat::Json(4),90			trace_format: Box::new(CompactFormat {91				padding: 4,92				resolver: trace::PathResolver::Absolute,93			}),94		}95	}96}9798#[derive(Default)]99struct EvaluationData {100	/// Used for stack overflow detection, stacktrace is populated on unwind101	stack_depth: usize,102	/// Contains file source codes and evaluation results for imports and pretty-printed stacktraces103	files: HashMap<Rc<PathBuf>, FileData>,104	str_files: HashMap<Rc<PathBuf>, Rc<str>>,105}106107pub struct FileData {108	source_code: Rc<str>,109	parsed: LocExpr,110	evaluated: Option<Val>,111}112#[derive(Default)]113pub struct EvaluationStateInternals {114	/// Internal state115	data: RefCell<EvaluationData>,116	/// Settings, safe to change at runtime117	settings: RefCell<EvaluationSettings>,118}119120thread_local! {121	/// Contains the state for a currently executed file.122	/// Global state is fine here.123	pub(crate) static EVAL_STATE: RefCell<Option<EvaluationState>> = RefCell::new(None)124}125pub(crate) fn with_state<T>(f: impl FnOnce(&EvaluationState) -> T) -> T {126	EVAL_STATE.with(|s| f(s.borrow().as_ref().unwrap()))127}128pub(crate) fn push<T>(129	e: &Option<ExprLocation>,130	frame_desc: impl FnOnce() -> String,131	f: impl FnOnce() -> Result<T>,132) -> Result<T> {133	if let Some(v) = e {134		with_state(|s| s.push(v, frame_desc, f))135	} else {136		f()137	}138}139140/// Maintains stack trace and import resolution141#[derive(Default, Clone)]142pub struct EvaluationState(Rc<EvaluationStateInternals>);143144impl EvaluationState {145	/// Parses and adds file as loaded146	pub fn add_file(&self, path: Rc<PathBuf>, source_code: Rc<str>) -> Result<()> {147		self.add_parsed_file(148			path.clone(),149			source_code.clone(),150			parse(151				&source_code,152				&ParserSettings {153					file_name: path.clone(),154					loc_data: true,155				},156			)157			.map_err(|error| ImportSyntaxError {158				error: Box::new(error),159				path,160				source_code,161			})?,162		)?;163164		Ok(())165	}166167	/// Adds file by source code and parsed expr168	pub fn add_parsed_file(169		&self,170		name: Rc<PathBuf>,171		source_code: Rc<str>,172		parsed: LocExpr,173	) -> Result<()> {174		self.data_mut().files.insert(175			name,176			FileData {177				source_code,178				parsed,179				evaluated: None,180			},181		);182183		Ok(())184	}185	pub fn get_source(&self, name: &PathBuf) -> Option<Rc<str>> {186		let ro_map = &self.data().files;187		ro_map.get(name).map(|value| value.source_code.clone())188	}189	pub fn map_source_locations(&self, file: &PathBuf, locs: &[usize]) -> Vec<CodeLocation> {190		offset_to_location(&self.get_source(file).unwrap(), locs)191	}192193	pub(crate) fn import_file(&self, from: &PathBuf, path: &PathBuf) -> Result<Val> {194		let file_path = self.resolve_file(from, path)?;195		{196			let files = &self.data().files;197			if files.contains_key(&file_path) {198				return self.evaluate_loaded_file_raw(&file_path);199			}200		}201		let contents = self.load_file_contents(&file_path)?;202		self.add_file(file_path.clone(), contents)?;203		self.evaluate_loaded_file_raw(&file_path)204	}205	pub(crate) fn import_file_str(&self, from: &PathBuf, path: &PathBuf) -> Result<Rc<str>> {206		let path = self.resolve_file(from, path)?;207		if !self.data().str_files.contains_key(&path) {208			let file_str = self.load_file_contents(&path)?;209			self.data_mut().str_files.insert(path.clone(), file_str);210		}211		Ok(self.data().str_files.get(&path).cloned().unwrap())212	}213214	fn evaluate_loaded_file_raw(&self, name: &PathBuf) -> Result<Val> {215		let expr: LocExpr = {216			let ro_map = &self.data().files;217			let value = ro_map218				.get(name)219				.unwrap_or_else(|| panic!("file not added: {:?}", name));220			if let Some(ref evaluated) = value.evaluated {221				return Ok(evaluated.clone());222			}223			value.parsed.clone()224		};225		let value = evaluate(self.create_default_context()?, &expr)?;226		{227			self.data_mut()228				.files229				.get_mut(name)230				.unwrap()231				.evaluated232				.replace(value.clone());233		}234		Ok(value)235	}236237	/// Adds standard library global variable (std) to this evaluator238	pub fn with_stdlib(&self) -> &Self {239		use jrsonnet_stdlib::STDLIB_STR;240		let std_path = Rc::new(PathBuf::from("std.jsonnet"));241		self.run_in_state(|| {242			self.add_parsed_file(243				std_path.clone(),244				STDLIB_STR.to_owned().into(),245				builtin::get_parsed_stdlib(),246			)247			.unwrap();248			let val = self.evaluate_loaded_file_raw(&std_path).unwrap();249			self.settings_mut().globals.insert("std".into(), val);250		});251		self252	}253254	/// Creates context with all passed global variables255	pub fn create_default_context(&self) -> Result<Context> {256		let globals = &self.settings().globals;257		let mut new_bindings: HashMap<Rc<str>, LazyBinding> = HashMap::new();258		for (name, value) in globals.iter() {259			new_bindings.insert(260				name.clone(),261				LazyBinding::Bound(resolved_lazy_val!(value.clone())),262			);263		}264		Context::new().extend_unbound(new_bindings, None, None, None)265	}266267	/// Executes code creating a new stack frame268	pub fn push<T>(269		&self,270		e: &ExprLocation,271		frame_desc: impl FnOnce() -> String,272		f: impl FnOnce() -> Result<T>,273	) -> Result<T> {274		{275			let mut data = self.data_mut();276			let stack_depth = &mut data.stack_depth;277			if *stack_depth > self.max_stack() {278				// Error creation uses data, so i drop guard here279				drop(data);280				throw!(StackOverflow);281			} else {282				*stack_depth += 1;283			}284		}285		let result = f();286		self.data_mut().stack_depth -= 1;287		if let Err(mut err) = result {288			err.trace_mut().0.push(StackTraceElement {289				location: e.clone(),290				desc: frame_desc(),291			});292			return Err(err);293		}294		result295	}296297	/// Runs passed function in state (required if function needs to modify stack trace)298	pub fn run_in_state<T>(&self, f: impl FnOnce() -> T) -> T {299		EVAL_STATE.with(|v| {300			let has_state = v.borrow().is_some();301			if !has_state {302				v.borrow_mut().replace(self.clone());303			}304			let result = f();305			if !has_state {306				v.borrow_mut().take();307			}308			result309		})310	}311312	pub fn stringify_err(&self, e: &LocError) -> String {313		let mut out = String::new();314		self.settings()315			.trace_format316			.write_trace(&mut out, self, e)317			.unwrap();318		out319	}320321	pub fn manifest(&self, val: Val) -> Result<Rc<str>> {322		self.run_in_state(|| val.manifest(&self.manifest_format()))323	}324	pub fn manifest_multi(&self, val: Val) -> Result<Vec<(Rc<str>, Rc<str>)>> {325		self.run_in_state(|| val.manifest_multi(&self.manifest_format()))326	}327	pub fn manifest_stream(&self, val: Val) -> Result<Vec<Rc<str>>> {328		self.run_in_state(|| val.manifest_stream(&self.manifest_format()))329	}330331	/// If passed value is function then call with set TLA332	pub fn with_tla(&self, val: Val) -> Result<Val> {333		self.run_in_state(|| {334			Ok(match val {335				Val::Func(func) => func.evaluate_map(336					self.create_default_context()?,337					&self.settings().tla_vars,338					true,339				)?,340				v => v,341			})342		})343	}344}345346/// Internals347impl EvaluationState {348	fn data(&self) -> Ref<EvaluationData> {349		self.0.data.borrow()350	}351	fn data_mut(&self) -> RefMut<EvaluationData> {352		self.0.data.borrow_mut()353	}354	pub fn settings(&self) -> Ref<EvaluationSettings> {355		self.0.settings.borrow()356	}357	pub fn settings_mut(&self) -> RefMut<EvaluationSettings> {358		self.0.settings.borrow_mut()359	}360}361362/// Raw methods evaluate passed values but don't perform TLA execution363impl EvaluationState {364	pub fn evaluate_file_raw(&self, name: &PathBuf) -> Result<Val> {365		self.run_in_state(|| self.import_file(&std::env::current_dir().expect("cwd"), name))366	}367	pub fn evaluate_file_raw_nocwd(&self, name: &PathBuf) -> Result<Val> {368		self.run_in_state(|| self.import_file(&PathBuf::from("."), name))369	}370	/// Parses and evaluates the given snippet371	pub fn evaluate_snippet_raw(&self, source: Rc<PathBuf>, code: Rc<str>) -> Result<Val> {372		let parsed = parse(373			&code,374			&ParserSettings {375				file_name: source.clone(),376				loc_data: true,377			},378		)379		.unwrap();380		self.add_parsed_file(source, code, parsed.clone())?;381		self.evaluate_expr_raw(parsed)382	}383	/// Evaluates the parsed expression384	pub fn evaluate_expr_raw(&self, code: LocExpr) -> Result<Val> {385		self.run_in_state(|| evaluate(self.create_default_context()?, &code))386	}387}388389/// Settings utilities390impl EvaluationState {391	pub fn add_ext_var(&self, name: Rc<str>, value: Val) {392		self.settings_mut().ext_vars.insert(name, value);393	}394	pub fn add_ext_str(&self, name: Rc<str>, value: Rc<str>) {395		self.add_ext_var(name, Val::Str(value));396	}397	pub fn add_ext_code(&self, name: Rc<str>, code: Rc<str>) -> Result<()> {398		let value =399			self.evaluate_snippet_raw(Rc::new(PathBuf::from(format!("ext_code {}", name))), code)?;400		self.add_ext_var(name, value);401		Ok(())402	}403404	pub fn add_tla(&self, name: Rc<str>, value: Val) {405		self.settings_mut().tla_vars.insert(name, value);406	}407	pub fn add_tla_str(&self, name: Rc<str>, value: Rc<str>) {408		self.add_tla(name, Val::Str(value));409	}410	pub fn add_tla_code(&self, name: Rc<str>, code: Rc<str>) -> Result<()> {411		let value =412			self.evaluate_snippet_raw(Rc::new(PathBuf::from(format!("tla_code {}", name))), code)?;413		self.add_tla(name, value);414		Ok(())415	}416417	pub fn resolve_file(&self, from: &PathBuf, path: &PathBuf) -> Result<Rc<PathBuf>> {418		Ok(self.settings().import_resolver.resolve_file(from, path)?)419	}420	pub fn load_file_contents(&self, path: &PathBuf) -> Result<Rc<str>> {421		Ok(self.settings().import_resolver.load_file_contents(path)?)422	}423424	pub fn import_resolver(&self) -> Ref<dyn ImportResolver> {425		Ref::map(self.settings(), |s| &*s.import_resolver)426	}427	pub fn set_import_resolver(&self, resolver: Box<dyn ImportResolver>) {428		self.settings_mut().import_resolver = resolver;429	}430431	pub fn add_native(&self, name: Rc<str>, cb: Rc<NativeCallback>) {432		self.settings_mut().ext_natives.insert(name, cb);433	}434435	pub fn manifest_format(&self) -> ManifestFormat {436		self.settings().manifest_format.clone()437	}438	pub fn set_manifest_format(&self, format: ManifestFormat) {439		self.settings_mut().manifest_format = format;440	}441442	pub fn trace_format(&self) -> Ref<dyn TraceFormat> {443		Ref::map(self.settings(), |s| &*s.trace_format)444	}445	pub fn set_trace_format(&self, format: Box<dyn TraceFormat>) {446		self.settings_mut().trace_format = format;447	}448449	pub fn max_trace(&self) -> usize {450		self.settings().max_trace451	}452	pub fn set_max_trace(&self, trace: usize) {453		self.settings_mut().max_trace = trace;454	}455456	pub fn max_stack(&self) -> usize {457		self.settings().max_stack458	}459	pub fn set_max_stack(&self, trace: usize) {460		self.settings_mut().max_stack = trace;461	}462}463464#[cfg(test)]465pub mod tests {466	use super::Val;467	use crate::{error::Error::*, primitive_equals, EvaluationState};468	use jrsonnet_parser::*;469	use std::{path::PathBuf, rc::Rc};470471	#[test]472	#[should_panic]473	fn eval_state_stacktrace() {474		let state = EvaluationState::default();475		state.run_in_state(|| {476			state477				.push(478					&ExprLocation(Rc::new(PathBuf::from("test1.jsonnet")), 10, 20),479					|| "outer".to_owned(),480					|| {481						state.push(482							&ExprLocation(Rc::new(PathBuf::from("test2.jsonnet")), 30, 40),483							|| "inner".to_owned(),484							|| Err(RuntimeError("".into()).into()),485						)?;486						Ok(())487					},488				)489				.unwrap();490		});491	}492493	#[test]494	fn eval_state_standard() {495		let state = EvaluationState::default();496		state.with_stdlib();497		assert!(primitive_equals(498			&state499				.evaluate_snippet_raw(500					Rc::new(PathBuf::from("raw.jsonnet")),501					r#"std.assertEqual(std.base64("test"), "dGVzdA==")"#.into()502				)503				.unwrap(),504			&Val::Bool(true),505		)506		.unwrap());507	}508509	macro_rules! eval {510		($str: expr) => {511			EvaluationState::default()512				.with_stdlib()513				.evaluate_snippet_raw(Rc::new(PathBuf::from("raw.jsonnet")), $str.into())514				.unwrap()515		};516	}517	macro_rules! eval_json {518		($str: expr) => {{519			let evaluator = EvaluationState::default();520			evaluator.with_stdlib();521			evaluator.run_in_state(|| {522				evaluator523					.evaluate_snippet_raw(Rc::new(PathBuf::from("raw.jsonnet")), $str.into())524					.unwrap()525					.to_json(0)526					.unwrap()527					.replace("\n", "")528				})529			}};530	}531532	/// Asserts given code returns `true`533	macro_rules! assert_eval {534		($str: expr) => {535			assert!(primitive_equals(&eval!($str), &Val::Bool(true)).unwrap())536		};537	}538539	/// Asserts given code returns `false`540	macro_rules! assert_eval_neg {541		($str: expr) => {542			assert!(primitive_equals(&eval!($str), &Val::Bool(false)).unwrap())543		};544	}545	macro_rules! assert_json {546		($str: expr, $out: expr) => {547			assert_eq!(eval_json!($str), $out.replace("\t", ""))548		};549	}550551	/// Sanity checking, before trusting to another tests552	#[test]553	fn equality_operator() {554		assert_eval!("2 == 2");555		assert_eval_neg!("2 != 2");556		assert_eval!("2 != 3");557		assert_eval_neg!("2 == 3");558		assert_eval!("'Hello' == 'Hello'");559		assert_eval_neg!("'Hello' != 'Hello'");560		assert_eval!("'Hello' != 'World'");561		assert_eval_neg!("'Hello' == 'World'");562	}563564	#[test]565	fn math_evaluation() {566		assert_eval!("2 + 2 * 2 == 6");567		assert_eval!("3 + (2 + 2 * 2) == 9");568	}569570	#[test]571	fn string_concat() {572		assert_eval!("'Hello' + 'World' == 'HelloWorld'");573		assert_eval!("'Hello' * 3 == 'HelloHelloHello'");574		assert_eval!("'Hello' + 'World' * 3 == 'HelloWorldWorldWorld'");575	}576577	#[test]578	fn faster_join() {579		assert_eval!("std.join([0,0], [[1,2],[3,4],[5,6]]) == [1,2,0,0,3,4,0,0,5,6]");580		assert_eval!("std.join(',', ['1','2','3','4']) == '1,2,3,4'");581	}582583	#[test]584	fn function_contexts() {585		assert_eval!(586			r#"587				local k = {588					t(name = self.h): [self.h, name],589					h: 3,590				};591				local f = {592					t: k.t(),593					h: 4,594				};595				f.t[0] == f.t[1]596			"#597		);598	}599600	#[test]601	fn local() {602		assert_eval!("local a = 2; local b = 3; a + b == 5");603		assert_eval!("local a = 1, b = a + 1; a + b == 3");604		assert_eval!("local a = 1; local a = 2; a == 2");605	}606607	#[test]608	fn object_lazyness() {609		assert_json!("local a = {a:error 'test'}; {}", r#"{}"#);610	}611612	#[test]613	fn object_inheritance() {614		assert_json!("{a: self.b} + {b:3}", r#"{"a": 3,"b": 3}"#);615	}616617	#[test]618	fn object_assertion_success() {619		eval!("{assert \"a\" in self} + {a:2}");620	}621622	#[test]623	fn object_assertion_error() {624		eval!("{assert \"a\" in self}");625	}626627	#[test]628	fn lazy_args() {629		eval!("local test(a) = 2; test(error '3')");630	}631632	#[test]633	#[should_panic]634	fn tailstrict_args() {635		eval!("local test(a) = 2; test(error '3') tailstrict");636	}637638	#[test]639	#[should_panic]640	fn no_binding_error() {641		eval!("a");642	}643644	#[test]645	fn test_object() {646		assert_json!("{a:2}", r#"{"a": 2}"#);647		assert_json!("{a:2+2}", r#"{"a": 4}"#);648		assert_json!("{a:2}+{b:2}", r#"{"a": 2,"b": 2}"#);649		assert_json!("{b:3}+{b:2}", r#"{"b": 2}"#);650		assert_json!("{b:3}+{b+:2}", r#"{"b": 5}"#);651		assert_json!("local test='a'; {[test]:2}", r#"{"a": 2}"#);652		assert_json!(653			r#"654				{655					name: "Alice",656					welcome: "Hello " + self.name + "!",657				}658			"#,659			r#"{"name": "Alice","welcome": "Hello Alice!"}"#660		);661		assert_json!(662			r#"663				{664					name: "Alice",665					welcome: "Hello " + self.name + "!",666				} + {667					name: "Bob"668				}669			"#,670			r#"{"name": "Bob","welcome": "Hello Bob!"}"#671		);672	}673674	#[test]675	fn functions() {676		assert_json!(r#"local a = function(b, c = 2) b + c; a(2)"#, "4");677		assert_json!(678			r#"local a = function(b, c = "Dear") b + c + d, d = "World"; a("Hello")"#,679			r#""HelloDearWorld""#680		);681	}682683	#[test]684	fn local_methods() {685		assert_json!(r#"local a(b, c = 2) = b + c; a(2)"#, "4");686		assert_json!(687			r#"local a(b, c = "Dear") = b + c + d, d = "World"; a("Hello")"#,688			r#""HelloDearWorld""#689		);690	}691692	#[test]693	fn object_locals() {694		assert_json!(r#"{local a = 3, b: a}"#, r#"{"b": 3}"#);695		assert_json!(r#"{local a = 3, local c = a, b: c}"#, r#"{"b": 3}"#);696		assert_json!(697			r#"{local a = function (b) {[b]:4}, test: a("test")}"#,698			r#"{"test": {"test": 4}}"#699		);700	}701702	#[test]703	fn object_comp() {704		assert_json!(705			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}"#,706			"{\"h1_2\": \"0a\",\"h1_3\": \"0a\",\"h1_4\": \"0a\",\"h2_3\": \"a1\",\"h2_4\": \"a1\",\"h3_2\": \"0a\",\"h3_4\": \"a1\"}"707		)708	}709710	#[test]711	fn direct_self() {712		println!(713			"{:#?}",714			eval!(715				r#"716					{717						local me = self,718						a: 3,719						b(): me.a,720					}721				"#722			)723		);724	}725726	#[test]727	fn indirect_self() {728		// `self` assigned to `me` was lost when being729		// referenced from field730		eval!(731			r#"{732				local me = self,733				a: 3,734				b: me.a,735			}.b"#736		);737	}738739	// We can't trust other tests (And official jsonnet testsuite), if assert is not working correctly740	#[test]741	fn std_assert_ok() {742		eval!("std.assertEqual(4.5 << 2, 16)");743	}744745	#[test]746	#[should_panic]747	fn std_assert_failure() {748		eval!("std.assertEqual(4.5 << 2, 15)");749	}750751	#[test]752	fn string_is_string() {753		assert!(primitive_equals(754			&eval!("local arr = 'hello'; (!std.isArray(arr)) && (!std.isString(arr))"),755			&Val::Bool(false),756		)757		.unwrap());758	}759760	#[test]761	fn base64_works() {762		assert_json!(r#"std.base64("test")"#, r#""dGVzdA==""#);763	}764765	#[test]766	fn utf8_chars() {767		assert_json!(768			r#"local c="😎";{c:std.codepoint(c),l:std.length(c)}"#,769			r#"{"c": 128526,"l": 1}"#770		)771	}772773	#[test]774	fn json() {775		assert_json!(776			r#"std.manifestJsonEx({a:3, b:4, c:6},"")"#,777			r#""{\n\"a\": 3,\n\"b\": 4,\n\"c\": 6\n}""#778		);779	}780781	#[test]782	fn test() {783		assert_json!(784			r#"[[a, b] for a in [1,2,3] for b in [4,5,6]]"#,785			"[[1,4],[1,5],[1,6],[2,4],[2,5],[2,6],[3,4],[3,5],[3,6]]"786		);787	}788789	#[test]790	fn sjsonnet() {791		eval!(792			r#"793			local x0 = {k: 1};794			local x1 = {k: x0.k + x0.k};795			local x2 = {k: x1.k + x1.k};796			local x3 = {k: x2.k + x2.k};797			local x4 = {k: x3.k + x3.k};798			local x5 = {k: x4.k + x4.k};799			local x6 = {k: x5.k + x5.k};800			local x7 = {k: x6.k + x6.k};801			local x8 = {k: x7.k + x7.k};802			local x9 = {k: x8.k + x8.k};803			local x10 = {k: x9.k + x9.k};804			local x11 = {k: x10.k + x10.k};805			local x12 = {k: x11.k + x11.k};806			local x13 = {k: x12.k + x12.k};807			local x14 = {k: x13.k + x13.k};808			local x15 = {k: x14.k + x14.k};809			local x16 = {k: x15.k + x15.k};810			local x17 = {k: x16.k + x16.k};811			local x18 = {k: x17.k + x17.k};812			local x19 = {k: x18.k + x18.k};813			local x20 = {k: x19.k + x19.k};814			local x21 = {k: x20.k + x20.k};815			x21.k816		"#817		);818	}819820	// This test is commented out by default, because of huge compilation slowdown821	// #[bench]822	// fn bench_codegen(b: &mut Bencher) {823	// 	b.iter(|| {824	// 		#[allow(clippy::all)]825	// 		let stdlib = {826	// 			use jrsonnet_parser::*;827	// 			include!(concat!(env!("OUT_DIR"), "/stdlib.rs"))828	// 		};829	// 		stdlib830	// 	})831	// }832833	/*834	#[bench]835	fn bench_serialize(b: &mut Bencher) {836		b.iter(|| {837			bincode::deserialize::<jrsonnet_parser::LocExpr>(include_bytes!(concat!(838				env!("OUT_DIR"),839				"/stdlib.bincode"840			)))841			.expect("deserialize stdlib")842		})843	}844845	#[bench]846	fn bench_parse(b: &mut Bencher) {847		b.iter(|| {848			jrsonnet_parser::parse(849				jrsonnet_stdlib::STDLIB_STR,850				&jrsonnet_parser::ParserSettings {851					loc_data: true,852					file_name: Rc::new(PathBuf::from("std.jsonnet")),853				},854			)855		})856	}857	*/858859	#[test]860	fn equality() {861		println!(862			"{:?}",863			jrsonnet_parser::parse(864				"{ x: 1, y: 2 } == { x: 1, y: 2 }",865				&ParserSettings::default()866			)867		);868		assert_eval!("{ x: 1, y: 2 } == { x: 1, y: 2 }")869	}870871	#[test]872	fn native_ext() -> crate::error::Result<()> {873		use super::native::NativeCallback;874		let evaluator = EvaluationState::default();875876		evaluator.with_stdlib();877		evaluator.settings_mut().ext_natives.insert(878			"native_add".into(),879			Rc::new(NativeCallback::new(880				ParamsDesc(Rc::new(vec![881					Param("a".into(), None),882					Param("b".into(), None),883				])),884				|args| match (&args[0], &args[1]) {885					(Val::Num(a), Val::Num(b)) => Ok(Val::Num(a + b)),886					(_, _) => todo!(),887				},888			)),889		);890		evaluator.evaluate_snippet_raw(891			Rc::new(PathBuf::from("test.jsonnet")),892			"std.assertEqual(std.native(\"native_add\")(1, 2), 3)".into(),893		)?;894		Ok(())895	}896897	#[test]898	fn constant_intrinsic() -> crate::error::Result<()> {899		assert_eval!(900			"local std2 = std; local std = std2 { primitiveEquals(a, b):: false }; 1 == 1"901		);902		Ok(())903	}904}
modifiedcrates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/val.rs
+++ b/crates/jrsonnet-evaluator/src/val.rs
@@ -76,7 +76,7 @@
 	/// Plain function implemented in jsonnet
 	Normal(FuncDesc),
 	/// Standard library function
-	Intrinsic(Rc<str>, Rc<str>),
+	Intrinsic(Rc<str>),
 	/// Library functions implemented in native
 	NativeExt(Rc<str>, Rc<NativeCallback>),
 }
@@ -85,7 +85,7 @@
 	fn eq(&self, other: &Self) -> bool {
 		match (self, other) {
 			(Self::Normal(a), Self::Normal(b)) => a == b,
-			(Self::Intrinsic(ans, an), Self::Intrinsic(bns, bn)) => ans == bns && an == bn,
+			(Self::Intrinsic(an), Self::Intrinsic(bn)) => an == bn,
 			(Self::NativeExt(an, _), Self::NativeExt(bn, _)) => an == bn,
 			(..) => false,
 		}
@@ -93,12 +93,12 @@
 }
 impl FuncVal {
 	pub fn is_ident(&self) -> bool {
-		matches!(&self, Self::Intrinsic(ns, n) if ns as &str == "std" && n as &str == "id")
+		matches!(&self, Self::Intrinsic(n) if n as &str == "id")
 	}
 	pub fn name(&self) -> Rc<str> {
 		match self {
 			Self::Normal(normal) => normal.name.clone(),
-			Self::Intrinsic(ns, name) => format!("intrinsic.{}.{}", ns, name).into(),
+			Self::Intrinsic(name) => format!("std.{}", name).into(),
 			Self::NativeExt(n, _) => format!("native.{}", n).into(),
 		}
 	}
@@ -120,7 +120,7 @@
 				)?;
 				evaluate(ctx, &func.body)
 			}
-			Self::Intrinsic(ns, name) => call_builtin(call_ctx, loc, ns, name, args),
+			Self::Intrinsic(name) => call_builtin(call_ctx, loc, name, args),
 			Self::NativeExt(_name, handler) => {
 				let args = parse_function_call(call_ctx, None, &handler.params, args, true)?;
 				let mut out_args = Vec::with_capacity(handler.params.len());
@@ -149,7 +149,7 @@
 				)?;
 				evaluate(ctx, &func.body)
 			}
-			Self::Intrinsic(_, _) => todo!(),
+			Self::Intrinsic(_) => todo!(),
 			Self::NativeExt(_, _) => todo!(),
 		}
 	}
@@ -160,7 +160,7 @@
 				let ctx = place_args(call_ctx, Some(func.ctx.clone()), &func.params, args)?;
 				evaluate(ctx, &func.body)
 			}
-			Self::Intrinsic(_, _) => todo!(),
+			Self::Intrinsic(_) => todo!(),
 			Self::NativeExt(_, _) => todo!(),
 		}
 	}
modifiedcrates/jrsonnet-parser/src/expr.rsdiffbeforeafterboth
--- a/crates/jrsonnet-parser/src/expr.rs
+++ b/crates/jrsonnet-parser/src/expr.rs
@@ -311,6 +311,8 @@
 	Index(LocExpr, LocExpr),
 	/// function(x) x
 	Function(ParamsDesc, LocExpr),
+	/// std.primitiveEquals
+	Intrinsic(Rc<str>),
 	/// if true == false then 1 else 2
 	IfElse {
 		cond: IfSpecData,
modifiedcrates/jrsonnet-parser/src/lib.rsdiffbeforeafterboth
--- a/crates/jrsonnet-parser/src/lib.rs
+++ b/crates/jrsonnet-parser/src/lib.rs
@@ -221,18 +221,12 @@
 				a:(@) _ "&" _ b:@ {loc_expr_todo!(Expr::BinaryOp(a, BinaryOpType::BitAnd, b))}
 				--
 				a:(@) _ "==" _ b:@ {loc_expr_todo!(Expr::Apply(
-					el!(Expr::Index(
-						el!(Expr::Var("std".into())),
-						el!(Expr::Str("equals".into()))
-					)),
+					el!(Expr::Intrinsic("equals".into())),
 					ArgsDesc(vec![Arg(None, a), Arg(None, b)]),
 					true
 				))}
 				a:(@) _ "!=" _ b:@ {loc_expr_todo!(Expr::UnaryOp(UnaryOpType::Not, el!(Expr::Apply(
-					el!(Expr::Index(
-						el!(Expr::Var("std".into())),
-						el!(Expr::Str("equals".into()))
-					)),
+					el!(Expr::Intrinsic("equals".into())),
 					ArgsDesc(vec![Arg(None, a), Arg(None, b)]),
 					true
 				))))}
@@ -242,10 +236,7 @@
 				a:(@) _ "<=" _ b:@ {loc_expr_todo!(Expr::BinaryOp(a, BinaryOpType::Lte, b))}
 				a:(@) _ ">=" _ b:@ {loc_expr_todo!(Expr::BinaryOp(a, BinaryOpType::Gte, b))}
 				a:(@) _ keyword("in") _ b:@ {loc_expr_todo!(Expr::Apply(
-					el!(Expr::Index(
-						el!(Expr::Var("std".into())),
-						el!(Expr::Str("objectHasEx".into()))
-					)), ArgsDesc(vec![Arg(None, b), Arg(None, a), Arg(None, el!(Expr::Literal(LiteralType::True)))]),
+					el!(Expr::Intrinsic("objectHasEx".into())), ArgsDesc(vec![Arg(None, b), Arg(None, a), Arg(None, el!(Expr::Literal(LiteralType::True)))]),
 					true
 				))}
 				--
@@ -258,10 +249,7 @@
 				a:(@) _ "*" _ b:@ {loc_expr_todo!(Expr::BinaryOp(a, BinaryOpType::Mul, b))}
 				a:(@) _ "/" _ b:@ {loc_expr_todo!(Expr::BinaryOp(a, BinaryOpType::Div, b))}
 				a:(@) _ "%" _ b:@ {loc_expr_todo!(Expr::Apply(
-					el!(Expr::Index(
-						el!(Expr::Var("std".into())),
-						el!(Expr::Str("mod".into()))
-					)), ArgsDesc(vec![Arg(None, a), Arg(None, b)]),
+					el!(Expr::Intrinsic("mod".into())), ArgsDesc(vec![Arg(None, a), Arg(None, b)]),
 					false
 				))}
 				--
@@ -270,10 +258,7 @@
 						"~" _ b:@ { loc_expr_todo!(Expr::UnaryOp(UnaryOpType::BitNot, b)) }
 				--
 				a:(@) _ "[" _ s:slice_desc(s) _ "]" {loc_expr_todo!(Expr::Apply(
-					el!(Expr::Index(
-						el!(Expr::Var("std".into())),
-						el!(Expr::Str("slice".into())),
-					)),
+					el!(Expr::Intrinsic("slice".into())),
 					ArgsDesc(vec![
 						Arg(None, a),
 						Arg(None, s.start.unwrap_or_else(||el!(Expr::Literal(LiteralType::Null)))),