git.delta.rocks / jrsonnet / refs/commits / 9f8d4fc520b3

difftreelog

feat friendlier errors

Yaroslav Bolyukin2022-05-26parent: #96da6f3.patch.diff
in: master

8 files changed

modifiedCargo.lockdiffbeforeafterboth
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3,6 +3,17 @@
 version = 3
 
 [[package]]
+name = "ahash"
+version = "0.7.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fcb51a0695d8f838b1ee009b3fbf66bda078cd64590202a864a8f3e8c4315c47"
+dependencies = [
+ "getrandom",
+ "once_cell",
+ "version_check",
+]
+
+[[package]]
 name = "annotate-snippets"
 version = "0.9.1"
 source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -69,6 +80,12 @@
 checksum = "4785bdd1c96b2a846b2bd7cc02e86b6b3dbf14e7e53446c4f54c92a361040822"
 
 [[package]]
+name = "cfg-if"
+version = "1.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
+
+[[package]]
 name = "clap"
 version = "3.1.13"
 source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -152,12 +169,32 @@
 ]
 
 [[package]]
+name = "getrandom"
+version = "0.2.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9be70c98951c83b8d2f8f60d7065fa6d5146873094452a1008da8c2f1e4205ad"
+dependencies = [
+ "cfg-if 1.0.0",
+ "libc",
+ "wasi",
+]
+
+[[package]]
 name = "hashbrown"
 version = "0.11.2"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "ab5ef0d4909ef3724cc8cce6ccc8572c5c817592e9285f5464f8e86f8bd3726e"
 
 [[package]]
+name = "hashbrown"
+version = "0.12.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "db0d4cf898abf0081f964436dc980e96670a0f36863e4b83aaacdb65c9d7ccc3"
+dependencies = [
+ "ahash",
+]
+
+[[package]]
 name = "heck"
 version = "0.4.0"
 source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -179,7 +216,7 @@
 checksum = "bc633605454125dec4b66843673f01c7df2b89479b32e0ed634e43a91cff62a5"
 dependencies = [
  "autocfg",
- "hashbrown",
+ "hashbrown 0.11.2",
 ]
 
 [[package]]
@@ -221,6 +258,7 @@
  "base64",
  "bincode",
  "gcmodule",
+ "hashbrown 0.12.1",
  "jrsonnet-interner",
  "jrsonnet-macros",
  "jrsonnet-parser",
@@ -232,6 +270,8 @@
  "serde",
  "serde_json",
  "serde_yaml",
+ "static_assertions",
+ "strsim",
  "thiserror",
 ]
 
@@ -240,6 +280,7 @@
 version = "0.4.2"
 dependencies = [
  "gcmodule",
+ "hashbrown 0.12.1",
  "rustc-hash",
  "serde",
 ]
@@ -262,6 +303,7 @@
  "jrsonnet-stdlib",
  "peg",
  "serde",
+ "static_assertions",
 ]
 
 [[package]]
@@ -293,9 +335,9 @@
 
 [[package]]
 name = "libc"
-version = "0.2.108"
+version = "0.2.125"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "8521a1b57e76b1ec69af7599e75e38e7b7fad6610f037db8c79b127201b5d119"
+checksum = "5916d2ae698f6de9bfb891ad7a8d65c09d232dc58cc4ac433c7da3b2fd84bc2b"
 
 [[package]]
 name = "linked-hash-map"
@@ -338,6 +380,12 @@
 ]
 
 [[package]]
