git.delta.rocks / jrsonnet / refs/commits / 90e93cc51b3a

difftreelog

feat experimental object field order preservation

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

15 files changed

modifiedCargo.lockdiffbeforeafterboth
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -492,6 +492,7 @@
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "d0ffa0837f2dfa6fb90868c2b5468cad482e175f7dad97e7421951e663f2b527"
 dependencies = [
+ "indexmap",
  "itoa",
  "ryu",
  "serde",
modifiedbindings/jsonnet/Cargo.tomldiffbeforeafterboth
--- a/bindings/jsonnet/Cargo.toml
+++ b/bindings/jsonnet/Cargo.toml
@@ -17,3 +17,4 @@
 
 [features]
 interop = []
+exp-preserve-order = ["jrsonnet-evaluator/exp-preserve-order"]
modifiedbindings/jsonnet/src/lib.rsdiffbeforeafterboth
--- a/bindings/jsonnet/src/lib.rs
+++ b/bindings/jsonnet/src/lib.rs
@@ -58,7 +58,11 @@
 pub extern "C" fn jsonnet_string_output(vm: &EvaluationState, v: c_int) {
 	match v {
 		1 => vm.set_manifest_format(ManifestFormat::String),
-		0 => vm.set_manifest_format(ManifestFormat::Json(4)),
+		0 => vm.set_manifest_format(ManifestFormat::Json {
+			padding: 4,
+			#[cfg(feature = "exp-preserve-order")]
+			preserve_order: false,
+		}),
 		_ => panic!("incorrect output format"),
 	}
 }
modifiedbindings/jsonnet/src/val_modify.rsdiffbeforeafterboth
--- a/bindings/jsonnet/src/val_modify.rs
+++ b/bindings/jsonnet/src/val_modify.rs
@@ -5,8 +5,7 @@
 use std::{ffi::CStr, os::raw::c_char};
 
 use gcmodule::Cc;
-use jrsonnet_evaluator::{val::ArrValue, EvaluationState, LazyBinding, LazyVal, ObjMember, Val};
-use jrsonnet_parser::Visibility;
+use jrsonnet_evaluator::{val::ArrValue, EvaluationState, LazyVal, Val};
 
 /// # Safety
 ///
@@ -41,19 +40,9 @@
 	val: &Val,
 ) {
 	match obj {
-		Val::Obj(old) => {
-			let new_obj = old.clone().extend_with_field(
-				CStr::from_ptr(name).to_str().unwrap().into(),
-				ObjMember {
-					add: false,
-					visibility: Visibility::Normal,
-					invoke: LazyBinding::Bound(LazyVal::new_resolved(val.clone())),
-					location: None,
-				},
-			);
-
-			*obj = Val::Obj(new_obj);
-		}
+		Val::Obj(old) => old
+			.extend_field(CStr::from_ptr(name).to_str().unwrap().into())
+			.value(val.clone()),
 		_ => panic!("should receive object"),
 	}
 }
modifiedcmds/jrsonnet/Cargo.tomldiffbeforeafterboth
--- a/cmds/jrsonnet/Cargo.toml
+++ b/cmds/jrsonnet/Cargo.toml
@@ -9,6 +9,12 @@
 [features]
 # Use mimalloc as allocator
 mimalloc = ["mimallocator"]
+# Experimental feature, which allows to preserve order of object fields
+exp-preserve-order = [
+    "jrsonnet-evaluator/exp-preserve-order",
+    "jrsonnet-evaluator/exp-serde-preserve-order",
+    "jrsonnet-cli/exp-preserve-order",
+]
 
 [dependencies]
 jrsonnet-evaluator = { path = "../../crates/jrsonnet-evaluator", version = "0.4.2" }
modifiedcrates/jrsonnet-cli/Cargo.tomldiffbeforeafterboth
--- a/crates/jrsonnet-cli/Cargo.toml
+++ b/crates/jrsonnet-cli/Cargo.toml
@@ -6,6 +6,9 @@
 license = "MIT"
 edition = "2021"
 
