Skip to content

New rule: Set containment checks should be enclosed in parentheses #97

Closed
@fourls

Description

@fourls

Prerequisites

  • This rule has not already been suggested.
  • This should be a new rule, not an improvement to an existing rule.
  • This rule would be generally useful, not specific to my code or setup.

Suggested rule title

Set containment checks should be enclosed in parentheses

Rule description

In Delphi, the not unary operator is stronger than the in binary operator, meaning that not MyVar in MySet is parsed as (not MyVar) in MySet instead of the generally expected not (MyVar in MySet).

This can be particularly confusing for integers, for which not is a perfectly valid operator - the example below incorrectly prints MyByte is neither 3 or 252.

procedure RunTest;
var
  MyByte: Byte;
begin
  MyByte := 3;
  Assert(not MyByte = 252);

  if not MyByte in [3, 252] then begin
    Writeln('MyByte is neither 3 or 252');
  end
  else begin
    Writeln('MyByte is 3 or 252!');
  end;
end;

This rule would pick up these cases and suggest using parentheses to make the order of operations clear and intentional.

Rationale

This is a case in which the compiler's interpretation is almost never what the programmer intended. Even if the programmer did mean to check if not X was in the array, parentheses are needed to make this clear to other maintainers.

Metadata

Metadata

Assignees

No one assigned

    Labels

    featureNew feature or requestruleImprovements or additions to rules

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions