eyemind 0.5.16 → 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
@@ -7,7 +7,7 @@ eyemind is a **JavaScript rule language** with forward and backward reasoning an
7
7
 
8
8
  [Playground](https://eyereasoner.github.io/eyemind/playground/) · [Specification](https://eyereasoner.github.io/eyemind/SPEC) · [Conformance](https://eyereasoner.github.io/eyemind/conformance/) · [Examples](https://eyereasoner.github.io/eyemind/examples/)
9
9
 
10
- The playground runs programs in your browser; the specification defines the language, its canonical text, the proof format and the C1–C10 checks. The examples are 135 runnable programs, each with a card deck and saved conclusions, proofs and check reports. The conformance suite has 1371 cases that test any implementation of the specification through its command line; run it [in your browser](https://eyereasoner.github.io/eyemind/playground/conformance).
10
+ The playground runs programs in your browser; the specification defines the language, its canonical text, the proof format and the C1–C10 checks. The examples are 135 runnable programs, each with a card deck and saved conclusions, proofs and check reports. The conformance suite has 1376 cases that test any implementation of the specification through its command line; run it [in your browser](https://eyereasoner.github.io/eyemind/playground/conformance).
11
11
 
12
12
  ## Contents
13
13
 
@@ -480,6 +480,7 @@ A negation `not(G)` concludes from what is *absent* and a collection `findall(T,
480
480
  - **Negate only what is bound.** The variables of `not(G)` must be bound when it runs; write `not(q(X, _))` for "no value at all".
481
481
  - **Check the search, not just its result.** A proof ends with a search certificate: `searched(Call, Answers)` lists each call's answers and `derived(Pattern, Facts)` each consulted relation. The checker expands each call one level against the program, so a wrong table shows up as a disagreement.
482
482
  - **Say what was taken on trust.** Anything the certificate cannot settle becomes an obligation, and evidence in the proof can still refute it (C6).
483
+ - **Certify relational negation.** Supported, closed listings can establish the original calls of ground relational rules with bound negations, including inside conjunctions and disjunctions. A proof within this fragment can be `checked` with no obligation, even under `--strict-proof`. Collections of derived facts, whose order a listing cannot show, and dependencies on `restricted` rules with new witnesses keep an obligation.
483
484
 
484
485
  ## Checking the translation
485
486
 
@@ -564,7 +565,7 @@ console.log(result.bindings);
564
565
  console.log(checkProof(socrates, result.proof, { goals }).valid);
565
566
  ```
566
567
 
567
- `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.
568
569
 
569
570
  The core library's `result.proof` is the JavaScript certificate.
570
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.16
5
+ Version: eyemind 0.5.18
6
6
  ```
7
7
 
8
8
  This document specifies the syntax and meaning of eyemind programs and data
@@ -1005,6 +1005,12 @@ concludes `man('bob')` and invents no father for `'jo'`, since `'bob'`
1005
1005
  already satisfies the heads once the third rule has run. A restricted
1006
1006
  rule's display omits its guard ([Section 10.2](#102-clause-displays)).
1007
1007
 
1008
+ A `restricted` call states a clause and is no rule value: a `restricted`
1009
+ call nested in another statement MUST be rejected. Its premise MUST bind
1010
+ every variable of its heads other than the head-only ones when the guard is
1011
+ solved; a solution that leaves one unbound, as a fact with variables can,
1012
+ is an error.
1013
+
1008
1014
  This gives the specified Skolemized reading of existential conclusions.
1009
1015
  The original existential rule need not have a least model over its original
1010
1016
  vocabulary. A witness is an ordinary compound in subsequent reasoning; it
@@ -1039,6 +1045,20 @@ holds when `G` has no solution, with the binding restrictions of [Section
1039
1045
  4.2](#42-controls). This is absence relative to the program, not falsity in the world.
1040
1046
  For relational goals this gives the stratified least-model reading.
1041
1047
 
1048
+ A chain-stratified program ([Section 6.4](#64-chain-stratification)) has no such ranks. Its meaning
1049
+ is the set of facts [Section 8.2](#82-forward-evaluation-and-witnesses)'s chain strata derive. When no
1050
+ contradiction holds, that set is a **stable model**: the least model of
1051
+ the program's rules with every negation decided by the set itself. Chain
1052
+ stratification is what makes it the only one, so the order of rule
1053
+ applications cannot change it.
1054
+
1055
+ A restricted rule ([Section 7.2](#72-variables-and-witnesses)) reads its conclusion existentially: for each
1056
+ solution of its premise, some values satisfy its heads. A result is **lean**
1057
+ when each witness a restricted rule made is needed, no other values
1058
+ satisfying those heads. [Section 8.2](#82-forward-evaluation-and-witnesses) derives one lean result or fails;
1059
+ another order of rule applications could derive another, so a lean result
1060
+ is not determined by the program alone.
1061
+
1042
1062
  Collection also waits for its dependencies. `findall` collects ordered
1043
1063
  search solutions, including repeated derivations and nonground instances;
1044
1064
  its meaning is not determined by a set of ground atoms alone. Bindings
@@ -1631,6 +1651,16 @@ boundary is established by its search certificate. An unconditional
1631
1651
  `checked` verdict also establishes operational query fidelity
1632
1652
  ([Section 11.2](#112-operational-query-fidelity)).
1633
1653
 
1654
+ For a program with negation, "follows" is relative to the facts the
1655
+ certificate lists: C9 establishes that they are supported by steps, closed
1656
+ under the forward rules and consistent with every settled negation. In the
1657
+ ground relational fragment of [Section 11.13](#1113-c10-call-fidelity), a stratified or
1658
+ chain-stratified program has only one such result ([Section 7.4](#74-negation-and-collection)). With restricted
1659
+ witnesses, different lean results can have these properties. A claim whose
1660
+ forward dependency closure includes a restricted rule with head-only
1661
+ variables therefore retains a call-fidelity obligation, and a strict check
1662
+ rejects it. Independent claims may still check strictly.
1663
+
1634
1664
  It does not establish:
1635
1665
 
1636
1666
  - that the proof contains all conclusions of the program;
@@ -2125,8 +2155,8 @@ with these differences:
2125
2155
  4. A comparison `compare/3` with either compared term nonground is not
2126
2156
  supported by this certificate format: alpha renaming of a table need
2127
2157
  not preserve the order of variable names. Such a search leaves call fidelity unproved.
2128
- 5. A consulted forward listing MUST have a dependency closure in the ground
2129
- positive fragment described below. A final listing alone MUST NOT certify
2158
+ 5. A consulted forward listing MUST have a dependency closure in the
2159
+ supported fragment described below. A final listing alone MUST NOT certify
2130
2160
  binding-sensitive or order-sensitive forward firings outside that fragment.
2131
2161
 
2132
2162
  For the `once` example in [Section 11.2](#112-operational-query-fidelity),
@@ -2144,14 +2174,18 @@ first, and `once` selects it. Thus `q('a')` is an answer and `q('b')` is
2144
2174
  excluded. Substituting `called(p('b'), [p('b')])` cannot establish the
2145
2175
  different call `p(X)`.
2146
2176
 
2147
- **Supported forward listings.** A forward listing's **ground positive
2148
- dependency closure** contains its relation and each ordinary body relation
2149
- of every source fact, backward rule or forward rule defining any relation
2150
- in that closure. To use a listing for C10:
2177
+ **Supported forward listings.** A forward listing's **ground dependency
2178
+ closure** contains its relation and each ordinary body relation, inside a
2179
+ negation or not, of every source fact, backward rule or forward rule
2180
+ defining any relation in that closure. To use a listing for C10:
2151
2181
 
2152
2182
  - All source facts in the closure MUST be ground.
2153
- - Rule bodies MUST contain only ordinary calls, `'true'`, conjunction and
2154
- disjunction. Templates, captures and source inspection are excluded.
2183
+ - Rule bodies MUST contain only ordinary calls, `'true'`, conjunction,
2184
+ disjunction and negations of these. Templates, captures and source
2185
+ inspection are excluded.
2186
+ - A negation grounds nothing. Each of its variables other than anonymous
2187
+ ones MUST be grounded by the body goals before it, and it MUST NOT contain
2188
+ a negation.
2155
2189
  - A body call to an ordinary relation grounds its variables. Conjunction
2156
2190
  accumulates the grounded variables of its parts; disjunction grounds only
2157
2191
  those grounded by both alternatives.
@@ -2163,8 +2197,13 @@ in that closure. To use a listing for C10:
2163
2197
  restricted rule makes can depend on the order of rule applications.
2164
2198
 
2165
2199
  Supported facts and closed listings then establish the least ground
2166
- positive closure. More general forward execution requires publication
2167
- evidence this format does not supply, leaving call fidelity unproved.
2200
+ positive closure and, with negations, a set of facts that is supported,
2201
+ closed under the rules and consistent with each negation, every negation
2202
+ being decided by the listed facts alone. A stratified or chain-stratified
2203
+ program has exactly one such set ([Section 7.4](#74-negation-and-collection)), its result, so the
2204
+ listings are the facts the original calls consult. More general forward
2205
+ execution requires publication evidence this format does not supply,
2206
+ leaving call fidelity unproved.
2168
2207
 
2169
2208
  **Deciding claims.** Every relevant call certificate MUST be valid. Each
2170
2209
  claim MUST be identical, up to variable renaming, to an answer of at least
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "eyemind",
3
- "version": "0.5.16",
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
@@ -165,8 +165,10 @@ function unboundNegation(goal, env) {
165
165
  const shown = write(resolved, null, naming);
166
166
  const unbound = [...new Set([...variables(resolved).values()]
167
167
  .filter((variable) => !isAnonymous(variable)).map((variable) => naming.get(variable.name)))];
168
- return new EyemindError('negation requires a goal whose variables are bound, except for anonymous ones: ' +
168
+ const error = new EyemindError('negation requires a goal whose variables are bound, except for anonymous ones: ' +
169
169
  `${unbound.join(', ')} ${unbound.length === 1 ? 'is' : 'are'} unbound in ${shown}`);
170
+ error.goal = goal;
171
+ return error;
170
172
  }
171
173
 
172
174
  // Resolve a proof forest with an explicit stack: a derivation chain is as deep
@@ -283,6 +285,10 @@ export class Solver {
283
285
  // of the facts with that value there.
284
286
  this.factIndex = new Map();
285
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
+ }
286
292
  this.genericKeys = new Set();
287
293
  this.genericPredicates = new Set();
288
294
  this.derived = [];
@@ -299,6 +305,7 @@ export class Solver {
299
305
  this.chosen = null;
300
306
  this.snapshots = new Map();
301
307
  this.direct = new Map();
308
+ this.groundCalls = new Map();
302
309
  this.rules = new Map();
303
310
  this.ruleKeys = new Map();
304
311
  this.maxInferences = options.maxInferences || 1000000;
@@ -546,13 +553,28 @@ export class Solver {
546
553
  const argument = indexKey(arg);
547
554
  if (argument !== undefined) {
548
555
  const bucket = positions[position].get(argument);
549
- 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]);
550
558
  else bucket.push(number);
551
559
  }
552
560
  });
553
561
  }
554
562
  }
555
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
+
556
578
  // The indexes of the derived facts a goal could match, in order, when an
557
579
  // argument of the goal narrows them down; null to try them all.
558
580
  factOrder(goal, env, goalKey) {
@@ -564,7 +586,8 @@ export class Solver {
564
586
  for (let position = 0; position < goal.args.length; position++) {
565
587
  const arg = indexKey(goal.args[position], env);
566
588
  if (arg !== undefined) {
567
- 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;
568
591
  if (bucket.length < size) {
569
592
  best = bucket;
570
593
  size = bucket.length;
@@ -716,8 +739,7 @@ export class Solver {
716
739
  let now = null;
717
740
  let previous = null;
718
741
  if (keys !== null) {
719
- now = new Map();
720
- 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);
721
743
  previous = this.snapshots.get(clause) || null;
722
744
  this.snapshots.set(clause, now);
723
745
  }
@@ -725,13 +747,15 @@ export class Solver {
725
747
  if (previous !== null) {
726
748
  positions = [];
727
749
  keys.forEach((goalKey, i) => {
728
- if (goalKey && now.get(goalKey) > previous.get(goalKey)) positions.push(i);
750
+ if (goalKey && now[i] > previous[i]) positions.push(i);
729
751
  });
730
- 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]))) {
731
753
  return []; // nothing derived since its last search can be used, so nothing new follows
732
754
  }
733
755
  }
734
756
  this.serial++;
757
+ const direct = this.directFirings(clause, keys, previous);
758
+ if (direct !== null) return direct;
735
759
  const [head, fullBody, names] = freshClause(clause, this.serial, true);
736
760
  const body = fullBody.slice(clause.prefixLength);
737
761
  const env = new Env();
@@ -741,9 +765,9 @@ export class Solver {
741
765
  for (const delta of positions) {
742
766
  const window = keys.map((goalKey, i) => {
743
767
  if (goalKey === null) return null;
744
- if (i < delta) return [0, previous.get(goalKey), true];
745
- if (i === delta) return [previous.get(goalKey), now.get(goalKey), false];
746
- 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];
747
771
  });
748
772
  this.window = window;
749
773
  this.windowGoals = body;
@@ -758,14 +782,72 @@ export class Solver {
758
782
  return found.map(([firing]) => firing);
759
783
  }
760
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
+
761
827
  // Whether a body goal, as the rule writes it, could match a fact derived
762
828
  // since the rule's last search. The goal's own atoms and numbers narrow the
763
829
  // facts down before the rule is renamed and searched.
764
830
  mayMatchNew(goal, goalKey, previous, now) {
765
831
  const order = this.factOrder(goal, null, goalKey);
766
832
  if (order === null) return true;
767
- const first = bisectLeft(order, previous.get(goalKey));
768
- return first < order.length && order[first] < now.get(goalKey);
833
+ const first = bisectLeft(order, previous);
834
+ return first < order.length && order[first] < now;
835
+ }
836
+
837
+ // The solutions of a rule's body. A restricted rule's guard is a negation
838
+ // the program did not write: when its premise leaves a variable of its
839
+ // heads unbound, the error names the rule rather than the guard.
840
+ *guarded(clause, guard, solutions) {
841
+ if (clause.guard === null) {
842
+ yield* solutions;
843
+ return;
844
+ }
845
+ try {
846
+ yield* solutions;
847
+ } catch (error) {
848
+ if (!(error instanceof EyemindError) || error.goal !== guard) throw error;
849
+ throw new EyemindError(`restricted rule ${clause.id} needs its premise to bind the variables of its conclusion other than its new values`);
850
+ }
769
851
  }
770
852
 
771
853
  // Each solution of a renamed rule's body, as what it concludes, with the
@@ -775,7 +857,7 @@ export class Solver {
775
857
  // first and concluded afterwards.
776
858
  scan(clause, head, body, names, env, prefix) {
777
859
  const found = [];
778
- for (const [answerEnv, nodes] of this.solve(body, env)) {
860
+ for (const [answerEnv, nodes] of this.guarded(clause, body[body.length - 1], this.solve(body, env))) {
779
861
  const mark = answerEnv.mark();
780
862
  // Head variables the body leaves unbound become Skolem terms, shared
781
863
  // between the heads of one conclusion.
@@ -911,6 +993,7 @@ export class Solver {
911
993
  // bodies and their observable order.
912
994
  for (const [clause, [conclusions, children, bindings, claim, guard]] of firings) {
913
995
  if (guard) this.guards.push([clause, guard, conclusions]);
996
+ const by = new Struct('clause', [BigInt(clause.id)]);
914
997
  for (const [position, conclusion] of conclusions.entries()) {
915
998
  const template = clause.templates.find((item) => item.position === position);
916
999
  if (template) {
@@ -922,14 +1005,14 @@ export class Solver {
922
1005
  if (!this.reported.has(claimId)) this.reported.set(claimId, [claim, children, clause.id]);
923
1006
  continue;
924
1007
  }
925
- 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);
926
1009
  if (conclusion === 'false') {
927
1010
  this.derived.push(node);
928
1011
  this.haltCode = 65;
929
1012
  return 'halt';
930
1013
  }
931
1014
  node.generic = this.program.inspectionEnabled && !isGround(conclusion);
932
- const conclusionId = node.generic ? variant(conclusion) : identity(conclusion);
1015
+ const conclusionId = node.generic ? variant(conclusion) : this.factKey(conclusion);
933
1016
  const factKeys = node.generic ? this.genericKeys : this.factKeys;
934
1017
  if (factKeys.has(conclusionId)) continue;
935
1018
  factKeys.add(conclusionId);
@@ -1126,7 +1209,7 @@ class Missing extends Error {
1126
1209
  // of clauses only searches behind a trusted boundary could consult.
1127
1210
  export class Result {
1128
1211
  constructor(fields) {
1129
- Object.assign(this, fields);
1212
+ Object.defineProperties(this, Object.getOwnPropertyDescriptors(fields));
1130
1213
  }
1131
1214
 
1132
1215
  // The derived facts as text, written only when asked for.
@@ -1218,12 +1301,9 @@ function reason(program, goalInputs, options) {
1218
1301
  // Variables are named A, B, ... in the order the conclusions show them; the
1219
1302
  // bindings of each answer name them as its conclusion does.
1220
1303
  const lettering = new Lettering();
1221
- const answers = claims.map((claim) => write(claim, null, lettering));
1222
- const answerBindings = bindings.map((answer) => {
1223
- const out = {};
1224
- for (const [name, value] of answer) out[name] = write(value, null, lettering);
1225
- return out;
1226
- });
1304
+ let answers = null;
1305
+ let answerBindings = null;
1306
+ let stdout = null;
1227
1307
  const rendered = options.proof
1228
1308
  ? renderProof(program, claims, roots, true, heading, (boundaries) => {
1229
1309
  const ordinary = certify(solver, boundaries);
@@ -1253,12 +1333,22 @@ function reason(program, goalInputs, options) {
1253
1333
  behind = [...clausesBehindBoundaries(program, roots)].filter((id) => !used.has(id)).sort((a, b) => a - b);
1254
1334
  }
1255
1335
  return new Result({
1256
- answers,
1257
- 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
+ },
1258
1348
  derived: solver.derived,
1259
1349
  clausesUsed: used !== null ? [...used].sort((a, b) => a - b) : null,
1260
1350
  clausesBehindBoundaries: behind,
1261
- 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(''); },
1262
1352
  proof: document,
1263
1353
  proofReport: report,
1264
1354
  stats: solver.stats,
package/src/fidelity.js CHANGED
@@ -6,7 +6,7 @@ import { text, variant } from './common.js';
6
6
  import { goalTerm } from './goals.js';
7
7
  import { INSPECTION_KEYS } from './inspection.js';
8
8
  import {
9
- Env, conjunction, copyResolved, freshTerm, isCallable, isGround, isTerm, key, unify, variables,
9
+ Env, conjunction, copyResolved, freshTerm, isAnonymous, isCallable, isGround, isTerm, key, unify, variables,
10
10
  } from './terms.js';
11
11
 
12
12
  function instance(goal, pattern) {
@@ -34,27 +34,39 @@ export function callQuestions(program, goals, claims) {
34
34
  });
35
35
  }
36
36
 
37
- // C9's support plus closure establishes the least ground positive model.
38
- // For forward rules that observe bindings or order, a final listing alone
39
- // does not establish which firings occurred. Refuse that stronger promise.
37
+ // C9's support plus closure establishes the least ground positive model,
38
+ // and with negations the one stable model of a stratified or
39
+ // chain-stratified program: a negation whose named variables earlier goals
40
+ // bind is decided by the listed facts alone. For forward rules that observe
41
+ // bindings or order, and for restricted rules, whose guard another order of
42
+ // firings could decide otherwise, a final listing alone does not establish
43
+ // which firings occurred. Refuse that stronger promise.
40
44
  export function positiveListings(program, listings) {
41
45
  const pending = [...listings];
42
46
  const seen = new Set();
43
- function bound(goal) {
44
- if (goal === 'true') return new Set();
47
+ function bound(goal, grounded, negated = false) {
48
+ if (goal === 'true') return grounded;
45
49
  if (isTerm(goal, 'and', 2) || isTerm(goal, 'or', 2)) {
46
- const left = bound(goal.args[0]);
47
- const right = bound(goal.args[1]);
48
- if (left === null || right === null) return null;
49
- return goal.name === 'and' ? new Set([...left, ...right])
50
+ const left = bound(goal.args[0], grounded, negated);
51
+ if (left === null) return null;
52
+ const right = bound(goal.args[1], goal.name === 'and' ? left : grounded, negated);
53
+ if (right === null) return null;
54
+ return goal.name === 'and' ? right
50
55
  : new Set([...left].filter((name) => right.has(name)));
51
56
  }
57
+ if (isTerm(goal, 'not', 1)) {
58
+ if (negated) return null;
59
+ for (const [name, variable] of variables(goal)) {
60
+ if (!isAnonymous(variable) && !grounded.has(name)) return null;
61
+ }
62
+ return bound(goal.args[0], grounded, true) === null ? null : grounded;
63
+ }
52
64
  if (!isCallable(goal)) return null;
53
65
  const goalKey = key(goal);
54
66
  if (PRIMITIVE_KEYS.has(goalKey) || INSPECTION_KEYS.has(goalKey) ||
55
67
  ['not/1', 'findall/3', 'once/1', 'call/1'].includes(goalKey)) return null;
56
68
  pending.push(goalKey);
57
- return new Set(variables(goal).keys());
69
+ return new Set([...grounded, ...variables(goal).keys()]);
58
70
  }
59
71
  while (pending.length) {
60
72
  const goalKey = pending.pop();
@@ -63,16 +75,15 @@ export function positiveListings(program, listings) {
63
75
  const clauses = [...(program.groups.get(goalKey) || []), ...program.forward.filter((clause) =>
64
76
  clause.plainHeads.some((head) => isCallable(head) && key(head) === goalKey))];
65
77
  for (const clause of clauses) {
66
- if (clause.parentId !== null || clause.templates.length || clause.captures !== null) return false;
78
+ if (clause.parentId !== null || clause.templates.length || clause.captures !== null || clause.guard !== null) return false;
67
79
  if (!clause.forward && !clause.body.length) {
68
80
  if (!isGround(clause.head)) return false;
69
81
  continue;
70
82
  }
71
- const grounded = new Set();
83
+ let grounded = new Set();
72
84
  for (const goal of clause.body) {
73
- const names = bound(goal);
74
- if (names === null) return false;
75
- for (const name of names) grounded.add(name);
85
+ grounded = bound(goal, grounded);
86
+ if (grounded === null) return false;
76
87
  }
77
88
  const witnesses = new Set(clause.forward ? clause.witnessNames : []);
78
89
  for (const name of variables(clause.head).keys()) {
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/lang.js CHANGED
@@ -183,6 +183,11 @@ class Builder {
183
183
  const term = pending.pop();
184
184
  if (!(term instanceof Struct)) continue;
185
185
  const source = this.rules.get(term);
186
+ // A restricted rule is a statement only: nested, it would be read as
187
+ // a term and its rule dropped.
188
+ if (source !== undefined && source.kind === 'restricted') {
189
+ throw new EyemindError('restricted() states a rule and cannot be nested in another statement');
190
+ }
186
191
  if (source !== undefined) this.embedded.add(source);
187
192
  pending.push(...term.args);
188
193
  }
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.16';
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];