All files / PARSE/3-Declare/cnext/collectors ScopeCollector.ts

100% Statements 62/62
100% Branches 16/16
100% Functions 2/2
100% Lines 62/62

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                                                                                                          588x 588x     588x       588x     588x                                               588x               588x 424x 424x   588x     588x     588x       588x 588x                                 588x 973x 748x       588x 979x     979x 329x 329x 329x 329x   329x             329x       979x 460x 460x 460x 460x     460x               460x       979x 94x 94x 94x 94x   94x           94x       979x 11x 11x 11x 11x   11x           11x       979x 57x 57x 57x 57x   57x             57x       979x 22x 22x 22x 22x   22x               22x       588x          
/**
 * ScopeCollector - Extracts scope declarations and their nested members.
 * ADR-016: Scopes group related functions and control member visibility.
 *
 * Produces TType-based symbols with proper IScopeSymbol references.
 * Uses SymbolRegistry for scope management.
 */
 
import * as Parser from "../../../2-Parse/grammar/CNextParser";
import DeclarationSite from "../../../../utils/DeclarationSite";
import ESourceLanguage from "../../../../utils/types/ESourceLanguage";
import ScopeUtils from "../../../../utils/ScopeUtils";
import TSymbol from "../../../../types/symbols/TSymbol";
import TVisibility from "../../../../types/TVisibility";
import IScopeCollectorResult from "../types/IScopeCollectorResult";
import SymbolRegistry from "../../SymbolRegistry";
import BitmapCollector from "./BitmapCollector";
import EnumCollector from "./EnumCollector";
import StructCollector from "./StructCollector";
import FunctionCollector from "./FunctionCollector";
import VariableCollector from "./VariableCollector";
import RegisterCollector from "./RegisterCollector";
import type ISourceSpan from "../../../../types/ISourceSpan";
import UNSET_SOURCE_SPAN from "../../../../types/UNSET_SOURCE_SPAN";
import ParserUtils from "../../../../utils/ParserUtils";
 
