From 2416d7fc8eeddf6c9e4ff135cce5b0bf4aaa0e16 Mon Sep 17 00:00:00 2001 From: Alex Maldonado Date: Mon, 5 Oct 2026 03:32:06 +0000 Subject: [PATCH] Convert the VC generator to TypeScript vcgen.ts types the symbolic executor under strict mode: the store (a term, or the mark of a variable not yet set), the translation context, the raw obligations, the loop hooks the invariant inference uses, and the report it returns (Obligation, UnitReport, Report, VerifyOptions, exported for the next stages). The parsed program is still built by parse.js and check.js, which stay JavaScript, so its nodes are typed as PNode: a kind, a position and untyped fields. The behavior is unchanged: every obligation of every exercise, corpus program, lesson solution and example, and the regression programs, comes out byte for byte as it did before the conversion. Places where the code read a store value it knew to be a term now say so (valOf), and an unset value read as a term becomes a fresh unknown (asTerm), which is what the name lookup already did. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01FgvbRdoEheAHqsRmr2WuKZ --- src/engines/pseudo/{vcgen.js => vcgen.ts} | 415 ++++++++++++++-------- 1 file changed, 269 insertions(+), 146 deletions(-) rename src/engines/pseudo/{vcgen.js => vcgen.ts} (72%) diff --git a/src/engines/pseudo/vcgen.js b/src/engines/pseudo/vcgen.ts similarity index 72% rename from src/engines/pseudo/vcgen.js rename to src/engines/pseudo/vcgen.ts index 9ac816e..21b8c29 100644 --- a/src/engines/pseudo/vcgen.js +++ b/src/engines/pseudo/vcgen.ts @@ -30,21 +30,120 @@ import { sym, bv, num, lit, TRUE, FALSE, and, or, not, cmp, ite, app, at, at2, length, member, arith, add, sub, neg, mkq, key, substSyms, show, symsOf, sortOf, numeric, } from './logic.js'; +import type { Term, Sort, TypeLike, CmpOp } from './logic.js'; import { prove } from './solver.js'; import { sourceOf } from './parse.js'; import { walkStatements, rootName, statementExprs, walkExpr } from './analyze.js'; -const up = (s) => String(s).toUpperCase(); +/* ------------------------------------------------------------------ */ +/* Types */ +/* ------------------------------------------------------------------ */ + +/** + * A node of the parsed program, as parse.js and check.js build it: a `kind` + * ('For', 'Binary', 'CallExpr', ...), a position, and the fields of that kind. + * The parser is still JavaScript, so the fields are not typed here. + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +export type PNode = { kind: string; line?: number; col?: number; [field: string]: any }; +/** A subroutine as check.js records it (params, requires, ensures, decreases, node). */ +export type Routine = PNode; +/** The checked program: subs, main, constants, defines. */ +export type Program = PNode; + +/** The verifier's unit of work: one subroutine, or the main program. */ +export interface Unit { + name: string; + kind: string; + node: PNode | null; + body: PNode[]; + params: PNode[]; + symbols: PNode[]; + requires: PNode[]; + ensures: PNode[]; + sub?: Routine; +} + +export interface VerifyOptions { budgetMs?: number; maxPaths?: number; infer?: boolean; debug?: boolean } + +/** One obligation group as the report gives it: one place in the source, one kind. */ +export interface Obligation { + kind: string; + line: number | null; + col: number; + label: string; + status: 'proved' | 'unknown'; + paths: number; + target?: number; + measure?: string; + needsMeasure?: boolean; + recursive?: 'self' | 'mutual'; + shown: { facts: string[]; goal: string; trail: string[]; reason?: string; witness?: string[] } | null; +} +export interface Note { line: number; text: string; kind?: string } +export interface UnitReport { + name: string; + kind: string; + line: number; + obligations: Obligation[]; + inferred: Array<{ line: number; facts: string[] }>; + notes: Note[]; + partial: boolean; +} +export interface Report { units: UnitReport[]; counts: { proved: number; unknown: number; total: number } } + +/** A value in the symbolic store: a term, or the mark of a variable declared but not yet set. */ +const UNSET = { k: 'unset' } as const; +type Val = Term | typeof UNSET; +type Env = Map; + +/** What an expression is translated in: inside a spec, under quantifiers, at a call. */ +interface Ctx { + spec?: boolean; + bound?: Map; + result?: Term | null; + paramEnv?: Env; + oldEnv?: Env; + breaks?: State[]; + continues?: State[]; +} +/** One obligation as recorded, before grouping and proving. */ +interface RawOb { + kind: string; line: number | null; col: number; label: string; hyps: Term[]; goal: Term | null; trail: string[]; + target?: number; measure?: string; needsMeasure?: boolean; recursive?: 'self' | 'mutual'; + status?: string; reason?: string; witness?: Term[]; +} +/** A candidate invariant: its text, and the formula it makes over a store. */ +interface Cand { text: string; at: (env: Env) => Term } +/** How a loop kind lets the inference build its head and take a pass. */ +interface InferHooks { + entryEnv: (env: Env) => Env; + makeHead: (extra: (h: State) => Term[]) => { H: State; i?: Term }; + guardOf: ((i: Term) => Term) | null; + whileGuard?: (H: State) => Term; + advance: (st: State, i: Term) => State; + counter?: string; + start?: Term; + step?: number; +} + +const up = (s: unknown): string => String(s).toUpperCase(); +/** A stored value as a term: an unset variable reads as a fresh unknown. */ +const isSet = (v: Val | undefined): v is Term => !!v && v !== UNSET; +const asTerm = (v: Val | undefined, name: string, sort: Sort): Term => (isSet(v) ? v : sym(name, sort)); +/** A store value the code knows is a term (a loop counter, a variable the loop head made fresh). */ +const valOf = (env: Env, k: string): Term => env.get(k) as Term; /** The subroutines a subroutine's body calls directly. */ -const calleeCache = new WeakMap(); -function calleesOf(routine) { - if (calleeCache.has(routine)) return calleeCache.get(routine); - const out = new Set(); +const calleeCache = new WeakMap>(); +function calleesOf(routine: Routine): Set { + const hit = calleeCache.get(routine); + if (hit) return hit; + const out = new Set(); const body = routine.node?.body || []; - const look = (s) => { + const look = (s: PNode): void => { if (s.kind === 'Call' && s.sub) out.add(s.sub); - for (const e of statementExprs(s)) walkExpr(e, (x) => { if (x.kind === 'CallExpr' && x.sub && !x.isOld) out.add(x.sub); }); + for (const e of statementExprs(s)) walkExpr(e, (x: PNode) => { if (x.kind === 'CallExpr' && x.sub && !x.isOld) out.add(x.sub); }); }; walkStatements(body, look); for (const c of [...(routine.requires || []), ...(routine.ensures || [])]) look(c); @@ -53,11 +152,11 @@ function calleesOf(routine) { } /** Whether calling `from` can lead, through any chain of calls, to `to` (from === to counts). */ -function callsReach(program, from, to) { - const seen = new Set(); - const stack = [from]; +function callsReach(program: Program, from: Routine, to: Routine): boolean { + const seen = new Set(); + const stack: Routine[] = [from]; while (stack.length) { - const r = stack.pop(); + const r = stack.pop()!; if (r === to) return true; if (seen.has(r)) continue; seen.add(r); @@ -65,7 +164,6 @@ function callsReach(program, from, to) { } return false; } -const UNSET = { k: 'unset' }; let arrayIds = 0; /* ------------------------------------------------------------------ */ @@ -73,9 +171,12 @@ let arrayIds = 0; /* ------------------------------------------------------------------ */ class State { - constructor(env = new Map(), facts = [], trail = []) { this.env = env; this.facts = facts; this.trail = trail; } - clone() { return new State(new Map(this.env), this.facts.slice(), this.trail.slice()); } - assume(f, why) { + env: Env; + facts: Term[]; + trail: string[]; + constructor(env: Env = new Map(), facts: Term[] = [], trail: string[] = []) { this.env = env; this.facts = facts; this.trail = trail; } + clone(): State { return new State(new Map(this.env), this.facts.slice(), this.trail.slice()); } + assume(f: Term | null | undefined, why?: string): State { const s = this.clone(); if (f && !(f.k === 'lit' && f.v === true)) s.facts.push(f); if (why) s.trail.push(why); @@ -84,12 +185,12 @@ class State { } /** Every variable a list of statements can change. */ -function modifiedIn(body) { - const out = new Set(); - walkStatements(body, (x) => { +function modifiedIn(body: PNode[]): Set { + const out = new Set(); + walkStatements(body, (x: PNode) => { if (x.kind === 'Assign' || x.kind === 'Input') { const r = rootName(x.target); if (r) out.add(up(r)); } if (x.kind === 'BuiltinCall' && x.args[0]) { const r = rootName(x.args[0]); if (r) out.add(up(r)); } - if (x.kind === 'Call') x.args.forEach((a, i) => { if (x.sub?.params?.[i]?.mode === 'BYREF' && a.kind === 'Name') out.add(up(a.name)); }); + if (x.kind === 'Call') x.args.forEach((a: PNode, i: number) => { if (x.sub?.params?.[i]?.mode === 'BYREF' && a.kind === 'Name') out.add(up(a.name)); }); if (x.kind === 'For' || x.kind === 'ForEach') out.add(up(x.var)); if (x.kind === 'Declare') for (const n of x.names) out.add(up(n.name)); }); @@ -101,7 +202,24 @@ function modifiedIn(body) { /* ------------------------------------------------------------------ */ class Exec { - constructor(program, unit, options) { + program: Program; + unit: Unit; + opts: Required> & VerifyOptions; + recording: boolean; + raw: RawOb[]; + notes: Note[]; + inferred: Array<{ line: number; facts: string[] }>; + partial: boolean; + types: Map; + consts: Map; + defines: Map; + depth: number; + quiet = 0; + deadline = 0; + entryEnv: Env = new Map(); + intArith: unknown = false; + floatArith = false; + constructor(program: Program, unit: Unit, options: VerifyOptions) { this.program = program; this.unit = unit; this.opts = { maxPaths: 48, infer: true, budgetMs: 4000, ...options }; @@ -115,21 +233,21 @@ class Exec { for (const p of unit.params || []) this.types.set(up(p.name), p.type); this.consts = new Map(); for (const c of program.constants.values()) this.consts.set(up(c.name), c); - this.defines = new Map([...program.defines.values()].map((d) => [up(d.name), d])); + this.defines = new Map([...program.defines.values()].map((d: PNode): [string, PNode] => [up(d.name), d])); this.depth = 0; } - sortOfName(name) { return sortOf(this.types.get(up(name))); } + sortOfName(name: string): Sort { return sortOf(this.types.get(up(name))); } - obligation(kind, node, label, st, guards, goal, extra = {}) { + obligation(kind: string, node: PNode | null | undefined, label: string, st: State, guards: Term[], goal: Term | null, extra: Partial = {}): void { if (!this.recording || this.quiet) return; this.raw.push({ kind, line: node?.line ?? null, col: node?.col ?? 1, label, hyps: [...st.facts, ...guards], goal, trail: st.trail.slice(), ...extra }); } - fresh(name, sort) { return sym(name, sort); } + fresh(name: string, sort: Sort): Term { return sym(name, sort); } /* ---------- expressions ---------- */ - tr(e, st, g = [], ctx = {}) { + tr(e: PNode, st: State, g: Term[] = [], ctx: Ctx = {}): Term { switch (e.kind) { case 'Num': return num(e.value, e.float ? 'float' : 'int'); case 'Str': return lit(e.value, 'string'); @@ -143,13 +261,13 @@ class Exec { } case 'Binary': return this.binary(e, st, g, ctx); case 'Chain': { - const parts = []; - let prev = this.tr(e.operands[0], st, g, ctx); + const parts: Term[] = []; + let prev: Term | null = this.tr(e.operands[0], st, g, ctx); for (let i = 0; i < e.ops.length; i++) { const nextNode = e.operands[i + 1]; - if (e.ops[i] === 'IN') { parts.push(this.membership(prev, nextNode, st, [...g, ...parts], ctx)); prev = null; continue; } + if (e.ops[i] === 'IN') { parts.push(this.membership(prev ?? this.fresh('?', 'any'), nextNode, st, [...g, ...parts], ctx)); prev = null; continue; } const nx = this.tr(nextNode, st, [...g, ...parts], ctx); - parts.push(cmp(e.ops[i], prev, nx)); + parts.push(cmp(e.ops[i] as CmpOp, prev ?? this.fresh('?', 'any'), nx)); prev = nx; } return and(parts); @@ -160,33 +278,33 @@ class Exec { return fieldRead(r, e.field, sortOf(e.type)); } case 'CallExpr': return this.call(e, st, g, ctx); - case 'ListLit': return app('LIST', e.items.map((x) => this.tr(x, st, g, ctx)), 'list'); - case 'SetLit': return app('SET', e.items.map((x) => this.tr(x, st, g, ctx)), 'set'); - case 'MapLit': return e.entries.reduce((m, x) => app('MAPPUT', [m, this.tr(x.key, st, g, ctx), this.tr(x.value, st, g, ctx)], 'map'), app('EMPTY', [], 'map')); + case 'ListLit': return app('LIST', e.items.map((x: PNode) => this.tr(x, st, g, ctx)), 'list'); + case 'SetLit': return app('SET', e.items.map((x: PNode) => this.tr(x, st, g, ctx)), 'set'); + case 'MapLit': return e.entries.reduce((m: Term, x: PNode) => app('MAPPUT', [m, this.tr(x.key, st, g, ctx), this.tr(x.value, st, g, ctx)], 'map'), app('EMPTY', [], 'map')); case 'Range': return app('RANGE', [this.tr(e.lo, st, g, ctx), this.tr(e.hi, st, g, ctx)], 'range'); case 'SetBuilder': case 'Quant': return this.binder(e, st, g, ctx); default: return this.fresh('?', 'any'); } } - name(e, st, ctx) { + name(e: PNode, st: State, ctx: Ctx): Term { const k = up(e.name); - if (ctx.bound && ctx.bound.has(k)) return bv(ctx.bound.get(k), sortOf(e.type)); + if (ctx.bound && ctx.bound.has(k)) return bv(ctx.bound.get(k)!, sortOf(e.type)); if (ctx.result && k === 'RESULT' && e.sym?.kind === 'result') return ctx.result; - if (ctx.paramEnv && ctx.paramEnv.has(k)) return ctx.paramEnv.get(k); + if (ctx.paramEnv && ctx.paramEnv.has(k)) return asTerm(ctx.paramEnv.get(k), e.name, sortOf(e.type)); if (st.env.has(k)) { const v = st.env.get(k); - if (v === UNSET) return this.fresh(e.name, sortOf(e.type)); + if (!isSet(v)) return this.fresh(e.name, sortOf(e.type)); return v; } const c = this.consts.get(k); if (c) return this.tr(c.node.value, new State(), [], {}); const d = this.defines.get(k); - if (d) return app('SET', d.node.values.map((v) => this.tr(v, new State(), [], {})), 'set'); + if (d) return app('SET', d.node.values.map((v: PNode) => this.tr(v, new State(), [], {})), 'set'); return this.fresh(e.name, sortOf(e.type)); } - binary(e, st, g, ctx) { + binary(e: PNode, st: State, g: Term[], ctx: Ctx): Term { const op = e.op; if (op === 'AND') { const l = this.tr(e.left, st, g, ctx); return and(l, this.tr(e.right, st, [...g, l], ctx)); } if (op === 'OR') { const l = this.tr(e.left, st, g, ctx); return or(l, this.tr(e.right, st, [...g, not(l)], ctx)); } @@ -196,7 +314,7 @@ class Exec { if (['/', 'DIV', 'MOD'].includes(op) && !ctx.spec) { this.obligation('divide', e.right, `${sourceOf(e.right)} is not 0`, st, g, cmp('!=', r, num(0, r.t))); } - if (['==', '!=', '<', '<=', '>', '>='].includes(op)) return cmp(op, l, r); + if (['==', '!=', '<', '<=', '>', '>='].includes(op)) return cmp(op as CmpOp, l, r); // FLOAT arithmetic rounds at every step, so 0.2 + 0.1 - 0.2 is not 0.1 // and X + 1.0 can equal X. The checker knows nothing about a rounded // result except that the same operation on the same values gives it @@ -209,7 +327,7 @@ class Exec { return arith(op, l, r, sortOf(e.type)); } - membership(x, rightNode, st, g, ctx) { + membership(x: Term, rightNode: PNode, st: State, g: Term[], ctx: Ctx): Term { if (rightNode.kind === 'Range') { const lo = this.tr(rightNode.lo, st, g, ctx); const hi = this.tr(rightNode.hi, st, g, ctx); return and(cmp('<=', lo, x), cmp('<', x, hi)); @@ -217,9 +335,9 @@ class Exec { return member(x, this.tr(rightNode, st, g, ctx)); } - index(e, st, g, ctx) { + index(e: PNode, st: State, g: Term[], ctx: Ctx): Term { const c = this.tr(e.target, st, g, ctx); - const idx = e.indices.map((i) => this.tr(i, st, g, ctx)); + const idx: Term[] = e.indices.map((i: PNode) => this.tr(i, st, g, ctx)); const tk = e.target.type?.k; const s = sortOf(e.type); const quiet = ctx.spec || ctx.bound; @@ -241,13 +359,13 @@ class Exec { return at(c, idx[0], s); } - binder(e, st, g, ctx) { - const bound = new Map(ctx.bound || []); + binder(e: PNode, st: State, g: Term[], ctx: Ctx): Term { + const bound = new Map(ctx.bound || []); const name = `${e.var}`; bound.set(up(e.var), name); - const inner = { ...ctx, bound, spec: true }; + const inner: Ctx = { ...ctx, bound, spec: true }; const q = e.kind === 'SetBuilder' ? 'SETOF' : e.q; - const t = e.kind === 'SetBuilder' ? 'set' : e.q === 'SUM' ? sortOf(e.type) : 'bool'; + const t: Sort = e.kind === 'SetBuilder' ? 'set' : e.q === 'SUM' ? sortOf(e.type) : 'bool'; if (e.domain?.kind === 'Range') { const lo = this.tr(e.domain.lo, st, g, ctx); const hi = this.tr(e.domain.hi, st, g, ctx); const body = this.tr(e.body, st, [], inner); @@ -257,13 +375,13 @@ class Exec { return { k: 'qc', q, v: name, dom, body: this.tr(e.body, st, [], inner), t }; } - call(e, st, g, ctx) { + call(e: PNode, st: State, g: Term[], ctx: Ctx): Term { if (e.isOld) { const n = e.args[0]; - if (ctx.oldEnv && n.kind === 'Name' && ctx.oldEnv.has(up(n.name))) return ctx.oldEnv.get(up(n.name)); + if (ctx.oldEnv && n.kind === 'Name' && ctx.oldEnv.has(up(n.name))) return asTerm(ctx.oldEnv.get(up(n.name)), n.name, sortOf(n.type)); return this.tr(n, st, g, ctx); } - const args = e.args.map((a) => this.tr(a, st, g, ctx)); + const args: Term[] = e.args.map((a: PNode) => this.tr(a, st, g, ctx)); const s = sortOf(e.type); if (e.builtin) { const [x, y, z] = args; @@ -316,7 +434,7 @@ class Exec { const sub = e.sub; if (!sub) return this.fresh(e.name, s); const result = app(`FN:${sub.name}`, args, s); - const paramEnv = new Map(sub.params.map((p, i) => [up(p.name), args[i]])); + const paramEnv: Env = new Map(sub.params.map((p: PNode, i: number): [string, Val] => [up(p.name), args[i]])); if (!ctx.spec) { for (const r of sub.requires) { const goal = this.tr(r.expr, st, [], { paramEnv, spec: true }); @@ -331,7 +449,7 @@ class Exec { } /** A recursive call has to make the DECREASES measure smaller, and keep it at 0 or above. */ - recursion(sub, at, args, st, g) { + recursion(sub: Routine, at: PNode, args: Term[], st: State, g: Term[]): void { const cur = this.unit.sub; if (!cur || !callsReach(this.program, sub, cur)) return; // Only a subroutine calling itself, with a DECREASES, has a measure to @@ -340,18 +458,18 @@ class Exec { this.obligation('terminates', at, sub === cur ? `the recursive calls to ${sub.name} end` : `the calls from ${cur.name} to ${sub.name} and back end`, st, g, null, { needsMeasure: true, recursive: sub === cur ? 'self' : 'mutual' }); return; } - const paramEnv = new Map(sub.params.map((p, i) => [up(p.name), args[i]])); + const paramEnv: Env = new Map(sub.params.map((p: PNode, i: number): [string, Val] => [up(p.name), args[i]])); const now = this.tr(sub.decreases.expr, st, [], { spec: true }); const then = this.tr(sub.decreases.expr, st, [], { paramEnv, spec: true }); this.obligation('decreases-step', at, `the recursive call makes ${sourceOf(sub.decreases.expr)} smaller`, st, g, and(cmp('<', then, now), cmp('>=', then, num(0)))); } /* ---------- statements ---------- */ - run(body, states, ctx) { + run(body: PNode[], states: State[], ctx: Ctx): State[] { let cur = states; for (const s of body) { if (!cur.length) break; - const next = []; + const next: State[] = []; for (const st of cur) next.push(...this.stmt(s, st, ctx)); if (next.length > this.opts.maxPaths) { this.partial = true; cur = next.slice(0, this.opts.maxPaths); } else cur = next; if (this.deadline && Date.now() > this.deadline) { this.partial = true; return []; } @@ -359,17 +477,17 @@ class Exec { return cur; } - stmt(s, st, ctx) { + stmt(s: PNode, st: State, ctx: Ctx): State[] { switch (s.kind) { case 'Declare': { const n = st.clone(); for (const nm of s.names) { const k = s.resolved?.k; - let v = UNSET; + let v: Val = UNSET; if (k === 'LIST') v = app('LIST', [], 'list'); else if (k === 'HASHMAP' || k === 'SET') v = app('EMPTY', [], k === 'SET' ? 'set' : 'map'); else if (k === 'ARRAY') { - const dims = (s.resolved.dimExprs || []).map((d) => this.tr(d, st, [])); + const dims: Term[] = (s.resolved.dimExprs || []).map((d: PNode) => this.tr(d, st, [])); v = app('NEWARRAY', [num(++arrayIds), ...dims], 'array'); if (dims.length) n.facts.push(cmp('>=', dims[0], num(0))); } else if (k === 'RECORD') v = this.fresh(nm.name, 'record'); @@ -417,14 +535,14 @@ class Exec { } /** Write a value into a target, updating the symbolic store. */ - store(target, v, n, st) { + store(target: PNode, v: Term, n: State, st: State): void { if (target.kind === 'Name') { n.env.set(up(target.name), v); return; } const root = rootName(target); - const build = (t, value) => { + const build = (t: PNode, value: Term): Term => { if (t.kind === 'Name') return value; if (t.kind === 'Index') { const container = this.tr(t.target, n, []); - const idx = t.indices.map((i) => this.tr(i, st, [])); + const idx: Term[] = t.indices.map((i: PNode) => this.tr(i, st, [])); const tk = t.target.type?.k; if (tk === 'HASHMAP') return build(t.target, app('MAPPUT', [container, idx[0], value], 'map')); if (idx.length === 2) { @@ -444,12 +562,12 @@ class Exec { n.env.set(up(root), build(target, v)); } - builtin(s, st) { - const [first, ...rest] = s.args; - const vals = rest.map((a) => this.tr(a, st, [])); + builtin(s: PNode, st: State): State { + const [first, ...rest]: PNode[] = s.args; + const vals: Term[] = rest.map((a) => this.tr(a, st, [])); const coll = this.tr(first, st, []); const n = st.clone(); - let nv; + let nv: Term; switch (s.name) { case 'APPEND': nv = app('APPENDED', [coll, vals[0]], 'list'); break; case 'ADD': nv = app('SETADD', [coll, vals[0]], 'set'); break; @@ -473,18 +591,18 @@ class Exec { return n; } - procCall(s, st) { + procCall(s: PNode, st: State): State { const sub = s.sub; if (!sub) return st; - const args = s.args.map((a) => this.tr(a, st, [])); - const paramEnv = new Map(sub.params.map((p, i) => [up(p.name), args[i]])); + const args: Term[] = s.args.map((a: PNode) => this.tr(a, st, [])); + const paramEnv: Env = new Map(sub.params.map((p: PNode, i: number): [string, Val] => [up(p.name), args[i]])); for (const r of sub.requires) { this.obligation('require', s, `this call to ${sub.name} meets its REQUIRE, ${sourceOf(r.expr)}`, st, [], this.tr(r.expr, st, [], { paramEnv, spec: true }), { target: r.line }); } this.recursion(sub, s, args, st, []); const n = st.clone(); const after = new Map(paramEnv); - sub.params.forEach((p, i) => { + sub.params.forEach((p: PNode, i: number) => { if (p.mode === 'BYREF' && s.args[i].kind === 'Name') { const fresh = this.fresh(s.args[i].name, sortOf(p.type)); n.env.set(up(s.args[i].name), fresh); @@ -495,13 +613,13 @@ class Exec { return n; } - ensure(at, st, value) { + ensure(at: PNode, st: State, value: Term | null): void { const u = this.unit; if (!u.ensures?.length) return; - const paramEnv = new Map(); + const paramEnv: Env = new Map(); for (const p of u.params || []) { const k = up(p.name); - paramEnv.set(k, p.mode === 'BYREF' ? st.env.get(k) : this.entryEnv.get(k)); + paramEnv.set(k, (p.mode === 'BYREF' ? st.env.get(k) : this.entryEnv.get(k)) ?? UNSET); } for (const en of u.ensures) { const goal = this.tr(en.expr, st, [], { paramEnv, result: value, oldEnv: this.entryEnv, spec: true }); @@ -509,8 +627,8 @@ class Exec { } } - ifStmt(s, st, ctx) { - const out = []; + ifStmt(s: PNode, st: State, ctx: Ctx): State[] { + const out: State[] = []; let rest = st; for (let i = 0; i < s.branches.length; i++) { const b = s.branches[i]; @@ -523,12 +641,12 @@ class Exec { return out; } - caseStmt(s, st, ctx) { + caseStmt(s: PNode, st: State, ctx: Ctx): State[] { const v = s.subject ? this.tr(s.subject, st, []) : this.fresh('case', 'any'); - const out = []; + const out: State[] = []; let rest = st; for (const arm of s.arms) { - const c = or(arm.labels.map((l) => (l.value ? cmp('==', v, this.tr(l.value, st, [])) : and(cmp('<=', this.tr(l.low, st, []), v), cmp('<', v, this.tr(l.high, st, [])))))); + const c = or(arm.labels.map((l: PNode) => (l.value ? cmp('==', v, this.tr(l.value, st, [])) : and(cmp('<=', this.tr(l.low, st, []), v), cmp('<', v, this.tr(l.high, st, [])))))); out.push(...this.run(arm.body, [rest.assume(c, `line ${arm.line}`)], ctx)); rest = rest.assume(not(c)); } @@ -540,29 +658,30 @@ class Exec { /* ---------- loops ---------- */ /** The state at the top of a loop: changed variables become fresh symbols. */ - havoc(st, modified, loopLine) { + havoc(st: State, modified: Set, loopLine: number | undefined): State { const n = st.clone(); for (const k of modified) { const old = st.env.get(k); const name = this.types.get(k) ? [...(this.unit.symbols || []), ...(this.unit.params || [])].find((x) => up(x.name) === k)?.name || k : k; - const fresh = this.fresh(name, old && old !== UNSET && old.t ? old.t : this.sortOfName(k)); + const known = isSet(old) ? old : null; + const fresh = this.fresh(name, known && known.t ? known.t : this.sortOfName(k)); n.env.set(k, fresh); // an ARRAY keeps its dimensions, however its contents change - if (old && old !== UNSET && old.t === 'array') n.facts.push(cmp('==', length(fresh), length(old)), cmp('==', columns(fresh), columns(old))); + if (known && known.t === 'array') n.facts.push(cmp('==', length(fresh), length(known)), cmp('==', columns(fresh), columns(known))); } n.trail.push(`the top of the loop on line ${loopLine}`); return n; } - userInvariants(s, st, env) { + userInvariants(s: PNode, st: State, env?: Env): Array<{ node: PNode; term: Term }> { const view = new State(env || st.env, st.facts, st.trail); - return (s.invariants || []).map((inv) => ({ node: inv, term: this.tr(inv.expr, view, [], { spec: true }) })); + return (s.invariants || []).map((inv: PNode) => ({ node: inv, term: this.tr(inv.expr, view, [], { spec: true }) })); } - forStmt(s, E, ctx) { + forStmt(s: PNode, E: State, ctx: Ctx): State[] { const a = this.tr(s.start, E, []); const b = this.tr(s.stop, E, []); - const step = s.step ? (s.step.kind === 'Num' ? s.step.value : null) : 1; + const step: number | null = s.step ? (s.step.kind === 'Num' ? s.step.value : null) : 1; const I = up(s.var); const modified = modifiedIn(s.body); modified.delete(I); @@ -571,15 +690,15 @@ class Exec { for (const inv of this.userInvariants(s, E, entryEnv)) { this.obligation('invariant-init', inv.node, `the INVARIANT holds before the first pass`, E, [], inv.term); } - const counterFacts = (i) => { + const counterFacts = (i: Term): Term => { if (step === null) return TRUE; // The counter never passes the stop by a whole step or more, unless the // loop never ran at all and it still holds its start. if (step > 0) return and(cmp('<=', a, i), or(cmp('<', i, add(b, num(step))), cmp('==', i, a))); return and(cmp('>=', a, i), or(cmp('>', i, add(b, num(step))), cmp('==', i, a))); }; - const guardOf = (i) => (step === null ? this.fresh('guard', 'bool') : step > 0 ? cmp('<', i, b) : cmp('>', i, b)); - const makeHead = (extra) => { + const guardOf = (i: Term): Term => (step === null ? this.fresh('guard', 'bool') : step > 0 ? cmp('<', i, b) : cmp('>', i, b)); + const makeHead = (extra: (h: State) => Term[]) => { const H = this.havoc(E, modified, s.line); const i = this.fresh(s.var, 'int'); H.env.set(I, i); @@ -593,14 +712,14 @@ class Exec { for (const inv of this.userInvariants(s, H)) H.facts.push(inv.term); return { H, i }; }; - const advance = (st, i) => { const n = st.clone(); n.env.set(I, add(n.env.get(I), num(step ?? 1))); return n; }; + const advance = (st: State, _i: Term): State => { const n = st.clone(); n.env.set(I, add(asTerm(n.env.get(I), s.var, 'int'), num(step ?? 1))); return n; }; const cands = this.opts.infer ? this.infer(s, E, modified, { - entryEnv: (env) => { const m = new Map(env); m.set(I, a); return m; }, + entryEnv: (env: Env) => { const m = new Map(env); m.set(I, a); return m; }, makeHead, guardOf, advance, counter: I, start: a, step: step ?? 1, }) : []; const { H, i } = makeHead((h) => cands.map((c) => c.at(h.env))); const g = guardOf(i); - const inner = { breaks: [], continues: [] }; + const inner: { breaks: State[]; continues: State[] } = { breaks: [], continues: [] }; const ends = this.run(s.body, [H.assume(g, `line ${s.line}: ${s.var} < ${sourceOf(s.stop)}`)], inner); for (const st of [...ends, ...inner.continues]) { const n = advance(st, i); @@ -616,7 +735,7 @@ class Exec { return after; } - forEach(s, E, ctx) { + forEach(s: PNode, E: State, ctx: Ctx): State[] { const coll = this.tr(s.iterable, E, []); const X = up(s.var); const modified = modifiedIn(s.body); @@ -633,7 +752,7 @@ class Exec { let inPass = H; if (coll.k === 'app' && coll.f === 'RANGE') inPass = H.assume(and(cmp('<=', coll.args[0], x), cmp('<', x, coll.args[1]))); else if (coll.t === 'list' || coll.t === 'set' || coll.t === 'map') inPass = H.assume(member(x, coll)); - const inner = { breaks: [], continues: [] }; + const inner: { breaks: State[]; continues: State[] } = { breaks: [], continues: [] }; const ends = this.run(s.body, [inPass], inner); for (const st of [...ends, ...inner.continues]) { for (const inv of this.userInvariants(s, st)) this.obligation('invariant-keep', inv.node, `each pass keeps the INVARIANT`, st, [], inv.term); @@ -642,22 +761,22 @@ class Exec { return out; } - whileStmt(s, E, ctx) { + whileStmt(s: PNode, E: State, ctx: Ctx): State[] { const modified = modifiedIn(s.body); for (const inv of this.userInvariants(s, E)) this.obligation('invariant-init', inv.node, `the INVARIANT holds before the first pass`, E, [], inv.term); - const makeHead = (extra) => { + const makeHead = (extra: (h: State) => Term[]) => { const H = this.havoc(E, modified, s.line); for (const f of extra(H)) H.facts.push(f); for (const inv of this.userInvariants(s, H)) H.facts.push(inv.term); return { H }; }; - const guardOf = (H) => this.withQuiet(() => this.tr(s.cond, H, [])); + const guardOf = (H: State): Term => this.withQuiet(() => this.tr(s.cond, H, [])); const cands = this.opts.infer ? this.infer(s, E, modified, { - entryEnv: (env) => env, makeHead, guardOf: null, whileGuard: guardOf, advance: (st) => st, + entryEnv: (env: Env) => env, makeHead, guardOf: null, whileGuard: guardOf, advance: (st: State) => st, }) : []; const { H } = makeHead((h) => cands.map((c) => c.at(h.env))); const g = this.tr(s.cond, H, []); - const inner = { breaks: [], continues: [] }; + const inner: { breaks: State[]; continues: State[] } = { breaks: [], continues: [] }; const ends = this.run(s.body, [H.assume(g, `line ${s.line}: ${sourceOf(s.cond)}`)], inner); const back = [...ends, ...inner.continues]; for (const st of back) { @@ -667,15 +786,15 @@ class Exec { return [H.assume(not(g), `line ${s.line}: NOT (${sourceOf(s.cond)})`), ...inner.breaks]; } - repeatStmt(s, E, ctx) { + repeatStmt(s: PNode, E: State, ctx: Ctx): State[] { const modified = modifiedIn(s.body); for (const inv of this.userInvariants(s, E)) this.obligation('invariant-init', inv.node, `the INVARIANT holds before the first pass`, E, [], inv.term); const H = this.havoc(E, modified, s.line); for (const inv of this.userInvariants(s, H)) H.facts.push(inv.term); - const inner = { breaks: [], continues: [] }; + const inner: { breaks: State[]; continues: State[] } = { breaks: [], continues: [] }; const ends = this.run(s.body, [H], inner); - const exits = []; - const again = []; + const exits: State[] = []; + const again: State[] = []; for (const st of [...ends, ...inner.continues]) { const c = s.cond ? this.tr(s.cond, st, []) : TRUE; exits.push(st.assume(c, `line ${s.endLine}: UNTIL ${sourceOf(s.cond)}`)); @@ -687,7 +806,7 @@ class Exec { return [...exits, ...inner.breaks]; } - withQuiet(fn) { this.quiet = (this.quiet || 0) + 1; try { return fn(); } finally { this.quiet--; } } + withQuiet(fn: () => T): T { this.quiet = (this.quiet || 0) + 1; try { return fn(); } finally { this.quiet--; } } /** * Termination. A DECREASES line gives two obligations: the measure is at @@ -695,7 +814,7 @@ class Exec { * Without one, a WHILE loop gets a guess from its condition (N - I for * I < N) that is kept only if both obligations prove. */ - decreases(s, H, guard, backStates, needed = false, cands = []) { + decreases(s: PNode, H: State, guard: Term, backStates: State[], needed = false, _cands: Cand[] = []): void { if (s.decreases) { const d0 = this.tr(s.decreases.expr, H, [], { spec: true }); this.obligation('decreases-bound', s.decreases, `${sourceOf(s.decreases.expr)} is at least 0 while the loop continues`, H, [guard], cmp('>=', d0, num(0))); @@ -707,7 +826,7 @@ class Exec { } if (!needed || s.kind === 'For' || !this.recording) return; // guess a measure from the condition - const guesses = []; + const guesses: PNode[] = []; const conds = s.cond ? conjuncts(s.cond) : []; for (const c of conds) { if (c.kind !== 'Binary') continue; @@ -723,7 +842,7 @@ class Exec { const okBound = prove([...H.facts, guard], cmp('>=', d0, num(0))).status === 'proved'; const okStep = okBound && backStates.every((st) => prove(st.facts, cmp('<', this.withQuiet(() => this.tr(gs, st, [], { spec: true })), d0)).status === 'proved'); if (okBound && okStep) { - this.notes.push({ line: s.line, text: `The ${s.kind === 'While' ? 'WHILE' : 'REPEAT'} loop on line ${s.line} ends: ${sourceOf(gs)} is at least 0 whenever the loop continues, and every pass makes it smaller. The checker found this measure itself; writing it as DECREASES ${sourceOf(gs)} states it for a reader.` }); + this.notes.push({ line: s.line as number, text: `The ${s.kind === 'While' ? 'WHILE' : 'REPEAT'} loop on line ${s.line} ends: ${sourceOf(gs)} is at least 0 whenever the loop continues, and every pass makes it smaller. The checker found this measure itself; writing it as DECREASES ${sourceOf(gs)} states it for a reader.` }); this.obligation('terminates', s, `the ${s.kind === 'While' ? 'WHILE' : 'REPEAT'} loop on line ${s.line} ends`, H, [], TRUE, { measure: sourceOf(gs) }); return; } @@ -739,29 +858,30 @@ class Exec { * left survives. What is left is proved, and the loop's real analysis * assumes it. */ - infer(s, E, modified, h) { + infer(s: PNode, E: State, modified: Set, h: InferHooks): Cand[] { if (this.depth > 2) return []; - const cands = []; + const cands: Cand[] = []; const entry = h.entryEnv(E.env); const counter = h.counter; - const startTerm = h.start; + const startTerm = h.start ?? num(0); const loopLine = s.line; for (const k of modified) { const v0 = E.env.get(k); const nm = [...(this.unit.symbols || [])].find((x) => up(x.name) === k)?.name || k; if (!v0 || v0 === UNSET) continue; + if (!isSet(v0)) continue; const t = v0.t; if (numeric(t)) { - cands.push({ text: `${nm} >= ${show(v0)}`, at: (env) => cmp('>=', env.get(k), v0) }); - cands.push({ text: `${nm} <= ${show(v0)}`, at: (env) => cmp('<=', env.get(k), v0) }); - if (counter) cands.push({ text: `${nm} <= ${show(v0)} + ${counter} - ${show(startTerm)}`, at: (env) => cmp('<=', env.get(k), add(v0, sub(env.get(counter), startTerm))) }); + cands.push({ text: `${nm} >= ${show(v0)}`, at: (env) => cmp('>=', valOf(env, k), v0) }); + cands.push({ text: `${nm} <= ${show(v0)}`, at: (env) => cmp('<=', valOf(env, k), v0) }); + if (counter) cands.push({ text: `${nm} <= ${show(v0)} + ${counter} - ${show(startTerm)}`, at: (env) => cmp('<=', valOf(env, k), add(v0, sub(valOf(env, counter), startTerm))) }); } if (t === 'list' || t === 'string') { - cands.push({ text: `LENGTH(${nm}) >= LENGTH(before the loop)`, at: (env) => cmp('>=', length(env.get(k)), length(v0)) }); + cands.push({ text: `LENGTH(${nm}) >= LENGTH(before the loop)`, at: (env) => cmp('>=', length(valOf(env, k)), length(v0)) }); if (counter) { - const passes = (env) => (h.step < 0 ? sub(startTerm, env.get(counter)) : sub(env.get(counter), startTerm)); - cands.push({ text: `LENGTH(${nm}) <= LENGTH(before) + passes`, at: (env) => cmp('<=', length(env.get(k)), add(length(v0), passes(env))) }); - cands.push({ text: `LENGTH(${nm}) == LENGTH(before) + passes`, at: (env) => cmp('==', length(env.get(k)), add(length(v0), passes(env))) }); + const passes = (env: Env): Term => ((h.step ?? 1) < 0 ? sub(startTerm, valOf(env, counter)) : sub(valOf(env, counter), startTerm)); + cands.push({ text: `LENGTH(${nm}) <= LENGTH(before) + passes`, at: (env) => cmp('<=', length(valOf(env, k)), add(length(v0), passes(env))) }); + cands.push({ text: `LENGTH(${nm}) == LENGTH(before) + passes`, at: (env) => cmp('==', length(valOf(env, k)), add(length(v0), passes(env))) }); } } } @@ -773,12 +893,12 @@ class Exec { if (l.kind === 'Name' && modified.has(up(l.name)) && l.type?.k === 'INTEGER') { const op = c.op === '<' ? '<=' : c.op === '>' ? '>=' : c.op; const extra = c.op === '<=' ? 1 : c.op === '>=' ? -1 : 0; - cands.push({ text: `${l.name} ${op} ${sourceOf(r)}${extra ? (extra > 0 ? ' + 1' : ' - 1') : ''}`, at: (env) => { const st = new State(env, []); const R = this.withQuiet(() => this.tr(r, st, [], { spec: true })); return cmp(op, env.get(up(l.name)), extra ? add(R, num(extra)) : R); } }); + cands.push({ text: `${l.name} ${op} ${sourceOf(r)}${extra ? (extra > 0 ? ' + 1' : ' - 1') : ''}`, at: (env) => { const st = new State(env, []); const R = this.withQuiet(() => this.tr(r, st, [], { spec: true })); return cmp(op as CmpOp, valOf(env, up(l.name)), extra ? add(R, num(extra)) : R); } }); } } } if (!cands.length) return []; - let lastHead = null; + let lastHead: State | null = null; let live = cands.filter((c) => { try { return prove(E.facts, c.at(entry)).status === 'proved'; } catch { return false; } }); @@ -794,10 +914,10 @@ class Exec { const { H, i } = h.makeHead((hh) => live.map((c) => c.at(hh.env))); lastHead = H; let start = H; - if (h.guardOf) start = H.assume(h.guardOf(i)); + if (h.guardOf) start = H.assume(h.guardOf(i as Term)); else if (h.whileGuard) start = H.assume(h.whileGuard(H)); const inner = { breaks: [], continues: [] }; - const ends = this.run(s.body, [start], inner).concat(inner.continues).map((st) => h.advance(st, i)); + const ends = this.run(s.body, [start], inner).concat(inner.continues).map((st) => h.advance(st, i as Term)); const keep = live.filter((c) => ends.every((st) => { try { return prove(st.facts, c.at(st.env)).status === 'proved'; } catch { return false; } })); @@ -814,13 +934,13 @@ class Exec { const env = lastHead ? lastHead.env : entry; const texts = live.filter((c) => { try { return prove([], c.at(env)).status !== 'proved'; } catch { return true; } }) .map((c) => { try { return show(c.at(env)); } catch { return c.text; } }); - this.inferred.push({ line: loopLine, facts: [...new Set(texts)] }); + this.inferred.push({ line: loopLine as number, facts: [...new Set(texts)] }); } return live; } /* ---------- a whole unit ---------- */ - runUnit() { + runUnit(): void { const u = this.unit; const st = new State(); this.entryEnv = new Map(); @@ -831,22 +951,22 @@ class Exec { } for (const r of u.requires || []) st.facts.push(this.tr(r.expr, st, [], { spec: true })); const ends = this.run(u.body, [st], { breaks: [], continues: [] }); - if (u.kind === 'Procedure') for (const e of ends) this.ensure({ line: u.node.endLine, col: 1 }, e, null); + if (u.kind === 'Procedure') for (const e of ends) this.ensure({ kind: 'End', line: u.node!.endLine, col: 1 }, e, null); } } -function conjuncts(e) { +function conjuncts(e: PNode | null | undefined): PNode[] { if (!e) return []; if (e.kind === 'Binary' && e.op === 'AND') return [...conjuncts(e.left), ...conjuncts(e.right)]; return [e]; } -function fieldRead(r, field, s) { +function fieldRead(r: Term, field: string, s: Sort): Term { if (r.k === 'app' && r.f.startsWith('FSTORE.')) return r.f === `FSTORE.${up(field)}` ? r.args[1] : fieldRead(r.args[0], field, s); return app(`FIELD.${field}`, [r], s); } -function columns(x) { +function columns(x: Term): Term { if (x.k === 'app' && x.f === 'NEWARRAY') return x.args[2] || num(0); if (x.k === 'app' && x.f === 'STORE2') return columns(x.args[0]); return app('COLUMNS', [x], 'int'); @@ -857,9 +977,9 @@ function columns(x) { /* ------------------------------------------------------------------ */ /** The facts that share a symbol with the goal, directly or through another fact. */ -function relevantFacts(hyps, goal, limit = 14) { +function relevantFacts(hyps: Term[], goal: Term, limit = 14): Term[] { const want = new Set(symsOf(goal).keys()); - const chosen = new Set(); + const chosen = new Set(); for (let round = 0; round < 3; round++) { let grew = false; hyps.forEach((h, i) => { @@ -873,12 +993,12 @@ function relevantFacts(hyps, goal, limit = 14) { } /** Display names: the newest version of I prints as I, older ones as I0, I1, ... */ -function namesFor(terms) { - const all = new Map(); +function namesFor(terms: Term[]): Map { + const all = new Map(); for (const t of terms) symsOf(t, all); - const byName = new Map(); - for (const s of all.values()) { if (!byName.has(s.name)) byName.set(s.name, []); byName.get(s.name).push(s); } - const names = new Map(); + const byName = new Map>(); + for (const s of all.values()) { let l = byName.get(s.name); if (!l) { l = []; byName.set(s.name, l); } l.push(s); } + const names = new Map(); for (const [n, list] of byName) { list.sort((a, b) => a.id - b.id); list.forEach((s, i) => names.set(key(s), i === list.length - 1 ? n : `${n}${'₀₁₂₃₄₅₆₇₈₉'[i] || i}`)); @@ -886,44 +1006,47 @@ function namesFor(terms) { return names; } -export function verifyUnit(program, unit, options = {}) { +export function verifyUnit(program: Program, unit: Unit, options: VerifyOptions = {}): UnitReport { const ex = new Exec(program, unit, options); ex.deadline = Date.now() + (options.budgetMs ?? 4000); - try { ex.runUnit(); } catch (err) { ex.partial = true; ex.notes.push({ line: unit.node?.line ?? 1, text: `The checker stopped early: ${err.message}` }); } + try { ex.runUnit(); } catch (err) { ex.partial = true; ex.notes.push({ line: unit.node?.line ?? 1, text: `The checker stopped early: ${(err as Error).message}` }); } // The number model behind "proved": INTEGER is a whole number of any size. // Neither the lab's limit (a run stops past 2^53 - 1) nor Mojo's 64-bit Int // (which wraps past 2^63 - 1, probes/int-overflow-int) is part of the proof. if (ex.floatArith) ex.notes.push({ line: unit.node?.line ?? 1, kind: 'float-model', text: 'The proofs here treat a FLOAT as a finite number and assume nothing about a rounded result except that the same calculation gives it again. A run in this lab stops when a FLOAT passes about 1.8 × 10^308; in the Mojo made from this program, a Float64 division by zero gives inf or nan and the run goes on (probes/float-special).' }); if (ex.intArith) ex.notes.push({ line: unit.node?.line ?? 1, kind: 'int-model', text: 'The proofs here treat INTEGER as a whole number of any size. A run in this lab stops when a whole number passes 9,007,199,254,740,991, and the Mojo made from this program uses a 64-bit Int, which wraps around past 9,223,372,036,854,775,807. Neither limit is part of the proof.' }); - const groups = new Map(); + type Group = { kind: string; line: number | null; col: number; label: string; instances: RawOb[]; target?: number; measure?: string; needsMeasure?: boolean; recursive?: 'self' | 'mutual' }; + const groups = new Map(); for (const o of ex.raw) { const k = `${o.kind}@${o.line}:${o.col}@${o.label}`; if (!groups.has(k)) groups.set(k, { kind: o.kind, line: o.line, col: o.col, label: o.label, instances: [], target: o.target, measure: o.measure, needsMeasure: o.needsMeasure, recursive: o.recursive }); - groups.get(k).instances.push(o); + groups.get(k)!.instances.push(o); } - const obligations = []; + const obligations: Obligation[] = []; for (const gr of groups.values()) { - let status = 'proved'; - let failing = null; + let status: 'proved' | 'unknown' = 'proved'; + let failing: RawOb | null = null; if (gr.needsMeasure) { status = 'unknown'; failing = gr.instances[0]; } else { for (const inst of gr.instances) { if (Date.now() > ex.deadline + 2000) { status = 'unknown'; failing = inst; inst.reason = 'the checker ran out of time'; break; } - let r; - try { r = prove(inst.hyps, inst.goal); } catch (err) { r = { status: 'unknown', reason: err.message }; } + let r: import('./solver.js').ProveResult; + try { r = inst.goal ? prove(inst.hyps, inst.goal) : { status: 'unknown', reason: 'there is no goal to prove' }; } catch (err) { r = { status: 'unknown', reason: (err as Error).message }; } inst.status = r.status; if (r.status !== 'proved') { status = 'unknown'; failing = inst; inst.reason = r.reason; inst.witness = r.witness; break; } } } const shownInst = failing || gr.instances[0]; - let shown = null; + let shown: Obligation['shown'] = null; if (shownInst && shownInst.goal) { const facts = relevantFacts(shownInst.hyps, shownInst.goal); const names = namesFor([...facts, shownInst.goal]); shown = { facts: facts.map((f) => show(f, names)), goal: show(shownInst.goal, names), trail: shownInst.trail, reason: shownInst.reason }; - if (options.debug && shownInst.witness) shown.witness = shownInst.witness.map((l) => show(l, namesFor([...shownInst.hyps, shownInst.goal]))); + const goal = shownInst.goal; + if (options.debug && shownInst.witness) shown.witness = shownInst.witness.map((l) => show(l, namesFor([...shownInst.hyps, goal]))); } - obligations.push({ ...gr, status, paths: gr.instances.length, shown, instances: undefined }); + const { instances, ...place } = gr; + obligations.push({ ...place, status, paths: instances.length, shown, instances: undefined } as Obligation); } obligations.sort((a, b) => (a.line ?? 0) - (b.line ?? 0) || KIND_ORDER.indexOf(a.kind) - KIND_ORDER.indexOf(b.kind)); return { name: unit.name, kind: unit.kind, line: unit.node?.line ?? 1, obligations, inferred: ex.inferred, notes: ex.notes, partial: ex.partial }; @@ -931,8 +1054,8 @@ export function verifyUnit(program, unit, options = {}) { const KIND_ORDER = ['require', 'index', 'key', 'slice', 'divide', 'argument', 'invariant-init', 'invariant-keep', 'decreases-bound', 'decreases-step', 'terminates', 'assert', 'ensure']; -export function verify(program, options = {}) { - const units = []; +export function verify(program: Program, options: VerifyOptions = {}): Report { + const units: UnitReport[] = []; for (const sub of program.subs.values()) { units.push(verifyUnit(program, { name: sub.name, kind: sub.kind, node: sub.node, body: sub.node.body, params: sub.params, symbols: sub.symbols || [], requires: sub.requires, ensures: sub.ensures, sub }, options)); } @@ -941,7 +1064,7 @@ export function verify(program, options = {}) { return { units, counts: { proved: all.filter((o) => o.status === 'proved').length, unknown: all.filter((o) => o.status !== 'proved').length, total: all.length } }; } -export const OBLIGATION_WORDS = { +export const OBLIGATION_WORDS: Record = { index: 'Position exists', key: 'Key present', slice: 'Slice in range',