Skip to content

Shift 3 (Milestone 1): self-verified spec type parser and structured Ty on RawIR - #415

Open
robertpenner wants to merge 9 commits into
midspiral:mainfrom
robertpenner:afk/shift3-types-55
Open

robertpenner wants to merge 9 commits into
midspiral:mainfrom
robertpenner:afk/shift3-types-55

Conversation

@robertpenner

Copy link
Copy Markdown
Contributor

Motivation

LemmaScript previously flattened TypeScript types to strings during extraction (getText(), typeToString(), tyToTsStr()), stored those strings on RawIR, and re-parsed them inside resolve.ts by injecting synthetic TypeScript source files (__lsc_type_parse__.ts) into ts-morph via parseTsType. That architecture coupled types.ts and resolve.ts to ts-morph, blocked self-verification of downstream compiler passes, and forced every RawIR consumer to re-parse type strings.

This PR delivers Milestone 1 of Shift 3 (Refs #396, part of #386).

Summary

tools/src/
├── spec-type-parser.ts    # Self-verified (Dafny) tokenizer, recursive-descent parser, and nullability normalizer
├── spec-type.ts           # Thin adapter exposing parseSpecType(text): Ty (fails closed on malformed input)
├── extract-types.ts       # Direct ts-morph Type / TypeNode -> Ty extractor, T[] | U synthesis, generic erasure
├── extract.ts             # Populates structured Ty across RawIR and retains tsType display metadata
├── rawir.ts               # Carries structured Ty fields across RawIR nodes
├── types.ts               # ts-morph-free; removed initTypeParser, parseTsType, tyFromTypeNode, tyToTsStr
├── resolve.ts             # Consumes precomputed RawIR Ty; calls parseSpecType only for //@ annotations
├── specparser.ts          # Parses //@ forall/exists/new Set/Map type text via parseSpecType
├── checked-reads.ts       # Consumes precomputed FieldInfo.type (no parseSpecType fallback)
├── narrow-checks.ts       # Consumes precomputed FieldInfo.type (no parseSpecType fallback)
└── transform.ts           # Consumes precomputed FieldInfo.type (no parseSpecType fallback)
  • Self-verified spec type parser (tools/src/spec-type-parser.ts + tools/src/spec-type.ts):
    • Registered tools/src/spec-type-parser.ts (//@ backend dafny) in LemmaScript-files.txt, with generated tools/src/spec-type-parser.dfy and tools/src/spec-type-parser.dfy.gen (zero hand edits).
    • Routed all //@ annotation type-parsing sites (//@ type, //@ declare-type, //@ ghost let, //@ havoc : Type, forall/exists, and spec new Set<T>()/new Map<K, V>()) through parseSpecType.
  • Direct ts-morph extraction and structured Ty on RawIR (tools/src/extract-types.ts + tools/src/extract.ts):
    • Added extractTy, extractTyFromNode, typeToTsString, wrapNullability, eraseGenericTy, eraseTypeText, registerSynthArrayUnion, and trySynthArrayUnionFromNodes.
    • Populated structured Ty on all RawIR declarations, parameters, fields, statements, expressions, and synthesized T[] | U datatypes, while preserving tsType display metadata for lsc info --typed (Map<K, V> vs Record<K, V>).
    • Removed initTypeParser, parseTsType, tyFromTypeNode, tyToTsStr, the synthetic __lsc_type_parse__.ts file, and all ts-morph imports from tools/src/types.ts and tools/src/resolve.ts.
    • Removed post-resolve parseSpecType fallbacks in checked-reads.ts, narrow-checks.ts, and transform.ts.
    • Preserved unresolved imported type names in lowerCheckerType (checking getAliasSymbol() and getSymbol() before isVoid() and isAny() || isUnknown()) so //@ declare-type shadowing works when external node_modules are absent (verified against flue-lemmascript and mcp-sdk-lemmascript).

Findings and advances

  • Self-verified spec type parser: tools/src/spec-type-parser.ts verifies under ./tools/check.sh dafny with 18 verified, 0 errors, zero assume/havoc/{:axiom}, and 0-byte diff between tools/src/spec-type-parser.dfy and tools/src/spec-type-parser.dfy.gen. Proved postconditions cover token-stream validity, progress, nullability flattening (no nested optional/nullish wrappers, void | null normalizing to nullish(void)), and full-input consumption.
  • Compiler ts-morph boundary: Static tests in tools/tests/spec-type-parser.test.ts scan tools/src/ and confirm ts-morph and typescript imports exist only in the 6 allowlisted extraction/CLI files (config.ts, extract.ts, extract-types.ts, lexical-names.ts, lsc.ts, source-projects.ts). Neither types.ts, resolve.ts, spec-type*.ts, nor downstream passes import ts-morph.
  • Zero output drift: Regenerating all examples under ./regen-dafny.sh --no-verify and ./regen-lean.sh produces 0 lines of diff in examples/.

Future Work

Evidence

  • Before (096600e): tools/src/types.ts imported ts-morph and created a synthetic __lsc_type_parse__.ts source file to re-parse RawIR tsType strings in resolve.ts; LemmaScript-files.txt listed 2 self-verified files (alias-check.ts, places.ts).
  • After (a487b65, merged with upstream/main 1e657a9):
    • Fork CI (robertpenner/LemmaScript run 46110971477): 46/46 checks passing (tools, unit-tests (1) & (2), examples-dafny (0..3), generated-dafny, generated-lean, lean, all 32 case-studies-dafny jobs, and all 4 case-studies-lean jobs).
    • Local checks: npm run build, npx tsc --noEmit -p tools/tsconfig.json, npx tsc --noEmit -p examples/tsconfig.json, ./regen-dafny.sh --no-verify, ./regen-lean.sh (0 drift), diff -u tools/src/spec-type-parser.dfy tools/src/spec-type-parser.dfy.gen (0 diff), ./tools/check.sh dafny (alias-check 6, places 11, spec-type-parser 18 verified, 0 errors), dafny verify formal/narrowing-model.dfy (93 verified, 0 errors), ./tools/test-fixtures.sh --fixtures (exit 0).

Blast Radius: Modifies type extraction, RawIR fields, type resolution, and LemmaScript-files.txt. All examples regenerate identically for both Dafny and Lean, all 3 self-verified compiler files plus formal/narrowing-model.dfy verify with 0 errors, and all 36 Dafny/Lean case-study jobs pass.

Refs #396

Add tools/src/spec-type-parser.ts (//@ backend dafny) implementing a
ts-morph-free tokenizer, recursive-descent parser, and nullability
normalizer for LemmaScript //@ type annotations, registered in
LemmaScript-files.txt and verified with 18 verified, 0 errors and zero
assumptions or axioms. Add tools/src/spec-type.ts as a thin adapter
converting SpecTy to Ty and failing closed on malformed inputs.

Refs #55, #56
Migrate all //@ annotation type-parsing sites in extract.ts, resolve.ts,
specparser.ts, and rawir.ts from parseTsType to parseSpecType so spec
annotations no longer invoke ts-morph. Add differential, fail-closed,
zero-ts-morph, and Dafny self-verification tests in
tools/tests/spec-type-parser.test.ts.

Refs #55, #56
Wire extract-types directly into extract.ts so RawIR nodes (params,
returnTy, constants, externs, class fields, record/variant fields,
lambdas, empty collections, and type-asserted records) carry structured
Ty alongside tsType strings.

Switch info-command.ts renderSig off parseTsType while preserving
params[].tsType in lsc info --typed so satellites can distinguish
Map<K, V> from Record<K, V>. Restrict TypeOperatorTypeNode unwrapping
in extract-types.ts to ReadonlyKeyword so keyof T is preserved.

Verified:
- npm run build, npm run typecheck, cd tools && npm run typecheck
- tools/tests/extract-types.test.ts (14/14), spec-type-parser.test.ts (7/7), class-dependencies.test.ts (10/10)
- ./regen-dafny.sh --no-verify (0/95 drift), ./regen-lean.sh (0/95 drift)

Refs #57
….ts and resolve

Switch resolve.ts, checked-reads.ts, narrow-checks.ts, transform.ts, and
specparser.ts to consume structured Ty directly (falling back to
parseSpecType only for hand-built RawIR without type fields). Delete
initTypeParser, parseTsType, tyFromTypeNode, tyToTsStr, and the scratch
__lsc_type_parse__.ts parser from types.ts so ts-morph is no longer
imported outside extract*.ts.

Align extract.ts class property, const, and primitive alias extraction
with typeToString so const enums and primitive aliases preserve zero
regen drift across all Dafny and Lean examples.

Refs #57
…e cases

Addresses code-review findings across the verified spec type parser and ts-morph type extractor:
- Normalize wrapNullability across spec-type-parser.ts and extract-types.ts (void | undefined -> void, void | null and null | undefined -> nullish(void), null | null -> null) with strengthened Dafny ensures.
- Support optional function params, optional named/unnamed tuple elements, Readonly<T>, and parenthesized null/undefined/boolean union arms in both parser and extractor.
- Guard recursive types with a visited set and preserve named callable interfaces via !type.isInterface() while keeping arrow/function values lowered to fn.
- Deduplicate T[] | U synthesis and generic erasure helpers in extract-types.ts, route annotated local UnionTypeNode through synthesis, preserve synthesized names under brownfield pruning, and dispatch uninitialized let defaults from structured Ty.
… Shift 3 tests

- Remove parseSpecType imports and fallbacks from checked-reads.ts, narrow-checks.ts, and transform.ts; populate emptyCollection.type in resolve.ts ghost let.
- Fix corpus collection filters in spec-type-parser.test.ts (remove startsWith('(') filter, scan balanced <...> generics) and broaden static boundary checks across all of tools/src/.
- Add regression tests for nullability parity, optional function params and tuple elements, Readonly<T>, recursive/named callable interfaces, discriminated union/class/record/alias extraction, brownfield T[] | U local retention, bounded generic T[] | U erasure, and uninitialized let defaults.
TypeScript marks unresolved imported types (such as types shadowed by
//@ declare-type when external node_modules are absent) as isAny() === true
with aliasSym carrying the imported name. Check aliasSym and symbol before
isAny()/isUnknown()/isVoid() in lowerCheckerType so unresolved imported
types lower to user types instead of collapsing to unknown.

Add a regression test covering discriminated union fields, //@ extern
parameters, array elements, and explicit any/unknown parameters.
@namin

namin commented Nov 28, 2026

Copy link
Copy Markdown
Member

This looks great. I am still reading through.

In the meantime, here are some small issues found by codex.

  1. A tuple rest element becomes one required array slot. For xs: [first: number, ...rest: string[]], the PR emits (int, seq<string>). A function returning !!xs[1] then verifies with //@ ensures \result. But xs = [0, ""] is a valid input, and I ran it in Node and got false. The merge base rejected the generated Dafny. I’d reject variadic tuples during extraction until the model supports their indexing semantics. [Tuple extraction](

    if (Node.isTupleTypeNode(tn)) {
    const elems = tn.getElements().map(e => {
    if (Node.isNamedTupleMember(e)) {
    const ty = lowerTypeNode(e.getTypeNode(), ctx);
    return e.hasQuestionToken() ? wrapNullability(ty, false, true) : ty;
    }
    if (e.getKind() === SyntaxKind.OptionalType) {
    const inner = e.getFirstChild();
    const ty: Ty = inner ? lowerTypeNode(inner as TypeNode, ctx) : { kind: "unknown" };
    return wrapNullability(ty, false, true);
    }
    return lowerTypeNode(e, ctx);
    });
    )

  2. An escaped string key can select the wrong record field. For return r[k] with //@ type k "\u0061"|"b", the merge base correctly tests k == "a". The PR tests k == "u0061", so an actual "a" selects r.b. I ran lsc check with the false postcondition k === "a" ==> \result === r.b. The base rejected it and the PR verified it. The tokenizer should decode each supported escape faithfully and reject the rest. [String literal tokenizer](

    if (ch === 92) {
    // Backslash escape
    if (i + 1 >= input.length) {
    return { kind: "err", error: "Unterminated escape in string literal type" };
    }
    const escCode = input.charCodeAt(i + 1);
    if (escCode === 110) {
    val = val + "\n";
    } else if (escCode === 114) {
    val = val + "\r";
    } else if (escCode === 116) {
    val = val + "\t";
    } else {
    val = val + input.slice(i + 1, i + 2);
    }
    i = i + 2;
    )

@namin

namin commented Nov 28, 2026

Copy link
Copy Markdown
Member

Assertion callbacks acquire a boolean return value during extraction

From Codex. Review finding for PR #415 at a487b65, compared with main at bed1418b.

PR #415 verifies that demo always returns true. An assertion callback can return normally with undefined, which makes demo return false.

repro.ts

//@ backend dafny
//@ ensures \result
export function demo(check: (x: number) => asserts x is 0): boolean {
  return check(0) !== undefined;
}

Run this command from a built LemmaScript checkout with Dafny 4.11.0 on PATH. Use a fresh fixture directory for each revision.

node tools/dist/lsc.js check --backend=dafny /path/to/repro.ts

PR head a487b65 gives the callback type (int) -> bool, reduces the function body to true, and reports 1 verified, 0 errors. Main bed1418b rejects the generated Dafny for this example.

Runtime witness

This separate caller next to repro.ts passes strict TypeScript checking.

import { demo } from "./repro";

function assertZero(x: number): asserts x is 0 {
  if (x !== 0) throw new Error("Expected zero");
}

console.log(demo(assertZero)); // false

Expected behavior

Distinguish an assertion signature (asserts x is T) from a boolean type guard (x is T). Model the assertion’s normal return as void or reject the unsupported signature. A regression test should reject this postcondition while retaining boolean results for ordinary type guards.

Main already classifies top-level type predicates as returning boolean. The regression in #415 is that the same rule now lets the callback example verify. PR callback type lowering · Existing main rule

@namin

namin commented Nov 28, 2026

Copy link
Copy Markdown
Member

Preserve renamed imports in Dafny extern signatures

From Codex. Review finding for PR #415 at a487b65, compared with main at bed1418b.

In #415, a caller and its imported function can acquire different Dafny types for the same TypeScript interface. The following two-file program verified on main at bed1418b.

dep.ts

export interface Entity { val: number }

//@ ensures \result === x.val
export function f(x: Entity): number { return x.val; }

main.ts

import { f, type Entity as Renamed } from "./dep";
//@ declare-type Renamed { val: number }

//@ verify
//@ ensures \result === x.val
export function relay(x: Renamed): number { return f(x); }

Save the files together, using a fresh fixture directory for each revision. Run this from a built LemmaScript checkout with Dafny 4.11.0 on PATH.

node tools/dist/lsc.js check --backend=dafny /path/to/main.ts

Observed. On main, Dafny reports 2 verified, 0 errors. PR head a487b65 emits f(x: Entity) and relay(x: Renamed) with two distinct datatypes. Dafny rejects f(x) with expected Entity, found Renamed.

Expected. Both signatures should refer to the same modeled declaration, respecting the caller's //@ declare-type Renamed. The example should verify again.

The extractor renders the extern's display text relative to the call site while separately lowering its structured type from the checker. Carry the call site's local alias identity into both the parameter and result types of the extern. Extern extraction at the reviewed commit

@namin

namin commented Nov 28, 2026

Copy link
Copy Markdown
Member

Accept hexadecimal numeric literal unions in spec type annotations

From Codex. Review finding for PR #415 at a487b65, compared with main at bed1418b.

The spec type parser introduced in #415 rejects a previously accepted hexadecimal flag union in //@ declare-type.

main.ts

//@ backend dafny
//@ declare-type Mode = 0x10 | 0x20
type Mode = 0x10 | 0x20;

//@ ensures \result === m
export function identity(m: Mode): number {
  return m;
}

From a built LemmaScript checkout with Dafny 4.11.0 on PATH, use a fresh copy of the fixture for each revision.

node tools/dist/lsc.js check --backend=dafny /path/to/main.ts

Observed. On main at bed1418b, Dafny reports 1 verified, 0 errors. On PR head a487b65, extraction stops with Invalid spec type annotation "0x10 | 0x20": Unexpected trailing token 'x10' in type annotation. The lexer consumes the leading zero as a complete decimal token.

Expected. The parser should recognize each hexadecimal integer as one numeric literal and lower this union the same way it lowers 16 | 32. Use this fixture as an end-to-end regression test. The spec-expression lexer already recognizes hexadecimal integers. Spec-type tokenization · Spec-expression numeric grammar

@namin

namin commented Nov 28, 2026

Copy link
Copy Markdown
Member

Named tuple rest elements become a single required array slot

From Codex. Review finding for PR #415 at a487b65, compared with main at bed1418b.

This is the full reproducer for finding 1 in the earlier Codex summary.

For [first: number, ...rest: string[]], the value at index 1 is the first string supplied in the rest portion, or undefined when that portion is empty. On #415 the extractor gives the second slot the type seq<string> and simplifies its truthiness to a constant.

repro.ts

//@ backend dafny
//@ ensures \result
export function truth(xs: [first: number, ...rest: string[]]): boolean {
  return !!xs[1];
}

From a built LemmaScript checkout with Dafny 4.11.0 on PATH, run the following command. Use a fresh fixture directory for each revision.

node tools/dist/lsc.js check --backend=dafny /path/to/repro.ts

Observed behavior

On #415 at a487b65, Dafny verifies truth(xs: (int, seq<string>)) with body !(false) and reports 1 verified, 0 errors. In JavaScript, truth([0, ""]) returns false because the second element is an empty string. On main at bed1418b, the generated Dafny fails to parse for this same program.

Expected behavior

Preserve the element and indexing semantics of tuple rests, or reject variadic tuples during extraction until they can be represented. Use this counterexample to test that the false postcondition cannot verify. Named tuple extraction

@namin

namin commented Nov 28, 2026

Copy link
Copy Markdown
Member

Erasing Readonly from a callable interface excludes valid TypeScript inputs

From Codex. Review finding for PR #415 at a487b65, compared with main at bed1418b.

For an interface containing only a call signature, the standard Readonly<Fn> mapped type has no named properties. TypeScript therefore accepts 0 as an argument. PR #415 erases the wrapper and proves every argument is truthy.

repro.ts

interface Fn { (): number }

//@ ensures \result
export function truthy(x: Readonly<Fn>): boolean {
  return !!x;
}

Run this command from a built LemmaScript checkout with Dafny 4.11.0 on PATH. Use a fresh fixture directory for each revision.

node tools/dist/lsc.js check --backend=dafny /path/to/repro.ts

On PR head a487b65, the generated function takes x: Fn and has the constant body !(false). Dafny reports 1 verified, 0 errors. Main bed1418b rejects the generated Dafny for this example.

Runtime witness

This separate caller next to repro.ts passes strict TypeScript checking.

import { truthy } from "./repro";

console.log(truthy(0)); // false

Expected behavior

Lower the resolved shape of the mapped type, or reject the case when the model cannot represent its input domain. A regression test should ensure that this postcondition fails verification or extraction rejects the unsupported shape. Readonly wrapper lowering

@namin

namin commented Nov 28, 2026

Copy link
Copy Markdown
Member

Unicode escapes in spec type annotations can redirect a verified record lookup

From Codex. Review finding for PR #415 at a487b65, compared with main at bed1418b.

This is the full reproducer for finding 2 in the earlier Codex summary.

The spec type "\u0061"|"b" denotes the keys "a" and "b". On #415, the emitted lookup uses "u0061" as its first key. This lets the verifier accept a postcondition about the wrong record field.

repro.ts

interface Fields { a: number; u0061: number; b: number }
//@ verify
//@ ensures k === "a" ==> \result === r.b
export function read(r: Fields, k: "a" | "b"): number {
  //@ type k "\u0061"|"b"
  return r[k];
}

From a built LemmaScript checkout with Dafny 4.11.0 on PATH, run the following command. Use a fresh fixture directory for each revision.

node tools/dist/lsc.js check --backend=dafny /path/to/repro.ts

Observed behavior

On #415 at a487b65, Dafny reports 1 verified, 0 errors. The generated body is if k == "u0061" then r.u0061 else r.b. In JavaScript, read({ a: 1, u0061: 3, b: 2 }, "a") returns 1, while the postcondition requires 2. On main at bed1418b, the generated comparison uses "a" and Dafny rejects the postcondition.

Expected behavior

The tokenizer should decode supported escapes according to TypeScript string-literal semantics and report unsupported escape forms explicitly. Add the example above as a regression test that the false postcondition cannot verify. Spec type tokenizer

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants