eyemind 0.5.18 → 0.5.20

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
@@ -200,9 +200,9 @@ A reified triple `<< s p o >>` and an annotation `{| ... |}` become their reifie
200
200
  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 default-graph data joins the N3 document as triples:
201
201
 
202
202
  ```sh
203
- eyemind examples/family.n3 # the derived triples as N3
204
- eyemind --program examples/family.n3 > /tmp/family.js # the compiled program, to inspect
205
- eyemind -c examples/family.n3 # a proof of it, checked
203
+ eyemind examples/family-n3.n3 # the derived triples as N3
204
+ eyemind --program examples/family-n3.n3 > /tmp/family.js # the compiled program, to inspect
205
+ eyemind -c examples/family-n3.n3 # a proof of it, checked
206
206
  ```
207
207
 
208
208
  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`, or `restricted` when the conclusion has blank nodes of its own, `<=` 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.
@@ -233,11 +233,11 @@ for a quoted universal, as rules stated as data quote their variables.
233
233
  `log:includes` never instantiates the universals of its subject. Matching in
234
234
  nested graph terms below the first level is by unification, so it depends on
235
235
  the order of their triples. See
236
- [universal instances](https://eyereasoner.github.io/eyemind/examples/deck/universal-instances),
237
- [a shared existential](https://eyereasoner.github.io/eyemind/examples/deck/shared-existential),
238
- [an existential rule](https://eyereasoner.github.io/eyemind/examples/deck/explicit-existential-rule),
239
- [quantifier scopes](https://eyereasoner.github.io/eyemind/examples/deck/quantifier-scopes) and
240
- [graph terms](https://eyereasoner.github.io/eyemind/examples/deck/graph-terms).
236
+ [universal instances](https://eyereasoner.github.io/eyemind/examples/deck/universal-instances-n3),
237
+ [a shared existential](https://eyereasoner.github.io/eyemind/examples/deck/shared-existential-n3),
238
+ [an existential rule](https://eyereasoner.github.io/eyemind/examples/deck/explicit-existential-rule-n3),
239
+ [quantifier scopes](https://eyereasoner.github.io/eyemind/examples/deck/quantifier-scopes-n3) and
240
+ [graph terms](https://eyereasoner.github.io/eyemind/examples/deck/graph-terms-n3).
241
241
 
242
242
  The Notation3 test suite case `static/success-literal-22.n3` expects the
243
243
  pattern `{ _:X :B :C }` to match `{ :A :B :C }`. eyemind's scorer checks
@@ -260,17 +260,17 @@ inside their formulas; `?g graph:content ?data` and
260
260
  `?data log:includes { ... }` inspect them. Contents with the same graph name
261
261
  from several RDF inputs are combined, while blank nodes keep their source
262
262
  scopes. Conclusions can attach further formulas to that name; the output
263
- writes these as N3 formulas. See the [named graph example](https://eyereasoner.github.io/eyemind/examples/deck/trig-named-graph).
263
+ writes these as N3 formulas. See the [named graph example](https://eyereasoner.github.io/eyemind/examples/deck/trig-named-graph-n3).
264
264
 
265
265
  Scoped calls can use formulas supplied by the document's stated lists, including RDF collections written with `rdf:first` and `rdf:rest`, and the named-graph formulas loaded from RDF. 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.
266
266
 
267
267
  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.
268
268
 
269
269
  Examples run directly from their N3 source in the playground and on the command line:
270
- [family queries](https://eyereasoner.github.io/eyemind/examples/deck/family),
271
- [scoped negation](https://eyereasoner.github.io/eyemind/examples/deck/scoped-negation),
272
- [invoice collection](https://eyereasoner.github.io/eyemind/examples/deck/invoice),
273
- [French cities](https://eyereasoner.github.io/eyemind/examples/deck/french-cities), and
270
+ [family queries](https://eyereasoner.github.io/eyemind/examples/deck/family-n3),
271
+ [scoped negation](https://eyereasoner.github.io/eyemind/examples/deck/scoped-negation-n3),
272
+ [invoice collection](https://eyereasoner.github.io/eyemind/examples/deck/invoice-n3),
273
+ [French cities](https://eyereasoner.github.io/eyemind/examples/deck/french-cities-n3), and
274
274
  [existential witnesses](https://eyereasoner.github.io/eyemind/examples/deck/witnesses-n3).
275
275
  Each deck shows the N3 result and what its saved proof establishes, including
276
276
  any remaining obligations.
@@ -287,9 +287,9 @@ to their message. Prefix and base changes apply to subsequent data.
287
287
  Whole-log replay gives N3 or JavaScript rules an ordered view of the messages:
288
288
 
289
289
  ```sh
