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
--- a/crates/jrsonnet-evaluator/src/builtin/mod.rs
+++ b/crates/jrsonnet-evaluator/src/builtin/mod.rs
@@ -162,11 +162,7 @@
 	Ok(match x {
 		A(x) => x.chars().count(),
 		B(x) => x.len(),
-		C(x) => x
-			.fields_visibility()
-			.into_iter()
-			.filter(|(_k, v)| *v)
-			.count(),
+		C(x) => x.len(),
 		D(f) => f.args_len(),
 	})
 }
@@ -191,8 +187,20 @@
 }
 
 #[jrsonnet_macros::builtin]
-fn builtin_object_fields_ex(obj: ObjValue, inc_hidden: bool) -> Result<VecVal> {
-	let out = obj.fields_ex(inc_hidden);
+fn builtin_object_fields_ex(
+	obj: ObjValue,
+	inc_hidden: bool,
+	#[cfg(feature = "exp-preserve-order")] preserve_order: Option<bool>,
+) -> Result<VecVal> {
+	#[cfg(not(feature = "exp-preserve-order"))]
+	let preserve_order = false;
+	#[cfg(feature = "exp-preserve-order")]
+	let preserve_order = preserve_order.unwrap_or(false);
+	let out = obj.fields_ex(
+		inc_hidden,
+		#[cfg(feature = "exp-preserve-order")]
+		preserve_order,
+	);
 	Ok(VecVal(Cc::new(
 		out.into_iter().map(Val::Str).collect::<Vec<_>>(),
 	)))
@@ -586,6 +594,7 @@
 	indent: IStr,
 	newline: Option<IStr>,
 	key_val_sep: Option<IStr>,
+	#[cfg(feature = "exp-preserve-order")] preserve_order: Option<bool>,
 ) -> Result<String> {
 	let newline = newline.as_deref().unwrap_or("\n");
 	let key_val_sep = key_val_sep.as_deref().unwrap_or(": ");
@@ -596,6 +605,8 @@
 			mtype: ManifestType::Std,
 			newline,
 			key_val_sep,
+			#[cfg(feature = "exp-preserve-order")]
+			preserve_order: preserve_order.unwrap_or(false),
 		},
 	)
 }
@@ -605,6 +616,7 @@
 	value: Any,
 	indent_array_in_object: Option<bool>,
 	quote_keys: Option<bool>,
