All files / transpiler/output/codegen/generators/declarationGenerators ScopeGenerator.ts

95.31% Statements 183/192
91.17% Branches 93/102
100% Functions 18/18
96.27% Lines 181/188

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 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684                                                                                      107x     56x 56x 56x 56x         51x                     9x 9x                               3x   3x 4x   4x           4x 1x           3x     2x                         119x     119x 119x 3x                     116x         116x 116x 119x         119x 3x     113x                                         3x 3x 3x     3x 3x 3x             3x                           113x 113x 113x 113x     113x       113x 113x 1x   113x         113x 113x 113x 5x       5x           113x               113x 113x 113x     113x 113x         113x   6x       112x                 112x 5x   107x     112x                         174x 174x   174x       174x     174x     174x     174x       174x     174x     174x         174x 174x 174x   174x 174x     174x   174x                       3x 3x   3x 8x 8x     8x   8x 3x 3x 3x       8x 8x 8x     3x                                     370x     370x 370x   370x 370x     370x 119x 119x           119x       251x 174x 174x                   77x 3x 3x               74x 6x 6x       68x 7x 7x             7x         61x 6x 6x                     55x                     29x           244x     244x                           244x   244x 244x   244x 370x         234x     234x   234x                               3x 3x     3x 3x                           3x         3x   3x                     6x 6x   6x 6x   2x   2x   1x   1x                   6x   2x 2x   2x 4x 4x     4x   4x 4x     4x     2x 2x                       6x 6x 6x   6x 6x     6x 6x     6x     6x   6x                   7x 7x     7x 7x           7x 7x 1x       7x   7x                         6x 6x     6x 7x     6x   6x        
/**
 * ScopeGenerator - ADR-016 Scope Declaration Generation
 *
 * Generates C code from C-Next scope declarations with visibility control.
 * Scopes provide namespace prefixing and static/extern visibility.
 *
 * Example:
 *   scope Driver {
 *     private u32 counter;
 *     public fn init() -> void { counter <- 0; }
 *   }
 *   ->
 *   // Scope: Driver
 *   static uint32_t Driver_counter = 0;
 *   void Driver_init(void) { Driver_counter = 0; }
 */
import * as Parser from "../../../../logic/parser/grammar/CNextParser";
import IGeneratorInput from "../IGeneratorInput";
import IGeneratorState from "../IGeneratorState";
import IGeneratorOutput from "../IGeneratorOutput";
import IOrchestrator from "../IOrchestrator";
import TGeneratorFn from "../TGeneratorFn";
import generateScopedRegister from "./ScopedRegisterGenerator";
import BitmapCommentUtils from "./BitmapCommentUtils";
import ArrayDimensionUtils from "./ArrayDimensionUtils";
import QualifiedNameGenerator from "../../utils/QualifiedNameGenerator";
import type IScopeSymbol from "../../../../types/symbols/IScopeSymbol";
import CodeGenState from "../../../../state/CodeGenState";
import AdrProvenance from "../../../../state/AdrProvenance";
import SymbolRegistry from "../../../../state/SymbolRegistry";
import ScopeUtils from "../../../../../utils/ScopeUtils";
import QualifiedCName from "../../../../../utils/QualifiedCName";
import VariableModifierBuilder from "../../helpers/VariableModifierBuilder";
 
/**
 * Generate initializer expression for a variable declaration.
 * Issue #872: Sets expectedType for MISRA 7.2 U suffix on unsigned literals.
 */
function generateInitializer(
  varDecl: Parser.VariableDeclarationContext,
  isArray: boolean,
  orchestrator: IOrchestrator,
): string {
  if (varDecl.expression()) {
    // Issue #872: Set expectedType for MISRA 7.2 U suffix compliance
    // Issue #992: withDeclarationInit suppresses compound literals at file scope (GCC 9-12 compat)
    const typeName = orchestrator.generateType(varDecl.type());
    return CodeGenState.withExpectedType(typeName, () =>
      CodeGenState.withDeclarationInit(
        () => ` = ${orchestrator.generateExpression(varDecl.expression()!)}`,
      ),
    );
  }
  // ADR-015: Zero initialization for uninitialized scope variables
  return ` = ${orchestrator.getZeroInitializer(varDecl.type(), isArray)}`;
}
 
/**
 * Extract scoped name from a declaration node.
 * Returns both the local name and the fully qualified scoped name.
 */
