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
// Copyright 2020 the Deno authors. All rights reserved. MIT license.
use super::Context;
use super::LintRule;
use crate::swc_ecma_ast;
use crate::swc_ecma_ast::VarDecl;
use swc_ecma_visit::Node;
use swc_ecma_visit::Visit;

pub struct SingleVarDeclarator;

impl LintRule for SingleVarDeclarator {
  fn new() -> Box<Self> {
    Box::new(SingleVarDeclarator)
  }

  fn code(&self) -> &'static str {
    "single-var-declarator"
  }

  fn lint_module(&self, context: Context, module: swc_ecma_ast::Module) {
    let mut visitor = SingleVarDeclaratorVisitor::new(context);
    visitor.visit_module(&module, &module);
  }
}

struct SingleVarDeclaratorVisitor {
  context: Context,
}

impl SingleVarDeclaratorVisitor {
  pub fn new(context: Context) -> Self {
    Self { context }
  }
}

impl Visit for SingleVarDeclaratorVisitor {
  fn visit_var_decl(&mut self, var_decl: &VarDecl, _parent: &dyn Node) {
    if var_decl.decls.len() > 1 {
      self.context.add_diagnostic(
        var_decl.span,
        "single-var-declarator",
        "Multiple variable declarators are not allowed",
      );
    }
  }
}

#[cfg(test)]
mod tests {
  use super::*;
  use crate::test_util::*;

  #[test]
  fn single_var_declarator_test() {
    assert_lint_err::<SingleVarDeclarator>(
      r#"const a1 = "a", b1 = "b", c1 = "c";"#,
      0,
    );
    assert_lint_err::<SingleVarDeclarator>(
      r#"let a2 = "a", b2 = "b", c2 = "c";"#,
      0,
    );
    assert_lint_err::<SingleVarDeclarator>(
      r#"var a3 = "a", b3 = "b", c3 = "c";"#,
      0,
    );
  }
}