All files / transpiler/output/codegen/helpers TypeRegistrationEngine.ts

98.37% Statements 121/123
93.02% Branches 80/86
94.11% Functions 16/17
98.36% Lines 120/122

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                                                                                              961x 1609x 418x         1609x 153x                             418x 418x 21x 21x 21x 14x                       153x 153x 153x   153x 236x 73x 73x 73x 73x               153x                           5x 5x     5x 5x 1x   4x 4x                       7x                             832x 682x     150x   8x 8x     142x   3x     139x     13x 26x     13x 12x   1x     126x 124x       2x                             450x             868x 868x               941x 941x 941x   941x   941x   941x   941x                     41x     900x 75x                 75x     825x         825x 1x     824x                     61x     763x                                               941x 941x 899x     42x 42x 1x     41x 41x 41x   41x   41x   941x                     941x                               75x 75x   75x 57x 57x 18x 17x   17x 17x                     2x 2x   2x 2x     2x           2x       73x 1x     72x           72x                               72x   72x 73x 73x 73x 73x 66x         72x       72x 5x     72x             866x                               763x 763x 763x       763x                                               841x               841x           56x     785x       785x             7x     778x          
/**
 * Type Registration Engine
 * Issue #791: Extracted from CodeGenerator to reduce file size
 *
 * Registers variable types from AST before code generation.
 * This ensures type information is available for .length and
 * other type-dependent operations regardless of declaration order.
 */
 
import * as Parser from "../../../logic/parser/grammar/CNextParser";
import TIncludeHeader from "../generators/TIncludeHeader";
import TOverflowBehavior from "../types/TOverflowBehavior";
import TYPE_WIDTH from "../types/TYPE_WIDTH";
import CodeGenState from "../../../state/CodeGenState";
import TypeRegistrationUtils from "../TypeRegistrationUtils";
import QualifiedNameGenerator from "../utils/QualifiedNameGenerator";
import ArrayDimensionParser from "./ArrayDimensionParser";
 
/**
 * Callbacks required for type registration.
 * Minimizes coupling to CodeGenerator.
 */
interface ITypeRegistrationCallbacks {
  /** Evaluate a compile-time constant expression */
  tryEvaluateConstant: (ctx: Parser.ExpressionContext) => number | undefined;
  /** Request an include header */
  requireInclude: (header: TIncludeHeader) => void;
  /** Resolve qualified type names (optional, for C++ namespace support) */
  resolveQualifiedType?: (identifiers: string[]) => string;
}
 
/**
 * Static class that registers variable types from the AST.
 * Called during Stage 2 of code generation, before generating any code.
 */
class TypeRegistrationEngine {
  // ============================================================================
  // Public entry points
  // ============================================================================
 
  /**
   * Entry point: Register all variable types from the program tree.
   */
  static register(
    tree: Parser.ProgramContext,
    callbacks: ITypeRegistrationCallbacks,
  ): void {
    for (const decl of tree.declaration()) {
      if (decl.variableDeclaration()) {
        TypeRegistrationEngine.registerGlobalVariable(
          decl.variableDeclaration()!,
          callbacks,
        );
      }
      if (decl.scopeDeclaration()) {
        TypeRegistrationEngine.registerScopeMemberTypes(
          decl.scopeDeclaration()!,
          callbacks,
        );
      }
    }
  }
 
  /**
   * Register a global variable's type information.
   */
  static registerGlobalVariable(
    varDecl: Parser.VariableDeclarationContext,
    callbacks: ITypeRegistrationCallbacks,
  ): void {
    TypeRegistrationEngine._trackVariableType(varDecl, callbacks);
    if (varDecl.constModifier() && varDecl.expression()) {
      const constName = varDecl.IDENTIFIER().getText();
      const constValue = callbacks.tryEvaluateConstant(varDecl.expression()!);
      if (constValue !== undefined) {
        CodeGenState.constValues.set(constName, constValue);
      }
    }
  }
 
