eyemind 0.8.10 → 0.8.11
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/LE-SPEC.md +76 -0
- package/LS-SPEC.md +1 -1
- package/README.md +34 -8
- package/package.json +1 -1
- package/src/cli.js +30 -6
- package/src/formats.js +32 -13
- package/src/le.js +167 -33
- package/src/node-messages.js +1 -1
- package/src/program.js +31 -0
- package/src/rdf-logic.js +48 -4
- package/src/specialize.js +533 -0
- package/src/version.js +1 -1
package/LE-SPEC.md
CHANGED
|
@@ -125,6 +125,79 @@ keeps integer and float terms distinct. Calculations belong in premises,
|
|
|
125
125
|
followed by relational conclusions. These calculations do not prove arbitrary
|
|
126
126
|
algebraic identities or supply induction.
|
|
127
127
|
|
|
128
|
+
## Alternative premises
|
|
129
|
+
|
|
130
|
+
```text
|
|
131
|
+
Every cat or dog is a pet.
|
|
132
|
+
For every V, if V is registered or V is a provisionalVoter and V is verified
|
|
133
|
+
then V is an eligibleVoter.
|
|
134
|
+
For every X, it is impossible that X is a minor and X is a voter or X is barred.
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
`or` separates alternative premises of a rule or contradiction. `and` binds
|
|
138
|
+
more tightly, so each alternative is a conjunction; there are no parentheses
|
|
139
|
+
around alternatives. Each alternative compiles to its own LS clause with the
|
|
140
|
+
same conclusion, in the order written: `Every A or B is C.` is
|
|
141
|
+
`implies(A(X), C(X))` followed by `implies(B(X), C(X))`. The sentence's
|
|
142
|
+
declarations are shared, and an alternative need not use every declared
|
|
143
|
+
variable, but each conclusion variable must be supplied by every alternative
|
|
144
|
+
or introduced with `there exists`. An existential conclusion therefore has a
|
|
145
|
+
witness per alternative and firing. The order of premises is checked within
|
|
146
|
+
each alternative.
|
|
147
|
+
|
|
148
|
+
Questions have no `or`: ask one question per alternative, or ask for a relation
|
|
149
|
+
that an `or` rule derives. Conclusions are never disjunctive.
|
|
150
|
+
|
|
151
|
+
## Aggregates
|
|
152
|
+
|
|
153
|
+
```text
|
|
154
|
+
For every M and T,
|
|
155
|
+
if M is a member and T is the sum of F for every C and F such that charge(M, C, F)
|
|
156
|
+
then T is an amountDue of M.
|
|
157
|
+
For every V and N,
|
|
158
|
+
if V is a participant and N is the number of C such that choice(V, C) and N is at least 2
|
|
159
|
+
then V is a spoiledVoter.
|
|
160
|
+
For every C and N,
|
|
161
|
+
if C is a candidate and N is the number of V such that
|
|
162
|
+
(choice(V, C) and V is an eligibleVoter and it is not known that V is a spoiledVoter)
|
|
163
|
+
then N is a voteCount of C.
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
These premise forms collect every solution of a condition:
|
|
167
|
+
|
|
168
|
+
| LE form | Result |
|
|
169
|
+
| --- | --- |
|
|
170
|
+
| `N is the number of X1 and ... such that C` | The number of distinct combinations of `X1 ...` satisfying `C`. |
|
|
171
|
+
| `S is the sum of V for every X1 and ... such that C` | The sum of `V` over those combinations; `0` when there are none. |
|
|
172
|
+
| `M is the maximum of V for every X1 and ... such that C` | The greatest `V` over those combinations; no result when there are none. |
|
|
173
|
+
| `M is the minimum of V for every X1 and ... such that C` | The least `V` over those combinations; no result when there are none. |
|
|
174
|
+
|
|
175
|
+
The variables after `the number of` or `for every` are declared by the
|
|
176
|
+
aggregate, must be new in the sentence, and cannot be used after it. `V` must
|
|
177
|
+
be one of them. The condition `C` is one statement, or a conjunction in
|
|
178
|
+
parentheses; it can use calculations, comparisons and absence tests, but no
|
|
179
|
+
`or` and no other aggregate. Any other variable of `C` must be supplied by an earlier premise. The
|
|
180
|
+
left-hand side is a declared variable or a number, as in the value-of form:
|
|
181
|
+
an unbound variable receives the result and a bound one is compared with it.
|
|
182
|
+
|
|
183
|
+
Each distinct combination of the declared variables' values counts once, however
|
|
184
|
+
many derivations it has. To count distinct values of one variable when the
|
|
185
|
+
condition needs others, derive a relation of that variable first, as
|
|
186
|
+
`choice(V, C)` above does for ballots. Values are summed with LS arithmetic, so
|
|
187
|
+
integers stay exact and a float makes the sum a float; maximum and minimum
|
|
188
|
+
compare numerically.
|
|
189
|
+
|
|
190
|
+
An aggregate compiles to
|
|
191
|
+
`findall_sorted(t(V, X1, ...), C, L)`, followed by goals of backward helper
|
|
192
|
+
relations named `le:distinct`, `le:count`, `le:sum`, `le:max` and `le:min`,
|
|
193
|
+
which remove repeated tuples and fold the rest. The helpers are added after
|
|
194
|
+
the program's own clauses, only when used, so they do not change the rule
|
|
195
|
+
numbers of witnesses; their names cannot be written as LE names. Like a
|
|
196
|
+
negation, an aggregate waits until the relations of its condition are complete,
|
|
197
|
+
so a program cannot aggregate over a relation that depends on the aggregate's
|
|
198
|
+
own result. Questions cannot aggregate: derive the aggregate in a rule and ask
|
|
199
|
+
for its conclusion.
|
|
200
|
+
|
|
128
201
|
## Absence and existential conclusions
|
|
129
202
|
|
|
130
203
|
An absence test has exactly this form, followed by one positive statement:
|
|
@@ -186,6 +259,9 @@ These programs use the grammar above without additional syntax:
|
|
|
186
259
|
| [Pell equations](https://eyereasoner.github.io/eyemind/examples/deck/pell-equation-le) | Recursive arithmetic beyond binary64 integer precision and exact polynomial checks. |
|
|
187
260
|
| [Course certificates](https://eyereasoner.github.io/eyemind/examples/deck/course-certificates-le) | Recursive requirements, absence of a counterexample, shared existential witnesses and witnesses containing earlier witnesses. |
|
|
188
261
|
| [Symbolic differentiation](https://eyereasoner.github.io/eyemind/examples/deck/symbolic-derivative-le) | Structural recursion over expression trees, constructed derivatives and evaluation at separate points. |
|
|
262
|
+
| [British citizenship](https://eyereasoner.github.io/eyemind/examples/deck/british-citizenship-le) | Section 1 of the British Nationality Act 1981: alternative premises, a presumption that holds unless the contrary is shown, date comparisons and citizenship through a derived parent. |
|
|
263
|
+
| [Library fines](https://eyereasoner.github.io/eyemind/examples/deck/library-fines-le) | Charges from alternative rules, then the sum, number and maximum per member over distinct combinations. |
|
|
264
|
+
| [Election tally](https://eyereasoner.github.io/eyemind/examples/deck/election-tally-le) | Eligibility by alternatives, distinct choices, an absence test inside a count, winners by maximum with ties, and a quorum. |
|
|
189
265
|
|
|
190
266
|
Their decks state the modeled assumptions and what the checked proofs establish.
|
|
191
267
|
Bounds and finite expression domains are explicit in the programs.
|
package/LS-SPEC.md
CHANGED
package/README.md
CHANGED
|
@@ -12,8 +12,8 @@ program, a JavaScript library and a browser application.
|
|
|
12
12
|
|
|
13
13
|
[Playground](https://eyereasoner.github.io/eyemind/playground/) · [Examples](https://eyereasoner.github.io/eyemind/examples/) · [Specification](https://eyereasoner.github.io/eyemind/LS-SPEC) · [Conformance](https://eyereasoner.github.io/eyemind/conformance/)
|
|
14
14
|
|
|
15
|
-
The examples are
|
|
16
|
-
conclusions
|
|
15
|
+
The examples are 156 runnable programs, each with a card deck and saved
|
|
16
|
+
conclusions; all but one streamed example also save proofs and check reports. The specification defines the language,
|
|
17
17
|
the proof format and how a proof is checked; its conformance suite has
|
|
18
18
|
1247 cases that test language and proof behavior, and runs
|
|
19
19
|
[in your browser](https://eyereasoner.github.io/eyemind/playground/conformance).
|
|
@@ -227,16 +227,20 @@ its scope. Terms also include exact integers, floats (`1.0`, `1e3`), lists
|
|
|
227
227
|
| `For every X, ...` | a universally quantified fact |
|
|
228
228
|
| `Every A is B.` | `implies(A(X), B(X))` |
|
|
229
229
|
| `For every X and Y, if ... then ...` | a forward rule |
|
|
230
|
+
| `if A and B or C then ...`, `Every A or B is C.` | one rule per alternative; `and` binds more tightly |
|
|
230
231
|
| `Y is the value of E` | `is(Y, E)`, with `+ - * /` and parentheses |
|
|
231
232
|
| `X is greater than`, `less than`, `at least`, `at most`, `equal to`, `different from E` | `gt`, `lt`, `ge`, `le`, `eq`, `ne` |
|
|
232
233
|
| `it is not known that S` | `not(S)`, with LS's stratified meaning |
|
|
234
|
+
| `N is the number of X such that S` | a count of the distinct values of `X` |
|
|
235
|
+
| `T is the sum`, `maximum`, `minimum of V for every X and V such that S` | a fold of `V` over the distinct combinations |
|
|
233
236
|
| `then there exists Y such that ...` | a Skolem witness of the firing |
|
|
234
237
|
| `Find every X such that ...`, `Find whether ...` | `query(...)` |
|
|
235
238
|
| `It is impossible that ...`, `Contradiction.` | `contradiction(...)` |
|
|
236
239
|
|
|
237
|
-
Arithmetic
|
|
238
|
-
|
|
239
|
-
|
|
240
|
+
Arithmetic, absence tests and aggregates need their inputs from earlier
|
|
241
|
+
premises; an aggregate's own variables stay inside it, and a conjunction in its
|
|
242
|
+
condition is put in parentheses. Arithmetic follows LS: integers stay exact,
|
|
243
|
+
division gives a float. An answer becomes a sentence such as `16 is a square of 4.`; a witness is written
|
|
240
244
|
`witness(rule 4, Y, Alice)`, and conclusions read back as facts of another LE
|
|
241
245
|
program. Several `.le` files form one program, `--to le` writes LS conclusions
|
|
242
246
|
as LE, and proofs check the compiled LS, not the English-to-LS translation.
|
|
@@ -248,8 +252,11 @@ mapped to the `eval:` and `odrl:` vocabularies; see the
|
|
|
248
252
|
[handicap-card LE deck](https://eyereasoner.github.io/eyemind/examples/deck/handicap-card-le).
|
|
249
253
|
For larger programs, try
|
|
250
254
|
[shortest paths](https://eyereasoner.github.io/eyemind/examples/deck/shortest-path-le),
|
|
251
|
-
[river-crossing plans](https://eyereasoner.github.io/eyemind/examples/deck/river-crossing-le)
|
|
252
|
-
[Pell equations](https://eyereasoner.github.io/eyemind/examples/deck/pell-equation-le)
|
|
255
|
+
[river-crossing plans](https://eyereasoner.github.io/eyemind/examples/deck/river-crossing-le),
|
|
256
|
+
[Pell equations](https://eyereasoner.github.io/eyemind/examples/deck/pell-equation-le),
|
|
257
|
+
[British citizenship](https://eyereasoner.github.io/eyemind/examples/deck/british-citizenship-le),
|
|
258
|
+
[library fines](https://eyereasoner.github.io/eyemind/examples/deck/library-fines-le) or an
|
|
259
|
+
[election tally](https://eyereasoner.github.io/eyemind/examples/deck/election-tally-le).
|
|
253
260
|
|
|
254
261
|
### RDF 1.2
|
|
255
262
|
|
|
@@ -295,6 +302,25 @@ standard input or HTTP(S) incrementally. See the
|
|
|
295
302
|
[message-boundaries](https://eyereasoner.github.io/eyemind/examples/deck/message-boundaries-n3)
|
|
296
303
|
and [message-alerts](https://eyereasoner.github.io/eyemind/examples/deck/message-alerts-n3) decks.
|
|
297
304
|
|
|
305
|
+
With an [RDF logic profile](#rdf-logic-profiles), `--stream-messages` treats
|
|
306
|
+
the other inputs as a background graph and writes, for each message, the
|
|
307
|
+
triples it adds to what the background alone concludes. The background is
|
|
308
|
+
closed once. Each shape of message, its properties and whether its values
|
|
309
|
+
are IRIs or literals of a datatype, gets the rule instances that can use one
|
|
310
|
+
of its triples, with background facts unfolded where they fix a property or
|
|
311
|
+
class; later messages of that shape only add their own facts. The result is
|
|
312
|
+
the same as running the whole program over the background and the message,
|
|
313
|
+
and the whole program runs instead when new triples could have any property,
|
|
314
|
+
as `owl:sameAs` between individuals makes, or when a negation could retract
|
|
315
|
+
a background conclusion. `--program` prints the specialized program of each
|
|
316
|
+
new shape, and `--stats` says whether each message used one. Streamed
|
|
317
|
+
messages have no proofs. See the
|
|
318
|
+
[observations](https://eyereasoner.github.io/eyemind/examples/deck/observations-owl2rl) deck.
|
|
319
|
+
|
|
320
|
+
```sh
|
|
321
|
+
eyemind --owl2rl --stream-messages ontology.ttl messages.trig # each message's new triples
|
|
322
|
+
```
|
|
323
|
+
|
|
298
324
|
### SPARQL 1.2 RL
|
|
299
325
|
|
|
300
326
|
A `.srl` file is a [SPARQL 1.2 RL](https://www.w3.org/TR/sparql12-rl/) rule
|
|
@@ -517,7 +543,7 @@ eyemind [OPTION ...] [FILE ...]
|
|
|
517
543
|
| `--json` | With a checking mode, print the report as JSON. |
|
|
518
544
|
| `--goal GOAL` | Ask `GOAL` after forward reasoning; may be repeated. |
|
|
519
545
|
| `--unused` | List the clauses that make no difference to the conclusions. |
|
|
520
|
-
| `--stream-messages` | Read an RDF Message Log and run the rules independently per message; Node reads files, stdin and HTTP(S) incrementally. |
|
|
546
|
+
| `--stream-messages` | Read an RDF Message Log and run the rules independently per message; Node reads files, stdin and HTTP(S) incrementally. With an RDF logic profile, the other inputs are a background closed once and the rules are specialized per message shape. |
|
|
521
547
|
| `--stats` | Print reasoning statistics as JSON to standard error. |
|
|
522
548
|
| `--max-depth N`, `--max-iterations N`, `--max-inferences N` | Bound backward depth (1000000), forward rounds per stratum (1000) and goals started (1000000); a compiled N3, SRL, ODRL or RDF profile program has 1000000, 100000 and 1000000000. |
|
|
523
549
|
| `--to FORMAT` | Write the conclusions as `turtle`, `trig`, `n-triples`, `n-quads`, `n3`, `le` or `eyemind`; by default LE for LE, N3 for N3, Turtle for SRL, ODRL and RDF profiles, eyemind otherwise. |
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "eyemind",
|
|
3
|
-
"version": "0.8.
|
|
3
|
+
"version": "0.8.11",
|
|
4
4
|
"description": "A dependency-free Logic Script (LS) reasoner with forward and backward reasoning, checkable proofs, and RDF 1.2, Notation3 (N3), SPARQL 1.2 RL (SRL) and Logical English (LE) interoperability.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./src/index.js",
|
package/src/cli.js
CHANGED
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
// The eyemind command line.
|
|
2
2
|
import { run, unusedClauses } from './engine.js';
|
|
3
|
-
import { OUTPUT_FORMATS, RDF_PROFILES, defaultFormat, inputKind, loadInputs, rdfMessageFormat, scopeOf, writeConclusions } from './formats.js';
|
|
3
|
+
import { OUTPUT_FORMATS, RDF_PROFILES, defaultFormat, inputKind, loadInputs, loadMessageReasoner, rdfMessageFormat, scopeOf, writeConclusions } from './formats.js';
|
|
4
4
|
import { isRdfMessageLog, replayMessages, RdfMessageReader } from './messages.js';
|
|
5
5
|
import { checkProof, checkReport, publicReport } from './proof.js';
|
|
6
|
+
import { writeRdf } from './rdf.js';
|
|
7
|
+
import { programText } from './specialize.js';
|
|
6
8
|
import { EyemindError } from './terms.js';
|
|
7
9
|
import { VERSION } from './version.js';
|
|
8
10
|
import { srlContextFromProof } from './srl.js';
|
|
@@ -46,6 +48,8 @@ const ALIASES = new Map([['-p', '--proof'], ['-c', '--prove-and-check'], ['-v',
|
|
|
46
48
|
// N3 and SPARQL 1.2 RL programs run longer than eyemind's defaults allow.
|
|
47
49
|
const COMPILED_LIMITS = { maxDepth: 1000000, maxIterations: 100000, maxInferences: 1000000000 };
|
|
48
50
|
|
|
51
|
+
const RDF_FORMATS = ['turtle', 'trig', 'n-triples', 'n-quads'];
|
|
52
|
+
|
|
49
53
|
class UsageError extends Error {}
|
|
50
54
|
|
|
51
55
|
function readSource(path, io) {
|
|
@@ -149,17 +153,37 @@ export function main(argv, io) {
|
|
|
149
153
|
if (!files.length) files.push('-');
|
|
150
154
|
if (files.filter((file) => file === '-').length > 1) throw new UsageError('stdin can only be read once');
|
|
151
155
|
if (streamMessages) {
|
|
156
|
+
const profiles = RDF_PROFILES.filter((p) => rdfLogic[p]);
|
|
152
157
|
if (odrl) throw new UsageError('--odrl cannot be combined with --stream-messages');
|
|
153
|
-
if (
|
|
154
|
-
|
|
155
|
-
|
|
158
|
+
if (proofFile !== null || options.proof || proveAndCheck || unused || (printProgram && !profiles.length)) {
|
|
159
|
+
throw new UsageError('--stream-messages cannot be combined with --proof, --check-proof, --prove-and-check or --unused, ' +
|
|
160
|
+
'nor with --program without an RDF logic profile; replay the whole log to prove its conclusions');
|
|
161
|
+
}
|
|
162
|
+
if (profiles.length && format !== null && !RDF_FORMATS.includes(format)) {
|
|
163
|
+
throw new UsageError(`--stream-messages with ${profiles.map((p) => '--' + p).join(' ')} writes ${RDF_FORMATS.join(', ')}, not ${format}`);
|
|
156
164
|
}
|
|
157
165
|
const args = argv.filter((arg, i) => arg !== '--stream-messages' && !filePositions.has(i));
|
|
158
166
|
let messageNumber = 0;
|
|
167
|
+
// The logic profiles close the other inputs once and reason over each
|
|
168
|
+
// message with rules specialized to its shape (rdf-logic.js).
|
|
169
|
+
let reasoner = null;
|
|
170
|
+
const infer = (inputs, message) => {
|
|
171
|
+
reasoner ??= loadMessageReasoner(inputs.map(([path, text]) => [text, path === '-' ? '<stdin>' : path]), io, { base, ...rdfLogic });
|
|
172
|
+
const result = reasoner.infer(message.quads, { ...COMPILED_LIMITS, ...options });
|
|
173
|
+
messageNumber++;
|
|
174
|
+
if (printProgram) {
|
|
175
|
+
if (result.sources) stdout(`// The rules specialized for message ${message.index} and those shaped like it, without their facts.\n${programText(result.sources)}`);
|
|
176
|
+
else if (!result.specialized && messageNumber === 1) stdout(`// These rules are not specialized: ${reasoner.reason ?? 'a message has a shape they cannot be specialized to'}.\n`);
|
|
177
|
+
return 0;
|
|
178
|
+
}
|
|
179
|
+
stdout(writeRdf(result.quads, { format: format ?? 'turtle', prefixes: { ...reasoner.prefixes, ...message.prefixes }, blankNodePrefix: `m${messageNumber}_` }));
|
|
180
|
+
if (stats) stderr(`${JSON.stringify({ message: message.index, specialized: result.specialized, ...result.stats })}\n`);
|
|
181
|
+
return result.haltCode || 0;
|
|
182
|
+
};
|
|
159
183
|
const request = {
|
|
160
184
|
files, base,
|
|
161
185
|
scope: (name, index = files.indexOf(name)) => scopeOf(files.map((f) => ['', f]), name, index),
|
|
162
|
-
run: (inputs, name, replay) => main([...args, ...inputs.map(([path]) => path), name], {
|
|
186
|
+
run: (inputs, name, replay, message) => profiles.length ? infer(inputs, message) : main([...args, ...inputs.map(([path]) => path), name], {
|
|
163
187
|
...io,
|
|
164
188
|
// Each result is serialized separately; keep its blank labels
|
|
165
189
|
// distinct without retaining nodes from previous messages.
|
|
@@ -180,7 +204,7 @@ export function main(argv, io) {
|
|
|
180
204
|
let code = 0;
|
|
181
205
|
const scope = request.scope(name, index);
|
|
182
206
|
const reader = new RdfMessageReader({ format: rdfMessageFormat(name), base: base ?? io.fileIri?.(name), scope, onMessage: (message) => {
|
|
183
|
-
code = request.run(inputs, name, replayMessages([message], { scope }));
|
|
207
|
+
code = request.run(inputs, name, replayMessages([message], { scope }), message);
|
|
184
208
|
return code === 0;
|
|
185
209
|
} });
|
|
186
210
|
reader.write(text);
|
package/src/formats.js
CHANGED
|
@@ -26,7 +26,7 @@ import { DEFAULT_GRAPH, parseRdf, rdfDocument, rdfFormat, writeRdf } from './rdf
|
|
|
26
26
|
import { resultToN3, compileSources } from './n3.js';
|
|
27
27
|
import { compileSrl, srlAnswers, srlQuads } from './srl.js';
|
|
28
28
|
import { compileOdrl } from './odrl.js';
|
|
29
|
-
import { compileRdfLogic, RDF_PROFILES } from './rdf-logic.js';
|
|
29
|
+
import { compileRdfLogic, messageReasoner, RDF_PROFILES } from './rdf-logic.js';
|
|
30
30
|
import { compileLe, writeLe } from './le.js';
|
|
31
31
|
import { write } from './writer.js';
|
|
32
32
|
import { isRdfMessageLog, parseRdfMessages } from './messages.js';
|
|
@@ -63,7 +63,33 @@ export function loadInputs(inputs, io = null, options = {}) {
|
|
|
63
63
|
}
|
|
64
64
|
}
|
|
65
65
|
|
|
66
|
-
|
|
66
|
+
// The RDF inputs of the logic profiles as one graph.
|
|
67
|
+
function profileGraph(inputs, kinds, rdf, baseOf, switches) {
|
|
68
|
+
if (inputs.some(([, name], k) => kinds[k] !== 'rdf' && name !== '<stdin>')) {
|
|
69
|
+
throw new EyemindError(`${switches} takes RDF inputs; standard input is Turtle`);
|
|
70
|
+
}
|
|
71
|
+
const prefixes = {}, quads = [];
|
|
72
|
+
inputs.forEach(([text, name], k) => {
|
|
73
|
+
const parsed = name === '<stdin>' ? parseRdf(text, { format: 'turtle', base: baseOf(name), scope: scopeOf(inputs, name, k) }) : rdf(text, name, k);
|
|
74
|
+
if (parsed.triples) throw new EyemindError(`${switches} takes RDF graphs, not RDF Message Logs`);
|
|
75
|
+
Object.assign(prefixes, parsed.prefixes);
|
|
76
|
+
quads.push(...parsed.quads);
|
|
77
|
+
});
|
|
78
|
+
return { quads, prefixes };
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// The reasoner the logic profiles run each RDF Message with, given the
|
|
82
|
+
// background inputs as [text, name] pairs (rdf-logic.js).
|
|
83
|
+
export function loadMessageReasoner(inputs, io = null, options = {}) {
|
|
84
|
+
try {
|
|
85
|
+
return load(inputs, io, { ...options, messages: true });
|
|
86
|
+
} catch (error) {
|
|
87
|
+
if (error instanceof EyemindError || !(error instanceof Error) || error instanceof TypeError || error instanceof ReferenceError) throw error;
|
|
88
|
+
throw new EyemindError(error.message);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function load(inputs, io, { base = null, messageInputs = null, srlContext = null, odrl = false, owl2rl = false, qudt = false, skos = false, shacl = false, messages = false }) {
|
|
67
93
|
const options = { owl2rl, qudt, skos, shacl }, profiles = RDF_PROFILES.filter((p) => options[p]);
|
|
68
94
|
const switches = profiles.map((p) => '--' + p).join(' ');
|
|
69
95
|
const kinds = inputs.map(([text, name]) => messageInputs?.has(name) ||
|
|
@@ -82,17 +108,10 @@ function load(inputs, io, { base = null, messageInputs = null, srlContext = null
|
|
|
82
108
|
}
|
|
83
109
|
if (profiles.length && odrl) throw new EyemindError(`--odrl cannot be combined with ${switches}`);
|
|
84
110
|
if (profiles.length) {
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
}
|
|
88
|
-
|
|
89
|
-
inputs.forEach(([text, name], k) => {
|
|
90
|
-
const parsed = name === '<stdin>' ? parseRdf(text, { format: 'turtle', base: baseOf(name), scope: scopeOf(inputs, name, k) }) : rdf(text, name, k);
|
|
91
|
-
if (parsed.triples) throw new EyemindError(`${switches} takes RDF graphs, not RDF Message Logs`);
|
|
92
|
-
Object.assign(prefixes, parsed.prefixes);
|
|
93
|
-
quads.push(...parsed.quads);
|
|
94
|
-
});
|
|
95
|
-
return compileRdfLogic({ quads, prefixes }, { profiles, source: inputs.map(([, n]) => n).join(', '), context: srlContext });
|
|
111
|
+
const graph = profileGraph(inputs, kinds, rdf, baseOf, switches);
|
|
112
|
+
const source = inputs.map(([, n]) => n).join(', ');
|
|
113
|
+
if (messages) return messageReasoner(graph, { profiles, source });
|
|
114
|
+
return compileRdfLogic(graph, { profiles, source, context: srlContext });
|
|
96
115
|
}
|
|
97
116
|
if (odrl) {
|
|
98
117
|
if (inputs.length !== 1) throw new EyemindError('--odrl takes one Turtle snapshot containing policies, requests and SOTW');
|
package/src/le.js
CHANGED
|
@@ -15,6 +15,54 @@ const RESERVED = new Set([...PRIMITIVE_KEYS, ...CONTROL_KEYS, ...RESERVED_KEYS].
|
|
|
15
15
|
for (const name of ['true', 'false', 'fail']) RESERVED.add(name);
|
|
16
16
|
const OPERATORS = { '+': ['add', 1], '-': ['sub', 1], '*': ['mul', 2], '/': ['div', 2] };
|
|
17
17
|
const list = (items) => items.reduceRight((tail, head) => st('.', head, tail), EMPTY);
|
|
18
|
+
const cons = (head, tail) => st('.', head, tail);
|
|
19
|
+
const AGGREGATES = { number: 'le:count', sum: 'le:sum', maximum: 'le:max', minimum: 'le:min' };
|
|
20
|
+
|
|
21
|
+
// Aggregates collect t(...) tuples with findall_sorted, drop repeated tuples
|
|
22
|
+
// with le:distinct and fold the rest with these backward rules. Their names
|
|
23
|
+
// contain ':', which no LE name can, so they never meet a user's relation.
|
|
24
|
+
// Each clause is a function so that every use has its own variables.
|
|
25
|
+
const HELPERS = {
|
|
26
|
+
'le:distinct': [
|
|
27
|
+
() => [st('le:distinct', EMPTY, EMPTY), []],
|
|
28
|
+
() => { const X = new Var('X'); return [st('le:distinct', list([X]), list([X])), []]; },
|
|
29
|
+
() => {
|
|
30
|
+
const X = new Var('X'), Y = new Var('Y'), T = new Var('T'), R = new Var('R');
|
|
31
|
+
return [st('le:distinct', cons(X, cons(Y, T)), R), [st('identical', X, Y), st('le:distinct', cons(Y, T), R)]];
|
|
32
|
+
},
|
|
33
|
+
() => {
|
|
34
|
+
const X = new Var('X'), Y = new Var('Y'), T = new Var('T'), R = new Var('R');
|
|
35
|
+
return [st('le:distinct', cons(X, cons(Y, T)), cons(X, R)), [st('not_identical', X, Y), st('le:distinct', cons(Y, T), R)]];
|
|
36
|
+
},
|
|
37
|
+
],
|
|
38
|
+
'le:count': [
|
|
39
|
+
() => [st('le:count', EMPTY, 0n), []],
|
|
40
|
+
() => {
|
|
41
|
+
const H = new Var('H'), T = new Var('T'), N = new Var('N'), M = new Var('M');
|
|
42
|
+
return [st('le:count', cons(H, T), N), [st('le:count', T, M), st('is', N, st('add', M, 1n))]];
|
|
43
|
+
},
|
|
44
|
+
],
|
|
45
|
+
'le:sum': [
|
|
46
|
+
() => [st('le:sum', EMPTY, 0n), []],
|
|
47
|
+
() => {
|
|
48
|
+
const H = new Var('H'), T = new Var('T'), S = new Var('S'), S0 = new Var('S0'), V = new Var('V');
|
|
49
|
+
return [st('le:sum', cons(H, T), S), [st('arg', 1n, H, V), st('le:sum', T, S0), st('is', S, st('add', S0, V))]];
|
|
50
|
+
},
|
|
51
|
+
],
|
|
52
|
+
'le:max': extremum('le:max', 'ge', 'lt'),
|
|
53
|
+
'le:min': extremum('le:min', 'le', 'gt'),
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
// The value of a list's best tuple; an empty list has none.
|
|
57
|
+
function extremum(name, keep, pass) {
|
|
58
|
+
const one = () => { const H = new Var('H'), V = new Var('V'); return [st(name, list([H]), V), [st('arg', 1n, H, V)]]; };
|
|
59
|
+
const more = (test, chosen) => () => {
|
|
60
|
+
const H = new Var('H'), I = new Var('I'), T = new Var('T'), M = new Var('M'), M0 = new Var('M0'), V = new Var('V');
|
|
61
|
+
return [st(name, cons(H, cons(I, T)), M),
|
|
62
|
+
[st(name, cons(I, T), M0), st('arg', 1n, H, V), st(test, V, M0), st('unify', M, chosen(V, M0))]];
|
|
63
|
+
};
|
|
64
|
+
return [one, more(keep, (V) => V), more(pass, (V, M0) => M0)];
|
|
65
|
+
}
|
|
18
66
|
|
|
19
67
|
function listItems(term) {
|
|
20
68
|
const items = [];
|
|
@@ -31,6 +79,9 @@ class Parser {
|
|
|
31
79
|
this.tokens = [];
|
|
32
80
|
this.at = 0;
|
|
33
81
|
this.scope = new Map();
|
|
82
|
+
this.closed = new Set();
|
|
83
|
+
this.helpers = new Set();
|
|
84
|
+
this.aggregates = 0;
|
|
34
85
|
this.depth = 0;
|
|
35
86
|
let line = 1, pos = 0;
|
|
36
87
|
while (pos < text.length) {
|
|
@@ -130,6 +181,7 @@ class Parser {
|
|
|
130
181
|
return st(token.value, ...args);
|
|
131
182
|
}
|
|
132
183
|
if (token.kind === 'word' && VARIABLE.test(token.value)) {
|
|
184
|
+
if (this.closed.has(token.value)) this.error(`variable ${token.value} belongs to the aggregate that declares it and cannot be used outside it`, token.line);
|
|
133
185
|
if (!this.scope.has(token.value)) this.error(`variable ${token.value} is undeclared; introduce it with "For every", "Find every" or "there exists", or quote it as a name`, token.line);
|
|
134
186
|
return this.scope.get(token.value);
|
|
135
187
|
}
|
|
@@ -180,8 +232,10 @@ class Parser {
|
|
|
180
232
|
}
|
|
181
233
|
if (body) {
|
|
182
234
|
if (this.take('the')) {
|
|
183
|
-
this.need('value'); this.need('of');
|
|
184
235
|
if (!(subject instanceof Var) && !['bigint', 'number'].includes(typeof subject)) this.error('a calculation needs a variable or number on its left');
|
|
236
|
+
const kind = Object.keys(AGGREGATES).find((word) => this.is(word));
|
|
237
|
+
if (kind) return this.aggregate(subject, kind);
|
|
238
|
+
this.need('value'); this.need('of');
|
|
185
239
|
return st('is', subject, this.expression());
|
|
186
240
|
}
|
|
187
241
|
let comparison;
|
|
@@ -205,15 +259,78 @@ class Parser {
|
|
|
205
259
|
this.error('expected "is a class", "is a relation of", or a relation call such as parent(Alice, Bob)');
|
|
206
260
|
}
|
|
207
261
|
|
|
262
|
+
// An aggregate statement stands for several goals, so goals are flattened.
|
|
208
263
|
goals(body) {
|
|
209
264
|
const goals = [this.atomic(body)];
|
|
210
265
|
while (this.take('and')) goals.push(this.atomic(body));
|
|
211
|
-
return goals;
|
|
266
|
+
return goals.flat();
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
// Premises joined by "or", with "and" binding more tightly; each
|
|
270
|
+
// alternative becomes a clause of its own.
|
|
271
|
+
alternatives() {
|
|
272
|
+
const result = [this.goals(true)];
|
|
273
|
+
while (this.take('or')) result.push(this.goals(true));
|
|
274
|
+
return result;
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
// "N is the number of X and Y such that ..." counts the distinct
|
|
278
|
+
// combinations of the declared variables; sum, maximum and minimum fold the
|
|
279
|
+
// value V over them. The condition is one statement or a conjunction in
|
|
280
|
+
// parentheses, and its declared variables stay inside it.
|
|
281
|
+
aggregate(result, kind) {
|
|
282
|
+
this.at++; this.need('of');
|
|
283
|
+
let value = null;
|
|
284
|
+
if (kind !== 'number') {
|
|
285
|
+
if (this.token.kind !== 'word' || !VARIABLE.test(this.token.value)) {
|
|
286
|
+
this.error(`"the ${kind} of" needs a variable, as in "the ${kind} of V for every X and V such that ..."`);
|
|
287
|
+
}
|
|
288
|
+
value = this.token.value;
|
|
289
|
+
this.at++; this.need('for'); this.need('every');
|
|
290
|
+
}
|
|
291
|
+
const locals = this.declarations();
|
|
292
|
+
if (value !== null && !locals.some((v) => v.name === value)) this.error(`${value} must be declared after "for every" in its aggregate`);
|
|
293
|
+
this.need('such'); this.need('that');
|
|
294
|
+
let condition;
|
|
295
|
+
if (this.take('(')) { condition = this.goals(true); this.need(')'); }
|
|
296
|
+
else condition = [this.atomic(true)].flat();
|
|
297
|
+
if (condition.some((goal) => goal instanceof Struct && goal.name === 'findall_sorted')) {
|
|
298
|
+
this.error('an aggregate cannot contain another aggregate; derive the inner one in a rule and use its conclusion');
|
|
299
|
+
}
|
|
300
|
+
for (const v of locals) this.closed.add(v.name);
|
|
301
|
+
const ordered = value === null ? locals : [locals.find((v) => v.name === value), ...locals.filter((v) => v.name !== value)];
|
|
302
|
+
const n = ++this.aggregates, all = new Var(`Agg${n}`), distinct = new Var(`Agg${n}d`), helper = AGGREGATES[kind];
|
|
303
|
+
this.helpers.add('le:distinct');
|
|
304
|
+
this.helpers.add(helper);
|
|
305
|
+
return [st('findall_sorted', st('t', ...ordered), conjunction(condition), all),
|
|
306
|
+
st('le:distinct', all, distinct), st(helper, distinct, result)];
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
// Calculations, comparisons and absence tests need their inputs from
|
|
310
|
+
// earlier premises; an aggregate needs those of its condition other than
|
|
311
|
+
// its own variables, and checks its condition in the same way.
|
|
312
|
+
checkOrder(goals, bound, line) {
|
|
313
|
+
for (const goal of goals) {
|
|
314
|
+
if (goal instanceof Struct && goal.name === 'findall_sorted') {
|
|
315
|
+
const locals = variablesIn([goal.args[0]]), inner = new Set(bound);
|
|
316
|
+
for (const name of variablesIn([goal.args[1]])) {
|
|
317
|
+
if (!locals.has(name) && !bound.has(name)) this.error(`${name} must be supplied by an earlier premise before the aggregate that uses it`, line);
|
|
318
|
+
}
|
|
319
|
+
this.checkOrder(flattenConjunction(goal.args[1]), inner, line);
|
|
320
|
+
bound.add(goal.args[2].name);
|
|
321
|
+
continue;
|
|
322
|
+
}
|
|
323
|
+
const required = goal instanceof Struct && RESERVED.has(goal.name) ? variablesIn(goal.name === 'is' ? [goal.args[1]] : [goal]) : new Set();
|
|
324
|
+
for (const name of required) if (!bound.has(name)) this.error(`${name} must be supplied by an earlier positive premise or calculation`, line);
|
|
325
|
+
if (!(goal instanceof Struct && goal.name === 'not')) for (const name of variablesIn([goal])) bound.add(name);
|
|
326
|
+
}
|
|
327
|
+
return bound;
|
|
212
328
|
}
|
|
213
329
|
|
|
214
330
|
sentence() {
|
|
215
331
|
const line = this.token.line;
|
|
216
332
|
this.scope = new Map();
|
|
333
|
+
this.closed = new Set();
|
|
217
334
|
if (this.is('use') && this.tokens[this.at + 1]?.kind === 'word' && this.tokens[this.at + 1].value.toLowerCase() === 'odrl') {
|
|
218
335
|
this.at++;
|
|
219
336
|
this.need('odrl');
|
|
@@ -229,45 +346,49 @@ class Parser {
|
|
|
229
346
|
return { kind: 'odrl', namespace, evaluate, line };
|
|
230
347
|
}
|
|
231
348
|
if (this.take('every')) {
|
|
232
|
-
const
|
|
233
|
-
|
|
349
|
+
const x = new Var('X'), froms = [this.name()], heads = [];
|
|
350
|
+
while (this.take('or')) froms.push(this.name());
|
|
351
|
+
this.need('is');
|
|
234
352
|
do { this.take('a') || this.take('an'); heads.push(st(this.name(), x)); } while (this.take('and'));
|
|
235
353
|
this.need('.');
|
|
236
|
-
return { kind: 'forward', heads,
|
|
354
|
+
return { kind: 'forward', heads, bodies: froms.map((from) => [st(from, x)]), line };
|
|
237
355
|
}
|
|
238
356
|
let quantified = false;
|
|
239
357
|
if (this.take('for')) { this.need('every'); this.declarations(); this.need(','); quantified = true; }
|
|
240
|
-
let kind = 'fact',
|
|
358
|
+
let kind = 'fact', bodies = [[]], heads = [], witnesses = [];
|
|
241
359
|
if (this.take('find')) {
|
|
242
360
|
if (quantified) this.error('a question introduces its variables with "Find every"');
|
|
243
361
|
if (this.take('every')) { this.declarations(); this.need('such'); this.need('that'); }
|
|
244
362
|
else this.need('whether');
|
|
245
|
-
kind = 'query';
|
|
363
|
+
kind = 'query'; bodies = [this.goals(true)];
|
|
364
|
+
if (this.is('or')) this.error('a question has no "or"; ask one question per alternative, or derive a relation with an "or" rule and ask for it');
|
|
365
|
+
if (bodies[0].some((goal) => goal instanceof Struct && goal.name === 'findall_sorted')) {
|
|
366
|
+
this.error('a question cannot aggregate; derive the aggregate in a rule and ask for its conclusion');
|
|
367
|
+
}
|
|
246
368
|
} else if (this.take('contradiction')) {
|
|
247
|
-
kind = 'contradiction';
|
|
369
|
+
kind = 'contradiction'; bodies = [['true']];
|
|
248
370
|
} else if (this.take('it')) {
|
|
249
371
|
this.need('is'); this.need('impossible'); this.need('that');
|
|
250
|
-
kind = 'contradiction';
|
|
372
|
+
kind = 'contradiction'; bodies = this.alternatives();
|
|
251
373
|
} else {
|
|
252
|
-
if (this.take('if')) { kind = 'forward';
|
|
374
|
+
if (this.take('if')) { kind = 'forward'; bodies = this.alternatives(); this.need('then'); }
|
|
253
375
|
if (this.take('there')) {
|
|
254
376
|
this.need('exists'); witnesses = this.declarations(); this.need('such'); this.need('that');
|
|
255
|
-
if (kind === 'fact') { kind = 'forward';
|
|
377
|
+
if (kind === 'fact') { kind = 'forward'; bodies = [['true']]; }
|
|
256
378
|
}
|
|
257
379
|
heads = this.goals(false);
|
|
258
380
|
}
|
|
259
381
|
this.need('.');
|
|
260
|
-
const headVars = variablesIn(heads),
|
|
261
|
-
for (const goal of body) {
|
|
262
|
-
const required = goal instanceof Struct && RESERVED.has(goal.name) ? variablesIn(goal.name === 'is' ? [goal.args[1]] : [goal]) : new Set();
|
|
263
|
-
for (const name of required) if (!bound.has(name)) this.error(`${name} must be supplied by an earlier positive premise or calculation`, line);
|
|
264
|
-
if (!(goal instanceof Struct && goal.name === 'not')) for (const name of variablesIn([goal])) bound.add(name);
|
|
265
|
-
}
|
|
382
|
+
const headVars = variablesIn(heads), witnessNames = new Set(witnesses.map((v) => v.name));
|
|
266
383
|
if (witnesses.some((v) => !headVars.has(v.name))) this.error('every existential variable must occur in its conclusion', line);
|
|
267
|
-
|
|
268
|
-
this.
|
|
384
|
+
for (const body of bodies) {
|
|
385
|
+
const bound = this.checkOrder(body, new Set(), line);
|
|
386
|
+
if (kind === 'forward' && [...headVars].some((name) => !bound.has(name) && !witnessNames.has(name))) {
|
|
387
|
+
this.error(bodies.length > 1 ? 'a conclusion variable must occur in every alternative of an "or" premise, or be introduced with "there exists"'
|
|
388
|
+
: 'a conclusion variable must occur in a premise or be introduced with "there exists"', line);
|
|
389
|
+
}
|
|
269
390
|
}
|
|
270
|
-
return { kind, heads,
|
|
391
|
+
return { kind, heads, bodies, line };
|
|
271
392
|
}
|
|
272
393
|
}
|
|
273
394
|
|
|
@@ -291,34 +412,47 @@ function javascript(term) {
|
|
|
291
412
|
}
|
|
292
413
|
|
|
293
414
|
export function compileLe(inputs) {
|
|
294
|
-
const clauses = [], statements = [], sources = [];
|
|
415
|
+
const clauses = [], statements = [], sources = [], helpers = new Set();
|
|
295
416
|
let profile = null;
|
|
296
417
|
for (const [text, file] of inputs) {
|
|
297
418
|
const parser = new Parser(String(text), file);
|
|
298
419
|
while (parser.token.kind !== 'end') {
|
|
299
|
-
const sentence = parser.sentence(), { kind, heads,
|
|
420
|
+
const sentence = parser.sentence(), { kind, heads, bodies, line } = sentence;
|
|
300
421
|
if (kind === 'odrl') {
|
|
301
422
|
if (profile || statements.length || inputs.length !== 1) parser.error('an ODRL directive must be the first sentence of one LE file', line);
|
|
302
423
|
profile = { namespace: sentence.namespace, evaluate: sentence.evaluate };
|
|
303
424
|
continue;
|
|
304
425
|
}
|
|
305
|
-
statements.push({ ...sentence, file });
|
|
306
426
|
clauses.push(`// ${String(file).replace(/[\r\n\u2028\u2029]/g, ' ')}: line ${line}`);
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
427
|
+
for (const body of bodies) {
|
|
428
|
+
statements.push({ kind, heads, body, line, file });
|
|
429
|
+
if (kind === 'fact') {
|
|
430
|
+
for (const head of heads) {
|
|
431
|
+
clauses.push(`fact(${javascript(head)})`);
|
|
432
|
+
sources.push(new Source('fact', head, [], line, file));
|
|
433
|
+
}
|
|
434
|
+
} else if (kind === 'forward') {
|
|
435
|
+
clauses.push(`implies(${javascript(conjunction(body))}, ${javascript(conjunction(heads))})`);
|
|
436
|
+
sources.push(new Source('forward', conjunction(heads), body, line, file));
|
|
437
|
+
} else {
|
|
438
|
+
clauses.push(`${kind}(${body.map(javascript).join(', ')})`);
|
|
439
|
+
sources.push(new Source(kind, kind === 'query' ? 'true' : 'false', body, line, file));
|
|
311
440
|
}
|
|
312
|
-
} else if (kind === 'forward') {
|
|
313
|
-
clauses.push(`implies(${javascript(conjunction(body))}, ${javascript(conjunction(heads))})`);
|
|
314
|
-
sources.push(new Source('forward', conjunction(heads), body, line, file));
|
|
315
|
-
} else {
|
|
316
|
-
clauses.push(`${kind}(${body.map(javascript).join(', ')})`);
|
|
317
|
-
sources.push(new Source(kind, kind === 'query' ? 'true' : 'false', body, line, file));
|
|
318
441
|
}
|
|
319
442
|
}
|
|
443
|
+
for (const name of parser.helpers) helpers.add(name);
|
|
320
444
|
}
|
|
321
445
|
if (profile) return compileOdrlLe(statements, profile, inputs[0][1]);
|
|
446
|
+
// The helpers follow every stated clause, so a witness's rule number is
|
|
447
|
+
// the same whether or not the program aggregates.
|
|
448
|
+
if (helpers.size) clauses.push('// Aggregation helpers.');
|
|
449
|
+
for (const name of Object.keys(HELPERS).filter((key) => helpers.has(key))) {
|
|
450
|
+
for (const make of HELPERS[name]) {
|
|
451
|
+
const [head, body] = make();
|
|
452
|
+
clauses.push(`implied_by(${javascript(head)}, ${body.length ? javascript(conjunction(body)) : "'true'"})`);
|
|
453
|
+
sources.push(new Source('backward', head, body.length ? body : ['true'], null, null));
|
|
454
|
+
}
|
|
455
|
+
}
|
|
322
456
|
return { kind: 'le', text: '// Compiled from Logical English to Logic Script.\n\n' + clauses.join('\n') + '\n',
|
|
323
457
|
program: new Program(sources), prefixes: {}, compiled: { statements } };
|
|
324
458
|
}
|
package/src/node-messages.js
CHANGED
|
@@ -66,7 +66,7 @@ export async function streamMessages(request, io) {
|
|
|
66
66
|
let code = 0;
|
|
67
67
|
const reader = new RdfMessageReader({ format: source.format ?? rdfMessageFormat(name), base: request.base ?? source.base, scope,
|
|
68
68
|
onMessage: (message) => {
|
|
69
|
-
code = request.run(inputs, name, replayMessages([message], { scope }));
|
|
69
|
+
code = request.run(inputs, name, replayMessages([message], { scope }), message);
|
|
70
70
|
return code === 0;
|
|
71
71
|
} });
|
|
72
72
|
for await (const text of source.body) {
|
package/src/program.js
CHANGED
|
@@ -200,6 +200,37 @@ export class Program {
|
|
|
200
200
|
this.layered = this.strata.layered === true;
|
|
201
201
|
}
|
|
202
202
|
|
|
203
|
+
// This program with more ground facts after its clauses, sharing its
|
|
204
|
+
// rules and strata: a fact changes no stratum. Programs specialized for
|
|
205
|
+
// RDF Messages (specialize.js) get each message's facts this way.
|
|
206
|
+
withFacts(facts) {
|
|
207
|
+
const program = Object.assign(Object.create(Program.prototype), this);
|
|
208
|
+
program.sources = [...this.sources];
|
|
209
|
+
program.clauses = [...this.clauses];
|
|
210
|
+
program.byId = new Map(this.byId);
|
|
211
|
+
program.groups = new Map(this.groups);
|
|
212
|
+
program.indexes = new Map(this.indexes);
|
|
213
|
+
program.groundFactKeys = new Set(this.groundFactKeys);
|
|
214
|
+
for (const fact of facts) {
|
|
215
|
+
if (!isCallable(fact) || !isGround(fact) || fact === EMPTY || isTerm(fact, '.', 2) || RESERVED_KEYS.has(key(fact)) ||
|
|
216
|
+
PRIMITIVE_KEYS.has(key(fact)) || CONTROL_KEYS.has(key(fact))) {
|
|
217
|
+
throw new EyemindError(`${write(fact)} is not a ground fact`);
|
|
218
|
+
}
|
|
219
|
+
const source = new Source('fact', fact, []);
|
|
220
|
+
const clause = new Clause(++program.maxClauseId, fact, null, [], false, null);
|
|
221
|
+
clause.originalHead = fact;
|
|
222
|
+
clause.plainHeads = [fact];
|
|
223
|
+
program.sources.push(source);
|
|
224
|
+
program.clauses.push(clause);
|
|
225
|
+
program.byId.set(clause.id, clause);
|
|
226
|
+
const factKey = key(fact);
|
|
227
|
+
program.groups.set(factKey, [...(program.groups.get(factKey) ?? []), clause]);
|
|
228
|
+
program.indexes.delete(factKey);
|
|
229
|
+
program.groundFactKeys.add(identity(fact));
|
|
230
|
+
}
|
|
231
|
+
return program;
|
|
232
|
+
}
|
|
233
|
+
|
|
203
234
|
// Restricted rules in the order they run: one whose heads can satisfy
|
|
204
235
|
// another's, its witnesses free, before that one, and otherwise, as on a
|
|
205
236
|
// cycle of such rules, in clause order (SPEC Section 8.2).
|
package/src/rdf-logic.js
CHANGED
|
@@ -10,11 +10,14 @@ import { compileShacl } from './shacl.js';
|
|
|
10
10
|
import { NODE_FUNCTIONS } from './shacl-expr.js';
|
|
11
11
|
import { executionContext } from './srl.js';
|
|
12
12
|
import { rdfValueRules } from './rdf-values.js';
|
|
13
|
+
import { run } from './engine.js';
|
|
14
|
+
import { Specializer } from './specialize.js';
|
|
15
|
+
import { Struct, identity } from './terms.js';
|
|
13
16
|
|
|
14
17
|
export const ENTAILMENT = 'https://eyereasoner.github.io/eyemind/entailment#';
|
|
15
18
|
export const RDF_PROFILES = ['owl2rl', 'qudt', 'skos', 'shacl'];
|
|
16
19
|
|
|
17
|
-
export function compileRdfLogic({ quads, prefixes, shapes = quads }, { profiles, source = '<input>', disallows, evaluate, context }) {
|
|
20
|
+
export function compileRdfLogic({ quads, prefixes, shapes = quads }, { profiles, source = '<input>', disallows, evaluate, context, stream = false }) {
|
|
18
21
|
quads = [...new Map(quads.map((q) => [q.map((t) => write(t)).join(' '), q])).values()];
|
|
19
22
|
const selected = new Set(profiles), needs = new Set();
|
|
20
23
|
// SHACL node expressions may call SPARQL functions beyond the value rules.
|
|
@@ -32,13 +35,52 @@ export function compileRdfLogic({ quads, prefixes, shapes = quads }, { profiles,
|
|
|
32
35
|
(selected.has('owl2rl') ? owl2rlRules : '') +
|
|
33
36
|
(selected.has('skos') ? skosRules : '') +
|
|
34
37
|
(selected.has('qudt') ? qudtRules : '') +
|
|
35
|
-
shacl + (evaluate ? "query(sh_evaluation(R));\n" :
|
|
38
|
+
shacl + (evaluate ? "query(sh_evaluation(R));\n" : REPORTS + (stream ? '' : RESULT));
|
|
36
39
|
return { kind: profiles[0], text, program: loadText(text, source),
|
|
37
40
|
prefixes: { ...prefixes, ent: ENTAILMENT, ...(selected.has('skos') ? { skos: 'http://www.w3.org/2004/02/skos/core#' } : {}),
|
|
38
41
|
...(selected.has('qudt') ? { qconv: 'https://eyereasoner.github.io/eyemind/qudt#', qudt: 'http://qudt.org/schema/qudt/', unit: 'http://qudt.org/vocab/unit/' } : {}),
|
|
39
42
|
...(selected.has('shacl') ? { sh: 'http://www.w3.org/ns/shacl#' } : {}) }, compiled: null };
|
|
40
43
|
}
|
|
41
44
|
|
|
45
|
+
// Reasoning over messages one at a time, each with the same background
|
|
46
|
+
// graph: infer(quads) gives the triples a message adds to what the background
|
|
47
|
+
// alone concludes. The background is closed once and the rules are
|
|
48
|
+
// specialized to the kinds of triples a message has (specialize.js); a
|
|
49
|
+
// program that cannot be specialized runs whole for every message instead.
|
|
50
|
+
export function messageReasoner({ quads, prefixes }, { profiles, source = '<input>' }) {
|
|
51
|
+
const options = { profiles, source };
|
|
52
|
+
const background = compileRdfLogic({ quads, prefixes }, { ...options, stream: true });
|
|
53
|
+
const specializer = new Specializer(background.program, { quads: ['rdf/4', 'ent_base/4'] });
|
|
54
|
+
let alone = null;
|
|
55
|
+
const answers = (program, limits) => run(program, limits).conclusions.filter((t) => t instanceof Struct && t.name === 'result_rdf');
|
|
56
|
+
return {
|
|
57
|
+
prefixes: background.prefixes,
|
|
58
|
+
reason: specializer.reason,
|
|
59
|
+
specializer,
|
|
60
|
+
// limits are run()'s bounds. The result has the added quads, whether
|
|
61
|
+
// the rules were specialized, and the specialized program's sources the
|
|
62
|
+
// first time a message has its shape.
|
|
63
|
+
infer(message, limits = {}) {
|
|
64
|
+
const facts = message.flatMap((q) => [new Struct('rdf', q), new Struct('ent_base', q)]);
|
|
65
|
+
const special = specializer.specialize(facts);
|
|
66
|
+
if (special !== null) {
|
|
67
|
+
const result = run(special.program, limits);
|
|
68
|
+
const added = result.derived.map((node) => node.goal).filter((t) => !special.old.has(identity(t)) &&
|
|
69
|
+
(t.name === 'ent_report' || (t.name === 'rdf' && RESOURCES.has(t.args[0].name) && t.args[1].name === 'iri')));
|
|
70
|
+
return { quads: added.map((t) => t.args), specialized: true, stats: result.stats, haltCode: result.haltCode,
|
|
71
|
+
sources: special.fresh ? special.sources : null };
|
|
72
|
+
}
|
|
73
|
+
alone ??= new Set(answers(compileRdfLogic({ quads, prefixes }, options).program, limits).map(identity));
|
|
74
|
+
const result = run(compileRdfLogic({ quads: [...quads, ...message], prefixes, shapes: quads }, options).program, limits);
|
|
75
|
+
const added = result.conclusions.filter((t) => t instanceof Struct && t.name === 'result_rdf' && !alone.has(identity(t)));
|
|
76
|
+
return { quads: added.map((t) => t.args), specialized: false, stats: result.stats, haltCode: result.haltCode, sources: null };
|
|
77
|
+
},
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// The subjects ent_resource/1 accepts.
|
|
82
|
+
const RESOURCES = new Set(['iri', 'bnode', 'skolem', 'triple']);
|
|
83
|
+
|
|
42
84
|
const COMMON = String.raw`
|
|
43
85
|
implied_by(ent_resource(iri(A)), is_atom(A));
|
|
44
86
|
implied_by(ent_resource(bnode(A, B)), [is_atom(A), is_atom(B)]);
|
|
@@ -52,7 +94,7 @@ fact(ent_member(X, [X, ..._]));
|
|
|
52
94
|
implied_by(ent_member(X, [_, ...T]), ent_member(X, T));
|
|
53
95
|
`;
|
|
54
96
|
|
|
55
|
-
const
|
|
97
|
+
const REPORTS = String.raw`
|
|
56
98
|
// A report cannot create more ontology consequences or affect a constraint.
|
|
57
99
|
implies(ent_conflict(R, X, P, Y, G), [
|
|
58
100
|
ent_report(B, iri('http://www.w3.org/1999/02/22-rdf-syntax-ns#type'), iri('https://eyereasoner.github.io/eyemind/entailment#Conflict'), G),
|
|
@@ -61,7 +103,9 @@ implies(ent_conflict(R, X, P, Y, G), [
|
|
|
61
103
|
ent_report(B, iri('https://eyereasoner.github.io/eyemind/entailment#left'), P, G),
|
|
62
104
|
ent_report(B, iri('https://eyereasoner.github.io/eyemind/entailment#right'), Y, G)
|
|
63
105
|
]);
|
|
64
|
-
|
|
106
|
+
`;
|
|
107
|
+
|
|
108
|
+
const RESULT = String.raw`implies([rdf(S, iri(P), O, G), ent_resource(S), not(ent_base(S, iri(P), O, G))], result_rdf(S, iri(P), O, G));
|
|
65
109
|
implies(ent_report(S, P, O, G), result_rdf(S, P, O, G));
|
|
66
110
|
query(result_rdf(S, P, O, G));
|
|
67
111
|
`;
|
|
@@ -0,0 +1,533 @@
|
|
|
1
|
+
// Specializing a program for facts that arrive again and again, such as RDF
|
|
2
|
+
// Messages: the program's own facts are closed once, and each shape of
|
|
3
|
+
// arriving facts gets only the rule instances that can use one of them.
|
|
4
|
+
//
|
|
5
|
+
// The closure of the program's own facts are the old facts; facts not among
|
|
6
|
+
// them are new. A rule instance whose premises are all old concludes an old
|
|
7
|
+
// fact, so for each forward rule every choice of which data premises are
|
|
8
|
+
// new, at least one, is a variant. An old premise is unfolded into the old
|
|
9
|
+
// facts it matches when they are few and bind a property or class that makes
|
|
10
|
+
// another premise or a conclusion specific; otherwise it is kept, bound to
|
|
11
|
+
// what all those facts share, and reads old_NAME, a copy of the old facts it
|
|
12
|
+
// needs. A new premise reads NAME, the arriving and the derived new facts,
|
|
13
|
+
// and is specialized to each pattern new facts can have: the arriving facts
|
|
14
|
+
// with their values made variables, and the conclusions of the variants,
|
|
15
|
+
// generalized per relation, property and class until no variant adds one. A
|
|
16
|
+
// conclusion that is one of its premises or an old fact is never new and is
|
|
17
|
+
// dropped. The variants, the backward clauses and the old facts they read
|
|
18
|
+
// form an ordinary program, cached per shape of arriving facts, and the
|
|
19
|
+
// arriving facts complete it.
|
|
20
|
+
//
|
|
21
|
+
// Negation and collection are not monotone: more facts can retract an old
|
|
22
|
+
// conclusion. A program that negates or collects what can be new, or that
|
|
23
|
+
// has restricted rules, rule templates or inspection, is not specialized.
|
|
24
|
+
import { CONTROL_KEYS, Program, Source } from './program.js';
|
|
25
|
+
import { run } from './engine.js';
|
|
26
|
+
import { Env, Struct, Var, conjunction, copyResolved, deref, freshTerm, flattenConjunction, identical, identity, isGround, isTerm, key, listFromItems, unify, variables } from './terms.js';
|
|
27
|
+
import { Lettering, write } from './writer.js';
|
|
28
|
+
|
|
29
|
+
const RDF_TYPE = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#type';
|
|
30
|
+
const NEGATING = new Set(['not/1', 'findall/3', 'findall_sorted/3']);
|
|
31
|
+
// Unfold an old premise into at most this many facts.
|
|
32
|
+
const UNFOLD = 256;
|
|
33
|
+
// Generalize, or guard a conclusion against, at most this many old facts.
|
|
34
|
+
const MANY = 4096;
|
|
35
|
+
// How deep to look into backward clauses for a goal that cannot hold.
|
|
36
|
+
const DEPTH = 4;
|
|
37
|
+
// Give up on specializing a rule that unfolds into more instances than this,
|
|
38
|
+
// or on a shape of messages that takes more search steps than STEPS.
|
|
39
|
+
const LEAVES = 100000;
|
|
40
|
+
const STEPS = 60000;
|
|
41
|
+
|
|
42
|
+
class Unsupported extends Error {}
|
|
43
|
+
|
|
44
|
+
let fresh = 0;
|
|
45
|
+
const variable = () => new Var(`G#${++fresh}`);
|
|
46
|
+
const renamed = (term) => freshTerm(term, `p${++fresh}`);
|
|
47
|
+
const isType = (term) => term instanceof Struct && term.name === 'iri' && term.args[0] === RDF_TYPE;
|
|
48
|
+
// Type tests a pattern can decide once its argument is bound.
|
|
49
|
+
const TYPE_TESTS = new Map([
|
|
50
|
+
['is_atom/1', (t) => typeof t === 'string'], ['is_int/1', (t) => typeof t === 'bigint'],
|
|
51
|
+
['is_float/1', (t) => typeof t === 'number'], ['is_number/1', (t) => typeof t === 'bigint' || typeof t === 'number' || t instanceof Struct],
|
|
52
|
+
]);
|
|
53
|
+
const old = (goal) => new Struct(`old_${goal.name}`, goal.args);
|
|
54
|
+
|
|
55
|
+
// The most specific term every one of these terms is an instance of: where
|
|
56
|
+
// two differ, a variable, the same one for the same pair of subterms.
|
|
57
|
+
export function generalize(terms) {
|
|
58
|
+
let general = terms[0];
|
|
59
|
+
for (const term of terms.slice(1)) {
|
|
60
|
+
const pairs = new Map();
|
|
61
|
+
const walk = (a, b) => {
|
|
62
|
+
if (a instanceof Struct && b instanceof Struct && a.name === b.name && a.args.length === b.args.length) {
|
|
63
|
+
return new Struct(a.name, a.args.map((arg, i) => walk(arg, b.args[i])));
|
|
64
|
+
}
|
|
65
|
+
if (!(a instanceof Var) && !(a instanceof Struct) && typeof a === typeof b && a === b) return a;
|
|
66
|
+
const pair = `${identity(a)}\u0001${identity(b)}`;
|
|
67
|
+
let found = pairs.get(pair);
|
|
68
|
+
if (found === undefined) pairs.set(pair, found = variable());
|
|
69
|
+
return found;
|
|
70
|
+
};
|
|
71
|
+
general = walk(general, term);
|
|
72
|
+
}
|
|
73
|
+
return general;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
// Whether term is an instance of pattern.
|
|
77
|
+
function instance(pattern, term) {
|
|
78
|
+
const env = new Env();
|
|
79
|
+
const frozen = new Map();
|
|
80
|
+
for (const [name] of variables(term)) frozen.set(name, `\u0000${name}`);
|
|
81
|
+
const freeze = (t) => t instanceof Var ? frozen.get(t.name) : t instanceof Struct ? new Struct(t.name, t.args.map(freeze)) : t;
|
|
82
|
+
return unify(renamed(pattern), freeze(term), env);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
// Whether two terms differ in a constant or functor near their roots, so
|
|
86
|
+
// they cannot unify; false is no promise that they do.
|
|
87
|
+
function clashes(a, b, env, depth = 2) {
|
|
88
|
+
a = deref(a, env);
|
|
89
|
+
if (a instanceof Var || b instanceof Var) return false;
|
|
90
|
+
if (!(a instanceof Struct) || !(b instanceof Struct)) return a !== b || typeof a !== typeof b;
|
|
91
|
+
if (a.name !== b.name || a.args.length !== b.args.length) return true;
|
|
92
|
+
return depth > 1 && a.args.some((arg, i) => clashes(arg, b.args[i], env, depth - 1));
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// The identity of a pattern with its variables named in order.
|
|
96
|
+
function canonical(pattern) {
|
|
97
|
+
const names = new Map();
|
|
98
|
+
const walk = (t) => {
|
|
99
|
+
if (t instanceof Var) {
|
|
100
|
+
if (!names.has(t.name)) names.set(t.name, new Var(`V${names.size}`));
|
|
101
|
+
return names.get(t.name);
|
|
102
|
+
}
|
|
103
|
+
return t instanceof Struct ? new Struct(t.name, t.args.map(walk)) : t;
|
|
104
|
+
};
|
|
105
|
+
return identity(walk(pattern));
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
// A term with its atoms and numbers made variables: the shape of a value.
|
|
109
|
+
// A literal keeps its datatype.
|
|
110
|
+
const shape = (term) => term instanceof Var ? term : !(term instanceof Struct) ? variable()
|
|
111
|
+
: term.name === 'datatype' && term.args.length === 1 ? term : new Struct(term.name, term.args.map(shape));
|
|
112
|
+
// The functors of a term to a depth, and the datatypes of its literals:
|
|
113
|
+
// patterns with the same skeleton are generalized into one.
|
|
114
|
+
const skeleton = (term, depth) => term instanceof Var || !depth ? '*' : !(term instanceof Struct) ? typeof term
|
|
115
|
+
: term.name === 'datatype' && term.args.length === 1 ? identity(term)
|
|
116
|
+
: `${term.name}(${term.args.map((arg) => skeleton(arg, depth - 1)).join(',')})`;
|
|
117
|
+
|
|
118
|
+
// Sources as Logic Script statements.
|
|
119
|
+
export function programText(sources) {
|
|
120
|
+
return sources.map((source) => {
|
|
121
|
+
const body = listFromItems(source.body);
|
|
122
|
+
const statement = source.kind === 'fact' ? new Struct('fact', [source.head])
|
|
123
|
+
: source.kind === 'backward' ? new Struct('implied_by', [source.head, body])
|
|
124
|
+
: source.kind === 'contradiction' ? new Struct('contradiction', [body])
|
|
125
|
+
: new Struct('implies', [body, isTerm(source.head, 'and', 2) ? listFromItems(flattenConjunction(source.head)) : source.head]);
|
|
126
|
+
return `${write(statement, null, new Lettering())};\n`;
|
|
127
|
+
}).join('');
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
export class Specializer {
|
|
131
|
+
// quads: the keys whose arguments are subject, property, object and graph.
|
|
132
|
+
constructor(program, { quads = [] } = {}) {
|
|
133
|
+
this.quads = new Set(quads);
|
|
134
|
+
this.cache = new Map();
|
|
135
|
+
this.reason = null;
|
|
136
|
+
try {
|
|
137
|
+
this.prepare(program);
|
|
138
|
+
} catch (error) {
|
|
139
|
+
if (!(error instanceof Unsupported)) throw error;
|
|
140
|
+
this.reason = error.message;
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
prepare(program) {
|
|
145
|
+
if (program.inspectionEnabled) throw new Unsupported('it inspects rules');
|
|
146
|
+
const bodied = new Set(program.clauses.filter((c) => !c.forward && c.body.length).map((c) => key(c.head)));
|
|
147
|
+
this.data = new Set();
|
|
148
|
+
for (const clause of program.clauses) {
|
|
149
|
+
if (clause.restricted || clause.templates.length || clause.parentId !== null || clause.captures !== null) {
|
|
150
|
+
throw new Unsupported('it has restricted rules or rule templates');
|
|
151
|
+
}
|
|
152
|
+
if (clause.forward) {
|
|
153
|
+
for (const head of clause.heads) if (head !== 'true' && head !== 'false') this.data.add(key(head));
|
|
154
|
+
if (clause.body.some((goal) => goal instanceof Var)) throw new Unsupported('a forward rule calls a variable');
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
for (const clause of program.clauses) {
|
|
158
|
+
if (!clause.forward && !clause.body.length && !bodied.has(key(clause.head))) this.data.add(key(clause.head));
|
|
159
|
+
}
|
|
160
|
+
for (const k of this.data) {
|
|
161
|
+
if (bodied.has(k)) throw new Unsupported(`${k} has forward and backward clauses`);
|
|
162
|
+
if (program.groups.has(`old_${k}`) || this.data.has(`old_${k}`)) throw new Unsupported(`it names old_${k}`);
|
|
163
|
+
}
|
|
164
|
+
// Backward clauses and the facts of backward relations stay as they are.
|
|
165
|
+
this.backward = program.clauses.filter((c) => !c.forward && !this.data.has(key(c.head)));
|
|
166
|
+
this.backwardKeys = new Set(this.backward.map((c) => key(c.head)));
|
|
167
|
+
this.clausesOf = new Map();
|
|
168
|
+
for (const clause of this.backward) {
|
|
169
|
+
const k = key(clause.head);
|
|
170
|
+
if (!this.clausesOf.has(k)) this.clausesOf.set(k, []);
|
|
171
|
+
this.clausesOf.get(k).push(clause);
|
|
172
|
+
}
|
|
173
|
+
this.rules = program.clauses.filter((c) => c.forward && !c.heads.every((head) => head === 'true'));
|
|
174
|
+
const result = run(program);
|
|
175
|
+
if (result.haltCode !== null) throw new Unsupported('its own facts are contradictory');
|
|
176
|
+
const facts = program.clauses.filter((c) => !c.forward && !c.body.length && this.data.has(key(c.head))).map((c) => c.head);
|
|
177
|
+
for (const node of result.derived) if (this.data.has(key(node.goal))) facts.push(node.goal);
|
|
178
|
+
if (!facts.every((fact) => isGround(fact))) throw new Unsupported('it has facts with variables');
|
|
179
|
+
this.oldIds = new Set(facts.map(identity));
|
|
180
|
+
this.index = new Map();
|
|
181
|
+
for (const fact of facts) {
|
|
182
|
+
for (const at of this.indexKeys(fact)) {
|
|
183
|
+
let list = this.index.get(at);
|
|
184
|
+
if (list === undefined) this.index.set(at, list = []);
|
|
185
|
+
list.push(fact);
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
// The index keys of a term from least to most specific: its key, and for
|
|
191
|
+
// a quad its property, and the class of an rdf:type statement.
|
|
192
|
+
indexKeys(goal, env = null) {
|
|
193
|
+
const k = key(goal);
|
|
194
|
+
const keys = [k];
|
|
195
|
+
if (!this.quads.has(k)) return keys;
|
|
196
|
+
const p = env === null ? goal.args[1] : copyResolved(goal.args[1], env);
|
|
197
|
+
if (!isGround(p)) return keys;
|
|
198
|
+
keys.push(`${k}|${identity(p)}`);
|
|
199
|
+
if (!isType(p)) return keys;
|
|
200
|
+
const o = env === null ? goal.args[2] : copyResolved(goal.args[2], env);
|
|
201
|
+
if (isGround(o)) keys.push(`${k}|${identity(p)}|${identity(o)}`);
|
|
202
|
+
return keys;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
// The old facts a goal matches.
|
|
206
|
+
matches(goal, env, limit = Infinity) {
|
|
207
|
+
const bucket = this.index.get(this.indexKeys(goal, env).at(-1)) ?? [];
|
|
208
|
+
if (bucket.length > limit) return null;
|
|
209
|
+
return bucket.filter((fact) => {
|
|
210
|
+
const mark = env.mark();
|
|
211
|
+
const matches = unify(goal, fact, env);
|
|
212
|
+
env.undo(mark);
|
|
213
|
+
return matches;
|
|
214
|
+
});
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
// A program for these arriving facts, or null when this program cannot be
|
|
218
|
+
// specialized; old holds the identities of the old facts.
|
|
219
|
+
specialize(facts) {
|
|
220
|
+
if (this.reason !== null) return null;
|
|
221
|
+
const arriving = facts.filter((fact) => !this.oldIds.has(identity(fact)));
|
|
222
|
+
this.patterns = new Map();
|
|
223
|
+
for (const fact of arriving) {
|
|
224
|
+
const k = key(fact);
|
|
225
|
+
// A relation without facts or forward rules of its own may be read
|
|
226
|
+
// anywhere, under negation too: the whole program runs.
|
|
227
|
+
if (!this.data.has(k)) return null;
|
|
228
|
+
this.addPattern(this.quads.has(k)
|
|
229
|
+
? new Struct(fact.name, [shape(fact.args[0]), fact.args[1], isType(fact.args[1]) ? fact.args[2] : shape(fact.args[2]), fact.args[3]])
|
|
230
|
+
: shape(fact));
|
|
231
|
+
}
|
|
232
|
+
const id = [...this.patterns.values()].flatMap((group) => [...group.values()].map(canonical)).sort().join('\n');
|
|
233
|
+
let compiled = this.cache.get(id);
|
|
234
|
+
if (compiled === undefined) {
|
|
235
|
+
try {
|
|
236
|
+
compiled = this.compile();
|
|
237
|
+
} catch (error) {
|
|
238
|
+
if (!(error instanceof Unsupported)) throw error;
|
|
239
|
+
compiled = { reason: error.message };
|
|
240
|
+
}
|
|
241
|
+
this.cache.set(id, compiled);
|
|
242
|
+
}
|
|
243
|
+
if (compiled.reason) return null;
|
|
244
|
+
const first = compiled.program === undefined;
|
|
245
|
+
compiled.program ??= new Program(compiled.sources);
|
|
246
|
+
return { program: compiled.program.withFacts(arriving), sources: compiled.sources, old: this.oldIds, fresh: first };
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
// Add a pattern of new facts, generalizing the one of its relation,
|
|
250
|
+
// property and class; true when that changes what can be new.
|
|
251
|
+
addPattern(pattern) {
|
|
252
|
+
const k = key(pattern);
|
|
253
|
+
// With new facts of any property, as owl:sameAs between individuals
|
|
254
|
+
// makes, nearly every rule is a variant: the whole program runs instead.
|
|
255
|
+
if (this.quads.has(k) && !isGround(pattern.args[1])) throw new Unsupported('new facts can have any property');
|
|
256
|
+
let group = this.patterns.get(k);
|
|
257
|
+
if (group === undefined) this.patterns.set(k, group = new Map());
|
|
258
|
+
const at = `${this.indexKeys(pattern).at(-1)}|${skeleton(pattern, 4)}`;
|
|
259
|
+
const known = group.get(at);
|
|
260
|
+
if (known !== undefined && instance(known, pattern)) return false;
|
|
261
|
+
group.set(at, known === undefined ? pattern : generalize([known, pattern]));
|
|
262
|
+
return true;
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
// The patterns of new facts a goal can match.
|
|
266
|
+
newPatterns(goal, env) {
|
|
267
|
+
const found = [];
|
|
268
|
+
const args = goal.args.map((arg) => deref(arg, env));
|
|
269
|
+
for (const pattern of this.patterns.get(key(goal))?.values() ?? []) {
|
|
270
|
+
if (pattern.args.some((arg, i) => clashes(args[i], arg, env))) continue;
|
|
271
|
+
const copy = renamed(pattern);
|
|
272
|
+
const mark = env.mark();
|
|
273
|
+
if (unify(goal, copy, env)) found.push(copy);
|
|
274
|
+
env.undo(mark);
|
|
275
|
+
}
|
|
276
|
+
return found;
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
mayBeNew(goal, env = new Env()) {
|
|
280
|
+
return this.newPatterns(goal, env).length > 0;
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
compile() {
|
|
284
|
+
this.readsMemo = new Map();
|
|
285
|
+
this.steps = 0;
|
|
286
|
+
// The patterns of new facts, to a fixpoint.
|
|
287
|
+
for (let changed = true; changed;) {
|
|
288
|
+
changed = false;
|
|
289
|
+
for (const rule of this.rules) {
|
|
290
|
+
this.variants(rule, (heads) => {
|
|
291
|
+
for (const head of heads) if (head !== 'false' && this.addPattern(head)) changed = true;
|
|
292
|
+
});
|
|
293
|
+
}
|
|
294
|
+
if (changed) this.readsMemo = new Map();
|
|
295
|
+
}
|
|
296
|
+
const sources = [];
|
|
297
|
+
const needed = new Map();
|
|
298
|
+
const need = (goal) => {
|
|
299
|
+
for (const fact of this.matches(goal, new Env())) needed.set(identity(fact), fact);
|
|
300
|
+
};
|
|
301
|
+
for (const rule of this.rules) {
|
|
302
|
+
this.variants(rule, (heads, body, newIndex) => {
|
|
303
|
+
const goals = body.map(([goal, mode]) => {
|
|
304
|
+
if (mode === 'old') {
|
|
305
|
+
need(goal);
|
|
306
|
+
return old(goal);
|
|
307
|
+
}
|
|
308
|
+
return mode === 'new' ? goal : this.rewrite(goal, false, need);
|
|
309
|
+
});
|
|
310
|
+
// A new premise first: it has the fewest facts to try.
|
|
311
|
+
const ordered = newIndex < 0 ? goals : [goals[newIndex], ...goals.filter((_, i) => i !== newIndex)];
|
|
312
|
+
const inBody = new Set();
|
|
313
|
+
for (const goal of ordered) for (const name of variables(goal).keys()) inBody.add(name);
|
|
314
|
+
if (heads.some((head) => [...variables(head).keys()].some((name) => !inBody.has(name)))) {
|
|
315
|
+
// Witnesses are shared by the conclusions of one firing.
|
|
316
|
+
sources.push(new Source('forward', conjunction(heads), ordered));
|
|
317
|
+
return;
|
|
318
|
+
}
|
|
319
|
+
for (const head of heads) {
|
|
320
|
+
if (head === 'false') {
|
|
321
|
+
sources.push(new Source('contradiction', 'false', ordered));
|
|
322
|
+
continue;
|
|
323
|
+
}
|
|
324
|
+
// An old conclusion is not new: say so when the old facts it
|
|
325
|
+
// could be are few enough to copy.
|
|
326
|
+
const could = this.matches(head, new Env(), MANY);
|
|
327
|
+
if (could !== null && could.length) {
|
|
328
|
+
need(head);
|
|
329
|
+
sources.push(new Source('forward', head, [...ordered, new Struct('not', [old(head)])]));
|
|
330
|
+
} else {
|
|
331
|
+
sources.push(new Source('forward', head, ordered));
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
});
|
|
335
|
+
}
|
|
336
|
+
for (const clause of this.backward) {
|
|
337
|
+
sources.push(clause.body.length
|
|
338
|
+
? new Source('backward', clause.head, clause.body.map((goal) => this.rewrite(goal, false, need)))
|
|
339
|
+
: new Source('fact', clause.head, []));
|
|
340
|
+
}
|
|
341
|
+
for (const fact of needed.values()) sources.push(new Source('fact', old(fact), []));
|
|
342
|
+
return { sources };
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
// Whether a goal that is no premise may hold: false when no clause can
|
|
346
|
+
// answer it within depth steps, or a type test fails. A goal only one fact
|
|
347
|
+
// can answer is bound to it in env, so the goals after it see its values.
|
|
348
|
+
holds(goal, depth, env) {
|
|
349
|
+
const resolved = copyResolved(goal, env);
|
|
350
|
+
if (!(resolved instanceof Struct)) return true;
|
|
351
|
+
const goalKey = key(resolved);
|
|
352
|
+
if (TYPE_TESTS.has(goalKey)) return resolved.args[0] instanceof Var || TYPE_TESTS.get(goalKey)(resolved.args[0]);
|
|
353
|
+
if (goalKey === 'and/2') return resolved.args.every((arg) => this.holds(arg, depth, env));
|
|
354
|
+
if (goalKey === 'or/2') return resolved.args.some((arg) => this.holds(arg, depth, new Env()));
|
|
355
|
+
if (!this.backwardKeys.has(goalKey)) return true;
|
|
356
|
+
let only = null;
|
|
357
|
+
let count = 0;
|
|
358
|
+
for (const clause of this.clausesOf.get(goalKey)) {
|
|
359
|
+
const names = new Map();
|
|
360
|
+
const suffix = `h${++fresh}`;
|
|
361
|
+
const head = freshTerm(clause.head, suffix, names);
|
|
362
|
+
const local = new Env();
|
|
363
|
+
if (!unify(resolved, head, local)) continue;
|
|
364
|
+
if (depth && !clause.body.every((item) => this.holds(freshTerm(item, suffix, names), depth - 1, local))) continue;
|
|
365
|
+
if (++count > 1) return true;
|
|
366
|
+
only = clause.body.length ? null : copyResolved(head, local);
|
|
367
|
+
}
|
|
368
|
+
if (only !== null) unify(resolved, only, env);
|
|
369
|
+
return count > 0;
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
// Whether a goal that is no premise reads facts that can be new: a data
|
|
373
|
+
// goal inside a control goal, or a backward relation that reads them.
|
|
374
|
+
readsNew(goal) {
|
|
375
|
+
if (!(goal instanceof Struct || typeof goal === 'string')) return goal instanceof Var;
|
|
376
|
+
const goalKey = key(goal);
|
|
377
|
+
if (this.data.has(goalKey)) return this.mayBeNew(goal);
|
|
378
|
+
if (CONTROL_KEYS.has(goalKey)) return goal.args.some((arg) => this.readsNew(arg));
|
|
379
|
+
if (!this.backwardKeys.has(goalKey)) return false;
|
|
380
|
+
let reads = this.readsMemo.get(goalKey);
|
|
381
|
+
if (reads !== undefined) return reads;
|
|
382
|
+
const seen = new Set([goalKey]);
|
|
383
|
+
const walk = (item) => {
|
|
384
|
+
if (!(item instanceof Struct || typeof item === 'string')) return item instanceof Var;
|
|
385
|
+
const itemKey = key(item);
|
|
386
|
+
if (this.data.has(itemKey)) return this.mayBeNew(item);
|
|
387
|
+
if (CONTROL_KEYS.has(itemKey)) return item.args.some(walk);
|
|
388
|
+
if (!this.backwardKeys.has(itemKey) || seen.has(itemKey)) return false;
|
|
389
|
+
seen.add(itemKey);
|
|
390
|
+
return this.clausesOf.get(itemKey).some((c) => c.body.some(walk));
|
|
391
|
+
};
|
|
392
|
+
reads = this.clausesOf.get(goalKey).some((c) => c.body.some(walk));
|
|
393
|
+
this.readsMemo.set(goalKey, reads);
|
|
394
|
+
return reads;
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
// A goal that is not a premise of a variant, with its data goals reading
|
|
398
|
+
// old facts, or old and new ones; negating or collecting new facts is not
|
|
399
|
+
// specialized.
|
|
400
|
+
rewrite(goal, negated, need) {
|
|
401
|
+
if (goal instanceof Var) throw new Unsupported('a goal is a variable');
|
|
402
|
+
if (!(goal instanceof Struct || typeof goal === 'string')) return goal;
|
|
403
|
+
const goalKey = key(goal);
|
|
404
|
+
if (this.data.has(goalKey)) {
|
|
405
|
+
const may = this.mayBeNew(goal);
|
|
406
|
+
if (may && negated) throw new Unsupported(`it negates or collects ${goalKey} facts that can be new`);
|
|
407
|
+
need(goal);
|
|
408
|
+
return may ? new Struct('or', [old(goal), goal]) : old(goal);
|
|
409
|
+
}
|
|
410
|
+
if (NEGATING.has(goalKey)) {
|
|
411
|
+
const at = goalKey === 'not/1' ? 0 : 1;
|
|
412
|
+
return new Struct(goal.name, goal.args.map((arg, i) => i === at ? this.rewrite(arg, true, need) : arg));
|
|
413
|
+
}
|
|
414
|
+
if (CONTROL_KEYS.has(goalKey)) return new Struct(goal.name, goal.args.map((arg) => this.rewrite(arg, negated, need)));
|
|
415
|
+
if (negated && this.readsNew(goal)) {
|
|
416
|
+
throw new Unsupported(`it negates or collects ${goalKey}, which reads facts that can be new`);
|
|
417
|
+
}
|
|
418
|
+
return goal;
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
// Each variant of a forward rule: emit(heads, body, newIndex), the body a
|
|
422
|
+
// list of [goal, mode], mode 'new', 'old' or null for a goal that is no
|
|
423
|
+
// premise, and newIndex the position of the first new premise.
|
|
424
|
+
variants(rule, emit) {
|
|
425
|
+
const names = new Map();
|
|
426
|
+
const suffix = `s${++fresh}`;
|
|
427
|
+
const heads = rule.heads.filter((head) => head !== 'true').map((head) => freshTerm(head, suffix, names));
|
|
428
|
+
const body = rule.body.map((goal) => freshTerm(goal, suffix, names));
|
|
429
|
+
const data = body.map((goal, i) => this.data.has(key(goal)) ? i : -1).filter((i) => i >= 0);
|
|
430
|
+
// A negation or collection of what can be new is refused whether or not
|
|
431
|
+
// a variant survives: more facts could retract an old conclusion.
|
|
432
|
+
for (const goal of body) if (!this.data.has(key(goal))) this.rewrite(goal, false, () => {});
|
|
433
|
+
// A goal that is no premise but reads new facts makes a variant new.
|
|
434
|
+
const reading = body.some((goal) => !this.data.has(key(goal)) && this.readsNew(goal));
|
|
435
|
+
const modes = new Array(body.length).fill(null);
|
|
436
|
+
const env = new Env();
|
|
437
|
+
let leaves = 0;
|
|
438
|
+
const leaf = (count) => {
|
|
439
|
+
if (!count && !reading) return;
|
|
440
|
+
const mark = env.mark();
|
|
441
|
+
try {
|
|
442
|
+
for (const [i, goal] of body.entries()) if (modes[i] === null && !this.holds(goal, DEPTH, env)) return;
|
|
443
|
+
settled(count);
|
|
444
|
+
} finally {
|
|
445
|
+
env.undo(mark);
|
|
446
|
+
}
|
|
447
|
+
};
|
|
448
|
+
const settled = () => {
|
|
449
|
+
const resolved = body.map((goal) => copyResolved(goal, env));
|
|
450
|
+
const premises = resolved.filter((_, i) => modes[i] === 'new' || modes[i] === 'old');
|
|
451
|
+
const kept = heads.map((head) => copyResolved(head, env)).filter((head) => head === 'false' ||
|
|
452
|
+
(!premises.some((goal) => identical(goal, head)) && !(isGround(head) && this.oldIds.has(identity(head)))));
|
|
453
|
+
if (!kept.length) return;
|
|
454
|
+
const list = [];
|
|
455
|
+
let newIndex = -1;
|
|
456
|
+
resolved.forEach((goal, i) => {
|
|
457
|
+
if (modes[i] === 'fact') return;
|
|
458
|
+
if (modes[i] === 'new' && newIndex < 0) newIndex = list.length;
|
|
459
|
+
list.push([goal, modes[i]]);
|
|
460
|
+
});
|
|
461
|
+
emit(kept, list, newIndex);
|
|
462
|
+
};
|
|
463
|
+
// The variables in the property, or rdf:type class, of the conclusions
|
|
464
|
+
// and the other premises: unfolding an old premise that binds one makes
|
|
465
|
+
// a pattern specific.
|
|
466
|
+
const keyed = (i) => {
|
|
467
|
+
const found = new Set();
|
|
468
|
+
for (const term of [...heads, ...data.filter((j) => j !== i).map((j) => body[j])]) {
|
|
469
|
+
if (!(term instanceof Struct) || !this.quads.has(key(term))) continue;
|
|
470
|
+
const [, p, o] = term.args.map((arg) => copyResolved(arg, env));
|
|
471
|
+
for (const name of variables(p).keys()) found.add(name);
|
|
472
|
+
if (p instanceof Var || isType(p)) for (const name of variables(o).keys()) found.add(name);
|
|
473
|
+
}
|
|
474
|
+
return found;
|
|
475
|
+
};
|
|
476
|
+
const visit = (pending, count) => {
|
|
477
|
+
if (++this.steps > STEPS) throw new Unsupported('its messages need too many specialized rules');
|
|
478
|
+
if (!pending.length) return leaf(count);
|
|
479
|
+
if (!count && !reading && !pending.some((i) => this.mayBeNew(body[i], env))) return;
|
|
480
|
+
// The premise with the fewest alternatives first; none ends the search.
|
|
481
|
+
let choice = null;
|
|
482
|
+
for (const [at, i] of pending.entries()) {
|
|
483
|
+
const goal = body[i];
|
|
484
|
+
const patterns = this.newPatterns(goal, env);
|
|
485
|
+
const facts = this.matches(goal, env, MANY);
|
|
486
|
+
const any = facts === null || facts.length > 0;
|
|
487
|
+
let unfold = facts !== null && facts.length > 0 && facts.length <= UNFOLD;
|
|
488
|
+
if (unfold) {
|
|
489
|
+
const names = keyed(i);
|
|
490
|
+
unfold = [...variables(copyResolved(goal, env)).keys()].some((name) => names.has(name));
|
|
491
|
+
}
|
|
492
|
+
const branches = patterns.length + (unfold ? facts.length : any ? 1 : 0);
|
|
493
|
+
if (!branches) return;
|
|
494
|
+
if (choice === null || branches < choice.branches) choice = { at, i, patterns, facts, any, unfold, branches };
|
|
495
|
+
}
|
|
496
|
+
const { at, i, patterns, facts, any, unfold } = choice;
|
|
497
|
+
const rest = pending.filter((_, k) => k !== at);
|
|
498
|
+
const goal = body[i];
|
|
499
|
+
for (const pattern of patterns) {
|
|
500
|
+
const mark = env.mark();
|
|
501
|
+
if (unify(goal, pattern, env)) {
|
|
502
|
+
modes[i] = 'new';
|
|
503
|
+
visit(rest, count + 1);
|
|
504
|
+
}
|
|
505
|
+
env.undo(mark);
|
|
506
|
+
}
|
|
507
|
+
// Old: possible only if a later premise can still be new.
|
|
508
|
+
if (any && (count || reading || rest.some((j) => this.mayBeNew(body[j], env)))) {
|
|
509
|
+
if (unfold) {
|
|
510
|
+
for (const fact of facts) {
|
|
511
|
+
const mark = env.mark();
|
|
512
|
+
if (unify(goal, fact, env)) {
|
|
513
|
+
modes[i] = 'fact';
|
|
514
|
+
if (++leaves > LEAVES) throw new Unsupported(`rule ${rule.id} has too many specialized instances`);
|
|
515
|
+
visit(rest, count);
|
|
516
|
+
}
|
|
517
|
+
env.undo(mark);
|
|
518
|
+
}
|
|
519
|
+
} else {
|
|
520
|
+
// What all the old facts it matches share, such as the same
|
|
521
|
+
// subject and object, still binds the premise.
|
|
522
|
+
const mark = env.mark();
|
|
523
|
+
if (facts !== null) unify(goal, generalize(facts), env);
|
|
524
|
+
modes[i] = 'old';
|
|
525
|
+
visit(rest, count);
|
|
526
|
+
env.undo(mark);
|
|
527
|
+
}
|
|
528
|
+
}
|
|
529
|
+
modes[i] = null;
|
|
530
|
+
};
|
|
531
|
+
visit(data, 0);
|
|
532
|
+
}
|
|
533
|
+
}
|
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.8.
|
|
2
|
+
export const VERSION = '0.8.11';
|