class ScopeCollector {
  /**
   * Collect a scope declaration and all its nested members.
   *
   * Uses SymbolRegistry to get/create the scope, ensuring proper scope
   * references in all member symbols.
   *
   * **Side-effect**: This method calls registry.getOrCreateScope(),
   * which creates the scope in global state if it doesn't exist. Tests
   * constructs its own registry, so there is nothing to reset (#1452 box 3).
   *
   * @param ctx The scope declaration context
   * @param sourceFile Source file path
   * @param knownBitmaps Set of known bitmap type names for register resolution
   * @param isScopeType ADR-057: predicate answering whether a *qualified* name
   *                    is a type declared in a scope. Supplied by CNextResolver
   *                    from a pre-pass so the answer is complete before any
   *                    member's types are resolved.
   * @returns The scope symbol and all member symbols
   */
  static collect(
    registry: SymbolRegistry,
    ctx: Parser.ScopeDeclarationContext,
    sourceFile: string,
    knownBitmaps: Set<string>,
    isScopeType?: (qualifiedName: string) => boolean,
  ): IScopeCollectorResult {
    const scopeName = ctx.IDENTIFIER().getText();
    const span = ParserUtils.getSpan(ctx);
 
    // Get or create the scope via SymbolRegistry
    const scope = registry.getOrCreateScope(scopeName);
 
    // #1298: members carry the scope's PATH, not the scope object. Derived once
    // here so the six member collectors below cannot disagree about it.
    const scopePath = ScopeUtils.pathOf(scope);
 
    // Update scope metadata (cast to mutable for initialization)
    const mutableScope = scope as unknown as {
      sourceFile: string;
      span: ISourceSpan;
      sourceLanguage: ESourceLanguage;
      visibility: TVisibility;
      declarationSites: Set<string>;
    };
 
    // #1334: RECORD this block; do not overwrite the previous one. ADR-016 lets a
    // scope be reopened, getOrCreateScope caches by path, and this method used
    // to assign sourceFile/sourceLine unconditionally -- so a scope declared in
    // four files reported only the fourth, and a conflict naming two definitions
    // printed one location twice because there was only ever one position.
    //
    // Set membership is keyed on the rendered `file:line`, so re-collecting the
    // same textual block is a no-op rather than a duplicate entry.
    //
    // #1301 removed the only thing that presented a duplicate: `CNextResolver.resolve`
    // ran twice per file while Transpiler stages 3 and 5 each declared every file,
    // and now runs once. A scope REOPENED across files does NOT present one either --
    // each declaring block contributes a DISTINCT `file:line`. So this dedup is now
    // a ratchet with nothing exercising it, kept so that a reintroduced second pass
    // is absorbed rather than silently duplicating. Stated plainly because the
    // alternative is a comment claiming coverage the code no longer has.
    mutableScope.declarationSites.add(
      DeclarationSite.format(sourceFile, span.line),
    );
 
    // The scalars keep the FIRST site. Lossless now that declarationSites holds
    // the rest: UNSET_SOURCE_SPAN is createScope's initial value and its line is
    // 0, which no real position can be because ANTLR lines are 1-based -- so an
    // unset span is distinguishable from a real one.
    if (mutableScope.span.line === UNSET_SOURCE_SPAN.line) {
      mutableScope.sourceFile = sourceFile;
      mutableScope.span = span;
    }
    mutableScope.sourceLanguage = ESourceLanguage.CNext;
    // A scope is a container, not a declaration -- it is never marked private,
    // and `PublicInterface` excludes kind "scope" from the header regardless.
    mutableScope.visibility = "public";
 
    // Cast readonly collections to mutable (scope is being populated)
    const memberVisibility = scope.memberVisibility as unknown as Map<
      string,
      TVisibility
    >;
    const members = scope.members as unknown as string[];
    const memberSymbols: TSymbol[] = [];
 
    // #1334: `scope.members` is a shared mutable array on the cached scope, and
    // `CNextResolver.resolve` USED TO run more than once per file, so every member
    // was re-pushed on each pass -- measured, a four-block scope grew to
    // [Point, Mode, fromC, runAll, Point, Mode, fromC]. #1301 removed that pass.
    //
    // Like the `declarationSites` dedup above, this one is now UNEXERCISED: a
    // reopened scope contributes distinct names, and two members sharing a name in
    // one scope are rejected as E0425 before this list is read. Kept as a ratchet
    // against a reintroduced second pass, not because anything reaches it today.
    //
    // Harmless today only by coincidence: the one real consumer wraps it in a Set
    // (TSymbolInfoAdapter.ts:395). That is a latent divergence, not a working
    // path, so the duplication is stopped at the source instead. A scope cannot
    // legitimately hold two members of one name -- that case is a conflict, and
    // conflict detection reads the TSymbols, not this array.
    const addMember = (memberName: string): void => {
      if (!members.includes(memberName)) {
        members.push(memberName);
      }
    };
 
    for (const member of ctx.scopeMember()) {
      const visibility = ScopeUtils.getMemberVisibility(member);
 
      // Handle variable declarations
      if (member.variableDeclaration()) {
        const varDecl = member.variableDeclaration()!;
        const varName = varDecl.IDENTIFIER().getText();
        memberVisibility.set(varName, visibility);
        addMember(varName);
 
        const varSymbol = VariableCollector.collect(
          varDecl,
          sourceFile,
          scopePath,
          visibility,
          isScopeType,
        );
        memberSymbols.push(varSymbol);
      }
 
      // Handle function declarations
      if (member.functionDeclaration()) {
        const funcDecl = member.functionDeclaration()!;
        const funcName = funcDecl.IDENTIFIER().getText();
        memberVisibility.set(funcName, visibility);
        addMember(funcName);
 
        // Use collectAndRegister to populate both memberSymbols and SymbolRegistry
        const funcSymbol = FunctionCollector.collectAndRegister(
          registry,
          funcDecl,
          sourceFile,
          scopePath,
          visibility,
          isScopeType,
        );
        memberSymbols.push(funcSymbol);
      }
 
      // Handle enum declarations
      if (member.enumDeclaration()) {
        const enumDecl = member.enumDeclaration()!;
        const enumName = enumDecl.IDENTIFIER().getText();
        memberVisibility.set(enumName, visibility);
        addMember(enumName);
 
        const enumSymbol = EnumCollector.collect(
          enumDecl,
          sourceFile,
          scopePath,
          visibility,
        );
        memberSymbols.push(enumSymbol);
      }
 
      // Handle bitmap declarations
      if (member.bitmapDeclaration()) {
        const bitmapDecl = member.bitmapDeclaration()!;
        const bitmapName = bitmapDecl.IDENTIFIER().getText();
        memberVisibility.set(bitmapName, visibility);
        addMember(bitmapName);
 
        const bitmapSymbol = BitmapCollector.collect(
          bitmapDecl,
          sourceFile,
          scopePath,
          visibility,
        );
        memberSymbols.push(bitmapSymbol);
      }
 
      // Handle struct declarations
      if (member.structDeclaration()) {
        const structDecl = member.structDeclaration()!;
        const structName = structDecl.IDENTIFIER().getText();
        memberVisibility.set(structName, visibility);
        addMember(structName);
 
        const structSymbol = StructCollector.collect(
          structDecl,
          sourceFile,
          scopePath,
          visibility,
          isScopeType,
        );
        memberSymbols.push(structSymbol);
      }
 
      // Handle register declarations
      if (member.registerDeclaration()) {
        const regDecl = member.registerDeclaration()!;
        const regName = regDecl.IDENTIFIER().getText();
        memberVisibility.set(regName, visibility);
        addMember(regName);
 
        const regSymbol = RegisterCollector.collect(
          regDecl,
          sourceFile,
          knownBitmaps,
          scopePath,
          visibility,
          isScopeType,
        );
        memberSymbols.push(regSymbol);
      }
    }
 
    return { scopeSymbol: scope, memberSymbols };
  }
}
 
export default ScopeCollector;