difftreelog
style fix clippy warnings
in: master
36 files changed
bindings/jsonnet/src/native.rsdiffbeforeafterboth--- a/bindings/jsonnet/src/native.rs
+++ b/bindings/jsonnet/src/native.rs
@@ -43,7 +43,7 @@
}
n_args.push(None);
let mut success = 1;
- let v = unsafe { (self.cb)(self.ctx, n_args.as_ptr().cast(), &mut success) };
+ let v = unsafe { (self.cb)(self.ctx, n_args.as_ptr().cast(), &raw mut success) };
let v = unsafe { *Box::from_raw(v) };
if success == 1 {
Ok(v)
crates/jrsonnet-cli/src/tla.rsdiffbeforeafterboth--- a/crates/jrsonnet-cli/src/tla.rs
+++ b/crates/jrsonnet-cli/src/tla.rs
@@ -7,6 +7,7 @@
#[derive(Parser)]
#[clap(next_help_heading = "TOP LEVEL ARGUMENTS")]
+#[allow(clippy::struct_field_names)]
pub struct TlaOpts {
/// Add top level string argument.
/// Top level arguments will be passed to function before manifestification stage.
crates/jrsonnet-evaluator/src/arr/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/arr/mod.rs
+++ b/crates/jrsonnet-evaluator/src/arr/mod.rs
@@ -77,7 +77,7 @@
let i = i?;
if filter(&i)? {
out.push(i);
- };
+ }
}
Ok(Self::eager(out))
}
crates/jrsonnet-evaluator/src/arr/spec.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/arr/spec.rs
+++ b/crates/jrsonnet-evaluator/src/arr/spec.rs
@@ -38,7 +38,7 @@
}
impl ArrayLike for SliceArray {
fn len(&self) -> usize {
- ((self.to - self.from + self.step - 1) / self.step) as usize
+ (self.to - self.from).div_ceil(self.step) as usize
}
fn get(&self, index: usize) -> Result<Option<Val>> {
@@ -139,7 +139,7 @@
ArrayThunk::Errored(e) => return Err(e.clone()),
ArrayThunk::Pending => return Err(InfiniteRecursionDetected.into()),
ArrayThunk::Waiting => {}
- };
+ }
let ArrayThunk::Waiting =
replace(&mut self.cached.borrow_mut()[index], ArrayThunk::Pending)
@@ -158,15 +158,6 @@
Ok(Some(new_value))
}
fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {
- if index >= self.len() {
- return None;
- }
- match &self.cached.borrow()[index] {
- ArrayThunk::Computed(c) => return Some(Thunk::evaluated(c.clone())),
- ArrayThunk::Errored(e) => return Some(Thunk::errored(e.clone())),
- ArrayThunk::Waiting | ArrayThunk::Pending => {}
- };
-
#[derive(Trace)]
struct ExprArrThunk {
expr: ExprArray,
@@ -183,6 +174,15 @@
}
}
+ if index >= self.len() {
+ return None;
+ }
+ match &self.cached.borrow()[index] {
+ ArrayThunk::Computed(c) => return Some(Thunk::evaluated(c.clone())),
+ ArrayThunk::Errored(e) => return Some(Thunk::errored(e.clone())),
+ ArrayThunk::Waiting | ArrayThunk::Pending => {}
+ }
+
Some(Thunk::new(ExprArrThunk {
expr: self.clone(),
index,
@@ -441,7 +441,7 @@
ArrayThunk::Errored(e) => return Err(e.clone()),
ArrayThunk::Pending => return Err(InfiniteRecursionDetected.into()),
ArrayThunk::Waiting => {}
- };
+ }
let ArrayThunk::Waiting =
replace(&mut self.cached.borrow_mut()[index], ArrayThunk::Pending)
@@ -467,15 +467,6 @@
Ok(Some(new_value))
}
fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {
- if index >= self.len() {
- return None;
- }
- match &self.cached.borrow()[index] {
- ArrayThunk::Computed(c) => return Some(Thunk::evaluated(c.clone())),
- ArrayThunk::Errored(e) => return Some(Thunk::errored(e.clone())),
- ArrayThunk::Waiting | ArrayThunk::Pending => {}
- };
-
#[derive(Trace)]
struct MappedArrayThunk<const WITH_INDEX: bool> {
arr: MappedArray<WITH_INDEX>,
@@ -489,6 +480,15 @@
}
}
+ if index >= self.len() {
+ return None;
+ }
+ match &self.cached.borrow()[index] {
+ ArrayThunk::Computed(c) => return Some(Thunk::evaluated(c.clone())),
+ ArrayThunk::Errored(e) => return Some(Thunk::errored(e.clone())),
+ ArrayThunk::Waiting | ArrayThunk::Pending => {}
+ }
+
Some(Thunk::new(MappedArrayThunk {
arr: self.clone(),
index,
crates/jrsonnet-evaluator/src/async_import.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/async_import.rs
+++ b/crates/jrsonnet-evaluator/src/async_import.rs
@@ -21,7 +21,8 @@
// Visits all nodes, trying to find import statements
#[allow(clippy::too_many_lines)]
pub fn find_imports(expr: &Spanned<Expr>, out: &mut FoundImports) {
- fn in_destruct(dest: &Destruct, #[allow(unused_variables)] out: &mut FoundImports) {
+ #[allow(unused_variables, clippy::needless_pass_by_ref_mut)]
+ fn in_destruct(dest: &Destruct, out: &mut FoundImports) {
match dest {
#[cfg(feature = "exp-destruct")]
Destruct::Array {
@@ -295,8 +296,6 @@
let resolved = (s.import_resolver() as &dyn Any)
.downcast_ref::<ResolvedImportResolver>()
.expect("for async imports, import_resolver should be set to ResolvedImportResolver");
-
- let mut resolved_map = resolved.resolved.borrow_mut();
let mut queue = vec![Job::LoadFile {
path: handler.resolve_from_default(path).await?,
@@ -340,14 +339,17 @@
}
}
Job::ResolveImport { from, import } => {
- if let Some((resolved, expression)) =
- resolved_map.get_mut(&(from.clone(), import.path.clone()))
{
- if import.expression && !*expression {
- *expression = true;
- queue.push(Job::ParseFile(resolved.clone()));
+ let mut resolved_map = resolved.resolved.borrow_mut();
+ if let Some((resolved, expression)) =
+ resolved_map.get_mut(&(from.clone(), import.path.clone()))
+ {
+ if import.expression && !*expression {
+ *expression = true;
+ queue.push(Job::ParseFile(resolved.clone()));
+ }
+ continue;
}
- continue;
}
let resolved = handler.resolve_from(&from, &import.path).await?;
queue.push(Job::LoadFile {
crates/jrsonnet-evaluator/src/evaluate/destructure.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/evaluate/destructure.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/destructure.rs
@@ -1,6 +1,7 @@
+use std::{collections::HashMap, hash::BuildHasher};
+
use jrsonnet_interner::IStr;
use jrsonnet_parser::{BindSpec, Destruct};
-use rustc_hash::FxHashMap;
use crate::{
bail,
@@ -10,11 +11,11 @@
#[allow(clippy::too_many_lines)]
#[allow(unused_variables)]
-pub fn destruct(
+pub fn destruct<H: BuildHasher>(
d: &Destruct,
parent: Thunk<Val>,
fctx: Pending<Context>,
- new_bindings: &mut FxHashMap<IStr, Thunk<Val>>,
+ new_bindings: &mut HashMap<IStr, Thunk<Val>, H>,
) -> Result<()> {
match d {
Destruct::Full(v) => {
@@ -159,10 +160,10 @@
Ok(())
}
-pub fn evaluate_dest(
+pub fn evaluate_dest<H: BuildHasher>(
d: &BindSpec,
fctx: Pending<Context>,
- new_bindings: &mut FxHashMap<IStr, Thunk<Val>>,
+ new_bindings: &mut HashMap<IStr, Thunk<Val>, H>,
) -> Result<()> {
match d {
BindSpec::Field { into, value } => {
crates/jrsonnet-evaluator/src/evaluate/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/evaluate/mod.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/mod.rs
@@ -291,7 +291,7 @@
let uctx = CachedUnbound::new(evaluate_object_locals(ctx.clone(), locals));
for field in &members.fields {
- evaluate_field_member(&mut builder, ctx.clone(), uctx.clone(), &field)?;
+ evaluate_field_member(&mut builder, ctx.clone(), uctx.clone(), field)?;
}
if !members.asserts.is_empty() {
@@ -304,13 +304,13 @@
fn run(&self, sup_this: SupThis) -> Result<()> {
let ctx = self.uctx.bind(sup_this)?;
for assert in &*self.asserts {
- evaluate_assert(ctx.clone(), &assert)?;
+ evaluate_assert(ctx.clone(), assert)?;
}
Ok(())
}
}
builder.assert(ObjectAssert {
- uctx: uctx.clone(),
+ uctx,
asserts: members.asserts.clone(),
});
}
@@ -567,7 +567,7 @@
evaluate_dest(b, fctx.clone(), &mut new_bindings)?;
}
let ctx = ctx.extend_bindings(new_bindings).into_future(fctx);
- evaluate(ctx, &returned.clone())?
+ evaluate(ctx, returned)?
}
Arr(items) => {
if items.is_empty() {
crates/jrsonnet-evaluator/src/evaluate/operator.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/evaluate/operator.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/operator.rs
@@ -95,9 +95,9 @@
// string format
(Str(_), _) => false,
- (_, Num(b)) => return **b == 0.,
+ (_, Num(b)) => **b == 0.,
#[cfg(feature = "exp-bigint")]
- (_, BigInt(b)) => return **b == num_bigint::BigInt::ZERO,
+ (_, BigInt(b)) => **b == num_bigint::BigInt::ZERO,
// something else
_ => false,
crates/jrsonnet-evaluator/src/function/arglike.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/function/arglike.rs
+++ b/crates/jrsonnet-evaluator/src/function/arglike.rs
@@ -239,7 +239,7 @@
}
fn named_names(&self, handler: &mut dyn FnMut(&IStr)) {
- for (name, _) in self {
+ for name in self.keys() {
handler(name);
}
}
crates/jrsonnet-evaluator/src/function/parse.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/function/parse.rs
+++ b/crates/jrsonnet-evaluator/src/function/parse.rs
@@ -1,5 +1,3 @@
-use std::mem::replace;
-
use jrsonnet_parser::{
function::{FunctionSignature, ParamName},
ExprParams,
@@ -87,7 +85,7 @@
}
destruct(
- &into,
+ into,
{
let ctx = fctx.clone();
let name = into.name();
@@ -97,7 +95,7 @@
fctx.clone(),
&mut defaults,
)?;
- if !into.name().is_anonymous() {
+ if into.name().is_named() {
filled_named += 1;
} else {
filled_positionals += 1;
@@ -165,7 +163,7 @@
.iter()
.position(|p| p.name() == name)
.ok_or_else(|| UnknownFunctionParameter(name.clone()))?;
- if replace(&mut passed_args[id], Some(arg)).is_some() {
+ if passed_args[id].replace(arg).is_some() {
bail!(BindingParameterASecondTime(name.clone()));
}
filled_args += 1;
@@ -230,7 +228,7 @@
let params = params.clone();
Thunk!(move || Err(FunctionParameterNotBoundInCall(
param_name,
- params.signature.clone()
+ params.signature
)
.into()))
},
crates/jrsonnet-evaluator/src/gc.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/gc.rs
+++ b/crates/jrsonnet-evaluator/src/gc.rs
@@ -1,3 +1,8 @@
+#![allow(
+ clippy::implicit_hasher,
+ reason = "those methods exist exactly because with_capacity is only present for default BuildHasher"
+)]
+
/// Macros to help deal with Gc
use jrsonnet_gcmodule::Trace;
use rustc_hash::{FxBuildHasher, FxHashMap, FxHashSet};
@@ -8,20 +13,20 @@
}
impl<V> WithCapacityExt for FxHashSet<V> {
fn with_capacity(capacity: usize) -> Self {
- Self::with_capacity_and_hasher(capacity, FxBuildHasher::default())
+ Self::with_capacity_and_hasher(capacity, FxBuildHasher)
}
fn new() -> Self {
- Self::with_hasher(FxBuildHasher::default())
+ Self::with_hasher(FxBuildHasher)
}
}
impl<K, V> WithCapacityExt for FxHashMap<K, V> {
fn with_capacity(capacity: usize) -> Self {
- Self::with_capacity_and_hasher(capacity, FxBuildHasher::default())
+ Self::with_capacity_and_hasher(capacity, FxBuildHasher)
}
fn new() -> Self {
- Self::with_hasher(FxBuildHasher::default())
+ Self::with_hasher(FxBuildHasher)
}
}
crates/jrsonnet-evaluator/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/lib.rs
+++ b/crates/jrsonnet-evaluator/src/lib.rs
@@ -367,7 +367,7 @@
let res = evaluate(self.create_default_context(file_name), &parsed);
let mut file_cache = self.file_cache();
- let mut file = file_cache.entry(path.clone());
+ let mut file = file_cache.entry(path);
let Entry::Occupied(file) = &mut file else {
unreachable!("this file was just here")
crates/jrsonnet-evaluator/src/manifest.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/manifest.rs
+++ b/crates/jrsonnet-evaluator/src/manifest.rs
@@ -240,7 +240,7 @@
}
ToString if i != 0 => buf.push(' '),
Minify | ToString => {}
- };
+ }
in_description_frame(
|| format!("elem <{i}> manifestification"),
@@ -335,7 +335,7 @@
buf.push('}');
}
Val::Func(_) => bail!("tried to manifest function"),
- };
+ }
Ok(())
}
crates/jrsonnet-evaluator/src/map.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/map.rs
+++ b/crates/jrsonnet-evaluator/src/map.rs
@@ -16,7 +16,7 @@
impl LayeredHashMap {
pub fn iter_keys(self, mut handler: impl FnMut(IStr)) {
- for (k, _) in &self.0.current {
+ for k in self.0.current.keys() {
handler(k.clone());
}
if let Some(parent) = self.0.parent.clone() {
@@ -47,11 +47,7 @@
pub fn contains_key(&self, key: &IStr) -> bool {
(self.0).current.contains_key(key)
- || self
- .0
- .parent
- .as_ref()
- .map_or(false, |p| p.contains_key(key))
+ || self.0.parent.as_ref().is_some_and(|p| p.contains_key(key))
}
}
crates/jrsonnet-evaluator/src/obj/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/obj/mod.rs
+++ b/crates/jrsonnet-evaluator/src/obj/mod.rs
@@ -1,6 +1,7 @@
use std::{
any::Any,
cell::{Cell, RefCell},
+ clone::Clone,
collections::hash_map::Entry,
fmt::{self, Debug},
hash::{Hash, Hasher},
@@ -272,7 +273,7 @@
impl ObjValue {
pub fn empty() -> Self {
- EMPTY_OBJ.with(|v| v.clone())
+ EMPTY_OBJ.with(Clone::clone)
}
pub fn is_empty(&self) -> bool {
self.0.cores.is_empty() || self.len() == 0
@@ -306,14 +307,13 @@
return Ok(GetFor::NotFound);
}
let v = self.this.get_idx(key, self.sup)?;
- Ok(v.map_or(GetFor::NotFound, |v| GetFor::Final(v)))
+ Ok(v.map_or(GetFor::NotFound, GetFor::Final))
}
fn field_visibility_core(&self, field: IStr) -> FieldVisibility {
- match self.this.field_visibility_idx(field, self.sup) {
- Some(c) => FieldVisibility::Found(c),
- None => FieldVisibility::NotFound,
- }
+ self.this
+ .field_visibility_idx(field, self.sup)
+ .map_or(FieldVisibility::NotFound, FieldVisibility::Found)
}
fn run_assertions_core(&self, _sup_this: SupThis) -> Result<()> {
crates/jrsonnet-evaluator/src/obj/oop.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/obj/oop.rs
+++ b/crates/jrsonnet-evaluator/src/obj/oop.rs
@@ -1,4 +1,4 @@
-use std::cell::Cell;
+use std::cell::{Cell, RefCell};
use std::ops::ControlFlow;
use std::{fmt, mem};
@@ -105,7 +105,7 @@
fn run_assertions_core(&self, sup_this: SupThis) -> Result<()> {
if let Some(assertion) = &self.assertion {
- assertion.0.run(sup_this.clone())?;
+ assertion.0.run(sup_this)?;
}
Ok(())
}
@@ -196,7 +196,7 @@
ObjValue(Cc::new(ObjValueInner {
cores: self.sup,
assertions_ran: Cell::new(false),
- value_cache: Default::default(),
+ value_cache: RefCell::default(),
}))
}
}
crates/jrsonnet-evaluator/src/stack.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/stack.rs
+++ b/crates/jrsonnet-evaluator/src/stack.rs
@@ -17,6 +17,7 @@
}
}
#[cfg(not(nightly))]
+#[allow(dead_code)]
type NightlyLocalKey<T> = std::thread::LocalKey<T>;
#[cfg(nightly)]
@@ -60,7 +61,7 @@
pub struct StackDepthGuard(PhantomData<()>);
impl Drop for StackDepthGuard {
fn drop(&mut self) {
- STACK_LIMIT.with(|limit| limit.current_depth.set(limit.current_depth.get() - 1))
+ STACK_LIMIT.with(|limit| limit.current_depth.set(limit.current_depth.get() - 1));
}
}
crates/jrsonnet-evaluator/src/stdlib/format.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/stdlib/format.rs
+++ b/crates/jrsonnet-evaluator/src/stdlib/format.rs
@@ -297,6 +297,7 @@
const NUMBERS: &[u8] = b"0123456789abcdefghijklmnopqrstuvwxyz";
#[inline]
+#[allow(clippy::fn_params_excessive_bools)]
pub fn render_integer(
out: &mut String,
neg: bool,
@@ -330,7 +331,7 @@
let pref_len = zero_prefix.len() as u16;
let zp2 = zp
- .saturating_sub(if !prefix_in_padding { pref_len } else { 0 })
+ .saturating_sub(if prefix_in_padding { 0 } else { pref_len })
.max(precision)
.saturating_sub(if prefix_in_padding { pref_len } else { 0 } + digits.len() as u16);
@@ -369,6 +370,7 @@
out, neg, iv, padding, precision, blank, sign, 10, "", false, false,
);
}
+#[allow(clippy::fn_params_excessive_bools)]
pub fn render_octal(
out: &mut String,
neg: bool,
@@ -439,8 +441,8 @@
// Note that it can also be equal to 10**prec and we'll need to carry
// over to the wholes. We operate on the absolute numbers, so that we
// don't have trouble with the rounding direction.
- let denominator = 10.0f64.powi(precision as i32);
- let numerator = n.abs() * denominator + 0.5;
+ let denominator = 10.0f64.powi(i32::from(precision));
+ let numerator = n.abs().mul_add(denominator, 0.5);
let whole = (numerator / denominator).floor();
let frac = numerator.floor() % denominator;
@@ -611,7 +613,7 @@
} else {
value.abs().log10().floor()
};
- if exponent < -4.0 || exponent >= fpprec as f64 {
+ if exponent < -4.0 || exponent >= f64::from(fpprec) {
render_float_sci(
&mut tmp_out,
value,
@@ -661,7 +663,7 @@
}
},
ConvTypeV::Percent => tmp_out.push('%'),
- };
+ }
let padding = width.saturating_sub(tmp_out.len() as u16);
crates/jrsonnet-evaluator/src/tla.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/tla.rs
+++ b/crates/jrsonnet-evaluator/src/tla.rs
@@ -1,13 +1,14 @@
+use std::{collections::HashMap, hash::BuildHasher};
+
use jrsonnet_interner::IStr;
use jrsonnet_parser::Source;
-use rustc_hash::FxHashMap;
use crate::{
function::{CallLocation, TlaArg},
in_description_frame, with_state, Result, Val,
};
-pub fn apply_tla(args: &FxHashMap<IStr, TlaArg>, val: Val) -> Result<Val> {
+pub fn apply_tla<H: BuildHasher>(args: &HashMap<IStr, TlaArg, H>, val: Val) -> Result<Val> {
Ok(if let Val::Func(func) = val {
in_description_frame(
|| "during TLA call".to_owned(),
crates/jrsonnet-evaluator/src/typed/conversions.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/typed/conversions.rs
+++ b/crates/jrsonnet-evaluator/src/typed/conversions.rs
@@ -462,7 +462,7 @@
};
if let Some(bytes) = a.as_any().downcast_ref::<BytesArray>() {
return Ok(bytes.0.as_slice().into());
- };
+ }
<Self as Typed>::TYPE.check(&value)?;
// Any::downcast_ref::<ByteArray>(&a);
let mut out = Vec::with_capacity(a.len());
crates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/val.rs
+++ b/crates/jrsonnet-evaluator/src/val.rs
@@ -65,7 +65,7 @@
MemoizedClusureThunkInner::Errored(e) => return Err(e.clone()),
MemoizedClusureThunkInner::Pending => return Err(InfiniteRecursionDetected.into()),
MemoizedClusureThunkInner::Waiting { .. } => (),
- };
+ }
let MemoizedClusureThunkInner::Waiting { env, closure } = replace(
&mut *self.0.borrow_mut(),
MemoizedClusureThunkInner::Pending,
@@ -288,14 +288,11 @@
Self::Str(s) => {
let mut computed_len = None;
let mut get_len = || {
- computed_len.map_or_else(
- || {
- let len = s.chars().count();
- let _ = computed_len.insert(len);
- len
- },
- |len| len,
- )
+ computed_len.unwrap_or_else(|| {
+ let len = s.chars().count();
+ let _ = computed_len.insert(len);
+ len
+ })
};
let mut get_idx = |pos: Option<i32>, default| {
match pos {
@@ -446,7 +443,7 @@
pub const fn get(&self) -> f64 {
self.0
}
- pub(crate) fn truncate_for_bitwise(&self) -> Result<i64> {
+ pub(crate) fn truncate_for_bitwise(self) -> Result<i64> {
if self.0 < MIN_SAFE_INTEGER || self.0 > MAX_SAFE_INTEGER {
bail!("numberic value outside of safe integer range for bitwise operation");
}
crates/jrsonnet-interner/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-interner/src/lib.rs
+++ b/crates/jrsonnet-interner/src/lib.rs
@@ -227,9 +227,11 @@
type PoolMap = HashMap<Inner, (), FxBuildHasher>;
thread_local! {
- static POOL: RefCell<PoolMap> = RefCell::new(HashMap::with_capacity_and_hasher(200, FxBuildHasher::default()));
+ static POOL: RefCell<PoolMap> = RefCell::new(HashMap::with_capacity_and_hasher(200, FxBuildHasher));
}
+/// Utils for embedding jrsonnet in non-rust.
+///
/// Jrsonnet golang bindings require that it is possible to move jsonnet
/// VM between OS threads, and this is not possible due to usage of
/// `thread_local`. Instead, there is two methods added, one should be
crates/jrsonnet-macros/src/lib.rsdiffbeforeafterboth1use std::string::String;23use proc_macro2::TokenStream;4use quote::{quote, quote_spanned};5use syn::{6 parenthesized,7 parse::{Parse, ParseStream},8 parse_macro_input,9 punctuated::Punctuated,10 spanned::Spanned,11 token::{self, Comma},12 Attribute, DeriveInput, Error, Expr, ExprClosure, FnArg, GenericArgument, Ident, ItemFn,13 LitStr, Pat, Path, PathArguments, Result, ReturnType, Token, Type,14};1516fn parse_attr<A: Parse, I>(attrs: &[Attribute], ident: I) -> Result<Option<A>>17where18 Ident: PartialEq<I>,19{20 let attrs = attrs21 .iter()22 .filter(|a| a.path().is_ident(&ident))23 .collect::<Vec<_>>();24 if attrs.len() > 1 {25 return Err(Error::new(26 attrs[1].span(),27 "this attribute may be specified only once",28 ));29 } else if attrs.is_empty() {30 return Ok(None);31 }32 let attr = attrs[0];33 let attr = attr.parse_args::<A>()?;3435 Ok(Some(attr))36}37fn remove_attr<I>(attrs: &mut Vec<Attribute>, ident: I)38where39 Ident: PartialEq<I>,40{41 attrs.retain(|a| !a.path().is_ident(&ident));42}4344fn path_is(path: &Path, needed: &str) -> bool {45 path.leading_colon.is_none()46 && !path.segments.is_empty()47 && path.segments.iter().last().unwrap().ident == needed48}4950fn type_is_path<'ty>(ty: &'ty Type, needed: &str) -> Option<&'ty PathArguments> {51 match ty {52 Type::Path(path) if path.qself.is_none() && path_is(&path.path, needed) => {53 let args = &path.path.segments.iter().last().unwrap().arguments;54 Some(args)55 }56 _ => None,57 }58}5960fn extract_type_from_option(ty: &Type) -> Result<Option<&Type>> {61 let Some(args) = type_is_path(ty, "Option") else {62 return Ok(None);63 };64 // It should have only on angle-bracketed param ("<String>"):65 let PathArguments::AngleBracketed(params) = args else {66 return Err(Error::new(args.span(), "missing option generic"));67 };68 let generic_arg = params.args.iter().next().unwrap();69 // This argument must be a type:70 let GenericArgument::Type(ty) = generic_arg else {71 return Err(Error::new(72 generic_arg.span(),73 "option generic should be a type",74 ));75 };76 Ok(Some(ty))77}7879struct Field {80 attrs: Vec<Attribute>,81 name: Ident,82 _colon: Token![:],83 ty: Type,84}85impl Parse for Field {86 fn parse(input: ParseStream) -> syn::Result<Self> {87 Ok(Self {88 attrs: input.call(Attribute::parse_outer)?,89 name: input.parse()?,90 _colon: input.parse()?,91 ty: input.parse()?,92 })93 }94}9596mod kw {97 syn::custom_keyword!(fields);98 syn::custom_keyword!(rename);99 syn::custom_keyword!(alias);100 syn::custom_keyword!(flatten);101 syn::custom_keyword!(add);102 syn::custom_keyword!(hide);103 syn::custom_keyword!(ok);104}105106struct BuiltinAttrs {107 fields: Vec<Field>,108}109impl Parse for BuiltinAttrs {110 fn parse(input: ParseStream) -> syn::Result<Self> {111 if input.is_empty() {112 return Ok(Self { fields: Vec::new() });113 }114 input.parse::<kw::fields>()?;115 let fields;116 parenthesized!(fields in input);117 let p = Punctuated::<Field, Comma>::parse_terminated(&fields)?;118 Ok(Self {119 fields: p.into_iter().collect(),120 })121 }122}123124enum Optionality {125 Required,126 Optional,127 Default(Expr),128}129130enum ArgInfo {131 Normal {132 ty: Box<Type>,133 optionality: Optionality,134 name: Option<String>,135 cfg_attrs: Vec<Attribute>,136 },137 Lazy {138 is_option: bool,139 name: Option<String>,140 },141 Context,142 Location,143 This,144}145146impl ArgInfo {147 fn parse(name: &str, arg: &mut FnArg) -> Result<Self> {148 let FnArg::Typed(arg) = arg else {149 unreachable!()150 };151 let ident = match &arg.pat as &Pat {152 Pat::Ident(i) => Some(i.ident.clone()),153 _ => None,154 };155 let ty = &arg.ty;156 if type_is_path(ty, "Context").is_some() {157 return Ok(Self::Context);158 } else if type_is_path(ty, "CallLocation").is_some() {159 return Ok(Self::Location);160 } else if type_is_path(ty, "Thunk").is_some() {161 return Ok(Self::Lazy {162 is_option: false,163 name: ident.map(|v| v.to_string()),164 });165 }166167 match ty as &Type {168 Type::Reference(r) if type_is_path(&r.elem, name).is_some() => return Ok(Self::This),169 _ => {}170 }171172 let (optionality, ty) = if let Some(default) = parse_attr::<_, _>(&arg.attrs, "default")? {173 remove_attr(&mut arg.attrs, "default");174 (Optionality::Default(default), ty.clone())175 } else if let Some(ty) = extract_type_from_option(ty)? {176 if type_is_path(ty, "Thunk").is_some() {177 return Ok(Self::Lazy {178 is_option: true,179 name: ident.map(|v| v.to_string()),180 });181 }182183 (Optionality::Optional, Box::new(ty.clone()))184 } else {185 (Optionality::Required, ty.clone())186 };187188 let cfg_attrs = arg189 .attrs190 .iter()191 .filter(|a| a.path().is_ident("cfg"))192 .cloned()193 .collect();194195 Ok(Self::Normal {196 ty,197 optionality,198 name: ident.map(|v| v.to_string()),199 cfg_attrs,200 })201 }202}203204#[proc_macro_attribute]205pub fn builtin(206 attr: proc_macro::TokenStream,207 item: proc_macro::TokenStream,208) -> proc_macro::TokenStream {209 let attr = parse_macro_input!(attr as BuiltinAttrs);210 let item_fn = parse_macro_input!(item as ItemFn);211212 match builtin_inner(attr, item_fn) {213 Ok(v) => v.into(),214 Err(e) => e.into_compile_error().into(),215 }216}217218#[allow(clippy::too_many_lines)]219fn builtin_inner(attr: BuiltinAttrs, mut fun: ItemFn) -> syn::Result<TokenStream> {220 let ReturnType::Type(_, result) = &fun.sig.output else {221 return Err(Error::new(222 fun.sig.span(),223 "builtin should return something",224 ));225 };226227 let name = fun.sig.ident.to_string();228 let args = fun229 .sig230 .inputs231 .iter_mut()232 .map(|arg| ArgInfo::parse(&name, arg))233 .collect::<Result<Vec<_>>>()?;234235 let params_desc = args.iter().filter_map(|a| match a {236 ArgInfo::Normal {237 optionality,238 name,239 cfg_attrs,240 ..241 } => {242 let name = name243 .as_ref()244 .map_or_else(|| quote! {unnamed}, |n| quote! {named(#n)});245 let default = match optionality {246 Optionality::Required => quote!(ParamDefault::None),247 Optionality::Optional => quote!(ParamDefault::Exists),248 Optionality::Default(e) => quote!(ParamDefault::Literal(stringify!(#e))),249 };250 Some(quote! {251 #(#cfg_attrs)*252 [#name => #default],253 })254 }255 ArgInfo::Lazy { is_option, name } => {256 let name = name257 .as_ref()258 .map_or_else(|| quote! {unnamed}, |n| quote! {named(#n)});259 Some(quote! {260 [#name => ParamDefault::exists(#is_option)],261 })262 }263 ArgInfo::Context | ArgInfo::Location | ArgInfo::This => None,264 });265266 let mut id = 0usize;267 let pass = args268 .iter()269 .map(|a| match a {270 ArgInfo::Normal { .. } | ArgInfo::Lazy { .. } => {271 let cid = id;272 id += 1;273 (quote! {#cid}, a)274 }275 ArgInfo::Context | ArgInfo::Location | ArgInfo::This => {276 (quote! {compile_error!("should not use id")}, a)277 }278 })279 .map(|(id, a)| match a {280 ArgInfo::Normal {281 ty,282 optionality,283 name,284 cfg_attrs,285 } => {286 let name = name.as_ref().map_or("<unnamed>", String::as_str);287 let eval = quote! {jrsonnet_evaluator::in_description_frame(288 || format!("argument <{}> evaluation", #name),289 || <#ty>::from_untyped(value.evaluate()?),290 )?};291 let value = match optionality {292 Optionality::Required => quote! {{293 let value = parsed[#id].as_ref().expect("args shape is checked");294 #eval295 },},296 Optionality::Optional => quote! {if let Some(value) = &parsed[#id] {297 Some(#eval)298 } else {299 None300 },},301 Optionality::Default(expr) => quote! {if let Some(value) = &parsed[#id] {302 #eval303 } else {304 let v: #ty = #expr;305 v306 },},307 };308 quote! {309 #(#cfg_attrs)*310 #value311 }312 }313 ArgInfo::Lazy { is_option, .. } => {314 if *is_option {315 quote! {if let Some(value) = &parsed[#id] {316 Some(value.clone())317 } else {318 None319 },}320 } else {321 quote! {322 parsed[#id].as_ref().expect("args shape is correct").clone(),323 }324 }325 }326 ArgInfo::Context => quote! {ctx.clone(),},327 ArgInfo::Location => quote! {location,},328 ArgInfo::This => quote! {self,},329 });330331 let fields = attr.fields.iter().map(|field| {332 let attrs = &field.attrs;333 let name = &field.name;334 let ty = &field.ty;335 quote! {336 #(#attrs)*337 pub #name: #ty,338 }339 });340341 let name = &fun.sig.ident;342 let vis = &fun.vis;343 let static_ext = if attr.fields.is_empty() {344 quote! {345 impl #name {346 pub const INST: &'static dyn StaticBuiltin = &#name {};347 }348 impl StaticBuiltin for #name {}349 }350 } else {351 quote! {}352 };353 let static_derive_copy = if attr.fields.is_empty() {354 quote! {, Copy}355 } else {356 quote! {}357 };358359 Ok(quote! {360 #fun361362 #[doc(hidden)]363 #[allow(non_camel_case_types)]364 #[derive(Clone, jrsonnet_gcmodule::Trace #static_derive_copy)]365 #vis struct #name {366 #(#fields)*367 }368 const _: () = {369 use ::jrsonnet_evaluator::{370 State, Val,371 function::{builtin::{Builtin, StaticBuiltin}, FunctionSignature, ParamParse, ParamName, ParamDefault, CallLocation, ArgsLike, parse::parse_builtin_call},372 Result, Context, typed::Typed,373 parser::Span, params,374 };375 params!(376 #(#params_desc)*377 );378379 #static_ext380 impl Builtin for #name381 where382 Self: 'static383 {384 fn name(&self) -> &str {385 stringify!(#name)386 }387 fn params(&self) -> FunctionSignature {388 PARAMS.with(|p| p.clone())389 }390 #[allow(unused_variables)]391 fn call(&self, ctx: Context, location: CallLocation, args: &dyn ArgsLike) -> Result<Val> {392 let parsed = parse_builtin_call(ctx.clone(), self.params(), args, false)?;393394 let result: #result = #name(#(#pass)*);395 <_ as Typed>::into_result(result)396 }397 fn as_any(&self) -> &dyn ::std::any::Any {398 self399 }400 }401 };402 })403}404405#[derive(Default)]406#[allow(clippy::struct_excessive_bools)]407struct TypedAttr {408 rename: Option<String>,409 aliases: Vec<String>,410 flatten: bool,411 /// flatten(ok) strategy for flattened optionals412 /// field would be None in case of any parsing error (as in serde)413 flatten_ok: bool,414 // Should it be `field+:` instead of `field:`415 add: bool,416 // Should it be `field::` instead of `field:`417 hide: bool,418}419impl Parse for TypedAttr {420 fn parse(input: ParseStream) -> syn::Result<Self> {421 let mut out = Self::default();422 loop {423 let lookahead = input.lookahead1();424 if lookahead.peek(kw::rename) {425 input.parse::<kw::rename>()?;426 input.parse::<Token![=]>()?;427 let name = input.parse::<LitStr>()?;428 if out.rename.is_some() {429 return Err(Error::new(430 name.span(),431 "rename attribute may only be specified once",432 ));433 }434 out.rename = Some(name.value());435 } else if lookahead.peek(kw::alias) {436 input.parse::<kw::alias>()?;437 input.parse::<Token![=]>()?;438 let alias = input.parse::<LitStr>()?;439 out.aliases.push(alias.value());440 } else if lookahead.peek(kw::flatten) {441 input.parse::<kw::flatten>()?;442 out.flatten = true;443 if input.peek(token::Paren) {444 let content;445 parenthesized!(content in input);446 let lookahead = content.lookahead1();447 if lookahead.peek(kw::ok) {448 content.parse::<kw::ok>()?;449 out.flatten_ok = true;450 } else {451 return Err(lookahead.error());452 }453 }454 } else if lookahead.peek(kw::add) {455 input.parse::<kw::add>()?;456 out.add = true;457 } else if lookahead.peek(kw::hide) {458 input.parse::<kw::hide>()?;459 out.hide = true;460 } else if input.is_empty() {461 break;462 } else {463 return Err(lookahead.error());464 }465 if input.peek(Token![,]) {466 input.parse::<Token![,]>()?;467 } else {468 break;469 }470 }471 Ok(out)472 }473}474475struct TypedField {476 attr: TypedAttr,477 ident: Ident,478 ty: Type,479 is_option: bool,480 is_lazy: bool,481}482impl TypedField {483 fn parse(field: &syn::Field) -> Result<Self> {484 let attr = parse_attr::<TypedAttr, _>(&field.attrs, "typed")?.unwrap_or_default();485 let Some(ident) = field.ident.clone() else {486 return Err(Error::new(487 field.span(),488 "this field should appear in output object, but it has no visible name",489 ));490 };491 let (is_option, ty) = extract_type_from_option(&field.ty)?492 .map_or_else(|| (false, field.ty.clone()), |ty| (true, ty.clone()));493 if is_option && attr.flatten {494 if !attr.flatten_ok {495 return Err(Error::new(496 field.span(),497 "strategy should be set when flattening Option",498 ));499 }500 } else if attr.flatten_ok {501 return Err(Error::new(502 field.span(),503 "flatten(ok) is only useable on optional fields",504 ));505 }506507 let is_lazy = type_is_path(&ty, "Thunk").is_some();508509 Ok(Self {510 attr,511 ident,512 ty,513 is_option,514 is_lazy,515 })516 }517 /// None if this field is flattened in jsonnet output518 fn name(&self) -> Option<String> {519 if self.attr.flatten {520 return None;521 }522 Some(523 self.attr524 .rename525 .clone()526 .unwrap_or_else(|| self.ident.to_string()),527 )528 }529530 fn expand_field(&self) -> Option<TokenStream> {531 if self.is_option {532 return None;533 }534 let name = self.name()?;535 let ty = &self.ty;536 Some(quote! {537 (#name, <#ty as Typed>::TYPE)538 })539 }540541 fn expand_parse(&self) -> TokenStream {542 if self.is_option {543 self.expand_parse_optional()544 } else {545 self.expand_parse_mandatory()546 }547 }548549 fn expand_parse_optional(&self) -> TokenStream {550 let ident = &self.ident;551 let ty = &self.ty;552553 // optional flatten is handled in same way as serde554 if self.attr.flatten {555 return quote! {556 #ident: <#ty as TypedObj>::parse(&obj).ok(),557 };558 }559560 let name = self.name().unwrap();561 let aliases = &self.attr.aliases;562563 quote! {564 #ident: {565 let __value = if let Some(__v) = obj.get(#name.into())? {566 Some(__v)567 } #(else if let Some(__v) = obj.get(#aliases.into())? {568 Some(__v)569 })* else {570 None571 };572573 __value.map(<#ty as Typed>::from_untyped).transpose()?574 },575 }576 }577578 fn expand_parse_mandatory(&self) -> TokenStream {579 let ident = &self.ident;580 let ty = &self.ty;581582 // optional flatten is handled in same way as serde583 if self.attr.flatten {584 return quote! {585 #ident: <#ty as TypedObj>::parse(&obj)?,586 };587 }588589 let name = self.name().unwrap();590 let aliases = &self.attr.aliases;591592 let error_text = if aliases.is_empty() {593 // clippy does not understand name variable usage in quote! macro594 #[allow(clippy::redundant_clone)]595 name.clone()596 } else {597 format!("{name} (alias {})", aliases.join(", "))598 };599600 quote! {601 #ident: {602 let __value = if let Some(__v) = obj.get(#name.into())? {603 __v604 } #(else if let Some(__v) = obj.get(#aliases.into())? {605 __v606 })* else {607 return Err(ErrorKind::NoSuchField(#error_text.into(), vec![]).into());608 };609610 <#ty as Typed>::from_untyped(__value)?611 },612 }613 }614615 fn expand_serialize(&self) -> TokenStream {616 let ident = &self.ident;617 let ty = &self.ty;618 self.name().map_or_else(619 || {620 if self.is_option {621 quote! {622 if let Some(value) = self.#ident {623 <#ty as TypedObj>::serialize(value, out)?;624 }625 }626 } else {627 quote! {628 <#ty as TypedObj>::serialize(self.#ident, out)?;629 }630 }631 },632 |name| {633 let hide = if self.attr.hide {634 quote! {.hide()}635 } else {636 quote! {}637 };638 let add = if self.attr.add {639 quote! {.add()}640 } else {641 quote! {}642 };643 let value = if self.is_lazy {644 quote! {645 out.field(#name)646 #hide647 #add648 .try_thunk(<#ty as Typed>::into_lazy_untyped(value))?;649 }650 } else {651 quote! {652 out.field(#name)653 #hide654 #add655 .try_value(<#ty as Typed>::into_untyped(value)?)?;656 }657 };658 if self.is_option {659 quote! {660 if let Some(value) = self.#ident {661 #value662 }663 }664 } else {665 quote! {666 {667 let value = self.#ident;668 #value669 }670 }671 }672 },673 )674 }675}676677#[proc_macro_derive(Typed, attributes(typed))]678pub fn derive_typed(item: proc_macro::TokenStream) -> proc_macro::TokenStream {679 let input = parse_macro_input!(item as DeriveInput);680681 match derive_typed_inner(input) {682 Ok(v) => v.into(),683 Err(e) => e.to_compile_error().into(),684 }685}686687fn derive_typed_inner(input: DeriveInput) -> Result<TokenStream> {688 let syn::Data::Struct(data) = &input.data else {689 return Err(Error::new(input.span(), "only structs supported"));690 };691692 let ident = &input.ident;693 let fields = data694 .fields695 .iter()696 .map(TypedField::parse)697 .collect::<Result<Vec<_>>>()?;698699 let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();700701 let typed = {702 let fields = fields703 .iter()704 .filter_map(TypedField::expand_field)705 .collect::<Vec<_>>();706 quote! {707 impl #impl_generics Typed for #ident #ty_generics #where_clause {708 const TYPE: &'static ComplexValType = &ComplexValType::ObjectRef(&[709 #(#fields,)*710 ]);711712 fn from_untyped(value: Val) -> JrResult<Self> {713 let obj = value.as_obj().expect("shape is correct");714 Self::parse(&obj)715 }716717 fn into_untyped(value: Self) -> JrResult<Val> {718 let mut out = ObjValueBuilder::new();719 value.serialize(&mut out)?;720 Ok(Val::Obj(out.build()))721 }722723 }724 }725 };726727 let fields_parse = fields.iter().map(TypedField::expand_parse);728 let fields_serialize = fields729 .iter()730 .map(TypedField::expand_serialize)731 .collect::<Vec<_>>();732733 Ok(quote! {734 const _: () = {735 use ::jrsonnet_evaluator::{736 typed::{ComplexValType, Typed, TypedObj, CheckType},737 Val, State,738 error::{ErrorKind, Result as JrResult},739 ObjValueBuilder, ObjValue,740 };741742 #typed743744 impl #impl_generics TypedObj for #ident #ty_generics #where_clause {745 fn serialize(self, out: &mut ObjValueBuilder) -> JrResult<()> {746 #(#fields_serialize)*747748 Ok(())749 }750 fn parse(obj: &ObjValue) -> JrResult<Self> {751 Ok(Self {752 #(#fields_parse)*753 })754 }755 }756 };757 })758}759760struct FormatInput {761 formatting: LitStr,762 arguments: Vec<Expr>,763}764impl Parse for FormatInput {765 fn parse(input: ParseStream) -> Result<Self> {766 let formatting = input.parse()?;767 let mut arguments = Vec::new();768769 while input.peek(Token![,]) {770 input.parse::<Token![,]>()?;771 if input.is_empty() {772 // Trailing comma773 break;774 }775 let expr = input.parse()?;776 arguments.push(expr);777 }778779 if !input.is_empty() {780 return Err(syn::Error::new(input.span(), "unexpected trailing input"));781 }782783 Ok(Self {784 formatting,785 arguments,786 })787 }788}789fn is_format_str(i: &str) -> bool {790 let mut is_plain = true;791 // -1 = {792 // +1 = }793 let mut is_bracket = 0i8;794 for ele in i.chars() {795 match ele {796 '{' if is_bracket == -1 => {797 is_bracket = 0;798 }799 '}' if is_bracket == -1 => {800 is_plain = false;801 break;802 }803 '}' if is_bracket == 1 => {804 is_bracket = 0;805 }806 '{' if is_bracket == 1 => {807 is_plain = false;808 break;809 }810 '{' => {811 is_bracket = -1;812 }813 '}' => {814 is_bracket = 1;815 }816 _ if is_bracket != 0 => {817 is_plain = false;818 break;819 }820 _ => {}821 }822 }823 !is_plain || is_bracket != 0824}825impl FormatInput {826 fn expand(self) -> TokenStream {827 let format = self.formatting;828 if is_format_str(&format.value()) {829 let args = self.arguments;830 quote! {831 ::jrsonnet_evaluator::IStr::from(format!(#format #(, #args)*))832 }833 } else {834 if let Some(first) = self.arguments.first() {835 return syn::Error::new(836 first.span(),837 "string has no formatting codes, it should not have the arguments",838 )839 .into_compile_error();840 }841 quote! {842 ::jrsonnet_evaluator::IStr::from(#format)843 }844 }845 }846}847848/// `IStr` formatting helper849///850/// Using `format!("literal with no codes").into()` is slower than just `"literal with no codes".into()`851/// This macro looks for formatting codes in the input string, and uses852/// `format!()` only when necessary853#[proc_macro]854pub fn format_istr(input: proc_macro::TokenStream) -> proc_macro::TokenStream {855 let input = parse_macro_input!(input as FormatInput);856 input.expand().into()857}858859/// Create Thunk using closure syntax860#[proc_macro]861#[allow(non_snake_case)]862pub fn Thunk(input: proc_macro::TokenStream) -> proc_macro::TokenStream {863 let input = parse_macro_input!(input as ExprClosure);864865 let span = input.inputs.span();866 let move_check = input.capture.is_none().then(|| {867 quote_spanned! {span => {868 compile_error!("Thunk! needs to be called with move closure");869 }}870 });871872 let (env, closure, args) = syn_dissect_closure::split_env(input);873874 let trace_check = args.iter().map(|el| {875 let span = el.span();876 quote_spanned! {span => ::jrsonnet_evaluator::gc::assert_trace(&#el);}877 });878879 quote! {{880 #move_check881 #(#trace_check)*882 ::jrsonnet_evaluator::Thunk::new(::jrsonnet_evaluator::val::MemoizedClosureThunk::new(#env, #closure))883 }}.into()884}1use std::string::String;23use proc_macro2::TokenStream;4use quote::{quote, quote_spanned};5use syn::{6 parenthesized,7 parse::{Parse, ParseStream},8 parse_macro_input,9 punctuated::Punctuated,10 spanned::Spanned,11 token::{self, Comma},12 Attribute, DeriveInput, Error, Expr, ExprClosure, FnArg, GenericArgument, Ident, ItemFn,13 LitStr, Pat, Path, PathArguments, Result, ReturnType, Token, Type,14};1516fn parse_attr<A: Parse, I>(attrs: &[Attribute], ident: I) -> Result<Option<A>>17where18 Ident: PartialEq<I>,19{20 let attrs = attrs21 .iter()22 .filter(|a| a.path().is_ident(&ident))23 .collect::<Vec<_>>();24 if attrs.len() > 1 {25 return Err(Error::new(26 attrs[1].span(),27 "this attribute may be specified only once",28 ));29 } else if attrs.is_empty() {30 return Ok(None);31 }32 let attr = attrs[0];33 let attr = attr.parse_args::<A>()?;3435 Ok(Some(attr))36}37fn remove_attr<I>(attrs: &mut Vec<Attribute>, ident: I)38where39 Ident: PartialEq<I>,40{41 attrs.retain(|a| !a.path().is_ident(&ident));42}4344fn path_is(path: &Path, needed: &str) -> bool {45 path.leading_colon.is_none()46 && !path.segments.is_empty()47 && path.segments.iter().last().unwrap().ident == needed48}4950fn type_is_path<'ty>(ty: &'ty Type, needed: &str) -> Option<&'ty PathArguments> {51 match ty {52 Type::Path(path) if path.qself.is_none() && path_is(&path.path, needed) => {53 let args = &path.path.segments.iter().last().unwrap().arguments;54 Some(args)55 }56 _ => None,57 }58}5960fn extract_type_from_option(ty: &Type) -> Result<Option<&Type>> {61 let Some(args) = type_is_path(ty, "Option") else {62 return Ok(None);63 };64 // It should have only on angle-bracketed param ("<String>"):65 let PathArguments::AngleBracketed(params) = args else {66 return Err(Error::new(args.span(), "missing option generic"));67 };68 let generic_arg = params.args.iter().next().unwrap();69 // This argument must be a type:70 let GenericArgument::Type(ty) = generic_arg else {71 return Err(Error::new(72 generic_arg.span(),73 "option generic should be a type",74 ));75 };76 Ok(Some(ty))77}7879struct Field {80 attrs: Vec<Attribute>,81 name: Ident,82 _colon: Token![:],83 ty: Type,84}85impl Parse for Field {86 fn parse(input: ParseStream) -> syn::Result<Self> {87 Ok(Self {88 attrs: input.call(Attribute::parse_outer)?,89 name: input.parse()?,90 _colon: input.parse()?,91 ty: input.parse()?,92 })93 }94}9596mod kw {97 syn::custom_keyword!(fields);98 syn::custom_keyword!(rename);99 syn::custom_keyword!(alias);100 syn::custom_keyword!(flatten);101 syn::custom_keyword!(add);102 syn::custom_keyword!(hide);103 syn::custom_keyword!(ok);104}105106struct BuiltinAttrs {107 fields: Vec<Field>,108}109impl Parse for BuiltinAttrs {110 fn parse(input: ParseStream) -> syn::Result<Self> {111 if input.is_empty() {112 return Ok(Self { fields: Vec::new() });113 }114 input.parse::<kw::fields>()?;115 let fields;116 parenthesized!(fields in input);117 let p = Punctuated::<Field, Comma>::parse_terminated(&fields)?;118 Ok(Self {119 fields: p.into_iter().collect(),120 })121 }122}123124enum Optionality {125 Required,126 Optional,127 Default(Expr),128}129130#[allow(clippy::large_enum_variant, reason = "this macro is not that hot for it to matter")]131enum ArgInfo {132 Normal {133 ty: Box<Type>,134 optionality: Optionality,135 name: Option<String>,136 cfg_attrs: Vec<Attribute>,137 },138 Lazy {139 is_option: bool,140 name: Option<String>,141 },142 Context,143 Location,144 This,145}146147impl ArgInfo {148 fn parse(name: &str, arg: &mut FnArg) -> Result<Self> {149 let FnArg::Typed(arg) = arg else {150 unreachable!()151 };152 let ident = match &arg.pat as &Pat {153 Pat::Ident(i) => Some(i.ident.clone()),154 _ => None,155 };156 let ty = &arg.ty;157 if type_is_path(ty, "Context").is_some() {158 return Ok(Self::Context);159 } else if type_is_path(ty, "CallLocation").is_some() {160 return Ok(Self::Location);161 } else if type_is_path(ty, "Thunk").is_some() {162 return Ok(Self::Lazy {163 is_option: false,164 name: ident.map(|v| v.to_string()),165 });166 }167168 match ty as &Type {169 Type::Reference(r) if type_is_path(&r.elem, name).is_some() => return Ok(Self::This),170 _ => {}171 }172173 let (optionality, ty) = if let Some(default) = parse_attr::<_, _>(&arg.attrs, "default")? {174 remove_attr(&mut arg.attrs, "default");175 (Optionality::Default(default), ty.clone())176 } else if let Some(ty) = extract_type_from_option(ty)? {177 if type_is_path(ty, "Thunk").is_some() {178 return Ok(Self::Lazy {179 is_option: true,180 name: ident.map(|v| v.to_string()),181 });182 }183184 (Optionality::Optional, Box::new(ty.clone()))185 } else {186 (Optionality::Required, ty.clone())187 };188189 let cfg_attrs = arg190 .attrs191 .iter()192 .filter(|a| a.path().is_ident("cfg"))193 .cloned()194 .collect();195196 Ok(Self::Normal {197 ty,198 optionality,199 name: ident.map(|v| v.to_string()),200 cfg_attrs,201 })202 }203}204205#[proc_macro_attribute]206pub fn builtin(207 attr: proc_macro::TokenStream,208 item: proc_macro::TokenStream,209) -> proc_macro::TokenStream {210 let attr = parse_macro_input!(attr as BuiltinAttrs);211 let item_fn = parse_macro_input!(item as ItemFn);212213 match builtin_inner(attr, item_fn) {214 Ok(v) => v.into(),215 Err(e) => e.into_compile_error().into(),216 }217}218219#[allow(clippy::too_many_lines)]220fn builtin_inner(attr: BuiltinAttrs, mut fun: ItemFn) -> syn::Result<TokenStream> {221 let ReturnType::Type(_, result) = &fun.sig.output else {222 return Err(Error::new(223 fun.sig.span(),224 "builtin should return something",225 ));226 };227228 let name = fun.sig.ident.to_string();229 let args = fun230 .sig231 .inputs232 .iter_mut()233 .map(|arg| ArgInfo::parse(&name, arg))234 .collect::<Result<Vec<_>>>()?;235236 let params_desc = args.iter().filter_map(|a| match a {237 ArgInfo::Normal {238 optionality,239 name,240 cfg_attrs,241 ..242 } => {243 let name = name244 .as_ref()245 .map_or_else(|| quote! {unnamed}, |n| quote! {named(#n)});246 let default = match optionality {247 Optionality::Required => quote!(ParamDefault::None),248 Optionality::Optional => quote!(ParamDefault::Exists),249 Optionality::Default(e) => quote!(ParamDefault::Literal(stringify!(#e))),250 };251 Some(quote! {252 #(#cfg_attrs)*253 [#name => #default],254 })255 }256 ArgInfo::Lazy { is_option, name } => {257 let name = name258 .as_ref()259 .map_or_else(|| quote! {unnamed}, |n| quote! {named(#n)});260 Some(quote! {261 [#name => ParamDefault::exists(#is_option)],262 })263 }264 ArgInfo::Context | ArgInfo::Location | ArgInfo::This => None,265 });266267 let mut id = 0usize;268 let pass = args269 .iter()270 .map(|a| match a {271 ArgInfo::Normal { .. } | ArgInfo::Lazy { .. } => {272 let cid = id;273 id += 1;274 (quote! {#cid}, a)275 }276 ArgInfo::Context | ArgInfo::Location | ArgInfo::This => {277 (quote! {compile_error!("should not use id")}, a)278 }279 })280 .map(|(id, a)| match a {281 ArgInfo::Normal {282 ty,283 optionality,284 name,285 cfg_attrs,286 } => {287 let name = name.as_ref().map_or("<unnamed>", String::as_str);288 let eval = quote! {jrsonnet_evaluator::in_description_frame(289 || format!("argument <{}> evaluation", #name),290 || <#ty>::from_untyped(value.evaluate()?),291 )?};292 let value = match optionality {293 Optionality::Required => quote! {{294 let value = parsed[#id].as_ref().expect("args shape is checked");295 #eval296 },},297 Optionality::Optional => quote! {if let Some(value) = &parsed[#id] {298 Some(#eval)299 } else {300 None301 },},302 Optionality::Default(expr) => quote! {if let Some(value) = &parsed[#id] {303 #eval304 } else {305 let v: #ty = #expr;306 v307 },},308 };309 quote! {310 #(#cfg_attrs)*311 #value312 }313 }314 ArgInfo::Lazy { is_option, .. } => {315 if *is_option {316 quote! {if let Some(value) = &parsed[#id] {317 Some(value.clone())318 } else {319 None320 },}321 } else {322 quote! {323 parsed[#id].as_ref().expect("args shape is correct").clone(),324 }325 }326 }327 ArgInfo::Context => quote! {ctx.clone(),},328 ArgInfo::Location => quote! {location,},329 ArgInfo::This => quote! {self,},330 });331332 let fields = attr.fields.iter().map(|field| {333 let attrs = &field.attrs;334 let name = &field.name;335 let ty = &field.ty;336 quote! {337 #(#attrs)*338 pub #name: #ty,339 }340 });341342 let name = &fun.sig.ident;343 let vis = &fun.vis;344 let static_ext = if attr.fields.is_empty() {345 quote! {346 impl #name {347 pub const INST: &'static dyn StaticBuiltin = &#name {};348 }349 impl StaticBuiltin for #name {}350 }351 } else {352 quote! {}353 };354 let static_derive_copy = if attr.fields.is_empty() {355 quote! {, Copy}356 } else {357 quote! {}358 };359360 Ok(quote! {361 #fun362363 #[doc(hidden)]364 #[allow(non_camel_case_types)]365 #[derive(Clone, jrsonnet_gcmodule::Trace #static_derive_copy)]366 #vis struct #name {367 #(#fields)*368 }369 const _: () = {370 use ::jrsonnet_evaluator::{371 State, Val,372 function::{builtin::{Builtin, StaticBuiltin}, FunctionSignature, ParamParse, ParamName, ParamDefault, CallLocation, ArgsLike, parse::parse_builtin_call},373 Result, Context, typed::Typed,374 parser::Span, params,375 };376 params!(377 #(#params_desc)*378 );379380 #static_ext381 impl Builtin for #name382 where383 Self: 'static384 {385 fn name(&self) -> &str {386 stringify!(#name)387 }388 fn params(&self) -> FunctionSignature {389 PARAMS.with(|p| p.clone())390 }391 #[allow(unused_variables)]392 fn call(&self, ctx: Context, location: CallLocation, args: &dyn ArgsLike) -> Result<Val> {393 let parsed = parse_builtin_call(ctx.clone(), self.params(), args, false)?;394395 let result: #result = #name(#(#pass)*);396 <_ as Typed>::into_result(result)397 }398 fn as_any(&self) -> &dyn ::std::any::Any {399 self400 }401 }402 };403 })404}405406#[derive(Default)]407#[allow(clippy::struct_excessive_bools)]408struct TypedAttr {409 rename: Option<String>,410 aliases: Vec<String>,411 flatten: bool,412 /// flatten(ok) strategy for flattened optionals413 /// field would be None in case of any parsing error (as in serde)414 flatten_ok: bool,415 // Should it be `field+:` instead of `field:`416 add: bool,417 // Should it be `field::` instead of `field:`418 hide: bool,419}420impl Parse for TypedAttr {421 fn parse(input: ParseStream) -> syn::Result<Self> {422 let mut out = Self::default();423 loop {424 let lookahead = input.lookahead1();425 if lookahead.peek(kw::rename) {426 input.parse::<kw::rename>()?;427 input.parse::<Token![=]>()?;428 let name = input.parse::<LitStr>()?;429 if out.rename.is_some() {430 return Err(Error::new(431 name.span(),432 "rename attribute may only be specified once",433 ));434 }435 out.rename = Some(name.value());436 } else if lookahead.peek(kw::alias) {437 input.parse::<kw::alias>()?;438 input.parse::<Token![=]>()?;439 let alias = input.parse::<LitStr>()?;440 out.aliases.push(alias.value());441 } else if lookahead.peek(kw::flatten) {442 input.parse::<kw::flatten>()?;443 out.flatten = true;444 if input.peek(token::Paren) {445 let content;446 parenthesized!(content in input);447 let lookahead = content.lookahead1();448 if lookahead.peek(kw::ok) {449 content.parse::<kw::ok>()?;450 out.flatten_ok = true;451 } else {452 return Err(lookahead.error());453 }454 }455 } else if lookahead.peek(kw::add) {456 input.parse::<kw::add>()?;457 out.add = true;458 } else if lookahead.peek(kw::hide) {459 input.parse::<kw::hide>()?;460 out.hide = true;461 } else if input.is_empty() {462 break;463 } else {464 return Err(lookahead.error());465 }466 if input.peek(Token![,]) {467 input.parse::<Token![,]>()?;468 } else {469 break;470 }471 }472 Ok(out)473 }474}475476struct TypedField {477 attr: TypedAttr,478 ident: Ident,479 ty: Type,480 is_option: bool,481 is_lazy: bool,482}483impl TypedField {484 fn parse(field: &syn::Field) -> Result<Self> {485 let attr = parse_attr::<TypedAttr, _>(&field.attrs, "typed")?.unwrap_or_default();486 let Some(ident) = field.ident.clone() else {487 return Err(Error::new(488 field.span(),489 "this field should appear in output object, but it has no visible name",490 ));491 };492 let (is_option, ty) = extract_type_from_option(&field.ty)?493 .map_or_else(|| (false, field.ty.clone()), |ty| (true, ty.clone()));494 if is_option && attr.flatten {495 if !attr.flatten_ok {496 return Err(Error::new(497 field.span(),498 "strategy should be set when flattening Option",499 ));500 }501 } else if attr.flatten_ok {502 return Err(Error::new(503 field.span(),504 "flatten(ok) is only useable on optional fields",505 ));506 }507508 let is_lazy = type_is_path(&ty, "Thunk").is_some();509510 Ok(Self {511 attr,512 ident,513 ty,514 is_option,515 is_lazy,516 })517 }518 /// None if this field is flattened in jsonnet output519 fn name(&self) -> Option<String> {520 if self.attr.flatten {521 return None;522 }523 Some(524 self.attr525 .rename526 .clone()527 .unwrap_or_else(|| self.ident.to_string()),528 )529 }530531 fn expand_field(&self) -> Option<TokenStream> {532 if self.is_option {533 return None;534 }535 let name = self.name()?;536 let ty = &self.ty;537 Some(quote! {538 (#name, <#ty as Typed>::TYPE)539 })540 }541542 fn expand_parse(&self) -> TokenStream {543 if self.is_option {544 self.expand_parse_optional()545 } else {546 self.expand_parse_mandatory()547 }548 }549550 fn expand_parse_optional(&self) -> TokenStream {551 let ident = &self.ident;552 let ty = &self.ty;553554 // optional flatten is handled in same way as serde555 if self.attr.flatten {556 return quote! {557 #ident: <#ty as TypedObj>::parse(&obj).ok(),558 };559 }560561 let name = self.name().unwrap();562 let aliases = &self.attr.aliases;563564 quote! {565 #ident: {566 let __value = if let Some(__v) = obj.get(#name.into())? {567 Some(__v)568 } #(else if let Some(__v) = obj.get(#aliases.into())? {569 Some(__v)570 })* else {571 None572 };573574 __value.map(<#ty as Typed>::from_untyped).transpose()?575 },576 }577 }578579 fn expand_parse_mandatory(&self) -> TokenStream {580 let ident = &self.ident;581 let ty = &self.ty;582583 // optional flatten is handled in same way as serde584 if self.attr.flatten {585 return quote! {586 #ident: <#ty as TypedObj>::parse(&obj)?,587 };588 }589590 let name = self.name().unwrap();591 let aliases = &self.attr.aliases;592593 let error_text = if aliases.is_empty() {594 // clippy does not understand name variable usage in quote! macro595 #[allow(clippy::redundant_clone)]596 name.clone()597 } else {598 format!("{name} (alias {})", aliases.join(", "))599 };600601 quote! {602 #ident: {603 let __value = if let Some(__v) = obj.get(#name.into())? {604 __v605 } #(else if let Some(__v) = obj.get(#aliases.into())? {606 __v607 })* else {608 return Err(ErrorKind::NoSuchField(#error_text.into(), vec![]).into());609 };610611 <#ty as Typed>::from_untyped(__value)?612 },613 }614 }615616 fn expand_serialize(&self) -> TokenStream {617 let ident = &self.ident;618 let ty = &self.ty;619 self.name().map_or_else(620 || {621 if self.is_option {622 quote! {623 if let Some(value) = self.#ident {624 <#ty as TypedObj>::serialize(value, out)?;625 }626 }627 } else {628 quote! {629 <#ty as TypedObj>::serialize(self.#ident, out)?;630 }631 }632 },633 |name| {634 let hide = if self.attr.hide {635 quote! {.hide()}636 } else {637 quote! {}638 };639 let add = if self.attr.add {640 quote! {.add()}641 } else {642 quote! {}643 };644 let value = if self.is_lazy {645 quote! {646 out.field(#name)647 #hide648 #add649 .try_thunk(<#ty as Typed>::into_lazy_untyped(value))?;650 }651 } else {652 quote! {653 out.field(#name)654 #hide655 #add656 .try_value(<#ty as Typed>::into_untyped(value)?)?;657 }658 };659 if self.is_option {660 quote! {661 if let Some(value) = self.#ident {662 #value663 }664 }665 } else {666 quote! {667 {668 let value = self.#ident;669 #value670 }671 }672 }673 },674 )675 }676}677678#[proc_macro_derive(Typed, attributes(typed))]679pub fn derive_typed(item: proc_macro::TokenStream) -> proc_macro::TokenStream {680 let input = parse_macro_input!(item as DeriveInput);681682 match derive_typed_inner(input) {683 Ok(v) => v.into(),684 Err(e) => e.to_compile_error().into(),685 }686}687688fn derive_typed_inner(input: DeriveInput) -> Result<TokenStream> {689 let syn::Data::Struct(data) = &input.data else {690 return Err(Error::new(input.span(), "only structs supported"));691 };692693 let ident = &input.ident;694 let fields = data695 .fields696 .iter()697 .map(TypedField::parse)698 .collect::<Result<Vec<_>>>()?;699700 let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();701702 let typed = {703 let fields = fields704 .iter()705 .filter_map(TypedField::expand_field)706 .collect::<Vec<_>>();707 quote! {708 impl #impl_generics Typed for #ident #ty_generics #where_clause {709 const TYPE: &'static ComplexValType = &ComplexValType::ObjectRef(&[710 #(#fields,)*711 ]);712713 fn from_untyped(value: Val) -> JrResult<Self> {714 let obj = value.as_obj().expect("shape is correct");715 Self::parse(&obj)716 }717718 fn into_untyped(value: Self) -> JrResult<Val> {719 let mut out = ObjValueBuilder::new();720 value.serialize(&mut out)?;721 Ok(Val::Obj(out.build()))722 }723724 }725 }726 };727728 let fields_parse = fields.iter().map(TypedField::expand_parse);729 let fields_serialize = fields730 .iter()731 .map(TypedField::expand_serialize)732 .collect::<Vec<_>>();733734 Ok(quote! {735 const _: () = {736 use ::jrsonnet_evaluator::{737 typed::{ComplexValType, Typed, TypedObj, CheckType},738 Val, State,739 error::{ErrorKind, Result as JrResult},740 ObjValueBuilder, ObjValue,741 };742743 #typed744745 impl #impl_generics TypedObj for #ident #ty_generics #where_clause {746 fn serialize(self, out: &mut ObjValueBuilder) -> JrResult<()> {747 #(#fields_serialize)*748749 Ok(())750 }751 fn parse(obj: &ObjValue) -> JrResult<Self> {752 Ok(Self {753 #(#fields_parse)*754 })755 }756 }757 };758 })759}760761struct FormatInput {762 formatting: LitStr,763 arguments: Vec<Expr>,764}765impl Parse for FormatInput {766 fn parse(input: ParseStream) -> Result<Self> {767 let formatting = input.parse()?;768 let mut arguments = Vec::new();769770 while input.peek(Token![,]) {771 input.parse::<Token![,]>()?;772 if input.is_empty() {773 // Trailing comma774 break;775 }776 let expr = input.parse()?;777 arguments.push(expr);778 }779780 if !input.is_empty() {781 return Err(syn::Error::new(input.span(), "unexpected trailing input"));782 }783784 Ok(Self {785 formatting,786 arguments,787 })788 }789}790fn is_format_str(i: &str) -> bool {791 let mut is_plain = true;792 // -1 = {793 // +1 = }794 let mut is_bracket = 0i8;795 for ele in i.chars() {796 match ele {797 '{' if is_bracket == -1 => {798 is_bracket = 0;799 }800 '}' if is_bracket == -1 => {801 is_plain = false;802 break;803 }804 '}' if is_bracket == 1 => {805 is_bracket = 0;806 }807 '{' if is_bracket == 1 => {808 is_plain = false;809 break;810 }811 '{' => {812 is_bracket = -1;813 }814 '}' => {815 is_bracket = 1;816 }817 _ if is_bracket != 0 => {818 is_plain = false;819 break;820 }821 _ => {}822 }823 }824 !is_plain || is_bracket != 0825}826impl FormatInput {827 fn expand(self) -> TokenStream {828 let format = self.formatting;829 if is_format_str(&format.value()) {830 let args = self.arguments;831 quote! {832 ::jrsonnet_evaluator::IStr::from(format!(#format #(, #args)*))833 }834 } else {835 if let Some(first) = self.arguments.first() {836 return syn::Error::new(837 first.span(),838 "string has no formatting codes, it should not have the arguments",839 )840 .into_compile_error();841 }842 quote! {843 ::jrsonnet_evaluator::IStr::from(#format)844 }845 }846 }847}848849/// `IStr` formatting helper850///851/// Using `format!("literal with no codes").into()` is slower than just `"literal with no codes".into()`852/// This macro looks for formatting codes in the input string, and uses853/// `format!()` only when necessary854#[proc_macro]855pub fn format_istr(input: proc_macro::TokenStream) -> proc_macro::TokenStream {856 let input = parse_macro_input!(input as FormatInput);857 input.expand().into()858}859860/// Create Thunk using closure syntax861#[proc_macro]862#[allow(non_snake_case)]863pub fn Thunk(input: proc_macro::TokenStream) -> proc_macro::TokenStream {864 let input = parse_macro_input!(input as ExprClosure);865866 let span = input.inputs.span();867 let move_check = input.capture.is_none().then(|| {868 quote_spanned! {span => {869 compile_error!("Thunk! needs to be called with move closure");870 }}871 });872873 let (env, closure, args) = syn_dissect_closure::split_env(input);874875 let trace_check = args.iter().map(|el| {876 let span = el.span();877 quote_spanned! {span => ::jrsonnet_evaluator::gc::assert_trace(&#el);}878 });879880 quote! {{881 #move_check882 #(#trace_check)*883 ::jrsonnet_evaluator::Thunk::new(::jrsonnet_evaluator::val::MemoizedClosureThunk::new(#env, #closure))884 }}.into()885}crates/jrsonnet-parser/src/expr.rsdiffbeforeafterboth--- a/crates/jrsonnet-parser/src/expr.rs
+++ b/crates/jrsonnet-parser/src/expr.rs
@@ -166,6 +166,10 @@
pub fn len(&self) -> usize {
self.exprs.len()
}
+ pub fn is_empty(&self) -> bool {
+ self.exprs.is_empty()
+ }
+
pub fn binds_len(&self) -> usize {
self.binds_len
}
crates/jrsonnet-stdlib/src/arrays.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/arrays.rs
+++ b/crates/jrsonnet-stdlib/src/arrays.rs
@@ -98,9 +98,9 @@
for c in str.chars() {
match func(Either2::A(c.to_string()))? {
Val::Str(o) => write!(out, "{o}").unwrap(),
- Val::Null => continue,
+ Val::Null => {},
_ => bail!("in std.join all items should be strings"),
- };
+ }
}
Ok(IndexableVal::Str(out.into()))
}
@@ -114,9 +114,9 @@
out.push(oe?);
}
}
- Val::Null => continue,
+ Val::Null => {},
_ => bail!("in std.join all items should be arrays"),
- };
+ }
}
Ok(IndexableVal::Arr(out.into()))
}
@@ -205,7 +205,6 @@
out.push(item?);
}
} else if matches!(item, Val::Null) {
- continue;
} else {
bail!("in std.join all items should be arrays");
}
@@ -226,7 +225,6 @@
first = false;
write!(out, "{item}").unwrap();
} else if matches!(item, Val::Null) {
- continue;
} else {
bail!("in std.join all items should be strings");
}
crates/jrsonnet-stdlib/src/manifest/xml.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/manifest/xml.rs
+++ b/crates/jrsonnet-stdlib/src/manifest/xml.rs
@@ -46,7 +46,7 @@
};
if arr.is_empty() {
bail!("JSONML value should have tag (array length should be >=1)");
- };
+ }
let tag = String::from_untyped(
arr.get(0)
.description("getting JSONML tag")?
crates/jrsonnet-stdlib/src/manifest/yaml.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/manifest/yaml.rs
+++ b/crates/jrsonnet-stdlib/src/manifest/yaml.rs
@@ -90,6 +90,7 @@
RESERVED.iter().any(|k| key.eq_ignore_ascii_case(k))
}
+ #[allow(clippy::if_same_then_else)]
// Check for unsafe characters
if !key
.chars()
@@ -98,7 +99,7 @@
return false;
}
// Check for reserved words
- if is_reserved(key) {
+ else if is_reserved(key) {
return false;
}
// Check for timestamp values. Since spaces and colons are already forbidden,
@@ -107,7 +108,7 @@
// - all characters match [0-9\-]
// - has exactly 2 dashes
// are considered dates.
- if key.chars().all(|v| matches!(v, '0'..='9' | '-')) && count_char(key, '-') == 2 {
+ else if key.chars().all(|v| matches!(v, '0'..='9' | '-')) && count_char(key, '-') == 2 {
return false;
}
// Check for integers. Keys that meet all of the following:
crates/jrsonnet-stdlib/src/misc.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/misc.rs
+++ b/crates/jrsonnet-stdlib/src/misc.rs
@@ -172,7 +172,7 @@
let Some(patch) = patch.as_obj() else {
return Ok(patch);
};
- let target = target.as_obj().unwrap_or_else(|| ObjValue::empty());
+ let target = target.as_obj().unwrap_or_else(ObjValue::empty);
let target_fields = target
.fields(
// FIXME: Makes no sense to preserve order for BTreeSet, it would be better to use IndexSet here?
crates/jrsonnet-stdlib/src/sets.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/sets.rs
+++ b/crates/jrsonnet-stdlib/src/sets.rs
@@ -21,7 +21,7 @@
let x = keyF(x)?;
while low < high {
- let middle = (high + low) / 2;
+ let middle = usize::midpoint(high, low);
let comp = keyF(arr.get_lazy(middle).expect("in bounds"))?;
match evaluate_compare_op(&comp, &x, BinaryOpType::Lt)? {
Ordering::Less => low = middle + 1,
@@ -66,7 +66,7 @@
bv = b.next();
bk = bv.map(keyF).transpose()?;
}
- };
+ }
}
Ok(ArrValue::lazy(out))
}
@@ -106,7 +106,7 @@
bv = b.next();
bk = bv.map(keyF).transpose()?;
}
- };
+ }
}
while let Some(_ac) = &ak {
// In a, but not in b
@@ -154,7 +154,7 @@
bv = b.next();
bk = bv.clone().map(keyF).transpose()?;
}
- };
+ }
}
// a.len() > b.len()
while let Some(_ac) = &ak {
crates/jrsonnet-stdlib/src/sort.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/sort.rs
+++ b/crates/jrsonnet-stdlib/src/sort.rs
@@ -66,7 +66,7 @@
return Err(err);
}
}
- };
+ }
Ok(values)
}
@@ -107,7 +107,7 @@
return Err(err);
}
}
- };
+ }
Ok(vk.into_iter().map(|v| v.0).collect())
}
@@ -204,7 +204,7 @@
}
}
-fn eval_keyf(val: Val, key_f: &Option<FuncVal>) -> Result<Val> {
+fn eval_keyf(val: Val, key_f: Option<&FuncVal>) -> Result<Val> {
if let Some(key_f) = key_f {
key_f.evaluate_simple(&(val,), false)
} else {
@@ -212,13 +212,13 @@
}
}
-fn array_top1(arr: ArrValue, key_f: Option<FuncVal>, ordering: Ordering) -> Result<Val> {
+fn array_top1(arr: ArrValue, key_f: Option<&FuncVal>, ordering: Ordering) -> Result<Val> {
let mut iter = arr.iter();
let mut min = iter.next().expect("not empty")?;
- let mut min_key = eval_keyf(min.clone(), &key_f)?;
+ let mut min_key = eval_keyf(min.clone(), key_f)?;
for item in iter {
let cur = item?;
- let cur_key = eval_keyf(cur.clone(), &key_f)?;
+ let cur_key = eval_keyf(cur.clone(), key_f)?;
if evaluate_compare_op(&cur_key, &min_key, BinaryOpType::Lt)? == ordering {
min = cur;
min_key = cur_key;
@@ -236,7 +236,7 @@
if arr.is_empty() {
return eval_on_empty(onEmpty);
}
- array_top1(arr, keyF, Ordering::Less)
+ array_top1(arr, keyF.as_ref(), Ordering::Less)
}
#[builtin]
pub fn builtin_max_array(
@@ -247,5 +247,5 @@
if arr.is_empty() {
return eval_on_empty(onEmpty);
}
- array_top1(arr, keyF, Ordering::Greater)
+ array_top1(arr, keyF.as_ref(), Ordering::Greater)
}
crates/jrsonnet-stdlib/src/strings.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/strings.rs
+++ b/crates/jrsonnet-stdlib/src/strings.rs
@@ -53,7 +53,7 @@
#[builtin]
pub fn builtin_equals_ignore_case(str1: String, str2: String) -> bool {
- str1.to_ascii_lowercase() == str2.to_ascii_lowercase()
+ str1.eq_ignore_ascii_case(&str2)
}
#[builtin]
crates/jrsonnet-types/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-types/src/lib.rs
+++ b/crates/jrsonnet-types/src/lib.rs
@@ -133,7 +133,7 @@
Self::Sum(v) => write_union(f, false, v.iter())?,
Self::SumRef(v) => write_union(f, false, v.iter().copied())?,
Self::Lazy(lazy) => write!(f, "Lazy<{lazy}>")?,
- };
+ }
Ok(())
}
}
tests/tests/common.rsdiffbeforeafterboth--- a/tests/tests/common.rs
+++ b/tests/tests/common.rs
@@ -57,12 +57,13 @@
#[builtin]
fn param_names(fun: FuncVal) -> Vec<String> {
fun.params()
- .into_iter()
+ .iter()
.map(|v| v.name().as_str().unwrap_or("<unnamed>").to_owned())
.collect()
}
#[derive(Trace)]
+#[allow(dead_code)]
pub struct ContextInitializer;
impl ContextInitializerT for ContextInitializer {
fn populate(&self, _for_file: Source, builder: &mut ContextBuilder) {
tests/tests/cpp_test_suite.rsdiffbeforeafterboth--- a/tests/tests/cpp_test_suite.rs
+++ b/tests/tests/cpp_test_suite.rs
@@ -23,29 +23,29 @@
// C++ test suite
std_context.add_ext_str("var1".into(), "test".into());
std_context
- .add_ext_code("var2".into(), "{x:1,y:2}")
+ .add_ext_code("var2", "{x:1,y:2}")
.expect("code is valid");
// Golang test suite
std_context
- .add_ext_code("codeVar".into(), "3+3")
+ .add_ext_code("codeVar", "3+3")
.expect("code is valid");
std_context.add_ext_str("stringVar".into(), "2 + 2".into());
std_context
.add_ext_code(
- "selfRecursiveVar".into(),
+ "selfRecursiveVar",
r#"[42, std.extVar("selfRecursiveVar")[0] + 1]"#,
)
.expect("code is valid");
std_context
.add_ext_code(
- "mutuallyRecursiveVar1".into(),
+ "mutuallyRecursiveVar1",
r#"[42, std.extVar("mutuallyRecursiveVar2")[0] + 1]"#,
)
.expect("code is valid");
std_context
.add_ext_code(
- "mutuallyRecursiveVar2".into(),
+ "mutuallyRecursiveVar2",
r#"[42, std.extVar("mutuallyRecursiveVar1")[0] + 1]"#,
)
.expect("code is valid");
@@ -203,9 +203,9 @@
let root = root_tests.join(root_dir);
let root_override = root_tests.join(format!("{root_dir}_golden_override"));
- for entry in fs::read_dir(&root).map_err(|e| io::Error::new(ErrorKind::Other, format!("failed to enumerate cpp_test_suite dir (Note: it needs to be cloned from C++ jsonnet repo for this test): {e}")))? {
+ for entry in fs::read_dir(&root).map_err(|e| io::Error::other(format!("failed to enumerate cpp_test_suite dir (Note: it needs to be cloned from C++ jsonnet repo for this test): {e}")))? {
let entry = entry?;
- if !entry.path().extension().map_or(false, |e| e == "jsonnet") {
+ if entry.path().extension().is_none_or(|e| e != "jsonnet") {
continue;
}
@@ -213,7 +213,7 @@
.path()
.file_name()
.and_then(|v| v.to_str())
- .map_or(false, |v| SKIPPED.contains(&v))
+ .is_some_and(|v| SKIPPED.contains(&v))
{
continue;
}
@@ -227,7 +227,7 @@
golden_path2.set_extension("golden");
let golden_override =
- root_override.join(&golden_path.file_name().expect("file has basename"));
+ root_override.join(golden_path.file_name().expect("file has basename"));
// .jsonnet.golden for C++ tests
let mut golden = read_file(&golden_path)?;
@@ -282,7 +282,7 @@
}
}
}
- };
+ }
}
}
tests/tests/golden.rsdiffbeforeafterboth--- a/tests/tests/golden.rs
+++ b/tests/tests/golden.rs
@@ -40,8 +40,8 @@
#[test]
fn golden() {
glob!("../", "golden/*.jsonnet", |path| {
- let result = run(&path);
+ let result = run(path);
- assert_snapshot!(result)
+ assert_snapshot!(result);
});
}
tests/tests/suite.rsdiffbeforeafterboth--- a/tests/tests/suite.rs
+++ b/tests/tests/suite.rs
@@ -32,7 +32,7 @@
file.display(),
trace_format.format(&e).unwrap()
),
- };
+ }
}
#[test]
@@ -42,11 +42,9 @@
for entry in fs::read_dir(&root)? {
let entry = entry?;
- if !entry.path().extension().map_or(false, |e| e == "jsonnet") {
- continue;
+ if entry.path().extension().is_some_and(|e| e == "jsonnet") {
+ run(&entry.path());
}
-
- run(&entry.path());
}
Ok(())