difftreelog
style fix clippy warnings
in: master
20 files changed
bindings/jsonnet/src/lib.rsdiffbeforeafterboth--- a/bindings/jsonnet/src/lib.rs
+++ b/bindings/jsonnet/src/lib.rs
@@ -70,6 +70,7 @@
/// Creates a new Jsonnet virtual machine.
#[no_mangle]
+#[allow(clippy::box_default)]
pub extern "C" fn jsonnet_make() -> *mut State {
let state = State::default();
state.settings_mut().import_resolver = Box::new(FileImportResolver::default());
crates/jrsonnet-cli/src/stdlib.rsdiffbeforeafterboth--- a/crates/jrsonnet-cli/src/stdlib.rs
+++ b/crates/jrsonnet-cli/src/stdlib.rs
@@ -44,7 +44,7 @@
if out.len() != 2 {
return Err("bad ext-file syntax".to_owned());
}
- let file = read_to_string(&out[1]);
+ let file = read_to_string(out[1]);
match file {
Ok(content) => Ok(Self {
name: out[0].into(),
crates/jrsonnet-evaluator/src/error.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/error.rs
+++ b/crates/jrsonnet-evaluator/src/error.rs
@@ -100,7 +100,7 @@
#[error("duplicate local var: {0}")]
DuplicateLocalVar(IStr),
- #[error("type mismatch: expected {}, got {2} {0}", .1.iter().map(|e| format!("{}", e)).collect::<Vec<_>>().join(", "))]
+ #[error("type mismatch: expected {}, got {2} {0}", .1.iter().map(|e| format!("{e}")).collect::<Vec<_>>().join(", "))]
TypeMismatch(&'static str, Vec<ValType>, ValType),
#[error("no such field: {}{}", format_empty_str(.0), format_found(.1, "field"))]
NoSuchField(IStr, Vec<IStr>),
@@ -113,7 +113,7 @@
BindingParameterASecondTime(IStr),
#[error("too many args, function has {0}{}", format_signature(.1))]
TooManyArgsFunctionHas(usize, FunctionSignature),
- #[error("function argument is not passed: {}{}", .0.as_ref().map(|n| n.as_str()).unwrap_or("<unnamed>"), format_signature(.1))]
+ #[error("function argument is not passed: {}{}", .0.as_ref().map_or("<unnamed>", IStr::as_str), format_signature(.1))]
FunctionParameterNotBoundInCall(Option<IStr>, FunctionSignature),
#[error("external variable is not defined: {0}")]
@@ -249,7 +249,7 @@
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
writeln!(f, "{}", self.0 .0)?;
for el in &self.0 .1 .0 {
- writeln!(f, "\t{:?}", el)?;
+ writeln!(f, "\t{el:?}")?;
}
Ok(())
}
crates/jrsonnet-evaluator/src/evaluate/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/evaluate/mod.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/mod.rs
@@ -436,7 +436,7 @@
UnaryOp(o, v) => evaluate_unary_op(*o, &evaluate(s, ctx, v)?)?,
Var(name) => s.push(
CallLocation::new(loc),
- || format!("variable <{}> access", name),
+ || format!("variable <{name}> access"),
|| ctx.binding(name.clone())?.evaluate(s.clone()),
)?,
Index(value, index) => {
@@ -446,7 +446,7 @@
) {
(Val::Obj(v), Val::Str(key)) => s.push(
CallLocation::new(loc),
- || format!("field <{}> access", key),
+ || format!("field <{key}> access"),
|| match v.get(s.clone(), key.clone()) {
Ok(Some(v)) => Ok(v),
#[cfg(not(feature = "friendly-errors"))]
@@ -611,7 +611,7 @@
if let Some(value) = expr {
Ok(Some(s.push(
loc,
- || format!("slice {}", desc),
+ || format!("slice {desc}"),
|| T::from_untyped(evaluate(s.clone(), ctx.clone(), value)?, s.clone()),
)?))
} else {
crates/jrsonnet-evaluator/src/evaluate/operator.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/evaluate/operator.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/operator.rs
@@ -30,8 +30,8 @@
(Str(a), Num(b)) => Str(format!("{a}{b}").into()),
(Str(a), o) | (o, Str(a)) if a.is_empty() => Val::Str(o.clone().to_string(s)?),
- (Str(a), o) => Str(format!("{}{}", a, o.clone().to_string(s)?).into()),
- (o, Str(a)) => Str(format!("{}{}", o.clone().to_string(s)?, a).into()),
+ (Str(a), o) => Str(format!("{a}{}", o.clone().to_string(s)?).into()),
+ (o, Str(a)) => Str(format!("{}{a}", o.clone().to_string(s)?).into()),
(Obj(v1), Obj(v2)) => Obj(v2.extend_from(v1.clone())),
(Arr(a), Arr(b)) => {
crates/jrsonnet-evaluator/src/function/arglike.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/function/arglike.rs
+++ b/crates/jrsonnet-evaluator/src/function/arglike.rs
@@ -108,7 +108,7 @@
handler: &mut dyn FnMut(usize, Thunk<Val>) -> Result<()>,
) -> Result<()> {
for (idx, el) in self.iter().enumerate() {
- handler(idx, Thunk::evaluated(el.clone()))?
+ handler(idx, Thunk::evaluated(el.clone()))?;
}
Ok(())
}
crates/jrsonnet-evaluator/src/function/parse.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/function/parse.rs
+++ b/crates/jrsonnet-evaluator/src/function/parse.rs
@@ -179,12 +179,7 @@
// FIXME: O(n) for arg existence check
let id = params
.iter()
- .position(|p| {
- p.name
- .as_ref()
- .map(|v| &v as &str == name as &str)
- .unwrap_or(false)
- })
+ .position(|p| p.name.as_ref().map_or(false, |v| v as &str == name as &str))
.ok_or_else(|| UnknownFunctionParameter((name as &str).to_owned()))?;
if replace(&mut passed_args[id], Some(arg)).is_some() {
throw!(BindingParameterASecondTime(name.clone()));
@@ -209,8 +204,7 @@
if param
.name
.as_ref()
- .map(|v| &v as &str == name as &str)
- .unwrap_or(false)
+ .map_or(false, |v| v as &str == name as &str)
{
found = true;
}
crates/jrsonnet-evaluator/src/import.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/import.rs
+++ b/crates/jrsonnet-evaluator/src/import.rs
@@ -123,15 +123,11 @@
};
if meta.is_file() {
Ok(SourcePath::new(SourceFile::new(
- path.canonicalize()
- .map_err(|e| ImportIo(e.to_string()))?
- .to_owned(),
+ path.canonicalize().map_err(|e| ImportIo(e.to_string()))?,
)))
} else if meta.is_dir() {
Ok(SourcePath::new(SourceDirectory::new(
- path.canonicalize()
- .map_err(|e| ImportIo(e.to_string()))?
- .to_owned(),
+ path.canonicalize().map_err(|e| ImportIo(e.to_string()))?,
)))
} else {
unreachable!("this can't be a symlink")
crates/jrsonnet-evaluator/src/integrations/serde.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/integrations/serde.rs
+++ b/crates/jrsonnet-evaluator/src/integrations/serde.rs
@@ -16,7 +16,7 @@
Self::Null => Val::Null,
Self::Bool(v) => Val::Bool(v),
Self::Number(n) => Val::Num(n.as_f64().ok_or_else(|| {
- RuntimeError(format!("json number can't be represented as jsonnet: {}", n).into())
+ RuntimeError(format!("json number can't be represented as jsonnet: {n}").into())
})?),
Self::String(s) => Val::Str((&s as &str).into()),
Self::Array(a) => {
crates/jrsonnet-evaluator/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/lib.rs
+++ b/crates/jrsonnet-evaluator/src/lib.rs
@@ -594,7 +594,7 @@
.insert(name, TlaArg::String(value));
}
pub fn add_tla_code(&self, name: IStr, code: &str) -> Result<()> {
- let source_name = format!("<top-level-arg:{}>", name);
+ let source_name = format!("<top-level-arg:{name}>");
let source = Source::new_virtual(source_name.into(), code.into());
let parsed = jrsonnet_parser::parse(
code,
crates/jrsonnet-evaluator/src/obj.rsdiffbeforeafterboth1use std::{2 cell::RefCell,3 fmt::Debug,4 hash::{Hash, Hasher},5 ptr::addr_of,6};78use jrsonnet_gcmodule::{Cc, Trace, Weak};9use jrsonnet_interner::IStr;10use jrsonnet_parser::{ExprLocation, Visibility};11use rustc_hash::FxHashMap;1213use crate::{14 error::{Error::*, LocError},15 function::CallLocation,16 gc::{GcHashMap, GcHashSet, TraceBox},17 operator::evaluate_add_op,18 throw, LazyBinding, Result, State, Thunk, Unbound, Val,19};2021#[cfg(not(feature = "exp-preserve-order"))]22mod ordering {23 #![allow(24 // This module works as stub for preserve-order feature25 clippy::unused_self,26 )]2728 use jrsonnet_gcmodule::Trace;2930 #[derive(Clone, Copy, Default, Debug, Trace)]31 pub struct FieldIndex;32 impl FieldIndex {33 pub const fn next(self) -> Self {34 Self35 }36 }3738 #[derive(Clone, Copy, Default, Debug, Trace)]39 pub struct SuperDepth;40 impl SuperDepth {41 pub const fn deeper(self) -> Self {42 Self43 }44 }4546 #[derive(Clone, Copy)]47 pub struct FieldSortKey;48 impl FieldSortKey {49 pub const fn new(_: SuperDepth, _: FieldIndex) -> Self {50 Self51 }52 }53}5455#[cfg(feature = "exp-preserve-order")]56mod ordering {57 use std::cmp::Reverse;5859 use jrsonnet_gcmodule::Trace;6061 #[derive(Clone, Copy, Default, Debug, Trace, PartialEq, Eq, PartialOrd, Ord)]62 pub struct FieldIndex(u32);63 impl FieldIndex {64 pub fn next(self) -> Self {65 Self(self.0 + 1)66 }67 }6869 #[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Debug)]70 pub struct SuperDepth(u32);71 impl SuperDepth {72 pub fn deeper(self) -> Self {73 Self(self.0 + 1)74 }75 }7677 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]78 pub struct FieldSortKey(Reverse<SuperDepth>, FieldIndex);79 impl FieldSortKey {80 pub fn new(depth: SuperDepth, index: FieldIndex) -> Self {81 Self(Reverse(depth), index)82 }83 pub fn collide(self, other: Self) -> Self {84 if self.0 .0 > other.0 .0 {85 self86 } else if self.0 .0 < other.0 .0 {87 other88 } else {89 unreachable!("object can't have two fields with same name")90 }91 }92 }93}9495use ordering::*;9697#[allow(clippy::module_name_repetitions)]98#[derive(Debug, Trace)]99pub struct ObjMember {100 pub add: bool,101 pub visibility: Visibility,102 original_index: FieldIndex,103 pub invoke: LazyBinding,104 pub location: Option<ExprLocation>,105}106107pub trait ObjectAssertion: Trace {108 fn run(&self, s: State, super_obj: Option<ObjValue>, this: Option<ObjValue>) -> Result<()>;109}110111// Field => This112113#[derive(Trace)]114enum CacheValue {115 Cached(Val),116 NotFound,117 Pending,118 Errored(LocError),119}120121#[allow(clippy::module_name_repetitions)]122#[derive(Trace)]123#[trace(tracking(force))]124pub struct ObjValueInternals {125 sup: Option<ObjValue>,126 this: Option<ObjValue>,127128 assertions: Cc<Vec<TraceBox<dyn ObjectAssertion>>>,129 assertions_ran: RefCell<GcHashSet<ObjValue>>,130 this_entries: Cc<GcHashMap<IStr, ObjMember>>,131 value_cache: RefCell<GcHashMap<IStr, CacheValue>>,132}133134#[derive(Clone, Trace)]135pub struct WeakObjValue(#[trace(skip)] pub(crate) Weak<ObjValueInternals>);136137impl PartialEq for WeakObjValue {138 fn eq(&self, other: &Self) -> bool {139 Weak::ptr_eq(&self.0, &other.0)140 }141}142143impl Eq for WeakObjValue {}144impl Hash for WeakObjValue {145 fn hash<H: Hasher>(&self, hasher: &mut H) {146 // Safety: usize is POD147 let addr = unsafe { *std::ptr::addr_of!(self.0).cast() };148 hasher.write_usize(addr);149 }150}151152#[allow(clippy::module_name_repetitions)]153#[derive(Clone, Trace)]154pub struct ObjValue(pub(crate) Cc<ObjValueInternals>);155impl Debug for ObjValue {156 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {157 if let Some(super_obj) = self.0.sup.as_ref() {158 if f.alternate() {159 write!(f, "{:#?}", super_obj)?;160 } else {161 write!(f, "{:?}", super_obj)?;162 }163 write!(f, " + ")?;164 }165 let mut debug = f.debug_struct("ObjValue");166 for (name, member) in self.0.this_entries.iter() {167 debug.field(name, member);168 }169 debug.finish_non_exhaustive()170 }171}172173impl ObjValue {174 pub fn new(175 sup: Option<Self>,176 this_entries: Cc<GcHashMap<IStr, ObjMember>>,177 assertions: Cc<Vec<TraceBox<dyn ObjectAssertion>>>,178 ) -> Self {179 Self(Cc::new(ObjValueInternals {180 sup,181 this: None,182 assertions,183 assertions_ran: RefCell::new(GcHashSet::new()),184 this_entries,185 value_cache: RefCell::new(GcHashMap::new()),186 }))187 }188 pub fn new_empty() -> Self {189 Self::new(None, Cc::new(GcHashMap::new()), Cc::new(Vec::new()))190 }191 #[must_use]192 pub fn extend_from(&self, sup: Self) -> Self {193 match &self.0.sup {194 None => Self::new(195 Some(sup),196 self.0.this_entries.clone(),197 self.0.assertions.clone(),198 ),199 Some(v) => Self::new(200 Some(v.extend_from(sup)),201 self.0.this_entries.clone(),202 self.0.assertions.clone(),203 ),204 }205 }206 pub(crate) fn extend_with_raw_member(self, key: IStr, value: ObjMember) -> Self {207 let mut new = GcHashMap::with_capacity(1);208 new.insert(key, value);209 Self::new(Some(self), Cc::new(new), Cc::new(Vec::new()))210 }211 pub fn extend_field(&mut self, name: IStr) -> ObjMemberBuilder<ExtendBuilder> {212 ObjMemberBuilder::new(ExtendBuilder(self), name, FieldIndex::default())213 }214215 #[must_use]216 pub fn with_this(&self, this: Self) -> Self {217 Self(Cc::new(ObjValueInternals {218 sup: self.0.sup.clone(),219 assertions: self.0.assertions.clone(),220 assertions_ran: RefCell::new(GcHashSet::new()),221 this: Some(this),222 this_entries: self.0.this_entries.clone(),223 value_cache: RefCell::new(GcHashMap::new()),224 }))225 }226227 pub fn len(&self) -> usize {228 self.fields_visibility()229 .into_iter()230 .filter(|(_, (visible, _))| *visible)231 .count()232 }233234 pub fn is_empty(&self) -> bool {235 if !self.0.this_entries.is_empty() {236 return false;237 }238 self.0.sup.as_ref().map_or(true, Self::is_empty)239 }240241 /// Run callback for every field found in object242 pub(crate) fn enum_fields(243 &self,244 depth: SuperDepth,245 handler: &mut impl FnMut(SuperDepth, &IStr, &ObjMember) -> bool,246 ) -> bool {247 if let Some(s) = &self.0.sup {248 if s.enum_fields(depth.deeper(), handler) {249 return true;250 }251 }252 for (name, member) in self.0.this_entries.iter() {253 if handler(depth, name, member) {254 return true;255 }256 }257 false258 }259260 pub fn fields_visibility(&self) -> FxHashMap<IStr, (bool, FieldSortKey)> {261 let mut out = FxHashMap::default();262 self.enum_fields(SuperDepth::default(), &mut |depth, name, member| {263 let new_sort_key = FieldSortKey::new(depth, member.original_index);264 let entry = out.entry(name.clone());265 let (visible, _) = entry.or_insert((true, new_sort_key));266 match member.visibility {267 Visibility::Normal => {}268 Visibility::Hidden => {269 *visible = false;270 }271 Visibility::Unhide => {272 *visible = true;273 }274 };275 false276 });277 out278 }279 pub fn fields_ex(280 &self,281 include_hidden: bool,282 #[cfg(feature = "exp-preserve-order")] preserve_order: bool,283 ) -> Vec<IStr> {284 #[cfg(feature = "exp-preserve-order")]285 if preserve_order {286 let (mut fields, mut keys): (Vec<_>, Vec<_>) = self287 .fields_visibility()288 .into_iter()289 .filter(|(_, (visible, _))| include_hidden || *visible)290 .enumerate()291 .map(|(idx, (k, (_, sk)))| (k, (sk, idx)))292 .unzip();293 keys.sort_unstable_by_key(|v| v.0);294 // Reorder in-place by resulting indexes295 for i in 0..fields.len() {296 let x = fields[i].clone();297 let mut j = i;298 loop {299 let k = keys[j].1;300 keys[j].1 = j;301 if k == i {302 break;303 }304 fields[j] = fields[k].clone();305 j = k306 }307 fields[j] = x;308 }309 return fields;310 }311312 let mut fields: Vec<_> = self313 .fields_visibility()314 .into_iter()315 .filter(|(_, (visible, _))| include_hidden || *visible)316 .map(|(k, _)| k)317 .collect();318 fields.sort_unstable();319 fields320 }321 pub fn fields(&self, #[cfg(feature = "exp-preserve-order")] preserve_order: bool) -> Vec<IStr> {322 self.fields_ex(323 false,324 #[cfg(feature = "exp-preserve-order")]325 preserve_order,326 )327 }328329 pub fn field_visibility(&self, name: IStr) -> Option<Visibility> {330 if let Some(m) = self.0.this_entries.get(&name) {331 Some(match &m.visibility {332 Visibility::Normal => self333 .0334 .sup335 .as_ref()336 .and_then(|super_obj| super_obj.field_visibility(name))337 .unwrap_or(Visibility::Normal),338 v => *v,339 })340 } else if let Some(super_obj) = &self.0.sup {341 super_obj.field_visibility(name)342 } else {343 None344 }345 }346347 fn has_field_include_hidden(&self, name: IStr) -> bool {348 if self.0.this_entries.contains_key(&name) {349 true350 } else if let Some(super_obj) = &self.0.sup {351 super_obj.has_field_include_hidden(name)352 } else {353 false354 }355 }356357 pub fn has_field_ex(&self, name: IStr, include_hidden: bool) -> bool {358 if include_hidden {359 self.has_field_include_hidden(name)360 } else {361 self.has_field(name)362 }363 }364 pub fn has_field(&self, name: IStr) -> bool {365 self.field_visibility(name)366 .map_or(false, |v| v.is_visible())367 }368369 pub fn get(&self, s: State, key: IStr) -> Result<Option<Val>> {370 self.run_assertions(s.clone())?;371 if let Some(v) = self.0.value_cache.borrow().get(&key) {372 return Ok(match v {373 CacheValue::Cached(v) => Some(v.clone()),374 CacheValue::NotFound => None,375 CacheValue::Pending => throw!(InfiniteRecursionDetected),376 CacheValue::Errored(e) => return Err(e.clone()),377 });378 }379 self.0380 .value_cache381 .borrow_mut()382 .insert(key.clone(), CacheValue::Pending);383 let value = self384 .get_raw(385 s,386 key.clone(),387 self.0.this.clone().unwrap_or_else(|| self.clone()),388 )389 .map_err(|e| {390 self.0391 .value_cache392 .borrow_mut()393 .insert(key.clone(), CacheValue::Errored(e.clone()));394 e395 })?;396 self.0.value_cache.borrow_mut().insert(397 key,398 match &value {399 Some(v) => CacheValue::Cached(v.clone()),400 None => CacheValue::NotFound,401 },402 );403 Ok(value)404 }405406 fn get_raw(&self, s: State, key: IStr, real_this: Self) -> Result<Option<Val>> {407 match (self.0.this_entries.get(&key), &self.0.sup) {408 (Some(k), None) => Ok(Some(self.evaluate_this(s, k, real_this)?)),409 (Some(k), Some(super_obj)) => {410 let our = self.evaluate_this(s.clone(), k, real_this.clone())?;411 if k.add {412 super_obj413 .get_raw(s.clone(), key, real_this)?414 .map_or(Ok(Some(our.clone())), |v| {415 Ok(Some(evaluate_add_op(s.clone(), &v, &our)?))416 })417 } else {418 Ok(Some(our))419 }420 }421 (None, Some(super_obj)) => super_obj.get_raw(s, key, real_this),422 (None, None) => Ok(None),423 }424 }425 fn evaluate_this(&self, s: State, v: &ObjMember, real_this: Self) -> Result<Val> {426 v.invoke427 .evaluate(s.clone(), self.0.sup.clone(), Some(real_this))?428 .evaluate(s)429 }430431 fn run_assertions_raw(&self, s: State, real_this: &Self) -> Result<()> {432 if self.0.assertions_ran.borrow_mut().insert(real_this.clone()) {433 for assertion in self.0.assertions.iter() {434 if let Err(e) =435 assertion.run(s.clone(), self.0.sup.clone(), Some(real_this.clone()))436 {437 self.0.assertions_ran.borrow_mut().remove(real_this);438 return Err(e);439 }440 }441 if let Some(super_obj) = &self.0.sup {442 super_obj.run_assertions_raw(s, real_this)?;443 }444 }445 Ok(())446 }447 pub fn run_assertions(&self, s: State) -> Result<()> {448 self.run_assertions_raw(s, self)449 }450451 pub fn ptr_eq(a: &Self, b: &Self) -> bool {452 Cc::ptr_eq(&a.0, &b.0)453 }454 pub fn downgrade(self) -> WeakObjValue {455 WeakObjValue(self.0.downgrade())456 }457}458459impl PartialEq for ObjValue {460 fn eq(&self, other: &Self) -> bool {461 Cc::ptr_eq(&self.0, &other.0)462 }463}464465impl Eq for ObjValue {}466impl Hash for ObjValue {467 fn hash<H: Hasher>(&self, hasher: &mut H) {468 hasher.write_usize(addr_of!(*self.0) as usize);469 }470}471472#[allow(clippy::module_name_repetitions)]473pub struct ObjValueBuilder {474 sup: Option<ObjValue>,475 map: GcHashMap<IStr, ObjMember>,476 assertions: Vec<TraceBox<dyn ObjectAssertion>>,477 next_field_index: FieldIndex,478}479impl ObjValueBuilder {480 pub fn new() -> Self {481 Self::with_capacity(0)482 }483 pub fn with_capacity(capacity: usize) -> Self {484 Self {485 sup: None,486 map: GcHashMap::with_capacity(capacity),487 assertions: Vec::new(),488 next_field_index: FieldIndex::default(),489 }490 }491 pub fn reserve_asserts(&mut self, capacity: usize) -> &mut Self {492 self.assertions.reserve_exact(capacity);493 self494 }495 pub fn with_super(&mut self, super_obj: ObjValue) -> &mut Self {496 self.sup = Some(super_obj);497 self498 }499500 pub fn assert(&mut self, assertion: TraceBox<dyn ObjectAssertion>) -> &mut Self {501 self.assertions.push(assertion);502 self503 }504 pub fn member(&mut self, name: IStr) -> ObjMemberBuilder<ValueBuilder> {505 let field_index = self.next_field_index;506 self.next_field_index = self.next_field_index.next();507 ObjMemberBuilder::new(ValueBuilder(self), name, field_index)508 }509510 pub fn build(self) -> ObjValue {511 ObjValue::new(self.sup, Cc::new(self.map), Cc::new(self.assertions))512 }513}514impl Default for ObjValueBuilder {515 fn default() -> Self {516 Self::with_capacity(0)517 }518}519520#[allow(clippy::module_name_repetitions)]521#[must_use = "value not added unless binding() was called"]522pub struct ObjMemberBuilder<Kind> {523 kind: Kind,524 name: IStr,525 add: bool,526 visibility: Visibility,527 original_index: FieldIndex,528 location: Option<ExprLocation>,529}530531#[allow(clippy::missing_const_for_fn)]532impl<Kind> ObjMemberBuilder<Kind> {533 pub(crate) fn new(kind: Kind, name: IStr, original_index: FieldIndex) -> Self {534 Self {535 kind,536 name,537 original_index,538 add: false,539 visibility: Visibility::Normal,540 location: None,541 }542 }543544 pub const fn with_add(mut self, add: bool) -> Self {545 self.add = add;546 self547 }548 pub fn add(self) -> Self {549 self.with_add(true)550 }551 pub fn with_visibility(mut self, visibility: Visibility) -> Self {552 self.visibility = visibility;553 self554 }555 pub fn hide(self) -> Self {556 self.with_visibility(Visibility::Hidden)557 }558 pub fn with_location(mut self, location: ExprLocation) -> Self {559 self.location = Some(location);560 self561 }562 fn build_member(self, binding: LazyBinding) -> (Kind, IStr, ObjMember) {563 (564 self.kind,565 self.name,566 ObjMember {567 add: self.add,568 visibility: self.visibility,569 original_index: self.original_index,570 invoke: binding,571 location: self.location,572 },573 )574 }575}576577pub struct ValueBuilder<'v>(&'v mut ObjValueBuilder);578impl<'v> ObjMemberBuilder<ValueBuilder<'v>> {579 pub fn value(self, s: State, value: Val) -> Result<()> {580 self.binding(s, LazyBinding::Bound(Thunk::evaluated(value)))581 }582 pub fn bindable(583 self,584 s: State,585 bindable: TraceBox<dyn Unbound<Bound = Thunk<Val>>>,586 ) -> Result<()> {587 self.binding(s, LazyBinding::Bindable(Cc::new(bindable)))588 }589 pub fn binding(self, s: State, binding: LazyBinding) -> Result<()> {590 let (receiver, name, member) = self.build_member(binding);591 let location = member.location.clone();592 let old = receiver.0.map.insert(name.clone(), member);593 if old.is_some() {594 s.push(595 CallLocation(location.as_ref()),596 || format!("field <{}> initializtion", name.clone()),597 || throw!(DuplicateFieldName(name.clone())),598 )?;599 }600 Ok(())601 }602}603604pub struct ExtendBuilder<'v>(&'v mut ObjValue);605impl<'v> ObjMemberBuilder<ExtendBuilder<'v>> {606 pub fn value(self, value: Val) {607 self.binding(LazyBinding::Bound(Thunk::evaluated(value)));608 }609 pub fn bindable(self, bindable: TraceBox<dyn Unbound<Bound = Thunk<Val>>>) {610 self.binding(LazyBinding::Bindable(Cc::new(bindable)));611 }612 pub fn binding(self, binding: LazyBinding) {613 let (receiver, name, member) = self.build_member(binding);614 let new = receiver.0.clone();615 *receiver.0 = new.extend_with_raw_member(name, member);616 }617}1use std::{2 cell::RefCell,3 fmt::Debug,4 hash::{Hash, Hasher},5 ptr::addr_of,6};78use jrsonnet_gcmodule::{Cc, Trace, Weak};9use jrsonnet_interner::IStr;10use jrsonnet_parser::{ExprLocation, Visibility};11use rustc_hash::FxHashMap;1213use crate::{14 error::{Error::*, LocError},15 function::CallLocation,16 gc::{GcHashMap, GcHashSet, TraceBox},17 operator::evaluate_add_op,18 throw, LazyBinding, Result, State, Thunk, Unbound, Val,19};2021#[cfg(not(feature = "exp-preserve-order"))]22mod ordering {23 #![allow(24 // This module works as stub for preserve-order feature25 clippy::unused_self,26 )]2728 use jrsonnet_gcmodule::Trace;2930 #[derive(Clone, Copy, Default, Debug, Trace)]31 pub struct FieldIndex;32 impl FieldIndex {33 pub const fn next(self) -> Self {34 Self35 }36 }3738 #[derive(Clone, Copy, Default, Debug, Trace)]39 pub struct SuperDepth;40 impl SuperDepth {41 pub const fn deeper(self) -> Self {42 Self43 }44 }4546 #[derive(Clone, Copy)]47 pub struct FieldSortKey;48 impl FieldSortKey {49 pub const fn new(_: SuperDepth, _: FieldIndex) -> Self {50 Self51 }52 }53}5455#[cfg(feature = "exp-preserve-order")]56mod ordering {57 use std::cmp::Reverse;5859 use jrsonnet_gcmodule::Trace;6061 #[derive(Clone, Copy, Default, Debug, Trace, PartialEq, Eq, PartialOrd, Ord)]62 pub struct FieldIndex(u32);63 impl FieldIndex {64 pub fn next(self) -> Self {65 Self(self.0 + 1)66 }67 }6869 #[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Debug)]70 pub struct SuperDepth(u32);71 impl SuperDepth {72 pub fn deeper(self) -> Self {73 Self(self.0 + 1)74 }75 }7677 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]78 pub struct FieldSortKey(Reverse<SuperDepth>, FieldIndex);79 impl FieldSortKey {80 pub fn new(depth: SuperDepth, index: FieldIndex) -> Self {81 Self(Reverse(depth), index)82 }83 pub fn collide(self, other: Self) -> Self {84 if self.0 .0 > other.0 .0 {85 self86 } else if self.0 .0 < other.0 .0 {87 other88 } else {89 unreachable!("object can't have two fields with same name")90 }91 }92 }93}9495use ordering::*;9697#[allow(clippy::module_name_repetitions)]98#[derive(Debug, Trace)]99pub struct ObjMember {100 pub add: bool,101 pub visibility: Visibility,102 original_index: FieldIndex,103 pub invoke: LazyBinding,104 pub location: Option<ExprLocation>,105}106107pub trait ObjectAssertion: Trace {108 fn run(&self, s: State, super_obj: Option<ObjValue>, this: Option<ObjValue>) -> Result<()>;109}110111// Field => This112113#[derive(Trace)]114enum CacheValue {115 Cached(Val),116 NotFound,117 Pending,118 Errored(LocError),119}120121#[allow(clippy::module_name_repetitions)]122#[derive(Trace)]123#[trace(tracking(force))]124pub struct ObjValueInternals {125 sup: Option<ObjValue>,126 this: Option<ObjValue>,127128 assertions: Cc<Vec<TraceBox<dyn ObjectAssertion>>>,129 assertions_ran: RefCell<GcHashSet<ObjValue>>,130 this_entries: Cc<GcHashMap<IStr, ObjMember>>,131 value_cache: RefCell<GcHashMap<IStr, CacheValue>>,132}133134#[derive(Clone, Trace)]135pub struct WeakObjValue(#[trace(skip)] pub(crate) Weak<ObjValueInternals>);136137impl PartialEq for WeakObjValue {138 fn eq(&self, other: &Self) -> bool {139 Weak::ptr_eq(&self.0, &other.0)140 }141}142143impl Eq for WeakObjValue {}144impl Hash for WeakObjValue {145 fn hash<H: Hasher>(&self, hasher: &mut H) {146 // Safety: usize is POD147 let addr = unsafe { *std::ptr::addr_of!(self.0).cast() };148 hasher.write_usize(addr);149 }150}151152#[allow(clippy::module_name_repetitions)]153#[derive(Clone, Trace)]154pub struct ObjValue(pub(crate) Cc<ObjValueInternals>);155impl Debug for ObjValue {156 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {157 if let Some(super_obj) = self.0.sup.as_ref() {158 if f.alternate() {159 write!(f, "{super_obj:#?}")?;160 } else {161 write!(f, "{super_obj:?}")?;162 }163 write!(f, " + ")?;164 }165 let mut debug = f.debug_struct("ObjValue");166 for (name, member) in self.0.this_entries.iter() {167 debug.field(name, member);168 }169 debug.finish_non_exhaustive()170 }171}172173impl ObjValue {174 pub fn new(175 sup: Option<Self>,176 this_entries: Cc<GcHashMap<IStr, ObjMember>>,177 assertions: Cc<Vec<TraceBox<dyn ObjectAssertion>>>,178 ) -> Self {179 Self(Cc::new(ObjValueInternals {180 sup,181 this: None,182 assertions,183 assertions_ran: RefCell::new(GcHashSet::new()),184 this_entries,185 value_cache: RefCell::new(GcHashMap::new()),186 }))187 }188 pub fn new_empty() -> Self {189 Self::new(None, Cc::new(GcHashMap::new()), Cc::new(Vec::new()))190 }191 #[must_use]192 pub fn extend_from(&self, sup: Self) -> Self {193 match &self.0.sup {194 None => Self::new(195 Some(sup),196 self.0.this_entries.clone(),197 self.0.assertions.clone(),198 ),199 Some(v) => Self::new(200 Some(v.extend_from(sup)),201 self.0.this_entries.clone(),202 self.0.assertions.clone(),203 ),204 }205 }206 pub(crate) fn extend_with_raw_member(self, key: IStr, value: ObjMember) -> Self {207 let mut new = GcHashMap::with_capacity(1);208 new.insert(key, value);209 Self::new(Some(self), Cc::new(new), Cc::new(Vec::new()))210 }211 pub fn extend_field(&mut self, name: IStr) -> ObjMemberBuilder<ExtendBuilder> {212 ObjMemberBuilder::new(ExtendBuilder(self), name, FieldIndex::default())213 }214215 #[must_use]216 pub fn with_this(&self, this: Self) -> Self {217 Self(Cc::new(ObjValueInternals {218 sup: self.0.sup.clone(),219 assertions: self.0.assertions.clone(),220 assertions_ran: RefCell::new(GcHashSet::new()),221 this: Some(this),222 this_entries: self.0.this_entries.clone(),223 value_cache: RefCell::new(GcHashMap::new()),224 }))225 }226227 pub fn len(&self) -> usize {228 self.fields_visibility()229 .into_iter()230 .filter(|(_, (visible, _))| *visible)231 .count()232 }233234 pub fn is_empty(&self) -> bool {235 if !self.0.this_entries.is_empty() {236 return false;237 }238 self.0.sup.as_ref().map_or(true, Self::is_empty)239 }240241 /// Run callback for every field found in object242 pub(crate) fn enum_fields(243 &self,244 depth: SuperDepth,245 handler: &mut impl FnMut(SuperDepth, &IStr, &ObjMember) -> bool,246 ) -> bool {247 if let Some(s) = &self.0.sup {248 if s.enum_fields(depth.deeper(), handler) {249 return true;250 }251 }252 for (name, member) in self.0.this_entries.iter() {253 if handler(depth, name, member) {254 return true;255 }256 }257 false258 }259260 pub fn fields_visibility(&self) -> FxHashMap<IStr, (bool, FieldSortKey)> {261 let mut out = FxHashMap::default();262 self.enum_fields(SuperDepth::default(), &mut |depth, name, member| {263 let new_sort_key = FieldSortKey::new(depth, member.original_index);264 let entry = out.entry(name.clone());265 let (visible, _) = entry.or_insert((true, new_sort_key));266 match member.visibility {267 Visibility::Normal => {}268 Visibility::Hidden => {269 *visible = false;270 }271 Visibility::Unhide => {272 *visible = true;273 }274 };275 false276 });277 out278 }279 pub fn fields_ex(280 &self,281 include_hidden: bool,282 #[cfg(feature = "exp-preserve-order")] preserve_order: bool,283 ) -> Vec<IStr> {284 #[cfg(feature = "exp-preserve-order")]285 if preserve_order {286 let (mut fields, mut keys): (Vec<_>, Vec<_>) = self287 .fields_visibility()288 .into_iter()289 .filter(|(_, (visible, _))| include_hidden || *visible)290 .enumerate()291 .map(|(idx, (k, (_, sk)))| (k, (sk, idx)))292 .unzip();293 keys.sort_unstable_by_key(|v| v.0);294 // Reorder in-place by resulting indexes295 for i in 0..fields.len() {296 let x = fields[i].clone();297 let mut j = i;298 loop {299 let k = keys[j].1;300 keys[j].1 = j;301 if k == i {302 break;303 }304 fields[j] = fields[k].clone();305 j = k306 }307 fields[j] = x;308 }309 return fields;310 }311312 let mut fields: Vec<_> = self313 .fields_visibility()314 .into_iter()315 .filter(|(_, (visible, _))| include_hidden || *visible)316 .map(|(k, _)| k)317 .collect();318 fields.sort_unstable();319 fields320 }321 pub fn fields(&self, #[cfg(feature = "exp-preserve-order")] preserve_order: bool) -> Vec<IStr> {322 self.fields_ex(323 false,324 #[cfg(feature = "exp-preserve-order")]325 preserve_order,326 )327 }328329 pub fn field_visibility(&self, name: IStr) -> Option<Visibility> {330 if let Some(m) = self.0.this_entries.get(&name) {331 Some(match &m.visibility {332 Visibility::Normal => self333 .0334 .sup335 .as_ref()336 .and_then(|super_obj| super_obj.field_visibility(name))337 .unwrap_or(Visibility::Normal),338 v => *v,339 })340 } else if let Some(super_obj) = &self.0.sup {341 super_obj.field_visibility(name)342 } else {343 None344 }345 }346347 fn has_field_include_hidden(&self, name: IStr) -> bool {348 if self.0.this_entries.contains_key(&name) {349 true350 } else if let Some(super_obj) = &self.0.sup {351 super_obj.has_field_include_hidden(name)352 } else {353 false354 }355 }356357 pub fn has_field_ex(&self, name: IStr, include_hidden: bool) -> bool {358 if include_hidden {359 self.has_field_include_hidden(name)360 } else {361 self.has_field(name)362 }363 }364 pub fn has_field(&self, name: IStr) -> bool {365 self.field_visibility(name)366 .map_or(false, |v| v.is_visible())367 }368369 pub fn get(&self, s: State, key: IStr) -> Result<Option<Val>> {370 self.run_assertions(s.clone())?;371 if let Some(v) = self.0.value_cache.borrow().get(&key) {372 return Ok(match v {373 CacheValue::Cached(v) => Some(v.clone()),374 CacheValue::NotFound => None,375 CacheValue::Pending => throw!(InfiniteRecursionDetected),376 CacheValue::Errored(e) => return Err(e.clone()),377 });378 }379 self.0380 .value_cache381 .borrow_mut()382 .insert(key.clone(), CacheValue::Pending);383 let value = self384 .get_raw(385 s,386 key.clone(),387 self.0.this.clone().unwrap_or_else(|| self.clone()),388 )389 .map_err(|e| {390 self.0391 .value_cache392 .borrow_mut()393 .insert(key.clone(), CacheValue::Errored(e.clone()));394 e395 })?;396 self.0.value_cache.borrow_mut().insert(397 key,398 value399 .as_ref()400 .map_or(CacheValue::NotFound, |v| CacheValue::Cached(v.clone())),401 );402 Ok(value)403 }404405 fn get_raw(&self, s: State, key: IStr, real_this: Self) -> Result<Option<Val>> {406 match (self.0.this_entries.get(&key), &self.0.sup) {407 (Some(k), None) => Ok(Some(self.evaluate_this(s, k, real_this)?)),408 (Some(k), Some(super_obj)) => {409 let our = self.evaluate_this(s.clone(), k, real_this.clone())?;410 if k.add {411 super_obj412 .get_raw(s.clone(), key, real_this)?413 .map_or(Ok(Some(our.clone())), |v| {414 Ok(Some(evaluate_add_op(s.clone(), &v, &our)?))415 })416 } else {417 Ok(Some(our))418 }419 }420 (None, Some(super_obj)) => super_obj.get_raw(s, key, real_this),421 (None, None) => Ok(None),422 }423 }424 fn evaluate_this(&self, s: State, v: &ObjMember, real_this: Self) -> Result<Val> {425 v.invoke426 .evaluate(s.clone(), self.0.sup.clone(), Some(real_this))?427 .evaluate(s)428 }429430 fn run_assertions_raw(&self, s: State, real_this: &Self) -> Result<()> {431 if self.0.assertions_ran.borrow_mut().insert(real_this.clone()) {432 for assertion in self.0.assertions.iter() {433 if let Err(e) =434 assertion.run(s.clone(), self.0.sup.clone(), Some(real_this.clone()))435 {436 self.0.assertions_ran.borrow_mut().remove(real_this);437 return Err(e);438 }439 }440 if let Some(super_obj) = &self.0.sup {441 super_obj.run_assertions_raw(s, real_this)?;442 }443 }444 Ok(())445 }446 pub fn run_assertions(&self, s: State) -> Result<()> {447 self.run_assertions_raw(s, self)448 }449450 pub fn ptr_eq(a: &Self, b: &Self) -> bool {451 Cc::ptr_eq(&a.0, &b.0)452 }453 pub fn downgrade(self) -> WeakObjValue {454 WeakObjValue(self.0.downgrade())455 }456}457458impl PartialEq for ObjValue {459 fn eq(&self, other: &Self) -> bool {460 Cc::ptr_eq(&self.0, &other.0)461 }462}463464impl Eq for ObjValue {}465impl Hash for ObjValue {466 fn hash<H: Hasher>(&self, hasher: &mut H) {467 hasher.write_usize(addr_of!(*self.0) as usize);468 }469}470471#[allow(clippy::module_name_repetitions)]472pub struct ObjValueBuilder {473 sup: Option<ObjValue>,474 map: GcHashMap<IStr, ObjMember>,475 assertions: Vec<TraceBox<dyn ObjectAssertion>>,476 next_field_index: FieldIndex,477}478impl ObjValueBuilder {479 pub fn new() -> Self {480 Self::with_capacity(0)481 }482 pub fn with_capacity(capacity: usize) -> Self {483 Self {484 sup: None,485 map: GcHashMap::with_capacity(capacity),486 assertions: Vec::new(),487 next_field_index: FieldIndex::default(),488 }489 }490 pub fn reserve_asserts(&mut self, capacity: usize) -> &mut Self {491 self.assertions.reserve_exact(capacity);492 self493 }494 pub fn with_super(&mut self, super_obj: ObjValue) -> &mut Self {495 self.sup = Some(super_obj);496 self497 }498499 pub fn assert(&mut self, assertion: TraceBox<dyn ObjectAssertion>) -> &mut Self {500 self.assertions.push(assertion);501 self502 }503 pub fn member(&mut self, name: IStr) -> ObjMemberBuilder<ValueBuilder> {504 let field_index = self.next_field_index;505 self.next_field_index = self.next_field_index.next();506 ObjMemberBuilder::new(ValueBuilder(self), name, field_index)507 }508509 pub fn build(self) -> ObjValue {510 ObjValue::new(self.sup, Cc::new(self.map), Cc::new(self.assertions))511 }512}513impl Default for ObjValueBuilder {514 fn default() -> Self {515 Self::with_capacity(0)516 }517}518519#[allow(clippy::module_name_repetitions)]520#[must_use = "value not added unless binding() was called"]521pub struct ObjMemberBuilder<Kind> {522 kind: Kind,523 name: IStr,524 add: bool,525 visibility: Visibility,526 original_index: FieldIndex,527 location: Option<ExprLocation>,528}529530#[allow(clippy::missing_const_for_fn)]531impl<Kind> ObjMemberBuilder<Kind> {532 pub(crate) fn new(kind: Kind, name: IStr, original_index: FieldIndex) -> Self {533 Self {534 kind,535 name,536 original_index,537 add: false,538 visibility: Visibility::Normal,539 location: None,540 }541 }542543 pub const fn with_add(mut self, add: bool) -> Self {544 self.add = add;545 self546 }547 pub fn add(self) -> Self {548 self.with_add(true)549 }550 pub fn with_visibility(mut self, visibility: Visibility) -> Self {551 self.visibility = visibility;552 self553 }554 pub fn hide(self) -> Self {555 self.with_visibility(Visibility::Hidden)556 }557 pub fn with_location(mut self, location: ExprLocation) -> Self {558 self.location = Some(location);559 self560 }561 fn build_member(self, binding: LazyBinding) -> (Kind, IStr, ObjMember) {562 (563 self.kind,564 self.name,565 ObjMember {566 add: self.add,567 visibility: self.visibility,568 original_index: self.original_index,569 invoke: binding,570 location: self.location,571 },572 )573 }574}575576pub struct ValueBuilder<'v>(&'v mut ObjValueBuilder);577impl<'v> ObjMemberBuilder<ValueBuilder<'v>> {578 pub fn value(self, s: State, value: Val) -> Result<()> {579 self.binding(s, LazyBinding::Bound(Thunk::evaluated(value)))580 }581 pub fn bindable(582 self,583 s: State,584 bindable: TraceBox<dyn Unbound<Bound = Thunk<Val>>>,585 ) -> Result<()> {586 self.binding(s, LazyBinding::Bindable(Cc::new(bindable)))587 }588 pub fn binding(self, s: State, binding: LazyBinding) -> Result<()> {589 let (receiver, name, member) = self.build_member(binding);590 let location = member.location.clone();591 let old = receiver.0.map.insert(name.clone(), member);592 if old.is_some() {593 s.push(594 CallLocation(location.as_ref()),595 || format!("field <{}> initializtion", name.clone()),596 || throw!(DuplicateFieldName(name.clone())),597 )?;598 }599 Ok(())600 }601}602603pub struct ExtendBuilder<'v>(&'v mut ObjValue);604impl<'v> ObjMemberBuilder<ExtendBuilder<'v>> {605 pub fn value(self, value: Val) {606 self.binding(LazyBinding::Bound(Thunk::evaluated(value)));607 }608 pub fn bindable(self, bindable: TraceBox<dyn Unbound<Bound = Thunk<Val>>>) {609 self.binding(LazyBinding::Bindable(Cc::new(bindable)));610 }611 pub fn binding(self, binding: LazyBinding) {612 let (receiver, name, member) = self.build_member(binding);613 let new = receiver.0.clone();614 *receiver.0 = new.extend_with_raw_member(name, member);615 }616}crates/jrsonnet-evaluator/src/stdlib/format.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/stdlib/format.rs
+++ b/crates/jrsonnet-evaluator/src/stdlib/format.rs
@@ -45,7 +45,7 @@
let mut i = 1;
while i < bytes.len() {
if bytes[i] == b')' {
- return Ok((&str[1..i as usize], &str[i as usize + 1..]));
+ return Ok((&str[1..i], &str[i + 1..]));
}
i += 1;
}
@@ -310,6 +310,7 @@
nums
};
let neg = iv < 0.0;
+ #[allow(clippy::bool_to_int_with_if)]
let zp = padding.saturating_sub(if neg || blank || sign { 1 } else { 0 });
let zp2 = zp
.max(precision)
@@ -406,6 +407,7 @@
ensure_pt: bool,
trailing: bool,
) {
+ #[allow(clippy::bool_to_int_with_if)]
let dot_size = if precision == 0 && !ensure_pt { 0 } else { 1 };
padding = padding.saturating_sub(dot_size + precision);
render_decimal(out, n.floor(), padding, 0, blank, sign);
@@ -478,10 +480,7 @@
precision: Option<usize>,
) -> Result<()> {
let clfags = &code.cflags;
- let (fpprec, iprec) = match precision {
- Some(v) => (v, v),
- None => (6, 0),
- };
+ let (fpprec, iprec) = precision.map_or((6, 0), |v| (v, v));
let padding = if clfags.zero && !clfags.left {
width
} else {
@@ -586,8 +585,10 @@
}
}
ConvTypeV::Char => match value.clone() {
- Val::Num(n) => tmp_out
- .push(std::char::from_u32(n as u32).ok_or(InvalidUnicodeCodepointGot(n as u32))?),
+ Val::Num(n) => tmp_out.push(
+ std::char::from_u32(n as u32)
+ .ok_or_else(|| InvalidUnicodeCodepointGot(n as u32))?,
+ ),
Val::Str(s) => {
if s.chars().count() != 1 {
throw!(RuntimeError(
crates/jrsonnet-evaluator/src/stdlib/manifest.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/stdlib/manifest.rs
+++ b/crates/jrsonnet-evaluator/src/stdlib/manifest.rs
@@ -49,7 +49,7 @@
}
Val::Null => buf.push_str("null"),
Val::Str(s) => escape_string_json_buf(s, buf),
- Val::Num(n) => write!(buf, "{}", n).unwrap(),
+ Val::Num(n) => write!(buf, "{n}").unwrap(),
Val::Arr(items) => {
buf.push('[');
if !items.is_empty() {
crates/jrsonnet-evaluator/src/stdlib/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/stdlib/mod.rs
+++ b/crates/jrsonnet-evaluator/src/stdlib/mod.rs
@@ -12,7 +12,7 @@
pub fn std_format(s: State, str: IStr, vals: Val) -> Result<String> {
s.push(
CallLocation::native(),
- || format!("std.format of {}", str),
+ || format!("std.format of {str}"),
|| {
Ok(match vals {
Val::Arr(vals) => format_arr(s.clone(), &str, &vals.evaluated(s.clone())?)?,
crates/jrsonnet-evaluator/src/trace/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/trace/mod.rs
+++ b/crates/jrsonnet-evaluator/src/trace/mod.rs
@@ -16,12 +16,9 @@
}
impl PathResolver {
- /// Will return Self::Relative(cwd), or Self::Absolute on cwd failure
+ /// Will return `Self::Relative(cwd)`, or `Self::Absolute` on cwd failure
pub fn new_cwd_fallback() -> Self {
- match std::env::current_dir() {
- Ok(v) => Self::Relative(v),
- Err(_) => Self::Absolute,
- }
+ std::env::current_dir().map_or(Self::Absolute, Self::Relative)
}
pub fn resolve(&self, from: &Path) -> String {
match self {
@@ -97,10 +94,10 @@
use std::fmt::Write;
writeln!(out)?;
- let mut n = match path.source_path().path() {
- Some(r) => self.resolver.resolve(r),
- None => path.source_path().to_string(),
- };
+ let mut n = path.source_path().path().map_or_else(
+ || path.source_path().to_string(),
+ |r| self.resolver.resolve(r),
+ );
let mut offset = error.location.offset;
let is_eof = if offset >= path.code().len() {
offset = path.code().len().saturating_sub(1);
@@ -119,7 +116,7 @@
write!(n, ":").unwrap();
print_code_location(&mut n, &location, &location).unwrap();
- write!(out, "{:<p$}{}", "", n, p = self.padding,)?;
+ write!(out, "{:<p$}{n}", "", p = self.padding)?;
}
let file_names = error
.trace()
@@ -185,10 +182,10 @@
let desc = &item.desc;
if let Some(source) = &item.location {
let start_end = source.0.map_source_locations(&[source.1, source.2]);
- let resolved_path = match source.0.source_path().path() {
- Some(r) => r.display().to_string(),
- None => source.0.source_path().to_string(),
- };
+ let resolved_path = source.0.source_path().path().map_or_else(
+ || source.0.source_path().to_string(),
+ |r| r.display().to_string(),
+ );
write!(
out,
@@ -196,7 +193,7 @@
desc, resolved_path, start_end[0].line, start_end[0].column,
)?;
} else {
- write!(out, " during {}", desc)?;
+ write!(out, " during {desc}")?;
}
}
Ok(())
@@ -252,7 +249,7 @@
desc,
)?;
} else {
- write!(out, "{}", desc)?;
+ write!(out, "{desc}")?;
}
}
Ok(())
@@ -280,10 +277,10 @@
.take(end.line_end_offset - end.line_start_offset)
.collect();
- let origin = match origin.source_path().path() {
- Some(r) => self.resolver.resolve(r),
- None => origin.source_path().to_string(),
- };
+ let origin = origin.source_path().path().map_or_else(
+ || origin.source_path().to_string(),
+ |r| self.resolver.resolve(r),
+ );
let snippet = Snippet {
opt: FormatOptions {
color: true,
@@ -308,7 +305,7 @@
};
let dl = DisplayList::from(snippet);
- write!(out, "{}", dl)?;
+ write!(out, "{dl}")?;
Ok(())
}
crates/jrsonnet-evaluator/src/typed/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/typed/mod.rs
+++ b/crates/jrsonnet-evaluator/src/typed/mod.rs
@@ -21,8 +21,8 @@
UnionFailed(ComplexValType, TypeLocErrorList),
#[error(
"number out of bounds: {0} not in {}..{}",
- .1.map(|v|v.to_string()).unwrap_or_else(|| "".to_owned()),
- .2.map(|v|v.to_string()).unwrap_or_else(|| "".to_owned()),
+ .1.map(|v|v.to_string()).unwrap_or_default(),
+ .2.map(|v|v.to_string()).unwrap_or_default(),
)]
BoundsFailed(f64, Option<f64>, Option<f64>),
}
@@ -65,7 +65,7 @@
writeln!(f)?;
}
out.clear();
- write!(out, "{}", err)?;
+ write!(out, "{err}")?;
for (i, line) in out.lines().enumerate() {
if line.trim().is_empty() {
@@ -77,7 +77,7 @@
writeln!(f)?;
write!(f, " ")?;
}
- write!(f, "{}", line)?;
+ write!(f, "{line}")?;
}
}
Ok(())
@@ -125,8 +125,8 @@
impl Display for ValuePathItem {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
- Self::Field(name) => write!(f, ".{:?}", name)?,
- Self::Index(idx) => write!(f, "[{}]", idx)?,
+ Self::Field(name) => write!(f, ".{name:?}")?,
+ Self::Index(idx) => write!(f, "[{idx}]")?,
}
Ok(())
}
@@ -138,7 +138,7 @@
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "self")?;
for elem in self.0.iter().rev() {
- write!(f, "{}", elem)?;
+ write!(f, "{elem}")?;
}
Ok(())
}
@@ -171,7 +171,7 @@
for (i, item) in a.iter(s.clone()).enumerate() {
push_type_description(
s.clone(),
- || format!("array index {}", i),
+ || format!("array index {i}"),
|| ValuePathItem::Index(i as u64),
|| elem_type.check(s.clone(), &item.clone()?),
)?;
@@ -185,7 +185,7 @@
for (i, item) in a.iter(s.clone()).enumerate() {
push_type_description(
s.clone(),
- || format!("array index {}", i),
+ || format!("array index {i}"),
|| ValuePathItem::Index(i as u64),
|| elem_type.check(s.clone(), &item.clone()?),
)?;
@@ -200,7 +200,7 @@
if let Some(got_v) = obj.get(s.clone(), (*k).into())? {
push_type_description(
s.clone(),
- || format!("property {}", k),
+ || format!("property {k}"),
|| ValuePathItem::Field((*k).into()),
|| v.check(s.clone(), &got_v),
)?;
crates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/val.rs
+++ b/crates/jrsonnet-evaluator/src/val.rs
@@ -292,7 +292,7 @@
if index >= v.to() {
return Ok(None);
}
- v.inner.get(s, index as usize)
+ v.inner.get(s, index)
}
}
}
@@ -332,7 +332,7 @@
if index >= s.to() {
return None;
}
- s.inner.get_lazy(index as usize)
+ s.inner.get_lazy(index)
}
}
}
@@ -531,8 +531,9 @@
}
}
-#[cfg(target_pointer_width = "64")]
-static_assertions::assert_eq_size!(Val, [u8; 32]);
+// Broken between stable and nightly, as there is new layout size optimization
+// #[cfg(target_pointer_width = "64")]
+// static_assertions::assert_eq_size!(Val, [u8; 24]);
impl Val {
pub const fn as_bool(&self) -> Option<bool> {
crates/jrsonnet-stdlib/src/encoding.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/encoding.rs
+++ b/crates/jrsonnet-stdlib/src/encoding.rs
@@ -28,7 +28,7 @@
#[builtin]
pub fn builtin_base64_decode_bytes(input: IStr) -> Result<IBytes> {
- Ok(base64::decode(&input.as_bytes())
+ Ok(base64::decode(input.as_bytes())
.map_err(|_| RuntimeError("bad base64".into()))?
.as_slice()
.into())
@@ -36,6 +36,6 @@
#[builtin]
pub fn builtin_base64_decode(input: IStr) -> Result<String> {
- let bytes = base64::decode(&input.as_bytes()).map_err(|_| RuntimeError("bad base64".into()))?;
+ let bytes = base64::decode(input.as_bytes()).map_err(|_| RuntimeError("bad base64".into()))?;
Ok(String::from_utf8(bytes).map_err(|_| RuntimeError("bad utf8".into()))?)
}
crates/jrsonnet-stdlib/src/hash.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/hash.rs
+++ b/crates/jrsonnet-stdlib/src/hash.rs
@@ -2,5 +2,5 @@
#[builtin]
pub fn builtin_md5(str: IStr) -> Result<String> {
- Ok(format!("{:x}", md5::compute(&str.as_bytes())))
+ Ok(format!("{:x}", md5::compute(str.as_bytes())))
}
crates/jrsonnet-stdlib/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/lib.rs
+++ b/crates/jrsonnet-stdlib/src/lib.rs
@@ -366,7 +366,7 @@
#[builtin]
fn builtin_substr(str: IStr, from: usize, len: usize) -> Result<String> {
- Ok(str.chars().skip(from as usize).take(len as usize).collect())
+ Ok(str.chars().skip(from).take(len).collect())
}
#[builtin(fields(
@@ -380,7 +380,7 @@
.ext_vars
.get(&x)
.cloned()
- .ok_or(UndefinedExternalVariable(x))?
+ .ok_or_else(|| UndefinedExternalVariable(x))?
.evaluate_arg(s.clone(), ctx, true)?
.evaluate(s)?))
}
@@ -402,7 +402,7 @@
#[builtin]
fn builtin_char(n: u32) -> Result<char> {
- Ok(std::char::from_u32(n as u32).ok_or(InvalidUnicodeCodepointGot(n as u32))?)
+ Ok(std::char::from_u32(n).ok_or_else(|| InvalidUnicodeCodepointGot(n))?)
}
#[builtin(fields(