eyemind 0.5.17 → 0.5.18

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
@@ -565,7 +565,7 @@ console.log(result.bindings);
565
565
  console.log(checkProof(socrates, result.proof, { goals }).valid);
566
566
  ```
567
567
 
568
- `run()` returns `answers`, `bindings`, `inferred`, `stdout`, `proof`, `proofReport`, `stats` and `haltCode`, and takes `goal`, `goals`, `proof`, `maxDepth`, `maxIterations` and `maxInferences`; exceeding a bound throws an `EyemindError`. `loadSources([[text, filename], ...], io)` loads several sources as one program; pass `nodeIO` from `eyemind/node` as `io` to let `facts_from(path)` read files. `checkProof(program, document, { goals, allowTrusted })` checks C1–C10, and `allowTrusted: false` rejects every obligation. `checkReport`, `readTerm`, `readTerms` and `write` format reports and read and write the canonical text.
568
+ `run()` returns `conclusions`, `answers`, `bindings`, `inferred`, `stdout`, `proof`, `proofReport`, `stats` and `haltCode`, and takes `goal`, `goals`, `proof`, `maxDepth`, `maxIterations` and `maxInferences`; exceeding a bound throws an `EyemindError`. `conclusions` holds the answer terms; `answers`, `bindings` and `stdout` are rendered when first read. Ground N3 conclusions are written directly from their terms. `loadSources([[text, filename], ...], io)` loads several sources as one program; pass `nodeIO` from `eyemind/node` as `io` to let `facts_from(path)` read files. `checkProof(program, document, { goals, allowTrusted })` checks C1–C10, and `allowTrusted: false` rejects every obligation. `checkReport`, `readTerm`, `readTerms` and `write` format reports and read and write the canonical text.
569
569
 
570
570
  The core library's `result.proof` is the JavaScript certificate.
571
571
  `writeNativeProof(result.proof, { format: 'n3', prefixes })` writes its N3
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.17
5
+ Version: eyemind 0.5.18
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.17",
3
+ "version": "0.5.18",
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
@@ -285,6 +285,10 @@ export class Solver {
285
285
  // of the facts with that value there.
286
286
  this.factIndex = new Map();
287
287
  this.factKeys = new Set(program.groundFactKeys);
288
+ this.iriIds = new Map();
289
+ for (const clause of program.clauses) {
290
+ if (!clause.forward && !clause.body.length && isGround(clause.head)) this.factKeys.add(this.factKey(clause.head));
291
+ }
288
292
  this.genericKeys = new Set();
289
293
  this.genericPredicates = new Set();
290
294
  this.derived = [];
@@ -301,6 +305,7 @@ export class Solver {
301
305
  this.chosen = null;
302
306
  this.snapshots = new Map();
303
307
  this.direct = new Map();
308
+ this.groundCalls = new Map();
304
309
  this.rules = new Map();
305
310
  this.ruleKeys = new Map();
306
311
  this.maxInferences = options.maxInferences || 1000000;
@@ -548,13 +553,28 @@ export class Solver {
548
553
  const argument = indexKey(arg);
549
554
  if (argument !== undefined) {
550
555
  const bucket = positions[position].get(argument);
551
- if (bucket === undefined) positions[position].set(argument, [number]);
556
+ if (bucket === undefined) positions[position].set(argument, number);
557
+ else if (typeof bucket === 'number') positions[position].set(argument, [bucket, number]);
552
558
  else bucket.push(number);
553
559
  }
554
560
  });
555
561
  }
556
562
  }
557
563
 
564
+ // RDF rules often derive only IRI tuples. Small per-run identifiers avoid
565
+ // retaining a second copy of every IRI in each fact's duplicate key.
566
+ factKey(term) {
567
+ if (!(term instanceof Struct) || !term.args.length ||
568
+ !term.args.every((arg) => isTerm(arg, 'iri', 1) && typeof arg.args[0] === 'string')) return identity(term);
569
+ const ids = term.args.map((arg) => {
570
+ const iri = arg.args[0];
571
+ let id = this.iriIds.get(iri);
572
+ if (id === undefined) this.iriIds.set(iri, id = this.iriIds.size);
573
+ return id;
574
+ });
575
+ return `@${term.name.length}:${term.name}:${ids.length}:${ids.join(',')}`;
576
+ }
577
+
558
578
  // The indexes of the derived facts a goal could match, in order, when an
559
579
  // argument of the goal narrows them down; null to try them all.
560
580
  factOrder(goal, env, goalKey) {
@@ -566,7 +586,8 @@ export class Solver {
566
586
  for (let position = 0; position < goal.args.length; position++) {
567
587
  const arg = indexKey(goal.args[position], env);
568
588
  if (arg !== undefined) {
569
- const bucket = positions[position].get(arg) || NO_NODES;
589
+ const stored = positions[position].get(arg);
590
+ const bucket = typeof stored === 'number' ? [stored] : stored ?? NO_NODES;
570
591
  if (bucket.length < size) {
571
592
  best = bucket;
572
593
  size = bucket.length;
@@ -718,8 +739,7 @@ export class Solver {
718
739
  let now = null;
719
740
  let previous = null;
720
741
  if (keys !== null) {
721
- now = new Map();
722
- for (const goalKey of keys) if (goalKey) now.set(goalKey, (this.facts.get(goalKey) || NO_NODES).length);
742
+ now = keys.map((goalKey) => goalKey === null ? null : (this.facts.get(goalKey) || NO_NODES).length);
723
743
  previous = this.snapshots.get(clause) || null;
724
744
  this.snapshots.set(clause, now);
725
745
  }
@@ -727,13 +747,15 @@ export class Solver {
727
747
  if (previous !== null) {
728
748
  positions = [];
729
749
  keys.forEach((goalKey, i) => {
730
- if (goalKey && now.get(goalKey) > previous.get(goalKey)) positions.push(i);
750
+ if (goalKey && now[i] > previous[i]) positions.push(i);
731
751
  });
732
- if (!positions.some((i) => this.mayMatchNew(clause.localBody[i], keys[i], previous, now))) {
752
+ if (!positions.some((i) => this.mayMatchNew(clause.localBody[i], keys[i], previous[i], now[i]))) {
733
753
  return []; // nothing derived since its last search can be used, so nothing new follows
734
754
  }
735
755
  }
736
756
  this.serial++;
757
+ const direct = this.directFirings(clause, keys, previous);
758
+ if (direct !== null) return direct;
737
759
  const [head, fullBody, names] = freshClause(clause, this.serial, true);
738
760
  const body = fullBody.slice(clause.prefixLength);
739
761
  const env = new Env();
@@ -743,9 +765,9 @@ export class Solver {
743
765
  for (const delta of positions) {
744
766
  const window = keys.map((goalKey, i) => {
745
767
  if (goalKey === null) return null;
746
- if (i < delta) return [0, previous.get(goalKey), true];
747
- if (i === delta) return [previous.get(goalKey), now.get(goalKey), false];
748
- return [0, now.get(goalKey), true];
768
+ if (i < delta) return [0, previous[i], true];
769
+ if (i === delta) return [previous[i], now[i], false];
770
+ return [0, now[i], true];
749
771
  });
750
772
  this.window = window;
751
773
  this.windowGoals = body;
@@ -760,14 +782,56 @@ export class Solver {
760
782
  return found.map(([firing]) => firing);
761
783
  }
762
784
 
785
+ // A single ordinary call over ground facts needs only a substitution.
786
+ // Keep the search machine for proofs, templates, witnesses and nonground
787
+ // source facts; otherwise no renamed clause or choice-point frames escape.
788
+ directFirings(clause, keys, previous) {
789
+ if (this.recording || keys === null || keys.length !== 1 || keys[0] === null ||
790
+ clause.parentId !== null || clause.templates.length || clause.captures !== null || clause.witnessNames.length) return null;
791
+ const goalKey = keys[0];
792
+ let ground = this.groundCalls.get(goalKey);
793
+ if (ground === undefined) {
794
+ ground = (this.program.groups.get(goalKey) || []).every((candidate) => isGround(candidate.head));
795
+ this.groundCalls.set(goalKey, ground);
796
+ }
797
+ if (!ground) return null;
798
+ if (++this.stats.inferences > this.maxInferences) throw new EyemindError('reasoning exceeded max_inferences');
799
+ const goal = clause.localBody[0];
800
+ const facts = this.facts.get(goalKey) || NO_NODES;
801
+ const order = this.factOrder(goal, null, goalKey);
802
+ const start = previous === null ? 0 : previous[0];
803
+ const found = [];
804
+ const env = new Env();
805
+ const add = (fact) => {
806
+ if (unify(goal, fact, env)) {
807
+ const conclusions = flattenConjunction(copyResolved(clause.head, env));
808
+ const claim = conclusions.includes('true') ? copyResolved(goal, env) : null;
809
+ found.push([conclusions, NO_NODES, NO_NODES, claim, null]);
810
+ }
811
+ env.undo(0);
812
+ };
813
+ if (order === null) {
814
+ for (let i = start; i < facts.length; i++) add(facts[i].goal);
815
+ } else {
816
+ for (let i = bisectLeft(order, start); i < order.length; i++) add(facts[order[i]].goal);
817
+ }
818
+ if (previous === null) {
819
+ for (const candidate of this.program.candidates(goal, null, goalKey)) {
820
+ this.serial++;
821
+ add(candidate.head);
822
+ }
823
+ }
824
+ return found;
825
+ }
826
+
763
827
  // Whether a body goal, as the rule writes it, could match a fact derived
764
828
  // since the rule's last search. The goal's own atoms and numbers narrow the
765
829
  // facts down before the rule is renamed and searched.
766
830
  mayMatchNew(goal, goalKey, previous, now) {
767
831
  const order = this.factOrder(goal, null, goalKey);
768
832
  if (order === null) return true;
769
- const first = bisectLeft(order, previous.get(goalKey));
770
- return first < order.length && order[first] < now.get(goalKey);
833
+ const first = bisectLeft(order, previous);
834
+ return first < order.length && order[first] < now;
771
835
  }
772
836
 
773
837
  // The solutions of a rule's body. A restricted rule's guard is a negation
@@ -929,6 +993,7 @@ export class Solver {
929
993
  // bodies and their observable order.
930
994
  for (const [clause, [conclusions, children, bindings, claim, guard]] of firings) {
931
995
  if (guard) this.guards.push([clause, guard, conclusions]);
996
+ const by = new Struct('clause', [BigInt(clause.id)]);
932
997
  for (const [position, conclusion] of conclusions.entries()) {
933
998
  const template = clause.templates.find((item) => item.position === position);
934
999
  if (template) {
@@ -940,14 +1005,14 @@ export class Solver {
940
1005
  if (!this.reported.has(claimId)) this.reported.set(claimId, [claim, children, clause.id]);
941
1006
  continue;
942
1007
  }
943
- const node = new Node(conclusion, new Struct('clause', [BigInt(clause.id)]), bindings, children, null, true);
1008
+ const node = new Node(conclusion, by, bindings, children, null, true);
944
1009
  if (conclusion === 'false') {
945
1010
  this.derived.push(node);
946
1011
  this.haltCode = 65;
947
1012
  return 'halt';
948
1013
  }
949
1014
  node.generic = this.program.inspectionEnabled && !isGround(conclusion);
950
- const conclusionId = node.generic ? variant(conclusion) : identity(conclusion);
1015
+ const conclusionId = node.generic ? variant(conclusion) : this.factKey(conclusion);
951
1016
  const factKeys = node.generic ? this.genericKeys : this.factKeys;
952
1017
  if (factKeys.has(conclusionId)) continue;
953
1018
  factKeys.add(conclusionId);
@@ -1144,7 +1209,7 @@ class Missing extends Error {
1144
1209
  // of clauses only searches behind a trusted boundary could consult.
1145
1210
  export class Result {
1146
1211
  constructor(fields) {
1147
- Object.assign(this, fields);
1212
+ Object.defineProperties(this, Object.getOwnPropertyDescriptors(fields));
1148
1213
  }
1149
1214
 
1150
1215
  // The derived facts as text, written only when asked for.
@@ -1236,12 +1301,9 @@ function reason(program, goalInputs, options) {
1236
1301
  // Variables are named A, B, ... in the order the conclusions show them; the
1237
1302
  // bindings of each answer name them as its conclusion does.
1238
1303
  const lettering = new Lettering();
1239
- const answers = claims.map((claim) => write(claim, null, lettering));
1240
- const answerBindings = bindings.map((answer) => {
1241
- const out = {};
1242
- for (const [name, value] of answer) out[name] = write(value, null, lettering);
1243
- return out;
1244
- });
1304
+ let answers = null;
1305
+ let answerBindings = null;
1306
+ let stdout = null;
1245
1307
  const rendered = options.proof
1246
1308
  ? renderProof(program, claims, roots, true, heading, (boundaries) => {
1247
1309
  const ordinary = certify(solver, boundaries);
@@ -1271,12 +1333,22 @@ function reason(program, goalInputs, options) {
1271
1333
  behind = [...clausesBehindBoundaries(program, roots)].filter((id) => !used.has(id)).sort((a, b) => a - b);
1272
1334
  }
1273
1335
  return new Result({
1274
- answers,
1275
- bindings: answerBindings,
1336
+ conclusions: claims,
1337
+ // Native writers consume terms directly. Canonical text is made only
1338
+ // when asked for, with conclusions named before their bindings.
1339
+ get answers() { return answers ??= claims.map((claim) => write(claim, null, lettering)); },
1340
+ get bindings() {
1341
+ this.answers;
1342
+ return answerBindings ??= bindings.map((answer) => {
1343
+ const out = {};
1344
+ for (const [name, value] of answer) out[name] = write(value, null, lettering);
1345
+ return out;
1346
+ });
1347
+ },
1276
1348
  derived: solver.derived,
1277
1349
  clausesUsed: used !== null ? [...used].sort((a, b) => a - b) : null,
1278
1350
  clausesBehindBoundaries: behind,
1279
- stdout: document !== null ? document : [heading, ...answers].map((line) => `${line}\n`).join(''),
1351
+ get stdout() { return stdout ??= document ?? [heading, ...this.answers].map((line) => `${line}\n`).join(''); },
1280
1352
  proof: document,
1281
1353
  proofReport: report,
1282
1354
  stats: solver.stats,
package/src/formats.js CHANGED
@@ -18,7 +18,7 @@ import { EyemindError, Struct } from './terms.js';
18
18
  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
- import { answersToN3, compileSources } from './n3.js';
21
+ import { resultToN3, compileSources } from './n3.js';
22
22
  import { compileSrl, srlQuads } from './srl.js';
23
23
  import { write } from './writer.js';
24
24
  import { isRdfMessageLog, parseRdfMessages } from './messages.js';
@@ -83,8 +83,9 @@ function load(inputs, io, { base = null, messageInputs = null, srlContext = null
83
83
  if (kinds.includes('js')) throw new EyemindError('an N3 run takes .n3 documents and RDF data, not JavaScript programs');
84
84
  const sources = inputs.map(([t, n], k) => (kinds[k] === 'rdf' ? rdf(t, n, k) : [t, n]));
85
85
  const compiled = compileSources(sources, { base: base ?? '', baseOf: (n) => baseOf(n) ?? '', readFile: io?.readFile ?? null, readDocument: io?.readDocument ?? null,
86
- source: inputs.map(([, n]) => n).join(', ') });
87
- return { kind: 'n3', program: loadSources([[compiled.program, inputs[kinds.indexOf('n3')][1]]], io), text: compiled.program, prefixes: compiled.doc.prefixes, compiled };
86
+ source: inputs.map(([, n]) => n).join(', '), native: true });
87
+ return { kind: 'n3', program: compiled.nativeProgram ?? loadSources([[compiled.program, inputs[kinds.indexOf('n3')][1]]], io),
88
+ get text() { return compiled.program; }, prefixes: compiled.doc.prefixes, compiled };
88
89
  }
89
90
  // RDF data joins a program as rdf/4 facts, read without running anything.
90
91
  const prefixes = {};
@@ -136,11 +137,11 @@ export function writeProof(loaded, result, { goals = null } = {}) {
136
137
  // all also writes the given data. Throws when a conclusion is no triple.
137
138
  export function writeConclusions(loaded, result, { format, all = false, blankNodePrefix = '' } = {}) {
138
139
  if (format === 'eyemind') return null;
139
- const answers = result.answers;
140
140
  if (format === 'n3') {
141
141
  if (loaded.kind !== 'n3') throw new EyemindError('--to n3 writes the conclusions of an N3 run');
142
- return answersToN3(loaded.compiled.doc, answers, { mode: all ? 'all' : 'new', blankNodePrefix }).n3;
142
+ return resultToN3(loaded.compiled.doc, result, { mode: all ? 'all' : 'new', blankNodePrefix }).n3;
143
143
  }
144
+ const answers = result.answers;
144
145
  let quads;
145
146
  if (loaded.kind === 'srl') quads = srlQuads(loaded.text, answers, { all });
146
147
  else quads = conclusionQuads(answers, all ? loaded.text : null);
package/src/n3-parser.js CHANGED
@@ -34,13 +34,21 @@ export class N3SyntaxError extends SyntaxError {
34
34
 
35
35
  const NUMBER = /[+-]?(?:[0-9]+\.[0-9]*[eE][+-]?[0-9]+|\.[0-9]+[eE][+-]?[0-9]+|[0-9]+[eE][+-]?[0-9]+|[0-9]*\.[0-9]+|[0-9]+)/y;
36
36
  const PUNCT = ['^^', '=>', '<=', '<-', '.', ';', ',', '[', ']', '(', ')', '{', '}', '=', '!', '^'];
37
+ const punctuation = new Map();
38
+ for (const p of PUNCT) punctuation.set(p[0], [...(punctuation.get(p[0]) || []), p]);
37
39
 
38
40
  function isPnCharsBase(c) {
41
+ const code = c.charCodeAt(0);
42
+ if (code < 128) return (code >= 65 && code <= 90) || (code >= 97 && code <= 122);
39
43
  return /[A-Za-zÀ-ÖØ-öø-˿Ͱ-ͽͿ-῿‌-‍⁰-↏Ⰰ-⿯、-퟿豈-﷏ﷰ-�]/u.test(c) ||
40
44
  (c.codePointAt(0) >= 0x10000 && c.codePointAt(0) <= 0xEFFFF);
41
45
  }
42
46
  const isPnCharsU = (c) => isPnCharsBase(c) || c === '_';
43
- const isPnChars = (c) => isPnCharsU(c) || c === '-' || /[0-9·̀-ͯ‿-⁀]/u.test(c);
47
+ const isPnChars = (c) => {
48
+ const code = c.charCodeAt(0);
49
+ if (code < 128) return (code >= 65 && code <= 90) || (code >= 97 && code <= 122) || (code >= 48 && code <= 57) || c === '_' || c === '-';
50
+ return isPnCharsU(c) || /[·̀-ͯ‿-⁀]/u.test(c);
51
+ };
44
52
 
45
53
  function decodeEscapes(text, line) {
46
54
  let out = '';
@@ -69,11 +77,16 @@ function decodeEscapes(text, line) {
69
77
  // Tokens: { k: kind, v: text, line }. Kinds: iri, pname, bnode, var, string,
70
78
  // lang, number, word, punct, eof.
71
79
  export function tokenize(src) {
72
- const toks = [];
80
+ return [...tokens(src)];
81
+ }
82
+
83
+ // The parser needs only two tokens of lookahead, even for a large document.
84
+ function* tokens(src) {
85
+ let previous = null;
73
86
  let i = 0;
74
87
  let line = 1;
75
88
  const n = src.length;
76
- const push = (k, v) => toks.push({ k, v, line });
89
+ const push = (k, v) => (previous = { k, v, line });
77
90
  while (i < n) {
78
91
  const c = src[i];
79
92
  if (c === '\n') { line++; i++; continue; }
@@ -81,7 +94,7 @@ export function tokenize(src) {
81
94
  if (c === '#') { while (i < n && src[i] !== '\n') i++; continue; }
82
95
  if (src.startsWith('<<', i) || src.startsWith('>>', i) || src.startsWith(')>>', i)) {
83
96
  const v = src.startsWith('<<(', i) ? '<<(' : src.startsWith(')>>', i) ? ')>>' : src.slice(i, i + 2);
84
- push('punct', v);
97
+ yield push('punct', v);
85
98
  i += v.length;
86
99
  continue;
87
100
  }
@@ -93,7 +106,7 @@ export function tokenize(src) {
93
106
  const decoded = decodeEscapes(raw, line);
94
107
  // An escape may not bring in what the IRI could not hold as written.
95
108
  if (/[\u0000-\u0020<>"{}|^`\\]/.test(decoded)) throw new N3SyntaxError(`invalid character in IRI <${raw}>`, line);
