Skip to content

Commit

Permalink
style: fix clippy warnings
Browse files Browse the repository at this point in the history
  • Loading branch information
CertainLach committed Aug 26, 2024
1 parent 7cdcae3 commit 7cd3ab4
Show file tree
Hide file tree
Showing 19 changed files with 350 additions and 488 deletions.
383 changes: 218 additions & 165 deletions Cargo.lock

Large diffs are not rendered by default.

7 changes: 4 additions & 3 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,7 @@ regex = "1.10"
lru = "0.12.3"

json-structural-diff = "0.1.0"
syn-dissect-closure = "0.1.0"

[workspace.lints.rust]
unsafe_op_in_unsafe_fn = "deny"
Expand All @@ -107,9 +108,9 @@ macro_expanded_macro_exports_accessed_by_absolute_paths = "allow"
all = "warn"

[workspace.lints.clippy]
all = "warn"
nursery = "warn"
pedantic = "warn"
all = { level = "warn", priority = -1 }
nursery = { level = "warn", priority = -1 }
pedantic = { level = "warn", priority = -1 }

ptr_arg = "allow"
# Too verbose
Expand Down
1 change: 1 addition & 0 deletions bindings/jsonnet/src/native.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ use crate::VM;
/// - `ctx` User pointer, given in `jsonnet_native_callback`.
/// - `argv` Array of arguments from Jsonnet code.
/// - `param` success Set this byref param to 1 to indicate success and 0 for failure.
///
/// Returns the content of the imported file, or an error message.
type JsonnetNativeCallback = unsafe extern "C" fn(
ctx: *const c_void,
Expand Down
2 changes: 1 addition & 1 deletion cmds/jrsonnet-fmt/src/comments.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ pub fn format_comments(comments: &ChildTrivia, loc: CommentLocation, out: &mut P
let Ok(c) = c else {
let mut text = c.as_ref().unwrap_err() as &str;
while !text.is_empty() {
let pos = text.find(|c| c == '\n' || c == '\t').unwrap_or(text.len());
let pos = text.find(['\n', '\t']).unwrap_or(text.len());
let sliced = &text[..pos];
p!(out, string(sliced.to_string()));
text = &text[pos..];
Expand Down
2 changes: 1 addition & 1 deletion cmds/jrsonnet-fmt/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,5 +75,5 @@ fn complex_comments_snapshot() {
b: '',
},
}"
)))
)));
}
57 changes: 23 additions & 34 deletions crates/jrsonnet-evaluator/src/function/arglike.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,7 @@ pub trait ArgsLike {
handler: &mut dyn FnMut(&IStr, Thunk<Val>) -> Result<()>,
) -> Result<()>;
fn named_names(&self, handler: &mut dyn FnMut(&IStr));
fn is_empty(&self) -> bool;
}

impl ArgsLike for Vec<Val> {
Expand All @@ -117,6 +118,9 @@ impl ArgsLike for Vec<Val> {
Ok(())
}
fn named_names(&self, _handler: &mut dyn FnMut(&IStr)) {}
fn is_empty(&self) -> bool {
self.is_empty()
}
}

impl ArgsLike for ArgsDesc {
Expand Down Expand Up @@ -173,6 +177,10 @@ impl ArgsLike for ArgsDesc {
handler(name);
}
}

fn is_empty(&self) -> bool {
self.unnamed.is_empty() && self.named.is_empty()
}
}

impl<V: ArgLike, S> ArgsLike for HashMap<IStr, V, S> {
Expand Down Expand Up @@ -206,6 +214,10 @@ impl<V: ArgLike, S> ArgsLike for HashMap<IStr, V, S> {
handler(name);
}
}

fn is_empty(&self) -> bool {
self.is_empty()
}
}
impl<V, S> OptionalContext for HashMap<IStr, V, S> where V: ArgLike + OptionalContext {}

