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
// 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::{TsModuleDecl, TsModuleName};
use swc_ecma_visit::Node;
use swc_ecma_visit::Visit;

pub struct NoNamespace;

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

  fn code(&self) -> &'static str {
    "no-namespace"
  }

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

struct NoNamespaceVisitor {
  context: Context,
}

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

impl Visit for NoNamespaceVisitor {
  fn visit_ts_module_decl(
    &mut self,
    mod_decl: &TsModuleDecl,
    parent: &dyn Node,
  ) {
    if !mod_decl.global {
      if let TsModuleName::Ident(_) = mod_decl.id {
        self.context.add_diagnostic(
          mod_decl.span,
          "no-namespace",
          "custom typescript modules are outdated",
        );
      }
    }
    for stmt in &mod_decl.body {
      self.visit_ts_namespace_body(stmt, parent);
    }
  }
}

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

  #[test]
  fn no_namespace_valid() {
    assert_lint_ok::<NoNamespace>(r#"declare global {}"#);
    assert_lint_ok::<NoNamespace>(r#"declare module 'foo' {}"#);
  }
  #[test]
  fn no_namespace_invalid() {
    assert_lint_err::<NoNamespace>("module foo {}", 0);
    assert_lint_err::<NoNamespace>("declare module foo {}", 0);
    assert_lint_err::<NoNamespace>("namespace foo {}", 0);
    assert_lint_err::<NoNamespace>("declare namespace foo {}", 0);
    assert_lint_err_n::<NoNamespace>(
      "namespace Foo.Bar { namespace Baz.Bas {} }",
      vec![0, 20],
    );
  }
}