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.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);
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.rsdiffbeforeafterboth1use std::{2 cell::RefCell,3 fmt::Debug,4 hash::{Hash, Hasher},5};67use gcmodule::{Cc, Trace, Weak};8use jrsonnet_interner::IStr;9use jrsonnet_parser::{ExprLocation, Visibility};10use rustc_hash::FxHashMap;1112use crate::{13 cc_ptr_eq,14 error::{Error::*, LocError},15 function::CallLocation,16 gc::{GcHashMap, GcHashSet, TraceBox},17 operator::evaluate_add_op,18 push_frame, throw, weak_ptr_eq, weak_raw, Bindable, LazyBinding, LazyVal, Result, Val,19};2021#[derive(Debug, Trace)]22pub struct ObjMember {23 pub add: bool,24 pub visibility: Visibility,25 pub invoke: LazyBinding,26 pub location: Option<ExprLocation>,27}2829pub trait ObjectAssertion: Trace {30 fn run(&self, this: Option<ObjValue>, super_obj: Option<ObjValue>) -> Result<()>;31}3233// Field => This34type CacheKey = (IStr, WeakObjValue);3536#[derive(Trace)]37enum CacheValue {38 Cached(Val),39 NotFound,40 Pending,41 Errored(LocError),42}4344#[derive(Trace)]45#[force_tracking]46pub struct ObjValueInternals {47 super_obj: Option<ObjValue>,48 assertions: Cc<Vec<TraceBox<dyn ObjectAssertion>>>,49 assertions_ran: RefCell<GcHashSet<ObjValue>>,50 this_obj: Option<ObjValue>,51 this_entries: Cc<GcHashMap<IStr, ObjMember>>,52 value_cache: RefCell<GcHashMap<CacheKey, CacheValue>>,53}5455#[derive(Clone, Trace)]56pub struct WeakObjValue(#[skip_trace] pub(crate) Weak<ObjValueInternals>);5758impl PartialEq for WeakObjValue {59 fn eq(&self, other: &Self) -> bool {60 weak_ptr_eq(self.0.clone(), other.0.clone())61 }62}6364impl Eq for WeakObjValue {}65impl Hash for WeakObjValue {66 fn hash<H: Hasher>(&self, hasher: &mut H) {67 hasher.write_usize(weak_raw(self.0.clone()) as usize)68 }69}7071#[derive(Clone, Trace)]72pub struct ObjValue(pub(crate) Cc<ObjValueInternals>);73impl Debug for ObjValue {74 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {75 if let Some(super_obj) = self.0.super_obj.as_ref() {76 if f.alternate() {77 write!(f, "{:#?}", super_obj)?;78 } else {79 write!(f, "{:?}", super_obj)?;80 }81 write!(f, " + ")?;82 }83 let mut debug = f.debug_struct("ObjValue");84 for (name, member) in self.0.this_entries.iter() {85 debug.field(name, member);86 }87 debug.finish_non_exhaustive()88 }89}9091impl ObjValue {92 pub fn new(93 super_obj: Option<Self>,94 this_entries: Cc<GcHashMap<IStr, ObjMember>>,95 assertions: Cc<Vec<TraceBox<dyn ObjectAssertion>>>,96 ) -> Self {97 Self(Cc::new(ObjValueInternals {98 super_obj,99 assertions,100 assertions_ran: RefCell::new(GcHashSet::new()),101 this_obj: None,102 this_entries,103 value_cache: RefCell::new(GcHashMap::new()),104 }))105 }106 pub fn new_empty() -> Self {107 Self::new(None, Cc::new(GcHashMap::new()), Cc::new(Vec::new()))108 }109 pub fn extend_from(&self, super_obj: Self) -> Self {110 match &self.0.super_obj {111 None => Self::new(112 Some(super_obj),113 self.0.this_entries.clone(),114 self.0.assertions.clone(),115 ),116 Some(v) => Self::new(117 Some(v.extend_from(super_obj)),118 self.0.this_entries.clone(),119 self.0.assertions.clone(),120 ),121 }122 }123 pub fn with_this(&self, this_obj: Self) -> Self {124 Self(Cc::new(ObjValueInternals {125 super_obj: self.0.super_obj.clone(),126 assertions: self.0.assertions.clone(),127 assertions_ran: RefCell::new(GcHashSet::new()),128 this_obj: Some(this_obj),129 this_entries: self.0.this_entries.clone(),130 value_cache: RefCell::new(GcHashMap::new()),131 }))132 }133134 pub fn is_empty(&self) -> bool {135 if !self.0.this_entries.is_empty() {136 return false;137 }138 self.0139 .super_obj140 .as_ref()141 .map(|s| s.is_empty())142 .unwrap_or(true)143 }144145 /// Run callback for every field found in object146 pub(crate) fn enum_fields(&self, handler: &mut impl FnMut(&IStr, &ObjMember) -> bool) -> bool {147 if let Some(s) = &self.0.super_obj {148 if s.enum_fields(handler) {149 return true;150 }151 }152 for (name, member) in self.0.this_entries.iter() {153 if handler(name, member) {154 return true;155 }156 }157 false158 }159160 pub fn fields_visibility(&self) -> FxHashMap<IStr, bool> {161 let mut out = FxHashMap::default();162 self.enum_fields(&mut |name, member| {163 match member.visibility {164 Visibility::Normal => {165 let entry = out.entry(name.to_owned());166 entry.or_insert(true);167 }168 Visibility::Hidden => {169 out.insert(name.to_owned(), false);170 }171 Visibility::Unhide => {172 out.insert(name.to_owned(), true);173 }174 };175 false176 });177 out178 }179 pub fn fields_ex(&self, include_hidden: bool) -> Vec<IStr> {180 let mut fields: Vec<_> = self181 .fields_visibility()182 .into_iter()183 .filter(|(_k, v)| include_hidden || *v)184 .map(|(k, _)| k)185 .collect();186 fields.sort_unstable();187 fields188 }189 pub fn fields(&self) -> Vec<IStr> {190 self.fields_ex(false)191 }192193 pub fn field_visibility(&self, name: IStr) -> Option<Visibility> {194 if let Some(m) = self.0.this_entries.get(&name) {195 Some(match &m.visibility {196 Visibility::Normal => self197 .0198 .super_obj199 .as_ref()200 .and_then(|super_obj| super_obj.field_visibility(name))201 .unwrap_or(Visibility::Normal),202 v => *v,203 })204 } else if let Some(super_obj) = &self.0.super_obj {205 super_obj.field_visibility(name)206 } else {207 None208 }209 }210211 fn has_field_include_hidden(&self, name: IStr) -> bool {212 if self.0.this_entries.contains_key(&name) {213 true214 } else if let Some(super_obj) = &self.0.super_obj {215 super_obj.has_field_include_hidden(name)216 } else {217 false218 }219 }220221 pub fn has_field_ex(&self, name: IStr, include_hidden: bool) -> bool {222 if include_hidden {223 self.has_field_include_hidden(name)224 } else {225 self.has_field(name)226 }227 }228 pub fn has_field(&self, name: IStr) -> bool {229 self.field_visibility(name)230 .map(|v| v.is_visible())231 .unwrap_or(false)232 }233234 pub fn get(&self, key: IStr) -> Result<Option<Val>> {235 self.run_assertions()?;236 self.get_raw(key, self.0.this_obj.as_ref())237 }238239 pub fn extend_with_field(self, key: IStr, value: ObjMember) -> Self {240 let mut new = GcHashMap::with_capacity(1);241 new.insert(key, value);242 Self::new(Some(self), Cc::new(new), Cc::new(Vec::new()))243 }244245 fn get_raw(&self, key: IStr, real_this: Option<&Self>) -> Result<Option<Val>> {246 let real_this = real_this.unwrap_or(self);247 let cache_key = (key.clone(), WeakObjValue(real_this.0.downgrade()));248249 if let Some(v) = self.0.value_cache.borrow().get(&cache_key) {250 return Ok(match v {251 CacheValue::Cached(v) => Some(v.clone()),252 CacheValue::NotFound => None,253 CacheValue::Pending => throw!(InfiniteRecursionDetected),254 CacheValue::Errored(e) => return Err(e.clone()),255 });256 }257 self.0258 .value_cache259 .borrow_mut()260 .insert(cache_key.clone(), CacheValue::Pending);261 let value = match (self.0.this_entries.get(&key), &self.0.super_obj) {262 (Some(k), None) => Ok(Some(self.evaluate_this(k, real_this)?)),263 (Some(k), Some(s)) => {264 let our = self.evaluate_this(k, real_this)?;265 if k.add {266 s.get_raw(key, Some(real_this))?267 .map_or(Ok(Some(our.clone())), |v| {268 Ok(Some(evaluate_add_op(&v, &our)?))269 })270 } else {271 Ok(Some(our))272 }273 }274 (None, Some(s)) => s.get_raw(key, Some(real_this)),275 (None, None) => Ok(None),276 };277 let value = match value {278 Ok(v) => v,279 Err(e) => {280 self.0281 .value_cache282 .borrow_mut()283 .insert(cache_key, CacheValue::Errored(e.clone()));284 return Err(e);285 }286 };287 self.0.value_cache.borrow_mut().insert(288 cache_key,289 match &value {290 Some(v) => CacheValue::Cached(v.clone()),291 None => CacheValue::NotFound,292 },293 );294 Ok(value)295 }296 fn evaluate_this(&self, v: &ObjMember, real_this: &Self) -> Result<Val> {297 v.invoke298 .evaluate(Some(real_this.clone()), self.0.super_obj.clone())?299 .evaluate()300 }301302 fn run_assertions_raw(&self, real_this: &Self) -> Result<()> {303 if self.0.assertions_ran.borrow_mut().insert(real_this.clone()) {304 for assertion in self.0.assertions.iter() {305 if let Err(e) = assertion.run(Some(real_this.clone()), self.0.super_obj.clone()) {306 self.0.assertions_ran.borrow_mut().remove(real_this);307 return Err(e);308 }309 }310 if let Some(super_obj) = &self.0.super_obj {311 super_obj.run_assertions_raw(real_this)?;312 }313 }314 Ok(())315 }316 pub fn run_assertions(&self) -> Result<()> {317 self.run_assertions_raw(self)318 }319320 pub fn ptr_eq(a: &Self, b: &Self) -> bool {321 cc_ptr_eq(&a.0, &b.0)322 }323}324325impl PartialEq for ObjValue {326 fn eq(&self, other: &Self) -> bool {327 cc_ptr_eq(&self.0, &other.0)328 }329}330331impl Eq for ObjValue {}332impl Hash for ObjValue {333 fn hash<H: Hasher>(&self, hasher: &mut H) {334 hasher.write_usize(&*self.0 as *const _ as usize)335 }336}337338pub struct ObjValueBuilder {339 super_obj: Option<ObjValue>,340 map: GcHashMap<IStr, ObjMember>,341 assertions: Vec<TraceBox<dyn ObjectAssertion>>,342}343impl ObjValueBuilder {344 pub fn new() -> Self {345 Self::with_capacity(0)346 }347 pub fn with_capacity(capacity: usize) -> Self {348 Self {349 super_obj: None,350 map: GcHashMap::with_capacity(capacity),351 assertions: Vec::new(),352 }353 }354 pub fn reserve_asserts(&mut self, capacity: usize) -> &mut Self {355 self.assertions.reserve_exact(capacity);356 self357 }358 pub fn with_super(&mut self, super_obj: ObjValue) -> &mut Self {359 self.super_obj = Some(super_obj);360 self361 }362363 pub fn assert(&mut self, assertion: TraceBox<dyn ObjectAssertion>) -> &mut Self {364 self.assertions.push(assertion);365 self366 }367 pub fn member(&mut self, name: IStr) -> ObjMemberBuilder {368 ObjMemberBuilder {369 value: self,370 name,371 add: false,372 visibility: Visibility::Normal,373 location: None,374 }375 }376377 pub fn build(self) -> ObjValue {378 ObjValue::new(self.super_obj, Cc::new(self.map), Cc::new(self.assertions))379 }380}381impl Default for ObjValueBuilder {382 fn default() -> Self {383 Self::with_capacity(0)384 }385}386387#[must_use = "value not added unless binding() was called"]388pub struct ObjMemberBuilder<'v> {389 value: &'v mut ObjValueBuilder,390 name: IStr,391 add: bool,392 visibility: Visibility,393 location: Option<ExprLocation>,394}395396#[allow(clippy::missing_const_for_fn)]397impl<'v> ObjMemberBuilder<'v> {398 pub const fn with_add(mut self, add: bool) -> Self {399 self.add = add;400 self401 }402 pub fn add(self) -> Self {403 self.with_add(true)404 }405 pub fn with_visibility(mut self, visibility: Visibility) -> Self {406 self.visibility = visibility;407 self408 }409 pub fn hide(self) -> Self {410 self.with_visibility(Visibility::Hidden)411 }412 pub fn with_location(mut self, location: ExprLocation) -> Self {413 self.location = Some(location);414 self415 }416 pub fn value(self, value: Val) -> Result<()> {417 self.binding(LazyBinding::Bound(LazyVal::new_resolved(value)))418 }419 pub fn bindable(self, bindable: TraceBox<dyn Bindable>) -> Result<()> {420 self.binding(LazyBinding::Bindable(Cc::new(bindable)))421 }422 pub fn binding(self, binding: LazyBinding) -> Result<()> {423 let old = self.value.map.insert(424 self.name.clone(),425 ObjMember {426 add: self.add,427 visibility: self.visibility,428 invoke: binding,429 location: self.location.clone(),430 },431 );432 if old.is_some() {433 push_frame(434 CallLocation(self.location.as_ref()),435 || format!("field <{}> initializtion", self.name.clone()),436 || throw!(DuplicateFieldName(self.name.clone())),437 )?438 }439 Ok(())440 }441}1use std::{2 cell::RefCell,3 fmt::Debug,4 hash::{Hash, Hasher},5};67use gcmodule::{Cc, Trace, Weak};8use jrsonnet_interner::IStr;9use jrsonnet_parser::{ExprLocation, Visibility};10use rustc_hash::FxHashMap;1112use crate::{13 cc_ptr_eq,14 error::{Error::*, LocError},15 function::CallLocation,16 gc::{GcHashMap, GcHashSet, TraceBox},17 operator::evaluate_add_op,18 push_frame, throw, weak_ptr_eq, weak_raw, Bindable, LazyBinding, LazyVal, Result, Val,19};2021#[cfg(not(feature = "exp-preserve-order"))]22pub(crate) mod ordering {23 use gcmodule::Trace;2425 #[derive(Clone, Copy, Default, Debug, Trace)]26 pub struct FieldIndex;27 impl FieldIndex {28 pub fn next(self) -> Self {29 Self30 }31 }3233 #[derive(Clone, Copy, Default, Debug, Trace)]34 pub struct SuperDepth;35 impl SuperDepth {36 pub fn deeper(self) -> Self {37 Self38 }39 }4041 #[derive(Clone, Copy)]42 pub struct FieldSortKey;43 impl FieldSortKey {44 pub fn new(_: SuperDepth, _: FieldIndex) -> Self {45 Self46 }47 }48}4950#[cfg(feature = "exp-preserve-order")]51mod ordering {52 use std::cmp::Reverse;5354 use gcmodule::Trace;5556 #[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 }6364 #[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 }7172 #[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 self81 } else if self.0 .0 < other.0 .0 {82 other83 } else {84 unreachable!("object can't have two fields with same name")85 }86 }87 }88}8990pub(crate) use ordering::*;9192#[derive(Debug, Trace)]93pub struct ObjMember {94 pub add: bool,95 pub visibility: Visibility,96 original_index: FieldIndex,97 pub invoke: LazyBinding,98 pub location: Option<ExprLocation>,99}100101pub trait ObjectAssertion: Trace {102 fn run(&self, this: Option<ObjValue>, super_obj: Option<ObjValue>) -> Result<()>;103}104105// Field => This106type CacheKey = (IStr, WeakObjValue);107108#[derive(Trace)]109enum CacheValue {110 Cached(Val),111 NotFound,112 Pending,113 Errored(LocError),114}115116#[derive(Trace)]117#[force_tracking]118pub struct ObjValueInternals {119 super_obj: Option<ObjValue>,120 assertions: Cc<Vec<TraceBox<dyn ObjectAssertion>>>,121 assertions_ran: RefCell<GcHashSet<ObjValue>>,122 this_obj: Option<ObjValue>,123 this_entries: Cc<GcHashMap<IStr, ObjMember>>,124 value_cache: RefCell<GcHashMap<CacheKey, CacheValue>>,125}126127#[derive(Clone, Trace)]128pub struct WeakObjValue(#[skip_trace] pub(crate) Weak<ObjValueInternals>);129130impl PartialEq for WeakObjValue {131 fn eq(&self, other: &Self) -> bool {132 weak_ptr_eq(self.0.clone(), other.0.clone())133 }134}135136impl Eq for WeakObjValue {}137impl Hash for WeakObjValue {138 fn hash<H: Hasher>(&self, hasher: &mut H) {139 hasher.write_usize(weak_raw(self.0.clone()) as usize)140 }141}142143#[derive(Clone, Trace)]144pub struct ObjValue(pub(crate) Cc<ObjValueInternals>);145impl Debug for ObjValue {146 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {147 if let Some(super_obj) = self.0.super_obj.as_ref() {148 if f.alternate() {149 write!(f, "{:#?}", super_obj)?;150 } else {151 write!(f, "{:?}", super_obj)?;152 }153 write!(f, " + ")?;154 }155 let mut debug = f.debug_struct("ObjValue");156 for (name, member) in self.0.this_entries.iter() {157 debug.field(name, member);158 }159 debug.finish_non_exhaustive()160 }161}162163impl ObjValue {164 pub fn new(165 super_obj: Option<Self>,166 this_entries: Cc<GcHashMap<IStr, ObjMember>>,167 assertions: Cc<Vec<TraceBox<dyn ObjectAssertion>>>,168 ) -> Self {169 Self(Cc::new(ObjValueInternals {170 super_obj,171 assertions,172 assertions_ran: RefCell::new(GcHashSet::new()),173 this_obj: None,174 this_entries,175 value_cache: RefCell::new(GcHashMap::new()),176 }))177 }178 pub fn new_empty() -> Self {179 Self::new(None, Cc::new(GcHashMap::new()), Cc::new(Vec::new()))180 }181 pub fn extend_from(&self, super_obj: Self) -> Self {182 match &self.0.super_obj {183 None => Self::new(184 Some(super_obj),185 self.0.this_entries.clone(),186 self.0.assertions.clone(),187 ),188 Some(v) => Self::new(189 Some(v.extend_from(super_obj)),190 self.0.this_entries.clone(),191 self.0.assertions.clone(),192 ),193 }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 }203 pub fn with_this(&self, this_obj: Self) -> Self {204 Self(Cc::new(ObjValueInternals {205 super_obj: self.0.super_obj.clone(),206 assertions: self.0.assertions.clone(),207 assertions_ran: RefCell::new(GcHashSet::new()),208 this_obj: Some(this_obj),209 this_entries: self.0.this_entries.clone(),210 value_cache: RefCell::new(GcHashMap::new()),211 }))212 }213214 pub fn len(&self) -> usize {215 self.fields_visibility()216 .into_iter()217 .filter(|(_, (visible, _))| *visible)218 .count()219 }220221 pub fn is_empty(&self) -> bool {222 if !self.0.this_entries.is_empty() {223 return false;224 }225 self.0226 .super_obj227 .as_ref()228 .map(|s| s.is_empty())229 .unwrap_or(true)230 }231232 /// Run callback for every field found in object233 pub(crate) fn enum_fields(234 &self,235 depth: SuperDepth,236 handler: &mut impl FnMut(SuperDepth, &IStr, &ObjMember) -> bool,237 ) -> bool {238 if let Some(s) = &self.0.super_obj {239 if s.enum_fields(depth.deeper(), handler) {240 return true;241 }242 }243 for (name, member) in self.0.this_entries.iter() {244 if handler(depth, name, member) {245 return true;246 }247 }248 false249 }250251 pub fn fields_visibility(&self) -> FxHashMap<IStr, (bool, FieldSortKey)> {252 let mut out = FxHashMap::default();253 self.enum_fields(SuperDepth::default(), &mut |depth, name, member| {254 let new_sort_key = FieldSortKey::new(depth, member.original_index);255 match member.visibility {256 Visibility::Normal => {257 let entry = out.entry(name.to_owned());258 let v = entry.or_insert((true, new_sort_key));259 v.1 = new_sort_key;260 }261 Visibility::Hidden => {262 out.insert(name.to_owned(), (false, new_sort_key));263 }264 Visibility::Unhide => {265 out.insert(name.to_owned(), (true, new_sort_key));266 }267 };268 false269 });270 out271 }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<_>) = self280 .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 indexes288 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 = k299 }300 fields[j] = x;301 }302 return fields;303 }304305 let mut fields: Vec<_> = self306 .fields_visibility()307 .into_iter()308 .filter(|(_, (visible, _))| include_hidden || *visible)309 .map(|(k, _)| k)310 .collect();311 fields.sort_unstable();312 fields313 }314 pub fn fields(&self, #[cfg(feature = "exp-preserve-order")] preserve_order: bool) -> Vec<IStr> {315 self.fields_ex(316 false,317 #[cfg(feature = "exp-preserve-order")]318 preserve_order,319 )320 }321322 pub fn field_visibility(&self, name: IStr) -> Option<Visibility> {323 if let Some(m) = self.0.this_entries.get(&name) {324 Some(match &m.visibility {325 Visibility::Normal => self326 .0327 .super_obj328 .as_ref()329 .and_then(|super_obj| super_obj.field_visibility(name))330 .unwrap_or(Visibility::Normal),331 v => *v,332 })333 } else if let Some(super_obj) = &self.0.super_obj {334 super_obj.field_visibility(name)335 } else {336 None337 }338 }339340 fn has_field_include_hidden(&self, name: IStr) -> bool {341 if self.0.this_entries.contains_key(&name) {342 true343 } else if let Some(super_obj) = &self.0.super_obj {344 super_obj.has_field_include_hidden(name)345 } else {346 false347 }348 }349350 pub fn has_field_ex(&self, name: IStr, include_hidden: bool) -> bool {351 if include_hidden {352 self.has_field_include_hidden(name)353 } else {354 self.has_field(name)355 }356 }357 pub fn has_field(&self, name: IStr) -> bool {358 self.field_visibility(name)359 .map(|v| v.is_visible())360 .unwrap_or(false)361 }362363 pub fn get(&self, key: IStr) -> Result<Option<Val>> {364 self.run_assertions()?;365 self.get_raw(key, self.0.this_obj.as_ref())366 }367368 // pub fn extend_with(self, key: )369370 fn get_raw(&self, key: IStr, real_this: Option<&Self>) -> Result<Option<Val>> {371 let real_this = real_this.unwrap_or(self);372 let cache_key = (key.clone(), WeakObjValue(real_this.0.downgrade()));373374 if let Some(v) = self.0.value_cache.borrow().get(&cache_key) {375 return Ok(match v {376 CacheValue::Cached(v) => Some(v.clone()),377 CacheValue::NotFound => None,378 CacheValue::Pending => throw!(InfiniteRecursionDetected),379 CacheValue::Errored(e) => return Err(e.clone()),380 });381 }382 self.0383 .value_cache384 .borrow_mut()385 .insert(cache_key.clone(), CacheValue::Pending);386 let value = match (self.0.this_entries.get(&key), &self.0.super_obj) {387 (Some(k), None) => Ok(Some(self.evaluate_this(k, real_this)?)),388 (Some(k), Some(s)) => {389 let our = self.evaluate_this(k, real_this)?;390 if k.add {391 s.get_raw(key, Some(real_this))?392 .map_or(Ok(Some(our.clone())), |v| {393 Ok(Some(evaluate_add_op(&v, &our)?))394 })395 } else {396 Ok(Some(our))397 }398 }399 (None, Some(s)) => s.get_raw(key, Some(real_this)),400 (None, None) => Ok(None),401 };402 let value = match value {403 Ok(v) => v,404 Err(e) => {405 self.0406 .value_cache407 .borrow_mut()408 .insert(cache_key, CacheValue::Errored(e.clone()));409 return Err(e);410 }411 };412 self.0.value_cache.borrow_mut().insert(413 cache_key,414 match &value {415 Some(v) => CacheValue::Cached(v.clone()),416 None => CacheValue::NotFound,417 },418 );419 Ok(value)420 }421 fn evaluate_this(&self, v: &ObjMember, real_this: &Self) -> Result<Val> {422 v.invoke423 .evaluate(Some(real_this.clone()), self.0.super_obj.clone())?424 .evaluate()425 }426427 fn run_assertions_raw(&self, real_this: &Self) -> Result<()> {428 if self.0.assertions_ran.borrow_mut().insert(real_this.clone()) {429 for assertion in self.0.assertions.iter() {430 if let Err(e) = assertion.run(Some(real_this.clone()), self.0.super_obj.clone()) {431 self.0.assertions_ran.borrow_mut().remove(real_this);432 return Err(e);433 }434 }435 if let Some(super_obj) = &self.0.super_obj {436 super_obj.run_assertions_raw(real_this)?;437 }438 }439 Ok(())440 }441 pub fn run_assertions(&self) -> Result<()> {442 self.run_assertions_raw(self)443 }444445 pub fn ptr_eq(a: &Self, b: &Self) -> bool {446 cc_ptr_eq(&a.0, &b.0)447 }448}449450impl PartialEq for ObjValue {451 fn eq(&self, other: &Self) -> bool {452 cc_ptr_eq(&self.0, &other.0)453 }454}455456impl Eq for ObjValue {}457impl Hash for ObjValue {458 fn hash<H: Hasher>(&self, hasher: &mut H) {459 hasher.write_usize(&*self.0 as *const _ as usize)460 }461}462463pub struct ObjValueBuilder {464 super_obj: Option<ObjValue>,465 map: GcHashMap<IStr, ObjMember>,466 assertions: Vec<TraceBox<dyn ObjectAssertion>>,467 next_field_index: FieldIndex,468}469impl ObjValueBuilder {470 pub fn new() -> Self {471 Self::with_capacity(0)472 }473 pub fn with_capacity(capacity: usize) -> Self {474 Self {475 super_obj: None,476 map: GcHashMap::with_capacity(capacity),477 assertions: Vec::new(),478 next_field_index: FieldIndex::default(),479 }480 }481 pub fn reserve_asserts(&mut self, capacity: usize) -> &mut Self {482 self.assertions.reserve_exact(capacity);483 self484 }485 pub fn with_super(&mut self, super_obj: ObjValue) -> &mut Self {486 self.super_obj = Some(super_obj);487 self488 }489490 pub fn assert(&mut self, assertion: TraceBox<dyn ObjectAssertion>) -> &mut Self {491 self.assertions.push(assertion);492 self493 }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();497 ObjMemberBuilder::new(ValueBuilder(self), name, field_index)498 }499500 pub fn build(self) -> ObjValue {501 ObjValue::new(self.super_obj, Cc::new(self.map), Cc::new(self.assertions))502 }503}504impl Default for ObjValueBuilder {505 fn default() -> Self {506 Self::with_capacity(0)507 }508}509510#[must_use = "value not added unless binding() was called"]511pub struct ObjMemberBuilder<Kind> {512 kind: Kind,513 name: IStr,514 add: bool,515 visibility: Visibility,516 original_index: FieldIndex,517 location: Option<ExprLocation>,518}519520#[allow(clippy::missing_const_for_fn)]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 }532533 pub const fn with_add(mut self, add: bool) -> Self {534 self.add = add;535 self536 }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 self543 }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 self550 }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}565566pub struct ValueBuilder<'v>(&'v mut ObjValueBuilder);567impl<'v> ObjMemberBuilder<ValueBuilder<'v>> {568 pub fn value(self, value: Val) -> Result<()> {569 self.binding(LazyBinding::Bound(LazyVal::new_resolved(value)))570 }571 pub fn bindable(self, bindable: TraceBox<dyn Bindable>) -> Result<()> {572 self.binding(LazyBinding::Bindable(Cc::new(bindable)))573 }574 pub fn binding(self, binding: LazyBinding) -> Result<()> {575 let (receiver, name, member) = self.build_member(binding);576 let location = member.location.clone();577 let old = receiver.0.map.insert(name.clone(), member);578 if old.is_some() {579 push_frame(580 CallLocation(location.as_ref()),581 || format!("field <{}> initializtion", name.clone()),582 || throw!(DuplicateFieldName(name.clone())),583 )?584 }585 Ok(())586 }587}588589pub 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}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()
}