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

feat(linter): implement no-throw-literal #6144

Merged
merged 7 commits into from
Oct 7, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
2 changes: 2 additions & 0 deletions crates/oxc_linter/src/rules.rs
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,7 @@ mod eslint {
pub mod no_template_curly_in_string;
pub mod no_ternary;
pub mod no_this_before_super;
pub mod no_throw_literal;
pub mod no_undef;
pub mod no_undefined;
pub mod no_unexpected_multiline;
Expand Down Expand Up @@ -574,6 +575,7 @@ oxc_macros::declare_all_lint_rules! {
eslint::no_template_curly_in_string,
eslint::no_ternary,
eslint::no_this_before_super,
eslint::no_throw_literal,
eslint::no_undef,
eslint::no_undefined,
eslint::no_unexpected_multiline,
Expand Down
197 changes: 197 additions & 0 deletions crates/oxc_linter/src/rules/eslint/no_throw_literal.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,197 @@
use oxc_ast::{
ast::{AssignmentOperator, AssignmentTarget, Expression, LogicalOperator},
AstKind,
};
use oxc_diagnostics::OxcDiagnostic;
use oxc_macros::declare_oxc_lint;
use oxc_span::Span;

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

fn no_throw_literal_diagnostic(span: Span, is_undef: bool) -> OxcDiagnostic {
let message =
if is_undef { "Do not throw undefined." } else { "Expected an error object to be thrown." };

OxcDiagnostic::warn("Disallow throwing literals as exceptions")
shulaoda marked this conversation as resolved.
Show resolved Hide resolved
.with_help(message)
.with_label(span)
}

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

declare_oxc_lint!(
/// ### What it does
///
/// Disallows throwing literals or non-Error objects as exceptions.
///
/// ### Why is this bad?
///
/// It is considered good practice to only throw the Error object itself or an object using
/// the Error object as base objects for user-defined exceptions. The fundamental benefit of
/// Error objects is that they automatically keep track of where they were built and originated.
///
/// ### Examples
///
/// Examples of **incorrect** code for this rule:
/// ```js
/// throw "error";
///
/// throw 0;
///
/// throw undefined;
///
/// throw null;
///
/// var err = new Error();
/// throw "an " + err;
/// // err is recast to a string literal
///
/// var err = new Error();
/// throw `${err}`
/// ```
///
/// Examples of **correct** code for this rule:
/// ```js
/// throw new Error();
///
/// throw new Error("error");
///
/// var e = new Error("error");
/// throw e;
///
/// try {
/// throw new Error("error");
/// } catch (e) {
/// throw e;
/// }
/// ```
NoThrowLiteral,
correctness,
DonIsaac marked this conversation as resolved.
Show resolved Hide resolved
);

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

if !Self::could_be_error(&stmt.argument) {
ctx.diagnostic(no_throw_literal_diagnostic(stmt.span, false));
} else if matches!(&stmt.argument, Expression::Identifier(id) if id.name == "undefined") {
ctx.diagnostic(no_throw_literal_diagnostic(stmt.span, true));
};
}
}

impl NoThrowLiteral {
fn could_be_error(expr: &Expression) -> bool {
match expr {
shulaoda marked this conversation as resolved.
Show resolved Hide resolved
Expression::Identifier(_)
DonIsaac marked this conversation as resolved.
Show resolved Hide resolved
| Expression::NewExpression(_)
| Expression::AwaitExpression(_)
| Expression::CallExpression(_)
| Expression::ChainExpression(_)
| Expression::YieldExpression(_)
| Expression::PrivateFieldExpression(_)
| Expression::StaticMemberExpression(_)
| Expression::ComputedMemberExpression(_)
| Expression::TaggedTemplateExpression(_) => true,
Expression::AssignmentExpression(expr) => {
if matches!(
expr.operator,
AssignmentOperator::Assign | AssignmentOperator::LogicalAnd
) {
return Self::could_be_error(&expr.right);
}

if matches!(
expr.operator,
AssignmentOperator::LogicalOr | AssignmentOperator::LogicalNullish
) {
return matches!(
expr.left,
AssignmentTarget::AssignmentTargetIdentifier(_)
| AssignmentTarget::PrivateFieldExpression(_)
| AssignmentTarget::StaticMemberExpression(_)
| AssignmentTarget::ComputedMemberExpression(_)
) || Self::could_be_error(&expr.right);
}

false
}
Expression::SequenceExpression(expr) => {
if expr.expressions.len() > 0 {
return Self::could_be_error(expr.expressions.last().unwrap());
shulaoda marked this conversation as resolved.
Show resolved Hide resolved
}

false
}
Expression::LogicalExpression(expr) => {
if matches!(expr.operator, LogicalOperator::And) {
return Self::could_be_error(&expr.right);
}

Self::could_be_error(&expr.left) || Self::could_be_error(&expr.right)
}
Expression::ConditionalExpression(expr) => {
Self::could_be_error(&expr.consequent) || Self::could_be_error(&expr.alternate)
}
_ => false,
}
}
}

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

