All files / transpiler/logic/analysis BooleanOperandAnalyzer.ts

96.36% Statements 53/55
91.66% Branches 22/24
90% Functions 9/10
97.95% Lines 48/49

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 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 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241                                                                                                              380x 380x 380x 380x                                       323x                           161x     161x 161x   28x 28x   28x         11x 11x 11x     17x 17x 2x 2x                         147x 147x   147x 150x 150x 150x   42x 150x 150x 150x         1727x     1727x 1727x   6x 6x   6x 2x 2x                   380x           380x   380x 380x   380x             380x   199x 147x           380x   380x             46x                                           11x                                    
/**
 * Boolean Operand Analyzer
 *
 * Detects arithmetic, bitwise, shift and relational operators applied to an
 * essentially Boolean operand.
 *
 * MISRA C:2012 Rule 10.1: "Operands shall not be of an inappropriate essential
 * type." An essentially Boolean operand is permitted only for the logical
 * operators (&&, ||, !), for equality (=, !=), and as a controlling expression.
 * It is not a number: `flag + 1` relies on Boolean-to-integer promotion, and
 * `a / b` on two bools is an unguarded division by zero whenever `b` is false
 * (Issue #1183) -- a risk carried by the TYPE, so the literal-divisor check in
 * DivisionByZeroAnalyzer (E0800) can never see it.
 *
 * `a - b` is the other trap: `false - true` is -1, which stores back into a
 * bool as `true`, so subtracting from a false flag sets it.
 *
 * Equality is deliberately NOT checked: C-Next requires conditions to be
 * explicit comparisons, so `if (flag = true)` is the idiomatic test and must
 * stay legal. `!flag` likewise remains the way to negate.
 *
 * This is the same rule E0805 enforces for signed shift operands, and the
 * sibling of E0806 (compound assignment to a bool, Issue #1145) on the
 * assignment side.
 *
 * Two-pass analysis, sharing DeclarationScopeCollector with the Rule 10.4
 * analyzer so both resolve declarations through one scope-shadowing pass:
 * 1. Collect declarations into per-scope frames.
 * 2. Walk each guarded operator level and report any Boolean operand.
 */
 
import { ParseTreeWalker, ParserRuleContext } from "antlr4ng";
import { CNextListener } from "../parser/grammar/CNextListener";
import * as Parser from "../parser/grammar/CNextParser";
import IBooleanOperandError from "./types/IBooleanOperandError";
import IScopeFrame from "./types/IScopeFrame";
import DeclarationScopeCollector from "./DeclarationScopeCollector";
import ScopeFrameResolver from "./ScopeFrameResolver";
import OperandTypeResolver from "./OperandTypeResolver";
import BinaryOperatorLevelListener from "./BinaryOperatorLevelListener";
import ParserUtils from "../../../utils/ParserUtils";
 
/**
 * Second pass: report essentially Boolean operands of guarded operators.
 */
class BooleanOperandListener extends CNextListener {
  private readonly analyzer: BooleanOperandAnalyzer;
 
  // eslint-disable-next-line @typescript-eslint/lines-between-class-members
  private readonly scopes: ScopeFrameResolver;
 
  // eslint-disable-next-line @typescript-eslint/lines-between-class-members
  private readonly types: OperandTypeResolver;
 
  constructor(analyzer: BooleanOperandAnalyzer, scopes: ScopeFrameResolver) {
    super();
    this.analyzer = analyzer;
    this.scopes = scopes;
    this.types = new OperandTypeResolver(scopes);
  }
 
  /**
   * Whether an operand is essentially Boolean.
   *
   * Every case defers to the shared type resolver, so a bool reads the same
   * however it is spelled: a declaration (`flag`, `this.flag`, `sensor.ready`,
   * `outer.inner.ready`, `flags[0]`), a literal, `!x`, or a comparison or
   * logical result (`a && b`, `a = b`, `n < 5`) that no declaration names.
   *
   * An ARITHMETIC child is deliberately not Boolean and needs no case here:
   * `a + b` inside `(a + b) * c` reports at its own level. A Boolean child is
   * the opposite -- it is well-formed alone, so the parent operator is the only
   * place its misuse can be reported (Issue #1183 review).
   */
  private isBooleanOperand(
    ctx: ParserRuleContext,
    frame: IScopeFrame,
  ): boolean {
    return OperandTypeResolver.isBooleanType(
      this.types.typeOfOperand(ctx, frame),
    );
  }
 
