git.delta.rocks / jrsonnet / refs/commits / 3302a3dd316f

difftreelog

feat CLI

Лач2020-06-03parent: #fab41c8.patch.diff
in: master

6 files changed

modifiedCargo.lockdiffbeforeafterboth
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1,12 +1,110 @@
 # This file is automatically @generated by Cargo.
 # It is not intended for manual editing.
 [[package]]
+name = "annotate-snippets"
+version = "0.8.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d78ea013094e5ea606b1c05fe35f1dd7ea1eb1ea259908d040b25bd5ec677ee5"
+
+[[package]]
+name = "atty"
+version = "0.2.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d9b39be18770d11421cdb1b9947a45dd3f37e93092cbf377614828a319d5fee8"
+dependencies = [
+ "hermit-abi",
+ "libc",
+ "winapi 0.3.8",
+]
+
+[[package]]
+name = "autocfg"
+version = "1.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f8aac770f1885fd7e387acedd76065302551364496e46b3dd00860b2f8359b9d"
+
+[[package]]
+name = "bitflags"
+version = "1.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cf1de2fe8c75bc145a2f577add951f8134889b4795d47466a54a5c846d691693"
+
+[[package]]
+name = "clap"
+version = "3.0.0-beta.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "860643c53f980f0d38a5e25dfab6c3c93b2cb3aa1fe192643d17a293c6c41936"
+dependencies = [
+ "atty",
+ "bitflags",
+ "clap_derive",
+ "indexmap",
+ "lazy_static",
+ "os_str_bytes",
+ "strsim",
+ "term_size 1.0.0-beta1",
+ "termcolor",
+ "textwrap",
+ "unicode-width",
+ "vec_map",
+]
+
+[[package]]
+name = "clap_derive"
+version = "3.0.0-beta.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fb51c9e75b94452505acd21d929323f5a5c6c4735a852adbd39ef5fb1b014f30"
+dependencies = [
+ "heck",
+ "proc-macro-error",
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
 name = "closure"
 version = "0.3.0"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "d6173fd61b610d15a7566dd7b7620775627441c4ab9dac8906e17cb93a24b782"
 
 [[package]]
+name = "heck"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "20564e78d53d2bb135c343b3f47714a56af2061f1c928fdb541dc7b9fdd94205"
+dependencies = [
+ "unicode-segmentation",
+]
+
+[[package]]
+name = "hermit-abi"
+version = "0.1.13"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "91780f809e750b0a89f5544be56617ff6b1227ee485bcb06ebe10cdf89bd3b71"
+dependencies = [
+ "libc",
+]
+
+[[package]]
+name = "indexmap"
+version = "1.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c398b2b113b55809ceb9ee3e753fcbac793f1956663f3c36549c1346015c2afe"
+dependencies = [
+ "autocfg",
+]
+
+[[package]]
+name = "jsonnet"
+version = "0.1.0"
+dependencies = [
+ "annotate-snippets",
+ "clap",
+ "jsonnet-evaluator",
+]
+
+[[package]]
 name = "jsonnet-evaluator"
 version = "0.1.0"
 dependencies = [
@@ -28,6 +126,34 @@
 version = "0.1.0"
 
 [[package]]
+name = "kernel32-sys"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7507624b29483431c0ba2d82aece8ca6cdba9382bff4ddd0f7490560c056098d"
+dependencies = [
+ "winapi 0.2.8",
+ "winapi-build",
+]
+
+[[package]]
+name = "lazy_static"
+version = "1.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646"
+
+[[package]]
+name = "libc"
+version = "0.2.71"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9457b06509d27052635f90d6466700c65095fdf75409b3fbdd903e988b886f49"
+
+[[package]]
+name = "os_str_bytes"
+version = "2.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "06de47b848347d8c4c94219ad8ecd35eb90231704b067e67e6ae2e36ee023510"
+
+[[package]]
 name = "peg"
 version = "0.6.2"
 source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -55,6 +181,32 @@
 checksum = "0c1a2897e69d986c7986747ebad425cf03746ec5e3e09bb3b2600f91301ba864"
 
 [[package]]
+name = "proc-macro-error"
+version = "0.4.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "18f33027081eba0a6d8aba6d1b1c3a3be58cbb12106341c2d5759fcd9b5277e7"
+dependencies = [
+ "proc-macro-error-attr",
+ "proc-macro2",
+ "quote",
+ "syn",
+ "version_check",
+]
+
+[[package]]
+name = "proc-macro-error-attr"
+version = "0.4.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8a5b4b77fdb63c1eca72173d68d24501c54ab1269409f6b672c85deb18af69de"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+ "syn-mid",
+ "version_check",
+]
+
+[[package]]
 name = "proc-macro2"
 version = "1.0.12"
 source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -73,7 +225,142 @@
 ]
 
 [[package]]
+name = "strsim"
+version = "0.10.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623"
+
+[[package]]
+name = "syn"
+version = "1.0.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4696caa4048ac7ce2bcd2e484b3cef88c1004e41b8e945a277e2c25dc0b72060"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "unicode-xid",
+]
+
+[[package]]
+name = "syn-mid"
+version = "0.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7be3539f6c128a931cf19dcee741c1af532c7fd387baa739c03dd2e96479338a"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "term_size"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1e4129646ca0ed8f45d09b929036bafad5377103edd06e50bf574b353d2b08d9"
+dependencies = [
+ "libc",
+ "winapi 0.3.8",
+]
+
+[[package]]
+name = "term_size"
+version = "1.0.0-beta1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a8a17d8699e154863becdf18e4fd28bd0be27ca72856f54daf75c00f2566898f"
+dependencies = [
+ "kernel32-sys",
+ "libc",
+ "winapi 0.2.8",
+]
+
+[[package]]
+name = "termcolor"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bb6bfa289a4d7c5766392812c0a1f4c1ba45afa1ad47803c11e1f407d846d75f"
+dependencies = [
+ "winapi-util",
+]
+
+[[package]]
+name = "textwrap"
+version = "0.11.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d326610f408c7a4eb6f51c37c330e496b08506c9457c9d34287ecc38809fb060"
+dependencies = [
+ "term_size 0.3.2",
+ "unicode-width",
+]
+
+[[package]]
+name = "unicode-segmentation"
+version = "1.6.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e83e153d1053cbb5a118eeff7fd5be06ed99153f00dbcd8ae310c5fb2b22edc0"
+
+[[package]]
+name = "unicode-width"
+version = "0.1.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "caaa9d531767d1ff2150b9332433f32a24622147e5ebb1f26409d5da67afd479"
+
+[[package]]
 name = "unicode-xid"
 version = "0.2.0"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "826e7639553986605ec5979c7dd957c7895e93eabed50ab2ffa7f6128a75097c"