+name = "once_cell"
+version = "1.10.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "87f3e037eac156d1775da914196f0f37741a274155e34a0b7e427c35d2a2ecb9"
+
+[[package]]
 name = "os_str_bytes"
 version = "6.0.0"
 source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -359,7 +407,7 @@
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "d58c7c768d4ba344e3e8d72518ac13e259d7c7ade24167003b8488e10b6740a3"
 dependencies = [
- "cfg-if",
+ "cfg-if 0.1.10",
  "cloudabi",
  "libc",
  "redox_syscall",
@@ -516,6 +564,12 @@
 checksum = "1ecab6c735a6bb4139c0caafd0cc3635748bbb3acf4550e8138122099251f309"
 
 [[package]]
+name = "static_assertions"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"
+
+[[package]]
 name = "strsim"
 version = "0.10.0"
 source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -598,6 +652,12 @@
 checksum = "5fecdca9a5291cc2b8dcf7dc02453fee791a280f3743cb0905f8822ae463b3fe"
 
 [[package]]
+name = "wasi"
+version = "0.10.2+wasi-snapshot-preview1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fd6fbd9a79829dd1ad0cc20627bf1ed606756a7f77edff7b66b7064f9cb327c6"
+
+[[package]]
 name = "winapi"
 version = "0.3.9"
 source = "registry+https://github.com/rust-lang/crates.io-index"
modifiedCargo.tomldiffbeforeafterboth
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,9 +1,5 @@
 [workspace]
-members = [
-	"crates/*",
-	"bindings/jsonnet",
-	"cmds/jrsonnet",
-]
+members = ["crates/*", "bindings/jsonnet", "cmds/jrsonnet"]
 
 [profile.test]
 opt-level = 1
@@ -14,3 +10,4 @@
 codegen-units = 1
 debug = 0
 panic = "abort"
+strip = true
modifiedbindings/jsonnet/src/import.rsdiffbeforeafterboth
--- a/bindings/jsonnet/src/import.rs
+++ b/bindings/jsonnet/src/import.rs
@@ -32,9 +32,9 @@
 	out: RefCell<HashMap<PathBuf, Vec<u8>>>,
 }
 impl ImportResolver for CallbackImportResolver {
-	fn resolve_file(&self, from: &Path, path: &Path) -> Result<PathBuf> {
+	fn resolve_file(&self, from: &Path, path: &str) -> Result<PathBuf> {
 		let base = CString::new(from.to_str().unwrap()).unwrap().into_raw();
-		let rel = CString::new(path.to_str().unwrap()).unwrap().into_raw();
+		let rel = CString::new(path).unwrap().into_raw();
 		let found_here: *mut c_char = null_mut();
 		let mut success: i32 = 0;
 		let result_ptr = unsafe {
@@ -108,17 +108,17 @@
 	}
 }
 impl ImportResolver for NativeImportResolver {
-	fn resolve_file(&self, from: &Path, path: &Path) -> Result<PathBuf> {
+	fn resolve_file(&self, from: &Path, path: &str) -> Result<PathBuf> {
 		let mut new_path = from.to_owned();
 		new_path.push(path);
 		if new_path.exists() {
-			Ok(new_path.into())
+			Ok(new_path)
 		} else {
 			for library_path in self.library_paths.borrow().iter() {
 				let mut cloned = library_path.clone();
 				cloned.push(path);
 				if cloned.exists() {
-					return Ok(cloned.into());
+					return Ok(cloned);
 				}
 			}
 			throw!(ImportFileNotFound(from.to_owned(), path.to_owned()))
modifiedbindings/jsonnet/src/vars_tlas.rsdiffbeforeafterboth
--- a/bindings/jsonnet/src/vars_tlas.rs
+++ b/bindings/jsonnet/src/vars_tlas.rs
@@ -20,11 +20,8 @@
 pub unsafe extern "C" fn jsonnet_ext_code(vm: &State, name: *const c_char, value: *const c_char) {
 	let name = CStr::from_ptr(name);
 	let value = CStr::from_ptr(value);
-	vm.add_ext_code(
-		name.to_str().unwrap().into(),
-		value.to_str().unwrap().into(),
-	)
-	.unwrap()
+	vm.add_ext_code(name.to_str().unwrap(), value.to_str().unwrap().into())
+		.unwrap()
 }
 /// # Safety
 #[no_mangle]
@@ -41,9 +38,6 @@
 pub unsafe extern "C" fn jsonnet_tla_code(vm: &State, name: *const c_char, value: *const c_char) {
 	let name = CStr::from_ptr(name);
 	let value = CStr::from_ptr(value);
-	vm.add_tla_code(
-		name.to_str().unwrap().into(),
-		value.to_str().unwrap().into(),
-	)
-	.unwrap()
+	vm.add_tla_code(name.to_str().unwrap().into(), value.to_str().unwrap())
+		.unwrap()
 }
modifiedcrates/jrsonnet-evaluator/Cargo.tomldiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/Cargo.toml
+++ b/crates/jrsonnet-evaluator/Cargo.toml
@@ -7,13 +7,16 @@
 edition = "2021"
 
 [features]
-default = ["serialized-stdlib", "explaining-traces"]
+default = ["serialized-stdlib", "explaining-traces", "friendly-errors"]
 # Serializes standard library AST instead of parsing them every run
 serialized-stdlib = ["bincode", "jrsonnet-parser/serde"]
 # Rustc-like trace visualization
 explaining-traces = ["annotate-snippets"]
 # Allows library authors to throw custom errors
 anyhow-error = ["anyhow"]
+# Provides helpful explaintations to errors, at cost of adding
+# more dependencies and slowing down error path
+friendly-errors = ["strsim"]
 
 # Allows to preserve field order in objects
 exp-preserve-order = []
@@ -42,20 +45,13 @@
 serde_json = "1.0"
 serde_yaml = { git = "https://github.com/CertainLach/serde-yaml", branch = "feature/old-octals-quirk" }
 
-[dependencies.anyhow]
-version = "1.0"
-optional = true
-
+anyhow = { version = "1.0", optional = true }
+# Friendly errors
+strsim = { version = "0.10.0", optional = true }
 # Serialized stdlib
-[dependencies.bincode]
-version = "1.3"
-optional = true
-
+bincode = { version = "1.3", optional = true }
 # Explaining traces
-[dependencies.annotate-snippets]
-version = "0.9.1"
-features = ["color"]
-optional = true
+annotate-snippets = { version = "0.9.1", features = ["color"], optional = true }
 
 [build-dependencies]
 jrsonnet-stdlib = { path = "../jrsonnet-stdlib", version = "0.4.2" }
modifiedcrates/jrsonnet-evaluator/src/ctx.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/ctx.rs
+++ b/crates/jrsonnet-evaluator/src/ctx.rs
@@ -49,13 +49,40 @@
 		}))
 	}
 
+	#[cfg(not(feature = "friendly-errors"))]
 	pub fn binding(&self, name: IStr) -> Result<Thunk<Val>> {
 		Ok(self
 			.0
 			.bindings
 			.get(&name)
 			.cloned()
-			.ok_or(VariableIsNotDefined(name))?)
+			.ok_or(VariableIsNotDefined(name, vec![]))?)
+	}
+
+	#[cfg(feature = "friendly-errors")]
+	pub fn binding(&self, name: IStr) -> Result<Thunk<Val>> {
+		use std::cmp::Ordering;
+
+		use crate::throw;
+
+		if let Some(val) = self.0.bindings.get(&name).cloned() {
+			return Ok(val);
+		}
+
+		let mut heap = Vec::new();
+		self.0.bindings.clone().iter_keys(|k| {
+			let conf = strsim::jaro_winkler(&k as &str, &name as &str);
+			if conf < 0.8 {
+				return;
+			}
+			heap.push((conf, k));
+		});
+		heap.sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap_or(Ordering::Equal));
+
+		throw!(VariableIsNotDefined(
+			name,
+			heap.into_iter().map(|(_, k)| k).collect()
+		))
 	}
 	pub fn contains_binding(&self, name: IStr) -> bool {
 		self.0.bindings.contains_key(&name)
modifiedcrates/jrsonnet-evaluator/src/error.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/error.rs
+++ b/crates/jrsonnet-evaluator/src/error.rs
@@ -11,6 +11,30 @@
 	typed::TypeLocError,
 };
 
