eyemind 0.5.32 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "eyemind",
3
- "version": "0.5.32",
3
+ "version": "0.6.1",
4
4
  "description": "A dependency-free JavaScript rule language with forward and backward reasoning and checkable proofs.",
5
5
  "type": "module",
6
6
  "main": "./src/index.js",
package/src/cli.js CHANGED
@@ -11,13 +11,12 @@ export const HELP = `Usage: eyemind [OPTION ...] [FILE ...]
11
11
  Programs are JavaScript; forward rules run to a fixpoint. Other files are read
12
12
  by their extension: .ttl, .trig, .nt and .nq as RDF 1.2 data, .n3 as Notation3
13
13
  and .srl as a SPARQL 1.2 RL rule set, both compiled to an eyemind program.
14
- -p, --proof Print a proof in the input's format (JavaScript, N3, SRL)
14
+ -p, --proof Print a proof of the conclusions
15
15
  -c, --prove-and-check Generate a proof and check it against the input program
16
- --check-proof FILE Print checked answers and a proof check report (- for stdin)
16
+ --check-proof FILE Check a proof and print its answers and verdict (- for stdin)
17
17
  --json Print the check report as JSON instead
18
18
  --goal GOAL Ask a backward goal after forward reasoning; with
19
19
  --check-proof, the goal the proof answers
20
- --strict-proof Reject proofs with unresolved obligations
21
20
  --unused List the clauses that make no difference to the conclusions
22
21
  --stats Print reasoning statistics to stderr
23
22
  --max-depth N Bound backward recursion (default 1000000)
@@ -25,8 +24,8 @@ and .srl as a SPARQL 1.2 RL rule set, both compiled to an eyemind program.
25
24
  --max-inferences N Bound reasoning work (default 1000000)
26
25
  --to FORMAT Write the conclusions as turtle, trig, n-triples,
27
26
  n-quads, n3 or eyemind (default: n3 for N3, turtle
28
- for a rule set, eyemind otherwise)
29
- --all With RDF output, write the given data too
27
+ for a rule set, eyemind otherwise or with --goal)
28
+ --all With RDF or N3 output, write the given data too
30
29
  --program Print the program the inputs compile to
31
30
  --base IRI Resolve relative IRIs of the inputs against IRI
32
31
  --stream-messages Run the rules independently for each RDF Message
@@ -37,6 +36,7 @@ Exit codes: 0 success, 1 error, 2 invalid proof, 65 contradiction.
37
36
  `;
38
37
 
39
38
  const LIMITS = { '--max-depth': 'maxDepth', '--max-iterations': 'maxIterations', '--max-inferences': 'maxInferences' };
39
+ const ALIASES = new Map([['-p', '--proof'], ['-c', '--prove-and-check'], ['-v', '--version'], ['-h', '--help']]);
40
40
  // N3 and SPARQL 1.2 RL programs run longer than eyemind's defaults allow.
41
41
  const COMPILED_LIMITS = { maxDepth: 1000000, maxIterations: 100000, maxInferences: 1000000000 };
42
42
 
