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
492source = "registry+https://github.com/rust-lang/crates.io-index"492source = "registry+https://github.com/rust-lang/crates.io-index"
493checksum = "d0ffa0837f2dfa6fb90868c2b5468cad482e175f7dad97e7421951e663f2b527"493checksum = "d0ffa0837f2dfa6fb90868c2b5468cad482e175f7dad97e7421951e663f2b527"
494dependencies = [494dependencies = [
495 "indexmap",
495 "itoa",496 "itoa",
496 "ryu",497 "ryu",
497 "serde",498 "serde",
modifiedbindings/jsonnet/Cargo.tomldiffbeforeafterboth
1717
18[features]18[features]
19interop = []19interop = []
20exp-preserve-order = ["jrsonnet-evaluator/exp-preserve-order"]
2021
modifiedbindings/jsonnet/src/lib.rsdiffbeforeafterboth
58pub extern "C" fn jsonnet_string_output(vm: &EvaluationState, v: c_int) {58pub extern "C" fn jsonnet_string_output(vm: &EvaluationState, v: c_int) {
59 match v {59 match v {
60 1 => vm.set_manifest_format(ManifestFormat::String),60 1 => vm.set_manifest_format(ManifestFormat::String),
61 0 => vm.set_manifest_format(ManifestFormat::Json(4)),61 0 => vm.set_manifest_format(ManifestFormat::Json {
62 padding: 4,
63 #[cfg(feature = "exp-preserve-order")]
64 preserve_order: false,
65 }),
62 _ => panic!("incorrect output format"),66 _ => panic!("incorrect output format"),
63 }67 }
64}68}
modifiedbindings/jsonnet/src/val_modify.rsdiffbeforeafterboth
5use std::{ffi::CStr, os::raw::c_char};5use std::{ffi::CStr, os::raw::c_char};
66
7use gcmodule::Cc;7use gcmodule::Cc;
8use jrsonnet_evaluator::{val::ArrValue, EvaluationState, LazyBinding, LazyVal, ObjMember, Val};8use jrsonnet_evaluator::{val::ArrValue, EvaluationState, LazyVal, Val};
9use jrsonnet_parser::Visibility;
109
11/// # Safety10/// # Safety
12///11///
41 val: &Val,40 val: &Val,
42) {41) {
43 match obj {42 match obj {
44 Val::Obj(old) => {43 Val::Obj(old) => old
45 let new_obj = old.clone().extend_with_field(44 .extend_field(CStr::from_ptr(name).to_str().unwrap().into())
46 CStr::from_ptr(name).to_str().unwrap().into(),
47 ObjMember {
48 add: false,
49 visibility: Visibility::Normal,
50 invoke: LazyBinding::Bound(LazyVal::new_resolved(val.clone())),
51 location: None,
52 },
53 );
54
55 *obj = Val::Obj(new_obj);45 .value(val.clone()),
56 }
57 _ => panic!("should receive object"),46 _ => panic!("should receive object"),
58 }47 }
59}48}
modifiedcmds/jrsonnet/Cargo.tomldiffbeforeafterboth
9[features]9[features]
10# Use mimalloc as allocator10# Use mimalloc as allocator
11mimalloc = ["mimallocator"]11mimalloc = ["mimallocator"]
12# Experimental feature, which allows to preserve order of object fields
13exp-preserve-order = [
14 "jrsonnet-evaluator/exp-preserve-order",
15 "jrsonnet-evaluator/exp-serde-preserve-order",
16 "jrsonnet-cli/exp-preserve-order",
17]
1218
13[dependencies]19[dependencies]
14jrsonnet-evaluator = { path = "../../crates/jrsonnet-evaluator", version = "0.4.2" }20jrsonnet-evaluator = { path = "../../crates/jrsonnet-evaluator", version = "0.4.2" }
modifiedcrates/jrsonnet-cli/Cargo.tomldiffbeforeafterboth
6license = "MIT"6license = "MIT"
7edition = "2021"7edition = "2021"
8
9[features]
10exp-preserve-order = ["jrsonnet-evaluator/exp-preserve-order"]
811
9[dependencies]12[dependencies]
10jrsonnet-evaluator = { path = "../../crates/jrsonnet-evaluator", version = "0.4.2", features = [13jrsonnet-evaluator = { path = "../../crates/jrsonnet-evaluator", version = "0.4.2", features = [
modifiedcrates/jrsonnet-cli/src/manifest.rsdiffbeforeafterboth
43 /// `0` for hard tabs, `-1` for single line output [default: 3 for json, 2 for yaml]43 /// `0` for hard tabs, `-1` for single line output [default: 3 for json, 2 for yaml]
44 #[clap(long)]44 #[clap(long)]
45 line_padding: Option<usize>,45 line_padding: Option<usize>,
46 /// Preserve order in object manifestification
47 #[cfg(feature = "exp-preserve-order")]
48 #[clap(long)]
49 exp_preserve_order: bool,
46}50}
47impl ConfigureState for ManifestOpts {51impl ConfigureState for ManifestOpts {
48 fn configure(&self, state: &EvaluationState) -> Result<()> {52 fn configure(&self, state: &EvaluationState) -> Result<()> {
49 if self.string {53 if self.string {
50 state.set_manifest_format(ManifestFormat::String);54 state.set_manifest_format(ManifestFormat::String);
51 } else {55 } else {
56 #[cfg(feature = "exp-preserve-order")]
57 let preserve_order = self.exp_preserve_order;
52 match self.format {58 match self.format {
53 ManifestFormatName::String => state.set_manifest_format(ManifestFormat::String),59 ManifestFormatName::String => state.set_manifest_format(ManifestFormat::String),
54 ManifestFormatName::Json => {60 ManifestFormatName::Json => state.set_manifest_format(ManifestFormat::Json {
55 state.set_manifest_format(ManifestFormat::Json(self.line_padding.unwrap_or(3)))61 padding: self.line_padding.unwrap_or(3),
56 }62 #[cfg(feature = "exp-preserve-order")]
63 preserve_order,
64 }),
57 ManifestFormatName::Yaml => {65 ManifestFormatName::Yaml => state.set_manifest_format(ManifestFormat::Yaml {
58 state.set_manifest_format(ManifestFormat::Yaml(self.line_padding.unwrap_or(2)))66 padding: self.line_padding.unwrap_or(2),
59 }67 #[cfg(feature = "exp-preserve-order")]
68 preserve_order,
69 }),
60 }70 }
61 }71 }
62 if self.yaml_stream {72 if self.yaml_stream {
modifiedcrates/jrsonnet-evaluator/Cargo.tomldiffbeforeafterboth
15# Allows library authors to throw custom errors15# Allows library authors to throw custom errors
16anyhow-error = ["anyhow"]16anyhow-error = ["anyhow"]
17
18# Allows to preserve field order in objects
19exp-preserve-order = []
20exp-serde-preserve-order = ["serde_json/preserve_order"]
1721
18[dependencies]22[dependencies]
19jrsonnet-interner = { path = "../jrsonnet-interner", version = "0.4.2" }23jrsonnet-interner = { path = "../jrsonnet-interner", version = "0.4.2" }
modifiedcrates/jrsonnet-evaluator/src/builtin/manifest.rsdiffbeforeafterboth
21 pub mtype: ManifestType,21 pub mtype: ManifestType,
22 pub newline: &'s str,22 pub newline: &'s str,
23 pub key_val_sep: &'s str,23 pub key_val_sep: &'s str,
24 #[cfg(feature = "exp-preserve-order")]
25 pub preserve_order: bool,
24}26}
2527
26pub fn manifest_json_ex(val: &Val, options: &ManifestJsonOptions<'_>) -> Result<String> {28pub fn manifest_json_ex(val: &Val, options: &ManifestJsonOptions<'_>) -> Result<String> {
86 obj.run_assertions()?;88 obj.run_assertions()?;
87 buf.push('{');89 buf.push('{');
88 let fields = obj.fields();90 let fields = obj.fields(
91 #[cfg(feature = "exp-preserve-order")]
92 options.preserve_order,
93 );
89 if !fields.is_empty() {94 if !fields.is_empty() {
90 if mtype != ManifestType::ToString && mtype != ManifestType::Minify {95 if mtype != ManifestType::ToString && mtype != ManifestType::Minify {
182 /// safe_key: 1187 /// safe_key: 1
183 /// ```188 /// ```
184 pub quote_keys: bool,189 pub quote_keys: bool,
190 /// If true - then order of fields is preserved as written,
191 /// instead of sorting alphabetically
192 #[cfg(feature = "exp-preserve-order")]
193 pub preserve_order: bool,
185}194}
186195
187/// From https://github.com/chyh1990/yaml-rust/blob/da52a68615f2ecdd6b7e4567019f280c433c1521/src/emitter.rs#L289196/// From https://github.com/chyh1990/yaml-rust/blob/da52a68615f2ecdd6b7e4567019f280c433c1521/src/emitter.rs#L289
289 } else {298 } else {
290 for (i, key) in o.fields().iter().enumerate() {299 for (i, key) in o
300 .fields(
301 #[cfg(feature = "exp-preserve-order")]
302 options.preserve_order,
303 )
304 .iter()
305 .enumerate()
modifiedcrates/jrsonnet-evaluator/src/builtin/mod.rsdiffbeforeafterboth
162 Ok(match x {162 Ok(match x {
163 A(x) => x.chars().count(),163 A(x) => x.chars().count(),
164 B(x) => x.len(),164 B(x) => x.len(),
165 C(x) => x165 C(x) => x.len(),
166 .fields_visibility()
167 .into_iter()
168 .filter(|(_k, v)| *v)
169 .count(),
170 D(f) => f.args_len(),166 D(f) => f.args_len(),
171 })167 })
172}168}
193#[jrsonnet_macros::builtin]189#[jrsonnet_macros::builtin]
194fn builtin_object_fields_ex(obj: ObjValue, inc_hidden: bool) -> Result<VecVal> {190fn builtin_object_fields_ex(
191 obj: ObjValue,
192 inc_hidden: bool,
193 #[cfg(feature = "exp-preserve-order")] preserve_order: Option<bool>,
194) -> Result<VecVal> {
195 #[cfg(not(feature = "exp-preserve-order"))]
196 let preserve_order = false;
197 #[cfg(feature = "exp-preserve-order")]
198 let preserve_order = preserve_order.unwrap_or(false);
195 let out = obj.fields_ex(inc_hidden);199 let out = obj.fields_ex(
200 inc_hidden,
201 #[cfg(feature = "exp-preserve-order")]
202 preserve_order,
203 );
196 Ok(VecVal(Cc::new(204 Ok(VecVal(Cc::new(
197 out.into_iter().map(Val::Str).collect::<Vec<_>>(),205 out.into_iter().map(Val::Str).collect::<Vec<_>>(),
586 indent: IStr,594 indent: IStr,
587 newline: Option<IStr>,595 newline: Option<IStr>,
588 key_val_sep: Option<IStr>,596 key_val_sep: Option<IStr>,
597 #[cfg(feature = "exp-preserve-order")] preserve_order: Option<bool>,
589) -> Result<String> {598) -> Result<String> {
590 let newline = newline.as_deref().unwrap_or("\n");599 let newline = newline.as_deref().unwrap_or("\n");
591 let key_val_sep = key_val_sep.as_deref().unwrap_or(": ");600 let key_val_sep = key_val_sep.as_deref().unwrap_or(": ");
596 mtype: ManifestType::Std,605 mtype: ManifestType::Std,
597 newline,606 newline,
598 key_val_sep,607 key_val_sep,
608 #[cfg(feature = "exp-preserve-order")]
609 preserve_order: preserve_order.unwrap_or(false),
599 },610 },
600 )611 )
601}612}
605 value: Any,616 value: Any,
606 indent_array_in_object: Option<bool>,617 indent_array_in_object: Option<bool>,
607 quote_keys: Option<bool>,618 quote_keys: Option<bool>,
619 #[cfg(feature = "exp-preserve-order")] preserve_order: Option<bool>,
608) -> Result<String> {620) -> Result<String> {
609 manifest_yaml_ex(621 manifest_yaml_ex(
610 &value.0,622 &value.0,
616 ""628 ""
617 },629 },
618 quote_keys: quote_keys.unwrap_or(true),630 quote_keys: quote_keys.unwrap_or(true),
631 #[cfg(feature = "exp-preserve-order")]
632 preserve_order: preserve_order.unwrap_or(false),
619 },633 },
620 )634 )
621}635}
modifiedcrates/jrsonnet-evaluator/src/integrations/serde.rsdiffbeforeafterboth
29 Val::Obj(o) => {29 Val::Obj(o) => {
30 let mut out = Map::new();30 let mut out = Map::new();
31 for key in o.fields() {31 for key in o.fields(
32 #[cfg(feature = "exp-preserve-order")]
33 cfg!(feature = "exp-serde-preserve-order"),
34 ) {
32 out.insert(35 out.insert(
33 (&key as &str).into(),36 (&key as &str).into(),
modifiedcrates/jrsonnet-evaluator/src/lib.rsdiffbeforeafterboth
100 ext_natives: Default::default(),100 ext_natives: Default::default(),
101 tla_vars: Default::default(),101 tla_vars: Default::default(),
102 import_resolver: Box::new(DummyImportResolver),102 import_resolver: Box::new(DummyImportResolver),
103 manifest_format: ManifestFormat::Json(4),103 manifest_format: ManifestFormat::Json {
104 padding: 4,
105 #[cfg(feature = "exp-preserve-order")]
106 preserve_order: false,
107 },
104 trace_format: Box::new(CompactFormat {108 trace_format: Box::new(CompactFormat {
105 padding: 4,109 padding: 4,
106 resolver: trace::PathResolver::Absolute,110 resolver: trace::PathResolver::Absolute,
modifiedcrates/jrsonnet-evaluator/src/obj.rsdiffbeforeafterboth
18 push_frame, throw, weak_ptr_eq, weak_raw, Bindable, LazyBinding, LazyVal, Result, Val,18 push_frame, throw, weak_ptr_eq, weak_raw, Bindable, LazyBinding, LazyVal, Result, Val,
19};19};
20
21#[cfg(not(feature = "exp-preserve-order"))]
22pub(crate) mod ordering {
23 use gcmodule::Trace;
24
25 #[derive(Clone, Copy, Default, Debug, Trace)]
26 pub struct FieldIndex;
27 impl FieldIndex {
28 pub fn next(self) -> Self {
29 Self
30 }
31 }
32
33 #[derive(Clone, Copy, Default, Debug, Trace)]
34 pub struct SuperDepth;
35 impl SuperDepth {
36 pub fn deeper(self) -> Self {
37 Self
38 }
39 }
40
41 #[derive(Clone, Copy)]
42 pub struct FieldSortKey;
43 impl FieldSortKey {
44 pub fn new(_: SuperDepth, _: FieldIndex) -> Self {
45 Self
46 }
47 }
48}
49
50#[cfg(feature = "exp-preserve-order")]
51mod ordering {
52 use std::cmp::Reverse;
53
54 use gcmodule::Trace;
55
56 #[derive(Clone, Copy, Default, Debug, Trace, PartialEq, Eq, PartialOrd, Ord)]
57 pub struct FieldIndex(u32);
58 impl FieldIndex {
59 pub fn next(self) -> Self {
60 Self(self.0 + 1)
61 }
62 }
63
64 #[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Debug)]
65 pub struct SuperDepth(u32);
66 impl SuperDepth {
67 pub fn deeper(self) -> Self {
68 Self(self.0 + 1)
69 }
70 }
71
72 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
73 pub struct FieldSortKey(Reverse<SuperDepth>, FieldIndex);
74 impl FieldSortKey {
75 pub fn new(depth: SuperDepth, index: FieldIndex) -> Self {
76 Self(Reverse(depth), index)
77 }
78 pub fn collide(self, other: Self) -> Self {
79 if self.0 .0 > other.0 .0 {
80 self
81 } else if self.0 .0 < other.0 .0 {
82 other
83 } else {
84 unreachable!("object can't have two fields with same name")
85 }
86 }
87 }
88}
89
90pub(crate) use ordering::*;
2091
21#[derive(Debug, Trace)]92#[derive(Debug, Trace)]
22pub struct ObjMember {93pub struct ObjMember {
23 pub add: bool,94 pub add: bool,
24 pub visibility: Visibility,95 pub visibility: Visibility,
96 original_index: FieldIndex,
25 pub invoke: LazyBinding,97 pub invoke: LazyBinding,
26 pub location: Option<ExprLocation>,98 pub location: Option<ExprLocation>,
27}99}
120 ),192 ),
121 }193 }
122 }194 }
195 pub(crate) fn extend_with_raw_member(self, key: IStr, value: ObjMember) -> Self {
196 let mut new = GcHashMap::with_capacity(1);
197 new.insert(key, value);
198 Self::new(Some(self), Cc::new(new), Cc::new(Vec::new()))
199 }
200 pub fn extend_field(&mut self, name: IStr) -> ObjMemberBuilder<ExtendBuilder> {
201 ObjMemberBuilder::new(ExtendBuilder(self), name, FieldIndex::default())
202 }
123 pub fn with_this(&self, this_obj: Self) -> Self {203 pub fn with_this(&self, this_obj: Self) -> Self {
124 Self(Cc::new(ObjValueInternals {204 Self(Cc::new(ObjValueInternals {
125 super_obj: self.0.super_obj.clone(),205 super_obj: self.0.super_obj.clone(),
131 }))211 }))
132 }212 }
213
214 pub fn len(&self) -> usize {
215 self.fields_visibility()
216 .into_iter()
217 .filter(|(_, (visible, _))| *visible)
218 .count()
219 }
133220
134 pub fn is_empty(&self) -> bool {221 pub fn is_empty(&self) -> bool {
135 if !self.0.this_entries.is_empty() {222 if !self.0.this_entries.is_empty() {
145 /// Run callback for every field found in object232 /// Run callback for every field found in object
146 pub(crate) fn enum_fields(&self, handler: &mut impl FnMut(&IStr, &ObjMember) -> bool) -> bool {233 pub(crate) fn enum_fields(
234 &self,
235 depth: SuperDepth,
236 handler: &mut impl FnMut(SuperDepth, &IStr, &ObjMember) -> bool,
237 ) -> bool {
147 if let Some(s) = &self.0.super_obj {238 if let Some(s) = &self.0.super_obj {
148 if s.enum_fields(handler) {239 if s.enum_fields(depth.deeper(), handler) {
149 return true;240 return true;
150 }241 }
151 }242 }
152 for (name, member) in self.0.this_entries.iter() {243 for (name, member) in self.0.this_entries.iter() {
153 if handler(name, member) {244 if handler(depth, name, member) {
154 return true;245 return true;
155 }246 }
156 }247 }
157 false248 false
158 }249 }
159250
160 pub fn fields_visibility(&self) -> FxHashMap<IStr, bool> {251 pub fn fields_visibility(&self) -> FxHashMap<IStr, (bool, FieldSortKey)> {
161 let mut out = FxHashMap::default();252 let mut out = FxHashMap::default();
162 self.enum_fields(&mut |name, member| {253 self.enum_fields(SuperDepth::default(), &mut |depth, name, member| {
254 let new_sort_key = FieldSortKey::new(depth, member.original_index);
163 match member.visibility {255 match member.visibility {
164 Visibility::Normal => {256 Visibility::Normal => {
165 let entry = out.entry(name.to_owned());257 let entry = out.entry(name.to_owned());
166 entry.or_insert(true);258 let v = entry.or_insert((true, new_sort_key));
259 v.1 = new_sort_key;
167 }260 }
168 Visibility::Hidden => {261 Visibility::Hidden => {
169 out.insert(name.to_owned(), false);262 out.insert(name.to_owned(), (false, new_sort_key));
170 }263 }
171 Visibility::Unhide => {264 Visibility::Unhide => {
172 out.insert(name.to_owned(), true);265 out.insert(name.to_owned(), (true, new_sort_key));
173 }266 }
174 };267 };
175 false268 false
176 });269 });
177 out270 out
178 }271 }
179 pub fn fields_ex(&self, include_hidden: bool) -> Vec<IStr> {272 pub fn fields_ex(
273 &self,
274 include_hidden: bool,
275 #[cfg(feature = "exp-preserve-order")] preserve_order: bool,
276 ) -> Vec<IStr> {
277 #[cfg(feature = "exp-preserve-order")]
278 if preserve_order {
279 let (mut fields, mut keys): (Vec<_>, Vec<_>) = self
280 .fields_visibility()
281 .into_iter()
282 .filter(|(_, (visible, _))| include_hidden || *visible)
283 .enumerate()
284 .map(|(idx, (k, (_, sk)))| (k, (sk, idx)))
285 .unzip();
286 keys.sort_unstable_by_key(|v| v.0);
287 // Reorder in-place by resulting indexes
288 for i in 0..fields.len() {
289 let x = fields[i].clone();
290 let mut j = i;
291 loop {
292 let k = keys[j].1;
293 keys[j].1 = j;
294 if k == i {
295 break;
296 }
297 fields[j] = fields[k].clone();
298 j = k
299 }
300 fields[j] = x;
301 }
302 return fields;
303 }
304
180 let mut fields: Vec<_> = self305 let mut fields: Vec<_> = self
181 .fields_visibility()306 .fields_visibility()
182 .into_iter()307 .into_iter()
183 .filter(|(_k, v)| include_hidden || *v)308 .filter(|(_, (visible, _))| include_hidden || *visible)
184 .map(|(k, _)| k)309 .map(|(k, _)| k)
185 .collect();310 .collect();
186 fields.sort_unstable();311 fields.sort_unstable();
187 fields312 fields
188 }313 }
189 pub fn fields(&self) -> Vec<IStr> {314 pub fn fields(&self, #[cfg(feature = "exp-preserve-order")] preserve_order: bool) -> Vec<IStr> {
190 self.fields_ex(false)315 self.fields_ex(
316 false,
317 #[cfg(feature = "exp-preserve-order")]
318 preserve_order,
319 )
191 }320 }
192321
236 self.get_raw(key, self.0.this_obj.as_ref())365 self.get_raw(key, self.0.this_obj.as_ref())
237 }366 }
238367
239 pub fn extend_with_field(self, key: IStr, value: ObjMember) -> Self {368 // pub fn extend_with(self, key: )
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 }
244369
245 fn get_raw(&self, key: IStr, real_this: Option<&Self>) -> Result<Option<Val>> {370 fn get_raw(&self, key: IStr, real_this: Option<&Self>) -> Result<Option<Val>> {
246 let real_this = real_this.unwrap_or(self);371 let real_this = real_this.unwrap_or(self);
339 super_obj: Option<ObjValue>,464 super_obj: Option<ObjValue>,
340 map: GcHashMap<IStr, ObjMember>,465 map: GcHashMap<IStr, ObjMember>,
341 assertions: Vec<TraceBox<dyn ObjectAssertion>>,466 assertions: Vec<TraceBox<dyn ObjectAssertion>>,
467 next_field_index: FieldIndex,
342}468}
343impl ObjValueBuilder {469impl ObjValueBuilder {
344 pub fn new() -> Self {470 pub fn new() -> Self {
349 super_obj: None,475 super_obj: None,
350 map: GcHashMap::with_capacity(capacity),476 map: GcHashMap::with_capacity(capacity),
351 assertions: Vec::new(),477 assertions: Vec::new(),
478 next_field_index: FieldIndex::default(),
352 }479 }
353 }480 }
354 pub fn reserve_asserts(&mut self, capacity: usize) -> &mut Self {481 pub fn reserve_asserts(&mut self, capacity: usize) -> &mut Self {
364 self.assertions.push(assertion);491 self.assertions.push(assertion);
365 self492 self
366 }493 }
367 pub fn member(&mut self, name: IStr) -> ObjMemberBuilder {494 pub fn member(&mut self, name: IStr) -> ObjMemberBuilder<ValueBuilder> {
495 let field_index = self.next_field_index;
496 self.next_field_index = self.next_field_index.next();
368 ObjMemberBuilder {497 ObjMemberBuilder::new(ValueBuilder(self), name, field_index)
369 value: self,
370 name,
371 add: false,
372 visibility: Visibility::Normal,
373 location: None,
374 }
375 }498 }
376499
377 pub fn build(self) -> ObjValue {500 pub fn build(self) -> ObjValue {
385}508}
386509
387#[must_use = "value not added unless binding() was called"]510#[must_use = "value not added unless binding() was called"]
388pub struct ObjMemberBuilder<'v> {511pub struct ObjMemberBuilder<Kind> {
389 value: &'v mut ObjValueBuilder,512 kind: Kind,
390 name: IStr,513 name: IStr,
391 add: bool,514 add: bool,
392 visibility: Visibility,515 visibility: Visibility,
516 original_index: FieldIndex,
393 location: Option<ExprLocation>,517 location: Option<ExprLocation>,
394}518}
395519
396#[allow(clippy::missing_const_for_fn)]520#[allow(clippy::missing_const_for_fn)]
397impl<'v> ObjMemberBuilder<'v> {521impl<Kind> ObjMemberBuilder<Kind> {
522 pub(crate) fn new(kind: Kind, name: IStr, original_index: FieldIndex) -> Self {
523 Self {
524 kind,
525 name,
526 original_index,
527 add: false,
528 visibility: Visibility::Normal,
529 location: None,
530 }
531 }
532
533 pub const fn with_add(mut self, add: bool) -> Self {
534 self.add = add;
535 self
536 }
537 pub fn add(self) -> Self {
538 self.with_add(true)
539 }
540 pub fn with_visibility(mut self, visibility: Visibility) -> Self {
541 self.visibility = visibility;
542 self
543 }
544 pub fn hide(self) -> Self {
545 self.with_visibility(Visibility::Hidden)
546 }
547 pub fn with_location(mut self, location: ExprLocation) -> Self {
548 self.location = Some(location);
549 self
550 }
551 fn build_member(self, binding: LazyBinding) -> (Kind, IStr, ObjMember) {
552 (
553 self.kind,
554 self.name,
555 ObjMember {
556 add: self.add,
557 visibility: self.visibility,
558 original_index: self.original_index,
559 invoke: binding,
560 location: self.location,
561 },
562 )
563 }
564}
565
398 pub const fn with_add(mut self, add: bool) -> Self {566pub struct ValueBuilder<'v>(&'v mut ObjValueBuilder);
399 self.add = add;567impl<'v> ObjMemberBuilder<ValueBuilder<'v>> {
400 self
401 }
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 self
408 }
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 self
415 }
416 pub fn value(self, value: Val) -> Result<()> {568 pub fn value(self, value: Val) -> Result<()> {
417 self.binding(LazyBinding::Bound(LazyVal::new_resolved(value)))569 self.binding(LazyBinding::Bound(LazyVal::new_resolved(value)))
418 }570 }
419 pub fn bindable(self, bindable: TraceBox<dyn Bindable>) -> Result<()> {571 pub fn bindable(self, bindable: TraceBox<dyn Bindable>) -> Result<()> {
420 self.binding(LazyBinding::Bindable(Cc::new(bindable)))572 self.binding(LazyBinding::Bindable(Cc::new(bindable)))
421 }573 }
422 pub fn binding(self, binding: LazyBinding) -> Result<()> {574 pub fn binding(self, binding: LazyBinding) -> Result<()> {
575 let (receiver, name, member) = self.build_member(binding);
576 let location = member.location.clone();
423 let old = self.value.map.insert(577 let old = receiver.0.map.insert(name.clone(), member);
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() {578 if old.is_some() {
433 push_frame(579 push_frame(
434 CallLocation(self.location.as_ref()),580 CallLocation(location.as_ref()),
435 || format!("field <{}> initializtion", self.name.clone()),581 || format!("field <{}> initializtion", name.clone()),
436 || throw!(DuplicateFieldName(self.name.clone())),582 || throw!(DuplicateFieldName(name.clone())),
437 )?583 )?
438 }584 }
439 Ok(())585 Ok(())
440 }586 }
441}587}
588
589pub struct ExtendBuilder<'v>(&'v mut ObjValue);
590impl<'v> ObjMemberBuilder<ExtendBuilder<'v>> {
591 pub fn value(self, value: Val) {
592 self.binding(LazyBinding::Bound(LazyVal::new_resolved(value)))
593 }
594 pub fn bindable(self, bindable: TraceBox<dyn Bindable>) {
595 self.binding(LazyBinding::Bindable(Cc::new(bindable)))
596 }
597 pub fn binding(self, binding: LazyBinding) -> () {
598 let (receiver, name, member) = self.build_member(binding);
599 let new = receiver.0.clone();
600 *receiver.0 = new.extend_with_raw_member(name, member)
601 }
602}
442603
modifiedcrates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth
167#[derive(Clone)]167#[derive(Clone)]
168pub enum ManifestFormat {168pub enum ManifestFormat {
169 YamlStream(Box<ManifestFormat>),169 YamlStream(Box<ManifestFormat>),
170 Yaml(usize),170 Yaml {
171 padding: usize,
172 #[cfg(feature = "exp-preserve-order")]
173 preserve_order: bool,
174 },
171 Json(usize),175 Json {
176 padding: usize,
177 #[cfg(feature = "exp-preserve-order")]
178 preserve_order: bool,
179 },
172 ToString,180 ToString,
173 String,181 String,
174}182}
183impl ManifestFormat {
184 #[cfg(feature = "exp-preserve-order")]
185 fn preserve_order(&self) -> bool {
186 match self {
187 ManifestFormat::YamlStream(s) => s.preserve_order(),
188 ManifestFormat::Yaml { preserve_order, .. } => *preserve_order,
189 ManifestFormat::Json { preserve_order, .. } => *preserve_order,
190 ManifestFormat::ToString => false,
191 ManifestFormat::String => false,
192 }
193 }
194}
175195
176#[derive(Debug, Clone, Trace)]196#[derive(Debug, Clone, Trace)]
177pub struct Slice {197pub struct Slice {
559 mtype: ManifestType::ToString,579 mtype: ManifestType::ToString,
560 newline: "\n",580 newline: "\n",
561 key_val_sep: ": ",581 key_val_sep: ": ",
582 #[cfg(feature = "exp-preserve-order")]
583 preserve_order: false,
562 },584 },
563 )?585 )?
564 .into(),586 .into(),
572 _ => throw!(MultiManifestOutputIsNotAObject),594 _ => throw!(MultiManifestOutputIsNotAObject),
573 };595 };
574 let keys = obj.fields();596 let keys = obj.fields(
597 #[cfg(feature = "exp-preserve-order")]
598 ty.preserve_order(),
599 );
575 let mut out = Vec::with_capacity(keys.len());600 let mut out = Vec::with_capacity(keys.len());
576 for key in keys {601 for key in keys {
622647
623 out.into()648 out.into()
624 }649 }
625 ManifestFormat::Yaml(padding) => self.to_yaml(*padding)?,650 ManifestFormat::Yaml {
651 padding,
652 #[cfg(feature = "exp-preserve-order")]
653 preserve_order,
654 } => self.to_yaml(
655 *padding,
656 #[cfg(feature = "exp-preserve-order")]
657 *preserve_order,
658 )?,
626 ManifestFormat::Json(padding) => self.to_json(*padding)?,659 ManifestFormat::Json {
660 padding,
661 #[cfg(feature = "exp-preserve-order")]
662 preserve_order,
663 } => self.to_json(
664 *padding,
665 #[cfg(feature = "exp-preserve-order")]
666 *preserve_order,
667 )?,
627 ManifestFormat::ToString => self.to_string()?,668 ManifestFormat::ToString => self.to_string()?,
628 ManifestFormat::String => match self {669 ManifestFormat::String => match self {
635 /// For manifestification676 /// For manifestification
636 pub fn to_json(&self, padding: usize) -> Result<IStr> {677 pub fn to_json(
678 &self,
679 padding: usize,
680 #[cfg(feature = "exp-preserve-order")] preserve_order: bool,
681 ) -> Result<IStr> {
637 manifest_json_ex(682 manifest_json_ex(
638 self,683 self,
645 },690 },
646 newline: "\n",691 newline: "\n",
647 key_val_sep: ": ",692 key_val_sep: ": ",
693 #[cfg(feature = "exp-preserve-order")]
694 preserve_order,
648 },695 },
649 )696 )
650 .map(|s| s.into())697 .map(|s| s.into())
651 }698 }
652699
653 /// Calls `std.manifestJson`700 /// Calls `std.manifestJson`
654 pub fn to_std_json(&self, padding: usize) -> Result<Rc<str>> {701 pub fn to_std_json(
702 &self,
703 padding: usize,
704 #[cfg(feature = "exp-preserve-order")] preserve_order: bool,
705 ) -> Result<Rc<str>> {
655 manifest_json_ex(706 manifest_json_ex(
656 self,707 self,
659 mtype: ManifestType::Std,710 mtype: ManifestType::Std,
660 newline: "\n",711 newline: "\n",
661 key_val_sep: ": ",712 key_val_sep: ": ",
713 #[cfg(feature = "exp-preserve-order")]
714 preserve_order,
662 },715 },
663 )716 )
664 .map(|s| s.into())717 .map(|s| s.into())
665 }718 }
666719
667 pub fn to_yaml(&self, padding: usize) -> Result<IStr> {720 pub fn to_yaml(
721 &self,
722 padding: usize,
723 #[cfg(feature = "exp-preserve-order")] preserve_order: bool,
724 ) -> Result<IStr> {
668 let padding = &" ".repeat(padding);725 let padding = &" ".repeat(padding);
669 manifest_yaml_ex(726 manifest_yaml_ex(
672 padding,729 padding,
673 arr_element_padding: padding,730 arr_element_padding: padding,
674 quote_keys: false,731 quote_keys: false,
732 #[cfg(feature = "exp-preserve-order")]
733 preserve_order,
675 },734 },
676 )735 )
677 .map(|s| s.into())736 .map(|s| s.into())
734 return Ok(true);793 return Ok(true);
735 }794 }
736 let fields = a.fields();795 let fields = a.fields(
796 #[cfg(feature = "exp-preserve-order")]
797 false,
798 );
737 if fields != b.fields() {799 if fields
800 != b.fields(
801 #[cfg(feature = "exp-preserve-order")]
802 false,
803 ) {
738 return Ok(false);804 return Ok(false);
739 }805 }
modifiedcrates/jrsonnet-macros/src/lib.rsdiffbeforeafterboth
122 ty: Box<Type>,122 ty: Box<Type>,
123 is_option: bool,123 is_option: bool,
124 name: String,124 name: String,
125 cfg_attrs: Vec<Attribute>,
125 // ident: Ident,126 // ident: Ident,
126 },127 },
127 Lazy {128 Lazy {
134135
135impl ArgInfo {136impl ArgInfo {
136 fn parse(arg: &FnArg) -> Result<Self> {137 fn parse(arg: &FnArg) -> Result<Self> {
137 let typed = match arg {138 let arg = match arg {
138 FnArg::Receiver(_) => unreachable!(),139 FnArg::Receiver(_) => unreachable!(),
139 FnArg::Typed(a) => a,140 FnArg::Typed(a) => a,
140 };141 };
141 let ident = match &typed.pat as &Pat {142 let ident = match &arg.pat as &Pat {
142 Pat::Ident(i) => i.ident.clone(),143 Pat::Ident(i) => i.ident.clone(),
143 _ => {144 _ => return Err(Error::new(arg.pat.span(), "arg should be plain identifier")),
144 return Err(Error::new(
145 typed.pat.span(),
146 "arg should be plain identifier",
147 ))
148 }
149 };145 };
150 let ty = &typed.ty;146 let ty = &arg.ty;
151 if type_is_path(ty, "CallLocation").is_some() {147 if type_is_path(ty, "CallLocation").is_some() {
152 return Ok(Self::Location);148 return Ok(Self::Location);
153 } else if type_is_path(ty, "Self").is_some() {149 } else if type_is_path(ty, "Self").is_some() {
172 (false, ty.clone())168 (false, ty.clone())
173 };169 };
170
171 let cfg_attrs = arg
172 .attrs
173 .iter()
174 .filter(|a| a.path.is_ident("cfg"))
175 .cloned()
176 .collect();
174177
175 Ok(Self::Normal {178 Ok(Self::Normal {
176 ty,179 ty,
177 is_option,180 is_option,
178 name: ident.to_string(),181 name: ident.to_string(),
179 // ident,182 cfg_attrs,
180 })183 })
181 }184 }
182}185}
214 .collect::<Result<Vec<_>>>()?;217 .collect::<Result<Vec<_>>>()?;
215218
216 let params_desc = args.iter().flat_map(|a| match a {219 let params_desc = args.iter().flat_map(|a| match a {
217 ArgInfo::Normal {220 ArgInfo::Normal {
218 is_option, name, ..221 is_option,
219 }222 name,
223 cfg_attrs,
224 ..
225 } => Some(quote! {
226 #(#cfg_attrs)*
227 BuiltinParam {
228 name: std::borrow::Cow::Borrowed(#name),
229 has_default: #is_option,
230 },
231 }),
220 | ArgInfo::Lazy { is_option, name } => Some(quote! {232 ArgInfo::Lazy { is_option, name } => Some(quote! {
221 BuiltinParam {233 BuiltinParam {
222 name: std::borrow::Cow::Borrowed(#name),234 name: std::borrow::Cow::Borrowed(#name),
223 has_default: #is_option,235 has_default: #is_option,
232 ty,244 ty,
233 is_option,245 is_option,
234 name,246 name,
235 // ident,247 cfg_attrs,
236 } => {248 } => {
237 let eval = quote! {::jrsonnet_evaluator::push_description_frame(249 let eval = quote! {::jrsonnet_evaluator::push_description_frame(
238 || format!("argument <{}> evaluation", #name),250 || format!("argument <{}> evaluation", #name),
239 || <#ty>::try_from(value.evaluate()?),251 || <#ty>::try_from(value.evaluate()?),
240 )?};252 )?};
241 if *is_option {253 let value = if *is_option {
242 quote! {if let Some(value) = parsed.get(#name) {254 quote! {if let Some(value) = parsed.get(#name) {
243 Some(#eval)255 Some(#eval)
244 } else {256 } else {
249 let value = parsed.get(#name).expect("args shape is checked");261 let value = parsed.get(#name).expect("args shape is checked");
250 #eval262 #eval
251 }}263 },}
252 }264 };
265 quote! {
266 #(#cfg_attrs)*
267 #value
268 }
253 }269 }
254 ArgInfo::Lazy { is_option, name } => {270 ArgInfo::Lazy { is_option, name } => {
255 if *is_option {271 if *is_option {
309 parser::ExprLocation,325 parser::ExprLocation,
310 };326 };
311 const PARAMS: &'static [BuiltinParam] = &[327 const PARAMS: &'static [BuiltinParam] = &[
312 #(#params_desc),*328 #(#params_desc)*
313 ];329 ];
314330
315 #static_ext331 #static_ext
326 fn call(&self, context: Context, location: CallLocation, args: &dyn ArgsLike) -> Result<Val> {342 fn call(&self, context: Context, location: CallLocation, args: &dyn ArgsLike) -> Result<Val> {
327 let parsed = parse_builtin_call(context, &PARAMS, args, false)?;343 let parsed = parse_builtin_call(context, &PARAMS, args, false)?;
328344
329 let result: #result = #name(#(#pass),*);345 let result: #result = #name(#(#pass)*);
330 let result = result?;346 let result = result?;
331 result.try_into()347 result.try_into()
332 }348 }