96
- push('iri', decoded);
109
+ yield push('iri', decoded);
97
110
  i = end + 1;
98
111
  continue;
99
112
  }
@@ -114,7 +127,7 @@ export function tokenize(src) {
114
127
  if (src[j] === '\n') { if (!long) throw new N3SyntaxError('line break in a short string', line); line++; }
115
128
  raw += src[j++];
116
129
  }
117
- push('string', decodeEscapes(raw, start));
130
+ yield push('string', decodeEscapes(raw, start));
118
131
  i = j + q.length;
119
132
  continue;
120
133
  }
@@ -122,10 +135,10 @@ export function tokenize(src) {
122
135
  const m = /^@([A-Za-z]+(?:-[A-Za-z0-9]+)*(?:--(?:ltr|rtl))?)/.exec(src.slice(i, i + 100));
123
136
  if (!m) throw new N3SyntaxError('expected a language tag or keyword after @', line);
124
137
  const word = m[1];
125
- const prev = toks[toks.length - 1];
126
- if (['prefix', 'base', 'version', 'keywords', 'forAll', 'forSome'].includes(word) && !(prev && prev.k === 'string')) push('word', `@${word}`);
127
- else if (['a', 'is', 'of', 'has'].includes(word) && !(prev && prev.k === 'string')) push('word', word);
128
- else push('lang', word);
138
+ const prev = previous;
139
+ if (['prefix', 'base', 'version', 'keywords', 'forAll', 'forSome'].includes(word) && !(prev && prev.k === 'string')) yield push('word', `@${word}`);
140
+ else if (['a', 'is', 'of', 'has'].includes(word) && !(prev && prev.k === 'string')) yield push('word', word);
141
+ else yield push('lang', word);
129
142
  i += m[0].length;
130
143
  continue;
131
144
  }
