difftreelog
style fix clippy warnings
in: master
30 files changed
bindings/jrsonnet-web/src/lib.rsdiffbeforeafterboth--- a/bindings/jrsonnet-web/src/lib.rs
+++ b/bindings/jrsonnet-web/src/lib.rs
@@ -65,6 +65,11 @@
}
fn unwrap_val_ref(value: &JsValue) -> Result<<WasmVal as RefFromWasmAbi>::Anchor, JsValue> {
+ #[allow(
+ clippy::cast_sign_loss,
+ clippy::cast_possible_truncation,
+ reason = "defined to be u32"
+ )]
let ptr = get(value, &JsValue::from_str("__wbg_ptr"))
.ok()
.and_then(|v| v.as_f64())
@@ -371,14 +376,14 @@
impl WasmArrValue {
#[wasm_bindgen(getter)]
pub fn length(&self) -> u32 {
- self.arr.len()
+ self.arr.len32()
}
pub fn at(&self, index: u32) -> Result<Option<WasmVal>, JsValue> {
let result = self.state.as_ref().map_or_else(
- || self.arr.get(index),
+ || self.arr.get32(index),
|state| {
let _guard = state.try_enter();
- self.arr.get(index)
+ self.arr.get32(index)
},
);
result
bindings/jsonnet/src/lib.rsdiffbeforeafterboth--- a/bindings/jsonnet/src/lib.rs
+++ b/bindings/jsonnet/src/lib.rs
@@ -66,14 +66,12 @@
#[cfg(target_family = "unix")]
{
use std::os::unix::ffi::OsStrExt;
- let str = CString::new(input.as_os_str().as_bytes()).expect("input has zero byte in it");
- str
+ CString::new(input.as_os_str().as_bytes()).expect("input has zero byte in it")
}
#[cfg(not(target_family = "unix"))]
{
let str = input.as_os_str().to_str().expect("bad utf-8");
- let cstr = CString::new(str).expect("input has NUL inside");
- cstr
+ CString::new(str).expect("input has NUL inside")
}
}
cmds/jrb/src/main.rsdiffbeforeafterboth--- a/cmds/jrb/src/main.rs
+++ b/cmds/jrb/src/main.rs
@@ -104,6 +104,7 @@
}
}
+#[allow(clippy::too_many_lines)]
fn main() {
tracing_subscriber::fmt().init();
crates/jrsonnet-evaluator/src/analyze.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/analyze.rs
+++ b/crates/jrsonnet-evaluator/src/analyze.rs
@@ -28,7 +28,10 @@
use rustc_hash::FxHashMap;
use smallvec::SmallVec;
-use crate::error::{format_found, suggest_names};
+use crate::{
+ arr::arridx,
+ error::{format_found, suggest_names},
+};
#[derive(Debug, Clone, Copy)]
#[must_use]
@@ -658,7 +661,7 @@
stack: &'s mut AnalysisStack,
bomb: DropBomb,
}
-impl<'s> PendingBody<'s> {
+impl PendingBody<'_> {
/// After the body is processed, drop the frame's locals and emit any
/// "unused local" warnings.
fn finish(self) {
@@ -704,7 +707,7 @@
.drain(closures.first_in_frame.idx()..)
.collect();
for (i, def) in drained.iter().enumerate().rev() {
- let id = LocalId(closures.first_in_frame.0 + i as u32);
+ let id = LocalId(closures.first_in_frame.0 + arridx(i));
let stack_locals = stack
.local_by_name
.get_mut(&def.name)
@@ -819,7 +822,7 @@
let (this_refs, rest) = refs.split_at(*refs_len);
refs = rest;
let start = next_id;
- next_id += *dest_count as u32;
+ next_id += arridx(*dest_count);
Closure {
references: this_refs,
ids: start..next_id,
@@ -1043,7 +1046,7 @@
}
fn next_local_id(&self) -> LocalId {
- LocalId(self.local_defs.len() as u32)
+ LocalId(arridx(self.local_defs.len()))
}
fn report_error(&mut self, msg: impl Into<String>, span: Option<Span>) {
@@ -1565,7 +1568,7 @@
let mut pending = alloc.finish();
let mut l_binds: Vec<LBind> = Vec::with_capacity(binds.len());
- for (bind, destruct) in binds.iter().zip(destructs.into_iter()) {
+ for (bind, destruct) in binds.iter().zip(destructs) {
let mut value_taint = AnalysisResult::default();
let (value_shape, value) = pending
.stack
@@ -1608,7 +1611,7 @@
let mut pending = alloc.finish();
let mut l_params: Vec<LParam> = Vec::with_capacity(params.exprs.len());
- for (p, destruct) in params.exprs.iter().zip(param_destructs.into_iter()) {
+ for (p, destruct) in params.exprs.iter().zip(param_destructs) {
let mut value_taint = AnalysisResult::default();
let default = p.default.as_ref().map_or_else(
|| None,
crates/jrsonnet-evaluator/src/arr/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/arr/mod.rs
+++ b/crates/jrsonnet-evaluator/src/arr/mod.rs
@@ -2,6 +2,7 @@
any::Any,
fmt::{self},
num::NonZeroU32,
+ ops::{Bound, RangeBounds},
rc::Rc,
};
@@ -104,20 +105,37 @@
Self::new(RangeArray::new_inclusive(a, b))
}
+ #[inline]
#[must_use]
- pub fn slice(self, index: Option<i32>, end: Option<i32>, step: Option<NonZeroU32>) -> Self {
+ pub fn slice(self, range: impl RangeBounds<usize>) -> Self {
+ fn map_bound(start: bool, bound: Bound<&usize>) -> Option<i32> {
+ match bound {
+ Bound::Included(&v) => Some(i32::try_from(v).unwrap_or(i32::MAX)),
+ Bound::Excluded(&v) => Some(
+ i32::try_from(v)
+ .unwrap_or(i32::MAX)
+ .saturating_add(if start { 1 } else { -1 }),
+ ),
+ Bound::Unbounded => None,
+ }
+ }
+ self.slice32(
+ map_bound(true, range.start_bound()),
+ map_bound(false, range.end_bound()),
+ None,
+ )
+ }
+
+ #[must_use]
+ pub fn slice32(self, index: Option<i32>, end: Option<i32>, step: Option<NonZeroU32>) -> Self {
let get_idx = |pos: Option<i32>, len: u32, default| match pos {
- #[expect(
- clippy::cast_sign_loss,
- reason = "abs value is used, len is limited to u31"
- )]
Some(v) if v < 0 => len.saturating_add_signed(v),
#[expect(clippy::cast_sign_loss, reason = "abs value is used")]
Some(v) => (v as u32).min(len),
None => default,
};
- let index = get_idx(index, self.len(), 0);
- let end = get_idx(end, self.len(), self.len());
+ let index = get_idx(index, self.len32(), 0);
+ let end = get_idx(end, self.len32(), self.len32());
let step = step.unwrap_or_else(|| NonZeroU32::new(1).expect("1 != 0"));
if index >= end {
@@ -126,24 +144,29 @@
Self::new(SliceArray {
inner: self,
- #[expect(clippy::cast_possible_truncation, reason = "len is limited to u31")]
- from: index as u32,
- #[expect(clippy::cast_possible_truncation, reason = "len is limited to u31")]
- to: end as u32,
+ from: index,
+ to: end,
step: step.get(),
})
}
/// Array length.
- pub fn len(&self) -> u32 {
- self.0.len()
+ #[inline]
+ pub fn len32(&self) -> u32 {
+ self.0.len32()
}
+ pub fn len(&self) -> usize {
+ self.len32() as usize
+ }
+
/// Is array contains no elements?
+ #[inline]
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
+ #[inline]
pub fn is_cheap(&self) -> bool {
self.0.is_cheap()
}
@@ -151,24 +174,37 @@
/// Get array element by index, evaluating it, if it is lazy.
///
/// Returns `None` on out-of-bounds condition.
- pub fn get(&self, index: u32) -> Result<Option<Val>> {
- self.0.get(index)
+ #[inline]
+ pub fn get32(&self, index: u32) -> Result<Option<Val>> {
+ self.0.get32(index)
+ }
+
+ pub fn get(&self, index: usize) -> Result<Option<Val>> {
+ let Ok(i) = u32::try_from(index) else {
+ return Ok(None);
+ };
+ self.get32(i)
}
/// Get array element by index, without evaluation.
///
/// Returns `None` on out-of-bounds condition.
- pub fn get_lazy(&self, index: u32) -> Option<Thunk<Val>> {
- self.0.get_lazy(index)
+ #[inline]
+ pub fn get_lazy32(&self, index: u32) -> Option<Thunk<Val>> {
+ self.0.get_lazy32(index)
+ }
+
+ pub fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {
+ u32::try_from(index).ok().and_then(|i| self.get_lazy32(i))
}
pub fn iter(&self) -> impl ArrayLikeIter<Result<Val>> + '_ {
- (0..self.len()).map(|i| self.get(i).transpose().expect("length checked"))
+ (0..self.len32()).map(|i| self.get32(i).transpose().expect("length checked"))
}
/// Iterate over elements, returning lazy values.
pub fn iter_lazy(&self) -> impl ArrayLikeIter<Thunk<Val>> + '_ {
- (0..self.len()).map(|i| self.get_lazy(i).expect("length checked"))
+ (0..self.len32()).map(|i| self.get_lazy32(i).expect("length checked"))
}
/// Return a reversed view on current array.
@@ -201,3 +237,18 @@
Self::new(iter.into_iter().collect::<Vec<_>>())
}
}
+
+/// Checks that the usize does not exceed 4g with debug assertions enabled
+/// Should only be used on values that can't reasonably exceed this value
+#[inline]
+pub(crate) fn arridx(i: usize) -> u32 {
+ #[allow(
+ clippy::cast_possible_truncation,
+ reason = "array indexes never exceed 4g"
+ )]
+ if cfg!(debug_assertions) {
+ u32::try_from(i).expect("4g hard limit")
+ } else {
+ i as u32
+ }
+}
crates/jrsonnet-evaluator/src/arr/spec.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/arr/spec.rs
+++ b/crates/jrsonnet-evaluator/src/arr/spec.rs
@@ -9,7 +9,7 @@
use jrsonnet_gcmodule::{Cc, Trace};
use jrsonnet_interner::{IBytes, IStr};
-use super::ArrValue;
+use super::{ArrValue, arridx};
use crate::{
Context, Error, ObjValue, Result, Thunk, Val,
analyze::{ClosureShape, LExpr},
@@ -21,12 +21,12 @@
};
pub trait ArrayLike: Any + Trace + Debug {
- fn len(&self) -> u32;
+ fn len32(&self) -> u32;
fn is_empty(&self) -> bool {
- self.len() == 0
+ self.len32() == 0
}
- fn get(&self, index: u32) -> Result<Option<Val>>;
- fn get_lazy(&self, index: u32) -> Option<Thunk<Val>>;
+ fn get32(&self, index: u32) -> Result<Option<Val>>;
+ fn get_lazy32(&self, index: u32) -> Option<Thunk<Val>>;
fn is_cheap(&self) -> bool {
false
@@ -40,15 +40,15 @@
where
T: Any + Trace + Debug + ArrayCheap,
{
- fn len(&self) -> u32 {
+ fn len32(&self) -> u32 {
<T as ArrayCheap>::len(self)
}
- fn get(&self, index: u32) -> Result<Option<Val>> {
+ fn get32(&self, index: u32) -> Result<Option<Val>> {
Ok(<T as ArrayCheap>::get(self, index))
}
- fn get_lazy(&self, index: u32) -> Option<Thunk<Val>> {
+ fn get_lazy32(&self, index: u32) -> Option<Thunk<Val>> {
<T as ArrayCheap>::get(self, index).map(Thunk::evaluated)
}
@@ -80,16 +80,16 @@
}
}
impl ArrayLike for SliceArray {
- fn len(&self) -> u32 {
+ fn len32(&self) -> u32 {
(self.to - self.from).div_ceil(self.step)
}
- fn get(&self, index: u32) -> Result<Option<Val>> {
- self.inner.get(self.map_idx(index))
+ fn get32(&self, index: u32) -> Result<Option<Val>> {
+ self.inner.get32(self.map_idx(index))
}
- fn get_lazy(&self, index: u32) -> Option<Thunk<Val>> {
- self.inner.get_lazy(self.map_idx(index))
+ fn get_lazy32(&self, index: u32) -> Option<Thunk<Val>> {
+ self.inner.get_lazy32(self.map_idx(index))
}
fn is_cheap(&self) -> bool {
@@ -99,7 +99,7 @@
impl ArrayCheap for IBytes {
fn len(&self) -> u32 {
- self.as_slice().len() as u32
+ arridx(self.as_slice().len())
}
fn get(&self, index: u32) -> Option<Val> {
self.as_slice()
@@ -132,11 +132,11 @@
}
}
impl ArrayLike for ExprArray {
- fn len(&self) -> u32 {
- self.cached.borrow().len() as u32
+ fn len32(&self) -> u32 {
+ arridx(self.cached.borrow().len())
}
- fn get(&self, index: u32) -> Result<Option<Val>> {
- if index >= self.len() {
+ fn get32(&self, index: u32) -> Result<Option<Val>> {
+ if index >= self.len32() {
return Ok(None);
}
match &self.cached.borrow()[index as usize] {
@@ -157,7 +157,7 @@
self.cached.borrow_mut()[index as usize] = ArrayThunk::Computed(new_value.clone());
Ok(Some(new_value))
}
- fn get_lazy(&self, index: u32) -> Option<Thunk<Val>> {
+ fn get_lazy32(&self, index: u32) -> Option<Thunk<Val>> {
#[derive(Trace)]
struct ExprArrThunk {
expr: ExprArray,
@@ -168,13 +168,13 @@
fn get(&self) -> Result<Self::Output> {
self.expr
- .get(self.index)
+ .get32(self.index)
.transpose()
.expect("index checked")
}
}
- if index >= self.len() {
+ if index >= self.len32() {
return None;
}
match &self.cached.borrow()[index as usize] {
@@ -202,8 +202,8 @@
}
impl ExtendedArray {
pub fn new(a: ArrValue, b: ArrValue) -> Option<Self> {
- let a_len = a.len();
- let b_len = b.len();
+ let a_len = a.len32();
+ let b_len = b.len32();
let len = a_len.checked_add(b_len)?;
Some(Self {
a,
@@ -251,22 +251,22 @@
}
}
impl ArrayLike for ExtendedArray {
- fn get(&self, index: u32) -> Result<Option<Val>> {
+ fn get32(&self, index: u32) -> Result<Option<Val>> {
if self.split > index {
- self.a.get(index)
+ self.a.get32(index)
} else {
- self.b.get(index - self.split)
+ self.b.get32(index - self.split)
}
}
- fn get_lazy(&self, index: u32) -> Option<Thunk<Val>> {
+ fn get_lazy32(&self, index: u32) -> Option<Thunk<Val>> {
if self.split > index {
- self.a.get_lazy(index)
+ self.a.get_lazy32(index)
} else {
- self.b.get_lazy(index - self.split)
+ self.b.get_lazy32(index - self.split)
}
}
- fn len(&self) -> u32 {
+ fn len32(&self) -> u32 {
self.len
}
@@ -280,18 +280,18 @@
T: IntoUntyped + Trace + fmt::Debug,
for<'a> &'a T: IntoUntyped,
{
- fn len(&self) -> u32 {
+ fn len32(&self) -> u32 {
self.as_slice().len().try_into().unwrap_or(u32::MAX)
}
- fn get(&self, index: u32) -> Result<Option<Val>> {
+ fn get32(&self, index: u32) -> Result<Option<Val>> {
let Some(elem) = self.as_slice().get(index as usize) else {
return Ok(None);
};
IntoUntyped::into_untyped(elem).map(Some)
}
- fn get_lazy(&self, index: u32) -> Option<Thunk<Val>> {
+ fn get_lazy32(&self, index: u32) -> Option<Thunk<Val>> {
let elem = self.as_slice().get(index as usize)?;
Some(IntoUntyped::into_lazy_untyped(elem))
}
@@ -343,16 +343,16 @@
#[derive(Debug, Trace)]
pub struct ReverseArray(pub ArrValue);
impl ArrayLike for ReverseArray {
- fn len(&self) -> u32 {
- self.0.len()
+ fn len32(&self) -> u32 {
+ self.0.len32()
}
- fn get(&self, index: u32) -> Result<Option<Val>> {
- self.0.get(self.0.len() - index - 1)
+ fn get32(&self, index: u32) -> Result<Option<Val>> {
+ self.0.get32(self.0.len32() - index - 1)
}
- fn get_lazy(&self, index: u32) -> Option<Thunk<Val>> {
- self.0.get_lazy(self.0.len() - index - 1)
+ fn get_lazy32(&self, index: u32) -> Option<Thunk<Val>> {
+ self.0.get_lazy32(self.0.len32() - index - 1)
}
fn is_cheap(&self) -> bool {
@@ -374,7 +374,7 @@
}
impl MappedArray {
pub fn new(inner: ArrValue, mapper: ArrayMapper) -> Self {
- let len = inner.len();
+ let len = inner.len32();
Self {
inner,
cached: Cc::new(RefCell::new(vec![ArrayThunk::Waiting; len as usize])),
@@ -389,12 +389,12 @@
}
}
impl ArrayLike for MappedArray {
- fn len(&self) -> u32 {
- self.cached.borrow().len() as u32
+ fn len32(&self) -> u32 {
+ arridx(self.cached.borrow().len())
}
- fn get(&self, index: u32) -> Result<Option<Val>> {
- if index >= self.len() {
+ fn get32(&self, index: u32) -> Result<Option<Val>> {
+ if index >= self.len32() {
return Ok(None);
}
match &self.cached.borrow()[index as usize] {
@@ -413,7 +413,7 @@
let val = self
.inner
- .get(index)
+ .get32(index)
.transpose()
.expect("index checked")
.and_then(|r| self.evaluate(index, r));
@@ -428,7 +428,7 @@
self.cached.borrow_mut()[index as usize] = ArrayThunk::Computed(new_value.clone());
Ok(Some(new_value))
}
- fn get_lazy(&self, index: u32) -> Option<Thunk<Val>> {
+ fn get_lazy32(&self, index: u32) -> Option<Thunk<Val>> {
#[derive(Trace)]
struct MappedArrayThunk {
arr: MappedArray,
@@ -438,11 +438,14 @@
type Output = Val;
fn get(&self) -> Result<Self::Output> {
- self.arr.get(self.index).transpose().expect("index checked")
+ self.arr
+ .get32(self.index)
+ .transpose()
+ .expect("index checked")
}
}
- if index >= self.len() {
+ if index >= self.len32() {
return None;
}
match &self.cached.borrow()[index as usize] {
@@ -471,12 +474,12 @@
}
}
impl ArrayLike for MakeArray {
- fn len(&self) -> u32 {
- self.cached.borrow().len() as u32
+ fn len32(&self) -> u32 {
+ arridx(self.cached.borrow().len())
}
- fn get(&self, index: u32) -> Result<Option<Val>> {
- if index >= self.len() {
+ fn get32(&self, index: u32) -> Result<Option<Val>> {
+ if index >= self.len32() {
return Ok(None);
}
match &self.cached.borrow()[index as usize] {
@@ -493,7 +496,7 @@
unreachable!()
};
- let val = self.mapper.call(index as u32);
+ let val = self.mapper.call(index);
let new_value = match val {
Ok(v) => v,
@@ -505,7 +508,7 @@
self.cached.borrow_mut()[index as usize] = ArrayThunk::Computed(new_value.clone());
Ok(Some(new_value))
}
- fn get_lazy(&self, index: u32) -> Option<Thunk<Val>> {
+ fn get_lazy32(&self, index: u32) -> Option<Thunk<Val>> {
#[derive(Trace)]
struct MakeArrayThunk {
arr: MakeArray,
@@ -515,11 +518,14 @@
type Output = Val;
fn get(&self) -> Result<Self::Output> {
- self.arr.get(self.index).transpose().expect("index checked")
+ self.arr
+ .get32(self.index)
+ .transpose()
+ .expect("index checked")
}
}
- if index >= self.len() {
+ if index >= self.len32() {
return None;
}
match &self.cached.borrow()[index as usize] {
@@ -543,7 +549,7 @@
}
impl RepeatedArray {
pub fn new(data: ArrValue, repeats: u32) -> Option<Self> {
- let total_len = data.len().checked_mul(repeats)?;
+ let total_len = data.len32().checked_mul(repeats)?;
Some(Self {
data,
repeats,
@@ -554,25 +560,25 @@
if index > self.total_len {
return None;
}
- Some(index % self.data.len())
+ Some(index % self.data.len32())
}
}
impl ArrayLike for RepeatedArray {
- fn len(&self) -> u32 {
+ fn len32(&self) -> u32 {
self.total_len
}
- fn get(&self, index: u32) -> Result<Option<Val>> {
+ fn get32(&self, index: u32) -> Result<Option<Val>> {
let Some(idx) = self.map_idx(index) else {
return Ok(None);
};
- self.data.get(idx)
+ self.data.get32(idx)
}
- fn get_lazy(&self, index: u32) -> Option<Thunk<Val>> {
+ fn get_lazy32(&self, index: u32) -> Option<Thunk<Val>> {
let idx = self.map_idx(index)?;
- self.data.get_lazy(idx)
+ self.data.get_lazy32(idx)
}
fn is_cheap(&self) -> bool {
@@ -593,18 +599,18 @@
}
impl ArrayLike for PickObjectValues {
- fn len(&self) -> u32 {
- self.keys.len() as u32
+ fn len32(&self) -> u32 {
+ arridx(self.keys.len())
}
- fn get(&self, index: u32) -> Result<Option<Val>> {
+ fn get32(&self, index: u32) -> Result<Option<Val>> {
let Some(key) = self.keys.as_slice().get(index as usize) else {
return Ok(None);
};
Ok(Some(self.obj.get_or_bail(key.clone())?))
}
- fn get_lazy(&self, index: u32) -> Option<Thunk<Val>> {
+ fn get_lazy32(&self, index: u32) -> Option<Thunk<Val>> {
let key = self.keys.as_slice().get(index as usize)?;
Some(self.obj.get_lazy_or_bail(key.clone()))
}
@@ -633,11 +639,11 @@
}
impl ArrayLike for PickObjectKeyValues {
- fn len(&self) -> u32 {
- self.keys.len() as u32
+ fn len32(&self) -> u32 {
+ arridx(self.keys.len())
}
- fn get(&self, index: u32) -> Result<Option<Val>> {
+ fn get32(&self, index: u32) -> Result<Option<Val>> {
let Some(key) = self.keys.as_slice().get(index as usize) else {
return Ok(None);
};
@@ -650,7 +656,7 @@
))
}
- fn get_lazy(&self, index: u32) -> Option<Thunk<Val>> {
+ fn get_lazy32(&self, index: u32) -> Option<Thunk<Val>> {
let key = self.keys.as_slice().get(index as usize)?;
// Nothing can fail in the key part, yet value is still
// lazy-evaluated
crates/jrsonnet-evaluator/src/ctx.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/ctx.rs
+++ b/crates/jrsonnet-evaluator/src/ctx.rs
@@ -122,7 +122,7 @@
pub fn enter(self, sup_this: SupThis, build: impl FnOnce(&LocalsFrame, &Context)) -> Context {
let locals = LocalsFrame::new_once(self.n_locals);
let val = Context(Cc::new(ContextInternal {
- captures: self.captures.clone(),
+ captures: self.captures,
locals,
sup_this: Some(sup_this),
}));
crates/jrsonnet-evaluator/src/evaluate/compspec.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/evaluate/compspec.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/compspec.rs
@@ -97,7 +97,7 @@
let value_ctx = inner_ctx
.pack_captures_sup_this(self.frame_shape)
.enter(|fill, ctx| {
- fill_letrec_binds(fill, &ctx, self.locals);
+ fill_letrec_binds(fill, ctx, self.locals);
});
evaluate_field_member_static(self.builder, inner_ctx, value_ctx, self.field)
}
@@ -336,6 +336,7 @@
Ok(())
}
+#[allow(clippy::too_many_lines)]
fn evaluate_compspecs(
ctx: Context,
specs: &[LCompSpec],
@@ -381,7 +382,7 @@
for (i, item) in arr.iter().enumerate() {
let item = item?;
let inner_ctx = ctx.pack_captures_sup_this(frame_shape).enter(|fill, ctx| {
- destruct(dst, fill, Thunk::evaluated(item), &ctx);
+ destruct(dst, fill, Thunk::evaluated(item), ctx);
});
evaluate_compspecs(
inner_ctx,
crates/jrsonnet-evaluator/src/evaluate/destructure.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/evaluate/destructure.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/destructure.rs
@@ -5,7 +5,7 @@
use crate::{
Context, LocalsFrame, PackedContext, Result, SupThis, Thunk, Unbound, Val,
analyze::{
- ClosureShape, LBind, LDestruct, LDestructField, LDestructRest, LExpr, LLocalExpr, LocalSlot,
+ ClosureShape, LBind, LDestruct, LDestructField, LDestructRest, LLocalExpr, LocalSlot,
},
bail,
evaluate::evaluate,
@@ -19,7 +19,7 @@
fill: &LocalsFrame,
value: Thunk<Val>,
- a_ctx: &Context,
+ ctx: &Context,
) {
let min_len = start.len() + end.len();
let has_rest = rest.is_some();
@@ -29,14 +29,14 @@
bail!("expected array");
};
if !has_rest {
- if arr.len() as usize != min_len {
- bail!("expected {} elements, got {}", min_len, arr.len())
+ if arr.len() != min_len {
+ bail!("expected {} elements, got {}", min_len, arr.len32())
}
- } else if (arr.len() as usize) < min_len {
+ } else if arr.len() < min_len {
bail!(
"expected at least {} elements, but array was only {}",
min_len,
- arr.len()
+ arr.len32()
)
}
Ok(arr)
@@ -47,13 +47,13 @@
destruct(
d,
fill,
- Thunk!(move || Ok(full.evaluate()?.get(i as u32)?.expect("length is checked"))),
- a_ctx,
+ Thunk!(move || Ok(full.evaluate()?.get(i)?.expect("length is checked"))),
+ ctx,
);
}
- let start_len = start.len() as u32;
- let end_len = end.len() as u32;
+ let start_len = start.len();
+ let end_len = end.len();
if let Some(LDestructRest::Keep(slot)) = rest {
let full = full.clone();
@@ -62,11 +62,7 @@
Thunk!(move || {
let full = full.evaluate()?;
let to = full.len() - end_len;
- Ok(Val::Arr(full.slice(
- Some(start_len as i32),
- Some(to as i32),
- None,
- )))
+ Ok(Val::Arr(full.slice(start_len..to)))
}),
);
}
@@ -79,10 +75,10 @@
Thunk!(move || {
let full = full.evaluate()?;
Ok(full
- .get(full.len() - end_len + i as u32)?
+ .get(full.len() - end_len + i)?
.expect("length is checked"))
}),
- a_ctx,
+ ctx,
);
}
}
@@ -94,7 +90,7 @@
fill: &LocalsFrame,
value: Thunk<Val>,
- a_ctx: &Context,
+ ctx: &Context,
) {
use jrsonnet_interner::IStr;
use rustc_hash::FxHashSet;
@@ -118,7 +114,7 @@
}
}
if !has_rest {
- let len = obj.len();
+ let len = obj.len32();
if len as usize > field_names.len() {
bail!("too many fields, and rest not found");
}
@@ -142,10 +138,11 @@
for field in fields {
let field_name = field.name.clone();
- let default_thunk: Option<Thunk<Val>> = field
- .default
- .as_ref()
- .map(|(shape, expr)| build_b_thunk(a_ctx, shape, expr.clone()));
+ let default_thunk: Option<Thunk<Val>> = field.default.as_ref().map(|(shape, expr)| {
+ let expr = expr.clone();
+ let env = Context::enter_using(ctx, shape);
+ Thunk!(move || evaluate(env, &expr))
+ });
let field_full = full.clone();
let value_thunk = Thunk!(move || {
@@ -157,7 +154,7 @@
});
if let Some(into) = &field.into {
- destruct(into, fill, value_thunk, a_ctx);
+ destruct(into, fill, value_thunk, ctx);
} else {
unreachable!("analyzer lowers object-destruct shorthands into `into`");
}
@@ -177,21 +174,18 @@
#[cfg(feature = "exp-destruct")]
LDestruct::Object { fields, rest } => destruct_object(fields, rest.as_ref(), fill, value, a_ctx),
}
-}
-
-pub fn build_b_thunk(a_ctx: &Context, shape: &ClosureShape, expr: Rc<LExpr>) -> Thunk<Val> {
- let env = Context::enter_using(a_ctx, shape);
- Thunk!(move || evaluate(env, &expr))
-}
-pub fn build_b_thunk_uno(a_ctx: &Context, shape: Rc<(ClosureShape, LExpr)>) -> Thunk<Val> {
- let env = Context::enter_using(a_ctx, &shape.0);
- Thunk!(move || evaluate(env, &shape.1))
}
pub fn fill_letrec_binds(fill: &LocalsFrame, ctx: &Context, binds: &[LBind]) {
for bind in binds {
- let value_thunk = build_b_thunk(ctx, &bind.value_shape, bind.value.clone());
- destruct(&bind.destruct, fill, value_thunk, ctx);
+ let expr = bind.value.clone();
+ let env = Context::enter_using(ctx, &bind.value_shape);
+ destruct(
+ &bind.destruct,
+ fill,
+ Thunk!(move || evaluate(env, &expr)),
+ ctx,
+ );
}
}
crates/jrsonnet-evaluator/src/evaluate/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/evaluate/mod.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/mod.rs
@@ -7,7 +7,7 @@
use self::{
compspec::{evaluate_arr_comp, evaluate_obj_comp},
- destructure::{build_b_thunk_uno, evaluate_local_expr, evaluate_locals_unbound},
+ destructure::{evaluate_local_expr, evaluate_locals_unbound},
operator::evaluate_binary_op_special,
};
use crate::{
@@ -115,6 +115,7 @@
}
}
+#[allow(clippy::too_many_lines)]
pub fn evaluate(ctx: Context, expr: &LExpr) -> Result<Val> {
Ok(match expr {
LExpr::Null => Val::Null,
@@ -218,7 +219,7 @@
BoundedUsize::from_untyped(v).description("slice step value")
})
.transpose()?;
- Val::from(indexable.slice(start, end, step)?)
+ Val::from(indexable.slice32(start, end, step)?)
}
LExpr::Super => Val::Obj(ctx.try_sup_this()?.standalone_super().ok_or(NoSuperFound)?),
LExpr::Import {
@@ -320,6 +321,7 @@
)
}
+#[allow(clippy::too_many_lines)]
fn evaluate_index(ctx: Context, indexable: &LExpr, parts: &[LIndexPart]) -> Result<Val> {
let mut parts = parts.iter();
let mut indexable = if matches!(indexable, LExpr::Super) {
@@ -394,17 +396,17 @@
if n.fract() > f64::EPSILON {
bail!(FractionalIndex)
}
- let len = arr.len();
+ let len = arr.len32();
if n < 0.0 || n > f64::from(len) {
bail!(ArrayBoundsError(n, len));
}
#[expect(
clippy::cast_possible_truncation,
clippy::cast_sign_loss,
- reason = "n is checked positive"
+ reason = "n is checked range"
)]
let i = n as u32;
- arr.get(i)
+ arr.get32(i)
.with_description_src(loc, || format!("element <{i}> access"))?
.ok_or_else(|| ArrayBoundsError(n, len))?
}
@@ -507,12 +509,13 @@
return Ok(());
};
- let thunk = build_b_thunk_uno(&value_ctx, value.clone());
+ let env = Context::enter_using(&value_ctx, &value.0);
+ let value = value.clone();
builder
.field(name)
.with_add(*plus)
.with_visibility(*visibility)
- .try_thunk(thunk)?;
+ .try_thunk(Thunk!(move || evaluate(env, &value.1)))?;
Ok(())
}
crates/jrsonnet-evaluator/src/function/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/function/mod.rs
+++ b/crates/jrsonnet-evaluator/src/function/mod.rs
@@ -11,12 +11,10 @@
prepared::{PreparedCall, parse_prepared_builtin_call},
};
use crate::{
- PackedContextSupThis, Result, Thunk, Val,
+ Context, PackedContextSupThis, Result, Thunk, Val,
analyze::LFunction,
- evaluate::{
- destructure::{build_b_thunk, destruct},
- ensure_sufficient_stack, evaluate, evaluate_trivial,
- },
+ arr::arridx,
+ evaluate::{destructure::destruct, ensure_sufficient_stack, evaluate, evaluate_trivial},
function::builtin::BuiltinFunc,
};
@@ -83,7 +81,7 @@
&self.func.params[param_idx].destruct,
fill,
thunk.clone(),
- &ctx,
+ ctx,
);
}
for &(param_idx, arg_idx) in prepared.named() {
@@ -91,15 +89,22 @@
&self.func.params[param_idx].destruct,
fill,
named[arg_idx].clone(),
- &ctx,
+ ctx,
);
}
for ¶m_idx in prepared.defaults() {
let param = &self.func.params[param_idx];
let (shape, expr) = param.default.as_ref().expect("default exists");
- let thunk = build_b_thunk(&ctx, shape, expr.clone());
- destruct(¶m.destruct, fill, thunk, &ctx);
+ let expr = expr.clone();
+ let env = Context::enter_using(ctx, shape);
+
+ destruct(
+ ¶m.destruct,
+ fill,
+ Thunk!(move || evaluate(env, &expr)),
+ ctx,
+ );
}
});
@@ -152,8 +157,8 @@
}
}
/// Amount of non-default required arguments
- pub fn params_len(&self) -> u32 {
- self.params().iter().filter(|p| !p.has_default()).count() as u32
+ pub fn params_len32(&self) -> u32 {
+ arridx(self.params().iter().filter(|p| !p.has_default()).count())
}
/// Function name, as defined in code.
pub fn name(&self) -> IStr {
crates/jrsonnet-evaluator/src/integrations/serde.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/integrations/serde.rs
+++ b/crates/jrsonnet-evaluator/src/integrations/serde.rs
@@ -182,7 +182,7 @@
#[cfg(feature = "exp-bigint")]
Self::BigInt(b) => b.serialize(serializer),
Self::Arr(arr) => {
- let mut seq = serializer.serialize_seq(Some(arr.len() as usize))?;
+ let mut seq = serializer.serialize_seq(Some(arr.len()))?;
for (i, element) in arr.iter().enumerate() {
let mut serde_error = None;
in_description_frame(
@@ -203,7 +203,7 @@
seq.end()
}
Self::Obj(obj) => {
- let mut map = serializer.serialize_map(Some(obj.len() as usize))?;
+ let mut map = serializer.serialize_map(Some(obj.len32() as usize))?;
for (field, value) in obj.iter(
#[cfg(feature = "exp-preserve-order")]
true,
crates/jrsonnet-evaluator/src/obj/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/obj/mod.rs
+++ b/crates/jrsonnet-evaluator/src/obj/mod.rs
@@ -23,7 +23,7 @@
use crate::{
CcUnbound, MaybeUnbound, Result, Thunk, Unbound, Val,
- arr::{PickObjectKeyValues, PickObjectValues},
+ arr::{PickObjectKeyValues, PickObjectValues, arridx},
bail,
error::{ErrorKind::*, suggest_object_fields},
evaluate::operator::evaluate_add_op,
@@ -510,11 +510,14 @@
// }
/// Returns amount of visible object fields
/// If object only contains hidden fields - may return zero.
- pub fn len(&self) -> u32 {
+ pub fn len(&self) -> usize {
self.fields_visibility()
.values()
.filter(|d| d.visible())
- .count() as u32
+ .count()
+ }
+ pub fn len32(&self) -> u32 {
+ arridx(self.len())
}
/// For each field, calls callback.
/// If callback returns false - ends iteration prematurely.
@@ -625,7 +628,7 @@
Entry::Vacant(v) => {
v.insert(CacheValue::Pending);
}
- };
+ }
}
let result = self.get_idx_uncached(key, core);
{
crates/jrsonnet-evaluator/src/stack.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/stack.rs
+++ b/crates/jrsonnet-evaluator/src/stack.rs
@@ -11,7 +11,7 @@
struct NightlyLocalKey<T>(pub T);
#[cfg(nightly)]
impl<T> NightlyLocalKey<T> {
- #[inline(always)]
+ #[inline]
fn with<U>(&self, v: impl FnOnce(&T) -> U) -> U {
v(&self.0)
}
crates/jrsonnet-evaluator/src/trace/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/trace/mod.rs
+++ b/crates/jrsonnet-evaluator/src/trace/mod.rs
@@ -197,7 +197,7 @@
w = align
)?;
} else {
- write!(out, "{:<p$}{}", "", el.desc, p = self.padding,)?;
+ write!(out, "{:<p$}{}", "", el.desc, p = self.padding)?;
}
}
Ok(())
@@ -258,6 +258,7 @@
}
#[cfg(feature = "explaining-traces")]
impl TraceFormat for HiDocFormat {
+ #[allow(clippy::too_many_lines)]
fn write_trace(&self, out: &mut dyn fmt::Write, error: &Error) -> Result<(), fmt::Error> {
struct ResetData {
loc: Span,
crates/jrsonnet-evaluator/src/typed/conversions.rsdiffbeforeafterboth1use std::{any::TypeId, collections::BTreeMap, marker::PhantomData, mem::transmute, ops::Deref};23use jrsonnet_gcmodule::Trace;4use jrsonnet_interner::{IBytes, IStr};5use jrsonnet_ir::NumValue;6pub use jrsonnet_ir::{MAX_SAFE_INTEGER, MIN_SAFE_INTEGER};7use jrsonnet_types::{ComplexValType, ValType};89use crate::{10 ObjValue, ObjValueBuilder, Result, ResultExt, Thunk, Val,11 arr::ArrValue,12 bail,13 function::FuncVal,14 typed::CheckType,15 val::{IndexableVal, StrValue, ThunkMapper},16};1718#[doc(hidden)]19pub mod __typed_macro_prelude {20 pub use ::jrsonnet_evaluator::{21 IStr, ObjValue, ObjValueBuilder, State, Val,22 error::{ErrorKind, Result as JrResult},23 typed::{24 CheckType, ComplexValType, FromUntyped, IntoUntyped, ParseTypedObj, SerializeTypedObj,25 Typed,26 },27 };28}29pub use jrsonnet_macros::{FromUntyped, IntoUntyped, Typed};3031#[derive(Trace)]32struct ThunkFromUntyped<K: Trace>(PhantomData<fn() -> K>);33impl<K> ThunkMapper<Val> for ThunkFromUntyped<K>34where35 K: Typed + FromUntyped + Trace,36{37 type Output = K;3839 fn map(self, from: Val) -> Result<Self::Output> {40 K::from_untyped(from)41 }42}43impl<K: Trace> Default for ThunkFromUntyped<K> {44 fn default() -> Self {45 Self(PhantomData)46 }47}48#[derive(Trace)]49struct ThunkIntoUntyped<K: Trace>(PhantomData<fn() -> K>);50impl<K> ThunkMapper<K> for ThunkIntoUntyped<K>51where52 K: Typed + Trace + IntoUntyped,53{54 type Output = Val;5556 fn map(self, from: K) -> Result<Self::Output> {57 K::into_untyped(from)58 }59}60impl<K: Trace> Default for ThunkIntoUntyped<K> {61 fn default() -> Self {62 Self(PhantomData)63 }64}6566#[diagnostic::on_unimplemented(67 note = "don't implement `ParseTypedObj` directly, it is automatically provided by `FromUntyped` derive"68)]69pub trait ParseTypedObj: Typed {70 fn parse(obj: &ObjValue) -> Result<Self>;71}7273#[diagnostic::on_unimplemented(74 note = "don't implement `SerializeTypedObj` directly, it is automatically provided by `IntoUntyped` derive"75)]76pub trait SerializeTypedObj: Typed {77 fn serialize(self, out: &mut ObjValueBuilder) -> Result<()>;78 fn into_object(self) -> Result<ObjValue> {79 let mut builder = ObjValueBuilder::new();80 self.serialize(&mut builder)?;81 Ok(builder.build())82 }83}8485pub trait Typed: Sized {86 const TYPE: &'static ComplexValType;87}88impl<T> Typed for &T89where90 T: Typed,91{92 const TYPE: &'static ComplexValType = <&T as Typed>::TYPE;93}94pub trait IntoUntyped: Typed {95 // Whatever caller should use `into_lazy_untyped` instead of `into_untyped`96 fn provides_lazy() -> bool {97 false98 }99 fn into_untyped(typed: Self) -> Result<Val>;100 fn into_lazy_untyped(typed: Self) -> Thunk<Val> {101 Thunk::from(Self::into_untyped(typed))102 }103}104105pub trait IntoUntypedResult: Typed {106 /// Hack to make builtins be able to return non-result values, and make macros able to convert those values to result107 /// This method returns identity in impl Typed for Result, and should not be overriden108 #[doc(hidden)]109 fn into_untyped_result(typed: Self) -> Result<Val>;110}111impl<T> IntoUntypedResult for T112where113 T: IntoUntyped,114{115 fn into_untyped_result(typed: Self) -> Result<Val> {116 T::into_untyped(typed)117 }118}119120pub trait FromUntyped: Typed {121 fn from_untyped(untyped: Val) -> Result<Self>;122 fn from_lazy_untyped(lazy: Thunk<Val>) -> Result<Self> {123 Self::from_untyped(lazy.evaluate()?)124 }125126 // Whatever caller should use `from_lazy_untyped` instead of `from_untyped` when possible127 fn wants_lazy() -> bool {128 false129 }130}131132impl<T> Typed for Thunk<T>133where134 T: Typed + Trace + Clone,135{136 const TYPE: &'static ComplexValType = &ComplexValType::Lazy(T::TYPE);137}138139#[inline]140fn try_cast_thunk_val<T: 'static>(typed: Thunk<T>) -> Result<Thunk<Val>, Thunk<T>> {141 if TypeId::of::<T>() == TypeId::of::<Val>() {142 // SAFETY: We know that it is exactly the same type, and we discard the original after that143 // to avoid double-free.144 let transmuted = unsafe { transmute::<Thunk<T>, Thunk<Val>>(typed) };145 Ok(transmuted)146 } else {147 Err(typed)148 }149}150impl<T> IntoUntyped for Thunk<T>151where152 T: IntoUntyped + Trace + Clone,153{154 #[inline]155 fn into_untyped(typed: Self) -> Result<Val> {156 T::into_untyped(typed.evaluate()?)157 }158 fn provides_lazy() -> bool {159 true160 }161162 fn into_lazy_untyped(inner: Self) -> Thunk<Val> {163 // Avoid lazy mapping164 let inner = match try_cast_thunk_val(inner) {165 Ok(v) => return v,166 Err(e) => e,167 };168 inner.map(<ThunkIntoUntyped<T>>::default())169 }170}171impl<T> IntoUntyped for &Thunk<T>172where173 T: IntoUntyped + Trace + Clone,174{175 fn into_untyped(typed: Self) -> Result<Val> {176 T::into_untyped(typed.evaluate()?)177 }178 fn provides_lazy() -> bool {179 true180 }181182 fn into_lazy_untyped(inner: Self) -> Thunk<Val> {183 // Avoid lazy mapping184 let inner = match try_cast_thunk_val(inner.clone()) {185 Ok(v) => return v,186 Err(e) => e,187 };188 inner.map(<ThunkIntoUntyped<T>>::default())189 }190}191192#[inline]193fn try_cast_thunk_t<T: 'static>(typed: Thunk<Val>) -> Result<Thunk<T>, Thunk<Val>> {194 if TypeId::of::<T>() == TypeId::of::<Val>() {195 // SAFETY: We know that it is exactly the same type, and we discard the original after that196 // to avoid double-free.197 let transmuted = unsafe { transmute::<Thunk<Val>, Thunk<T>>(typed) };198 Ok(transmuted)199 } else {200 Err(typed)201 }202}203impl<T> FromUntyped for Thunk<T>204where205 T: Typed + FromUntyped + Trace + Clone,206{207 fn from_untyped(untyped: Val) -> Result<Self> {208 Self::from_lazy_untyped(Thunk::evaluated(untyped))209 }210211 fn wants_lazy() -> bool {212 true213 }214215 fn from_lazy_untyped(inner: Thunk<Val>) -> Result<Self> {216 // Avoid lazy mapping217 let inner = match try_cast_thunk_t(inner) {218 Ok(v) => return Ok(v),219 Err(e) => e,220 };221 Ok(inner.map(<ThunkFromUntyped<T>>::default()))222 }223}224225macro_rules! impl_int {226 ($($ty:ty)*) => {$(227 impl Typed for $ty {228 const TYPE: &'static ComplexValType =229 &ComplexValType::BoundedNumber(Some(Self::MIN as f64), Some(Self::MAX as f64));230 }231 impl FromUntyped for $ty {232 fn from_untyped(value: Val) -> Result<Self> {233 <Self as Typed>::TYPE.check(&value)?;234 match value {235 Val::Num(n) => {236 let n = n.get();237 #[allow(clippy::float_cmp)]238 if n.trunc() != n {239 bail!(240 "cannot convert number with fractional part to {}",241 stringify!($ty)242 )243 }244 #[allow(clippy::cast_sign_loss, clippy::cast_possible_truncation, reason = "checked by TYPE")]245 Ok(n as Self)246 }247 _ => unreachable!(),248 }249 }250 }251 impl IntoUntyped for &$ty {252 fn into_untyped(value: Self) -> Result<Val> {253 Ok(Val::Num((*value).into()))254 }255 }256 impl IntoUntyped for $ty {257 fn into_untyped(value: Self) -> Result<Val> {258 Ok(Val::Num(value.into()))259 }260 }261 )*};262}263264impl_int!(i8 u8 i16 u16 i32 u32);265266macro_rules! impl_bounded_int {267 ($($name:ident = $ty:ty)*) => {$(268 #[derive(Clone, Copy)]269 #[allow(clippy::cast_possible_truncation, reason = "overflow is api misuse")]270 pub struct $name<const MIN: $ty, const MAX: $ty>($ty);271 impl<const MIN: $ty, const MAX: $ty> $name<MIN, MAX> {272 pub const fn new(value: $ty) -> Option<$name<MIN, MAX>> {273 if value >= MIN && value <= MAX {274 Some(Self(value))275 } else {276 None277 }278 }279 pub const fn value(self) -> $ty {280 self.0281 }282 }283 impl<const MIN: $ty, const MAX: $ty> Deref for $name<MIN, MAX> {284 type Target = $ty;285 fn deref(&self) -> &Self::Target {286 &self.0287 }288 }289290 impl<const MIN: $ty, const MAX: $ty> Typed for $name<MIN, MAX> {291 #[allow(clippy::cast_possible_truncation, clippy::cast_precision_loss, reason = "overflow is api misuse")]292 const TYPE: &'static ComplexValType =293 &ComplexValType::BoundedNumber(294 Some(MIN as f64),295 Some(MAX as f64),296 );297 }298299 impl<const MIN: $ty, const MAX: $ty> FromUntyped for $name<MIN, MAX> {300 fn from_untyped(value: Val) -> Result<Self> {301 <Self as Typed>::TYPE.check(&value)?;302 match value {303 Val::Num(n) => {304 let n = n.get();305 #[allow(clippy::float_cmp)]306 if n.trunc() != n {307 bail!(308 "cannot convert number with fractional part to {}",309 stringify!($ty)310 )311 }312 #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss, reason = "overflow is api misuse, the range is checked by TYPE")]313 Ok(Self(n as $ty))314 }315 _ => unreachable!(),316 }317 }318 }319320 impl<const MIN: $ty, const MAX: $ty> IntoUntyped for $name<MIN, MAX> {321 #[allow(clippy::cast_lossless)]322 fn into_untyped(value: Self) -> Result<Val> {323 Ok(Val::try_num(value.0)?)324 }325 }326 )*};327}328329impl_bounded_int!(330 BoundedI8 = i8331 BoundedI16 = i16332 BoundedI32 = i32333 BoundedI64 = i64334 BoundedUsize = usize335);336337impl Typed for f64 {338 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Num);339}340impl IntoUntyped for &f64 {341 fn into_untyped(value: Self) -> Result<Val> {342 Ok(Val::try_num(*value)?)343 }344}345impl IntoUntyped for f64 {346 fn into_untyped(value: Self) -> Result<Val> {347 Ok(Val::try_num(value)?)348 }349}350impl FromUntyped for f64 {351 fn from_untyped(value: Val) -> Result<Self> {352 <Self as Typed>::TYPE.check(&value)?;353 match value {354 Val::Num(n) => Ok(n.get()),355 _ => unreachable!(),356 }357 }358}359360pub struct PositiveF64(pub f64);361impl Typed for PositiveF64 {362 const TYPE: &'static ComplexValType = &ComplexValType::BoundedNumber(Some(0.0), None);363}364impl IntoUntyped for &PositiveF64 {365 fn into_untyped(value: Self) -> Result<Val> {366 Ok(Val::try_num(value.0)?)367 }368}369impl FromUntyped for PositiveF64 {370 fn from_untyped(value: Val) -> Result<Self> {371 <Self as Typed>::TYPE.check(&value)?;372 match value {373 Val::Num(n) => Ok(Self(n.get())),374 _ => unreachable!(),375 }376 }377}378impl Typed for usize {379 const TYPE: &'static ComplexValType =380 &ComplexValType::BoundedNumber(Some(0.0), Some(MAX_SAFE_INTEGER));381}382impl IntoUntyped for usize {383 fn into_untyped(value: Self) -> Result<Val> {384 Ok(Val::try_num(value)?)385 }386}387impl FromUntyped for usize {388 fn from_untyped(value: Val) -> Result<Self> {389 <Self as Typed>::TYPE.check(&value)?;390 match value {391 Val::Num(n) => {392 let n = n.get();393 #[allow(clippy::float_cmp)]394 if n.trunc() != n {395 bail!("cannot convert number with fractional part to usize")396 }397 #[allow(398 clippy::cast_possible_truncation,399 clippy::cast_sign_loss,400 reason = "the range is checked by TYPE"401 )]402 Ok(n as Self)403 }404 _ => unreachable!(),405 }406 }407}408409impl Typed for IStr {410 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Str);411}412impl IntoUntyped for IStr {413 fn into_untyped(value: Self) -> Result<Val> {414 Ok(Val::string(value))415 }416}417impl FromUntyped for IStr {418 fn from_untyped(value: Val) -> Result<Self> {419 <Self as Typed>::TYPE.check(&value)?;420 match value {421 Val::Str(s) => Ok(s.into_flat()),422 _ => unreachable!(),423 }424 }425}426427impl Typed for String {428 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Str);429}430impl IntoUntyped for String {431 fn into_untyped(value: Self) -> Result<Val> {432 Ok(Val::string(value))433 }434}435impl FromUntyped for String {436 fn from_untyped(value: Val) -> Result<Self> {437 <Self as Typed>::TYPE.check(&value)?;438 match value {439 Val::Str(s) => Ok(s.to_string()),440 _ => unreachable!(),441 }442 }443}444445impl Typed for StrValue {446 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Str);447}448impl IntoUntyped for StrValue {449 fn into_untyped(value: Self) -> Result<Val> {450 Ok(Val::Str(value))451 }452}453impl FromUntyped for StrValue {454 fn from_untyped(value: Val) -> Result<Self> {455 <Self as Typed>::TYPE.check(&value)?;456 match value {457 Val::Str(s) => Ok(s),458 _ => unreachable!(),459 }460 }461}462463impl Typed for char {464 const TYPE: &'static ComplexValType = &ComplexValType::Char;465}466impl IntoUntyped for &char {467 fn into_untyped(value: Self) -> Result<Val> {468 Ok(Val::string(*value))469 }470}471impl IntoUntyped for char {472 fn into_untyped(value: Self) -> Result<Val> {473 Ok(Val::string(value))474 }475}476impl FromUntyped for char {477 fn from_untyped(value: Val) -> Result<Self> {478 <Self as Typed>::TYPE.check(&value)?;479 match value {480 Val::Str(s) => Ok(s.into_flat().chars().next().unwrap()),481 _ => unreachable!(),482 }483 }484}485486// TODO: View into vec using ArrayLike?487impl<T> Typed for Vec<T>488where489 T: Typed,490{491 const TYPE: &'static ComplexValType = &ComplexValType::ArrayRef(T::TYPE);492}493impl<T: Typed + IntoUntyped> IntoUntyped for Vec<T> {494 fn into_untyped(value: Self) -> Result<Val> {495 Ok(Val::Arr(496 value497 .into_iter()498 .map(T::into_untyped)499 .collect::<Result<ArrValue>>()?,500 ))501 }502}503impl<T: Typed + FromUntyped> FromUntyped for Vec<T> {504 fn from_untyped(value: Val) -> Result<Self> {505 let Val::Arr(a) = value else {506 <Self as Typed>::TYPE.check(&value)?;507 unreachable!("typecheck should fail")508 };509 a.iter()510 .enumerate()511 .map(|(i, r)| {512 r.and_then(|t| {513 T::from_untyped(t).with_description(|| format!("parsing elem <{i}>"))514 })515 })516 .collect::<Result<Self>>()517 }518}519520// TODO: View into BTreeMap using ObjectCore?521impl<K, V> Typed for BTreeMap<K, V>522where523 K: Typed + Ord,524 V: Typed,525{526 const TYPE: &'static ComplexValType = &ComplexValType::AttrsOf(V::TYPE);527}528impl<K, V> IntoUntyped for BTreeMap<K, V>529where530 K: Typed + Ord + IntoUntyped,531 V: Typed + IntoUntyped,532{533 fn into_untyped(typed: Self) -> Result<Val> {534 let mut out = ObjValueBuilder::with_capacity(typed.len());535 for (k, v) in typed {536 let Some(key) = K::into_untyped(k)?.as_str() else {537 bail!("map key should serialize to string");538 };539 let value = V::into_untyped(v)?;540 out.field(key).value(value);541 }542 Ok(Val::Obj(out.build()))543 }544}545impl<K, V> FromUntyped for BTreeMap<K, V>546where547 K: FromUntyped + Ord,548 V: FromUntyped,549{550 fn from_untyped(value: Val) -> Result<Self> {551 Self::TYPE.check(&value)?;552 let obj = value.as_obj().expect("typecheck should fail");553554 let mut out = Self::new();555 if V::wants_lazy() {556 for key in obj.fields_ex(557 false,558 #[cfg(feature = "exp-preserve-order")]559 false,560 ) {561 let value = obj.get_lazy(key.clone()).expect("field exists");562 let value = V::from_lazy_untyped(value)?;563 let key = K::from_untyped(Val::Str(key.into()))?;564 let _ = out.insert(key, value);565 }566 } else {567 for (key, value) in obj.iter(568 #[cfg(feature = "exp-preserve-order")]569 false,570 ) {571 let key = K::from_untyped(Val::Str(key.into()))?;572 let value = V::from_untyped(value?)?;573 let _ = out.insert(key, value);574 }575 }576 Ok(out)577 }578}579580impl Typed for Val {581 const TYPE: &'static ComplexValType = &ComplexValType::Any;582}583impl IntoUntyped for &Val {584 #[inline]585 fn into_untyped(typed: Self) -> Result<Val> {586 Ok(typed.clone())587 }588}589impl IntoUntyped for Val {590 #[inline]591 fn into_untyped(typed: Self) -> Result<Val> {592 Ok(typed)593 }594}595impl FromUntyped for Val {596 fn from_untyped(untyped: Val) -> Result<Self> {597 Ok(untyped)598 }599}600601#[doc(hidden)]602impl<T> Typed for Result<T>603where604 T: Typed,605{606 const TYPE: &'static ComplexValType = &ComplexValType::Any;607}608impl<T: IntoUntyped> IntoUntypedResult for Result<T> {609 fn into_untyped_result(typed: Self) -> Result<Val> {610 typed.map(T::into_untyped)?611 }612}613614/// Specialization615impl Typed for IBytes {616 const TYPE: &'static ComplexValType =617 &ComplexValType::ArrayRef(&ComplexValType::BoundedNumber(Some(0.0), Some(255.0)));618}619impl IntoUntyped for &IBytes {620 fn into_untyped(value: Self) -> Result<Val> {621 Ok(Val::arr(value.clone()))622 }623}624impl IntoUntyped for IBytes {625 fn into_untyped(value: Self) -> Result<Val> {626 Ok(Val::arr(value))627 }628}629impl FromUntyped for IBytes {630 fn from_untyped(value: Val) -> Result<Self> {631 let Val::Arr(a) = &value else {632 <Self as Typed>::TYPE.check(&value)?;633 unreachable!()634 };635 if let Some(bytes) = a.as_any().downcast_ref::<IBytes>() {636 return Ok(bytes.clone());637 }638 <Self as Typed>::TYPE.check(&value)?;639 // Any::downcast_ref::<ByteArray>(&a);640 let mut out = Vec::with_capacity(a.len());641 for e in a.iter() {642 let r = e?;643 out.push(u8::from_untyped(r)?);644 }645 Ok(out.as_slice().into())646 }647}648649pub struct M1;650impl Typed for M1 {651 const TYPE: &'static ComplexValType = &ComplexValType::BoundedNumber(Some(-1.0), Some(-1.0));652}653impl IntoUntyped for &M1 {654 fn into_untyped(_: Self) -> Result<Val> {655 Ok(Val::Num(NumValue::new(-1.0).expect("finite")))656 }657}658impl FromUntyped for M1 {659 fn from_untyped(value: Val) -> Result<Self> {660 <Self as Typed>::TYPE.check(&value)?;661 Ok(Self)662 }663}664665macro_rules! decl_either {666 ($($name: ident, $($id: ident)*);*) => {$(667 #[derive(Clone)]668 pub enum $name<$($id),*> {669 $($id($id)),*670 }671 impl<$($id),*> Typed for $name<$($id),*>672 where673 $($id: Typed,)*674 {675 const TYPE: &'static ComplexValType = &ComplexValType::UnionRef(&[$($id::TYPE),*]);676 }677 impl<$($id),*> IntoUntyped for $name<$($id),*>678 where679 $($id: Typed + IntoUntyped,)*680 {681 fn into_untyped(value: Self) -> Result<Val> {682 match value {$(683 $name::$id(v) => $id::into_untyped(v)684 ),*}685 }686 }687688 impl<$($id),*> FromUntyped for $name<$($id),*>689 where690 $($id: Typed + FromUntyped,)*691 {692 fn from_untyped(value: Val) -> Result<Self> {693 $(694 if $id::TYPE.check(&value).is_ok() {695 $id::from_untyped(value).map(Self::$id)696 } else697 )* {698 <Self as Typed>::TYPE.check(&value)?;699 unreachable!()700 }701 }702 }703 )*}704}705decl_either!(706 Either1, A;707 Either2, A B;708 Either3, A B C;709 Either4, A B C D;710 Either5, A B C D E;711 Either6, A B C D E F;712 Either7, A B C D E F G713);714#[macro_export]715macro_rules! Either {716 ($a:ty) => {$crate::typed::Either1<$a>};717 ($a:ty, $b:ty) => {$crate::typed::Either2<$a, $b>};718 ($a:ty, $b:ty, $c:ty) => {$crate::typed::Either3<$a, $b, $c>};719 ($a:ty, $b:ty, $c:ty, $d:ty) => {$crate::typed::Either4<$a, $b, $c, $d>};720 ($a:ty, $b:ty, $c:ty, $d:ty, $e:ty) => {$crate::typed::Either5<$a, $b, $c, $d, $e>};721 ($a:ty, $b:ty, $c:ty, $d:ty, $e:ty, $f:ty) => {$crate::typed::Either6<$a, $b, $c, $d, $e, $f>};722 ($a:ty, $b:ty, $c:ty, $d:ty, $e:ty, $f:ty, $g:ty) => {$crate::typed::Either7<$a, $b, $c, $d, $e, $f, $g>};723}724pub use Either;725726pub type MyType = Either![u32, f64, String];727728impl Typed for ArrValue {729 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Arr);730}731impl IntoUntyped for ArrValue {732 fn into_untyped(value: Self) -> Result<Val> {733 Ok(Val::Arr(value))734 }735}736impl FromUntyped for ArrValue {737 fn from_untyped(value: Val) -> Result<Self> {738 <Self as Typed>::TYPE.check(&value)?;739 match value {740 Val::Arr(a) => Ok(a),741 _ => unreachable!(),742 }743 }744}745746impl Typed for FuncVal {747 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Func);748}749impl IntoUntyped for FuncVal {750 fn into_untyped(value: Self) -> Result<Val> {751 Ok(Val::Func(value))752 }753}754impl FromUntyped for FuncVal {755 fn from_untyped(value: Val) -> Result<Self> {756 <Self as Typed>::TYPE.check(&value)?;757 match value {758 Val::Func(a) => Ok(a),759 _ => unreachable!(),760 }761 }762}763764impl Typed for ObjValue {765 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Obj);766}767impl IntoUntyped for ObjValue {768 fn into_untyped(value: Self) -> Result<Val> {769 Ok(Val::Obj(value))770 }771}772impl FromUntyped for ObjValue {773 fn from_untyped(value: Val) -> Result<Self> {774 <Self as Typed>::TYPE.check(&value)?;775 match value {776 Val::Obj(a) => Ok(a),777 _ => unreachable!(),778 }779 }780}781782impl Typed for bool {783 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Bool);784}785impl IntoUntyped for &bool {786 fn into_untyped(value: Self) -> Result<Val> {787 Ok(Val::Bool(*value))788 }789}790impl IntoUntyped for bool {791 fn into_untyped(value: Self) -> Result<Val> {792 Ok(Val::Bool(value))793 }794}795impl FromUntyped for bool {796 fn from_untyped(value: Val) -> Result<Self> {797 <Self as Typed>::TYPE.check(&value)?;798 match value {799 Val::Bool(a) => Ok(a),800 _ => unreachable!(),801 }802 }803}804805impl Typed for IndexableVal {806 const TYPE: &'static ComplexValType = &ComplexValType::UnionRef(&[807 &ComplexValType::Simple(ValType::Arr),808 &ComplexValType::Simple(ValType::Str),809 ]);810}811impl IntoUntyped for IndexableVal {812 fn into_untyped(value: Self) -> Result<Val> {813 match value {814 Self::Str(s) => Ok(Val::string(s)),815 Self::Arr(a) => Ok(Val::Arr(a)),816 }817 }818}819impl FromUntyped for IndexableVal {820 fn from_untyped(value: Val) -> Result<Self> {821 <Self as Typed>::TYPE.check(&value)?;822 value.into_indexable()823 }824}825826impl Typed for () {827 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Null);828}829impl IntoUntyped for &() {830 fn into_untyped((): Self) -> Result<Val> {831 Ok(Val::Null)832 }833}834impl IntoUntyped for () {835 fn into_untyped((): Self) -> Result<Val> {836 Ok(Val::Null)837 }838}839impl FromUntyped for () {840 fn from_untyped(value: Val) -> Result<Self> {841 <Self as Typed>::TYPE.check(&value)?;842 Ok(())843 }844}845846impl<T> Typed for Option<T>847where848 T: Typed,849{850 const TYPE: &'static ComplexValType =851 &ComplexValType::UnionRef(&[&ComplexValType::Simple(ValType::Null), T::TYPE]);852}853impl<T> IntoUntyped for Option<T>854where855 T: Typed + IntoUntyped,856{857 fn into_untyped(typed: Self) -> Result<Val> {858 typed.map_or_else(|| Ok(Val::Null), |v| T::into_untyped(v))859 }860}861impl<T> FromUntyped for Option<T>862where863 T: Typed + FromUntyped,864{865 fn from_untyped(untyped: Val) -> Result<Self> {866 if matches!(untyped, Val::Null) {867 Ok(None)868 } else {869 T::from_untyped(untyped).map(Some)870 }871 }872}873874impl Typed for NumValue {875 const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Num);876}877impl IntoUntyped for &NumValue {878 fn into_untyped(typed: Self) -> Result<Val> {879 Ok(Val::Num(*typed))880 }881}882impl FromUntyped for NumValue {883 fn from_untyped(untyped: Val) -> Result<Self> {884 Self::TYPE.check(&untyped)?;885 match untyped {886 Val::Num(v) => Ok(v),887 _ => unreachable!(),888 }889 }890}crates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/val.rs
+++ b/crates/jrsonnet-evaluator/src/val.rs
@@ -277,7 +277,7 @@
/// For strings, will create a copy of specified interval.
///
/// For arrays, nothing will be copied on this call, instead [`ArrValue::Slice`] view will be returned.
- pub fn slice(
+ pub fn slice32(
self,
index: Option<i32>,
end: Option<i32>,
@@ -321,7 +321,7 @@
.into(),
))
}
- Self::Arr(arr) => Ok(Self::Arr(arr.clone().slice(
+ Self::Arr(arr) => Ok(Self::Arr(arr.clone().slice32(
index,
end,
#[expect(
@@ -658,7 +658,7 @@
if ArrValue::ptr_eq(a, b) {
return Ok(true);
}
- if a.len() != b.len() {
+ if a.len32() != b.len32() {
return Ok(false);
}
for (a, b) in a.iter().zip(b.iter()) {
crates/jrsonnet-formatter/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-formatter/src/lib.rs
+++ b/crates/jrsonnet-formatter/src/lib.rs
@@ -477,8 +477,7 @@
&mut out,
);
- let mut compspecs = compspecs.into_iter().peekable();
- while let Some(mem) = compspecs.next() {
+ for mem in compspecs {
if mem.should_start_with_newline {
p!(out, nl);
}
crates/jrsonnet-peg-parser/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-peg-parser/src/lib.rs
+++ b/crates/jrsonnet-peg-parser/src/lib.rs
@@ -273,19 +273,15 @@
Expr::ArrComp(Box::new(expr), specs)
}
pub rule number_expr(s: &ParserSettings) -> Expr
- = n:number() {? if let Some(n) = NumValue::new(n) {
- Ok(Expr::Num(n))
- } else {
- Err("!!!numbers are finite")
- }}
+ = n:number() {? NumValue::new(n).map_or_else(|| Err("!!!numbers are finite"), |n| Ok(Expr::Num(n)))}
rule spanned<T: Acyclic>(x: rule<T>, s: &ParserSettings) -> Spanned<T>
- = a:position!() n:x() b:position!() { Spanned::new(n, Span(s.source.clone(), a as u32, b as u32)) }
+ = a:position!() n:x() b:position!() { Spanned::new(n, Span(s.source.clone(), codeidx(a), codeidx(b))) }
pub rule var_expr(s: &ParserSettings) -> Expr
= n:spanned(<id()>, s) { Expr::Var(n) }
pub rule id_loc(s: &ParserSettings) -> Spanned<Expr>
- = a:position!() n:id() b:position!() { Spanned::new(Expr::Str(n), Span(s.source.clone(), a as u32,b as u32)) }
+ = a:position!() n:id() b:position!() { Spanned::new(Expr::Str(n), Span(s.source.clone(), codeidx(a), codeidx(b))) }
pub rule if_then_else_expr(s: &ParserSettings) -> Expr
= cond:ifspec(s) _ keyword("then") _ cond_then:expr(s) cond_else:(_ keyword("else") _ e:expr(s) {e})? {Expr::IfElse(Box::new(IfElse{
cond,
@@ -421,6 +417,10 @@
}
}
+fn codeidx(i: usize) -> u32 {
+ u32::try_from(i).expect("code has 4g hard limit")
+}
+
pub type ParseError = peg::error::ParseError<peg::str::LineCol>;
pub fn parse(str: &str, settings: &ParserSettings) -> Result<Expr, ParseError> {
jsonnet_parser::jsonnet(str, settings)
@@ -428,7 +428,10 @@
/// Used for importstr values
pub fn string_to_expr(str: IStr, settings: &ParserSettings) -> Spanned<Expr> {
let len = str.len();
- Spanned::new(Expr::Str(str), Span(settings.source.clone(), 0, len as u32))
+ Spanned::new(
+ Expr::Str(str),
+ Span(settings.source.clone(), 0, codeidx(len)),
+ )
}
#[cfg(test)]
crates/jrsonnet-pkg/src/install/accessor.rsdiffbeforeafterboth--- a/crates/jrsonnet-pkg/src/install/accessor.rs
+++ b/crates/jrsonnet-pkg/src/install/accessor.rs
@@ -66,6 +66,10 @@
Ok(Some(out))
}
#[allow(clippy::significant_drop_tightening, reason = "false-positive")]
+ #[allow(
+ clippy::iter_not_returning_iterator,
+ reason = "idk for a better name, it is still inner iteration"
+ )]
pub fn iter<E>(
&self,
subdir: &SubDir,
crates/jrsonnet-rowan-parser/src/parser.rsdiffbeforeafterboth--- a/crates/jrsonnet-rowan-parser/src/parser.rs
+++ b/crates/jrsonnet-rowan-parser/src/parser.rs
@@ -226,12 +226,12 @@
self.nth_at(0, kind)
}
pub fn nth_at(&self, n: usize, kind: SyntaxKind) -> bool {
- if n == 0 {
- if let ExpectedSyntax::Unnamed(kinds) = self.expected_syntax_tracking_state.get() {
- let kinds = kinds.with(kind);
- self.expected_syntax_tracking_state
- .set(ExpectedSyntax::Unnamed(kinds));
- }
+ if n == 0
+ && let ExpectedSyntax::Unnamed(kinds) = self.expected_syntax_tracking_state.get()
+ {
+ let kinds = kinds.with(kind);
+ self.expected_syntax_tracking_state
+ .set(ExpectedSyntax::Unnamed(kinds));
}
self.nth(n) == kind
}
crates/jrsonnet-stdlib/src/arrays.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/arrays.rs
+++ b/crates/jrsonnet-stdlib/src/arrays.rs
@@ -52,7 +52,7 @@
step: Option<Option<BoundedUsize<1, { i32::MAX as usize }>>>,
) -> Result<Val> {
indexable
- .slice(index.flatten(), end.flatten(), step.flatten())
+ .slice32(index.flatten(), end.flatten(), step.flatten())
.map(Val::from)
}
@@ -204,14 +204,14 @@
let item = item?.clone();
if let Val::Arr(items) = item {
if !first {
- out.reserve(joiner_items.len() as usize);
+ out.reserve(joiner_items.len());
// TODO: extend
for item in joiner_items.iter() {
out.push(item?);
}
}
first = false;
- out.reserve(items.len() as usize);
+ out.reserve(items.len());
for item in items.iter() {
out.push(item?);
}
@@ -372,10 +372,10 @@
#[builtin]
pub fn builtin_remove_at(arr: ArrValue, at: i32) -> Result<ArrValue> {
- let newArrLeft = arr.clone().slice(None, Some(at), None);
- let newArrRight = arr.slice(Some(at + 1), None, None);
+ let newArrLeft = arr.clone().slice32(None, Some(at), None);
+ let newArrRight = arr.slice32(Some(at + 1), None, None);
- Ok(ArrValue::extended(newArrLeft, newArrRight).ok_or_else(|| error!("array is too large"))?)
+ ArrValue::extended(newArrLeft, newArrRight).ok_or_else(|| error!("array is too large"))
}
#[builtin]
crates/jrsonnet-stdlib/src/manifest/xml.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/manifest/xml.rs
+++ b/crates/jrsonnet-stdlib/src/manifest/xml.rs
@@ -44,15 +44,15 @@
bail!("JSONML value should have tag (array length should be >=1)");
}
let tag = String::from_untyped(
- arr.get(0)
+ arr.get32(0)
.description("getting JSONML tag")?
.expect("length checked"),
)
.description("parsing JSONML tag")?;
- let (has_attrs, attrs) = if arr.len() >= 2 {
+ let (has_attrs, attrs) = if arr.len32() >= 2 {
let maybe_attrs = arr
- .get(1)
+ .get32(1)
.with_description(|| "getting JSONML attrs")?
.expect("length checked");
if let Val::Obj(attrs) = maybe_attrs {
@@ -68,13 +68,7 @@
attrs,
children: in_description_frame(
|| "parsing children".to_owned(),
- || {
- FromUntyped::from_untyped(Val::Arr(arr.slice(
- Some(if has_attrs { 2 } else { 1 }),
- None,
- None,
- )))
- },
+ || FromUntyped::from_untyped(Val::Arr(arr.slice(if has_attrs { 2 } else { 1 }..))),
)?,
})
}
crates/jrsonnet-stdlib/src/misc.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/misc.rs
+++ b/crates/jrsonnet-stdlib/src/misc.rs
@@ -16,10 +16,10 @@
pub fn builtin_length(x: Either![IStr, ArrValue, ObjValue, FuncVal]) -> u32 {
use Either4::*;
match x {
- A(x) => x.chars().count() as u32,
- B(x) => x.len(),
- C(x) => x.len(),
- D(f) => f.params_len(),
+ A(x) => u32::try_from(x.chars().count()).expect("4g limit"),
+ B(x) => x.len32(),
+ C(x) => x.len32(),
+ D(f) => f.params_len32(),
}
}
@@ -102,7 +102,7 @@
} else if b.len() == a.len() {
return equals(&Val::Arr(a), &Val::Arr(b));
}
- for (a, b) in a.iter().take(b.len() as usize).zip(b.iter()) {
+ for (a, b) in a.iter().take(b.len()).zip(b.iter()) {
let a = a?;
let b = b?;
if !equals(&a, &b)? {
@@ -127,7 +127,7 @@
return equals(&Val::Arr(a), &Val::Arr(b));
}
let a_len = a.len();
- for (a, b) in a.iter().skip((a_len - b.len()) as usize).zip(b.iter()) {
+ for (a, b) in a.iter().skip(a_len - b.len()).zip(b.iter()) {
let a = a?;
let b = b?;
if !equals(&a, &b)? {
crates/jrsonnet-stdlib/src/sets.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/sets.rs
+++ b/crates/jrsonnet-stdlib/src/sets.rs
@@ -8,13 +8,13 @@
#[allow(non_snake_case)]
pub fn builtin_set_member(x: Thunk<Val>, arr: ArrValue, #[default] keyF: KeyF) -> Result<bool> {
let mut low = 0;
- let mut high = arr.len();
+ let mut high = arr.len32();
let x = keyF.eval(x)?;
while low < high {
let middle = u32::midpoint(high, low);
- let comp = keyF.eval(arr.get_lazy(middle).expect("in bounds"))?;
+ let comp = keyF.eval(arr.get_lazy32(middle).expect("in bounds"))?;
match Val::try_cmp(&comp, &x)? {
Ordering::Less => low = middle + 1,
Ordering::Equal => return Ok(true),
crates/jrsonnet-stdlib/src/sort.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/sort.rs
+++ b/crates/jrsonnet-stdlib/src/sort.rs
@@ -69,7 +69,7 @@
fn sort_keyf(values: ArrValue, keyf: KeyF) -> Result<Vec<Thunk<Val>>> {
// Slow path, user provided key getter
- let mut vk = Vec::with_capacity(values.len() as usize);
+ let mut vk = Vec::with_capacity(values.len());
for value in values.iter_lazy() {
vk.push((value.clone(), keyf.eval(value)?));
}
@@ -137,7 +137,7 @@
fn uniq_keyf(arr: ArrValue, keyf: KeyF) -> Result<Vec<Thunk<Val>>> {
let mut out = Vec::new();
- let last_value = arr.get_lazy(0).unwrap();
+ let last_value = arr.get_lazy32(0).unwrap();
let mut last_key = keyf.eval(last_value.clone())?;
out.push(last_value);
crates/jrsonnet-types/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-types/src/lib.rs
+++ b/crates/jrsonnet-types/src/lib.rs
@@ -103,10 +103,8 @@
Self::BoundedNumber(a, b) => write!(
f,
"BoundedNumber<{}, {}>",
- a.map(|e| e.to_string())
- .unwrap_or_else(|| "open".to_owned()),
- b.map(|e| e.to_string())
- .unwrap_or_else(|| "open".to_owned())
+ a.map_or_else(|| "open".to_owned(), |e| e.to_string()),
+ b.map_or_else(|| "open".to_owned(), |e| e.to_string())
)?,
Self::ArrayRef(a) => print_array(a, f)?,
Self::Array(a) => print_array(a, f)?,
tests/tests/cpp_test_suite.rsdiffbeforeafterboth--- a/tests/tests/cpp_test_suite.rs
+++ b/tests/tests/cpp_test_suite.rs
@@ -60,7 +60,7 @@
let _entered = s.enter();
let trace_format = CompactFormat {
- resolver: resolver.clone(),
+ resolver,
max_trace: 20,
padding: 4,
};
xtask/src/bench.rsdiffbeforeafterboth--- a/xtask/src/bench.rs
+++ b/xtask/src/bench.rs
@@ -91,6 +91,10 @@
let start = Instant::now();
let child = cmd.spawn()?;
+ #[allow(
+ clippy::cast_possible_wrap,
+ reason = "it is signed, but libc didn't set unsigned for it"
+ )]
let pid = child.id() as libc::pid_t;
// We'll reap via wait4 ourselves; don't let std touch this handle again.
mem::forget(child);
@@ -133,10 +137,10 @@
);
eprintln!(
" max_rss: {} ± {} KiB [{}..{}]",
- r.max_rss_kib.mean as i64,
- r.max_rss_kib.stddev as i64,
- r.max_rss_kib.min as i64,
- r.max_rss_kib.max as i64,
+ r.max_rss_kib.mean.trunc(),
+ r.max_rss_kib.stddev.trunc(),
+ r.max_rss_kib.min.trunc(),
+ r.max_rss_kib.max.trunc(),
);
Ok(())
}
xtask/src/sourcegen/mod.rsdiffbeforeafterboth--- a/xtask/src/sourcegen/mod.rs
+++ b/xtask/src/sourcegen/mod.rs
@@ -113,6 +113,7 @@
Ok(())
}
+#[allow(clippy::too_many_lines)]
fn generate_syntax_kinds(kinds: &KindsSrc, grammar: &AstSrc, lexer: bool) -> Result<String> {
let t_macros = kinds.tokens().filter_map(TokenKind::expand_t_macros);
let token_kinds = kinds.tokens().map(|t| t.expand_kind(lexer));