From 44606bf0cf4bbc15e1f7b84d91b44db4919f7e3e Mon Sep 17 00:00:00 2001 From: Alex Maldonado Date: Mon, 5 Oct 2026 03:24:09 +0000 Subject: [PATCH] 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 Claude-Session: https://claude.ai/code/session_01FgvbRdoEheAHqsRmr2WuKZ --- src/engines/pseudo/logic.ts | 510 ++++++++++++++++++++++++++++ src/engines/pseudo/solver.ts | 629 +++++++++++++++++++++++++++++++++++ 2 files changed, 1139 insertions(+) create mode 100644 src/engines/pseudo/logic.ts create mode 100644 src/engines/pseudo/solver.ts diff --git a/src/engines/pseudo/logic.ts b/src/engines/pseudo/logic.ts new file mode 100644 index 0000000..500a9c2 --- /dev/null +++ b/src/engines/pseudo/logic.ts @@ -0,0 +1,510 @@ +/** + * pseudo/logic.js + * + * The verifier's own small language of terms and formulas, with the + * rewrite rules that make reasoning about sequences possible. A formula is + * just a term of type 'bool'. + * + * Term kinds + * num { v, t: 'int' | 'float' } a number + * lit { v, t: 'char' | 'string' | 'bool' } + * sym { name, id, t } a value the program cannot see into: a + * parameter, or a variable after a loop has + * changed it an unknown number of times + * bv { name, t } a quantifier's own name, inside its body + * op { op, args, t } + - * / DIV MOD ^ neg & + * and / or { args } not { a } cmp { op, a, b } + * ite { c, a, b, t } if c then a else b + * app { f, args, t } LENGTH, AT (indexing), APPENDED, STORE, + * IN, a user FUNCTION, a built-in ... + * q { q, v, lo, hi, body, t } SIZE, SORTED, FORALL, EXISTS, SUM, SETOF + * over the range [lo, hi) + * qc { q, v, dom, body, t } the same over a collection; opaque + */ + +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 */ +/* ------------------------------------------------------------------ */ + +export function sortOf(type: TypeLike | null | undefined): Sort { + if (!type) return 'any'; + switch (type.k) { + case 'INTEGER': return 'int'; + case 'FLOAT': return 'float'; + case 'CHAR': return 'char'; + case 'STRING': return 'string'; + case 'BOOL': return 'bool'; + case 'LIST': return 'list'; + case 'ARRAY': return 'array'; + case 'HASHMAP': return 'map'; + case 'SET': return 'set'; + case 'RECORD': return 'record'; + default: return 'any'; + } +} +export const numeric = (t: Sort | undefined): boolean => t === 'int' || t === 'float'; +export const isNum = (x: Term): boolean => numeric(x.t); + +/* ------------------------------------------------------------------ */ +/* Constructors, simplifying as they go */ +/* ------------------------------------------------------------------ */ + +export const TRUE: Lit = { k: 'lit', v: true, t: 'bool' }; +export const FALSE: Lit = { k: 'lit', v: false, t: 'bool' }; +export const num = (v: number, t?: Sort): Num => ({ k: 'num', v, t: t || (Number.isInteger(v) ? 'int' : 'float') }); +export const lit = (v: string | boolean, t: Sort): Lit => ({ k: 'lit', v, t }); +let symIds = 0; +export const sym = (name: string, t: Sort): Sym => ({ k: 'sym', name, id: ++symIds, t }); +export const bv = (name: string, t: Sort): Bv => ({ k: 'bv', name, t }); + +const isConst = (x: Term): x is Num => x.k === 'num'; +const isTrue = (x: Term): boolean => x.k === 'lit' && x.v === true; +const isFalse = (x: Term): boolean => x.k === 'lit' && x.v === false; + +export function numType(a: Term, b?: Term | null): Sort { return a.t === 'float' || b?.t === 'float' ? 'float' : 'int'; } + +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) && a.v === 0) return b; + if (isConst(b) && b.v === 0) return a; + return { k: 'op', op: '+', args: [a, b], t: numType(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(b) && b.v === 0) return a; + if (key(a) === key(b)) return num(0, numType(a, b)); + return { k: 'op', op: '-', args: [a, b], t: numType(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) && a.v === 0) || (isConst(b) && b.v === 0)) return num(0, numType(a, b)); + if (isConst(a) && a.v === 1) return b; + if (isConst(b) && b.v === 1) return a; + return { k: 'op', op: '*', args: [a, b], t: numType(a, b) }; +} +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: string, a: Term, b: Term, t?: Sort): Term { + switch (op) { + case '+': return add(a, b); + case '-': return sub(a, b); + case '*': return mul(a, b); + case '/': + if (isConst(a) && isConst(b) && b.v !== 0) return num(a.v / b.v, 'float'); + if (isConst(b) && b.v !== 0) return { k: 'op', op: '*', args: [num(1 / b.v, 'float'), a], t: 'float' }; + return { k: 'op', op: '/', args: [a, b], t: 'float' }; + case 'DIV': + if (isConst(a) && isConst(b) && b.v !== 0) return num(Math.floor(a.v / b.v), 'int'); + if (isConst(b) && b.v === 1) return a; + return { k: 'op', op: 'DIV', args: [a, b], t: 'int' }; + case 'MOD': + if (isConst(a) && isConst(b) && b.v !== 0) return num(a.v - b.v * Math.floor(a.v / b.v), 'int'); + return { k: 'op', op: 'MOD', args: [a, b], t: 'int' }; + case '^': + if (isConst(a) && isConst(b)) return num(a.v ** b.v, t === 'float' ? 'float' : numType(a, b)); + return { k: 'op', op: '^', args: [a, b], t: t || numType(a, b) }; + case '&': + if (a.k === 'lit' && b.k === 'lit') return lit(String(a.v) + String(b.v), 'string'); + return { k: 'op', op: '&', args: [a, b], t: 'string' }; + default: return { k: 'op', op, args: [a, b], t: t || 'any' }; + } +} + +export function and(...xs: Array): Term { + const out: Term[] = []; + for (const x of xs.flat()) { + if (!x || isTrue(x)) continue; + if (isFalse(x)) return FALSE; + if (x.k === 'and') out.push(...x.args); else out.push(x); + } + if (!out.length) return TRUE; + return out.length === 1 ? out[0] : { k: 'and', args: out, t: 'bool' }; +} +export function or(...xs: Array): Term { + const out: Term[] = []; + for (const x of xs.flat()) { + if (!x || isFalse(x)) continue; + if (isTrue(x)) return TRUE; + if (x.k === 'or') out.push(...x.args); else out.push(x); + } + if (!out.length) return FALSE; + return out.length === 1 ? out[0] : { k: 'or', args: out, t: 'bool' }; +} +const FLIP: Record = { '==': '!=', '!=': '==', '<': '>=', '<=': '>', '>': '<=', '>=': '<' }; +export function not(a: Term): Term { + if (isTrue(a)) return FALSE; + if (isFalse(a)) return TRUE; + 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); + return { k: 'not', a, t: 'bool' }; +} +export function implies(a: Term, b: Term): Term { return or(not(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 (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 === '!=') { + const r = listEquality(a, b); + if (r) return op === '==' ? r : not(r); + if (a.t === 'bool' || b.t === 'bool') { + if (isTrue(b)) return op === '==' ? a : not(a); + if (isFalse(b)) return op === '==' ? not(a) : a; + if (isTrue(a)) return op === '==' ? b : not(b); + if (isFalse(a)) return op === '==' ? not(b) : b; + const same = or(and(a, b), and(not(a), not(b))); + return op === '==' ? same : not(same); + } + } + return { k: 'cmp', op, a, b, t: 'bool' }; +} +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; } +} + +/** Two lists are equal when they have the same length and the same values in order. */ +function listEquality(a: Term, b: Term): Term | null { + const asList = (x: Term): Term[] | null => (x.k === 'app' && x.f === 'LIST' ? x.args : null); + 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]))); + const ap = (x: Term): App | null => (x.k === 'app' && x.f === 'APPENDED' ? x : null); + 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 && la && !la.length) || (pb && lb && !lb.length)) return FALSE; + if (pa && lb && lb.length) return and(cmp('==', pa.args[0], app('LIST', lb.slice(0, -1), 'list')), cmp('==', pa.args[1], lb[lb.length - 1])); + if (pb && la && la.length) return and(cmp('==', pb.args[0], app('LIST', la.slice(0, -1), 'list')), cmp('==', pb.args[1], la[la.length - 1])); + return null; +} + +export function ite(c: Term, a: Term, b: Term): Term { + if (isTrue(c)) return a; + if (isFalse(c)) return b; + if (key(a) === key(b)) return a; + if (a.t === 'bool') return or(and(c, a), and(not(c), b)); + return { k: 'ite', c, a, b, t: a.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. */ +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 === '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 === '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(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); + return app('AT', [x, i], 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)); + return app('AT2', [x, r, c], t); +} + +export function length(x: Term): Term { + if (x.k === 'app') { + switch (x.f) { + case 'APPENDED': return add(length(x.args[0]), num(1)); + case 'STORE': case 'STORE2': case 'SORTLIST': return length(x.args[0]); + case 'LIST': return num(x.args.length); + case 'EMPTY': return num(0); + case 'NEWARRAY': return x.args[1]; + case 'SLICE': return sub(x.args[2], x.args[1]); + case 'SORTEDOF': return length(x.args[0]); + default: break; + } + } + 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.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 === 'SORTED') return { k: 'q', q: 'SIZE', v: x.v, lo: x.lo, hi: x.hi, body: x.body, t: 'int' }; + return app('LENGTH', [x], 'int'); +} + +/** X IN S, unfolded wherever S's shape allows. */ +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 === '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 === 'MAPPUT') return or(cmp('==', x, s.args[1]), member(x, s.args[0])); + if (s.k === 'app' && (s.f === 'SETDEL' || s.f === 'MAPDEL')) return and(cmp('!=', x, s.args[1]), member(x, s.args[0])); + if (s.k === 'app' && s.f === 'EMPTY') return FALSE; + if (s.k === 'q' && s.q === 'SORTED') return and(cmp('<=', s.lo, x), cmp('<', x, s.hi), substBound(s.body, s.v, x)); + return app('IN', [x, s], 'bool'); +} + +/* ------------------------------------------------------------------ */ +/* Keys: one string per term, equal for equal terms */ +/* ------------------------------------------------------------------ */ + +const KEY = new WeakMap(); +export function key(x: Term | null | undefined): string { + if (!x || typeof x !== 'object') return String(x); + const hit = KEY.get(x); + if (hit) return hit; + const k = keyOf(x, []); + KEY.set(x, k); + return k; +} +function keyOf(x: Term, bound: string[]): string { + switch (x.k) { + case 'num': return `${x.v}`; + case 'lit': return x.t === 'bool' ? (x.v ? 'TRUE' : 'FALSE') : `${x.t}:${JSON.stringify(x.v)}`; + case 'sym': return `${x.name}#${x.id}`; + case 'bv': { const i = bound.lastIndexOf(x.name); return i >= 0 ? `$${bound.length - 1 - i}` : `bv:${x.name}`; } + case 'op': return `(${x.op} ${x.args.map((a) => keyOf(a, bound)).join(' ')})`; + case 'and': case 'or': return `(${x.k} ${x.args.map((a) => keyOf(a, bound)).join(' ')})`; + case 'not': return `(not ${keyOf(x.a, bound)})`; + case 'cmp': return `(${x.op} ${keyOf(x.a, bound)} ${keyOf(x.b, bound)})`; + case 'ite': return `(ite ${keyOf(x.c, bound)} ${keyOf(x.a, bound)} ${keyOf(x.b, bound)})`; + case 'app': return `(${x.f} ${x.args.map((a) => keyOf(a, bound)).join(' ')})`; + case 'q': return `(${x.q} ${keyOf(x.lo, bound)} ${keyOf(x.hi, bound)} ${keyOf(x.body, [...bound, x.v])})`; + case 'qc': return `(${x.q}c ${keyOf(x.dom, bound)} ${keyOf(x.body, [...bound, x.v])})`; + default: return '?'; + } +} +/** The body of a quantifier, keyed so that renaming its variable changes nothing. */ +export function bodyKey(q: Quant | QuantC): string { return keyOf(q.body, [q.v]); } + +/* ------------------------------------------------------------------ */ +/* Substitution */ +/* ------------------------------------------------------------------ */ + +/** Replace a quantifier's variable with a term throughout its body. */ +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), []); +} + +/** Replace symbols, by key, throughout a term. */ +export function substSyms(t: Term, map: Map): Term { + if (!map.size) return t; + 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. */ +/** 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); + if (r) return r; + switch (x.k) { + case 'num': case 'lit': case 'sym': case 'bv': return x; + case 'op': { + const args = x.args.map((a) => rebuild(a, fn, shadow)); + return x.op === 'neg' ? neg(args[0]) : arith(x.op, args[0], args[1], x.t); + } + case 'and': return and(x.args.map((a) => rebuild(a, fn, shadow))); + case 'or': return or(x.args.map((a) => rebuild(a, fn, shadow))); + case 'not': return not(rebuild(x.a, fn, shadow)); + case 'cmp': return cmp(x.op, rebuild(x.a, fn, shadow), rebuild(x.b, fn, shadow)); + case 'ite': return ite(rebuild(x.c, fn, shadow), rebuild(x.a, fn, shadow), rebuild(x.b, fn, shadow)); + case 'app': { + const args = x.args.map((a) => rebuild(a, fn, shadow)); + switch (x.f) { + case 'AT': return at(args[0], args[1], x.t); + case 'AT2': return at2(args[0], args[1], args[2], x.t); + case 'LENGTH': return length(args[0]); + case 'IN': return member(args[0], args[1]); + default: return app(x.f, args, x.t); + } + } + case 'q': { + const inner = [...shadow, x.v]; + return mkq(x.q, x.v, rebuild(x.lo, fn, shadow), rebuild(x.hi, fn, shadow), rebuild(x.body, fn, inner), x.t); + } + case 'qc': return { ...x, dom: rebuild(x.dom, fn, shadow), body: rebuild(x.body, fn, [...shadow, x.v]) }; + default: return x; + } +} + +/** A quantifier over [lo, hi), folded when the range is empty or a single position. */ +export function mkq(q: string, v: string, lo: Term, hi: Term, body: Term, t: Sort): Term { + const span = constDiff(hi, lo); + // 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 }; +} + +export function identity(q: string, t: Sort): Term | null { + switch (q) { + case 'SIZE': return num(0); + case 'SUM': return num(0, t === 'float' ? 'float' : 'int'); + case 'FORALL': return TRUE; + case 'EXISTS': return FALSE; + case 'SORTED': return app('LIST', [], 'list'); + case 'SETOF': return app('EMPTY', [], 'set'); + default: return null; + } +} + +/** Add one more position, h, to a quantifier's range: the step that makes induction work. */ +export function extend(q: Quant, prev: Term, h: Term): Term | null { + const b = substBound(q.body, q.v, h); + switch (q.q) { + case 'SIZE': return add(prev, ite(b, num(1), num(0))); + case 'SUM': return add(prev, b); + case 'FORALL': return and(prev, b); + case 'EXISTS': return or(prev, b); + case 'SORTED': return ite(b, app('APPENDED', [prev, h], 'list'), prev); + default: return null; + } +} + +/* ------------------------------------------------------------------ */ +/* Linear forms, for comparing bounds */ +/* ------------------------------------------------------------------ */ + +/** a - b as a constant, when the difference is a plain number. */ +export function constDiff(a: Term, b: Term): number | null { + const la = linear(a); const lb = linear(b); + if (!la || !lb) return null; + const keys = new Set([...la.terms.keys(), ...lb.terms.keys()]); + for (const k of keys) if ((la.terms.get(k) || 0) !== (lb.terms.get(k) || 0)) return null; + return la.c - lb.c; +} + +/** A term as sum(coefficient * atom) + constant, with number coefficients. */ +export function linear(x: Term): { terms: Map; c: number } | null { + const terms = new Map(); + let c = 0; + let ok = true; + const visit = (t: Term, m: number): void => { + if (!ok) 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; } + if (t.k === 'op' && t.op === 'neg') { visit(t.args[0], -m); return; } + if (t.k === 'op' && t.op === '*' && t.args[0].k === 'num') { visit(t.args[1], m * t.args[0].v); return; } + if (t.k === 'op' && t.op === '*' && t.args[1].k === 'num') { visit(t.args[0], m * t.args[1].v); return; } + const k = key(t); + terms.set(k, (terms.get(k) || 0) + m); + }; + visit(x, 1); + if (!ok) return null; + for (const [k, v] of terms) if (v === 0) terms.delete(k); + return { terms, c }; +} + +/* ------------------------------------------------------------------ */ +/* Printing, as pseudocode */ +/* ------------------------------------------------------------------ */ + +/** + * 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'. + */ +export function show(x: Term, names: Map = new Map(), prec = 0): string { + const p = (inner: string, level: number): string => (level < prec ? `(${inner})` : inner); + switch (x.k) { + case 'num': return x.t === 'float' && Number.isInteger(x.v) ? `${x.v}.0` : String(x.v); + case 'lit': + if (x.t === 'bool') return x.v ? 'TRUE' : 'FALSE'; + if (x.t === 'char') return `'${x.v}'`; + return JSON.stringify(x.v); + case 'sym': return names.get(key(x)) || x.name; + case 'bv': return x.name; + case 'op': { + if (x.op === 'neg') return p(`-${show(x.args[0], names, 8)}`, 8); + const lv = { '+': 6, '-': 6, '*': 7, '/': 7, DIV: 7, MOD: 7, '^': 9, '&': 5 }[x.op] || 6; + if (x.op === '+' && x.args[1].k === 'num' && x.args[1].v < 0) return p(`${show(x.args[0], names, lv)} - ${-x.args[1].v}`, lv); + if (x.op === '*' && x.args[0].k === 'num' && x.args[0].t === 'float' && x.args[0].v !== 0 && Number.isInteger(1 / x.args[0].v)) return p(`${show(x.args[1], names, 7)} / ${1 / x.args[0].v}`, 7); + return p(`${show(x.args[0], names, lv)} ${x.op} ${show(x.args[1], names, lv + (x.op === '^' ? 0 : 1))}`, lv); + } + case 'and': return p(x.args.map((a) => show(a, names, 3)).join(' AND '), 2); + case 'or': return p(x.args.map((a) => show(a, names, 2)).join(' OR '), 1); + case 'not': { + if (x.a.k === 'app' && x.a.f === 'IN') return p(`NOT (${show(x.a, names, 0)})`, 3); + return p(`NOT ${show(x.a, names, 4)}`, 3); + } + case 'cmp': return p(`${show(x.a, names, 5)} ${x.op} ${show(x.b, names, 5)}`, 4); + case 'ite': return `(IF ${show(x.c, names)} THEN ${show(x.a, names)} ELSE ${show(x.b, names)})`; + case 'app': return showApp(x, names, p); + case 'q': { + const dom = `[${show(x.lo, names)}, ${show(x.hi, names)})`; + switch (x.q) { + case 'SIZE': return `LENGTH({ ${x.v} IN ${dom} : ${show(x.body, names)} })`; + case 'SORTED': return `SORTED({ ${x.v} IN ${dom} : ${show(x.body, names)} })`; + case 'SETOF': return `{ ${x.v} IN ${dom} : ${show(x.body, names)} }`; + case 'SUM': return p(`SUM ${x.v} IN ${dom} : ${show(x.body, names)}`, 0); + default: return p(`${x.q} ${x.v} IN ${dom} : ${show(x.body, names)}`, 0); + } + } + case 'qc': return p(`${x.q} ${x.v} IN ${show(x.dom, names)} : ${show(x.body, names)}`, 0); + default: return '?'; + } +} + +function showApp(x: App, names: Map, p: (inner: string, level: number) => string): string { + if (/^FLOAT[-+*/^]$/.test(x.f)) { + const op = x.f.slice(5); + const lv = ({ '+': 6, '-': 6, '*': 7, '/': 7, '^': 9 } as Record)[op] ?? 7; + 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)); + switch (x.f) { + case 'AT': return `${show(x.args[0], names, 10)}[${a[1]}]`; + case 'AT2': return `${show(x.args[0], names, 10)}[${a[1]}, ${a[2]}]`; + case 'LENGTH': return `LENGTH(${a[0]})`; + case 'IN': return p(`${show(x.args[0], names, 5)} IN ${show(x.args[1], names, 5)}`, 4); + case 'LIST': return `[${a.join(', ')}]`; + case 'SET': return `{${a.join(', ')}}`; + case 'EMPTY': return '{}'; + case 'APPENDED': return `${show(x.args[0], names, 10)} with ${a[1]} appended`; + case 'STORE': return `${show(x.args[0], names, 10)} with [${a[1]}] set to ${a[2]}`; + case 'STORE2': return `${show(x.args[0], names, 10)} with [${a[1]}, ${a[2]}] set to ${a[3]}`; + case 'MAPPUT': return `${show(x.args[0], names, 10)} with [${a[1]}] set to ${a[2]}`; + case 'SETADD': return `${show(x.args[0], names, 10)} with ${a[1]} added`; + case 'SETDEL': case 'MAPDEL': return `${show(x.args[0], names, 10)} without ${a[1]}`; + default: break; + } + if (x.f.startsWith('FIELD.')) return `${show(x.args[0], names, 10)}.${x.f.slice(6)}`; + if (x.f.startsWith('FSTORE.')) return `${show(x.args[0], names, 10)} with .${x.f.slice(7)} set to ${a[1]}`; + switch (x.f) { + case 'NEWARRAY': return `a new ARRAY of length ${a[1]}`; + case 'SORTLIST': return `${show(x.args[0], names, 10)} sorted`; + default: return `${x.f.replace(/^FN:/, '')}(${a.join(', ')})`; + } +} + +/** Every symbol a term mentions. */ +export function symsOf(x: Term | null | undefined, out: Map = new Map()): Map { + if (!x || typeof x !== 'object') return out; + if (x.k === 'sym') { out.set(key(x), x); return out; } + const r = x as unknown as Record; + 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; +} + +export function describeSort(t: Sort): string { return typeName({ k: { int: 'INTEGER', float: 'FLOAT', char: 'CHAR', string: 'STRING', bool: 'BOOL' }[t] || 'ANY' }); } diff --git a/src/engines/pseudo/solver.ts b/src/engines/pseudo/solver.ts new file mode 100644 index 0000000..bd2570f --- /dev/null +++ b/src/engines/pseudo/solver.ts @@ -0,0 +1,629 @@ +/** + * pseudo/solver.js + * + * A small decision procedure: given facts and a goal, either prove the goal + * follows from the facts, or say it could not. "Could not" is never "false": + * the verifier reports it as not proved, and the lab tests the program + * instead. + * + * prove(facts, goal, options) -> { status: 'proved' | 'unknown', reason } + * + * How it works, in the order it happens: + * 1. Quantifiers over [lo, hi) are extended one position at a time where + * another fact talks about [lo, hi - 1): this is the step that lets an + * invariant like Total == LENGTH({ K IN [0, I) : T[K] == B }) carry + * from one pass to the next. + * 2. The facts and the negated goal become a list of cases (disjunctive + * normal form). The goal is proved when every case is impossible. + * 3. Each case is checked with three cooperating parts: equalities between + * letters, strings, and lists (union-find); linear arithmetic over whole + * numbers (Fourier-Motzkin elimination, tightened for integers); and + * congruence, which merges LENGTH(T) with LENGTH(T) and T[I] with T[J] + * whenever the arithmetic shows I == J. + * + * Everything it concludes is sound: a "proved" is a proof. It is incomplete: + * multiplication of two unknowns, MOD, and most facts about quantifiers + * over collections are opaque to it. + */ + +import { + key, bodyKey, and, or, not, cmp, ite, TRUE, FALSE, numeric, linear, rebuild, + constDiff, extend, identity, num, add, substBound, +} 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; + 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 */ +/* ------------------------------------------------------------------ */ + +const babs = (x: bigint): bigint => (x < 0n ? -x : x); +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 { + n: bigint; + d: bigint; + constructor(n: bigint, d = 1n) { + if (d < 0n) { n = -n; d = -d; } + const g = bgcd(n, d); + this.n = n / g; this.d = d / g; + } + static of(x: number | Q): Q { + if (x instanceof Q) return x; + if (Number.isInteger(x)) return new Q(BigInt(x)); + const s = x.toString(); + if (/e/i.test(s)) { const [m, e] = s.split(/e/i); const q = Q.of(Number(m)); const p = 10n ** BigInt(Math.abs(Number(e))); return Number(e) >= 0 ? new Q(q.n * p, q.d) : new Q(q.n, q.d * p); } + const [i, f = ''] = s.split('.'); + const d = 10n ** BigInt(f.length); + return new Q(BigInt(i + f), d); + } + add(o: Q): Q { 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: Q): Q { return new Q(this.n * o.n, this.d * o.d); } + div(o: Q): Q { return new Q(this.n * o.d, this.d * o.n); } + neg(): Q { return new Q(-this.n, this.d); } + get zero(): boolean { return this.n === 0n; } + get sign(): number { return this.n > 0n ? 1 : this.n < 0n ? -1 : 0; } + toString(): string { return this.d === 1n ? `${this.n}` : `${this.n}/${this.d}`; } +} +const ZERO = new Q(0n); +const ONE = new Q(1n); + +/* ------------------------------------------------------------------ */ +/* Linear constraints */ +/* ------------------------------------------------------------------ */ + +/** + * { co: Map(atomKey -> Q), c: Q, op: '<=' | '<' | '==' } meaning + * sum(co[x] * x) + c op 0. + */ +type LinOp = '<=' | '<' | '=='; +/** sum(co[atom] * atom) + c op 0 */ +interface Constraint { co: Map; c: Q; op: LinOp } +function constraint(co: Map, c: Q, op: LinOp): Constraint { return { co, c, op }; } + +function tighten(k: Constraint, ints: Set): Constraint { + // Every atom whole-numbered: scale to whole coefficients, divide by their + // common factor, round the constant up, and turn < into <= -1. + if (k.op === '==' || ![...k.co.keys()].every((a) => ints.has(a))) return k; + let l = k.c.d; + for (const v of k.co.values()) l = (l * v.d) / bgcd(l, v.d); + const co = new Map(); 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); } + let c = (k.c.n * l) / k.c.d; + if (k.op === '<') c += 1n; + 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 + const cg = c >= 0n ? (c + g - 1n) / g : -((-c) / g); + const out = new Map(); + for (const [a, w] of co) out.set(a, new Q(w / g)); + return constraint(out, new Q(cg), '<='); +} + +function trivial(k: Constraint): boolean | null { + if (k.co.size) return null; + const s = k.c.sign; + if (k.op === '<=') return s <= 0; + if (k.op === '<') return s < 0; + return s === 0; +} + +function ckey(k: Constraint): string { + 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}`; +} + +/** Is this set of constraints impossible? true: yes; false: possibly satisfiable. */ +function infeasible(list: Constraint[], ints: Set, budget = { n: 6000 }): boolean { + let cs = list.map((k) => tighten(k, ints)); + for (const k of cs) if (trivial(k) === false) return true; + // equalities first: solve for one atom and substitute + for (; ;) { + const i = cs.findIndex((k) => k.op === '==' && k.co.size); + if (i < 0) break; + const eq = cs[i]; + const pivot = [...eq.co].find(([, v]) => !v.zero); + if (!pivot) { cs.splice(i, 1); continue; } + const [a, ca] = pivot; + const next: Constraint[] = []; + for (let j = 0; j < cs.length; j++) { + if (j === i) continue; + const k = cs[j]; + const f = k.co.get(a); + if (!f) { next.push(k); continue; } + // k - (f / ca) * eq + const m = f.div(ca); + const co = new Map(k.co); + for (const [b, v] of eq.co) { + const nv = (co.get(b) || ZERO).sub(m.mul(v)); + if (nv.zero) co.delete(b); else co.set(b, nv); + } + const nk = tighten(constraint(co, k.c.sub(m.mul(eq.c)), k.op), ints); + if (trivial(nk) === false) return true; + next.push(nk); + } + cs = next; + } + cs = cs.filter((k) => trivial(k) !== true); + if (cs.some((k) => trivial(k) === false)) return true; + // Fourier-Motzkin + const seen = new Set(cs.map(ckey)); + for (; ;) { + const atoms = new Map(); + for (const k of cs) for (const [a, v] of k.co) { + let n = atoms.get(a); + 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); + 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; } } + const P: Constraint[] = []; const N: Constraint[] = []; const rest: Constraint[] = []; + for (const k of cs) { + const v = k.co.get(best); + if (!v) rest.push(k); else if (v.sign > 0) P.push(k); else N.push(k); + } + const out = rest; + for (const p of P) { + for (const n of N) { + if (--budget.n < 0) return false; + const a = p.co.get(best)!; const b = n.co.get(best)!.neg(); + const co = new Map(); + 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); } + const nk = tighten(constraint(co, p.c.mul(b).add(n.c.mul(a)), p.op === '<' || n.op === '<' ? '<' : '<='), ints); + const t = trivial(nk); + if (t === false) return true; + if (t === true) continue; + const kk = ckey(nk); + if (seen.has(kk)) continue; + seen.add(kk); + out.push(nk); + } + } + cs = out; + if (cs.length > 3000) return false; + } +} + +/* ------------------------------------------------------------------ */ +/* From terms to constraints */ +/* ------------------------------------------------------------------ */ + +/** A numeric comparison as linear constraints (a list: == gives one, < gives one). */ +type Atoms = Map; +function toConstraints(op: CmpOp, a: Term, b: Term, atoms: Atoms): Constraint[] { + const la = linear(a)!; const lb = linear(b)!; + 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)); + return lin; + }; + register(a); register(b); + const co = new Map(); + 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); } + const c = Q.of(la.c).sub(Q.of(lb.c)); + // a - b op 0 + switch (op) { + case '<=': return [constraint(co, c, '<=')]; + case '<': return [constraint(co, c, '<')]; + case '>=': return [constraint(negate(co), c.neg(), '<=')]; + case '>': return [constraint(negate(co), c.neg(), '<')]; + case '==': return [constraint(co, c, '==')]; + default: return []; + } +} +function negate(co: Map): Map { const m = new Map(); for (const [k, v] of co) m.set(k, v.neg()); return m; } + +/** The subterm of `t` whose key is `k`. */ +function findAtom(t: Term, k: string): Term | null { + let found: Term | null = null; + const visit = (x: Term): void => { + if (found || !x || typeof x !== 'object') return; + if (key(x) === k) { found = x; return; } + if (x.k === 'op') x.args.forEach(visit); + }; + visit(t); + return found; +} + +/* ------------------------------------------------------------------ */ +/* Cases */ +/* ------------------------------------------------------------------ */ + +/** The first if-then-else inside an atom, outside any quantifier body. */ +function firstIte(x: Term | undefined): Ite | null { + if (!x || typeof x !== 'object') return null; + if (x.k === 'ite') return x; + if (x.k === 'q') return firstIte(x.lo) || firstIte(x.hi); + if (x.k === 'qc') return firstIte(x.dom); + 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; +} + +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. */ +function nnf(f: Term, depth = 0): Term { + if (depth > 40) return f; + switch (f.k) { + case 'and': return and(f.args.map((x) => nnf(x, depth + 1))); + case 'or': return or(f.args.map((x) => nnf(x, depth + 1))); + case 'not': { + const a = f.a; + if (a.k === 'and') return or(a.args.map((x) => nnf(not(x), depth + 1))); + if (a.k === 'or') return and(a.args.map((x) => nnf(not(x), depth + 1))); + if (a.k === 'not') return nnf(a.a, depth + 1); + if (a.k === 'lit') return a.v ? FALSE : TRUE; + const it = firstIte(a); + if (it) return nnf(not(liftOne(a, it)), depth + 1); + if (a.k === 'cmp' && numeric(a.a.t) && a.op === '==') return or(cmp('<', a.a, a.b), cmp('>', a.a, a.b)); + return f; + } + case 'cmp': { + const it = firstIte(f); + if (it) return nnf(liftOne(f, it), depth + 1); + if (numeric(f.a.t) && f.op === '!=') return or(cmp('<', f.a, f.b), cmp('>', f.a, f.b)); + return f; + } + case 'app': { const it = firstIte(f); return it ? nnf(liftOne(f, it), depth + 1) : f; } + default: return f; + } +} +function liftOne(atom: Term, it: Ite): Term { + const k = key(it); + 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. */ +function dnf(f: Term, cap: number): Term[][] | null { + if (f.k === 'and') { + let cases: Term[][] = [[]]; + for (const g of f.args) { + const gs = dnf(g, cap); + if (gs === null) return null; + const next: Term[][] = []; + for (const c of cases) for (const d of gs) { next.push(c.concat(d)); if (next.length > cap) return null; } + cases = next; + } + return cases; + } + if (f.k === 'or') { + 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; } + return out; + } + if (f.k === 'lit' && f.t === 'bool') return f.v ? [[]] : []; + return [[f]]; +} + +/* ------------------------------------------------------------------ */ +/* One case */ +/* ------------------------------------------------------------------ */ + +class UF { + p = new Map(); + term = new Map(); + 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; } + 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; } + 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. */ +type Compound = App | Quant; +function subterms(x: Term, out: Map): void { + if (!x || typeof x !== 'object') return; + 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 === 'qc') return; + for (const y of fields(x, ABC)) subterms(y, out); + for (const y of argsIn(x)) subterms(y, out); +} + +function signature(t: Compound): string { + if (t.k === 'q') return `q:${t.q}:${bodyKey(t)}`; + return `app:${t.f}:${t.args.length}`; +} +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. */ +function caseSatisfiable(lits: Term[]): boolean { + const uf = new UF(); + const bools = new Map(); // atom key -> true/false + const boolTerms = new Map(); + const diseqs: Array<[Term, Term]> = []; + const lin: Constraint[] = []; + const atoms: Atoms = new Map(); // numeric atom key -> term + const all = new Map(); + + const literal = (atom: Term, pos: boolean): boolean => { + if (atom.k === 'lit') return atom.v === pos; + if (atom.k === 'cmp' && numeric(atom.a.t) && numeric(atom.b.t)) { + if (!pos) return true; // nnf removed negated numeric comparisons + const cs = toConstraints(atom.op, atom.a, atom.b, atoms); + if (cs) lin.push(...cs); + subterms(atom, all); + return true; + } + if (atom.k === 'cmp' && (atom.op === '==' || atom.op === '!=')) { + const eq = (atom.op === '==') === pos; + subterms(atom, all); + uf.add(atom.a); uf.add(atom.b); + if (eq) uf.union(atom.a, atom.b); else diseqs.push([atom.a, atom.b]); + return true; + } + const k = key(atom); + subterms(atom, all); + if (bools.has(k) && bools.get(k) !== pos) return false; + bools.set(k, pos); + boolTerms.set(k, atom); + return true; + }; + for (const l of lits) { + const pos = l.k !== 'not'; + const atom = l.k === 'not' ? l.a : l; + 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. + const divs = new Map(); + const findDivs = (x: Term): void => { + if (!x || typeof x !== 'object') return; + 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; } + for (const y of fields(x, ABC)) findDivs(y); + for (const y of argsIn(x)) findDivs(y); + }; + for (const l of lits) findDivs(l); + for (const d of divs.values()) { + const [x, cTerm] = d.args; + 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 + 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)); + if (d.op === 'MOD') lin.push(...toConstraints('==', d, { k: 'op', op: '-', args: [x, { k: 'op', op: '*', args: [c, q], t: 'int' }], t: 'int' }, atoms)); + } + // Every length and every count is at least 0. + for (const [k, t] of [...all]) { + if ((t.k === 'app' && t.f === 'LENGTH') || (t.k === 'q' && t.q === 'SIZE')) { + lin.push(...toConstraints('>=', t, num(0), atoms)); + } + } + const ints = () => new Set([...atoms].filter(([, t]) => t && t.t === 'int').map(([k]) => k)); + + const conflict = () => { + for (const [a, b] of diseqs) if (uf.same(a, b)) return true; + // two different literal values in one class + const lits = new Map(); + for (const [k, t] of uf.term) { + if (t.k !== 'lit') continue; + const r = uf.find(k); + if (lits.has(r) && lits.get(r) !== k) return true; + lits.set(r, k); + } + return infeasible(lin, ints()); + }; + + const merged = new Set(); + for (let round = 0; round < 6; round++) { + if (conflict()) return false; + // congruence: same function, equal arguments, therefore equal results + const groups = new Map(); + for (const t of all.values()) { + const s = signature(t); + let g = groups.get(s); + if (!g) { g = []; groups.set(s, g); } + g.push(t); + } + let changed = false; + const intSet = ints(); + const entailedEqual = (a: Term, b: Term): boolean => { + if (key(a) === key(b)) return true; + if (!numeric(a.t) || !numeric(b.t)) return uf.same(a, b); + const d = constDiff(a, b); + if (d !== null) return d === 0; + const scratch = new Map(atoms); + const up = toConstraints('>', a, b, scratch); const dn = toConstraints('<', a, b, scratch); + const si = new Set([...scratch].filter(([, t]) => t && t.t === 'int').map(([k]) => k)); + return infeasible([...lin, ...up], si, { n: 1500 }) && infeasible([...lin, ...dn], si, { n: 1500 }); + }; + for (const list of groups.values()) { + if (list.length < 2 || list.length > 12) continue; + for (let i = 0; i < list.length; i++) { + for (let j = i + 1; j < list.length; j++) { + const a = list[i]; const b = list[j]; + const pk = `${key(a)}~${key(b)}`; + if (merged.has(pk)) continue; + const xa = argsOf(a); const xb = argsOf(b); + if (xa.length !== xb.length) continue; + if (!xa.every((x, n) => entailedEqual(x, xb[n]))) continue; + merged.add(pk); + changed = true; + if (numeric(a.t)) { lin.push(...toConstraints('==', a, b, atoms)); } + else if (a.t === 'bool') { + 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.set(kb, bools.get(ka)!); else if (bools.has(kb)) bools.set(ka, bools.get(kb)!); + uf.union(a, b); + } else uf.union(a, b); + } + } + } + // A range that ends at or before it starts is empty. + for (const t of all.values()) { + if (t.k !== 'q') continue; + const pk = `empty:${key(t)}`; + if (merged.has(pk)) continue; + const d = constDiff(t.hi, t.lo); + let empty = d !== null ? d <= 0 : false; + if (d === null) { + const scratch = new Map(atoms); + const over = toConstraints('>', t.hi, t.lo, scratch); + const si = new Set([...scratch].filter(([, x]) => x && x.t === 'int').map(([k]) => k)); + empty = infeasible([...lin, ...over], si, { n: 1500 }); + } + if (!empty) continue; + merged.add(pk); + changed = true; + const id = identity(t.q, t.t); + if (!id) continue; + if (numeric(t.t)) lin.push(...toConstraints('==', t, id, atoms)); + else if (t.t === 'bool') { + const k = key(t); + const v = id.k === 'lit' && id.v === true; + if (bools.has(k) && bools.get(k) !== v) return false; + bools.set(k, v); + } else uf.union(t, id); + } + // Equalities between numeric atoms that the union-find learned. + for (const [k, t] of uf.term) { + if (!numeric(t.t)) continue; + const r = uf.find(k); + if (r !== k && numeric(uf.term.get(r)?.t)) { + const pk = `uf:${k}=${r}`; + 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 + if (!changed) return !conflict(); + } + return !conflict(); +} + +/* ------------------------------------------------------------------ */ +/* Quantifier ranges, one position at a time */ +/* ------------------------------------------------------------------ */ + +function quantifiers(x: Term, out: Map = new Map()): Map { + if (!x || typeof x !== 'object') return out; + 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; } + for (const y of fields(x, ['a', 'b', 'c', 'dom'])) quantifiers(y, out); + for (const y of argsIn(x)) quantifiers(y, out); + return out; +} + +/** + * Rewrite Q over [lo, h + d) as Q over [lo, h) extended by d positions, + * whenever another quantifier of the same shape over [lo, h) is present and + * lo <= h follows from the facts. Also folds single-position ranges. + */ +function splitRanges(formulas: Term[], facts: Term[], depth: number): Term[] { + let fs = formulas; + for (let round = 0; round < 4; round++) { + const qs = new Map(); + for (const f of fs) quantifiers(f, qs); + const list = [...qs.values()]; + const replace = new Map(); + for (const a of list) { + if (replace.has(key(a))) continue; + // a single position + const span = constDiff(a.hi, a.lo); + 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) { + 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); + if (d === null || d < 1 || d > 3) continue; + if (depth > 0 || proveSimple(facts, cmp('<=', b.lo, b.hi)) !== 'proved') continue; + let v: Term | null = b; + 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); + break; + } + } + if (!replace.size) return fs; + fs = fs.map((f) => rebuild(f, (y) => (y.k === 'q' && replace.has(key(y)) ? replace.get(key(y))! : null))); + } + return fs; +} + +/* ------------------------------------------------------------------ */ +/* FORALL, used at particular positions */ +/* ------------------------------------------------------------------ */ + +/** + * A FORALL that holds (or an EXISTS that fails) says something about every + * position in its range. Try it at each whole-number term the case + * 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. + */ +function instantiate(lits: Term[], cap: number): boolean { + const qs: Array<{ q: Quant; neg: boolean }> = []; + for (const l of lits) { + 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 (!qs.length) return false; + const cands = new Map(); + const visit = (x: Term, inBody: boolean): void => { + if (!x || typeof x !== 'object' || cands.size > 14) return; + 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 === 'q') { visit(x.lo, inBody); visit(x.hi, inBody); visit(x.body, true); return; } + for (const y of fields(x, ABC)) visit(y, inBody); + for (const y of argsIn(x)) visit(y, inBody); + }; + for (const l of lits) visit(l, false); + if (!cands.size) return false; + // 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. + const inst: Term[] = []; + for (const { q, neg } of qs) { + for (const t of cands.values()) { + const inside = and(cmp('<=', q.lo, t), cmp('<', t, q.hi)); + if (prove(lits, inside, { depth: 1 }).status !== 'proved') continue; + const body = substBound(q.body, q.v, t); + inst.push(neg ? not(body) : body); + } + } + if (!inst.length) return false; + const f = nnf(and([...lits, ...inst])); + const cases = dnf(f, cap * 2); + if (cases === null) return false; + return cases.every((c) => !caseSatisfiable(c)); +} + +/* ------------------------------------------------------------------ */ +/* Entry points */ +/* ------------------------------------------------------------------ */ + +function proveSimple(facts: Term[], goal: Term): ProveResult['status'] { return prove(facts, goal, { depth: 1 }).status; } + +export function prove(facts: Term[], goal: Term, options: ProveOptions = {}): ProveResult { + const depth = options.depth || 0; + const cap = options.cap || 512; + if (goal.k === 'lit' && goal.v === true) return { status: 'proved', reason: 'the goal is TRUE as written' }; + let fs = [...facts, not(goal)]; + fs = splitRanges(fs, facts, depth); + let f = and(fs.map((x) => nnf(x))); + if (f.k === 'lit') return f.v ? { status: 'unknown', reason: 'nothing contradicts the negated goal' } : { status: 'proved', reason: 'the facts contradict each other or the goal is trivial' }; + f = nnf(f); + const cases = dnf(f, cap); + if (cases === null) return { status: 'unknown', reason: 'too many cases to check' }; + for (const c of cases) { + if (!caseSatisfiable(c)) continue; + if (depth === 0 && instantiate(c, cap)) continue; + return { status: 'unknown', reason: 'at least one case could not be ruled out', witness: c }; + } + return { status: 'proved', reason: `${cases.length} ${cases.length === 1 ? 'case' : 'cases'} ruled out` }; +} + +export { Q, infeasible };