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.rsdiffbeforeafterboth1use std::{2 any::Any,3 cell::RefCell,4 fmt::{self, Debug},5 mem::replace,6 rc::Rc,7};89use jrsonnet_gcmodule::{Cc, Trace};10use jrsonnet_interner::{IBytes, IStr};1112use super::{ArrValue, arridx};13use crate::{14 Context, Error, ObjValue, Result, Thunk, Val,15 analyze::{ClosureShape, LExpr},16 error::ErrorKind::InfiniteRecursionDetected,17 evaluate::evaluate,18 function::NativeFn,19 typed::{IntoUntyped, Typed},20 val::ThunkValue,21};2223pub trait ArrayLike: Any + Trace + Debug {24 fn len32(&self) -> u32;25 fn is_empty(&self) -> bool {26 self.len32() == 027 }28 fn get32(&self, index: u32) -> Result<Option<Val>>;29 fn get_lazy32(&self, index: u32) -> Option<Thunk<Val>>;3031 fn is_cheap(&self) -> bool {32 false33 }34}35trait ArrayCheap {36 fn get(&self, index: u32) -> Option<Val>;37 fn len(&self) -> u32;38}39impl<T> ArrayLike for T40where41 T: Any + Trace + Debug + ArrayCheap,42{43 fn len32(&self) -> u32 {44 <T as ArrayCheap>::len(self)45 }4647 fn get32(&self, index: u32) -> Result<Option<Val>> {48 Ok(<T as ArrayCheap>::get(self, index))49 }5051 fn get_lazy32(&self, index: u32) -> Option<Thunk<Val>> {52 <T as ArrayCheap>::get(self, index).map(Thunk::evaluated)53 }5455 fn is_cheap(&self) -> bool {56 true57 }58}5960impl ArrayCheap for () {61 fn len(&self) -> u32 {62 063 }64 fn get(&self, _index: u32) -> Option<Val> {65 None66 }67}6869#[derive(Debug, Trace)]70pub struct SliceArray {71 pub(crate) inner: ArrValue,72 pub(crate) from: u32,73 pub(crate) to: u32,74 pub(crate) step: u32,75}7677impl SliceArray {78 fn map_idx(&self, index: u32) -> u32 {79 self.from + self.step * index80 }81}82impl ArrayLike for SliceArray {83 fn len32(&self) -> u32 {84 (self.to - self.from).div_ceil(self.step)85 }8687 fn get32(&self, index: u32) -> Result<Option<Val>> {88 self.inner.get32(self.map_idx(index))89 }9091 fn get_lazy32(&self, index: u32) -> Option<Thunk<Val>> {92 self.inner.get_lazy32(self.map_idx(index))93 }9495 fn is_cheap(&self) -> bool {96 self.inner.is_cheap()97 }98}99100impl ArrayCheap for IBytes {101 fn len(&self) -> u32 {102 arridx(self.as_slice().len())103 }104 fn get(&self, index: u32) -> Option<Val> {105 self.as_slice()106 .get(index as usize)107 .map(|v| Val::Num((*v).into()))108 }109}110111#[derive(Debug, Trace, Clone)]112enum ArrayThunk {113 Computed(Val),114 Errored(Error),115 Waiting,116 Pending,117}118119#[derive(Debug, Trace, Clone)]120pub struct ExprArray {121 ctx: Context,122 src: Rc<Vec<LExpr>>,123 cached: Cc<RefCell<Vec<ArrayThunk>>>,124}125impl ExprArray {126 pub fn new(outer: Context, shape: &ClosureShape, src: Rc<Vec<LExpr>>) -> Self {127 Self {128 ctx: Context::enter_using(&outer, shape),129 cached: Cc::new(RefCell::new(vec![ArrayThunk::Waiting; src.len()])),130 src,131 }132 }133}134impl ArrayLike for ExprArray {135 fn len32(&self) -> u32 {136 arridx(self.cached.borrow().len())137 }138 fn get32(&self, index: u32) -> Result<Option<Val>> {139 if index >= self.len32() {140 return Ok(None);141 }142 match &self.cached.borrow()[index as usize] {143 ArrayThunk::Computed(c) => return Ok(Some(c.clone())),144 ArrayThunk::Errored(e) => return Err(e.clone()),145 ArrayThunk::Pending => return Err(InfiniteRecursionDetected.into()),146 ArrayThunk::Waiting => {}147 }148149 let ArrayThunk::Waiting = replace(150 &mut self.cached.borrow_mut()[index as usize],151 ArrayThunk::Pending,152 ) else {153 unreachable!()154 };155156 let new_value: Val = evaluate(self.ctx.clone(), &self.src[index as usize])?;157 self.cached.borrow_mut()[index as usize] = ArrayThunk::Computed(new_value.clone());158 Ok(Some(new_value))159 }160 fn get_lazy32(&self, index: u32) -> Option<Thunk<Val>> {161 #[derive(Trace)]162 struct ExprArrThunk {163 expr: ExprArray,164 index: u32,165 }166 impl ThunkValue for ExprArrThunk {167 type Output = Val;168169 fn get(&self) -> Result<Self::Output> {170 self.expr171 .get32(self.index)172 .transpose()173 .expect("index checked")174 }175 }176177 if index >= self.len32() {178 return None;179 }180 match &self.cached.borrow()[index as usize] {181 ArrayThunk::Computed(c) => return Some(Thunk::evaluated(c.clone())),182 ArrayThunk::Errored(e) => return Some(Thunk::errored(e.clone())),183 ArrayThunk::Waiting | ArrayThunk::Pending => {}184 }185186 Some(Thunk::new(ExprArrThunk {187 expr: self.clone(),188 index,189 }))190 }191 fn is_cheap(&self) -> bool {192 false193 }194}195196#[derive(Trace, Debug)]197pub struct ExtendedArray {198 pub a: ArrValue,199 pub b: ArrValue,200 split: u32,201 len: u32,202}203impl ExtendedArray {204 pub fn new(a: ArrValue, b: ArrValue) -> Option<Self> {205 let a_len = a.len32();206 let b_len = b.len32();207 let len = a_len.checked_add(b_len)?;208 Some(Self {209 a,210 b,211 split: a_len,212 len,213 })214 }215}216217struct WithExactSize<I>(I, usize);218impl<I, T> Iterator for WithExactSize<I>219where220 I: Iterator<Item = T>,221{222 type Item = T;223224 fn next(&mut self) -> Option<Self::Item> {225 self.0.next()226 }227 fn nth(&mut self, n: usize) -> Option<Self::Item> {228 self.0.nth(n)229 }230 fn size_hint(&self) -> (usize, Option<usize>) {231 (self.1, Some(self.1))232 }233}234impl<I> DoubleEndedIterator for WithExactSize<I>235where236 I: DoubleEndedIterator,237{238 fn next_back(&mut self) -> Option<Self::Item> {239 self.0.next_back()240 }241 fn nth_back(&mut self, n: usize) -> Option<Self::Item> {242 self.0.nth_back(n)243 }244}245impl<I> ExactSizeIterator for WithExactSize<I>246where247 I: Iterator,248{249 fn len(&self) -> usize {250 self.1251 }252}253impl ArrayLike for ExtendedArray {254 fn get32(&self, index: u32) -> Result<Option<Val>> {255 if self.split > index {256 self.a.get32(index)257 } else {258 self.b.get32(index - self.split)259 }260 }261 fn get_lazy32(&self, index: u32) -> Option<Thunk<Val>> {262 if self.split > index {263 self.a.get_lazy32(index)264 } else {265 self.b.get_lazy32(index - self.split)266 }267 }268269 fn len32(&self) -> u32 {270 self.len271 }272273 fn is_cheap(&self) -> bool {274 self.a.is_cheap() && self.b.is_cheap()275 }276}277278impl<T> ArrayLike for Vec<T>279where280 T: IntoUntyped + Trace + fmt::Debug,281 for<'a> &'a T: IntoUntyped,282{283 fn len32(&self) -> u32 {284 self.as_slice().len().try_into().unwrap_or(u32::MAX)285 }286287 fn get32(&self, index: u32) -> Result<Option<Val>> {288 let Some(elem) = self.as_slice().get(index as usize) else {289 return Ok(None);290 };291 IntoUntyped::into_untyped(elem).map(Some)292 }293294 fn get_lazy32(&self, index: u32) -> Option<Thunk<Val>> {295 let elem = self.as_slice().get(index as usize)?;296 Some(IntoUntyped::into_lazy_untyped(elem))297 }298299 fn is_cheap(&self) -> bool {300 !T::provides_lazy()301 }302}303304/// Inclusive range type305#[derive(Debug, Trace, PartialEq, Eq)]306pub struct RangeArray {307 start: i32,308 end: i32,309}310impl RangeArray {311 pub fn empty() -> Self {312 Self::new_exclusive(0, 0)313 }314 pub fn new_exclusive(start: i32, end: i32) -> Self {315 end.checked_sub(1)316 .map_or_else(Self::empty, |end| Self { start, end })317 }318 pub fn new_inclusive(start: i32, end: i32) -> Self {319 Self { start, end }320 }321 #[expect(322 clippy::cast_sign_loss,323 reason = "the math is valid with wrapping, sign loss works as intended"324 )]325 fn size(&self) -> u32 {326 (self.end as u32)327 .wrapping_sub(self.start as u32)328 .wrapping_add(1)329 }330 fn range(&self) -> impl ExactSizeIterator<Item = i32> + DoubleEndedIterator {331 WithExactSize(self.start..=self.end, self.size() as usize)332 }333}334impl ArrayCheap for RangeArray {335 fn get(&self, index: u32) -> Option<Val> {336 self.range().nth(index as usize).map(|i| Val::Num(i.into()))337 }338 fn len(&self) -> u32 {339 self.size()340 }341}342343#[derive(Debug, Trace)]344pub struct ReverseArray(pub ArrValue);345impl ArrayLike for ReverseArray {346 fn len32(&self) -> u32 {347 self.0.len32()348 }349350 fn get32(&self, index: u32) -> Result<Option<Val>> {351 self.0.get32(self.0.len32() - index - 1)352 }353354 fn get_lazy32(&self, index: u32) -> Option<Thunk<Val>> {355 self.0.get_lazy32(self.0.len32() - index - 1)356 }357358 fn is_cheap(&self) -> bool {359 self.0.is_cheap()360 }361}362363#[derive(Trace, Clone, Debug)]364pub enum ArrayMapper {365 Plain(NativeFn!((Val) -> Val)),366 WithIndex(NativeFn!((u32, Val) -> Val)),367}368369#[derive(Trace, Debug, Clone)]370pub struct MappedArray {371 inner: ArrValue,372 cached: Cc<RefCell<Vec<ArrayThunk>>>,373 mapper: ArrayMapper,374}375impl MappedArray {376 pub fn new(inner: ArrValue, mapper: ArrayMapper) -> Self {377 let len = inner.len32();378 Self {379 inner,380 cached: Cc::new(RefCell::new(vec![ArrayThunk::Waiting; len as usize])),381 mapper,382 }383 }384 fn evaluate(&self, index: u32, value: Val) -> Result<Val> {385 match &self.mapper {386 ArrayMapper::Plain(f) => f.call(value),387 ArrayMapper::WithIndex(f) => f.call(index, value),388 }389 }390}391impl ArrayLike for MappedArray {392 fn len32(&self) -> u32 {393 arridx(self.cached.borrow().len())394 }395396 fn get32(&self, index: u32) -> Result<Option<Val>> {397 if index >= self.len32() {398 return Ok(None);399 }400 match &self.cached.borrow()[index as usize] {401 ArrayThunk::Computed(c) => return Ok(Some(c.clone())),402 ArrayThunk::Errored(e) => return Err(e.clone()),403 ArrayThunk::Pending => return Err(InfiniteRecursionDetected.into()),404 ArrayThunk::Waiting => {}405 }406407 let ArrayThunk::Waiting = replace(408 &mut self.cached.borrow_mut()[index as usize],409 ArrayThunk::Pending,410 ) else {411 unreachable!()412 };413414 let val = self415 .inner416 .get32(index)417 .transpose()418 .expect("index checked")419 .and_then(|r| self.evaluate(index, r));420421 let new_value = match val {422 Ok(v) => v,423 Err(e) => {424 self.cached.borrow_mut()[index as usize] = ArrayThunk::Errored(e.clone());425 return Err(e);426 }427 };428 self.cached.borrow_mut()[index as usize] = ArrayThunk::Computed(new_value.clone());429 Ok(Some(new_value))430 }431 fn get_lazy32(&self, index: u32) -> Option<Thunk<Val>> {432 #[derive(Trace)]433 struct MappedArrayThunk {434 arr: MappedArray,435 index: u32,436 }437 impl ThunkValue for MappedArrayThunk {438 type Output = Val;439440 fn get(&self) -> Result<Self::Output> {441 self.arr442 .get32(self.index)443 .transpose()444 .expect("index checked")445 }446 }447448 if index >= self.len32() {449 return None;450 }451 match &self.cached.borrow()[index as usize] {452 ArrayThunk::Computed(c) => return Some(Thunk::evaluated(c.clone())),453 ArrayThunk::Errored(e) => return Some(Thunk::errored(e.clone())),454 ArrayThunk::Waiting | ArrayThunk::Pending => {}455 }456457 Some(Thunk::new(MappedArrayThunk {458 arr: self.clone(),459 index,460 }))461 }462}463#[derive(Trace, Debug, Clone)]464pub struct MakeArray {465 cached: Cc<RefCell<Vec<ArrayThunk>>>,466 mapper: NativeFn!((u32,)->Val),467}468impl MakeArray {469 pub fn new(len: u32, mapper: NativeFn!((u32)->Val)) -> Self {470 Self {471 cached: Cc::new(RefCell::new(vec![ArrayThunk::Waiting; len as usize])),472 mapper,473 }474 }475}476impl ArrayLike for MakeArray {477 fn len32(&self) -> u32 {478 arridx(self.cached.borrow().len())479 }480481 fn get32(&self, index: u32) -> Result<Option<Val>> {482 if index >= self.len32() {483 return Ok(None);484 }485 match &self.cached.borrow()[index as usize] {486 ArrayThunk::Computed(c) => return Ok(Some(c.clone())),487 ArrayThunk::Errored(e) => return Err(e.clone()),488 ArrayThunk::Pending => return Err(InfiniteRecursionDetected.into()),489 ArrayThunk::Waiting => {}490 }491492 let ArrayThunk::Waiting = replace(493 &mut self.cached.borrow_mut()[index as usize],494 ArrayThunk::Pending,495 ) else {496 unreachable!()497 };498499 let val = self.mapper.call(index);500501 let new_value = match val {502 Ok(v) => v,503 Err(e) => {504 self.cached.borrow_mut()[index as usize] = ArrayThunk::Errored(e.clone());505 return Err(e);506 }507 };508 self.cached.borrow_mut()[index as usize] = ArrayThunk::Computed(new_value.clone());509 Ok(Some(new_value))510 }511 fn get_lazy32(&self, index: u32) -> Option<Thunk<Val>> {512 #[derive(Trace)]513 struct MakeArrayThunk {514 arr: MakeArray,515 index: u32,516 }517 impl ThunkValue for MakeArrayThunk {518 type Output = Val;519520 fn get(&self) -> Result<Self::Output> {521 self.arr522 .get32(self.index)523 .transpose()524 .expect("index checked")525 }526 }527528 if index >= self.len32() {529 return None;530 }531 match &self.cached.borrow()[index as usize] {532 ArrayThunk::Computed(c) => return Some(Thunk::evaluated(c.clone())),533 ArrayThunk::Errored(e) => return Some(Thunk::errored(e.clone())),534 ArrayThunk::Waiting | ArrayThunk::Pending => {}535 }536537 Some(Thunk::new(MakeArrayThunk {538 arr: self.clone(),539 index,540 }))541 }542}543544#[derive(Trace, Debug)]545pub struct RepeatedArray {546 data: ArrValue,547 repeats: u32,548 total_len: u32,549}550impl RepeatedArray {551 pub fn new(data: ArrValue, repeats: u32) -> Option<Self> {552 let total_len = data.len32().checked_mul(repeats)?;553 Some(Self {554 data,555 repeats,556 total_len,557 })558 }559 fn map_idx(&self, index: u32) -> Option<u32> {560 if index > self.total_len {561 return None;562 }563 Some(index % self.data.len32())564 }565}566567impl ArrayLike for RepeatedArray {568 fn len32(&self) -> u32 {569 self.total_len570 }571572 fn get32(&self, index: u32) -> Result<Option<Val>> {573 let Some(idx) = self.map_idx(index) else {574 return Ok(None);575 };576 self.data.get32(idx)577 }578579 fn get_lazy32(&self, index: u32) -> Option<Thunk<Val>> {580 let idx = self.map_idx(index)?;581 self.data.get_lazy32(idx)582 }583584 fn is_cheap(&self) -> bool {585 self.data.is_cheap()586 }587}588589#[derive(Trace, Debug)]590pub struct PickObjectValues {591 obj: ObjValue,592 keys: Vec<IStr>,593}594595impl PickObjectValues {596 pub fn new(obj: ObjValue, keys: Vec<IStr>) -> Self {597 Self { obj, keys }598 }599}600601impl ArrayLike for PickObjectValues {602 fn len32(&self) -> u32 {603 arridx(self.keys.len())604 }605606 fn get32(&self, index: u32) -> Result<Option<Val>> {607 let Some(key) = self.keys.as_slice().get(index as usize) else {608 return Ok(None);609 };610 Ok(Some(self.obj.get_or_bail(key.clone())?))611 }612613 fn get_lazy32(&self, index: u32) -> Option<Thunk<Val>> {614 let key = self.keys.as_slice().get(index as usize)?;615 Some(self.obj.get_lazy_or_bail(key.clone()))616 }617618 fn is_cheap(&self) -> bool {619 false620 }621}622623#[derive(Trace, Debug)]624pub struct PickObjectKeyValues {625 obj: ObjValue,626 keys: Vec<IStr>,627}628629impl PickObjectKeyValues {630 pub fn new(obj: ObjValue, keys: Vec<IStr>) -> Self {631 Self { obj, keys }632 }633}634635#[derive(Typed, IntoUntyped)]636pub struct KeyValue {637 key: IStr,638 value: Thunk<Val>,639}640641impl ArrayLike for PickObjectKeyValues {642 fn len32(&self) -> u32 {643 arridx(self.keys.len())644 }645646 fn get32(&self, index: u32) -> Result<Option<Val>> {647 let Some(key) = self.keys.as_slice().get(index as usize) else {648 return Ok(None);649 };650 Ok(Some(651 KeyValue::into_untyped(KeyValue {652 key: key.clone(),653 value: Thunk::evaluated(self.obj.get_or_bail(key.clone())?),654 })655 .expect("convertible"),656 ))657 }658659 fn get_lazy32(&self, index: u32) -> Option<Thunk<Val>> {660 let key = self.keys.as_slice().get(index as usize)?;661 // Nothing can fail in the key part, yet value is still662 // lazy-evaluated663 Some(Thunk::evaluated(664 KeyValue::into_untyped(KeyValue {665 key: key.clone(),666 value: self.obj.get_lazy_or_bail(key.clone()),667 })668 .expect("convertible"),669 ))670 }671672 fn is_cheap(&self) -> bool {673 false674 }675}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.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));