Repository navigation
Shift 3 (Milestone 1): self-verified spec type parser and structured Ty on RawIR - #415
robertpenner wants to merge 9 commits into
Conversation
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.
# Conflicts: # tools/src/transform.ts
|
This looks great. I am still reading through. In the meantime, here are some small issues found by codex.
|
Assertion callbacks acquire a boolean return value during extractionFrom Codex. Review finding for PR #415 at PR #415 verifies that 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 node tools/dist/lsc.js check --backend=dafny /path/to/repro.tsPR head Runtime witnessThis separate caller next to import { demo } from "./repro";
function assertZero(x: number): asserts x is 0 {
if (x !== 0) throw new Error("Expected zero");
}
console.log(demo(assertZero)); // falseExpected behaviorDistinguish an assertion signature ( 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 |
Preserve renamed imports in Dafny extern signaturesFrom Codex. Review finding for PR #415 at 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 dep.tsexport interface Entity { val: number }
//@ ensures \result === x.val
export function f(x: Entity): number { return x.val; }main.tsimport { 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 node tools/dist/lsc.js check --backend=dafny /path/to/main.tsObserved. On Expected. Both signatures should refer to the same modeled declaration, respecting the caller's 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 |
Accept hexadecimal numeric literal unions in spec type annotationsFrom Codex. Review finding for PR #415 at The spec type parser introduced in #415 rejects a previously accepted hexadecimal flag union in 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 node tools/dist/lsc.js check --backend=dafny /path/to/main.tsObserved. On Expected. The parser should recognize each hexadecimal integer as one numeric literal and lower this union the same way it lowers |
Named tuple rest elements become a single required array slotFrom Codex. Review finding for PR #415 at This is the full reproducer for finding 1 in the earlier Codex summary. For 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 node tools/dist/lsc.js check --backend=dafny /path/to/repro.tsObserved behaviorOn #415 at Expected behaviorPreserve 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 |
Erasing Readonly from a callable interface excludes valid TypeScript inputsFrom Codex. Review finding for PR #415 at For an interface containing only a call signature, the standard repro.tsinterface 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 node tools/dist/lsc.js check --backend=dafny /path/to/repro.tsOn PR head Runtime witnessThis separate caller next to import { truthy } from "./repro";
console.log(truthy(0)); // falseExpected behaviorLower 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 |
Unicode escapes in spec type annotations can redirect a verified record lookupFrom Codex. Review finding for PR #415 at This is the full reproducer for finding 2 in the earlier Codex summary. The spec type repro.tsinterface 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 node tools/dist/lsc.js check --backend=dafny /path/to/repro.tsObserved behaviorOn #415 at Expected behaviorThe 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 |
Motivation
LemmaScript previously flattened TypeScript types to strings during extraction (
getText(),typeToString(),tyToTsStr()), stored those strings onRawIR, and re-parsed them insideresolve.tsby injecting synthetic TypeScript source files (__lsc_type_parse__.ts) intots-morphviaparseTsType. That architecture coupledtypes.tsandresolve.tstots-morph, blocked self-verification of downstream compiler passes, and forced everyRawIRconsumer 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+tools/src/spec-type.ts):tools/src/spec-type-parser.ts(//@ backend dafny) inLemmaScript-files.txt, with generatedtools/src/spec-type-parser.dfyandtools/src/spec-type-parser.dfy.gen(zero hand edits).//@annotation type-parsing sites (//@ type,//@ declare-type,//@ ghost let,//@ havoc : Type,forall/exists, and specnew Set<T>()/new Map<K, V>()) throughparseSpecType.ts-morphextraction and structuredTyonRawIR(tools/src/extract-types.ts+tools/src/extract.ts):extractTy,extractTyFromNode,typeToTsString,wrapNullability,eraseGenericTy,eraseTypeText,registerSynthArrayUnion, andtrySynthArrayUnionFromNodes.Tyon allRawIRdeclarations, parameters, fields, statements, expressions, and synthesizedT[] | Udatatypes, while preservingtsTypedisplay metadata forlsc info --typed(Map<K, V>vsRecord<K, V>).initTypeParser,parseTsType,tyFromTypeNode,tyToTsStr, the synthetic__lsc_type_parse__.tsfile, and allts-morphimports fromtools/src/types.tsandtools/src/resolve.ts.parseSpecTypefallbacks inchecked-reads.ts,narrow-checks.ts, andtransform.ts.lowerCheckerType(checkinggetAliasSymbol()andgetSymbol()beforeisVoid()andisAny() || isUnknown()) so//@ declare-typeshadowing works when externalnode_modulesare absent (verified againstflue-lemmascriptandmcp-sdk-lemmascript).Findings and advances
tools/src/spec-type-parser.tsverifies under./tools/check.sh dafnywith 18 verified, 0 errors, zeroassume/havoc/{:axiom}, and 0-byte diff betweentools/src/spec-type-parser.dfyandtools/src/spec-type-parser.dfy.gen. Proved postconditions cover token-stream validity, progress, nullability flattening (no nestedoptional/nullishwrappers,void | nullnormalizing tonullish(void)), and full-input consumption.ts-morphboundary: Static tests intools/tests/spec-type-parser.test.tsscantools/src/and confirmts-morphandtypescriptimports exist only in the 6 allowlisted extraction/CLI files (config.ts,extract.ts,extract-types.ts,lexical-names.ts,lsc.ts,source-projects.ts). Neithertypes.ts,resolve.ts,spec-type*.ts, nor downstream passes importts-morph../regen-dafny.sh --no-verifyand./regen-lean.shproduces 0 lines of diff inexamples/.Future Work
extractTy(including inlinePartial<T>,Pick<T, K>,Omit<T, K>), pending Open Question 1 on Spec: Direct ts-morph type extraction, uniform inline-record synthesis, and structured generic types (Shift 3 of #386) #396.Ty.args), structuralTysubstitution, bounded-generic policy, and Lean generic declarations, pending Open Question 2 on Spec: Direct ts-morph type extraction, uniform inline-record synthesis, and structured generic types (Shift 3 of #386) #396.Evidence
096600e):tools/src/types.tsimportedts-morphand created a synthetic__lsc_type_parse__.tssource file to re-parseRawIRtsTypestrings inresolve.ts;LemmaScript-files.txtlisted 2 self-verified files (alias-check.ts,places.ts).a487b65, merged withupstream/main1e657a9):robertpenner/LemmaScriptrun46110971477): 46/46 checks passing (tools,unit-tests (1)&(2),examples-dafny (0..3),generated-dafny,generated-lean,lean, all 32case-studies-dafnyjobs, and all 4case-studies-leanjobs).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-check6,places11,spec-type-parser18 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,
RawIRfields, type resolution, andLemmaScript-files.txt. All examples regenerate identically for both Dafny and Lean, all 3 self-verified compiler files plusformal/narrowing-model.dfyverify with 0 errors, and all 36 Dafny/Lean case-study jobs pass.Refs #396