1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
|
use crate::{make, session::SessionInfo, Metadata, Report, Rule, Suggestion};
use if_chain::if_chain;
use macros::lint;
use rnix::{
types::{AttrSet, EntryHolder, Lambda, Pattern, TypedNode},
NodeOrToken, SyntaxElement, SyntaxKind, SyntaxNode,
};
/// ## What it does
/// Checks for an empty variadic pattern: `{...}`, in a function
/// argument.
///
/// ## Why is this bad?
/// The intention with empty patterns is not instantly obvious. Prefer
/// an underscore identifier instead, to indicate that the argument
/// is being ignored.
///
/// ## Example
///
/// ```nix
/// client = { ... }: {
/// services.irmaseal-pkg.enable = true;
/// };
/// ```
///
/// Replace the empty variadic pattern with `_` to indicate that you
/// intend to ignore the argument:
///
/// ```nix
/// client = _: {
/// services.irmaseal-pkg.enable = true;
/// };
/// ```
#[lint(
name = "empty_pattern",
note = "Found empty pattern in function argument",
code = 10,
match_with = SyntaxKind::NODE_LAMBDA
)]
struct EmptyPattern;
impl Rule for EmptyPattern {
fn validate(&self, node: &SyntaxElement, _sess: &SessionInfo) -> Option<Report> {
if_chain! {
if let NodeOrToken::Node(node) = node;
if let Some(lambda_expr) = Lambda::cast(node.clone());
if let Some(arg) = lambda_expr.arg();
if let Some(body) = lambda_expr.body();
if let Some(pattern) = Pattern::cast(arg.clone());
// no patterns within `{ }`
if pattern.entries().count() == 0;
// pattern is not bound
if pattern.at().is_none();
// not a nixos module
if !is_module(&body);
then {
let at = pattern.node().text_range();
let message = "This pattern is empty, use `_` instead";
let replacement = make::ident("_").node().clone();
Some(self.report().suggest(at, message, Suggestion::new(at, replacement)))
} else {
None
}
}
}
}
fn is_module(body: &SyntaxNode) -> bool {
if_chain! {
if let Some(attr_set) = AttrSet::cast(body.clone());
if attr_set
.entries()
.map(|e| e.key())
.flatten()
.any(|k| k.node().to_string() == "imports");
then {
true
} else {
false
}
}
}
|