function getScopedName(
  node: { IDENTIFIER(): { getText(): string } },
  declaringScope: IScopeSymbol | null,
): { name: string; fullName: string } {
  const name = node.IDENTIFIER().getText();
  return {
    name,
    fullName: QualifiedNameGenerator.forMember(declaringScope, name),
  };
}
 
/**
 * Validate and resolve constructor arguments, ensuring each is const.
 * Returns array of scope-prefixed argument names.
 */
function resolveConstructorArgs(
  argIdentifiers: { getText(): string }[],
  declaringScope: IScopeSymbol | null,
  line: number,
  orchestrator: IOrchestrator,
): string[] {
  const resolvedArgs: string[] = [];
 
  for (const argNode of argIdentifiers) {
    const argName = argNode.getText();
    // Arguments must be resolved with scope prefix
    const scopedArgName = QualifiedNameGenerator.forMember(
      declaringScope,
      argName,
    );
 
    // Check if it's const using orchestrator
    if (!orchestrator.isConstValue(scopedArgName)) {
      throw new Error(
        `Error at line ${line}: Constructor argument '${argName}' must be const. ` +
          `C++ constructors in C-Next only accept const variables.`,
      );
    }
 
    resolvedArgs.push(scopedArgName);
  }
 
  return resolvedArgs;
}
 
/**
 * Generate a scope variable declaration.
 * Returns the declaration string, or null if the variable should be skipped.
 */
function generateScopeVariable(
  varDecl: Parser.VariableDeclarationContext,
  declaringScope: IScopeSymbol | null,
  isPrivate: boolean,
  orchestrator: IOrchestrator,
): string | null {
  const varName = varDecl.IDENTIFIER().getText();
 
  // Issue #375: Check for constructor syntax
  const constructorArgList = varDecl.constructorArgumentList();
  if (constructorArgList) {
    return generateConstructorVariable(
      varDecl,
      varName,
      declaringScope,
      isPrivate,
      constructorArgList,
      orchestrator,
    );
  }
 
  // Issue #282: Check if this is a const variable - const values should be inlined
  const isConst = varDecl.constModifier() !== null;
 
  // Issue #500: Check if array before skipping - arrays must be emitted
  // Check both C-style arrayDimension and C-Next style arrayType
  // Use optional chaining for mock compatibility in tests
  const arrayDims = varDecl.arrayDimension();
  const arrayTypeCtx = varDecl.type().arrayType?.() ?? null;
  const isArray = arrayDims.length > 0 || arrayTypeCtx !== null;
 
  // Issue #282: Private const variables should be inlined, not emitted at file scope
  // Issue #500: EXCEPT arrays - arrays must be emitted as static const
  // The inlining happens in CodeGenerator when resolving this.CONST_NAME
  if (isPrivate && isConst && !isArray) {
    return null;
  }
 
  return generateRegularVariable(
    varDecl,
    varName,
    declaringScope,
    isPrivate,
    orchestrator,
  );
}
 
/**
 * Generate a constructor-style variable declaration.
 */
function generateConstructorVariable(
  varDecl: Parser.VariableDeclarationContext,
  varName: string,
  declaringScope: IScopeSymbol | null,
  isPrivate: boolean,
  constructorArgList: Parser.ConstructorArgumentListContext,
  orchestrator: IOrchestrator,
): string {
  // ADR-016: All scope variables are emitted at file scope
  const type = orchestrator.generateType(varDecl.type());
  const fullName = QualifiedNameGenerator.forMember(declaringScope, varName);
  const prefix = isPrivate ? "static " : "";
 
  // Validate and resolve constructor arguments
  const argIdentifiers = constructorArgList.IDENTIFIER();
  const line = varDecl.start?.line ?? 0;
  const resolvedArgs = resolveConstructorArgs(
    argIdentifiers,
    declaringScope,
    line,
    orchestrator,
  );
 
  return `${prefix}${type} ${fullName}(${resolvedArgs.join(", ")});`;
}
 
/**
 * Generate a regular (non-constructor) variable declaration.
 */
