difftreelog
refactor fix clippy warnings
in: master
27 files changed
Cargo.tomldiffbeforeafterboth--- a/Cargo.toml
+++ b/Cargo.toml
@@ -150,6 +150,9 @@
redundant_pub_crate = "allow"
# Sometimes code is fancier without that
manual_let_else = "allow"
+# Something is broken about that lint, can't be allowed for
+# codegenerated-stdlib block
+similar_names = "allow"
#[profile.test]
#opt-level = 1
cmds/jrsonnet-fmt/src/tests.rsdiffbeforeafterboth--- a/cmds/jrsonnet-fmt/src/tests.rs
+++ b/cmds/jrsonnet-fmt/src/tests.rs
@@ -1,4 +1,4 @@
-use dprint_core::formatting::{PrintOptions, PrintItems};
+use dprint_core::formatting::{PrintItems, PrintOptions};
use indoc::indoc;
use crate::Printable;
cmds/jrsonnet/src/main.rsdiffbeforeafterboth--- a/cmds/jrsonnet/src/main.rs
+++ b/cmds/jrsonnet/src/main.rs
@@ -153,7 +153,7 @@
if let Error::Evaluation(e) = e {
let mut out = String::new();
trace.write_trace(&mut out, &e).expect("format error");
- eprintln!("{out}")
+ eprintln!("{out}");
} else {
eprintln!("{e}");
}
crates/jrsonnet-cli/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-cli/src/lib.rs
+++ b/crates/jrsonnet-cli/src/lib.rs
@@ -10,7 +10,7 @@
stack::{limit_stack_depth, StackDepthLimitOverrideGuard},
FileImportResolver,
};
-use jrsonnet_gcmodule::with_thread_object_space;
+use jrsonnet_gcmodule::{with_thread_object_space, ObjectSpace};
pub use manifest::*;
pub use stdlib::*;
pub use tla::*;
@@ -88,7 +88,7 @@
impl Drop for LeakSpace {
fn drop(&mut self) {
- with_thread_object_space(|s| s.leak())
+ with_thread_object_space(ObjectSpace::leak);
}
}
@@ -102,6 +102,6 @@
let collected = jrsonnet_gcmodule::collect_thread_cycles();
eprintln!("Collected: {collected}");
}
- eprintln!("Tracked: {}", jrsonnet_gcmodule::count_thread_tracked())
+ eprintln!("Tracked: {}", jrsonnet_gcmodule::count_thread_tracked());
}
}
crates/jrsonnet-cli/src/stdlib.rsdiffbeforeafterboth--- a/crates/jrsonnet-cli/src/stdlib.rs
+++ b/crates/jrsonnet-cli/src/stdlib.rs
@@ -39,11 +39,11 @@
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
match s.find('=') {
- Some(idx) => Ok(ExtStr {
+ Some(idx) => Ok(Self {
name: s[..idx].to_owned(),
value: s[idx + 1..].to_owned(),
}),
- None => Ok(ExtStr {
+ None => Ok(Self {
name: s.to_owned(),
value: std::env::var(s).or(Err("missing env var"))?,
}),
@@ -109,16 +109,16 @@
return Ok(None);
}
let ctx = ContextInitializer::new(s.clone(), PathResolver::new_cwd_fallback());
- for ext in self.ext_str.iter() {
+ for ext in &self.ext_str {
ctx.add_ext_str((&ext.name as &str).into(), (&ext.value as &str).into());
}
- for ext in self.ext_str_file.iter() {
+ for ext in &self.ext_str_file {
ctx.add_ext_str((&ext.name as &str).into(), (&ext.value as &str).into());
}
- for ext in self.ext_code.iter() {
+ for ext in &self.ext_code {
ctx.add_ext_code(&ext.name as &str, &ext.value as &str)?;
}
- for ext in self.ext_code_file.iter() {
+ for ext in &self.ext_code_file {
ctx.add_ext_code(&ext.name as &str, &ext.value as &str)?;
}
Ok(Some(ctx))
crates/jrsonnet-evaluator/src/arr/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/arr/mod.rs
+++ b/crates/jrsonnet-evaluator/src/arr/mod.rs
@@ -42,7 +42,7 @@
Self::new(EagerArray(values))
}
- pub fn repeated(data: ArrValue, repeats: usize) -> Option<Self> {
+ pub fn repeated(data: Self, repeats: usize) -> Option<Self> {
Some(Self::new(RepeatedArray::new(data, repeats)?))
}
@@ -70,7 +70,7 @@
Ok(Self::eager(out))
}
- pub fn extended(a: ArrValue, b: ArrValue) -> Self {
+ pub fn extended(a: Self, b: Self) -> Self {
// TODO: benchmark for an optimal value, currently just a arbitrary choice
const ARR_EXTEND_THRESHOLD: usize = 100;
crates/jrsonnet-evaluator/src/function/arglike.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/function/arglike.rs
+++ b/crates/jrsonnet-evaluator/src/function/arglike.rs
@@ -61,8 +61,8 @@
impl ArgLike for TlaArg {
fn evaluate_arg(&self, ctx: Context, tailstrict: bool) -> Result<Thunk<Val>> {
match self {
- TlaArg::String(s) => Ok(Thunk::evaluated(Val::string(s.clone()))),
- TlaArg::Code(code) => Ok(if tailstrict {
+ Self::String(s) => Ok(Thunk::evaluated(Val::string(s.clone()))),
+ Self::Code(code) => Ok(if tailstrict {
Thunk::evaluated(evaluate(ctx, code)?)
} else {
Thunk::new(EvaluateThunk {
@@ -70,8 +70,8 @@
expr: code.clone(),
})
}),
- TlaArg::Val(val) => Ok(Thunk::evaluated(val.clone())),
- TlaArg::Lazy(lazy) => Ok(lazy.clone()),
+ Self::Val(val) => Ok(Thunk::evaluated(val.clone())),
+ Self::Lazy(lazy) => Ok(lazy.clone()),
}
}
}
crates/jrsonnet-evaluator/src/function/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/function/mod.rs
+++ b/crates/jrsonnet-evaluator/src/function/mod.rs
@@ -237,7 +237,7 @@
pub fn evaluate_trivial(&self) -> Option<Val> {
match self {
- FuncVal::Normal(n) => n.evaluate_trivial(),
+ Self::Normal(n) => n.evaluate_trivial(),
_ => None,
}
}
crates/jrsonnet-evaluator/src/import.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/import.rs
+++ b/crates/jrsonnet-evaluator/src/import.rs
@@ -10,7 +10,7 @@
use fs::File;
use jrsonnet_gcmodule::Trace;
use jrsonnet_interner::IBytes;
-use jrsonnet_parser::{SourceDirectory, SourceFile, SourcePath, SourceFifo};
+use jrsonnet_parser::{SourceDirectory, SourceFifo, SourceFile, SourcePath};
use crate::{
bail,
crates/jrsonnet-evaluator/src/integrations/serde.rsdiffbeforeafterboth1use std::borrow::Cow;23use jrsonnet_interner::IStr;4use serde::{5 de::Visitor,6 ser::{7 Error, SerializeMap, SerializeSeq, SerializeStruct, SerializeStructVariant, SerializeTuple,8 SerializeTupleStruct, SerializeTupleVariant,9 },10 Deserialize, Serialize, Serializer,11};1213use crate::{14 arr::ArrValue, runtime_error, Error as JrError, ObjValue, ObjValueBuilder, Result, State, Val,15};1617impl<'de> Deserialize<'de> for Val {18 fn deserialize<D>(deserializer: D) -> Result<Val, D::Error>19 where20 D: serde::Deserializer<'de>,21 {22 struct ValVisitor;2324 // macro_rules! visit_num {25 // ($($method:ident => $ty:ty),* $(,)?) => {$(26 // fn $method<E>(self, v: $ty) -> Result<Self::Value, E>27 // where28 // E: serde::de::Error,29 // {30 // Ok(Val::Num(f64::from(v)))31 // }32 // )*};33 // }3435 impl<'de> Visitor<'de> for ValVisitor {36 type Value = Val;3738 fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E>39 where40 E: serde::de::Error,41 {42 Ok(Val::Bool(v))43 }44 fn visit_f64<E>(self, v: f64) -> Result<Self::Value, E>45 where46 E: serde::de::Error,47 {48 if !v.is_finite() {49 return Err(E::custom("only finite numbers are supported"));50 }51 Ok(Val::Num(v))52 }53 fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>54 where55 E: serde::de::Error,56 {57 Ok(Val::string(v))58 }5960 // visit_num! {61 // visit_i8 => i8,62 // visit_i16 => i16,63 // visit_i32 => i32,64 // visit_u8 => u8,65 // visit_u16 => u16,66 // visit_u32 => u32,67 // }68 fn visit_i64<E>(self, v: i64) -> Result<Self::Value, E>69 where70 E: serde::de::Error,71 {72 Ok(Val::Num(v as f64))73 }74 fn visit_u64<E>(self, v: u64) -> Result<Self::Value, E>75 where76 E: serde::de::Error,77 {78 Ok(Val::Num(v as f64))79 }8081 fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>82 where83 E: serde::de::Error,84 {85 Ok(Val::Arr(ArrValue::bytes(v.into())))86 }8788 fn visit_none<E>(self) -> Result<Self::Value, E>89 where90 E: serde::de::Error,91 {92 Ok(Val::Null)93 }94 fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error>95 where96 D: serde::Deserializer<'de>,97 {98 deserializer.deserialize_any(self)99 }100101 fn visit_unit<E>(self) -> Result<Self::Value, E>102 where103 E: serde::de::Error,104 {105 Ok(Val::Null)106 }107108 fn visit_newtype_struct<D>(self, deserializer: D) -> Result<Self::Value, D::Error>109 where110 D: serde::Deserializer<'de>,111 {112 deserializer.deserialize_any(self)113 }114115 fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>116 where117 A: serde::de::SeqAccess<'de>,118 {119 let mut out = seq.size_hint().map_or_else(Vec::new, Vec::with_capacity);120121 while let Some(val) = seq.next_element::<Val>()? {122 out.push(val);123 }124125 Ok(Val::Arr(ArrValue::eager(out)))126 }127128 fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>129 where130 A: serde::de::MapAccess<'de>,131 {132 let mut out = map133 .size_hint()134 .map_or_else(ObjValueBuilder::new, ObjValueBuilder::with_capacity);135136 while let Some((k, v)) = map.next_entry::<Cow<'de, str>, Val>()? {137 // Jsonnet ignores duplicate keys138 out.field(k).value(v);139 }140141 Ok(Val::Obj(out.build()))142 }143144 fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {145 write!(formatter, "any valid jsonnet value")146 }147 }148 deserializer.deserialize_any(ValVisitor)149 }150}151152impl Serialize for Val {153 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>154 where155 S: serde::Serializer,156 {157 match self {158 Val::Bool(v) => serializer.serialize_bool(*v),159 Val::Null => serializer.serialize_none(),160 Val::Str(s) => serializer.serialize_str(&s.clone().into_flat()),161 Val::Num(n) => {162 if n.fract() == 0.0 {163 let n = *n as i64;164 serializer.serialize_i64(n)165 } else {166 serializer.serialize_f64(*n)167 }168 }169 #[cfg(feature = "exp-bigint")]170 Val::BigInt(b) => b.serialize(serializer),171 Val::Arr(arr) => {172 let mut seq = serializer.serialize_seq(Some(arr.len()))?;173 for (i, element) in arr.iter().enumerate() {174 let mut serde_error = None;175 // TODO: rewrite using try{} after stabilization176 State::push_description(177 || format!("array index [{i}]"),178 || {179 let e = element?;180 if let Err(e) = seq.serialize_element(&e) {181 serde_error = Some(e);182 }183 Ok(())184 },185 )186 .map_err(|e| S::Error::custom(e.to_string()))?;187 if let Some(e) = serde_error {188 return Err(e);189 }190 }191 seq.end()192 }193 Val::Obj(obj) => {194 let mut map = serializer.serialize_map(Some(obj.len()))?;195 for (field, value) in obj.iter(196 #[cfg(feature = "exp-preserve-order")]197 true,198 ) {199 let mut serde_error = None;200 // TODO: rewrite using try{} after stabilization201 State::push_description(202 || format!("object field {field:?}"),203 || {204 let v = value?;205 if let Err(e) = map.serialize_entry(field.as_str(), &v) {206 serde_error = Some(e);207 }208 Ok(())209 },210 )211 .map_err(|e| S::Error::custom(e.to_string()))?;212 if let Some(e) = serde_error {213 return Err(e);214 }215 }216 map.end()217 }218 Val::Func(_) => Err(S::Error::custom("tried to manifest function")),219 }220 }221}222223struct IntoVecValSerializer {224 variant: Option<IStr>,225 data: Vec<Val>,226}227impl IntoVecValSerializer {228 fn new() -> Self {229 Self {230 variant: None,231 data: Vec::new(),232 }233 }234 fn with_capacity(capacity: usize) -> Self {235 Self {236 variant: None,237 data: Vec::with_capacity(capacity),238 }239 }240 fn variant_with_capacity(variant: impl Into<IStr>, capacity: usize) -> Self {241 Self {242 variant: Some(variant.into()),243 data: Vec::with_capacity(capacity),244 }245 }246}247impl SerializeSeq for IntoVecValSerializer {248 type Ok = Val;249 type Error = JrError;250251 fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<()>252 where253 T: Serialize,254 {255 let value = value.serialize(IntoValSerializer)?;256 self.data.push(value);257 Ok(())258 }259260 fn end(self) -> Result<Val> {261 let inner = Val::Arr(ArrValue::eager(self.data));262 if let Some(variant) = self.variant {263 let mut out = ObjValue::builder_with_capacity(1);264 out.field(variant).value(inner);265 Ok(Val::Obj(out.build()))266 } else {267 Ok(inner)268 }269 }270}271impl SerializeTuple for IntoVecValSerializer {272 type Ok = Val;273 type Error = JrError;274275 fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<()>276 where277 T: Serialize,278 {279 SerializeSeq::serialize_element(self, value)280 }281282 fn end(self) -> Result<Val> {283 SerializeSeq::end(self)284 }285}286impl SerializeTupleVariant for IntoVecValSerializer {287 type Ok = Val;288 type Error = JrError;289290 fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<()>291 where292 T: Serialize,293 {294 SerializeSeq::serialize_element(self, value)295 }296297 fn end(self) -> Result<Val> {298 SerializeSeq::end(self)299 }300}301impl SerializeTupleStruct for IntoVecValSerializer {302 type Ok = Val;303 type Error = JrError;304305 fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<()>306 where307 T: Serialize,308 {309 SerializeSeq::serialize_element(self, value)310 }311312 fn end(self) -> Result<Val> {313 SerializeSeq::end(self)314 }315}316317struct IntoObjValueSerializer {318 variant: Option<IStr>,319 data: ObjValueBuilder,320 key: Option<IStr>,321}322impl IntoObjValueSerializer {323 fn new() -> Self {324 Self {325 variant: None,326 data: ObjValue::builder(),327 key: None,328 }329 }330 fn with_capacity(capacity: usize) -> Self {331 Self {332 variant: None,333 data: ObjValue::builder_with_capacity(capacity),334 key: None,335 }336 }337 fn variant_with_capacity(variant: impl Into<IStr>, capacity: usize) -> Self {338 Self {339 variant: Some(variant.into()),340 data: ObjValue::builder_with_capacity(capacity),341 key: None,342 }343 }344}345impl SerializeMap for IntoObjValueSerializer {346 type Ok = Val;347 type Error = JrError;348349 fn serialize_key<T: ?Sized>(&mut self, key: &T) -> Result<()>350 where351 T: Serialize,352 {353 let key = key.serialize(IntoValSerializer)?;354 let key = key.to_string()?;355 self.key = Some(key);356 Ok(())357 }358359 fn serialize_value<T: ?Sized>(&mut self, value: &T) -> Result<()>360 where361 T: Serialize,362 {363 let key = self.key.take().expect("no serialize_key called");364 let value = value.serialize(IntoValSerializer)?;365 self.data.field(key).try_value(value)?;366 Ok(())367 }368369 // TODO: serialize_key/serialize_value370 fn serialize_entry<K: ?Sized, V: ?Sized>(&mut self, key: &K, value: &V) -> Result<()>371 where372 K: Serialize,373 V: Serialize,374 {375 let key = key.serialize(IntoValSerializer)?;376 let key = key.to_string()?;377 let value = value.serialize(IntoValSerializer)?;378 self.data.field(key).try_value(value)?;379 Ok(())380 }381382 fn end(self) -> Result<Val> {383 let inner = Val::Obj(self.data.build());384 if let Some(variant) = self.variant {385 let mut out = ObjValue::builder_with_capacity(1);386 out.field(variant).value(inner);387 Ok(Val::Obj(out.build()))388 } else {389 Ok(inner)390 }391 }392}393impl SerializeStruct for IntoObjValueSerializer {394 type Ok = Val;395 type Error = JrError;396397 fn serialize_field<T: ?Sized>(&mut self, key: &'static str, value: &T) -> Result<()>398 where399 T: Serialize,400 {401 SerializeMap::serialize_entry(self, key, value)?;402 Ok(())403 }404405 fn end(self) -> Result<Val> {406 SerializeMap::end(self)407 }408}409impl SerializeStructVariant for IntoObjValueSerializer {410 type Ok = Val;411412 type Error = JrError;413414 fn serialize_field<T: ?Sized>(&mut self, key: &'static str, value: &T) -> Result<()>415 where416 T: Serialize,417 {418 SerializeMap::serialize_entry(self, key, value)?;419 Ok(())420 }421422 fn end(self) -> Result<Val> {423 SerializeMap::end(self)424 }425}426427struct IntoValSerializer;428impl Serializer for IntoValSerializer {429 type Ok = Val;430431 type Error = JrError;432433 type SerializeSeq = IntoVecValSerializer;434435 type SerializeTuple = IntoVecValSerializer;436437 type SerializeTupleStruct = IntoVecValSerializer;438439 type SerializeTupleVariant = IntoVecValSerializer;440441 type SerializeMap = IntoObjValueSerializer;442443 type SerializeStruct = IntoObjValueSerializer;444445 type SerializeStructVariant = IntoObjValueSerializer;446447 fn serialize_bool(self, v: bool) -> Result<Val> {448 Ok(Val::Bool(v))449 }450451 fn serialize_i8(self, v: i8) -> Result<Val> {452 Ok(Val::Num(f64::from(v)))453 }454455 fn serialize_i16(self, v: i16) -> Result<Val> {456 Ok(Val::Num(f64::from(v)))457 }458459 fn serialize_i32(self, v: i32) -> Result<Val> {460 Ok(Val::Num(f64::from(v)))461 }462463 fn serialize_i64(self, v: i64) -> Result<Val> {464 Ok(Val::Str(v.to_string().into()))465 }466467 fn serialize_u8(self, v: u8) -> Result<Val> {468 Ok(Val::Num(f64::from(v)))469 }470471 fn serialize_u16(self, v: u16) -> Result<Val> {472 Ok(Val::Num(f64::from(v)))473 }474475 fn serialize_u32(self, v: u32) -> Result<Val> {476 Ok(Val::Num(f64::from(v)))477 }478479 fn serialize_u64(self, v: u64) -> Result<Val> {480 Ok(Val::Str(v.to_string().into()))481 }482483 fn serialize_f32(self, v: f32) -> Result<Val> {484 Ok(Val::Num(f64::from(v)))485 }486487 fn serialize_f64(self, v: f64) -> Result<Val> {488 Ok(Val::Num(v))489 }490491 fn serialize_char(self, v: char) -> Result<Val> {492 Ok(Val::Str(v.to_string().into()))493 }494495 fn serialize_str(self, v: &str) -> Result<Val> {496 Ok(Val::Str(v.into()))497 }498499 fn serialize_bytes(self, v: &[u8]) -> Result<Val> {500 Ok(Val::Arr(ArrValue::bytes(v.into())))501 }502503 fn serialize_none(self) -> Result<Val> {504 Ok(Val::Null)505 }506507 fn serialize_some<T: ?Sized>(self, value: &T) -> Result<Val>508 where509 T: Serialize,510 {511 value.serialize(self)512 }513514 fn serialize_unit(self) -> Result<Val> {515 Ok(Val::Null)516 }517518 fn serialize_unit_struct(self, _name: &'static str) -> Result<Val> {519 Ok(Val::Null)520 }521522 fn serialize_unit_variant(523 self,524 _name: &'static str,525 _variant_index: u32,526 variant: &'static str,527 ) -> Result<Val> {528 Ok(Val::Str(variant.into()))529 }530531 fn serialize_newtype_struct<T: ?Sized>(self, _name: &'static str, value: &T) -> Result<Val>532 where533 T: Serialize,534 {535 value.serialize(self)536 }537538 fn serialize_newtype_variant<T: ?Sized>(539 self,540 _name: &'static str,541 _variant_index: u32,542 variant: &'static str,543 value: &T,544 ) -> Result<Val>545 where546 T: Serialize,547 {548 let mut out = ObjValue::builder_with_capacity(1);549 let value = value.serialize(self)?;550 out.field(variant).value(value);551 Ok(Val::Obj(out.build()))552 }553554 fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, Self::Error> {555 Ok(len.map_or_else(556 IntoVecValSerializer::new,557 IntoVecValSerializer::with_capacity,558 ))559 }560561 fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple, Self::Error> {562 Ok(IntoVecValSerializer::with_capacity(len))563 }564565 fn serialize_tuple_struct(566 self,567 _name: &'static str,568 len: usize,569 ) -> Result<Self::SerializeTupleStruct, Self::Error> {570 Ok(IntoVecValSerializer::with_capacity(len))571 }572573 fn serialize_tuple_variant(574 self,575 _name: &'static str,576 _variant_index: u32,577 variant: &'static str,578 len: usize,579 ) -> Result<Self::SerializeTupleVariant, Self::Error> {580 Ok(IntoVecValSerializer::variant_with_capacity(variant, len))581 }582583 fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap, Self::Error> {584 Ok(len.map_or_else(585 IntoObjValueSerializer::new,586 IntoObjValueSerializer::with_capacity,587 ))588 }589590 fn serialize_struct(591 self,592 _name: &'static str,593 len: usize,594 ) -> Result<Self::SerializeStruct, Self::Error> {595 Ok(IntoObjValueSerializer::with_capacity(len))596 }597598 fn serialize_struct_variant(599 self,600 _name: &'static str,601 _variant_index: u32,602 variant: &'static str,603 len: usize,604 ) -> Result<Self::SerializeStructVariant, Self::Error> {605 Ok(IntoObjValueSerializer::variant_with_capacity(variant, len))606 }607}608609impl Val {610 pub fn from_serde(v: impl Serialize) -> Result<Val, JrError> {611 v.serialize(IntoValSerializer)612 }613}614615impl serde::ser::Error for JrError {616 fn custom<T>(msg: T) -> Self617 where618 T: std::fmt::Display,619 {620 runtime_error!("serde: {msg}")621 }622}1use std::borrow::Cow;23use jrsonnet_interner::IStr;4use serde::{5 de::Visitor,6 ser::{7 Error, SerializeMap, SerializeSeq, SerializeStruct, SerializeStructVariant, SerializeTuple,8 SerializeTupleStruct, SerializeTupleVariant,9 },10 Deserialize, Serialize, Serializer,11};1213use crate::{14 arr::ArrValue, runtime_error, Error as JrError, ObjValue, ObjValueBuilder, Result, State, Val,15};1617impl<'de> Deserialize<'de> for Val {18 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>19 where20 D: serde::Deserializer<'de>,21 {22 struct ValVisitor;2324 // macro_rules! visit_num {25 // ($($method:ident => $ty:ty),* $(,)?) => {$(26 // fn $method<E>(self, v: $ty) -> Result<Self::Value, E>27 // where28 // E: serde::de::Error,29 // {30 // Ok(Val::Num(f64::from(v)))31 // }32 // )*};33 // }3435 impl<'de> Visitor<'de> for ValVisitor {36 type Value = Val;3738 fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E>39 where40 E: serde::de::Error,41 {42 Ok(Val::Bool(v))43 }44 fn visit_f64<E>(self, v: f64) -> Result<Self::Value, E>45 where46 E: serde::de::Error,47 {48 if !v.is_finite() {49 return Err(E::custom("only finite numbers are supported"));50 }51 Ok(Val::Num(v))52 }53 fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>54 where55 E: serde::de::Error,56 {57 Ok(Val::string(v))58 }5960 // visit_num! {61 // visit_i8 => i8,62 // visit_i16 => i16,63 // visit_i32 => i32,64 // visit_u8 => u8,65 // visit_u16 => u16,66 // visit_u32 => u32,67 // }68 fn visit_i64<E>(self, v: i64) -> Result<Self::Value, E>69 where70 E: serde::de::Error,71 {72 Ok(Val::Num(v as f64))73 }74 fn visit_u64<E>(self, v: u64) -> Result<Self::Value, E>75 where76 E: serde::de::Error,77 {78 Ok(Val::Num(v as f64))79 }8081 fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>82 where83 E: serde::de::Error,84 {85 Ok(Val::Arr(ArrValue::bytes(v.into())))86 }8788 fn visit_none<E>(self) -> Result<Self::Value, E>89 where90 E: serde::de::Error,91 {92 Ok(Val::Null)93 }94 fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error>95 where96 D: serde::Deserializer<'de>,97 {98 deserializer.deserialize_any(self)99 }100101 fn visit_unit<E>(self) -> Result<Self::Value, E>102 where103 E: serde::de::Error,104 {105 Ok(Val::Null)106 }107108 fn visit_newtype_struct<D>(self, deserializer: D) -> Result<Self::Value, D::Error>109 where110 D: serde::Deserializer<'de>,111 {112 deserializer.deserialize_any(self)113 }114115 fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>116 where117 A: serde::de::SeqAccess<'de>,118 {119 let mut out = seq.size_hint().map_or_else(Vec::new, Vec::with_capacity);120121 while let Some(val) = seq.next_element::<Val>()? {122 out.push(val);123 }124125 Ok(Val::Arr(ArrValue::eager(out)))126 }127128 fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>129 where130 A: serde::de::MapAccess<'de>,131 {132 let mut out = map133 .size_hint()134 .map_or_else(ObjValueBuilder::new, ObjValueBuilder::with_capacity);135136 while let Some((k, v)) = map.next_entry::<Cow<'de, str>, Val>()? {137 // Jsonnet ignores duplicate keys138 out.field(k).value(v);139 }140141 Ok(Val::Obj(out.build()))142 }143144 fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {145 write!(formatter, "any valid jsonnet value")146 }147 }148 deserializer.deserialize_any(ValVisitor)149 }150}151152impl Serialize for Val {153 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>154 where155 S: serde::Serializer,156 {157 match self {158 Self::Bool(v) => serializer.serialize_bool(*v),159 Self::Null => serializer.serialize_none(),160 Self::Str(s) => serializer.serialize_str(&s.clone().into_flat()),161 Self::Num(n) => {162 if n.fract() == 0.0 {163 let n = *n as i64;164 serializer.serialize_i64(n)165 } else {166 serializer.serialize_f64(*n)167 }168 }169 #[cfg(feature = "exp-bigint")]170 Self::BigInt(b) => b.serialize(serializer),171 Self::Arr(arr) => {172 let mut seq = serializer.serialize_seq(Some(arr.len()))?;173 for (i, element) in arr.iter().enumerate() {174 let mut serde_error = None;175 // TODO: rewrite using try{} after stabilization176 State::push_description(177 || format!("array index [{i}]"),178 || {179 let e = element?;180 if let Err(e) = seq.serialize_element(&e) {181 serde_error = Some(e);182 }183 Ok(())184 },185 )186 .map_err(|e| S::Error::custom(e.to_string()))?;187 if let Some(e) = serde_error {188 return Err(e);189 }190 }191 seq.end()192 }193 Self::Obj(obj) => {194 let mut map = serializer.serialize_map(Some(obj.len()))?;195 for (field, value) in obj.iter(196 #[cfg(feature = "exp-preserve-order")]197 true,198 ) {199 let mut serde_error = None;200 // TODO: rewrite using try{} after stabilization201 State::push_description(202 || format!("object field {field:?}"),203 || {204 let v = value?;205 if let Err(e) = map.serialize_entry(field.as_str(), &v) {206 serde_error = Some(e);207 }208 Ok(())209 },210 )211 .map_err(|e| S::Error::custom(e.to_string()))?;212 if let Some(e) = serde_error {213 return Err(e);214 }215 }216 map.end()217 }218 Self::Func(_) => Err(S::Error::custom("tried to manifest function")),219 }220 }221}222223struct IntoVecValSerializer {224 variant: Option<IStr>,225 data: Vec<Val>,226}227impl IntoVecValSerializer {228 fn new() -> Self {229 Self {230 variant: None,231 data: Vec::new(),232 }233 }234 fn with_capacity(capacity: usize) -> Self {235 Self {236 variant: None,237 data: Vec::with_capacity(capacity),238 }239 }240 fn variant_with_capacity(variant: impl Into<IStr>, capacity: usize) -> Self {241 Self {242 variant: Some(variant.into()),243 data: Vec::with_capacity(capacity),244 }245 }246}247impl SerializeSeq for IntoVecValSerializer {248 type Ok = Val;249 type Error = JrError;250251 fn serialize_element<T>(&mut self, value: &T) -> Result<()>252 where253 T: ?Sized + Serialize,254 {255 let value = value.serialize(IntoValSerializer)?;256 self.data.push(value);257 Ok(())258 }259260 fn end(self) -> Result<Val> {261 let inner = Val::Arr(ArrValue::eager(self.data));262 if let Some(variant) = self.variant {263 let mut out = ObjValue::builder_with_capacity(1);264 out.field(variant).value(inner);265 Ok(Val::Obj(out.build()))266 } else {267 Ok(inner)268 }269 }270}271impl SerializeTuple for IntoVecValSerializer {272 type Ok = Val;273 type Error = JrError;274275 fn serialize_element<T>(&mut self, value: &T) -> Result<()>276 where277 T: ?Sized + Serialize,278 {279 SerializeSeq::serialize_element(self, value)280 }281282 fn end(self) -> Result<Val> {283 SerializeSeq::end(self)284 }285}286impl SerializeTupleVariant for IntoVecValSerializer {287 type Ok = Val;288 type Error = JrError;289290 fn serialize_field<T>(&mut self, value: &T) -> Result<()>291 where292 T: ?Sized + Serialize,293 {294 SerializeSeq::serialize_element(self, value)295 }296297 fn end(self) -> Result<Val> {298 SerializeSeq::end(self)299 }300}301impl SerializeTupleStruct for IntoVecValSerializer {302 type Ok = Val;303 type Error = JrError;304305 fn serialize_field<T>(&mut self, value: &T) -> Result<()>306 where307 T: ?Sized + Serialize,308 {309 SerializeSeq::serialize_element(self, value)310 }311312 fn end(self) -> Result<Val> {313 SerializeSeq::end(self)314 }315}316317struct IntoObjValueSerializer {318 variant: Option<IStr>,319 data: ObjValueBuilder,320 key: Option<IStr>,321}322impl IntoObjValueSerializer {323 fn new() -> Self {324 Self {325 variant: None,326 data: ObjValue::builder(),327 key: None,328 }329 }330 fn with_capacity(capacity: usize) -> Self {331 Self {332 variant: None,333 data: ObjValue::builder_with_capacity(capacity),334 key: None,335 }336 }337 fn variant_with_capacity(variant: impl Into<IStr>, capacity: usize) -> Self {338 Self {339 variant: Some(variant.into()),340 data: ObjValue::builder_with_capacity(capacity),341 key: None,342 }343 }344}345impl SerializeMap for IntoObjValueSerializer {346 type Ok = Val;347 type Error = JrError;348349 fn serialize_key<T: ?Sized>(&mut self, key: &T) -> Result<()>350 where351 T: Serialize,352 {353 let key = key.serialize(IntoValSerializer)?;354 let key = key.to_string()?;355 self.key = Some(key);356 Ok(())357 }358359 fn serialize_value<T: ?Sized>(&mut self, value: &T) -> Result<()>360 where361 T: Serialize,362 {363 let key = self.key.take().expect("no serialize_key called");364 let value = value.serialize(IntoValSerializer)?;365 self.data.field(key).try_value(value)?;366 Ok(())367 }368369 // TODO: serialize_key/serialize_value370 fn serialize_entry<K: ?Sized, V: ?Sized>(&mut self, key: &K, value: &V) -> Result<()>371 where372 K: Serialize,373 V: Serialize,374 {375 let key = key.serialize(IntoValSerializer)?;376 let key = key.to_string()?;377 let value = value.serialize(IntoValSerializer)?;378 self.data.field(key).try_value(value)?;379 Ok(())380 }381382 fn end(self) -> Result<Val> {383 let inner = Val::Obj(self.data.build());384 if let Some(variant) = self.variant {385 let mut out = ObjValue::builder_with_capacity(1);386 out.field(variant).value(inner);387 Ok(Val::Obj(out.build()))388 } else {389 Ok(inner)390 }391 }392}393impl SerializeStruct for IntoObjValueSerializer {394 type Ok = Val;395 type Error = JrError;396397 fn serialize_field<T: ?Sized>(&mut self, key: &'static str, value: &T) -> Result<()>398 where399 T: Serialize,400 {401 SerializeMap::serialize_entry(self, key, value)?;402 Ok(())403 }404405 fn end(self) -> Result<Val> {406 SerializeMap::end(self)407 }408}409impl SerializeStructVariant for IntoObjValueSerializer {410 type Ok = Val;411412 type Error = JrError;413414 fn serialize_field<T: ?Sized>(&mut self, key: &'static str, value: &T) -> Result<()>415 where416 T: Serialize,417 {418 SerializeMap::serialize_entry(self, key, value)?;419 Ok(())420 }421422 fn end(self) -> Result<Val> {423 SerializeMap::end(self)424 }425}426427struct IntoValSerializer;428impl Serializer for IntoValSerializer {429 type Ok = Val;430431 type Error = JrError;432433 type SerializeSeq = IntoVecValSerializer;434435 type SerializeTuple = IntoVecValSerializer;436437 type SerializeTupleStruct = IntoVecValSerializer;438439 type SerializeTupleVariant = IntoVecValSerializer;440441 type SerializeMap = IntoObjValueSerializer;442443 type SerializeStruct = IntoObjValueSerializer;444445 type SerializeStructVariant = IntoObjValueSerializer;446447 fn serialize_bool(self, v: bool) -> Result<Val> {448 Ok(Val::Bool(v))449 }450451 fn serialize_i8(self, v: i8) -> Result<Val> {452 Ok(Val::Num(f64::from(v)))453 }454455 fn serialize_i16(self, v: i16) -> Result<Val> {456 Ok(Val::Num(f64::from(v)))457 }458459 fn serialize_i32(self, v: i32) -> Result<Val> {460 Ok(Val::Num(f64::from(v)))461 }462463 fn serialize_i64(self, v: i64) -> Result<Val> {464 Ok(Val::Str(v.to_string().into()))465 }466467 fn serialize_u8(self, v: u8) -> Result<Val> {468 Ok(Val::Num(f64::from(v)))469 }470471 fn serialize_u16(self, v: u16) -> Result<Val> {472 Ok(Val::Num(f64::from(v)))473 }474475 fn serialize_u32(self, v: u32) -> Result<Val> {476 Ok(Val::Num(f64::from(v)))477 }478479 fn serialize_u64(self, v: u64) -> Result<Val> {480 Ok(Val::Str(v.to_string().into()))481 }482483 fn serialize_f32(self, v: f32) -> Result<Val> {484 Ok(Val::Num(f64::from(v)))485 }486487 fn serialize_f64(self, v: f64) -> Result<Val> {488 Ok(Val::Num(v))489 }490491 fn serialize_char(self, v: char) -> Result<Val> {492 Ok(Val::Str(v.to_string().into()))493 }494495 fn serialize_str(self, v: &str) -> Result<Val> {496 Ok(Val::Str(v.into()))497 }498499 fn serialize_bytes(self, v: &[u8]) -> Result<Val> {500 Ok(Val::Arr(ArrValue::bytes(v.into())))501 }502503 fn serialize_none(self) -> Result<Val> {504 Ok(Val::Null)505 }506507 fn serialize_some<T: ?Sized>(self, value: &T) -> Result<Val>508 where509 T: Serialize,510 {511 value.serialize(self)512 }513514 fn serialize_unit(self) -> Result<Val> {515 Ok(Val::Null)516 }517518 fn serialize_unit_struct(self, _name: &'static str) -> Result<Val> {519 Ok(Val::Null)520 }521522 fn serialize_unit_variant(523 self,524 _name: &'static str,525 _variant_index: u32,526 variant: &'static str,527 ) -> Result<Val> {528 Ok(Val::Str(variant.into()))529 }530531 fn serialize_newtype_struct<T: ?Sized>(self, _name: &'static str, value: &T) -> Result<Val>532 where533 T: Serialize,534 {535 value.serialize(self)536 }537538 fn serialize_newtype_variant<T: ?Sized>(539 self,540 _name: &'static str,541 _variant_index: u32,542 variant: &'static str,543 value: &T,544 ) -> Result<Val>545 where546 T: Serialize,547 {548 let mut out = ObjValue::builder_with_capacity(1);549 let value = value.serialize(self)?;550 out.field(variant).value(value);551 Ok(Val::Obj(out.build()))552 }553554 fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, Self::Error> {555 Ok(len.map_or_else(556 IntoVecValSerializer::new,557 IntoVecValSerializer::with_capacity,558 ))559 }560561 fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple, Self::Error> {562 Ok(IntoVecValSerializer::with_capacity(len))563 }564565 fn serialize_tuple_struct(566 self,567 _name: &'static str,568 len: usize,569 ) -> Result<Self::SerializeTupleStruct, Self::Error> {570 Ok(IntoVecValSerializer::with_capacity(len))571 }572573 fn serialize_tuple_variant(574 self,575 _name: &'static str,576 _variant_index: u32,577 variant: &'static str,578 len: usize,579 ) -> Result<Self::SerializeTupleVariant, Self::Error> {580 Ok(IntoVecValSerializer::variant_with_capacity(variant, len))581 }582583 fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap, Self::Error> {584 Ok(len.map_or_else(585 IntoObjValueSerializer::new,586 IntoObjValueSerializer::with_capacity,587 ))588 }589590 fn serialize_struct(591 self,592 _name: &'static str,593 len: usize,594 ) -> Result<Self::SerializeStruct, Self::Error> {595 Ok(IntoObjValueSerializer::with_capacity(len))596 }597598 fn serialize_struct_variant(599 self,600 _name: &'static str,601 _variant_index: u32,602 variant: &'static str,603 len: usize,604 ) -> Result<Self::SerializeStructVariant, Self::Error> {605 Ok(IntoObjValueSerializer::variant_with_capacity(variant, len))606 }607}608609impl Val {610 pub fn from_serde(v: impl Serialize) -> Result<Self, JrError> {611 v.serialize(IntoValSerializer)612 }613}614615impl serde::ser::Error for JrError {616 fn custom<T>(msg: T) -> Self617 where618 T: std::fmt::Display,619 {620 runtime_error!("serde: {msg}")621 }622}crates/jrsonnet-evaluator/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/lib.rs
+++ b/crates/jrsonnet-evaluator/src/lib.rs
@@ -45,7 +45,7 @@
#[doc(hidden)]
pub use jrsonnet_macros;
pub use jrsonnet_parser as parser;
-use jrsonnet_parser::*;
+use jrsonnet_parser::{ExprLocation, LocExpr, ParserSettings, Source, SourcePath};
pub use obj::*;
use stack::check_depth;
pub use tla::apply_tla;
crates/jrsonnet-evaluator/src/stack.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/stack.rs
+++ b/crates/jrsonnet-evaluator/src/stack.rs
@@ -24,7 +24,7 @@
pub struct StackOverflowError;
impl From<StackOverflowError> for ErrorKind {
fn from(_: StackOverflowError) -> Self {
- ErrorKind::StackOverflow
+ Self::StackOverflow
}
}
impl From<StackOverflowError> for Error {
crates/jrsonnet-evaluator/src/typed/conversions.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/typed/conversions.rs
+++ b/crates/jrsonnet-evaluator/src/typed/conversions.rs
@@ -358,7 +358,7 @@
};
a.iter()
.map(|r| r.and_then(T::from_untyped))
- .collect::<Result<Vec<T>>>()
+ .collect::<Result<Self>>()
}
}
@@ -381,7 +381,7 @@
Self::TYPE.check(&value)?;
let obj = value.as_obj().expect("typecheck should fail");
- let mut out = BTreeMap::new();
+ let mut out = Self::new();
if V::wants_lazy() {
for key in obj.fields_ex(
false,
@@ -623,8 +623,8 @@
fn into_untyped(value: Self) -> Result<Val> {
match value {
- IndexableVal::Str(s) => Ok(Val::string(s)),
- IndexableVal::Arr(a) => Ok(Val::Arr(a)),
+ Self::Str(s) => Ok(Val::string(s)),
+ Self::Arr(a) => Ok(Val::Arr(a)),
}
}
crates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/val.rs
+++ b/crates/jrsonnet-evaluator/src/val.rs
@@ -147,7 +147,7 @@
T: ThunkValue<Output = V>,
{
fn from(value: T) -> Self {
- Thunk::new(value)
+ Self::new(value)
}
}
@@ -221,8 +221,8 @@
impl IndexableVal {
pub fn to_array(self) -> ArrValue {
match self {
- IndexableVal::Str(s) => ArrValue::chars(s.chars()),
- IndexableVal::Arr(arr) => arr,
+ Self::Str(s) => ArrValue::chars(s.chars()),
+ Self::Arr(arr) => arr,
}
}
/// Slice the value.
@@ -239,7 +239,7 @@
step: Option<BoundedUsize<1, { i32::MAX as usize }>>,
) -> Result<Self> {
match &self {
- IndexableVal::Str(s) => {
+ Self::Str(s) => {
let mut computed_len = None;
let mut get_len = || {
computed_len.map_or_else(
@@ -277,7 +277,7 @@
.into(),
))
}
- IndexableVal::Arr(arr) => {
+ Self::Arr(arr) => {
let get_idx = |pos: Option<i32>, len: usize, default| match pos {
Some(v) if v < 0 => len.saturating_sub((-v) as usize),
Some(v) => (v as usize).min(len),
@@ -307,7 +307,7 @@
Tree(Rc<(StrValue, StrValue, usize)>),
}
impl StrValue {
- pub fn concat(a: StrValue, b: StrValue) -> Self {
+ pub fn concat(a: Self, b: Self) -> Self {
// TODO: benchmark for an optimal value, currently just a arbitrary choice
const STRING_EXTEND_THRESHOLD: usize = 100;
@@ -334,8 +334,8 @@
}
}
match self {
- StrValue::Flat(f) => f,
- StrValue::Tree(_) => {
+ Self::Flat(f) => f,
+ Self::Tree(_) => {
let mut buf = String::with_capacity(self.len());
write_buf(&self, &mut buf);
buf.into()
@@ -344,8 +344,8 @@
}
pub fn len(&self) -> usize {
match self {
- StrValue::Flat(v) => v.len(),
- StrValue::Tree(t) => t.2,
+ Self::Flat(v) => v.len(),
+ Self::Tree(t) => t.2,
}
}
pub fn is_empty(&self) -> bool {
@@ -367,8 +367,8 @@
impl Display for StrValue {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
- StrValue::Flat(v) => write!(f, "{v}"),
- StrValue::Tree(t) => {
+ Self::Flat(v) => write!(f, "{v}"),
+ Self::Tree(t) => {
write!(f, "{}", t.0)?;
write!(f, "{}", t.1)
}
@@ -522,8 +522,8 @@
pub fn into_indexable(self) -> Result<IndexableVal> {
Ok(match self {
- Val::Str(s) => IndexableVal::Str(s.into_flat()),
- Val::Arr(arr) => IndexableVal::Arr(arr),
+ Self::Str(s) => IndexableVal::Str(s.into_flat()),
+ Self::Arr(arr) => IndexableVal::Arr(arr),
_ => bail!(ValueIsNotIndexable(self.value_type())),
})
}
crates/jrsonnet-macros/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-macros/src/lib.rs
+++ b/crates/jrsonnet-macros/src/lib.rs
@@ -1,3 +1,5 @@
+use std::string::String;
+
use proc_macro2::TokenStream;
use quote::quote;
use syn::{
@@ -205,6 +207,7 @@
}
}
+#[allow(clippy::too_many_lines)]
fn builtin_inner(
attr: BuiltinAttrs,
fun: ItemFn,
@@ -225,7 +228,7 @@
.map(|arg| ArgInfo::parse(&name, arg))
.collect::<Result<Vec<_>>>()?;
- let params_desc = args.iter().flat_map(|a| match a {
+ let params_desc = args.iter().filter_map(|a| match a {
ArgInfo::Normal {
is_option,
name,
@@ -234,8 +237,7 @@
} => {
let name = name
.as_ref()
- .map(|n| quote! {ParamName::new_static(#n)})
- .unwrap_or_else(|| quote! {None});
+ .map_or_else(|| quote! {None}, |n| quote! {ParamName::new_static(#n)});
Some(quote! {
#(#cfg_attrs)*
BuiltinParam::new(#name, #is_option),
@@ -244,15 +246,12 @@
ArgInfo::Lazy { is_option, name } => {
let name = name
.as_ref()
- .map(|n| quote! {ParamName::new_static(#n)})
- .unwrap_or_else(|| quote! {None});
+ .map_or_else(|| quote! {None}, |n| quote! {ParamName::new_static(#n)});
Some(quote! {
BuiltinParam::new(#name, #is_option),
})
}
- ArgInfo::Context => None,
- ArgInfo::Location => None,
- ArgInfo::This => None,
+ ArgInfo::Context | ArgInfo::Location | ArgInfo::This => None,
});
let mut id = 0usize;
@@ -275,7 +274,7 @@
name,
cfg_attrs,
} => {
- let name = name.as_ref().map(|v| v.as_str()).unwrap_or("<unnamed>");
+ let name = name.as_ref().map_or("<unnamed>", String::as_str);
let eval = quote! {jrsonnet_evaluator::State::push_description(
|| format!("argument <{}> evaluation", #name),
|| <#ty>::from_untyped(value.evaluate()?),
@@ -390,6 +389,7 @@
}
#[derive(Default)]
+#[allow(clippy::struct_excessive_bools)]
struct TypedAttr {
rename: Option<String>,
flatten: bool,
@@ -467,11 +467,8 @@
"this field should appear in output object, but it has no visible name",
));
};
- let (is_option, ty) = if let Some(ty) = extract_type_from_option(&field.ty)? {
- (true, ty.clone())
- } else {
- (false, field.ty.clone())
- };
+ let (is_option, ty) = extract_type_from_option(&field.ty)?
+ .map_or_else(|| (false, field.ty.clone()), |ty| (true, ty.clone()));
if is_option && attr.flatten {
if !attr.flatten_ok {
return Err(Error::new(
@@ -551,48 +548,53 @@
#ident: #value,
}
}
- fn expand_serialize(&self) -> Result<TokenStream> {
+ fn expand_serialize(&self) -> TokenStream {
let ident = &self.ident;
let ty = &self.ty;
- Ok(if let Some(name) = self.name() {
- let hide = if self.attr.hide {
- quote! {.hide()}
- } else {
- quote! {}
- };
- let add = if self.attr.add {
- quote! {.add()}
- } else {
- quote! {}
- };
- if self.is_option {
- quote! {
- if let Some(value) = self.#ident {
+ self.name().map_or_else(
+ || {
+ if self.is_option {
+ quote! {
+ if let Some(value) = self.#ident {
+ <#ty as TypedObj>::serialize(value, out)?;
+ }
+ }
+ } else {
+ quote! {
+ <#ty as TypedObj>::serialize(self.#ident, out)?;
+ }
+ }
+ },
+ |name| {
+ let hide = if self.attr.hide {
+ quote! {.hide()}
+ } else {
+ quote! {}
+ };
+ let add = if self.attr.add {
+ quote! {.add()}
+ } else {
+ quote! {}
+ };
+ if self.is_option {
+ quote! {
+ if let Some(value) = self.#ident {
+ out.field(#name)
+ #hide
+ #add
+ .try_value(<#ty as Typed>::into_untyped(value)?)?;
+ }
+ }
+ } else {
+ quote! {
out.field(#name)
#hide
#add
- .try_value(<#ty as Typed>::into_untyped(value)?)?;
+ .try_value(<#ty as Typed>::into_untyped(self.#ident)?)?;
}
}
- } else {
- quote! {
- out.field(#name)
- #hide
- #add
- .try_value(<#ty as Typed>::into_untyped(self.#ident)?)?;
- }
- }
- } else if self.is_option {
- quote! {
- if let Some(value) = self.#ident {
- <#ty as TypedObj>::serialize(value, out)?;
- }
- }
- } else {
- quote! {
- <#ty as TypedObj>::serialize(self.#ident, out)?;
- }
- })
+ },
+ )
}
}
@@ -623,7 +625,7 @@
let typed = {
let fields = fields
.iter()
- .flat_map(TypedField::expand_field)
+ .filter_map(TypedField::expand_field)
.collect::<Vec<_>>();
quote! {
impl #impl_generics Typed for #ident #ty_generics #where_clause {
@@ -650,7 +652,7 @@
let fields_serialize = fields
.iter()
.map(TypedField::expand_serialize)
- .collect::<Result<Vec<_>>>()?;
+ .collect::<Vec<_>>();
Ok(quote! {
const _: () = {
@@ -767,7 +769,7 @@
}
}
-/// IStr formatting helper
+/// `IStr` formatting helper
///
/// Using `format!("literal with no codes").into()` is slower than just `"literal with no codes".into()`
/// This macro looks for formatting codes in the input string, and uses
crates/jrsonnet-rowan-parser/src/parser.rsdiffbeforeafterboth--- a/crates/jrsonnet-rowan-parser/src/parser.rs
+++ b/crates/jrsonnet-rowan-parser/src/parser.rs
@@ -758,10 +758,10 @@
} else if p.at(T![...]) {
// let m_err = p.start_ranger();
destruct_rest(p);
- // if had_rest {
- // p.custom_error(m_err.finish(p), "only one rest can be present in array");
- // }
- // had_rest = true;
+ // if had_rest {
+ // p.custom_error(m_err.finish(p), "only one rest can be present in array");
+ // }
+ // had_rest = true;
} else {
destruct(p);
}
crates/jrsonnet-stdlib/build.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/build.rs
+++ b/crates/jrsonnet-stdlib/build.rs
@@ -26,7 +26,9 @@
let dest_path = Path::new(&out_dir).join("stdlib.rs");
let mut f = File::create(dest_path).unwrap();
f.write_all(
- ("#[allow(clippy::redundant_clone)]".to_owned() + &v.to_string()).as_bytes(),
+ ("#[allow(clippy::redundant_clone, clippy::similar_names)]".to_owned()
+ + &v.to_string())
+ .as_bytes(),
)
.unwrap();
}
crates/jrsonnet-stdlib/src/arrays.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/arrays.rs
+++ b/crates/jrsonnet-stdlib/src/arrays.rs
@@ -9,7 +9,7 @@
Either, IStr, ObjValueBuilder, Result, ResultExt, Thunk, Val,
};
-pub(crate) fn eval_on_empty(on_empty: Option<Thunk<Val>>) -> Result<Val> {
+pub fn eval_on_empty(on_empty: Option<Thunk<Val>>) -> Result<Val> {
if let Some(on_empty) = on_empty {
on_empty.evaluate()
} else {
@@ -270,8 +270,8 @@
let newArrRight = arr.slice(Some(at + 1), None, None);
Ok(ArrValue::extended(
- newArrLeft.unwrap_or(ArrValue::empty()),
- newArrRight.unwrap_or(ArrValue::empty()),
+ newArrLeft.unwrap_or_else(ArrValue::empty),
+ newArrRight.unwrap_or_else(ArrValue::empty),
))
}
crates/jrsonnet-stdlib/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/lib.rs
+++ b/crates/jrsonnet-stdlib/src/lib.rs
@@ -313,10 +313,10 @@
settings: Rc<RefCell<Settings>>,
}
impl ContextInitializer {
- pub fn new(_s: State, resolver: PathResolver) -> Self {
+ pub fn new(s: State, resolver: PathResolver) -> Self {
let settings = Settings {
- ext_vars: Default::default(),
- ext_natives: Default::default(),
+ ext_vars: HashMap::new(),
+ ext_natives: HashMap::new(),
trace_printer: Box::new(StdTracePrinter::new(resolver.clone())),
path_resolver: resolver,
};
@@ -324,10 +324,12 @@
let stdlib_obj = stdlib_uncached(settings.clone());
#[cfg(not(feature = "legacy-this-file"))]
let stdlib_thunk = Thunk::evaluated(Val::Obj(stdlib_obj));
+ #[cfg(feature = "legacy-this-file")]
+ let _ = s;
Self {
#[cfg(not(feature = "legacy-this-file"))]
context: {
- let mut context = ContextBuilder::with_capacity(_s, 1);
+ let mut context = ContextBuilder::with_capacity(s, 1);
context.bind("std", stdlib_thunk.clone());
context.build()
},
crates/jrsonnet-stdlib/src/manifest/toml.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/manifest/toml.rs
+++ b/crates/jrsonnet-stdlib/src/manifest/toml.rs
@@ -180,7 +180,9 @@
options.preserve_order,
) {
let value = value?;
- if !is_section(&value)? {
+ if is_section(&value)? {
+ sections.push((key, value));
+ } else {
if !first {
buf.push('\n');
}
@@ -189,8 +191,6 @@
escape_key_toml_buf(&key, buf);
buf.push_str(" = ");
manifest_value(&value, false, buf, cur_padding, options)?;
- } else {
- sections.push((key, value));
}
}
for (k, v) in sections {
crates/jrsonnet-stdlib/src/math.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/math.rs
+++ b/crates/jrsonnet-stdlib/src/math.rs
@@ -131,16 +131,19 @@
}
#[builtin]
+#[allow(clippy::float_cmp)]
pub fn builtin_is_odd(x: f64) -> bool {
builtin_round(x) % 2.0 == 1.0
}
#[builtin]
+#[allow(clippy::float_cmp)]
pub fn builtin_is_integer(x: f64) -> bool {
builtin_round(x) == x
}
#[builtin]
+#[allow(clippy::float_cmp)]
pub fn builtin_is_decimal(x: f64) -> bool {
builtin_round(x) != x
}
crates/jrsonnet-stdlib/src/misc.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/misc.rs
+++ b/crates/jrsonnet-stdlib/src/misc.rs
@@ -67,11 +67,7 @@
v => v.manifest(JsonFormat::debug())?.into(),
},
);
- if let Some(rest) = rest {
- rest.evaluate()
- } else {
- Ok(str)
- }
+ rest.map_or_else(|| Ok(str), |rest| rest.evaluate())
}
#[allow(clippy::comparison_chain)]
@@ -84,16 +80,15 @@
return Ok(false);
} else if b.len() == a.len() {
return equals(&Val::Arr(a), &Val::Arr(b));
- } else {
- for (a, b) in a.iter().take(b.len()).zip(b.iter()) {
- let a = a?;
- let b = b?;
- if !equals(&a, &b)? {
- return Ok(false);
- }
+ }
+ for (a, b) in a.iter().take(b.len()).zip(b.iter()) {
+ let a = a?;
+ let b = b?;
+ if !equals(&a, &b)? {
+ return Ok(false);
}
- true
}
+ true
}
_ => bail!("both arguments should be of the same type"),
})
@@ -109,17 +104,16 @@
return Ok(false);
} else if b.len() == a.len() {
return equals(&Val::Arr(a), &Val::Arr(b));
- } else {
- let a_len = a.len();
- for (a, b) in a.iter().skip(a_len - b.len()).zip(b.iter()) {
- let a = a?;
- let b = b?;
- if !equals(&a, &b)? {
- return Ok(false);
- }
+ }
+ let a_len = a.len();
+ for (a, b) in a.iter().skip(a_len - b.len()).zip(b.iter()) {
+ let a = a?;
+ let b = b?;
+ if !equals(&a, &b)? {
+ return Ok(false);
}
- true
}
+ true
}
_ => bail!("both arguments should be of the same type"),
})
crates/jrsonnet-stdlib/src/objects.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/objects.rs
+++ b/crates/jrsonnet-stdlib/src/objects.rs
@@ -155,7 +155,7 @@
if k == key {
continue;
}
- new_obj.field(k).value(v.unwrap())
+ new_obj.field(k).value(v.unwrap());
}
new_obj.build()
crates/jrsonnet-stdlib/src/sort.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/sort.rs
+++ b/crates/jrsonnet-stdlib/src/sort.rs
@@ -36,7 +36,7 @@
fn get_sort_type<T>(values: &[T], key_getter: impl Fn(&T) -> &Val) -> Result<SortKeyType> {
let mut sort_type = SortKeyType::Unknown;
- for i in values.iter() {
+ for i in values {
let i = key_getter(i);
match (i, sort_type) {
(Val::Str(_), SortKeyType::Unknown) => sort_type = SortKeyType::String,
crates/jrsonnet-stdlib/src/strings.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/strings.rs
+++ b/crates/jrsonnet-stdlib/src/strings.rs
@@ -75,7 +75,7 @@
.enumerate()
{
if &strb[i..i + pat.len()] == pat {
- out.push(Val::Num(ch_idx as f64))
+ out.push(Val::Num(ch_idx as f64));
}
}
out.into()
@@ -117,11 +117,6 @@
}
fn parse_nat<const BASE: u32>(raw: &str) -> Result<f64> {
- debug_assert!(
- 1 <= BASE && BASE <= 16,
- "integer base should be between 1 and 16"
- );
-
const ZERO_CODE: u32 = '0' as u32;
const UPPER_A_CODE: u32 = 'A' as u32;
const LOWER_A_CODE: u32 = 'a' as u32;
@@ -135,10 +130,17 @@
}
}
- let base = BASE as f64;
+ debug_assert!(
+ 1 <= BASE && BASE <= 16,
+ "integer base should be between 1 and 16"
+ );
+
+ let base = f64::from(BASE);
raw.chars().try_fold(0f64, |aggregate, digit| {
let digit = digit as u32;
+ // if-let-else looks better here than Option combinators
+ #[allow(clippy::option_if_let_else)]
let digit = if let Some(digit) = checked_sub_if(BASE > 10, digit, LOWER_A_CODE) {
digit + 10
} else if let Some(digit) = checked_sub_if(BASE > 10, digit, UPPER_A_CODE) {
@@ -148,7 +150,7 @@
};
if digit < BASE {
- Ok(base * aggregate + digit as f64)
+ Ok(base.mul_add(aggregate, f64::from(digit)))
} else {
bail!("{raw:?} is not a base {BASE} integer");
}
crates/jrsonnet-types/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-types/src/lib.rs
+++ b/crates/jrsonnet-types/src/lib.rs
@@ -166,9 +166,9 @@
fn print_array(a: &ComplexValType, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
if *a == ComplexValType::Any {
- write!(f, "array")?
+ write!(f, "array")?;
} else {
- write!(f, "Array<{a}>")?
+ write!(f, "Array<{a}>")?;
}
Ok(())
}
@@ -176,18 +176,20 @@
impl Display for ComplexValType {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
- ComplexValType::Any => write!(f, "any")?,
- ComplexValType::Simple(s) => write!(f, "{s}")?,
- ComplexValType::Char => write!(f, "char")?,
- ComplexValType::BoundedNumber(a, b) => write!(
+ Self::Any => write!(f, "any")?,
+ Self::Simple(s) => write!(f, "{s}")?,
+ Self::Char => write!(f, "char")?,
+ Self::BoundedNumber(a, b) => write!(
f,
"BoundedNumber<{}, {}>",
- a.map(|e| e.to_string()).unwrap_or_else(|| "".into()),
- b.map(|e| e.to_string()).unwrap_or_else(|| "".into())
+ a.map(|e| e.to_string())
+ .unwrap_or_else(|| "open".to_owned()),
+ b.map(|e| e.to_string())
+ .unwrap_or_else(|| "open".to_owned())
)?,
- ComplexValType::ArrayRef(a) => print_array(a, f)?,
- ComplexValType::Array(a) => print_array(a, f)?,
- ComplexValType::ObjectRef(fields) => {
+ Self::ArrayRef(a) => print_array(a, f)?,
+ Self::Array(a) => print_array(a, f)?,
+ Self::ObjectRef(fields) => {
write!(f, "{{")?;
for (i, (k, v)) in fields.iter().enumerate() {
if i != 0 {
@@ -197,18 +199,18 @@
}
write!(f, "}}")?;
}
- ComplexValType::AttrsOf(a) => {
- if matches!(a, ComplexValType::Any) {
+ Self::AttrsOf(a) => {
+ if matches!(a, Self::Any) {
write!(f, "object")?;
} else {
write!(f, "AttrsOf<{a}>")?;
}
}
- ComplexValType::Union(v) => write_union(f, true, v.iter())?,
- ComplexValType::UnionRef(v) => write_union(f, true, v.iter().copied())?,
- ComplexValType::Sum(v) => write_union(f, false, v.iter())?,
- ComplexValType::SumRef(v) => write_union(f, false, v.iter().copied())?,
- ComplexValType::Lazy(lazy) => write!(f, "Lazy<{lazy}>")?,
+ Self::Union(v) => write_union(f, true, v.iter())?,
+ Self::UnionRef(v) => write_union(f, true, v.iter().copied())?,
+ Self::Sum(v) => write_union(f, false, v.iter())?,
+ Self::SumRef(v) => write_union(f, false, v.iter().copied())?,
+ Self::Lazy(lazy) => write!(f, "Lazy<{lazy}>")?,
};
Ok(())
}
tests/suite/std_param_names.jsonnetdiffbeforeafterboth--- a/tests/suite/std_param_names.jsonnet
+++ b/tests/suite/std_param_names.jsonnet
@@ -49,6 +49,7 @@
min: ['a', 'b'],
clamp: ['x', 'minVal', 'maxVal'],
flattenArrays: ['arrs'],
+ flattenDeepArray: ['value'],
manifestIni: ['ini'],
manifestToml: ['value'],
manifestTomlEx: ['value', 'indent'],