eyemind 0.8.8 → 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 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
@@ -2,7 +2,7 @@
2
2
 
3
3
  ```text
4
4
  Title: The Logic Script (LS) Language and Proof Format
5
- Version: eyemind 0.8.8
5
+ Version: eyemind 0.8.11
6
6
  ```
7
7
 
8
8
  This document specifies Logic Script (LS): the syntax and meaning of its
@@ -565,6 +565,7 @@ primitive called outside its patterns raises an error.
565
565
  | `regex_match` | `regex_match(+P, +T)` | Some part of the atom `T` matches the regular expression `P`. |
566
566
  | `regex_find` | `regex_find(+P, +T, ?G)` | One solution per match of `P` in `T`, from left to right: `G` is the list of the matched text followed by each capture group's text, `''` for a group that took no part in the match. |
567
567
  | `regex_replace` | `regex_replace(+P, +T, +R, ?U)` | `U` is `T` with every match of `P` replaced by `R`. |
568
+ | `xml_content` | `xml_content(+T)` | The atom `T` is self-contained XML content, as defined below. |
568
569
 
569
570
  A character is a Unicode code point. Every primitive except `atom_concat`
570
571
  and `regex_find` has at most one solution.
@@ -603,6 +604,15 @@ their arguments. A primitive given an argument of the wrong kind for its
603
604
  patterns raises an error, as `atom_length(123, N)` does; one given arguments
604
605
  of the right kinds that has no solution fails, as `arg(5, f(1), A)` does.
605
606
 