@@ -136,7 +149,7 @@ export function tokenize(src) {
136
149
  if (!isPnChars(ch)) break;
137
150
  j += ch.length;
138
151
  }
139
- push('var', src.slice(i + 1, j));
152
+ yield push('var', src.slice(i + 1, j));
140
153
  i = j;
141
154
  continue;
142
155
  }
@@ -148,20 +161,20 @@ export function tokenize(src) {
148
161
  j += ch.length;
149
162
  }
150
163
  while (src[j - 1] === '.') j--;
151
- push('bnode', src.slice(i + 2, j));
164
+ yield push('bnode', src.slice(i + 2, j));
152
165
  i = j;
153
166
  continue;
154
167
  }
155
168
  NUMBER.lastIndex = i;
156
169
  const num = NUMBER.exec(src);
157
170
  if (num && (/[0-9]/.test(c) || ((c === '+' || c === '-' || c === '.') && /[0-9.]/.test(src[i + 1] ?? '')))) {
158
- push('number', num[0]);
171
+ yield push('number', num[0]);
159
172
  i += num[0].length;
160
173
  continue;
161
174
  }
162
- const punct = PUNCT.find((p) => src.startsWith(p, i));
175
+ const punct = punctuation.get(c)?.find((p) => src.startsWith(p, i));
163
176
  if (punct && !(punct === '.' && /[0-9]/.test(src[i + 1] ?? ''))) {
164
- push('punct', punct);
177
+ yield push('punct', punct);
165
178
  i += punct.length;
166
179
  continue;
167
180
  }
