All files / transpiler/output/codegen/generators/statements ControlFlowGenerator.ts

98.52% Statements 134/136
87.03% Branches 47/54
100% Functions 9/9
99.25% Lines 134/135

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 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428                                                                              23x   23x 4x 1x 1x 1x                     17x           113x   113x 9x       104x 104x   104x       113x 98x 98x 23x         103x       113x             17x           42x 42x     42x         42x 42x 33x       42x     42x     42x     42x     42x   42x   42x   42x 11x 11x       39x     39x 1x   39x 2x     39x           17x           16x     16x     16x     16x   16x       16x   16x 16x     16x 1x     14x           17x           11x     11x     11x     11x   11x 11x       11x   11x   11x 1x     11x           17x           21x   21x 21x 21x     21x   21x     21x 21x 1x       21x 14x 14x     21x           17x           14x 14x 14x 14x 14x 14x 14x                     17x           18x       18x 1x           17x 17x 17x 16x 15x           15x 15x 1x 1x           1x 1x         17x       17x     17x     17x     17x   17x     17x   17x 17x 17x 14x     14x 14x 14x 14x 14x       17x   17x   17x     17x     17x 1x     17x                       17x           1x     1x 1x               1x   1x   1x       17x                        
/**
 * Control Flow Statement Generators (ADR-053 A3)
 *
 * Generates C code for control flow statements:
 * - return statements
 * - if/else statements
 * - while loops
 * - do-while loops
 * - for loops
 */
import {
  ReturnStatementContext,
  IfStatementContext,
  WhileStatementContext,
  DoWhileStatementContext,
  ForStatementContext,
  ForeverStatementContext,
  ForVarDeclContext,
  ForAssignmentContext,
  ExpressionContext,
} from "../../../../logic/parser/grammar/CNextParser";
import IGeneratorOutput from "../IGeneratorOutput";
import TGeneratorEffect from "../TGeneratorEffect";
import IGeneratorInput from "../IGeneratorInput";
import IGeneratorState from "../IGeneratorState";
import IOrchestrator from "../IOrchestrator";
import VariableModifierBuilder from "../../helpers/VariableModifierBuilder";
import ExpressionUtils from "../../../../../utils/ExpressionUtils";
import ASSIGNMENT_OPERATOR_MAP from "../../../../../utils/constants/OperatorMappings";
 
/**
 * Issue #477: Check if a simple identifier is an unqualified enum member.
 * Throws an error with helpful suggestion if found.
 */
function rejectUnqualifiedEnumInReturn(
  simpleId: string,
  symbols: IGeneratorInput["symbols"],
  exprCtx: ExpressionContext,
): void {
  Iif (!symbols) return;
 
  for (const [enumName, members] of symbols.enumMembers) {
    if (members.has(simpleId)) {
      const line = exprCtx.start?.line ?? 0;
      const col = exprCtx.start?.column ?? 0;
      throw new Error(
        `${line}:${col} error[E0424]: '${simpleId}' is not defined; did you mean '${enumName}.${simpleId}'?`,
      );
    }
  }
}
 
/**
 * Generate C code for a return statement.
 * Issue #477: Uses function return type as expected type for enum inference.
 */
const generateReturn = (
  node: ReturnStatementContext,
  input: IGeneratorInput,
  _state: IGeneratorState,
  orchestrator: IOrchestrator,
): IGeneratorOutput => {
  const effects: TGeneratorEffect[] = [];
 
  if (!node.expression()) {
    return { code: "return;", effects };
  }
 
  // Issue #477: Get function return type for enum inference
  const returnType = orchestrator.getCurrentFunctionReturnType();
  const exprCtx = node.expression()!;
  const returnTypeIsEnum =
    returnType && input.symbols?.knownEnums.has(returnType);
 
  // Issue #477: Validate unqualified enum in non-enum return context
  // Use ExpressionUtils to check for simple identifier (no binary ops, no postfix)
  if (!returnTypeIsEnum) {
    const simpleId = ExpressionUtils.extractIdentifier(exprCtx);
    if (simpleId) {
      rejectUnqualifiedEnumInReturn(simpleId, input.symbols, exprCtx);
    }
  }
 
  // Set expectedType if return type is enum (enables unqualified enum returns)
  const expr = returnTypeIsEnum
    ? orchestrator.generateExpressionWithExpectedType(exprCtx, returnType)
    : orchestrator.generateExpression(exprCtx);
 
  return { code: `return ${expr};`, effects };
};
 
