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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FgvbRdoEheAHqsRmr2WuKZ
This commit is contained in:
alexmandClaude committed 2026-10-05 03:32:06 +00:00
1 parent 765459c340
commit 2416d7fc8e
1 file changed
+269 -146
@@ -30,21 +30,120 @@ import {
sym, bv, num, lit, TRUE, FALSE, and, or, not, cmp, ite, app, at, at2, length, member, 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, arith, add, sub, neg, mkq, key, substSyms, show, symsOf, sortOf, numeric,
} from './logic.js'; } from './logic.js';
import type { Term, Sort, TypeLike, CmpOp } from './logic.js';
import { prove } from './solver.js'; import { prove } from './solver.js';
import { sourceOf } from './parse.js'; import { sourceOf } from './parse.js';
import { walkStatements, rootName, statementExprs, walkExpr } from './analyze.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<string, Val>;
/** What an expression is translated in: inside a spec, under quantifiers, at a call. */
interface Ctx {
spec?: boolean;
bound?: Map<string, string>;
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. */ /** The subroutines a subroutine's body calls directly. */
const calleeCache = new WeakMap(); const calleeCache = new WeakMap<Routine, Set<Routine>>();
function calleesOf(routine) { function calleesOf(routine: Routine): Set<Routine> {
if (calleeCache.has(routine)) return calleeCache.get(routine); const hit = calleeCache.get(routine);
const out = new Set(); if (hit) return hit;
const out = new Set<Routine>();
const body = routine.node?.body || []; const body = routine.node?.body || [];
const look = (s) => { const look = (s: PNode): void => {
if (s.kind === 'Call' && s.sub) out.add(s.sub); 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); walkStatements(body, look);
for (const c of [...(routine.requires || []), ...(routine.ensures || [])]) look(c); 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). */ /** Whether calling `from` can lead, through any chain of calls, to `to` (from === to counts). */
function callsReach(program, from, to) { function callsReach(program: Program, from: Routine, to: Routine): boolean {
const seen = new Set(); const seen = new Set<Routine>();
const stack = [from]; const stack: Routine[] = [from];
while (stack.length) { while (stack.length) {
const r = stack.pop(); const r = stack.pop()!;
if (r === to) return true; if (r === to) return true;
if (seen.has(r)) continue; if (seen.has(r)) continue;
seen.add(r); seen.add(r);
@@ -65,7 +164,6 @@ function callsReach(program, from, to) {
} }
return false; return false;
} }
const UNSET = { k: 'unset' };
let arrayIds = 0; let arrayIds = 0;
/* ------------------------------------------------------------------ */ /* ------------------------------------------------------------------ */
@@ -73,9 +171,12 @@ let arrayIds = 0;
/* ------------------------------------------------------------------ */ /* ------------------------------------------------------------------ */
class State { class State {
constructor(env = new Map(), facts = [], trail = []) { this.env = env; this.facts = facts; this.trail = trail; } env: Env;
clone() { return new State(new Map(this.env), this.facts.slice(), this.trail.slice()); } facts: Term[];
assume(f, why) { 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(); const s = this.clone();
if (f && !(f.k === 'lit' && f.v === true)) s.facts.push(f); if (f && !(f.k === 'lit' && f.v === true)) s.facts.push(f);
if (why) s.trail.push(why); if (why) s.trail.push(why);
@@ -84,12 +185,12 @@ class State {
} }
/** Every variable a list of statements can change. */ /** Every variable a list of statements can change. */
function modifiedIn(body) { function modifiedIn(body: PNode[]): Set<string> {
const out = new Set(); const out = new Set<string>();
walkStatements(body, (x) => { 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 === '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 === '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 === 'For' || x.kind === 'ForEach') out.add(up(x.var));
if (x.kind === 'Declare') for (const n of x.names) out.add(up(n.name)); if (x.kind === 'Declare') for (const n of x.names) out.add(up(n.name));
}); });
@@ -101,7 +202,24 @@ function modifiedIn(body) {
/* ------------------------------------------------------------------ */ /* ------------------------------------------------------------------ */
class Exec { class Exec {
constructor(program, unit, options) { program: Program;
unit: Unit;
opts: Required<Pick<VerifyOptions, 'maxPaths' | 'infer' | 'budgetMs'>> & VerifyOptions;
recording: boolean;
raw: RawOb[];
notes: Note[];
inferred: Array<{ line: number; facts: string[] }>;
partial: boolean;
types: Map<string, TypeLike>;
consts: Map<string, PNode>;
defines: Map<string, PNode>;
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.program = program;
this.unit = unit; this.unit = unit;
this.opts = { maxPaths: 48, infer: true, budgetMs: 4000, ...options }; 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); for (const p of unit.params || []) this.types.set(up(p.name), p.type);
this.consts = new Map(); this.consts = new Map();
for (const c of program.constants.values()) this.consts.set(up(c.name), c); 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; 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<RawOb> = {}): void {
if (!this.recording || this.quiet) return; 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 }); 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 ---------- */ /* ---------- expressions ---------- */
tr(e, st, g = [], ctx = {}) { tr(e: PNode, st: State, g: Term[] = [], ctx: Ctx = {}): Term {
switch (e.kind) { switch (e.kind) {
case 'Num': return num(e.value, e.float ? 'float' : 'int'); case 'Num': return num(e.value, e.float ? 'float' : 'int');
case 'Str': return lit(e.value, 'string'); case 'Str': return lit(e.value, 'string');
@@ -143,13 +261,13 @@ class Exec {
} }
case 'Binary': return this.binary(e, st, g, ctx); case 'Binary': return this.binary(e, st, g, ctx);
case 'Chain': { case 'Chain': {
const parts = []; const parts: Term[] = [];
let prev = this.tr(e.operands[0], st, g, ctx); let prev: Term | null = this.tr(e.operands[0], st, g, ctx);
for (let i = 0; i < e.ops.length; i++) { for (let i = 0; i < e.ops.length; i++) {
const nextNode = e.operands[i + 1]; 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); 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; prev = nx;
} }
return and(parts); return and(parts);
@@ -160,33 +278,33 @@ class Exec {
return fieldRead(r, e.field, sortOf(e.type)); return fieldRead(r, e.field, sortOf(e.type));
} }
case 'CallExpr': return this.call(e, st, g, ctx); 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 '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) => this.tr(x, st, g, ctx)), 'set'); case 'SetLit': return app('SET', e.items.map((x: PNode) => 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 '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 '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); case 'SetBuilder': case 'Quant': return this.binder(e, st, g, ctx);
default: return this.fresh('?', 'any'); default: return this.fresh('?', 'any');
} }
} }
name(e, st, ctx) { name(e: PNode, st: State, ctx: Ctx): Term {
const k = up(e.name); 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.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)) { if (st.env.has(k)) {
const v = st.env.get(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; return v;
} }
const c = this.consts.get(k); const c = this.consts.get(k);
if (c) return this.tr(c.node.value, new State(), [], {}); if (c) return this.tr(c.node.value, new State(), [], {});
const d = this.defines.get(k); 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)); 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; 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 === '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)); } 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) { 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))); 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 // 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 // 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 // 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)); 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') { if (rightNode.kind === 'Range') {
const lo = this.tr(rightNode.lo, st, g, ctx); const hi = this.tr(rightNode.hi, st, g, ctx); 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)); return and(cmp('<=', lo, x), cmp('<', x, hi));
@@ -217,9 +335,9 @@ class Exec {
return member(x, this.tr(rightNode, st, g, ctx)); 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 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 tk = e.target.type?.k;
const s = sortOf(e.type); const s = sortOf(e.type);
const quiet = ctx.spec || ctx.bound; const quiet = ctx.spec || ctx.bound;
@@ -241,13 +359,13 @@ class Exec {
return at(c, idx[0], s); return at(c, idx[0], s);
} }
binder(e, st, g, ctx) { binder(e: PNode, st: State, g: Term[], ctx: Ctx): Term {
const bound = new Map(ctx.bound || []); const bound = new Map<string, string>(ctx.bound || []);
const name = `${e.var}`; const name = `${e.var}`;
bound.set(up(e.var), name); 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 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') { 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 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); 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 }; 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) { if (e.isOld) {
const n = e.args[0]; 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); 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); const s = sortOf(e.type);
if (e.builtin) { if (e.builtin) {
const [x, y, z] = args; const [x, y, z] = args;
@@ -316,7 +434,7 @@ class Exec {
const sub = e.sub; const sub = e.sub;
if (!sub) return this.fresh(e.name, s); if (!sub) return this.fresh(e.name, s);
const result = app(`FN:${sub.name}`, args, 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) { if (!ctx.spec) {
for (const r of sub.requires) { for (const r of sub.requires) {
const goal = this.tr(r.expr, st, [], { paramEnv, spec: true }); 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. */ /** 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; const cur = this.unit.sub;
if (!cur || !callsReach(this.program, sub, cur)) return; if (!cur || !callsReach(this.program, sub, cur)) return;
// Only a subroutine calling itself, with a DECREASES, has a measure to // 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' }); 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; 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 now = this.tr(sub.decreases.expr, st, [], { spec: true });
const then = this.tr(sub.decreases.expr, st, [], { paramEnv, 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)))); 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 ---------- */ /* ---------- statements ---------- */
run(body, states, ctx) { run(body: PNode[], states: State[], ctx: Ctx): State[] {
let cur = states; let cur = states;
for (const s of body) { for (const s of body) {
if (!cur.length) break; if (!cur.length) break;
const next = []; const next: State[] = [];
for (const st of cur) next.push(...this.stmt(s, st, ctx)); 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 (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 []; } if (this.deadline && Date.now() > this.deadline) { this.partial = true; return []; }
@@ -359,17 +477,17 @@ class Exec {
return cur; return cur;
} }
stmt(s, st, ctx) { stmt(s: PNode, st: State, ctx: Ctx): State[] {
switch (s.kind) { switch (s.kind) {
case 'Declare': { case 'Declare': {
const n = st.clone(); const n = st.clone();
for (const nm of s.names) { for (const nm of s.names) {
const k = s.resolved?.k; const k = s.resolved?.k;
let v = UNSET; let v: Val = UNSET;
if (k === 'LIST') v = app('LIST', [], 'list'); if (k === 'LIST') v = app('LIST', [], 'list');
else if (k === 'HASHMAP' || k === 'SET') v = app('EMPTY', [], k === 'SET' ? 'set' : 'map'); else if (k === 'HASHMAP' || k === 'SET') v = app('EMPTY', [], k === 'SET' ? 'set' : 'map');
else if (k === 'ARRAY') { 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'); v = app('NEWARRAY', [num(++arrayIds), ...dims], 'array');
if (dims.length) n.facts.push(cmp('>=', dims[0], num(0))); if (dims.length) n.facts.push(cmp('>=', dims[0], num(0)));
} else if (k === 'RECORD') v = this.fresh(nm.name, 'record'); } 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. */ /** 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; } if (target.kind === 'Name') { n.env.set(up(target.name), v); return; }
const root = rootName(target); const root = rootName(target);
const build = (t, value) => { const build = (t: PNode, value: Term): Term => {
if (t.kind === 'Name') return value; if (t.kind === 'Name') return value;
if (t.kind === 'Index') { if (t.kind === 'Index') {
const container = this.tr(t.target, n, []); 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; const tk = t.target.type?.k;
if (tk === 'HASHMAP') return build(t.target, app('MAPPUT', [container, idx[0], value], 'map')); if (tk === 'HASHMAP') return build(t.target, app('MAPPUT', [container, idx[0], value], 'map'));
if (idx.length === 2) { if (idx.length === 2) {
@@ -444,12 +562,12 @@ class Exec {
n.env.set(up(root), build(target, v)); n.env.set(up(root), build(target, v));
} }
builtin(s, st) { builtin(s: PNode, st: State): State {
const [first, ...rest] = s.args; const [first, ...rest]: PNode[] = s.args;
const vals = rest.map((a) => this.tr(a, st, [])); const vals: Term[] = rest.map((a) => this.tr(a, st, []));
const coll = this.tr(first, st, []); const coll = this.tr(first, st, []);
const n = st.clone(); const n = st.clone();
let nv; let nv: Term;
switch (s.name) { switch (s.name) {
case 'APPEND': nv = app('APPENDED', [coll, vals[0]], 'list'); break; case 'APPEND': nv = app('APPENDED', [coll, vals[0]], 'list'); break;
case 'ADD': nv = app('SETADD', [coll, vals[0]], 'set'); break; case 'ADD': nv = app('SETADD', [coll, vals[0]], 'set'); break;
@@ -473,18 +591,18 @@ class Exec {
return n; return n;
} }
procCall(s, st) { procCall(s: PNode, st: State): State {
const sub = s.sub; const sub = s.sub;
if (!sub) return st; if (!sub) return st;
const args = s.args.map((a) => this.tr(a, st, [])); const args: Term[] = s.args.map((a: PNode) => this.tr(a, st, []));
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]]));
for (const r of sub.requires) { 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.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, []); this.recursion(sub, s, args, st, []);
const n = st.clone(); const n = st.clone();
const after = new Map(paramEnv); 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') { if (p.mode === 'BYREF' && s.args[i].kind === 'Name') {
const fresh = this.fresh(s.args[i].name, sortOf(p.type)); const fresh = this.fresh(s.args[i].name, sortOf(p.type));
n.env.set(up(s.args[i].name), fresh); n.env.set(up(s.args[i].name), fresh);
@@ -495,13 +613,13 @@ class Exec {
return n; return n;
} }
ensure(at, st, value) { ensure(at: PNode, st: State, value: Term | null): void {
const u = this.unit; const u = this.unit;
if (!u.ensures?.length) return; if (!u.ensures?.length) return;
const paramEnv = new Map(); const paramEnv: Env = new Map();
for (const p of u.params || []) { for (const p of u.params || []) {
const k = up(p.name); 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) { for (const en of u.ensures) {
const goal = this.tr(en.expr, st, [], { paramEnv, result: value, oldEnv: this.entryEnv, spec: true }); 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) { ifStmt(s: PNode, st: State, ctx: Ctx): State[] {
const out = []; const out: State[] = [];
let rest = st; let rest = st;
for (let i = 0; i < s.branches.length; i++) { for (let i = 0; i < s.branches.length; i++) {
const b = s.branches[i]; const b = s.branches[i];
@@ -523,12 +641,12 @@ class Exec {
return out; 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 v = s.subject ? this.tr(s.subject, st, []) : this.fresh('case', 'any');
const out = []; const out: State[] = [];
let rest = st; let rest = st;
for (const arm of s.arms) { 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)); out.push(...this.run(arm.body, [rest.assume(c, `line ${arm.line}`)], ctx));
rest = rest.assume(not(c)); rest = rest.assume(not(c));
} }
@@ -540,29 +658,30 @@ class Exec {
/* ---------- loops ---------- */ /* ---------- loops ---------- */
/** The state at the top of a loop: changed variables become fresh symbols. */ /** The state at the top of a loop: changed variables become fresh symbols. */
havoc(st, modified, loopLine) { havoc(st: State, modified: Set<string>, loopLine: number | undefined): State {
const n = st.clone(); const n = st.clone();
for (const k of modified) { for (const k of modified) {
const old = st.env.get(k); 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 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); n.env.set(k, fresh);
// an ARRAY keeps its dimensions, however its contents change // 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}`); n.trail.push(`the top of the loop on line ${loopLine}`);
return n; 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); 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 a = this.tr(s.start, E, []);
const b = this.tr(s.stop, 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 I = up(s.var);
const modified = modifiedIn(s.body); const modified = modifiedIn(s.body);
modified.delete(I); modified.delete(I);
@@ -571,15 +690,15 @@ class Exec {
for (const inv of this.userInvariants(s, E, entryEnv)) { 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); 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; if (step === null) return TRUE;
// The counter never passes the stop by a whole step or more, unless the // 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. // 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))); 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))); 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 guardOf = (i: Term): Term => (step === null ? this.fresh('guard', 'bool') : step > 0 ? cmp('<', i, b) : cmp('>', i, b));
const makeHead = (extra) => { const makeHead = (extra: (h: State) => Term[]) => {
const H = this.havoc(E, modified, s.line); const H = this.havoc(E, modified, s.line);
const i = this.fresh(s.var, 'int'); const i = this.fresh(s.var, 'int');
H.env.set(I, i); H.env.set(I, i);
@@ -593,14 +712,14 @@ class Exec {
for (const inv of this.userInvariants(s, H)) H.facts.push(inv.term); for (const inv of this.userInvariants(s, H)) H.facts.push(inv.term);
return { H, i }; 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, { 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, makeHead, guardOf, advance, counter: I, start: a, step: step ?? 1,
}) : []; }) : [];
const { H, i } = makeHead((h) => cands.map((c) => c.at(h.env))); const { H, i } = makeHead((h) => cands.map((c) => c.at(h.env)));
const g = guardOf(i); 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); 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]) { for (const st of [...ends, ...inner.continues]) {
const n = advance(st, i); const n = advance(st, i);
@@ -616,7 +735,7 @@ class Exec {
return after; return after;
} }
forEach(s, E, ctx) { forEach(s: PNode, E: State, ctx: Ctx): State[] {
const coll = this.tr(s.iterable, E, []); const coll = this.tr(s.iterable, E, []);
const X = up(s.var); const X = up(s.var);
const modified = modifiedIn(s.body); const modified = modifiedIn(s.body);
@@ -633,7 +752,7 @@ class Exec {
let inPass = H; let inPass = H;
if (coll.k === 'app' && coll.f === 'RANGE') inPass = H.assume(and(cmp('<=', coll.args[0], x), cmp('<', x, coll.args[1]))); 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)); 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); const ends = this.run(s.body, [inPass], inner);
for (const st of [...ends, ...inner.continues]) { 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); 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; return out;
} }
whileStmt(s, E, ctx) { whileStmt(s: PNode, E: State, ctx: Ctx): State[] {
const modified = modifiedIn(s.body); 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); 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); const H = this.havoc(E, modified, s.line);
for (const f of extra(H)) H.facts.push(f); for (const f of extra(H)) H.facts.push(f);
for (const inv of this.userInvariants(s, H)) H.facts.push(inv.term); for (const inv of this.userInvariants(s, H)) H.facts.push(inv.term);
return { H }; 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, { 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 { H } = makeHead((h) => cands.map((c) => c.at(h.env)));
const g = this.tr(s.cond, H, []); 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 ends = this.run(s.body, [H.assume(g, `line ${s.line}: ${sourceOf(s.cond)}`)], inner);
const back = [...ends, ...inner.continues]; const back = [...ends, ...inner.continues];
for (const st of back) { 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]; 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); 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); 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); const H = this.havoc(E, modified, s.line);
for (const inv of this.userInvariants(s, H)) H.facts.push(inv.term); 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 ends = this.run(s.body, [H], inner);
const exits = []; const exits: State[] = [];
const again = []; const again: State[] = [];
for (const st of [...ends, ...inner.continues]) { for (const st of [...ends, ...inner.continues]) {
const c = s.cond ? this.tr(s.cond, st, []) : TRUE; const c = s.cond ? this.tr(s.cond, st, []) : TRUE;
exits.push(st.assume(c, `line ${s.endLine}: UNTIL ${sourceOf(s.cond)}`)); exits.push(st.assume(c, `line ${s.endLine}: UNTIL ${sourceOf(s.cond)}`));
@@ -687,7 +806,7 @@ class Exec {
return [...exits, ...inner.breaks]; return [...exits, ...inner.breaks];
} }
withQuiet(fn) { this.quiet = (this.quiet || 0) + 1; try { return fn(); } finally { this.quiet--; } } withQuiet<T>(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 * 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 * Without one, a WHILE loop gets a guess from its condition (N - I for
* I < N) that is kept only if both obligations prove. * 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) { if (s.decreases) {
const d0 = this.tr(s.decreases.expr, H, [], { spec: true }); 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))); 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; if (!needed || s.kind === 'For' || !this.recording) return;
// guess a measure from the condition // guess a measure from the condition
const guesses = []; const guesses: PNode[] = [];
const conds = s.cond ? conjuncts(s.cond) : []; const conds = s.cond ? conjuncts(s.cond) : [];
for (const c of conds) { for (const c of conds) {
if (c.kind !== 'Binary') continue; if (c.kind !== 'Binary') continue;
@@ -723,7 +842,7 @@ class Exec {
const okBound = prove([...H.facts, guard], cmp('>=', d0, num(0))).status === 'proved'; 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'); const okStep = okBound && backStates.every((st) => prove(st.facts, cmp('<', this.withQuiet(() => this.tr(gs, st, [], { spec: true })), d0)).status === 'proved');
if (okBound && okStep) { 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) }); this.obligation('terminates', s, `the ${s.kind === 'While' ? 'WHILE' : 'REPEAT'} loop on line ${s.line} ends`, H, [], TRUE, { measure: sourceOf(gs) });
return; return;
} }
@@ -739,29 +858,30 @@ class Exec {
* left survives. What is left is proved, and the loop's real analysis * left survives. What is left is proved, and the loop's real analysis
* assumes it. * assumes it.
*/ */
infer(s, E, modified, h) { infer(s: PNode, E: State, modified: Set<string>, h: InferHooks): Cand[] {
if (this.depth > 2) return []; if (this.depth > 2) return [];
const cands = []; const cands: Cand[] = [];
const entry = h.entryEnv(E.env); const entry = h.entryEnv(E.env);
const counter = h.counter; const counter = h.counter;
const startTerm = h.start; const startTerm = h.start ?? num(0);
const loopLine = s.line; const loopLine = s.line;
for (const k of modified) { for (const k of modified) {
const v0 = E.env.get(k); const v0 = E.env.get(k);
const nm = [...(this.unit.symbols || [])].find((x) => up(x.name) === k)?.name || k; const nm = [...(this.unit.symbols || [])].find((x) => up(x.name) === k)?.name || k;
if (!v0 || v0 === UNSET) continue; if (!v0 || v0 === UNSET) continue;
if (!isSet(v0)) continue;
const t = v0.t; const t = v0.t;
if (numeric(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('>=', valOf(env, k), v0) });
cands.push({ text: `${nm} <= ${show(v0)}`, at: (env) => cmp('<=', env.get(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('<=', env.get(k), add(v0, sub(env.get(counter), startTerm))) }); 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') { 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) { if (counter) {
const passes = (env) => (h.step < 0 ? sub(startTerm, env.get(counter)) : sub(env.get(counter), startTerm)); 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(env.get(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))) });
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(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') { if (l.kind === 'Name' && modified.has(up(l.name)) && l.type?.k === 'INTEGER') {
const op = c.op === '<' ? '<=' : c.op === '>' ? '>=' : c.op; const op = c.op === '<' ? '<=' : c.op === '>' ? '>=' : c.op;
const extra = c.op === '<=' ? 1 : c.op === '>=' ? -1 : 0; 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 []; if (!cands.length) return [];
let lastHead = null; let lastHead: State | null = null;
let live = cands.filter((c) => { let live = cands.filter((c) => {
try { return prove(E.facts, c.at(entry)).status === 'proved'; } catch { return false; } 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))); const { H, i } = h.makeHead((hh) => live.map((c) => c.at(hh.env)));
lastHead = H; lastHead = H;
let start = 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)); else if (h.whileGuard) start = H.assume(h.whileGuard(H));
const inner = { breaks: [], continues: [] }; 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) => { const keep = live.filter((c) => ends.every((st) => {
try { return prove(st.facts, c.at(st.env)).status === 'proved'; } catch { return false; } 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 env = lastHead ? lastHead.env : entry;
const texts = live.filter((c) => { try { return prove([], c.at(env)).status !== 'proved'; } catch { return true; } }) 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; } }); .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; return live;
} }
/* ---------- a whole unit ---------- */ /* ---------- a whole unit ---------- */
runUnit() { runUnit(): void {
const u = this.unit; const u = this.unit;
const st = new State(); const st = new State();
this.entryEnv = new Map(); 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 })); 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: [] }); 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) return [];
if (e.kind === 'Binary' && e.op === 'AND') return [...conjuncts(e.left), ...conjuncts(e.right)]; if (e.kind === 'Binary' && e.op === 'AND') return [...conjuncts(e.left), ...conjuncts(e.right)];
return [e]; 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); 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); 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 === 'NEWARRAY') return x.args[2] || num(0);
if (x.k === 'app' && x.f === 'STORE2') return columns(x.args[0]); if (x.k === 'app' && x.f === 'STORE2') return columns(x.args[0]);
return app('COLUMNS', [x], 'int'); 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. */ /** 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 want = new Set(symsOf(goal).keys());
const chosen = new Set(); const chosen = new Set<number>();
for (let round = 0; round < 3; round++) { for (let round = 0; round < 3; round++) {
let grew = false; let grew = false;
hyps.forEach((h, i) => { 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, ... */ /** Display names: the newest version of I prints as I, older ones as I0, I1, ... */
function namesFor(terms) { function namesFor(terms: Term[]): Map<string, string> {
const all = new Map(); const all = new Map<string, import('./logic.js').Sym>();
for (const t of terms) symsOf(t, all); for (const t of terms) symsOf(t, all);
const byName = new Map(); const byName = new Map<string, Array<import('./logic.js').Sym>>();
for (const s of all.values()) { if (!byName.has(s.name)) byName.set(s.name, []); byName.get(s.name).push(s); } 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(); const names = new Map<string, string>();
for (const [n, list] of byName) { for (const [n, list] of byName) {
list.sort((a, b) => a.id - b.id); list.sort((a, b) => a.id - b.id);
list.forEach((s, i) => names.set(key(s), i === list.length - 1 ? n : `${n}${'₀₁₂₃₄₅₆₇₈₉'[i] || i}`)); 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; 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); const ex = new Exec(program, unit, options);
ex.deadline = Date.now() + (options.budgetMs ?? 4000); 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. // 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 // 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. // (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.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.' }); 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<string, Group>();
for (const o of ex.raw) { for (const o of ex.raw) {
const k = `${o.kind}@${o.line}:${o.col}@${o.label}`; 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 }); 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()) { for (const gr of groups.values()) {
let status = 'proved'; let status: 'proved' | 'unknown' = 'proved';
let failing = null; let failing: RawOb | null = null;
if (gr.needsMeasure) { status = 'unknown'; failing = gr.instances[0]; } if (gr.needsMeasure) { status = 'unknown'; failing = gr.instances[0]; }
else { else {
for (const inst of gr.instances) { 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; } if (Date.now() > ex.deadline + 2000) { status = 'unknown'; failing = inst; inst.reason = 'the checker ran out of time'; break; }
let r; let r: import('./solver.js').ProveResult;
try { r = prove(inst.hyps, inst.goal); } catch (err) { r = { status: 'unknown', reason: err.message }; } 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; inst.status = r.status;
if (r.status !== 'proved') { status = 'unknown'; failing = inst; inst.reason = r.reason; inst.witness = r.witness; break; } if (r.status !== 'proved') { status = 'unknown'; failing = inst; inst.reason = r.reason; inst.witness = r.witness; break; }
} }
} }
const shownInst = failing || gr.instances[0]; const shownInst = failing || gr.instances[0];
let shown = null; let shown: Obligation['shown'] = null;
if (shownInst && shownInst.goal) { if (shownInst && shownInst.goal) {
const facts = relevantFacts(shownInst.hyps, shownInst.goal); const facts = relevantFacts(shownInst.hyps, shownInst.goal);
const names = namesFor([...facts, 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 }; 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)); 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 }; 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']; 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 = {}) { export function verify(program: Program, options: VerifyOptions = {}): Report {
const units = []; const units: UnitReport[] = [];
for (const sub of program.subs.values()) { 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)); 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 } }; 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<string, string> = {
index: 'Position exists', index: 'Position exists',
key: 'Key present', key: 'Key present',
slice: 'Slice in range', slice: 'Slice in range',