All files / transpiler/logic/analysis SignedShiftAnalyzer.ts

87.65% Statements 71/81
72.22% Branches 26/36
92.85% Functions 13/14
95.71% Lines 67/70

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                                                        170x     170x                   191x   191x 191x   42x   42x           149x     149x           39x 39x           3x 3x                           170x 170x 170x             309x     309x 309x     21x 21x 21x   21x 21x   21x     21x 15x 15x                   23x 23x 23x 23x 23x 16x       7x                 23x 1x 1x   1x 1x 1x 1x 1x                 22x 22x   22x 22x     22x 22x 2x       20x 20x 19x       1x             2x 2x   2x 2x               170x           170x     170x 170x 170x     170x 170x   170x             15x                                      
/**
 * Signed Shift Analyzer
 * Detects shift operators used with signed integer types at compile time
 *
 * MISRA C:2012 Rule 10.1: Operands shall not be of an inappropriate essential type
 * - Left-shifting negative signed values is undefined behavior in C
 * - Right-shifting negative signed values is implementation-defined in C
 *
 * C-Next rejects all shift operations on signed types (i8, i16, i32, i64) at
 * compile time to ensure defined, portable behavior.
 *
 * Two-pass analysis:
 * 1. Collect variable declarations with their types
 * 2. Detect shift operations with signed operands
 */
 
import { ParseTreeWalker } from "antlr4ng";
import { CNextListener } from "../parser/grammar/CNextListener";
import * as Parser from "../parser/grammar/CNextParser";
import ISignedShiftError from "./types/ISignedShiftError";
import ParserUtils from "../../../utils/ParserUtils";
import TypeConstants from "../../../utils/constants/TypeConstants";
import ExpressionUtils from "../../../utils/ExpressionUtils";
 
/**
 * First pass: Collect variable declarations with their types
 */
class SignedVariableCollector extends CNextListener {
  private readonly signedVars: Set<string> = new Set();
 
  public getSignedVars(): Set<string> {
    return this.signedVars;
  }
 
  /**
   * Track a typed identifier if it has a signed type
   */
  private trackIfSigned(
    typeCtx: Parser.TypeContext | null,
    identifier: { getText(): string } | null,
  ): void {
    Iif (!typeCtx) return;
 
    const typeName = typeCtx.getText();
    if (!TypeConstants.SIGNED_TYPES.includes(typeName)) return;
 
    Iif (!identifier) return;
 
    this.signedVars.add(identifier.getText());
  }
 
  /**
   * Track variable declarations with signed types
   */
  override enterVariableDeclaration = (
    ctx: Parser.VariableDeclarationContext,
  ): void => {
    this.trackIfSigned(ctx.type(), ctx.IDENTIFIER());
  };
 
  /**
   * Track function parameters with signed types
   */
  override enterParameter = (ctx: Parser.ParameterContext): void => {
    this.trackIfSigned(ctx.type(), ctx.IDENTIFIER());
  };
 
  /**
   * Track for-loop variable declarations with signed types
   */
  override enterForVarDecl = (ctx: Parser.ForVarDeclContext): void => {
    this.trackIfSigned(ctx.type(), ctx.IDENTIFIER());
  };
}
 
/**
 * Second pass: Detect shift operations with signed operands
 */
class SignedShiftListener extends CNextListener {
  private readonly analyzer: SignedShiftAnalyzer;
 
  // eslint-disable-next-line @typescript-eslint/lines-between-class-members
  private readonly signedVars: Set<string>;
 
  constructor(analyzer: SignedShiftAnalyzer, signedVars: Set<string>) {
    super();
    this.analyzer = analyzer;
    this.signedVars = signedVars;
  }
 
  /**
   * Check shift expressions for signed operands
   * shiftExpression: additiveExpression (('<<' | '>>') additiveExpression)*
   */
  override enterShiftExpression = (
    ctx: Parser.ShiftExpressionContext,
  ): void => {
    const operands = ctx.additiveExpression();
    if (operands.length < 2) return;
 
    // Check each operator between additive expressions
    for (let i = 0; i < operands.length - 1; i++) {
      const operatorToken = ctx.getChild(i * 2 + 1);
      Iif (!operatorToken) continue;
 
      const operator = operatorToken.getText();
      Iif (operator !== "<<" && operator !== ">>") continue;
 
      const leftOperand = operands[i];
 
      // Check left operand (the value being shifted)
      if (this.isSignedOperand(leftOperand)) {
        const { line, column } = ParserUtils.getPosition(leftOperand);
        this.analyzer.addError(line, column, operator);
      }
    }
  };
 