Expand Down Expand Up @@ -235,6 +247,10 @@ impl<A: ArgLike> ArgsLike for GcHashMap<IStr, A> {
fn named_names(&self, handler: &mut dyn FnMut(&IStr)) {
self.0.named_names(handler);
}

fn is_empty(&self) -> bool {
self.0.is_empty()
}
}

macro_rules! impl_args_like {
Expand Down Expand Up @@ -267,43 +283,13 @@ macro_rules! impl_args_like {
Ok(())
}
fn named_names(&self, _handler: &mut dyn FnMut(&IStr)) {}
}
impl<$($gen: ArgLike,)*> OptionalContext for ($($gen,)*) where $($gen: OptionalContext),* {}

impl<$($gen: ArgLike,)*> ArgsLike for ($((IStr, $gen),)*) {
fn unnamed_len(&self) -> usize {
0
}
fn unnamed_iter(
&self,
_ctx: Context,
_tailstrict: bool,
_handler: &mut dyn FnMut(usize, Thunk<Val>) -> Result<()>,
) -> Result<()> {
Ok(())
}
#[allow(non_snake_case)]
fn named_iter(
&self,
ctx: Context,
tailstrict: bool,
handler: &mut dyn FnMut(&IStr, Thunk<Val>) -> Result<()>,
) -> Result<()> {
let ($($gen,)*) = self;
$(
handler(&$gen.0, $gen.1.evaluate_arg(ctx.clone(), tailstrict)?)?;
)*
Ok(())
}
#[allow(non_snake_case)]
fn named_names(&self, handler: &mut dyn FnMut(&IStr)) {
let ($($gen,)*) = self;
$(
handler(&$gen.0);
)*
fn is_empty(&self) -> bool {
// impl_args_like only implements non-empty tuples.
false
}
}
impl<$($gen: ArgLike,)*> OptionalContext for ($((IStr, $gen),)*) where $($gen: OptionalContext),* {}
impl<$($gen: ArgLike,)*> OptionalContext for ($($gen,)*) where $($gen: OptionalContext),* {}
};
($count:expr; $($cur:ident)* @ $c:ident $($rest:ident)*) => {
impl_args_like!($count; $($cur)*);
Expand Down Expand Up @@ -342,5 +328,8 @@ impl ArgsLike for () {
}

fn named_names(&self, _handler: &mut dyn FnMut(&IStr)) {}
fn is_empty(&self) -> bool {
true
}
}
impl OptionalContext for () {}
17 changes: 16 additions & 1 deletion crates/jrsonnet-evaluator/src/function/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,10 @@ use self::{
native::NativeDesc,
parse::{parse_default_function_call, parse_function_call},
};
use crate::{evaluate, evaluate_trivial, gc::TraceBox, tb, Context, ContextBuilder, Result, Val};
use crate::{
bail, error::ErrorKind::*, evaluate, evaluate_trivial, gc::TraceBox, tb, Context,
ContextBuilder, Result, Thunk, Val,
};

