difftreelog
feat experimental object field order preservation
in: master
15 files changed
Cargo.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",
bindings/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"]
bindings/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"),
}
}
bindings/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"),
}
}
cmds/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" }
crates/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",
crates/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 {
crates/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" }
crates/jrsonnet-evaluator/src/builtin/manifest.rsdiffbeforeafterboth1use crate::{2 error::{Error::*, Result},3 push_description_frame, throw, Val,4};56#[derive(PartialEq, Clone, Copy)]7pub enum ManifestType {8 // Applied in manifestification9 Manifest,10 /// Used for std.manifestJson11 /// Empty array/objects extends to "[\n\n]" instead of "[ ]" as in manifest12 Std,13 /// No line breaks, used in `obj+''`14 ToString,15 /// Minified json16 Minify,17}1819pub struct ManifestJsonOptions<'s> {20 pub padding: &'s str,21 pub mtype: ManifestType,22 pub newline: &'s str,23 pub key_val_sep: &'s str,24}2526pub fn manifest_json_ex(val: &Val, options: &ManifestJsonOptions<'_>) -> Result<String> {27 let mut out = String::new();28 manifest_json_ex_buf(val, &mut out, &mut String::new(), options)?;29 Ok(out)30}31fn manifest_json_ex_buf(32 val: &Val,33 buf: &mut String,34 cur_padding: &mut String,35 options: &ManifestJsonOptions<'_>,36) -> Result<()> {37 use std::fmt::Write;38 let mtype = options.mtype;39 match val {40 Val::Bool(v) => {41 if *v {42 buf.push_str("true");43 } else {44 buf.push_str("false");45 }46 }47 Val::Null => buf.push_str("null"),48 Val::Str(s) => escape_string_json_buf(s, buf),49 Val::Num(n) => write!(buf, "{}", n).unwrap(),50 Val::Arr(items) => {51 buf.push('[');52 if !items.is_empty() {53 if mtype != ManifestType::ToString && mtype != ManifestType::Minify {54 buf.push_str(options.newline);55 }5657 let old_len = cur_padding.len();58 cur_padding.push_str(options.padding);59 for (i, item) in items.iter().enumerate() {60 if i != 0 {61 buf.push(',');62 if mtype == ManifestType::ToString {63 buf.push(' ');64 } else if mtype != ManifestType::Minify {65 buf.push_str(options.newline);66 }67 }68 buf.push_str(cur_padding);69 manifest_json_ex_buf(&item?, buf, cur_padding, options)?;70 }71 cur_padding.truncate(old_len);7273 if mtype != ManifestType::ToString && mtype != ManifestType::Minify {74 buf.push_str(options.newline);75 buf.push_str(cur_padding);76 }77 } else if mtype == ManifestType::Std {78 buf.push_str("\n\n");79 buf.push_str(cur_padding);80 } else if mtype == ManifestType::ToString || mtype == ManifestType::Manifest {81 buf.push(' ');82 }83 buf.push(']');84 }85 Val::Obj(obj) => {86 obj.run_assertions()?;87 buf.push('{');88 let fields = obj.fields();89 if !fields.is_empty() {90 if mtype != ManifestType::ToString && mtype != ManifestType::Minify {91 buf.push_str(options.newline);92 }9394 let old_len = cur_padding.len();95 cur_padding.push_str(options.padding);96 for (i, field) in fields.into_iter().enumerate() {97 if i != 0 {98 buf.push(',');99 if mtype == ManifestType::ToString {100 buf.push(' ');101 } else if mtype != ManifestType::Minify {102 buf.push_str(options.newline);103 }104 }105 buf.push_str(cur_padding);106 escape_string_json_buf(&field, buf);107 buf.push_str(options.key_val_sep);108 push_description_frame(109 || format!("field <{}> manifestification", field.clone()),110 || {111 let value = obj.get(field.clone())?.unwrap();112 manifest_json_ex_buf(&value, buf, cur_padding, options)?;113 Ok(Val::Null)114 },115 )?;116 }117 cur_padding.truncate(old_len);118119 if mtype != ManifestType::ToString && mtype != ManifestType::Minify {120 buf.push_str(options.newline);121 buf.push_str(cur_padding);122 }123 } else if mtype == ManifestType::Std {124 buf.push_str("\n\n");125 buf.push_str(cur_padding);126 } else if mtype == ManifestType::ToString || mtype == ManifestType::Manifest {127 buf.push(' ');128 }129 buf.push('}');130 }131 Val::Func(_) => throw!(RuntimeError("tried to manifest function".into())),132 };133 Ok(())134}135136pub fn escape_string_json(s: &str) -> String {137 let mut buf = String::new();138 escape_string_json_buf(s, &mut buf);139 buf140}141142fn escape_string_json_buf(s: &str, buf: &mut String) {143 use std::fmt::Write;144 buf.push('"');145 for c in s.chars() {146 match c {147 '"' => buf.push_str("\\\""),148 '\\' => buf.push_str("\\\\"),149 '\u{0008}' => buf.push_str("\\b"),150 '\u{000c}' => buf.push_str("\\f"),151 '\n' => buf.push_str("\\n"),152 '\r' => buf.push_str("\\r"),153 '\t' => buf.push_str("\\t"),154 c if c < 32 as char || (c >= 127 as char && c <= 159 as char) => {155 write!(buf, "\\u{:04x}", c as u32).unwrap()156 }157 c => buf.push(c),158 }159 }160 buf.push('"');161}162163pub struct ManifestYamlOptions<'s> {164 /// Padding before fields, i.e165 /// ```yaml166 /// a:167 /// b:168 /// ## <- this169 /// ```170 pub padding: &'s str,171 /// Padding before array elements in objects172 /// ```yaml173 /// a:174 /// - 1175 /// ## <- this176 /// ```177 pub arr_element_padding: &'s str,178 /// Should yaml keys appear unescaped, when possible179 /// ```yaml180 /// "safe_key": 1181 /// # vs182 /// safe_key: 1183 /// ```184 pub quote_keys: bool,185}186187/// From https://github.com/chyh1990/yaml-rust/blob/da52a68615f2ecdd6b7e4567019f280c433c1521/src/emitter.rs#L289188/// With added date check189fn yaml_needs_quotes(string: &str) -> bool {190 fn need_quotes_spaces(string: &str) -> bool {191 string.starts_with(' ') || string.ends_with(' ')192 }193194 string.is_empty()195 || need_quotes_spaces(string)196 || string.starts_with(|c| matches!(c, '&' | '*' | '?' | '|' | '-' | '<' | '>' | '=' | '!' | '%' | '@'))197 || string.contains(|c| matches!(c, ':' | '{' | '}' | '[' | ']' | ',' | '#' | '`' | '\"' | '\'' | '\\' | '\0'..='\x06' | '\t' | '\n' | '\r' | '\x0e'..='\x1a' | '\x1c'..='\x1f'))198 || [199 // http://yaml.org/type/bool.html200 // Note: 'y', 'Y', 'n', 'N', is not quoted deliberately, as in libyaml. PyYAML also parse201 // them as string, not booleans, although it is violating the YAML 1.1 specification.202 // See https://github.com/dtolnay/serde-yaml/pull/83#discussion_r152628088.203 "yes", "Yes", "YES", "no", "No", "NO", "True", "TRUE", "true", "False", "FALSE", "false",204 "on", "On", "ON", "off", "Off", "OFF", // http://yaml.org/type/null.html205 "null", "Null", "NULL", "~",206 ].contains(&string)207 || (string.chars().all(|c| matches!(c, '0'..='9' | '-'))208 && string.chars().filter(|c| *c == '-').count() == 2)209 || string.starts_with('.')210 || string.starts_with("0x")211 || string.parse::<i64>().is_ok()212 || string.parse::<f64>().is_ok()213}214215pub fn manifest_yaml_ex(val: &Val, options: &ManifestYamlOptions<'_>) -> Result<String> {216 let mut out = String::new();217 manifest_yaml_ex_buf(val, &mut out, &mut String::new(), options)?;218 Ok(out)219}220fn manifest_yaml_ex_buf(221 val: &Val,222 buf: &mut String,223 cur_padding: &mut String,224 options: &ManifestYamlOptions<'_>,225) -> Result<()> {226 use std::fmt::Write;227 match val {228 Val::Bool(v) => {229 if *v {230 buf.push_str("true")231 } else {232 buf.push_str("false")233 }234 }235 Val::Null => buf.push_str("null"),236 Val::Str(s) => {237 if s.is_empty() {238 buf.push_str("\"\"");239 } else if let Some(s) = s.strip_suffix('\n') {240 buf.push('|');241 for line in s.split('\n') {242 buf.push('\n');243 buf.push_str(options.padding);244 buf.push_str(line);245 }246 } else if !options.quote_keys && !yaml_needs_quotes(s) {247 buf.push_str(s);248 } else {249 escape_string_json_buf(s, buf);250 }251 }252 Val::Num(n) => write!(buf, "{}", *n).unwrap(),253 Val::Arr(a) => {254 if a.is_empty() {255 buf.push_str("[]");256 } else {257 for (i, item) in a.iter().enumerate() {258 if i != 0 {259 buf.push('\n');260 buf.push_str(cur_padding);261 }262 let item = item?;263 buf.push('-');264 match &item {265 Val::Arr(a) if !a.is_empty() => {266 buf.push('\n');267 buf.push_str(cur_padding);268 buf.push_str(options.padding);269 }270 _ => buf.push(' '),271 }272 let extra_padding = match &item {273 Val::Arr(a) => !a.is_empty(),274 Val::Obj(o) => !o.is_empty(),275 _ => false,276 };277 let prev_len = cur_padding.len();278 if extra_padding {279 cur_padding.push_str(options.padding);280 }281 manifest_yaml_ex_buf(&item, buf, cur_padding, options)?;282 cur_padding.truncate(prev_len);283 }284 }285 }286 Val::Obj(o) => {287 if o.is_empty() {288 buf.push_str("{}");289 } else {290 for (i, key) in o.fields().iter().enumerate() {291 if i != 0 {292 buf.push('\n');293 buf.push_str(cur_padding);294 }295 if !options.quote_keys && !yaml_needs_quotes(key) {296 buf.push_str(key);297 } else {298 escape_string_json_buf(key, buf);299 }300 buf.push(':');301 let prev_len = cur_padding.len();302 let item = o.get(key.clone())?.expect("field exists");303 match &item {304 Val::Arr(a) if !a.is_empty() => {305 buf.push('\n');306 buf.push_str(cur_padding);307 buf.push_str(options.arr_element_padding);308 cur_padding.push_str(options.arr_element_padding);309 }310 Val::Obj(o) if !o.is_empty() => {311 buf.push('\n');312 buf.push_str(cur_padding);313 buf.push_str(options.padding);314 cur_padding.push_str(options.padding);315 }316 _ => buf.push(' '),317 }318 manifest_yaml_ex_buf(&item, buf, cur_padding, options)?;319 cur_padding.truncate(prev_len);320 }321 }322 }323 Val::Func(_) => throw!(RuntimeError("tried to manifest function".into())),324 }325 Ok(())326}1use crate::{2 error::{Error::*, Result},3 push_description_frame, throw, Val,4};56#[derive(PartialEq, Clone, Copy)]7pub enum ManifestType {8 // Applied in manifestification9 Manifest,10 /// Used for std.manifestJson11 /// Empty array/objects extends to "[\n\n]" instead of "[ ]" as in manifest12 Std,13 /// No line breaks, used in `obj+''`14 ToString,15 /// Minified json16 Minify,17}1819pub struct ManifestJsonOptions<'s> {20 pub padding: &'s str,21 pub mtype: ManifestType,22 pub newline: &'s str,23 pub key_val_sep: &'s str,24 #[cfg(feature = "exp-preserve-order")]25 pub preserve_order: bool,26}2728pub fn manifest_json_ex(val: &Val, options: &ManifestJsonOptions<'_>) -> Result<String> {29 let mut out = String::new();30 manifest_json_ex_buf(val, &mut out, &mut String::new(), options)?;31 Ok(out)32}33fn manifest_json_ex_buf(34 val: &Val,35 buf: &mut String,36 cur_padding: &mut String,37 options: &ManifestJsonOptions<'_>,38) -> Result<()> {39 use std::fmt::Write;40 let mtype = options.mtype;41 match val {42 Val::Bool(v) => {43 if *v {44 buf.push_str("true");45 } else {46 buf.push_str("false");47 }48 }49 Val::Null => buf.push_str("null"),50 Val::Str(s) => escape_string_json_buf(s, buf),51 Val::Num(n) => write!(buf, "{}", n).unwrap(),52 Val::Arr(items) => {53 buf.push('[');54 if !items.is_empty() {55 if mtype != ManifestType::ToString && mtype != ManifestType::Minify {56 buf.push_str(options.newline);57 }5859 let old_len = cur_padding.len();60 cur_padding.push_str(options.padding);61 for (i, item) in items.iter().enumerate() {62 if i != 0 {63 buf.push(',');64 if mtype == ManifestType::ToString {65 buf.push(' ');66 } else if mtype != ManifestType::Minify {67 buf.push_str(options.newline);68 }69 }70 buf.push_str(cur_padding);71 manifest_json_ex_buf(&item?, buf, cur_padding, options)?;72 }73 cur_padding.truncate(old_len);7475 if mtype != ManifestType::ToString && mtype != ManifestType::Minify {76 buf.push_str(options.newline);77 buf.push_str(cur_padding);78 }79 } else if mtype == ManifestType::Std {80 buf.push_str("\n\n");81 buf.push_str(cur_padding);82 } else if mtype == ManifestType::ToString || mtype == ManifestType::Manifest {83 buf.push(' ');84 }85 buf.push(']');86 }87 Val::Obj(obj) => {88 obj.run_assertions()?;89 buf.push('{');90 let fields = obj.fields(91 #[cfg(feature = "exp-preserve-order")]92 options.preserve_order,93 );94 if !fields.is_empty() {95 if mtype != ManifestType::ToString && mtype != ManifestType::Minify {96 buf.push_str(options.newline);97 }9899 let old_len = cur_padding.len();100 cur_padding.push_str(options.padding);101 for (i, field) in fields.into_iter().enumerate() {102 if i != 0 {103 buf.push(',');104 if mtype == ManifestType::ToString {105 buf.push(' ');106 } else if mtype != ManifestType::Minify {107 buf.push_str(options.newline);108 }109 }110 buf.push_str(cur_padding);111 escape_string_json_buf(&field, buf);112 buf.push_str(options.key_val_sep);113 push_description_frame(114 || format!("field <{}> manifestification", field.clone()),115 || {116 let value = obj.get(field.clone())?.unwrap();117 manifest_json_ex_buf(&value, buf, cur_padding, options)?;118 Ok(Val::Null)119 },120 )?;121 }122 cur_padding.truncate(old_len);123124 if mtype != ManifestType::ToString && mtype != ManifestType::Minify {125 buf.push_str(options.newline);126 buf.push_str(cur_padding);127 }128 } else if mtype == ManifestType::Std {129 buf.push_str("\n\n");130 buf.push_str(cur_padding);131 } else if mtype == ManifestType::ToString || mtype == ManifestType::Manifest {132 buf.push(' ');133 }134 buf.push('}');135 }136 Val::Func(_) => throw!(RuntimeError("tried to manifest function".into())),137 };138 Ok(())139}140141pub fn escape_string_json(s: &str) -> String {142 let mut buf = String::new();143 escape_string_json_buf(s, &mut buf);144 buf145}146147fn escape_string_json_buf(s: &str, buf: &mut String) {148 use std::fmt::Write;149 buf.push('"');150 for c in s.chars() {151 match c {152 '"' => buf.push_str("\\\""),153 '\\' => buf.push_str("\\\\"),154 '\u{0008}' => buf.push_str("\\b"),155 '\u{000c}' => buf.push_str("\\f"),156 '\n' => buf.push_str("\\n"),157 '\r' => buf.push_str("\\r"),158 '\t' => buf.push_str("\\t"),159 c if c < 32 as char || (c >= 127 as char && c <= 159 as char) => {160 write!(buf, "\\u{:04x}", c as u32).unwrap()161 }162 c => buf.push(c),163 }164 }165 buf.push('"');166}167168pub struct ManifestYamlOptions<'s> {169 /// Padding before fields, i.e170 /// ```yaml171 /// a:172 /// b:173 /// ## <- this174 /// ```175 pub padding: &'s str,176 /// Padding before array elements in objects177 /// ```yaml178 /// a:179 /// - 1180 /// ## <- this181 /// ```182 pub arr_element_padding: &'s str,183 /// Should yaml keys appear unescaped, when possible184 /// ```yaml185 /// "safe_key": 1186 /// # vs187 /// safe_key: 1188 /// ```189 pub quote_keys: bool,190 /// If true - then order of fields is preserved as written,191 /// instead of sorting alphabetically192 #[cfg(feature = "exp-preserve-order")]193 pub preserve_order: bool,194}195196/// From https://github.com/chyh1990/yaml-rust/blob/da52a68615f2ecdd6b7e4567019f280c433c1521/src/emitter.rs#L289197/// With added date check198fn yaml_needs_quotes(string: &str) -> bool {199 fn need_quotes_spaces(string: &str) -> bool {200 string.starts_with(' ') || string.ends_with(' ')201 }202203 string.is_empty()204 || need_quotes_spaces(string)205 || string.starts_with(|c| matches!(c, '&' | '*' | '?' | '|' | '-' | '<' | '>' | '=' | '!' | '%' | '@'))206 || string.contains(|c| matches!(c, ':' | '{' | '}' | '[' | ']' | ',' | '#' | '`' | '\"' | '\'' | '\\' | '\0'..='\x06' | '\t' | '\n' | '\r' | '\x0e'..='\x1a' | '\x1c'..='\x1f'))207 || [208 // http://yaml.org/type/bool.html209 // Note: 'y', 'Y', 'n', 'N', is not quoted deliberately, as in libyaml. PyYAML also parse210 // them as string, not booleans, although it is violating the YAML 1.1 specification.211 // See https://github.com/dtolnay/serde-yaml/pull/83#discussion_r152628088.212 "yes", "Yes", "YES", "no", "No", "NO", "True", "TRUE", "true", "False", "FALSE", "false",213 "on", "On", "ON", "off", "Off", "OFF", // http://yaml.org/type/null.html214 "null", "Null", "NULL", "~",215 ].contains(&string)216 || (string.chars().all(|c| matches!(c, '0'..='9' | '-'))217 && string.chars().filter(|c| *c == '-').count() == 2)218 || string.starts_with('.')219 || string.starts_with("0x")220 || string.parse::<i64>().is_ok()221 || string.parse::<f64>().is_ok()222}223224pub fn manifest_yaml_ex(val: &Val, options: &ManifestYamlOptions<'_>) -> Result<String> {225 let mut out = String::new();226 manifest_yaml_ex_buf(val, &mut out, &mut String::new(), options)?;227 Ok(out)228}229fn manifest_yaml_ex_buf(230 val: &Val,231 buf: &mut String,232 cur_padding: &mut String,233 options: &ManifestYamlOptions<'_>,234) -> Result<()> {235 use std::fmt::Write;236 match val {237 Val::Bool(v) => {238 if *v {239 buf.push_str("true")240 } else {241 buf.push_str("false")242 }243 }244 Val::Null => buf.push_str("null"),245 Val::Str(s) => {246 if s.is_empty() {247 buf.push_str("\"\"");248 } else if let Some(s) = s.strip_suffix('\n') {249 buf.push('|');250 for line in s.split('\n') {251 buf.push('\n');252 buf.push_str(options.padding);253 buf.push_str(line);254 }255 } else if !options.quote_keys && !yaml_needs_quotes(s) {256 buf.push_str(s);257 } else {258 escape_string_json_buf(s, buf);259 }260 }261 Val::Num(n) => write!(buf, "{}", *n).unwrap(),262 Val::Arr(a) => {263 if a.is_empty() {264 buf.push_str("[]");265 } else {266 for (i, item) in a.iter().enumerate() {267 if i != 0 {268 buf.push('\n');269 buf.push_str(cur_padding);270 }271 let item = item?;272 buf.push('-');273 match &item {274 Val::Arr(a) if !a.is_empty() => {275 buf.push('\n');276 buf.push_str(cur_padding);277 buf.push_str(options.padding);278 }279 _ => buf.push(' '),280 }281 let extra_padding = match &item {282 Val::Arr(a) => !a.is_empty(),283 Val::Obj(o) => !o.is_empty(),284 _ => false,285 };286 let prev_len = cur_padding.len();287 if extra_padding {288 cur_padding.push_str(options.padding);289 }290 manifest_yaml_ex_buf(&item, buf, cur_padding, options)?;291 cur_padding.truncate(prev_len);292 }293 }294 }295 Val::Obj(o) => {296 if o.is_empty() {297 buf.push_str("{}");298 } else {299 for (i, key) in o300 .fields(301 #[cfg(feature = "exp-preserve-order")]302 options.preserve_order,303 )304 .iter()305 .enumerate()306 {307 if i != 0 {308 buf.push('\n');309 buf.push_str(cur_padding);310 }311 if !options.quote_keys && !yaml_needs_quotes(key) {312 buf.push_str(key);313 } else {314 escape_string_json_buf(key, buf);315 }316 buf.push(':');317 let prev_len = cur_padding.len();318 let item = o.get(key.clone())?.expect("field exists");319 match &item {320 Val::Arr(a) if !a.is_empty() => {321 buf.push('\n');322 buf.push_str(cur_padding);323 buf.push_str(options.arr_element_padding);324 cur_padding.push_str(options.arr_element_padding);325 }326 Val::Obj(o) if !o.is_empty() => {327 buf.push('\n');328 buf.push_str(cur_padding);329 buf.push_str(options.padding);330 cur_padding.push_str(options.padding);331 }332 _ => buf.push(' '),333 }334 manifest_yaml_ex_buf(&item, buf, cur_padding, options)?;335 cur_padding.truncate(prev_len);336 }337 }338 }339 Val::Func(_) => throw!(RuntimeError("tried to manifest function".into())),340 }341 Ok(())342}crates/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),
},
)
}
crates/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)?
crates/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,
crates/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)
+ }
+}
crates/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 {
crates/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()
}