/**
 * Generate C code for an if statement.
 * Includes strlen optimization for repeated .length accesses.
 */
const generateIf = (
  node: IfStatementContext,
  _input: IGeneratorInput,
  _state: IGeneratorState,
  orchestrator: IOrchestrator,
): IGeneratorOutput => {
  const effects: TGeneratorEffect[] = [];
  const statements = node.statement();
 
  // Analyze condition and body for repeated .length accesses (strlen optimization)
  const lengthCounts = orchestrator.countStringLengthAccesses(
    node.expression(),
  );
 
  // Also count in the then branch if it's a block
  const thenStmt = statements[0];
  if (thenStmt.block()) {
    orchestrator.countBlockLengthAccesses(thenStmt.block()!, lengthCounts);
  }
 
  // Set up cache and generate declarations
  const cacheDecls = orchestrator.setupLengthCache(lengthCounts);
 
  // Issue #254: Validate no function calls in condition (E0702)
  orchestrator.validateConditionNoFunctionCall(node.expression(), "if");
 
  // Issue #884: Validate condition is a boolean expression (E0701)
  orchestrator.validateConditionIsBoolean(node.expression(), "if");
 
  // Generate with cache enabled
  const condition = orchestrator.generateExpression(node.expression());
 
  // Issue #250: Flush any temp vars from condition BEFORE generating branches
  const conditionTemps = orchestrator.flushPendingTempDeclarations();
 
  const thenBranch = orchestrator.generateStatement(thenStmt);
 
  let result = `if (${condition}) ${thenBranch}`;
 
  if (statements.length > 1) {
    const elseBranch = orchestrator.generateStatement(statements[1]);
    result += ` else ${elseBranch}`;
  }
 
  // Clear cache after generating
  orchestrator.clearLengthCache();
 
  // Prepend condition temps and cache declarations
  if (conditionTemps) {
    result = conditionTemps + "\n" + result;
  }
  if (cacheDecls) {
    result = cacheDecls + result;
  }
 
  return { code: result, effects };
};
 
/**
 * Generate C code for a while statement.
 */
const generateWhile = (
  node: WhileStatementContext,
  _input: IGeneratorInput,
  _state: IGeneratorState,
  orchestrator: IOrchestrator,
): IGeneratorOutput => {
  const effects: TGeneratorEffect[] = [];
 
  // Issue #254: Validate no function calls in condition (E0702)
  orchestrator.validateConditionNoFunctionCall(node.expression(), "while");
 
  // Issue #884: Validate condition is a boolean expression (E0701)
  orchestrator.validateConditionIsBoolean(node.expression(), "while");
 
  // ADR-113 / #1075: reject always-true literal condition (E0707)
  orchestrator.validateLoopConditionNotAlwaysTrue(node.expression());
 
  const condition = orchestrator.generateExpression(node.expression());
 
  // Issue #250: Flush any temp vars from condition BEFORE generating body
  // Otherwise they end up inside the loop body, causing "not declared" errors
  const conditionTemps = orchestrator.flushPendingTempDeclarations();
 
  const body = orchestrator.generateStatement(node.statement());
  let result = `while (${condition}) ${body}`;
 
  // Prepend condition temps before the while statement
  if (conditionTemps) {
    result = conditionTemps + "\n" + result;
  }
 
  return { code: result, effects };
};
 
/**
 * Generate C code for a do-while statement (ADR-027).
 */
