Class: SasLinter::Rules::IdenticalIfElseBranches

Inherits:
SasLinter::Rule show all
Defined in:
lib/sas_linter/rules/identical_if_else_branches.rb

Overview

Flag ‘if COND then S; else S;` where the THEN and ELSE bodies are identical token-for-token — the condition has no effect on the outcome, which is almost always a copy-paste error.

Motivating bug (‘docs/AK_LOC_HOME_CARE_SCALE_notes.txt` #1):

if iK3 in (6,7,8) then NF1_2=0; else NF1_2=0;

Both branches assign ‘NF1_2 = 0`; the THEN should have been `=1`.

Scope: simple-statement bodies only (‘then STMT; else STMT;`). The block form (`then do; … end; else do; … end;`) is ignored — it’s rare and the equivalence check would need to span an unbounded body.

Constant Summary collapse

TT =
SasLexer::Lexer::TokenType

Instance Attribute Summary

Attributes inherited from SasLinter::Rule

#autofix

Instance Method Summary collapse

Methods inherited from SasLinter::Rule

all, #autofix?, description, fetch, from_config, inherited, #initialize, register, registry, rule_id, severity, supports_autofix?

Constructor Details

This class inherits a constructor from SasLinter::Rule

Instance Method Details

#check(tokens, path:, all_tokens: nil, source: nil) ⇒ Object

rubocop:disable Lint/UnusedMethodArgument



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/sas_linter/rules/identical_if_else_branches.rb', line 29

def check(tokens, path:, all_tokens: nil, source: nil) # rubocop:disable Lint/UnusedMethodArgument
  findings = []
  i = 0

  while i < tokens.length
    tok = tokens[i]

    if tok[:type] == TT::KW_THEN
      # Bail on `then do;` — only handle simple statement bodies.
      nxt = tokens[i + 1]
      if nxt && nxt[:type] != TT::KW_DO
        then_body, after_then = collect_simple_body(tokens, i + 1)
        if then_body && tokens[after_then] && tokens[after_then][:type] == TT::KW_ELSE
          else_idx = after_then
          # Same bail-out for `else do;`.
          else_first = tokens[else_idx + 1]
          if else_first && else_first[:type] != TT::KW_DO
            else_body, after_else = collect_simple_body(tokens, else_idx + 1)
            if else_body && bodies_equivalent?(then_body, else_body)
              findings << finding(
                line: tokens[else_idx][:start_line],
                column: tokens[else_idx][:start_column] + 1,
                message: "`if ... then #{render_body(then_body)}; else #{render_body(else_body)};` — " \
                         "branches are identical; the condition has no effect.",
                path: path
              )
              i = after_else
              next
            end
          end
        end
      end
    end

    i += 1
  end

  findings
end