lemmascript 0.6.6 → 0.6.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -4,11 +4,12 @@
4
4
  * Produces structured AST nodes, not strings.
5
5
  * The only strings are //@ annotation expressions (parsed later by specparser).
6
6
  */
7
+ import path from "path";
7
8
  import { Project, Node, SyntaxKind, ScriptTarget, ts } from "ts-morph";
8
9
  import { initTypeParser } from "./types.js";
9
10
  import { normalizeBigIntLiteral } from "./rawir.js";
10
11
  import { setUserNames, freshName } from "./names.js";
11
- import { DEFAULT_OPTIONS } from "./config.js";
12
+ import { DEFAULT_OPTIONS, fileCommentLines, isOptionDirective } from "./config.js";
12
13
  // ── Expression extraction ────────────────────────────────────
13
14
  /** When set, calls whose function/method name matches this key are replaced with havoc. */
14
15
  let _havocKey = null;
@@ -371,7 +372,8 @@ function extractExpr(node) {
371
372
  }
372
373
  // Numeric literal
373
374
  if (Node.isNumericLiteral(node)) {
374
- return { kind: "num", value: Number(node.getLiteralValue()) };
375
+ // ts-morph's getLiteralValue truncates exponent forms with an integer mantissa.
376
+ return { kind: "num", value: Number(node.getText().replace(/_/g, "")) };
375
377
  }
376
378
  // BigInt literal (e.g. 32n, 0xffffn) — exact integer, with bigint division
377
379
  // semantics. Kept as a decimal string: `getLiteralValue()`/`Number()` would