  /**
   * Register type information for all members in a scope.
   */
  static registerScopeMemberTypes(
    scopeDecl: Parser.ScopeDeclarationContext,
    callbacks: ITypeRegistrationCallbacks,
  ): void {
    const scopeName = scopeDecl.IDENTIFIER().getText();
    const savedScope = CodeGenState.currentScope;
    CodeGenState.currentScope = scopeName;
 
    for (const member of scopeDecl.scopeMember()) {
      if (member.variableDeclaration()) {
        const varDecl = member.variableDeclaration()!;
        const varName = varDecl.IDENTIFIER().getText();
        const fullName = QualifiedNameGenerator.forMember(scopeName, varName);
        TypeRegistrationEngine._trackVariableTypeWithName(
          varDecl,
          fullName,
          callbacks,
        );
      }
    }
 
    CodeGenState.currentScope = savedScope;
  }
 
  // ============================================================================
  // Static helper methods (public)
  // ============================================================================
 
  /**
   * Parse array dimension from arrayType context.
   * Returns the numeric size, or undefined if not a simple integer literal.
   */
  static parseArrayTypeDimension(
    arrayTypeCtx: Parser.ArrayTypeContext,
  ): number | undefined {
    const dims = arrayTypeCtx.arrayTypeDimension();
    Iif (dims.length === 0) {
      return undefined;
    }
    const sizeExpr = dims[0].expression();
    if (!sizeExpr) {
      return undefined;
    }
    const size = Number.parseInt(sizeExpr.getText(), 10);
    return Number.isNaN(size) ? undefined : size;
  }
 
  /**
   * Resolve base type name from a type context.
   * Handles primitive, scoped (this.Type), global, qualified, and user types.
   * Returns null for special types like string<N> that need separate handling.
   */
  static resolveBaseType(
    typeCtx: Parser.TypeContext,
    currentScope: string | null,
  ): string | null {
    return TypeRegistrationEngine._resolveBaseTypeWithCallbacks(
      typeCtx,
      currentScope,
    );
  }
 
  /**
   * Internal: Resolve base type with optional callback for qualified types.
   * When resolveQualifiedType callback is provided, uses it for C++ namespace support.
   */
  private static _resolveBaseTypeWithCallbacks(
    typeCtx: Parser.TypeContext,
    currentScope: string | null,
    callbacks?: ITypeRegistrationCallbacks,
  ): string | null {
    if (typeCtx.primitiveType()) {
      return typeCtx.primitiveType()!.getText();
    }
 
    if (typeCtx.scopedType()) {
      // ADR-016: Handle this.Type for scoped types (e.g., this.State -> Motor_State)
      const typeName = typeCtx.scopedType()!.IDENTIFIER().getText();
      return currentScope ? `${currentScope}_${typeName}` : typeName;
    }
 
    if (typeCtx.globalType()) {
      // Issue #478: Handle global.Type for global types inside scope
      return typeCtx.globalType()!.IDENTIFIER().getText();
    }
 
    if (typeCtx.qualifiedType()) {
      // ADR-016: Handle Scope.Type from outside scope
      // Issue #388: Also handles C++ namespace types when callback is provided
      const identifiers = typeCtx.qualifiedType()!.IDENTIFIER();
      const identifierNames = identifiers.map((id) => id.getText());
 
      // Use callback if provided for C++ namespace support
      if (callbacks?.resolveQualifiedType) {
        return callbacks.resolveQualifiedType(identifierNames);
      }
      return identifierNames.join("_");
    }
 
    if (typeCtx.userType()) {
      return typeCtx.userType()!.getText();
    }
 
    // String types and array types are handled separately
    return null;
  }
 
  // ============================================================================
  // Variable tracking methods
  // ============================================================================
 
  /**
   * Track a single variable declaration.
   * Used for local variable tracking during code generation.
   */
  static trackVariable(
    varDecl: Parser.VariableDeclarationContext,
    callbacks: ITypeRegistrationCallbacks,
  ): void {
    TypeRegistrationEngine._trackVariableType(varDecl, callbacks);
  }
 
  private static _trackVariableType(
    varDecl: Parser.VariableDeclarationContext,
    callbacks: ITypeRegistrationCallbacks,
  ): void {
    const name = varDecl.IDENTIFIER().getText();
    TypeRegistrationEngine._trackVariableTypeWithName(varDecl, name, callbacks);
  }
 
