git.delta.rocks / jrsonnet / refs/commits / 349c41065b93

difftreelog

feat lazy values in builtin

Yaroslav Bolyukin2022-04-20parent: #c7fb888.patch.diff
in: master

8 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
@@ -1,4 +1,4 @@
-use crate::function::StaticBuiltin;
+use crate::function::{CallLocation, StaticBuiltin};
 use crate::typed::{Any, PositiveF64, VecVal, M1};
 use crate::{
 	builtin::manifest::{manifest_yaml_ex, ManifestYamlOptions},
@@ -12,7 +12,6 @@
 use crate::{Either, ObjValue};
 use format::{format_arr, format_obj};
 use jrsonnet_interner::IStr;
-use jrsonnet_parser::ExprLocation;
 use serde::Deserialize;
 use serde_yaml::DeserializingQuirks;
 use std::collections::HashMap;
@@ -29,7 +28,7 @@
 
 pub fn std_format(str: IStr, vals: Val) -> Result<String> {
 	push_frame(
-		None,
+		CallLocation::native(),
 		|| format!("std.format of {}", str),
 		|| {
 			Ok(match vals {
@@ -467,9 +466,9 @@
 }
 
 #[jrsonnet_macros::builtin]
-fn builtin_trace(#[location] loc: Option<&ExprLocation>, str: IStr, rest: Any) -> Result<Any> {
+fn builtin_trace(loc: CallLocation, str: IStr, rest: Any) -> Result<Any> {
 	eprint!("TRACE:");
-	if let Some(loc) = loc {
+	if let Some(loc) = loc.0 {
 		with_state(|s| {
 			let locs = s.map_source_locations(&loc.0, &[loc.1]);
 			eprint!(
modifiedcrates/jrsonnet-evaluator/src/evaluate/mod.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/evaluate/mod.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/mod.rs
@@ -4,6 +4,7 @@
 	builtin::{std_slice, BUILTINS},
 	error::Error::*,
 	evaluate::operator::{evaluate_add_op, evaluate_binary_op_special, evaluate_unary_op},
+	function::CallLocation,
 	gc::TraceBox,
 	push_frame, throw, with_state, ArrValue, Bindable, Context, ContextCreator, FuncDesc, FuncVal,
 	FutureWrapper, GcHashMap, LazyBinding, LazyVal, LazyValValue, ObjValue, ObjValueBuilder,
@@ -12,8 +13,8 @@
 use gcmodule::{Cc, Trace};
 use jrsonnet_interner::IStr;
 use jrsonnet_parser::{
-	ArgsDesc, AssertStmt, BindSpec, CompSpec, Expr, ExprLocation, FieldMember, ForSpecData,
-	IfSpecData, LiteralType, LocExpr, Member, ObjBody, ParamsDesc,
+	ArgsDesc, AssertStmt, BindSpec, CompSpec, Expr, FieldMember, ForSpecData, IfSpecData,
+	LiteralType, LocExpr, Member, ObjBody, ParamsDesc,
 };
 use jrsonnet_types::ValType;
 pub mod operator;
@@ -192,7 +193,7 @@
 	Ok(match field_name {
 		jrsonnet_parser::FieldName::Fixed(n) => Some(n.clone()),
 		jrsonnet_parser::FieldName::Dyn(expr) => push_frame(
-			Some(&expr.1),
+			CallLocation::new(&expr.1),
 			|| "evaluating field name".to_string(),
 			|| {
 				let value = evaluate(context, expr)?;
@@ -442,7 +443,7 @@
 	context: Context,
 	value: &LocExpr,
 	args: &ArgsDesc,
-	loc: Option<&ExprLocation>,
+	loc: CallLocation,
 	tailstrict: bool,
 ) -> Result<Val> {
 	let value = evaluate(context.clone(), value)?;
@@ -463,13 +464,13 @@
 	let value = &assertion.0;
 	let msg = &assertion.1;
 	let assertion_result = push_frame(
-		Some(&value.1),
+		CallLocation::new(&value.1),
 		|| "assertion condition".to_owned(),
 		|| bool::try_from(evaluate(context.clone(), value)?),
 	)?;
 	if !assertion_result {
 		push_frame(
-			Some(&value.1),
+			CallLocation::new(&value.1),
 			|| "assertion failure".to_owned(),
 			|| {
 				if let Some(msg) = msg {
@@ -519,7 +520,7 @@
 		BinaryOp(v1, o, v2) => evaluate_binary_op_special(context, v1, *o, v2)?,
 		UnaryOp(o, v) => evaluate_unary_op(*o, &evaluate(context, v)?)?,
 		Var(name) => push_frame(
-			Some(loc),
+			CallLocation::new(loc),
 			|| format!("variable <{}> access", name),
 			|| context.binding(name.clone())?.evaluate(),
 		)?,
@@ -528,7 +529,7 @@
 				(Val::Obj(v), Val::Str(s)) => {
 					let sn = s.clone();
 					push_frame(
-						Some(loc),
+						CallLocation::new(loc),
 						|| format!("field <{}> access", sn),
 						|| {
 							if let Some(v) = v.get(s.clone())? {
@@ -625,7 +626,7 @@
 			&Val::Obj(evaluate_object(context, t)?),
 		)?,
 		Apply(value, args, tailstrict) => {
-			evaluate_apply(context, value, args, Some(loc), *tailstrict)?
+			evaluate_apply(context, value, args, CallLocation::new(loc), *tailstrict)?
 		}
 		Function(params, body) => {
 			evaluate_method(context, "anonymous".into(), params.clone(), body.clone())
@@ -640,7 +641,7 @@
 			evaluate(context, returned)?
 		}
 		ErrorStmt(e) => push_frame(
-			Some(loc),
+			CallLocation::new(loc),
 			|| "error statement".to_owned(),
 			|| throw!(RuntimeError(IStr::try_from(evaluate(context, e)?)?,)),
 		)?,
@@ -650,7 +651,7 @@
 			cond_else,
 		} => {
 			if push_frame(
-				Some(loc),
+				CallLocation::new(loc),
 				|| "if condition".to_owned(),
 				|| bool::try_from(evaluate(context.clone(), &cond.0)?),
 			)? {
@@ -689,7 +690,7 @@
 			let mut import_location = tmp.to_path_buf();
 			import_location.pop();
 			push_frame(
-				Some(loc),
+				CallLocation::new(loc),
 				|| format!("import {:?}", path),
 				|| with_state(|s| s.import_file(&import_location, path)),
 			)?
modifiedcrates/jrsonnet-evaluator/src/function.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/function.rs
+++ b/crates/jrsonnet-evaluator/src/function.rs
@@ -12,6 +12,19 @@
 use jrsonnet_parser::{ArgsDesc, ExprLocation, LocExpr, ParamsDesc};
 use std::{borrow::Cow, collections::HashMap, convert::TryFrom};
 
+#[derive(Clone, Copy)]
+pub struct CallLocation<'l>(pub Option<&'l ExprLocation>);
+impl<'l> CallLocation<'l> {
+	pub fn new(loc: &'l ExprLocation) -> Self {
+		Self(Some(loc))
+	}
+}
+impl CallLocation<'static> {
+	pub fn native() -> Self {
+		Self(None)
+	}
+}
+
 #[derive(Trace)]
 struct EvaluateLazyVal {
 	context: Context,
@@ -383,12 +396,7 @@
 pub trait Builtin: Trace {
 	fn name(&self) -> &str;
 	fn params(&self) -> &[BuiltinParam];
-	fn call(
-		&self,
-		context: Context,
-		loc: Option<&ExprLocation>,
-		args: &dyn ArgsLike,
-	) -> Result<Val>;
+	fn call(&self, context: Context, loc: CallLocation, args: &dyn ArgsLike) -> Result<Val>;
 }
 
 pub trait StaticBuiltin: Builtin + Send + Sync
modifiedcrates/jrsonnet-evaluator/src/lib.rsdiffbeforeafterboth
before · crates/jrsonnet-evaluator/src/lib.rs
1#![warn(clippy::all, clippy::nursery)]2#![allow(3	macro_expanded_macro_exports_accessed_by_absolute_paths,4	clippy::ptr_arg5)]67// For jrsonnet-macros8extern crate self as jrsonnet_evaluator;910mod builtin;11mod ctx;12mod dynamic;13pub mod error;14mod evaluate;15pub mod function;16mod import;17mod integrations;18mod map;19pub mod native;20mod obj;21pub mod trace;22pub mod typed;23mod val;2425pub use jrsonnet_parser as parser;2627pub use ctx::*;28pub use dynamic::*;29use error::{Error::*, LocError, Result, StackTraceElement};30pub use evaluate::*;31use function::{Builtin, TlaArg};32use gc::{GcHashMap, TraceBox};33use gcmodule::{Cc, Trace, Weak};34pub use import::*;35pub use jrsonnet_interner::IStr;36use jrsonnet_parser::*;37pub use obj::*;38use std::{39	cell::{Ref, RefCell, RefMut},40	collections::HashMap,41	fmt::Debug,42	path::{Path, PathBuf},43	rc::Rc,44};45use trace::{location_to_offset, offset_to_location, CodeLocation, CompactFormat, TraceFormat};46pub use val::*;47pub mod gc;4849pub trait Bindable: Trace + 'static {50	fn bind(&self, this: Option<ObjValue>, super_obj: Option<ObjValue>) -> Result<LazyVal>;51}5253#[derive(Clone, Trace)]54pub enum LazyBinding {55	Bindable(Cc<TraceBox<dyn Bindable>>),56	Bound(LazyVal),57}5859impl Debug for LazyBinding {60	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {61		write!(f, "LazyBinding")62	}63}64impl LazyBinding {65	pub fn evaluate(&self, this: Option<ObjValue>, super_obj: Option<ObjValue>) -> Result<LazyVal> {66		match self {67			Self::Bindable(v) => v.bind(this, super_obj),68			Self::Bound(v) => Ok(v.clone()),69		}70	}71}7273pub struct EvaluationSettings {74	/// Limits recursion by limiting the number of stack frames75	pub max_stack: usize,76	/// Limits amount of stack trace items preserved77	pub max_trace: usize,78	/// Used for s`td.extVar`79	pub ext_vars: HashMap<IStr, Val>,80	/// Used for ext.native81	pub ext_natives: HashMap<IStr, Cc<TraceBox<dyn Builtin>>>,82	/// TLA vars83	pub tla_vars: HashMap<IStr, TlaArg>,84	/// Global variables are inserted in default context85	pub globals: HashMap<IStr, Val>,86	/// Used to resolve file locations/contents87	pub import_resolver: Box<dyn ImportResolver>,88	/// Used in manifestification functions89	pub manifest_format: ManifestFormat,90	/// Used for bindings91	pub trace_format: Box<dyn TraceFormat>,92}93impl Default for EvaluationSettings {94	fn default() -> Self {95		Self {96			max_stack: 200,97			max_trace: 20,98			globals: Default::default(),99			ext_vars: Default::default(),100			ext_natives: Default::default(),101			tla_vars: Default::default(),102			import_resolver: Box::new(DummyImportResolver),103			manifest_format: ManifestFormat::Json(4),104			trace_format: Box::new(CompactFormat {105				padding: 4,106				resolver: trace::PathResolver::Absolute,107			}),108		}109	}110}111112#[derive(Default)]113struct EvaluationData {114	/// Used for stack overflow detection, stacktrace is populated on unwind115	stack_depth: usize,116	/// Updated every time stack entry is popt117	stack_generation: usize,118119	breakpoints: Breakpoints,120	/// Contains file source codes and evaluation results for imports and pretty-printed stacktraces121	files: HashMap<Rc<Path>, FileData>,122	str_files: HashMap<Rc<Path>, IStr>,123}124125pub struct FileData {126	source_code: IStr,127	parsed: LocExpr,128	evaluated: Option<Val>,129}130131#[allow(clippy::type_complexity)]132pub struct Breakpoint {133	loc: ExprLocation,134	collected: RefCell<HashMap<usize, (usize, Vec<Result<Val>>)>>,135}136#[derive(Default)]137struct Breakpoints(Vec<Rc<Breakpoint>>);138impl Breakpoints {139	fn insert(140		&self,141		stack_depth: usize,142		stack_generation: usize,143		loc: &ExprLocation,144		result: Result<Val>,145	) -> Result<Val> {146		if self.0.is_empty() {147			return result;148		}149		for item in self.0.iter() {150			if item.loc.belongs_to(loc) {151				let mut collected = item.collected.borrow_mut();152				let (depth, vals) = collected.entry(stack_generation).or_default();153				if stack_depth > *depth {154					vals.clear();155				}156				vals.push(result.clone());157			}158		}159		result160	}161}162163#[derive(Default)]164pub struct EvaluationStateInternals {165	/// Internal state166	data: RefCell<EvaluationData>,167	/// Settings, safe to change at runtime168	settings: RefCell<EvaluationSettings>,169}170171thread_local! {172	/// Contains the state for a currently executed file.173	/// Global state is fine here.174	pub(crate) static EVAL_STATE: RefCell<Option<EvaluationState>> = RefCell::new(None)175}176pub(crate) fn with_state<T>(f: impl FnOnce(&EvaluationState) -> T) -> T {177	EVAL_STATE.with(|s| {178		f(s.borrow().as_ref().expect(179			"missing evaluation state, some functions should be called inside of run_in_state call",180		))181	})182}183pub fn push_frame<T>(184	e: Option<&ExprLocation>,185	frame_desc: impl FnOnce() -> String,186	f: impl FnOnce() -> Result<T>,187) -> Result<T> {188	with_state(|s| s.push(e, frame_desc, f))189}190191#[allow(dead_code)]192pub fn push_val_frame(193	e: &ExprLocation,194	frame_desc: impl FnOnce() -> String,195	f: impl FnOnce() -> Result<Val>,196) -> Result<Val> {197	with_state(|s| s.push_val(e, frame_desc, f))198}199#[allow(dead_code)]200pub fn push_description_frame<T>(201	frame_desc: impl FnOnce() -> String,202	f: impl FnOnce() -> Result<T>,203) -> Result<T> {204	with_state(|s| s.push_description(frame_desc, f))205}206207/// Maintains stack trace and import resolution208#[derive(Default, Clone)]209pub struct EvaluationState(Rc<EvaluationStateInternals>);210211impl EvaluationState {212	/// Parses and adds file as loaded213	pub fn add_file(&self, path: Rc<Path>, source_code: IStr) -> Result<LocExpr> {214		let parsed = parse(215			&source_code,216			&ParserSettings {217				file_name: path.clone(),218			},219		)220		.map_err(|error| ImportSyntaxError {221			error: Box::new(error),222			path: path.to_owned(),223			source_code: source_code.clone(),224		})?;225		self.add_parsed_file(path, source_code, parsed.clone())?;226227		Ok(parsed)228	}229230	pub fn reset_evaluation_state(&self, name: &Path) {231		self.data_mut()232			.files233			.get_mut(name)234			.unwrap()235			.evaluated236			.take();237	}238239	/// Adds file by source code and parsed expr240	pub fn add_parsed_file(241		&self,242		name: Rc<Path>,243		source_code: IStr,244		parsed: LocExpr,245	) -> Result<()> {246		self.data_mut().files.insert(247			name,248			FileData {249				source_code,250				parsed,251				evaluated: None,252			},253		);254255		Ok(())256	}257	pub fn get_source(&self, name: &Path) -> Option<IStr> {258		let ro_map = &self.data().files;259		ro_map.get(name).map(|value| value.source_code.clone())260	}261	pub fn map_source_locations(&self, file: &Path, locs: &[usize]) -> Vec<CodeLocation> {262		offset_to_location(&self.get_source(file).unwrap_or_else(|| "".into()), locs)263	}264	pub fn map_from_source_location(265		&self,266		file: &Path,267		line: usize,268		column: usize,269	) -> Option<usize> {270		location_to_offset(&self.get_source(file).unwrap(), line, column)271	}272	pub fn import_file(&self, from: &Path, path: &Path) -> Result<Val> {273		let file_path = self.resolve_file(from, path)?;274		{275			let data = self.data();276			let files = &data.files;277			if files.contains_key(&file_path as &Path) {278				drop(data);279				return self.evaluate_loaded_file_raw(&file_path);280			}281		}282		let contents = self.load_file_contents(&file_path)?;283		self.add_file(file_path.clone(), contents)?;284		self.evaluate_loaded_file_raw(&file_path)285	}286	pub(crate) fn import_file_str(&self, from: &Path, path: &Path) -> Result<IStr> {287		let path = self.resolve_file(from, path)?;288		if !self.data().str_files.contains_key(&path) {289			let file_str = self.load_file_contents(&path)?;290			self.data_mut().str_files.insert(path.clone(), file_str);291		}292		Ok(self.data().str_files.get(&path).cloned().unwrap())293	}294295	fn evaluate_loaded_file_raw(&self, name: &Path) -> Result<Val> {296		let expr: LocExpr = {297			let ro_map = &self.data().files;298			let value = ro_map299				.get(name)300				.unwrap_or_else(|| panic!("file not added: {:?}", name));301			if let Some(ref evaluated) = value.evaluated {302				return Ok(evaluated.clone());303			}304			value.parsed.clone()305		};306		let value = evaluate(self.create_default_context(), &expr)?;307		{308			self.data_mut()309				.files310				.get_mut(name)311				.unwrap()312				.evaluated313				.replace(value.clone());314		}315		Ok(value)316	}317318	/// Adds standard library global variable (std) to this evaluator319	pub fn with_stdlib(&self) -> &Self {320		use jrsonnet_stdlib::STDLIB_STR;321		let std_path: Rc<Path> = PathBuf::from("std.jsonnet").into();322		self.run_in_state(|| {323			self.add_parsed_file(324				std_path.clone(),325				STDLIB_STR.to_owned().into(),326				builtin::get_parsed_stdlib(),327			)328			.unwrap();329			let val = self.evaluate_loaded_file_raw(&std_path).unwrap();330			self.settings_mut().globals.insert("std".into(), val);331		});332		self333	}334335	/// Creates context with all passed global variables336	pub fn create_default_context(&self) -> Context {337		let globals = &self.settings().globals;338		let mut new_bindings = GcHashMap::with_capacity(globals.len());339		for (name, value) in globals.iter() {340			new_bindings.insert(name.clone(), LazyVal::new_resolved(value.clone()));341		}342		Context::new().extend_bound(new_bindings)343	}344345	/// Executes code creating a new stack frame346	pub fn push<T>(347		&self,348		e: Option<&ExprLocation>,349		frame_desc: impl FnOnce() -> String,350		f: impl FnOnce() -> Result<T>,351	) -> Result<T> {352		{353			let mut data = self.data_mut();354			let stack_depth = &mut data.stack_depth;355			if *stack_depth > self.max_stack() {356				// Error creation uses data, so i drop guard here357				drop(data);358				throw!(StackOverflow);359			} else {360				*stack_depth += 1;361			}362		}363		let result = f();364		{365			let mut data = self.data_mut();366			data.stack_depth -= 1;367			data.stack_generation += 1;368		}369		if let Err(mut err) = result {370			err.trace_mut().0.push(StackTraceElement {371				location: e.cloned(),372				desc: frame_desc(),373			});374			return Err(err);375		}376		result377	}378379	/// Executes code creating a new stack frame380	pub fn push_val(381		&self,382		e: &ExprLocation,383		frame_desc: impl FnOnce() -> String,384		f: impl FnOnce() -> Result<Val>,385	) -> Result<Val> {386		{387			let mut data = self.data_mut();388			let stack_depth = &mut data.stack_depth;389			if *stack_depth > self.max_stack() {390				// Error creation uses data, so i drop guard here391				drop(data);392				throw!(StackOverflow);393			} else {394				*stack_depth += 1;395			}396		}397		let mut result = f();398		{399			let mut data = self.data_mut();400			data.stack_depth -= 1;401			data.stack_generation += 1;402			result = data403				.breakpoints404				.insert(data.stack_depth, data.stack_generation, e, result);405		}406		if let Err(mut err) = result {407			err.trace_mut().0.push(StackTraceElement {408				location: Some(e.clone()),409				desc: frame_desc(),410			});411			return Err(err);412		}413		result414	}415	/// Executes code creating a new stack frame416	pub fn push_description<T>(417		&self,418		frame_desc: impl FnOnce() -> String,419		f: impl FnOnce() -> Result<T>,420	) -> Result<T> {421		{422			let mut data = self.data_mut();423			let stack_depth = &mut data.stack_depth;424			if *stack_depth > self.max_stack() {425				// Error creation uses data, so i drop guard here426				drop(data);427				throw!(StackOverflow);428			} else {429				*stack_depth += 1;430			}431		}432		let result = f();433		{434			let mut data = self.data_mut();435			data.stack_depth -= 1;436			data.stack_generation += 1;437		}438		if let Err(mut err) = result {439			err.trace_mut().0.push(StackTraceElement {440				location: None,441				desc: frame_desc(),442			});443			return Err(err);444		}445		result446	}447448	/// Runs passed function in state (required if function needs to modify stack trace)449	pub fn run_in_state<T>(&self, f: impl FnOnce() -> T) -> T {450		EVAL_STATE.with(|v| {451			let has_state = v.borrow().is_some();452			if !has_state {453				v.borrow_mut().replace(self.clone());454			}455			let result = f();456			if !has_state {457				v.borrow_mut().take();458			}459			result460		})461	}462	pub fn run_in_state_with_breakpoint(463		&self,464		bp: Rc<Breakpoint>,465		f: impl FnOnce() -> Result<()>,466	) -> Result<()> {467		{468			let mut data = self.data_mut();469			data.breakpoints.0.push(bp);470		}471472		let result = self.run_in_state(f);473474		{475			let mut data = self.data_mut();476			data.breakpoints.0.pop();477		}478479		result480	}481482	pub fn stringify_err(&self, e: &LocError) -> String {483		let mut out = String::new();484		self.settings()485			.trace_format486			.write_trace(&mut out, self, e)487			.unwrap();488		out489	}490491	pub fn manifest(&self, val: Val) -> Result<IStr> {492		self.run_in_state(|| {493			push_description_frame(494				|| "manifestification".to_string(),495				|| val.manifest(&self.manifest_format()),496			)497		})498	}499	pub fn manifest_multi(&self, val: Val) -> Result<Vec<(IStr, IStr)>> {500		self.run_in_state(|| val.manifest_multi(&self.manifest_format()))501	}502	pub fn manifest_stream(&self, val: Val) -> Result<Vec<IStr>> {503		self.run_in_state(|| val.manifest_stream(&self.manifest_format()))504	}505506	/// If passed value is function then call with set TLA507	pub fn with_tla(&self, val: Val) -> Result<Val> {508		self.run_in_state(|| {509			Ok(match val {510				Val::Func(func) => push_description_frame(511					|| "during TLA call".to_owned(),512					|| {513						func.evaluate(514							self.create_default_context(),515							None,516							&self.settings().tla_vars,517							true,518						)519					},520				)?,521				v => v,522			})523		})524	}525}526527/// Internals528impl EvaluationState {529	fn data(&self) -> Ref<EvaluationData> {530		self.0.data.borrow()531	}532	fn data_mut(&self) -> RefMut<EvaluationData> {533		self.0.data.borrow_mut()534	}535	pub fn settings(&self) -> Ref<EvaluationSettings> {536		self.0.settings.borrow()537	}538	pub fn settings_mut(&self) -> RefMut<EvaluationSettings> {539		self.0.settings.borrow_mut()540	}541}542543/// Raw methods evaluate passed values but don't perform TLA execution544impl EvaluationState {545	pub fn evaluate_file_raw(&self, name: &Path) -> Result<Val> {546		self.run_in_state(|| self.import_file(&std::env::current_dir().expect("cwd"), name))547	}548	pub fn evaluate_file_raw_nocwd(&self, name: &Path) -> Result<Val> {549		self.run_in_state(|| self.import_file(&PathBuf::from("."), name))550	}551	/// Parses and evaluates the given snippet552	pub fn evaluate_snippet_raw(&self, source: Rc<Path>, code: IStr) -> Result<Val> {553		let parsed = parse(554			&code,555			&ParserSettings {556				file_name: source.clone(),557			},558		)559		.map_err(|e| ImportSyntaxError {560			path: source.clone(),561			source_code: code.clone(),562			error: Box::new(e),563		})?;564		self.add_parsed_file(source, code, parsed.clone())?;565		self.evaluate_expr_raw(parsed)566	}567	/// Evaluates the parsed expression568	pub fn evaluate_expr_raw(&self, code: LocExpr) -> Result<Val> {569		self.run_in_state(|| evaluate(self.create_default_context(), &code))570	}571}572573/// Settings utilities574impl EvaluationState {575	pub fn add_ext_var(&self, name: IStr, value: Val) {576		self.settings_mut().ext_vars.insert(name, value);577	}578	pub fn add_ext_str(&self, name: IStr, value: IStr) {579		self.add_ext_var(name, Val::Str(value));580	}581	pub fn add_ext_code(&self, name: IStr, code: IStr) -> Result<()> {582		let value =583			self.evaluate_snippet_raw(PathBuf::from(format!("ext_code {}", name)).into(), code)?;584		self.add_ext_var(name, value);585		Ok(())586	}587588	pub fn add_tla(&self, name: IStr, value: Val) {589		self.settings_mut()590			.tla_vars591			.insert(name, TlaArg::Val(value));592	}593	pub fn add_tla_str(&self, name: IStr, value: IStr) {594		self.settings_mut()595			.tla_vars596			.insert(name, TlaArg::String(value));597	}598	pub fn add_tla_code(&self, name: IStr, code: IStr) -> Result<()> {599		let parsed = self.add_file(PathBuf::from(format!("tla_code {}", name)).into(), code)?;600		self.settings_mut()601			.tla_vars602			.insert(name, TlaArg::Code(parsed));603		Ok(())604	}605606	pub fn resolve_file(&self, from: &Path, path: &Path) -> Result<Rc<Path>> {607		self.settings().import_resolver.resolve_file(from, path)608	}609	pub fn load_file_contents(&self, path: &Path) -> Result<IStr> {610		self.settings().import_resolver.load_file_contents(path)611	}612613	pub fn import_resolver(&self) -> Ref<dyn ImportResolver> {614		Ref::map(self.settings(), |s| &*s.import_resolver)615	}616	pub fn set_import_resolver(&self, resolver: Box<dyn ImportResolver>) {617		self.settings_mut().import_resolver = resolver;618	}619620	pub fn add_native(&self, name: IStr, cb: Cc<TraceBox<dyn Builtin>>) {621		self.settings_mut().ext_natives.insert(name, cb);622	}623624	pub fn manifest_format(&self) -> ManifestFormat {625		self.settings().manifest_format.clone()626	}627	pub fn set_manifest_format(&self, format: ManifestFormat) {628		self.settings_mut().manifest_format = format;629	}630631	pub fn trace_format(&self) -> Ref<dyn TraceFormat> {632		Ref::map(self.settings(), |s| &*s.trace_format)633	}634	pub fn set_trace_format(&self, format: Box<dyn TraceFormat>) {635		self.settings_mut().trace_format = format;636	}637638	pub fn max_trace(&self) -> usize {639		self.settings().max_trace640	}641	pub fn set_max_trace(&self, trace: usize) {642		self.settings_mut().max_trace = trace;643	}644645	pub fn max_stack(&self) -> usize {646		self.settings().max_stack647	}648	pub fn set_max_stack(&self, trace: usize) {649		self.settings_mut().max_stack = trace;650	}651}652653pub fn cc_ptr_eq<T>(a: &Cc<T>, b: &Cc<T>) -> bool {654	let a = a as &T;655	let b = b as &T;656	std::ptr::eq(a, b)657}658659fn weak_raw<T>(a: Weak<T>) -> *const () {660	unsafe { std::mem::transmute(a) }661}662fn weak_ptr_eq<T>(a: Weak<T>, b: Weak<T>) -> bool {663	std::ptr::eq(weak_raw(a), weak_raw(b))664}665666#[test]667fn weak_unsafe() {668	let a = Cc::new(1);669	let b = Cc::new(2);670671	let aw1 = a.clone().downgrade();672	let aw2 = a.clone().downgrade();673	let aw3 = a.clone().downgrade();674675	let bw = b.clone().downgrade();676677	assert!(weak_ptr_eq(aw1, aw2));678	assert!(!weak_ptr_eq(aw3, bw));679}680681#[cfg(test)]682pub mod tests {683	use super::Val;684	use crate::{685		error::Error::*, function::BuiltinParam, gc::TraceBox, native::NativeCallbackHandler,686		primitive_equals, EvaluationState,687	};688	use gcmodule::{Cc, Trace};689	use jrsonnet_interner::IStr;690	use jrsonnet_parser::*;691	use std::{692		path::{Path, PathBuf},693		rc::Rc,694	};695696	#[test]697	#[should_panic]698	fn eval_state_stacktrace() {699		let state = EvaluationState::default();700		state.run_in_state(|| {701			state702				.push(703					Some(&ExprLocation(PathBuf::from("test1.jsonnet").into(), 10, 20)),704					|| "outer".to_owned(),705					|| {706						state.push(707							Some(&ExprLocation(PathBuf::from("test2.jsonnet").into(), 30, 40)),708							|| "inner".to_owned(),709							|| Err(RuntimeError("".into()).into()),710						)?;711						Ok(Val::Null)712					},713				)714				.unwrap();715		});716	}717718	#[test]719	fn eval_state_standard() {720		let state = EvaluationState::default();721		state.with_stdlib();722		assert!(primitive_equals(723			&state724				.evaluate_snippet_raw(725					PathBuf::from("raw.jsonnet").into(),726					r#"std.assertEqual(std.base64("test"), "dGVzdA==")"#.into()727				)728				.unwrap(),729			&Val::Bool(true),730		)731		.unwrap());732	}733734	macro_rules! eval {735		($str: expr) => {{736			let evaluator = EvaluationState::default();737			evaluator.with_stdlib();738			evaluator.run_in_state(|| {739				evaluator740					.evaluate_snippet_raw(PathBuf::from("raw.jsonnet").into(), $str.into())741					.unwrap()742			})743		}};744	}745	macro_rules! eval_json {746		($str: expr) => {{747			let evaluator = EvaluationState::default();748			evaluator.with_stdlib();749			evaluator.run_in_state(|| {750				evaluator751					.evaluate_snippet_raw(PathBuf::from("raw.jsonnet").into(), $str.into())752					.unwrap()753					.to_json(0)754					.unwrap()755					.replace("\n", "")756			})757		}};758	}759760	/// Asserts given code returns `true`761	macro_rules! assert_eval {762		($str: expr) => {763			assert!(primitive_equals(&eval!($str), &Val::Bool(true)).unwrap())764		};765	}766767	/// Asserts given code returns `false`768	macro_rules! assert_eval_neg {769		($str: expr) => {770			assert!(primitive_equals(&eval!($str), &Val::Bool(false)).unwrap())771		};772	}773	macro_rules! assert_json {774		($str: expr, $out: expr) => {775			assert_eq!(eval_json!($str), $out.replace("\t", ""))776		};777	}778779	/// Sanity checking, before trusting to another tests780	#[test]781	fn equality_operator() {782		assert_eval!("2 == 2");783		assert_eval_neg!("2 != 2");784		assert_eval!("2 != 3");785		assert_eval_neg!("2 == 3");786		assert_eval!("'Hello' == 'Hello'");787		assert_eval_neg!("'Hello' != 'Hello'");788		assert_eval!("'Hello' != 'World'");789		assert_eval_neg!("'Hello' == 'World'");790	}791792	#[test]793	fn math_evaluation() {794		assert_eval!("2 + 2 * 2 == 6");795		assert_eval!("3 + (2 + 2 * 2) == 9");796	}797798	#[test]799	fn string_concat() {800		assert_eval!("'Hello' + 'World' == 'HelloWorld'");801		assert_eval!("'Hello' * 3 == 'HelloHelloHello'");802		assert_eval!("'Hello' + 'World' * 3 == 'HelloWorldWorldWorld'");803	}804805	#[test]806	fn faster_join() {807		assert_eval!("std.join([0,0], [[1,2],[3,4],[5,6]]) == [1,2,0,0,3,4,0,0,5,6]");808		assert_eval!("std.join(',', ['1','2','3','4']) == '1,2,3,4'");809	}810811	#[test]812	fn function_contexts() {813		assert_eval!(814			r#"815				local k = {816					t(name = self.h): [self.h, name],817					h: 3,818				};819				local f = {820					t: k.t(),821					h: 4,822				};823				f.t[0] == f.t[1]824			"#825		);826	}827828	#[test]829	fn local() {830		assert_eval!("local a = 2; local b = 3; a + b == 5");831		assert_eval!("local a = 1, b = a + 1; a + b == 3");832		assert_eval!("local a = 1; local a = 2; a == 2");833	}834835	#[test]836	fn object_lazyness() {837		assert_json!("local a = {a:error 'test'}; {}", r#"{}"#);838	}839840	#[test]841	fn object_inheritance() {842		assert_json!("{a: self.b} + {b:3}", r#"{"a": 3,"b": 3}"#);843	}844845	#[test]846	fn object_assertion_success() {847		eval!("{assert \"a\" in self} + {a:2}");848	}849850	#[test]851	fn object_assertion_error() {852		eval!("{assert \"a\" in self}");853	}854855	#[test]856	fn lazy_args() {857		eval!("local test(a) = 2; test(error '3')");858	}859860	#[test]861	#[should_panic]862	fn tailstrict_args() {863		eval!("local test(a) = 2; test(error '3') tailstrict");864	}865866	#[test]867	#[should_panic]868	fn no_binding_error() {869		eval!("a");870	}871872	#[test]873	fn test_object() {874		assert_json!("{a:2}", r#"{"a": 2}"#);875		assert_json!("{a:2+2}", r#"{"a": 4}"#);876		assert_json!("{a:2}+{b:2}", r#"{"a": 2,"b": 2}"#);877		assert_json!("{b:3}+{b:2}", r#"{"b": 2}"#);878		assert_json!("{b:3}+{b+:2}", r#"{"b": 5}"#);879		assert_json!("local test='a'; {[test]:2}", r#"{"a": 2}"#);880		assert_json!(881			r#"882				{883					name: "Alice",884					welcome: "Hello " + self.name + "!",885				}886			"#,887			r#"{"name": "Alice","welcome": "Hello Alice!"}"#888		);889		assert_json!(890			r#"891				{892					name: "Alice",893					welcome: "Hello " + self.name + "!",894				} + {895					name: "Bob"896				}897			"#,898			r#"{"name": "Bob","welcome": "Hello Bob!"}"#899		);900	}901902	#[test]903	fn functions() {904		assert_json!(r#"local a = function(b, c = 2) b + c; a(2)"#, "4");905		assert_json!(906			r#"local a = function(b, c = "Dear") b + c + d, d = "World"; a("Hello")"#,907			r#""HelloDearWorld""#908		);909	}910911	#[test]912	fn local_methods() {913		assert_json!(r#"local a(b, c = 2) = b + c; a(2)"#, "4");914		assert_json!(915			r#"local a(b, c = "Dear") = b + c + d, d = "World"; a("Hello")"#,916			r#""HelloDearWorld""#917		);918	}919920	#[test]921	fn object_locals() {922		assert_json!(r#"{local a = 3, b: a}"#, r#"{"b": 3}"#);923		assert_json!(r#"{local a = 3, local c = a, b: c}"#, r#"{"b": 3}"#);924		assert_json!(925			r#"{local a = function (b) {[b]:4}, test: a("test")}"#,926			r#"{"test": {"test": 4}}"#927		);928	}929930	#[test]931	fn object_comp() {932		assert_json!(933			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}"#,934			"{\"h1_2\": \"0a\",\"h1_3\": \"0a\",\"h1_4\": \"0a\",\"h2_3\": \"a1\",\"h2_4\": \"a1\",\"h3_2\": \"0a\",\"h3_4\": \"a1\"}"935		)936	}937938	#[test]939	fn direct_self() {940		println!(941			"{:#?}",942			eval!(943				r#"944					{945						local me = self,946						a: 3,947						b(): me.a,948					}949				"#950			)951		);952	}953954	#[test]955	fn indirect_self() {956		// `self` assigned to `me` was lost when being957		// referenced from field958		eval!(959			r#"{960				local me = self,961				a: 3,962				b: me.a,963			}.b"#964		);965	}966967	// We can't trust other tests (And official jsonnet testsuite), if assert is not working correctly968	#[test]969	fn std_assert_ok() {970		eval!("std.assertEqual(4.5 << 2, 16)");971	}972973	#[test]974	#[should_panic]975	fn std_assert_failure() {976		eval!("std.assertEqual(4.5 << 2, 15)");977	}978979	#[test]980	fn string_is_string() {981		assert!(primitive_equals(982			&eval!("local arr = 'hello'; (!std.isArray(arr)) && (!std.isString(arr))"),983			&Val::Bool(false),984		)985		.unwrap());986	}987988	#[test]989	fn base64_works() {990		assert_json!(r#"std.base64("test")"#, r#""dGVzdA==""#);991	}992993	#[test]994	fn utf8_chars() {995		assert_json!(996			r#"local c="😎";{c:std.codepoint(c),l:std.length(c)}"#,997			r#"{"c": 128526,"l": 1}"#998		)999	}10001001	#[test]1002	fn json() {1003		assert_json!(1004			r#"std.manifestJsonEx({a:3, b:4, c:6},"")"#,1005			r#""{\n\"a\": 3,\n\"b\": 4,\n\"c\": 6\n}""#1006		);1007	}10081009	#[test]1010	fn json_minified() {1011		assert_json!(1012			r#"std.manifestJsonMinified({a:3, b:4, c:6})"#,1013			r#""{\"a\":3,\"b\":4,\"c\":6}""#1014		);1015	}10161017	#[test]1018	fn parse_json() {1019		assert_json!(1020			r#"std.parseJson('{"a": -1,"b": 1,"c": 3.141,"d": []}')"#,1021			r#"{"a": -1,"b": 1,"c": 3.141,"d": []}"#1022		);1023	}10241025	#[test]1026	fn test() {1027		assert_json!(1028			r#"[[a, b] for a in [1,2,3] for b in [4,5,6]]"#,1029			"[[1,4],[1,5],[1,6],[2,4],[2,5],[2,6],[3,4],[3,5],[3,6]]"1030		);1031	}10321033	#[test]1034	fn sjsonnet() {1035		eval!(1036			r#"1037			local x0 = {k: 1};1038			local x1 = {k: x0.k + x0.k};1039			local x2 = {k: x1.k + x1.k};1040			local x3 = {k: x2.k + x2.k};1041			local x4 = {k: x3.k + x3.k};1042			local x5 = {k: x4.k + x4.k};1043			local x6 = {k: x5.k + x5.k};1044			local x7 = {k: x6.k + x6.k};1045			local x8 = {k: x7.k + x7.k};1046			local x9 = {k: x8.k + x8.k};1047			local x10 = {k: x9.k + x9.k};1048			local x11 = {k: x10.k + x10.k};1049			local x12 = {k: x11.k + x11.k};1050			local x13 = {k: x12.k + x12.k};1051			local x14 = {k: x13.k + x13.k};1052			local x15 = {k: x14.k + x14.k};1053			local x16 = {k: x15.k + x15.k};1054			local x17 = {k: x16.k + x16.k};1055			local x18 = {k: x17.k + x17.k};1056			local x19 = {k: x18.k + x18.k};1057			local x20 = {k: x19.k + x19.k};1058			local x21 = {k: x20.k + x20.k};1059			x21.k1060		"#1061		);1062	}10631064	// This test is commented out by default, because of huge compilation slowdown1065	// #[bench]1066	// fn bench_codegen(b: &mut Bencher) {1067	// 	b.iter(|| {1068	// 		#[allow(clippy::all)]1069	// 		let stdlib = {1070	// 			use jrsonnet_parser::*;1071	// 			include!(concat!(env!("OUT_DIR"), "/stdlib.rs"))1072	// 		};1073	// 		stdlib1074	// 	})1075	// }10761077	/*1078	#[bench]1079	fn bench_serialize(b: &mut Bencher) {1080		b.iter(|| {1081			bincode::deserialize::<jrsonnet_parser::LocExpr>(include_bytes!(concat!(1082				env!("OUT_DIR"),1083				"/stdlib.bincode"1084			)))1085			.expect("deserialize stdlib")1086		})1087	}10881089	#[bench]1090	fn bench_parse(b: &mut Bencher) {1091		b.iter(|| {1092			jrsonnet_parser::parse(1093				jrsonnet_stdlib::STDLIB_STR,1094				&jrsonnet_parser::ParserSettings {1095					loc_data: true,1096					file_name: Rc::new(PathBuf::from("std.jsonnet")),1097				},1098			)1099		})1100	}1101	*/11021103	#[test]1104	fn equality() {1105		println!(1106			"{:?}",1107			jrsonnet_parser::parse(1108				"{ x: 1, y: 2 } == { x: 1, y: 2 }",1109				&ParserSettings {1110					file_name: PathBuf::from("equality").into(),1111				}1112			)1113		);1114		assert_eval!("{ x: 1, y: 2 } == { x: 1, y: 2 }")1115	}11161117	#[test]1118	fn native_ext() -> crate::error::Result<()> {1119		use super::native::NativeCallback;1120		let evaluator = EvaluationState::default();11211122		evaluator.with_stdlib();11231124		#[derive(Trace)]1125		struct NativeAdd;1126		impl NativeCallbackHandler for NativeAdd {1127			fn call(&self, from: Option<Rc<Path>>, args: &[Val]) -> crate::error::Result<Val> {1128				assert_eq!(1129					&from.unwrap() as &Path,1130					&PathBuf::from("native_caller.jsonnet")1131				);1132				match (&args[0], &args[1]) {1133					(Val::Num(a), Val::Num(b)) => Ok(Val::Num(a + b)),1134					(_, _) => unreachable!(),1135				}1136			}1137		}1138		evaluator.settings_mut().ext_natives.insert(1139			"native_add".into(),1140			#[allow(deprecated)]1141			Cc::new(TraceBox(Box::new(NativeCallback::new(1142				vec![1143					BuiltinParam {1144						name: "a".into(),1145						has_default: false,1146					},1147					BuiltinParam {1148						name: "b".into(),1149						has_default: false,1150					},1151				],1152				TraceBox(Box::new(NativeAdd)),1153			)))),1154		);1155		evaluator.evaluate_snippet_raw(1156			PathBuf::from("native_caller.jsonnet").into(),1157			"std.assertEqual(std.native(\"native_add\")(1, 2), 3)".into(),1158		)?;1159		Ok(())1160	}11611162	#[test]1163	fn constant_intrinsic() -> crate::error::Result<()> {1164		assert_eval!(1165			"local std2 = std; local std = std2 { primitiveEquals(a, b):: false }; 1 == 1"1166		);1167		Ok(())1168	}11691170	#[test]1171	fn standalone_super() -> crate::error::Result<()> {1172		assert_eval!(1173			r#"1174			local obj = {1175				a: 1,1176				b: 2,1177				c: 3,1178			};1179			local test = obj + {1180				fields: std.objectFields(super),1181				d: 5,1182			};1183			test.fields == ['a', 'b', 'c']1184		"#1185		);1186		Ok(())1187	}11881189	#[test]1190	fn comp_self() -> crate::error::Result<()> {1191		assert_eval!(1192			r#"1193			std.objectFields({1194				a:{1195					[name]: name for name in std.objectFields(self)1196				},1197				b: 2,1198				c: 3,1199			}.a) == ['a', 'b', 'c']1200			"#1201		);12021203		Ok(())1204	}12051206	struct TestImportResolver(IStr);1207	impl crate::import::ImportResolver for TestImportResolver {1208		fn resolve_file(&self, _: &Path, _: &Path) -> crate::error::Result<Rc<Path>> {1209			Ok(PathBuf::from("/test").into())1210		}12111212		fn load_file_contents(&self, _: &Path) -> crate::error::Result<IStr> {1213			Ok(self.0.clone())1214		}12151216		unsafe fn as_any(&self) -> &dyn std::any::Any {1217			panic!()1218		}1219	}12201221	#[test]1222	fn issue_23() {1223		let state = EvaluationState::default();1224		state.set_import_resolver(Box::new(TestImportResolver(r#"import "/test""#.into())));1225		let _ = state.evaluate_file_raw(&PathBuf::from("/test"));1226	}12271228	#[test]1229	fn issue_40() {1230		let state = EvaluationState::default();1231		state.with_stdlib();12321233		let error = state1234			.evaluate_snippet_raw(1235				PathBuf::from("issue40.jsonnet").into(),1236				r#"1237				local conf = {1238					n: ""1239				};12401241				local result = conf + {1242					assert std.isNumber(self.n): "is number"1243				};12441245				std.manifestJsonEx(result, "")1246			"#1247				.into(),1248			)1249			.unwrap_err();1250		assert_eq!(error.error().to_string(), "assert failed: is number");1251	}12521253	#[test]1254	fn test_ascii_upper_lower() {1255		assert_eval!(r#"std.assertEqual(std.asciiUpper("aBc😀"), "ABC😀")"#);1256		assert_eval!(r#"std.assertEqual(std.asciiLower("aBc😀"), "abc😀")"#);1257	}12581259	#[test]1260	fn test_member() {1261		assert_eval!(r#"!std.member("", "")"#);1262		assert_eval!(r#"std.member("abc", "a")"#);1263		assert_eval!(r#"!std.member("abc", "d")"#);1264		assert_eval!(r#"!std.member([], "")"#);1265		assert_eval!(r#"std.member(["a", "b", "c"], "a")"#);1266		assert_eval!(r#"!std.member(["a", "b", "c"], "d")"#);1267	}12681269	#[test]1270	fn test_count() {1271		assert_eval!(r#"std.assertEqual(std.count([], ""), 0)"#);1272		assert_eval!(r#"std.assertEqual(std.count(["a", "b", "a"], "d"), 0)"#);1273		assert_eval!(r#"std.assertEqual(std.count(["a", "b", "a"], "a"), 2)"#);1274	}12751276	mod derive_typed {1277		use crate::{typed::Typed, EvaluationState};1278		use std::path::PathBuf;12791280		#[derive(Typed, PartialEq, Debug)]1281		struct MyTyped {1282			a: u32,1283			#[typed(rename = "b")]1284			c: String,1285		}12861287		#[test]1288		fn test() {1289			let es = EvaluationState::default();1290			let val = eval!("{a: 14, b: 'Hello, world!'}");1291			let typed = es.run_in_state(|| MyTyped::try_from(val).unwrap());12921293			assert_eq!(1294				typed,1295				MyTyped {1296					a: 14,1297					c: "Hello, world!".to_string()1298				}1299			);1300			es.settings_mut().globals.insert(1301				"mytyped".into(),1302				es.run_in_state(|| typed.try_into()).unwrap(),1303			);13041305			let v = es1306				.evaluate_snippet_raw(1307					PathBuf::from("raw.jsonnet").into(),1308					"1309				mytyped == {a: 14, b: 'Hello, world!'}1310			"1311					.into(),1312				)1313				.unwrap()1314				.as_bool()1315				.unwrap();1316			assert!(v)1317		}1318	}1319}
after · crates/jrsonnet-evaluator/src/lib.rs
1#![warn(clippy::all, clippy::nursery)]2#![allow(3	macro_expanded_macro_exports_accessed_by_absolute_paths,4	clippy::ptr_arg5)]67// For jrsonnet-macros8extern crate self as jrsonnet_evaluator;910mod builtin;11mod ctx;12mod dynamic;13pub mod error;14mod evaluate;15pub mod function;16mod import;17mod integrations;18mod map;19pub mod native;20mod obj;21pub mod trace;22pub mod typed;23mod val;2425pub use jrsonnet_parser as parser;2627pub use ctx::*;28pub use dynamic::*;29use error::{Error::*, LocError, Result, StackTraceElement};30pub use evaluate::*;31use function::{Builtin, CallLocation, TlaArg};32use gc::{GcHashMap, TraceBox};33use gcmodule::{Cc, Trace, Weak};34pub use import::*;35pub use jrsonnet_interner::IStr;36use jrsonnet_parser::*;37pub use obj::*;38use std::{39	cell::{Ref, RefCell, RefMut},40	collections::HashMap,41	fmt::Debug,42	path::{Path, PathBuf},43	rc::Rc,44};45use trace::{location_to_offset, offset_to_location, CodeLocation, CompactFormat, TraceFormat};46pub use val::*;47pub mod gc;4849pub trait Bindable: Trace + 'static {50	fn bind(&self, this: Option<ObjValue>, super_obj: Option<ObjValue>) -> Result<LazyVal>;51}5253#[derive(Clone, Trace)]54pub enum LazyBinding {55	Bindable(Cc<TraceBox<dyn Bindable>>),56	Bound(LazyVal),57}5859impl Debug for LazyBinding {60	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {61		write!(f, "LazyBinding")62	}63}64impl LazyBinding {65	pub fn evaluate(&self, this: Option<ObjValue>, super_obj: Option<ObjValue>) -> Result<LazyVal> {66		match self {67			Self::Bindable(v) => v.bind(this, super_obj),68			Self::Bound(v) => Ok(v.clone()),69		}70	}71}7273pub struct EvaluationSettings {74	/// Limits recursion by limiting the number of stack frames75	pub max_stack: usize,76	/// Limits amount of stack trace items preserved77	pub max_trace: usize,78	/// Used for s`td.extVar`79	pub ext_vars: HashMap<IStr, Val>,80	/// Used for ext.native81	pub ext_natives: HashMap<IStr, Cc<TraceBox<dyn Builtin>>>,82	/// TLA vars83	pub tla_vars: HashMap<IStr, TlaArg>,84	/// Global variables are inserted in default context85	pub globals: HashMap<IStr, Val>,86	/// Used to resolve file locations/contents87	pub import_resolver: Box<dyn ImportResolver>,88	/// Used in manifestification functions89	pub manifest_format: ManifestFormat,90	/// Used for bindings91	pub trace_format: Box<dyn TraceFormat>,92}93impl Default for EvaluationSettings {94	fn default() -> Self {95		Self {96			max_stack: 200,97			max_trace: 20,98			globals: Default::default(),99			ext_vars: Default::default(),100			ext_natives: Default::default(),101			tla_vars: Default::default(),102			import_resolver: Box::new(DummyImportResolver),103			manifest_format: ManifestFormat::Json(4),104			trace_format: Box::new(CompactFormat {105				padding: 4,106				resolver: trace::PathResolver::Absolute,107			}),108		}109	}110}111112#[derive(Default)]113struct EvaluationData {114	/// Used for stack overflow detection, stacktrace is populated on unwind115	stack_depth: usize,116	/// Updated every time stack entry is popt117	stack_generation: usize,118119	breakpoints: Breakpoints,120	/// Contains file source codes and evaluation results for imports and pretty-printed stacktraces121	files: HashMap<Rc<Path>, FileData>,122	str_files: HashMap<Rc<Path>, IStr>,123}124125pub struct FileData {126	source_code: IStr,127	parsed: LocExpr,128	evaluated: Option<Val>,129}130131#[allow(clippy::type_complexity)]132pub struct Breakpoint {133	loc: ExprLocation,134	collected: RefCell<HashMap<usize, (usize, Vec<Result<Val>>)>>,135}136#[derive(Default)]137struct Breakpoints(Vec<Rc<Breakpoint>>);138impl Breakpoints {139	fn insert(140		&self,141		stack_depth: usize,142		stack_generation: usize,143		loc: &ExprLocation,144		result: Result<Val>,145	) -> Result<Val> {146		if self.0.is_empty() {147			return result;148		}149		for item in self.0.iter() {150			if item.loc.belongs_to(loc) {151				let mut collected = item.collected.borrow_mut();152				let (depth, vals) = collected.entry(stack_generation).or_default();153				if stack_depth > *depth {154					vals.clear();155				}156				vals.push(result.clone());157			}158		}159		result160	}161}162163#[derive(Default)]164pub struct EvaluationStateInternals {165	/// Internal state166	data: RefCell<EvaluationData>,167	/// Settings, safe to change at runtime168	settings: RefCell<EvaluationSettings>,169}170171thread_local! {172	/// Contains the state for a currently executed file.173	/// Global state is fine here.174	pub(crate) static EVAL_STATE: RefCell<Option<EvaluationState>> = RefCell::new(None)175}176177pub(crate) fn with_state<T>(f: impl FnOnce(&EvaluationState) -> T) -> T {178	EVAL_STATE.with(|s| {179		f(s.borrow().as_ref().expect(180			"missing evaluation state, some functions should be called inside of run_in_state call",181		))182	})183}184pub fn push_frame<T>(185	e: CallLocation,186	frame_desc: impl FnOnce() -> String,187	f: impl FnOnce() -> Result<T>,188) -> Result<T> {189	with_state(|s| s.push(e, frame_desc, f))190}191192#[allow(dead_code)]193pub fn push_val_frame(194	e: &ExprLocation,195	frame_desc: impl FnOnce() -> String,196	f: impl FnOnce() -> Result<Val>,197) -> Result<Val> {198	with_state(|s| s.push_val(e, frame_desc, f))199}200#[allow(dead_code)]201pub fn push_description_frame<T>(202	frame_desc: impl FnOnce() -> String,203	f: impl FnOnce() -> Result<T>,204) -> Result<T> {205	with_state(|s| s.push_description(frame_desc, f))206}207208/// Maintains stack trace and import resolution209#[derive(Default, Clone)]210pub struct EvaluationState(Rc<EvaluationStateInternals>);211212impl EvaluationState {213	/// Parses and adds file as loaded214	pub fn add_file(&self, path: Rc<Path>, source_code: IStr) -> Result<LocExpr> {215		let parsed = parse(216			&source_code,217			&ParserSettings {218				file_name: path.clone(),219			},220		)221		.map_err(|error| ImportSyntaxError {222			error: Box::new(error),223			path: path.to_owned(),224			source_code: source_code.clone(),225		})?;226		self.add_parsed_file(path, source_code, parsed.clone())?;227228		Ok(parsed)229	}230231	pub fn reset_evaluation_state(&self, name: &Path) {232		self.data_mut()233			.files234			.get_mut(name)235			.unwrap()236			.evaluated237			.take();238	}239240	/// Adds file by source code and parsed expr241	pub fn add_parsed_file(242		&self,243		name: Rc<Path>,244		source_code: IStr,245		parsed: LocExpr,246	) -> Result<()> {247		self.data_mut().files.insert(248			name,249			FileData {250				source_code,251				parsed,252				evaluated: None,253			},254		);255256		Ok(())257	}258	pub fn get_source(&self, name: &Path) -> Option<IStr> {259		let ro_map = &self.data().files;260		ro_map.get(name).map(|value| value.source_code.clone())261	}262	pub fn map_source_locations(&self, file: &Path, locs: &[usize]) -> Vec<CodeLocation> {263		offset_to_location(&self.get_source(file).unwrap_or_else(|| "".into()), locs)264	}265	pub fn map_from_source_location(266		&self,267		file: &Path,268		line: usize,269		column: usize,270	) -> Option<usize> {271		location_to_offset(&self.get_source(file).unwrap(), line, column)272	}273	pub fn import_file(&self, from: &Path, path: &Path) -> Result<Val> {274		let file_path = self.resolve_file(from, path)?;275		{276			let data = self.data();277			let files = &data.files;278			if files.contains_key(&file_path as &Path) {279				drop(data);280				return self.evaluate_loaded_file_raw(&file_path);281			}282		}283		let contents = self.load_file_contents(&file_path)?;284		self.add_file(file_path.clone(), contents)?;285		self.evaluate_loaded_file_raw(&file_path)286	}287	pub(crate) fn import_file_str(&self, from: &Path, path: &Path) -> Result<IStr> {288		let path = self.resolve_file(from, path)?;289		if !self.data().str_files.contains_key(&path) {290			let file_str = self.load_file_contents(&path)?;291			self.data_mut().str_files.insert(path.clone(), file_str);292		}293		Ok(self.data().str_files.get(&path).cloned().unwrap())294	}295296	fn evaluate_loaded_file_raw(&self, name: &Path) -> Result<Val> {297		let expr: LocExpr = {298			let ro_map = &self.data().files;299			let value = ro_map300				.get(name)301				.unwrap_or_else(|| panic!("file not added: {:?}", name));302			if let Some(ref evaluated) = value.evaluated {303				return Ok(evaluated.clone());304			}305			value.parsed.clone()306		};307		let value = evaluate(self.create_default_context(), &expr)?;308		{309			self.data_mut()310				.files311				.get_mut(name)312				.unwrap()313				.evaluated314				.replace(value.clone());315		}316		Ok(value)317	}318319	/// Adds standard library global variable (std) to this evaluator320	pub fn with_stdlib(&self) -> &Self {321		use jrsonnet_stdlib::STDLIB_STR;322		let std_path: Rc<Path> = PathBuf::from("std.jsonnet").into();323		self.run_in_state(|| {324			self.add_parsed_file(325				std_path.clone(),326				STDLIB_STR.to_owned().into(),327				builtin::get_parsed_stdlib(),328			)329			.unwrap();330			let val = self.evaluate_loaded_file_raw(&std_path).unwrap();331			self.settings_mut().globals.insert("std".into(), val);332		});333		self334	}335336	/// Creates context with all passed global variables337	pub fn create_default_context(&self) -> Context {338		let globals = &self.settings().globals;339		let mut new_bindings = GcHashMap::with_capacity(globals.len());340		for (name, value) in globals.iter() {341			new_bindings.insert(name.clone(), LazyVal::new_resolved(value.clone()));342		}343		Context::new().extend_bound(new_bindings)344	}345346	/// Executes code creating a new stack frame347	pub fn push<T>(348		&self,349		e: CallLocation,350		frame_desc: impl FnOnce() -> String,351		f: impl FnOnce() -> Result<T>,352	) -> Result<T> {353		{354			let mut data = self.data_mut();355			let stack_depth = &mut data.stack_depth;356			if *stack_depth > self.max_stack() {357				// Error creation uses data, so i drop guard here358				drop(data);359				throw!(StackOverflow);360			} else {361				*stack_depth += 1;362			}363		}364		let result = f();365		{366			let mut data = self.data_mut();367			data.stack_depth -= 1;368			data.stack_generation += 1;369		}370		if let Err(mut err) = result {371			err.trace_mut().0.push(StackTraceElement {372				location: e.0.cloned(),373				desc: frame_desc(),374			});375			return Err(err);376		}377		result378	}379380	/// Executes code creating a new stack frame381	pub fn push_val(382		&self,383		e: &ExprLocation,384		frame_desc: impl FnOnce() -> String,385		f: impl FnOnce() -> Result<Val>,386	) -> Result<Val> {387		{388			let mut data = self.data_mut();389			let stack_depth = &mut data.stack_depth;390			if *stack_depth > self.max_stack() {391				// Error creation uses data, so i drop guard here392				drop(data);393				throw!(StackOverflow);394			} else {395				*stack_depth += 1;396			}397		}398		let mut result = f();399		{400			let mut data = self.data_mut();401			data.stack_depth -= 1;402			data.stack_generation += 1;403			result = data404				.breakpoints405				.insert(data.stack_depth, data.stack_generation, e, result);406		}407		if let Err(mut err) = result {408			err.trace_mut().0.push(StackTraceElement {409				location: Some(e.clone()),410				desc: frame_desc(),411			});412			return Err(err);413		}414		result415	}416	/// Executes code creating a new stack frame417	pub fn push_description<T>(418		&self,419		frame_desc: impl FnOnce() -> String,420		f: impl FnOnce() -> Result<T>,421	) -> Result<T> {422		{423			let mut data = self.data_mut();424			let stack_depth = &mut data.stack_depth;425			if *stack_depth > self.max_stack() {426				// Error creation uses data, so i drop guard here427				drop(data);428				throw!(StackOverflow);429			} else {430				*stack_depth += 1;431			}432		}433		let result = f();434		{435			let mut data = self.data_mut();436			data.stack_depth -= 1;437			data.stack_generation += 1;438		}439		if let Err(mut err) = result {440			err.trace_mut().0.push(StackTraceElement {441				location: None,442				desc: frame_desc(),443			});444			return Err(err);445		}446		result447	}448449	/// Runs passed function in state (required if function needs to modify stack trace)450	pub fn run_in_state<T>(&self, f: impl FnOnce() -> T) -> T {451		EVAL_STATE.with(|v| {452			let has_state = v.borrow().is_some();453			if !has_state {454				v.borrow_mut().replace(self.clone());455			}456			let result = f();457			if !has_state {458				v.borrow_mut().take();459			}460			result461		})462	}463	pub fn run_in_state_with_breakpoint(464		&self,465		bp: Rc<Breakpoint>,466		f: impl FnOnce() -> Result<()>,467	) -> Result<()> {468		{469			let mut data = self.data_mut();470			data.breakpoints.0.push(bp);471		}472473		let result = self.run_in_state(f);474475		{476			let mut data = self.data_mut();477			data.breakpoints.0.pop();478		}479480		result481	}482483	pub fn stringify_err(&self, e: &LocError) -> String {484		let mut out = String::new();485		self.settings()486			.trace_format487			.write_trace(&mut out, self, e)488			.unwrap();489		out490	}491492	pub fn manifest(&self, val: Val) -> Result<IStr> {493		self.run_in_state(|| {494			push_description_frame(495				|| "manifestification".to_string(),496				|| val.manifest(&self.manifest_format()),497			)498		})499	}500	pub fn manifest_multi(&self, val: Val) -> Result<Vec<(IStr, IStr)>> {501		self.run_in_state(|| val.manifest_multi(&self.manifest_format()))502	}503	pub fn manifest_stream(&self, val: Val) -> Result<Vec<IStr>> {504		self.run_in_state(|| val.manifest_stream(&self.manifest_format()))505	}506507	/// If passed value is function then call with set TLA508	pub fn with_tla(&self, val: Val) -> Result<Val> {509		self.run_in_state(|| {510			Ok(match val {511				Val::Func(func) => push_description_frame(512					|| "during TLA call".to_owned(),513					|| {514						func.evaluate(515							self.create_default_context(),516							CallLocation::native(),517							&self.settings().tla_vars,518							true,519						)520					},521				)?,522				v => v,523			})524		})525	}526}527528/// Internals529impl EvaluationState {530	fn data(&self) -> Ref<EvaluationData> {531		self.0.data.borrow()532	}533	fn data_mut(&self) -> RefMut<EvaluationData> {534		self.0.data.borrow_mut()535	}536	pub fn settings(&self) -> Ref<EvaluationSettings> {537		self.0.settings.borrow()538	}539	pub fn settings_mut(&self) -> RefMut<EvaluationSettings> {540		self.0.settings.borrow_mut()541	}542}543544/// Raw methods evaluate passed values but don't perform TLA execution545impl EvaluationState {546	pub fn evaluate_file_raw(&self, name: &Path) -> Result<Val> {547		self.run_in_state(|| self.import_file(&std::env::current_dir().expect("cwd"), name))548	}549	pub fn evaluate_file_raw_nocwd(&self, name: &Path) -> Result<Val> {550		self.run_in_state(|| self.import_file(&PathBuf::from("."), name))551	}552	/// Parses and evaluates the given snippet553	pub fn evaluate_snippet_raw(&self, source: Rc<Path>, code: IStr) -> Result<Val> {554		let parsed = parse(555			&code,556			&ParserSettings {557				file_name: source.clone(),558			},559		)560		.map_err(|e| ImportSyntaxError {561			path: source.clone(),562			source_code: code.clone(),563			error: Box::new(e),564		})?;565		self.add_parsed_file(source, code, parsed.clone())?;566		self.evaluate_expr_raw(parsed)567	}568	/// Evaluates the parsed expression569	pub fn evaluate_expr_raw(&self, code: LocExpr) -> Result<Val> {570		self.run_in_state(|| evaluate(self.create_default_context(), &code))571	}572}573574/// Settings utilities575impl EvaluationState {576	pub fn add_ext_var(&self, name: IStr, value: Val) {577		self.settings_mut().ext_vars.insert(name, value);578	}579	pub fn add_ext_str(&self, name: IStr, value: IStr) {580		self.add_ext_var(name, Val::Str(value));581	}582	pub fn add_ext_code(&self, name: IStr, code: IStr) -> Result<()> {583		let value =584			self.evaluate_snippet_raw(PathBuf::from(format!("ext_code {}", name)).into(), code)?;585		self.add_ext_var(name, value);586		Ok(())587	}588589	pub fn add_tla(&self, name: IStr, value: Val) {590		self.settings_mut()591			.tla_vars592			.insert(name, TlaArg::Val(value));593	}594	pub fn add_tla_str(&self, name: IStr, value: IStr) {595		self.settings_mut()596			.tla_vars597			.insert(name, TlaArg::String(value));598	}599	pub fn add_tla_code(&self, name: IStr, code: IStr) -> Result<()> {600		let parsed = self.add_file(PathBuf::from(format!("tla_code {}", name)).into(), code)?;601		self.settings_mut()602			.tla_vars603			.insert(name, TlaArg::Code(parsed));604		Ok(())605	}606607	pub fn resolve_file(&self, from: &Path, path: &Path) -> Result<Rc<Path>> {608		self.settings().import_resolver.resolve_file(from, path)609	}610	pub fn load_file_contents(&self, path: &Path) -> Result<IStr> {611		self.settings().import_resolver.load_file_contents(path)612	}613614	pub fn import_resolver(&self) -> Ref<dyn ImportResolver> {615		Ref::map(self.settings(), |s| &*s.import_resolver)616	}617	pub fn set_import_resolver(&self, resolver: Box<dyn ImportResolver>) {618		self.settings_mut().import_resolver = resolver;619	}620621	pub fn add_native(&self, name: IStr, cb: Cc<TraceBox<dyn Builtin>>) {622		self.settings_mut().ext_natives.insert(name, cb);623	}624625	pub fn manifest_format(&self) -> ManifestFormat {626		self.settings().manifest_format.clone()627	}628	pub fn set_manifest_format(&self, format: ManifestFormat) {629		self.settings_mut().manifest_format = format;630	}631632	pub fn trace_format(&self) -> Ref<dyn TraceFormat> {633		Ref::map(self.settings(), |s| &*s.trace_format)634	}635	pub fn set_trace_format(&self, format: Box<dyn TraceFormat>) {636		self.settings_mut().trace_format = format;637	}638639	pub fn max_trace(&self) -> usize {640		self.settings().max_trace641	}642	pub fn set_max_trace(&self, trace: usize) {643		self.settings_mut().max_trace = trace;644	}645646	pub fn max_stack(&self) -> usize {647		self.settings().max_stack648	}649	pub fn set_max_stack(&self, trace: usize) {650		self.settings_mut().max_stack = trace;651	}652}653654pub fn cc_ptr_eq<T>(a: &Cc<T>, b: &Cc<T>) -> bool {655	let a = a as &T;656	let b = b as &T;657	std::ptr::eq(a, b)658}659660fn weak_raw<T>(a: Weak<T>) -> *const () {661	unsafe { std::mem::transmute(a) }662}663fn weak_ptr_eq<T>(a: Weak<T>, b: Weak<T>) -> bool {664	std::ptr::eq(weak_raw(a), weak_raw(b))665}666667#[test]668fn weak_unsafe() {669	let a = Cc::new(1);670	let b = Cc::new(2);671672	let aw1 = a.clone().downgrade();673	let aw2 = a.clone().downgrade();674	let aw3 = a.clone().downgrade();675676	let bw = b.clone().downgrade();677678	assert!(weak_ptr_eq(aw1, aw2));679	assert!(!weak_ptr_eq(aw3, bw));680}681682#[cfg(test)]683pub mod tests {684	use super::Val;685	use crate::{686		error::Error::*, function::BuiltinParam, gc::TraceBox, native::NativeCallbackHandler,687		primitive_equals, EvaluationState,688	};689	use gcmodule::{Cc, Trace};690	use jrsonnet_interner::IStr;691	use jrsonnet_parser::*;692	use std::{693		path::{Path, PathBuf},694		rc::Rc,695	};696697	#[test]698	#[should_panic]699	fn eval_state_stacktrace() {700		let state = EvaluationState::default();701		state.run_in_state(|| {702			state703				.push(704					Some(&ExprLocation(PathBuf::from("test1.jsonnet").into(), 10, 20)),705					|| "outer".to_owned(),706					|| {707						state.push(708							Some(&ExprLocation(PathBuf::from("test2.jsonnet").into(), 30, 40)),709							|| "inner".to_owned(),710							|| Err(RuntimeError("".into()).into()),711						)?;712						Ok(Val::Null)713					},714				)715				.unwrap();716		});717	}718719	#[test]720	fn eval_state_standard() {721		let state = EvaluationState::default();722		state.with_stdlib();723		assert!(primitive_equals(724			&state725				.evaluate_snippet_raw(726					PathBuf::from("raw.jsonnet").into(),727					r#"std.assertEqual(std.base64("test"), "dGVzdA==")"#.into()728				)729				.unwrap(),730			&Val::Bool(true),731		)732		.unwrap());733	}734735	macro_rules! eval {736		($str: expr) => {{737			let evaluator = EvaluationState::default();738			evaluator.with_stdlib();739			evaluator.run_in_state(|| {740				evaluator741					.evaluate_snippet_raw(PathBuf::from("raw.jsonnet").into(), $str.into())742					.unwrap()743			})744		}};745	}746	macro_rules! eval_json {747		($str: expr) => {{748			let evaluator = EvaluationState::default();749			evaluator.with_stdlib();750			evaluator.run_in_state(|| {751				evaluator752					.evaluate_snippet_raw(PathBuf::from("raw.jsonnet").into(), $str.into())753					.unwrap()754					.to_json(0)755					.unwrap()756					.replace("\n", "")757			})758		}};759	}760761	/// Asserts given code returns `true`762	macro_rules! assert_eval {763		($str: expr) => {764			assert!(primitive_equals(&eval!($str), &Val::Bool(true)).unwrap())765		};766	}767768	/// Asserts given code returns `false`769	macro_rules! assert_eval_neg {770		($str: expr) => {771			assert!(primitive_equals(&eval!($str), &Val::Bool(false)).unwrap())772		};773	}774	macro_rules! assert_json {775		($str: expr, $out: expr) => {776			assert_eq!(eval_json!($str), $out.replace("\t", ""))777		};778	}779780	/// Sanity checking, before trusting to another tests781	#[test]782	fn equality_operator() {783		assert_eval!("2 == 2");784		assert_eval_neg!("2 != 2");785		assert_eval!("2 != 3");786		assert_eval_neg!("2 == 3");787		assert_eval!("'Hello' == 'Hello'");788		assert_eval_neg!("'Hello' != 'Hello'");789		assert_eval!("'Hello' != 'World'");790		assert_eval_neg!("'Hello' == 'World'");791	}792793	#[test]794	fn math_evaluation() {795		assert_eval!("2 + 2 * 2 == 6");796		assert_eval!("3 + (2 + 2 * 2) == 9");797	}798799	#[test]800	fn string_concat() {801		assert_eval!("'Hello' + 'World' == 'HelloWorld'");802		assert_eval!("'Hello' * 3 == 'HelloHelloHello'");803		assert_eval!("'Hello' + 'World' * 3 == 'HelloWorldWorldWorld'");804	}805806	#[test]807	fn faster_join() {808		assert_eval!("std.join([0,0], [[1,2],[3,4],[5,6]]) == [1,2,0,0,3,4,0,0,5,6]");809		assert_eval!("std.join(',', ['1','2','3','4']) == '1,2,3,4'");810	}811812	#[test]813	fn function_contexts() {814		assert_eval!(815			r#"816				local k = {817					t(name = self.h): [self.h, name],818					h: 3,819				};820				local f = {821					t: k.t(),822					h: 4,823				};824				f.t[0] == f.t[1]825			"#826		);827	}828829	#[test]830	fn local() {831		assert_eval!("local a = 2; local b = 3; a + b == 5");832		assert_eval!("local a = 1, b = a + 1; a + b == 3");833		assert_eval!("local a = 1; local a = 2; a == 2");834	}835836	#[test]837	fn object_lazyness() {838		assert_json!("local a = {a:error 'test'}; {}", r#"{}"#);839	}840841	#[test]842	fn object_inheritance() {843		assert_json!("{a: self.b} + {b:3}", r#"{"a": 3,"b": 3}"#);844	}845846	#[test]847	fn object_assertion_success() {848		eval!("{assert \"a\" in self} + {a:2}");849	}850851	#[test]852	fn object_assertion_error() {853		eval!("{assert \"a\" in self}");854	}855856	#[test]857	fn lazy_args() {858		eval!("local test(a) = 2; test(error '3')");859	}860861	#[test]862	#[should_panic]863	fn tailstrict_args() {864		eval!("local test(a) = 2; test(error '3') tailstrict");865	}866867	#[test]868	#[should_panic]869	fn no_binding_error() {870		eval!("a");871	}872873	#[test]874	fn test_object() {875		assert_json!("{a:2}", r#"{"a": 2}"#);876		assert_json!("{a:2+2}", r#"{"a": 4}"#);877		assert_json!("{a:2}+{b:2}", r#"{"a": 2,"b": 2}"#);878		assert_json!("{b:3}+{b:2}", r#"{"b": 2}"#);879		assert_json!("{b:3}+{b+:2}", r#"{"b": 5}"#);880		assert_json!("local test='a'; {[test]:2}", r#"{"a": 2}"#);881		assert_json!(882			r#"883				{884					name: "Alice",885					welcome: "Hello " + self.name + "!",886				}887			"#,888			r#"{"name": "Alice","welcome": "Hello Alice!"}"#889		);890		assert_json!(891			r#"892				{893					name: "Alice",894					welcome: "Hello " + self.name + "!",895				} + {896					name: "Bob"897				}898			"#,899			r#"{"name": "Bob","welcome": "Hello Bob!"}"#900		);901	}902903	#[test]904	fn functions() {905		assert_json!(r#"local a = function(b, c = 2) b + c; a(2)"#, "4");906		assert_json!(907			r#"local a = function(b, c = "Dear") b + c + d, d = "World"; a("Hello")"#,908			r#""HelloDearWorld""#909		);910	}911912	#[test]913	fn local_methods() {914		assert_json!(r#"local a(b, c = 2) = b + c; a(2)"#, "4");915		assert_json!(916			r#"local a(b, c = "Dear") = b + c + d, d = "World"; a("Hello")"#,917			r#""HelloDearWorld""#918		);919	}920921	#[test]922	fn object_locals() {923		assert_json!(r#"{local a = 3, b: a}"#, r#"{"b": 3}"#);924		assert_json!(r#"{local a = 3, local c = a, b: c}"#, r#"{"b": 3}"#);925		assert_json!(926			r#"{local a = function (b) {[b]:4}, test: a("test")}"#,927			r#"{"test": {"test": 4}}"#928		);929	}930931	#[test]932	fn object_comp() {933		assert_json!(934			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}"#,935			"{\"h1_2\": \"0a\",\"h1_3\": \"0a\",\"h1_4\": \"0a\",\"h2_3\": \"a1\",\"h2_4\": \"a1\",\"h3_2\": \"0a\",\"h3_4\": \"a1\"}"936		)937	}938939	#[test]940	fn direct_self() {941		println!(942			"{:#?}",943			eval!(944				r#"945					{946						local me = self,947						a: 3,948						b(): me.a,949					}950				"#951			)952		);953	}954955	#[test]956	fn indirect_self() {957		// `self` assigned to `me` was lost when being958		// referenced from field959		eval!(960			r#"{961				local me = self,962				a: 3,963				b: me.a,964			}.b"#965		);966	}967968	// We can't trust other tests (And official jsonnet testsuite), if assert is not working correctly969	#[test]970	fn std_assert_ok() {971		eval!("std.assertEqual(4.5 << 2, 16)");972	}973974	#[test]975	#[should_panic]976	fn std_assert_failure() {977		eval!("std.assertEqual(4.5 << 2, 15)");978	}979980	#[test]981	fn string_is_string() {982		assert!(primitive_equals(983			&eval!("local arr = 'hello'; (!std.isArray(arr)) && (!std.isString(arr))"),984			&Val::Bool(false),985		)986		.unwrap());987	}988989	#[test]990	fn base64_works() {991		assert_json!(r#"std.base64("test")"#, r#""dGVzdA==""#);992	}993994	#[test]995	fn utf8_chars() {996		assert_json!(997			r#"local c="😎";{c:std.codepoint(c),l:std.length(c)}"#,998			r#"{"c": 128526,"l": 1}"#999		)1000	}10011002	#[test]1003	fn json() {1004		assert_json!(1005			r#"std.manifestJsonEx({a:3, b:4, c:6},"")"#,1006			r#""{\n\"a\": 3,\n\"b\": 4,\n\"c\": 6\n}""#1007		);1008	}10091010	#[test]1011	fn json_minified() {1012		assert_json!(1013			r#"std.manifestJsonMinified({a:3, b:4, c:6})"#,1014			r#""{\"a\":3,\"b\":4,\"c\":6}""#1015		);1016	}10171018	#[test]1019	fn parse_json() {1020		assert_json!(1021			r#"std.parseJson('{"a": -1,"b": 1,"c": 3.141,"d": []}')"#,1022			r#"{"a": -1,"b": 1,"c": 3.141,"d": []}"#1023		);1024	}10251026	#[test]1027	fn test() {1028		assert_json!(1029			r#"[[a, b] for a in [1,2,3] for b in [4,5,6]]"#,1030			"[[1,4],[1,5],[1,6],[2,4],[2,5],[2,6],[3,4],[3,5],[3,6]]"1031		);1032	}10331034	#[test]1035	fn sjsonnet() {1036		eval!(1037			r#"1038			local x0 = {k: 1};1039			local x1 = {k: x0.k + x0.k};1040			local x2 = {k: x1.k + x1.k};1041			local x3 = {k: x2.k + x2.k};1042			local x4 = {k: x3.k + x3.k};1043			local x5 = {k: x4.k + x4.k};1044			local x6 = {k: x5.k + x5.k};1045			local x7 = {k: x6.k + x6.k};1046			local x8 = {k: x7.k + x7.k};1047			local x9 = {k: x8.k + x8.k};1048			local x10 = {k: x9.k + x9.k};1049			local x11 = {k: x10.k + x10.k};1050			local x12 = {k: x11.k + x11.k};1051			local x13 = {k: x12.k + x12.k};1052			local x14 = {k: x13.k + x13.k};1053			local x15 = {k: x14.k + x14.k};1054			local x16 = {k: x15.k + x15.k};1055			local x17 = {k: x16.k + x16.k};1056			local x18 = {k: x17.k + x17.k};1057			local x19 = {k: x18.k + x18.k};1058			local x20 = {k: x19.k + x19.k};1059			local x21 = {k: x20.k + x20.k};1060			x21.k1061		"#1062		);1063	}10641065	// This test is commented out by default, because of huge compilation slowdown1066	// #[bench]1067	// fn bench_codegen(b: &mut Bencher) {1068	// 	b.iter(|| {1069	// 		#[allow(clippy::all)]1070	// 		let stdlib = {1071	// 			use jrsonnet_parser::*;1072	// 			include!(concat!(env!("OUT_DIR"), "/stdlib.rs"))1073	// 		};1074	// 		stdlib1075	// 	})1076	// }10771078	/*1079	#[bench]1080	fn bench_serialize(b: &mut Bencher) {1081		b.iter(|| {1082			bincode::deserialize::<jrsonnet_parser::LocExpr>(include_bytes!(concat!(1083				env!("OUT_DIR"),1084				"/stdlib.bincode"1085			)))1086			.expect("deserialize stdlib")1087		})1088	}10891090	#[bench]1091	fn bench_parse(b: &mut Bencher) {1092		b.iter(|| {1093			jrsonnet_parser::parse(1094				jrsonnet_stdlib::STDLIB_STR,1095				&jrsonnet_parser::ParserSettings {1096					loc_data: true,1097					file_name: Rc::new(PathBuf::from("std.jsonnet")),1098				},1099			)1100		})1101	}1102	*/11031104	#[test]1105	fn equality() {1106		println!(1107			"{:?}",1108			jrsonnet_parser::parse(1109				"{ x: 1, y: 2 } == { x: 1, y: 2 }",1110				&ParserSettings {1111					file_name: PathBuf::from("equality").into(),1112				}1113			)1114		);1115		assert_eval!("{ x: 1, y: 2 } == { x: 1, y: 2 }")1116	}11171118	#[test]1119	fn native_ext() -> crate::error::Result<()> {1120		use super::native::NativeCallback;1121		let evaluator = EvaluationState::default();11221123		evaluator.with_stdlib();11241125		#[derive(Trace)]1126		struct NativeAdd;1127		impl NativeCallbackHandler for NativeAdd {1128			fn call(&self, from: Option<Rc<Path>>, args: &[Val]) -> crate::error::Result<Val> {1129				assert_eq!(1130					&from.unwrap() as &Path,1131					&PathBuf::from("native_caller.jsonnet")1132				);1133				match (&args[0], &args[1]) {1134					(Val::Num(a), Val::Num(b)) => Ok(Val::Num(a + b)),1135					(_, _) => unreachable!(),1136				}1137			}1138		}1139		evaluator.settings_mut().ext_natives.insert(1140			"native_add".into(),1141			#[allow(deprecated)]1142			Cc::new(TraceBox(Box::new(NativeCallback::new(1143				vec![1144					BuiltinParam {1145						name: "a".into(),1146						has_default: false,1147					},1148					BuiltinParam {1149						name: "b".into(),1150						has_default: false,1151					},1152				],1153				TraceBox(Box::new(NativeAdd)),1154			)))),1155		);1156		evaluator.evaluate_snippet_raw(1157			PathBuf::from("native_caller.jsonnet").into(),1158			"std.assertEqual(std.native(\"native_add\")(1, 2), 3)".into(),1159		)?;1160		Ok(())1161	}11621163	#[test]1164	fn constant_intrinsic() -> crate::error::Result<()> {1165		assert_eval!(1166			"local std2 = std; local std = std2 { primitiveEquals(a, b):: false }; 1 == 1"1167		);1168		Ok(())1169	}11701171	#[test]1172	fn standalone_super() -> crate::error::Result<()> {1173		assert_eval!(1174			r#"1175			local obj = {1176				a: 1,1177				b: 2,1178				c: 3,1179			};1180			local test = obj + {1181				fields: std.objectFields(super),1182				d: 5,1183			};1184			test.fields == ['a', 'b', 'c']1185		"#1186		);1187		Ok(())1188	}11891190	#[test]1191	fn comp_self() -> crate::error::Result<()> {1192		assert_eval!(1193			r#"1194			std.objectFields({1195				a:{1196					[name]: name for name in std.objectFields(self)1197				},1198				b: 2,1199				c: 3,1200			}.a) == ['a', 'b', 'c']1201			"#1202		);12031204		Ok(())1205	}12061207	struct TestImportResolver(IStr);1208	impl crate::import::ImportResolver for TestImportResolver {1209		fn resolve_file(&self, _: &Path, _: &Path) -> crate::error::Result<Rc<Path>> {1210			Ok(PathBuf::from("/test").into())1211		}12121213		fn load_file_contents(&self, _: &Path) -> crate::error::Result<IStr> {1214			Ok(self.0.clone())1215		}12161217		unsafe fn as_any(&self) -> &dyn std::any::Any {1218			panic!()1219		}1220	}12211222	#[test]1223	fn issue_23() {1224		let state = EvaluationState::default();1225		state.set_import_resolver(Box::new(TestImportResolver(r#"import "/test""#.into())));1226		let _ = state.evaluate_file_raw(&PathBuf::from("/test"));1227	}12281229	#[test]1230	fn issue_40() {1231		let state = EvaluationState::default();1232		state.with_stdlib();12331234		let error = state1235			.evaluate_snippet_raw(1236				PathBuf::from("issue40.jsonnet").into(),1237				r#"1238				local conf = {1239					n: ""1240				};12411242				local result = conf + {1243					assert std.isNumber(self.n): "is number"1244				};12451246				std.manifestJsonEx(result, "")1247			"#1248				.into(),1249			)1250			.unwrap_err();1251		assert_eq!(error.error().to_string(), "assert failed: is number");1252	}12531254	#[test]1255	fn test_ascii_upper_lower() {1256		assert_eval!(r#"std.assertEqual(std.asciiUpper("aBc😀"), "ABC😀")"#);1257		assert_eval!(r#"std.assertEqual(std.asciiLower("aBc😀"), "abc😀")"#);1258	}12591260	#[test]1261	fn test_member() {1262		assert_eval!(r#"!std.member("", "")"#);1263		assert_eval!(r#"std.member("abc", "a")"#);1264		assert_eval!(r#"!std.member("abc", "d")"#);1265		assert_eval!(r#"!std.member([], "")"#);1266		assert_eval!(r#"std.member(["a", "b", "c"], "a")"#);1267		assert_eval!(r#"!std.member(["a", "b", "c"], "d")"#);1268	}12691270	#[test]1271	fn test_count() {1272		assert_eval!(r#"std.assertEqual(std.count([], ""), 0)"#);1273		assert_eval!(r#"std.assertEqual(std.count(["a", "b", "a"], "d"), 0)"#);1274		assert_eval!(r#"std.assertEqual(std.count(["a", "b", "a"], "a"), 2)"#);1275	}12761277	mod derive_typed {1278		use crate::{typed::Typed, EvaluationState};1279		use std::path::PathBuf;12801281		#[derive(Typed, PartialEq, Debug)]1282		struct MyTyped {1283			a: u32,1284			#[typed(rename = "b")]1285			c: String,1286		}12871288		#[test]1289		fn test() {1290			let es = EvaluationState::default();1291			let val = eval!("{a: 14, b: 'Hello, world!'}");1292			let typed = es.run_in_state(|| MyTyped::try_from(val).unwrap());12931294			assert_eq!(1295				typed,1296				MyTyped {1297					a: 14,1298					c: "Hello, world!".to_string()1299				}1300			);1301			es.settings_mut().globals.insert(1302				"mytyped".into(),1303				es.run_in_state(|| typed.try_into()).unwrap(),1304			);13051306			let v = es1307				.evaluate_snippet_raw(1308					PathBuf::from("raw.jsonnet").into(),1309					"1310				mytyped == {a: 14, b: 'Hello, world!'}1311			"1312					.into(),1313				)1314				.unwrap()1315				.as_bool()1316				.unwrap();1317			assert!(v)1318		}1319	}1320}
modifiedcrates/jrsonnet-evaluator/src/native.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/native.rs
+++ b/crates/jrsonnet-evaluator/src/native.rs
@@ -1,11 +1,10 @@
 #![allow(clippy::type_complexity)]
 
-use crate::function::{parse_builtin_call, ArgsLike, Builtin, BuiltinParam};
+use crate::function::{parse_builtin_call, ArgsLike, Builtin, BuiltinParam, CallLocation};
 use crate::gc::TraceBox;
 use crate::Context;
 use crate::{error::Result, Val};
 use gcmodule::Trace;
-use jrsonnet_parser::ExprLocation;
 use std::path::Path;
 use std::rc::Rc;
 
@@ -32,18 +31,13 @@
 		&self.params
 	}
 
-	fn call(
-		&self,
-		context: Context,
-		loc: Option<&ExprLocation>,
-		args: &dyn ArgsLike,
-	) -> Result<Val> {
+	fn call(&self, context: Context, loc: CallLocation, args: &dyn ArgsLike) -> Result<Val> {
 		let args = parse_builtin_call(context, &self.params, args, true)?;
 		let mut out_args = Vec::with_capacity(self.params.len());
 		for p in self.params.iter() {
 			out_args.push(args[&p.name].evaluate()?);
 		}
-		self.handler.call(loc.map(|l| l.0.clone()), &out_args)
+		self.handler.call(loc.0.map(|l| l.0.clone()), &out_args)
 	}
 }
 
modifiedcrates/jrsonnet-evaluator/src/typed/conversions.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/typed/conversions.rs
+++ b/crates/jrsonnet-evaluator/src/typed/conversions.rs
@@ -1,5 +1,6 @@
 use std::convert::{TryFrom, TryInto};
 
+use gcmodule::Cc;
 use jrsonnet_interner::IStr;
 pub use jrsonnet_macros::Typed;
 use jrsonnet_types::{ComplexValType, ValType};
@@ -8,7 +9,7 @@
 	error::{Error::*, LocError, Result},
 	throw,
 	typed::CheckType,
-	ArrValue, FuncVal, IndexableVal, ObjValue, ObjValueBuilder, Val,
+	ArrValue, FuncDesc, FuncVal, IndexableVal, ObjValue, ObjValueBuilder, Val,
 };
 
 pub trait TypedObj: Typed {
@@ -431,6 +432,30 @@
 		Ok(Self::Func(value))
 	}
 }
+
+impl Typed for Cc<FuncDesc> {
+	const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Func);
+}
+impl TryFrom<Val> for Cc<FuncDesc> {
+	type Error = LocError;
+
+	fn try_from(value: Val) -> Result<Self, Self::Error> {
+		<Self as Typed>::TYPE.check(&value)?;
+		match value {
+			Val::Func(FuncVal::Normal(desc)) => Ok(desc.clone()),
+			Val::Func(_) => throw!(RuntimeError("expected normal function, not builtin".into())),
+			_ => unreachable!(),
+		}
+	}
+}
+impl TryFrom<Cc<FuncDesc>> for Val {
+	type Error = LocError;
+
+	fn try_from(value: Cc<FuncDesc>) -> Result<Self, Self::Error> {
+		Ok(Self::Func(FuncVal::Normal(value)))
+	}
+}
+
 impl Typed for ObjValue {
 	const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Obj);
 }
modifiedcrates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/val.rs
+++ b/crates/jrsonnet-evaluator/src/val.rs
@@ -6,14 +6,15 @@
 	error::{Error::*, LocError},
 	evaluate,
 	function::{
-		parse_default_function_call, parse_function_call, ArgsLike, Builtin, StaticBuiltin,
+		parse_default_function_call, parse_function_call, ArgsLike, Builtin, CallLocation,
+		StaticBuiltin,
 	},
 	gc::TraceBox,
 	throw, Context, ObjValue, Result,
 };
 use gcmodule::{Cc, Trace};
 use jrsonnet_interner::IStr;
-use jrsonnet_parser::{ExprLocation, LocExpr, ParamsDesc};
+use jrsonnet_parser::{LocExpr, ParamsDesc};
 use jrsonnet_types::ValType;
 use std::{cell::RefCell, fmt::Debug, rc::Rc};
 
@@ -152,7 +153,7 @@
 	pub fn evaluate(
 		&self,
 		call_ctx: Context,
-		loc: Option<&ExprLocation>,
+		loc: CallLocation,
 		args: &dyn ArgsLike,
 		tailstrict: bool,
 	) -> Result<Val> {
@@ -166,7 +167,7 @@
 		}
 	}
 	pub fn evaluate_simple(&self, args: &dyn ArgsLike) -> Result<Val> {
-		self.evaluate(Context::default(), None, args, true)
+		self.evaluate(Context::default(), CallLocation::native(), args, true)
 	}
 }
 
modifiedcrates/jrsonnet-macros/src/lib.rsdiffbeforeafterboth
--- a/crates/jrsonnet-macros/src/lib.rs
+++ b/crates/jrsonnet-macros/src/lib.rs
@@ -1,5 +1,5 @@
 use proc_macro2::TokenStream;
-use quote::{quote, quote_spanned};
+use quote::quote;
 use syn::{
 	parenthesized,
 	parse::{Parse, ParseStream},
@@ -7,8 +7,8 @@
 	punctuated::Punctuated,
 	spanned::Spanned,
 	token::Comma,
-	Attribute, DeriveInput, Error, FnArg, GenericArgument, Ident, ItemFn, LitStr, Pat, PatType,
-	Path, PathArguments, Result, Token, Type,
+	Attribute, DeriveInput, Error, FnArg, GenericArgument, Ident, ItemFn, LitStr, Pat, Path,
+	PathArguments, Result, ReturnType, Token, Type,
 };
 
 fn parse_attr<A: Parse, I>(attrs: &[Attribute], ident: I) -> Result<Option<A>>
@@ -33,49 +33,42 @@
 	Ok(Some(attr))
 }
 
-fn is_location_arg(t: &PatType) -> bool {
-	t.attrs.iter().any(|a| a.path.is_ident("location"))
-}
-fn is_self_arg(t: &PatType) -> bool {
-	t.attrs.iter().any(|a| a.path.is_ident("self"))
+fn path_is(path: &Path, needed: &str) -> bool {
+	path.leading_colon.is_none()
+		&& path.segments.len() >= 1
+		&& path.segments.iter().last().unwrap().ident == needed
 }
 
-trait RetainHad<T> {
-	fn retain_had(&mut self, h: impl FnMut(&T) -> bool) -> bool;
-}
-impl<T> RetainHad<T> for Vec<T> {
-	fn retain_had(&mut self, h: impl FnMut(&T) -> bool) -> bool {
-		let before = self.len();
-		self.retain(h);
-		let after = self.len();
-		before != after
+fn type_is_path<'ty>(ty: &'ty Type, needed: &str) -> Option<&'ty PathArguments> {
+	match ty {
+		Type::Path(path) if path.qself.is_none() && path_is(&path.path, needed) => {
+			let args = &path.path.segments.iter().last().unwrap().arguments;
+			Some(args)
+		}
+		_ => None,
 	}
 }
 
-fn extract_type_from_option(ty: &Type) -> Option<&Type> {
-	fn path_is_option(path: &Path) -> bool {
-		path.leading_colon.is_none()
-			&& path.segments.len() == 1
-			&& path.segments.iter().next().unwrap().ident == "Option"
-	}
-
-	match ty {
-		Type::Path(typepath) if typepath.qself.is_none() && path_is_option(&typepath.path) => {
-			// Get the first segment of the path (there is only one, in fact: "Option"):
-			let type_params = &typepath.path.segments.iter().next().unwrap().arguments;
-			// It should have only on angle-bracketed param ("<String>"):
-			let generic_arg = match type_params {
-				PathArguments::AngleBracketed(params) => params.args.iter().next().unwrap(),
-				_ => panic!("missing option generic"),
-			};
-			// This argument must be a type:
-			match generic_arg {
-				GenericArgument::Type(ty) => Some(ty),
-				_ => panic!("option generic should be a type"),
+fn extract_type_from_option(ty: &Type) -> Result<Option<&Type>> {
+	Ok(if let Some(args) = type_is_path(ty, "Option") {
+		// It should have only on angle-bracketed param ("<String>"):
+		let generic_arg = match args {
+			PathArguments::AngleBracketed(params) => params.args.iter().next().unwrap(),
+			_ => return Err(Error::new(args.span(), "missing option generic")),
+		};
+		// This argument must be a type:
+		match generic_arg {
+			GenericArgument::Type(ty) => Some(ty),
+			_ => {
+				return Err(Error::new(
+					generic_arg.span(),
+					"option generic should be a type",
+				))
 			}
 		}
-		_ => None,
-	}
+	} else {
+		None
+	})
 }
 
 struct Field {
@@ -101,7 +94,7 @@
 
 struct EmptyAttr;
 impl Parse for EmptyAttr {
-	fn parse(input: ParseStream) -> Result<Self> {
+	fn parse(_input: ParseStream) -> Result<Self> {
 		Ok(Self)
 	}
 }
@@ -124,107 +117,158 @@
 	}
 }
 
+enum ArgInfo {
+	Normal {
+		ty: Type,
+		is_option: bool,
+		name: String,
+		// ident: Ident,
+	},
+	Lazy {
+		is_option: bool,
+		name: String,
+	},
+	Location,
+	This,
+}
+
+impl ArgInfo {
+	fn parse(arg: &FnArg) -> Result<Self> {
+		let typed = match arg {
+			FnArg::Receiver(_) => unreachable!(),
+			FnArg::Typed(a) => a,
+		};
+		let ident = match &typed.pat as &Pat {
+			Pat::Ident(i) => i.ident.clone(),
+			_ => {
+				return Err(Error::new(
+					typed.pat.span(),
+					"arg should be plain identifier",
+				))
+			}
+		};
+		let ty = &typed.ty as &Type;
+		if type_is_path(&ty, "CallLocation").is_some() {
+			return Ok(Self::Location);
+		} else if type_is_path(&ty, "Self").is_some() {
+			return Ok(Self::This);
+		} else if type_is_path(&ty, "LazyVal").is_some() {
+			return Ok(Self::Lazy {
+				is_option: false,
+				name: ident.to_string(),
+			});
+		}
+
+		let (is_option, ty) = if let Some(ty) = extract_type_from_option(&ty)? {
+			if type_is_path(&ty, "LazyVal").is_some() {
+				return Ok(Self::Lazy {
+					is_option: true,
+					name: ident.to_string(),
+				});
+			}
+
+			(true, ty.clone())
+		} else {
+			(false, ty.clone())
+		};
+
+		Ok(Self::Normal {
+			ty,
+			is_option,
+			name: ident.to_string(),
+			// ident,
+		})
+	}
+}
+
 #[proc_macro_attribute]
 pub fn builtin(
 	attr: proc_macro::TokenStream,
 	item: proc_macro::TokenStream,
 ) -> proc_macro::TokenStream {
-	let attrs = parse_macro_input!(attr as BuiltinAttrs);
-	let mut fun: ItemFn = parse_macro_input!(item);
+	let attr = parse_macro_input!(attr as BuiltinAttrs);
+	let item: ItemFn = parse_macro_input!(item);
+
+	match builtin_inner(attr, item) {
+		Ok(v) => v.into(),
+		Err(e) => e.into_compile_error().into(),
+	}
+}
 
+fn builtin_inner(attr: BuiltinAttrs, fun: ItemFn) -> syn::Result<TokenStream> {
 	let result = match fun.sig.output {
-		syn::ReturnType::Default => {
-			return quote_spanned! { fun.sig.span() =>
-				compile_error!("builtins should return something");
-			}
-			.into()
+		ReturnType::Default => {
+			return Err(Error::new(
+				fun.sig.span(),
+				"builtin should return something",
+			))
 		}
-		syn::ReturnType::Type(_, ref ty) => ty.clone(),
+		ReturnType::Type(_, ref ty) => ty.clone(),
 	};
 
-	let params = fun
+	let args = fun
 		.sig
 		.inputs
 		.iter()
-		.map(|i| match i {
-			FnArg::Receiver(_) => unreachable!(),
-			FnArg::Typed(t) => t,
-		})
-		.filter(|a| !is_location_arg(a) && !is_self_arg(a))
-		.map(|t| {
-			let ident = match &t.pat as &Pat {
-				Pat::Ident(i) => i.ident.to_string(),
-				_ => {
-					return quote_spanned! { t.pat.span() =>
-						compile_error!("args should be plain identifiers")
-					}
-					.into()
-				}
-			};
-			let optional = extract_type_from_option(&t.ty).is_some();
-			quote! {
-				BuiltinParam {
-					name: std::borrow::Cow::Borrowed(#ident),
-					has_default: #optional,
-				}
+		.map(|a| ArgInfo::parse(a))
+		.collect::<Result<Vec<_>>>()?;
+
+	let params_desc = args.iter().flat_map(|a| match a {
+		ArgInfo::Normal {
+			is_option, name, ..
+		}
+		| ArgInfo::Lazy { is_option, name } => Some(quote! {
+			BuiltinParam {
+				name: std::borrow::Cow::Borrowed(#name),
+				has_default: #is_option,
 			}
-		})
-		.collect::<Vec<_>>();
+		}),
+		ArgInfo::Location => None,
+		ArgInfo::This => None,
+	});
 
-	let args = fun
-		.sig
-		.inputs
-		.iter_mut()
-		.map(|i| match i {
-			FnArg::Receiver(_) => unreachable!(),
-			FnArg::Typed(t) => t,
-		})
-		.map(|t| {
-			if t.attrs.retain_had(|a| !a.path.is_ident("location")) {
-				quote! {{
-					loc
+	let pass = args.iter().map(|a| match a {
+		ArgInfo::Normal {
+			ty,
+			is_option,
+			name,
+			// ident,
+		} => {
+			let eval = quote! {::jrsonnet_evaluator::push_description_frame(
+				|| format!("argument <{}> evaluation", #name),
+				|| <#ty>::try_from(value.evaluate()?),
+			)?};
+			if *is_option {
+				quote! {if let Some(value) = parsed.get(#name) {
+					Some(#eval)
+				} else {
+					None
 				}}
-			} else if t.attrs.retain_had(|a| !a.path.is_ident("self")) {
+			} else {
 				quote! {{
-					self
+					let value = parsed.get(#name).expect("args shape is checked");
+					#eval
 				}}
-			} else {
-				let ident = match &t.pat as &Pat {
-					Pat::Ident(i) => i.ident.to_string(),
-					_ => {
-						return quote_spanned! { t.pat.span() =>
-							compile_error!("args should be plain identifiers")
-						}
-						.into()
-					}
-				};
-				let ty = &t.ty;
-				if let Some(opt_ty) = extract_type_from_option(&t.ty) {
-					quote! {{
-						if let Some(value) = parsed.get(#ident) {
-							Some(::jrsonnet_evaluator::push_description_frame(
-								|| format!("argument <{}> evaluation", #ident),
-								|| <#opt_ty>::try_from(value.evaluate()?),
-							)?)
-						} else {
-							None
-						}
-					}}
+			}
+		}
+		ArgInfo::Lazy { is_option, name } => {
+			if *is_option {
+				quote! {if let Some(value) = parsed.get(#name) {
+					Some(value.clone())
 				} else {
-					quote! {{
-						let value = parsed.get(#ident).unwrap();
-
-						::jrsonnet_evaluator::push_description_frame(
-							|| format!("argument <{}> evaluation", #ident),
-							|| <#ty>::try_from(value.evaluate()?),
-						)?
-					}}
+					None
+				}}
+			} else {
+				quote! {
+					parsed.get(#name).expect("args shape is correct").clone()
 				}
 			}
-		})
-		.collect::<Vec<_>>();
+		}
+		ArgInfo::Location => quote! {location},
+		ArgInfo::This => quote! {self},
+	});
 
-	let fields = attrs.fields.iter().map(|field| {
+	let fields = attr.fields.iter().map(|field| {
 		let name = &field.name;
 		let ty = &field.ty;
 		quote! {
@@ -234,7 +278,7 @@
 
 	let name = &fun.sig.ident;
 	let vis = &fun.vis;
-	let static_ext = if attrs.fields.is_empty() {
+	let static_ext = if attr.fields.is_empty() {
 		quote! {
 			impl #name {
 				pub const INST: &'static dyn StaticBuiltin = &#name {};
@@ -244,13 +288,13 @@
 	} else {
 		quote! {}
 	};
-	let static_derive_copy = if attrs.fields.is_empty() {
+	let static_derive_copy = if attr.fields.is_empty() {
 		quote! {, Copy}
 	} else {
 		quote! {}
 	};
 
-	(quote! {
+	Ok(quote! {
 		#fun
 		#[doc(hidden)]
 		#[allow(non_camel_case_types)]
@@ -260,12 +304,12 @@
 		}
 		const _: () = {
 			use ::jrsonnet_evaluator::{
-				function::{Builtin, StaticBuiltin, BuiltinParam, ArgsLike, parse_builtin_call},
+				function::{Builtin, CallLocation, StaticBuiltin, BuiltinParam, ArgsLike, parse_builtin_call},
 				error::Result, Context,
 				parser::ExprLocation,
 			};
 			const PARAMS: &'static [BuiltinParam] = &[
-				#(#params),*
+				#(#params_desc),*
 			];
 
 			#static_ext
@@ -279,17 +323,16 @@
 				fn params(&self) -> &[BuiltinParam] {
 					PARAMS
 				}
-				fn call(&self, context: Context, loc: Option<&ExprLocation>, args: &dyn ArgsLike) -> Result<Val> {
+				fn call(&self, context: Context, location: CallLocation, args: &dyn ArgsLike) -> Result<Val> {
 					let parsed = parse_builtin_call(context, &PARAMS, args, false)?;
 
-					let result: #result = #name(#(#args),*);
+					let result: #result = #name(#(#pass),*);
 					let result = result?;
 					result.try_into()
 				}
 			}
 		};
 	})
-	.into()
 }
 
 #[derive(Default)]
@@ -366,15 +409,6 @@
 		)
 	}
 
-	fn expand_shallow_field(&self) -> Option<TokenStream> {
-		if self.is_option() {
-			return None;
-		}
-		let name = self.name()?;
-		Some(quote! {
-			(#name, ComplexValType::Any)
-		})
-	}
 	fn expand_field(&self) -> Option<TokenStream> {
 		if self.is_option() {
 			return None;
@@ -450,7 +484,7 @@
 	}
 
 	fn as_option(&self) -> Option<&Type> {
-		extract_type_from_option(&self.0.ty)
+		extract_type_from_option(&self.0.ty).unwrap()
 	}
 	fn is_option(&self) -> bool {
 		self.as_option().is_some()
@@ -460,25 +494,25 @@
 #[proc_macro_derive(Typed, attributes(typed))]
 pub fn derive_typed(item: proc_macro::TokenStream) -> proc_macro::TokenStream {
 	let input = parse_macro_input!(item as DeriveInput);
+
+	match derive_typed_inner(input) {
+		Ok(v) => v.into(),
+		Err(e) => e.to_compile_error().into(),
+	}
+}
+
+fn derive_typed_inner(input: DeriveInput) -> Result<TokenStream> {
 	let data = match &input.data {
 		syn::Data::Struct(s) => s,
-		_ => {
-			return syn::Error::new(input.span(), "only structs supported")
-				.to_compile_error()
-				.into()
-		}
+		_ => return Err(Error::new(input.span(), "only structs supported")),
 	};
 
 	let ident = &input.ident;
-	let fields = match data
+	let fields = data
 		.fields
 		.iter()
 		.map(TypedField::try_new)
-		.collect::<Result<Vec<_>>>()
-	{
-		Ok(v) => v,
-		Err(e) => return e.to_compile_error().into(),
-	};
+		.collect::<Result<Vec<_>>>()?;
 
 	let typed = {
 		let fields = fields
@@ -499,7 +533,7 @@
 	let fields_parse = fields.iter().map(TypedField::expand_parse);
 	let fields_serialize = fields.iter().map(TypedField::expand_serialize);
 
-	quote! {
+	Ok(quote! {
 		const _: () = {
 			use ::jrsonnet_evaluator::{
 				typed::{ComplexValType, Typed, TypedObj, CheckType},
@@ -540,6 +574,5 @@
 			}
 			()
 		};
-	}
-	.into()
+	})
 }