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
88
89
90
91
92
use super::Context;
use super::LintRule;
use crate::swc_common::Span;
use crate::swc_ecma_ast;
use crate::swc_ecma_ast::ArrowExpr;
use crate::swc_ecma_ast::Function;
use crate::swc_ecma_ast::Param;
use crate::swc_ecma_ast::Pat;
use std::collections::HashSet;
use swc_ecma_visit::Node;
use swc_ecma_visit::Visit;
pub struct NoDupeArgs;
impl LintRule for NoDupeArgs {
fn new() -> Box<Self> {
Box::new(NoDupeArgs)
}
fn code(&self) -> &'static str {
"no-dupe-args"
}
fn lint_module(&self, context: Context, module: swc_ecma_ast::Module) {
let mut visitor = NoDupeArgsVisitor::new(context);
visitor.visit_module(&module, &module);
}
}
struct NoDupeArgsVisitor {
context: Context,
}
impl NoDupeArgsVisitor {
pub fn new(context: Context) -> Self {
Self { context }
}
fn check_pats(&self, span: Span, pats: &[Pat]) {
let mut seen: HashSet<String> = HashSet::new();
for pat in pats {
match &pat {
Pat::Ident(ident) => {
let pat_name = ident.sym.to_string();
if seen.get(&pat_name).is_some() {
self.context.add_diagnostic(
span,
"no-dupe-args",
"Duplicate arguments not allowed",
);
} else {
seen.insert(pat_name);
}
}
_ => continue,
}
}
}
fn check_params(&self, span: Span, params: &[Param]) {
let pats = params
.iter()
.map(|param| param.pat.clone())
.collect::<Vec<Pat>>();
self.check_pats(span, &pats);
}
}
impl Visit for NoDupeArgsVisitor {
fn visit_function(&mut self, function: &Function, _parent: &dyn Node) {
self.check_params(function.span, &function.params);
}
fn visit_arrow_expr(&mut self, arrow_expr: &ArrowExpr, _parent: &dyn Node) {
self.check_pats(arrow_expr.span, &arrow_expr.params);
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test_util::*;
#[test]
fn no_dupe_args_test() {
assert_lint_err::<NoDupeArgs>("function dupeArgs1(a, b, a) { }", 0);
assert_lint_err::<NoDupeArgs>("const dupeArgs2 = (a, b, a) => { }", 18);
}
}