  /**
   * MISRA C:2012 Rule 10.1 on the assignment side.
   *
   * A compound assignment applies an arithmetic or bitwise operator that the
   * expression grammar never expresses as a level, so neither the operator
   * levels nor a target-only check sees both halves. Both are checked here:
   * a bool TARGET (E0806) and a bool right-hand side (E0807). Before this,
   * `n +<- flag` was accepted while the identical `n <- n + flag` was rejected.
   */
  override enterAssignmentStatement = (
    ctx: Parser.AssignmentStatementContext,
  ): void => {
    const operator = ctx.assignmentOperator().getText();
    if (operator === "<-") return;
 
    const target = ctx.assignmentTarget();
    const frame = this.scopes.frameFor(ctx);
 
    if (
      OperandTypeResolver.isBooleanType(
        this.types.typeOfAssignmentTarget(target, frame),
      )
    ) {
      const { line, column } = ParserUtils.getPosition(target);
      this.analyzer.addCompoundAssignmentError(line, column, target.getText());
      return;
    }
 
    const value = ctx.expression();
    if (this.isBooleanOperand(value, frame)) {
      const { line, column } = ParserUtils.getPosition(value);
      this.analyzer.addError(line, column, operator);
    }
  };
 
  /**
   * Report one error per guarded operator whose left or right operand is
   * essentially Boolean. The operator sits between adjacent operands, so the
   * operator joining operand `i` to `i + 1` is child `i * 2 + 1`.
   *
   * Reported once per operator rather than once per operand: `flag / other` is
   * a single mistake, and naming both operands would double every diagnostic.
   */
  public checkLevel(operands: ParserRuleContext[]): void {
    const frame = this.scopes.frameFor(operands[0]);
    const parent = operands[0].parent;
 
    for (let i = 0; i < operands.length - 1; i += 1) {
      const leftIsBoolean = this.isBooleanOperand(operands[i], frame);
      const rightIsBoolean = this.isBooleanOperand(operands[i + 1], frame);
      if (!leftIsBoolean && !rightIsBoolean) continue;
 
      const operator = parent?.getChild(i * 2 + 1)?.getText() ?? "";
      const offending = leftIsBoolean ? operands[i] : operands[i + 1];
      const { line, column } = ParserUtils.getPosition(offending);
      this.analyzer.addError(line, column, operator);
    }
  }
 
  // Prefix `-` and `~` are arithmetic/bitwise; `!` is the correct negation.
  override enterUnaryExpression = (
    ctx: Parser.UnaryExpressionContext,
  ): void => {
    const operator = ctx.getChild(0)?.getText();
    if (operator !== "-" && operator !== "~") return;
 
    const operand = ctx.unaryExpression();
    Iif (!operand) return;
 
    if (this.isBooleanOperand(operand, this.scopes.frameFor(ctx))) {
      const { line, column } = ParserUtils.getPosition(ctx);
      this.analyzer.addError(line, column, operator);
    }
  };
}
 
/**
 * Analyzer that detects essentially Boolean operands of arithmetic, bitwise,
 * shift and relational operators.
 */
class BooleanOperandAnalyzer {
  private errors: IBooleanOperandError[] = [];
 
  /**
   * Analyze the parse tree for Boolean operands of inappropriate operators.
   */
  public analyze(tree: Parser.ProgramContext): IBooleanOperandError[] {
    this.errors = [];
 
    const collector = new DeclarationScopeCollector();
    ParseTreeWalker.DEFAULT.walk(collector, tree);
 
    const listener = new BooleanOperandListener(
      this,
      new ScopeFrameResolver(collector),
    );
 
    // Every binary level EXCEPT equality: comparing two bools with = / != is
    // permitted by Rule 10.1 and is how C-Next tests a flag.
    ParseTreeWalker.DEFAULT.walk(
      new BinaryOperatorLevelListener((operands, level) => {
        if (level === "equality") return;
        listener.checkLevel(operands);
      }),
      tree,
    );
 
    // Prefix `-` / `~` are not a binary level, so the listener hooks them.
    ParseTreeWalker.DEFAULT.walk(listener, tree);
 
    return this.errors;
  }
 
  /**
   * Add a Boolean-operand error.
   */
  public addError(line: number, column: number, operator: string): void {
    this.errors.push({
      code: "E0807",
      line,
      column,
      message: `Operator '${operator}' is not valid on a bool operand`,
      helpText:
        "MISRA C:2012 Rule 10.1: a bool is not a number. Use the logical operators " +
        "(&&, ||, !) to combine flags, or '=' / '!=' to compare them.",
    });
  }
 
  /**
   * Add a compound-assignment-to-bool error, naming the target as written so
   * the suggested fix is code that can be pasted back (Issue #1183 review:
   * `flags[0] +<- true` used to suggest `flags <- !flags`, which does not
   * compile).
   */
  public addCompoundAssignmentError(
    line: number,
    column: number,
    target: string,
  ): void {
    this.errors.push({
      code: "E0806",
      line,
      column,
      message: `Compound assignment is not valid on bool '${target}' - only '<-' is`,
      helpText: `MISRA C:2012 Rule 10.1: a bool is not a number. To flip it, use '${target} <- !${target}'.`,
    });
  }
 
  /**
   * Get all detected errors.
   */
  public getErrors(): IBooleanOperandError[] {
    return this.errors;
  }
}
 
export default BooleanOperandAnalyzer;