Convert the prover's term language and solver to TypeScript

This repository now owns the engines, and the next stages extend the prover
(a claims model, translation to Dafny and Lean, precision claims). Doing that
under strict mode needs the terms it reasons about to have types.

logic.ts gives the term language a discriminated union (Num, Lit, Sym, Bv,
Op, And, Or, Not, Cmp, Ite, App, Quant, QuantC) and types every
constructor, rewrite and printer. solver.ts types the rationals, linear
constraints, Fourier-Motzkin, union-find with congruence, the case split
and quantifier instantiation, and exports ProveResult and ProveOptions.
Walks that looked inside any kind of term through x[k] now go through a
small fields() helper that keeps the same order.

The behavior is unchanged: every obligation of every exercise, corpus
program, lesson solution and example, and the regression programs, comes
out byte for byte the same as before the conversion (kind, line, column,
label, status, paths, goal and facts as shown, inferred invariants, notes).
The few places where the JavaScript would have thrown on a null it never
receives (an identity for a quantifier that has one) now skip instead.

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:24:09 +00:00
1 parent ee44a03c54
commit f219384e57
2 files changed
+230 -165

No files matched your search

@@ -24,11 +24,40 @@
import { typeName } from './lang.js'; import { typeName } from './lang.js';
/* ------------------------------------------------------------------ */
/* The term language, as types */
/* ------------------------------------------------------------------ */
/** A term's sort: 'int', 'float', 'char', 'string', 'bool', 'list', 'array', 'map', 'set', 'record' or 'any'. */
export type Sort = string;
export type CmpOp = '==' | '!=' | '<' | '<=' | '>' | '>=';
export interface Num { k: 'num'; v: number; t: Sort }
export interface Lit { k: 'lit'; v: string | boolean; t: Sort }
export interface Sym { k: 'sym'; name: string; id: number; t: Sort }
export interface Bv { k: 'bv'; name: string; t: Sort }
export interface Op { k: 'op'; op: string; args: Term[]; t: Sort }
export interface And { k: 'and'; args: Term[]; t: 'bool' }
export interface Or { k: 'or'; args: Term[]; t: 'bool' }
export interface Not { k: 'not'; a: Term; t: 'bool' }
export interface Cmp { k: 'cmp'; op: CmpOp; a: Term; b: Term; t: 'bool' }
export interface Ite { k: 'ite'; c: Term; a: Term; b: Term; t: Sort }
export interface App { k: 'app'; f: string; args: Term[]; t: Sort }
/** A quantifier over the range [lo, hi). */
export interface Quant { k: 'q'; q: string; v: string; lo: Term; hi: Term; body: Term; t: Sort }
/** A quantifier over a collection; opaque to the solver. */
export interface QuantC { k: 'qc'; q: string; v: string; dom: Term; body: Term; t: Sort }
export type Term = Num | Lit | Sym | Bv | Op | And | Or | Not | Cmp | Ite | App | Quant | QuantC;
/** A type as the parser writes it: `{ k: 'INTEGER' }`, `{ k: 'LIST', of: ... }`. */
export interface TypeLike { k: string }
/* ------------------------------------------------------------------ */ /* ------------------------------------------------------------------ */
/* Types */ /* Types */
/* ------------------------------------------------------------------ */ /* ------------------------------------------------------------------ */
export function sortOf(type) { export function sortOf(type: TypeLike | null | undefined): Sort {
if (!type) return 'any'; if (!type) return 'any';
switch (type.k) { switch (type.k) {
case 'INTEGER': return 'int'; case 'INTEGER': return 'int';
@@ -44,48 +73,48 @@ export function sortOf(type) {
default: return 'any'; default: return 'any';
} }
} }
export const numeric = (t) => t === 'int' || t === 'float'; export const numeric = (t: Sort | undefined): boolean => t === 'int' || t === 'float';
export const isNum = (x) => numeric(x.t); export const isNum = (x: Term): boolean => numeric(x.t);
/* ------------------------------------------------------------------ */ /* ------------------------------------------------------------------ */
/* Constructors, simplifying as they go */ /* Constructors, simplifying as they go */
/* ------------------------------------------------------------------ */ /* ------------------------------------------------------------------ */
export const TRUE = { k: 'lit', v: true, t: 'bool' }; export const TRUE: Lit = { k: 'lit', v: true, t: 'bool' };
export const FALSE = { k: 'lit', v: false, t: 'bool' }; export const FALSE: Lit = { k: 'lit', v: false, t: 'bool' };
export const num = (v, t) => ({ k: 'num', v, t: t || (Number.isInteger(v) ? 'int' : 'float') }); export const num = (v: number, t?: Sort): Num => ({ k: 'num', v, t: t || (Number.isInteger(v) ? 'int' : 'float') });
export const lit = (v, t) => ({ k: 'lit', v, t }); export const lit = (v: string | boolean, t: Sort): Lit => ({ k: 'lit', v, t });
let symIds = 0; let symIds = 0;
export const sym = (name, t, info = {}) => ({ k: 'sym', name, id: ++symIds, t, ...info }); export const sym = (name: string, t: Sort): Sym => ({ k: 'sym', name, id: ++symIds, t });
export const bv = (name, t) => ({ k: 'bv', name, t }); export const bv = (name: string, t: Sort): Bv => ({ k: 'bv', name, t });
const isConst = (x) => x.k === 'num'; const isConst = (x: Term): x is Num => x.k === 'num';
const isTrue = (x) => x.k === 'lit' && x.v === true; const isTrue = (x: Term): boolean => x.k === 'lit' && x.v === true;
const isFalse = (x) => x.k === 'lit' && x.v === false; const isFalse = (x: Term): boolean => x.k === 'lit' && x.v === false;
export function numType(a, b) { return a.t === 'float' || b?.t === 'float' ? 'float' : 'int'; } export function numType(a: Term, b?: Term | null): Sort { return a.t === 'float' || b?.t === 'float' ? 'float' : 'int'; }
export function add(a, b) { export function add(a: Term, b: Term): Term {
if (isConst(a) && isConst(b)) return num(a.v + b.v, numType(a, b)); if (isConst(a) && isConst(b)) return num(a.v + b.v, numType(a, b));
if (isConst(a) && a.v === 0) return b; if (isConst(a) && a.v === 0) return b;
if (isConst(b) && b.v === 0) return a; if (isConst(b) && b.v === 0) return a;
return { k: 'op', op: '+', args: [a, b], t: numType(a, b) }; return { k: 'op', op: '+', args: [a, b], t: numType(a, b) };
} }
export function sub(a, b) { export function sub(a: Term, b: Term): Term {
if (isConst(a) && isConst(b)) return num(a.v - b.v, numType(a, b)); if (isConst(a) && isConst(b)) return num(a.v - b.v, numType(a, b));
if (isConst(b) && b.v === 0) return a; if (isConst(b) && b.v === 0) return a;
if (key(a) === key(b)) return num(0, numType(a, b)); if (key(a) === key(b)) return num(0, numType(a, b));
return { k: 'op', op: '-', args: [a, b], t: numType(a, b) }; return { k: 'op', op: '-', args: [a, b], t: numType(a, b) };
} }
export function mul(a, b) { export function mul(a: Term, b: Term): Term {
if (isConst(a) && isConst(b)) return num(a.v * b.v, numType(a, b)); if (isConst(a) && isConst(b)) return num(a.v * b.v, numType(a, b));
if ((isConst(a) && a.v === 0) || (isConst(b) && b.v === 0)) return num(0, numType(a, b)); if ((isConst(a) && a.v === 0) || (isConst(b) && b.v === 0)) return num(0, numType(a, b));
if (isConst(a) && a.v === 1) return b; if (isConst(a) && a.v === 1) return b;
if (isConst(b) && b.v === 1) return a; if (isConst(b) && b.v === 1) return a;
return { k: 'op', op: '*', args: [a, b], t: numType(a, b) }; return { k: 'op', op: '*', args: [a, b], t: numType(a, b) };
} }
export function neg(a) { return isConst(a) ? num(-a.v, a.t) : { k: 'op', op: 'neg', args: [a], t: a.t }; } export function neg(a: Term): Term { return isConst(a) ? num(-a.v, a.t) : { k: 'op', op: 'neg', args: [a], t: a.t }; }
export function arith(op, a, b, t) { export function arith(op: string, a: Term, b: Term, t?: Sort): Term {
switch (op) { switch (op) {
case '+': return add(a, b); case '+': return add(a, b);
case '-': return sub(a, b); case '-': return sub(a, b);
@@ -111,8 +140,8 @@ export function arith(op, a, b, t) {
} }
} }
export function and(...xs) { export function and(...xs: Array<Term | Term[] | null | undefined | false>): Term {
const out = []; const out: Term[] = [];
for (const x of xs.flat()) { for (const x of xs.flat()) {
if (!x || isTrue(x)) continue; if (!x || isTrue(x)) continue;
if (isFalse(x)) return FALSE; if (isFalse(x)) return FALSE;
@@ -121,8 +150,8 @@ export function and(...xs) {
if (!out.length) return TRUE; if (!out.length) return TRUE;
return out.length === 1 ? out[0] : { k: 'and', args: out, t: 'bool' }; return out.length === 1 ? out[0] : { k: 'and', args: out, t: 'bool' };
} }
export function or(...xs) { export function or(...xs: Array<Term | Term[] | null | undefined | false>): Term {
const out = []; const out: Term[] = [];
for (const x of xs.flat()) { for (const x of xs.flat()) {
if (!x || isFalse(x)) continue; if (!x || isFalse(x)) continue;
if (isTrue(x)) return TRUE; if (isTrue(x)) return TRUE;
@@ -131,17 +160,17 @@ export function or(...xs) {
if (!out.length) return FALSE; if (!out.length) return FALSE;
return out.length === 1 ? out[0] : { k: 'or', args: out, t: 'bool' }; return out.length === 1 ? out[0] : { k: 'or', args: out, t: 'bool' };
} }
const FLIP = { '==': '!=', '!=': '==', '<': '>=', '<=': '>', '>': '<=', '>=': '<' }; const FLIP: Record<CmpOp, CmpOp> = { '==': '!=', '!=': '==', '<': '>=', '<=': '>', '>': '<=', '>=': '<' };
export function not(a) { export function not(a: Term): Term {
if (isTrue(a)) return FALSE; if (isTrue(a)) return FALSE;
if (isFalse(a)) return TRUE; if (isFalse(a)) return TRUE;
if (a.k === 'not') return a.a; if (a.k === 'not') return a.a;
if (a.k === 'cmp' && (numeric(a.a.t) || a.op === '==' || a.op === '!=')) return cmp(FLIP[a.op], a.a, a.b); if (a.k === 'cmp' && (numeric(a.a.t) || a.op === '==' || a.op === '!=')) return cmp(FLIP[a.op], a.a, a.b);
return { k: 'not', a, t: 'bool' }; return { k: 'not', a, t: 'bool' };
} }
export function implies(a, b) { return or(not(a), b); } export function implies(a: Term, b: Term): Term { return or(not(a), b); }
export function cmp(op, a, b) { export function cmp(op: CmpOp, a: Term, b: Term): Term {
if (isConst(a) && isConst(b)) return evalCmp(op, a.v, b.v) ? TRUE : FALSE; if (isConst(a) && isConst(b)) return evalCmp(op, a.v, b.v) ? TRUE : FALSE;
if (a.k === 'lit' && b.k === 'lit' && (op === '==' || op === '!=')) return (a.v === b.v) === (op === '==') ? TRUE : FALSE; if (a.k === 'lit' && b.k === 'lit' && (op === '==' || op === '!=')) return (a.v === b.v) === (op === '==') ? TRUE : FALSE;
if ((op === '==' || op === '!=') && key(a) === key(b)) return op === '==' ? TRUE : FALSE; if ((op === '==' || op === '!=') && key(a) === key(b)) return op === '==' ? TRUE : FALSE;
@@ -159,16 +188,16 @@ export function cmp(op, a, b) {
} }
return { k: 'cmp', op, a, b, t: 'bool' }; return { k: 'cmp', op, a, b, t: 'bool' };
} }
function evalCmp(op, x, y) { function evalCmp(op: CmpOp, x: number, y: number): boolean {
switch (op) { case '==': return x === y; case '!=': return x !== y; case '<': return x < y; case '<=': return x <= y; case '>': return x > y; default: return x >= y; } switch (op) { case '==': return x === y; case '!=': return x !== y; case '<': return x < y; case '<=': return x <= y; case '>': return x > y; default: return x >= y; }
} }
/** Two lists are equal when they have the same length and the same values in order. */ /** Two lists are equal when they have the same length and the same values in order. */
function listEquality(a, b) { function listEquality(a: Term, b: Term): Term | null {
const asList = (x) => (x.k === 'app' && x.f === 'LIST' ? x.args : null); const asList = (x: Term): Term[] | null => (x.k === 'app' && x.f === 'LIST' ? x.args : null);
const la = asList(a); const lb = asList(b); const la = asList(a); const lb = asList(b);
if (la && lb) return la.length !== lb.length ? FALSE : and(la.map((x, i) => cmp('==', x, lb[i]))); if (la && lb) return la.length !== lb.length ? FALSE : and(la.map((x, i) => cmp('==', x, lb[i])));
const ap = (x) => (x.k === 'app' && x.f === 'APPENDED' ? x : null); const ap = (x: Term): App | null => (x.k === 'app' && x.f === 'APPENDED' ? x : null);
const pa = ap(a); const pb = ap(b); const pa = ap(a); const pb = ap(b);
if (pa && pb) return and(cmp('==', pa.args[0], pb.args[0]), cmp('==', pa.args[1], pb.args[1])); if (pa && pb) return and(cmp('==', pa.args[0], pb.args[0]), cmp('==', pa.args[1], pb.args[1]));
if ((pa && la && !la.length) || (pb && lb && !lb.length)) return FALSE; if ((pa && la && !la.length) || (pb && lb && !lb.length)) return FALSE;
@@ -177,7 +206,7 @@ function listEquality(a, b) {
return null; return null;
} }
export function ite(c, a, b) { export function ite(c: Term, a: Term, b: Term): Term {
if (isTrue(c)) return a; if (isTrue(c)) return a;
if (isFalse(c)) return b; if (isFalse(c)) return b;
if (key(a) === key(b)) return a; if (key(a) === key(b)) return a;
@@ -185,24 +214,24 @@ export function ite(c, a, b) {
return { k: 'ite', c, a, b, t: a.t }; return { k: 'ite', c, a, b, t: a.t };
} }
export function app(f, args, t) { return { k: 'app', f, args, t }; } export function app(f: string, args: Term[], t: Sort): App { return { k: 'app', f, args, t }; }
/** X[I], looking through APPENDED and STORE to the value actually there. */ /** X[I], looking through APPENDED and STORE to the value actually there. */
export function at(x, i, t) { export function at(x: Term, i: Term, t: Sort): Term {
if (x.k === 'app' && x.f === 'APPENDED') return ite(cmp('==', i, length(x.args[0])), x.args[1], at(x.args[0], i, t)); if (x.k === 'app' && x.f === 'APPENDED') return ite(cmp('==', i, length(x.args[0])), x.args[1], at(x.args[0], i, t));
if (x.k === 'app' && x.f === 'STORE') return ite(cmp('==', i, x.args[1]), x.args[2], at(x.args[0], i, t)); if (x.k === 'app' && x.f === 'STORE') return ite(cmp('==', i, x.args[1]), x.args[2], at(x.args[0], i, t));
if (x.k === 'app' && x.f === 'MAPPUT') return ite(cmp('==', i, x.args[1]), x.args[2], at(x.args[0], i, t)); if (x.k === 'app' && x.f === 'MAPPUT') return ite(cmp('==', i, x.args[1]), x.args[2], at(x.args[0], i, t));
if (x.k === 'app' && x.f === 'LIST' && isConst(i) && i.v >= 0 && i.v < x.args.length) return x.args[i.v]; if (x.k === 'app' && x.f === 'LIST' && isConst(i) && i.v >= 0 && i.v < x.args.length) return x.args[i.v];
if (x.k === 'lit' && x.t === 'string' && isConst(i)) { const cs = Array.from(x.v); if (i.v >= 0 && i.v < cs.length) return lit(cs[i.v], 'char'); } if (x.k === 'lit' && x.t === 'string' && isConst(i)) { const cs = Array.from(String(x.v)); if (i.v >= 0 && i.v < cs.length) return lit(cs[i.v], 'char'); }
if (x.k === 'app' && x.f === 'SLICE') return at(x.args[0], add(x.args[1], i), t); if (x.k === 'app' && x.f === 'SLICE') return at(x.args[0], add(x.args[1], i), t);
return app('AT', [x, i], t); return app('AT', [x, i], t);
} }
export function at2(x, r, c, t) { export function at2(x: Term, r: Term, c: Term, t: Sort): Term {
if (x.k === 'app' && x.f === 'STORE2') return ite(and(cmp('==', r, x.args[1]), cmp('==', c, x.args[2])), x.args[3], at2(x.args[0], r, c, t)); if (x.k === 'app' && x.f === 'STORE2') return ite(and(cmp('==', r, x.args[1]), cmp('==', c, x.args[2])), x.args[3], at2(x.args[0], r, c, t));
return app('AT2', [x, r, c], t); return app('AT2', [x, r, c], t);
} }
export function length(x) { export function length(x: Term): Term {
if (x.k === 'app') { if (x.k === 'app') {
switch (x.f) { switch (x.f) {
case 'APPENDED': return add(length(x.args[0]), num(1)); case 'APPENDED': return add(length(x.args[0]), num(1));
@@ -215,7 +244,7 @@ export function length(x) {
default: break; default: break;
} }
} }
if (x.k === 'lit' && x.t === 'string') return num(Array.from(x.v).length); if (x.k === 'lit' && x.t === 'string') return num(Array.from(String(x.v)).length);
if (x.k === 'op' && x.op === '&') return add(length(x.args[0]), length(x.args[1])); if (x.k === 'op' && x.op === '&') return add(length(x.args[0]), length(x.args[1]));
if (x.t === 'char') return num(1); if (x.t === 'char') return num(1);
if (x.k === 'q' && x.q === 'SETOF') return { k: 'q', q: 'SIZE', v: x.v, lo: x.lo, hi: x.hi, body: x.body, t: 'int' }; if (x.k === 'q' && x.q === 'SETOF') return { k: 'q', q: 'SIZE', v: x.v, lo: x.lo, hi: x.hi, body: x.body, t: 'int' };
@@ -224,7 +253,7 @@ export function length(x) {
} }
/** X IN S, unfolded wherever S's shape allows. */ /** X IN S, unfolded wherever S's shape allows. */
export function member(x, s) { export function member(x: Term, s: Term): Term {
if (s.k === 'q' && s.q === 'SETOF') return and(cmp('<=', s.lo, x), cmp('<', x, s.hi), substBound(s.body, s.v, x)); if (s.k === 'q' && s.q === 'SETOF') return and(cmp('<=', s.lo, x), cmp('<', x, s.hi), substBound(s.body, s.v, x));
if (s.k === 'app' && (s.f === 'SET' || s.f === 'LIST')) return or(s.args.map((y) => cmp('==', x, y))); if (s.k === 'app' && (s.f === 'SET' || s.f === 'LIST')) return or(s.args.map((y) => cmp('==', x, y)));
if (s.k === 'app' && (s.f === 'SETADD' || s.f === 'APPENDED')) return or(cmp('==', x, s.args[1]), member(x, s.args[0])); if (s.k === 'app' && (s.f === 'SETADD' || s.f === 'APPENDED')) return or(cmp('==', x, s.args[1]), member(x, s.args[0]));
@@ -239,8 +268,8 @@ export function member(x, s) {
/* Keys: one string per term, equal for equal terms */ /* Keys: one string per term, equal for equal terms */
/* ------------------------------------------------------------------ */ /* ------------------------------------------------------------------ */
const KEY = new WeakMap(); const KEY = new WeakMap<object, string>();
export function key(x) { export function key(x: Term | null | undefined): string {
if (!x || typeof x !== 'object') return String(x); if (!x || typeof x !== 'object') return String(x);
const hit = KEY.get(x); const hit = KEY.get(x);
if (hit) return hit; if (hit) return hit;
@@ -248,7 +277,7 @@ export function key(x) {
KEY.set(x, k); KEY.set(x, k);
return k; return k;
} }
function keyOf(x, bound) { function keyOf(x: Term, bound: string[]): string {
switch (x.k) { switch (x.k) {
case 'num': return `${x.v}`; case 'num': return `${x.v}`;
case 'lit': return x.t === 'bool' ? (x.v ? 'TRUE' : 'FALSE') : `${x.t}:${JSON.stringify(x.v)}`; case 'lit': return x.t === 'bool' ? (x.v ? 'TRUE' : 'FALSE') : `${x.t}:${JSON.stringify(x.v)}`;
@@ -266,25 +295,27 @@ function keyOf(x, bound) {
} }
} }
/** The body of a quantifier, keyed so that renaming its variable changes nothing. */ /** The body of a quantifier, keyed so that renaming its variable changes nothing. */
export function bodyKey(q) { return keyOf(q.body, [q.v]); } export function bodyKey(q: Quant | QuantC): string { return keyOf(q.body, [q.v]); }
/* ------------------------------------------------------------------ */ /* ------------------------------------------------------------------ */
/* Substitution */ /* Substitution */
/* ------------------------------------------------------------------ */ /* ------------------------------------------------------------------ */
/** Replace a quantifier's variable with a term throughout its body. */ /** Replace a quantifier's variable with a term throughout its body. */
export function substBound(body, name, value) { export function substBound(body: Term, name: string, value: Term): Term {
return rebuild(body, (x, depthNames) => (x.k === 'bv' && x.name === name && !depthNames.includes(name) ? value : null), []); return rebuild(body, (x, depthNames) => (x.k === 'bv' && x.name === name && !depthNames.includes(name) ? value : null), []);
} }
/** Replace symbols, by key, throughout a term. */ /** Replace symbols, by key, throughout a term. */
export function substSyms(t, map) { export function substSyms(t: Term, map: Map<string, Term>): Term {
if (!map.size) return t; if (!map.size) return t;
return rebuild(t, (x) => (x.k === 'sym' && map.has(key(x)) ? map.get(key(x)) : null), []); return rebuild(t, (x) => (x.k === 'sym' && map.has(key(x)) ? map.get(key(x)) : null), []);
} }
/** Rebuild a term bottom-up through the smart constructors, so rewrites cascade. */ /** Rebuild a term bottom-up through the smart constructors, so rewrites cascade. */
export function rebuild(x, fn, shadow = []) { /** A rewrite step: a replacement for a term, or null to keep rebuilding below it. */
export type Rewrite = (x: Term, shadow: string[]) => Term | null | undefined;
export function rebuild(x: Term, fn: Rewrite, shadow: string[] = []): Term {
const r = fn(x, shadow); const r = fn(x, shadow);
if (r) return r; if (r) return r;
switch (x.k) { switch (x.k) {
@@ -318,13 +349,14 @@ export function rebuild(x, fn, shadow = []) {
} }
/** A quantifier over [lo, hi), folded when the range is empty or a single position. */ /** A quantifier over [lo, hi), folded when the range is empty or a single position. */
export function mkq(q, v, lo, hi, body, t) { export function mkq(q: string, v: string, lo: Term, hi: Term, body: Term, t: Sort): Term {
const span = constDiff(hi, lo); const span = constDiff(hi, lo);
if (span !== null && span <= 0) return identity(q, t); // Every quantifier mkq is given has an identity; an unknown one stays unfolded, which is still right.
if (span !== null && span <= 0) return identity(q, t) ?? { k: 'q', q, v, lo, hi, body, t };
return { k: 'q', q, v, lo, hi, body, t }; return { k: 'q', q, v, lo, hi, body, t };
} }
export function identity(q, t) { export function identity(q: string, t: Sort): Term | null {
switch (q) { switch (q) {
case 'SIZE': return num(0); case 'SIZE': return num(0);
case 'SUM': return num(0, t === 'float' ? 'float' : 'int'); case 'SUM': return num(0, t === 'float' ? 'float' : 'int');
@@ -337,7 +369,7 @@ export function identity(q, t) {
} }
/** Add one more position, h, to a quantifier's range: the step that makes induction work. */ /** Add one more position, h, to a quantifier's range: the step that makes induction work. */
export function extend(q, prev, h) { export function extend(q: Quant, prev: Term, h: Term): Term | null {
const b = substBound(q.body, q.v, h); const b = substBound(q.body, q.v, h);
switch (q.q) { switch (q.q) {
case 'SIZE': return add(prev, ite(b, num(1), num(0))); case 'SIZE': return add(prev, ite(b, num(1), num(0)));
@@ -354,7 +386,7 @@ export function extend(q, prev, h) {
/* ------------------------------------------------------------------ */ /* ------------------------------------------------------------------ */
/** a - b as a constant, when the difference is a plain number. */ /** a - b as a constant, when the difference is a plain number. */
export function constDiff(a, b) { export function constDiff(a: Term, b: Term): number | null {
const la = linear(a); const lb = linear(b); const la = linear(a); const lb = linear(b);
if (!la || !lb) return null; if (!la || !lb) return null;
const keys = new Set([...la.terms.keys(), ...lb.terms.keys()]); const keys = new Set([...la.terms.keys(), ...lb.terms.keys()]);
@@ -363,11 +395,11 @@ export function constDiff(a, b) {
} }
/** A term as sum(coefficient * atom) + constant, with number coefficients. */ /** A term as sum(coefficient * atom) + constant, with number coefficients. */
export function linear(x) { export function linear(x: Term): { terms: Map<string, number>; c: number } | null {
const terms = new Map(); const terms = new Map<string, number>();
let c = 0; let c = 0;
let ok = true; let ok = true;
const visit = (t, m) => { const visit = (t: Term, m: number): void => {
if (!ok) return; if (!ok) return;
if (t.k === 'num') { c += m * t.v; return; } if (t.k === 'num') { c += m * t.v; return; }
if (t.k === 'op' && t.op === '+') { visit(t.args[0], m); visit(t.args[1], m); return; } if (t.k === 'op' && t.op === '+') { visit(t.args[0], m); visit(t.args[1], m); return; }
@@ -392,8 +424,8 @@ export function linear(x) {
* Print a term the way a student would write it. `names` maps a symbol's * Print a term the way a student would write it. `names` maps a symbol's
* key to its display name, so that two versions of I can read as I and I'. * key to its display name, so that two versions of I can read as I and I'.
*/ */
export function show(x, names = new Map(), prec = 0) { export function show(x: Term, names: Map<string, string> = new Map(), prec = 0): string {
const p = (inner, level) => (level < prec ? `(${inner})` : inner); const p = (inner: string, level: number): string => (level < prec ? `(${inner})` : inner);
switch (x.k) { switch (x.k) {
case 'num': return x.t === 'float' && Number.isInteger(x.v) ? `${x.v}.0` : String(x.v); case 'num': return x.t === 'float' && Number.isInteger(x.v) ? `${x.v}.0` : String(x.v);
case 'lit': case 'lit':
@@ -433,10 +465,10 @@ export function show(x, names = new Map(), prec = 0) {
} }
} }
function showApp(x, names, p) { function showApp(x: App, names: Map<string, string>, p: (inner: string, level: number) => string): string {
if (/^FLOAT[-+*/^]$/.test(x.f)) { if (/^FLOAT[-+*/^]$/.test(x.f)) {
const op = x.f.slice(5); const op = x.f.slice(5);
const lv = { '+': 6, '-': 6, '*': 7, '/': 7, '^': 9 }[op]; const lv = ({ '+': 6, '-': 6, '*': 7, '/': 7, '^': 9 } as Record<string, number>)[op] ?? 7;
return p(`${show(x.args[0], names, lv)} ${op} ${show(x.args[1], names, lv + (op === '^' ? 0 : 1))}`, lv); return p(`${show(x.args[0], names, lv)} ${op} ${show(x.args[1], names, lv + (op === '^' ? 0 : 1))}`, lv);
} }
const a = x.args.map((y) => show(y, names)); const a = x.args.map((y) => show(y, names));
@@ -466,12 +498,13 @@ function showApp(x, names, p) {
} }
/** Every symbol a term mentions. */ /** Every symbol a term mentions. */
export function symsOf(x, out = new Map()) { export function symsOf(x: Term | null | undefined, out: Map<string, Sym> = new Map()): Map<string, Sym> {
if (!x || typeof x !== 'object') return out; if (!x || typeof x !== 'object') return out;
if (x.k === 'sym') { out.set(key(x), x); return out; } if (x.k === 'sym') { out.set(key(x), x); return out; }
for (const k of ['a', 'b', 'c', 'lo', 'hi', 'body', 'dom']) if (x[k]) symsOf(x[k], out); const r = x as unknown as Record<string, unknown>;
if (x.args) for (const y of x.args) symsOf(y, out); for (const k of ['a', 'b', 'c', 'lo', 'hi', 'body', 'dom']) if (r[k] && typeof r[k] === 'object') symsOf(r[k] as Term, out);
if ('args' in x) for (const y of x.args) symsOf(y, out);
return out; return out;
} }
export function describeSort(t) { return typeName({ k: { int: 'INTEGER', float: 'FLOAT', char: 'CHAR', string: 'STRING', bool: 'BOOL' }[t] || 'ANY' }); } export function describeSort(t: Sort): string { return typeName({ k: { int: 'INTEGER', float: 'FLOAT', char: 'CHAR', string: 'STRING', bool: 'BOOL' }[t] || 'ANY' }); }
@@ -30,21 +30,38 @@ import {
key, bodyKey, and, or, not, cmp, ite, TRUE, FALSE, numeric, linear, rebuild, key, bodyKey, and, or, not, cmp, ite, TRUE, FALSE, numeric, linear, rebuild,
constDiff, extend, identity, num, add, substBound, constDiff, extend, identity, num, add, substBound,
} from './logic.js'; } from './logic.js';
import type { Term, Op, App, Quant, Ite, CmpOp } from './logic.js';
/** What `prove` answers: a proof, or "could not", never "false". */
export interface ProveResult { status: 'proved' | 'unknown'; reason?: string; witness?: Term[] }
export interface ProveOptions { depth?: number; cap?: number }
/** The terms stored under some of a term's fields, in the order named, for walks that look inside any kind of term. */
function fields(x: Term, names: readonly string[]): Term[] {
const r = x as unknown as Record<string, unknown>;
const out: Term[] = [];
for (const n of names) { const v = r[n]; if (v && typeof v === 'object') out.push(v as Term); }
return out;
}
const argsIn = (x: Term): Term[] => ('args' in x ? x.args : []);
const ABC = ['a', 'b', 'c'] as const;
/* ------------------------------------------------------------------ */ /* ------------------------------------------------------------------ */
/* Rational numbers */ /* Rational numbers */
/* ------------------------------------------------------------------ */ /* ------------------------------------------------------------------ */
const babs = (x) => (x < 0n ? -x : x); const babs = (x: bigint): bigint => (x < 0n ? -x : x);
function bgcd(a, b) { a = babs(a); b = babs(b); while (b) [a, b] = [b, a % b]; return a || 1n; } function bgcd(a: bigint, b: bigint): bigint { a = babs(a); b = babs(b); while (b) [a, b] = [b, a % b]; return a || 1n; }
class Q { class Q {
constructor(n, d = 1n) { n: bigint;
d: bigint;
constructor(n: bigint, d = 1n) {
if (d < 0n) { n = -n; d = -d; } if (d < 0n) { n = -n; d = -d; }
const g = bgcd(n, d); const g = bgcd(n, d);
this.n = n / g; this.d = d / g; this.n = n / g; this.d = d / g;
} }
static of(x) { static of(x: number | Q): Q {
if (x instanceof Q) return x; if (x instanceof Q) return x;
if (Number.isInteger(x)) return new Q(BigInt(x)); if (Number.isInteger(x)) return new Q(BigInt(x));
const s = x.toString(); const s = x.toString();
@@ -53,14 +70,14 @@ class Q {
const d = 10n ** BigInt(f.length); const d = 10n ** BigInt(f.length);
return new Q(BigInt(i + f), d); return new Q(BigInt(i + f), d);
} }
add(o) { return new Q(this.n * o.d + o.n * this.d, this.d * o.d); } add(o: Q): Q { return new Q(this.n * o.d + o.n * this.d, this.d * o.d); }
sub(o) { return new Q(this.n * o.d - o.n * this.d, this.d * o.d); } sub(o: Q): Q { return new Q(this.n * o.d - o.n * this.d, this.d * o.d); }
mul(o) { return new Q(this.n * o.n, this.d * o.d); } mul(o: Q): Q { return new Q(this.n * o.n, this.d * o.d); }
div(o) { return new Q(this.n * o.d, this.d * o.n); } div(o: Q): Q { return new Q(this.n * o.d, this.d * o.n); }
neg() { return new Q(-this.n, this.d); } neg(): Q { return new Q(-this.n, this.d); }
get zero() { return this.n === 0n; } get zero(): boolean { return this.n === 0n; }
get sign() { return this.n > 0n ? 1 : this.n < 0n ? -1 : 0; } get sign(): number { return this.n > 0n ? 1 : this.n < 0n ? -1 : 0; }
toString() { return this.d === 1n ? `${this.n}` : `${this.n}/${this.d}`; } toString(): string { return this.d === 1n ? `${this.n}` : `${this.n}/${this.d}`; }
} }
const ZERO = new Q(0n); const ZERO = new Q(0n);
const ONE = new Q(1n); const ONE = new Q(1n);
@@ -73,27 +90,30 @@ const ONE = new Q(1n);
* { co: Map(atomKey -> Q), c: Q, op: '<=' | '<' | '==' } meaning * { co: Map(atomKey -> Q), c: Q, op: '<=' | '<' | '==' } meaning
* sum(co[x] * x) + c op 0. * sum(co[x] * x) + c op 0.
*/ */
function constraint(co, c, op) { return { co, c, op }; } type LinOp = '<=' | '<' | '==';
/** sum(co[atom] * atom) + c op 0 */
interface Constraint { co: Map<string, Q>; c: Q; op: LinOp }
function constraint(co: Map<string, Q>, c: Q, op: LinOp): Constraint { return { co, c, op }; }
function tighten(k, ints) { function tighten(k: Constraint, ints: Set<string>): Constraint {
// Every atom whole-numbered: scale to whole coefficients, divide by their // Every atom whole-numbered: scale to whole coefficients, divide by their
// common factor, round the constant up, and turn < into <= -1. // common factor, round the constant up, and turn < into <= -1.
if (k.op === '==' || ![...k.co.keys()].every((a) => ints.has(a))) return k; if (k.op === '==' || ![...k.co.keys()].every((a) => ints.has(a))) return k;
let l = k.c.d; let l = k.c.d;
for (const v of k.co.values()) l = (l * v.d) / bgcd(l, v.d); for (const v of k.co.values()) l = (l * v.d) / bgcd(l, v.d);
const co = new Map(); let g = 0n; const co = new Map<string, bigint>(); let g = 0n;
for (const [a, v] of k.co) { const w = (v.n * l) / v.d; co.set(a, w); g = bgcd(g, w); } for (const [a, v] of k.co) { const w = (v.n * l) / v.d; co.set(a, w); g = bgcd(g, w); }
let c = (k.c.n * l) / k.c.d; let c = (k.c.n * l) / k.c.d;
if (k.op === '<') c += 1n; if (k.op === '<') c += 1n;
if (!co.size) return constraint(new Map(), new Q(c), '<='); if (!co.size) return constraint(new Map(), new Q(c), '<=');
// sum(w x) + c <= 0 with every w divisible by g: sum(w/g x) + ceil(c/g) <= 0 // sum(w x) + c <= 0 with every w divisible by g: sum(w/g x) + ceil(c/g) <= 0
const cg = c >= 0n ? (c + g - 1n) / g : -((-c) / g); const cg = c >= 0n ? (c + g - 1n) / g : -((-c) / g);
const out = new Map(); const out = new Map<string, Q>();
for (const [a, w] of co) out.set(a, new Q(w / g)); for (const [a, w] of co) out.set(a, new Q(w / g));
return constraint(out, new Q(cg), '<='); return constraint(out, new Q(cg), '<=');
} }
function trivial(k) { function trivial(k: Constraint): boolean | null {
if (k.co.size) return null; if (k.co.size) return null;
const s = k.c.sign; const s = k.c.sign;
if (k.op === '<=') return s <= 0; if (k.op === '<=') return s <= 0;
@@ -101,13 +121,13 @@ function trivial(k) {
return s === 0; return s === 0;
} }
function ckey(k) { function ckey(k: Constraint): string {
const parts = [...k.co].sort((a, b) => (a[0] < b[0] ? -1 : 1)).map(([a, v]) => `${v}*${a}`); const parts = [...k.co].sort((a, b) => (a[0] < b[0] ? -1 : 1)).map(([a, v]) => `${v}*${a}`);
return `${parts.join('+')}|${k.c}|${k.op}`; return `${parts.join('+')}|${k.c}|${k.op}`;
} }
/** Is this set of constraints impossible? true: yes; false: possibly satisfiable. */ /** Is this set of constraints impossible? true: yes; false: possibly satisfiable. */
function infeasible(list, ints, budget = { n: 6000 }) { function infeasible(list: Constraint[], ints: Set<string>, budget = { n: 6000 }): boolean {
let cs = list.map((k) => tighten(k, ints)); let cs = list.map((k) => tighten(k, ints));
for (const k of cs) if (trivial(k) === false) return true; for (const k of cs) if (trivial(k) === false) return true;
// equalities first: solve for one atom and substitute // equalities first: solve for one atom and substitute
@@ -115,9 +135,10 @@ function infeasible(list, ints, budget = { n: 6000 }) {
const i = cs.findIndex((k) => k.op === '==' && k.co.size); const i = cs.findIndex((k) => k.op === '==' && k.co.size);
if (i < 0) break; if (i < 0) break;
const eq = cs[i]; const eq = cs[i];
const [a, ca] = [...eq.co].find(([, v]) => !v.zero) || []; const pivot = [...eq.co].find(([, v]) => !v.zero);
if (!a) { cs.splice(i, 1); continue; } if (!pivot) { cs.splice(i, 1); continue; }
const next = []; const [a, ca] = pivot;
const next: Constraint[] = [];
for (let j = 0; j < cs.length; j++) { for (let j = 0; j < cs.length; j++) {
if (j === i) continue; if (j === i) continue;
const k = cs[j]; const k = cs[j];
@@ -141,15 +162,16 @@ function infeasible(list, ints, budget = { n: 6000 }) {
// Fourier-Motzkin // Fourier-Motzkin
const seen = new Set(cs.map(ckey)); const seen = new Set(cs.map(ckey));
for (; ;) { for (; ;) {
const atoms = new Map(); const atoms = new Map<string, { pos: number; neg: number }>();
for (const k of cs) for (const [a, v] of k.co) { for (const k of cs) for (const [a, v] of k.co) {
if (!atoms.has(a)) atoms.set(a, { pos: 0, neg: 0 }); let n = atoms.get(a);
if (v.sign > 0) atoms.get(a).pos++; else atoms.get(a).neg++; if (!n) { n = { pos: 0, neg: 0 }; atoms.set(a, n); }
if (v.sign > 0) n.pos++; else n.neg++;
} }
if (!atoms.size) return cs.some((k) => trivial(k) === false); if (!atoms.size) return cs.some((k) => trivial(k) === false);
let best = null; let cost = Infinity; let best = ''; let cost = Infinity;
for (const [a, { pos, neg }] of atoms) { const c = pos * neg - pos - neg; if (c < cost) { cost = c; best = a; } } for (const [a, { pos, neg }] of atoms) { const c = pos * neg - pos - neg; if (c < cost) { cost = c; best = a; } }
const P = []; const N = []; const rest = []; const P: Constraint[] = []; const N: Constraint[] = []; const rest: Constraint[] = [];
for (const k of cs) { for (const k of cs) {
const v = k.co.get(best); const v = k.co.get(best);
if (!v) rest.push(k); else if (v.sign > 0) P.push(k); else N.push(k); if (!v) rest.push(k); else if (v.sign > 0) P.push(k); else N.push(k);
@@ -158,8 +180,8 @@ function infeasible(list, ints, budget = { n: 6000 }) {
for (const p of P) { for (const p of P) {
for (const n of N) { for (const n of N) {
if (--budget.n < 0) return false; if (--budget.n < 0) return false;
const a = p.co.get(best); const b = n.co.get(best).neg(); const a = p.co.get(best)!; const b = n.co.get(best)!.neg();
const co = new Map(); const co = new Map<string, Q>();
for (const [x, v] of p.co) if (x !== best) co.set(x, v.mul(b)); for (const [x, v] of p.co) if (x !== best) co.set(x, v.mul(b));
for (const [x, v] of n.co) if (x !== best) { const nv = (co.get(x) || ZERO).add(v.mul(a)); if (nv.zero) co.delete(x); else co.set(x, nv); } for (const [x, v] of n.co) if (x !== best) { const nv = (co.get(x) || ZERO).add(v.mul(a)); if (nv.zero) co.delete(x); else co.set(x, nv); }
const nk = tighten(constraint(co, p.c.mul(b).add(n.c.mul(a)), p.op === '<' || n.op === '<' ? '<' : '<='), ints); const nk = tighten(constraint(co, p.c.mul(b).add(n.c.mul(a)), p.op === '<' || n.op === '<' ? '<' : '<='), ints);
@@ -182,15 +204,16 @@ function infeasible(list, ints, budget = { n: 6000 }) {
/* ------------------------------------------------------------------ */ /* ------------------------------------------------------------------ */
/** A numeric comparison as linear constraints (a list: == gives one, < gives one). */ /** A numeric comparison as linear constraints (a list: == gives one, < gives one). */
function toConstraints(op, a, b, atoms) { type Atoms = Map<string, Term | null>;
const la = linear(a); const lb = linear(b); function toConstraints(op: CmpOp, a: Term, b: Term, atoms: Atoms): Constraint[] {
const register = (t) => { const la = linear(a)!; const lb = linear(b)!;
const lin = linear(t); const register = (t: Term) => {
const lin = linear(t)!;
for (const k of lin.terms.keys()) if (!atoms.has(k)) atoms.set(k, findAtom(t, k)); for (const k of lin.terms.keys()) if (!atoms.has(k)) atoms.set(k, findAtom(t, k));
return lin; return lin;
}; };
register(a); register(b); register(a); register(b);
const co = new Map(); const co = new Map<string, Q>();
for (const [k, v] of la.terms) co.set(k, Q.of(v)); for (const [k, v] of la.terms) co.set(k, Q.of(v));
for (const [k, v] of lb.terms) { const nv = (co.get(k) || ZERO).sub(Q.of(v)); if (nv.zero) co.delete(k); else co.set(k, nv); } for (const [k, v] of lb.terms) { const nv = (co.get(k) || ZERO).sub(Q.of(v)); if (nv.zero) co.delete(k); else co.set(k, nv); }
const c = Q.of(la.c).sub(Q.of(lb.c)); const c = Q.of(la.c).sub(Q.of(lb.c));
@@ -201,15 +224,15 @@ function toConstraints(op, a, b, atoms) {
case '>=': return [constraint(negate(co), c.neg(), '<=')]; case '>=': return [constraint(negate(co), c.neg(), '<=')];
case '>': return [constraint(negate(co), c.neg(), '<')]; case '>': return [constraint(negate(co), c.neg(), '<')];
case '==': return [constraint(co, c, '==')]; case '==': return [constraint(co, c, '==')];
default: return null; default: return [];
} }
} }
function negate(co) { const m = new Map(); for (const [k, v] of co) m.set(k, v.neg()); return m; } function negate(co: Map<string, Q>): Map<string, Q> { const m = new Map<string, Q>(); for (const [k, v] of co) m.set(k, v.neg()); return m; }
/** The subterm of `t` whose key is `k`. */ /** The subterm of `t` whose key is `k`. */
function findAtom(t, k) { function findAtom(t: Term, k: string): Term | null {
let found = null; let found: Term | null = null;
const visit = (x) => { const visit = (x: Term): void => {
if (found || !x || typeof x !== 'object') return; if (found || !x || typeof x !== 'object') return;
if (key(x) === k) { found = x; return; } if (key(x) === k) { found = x; return; }
if (x.k === 'op') x.args.forEach(visit); if (x.k === 'op') x.args.forEach(visit);
@@ -223,19 +246,20 @@ function findAtom(t, k) {
/* ------------------------------------------------------------------ */ /* ------------------------------------------------------------------ */
/** The first if-then-else inside an atom, outside any quantifier body. */ /** The first if-then-else inside an atom, outside any quantifier body. */
function firstIte(x) { function firstIte(x: Term | undefined): Ite | null {
if (!x || typeof x !== 'object') return null; if (!x || typeof x !== 'object') return null;
if (x.k === 'ite') return x; if (x.k === 'ite') return x;
if (x.k === 'q' || x.k === 'qc') return firstIte(x.lo) || firstIte(x.hi) || (x.dom && firstIte(x.dom)); if (x.k === 'q') return firstIte(x.lo) || firstIte(x.hi);
for (const k of ['a', 'b', 'c']) { const r = x[k] && firstIte(x[k]); if (r) return r; } if (x.k === 'qc') return firstIte(x.dom);
if (x.args) for (const y of x.args) { const r = firstIte(y); if (r) return r; } for (const y of fields(x, ABC)) { const r = firstIte(y); if (r) return r; }
for (const y of argsIn(x)) { const r = firstIte(y); if (r) return r; }
return null; return null;
} }
function replaceKey(x, k, by) { return rebuild(x, (y) => (key(y) === k ? by : null)); } function replaceKey(x: Term, k: string, by: Term): Term { return rebuild(x, (y) => (key(y) === k ? by : null)); }
/** Negation normal form, with if-then-else lifted out of atoms. */ /** Negation normal form, with if-then-else lifted out of atoms. */
function nnf(f, depth = 0) { function nnf(f: Term, depth = 0): Term {
if (depth > 40) return f; if (depth > 40) return f;
switch (f.k) { switch (f.k) {
case 'and': return and(f.args.map((x) => nnf(x, depth + 1))); case 'and': return and(f.args.map((x) => nnf(x, depth + 1)));
@@ -261,26 +285,26 @@ function nnf(f, depth = 0) {
default: return f; default: return f;
} }
} }
function liftOne(atom, it) { function liftOne(atom: Term, it: Ite): Term {
const k = key(it); const k = key(it);
return or(and(it.c, replaceKey(atom, k, it.a)), and(not(it.c), replaceKey(atom, k, it.b))); return or(and(it.c, replaceKey(atom, k, it.a)), and(not(it.c), replaceKey(atom, k, it.b)));
} }
/** Disjunctive normal form: a list of cases, each a list of literals. */ /** Disjunctive normal form: a list of cases, each a list of literals. */
function dnf(f, cap) { function dnf(f: Term, cap: number): Term[][] | null {
if (f.k === 'and') { if (f.k === 'and') {
let cases = [[]]; let cases: Term[][] = [[]];
for (const g of f.args) { for (const g of f.args) {
const gs = dnf(g, cap); const gs = dnf(g, cap);
if (gs === null) return null; if (gs === null) return null;
const next = []; const next: Term[][] = [];
for (const c of cases) for (const d of gs) { next.push(c.concat(d)); if (next.length > cap) return null; } for (const c of cases) for (const d of gs) { next.push(c.concat(d)); if (next.length > cap) return null; }
cases = next; cases = next;
} }
return cases; return cases;
} }
if (f.k === 'or') { if (f.k === 'or') {
const out = []; const out: Term[][] = [];
for (const g of f.args) { const gs = dnf(g, cap); if (gs === null) return null; out.push(...gs); if (out.length > cap) return null; } for (const g of f.args) { const gs = dnf(g, cap); if (gs === null) return null; out.push(...gs); if (out.length > cap) return null; }
return out; return out;
} }
@@ -293,40 +317,42 @@ function dnf(f, cap) {
/* ------------------------------------------------------------------ */ /* ------------------------------------------------------------------ */
class UF { class UF {
constructor() { this.p = new Map(); this.term = new Map(); } p = new Map<string, string>();
add(t) { const k = key(t); if (!this.p.has(k)) { this.p.set(k, k); this.term.set(k, t); } return k; } term = new Map<string, Term>();
find(k) { let r = k; while (this.p.get(r) !== r) r = this.p.get(r); let x = k; while (this.p.get(x) !== r) { const n = this.p.get(x); this.p.set(x, r); x = n; } return r; } add(t: Term): string { const k = key(t); if (!this.p.has(k)) { this.p.set(k, k); this.term.set(k, t); } return k; }
union(a, b) { const ra = this.find(this.add(a)); const rb = this.find(this.add(b)); if (ra !== rb) this.p.set(ra, rb); return ra !== rb; } find(k: string): string { let r = k; while (this.p.get(r) !== r) r = this.p.get(r)!; let x = k; while (this.p.get(x) !== r) { const n = this.p.get(x)!; this.p.set(x, r); x = n; } return r; }
same(a, b) { return this.find(this.add(a)) === this.find(this.add(b)); } union(a: Term, b: Term): boolean { const ra = this.find(this.add(a)); const rb = this.find(this.add(b)); if (ra !== rb) this.p.set(ra, rb); return ra !== rb; }
same(a: Term, b: Term): boolean { return this.find(this.add(a)) === this.find(this.add(b)); }
} }
/** Collect every compound subterm, for congruence. */ /** Collect every compound subterm, for congruence. */
function subterms(x, out) { type Compound = App | Quant;
function subterms(x: Term, out: Map<string, Compound>): void {
if (!x || typeof x !== 'object') return; if (!x || typeof x !== 'object') return;
if (x.k === 'app' || x.k === 'q') out.set(key(x), x); if (x.k === 'app' || x.k === 'q') out.set(key(x), x);
if (x.k === 'q') { subterms(x.lo, out); subterms(x.hi, out); return; } if (x.k === 'q') { subterms(x.lo, out); subterms(x.hi, out); return; }
if (x.k === 'qc') return; if (x.k === 'qc') return;
for (const k of ['a', 'b', 'c']) if (x[k]) subterms(x[k], out); for (const y of fields(x, ABC)) subterms(y, out);
if (x.args) for (const y of x.args) subterms(y, out); for (const y of argsIn(x)) subterms(y, out);
} }
function signature(t) { function signature(t: Compound): string {
if (t.k === 'q') return `q:${t.q}:${bodyKey(t)}`; if (t.k === 'q') return `q:${t.q}:${bodyKey(t)}`;
return `app:${t.f}:${t.args.length}`; return `app:${t.f}:${t.args.length}`;
} }
function argsOf(t) { return t.k === 'q' ? [t.lo, t.hi] : t.args; } function argsOf(t: Compound): Term[] { return t.k === 'q' ? [t.lo, t.hi] : t.args; }
/** Can this case happen? false when a contradiction is found. */ /** Can this case happen? false when a contradiction is found. */
function caseSatisfiable(lits) { function caseSatisfiable(lits: Term[]): boolean {
const uf = new UF(); const uf = new UF();
const bools = new Map(); // atom key -> true/false const bools = new Map<string, boolean>(); // atom key -> true/false
const boolTerms = new Map(); const boolTerms = new Map<string, Term>();
const diseqs = []; const diseqs: Array<[Term, Term]> = [];
const lin = []; const lin: Constraint[] = [];
const atoms = new Map(); // numeric atom key -> term const atoms: Atoms = new Map(); // numeric atom key -> term
const all = new Map(); const all = new Map<string, Compound>();
const literal = (atom, pos) => { const literal = (atom: Term, pos: boolean): boolean => {
if (atom.k === 'lit') return atom.v === pos; if (atom.k === 'lit') return atom.v === pos;
if (atom.k === 'cmp' && numeric(atom.a.t) && numeric(atom.b.t)) { if (atom.k === 'cmp' && numeric(atom.a.t) && numeric(atom.b.t)) {
if (!pos) return true; // nnf removed negated numeric comparisons if (!pos) return true; // nnf removed negated numeric comparisons
@@ -351,22 +377,24 @@ function caseSatisfiable(lits) {
}; };
for (const l of lits) { for (const l of lits) {
const pos = l.k !== 'not'; const pos = l.k !== 'not';
const atom = pos ? l : l.a; const atom = l.k === 'not' ? l.a : l;
if (!literal(atom, pos)) return false; if (!literal(atom, pos)) return false;
} }
// x DIV c and x MOD c, for a constant c above 0, are pinned by c * (x DIV c) <= x < c * (x DIV c) + c. // x DIV c and x MOD c, for a constant c above 0, are pinned by c * (x DIV c) <= x < c * (x DIV c) + c.
const divs = new Map(); const divs = new Map<string, Op>();
const findDivs = (x) => { const findDivs = (x: Term): void => {
if (!x || typeof x !== 'object') return; if (!x || typeof x !== 'object') return;
if (x.k === 'op' && (x.op === 'DIV' || x.op === 'MOD') && x.args[1].k === 'num' && Number.isInteger(x.args[1].v) && x.args[1].v > 0) divs.set(key(x), x); if (x.k === 'op' && (x.op === 'DIV' || x.op === 'MOD')) { const c = x.args[1]; if (c.k === 'num' && Number.isInteger(c.v) && c.v > 0) divs.set(key(x), x); }
if (x.k === 'q') { findDivs(x.lo); findDivs(x.hi); return; } if (x.k === 'q') { findDivs(x.lo); findDivs(x.hi); return; }
for (const k of ['a', 'b', 'c']) if (x[k]) findDivs(x[k]); for (const y of fields(x, ABC)) findDivs(y);
if (x.args) for (const y of x.args) findDivs(y); for (const y of argsIn(x)) findDivs(y);
}; };
for (const l of lits) findDivs(l); for (const l of lits) findDivs(l);
for (const d of divs.values()) { for (const d of divs.values()) {
const [x, c] = d.args; const [x, cTerm] = d.args;
const q = d.op === 'DIV' ? d : { k: 'op', op: 'DIV', args: [x, c], t: 'int' }; if (cTerm.k !== 'num') continue;
const c = cTerm;
const q: Term = d.op === 'DIV' ? d : { k: 'op', op: 'DIV', args: [x, c], t: 'int' };
// c * q <= x <= c * q + c - 1 // c * q <= x <= c * q + c - 1
lin.push(...toConstraints('<=', { k: 'op', op: '*', args: [c, q], t: 'int' }, x, atoms)); lin.push(...toConstraints('<=', { k: 'op', op: '*', args: [c, q], t: 'int' }, x, atoms));
lin.push(...toConstraints('<=', x, { k: 'op', op: '+', args: [{ k: 'op', op: '*', args: [c, q], t: 'int' }, num(c.v - 1)], t: 'int' }, atoms)); lin.push(...toConstraints('<=', x, { k: 'op', op: '+', args: [{ k: 'op', op: '*', args: [c, q], t: 'int' }, num(c.v - 1)], t: 'int' }, atoms));
@@ -383,7 +411,7 @@ function caseSatisfiable(lits) {
const conflict = () => { const conflict = () => {
for (const [a, b] of diseqs) if (uf.same(a, b)) return true; for (const [a, b] of diseqs) if (uf.same(a, b)) return true;
// two different literal values in one class // two different literal values in one class
const lits = new Map(); const lits = new Map<string, string>();
for (const [k, t] of uf.term) { for (const [k, t] of uf.term) {
if (t.k !== 'lit') continue; if (t.k !== 'lit') continue;
const r = uf.find(k); const r = uf.find(k);
@@ -397,15 +425,16 @@ function caseSatisfiable(lits) {
for (let round = 0; round < 6; round++) { for (let round = 0; round < 6; round++) {
if (conflict()) return false; if (conflict()) return false;
// congruence: same function, equal arguments, therefore equal results // congruence: same function, equal arguments, therefore equal results
const groups = new Map(); const groups = new Map<string, Compound[]>();
for (const t of all.values()) { for (const t of all.values()) {
const s = signature(t); const s = signature(t);
if (!groups.has(s)) groups.set(s, []); let g = groups.get(s);
groups.get(s).push(t); if (!g) { g = []; groups.set(s, g); }
g.push(t);
} }
let changed = false; let changed = false;
const intSet = ints(); const intSet = ints();
const entailedEqual = (a, b) => { const entailedEqual = (a: Term, b: Term): boolean => {
if (key(a) === key(b)) return true; if (key(a) === key(b)) return true;
if (!numeric(a.t) || !numeric(b.t)) return uf.same(a, b); if (!numeric(a.t) || !numeric(b.t)) return uf.same(a, b);
const d = constDiff(a, b); const d = constDiff(a, b);
@@ -431,7 +460,7 @@ function caseSatisfiable(lits) {
else if (a.t === 'bool') { else if (a.t === 'bool') {
const ka = key(a); const kb = key(b); const ka = key(a); const kb = key(b);
if (bools.has(ka) && bools.has(kb) && bools.get(ka) !== bools.get(kb)) return false; if (bools.has(ka) && bools.has(kb) && bools.get(ka) !== bools.get(kb)) return false;
if (bools.has(ka)) bools.set(kb, bools.get(ka)); else if (bools.has(kb)) bools.set(ka, bools.get(kb)); if (bools.has(ka)) bools.set(kb, bools.get(ka)!); else if (bools.has(kb)) bools.set(ka, bools.get(kb)!);
uf.union(a, b); uf.union(a, b);
} else uf.union(a, b); } else uf.union(a, b);
} }
@@ -454,11 +483,13 @@ function caseSatisfiable(lits) {
merged.add(pk); merged.add(pk);
changed = true; changed = true;
const id = identity(t.q, t.t); const id = identity(t.q, t.t);
if (!id) continue;
if (numeric(t.t)) lin.push(...toConstraints('==', t, id, atoms)); if (numeric(t.t)) lin.push(...toConstraints('==', t, id, atoms));
else if (t.t === 'bool') { else if (t.t === 'bool') {
const k = key(t); const k = key(t);
if (bools.has(k) && bools.get(k) !== id.v) return false; const v = id.k === 'lit' && id.v === true;
bools.set(k, id.v); if (bools.has(k) && bools.get(k) !== v) return false;
bools.set(k, v);
} else uf.union(t, id); } else uf.union(t, id);
} }
// Equalities between numeric atoms that the union-find learned. // Equalities between numeric atoms that the union-find learned.
@@ -467,7 +498,7 @@ function caseSatisfiable(lits) {
const r = uf.find(k); const r = uf.find(k);
if (r !== k && numeric(uf.term.get(r)?.t)) { if (r !== k && numeric(uf.term.get(r)?.t)) {
const pk = `uf:${k}=${r}`; const pk = `uf:${k}=${r}`;
if (!merged.has(pk)) { merged.add(pk); lin.push(...toConstraints('==', t, uf.term.get(r), atoms)); changed = true; } if (!merged.has(pk)) { merged.add(pk); lin.push(...toConstraints('==', t, uf.term.get(r)!, atoms)); changed = true; }
} }
} }
// bool atoms that became the same class // bool atoms that became the same class
@@ -480,12 +511,12 @@ function caseSatisfiable(lits) {
/* Quantifier ranges, one position at a time */ /* Quantifier ranges, one position at a time */
/* ------------------------------------------------------------------ */ /* ------------------------------------------------------------------ */
function quantifiers(x, out = new Map()) { function quantifiers(x: Term, out: Map<string, Quant> = new Map()): Map<string, Quant> {
if (!x || typeof x !== 'object') return out; if (!x || typeof x !== 'object') return out;
if (x.k === 'q' && x.q !== 'SETOF') out.set(key(x), x); if (x.k === 'q' && x.q !== 'SETOF') out.set(key(x), x);
if (x.k === 'q') { quantifiers(x.lo, out); quantifiers(x.hi, out); return out; } if (x.k === 'q') { quantifiers(x.lo, out); quantifiers(x.hi, out); return out; }
for (const k of ['a', 'b', 'c', 'dom']) if (x[k]) quantifiers(x[k], out); for (const y of fields(x, ['a', 'b', 'c', 'dom'])) quantifiers(y, out);
if (x.args) for (const y of x.args) quantifiers(y, out); for (const y of argsIn(x)) quantifiers(y, out);
return out; return out;
} }
@@ -494,31 +525,32 @@ function quantifiers(x, out = new Map()) {
* whenever another quantifier of the same shape over [lo, h) is present and * whenever another quantifier of the same shape over [lo, h) is present and
* lo <= h follows from the facts. Also folds single-position ranges. * lo <= h follows from the facts. Also folds single-position ranges.
*/ */
function splitRanges(formulas, facts, depth) { function splitRanges(formulas: Term[], facts: Term[], depth: number): Term[] {
let fs = formulas; let fs = formulas;
for (let round = 0; round < 4; round++) { for (let round = 0; round < 4; round++) {
const qs = new Map(); const qs = new Map<string, Quant>();
for (const f of fs) quantifiers(f, qs); for (const f of fs) quantifiers(f, qs);
const list = [...qs.values()]; const list = [...qs.values()];
const replace = new Map(); const replace = new Map<string, Term>();
for (const a of list) { for (const a of list) {
if (replace.has(key(a))) continue; if (replace.has(key(a))) continue;
// a single position // a single position
const span = constDiff(a.hi, a.lo); const span = constDiff(a.hi, a.lo);
if (span === 1) { replace.set(key(a), extend(a, identity(a.q, a.t), a.lo)); continue; } if (span === 1) { const id = identity(a.q, a.t); const one = id && extend(a, id, a.lo); if (one) replace.set(key(a), one); continue; }
for (const b of list) { for (const b of list) {
if (a === b || a.q !== b.q || bodyKey(a) !== bodyKey(b) || constDiff(a.lo, b.lo) !== 0) continue; if (a === b || a.q !== b.q || bodyKey(a) !== bodyKey(b) || constDiff(a.lo, b.lo) !== 0) continue;
const d = constDiff(a.hi, b.hi); const d = constDiff(a.hi, b.hi);
if (d === null || d < 1 || d > 3) continue; if (d === null || d < 1 || d > 3) continue;
if (depth > 0 || proveSimple(facts, cmp('<=', b.lo, b.hi)) !== 'proved') continue; if (depth > 0 || proveSimple(facts, cmp('<=', b.lo, b.hi)) !== 'proved') continue;
let v = b; let v: Term | null = b;
for (let s = 0; s < d; s++) v = extend(a, v, add(b.hi, num(s))); for (let s = 0; s < d && v; s++) v = extend(a, v, add(b.hi, num(s)));
if (!v) continue;
replace.set(key(a), v); replace.set(key(a), v);
break; break;
} }
} }
if (!replace.size) return fs; if (!replace.size) return fs;
fs = fs.map((f) => rebuild(f, (y) => (y.k === 'q' && replace.has(key(y)) ? replace.get(key(y)) : null))); fs = fs.map((f) => rebuild(f, (y) => (y.k === 'q' && replace.has(key(y)) ? replace.get(key(y))! : null)));
} }
return fs; return fs;
} }
@@ -533,27 +565,27 @@ function splitRanges(formulas, facts, depth) {
* mentions: for each such t, either t is outside the range or the body * mentions: for each such t, either t is outside the range or the body
* holds at t. If every resulting case is impossible, so is this one. * holds at t. If every resulting case is impossible, so is this one.
*/ */
function instantiate(lits, cap) { function instantiate(lits: Term[], cap: number): boolean {
const qs = []; const qs: Array<{ q: Quant; neg: boolean }> = [];
for (const l of lits) { for (const l of lits) {
if (l.k === 'q' && l.q === 'FORALL') qs.push({ q: l, neg: false }); if (l.k === 'q' && l.q === 'FORALL') qs.push({ q: l, neg: false });
if (l.k === 'not' && l.a.k === 'q' && l.a.q === 'EXISTS') qs.push({ q: l.a, neg: true }); if (l.k === 'not' && l.a.k === 'q' && l.a.q === 'EXISTS') qs.push({ q: l.a, neg: true });
} }
if (!qs.length) return false; if (!qs.length) return false;
const cands = new Map(); const cands = new Map<string, Term>();
const visit = (x, inBody) => { const visit = (x: Term, inBody: boolean): void => {
if (!x || typeof x !== 'object' || cands.size > 14) return; if (!x || typeof x !== 'object' || cands.size > 14) return;
if (x.k === 'sym' && x.t === 'int') cands.set(key(x), x); if (x.k === 'sym' && x.t === 'int') cands.set(key(x), x);
if (x.k === 'app' && x.f === 'AT' && !inBody && numeric(x.args[1].t)) cands.set(key(x.args[1]), x.args[1]); if (x.k === 'app' && x.f === 'AT' && !inBody && numeric(x.args[1].t)) cands.set(key(x.args[1]), x.args[1]);
if (x.k === 'q') { visit(x.lo, inBody); visit(x.hi, inBody); visit(x.body, true); return; } if (x.k === 'q') { visit(x.lo, inBody); visit(x.hi, inBody); visit(x.body, true); return; }
for (const k of ['a', 'b', 'c']) if (x[k]) visit(x[k], inBody); for (const y of fields(x, ABC)) visit(y, inBody);
if (x.args) for (const y of x.args) visit(y, inBody); for (const y of argsIn(x)) visit(y, inBody);
}; };
for (const l of lits) visit(l, false); for (const l of lits) visit(l, false);
if (!cands.size) return false; if (!cands.size) return false;
// Use the quantifier only where the case shows t is inside its range: // Use the quantifier only where the case shows t is inside its range:
// then the body at t is a plain fact, with no new case split. // then the body at t is a plain fact, with no new case split.
const inst = []; const inst: Term[] = [];
for (const { q, neg } of qs) { for (const { q, neg } of qs) {
for (const t of cands.values()) { for (const t of cands.values()) {
const inside = and(cmp('<=', q.lo, t), cmp('<', t, q.hi)); const inside = and(cmp('<=', q.lo, t), cmp('<', t, q.hi));
@@ -573,9 +605,9 @@ function instantiate(lits, cap) {
/* Entry points */ /* Entry points */
/* ------------------------------------------------------------------ */ /* ------------------------------------------------------------------ */
function proveSimple(facts, goal) { return prove(facts, goal, { depth: 1 }).status; } function proveSimple(facts: Term[], goal: Term): ProveResult['status'] { return prove(facts, goal, { depth: 1 }).status; }
export function prove(facts, goal, options = {}) { export function prove(facts: Term[], goal: Term, options: ProveOptions = {}): ProveResult {
const depth = options.depth || 0; const depth = options.depth || 0;
const cap = options.cap || 512; const cap = options.cap || 512;
if (goal.k === 'lit' && goal.v === true) return { status: 'proved', reason: 'the goal is TRUE as written' }; if (goal.k === 'lit' && goal.v === true) return { status: 'proved', reason: 'the goal is TRUE as written' };