function generateRegularVariable(
  varDecl: Parser.VariableDeclarationContext,
  varName: string,
  declaringScope: IScopeSymbol | null,
  isPrivate: boolean,
  orchestrator: IOrchestrator,
): string {
  // Derive array and const info from varDecl
  const isConst = varDecl.constModifier() !== null;
  const arrayDims = varDecl.arrayDimension();
  const arrayTypeCtx = varDecl.type().arrayType?.() ?? null;
  const isArray = arrayDims.length > 0 || arrayTypeCtx !== null;
 
  // ADR-016: All scope variables are emitted at file scope (static-like persistence)
  let type = orchestrator.generateType(varDecl.type());
  // Issue #1200: a callback-typed scope member renders as its function-pointer
  // typedef. Without this the raw function name was emitted as the type, which
  // collides with the function of the same name.
  const callbackTypedef = orchestrator.getCallbackTypedefName(type);
  if (callbackTypedef !== null) {
    type = callbackTypedef;
  }
  const fullName = QualifiedNameGenerator.forMember(declaringScope, varName);
 
  // Issue #948: Check if this is an opaque (forward-declared) struct type
  // Issue #958: Also check for external typedef struct types (complete definitions)
  // Both opaque and external typedef struct types must be declared as pointers
  const isOpaque = orchestrator.isOpaqueType(type);
  const isExternalStruct = orchestrator.isTypedefStructType(type);
  if (isOpaque || isExternalStruct) {
    type = `${type}*`;
    // Mark as "opaque" scope variable so CallExprGenerator knows this is already
    // a pointer and doesn't add '&' when passing to functions. The name is historical
    // but the tracking applies to any scope variable declared as a pointer type.
    orchestrator.markOpaqueScopeVariable(fullName);
  }
 
  // Issue #998: Use VariableModifierBuilder for consistent modifier handling
  // This handles const, atomic, volatile, and validates mutual exclusion
  // Scope variables are always at file scope (not in function body), no initializer for modifier purposes
  const modifiers = VariableModifierBuilder.build(
    varDecl,
    false, // inFunctionBody - scope vars are file scope
    false, // hasInitializer - doesn't affect volatile/atomic handling
    false, // cppMode - doesn't affect volatile/atomic handling
  );
  // For scope variables: static for private, no modifier for public
  // Then add volatile (from atomic or volatile keyword), then const
  const staticPrefix = isPrivate ? "static " : "";
  const volatilePrefix = modifiers.atomic || modifiers.volatile;
  const constPrefix = isConst ? "const " : "";
 
  // Build declaration with all dimensions
  let decl = `${staticPrefix}${volatilePrefix}${constPrefix}${type} ${fullName}`;
  decl += ArrayDimensionUtils.generateArrayTypeDimension(
    arrayTypeCtx,
    orchestrator,
  );
 
  if (arrayDims.length > 0) {
    // C-style or additional dimensions
    decl += orchestrator.generateArrayDimensions(arrayDims);
  }
 
  // ADR-045: Add string capacity dimension for string arrays
  decl += ArrayDimensionUtils.generateStringCapacityDim(varDecl.type());
 
  // Issue #948: Opaque types use NULL initialization instead of {0}
  // Issue #958: External typedef struct types also use NULL initialization
  // Issue #996: ...but only for SCALAR handles, which are single pointers. An
  // *array* of opaque handles needs a brace initializer ({0}), not a scalar
  // NULL. Route arrays through generateInitializer, which uses
  // getZeroInitializer(type, isArray) — the single source of truth for
  // zero-initialization (ADR-015).
  if ((isOpaque || isExternalStruct) && !isArray) {
    decl += " = NULL";
  } else {
    decl += generateInitializer(varDecl, isArray, orchestrator);
  }
 
  return decl + ";";
}
 
/**
 * Generate a scope function declaration.
 * Returns array of output lines (function definition + optional callback typedef).
 */
