Skip to content

Rewrite Check to Yoda Condition Has Fix

Description

In programming jargon, a Yoda condition is a style that places the constant portion of the expression on the left side of the conditional statement. It is used to prevent assignment errors that may occur in languages like C.

YAML

yaml
id: may-the-force-be-with-you
language: c
rule:
  pattern: $A == $B                 # Find equality comparison
  inside:                           # inside an if_statement
    kind: parenthesized_expression
    inside: {kind: if_statement}
constraints:                        # with the constraint that
  B: { kind: number_literal }       # right side is a number
fix: $B == $A

The rule targets an equality comparison, denoted by the pattern $A == $B. This comparison must occur inside an if_statement. Additionally, there’s a constraint that the right side of the comparison, $B, must be a number_literal like 42.

Example

c
if (myNumber == 42) { /* ... */}
if (notMatch == another) { /* ... */}
if (notMatch) { /* ... */}

Diff

c
if (myNumber == 42) { /* ... */}
if (42 == myNumber) { /* ... */}
if (notMatch == another) { /* ... */}
if (notMatch) { /* ... */}

Contributed by

Inspired by this thread

Made with ❤️ with Rust