All files / transpiler/logic/analysis SignedShiftAnalyzer.ts

83.01% Statements 88/106
70.68% Branches 41/58
92.3% Functions 12/13
90.32% Lines 84/93

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 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308                                                                                        333x 333x 333x                 31x             29x 29x             1311x     1311x 1311x     21x 21x 21x   21x 21x   21x     21x 15x 15x                       162x     162x 162x   162x 162x 162x   12x 12x     12x 12x     12x 8x 8x 8x                           12x 12x   12x     12x 10x       2x 2x           2x 2x 2x   2x 2x       2x   2x                                               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               333x           333x     333x 333x     333x       333x   333x             23x                                      
/**
 * 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. Build lexical scope frames (DeclarationScopeCollector)
 * 2. Detect shift operations with signed operands
 *
 * Issue #1220: pass 1 used to be private Set/Map caches built from this file's
 * parse tree alone, so an `i32` arriving through an #include was invisible and
 * `signedValue >> 1` shipped silently -- gcc accepts it even under
 * -Wall -Wextra -Wconversion, and right-shifting a negative value is
 * implementation-defined. Resolution now goes through ScopeFrameResolver,
 * which searches the lexical frames and falls back to the symbol table.
 */
 
import { ParserRuleContext, 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";
import CodeGenState from "../../state/CodeGenState";
import DeclarationScopeCollector from "./DeclarationScopeCollector";
import ScopeFrameResolver from "./ScopeFrameResolver";
 
/**
 * 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 scopes: ScopeFrameResolver;
 
  constructor(analyzer: SignedShiftAnalyzer, scopes: ScopeFrameResolver) {
    super();
    this.analyzer = analyzer;
    this.scopes = scopes;
  }
 
  /**
   * Declared type of a name as seen from the frame enclosing `at`. One place
   * decides how this analyzer resolves a name, so the lexical-then-symbol-table
   * order cannot drift between the operand and assignment-target paths (#1220).
   */
  private declaredTypeAt(name: string, at: ParserRuleContext): string | null {
    return this.scopes.typeOfName(name, this.scopes.frameFor(at));
  }
 
  /**
   * Whether a name resolves to one of the signed integer types.
   */
  private isSignedName(name: string, at: ParserRuleContext): boolean {
    const typeName = this.declaredTypeAt(name, at);
    return typeName !== null && TypeConstants.SIGNED_TYPES.includes(typeName);
  }
 
  /**
   * 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 compound shift-assign statements for signed targets
   * assignmentStatement: assignmentTarget assignmentOperator expression ';'
   * Issue #1008: <<<- and >><- must also be rejected on signed types
   *
   * Handles both simple identifiers (x <<<- 2) and member chains (s.x <<<- 2)
   */
  override enterAssignmentStatement = (
    ctx: Parser.AssignmentStatementContext,
  ): void => {
    const opCtx = ctx.assignmentOperator();
    Iif (!opCtx) return;
 
    const isLeftShiftAssign = opCtx.LSHIFT_ASSIGN() !== null;
    const isRightShiftAssign = opCtx.RSHIFT_ASSIGN() !== null;
    if (!isLeftShiftAssign && !isRightShiftAssign) return;
 
    const target = ctx.assignmentTarget();
    Iif (!target) return;
 
    // Get the base identifier from the assignment target
    const identifier = target.IDENTIFIER();
    Iif (!identifier) return;
 
    // Check if the final target type is signed
    if (this.isSignedTarget(target)) {
      const operator = isLeftShiftAssign ? "<<<-" : ">><-";
      const { line, column } = ParserUtils.getPosition(target);
      this.analyzer.addError(line, column, operator);
    }
  };
 
  /**
   * Resolve the final type of an assignment target, handling member chains.
   * Returns true if the final target is a signed type.
   *
   * Examples:
   *   - "x" with no postfix ops → check if x is signed
   *   - "s" with postfixOps [".x"] → check if s.x field is signed
   *   - "arr" with postfixOps ["[0]", ".field"] → check if field is signed
   */
  private isSignedTarget(target: Parser.AssignmentTargetContext): boolean {
    const baseName = target.IDENTIFIER()?.getText();
    Iif (!baseName) return false;
 
    const postfixOps = target.postfixTargetOp();
 
    // Simple case: no member access, just a variable
    if (postfixOps.length === 0) {
      return this.isSignedName(baseName, target);
    }
 
    // Member chain case: resolve through the chain
    let currentType: string | null = this.declaredTypeAt(baseName, target);
    Iif (!currentType) {
      // Unknown base type - can't resolve, skip
      return false;
    }
 
    // Walk through the postfix operations
    for (const op of postfixOps) {
      const memberIdent = op.IDENTIFIER();
      if (memberIdent) {
        // Member access: .fieldName
        const fieldName = memberIdent.getText();
        const fieldType = CodeGenState.getStructFieldType(
          currentType,
          fieldName,
        );
        Eif (!fieldType) {
          // Unknown field - can't resolve, skip
          return false;
        }
        currentType = fieldType;
      } else E{
        // Array subscript: [expr] - doesn't change the base type for primitives
        // For arrays like u8[4], after [i] we still have u8
        // Strip array dimensions if present
        const bracketIndex = currentType.indexOf("[");
        if (bracketIndex !== -1) {
          currentType = currentType.substring(0, bracketIndex);
        }
        // Otherwise keep the type as-is (e.g., bit indexing on u8)
      }
    }
 
    // Check if the final resolved type is signed
    return TypeConstants.SIGNED_TYPES.includes(currentType);
  }
 
  /**
   * 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.isSignedName(identifier.getText(), ctx);
    }
 
    // 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: build the lexical scope frames
    const declarations = new DeclarationScopeCollector();
    ParseTreeWalker.DEFAULT.walk(declarations, tree);
 
    // Second pass: detect shift with signed operands
    const listener = new SignedShiftListener(
      this,
      new ScopeFrameResolver(declarations),
    );
    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;