feat(linter/eslint): Implement no-new (#3368)

Rule Detail:
[link](https://eslint.org/docs/latest/rules/no-new)
This commit is contained in:
Jelle van der Waa 2024-05-20 18:28:04 +02:00 committed by GitHub
parent 2b5b3fd22a
commit 74be8b146c
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 68 additions and 0 deletions

View file

@ -72,6 +72,7 @@ mod eslint {
pub mod no_irregular_whitespace;
pub mod no_iterator;
pub mod no_loss_of_precision;
pub mod no_new;
pub mod no_new_native_nonconstructor;
pub mod no_new_wrappers;
pub mod no_nonoctal_decimal_escape;
@ -438,6 +439,7 @@ oxc_macros::declare_all_lint_rules! {
eslint::no_irregular_whitespace,
eslint::no_iterator,
eslint::no_loss_of_precision,
eslint::no_new,
eslint::no_new_wrappers,
eslint::no_nonoctal_decimal_escape,
eslint::no_obj_calls,

View file

@ -0,0 +1,57 @@
use oxc_ast::AstKind;
use oxc_diagnostics::OxcDiagnostic;
use oxc_macros::declare_oxc_lint;
use oxc_span::Span;
use crate::{context::LintContext, rule::Rule, AstNode};
fn no_new_diagnostic(span0: Span) -> OxcDiagnostic {
OxcDiagnostic::warn("eslint(no-new): Do not use 'new' for side effects.")
.with_labels([span0.into()])
}
#[derive(Debug, Default, Clone)]
pub struct NoNew;
declare_oxc_lint!(
/// ### What it does
///
/// Disallow new operators outside of assignments or comparisons.
///
/// ### Why is this bad?
///
/// Calling new without assigning or comparing it the reference is thrown away and in many
/// cases the constructor can be replaced with a function.
///
/// ### Example
/// ```javascript
/// new Person();
/// ```
NoNew,
suspicious,
);
impl Rule for NoNew {
fn run<'a>(&self, node: &AstNode<'a>, ctx: &LintContext<'a>) {
let AstKind::NewExpression(expr) = node.kind() else {
return;
};
if let Some(parent_node) = ctx.nodes().parent_node(node.id()) {
if matches!(parent_node.kind(), AstKind::ExpressionStatement(_)) {
ctx.diagnostic(no_new_diagnostic(expr.span));
}
}
}
}
#[test]
fn test() {
use crate::tester::Tester;
let pass = vec!["var a = new Date()", "var a; if (a === new Date()) { a = false; }"];
let fail = vec!["new Date()"];
Tester::new(NoNew::NAME, pass, fail).test_and_snapshot();
}

View file

@ -0,0 +1,9 @@
---
source: crates/oxc_linter/src/tester.rs
expression: no_new
---
⚠ eslint(no-new): Do not use 'new' for side effects.
╭─[no_new.tsx:1:1]
1 │ new Date()
· ──────────
╰────