All files / TRANSPILE/1-Analyze CallbackAssignmentAnalyzer.ts

93.54% Statements 87/93
80% Branches 40/50
100% Functions 23/23
98.76% Lines 80/81

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                                                                                                                                  470x 470x   470x 470x       469x         158x 158x 158x               463x     463x       3x 3x       267x     267x 267x 267x 267x 261x 261x               1754x     1754x 1754x 178x         178x 111x 1754x 106x 106x 106x                     158x 158x 82x   76x 50x   26x               466x 397x                               921x 921x 921x         921x 18x 18x   18x 18x 6x           6x     12x 12x         1x     1x                                                             8x 8x       4x               4x 4x 8x   4x         4x 4x 4x 4x 29x 8x 8x       4x             18x           18x 18x 18x 18x                             7x 7x           470x     470x 470x 470x 158x       470x   7x          
/**
 * ADR-029 callback typing: E0879, E0880.
 *
 * #1322. Two throws in `TypeValidator`, reached from `AssignmentValidator`
 * for exactly one target shape -- `h.down <- f`, a variable's direct field --
 * and reported as `1:0`. A function is a type under ADR-029, so a function
 * NAMED as a value must fit the slot it is placed in: its signature must
 * match the slot's type (E0879), and a function that is itself used as a
 * field type is nominally distinct from every other (E0880). A variable of
 * callback type placed in a slot is not named here: it already carries its
 * type, and codegen never asked; stated below.
 *
 * ## Four slots, one rule
 *
 * The rule is about where a function name lands, and codegen checked one of
 * the four places it can:
 *
 * - an assignment, `h.down <- f` -- checked, for a direct field only;
 *   `this.h.down`, `a.b.down` and a callback-typed variable never reached it
 * - a declaration's initializer, `onDown cb <- f`
 * - a struct initializer's field, `{ down: f }`
 * - a call's argument, `register(f)` -- the case ADR-029's own example marks
 *   `COMPILE ERROR`
 *
 * All four are decided here, from the slot's declared type through the same
 * lookup (`FunctionReference`), at the value's own position.
 *
 * ## What "used as a field type" reads
 *
 * Codegen's nominal rule read a map filled while emitting struct
 * declarations, so it held the structs emitted so far in the CURRENT file:
 * a struct declared below the assignment, in an enclosing scope, or in an
 * include did not count. The per-file symbol view holds every struct this
 * file can see, and that is what a type identity is.
 *
 * ## Stated, not closed
 *
 * A function used only as a PARAMETER type (`void reg(onUp cb)`) is not a
 * nominal type here, as it was not in codegen; widening that is a language
 * decision (ADR-029 §Nominal Typing names struct fields). Array dimensions of
 * parameters are not compared, as they were not.
 */
 
import { ParserRuleContext, ParseTreeWalker } from "antlr4ng";
 
import { CNextListener } from "../../PARSE/2-Parse/grammar/CNextListener";
import * as Parser from "../../PARSE/2-Parse/grammar/CNextParser";
import IFunctionSymbol from "../../types/symbols/IFunctionSymbol";
import ParserUtils from "../../utils/ParserUtils";
import TypeResolver from "../../utils/TypeResolver";
import OperandTyper from "../../utils/OperandTyper";
import FunctionReference from "./helpers/FunctionReference";
import StructInitializerType from "./helpers/StructInitializerType";
import AssignmentSiteListener from "./AssignmentSiteListener";
import ICallbackAssignmentError from "./types/ICallbackAssignmentError";
import type IAnalysisContext from "./types/IAnalysisContext";
import type TAssignmentSite from "./types/TAssignmentSite";
 
/** Where a function name landed, for the message. */
interface ISlot {
  readonly verb: "assign" | "pass";
  readonly description: string;
}
 
class CallbackAssignmentListener extends CNextListener {
  private readonly found: ICallbackAssignmentError[] = [];
  private fieldTypes: ReadonlySet<string> | null = null;
 
  public constructor(private readonly context: IAnalysisContext) {
    super();
  }
 
  public errors(): ICallbackAssignmentError[] {
    return this.found;
  }
 
