eyemind 0.5.14 → 0.5.16
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 +3 -3
- package/SPEC.md +133 -3
- package/package.json +1 -1
- package/src/chains.js +333 -0
- package/src/engine.js +100 -46
- package/src/program.js +57 -1
- package/src/version.js +1 -1
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
|
|
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 1371 cases that test any implementation of the specification through its command line; run it [in your browser](https://eyereasoner.github.io/eyemind/playground/conformance).
|
|
11
11
|
|
|
12
12
|
## Contents
|
|
13
13
|
|
|
@@ -392,9 +392,9 @@ The statement chooses the direction:
|
|
|
392
392
|
| **Forward** | `implies`, `restricted`, `query`, `contradiction` | From the facts, round after round, until a round adds nothing new. |
|
|
393
393
|
| **Backward** | `implied_by`, `fact` | When a goal asks: depth-first, left to right, in the order the clauses are written. |
|
|
394
394
|
|
|
395
|
-
Forward rules suit closures and classifications: `implies([path(X, Y), edge(Y, Z)], path(X, Z))` terminates on a cyclic graph. A variable only a forward rule's conclusion mentions gets a fresh value, a Skolem term, for each firing. `restricted` makes one only where none is known: `restricted(human(X), [father(X, F), man(F)])` gives no new father to a human whose known father is a man. Its other rules run first in each stratum, and its proof shows each new value is needed, as the restricted chase of N. Küchenmeister, A. Ivliev, D. Arndt and M. Krötzsch, ["Stratified Negation in RDF Rules"](https://arxiv.org/abs/2607.28778), requires. Which firings it makes can depend on the order of rule applications, so call fidelity stays an obligation. Backward rules suit computations driven by their inputs, such as arithmetic recursion and list processing. Backward chaining keeps no table of answers, so a backward rule that calls itself with the same goal runs until a bound stops it; such recursion belongs in a forward rule.
|
|
395
|
+
Forward rules suit closures and classifications: `implies([path(X, Y), edge(Y, Z)], path(X, Z))` terminates on a cyclic graph. A variable only a forward rule's conclusion mentions gets a fresh value, a Skolem term, for each firing. `restricted` makes one only where none is known: `restricted(human(X), [father(X, F), man(F)])` gives no new father to a human whose known father is a man. Its other rules run first in each stratum, a restricted rule whose conclusion can satisfy another's runs before it, a run whose new value later facts make unneeded stops with an error, and its proof shows each new value is needed, as the restricted chase of N. Küchenmeister, A. Ivliev, D. Arndt and M. Krötzsch, ["Stratified Negation in RDF Rules"](https://arxiv.org/abs/2607.28778), requires. Which firings it makes can depend on the order of rule applications, so call fidelity stays an obligation. Backward rules suit computations driven by their inputs, such as arithmetic recursion and list processing. Backward chaining keeps no table of answers, so a backward rule that calls itself with the same goal runs until a bound stops it; such recursion belongs in a forward rule.
|
|
396
396
|
|
|
397
|
-
The two work together: a forward rule's premise can call a backward definition, and a backward goal sees the facts forward rules derived. Forward rules run stratum by stratum, so a negation or collection waits until everything it inspects is final. `--max-depth`, `--max-iterations` and `--max-inferences` bound a run, and exceeding one is an error, never a partial answer. [SPEC §8](https://eyereasoner.github.io/eyemind/SPEC#8-evaluation-and-conclusions) defines the details.
|
|
397
|
+
The two work together: a forward rule's premise can call a backward definition, and a backward goal sees the facts forward rules derived. Forward rules run stratum by stratum, so a negation or collection waits until everything it inspects is final. A rule with a variable in every position, such as `implies([rdf(P, 'spo', Q), rdf(X, P, Y)], rdf(X, Q, Y))`, reaches every negation of its relation, and a cycle through it has no strata. Such a program is still accepted when it is chain-stratified, as Küchenmeister, Ivliev, Arndt and Krötzsch define it: no chain of rule applications from a rule with a negation can make one of its negated goals true without also satisfying a `contradiction`. Its rules then run in ranks, the Datalog rules first, and a rule fires only while no lower-ranked rule has a firing left ([SPEC §6.4](https://eyereasoner.github.io/eyemind/SPEC#64-chain-stratification)). `--max-depth`, `--max-iterations` and `--max-inferences` bound a run, and exceeding one is an error, never a partial answer. [SPEC §8](https://eyereasoner.github.io/eyemind/SPEC#8-evaluation-and-conclusions) defines the details.
|
|
398
398
|
|
|
399
399
|
## Proofs, and what checking one means
|
|
400
400
|
|
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.
|
|
5
|
+
Version: eyemind 0.5.16
|
|
6
6
|
```
|
|
7
7
|
|
|
8
8
|
This document specifies the syntax and meaning of eyemind programs and data
|
|
@@ -39,6 +39,7 @@ proof.
|
|
|
39
39
|
- [6.1 Dependencies and stratification](#61-dependencies-and-stratification)
|
|
40
40
|
- [6.2 Inline rule templates](#62-inline-rule-templates)
|
|
41
41
|
- [6.3 Source rule inspection](#63-source-rule-inspection)
|
|
42
|
+
- [6.4 Chain stratification](#64-chain-stratification)
|
|
42
43
|
- [7. Semantics](#7-semantics)
|
|
43
44
|
- [7.1 Herbrand interpretation](#71-herbrand-interpretation)
|
|
44
45
|
- [7.2 Variables and witnesses](#72-variables-and-witnesses)
|
|
@@ -721,7 +722,8 @@ dependency. Forward rules run in order of rank ([Section 8.2](#82-forward-evalua
|
|
|
721
722
|
|
|
722
723
|
A program MUST be rejected when:
|
|
723
724
|
|
|
724
|
-
- no such assignment exists, because a closed dependency lies on a cycle
|
|
725
|
+
- no such assignment exists, because a closed dependency lies on a cycle,
|
|
726
|
+
and the program is not chain-stratified ([Section 6.4](#64-chain-stratification));
|
|
725
727
|
- a forward rule can reach, through dependencies, a clause with a body goal
|
|
726
728
|
that is a variable.
|
|
727
729
|
|
|
@@ -852,6 +854,98 @@ Inspection uses a fixed source catalogue, so its own results do not depend on
|
|
|
852
854
|
forward rounds. Other goals using derived patterns still participate in
|
|
853
855
|
stratification. Negation and collection keep their own justifications ([Section 10.3](#103-steps)).
|
|
854
856
|
|
|
857
|
+
### 6.4 Chain stratification
|
|
858
|
+
|
|
859
|
+
A rule whose head has a variable in every argument, such as
|
|
860
|
+
`implies([rdf(P, 'spo', Q), rdf(X, P, Y)], rdf(X, Q, Y))`, unifies with every
|
|
861
|
+
negated goal of its relation, so a cycle through it and a negation defeats
|
|
862
|
+
[Section 6.1](#61-dependencies-and-stratification)'s ranks. Many such programs still have one intended result:
|
|
863
|
+
no sequence of rule applications that starts at a rule with a negation can
|
|
864
|
+
make one of its negated goals true without also satisfying a
|
|
865
|
+
contradiction's body. N. Küchenmeister, A. Ivliev, D. Arndt and
|
|
866
|
+
M. Krötzsch, "Stratified Negation in RDF Rules: A Correct Approach"
|
|
867
|
+
(arXiv:2607.28778), call such programs chain-stratified under constraints.
|
|
868
|
+
This section defines the decision eyemind makes, which errs towards
|
|
869
|
+
rejection: a program it accepts is chain-stratified in the paper's sense.
|
|
870
|
+
It is made only for a program [Section 6.1](#61-dependencies-and-stratification) rejects for a closed cycle.
|
|
871
|
+
|
|
872
|
+
**Rules.** The rules are the forward clauses and the backward clauses with a
|
|
873
|
+
body. A program with templates or captures, a rule body goal `or`, `once`,
|
|
874
|
+
`call` or a variable, or a backward rule with a negation or collection, is
|
|
875
|
+
not chain-stratified. A rule has:
|
|
876
|
+
|
|
877
|
+
- **positive goals**: its body goals other than primitives, negations,
|
|
878
|
+
collections and `'true'`, and other than a restricted rule's guard
|
|
879
|
+
([Section 7.2](#72-variables-and-witnesses));
|
|
880
|
+
- **negated groups**: for each `not(G)` and `findall(T, G, L)` body goal,
|
|
881
|
+
the goals of the conjunction `G` other than primitives; a group with a
|
|
882
|
+
control or a variable makes the program not chain-stratified, and an
|
|
883
|
+
empty group is left out;
|
|
884
|
+
- **heads**: a forward rule's heads other than `'true'` and `'false'`, or a
|
|
885
|
+
backward rule's head.
|
|
886
|
+
|
|
887
|
+
A rule is **Datalog** when it has no negation or collection and is not
|
|
888
|
+
restricted; a Datalog rule without primitives is **pure**. A contradiction is
|
|
889
|
+
a forward rule whose head is `'false'`.
|
|
890
|
+
|
|
891
|
+
**Closure.** Chain facts are terms whose variables are treated as distinct
|
|
892
|
+
constants. The closure of a set of chain facts adds, for each pure Datalog
|
|
893
|
+
rule renamed apart and each way its positive goals unify with facts of the
|
|
894
|
+
set, its heads that the unifier makes ground, repeatedly until nothing is
|
|
895
|
+
added. The set is **contradictory** when a contradiction's positive goals
|
|
896
|
+
match it.
|
|
897
|
+
|
|
898
|
+
**States.** A chain state is formed from a rule `r`, its heads `H`,
|
|
899
|
+
**conditions** `C` and **caused facts** `K`. Let `B` be the closure of `C`
|
|
900
|
+
and `F` the closure of `C ∪ K ∪ H`; there is no state when either is
|
|
901
|
+
contradictory. The state's facts are the facts of `F` whose variables all
|
|
902
|
+
occur in `H`, each marked **caused** when it is not in `B`. Two states are
|
|
903
|
+
the same when they have the same rule and, after renaming their variables
|
|
904
|
+
to `V0`, `V1`, ... in order of first occurrence in `H`, the same heads and
|
|
905
|
+
the same facts with the same marks.
|
|
906
|
+
|
|
907
|
+
**Chains.** Each forward rule `s` that is not Datalog starts a search with
|
|
908
|
+
the state of `s` with `C` its positive goals, `K` empty and `H` its heads,
|
|
909
|
+
renamed apart. A state `S` is **extended** by a rule `r` with heads, renamed
|
|
910
|
+
apart, for each positive goal `g` of `r` and each caused fact `c` of `S`
|
|
911
|
+
whose most general unifier with `g` is `σ`. Let `D` be the facts of `S` and
|
|
912
|
+
the positive goals of `r`, under `σ`. The extension is discarded when the
|
|
913
|
+
closure of `D` is contradictory, when the heads of `r` under `σ` match facts
|
|
914
|
+
of `D` with only their variables absent from `D` free, or when the goals of
|
|
915
|
+
a negated group of `r` under `σ` match facts of `D` in the same way.
|
|
916
|
+
Otherwise it gives the state of `r` with `H` its heads under `σ`, `K` the
|
|
917
|
+
caused facts of `S` under `σ`, and `C` the other facts of `S` under `σ`
|
|
918
|
+
together with the positive goals of `r` under `σ` that are not among `K`.
|
|
919
|
+
Each search visits a state once.
|
|
920
|
+
|
|
921
|
+
**Edges.** A rule `s` has an edge to a rule `t` with a negated group when a
|
|
922
|
+
state of `s`'s search has a caused fact that unifies, by `τ`, with a goal of
|
|
923
|
+
a negated group of `t` renamed apart, and the facts of the state under `τ`
|
|
924
|
+
have a closure that is not contradictory. The program is
|
|
925
|
+
**chain-stratified** when no rule reaches itself through edges. A search
|
|
926
|
+
that visits more than 4096 states in total, or a closure of more than 2048
|
|
927
|
+
facts, makes the program not chain-stratified.
|
|
928
|
+
|
|
929
|
+
**Ranks.** A Datalog forward rule has rank 0. Another forward rule has rank 1,
|
|
930
|
+
or one more than the greatest rank of a rule with an edge to it. Forward
|
|
931
|
+
rules then run by these ranks as [Section 8.2](#82-forward-evaluation-and-witnesses) specifies for chain strata. For
|
|
932
|
+
example, with constraints that the examiner relation is no subproperty of
|
|
933
|
+
the participant relation, of `spo` or of the type relation:
|
|
934
|
+
|
|
935
|
+
```js
|
|
936
|
+
implies(rdf(C, 'participant', P), rdf(P, 'type', 'Student'))
|
|
937
|
+
implies([rdf(C, 'teacher', P), not(rdf(P, 'type', 'Student'))], rdf(C, 'examiner', P))
|
|
938
|
+
implies([rdf(P, 'spo', Q), rdf(Q, 'spo', R)], rdf(P, 'spo', R))
|
|
939
|
+
implies([rdf(P, 'spo', Q), rdf(X, P, Y)], rdf(X, Q, Y))
|
|
940
|
+
contradiction(rdf('examiner', 'spo', 'participant'))
|
|
941
|
+
contradiction(rdf('examiner', 'spo', 'spo'))
|
|
942
|
+
contradiction(rdf('examiner', 'spo', 'type'))
|
|
943
|
+
```
|
|
944
|
+
|
|
945
|
+
is chain-stratified: every chain from the second rule that could make
|
|
946
|
+
`rdf(P, 'type', 'Student')` true satisfies a contradiction's body. Without
|
|
947
|
+
any one of the three contradictions it is not.
|
|
948
|
+
|
|
855
949
|
## 7. Semantics
|
|
856
950
|
|
|
857
951
|
### 7.1 Herbrand interpretation
|
|
@@ -1042,14 +1136,50 @@ and `p(2)` publishes `a(1)`, `b(1)`, `a(2)`, `b(2)`. For each head:
|
|
|
1042
1136
|
When the run asks its own goals ([Section 8.4](#84-external-goals)), rules whose heads are all
|
|
1043
1137
|
`'true'` are not run.
|
|
1044
1138
|
|
|
1139
|
+
A program accepted by chain stratification ([Section 6.4](#64-chain-stratification)) runs its forward
|
|
1140
|
+
rules by chain strata instead of stratum by stratum. Rules of rank 0 run in
|
|
1141
|
+
rounds; a round of the rules of a rank `k > 0` runs only after a round of
|
|
1142
|
+
each lower rank, in increasing order, that added nothing; after a round of
|
|
1143
|
+
any rank that adds something, rank 0 runs again. Reasoning ends after a
|
|
1144
|
+
round of the highest rank that adds nothing, all lower ranks' latest rounds
|
|
1145
|
+
having added nothing. A rule thus never fires while a rule of a lower rank
|
|
1146
|
+
has a firing left.
|
|
1147
|
+
|
|
1045
1148
|
A stratum with restricted rules alternates two kinds of round. Its other
|
|
1046
|
-
rules run in rounds as above; a round of its restricted rules, in
|
|
1149
|
+
rules run in rounds as above; a round of its restricted rules, in restraint
|
|
1047
1150
|
order, follows only a round of the other rules that adds nothing, and is
|
|
1048
1151
|
followed by rounds of the other rules again when it adds something. The
|
|
1049
1152
|
stratum ends with a round of its restricted rules that adds nothing. The
|
|
1050
1153
|
other rules of a stratum thus run before its restricted rules, whose guards
|
|
1051
1154
|
see what they derive.
|
|
1052
1155
|
|
|
1156
|
+
A restricted rule `A` **restrains** a restricted rule `B`, both renamed
|
|
1157
|
+
apart, when for some head `h` of `B` with a head-only variable of `B`, the
|
|
1158
|
+
heads of `B` sharing a head-only variable with `h` (`h` included) unify, one
|
|
1159
|
+
after another under one substitution, each with some head of `A`: firing
|
|
1160
|
+
`A` can then satisfy `B`'s heads. The **restraint order** of a set of
|
|
1161
|
+
restricted rules repeatedly takes the first rule, in clause order, that no
|
|
1162
|
+
other remaining rule restrains, or the first remaining rule when every one
|
|
1163
|
+
is restrained. A chain stratum ([Section 6.4](#64-chain-stratification)) runs its restricted rules after its
|
|
1164
|
+
other rules, in restraint order.
|
|
1165
|
+
|
|
1166
|
+
When reasoning ends without a contradiction, every guard of a published
|
|
1167
|
+
restricted firing MUST hold again, with the firing's bindings, in the final
|
|
1168
|
+
facts. Otherwise later facts satisfy the firing's heads, so its witness is
|
|
1169
|
+
not needed and the result depends on the order in which rules were applied:
|
|
1170
|
+
the run MUST fail with an error. For example,
|
|
1171
|
+
|
|
1172
|
+
```js
|
|
1173
|
+
fact(f('a'))
|
|
1174
|
+
restricted(f(X), h(W))
|
|
1175
|
+
implies(g(X, Y), h(Y))
|
|
1176
|
+
restricted(f(X), g(X, W))
|
|
1177
|
+
```
|
|
1178
|
+
|
|
1179
|
+
fails: the second rule makes `h(skolem(2, 'W', []))`, and the last rule's
|
|
1180
|
+
`g('a', skolem(4, 'W', ['a']))` then gives `h(skolem(4, 'W', ['a']))`,
|
|
1181
|
+
which satisfies the second rule's head too.
|
|
1182
|
+
|
|
1053
1183
|
For a generator, use its scope projection ([Section 6.2](#62-inline-rule-templates)) as its head when
|
|
1054
1184
|
constructing witnesses. For an appended forward clause of [Section 6.2](#62-inline-rule-templates),
|
|
1055
1185
|
prepend one element to
|
package/package.json
CHANGED
package/src/chains.js
ADDED
|
@@ -0,0 +1,333 @@
|
|
|
1
|
+
// Chain stratification: an ordering of forward rules for programs whose
|
|
2
|
+
// negations or collections lie on a dependency cycle (SPEC Section 6.4).
|
|
3
|
+
//
|
|
4
|
+
// Classic stratification (program.js) asks whether a rule's head can unify
|
|
5
|
+
// with a negated goal. A head written with variables in every position, as
|
|
6
|
+
// rdf(X, Q, Y), then reaches every negation, and so does any cycle through
|
|
7
|
+
// it. Following N. Küchenmeister, A. Ivliev, D. Arndt and M. Krötzsch,
|
|
8
|
+
// "Stratified Negation in RDF Rules: A Correct Approach" (arXiv:2607.28778),
|
|
9
|
+
// this asks instead which chains of rule applications starting at a rule
|
|
10
|
+
// with a negation can make some negated goal true, given the Datalog rules
|
|
11
|
+
// and the contradictions: a chain whose facts make a contradiction hold
|
|
12
|
+
// is no chain. The rules form layers when no chain leads from a rule back to
|
|
13
|
+
// itself. Each check errs on the side of more chains, so an accepted program
|
|
14
|
+
// is chain-stratified in the paper's sense.
|
|
15
|
+
import { PRIMITIVE_KEYS } from './builtins.js';
|
|
16
|
+
import { Env, Struct, Var, copyResolved, flattenConjunction, freshTerm, identity, isCallable, isTerm, key, unify, variables } from './terms.js';
|
|
17
|
+
|
|
18
|
+
// The analysis stops, rejecting the program, beyond these many chain states,
|
|
19
|
+
// or closure facts for one state.
|
|
20
|
+
export const CHAIN_LIMITS = { states: 4096, facts: 2048 };
|
|
21
|
+
|
|
22
|
+
// Ranks for the forward clauses of a program classic stratification
|
|
23
|
+
// rejects, or null when the program is not chain-stratified, as far as this
|
|
24
|
+
// analysis can tell. Rank 0 holds the Datalog rules; a rule with a negation,
|
|
25
|
+
// a collection or a restriction ranks above every rule a chain from it can
|
|
26
|
+
// disable.
|
|
27
|
+
export function chainStrata(clauses) {
|
|
28
|
+
const rules = [];
|
|
29
|
+
for (const clause of clauses) {
|
|
30
|
+
if (clause.parentId !== null || clause.templates.length || clause.captures !== null) return null;
|
|
31
|
+
if (!clause.forward && !clause.body.length) continue;
|
|
32
|
+
const rule = ruleOf(clause);
|
|
33
|
+
if (rule === null) return null;
|
|
34
|
+
rules.push(rule);
|
|
35
|
+
}
|
|
36
|
+
const datalog = rules.filter((rule) => rule.datalog && rule.pure);
|
|
37
|
+
const negating = rules.filter((rule) => rule.negated.length);
|
|
38
|
+
const edges = new Map();
|
|
39
|
+
let states = 0;
|
|
40
|
+
for (const start of rules.filter((rule) => rule.forward && !rule.datalog)) {
|
|
41
|
+
const seen = new Set();
|
|
42
|
+
const first = stateOf(start, renamed(start), datalog);
|
|
43
|
+
if (first === null) continue;
|
|
44
|
+
const pending = [first];
|
|
45
|
+
while (pending.length) {
|
|
46
|
+
const state = pending.pop();
|
|
47
|
+
if (seen.has(state.label)) continue;
|
|
48
|
+
seen.add(state.label);
|
|
49
|
+
if (++states > CHAIN_LIMITS.states) return null;
|
|
50
|
+
for (const target of negating) {
|
|
51
|
+
if (edges.get(start.id)?.has(target.id) || !disables(state, target, datalog)) continue;
|
|
52
|
+
if (!edges.has(start.id)) edges.set(start.id, new Set());
|
|
53
|
+
edges.get(start.id).add(target.id);
|
|
54
|
+
// An edge that closes a cycle settles the question.
|
|
55
|
+
if (reaches(edges, target.id, start.id)) return null;
|
|
56
|
+
}
|
|
57
|
+
for (const next of rules) {
|
|
58
|
+
if (!next.heads.length) continue;
|
|
59
|
+
for (const extended of extensions(state, next, datalog)) {
|
|
60
|
+
if (extended === undefined) return null;
|
|
61
|
+
if (!seen.has(extended.label)) pending.push(extended);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
// Layers: the longest path of chain edges, above the Datalog rules.
|
|
67
|
+
const ranks = new Map();
|
|
68
|
+
const forward = rules.filter((rule) => rule.forward);
|
|
69
|
+
const visiting = new Set();
|
|
70
|
+
const rank = (rule) => {
|
|
71
|
+
if (ranks.has(rule.id)) return ranks.get(rule.id);
|
|
72
|
+
if (rule.datalog) return 0;
|
|
73
|
+
if (visiting.has(rule.id)) return null;
|
|
74
|
+
visiting.add(rule.id);
|
|
75
|
+
let value = 1;
|
|
76
|
+
for (const [from, targets] of edges) {
|
|
77
|
+
if (!targets.has(rule.id)) continue;
|
|
78
|
+
const before = rules.find((item) => item.id === from);
|
|
79
|
+
const below = rank(before);
|
|
80
|
+
if (below === null) return null;
|
|
81
|
+
value = Math.max(value, below + 1);
|
|
82
|
+
}
|
|
83
|
+
visiting.delete(rule.id);
|
|
84
|
+
ranks.set(rule.id, value);
|
|
85
|
+
return value;
|
|
86
|
+
};
|
|
87
|
+
for (const rule of forward) {
|
|
88
|
+
const value = rank(rule);
|
|
89
|
+
if (value === null) return null;
|
|
90
|
+
ranks.set(rule.id, value);
|
|
91
|
+
}
|
|
92
|
+
return ranks;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// Whether edges lead from one rule to another, or back to itself.
|
|
96
|
+
function reaches(edges, from, to) {
|
|
97
|
+
const pending = [from];
|
|
98
|
+
const seen = new Set();
|
|
99
|
+
while (pending.length) {
|
|
100
|
+
const id = pending.pop();
|
|
101
|
+
if (id === to) return true;
|
|
102
|
+
if (seen.has(id)) continue;
|
|
103
|
+
seen.add(id);
|
|
104
|
+
pending.push(...(edges.get(id) ?? []));
|
|
105
|
+
}
|
|
106
|
+
return false;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
// A clause as the analysis reads it: positive goals, negated groups (a
|
|
110
|
+
// negation or a collection), heads, and whether it is Datalog (no negation,
|
|
111
|
+
// collection or restriction) and pure (no primitive, so its closure is
|
|
112
|
+
// exact). A control other than these, or a variable goal, gives null.
|
|
113
|
+
function ruleOf(clause) {
|
|
114
|
+
const positive = [];
|
|
115
|
+
const negated = [];
|
|
116
|
+
let pure = true;
|
|
117
|
+
for (const goal of clause.localBody) {
|
|
118
|
+
if (goal === clause.guard) continue;
|
|
119
|
+
if (goal === 'true') continue;
|
|
120
|
+
if (!isCallable(goal)) return null;
|
|
121
|
+
const goalKey = key(goal);
|
|
122
|
+
if (goalKey === 'not/1' || goalKey === 'findall/3') {
|
|
123
|
+
const group = [];
|
|
124
|
+
for (const inner of flattenConjunction(goalKey === 'not/1' ? goal.args[0] : goal.args[1])) {
|
|
125
|
+
if (inner instanceof Var || !isCallable(inner)) return null;
|
|
126
|
+
if (PRIMITIVE_KEYS.has(key(inner))) continue;
|
|
127
|
+
if (['not/1', 'findall/3', 'or/2', 'once/1', 'call/1'].includes(key(inner))) return null;
|
|
128
|
+
group.push(inner);
|
|
129
|
+
}
|
|
130
|
+
if (group.length) negated.push(group);
|
|
131
|
+
pure = false;
|
|
132
|
+
} else if (['or/2', 'once/1', 'call/1'].includes(goalKey)) {
|
|
133
|
+
return null;
|
|
134
|
+
} else if (PRIMITIVE_KEYS.has(goalKey)) {
|
|
135
|
+
pure = false;
|
|
136
|
+
} else {
|
|
137
|
+
positive.push(goal);
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
// A backward rule is answered by search, which a cycle through its
|
|
141
|
+
// negation or collection would never finish.
|
|
142
|
+
if (!clause.forward && negated.length) return null;
|
|
143
|
+
const heads = clause.forward ? clause.plainHeads.filter((head) => head !== 'true' && head !== 'false') : [clause.head];
|
|
144
|
+
const constraint = clause.forward && clause.plainHeads.includes('false');
|
|
145
|
+
return {
|
|
146
|
+
id: clause.id, forward: clause.forward, positive, negated, heads, constraint, pure,
|
|
147
|
+
datalog: !negated.length && !clause.restricted,
|
|
148
|
+
};
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
let serial = 0;
|
|
152
|
+
function renamed(rule) {
|
|
153
|
+
const names = new Map();
|
|
154
|
+
const suffix = `chain${++serial}`;
|
|
155
|
+
return {
|
|
156
|
+
positive: rule.positive.map((goal) => freshTerm(goal, suffix, names)),
|
|
157
|
+
negated: rule.negated.map((group) => group.map((goal) => freshTerm(goal, suffix, names))),
|
|
158
|
+
heads: rule.heads.map((goal) => freshTerm(goal, suffix, names)),
|
|
159
|
+
};
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
// Variables written as constants, so that facts can be matched by rules.
|
|
163
|
+
function freeze(term, names) {
|
|
164
|
+
if (term instanceof Var) {
|
|
165
|
+
if (!names.has(term.name)) names.set(term.name, new Struct('$chain_var', [term.name]));
|
|
166
|
+
return names.get(term.name);
|
|
167
|
+
}
|
|
168
|
+
if (term instanceof Struct) return new Struct(term.name, term.args.map((arg) => freeze(arg, names)));
|
|
169
|
+
return term;
|
|
170
|
+
}
|
|
171
|
+
function thaw(term, vars) {
|
|
172
|
+
if (isTerm(term, '$chain_var', 1)) {
|
|
173
|
+
if (!vars.has(term.args[0])) vars.set(term.args[0], new Var(term.args[0]));
|
|
174
|
+
return vars.get(term.args[0]);
|
|
175
|
+
}
|
|
176
|
+
if (term instanceof Struct) return new Struct(term.name, term.args.map((arg) => thaw(arg, vars)));
|
|
177
|
+
return term;
|
|
178
|
+
}
|
|
179
|
+
function frozenNames(term, out = new Set()) {
|
|
180
|
+
if (isTerm(term, '$chain_var', 1)) out.add(term.args[0]);
|
|
181
|
+
else if (term instanceof Struct) for (const arg of term.args) frozenNames(arg, out);
|
|
182
|
+
return out;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
// The closure of frozen facts under the pure Datalog rules: a Map of facts by
|
|
186
|
+
// identity, null when a contradiction holds, undefined beyond the limit.
|
|
187
|
+
function closure(facts, datalog) {
|
|
188
|
+
const known = new Map(facts.map((fact) => [identity(fact), fact]));
|
|
189
|
+
for (let changed = true; changed;) {
|
|
190
|
+
changed = false;
|
|
191
|
+
for (const rule of datalog) {
|
|
192
|
+
const fresh = renamed(rule);
|
|
193
|
+
for (const env of matches(fresh.positive, 0, [...known.values()], new Env())) {
|
|
194
|
+
if (rule.constraint) return null;
|
|
195
|
+
for (const head of fresh.heads) {
|
|
196
|
+
const fact = copyResolved(head, env);
|
|
197
|
+
if (variables(fact).size) continue;
|
|
198
|
+
const id = identity(fact);
|
|
199
|
+
if (known.has(id)) continue;
|
|
200
|
+
known.set(id, fact);
|
|
201
|
+
changed = true;
|
|
202
|
+
if (known.size > CHAIN_LIMITS.facts) return undefined;
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
return known;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
function* matches(goals, index, facts, env) {
|
|
211
|
+
if (index === goals.length) {
|
|
212
|
+
yield env;
|
|
213
|
+
return;
|
|
214
|
+
}
|
|
215
|
+
for (const fact of facts) {
|
|
216
|
+
const mark = env.mark();
|
|
217
|
+
if (unify(goals[index], fact, env)) yield* matches(goals, index + 1, facts, env);
|
|
218
|
+
env.undo(mark);
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
// Whether goals, their variables free, hold among frozen facts.
|
|
223
|
+
function holds(goals, facts) {
|
|
224
|
+
for (const _ of matches(goals, 0, facts, new Env())) return true; // eslint-disable-line no-unused-vars
|
|
225
|
+
return false;
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
// A chain state: the last rule's heads, the closure of the chain's facts
|
|
229
|
+
// that mention only their variables, and which of those the chain caused,
|
|
230
|
+
// with a label naming it up to renaming. The chain's conditions hold
|
|
231
|
+
// independently of it: the start's goals, and each later rule's goals but
|
|
232
|
+
// the one a caused fact matched. A fact is caused when the closure of
|
|
233
|
+
// everything holds it but the closure of the conditions does not. null when
|
|
234
|
+
// a contradiction holds, undefined beyond the limit.
|
|
235
|
+
function stateOf(rule, instance, datalog, conditions = instance.positive, caused = []) {
|
|
236
|
+
const names = new Map();
|
|
237
|
+
const independent = conditions.map((goal) => freeze(goal, names));
|
|
238
|
+
const base = closure(independent, datalog);
|
|
239
|
+
if (base === null) return null;
|
|
240
|
+
if (base === undefined) return undefined;
|
|
241
|
+
const heads = instance.heads.map((goal) => freeze(goal, names));
|
|
242
|
+
const facts = closure([...independent, ...caused.map((goal) => freeze(goal, names)), ...heads], datalog);
|
|
243
|
+
if (facts === null) return null;
|
|
244
|
+
if (facts === undefined) return undefined;
|
|
245
|
+
const keep = new Set();
|
|
246
|
+
for (const head of heads) frozenNames(head, keep);
|
|
247
|
+
const kept = [...facts.values()].filter((fact) => [...frozenNames(fact)].every((name) => keep.has(name)));
|
|
248
|
+
const added = kept.map((fact) => !base.has(identity(fact)));
|
|
249
|
+
// Rename the kept variables in order of their first occurrence in the heads.
|
|
250
|
+
const order = new Map();
|
|
251
|
+
for (const head of heads) for (const name of frozenNames(head)) if (!order.has(name)) order.set(name, `V${order.size}`);
|
|
252
|
+
const canonical = (term) => (isTerm(term, '$chain_var', 1) ? new Struct('$chain_var', [order.get(term.args[0])])
|
|
253
|
+
: term instanceof Struct ? new Struct(term.name, term.args.map(canonical)) : term);
|
|
254
|
+
const texts = kept.map((fact, i) => `${added[i] ? '+' : ''}${identity(canonical(fact))}`).sort();
|
|
255
|
+
const label = `${rule.id}\u0001${heads.map((head) => identity(canonical(head))).join('\u0002')}\u0001${texts.join('\u0002')}`;
|
|
256
|
+
return { rule, heads: heads.map(canonical), facts: kept.map(canonical), added, label };
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
// The chain states extending a state by one application of next: a goal of
|
|
260
|
+
// next matches a fact the state's heads add, a head or what the Datalog
|
|
261
|
+
// rules derive with it, the facts do not already satisfy next's heads or a
|
|
262
|
+
// negated group of next, and no contradiction holds.
|
|
263
|
+
function* extensions(state, next, datalog) {
|
|
264
|
+
const vars = new Map();
|
|
265
|
+
const facts = state.facts.map((fact) => thaw(fact, vars));
|
|
266
|
+
const added = facts.filter((_, i) => state.added[i]);
|
|
267
|
+
for (let position = 0; position < next.positive.length; position++) {
|
|
268
|
+
for (const head of added) {
|
|
269
|
+
const instance = renamed(next);
|
|
270
|
+
const env = new Env();
|
|
271
|
+
if (!unify(instance.positive[position], head, env)) continue;
|
|
272
|
+
const resolve = (goal) => copyResolved(goal, env);
|
|
273
|
+
const body = [...facts.map(resolve), ...instance.positive.map(resolve)];
|
|
274
|
+
const causedBefore = facts.filter((_, i) => state.added[i]).map(resolve);
|
|
275
|
+
const causedIds = new Set(causedBefore.map((goal) => identity(goal)));
|
|
276
|
+
const conditions = [...facts.filter((_, i) => !state.added[i]).map(resolve),
|
|
277
|
+
...instance.positive.map(resolve).filter((goal) => !causedIds.has(identity(goal)))];
|
|
278
|
+
const applied = { positive: instance.positive.map(resolve), negated: instance.negated.map((group) => group.map(resolve)), heads: instance.heads.map(resolve) };
|
|
279
|
+
const names = new Map();
|
|
280
|
+
const known = closure(body.map((goal) => freeze(goal, names)), datalog);
|
|
281
|
+
if (known === null) continue;
|
|
282
|
+
if (known === undefined) {
|
|
283
|
+
yield undefined;
|
|
284
|
+
return;
|
|
285
|
+
}
|
|
286
|
+
// Whether next adds something, and whether its negations hold, is
|
|
287
|
+
// asked of the chain's closed facts and next's own goals, not of
|
|
288
|
+
// their closure: the closure would include next's own conclusion.
|
|
289
|
+
// Frozen, but with the variables only next's heads or negations
|
|
290
|
+
// mention left free, as existential patterns.
|
|
291
|
+
const pattern = (goal) => freezeBound(goal, names);
|
|
292
|
+
const before = body.map(pattern);
|
|
293
|
+
if (holds(applied.heads.map(pattern), before)) continue;
|
|
294
|
+
if (applied.negated.some((group) => holds(group.map(pattern), before))) continue;
|
|
295
|
+
const extended = stateOf(next, applied, datalog, conditions, causedBefore);
|
|
296
|
+
if (extended === undefined) {
|
|
297
|
+
yield undefined;
|
|
298
|
+
return;
|
|
299
|
+
}
|
|
300
|
+
if (extended !== null) yield extended;
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
// A goal with the variables the frozen facts name frozen and the others free.
|
|
306
|
+
function freezeBound(term, names) {
|
|
307
|
+
if (term instanceof Var) return names.has(term.name) ? names.get(term.name) : term;
|
|
308
|
+
if (term instanceof Struct) return new Struct(term.name, term.args.map((arg) => freezeBound(arg, names)));
|
|
309
|
+
return term;
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
// Whether a fact the state's heads add, a head or what the Datalog rules
|
|
313
|
+
// derive with it, can make a negated goal of target true without a
|
|
314
|
+
// contradiction holding.
|
|
315
|
+
function disables(state, target, datalog) {
|
|
316
|
+
const vars = new Map();
|
|
317
|
+
const facts = state.facts.map((fact) => thaw(fact, vars));
|
|
318
|
+
const added = facts.filter((_, i) => state.added[i]);
|
|
319
|
+
for (const group of target.negated) {
|
|
320
|
+
for (let position = 0; position < group.length; position++) {
|
|
321
|
+
for (const head of added) {
|
|
322
|
+
const instance = renamed(target);
|
|
323
|
+
const env = new Env();
|
|
324
|
+
const goal = instance.negated[target.negated.indexOf(group)][position];
|
|
325
|
+
if (!unify(goal, head, env)) continue;
|
|
326
|
+
const names = new Map();
|
|
327
|
+
const known = closure(facts.map((fact) => freeze(copyResolved(fact, env), names)), datalog);
|
|
328
|
+
if (known !== null) return true;
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
return false;
|
|
333
|
+
}
|
package/src/engine.js
CHANGED
|
@@ -286,6 +286,7 @@ export class Solver {
|
|
|
286
286
|
this.genericKeys = new Set();
|
|
287
287
|
this.genericPredicates = new Set();
|
|
288
288
|
this.derived = [];
|
|
289
|
+
this.guards = [];
|
|
289
290
|
this.reported = new Map();
|
|
290
291
|
this.stats = { inferences: 0, rounds: 0, derived: 0 };
|
|
291
292
|
this.haltCode = null;
|
|
@@ -810,7 +811,9 @@ export class Solver {
|
|
|
810
811
|
}
|
|
811
812
|
if (this.recording || clause.templates.length) bindings = [...names].map(([name, value]) => [name, copyResolved(value, answerEnv)]);
|
|
812
813
|
const claim = conclusions.some((item) => item === 'true') ? copyResolved(conjunction(body), answerEnv) : null;
|
|
813
|
-
|
|
814
|
+
// A restricted firing keeps its guard, checked again once reasoning ends.
|
|
815
|
+
const guard = clause.guard === null || !unresolved.size ? null : copyResolved(body[body.length - 1], answerEnv);
|
|
816
|
+
found.push([[conclusions, children, bindings, claim, guard], this.chosen !== null ? [...this.chosen] : null]);
|
|
814
817
|
answerEnv.undo(mark);
|
|
815
818
|
}
|
|
816
819
|
return found;
|
|
@@ -822,71 +825,122 @@ export class Solver {
|
|
|
822
825
|
// stratum, restricted rules run only in a round where the other rules
|
|
823
826
|
// derive nothing, so their guards see what those rules derive.
|
|
824
827
|
forward(reporting = true) {
|
|
828
|
+
this.forwardRounds(reporting);
|
|
829
|
+
// A restricted rule's witness must still be needed once reasoning ends:
|
|
830
|
+
// otherwise later facts satisfy its heads, and the result depends on
|
|
831
|
+
// the order in which rules were applied (SPEC Section 8.2).
|
|
832
|
+
if (this.haltCode !== null) return;
|
|
833
|
+
for (const [clause, guard, conclusions] of this.guards) {
|
|
834
|
+
if (this.holds(guard)) continue;
|
|
835
|
+
throw new EyemindError(`restricted rule ${clause.id} concluded ${text(conclusions[0])}, whose witness later facts make unneeded; ` +
|
|
836
|
+
'the result depends on the order of rule applications');
|
|
837
|
+
}
|
|
838
|
+
}
|
|
839
|
+
|
|
840
|
+
// Whether a goal holds in the current state.
|
|
841
|
+
holds(goal) {
|
|
842
|
+
for (const _ of this.solve([goal], new Env())) return true; // eslint-disable-line no-unused-vars
|
|
843
|
+
return false;
|
|
844
|
+
}
|
|
845
|
+
|
|
846
|
+
forwardRounds(reporting) {
|
|
825
847
|
const layers = new Map();
|
|
826
848
|
for (const clause of this.program.forward) {
|
|
827
849
|
const rank = this.program.strata.get(clause.id) || 0;
|
|
828
850
|
if (!layers.has(rank)) layers.set(rank, []);
|
|
829
851
|
layers.get(rank).push(clause);
|
|
830
852
|
}
|
|
853
|
+
// In a chain stratum too, a restricted rule runs after those whose heads
|
|
854
|
+
// can satisfy its own.
|
|
855
|
+
if (this.program.layered) {
|
|
856
|
+
for (const [rank, rules] of layers) {
|
|
857
|
+
const restricted = this.program.restraining(rules.filter((clause) => clause.restricted));
|
|
858
|
+
layers.set(rank, [...rules.filter((clause) => !clause.restricted), ...restricted]);
|
|
859
|
+
}
|
|
860
|
+
}
|
|
861
|
+
const ranks = [...layers.keys()].sort((a, b) => a - b);
|
|
831
862
|
const maxIterations = this.options.maxIterations || 1000;
|
|
832
|
-
|
|
863
|
+
let rounds = 0;
|
|
864
|
+
const round = (rules) => {
|
|
865
|
+
rounds++;
|
|
866
|
+
if (rounds > maxIterations) throw new EyemindError('forward reasoning exceeded max_iterations');
|
|
867
|
+
this.stats.rounds++;
|
|
868
|
+
return this.round(rules, reporting);
|
|
869
|
+
};
|
|
870
|
+
if (this.program.layered) {
|
|
871
|
+
// Chain strata (SPEC Section 6.4): a layer runs a round only when
|
|
872
|
+
// every lower layer's last round derived nothing, and after a round
|
|
873
|
+
// that derives something the lowest layer runs again.
|
|
874
|
+
for (let i = 0; i < ranks.length;) {
|
|
875
|
+
const changed = round(layers.get(ranks[i]));
|
|
876
|
+
if (changed === 'halt') return;
|
|
877
|
+
i = changed ? 0 : i + 1;
|
|
878
|
+
}
|
|
879
|
+
return;
|
|
880
|
+
}
|
|
881
|
+
for (const rank of ranks) {
|
|
882
|
+
rounds = 0;
|
|
833
883
|
const all = layers.get(rank);
|
|
834
|
-
const restricted = all.filter((clause) => clause.restricted);
|
|
884
|
+
const restricted = this.program.restraining(all.filter((clause) => clause.restricted));
|
|
835
885
|
const ordinary = restricted.length ? all.filter((clause) => !clause.restricted) : all;
|
|
836
886
|
let changed = true;
|
|
837
|
-
let rounds = 0;
|
|
838
887
|
let lean = false;
|
|
839
888
|
while (changed || (!lean && restricted.length)) {
|
|
840
889
|
// After a round of the other rules that derives nothing, a round of
|
|
841
890
|
// the restricted ones; after one of those that derives nothing, done.
|
|
842
891
|
lean = !changed && restricted.length > 0;
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
892
|
+
changed = round(lean ? restricted : ordinary);
|
|
893
|
+
if (changed === 'halt') return;
|
|
894
|
+
}
|
|
895
|
+
}
|
|
896
|
+
}
|
|
897
|
+
|
|
898
|
+
// One round of rules in clause order: true when it derived something,
|
|
899
|
+
// 'halt' when a contradiction stopped reasoning.
|
|
900
|
+
round(rules, reporting) {
|
|
901
|
+
let changed = false;
|
|
902
|
+
for (const original of rules) {
|
|
903
|
+
const instances = original.parentId === null ? [original] : this.rules.get(original.id) || NO_NODES;
|
|
904
|
+
const firings = [];
|
|
905
|
+
for (const clause of instances) {
|
|
906
|
+
if (!reporting && clause.heads.every((item) => item === 'true')) continue;
|
|
907
|
+
for (const firing of this.firings(clause)) firings.push([clause, firing]);
|
|
908
|
+
}
|
|
909
|
+
// All instances of this template see the same state. Publishing one
|
|
910
|
+
// instance's conclusions during another's search changes recursive
|
|
911
|
+
// bodies and their observable order.
|
|
912
|
+
for (const [clause, [conclusions, children, bindings, claim, guard]] of firings) {
|
|
913
|
+
if (guard) this.guards.push([clause, guard, conclusions]);
|
|
914
|
+
for (const [position, conclusion] of conclusions.entries()) {
|
|
915
|
+
const template = clause.templates.find((item) => item.position === position);
|
|
916
|
+
if (template) {
|
|
917
|
+
if (this.deriveRules(template, conclusion, bindings, children)) changed = true;
|
|
918
|
+
continue;
|
|
919
|
+
}
|
|
920
|
+
if (conclusion === 'true') {
|
|
921
|
+
const claimId = this.program.inspectionEnabled ? variant(claim) : text(claim);
|
|
922
|
+
if (!this.reported.has(claimId)) this.reported.set(claimId, [claim, children, clause.id]);
|
|
923
|
+
continue;
|
|
854
924
|
}
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
const template = clause.templates.find((item) => item.position === position);
|
|
861
|
-
if (template) {
|
|
862
|
-
if (this.deriveRules(template, conclusion, bindings, children)) changed = true;
|
|
863
|
-
continue;
|
|
864
|
-
}
|
|
865
|
-
if (conclusion === 'true') {
|
|
866
|
-
const claimId = this.program.inspectionEnabled ? variant(claim) : text(claim);
|
|
867
|
-
if (!this.reported.has(claimId)) this.reported.set(claimId, [claim, children, clause.id]);
|
|
868
|
-
continue;
|
|
869
|
-
}
|
|
870
|
-
const node = new Node(conclusion, new Struct('clause', [BigInt(clause.id)]), bindings, children, null, true);
|
|
871
|
-
if (conclusion === 'false') {
|
|
872
|
-
this.derived.push(node);
|
|
873
|
-
this.haltCode = 65;
|
|
874
|
-
return;
|
|
875
|
-
}
|
|
876
|
-
node.generic = this.program.inspectionEnabled && !isGround(conclusion);
|
|
877
|
-
const conclusionId = node.generic ? variant(conclusion) : identity(conclusion);
|
|
878
|
-
const factKeys = node.generic ? this.genericKeys : this.factKeys;
|
|
879
|
-
if (factKeys.has(conclusionId)) continue;
|
|
880
|
-
factKeys.add(conclusionId);
|
|
881
|
-
this.addFact(key(conclusion), node);
|
|
882
|
-
this.derived.push(node);
|
|
883
|
-
this.stats.derived++;
|
|
884
|
-
changed = true;
|
|
885
|
-
}
|
|
925
|
+
const node = new Node(conclusion, new Struct('clause', [BigInt(clause.id)]), bindings, children, null, true);
|
|
926
|
+
if (conclusion === 'false') {
|
|
927
|
+
this.derived.push(node);
|
|
928
|
+
this.haltCode = 65;
|
|
929
|
+
return 'halt';
|
|
886
930
|
}
|
|
931
|
+
node.generic = this.program.inspectionEnabled && !isGround(conclusion);
|
|
932
|
+
const conclusionId = node.generic ? variant(conclusion) : identity(conclusion);
|
|
933
|
+
const factKeys = node.generic ? this.genericKeys : this.factKeys;
|
|
934
|
+
if (factKeys.has(conclusionId)) continue;
|
|
935
|
+
factKeys.add(conclusionId);
|
|
936
|
+
this.addFact(key(conclusion), node);
|
|
937
|
+
this.derived.push(node);
|
|
938
|
+
this.stats.derived++;
|
|
939
|
+
changed = true;
|
|
887
940
|
}
|
|
888
941
|
}
|
|
889
942
|
}
|
|
943
|
+
return changed;
|
|
890
944
|
}
|
|
891
945
|
}
|
|
892
946
|
|
package/src/program.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
// A program: its clauses, validated, indexed and stratified.
|
|
2
2
|
import { PRIMITIVE_KEYS } from './builtins.js';
|
|
3
3
|
import { containsTemplate, expandTemplates } from './templates.js';
|
|
4
|
+
import { chainStrata } from './chains.js';
|
|
4
5
|
import { subgoals } from './goals.js';
|
|
5
6
|
import { hasInspection, inspectionTerm } from './inspection.js';
|
|
6
7
|
import {
|
|
@@ -195,6 +196,30 @@ export class Program {
|
|
|
195
196
|
if (!clause.forward && !clause.body.length && isGround(clause.head)) this.groundFactKeys.add(identity(clause.head));
|
|
196
197
|
}
|
|
197
198
|
this.strata = stratify(this.clauses, stratifying);
|
|
199
|
+
// Chain strata run layer by layer, a lower layer again after each change.
|
|
200
|
+
this.layered = this.strata.layered === true;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
// Restricted rules in the order they run: one whose heads can satisfy
|
|
204
|
+
// another's, its witnesses free, before that one, and otherwise, as on a
|
|
205
|
+
// cycle of such rules, in clause order (SPEC Section 8.2).
|
|
206
|
+
restraining(rules) {
|
|
207
|
+
if (rules.length < 2) return rules;
|
|
208
|
+
const before = new Map(rules.map((rule) => [rule.id, new Set()]));
|
|
209
|
+
for (const first of rules) {
|
|
210
|
+
for (const second of rules) {
|
|
211
|
+
if (first !== second && restrains(first, second)) before.get(second.id).add(first.id);
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
const order = [];
|
|
215
|
+
const placed = new Set();
|
|
216
|
+
while (order.length < rules.length) {
|
|
217
|
+
const ready = rules.find((rule) => !placed.has(rule.id) && [...before.get(rule.id)].every((id) => placed.has(id)))
|
|
218
|
+
?? rules.find((rule) => !placed.has(rule.id));
|
|
219
|
+
order.push(ready);
|
|
220
|
+
placed.add(ready.id);
|
|
221
|
+
}
|
|
222
|
+
return order;
|
|
198
223
|
}
|
|
199
224
|
|
|
200
225
|
prepareInspections() {
|
|
@@ -355,6 +380,33 @@ function restriction(ordinal, head, heads, body) {
|
|
|
355
380
|
return new Struct('not', [conjunction([...heads.map(rename), other])]);
|
|
356
381
|
}
|
|
357
382
|
|
|
383
|
+
// Whether firing a restricted rule can satisfy another's heads: a head of
|
|
384
|
+
// the first matches a head of the second that holds a witness, and the
|
|
385
|
+
// first's heads also match every other head of the second sharing that
|
|
386
|
+
// witness.
|
|
387
|
+
function restrains(first, second) {
|
|
388
|
+
const witnesses = new Set(second.witnessNames.map((name) => `${name}#restrained`));
|
|
389
|
+
const targets = flattenConjunction(freshTerm(conjunction(second.plainHeads), 'restrained'));
|
|
390
|
+
const own = flattenConjunction(freshTerm(conjunction(first.plainHeads), 'restraining'));
|
|
391
|
+
const witnessesOf = (term) => [...variables(term).keys()].filter((name) => witnesses.has(name));
|
|
392
|
+
const matchAll = (goals, env) => {
|
|
393
|
+
if (!goals.length) return true;
|
|
394
|
+
for (const head of own) {
|
|
395
|
+
const mark = env.mark();
|
|
396
|
+
if (unify(head, goals[0], env) && matchAll(goals.slice(1), env)) return true;
|
|
397
|
+
env.undo(mark);
|
|
398
|
+
}
|
|
399
|
+
return false;
|
|
400
|
+
};
|
|
401
|
+
for (const target of targets) {
|
|
402
|
+
const shared = witnessesOf(target);
|
|
403
|
+
if (!shared.length) continue;
|
|
404
|
+
const piece = targets.filter((other) => witnessesOf(other).some((name) => shared.includes(name)));
|
|
405
|
+
if (matchAll(piece, new Env())) return true;
|
|
406
|
+
}
|
|
407
|
+
return false;
|
|
408
|
+
}
|
|
409
|
+
|
|
358
410
|
// Whether a goal could contribute a closed dependency or a dynamic call.
|
|
359
411
|
function mayNeedStratifying(goal) {
|
|
360
412
|
if (goal instanceof Var || isTerm(goal, 'not', 1) || isTerm(goal, 'findall', 3)) return true;
|
|
@@ -449,5 +501,9 @@ function stratify(clauses, stratifying) {
|
|
|
449
501
|
}
|
|
450
502
|
if (!changed) return ranks;
|
|
451
503
|
}
|
|
452
|
-
|
|
504
|
+
// A program classic stratification rejects may still be chain-stratified.
|
|
505
|
+
const chained = chainStrata(clauses);
|
|
506
|
+
if (chained === null) throw new EyemindError('unstratified negation or collection dependency');
|
|
507
|
+
chained.layered = true;
|
|
508
|
+
return chained;
|
|
453
509
|
}
|
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.
|
|
2
|
+
export const VERSION = '0.5.16';
|