All files / transpiler/logic/symbols TypeBinding.ts

100% Statements 33/33
100% Branches 24/24
100% Functions 5/5
100% Lines 32/32

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                                                                                                                                                5845x         5845x 4464x       1381x 5845x 293x     1088x 1088x 94x     994x                                           6925x 6925x 1030x     5895x 5895x                                               7190x 7190x 41x       7149x 7149x 31x       7118x 7118x 76x 38x           7080x 7080x 1087x 1087x         5993x             94x 94x          
/**
 * TypeBinding — the one ladder from a type parse context to a resolved name.
 *
 * Seven independent `scopedType()/globalType()/qualifiedType()/userType()`
 * ladders existed: two in TypeRegistrationEngine, one each in TypeUtils,
 * CodeGenerator.getTypeName, FunctionContextManager, TypeGenerationHelper, and
 * CodeGenerator's parameter path. Each decided ADR-057 qualification for itself,
 * so unifying the encoder (#1285 PR3) left seven places that still had to agree
 * about WHICH branch to apply it in.
 *
 * They already disagreed about coverage: each handled a different subset of the
 * six `arrayType` element alternatives, and their fallbacks differed (null vs
 * the raw parse text). Those subsets ARE reachable, and collapsing the ladders
 * closed two of them:
 *
 *   - `CodeGenerator.getTypeName` handled only `primitiveType` and `userType`
 *     inside `arrayType`, so `const Scope.TItem[] items <- ...` fell through to
 *     `ctx.getText()` and yielded the raw parse text `Scope.TItem[]`. The field
 *     types were then unknown and the initializer literals lost their integer
 *     suffixes (tests/header-generation/const-struct-array-inferred).
 *   - `getZeroInitializer` resolved a bare `userType()` unqualified, so a
 *     scope-local enum missed `knownEnums` and got the aggregate zero brace
 *     instead of ADR-017's zero member
 *     (tests/bugs/issue-1285-scope-enum-zero-init).
 *
 * So this is a bug fix as well as a unification, and the corpus does move --
 * in exactly those two places, both verified as corrections rather than
 * regressions before their snapshots were regenerated.
 *
 * Lives in `logic/symbols/` so both the symbols layer and codegen can reach it:
 * `logic/` may not import `output/`, and the predicates are injected rather than
 * read from CodeGenState so nothing here depends on codegen state.
 */
 
import ITypeAccessors from "../../types/ITypeAccessors";
import IScopeSymbol from "../../types/symbols/IScopeSymbol";
import QualifiedCName from "../../../utils/QualifiedCName";
import ScopeUtils from "../../../utils/ScopeUtils";
import * as Parser from "../parser/grammar/CNextParser";
 
interface ITypeBindingDeps {
  /**
   * ADR-057: whether a QUALIFIED name is a type declared in the current scope.
   * Consulted only for a bare `userType()` -- `this.T`, `global.T` and `Scope.T`
   * state their answer in the syntax and must keep their own branches, because
   * once a name is a string `global.Mode` and a bare `Mode` are identical.
   */
  readonly isScopeType?: (qualifiedName: string) => boolean;
 
  /**
   * C++ namespace-aware resolution for `Scope.Type` (Issue #388). Injected
   * because it is a codegen concern; without it the components are joined.
   */
  readonly resolveQualifiedType?: (identifiers: string[]) => string;
}
 
/**
 * Static utility class resolving a type context to its C name.
 */
class TypeBinding {
  /**
   * The C name for a type context, or null when no alternative matched.
   *
   * The six alternatives are mutually exclusive in the grammar, so branch order
   * carries no meaning -- which is why seven ladders in different orders behaved
   * the same and why collapsing them is safe.
   */
  static resolveName(
    accessors: ITypeAccessors,
    scope: IScopeSymbol | null,
    deps?: ITypeBindingDeps,
  ): string | null {
    const direct = TypeBinding.resolveNamedOrPrimitiveType(
      accessors,
      scope,
      deps,
    );
    if (direct !== null) {
      return direct;
    }
 
    // Arrays carry their element type; recurse rather than re-deriving it.
    const array = accessors.arrayType?.();
    if (array) {
      return TypeBinding.resolveName(array, scope, deps);
    }
 
    const str = accessors.stringType();
    if (str) {
      return TypeBinding.resolveStringType(str);
    }
 
    return null;
  }
 