+
+[[package]]
+name = "vec_map"
+version = "0.8.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f1bddf1187be692e79c5ffeab891132dfb0f236ed36a43c7ed39f1165ee20191"
+
+[[package]]
+name = "version_check"
+version = "0.9.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b5a972e5669d67ba988ce3dc826706fb0a8b01471c088cb0b6110b805cc36aed"
+
+[[package]]
+name = "winapi"
+version = "0.2.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "167dc9d6949a9b857f3451275e911c3f44255842c1f7a76f33c55103a909087a"
+
+[[package]]
+name = "winapi"
+version = "0.3.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8093091eeb260906a183e6ae1abdba2ef5ef2257a21801128899c3fc699229c6"
+dependencies = [
+ "winapi-i686-pc-windows-gnu",
+ "winapi-x86_64-pc-windows-gnu",
+]
+
+[[package]]
+name = "winapi-build"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2d315eee3b34aca4797b2da6b13ed88266e6d612562a0c46390af8299fc699bc"
+
+[[package]]
+name = "winapi-i686-pc-windows-gnu"
+version = "0.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
+
+[[package]]
+name = "winapi-util"
+version = "0.1.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "70ec6ce85bb158151cae5e5c87f95a8e97d2c0c4b001223f33a334e3ce5de178"
+dependencies = [
+ "winapi 0.3.8",
+]
+
+[[package]]
+name = "winapi-x86_64-pc-windows-gnu"
+version = "0.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
modifiedCargo.tomldiffbeforeafterboth
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -3,4 +3,5 @@
 	"crates/jsonnet-parser",
 	"crates/jsonnet-evaluator",
 	"crates/jsonnet-stdlib",
+	"cmds/jsonnet"
 ]
