-
-
Notifications
You must be signed in to change notification settings - Fork 502
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(linter): implement no-callback-in-promise
- Loading branch information
Showing
3 changed files
with
269 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
193 changes: 193 additions & 0 deletions
193
crates/oxc_linter/src/rules/promise/no_callback_in_promise.rs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,193 @@ | ||
use oxc_ast::{ | ||
ast::{Expression, MemberExpression}, | ||
AstKind, | ||
}; | ||
use oxc_diagnostics::OxcDiagnostic; | ||
use oxc_macros::declare_oxc_lint; | ||
use oxc_span::{GetSpan, Span}; | ||
|
||
use crate::{context::LintContext, rule::Rule, AstNode}; | ||
|
||
static CALLBACKS: [&str; 4] = ["done", "cb", "callback", "next"]; | ||
|
||
fn no_callback_in_promise_diagnostic(span: Span) -> OxcDiagnostic { | ||
OxcDiagnostic::warn("Avoid calling back inside of a promise").with_label(span) | ||
} | ||
|
||
#[derive(Debug, Default, Clone)] | ||
pub struct NoCallbackInPromise(Box<NoCallbackInPromiseConfig>); | ||
|
||
#[derive(Debug, Default, Clone)] | ||
pub struct NoCallbackInPromiseConfig { | ||
exceptions: Vec<String>, | ||
} | ||
|
||
impl std::ops::Deref for NoCallbackInPromise { | ||
type Target = NoCallbackInPromiseConfig; | ||
|
||
fn deref(&self) -> &Self::Target { | ||
&self.0 | ||
} | ||
} | ||
|
||
declare_oxc_lint!( | ||
/// ### What it does | ||
/// | ||
/// Disallows calling a callback function (`cb()`) inside a `Promise.prototype.then()` | ||
/// or `Promise.prototype.catch()`. | ||
/// | ||
/// ### Why is this bad? | ||
/// | ||
/// Directly invoking a callback inside a `then()` or `catch()` method can lead to | ||
/// unexpected behavior, such as the callback being called multiple times. Additionally, | ||
/// mixing the callback and promise paradigms in this way can make the code confusing | ||
/// and harder to maintain. | ||
/// | ||
/// ### Examples | ||
/// | ||
/// Examples of **incorrect** code for this rule: | ||
/// ```js | ||
/// function callback(err, data) { | ||
/// console.log('Callback got called with:', err, data) | ||
/// throw new Error('My error') | ||
/// } | ||
/// | ||
/// Promise.resolve() | ||
/// .then(() => callback(null, 'data')) | ||
/// .catch((err) => callback(err.message, null)) | ||
/// ``` | ||
/// | ||
/// Examples of **correct** code for this rule: | ||
/// ```js | ||
/// Promise.resolve() | ||
/// .then(() => setTimeout(() => callback(null, 'data'), 0)) | ||
/// .catch((err) => setTimeout(() => callback(err.message, null), 0)) | ||
/// ``` | ||
NoCallbackInPromise, | ||
correctness, | ||
); | ||
|
||
impl Rule for NoCallbackInPromise { | ||
fn from_configuration(value: serde_json::Value) -> Self { | ||
Self(Box::new(NoCallbackInPromiseConfig { | ||
exceptions: value | ||
.get(0) | ||
.and_then(|v| v.get("exceptions")) | ||
.and_then(serde_json::Value::as_array) | ||
.map(|v| { | ||
v.iter() | ||
.filter_map(serde_json::Value::as_str) | ||
.map(ToString::to_string) | ||
.collect() | ||
}) | ||
.unwrap_or_default(), | ||
})) | ||
} | ||
|
||
fn run<'a>(&self, node: &AstNode<'a>, ctx: &LintContext<'a>) { | ||
if !self.is_callback(node) { | ||
if Self::has_promise_callback(node) { | ||
let Some(call_expr) = node.kind().as_call_expression() else { | ||
return; | ||
}; | ||
|
||
let Some(id) = call_expr.arguments.first().and_then(|arg| { | ||
arg.as_expression().and_then(Expression::get_identifier_reference) | ||
}) else { | ||
return; | ||
}; | ||
|
||
let name = id.name.as_str(); | ||
if !self.exceptions.iter().any(|exception| exception == name) | ||
&& CALLBACKS.contains(&name) | ||
{ | ||
ctx.diagnostic(no_callback_in_promise_diagnostic(id.span)); | ||
} | ||
} | ||
} else if ctx | ||
.nodes() | ||
.iter_parents(node.id()) | ||
.skip(1) | ||
.any(|node| Self::is_inside_promise(node, ctx)) | ||
{ | ||
ctx.diagnostic(no_callback_in_promise_diagnostic(node.span())); | ||
} | ||
} | ||
} | ||
|
||
impl NoCallbackInPromise { | ||
fn is_inside_promise(node: &AstNode, ctx: &LintContext) -> bool { | ||
if !matches!(node.kind(), AstKind::Function(_) | AstKind::ArrowFunctionExpression(_)) | ||
|| !matches!(ctx.nodes().parent_kind(node.id()), Some(AstKind::Argument(_))) | ||
{ | ||
return false; | ||
} | ||
|
||
ctx.nodes().iter_parents(node.id()).nth(2).is_some_and(Self::has_promise_callback) | ||
} | ||
|
||
fn has_promise_callback(node: &AstNode) -> bool { | ||
let AstKind::CallExpression(call_expr) = node.kind() else { | ||
return false; | ||
}; | ||
|
||
matches!( | ||
call_expr | ||
.callee | ||
.as_member_expression() | ||
.and_then(MemberExpression::static_property_name), | ||
Some("then" | "catch") | ||
) | ||
} | ||
|
||
fn is_callback(&self, node: &AstNode) -> bool { | ||
let AstKind::CallExpression(call_expr) = node.kind() else { | ||
return false; | ||
}; | ||
|
||
call_expr.callee.get_identifier_reference().is_some_and(|id| { | ||
let callbacks: Vec<_> = CALLBACKS | ||
.iter() | ||
.filter(|&&item| !self.exceptions.iter().any(|exception| exception == item)) | ||
.collect(); | ||
|
||
callbacks.contains(&&id.name.as_str()) | ||
}) | ||
} | ||
} | ||
|
||
#[test] | ||
fn test() { | ||
use crate::tester::Tester; | ||
|
||
let pass = vec![ | ||
("function thing(cb) { cb() }", None), | ||
("doSomething(function(err) { cb(err) })", None), | ||
("function thing(callback) { callback() }", None), | ||
("doSomething(function(err) { callback(err) })", None), | ||
("let thing = (cb) => cb()", None), | ||
("doSomething(err => cb(err))", None), | ||
("a.then(() => next())", Some(serde_json::json!([{ "exceptions": ["next"] }]))), | ||
( | ||
"a.then(() => next()).catch((err) => next(err))", | ||
Some(serde_json::json!([{ "exceptions": ["next"] }])), | ||
), | ||
("a.then(next)", Some(serde_json::json!([{ "exceptions": ["next"] }]))), | ||
("a.then(next).catch(next)", Some(serde_json::json!([{ "exceptions": ["next"] }]))), | ||
]; | ||
|
||
let fail = vec![ | ||
("a.then(cb)", None), | ||
("a.then(() => cb())", None), | ||
("a.then(function(err) { cb(err) })", None), | ||
("a.then(function(data) { cb(data) }, function(err) { cb(err) })", None), | ||
("a.catch(function(err) { cb(err) })", None), | ||
("a.then(callback)", None), | ||
("a.then(() => callback())", None), | ||
("a.then(function(err) { callback(err) })", None), | ||
("a.then(function(data) { callback(data) }, function(err) { callback(err) })", None), | ||
("a.catch(function(err) { callback(err) })", None), | ||
]; | ||
|
||
Tester::new(NoCallbackInPromise::NAME, pass, fail).test_and_snapshot(); | ||
} |
74 changes: 74 additions & 0 deletions
74
crates/oxc_linter/src/snapshots/no_callback_in_promise.snap
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,74 @@ | ||
--- | ||
source: crates/oxc_linter/src/tester.rs | ||
--- | ||
⚠ eslint-plugin-promise(no-callback-in-promise): Avoid calling back inside of a promise | ||
╭─[no_callback_in_promise.tsx:1:8] | ||
1 │ a.then(cb) | ||
· ── | ||
╰──── | ||
|
||
⚠ eslint-plugin-promise(no-callback-in-promise): Avoid calling back inside of a promise | ||
╭─[no_callback_in_promise.tsx:1:14] | ||
1 │ a.then(() => cb()) | ||
· ──── | ||
╰──── | ||
|
||
⚠ eslint-plugin-promise(no-callback-in-promise): Avoid calling back inside of a promise | ||
╭─[no_callback_in_promise.tsx:1:24] | ||
1 │ a.then(function(err) { cb(err) }) | ||
· ─────── | ||
╰──── | ||
|
||
⚠ eslint-plugin-promise(no-callback-in-promise): Avoid calling back inside of a promise | ||
╭─[no_callback_in_promise.tsx:1:25] | ||
1 │ a.then(function(data) { cb(data) }, function(err) { cb(err) }) | ||
· ──────── | ||
╰──── | ||
|
||
⚠ eslint-plugin-promise(no-callback-in-promise): Avoid calling back inside of a promise | ||
╭─[no_callback_in_promise.tsx:1:53] | ||
1 │ a.then(function(data) { cb(data) }, function(err) { cb(err) }) | ||
· ─────── | ||
╰──── | ||
|
||
⚠ eslint-plugin-promise(no-callback-in-promise): Avoid calling back inside of a promise | ||
╭─[no_callback_in_promise.tsx:1:25] | ||
1 │ a.catch(function(err) { cb(err) }) | ||
· ─────── | ||
╰──── | ||
|
||
⚠ eslint-plugin-promise(no-callback-in-promise): Avoid calling back inside of a promise | ||
╭─[no_callback_in_promise.tsx:1:8] | ||
1 │ a.then(callback) | ||
· ──────── | ||
╰──── | ||
|
||
⚠ eslint-plugin-promise(no-callback-in-promise): Avoid calling back inside of a promise | ||
╭─[no_callback_in_promise.tsx:1:14] | ||
1 │ a.then(() => callback()) | ||
· ────────── | ||
╰──── | ||
|
||
⚠ eslint-plugin-promise(no-callback-in-promise): Avoid calling back inside of a promise | ||
╭─[no_callback_in_promise.tsx:1:24] | ||
1 │ a.then(function(err) { callback(err) }) | ||
· ───────────── | ||
╰──── | ||
|
||
⚠ eslint-plugin-promise(no-callback-in-promise): Avoid calling back inside of a promise | ||
╭─[no_callback_in_promise.tsx:1:25] | ||
1 │ a.then(function(data) { callback(data) }, function(err) { callback(err) }) | ||
· ────────────── | ||
╰──── | ||
|
||
⚠ eslint-plugin-promise(no-callback-in-promise): Avoid calling back inside of a promise | ||
╭─[no_callback_in_promise.tsx:1:59] | ||
1 │ a.then(function(data) { callback(data) }, function(err) { callback(err) }) | ||
· ───────────── | ||
╰──── | ||
|
||
⚠ eslint-plugin-promise(no-callback-in-promise): Avoid calling back inside of a promise | ||
╭─[no_callback_in_promise.tsx:1:25] | ||
1 │ a.catch(function(err) { callback(err) }) | ||
· ───────────── | ||
╰──── |