  /**
   * The C name for a type that names itself outright -- a named type or a
   * primitive -- and null for the two alternatives that WRAP another type.
   *
   * This is the allow-list a caller wants when it handles `arrayType` and
   * `stringType` itself because it needs a bit width or a capacity alongside
   * the name, which is what TypeRegistrationEngine's variable-registration path
   * does. Asking `resolveNamedType` there dropped every primitive on the floor:
   * its caller treats a falsy base type as "not registerable" and returns, so
   * `u32 counter` registered no type info at all and the ADR-044 overflow
   * helpers stopped being emitted across 478 fixtures. Naming the pair the
   * caller accepts keeps that an allow-list rather than reinstating the
   * grammar-tracking exclusion list it replaced.
   */
  static resolveNamedOrPrimitiveType(
    accessors: ITypeAccessors,
    scope: IScopeSymbol | null,
    deps?: ITypeBindingDeps,
  ): string | null {
    const named = TypeBinding.resolveNamedType(accessors, scope, deps);
    if (named !== null) {
      return named;
    }
 
    const primitive = accessors.primitiveType();
    return primitive ? primitive.getText() : null;
  }
 
  /**
   * The C name for a NAMED type -- `this.T`, `global.T`, `Scope.T` or a bare
   * `T` -- and null for every other alternative.
   *
   * This is an ALLOW-LIST, and that direction is the point. Callers that only
   * ever wanted named types previously spelled out the alternatives they would
   * NOT answer for and let everything else through to the ladder; three callers
   * did that with three different exclusion lists, each correct only as long as
   * someone remembered to update it when the grammar grew. A new `type`
   * alternative would have reached the ladder, resolved to something, and been
   * silently mistaken for a named type -- `getZeroInitializer` would emit
   * `= {0}` with no diagnostic. Asking for named types by name makes an
   * unrecognized alternative `null` by default, which is where the callers'
   * own fallbacks already handle it.
   */
  static resolveNamedType(
    accessors: ITypeAccessors,
    scope: IScopeSymbol | null,
    deps?: ITypeBindingDeps,
  ): string | null {
    // this.T -- the scope is stated, so qualify against the chain unconditionally
    const scoped = accessors.scopedType();
    if (scoped) {
      return ScopeUtils.qualifyInScope(scoped.IDENTIFIER().getText(), scope);
    }
 
    // global.T -- explicitly opts out of scope qualification
    const global = accessors.globalType();
    if (global) {
      return global.IDENTIFIER().getText();
    }
 
    // Scope.T -- the path is stated in full
    const qualified = accessors.qualifiedType();
    if (qualified) {
      const names = qualified.IDENTIFIER().map((id) => id.getText());
      return deps?.resolveQualifiedType
        ? deps.resolveQualifiedType(names)
        : QualifiedCName.fromParts(names);
    }
 
    // Bare T -- the ONLY branch that resolves local -> scope -> global
    const user = accessors.userType();
    if (user) {
      const typeName = user.getText();
      return deps?.isScopeType
        ? ScopeUtils.qualifyScopeType(typeName, scope, deps.isScopeType)
        : typeName;
    }
 
    return null;
  }
 
  /**
   * `string<32>` keeps its capacity; a bare `string` does not (Issue #139).
   */
  static resolveStringType(stringCtx: Parser.StringTypeContext): string {
    const intLiteral = stringCtx.INTEGER_LITERAL();
    return intLiteral ? `string<${intLiteral.getText()}>` : "string";
  }
}
 
export default TypeBinding;