+	#[cfg(feature = "exp-preserve-order")] preserve_order: Option<bool>,
 ) -> Result<String> {
 	manifest_yaml_ex(
 		&value.0,
@@ -616,6 +628,8 @@
 				""
 			},
 			quote_keys: quote_keys.unwrap_or(true),
+			#[cfg(feature = "exp-preserve-order")]
+			preserve_order: preserve_order.unwrap_or(false),
 		},
 	)
 }
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
before · crates/jrsonnet-evaluator/src/obj.rs
1use std::{2	cell::RefCell,3	fmt::Debug,4	hash::{Hash, Hasher},5};67use gcmodule::{Cc, Trace, Weak};8use jrsonnet_interner::IStr;9use jrsonnet_parser::{ExprLocation, Visibility};10use rustc_hash::FxHashMap;1112use crate::{13	cc_ptr_eq,14	error::{Error::*, LocError},15	function::CallLocation,16	gc::{GcHashMap, GcHashSet, TraceBox},17	operator::evaluate_add_op,18	push_frame, throw, weak_ptr_eq, weak_raw, Bindable, LazyBinding, LazyVal, Result, Val,19};2021#[derive(Debug, Trace)]22pub struct ObjMember {23	pub add: bool,24	pub visibility: Visibility,25	pub invoke: LazyBinding,26	pub location: Option<ExprLocation>,27}2829pub trait ObjectAssertion: Trace {30	fn run(&self, this: Option<ObjValue>, super_obj: Option<ObjValue>) -> Result<()>;31}3233// Field => This34type CacheKey = (IStr, WeakObjValue);3536#[derive(Trace)]37enum CacheValue {38	Cached(Val),39	NotFound,40	Pending,41	Errored(LocError),42}4344#[derive(Trace)]45#[force_tracking]46pub struct ObjValueInternals {47	super_obj: Option<ObjValue>,48	assertions: Cc<Vec<TraceBox<dyn ObjectAssertion>>>,49	assertions_ran: RefCell<GcHashSet<ObjValue>>,50	this_obj: Option<ObjValue>,51	this_entries: Cc<GcHashMap<IStr, ObjMember>>,52	value_cache: RefCell<GcHashMap<CacheKey, CacheValue>>,53}5455#[derive(Clone, Trace)]56pub struct WeakObjValue(#[skip_trace] pub(crate) Weak<ObjValueInternals>);5758impl PartialEq for WeakObjValue {59	fn eq(&self, other: &Self) -> bool {60		weak_ptr_eq(self.0.clone(), other.0.clone())61	}62}6364impl Eq for WeakObjValue {}65impl Hash for WeakObjValue {66	fn hash<H: Hasher>(&self, hasher: &mut H) {67		hasher.write_usize(weak_raw(self.0.clone()) as usize)68	}69}7071#[derive(Clone, Trace)]72pub struct ObjValue(pub(crate) Cc<ObjValueInternals>);73impl Debug for ObjValue {74	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {75		if let Some(super_obj) = self.0.super_obj.as_ref() {76			if f.alternate() {77				write!(f, "{:#?}", super_obj)?;78			} else {79				write!(f, "{:?}", super_obj)?;80			}81			write!(f, " + ")?;82		}83		let mut debug = f.debug_struct("ObjValue");84		for (name, member) in self.0.this_entries.iter() {85			debug.field(name, member);86		}87		debug.finish_non_exhaustive()88	}89}9091impl ObjValue {92	pub fn new(93		super_obj: Option<Self>,94		this_entries: Cc<GcHashMap<IStr, ObjMember>>,95		assertions: Cc<Vec<TraceBox<dyn ObjectAssertion>>>,96	) -> Self {97		Self(Cc::new(ObjValueInternals {98			super_obj,99			assertions,100			assertions_ran: RefCell::new(GcHashSet::new()),101			this_obj: None,102			this_entries,103			value_cache: RefCell::new(GcHashMap::new()),104		}))105	}106	pub fn new_empty() -> Self {107		Self::new(None, Cc::new(GcHashMap::new()), Cc::new(Vec::new()))108	}109	pub fn extend_from(&self, super_obj: Self) -> Self {110		match &self.0.super_obj {111			None => Self::new(112				Some(super_obj),113				self.0.this_entries.clone(),114				self.0.assertions.clone(),115			),116			Some(v) => Self::new(117				Some(v.extend_from(super_obj)),118				self.0.this_entries.clone(),119				self.0.assertions.clone(),120			),121		}122	}123	pub fn with_this(&self, this_obj: Self) -> Self {124		Self(Cc::new(ObjValueInternals {125			super_obj: self.0.super_obj.clone(),126			assertions: self.0.assertions.clone(),127			assertions_ran: RefCell::new(GcHashSet::new()),128			this_obj: Some(this_obj),129			this_entries: self.0.this_entries.clone(),130			value_cache: RefCell::new(GcHashMap::new()),131		}))132	}133134	pub fn is_empty(&self) -> bool {135		if !self.0.this_entries.is_empty() {136			return false;137		}138		self.0139			.super_obj140			.as_ref()141			.map(|s| s.is_empty())142			.unwrap_or(true)143	}144145	/// Run callback for every field found in object146	pub(crate) fn enum_fields(&self, handler: &mut impl FnMut(&IStr, &ObjMember) -> bool) -> bool {147		if let Some(s) = &self.0.super_obj {148			if s.enum_fields(handler) {149				return true;150			}151		}152		for (name, member) in self.0.this_entries.iter() {153			if handler(name, member) {154				return true;155			}156		}157		false158	}159160	pub fn fields_visibility(&self) -> FxHashMap<IStr, bool> {161		let mut out = FxHashMap::default();162		self.enum_fields(&mut |name, member| {163			match member.visibility {164				Visibility::Normal => {165					let entry = out.entry(name.to_owned());166					entry.or_insert(true);167				}168				Visibility::Hidden => {169					out.insert(name.to_owned(), false);170				}171				Visibility::Unhide => {172					out.insert(name.to_owned(), true);173				}174			};175			false176		});177		out178	}179	pub fn fields_ex(&self, include_hidden: bool) -> Vec<IStr> {180		let mut fields: Vec<_> = self181			.fields_visibility()182			.into_iter()183			.filter(|(_k, v)| include_hidden || *v)184			.map(|(k, _)| k)185			.collect();186		fields.sort_unstable();187		fields188	}189	pub fn fields(&self) -> Vec<IStr> {190		self.fields_ex(false)191	}192193	pub fn field_visibility(&self, name: IStr) -> Option<Visibility> {194		if let Some(m) = self.0.this_entries.get(&name) {195			Some(match &m.visibility {196				Visibility::Normal => self197					.0198					.super_obj199					.as_ref()200					.and_then(|super_obj| super_obj.field_visibility(name))201					.unwrap_or(Visibility::Normal),202				v => *v,203			})204		} else if let Some(super_obj) = &self.0.super_obj {205			super_obj.field_visibility(name)206		} else {207			None208		}209	}210211	fn has_field_include_hidden(&self, name: IStr) -> bool {212		if self.0.this_entries.contains_key(&name) {213			true214		} else if let Some(super_obj) = &self.0.super_obj {215			super_obj.has_field_include_hidden(name)216		} else {217			false218		}219	}220221	pub fn has_field_ex(&self, name: IStr, include_hidden: bool) -> bool {222		if include_hidden {223			self.has_field_include_hidden(name)224		} else {225			self.has_field(name)226		}227	}228	pub fn has_field(&self, name: IStr) -> bool {229		self.field_visibility(name)230			.map(|v| v.is_visible())231			.unwrap_or(false)232	}233234	pub fn get(&self, key: IStr) -> Result<Option<Val>> {235		self.run_assertions()?;236		self.get_raw(key, self.0.this_obj.as_ref())237	}238239	pub fn extend_with_field(self, key: IStr, value: ObjMember) -> Self {240		let mut new = GcHashMap::with_capacity(1);241		new.insert(key, value);242		Self::new(Some(self), Cc::new(new), Cc::new(Vec::new()))243	}244245	fn get_raw(&self, key: IStr, real_this: Option<&Self>) -> Result<Option<Val>> {246		let real_this = real_this.unwrap_or(self);247		let cache_key = (key.clone(), WeakObjValue(real_this.0.downgrade()));248249		if let Some(v) = self.0.value_cache.borrow().get(&cache_key) {250			return Ok(match v {251				CacheValue::Cached(v) => Some(v.clone()),252				CacheValue::NotFound => None,253				CacheValue::Pending => throw!(InfiniteRecursionDetected),254				CacheValue::Errored(e) => return Err(e.clone()),255			});256		}257		self.0258			.value_cache259			.borrow_mut()260			.insert(cache_key.clone(), CacheValue::Pending);261		let value = match (self.0.this_entries.get(&key), &self.0.super_obj) {262			(Some(k), None) => Ok(Some(self.evaluate_this(k, real_this)?)),263			(Some(k), Some(s)) => {264				let our = self.evaluate_this(k, real_this)?;265				if k.add {266					s.get_raw(key, Some(real_this))?267						.map_or(Ok(Some(our.clone())), |v| {268							Ok(Some(evaluate_add_op(&v, &our)?))269						})270				} else {271					Ok(Some(our))272				}273			}274			(None, Some(s)) => s.get_raw(key, Some(real_this)),275			(None, None) => Ok(None),276		};277		let value = match value {278			Ok(v) => v,279			Err(e) => {280				self.0281					.value_cache282					.borrow_mut()283					.insert(cache_key, CacheValue::Errored(e.clone()));284				return Err(e);285			}286		};287		self.0.value_cache.borrow_mut().insert(288			cache_key,289			match &value {290				Some(v) => CacheValue::Cached(v.clone()),291				None => CacheValue::NotFound,292			},293		);294		Ok(value)295	}296	fn evaluate_this(&self, v: &ObjMember, real_this: &Self) -> Result<Val> {297		v.invoke298			.evaluate(Some(real_this.clone()), self.0.super_obj.clone())?299			.evaluate()300	}301302	fn run_assertions_raw(&self, real_this: &Self) -> Result<()> {303		if self.0.assertions_ran.borrow_mut().insert(real_this.clone()) {304			for assertion in self.0.assertions.iter() {305				if let Err(e) = assertion.run(Some(real_this.clone()), self.0.super_obj.clone()) {306					self.0.assertions_ran.borrow_mut().remove(real_this);307					return Err(e);308				}309			}310			if let Some(super_obj) = &self.0.super_obj {311				super_obj.run_assertions_raw(real_this)?;312			}313		}314		Ok(())315	}316	pub fn run_assertions(&self) -> Result<()> {317		self.run_assertions_raw(self)318	}319320	pub fn ptr_eq(a: &Self, b: &Self) -> bool {321		cc_ptr_eq(&a.0, &b.0)322	}323}324325impl PartialEq for ObjValue {326	fn eq(&self, other: &Self) -> bool {327		cc_ptr_eq(&self.0, &other.0)328	}329}330331impl Eq for ObjValue {}332impl Hash for ObjValue {333	fn hash<H: Hasher>(&self, hasher: &mut H) {334		hasher.write_usize(&*self.0 as *const _ as usize)335	}336}337338pub struct ObjValueBuilder {339	super_obj: Option<ObjValue>,340	map: GcHashMap<IStr, ObjMember>,341	assertions: Vec<TraceBox<dyn ObjectAssertion>>,342}343impl ObjValueBuilder {344	pub fn new() -> Self {345		Self::with_capacity(0)346	}347	pub fn with_capacity(capacity: usize) -> Self {348		Self {349			super_obj: None,350			map: GcHashMap::with_capacity(capacity),351			assertions: Vec::new(),352		}353	}354	pub fn reserve_asserts(&mut self, capacity: usize) -> &mut Self {355		self.assertions.reserve_exact(capacity);356		self357	}358	pub fn with_super(&mut self, super_obj: ObjValue) -> &mut Self {359		self.super_obj = Some(super_obj);360		self361	}362363	pub fn assert(&mut self, assertion: TraceBox<dyn ObjectAssertion>) -> &mut Self {364		self.assertions.push(assertion);365		self366	}367	pub fn member(&mut self, name: IStr) -> ObjMemberBuilder {368		ObjMemberBuilder {369			value: self,370			name,371			add: false,372			visibility: Visibility::Normal,373			location: None,374		}375	}376377	pub fn build(self) -> ObjValue {378		ObjValue::new(self.super_obj, Cc::new(self.map), Cc::new(self.assertions))379	}380}381impl Default for ObjValueBuilder {382	fn default() -> Self {383		Self::with_capacity(0)384	}385}386387#[must_use = "value not added unless binding() was called"]388pub struct ObjMemberBuilder<'v> {389	value: &'v mut ObjValueBuilder,390	name: IStr,391	add: bool,392	visibility: Visibility,393	location: Option<ExprLocation>,394}395396#[allow(clippy::missing_const_for_fn)]397impl<'v> ObjMemberBuilder<'v> {398	pub const fn with_add(mut self, add: bool) -> Self {399		self.add = add;400		self401	}402	pub fn add(self) -> Self {403		self.with_add(true)404	}405	pub fn with_visibility(mut self, visibility: Visibility) -> Self {406		self.visibility = visibility;407		self408	}409	pub fn hide(self) -> Self {410		self.with_visibility(Visibility::Hidden)411	}412	pub fn with_location(mut self, location: ExprLocation) -> Self {413		self.location = Some(location);414		self415	}416	pub fn value(self, value: Val) -> Result<()> {417		self.binding(LazyBinding::Bound(LazyVal::new_resolved(value)))418	}419	pub fn bindable(self, bindable: TraceBox<dyn Bindable>) -> Result<()> {420		self.binding(LazyBinding::Bindable(Cc::new(bindable)))421	}422	pub fn binding(self, binding: LazyBinding) -> Result<()> {423		let old = self.value.map.insert(424			self.name.clone(),425			ObjMember {426				add: self.add,427				visibility: self.visibility,428				invoke: binding,429				location: self.location.clone(),430			},431		);432		if old.is_some() {433			push_frame(434				CallLocation(self.location.as_ref()),435				|| format!("field <{}> initializtion", self.name.clone()),436				|| throw!(DuplicateFieldName(self.name.clone())),437			)?438		}439		Ok(())440	}441}
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()
 				}