lemmascript 0.6.6 → 0.6.8

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