  /**
   * Check if an additive expression contains a signed type operand
   */
  private isSignedOperand(ctx: Parser.AdditiveExpressionContext): boolean {
    // Walk down to unary expressions
    const multExprs = ctx.multiplicativeExpression();
    for (const multExpr of multExprs) {
      const unaryExprs = multExpr.unaryExpression();
      for (const unaryExpr of unaryExprs) {
        if (this.isSignedUnaryExpression(unaryExpr)) {
          return true;
        }
      }
    }
    return false;
  }
 
  /**
   * Check if a unary expression is a signed type
   */
  private isSignedUnaryExpression(ctx: Parser.UnaryExpressionContext): boolean {
    // Check for MINUS prefix (negation) - indicates signed context
    // Grammar: unaryExpression: MINUS unaryExpression | ...
    if (ctx.MINUS()) {
      const nestedUnary = ctx.unaryExpression();
      Eif (nestedUnary) {
        // If negating a literal, it's a negative number (signed)
        const nestedPostfix = nestedUnary.postfixExpression();
        Eif (nestedPostfix) {
          const nestedPrimary = nestedPostfix.primaryExpression();
          Eif (nestedPrimary?.literal()) {
            return true;
          }
        }
        // If negating a variable, check if it's signed
        return this.isSignedUnaryExpression(nestedUnary);
      }
      return false;
    }
 
    const postfixExpr = ctx.postfixExpression();
    Iif (!postfixExpr) return false;
 
    const primaryExpr = postfixExpr.primaryExpression();
    Iif (!primaryExpr) return false;
 
    // Check for parenthesized expression
    const parenExpr = primaryExpr.expression();
    if (parenExpr) {
      return this.isSignedExpression(parenExpr);
    }
 
    // Check for identifier that's a signed variable
    const identifier = primaryExpr.IDENTIFIER();
    if (identifier) {
      return this.signedVars.has(identifier.getText());
    }
 
    // Positive integer literals are treated as unsigned
    return false;
  }
 
  /**
   * Check if a full expression contains signed operands
   */
  private isSignedExpression(ctx: Parser.ExpressionContext): boolean {
    const ternary = ctx.ternaryExpression();
    Iif (!ternary) return false;
 
    const additiveExprs = ExpressionUtils.collectAdditiveExpressions(ternary);
    return additiveExprs.some((addExpr) => this.isSignedOperand(addExpr));
  }
}
 
/**
 * Analyzer that detects shift operations on signed integer types
 */
class SignedShiftAnalyzer {
  private errors: ISignedShiftError[] = [];
 
  /**
   * Analyze the parse tree for signed shift operations
   */
  public analyze(tree: Parser.ProgramContext): ISignedShiftError[] {
    this.errors = [];
 
    // First pass: collect signed variables
    const collector = new SignedVariableCollector();
    ParseTreeWalker.DEFAULT.walk(collector, tree);
    const signedVars = collector.getSignedVars();
 
    // Second pass: detect shift with signed operands
    const listener = new SignedShiftListener(this, signedVars);
    ParseTreeWalker.DEFAULT.walk(listener, tree);
 
    return this.errors;
  }
 
  /**
   * Add a signed shift error
   */
  public addError(line: number, column: number, operator: string): void {
    this.errors.push({
      code: "E0805",
      line,
      column,
      message: `Shift operator '${operator}' not allowed on signed integer types`,
      helpText:
        "Shift operations on signed integers have undefined (<<) or implementation-defined (>>) behavior. Use unsigned types (u8, u16, u32, u64) for bit manipulation.",
    });
  }
 
  /**
   * Get all detected errors
   */
  public getErrors(): ISignedShiftError[] {
    return this.errors;
  }
}
 
export default SignedShiftAnalyzer;