diff --git a/src/engines/pseudo/logic.js b/src/engines/pseudo/logic.ts similarity index 75% rename from src/engines/pseudo/logic.js rename to src/engines/pseudo/logic.ts index 44a7c70..500a9c2 100644 --- a/src/engines/pseudo/logic.js +++ b/src/engines/pseudo/logic.ts @@ -24,11 +24,40 @@ 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) { +export function sortOf(type: TypeLike | null | undefined): Sort { if (!type) return 'any'; switch (type.k) { case 'INTEGER': return 'int'; @@ -44,48 +73,48 @@ export function sortOf(type) { default: return 'any'; } } -export const numeric = (t) => t === 'int' || t === 'float'; -export const isNum = (x) => numeric(x.t); +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 = { k: 'lit', v: true, t: 'bool' }; -export const FALSE = { k: 'lit', v: false, t: 'bool' }; -export const num = (v, t) => ({ k: 'num', v, t: t || (Number.isInteger(v) ? 'int' : 'float') }); -export const lit = (v, t) => ({ k: 'lit', v, t }); +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, t, info = {}) => ({ k: 'sym', name, id: ++symIds, t, ...info }); -export const bv = (name, t) => ({ k: 'bv', name, t }); +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) => x.k === 'num'; -const isTrue = (x) => x.k === 'lit' && x.v === true; -const isFalse = (x) => x.k === 'lit' && x.v === false; +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, 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) && 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, 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, 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) { 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 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); @@ -111,8 +140,8 @@ export function arith(op, a, b, t) { } } -export function and(...xs) { - const out = []; +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; @@ -121,8 +150,8 @@ export function and(...xs) { if (!out.length) return TRUE; return out.length === 1 ? out[0] : { k: 'and', args: out, t: 'bool' }; } -export function or(...xs) { - const out = []; +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; @@ -131,17 +160,17 @@ export function or(...xs) { if (!out.length) return FALSE; return out.length === 1 ? out[0] : { k: 'or', args: out, t: 'bool' }; } -const FLIP = { '==': '!=', '!=': '==', '<': '>=', '<=': '>', '>': '<=', '>=': '<' }; -export function not(a) { +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, 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 (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; @@ -159,16 +188,16 @@ export function cmp(op, a, b) { } 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; } } /** Two lists are equal when they have the same length and the same values in order. */ -function listEquality(a, b) { - const asList = (x) => (x.k === 'app' && x.f === 'LIST' ? x.args : null); +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) => (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); 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; @@ -177,7 +206,7 @@ function listEquality(a, b) { return null; } -export function ite(c, a, b) { +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; @@ -185,24 +214,24 @@ export function ite(c, a, b) { 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. */ -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 === '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(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); 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)); return app('AT2', [x, r, c], t); } -export function length(x) { +export function length(x: Term): Term { if (x.k === 'app') { switch (x.f) { case 'APPENDED': return add(length(x.args[0]), num(1)); @@ -215,7 +244,7 @@ export function length(x) { 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.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' }; @@ -224,7 +253,7 @@ export function length(x) { } /** 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 === '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])); @@ -239,8 +268,8 @@ export function member(x, s) { /* Keys: one string per term, equal for equal terms */ /* ------------------------------------------------------------------ */ -const KEY = new WeakMap(); -export function key(x) { +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; @@ -248,7 +277,7 @@ export function key(x) { KEY.set(x, k); return k; } -function keyOf(x, bound) { +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)}`; @@ -266,25 +295,27 @@ function keyOf(x, bound) { } } /** 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 */ /* ------------------------------------------------------------------ */ /** 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), []); } /** Replace symbols, by key, throughout a term. */ -export function substSyms(t, map) { +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. */ -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); if (r) return r; 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. */ -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); - 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 }; } -export function identity(q, 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'); @@ -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. */ -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); switch (q.q) { 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. */ -export function constDiff(a, b) { +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()]); @@ -363,11 +395,11 @@ export function constDiff(a, b) { } /** A term as sum(coefficient * atom) + constant, with number coefficients. */ -export function linear(x) { - const terms = new Map(); +export function linear(x: Term): { terms: Map; c: number } | null { + const terms = new Map(); let c = 0; let ok = true; - const visit = (t, m) => { + 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; } @@ -392,8 +424,8 @@ export function linear(x) { * 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, names = new Map(), prec = 0) { - const p = (inner, level) => (level < prec ? `(${inner})` : inner); +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': @@ -433,10 +465,10 @@ export function show(x, names = new Map(), prec = 0) { } } -function showApp(x, names, p) { +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 }[op]; + 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)); @@ -466,12 +498,13 @@ function showApp(x, names, p) { } /** Every symbol a term mentions. */ -export function symsOf(x, out = new Map()) { +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; } - for (const k of ['a', 'b', 'c', 'lo', 'hi', 'body', 'dom']) if (x[k]) symsOf(x[k], out); - if (x.args) for (const y of x.args) symsOf(y, 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) { 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' }); } diff --git a/src/engines/pseudo/solver.js b/src/engines/pseudo/solver.ts similarity index 72% rename from src/engines/pseudo/solver.js rename to src/engines/pseudo/solver.ts index 1caf2ea..bd2570f 100644 --- a/src/engines/pseudo/solver.js +++ b/src/engines/pseudo/solver.ts @@ -30,21 +30,38 @@ 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) => (x < 0n ? -x : x); -function bgcd(a, b) { a = babs(a); b = babs(b); while (b) [a, b] = [b, a % b]; return a || 1n; } +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 { - constructor(n, d = 1n) { + 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) { + 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(); @@ -53,14 +70,14 @@ class Q { const d = 10n ** BigInt(f.length); return new Q(BigInt(i + f), d); } - add(o) { 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); } - mul(o) { return new Q(this.n * o.n, this.d * o.d); } - div(o) { return new Q(this.n * o.d, this.d * o.n); } - neg() { return new Q(-this.n, this.d); } - get zero() { return this.n === 0n; } - get sign() { return this.n > 0n ? 1 : this.n < 0n ? -1 : 0; } - toString() { return this.d === 1n ? `${this.n}` : `${this.n}/${this.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); @@ -73,27 +90,30 @@ const ONE = new Q(1n); * { co: Map(atomKey -> Q), c: Q, op: '<=' | '<' | '==' } meaning * 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; c: Q; op: LinOp } +function constraint(co: Map, c: Q, op: LinOp): Constraint { return { co, c, op }; } -function tighten(k, ints) { +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; + 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(); + 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) { +function trivial(k: Constraint): boolean | null { if (k.co.size) return null; const s = k.c.sign; if (k.op === '<=') return s <= 0; @@ -101,13 +121,13 @@ function trivial(k) { 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}`); return `${parts.join('+')}|${k.c}|${k.op}`; } /** Is this set of constraints impossible? true: yes; false: possibly satisfiable. */ -function infeasible(list, ints, budget = { n: 6000 }) { +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 @@ -115,9 +135,10 @@ function infeasible(list, ints, budget = { n: 6000 }) { const i = cs.findIndex((k) => k.op === '==' && k.co.size); if (i < 0) break; const eq = cs[i]; - const [a, ca] = [...eq.co].find(([, v]) => !v.zero) || []; - if (!a) { cs.splice(i, 1); continue; } - const next = []; + 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]; @@ -141,15 +162,16 @@ function infeasible(list, ints, budget = { n: 6000 }) { // Fourier-Motzkin const seen = new Set(cs.map(ckey)); for (; ;) { - const atoms = new Map(); + const atoms = new Map(); for (const k of cs) for (const [a, v] of k.co) { - if (!atoms.has(a)) atoms.set(a, { pos: 0, neg: 0 }); - if (v.sign > 0) atoms.get(a).pos++; else atoms.get(a).neg++; + 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 = 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; } } - const P = []; const N = []; const rest = []; + 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); @@ -158,8 +180,8 @@ function infeasible(list, ints, budget = { n: 6000 }) { 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(); + 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); @@ -182,15 +204,16 @@ function infeasible(list, ints, budget = { n: 6000 }) { /* ------------------------------------------------------------------ */ /** A numeric comparison as linear constraints (a list: == gives one, < gives one). */ -function toConstraints(op, a, b, atoms) { - const la = linear(a); const lb = linear(b); - const register = (t) => { - const lin = linear(t); +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(); + 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)); @@ -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(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): 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, k) { - let found = null; - const visit = (x) => { +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); @@ -223,19 +246,20 @@ function findAtom(t, k) { /* ------------------------------------------------------------------ */ /** 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.k === 'ite') return x; - if (x.k === 'q' || x.k === 'qc') return firstIte(x.lo) || firstIte(x.hi) || (x.dom && firstIte(x.dom)); - for (const k of ['a', 'b', 'c']) { const r = x[k] && firstIte(x[k]); if (r) return r; } - if (x.args) for (const y of x.args) { const r = firstIte(y); if (r) return r; } + 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, 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. */ -function nnf(f, depth = 0) { +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))); @@ -261,26 +285,26 @@ function nnf(f, depth = 0) { default: return f; } } -function liftOne(atom, it) { +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, cap) { +function dnf(f: Term, cap: number): Term[][] | null { if (f.k === 'and') { - let cases = [[]]; + let cases: Term[][] = [[]]; for (const g of f.args) { const gs = dnf(g, cap); 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; } cases = next; } return cases; } 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; } return out; } @@ -293,40 +317,42 @@ function dnf(f, cap) { /* ------------------------------------------------------------------ */ class UF { - constructor() { this.p = new Map(); this.term = new Map(); } - add(t) { const k = key(t); if (!this.p.has(k)) { this.p.set(k, k); this.term.set(k, t); } return k; } - 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; } - 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; } - same(a, b) { return this.find(this.add(a)) === this.find(this.add(b)); } + 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. */ -function subterms(x, out) { +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 k of ['a', 'b', 'c']) if (x[k]) subterms(x[k], out); - if (x.args) for (const y of x.args) subterms(y, out); + for (const y of fields(x, ABC)) 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)}`; 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. */ -function caseSatisfiable(lits) { +function caseSatisfiable(lits: Term[]): boolean { const uf = new UF(); - const bools = new Map(); // atom key -> true/false - const boolTerms = new Map(); - const diseqs = []; - const lin = []; - const atoms = new Map(); // numeric atom key -> term - const all = new Map(); + 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, pos) => { + 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 @@ -351,22 +377,24 @@ function caseSatisfiable(lits) { }; for (const l of lits) { 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; } // 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) => { + 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') && 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; } - for (const k of ['a', 'b', 'c']) if (x[k]) findDivs(x[k]); - if (x.args) for (const y of x.args) findDivs(y); + 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, c] = d.args; - const q = d.op === 'DIV' ? d : { k: 'op', op: 'DIV', args: [x, c], t: 'int' }; + 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)); @@ -383,7 +411,7 @@ function caseSatisfiable(lits) { 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(); + const lits = new Map(); for (const [k, t] of uf.term) { if (t.k !== 'lit') continue; const r = uf.find(k); @@ -397,15 +425,16 @@ function caseSatisfiable(lits) { for (let round = 0; round < 6; round++) { if (conflict()) return false; // congruence: same function, equal arguments, therefore equal results - const groups = new Map(); + const groups = new Map(); for (const t of all.values()) { const s = signature(t); - if (!groups.has(s)) groups.set(s, []); - groups.get(s).push(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, b) => { + 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); @@ -431,7 +460,7 @@ function caseSatisfiable(lits) { 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)); + 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); } @@ -454,11 +483,13 @@ function caseSatisfiable(lits) { 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); - if (bools.has(k) && bools.get(k) !== id.v) return false; - bools.set(k, id.v); + 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. @@ -467,7 +498,7 @@ function caseSatisfiable(lits) { 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; } + 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 @@ -480,12 +511,12 @@ function caseSatisfiable(lits) { /* Quantifier ranges, one position at a time */ /* ------------------------------------------------------------------ */ -function quantifiers(x, out = new Map()) { +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 k of ['a', 'b', 'c', 'dom']) if (x[k]) quantifiers(x[k], out); - if (x.args) for (const y of x.args) quantifiers(y, 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; } @@ -494,31 +525,32 @@ function quantifiers(x, out = new Map()) { * 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, facts, depth) { +function splitRanges(formulas: Term[], facts: Term[], depth: number): Term[] { let fs = formulas; for (let round = 0; round < 4; round++) { - const qs = new Map(); + const qs = new Map(); for (const f of fs) quantifiers(f, qs); const list = [...qs.values()]; - const replace = new Map(); + 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) { 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) { 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 = b; - for (let s = 0; s < d; s++) v = extend(a, v, add(b.hi, num(s))); + 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))); + fs = fs.map((f) => rebuild(f, (y) => (y.k === 'q' && replace.has(key(y)) ? replace.get(key(y))! : null))); } 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 * holds at t. If every resulting case is impossible, so is this one. */ -function instantiate(lits, cap) { - const qs = []; +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, inBody) => { + 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 k of ['a', 'b', 'c']) if (x[k]) visit(x[k], inBody); - if (x.args) for (const y of x.args) visit(y, inBody); + 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 = []; + 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)); @@ -573,9 +605,9 @@ function instantiate(lits, cap) { /* 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 cap = options.cap || 512; if (goal.k === 'lit' && goal.v === true) return { status: 'proved', reason: 'the goal is TRUE as written' };