pub mod arglike;
pub mod builtin;
Expand Down Expand Up @@ -94,6 +97,8 @@ pub enum FuncVal {
Id,
/// Plain function implemented in jsonnet.
Normal(Cc<FuncDesc>),
/// Function without arguments works just as a fancy thunk value.
Thunk(Thunk<Val>),
/// Standard library function.
StaticBuiltin(#[trace(skip)] &'static dyn StaticBuiltin),
/// User-provided function.
Expand All @@ -104,6 +109,7 @@ impl Debug for FuncVal {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Id => f.debug_tuple("Id").finish(),
Self::Thunk(arg0) => f.debug_tuple("Thunk").field(arg0).finish(),
Self::Normal(arg0) => f.debug_tuple("Normal").field(arg0).finish(),
Self::StaticBuiltin(arg0) => {
f.debug_tuple("StaticBuiltin").field(&arg0.name()).finish()
Expand Down Expand Up @@ -146,6 +152,7 @@ impl FuncVal {
)
})
.collect(),
Self::Thunk(_) => vec![],
}
}
/// Amount of non-default required arguments
Expand All @@ -155,6 +162,7 @@ impl FuncVal {
Self::Normal(n) => n.params.iter().filter(|p| p.1.is_none()).count(),
Self::StaticBuiltin(i) => i.params().iter().filter(|p| !p.has_default()).count(),
Self::Builtin(i) => i.params().iter().filter(|p| !p.has_default()).count(),
Self::Thunk(_) => 0,
}
}
/// Function name, as defined in code.
Expand All @@ -164,6 +172,7 @@ impl FuncVal {
Self::Normal(normal) => normal.name.clone(),
Self::StaticBuiltin(builtin) => builtin.name().into(),
Self::Builtin(builtin) => builtin.name().into(),
Self::Thunk(_) => "thunk".into(),
}
}
/// Call function using arguments evaluated in specified `call_ctx` [`Context`].
Expand All @@ -182,6 +191,12 @@ impl FuncVal {
let body_ctx = func.call_body_context(call_ctx, args, tailstrict)?;
evaluate(body_ctx, &func.body)
}
Self::Thunk(thunk) => {
if args.is_empty() {
bail!(TooManyArgsFunctionHas(0, vec![],))
}
thunk.evaluate()
}
Self::StaticBuiltin(b) => b.call(call_ctx, loc, args),
Self::Builtin(b) => b.call(call_ctx, loc, args),
}
Expand Down
11 changes: 5 additions & 6 deletions crates/jrsonnet-evaluator/src/stdlib/format.rs
Original file line number Diff line number Diff line change
Expand Up @@ -308,22 +308,21 @@ pub fn render_integer(
prefix: &str,
caps: bool,
) {
let radix = radix as f64;
let iv = iv.floor();
let iv = iv.floor() as i64;
// Digit char indexes in reverse order, i.e
// for radix = 16 and n = 12f: [15, 2, 1]
let digits = if iv == 0.0 {
let digits = if iv == 0 {
vec![0u8]
} else {
let mut v = iv.abs();
let mut nums = Vec::with_capacity(1);
while v != 0.0 {
while v != 0 {
nums.push((v % radix) as u8);
v = (v / radix).floor();
v /= radix;
}
nums
};
let neg = iv < 0.0;
let neg = iv < 0;
#[allow(clippy::bool_to_int_with_if)]
let zp = padding.saturating_sub(if neg || blank || sign { 1 } else { 0 });
let zp2 = zp
Expand Down
6 changes: 5 additions & 1 deletion crates/jrsonnet-rowan-parser/src/ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,14 @@ pub trait AstNode {
Self: Sized;

fn syntax(&self) -> &SyntaxNode;
#[must_use]
fn clone_for_update(&self) -> Self
where
Self: Sized,
{
Self::cast(self.syntax().clone_for_update()).unwrap()
}
#[must_use]
fn clone_subtree(&self) -> Self
where
Self: Sized,
Expand Down Expand Up @@ -70,6 +72,8 @@ impl<N: AstNode> Iterator for AstChildren<N> {
}

pub mod support {
use rowan::NodeOrToken;

use super::{AstChildren, AstNode, AstToken, SyntaxKind, SyntaxNode, SyntaxToken};

pub fn child<N: AstNode>(parent: &SyntaxNode) -> Option<N> {
Expand All @@ -89,7 +93,7 @@ pub mod support {
pub fn token(parent: &SyntaxNode, kind: SyntaxKind) -> Option<SyntaxToken> {
parent
.children_with_tokens()
.filter_map(|it| it.into_token())
.filter_map(NodeOrToken::into_token)
.find(|it| it.kind() == kind)
}
}
21 changes: 11 additions & 10 deletions crates/jrsonnet-rowan-parser/src/event.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ pub enum Event {
// VirtualToken { kind: SyntaxKind },
/// Position of finished node
Finish {
/// Same as forward_parent of Start, but for wrapping
/// Same as `forward_parent` of Start, but for wrapping
wrapper: Option<NonZeroUsize>,
error: Option<Box<SyntaxError>>,
},
Expand Down Expand Up @@ -57,13 +57,14 @@ impl<'i> Sink<'i> {
if self.offset == 0 {
return 0.into();
};
if let Some(lex) = self.lexemes.get(self.offset) {
lex.range.start()
} else if let Some(lex) = self.lexemes.get(self.offset - 1) {
lex.range.end()
} else {
panic!("hard oob")
}
self.lexemes.get(self.offset).map_or_else(
|| {
self.lexemes
.get(self.offset - 1)
.map_or_else(|| panic!("hard oob"), |lex| lex.range.end())
},
|lex| lex.range.start(),
)
}

pub(super) fn finish(mut self) -> Parse {
Expand Down Expand Up @@ -139,7 +140,7 @@ impl<'i> Sink<'i> {
self.errors.push(LocatedSyntaxError {
error: *error,
range: TextRange::new(range.0, range.1),
})
});
}
self.builder.finish_node();
depth -= 1;
Expand All @@ -158,7 +159,7 @@ impl<'i> Sink<'i> {
self.errors.push(LocatedSyntaxError {
error: *error,
range: TextRange::new(range.0, range.1),
})
});
}

if depth == 1 {
Expand Down
1 change: 1 addition & 0 deletions crates/jrsonnet-stdlib/src/manifest/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@ pub fn builtin_manifest_yaml_doc(
}

#[builtin]
#[allow(clippy::fn_params_excessive_bools)]
pub fn builtin_manifest_yaml_stream(
value: Val,
#[default(false)] indent_array_in_object: bool,
Expand Down
2 changes: 1 addition & 1 deletion crates/jrsonnet-stdlib/src/manifest/yaml.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ fn yaml_needs_quotes(string: &str) -> bool {

string.is_empty()
|| need_quotes_spaces(string)
|| string.starts_with(|c| matches!(c, '&' | '*' | '?' | '|' | '-' | '<' | '>' | '=' | '!' | '%' | '@'))
|| string.starts_with(['&' , '*' , '?' , '|' , '-' , '<' , '>' , '=' , '!' , '%' , '@'])
|| string.contains(|c| matches!(c, ':' | '{' | '}' | '[' | ']' | ',' | '#' | '`' | '\"' | '\'' | '\\' | '\0'..='\x06' | '\t' | '\n' | '\r' | '\x0e'..='\x1a' | '\x1c'..='\x1f'))
|| [
// http://yaml.org/type/bool.html
Expand Down
9 changes: 5 additions & 4 deletions crates/jrsonnet-stdlib/src/strings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -267,15 +267,16 @@ fn new_trim_pattern(chars: IndexableVal) -> Result<impl Fn(char) -> bool> {
}

#[cfg(test)]
#[allow(clippy::float_cmp)]
mod tests {
use super::*;

#[test]
fn parse_nat_base_8() {
assert_eq!(parse_nat::<8>("0").unwrap(), 0.);
assert_eq!(parse_nat::<8>("5").unwrap(), 5.);
assert_eq!(parse_nat::<8>("32").unwrap(), 0o32 as f64);
assert_eq!(parse_nat::<8>("761").unwrap(), 0o761 as f64);
assert_eq!(parse_nat::<8>("32").unwrap(), f64::from(0o32));
assert_eq!(parse_nat::<8>("761").unwrap(), f64::from(0o761));
}

#[test]
Expand All @@ -290,7 +291,7 @@ mod tests {
fn parse_nat_base_16() {
assert_eq!(parse_nat::<16>("0").unwrap(), 0.);
assert_eq!(parse_nat::<16>("A").unwrap(), 10.);
assert_eq!(parse_nat::<16>("a9").unwrap(), 0xA9 as f64);
assert_eq!(parse_nat::<16>("BbC").unwrap(), 0xBBC as f64);
assert_eq!(parse_nat::<16>("a9").unwrap(), f64::from(0xA9));
assert_eq!(parse_nat::<16>("BbC").unwrap(), f64::from(0xBBC));
}
}
Loading

0 comments on commit 7cd3ab4

Please sign in to comment.