sonar-delphi icon indicating copy to clipboard operation
sonar-delphi copied to clipboard

New rule: Identifiers should not shadow keywords

Open fourls opened this issue 2 years ago • 1 comments

Prerequisites

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

Suggested rule title

Identifiers should not shadow keywords

Rule description

This rule identifies identifiers that share a name with a keyword.

This would include a configurable whitelist for acceptable keywords to shadow, such as message or index.

Rationale

It can be easy to accidentally share the name of a variable with a keyword, as many of Delphi's keywords are context-dependent. This can be very confusing, particularly when used in a similar place to where the keyword is seen. In certain circumstances, the compiler can interpret attempted usages of your identifier as a keyword, making certain constructions impossible for identifiers that shadow a keyword.

type
  stdcall = string;

  override = class
    public function public: stdcall overload stdcall;
  end;

In the Delphi IDE, these are all highlighted as keywords.

fourls avatar Oct 31 '23 05:10 fourls

Great suggestion, and sufficiently upsetting code example. 🥇

cirras avatar Nov 14 '23 04:11 cirras