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
// 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::Expr;
use crate::swc_ecma_ast::NewExpr;
use swc_ecma_visit::Node;
use swc_ecma_visit::Visit;

pub struct NoAsyncPromiseExecutor;

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

  fn code(&self) -> &'static str {
    "no-async-promise-executor"
  }

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

struct NoAsyncPromiseExecutorVisitor {
  context: Context,
}

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

impl Visit for NoAsyncPromiseExecutorVisitor {
  fn visit_new_expr(&mut self, new_expr: &NewExpr, _parent: &dyn Node) {
    if let Expr::Ident(ident) = &*new_expr.callee {
      let name = ident.sym.to_string();
      if name != "Promise" {
        return;
      }

      if let Some(args) = &new_expr.args {
        if let Some(first_arg) = args.get(0) {
          let is_async = match &*first_arg.expr {
            Expr::Fn(fn_expr) => fn_expr.function.is_async,
            Expr::Arrow(arrow_expr) => arrow_expr.is_async,
            _ => return,
          };

          if is_async {
            self.context.add_diagnostic(
              new_expr.span,
              "no-async-promise-executor",
              "Async promise executors are not allowed",
            );
          }
        }
      }
    }
  }
}

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

  #[test]
  fn no_async_promise_executor_test() {
    assert_lint_ok_n::<NoAsyncPromiseExecutor>(vec![
      "new Promise(function(a, b) {});",
      "new Promise((a, b) => {});",
    ]);
    assert_lint_err::<NoAsyncPromiseExecutor>(
      "new Promise(async function(a, b) {});",
      0,
    );
    assert_lint_err::<NoAsyncPromiseExecutor>(
      "new Promise(async (a, b) => {});",
      0,
    );
  }
}