const generateDoWhile = (
  node: DoWhileStatementContext,
  _input: IGeneratorInput,
  _state: IGeneratorState,
  orchestrator: IOrchestrator,
): IGeneratorOutput => {
  const effects: TGeneratorEffect[] = [];
 
  // Issue #254: Validate no function calls in condition (E0702)
  orchestrator.validateConditionNoFunctionCall(node.expression(), "do-while");
 
  // Issue #884: Validate condition is a boolean expression (E0701)
  orchestrator.validateConditionIsBoolean(node.expression(), "do-while");
 
  // ADR-113 / #1075: reject always-true literal condition (E0707)
  orchestrator.validateLoopConditionNotAlwaysTrue(node.expression());
 
  const body = orchestrator.generateBlock(node.block());
  const condition = orchestrator.generateExpression(node.expression());
 
  // Issue #250: Flush any temp vars from condition
  // For do-while, condition is evaluated after body, but temps must be declared before
  const conditionTemps = orchestrator.flushPendingTempDeclarations();
 
  let result = `do ${body} while (${condition});`;
 
  if (conditionTemps) {
    result = conditionTemps + "\n" + result;
  }
 
  return { code: result, effects };
};
 
/**
 * Generate variable declaration for for loop init (no trailing semicolon).
 */
const generateForVarDecl = (
  node: ForVarDeclContext,
  _input: IGeneratorInput,
  _state: IGeneratorState,
  orchestrator: IOrchestrator,
): IGeneratorOutput => {
  const effects: TGeneratorEffect[] = [];
  // Issue #696: Use shared modifier builder
  const modifiers = VariableModifierBuilder.buildSimple(node);
  const typeName = orchestrator.generateType(node.type());
  const name = node.IDENTIFIER().getText();
 
  // ADR-016: Track local variables (allowed as bare identifiers inside scopes)
  orchestrator.registerLocalVariable(name);
 
  let result = `${modifiers.atomic}${modifiers.volatile}${typeName} ${name}`;
 
  // ADR-036: Handle array dimensions (now returns array for multi-dim support)
  const arrayDims = node.arrayDimension();
  if (arrayDims.length > 0) {
    result = `${typeName} ${name}${orchestrator.generateArrayDimensions(arrayDims)}`;
  }
 
  // Handle initialization
  if (node.expression()) {
    const value = orchestrator.generateExpression(node.expression()!);
    result += ` = ${value}`;
  }
 
  return { code: result, effects };
};
 
/**
 * Generate assignment for for loop init/update (no trailing semicolon).
 */
const generateForAssignment = (
  node: ForAssignmentContext,
  _input: IGeneratorInput,
  _state: IGeneratorState,
  orchestrator: IOrchestrator,
): IGeneratorOutput => {
  const effects: TGeneratorEffect[] = [];
  const target = orchestrator.generateAssignmentTarget(node.assignmentTarget());
  const value = orchestrator.generateExpression(node.expression());
  const operatorCtx = node.assignmentOperator();
  const cnextOp = operatorCtx.getText();
  const cOp = ASSIGNMENT_OPERATOR_MAP[cnextOp] || "=";
  return { code: `${target} ${cOp} ${value}`, effects };
};
 
/**
 * Generate C code for a for statement.
 *
 * Note: Issue #250 - temps from condition/update are hoisted before the for loop.
 * This means the expression is evaluated once, not on each iteration.
 * This is a known limitation; if the value changes inside the loop,
 * the user should capture it in a variable explicitly.
 */