let pass = vec![
"throw new Error();",
"throw new Error('error');",
"throw Error('error');",
"var e = new Error(); throw e;",
"try {throw new Error();} catch (e) {throw e;};",
"throw a;",
"throw foo();",
"throw new foo();",
"throw foo.bar;",
"throw foo[bar];",
"class C { #field; foo() { throw foo.#field; } }", // { "ecmaVersion": 2022 },
"throw foo = new Error();",
"throw foo.bar ||= 'literal'", // { "ecmaVersion": 2021 },
"throw foo[bar] ??= 'literal'", // { "ecmaVersion": 2021 },
"throw 1, 2, new Error();",
"throw 'literal' && new Error();",
"throw new Error() || 'literal';",
"throw foo ? new Error() : 'literal';",
"throw foo ? 'literal' : new Error();",
"throw tag `${foo}`;", // { "ecmaVersion": 6 },
"function* foo() { var index = 0; throw yield index++; }", // { "ecmaVersion": 6 },
"async function foo() { throw await bar; }", // { "ecmaVersion": 8 },
"throw obj?.foo", // { "ecmaVersion": 2020 },
"throw obj?.foo()", // { "ecmaVersion": 2020 }
];
shulaoda marked this conversation as resolved.
Show resolved Hide resolved

let fail = vec![
"throw 'error';",
"throw 0;",
"throw false;",
"throw null;",
"throw {};",
"throw undefined;",
"throw 'a' + 'b';",
"var b = new Error(); throw 'a' + b;",
"throw foo = 'error';",
"throw foo += new Error();",
"throw foo &= new Error();",
"throw foo &&= 'literal'", // { "ecmaVersion": 2021 },
"throw new Error(), 1, 2, 3;",
"throw 'literal' && 'not an Error';",
"throw foo && 'literal'",
"throw foo ? 'not an Error' : 'literal';",
"throw `${err}`;", // { "ecmaVersion": 6 }
];

Tester::new(NoThrowLiteral::NAME, pass, fail).test_and_snapshot();
}
121 changes: 121 additions & 0 deletions crates/oxc_linter/src/snapshots/no_throw_literal.snap
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
---
source: crates/oxc_linter/src/tester.rs
---
⚠ eslint(no-throw-literal): Disallow throwing literals as exceptions
╭─[no_throw_literal.tsx:1:1]
1 │ throw 'error';
shulaoda marked this conversation as resolved.
Show resolved Hide resolved
· ──────────────
╰────
help: Expected an error object to be thrown.

⚠ eslint(no-throw-literal): Disallow throwing literals as exceptions
╭─[no_throw_literal.tsx:1:1]
1 │ throw 0;
· ────────
╰────
help: Expected an error object to be thrown.

⚠ eslint(no-throw-literal): Disallow throwing literals as exceptions
╭─[no_throw_literal.tsx:1:1]
1 │ throw false;
· ────────────
╰────
help: Expected an error object to be thrown.

⚠ eslint(no-throw-literal): Disallow throwing literals as exceptions
╭─[no_throw_literal.tsx:1:1]
1 │ throw null;
· ───────────
╰────
help: Expected an error object to be thrown.

⚠ eslint(no-throw-literal): Disallow throwing literals as exceptions
╭─[no_throw_literal.tsx:1:1]
1 │ throw {};
· ─────────
╰────
help: Expected an error object to be thrown.

⚠ eslint(no-throw-literal): Disallow throwing literals as exceptions
╭─[no_throw_literal.tsx:1:1]
1 │ throw undefined;
· ────────────────
╰────
help: Do not throw undefined.

⚠ eslint(no-throw-literal): Disallow throwing literals as exceptions
╭─[no_throw_literal.tsx:1:1]
1 │ throw 'a' + 'b';
· ────────────────
╰────
help: Expected an error object to be thrown.

⚠ eslint(no-throw-literal): Disallow throwing literals as exceptions
╭─[no_throw_literal.tsx:1:22]
1 │ var b = new Error(); throw 'a' + b;
· ──────────────
╰────
help: Expected an error object to be thrown.

⚠ eslint(no-throw-literal): Disallow throwing literals as exceptions
╭─[no_throw_literal.tsx:1:1]
1 │ throw foo = 'error';
· ────────────────────
╰────
help: Expected an error object to be thrown.

⚠ eslint(no-throw-literal): Disallow throwing literals as exceptions
╭─[no_throw_literal.tsx:1:1]
1 │ throw foo += new Error();
· ─────────────────────────
╰────
help: Expected an error object to be thrown.

⚠ eslint(no-throw-literal): Disallow throwing literals as exceptions
╭─[no_throw_literal.tsx:1:1]
1 │ throw foo &= new Error();
· ─────────────────────────
╰────
help: Expected an error object to be thrown.

⚠ eslint(no-throw-literal): Disallow throwing literals as exceptions
╭─[no_throw_literal.tsx:1:1]
1 │ throw foo &&= 'literal'
· ───────────────────────
╰────
help: Expected an error object to be thrown.

⚠ eslint(no-throw-literal): Disallow throwing literals as exceptions
╭─[no_throw_literal.tsx:1:1]
1 │ throw new Error(), 1, 2, 3;
· ───────────────────────────
╰────
help: Expected an error object to be thrown.

⚠ eslint(no-throw-literal): Disallow throwing literals as exceptions
╭─[no_throw_literal.tsx:1:1]
1 │ throw 'literal' && 'not an Error';
· ──────────────────────────────────
╰────
help: Expected an error object to be thrown.

⚠ eslint(no-throw-literal): Disallow throwing literals as exceptions
╭─[no_throw_literal.tsx:1:1]
1 │ throw foo && 'literal'
· ──────────────────────
╰────
help: Expected an error object to be thrown.

⚠ eslint(no-throw-literal): Disallow throwing literals as exceptions
╭─[no_throw_literal.tsx:1:1]
1 │ throw foo ? 'not an Error' : 'literal';
· ───────────────────────────────────────
╰────
help: Expected an error object to be thrown.

⚠ eslint(no-throw-literal): Disallow throwing literals as exceptions
╭─[no_throw_literal.tsx:1:1]
1 │ throw `${err}`;
· ───────────────
╰────
help: Expected an error object to be thrown.