  private static _trackVariableTypeWithName(
    varDecl: Parser.VariableDeclarationContext,
    registryName: string,
    callbacks: ITypeRegistrationCallbacks,
  ): void {
    const typeCtx = varDecl.type();
    const arrayDim = varDecl.arrayDimension();
    const isConst = varDecl.constModifier() !== null;
 
    const overflowMod = varDecl.overflowModifier();
    const overflowBehavior: TOverflowBehavior =
      overflowMod?.getText() === "wrap" ? "wrap" : "clamp";
 
    const isAtomic = varDecl.atomicModifier() !== null;
 
    if (
      TypeRegistrationEngine._tryRegisterStringType(
        registryName,
        typeCtx,
        arrayDim,
        isConst,
        overflowBehavior,
        isAtomic,
        callbacks,
      )
    ) {
      return;
    }
 
    if (typeCtx.arrayType()) {
      TypeRegistrationEngine._registerArrayTypeVariable(
        registryName,
        typeCtx.arrayType()!,
        arrayDim,
        isConst,
        overflowBehavior,
        isAtomic,
        callbacks,
      );
      return;
    }
 
    const baseType = TypeRegistrationEngine._resolveBaseTypeWithCallbacks(
      typeCtx,
      CodeGenState.currentScope,
      callbacks,
    );
    if (!baseType) {
      return;
    }
 
    if (
      TypeRegistrationEngine._tryRegisterEnumOrBitmapType(
        registryName,
        baseType,
        isConst,
        arrayDim,
        overflowBehavior,
        isAtomic,
        callbacks,
      )
    ) {
      return;
    }
 
    TypeRegistrationEngine._registerStandardType(
      registryName,
      baseType,
      arrayDim,
      isConst,
      overflowBehavior,
      isAtomic,
      callbacks,
    );
  }
 
  // ============================================================================
  // String type registration
  // ============================================================================
 
  private static _tryRegisterStringType(
    registryName: string,
    typeCtx: Parser.TypeContext,
    arrayDim: Parser.ArrayDimensionContext[] | null,
    isConst: boolean,
    overflowBehavior: TOverflowBehavior,
    isAtomic: boolean,
    callbacks: ITypeRegistrationCallbacks,
  ): boolean {
    const stringCtx = typeCtx.stringType();
    if (!stringCtx) {
      return false;
    }
 
    const intLiteral = stringCtx.INTEGER_LITERAL();
    if (!intLiteral) {
      return false;
    }
 
    const capacity = Number.parseInt(intLiteral.getText(), 10);
    callbacks.requireInclude("string");
    const stringDim = capacity + 1;
 
    const additionalDims = ArrayDimensionParser.parseSimpleDimensions(arrayDim);
    const allDims =
      additionalDims.length > 0 ? [...additionalDims, stringDim] : [stringDim];
 
    CodeGenState.setVariableTypeInfo(registryName, {
      baseType: "char",
      bitWidth: 8,
      isArray: true,
      arrayDimensions: allDims,
      isConst,
      isString: true,
      stringCapacity: capacity,
      overflowBehavior,
      isAtomic,
    });
    return true;
  }
 
  // ============================================================================
  // Array and standard type registration
  // ============================================================================
 
  private static _registerArrayTypeVariable(
    registryName: string,
    arrayTypeCtx: Parser.ArrayTypeContext,
    arrayDim: Parser.ArrayDimensionContext[] | null,
    isConst: boolean,
    overflowBehavior: TOverflowBehavior,
    isAtomic: boolean,
    callbacks: ITypeRegistrationCallbacks,
  ): void {
    let baseType = "";
    let bitWidth = 0;
 
    if (arrayTypeCtx.primitiveType()) {
      baseType = arrayTypeCtx.primitiveType()!.getText();
      bitWidth = TYPE_WIDTH[baseType] || 0;
    } else if (arrayTypeCtx.userType()) {
      baseType = arrayTypeCtx.userType()!.getText();
 
      const combinedArrayDim = arrayDim ?? [];
      if (
        TypeRegistrationEngine._tryRegisterEnumOrBitmapType(
          registryName,
          baseType,
          isConst,
          combinedArrayDim,
          overflowBehavior,
          isAtomic,
          callbacks,
        )
      ) {
        const existingInfo = CodeGenState.getVariableTypeInfo(registryName);
        Eif (existingInfo) {
          const arrayTypeDim =
            TypeRegistrationEngine.parseArrayTypeDimension(arrayTypeCtx);
          const allDims = arrayTypeDim
            ? [arrayTypeDim, ...(existingInfo.arrayDimensions ?? [])]
            : existingInfo.arrayDimensions;
          CodeGenState.setVariableTypeInfo(registryName, {
            ...existingInfo,
            isArray: true,
            arrayDimensions: allDims,
          });
        }
        return;
      }
    }
 
    if (!baseType) {
      return;
    }
 
    const arrayDimensions = TypeRegistrationEngine._collectArrayDimensions(
      arrayTypeCtx,
      arrayDim,
      callbacks,
    );
 
    CodeGenState.setVariableTypeInfo(registryName, {
      baseType,
      bitWidth,
      isArray: true,
      arrayDimensions: arrayDimensions.length > 0 ? arrayDimensions : undefined,
      isConst,
      overflowBehavior,
      isAtomic,
    });
  }
 
