Skip to content

Commit

Permalink
feat(linter): implement no-negated-condition rule
Browse files Browse the repository at this point in the history
  • Loading branch information
baseballyama committed Dec 27, 2024
1 parent 1c5db72 commit b6f15b8
Show file tree
Hide file tree
Showing 3 changed files with 168 additions and 0 deletions.
2 changes: 2 additions & 0 deletions crates/oxc_linter/src/rules.rs
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,7 @@ mod eslint {
pub mod no_loss_of_precision;
pub mod no_magic_numbers;
pub mod no_multi_str;
pub mod no_negated_condition;
pub mod no_new;
pub mod no_new_func;
pub mod no_new_native_nonconstructor;
Expand Down Expand Up @@ -586,6 +587,7 @@ oxc_macros::declare_all_lint_rules! {
eslint::no_loss_of_precision,
eslint::no_magic_numbers,
eslint::no_multi_str,
eslint::no_negated_condition,
eslint::no_new_func,
eslint::no_new_native_nonconstructor,
eslint::no_new_wrappers,
Expand Down
127 changes: 127 additions & 0 deletions crates/oxc_linter/src/rules/eslint/no_negated_condition.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
use crate::{context::LintContext, rule::Rule, AstNode};
use oxc_ast::ast::{ConditionalExpression, Expression, IfStatement, Statement};
use oxc_ast::AstKind;
use oxc_diagnostics::OxcDiagnostic;
use oxc_macros::declare_oxc_lint;
use oxc_span::{GetSpan, Span};
use oxc_syntax::operator::{BinaryOperator, UnaryOperator};

fn no_negated_condition_diagnostic(span: Span) -> OxcDiagnostic {
OxcDiagnostic::warn("Unexpected negated condition.").with_label(span)
}

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

declare_oxc_lint!(
/// ### What it does
///
/// This rule disallows the use of negated conditions in `if` statements to improve readability.
///
/// ### Why is this bad?
///
/// Negated conditions can make code harder to read and understand, especially in complex logic.
/// It is often clearer to use positive conditions or to refactor the code structure.
///
/// ### Examples
///
/// Examples of **incorrect** code for this rule:
/// ```js
/// if (!isReady) {
/// doSomething();
/// } else {
/// doSomethingElse();
/// }
/// ```
///
/// Examples of **correct** code for this rule:
/// ```js
/// if (isReady) {
/// doSomethingElse();
/// } else {
/// doSomething();
/// }
/// ```
NoNegatedCondition,
style,
);

impl Rule for NoNegatedCondition {
fn run<'a>(&self, node: &AstNode<'a>, ctx: &LintContext<'a>) {
match node.kind() {
AstKind::IfStatement(if_stmt) => {
if !has_else_without_condition(if_stmt) {
return;
}

if is_negated_if(if_stmt) {
ctx.diagnostic(no_negated_condition_diagnostic(node.span()));
}
}
AstKind::ConditionalExpression(conditional_expr) => {
if is_negated_if_conditional(conditional_expr) {
ctx.diagnostic(no_negated_condition_diagnostic(node.span()));
}
}
_ => {}
}
}
}

fn has_else_without_condition(node: &IfStatement) -> bool {
matches!(node.alternate, Some(Statement::BlockStatement(_)))
}

fn is_negated_unary_expression(test: &Expression) -> bool {
matches!(test, Expression::UnaryExpression(unary) if unary.operator == UnaryOperator::LogicalNot)
}

fn is_negated_binary_expression(test: &Expression) -> bool {
matches!(
test,
Expression::BinaryExpression(binary)
if binary.operator == BinaryOperator::Inequality
|| binary.operator == BinaryOperator::StrictInequality
)
}

fn is_negated_if(node: &IfStatement) -> bool {
is_negated_unary_expression(&node.test) || is_negated_binary_expression(&node.test)
}

fn is_negated_if_conditional(node: &ConditionalExpression) -> bool {
is_negated_unary_expression(&node.test) || is_negated_binary_expression(&node.test)
}

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

let pass = vec![
"if (a) {}",
"if (a) {} else {}",
"if (!a) {}",
"if (!a) {} else if (b) {}",
"if (!a) {} else if (b) {} else {}",
"if (a == b) {}",
"if (a == b) {} else {}",
"if (a != b) {}",
"if (a != b) {} else if (b) {}",
"if (a != b) {} else if (b) {} else {}",
"if (a !== b) {}",
"if (a === b) {} else {}",
"a ? b : c",
];

let fail = vec![
"if (!a) {;} else {;}",
"if (a != b) {;} else {;}",
"if (a !== b) {;} else {;}",
"!a ? b : c",
"a != b ? c : d",
"a !== b ? c : d",
];

Tester::new(NoNegatedCondition::NAME, NoNegatedCondition::CATEGORY, pass, fail)
.test_and_snapshot();
}
39 changes: 39 additions & 0 deletions crates/oxc_linter/src/snapshots/eslint_no_negated_condition.snap
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
---
source: crates/oxc_linter/src/tester.rs
snapshot_kind: text
---
eslint(no-negated-condition): Unexpected negated condition.
╭─[no_negated_condition.tsx:1:1]
1if (!a) {;} else {;}
· ────────────────────
╰────

eslint(no-negated-condition): Unexpected negated condition.
╭─[no_negated_condition.tsx:1:1]
1if (a != b) {;} else {;}
· ────────────────────────
╰────

eslint(no-negated-condition): Unexpected negated condition.
╭─[no_negated_condition.tsx:1:1]
1if (a !== b) {;} else {;}
· ─────────────────────────
╰────

eslint(no-negated-condition): Unexpected negated condition.
╭─[no_negated_condition.tsx:1:1]
1!a ? b : c
· ──────────
╰────

eslint(no-negated-condition): Unexpected negated condition.
╭─[no_negated_condition.tsx:1:1]
1a != b ? c : d
· ──────────────
╰────

eslint(no-negated-condition): Unexpected negated condition.
╭─[no_negated_condition.tsx:1:1]
1a !== b ? c : d
· ───────────────
╰────

0 comments on commit b6f15b8

Please sign in to comment.