Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
70 changes: 66 additions & 4 deletions builder/machine.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,13 @@ function missCondition(n, c) {
*/
export const MAX_DEPTH = 12;

/**
* The longest chain of rule tests one branch keeps. A rule's test can be a
* disjunction of misses, which costs `split` more than a dispatch atom: a
* 12-rule chain of compound misses does not split where 12 dispatch atoms do.
*/
export const MAX_CHAIN = 10;

/** A rule with the conditions on `fixed` fields dropped: inside that branch they hold. */
const specialize = (r, fixed) => ({ ...r, when: r.when.filter((c) => !fixed.has(c.field)), whole: r.whole ?? r });

Expand All @@ -95,10 +102,51 @@ function bestField(spec, rules, fixed) {

/** Kept for callers that ask which field a table is factored by first. */
export function factorField(spec) {
const field = truncate(spec.rules).tests.length > MAX_DEPTH ? bestField(spec, spec.rules, new Set()) : null;
const field = truncate(spec.rules).tests.length > MAX_CHAIN ? bestField(spec, spec.rules, new Set()) : null;
return field ? { state: field } : null;
}

/**
* How two numbers can stand: below, equal, above. A comparison of two fields is
* the set of standings it allows, read on the pair in name order.
*/
const STANDS = { '<': ['lt'], '<=': ['lt', 'eq'], '=': ['eq'], '!=': ['lt', 'gt'], '>': ['gt'], '>=': ['eq', 'gt'] };
const FLIP = { lt: 'gt', eq: 'eq', gt: 'lt' };
function standing(c) {
if (typeof c.value !== 'object' || !STANDS[c.op]) return null;
const [x, y] = [c.field, c.value.field];
return x < y ? { x, y, allows: STANDS[c.op] } : { x: y, y: x, allows: STANDS[c.op].map((s) => FLIP[s]) };
}

/** A rule inside the branch where pair x, y stands `at`: null when it cannot fire there, else without the comparisons that hold. */
function within(r, x, y, at) {
const when = [];
for (const c of r.when) {
const s = standing(c);
if (!s || s.x !== x || s.y !== y) when.push(c);
else if (!s.allows.includes(at)) return null;
}
return { ...r, when, whole: r.whole ?? r };
}

const STANDINGS = [['eq', 1], ['lt', 2], ['gt', 2]];

/**
* The pair of number fields that factors a too-deep table no choice field can:
* the one whose deepest standing (one test to equal, two to below or above) is
* shallowest, if that is shallower than the chain itself.
*/
function bestPair(rules) {
let best = null;
const pairs = new Map();
for (const r of rules) for (const c of r.when) { const s = standing(c); if (s) pairs.set(`${s.x} ${s.y}`, s); }
for (const { x, y } of pairs.values()) {
const depth = Math.max(...STANDINGS.map(([at, cost]) => cost + truncate(rules.map((r) => within(r, x, y, at)).filter(Boolean)).tests.length));
if (!best || depth < best.depth) best = { x, y, depth };
}
return best && best.depth < truncate(rules).tests.length ? best : null;
}

/** A condition that holds, as an atom (the rule's own name is used when it is unchanged). */
function holdCondition(n, c) {
const field = n.fields[c.field];
Expand Down Expand Up @@ -167,14 +215,28 @@ export function machineDeclarations(spec, machine, n = names(spec)) {
const body = steps.reduceRight((tail, s) => `(if (${stateOf} =? (${n.fields[field].choices[s.value]})) then (${s.name} request) else ${tail})`, chain(rest));
return { body, steps, rest };
};
// One branch per standing of a pair of number fields: equal, below, above.
const byPair = (rules, fixed, prefix, { x, y }, budget) => {
const [X, Y] = [`(project request ${n.fields[x].id})`, `(project request ${n.fields[y].id})`];
const step = Object.fromEntries(STANDINGS.map(([at, cost]) => {
const name = claim(`step${prefix}${pascal(x)}${pascal(at)}${pascal(y)}`);
stepDecls.push({ ...judge, name, body: build(rules.map((r) => within(r, x, y, at)).filter(Boolean), fixed, `${prefix}${pascal(x)}${pascal(at)}${pascal(y)}`, budget - cost) });
return [at, name];
}));
return `(if (${X} =? ${Y}) then (${step.eq} request) else (if (${X} <? ${Y}) then (${step.lt} request) else (${step.gt} request)))`;
};
const build = (rules, fixed, prefix, budget) => {
if (truncate(rules).tests.length <= budget) return chain(rules);
if (truncate(rules).tests.length <= Math.min(budget, MAX_CHAIN)) return chain(rules);
const field = bestField(spec, rules, fixed);
return field ? factor(rules, fixed, prefix, field, budget).body : chain(rules);
if (field) return factor(rules, fixed, prefix, field, budget).body;
const pair = bestPair(rules);
return pair ? byPair(rules, fixed, prefix, pair, budget) : chain(rules);
};
const owner = machine?.state ?? factorField(spec)?.state;
if (!owner) {
return { decls: [...decls.slice(0, at), ...missDecls, { ...judge, body: chain(spec.rules) }, ...decls.slice(at + 1)], steps: [], stepNames: [], misses: [...misses.values()], rest: spec.rules.map((r) => r.id), n };
// No choice field factors it: a table still too deep is factored by how its number fields stand.
const body = build(spec.rules, new Set(), '', MAX_DEPTH);
return { decls: [...decls.slice(0, at), ...missDecls, ...stepDecls, { ...judge, body }, ...decls.slice(at + 1)], steps: [], stepNames: stepDecls.map((d) => d.name), misses: [...misses.values()], rest: spec.rules.map((r) => r.id), n };
}
const { body, steps, rest } = factor(spec.rules, new Set(), '', owner, MAX_DEPTH);
return {
Expand Down
31 changes: 31 additions & 0 deletions builder/test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,37 @@ const CASES = {
ok(tallOwned.stepNames.length > tallOwned.steps.length, 'a branch still too deep is factored again');
ok(nest(term(defs.judge.body)) <= MAX_DEPTH, `no path of the decision nests past ${MAX_DEPTH} ifs`);
ok(everyTall.every((r) => answerOf[evalTerm(term(defs.judge.body), Object.fromEntries(Object.entries(r).map(([f, v]) => [tn.fields[f].id, codeOf(f, v)])))] === judge(tm.spec, r).outcome), 'the factored decision answers as the first-match chain, for every request');
// A table of number fields no choice field can factor is factored by how a pair of them stands (Allen's interval relations).
const allen = rule30();
const fld = (x) => ({ field: x });
const cmp = (a, op, b) => ({ field: a, op, value: fld(b) });
allen.app.fields = ['astart', 'aend', 'bstart', 'bend'].map((name) => ({ name, kind: 'number', min: 0, max: 9, means: name }));
const allenRules = [[[cmp('aend', '<=', 'astart')], 'malformed'], [[cmp('bend', '<=', 'bstart')], 'malformed'], [[cmp('aend', '<', 'bstart')], 'before'], [[cmp('aend', '=', 'bstart')], 'meets'], [[cmp('bend', '<', 'astart')], 'after'], [[cmp('bend', '=', 'astart')], 'metby'], [[cmp('astart', '=', 'bstart'), cmp('aend', '=', 'bend')], 'equals'], [[cmp('astart', '=', 'bstart'), cmp('aend', '<', 'bend')], 'starts'], [[cmp('astart', '=', 'bstart')], 'startedby'], [[cmp('aend', '=', 'bend'), cmp('astart', '>', 'bstart')], 'finishes'], [[cmp('aend', '=', 'bend')], 'finishedby'], [[cmp('astart', '>', 'bstart'), cmp('aend', '<', 'bend')], 'during'], [[cmp('astart', '<', 'bstart'), cmp('aend', '>', 'bend')], 'contains'], [[cmp('astart', '<', 'bstart')], 'overlaps']];
allen.app.outcomes = [...new Set([...allenRules.map(([, o]) => o), 'overlappedby'])];
allen.app.meanings = Object.fromEntries(allen.app.outcomes.map((o) => [o, o]));
allen.app.rules = allenRules.map(([when, then], i) => ({ id: `REQ-${String(i + 1).padStart(3, '0')}`, when, then, says: then, why: "Allen's relation" }));
allen.app.otherwise = 'overlappedby';
allen.app.properties = [{ id: 'INV-001', kind: 'never', when: [cmp('astart', '=', 'bstart'), cmp('aend', '=', 'bend'), cmp('astart', '<', 'aend')], then: 'before', says: 'equal intervals are not before', why: 'Allen' }];
allen.app.examples = [{ request: '0 1 2 3', response: 'before' }];
delete allen.journeys;
delete allen.app.journeys;
const am = deriveModel(allen);
const allenOwned = machineDeclarations(am.spec, null);
const adefs = Object.fromEntries(allenOwned.decls.map((d) => [d.name, d]));
const acode = (x) => +adefs[x].body;
const aeval = (x, req) => {
if (typeof x === 'string') return /^\d+$/.test(x) ? +x : acode(x);
if (x.length === 1) return aeval(x[0], req);
if (x[0] === 'if') return aeval(x[1], req) ? aeval(x[3], req) : aeval(x[5], req);
if (x[0] === 'project') return req[x[2]];
if (x[1] === 'request') return aeval(term(adefs[x[0]].body), req);
const [l, r] = [aeval(x[0], req), aeval(x[2], req)];
return { '=?': l === r, '<?': l < r, '<=?': l <= r, '||': l || r }[x[1]];
};
const aAnswer = Object.fromEntries(Object.entries(am.names.answers).map(([o, d]) => [acode(d), o]));
const everyAllen = allen.app.fields.reduce((reqs, f) => reqs.flatMap((r) => [0, 1, 2, 3, 4].map((v) => ({ ...r, [f.name]: v }))), [{}]);
ok(allenOwned.stepNames.length === 3 && adefs.judge.body.startsWith('(if ((project request astart) =? (project request bstart))'), 'the number table is factored by how astart and bstart stand: equal, below, above');
ok(everyAllen.every((r) => aAnswer[aeval(term(adefs.judge.body), Object.fromEntries(Object.entries(r).map(([f, v]) => [am.names.fields[f].id, v])))] === judge(am.spec, r).outcome), 'the pair-factored decision answers as the first-match chain, for every request');
// A request takes up to sixteen fields (the prism-code-wide-requests patch, UOR-Foundation/PrismPM#679).
const pad = (p, n) => ({ ...p, app: { ...p.app, fields: [...p.app.fields, ...Array.from({ length: n - p.app.fields.length }, (_, i) => ({ name: `pad${i}`, kind: 'choice', values: ['a', 'b'] }))], examples: p.app.examples.map((e) => ({ ...e, request: `${e.request}${' a'.repeat(n - p.app.fields.length)}` })) } });
ok(deriveModel(pad(rule30(), 16)).spec.fields.length === 16, 'a decision of sixteen fields is built');
Expand Down
Loading