607
+ `xml_content/1` tests the lexical space of [`rdf:XMLLiteral`](https://www.w3.org/TR/rdf12-concepts/#section-XMLLiteral).
608
+ The atom MUST be well-balanced, self-contained content as defined by
609
+ [XML 1.1](https://www.w3.org/TR/xml11/#NT-content) and conform to
610
+ [Namespaces in XML 1.0](https://www.w3.org/TR/xml-names/#Conformance) when
611
+ embedded inside an element with no namespace declarations. Empty content and
612
+ multiple top-level nodes are allowed. Only the predefined entities and
613
+ numeric character references are available. XML declarations and DTDs are
614
+ outside the content grammar. The test performs no I/O.
615
+
606
616
  All primitives take exactly the displayed number of arguments. `functor`
607
617
  and `univ` expose list structure as specified in [Section 2.2](#22-lists); use bracket
608
618
  syntax when writing lists.
package/README.md CHANGED
@@ -12,10 +12,10 @@ 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 152 runnable programs, each with a card deck and saved
16
- conclusions, proofs and check reports. The specification defines the language,
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
- 1246 cases that test language and proof behavior, and runs
18
+ 1247 cases that test language and proof behavior, and runs
19
19
  [in your browser](https://eyereasoner.github.io/eyemind/playground/conformance).
20
20
 
21
21
  ## Contents
@@ -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 and absence tests need their inputs from earlier premises, and
238
- arithmetic follows LS: integers stay exact, division gives a float. An
239
- answer becomes a sentence such as `16 is a square of 4.`; a witness is written
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) or
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,15 +302,36 @@ 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
301
327
  set over the RDF data given with it; the result is the inference graph, as
302
328
  Turtle (`--all` adds the base graph). Rules become `implies`, `NOT` becomes
303
329
  `not`, `GROUP` becomes `findall_sorted`, and a SPARQL error is a goal that
304
- fails. Decimals are exact (`0.1 + 0.2` is `0.3`) and floats are binary64.
330
+ fails. Local variable names in `NOT` and `GROUP` cannot be bound again
331
+ elsewhere in the same rule. Decimals are exact (`0.1 + 0.2` is `0.3`) and
332
+ floats are binary64.
305
333
  `NOW()` and `UUID()` use a clock and seed captured at compilation, which a
306
- saved proof retains. All 342 W3C SPARQL 1.2 RL tests pass.
334
+ saved proof retains. All 368 W3C SPARQL 1.2 RL tests pass.
307
335
 
308
336
  ```sh
309
337
  eyemind -c rules.srl facts.ttl # the inference graph, with a checked proof
@@ -319,7 +347,9 @@ is Turtle with the new triples and reports.
319
347
  rules, including the datatype map of its table 8: value equality and
320
348
  difference, membership across lexical forms, and ill-typed literals for the
321
349
  XSD numeric, string, temporal and binary types, `rdf:PlainLiteral` and
322
- `rdf:XMLLiteral`. It reports contradictions as `ent:Conflict` records
350
+ `rdf:XMLLiteral`. XML literal validation checks well-formed content and
351
+ namespaces. Equality and difference for XML literals use their lexical forms.
352
+ It reports contradictions as `ent:Conflict` records
323
353
  instead of inferring everything from them, and passes all 273 cases of the
324
354
  [MobiBench](https://github.com/william-vw/mobibench) OWL 2 RL suite.
325
355
  - `--qudt` normalizes QUDT quantity values and CDT literals to SI units from
@@ -513,7 +543,7 @@ eyemind [OPTION ...] [FILE ...]
513
543
  | `--json` | With a checking mode, print the report as JSON. |
514
544
  | `--goal GOAL` | Ask `GOAL` after forward reasoning; may be repeated. |
515
545
  | `--unused` | List the clauses that make no difference to the conclusions. |
516
- | `--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. |
517
547
  | `--stats` | Print reasoning statistics as JSON to standard error. |
518
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. |
519
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. |
@@ -662,6 +692,11 @@ The playground tests need Chrome (`CHROME` names it). A full run writes
662
692
  [REPORT.md](REPORT.md) and the [W3C EARL reports](reports/README.md); the
663
693
  [upstream suites](test/UPSTREAM.md) are cached in Git-ignored `.cache/`.
664
694
 
695
+ The example tests reproduce every saved conclusion and proof, then check
696
+ the proofs from disk. The deck tests check the documented claims and run
697
+ commands with extra goals, conversions or redirects. The corpus and CLI
698
+ tests cover the standard example commands.
699
+
665
700
  ## The name
666
701
 
667
702
  **eyemind** joins *eye* and *mind*: facts and rules lead to conclusions whose reasoning can be inspected and checked.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "eyemind",
3
- "version": "0.8.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/builtins.js CHANGED
@@ -17,6 +17,7 @@ import {
17
17
  } from './terms.js';
18
18
  import { DIGESTS, utf8 } from './digest.js';
19
19
  import { floatText, write } from './writer.js';
20
+ import { isXmlContent } from './xml.js';
20
21
 
21
22
  function comparison(holds) {
22
23
  return (args, resolved, env) => holds(arith.compare(args[0], args[1], env));
@@ -280,6 +281,7 @@ export const TESTS = new Map([
280
281
  ['term_text/2', termText],
281
282
  ['float64/4', float64],
282
283
  ['regex_match/2', regexMatch],
284
+ ['xml_content/1', (args, resolved) => isXmlContent(text('xml_content/1', resolved[0]))],
283
285
  ['regex_replace/4', regexReplace],
284
286
  ]);
285
287
 
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 (Object.keys(rdfLogic).length) throw new UsageError(`${Object.keys(rdfLogic).map((p) => '--' + p).join(' ')} cannot be combined with --stream-messages`);
154
- if (proofFile !== null || options.proof || proveAndCheck || printProgram || unused) {
155
- throw new UsageError('--stream-messages cannot be combined with --proof, --check-proof, --prove-and-check, --program or --unused; replay the whole log to prove its conclusions');
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);
@@ -192,7 +216,7 @@ export function main(argv, io) {
192
216
  const document = proofFile === null ? null : readSource(proofFile, io);
193
217
  const loaded = loadInputs(files.map((file) => [readSource(file, io), file === '-' ? '<stdin>' : file]), io,
194
218
  { base, messageInputs: io.messageInputs, odrl, ...rdfLogic,
195
- srlContext: document !== null && files.some((file) => inputKind(file) === 'srl') ? srlContextFromProof(document) : null });
219
+ srlContext: document !== null && (rdfLogic.shacl || files.some((file) => inputKind(file) === 'srl')) ? srlContextFromProof(document) : null });
196
220
  const program = loaded.program;
197
221
  if (printProgram) {
198
222
  stdout(loaded.text);
package/src/closure.js CHANGED
@@ -15,10 +15,11 @@
15
15
  import { PRIMITIVE_KEYS, primitive } from './builtins.js';
16
16
  import { freshClause, sameVariant, text, variant } from './common.js';
17
17
  import { INSPECTION_KEYS } from './inspection.js';
18
+ import { bucketEntries, positionIndexes } from './program.js';
18
19
  import { Lettering, write } from './writer.js';
19
20
  import {
20
- Env, EyemindError, Struct, Var, copyResolved, deref, flattenConjunction, freshTerm, identity, isCallable, isGround, key,
21
- isGroundButAnonymous, listFromItems, sortCollected, unify, variables,
21
+ Env, EyemindError, Struct, Var, copyResolved, deref, flattenConjunction, freshTerm, identity, indexKey, isCallable, isGround,
22
+ isGroundButAnonymous, key, keyArity, listFromItems, sortCollected, unify, variables,
22
23
  } from './terms.js';
23
24
 
24
25
  // Terms as a failure message shows them, variables lettered A, B, ... across
@@ -243,12 +244,23 @@ export class Settler {
243
244
  const goalKey = key(call);
244
245
  const mark = env.mark();
245
246
  if (this.derivedKeys.has(goalKey)) {
246
- const facts = this.listing(goalKey);
247
+ const entry = this.listing(goalKey);
247
248
  reliance.listings.add(goalKey);
249
+ let facts = entry.facts;
250
+ for (const [position, index] of entry.positions.entries()) {
251
+ // Only use buckets that leave no potentially matching facts out.
252
+ if (index === null || index[1].length) continue;
253
+ const argument = indexKey(call.args[position], env);
254
+ if (argument === undefined) continue;
255
+ const candidates = bucketEntries(index[0].get(argument));
256
+ if (candidates.length < facts.length) facts = candidates;
257
+ if (!facts.length) break;
258
+ }
248
259
  for (const fact of facts) {
249
260
  // A derived pattern is freshened at every use.
250
- if (!isGround(fact)) reliance.inspected = true;
251
- if (unify(call, isGround(fact) ? fact : freshTerm(fact, `pattern${++this.serial}`), env)) yield;
261
+ const ground = entry.ground || isGround(fact);
262
+ if (!ground) reliance.inspected = true;
263
+ if (unify(call, ground ? fact : freshTerm(fact, `pattern${++this.serial}`), env)) yield;
252
264
  env.undo(mark);
253
265
  }
254
266
  }
@@ -308,10 +320,18 @@ export class Settler {
308
320
  if (entry === undefined) {
309
321
  const facts = this.source.facts(goalKey);
310
322
  if (facts === null) throw new Unsettled();
311
- entry = { facts, checked: false, failure: null, subject: null, unsettled: false, reported: false, reliance: null };
323
+ const ground = facts.every((fact) => isGround(fact));
324
+ const arity = keyArity(goalKey);
325
+ // Large ground listings are read many times while expanding tables.
326
+ // The buckets retain listing order. Leave patterns and malformed facts
327
+ // on the ordinary scan path.
328
+ const positions = ground && arity && facts.length >= 16 &&
329
+ facts.every((fact) => fact instanceof Struct && key(fact) === goalKey)
330
+ ? positionIndexes(facts, (fact) => fact, arity) : [];
331
+ entry = { facts, ground, positions, checked: false, failure: null, subject: null, unsettled: false, reported: false, reliance: null };
312
332
  this.listings.set(goalKey, entry);
313
333
  }
314
- return entry.facts;
334
+ return entry;
315
335
  }
316
336
 
317
337
  // A table holds when expanding its call gives exactly its answers, in order.
package/src/fidelity.js CHANGED
@@ -50,6 +50,7 @@ export function callQuestions(program, goals, claims) {
50
50
  export function replayer(program, settler, stepOf, used) {
51
51
  const confirmed = new Map();
52
52
  const active = new Set();
53
+ const settledCalls = new Map();
53
54
  // The steps a firing's replay followed, each as [replayed, recorded]: once
54
55
  // the whole firing has replayed, each must be its step up to renaming.
55
56
  let followed = [];
@@ -104,10 +105,24 @@ export function replayer(program, settler, stepOf, used) {
104
105
  // an answer agrees with the use; null when its search consults derived
105
106
  // facts, whose support only steps show.
106
107
  function answered(goal, use, env) {
107
- const outcome = settler.answers(copyResolved(goal, env));
108
- if (outcome.status === 'unsettled' || (outcome.status === 'settled' && outcome.listings.length)) return null;
109
- for (const item of outcome.tables) used.tables.add(item);
110
- if (outcome.status !== 'settled') return false;
108
+ const call = copyResolved(goal, env);
109
+ const id = variant(call, true);
110
+ let outcome = settledCalls.get(id);
111
+ if (outcome === undefined) {
112
+ const checked = settler.answers(call);
113
+ if (checked.status === 'unsettled') return null;
114
+ if (checked.status === 'settled' && checked.listings.length) {
115
+ // The table depends on derived facts. Each use still follows its step.
116
+ settledCalls.set(id, null);
117
+ return null;
118
+ }
119
+ for (const item of checked.tables) used.tables.add(item);
120
+ if (checked.status !== 'settled') return false;
121
+ // Dependencies have already been checked and marked used for this call.
122
+ outcome = { answers: checked.answers, inspected: checked.inspected };
123
+ settledCalls.set(id, outcome);
124
+ }
125
+ if (outcome === null) return null;
111
126
  // The answer that is the use, up to renaming, is the one the firing
112
127
  // took; failing that, the first that can still become it.
113
128
  const target = variant(use);
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
- function load(inputs, io, { base = null, messageInputs = null, srlContext = null, odrl = false, owl2rl = false, qudt = false, skos = false, shacl = false }) {
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
- if (inputs.some(([, name], k) => kinds[k] !== 'rdf' && name !== '<stdin>')) {
86
- throw new EyemindError(`${switches} takes RDF inputs; standard input is Turtle`);
87
- }
88
- const prefixes = {}, quads = [];
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(', ') });
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');