Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement most of the Eslint plugin promise #4252

Draft
wants to merge 13 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions apps/oxlint/src/command/lint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -223,6 +223,10 @@ pub struct EnablePlugins {
/// Enable the React performance plugin and detect rendering performance problems
#[bpaf(switch, hide_usage)]
pub react_perf_plugin: bool,

/// Enable the promise plugin and detect promise usage problems
#[bpaf(switch, hide_usage)]
pub promise_plugin: bool,
}

#[cfg(test)]
Expand Down
3 changes: 2 additions & 1 deletion apps/oxlint/src/lint/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,8 @@ impl Runner for LintRunner {
.with_vitest_plugin(enable_plugins.vitest_plugin)
.with_jsx_a11y_plugin(enable_plugins.jsx_a11y_plugin)
.with_nextjs_plugin(enable_plugins.nextjs_plugin)
.with_react_perf_plugin(enable_plugins.react_perf_plugin);
.with_react_perf_plugin(enable_plugins.react_perf_plugin)
.with_promise_plugin(enable_plugins.promise_plugin);

let linter = match Linter::from_options(lint_options) {
Ok(lint_service) => lint_service,
Expand Down
31 changes: 31 additions & 0 deletions crates/oxc_linter/src/ast_util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -403,3 +403,34 @@ pub fn is_function_node(node: &AstNode) -> bool {
_ => false,
}
}

pub fn is_promise(call_expr: &CallExpression) -> bool {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Move to utils::promise instead.

let Some(member_expr) = call_expr.callee.get_member_expr() else {
return false;
};

let Some(prop_name) = member_expr.static_property_name() else {
return false;
};

// hello.then(), hello.catch(), hello.finally()
if matches!(prop_name, "then" | "catch" | "finally") {
return true;
}

// foo().then(foo => {}), needed?
if let Expression::CallExpression(inner_call_expr) = member_expr.object() {
return is_promise(inner_call_expr);
}

if member_expr.object().is_specific_id("Promise")
&& matches!(
prop_name,
"resolve" | "reject" | "all" | "allSettled" | "race" | "any" | "withResolvers"
)
{
return true;
}

false
}
9 changes: 9 additions & 0 deletions crates/oxc_linter/src/options.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ pub struct LintOptions {
pub jsx_a11y_plugin: bool,
pub nextjs_plugin: bool,
pub react_perf_plugin: bool,
pub promise_plugin: bool,
}

impl Default for LintOptions {
Expand All @@ -48,6 +49,7 @@ impl Default for LintOptions {
jsx_a11y_plugin: false,
nextjs_plugin: false,
react_perf_plugin: false,
promise_plugin: false,
}
}
}
Expand Down Expand Up @@ -138,6 +140,12 @@ impl LintOptions {
self.react_perf_plugin = yes;
self
}

#[must_use]
pub fn with_promise_plugin(mut self, yes: bool) -> Self {
self.promise_plugin = yes;
self
}
}

#[derive(Debug, Clone, Copy, Eq, PartialEq)]
Expand Down Expand Up @@ -342,6 +350,7 @@ impl LintOptions {
"react_perf" => self.react_perf_plugin,
"oxc" => self.oxc_plugin,
"eslint" | "tree_shaking" => true,
"promise" => self.promise_plugin,
name => panic!("Unhandled plugin: {name}"),
})
.cloned()
Expand Down
23 changes: 23 additions & 0 deletions crates/oxc_linter/src/rules.rs
Original file line number Diff line number Diff line change
Expand Up @@ -432,6 +432,19 @@ mod tree_shaking {
pub mod no_side_effects_in_initialization;
}

mod promise {
pub mod avoid_new;
pub mod catch_or_return;
pub mod no_callback_in_promise;
pub mod no_new_statics;
pub mod no_promise_in_callback;
pub mod no_return_in_finally;
pub mod no_return_wrap;
pub mod param_names;
pub mod prefer_await_to_then;
pub mod valid_params;
}

oxc_macros::declare_all_lint_rules! {
eslint::array_callback_return,
eslint::constructor_super,
Expand Down Expand Up @@ -822,4 +835,14 @@ oxc_macros::declare_all_lint_rules! {
jsdoc::require_returns_type,
jsdoc::require_yields,
tree_shaking::no_side_effects_in_initialization,
promise::avoid_new,
promise::no_new_statics,
promise::param_names,
promise::valid_params,
promise::no_return_in_finally,
promise::no_return_wrap,
promise::no_promise_in_callback,
promise::prefer_await_to_then,
promise::no_callback_in_promise,
promise::catch_or_return,
}
69 changes: 69 additions & 0 deletions crates/oxc_linter/src/rules/promise/avoid_new.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
use oxc_ast::{ast::Expression, AstKind};
use oxc_diagnostics::OxcDiagnostic;
use oxc_macros::declare_oxc_lint;
use oxc_span::Span;

use crate::{context::LintContext, rule::Rule, AstNode};

fn avoid_new_promise_diagnostic(span0: Span) -> OxcDiagnostic {
OxcDiagnostic::warn("eslint-plugin-promise(avoid-new): Avoid creating new promises")
.with_label(span0)
}

#[derive(Debug, Default, Clone)]
pub struct AvoidNew;

declare_oxc_lint!(
/// ### What it does
///
/// Disallow creating new promises outside of utility libs.
///
/// ### Why is this bad?
///
/// If you dislike the new promise style promises.
///
/// ### Example
/// ```javascript
/// new Promise((resolve, reject) => { ... });
/// ```
AvoidNew,
style,
);

impl Rule for AvoidNew {
fn run<'a>(&self, node: &AstNode<'a>, ctx: &LintContext<'a>) {
let AstKind::NewExpression(expr) = node.kind() else {
return;
};

let Expression::Identifier(ident) = &expr.callee else {
return;
};

if ident.name == "Promise" && ctx.semantic().is_reference_to_global_variable(ident) {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm wondering what is common in oxlint here, there is:

        let AstKind::NewExpression(new_expr) = node.kind() else {
            return;
        };
        if !new_expr.callee.is_specific_id("Array") {
            return;
        }

Which would also run for:

class Array {};

const list = new Array(5).map(_ => {});

So that seems like it should be refactored?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

And maybe we should get is_global_id("Array", ctx) which also checks if the global reference.

ctx.diagnostic(avoid_new_promise_diagnostic(expr.span));
}
}
}

#[test]
fn test() {
use crate::tester::Tester;

let pass = vec![
"Promise.resolve()",
"Promise.reject()",
"Promise.all()",
"new Horse()",
"new PromiseLikeThing()",
"new Promise.resolve()",
];

let fail = vec![
"var x = new Promise(function (x, y) {})",
"new Promise()",
"Thing(new Promise(() => {}))",
];

Tester::new(AvoidNew::NAME, pass, fail).test_and_snapshot();
}
Loading
Loading