@@ -57,7 +57,6 @@ export function main(argv, io) {
57
57
  const goals = [];
58
58
  let proofFile = null;
59
59
  let stats = false;
60
- let strictProof = false;
61
60
  let asJson = false;
62
61
  let unused = false;
63
62
  let proveAndCheck = false;
@@ -68,23 +67,21 @@ export function main(argv, io) {
68
67
  let streamMessages = false;
69
68
  const filePositions = new Set();
70
69
  for (let i = 0; i < argv.length; i++) {
71
- const arg = argv[i];
72
- if (arg === '--help' || arg === '-h') {
70
+ const arg = ALIASES.get(argv[i]) ?? argv[i];
71
+ if (arg === '--help') {
73
72
  stdout(HELP);
74
73
  return 0;
75
74
  }
76
- if (arg === '--version' || arg === '-v') {
75
+ if (arg === '--version') {
77
76
  stdout(`eyemind v${VERSION}\n`);
78
77
  return 0;
79
78
  }
80
- if (arg === '--proof' || arg === '-p') {
79
+ if (arg === '--proof') {
81
80
  options.proof = true;
82
- } else if (arg === '--prove-and-check' || arg === '-c') {
81
+ } else if (arg === '--prove-and-check') {
83
82
  proveAndCheck = true;
84
83
  } else if (arg === '--stats') {
85
84
  stats = true;
86
- } else if (arg === '--strict-proof') {
87
- strictProof = true;
88
85
  } else if (arg === '--json') {
89
86
  asJson = true;
90
87
  } else if (arg === '--unused') {
@@ -100,9 +97,9 @@ export function main(argv, io) {
100
97
  if (i >= argv.length) throw new UsageError(`${arg} needs a value`);
101
98
  const value = argv[i];
102
99
  // An option in the value's place means the value was left out, as in
103
- // --check-proof --strict-proof proof.js; reading the option as a file
100
+ // --check-proof --json proof.js; reading the option as a file
104
101
  // name would only fail later with a puzzling message.
105
- if (/^--./.test(value) || ['-p', '-c', '-h'].includes(value)) {
102
+ if (/^--./.test(value) || ALIASES.has(value)) {
106
103
  throw new UsageError(`${arg} needs a value right after it, not the option ${value}`);
107
104
  }
108
105
  if (arg === '--check-proof') {
@@ -127,7 +124,6 @@ export function main(argv, io) {
127
124
  }
128
125
  }
129
126
  if (asJson && proofFile === null && !proveAndCheck) throw new UsageError('--json requires --check-proof or --prove-and-check');
130
- if (strictProof && proofFile === null && !proveAndCheck) throw new UsageError('--strict-proof requires --check-proof or --prove-and-check');
131
127
  if (proveAndCheck && (proofFile !== null || options.proof)) {
132
128
  throw new UsageError('--prove-and-check cannot be combined with --proof or --check-proof');
133
129
  }
@@ -191,7 +187,7 @@ export function main(argv, io) {
191
187
  // A compiled program has the larger bounds, unless they are given.
192
188
  if (loaded.kind !== 'js') for (const [name, value] of Object.entries(COMPILED_LIMITS)) options[name] ??= value;
193
189
  if (proofFile !== null) {
194
- const report = checkProof(program, document, { goals, allowTrusted: !strictProof });
190
+ const report = checkProof(program, document, { goals });
195
191
  stdout(asJson ? `${JSON.stringify(publicReport(report), null, 2)}\n` : checkReport(report));
196
192
  // An invalid proof is a result, not an error: it has its own exit code.
197
193
  return report.valid ? 0 : 2;
@@ -204,7 +200,7 @@ export function main(argv, io) {
204
200
  if (proveAndCheck) {
205
201
  // Check the rendered certificate against the input, just as a saved
206
202
  // proof is checked; no second reasoning run supplies missing evidence.
207
- const report = checkProof(program, result.proof, { goals, allowTrusted: !strictProof });
203
+ const report = checkProof(program, result.proof, { goals });
208
204
  stdout(asJson ? `${JSON.stringify(publicReport(report), null, 2)}\n` : checkReport(report));
209
205
  if (stats) stderr(`${JSON.stringify(result.stats)}\n`);
210
206
  return report.valid ? result.haltCode || 0 : 2;
package/src/closure.js CHANGED
@@ -1,48 +1,50 @@
1
- // Search certificates: what settles a negation or a collection.
1
+ // The certificate of a proof: every answer of a call, and every derived fact.
2
2
  //
3
- // A negation holds when its goal has no solution, and a collection lists
4
- // every solution; no step can show either. A search certificate can. For each
5
- // call the search behind the boundary made, it lists every answer, in search
6
- // order: searched(Call, Answers). For each predicate that forward rules derive
7
- // and the search consulted, it lists every derived fact: derived(Pattern,
8
- // Facts). A table is checked by expanding its call one level against the
9
- // program, as a search would, with every inner call answered by the table of
10
- // that call, so no table vouches for itself and a wrong one shows as a
11
- // disagreement. A listing is checked by its facts' own steps, which show each
12
- // was derived, and by closure: under the listed facts no forward rule derives
13
- // a fact of that predicate the listing leaves out. Nothing is searched for.
3
+ // For each call a question's search makes, a call table lists every answer,
4
+ // in search order: called(Call, Answers). For each relation that forward
5
+ // rules derive and the search consulted, a listing lists every derived fact:
6
+ // derived(Pattern, Facts). A table is checked by expanding its call one level
7
+ // against the program, as a search would, with every inner call answered by
8
+ // the table of that call, so no table vouches for itself and a wrong one shows
9
+ // as a disagreement. A listing is checked by closure: under the listed facts
10
+ // no forward rule derives a fact of that relation the listing leaves out; its
11
+ // facts' own firings are replayed separately. Nothing is searched for.
14
12
  //
15
13
  // The order of derived facts cannot be checked this way, so a collection or
16
- // a once/1 whose answers rest on a listing stays an obligation, and so does a
17
- // boundary whose search reaches rule templates or inspection.
14
+ // a once/1 whose answers rest on a listing cannot be established.
18
15
  import { PRIMITIVE_KEYS, primitive } from './builtins.js';
19
16
  import { freshClause, sameVariant, text, variant } from './common.js';
20
17
  import { INSPECTION_KEYS } from './inspection.js';
18
+ import { Lettering, write } from './writer.js';
21
19
  import {
22
- Env, EyemindError, Struct, Var, copyResolved, deref, flattenConjunction, freshTerm, identity, isCallable, isGround, isTerm, key,
23
- isCollection, isGroundButAnonymous, listFromItems, sortCollected, unify, variables,
20
+ Env, EyemindError, Struct, Var, copyResolved, deref, flattenConjunction, freshTerm, identity, isCallable, isGround, key,
21
+ isGroundButAnonymous, listFromItems, sortCollected, unify, variables,
24
22
  } from './terms.js';
25
23
 
26
- // A search the certificate cannot vouch for: its boundary stays an obligation.
24
+ // Terms as a failure message shows them, variables lettered A, B, ... across
25
+ // them all.
26
+ function shown(...terms) {
27
+ const lettering = new Lettering(true);
28
+ return terms.map((term) => write(term, null, lettering));
29
+ }
30
+
31
+ // A search the certificate cannot establish.
27
32
  export class Unsettled extends Error {}
28
33
 
29
- // What one expansion relied on: the tables it read, the listings it read and
30
- // the tables whose answer order it needed.
34
+ // What one expansion relied on: the tables it read, the listings it read,
35
+ // the tables whose answer order it needed, and whether it read the source
36
+ // rule catalogue or a derived pattern, the only sources of the variables a
37
+ // derived pattern keeps.
31
38
  export class Reliance {
32
39
  constructor(ordered = false) {
33
40
  this.tables = new Set();
34
41
  this.listings = new Set();
35
42
  this.ordered = new Set();
36
43
  this.inner = ordered ? 1 : 0;
44
+ this.inspected = false;
37
45
  }
38
46
  }
39
47
 
40
- // Whether term is an instance of pattern, whose variables are its own.
41
- function instanceOf(term, pattern) {
42
- const env = new Env();
43
- return unify(pattern, term, env) && variant(copyResolved(term, env)) === variant(term);
44
- }
45
-
46
48
  // How a listing identifies a fact: a ground fact by identity, a derived
47
49
  // pattern up to the renaming of its variables (Section 6.3).
48
50
  function listedKey(fact) {
@@ -70,61 +72,42 @@ export function forwardKeys(program) {
70
72
  return keys;
71
73
  }
72
74
 
73
- // Settles boundaries against a source of certificate statements:
74
- // answers(call) gives the answers listed for a call, or null; facts(goalKey)
75
- // the facts listed for a predicate forward rules derive, or null; and
76
- // supported(fact) whether the proof has a step for a listed fact. Tables and
77
- // listings are checked once, however many boundaries rest on them.
75
+ // Answers calls from a source of certificate statements: answers(call)
76
+ // gives the answers listed for a call, or null; facts(goalKey) the facts
77
+ // listed for a relation forward rules derive, or null. Calls and answers are
78
+ // compared up to renaming that keeps anonymous variables anonymous, since a
79
+ // named unbound variable makes a negation an error. Tables and listings are
80
+ // checked once, however many calls rest on them.
78
81
  export class Settler {
79
- constructor(program, source, operational = false) {
82
+ constructor(program, source) {
80
83
  this.program = program;
81
84
  this.source = source;
82
85
  this.derivedKeys = forwardKeys(program);
83
86
  this.tables = new Map();
84
87
  this.listings = new Map();
85
88
  this.serial = 0;
86
- this.operational = operational;
87
- this.variant = (term) => variant(term, operational);
89
+ this.variant = (term) => variant(term, true);
88
90
  }
89
91
 
90
- // All answers of an original call, rather than a final substituted step.
91
- // This is the C10 root; inner calls still come only from the certificate.
92
+ // Every answer of a call, as its search finds them with the bindings it
93
+ // has when it runs; inner calls come only from the certificate. The
94
+ // outcome: status 'settled', 'unsettled' or 'failed', the failures as
95
+ // [detail, term] pairs, the answers, the tables and listings consulted,
96
+ // and whether the search read inspected rules or derived patterns.
92
97
  answers(call) {
93
- return this.settle(new Struct('answers', [call]));
94
- }
95
-
96
- // The outcome for one negation or collection: status 'settled',
97
- // 'unsettled' or 'failed', the failures as [detail, term] pairs, whether the
98
- // only failure is the boundary's own result, and the tables and listings it
99
- // rests on.
100
- settle(boundary) {
101
- const collecting = isCollection(boundary);
102
- const sorting = isTerm(boundary, 'findall_sorted', 3);
103
- const answering = isTerm(boundary, 'answers', 1);
104
- const goal = collecting ? boundary.args[1] : boundary.args[0];
105
- // A sorted collection of ground items depends on its answers, not their
106
- // order, so it does not need the order a listing cannot show.
107
- const root = new Reliance(collecting && !sorting);
108
- const outcome = { status: 'settled', failures: [], boundaryOnly: false, tables: [], listings: [] };
109
- let found = [];
98
+ const root = new Reliance();
99
+ const outcome = { status: 'settled', failures: [], tables: [], listings: [], inspected: false };
100
+ const found = [];
110
101
  try {
111
102
  const env = new Env();
112
- const copied = freshTerm(collecting ? new Struct('-', [boundary.args[0], goal]) : goal, `root${++this.serial}`);
113
- const [template, searched] = collecting ? copied.args : [answering ? copied : null, copied];
114
- for (const _ of this.solve(searched, env, root)) { // eslint-disable-line no-unused-vars
115
- found.push(collecting || answering ? freshTerm(copyResolved(template, env), `item${++this.serial}`) : null);
116
- if (!collecting && !answering) break;
103
+ const copied = freshTerm(call, `root${++this.serial}`);
104
+ for (const _ of this.solve(copied, env, root)) { // eslint-disable-line no-unused-vars
105
+ found.push(freshTerm(copyResolved(copied, env), `item${++this.serial}`));
117
106
  }
118
107
  } catch (error) {
119
108
  if (error instanceof Unsettled) return { ...outcome, status: 'unsettled' };
120
109
  if (!(error instanceof EyemindError)) throw error;
121
- outcome.failures.push([`search certificate leads to an error: ${error.message}`, boundary]);
122
- found = null;
123
- }
124
- if (sorting && found !== null) {
125
- // Items equal up to their variables keep their search order.
126
- if (!found.every((item) => isGround(item))) for (const item of root.tables) root.ordered.add(item);
127
- found = sortCollected(found);
110
+ outcome.failures.push([`the search of ${shown(call)} leads to an error: ${error.message}`, call]);
128
111
  }
129
112
  let unsettled = false;
130
113
  const tables = new Set();
@@ -140,6 +123,7 @@ export class Settler {
140
123
  seen.add(entryKey);
141
124
  const entry = fromTable ? this.checkTable(entryKey) : this.checkListing(entryKey);
142
125
  if (entry.unsettled) unsettled = true;
126
+ if (fromTable && entry.reliance.inspected) outcome.inspected = true;
143
127
  if (entry.failure !== null) {
144
128
  // A table or listing that fails is reported for the first boundary
145
129
  // resting on it; later ones fail with it, without repeating it.
@@ -155,21 +139,12 @@ export class Settler {
155
139
  outcome.listings = [...listings];
156
140
  const circular = this.checkDependencies(tables);
157
141
  if (circular !== null) {
158
- outcome.failures.push([`search certificate is circular at ${text(circular.call)}`, circular.call]);
142
+ outcome.failures.push([`the call tables are circular at ${shown(circular.call)}`, circular.call]);
159
143
  }
144
+ if (root.inspected) outcome.inspected = true;
160
145
  if (outcome.failures.length || outcome.failed) return { ...outcome, status: 'failed' };
161
146
  if (unsettled || [...ordered].some((item) => !this.exactness.get(item))) return { ...outcome, status: 'unsettled' };
162
- if (answering) return { ...outcome, answers: found };
163
- if (!collecting && found.length) {
164
- outcome.failures.push([`absence contradicted by its search: ${text(boundary)}`, boundary]);
165
- return { ...outcome, status: 'failed', boundaryOnly: true };
166
- }
167
- // A collection's list is the search's, renamed apart, bound perhaps by
168
- // later goals. A step shows its goal as the whole solution left it, so a
169
- // goal a later goal instantiated may no longer be the goal searched: a
170
- // list that disagrees is left to the evidence rather than refuted.
171
- if (collecting && !instanceOf(boundary.args[2], listFromItems(found))) return { ...outcome, status: 'unsettled' };
172
- return outcome;
147
+ return { ...outcome, answers: found };
173
148
  }
174
149
 
175
150
  // Each solution of a goal, its bindings made in env and undone before the
@@ -188,11 +163,9 @@ export class Settler {
188
163
  } else if (goalKey === 'call/1') {
189
164
  yield* this.solve(goal.args[0], env, reliance);
190
165
  } else if (goalKey === 'once/1' || goalKey === 'not/1') {
191
- // A negation's unbound variables stand for any value, as anonymous
192
- // ones do; a reasoner would not have run one with a named variable.
193
166
  const once = goalKey === 'once/1';
194
- if (this.operational && !once && !isGroundButAnonymous(goal.args[0], env)) {
195
- throw new EyemindError('call fidelity: negation has an unbound named variable');
167
+ if (!once && !isGroundButAnonymous(goal.args[0], env)) {
168
+ throw new EyemindError('negation has an unbound named variable');
196
169
  }
197
170
  if (once) reliance.inner++;
198
171
  const inner = this.solve(goal.args[0], env, reliance);
@@ -225,7 +198,7 @@ export class Settler {
225
198
  } else if (PRIMITIVE_KEYS.has(goalKey)) {
226
199
  // Relative names of unbound variables are not preserved by alpha
227
200
  // renaming of a table. A name-dependent comparison needs more evidence.
228
- if (this.operational && goalKey === 'compare/3' &&
201
+ if (goalKey === 'compare/3' &&
229
202
  (!isGround(goal.args[1], env) || !isGround(goal.args[2], env))) throw new Unsettled();
230
203
  for (const _ of primitive(goal, env)) { // eslint-disable-line no-unused-vars
231
204
  yield;
@@ -234,6 +207,7 @@ export class Settler {
234
207
  } else if (INSPECTION_KEYS.has(goalKey)) {
235
208
  // The catalogue of source rules, in source order, each renamed apart:
236
209
  // its variables are scoped pattern variables (Section 6.3).
210
+ reliance.inspected = true;
237
211
  for (const source of this.program.inspections.get(goalKey) || []) {
238
212
  if (unify(goal, freshTerm(source.term, `inspect${++this.serial}`), env)) yield;
239
213
  env.undo(mark);
@@ -273,6 +247,7 @@ export class Settler {
273
247
  reliance.listings.add(goalKey);
274
248
  for (const fact of facts) {
275
249
  // A derived pattern is freshened at every use.
250
+ if (!isGround(fact)) reliance.inspected = true;
276
251
  if (unify(call, isGround(fact) ? fact : freshTerm(fact, `pattern${++this.serial}`), env)) yield;
277
252
  env.undo(mark);
278
253
  }
@@ -352,17 +327,20 @@ export class Settler {
352
327
  for (const _ of this.expand(call, env, entry.reliance)) found.push(copyResolved(call, env)); // eslint-disable-line no-unused-vars
353
328
  const listed = entry.answers;
354
329
  let i = 0;
355
- while (i < found.length && i < listed.length && sameVariant(found[i], listed[i], this.operational)) i++;
330
+ while (i < found.length && i < listed.length && sameVariant(found[i], listed[i], true)) i++;
356
331
  if (i < found.length && i < listed.length) {
357
- entry.failure = `the search of ${text(entry.call)} answers ${text(found[i])} where its table lists ${text(listed[i])}`;
332
+ const [call, answer, listing] = shown(entry.call, found[i], listed[i]);
333
+ entry.failure = `the search of ${call} answers ${answer} where its table lists ${listing}`;
358
334
  } else if (i < found.length) {
359
- entry.failure = `the table of ${text(entry.call)} leaves out the answer ${text(found[i])}`;
335
+ const [call, answer] = shown(entry.call, found[i]);
336
+ entry.failure = `the table of ${call} leaves out the answer ${answer}`;
360
337
  } else if (i < listed.length) {
361
- entry.failure = `the table of ${text(entry.call)} lists ${text(listed[i])}, which its search does not answer`;
338
+ const [call, listing] = shown(entry.call, listed[i]);
339
+ entry.failure = `the table of ${call} lists ${listing}, which its search does not answer`;
362
340
  }
363
341
  } catch (error) {
364
342
  if (error instanceof Unsettled) entry.unsettled = true;
365
- else if (error instanceof EyemindError) entry.failure = `the search of ${text(entry.call)} leads to an error: ${error.message}`;
343
+ else if (error instanceof EyemindError) entry.failure = `the search of ${shown(entry.call)} leads to an error: ${error.message}`;
366
344
  else {
367
345
  // Checked again once whatever interrupted it is dealt with.
368
346
  entry.checked = false;
@@ -372,8 +350,8 @@ export class Settler {
372
350
  return entry;
373
351
  }
374
352
 
375
- // A listing holds when each fact has a step and no forward rule derives,
376
- // under the listed facts, a fact of that relation it leaves out.
353
+ // A listing holds when its facts are of its relation and no forward rule
354
+ // derives, under the listed facts, a fact of that relation it leaves out.
377
355
  checkListing(goalKey) {
378
356
  const entry = this.listings.get(goalKey);
379
357
  if (entry.checked) return entry;
@@ -383,14 +361,13 @@ export class Settler {
383
361
  try {
384
362
  for (const fact of entry.facts) {
385
363
  if (!isCallable(fact) || key(fact) !== goalKey) {
386
- entry.failure = `derived facts of ${goalKey} list ${text(fact)}`;
364
+ entry.failure = `derived facts of ${goalKey} list ${shown(fact)}`;
387
365
  entry.subject = fact;
388
366
  return entry;
389
367
  }
390
368
  // Only a program that inspects source rules derives patterns.
391
- if (!isGround(fact) && !this.program.inspectionEnabled) throw new Unsettled();
392
- if (!this.source.supported(fact)) {
393
- entry.failure = `derived fact without a step: ${text(fact)}`;
369
+ if (!isGround(fact) && !this.program.inspectionEnabled) {
370
+ entry.failure = `derived facts of ${goalKey} list ${shown(fact)}, which is not ground`;
394
371
  entry.subject = fact;
395
372
  return entry;
396
373
  }
@@ -408,7 +385,7 @@ export class Settler {
408
385
  ((rule.parentId !== null || rule.templates.length) && rule.witnessNames.length)) throw new Unsettled();
409
386
  const missing = this.closes(rule, goalKey, listed, entry.reliance);
410
387
  if (missing !== null) {
411
- entry.failure = `derived facts of ${goalKey} leave out ${text(missing)}, which clause ${rule.id} derives`;
388
+ entry.failure = `derived facts of ${goalKey} leave out ${shown(missing)}, which clause ${rule.id} derives`;
412
389
  entry.subject = missing;
413
390
  return entry;
414
391
  }
@@ -449,9 +426,10 @@ export class Settler {
449
426
  }
450
427
  for (const item of heads) {
451
428
  const conclusion = copyResolved(item, env);
452
- // Only variables an inspection supplied stay free in a conclusion;
453
- // any other would have been bound to a Skolem term.
454
- if ([...variables(conclusion).keys()].some((name) => !/#(?:inspect|pattern)\d+$/.test(name))) throw new Unsettled();
429
+ // Only a program that inspects source rules derives patterns; whether
430
+ // a listed pattern's variables came from an inspection, rather than
431
+ // standing for a Skolem term, its replay decides.
432
+ if (!isGround(conclusion) && !this.program.inspectionEnabled) throw new Unsettled();
455
433
  const conclusionId = listedKey(conclusion);
456
434
  if (!listed.has(conclusionId) && !(isGround(conclusion) && this.program.groundFactKeys.has(conclusionId))) return conclusion;
457
435
  }
@@ -461,7 +439,8 @@ export class Settler {
461
439
  }
462
440
 
463
441
  // Check the table dependency graph once: detect a cycle, or cache in
464
- // dependency order which tables are independent of forward listings.
442
+ // dependency order which tables have certified answer order: those
443
+ // independent of forward listings, and those with one distinct answer.
465
444
  checkDependencies(tables) {
466
445
  const exact = this.exactness ??= new Map();
467
446
  const open = new Set();
@@ -473,8 +452,11 @@ export class Settler {
473
452
  while (stack.length) {
474
453
  const top = stack[stack.length - 1];
475
454
  if (top[2] >= top[1].length) {
476
- const reliance = this.tables.get(top[0]).reliance;
477
- exact.set(top[0], !reliance.listings.size && top[1].every((item) => exact.get(item)));
455
+ const entry = this.tables.get(top[0]);
456
+ // A table with at most one distinct answer has that order however
457
+ // the facts it rests on were published.
458
+ exact.set(top[0], (!entry.reliance.listings.size && top[1].every((item) => exact.get(item))) ||
459
+ new Set(entry.answers.map((answer) => variant(answer, true))).size <= 1);
478
460
  open.delete(top[0]);
479
461
  stack.pop();
480
462
  continue;
package/src/common.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // Helpers shared by the engine and the proof checker.
2
- import { Struct, Var, deref, freshTerm, isAnonymous, unify } from './terms.js';
2
+ import { Env, Struct, Var, deref, freshTerm, isAnonymous, unify } from './terms.js';
3
3
  import { write } from './writer.js';
4
4
 
5
5
  // The canonical spelling of a term, which also serves as its identity.
@@ -242,3 +242,38 @@ export function variant(term, anonymous = false) {
242
242
  }
243
243
  return out.join('\u0001');
244
244
  }
245
+
246
+ export function sameValue(a, b) {
247
+ // Identical means the same canonical text: 0.0 and -0.0 differ.
248
+ return typeof a === 'number' ? Object.is(a, b) : a === b;
249
+ }
250
+
251
+ // Whether term, read through env, is exactly target, variables included.
252
+ export function resolvesTo(term, env, target) {
253
+ const pending = [term, target];
254
+ while (pending.length) {
255
+ const expected = pending.pop();
256
+ let actual = pending.pop();
257
+ if (actual instanceof Var) actual = deref(actual, env);
258
+ if (actual instanceof Struct) {
259
+ if (!(expected instanceof Struct) || actual.name !== expected.name || actual.args.length !== expected.args.length) {
260
+ return false;
261
+ }
262
+ for (let i = actual.args.length - 1; i >= 0; i--) pending.push(actual.args[i], expected.args[i]);
263
+ } else if (actual instanceof Var) {
264
+ if (!(expected instanceof Var) || actual.name !== expected.name) return false;
265
+ } else if (expected instanceof Struct || expected instanceof Var || typeof actual !== typeof expected ||
266
+ !sameValue(actual, expected)) {
267
+ return false;
268
+ }
269
+ }
270
+ return true;
271
+ }
272
+
273
+ // Whether goal is an instance of pattern: a copy of pattern renamed with
274
+ // suffix matches goal without binding any variable of goal.
275
+ export function isInstance(goal, pattern, suffix) {
276
+ const renamed = freshTerm(pattern, suffix);
277
+ const env = new Env();
278
+ return unify(renamed, goal, env) && resolvesTo(renamed, env, goal);
279
+ }