function generateScopeFunction(
  funcDecl: Parser.FunctionDeclarationContext,
  declaringScope: IScopeSymbol | null,
  isPrivate: boolean,
  orchestrator: IOrchestrator,
): string[] {
  const returnType = orchestrator.generateType(funcDecl.type());
  const funcName = funcDecl.IDENTIFIER().getText();
  // Use QualifiedNameGenerator for consistent C-style name generation
  const fullName = QualifiedNameGenerator.forFunctionInScope(
    declaringScope,
    funcName,
  );
  const prefix = isPrivate ? "static " : "";
 
  // Issue #269: Set current function name for pass-by-value lookup
  orchestrator.setCurrentFunctionName(fullName);
 
  // Track parameters for ADR-006 pointer semantics
  orchestrator.setParameters(funcDecl.parameterList() ?? null);
 
  // ADR-016: Enter function body context (also clears modifiedParameters for Issue #281)
  orchestrator.enterFunctionBody();
 
  // Issue #281: Generate body FIRST to track parameter modifications,
  // then generate parameter list using that tracking info
  const body = orchestrator.generateBlock(funcDecl.block());
 
  // Issue #281: Update symbol's parameter info with auto-const before generating params
  orchestrator.updateFunctionParamsAutoConst(fullName);
 
  // Now generate parameter list (can use modifiedParameters for auto-const)
  const params = funcDecl.parameterList()
    ? orchestrator.generateParameterList(funcDecl.parameterList()!)
    : "void";
 
  // ADR-016: Exit function body context
  orchestrator.exitFunctionBody();
  orchestrator.setCurrentFunctionName(null); // Issue #269: Clear function name
  orchestrator.clearParameters();
 
  const lines: string[] = [];
  lines.push("", `${prefix}${returnType} ${fullName}(${params}) ${body}`);
 
  // ADR-029: Generate callback typedef only if used as a type
  orchestrator.recordCallbackTypedef(fullName);
 
  return lines;
}
 
/**
 * Generate enum members from AST when symbol info is not available.
 * Returns array of formatted enum member lines.
 */
function generateEnumMembersFromAST(
  members: Parser.EnumMemberContext[],
  fullName: string,
  orchestrator: IOrchestrator,
): string[] {
  const lines: string[] = [];
  let currentValue = 0;
 
  for (let i = 0; i < members.length; i++) {
    const member = members[i];
    const memberName = member.IDENTIFIER().getText();
    // #1285: qualified by the ENUM, not a scope -- see the note in
    // generateScopedEnumInline. `fullName` is already fully qualified.
    const fullMemberName = QualifiedCName.fromParts([fullName, memberName]);
 
    if (member.expression()) {
      const constValue = orchestrator.tryEvaluateConstant(member.expression()!);
      Eif (constValue !== undefined) {
        currentValue = constValue;
      }
    }
 
    const comma = i < members.length - 1 ? "," : "";
    lines.push(`    ${fullMemberName} = ${currentValue}${comma}`);
    currentValue++;
  }
 
  return lines;
}
 
/**
 * Process a single scope member and return lines to add.
 */
function processScopeMember(
  member: Parser.ScopeMemberContext,
  declaringScope: IScopeSymbol | null,
  input: IGeneratorInput,
  state: IGeneratorState,
  orchestrator: IOrchestrator,
): string[] {
  // #1241: ADR-016's rule -- a scope member is emitted at file scope under a
  // scope-qualified C name, with visibility deciding linkage -- fires once per
  // member, here. Recorded at the MEMBER's position rather than the scope's, so
  // a variable member and a function member land in different matrix contexts
  // (scope-member vs scope-method) instead of both crediting whichever
  // declaration the scope keyword happens to sit in.
  AdrProvenance.record("016", member.start?.line);
 
  // ADR-016: Member-type-aware visibility defaults via ScopeUtils
  const explicitVisibility = member.visibilityModifier()?.getText();
  const isFunction = member.functionDeclaration() !== null;
  const visibility =
    explicitVisibility ?? ScopeUtils.getDefaultVisibility(isFunction);
  const isPrivate = visibility === "private";
 
  // Handle variable declarations
  if (member.variableDeclaration()) {
    const varDecl = member.variableDeclaration()!;
    const result = generateScopeVariable(
      varDecl,
      declaringScope,
      isPrivate,
      orchestrator,
    );
    return result === null ? [] : [result];
  }
 
  // Handle function declarations
  if (member.functionDeclaration()) {
    const funcDecl = member.functionDeclaration()!;
    return generateScopeFunction(
      funcDecl,
      declaringScope,
      isPrivate,
      orchestrator,
    );
  }
 
  // ADR-017: Handle enum declarations inside scopes
  // Issue #369: Skip enum definition if self-include was added (it will be in the header)
  if (member.enumDeclaration() && !state.selfIncludeAdded) {
    const enumDecl = member.enumDeclaration()!;
    return [
      "",
      generateScopedEnumInline(enumDecl, declaringScope, input, orchestrator),
    ];
  }
 
  // ADR-034: Handle bitmap declarations inside scopes
  // Issue #369: Skip bitmap definition if self-include was added (it will be in the header)
  if (member.bitmapDeclaration() && !state.selfIncludeAdded) {
    const bitmapDecl = member.bitmapDeclaration()!;
    return ["", generateScopedBitmapInline(bitmapDecl, declaringScope, input)];
  }
 
  // Handle register declarations inside scopes
  if (member.registerDeclaration()) {
    const regDecl = member.registerDeclaration()!;
    const result = generateScopedRegister(
      regDecl,
      declaringScope,
      input,
      state,
      orchestrator,
    );
    return ["", result.code];
  }
 
  // Handle struct declarations inside scopes
  // Issue #369: Skip struct definition if self-include was added (it will be in the header)
  if (member.structDeclaration() && !state.selfIncludeAdded) {
    const structDecl = member.structDeclaration()!;
    return [
      "",
      generateScopedStructInline(
        structDecl,
        declaringScope,
        input,
        orchestrator,
      ),
    ];
  }
 
  return [];
}
 
