All files / PARSE/3-Declare/cnext/adapters TSymbolInfoAdapter.ts

100% Statements 106/106
100% Branches 38/38
100% Functions 10/10
100% Lines 106/106

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                                                                                                        4094x 4094x 4094x 4094x 4094x     4094x     4094x 4094x           4094x 4094x 4094x           4094x     4094x 4094x 4094x     4094x 4094x 4094x 4094x 4094x 4094x     4094x     4094x     4094x 8507x   650x             650x     430x 430x     66x             66x     686x           686x     67x                 67x       2599x           2599x       4009x 4009x         4094x                                                                                 4094x           103x                   650x 650x   650x 650x 650x   650x   1052x 1052x   1052x 107x   107x         105x         650x 650x 650x 99x                 430x 430x               430x       969x                         66x 66x 66x 66x   66x 66x 364x         66x                           686x                             686x 686x 1168x   686x     686x                     67x 67x 67x     67x 67x 16x     67x 87x   87x 87x 87x           87x 19x                     2599x       2599x 2599x     2599x 395x 395x 9x 9x   395x               2204x       2599x     2599x             34x                     4009x 4009x 4009x       87x          
/**
 * TSymbolInfoAdapter - Converts TSymbol[] to ISymbolInfo for CodeGenerator.
 *
 * ADR-055 Phase 5: This adapter enables CodeGenerator to use pre-collected
 * symbols from CNextResolver instead of creating its own SymbolCollector.
 *
 * The conversion extracts and restructures the rich discriminated union types
 * into the flat map format that CodeGenerator expects via ISymbolInfo.
 */
 
import type IBitmapFieldLayout from "../../../../types/IBitmapFieldLayout";
import ICodeGenSymbols from "../../../../types/ICodeGenSymbols";
import CNEXT_TO_C_TYPE_MAP from "../../../../utils/constants/TypeMappings";
import TSymbol from "../../../../types/symbols/TSymbol";
import IBitmapSymbol from "../../../../types/symbols/IBitmapSymbol";
import IEnumSymbol from "../../../../types/symbols/IEnumSymbol";
import IFunctionSymbol from "../../../../types/symbols/IFunctionSymbol";
import IStructSymbol from "../../../../types/symbols/IStructSymbol";
import IRegisterSymbol from "../../../../types/symbols/IRegisterSymbol";
import IScopeSymbol from "../../../../types/symbols/IScopeSymbol";
import IVariableSymbol from "../../../../types/symbols/IVariableSymbol";
import TypeResolver from "../../../../utils/TypeResolver";
import ScopeUtils from "../../../../utils/ScopeUtils";
import QualifiedCName from "../../../../utils/QualifiedCName";
 
/**
 * Groups register-related maps for processRegister method.
 * Reduces parameter count for SonarCloud compliance.
 */
interface IRegisterMaps {
  knownRegisters: Set<string>;
  scopedRegisters: Map<string, string>;
  registerMemberAccess: Map<string, string>;
  registerMemberTypes: Map<string, string>;
  registerBaseAddresses: Map<string, string>;
  registerMemberOffsets: Map<string, string>;
  registerMemberCTypes: Map<string, string>;
}
 
/**
 * Converts TSymbol[] to ISymbolInfo for CodeGenerator.
 * Replaces the need for SymbolCollector during code generation.
 */
