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

New rule: Unreachable code should be removed

Open fourls opened this issue 1 year ago • 2 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

Unreachable code should be removed

Rule description

This rule would pick up simple statically verifiable cases of unreachable code, by raising an issue when encountering a statement immediately after the following (i.e. in the same block):

  • Exit
  • Break
  • Continue
  • raise
  • goto

As a gotcha, the rule must not raise an issue if the "dead" statement is a goto label, or contains a goto label nested inside it.

Rationale

Accidental unreachable code is a common problem when writing or refactoring code, and is at best messy and at worst an avenue for bugs and unexpected behaviour. Delphi also has no built in functionality to detect unreachable code, so this would fill a useful niche.

fourls avatar Feb 01 '24 06:02 fourls

Continuing on the label gotcha:

procedure foo;
var
  X: Integer;
label
  Cursed;
begin
  X := 0;
  goto Cursed;
  for X := 0 to 10 do begin
    Cursed:
      WriteLn;
  end;
end;

in this (cursed) code, nothing is actually dead

zaneduffield avatar Feb 01 '24 06:02 zaneduffield

The cursed code makes a good point 😢 In the PR description,

As a gotcha, the rule must not raise an issue if the "dead" statement is a goto label.

should actually read

As a gotcha, the rule must not raise an issue if the "dead" statement is a goto label, or contains a goto label nested inside it.

I've updated it now.

fourls avatar Feb 01 '24 06:02 fourls