/**
 * Generate C code from a C-Next scope declaration.
 *
 * ADR-016: Scopes provide:
 * - Namespace prefixing (Scope_member)
 * - Visibility control (private -> static, public -> extern)
 * - Organization without runtime overhead
 */
const generateScope: TGeneratorFn<Parser.ScopeDeclarationContext> = (
  node: Parser.ScopeDeclarationContext,
  input: IGeneratorInput,
  state: IGeneratorState,
  orchestrator: IOrchestrator,
): IGeneratorOutput => {
  const name = node.IDENTIFIER().getText();
 
  // Set current scope for nested generation (imperative, not effect-based)
  orchestrator.setCurrentScope(name);
 
  // #1285: thread the scope SYMBOL, not its name, so every member below qualifies
  // through the parent chain instead of re-joining one level from a leaf.
  //
  // Resolved here rather than read back from `CodeGenState.currentScope`: that
  // would make the generated NAMES depend on `orchestrator.setCurrentScope` having
  // reached global state, which is a side effect through an interface. A mock
  // orchestrator that does not forward it produced bare names with nothing failing
  // at the type level. `getOrCreateScope` is the same resolver `setCurrentScopeByPath`
  // uses, and it is cached, so this is one decision asked twice -- not two decisions.
  //
  // Passing a leaf path is correct while `scopeMember` admits no `scopeDeclaration`;
  // that limit is tracked as #1304 and is unchanged by this.
  const declaringScope = SymbolRegistry.getOrCreateScope(name);
 
  const lines: string[] = [];
  lines.push(`/* Scope: ${name} */`);
 
  for (const member of node.scopeMember()) {
    lines.push(
      ...processScopeMember(member, declaringScope, input, state, orchestrator),
    );
  }
 
  lines.push("");
 
  // Clear scope at end
  orchestrator.setCurrentScope(null);
 
  return {
    code: lines.join("\n"),
    effects: [],
  };
};
 
/**
 * Generate enum inside a scope with proper prefixing.
 * Uses symbol info for enum members if available.
 */
function generateScopedEnumInline(
  node: Parser.EnumDeclarationContext,
  declaringScope: IScopeSymbol | null,
  input: IGeneratorInput,
  orchestrator: IOrchestrator,
): string {
  const { fullName } = getScopedName(node, declaringScope);
  const lines: string[] = [`typedef enum {`];
 
  // Try to get members from symbol info first
  const symbolMembers = input.symbols?.enumMembers.get(fullName);
  Iif (symbolMembers) {
    const memberEntries = Array.from(symbolMembers.entries());
    for (let i = 0; i < memberEntries.length; i++) {
      const [memberName, value] = memberEntries[i];
      // #1285: an enum member is qualified by its ENUM, not by a scope, and
      // `fullName` is already fully qualified. Joining two qualified names is
      // `QualifiedCName.fromParts`; routing it through `forMember` was what forced
      // helper to keep taking plain strings, hiding a scope encoder behind an enum one.
      const fullMemberName = QualifiedCName.fromParts([fullName, memberName]);
      const comma = i < memberEntries.length - 1 ? "," : "";
      lines.push(`    ${fullMemberName} = ${value}${comma}`);
    }
  } else {
    // Fall back to AST parsing
    lines.push(
      ...generateEnumMembersFromAST(node.enumMember(), fullName, orchestrator),
    );
  }
 
  lines.push(`} ${fullName};`, "");
 
  return lines.join("\n");
}
 