class TSymbolInfoAdapter {
  /**
   * Convert TSymbol[] to ISymbolInfo for CodeGenerator consumption.
   *
   * @param symbols Array of discriminated union symbols from CNextResolver
   * @returns ISymbolInfo compatible with CodeGenerator
   */
  static convert(symbols: readonly TSymbol[]): ICodeGenSymbols {
    // === Known Type Sets ===
    const knownScopes = new Set<string>();
    const knownStructs = new Set<string>();
    const knownEnums = new Set<string>();
    const knownBitmaps = new Set<string>();
    const knownRegisters = new Set<string>();
 
    // === Issue #1398: File-Scope Value Names ===
    const knownVariables = new Set<string>();
 
    // === Scope Information ===
    const scopeMembers = new Map<string, Set<string>>();
    const scopeMemberVisibility = new Map<
      string,
      Map<string, "public" | "private">
    >();
 
    // === Struct Information ===
    const structFields = new Map<string, Map<string, string>>();
    const structFieldArrays = new Map<string, Set<string>>();
    const structFieldDimensions = new Map<
      string,
      Map<string, (number | string)[]>
    >();
 
    // === Enum Information ===
    const enumMembers = new Map<string, Map<string, number>>();
 
    // === Bitmap Information ===
    const bitmapFields = new Map<string, Map<string, IBitmapFieldLayout>>();
    const bitmapBackingType = new Map<string, string>();
    const bitmapBitWidth = new Map<string, number>();
 
    // === Register Information ===
    const scopedRegisters = new Map<string, string>();
    const registerMemberAccess = new Map<string, string>();
    const registerMemberTypes = new Map<string, string>();
    const registerBaseAddresses = new Map<string, string>();
    const registerMemberOffsets = new Map<string, string>();
    const registerMemberCTypes = new Map<string, string>();
 
    // === Issue #282: Private const values for inlining ===
    const scopePrivateConstValues = new Map<string, string>();
 
    // === Function Return Types ===
    const functionReturnTypes = new Map<string, string>();
 
    // Process each symbol
    for (const symbol of symbols) {
      switch (symbol.kind) {
        case "struct":
          TSymbolInfoAdapter.processStruct(
            symbol,
            knownStructs,
            structFields,
            structFieldArrays,
            structFieldDimensions,
          );
          break;
 
        case "enum":
          TSymbolInfoAdapter.processEnum(symbol, knownEnums, enumMembers);
          break;
 
        case "bitmap":
          TSymbolInfoAdapter.processBitmap(
            symbol,
            knownBitmaps,
            bitmapFields,
            bitmapBackingType,
            bitmapBitWidth,
          );
          break;
 
        case "scope":
          TSymbolInfoAdapter.processScope(
            symbol,
            knownScopes,
            scopeMembers,
            scopeMemberVisibility,
          );
          break;
 
        case "register":
          TSymbolInfoAdapter.processRegister(symbol, knownBitmaps, {
            knownRegisters,
            scopedRegisters,
            registerMemberAccess,
            registerMemberTypes,
            registerBaseAddresses,
            registerMemberOffsets,
            registerMemberCTypes,
          });
          break;
 
        case "variable":
          // Track scope membership, private const values, and file-scope names
          TSymbolInfoAdapter.processVariable(
            symbol,
            scopeMembers,
            scopePrivateConstValues,
            knownVariables,
          );
          break;
 
        // Track function return types for enum validation
        case "function":
          TSymbolInfoAdapter.processFunction(symbol, functionReturnTypes);
          break;
      }
    }
 
    // Build the ISymbolInfo result
    const result: ICodeGenSymbols = {
      // Type sets
      knownScopes,
      knownStructs,
      knownEnums,
      knownBitmaps,
      knownRegisters,
      knownVariables,
 
      // Scope info
      scopeMembers,
      scopeMemberVisibility,
 
      // Struct info
      structFields,
      structFieldArrays,
      structFieldDimensions,
 
      // Enum info
      enumMembers,
 
      // Bitmap info
      bitmapFields,
      bitmapBackingType,
      bitmapBitWidth,
 
      // Register info
      scopedRegisters,
      registerMemberAccess,
      registerMemberTypes,
      registerBaseAddresses,
      registerMemberOffsets,
      registerMemberCTypes,
 
      // Issue #282: Private const values for inlining
      scopePrivateConstValues,
 
      // Function return types
      functionReturnTypes,
    };
 
    return result;
  }
 
  // === Private Processing Methods ===
 
  // Use shared utility for transpiled C names
  private static readonly getTranspiledCName = ScopeUtils.getTranspiledCName;
 
