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.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/typed/conversions.rs
+++ b/crates/jrsonnet-evaluator/src/typed/conversions.rs
@@ -637,7 +637,7 @@
}
<Self as Typed>::TYPE.check(&value)?;
// Any::downcast_ref::<ByteArray>(&a);
- let mut out = Vec::with_capacity(a.len() as usize);
+ let mut out = Vec::with_capacity(a.len());
for e in a.iter() {
let r = e?;
out.push(u8::from_untyped(r)?);
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.rsdiffbeforeafterboth1use std::{cell::Cell, fmt, rc::Rc};23use rowan::{GreenNode, TextRange};45use crate::{6 AstToken, SyntaxKind,7 SyntaxKind::*,8 SyntaxNode, T, TS,9 event::Event,10 marker::{CompletedMarker, Marker},11 nodes::{BinaryOperatorKind, Literal, Number, Text, UnaryOperatorKind},12 token_set::SyntaxKindSet,13};1415pub struct Parse {16 pub green_node: GreenNode,17 pub errors: Vec<LocatedSyntaxError>,18}1920pub struct Parser {21 // TODO: remove all trivia before feeding to parser?22 kinds: Vec<SyntaxKind>,23 pub offset: usize,24 pub events: Vec<Event>,25 pub entered: u32,26 pub hints: Vec<(u32, TextRange, String)>,27 pub last_error_token: usize,28 expected_syntax_tracking_state: Rc<Cell<ExpectedSyntax>>,29 steps: Cell<u64>,30}3132#[derive(Clone, Debug)]33pub enum SyntaxError {34 Unexpected {35 expected: ExpectedSyntax,36 found: SyntaxKind,37 },38 Missing {39 expected: ExpectedSyntax,40 },41 Custom {42 error: String,43 },44 Hint {45 error: String,46 },47}48impl fmt::Display for SyntaxError {49 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {50 match self {51 SyntaxError::Unexpected { expected, found } => {52 write!(f, "unexpected {found:?}, expecting {expected}")53 }54 SyntaxError::Missing { expected } => write!(f, "missing {expected}"),55 SyntaxError::Custom { error } | SyntaxError::Hint { error } => write!(f, "{error}"),56 }57 }58}5960#[derive(Debug)]61pub struct LocatedSyntaxError {62 pub error: SyntaxError,63 pub range: TextRange,64}6566impl Parser {67 pub fn new(kinds: Vec<SyntaxKind>) -> Self {68 Self {69 kinds,70 offset: 0,71 events: vec![],72 entered: 0,73 last_error_token: 0,74 hints: vec![],75 expected_syntax_tracking_state: Rc::new(Cell::new(ExpectedSyntax::Unnamed(TS![]))),76 steps: Cell::new(0),77 }78 }79 pub fn clear_outdated_hints(&mut self) {80 let amount = self81 .hints82 .iter()83 .rev()84 .take_while(|h| h.0 > self.entered)85 .count();86 self.hints.truncate(self.hints.len() - amount);87 }88 fn clear_expected_syntaxes(&self) {89 self.expected_syntax_tracking_state90 .set(ExpectedSyntax::Unnamed(TS![]));91 }92 pub fn start(&mut self) -> Marker {93 let start_event_idx = self.events.len();94 self.events.push(Event::Pending);95 self.entered += 1;96 Marker::new(start_event_idx)97 }98 // pub fn start_ranger(&mut self) -> Ranger {99 // let pos = self.offset;100 // Ranger { pos }101 // }102 pub fn parse(mut self) -> Vec<Event> {103 let m = self.start();104 expr(&mut self);105 if !self.at(EOF) {106 let m = self.start();107 while !self.at(EOF) {108 self.bump();109 }110 m.complete_error(&mut self, "unexpected tokens after end");111 }112 m.complete(&mut self, SOURCE_FILE);113114 self.events115 }116117 pub(crate) fn expect(&mut self, kind: SyntaxKind) {118 self.expect_with_recovery_set(kind, TS![]);119 }120121 pub(crate) fn expect_with_recovery_set(122 &mut self,123 kind: SyntaxKind,124 recovery_set: SyntaxKindSet,125 ) {126 if self.at(kind) {127 if kind != EOF {128 self.bump();129 }130 } else {131 self.error_with_recovery_set(recovery_set);132 }133 }134135 // pub(crate) fn expect_with_no_skip(&mut self, kind: SyntaxKind) {136 // if self.at(kind) {137 // self.bump();138 // } else {139 // self.error_with_no_skip();140 // }141 // }142 pub fn error_with_no_skip(&mut self) -> CompletedMarker {143 self.error_with_recovery_set(SyntaxKindSet::ALL)144 }145146 pub fn error_with_recovery_set(&mut self, recovery_set: SyntaxKindSet) -> CompletedMarker {147 let expected = self.expected_syntax_tracking_state.get();148 self.expected_syntax_tracking_state149 .set(ExpectedSyntax::Unnamed(TS![]));150151 if self.at_end() || self.at_ts(recovery_set) {152 let m = self.start();153 return m.complete_missing(self, expected);154 }155156 let current_token = self.current();157158 self.last_error_token = self.offset;159160 let m = self.start();161 self.bump();162 let m = m.complete_unexpected(self, expected, current_token);163 self.clear_expected_syntaxes();164 m165 }166 fn bump_assert(&mut self, kind: SyntaxKind) {167 assert!(self.at(kind), "expected {kind:?}");168 self.bump_remap(self.current());169 }170 fn bump(&mut self) {171 self.bump_remap(self.current());172 }173 fn bump_remap(&mut self, kind: SyntaxKind) {174 assert_ne!(self.offset, self.kinds.len(), "already at end");175 self.events.push(Event::Token { kind });176 self.offset += 1;177 self.clear_expected_syntaxes();178 }179 fn step(&self) {180 use std::fmt::Write;181 let steps = self.steps.get();182 if steps >= 15_000_000 {183 let mut out = "seems like parsing is stuck".to_owned();184 {185 let last = 20;186 write!(out, "\n\nLast {last} events:").unwrap();187 for (i, event) in self188 .events189 .iter()190 .skip(self.events.len().saturating_sub(last))191 .enumerate()192 {193 write!(out, "\n{i}. {event:?}").unwrap();194 }195 }196 {197 let next = 20;198 write!(out, "\n\nNext {next} tokens:").unwrap();199 for (i, tok) in self.kinds.iter().skip(self.offset).take(next).enumerate() {200 write!(out, "\n{i}. {tok:?}").unwrap();201 }202 }203 panic!("{out}")204 }205 self.steps.set(steps + 1);206 }207 fn nth(&self, i: usize) -> SyntaxKind {208 self.step();209 let mut offset = self.offset;210 for _ in 0..i {211 offset += 1;212 }213 self.kinds.get(offset).copied().unwrap_or(EOF)214 }215 fn current(&self) -> SyntaxKind {216 self.nth(0)217 }218 #[must_use]219 pub(crate) fn expected_syntax_name(&self, name: &'static str) -> ExpectedSyntaxGuard {220 self.expected_syntax_tracking_state221 .set(ExpectedSyntax::Named(name));222223 ExpectedSyntaxGuard::new(Rc::clone(&self.expected_syntax_tracking_state))224 }225 pub fn at(&self, kind: SyntaxKind) -> bool {226 self.nth_at(0, kind)227 }228 pub fn nth_at(&self, n: usize, kind: SyntaxKind) -> bool {229 if n == 0 {230 if let ExpectedSyntax::Unnamed(kinds) = self.expected_syntax_tracking_state.get() {231 let kinds = kinds.with(kind);232 self.expected_syntax_tracking_state233 .set(ExpectedSyntax::Unnamed(kinds));234 }235 }236 self.nth(n) == kind237 }238 pub fn at_ts(&self, set: SyntaxKindSet) -> bool {239 if let ExpectedSyntax::Unnamed(kinds) = self.expected_syntax_tracking_state.get() {240 let kinds = kinds.union(set);241 self.expected_syntax_tracking_state242 .set(ExpectedSyntax::Unnamed(kinds));243 }244 set.contains(self.current())245 }246 pub fn at_end(&self) -> bool {247 self.at(EOF)248 }249}250pub struct ExpectedSyntaxGuard {251 expected_syntax_tracking_state: Rc<Cell<ExpectedSyntax>>,252}253254impl ExpectedSyntaxGuard {255 fn new(expected_syntax_tracking_state: Rc<Cell<ExpectedSyntax>>) -> Self {256 Self {257 expected_syntax_tracking_state,258 }259 }260}261262impl Drop for ExpectedSyntaxGuard {263 fn drop(&mut self) {264 self.expected_syntax_tracking_state265 .set(ExpectedSyntax::Unnamed(TS![]));266 }267}268269#[derive(Clone, Debug, Copy)]270pub enum ExpectedSyntax {271 Named(&'static str),272 Unnamed(SyntaxKindSet),273}274impl fmt::Display for ExpectedSyntax {275 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {276 match self {277 Self::Named(name) => write!(f, "{name}"),278 Self::Unnamed(set) => write!(f, "{set}"),279 }280 }281}282283fn expr(p: &mut Parser) -> CompletedMarker {284 let m = p.start();285 while p.at(T![local]) || p.at(T![assert]) {286 let m = p.start();287288 if p.at(T![local]) {289 p.bump();290 loop {291 if p.at(T![;]) {292 p.bump();293 break;294 }295 bind(p);296297 if p.at(T![,]) {298 p.bump();299 continue;300 }301 p.expect(T![;]);302 break;303 }304 m.complete(p, STMT_LOCAL);305 } else {306 assertion(p);307 p.expect(T![;]);308 m.complete(p, STMT_ASSERT);309 }310 }311 match expr_binding_power(p, 0) {312 Ok(m) | Err(m) => m,313 };314 m.complete(p, EXPR)315}316317fn expr_binding_power(318 p: &mut Parser,319 minimum_binding_power: u8,320) -> Result<CompletedMarker, CompletedMarker> {321 let mut lhs = lhs(p)?;322323 while let Some(op) = BinaryOperatorKind::cast(p.current())324 .or_else(|| p.at(T!['{']).then_some(BinaryOperatorKind::MetaObjectApply))325 {326 let (left_binding_power, right_binding_power) = op.binding_power();327 if left_binding_power < minimum_binding_power {328 break;329 }330331 let m = lhs.wrap(p, EXPR, false);332333 // Object apply is not a real operator, we dont have something to bump334 if op != BinaryOperatorKind::MetaObjectApply {335 p.bump();336 }337338 let m = m.precede(p);339 let parsed_rhs = if p.at(T![local]) || p.at(T![assert]) {340 expr(p);341 true342 } else {343 expr_binding_power(p, right_binding_power)344 .map(|v| v.precede(p).complete(p, EXPR))345 .is_ok()346 };347 lhs = m.complete(348 p,349 if op == BinaryOperatorKind::MetaObjectApply {350 EXPR_OBJ_EXTEND351 } else {352 EXPR_BINARY353 },354 );355356 if !parsed_rhs {357 break;358 }359 }360 Ok(lhs)361}362363const COMPSPEC: SyntaxKindSet = TS![for if];364fn compspec(p: &mut Parser) -> CompletedMarker {365 assert!(p.at_ts(COMPSPEC));366 if p.at(T![for]) {367 if p.nth_at(1, T!['[']) && p.nth_at(2, IDENT) && p.nth_at(3, T![']']) && p.nth_at(4, T![:])368 {369 let m = p.start();370 p.bump_assert(T![for]);371 p.bump_assert(T!['[']);372 name(p);373 p.expect(T![']']);374 visibility(p);375 destruct(p);376 p.expect(T![in]);377 expr(p);378 return m.complete(p, FOR_OBJ_SPEC);379 }380 let m = p.start();381 p.bump();382 destruct(p);383 p.expect(T![in]);384 expr(p);385 m.complete(p, FOR_SPEC)386 } else if p.at(T![if]) {387 let m = p.start();388 p.bump();389 expr(p);390 m.complete(p, IF_SPEC)391 } else {392 unreachable!()393 }394}395396fn comma(p: &mut Parser) -> bool {397 comma_with_alternatives(p, TS![])398}399fn comma_with_alternatives(p: &mut Parser, set: SyntaxKindSet) -> bool {400 if p.at(T![,]) {401 p.bump();402 true403 } else if p.at_ts(set) {404 let _ex = p.expected_syntax_name("comma");405 p.expect_with_recovery_set(T![,], TS![]);406 true407 } else {408 false409 }410}411412fn field_name(p: &mut Parser) {413 let _e = p.expected_syntax_name("field name");414 let m = p.start();415 if p.at(T!['[']) {416 p.bump();417 expr(p);418 p.expect(T![']']);419 m.complete(p, FIELD_NAME_DYNAMIC);420 } else if p.at(IDENT) {421 name(p);422 m.complete(p, FIELD_NAME_FIXED);423 } else if Text::can_cast(p.current()) {424 text(p);425 m.complete(p, FIELD_NAME_FIXED);426 } else {427 m.forget(p);428 // Recover with ::, :::429 p.error_with_recovery_set(TS![; : '(']);430 }431}432fn visibility(p: &mut Parser) {433 let m = p.start();434 if !p.at_ts(TS![:]) {435 p.error_with_recovery_set(TS![=]);436 }437 p.bump();438 'colons: {439 if !p.at_ts(TS![:]) {440 break 'colons;441 }442 p.bump();443 if !p.at_ts(TS![:]) {444 break 'colons;445 }446 p.bump();447 }448 m.complete(p, VISIBILITY);449}450fn assertion(p: &mut Parser) {451 let m = p.start();452 p.bump_assert(T![assert]);453 expr(p);454 if p.at(T![:]) {455 p.bump();456 expr(p);457 }458 m.complete(p, ASSERTION);459}460fn object(p: &mut Parser) -> CompletedMarker {461 let m_t = p.start();462 let m = p.start();463 p.bump_assert(T!['{']);464465 let mut elems = 0;466 let mut compspecs = Vec::new();467 let mut asserts = Vec::new();468 loop {469 if p.at(T!['}']) {470 p.bump();471 break;472 }473 if p.at_ts(TS![for]) {474 if elems == 0 {475 let m = p.start();476 m.complete_missing(p, ExpectedSyntax::Named("field definition"));477 }478 while p.at_ts(COMPSPEC) {479 compspecs.push(compspec(p));480 }481 if comma_with_alternatives(p, TS![;]) {482 continue;483 }484 p.expect(R_BRACE);485 break;486 }487 let m = p.start();488 if p.at(T![local]) {489 obj_local(p);490 m.complete(p, MEMBER_BIND_STMT);491 } else if p.at(T![assert]) {492 assertion(p);493 asserts.push(m.complete(p, MEMBER_ASSERT_STMT));494 } else {495 field_name(p);496 if p.at(T![+]) {497 p.bump();498 }499 let params = if p.at(T!['(']) {500 params_desc(p);501 visibility(p);502 expr(p);503 true504 } else {505 visibility(p);506 if p.at(T![function]) {507 p.bump_assert(T![function]);508 params_desc(p);509 expr(p);510 true511 } else {512 expr(p);513 false514 }515 };516 elems += 1;517518 if params {519 m.complete(p, MEMBER_FIELD_METHOD)520 } else {521 m.complete(p, MEMBER_FIELD_NORMAL)522 };523 }524 while p.at_ts(COMPSPEC) {525 compspecs.push(compspec(p));526 }527 if comma_with_alternatives(p, TS![;]) {528 continue;529 }530 p.expect(R_BRACE);531 break;532 }533534 if elems > 1 && !compspecs.is_empty() {535 for errored in compspecs {536 errored.wrap_error(537 p,538 "compspec may only be used if there is only one object element",539 true,540 );541 }542 m.complete(p, OBJ_BODY_MEMBER_LIST);543 } else if !compspecs.is_empty() {544 for errored in asserts {545 errored.wrap_error(p, "asserts can't be used in object comprehensions", true);546 }547 m.complete(p, OBJ_BODY_COMP);548 } else {549 m.complete(p, OBJ_BODY_MEMBER_LIST);550 }551 m_t.complete(p, EXPR_OBJECT)552}553fn param(p: &mut Parser) {554 let m = p.start();555 destruct(p);556 if p.at(T![=]) {557 p.bump();558 expr(p);559 }560 m.complete(p, PARAM);561}562fn params_desc(p: &mut Parser) -> CompletedMarker {563 let m = p.start();564 p.bump_assert(T!['(']);565566 loop {567 if p.at(T![')']) {568 p.bump();569 break;570 }571 param(p);572 if comma(p) {573 continue;574 }575 p.expect(T![')']);576 break;577 }578579 m.complete(p, PARAMS_DESC)580}581fn args_desc(p: &mut Parser) {582 let m = p.start();583 p.bump_assert(T!['(']);584585 let started_named = Cell::new(false);586 let mut unnamed_after_named = Vec::new();587588 loop {589 if p.at(T![')']) {590 break;591 }592593 let m = p.start();594 if p.at(IDENT) && p.nth_at(1, T![=]) {595 name(p);596 p.bump();597 expr(p);598 m.complete(p, ARG);599 started_named.set(true);600 } else {601 expr(p);602 let arg = m.complete(p, ARG);603 if started_named.get() {604 unnamed_after_named.push(arg);605 }606 }607 if comma(p) {608 continue;609 }610 break;611 }612 p.expect(T![')']);613 if p.at(T![tailstrict]) {614 p.bump();615 }616617 for errored in unnamed_after_named {618 errored.wrap_error(p, "can't use positional arguments after named", true);619 }620621 m.complete(p, ARGS_DESC);622}623624fn array(p: &mut Parser) -> CompletedMarker {625 // Start the list node626 let m = p.start();627 p.bump_assert(T!['[']);628629 let mut compspecs = Vec::new();630 let mut elems = 0;631632 loop {633 if p.at(T![']']) {634 p.bump();635 break;636 }637 if elems != 0 && p.at_ts(TS![for]) {638 while p.at_ts(COMPSPEC) {639 compspecs.push(compspec(p));640 }641 if comma(p) {642 continue;643 }644 p.expect(T![']']);645 break;646 }647 expr(p);648 elems += 1;649 while p.at_ts(COMPSPEC) {650 compspecs.push(compspec(p));651 }652 if comma(p) {653 continue;654 }655 p.expect(T![']']);656 break;657 }658659 if elems > 1 && !compspecs.is_empty() {660 for spec in compspecs {661 spec.wrap_error(662 p,663 "compspec may only be used if there is only one array element",664 true,665 );666 }667668 m.complete(p, EXPR_ARRAY)669 } else if !compspecs.is_empty() {670 m.complete(p, EXPR_ARRAY_COMP)671 } else {672 m.complete(p, EXPR_ARRAY)673 }674}675/// Returns true if it was slice, false if just index676#[must_use]677fn slice_desc_or_index(p: &mut Parser) -> bool {678 let m = p.start();679 p.bump();680 // Start681 if !p.at(T![:]) {682 expr(p);683 }684 if p.at(T![:]) {685 p.bump();686 // End687 if !p.at_ts(TS![']' :]) {688 expr(p).wrap(p, SLICE_DESC_END, true);689 }690 if p.at(T![:]) {691 p.bump();692 // Step693 if !p.at(T![']']) {694 expr(p).wrap(p, SLICE_DESC_STEP, true);695 }696 }697 } else {698 // It was not a slice699 p.expect(T![']']);700 m.forget(p);701 return false;702 }703 p.expect(T![']']);704 m.complete(p, SLICE_DESC);705 true706}707708fn suffix(p: &mut Parser) {709 loop {710 let start = p.start();711 let _marker: CompletedMarker = if p.at(T![?]) {712 p.bump();713 p.expect(T![.]);714 if p.at(IDENT) {715 name(p);716 start.complete(p, SUFFIX_INDEX)717 } else if p.at(T!['[']) {718 p.bump();719 expr(p);720 p.expect(T![']']);721 start.complete(p, SUFFIX_INDEX_EXPR)722 } else {723 start.complete_missing(p, ExpectedSyntax::Named("index"))724 }725 } else if p.at(T![.]) {726 p.bump();727 name(p);728 start.complete(p, SUFFIX_INDEX)729 } else if p.at(T!['[']) {730 if slice_desc_or_index(p) {731 start.complete(p, SUFFIX_SLICE)732 } else {733 start.complete(p, SUFFIX_INDEX_EXPR)734 }735 } else if p.at(T!['(']) {736 args_desc(p);737 start.complete(p, SUFFIX_APPLY)738 } else {739 start.forget(p);740 break;741 };742 }743}744745fn lhs(p: &mut Parser) -> Result<CompletedMarker, CompletedMarker> {746 let lhs = lhs_basic(p)?;747748 suffix(p);749750 Ok(lhs)751}752fn name(p: &mut Parser) {753 let m = p.start();754 p.expect(IDENT);755 m.complete(p, NAME);756}757fn destruct_rest(p: &mut Parser) {758 let m = p.start();759 p.bump_assert(T![...]);760 if p.at(IDENT) {761 p.bump();762 }763 m.complete(p, DESTRUCT_REST);764}765fn destruct_object_field(p: &mut Parser) {766 let m = p.start();767 name(p);768 if p.at(T![:]) {769 p.bump();770 destruct(p);771 }772 if p.at(T![=]) {773 p.bump();774 expr(p);775 }776 m.complete(p, DESTRUCT_OBJECT_FIELD);777}778fn obj_local(p: &mut Parser) {779 let m = p.start();780 p.bump_assert(T![local]);781 bind(p);782 m.complete(p, OBJ_LOCAL);783}784fn destruct(p: &mut Parser) -> CompletedMarker {785 let m = p.start();786 let _ex = p.expected_syntax_name("destruction specifier");787 if p.at(T![?]) {788 p.bump();789 m.complete(p, DESTRUCT_SKIP)790 } else if p.at(T!['[']) {791 p.bump();792 // let mut had_rest = false;793 loop {794 if p.at(T![']']) {795 p.bump();796 break;797 } else if p.at(T![...]) {798 // let m_err = p.start_ranger();799 destruct_rest(p);800 // if had_rest {801 // p.custom_error(m_err.finish(p), "only one rest can be present in array");802 // }803 // had_rest = true;804 } else {805 destruct(p);806 }807 if p.at(T![,]) {808 p.bump();809 continue;810 }811 p.expect(T![']']);812 break;813 }814 m.complete(p, DESTRUCT_ARRAY)815 } else if p.at(T!['{']) {816 p.bump();817 let mut had_rest = false;818 loop {819 if p.at(T!['}']) {820 p.bump();821 break;822 } else if p.at(T![...]) {823 // let m_err = p.start_ranger();824 destruct_rest(p);825 // if had_rest {826 // p.custom_error(m_err.finish(p), "only one rest can be present in object");827 // }828 had_rest = true;829 } else {830 if had_rest {831 p.error_with_recovery_set(TS![]);832 }833 destruct_object_field(p);834 }835 if p.at(T![,]) {836 p.bump();837 continue;838 }839 p.expect(T!['}']);840 break;841 }842 m.complete(p, DESTRUCT_OBJECT)843 } else if p.at(IDENT) {844 name(p);845 m.complete(p, DESTRUCT_FULL)846 } else {847 m.forget(p);848 p.error_with_recovery_set(TS![; , '}', '(', :])849 }850}851fn bind(p: &mut Parser) {852 let m = p.start();853 if p.at(IDENT) && p.nth_at(1, T!['(']) {854 name(p);855 params_desc(p);856 p.expect(T![=]);857 expr(p);858 m.complete(p, BIND_FUNCTION)859 } else if p.at(IDENT) && p.nth_at(1, T![=]) && p.nth_at(2, T![function]) {860 name(p);861 p.expect(T![=]);862 p.expect(T![function]);863 params_desc(p);864 expr(p);865 m.complete(p, BIND_FUNCTION)866 } else {867 destruct(p);868 p.expect(T![=]);869 expr(p);870 m.complete(p, BIND_DESTRUCT)871 };872}873fn text(p: &mut Parser) {874 assert!(Text::can_cast(p.current()));875 p.bump();876}877fn number(p: &mut Parser) {878 assert!(Number::can_cast(p.current()));879 p.bump();880}881fn literal(p: &mut Parser) {882 assert!(Literal::can_cast(p.current()));883 p.bump();884}885fn lhs_basic(p: &mut Parser) -> Result<CompletedMarker, CompletedMarker> {886 let _e = p.expected_syntax_name("expression");887 Ok(if Literal::can_cast(p.current()) {888 let m = p.start();889 literal(p);890 m.complete(p, EXPR_LITERAL)891 } else if Text::can_cast(p.current()) {892 let m = p.start();893 text(p);894 m.complete(p, EXPR_STRING)895 } else if Number::can_cast(p.current()) {896 let m = p.start();897 number(p);898 m.complete(p, EXPR_NUMBER)899 } else if p.at(IDENT) {900 let m = p.start();901 name(p);902 m.complete(p, EXPR_VAR)903 } else if p.at(T![if]) {904 let m = p.start();905 p.bump();906 expr(p);907 p.expect(T![then]);908 expr(p).wrap(p, TRUE_EXPR, true);909 if p.at(T![else]) {910 p.bump();911 expr(p).wrap(p, FALSE_EXPR, true);912 }913 m.complete(p, EXPR_IF_THEN_ELSE)914 } else if p.at(T!['[']) {915 array(p)916 } else if p.at(T!['{']) {917 object(p)918 } else if p.at(T![function]) {919 let m = p.start();920 p.bump();921 params_desc(p);922 expr(p);923 m.complete(p, EXPR_FUNCTION)924 } else if p.at(T![error]) {925 let m = p.start();926 p.bump();927 expr(p);928 m.complete(p, EXPR_ERROR)929 } else if p.at(T![import]) || p.at(T![importstr]) || p.at(T![importbin]) {930 let m = p.start();931 p.bump();932 text(p);933 m.complete(p, EXPR_IMPORT)934 } else if let Some(op) = UnaryOperatorKind::cast(p.current()) {935 let ((), right_binding_power) = op.binding_power();936937 let m = p.start();938 p.bump();939 let _ = expr_binding_power(p, right_binding_power).map(|v| v.precede(p).complete(p, EXPR));940 m.complete(p, EXPR_UNARY)941 } else if p.at(T!['(']) {942 let m = p.start();943 p.bump();944 expr(p);945 p.expect(T![')']);946 m.complete(p, EXPR_PARENED)947 } else {948 return Err(p.error_with_no_skip());949 })950}951952impl Parse {953 pub fn syntax(&self) -> SyntaxNode {954 SyntaxNode::new_root(self.green_node.clone())955 }956}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));