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.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/integrations/serde.rs
+++ b/crates/jrsonnet-evaluator/src/integrations/serde.rs
@@ -15,7 +15,7 @@
};
impl<'de> Deserialize<'de> for Val {
- fn deserialize<D>(deserializer: D) -> Result<Val, D::Error>
+ fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
@@ -155,10 +155,10 @@
S: serde::Serializer,
{
match self {
- Val::Bool(v) => serializer.serialize_bool(*v),
- Val::Null => serializer.serialize_none(),
- Val::Str(s) => serializer.serialize_str(&s.clone().into_flat()),
- Val::Num(n) => {
+ Self::Bool(v) => serializer.serialize_bool(*v),
+ Self::Null => serializer.serialize_none(),
+ Self::Str(s) => serializer.serialize_str(&s.clone().into_flat()),
+ Self::Num(n) => {
if n.fract() == 0.0 {
let n = *n as i64;
serializer.serialize_i64(n)
@@ -167,8 +167,8 @@
}
}
#[cfg(feature = "exp-bigint")]
- Val::BigInt(b) => b.serialize(serializer),
- Val::Arr(arr) => {
+ Self::BigInt(b) => b.serialize(serializer),
+ Self::Arr(arr) => {
let mut seq = serializer.serialize_seq(Some(arr.len()))?;
for (i, element) in arr.iter().enumerate() {
let mut serde_error = None;
@@ -190,7 +190,7 @@
}
seq.end()
}
- Val::Obj(obj) => {
+ Self::Obj(obj) => {
let mut map = serializer.serialize_map(Some(obj.len()))?;
for (field, value) in obj.iter(
#[cfg(feature = "exp-preserve-order")]
@@ -215,7 +215,7 @@
}
map.end()
}
- Val::Func(_) => Err(S::Error::custom("tried to manifest function")),
+ Self::Func(_) => Err(S::Error::custom("tried to manifest function")),
}
}
}
@@ -248,9 +248,9 @@
type Ok = Val;
type Error = JrError;
- fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<()>
+ fn serialize_element<T>(&mut self, value: &T) -> Result<()>
where
- T: Serialize,
+ T: ?Sized + Serialize,
{
let value = value.serialize(IntoValSerializer)?;
self.data.push(value);
@@ -272,9 +272,9 @@
type Ok = Val;
type Error = JrError;
- fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<()>
+ fn serialize_element<T>(&mut self, value: &T) -> Result<()>
where
- T: Serialize,
+ T: ?Sized + Serialize,
{
SerializeSeq::serialize_element(self, value)
}
@@ -287,9 +287,9 @@
type Ok = Val;
type Error = JrError;
- fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<()>
+ fn serialize_field<T>(&mut self, value: &T) -> Result<()>
where
- T: Serialize,
+ T: ?Sized + Serialize,
{
SerializeSeq::serialize_element(self, value)
}
@@ -302,9 +302,9 @@
type Ok = Val;
type Error = JrError;
- fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<()>
+ fn serialize_field<T>(&mut self, value: &T) -> Result<()>
where
- T: Serialize,
+ T: ?Sized + Serialize,
{
SerializeSeq::serialize_element(self, value)
}
@@ -607,7 +607,7 @@
}
impl Val {
- pub fn from_serde(v: impl Serialize) -> Result<Val, JrError> {
+ pub fn from_serde(v: impl Serialize) -> Result<Self, JrError> {
v.serialize(IntoValSerializer)
}
}
crates/jrsonnet-evaluator/src/lib.rsdiffbeforeafterboth1//! jsonnet interpreter implementation2#![cfg_attr(feature = "nightly", feature(thread_local, type_alias_impl_trait))]34// For jrsonnet-macros5extern crate self as jrsonnet_evaluator;67mod arr;8#[cfg(feature = "async-import")]9pub mod async_import;10mod ctx;11mod dynamic;12pub mod error;13mod evaluate;14pub mod function;15pub mod gc;16mod import;17mod integrations;18pub mod manifest;19mod map;20mod obj;21pub mod stack;22pub mod stdlib;23mod tla;24pub mod trace;25pub mod typed;26pub mod val;2728use std::{29 any::Any,30 cell::{Ref, RefCell, RefMut},31 fmt::{self, Debug},32 path::Path,33};3435pub use ctx::*;36pub use dynamic::*;37pub use error::{Error, ErrorKind::*, Result, ResultExt};38pub use evaluate::*;39use function::CallLocation;40use gc::{GcHashMap, TraceBox};41use hashbrown::hash_map::RawEntryMut;42pub use import::*;43use jrsonnet_gcmodule::{Cc, Trace};44pub use jrsonnet_interner::{IBytes, IStr};45#[doc(hidden)]46pub use jrsonnet_macros;47pub use jrsonnet_parser as parser;48use jrsonnet_parser::*;49pub use obj::*;50use stack::check_depth;51pub use tla::apply_tla;52pub use val::{Thunk, Val};5354/// Thunk without bound `super`/`this`55/// object inheritance may be overriden multiple times, and will be fixed only on field read56pub trait Unbound: Trace {57 /// Type of value after object context is bound58 type Bound;59 /// Create value bound to specified object context60 fn bind(&self, sup: Option<ObjValue>, this: Option<ObjValue>) -> Result<Self::Bound>;61}6263/// Object fields may, or may not depend on `this`/`super`, this enum allows cheaper reuse of object-independent fields for native code64/// Standard jsonnet fields are always unbound65#[derive(Clone, Trace)]66pub enum MaybeUnbound {67 /// Value needs to be bound to `this`/`super`68 Unbound(Cc<TraceBox<dyn Unbound<Bound = Val>>>),69 /// Value is object-independent70 Bound(Thunk<Val>),71}7273impl Debug for MaybeUnbound {74 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {75 write!(f, "MaybeUnbound")76 }77}78impl MaybeUnbound {79 /// Attach object context to value, if required80 pub fn evaluate(&self, sup: Option<ObjValue>, this: Option<ObjValue>) -> Result<Val> {81 match self {82 Self::Unbound(v) => v.bind(sup, this),83 Self::Bound(v) => Ok(v.evaluate()?),84 }85 }86}8788/// During import, this trait will be called to create initial context for file.89/// It may initialize global variables, stdlib for example.90pub trait ContextInitializer: Trace {91 /// For which size the builder should be preallocated92 fn reserve_vars(&self) -> usize {93 094 }95 /// Initialize default file context.96 /// Has default implementation, which calls `populate`.97 /// Prefer to always implement `populate` instead.98 fn initialize(&self, state: State, for_file: Source) -> Context {99 let mut builder = ContextBuilder::with_capacity(state, self.reserve_vars());100 self.populate(for_file, &mut builder);101 builder.build()102 }103 /// For composability: extend builder. May panic if this initialization is not supported,104 /// and the context may only be created via `initialize`.105 fn populate(&self, for_file: Source, builder: &mut ContextBuilder);106 /// Allows upcasting from abstract to concrete context initializer.107 /// jrsonnet by itself doesn't use this method, it is allowed for it to panic.108 fn as_any(&self) -> &dyn Any;109}110111/// Context initializer which adds nothing.112impl ContextInitializer for () {113 fn populate(&self, _for_file: Source, _builder: &mut ContextBuilder) {}114 fn as_any(&self) -> &dyn Any {115 self116 }117}118119macro_rules! impl_context_initializer {120 ($($gen:ident)*) => {121 #[allow(non_snake_case)]122 impl<$($gen: ContextInitializer + Trace,)*> ContextInitializer for ($($gen,)*) {123 fn reserve_vars(&self) -> usize {124 let mut out = 0;125 let ($($gen,)*) = self;126 $(out += $gen.reserve_vars();)*127 out128 }129 fn populate(&self, for_file: Source, builder: &mut ContextBuilder) {130 let ($($gen,)*) = self;131 $($gen.populate(for_file.clone(), builder);)*132 }133 fn as_any(&self) -> &dyn Any {134 self135 }136 }137 };138 ($($cur:ident)* @ $c:ident $($rest:ident)*) => {139 impl_context_initializer!($($cur)*);140 impl_context_initializer!($($cur)* $c @ $($rest)*);141 };142 ($($cur:ident)* @) => {143 impl_context_initializer!($($cur)*);144 }145}146impl_context_initializer! {147 A @ B C D E F G148}149150/// Dynamically reconfigurable evaluation settings151#[derive(Trace)]152pub struct EvaluationSettings {153 /// Context initializer, which will be used for imports and everything154 /// [`NoopContextInitializer`] is used by default, most likely you want to have `jrsonnet-stdlib`155 pub context_initializer: TraceBox<dyn ContextInitializer>,156 /// Used to resolve file locations/contents157 pub import_resolver: TraceBox<dyn ImportResolver>,158}159impl Default for EvaluationSettings {160 fn default() -> Self {161 Self {162 context_initializer: tb!(()),163 import_resolver: tb!(DummyImportResolver),164 }165 }166}167168#[derive(Trace)]169struct FileData {170 string: Option<IStr>,171 bytes: Option<IBytes>,172 parsed: Option<LocExpr>,173 evaluated: Option<Val>,174175 evaluating: bool,176}177impl FileData {178 fn new_string(data: IStr) -> Self {179 Self {180 string: Some(data),181 bytes: None,182 parsed: None,183 evaluated: None,184 evaluating: false,185 }186 }187 fn new_bytes(data: IBytes) -> Self {188 Self {189 string: None,190 bytes: Some(data),191 parsed: None,192 evaluated: None,193 evaluating: false,194 }195 }196 pub(crate) fn get_string(&mut self) -> Option<IStr> {197 if self.string.is_none() {198 self.string = Some(199 self.bytes200 .as_ref()201 .expect("either string or bytes should be set")202 .clone()203 .cast_str()?,204 );205 }206 Some(self.string.clone().expect("just set"))207 }208}209210#[derive(Default, Trace)]211pub struct EvaluationStateInternals {212 /// Internal state213 file_cache: RefCell<GcHashMap<SourcePath, FileData>>,214 /// Settings, safe to change at runtime215 settings: RefCell<EvaluationSettings>,216}217218/// Maintains stack trace and import resolution219#[derive(Default, Clone, Trace)]220pub struct State(Cc<EvaluationStateInternals>);221222impl State {223 /// Should only be called with path retrieved from [`resolve_path`], may panic otherwise224 pub fn import_resolved_str(&self, path: SourcePath) -> Result<IStr> {225 let mut file_cache = self.file_cache();226 let mut file = file_cache.raw_entry_mut().from_key(&path);227228 let file = match file {229 RawEntryMut::Occupied(ref mut d) => d.get_mut(),230 RawEntryMut::Vacant(v) => {231 let data = self.settings().import_resolver.load_file_contents(&path)?;232 v.insert(233 path.clone(),234 FileData::new_string(235 std::str::from_utf8(&data)236 .map_err(|_| ImportBadFileUtf8(path.clone()))?237 .into(),238 ),239 )240 .1241 }242 };243 Ok(file244 .get_string()245 .ok_or_else(|| ImportBadFileUtf8(path.clone()))?)246 }247 /// Should only be called with path retrieved from [`resolve_path`], may panic otherwise248 pub fn import_resolved_bin(&self, path: SourcePath) -> Result<IBytes> {249 let mut file_cache = self.file_cache();250 let mut file = file_cache.raw_entry_mut().from_key(&path);251252 let file = match file {253 RawEntryMut::Occupied(ref mut d) => d.get_mut(),254 RawEntryMut::Vacant(v) => {255 let data = self.settings().import_resolver.load_file_contents(&path)?;256 v.insert(path.clone(), FileData::new_bytes(data.as_slice().into()))257 .1258 }259 };260 if let Some(str) = &file.bytes {261 return Ok(str.clone());262 }263 if file.bytes.is_none() {264 file.bytes = Some(265 file.string266 .as_ref()267 .expect("either string or bytes should be set")268 .clone()269 .cast_bytes(),270 );271 }272 Ok(file.bytes.as_ref().expect("just set").clone())273 }274 /// Should only be called with path retrieved from [`resolve_path`], may panic otherwise275 pub fn import_resolved(&self, path: SourcePath) -> Result<Val> {276 let mut file_cache = self.file_cache();277 let mut file = file_cache.raw_entry_mut().from_key(&path);278279 let file = match file {280 RawEntryMut::Occupied(ref mut d) => d.get_mut(),281 RawEntryMut::Vacant(v) => {282 let data = self.settings().import_resolver.load_file_contents(&path)?;283 v.insert(284 path.clone(),285 FileData::new_string(286 std::str::from_utf8(&data)287 .map_err(|_| ImportBadFileUtf8(path.clone()))?288 .into(),289 ),290 )291 .1292 }293 };294 if let Some(val) = &file.evaluated {295 return Ok(val.clone());296 }297 let code = file298 .get_string()299 .ok_or_else(|| ImportBadFileUtf8(path.clone()))?;300 let file_name = Source::new(path.clone(), code.clone());301 if file.parsed.is_none() {302 file.parsed = Some(303 jrsonnet_parser::parse(304 &code,305 &ParserSettings {306 source: file_name.clone(),307 },308 )309 .map_err(|e| ImportSyntaxError {310 path: file_name.clone(),311 error: Box::new(e),312 })?,313 );314 }315 let parsed = file.parsed.as_ref().expect("just set").clone();316 if file.evaluating {317 bail!(InfiniteRecursionDetected)318 }319 file.evaluating = true;320 // Dropping file cache guard here, as evaluation may use this map too321 drop(file_cache);322 let res = evaluate(self.create_default_context(file_name), &parsed);323324 let mut file_cache = self.file_cache();325 let mut file = file_cache.raw_entry_mut().from_key(&path);326327 let RawEntryMut::Occupied(file) = &mut file else {328 unreachable!("this file was just here!")329 };330 let file = file.get_mut();331 file.evaluating = false;332 match res {333 Ok(v) => {334 file.evaluated = Some(v.clone());335 Ok(v)336 }337 Err(e) => Err(e),338 }339 }340341 /// Has same semantics as `import 'path'` called from `from` file342 pub fn import_from(&self, from: &SourcePath, path: &str) -> Result<Val> {343 let resolved = self.resolve_from(from, path)?;344 self.import_resolved(resolved)345 }346 pub fn import(&self, path: impl AsRef<Path>) -> Result<Val> {347 let resolved = self.resolve(path)?;348 self.import_resolved(resolved)349 }350351 /// Creates context with all passed global variables352 pub fn create_default_context(&self, source: Source) -> Context {353 let context_initializer = &self.settings().context_initializer;354 context_initializer.initialize(self.clone(), source)355 }356357 /// Creates context with all passed global variables, calling custom modifier358 pub fn create_default_context_with(359 &self,360 source: Source,361 context_initializer: impl ContextInitializer,362 ) -> Context {363 let default_initializer = &self.settings().context_initializer;364 let mut builder = ContextBuilder::with_capacity(365 self.clone(),366 default_initializer.reserve_vars() + context_initializer.reserve_vars(),367 );368 default_initializer.populate(source.clone(), &mut builder);369 context_initializer.populate(source, &mut builder);370371 builder.build()372 }373374 /// Executes code creating a new stack frame375 pub fn push<T>(376 e: CallLocation<'_>,377 frame_desc: impl FnOnce() -> String,378 f: impl FnOnce() -> Result<T>,379 ) -> Result<T> {380 let _guard = check_depth()?;381382 f().with_description_src(e, frame_desc)383 }384385 /// Executes code creating a new stack frame386 pub fn push_val(387 &self,388 e: &ExprLocation,389 frame_desc: impl FnOnce() -> String,390 f: impl FnOnce() -> Result<Val>,391 ) -> Result<Val> {392 let _guard = check_depth()?;393394 f().with_description_src(e, frame_desc)395 }396 /// Executes code creating a new stack frame397 pub fn push_description<T>(398 frame_desc: impl FnOnce() -> String,399 f: impl FnOnce() -> Result<T>,400 ) -> Result<T> {401 let _guard = check_depth()?;402403 f().with_description(frame_desc)404 }405}406407/// Internals408impl State {409 fn file_cache(&self) -> RefMut<'_, GcHashMap<SourcePath, FileData>> {410 self.0.file_cache.borrow_mut()411 }412 pub fn settings(&self) -> Ref<'_, EvaluationSettings> {413 self.0.settings.borrow()414 }415 pub fn settings_mut(&self) -> RefMut<'_, EvaluationSettings> {416 self.0.settings.borrow_mut()417 }418 pub fn add_global(&self, name: IStr, value: Thunk<Val>) {419 #[derive(Trace)]420 struct GlobalsCtx {421 globals: RefCell<GcHashMap<IStr, Thunk<Val>>>,422 inner: TraceBox<dyn ContextInitializer>,423 }424 impl ContextInitializer for GlobalsCtx {425 fn reserve_vars(&self) -> usize {426 self.inner.reserve_vars() + self.globals.borrow().len()427 }428 fn populate(&self, for_file: Source, builder: &mut ContextBuilder) {429 self.inner.populate(for_file, builder);430 for (name, val) in self.globals.borrow().iter() {431 builder.bind(name.clone(), val.clone());432 }433 }434435 fn as_any(&self) -> &dyn Any {436 self437 }438 }439 let mut settings = self.settings_mut();440 let initializer = &mut settings.context_initializer;441 if let Some(global) = initializer.as_any().downcast_ref::<GlobalsCtx>() {442 global.globals.borrow_mut().insert(name, value);443 } else {444 let inner = std::mem::replace(&mut settings.context_initializer, tb!(()));445 settings.context_initializer = tb!(GlobalsCtx {446 globals: {447 let mut out = GcHashMap::with_capacity(1);448 out.insert(name, value);449 RefCell::new(out)450 },451 inner452 });453 }454 }455}456457#[derive(Trace)]458pub struct InitialUnderscore(pub Thunk<Val>);459impl ContextInitializer for InitialUnderscore {460 fn populate(&self, _for_file: Source, builder: &mut ContextBuilder) {461 builder.bind("_", self.0.clone());462 }463464 fn as_any(&self) -> &dyn Any {465 self466 }467}468469/// Raw methods evaluate passed values but don't perform TLA execution470impl State {471 /// Parses and evaluates the given snippet472 pub fn evaluate_snippet(&self, name: impl Into<IStr>, code: impl Into<IStr>) -> Result<Val> {473 let code = code.into();474 let source = Source::new_virtual(name.into(), code.clone());475 let parsed = jrsonnet_parser::parse(476 &code,477 &ParserSettings {478 source: source.clone(),479 },480 )481 .map_err(|e| ImportSyntaxError {482 path: source.clone(),483 error: Box::new(e),484 })?;485 evaluate(self.create_default_context(source), &parsed)486 }487 /// Parses and evaluates the given snippet with custom context modifier488 pub fn evaluate_snippet_with(489 &self,490 name: impl Into<IStr>,491 code: impl Into<IStr>,492 context_initializer: impl ContextInitializer,493 ) -> Result<Val> {494 let code = code.into();495 let source = Source::new_virtual(name.into(), code.clone());496 let parsed = jrsonnet_parser::parse(497 &code,498 &ParserSettings {499 source: source.clone(),500 },501 )502 .map_err(|e| ImportSyntaxError {503 path: source.clone(),504 error: Box::new(e),505 })?;506 evaluate(507 self.create_default_context_with(source, context_initializer),508 &parsed,509 )510 }511}512513/// Settings utilities514impl State {515 // Only panics in case of [`ImportResolver`] contract violation516 #[allow(clippy::missing_panics_doc)]517 pub fn resolve_from(&self, from: &SourcePath, path: &str) -> Result<SourcePath> {518 self.import_resolver().resolve_from(from, path.as_ref())519 }520521 // Only panics in case of [`ImportResolver`] contract violation522 #[allow(clippy::missing_panics_doc)]523 pub fn resolve(&self, path: impl AsRef<Path>) -> Result<SourcePath> {524 self.import_resolver().resolve(path.as_ref())525 }526 pub fn import_resolver(&self) -> Ref<'_, dyn ImportResolver> {527 Ref::map(self.settings(), |s| &*s.import_resolver)528 }529 pub fn set_import_resolver(&self, resolver: impl ImportResolver) {530 self.settings_mut().import_resolver = tb!(resolver);531 }532 pub fn context_initializer(&self) -> Ref<'_, dyn ContextInitializer> {533 Ref::map(self.settings(), |s| &*s.context_initializer)534 }535 pub fn set_context_initializer(&self, initializer: impl ContextInitializer) {536 self.settings_mut().context_initializer = tb!(initializer);537 }538}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'],