  /** `target <- f`, any target shape, in a statement or a `for` header */
  public checkSite(site: TAssignmentSite): void {
    const target = site.assignmentTarget();
    const description = CallbackAssignmentListener.describeTarget(target);
    this.check(
      OperandTyper.typeOfTarget(target, this.context)?.typeName ?? null,
      site.expression(),
      { verb: "assign", description },
    );
  }
 
  /** `onDown cb <- f`, in a function, a scope, at file scope. */
  override enterVariableDeclaration = (
    ctx: Parser.VariableDeclarationContext,
  ): void => {
    this.checkDeclaration(ctx.type(), ctx.IDENTIFIER(), ctx.expression());
  };
 
  /** `for (onDown cb <- f; ...)`. */
  override enterForVarDecl = (ctx: Parser.ForVarDeclContext): void => {
    this.checkDeclaration(ctx.type(), ctx.IDENTIFIER(), ctx.expression());
  };
 
  /** `{ down: f }`, wherever the initializer's struct is established. */
  override enterFieldInitializer = (
    ctx: Parser.FieldInitializerContext,
  ): void => {
    const init = ctx.parent?.parent;
    Iif (!(init instanceof Parser.StructInitializerContext)) return;
    const structName = StructInitializerType.of(init, this.context);
    if (structName === null) return;
    const fieldName = ctx.IDENTIFIER().getText();
    this.check(
      this.context.symbols.structFields.get(structName)?.get(fieldName) ?? null,
      ctx.expression(),
      { verb: "assign", description: `callback field '${fieldName}'` },
    );
  };
 
  /** `register(f)`: each argument against its parameter's type. */
  override enterPostfixExpression = (
    ctx: Parser.PostfixExpressionContext,
  ): void => {
    const call = ctx.postfixOp().find((op) => op.LPAREN() !== null);
    if (call === undefined) return;
    const callee = FunctionReference.ofCall(
      ctx,
      OperandTyper.scopePathAt(ctx, this.context),
      this.context,
    );
    if (callee === null) return;
    const args = call.argumentList()?.expression() ?? [];
    args.forEach((arg, index) => {
      const param = callee.parameters[index];
      Iif (param === undefined) return;
      this.check(TypeResolver.getTypeName(param.type), arg, {
        verb: "pass",
        description: `parameter '${param.name}' of function '${callee.name}'`,
      });
    });
  };
 
  /** How an assignment target is named in a message. */
  private static describeTarget(
    target: Parser.AssignmentTargetContext,
  ): string {
    const last = target.postfixTargetOp().at(-1);
    if (last === undefined) {
      return `callback variable '${target.getText()}'`;
    }
    if (last.DOT() !== null) {
      return `callback field '${last.IDENTIFIER()?.getText()}'`;
    }
    return `callback '${target.getText()}'`;
  }
 
  private checkDeclaration(
    typeCtx: Parser.TypeContext | null,
    identifier: { getText(): string } | null,
    initializer: Parser.ExpressionContext | null,
  ): void {
    if (!typeCtx || !identifier || !initializer) return;
    this.check(typeCtx.getText(), initializer, {
      verb: "assign",
      description: `callback variable '${identifier.getText()}'`,
    });
  }
 
  /**
   * The rule. Silent unless the slot's type is a function AND the value
   * names one; then the signatures must match, and a value that is itself a
   * field type must be the slot's own.
   */
  private check(
    slotTypeText: string | null,
    value: Parser.ExpressionContext,
    slot: ISlot,
  ): void {
    Iif (slotTypeText === null) return;
    const scopePath = OperandTyper.scopePathAt(value, this.context);
    const expected = FunctionReference.ofTypeText(
      slotTypeText,
      scopePath,
      this.context,
    );
    if (expected === null) return;
    const actual = FunctionReference.ofValue(value, scopePath, this.context);
    Iif (actual === null) return;
 
    const valueText = value.getText();
    if (!CallbackAssignmentListener.signaturesMatch(expected, actual)) {
      this.report(
        value,
        "E0879",
        `Function '${valueText}' signature does not match callback type '${slotTypeText}'`,
        "A callback must match its type's signature exactly: return type, parameter count, and each parameter's type, const-ness and array-ness (ADR-029).",
      );
      return;
    }
 
    const actualName = FunctionReference.cNameOf(actual);
    if (
      actualName !== FunctionReference.cNameOf(expected) &&
      this.isFieldType(actualName)
    ) {
      const verb =
        slot.verb === "assign"
          ? `Cannot assign '${valueText}' to`
          : `Cannot pass '${valueText}' as`;
      this.report(
        value,
        "E0880",
        `${verb} ${slot.description} (expected ${slotTypeText} type, got ${valueText} type - nominal typing)`,
        "A function used as a struct field's type is its own callback type; only a function that is not itself a type may stand in for another (ADR-029).",
      );
    }
  }
 