290
- eyemind examples/message-boundaries.n3 examples/data/message-boundaries.trig
291
- eyemind --proof examples/message-boundaries.n3 examples/data/message-boundaries.trig
292
- eyemind --check-proof examples/proof/message-boundaries.n3 examples/message-boundaries.n3 examples/data/message-boundaries.trig
290
+ eyemind examples/message-boundaries-n3.n3 examples/data/message-boundaries-n3.trig
291
+ eyemind --proof examples/message-boundaries-n3.n3 examples/data/message-boundaries-n3.trig
292
+ eyemind --check-proof examples/proof/message-boundaries-n3.n3 examples/message-boundaries-n3.n3 examples/data/message-boundaries-n3.trig
293
293
  ```
294
294
 
295
295
  The replay vocabulary is `eymsg:`, with namespace
@@ -311,7 +311,7 @@ with `graph(...)` terms for payload formulas.
311
311
  For independent processing, run the rules once per message:
312
312
 
313
313
  ```sh
314
- eyemind --stream-messages examples/message-alerts.n3 examples/data/message-alerts.nt
314
+ eyemind --stream-messages examples/message-alerts-n3.n3 examples/data/message-alerts-n3.nt
315
315
  ```
316
316
 
317
317
  The Node command incrementally reads files, standard input (`-`) or HTTP(S)
@@ -324,9 +324,9 @@ the ordinary N3, RDF or term format selected for the run.
324
324
  The playground's **Independent RDF Messages** mode processes its loaded
325
325
  text with the same boundaries. Whole-log replay supports proofs;
326
326
  `--stream-messages` rejects proof, proof-checking, compiled-program and
327
- unused-clause modes. The [message-boundaries](https://eyereasoner.github.io/eyemind/examples/deck/message-boundaries),
328
- [message-alerts](https://eyereasoner.github.io/eyemind/examples/deck/message-alerts)
329
- and [message-provenance](https://eyereasoner.github.io/eyemind/examples/deck/message-provenance)
327
+ unused-clause modes. The [message-boundaries](https://eyereasoner.github.io/eyemind/examples/deck/message-boundaries-n3),
328
+ [message-alerts](https://eyereasoner.github.io/eyemind/examples/deck/message-alerts-n3)
329
+ and [message-provenance](https://eyereasoner.github.io/eyemind/examples/deck/message-provenance-n3)
330
330
  decks show the outputs and remaining proof obligations.
331
331
 
332
332
  Library hosts can import `RdfMessageReader` and `parseRdfMessages` from
@@ -358,7 +358,7 @@ use binary64 arithmetic: `0.1e0 + 0.2e0` is
358
358
  `"0.30000000000000004"^^xsd:double`. Floating-point overflow and division by
359
359
  zero follow IEEE-754, including `INF`, `-INF`, `NaN` and signed zero; decimal
360
360
  division by zero is an expression error. Mixed numeric expressions use
361
- SPARQL type promotion. The [exact decimals example](https://eyereasoner.github.io/eyemind/examples/deck/exact-decimals)
361
+ SPARQL type promotion. The [exact decimals example](https://eyereasoner.github.io/eyemind/examples/deck/exact-decimals-srl)
362
362
  shows both arithmetic models.
363
363
 
364
364
  `NOW()` returns one UTC `xsd:dateTime` throughout a rule set evaluation.
@@ -374,7 +374,7 @@ recorded context; it does not attest the wall-clock time or the randomness
374
374
  of the seed. Library calls to `compileSrl` and `reasonSrl` accept
375
375
  `context: { now, seed }`, with an ISO UTC timestamp including milliseconds
376
376
  and 64 lowercase hexadecimal seed digits, to reproduce an execution.
377
- The [execution identifiers example](https://eyereasoner.github.io/eyemind/examples/deck/execution-identifiers)
377
+ The [execution identifiers example](https://eyereasoner.github.io/eyemind/examples/deck/execution-identifiers-srl)
378
378
  has a fixed context in the example manifest for its saved artifacts;
379
379
  ordinary command-line and playground runs capture fresh values.
380
380
 
@@ -403,10 +403,10 @@ inference. JavaScript programs write `step(...)` records. N3 inputs write
403
403
  N3 proofs, and SRL inputs write SRL `DATA` proofs:
404
404
 
405
405
  ```sh