  private static processStruct(
    struct: IStructSymbol,
    knownStructs: Set<string>,
    structFields: Map<string, Map<string, string>>,
    structFieldArrays: Map<string, Set<string>>,
    structFieldDimensions: Map<string, Map<string, (number | string)[]>>,
  ): void {
    // Use transpiled C name for lookups (e.g., "Geometry_Point")
    const cName = TSymbolInfoAdapter.getTranspiledCName(struct);
    knownStructs.add(cName);
 
    const fields = new Map<string, string>();
    const arrayFields = new Set<string>();
    const dimensions = new Map<string, (number | string)[]>();
 
    for (const [fieldName, fieldInfo] of struct.fields) {
      // Convert TType to string for legacy ISymbolInfo format
      const typeStr = TypeResolver.getTypeName(fieldInfo.type);
      fields.set(fieldName, typeStr);
 
      if (fieldInfo.isArray) {
        arrayFields.add(fieldName);
 
        if (fieldInfo.dimensions && fieldInfo.dimensions.length > 0) {
          // Issue #1127: keep non-numeric dimensions. Filtering them out
          // dropped enum-qualified counts, so `u8[EColor.COUNT] slots` reached
          // the header as a scalar and the body as a bit-indexed value.
          // Filtering also shifted any dimension that followed a dropped one.
          dimensions.set(fieldName, [...fieldInfo.dimensions]);
        }
      }
    }
 
    structFields.set(cName, fields);
    structFieldArrays.set(cName, arrayFields);
    if (dimensions.size > 0) {
      structFieldDimensions.set(cName, dimensions);
    }
  }
 
  private static processEnum(
    enumSym: IEnumSymbol,
    knownEnums: Set<string>,
    enumMembers: Map<string, Map<string, number>>,
  ): void {
    const cName = TSymbolInfoAdapter.getTranspiledCName(enumSym);
    knownEnums.add(cName);
    // #1318: members are symbols now. `ICodeGenSymbols.enumMembers` is the
    // name-to-value view codegen wants, so project rather than widen it --
    // handing codegen a symbol here would put a second symbol vocabulary in
    // the per-file view for no consumer that asked for one.
    // #1669: a member with no value has its enum rejected by 2.1 (E0909,
    // E0910, E0911) before codegen reads this, so it is left out rather than
    // handed on as a number it does not have
    enumMembers.set(
      cName,
      new Map(
        [...enumSym.members].flatMap(([name, member]) =>
          member.value === null ? [] : [[name, member.value] as const],
        ),
      ),
    );
  }
 
  private static processBitmap(
    bitmap: IBitmapSymbol,
    knownBitmaps: Set<string>,
    bitmapFields: Map<string, Map<string, IBitmapFieldLayout>>,
    bitmapBackingType: Map<string, string>,
    bitmapBitWidth: Map<string, number>,
  ): void {
    const cName = TSymbolInfoAdapter.getTranspiledCName(bitmap);
    knownBitmaps.add(cName);
    bitmapBackingType.set(cName, bitmap.backingType);
    bitmapBitWidth.set(cName, bitmap.bitWidth);
 
    const fields = new Map<string, IBitmapFieldLayout>();
    for (const [fieldName, fieldInfo] of bitmap.fields) {
      fields.set(fieldName, {
        offset: fieldInfo.offset,
        width: fieldInfo.width,
      });
    }
    bitmapFields.set(cName, fields);
  }
 
  private static processScope(
    scope: IScopeSymbol,
    knownScopes: Set<string>,
    scopeMembers: Map<string, Set<string>>,
    scopeMemberVisibility: Map<string, Map<string, "public" | "private">>,
  ): void {
    // #1295: keyed by the scope's IDENTITY, never its leaf. `cnxScopedName` is
    // the dotted source path -- `Motor`, `Outer.Inner` -- which is the same
    // string every reader already holds (`currentScopePath`, a symbol's
    // `scopePath`), so no site converts. Keyed by the leaf, `Outer.Inner` and
    // `Other.Inner` collide and the second write silently replaces the first.
    knownScopes.add(scope.cnxScopedName);
 
    // Use scope.members as the authoritative list of member names
    // This includes functions, variables, enums, structs, etc.
    //
    // MERGED, not replaced. `processVariable` writes into the same key with
    // get-or-create-and-add, so an unconditional `set` here dropped every
    // variable that happened to be processed first. That was invisible because
    // `_collectScopeDeclaration` pushes the scope before its members -- an
    // emission-order coincidence nothing asserted, which is the shape this
    // whole line of work exists to remove.
    //
    // `scopeMemberVisibility` below needs no equivalent: `processScope` is its
    // only writer, and a reopened scope (ADR-016) is ONE symbol carrying many
    // `declarationSites` (#1334), not two symbols to merge.
    const members = scopeMembers.get(scope.cnxScopedName) ?? new Set<string>();
    for (const member of scope.members) {
      members.add(member);
    }
    scopeMembers.set(scope.cnxScopedName, members);
 
    // Copy visibility map
    scopeMemberVisibility.set(
      scope.cnxScopedName,
      new Map(scope.memberVisibility),
    );
  }
 