+fn format_found(list: &[IStr], what: &str) -> String {
+	if list.is_empty() {
+		return String::new();
+	}
+	let mut out = String::new();
+	out.push_str("\nThere is ");
+	out.push_str(what);
+	if list.len() > 1 {
+		out.push('s');
+	}
+	out.push_str(" with similar name");
+	if list.len() > 1 {
+		out.push('s');
+	}
+	out.push_str(" present: ");
+	for (i, v) in list.iter().enumerate() {
+		if i != 0 {
+			out.push_str(", ");
+		}
+		out.push_str(v as &str);
+	}
+	out
+}
+
 #[derive(Error, Debug, Clone, Trace)]
 pub enum Error {
 	#[error("intrinsic not found: {0}")]
@@ -39,15 +63,15 @@
 	#[error("assert failed: {0}")]
 	AssertionFailed(IStr),
 
-	#[error("variable is not defined: {0}")]
-	VariableIsNotDefined(IStr),
+	#[error("variable is not defined: {0}{}", format_found(.1, "variable"))]
+	VariableIsNotDefined(IStr, Vec<IStr>),
 	#[error("duplicate local var: {0}")]
 	DuplicateLocalVar(IStr),
 
 	#[error("type mismatch: expected {}, got {2} {0}", .1.iter().map(|e| format!("{}", e)).collect::<Vec<_>>().join(", "))]
 	TypeMismatch(&'static str, Vec<ValType>, ValType),
-	#[error("no such field: {0}")]
-	NoSuchField(IStr),
+	#[error("no such field: {0}{}", format_found(.1, "field"))]
+	NoSuchField(IStr, Vec<IStr>),
 
 	#[error("only functions can be called, got {0}")]
 	OnlyFunctionsCanBeCalledGot(ValType),
modifiedcrates/jrsonnet-evaluator/src/evaluate/mod.rsdiffbeforeafterboth
before · crates/jrsonnet-evaluator/src/evaluate/mod.rs
1use std::rc::Rc;23use gcmodule::{Cc, Trace};4use jrsonnet_interner::IStr;5use jrsonnet_parser::{6	ArgsDesc, AssertStmt, BindSpec, CompSpec, Expr, FieldMember, FieldName, ForSpecData,7	IfSpecData, LiteralType, LocExpr, Member, ObjBody, ParamsDesc,8};9use jrsonnet_types::ValType;1011use crate::{12	destructure::evaluate_dest,13	error::Error::*,14	evaluate::operator::{evaluate_add_op, evaluate_binary_op_special, evaluate_unary_op},15	function::{CallLocation, FuncDesc, FuncVal},16	stdlib::{std_slice, BUILTINS},17	tb, throw,18	typed::Typed,19	val::{ArrValue, CachedUnbound, Thunk, ThunkValue},20	Context, GcHashMap, ObjValue, ObjValueBuilder, ObjectAssertion, Pending, Result, State,21	Unbound, Val,22};23pub mod destructure;24pub mod operator;2526pub fn evaluate_method(ctx: Context, name: IStr, params: ParamsDesc, body: LocExpr) -> Val {27	Val::Func(FuncVal::Normal(Cc::new(FuncDesc {28		name,29		ctx,30		params,31		body,32	})))33}3435pub fn evaluate_field_name(s: State, ctx: Context, field_name: &FieldName) -> Result<Option<IStr>> {36	Ok(match field_name {37		FieldName::Fixed(n) => Some(n.clone()),38		FieldName::Dyn(expr) => s.push(39			CallLocation::new(&expr.1),40			|| "evaluating field name".to_string(),41			|| {42				let value = evaluate(s.clone(), ctx, expr)?;43				if matches!(value, Val::Null) {44					Ok(None)45				} else {46					Ok(Some(IStr::from_untyped(value, s.clone())?))47				}48			},49		)?,50	})51}5253pub fn evaluate_comp(54	s: State,55	ctx: Context,56	specs: &[CompSpec],57	callback: &mut impl FnMut(Context) -> Result<()>,58) -> Result<()> {59	match specs.get(0) {60		None => callback(ctx)?,61		Some(CompSpec::IfSpec(IfSpecData(cond))) => {62			if bool::from_untyped(evaluate(s.clone(), ctx.clone(), cond)?, s.clone())? {63				evaluate_comp(s, ctx, &specs[1..], callback)?;64			}65		}66		Some(CompSpec::ForSpec(ForSpecData(var, expr))) => {67			match evaluate(s.clone(), ctx.clone(), expr)? {68				Val::Arr(list) => {69					for item in list.iter(s.clone()) {70						evaluate_comp(71							s.clone(),72							ctx.clone().with_var(var.clone(), item?.clone()),73							&specs[1..],74							callback,75						)?;76					}77				}78				_ => throw!(InComprehensionCanOnlyIterateOverArray),79			}80		}81	}82	Ok(())83}8485trait CloneableUnbound<T>: Unbound<Bound = T> + Clone {}8687fn evaluate_object_locals(88	fctx: Pending<Context>,89	locals: Rc<Vec<BindSpec>>,90) -> impl CloneableUnbound<Context> {91	#[derive(Trace, Clone)]92	struct UnboundLocals {93		fctx: Pending<Context>,94		locals: Rc<Vec<BindSpec>>,95	}96	impl CloneableUnbound<Context> for UnboundLocals {}97	impl Unbound for UnboundLocals {98		type Bound = Context;99100		fn bind(101			&self,102			_s: State,103			sup: Option<ObjValue>,104			this: Option<ObjValue>,105		) -> Result<Context> {106			let fctx = Context::new_future();107			let mut new_bindings = GcHashMap::new();108			for b in self.locals.iter() {109				evaluate_dest(b, fctx.clone(), &mut new_bindings)?;110			}111112			let ctx = self.fctx.unwrap();113			let new_dollar = ctx.dollar().clone().or_else(|| this.clone());114115			let ctx = ctx116				.extend(new_bindings, new_dollar, sup, this)117				.into_future(fctx);118119			Ok(ctx)120		}121	}122123	UnboundLocals { fctx, locals }124}125126#[allow(clippy::too_many_lines)]127pub fn evaluate_member_list_object(s: State, ctx: Context, members: &[Member]) -> Result<ObjValue> {128	let mut builder = ObjValueBuilder::new();129	let locals = Rc::new(130		members131			.iter()132			.filter_map(|m| match m {133				Member::BindStmt(bind) => Some(bind.clone()),134				_ => None,135			})136			.collect::<Vec<_>>(),137	);138139	let fctx = Context::new_future();140141	// We have single context for all fields, so we can cache binds142	let uctx = CachedUnbound::new(evaluate_object_locals(fctx.clone(), locals));143144	for member in members.iter() {145		match member {146			Member::Field(FieldMember {147				name,148				plus,149				params: None,150				visibility,151				value,152			}) => {153				#[derive(Trace)]154				struct UnboundValue<B> {155					uctx: B,156					value: LocExpr,157					name: IStr,158				}159				impl<B: Unbound<Bound = Context>> Unbound for UnboundValue<B> {160					type Bound = Thunk<Val>;161					fn bind(162						&self,163						s: State,164						sup: Option<ObjValue>,165						this: Option<ObjValue>,166					) -> Result<Thunk<Val>> {167						Ok(Thunk::evaluated(evaluate_named(168							s.clone(),169							self.uctx.bind(s, sup, this)?,170							&self.value,171							self.name.clone(),172						)?))173					}174				}175176				let name = evaluate_field_name(s.clone(), ctx.clone(), name)?;177				let name = if let Some(name) = name {178					name179				} else {180					continue;181				};182183				builder184					.member(name.clone())185					.with_add(*plus)186					.with_visibility(*visibility)187					.with_location(value.1.clone())188					.bindable(189						s.clone(),190						tb!(UnboundValue {191							uctx: uctx.clone(),192							value: value.clone(),193							name: name.clone()194						}),195					)?;196			}197			Member::Field(FieldMember {198				name,199				params: Some(params),200				value,201				..202			}) => {203				#[derive(Trace)]204				struct UnboundMethod<B> {205					uctx: B,206					value: LocExpr,207					params: ParamsDesc,208					name: IStr,209				}210				impl<B: Unbound<Bound = Context>> Unbound for UnboundMethod<B> {211					type Bound = Thunk<Val>;212					fn bind(213						&self,214						s: State,215						sup: Option<ObjValue>,216						this: Option<ObjValue>,217					) -> Result<Thunk<Val>> {218						Ok(Thunk::evaluated(evaluate_method(219							self.uctx.bind(s, sup, this)?,220							self.name.clone(),221							self.params.clone(),222							self.value.clone(),223						)))224					}225				}226227				let name = if let Some(name) = evaluate_field_name(s.clone(), ctx.clone(), name)? {228					name229				} else {230					continue;231				};232233				builder234					.member(name.clone())235					.hide()236					.with_location(value.1.clone())237					.bindable(238						s.clone(),239						tb!(UnboundMethod {240							uctx: uctx.clone(),241							value: value.clone(),242							params: params.clone(),243							name: name.clone()244						}),245					)?;246			}247			Member::BindStmt(_) => {}248			Member::AssertStmt(stmt) => {249				#[derive(Trace)]250				struct ObjectAssert<B> {251					uctx: B,252					assert: AssertStmt,253				}254				impl<B: Unbound<Bound = Context>> ObjectAssertion for ObjectAssert<B> {255					fn run(256						&self,257						s: State,258						sup: Option<ObjValue>,259						this: Option<ObjValue>,260					) -> Result<()> {261						let ctx = self.uctx.bind(s.clone(), sup, this)?;262						evaluate_assert(s, ctx, &self.assert)263					}264				}265				builder.assert(tb!(ObjectAssert {266					uctx: uctx.clone(),267					assert: stmt.clone(),268				}));269			}270		}271	}272	let this = builder.build();273	let _ctx = ctx274		.extend(GcHashMap::new(), None, None, Some(this.clone()))275		.into_future(fctx);276	Ok(this)277}278279pub fn evaluate_object(s: State, ctx: Context, object: &ObjBody) -> Result<ObjValue> {280	Ok(match object {281		ObjBody::MemberList(members) => evaluate_member_list_object(s, ctx, members)?,282		ObjBody::ObjComp(obj) => {283			let mut builder = ObjValueBuilder::new();284			let locals = Rc::new(285				obj.pre_locals286					.iter()287					.chain(obj.post_locals.iter())288					.cloned()289					.collect::<Vec<_>>(),290			);291			let mut ctxs = vec![];292			evaluate_comp(s.clone(), ctx, &obj.compspecs, &mut |ctx| {293				let key = evaluate(s.clone(), ctx.clone(), &obj.key)?;294				let fctx = Context::new_future();295				ctxs.push((ctx, fctx.clone()));296				let uctx = evaluate_object_locals(fctx, locals.clone());297298				match key {299					Val::Null => {}300					Val::Str(n) => {301						#[derive(Trace)]302						struct UnboundValue<B> {303							uctx: B,304							value: LocExpr,305						}306						impl<B: Unbound<Bound = Context>> Unbound for UnboundValue<B> {307							type Bound = Thunk<Val>;308							fn bind(309								&self,310								s: State,311								sup: Option<ObjValue>,312								this: Option<ObjValue>,313							) -> Result<Thunk<Val>> {314								Ok(Thunk::evaluated(evaluate(315									s.clone(),316									self.uctx.bind(s, sup, this.clone())?.extend(317										GcHashMap::new(),318										None,319										None,320										this,321									),322									&self.value,323								)?))324							}325						}326						builder327							.member(n)328							.with_location(obj.value.1.clone())329							.with_add(obj.plus)330							.bindable(331								s.clone(),332								tb!(UnboundValue {333									uctx,334									value: obj.value.clone(),335								}),336							)?;337					}338					v => throw!(FieldMustBeStringGot(v.value_type())),339				}340341				Ok(())342			})?;343344			let this = builder.build();345			for (ctx, fctx) in ctxs {346				let _ctx = ctx347					.extend(GcHashMap::new(), None, None, Some(this.clone()))348					.into_future(fctx);349			}350			this351		}352	})353}354355pub fn evaluate_apply(356	s: State,357	ctx: Context,358	value: &LocExpr,359	args: &ArgsDesc,360	loc: CallLocation,361	tailstrict: bool,362) -> Result<Val> {363	let value = evaluate(s.clone(), ctx.clone(), value)?;364	Ok(match value {365		Val::Func(f) => {366			let body = || f.evaluate(s.clone(), ctx, loc, args, tailstrict);367			if tailstrict {368				body()?369			} else {370				s.push(loc, || format!("function <{}> call", f.name()), body)?371			}372		}373		v => throw!(OnlyFunctionsCanBeCalledGot(v.value_type())),374	})375}376377pub fn evaluate_assert(s: State, ctx: Context, assertion: &AssertStmt) -> Result<()> {378	let value = &assertion.0;379	let msg = &assertion.1;380	let assertion_result = s.push(381		CallLocation::new(&value.1),382		|| "assertion condition".to_owned(),383		|| bool::from_untyped(evaluate(s.clone(), ctx.clone(), value)?, s.clone()),384	)?;385	if !assertion_result {386		s.push(387			CallLocation::new(&value.1),388			|| "assertion failure".to_owned(),389			|| {390				if let Some(msg) = msg {391					throw!(AssertionFailed(392						evaluate(s.clone(), ctx, msg)?.to_string(s.clone())?393					));394				}395				throw!(AssertionFailed(Val::Null.to_string(s.clone())?));396			},397		)?;398	}399	Ok(())400}401402pub fn evaluate_named(s: State, ctx: Context, expr: &LocExpr, name: IStr) -> Result<Val> {403	use Expr::*;404	let LocExpr(raw_expr, _loc) = expr;405	Ok(match &**raw_expr {406		Function(params, body) => evaluate_method(ctx, name, params.clone(), body.clone()),407		_ => evaluate(s, ctx, expr)?,408	})409}410411#[allow(clippy::too_many_lines)]412pub fn evaluate(s: State, ctx: Context, expr: &LocExpr) -> Result<Val> {413	use Expr::*;414	let LocExpr(expr, loc) = expr;415	// let bp = with_state(|s| s.0.stop_at.borrow().clone());416	Ok(match &**expr {417		Literal(LiteralType::This) => {418			Val::Obj(ctx.this().clone().ok_or(CantUseSelfOutsideOfObject)?)419		}420		Literal(LiteralType::Super) => Val::Obj(421			ctx.super_obj().clone().ok_or(NoSuperFound)?.with_this(422				ctx.this()423					.clone()424					.expect("if super exists - then this should to"),425			),426		),427		Literal(LiteralType::Dollar) => {428			Val::Obj(ctx.dollar().clone().ok_or(NoTopLevelObjectFound)?)429		}430		Literal(LiteralType::True) => Val::Bool(true),431		Literal(LiteralType::False) => Val::Bool(false),432		Literal(LiteralType::Null) => Val::Null,433		Parened(e) => evaluate(s, ctx, e)?,434		Str(v) => Val::Str(v.clone()),435		Num(v) => Val::new_checked_num(*v)?,436		BinaryOp(v1, o, v2) => evaluate_binary_op_special(s, ctx, v1, *o, v2)?,437		UnaryOp(o, v) => evaluate_unary_op(*o, &evaluate(s, ctx, v)?)?,438		Var(name) => s.push(439			CallLocation::new(loc),440			|| format!("variable <{}> access", name),441			|| ctx.binding(name.clone())?.evaluate(s.clone()),442		)?,443		Index(value, index) => {444			match (445				evaluate(s.clone(), ctx.clone(), value)?,446				evaluate(s.clone(), ctx, index)?,447			) {448				(Val::Obj(v), Val::Str(key)) => s.push(449					CallLocation::new(loc),450					|| format!("field <{}> access", key),451					|| match v.get(s.clone(), key.clone()) {452						Ok(Some(v)) => Ok(v),453						Ok(None) => throw!(NoSuchField(key.clone())),454						Err(e) if matches!(e.error(), MagicThisFileUsed) => {455							Ok(Val::Str(loc.0.full_path().into()))456						}457						Err(e) => Err(e),458					},459				)?,460				(Val::Obj(_), n) => throw!(ValueIndexMustBeTypeGot(461					ValType::Obj,462					ValType::Str,463					n.value_type(),464				)),465466				(Val::Arr(v), Val::Num(n)) => {467					if n.fract() > f64::EPSILON {468						throw!(FractionalIndex)469					}470					v.get(s, n as usize)?471						.ok_or_else(|| ArrayBoundsError(n as usize, v.len()))?472				}473				(Val::Arr(_), Val::Str(n)) => throw!(AttemptedIndexAnArrayWithString(n)),474				(Val::Arr(_), n) => throw!(ValueIndexMustBeTypeGot(475					ValType::Arr,476					ValType::Num,477					n.value_type(),478				)),479480				(Val::Str(s), Val::Num(n)) => Val::Str({481					let v: IStr = s482						.chars()483						.skip(n as usize)484						.take(1)485						.collect::<String>()486						.into();487					if v.is_empty() {488						let size = s.chars().count();489						throw!(StringBoundsError(n as usize, size))490					}491					v492				}),493				(Val::Str(_), n) => throw!(ValueIndexMustBeTypeGot(494					ValType::Str,495					ValType::Num,496					n.value_type(),497				)),498499				(v, _) => throw!(CantIndexInto(v.value_type())),500			}501		}502		LocalExpr(bindings, returned) => {503			let mut new_bindings: GcHashMap<IStr, Thunk<Val>> =504				GcHashMap::with_capacity(bindings.len());505			let fctx = Context::new_future();506			for b in bindings {507				evaluate_dest(b, fctx.clone(), &mut new_bindings)?;508			}509			let ctx = ctx.extend(new_bindings, None, None, None).into_future(fctx);510			evaluate(s, ctx, &returned.clone())?511		}512		Arr(items) => {513			let mut out = Vec::with_capacity(items.len());514			for item in items {515				// TODO: Implement ArrValue::Lazy with same context for every element?516				#[derive(Trace)]517				struct ArrayElement {518					ctx: Context,519					item: LocExpr,520				}521				impl ThunkValue for ArrayElement {522					type Output = Val;523					fn get(self: Box<Self>, s: State) -> Result<Val> {524						evaluate(s, self.ctx, &self.item)525					}526				}527				out.push(Thunk::new(tb!(ArrayElement {528					ctx: ctx.clone(),529					item: item.clone(),530				})));531			}532			Val::Arr(out.into())533		}534		ArrComp(expr, comp_specs) => {535			let mut out = Vec::new();536			evaluate_comp(s.clone(), ctx, comp_specs, &mut |ctx| {537				out.push(evaluate(s.clone(), ctx, expr)?);538				Ok(())539			})?;540			Val::Arr(ArrValue::Eager(Cc::new(out)))541		}542		Obj(body) => Val::Obj(evaluate_object(s, ctx, body)?),543		ObjExtend(a, b) => evaluate_add_op(544			s.clone(),545			&evaluate(s.clone(), ctx.clone(), a)?,546			&Val::Obj(evaluate_object(s, ctx, b)?),547		)?,548		Apply(value, args, tailstrict) => {549			evaluate_apply(s, ctx, value, args, CallLocation::new(loc), *tailstrict)?550		}551		Function(params, body) => {552			evaluate_method(ctx, "anonymous".into(), params.clone(), body.clone())553		}554		Intrinsic(name) => Val::Func(FuncVal::StaticBuiltin(555			BUILTINS556				.with(|b| b.get(name).copied())557				.ok_or_else(|| IntrinsicNotFound(name.clone()))?,558		)),559		IntrinsicThisFile => return Err(MagicThisFileUsed.into()),560		IntrinsicId => Val::Func(FuncVal::identity()),561		AssertExpr(assert, returned) => {562			evaluate_assert(s.clone(), ctx.clone(), assert)?;563			evaluate(s, ctx, returned)?564		}565		ErrorStmt(e) => s.push(566			CallLocation::new(loc),567			|| "error statement".to_owned(),568			|| {569				throw!(RuntimeError(570					evaluate(s.clone(), ctx, e)?.to_string(s.clone())?,571				))572			},573		)?,574		IfElse {575			cond,576			cond_then,577			cond_else,578		} => {579			if s.push(580				CallLocation::new(loc),581				|| "if condition".to_owned(),582				|| bool::from_untyped(evaluate(s.clone(), ctx.clone(), &cond.0)?, s.clone()),583			)? {584				evaluate(s, ctx, cond_then)?585			} else {586				match cond_else {587					Some(v) => evaluate(s, ctx, v)?,588					None => Val::Null,589				}590			}591		}592		Slice(value, desc) => {593			fn parse_idx<T: Typed>(594				loc: CallLocation,595				s: State,596				ctx: &Context,597				expr: &Option<LocExpr>,598				desc: &'static str,599			) -> Result<Option<T>> {600				if let Some(value) = expr {601					Ok(Some(s.push(602						loc,603						|| format!("slice {}", desc),604						|| T::from_untyped(evaluate(s.clone(), ctx.clone(), value)?, s.clone()),605					)?))606				} else {607					Ok(None)608				}609			}610611			let indexable = evaluate(s.clone(), ctx.clone(), value)?;612			let loc = CallLocation::new(loc);613614			let start = parse_idx(loc, s.clone(), &ctx, &desc.start, "start")?;615			let end = parse_idx(loc, s.clone(), &ctx, &desc.end, "end")?;616			let step = parse_idx(loc, s, &ctx, &desc.step, "step")?;617618			std_slice(indexable.into_indexable()?, start, end, step)?619		}620		i @ (Import(path) | ImportStr(path) | ImportBin(path)) => {621			let tmp = loc.clone().0;622			let import_location = tmp623				.path()624				.map(|p| {625					let mut p = p.to_owned();626					p.pop();627					p628				})629				.unwrap_or_default();630			let path = s.resolve_file(&import_location, path as &str)?;631			match i {632				Import(_) => s.push(633				CallLocation::new(loc),634					|| format!("import {:?}", path.clone()),635					|| s.import(path.clone()),636				)?,637				ImportStr(_) => Val::Str(s.import_str(path)?),638				ImportBin(_) => Val::Arr(ArrValue::Bytes(s.import_bin(path)?)),639				_ => unreachable!(),640		}641		}642	})643}
after · crates/jrsonnet-evaluator/src/evaluate/mod.rs
1use std::{cmp::Ordering, rc::Rc};23use gcmodule::{Cc, Trace};4use jrsonnet_interner::IStr;5use jrsonnet_parser::{6	ArgsDesc, AssertStmt, BindSpec, CompSpec, Expr, FieldMember, FieldName, ForSpecData,7	IfSpecData, LiteralType, LocExpr, Member, ObjBody, ParamsDesc,8};9use jrsonnet_types::ValType;1011use crate::{12	destructure::evaluate_dest,13	error::Error::*,14	evaluate::operator::{evaluate_add_op, evaluate_binary_op_special, evaluate_unary_op},15	function::{CallLocation, FuncDesc, FuncVal},16	stdlib::{std_slice, BUILTINS},17	tb, throw,18	typed::Typed,19	val::{ArrValue, CachedUnbound, Thunk, ThunkValue},20	Context, GcHashMap, ObjValue, ObjValueBuilder, ObjectAssertion, Pending, Result, State,21	Unbound, Val,22};23pub mod destructure;24pub mod operator;2526pub fn evaluate_method(ctx: Context, name: IStr, params: ParamsDesc, body: LocExpr) -> Val {27	Val::Func(FuncVal::Normal(Cc::new(FuncDesc {28		name,29		ctx,30		params,31		body,32	})))33}3435pub fn evaluate_field_name(s: State, ctx: Context, field_name: &FieldName) -> Result<Option<IStr>> {36	Ok(match field_name {37		FieldName::Fixed(n) => Some(n.clone()),38		FieldName::Dyn(expr) => s.push(39			CallLocation::new(&expr.1),40			|| "evaluating field name".to_string(),41			|| {42				let value = evaluate(s.clone(), ctx, expr)?;43				if matches!(value, Val::Null) {44					Ok(None)45				} else {46					Ok(Some(IStr::from_untyped(value, s.clone())?))47				}48			},49		)?,50	})51}5253pub fn evaluate_comp(54	s: State,55	ctx: Context,56	specs: &[CompSpec],57	callback: &mut impl FnMut(Context) -> Result<()>,58) -> Result<()> {59	match specs.get(0) {60		None => callback(ctx)?,61		Some(CompSpec::IfSpec(IfSpecData(cond))) => {62			if bool::from_untyped(evaluate(s.clone(), ctx.clone(), cond)?, s.clone())? {63				evaluate_comp(s, ctx, &specs[1..], callback)?;64			}65		}66		Some(CompSpec::ForSpec(ForSpecData(var, expr))) => {67			match evaluate(s.clone(), ctx.clone(), expr)? {68				Val::Arr(list) => {69					for item in list.iter(s.clone()) {70						evaluate_comp(71							s.clone(),72							ctx.clone().with_var(var.clone(), item?.clone()),73							&specs[1..],74							callback,75						)?;76					}77				}78				_ => throw!(InComprehensionCanOnlyIterateOverArray),79			}80		}81	}82	Ok(())83}8485trait CloneableUnbound<T>: Unbound<Bound = T> + Clone {}8687fn evaluate_object_locals(88	fctx: Pending<Context>,89	locals: Rc<Vec<BindSpec>>,90) -> impl CloneableUnbound<Context> {91	#[derive(Trace, Clone)]92	struct UnboundLocals {93		fctx: Pending<Context>,94		locals: Rc<Vec<BindSpec>>,95	}96	impl CloneableUnbound<Context> for UnboundLocals {}97	impl Unbound for UnboundLocals {98		type Bound = Context;99100		fn bind(101			&self,102			_s: State,103			sup: Option<ObjValue>,104			this: Option<ObjValue>,105		) -> Result<Context> {106			let fctx = Context::new_future();107			let mut new_bindings = GcHashMap::new();108			for b in self.locals.iter() {109				evaluate_dest(b, fctx.clone(), &mut new_bindings)?;110			}111112			let ctx = self.fctx.unwrap();113			let new_dollar = ctx.dollar().clone().or_else(|| this.clone());114115			let ctx = ctx116				.extend(new_bindings, new_dollar, sup, this)117				.into_future(fctx);118119			Ok(ctx)120		}121	}122123	UnboundLocals { fctx, locals }124}125126#[allow(clippy::too_many_lines)]127pub fn evaluate_member_list_object(s: State, ctx: Context, members: &[Member]) -> Result<ObjValue> {128	let mut builder = ObjValueBuilder::new();129	let locals = Rc::new(130		members131			.iter()132			.filter_map(|m| match m {133				Member::BindStmt(bind) => Some(bind.clone()),134				_ => None,135			})136			.collect::<Vec<_>>(),137	);138139	let fctx = Context::new_future();140141	// We have single context for all fields, so we can cache binds142	let uctx = CachedUnbound::new(evaluate_object_locals(fctx.clone(), locals));143144	for member in members.iter() {145		match member {146			Member::Field(FieldMember {147				name,148				plus,149				params: None,150				visibility,151				value,152			}) => {153				#[derive(Trace)]154				struct UnboundValue<B> {155					uctx: B,156					value: LocExpr,157					name: IStr,158				}159				impl<B: Unbound<Bound = Context>> Unbound for UnboundValue<B> {160					type Bound = Thunk<Val>;161					fn bind(162						&self,163						s: State,164						sup: Option<ObjValue>,165						this: Option<ObjValue>,166					) -> Result<Thunk<Val>> {167						Ok(Thunk::evaluated(evaluate_named(168							s.clone(),169							self.uctx.bind(s, sup, this)?,170							&self.value,171							self.name.clone(),172						)?))173					}174				}175176				let name = evaluate_field_name(s.clone(), ctx.clone(), name)?;177				let name = if let Some(name) = name {178					name179				} else {180					continue;181				};182183				builder184					.member(name.clone())185					.with_add(*plus)186					.with_visibility(*visibility)187					.with_location(value.1.clone())188					.bindable(189						s.clone(),190						tb!(UnboundValue {191							uctx: uctx.clone(),192							value: value.clone(),193							name: name.clone()194						}),195					)?;196			}197			Member::Field(FieldMember {198				name,199				params: Some(params),200				value,201				..202			}) => {203				#[derive(Trace)]204				struct UnboundMethod<B> {205					uctx: B,206					value: LocExpr,207					params: ParamsDesc,208					name: IStr,209				}210				impl<B: Unbound<Bound = Context>> Unbound for UnboundMethod<B> {211					type Bound = Thunk<Val>;212					fn bind(213						&self,214						s: State,215						sup: Option<ObjValue>,216						this: Option<ObjValue>,217					) -> Result<Thunk<Val>> {218						Ok(Thunk::evaluated(evaluate_method(219							self.uctx.bind(s, sup, this)?,220							self.name.clone(),221							self.params.clone(),222							self.value.clone(),223						)))224					}225				}226227				let name = if let Some(name) = evaluate_field_name(s.clone(), ctx.clone(), name)? {228					name229				} else {230					continue;231				};232233				builder234					.member(name.clone())235					.hide()236					.with_location(value.1.clone())237					.bindable(238						s.clone(),239						tb!(UnboundMethod {240							uctx: uctx.clone(),241							value: value.clone(),242							params: params.clone(),243							name: name.clone()244						}),245					)?;246			}247			Member::BindStmt(_) => {}248			Member::AssertStmt(stmt) => {249				#[derive(Trace)]250				struct ObjectAssert<B> {251					uctx: B,252					assert: AssertStmt,253				}254				impl<B: Unbound<Bound = Context>> ObjectAssertion for ObjectAssert<B> {255					fn run(256						&self,257						s: State,258						sup: Option<ObjValue>,259						this: Option<ObjValue>,260					) -> Result<()> {261						let ctx = self.uctx.bind(s.clone(), sup, this)?;262						evaluate_assert(s, ctx, &self.assert)263					}264				}265				builder.assert(tb!(ObjectAssert {266					uctx: uctx.clone(),267					assert: stmt.clone(),268				}));269			}270		}271	}272	let this = builder.build();273	let _ctx = ctx274		.extend(GcHashMap::new(), None, None, Some(this.clone()))275		.into_future(fctx);276	Ok(this)277}278279pub fn evaluate_object(s: State, ctx: Context, object: &ObjBody) -> Result<ObjValue> {280	Ok(match object {281		ObjBody::MemberList(members) => evaluate_member_list_object(s, ctx, members)?,282		ObjBody::ObjComp(obj) => {283			let mut builder = ObjValueBuilder::new();284			let locals = Rc::new(285				obj.pre_locals286					.iter()287					.chain(obj.post_locals.iter())288					.cloned()289					.collect::<Vec<_>>(),290			);291			let mut ctxs = vec![];292			evaluate_comp(s.clone(), ctx, &obj.compspecs, &mut |ctx| {293				let key = evaluate(s.clone(), ctx.clone(), &obj.key)?;294				let fctx = Context::new_future();295				ctxs.push((ctx, fctx.clone()));296				let uctx = evaluate_object_locals(fctx, locals.clone());297298				match key {299					Val::Null => {}300					Val::Str(n) => {301						#[derive(Trace)]302						struct UnboundValue<B> {303							uctx: B,304							value: LocExpr,305						}306						impl<B: Unbound<Bound = Context>> Unbound for UnboundValue<B> {307							type Bound = Thunk<Val>;308							fn bind(309								&self,310								s: State,311								sup: Option<ObjValue>,312								this: Option<ObjValue>,313							) -> Result<Thunk<Val>> {314								Ok(Thunk::evaluated(evaluate(315									s.clone(),316									self.uctx.bind(s, sup, this.clone())?.extend(317										GcHashMap::new(),318										None,319										None,320										this,321									),322									&self.value,323								)?))324							}325						}326						builder327							.member(n)328							.with_location(obj.value.1.clone())329							.with_add(obj.plus)330							.bindable(331								s.clone(),332								tb!(UnboundValue {333									uctx,334									value: obj.value.clone(),335								}),336							)?;337					}338					v => throw!(FieldMustBeStringGot(v.value_type())),339				}340341				Ok(())342			})?;343344			let this = builder.build();345			for (ctx, fctx) in ctxs {346				let _ctx = ctx347					.extend(GcHashMap::new(), None, None, Some(this.clone()))348					.into_future(fctx);349			}350			this351		}352	})353}354355pub fn evaluate_apply(356	s: State,357	ctx: Context,358	value: &LocExpr,359	args: &ArgsDesc,360	loc: CallLocation,361	tailstrict: bool,362) -> Result<Val> {363	let value = evaluate(s.clone(), ctx.clone(), value)?;364	Ok(match value {365		Val::Func(f) => {366			let body = || f.evaluate(s.clone(), ctx, loc, args, tailstrict);367			if tailstrict {368				body()?369			} else {370				s.push(loc, || format!("function <{}> call", f.name()), body)?371			}372		}373		v => throw!(OnlyFunctionsCanBeCalledGot(v.value_type())),374	})375}376377pub fn evaluate_assert(s: State, ctx: Context, assertion: &AssertStmt) -> Result<()> {378	let value = &assertion.0;379	let msg = &assertion.1;380	let assertion_result = s.push(381		CallLocation::new(&value.1),382		|| "assertion condition".to_owned(),383		|| bool::from_untyped(evaluate(s.clone(), ctx.clone(), value)?, s.clone()),384	)?;385	if !assertion_result {386		s.push(387			CallLocation::new(&value.1),388			|| "assertion failure".to_owned(),389			|| {390				if let Some(msg) = msg {391					throw!(AssertionFailed(392						evaluate(s.clone(), ctx, msg)?.to_string(s.clone())?393					));394				}395				throw!(AssertionFailed(Val::Null.to_string(s.clone())?));396			},397		)?;398	}399	Ok(())400}401402pub fn evaluate_named(s: State, ctx: Context, expr: &LocExpr, name: IStr) -> Result<Val> {403	use Expr::*;404	let LocExpr(raw_expr, _loc) = expr;405	Ok(match &**raw_expr {406		Function(params, body) => evaluate_method(ctx, name, params.clone(), body.clone()),407		_ => evaluate(s, ctx, expr)?,408	})409}410411#[allow(clippy::too_many_lines)]412pub fn evaluate(s: State, ctx: Context, expr: &LocExpr) -> Result<Val> {413	use Expr::*;414	let LocExpr(expr, loc) = expr;415	// let bp = with_state(|s| s.0.stop_at.borrow().clone());416	Ok(match &**expr {417		Literal(LiteralType::This) => {418			Val::Obj(ctx.this().clone().ok_or(CantUseSelfOutsideOfObject)?)419		}420		Literal(LiteralType::Super) => Val::Obj(421			ctx.super_obj().clone().ok_or(NoSuperFound)?.with_this(422				ctx.this()423					.clone()424					.expect("if super exists - then this should to"),425			),426		),427		Literal(LiteralType::Dollar) => {428			Val::Obj(ctx.dollar().clone().ok_or(NoTopLevelObjectFound)?)429		}430		Literal(LiteralType::True) => Val::Bool(true),431		Literal(LiteralType::False) => Val::Bool(false),432		Literal(LiteralType::Null) => Val::Null,433		Parened(e) => evaluate(s, ctx, e)?,434		Str(v) => Val::Str(v.clone()),435		Num(v) => Val::new_checked_num(*v)?,436		BinaryOp(v1, o, v2) => evaluate_binary_op_special(s, ctx, v1, *o, v2)?,437		UnaryOp(o, v) => evaluate_unary_op(*o, &evaluate(s, ctx, v)?)?,438		Var(name) => s.push(439			CallLocation::new(loc),440			|| format!("variable <{}> access", name),441			|| ctx.binding(name.clone())?.evaluate(s.clone()),442		)?,443		Index(value, index) => {444			match (445				evaluate(s.clone(), ctx.clone(), value)?,446				evaluate(s.clone(), ctx, index)?,447			) {448				(Val::Obj(v), Val::Str(key)) => s.push(449					CallLocation::new(loc),450					|| format!("field <{}> access", key),451					|| match v.get(s.clone(), key.clone()) {452						Ok(Some(v)) => Ok(v),453						#[cfg(not(feature = "friendly-errors"))]454						Ok(None) => throw!(NoSuchField(key.clone(), vec![])),455						#[cfg(feature = "friendly-errors")]456						Ok(None) => {457							let mut heap = Vec::new();458							for field in v.fields_ex(459								true,460								#[cfg(feature = "exp-preserve-order")]461								false,462							) {463								let conf = strsim::jaro_winkler(&field as &str, &key as &str);464								if conf < 0.8 {465									continue;466								}467								heap.push((conf, field));468							}469							heap.sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap_or(Ordering::Equal));470471							throw!(NoSuchField(472								key.clone(),473								heap.into_iter().map(|(_, v)| v).collect()474							))475						}476						Err(e) if matches!(e.error(), MagicThisFileUsed) => {477							Ok(Val::Str(loc.0.full_path().into()))478						}479						Err(e) => Err(e),480					},481				)?,482				(Val::Obj(_), n) => throw!(ValueIndexMustBeTypeGot(483					ValType::Obj,484					ValType::Str,485					n.value_type(),486				)),487488				(Val::Arr(v), Val::Num(n)) => {489					if n.fract() > f64::EPSILON {490						throw!(FractionalIndex)491					}492					v.get(s, n as usize)?493						.ok_or_else(|| ArrayBoundsError(n as usize, v.len()))?494				}495				(Val::Arr(_), Val::Str(n)) => throw!(AttemptedIndexAnArrayWithString(n)),496				(Val::Arr(_), n) => throw!(ValueIndexMustBeTypeGot(497					ValType::Arr,498					ValType::Num,499					n.value_type(),500				)),501502				(Val::Str(s), Val::Num(n)) => Val::Str({503					let v: IStr = s504						.chars()505						.skip(n as usize)506						.take(1)507						.collect::<String>()508						.into();509					if v.is_empty() {510						let size = s.chars().count();511						throw!(StringBoundsError(n as usize, size))512					}513					v514				}),515				(Val::Str(_), n) => throw!(ValueIndexMustBeTypeGot(516					ValType::Str,517					ValType::Num,518					n.value_type(),519				)),520521				(v, _) => throw!(CantIndexInto(v.value_type())),522			}523		}524		LocalExpr(bindings, returned) => {525			let mut new_bindings: GcHashMap<IStr, Thunk<Val>> =526				GcHashMap::with_capacity(bindings.len());527			let fctx = Context::new_future();528			for b in bindings {529				evaluate_dest(b, fctx.clone(), &mut new_bindings)?;530			}531			let ctx = ctx.extend(new_bindings, None, None, None).into_future(fctx);532			evaluate(s, ctx, &returned.clone())?533		}534		Arr(items) => {535			let mut out = Vec::with_capacity(items.len());536			for item in items {537				// TODO: Implement ArrValue::Lazy with same context for every element?538				#[derive(Trace)]539				struct ArrayElement {540					ctx: Context,541					item: LocExpr,542				}543				impl ThunkValue for ArrayElement {544					type Output = Val;545					fn get(self: Box<Self>, s: State) -> Result<Val> {546						evaluate(s, self.ctx, &self.item)547					}548				}549				out.push(Thunk::new(tb!(ArrayElement {550					ctx: ctx.clone(),551					item: item.clone(),552				})));553			}554			Val::Arr(out.into())555		}556		ArrComp(expr, comp_specs) => {557			let mut out = Vec::new();558			evaluate_comp(s.clone(), ctx, comp_specs, &mut |ctx| {559				out.push(evaluate(s.clone(), ctx, expr)?);560				Ok(())561			})?;562			Val::Arr(ArrValue::Eager(Cc::new(out)))563		}564		Obj(body) => Val::Obj(evaluate_object(s, ctx, body)?),565		ObjExtend(a, b) => evaluate_add_op(566			s.clone(),567			&evaluate(s.clone(), ctx.clone(), a)?,568			&Val::Obj(evaluate_object(s, ctx, b)?),569		)?,570		Apply(value, args, tailstrict) => {571			evaluate_apply(s, ctx, value, args, CallLocation::new(loc), *tailstrict)?572		}573		Function(params, body) => {574			evaluate_method(ctx, "anonymous".into(), params.clone(), body.clone())575		}576		Intrinsic(name) => Val::Func(FuncVal::StaticBuiltin(577			BUILTINS578				.with(|b| b.get(name).copied())579				.ok_or_else(|| IntrinsicNotFound(name.clone()))?,580		)),581		IntrinsicThisFile => return Err(MagicThisFileUsed.into()),582		IntrinsicId => Val::Func(FuncVal::identity()),583		AssertExpr(assert, returned) => {584			evaluate_assert(s.clone(), ctx.clone(), assert)?;585			evaluate(s, ctx, returned)?586		}587		ErrorStmt(e) => s.push(588			CallLocation::new(loc),589			|| "error statement".to_owned(),590			|| {591				throw!(RuntimeError(592					evaluate(s.clone(), ctx, e)?.to_string(s.clone())?,593				))594			},595		)?,596		IfElse {597			cond,598			cond_then,599			cond_else,600		} => {601			if s.push(602				CallLocation::new(loc),603				|| "if condition".to_owned(),604				|| bool::from_untyped(evaluate(s.clone(), ctx.clone(), &cond.0)?, s.clone()),605			)? {606				evaluate(s, ctx, cond_then)?607			} else {608				match cond_else {609					Some(v) => evaluate(s, ctx, v)?,610					None => Val::Null,611				}612			}613		}614		Slice(value, desc) => {615			fn parse_idx<T: Typed>(616				loc: CallLocation,617				s: State,618				ctx: &Context,619				expr: &Option<LocExpr>,620				desc: &'static str,621			) -> Result<Option<T>> {622				if let Some(value) = expr {623					Ok(Some(s.push(624						loc,625						|| format!("slice {}", desc),626						|| T::from_untyped(evaluate(s.clone(), ctx.clone(), value)?, s.clone()),627					)?))628				} else {629					Ok(None)630				}631			}632633			let indexable = evaluate(s.clone(), ctx.clone(), value)?;634			let loc = CallLocation::new(loc);635636			let start = parse_idx(loc, s.clone(), &ctx, &desc.start, "start")?;637			let end = parse_idx(loc, s.clone(), &ctx, &desc.end, "end")?;638			let step = parse_idx(loc, s, &ctx, &desc.step, "step")?;639640			std_slice(indexable.into_indexable()?, start, end, step)?641		}642		i @ (Import(path) | ImportStr(path) | ImportBin(path)) => {643			let tmp = loc.clone().0;644			let import_location = tmp645				.path()646				.map(|p| {647					let mut p = p.to_owned();648					p.pop();649					p650				})651				.unwrap_or_default();652			let path = s.resolve_file(&import_location, path as &str)?;653			match i {654				Import(_) => s.push(655					CallLocation::new(loc),656					|| format!("import {:?}", path.clone()),657					|| s.import(path.clone()),658				)?,659				ImportStr(_) => Val::Str(s.import_str(path)?),660				ImportBin(_) => Val::Arr(ArrValue::Bytes(s.import_bin(path)?)),661				_ => unreachable!(),662			}663		}664	})665}