addedcmds/jsonnet/Cargo.tomldiffbeforeafterboth
--- /dev/null
+++ b/cmds/jsonnet/Cargo.toml
@@ -0,0 +1,16 @@
+[package]
+name = "jsonnet"
+version = "0.1.0"
+authors = ["Лач <iam@lach.pw>"]
+edition = "2018"
+
+# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
+
+[dependencies]
+jsonnet-evaluator = { path = "../../crates/jsonnet-evaluator" }
+annotate-snippets = "0.8.0"
+
+[dependencies.clap]
+version = "3.0.0-beta.1"
+default-features = false
+features = ["std", "derive", "suggestions", "color", "unstable", "wrap_help"]
addedcmds/jsonnet/src/main.rsdiffbeforeafterboth
--- /dev/null
+++ b/cmds/jsonnet/src/main.rs
@@ -0,0 +1,64 @@
+use clap::Clap;
+
+#[derive(Clap)]
+#[clap(version = "0.1.0", author = "Lach <iam@lach.pw>")]
+struct Opts {
+	#[clap(about = "File to compile")]
+	input: String,
+	#[clap(long, about = "Disable global std variable")]
+	no_stdlib: bool,
+}
+
+fn main() {
+	let opts: Opts = Opts::parse();
+	let evaluator = jsonnet_evaluator::EvaluationState::default();
+	if !opts.no_stdlib {
+		evaluator.add_stdlib();
+	}
+	evaluator
+		.add_file(
+			opts.input.clone(),
+			String::from_utf8(std::fs::read(opts.input.clone()).unwrap()).unwrap(),
+		)
+		.unwrap();
+	let result = evaluator.evaluate_file(&opts.input.clone());
+	match result {
+		Ok(v) => println!("{:?}", v),
+		Err(err) => {
+			use annotate_snippets::{
+				display_list::{DisplayList, FormatOptions},
+				snippet::{Annotation, AnnotationType, Slice, Snippet, SourceAnnotation},
+			};
+			for item in (err.1).0.iter() {
+				let source = (item.0).1.clone().unwrap();
+				let code = evaluator.get_source(&source.0);
+				let snippet = Snippet {
+					opt: FormatOptions {
+						color: true,
+						..Default::default()
+					},
+					title: Some(Annotation {
+						label: Some(&item.1),
+						id: None,
+						annotation_type: AnnotationType::Error,
+					}),
+					footer: vec![],
+					slices: vec![Slice {
+						source: &code,
+						line_start: 1,
+						origin: Some(&source.0),
+						fold: true,
+						annotations: vec![SourceAnnotation {
+							label: &"Example error annotation",
+							annotation_type: AnnotationType::Error,
+							range: (source.1, source.2),
+						}],
+					}],
+				};
+
+				let dl = DisplayList::from(snippet);
+				println!("{}", dl);
+			}
+		}
+	}
+}
modifiedcrates/jsonnet-evaluator/src/evaluate.rsdiffbeforeafterboth
before · crates/jsonnet-evaluator/src/evaluate.rs
1use crate::{2	binding, context_creator, create_error, function_default, function_rhs, future_wrapper,3	lazy_binding, lazy_val, push, Context, ContextCreator, FuncDesc, LazyBinding, ObjMember,4	ObjValue, Result, Val,5};6use closure::closure;7use jsonnet_parser::{8	el, Arg, ArgsDesc, AssertStmt, BinaryOpType, BindSpec, CompSpec, Expr, FieldMember,9	ForSpecData, IfSpecData, LiteralType, LocExpr, Member, ObjBody, ParamsDesc, UnaryOpType,10	Visibility,11};12use std::{13	collections::{BTreeMap, HashMap},14	rc::Rc,15};1617pub fn evaluate_binding(b: &BindSpec, context_creator: ContextCreator) -> (String, LazyBinding) {18	let b = b.clone();19	if let Some(args) = &b.params {20		let args = args.clone();21		(22			b.name.clone(),23			lazy_binding!(move |this, super_obj| Ok(lazy_val!(24				closure!(clone b, clone args, clone context_creator, || Ok(evaluate_method(25					context_creator.0(this.clone(), super_obj.clone())?,26					&b.value,27					args.clone()28				)))29			))),30		)31	} else {32		(33			b.name.clone(),34			lazy_binding!(move |this, super_obj| {35				Ok(lazy_val!(36					closure!(clone context_creator, clone b, || evaluate(37						context_creator.0(this.clone(), super_obj.clone())?,38						&b.value39					))40				))41			}),42		)43	}44}4546pub fn evaluate_method(ctx: Context, expr: &LocExpr, arg_spec: ParamsDesc) -> Val {47	Val::Func(FuncDesc {48		ctx,49		params: arg_spec,50		eval_rhs: function_rhs!(closure!(clone expr, |ctx| evaluate(ctx, &expr))),51		eval_default: function_default!(closure!(|ctx, default| evaluate(ctx, &default))),52	})53}5455pub fn evaluate_field_name(56	context: Context,57	field_name: &jsonnet_parser::FieldName,58) -> Result<String> {59	Ok(match field_name {60		jsonnet_parser::FieldName::Fixed(n) => n.clone(),61		jsonnet_parser::FieldName::Dyn(expr) => {62			evaluate(context, expr)?.try_cast_str("dynamic field name")?63		}64	})65}6667pub fn evaluate_unary_op(op: UnaryOpType, b: &Val) -> Result<Val> {68	Ok(match (op, b) {69		(o, Val::Lazy(l)) => evaluate_unary_op(o, &l.evaluate()?)?,70		(UnaryOpType::Not, Val::Bool(v)) => Val::Bool(!v),71		(op, o) => panic!("unary op not implemented: {:?} {:?}", op, o),72	})73}7475pub(crate) fn evaluate_add_op(a: &Val, b: &Val) -> Result<Val> {76	Ok(match (a, b) {77		(Val::Str(v1), Val::Str(v2)) => Val::Str(v1.to_owned() + &v2),78		(Val::Str(v1), Val::Num(v2)) => Val::Str(format!("{}{}", v1, v2)),79		(Val::Num(v1), Val::Str(v2)) => Val::Str(format!("{}{}", v1, v2)),80		(Val::Obj(v1), Val::Obj(v2)) => Val::Obj(v2.with_super(v1.clone())),81		(Val::Arr(a), Val::Arr(b)) => Val::Arr([&a[..], &b[..]].concat()),82		(Val::Num(v1), Val::Num(v2)) => Val::Num(v1 + v2),83		_ => panic!("can't add: {:?} and {:?}", a, b),84	})85}8687pub fn evaluate_binary_op(context: Context, a: &Val, op: BinaryOpType, b: &Val) -> Result<Val> {88	Ok(match (a, op, b) {89		(Val::Lazy(a), o, b) => evaluate_binary_op(context, &a.evaluate()?, o, b)?,90		(a, o, Val::Lazy(b)) => evaluate_binary_op(context, a, o, &b.evaluate()?)?,9192		(a, BinaryOpType::Add, b) => evaluate_add_op(a, b)?,9394		(Val::Str(v1), BinaryOpType::Ne, Val::Str(v2)) => Val::Bool(v1 != v2),9596		(Val::Str(v1), BinaryOpType::Mul, Val::Num(v2)) => Val::Str(v1.repeat(*v2 as usize)),97		(Val::Str(format), BinaryOpType::Mod, args) => evaluate(98			context99				.with_var("__tmp__format__".to_owned(), Val::Str(format.to_owned()))?100				.with_var(101					"__tmp__args__".to_owned(),102					match args {103						Val::Arr(v) => Val::Arr(v.clone()),104						v => Val::Arr(vec![v.clone()]),105					},106				)?,107			&el!(Expr::Apply(108				el!(Expr::Index(109					el!(Expr::Var("std".to_owned())),110					el!(Expr::Str("format".to_owned()))111				)),112				ArgsDesc(vec![113					Arg(None, el!(Expr::Var("__tmp__format__".to_owned()))),114					Arg(None, el!(Expr::Var("__tmp__args__".to_owned())))115				])116			)),117		)?,118119		(Val::Bool(a), BinaryOpType::And, Val::Bool(b)) => Val::Bool(*a && *b),120		(Val::Bool(a), BinaryOpType::Or, Val::Bool(b)) => Val::Bool(*a || *b),121122		(Val::Num(v1), BinaryOpType::Mul, Val::Num(v2)) => Val::Num(v1 * v2),123		(Val::Num(v1), BinaryOpType::Div, Val::Num(v2)) => Val::Num(v1 / v2),124		(Val::Num(v1), BinaryOpType::Mod, Val::Num(v2)) => Val::Num(v1 % v2),125126		(Val::Num(v1), BinaryOpType::Sub, Val::Num(v2)) => Val::Num(v1 - v2),127128		(Val::Num(v1), BinaryOpType::Lhs, Val::Num(v2)) => {129			Val::Num(((*v1 as i32) << (*v2 as i32)) as f64)130		}131		(Val::Num(v1), BinaryOpType::Rhs, Val::Num(v2)) => {132			Val::Num(((*v1 as i32) >> (*v2 as i32)) as f64)133		}134135		(Val::Num(v1), BinaryOpType::Lt, Val::Num(v2)) => Val::Bool(v1 < v2),136		(Val::Num(v1), BinaryOpType::Gt, Val::Num(v2)) => Val::Bool(v1 > v2),137		(Val::Num(v1), BinaryOpType::Lte, Val::Num(v2)) => Val::Bool(v1 <= v2),138		(Val::Num(v1), BinaryOpType::Gte, Val::Num(v2)) => Val::Bool(v1 >= v2),139140		(Val::Num(v1), BinaryOpType::Eq, Val::Num(v2)) => Val::Bool((v1 - v2).abs() < f64::EPSILON),141		(Val::Num(v1), BinaryOpType::Ne, Val::Num(v2)) => Val::Bool((v1 - v2).abs() > f64::EPSILON),142143		(Val::Num(v1), BinaryOpType::BitAnd, Val::Num(v2)) => {144			Val::Num(((*v1 as i32) & (*v2 as i32)) as f64)145		}146		(Val::Num(v1), BinaryOpType::BitOr, Val::Num(v2)) => {147			Val::Num(((*v1 as i32) | (*v2 as i32)) as f64)148		}149		(Val::Num(v1), BinaryOpType::BitXor, Val::Num(v2)) => {150			Val::Num(((*v1 as i32) ^ (*v2 as i32)) as f64)151		}152		(a, BinaryOpType::Eq, b) => Val::Bool(a == b),153		(a, BinaryOpType::Ne, b) => Val::Bool(a != b),154		_ => panic!("no rules for binary operation: {:?} {:?} {:?}", a, op, b),155	})156}157158future_wrapper!(HashMap<String, LazyBinding>, FutureNewBindings);159future_wrapper!(ObjValue, FutureObjValue);160161pub fn evaluate_comp(162	context: Context,163	value: &LocExpr,164	specs: &[CompSpec],165) -> Result<Option<Vec<Val>>> {166	Ok(match specs.get(0) {167		None => Some(vec![evaluate(context, &value)?]),168		Some(CompSpec::IfSpec(IfSpecData(cond))) => {169			if evaluate(context.clone(), &cond)?.try_cast_bool("if spec")? {170				evaluate_comp(context, value, &specs[1..])?171			} else {172				None173			}174		}175		Some(CompSpec::ForSpec(ForSpecData(var, expr))) => {176			match evaluate(context.clone(), &expr)?.unwrap_if_lazy()? {177				Val::Arr(list) => {178					let mut out = Vec::new();179					for item in list {180						let item = item.clone();181						out.push(evaluate_comp(182							context.with_var(var.clone(), item)?,183							value,184							&specs[1..],185						)?);186					}187					Some(out.iter().flatten().flatten().cloned().collect())188				}189				_ => panic!("for expression evaluated to non-iterable value"),190			}191		}192	})193}194195// TODO: Asserts196pub fn evaluate_object(context: Context, object: ObjBody) -> Result<ObjValue> {197	Ok(match object {198		ObjBody::MemberList(members) => {199			let new_bindings = FutureNewBindings::new();200			let future_this = FutureObjValue::new();201			let context_creator = context_creator!(202				closure!(clone context, clone new_bindings, clone future_this, |this: Option<ObjValue>, super_obj: Option<ObjValue>| {203					Ok(context.clone().extend(204						new_bindings.clone().unwrap(),205						context.clone().dollar().clone().or_else(||this.clone()),206						Some(this.unwrap()),207						super_obj208					)?)209				})210			);211			{212				let mut bindings: HashMap<String, LazyBinding> = HashMap::new();213				for (n, b) in members214					.iter()215					.filter_map(|m| match m {216						Member::BindStmt(b) => Some(b.clone()),217						_ => None,218					})219					.map(|b| evaluate_binding(&b, context_creator.clone()))220				{221					bindings.insert(n, b);222				}223				new_bindings.fill(bindings);224			}225226			let mut new_members = BTreeMap::new();227			for member in members.into_iter() {228				match member {229					Member::Field(FieldMember {230						name,231						plus,232						params: None,233						visibility,234						value,235					}) => {236						let name = evaluate_field_name(context.clone(), &name)?;237						new_members.insert(238							name,239							ObjMember {240								add: plus,241								visibility: visibility.clone(),242								invoke: binding!(243									closure!(clone value, clone context_creator, |this, super_obj| {244										let context = context_creator.0(this, super_obj)?;245										// TODO: Assert246										evaluate(247											context,248											&value,249										)?.unwrap_if_lazy()250									})251								),252							},253						);254					}255					Member::Field(FieldMember {256						name,257						params: Some(params),258						value,259						..260					}) => {261						let name = evaluate_field_name(context.clone(), &name)?;262						new_members.insert(263							name,264							ObjMember {265								add: false,266								visibility: Visibility::Hidden,267								invoke: binding!(268									closure!(clone value, clone context_creator, |this, super_obj| {269										// TODO: Assert270										Ok(evaluate_method(271											context_creator.0(this, super_obj)?,272											&value.clone(),273											params.clone(),274										))275									})276								),277							},278						);279					}280					Member::BindStmt(_) => {}281					Member::AssertStmt(_) => {}282				}283			}284			future_this.fill(ObjValue::new(None, Rc::new(new_members)))285		}286		_ => todo!(),287	})288}289290pub fn evaluate(context: Context, expr: &LocExpr) -> Result<Val> {291	use Expr::*;292	push(expr.clone(), "expr".to_owned(), || {293		let LocExpr(expr, loc) = expr;294		Ok(match &**expr {295			Literal(LiteralType::This) => Val::Obj(296				context297					.this()298					.clone()299					.unwrap_or_else(|| panic!("this not found")),300			),301			Literal(LiteralType::Super) => Val::Obj(302				context303					.super_obj()304					.clone()305					.unwrap_or_else(|| panic!("super not found")),306			),307			Literal(LiteralType::True) => Val::Bool(true),308			Literal(LiteralType::False) => Val::Bool(false),309			Literal(LiteralType::Null) => Val::Null,310			Parened(e) => evaluate(context, e)?,311			Str(v) => Val::Str(v.clone()),312			Num(v) => Val::Num(*v),313			BinaryOp(v1, o, v2) => {314				let a = evaluate(context.clone(), v1)?.unwrap_if_lazy()?;315				let op = *o;316				let b = evaluate(context.clone(), v2)?.unwrap_if_lazy()?;317				evaluate_binary_op(context, &a, op, &b)?318			}319			UnaryOp(o, v) => evaluate_unary_op(*o, &evaluate(context, v)?)?,320			Var(name) => Val::Lazy(context.binding(&name)).unwrap_if_lazy()?,321			Index(value, index) => {322				match (323					evaluate(context.clone(), value)?.unwrap_if_lazy()?,324					evaluate(context.clone(), index)?,325				) {326					(Val::Obj(v), Val::Str(s)) => {327						if let Some(v) = v.get(&s)? {328							v.unwrap_if_lazy()?329						} else if let Some(Val::Str(n)) = v.get("__intristic_namespace__")? {330							Val::Intristic(n, s)331						} else {332							create_error(crate::Error::NoSuchField(s))?333						}334					}335					(Val::Arr(v), Val::Num(n)) => v336						.get(n as usize)337						.unwrap_or_else(|| panic!("out of bounds"))338						.clone(),339					(Val::Str(s), Val::Num(n)) => {340						Val::Str(s.chars().skip(n as usize).take(1).collect())341					}342					(v, i) => todo!("not implemented: {:?}[{:?}]", v, i.unwrap_if_lazy()),343				}344			}345			LocalExpr(bindings, returned) => {346				let mut new_bindings: HashMap<String, LazyBinding> = HashMap::new();347				let future_context = Context::new_future();348349				let context_creator = context_creator!(350					closure!(clone future_context, |_, _| Ok(future_context.clone().unwrap()))351				);352353				for (k, v) in bindings354					.iter()355					.map(|b| evaluate_binding(b, context_creator.clone()))356				{357					new_bindings.insert(k, v);358				}359360				let context = context361					.extend(new_bindings, None, None, None)?362					.into_future(future_context);363				evaluate(context, &returned.clone())?364			}365			Arr(items) => {366				let mut out = Vec::with_capacity(items.len());367				for item in items {368					out.push(evaluate(context.clone(), item)?);369				}370				Val::Arr(out)371			}372			ArrComp(expr, compspecs) => Val::Arr(373				// First compspec should be forspec, so no "None" possible here374				evaluate_comp(context, expr, compspecs)?.unwrap(),375			),376			Obj(body) => Val::Obj(evaluate_object(context, body.clone())?),377			Apply(value, ArgsDesc(args)) => {378				let value = evaluate(context.clone(), value)?.unwrap_if_lazy()?;379				match value {380					// TODO: Capture context of application381					Val::Intristic(ns, name) => match (&ns as &str, &name as &str) {382						// arr/string/function383						("std", "length") => {384							assert_eq!(args.len(), 1);385							let expr = &args.get(0).unwrap().1;386							match evaluate(context, expr)? {387								Val::Str(n) => Val::Num(n.chars().count() as f64),388								Val::Arr(i) => Val::Num(i.len() as f64),389								v => panic!("can't get length of {:?}", v),390							}391						}392						// any393						("std", "type") => {394							assert_eq!(args.len(), 1);395							let expr = &args.get(0).unwrap().1;396							Val::Str(evaluate(context, expr)?.value_type()?.name().to_owned())397						}398						// length, idx=>any399						("std", "makeArray") => {400							assert_eq!(args.len(), 2);401							if let (Val::Num(v), Val::Func(d)) = (402								evaluate(context.clone(), &args[0].1)?,403								evaluate(context, &args[1].1)?,404							) {405								assert!(v > 0.0);406								let mut out = Vec::with_capacity(v as usize);407								for i in 0..v as usize {408									out.push(d.evaluate(vec![(None, Val::Num(i as f64))])?)409								}410								Val::Arr(out)411							} else {412								panic!("bad makeArray call");413							}414						}415						// string416						("std", "codepoint") => {417							assert_eq!(args.len(), 1);418							if let Val::Str(s) = evaluate(context, &args[0].1)? {419								assert!(420									s.chars().count() == 1,421									"std.codepoint should receive single char string"422								);423								Val::Num(s.chars().take(1).next().unwrap() as u32 as f64)424							} else {425								panic!("bad codepoint call");426							}427						}428						// object, includeHidden429						("std", "objectFieldsEx") => {430							assert_eq!(args.len(), 2);431							if let (Val::Obj(body), Val::Bool(_include_hidden)) = (432								evaluate(context.clone(), &args[0].1)?,433								evaluate(context, &args[1].1)?,434							) {435								// TODO: handle visibility (_include_hidden)436								Val::Arr(body.fields().into_iter().map(Val::Str).collect())437							} else {438								panic!("bad objectFieldsEx call");439							}440						}441						(ns, name) => panic!("Intristic not found: {}.{}", ns, name),442					},443					Val::Func(f) => f.evaluate(444						args.clone()445							.into_iter()446							.map(move |a| {447								(448									a.clone().0,449									Val::Lazy(lazy_val!(450										closure!(clone context, clone a, || evaluate(context.clone(), &a.clone().1))451									)),452								)453							})454							.collect(),455					)?,456					_ => panic!("{:?} is not a function", value),457				}458			}459			Function(params, body) => evaluate_method(context, body, params.clone()),460			AssertExpr(AssertStmt(value, msg), returned) => {461				if evaluate(context.clone(), &value)?462					.try_cast_bool("assertion condition should be boolean")?463				{464					evaluate(context, returned)?465				} else if let Some(msg) = msg {466					panic!(467						"assertion failed ({:?}): {}",468						value,469						evaluate(context, msg)?470							.try_cast_str("assertion message should be string")?471					);472				} else {473					panic!("assertion failed ({:?}): no message", value);474				}475			}476			Error(e) => create_error(crate::Error::RuntimeError(477				evaluate(context, e)?.try_cast_str("error text should be string")?,478			))?,479			IfElse {480				cond,481				cond_then,482				cond_else,483			} => {484				if evaluate(context.clone(), &cond.0)?485					.try_cast_bool("if condition should be boolean")?486				{487					evaluate(context, cond_then)?488				} else {489					match cond_else {490						Some(v) => evaluate(context, v)?,491						None => Val::Bool(false),492					}493				}494			}495			_ => panic!(496				"evaluation not implemented: {:?}",497				LocExpr(expr.clone(), loc.clone())498			),499		})500	})501}
after · crates/jsonnet-evaluator/src/evaluate.rs
1use crate::{2	binding, context_creator, create_error, function_default, function_rhs, future_wrapper,3	lazy_binding, lazy_val, push, Context, ContextCreator, FuncDesc, LazyBinding, ObjMember,4	ObjValue, Result, Val,5};6use closure::closure;7use jsonnet_parser::{8	el, Arg, ArgsDesc, AssertStmt, BinaryOpType, BindSpec, CompSpec, Expr, FieldMember,9	ForSpecData, IfSpecData, LiteralType, LocExpr, Member, ObjBody, ParamsDesc, UnaryOpType,10	Visibility,11};12use std::{13	collections::{BTreeMap, HashMap},14	rc::Rc,15};1617pub fn evaluate_binding(b: &BindSpec, context_creator: ContextCreator) -> (String, LazyBinding) {18	let b = b.clone();19	if let Some(args) = &b.params {20		let args = args.clone();21		(22			b.name.clone(),23			lazy_binding!(move |this, super_obj| Ok(lazy_val!(24				closure!(clone b, clone args, clone context_creator, || Ok(evaluate_method(25					context_creator.0(this.clone(), super_obj.clone())?,26					&b.value,27					args.clone()28				)))29			))),30		)31	} else {32		(33			b.name.clone(),34			lazy_binding!(move |this, super_obj| {35				Ok(lazy_val!(36					closure!(clone context_creator, clone b, || evaluate(37						context_creator.0(this.clone(), super_obj.clone())?,38						&b.value39					))40				))41			}),42		)43	}44}4546pub fn evaluate_method(ctx: Context, expr: &LocExpr, arg_spec: ParamsDesc) -> Val {47	Val::Func(FuncDesc {48		ctx,49		params: arg_spec,50		eval_rhs: function_rhs!(closure!(clone expr, |ctx| evaluate(ctx, &expr))),51		eval_default: function_default!(closure!(|ctx, default| evaluate(ctx, &default))),52	})53}5455pub fn evaluate_field_name(56	context: Context,57	field_name: &jsonnet_parser::FieldName,58) -> Result<String> {59	Ok(match field_name {60		jsonnet_parser::FieldName::Fixed(n) => n.clone(),61		jsonnet_parser::FieldName::Dyn(expr) => {62			evaluate(context, expr)?.try_cast_str("dynamic field name")?63		}64	})65}6667pub fn evaluate_unary_op(op: UnaryOpType, b: &Val) -> Result<Val> {68	Ok(match (op, b) {69		(o, Val::Lazy(l)) => evaluate_unary_op(o, &l.evaluate()?)?,70		(UnaryOpType::Not, Val::Bool(v)) => Val::Bool(!v),71		(op, o) => panic!("unary op not implemented: {:?} {:?}", op, o),72	})73}7475pub(crate) fn evaluate_add_op(a: &Val, b: &Val) -> Result<Val> {76	Ok(match (a, b) {77		(Val::Str(v1), Val::Str(v2)) => Val::Str(v1.to_owned() + &v2),78		(Val::Str(v1), Val::Num(v2)) => Val::Str(format!("{}{}", v1, v2)),79		(Val::Num(v1), Val::Str(v2)) => Val::Str(format!("{}{}", v1, v2)),80		(Val::Str(v1), v2) => Val::Str(format!("{}{:?}", v1, v2)),81		(Val::Obj(v1), Val::Obj(v2)) => Val::Obj(v2.with_super(v1.clone())),82		(Val::Arr(a), Val::Arr(b)) => Val::Arr([&a[..], &b[..]].concat()),83		(Val::Num(v1), Val::Num(v2)) => Val::Num(v1 + v2),84		_ => panic!("can't add: {:?} and {:?}", a, b),85	})86}8788pub fn evaluate_binary_op(context: Context, a: &Val, op: BinaryOpType, b: &Val) -> Result<Val> {89	Ok(match (a, op, b) {90		(Val::Lazy(a), o, b) => evaluate_binary_op(context, &a.evaluate()?, o, b)?,91		(a, o, Val::Lazy(b)) => evaluate_binary_op(context, a, o, &b.evaluate()?)?,9293		(a, BinaryOpType::Add, b) => evaluate_add_op(a, b)?,9495		(Val::Str(v1), BinaryOpType::Ne, Val::Str(v2)) => Val::Bool(v1 != v2),9697		(Val::Str(v1), BinaryOpType::Mul, Val::Num(v2)) => Val::Str(v1.repeat(*v2 as usize)),98		(Val::Str(format), BinaryOpType::Mod, args) => evaluate(99			context100				.with_var("__tmp__format__".to_owned(), Val::Str(format.to_owned()))?101				.with_var(102					"__tmp__args__".to_owned(),103					match args {104						Val::Arr(v) => Val::Arr(v.clone()),105						v => Val::Arr(vec![v.clone()]),106					},107				)?,108			&el!(Expr::Apply(109				el!(Expr::Index(110					el!(Expr::Var("std".to_owned())),111					el!(Expr::Str("format".to_owned()))112				)),113				ArgsDesc(vec![114					Arg(None, el!(Expr::Var("__tmp__format__".to_owned()))),115					Arg(None, el!(Expr::Var("__tmp__args__".to_owned())))116				])117			)),118		)?,119120		(Val::Bool(a), BinaryOpType::And, Val::Bool(b)) => Val::Bool(*a && *b),121		(Val::Bool(a), BinaryOpType::Or, Val::Bool(b)) => Val::Bool(*a || *b),122123		(Val::Num(v1), BinaryOpType::Mul, Val::Num(v2)) => Val::Num(v1 * v2),124		(Val::Num(v1), BinaryOpType::Div, Val::Num(v2)) => Val::Num(v1 / v2),125		(Val::Num(v1), BinaryOpType::Mod, Val::Num(v2)) => Val::Num(v1 % v2),126127		(Val::Num(v1), BinaryOpType::Sub, Val::Num(v2)) => Val::Num(v1 - v2),128129		(Val::Num(v1), BinaryOpType::Lhs, Val::Num(v2)) => {130			Val::Num(((*v1 as i32) << (*v2 as i32)) as f64)131		}132		(Val::Num(v1), BinaryOpType::Rhs, Val::Num(v2)) => {133			Val::Num(((*v1 as i32) >> (*v2 as i32)) as f64)134		}135136		(Val::Num(v1), BinaryOpType::Lt, Val::Num(v2)) => Val::Bool(v1 < v2),137		(Val::Num(v1), BinaryOpType::Gt, Val::Num(v2)) => Val::Bool(v1 > v2),138		(Val::Num(v1), BinaryOpType::Lte, Val::Num(v2)) => Val::Bool(v1 <= v2),139		(Val::Num(v1), BinaryOpType::Gte, Val::Num(v2)) => Val::Bool(v1 >= v2),140141		(Val::Num(v1), BinaryOpType::Eq, Val::Num(v2)) => Val::Bool((v1 - v2).abs() < f64::EPSILON),142		(Val::Num(v1), BinaryOpType::Ne, Val::Num(v2)) => Val::Bool((v1 - v2).abs() > f64::EPSILON),143144		(Val::Num(v1), BinaryOpType::BitAnd, Val::Num(v2)) => {145			Val::Num(((*v1 as i32) & (*v2 as i32)) as f64)146		}147		(Val::Num(v1), BinaryOpType::BitOr, Val::Num(v2)) => {148			Val::Num(((*v1 as i32) | (*v2 as i32)) as f64)149		}150		(Val::Num(v1), BinaryOpType::BitXor, Val::Num(v2)) => {151			Val::Num(((*v1 as i32) ^ (*v2 as i32)) as f64)152		}153		(a, BinaryOpType::Eq, b) => Val::Bool(a == b),154		(a, BinaryOpType::Ne, b) => Val::Bool(a != b),155		_ => panic!("no rules for binary operation: {:?} {:?} {:?}", a, op, b),156	})157}158159future_wrapper!(HashMap<String, LazyBinding>, FutureNewBindings);160future_wrapper!(ObjValue, FutureObjValue);161162pub fn evaluate_comp(163	context: Context,164	value: &LocExpr,165	specs: &[CompSpec],166) -> Result<Option<Vec<Val>>> {167	Ok(match specs.get(0) {168		None => Some(vec![evaluate(context, &value)?]),169		Some(CompSpec::IfSpec(IfSpecData(cond))) => {170			if evaluate(context.clone(), &cond)?.try_cast_bool("if spec")? {171				evaluate_comp(context, value, &specs[1..])?172			} else {173				None174			}175		}176		Some(CompSpec::ForSpec(ForSpecData(var, expr))) => {177			match evaluate(context.clone(), &expr)?.unwrap_if_lazy()? {178				Val::Arr(list) => {179					let mut out = Vec::new();180					for item in list {181						let item = item.clone();182						out.push(evaluate_comp(183							context.with_var(var.clone(), item)?,184							value,185							&specs[1..],186						)?);187					}188					Some(out.iter().flatten().flatten().cloned().collect())189				}190				_ => panic!("for expression evaluated to non-iterable value"),191			}192		}193	})194}195196// TODO: Asserts197pub fn evaluate_object(context: Context, object: ObjBody) -> Result<ObjValue> {198	Ok(match object {199		ObjBody::MemberList(members) => {200			let new_bindings = FutureNewBindings::new();201			let future_this = FutureObjValue::new();202			let context_creator = context_creator!(203				closure!(clone context, clone new_bindings, clone future_this, |this: Option<ObjValue>, super_obj: Option<ObjValue>| {204					Ok(context.clone().extend(205						new_bindings.clone().unwrap(),206						context.clone().dollar().clone().or_else(||this.clone()),207						Some(this.unwrap()),208						super_obj209					)?)210				})211			);212			{213				let mut bindings: HashMap<String, LazyBinding> = HashMap::new();214				for (n, b) in members215					.iter()216					.filter_map(|m| match m {217						Member::BindStmt(b) => Some(b.clone()),218						_ => None,219					})220					.map(|b| evaluate_binding(&b, context_creator.clone()))221				{222					bindings.insert(n, b);223				}224				new_bindings.fill(bindings);225			}226227			let mut new_members = BTreeMap::new();228			for member in members.into_iter() {229				match member {230					Member::Field(FieldMember {231						name,232						plus,233						params: None,234						visibility,235						value,236					}) => {237						let name = evaluate_field_name(context.clone(), &name)?;238						new_members.insert(239							name,240							ObjMember {241								add: plus,242								visibility: visibility.clone(),243								invoke: binding!(244									closure!(clone value, clone context_creator, |this, super_obj| {245										let context = context_creator.0(this, super_obj)?;246										// TODO: Assert247										evaluate(248											context,249											&value,250										)?.unwrap_if_lazy()251									})252								),253							},254						);255					}256					Member::Field(FieldMember {257						name,258						params: Some(params),259						value,260						..261					}) => {262						let name = evaluate_field_name(context.clone(), &name)?;263						new_members.insert(264							name,265							ObjMember {266								add: false,267								visibility: Visibility::Hidden,268								invoke: binding!(269									closure!(clone value, clone context_creator, |this, super_obj| {270										// TODO: Assert271										Ok(evaluate_method(272											context_creator.0(this, super_obj)?,273											&value.clone(),274											params.clone(),275										))276									})277								),278							},279						);280					}281					Member::BindStmt(_) => {}282					Member::AssertStmt(_) => {}283				}284			}285			future_this.fill(ObjValue::new(None, Rc::new(new_members)))286		}287		_ => todo!(),288	})289}290291pub fn evaluate(context: Context, expr: &LocExpr) -> Result<Val> {292	use Expr::*;293	push(expr.clone(), "expr".to_owned(), || {294		let LocExpr(expr, loc) = expr;295		Ok(match &**expr {296			Literal(LiteralType::This) => Val::Obj(297				context298					.this()299					.clone()300					.unwrap_or_else(|| panic!("this not found")),301			),302			Literal(LiteralType::Super) => Val::Obj(303				context304					.super_obj()305					.clone()306					.unwrap_or_else(|| panic!("super not found")),307			),308			Literal(LiteralType::True) => Val::Bool(true),309			Literal(LiteralType::False) => Val::Bool(false),310			Literal(LiteralType::Null) => Val::Null,311			Parened(e) => evaluate(context, e)?,312			Str(v) => Val::Str(v.clone()),313			Num(v) => Val::Num(*v),314			BinaryOp(v1, o, v2) => {315				let a = evaluate(context.clone(), v1)?.unwrap_if_lazy()?;316				let op = *o;317				let b = evaluate(context.clone(), v2)?.unwrap_if_lazy()?;318				evaluate_binary_op(context, &a, op, &b)?319			}320			UnaryOp(o, v) => evaluate_unary_op(*o, &evaluate(context, v)?)?,321			Var(name) => Val::Lazy(context.binding(&name)).unwrap_if_lazy()?,322			Index(value, index) => {323				match (324					evaluate(context.clone(), value)?.unwrap_if_lazy()?,325					evaluate(context.clone(), index)?,326				) {327					(Val::Obj(v), Val::Str(s)) => {328						if let Some(v) = v.get(&s)? {329							v.unwrap_if_lazy()?330						} else if let Some(Val::Str(n)) = v.get("__intristic_namespace__")? {331							Val::Intristic(n, s)332						} else {333							create_error(crate::Error::NoSuchField(s))?334						}335					}336					(Val::Arr(v), Val::Num(n)) => v337						.get(n as usize)338						.unwrap_or_else(|| panic!("out of bounds"))339						.clone(),340					(Val::Str(s), Val::Num(n)) => {341						Val::Str(s.chars().skip(n as usize).take(1).collect())342					}343					(v, i) => todo!("not implemented: {:?}[{:?}]", v, i.unwrap_if_lazy()),344				}345			}346			LocalExpr(bindings, returned) => {347				let mut new_bindings: HashMap<String, LazyBinding> = HashMap::new();348				let future_context = Context::new_future();349350				let context_creator = context_creator!(351					closure!(clone future_context, |_, _| Ok(future_context.clone().unwrap()))352				);353354				for (k, v) in bindings355					.iter()356					.map(|b| evaluate_binding(b, context_creator.clone()))357				{358					new_bindings.insert(k, v);359				}360361				let context = context362					.extend(new_bindings, None, None, None)?363					.into_future(future_context);364				evaluate(context, &returned.clone())?365			}366			Arr(items) => {367				let mut out = Vec::with_capacity(items.len());368				for item in items {369					out.push(evaluate(context.clone(), item)?);370				}371				Val::Arr(out)372			}373			ArrComp(expr, compspecs) => Val::Arr(374				// First compspec should be forspec, so no "None" possible here375				evaluate_comp(context, expr, compspecs)?.unwrap(),376			),377			Obj(body) => Val::Obj(evaluate_object(context, body.clone())?),378			Apply(value, ArgsDesc(args)) => {379				let value = evaluate(context.clone(), value)?.unwrap_if_lazy()?;380				match value {381					// TODO: Capture context of application382					Val::Intristic(ns, name) => match (&ns as &str, &name as &str) {383						// arr/string/function384						("std", "length") => {385							assert_eq!(args.len(), 1);386							let expr = &args.get(0).unwrap().1;387							match evaluate(context, expr)? {388								Val::Str(n) => Val::Num(n.chars().count() as f64),389								Val::Arr(i) => Val::Num(i.len() as f64),390								v => panic!("can't get length of {:?}", v),391							}392						}393						// any394						("std", "type") => {395							assert_eq!(args.len(), 1);396							let expr = &args.get(0).unwrap().1;397							Val::Str(evaluate(context, expr)?.value_type()?.name().to_owned())398						}399						// length, idx=>any400						("std", "makeArray") => {401							assert_eq!(args.len(), 2);402							if let (Val::Num(v), Val::Func(d)) = (403								evaluate(context.clone(), &args[0].1)?,404								evaluate(context, &args[1].1)?,405							) {406								assert!(v > 0.0);407								let mut out = Vec::with_capacity(v as usize);408								for i in 0..v as usize {409									out.push(d.evaluate(vec![(None, Val::Num(i as f64))])?)410								}411								Val::Arr(out)412							} else {413								panic!("bad makeArray call");414							}415						}416						// string417						("std", "codepoint") => {418							assert_eq!(args.len(), 1);419							if let Val::Str(s) = evaluate(context, &args[0].1)? {420								assert!(421									s.chars().count() == 1,422									"std.codepoint should receive single char string"423								);424								Val::Num(s.chars().take(1).next().unwrap() as u32 as f64)425							} else {426								panic!("bad codepoint call");427							}428						}429						// object, includeHidden430						("std", "objectFieldsEx") => {431							assert_eq!(args.len(), 2);432							if let (Val::Obj(body), Val::Bool(_include_hidden)) = (433								evaluate(context.clone(), &args[0].1)?,434								evaluate(context, &args[1].1)?,435							) {436								// TODO: handle visibility (_include_hidden)437								Val::Arr(body.fields().into_iter().map(Val::Str).collect())438							} else {439								panic!("bad objectFieldsEx call");440							}441						}442						(ns, name) => panic!("Intristic not found: {}.{}", ns, name),443					},444					Val::Func(f) => f.evaluate(445						args.clone()446							.into_iter()447							.map(move |a| {448								(449									a.clone().0,450									Val::Lazy(lazy_val!(451										closure!(clone context, clone a, || evaluate(context.clone(), &a.clone().1))452									)),453								)454							})455							.collect(),456					)?,457					_ => panic!("{:?} is not a function", value),458				}459			}460			Function(params, body) => evaluate_method(context, body, params.clone()),461			AssertExpr(AssertStmt(value, msg), returned) => {462				if evaluate(context.clone(), &value)?463					.try_cast_bool("assertion condition should be boolean")?464				{465					evaluate(context, returned)?466				} else if let Some(msg) = msg {467					panic!(468						"assertion failed ({:?}): {}",469						value,470						evaluate(context, msg)?471							.try_cast_str("assertion message should be string")?472					);473				} else {474					panic!("assertion failed ({:?}): no message", value);475				}476			}477			Error(e) => create_error(crate::Error::RuntimeError(478				evaluate(context, e)?.try_cast_str("error text should be string")?,479			))?,480			IfElse {481				cond,482				cond_then,483				cond_else,484			} => {485				if evaluate(context.clone(), &cond.0)?486					.try_cast_bool("if condition should be boolean")?487				{488					evaluate(context, cond_then)?489				} else {490					match cond_else {491						Some(v) => evaluate(context, v)?,492						None => Val::Bool(false),493					}494				}495			}496			_ => panic!(497				"evaluation not implemented: {:?}",498				LocExpr(expr.clone(), loc.clone())499			),500		})501	})502}
modifiedcrates/jsonnet-evaluator/src/lib.rsdiffbeforeafterboth
--- a/crates/jsonnet-evaluator/src/lib.rs
+++ b/crates/jsonnet-evaluator/src/lib.rs
@@ -84,6 +84,13 @@
 
 		Ok(())
 	}
+	pub fn get_source(&self, name: &str) -> String {
+		let ro_map = self.0.files.borrow();
+		let value = ro_map
+			.get(name)
+			.unwrap_or_else(|| panic!("file not added: {:?}", name));
+		value.0.clone()
+	}
 	pub fn evaluate_file(&self, name: &str) -> Result<Val> {
 		self.begin_state();
 		let expr: LocExpr = {