  private static processRegister(
    register: IRegisterSymbol,
    knownBitmaps: Set<string>,
    maps: IRegisterMaps,
  ): void {
    const cName = TSymbolInfoAdapter.getTranspiledCName(register);
    maps.knownRegisters.add(cName);
    maps.registerBaseAddresses.set(cName, register.baseAddress);
 
    // Check if this is a scoped register (has non-global scope)
    const isScoped = !ScopeUtils.isGlobalScopePath(register.scopePath);
    if (isScoped) {
      maps.scopedRegisters.set(cName, register.baseAddress);
    }
 
    for (const [memberName, memberInfo] of register.members) {
      const fullName = QualifiedCName.fromParts([cName, memberName]);
 
      maps.registerMemberAccess.set(fullName, memberInfo.access);
      maps.registerMemberOffsets.set(fullName, memberInfo.offset);
      maps.registerMemberCTypes.set(
        fullName,
        TSymbolInfoAdapter.cnextTypeToCType(memberInfo.cType),
      );
 
      // Track bitmap types for register members
      if (memberInfo.bitmapType && knownBitmaps.has(memberInfo.bitmapType)) {
        maps.registerMemberTypes.set(fullName, memberInfo.bitmapType);
      }
    }
  }
 
  private static processVariable(
    variable: IVariableSymbol,
    scopeMembers: Map<string, Set<string>>,
    scopePrivateConstValues: Map<string, string>,
    knownVariables: Set<string>,
  ): void {
    const cName = TSymbolInfoAdapter.getTranspiledCName(variable);
    // #1295: `scopeMembers` is keyed by the scope's dotted source path, which is
    // exactly what `scopePath` already holds -- no conversion here, and no
    // collision at depth two.
    const scopeName = variable.scopePath;
    const isScoped = !ScopeUtils.isGlobalScopePath(variable.scopePath);
 
    // Track scoped variables as scope members (needed for name resolution)
    if (isScoped) {
      let members = scopeMembers.get(scopeName);
      if (!members) {
        members = new Set<string>();
        scopeMembers.set(scopeName, members);
      }
      members.add(variable.name); // Add local name (e.g., "value"), not transpiled C name
    } else {
      // Issue #1398: a file-scope variable is reachable by its bare name, which
      // is the key the run-wide table is indexed by -- so recording it here is
      // what lets the value check ask a per-file question instead of a run-wide
      // one. Scoped variables are excluded because they are NOT reachable bare;
      // they are reached through `scopeMembers` above, which the value check
      // already consults under a scope path.
      knownVariables.add(variable.name);
    }
 
    // Issue #282: Track private const values for inlining
    const isPrivate = variable.visibility === "private";
 
    // Issue #500: Only inline SCALAR consts, not arrays - arrays must be emitted
    if (
      isScoped &&
      isPrivate &&
      variable.isConst &&
      variable.initialValue &&
      !variable.isArray
    ) {
      scopePrivateConstValues.set(cName, variable.initialValue);
    }
  }
 
  private static processFunction(
    func: IFunctionSymbol,
    functionReturnTypes: Map<string, string>,
  ): void {
    // Track function return types for enum validation in assignments
    // This enables recognizing that Motor.getMode() returns Motor_EMode
    // Use transpiled C name (e.g., "Motor_getMode") for lookup consistency
    const cName = TSymbolInfoAdapter.getTranspiledCName(func);
    const returnTypeStr = TypeResolver.getTypeName(func.returnType);
    functionReturnTypes.set(cName, returnTypeStr);
  }
 
  private static cnextTypeToCType(typeName: string): string {
    return CNEXT_TO_C_TYPE_MAP[typeName] || typeName;
  }
}
 
export default TSymbolInfoAdapter;