+[features]
+exp-preserve-order = ["jrsonnet-evaluator/exp-preserve-order"]
+
 [dependencies]
 jrsonnet-evaluator = { path = "../../crates/jrsonnet-evaluator", version = "0.4.2", features = [
     "explaining-traces",
modifiedcrates/jrsonnet-cli/src/manifest.rsdiffbeforeafterboth
--- a/crates/jrsonnet-cli/src/manifest.rs
+++ b/crates/jrsonnet-cli/src/manifest.rs
@@ -43,20 +43,30 @@
 	/// `0` for hard tabs, `-1` for single line output [default: 3 for json, 2 for yaml]
 	#[clap(long)]
 	line_padding: Option<usize>,
+	/// Preserve order in object manifestification
+	#[cfg(feature = "exp-preserve-order")]
+	#[clap(long)]
+	exp_preserve_order: bool,
 }
 impl ConfigureState for ManifestOpts {
 	fn configure(&self, state: &EvaluationState) -> Result<()> {
 		if self.string {
 			state.set_manifest_format(ManifestFormat::String);
 		} else {
+			#[cfg(feature = "exp-preserve-order")]
+			let preserve_order = self.exp_preserve_order;
 			match self.format {
 				ManifestFormatName::String => state.set_manifest_format(ManifestFormat::String),
-				ManifestFormatName::Json => {
-					state.set_manifest_format(ManifestFormat::Json(self.line_padding.unwrap_or(3)))
-				}
-				ManifestFormatName::Yaml => {
-					state.set_manifest_format(ManifestFormat::Yaml(self.line_padding.unwrap_or(2)))
-				}
+				ManifestFormatName::Json => state.set_manifest_format(ManifestFormat::Json {
+					padding: self.line_padding.unwrap_or(3),
+					#[cfg(feature = "exp-preserve-order")]
+					preserve_order,
+				}),
+				ManifestFormatName::Yaml => state.set_manifest_format(ManifestFormat::Yaml {
+					padding: self.line_padding.unwrap_or(2),
+					#[cfg(feature = "exp-preserve-order")]
+					preserve_order,
+				}),
 			}
 		}
 		if self.yaml_stream {
modifiedcrates/jrsonnet-evaluator/Cargo.tomldiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/Cargo.toml
+++ b/crates/jrsonnet-evaluator/Cargo.toml
@@ -15,6 +15,10 @@
 # Allows library authors to throw custom errors
 anyhow-error = ["anyhow"]
 
+# Allows to preserve field order in objects
+exp-preserve-order = []
+exp-serde-preserve-order = ["serde_json/preserve_order"]
+
 [dependencies]
 jrsonnet-interner = { path = "../jrsonnet-interner", version = "0.4.2" }
 jrsonnet-parser = { path = "../jrsonnet-parser", version = "0.4.2" }
modifiedcrates/jrsonnet-evaluator/src/builtin/manifest.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/builtin/manifest.rs
+++ b/crates/jrsonnet-evaluator/src/builtin/manifest.rs
@@ -21,6 +21,8 @@
 	pub mtype: ManifestType,
 	pub newline: &'s str,
 	pub key_val_sep: &'s str,
+	#[cfg(feature = "exp-preserve-order")]
+	pub preserve_order: bool,
 }
 
 pub fn manifest_json_ex(val: &Val, options: &ManifestJsonOptions<'_>) -> Result<String> {
@@ -85,7 +87,10 @@
 		Val::Obj(obj) => {
 			obj.run_assertions()?;
 			buf.push('{');
-			let fields = obj.fields();
+			let fields = obj.fields(
+				#[cfg(feature = "exp-preserve-order")]
+				options.preserve_order,
+			);
 			if !fields.is_empty() {
 				if mtype != ManifestType::ToString && mtype != ManifestType::Minify {
 					buf.push_str(options.newline);
@@ -182,6 +187,10 @@
 	/// safe_key: 1
 	/// ```
 	pub quote_keys: bool,
+	/// If true - then order of fields is preserved as written,
+	/// instead of sorting alphabetically
+	#[cfg(feature = "exp-preserve-order")]
+	pub preserve_order: bool,
 }
 
 /// From https://github.com/chyh1990/yaml-rust/blob/da52a68615f2ecdd6b7e4567019f280c433c1521/src/emitter.rs#L289
@@ -287,7 +296,14 @@
 			if o.is_empty() {
 				buf.push_str("{}");
 			} else {
-				for (i, key) in o.fields().iter().enumerate() {
+				for (i, key) in o
+					.fields(
+						#[cfg(feature = "exp-preserve-order")]
+						options.preserve_order,
+					)
+					.iter()
+					.enumerate()
+				{
 					if i != 0 {
 						buf.push('\n');
 						buf.push_str(cur_padding);
modifiedcrates/jrsonnet-evaluator/src/builtin/mod.rsdiffbeforeafterboth
before · crates/jrsonnet-evaluator/src/builtin/mod.rs
1use std::{2	collections::HashMap,3	convert::{TryFrom, TryInto},4};56use format::{format_arr, format_obj};7use gcmodule::Cc;8use jrsonnet_interner::IStr;9use serde::Deserialize;10use serde_yaml::DeserializingQuirks;1112use crate::{13	builtin::manifest::{manifest_yaml_ex, ManifestYamlOptions},14	error::{Error::*, Result},15	function::{CallLocation, StaticBuiltin},16	operator::evaluate_mod_op,17	push_frame, throw,18	typed::{Any, BoundedUsize, Bytes, Either2, Either4, PositiveF64, VecVal, M1},19	val::{equals, primitive_equals, ArrValue, FuncVal, IndexableVal, Slice},20	with_state, Either, ObjValue, Val,21};2223pub mod stdlib;24pub use stdlib::*;2526use self::manifest::{escape_string_json, manifest_json_ex, ManifestJsonOptions, ManifestType};2728pub mod format;29pub mod manifest;30pub mod sort;3132pub fn std_format(str: IStr, vals: Val) -> Result<String> {33	push_frame(34		CallLocation::native(),35		|| format!("std.format of {}", str),36		|| {37			Ok(match vals {38				Val::Arr(vals) => format_arr(&str, &vals.evaluated()?)?,39				Val::Obj(obj) => format_obj(&str, &obj)?,40				o => format_arr(&str, &[o])?,41			})42		},43	)44}4546pub fn std_slice(47	indexable: IndexableVal,48	index: Option<BoundedUsize<0, { i32::MAX as usize }>>,49	end: Option<BoundedUsize<0, { i32::MAX as usize }>>,50	step: Option<BoundedUsize<1, { i32::MAX as usize }>>,51) -> Result<Val> {52	match &indexable {53		IndexableVal::Str(s) => {54			let index = index.as_deref().copied().unwrap_or(0);55			let end = end.as_deref().copied().unwrap_or(usize::MAX);56			let step = step.as_deref().copied().unwrap_or(1);5758			if index >= end {59				return Ok(Val::Str("".into()));60			}6162			Ok(Val::Str(63				(s.chars()64					.skip(index)65					.take(end - index)66					.step_by(step)67					.collect::<String>())68				.into(),69			))70		}71		IndexableVal::Arr(arr) => {72			let index = index.as_deref().copied().unwrap_or(0);73			let end = end.as_deref().copied().unwrap_or(usize::MAX).min(arr.len());74			let step = step.as_deref().copied().unwrap_or(1);7576			if index >= end {77				return Ok(Val::Arr(ArrValue::new_eager()));78			}7980			Ok(Val::Arr(ArrValue::Slice(Box::new(Slice {81				inner: arr.clone(),82				from: index as u32,83				to: end as u32,84				step: step as u32,85			}))))86		}87	}88}8990type BuiltinsType = HashMap<IStr, &'static dyn StaticBuiltin>;9192thread_local! {93	pub static BUILTINS: BuiltinsType = {94		[95			("length".into(), builtin_length::INST),96			("type".into(), builtin_type::INST),97			("makeArray".into(), builtin_make_array::INST),98			("codepoint".into(), builtin_codepoint::INST),99			("objectFieldsEx".into(), builtin_object_fields_ex::INST),100			("objectHasEx".into(), builtin_object_has_ex::INST),101			("slice".into(), builtin_slice::INST),102			("substr".into(), builtin_substr::INST),103			("primitiveEquals".into(), builtin_primitive_equals::INST),104			("equals".into(), builtin_equals::INST),105			("modulo".into(), builtin_modulo::INST),106			("mod".into(), builtin_mod::INST),107			("floor".into(), builtin_floor::INST),108			("ceil".into(), builtin_ceil::INST),109			("log".into(), builtin_log::INST),110			("pow".into(), builtin_pow::INST),111			("sqrt".into(), builtin_sqrt::INST),112			("sin".into(), builtin_sin::INST),113			("cos".into(), builtin_cos::INST),114			("tan".into(), builtin_tan::INST),115			("asin".into(), builtin_asin::INST),116			("acos".into(), builtin_acos::INST),117			("atan".into(), builtin_atan::INST),118			("exp".into(), builtin_exp::INST),119			("mantissa".into(), builtin_mantissa::INST),120			("exponent".into(), builtin_exponent::INST),121			("extVar".into(), builtin_ext_var::INST),122			("native".into(), builtin_native::INST),123			("filter".into(), builtin_filter::INST),124			("map".into(), builtin_map::INST),125			("flatMap".into(), builtin_flatmap::INST),126			("foldl".into(), builtin_foldl::INST),127			("foldr".into(), builtin_foldr::INST),128			("sort".into(), builtin_sort::INST),129			("format".into(), builtin_format::INST),130			("range".into(), builtin_range::INST),131			("char".into(), builtin_char::INST),132			("encodeUTF8".into(), builtin_encode_utf8::INST),133			("decodeUTF8".into(), builtin_decode_utf8::INST),134			("md5".into(), builtin_md5::INST),135			("base64".into(), builtin_base64::INST),136			("base64DecodeBytes".into(), builtin_base64_decode_bytes::INST),137			("base64Decode".into(), builtin_base64_decode::INST),138			("trace".into(), builtin_trace::INST),139			("join".into(), builtin_join::INST),140			("escapeStringJson".into(), builtin_escape_string_json::INST),141			("manifestJsonEx".into(), builtin_manifest_json_ex::INST),142			("manifestYamlDoc".into(), builtin_manifest_yaml_doc::INST),143			("reverse".into(), builtin_reverse::INST),144			("id".into(), builtin_id::INST),145			("strReplace".into(), builtin_str_replace::INST),146			("splitLimit".into(), builtin_splitlimit::INST),147			("parseJson".into(), builtin_parse_json::INST),148			("parseYaml".into(), builtin_parse_yaml::INST),149			("asciiUpper".into(), builtin_ascii_upper::INST),150			("asciiLower".into(), builtin_ascii_lower::INST),151			("member".into(), builtin_member::INST),152			("count".into(), builtin_count::INST),153			("any".into(), builtin_any::INST),154			("all".into(), builtin_all::INST),155		].iter().cloned().collect()156	};157}158159#[jrsonnet_macros::builtin]160fn builtin_length(x: Either![IStr, ArrValue, ObjValue, FuncVal]) -> Result<usize> {161	use Either4::*;162	Ok(match x {163		A(x) => x.chars().count(),164		B(x) => x.len(),165		C(x) => x166			.fields_visibility()167			.into_iter()168			.filter(|(_k, v)| *v)169			.count(),170		D(f) => f.args_len(),171	})172}173174#[jrsonnet_macros::builtin]175fn builtin_type(x: Any) -> Result<IStr> {176	Ok(x.0.value_type().name().into())177}178179#[jrsonnet_macros::builtin]180fn builtin_make_array(sz: usize, func: FuncVal) -> Result<VecVal> {181	let mut out = Vec::with_capacity(sz);182	for i in 0..sz {183		out.push(func.evaluate_simple(&[i as f64].as_slice())?)184	}185	Ok(VecVal(Cc::new(out)))186}187188#[jrsonnet_macros::builtin]189const fn builtin_codepoint(str: char) -> Result<u32> {190	Ok(str as u32)191}192193#[jrsonnet_macros::builtin]194fn builtin_object_fields_ex(obj: ObjValue, inc_hidden: bool) -> Result<VecVal> {195	let out = obj.fields_ex(inc_hidden);196	Ok(VecVal(Cc::new(197		out.into_iter().map(Val::Str).collect::<Vec<_>>(),198	)))199}200201#[jrsonnet_macros::builtin]202fn builtin_object_has_ex(obj: ObjValue, f: IStr, inc_hidden: bool) -> Result<bool> {203	Ok(obj.has_field_ex(f, inc_hidden))204}205206#[jrsonnet_macros::builtin]207fn builtin_parse_json(s: IStr) -> Result<Any> {208	let value: serde_json::Value = serde_json::from_str(&s)209		.map_err(|e| RuntimeError(format!("failed to parse json: {}", e).into()))?;210	Ok(Any(Val::try_from(&value)?))211}212213#[jrsonnet_macros::builtin]214fn builtin_parse_yaml(s: IStr) -> Result<Any> {215	let value = serde_yaml::Deserializer::from_str_with_quirks(216		&s,217		DeserializingQuirks { old_octals: true },218	);219	let mut out = vec![];220	for item in value {221		let value = serde_json::Value::deserialize(item)222			.map_err(|e| RuntimeError(format!("failed to parse yaml: {}", e).into()))?;223		let val = Val::try_from(&value)?;224		out.push(val);225	}226	Ok(Any(if out.is_empty() {227		Val::Null228	} else if out.len() == 1 {229		out.into_iter().next().unwrap()230	} else {231		Val::Arr(out.into())232	}))233}234235#[jrsonnet_macros::builtin]236fn builtin_slice(237	indexable: IndexableVal,238	index: Option<BoundedUsize<0, { i32::MAX as usize }>>,239	end: Option<BoundedUsize<0, { i32::MAX as usize }>>,240	step: Option<BoundedUsize<1, { i32::MAX as usize }>>,241) -> Result<Any> {242	std_slice(indexable, index, end, step).map(Any)243}244245#[jrsonnet_macros::builtin]246fn builtin_substr(str: IStr, from: usize, len: usize) -> Result<String> {247	Ok(str.chars().skip(from as usize).take(len as usize).collect())248}249250#[jrsonnet_macros::builtin]251fn builtin_primitive_equals(a: Any, b: Any) -> Result<bool> {252	primitive_equals(&a.0, &b.0)253}254255#[jrsonnet_macros::builtin]256fn builtin_equals(a: Any, b: Any) -> Result<bool> {257	equals(&a.0, &b.0)258}259260#[jrsonnet_macros::builtin]261fn builtin_modulo(a: f64, b: f64) -> Result<f64> {262	Ok(a % b)263}264265#[jrsonnet_macros::builtin]266fn builtin_mod(a: Either![f64, IStr], b: Any) -> Result<Any> {267	use Either2::*;268	Ok(Any(evaluate_mod_op(269		&match a {270			A(v) => Val::Num(v),271			B(s) => Val::Str(s),272		},273		&b.0,274	)?))275}276277#[jrsonnet_macros::builtin]278fn builtin_floor(x: f64) -> Result<f64> {279	Ok(x.floor())280}281282#[jrsonnet_macros::builtin]283fn builtin_ceil(x: f64) -> Result<f64> {284	Ok(x.ceil())285}286287#[jrsonnet_macros::builtin]288fn builtin_log(n: f64) -> Result<f64> {289	Ok(n.ln())290}291292#[jrsonnet_macros::builtin]293fn builtin_pow(x: f64, n: f64) -> Result<f64> {294	Ok(x.powf(n))295}296297#[jrsonnet_macros::builtin]298fn builtin_sqrt(x: PositiveF64) -> Result<f64> {299	Ok(x.0.sqrt())300}301302#[jrsonnet_macros::builtin]303fn builtin_sin(x: f64) -> Result<f64> {304	Ok(x.sin())305}306307#[jrsonnet_macros::builtin]308fn builtin_cos(x: f64) -> Result<f64> {309	Ok(x.cos())310}311312#[jrsonnet_macros::builtin]313fn builtin_tan(x: f64) -> Result<f64> {314	Ok(x.tan())315}316317#[jrsonnet_macros::builtin]318fn builtin_asin(x: f64) -> Result<f64> {319	Ok(x.asin())320}321322#[jrsonnet_macros::builtin]323fn builtin_acos(x: f64) -> Result<f64> {324	Ok(x.acos())325}326327#[jrsonnet_macros::builtin]328fn builtin_atan(x: f64) -> Result<f64> {329	Ok(x.atan())330}331332#[jrsonnet_macros::builtin]333fn builtin_exp(x: f64) -> Result<f64> {334	Ok(x.exp())335}336337fn frexp(s: f64) -> (f64, i16) {338	if 0.0 == s {339		(s, 0)340	} else {341		let lg = s.abs().log2();342		let x = (lg - lg.floor() - 1.0).exp2();343		let exp = lg.floor() + 1.0;344		(s.signum() * x, exp as i16)345	}346}347348#[jrsonnet_macros::builtin]349fn builtin_mantissa(x: f64) -> Result<f64> {350	Ok(frexp(x).0)351}352353#[jrsonnet_macros::builtin]354fn builtin_exponent(x: f64) -> Result<i16> {355	Ok(frexp(x).1)356}357358#[jrsonnet_macros::builtin]359fn builtin_ext_var(x: IStr) -> Result<Any> {360	Ok(Any(with_state(|s| s.settings().ext_vars.get(&x).cloned())361		.ok_or(UndefinedExternalVariable(x))?))362}363364#[jrsonnet_macros::builtin]365fn builtin_native(name: IStr) -> Result<FuncVal> {366	Ok(with_state(|s| s.settings().ext_natives.get(&name).cloned())367		.map(|v| FuncVal::Builtin(v.clone()))368		.ok_or(UndefinedExternalFunction(name))?)369}370371#[jrsonnet_macros::builtin]372fn builtin_filter(func: FuncVal, arr: ArrValue) -> Result<ArrValue> {373	arr.filter(|val| bool::try_from(func.evaluate_simple(&[Any(val.clone())].as_slice())?))374}375376#[jrsonnet_macros::builtin]377fn builtin_map(func: FuncVal, arr: ArrValue) -> Result<ArrValue> {378	arr.map(|val| func.evaluate_simple(&[Any(val)].as_slice()))379}380381#[jrsonnet_macros::builtin]382fn builtin_flatmap(func: FuncVal, arr: IndexableVal) -> Result<IndexableVal> {383	match arr {384		IndexableVal::Str(s) => {385			let mut out = String::new();386			for c in s.chars() {387				match func.evaluate_simple(&[c.to_string()].as_slice())? {388					Val::Str(o) => out.push_str(&o),389					_ => throw!(RuntimeError(390						"in std.join all items should be strings".into()391					)),392				};393			}394			Ok(IndexableVal::Str(out.into()))395		}396		IndexableVal::Arr(a) => {397			let mut out = Vec::new();398			for el in a.iter() {399				let el = el?;400				match func.evaluate_simple(&[Any(el)].as_slice())? {401					Val::Arr(o) => {402						for oe in o.iter() {403							out.push(oe?)404						}405					}406					_ => throw!(RuntimeError(407						"in std.join all items should be arrays".into()408					)),409				};410			}411			Ok(IndexableVal::Arr(out.into()))412		}413	}414}415416#[jrsonnet_macros::builtin]417fn builtin_foldl(func: FuncVal, arr: ArrValue, init: Any) -> Result<Any> {418	let mut acc = init.0;419	for i in arr.iter() {420		acc = func.evaluate_simple(&[Any(acc), Any(i?)].as_slice())?;421	}422	Ok(Any(acc))423}424425#[jrsonnet_macros::builtin]426fn builtin_foldr(func: FuncVal, arr: ArrValue, init: Any) -> Result<Any> {427	let mut acc = init.0;428	for i in arr.iter().rev() {429		acc = func.evaluate_simple(&[Any(i?), Any(acc)].as_slice())?;430	}431	Ok(Any(acc))432}433434#[jrsonnet_macros::builtin]435#[allow(non_snake_case)]436fn builtin_sort(arr: ArrValue, keyF: Option<FuncVal>) -> Result<ArrValue> {437	if arr.len() <= 1 {438		return Ok(arr);439	}440	Ok(ArrValue::Eager(sort::sort(441		arr.evaluated()?,442		keyF.as_ref(),443	)?))444}445446#[jrsonnet_macros::builtin]447fn builtin_format(str: IStr, vals: Any) -> Result<String> {448	std_format(str, vals.0)449}450451#[jrsonnet_macros::builtin]452fn builtin_range(from: i32, to: i32) -> Result<ArrValue> {453	if to < from {454		return Ok(ArrValue::new_eager());455	}456	Ok(ArrValue::new_range(from, to))457}458459#[jrsonnet_macros::builtin]460fn builtin_char(n: u32) -> Result<char> {461	Ok(std::char::from_u32(n as u32).ok_or(InvalidUnicodeCodepointGot(n as u32))?)462}463464#[jrsonnet_macros::builtin]465fn builtin_encode_utf8(str: IStr) -> Result<Bytes> {466	Ok(Bytes(str.bytes().collect::<Vec<u8>>().into()))467}468469#[jrsonnet_macros::builtin]470fn builtin_decode_utf8(arr: Bytes) -> Result<IStr> {471	Ok(std::str::from_utf8(&arr.0)472		.map_err(|_| RuntimeError("bad utf8".into()))?473		.into())474}475476#[jrsonnet_macros::builtin]477fn builtin_md5(str: IStr) -> Result<String> {478	Ok(format!("{:x}", md5::compute(&str.as_bytes())))479}480481#[jrsonnet_macros::builtin]482fn builtin_trace(loc: CallLocation, str: IStr, rest: Any) -> Result<Any> {483	eprint!("TRACE:");484	if let Some(loc) = loc.0 {485		with_state(|s| {486			let locs = s.map_source_locations(&loc.0, &[loc.1]);487			eprint!(488				" {}:{}",489				loc.0.file_name().unwrap().to_str().unwrap(),490				locs[0].line491			);492		});493	}494	eprintln!(" {}", str);495	Ok(rest) as Result<Any>496}497498#[jrsonnet_macros::builtin]499fn builtin_base64(input: Either![Bytes, IStr]) -> Result<String> {500	use Either2::*;501	Ok(match input {502		A(a) => base64::encode(a.0),503		B(l) => base64::encode(l.bytes().collect::<Vec<_>>()),504	})505}506507#[jrsonnet_macros::builtin]508fn builtin_base64_decode_bytes(input: IStr) -> Result<Bytes> {509	Ok(Bytes(510		base64::decode(&input.as_bytes())511			.map_err(|_| RuntimeError("bad base64".into()))?512			.into(),513	))514}515516#[jrsonnet_macros::builtin]517fn builtin_base64_decode(input: IStr) -> Result<String> {518	let bytes = base64::decode(&input.as_bytes()).map_err(|_| RuntimeError("bad base64".into()))?;519	Ok(String::from_utf8(bytes).map_err(|_| RuntimeError("bad utf8".into()))?)520}521522#[jrsonnet_macros::builtin]523fn builtin_join(sep: IndexableVal, arr: ArrValue) -> Result<IndexableVal> {524	Ok(match sep {525		IndexableVal::Arr(joiner_items) => {526			let mut out = Vec::new();527528			let mut first = true;529			for item in arr.iter() {530				let item = item?.clone();531				if let Val::Arr(items) = item {532					if !first {533						out.reserve(joiner_items.len());534						// TODO: extend535						for item in joiner_items.iter() {536							out.push(item?);537						}538					}539					first = false;540					out.reserve(items.len());541					// TODO: extend542					for item in items.iter() {543						out.push(item?);544					}545				} else {546					throw!(RuntimeError(547						"in std.join all items should be arrays".into()548					));549				}550			}551552			IndexableVal::Arr(out.into())553		}554		IndexableVal::Str(sep) => {555			let mut out = String::new();556557			let mut first = true;558			for item in arr.iter() {559				let item = item?.clone();560				if let Val::Str(item) = item {561					if !first {562						out += &sep;563					}564					first = false;565					out += &item;566				} else {567					throw!(RuntimeError(568						"in std.join all items should be strings".into()569					));570				}571			}572573			IndexableVal::Str(out.into())574		}575	})576}577578#[jrsonnet_macros::builtin]579fn builtin_escape_string_json(str_: IStr) -> Result<String> {580	Ok(escape_string_json(&str_))581}582583#[jrsonnet_macros::builtin]584fn builtin_manifest_json_ex(585	value: Any,586	indent: IStr,587	newline: Option<IStr>,588	key_val_sep: Option<IStr>,589) -> Result<String> {590	let newline = newline.as_deref().unwrap_or("\n");591	let key_val_sep = key_val_sep.as_deref().unwrap_or(": ");592	manifest_json_ex(593		&value.0,594		&ManifestJsonOptions {595			padding: &indent,596			mtype: ManifestType::Std,597			newline,598			key_val_sep,599		},600	)601}602603#[jrsonnet_macros::builtin]604fn builtin_manifest_yaml_doc(605	value: Any,606	indent_array_in_object: Option<bool>,607	quote_keys: Option<bool>,608) -> Result<String> {609	manifest_yaml_ex(610		&value.0,611		&ManifestYamlOptions {612			padding: "  ",613			arr_element_padding: if indent_array_in_object.unwrap_or(false) {614				"  "615			} else {616				""617			},618			quote_keys: quote_keys.unwrap_or(true),619		},620	)621}622623#[jrsonnet_macros::builtin]624fn builtin_reverse(value: ArrValue) -> Result<ArrValue> {625	Ok(value.reversed())626}627628#[jrsonnet_macros::builtin]629const fn builtin_id(v: Any) -> Result<Any> {630	Ok(v)631}632633#[jrsonnet_macros::builtin]634fn builtin_str_replace(str: String, from: IStr, to: IStr) -> Result<String> {635	Ok(str.replace(&from as &str, &to as &str))636}637638#[jrsonnet_macros::builtin]639fn builtin_splitlimit(str: IStr, c: IStr, maxsplits: Either![usize, M1]) -> Result<VecVal> {640	use Either2::*;641	Ok(VecVal(Cc::new(match maxsplits {642		A(n) => str643			.splitn(n + 1, &c as &str)644			.map(|s| Val::Str(s.into()))645			.collect(),646		B(_) => str.split(&c as &str).map(|s| Val::Str(s.into())).collect(),647	})))648}649650#[jrsonnet_macros::builtin]651fn builtin_ascii_upper(str: IStr) -> Result<String> {652	Ok(str.to_ascii_uppercase())653}654655#[jrsonnet_macros::builtin]656fn builtin_ascii_lower(str: IStr) -> Result<String> {657	Ok(str.to_ascii_lowercase())658}659660#[jrsonnet_macros::builtin]661fn builtin_member(arr: IndexableVal, x: Any) -> Result<bool> {662	match arr {663		IndexableVal::Str(s) => {664			let x: IStr = IStr::try_from(x.0)?;665			Ok(!x.is_empty() && s.contains(&*x))666		}667		IndexableVal::Arr(a) => {668			for item in a.iter() {669				let item = item?;670				if equals(&item, &x.0)? {671					return Ok(true);672				}673			}674			Ok(false)675		}676	}677}678679#[jrsonnet_macros::builtin]680fn builtin_count(arr: Vec<Any>, v: Any) -> Result<usize> {681	let mut count = 0;682	for item in arr.iter() {683		if equals(&item.0, &v.0)? {684			count += 1;685		}686	}687	Ok(count)688}689690#[jrsonnet_macros::builtin]691fn builtin_any(arr: ArrValue) -> Result<bool> {692	for v in arr.iter() {693		let v: bool = v?.try_into()?;694		if v {695			return Ok(true);696		}697	}698	Ok(false)699}700701#[jrsonnet_macros::builtin]702fn builtin_all(arr: ArrValue) -> Result<bool> {703	for v in arr.iter() {704		let v: bool = v?.try_into()?;705		if !v {706			return Ok(false);707		}708	}709	Ok(true)710}
after · crates/jrsonnet-evaluator/src/builtin/mod.rs
1use std::{2	collections::HashMap,3	convert::{TryFrom, TryInto},4};56use format::{format_arr, format_obj};7use gcmodule::Cc;8use jrsonnet_interner::IStr;9use serde::Deserialize;10use serde_yaml::DeserializingQuirks;1112use crate::{13	builtin::manifest::{manifest_yaml_ex, ManifestYamlOptions},14	error::{Error::*, Result},15	function::{CallLocation, StaticBuiltin},16	operator::evaluate_mod_op,17	push_frame, throw,18	typed::{Any, BoundedUsize, Bytes, Either2, Either4, PositiveF64, VecVal, M1},19	val::{equals, primitive_equals, ArrValue, FuncVal, IndexableVal, Slice},20	with_state, Either, ObjValue, Val,21};2223pub mod stdlib;24pub use stdlib::*;2526use self::manifest::{escape_string_json, manifest_json_ex, ManifestJsonOptions, ManifestType};2728pub mod format;29pub mod manifest;30pub mod sort;3132pub fn std_format(str: IStr, vals: Val) -> Result<String> {33	push_frame(34		CallLocation::native(),35		|| format!("std.format of {}", str),36		|| {37			Ok(match vals {38				Val::Arr(vals) => format_arr(&str, &vals.evaluated()?)?,39				Val::Obj(obj) => format_obj(&str, &obj)?,40				o => format_arr(&str, &[o])?,41			})42		},43	)44}4546pub fn std_slice(47	indexable: IndexableVal,48	index: Option<BoundedUsize<0, { i32::MAX as usize }>>,49	end: Option<BoundedUsize<0, { i32::MAX as usize }>>,50	step: Option<BoundedUsize<1, { i32::MAX as usize }>>,51) -> Result<Val> {52	match &indexable {53		IndexableVal::Str(s) => {54			let index = index.as_deref().copied().unwrap_or(0);55			let end = end.as_deref().copied().unwrap_or(usize::MAX);56			let step = step.as_deref().copied().unwrap_or(1);5758			if index >= end {59				return Ok(Val::Str("".into()));60			}6162			Ok(Val::Str(63				(s.chars()64					.skip(index)65					.take(end - index)66					.step_by(step)67					.collect::<String>())68				.into(),69			))70		}71		IndexableVal::Arr(arr) => {72			let index = index.as_deref().copied().unwrap_or(0);73			let end = end.as_deref().copied().unwrap_or(usize::MAX).min(arr.len());74			let step = step.as_deref().copied().unwrap_or(1);7576			if index >= end {77				return Ok(Val::Arr(ArrValue::new_eager()));78			}7980			Ok(Val::Arr(ArrValue::Slice(Box::new(Slice {81				inner: arr.clone(),82				from: index as u32,83				to: end as u32,84				step: step as u32,85			}))))86		}87	}88}8990type BuiltinsType = HashMap<IStr, &'static dyn StaticBuiltin>;9192thread_local! {93	pub static BUILTINS: BuiltinsType = {94		[95			("length".into(), builtin_length::INST),96			("type".into(), builtin_type::INST),97			("makeArray".into(), builtin_make_array::INST),98			("codepoint".into(), builtin_codepoint::INST),99			("objectFieldsEx".into(), builtin_object_fields_ex::INST),100			("objectHasEx".into(), builtin_object_has_ex::INST),101			("slice".into(), builtin_slice::INST),102			("substr".into(), builtin_substr::INST),103			("primitiveEquals".into(), builtin_primitive_equals::INST),104			("equals".into(), builtin_equals::INST),105			("modulo".into(), builtin_modulo::INST),106			("mod".into(), builtin_mod::INST),107			("floor".into(), builtin_floor::INST),108			("ceil".into(), builtin_ceil::INST),109			("log".into(), builtin_log::INST),110			("pow".into(), builtin_pow::INST),111			("sqrt".into(), builtin_sqrt::INST),112			("sin".into(), builtin_sin::INST),113			("cos".into(), builtin_cos::INST),114			("tan".into(), builtin_tan::INST),115			("asin".into(), builtin_asin::INST),116			("acos".into(), builtin_acos::INST),117			("atan".into(), builtin_atan::INST),118			("exp".into(), builtin_exp::INST),119			("mantissa".into(), builtin_mantissa::INST),120			("exponent".into(), builtin_exponent::INST),121			("extVar".into(), builtin_ext_var::INST),122			("native".into(), builtin_native::INST),123			("filter".into(), builtin_filter::INST),124			("map".into(), builtin_map::INST),125			("flatMap".into(), builtin_flatmap::INST),126			("foldl".into(), builtin_foldl::INST),127			("foldr".into(), builtin_foldr::INST),128			("sort".into(), builtin_sort::INST),129			("format".into(), builtin_format::INST),130			("range".into(), builtin_range::INST),131			("char".into(), builtin_char::INST),132			("encodeUTF8".into(), builtin_encode_utf8::INST),133			("decodeUTF8".into(), builtin_decode_utf8::INST),134			("md5".into(), builtin_md5::INST),135			("base64".into(), builtin_base64::INST),136			("base64DecodeBytes".into(), builtin_base64_decode_bytes::INST),137			("base64Decode".into(), builtin_base64_decode::INST),138			("trace".into(), builtin_trace::INST),139			("join".into(), builtin_join::INST),140			("escapeStringJson".into(), builtin_escape_string_json::INST),141			("manifestJsonEx".into(), builtin_manifest_json_ex::INST),142			("manifestYamlDoc".into(), builtin_manifest_yaml_doc::INST),143			("reverse".into(), builtin_reverse::INST),144			("id".into(), builtin_id::INST),145			("strReplace".into(), builtin_str_replace::INST),146			("splitLimit".into(), builtin_splitlimit::INST),147			("parseJson".into(), builtin_parse_json::INST),148			("parseYaml".into(), builtin_parse_yaml::INST),149			("asciiUpper".into(), builtin_ascii_upper::INST),150			("asciiLower".into(), builtin_ascii_lower::INST),151			("member".into(), builtin_member::INST),152			("count".into(), builtin_count::INST),153			("any".into(), builtin_any::INST),154			("all".into(), builtin_all::INST),155		].iter().cloned().collect()156	};157}158159#[jrsonnet_macros::builtin]160fn builtin_length(x: Either![IStr, ArrValue, ObjValue, FuncVal]) -> Result<usize> {161	use Either4::*;162	Ok(match x {163		A(x) => x.chars().count(),164		B(x) => x.len(),165		C(x) => x.len(),166		D(f) => f.args_len(),167	})168}169170#[jrsonnet_macros::builtin]171fn builtin_type(x: Any) -> Result<IStr> {172	Ok(x.0.value_type().name().into())173}174175#[jrsonnet_macros::builtin]176fn builtin_make_array(sz: usize, func: FuncVal) -> Result<VecVal> {177	let mut out = Vec::with_capacity(sz);178	for i in 0..sz {179		out.push(func.evaluate_simple(&[i as f64].as_slice())?)180	}181	Ok(VecVal(Cc::new(out)))182}183184#[jrsonnet_macros::builtin]185const fn builtin_codepoint(str: char) -> Result<u32> {186	Ok(str as u32)187}188189#[jrsonnet_macros::builtin]190fn builtin_object_fields_ex(191	obj: ObjValue,192	inc_hidden: bool,193	#[cfg(feature = "exp-preserve-order")] preserve_order: Option<bool>,194) -> Result<VecVal> {195	#[cfg(not(feature = "exp-preserve-order"))]196	let preserve_order = false;197	#[cfg(feature = "exp-preserve-order")]198	let preserve_order = preserve_order.unwrap_or(false);199	let out = obj.fields_ex(200		inc_hidden,201		#[cfg(feature = "exp-preserve-order")]202		preserve_order,203	);204	Ok(VecVal(Cc::new(205		out.into_iter().map(Val::Str).collect::<Vec<_>>(),206	)))207}208209#[jrsonnet_macros::builtin]210fn builtin_object_has_ex(obj: ObjValue, f: IStr, inc_hidden: bool) -> Result<bool> {211	Ok(obj.has_field_ex(f, inc_hidden))212}213214#[jrsonnet_macros::builtin]215fn builtin_parse_json(s: IStr) -> Result<Any> {216	let value: serde_json::Value = serde_json::from_str(&s)217		.map_err(|e| RuntimeError(format!("failed to parse json: {}", e).into()))?;218	Ok(Any(Val::try_from(&value)?))219}220221#[jrsonnet_macros::builtin]222fn builtin_parse_yaml(s: IStr) -> Result<Any> {223	let value = serde_yaml::Deserializer::from_str_with_quirks(224		&s,225		DeserializingQuirks { old_octals: true },226	);227	let mut out = vec![];228	for item in value {229		let value = serde_json::Value::deserialize(item)230			.map_err(|e| RuntimeError(format!("failed to parse yaml: {}", e).into()))?;231		let val = Val::try_from(&value)?;232		out.push(val);233	}234	Ok(Any(if out.is_empty() {235		Val::Null236	} else if out.len() == 1 {237		out.into_iter().next().unwrap()238	} else {239		Val::Arr(out.into())240	}))241}242243#[jrsonnet_macros::builtin]244fn builtin_slice(245	indexable: IndexableVal,246	index: Option<BoundedUsize<0, { i32::MAX as usize }>>,247	end: Option<BoundedUsize<0, { i32::MAX as usize }>>,248	step: Option<BoundedUsize<1, { i32::MAX as usize }>>,249) -> Result<Any> {250	std_slice(indexable, index, end, step).map(Any)251}252253#[jrsonnet_macros::builtin]254fn builtin_substr(str: IStr, from: usize, len: usize) -> Result<String> {255	Ok(str.chars().skip(from as usize).take(len as usize).collect())256}257258#[jrsonnet_macros::builtin]259fn builtin_primitive_equals(a: Any, b: Any) -> Result<bool> {260	primitive_equals(&a.0, &b.0)261}262263#[jrsonnet_macros::builtin]264fn builtin_equals(a: Any, b: Any) -> Result<bool> {265	equals(&a.0, &b.0)266}267268#[jrsonnet_macros::builtin]269fn builtin_modulo(a: f64, b: f64) -> Result<f64> {270	Ok(a % b)271}272273#[jrsonnet_macros::builtin]274fn builtin_mod(a: Either![f64, IStr], b: Any) -> Result<Any> {275	use Either2::*;276	Ok(Any(evaluate_mod_op(277		&match a {278			A(v) => Val::Num(v),279			B(s) => Val::Str(s),280		},281		&b.0,282	)?))283}284285#[jrsonnet_macros::builtin]286fn builtin_floor(x: f64) -> Result<f64> {287	Ok(x.floor())288}289290#[jrsonnet_macros::builtin]291fn builtin_ceil(x: f64) -> Result<f64> {292	Ok(x.ceil())293}294295#[jrsonnet_macros::builtin]296fn builtin_log(n: f64) -> Result<f64> {297	Ok(n.ln())298}299300#[jrsonnet_macros::builtin]301fn builtin_pow(x: f64, n: f64) -> Result<f64> {302	Ok(x.powf(n))303}304305#[jrsonnet_macros::builtin]306fn builtin_sqrt(x: PositiveF64) -> Result<f64> {307	Ok(x.0.sqrt())308}309310#[jrsonnet_macros::builtin]311fn builtin_sin(x: f64) -> Result<f64> {312	Ok(x.sin())313}314315#[jrsonnet_macros::builtin]316fn builtin_cos(x: f64) -> Result<f64> {317	Ok(x.cos())318}319320#[jrsonnet_macros::builtin]321fn builtin_tan(x: f64) -> Result<f64> {322	Ok(x.tan())323}324325#[jrsonnet_macros::builtin]326fn builtin_asin(x: f64) -> Result<f64> {327	Ok(x.asin())328}329330#[jrsonnet_macros::builtin]331fn builtin_acos(x: f64) -> Result<f64> {332	Ok(x.acos())333}334335#[jrsonnet_macros::builtin]336fn builtin_atan(x: f64) -> Result<f64> {337	Ok(x.atan())338}339340#[jrsonnet_macros::builtin]341fn builtin_exp(x: f64) -> Result<f64> {342	Ok(x.exp())343}344345fn frexp(s: f64) -> (f64, i16) {346	if 0.0 == s {347		(s, 0)348	} else {349		let lg = s.abs().log2();350		let x = (lg - lg.floor() - 1.0).exp2();351		let exp = lg.floor() + 1.0;352		(s.signum() * x, exp as i16)353	}354}355356#[jrsonnet_macros::builtin]357fn builtin_mantissa(x: f64) -> Result<f64> {358	Ok(frexp(x).0)359}360361#[jrsonnet_macros::builtin]362fn builtin_exponent(x: f64) -> Result<i16> {363	Ok(frexp(x).1)364}365366#[jrsonnet_macros::builtin]367fn builtin_ext_var(x: IStr) -> Result<Any> {368	Ok(Any(with_state(|s| s.settings().ext_vars.get(&x).cloned())369		.ok_or(UndefinedExternalVariable(x))?))370}371372#[jrsonnet_macros::builtin]373fn builtin_native(name: IStr) -> Result<FuncVal> {374	Ok(with_state(|s| s.settings().ext_natives.get(&name).cloned())375		.map(|v| FuncVal::Builtin(v.clone()))376		.ok_or(UndefinedExternalFunction(name))?)377}378379#[jrsonnet_macros::builtin]380fn builtin_filter(func: FuncVal, arr: ArrValue) -> Result<ArrValue> {381	arr.filter(|val| bool::try_from(func.evaluate_simple(&[Any(val.clone())].as_slice())?))382}383384#[jrsonnet_macros::builtin]385fn builtin_map(func: FuncVal, arr: ArrValue) -> Result<ArrValue> {386	arr.map(|val| func.evaluate_simple(&[Any(val)].as_slice()))387}388389#[jrsonnet_macros::builtin]390fn builtin_flatmap(func: FuncVal, arr: IndexableVal) -> Result<IndexableVal> {391	match arr {392		IndexableVal::Str(s) => {393			let mut out = String::new();394			for c in s.chars() {395				match func.evaluate_simple(&[c.to_string()].as_slice())? {396					Val::Str(o) => out.push_str(&o),397					_ => throw!(RuntimeError(398						"in std.join all items should be strings".into()399					)),400				};401			}402			Ok(IndexableVal::Str(out.into()))403		}404		IndexableVal::Arr(a) => {405			let mut out = Vec::new();406			for el in a.iter() {407				let el = el?;408				match func.evaluate_simple(&[Any(el)].as_slice())? {409					Val::Arr(o) => {410						for oe in o.iter() {411							out.push(oe?)412						}413					}414					_ => throw!(RuntimeError(415						"in std.join all items should be arrays".into()416					)),417				};418			}419			Ok(IndexableVal::Arr(out.into()))420		}421	}422}423424#[jrsonnet_macros::builtin]425fn builtin_foldl(func: FuncVal, arr: ArrValue, init: Any) -> Result<Any> {426	let mut acc = init.0;427	for i in arr.iter() {428		acc = func.evaluate_simple(&[Any(acc), Any(i?)].as_slice())?;429	}430	Ok(Any(acc))431}432433#[jrsonnet_macros::builtin]434fn builtin_foldr(func: FuncVal, arr: ArrValue, init: Any) -> Result<Any> {435	let mut acc = init.0;436	for i in arr.iter().rev() {437		acc = func.evaluate_simple(&[Any(i?), Any(acc)].as_slice())?;438	}439	Ok(Any(acc))440}441442#[jrsonnet_macros::builtin]443#[allow(non_snake_case)]444fn builtin_sort(arr: ArrValue, keyF: Option<FuncVal>) -> Result<ArrValue> {445	if arr.len() <= 1 {446		return Ok(arr);447	}448	Ok(ArrValue::Eager(sort::sort(449		arr.evaluated()?,450		keyF.as_ref(),451	)?))452}453454#[jrsonnet_macros::builtin]455fn builtin_format(str: IStr, vals: Any) -> Result<String> {456	std_format(str, vals.0)457}458459#[jrsonnet_macros::builtin]460fn builtin_range(from: i32, to: i32) -> Result<ArrValue> {461	if to < from {462		return Ok(ArrValue::new_eager());463	}464	Ok(ArrValue::new_range(from, to))465}466467#[jrsonnet_macros::builtin]468fn builtin_char(n: u32) -> Result<char> {469	Ok(std::char::from_u32(n as u32).ok_or(InvalidUnicodeCodepointGot(n as u32))?)470}471472#[jrsonnet_macros::builtin]473fn builtin_encode_utf8(str: IStr) -> Result<Bytes> {474	Ok(Bytes(str.bytes().collect::<Vec<u8>>().into()))475}476477#[jrsonnet_macros::builtin]478fn builtin_decode_utf8(arr: Bytes) -> Result<IStr> {479	Ok(std::str::from_utf8(&arr.0)480		.map_err(|_| RuntimeError("bad utf8".into()))?481		.into())482}483484#[jrsonnet_macros::builtin]485fn builtin_md5(str: IStr) -> Result<String> {486	Ok(format!("{:x}", md5::compute(&str.as_bytes())))487}488489#[jrsonnet_macros::builtin]490fn builtin_trace(loc: CallLocation, str: IStr, rest: Any) -> Result<Any> {491	eprint!("TRACE:");492	if let Some(loc) = loc.0 {493		with_state(|s| {494			let locs = s.map_source_locations(&loc.0, &[loc.1]);495			eprint!(496				" {}:{}",497				loc.0.file_name().unwrap().to_str().unwrap(),498				locs[0].line499			);500		});501	}502	eprintln!(" {}", str);503	Ok(rest) as Result<Any>504}505506#[jrsonnet_macros::builtin]507fn builtin_base64(input: Either![Bytes, IStr]) -> Result<String> {508	use Either2::*;509	Ok(match input {510		A(a) => base64::encode(a.0),511		B(l) => base64::encode(l.bytes().collect::<Vec<_>>()),512	})513}514515#[jrsonnet_macros::builtin]516fn builtin_base64_decode_bytes(input: IStr) -> Result<Bytes> {517	Ok(Bytes(518		base64::decode(&input.as_bytes())519			.map_err(|_| RuntimeError("bad base64".into()))?520			.into(),521	))522}523524#[jrsonnet_macros::builtin]525fn builtin_base64_decode(input: IStr) -> Result<String> {526	let bytes = base64::decode(&input.as_bytes()).map_err(|_| RuntimeError("bad base64".into()))?;527	Ok(String::from_utf8(bytes).map_err(|_| RuntimeError("bad utf8".into()))?)528}529530#[jrsonnet_macros::builtin]531fn builtin_join(sep: IndexableVal, arr: ArrValue) -> Result<IndexableVal> {532	Ok(match sep {533		IndexableVal::Arr(joiner_items) => {534			let mut out = Vec::new();535536			let mut first = true;537			for item in arr.iter() {538				let item = item?.clone();539				if let Val::Arr(items) = item {540					if !first {541						out.reserve(joiner_items.len());542						// TODO: extend543						for item in joiner_items.iter() {544							out.push(item?);545						}546					}547					first = false;548					out.reserve(items.len());549					// TODO: extend550					for item in items.iter() {551						out.push(item?);552					}553				} else {554					throw!(RuntimeError(555						"in std.join all items should be arrays".into()556					));557				}558			}559560			IndexableVal::Arr(out.into())561		}562		IndexableVal::Str(sep) => {563			let mut out = String::new();564565			let mut first = true;566			for item in arr.iter() {567				let item = item?.clone();568				if let Val::Str(item) = item {569					if !first {570						out += &sep;571					}572					first = false;573					out += &item;574				} else {575					throw!(RuntimeError(576						"in std.join all items should be strings".into()577					));578				}579			}580581			IndexableVal::Str(out.into())582		}583	})584}585586#[jrsonnet_macros::builtin]587fn builtin_escape_string_json(str_: IStr) -> Result<String> {588	Ok(escape_string_json(&str_))589}590591#[jrsonnet_macros::builtin]592fn builtin_manifest_json_ex(593	value: Any,594	indent: IStr,595	newline: Option<IStr>,596	key_val_sep: Option<IStr>,597	#[cfg(feature = "exp-preserve-order")] preserve_order: Option<bool>,598) -> Result<String> {599	let newline = newline.as_deref().unwrap_or("\n");600	let key_val_sep = key_val_sep.as_deref().unwrap_or(": ");601	manifest_json_ex(602		&value.0,603		&ManifestJsonOptions {604			padding: &indent,605			mtype: ManifestType::Std,606			newline,607			key_val_sep,608			#[cfg(feature = "exp-preserve-order")]609			preserve_order: preserve_order.unwrap_or(false),610		},611	)612}613614#[jrsonnet_macros::builtin]615fn builtin_manifest_yaml_doc(616	value: Any,617	indent_array_in_object: Option<bool>,618	quote_keys: Option<bool>,619	#[cfg(feature = "exp-preserve-order")] preserve_order: Option<bool>,620) -> Result<String> {621	manifest_yaml_ex(622		&value.0,623		&ManifestYamlOptions {624			padding: "  ",625			arr_element_padding: if indent_array_in_object.unwrap_or(false) {626				"  "627			} else {628				""629			},630			quote_keys: quote_keys.unwrap_or(true),631			#[cfg(feature = "exp-preserve-order")]632			preserve_order: preserve_order.unwrap_or(false),633		},634	)635}636637#[jrsonnet_macros::builtin]638fn builtin_reverse(value: ArrValue) -> Result<ArrValue> {639	Ok(value.reversed())640}641642#[jrsonnet_macros::builtin]643const fn builtin_id(v: Any) -> Result<Any> {644	Ok(v)645}646647#[jrsonnet_macros::builtin]648fn builtin_str_replace(str: String, from: IStr, to: IStr) -> Result<String> {649	Ok(str.replace(&from as &str, &to as &str))650}651652#[jrsonnet_macros::builtin]653fn builtin_splitlimit(str: IStr, c: IStr, maxsplits: Either![usize, M1]) -> Result<VecVal> {654	use Either2::*;655	Ok(VecVal(Cc::new(match maxsplits {656		A(n) => str657			.splitn(n + 1, &c as &str)658			.map(|s| Val::Str(s.into()))659			.collect(),660		B(_) => str.split(&c as &str).map(|s| Val::Str(s.into())).collect(),661	})))662}663664#[jrsonnet_macros::builtin]665fn builtin_ascii_upper(str: IStr) -> Result<String> {666	Ok(str.to_ascii_uppercase())667}668669#[jrsonnet_macros::builtin]670fn builtin_ascii_lower(str: IStr) -> Result<String> {671	Ok(str.to_ascii_lowercase())672}673674#[jrsonnet_macros::builtin]675fn builtin_member(arr: IndexableVal, x: Any) -> Result<bool> {676	match arr {677		IndexableVal::Str(s) => {678			let x: IStr = IStr::try_from(x.0)?;679			Ok(!x.is_empty() && s.contains(&*x))680		}681		IndexableVal::Arr(a) => {682			for item in a.iter() {683				let item = item?;684				if equals(&item, &x.0)? {685					return Ok(true);686				}687			}688			Ok(false)689		}690	}691}692693#[jrsonnet_macros::builtin]694fn builtin_count(arr: Vec<Any>, v: Any) -> Result<usize> {695	let mut count = 0;696	for item in arr.iter() {697		if equals(&item.0, &v.0)? {698			count += 1;699		}700	}701	Ok(count)702}703704#[jrsonnet_macros::builtin]705fn builtin_any(arr: ArrValue) -> Result<bool> {706	for v in arr.iter() {707		let v: bool = v?.try_into()?;708		if v {709			return Ok(true);710		}711	}712	Ok(false)713}714715#[jrsonnet_macros::builtin]716fn builtin_all(arr: ArrValue) -> Result<bool> {717	for v in arr.iter() {718		let v: bool = v?.try_into()?;719		if !v {720			return Ok(false);721		}722	}723	Ok(true)724}
modifiedcrates/jrsonnet-evaluator/src/integrations/serde.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/integrations/serde.rs
+++ b/crates/jrsonnet-evaluator/src/integrations/serde.rs
@@ -28,7 +28,10 @@
 			}
 			Val::Obj(o) => {
 				let mut out = Map::new();
-				for key in o.fields() {
+				for key in o.fields(
+					#[cfg(feature = "exp-preserve-order")]
+					cfg!(feature = "exp-serde-preserve-order"),
+				) {
 					out.insert(
 						(&key as &str).into(),
 						o.get(key)?
modifiedcrates/jrsonnet-evaluator/src/lib.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/lib.rs
+++ b/crates/jrsonnet-evaluator/src/lib.rs
@@ -100,7 +100,11 @@
 			ext_natives: Default::default(),
 			tla_vars: Default::default(),
 			import_resolver: Box::new(DummyImportResolver),
-			manifest_format: ManifestFormat::Json(4),
+			manifest_format: ManifestFormat::Json {
+				padding: 4,
+				#[cfg(feature = "exp-preserve-order")]
+				preserve_order: false,
+			},
 			trace_format: Box::new(CompactFormat {
 				padding: 4,
 				resolver: trace::PathResolver::Absolute,
modifiedcrates/jrsonnet-evaluator/src/obj.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/obj.rs
+++ b/crates/jrsonnet-evaluator/src/obj.rs
@@ -18,10 +18,82 @@
 	push_frame, throw, weak_ptr_eq, weak_raw, Bindable, LazyBinding, LazyVal, Result, Val,
 };
 
+#[cfg(not(feature = "exp-preserve-order"))]
+pub(crate) mod ordering {
+	use gcmodule::Trace;
+
+	#[derive(Clone, Copy, Default, Debug, Trace)]
+	pub struct FieldIndex;
+	impl FieldIndex {
+		pub fn next(self) -> Self {
+			Self
+		}
+	}
+
+	#[derive(Clone, Copy, Default, Debug, Trace)]
+	pub struct SuperDepth;
+	impl SuperDepth {
+		pub fn deeper(self) -> Self {
+			Self
+		}
+	}
+
+	#[derive(Clone, Copy)]
+	pub struct FieldSortKey;
+	impl FieldSortKey {
+		pub fn new(_: SuperDepth, _: FieldIndex) -> Self {
+			Self
+		}
+	}
+}
+
+#[cfg(feature = "exp-preserve-order")]
+mod ordering {
+	use std::cmp::Reverse;
+
+	use gcmodule::Trace;
+
+	#[derive(Clone, Copy, Default, Debug, Trace, PartialEq, Eq, PartialOrd, Ord)]
+	pub struct FieldIndex(u32);
+	impl FieldIndex {
+		pub fn next(self) -> Self {
+			Self(self.0 + 1)
+		}
+	}
+
+	#[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Debug)]
+	pub struct SuperDepth(u32);
+	impl SuperDepth {
+		pub fn deeper(self) -> Self {
+			Self(self.0 + 1)
+		}
+	}
+
+	#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
+	pub struct FieldSortKey(Reverse<SuperDepth>, FieldIndex);
+	impl FieldSortKey {
+		pub fn new(depth: SuperDepth, index: FieldIndex) -> Self {
+			Self(Reverse(depth), index)
+		}
+		pub fn collide(self, other: Self) -> Self {
+			if self.0 .0 > other.0 .0 {
+				self
+			} else if self.0 .0 < other.0 .0 {
+				other
+			} else {
+				unreachable!("object can't have two fields with same name")
+			}
+		}
+	}
+}
+
+pub(crate) use ordering::*;
+
 #[derive(Debug, Trace)]
 pub struct ObjMember {
 	pub add: bool,
 	pub visibility: Visibility,
+	original_index: FieldIndex,
 	pub invoke: LazyBinding,
 	pub location: Option<ExprLocation>,
 }
@@ -120,6 +192,14 @@
 			),
 		}
 	}
+	pub(crate) fn extend_with_raw_member(self, key: IStr, value: ObjMember) -> Self {
+		let mut new = GcHashMap::with_capacity(1);
+		new.insert(key, value);
+		Self::new(Some(self), Cc::new(new), Cc::new(Vec::new()))
+	}
+	pub fn extend_field(&mut self, name: IStr) -> ObjMemberBuilder<ExtendBuilder> {
+		ObjMemberBuilder::new(ExtendBuilder(self), name, FieldIndex::default())
+	}
 	pub fn with_this(&self, this_obj: Self) -> Self {
 		Self(Cc::new(ObjValueInternals {
 			super_obj: self.0.super_obj.clone(),
@@ -131,6 +211,13 @@
 		}))
 	}
 
+	pub fn len(&self) -> usize {
+		self.fields_visibility()
+			.into_iter()
+			.filter(|(_, (visible, _))| *visible)
+			.count()
+	}
+
 	pub fn is_empty(&self) -> bool {
 		if !self.0.this_entries.is_empty() {
 			return false;
@@ -143,51 +230,93 @@
 	}
 
 	/// Run callback for every field found in object
-	pub(crate) fn enum_fields(&self, handler: &mut impl FnMut(&IStr, &ObjMember) -> bool) -> bool {
+	pub(crate) fn enum_fields(
+		&self,
+		depth: SuperDepth,
+		handler: &mut impl FnMut(SuperDepth, &IStr, &ObjMember) -> bool,
+	) -> bool {
 		if let Some(s) = &self.0.super_obj {
-			if s.enum_fields(handler) {
+			if s.enum_fields(depth.deeper(), handler) {
 				return true;
 			}
 		}
 		for (name, member) in self.0.this_entries.iter() {
-			if handler(name, member) {
+			if handler(depth, name, member) {
 				return true;
 			}
 		}
 		false
 	}
 
-	pub fn fields_visibility(&self) -> FxHashMap<IStr, bool> {
+	pub fn fields_visibility(&self) -> FxHashMap<IStr, (bool, FieldSortKey)> {
 		let mut out = FxHashMap::default();
-		self.enum_fields(&mut |name, member| {
+		self.enum_fields(SuperDepth::default(), &mut |depth, name, member| {
+			let new_sort_key = FieldSortKey::new(depth, member.original_index);
 			match member.visibility {
 				Visibility::Normal => {
 					let entry = out.entry(name.to_owned());
-					entry.or_insert(true);
+					let v = entry.or_insert((true, new_sort_key));
+					v.1 = new_sort_key;
 				}
 				Visibility::Hidden => {
-					out.insert(name.to_owned(), false);
+					out.insert(name.to_owned(), (false, new_sort_key));
 				}
 				Visibility::Unhide => {
-					out.insert(name.to_owned(), true);
+					out.insert(name.to_owned(), (true, new_sort_key));
 				}
 			};
 			false
 		});
 		out
 	}
-	pub fn fields_ex(&self, include_hidden: bool) -> Vec<IStr> {
+	pub fn fields_ex(
+		&self,
+		include_hidden: bool,
+		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,
+	) -> Vec<IStr> {
+		#[cfg(feature = "exp-preserve-order")]
+		if preserve_order {
+			let (mut fields, mut keys): (Vec<_>, Vec<_>) = self
+				.fields_visibility()
+				.into_iter()
+				.filter(|(_, (visible, _))| include_hidden || *visible)
+				.enumerate()
+				.map(|(idx, (k, (_, sk)))| (k, (sk, idx)))
+				.unzip();
+			keys.sort_unstable_by_key(|v| v.0);
+			// Reorder in-place by resulting indexes
+			for i in 0..fields.len() {
+				let x = fields[i].clone();
+				let mut j = i;
+				loop {
+					let k = keys[j].1;
+					keys[j].1 = j;
+					if k == i {
+						break;
+					}
+					fields[j] = fields[k].clone();
+					j = k
+				}
+				fields[j] = x;
+			}
+			return fields;
+		}
+
 		let mut fields: Vec<_> = self
 			.fields_visibility()
 			.into_iter()
-			.filter(|(_k, v)| include_hidden || *v)
+			.filter(|(_, (visible, _))| include_hidden || *visible)
 			.map(|(k, _)| k)
 			.collect();
 		fields.sort_unstable();
 		fields
 	}
-	pub fn fields(&self) -> Vec<IStr> {
-		self.fields_ex(false)
+	pub fn fields(&self, #[cfg(feature = "exp-preserve-order")] preserve_order: bool) -> Vec<IStr> {
+		self.fields_ex(
+			false,
+			#[cfg(feature = "exp-preserve-order")]
+			preserve_order,
+		)
 	}
 
 	pub fn field_visibility(&self, name: IStr) -> Option<Visibility> {
@@ -236,11 +365,7 @@
 		self.get_raw(key, self.0.this_obj.as_ref())
 	}
 
-	pub fn extend_with_field(self, key: IStr, value: ObjMember) -> Self {
-		let mut new = GcHashMap::with_capacity(1);
-		new.insert(key, value);
-		Self::new(Some(self), Cc::new(new), Cc::new(Vec::new()))
-	}
+	// pub fn extend_with(self, key: )
 
 	fn get_raw(&self, key: IStr, real_this: Option<&Self>) -> Result<Option<Val>> {
 		let real_this = real_this.unwrap_or(self);
@@ -339,6 +464,7 @@
 	super_obj: Option<ObjValue>,
 	map: GcHashMap<IStr, ObjMember>,
 	assertions: Vec<TraceBox<dyn ObjectAssertion>>,
+	next_field_index: FieldIndex,
 }
 impl ObjValueBuilder {
 	pub fn new() -> Self {
@@ -349,6 +475,7 @@
 			super_obj: None,
 			map: GcHashMap::with_capacity(capacity),
 			assertions: Vec::new(),
+			next_field_index: FieldIndex::default(),
 		}
 	}
 	pub fn reserve_asserts(&mut self, capacity: usize) -> &mut Self {
@@ -364,14 +491,10 @@
 		self.assertions.push(assertion);
 		self
 	}
-	pub fn member(&mut self, name: IStr) -> ObjMemberBuilder {
-		ObjMemberBuilder {
-			value: self,
-			name,
-			add: false,
-			visibility: Visibility::Normal,
-			location: None,
-		}
+	pub fn member(&mut self, name: IStr) -> ObjMemberBuilder<ValueBuilder> {
+		let field_index = self.next_field_index;
+		self.next_field_index = self.next_field_index.next();
+		ObjMemberBuilder::new(ValueBuilder(self), name, field_index)
 	}
 
 	pub fn build(self) -> ObjValue {
@@ -385,16 +508,28 @@
 }
 
 #[must_use = "value not added unless binding() was called"]
-pub struct ObjMemberBuilder<'v> {
-	value: &'v mut ObjValueBuilder,
+pub struct ObjMemberBuilder<Kind> {
+	kind: Kind,
 	name: IStr,
 	add: bool,
 	visibility: Visibility,
+	original_index: FieldIndex,
 	location: Option<ExprLocation>,
 }
 
 #[allow(clippy::missing_const_for_fn)]
-impl<'v> ObjMemberBuilder<'v> {
+impl<Kind> ObjMemberBuilder<Kind> {
+	pub(crate) fn new(kind: Kind, name: IStr, original_index: FieldIndex) -> Self {
+		Self {
+			kind,
+			name,
+			original_index,
+			add: false,
+			visibility: Visibility::Normal,
+			location: None,
+		}
+	}
+
 	pub const fn with_add(mut self, add: bool) -> Self {
 		self.add = add;
 		self
@@ -413,6 +548,23 @@
 		self.location = Some(location);
 		self
 	}
+	fn build_member(self, binding: LazyBinding) -> (Kind, IStr, ObjMember) {
+		(
+			self.kind,
+			self.name,
+			ObjMember {
+				add: self.add,
+				visibility: self.visibility,
+				original_index: self.original_index,
+				invoke: binding,
+				location: self.location,
+			},
+		)
+	}
+}
+
+pub struct ValueBuilder<'v>(&'v mut ObjValueBuilder);
+impl<'v> ObjMemberBuilder<ValueBuilder<'v>> {
 	pub fn value(self, value: Val) -> Result<()> {
 		self.binding(LazyBinding::Bound(LazyVal::new_resolved(value)))
 	}
@@ -420,22 +572,31 @@
 		self.binding(LazyBinding::Bindable(Cc::new(bindable)))
 	}
 	pub fn binding(self, binding: LazyBinding) -> Result<()> {
-		let old = self.value.map.insert(
-			self.name.clone(),
-			ObjMember {
-				add: self.add,
-				visibility: self.visibility,
-				invoke: binding,
-				location: self.location.clone(),
-			},
-		);
+		let (receiver, name, member) = self.build_member(binding);
+		let location = member.location.clone();
+		let old = receiver.0.map.insert(name.clone(), member);
 		if old.is_some() {
 			push_frame(
-				CallLocation(self.location.as_ref()),
-				|| format!("field <{}> initializtion", self.name.clone()),
-				|| throw!(DuplicateFieldName(self.name.clone())),
+				CallLocation(location.as_ref()),
+				|| format!("field <{}> initializtion", name.clone()),
+				|| throw!(DuplicateFieldName(name.clone())),
 			)?
 		}
 		Ok(())
 	}
 }
+
+pub struct ExtendBuilder<'v>(&'v mut ObjValue);
+impl<'v> ObjMemberBuilder<ExtendBuilder<'v>> {
+	pub fn value(self, value: Val) {
+		self.binding(LazyBinding::Bound(LazyVal::new_resolved(value)))
+	}
+	pub fn bindable(self, bindable: TraceBox<dyn Bindable>) {
+		self.binding(LazyBinding::Bindable(Cc::new(bindable)))
+	}
+	pub fn binding(self, binding: LazyBinding) -> () {
+		let (receiver, name, member) = self.build_member(binding);
+		let new = receiver.0.clone();
+		*receiver.0 = new.extend_with_raw_member(name, member)
+	}
+}
modifiedcrates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/val.rs
+++ b/crates/jrsonnet-evaluator/src/val.rs
@@ -167,11 +167,31 @@
 #[derive(Clone)]
 pub enum ManifestFormat {
 	YamlStream(Box<ManifestFormat>),
-	Yaml(usize),
-	Json(usize),
+	Yaml {
+		padding: usize,
+		#[cfg(feature = "exp-preserve-order")]
+		preserve_order: bool,
+	},
+	Json {
+		padding: usize,
+		#[cfg(feature = "exp-preserve-order")]
+		preserve_order: bool,
+	},
 	ToString,
 	String,
 }
+impl ManifestFormat {
+	#[cfg(feature = "exp-preserve-order")]
+	fn preserve_order(&self) -> bool {
+		match self {
+			ManifestFormat::YamlStream(s) => s.preserve_order(),
+			ManifestFormat::Yaml { preserve_order, .. } => *preserve_order,
+			ManifestFormat::Json { preserve_order, .. } => *preserve_order,
+			ManifestFormat::ToString => false,
+			ManifestFormat::String => false,
+		}
+	}
+}
 
 #[derive(Debug, Clone, Trace)]
 pub struct Slice {
@@ -559,6 +579,8 @@
 					mtype: ManifestType::ToString,
 					newline: "\n",
 					key_val_sep: ": ",
+					#[cfg(feature = "exp-preserve-order")]
+					preserve_order: false,
 				},
 			)?
 			.into(),
@@ -571,7 +593,10 @@
 			Self::Obj(obj) => obj,
 			_ => throw!(MultiManifestOutputIsNotAObject),
 		};
-		let keys = obj.fields();
+		let keys = obj.fields(
+			#[cfg(feature = "exp-preserve-order")]
+			ty.preserve_order(),
+		);
 		let mut out = Vec::with_capacity(keys.len());
 		for key in keys {
 			let value = obj
@@ -622,8 +647,24 @@
 
 				out.into()
 			}
-			ManifestFormat::Yaml(padding) => self.to_yaml(*padding)?,
-			ManifestFormat::Json(padding) => self.to_json(*padding)?,
+			ManifestFormat::Yaml {
+				padding,
+				#[cfg(feature = "exp-preserve-order")]
+				preserve_order,
+			} => self.to_yaml(
+				*padding,
+				#[cfg(feature = "exp-preserve-order")]
+				*preserve_order,
+			)?,
+			ManifestFormat::Json {
+				padding,
+				#[cfg(feature = "exp-preserve-order")]
+				preserve_order,
+			} => self.to_json(
+				*padding,
+				#[cfg(feature = "exp-preserve-order")]
+				*preserve_order,
+			)?,
 			ManifestFormat::ToString => self.to_string()?,
 			ManifestFormat::String => match self {
 				Self::Str(s) => s.clone(),
@@ -633,7 +674,11 @@
 	}
 
 	/// For manifestification
-	pub fn to_json(&self, padding: usize) -> Result<IStr> {
+	pub fn to_json(
+		&self,
+		padding: usize,
+		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,
+	) -> Result<IStr> {
 		manifest_json_ex(
 			self,
 			&ManifestJsonOptions {
@@ -645,13 +690,19 @@
 				},
 				newline: "\n",
 				key_val_sep: ": ",
+				#[cfg(feature = "exp-preserve-order")]
+				preserve_order,
 			},
 		)
 		.map(|s| s.into())
 	}
 
 	/// Calls `std.manifestJson`
-	pub fn to_std_json(&self, padding: usize) -> Result<Rc<str>> {
+	pub fn to_std_json(
+		&self,
+		padding: usize,
+		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,
+	) -> Result<Rc<str>> {
 		manifest_json_ex(
 			self,
 			&ManifestJsonOptions {
@@ -659,12 +710,18 @@
 				mtype: ManifestType::Std,
 				newline: "\n",
 				key_val_sep: ": ",
+				#[cfg(feature = "exp-preserve-order")]
+				preserve_order,
 			},
 		)
 		.map(|s| s.into())
 	}
 
-	pub fn to_yaml(&self, padding: usize) -> Result<IStr> {
+	pub fn to_yaml(
+		&self,
+		padding: usize,
+		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,
+	) -> Result<IStr> {
 		let padding = &" ".repeat(padding);
 		manifest_yaml_ex(
 			self,
@@ -672,6 +729,8 @@
 				padding,
 				arr_element_padding: padding,
 				quote_keys: false,
+				#[cfg(feature = "exp-preserve-order")]
+				preserve_order,
 			},
 		)
 		.map(|s| s.into())
@@ -733,8 +792,15 @@
 			if ObjValue::ptr_eq(a, b) {
 				return Ok(true);
 			}
-			let fields = a.fields();
-			if fields != b.fields() {
+			let fields = a.fields(
+				#[cfg(feature = "exp-preserve-order")]
+				false,
+			);
+			if fields
+				!= b.fields(
+					#[cfg(feature = "exp-preserve-order")]
+					false,
+				) {
 				return Ok(false);
 			}
 			for field in fields {
modifiedcrates/jrsonnet-macros/src/lib.rsdiffbeforeafterboth
--- a/crates/jrsonnet-macros/src/lib.rs
+++ b/crates/jrsonnet-macros/src/lib.rs
@@ -122,6 +122,7 @@
 		ty: Box<Type>,
 		is_option: bool,
 		name: String,
+		cfg_attrs: Vec<Attribute>,
 		// ident: Ident,
 	},
 	Lazy {
@@ -134,20 +135,15 @@
 
 impl ArgInfo {
 	fn parse(arg: &FnArg) -> Result<Self> {
-		let typed = match arg {
+		let arg = match arg {
 			FnArg::Receiver(_) => unreachable!(),
 			FnArg::Typed(a) => a,
 		};
-		let ident = match &typed.pat as &Pat {
+		let ident = match &arg.pat as &Pat {
 			Pat::Ident(i) => i.ident.clone(),
-			_ => {
-				return Err(Error::new(
-					typed.pat.span(),
-					"arg should be plain identifier",
-				))
-			}
+			_ => return Err(Error::new(arg.pat.span(), "arg should be plain identifier")),
 		};
-		let ty = &typed.ty;
+		let ty = &arg.ty;
 		if type_is_path(ty, "CallLocation").is_some() {
 			return Ok(Self::Location);
 		} else if type_is_path(ty, "Self").is_some() {
@@ -172,11 +168,18 @@
 			(false, ty.clone())
 		};
 
+		let cfg_attrs = arg
+			.attrs
+			.iter()
+			.filter(|a| a.path.is_ident("cfg"))
+			.cloned()
+			.collect();
+
 		Ok(Self::Normal {
 			ty,
 			is_option,
 			name: ident.to_string(),
-			// ident,
+			cfg_attrs,
 		})
 	}
 }
@@ -215,13 +218,22 @@
 
 	let params_desc = args.iter().flat_map(|a| match a {
 		ArgInfo::Normal {
-			is_option, name, ..
-		}
-		| ArgInfo::Lazy { is_option, name } => Some(quote! {
+			is_option,
+			name,
+			cfg_attrs,
+			..
+		} => Some(quote! {
+			#(#cfg_attrs)*
+			BuiltinParam {
+				name: std::borrow::Cow::Borrowed(#name),
+				has_default: #is_option,
+			},
+		}),
+		ArgInfo::Lazy { is_option, name } => Some(quote! {
 			BuiltinParam {
 				name: std::borrow::Cow::Borrowed(#name),
 				has_default: #is_option,
-			}
+			},
 		}),
 		ArgInfo::Location => None,
 		ArgInfo::This => None,
@@ -232,23 +244,27 @@
 			ty,
 			is_option,
 			name,
-			// ident,
+			cfg_attrs,
 		} => {
 			let eval = quote! {::jrsonnet_evaluator::push_description_frame(
 				|| format!("argument <{}> evaluation", #name),
 				|| <#ty>::try_from(value.evaluate()?),
 			)?};
-			if *is_option {
+			let value = if *is_option {
 				quote! {if let Some(value) = parsed.get(#name) {
 					Some(#eval)
 				} else {
 					None
-				}}
+				},}
 			} else {
 				quote! {{
 					let value = parsed.get(#name).expect("args shape is checked");
 					#eval
-				}}
+				},}
+			};
+			quote! {
+				#(#cfg_attrs)*
+				#value
 			}
 		}
 		ArgInfo::Lazy { is_option, name } => {
@@ -260,12 +276,12 @@
 				}}
 			} else {
 				quote! {
-					parsed.get(#name).expect("args shape is correct").clone()
+					parsed.get(#name).expect("args shape is correct").clone(),
 				}
 			}
 		}
-		ArgInfo::Location => quote! {location},
-		ArgInfo::This => quote! {self},
+		ArgInfo::Location => quote! {location,},
+		ArgInfo::This => quote! {self,},
 	});
 
 	let fields = attr.fields.iter().map(|field| {
@@ -309,7 +325,7 @@
 				parser::ExprLocation,
 			};
 			const PARAMS: &'static [BuiltinParam] = &[
-				#(#params_desc),*
+				#(#params_desc)*
 			];
 
 			#static_ext
@@ -326,7 +342,7 @@
 				fn call(&self, context: Context, location: CallLocation, args: &dyn ArgsLike) -> Result<Val> {
 					let parsed = parse_builtin_call(context, &PARAMS, args, false)?;
 
-					let result: #result = #name(#(#pass),*);
+					let result: #result = #name(#(#pass)*);
 					let result = result?;
 					result.try_into()
 				}