eyemind 0.5.14 → 0.5.15
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 +2 -2
- package/SPEC.md +105 -2
- package/package.json +1 -1
- package/src/chains.js +333 -0
- package/src/engine.js +67 -44
- package/src/program.js +8 -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 1369 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
|
|
|
@@ -394,7 +394,7 @@ The statement chooses the direction:
|
|
|
394
394
|
|
|
395
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.
|
|
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.15
|
|
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,6 +1136,15 @@ 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
1149
|
rules run in rounds as above; a round of its restricted rules, in clause
|
|
1047
1150
|
order, follows only a round of the other rules that adds nothing, and is
|
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
|
@@ -828,65 +828,88 @@ export class Solver {
|
|
|
828
828
|
if (!layers.has(rank)) layers.set(rank, []);
|
|
829
829
|
layers.get(rank).push(clause);
|
|
830
830
|
}
|
|
831
|
+
const ranks = [...layers.keys()].sort((a, b) => a - b);
|
|
831
832
|
const maxIterations = this.options.maxIterations || 1000;
|
|
832
|
-
|
|
833
|
+
let rounds = 0;
|
|
834
|
+
const round = (rules) => {
|
|
835
|
+
rounds++;
|
|
836
|
+
if (rounds > maxIterations) throw new EyemindError('forward reasoning exceeded max_iterations');
|
|
837
|
+
this.stats.rounds++;
|
|
838
|
+
return this.round(rules, reporting);
|
|
839
|
+
};
|
|
840
|
+
if (this.program.layered) {
|
|
841
|
+
// Chain strata (SPEC Section 6.4): a layer runs a round only when
|
|
842
|
+
// every lower layer's last round derived nothing, and after a round
|
|
843
|
+
// that derives something the lowest layer runs again.
|
|
844
|
+
for (let i = 0; i < ranks.length;) {
|
|
845
|
+
const changed = round(layers.get(ranks[i]));
|
|
846
|
+
if (changed === 'halt') return;
|
|
847
|
+
i = changed ? 0 : i + 1;
|
|
848
|
+
}
|
|
849
|
+
return;
|
|
850
|
+
}
|
|
851
|
+
for (const rank of ranks) {
|
|
852
|
+
rounds = 0;
|
|
833
853
|
const all = layers.get(rank);
|
|
834
854
|
const restricted = all.filter((clause) => clause.restricted);
|
|
835
855
|
const ordinary = restricted.length ? all.filter((clause) => !clause.restricted) : all;
|
|
836
856
|
let changed = true;
|
|
837
|
-
let rounds = 0;
|
|
838
857
|
let lean = false;
|
|
839
858
|
while (changed || (!lean && restricted.length)) {
|
|
840
859
|
// After a round of the other rules that derives nothing, a round of
|
|
841
860
|
// the restricted ones; after one of those that derives nothing, done.
|
|
842
861
|
lean = !changed && restricted.length > 0;
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
862
|
+
changed = round(lean ? restricted : ordinary);
|
|
863
|
+
if (changed === 'halt') return;
|
|
864
|
+
}
|
|
865
|
+
}
|
|
866
|
+
}
|
|
867
|
+
|
|
868
|
+
// One round of rules in clause order: true when it derived something,
|
|
869
|
+
// 'halt' when a contradiction stopped reasoning.
|
|
870
|
+
round(rules, reporting) {
|
|
871
|
+
let changed = false;
|
|
872
|
+
for (const original of rules) {
|
|
873
|
+
const instances = original.parentId === null ? [original] : this.rules.get(original.id) || NO_NODES;
|
|
874
|
+
const firings = [];
|
|
875
|
+
for (const clause of instances) {
|
|
876
|
+
if (!reporting && clause.heads.every((item) => item === 'true')) continue;
|
|
877
|
+
for (const firing of this.firings(clause)) firings.push([clause, firing]);
|
|
878
|
+
}
|
|
879
|
+
// All instances of this template see the same state. Publishing one
|
|
880
|
+
// instance's conclusions during another's search changes recursive
|
|
881
|
+
// bodies and their observable order.
|
|
882
|
+
for (const [clause, [conclusions, children, bindings, claim]] of firings) {
|
|
883
|
+
for (const [position, conclusion] of conclusions.entries()) {
|
|
884
|
+
const template = clause.templates.find((item) => item.position === position);
|
|
885
|
+
if (template) {
|
|
886
|
+
if (this.deriveRules(template, conclusion, bindings, children)) changed = true;
|
|
887
|
+
continue;
|
|
888
|
+
}
|
|
889
|
+
if (conclusion === 'true') {
|
|
890
|
+
const claimId = this.program.inspectionEnabled ? variant(claim) : text(claim);
|
|
891
|
+
if (!this.reported.has(claimId)) this.reported.set(claimId, [claim, children, clause.id]);
|
|
892
|
+
continue;
|
|
854
893
|
}
|
|
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
|
-
}
|
|
894
|
+
const node = new Node(conclusion, new Struct('clause', [BigInt(clause.id)]), bindings, children, null, true);
|
|
895
|
+
if (conclusion === 'false') {
|
|
896
|
+
this.derived.push(node);
|
|
897
|
+
this.haltCode = 65;
|
|
898
|
+
return 'halt';
|
|
886
899
|
}
|
|
900
|
+
node.generic = this.program.inspectionEnabled && !isGround(conclusion);
|
|
901
|
+
const conclusionId = node.generic ? variant(conclusion) : identity(conclusion);
|
|
902
|
+
const factKeys = node.generic ? this.genericKeys : this.factKeys;
|
|
903
|
+
if (factKeys.has(conclusionId)) continue;
|
|
904
|
+
factKeys.add(conclusionId);
|
|
905
|
+
this.addFact(key(conclusion), node);
|
|
906
|
+
this.derived.push(node);
|
|
907
|
+
this.stats.derived++;
|
|
908
|
+
changed = true;
|
|
887
909
|
}
|
|
888
910
|
}
|
|
889
911
|
}
|
|
912
|
+
return changed;
|
|
890
913
|
}
|
|
891
914
|
}
|
|
892
915
|
|
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,8 @@ 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;
|
|
198
201
|
}
|
|
199
202
|
|
|
200
203
|
prepareInspections() {
|
|
@@ -449,5 +452,9 @@ function stratify(clauses, stratifying) {
|
|
|
449
452
|
}
|
|
450
453
|
if (!changed) return ranks;
|
|
451
454
|
}
|
|
452
|
-
|
|
455
|
+
// A program classic stratification rejects may still be chain-stratified.
|
|
456
|
+
const chained = chainStrata(clauses);
|
|
457
|
+
if (chained === null) throw new EyemindError('unstratified negation or collection dependency');
|
|
458
|
+
chained.layered = true;
|
|
459
|
+
return chained;
|
|
453
460
|
}
|
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.15';
|