|
| 1 | +use oxc_ast::{ |
| 2 | + ast::{Argument, Expression, FormalParameters, MemberExpression}, |
| 3 | + AstKind, |
| 4 | +}; |
| 5 | +use oxc_diagnostics::OxcDiagnostic; |
| 6 | +use oxc_macros::declare_oxc_lint; |
| 7 | +use oxc_semantic::NodeId; |
| 8 | +use oxc_span::{GetSpan, Span}; |
| 9 | + |
| 10 | +use crate::{context::LintContext, rule::Rule, AstNode}; |
| 11 | + |
| 12 | +fn prefer_await_to_callbacks(span: Span) -> OxcDiagnostic { |
| 13 | + OxcDiagnostic::warn("Prefer `async`/`await` to the callback pattern").with_label(span) |
| 14 | +} |
| 15 | + |
| 16 | +#[derive(Debug, Default, Clone)] |
| 17 | +pub struct PreferAwaitToCallbacks; |
| 18 | + |
| 19 | +declare_oxc_lint!( |
| 20 | + /// ### What it does |
| 21 | + /// |
| 22 | + /// The rule encourages the use of `async/await` for handling asynchronous code |
| 23 | + /// instead of traditional callback functions. `async/await`, introduced in ES2017, |
| 24 | + /// provides a clearer and more concise syntax for writing asynchronous code, |
| 25 | + /// making it easier to read and maintain. |
| 26 | + /// |
| 27 | + /// ### Why is this bad? |
| 28 | + /// |
| 29 | + /// Using callbacks can lead to complex, nested structures known as "callback hell," |
| 30 | + /// which make code difficult to read and maintain. Additionally, error handling can |
| 31 | + /// become cumbersome with callbacks, whereas `async/await` allows for more straightforward |
| 32 | + /// try/catch blocks for managing errors. |
| 33 | + /// |
| 34 | + /// ### Examples |
| 35 | + /// |
| 36 | + /// Examples of **incorrect** code for this rule: |
| 37 | + /// ```js |
| 38 | + /// cb() |
| 39 | + /// callback() |
| 40 | + /// doSomething(arg, (err) => {}) |
| 41 | + /// function doSomethingElse(cb) {} |
| 42 | + /// ``` |
| 43 | + /// |
| 44 | + /// Examples of **correct** code for this rule: |
| 45 | + /// ```js |
| 46 | + /// await doSomething(arg) |
| 47 | + /// async function doSomethingElse() {} |
| 48 | + /// function* generator() { |
| 49 | + /// yield yieldValue(err => {}) |
| 50 | + /// } |
| 51 | + /// eventEmitter.on('error', err => {}) |
| 52 | + /// ``` |
| 53 | + PreferAwaitToCallbacks, |
| 54 | + style, |
| 55 | +); |
| 56 | + |
| 57 | +impl Rule for PreferAwaitToCallbacks { |
| 58 | + fn run<'a>(&self, node: &AstNode<'a>, ctx: &LintContext<'a>) { |
| 59 | + match node.kind() { |
| 60 | + AstKind::CallExpression(expr) => { |
| 61 | + let callee_name = expr.callee.get_identifier_reference().map(|id| id.name.as_str()); |
| 62 | + if matches!(callee_name, Some("callback" | "cb")) { |
| 63 | + ctx.diagnostic(prefer_await_to_callbacks(expr.span)); |
| 64 | + return; |
| 65 | + } |
| 66 | + |
| 67 | + if let Some(last_arg) = expr.arguments.last() { |
| 68 | + let args = match last_arg { |
| 69 | + Argument::FunctionExpression(expr) => &expr.params, |
| 70 | + Argument::ArrowFunctionExpression(expr) => &expr.params, |
| 71 | + _ => return, |
| 72 | + }; |
| 73 | + |
| 74 | + let callee_property_name = expr |
| 75 | + .callee |
| 76 | + .as_member_expression() |
| 77 | + .and_then(MemberExpression::static_property_name); |
| 78 | + |
| 79 | + if matches!(callee_property_name, Some("on" | "once")) { |
| 80 | + return; |
| 81 | + } |
| 82 | + |
| 83 | + let is_lodash = expr.callee.as_member_expression().map_or(false, |mem_expr| { |
| 84 | + matches!(mem_expr.object(), Expression::Identifier(id) if matches!(id.name.as_str(), "_" | "lodash" | "underscore")) |
| 85 | + }); |
| 86 | + |
| 87 | + let calls_array_method = callee_property_name |
| 88 | + .is_some_and(Self::is_array_method) |
| 89 | + && (expr.arguments.len() == 1 || (expr.arguments.len() == 2 && is_lodash)); |
| 90 | + |
| 91 | + let is_array_method = |
| 92 | + callee_name.is_some_and(Self::is_array_method) && expr.arguments.len() == 2; |
| 93 | + |
| 94 | + if calls_array_method || is_array_method { |
| 95 | + return; |
| 96 | + } |
| 97 | + |
| 98 | + let Some(param) = args.items.first() else { |
| 99 | + return; |
| 100 | + }; |
| 101 | + |
| 102 | + if matches!(param.pattern.get_identifier().as_deref(), Some("err" | "error")) |
| 103 | + && !Self::is_inside_yield_or_await(node.id(), ctx) |
| 104 | + { |
| 105 | + ctx.diagnostic(prefer_await_to_callbacks(last_arg.span())); |
| 106 | + } |
| 107 | + } |
| 108 | + } |
| 109 | + AstKind::Function(func) => { |
| 110 | + Self::check_last_params_for_callback(&func.params, ctx); |
| 111 | + } |
| 112 | + AstKind::ArrowFunctionExpression(expr) => { |
| 113 | + Self::check_last_params_for_callback(&expr.params, ctx); |
| 114 | + } |
| 115 | + _ => {} |
| 116 | + } |
| 117 | + } |
| 118 | +} |
| 119 | + |
| 120 | +impl PreferAwaitToCallbacks { |
| 121 | + fn check_last_params_for_callback(params: &FormalParameters, ctx: &LintContext) { |
| 122 | + let Some(param) = params.items.last() else { |
| 123 | + return; |
| 124 | + }; |
| 125 | + |
| 126 | + let id = param.pattern.get_identifier(); |
| 127 | + if matches!(id.as_deref(), Some("callback" | "cb")) { |
| 128 | + ctx.diagnostic(prefer_await_to_callbacks(param.span)); |
| 129 | + } |
| 130 | + } |
| 131 | + |
| 132 | + fn is_inside_yield_or_await(id: NodeId, ctx: &LintContext) -> bool { |
| 133 | + ctx.nodes().iter_parents(id).skip(1).any(|parent| { |
| 134 | + matches!(parent.kind(), AstKind::AwaitExpression(_) | AstKind::YieldExpression(_)) |
| 135 | + }) |
| 136 | + } |
| 137 | + |
| 138 | + fn is_array_method(name: &str) -> bool { |
| 139 | + ["map", "every", "forEach", "some", "find", "filter"].contains(&name) |
| 140 | + } |
| 141 | +} |
| 142 | + |
| 143 | +#[test] |
| 144 | +fn test() { |
| 145 | + use crate::tester::Tester; |
| 146 | + |
| 147 | + let pass = vec![ |
| 148 | + "async function hi() { await thing().catch(err => console.log(err)) }", |
| 149 | + "async function hi() { await thing().then() }", |
| 150 | + "async function hi() { await thing().catch() }", |
| 151 | + r#"dbConn.on("error", err => { console.error(err) })"#, |
| 152 | + r#"dbConn.once("error", err => { console.error(err) })"#, |
| 153 | + "heart(something => {})", |
| 154 | + "getErrors().map(error => responseTo(error))", |
| 155 | + "errors.filter(err => err.status === 402)", |
| 156 | + r#"errors.some(err => err.message.includes("Yo"))"#, |
| 157 | + "errors.every(err => err.status === 402)", |
| 158 | + "errors.filter(err => console.log(err))", |
| 159 | + r#"const error = errors.find(err => err.stack.includes("file.js"))"#, |
| 160 | + "this.myErrors.forEach(function(error) { log(error); })", |
| 161 | + r#"find(errors, function(err) { return err.type === "CoolError" })"#, |
| 162 | + r#"map(errors, function(error) { return err.type === "CoolError" })"#, |
| 163 | + r#"_.find(errors, function(error) { return err.type === "CoolError" })"#, |
| 164 | + r#"_.map(errors, function(err) { return err.type === "CoolError" })"#, |
| 165 | + ]; |
| 166 | + |
| 167 | + let fail = vec![ |
| 168 | + "heart(function(err) {})", |
| 169 | + "heart(err => {})", |
| 170 | + r#"heart("ball", function(err) {})"#, |
| 171 | + "function getData(id, callback) {}", |
| 172 | + "const getData = (cb) => {}", |
| 173 | + "var x = function (x, cb) {}", |
| 174 | + "cb()", |
| 175 | + "callback()", |
| 176 | + "heart(error => {})", |
| 177 | + "async.map(files, fs.stat, function(err, results) { if (err) throw err; });", |
| 178 | + "_.map(files, fs.stat, function(err, results) { if (err) throw err; });", |
| 179 | + "map(files, fs.stat, function(err, results) { if (err) throw err; });", |
| 180 | + "map(function(err, results) { if (err) throw err; });", |
| 181 | + "customMap(errors, (err) => err.message)", |
| 182 | + ]; |
| 183 | + |
| 184 | + Tester::new(PreferAwaitToCallbacks::NAME, pass, fail).test_and_snapshot(); |
| 185 | +} |
0 commit comments