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
before · bindings/jsonnet/src/lib.rs
1#[cfg(feature = "interop")]2pub mod interop;34pub mod import;5pub mod native;6pub mod val_extract;7pub mod val_make;8pub mod val_modify;9pub mod vars_tlas;1011use std::{12	alloc::Layout,13	ffi::{CStr, CString},14	os::raw::{c_char, c_double, c_int, c_uint},15	path::PathBuf,16};1718use import::NativeImportResolver;19use jrsonnet_evaluator::{EvaluationState, IStr, ManifestFormat, Val};2021/// WASM stub22#[cfg(target_arch = "wasm32")]23#[no_mangle]24pub extern "C" fn _start() {}2526#[no_mangle]27pub extern "C" fn jsonnet_version() -> &'static [u8; 8] {28	b"v0.16.0\0"29}3031#[no_mangle]32pub extern "C" fn jsonnet_make() -> *mut EvaluationState {33	let state = EvaluationState::default();34	state.with_stdlib();35	state.settings_mut().import_resolver = Box::new(NativeImportResolver::default());36	Box::into_raw(Box::new(state))37}3839/// # Safety40#[no_mangle]41#[allow(clippy::boxed_local)]42pub unsafe extern "C" fn jsonnet_destroy(vm: *mut EvaluationState) {43	Box::from_raw(vm);44}4546#[no_mangle]47pub extern "C" fn jsonnet_max_stack(vm: &EvaluationState, v: c_uint) {48	vm.settings_mut().max_stack = v as usize;49}5051// jrsonnet currently have no GC, so these functions is no-op52#[no_mangle]53pub extern "C" fn jsonnet_gc_min_objects(_vm: &EvaluationState, _v: c_uint) {}54#[no_mangle]55pub extern "C" fn jsonnet_gc_growth_trigger(_vm: &EvaluationState, _v: c_double) {}5657#[no_mangle]58pub extern "C" fn jsonnet_string_output(vm: &EvaluationState, v: c_int) {59	match v {60		1 => vm.set_manifest_format(ManifestFormat::String),61		0 => vm.set_manifest_format(ManifestFormat::Json(4)),62		_ => panic!("incorrect output format"),63	}64}6566/// # Safety67///68/// This function is most definitely broken, but it works somehow, see TODO inside69#[no_mangle]70pub unsafe extern "C" fn jsonnet_realloc(71	_vm: &EvaluationState,72	buf: *mut u8,73	sz: usize,74) -> *mut u8 {75	if buf.is_null() {76		assert!(sz != 0);77		return std::alloc::alloc(Layout::from_size_align(sz, std::mem::align_of::<u8>()).unwrap());78	}79	// TODO: Somehow store size of allocation, because its real size is probally not 16 :D80	// OR (Alternative way of fixing this TODO)81	// TODO: Standard allocator uses malloc, and it doesn't uses allocation size,82	// TODO: so it should work in normal cases. Maybe force allocator for this library?83	let old_layout = Layout::from_size_align(16, std::mem::align_of::<u8>()).unwrap();84	if sz == 0 {85		std::alloc::dealloc(buf, old_layout);86		return std::ptr::null_mut();87	}88	std::alloc::realloc(buf, old_layout, sz)89}9091/// # Safety92#[no_mangle]93#[allow(clippy::boxed_local)]94pub unsafe extern "C" fn jsonnet_json_destroy(_vm: &EvaluationState, v: *mut Val) {95	Box::from_raw(v);96}9798#[no_mangle]99pub extern "C" fn jsonnet_max_trace(vm: &EvaluationState, v: c_uint) {100	vm.set_max_trace(v as usize)101}102103/// # Safety104///105/// This function is safe, if received v is a pointer to normal C string106#[no_mangle]107pub unsafe extern "C" fn jsonnet_evaluate_file(108	vm: &EvaluationState,109	filename: *const c_char,110	error: &mut c_int,111) -> *const c_char {112	vm.run_in_state(|| {113		let filename = CStr::from_ptr(filename);114		match vm115			.evaluate_file_raw_nocwd(&PathBuf::from(filename.to_str().unwrap()))116			.and_then(|v| vm.with_tla(v))117			.and_then(|v| vm.manifest(v))118		{119			Ok(v) => {120				*error = 0;121				CString::new(&*v as &str).unwrap().into_raw()122			}123			Err(e) => {124				*error = 1;125				let out = vm.stringify_err(&e);126				CString::new(&out as &str).unwrap().into_raw()127			}128		}129	})130}131132/// # Safety133///134/// This function is safe, if received v is a pointer to normal C string135#[no_mangle]136pub unsafe extern "C" fn jsonnet_evaluate_snippet(137	vm: &EvaluationState,138	filename: *const c_char,139	snippet: *const c_char,140	error: &mut c_int,141) -> *const c_char {142	vm.run_in_state(|| {143		let filename = CStr::from_ptr(filename);144		let snippet = CStr::from_ptr(snippet);145		match vm146			.evaluate_snippet_raw(147				PathBuf::from(filename.to_str().unwrap()).into(),148				snippet.to_str().unwrap().into(),149			)150			.and_then(|v| vm.with_tla(v))151			.and_then(|v| vm.manifest(v))152		{153			Ok(v) => {154				*error = 0;155				CString::new(&*v as &str).unwrap().into_raw()156			}157			Err(e) => {158				*error = 1;159				let out = vm.stringify_err(&e);160				CString::new(&out as &str).unwrap().into_raw()161			}162		}163	})164}165166fn multi_to_raw(multi: Vec<(IStr, IStr)>) -> *const c_char {167	let mut out = Vec::new();168	for (i, (k, v)) in multi.iter().enumerate() {169		if i != 0 {170			out.push(0);171		}172		out.extend_from_slice(k.as_bytes());173		out.push(0);174		out.extend_from_slice(v.as_bytes());175	}176	out.push(0);177	out.push(0);178	let v = out.as_ptr();179	std::mem::forget(out);180	v as *const c_char181}182183/// # Safety184#[no_mangle]185pub unsafe extern "C" fn jsonnet_evaluate_file_multi(186	vm: &EvaluationState,187	filename: *const c_char,188	error: &mut c_int,189) -> *const c_char {190	vm.run_in_state(|| {191		let filename = CStr::from_ptr(filename);192		match vm193			.evaluate_file_raw_nocwd(&PathBuf::from(filename.to_str().unwrap()))194			.and_then(|v| vm.with_tla(v))195			.and_then(|v| vm.manifest_multi(v))196		{197			Ok(v) => {198				*error = 0;199				multi_to_raw(v)200			}201			Err(e) => {202				*error = 1;203				let out = vm.stringify_err(&e);204				CString::new(&out as &str).unwrap().into_raw()205			}206		}207	})208}209210/// # Safety211#[no_mangle]212pub unsafe extern "C" fn jsonnet_evaluate_snippet_multi(213	vm: &EvaluationState,214	filename: *const c_char,215	snippet: *const c_char,216	error: &mut c_int,217) -> *const c_char {218	vm.run_in_state(|| {219		let filename = CStr::from_ptr(filename);220		let snippet = CStr::from_ptr(snippet);221		match vm222			.evaluate_snippet_raw(223				PathBuf::from(filename.to_str().unwrap()).into(),224				snippet.to_str().unwrap().into(),225			)226			.and_then(|v| vm.with_tla(v))227			.and_then(|v| vm.manifest_multi(v))228		{229			Ok(v) => {230				*error = 0;231				multi_to_raw(v)232			}233			Err(e) => {234				*error = 1;235				let out = vm.stringify_err(&e);236				CString::new(&out as &str).unwrap().into_raw()237			}238		}239	})240}241242fn stream_to_raw(multi: Vec<IStr>) -> *const c_char {243	let mut out = Vec::new();244	for (i, v) in multi.iter().enumerate() {245		if i != 0 {246			out.push(0);247		}248		out.extend_from_slice(v.as_bytes());249	}250	out.push(0);251	out.push(0);252	let v = out.as_ptr();253	std::mem::forget(out);254	v as *const c_char255}256257/// # Safety258#[no_mangle]259pub unsafe extern "C" fn jsonnet_evaluate_file_stream(260	vm: &EvaluationState,261	filename: *const c_char,262	error: &mut c_int,263) -> *const c_char {264	vm.run_in_state(|| {265		let filename = CStr::from_ptr(filename);266		match vm267			.evaluate_file_raw_nocwd(&PathBuf::from(filename.to_str().unwrap()))268			.and_then(|v| vm.with_tla(v))269			.and_then(|v| vm.manifest_stream(v))270		{271			Ok(v) => {272				*error = 0;273				stream_to_raw(v)274			}275			Err(e) => {276				*error = 1;277				let out = vm.stringify_err(&e);278				CString::new(&out as &str).unwrap().into_raw()279			}280		}281	})282}283284/// # Safety285#[no_mangle]286pub unsafe extern "C" fn jsonnet_evaluate_snippet_stream(287	vm: &EvaluationState,288	filename: *const c_char,289	snippet: *const c_char,290	error: &mut c_int,291) -> *const c_char {292	vm.run_in_state(|| {293		let filename = CStr::from_ptr(filename);294		let snippet = CStr::from_ptr(snippet);295		match vm296			.evaluate_snippet_raw(297				PathBuf::from(filename.to_str().unwrap()).into(),298				snippet.to_str().unwrap().into(),299			)300			.and_then(|v| vm.with_tla(v))301			.and_then(|v| vm.manifest_stream(v))302		{303			Ok(v) => {304				*error = 0;305				stream_to_raw(v)306			}307			Err(e) => {308				*error = 1;309				let out = vm.stringify_err(&e);310				CString::new(&out as &str).unwrap().into_raw()311			}312		}313	})314}
after · bindings/jsonnet/src/lib.rs
1#[cfg(feature = "interop")]2pub mod interop;34pub mod import;5pub mod native;6pub mod val_extract;7pub mod val_make;8pub mod val_modify;9pub mod vars_tlas;1011use std::{12	alloc::Layout,13	ffi::{CStr, CString},14	os::raw::{c_char, c_double, c_int, c_uint},15	path::PathBuf,16};1718use import::NativeImportResolver;19use jrsonnet_evaluator::{EvaluationState, IStr, ManifestFormat, Val};2021/// WASM stub22#[cfg(target_arch = "wasm32")]23#[no_mangle]24pub extern "C" fn _start() {}2526#[no_mangle]27pub extern "C" fn jsonnet_version() -> &'static [u8; 8] {28	b"v0.16.0\0"29}3031#[no_mangle]32pub extern "C" fn jsonnet_make() -> *mut EvaluationState {33	let state = EvaluationState::default();34	state.with_stdlib();35	state.settings_mut().import_resolver = Box::new(NativeImportResolver::default());36	Box::into_raw(Box::new(state))37}3839/// # Safety40#[no_mangle]41#[allow(clippy::boxed_local)]42pub unsafe extern "C" fn jsonnet_destroy(vm: *mut EvaluationState) {43	Box::from_raw(vm);44}4546#[no_mangle]47pub extern "C" fn jsonnet_max_stack(vm: &EvaluationState, v: c_uint) {48	vm.settings_mut().max_stack = v as usize;49}5051// jrsonnet currently have no GC, so these functions is no-op52#[no_mangle]53pub extern "C" fn jsonnet_gc_min_objects(_vm: &EvaluationState, _v: c_uint) {}54#[no_mangle]55pub extern "C" fn jsonnet_gc_growth_trigger(_vm: &EvaluationState, _v: c_double) {}5657#[no_mangle]58pub extern "C" fn jsonnet_string_output(vm: &EvaluationState, v: c_int) {59	match v {60		1 => vm.set_manifest_format(ManifestFormat::String),61		0 => vm.set_manifest_format(ManifestFormat::Json {62			padding: 4,63			#[cfg(feature = "exp-preserve-order")]64			preserve_order: false,65		}),66		_ => panic!("incorrect output format"),67	}68}6970/// # Safety71///72/// This function is most definitely broken, but it works somehow, see TODO inside73#[no_mangle]74pub unsafe extern "C" fn jsonnet_realloc(75	_vm: &EvaluationState,76	buf: *mut u8,77	sz: usize,78) -> *mut u8 {79	if buf.is_null() {80		assert!(sz != 0);81		return std::alloc::alloc(Layout::from_size_align(sz, std::mem::align_of::<u8>()).unwrap());82	}83	// TODO: Somehow store size of allocation, because its real size is probally not 16 :D84	// OR (Alternative way of fixing this TODO)85	// TODO: Standard allocator uses malloc, and it doesn't uses allocation size,86	// TODO: so it should work in normal cases. Maybe force allocator for this library?87	let old_layout = Layout::from_size_align(16, std::mem::align_of::<u8>()).unwrap();88	if sz == 0 {89		std::alloc::dealloc(buf, old_layout);90		return std::ptr::null_mut();91	}92	std::alloc::realloc(buf, old_layout, sz)93}9495/// # Safety96#[no_mangle]97#[allow(clippy::boxed_local)]98pub unsafe extern "C" fn jsonnet_json_destroy(_vm: &EvaluationState, v: *mut Val) {99	Box::from_raw(v);100}101102#[no_mangle]103pub extern "C" fn jsonnet_max_trace(vm: &EvaluationState, v: c_uint) {104	vm.set_max_trace(v as usize)105}106107/// # Safety108///109/// This function is safe, if received v is a pointer to normal C string110#[no_mangle]111pub unsafe extern "C" fn jsonnet_evaluate_file(112	vm: &EvaluationState,113	filename: *const c_char,114	error: &mut c_int,115) -> *const c_char {116	vm.run_in_state(|| {117		let filename = CStr::from_ptr(filename);118		match vm119			.evaluate_file_raw_nocwd(&PathBuf::from(filename.to_str().unwrap()))120			.and_then(|v| vm.with_tla(v))121			.and_then(|v| vm.manifest(v))122		{123			Ok(v) => {124				*error = 0;125				CString::new(&*v as &str).unwrap().into_raw()126			}127			Err(e) => {128				*error = 1;129				let out = vm.stringify_err(&e);130				CString::new(&out as &str).unwrap().into_raw()131			}132		}133	})134}135136/// # Safety137///138/// This function is safe, if received v is a pointer to normal C string139#[no_mangle]140pub unsafe extern "C" fn jsonnet_evaluate_snippet(141	vm: &EvaluationState,142	filename: *const c_char,143	snippet: *const c_char,144	error: &mut c_int,145) -> *const c_char {146	vm.run_in_state(|| {147		let filename = CStr::from_ptr(filename);148		let snippet = CStr::from_ptr(snippet);149		match vm150			.evaluate_snippet_raw(151				PathBuf::from(filename.to_str().unwrap()).into(),152				snippet.to_str().unwrap().into(),153			)154			.and_then(|v| vm.with_tla(v))155			.and_then(|v| vm.manifest(v))156		{157			Ok(v) => {158				*error = 0;159				CString::new(&*v as &str).unwrap().into_raw()160			}161			Err(e) => {162				*error = 1;163				let out = vm.stringify_err(&e);164				CString::new(&out as &str).unwrap().into_raw()165			}166		}167	})168}169170fn multi_to_raw(multi: Vec<(IStr, IStr)>) -> *const c_char {171	let mut out = Vec::new();172	for (i, (k, v)) in multi.iter().enumerate() {173		if i != 0 {174			out.push(0);175		}176		out.extend_from_slice(k.as_bytes());177		out.push(0);178		out.extend_from_slice(v.as_bytes());179	}180	out.push(0);181	out.push(0);182	let v = out.as_ptr();183	std::mem::forget(out);184	v as *const c_char185}186187/// # Safety188#[no_mangle]189pub unsafe extern "C" fn jsonnet_evaluate_file_multi(190	vm: &EvaluationState,191	filename: *const c_char,192	error: &mut c_int,193) -> *const c_char {194	vm.run_in_state(|| {195		let filename = CStr::from_ptr(filename);196		match vm197			.evaluate_file_raw_nocwd(&PathBuf::from(filename.to_str().unwrap()))198			.and_then(|v| vm.with_tla(v))199			.and_then(|v| vm.manifest_multi(v))200		{201			Ok(v) => {202				*error = 0;203				multi_to_raw(v)204			}205			Err(e) => {206				*error = 1;207				let out = vm.stringify_err(&e);208				CString::new(&out as &str).unwrap().into_raw()209			}210		}211	})212}213214/// # Safety215#[no_mangle]216pub unsafe extern "C" fn jsonnet_evaluate_snippet_multi(217	vm: &EvaluationState,218	filename: *const c_char,219	snippet: *const c_char,220	error: &mut c_int,221) -> *const c_char {222	vm.run_in_state(|| {223		let filename = CStr::from_ptr(filename);224		let snippet = CStr::from_ptr(snippet);225		match vm226			.evaluate_snippet_raw(227				PathBuf::from(filename.to_str().unwrap()).into(),228				snippet.to_str().unwrap().into(),229			)230			.and_then(|v| vm.with_tla(v))231			.and_then(|v| vm.manifest_multi(v))232		{233			Ok(v) => {234				*error = 0;235				multi_to_raw(v)236			}237			Err(e) => {238				*error = 1;239				let out = vm.stringify_err(&e);240				CString::new(&out as &str).unwrap().into_raw()241			}242		}243	})244}245246fn stream_to_raw(multi: Vec<IStr>) -> *const c_char {247	let mut out = Vec::new();248	for (i, v) in multi.iter().enumerate() {249		if i != 0 {250			out.push(0);251		}252		out.extend_from_slice(v.as_bytes());253	}254	out.push(0);255	out.push(0);256	let v = out.as_ptr();257	std::mem::forget(out);258	v as *const c_char259}260261/// # Safety262#[no_mangle]263pub unsafe extern "C" fn jsonnet_evaluate_file_stream(264	vm: &EvaluationState,265	filename: *const c_char,266	error: &mut c_int,267) -> *const c_char {268	vm.run_in_state(|| {269		let filename = CStr::from_ptr(filename);270		match vm271			.evaluate_file_raw_nocwd(&PathBuf::from(filename.to_str().unwrap()))272			.and_then(|v| vm.with_tla(v))273			.and_then(|v| vm.manifest_stream(v))274		{275			Ok(v) => {276				*error = 0;277				stream_to_raw(v)278			}279			Err(e) => {280				*error = 1;281				let out = vm.stringify_err(&e);282				CString::new(&out as &str).unwrap().into_raw()283			}284		}285	})286}287288/// # Safety289#[no_mangle]290pub unsafe extern "C" fn jsonnet_evaluate_snippet_stream(291	vm: &EvaluationState,292	filename: *const c_char,293	snippet: *const c_char,294	error: &mut c_int,295) -> *const c_char {296	vm.run_in_state(|| {297		let filename = CStr::from_ptr(filename);298		let snippet = CStr::from_ptr(snippet);299		match vm300			.evaluate_snippet_raw(301				PathBuf::from(filename.to_str().unwrap()).into(),302				snippet.to_str().unwrap().into(),303			)304			.and_then(|v| vm.with_tla(v))305			.and_then(|v| vm.manifest_stream(v))306		{307			Ok(v) => {308				*error = 0;309				stream_to_raw(v)310			}311			Err(e) => {312				*error = 1;313				let out = vm.stringify_err(&e);314				CString::new(&out as &str).unwrap().into_raw()315			}316		}317	})318}
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
--- 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()
 				}