/**
 * Resolve bitmap backing type from symbols or keyword
 */
function _getBitmapBackingType(
  fullName: string,
  node: Parser.BitmapDeclarationContext,
  input: IGeneratorInput,
): string {
  const symbolType = input.symbols?.bitmapBackingType.get(fullName);
  Iif (symbolType) return symbolType;
 
  const bitmapKeyword = node.getChild(0)?.getText() || "bitmap32";
  switch (bitmapKeyword) {
    case "bitmap8":
      return "uint8_t";
    case "bitmap16":
      return "uint16_t";
    case "bitmap64":
      return "uint64_t";
    default:
      return "uint32_t";
  }
}
 
/**
 * Generate bitmap field comments from AST (fallback when symbols unavailable)
 */
function _generateBitmapFieldCommentsFromAST(
  fields: Parser.BitmapMemberContext[],
): string[] {
  if (fields.length === 0) return [];
 
  const lines: string[] = ["/* Fields:"];
  let bitOffset = 0;
 
  for (const field of fields) {
    const fieldName = field.IDENTIFIER().getText();
    const width = field.INTEGER_LITERAL()
      ? Number.parseInt(field.INTEGER_LITERAL()!.getText(), 10)
      : 1;
    const endBit = bitOffset + width - 1;
    const bitRange =
      width === 1 ? `bit ${bitOffset}` : `bits ${bitOffset}-${endBit}`;
    lines.push(
      ` *   ${fieldName}: ${bitRange} (${width} bit${width > 1 ? "s" : ""})`,
    );
    bitOffset += width;
  }
 
  lines.push(" */");
  return lines;
}
 
/**
 * Generate bitmap inside a scope with proper prefixing.
 * Uses symbol info for backing type if available.
 */
function generateScopedBitmapInline(
  node: Parser.BitmapDeclarationContext,
  declaringScope: IScopeSymbol | null,
  input: IGeneratorInput,
): string {
  const name = node.IDENTIFIER().getText();
  const fullName = QualifiedNameGenerator.forMember(declaringScope, name);
  const backingType = _getBitmapBackingType(fullName, node, input);
 
  const lines: string[] = [];
  lines.push(`/* Bitmap: ${fullName} */`);
 
  // Issue #707: Use shared utility for bitmap field comments
  const symbolFields = input.symbols?.bitmapFields.get(fullName);
  Iif (symbolFields) {
    lines.push(...BitmapCommentUtils.generateBitmapFieldComments(symbolFields));
  } else {
    lines.push(..._generateBitmapFieldCommentsFromAST(node.bitmapMember()));
  }
 
  lines.push(`typedef ${backingType} ${fullName};`, "");
 
  return lines.join("\n");
}
 
/**
 * Generate a single struct field declaration for scoped struct.
 */
function generateScopedStructField(
  member: Parser.StructMemberContext,
  orchestrator: IOrchestrator,
): string {
  const fieldName = member.IDENTIFIER().getText();
  const fieldType = orchestrator.generateType(member.type());
 
  // Handle C-Next style arrayType syntax (u16[8] arr)
  const arrayTypeCtx = member.type().arrayType?.() ?? null;
  let dimStr = ArrayDimensionUtils.generateArrayTypeDimension(
    arrayTypeCtx,
    orchestrator,
  );
 
  // Handle C-style array dimensions if present
  const arrayDims = member.arrayDimension();
  if (arrayDims.length > 0) {
    dimStr += orchestrator.generateArrayDimensions(arrayDims);
  }
 
  // Handle string capacity for string fields
  dimStr += ArrayDimensionUtils.generateStringCapacityDim(member.type());
 
  return `    ${fieldType} ${fieldName}${dimStr};`;
}
 
/**
 * Generate struct inside a scope with proper prefixing.
 * Struct fields maintain their original types.
 */
function generateScopedStructInline(
  node: Parser.StructDeclarationContext,
  declaringScope: IScopeSymbol | null,
  _input: IGeneratorInput,
  orchestrator: IOrchestrator,
): string {
  const { fullName } = getScopedName(node, declaringScope);
  const lines: string[] = [`typedef struct ${fullName} {`];
 
  // Process struct members
  for (const member of node.structMember()) {
    lines.push(generateScopedStructField(member, orchestrator));
  }
 
  lines.push(`} ${fullName};`, "");
 
  return lines.join("\n");
}
 
export default generateScope;