  /**
   * Whether any struct in the program declares a field of this type -- what
   * makes a function a nominal callback type rather than a plain function.
   *
   * Asked of the PROGRAM, not of the per-file view, and that is the decision.
   * ADR-029 says "type identity is the function name": a function IS a type
   * because some struct declares a field of it, which is a property of the
   * program and not of who imported whom. Reading a per-file set would make
   * the same function nominal in one file and plain in another, so the same
   * assignment would be rejected or accepted depending on the include graph.
   *
   * This is deliberately the opposite choice from #1398's VISIBILITY question
   * (E0427), where the run-wide table is wrong because a sibling that was
   * never included must not resolve. Here the function is visible either way
   * -- it was named in the source -- and the only question is what its type
   * identity is.
   *
   * Codegen asked `CodeGenState.callbackFieldTypes`, which holds the structs
   * emitted SO FAR in the current file, so a struct declared below the
   * assignment, in an enclosing scope, or in an include did not count.
   */
  private isFieldType(cName: string): boolean {
    this.fieldTypes ??= this.collectFieldTypes();
    return this.fieldTypes.has(cName);
  }
 
  private collectFieldTypes(): ReadonlySet<string> {
    return new Set([
      ...this.fieldTypesInFileView(),
      ...this.fieldTypesInProgram(),
    ]);
  }
 
  /** Field types of the structs this file declares. */
  private fieldTypesInFileView(): string[] {
    const types: string[] = [];
    for (const fields of this.context.symbols.structFields.values()) {
      types.push(...fields.values());
    }
    return types;
  }
 
  /** Field types of every struct the program declares, in any file. */
  private fieldTypesInProgram(): string[] {
    const program = this.context.program;
    const types: string[] = [];
    for (const sourceFile of program.sourceFiles()) {
      for (const symbol of program.symbolsInFile(sourceFile)) {
        if (symbol.kind !== "struct") continue;
        for (const field of symbol.fields.values()) {
          types.push(TypeResolver.getTypeName(field.type));
        }
      }
    }
    return types;
  }
 
  private static signaturesMatch(
    a: IFunctionSymbol,
    b: IFunctionSymbol,
  ): boolean {
    Iif (
      TypeResolver.getTypeName(a.returnType) !==
      TypeResolver.getTypeName(b.returnType)
    ) {
      return false;
    }
    Iif (a.parameters.length !== b.parameters.length) return false;
    return a.parameters.every((pa, i) => {
      const pb = b.parameters[i];
      return (
        TypeResolver.getTypeName(pa.type) ===
          TypeResolver.getTypeName(pb.type) &&
        pa.isConst === pb.isConst &&
        pa.isArray === pb.isArray
      );
    });
  }
 
  private report(
    at: ParserRuleContext,
    code: string,
    message: string,
    helpText: string,
  ): void {
    const { line, column } = ParserUtils.getPosition(at);
    this.found.push({ code, line, column, message, helpText });
  }
}
 
class CallbackAssignmentAnalyzer {
  /** #1456: handed in rather than read off shared state. */
  constructor(private readonly context: IAnalysisContext) {}
 
  public analyze(tree: Parser.ProgramContext): ICallbackAssignmentError[] {
    const listener = new CallbackAssignmentListener(this.context);
    ParseTreeWalker.DEFAULT.walk(listener, tree);
    ParseTreeWalker.DEFAULT.walk(
      new AssignmentSiteListener((site) => listener.checkSite(site)),
      tree,
    );
    // Reported in source order, as the one walk these replace did
    return listener
      .errors()
      .sort((a, b) => a.line - b.line || a.column - b.column);
  }
}
 
export default CallbackAssignmentAnalyzer;