406
- eyemind --proof examples/socrates.n3 > /tmp/socrates-proof.n3
407
- eyemind --check-proof /tmp/socrates-proof.n3 examples/socrates.n3
408
- eyemind --proof examples/socrates.srl > /tmp/socrates-proof.srl
409
- eyemind --check-proof /tmp/socrates-proof.srl examples/socrates.srl
406
+ eyemind --proof examples/socrates-n3.n3 > /tmp/socrates-proof.n3
407
+ eyemind --check-proof /tmp/socrates-proof.n3 examples/socrates-n3.n3
408
+ eyemind --proof examples/socrates-srl.srl > /tmp/socrates-proof.srl
409
+ eyemind --check-proof /tmp/socrates-proof.srl examples/socrates-srl.srl
410
410
  ```
411
411
 
412
412
  Native proofs use `pe:`, `https://eyereasoner.github.io/pe#`, for the claims,
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.18
5
+ Version: eyemind 0.5.20
6
6
  ```
7
7
 
8
8
  This document specifies the syntax and meaning of eyemind programs and data
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "eyemind",
3
- "version": "0.5.18",
3
+ "version": "0.5.20",
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/engine.js CHANGED
@@ -773,7 +773,8 @@ export class Solver {
773
773
  this.windowGoals = body;
774
774
  this.chosen = new Array(body.length).fill(null);
775
775
  try {
776
- found.push(...this.scan(clause, head, body, names, env, prefix));
776
+ // One push each: a scan can find more firings than a call takes arguments.
777
+ for (const item of this.scan(clause, head, body, names, env, prefix)) found.push(item);
777
778
  } finally {
778
779
  this.window = this.windowGoals = this.chosen = null;
779
780
  }
@@ -1001,7 +1002,7 @@ export class Solver {
1001
1002
  continue;
1002
1003
  }
1003
1004
  if (conclusion === 'true') {
1004
- const claimId = this.program.inspectionEnabled ? variant(claim) : text(claim);
1005
+ const claimId = this.program.inspectionEnabled ? variant(claim) : this.factKey(claim);
1005
1006
  if (!this.reported.has(claimId)) this.reported.set(claimId, [claim, children, clause.id]);
1006
1007
  continue;
1007
1008
  }
package/src/formats.js CHANGED
@@ -19,7 +19,7 @@ import { loadSources } from './lang.js';
19
19
  import { readTerms } from './reader.js';
20
20
  import { DEFAULT_GRAPH, parseRdf, rdfDocument, rdfFormat, writeRdf } from './rdf.js';
21
21
  import { resultToN3, compileSources } from './n3.js';
22
- import { compileSrl, srlQuads } from './srl.js';
22
+ import { compileSrl, srlAnswers, srlQuads } from './srl.js';
23
23
  import { write } from './writer.js';
24
24
  import { isRdfMessageLog, parseRdfMessages } from './messages.js';
25
25
  import { writeNativeProof } from './native-proof.js';
@@ -77,7 +77,8 @@ function load(inputs, io, { base = null, messageInputs = null, srlContext = null
77
77
  });
78
78
  const compiled = compileSrl(text, { base: baseOf(name), filename: name, resolve: importResolver(io), data, context: srlContext });
79
79
  for (const warning of compiled.warnings) io?.stderr?.(`eyemind: warning: ${warning}\n`);
80
- return { kind: 'srl', program: loadSources([[compiled.program, name]], io), text: compiled.program, prefixes: compiled.prefixes, compiled };
80
+ return { kind: 'srl', program: compiled.nativeProgram ?? loadSources([[compiled.program, name]], io),
81
+ get text() { return compiled.program; }, prefixes: compiled.prefixes, compiled };
81
82
  }
82
83
  if (kinds.includes('n3')) {
83
84
  if (kinds.includes('js')) throw new EyemindError('an N3 run takes .n3 documents and RDF data, not JavaScript programs');
@@ -141,10 +142,9 @@ export function writeConclusions(loaded, result, { format, all = false, blankNod
141
142
  if (loaded.kind !== 'n3') throw new EyemindError('--to n3 writes the conclusions of an N3 run');
142
143
  return resultToN3(loaded.compiled.doc, result, { mode: all ? 'all' : 'new', blankNodePrefix }).n3;
143
144
  }
144
- const answers = result.answers;
145
145
  let quads;
146
- if (loaded.kind === 'srl') quads = srlQuads(loaded.text, answers, { all });
147
- else quads = conclusionQuads(answers, all ? loaded.text : null);
146
+ if (loaded.kind === 'srl') quads = srlQuads(loaded.compiled, srlAnswers(result), { all });
147
+ else quads = conclusionQuads(result.answers, all ? loaded.text : null);
148
148
  return writeRdf(quads, { format, prefixes: loaded.kind === 'n3' ? Object.fromEntries(loaded.prefixes) : loaded.prefixes, blankNodePrefix });
149
149
  }
150
150
 
package/src/lang.js CHANGED
@@ -739,6 +739,67 @@ export function loadSources(sources, io = null) {
739
739
  return builder.program();
740
740
  }
741
741
 
742
+ // The clauses of statements that are document terms, read and never run:
743
+ // fact, implies, implied_by and query, and facts_from({ text: ... }), given
744
+ // the program line text starts on. A compiler's generated program has only
745
+ // these; they state the clauses loadText states from the same text, without
746
+ // the cost of compiling and running a large program as JavaScript. Null for
747
+ // any other text, which the caller runs instead.
748
+ export function statementSources(text, first = 1) {
749
+ let terms;
750
+ try {
751
+ terms = readTerms(text);
752
+ } catch {
753
+ return null;
754
+ }
755
+ const builder = new Builder(() => null);
756
+ try {
757
+ for (const [statement, at] of terms) {
758
+ if (!(statement instanceof Struct)) return null;
759
+ const { name } = statement;
760
+ const line = at + first - 1;
761
+ // A program's _ is one name each clause numbers; a document numbers it.
762
+ const args = statement.args.map(unnumbered);
763
+ if (name === 'fact') {
764
+ for (const term of args) builder.add('fact', term, [], line);
765
+ } else if (name === 'implies' && args.length === 2) {
766
+ builder.add('forward', normalizeGoal(args[1]), [normalizeGoal(args[0])], line);
767
+ } else if (name === 'implied_by' && args.length === 2) {
768
+ builder.add('backward', args[0], [normalizeGoal(args[1])], line);
769
+ } else if (name === 'query') {
770
+ builder.add('query', TRUE_ATOM, args.map(normalizeGoal), line);
771
+ } else if (name === 'facts_from' && args.length === 1 && args[0] instanceof Struct && args[0].name === '.' &&
772
+ args[0].args[1] === EMPTY && args[0].args[0] instanceof Struct && args[0].args[0].name === '=' &&
773
+ args[0].args[0].args[0] === 'text' && typeof args[0].args[0].args[1] === 'string') {
774
+ for (const [term] of readTerms(args[0].args[0].args[1])) builder.add('fact', term, [], line, false);
775
+ } else {
776
+ return null;
777
+ }
778
+ }
779
+ return builder.sources;
780
+ } catch {
781
+ // Run as JavaScript, it reports the error with its line.
782
+ return null;
783
+ }
784
+ }
785
+
786
+ const ANONYMOUS = new Var('_');
787
+
788
+ function unnumbered(term) {
789
+ if (term instanceof Var) return term.name.startsWith('_#') ? ANONYMOUS : term;
790
+ if (!(term instanceof Struct)) return term;
791
+ let args = null;
792
+ for (let index = 0; index < term.args.length; index++) {
793
+ const arg = term.args[index];
794
+ const plain = arg instanceof Struct || arg instanceof Var ? unnumbered(arg) : arg;
795
+ if (plain !== arg) {
796
+ if (args === null) args = [...term.args];
797
+ args[index] = plain;
798
+ }
799
+ }
800
+ return args === null ? term : new Struct(term.name, args);
801
+ }
802
+
742
803
  // A Program from a function that states clauses when called: a function of a
743
804
  // program, which states them with the names the program uses, or one of
744
805
  // library code, which is handed those names.
package/src/n3.js CHANGED
@@ -1027,7 +1027,7 @@ export function readSources(sources, { base = '', baseOf = () => '' } = {}) {
1027
1027
  if (!Array.isArray(sources[k]) && triple.p.v === GRAPH_CONTENT && triple.o.t === 'graph') {
1028
1028
  const key = `${triple.s.t}:${triple.s.v}`;
1029
1029
  if (graphs.has(key)) {
1030
- graphs.get(key).triples.push(...triple.o.triples);
1030
+ for (const item of triple.o.triples) graphs.get(key).triples.push(item);
1031
1031
  continue;
1032
1032
  }
1033
1033
  graphs.set(key, triple.o);
package/src/rdf.js CHANGED
@@ -359,9 +359,11 @@ export function writeRdf(quads, { format = 'turtle', prefixes = {}, blankNodePre
359
359
  graphs.get(key)[1].push(q);
360
360
  }
361
361
  for (const [key, [g, qs]] of graphs) {
362
- const lines = qs.map(([s, p, o]) => `${w.term(s)} ${w.predicate(p)} ${w.term(o)} .`);
363
- if (key === DEFAULT_GRAPH) body.push(...lines);
364
- else body.push(`${w.term(g)} {`, ...lines.map((l) => ` ${l}`), '}');
362
+ // One push per line: a graph can have more lines than a call takes arguments.
363
+ const indent = key === DEFAULT_GRAPH ? '' : ' ';
364
+ if (indent) body.push(`${w.term(g)} {`);
365
+ for (const [s, p, o] of qs) body.push(`${indent}${w.term(s)} ${w.predicate(p)} ${w.term(o)} .`);
366
+ if (indent) body.push('}');
365
367
  }
366
368
  const head = [...w.used].sort().map((name) => `PREFIX ${name}: <${w.prefixes.get(name)}>`);
367
369
  if (head.length && body.length) head.push('');
@@ -269,7 +269,7 @@ function stratificationLayers(ruleCount, components, componentOf, edges) {
269
269
  }
270
270
  }
271
271
  }
272
- const max = Math.max(0, ...levels);
272
+ const max = levels.reduce((a, b) => Math.max(a, b), 0); // eyemind: more levels than a call takes as arguments
273
273
  const layers = Array.from({ length: max + 1 }, () => []);
274
274
  levels.forEach((level, index) => layers[level].push(index));
275
275
  return layers;
package/src/srl.js CHANGED
@@ -36,10 +36,11 @@ import { BUILTIN_SIGNATURES, canonicalBuiltinName } from './srl-builtin-names.js
36
36
  import { libraryText } from './srl-functions.js';
37
37
  import { Parser } from './srl-parser.js';
38
38
  import { run } from './engine.js';
39
- import { loadText } from './lang.js';
39
+ import { loadText, statementSources } from './lang.js';
40
+ import { Program, Source } from './program.js';
40
41
  import { DEFAULT_GRAPH } from './rdf.js';
41
42
  import { readTerms } from './reader.js';
42
- import { Struct } from './terms.js';
43
+ import { Struct, Var, conjunction, identity, isGround } from './terms.js';
43
44
  import { readProofTerms } from './native-proof.js';
44
45
  import { write } from './writer.js';
45
46
 
@@ -79,12 +80,12 @@ function withImports(program, { filename, resolve, seen }) {
79
80
  const imported = withImports(new Parser(String(source), { baseIRI: target, filename: target, strictGrammar: true }).parseProgram(),
80
81
  { filename: target, resolve, seen });
81
82
  Object.assign(merged.prefixes, imported.prefixes);
82
- merged.data.push(...imported.data);
83
- merged.rules.push(...imported.rules);
83
+ merged.data = merged.data.concat(imported.data);
84
+ merged.rules = merged.rules.concat(imported.rules);
84
85
  }
85
86
  Object.assign(merged.prefixes, program.prefixes);
86
- merged.data.push(...program.data);
87
- merged.rules.push(...program.rules);
87
+ merged.data = merged.data.concat(program.data);
88
+ merged.rules = merged.rules.concat(program.rules);
88
89
  return merged;
89
90
  }
90
91
 
@@ -100,40 +101,90 @@ const RESERVED = new Set(['Math', 'JSON', 'BigInt', 'Infinity', 'NaN', 'undefine
100
101
  // Compile a rule set's text. Options: base (IRI), filename, resolve (for
101
102
  // IMPORTS, see readRuleSet), data (the base graph, as RDF quads from
102
103
  // parseRdf, in its default graph), context (a recorded execution's now and
103
- // seed). Returns { program, prefixes, warnings, context }.
104
+ // seed). Returns { program, nativeProgram, prefixes, warnings, context,
105
+ // data, given }; see compileRuleSet.
104
106
  export function compileSrl(text, { base = null, filename = '<input>', resolve = null, data = [], context = null } = {}) {
105
107
  const ruleSet = readRuleSet(text, { base, filename, resolve });
106
108
  return compileRuleSet(ruleSet, { data, source: filename, context });
107
109
  }
108
110
 
109
- // Compile a parsed rule set over a base graph of RDF quads.
111
+ // Compile a parsed rule set over a base graph of RDF quads. program is the
112
+ // compiled JavaScript text, written when first asked for; nativeProgram the
113
+ // Program it states, made without generating and running that text: data,
114
+ // DATA blocks and rules of triple patterns become clauses directly, and the
115
+ // text of other rules and of the function library is read as statements.
116
+ // data is the base graph and given the DATA triples, as inf/3 terms.
110
117
  export function compileRuleSet(ruleSet, { data = [], source = '<input>', context = null } = {}) {
111
118
  const needed = new Set();
112
119
  const warnings = [];
113
- const lines = [
120
+ // Each part is a line of the text, or clauses made directly, which can
121
+ // also write their line: { text(), sources(line) }.
122
+ const parts = [
114
123
  `// Generated by eyemind from ${String(source).replace(/[\r\n]/g, ' ')}, a SPARQL 1.2 RL rule set.`,
115
124
  '// Each RDF triple is rdf(Subject, Predicate, Object); base(S, P, O) is the',
116
125
  '// base graph and inf(S, P, O) the inference graph, the conclusions.',
117
126
  ];
118
127
  if (data.some((q) => q[3] !== DEFAULT_GRAPH)) throw new SrlError('the base graph is one graph; give the data as Turtle or N-Triples');
119
128
  if (data.length) {
120
- // Through facts_from, as document text, so integers of any size are exact.
121
- const document = data.flatMap(([S, P, O]) => [write(new Struct('rdf', [S, P, O])), write(new Struct('base', [S, P, O]))]);
122
- lines.push(`facts_from({ text: ${JSON.stringify(document.join('\n'))} })`);
129
+ parts.push({
130
+ // Through facts_from, as document text, so integers of any size are exact.
131
+ text: () => `facts_from({ text: ${JSON.stringify(data.flatMap(([S, P, O]) =>
132
+ [write(new Struct('rdf', [S, P, O])), write(new Struct('base', [S, P, O]))]).join('\n'))} })`,
133
+ sources: (line) => data.flatMap(([S, P, O]) =>
134
+ [new Source('fact', new Struct('rdf', [S, P, O]), [], line), new Source('fact', new Struct('base', [S, P, O]), [], line)]),
135
+ });
123
136
  }
124
137
  const terms = new Terms('srl');
125
- for (const t of ruleSet.data) lines.push(`fact(${terms.rdf(t, 'rdf')}, ${terms.rdf(t, 'inf')})`);
138
+ const native = new NativeTerms('srl');
139
+ const given = ruleSet.data.map((t) => native.rdf(t, 'inf'));
140
+ ruleSet.data.forEach((t, k) => parts.push({
141
+ text: () => `fact(${terms.rdf(t, 'rdf')}, ${terms.rdf(t, 'inf')})`,
142
+ sources: (line) => [new Source('fact', native.rdf(t, 'rdf'), [], line), new Source('fact', given[k], [], line)],
143
+ }));
126
144
  ruleSet.rules.forEach((rule, index) => {
127
- lines.push(...new RuleCompiler(rule, index + 1, { needed, warnings }).compile());
145
+ const compiler = new RuleCompiler(rule, index + 1, { needed, warnings });
146
+ const clause = compiler.plain(native);
147
+ if (clause === null) {
148
+ for (const line of compiler.compile()) parts.push(line);
149
+ } else {
150
+ parts.push({
151
+ text: () => new RuleCompiler(rule, index + 1, { needed: new Set(), warnings: [] }).compile()[0],
152
+ sources: (line) => [new Source('forward', clause[0], clause[1], line)],
153
+ });
154
+ }
128
155
  });
129
156
  if (needed.has('srl_now') || needed.has('srl_uuid')) {
130
157
  context = executionContext(context);
131
- lines.push(`fact(srl_execution(${q(context.now)}, ${q(context.seed)}))`);
158
+ parts.push(`fact(srl_execution(${q(context.now)}, ${q(context.seed)}))`);
132
159
  }
133
- lines.push('query(inf(S, P, O))');
160
+ parts.push('query(inf(S, P, O))');
134
161
  const library = libraryText(needed);
135
- if (library) lines.push('', '// SPARQL functions and aggregates.', library);
136
- return { program: `${lines.join('\n')}\n`, prefixes: ruleSet.prefixes, warnings, context };
162
+ if (library) parts.push('', '// SPARQL functions and aggregates.', library);
163
+ let program = null;
164
+ return {
165
+ get program() { return program ??= `${parts.map((part) => (typeof part === 'string' ? part : part.text())).join('\n')}\n`; },
166
+ nativeProgram: nativeProgram(parts),
167
+ prefixes: ruleSet.prefixes, warnings, context, data, given,
168
+ };
169
+ }
170
+
171
+ // The Program of a compiled rule set's parts, each on the line its text
172
+ // would start on; null when a part's text is not plain statements.
173
+ function nativeProgram(parts) {
174
+ const sources = [];
175
+ let line = 1;
176
+ for (const part of parts) {
177
+ if (typeof part === 'string') {
178
+ const stated = part === '' || part.startsWith('// ') && !part.includes('\n') ? [] : statementSources(part, line);
179
+ if (stated === null) return null;
180
+ for (const item of stated) sources.push(item);
181
+ line += part.split('\n').length;
182
+ } else {
183
+ for (const item of part.sources(line)) sources.push(item);
184
+ line++;
185
+ }
186
+ }
187
+ return new Program(sources);
137
188
  }