const generateFor = (
  node: ForStatementContext,
  input: IGeneratorInput,
  state: IGeneratorState,
  orchestrator: IOrchestrator,
): IGeneratorOutput => {
  const effects: TGeneratorEffect[] = [];
 
  // ADR-113 / #1075 E0707: a for-loop with no controlling expression (`for (;;)`)
  // is a disguised infinite loop. C-Next has one source form for that — `forever`.
  if (!node.expression()) {
    throw new Error(
      "Error E0707: for-loop has no controlling expression (infinite loop)\n" +
        "  help: write 'forever { ... }' for an intentional infinite loop",
    );
  }
 
  let init = "";
  const forInit = node.forInit();
  if (forInit) {
    if (forInit.forVarDecl()) {
      const result = generateForVarDecl(
        forInit.forVarDecl()!,
        input,
        state,
        orchestrator,
      );
      init = result.code;
      effects.push(...result.effects);
    E} else if (forInit.forAssignment()) {
      const result = generateForAssignment(
        forInit.forAssignment()!,
        input,
        state,
        orchestrator,
      );
      init = result.code;
      effects.push(...result.effects);
    }
  }
 
  // Issue #250: Flush temps from init before generating condition
  const initTemps = orchestrator.flushPendingTempDeclarations();
 
  // The empty-header case (`for (;;)`) already threw E0707 above, so the
  // controlling expression is guaranteed present here.
  const conditionExpr = node.expression()!;
 
  // Issue #254: Validate no function calls in condition (E0702)
  orchestrator.validateConditionNoFunctionCall(conditionExpr, "for");
 
  // Issue #884: Validate condition is a boolean expression (E0701)
  orchestrator.validateConditionIsBoolean(conditionExpr, "for");
 
  // ADR-113 / #1075: reject always-true literal condition (E0707)
  orchestrator.validateLoopConditionNotAlwaysTrue(conditionExpr);
 
  const condition = orchestrator.generateExpression(conditionExpr);
 
  // Issue #250: Flush temps from condition before generating update
  const conditionTemps = orchestrator.flushPendingTempDeclarations();
 
  let update = "";
  const forUpdate = node.forUpdate();
  if (forUpdate) {
    const target = orchestrator.generateAssignmentTarget(
      forUpdate.assignmentTarget(),
    );
    const value = orchestrator.generateExpression(forUpdate.expression());
    const operatorCtx = forUpdate.assignmentOperator();
    const cnextOp = operatorCtx.getText();
    const cOp = ASSIGNMENT_OPERATOR_MAP[cnextOp] || "=";
    update = `${target} ${cOp} ${value}`;
  }
 
  // Issue #250: Flush temps from update before generating body
  const updateTemps = orchestrator.flushPendingTempDeclarations();
 
  const body = orchestrator.generateStatement(node.statement());
 
  let result = `for (${init}; ${condition}; ${update}) ${body}`;
 
  // Prepend all temps before the for statement
  const allTemps = [initTemps, conditionTemps, updateTemps]
    .filter(Boolean)
    .join("\n");
  if (allTemps) {
    result = allTemps + "\n" + result;
  }
 
  return { code: result, effects };
};
 
/**
 * Generate C code for a forever statement (ADR-113).
 *
 * Lowers to the MISRA C:2012 Rule 14.3-compliant infinite-loop idiom `for (;;)`
 * (the carve-out that rule explicitly permits — no controlling expression to be
 * flagged as invariant). A `forever` loop may appear only in a void function
 * (E0705): a value-returning function can never honor its return type if it
 * loops forever.
 */
const generateForever = (
  node: ForeverStatementContext,
  _input: IGeneratorInput,
  _state: IGeneratorState,
  orchestrator: IOrchestrator,
): IGeneratorOutput => {
  const effects: TGeneratorEffect[] = [];
 
  // ADR-113 E0705: forever is void-only.
  const returnType = orchestrator.getCurrentFunctionReturnType();
  Iif (returnType && returnType !== "void") {
    throw new Error(
      "Error E0705: forever loop in non-void function\n" +
        "  help: a forever loop never returns a value; make the function return void, " +
        "or use a while loop with an exit condition",
    );
  }
 
  const body = orchestrator.generateBlock(node.block());
  const comment =
    "/* MISRA C:2012 Rule 14.3: infinite loop is intentional (C-Next `forever`) */";
 
  return { code: `${comment}\nfor (;;) ${body}`, effects };
};
 
// Export all control flow generators
const controlFlowGenerators = {
  generateReturn,
  generateIf,
  generateWhile,
  generateDoWhile,
  generateFor,
  generateForever,
  generateForVarDecl,
  generateForAssignment,
};
 
export default controlFlowGenerators;