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.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.rsdiffbeforeafterboth1use std::{cell::RefCell, fmt::Debug, rc::Rc};23use gcmodule::{Cc, Trace};4use jrsonnet_interner::IStr;5use jrsonnet_parser::{LocExpr, ParamsDesc};6use jrsonnet_types::ValType;78use crate::{9 builtin::manifest::{10 manifest_json_ex, manifest_yaml_ex, ManifestJsonOptions, ManifestType, ManifestYamlOptions,11 },12 cc_ptr_eq,13 error::{Error::*, LocError},14 evaluate,15 function::{16 parse_default_function_call, parse_function_call, ArgsLike, Builtin, CallLocation,17 StaticBuiltin,18 },19 gc::TraceBox,20 throw, Context, ObjValue, Result,21};2223pub trait LazyValValue: Trace {24 fn get(self: Box<Self>) -> Result<Val>;25}2627#[derive(Trace)]28enum LazyValInternals {29 Computed(Val),30 Errored(LocError),31 Waiting(TraceBox<dyn LazyValValue>),32 Pending,33}3435#[derive(Clone, Trace)]36pub struct LazyVal(Cc<RefCell<LazyValInternals>>);37impl LazyVal {38 pub fn new(f: TraceBox<dyn LazyValValue>) -> Self {39 Self(Cc::new(RefCell::new(LazyValInternals::Waiting(f))))40 }41 pub fn new_resolved(val: Val) -> Self {42 Self(Cc::new(RefCell::new(LazyValInternals::Computed(val))))43 }44 pub fn force(&self) -> Result<()> {45 self.evaluate()?;46 Ok(())47 }48 pub fn evaluate(&self) -> Result<Val> {49 match &*self.0.borrow() {50 LazyValInternals::Computed(v) => return Ok(v.clone()),51 LazyValInternals::Errored(e) => return Err(e.clone()),52 LazyValInternals::Pending => return Err(InfiniteRecursionDetected.into()),53 _ => (),54 };55 let value = if let LazyValInternals::Waiting(value) =56 std::mem::replace(&mut *self.0.borrow_mut(), LazyValInternals::Pending)57 {58 value59 } else {60 unreachable!()61 };62 let new_value = match value.0.get() {63 Ok(v) => v,64 Err(e) => {65 *self.0.borrow_mut() = LazyValInternals::Errored(e.clone());66 return Err(e);67 }68 };69 *self.0.borrow_mut() = LazyValInternals::Computed(new_value.clone());70 Ok(new_value)71 }72}7374impl Debug for LazyVal {75 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {76 write!(f, "Lazy")77 }78}79impl PartialEq for LazyVal {80 fn eq(&self, other: &Self) -> bool {81 cc_ptr_eq(&self.0, &other.0)82 }83}8485#[derive(Debug, PartialEq, Trace)]86pub struct FuncDesc {87 pub name: IStr,88 pub ctx: Context,89 pub params: ParamsDesc,90 pub body: LocExpr,91}92impl FuncDesc {93 /// Create body context, but fill arguments without defaults with lazy error94 pub fn default_body_context(&self) -> Context {95 parse_default_function_call(self.ctx.clone(), &self.params)96 }9798 /// Create context, with which body code will run99 pub fn call_body_context(100 &self,101 call_ctx: Context,102 args: &dyn ArgsLike,103 tailstrict: bool,104 ) -> Result<Context> {105 parse_function_call(call_ctx, self.ctx.clone(), &self.params, args, tailstrict)106 }107}108109#[derive(Trace, Clone)]110pub enum FuncVal {111 /// Plain function implemented in jsonnet112 Normal(Cc<FuncDesc>),113 /// Standard library function114 StaticBuiltin(#[skip_trace] &'static dyn StaticBuiltin),115 /// User-provided function116 Builtin(Cc<TraceBox<dyn Builtin>>),117}118119impl Debug for FuncVal {120 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {121 match self {122 Self::Normal(arg0) => f.debug_tuple("Normal").field(arg0).finish(),123 Self::StaticBuiltin(arg0) => {124 f.debug_tuple("StaticBuiltin").field(&arg0.name()).finish()125 }126 Self::Builtin(arg0) => f.debug_tuple("Builtin").field(&arg0.name()).finish(),127 }128 }129}130131impl FuncVal {132 pub fn args_len(&self) -> usize {133 match self {134 Self::Normal(n) => n.params.iter().filter(|p| p.1.is_none()).count(),135 Self::StaticBuiltin(i) => i.params().iter().filter(|p| !p.has_default).count(),136 Self::Builtin(i) => i.params().iter().filter(|p| !p.has_default).count(),137 }138 }139 pub fn name(&self) -> IStr {140 match self {141 Self::Normal(normal) => normal.name.clone(),142 Self::StaticBuiltin(builtin) => builtin.name().into(),143 Self::Builtin(builtin) => builtin.name().into(),144 }145 }146 pub fn evaluate(147 &self,148 call_ctx: Context,149 loc: CallLocation,150 args: &dyn ArgsLike,151 tailstrict: bool,152 ) -> Result<Val> {153 match self {154 Self::Normal(func) => {155 let body_ctx = func.call_body_context(call_ctx, args, tailstrict)?;156 evaluate(body_ctx, &func.body)157 }158 Self::StaticBuiltin(b) => b.call(call_ctx, loc, args),159 Self::Builtin(b) => b.call(call_ctx, loc, args),160 }161 }162 pub fn evaluate_simple(&self, args: &dyn ArgsLike) -> Result<Val> {163 self.evaluate(Context::default(), CallLocation::native(), args, true)164 }165}166167#[derive(Clone)]168pub enum ManifestFormat {169 YamlStream(Box<ManifestFormat>),170 Yaml(usize),171 Json(usize),172 ToString,173 String,174}175176#[derive(Debug, Clone, Trace)]177pub struct Slice {178 pub(crate) inner: ArrValue,179 pub(crate) from: u32,180 pub(crate) to: u32,181 pub(crate) step: u32,182}183impl Slice {184 fn from(&self) -> usize {185 self.from as usize186 }187 fn to(&self) -> usize {188 self.to as usize189 }190 fn step(&self) -> usize {191 self.step as usize192 }193 fn len(&self) -> usize {194 // TODO: use div_ceil195 let diff = self.to() - self.from();196 let rem = diff % self.step();197 let div = diff / self.step();198199 if rem != 0 {200 div + 1201 } else {202 div203 }204 }205}206207#[derive(Debug, Clone, Trace)]208#[force_tracking]209pub enum ArrValue {210 Bytes(#[skip_trace] Rc<[u8]>),211 Lazy(Cc<Vec<LazyVal>>),212 Eager(Cc<Vec<Val>>),213 Extended(Box<(Self, Self)>),214 Range(i32, i32),215 Slice(Box<Slice>),216 Reversed(Box<Self>),217}218impl ArrValue {219 pub fn new_eager() -> Self {220 Self::Eager(Cc::new(Vec::new()))221 }222 pub fn new_range(a: i32, b: i32) -> Self {223 assert!(a <= b);224 Self::Range(a, b)225 }226227 pub fn slice(self, from: Option<usize>, to: Option<usize>, step: Option<usize>) -> Self {228 let len = self.len();229 let from = from.unwrap_or(0);230 let to = to.unwrap_or(len).min(len);231 let step = step.unwrap_or(1);232 assert!(from < to);233 assert!(step > 0);234235 Self::Slice(Box::new(Slice {236 inner: self,237 from: from as u32,238 to: to as u32,239 step: step as u32,240 }))241 }242243 pub fn len(&self) -> usize {244 match self {245 Self::Bytes(i) => i.len(),246 Self::Lazy(l) => l.len(),247 Self::Eager(e) => e.len(),248 Self::Extended(v) => v.0.len() + v.1.len(),249 Self::Range(a, b) => a.abs_diff(*b) as usize,250 Self::Reversed(i) => i.len(),251 Self::Slice(s) => s.len(),252 }253 }254255 pub fn is_empty(&self) -> bool {256 self.len() == 0257 }258259 pub fn get(&self, index: usize) -> Result<Option<Val>> {260 match self {261 Self::Bytes(i) => i262 .get(index)263 .map_or(Ok(None), |v| Ok(Some(Val::Num(*v as f64)))),264 Self::Lazy(vec) => {265 if let Some(v) = vec.get(index) {266 Ok(Some(v.evaluate()?))267 } else {268 Ok(None)269 }270 }271 Self::Eager(vec) => Ok(vec.get(index).cloned()),272 Self::Extended(v) => {273 let a_len = v.0.len();274 if a_len > index {275 v.0.get(index)276 } else {277 v.1.get(index - a_len)278 }279 }280 Self::Range(a, _) => {281 if index >= self.len() {282 return Ok(None);283 }284 Ok(Some(Val::Num(((*a as isize) + index as isize) as f64)))285 }286 Self::Reversed(v) => {287 let len = v.len();288 if index >= len {289 return Ok(None);290 }291 v.get(len - index - 1)292 }293 Self::Slice(s) => {294 let index = s.from() + index * s.step();295 if index >= s.to() {296 return Ok(None);297 }298 s.inner.get(index as usize)299 }300 }301 }302303 pub fn get_lazy(&self, index: usize) -> Option<LazyVal> {304 match self {305 Self::Bytes(i) => i306 .get(index)307 .map(|b| LazyVal::new_resolved(Val::Num(*b as f64))),308 Self::Lazy(vec) => vec.get(index).cloned(),309 Self::Eager(vec) => vec.get(index).cloned().map(LazyVal::new_resolved),310 Self::Extended(v) => {311 let a_len = v.0.len();312 if a_len > index {313 v.0.get_lazy(index)314 } else {315 v.1.get_lazy(index - a_len)316 }317 }318 Self::Range(a, _) => {319 if index >= self.len() {320 return None;321 }322 Some(LazyVal::new_resolved(Val::Num(323 ((*a as isize) + index as isize) as f64,324 )))325 }326 Self::Reversed(v) => {327 let len = v.len();328 if index >= len {329 return None;330 }331 v.get_lazy(len - index - 1)332 }333 Self::Slice(s) => {334 let index = s.from() + index * s.step();335 if index >= s.to() {336 return None;337 }338 s.inner.get_lazy(index as usize)339 }340 }341 }342343 pub fn evaluated(&self) -> Result<Cc<Vec<Val>>> {344 Ok(match self {345 Self::Bytes(i) => {346 let mut out = Vec::with_capacity(i.len());347 for v in i.iter() {348 out.push(Val::Num(*v as f64));349 }350 Cc::new(out)351 }352 Self::Lazy(vec) => {353 let mut out = Vec::with_capacity(vec.len());354 for item in vec.iter() {355 out.push(item.evaluate()?);356 }357 Cc::new(out)358 }359 Self::Eager(vec) => vec.clone(),360 Self::Extended(_v) => {361 let mut out = Vec::with_capacity(self.len());362 for item in self.iter() {363 out.push(item?);364 }365 Cc::new(out)366 }367 Self::Range(a, b) => {368 let mut out = Vec::with_capacity(self.len());369 for i in *a..*b {370 out.push(Val::Num(i as f64));371 }372 Cc::new(out)373 }374 Self::Reversed(r) => {375 let mut r = r.evaluated()?;376 Cc::update_with(&mut r, |v| v.reverse());377 r378 }379 Self::Slice(v) => {380 let mut out = Vec::with_capacity(v.inner.len());381 for v in v382 .inner383 .iter_lazy()384 .skip(v.from())385 .take(v.to() - v.from())386 .step_by(v.step())387 {388 out.push(v.evaluate()?)389 }390 Cc::new(out)391 }392 })393 }394395 pub fn iter(&self) -> impl DoubleEndedIterator<Item = Result<Val>> + '_ {396 (0..self.len()).map(move |idx| match self {397 Self::Bytes(b) => Ok(Val::Num(b[idx] as f64)),398 Self::Lazy(l) => l[idx].evaluate(),399 Self::Eager(e) => Ok(e[idx].clone()),400 Self::Extended(_) => self.get(idx).map(|e| e.unwrap()),401 Self::Range(..) => self.get(idx).map(|e| e.unwrap()),402 Self::Reversed(..) => self.get(idx).map(|e| e.unwrap()),403 Self::Slice(..) => self.get(idx).map(|e| e.unwrap()),404 })405 }406407 pub fn iter_lazy(&self) -> impl DoubleEndedIterator<Item = LazyVal> + '_ {408 (0..self.len()).map(move |idx| match self {409 Self::Bytes(b) => LazyVal::new_resolved(Val::Num(b[idx] as f64)),410 Self::Lazy(l) => l[idx].clone(),411 Self::Eager(e) => LazyVal::new_resolved(e[idx].clone()),412 Self::Extended(_) => self.get_lazy(idx).unwrap(),413 Self::Range(..) => self.get_lazy(idx).unwrap(),414 Self::Reversed(..) => self.get_lazy(idx).unwrap(),415 Self::Slice(..) => self.get_lazy(idx).unwrap(),416 })417 }418419 pub fn reversed(self) -> Self {420 Self::Reversed(Box::new(self))421 }422423 pub fn map(self, mapper: impl Fn(Val) -> Result<Val>) -> Result<Self> {424 let mut out = Vec::with_capacity(self.len());425426 for value in self.iter() {427 out.push(mapper(value?)?);428 }429430 Ok(Self::Eager(Cc::new(out)))431 }432433 pub fn filter(self, filter: impl Fn(&Val) -> Result<bool>) -> Result<Self> {434 let mut out = Vec::with_capacity(self.len());435436 for value in self.iter() {437 let value = value?;438 if filter(&value)? {439 out.push(value);440 }441 }442443 Ok(Self::Eager(Cc::new(out)))444 }445446 pub fn ptr_eq(a: &Self, b: &Self) -> bool {447 match (a, b) {448 (Self::Lazy(a), Self::Lazy(b)) => cc_ptr_eq(a, b),449 (Self::Eager(a), Self::Eager(b)) => cc_ptr_eq(a, b),450 _ => false,451 }452 }453}454455impl From<Vec<LazyVal>> for ArrValue {456 fn from(v: Vec<LazyVal>) -> Self {457 Self::Lazy(Cc::new(v))458 }459}460461impl From<Vec<Val>> for ArrValue {462 fn from(v: Vec<Val>) -> Self {463 Self::Eager(Cc::new(v))464 }465}466467pub enum IndexableVal {468 Str(IStr),469 Arr(ArrValue),470}471472#[derive(Debug, Clone, Trace)]473pub enum Val {474 Bool(bool),475 Null,476 Str(IStr),477 Num(f64),478 Arr(ArrValue),479 Obj(ObjValue),480 Func(FuncVal),481}482483impl Val {484 pub const fn as_bool(&self) -> Option<bool> {485 match self {486 Val::Bool(v) => Some(*v),487 _ => None,488 }489 }490 pub const fn as_null(&self) -> Option<()> {491 match self {492 Val::Null => Some(()),493 _ => None,494 }495 }496 pub fn as_str(&self) -> Option<IStr> {497 match self {498 Val::Str(s) => Some(s.clone()),499 _ => None,500 }501 }502 pub const fn as_num(&self) -> Option<f64> {503 match self {504 Val::Num(n) => Some(*n),505 _ => None,506 }507 }508 pub fn as_arr(&self) -> Option<ArrValue> {509 match self {510 Val::Arr(a) => Some(a.clone()),511 _ => None,512 }513 }514 pub fn as_obj(&self) -> Option<ObjValue> {515 match self {516 Val::Obj(o) => Some(o.clone()),517 _ => None,518 }519 }520 pub fn as_func(&self) -> Option<FuncVal> {521 match self {522 Val::Func(f) => Some(f.clone()),523 _ => None,524 }525 }526527 /// Creates `Val::Num` after checking for numeric overflow.528 /// As numbers are `f64`, we can just check for their finity.529 pub fn new_checked_num(num: f64) -> Result<Self> {530 if num.is_finite() {531 Ok(Self::Num(num))532 } else {533 throw!(RuntimeError("overflow".into()))534 }535 }536537 pub const fn value_type(&self) -> ValType {538 match self {539 Self::Str(..) => ValType::Str,540 Self::Num(..) => ValType::Num,541 Self::Arr(..) => ValType::Arr,542 Self::Obj(..) => ValType::Obj,543 Self::Bool(_) => ValType::Bool,544 Self::Null => ValType::Null,545 Self::Func(..) => ValType::Func,546 }547 }548549 pub fn to_string(&self) -> Result<IStr> {550 Ok(match self {551 Self::Bool(true) => "true".into(),552 Self::Bool(false) => "false".into(),553 Self::Null => "null".into(),554 Self::Str(s) => s.clone(),555 v => manifest_json_ex(556 v,557 &ManifestJsonOptions {558 padding: "",559 mtype: ManifestType::ToString,560 newline: "\n",561 key_val_sep: ": ",562 },563 )?564 .into(),565 })566 }567568 /// Expects value to be object, outputs (key, manifested value) pairs569 pub fn manifest_multi(&self, ty: &ManifestFormat) -> Result<Vec<(IStr, IStr)>> {570 let obj = match self {571 Self::Obj(obj) => obj,572 _ => throw!(MultiManifestOutputIsNotAObject),573 };574 let keys = obj.fields();575 let mut out = Vec::with_capacity(keys.len());576 for key in keys {577 let value = obj578 .get(key.clone())?579 .expect("item in object")580 .manifest(ty)?;581 out.push((key, value));582 }583 Ok(out)584 }585586 /// Expects value to be array, outputs manifested values587 pub fn manifest_stream(&self, ty: &ManifestFormat) -> Result<Vec<IStr>> {588 let arr = match self {589 Self::Arr(a) => a,590 _ => throw!(StreamManifestOutputIsNotAArray),591 };592 let mut out = Vec::with_capacity(arr.len());593 for i in arr.iter() {594 out.push(i?.manifest(ty)?);595 }596 Ok(out)597 }598599 pub fn manifest(&self, ty: &ManifestFormat) -> Result<IStr> {600 Ok(match ty {601 ManifestFormat::YamlStream(format) => {602 let arr = match self {603 Self::Arr(a) => a,604 _ => throw!(StreamManifestOutputIsNotAArray),605 };606 let mut out = String::new();607608 match format as &ManifestFormat {609 ManifestFormat::YamlStream(_) => throw!(StreamManifestOutputCannotBeRecursed),610 ManifestFormat::String => throw!(StreamManifestCannotNestString),611 _ => {}612 };613614 if !arr.is_empty() {615 for v in arr.iter() {616 out.push_str("---\n");617 out.push_str(&v?.manifest(format)?);618 out.push('\n');619 }620 out.push_str("...");621 }622623 out.into()624 }625 ManifestFormat::Yaml(padding) => self.to_yaml(*padding)?,626 ManifestFormat::Json(padding) => self.to_json(*padding)?,627 ManifestFormat::ToString => self.to_string()?,628 ManifestFormat::String => match self {629 Self::Str(s) => s.clone(),630 _ => throw!(StringManifestOutputIsNotAString),631 },632 })633 }634635 /// For manifestification636 pub fn to_json(&self, padding: usize) -> Result<IStr> {637 manifest_json_ex(638 self,639 &ManifestJsonOptions {640 padding: &" ".repeat(padding),641 mtype: if padding == 0 {642 ManifestType::Minify643 } else {644 ManifestType::Manifest645 },646 newline: "\n",647 key_val_sep: ": ",648 },649 )650 .map(|s| s.into())651 }652653 /// Calls `std.manifestJson`654 pub fn to_std_json(&self, padding: usize) -> Result<Rc<str>> {655 manifest_json_ex(656 self,657 &ManifestJsonOptions {658 padding: &" ".repeat(padding),659 mtype: ManifestType::Std,660 newline: "\n",661 key_val_sep: ": ",662 },663 )664 .map(|s| s.into())665 }666667 pub fn to_yaml(&self, padding: usize) -> Result<IStr> {668 let padding = &" ".repeat(padding);669 manifest_yaml_ex(670 self,671 &ManifestYamlOptions {672 padding,673 arr_element_padding: padding,674 quote_keys: false,675 },676 )677 .map(|s| s.into())678 }679 pub fn into_indexable(self) -> Result<IndexableVal> {680 Ok(match self {681 Val::Str(s) => IndexableVal::Str(s),682 Val::Arr(arr) => IndexableVal::Arr(arr),683 _ => throw!(ValueIsNotIndexable(self.value_type())),684 })685 }686}687688const fn is_function_like(val: &Val) -> bool {689 matches!(val, Val::Func(_))690}691692/// Native implementation of `std.primitiveEquals`693pub fn primitive_equals(val_a: &Val, val_b: &Val) -> Result<bool> {694 Ok(match (val_a, val_b) {695 (Val::Bool(a), Val::Bool(b)) => a == b,696 (Val::Null, Val::Null) => true,697 (Val::Str(a), Val::Str(b)) => a == b,698 (Val::Num(a), Val::Num(b)) => (a - b).abs() <= f64::EPSILON,699 (Val::Arr(_), Val::Arr(_)) => throw!(RuntimeError(700 "primitiveEquals operates on primitive types, got array".into(),701 )),702 (Val::Obj(_), Val::Obj(_)) => throw!(RuntimeError(703 "primitiveEquals operates on primitive types, got object".into(),704 )),705 (a, b) if is_function_like(a) && is_function_like(b) => {706 throw!(RuntimeError("cannot test equality of functions".into()))707 }708 (_, _) => false,709 })710}711712/// Native implementation of `std.equals`713pub fn equals(val_a: &Val, val_b: &Val) -> Result<bool> {714 if val_a.value_type() != val_b.value_type() {715 return Ok(false);716 }717 match (val_a, val_b) {718 (Val::Arr(a), Val::Arr(b)) => {719 if ArrValue::ptr_eq(a, b) {720 return Ok(true);721 }722 if a.len() != b.len() {723 return Ok(false);724 }725 for (a, b) in a.iter().zip(b.iter()) {726 if !equals(&a?, &b?)? {727 return Ok(false);728 }729 }730 Ok(true)731 }732 (Val::Obj(a), Val::Obj(b)) => {733 if ObjValue::ptr_eq(a, b) {734 return Ok(true);735 }736 let fields = a.fields();737 if fields != b.fields() {738 return Ok(false);739 }740 for field in fields {741 if !equals(&a.get(field.clone())?.unwrap(), &b.get(field)?.unwrap())? {742 return Ok(false);743 }744 }745 Ok(true)746 }747 (a, b) => Ok(primitive_equals(a, b)?),748 }749}1use std::{cell::RefCell, fmt::Debug, rc::Rc};23use gcmodule::{Cc, Trace};4use jrsonnet_interner::IStr;5use jrsonnet_parser::{LocExpr, ParamsDesc};6use jrsonnet_types::ValType;78use crate::{9 builtin::manifest::{10 manifest_json_ex, manifest_yaml_ex, ManifestJsonOptions, ManifestType, ManifestYamlOptions,11 },12 cc_ptr_eq,13 error::{Error::*, LocError},14 evaluate,15 function::{16 parse_default_function_call, parse_function_call, ArgsLike, Builtin, CallLocation,17 StaticBuiltin,18 },19 gc::TraceBox,20 throw, Context, ObjValue, Result,21};2223pub trait LazyValValue: Trace {24 fn get(self: Box<Self>) -> Result<Val>;25}2627#[derive(Trace)]28enum LazyValInternals {29 Computed(Val),30 Errored(LocError),31 Waiting(TraceBox<dyn LazyValValue>),32 Pending,33}3435#[derive(Clone, Trace)]36pub struct LazyVal(Cc<RefCell<LazyValInternals>>);37impl LazyVal {38 pub fn new(f: TraceBox<dyn LazyValValue>) -> Self {39 Self(Cc::new(RefCell::new(LazyValInternals::Waiting(f))))40 }41 pub fn new_resolved(val: Val) -> Self {42 Self(Cc::new(RefCell::new(LazyValInternals::Computed(val))))43 }44 pub fn force(&self) -> Result<()> {45 self.evaluate()?;46 Ok(())47 }48 pub fn evaluate(&self) -> Result<Val> {49 match &*self.0.borrow() {50 LazyValInternals::Computed(v) => return Ok(v.clone()),51 LazyValInternals::Errored(e) => return Err(e.clone()),52 LazyValInternals::Pending => return Err(InfiniteRecursionDetected.into()),53 _ => (),54 };55 let value = if let LazyValInternals::Waiting(value) =56 std::mem::replace(&mut *self.0.borrow_mut(), LazyValInternals::Pending)57 {58 value59 } else {60 unreachable!()61 };62 let new_value = match value.0.get() {63 Ok(v) => v,64 Err(e) => {65 *self.0.borrow_mut() = LazyValInternals::Errored(e.clone());66 return Err(e);67 }68 };69 *self.0.borrow_mut() = LazyValInternals::Computed(new_value.clone());70 Ok(new_value)71 }72}7374impl Debug for LazyVal {75 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {76 write!(f, "Lazy")77 }78}79impl PartialEq for LazyVal {80 fn eq(&self, other: &Self) -> bool {81 cc_ptr_eq(&self.0, &other.0)82 }83}8485#[derive(Debug, PartialEq, Trace)]86pub struct FuncDesc {87 pub name: IStr,88 pub ctx: Context,89 pub params: ParamsDesc,90 pub body: LocExpr,91}92impl FuncDesc {93 /// Create body context, but fill arguments without defaults with lazy error94 pub fn default_body_context(&self) -> Context {95 parse_default_function_call(self.ctx.clone(), &self.params)96 }9798 /// Create context, with which body code will run99 pub fn call_body_context(100 &self,101 call_ctx: Context,102 args: &dyn ArgsLike,103 tailstrict: bool,104 ) -> Result<Context> {105 parse_function_call(call_ctx, self.ctx.clone(), &self.params, args, tailstrict)106 }107}108109#[derive(Trace, Clone)]110pub enum FuncVal {111 /// Plain function implemented in jsonnet112 Normal(Cc<FuncDesc>),113 /// Standard library function114 StaticBuiltin(#[skip_trace] &'static dyn StaticBuiltin),115 /// User-provided function116 Builtin(Cc<TraceBox<dyn Builtin>>),117}118119impl Debug for FuncVal {120 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {121 match self {122 Self::Normal(arg0) => f.debug_tuple("Normal").field(arg0).finish(),123 Self::StaticBuiltin(arg0) => {124 f.debug_tuple("StaticBuiltin").field(&arg0.name()).finish()125 }126 Self::Builtin(arg0) => f.debug_tuple("Builtin").field(&arg0.name()).finish(),127 }128 }129}130131impl FuncVal {132 pub fn args_len(&self) -> usize {133 match self {134 Self::Normal(n) => n.params.iter().filter(|p| p.1.is_none()).count(),135 Self::StaticBuiltin(i) => i.params().iter().filter(|p| !p.has_default).count(),136 Self::Builtin(i) => i.params().iter().filter(|p| !p.has_default).count(),137 }138 }139 pub fn name(&self) -> IStr {140 match self {141 Self::Normal(normal) => normal.name.clone(),142 Self::StaticBuiltin(builtin) => builtin.name().into(),143 Self::Builtin(builtin) => builtin.name().into(),144 }145 }146 pub fn evaluate(147 &self,148 call_ctx: Context,149 loc: CallLocation,150 args: &dyn ArgsLike,151 tailstrict: bool,152 ) -> Result<Val> {153 match self {154 Self::Normal(func) => {155 let body_ctx = func.call_body_context(call_ctx, args, tailstrict)?;156 evaluate(body_ctx, &func.body)157 }158 Self::StaticBuiltin(b) => b.call(call_ctx, loc, args),159 Self::Builtin(b) => b.call(call_ctx, loc, args),160 }161 }162 pub fn evaluate_simple(&self, args: &dyn ArgsLike) -> Result<Val> {163 self.evaluate(Context::default(), CallLocation::native(), args, true)164 }165}166167#[derive(Clone)]168pub enum ManifestFormat {169 YamlStream(Box<ManifestFormat>),170 Yaml {171 padding: usize,172 #[cfg(feature = "exp-preserve-order")]173 preserve_order: bool,174 },175 Json {176 padding: usize,177 #[cfg(feature = "exp-preserve-order")]178 preserve_order: bool,179 },180 ToString,181 String,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}195196#[derive(Debug, Clone, Trace)]197pub struct Slice {198 pub(crate) inner: ArrValue,199 pub(crate) from: u32,200 pub(crate) to: u32,201 pub(crate) step: u32,202}203impl Slice {204 fn from(&self) -> usize {205 self.from as usize206 }207 fn to(&self) -> usize {208 self.to as usize209 }210 fn step(&self) -> usize {211 self.step as usize212 }213 fn len(&self) -> usize {214 // TODO: use div_ceil215 let diff = self.to() - self.from();216 let rem = diff % self.step();217 let div = diff / self.step();218219 if rem != 0 {220 div + 1221 } else {222 div223 }224 }225}226227#[derive(Debug, Clone, Trace)]228#[force_tracking]229pub enum ArrValue {230 Bytes(#[skip_trace] Rc<[u8]>),231 Lazy(Cc<Vec<LazyVal>>),232 Eager(Cc<Vec<Val>>),233 Extended(Box<(Self, Self)>),234 Range(i32, i32),235 Slice(Box<Slice>),236 Reversed(Box<Self>),237}238impl ArrValue {239 pub fn new_eager() -> Self {240 Self::Eager(Cc::new(Vec::new()))241 }242 pub fn new_range(a: i32, b: i32) -> Self {243 assert!(a <= b);244 Self::Range(a, b)245 }246247 pub fn slice(self, from: Option<usize>, to: Option<usize>, step: Option<usize>) -> Self {248 let len = self.len();249 let from = from.unwrap_or(0);250 let to = to.unwrap_or(len).min(len);251 let step = step.unwrap_or(1);252 assert!(from < to);253 assert!(step > 0);254255 Self::Slice(Box::new(Slice {256 inner: self,257 from: from as u32,258 to: to as u32,259 step: step as u32,260 }))261 }262263 pub fn len(&self) -> usize {264 match self {265 Self::Bytes(i) => i.len(),266 Self::Lazy(l) => l.len(),267 Self::Eager(e) => e.len(),268 Self::Extended(v) => v.0.len() + v.1.len(),269 Self::Range(a, b) => a.abs_diff(*b) as usize,270 Self::Reversed(i) => i.len(),271 Self::Slice(s) => s.len(),272 }273 }274275 pub fn is_empty(&self) -> bool {276 self.len() == 0277 }278279 pub fn get(&self, index: usize) -> Result<Option<Val>> {280 match self {281 Self::Bytes(i) => i282 .get(index)283 .map_or(Ok(None), |v| Ok(Some(Val::Num(*v as f64)))),284 Self::Lazy(vec) => {285 if let Some(v) = vec.get(index) {286 Ok(Some(v.evaluate()?))287 } else {288 Ok(None)289 }290 }291 Self::Eager(vec) => Ok(vec.get(index).cloned()),292 Self::Extended(v) => {293 let a_len = v.0.len();294 if a_len > index {295 v.0.get(index)296 } else {297 v.1.get(index - a_len)298 }299 }300 Self::Range(a, _) => {301 if index >= self.len() {302 return Ok(None);303 }304 Ok(Some(Val::Num(((*a as isize) + index as isize) as f64)))305 }306 Self::Reversed(v) => {307 let len = v.len();308 if index >= len {309 return Ok(None);310 }311 v.get(len - index - 1)312 }313 Self::Slice(s) => {314 let index = s.from() + index * s.step();315 if index >= s.to() {316 return Ok(None);317 }318 s.inner.get(index as usize)319 }320 }321 }322323 pub fn get_lazy(&self, index: usize) -> Option<LazyVal> {324 match self {325 Self::Bytes(i) => i326 .get(index)327 .map(|b| LazyVal::new_resolved(Val::Num(*b as f64))),328 Self::Lazy(vec) => vec.get(index).cloned(),329 Self::Eager(vec) => vec.get(index).cloned().map(LazyVal::new_resolved),330 Self::Extended(v) => {331 let a_len = v.0.len();332 if a_len > index {333 v.0.get_lazy(index)334 } else {335 v.1.get_lazy(index - a_len)336 }337 }338 Self::Range(a, _) => {339 if index >= self.len() {340 return None;341 }342 Some(LazyVal::new_resolved(Val::Num(343 ((*a as isize) + index as isize) as f64,344 )))345 }346 Self::Reversed(v) => {347 let len = v.len();348 if index >= len {349 return None;350 }351 v.get_lazy(len - index - 1)352 }353 Self::Slice(s) => {354 let index = s.from() + index * s.step();355 if index >= s.to() {356 return None;357 }358 s.inner.get_lazy(index as usize)359 }360 }361 }362363 pub fn evaluated(&self) -> Result<Cc<Vec<Val>>> {364 Ok(match self {365 Self::Bytes(i) => {366 let mut out = Vec::with_capacity(i.len());367 for v in i.iter() {368 out.push(Val::Num(*v as f64));369 }370 Cc::new(out)371 }372 Self::Lazy(vec) => {373 let mut out = Vec::with_capacity(vec.len());374 for item in vec.iter() {375 out.push(item.evaluate()?);376 }377 Cc::new(out)378 }379 Self::Eager(vec) => vec.clone(),380 Self::Extended(_v) => {381 let mut out = Vec::with_capacity(self.len());382 for item in self.iter() {383 out.push(item?);384 }385 Cc::new(out)386 }387 Self::Range(a, b) => {388 let mut out = Vec::with_capacity(self.len());389 for i in *a..*b {390 out.push(Val::Num(i as f64));391 }392 Cc::new(out)393 }394 Self::Reversed(r) => {395 let mut r = r.evaluated()?;396 Cc::update_with(&mut r, |v| v.reverse());397 r398 }399 Self::Slice(v) => {400 let mut out = Vec::with_capacity(v.inner.len());401 for v in v402 .inner403 .iter_lazy()404 .skip(v.from())405 .take(v.to() - v.from())406 .step_by(v.step())407 {408 out.push(v.evaluate()?)409 }410 Cc::new(out)411 }412 })413 }414415 pub fn iter(&self) -> impl DoubleEndedIterator<Item = Result<Val>> + '_ {416 (0..self.len()).map(move |idx| match self {417 Self::Bytes(b) => Ok(Val::Num(b[idx] as f64)),418 Self::Lazy(l) => l[idx].evaluate(),419 Self::Eager(e) => Ok(e[idx].clone()),420 Self::Extended(_) => self.get(idx).map(|e| e.unwrap()),421 Self::Range(..) => self.get(idx).map(|e| e.unwrap()),422 Self::Reversed(..) => self.get(idx).map(|e| e.unwrap()),423 Self::Slice(..) => self.get(idx).map(|e| e.unwrap()),424 })425 }426427 pub fn iter_lazy(&self) -> impl DoubleEndedIterator<Item = LazyVal> + '_ {428 (0..self.len()).map(move |idx| match self {429 Self::Bytes(b) => LazyVal::new_resolved(Val::Num(b[idx] as f64)),430 Self::Lazy(l) => l[idx].clone(),431 Self::Eager(e) => LazyVal::new_resolved(e[idx].clone()),432 Self::Extended(_) => self.get_lazy(idx).unwrap(),433 Self::Range(..) => self.get_lazy(idx).unwrap(),434 Self::Reversed(..) => self.get_lazy(idx).unwrap(),435 Self::Slice(..) => self.get_lazy(idx).unwrap(),436 })437 }438439 pub fn reversed(self) -> Self {440 Self::Reversed(Box::new(self))441 }442443 pub fn map(self, mapper: impl Fn(Val) -> Result<Val>) -> Result<Self> {444 let mut out = Vec::with_capacity(self.len());445446 for value in self.iter() {447 out.push(mapper(value?)?);448 }449450 Ok(Self::Eager(Cc::new(out)))451 }452453 pub fn filter(self, filter: impl Fn(&Val) -> Result<bool>) -> Result<Self> {454 let mut out = Vec::with_capacity(self.len());455456 for value in self.iter() {457 let value = value?;458 if filter(&value)? {459 out.push(value);460 }461 }462463 Ok(Self::Eager(Cc::new(out)))464 }465466 pub fn ptr_eq(a: &Self, b: &Self) -> bool {467 match (a, b) {468 (Self::Lazy(a), Self::Lazy(b)) => cc_ptr_eq(a, b),469 (Self::Eager(a), Self::Eager(b)) => cc_ptr_eq(a, b),470 _ => false,471 }472 }473}474475impl From<Vec<LazyVal>> for ArrValue {476 fn from(v: Vec<LazyVal>) -> Self {477 Self::Lazy(Cc::new(v))478 }479}480481impl From<Vec<Val>> for ArrValue {482 fn from(v: Vec<Val>) -> Self {483 Self::Eager(Cc::new(v))484 }485}486487pub enum IndexableVal {488 Str(IStr),489 Arr(ArrValue),490}491492#[derive(Debug, Clone, Trace)]493pub enum Val {494 Bool(bool),495 Null,496 Str(IStr),497 Num(f64),498 Arr(ArrValue),499 Obj(ObjValue),500 Func(FuncVal),501}502503impl Val {504 pub const fn as_bool(&self) -> Option<bool> {505 match self {506 Val::Bool(v) => Some(*v),507 _ => None,508 }509 }510 pub const fn as_null(&self) -> Option<()> {511 match self {512 Val::Null => Some(()),513 _ => None,514 }515 }516 pub fn as_str(&self) -> Option<IStr> {517 match self {518 Val::Str(s) => Some(s.clone()),519 _ => None,520 }521 }522 pub const fn as_num(&self) -> Option<f64> {523 match self {524 Val::Num(n) => Some(*n),525 _ => None,526 }527 }528 pub fn as_arr(&self) -> Option<ArrValue> {529 match self {530 Val::Arr(a) => Some(a.clone()),531 _ => None,532 }533 }534 pub fn as_obj(&self) -> Option<ObjValue> {535 match self {536 Val::Obj(o) => Some(o.clone()),537 _ => None,538 }539 }540 pub fn as_func(&self) -> Option<FuncVal> {541 match self {542 Val::Func(f) => Some(f.clone()),543 _ => None,544 }545 }546547 /// Creates `Val::Num` after checking for numeric overflow.548 /// As numbers are `f64`, we can just check for their finity.549 pub fn new_checked_num(num: f64) -> Result<Self> {550 if num.is_finite() {551 Ok(Self::Num(num))552 } else {553 throw!(RuntimeError("overflow".into()))554 }555 }556557 pub const fn value_type(&self) -> ValType {558 match self {559 Self::Str(..) => ValType::Str,560 Self::Num(..) => ValType::Num,561 Self::Arr(..) => ValType::Arr,562 Self::Obj(..) => ValType::Obj,563 Self::Bool(_) => ValType::Bool,564 Self::Null => ValType::Null,565 Self::Func(..) => ValType::Func,566 }567 }568569 pub fn to_string(&self) -> Result<IStr> {570 Ok(match self {571 Self::Bool(true) => "true".into(),572 Self::Bool(false) => "false".into(),573 Self::Null => "null".into(),574 Self::Str(s) => s.clone(),575 v => manifest_json_ex(576 v,577 &ManifestJsonOptions {578 padding: "",579 mtype: ManifestType::ToString,580 newline: "\n",581 key_val_sep: ": ",582 #[cfg(feature = "exp-preserve-order")]583 preserve_order: false,584 },585 )?586 .into(),587 })588 }589590 /// Expects value to be object, outputs (key, manifested value) pairs591 pub fn manifest_multi(&self, ty: &ManifestFormat) -> Result<Vec<(IStr, IStr)>> {592 let obj = match self {593 Self::Obj(obj) => obj,594 _ => throw!(MultiManifestOutputIsNotAObject),595 };596 let keys = obj.fields(597 #[cfg(feature = "exp-preserve-order")]598 ty.preserve_order(),599 );600 let mut out = Vec::with_capacity(keys.len());601 for key in keys {602 let value = obj603 .get(key.clone())?604 .expect("item in object")605 .manifest(ty)?;606 out.push((key, value));607 }608 Ok(out)609 }610611 /// Expects value to be array, outputs manifested values612 pub fn manifest_stream(&self, ty: &ManifestFormat) -> Result<Vec<IStr>> {613 let arr = match self {614 Self::Arr(a) => a,615 _ => throw!(StreamManifestOutputIsNotAArray),616 };617 let mut out = Vec::with_capacity(arr.len());618 for i in arr.iter() {619 out.push(i?.manifest(ty)?);620 }621 Ok(out)622 }623624 pub fn manifest(&self, ty: &ManifestFormat) -> Result<IStr> {625 Ok(match ty {626 ManifestFormat::YamlStream(format) => {627 let arr = match self {628 Self::Arr(a) => a,629 _ => throw!(StreamManifestOutputIsNotAArray),630 };631 let mut out = String::new();632633 match format as &ManifestFormat {634 ManifestFormat::YamlStream(_) => throw!(StreamManifestOutputCannotBeRecursed),635 ManifestFormat::String => throw!(StreamManifestCannotNestString),636 _ => {}637 };638639 if !arr.is_empty() {640 for v in arr.iter() {641 out.push_str("---\n");642 out.push_str(&v?.manifest(format)?);643 out.push('\n');644 }645 out.push_str("...");646 }647648 out.into()649 }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 )?,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 )?,668 ManifestFormat::ToString => self.to_string()?,669 ManifestFormat::String => match self {670 Self::Str(s) => s.clone(),671 _ => throw!(StringManifestOutputIsNotAString),672 },673 })674 }675676 /// For manifestification677 pub fn to_json(678 &self,679 padding: usize,680 #[cfg(feature = "exp-preserve-order")] preserve_order: bool,681 ) -> Result<IStr> {682 manifest_json_ex(683 self,684 &ManifestJsonOptions {685 padding: &" ".repeat(padding),686 mtype: if padding == 0 {687 ManifestType::Minify688 } else {689 ManifestType::Manifest690 },691 newline: "\n",692 key_val_sep: ": ",693 #[cfg(feature = "exp-preserve-order")]694 preserve_order,695 },696 )697 .map(|s| s.into())698 }699700 /// Calls `std.manifestJson`701 pub fn to_std_json(702 &self,703 padding: usize,704 #[cfg(feature = "exp-preserve-order")] preserve_order: bool,705 ) -> Result<Rc<str>> {706 manifest_json_ex(707 self,708 &ManifestJsonOptions {709 padding: &" ".repeat(padding),710 mtype: ManifestType::Std,711 newline: "\n",712 key_val_sep: ": ",713 #[cfg(feature = "exp-preserve-order")]714 preserve_order,715 },716 )717 .map(|s| s.into())718 }719720 pub fn to_yaml(721 &self,722 padding: usize,723 #[cfg(feature = "exp-preserve-order")] preserve_order: bool,724 ) -> Result<IStr> {725 let padding = &" ".repeat(padding);726 manifest_yaml_ex(727 self,728 &ManifestYamlOptions {729 padding,730 arr_element_padding: padding,731 quote_keys: false,732 #[cfg(feature = "exp-preserve-order")]733 preserve_order,734 },735 )736 .map(|s| s.into())737 }738 pub fn into_indexable(self) -> Result<IndexableVal> {739 Ok(match self {740 Val::Str(s) => IndexableVal::Str(s),741 Val::Arr(arr) => IndexableVal::Arr(arr),742 _ => throw!(ValueIsNotIndexable(self.value_type())),743 })744 }745}746747const fn is_function_like(val: &Val) -> bool {748 matches!(val, Val::Func(_))749}750751/// Native implementation of `std.primitiveEquals`752pub fn primitive_equals(val_a: &Val, val_b: &Val) -> Result<bool> {753 Ok(match (val_a, val_b) {754 (Val::Bool(a), Val::Bool(b)) => a == b,755 (Val::Null, Val::Null) => true,756 (Val::Str(a), Val::Str(b)) => a == b,757 (Val::Num(a), Val::Num(b)) => (a - b).abs() <= f64::EPSILON,758 (Val::Arr(_), Val::Arr(_)) => throw!(RuntimeError(759 "primitiveEquals operates on primitive types, got array".into(),760 )),761 (Val::Obj(_), Val::Obj(_)) => throw!(RuntimeError(762 "primitiveEquals operates on primitive types, got object".into(),763 )),764 (a, b) if is_function_like(a) && is_function_like(b) => {765 throw!(RuntimeError("cannot test equality of functions".into()))766 }767 (_, _) => false,768 })769}770771/// Native implementation of `std.equals`772pub fn equals(val_a: &Val, val_b: &Val) -> Result<bool> {773 if val_a.value_type() != val_b.value_type() {774 return Ok(false);775 }776 match (val_a, val_b) {777 (Val::Arr(a), Val::Arr(b)) => {778 if ArrValue::ptr_eq(a, b) {779 return Ok(true);780 }781 if a.len() != b.len() {782 return Ok(false);783 }784 for (a, b) in a.iter().zip(b.iter()) {785 if !equals(&a?, &b?)? {786 return Ok(false);787 }788 }789 Ok(true)790 }791 (Val::Obj(a), Val::Obj(b)) => {792 if ObjValue::ptr_eq(a, b) {793 return Ok(true);794 }795 let fields = a.fields(796 #[cfg(feature = "exp-preserve-order")]797 false,798 );799 if fields800 != b.fields(801 #[cfg(feature = "exp-preserve-order")]802 false,803 ) {804 return Ok(false);805 }806 for field in fields {807 if !equals(&a.get(field.clone())?.unwrap(), &b.get(field)?.unwrap())? {808 return Ok(false);809 }810 }811 Ok(true)812 }813 (a, b) => Ok(primitive_equals(a, b)?),814 }815}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()
}