138
189
 
139
190
  // Clock and entropy are inputs captured once when the rule set is compiled.
@@ -192,6 +243,35 @@ class Terms {
192
243
  }
193
244
  }
194
245
 
246
+ // The same RDF terms, made directly: what the text of Terms reads as.
247
+ class NativeTerms {
248
+ constructor(scope) {
249
+ this.scope = scope;
250
+ }
251
+
252
+ term(t) {
253
+ switch (t.type) {
254
+ case 'iri': return new Struct('iri', [t.value]);
255
+ case 'blank': return new Struct('bnode', [this.scope, t.value]);
256
+ case 'literal': return literalTerm(t);
257
+ case 'triple': return new Struct('triple', [this.term(t.s), this.term(t.p), this.term(t.o)]);
258
+ default: throw new SrlError(`a ${t.type} cannot appear in data`);
259
+ }
260
+ }
261
+
262
+ rdf(t, name) {
263
+ return new Struct(name, [this.term(t.s), this.term(t.p), this.term(t.o)]);
264
+ }
265
+ }
266
+
267
+ function literalTerm(t) {
268
+ if (t.lang) return new Struct('literal', [String(t.value), new Struct('lang', t.langDir ? [t.lang, t.langDir] : [t.lang])]);
269
+ const datatype = t.datatype || `${XSD}string`;
270
+ const lexical = t.lexical ?? String(t.value);
271
+ if (datatype === `${XSD}integer` && /^(?:0|-?[1-9][0-9]*)$/.test(lexical)) return BigInt(lexical);
272
+ return new Struct('literal', [lexical, new Struct('datatype', [datatype])]);
273
+ }
274
+
195
275
  // A literal: an xsd:integer with a canonical lexical form is an integer,
