eyemind 0.5.1 → 0.5.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -20,6 +20,7 @@ The playground runs programs in your browser; the specification defines the lang
20
20
  - [Inspecting rules](#inspecting-rules)
21
21
  - [RDF 1.2](#rdf-12)
22
22
  - [Notation3](#notation3)
23
+ - [SPARQL 1.2 RL](#sparql-12-rl)
23
24
  - [How eyemind reasons](#how-eyemind-reasons)
24
25
  - [Proofs, and what checking one means](#proofs-and-what-checking-one-means)
25
26
  - [Why negation and collection are safe](#why-negation-and-collection-are-safe)
@@ -59,7 +60,7 @@ Prolog, Datalog, N3 and SRL already exist, and eyemind adds no new logic: rules
59
60
  When eyemind is not the right tool:
60
61
 
61
62
  - If you do not need proofs, use the mature tools: SWI-Prolog and XSB have tabling, and Soufflé is fast at scale.
62
- - N3 and SRL are designed around RDF and Web data. eyemind does not compete there: RDF comes in as data (see [RDF 1.2](#rdf-12)), and N3 programs compile to eyemind (see [Notation3](#notation3)).
63
+ - N3 and SRL are designed around RDF and Web data. eyemind does not compete there: RDF is read as data (see [RDF 1.2](#rdf-12)), and N3 programs and SRL rule sets compile to eyemind (see [Notation3](#notation3) and [SPARQL 1.2 RL](#sparql-12-rl)).
63
64
  - eyemind is for cases where someone else has to be able to check why a conclusion holds: audits, compliance, and decisions between parties that do not trust each other.
64
65
 
65
66
  ## Install and run
@@ -173,31 +174,40 @@ The answer is `test(a(A), c(A))`, with the shared variable preserved. Inspection
173
174
 
174
175
  ### RDF 1.2
175
176
 
176
- eyemind has no built-in RDF; RDF arrives as data through [rdf-interchange](https://github.com/eyereasoner/rdf-interchange). `rdf-to-eyemind` turns Turtle, TriG, N-Triples or N-Quads into `rdf(Subject, Predicate, Object, Graph)` facts for `facts_from`, and `eyemind-to-rdf` turns a run's `rdf` or `result_rdf` conclusions back into RDF:
177
+ eyemind reads RDF 1.2 itself, with no dependency: a file ending in `.ttl`, `.trig`, `.nt` or `.nq` is Turtle, TriG, N-Triples or N-Quads, read with the formats' own grammars, and given with a program its quads become `rdf(Subject, Predicate, Object, Graph)` facts, read as data through `facts_from` and never run. `--to turtle`, `trig`, `n-triples` or `n-quads` writes a run's `rdf` and `result_rdf` conclusions back as RDF:
178
+
179
+ ```sh
180
+ eyemind rules.js data.ttl # rdf/4 facts for the rules
181
+ eyemind --to trig rules.js data.trig # the conclusions as TriG
182
+ ```
177
183
 
178
184
  | RDF 1.2 | eyemind term |
179
185
  | --- | --- |
180
186
  | IRI | `iri('https://example.org/bob')` |
181
- | Blank node | `bnode(Scope, Label)` |
182
- | Typed literal | `literal('42', datatype('http://www.w3.org/2001/XMLSchema#integer'))` |
187
+ | Blank node | `bnode(Scope, Label)`, the scope naming the file |
188
+ | `xsd:integer` with a canonical lexical form | an integer, `42`, exact at any size |
189
+ | Other typed literal | `literal('1.50', datatype('http://www.w3.org/2001/XMLSchema#decimal'))`, its lexical form kept |
183
190
  | Language string | `literal('chat', lang('fr'))`, or `lang('ar', 'rtl')` with a direction |
184
191
  | Triple term | `triple(S, P, O)`, which may nest |
185
192
  | Default graph, named graph | `'default_graph'`, `iri(Name)` |
186
193
 
187
- A Skolem term becomes a blank node, the same one for the same rule firing. The `rdf12-*` examples show triple terms, annotations, directional strings, typed numbers and named graphs.
194
+ A reified triple `<< s p o >>` and an annotation `{| ... |}` become their reifier and its `rdf:reifies` triple, as RDF 1.2 defines. A Skolem term is written as a blank node, the same one for the same rule firing. The `rdf12-*` examples show triple terms, annotations, directional strings, typed numbers and named graphs. The W3C RDF test suites run in `npm test` from the mirror in `test/w3c/rdf-tests`: all 1055 tests of N-Triples, N-Quads, Turtle and TriG, in RDF 1.1 and 1.2, pass.
188
195
 
189
196
  ### Notation3
190
197
 
191
- N3 programs run on eyemind through [n3-interchange](https://github.com/eyereasoner/n3-interchange). `n3-to-eyemind` compiles N3 facts and rules into an eyemind program, with the N3 built-ins it uses written as eyemind rules, and `eyemind-to-n3` writes the conclusions back as N3; `eyemind-n3` does both around a run:
198
+ A file ending in `.n3` is Notation3: eyemind compiles its facts and rules into a program, with the N3 built-ins it uses written as eyemind rules, and writes the conclusions back as N3. RDF data files join the N3 document as triples:
192
199
 
193
200
  ```sh
194
- npm install -g n3-interchange
195
- eyemind-n3 examples/n3-family.n3 # answers as N3
196
- n3-to-eyemind examples/n3-family.n3 -o /tmp/n3-family.js # compile a program to inspect
197
- node bin/eyemind.js /tmp/n3-family.js # run it with eyemind
201
+ eyemind examples/n3-family.n3 # the derived triples as N3
202
+ eyemind --program examples/n3-family.n3 > /tmp/family.js # the compiled program, to inspect
203
+ eyemind -c examples/n3-family.n3 # a proof of it, checked
198
204
  ```
199
205
 
200
- Triples are `rdf(Subject, Predicate, Object)`, with IRIs, blank nodes and literals written as in the RDF table above and N3 numbers as eyemind numbers. `=>` becomes `implies`, `<=` becomes `implied_by`, and scoped negation and collection become `not` and `findall`, so an N3 run has a proof that eyemind checks like any other. The n3-interchange README lists its measured coverage and current limits.
206
+ Triples are `rdf(Subject, Predicate, Object)`, with IRIs, blank nodes and literals written as in the RDF table above. N3 integers and decimals become eyemind numbers; float and double literals retain their RDF datatype, including numbers written with an exponent. Decimals use binary64 storage; `math:sum` adds their canonical decimal values before rounding its result. `=>` becomes `implies`, `<=` becomes `implied_by`, `{ ... } => false` becomes `contradiction`, and scoped negation and collection become `not` and `findall`, so an N3 run has a proof that eyemind checks like any other. Derived rules can trigger inference fuses too.
207
+
208
+ Scoped calls can use formulas supplied by the document's stated lists, including RDF collections written with `rdf:first` and `rdf:rest`. These calls are specialized before reasoning so their dependencies remain available for stratification and proof checking; formulas constructed only during reasoning are not supported by this compilation.
209
+
210
+ The documents `log:semantics`, `log:semanticsOrError` and `log:content` name are read before compiling. The command reads local files and HTTP(S) documents, with a ten-second fetch timeout and a 16 MiB response limit. The library uses the host callbacks `readFile(path)` and `readDocument(iri)`; without them it does not read external documents. Their contents become facts of the compiled program, which can be saved with `--program` for later proof checking.
201
211
 
202
212
  Five examples pair the original N3 with a compiled JavaScript program:
203
213
  [family queries](https://eyereasoner.github.io/eyemind/examples/deck/n3-family),
@@ -205,11 +215,22 @@ Five examples pair the original N3 with a compiled JavaScript program:
205
215
  [invoice collection](https://eyereasoner.github.io/eyemind/examples/deck/n3-invoice),
206
216
  [French cities](https://eyereasoner.github.io/eyemind/examples/deck/n3-french-cities), and
207
217
  [existential witnesses](https://eyereasoner.github.io/eyemind/examples/deck/n3-witnesses).
208
- The saved `.js` programs run directly in the playground and with eyemind;
209
- compiling the `.n3` sources or writing answers back as N3 uses n3-interchange.
218
+ The saved `.js` programs run directly in the playground and with eyemind.
210
219
  Each deck shows the N3 result and what its saved proof establishes, including
211
220
  any remaining obligations.
212
221
 
222
+ ### SPARQL 1.2 RL
223
+
224
+ A file ending in `.srl` is a [SPARQL 1.2 RL](https://www.w3.org/TR/sparql12-rl/) rule set: eyemind parses and analyzes it, then compiles it into a program, with the SPARQL functions and aggregates it uses written as eyemind rules, and RDF data files given with it are its base graph. The result is the inference graph, as Turtle:
225
+
226
+ ```sh
227
+ eyemind rules.srl facts.ttl # the inference graph as Turtle
228
+ eyemind --all rules.srl facts.ttl # the base graph too
229
+ eyemind -c rules.srl facts.ttl # a proof of it, checked
230
+ ```
231
+
232
+ Triples are `rdf(Subject, Predicate, Object)`, with `base/3` marking the base graph and `inf/3` the inference graph. A rule becomes `implies`, `NOT` becomes `not` of a helper, `GROUP` becomes `findall`, a blank node in a rule head becomes the Skolem term of its firing, and a SPARQL error is a goal that fails, so `FILTER` rejects the solution and `SET` drops it. The W3C SPARQL 1.2 RL test suite runs in `npm test` from the mirror in `test/w3c/sparql-rl`: all 241 tests pass. `NOW`, `UUID` and `STRUUID` are not supported, as eyemind has no clock or randomness; decimals and doubles are computed as binary64 floats.
233
+
213
234
  ## How eyemind reasons
214
235
 
215
236
  The statement chooses the direction:
@@ -318,7 +339,7 @@ eyemind [OPTION ...] [FILE ...]
318
339
 
319
340
  | Option | Meaning |
320
341
  | --- | --- |
321
- | (none) | Load the files, or standard input, as one program and print its conclusions. |
342
+ | (none) | Load the files, or standard input, as one program and print its conclusions. `.ttl`, `.trig`, `.nt` and `.nq` files are RDF data, `.n3` Notation3 and `.srl` a SPARQL 1.2 RL rule set. |
322
343
  | `-p`, `--proof` | Print the proof instead. |
323
344
  | `-c`, `--prove-and-check` | Generate a proof, check it, and print the checked answers with the report. |
324
345
  | `--check-proof FILE` | Check a saved proof (`-` for standard input) against the program. |
@@ -327,7 +348,11 @@ eyemind [OPTION ...] [FILE ...]
327
348
  | `--strict-proof` | With a checking mode, reject proofs with any obligation. |
328
349
  | `--unused` | List the clauses that make no difference to the conclusions. |
329
350
  | `--stats` | Print reasoning statistics as JSON to standard error. |
330
- | `--max-depth N`, `--max-iterations N`, `--max-inferences N` | Bound backward depth (1000000), forward rounds per stratum (1000) and goals started (1000000). |
351
+ | `--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 or SRL program has 1000000, 100000 and 1000000000. |
352
+ | `--to FORMAT` | Write the conclusions as `turtle`, `trig`, `n-triples`, `n-quads`, `n3` or `eyemind`; by default N3 for N3, Turtle for SRL, eyemind otherwise. |
353
+ | `--all` | With RDF or N3 output, write the given data too. |
354
+ | `--program` | Print the program the inputs compile to. |
355
+ | `--base IRI` | Resolve relative IRIs of the inputs against `IRI` instead of each file's location. |
331
356
  | `-v`, `--version`, `-h`, `--help` | Print the version or the usage. |
332
357
 
333
358
  Exit codes: 0 success, 1 error, 2 a proof that is not valid, 65 a contradiction.
@@ -375,17 +400,22 @@ npm test -- unit examples # only these sections
375
400
  npm test -- -k skolem # only tests whose line contains "skolem"
376
401
  EYEMIND_PROPERTY_SCALE=20 npm test -- -k properties # deeper generated tests
377
402
  node tools/update-examples.js # regenerate example artifacts after an intended change
403
+ node tools/report.js # the table npm test ends with, into REPORT.md
404
+ node tools/notation3tests.js # the saved Notation3 suite, without network access
405
+ node tools/sync-notation3tests.js # refresh its tests and document fixtures from upstream
378
406
  node conformance/run.js --command "my-eyemind" # run the conformance suite against another implementation
379
407
  ```
380
408
 
381
409
  The full suite needs a few GB of memory; on a small machine run it under a cap, such as `systemd-run --user --scope -q -p MemoryMax=3G -p MemorySwapMax=0 -- npm test`. Generated tests forge saved proofs at random and require the checker to reject every forgery that claims more than the program entails. The playground tests need Chrome (`CHROME` names it). When adding an example, register it in [examples/manifest.json](https://github.com/eyereasoner/eyemind/blob/main/examples/manifest.json), write its deck in `examples/deck/`, and generate its artifacts.
382
410
 
411
+ The [Notation3 mirror](test/notation3tests/README.md) pins the upstream tests and their remote document inputs. Ordinary runs use those fixtures, with no network fallback. The sync command refreshes them for review; the scorer's `--live` option checks the current remote resources instead.
412
+
383
413
  ### Releases
384
414
 
385
415
  `./release patch "Describe the changes"` (or `minor`, `major`) requires a clean tree, pulls `main`, runs the tests, bumps the version, and pushes `main` with an annotated tag. The tag creates the GitHub release, which Zenodo archives, and publishes to npm through trusted publishing, with no stored token. To publish an existing tag again, use **Actions → Publish to npm → Run workflow**.
386
416
 
387
417
  ## The name
388
418
 
389
- **eyemind** joins *eye*, after the [EYE](https://github.com/eyereasoner/eye) family of reasoners, to *mind*: facts and rules lead to conclusions whose reasoning can be inspected and checked.
419
+ **eyemind** joins *eye* and *mind*: facts and rules lead to conclusions whose reasoning can be inspected and checked.
390
420
 
391
421
  MIT licensed; see [LICENSE.md](LICENSE.md).
package/SPEC.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  ```text
4
4
  Title: The eyemind Rule Language and Proof Format
5
- Version: eyemind 0.5.1
5
+ Version: eyemind 0.5.3
6
6
  ```
7
7
 
8
8
  This document specifies the syntax and meaning of eyemind programs and data
@@ -2139,6 +2139,16 @@ an invalid check returns 2, otherwise the run's halt code is retained
2139
2139
  text that has a line starting with `step(` or `called(` is a proof document; given one as
2140
2140
  a program, the command line MUST say how to check it instead.
2141
2141
 
2142
+ Files are programs ([Section 3](#3-program-syntax)) unless an
2143
+ implementation reads other formats. eyemind reads files by their extension:
2144
+ `.ttl`, `.trig`, `.nt` and `.nq` as RDF 1.2 data, joining a program as
2145
+ `rdf(S, P, O, G)` facts, `.n3` as Notation3 and `.srl` as a SPARQL 1.2 RL rule
2146
+ set, both compiled to a program, with the options `--to FORMAT` (the output
2147
+ format of the conclusions), `--all`, `--program` and `--base IRI`; its README
2148
+ describes the mappings. Such formats are outside conformance: a conforming
2149
+ implementation need not read them, and the suite does not test them. The
2150
+ proofs and checks of a compiled program are those of any program.
2151
+
2142
2152
  | Exit code | Meaning |
2143
2153
  | --- | --- |
2144
2154
  | 0 | Success, including a check that found the proof valid. |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "eyemind",
3
- "version": "0.5.1",
3
+ "version": "0.5.3",
4
4
  "description": "A dependency-free JavaScript rule language with forward and backward reasoning and checkable proofs.",
5
5
  "type": "module",
6
6
  "main": "./src/index.js",
package/src/cli.js CHANGED
@@ -1,12 +1,14 @@
1
1
  // The eyemind command line.
2
2
  import { run, unusedClauses } from './engine.js';
3
- import { loadSources } from './lang.js';
3
+ import { OUTPUT_FORMATS, defaultFormat, loadInputs, writeConclusions } from './formats.js';
4
4
  import { checkProof, checkReport, publicReport } from './proof.js';
5
5
  import { EyemindError } from './terms.js';
6
6
  import { VERSION } from './version.js';
7
7
 
8
8
  export const HELP = `Usage: eyemind [OPTION ...] [FILE ...]
9
- Programs are JavaScript; forward rules run to a fixpoint.
9
+ Programs are JavaScript; forward rules run to a fixpoint. Other files are read
10
+ by their extension: .ttl, .trig, .nt and .nq as RDF 1.2 data, .n3 as Notation3
11
+ and .srl as a SPARQL 1.2 RL rule set, both compiled to an eyemind program.
10
12
  -p, --proof Print the claims with clause(...) and step(...) records
11
13
  -c, --prove-and-check Generate a proof and check it against the input program
12
14
  --check-proof FILE Print checked answers and a proof check report (- for stdin)
@@ -19,6 +21,12 @@ Programs are JavaScript; forward rules run to a fixpoint.
19
21
  --max-depth N Bound backward recursion (default 1000000)
20
22
  --max-iterations N Bound forward rounds per stratum (default 1000)
21
23
  --max-inferences N Bound reasoning work (default 1000000)
24
+ --to FORMAT Write the conclusions as turtle, trig, n-triples,
25
+ n-quads, n3 or eyemind (default: n3 for N3, turtle
26
+ for a rule set, eyemind otherwise)
27
+ --all With RDF output, write the given data too
28
+ --program Print the program the inputs compile to
29
+ --base IRI Resolve relative IRIs of the inputs against IRI
22
30
  -v, --version Print the version
23
31
  -h, --help Print this help
24
32
  Source defaults to stdin; multiple files form one program.
@@ -26,6 +34,8 @@ Exit codes: 0 success, 1 error, 2 invalid proof, 65 contradiction.
26
34
  `;
27
35
 
28
36
  const LIMITS = { '--max-depth': 'maxDepth', '--max-iterations': 'maxIterations', '--max-inferences': 'maxInferences' };
37
+ // N3 and SPARQL 1.2 RL programs run longer than eyemind's defaults allow.
38
+ const COMPILED_LIMITS = { maxDepth: 1000000, maxIterations: 100000, maxInferences: 1000000000 };
29
39
 
30
40
  class UsageError extends Error {}
31
41
 
@@ -48,6 +58,10 @@ export function main(argv, io) {
48
58
  let asJson = false;
49
59
  let unused = false;
50
60
  let proveAndCheck = false;
61
+ let format = null;
62
+ let all = false;
63
+ let printProgram = false;
64
+ let base = null;
51
65
  for (let i = 0; i < argv.length; i++) {
52
66
  const arg = argv[i];
53
67
  if (arg === '--help' || arg === '-h') {
@@ -70,7 +84,11 @@ export function main(argv, io) {
70
84
  asJson = true;
71
85
  } else if (arg === '--unused') {
72
86
  unused = true;
73
- } else if (arg === '--check-proof' || arg === '--goal' || Object.hasOwn(LIMITS, arg)) {
87
+ } else if (arg === '--all') {
88
+ all = true;
89
+ } else if (arg === '--program') {
90
+ printProgram = true;
91
+ } else if (arg === '--check-proof' || arg === '--goal' || arg === '--to' || arg === '--base' || Object.hasOwn(LIMITS, arg)) {
74
92
  i++;
75
93
  if (i >= argv.length) throw new UsageError(`${arg} needs a value`);
76
94
  const value = argv[i];
@@ -82,6 +100,11 @@ export function main(argv, io) {
82
100
  }
83
101
  if (arg === '--check-proof') {
84
102
  proofFile = value;
103
+ } else if (arg === '--to') {
104
+ if (!OUTPUT_FORMATS.includes(value)) throw new UsageError(`--to takes one of ${OUTPUT_FORMATS.join(', ')}, not ${value}`);
105
+ format = value;
106
+ } else if (arg === '--base') {
107
+ base = value;
85
108
  } else if (arg === '--goal') {
86
109
  goals.push(value);
87
110
  } else {
@@ -109,7 +132,14 @@ export function main(argv, io) {
109
132
  }
110
133
  if (!files.length) files.push('-');
111
134
  if (files.filter((file) => file === '-').length > 1) throw new UsageError('stdin can only be read once');
112
- const program = loadSources(files.map((file) => [readSource(file, io), file === '-' ? '<stdin>' : file]), io);
135
+ const loaded = loadInputs(files.map((file) => [readSource(file, io), file === '-' ? '<stdin>' : file]), io, { base });
136
+ const program = loaded.program;
137
+ if (printProgram) {
138
+ stdout(loaded.text);
139
+ return 0;
140
+ }
141
+ // A compiled program has the larger bounds, unless they are given.
142
+ if (loaded.kind !== 'js') for (const [name, value] of Object.entries(COMPILED_LIMITS)) options[name] ??= value;
113
143
  if (proofFile !== null) {
114
144
  const document = readSource(proofFile, io);
115
145
  const report = checkProof(program, document, { goals, allowTrusted: !strictProof });
@@ -130,7 +160,9 @@ export function main(argv, io) {
130
160
  if (stats) stderr(`${JSON.stringify(result.stats)}\n`);
131
161
  return report.valid ? result.haltCode || 0 : 2;
132
162
  }
133
- stdout(result.stdout);
163
+ // Answers to goals are eyemind terms unless an output format is asked.
164
+ const written = options.proof ? null : writeConclusions(loaded, result, { format: format ?? (goals.length ? 'eyemind' : defaultFormat(loaded.kind)), all });
165
+ stdout(written ?? result.stdout);
134
166
  if (stats) stderr(`${JSON.stringify(result.stats)}\n`);
135
167
  return result.haltCode || 0;
136
168
  } catch (error) {
package/src/formats.js ADDED
@@ -0,0 +1,149 @@
1
+ // The inputs of a run in other formats than JavaScript, and its output as
2
+ // RDF or N3.
3
+ //
4
+ // A file's extension says what it holds:
5
+ //
6
+ // .js and standard input an eyemind program
7
+ // .ttl .trig .nt .nq RDF 1.2 data: with a program, rdf(S, P, O, G)
8
+ // facts; with an N3 document, its triples; with a
9
+ // rule set, its base graph
10
+ // .n3 Notation3, compiled to an eyemind program
11
+ // .srl a SPARQL 1.2 RL rule set, compiled to one
12
+ //
13
+ // The compiled program is ordinary eyemind: proofs, checking and --unused
14
+ // apply to it, and compiling is deterministic, so a saved proof checks later
15
+ // against the same inputs.
16
+ import { EyemindError, Struct } from './terms.js';
17
+ import { loadSources } from './lang.js';
18
+ import { readTerms } from './reader.js';
19
+ import { DEFAULT_GRAPH, parseRdf, rdfDocument, rdfFormat, writeRdf } from './rdf.js';
20
+ import { answersToN3, compileSources } from './n3.js';
21
+ import { compileSrl, srlQuads } from './srl.js';
22
+ import { write } from './writer.js';
23
+
24
+ export const OUTPUT_FORMATS = ['eyemind', 'turtle', 'trig', 'n-triples', 'n-quads', 'n3'];
25
+
26
+ // What a file holds: 'js', 'rdf', 'n3' or 'srl'.
27
+ export function inputKind(name) {
28
+ if (rdfFormat(name)) return 'rdf';
29
+ if (/\.n3$/i.test(name)) return 'n3';
30
+ if (/\.srl$/i.test(name)) return 'srl';
31
+ return 'js';
32
+ }
33
+
34
+ // Load inputs, given as [text, name] pairs, as one program. io may supply
35
+ // readFile, for the documents N3 and IMPORTS name, and fileIri(name), the
36
+ // base IRI of a file. Returns { kind, program, text, prefixes, compiled }:
37
+ // kind is 'js', 'n3' or 'srl', text the compiled program for N3 and SRL,
38
+ // and compiled what writing the conclusions needs.
39
+ export function loadInputs(inputs, io = null, options = {}) {
40
+ try {
41
+ return load(inputs, io, options);
42
+ } catch (error) {
43
+ // The N3 and SPARQL 1.2 RL readers report errors of their own kinds.
44
+ if (error instanceof EyemindError || !(error instanceof Error) || error instanceof TypeError || error instanceof ReferenceError) throw error;
45
+ throw new EyemindError(error.message);
46
+ }
47
+ }
48
+
49
+ function load(inputs, io, { base = null }) {
50
+ const kinds = inputs.map(([, name]) => inputKind(name));
51
+ const baseOf = (name) => base ?? io?.fileIri?.(name) ?? null;
52
+ const rdf = (text, name, k) => parseRdf(text, { format: rdfFormat(name), base: baseOf(name), scope: scopeOf(inputs, name, k) });
53
+ if (kinds.includes('srl')) {
54
+ const others = kinds.filter((k) => k !== 'srl' && k !== 'rdf');
55
+ if (kinds.filter((k) => k === 'srl').length > 1 || others.length) {
56
+ throw new EyemindError('a SPARQL 1.2 RL run takes one .srl rule set, and RDF data for its base graph');
57
+ }
58
+ const [text, name] = inputs[kinds.indexOf('srl')];
59
+ const data = inputs.flatMap(([t, n], k) => (kinds[k] === 'rdf' ? rdf(t, n, k).quads : []));
60
+ const compiled = compileSrl(text, { base: baseOf(name), filename: name, resolve: importResolver(io), data });
61
+ for (const warning of compiled.warnings) io?.stderr?.(`eyemind: warning: ${warning}\n`);
62
+ return { kind: 'srl', program: loadSources([[compiled.program, name]], io), text: compiled.program, prefixes: compiled.prefixes, compiled };
63
+ }
64
+ if (kinds.includes('n3')) {
65
+ if (kinds.includes('js')) throw new EyemindError('an N3 run takes .n3 documents and RDF data, not JavaScript programs');
66
+ const sources = inputs.map(([t, n], k) => (kinds[k] === 'rdf' ? rdf(t, n, k) : [t, n]));
67
+ const compiled = compileSources(sources, { base: base ?? '', baseOf: (n) => baseOf(n) ?? '', readFile: io?.readFile ?? null, readDocument: io?.readDocument ?? null,
68
+ source: inputs.map(([, n]) => n).join(', ') });
69
+ return { kind: 'n3', program: loadSources([[compiled.program, inputs[kinds.indexOf('n3')][1]]], io), text: compiled.program, prefixes: compiled.doc.prefixes, compiled };
70
+ }
71
+ // RDF data joins a program as rdf/4 facts, read without running anything.
72
+ const prefixes = {};
73
+ const sources = inputs.map(([t, n], k) => {
74
+ if (kinds[k] !== 'rdf') return [t, n];
75
+ const parsed = rdf(t, n, k);
76
+ Object.assign(prefixes, parsed.prefixes);
77
+ return [`facts_from({ text: ${JSON.stringify(rdfDocument(parsed.quads))} })\n`, n];
78
+ });
79
+ const text = sources.map(([t]) => t).join('\n');
80
+ return { kind: 'js', program: loadSources(sources, io), text, prefixes, compiled: null };
81
+ }
82
+
83
+ // A blank-node scope per data file: its name, numbered when names repeat.
84
+ function scopeOf(inputs, name, k) {
85
+ const base = String(name).replace(/^.*[\\/]/, '');
86
+ const same = inputs.filter(([, n]) => String(n).replace(/^.*[\\/]/, '') === base);
87
+ return same.length > 1 ? `${base}#${inputs.slice(0, k).filter(([, n]) => String(n).replace(/^.*[\\/]/, '') === base).length + 1}` : base;
88
+ }
89
+
90
+ // IMPORTS of local files, read by the host.
91
+ function importResolver(io) {
92
+ if (!io?.readFile) return null;
93
+ return (target) => {
94
+ if (!target.startsWith('file:')) return null;
95
+ try {
96
+ return io.readFile(decodeURIComponent(new URL(target).pathname));
97
+ } catch {
98
+ return null;
99
+ }
100
+ };
101
+ }
102
+
103
+ // The default output format of a run: N3 for N3, Turtle for SRL, and
104
+ // eyemind's own text for a program.
105
+ export const defaultFormat = (kind) => ({ n3: 'n3', srl: 'turtle' })[kind] ?? 'eyemind';
106
+
107
+ // The conclusions of a run in an output format; null for eyemind's own text.
108
+ // all also writes the given data. Throws when a conclusion is no triple.
109
+ export function writeConclusions(loaded, result, { format, all = false } = {}) {
110
+ if (format === 'eyemind') return null;
111
+ const answers = result.answers;
112
+ if (format === 'n3') {
113
+ if (loaded.kind !== 'n3') throw new EyemindError('--to n3 writes the conclusions of an N3 run');
114
+ return answersToN3(loaded.compiled.doc, answers, { mode: all ? 'all' : 'new' }).n3;
115
+ }
116
+ let quads;
117
+ if (loaded.kind === 'srl') quads = srlQuads(loaded.text, answers, { all });
118
+ else quads = conclusionQuads(answers, all ? loaded.text : null);
119
+ return writeRdf(quads, { format, prefixes: loaded.kind === 'n3' ? Object.fromEntries(loaded.prefixes) : loaded.prefixes });
120
+ }
121
+
122
+ // Conclusions that are triples, rdf/3 or result/3, or quads, rdf/4 or
123
+ // result_rdf/4, as quads; given, the program's own rdf facts come first.
124
+ function conclusionQuads(answers, given) {
125
+ const quads = [];
126
+ const seen = new Set();
127
+ const add = (t) => {
128
+ const quad = t.args.length === 3 ? [...t.args, DEFAULT_GRAPH] : t.args;
129
+ const key = quad.map((x) => (x === DEFAULT_GRAPH ? x : write(x))).join(' ');
130
+ if (!seen.has(key)) {
131
+ seen.add(key);
132
+ quads.push(quad);
133
+ }
134
+ };
135
+ if (given) {
136
+ for (const match of given.matchAll(/^facts_from\(\{ text: (".*") \}\)$/gm)) {
137
+ for (const [t] of readTerms(JSON.parse(match[1]))) add(t);
138
+ }
139
+ }
140
+ for (const answer of answers) {
141
+ const [[t]] = readTerms(answer);
142
+ if (t === 'false') continue;
143
+ const triple = t instanceof Struct && ['rdf', 'result', 'inf'].includes(t.name) && t.args.length === 3;
144
+ const quad = t instanceof Struct && ['rdf', 'result_rdf'].includes(t.name) && t.args.length === 4;
145
+ if (!triple && !quad) throw new EyemindError(`${answer} is no triple; write rdf(S, P, O) or rdf(S, P, O, G) conclusions, or leave out --to`);
146
+ add(t);
147
+ }
148
+ return quads;
149
+ }