@@ -180,15 +193,14 @@ export function tokenize(src) {
180
193
  }
181
194
  while (src[j - 1] === '.' && j > i) j--;
182
195
  const text = src.slice(i, j);
183
- if (prefix === null) push('word', text);
184
- else push('pname', text);
196
+ if (prefix === null) yield push('word', text);
197
+ else yield push('pname', text);
185
198
  i = j;
186
199
  continue;
187
200
  }
188
201
  throw new N3SyntaxError(`unexpected character ${JSON.stringify(c)}`, line);
189
202
  }
190
- push('eof', '');
191
- return toks;
203
+ yield push('eof', '');
192
204
  }
193
205
 
194
206
  // Resolve a relative IRI reference against a base (RFC 3986, Section 5.2).
@@ -221,8 +233,6 @@ function removeDots(path) {
221
233
  return out.join('/');
222
234
  }
223
235
 
224
- const iri = (v) => ({ t: 'iri', v });
225
-
226
236
  // Prefixes a document may use without declaring them.
227
237
  export const DEFAULT_PREFIXES = {
228
238
  rdf: RDF,
@@ -241,17 +251,30 @@ export const DEFAULT_PREFIXES = {
241
251
  // in declaration order. Native proof validation preserves numeric literal
242
252
  // text, so two different decimal displays cannot agree through rounding.
243
253
  export function parseN3(src, { base = '', preserveNumericLiterals = false } = {}) {
244
- const toks = tokenize(String(src));
245
- let pos = 0;
254
+ src = String(src);
255
+ const input = tokens(src);
256
+ const ahead = [];
257
+ const iris = new Map();
258
+ const iri = (v) => {
259
+ let term = iris.get(v);
260
+ if (term === undefined) iris.set(v, term = { t: 'iri', v });
261
+ return term;
262
+ };
246
263
  const prefixes = new Map();
247
264
  let bnodeCount = 0;
248
265
  let scopeCount = 0;
249
266
  const top = { id: 0, triples: [], parent: null, bound: new Map(), started: false, existential: false };
250
267
  // Names for declared variables, apart from those the document writes.
251
- const taken = new Set(toks.filter((t) => t.k === 'var' || t.k === 'bnode').map((t) => `${t.k}:${t.v}`));
268
+ const taken = new Set();
269
+ if (src.includes('@forAll') || src.includes('@forSome')) {
270
+ for (const t of tokens(src)) if (t.k === 'var' || t.k === 'bnode') taken.add(`${t.k}:${t.v}`);
271
+ }
252
272
  let scope = top;
253
- const peek = (k = 0) => toks[pos + k];
254
- const next = () => toks[pos++];
273
+ const peek = (k = 0) => {
274
+ while (ahead.length <= k) ahead.push(input.next().value);
275
+ return ahead[k];
276
+ };
277
+ const next = () => { const t = peek(); ahead.shift(); return t; };
255
278
  const fail = (message, tok = peek()) => new N3SyntaxError(message, tok.line);
256
279
  const isP = (v, tok = peek()) => tok.k === 'punct' && tok.v === v;
257
280
  const expectP = (v) => {
package/src/n3-writer.js CHANGED
@@ -5,7 +5,7 @@
5
5
  // Skolem term skolem(Rule, Variable, Arguments) is a blank node, the same one
6
6
  // for the same rule firing.
7
7
  import { readTerms } from './reader.js';
8
- import { Struct, Var } from './terms.js';
8
+ import { Struct, Var, identity } from './terms.js';
9
9
  import { write } from './writer.js';
10
10
  import { LOG, RDF, XSD } from './n3-parser.js';
11
11
 
@@ -14,16 +14,23 @@ export class N3WriteError extends Error {}
14
14
  // The triples of an eyemind conclusions document, in order and without
15
15
  // duplicates. Also reports whether a contradiction halted the run.
16
16
  export function triplesFromEyemind(text) {
17
+ return triplesFromTerms(readTerms(String(text)).map(([term]) => term));
18
+ }
19
+
20
+ // Native conclusions need no canonical-text round trip.
21
+ export function triplesFromTerms(terms, distinct = false) {
17
22
  const triples = [];
18
23
  const seen = new Set();
19
24
  let contradiction = false;
20
- for (const [term] of readTerms(String(text))) {
25
+ for (const term of terms) {
21
26
  if (term === 'false') { contradiction = true; continue; }
22
27
  const t = tripleTerm(term);
23
28
  if (!t) continue;
24
- const k = write(t);
25
- if (seen.has(k)) continue;
26
- seen.add(k);
29
+ if (!distinct) {
30
+ const k = identity(t);
31
+ if (seen.has(k)) continue;
32
+ seen.add(k);
33
+ }
27
34
  triples.push(t.args);
28
35
  }
29
36
  return { triples, contradiction };
package/src/n3.js CHANGED
@@ -23,10 +23,11 @@
23
23
  // predicates of a body become goals defined in eyemind itself (builtins.mjs).
24
24
  import { run } from './engine.js';
25
25
  import { loadText } from './lang.js';
26
- import { Struct } from './terms.js';
26
+ import { Program, Source } from './program.js';
27
+ import { Struct, Var, conjunction, isGround } from './terms.js';
27
28
  import { write } from './writer.js';
28
29
  import { N3SyntaxError, parseN3, typedLiteral, LOG, XSD } from './n3-parser.js';
29
- import { triplesFromEyemind, tripleToEyemind, writeN3 } from './n3-writer.js';
30
+ import { triplesFromEyemind, triplesFromTerms, termToEyemind, tripleToEyemind, writeN3 } from './n3-writer.js';
30
31
  import { documentIris, readDocuments } from './n3-documents.js';
31
32
 
32
33
  const MATH = 'http://www.w3.org/2000/10/swap/math#';
@@ -1040,11 +1041,63 @@ export function readSources(sources, { base = '', baseOf = () => '' } = {}) {
1040
1041
 
1041
1042
  // A document's program: { program, documents }; readFile reads the
1042
1043
  // documents it names for log:semantics and log:content.
1043
- export function compileSources(sources, { base = '', baseOf, readFile = null, readDocument = null, source } = {}) {
1044
+ export function compileSources(sources, { base = '', baseOf, readFile = null, readDocument = null, source, native = false } = {}) {
1044
1045
  const doc = readSources(sources, { base, baseOf });
1045
1046
  const documents = readDocuments(documentIris(doc.triples), readFile, readDocument);
1046
- const { program } = compileN3Document(doc, { source: source ?? sourceNames(sources), documents });
1047
- return { doc, program };
1047
+ let program;
1048
+ const compiled = native && !documents.size ? plainProgram(doc) : null;
1049
+ const display = () => compileN3Document(doc, { source: source ?? sourceNames(sources), documents }).program;
1050
+ if (compiled === null) program = display();
1051
+ return { doc, nativeProgram: compiled, get program() { return program ??= display(); } };
1052
+ }
1053
+
1054
+ // Ordinary triple rules already are clauses. Build them without generating
1055
+ // and executing a second language. Other N3 constructs use the full compiler;
1056
+ // the JavaScript display remains available and keeps the same clause lines.
1057
+ function plainProgram(doc) {
1058
+ const listIris = new Set(['first', 'rest', 'nil'].map((name) => `${RDF_NS}${name}`));
1059
+ const constant = (t) => ['iri', 'literal', 'int', 'float'].includes(t.t) && !(t.t === 'iri' && listIris.has(t.v));
1060
+ const ordinary = (x) => x.p.t === 'iri' && [x.s, x.p, x.o].every((t) => constant(t) || (t.t === 'var' && (t.scope ?? 0) === 0));
1061
+ const facts = [];
1062
+ const rules = [];
1063
+ for (const x of doc.triples) {
1064
+ if (x.p.t === 'iri' && x.p.v === `${LOG}implies` && x.s.t === 'graph' && x.o.t === 'graph') {
1065
+ if (!x.s.triples.every((b) => ordinary(b) && !BUILTINS.has(b.p.v) && !UNSUPPORTED.has(b.p.v) &&
1066
+ !INLINE.has(b.p.v) && !TESTS.has(b.p.v) && !SCOPED_SUBJECT.has(b.p.v) && !SCOPED_OBJECT.has(b.p.v) && !RULE_PREDICATES.has(b.p.v))) return null;
1067
+ if (!x.o.triples.every(ordinary)) return null;
1068
+ const bound = keysOf(x.s);
1069
+ if ([...keysOf(x.o)].some((name) => !bound.has(name))) return null;
1070
+ if (x.o.triples.length) rules.push(x);
1071
+ } else {
1072
+ if (![x.s, x.p, x.o].every(constant)) return null;
1073
+ facts.push(x);
1074
+ }
1075
+ }
1076
+ const iris = new Map();
1077
+ const named = new Map();
1078
+ const term = (t, ctx) => {
1079
+ if (t.t === 'var') {
1080
+ const name = ctx.name(`v:${t.v}`, t.v);
1081
+ let value = named.get(name);
1082
+ if (value === undefined) named.set(name, value = new Var(name));
1083
+ return value;
1084
+ }
1085
+ if (t.t === 'iri') {
1086
+ let value = iris.get(t.v);
1087
+ if (value === undefined) iris.set(t.v, value = new Struct('iri', [t.v]));
1088
+ return value;
1089
+ }
1090
+ return termToEyemind(t);
1091
+ };
1092
+ const triple = (x, ctx) => new Struct('rdf', [term(x.s, ctx), term(x.p, ctx), term(x.o, ctx)]);
1093
+ const sources = facts.map((x, i) => new Source('fact', triple(x), [], i + 4));
1094
+ for (const x of rules) {
1095
+ const ctx = new Context(true);
1096
+ const body = x.s.triples.map((b) => triple(b, ctx));
1097
+ const head = conjunction(x.o.triples.map((h) => triple(h, ctx)));
1098
+ sources.push(new Source('forward', head, body.length ? body : ['true'], sources.length + 4));
1099
+ }
1100
+ return new Program(sources);
1048
1101
  }
1049
1102
 
1050
1103
  const sourceNames = (sources) => (typeof sources === 'string' ? 'input' : sources.map((s) => (Array.isArray(s) ? s[1] : 'data')).join(', '));
@@ -1053,7 +1106,17 @@ const sourceNames = (sources) => (typeof sources === 'string' ? 'input' : source
1053
1106
  // mode 'all', and the document's own log:outputString strings when the
1054
1107
  // result writes strings.
1055
1108
  export function answersToN3(doc, answers, { mode = 'new', strings = 'auto', blankNodePrefix = '' } = {}) {
1056
- let { triples, contradiction } = triplesFromEyemind(answers.join('\n'));
1109
+ return conclusionsToN3(doc, triplesFromEyemind(answers.join('\n')), { mode, strings, blankNodePrefix });
1110
+ }
1111
+
1112
+ export function resultToN3(doc, result, options = {}) {
1113
+ // Nonground answers retain the document-wide variable names of their
1114
+ // canonical text. Forward ground conclusions are already distinct.
1115
+ if (!result.conclusions || result.conclusions.some((term) => !isGround(term))) return answersToN3(doc, result.answers, options);
1116
+ return conclusionsToN3(doc, triplesFromTerms(result.conclusions, true), options);
1117
+ }
1118
+
1119
+ function conclusionsToN3(doc, { triples, contradiction }, { mode = 'new', strings = 'auto', blankNodePrefix = '' } = {}) {
1057
1120
  const given = doc.triples.filter((x) => !isRule(x)).map(tripleToEyemind);
1058
1121
  if (mode === 'all') triples = [...given, ...triples];
1059
1122
  else if (strings !== false && triples.some(isOutputString)) triples = [...given.filter(isOutputString), ...triples];
@@ -1067,9 +1130,9 @@ export const N3_LIMITS = { maxDepth: 1000000, maxIterations: 100000, maxInferenc
1067
1130
  // result }; with proof, result.proof is eyemind's checked proof of the
1068
1131
  // compiled program.
1069
1132
  export function reasonN3(sources, { base = '', mode = 'new', strings = 'auto', limits = {}, proof = false, goals = [], readFile = null, readDocument = null } = {}) {
1070
- const { doc, program } = compileSources(sources, { base, readFile, readDocument });
1071
- const result = run(loadText(program, 'compiled.js'), { ...N3_LIMITS, ...limits, proof, goals });
1072
- return { ...answersToN3(doc, result.answers, { mode, strings }), program, result };
1133
+ const compiled = compileSources(sources, { base, readFile, readDocument, native: true });
1134
+ const result = run(compiled.nativeProgram ?? loadText(compiled.program, 'compiled.js'), { ...N3_LIMITS, ...limits, proof, goals });
1135
+ return { ...resultToN3(compiled.doc, result, { mode, strings }), get program() { return compiled.program; }, result };
1073
1136
  }
1074
1137
 
1075
1138
  const RULE_IRIS = new Set([`${LOG}implies`, `${LOG}impliedBy`, `${LOG}query`]);
package/src/terms.js CHANGED
@@ -483,12 +483,14 @@ export function identity(term) {
483
483
  }
484
484
 
485
485
  // The key an argument index files a term under: an atom or a number is its
486
- // own key, and a small ground compound, such as iri('http://e/a'), the text
486
+ // own key, an IRI uses its string, and another small ground compound the text
487
487
  // of its structure. Signed zeros share a key, as they unify. A variable, a
488
488
  // compound holding one, or one of more than INDEX_NODES nodes has none and
489
489
  // constrains nothing. A key is only a filter, so an atom whose text happens
490
490
  // to equal a compound's key could at most add candidates, never lose one.
491
491
  const INDEX_NODES = 64;
492
+ // Only variable-free terms have a key independent of later bindings.
493
+ const indexKeys = new WeakMap();
492
494
 
493
495
  export function indexKey(term, env = null) {
494
496
  if (term instanceof Var) {
@@ -497,12 +499,20 @@ export function indexKey(term, env = null) {
497
499
  if (term instanceof Var) return undefined;
498
500
  }
499
501
  if (!(term instanceof Struct)) return term;
502
+ if (term.name === 'iri' && term.args.length === 1) {
503
+ const value = env === null ? term.args[0] : deref(term.args[0], env);
504
+ if (typeof value === 'string') return value;
505
+ }
506
+ const known = indexKeys.get(term);
507
+ if (known !== undefined) return known;
500
508
  const out = ['\u0000k'];
501
509
  const pending = [term];
502
510
  let nodes = 0;
511
+ let ground = true;
503
512
  while (pending.length) {
504
513
  let item = pending.pop();
505
514
  if (item instanceof Var) {
515
+ ground = false;
506
516
  if (env === null) return undefined;
507
517
  item = deref(item, env);
508
518
  if (item instanceof Var) return undefined;
@@ -519,7 +529,9 @@ export function indexKey(term, env = null) {
519
529
  out.push('f', String(item));
520
530
  }
521
531
  }
522
- return out.join('\u0001');
532
+ const result = out.join('\u0001');
533
+ if (ground) indexKeys.set(term, result);
534
+ return result;
523
535
  }
524
536
 
525
537
  // The variables of a term by name, in order of first appearance.
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.17';
2
+ export const VERSION = '0.5.18';
package/src/writer.js CHANGED
@@ -91,6 +91,7 @@ const ESCAPES = { '\\': '\\\\', "'": "\\'", '\n': '\\n', '\r': '\\r', '\t': '\\t
91
91
  // separators and lone surrogates are escaped; any other character is written
92
92
  // as it is.
93
93
  export function quote(text) {
94
+ if (!/['\\\u0000-\u001f\u007f-\u009f\u2028\u2029\ud800-\udfff]/.test(text)) return `'${text}'`;
94
95
  let out = "'";
95
96
  for (let i = 0; i < text.length; i++) {
96
97
  const ch = text[i];