@@ -415,6 +417,20 @@ function extractExpr(node) {
415
417
  if (node.getKind() === SyntaxKind.ThisKeyword) {
416
418
  return { kind: "var", name: "this" };
417
419
  }
420
+ // Resolve actual enum members through symbols, so a local value shadowing
421
+ // an enum name remains a normal property access. Element accesses have no
422
+ // symbol of their own; look up the literal key on the receiver instead.
423
+ if (Node.isPropertyAccessExpression(node) || Node.isElementAccessExpression(node)) {
424
+ const arg = Node.isElementAccessExpression(node) ? node.getArgumentExpression() : undefined;
425
+ const symbol = Node.isPropertyAccessExpression(node) ? node.getSymbol()
426
+ : arg && Node.isStringLiteral(arg) ? node.getExpression().getType().getProperty(arg.getLiteralValue()) : undefined;
427
+ const member = symbol?.getDeclarations().find(Node.isEnumMember);
428
+ if (member) {
429
+ const info = tryExtractConstEnum(member.getParent());
430
+ if (info)
431
+ return { kind: "num", value: info.constEnumMembers.find(m => m.name === enumMemberName(member)).value };
432
+ }
433
+ }
418
434
  // Property access: x.foo or x?.foo
419
435
  // Each `?.` is its own short-circuit point — wrap the inner in a new optChain.
420
436
  // Non-`?` continuation of an existing optChain extends the chain (no new
@@ -727,23 +743,88 @@ function extractExpr(node) {
727
743
  // ── Annotation parsing ───────────────────────────────────────
728
744
  const PREFIX = "//@ ";
729
745
  const KEYWORDS = ["requires", "ensures", "contract", "invariant", "decreases", "done_with", "type"];
746
+ /** The other directives (SPEC §2.1) besides options, read by keyword elsewhere. */
747
+ const DIRECTIVES = ["verify", "pure", "impure", "skip", "extern", "havoc", "autohavoc", "assert", "assume",
748
+ "ghost", "declare-type", "backend", "lean-module"];
749
+ function parseAnnotation(text) {
750
+ if (!text.startsWith(PREFIX))
751
+ return null;
752
+ const content = text.slice(PREFIX.length);
753
+ const sp = content.indexOf(" ");
754
+ if (sp === -1)
755
+ return null;
756
+ const kw = content.slice(0, sp);
757
+ if (!KEYWORDS.includes(kw))
758
+ return null;
759
+ return { kind: kw, expr: content.slice(sp + 1).trim() };
760
+ }
730
761
  function parseAnnotations(node) {
731
762
  const result = [];
732
763
  for (const range of node.getLeadingCommentRanges()) {
733
- const text = range.getText().trim();
734
- if (!text.startsWith(PREFIX))
735
- continue;
736
- const content = text.slice(PREFIX.length);
737
- const sp = content.indexOf(" ");
738
- if (sp === -1)
739
- continue;
740
- const kw = content.slice(0, sp);
741
- if (!KEYWORDS.includes(kw))
764
+ const a = parseAnnotation(range.getText().trim());
765
+ if (!a)
742
766
  continue;
743
- result.push({ kind: kw, expr: content.slice(sp + 1).trim() });
767
+ a.line = currentFileLine(node, range.getPos());
768
+ result.push(a);
744
769
  }
745
770
  return result;
746
771
  }
772
+ /** The line of `pos` in `node`'s file, when that is the file being extracted. */
773
+ function currentFileLine(node, pos) {
774
+ const sourceFile = node.getSourceFile();
775
+ return sourceFile === _currentSourceFile ? sourceFile.getLineAndColumnAtPos(pos).line : undefined;
776
+ }
777
+ /** Lines of the annotations whose value reached the Raw IR. */
778
+ const _readLines = new Set();
779
+ /** Line spans the extractor leaves out on purpose: `//@ skip`, unselected and extern functions. */
780
+ const _skippedSpans = [];
781
+ /** The annotation's expression, recording that it was read. */
782
+ function readExpr(a) {
783
+ if (a.line !== undefined)
784
+ _readLines.add(a.line);
785
+ return a.expr;
786
+ }
787
+ function annotExprs(annots, kind) {
788
+ return annots.filter(a => a.kind === kind).map(readExpr);
789
+ }
790
+ /** Only the first is read; a repeated one is reported as unread. */
791
+ function firstAnnotExpr(annots, kind) {
792
+ const a = annots.find(a => a.kind === kind);
793
+ return a ? readExpr(a) : null;
794
+ }
795
+ function skipSpan(node) {
796
+ const first = node.getLeadingCommentRanges()[0];
797
+ const from = first ? node.getSourceFile().getLineAndColumnAtPos(first.getPos()).line : node.getStartLineNumber();
798
+ _skippedSpans.push([from, node.getEndLineNumber()]);
799
+ }
800
+ /** Report `//@` comments lsc ignores, as the `unread-annotations` option
801
+ * says: a malformed or unknown one, or a contract annotation where no reader
802
+ * looks. Other directives are checked by keyword only. TypeScript's
803
+ * `//@ts-…` comments are not ours. */
804
+ function checkAnnotationsRead(sourceFile) {
805
+ const mode = _extractOptions["unread-annotations"];
806
+ if (mode === "off")
807
+ return;
808
+ const fileName = path.relative(process.cwd(), sourceFile.getFilePath());
809
+ const errors = [];
810
+ for (const { comment, index } of fileCommentLines(sourceFile.getFullText())) {
811
+ const text = comment.trim();
812
+ if (!text.startsWith("//@") || text.startsWith("//@ts-"))
813
+ continue;
814
+ const line = index + 1;
815
+ const keyword = text.match(/^\/\/@ (\S+)(?: |$)/)?.[1];
816
+ const read = parseAnnotation(text)
817
+ ? _readLines.has(line) || _skippedSpans.some(([from, to]) => from <= line && line <= to)
818
+ : DIRECTIVES.includes(keyword ?? "") || isOptionDirective(text);
819
+ if (!read)
820
+ errors.push(`${fileName}:${line}: lsc does not read this annotation: ${text}`);
821
+ }
822
+ if (mode === "warn")
823
+ for (const error of errors)
824
+ console.error(`warning: ${error}`);
825
+ else if (errors.length > 0)
826
+ throw new Error(errors.join("\n"));
827
+ }
747
828
  function collectAnnotations(node, body) {
748
829
  const own = parseAnnotations(node);
749
830
  if (body && body.length > 0)
@@ -861,6 +942,39 @@ function externIsImpure(node, name, parentStmt) {
861
942
  return _extractOptions["extern-default"] === "impure";
862
943
  }
863
944
  // ── Type declaration extraction ──────────────────────────────
945
+ function constEnumInfo(type) {
946
+ for (const decl of type.getSymbol()?.getDeclarations() ?? []) {
947
+ const parent = Node.isEnumMember(decl) ? decl.getParent() : decl;
948
+ if (Node.isEnumDeclaration(parent))
949
+ return tryExtractConstEnum(parent);
950
+ }
951
+ return undefined;
952
+ }
953
+ function enumMemberName(member) {
954
+ const name = member.getNameNode();
955
+ return Node.isStringLiteral(name) ? name.getLiteralValue() : member.getName();
956
+ }
957
+ // All merged declarations must have safe-integer numeric const enum members.
958
+ // Otherwise the entire enum keeps ordinary expression and type extraction.
959
+ function tryExtractConstEnum(decl, name = decl.getName()) {
960
+ const declarations = decl.getSymbol()?.getDeclarations().filter(Node.isEnumDeclaration) ?? [decl];
961
+ const members = [];
962
+ for (const declaration of declarations) {
963
+ if (!declaration.isConstEnum())
964
+ return undefined;
965
+ for (const member of declaration.getMembers()) {
966
+ const value = member.getValue();
967
+ if (typeof value !== "number" || !Number.isSafeInteger(value))
968
+ return undefined;
969
+ members.push({ name: enumMemberName(member), value });
970
+ }
971
+ }
972
+ return { name, kind: "alias", aliasOf: "number", constEnumMembers: members };
973
+ }
974
+ function isNumberType(type) {
975
+ const members = type.isUnion() ? type.getUnionTypes() : [type];
976
+ return members.every(m => (m.isNumber() || m.isNumberLiteral()) && !m.isEnumLiteral());
977
+ }
864
978
  function extractTypeDecl(decl, extraDecls) {
865
979
  const name = decl.getName();
866
980
  const type = decl.getType();
@@ -869,9 +983,18 @@ function extractTypeDecl(decl, extraDecls) {
869
983
  // Leading `//@ type <ty>` overrides extraction — the declared TS type is
870
984
  // replaced by the annotated backend type. Used to coerce literal unions
871
985
  // (`5 | 15 | 30` → `nat`) and other types LS can't model precisely.
872
- const override = parseAnnotations(decl).find(a => a.kind === "type");
986
+ const override = firstAnnotExpr(parseAnnotations(decl), "type");
873
987
  if (override)
874
- return { name, typeParams: tpField, kind: "alias", aliasOf: override.expr };
988
+ return { name, typeParams: tpField, kind: "alias", aliasOf: override };
989
+ const enumInfo = constEnumInfo(type);
990
+ if (enumInfo) {
991
+ // A type alias preserves numeric behavior but creates no value binding.
992
+ return { ...enumInfo, name, constEnumMembers: [] };
993
+ }
994
+ // Numeric literal unions are numbers at runtime. Keeping the alias without
995
+ // its numeric target would make conditions treat its values as objects.
996
+ if (isNumberType(type))
997
+ return { name, typeParams: tpField, kind: "alias", aliasOf: "number" };
875
998
  if (type.isUnion()) {
876
999
  const members = type.getUnionTypes();
877
1000
  if (members.every(m => m.isStringLiteral())) {
@@ -963,15 +1086,22 @@ function extractTypeDecl(decl, extraDecls) {
963
1086
  return { name, kind: "alias", aliasOf: tsType };
964
1087
  return null;
965
1088
  }
1089
+ function fieldTypeOverride(node) {
1090
+ if (!node || !(Node.isPropertyDeclaration(node) ||
1091
+ (Node.isPropertySignature(node) && Node.isInterfaceDeclaration(node.getParent()))))
1092
+ return undefined;
1093
+ const text = node.getTrailingCommentRanges().map(r => r.getText()).join(" ");
1094
+ const type = text.match(/\/\/@ type (\w+)/)?.[1];
1095
+ return type === undefined ? undefined : readExpr({ kind: "type", expr: type, line: currentFileLine(node, node.getEnd()) });
1096
+ }
966
1097
  function extractInterface(decl, extraDecls) {
967
1098
  // Collect field type overrides from trailing //@ type annotations
968
1099
  const overrides = new Map();
969
1100
  for (const member of decl.getMembers()) {
970
1101
  if (Node.isPropertySignature(member)) {
971
- const text = member.getTrailingCommentRanges().map(r => r.getText()).join(" ");
972
- const match = text.match(/\/\/@ type (\w+)/);
973
- if (match)
974
- overrides.set(member.getName(), match[1]);
1102
+ const override = fieldTypeOverride(member);
1103
+ if (override)
1104
+ overrides.set(member.getName(), override);
975
1105
  }
976
1106
  }
977
1107
  return extractRecord(decl.getName(), decl.getType(), decl, overrides, extraDecls);
@@ -982,19 +1112,20 @@ function extractRecord(name, type, locationNode, overrides, extraDecls) {
982
1112
  return null;
983
1113
  const fields = [];
984
1114
  for (const prop of props) {
1115
+ const propDecl = prop.getDeclarations()[0];
1116
+ const optionalKey = propDecl && propDecl.hasQuestionToken?.() ? { optionalKey: true } : {};
985
1117
  const override = overrides?.get(prop.getName());
986
1118
  if (override) {
987
- fields.push({ name: prop.getName(), tsType: override });
1119
+ fields.push({ name: prop.getName(), tsType: override, ...optionalKey });
988
1120
  continue;
989
1121
  }
990
1122
  const propType = prop.getTypeAtLocation(locationNode);
991
1123
  let tsType = typeToString(propType);
992
- const propDecl = prop.getDeclarations()[0];
993
1124
  tsType = declaredTypeTextIfBetter(propDecl, tsType);
994
1125
  // Optional property: `foo?: T` reports as `T` (ts-morph strips the
995
1126
  // `| undefined` from a question-token type). Add it back so the field
996
1127
  // resolves to `Optional<T>`.
997
- if (propDecl && propDecl.hasQuestionToken?.()) {
1128
+ if (optionalKey.optionalKey) {
998
1129
  // Normalize checker output that puts `undefined` first, then ensure
999
1130
  // exactly one trailing `| undefined`.
1000
1131
  if (tsType.startsWith("undefined | "))
@@ -1025,7 +1156,7 @@ function extractRecord(name, type, locationNode, overrides, extraDecls) {
1025
1156
  }
1026
1157
  }
1027
1158
  }
1028
- fields.push({ name: prop.getName(), tsType });
1159
+ fields.push({ name: prop.getName(), tsType, ...optionalKey });
1029
1160
  }
1030
1161
  return { name, kind: "record", fields };
1031
1162
  }
@@ -1065,6 +1196,8 @@ function declaredTypeTextIfBetter(propDecl, tsType) {
1065
1196
  return text;
1066
1197
  }
1067
1198
  function typeToString(type) {
1199
+ if (constEnumInfo(type))
1200
+ return "number";
1068
1201
  if (type.isUndefined())
1069
1202
  return "undefined";
1070
1203
  if (type.isNumber() || type.isNumberLiteral())
@@ -1088,6 +1221,16 @@ function typeToString(type) {
1088
1221
  }
1089
1222
  if (type.isUnion()) {
1090
1223
  const unionTypes = type.getUnionTypes();
1224
+ // Mapping union members individually loses a named inner union. Ask the
1225
+ // checker for its non-nullable type before widening literals, preserving
1226
+ // alias metadata and generic substitutions in record fields.
1227
+ const nullish = unionTypes.filter(t => t.isNull() || t.isUndefined());
1228
+ if (nullish.length > 0) {
1229
+ const inner = type.getNonNullableType();
1230
+ if (inner.isUnion() && inner.getAliasSymbol()) {
1231
+ return [typeToString(inner), ...nullish.map(typeToString)].join(" | ");
1232
+ }
1233
+ }
1091
1234
  // `T[] | U` synthesis: exactly two members, one array, the other not
1092
1235
  // array/undefined/null. Detected via ts-morph type predicates (no string
1093
1236
  // parsing). Registers a discriminated-union TypeDeclInfo with variants
@@ -1409,6 +1552,7 @@ function extractStmts(stmts) {
1409
1552
  result.push(...parseSpecComments(leadingComments, line));
1410
1553
  // //@ skip — omit this statement from the verification model
1411
1554
  if (leadingComments.some(r => r.getText().trim() === "//@ skip")) {
1555
+ skipSpan(s);
1412
1556
  continue;
1413
1557
  }
1414
1558
  if (Node.isVariableStatement(s)) {
@@ -1625,9 +1769,9 @@ function extractStmts(stmts) {
1625
1769
  result.push({
1626
1770
  kind: "while",
1627
1771
  cond: extractExpr(s.getExpression()),
1628
- invariants: annots.filter(a => a.kind === "invariant").map(a => a.expr),
1629
- decreases: annots.find(a => a.kind === "decreases")?.expr ?? null,
1630
- doneWith: annots.find(a => a.kind === "done_with")?.expr ?? null,
1772
+ invariants: annotExprs(annots, "invariant"),
1773
+ decreases: firstAnnotExpr(annots, "decreases"),
1774
+ doneWith: firstAnnotExpr(annots, "done_with"),
1631
1775
  body: extractStmts(bodyStmts),
1632
1776
  line,
1633
1777
  });
@@ -1677,8 +1821,8 @@ function extractStmts(stmts) {
1677
1821
  kind: "forof",
1678
1822
  names,
1679
1823
  iterable: extractExpr(iterableExpr),
1680
- invariants: annots.filter(a => a.kind === "invariant").map(a => a.expr),
1681
- doneWith: annots.find(a => a.kind === "done_with")?.expr ?? null,
1824
+ invariants: annotExprs(annots, "invariant"),
1825
+ doneWith: firstAnnotExpr(annots, "done_with"),
1682
1826
  body: extractStmts(bodyStmts),
1683
1827
  line,
1684
1828
  });
@@ -1737,9 +1881,9 @@ function extractStmts(stmts) {
1737
1881
  extractedBody.push(asStmt);
1738
1882
  }
1739
1883
  let condExpr = cond ? extractExpr(cond) : { kind: "bool", value: true };
1740
- let invariants = annots.filter(a => a.kind === "invariant").map(a => a.expr);
1741
- let decreases = annots.find(a => a.kind === "decreases")?.expr ?? null;
1742
- let doneWith = annots.find(a => a.kind === "done_with")?.expr ?? null;
1884
+ let invariants = annotExprs(annots, "invariant");
1885
+ let decreases = firstAnnotExpr(annots, "decreases");
1886
+ let doneWith = firstAnnotExpr(annots, "done_with");
1743
1887
  for (const [from, to] of renames) {
1744
1888
  for (let k = 0; k < hoisted.length; k++)
1745
1889
  hoisted[k] = renameRawStmt(hoisted[k], from, to);
@@ -1775,8 +1919,8 @@ function extractStmts(stmts) {
1775
1919
  kind: "forof",
1776
1920
  names: [name],
1777
1921
  iterable: extractExpr(s.getExpression()),
1778
- invariants: annots.filter(a => a.kind === "invariant").map(a => a.expr),
1779
- doneWith: annots.find(a => a.kind === "done_with")?.expr ?? null,
1922
+ invariants: annotExprs(annots, "invariant"),
1923
+ doneWith: firstAnnotExpr(annots, "done_with"),
1780
1924
  body: extractStmts(bodyStmts),
1781
1925
  line,
1782
1926
  });
@@ -1989,8 +2133,10 @@ function extractFunctionInner(fn, parentAnnotations) {
1989
2133
  for (const a of annots) {
1990
2134
  if (a.kind === "type") {
1991
2135
  const parts = a.expr.split(/\s+/);
1992
- if (parts.length === 2)
1993
- typeAnnotations.push({ name: parts[0], type: parts[1] });
2136
+ if (parts.length !== 2)
2137
+ continue;
2138
+ readExpr(a);
2139
+ typeAnnotations.push({ name: parts[0], type: parts[1] });
1994
2140
  }
1995
2141
  }
1996
2142
  return {
@@ -2092,10 +2238,10 @@ function extractFunctionInner(fn, parentAnnotations) {
2092
2238
  return "unknown";
2093
2239
  return _eraseGenerics(typeToString(inferred));
2094
2240
  })(),
2095
- requires: annots.filter(a => a.kind === "requires").map(a => a.expr),
2096
- ensures: annots.filter(a => a.kind === "ensures").map(a => a.expr),
2097
- contract: annots.filter(a => a.kind === "contract").map(a => a.expr),
2098
- decreases: annots.find(a => a.kind === "decreases")?.expr ?? null,
2241
+ requires: annotExprs(annots, "requires"),
2242
+ ensures: annotExprs(annots, "ensures"),
2243
+ contract: annotExprs(annots, "contract"),
2244
+ decreases: firstAnnotExpr(annots, "decreases"),
2099
2245
  pure: hasPureAnnotation(fn, body && Node.isBlock(body) ? body.getStatements() : undefined),
2100
2246
  autohavoc: false, // set in extractModule (file-level directive or per-function)
2101
2247
  typeAnnotations,
@@ -2118,6 +2264,8 @@ export function extractModule(sourceFile, options = DEFAULT_OPTIONS, validateDep
2118
2264
  // here), deduped by qualified name.
2119
2265
  _externs.clear();
2120
2266
  _externSigTypes.length = 0;
2267
+ _readLines.clear();
2268
+ _skippedSpans.length = 0;
2121
2269
  // Match a `//@ <kw>` directive only as the first non-whitespace on a line,
2122
2270
  // so prose mentioning an annotation does not activate it.
2123
2271
  function hasLineDirective(text, kw) {
@@ -2220,13 +2368,45 @@ export function extractModule(sourceFile, options = DEFAULT_OPTIONS, validateDep
2220
2368
  if (info)
2221
2369
  typeDecls.push(info);
2222
2370
  }
2371
+ else if (Node.isEnumDeclaration(stmt)
2372
+ && !declaredNames.has(stmt.getName()) && !hasLeadingDirective(stmt, "skip")) {
2373
+ const info = tryExtractConstEnum(stmt);
2374
+ if (info && !typeDecls.some(d => d.name === info.name))
2375
+ typeDecls.push(info);
2376
+ }
2377
+ }
2378
+ // Specifications lack TS expression nodes. Retain enum values under each
2379
+ // local import binding, including renamed exports and barrel re-exports.
2380
+ for (const imp of sourceFile.getImportDeclarations()) {
2381
+ for (const binding of imp.getNamedImports()) {
2382
+ const local = binding.getAliasNode() ?? binding.getNameNode();
2383
+ if (declaredNames.has(local.getText()))
2384
+ continue;
2385
+ const symbol = local.getSymbol();
2386
+ const target = symbol?.getAliasedSymbol() ?? symbol;
2387
+ for (const decl of target?.getDeclarations() ?? []) {
2388
+ if (Node.isEnumDeclaration(decl)) {
2389
+ const info = tryExtractConstEnum(decl, local.getText());
2390
+ if (info && !typeDecls.some(d => d.name === info.name))
2391
+ typeDecls.push(info);
2392
+ }
2393
+ else if (Node.isTypeAliasDeclaration(decl)
2394
+ && (constEnumInfo(decl.getType()) || isNumberType(decl.getType()))) {
2395
+ const info = extractTypeDecl(decl);
2396
+ if (info)
2397
+ typeDecls.push({ ...info, name: local.getText() });
2398
+ }
2399
+ }
2400
+ }
2223
2401
  }
2224
2402
  // Extract module-level const declarations
2225
2403
  const constants = [];
2226
2404
  for (const stmt of sourceFile.getStatements()) {
2227
2405
  if (Node.isVariableStatement(stmt)) {
2228
- if (hasLeadingDirective(stmt, "skip"))
2406
+ if (hasLeadingDirective(stmt, "skip")) {
2407
+ skipSpan(stmt);
2229
2408
  continue;
2409
+ }
2230
2410
  for (const decl of stmt.getDeclarationList().getDeclarations()) {
2231
2411
  if (stmt.getDeclarationList().getFlags() & 2 /* const */) {
2232
2412
  const init = decl.getInitializer();
@@ -2389,6 +2569,13 @@ export function extractModule(sourceFile, options = DEFAULT_OPTIONS, validateDep
2389
2569
  const hasVerifiedClassMethod = sourceFile.getClasses().some(cls => !hasLeadingDirective(cls, "skip") && cls.getMethods().some(method => !hasLeadingDirective(method, "skip") && hasLineDirective(method.getFullText(), "verify")));
2390
2570
  const hasVerifyDirective = nonExternFns.some(hasVerify) || hasVerifiedClassMethod;
2391
2571
  const fnsToExtract = hasVerifyDirective ? nonExternFns.filter(hasVerify) : nonExternFns;
2572
+ // A statement holding a selected function keeps its comments checked.
2573
+ for (const f of allFns) {
2574
+ if (fnsToExtract.includes(f))
2575
+ continue;
2576
+ const wholeStmt = f.parentStmt && !fnsToExtract.some(s => s.parentStmt === f.parentStmt);
2577
+ skipSpan(wholeStmt ? f.parentStmt : f.node);
2578
+ }
2392
2579
  // `//@ autohavoc` — enable the auto-havoc abstraction (see autohavoc.ts).
2393
2580
  // File-level: a directive at column 0 (top of file) enables it for every
2394
2581
  // function. Per-function: the annotation attached to a function (or its
@@ -2420,6 +2607,36 @@ export function extractModule(sourceFile, options = DEFAULT_OPTIONS, validateDep
2420
2607
  raw.autohavoc = hasAutohavoc(f);
2421
2608
  return raw;
2422
2609
  });
2610
+ // Class methods participate in the same dependency passes as functions.
2611
+ // Keep their source nodes alongside the raw methods for imported-type lookup.
2612
+ const selected = fnsToExtract.map((f, i) => ({ node: f.node, fn: functions[i], owner: "" }));
2613
+ const classes = [];
2614
+ const classFields = [];
2615
+ for (const cls of sourceFile.getClasses()) {
2616
+ if (hasLeadingDirective(cls, "skip")) {
2617
+ skipSpan(cls);
2618
+ continue;
2619
+ }
2620
+ const methodNodes = cls.getMethods().filter(method => !hasLeadingDirective(method, "skip") && hasLineDirective(method.getFullText(), "verify"));
2621
+ if (methodNodes.length === 0) {
2622
+ skipSpan(cls);
2623
+ continue;
2624
+ }
2625
+ for (const method of cls.getMethods())
2626
+ if (!methodNodes.includes(method))
2627
+ skipSpan(method);
2628
+ const name = cls.getName() ?? "Anonymous";
2629
+ const methods = methodNodes.map(node => {
2630
+ const fn = extractFunction(node);
2631
+ selected.push({ node, fn, owner: name });
2632
+ return fn;
2633
+ });
2634
+ const fields = cls.getProperties().map(prop => {
2635
+ classFields.push(prop);
2636
+ return { name: prop.getName(), tsType: fieldTypeOverride(prop) ?? typeToString(prop.getType()) };
2637
+ });
2638
+ classes.push({ name, fields, methods });
2639
+ }
2423
2640
  // Resolve type references in function signatures via ts-morph's type
2424
2641
  // checker — walk the TypeNode tree, resolve each TypeReferenceNode to its
2425
2642
  // declaration through symbol resolution, recurse. This is the principled
@@ -2506,14 +2723,14 @@ export function extractModule(sourceFile, options = DEFAULT_OPTIONS, validateDep
2506
2723
  return;
2507
2724
  }
2508
2725
  }
2509
- for (const f of fnsToExtract) {
2726
+ for (const f of selected) {
2510
2727
  for (const p of f.node.getParameters())
2511
2728
  resolveTypeNodeRefs(p.getTypeNode());
2512
2729
  resolveTypeNodeRefs(f.node.getReturnTypeNode());
2513
2730
  }
2514
2731
  // Resolve union param types: A | B → intersection of fields
2515
2732
  const typeDeclMap = new Map(typeDecls.map(d => [d.name, d]));
2516
- for (const fn of functions) {
2733
+ for (const { fn } of selected) {
2517
2734
  for (const p of fn.params) {
2518
2735
  if (!p.tsType.includes(" | "))
2519
2736
  continue;
@@ -2544,9 +2761,15 @@ export function extractModule(sourceFile, options = DEFAULT_OPTIONS, validateDep
2544
2761
  }
2545
2762
  }
2546
2763
  }
2547
- // In brownfield mode, filter consts to only those referenced by verified functions.
2764
+ // In brownfield mode, keep dependencies of selected functions and methods.
2548
2765
  if (hasVerifyDirective) {
2549
2766
  const referencedNames = new Set();
2767
+ function collectSpecNames(spec) {
2768
+ if (!spec)
2769
+ return;
2770
+ for (const m of spec.matchAll(/\b([a-zA-Z_]\w*)\b/g))
2771
+ referencedNames.add(m[1]);
2772
+ }
2550
2773
  function collectNames(stmts) {
2551
2774
  for (const s of stmts) {
2552
2775
  if (s.kind === "let") {
@@ -2555,6 +2778,7 @@ export function extractModule(sourceFile, options = DEFAULT_OPTIONS, validateDep
2555
2778
  collectNamesExpr(s.init);
2556
2779
  }
2557
2780
  if (s.kind === "assign") {
2781
+ collectSpecNames(s.target);
2558
2782
  collectNamesExpr(s.value);
2559
2783
  }
2560
2784
  if (s.kind === "return") {
@@ -2568,14 +2792,34 @@ export function extractModule(sourceFile, options = DEFAULT_OPTIONS, validateDep
2568
2792
  if (s.kind === "while") {
2569
2793
  collectNamesExpr(s.cond);
2570
2794
  collectNames(s.body);
2795
+ s.invariants.forEach(collectSpecNames);
2796
+ collectSpecNames(s.decreases);
2797
+ collectSpecNames(s.doneWith);
2571
2798
  }
2572
2799
  if (s.kind === "forof") {
2573
2800
  collectNamesExpr(s.iterable);
2574
2801
  collectNames(s.body);
2802
+ s.invariants.forEach(collectSpecNames);
2803
+ collectSpecNames(s.doneWith);
2804
+ }
2805
+ if (s.kind === "switch") {
2806
+ collectNamesExpr(s.expr);
2807
+ s.cases.forEach(c => collectNames(c.body));
2808
+ collectNames(s.defaultBody);
2575
2809
  }
2576
2810
  if (s.kind === "expr") {
2577
2811
  collectNamesExpr(s.expr);
2578
2812
  }
2813
+ if (s.kind === "assert")
2814
+ collectSpecNames(s.expr);
2815
+ if (s.kind === "ghostLet") {
2816
+ collectSpecNames(s.tsType);
2817
+ collectSpecNames(s.init);
2818
+ }
2819
+ if (s.kind === "ghostAssign") {
2820
+ collectSpecNames(s.target);
2821
+ collectSpecNames(s.value);
2822
+ }
2579
2823
  }
2580
2824
  }
2581
2825
  function collectNamesExpr(e) {
@@ -2639,6 +2883,7 @@ export function extractModule(sourceFile, options = DEFAULT_OPTIONS, validateDep
2639
2883
  collectNamesExpr(e.body);
2640
2884
  }
2641
2885
  if (e.kind === "forall" || e.kind === "exists") {
2886
+ collectSpecNames(e.varType);
2642
2887
  collectNamesExpr(e.body);
2643
2888
  }
2644
2889
  }
@@ -2646,7 +2891,7 @@ export function extractModule(sourceFile, options = DEFAULT_OPTIONS, validateDep
2646
2891
  // spec references stay exact-match (so a body `let xs: Hunk[]` doesn't pull
2647
2892
  // `Hunk` into the filter early and reorder output that resolveType re-adds).
2648
2893
  const sigTypes = new Set();
2649
- for (const fn of functions) {
2894
+ for (const { fn } of selected) {
2650
2895
  for (const p of fn.params) {
2651
2896
  referencedNames.add(p.tsType);
2652
2897
  sigTypes.add(p.tsType);
@@ -2655,11 +2900,8 @@ export function extractModule(sourceFile, options = DEFAULT_OPTIONS, validateDep
2655
2900
  sigTypes.add(fn.returnType);
2656
2901
  collectNames(fn.body);
2657
2902
  // Also scan spec annotations for identifier references
2658
- for (const spec of [...fn.requires, ...fn.ensures]) {
2659
- for (const m of spec.matchAll(/\b([a-zA-Z_]\w*)\b/g)) {
2660
- referencedNames.add(m[1]);
2661
- }
2662
- }
2903
+ for (const spec of [...fn.requires, ...fn.ensures, fn.decreases])
2904
+ collectSpecNames(spec);
2663
2905
  }
2664
2906
  // A constant's initializer can reference other constants
2665
2907
  // (`const ZERO_NINE = ZERO + nthDigit(-1)`). Close over those initializers
@@ -2690,8 +2932,13 @@ export function extractModule(sourceFile, options = DEFAULT_OPTIONS, validateDep
2690
2932
  if (neededTypes.has(name))
2691
2933
  return;
2692
2934
  const d = typeDecls.find(t => t.name === name);
2693
- if (!d)
2935
+ if (!d) {
2936
+ const dot = name.lastIndexOf(".");
2937
+ const parent = typeDecls.find(t => t.name === name.slice(0, dot));
2938
+ if (dot > 0 && parent?.constEnumMembers?.some(m => m.name === name.slice(dot + 1)))
2939
+ markType(parent.name);
2694
2940
  return;
2941
+ }
2695
2942
  neededTypes.add(name);
2696
2943
  for (const f of d.fields ?? [])
2697
2944
  for (const m of f.tsType.matchAll(/\b([A-Z]\w*)\b/g))
@@ -2709,16 +2956,26 @@ export function extractModule(sourceFile, options = DEFAULT_OPTIONS, validateDep
2709
2956
  // (`Omit<FilePathOptions, …>` must not pull in the inner type).
2710
2957
  for (const name of sigTypes) {
2711
2958
  const base = name.replace(/\s*\|\s*(undefined|null)\s*$/, "").replace(/(\[\])+$/, "").trim();
2712
- if (base !== name && /^[A-Za-z_]\w*$/.test(base))
2959
+ if (base !== name && /^[A-Za-z_]\w*(?:\.\w+)*$/.test(base))
2713
2960
  markType(base);
2714
2961
  }
2962
+ // Fields can carry nested generic arguments and lowercase type aliases.
2963
+ // Only inspect the modeled type: an override hides the original field type.
2964
+ for (const cls of classes)
2965
+ for (const field of cls.fields) {
2966
+ for (const m of field.tsType.matchAll(/\b([A-Za-z_]\w*)\b/g))
2967
+ markType(m[1]);
2968
+ }
2715
2969
  typeDecls.splice(0, typeDecls.length, ...typeDecls.filter(d => neededTypes.has(d.name) || declaredNames.has(d.name)));
2716
2970
  }
2717
2971
  // Resolve imported types: extract types referenced in function signatures but not in this file
2718
- const knownTypes = new Set(typeDecls.map(d => d.name));
2972
+ const knownTypes = new Set([...typeDecls.map(d => d.name), ...classes.map(c => c.name)]);
2719
2973
  const builtins = new Set(["Map", "Set", "Array", "String", "Number", "Boolean", "Promise", "Date", "RegExp", "Error"]);
2720
2974
  const visitedTypes = new Set();
2721
2975
  function resolveType(t, locationNode) {
2976
+ // Enums are primitive values, not records of Number prototype methods.
2977
+ if (constEnumInfo(t))
2978
+ return;
2722
2979
  // Resolve type aliases (e.g. string unions imported from other files).
2723
2980
  // BEFORE the visited guard: the same interned compilerType can arrive both
2724
2981
  // with and without its alias symbol (getTypeAtLocation drops it), and an
@@ -2768,6 +3025,13 @@ export function extractModule(sourceFile, options = DEFAULT_OPTIONS, validateDep
2768
3025
  return;
2769
3026
  }
2770
3027
  if (t.isUnion()) {
3028
+ // Discover the same named inner type that typeToString preserves. Walking
3029
+ // only individual literals would leave an imported optional enum opaque.
3030
+ const inner = t.getNonNullableType();
3031
+ if (inner.compilerType !== t.compilerType && inner.isUnion() && inner.getAliasSymbol()) {
3032
+ resolveType(inner, locationNode);
3033
+ return;
3034
+ }
2771
3035
  for (const u of t.getUnionTypes())
2772
3036
  resolveType(u, locationNode);
2773
3037
  return;
@@ -2776,15 +3040,26 @@ export function extractModule(sourceFile, options = DEFAULT_OPTIONS, validateDep
2776
3040
  resolveType(arg, locationNode);
2777
3041
  const sym = t.getSymbol() ?? t.getAliasSymbol();
2778
3042
  const name = sym?.getName();
2779
- if (name && !name.startsWith("__") && !knownTypes.has(name) && !builtins.has(name) && (t.isObject() || t.isIntersection())) {
2780
- const extra = [];
2781
- const info = extractRecord(name, t, locationNode, undefined, extra);
2782
- if (info) {
2783
- typeDecls.push(...extra);
2784
- typeDecls.push(info);
2785
- knownTypes.add(name);
2786
- // Recursively resolve types referenced in this type's fields
2787
- for (const prop of t.getProperties()) {
3043
+ if (name && !name.startsWith("__") && !builtins.has(name) && (t.isObject() || t.isIntersection())) {
3044
+ if (declaredNames.has(name))
3045
+ return;
3046
+ let info = typeDecls.find(d => d.name === name);
3047
+ if (!knownTypes.has(name)) {
3048
+ const extra = [];
3049
+ info = extractRecord(name, t, locationNode, undefined, extra) ?? undefined;
3050
+ if (info) {
3051
+ typeDecls.push(...extra);
3052
+ typeDecls.push(info);
3053
+ knownTypes.add(name);
3054
+ }
3055
+ }
3056
+ // Local records are already known, but their field types can still be
3057
+ // imported. Follow their modeled fields too, respecting field overrides.
3058
+ if (info?.kind === "record") {
3059
+ for (const field of info.fields ?? []) {
3060
+ const prop = t.getProperty(field.name);
3061
+ if (!prop || field.tsType === fieldTypeOverride(prop.getDeclarations()[0]))
3062
+ continue;
2788
3063
  resolveType(prop.getTypeAtLocation(locationNode), locationNode);
2789
3064
  }
2790
3065
  }
@@ -2799,9 +3074,8 @@ export function extractModule(sourceFile, options = DEFAULT_OPTIONS, validateDep
2799
3074
  }
2800
3075
  }
2801
3076
  }
2802
- for (let i = 0; i < fnsToExtract.length; i++) {
2803
- const f = fnsToExtract[i];
2804
- const fn = functions[i];
3077
+ for (const f of selected) {
3078
+ const fn = f.fn;
2805
3079
  // Skip params whose TS type was overridden by `//@ type <param> <Override>`
2806
3080
  // — the verification works against the override, so cross-file resolving
2807
3081
  // the original type pulls in unused datatypes (often with unsupported
@@ -2812,15 +3086,24 @@ export function extractModule(sourceFile, options = DEFAULT_OPTIONS, validateDep
2812
3086
  continue;
2813
3087
  resolveType(p.getType(), p);
2814
3088
  }
3089
+ if (f.owner && !overriddenNames.has("\\result"))
3090
+ resolveType(f.node.getReturnType(), f.node);
3091
+ }
3092
+ for (const prop of classFields) {
3093
+ if (!fieldTypeOverride(prop))
3094
+ resolveType(prop.getType(), prop);
2815
3095
  }
2816
3096
  // Extern signature types: see _externSigTypes.
2817
3097
  for (const r of _externSigTypes)
2818
3098
  resolveType(r.type, r.node);
2819
3099
  // Resolve anonymous object return types into synthetic named types
2820
- for (let i = 0; i < fnsToExtract.length; i++) {
2821
- const f = fnsToExtract[i];
2822
- const fn = functions[i];
3100
+ for (const f of selected) {
3101
+ const fn = f.fn;
2823
3102
  const retType = f.node.getReturnType();
3103
+ // Preserve the source's local enum binding or member type. Restoring the
3104
+ // checker's canonical name here loses renamed imports.
3105
+ if (constEnumInfo(retType))
3106
+ continue;
2824
3107
  // Prefer alias symbol (named type aliases) over underlying object symbol (__type)
2825
3108
  const aliasSym = retType.getAliasSymbol();
2826
3109
  if (aliasSym && !aliasSym.getName().startsWith("__")) {
@@ -2856,7 +3139,7 @@ export function extractModule(sourceFile, options = DEFAULT_OPTIONS, validateDep
2856
3139
  || sourceReturnText.includes(" | null ") || sourceReturnText.includes(" | undefined ")
2857
3140
  || sourceReturnText.includes(" | null|") || sourceReturnText.includes(" | undefined|");
2858
3141
  const sym = retType.getSymbol();
2859
- if (sym?.getName() === "__type" && retType.isObject() && !retType.isArray()) {
3142
+ if ((sym?.getName() === "__type" || sym?.getName() === "__object") && retType.isObject() && !retType.isArray()) {
2860
3143
  innerType = retType;
2861
3144
  if (sourceHadNullish)
2862
3145
  wrapOptional = true;
@@ -2868,7 +3151,7 @@ export function extractModule(sourceFile, options = DEFAULT_OPTIONS, validateDep
2868
3151
  if (nullish.length >= 1 && others.length === 1) {
2869
3152
  const onlyOther = others[0];
2870
3153
  const otherSym = onlyOther.getSymbol();
2871
- if (otherSym?.getName() === "__type" && onlyOther.isObject() && !onlyOther.isArray()) {
3154
+ if ((otherSym?.getName() === "__type" || otherSym?.getName() === "__object") && onlyOther.isObject() && !onlyOther.isArray()) {
2872
3155
  innerType = onlyOther;
2873
3156
  wrapOptional = true;
2874
3157
  }
@@ -2881,7 +3164,7 @@ export function extractModule(sourceFile, options = DEFAULT_OPTIONS, validateDep
2881
3164
  fn.returnType = wrapOptional ? `${resolved} | undefined` : resolved;
2882
3165
  continue;
2883
3166
  }
2884
- const synName = fn.name.charAt(0).toUpperCase() + fn.name.slice(1) + "Result";
3167
+ const synName = f.owner + fn.name.charAt(0).toUpperCase() + fn.name.slice(1) + "Result";
2885
3168
  if (!knownTypes.has(synName)) {
2886
3169
  const extra = [];
2887
3170
  const info = extractRecord(synName, innerType, f.node, undefined, extra);
@@ -2898,30 +3181,10 @@ export function extractModule(sourceFile, options = DEFAULT_OPTIONS, validateDep
2898
3181
  }
2899
3182
  }
2900
3183
  }
2901
- // Extract classes with //@ verify methods
2902
- const classes = [];
2903
- for (const cls of sourceFile.getClasses()) {
2904
- if (hasLeadingDirective(cls, "skip"))
2905
- continue;
2906
- const methods = [];
2907
- for (const method of cls.getMethods()) {
2908
- if (hasLeadingDirective(method, "skip"))
2909
- continue;
2910
- if (!method.getFullText().includes('//@ verify'))
2911
- continue;
2912
- methods.push(extractFunction(method));
2913
- }
2914
- if (methods.length === 0)
2915
- continue;
2916
- const fields = [];
2917
- for (const prop of cls.getProperties()) {
2918
- fields.push({ name: prop.getName(), tsType: typeToString(prop.getType()) });
2919
- }
2920
- classes.push({ name: cls.getName() ?? "Anonymous", fields, methods });
2921
- }
2922
3184
  // Clear the synth-union accumulator so typeToString reverts to plain
2923
3185
  // union stringification outside of an extractModule call.
2924
3186
  _synthArrayUnions = null;
3187
+ checkAnnotationsRead(sourceFile);
2925
3188
  return {
2926
3189
  file: sourceFile.getFilePath(),
2927
3190
  typeDecls,