eyemind 0.5.30 → 0.5.31

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/README.md CHANGED
@@ -7,7 +7,7 @@ eyemind is a **JavaScript rule language** with forward and backward reasoning an
7
7
 
8
8
  [Playground](https://eyereasoner.github.io/eyemind/playground/) · [Specification](https://eyereasoner.github.io/eyemind/SPEC) · [Conformance](https://eyereasoner.github.io/eyemind/conformance/) · [Examples](https://eyereasoner.github.io/eyemind/examples/)
9
9
 
10
- The playground runs programs in your browser; the specification defines the language, its canonical text, the proof format and the C1–C10 checks. The examples are 135 runnable programs, each with a card deck and saved conclusions, proofs and check reports. The conformance suite has 1388 cases that test language and proof behavior through a command adapter, together with implementation interface checks; run it [in your browser](https://eyereasoner.github.io/eyemind/playground/conformance).
10
+ The playground runs programs in your browser; the specification defines the language, its canonical text, the proof format and the C1–C10 checks. The examples are 135 runnable programs, each with a card deck and saved conclusions, proofs and check reports. The conformance suite has 1390 cases that test language and proof behavior through a command adapter, together with implementation interface checks; run it [in your browser](https://eyereasoner.github.io/eyemind/playground/conformance).
11
11
 
12
12
  ## Contents
13
13
 
@@ -562,7 +562,7 @@ A negation `not(G)` concludes from what is *absent* and a collection `findall(T,
562
562
  - **Negate only what is bound.** The variables of `not(G)` must be bound when it runs; write `not(q(X, _))` for "no value at all".
563
563
  - **Check the search, not just its result.** A proof ends with a search certificate: `searched(Call, Answers)` lists each call's answers and `derived(Pattern, Facts)` each consulted relation. The checker expands each call one level against the program, so a wrong table shows up as a disagreement.
564
564
  - **Say what was taken on trust.** Anything the certificate cannot settle becomes an obligation, and evidence in the proof can still refute it (C6).
565
- - **Certify the original questions.** Supported, closed listings establish the original calls, and that the claims are all their answers, when no rule they depend on can observe bindings or evaluation order. A mode analysis checks this: primitives such as arithmetic run with their inputs bound, negations with their variables bound, and `once` and `findall` bind nothing other goals use. Where it does not apply, as for tests of whether a variable is bound, the checker replays each derived fact's recorded firing in source order instead. A proof within these bounds can be `checked` with no obligation, even under `--strict-proof`. Rules generated by templates are checked through their instances, and source rule inspection through the program's catalogue of rules. A `findall_sorted` of ground items is certified from the set of derived facts alone. `findall` and first answers over derived facts, whose order a listing cannot show, and `restricted` rules with new witnesses keep an obligation.
565
+ - **Certify the original questions.** Closed listings establish the original calls and all their answers when every listed fact's recorded firing replays. The checker follows the source rule and the recorded premise evidence in order, starting with no bindings, so a state test sees the bindings of its actual call and `once` takes the actual first answer. It does not call the reasoner or supply missing evidence. Rules generated by templates are checked through their instances, and source rule inspection through the program's catalogue. A proof within these bounds can be `checked` with no obligation, even under `--strict-proof`. A `findall_sorted` of ground items is certified from the set of derived facts alone. `findall` and first answers over derived facts, whose order a listing cannot show, and `restricted` rules with new witnesses keep an obligation.
566
566
 
567
567
  ## Checking the translation
568
568
 
package/SPEC.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  ```text
4
4
  Title: The eyemind Rule Language and Proof Format
5
- Version: eyemind 0.5.30
5
+ Version: eyemind 0.5.31
6
6
  ```
7
7
 
8
8
  This document specifies the syntax and meaning of eyemind programs and data
@@ -1666,9 +1666,9 @@ certified answer set, and every answer in it is claimed.
1666
1666
 
1667
1667
  For a program with negation, "follows" is relative to the facts the
1668
1668
  certificate lists: C9 establishes that they are supported by steps, closed
1669
- under the forward rules and consistent with every settled negation. In the
1670
- ground relational fragment of [Section 11.13](#1113-c10-call-fidelity), a stratified or
1671
- chain-stratified program has only one such result ([Section 7.4](#74-negation-and-collection)). With restricted
1669
+ under the forward rules and consistent with every settled negation. Under
1670
+ the call-fidelity requirements of [Section 11.13](#1113-c10-call-fidelity),
1671
+ a stratified or chain-stratified program has only one such result ([Section 7.4](#74-negation-and-collection)). With restricted
1672
1672
  witnesses, different lean results can have these properties. A claim whose
1673
1673
  forward dependency closure includes a restricted rule with head-only
1674
1674
  variables therefore retains a call-fidelity obligation, and a strict check
@@ -2064,6 +2064,10 @@ including those consulted transitively by table expansions and listing
2064
2064
  closure checks. No table it rests on may depend on itself through the
2065
2065
  tables consulted by its expansion.
2066
2066
 
2067
+ The same dependency graph establishes **answer order**. A table has
2068
+ certified answer order exactly when its expansion consults no forward
2069
+ listing and every table it depends on has certified answer order.
2070
+
2067
2071
  **Supporting and closing listings.** Every listed fact MUST have a step,
2068
2072
  have the listing's name and arity, and be ground, unless the program
2069
2073
  inspects source rules and the fact is a derived pattern
@@ -2095,13 +2099,12 @@ requires:
2095
2099
 
2096
2100
  **Certificate limits.** Settlement also requires all of the following:
2097
2101
 
2098
- - No `findall`, `once`, or `findall_sorted` collecting an item that is not
2099
- ground, in the boundary's search, a relied-on table or a closure check,
2100
- uses a table whose answers rest on a forward listing. This format checks
2101
- support and closure of derived facts, but cannot establish their
2102
- publication order for order-sensitive operations. A `findall_sorted` of
2103
- ground items depends on the solutions and how often each occurs, not on
2104
- their order.
2102
+ - Every table used by `findall` or `once`, or by `findall_sorted` whose
2103
+ results include a nonground item, MUST have certified answer order. This
2104
+ applies in the boundary's search, relied-on tables and closure checks.
2105
+ Support and closure do not establish the publication order of forward
2106
+ facts. A `findall_sorted` of ground items depends on the solutions and
2107
+ how often each occurs, not on their order.
2105
2108
  - No consulted listing's relation is concluded by a forward rule within a
2106
2109
  template's scope ([Section 6.2](#62-inline-rule-templates)) that
2107
2110
  introduces witnesses, or whose generators have a guard or introduce
@@ -2200,9 +2203,9 @@ with these differences:
2200
2203
  4. A comparison `compare/3` with either compared term nonground is not
2201
2204
  supported by this certificate format: alpha renaming of a table need
2202
2205
  not preserve the order of variable names. Such a search leaves call fidelity unproved.
2203
- 5. A consulted forward listing MUST have a dependency closure in the
2204
- supported fragment described below. A final listing alone MUST NOT certify
2205
- binding-sensitive or order-sensitive forward firings outside that fragment.
2206
+ 5. Each fact of every consulted forward listing MUST replay its recorded
2207
+ firing as specified below. Support and closure alone MUST NOT certify
2208
+ bindings or control choices that the recorded firing never makes.
2206
2209
 
2207
2210
  For the `once` example in [Section 11.2](#112-operational-query-fidelity),
2208
2211
  the call certificate contains:
@@ -2219,80 +2222,21 @@ first, and `once` selects it. Thus `q('a')` is an answer and `q('b')` is
2219
2222
  excluded. Substituting `called(p('b'), [p('b')])` cannot establish the
2220
2223
  different call `p(X)`.
2221
2224
 
2222
- **Supported forward listings.** A listing supports C10 when a search of
2223
- each rule body it depends on, in source order, finds exactly the ground
2224
- instances of that body that hold. Its steps, whose primitives C5 re-decides
2225
- on their ground instances, then show firings that a search makes. This holds
2226
- when no goal can observe the bindings or the order in which it runs. The
2227
- checker establishes it by a **mode analysis** of the rules the listing
2228
- depends on. A **mode** of a call gives, for each argument, whether it is
2229
- ground when the call runs: an argument is ground when every variable in it
2230
- is **grounded** at that point.
2231
-
2232
- The analysis starts from the listed relation and its forward rules, and
2233
- follows each ordinary body call, inside a negation or not, to the called
2234
- relation in the mode of that call: its forward rules once, and its backward
2235
- rules once in each mode. A forward rule's body starts with no grounded
2236
- variable. A backward rule's body starts with the variables of the head
2237
- arguments that are ground in the mode. Body goals are taken in order, each
2238
- with the variables grounded before it:
2239
-
2240
- - `'true'` grounds nothing. Conjunction accumulates the grounded variables
2241
- of its parts. Disjunction grounds only those grounded by both
2242
- alternatives. `call(G)` is `G`.
2243
- - A call to an ordinary relation grounds its variables when every source
2244
- fact of the relation is ground once the arguments ground in the mode are
2245
- unified with it, and the relation is not **loose** in that mode;
2246
- otherwise it grounds nothing.
2247
- - A negation grounds nothing. Each of its variables other than anonymous
2248
- ones MUST be grounded before it, and it MUST NOT contain a negation.
2249
- - `once(G)` grounds nothing. `G` MUST satisfy these conditions. Each named
2250
- variable of `G` that occurs elsewhere in the clause MUST be grounded before
2251
- it, so the choice of a first answer binds nothing another goal uses.
2252
- - A collection `findall(T, G, L)` or `findall_sorted(T, G, L)` follows the
2253
- same rule for `T` and `G`. It grounds the variables of `L` when `G`
2254
- grounds every variable of `T`.
2255
- - A primitive whose variables are all grounded before it is a test, and
2256
- grounds nothing. `unify/2` with one side ground grounds the other, and
2257
- with neither ground grounds nothing. Otherwise the primitive MUST be
2258
- called in one of the modes below, its input arguments ground, and it
2259
- grounds its variables.
2260
- - Source inspection, templates, captures and restricted rules are not
2261
- supported. A restricted rule's guard is a negation, but which firings the
2262
- rule makes can depend on the order of rule applications.
2263
-
2264
- After its body, every head variable of a forward rule MUST be grounded or
2265
- be a head-only witness checked by C8. If a head variable of a backward rule
2266
- is not grounded, the relation is loose in that mode, and the analysis
2267
- starts again with that call grounding nothing.
2268
-
2269
- | Primitive | Inputs → outputs |
2270
- | --- | --- |
2271
- | `is/2` | expression → result |
2272
- | `compare/3` | both compared terms → order |
2273
- | `atom_chars/2`, `atom_codes/2` | atom → list, or list → atom |
2274
- | `number_chars/2` | list → number |
2275
- | `atom_length/2`, `atom_lower/2`, `atom_upper/2`, `term_text/2` | first → second |
2276
- | `atom_concat/3` | both parts → whole, or whole → both parts |
2277
- | `regex_find/3`, `digest/3` | first two → third |
2278
- | `float64/4` | first three → fourth |
2279
-
2280
- In each listed mode, a call with ground inputs has exactly the solutions
2281
- whose ground instances C5 re-decides as holding. `number_chars/2` re-decides
2282
- a ground instance by reading its characters, so only that direction is
2283
- listed. A host-math result accepted by C5 only within its tolerance
2284
- ([Section 11.8](#118-c5-re-decision)) need not be the result a search
2285
- finds. A proof with such a step therefore supports no listing for C10 by
2286
- this analysis.
2287
-
2288
- **Replayed listings.** A listing the mode analysis does not support still
2289
- supports C10 when every fact of every consulted listing **replays**. A fact
2290
- replays when its step cites a forward rule that is not restricted, does
2291
- not introduce witnesses within a template's scope, and, if appended by a
2292
- template, has all its enclosing generators in the program, none with a
2293
- guard or witnesses; and when a search of that rule's body in
2294
- source order, starting with no bindings, solves each body goal as the
2295
- step's corresponding use records:
2225
+ **Replaying forward listings.** In addition to the support and closure
2226
+ checks of C9, every fact of every consulted listing MUST replay. Replay
2227
+ follows the source rule and the step's uses in order, starting with no
2228
+ bindings. It checks the bindings at each premise, rather than assuming
2229
+ the proof's final substitution was already available. It MUST NOT call a
2230
+ reasoner or supply a missing derivation.
2231
+
2232
+ A listing with a fact that does not replay is unsupported for C10 and
2233
+ leaves the obligations specified below. C1–C9 still check its steps normally.
2234
+
2235
+ A fact's step MUST cite a forward rule that is not restricted and introduces
2236
+ no witnesses within a template's scope. For a rule appended by a template,
2237
+ every enclosing generator MUST belong to the program and have no guard or
2238
+ witnesses. Replay checks each body goal against the step's corresponding
2239
+ use as follows:
2296
2240
 
2297
2241
  - A primitive runs on the bindings of that point of the search. Its first
2298
2242
  solution under which the goal can still unify with the use is taken.
@@ -2313,8 +2257,8 @@ step's corresponding use records:
2313
2257
  against its step's uses. For a backward rule appended by a template, the
2314
2258
  generator's part of the body replays first, before the head meets the
2315
2259
  goal, and the template's part after. A use with no step is unified with a source fact
2316
- of the relation, renamed apart. A replay that meets the same use under
2317
- the same call again does not replay.
2260
+ of the relation, renamed apart. A cycle through recorded uses does not
2261
+ replay, as required by C2.
2318
2262
  - An inspection follows its use's `source(N)` step: rule `N` of the
2319
2263
  catalogue, renamed apart, is unified with the goal.
2320
2264
  - After each goal, the goal MUST still unify with its use, since a step
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "eyemind",
3
- "version": "0.5.30",
3
+ "version": "0.5.31",
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/closure.js CHANGED
@@ -153,12 +153,12 @@ export class Settler {
153
153
  }
154
154
  outcome.tables = [...tables];
155
155
  outcome.listings = [...listings];
156
- const circular = this.circularity(tables);
156
+ const circular = this.checkDependencies(tables);
157
157
  if (circular !== null) {
158
158
  outcome.failures.push([`search certificate is circular at ${text(circular.call)}`, circular.call]);
159
159
  }
160
160
  if (outcome.failures.length || outcome.failed) return { ...outcome, status: 'failed' };
161
- if (unsettled || [...ordered].some((item) => !this.exact(item))) return { ...outcome, status: 'unsettled' };
161
+ if (unsettled || [...ordered].some((item) => !this.exactness.get(item))) return { ...outcome, status: 'unsettled' };
162
162
  if (answering) return { ...outcome, answers: found };
163
163
  if (!collecting && found.length) {
164
164
  outcome.failures.push([`absence contradicted by its search: ${text(boundary)}`, boundary]);
@@ -460,52 +460,32 @@ export class Settler {
460
460
  return null;
461
461
  }
462
462
 
463
- // The first table found on a cycle of tables, or null: a search that met
464
- // its own call again would never have finished.
465
- circularity(tables) {
466
- const state = new Map();
463
+ // Check the table dependency graph once: detect a cycle, or cache in
464
+ // dependency order which tables are independent of forward listings.
465
+ checkDependencies(tables) {
466
+ const exact = this.exactness ??= new Map();
467
+ const open = new Set();
468
+ const frame = (item) => [item, [...this.tables.get(item).reliance.tables], 0];
467
469
  for (const start of tables) {
468
- if (state.has(start)) continue;
469
- const stack = [[start, [...this.tables.get(start).reliance.tables], 0]];
470
- state.set(start, 'open');
470
+ if (exact.has(start)) continue;
471
+ const stack = [frame(start)];
472
+ open.add(start);
471
473
  while (stack.length) {
472
474
  const top = stack[stack.length - 1];
473
475
  if (top[2] >= top[1].length) {
474
- state.set(top[0], 'done');
476
+ const reliance = this.tables.get(top[0]).reliance;
477
+ exact.set(top[0], !reliance.listings.size && top[1].every((item) => exact.get(item)));
478
+ open.delete(top[0]);
475
479
  stack.pop();
476
480
  continue;
477
481
  }
478
482
  const next = top[1][top[2]++];
479
- if (state.get(next) === 'open') return this.tables.get(next);
480
- if (state.has(next)) continue;
481
- state.set(next, 'open');
482
- const entry = this.tables.get(next);
483
- stack.push([next, entry.reliance ? [...entry.reliance.tables] : [], 0]);
483
+ if (open.has(next)) return this.tables.get(next);
484
+ if (exact.has(next)) continue;
485
+ open.add(next);
486
+ stack.push(frame(next));
484
487
  }
485
488
  }
486
489
  return null;
487
490
  }
488
-
489
- // Whether a table's answers keep the order a search finds them in: none of
490
- // them, through any table it rests on, came from a listing.
491
- exact(callKey) {
492
- const memo = this.exactness ??= new Map();
493
- if (memo.has(callKey)) return memo.get(callKey);
494
- // Finish each dependency before caching its parent. Reversing discovery
495
- // order is insufficient when two branches share a dependency.
496
- const frame = (item) => [item, [...this.tables.get(item).reliance.tables], 0];
497
- const stack = [frame(callKey)];
498
- while (stack.length) {
499
- const top = stack[stack.length - 1];
500
- if (top[2] < top[1].length) {
501
- const next = top[1][top[2]++];
502
- if (!memo.has(next)) stack.push(frame(next));
503
- continue;
504
- }
505
- const reliance = this.tables.get(top[0]).reliance;
506
- memo.set(top[0], !reliance.listings.size && top[1].every((item) => memo.get(item)));
507
- stack.pop();
508
- }
509
- return memo.get(callKey);
510
- }
511
491
  }
package/src/engine.js CHANGED
@@ -3,7 +3,7 @@ import { PRIMITIVE_KEYS, STATE_TESTS, primitive } from './builtins.js';
3
3
  import { Reliance, Settler, Unsettled } from './closure.js';
4
4
  import { freshClause, matchHead, renaming, text, variant } from './common.js';
5
5
  import { goalTerm, subgoals } from './goals.js';
6
- import { callQuestions, positiveListings, replayed } from './fidelity.js';
6
+ import { callQuestions, replayed } from './fidelity.js';
7
7
  import { INSPECTION_KEYS } from './inspection.js';
8
8
  import { checkRendered, clauseDisplay, renderProof } from './proof.js';
9
9
  import { CONTROL_KEYS, Program } from './program.js';
@@ -1156,7 +1156,7 @@ function certify(solver, boundaries, operational = false) {
1156
1156
  }
1157
1157
  }
1158
1158
  // The recorded derivation of a listed fact or one of its premises, for the
1159
- // replay that supports a listing beyond the mode analysis.
1159
+ // replay that supports the original calls.
1160
1160
  let recorded = null;
1161
1161
  const stepOf = (goal) => {
1162
1162
  if (recorded === null) {
@@ -1192,8 +1192,7 @@ function certify(solver, boundaries, operational = false) {
1192
1192
  }
1193
1193
  }
1194
1194
  }
1195
- if (outcome.status === 'settled' && (!operational || positiveListings(program, outcome.listings) ||
1196
- replayed(program, settler, outcome.listings, stepOf))) {
1195
+ if (outcome.status === 'settled' && (!operational || replayed(program, settler, outcome.listings, stepOf))) {
1197
1196
  for (const item of outcome.tables) tables.add(item);
1198
1197
  for (const item of outcome.listings) listings.add(item);
1199
1198
  } else if (outcome.status === 'failed' && solver.haltCode === null) {
package/src/fidelity.js CHANGED
@@ -8,8 +8,8 @@ import { freshClause, sameVariant, text, variant } from './common.js';
8
8
  import { goalTerm } from './goals.js';
9
9
  import { INSPECTION_KEYS } from './inspection.js';
10
10
  import {
11
- Env, EyemindError, Struct, Var, conjunction, copyResolved, deref, flattenConjunction, freshTerm, identity, isAnonymous, isCallable,
12
- isCollection, isGround, isTerm, key, listFromItems, unify, variables,
11
+ Env, EyemindError, Struct, conjunction, copyResolved, deref, flattenConjunction, freshTerm, identity, isCallable,
12
+ isGround, isTerm, key, listFromItems, unify, variables,
13
13
  } from './terms.js';
14
14
  import { Lettering, write } from './writer.js';
15
15
 
@@ -39,179 +39,6 @@ export function callQuestions(program, goals, claims) {
39
39
  });
40
40
  }
41
41
 
42
- // Primitives that compute their outputs from ground inputs, in each mode an
43
- // argument's positions of the inputs, then of the outputs. With its inputs
44
- // ground such a call has exactly the solutions whose ground instances hold,
45
- // re-decided as C5 re-decides them, so a search finds what C5 accepts.
46
- // number_chars/2 re-decides by reading its characters, so only that mode.
47
- const MODES = new Map([
48
- ['is/2', [[[1], [0]]]],
49
- ['compare/3', [[[1, 2], [0]]]],
50
- ['atom_chars/2', [[[0], [1]], [[1], [0]]]],
51
- ['atom_codes/2', [[[0], [1]], [[1], [0]]]],
52
- ['number_chars/2', [[[1], [0]]]],
53
- ['atom_length/2', [[[0], [1]]]],
54
- ['atom_lower/2', [[[0], [1]]]],
55
- ['atom_upper/2', [[[0], [1]]]],
56
- ['atom_concat/3', [[[0, 1], [2]], [[2], [0, 1]]]],
57
- ['regex_find/3', [[[0, 1], [2]]]],
58
- ['digest/3', [[[0, 1], [2]]]],
59
- ['term_text/2', [[[0], [1]]]],
60
- ['float64/4', [[[0, 1, 2], [3]]]],
61
- ]);
62
-
63
- // The variables of a head's arguments that a call in mode grounds.
64
- function inputs(head, mode) {
65
- const names = new Set();
66
- if (head instanceof Struct) {
67
- head.args.forEach((arg, i) => {
68
- if (mode[i] === 'g') for (const name of variables(arg).keys()) names.add(name);
69
- });
70
- }
71
- return names;
72
- }
73
-
74
- // How often each variable occurs in term, by name.
75
- function occurrences(term, counts = new Map()) {
76
- const pending = [term];
77
- while (pending.length) {
78
- const item = pending.pop();
79
- if (item instanceof Struct) pending.push(...item.args);
80
- else if (item instanceof Var) counts.set(item.name, (counts.get(item.name) || 0) + 1);
81
- }
82
- return counts;
83
- }
84
-
85
- // C9's support plus closure establishes the least ground model, and with
86
- // negations the one stable model of a stratified or chain-stratified
87
- // program, when a search of each rule body in source order finds exactly the
88
- // ground instances that hold: then the steps that support a listed fact,
89
- // re-decided on their ground instances, show a firing a search makes. That
90
- // holds when no goal observes bindings: each primitive runs with its inputs
91
- // ground, each negation with its named variables ground, and once/1 and
92
- // findall/3 bind nothing other goals use. A backward rule is analyzed for
93
- // each mode it is called in, the head arguments a call grounds being ground
94
- // on entry, and must ground the rest of its head. A relation with a
95
- // nonground source fact grounds nothing. Rules that observe bindings or
96
- // order, templates, and restricted rules, whose guard another order of
97
- // firings could decide otherwise, leave which firings occurred
98
- // unestablished: refuse that promise.
99
- export function positiveListings(program, listings) {
100
- // Calls, by relation and mode, found to answer with nonground terms; the
101
- // analysis starts again whenever it finds another, assuming fewer grounded.
102
- const loose = new Set();
103
- for (;;) {
104
- const result = groundedListings(program, listings, loose);
105
- if (result !== 'again') return result;
106
- }
107
- }
108
-
109
- function groundedListings(program, listings, loose) {
110
- // A listed relation and the forward rules concluding it, or a called
111
- // relation and its mode: 'g' for each argument ground at the call, else 'f'.
112
- const pending = listings.map((goalKey) => [goalKey, null]);
113
- const seen = new Set();
114
- // Whether every source fact of a relation is ground once a call in this
115
- // mode has unified it: only then does the call ground its arguments.
116
- const groundsFacts = (goalKey, mode) => !loose.has(`${goalKey} ${mode}`) &&
117
- (program.groups.get(goalKey) || []).every((clause) => clause.body.length ||
118
- [...variables(clause.head).keys()].every((name) => inputs(clause.head, mode).has(name)));
119
- let outside = null;
120
- // The variables of goal used elsewhere in the clause, other than in goal.
121
- const shared = (goal) => {
122
- const inside = occurrences(goal);
123
- return [...variables(goal)].filter(([name, variable]) => !isAnonymous(variable) && outside.get(name) > inside.get(name))
124
- .map(([name]) => name);
125
- };
126
- function bound(goal, grounded, negated = false) {
127
- if (goal === 'true') return grounded;
128
- if (isTerm(goal, 'and', 2) || isTerm(goal, 'or', 2)) {
129
- const left = bound(goal.args[0], grounded, negated);
130
- if (left === null) return null;
131
- const right = bound(goal.args[1], goal.name === 'and' ? left : grounded, negated);
132
- if (right === null) return null;
133
- return goal.name === 'and' ? right
134
- : new Set([...left].filter((name) => right.has(name)));
135
- }
136
- if (isTerm(goal, 'not', 1)) {
137
- if (negated) return null;
138
- for (const [name, variable] of variables(goal)) {
139
- if (!isAnonymous(variable) && !grounded.has(name)) return null;
140
- }
141
- return bound(goal.args[0], grounded, true) === null ? null : grounded;
142
- }
143
- if (isTerm(goal, 'call', 1)) return bound(goal.args[0], grounded, negated);
144
- // A first answer or a collection binds nothing it shares, so which answer
145
- // came first, or which bindings a later goal makes, cannot matter.
146
- if (isTerm(goal, 'once', 1)) {
147
- const inner = bound(goal.args[0], grounded, negated);
148
- return inner === null || shared(goal).some((name) => !grounded.has(name)) ? null : grounded;
149
- }
150
- if (isCollection(goal)) {
151
- const inner = bound(goal.args[1], grounded, negated);
152
- const collected = new Struct('-', [goal.args[0], goal.args[1]]);
153
- if (inner === null || shared(collected).some((name) => !grounded.has(name))) return null;
154
- const items = [...variables(goal.args[0]).keys()].every((name) => inner.has(name));
155
- return items ? new Set([...grounded, ...variables(goal.args[2]).keys()]) : grounded;
156
- }
157
- if (!isCallable(goal)) return null;
158
- const goalKey = key(goal);
159
- if (INSPECTION_KEYS.has(goalKey)) return null;
160
- if (PRIMITIVE_KEYS.has(goalKey)) {
161
- const free = (term) => [...variables(term).keys()].filter((name) => !grounded.has(name));
162
- const args = goal instanceof Struct ? goal.args : [];
163
- if (args.every((arg) => !free(arg).length)) return grounded;
164
- if (goalKey === 'unify/2') {
165
- // Unification is pure; a ground side grounds the other.
166
- const [left, right] = args;
167
- if (!free(left).length || !free(right).length) return new Set([...grounded, ...variables(goal).keys()]);
168
- return grounded;
169
- }
170
- const modes = MODES.get(goalKey) || [];
171
- if (!modes.some(([inputs]) => inputs.every((i) => !free(args[i]).length))) return null;
172
- return new Set([...grounded, ...variables(goal).keys()]);
173
- }
174
- const args = goal instanceof Struct ? goal.args : [];
175
- const mode = args.map((arg) => ([...variables(arg).keys()].every((name) => grounded.has(name)) ? 'g' : 'f')).join('');
176
- pending.push([goalKey, mode]);
177
- return groundsFacts(goalKey, mode) ? new Set([...grounded, ...variables(goal).keys()]) : grounded;
178
- }
179
- while (pending.length) {
180
- const [goalKey, mode] = pending.pop();
181
- const clauses = [];
182
- if (!seen.has(goalKey)) {
183
- seen.add(goalKey);
184
- clauses.push(...(program.groups.get(goalKey) || []).filter((clause) => !clause.body.length),
185
- ...program.forward.filter((clause) => clause.plainHeads.some((head) => isCallable(head) && key(head) === goalKey)));
186
- }
187
- if (mode !== null && !seen.has(`${goalKey} ${mode}`)) {
188
- seen.add(`${goalKey} ${mode}`);
189
- clauses.push(...(program.groups.get(goalKey) || []).filter((clause) => clause.body.length));
190
- }
191
- for (const clause of clauses) {
192
- if (clause.parentId !== null || clause.templates.length || clause.captures !== null || clause.guard !== null) return false;
193
- if (!clause.forward && !clause.body.length) continue;
194
- outside = occurrences(new Struct('-', [clause.head, listFromItems(clause.body)]));
195
- let grounded = clause.forward ? new Set() : inputs(clause.head, mode);
196
- for (const goal of clause.body) {
197
- grounded = bound(goal, grounded);
198
- if (grounded === null) return false;
199
- }
200
- // A call in a mode whose facts stay nonground grounds nothing, so its
201
- // rules need not ground their heads either.
202
- if (!clause.forward && !groundsFacts(goalKey, mode)) continue;
203
- const witnesses = new Set(clause.forward ? clause.witnessNames : []);
204
- for (const name of variables(clause.head).keys()) {
205
- if (grounded.has(name) || witnesses.has(name)) continue;
206
- if (clause.forward) return false;
207
- loose.add(`${goalKey} ${mode}`);
208
- return 'again';
209
- }
210
- }
211
- }
212
- return true;
213
- }
214
-
215
42
  // Whether each fact of these listings is the conclusion of a firing that a
216
43
  // search makes, replaying in source order the derivation its steps record.
217
44
  // Primitives run on the bindings of that point of the search, so a test of
@@ -234,15 +61,35 @@ export function replayed(program, settler, listingKeys, stepOf) {
234
61
  (clause.parentId !== null || clause.captures === null) &&
235
62
  !((clause.parentId !== null || clause.templates.length) && clause.witnessNames.length);
236
63
  function compatible(goal, use, env) {
64
+ // Trial unification must not undo compression of existing bindings.
65
+ goal = copyResolved(goal, env);
237
66
  const mark = env.mark();
238
67
  const agrees = unify(goal, fresh(use), env);
239
68
  env.undo(mark);
240
69
  return agrees;
241
70
  }
242
- function all(goals, uses, env) {
243
- return goals.length === uses.length && goals.every((goal, i) => one(goal, uses[i], env));
71
+ // Keep deep recorded derivations off the host stack.
72
+ function finish(start) {
73
+ const pending = [start];
74
+ let value;
75
+ while (pending.length) {
76
+ const next = pending[pending.length - 1].next(value);
77
+ if (next.done) {
78
+ value = next.value;
79
+ pending.pop();
80
+ } else {
81
+ pending.push(next.value);
82
+ value = undefined;
83
+ }
84
+ }
85
+ return value;
86
+ }
87
+ function* all(goals, uses, env) {
88
+ if (goals.length !== uses.length) return false;
89
+ for (let i = 0; i < goals.length; i++) if (!(yield one(goals[i], uses[i], env))) return false;
90
+ return true;
244
91
  }
245
- function one(goal, use, env) {
92
+ function* one(goal, use, env) {
246
93
  goal = deref(goal, env);
247
94
  if (!isCallable(goal) || !isCallable(use)) return false;
248
95
  const goalKey = key(goal);
@@ -256,7 +103,7 @@ export function replayed(program, settler, listingKeys, stepOf) {
256
103
  const parts = flattenConjunction(use.args[i]);
257
104
  return parts.length === used.length && parts.every((part, j) => text(part) === used[j]);
258
105
  });
259
- return side !== undefined && all(flattenConjunction(goal.args[side]), step.uses, env);
106
+ return side !== undefined && (yield all(flattenConjunction(goal.args[side]), step.uses, env));
260
107
  }
261
108
  if (['once/1', 'not/1', 'findall/3', 'findall_sorted/3'].includes(goalKey)) {
262
109
  const outcome = settler.answers(copyResolved(goal, env));
@@ -296,22 +143,22 @@ export function replayed(program, settler, listingKeys, stepOf) {
296
143
  if (!isTerm(step.by, 'clause', 1)) return false;
297
144
  const clause = program.byId.get(Number(step.by.args[0]));
298
145
  if (!supportedRule(clause)) return false;
299
- if (clause.forward) return fact(use) && unify(goal, freshTerm(use, `pattern${++serial}`), env);
146
+ if (clause.forward) return (yield fact(use)) && unify(goal, freshTerm(use, `pattern${++serial}`), env);
300
147
  const [head, body] = freshClause(clause, `replay${++serial}`);
301
148
  if (!body.length) return unify(goal, head, env) && compatible(goal, use, env);
302
- const call = `${text(use)} ${text(copyResolved(goal, env))}`;
303
- if (active.has(call)) return false;
304
- active.add(call);
149
+ const id = text(use);
150
+ if (active.has(id)) return false;
151
+ active.add(id);
305
152
  // A generator ran before any caller: its premises replay before the head
306
153
  // meets the call.
307
154
  const prefix = clause.prefixLength;
308
- const solved = step.uses.length === body.length && all(body.slice(0, prefix), step.uses.slice(0, prefix), env) &&
309
- unify(goal, head, env) && all(body.slice(prefix), step.uses.slice(prefix), env) && compatible(goal, use, env);
310
- active.delete(call);
155
+ const solved = step.uses.length === body.length && (yield all(body.slice(0, prefix), step.uses.slice(0, prefix), env)) &&
156
+ unify(goal, head, env) && (yield all(body.slice(prefix), step.uses.slice(prefix), env)) && compatible(goal, use, env);
157
+ active.delete(id);
311
158
  return solved;
312
159
  }
313
160
  // A listed fact: a firing of the forward rule its step cites.
314
- function fact(goal) {
161
+ function* fact(goal) {
315
162
  const id = text(goal);
316
163
  if (confirmed.has(id)) return confirmed.get(id);
317
164
  if (active.has(id)) return false;
@@ -322,7 +169,7 @@ export function replayed(program, settler, listingKeys, stepOf) {
322
169
  active.add(id);
323
170
  const [head, body, names] = freshClause(clause, `replay${++serial}`);
324
171
  const env = new Env();
325
- holds = all(body, step.uses, env);
172
+ holds = yield all(body, step.uses, env);
326
173
  if (holds && clause.witnessNames.length) {
327
174
  // Each witness is the Skolem term of this firing (Section 8.2).
328
175
  const witnesses = new Set(clause.witnessNames.map((name) => names.get(name).name));
@@ -351,16 +198,14 @@ export function replayed(program, settler, listingKeys, stepOf) {
351
198
  confirmed.set(id, holds);
352
199
  return holds;
353
200
  }
354
- return listingKeys.every((goalKey) => (settler.listings.get(goalKey)?.facts || []).every(fact));
201
+ return listingKeys.every((goalKey) => (settler.listings.get(goalKey)?.facts || []).every((goal) => finish(fact(goal))));
355
202
  }
356
203
 
357
204
  // Both directions of C10: each claim is an answer of an original question,
358
205
  // and each answer of a certified question is claimed. When the conclusions
359
206
  // are the derived facts, a question's answers that are not derived (source
360
207
  // facts, backward answers) are no conclusions, so only its listed facts are.
361
- // A proof with a primitive only within host-math tolerance (C5) supports no
362
- // listing for C10: its derived facts need not be what a search here finds.
363
- export function checkCalls(program, claims, goals, certificate, steps, spellings, fail, allowTrusted, name, inexact = false) {
208
+ export function checkCalls(program, claims, goals, certificate, steps, spellings, fail, allowTrusted, name) {
364
209
  const settler = new Settler(program, {
365
210
  answers: (call) => certificate.calls.get(variant(call, true)) ?? null,
366
211
  facts: (goalKey) => certificate.listings.get(goalKey) ?? null,
@@ -368,12 +213,9 @@ export function checkCalls(program, claims, goals, certificate, steps, spellings
368
213
  }, true);
369
214
  if (claims.includes('false')) return { settler, outcomes: [], unresolved: [], covered: 0 };
370
215
  const stepOf = (goal) => steps.get(stepIdOf(steps, spellings, goal));
371
- // Replay runs host math exactly, so it needs no exclusion for tolerance.
372
- const supported = (listings) => (!(inexact && listings.length) && positiveListings(program, listings)) ||
373
- replayed(program, settler, listings, stepOf);
374
216
  const outcomes = callQuestions(program, goals, claims).map((question) => {
375
217
  const outcome = settler.answers(question);
376
- if (outcome.status === 'settled' && !supported(outcome.listings)) {
218
+ if (outcome.status === 'settled' && !replayed(program, settler, outcome.listings, stepOf)) {
377
219
  return { question, ...outcome, status: 'unsupported' };
378
220
  }
379
221
  return { question, ...outcome };
package/src/proof.js CHANGED
@@ -370,7 +370,7 @@ function check(program, claims, steps, certificate, goals, allowTrusted, fail, s
370
370
  const provenance = new WitnessProvenance(program, steps, certificate, settlement.outcomes, spellings);
371
371
  const tally = checkSteps(program, steps, allowTrusted, fail, spellings, name, settlement.outcomes, provenance);
372
372
  const [confronted, closed] = checkBoundaries(program, steps, tally.boundaries, fail, settlement.outcomes, spellings);
373
- settlement.calls = checkCalls(program, claims, goals, certificate, steps, spellings, fail, allowTrusted, name, tally.inexact);
373
+ settlement.calls = checkCalls(program, claims, goals, certificate, steps, spellings, fail, allowTrusted, name);
374
374
  tally.trusted.push(...settlement.calls.unresolved);
375
375
  checkRelevance(program, claims, steps, goals || [], fail, spellings, settlement, certificate);
376
376
  checkWellFounded(steps, fail, spellings);
@@ -510,7 +510,7 @@ const CONTROL_BY = 'control';
510
510
  // instance of the clause it cites, a recomputed primitive, a control composed
511
511
  // of its uses, or a trusted boundary the later checks confront.
512
512
  function checkSteps(program, steps, allowTrusted, fail, spellings, name, outcomes, provenance) {
513
- const tally = { verified: 0, redecided: 0, composed: 0, witnessed: 0, boundaries: [], trusted: [], inexact: false };
513
+ const tally = { verified: 0, redecided: 0, composed: 0, witnessed: 0, boundaries: [], trusted: [] };
514
514
 
515
515
  function covered(goal) {
516
516
  if (isTerm(goal, 'and', 2)) return flattenConjunction(goal).every(covered);
@@ -540,11 +540,8 @@ function checkSteps(program, steps, allowTrusted, fail, spellings, name, outcome
540
540
  fail.add('C3', 'invalid builtin justification', goal);
541
541
  continue;
542
542
  }
543
- const exact = redecidesExactly(goal);
544
- if (!exact && !nearHostMath(goal)) fail.add('C5', `primitive disagrees: ${text(goal)}`, goal);
543
+ if (!redecides(goal)) fail.add('C5', `primitive disagrees: ${text(goal)}`, goal);
545
544
  else tally.redecided++;
546
- // Host math within its tolerance is not the result a search here finds.
547
- if (!exact) tally.inexact = true;
548
545
  } else if (isTerm(by, 'called', 1)) {
549
546
  if (bindings.length || uses.length || !isCallable(goal) || !STATE_TESTS.has(key(goal))) {
550
547
  fail.add('C3', 'invalid called justification', goal);
package/src/version.js CHANGED
@@ -1,2 +1,2 @@
1
1
  // The release this checkout is; ./release keeps it in step with package.json.
2
- export const VERSION = '0.5.30';
2
+ export const VERSION = '0.5.31';