  private static _collectArrayDimensions(
    arrayTypeCtx: Parser.ArrayTypeContext,
    arrayDim: Parser.ArrayDimensionContext[] | null,
    callbacks: ITypeRegistrationCallbacks,
  ): number[] {
    const arrayDimensions: number[] = [];
 
    for (const dim of arrayTypeCtx.arrayTypeDimension()) {
      const sizeExpr = dim.expression();
      Eif (sizeExpr) {
        const size = Number.parseInt(sizeExpr.getText(), 10);
        if (!Number.isNaN(size)) {
          arrayDimensions.push(size);
        }
      }
    }
 
    const additionalDims = TypeRegistrationEngine._evaluateArrayDimensions(
      arrayDim,
      callbacks,
    );
    if (additionalDims) {
      arrayDimensions.push(...additionalDims);
    }
 
    return arrayDimensions;
  }
 
  private static _evaluateArrayDimensions(
    arrayDim: Parser.ArrayDimensionContext[] | null,
    _callbacks: ITypeRegistrationCallbacks,
  ): number[] | undefined {
    return ArrayDimensionParser.parseAllDimensions(arrayDim, {
      constValues: CodeGenState.constValues,
      typeWidths: TYPE_WIDTH,
      isKnownStruct: (name) => CodeGenState.isKnownStruct(name),
    });
  }
 
  private static _registerStandardType(
    registryName: string,
    baseType: string,
    arrayDim: Parser.ArrayDimensionContext[] | null,
    isConst: boolean,
    overflowBehavior: TOverflowBehavior,
    isAtomic: boolean,
    callbacks: ITypeRegistrationCallbacks,
  ): void {
    const bitWidth = TYPE_WIDTH[baseType] || 0;
    const isArray = arrayDim !== null && arrayDim.length > 0;
    const arrayDimensions = isArray
      ? TypeRegistrationEngine._evaluateArrayDimensions(arrayDim, callbacks)
      : undefined;
 
    CodeGenState.setVariableTypeInfo(registryName, {
      baseType,
      bitWidth,
      isArray,
      arrayDimensions: isArray ? arrayDimensions : undefined,
      isConst,
      overflowBehavior,
      isAtomic,
    });
  }
 
  // ============================================================================
  // Enum/bitmap type registration
  // ============================================================================
 
  private static _tryRegisterEnumOrBitmapType(
    name: string,
    baseType: string,
    isConst: boolean,
    arrayDim: Parser.ArrayDimensionContext[] | null,
    overflowBehavior: TOverflowBehavior,
    isAtomic: boolean,
    callbacks: ITypeRegistrationCallbacks,
  ): boolean {
    const registrationOptions = {
      name,
      baseType,
      isConst,
      overflowBehavior,
      isAtomic,
    };
 
    if (
      TypeRegistrationUtils.tryRegisterEnumType(
        CodeGenState.symbols!,
        registrationOptions,
      )
    ) {
      return true;
    }
 
    const bitmapDimensions = TypeRegistrationEngine._evaluateArrayDimensions(
      arrayDim,
      callbacks,
    );
    if (
      TypeRegistrationUtils.tryRegisterBitmapType(
        CodeGenState.symbols!,
        registrationOptions,
        bitmapDimensions,
      )
    ) {
      return true;
    }
 
    return false;
  }
}
 
export default TypeRegistrationEngine;