196
276
  // any other literal keeps its lexical form and datatype or language tag.
197
277
  function literalText(t) {
@@ -260,6 +340,41 @@ class RuleCompiler {
260
340
  return [...this.helpers, ...out];
261
341
  }
262
342
 
343
+ // A rule of triple patterns whose head has no blank node and only
344
+ // predicates that are IRIs is one clause, made directly with terms: the
345
+ // conclusion and body of the statement compile() writes. Null for another
346
+ // rule.
347
+ plain(terms) {
348
+ const { rule } = this;
349
+ if (rule.head.length === 0 || !rule.body.every((c) => c.type === 'triple')) return null;
350
+ const predicates = new Set(rule.body.filter((c) => c.triple.p.type === 'var').map((c) => c.triple.p.value));
351
+ if (rule.head.some((t) => (t.p.type === 'var' && !predicates.has(t.p.value)) || hasBlank(t))) return null;
352
+ const scope = new Scope(this, null, rule.groundData ? 'base' : 'rdf');
353
+ const vars = new Map();
354
+ // Names in the order compile() gives them: body terms bind, head terms do not.
355
+ const term = (t, binds) => {
356
+ if (t.type === 'var') {
357
+ if (binds) scope.bind(t.value);
358
+ const name = scope.name(t.value);
359
+ let v = vars.get(name);
360
+ if (v === undefined) vars.set(name, v = new Var(name));
361
+ return v;
362
+ }
363
+ if (t.type === 'triple') return new Struct('triple', [term(t.s, binds), term(t.p, binds), term(t.o, binds)]);
364
+ return terms.term(t);
365
+ };
366
+ try {
367
+ const body = rule.body.map(({ triple: t }) => new Struct(scope.graph, [term(t.s, true), term(t.p, true), term(t.o, true)]));
368
+ const heads = rule.head.flatMap((t) => {
369
+ const args = [term(t.s, false), term(t.p, false), term(t.o, false)];
370
+ return [new Struct('rdf', args), new Struct('inf', [...args])];
371
+ });
372
+ return [conjunction(heads), body.length ? [conjunction(body)] : ['true']];
373
+ } catch {
374
+ return null; // compile() reports it
375
+ }
376
+ }
377
+
263
378
  fresh(hint) {
264
379
  let base = hint.replace(/[^A-Za-z0-9_]/g, '_');
265
380
  if (/^[a-z]/.test(base)) base = base[0].toUpperCase() + base.slice(1);
@@ -642,6 +757,11 @@ class Scope {
642
757
  }
643
758
  }
644
759
 
760
+ function hasBlank(t) {
761
+ if (t.type === 'blank') return true;
762
+ return (t.type === 'triple' || t.s !== undefined) && [t.s, t.p, t.o].some(hasBlank);
763
+ }
764
+
645
765
  function collectClauseVars(clauses, out) {
646
766
  const term = (t) => {
647
767
  if (!t) return;
@@ -675,32 +795,43 @@ export const SRL_LIMITS = { maxDepth: 1000000, maxIterations: 100000, maxInferen
675
795
  // inference graph's, and with proof, result.proof is eyemind's checked
676
796
  // proof of the compiled program.
677
797
  export function reasonSrl(text, { base = null, filename = '<input>', resolve = null, data = [], all = false, limits = {}, proof = false, context = null } = {}) {
678
- const { program, prefixes, warnings, context: execution } = compileSrl(text, { base, filename, resolve, data, context });
679
- const result = run(loadText(program, 'compiled.js'), { ...SRL_LIMITS, ...limits, proof });
680
- return { quads: srlQuads(program, result.answers, { all }), program, prefixes, warnings, result, context: execution };
798
+ const compiled = compileSrl(text, { base, filename, resolve, data, context });
799
+ const result = run(compiled.nativeProgram ?? loadText(compiled.program, 'compiled.js'), { ...SRL_LIMITS, ...limits, proof });
800
+ const { prefixes, warnings, context: execution } = compiled;
801
+ return { quads: srlQuads(compiled, srlAnswers(result), { all }), get program() { return compiled.program; }, prefixes, warnings, result, context: execution };
681
802
  }
682
803
 
804
+ // A run's answers as terms when they are ground, as forward conclusions
805
+ // over RDF are; otherwise as text, which names their variables.
806
+ export const srlAnswers = (result) => (result.conclusions?.every((term) => isGround(term)) ? result.conclusions : result.answers);
807
+
683
808
  // The inference graph of a run's answers, as quads in the default graph:
684
- // the rule set's DATA triples, then the derived ones. With all, the base
685
- // graph the compiled program states comes first.
809
+ // the rule set's DATA triples, then the derived ones. program is a compiled
810
+ // rule set or its text, answers are terms or their text. With all, the base
811
+ // graph comes first.
686
812
  export function srlQuads(program, answers, { all = false } = {}) {
687
813
  const seen = new Set();
688
814
  const out = [];
689
815
  const add = (terms, name) => {
690
816
  for (const t of terms) {
691
817
  if (!(t instanceof Struct) || t.name !== name || t.args.length !== 3) continue;
692
- const key = write(new Struct('t', t.args));
818
+ const key = identity(new Struct('t', t.args));
693
819
  if (seen.has(key)) continue;
694
820
  seen.add(key);
695
821
  out.push([...t.args, DEFAULT_GRAPH]);
696
822
  }
697
823
  };
698
- const lines = program.split('\n');
699
- if (all) {
700
- const line = lines.find((l) => l.startsWith('facts_from({ text: '));
701
- if (line) add(readTerms(JSON.parse(line.slice('facts_from({ text: '.length, -' })'.length))).map(([t]) => t), 'base');
824
+ if (typeof program !== 'string') {
825
+ if (all) add(program.data.map(([S, P, O]) => new Struct('base', [S, P, O])), 'base');
826
+ add(program.given, 'inf');
827
+ } else {
828
+ const lines = program.split('\n');
829
+ if (all) {
830
+ const line = lines.find((l) => l.startsWith('facts_from({ text: '));
831
+ if (line) add(readTerms(JSON.parse(line.slice('facts_from({ text: '.length, -' })'.length))).map(([t]) => t), 'base');
832
+ }
833
+ add(readTerms(lines.filter((l) => l.startsWith('fact(rdf(') && l.includes(', inf(')).join('\n')).map(([t]) => t.args[1]), 'inf');
702
834
  }
703
- add(readTerms(lines.filter((l) => l.startsWith('fact(rdf(') && l.includes(', inf(')).join('\n')).map(([t]) => t.args[1]), 'inf');
704
- add(answers.map((a) => readTerms(a)[0][0]), 'inf');
835
+ add(answers.map((a) => (typeof a === 'string' ? readTerms(a)[0][0] : a)), 'inf');
705
836
  return out;
706
837
  }
package/src/version.js CHANGED
@@ -1,2 +1,2 @@
1
1
  // The release this checkout is; ./release keeps it in step with package.json.
2
- export const VERSION = '0.5.18';
2
+ export const VERSION = '0.5.20';