eyemind 0.9.1 → 0.9.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/engine.js CHANGED
@@ -10,7 +10,7 @@ import { CONTROL_KEYS, Program } from './program.js';
10
10
  import {
11
11
  Env, EyemindError, Struct, Var, conjunction, copyResolved, deref, flattenConjunction, freshTerm,
12
12
  identity, indexKey, isAnonymous, isCallable, isGround, isGroundButAnonymous, isTerm, key, keyArity, listFromItems,
13
- sortCollected, unify, variables,
13
+ match, sortCollected, TermIds, unify, variables,
14
14
  } from './terms.js';
15
15
  import { Lettering, SourceNaming, write } from './writer.js';
16
16
 
@@ -296,8 +296,8 @@ export class Solver {
296
296
  // as rdf(S, P, O, G) with a common subject and a given property finds its
297
297
  // facts directly rather than among all the subject's facts.
298
298
  this.pairIndex = new Map();
299
- this.factKeys = new Set(program.groundFactKeys);
300
- this.iriIds = new Map();
299
+ this.factKeys = new Set();
300
+ this.termIds = new TermIds();
301
301
  for (const clause of program.clauses) {
302
302
  if (!clause.forward && !clause.body.length && isGround(clause.head)) this.factKeys.add(this.factKey(clause.head));
303
303
  }
@@ -481,7 +481,7 @@ export class Solver {
481
481
  return this.childFrame(frame, [goal.args[0]], this.controlPending(goal, cut), frame.depth + 1);
482
482
  } else if (PRIMITIVE_KEYS.has(goalKey)) {
483
483
  point = new Point('primitive', frame, env.mark(), goal, { iterator: primitive(goal, env) });
484
- } else if (windowed) {
484
+ } else if (windowed && this.window[frame.index] !== null) {
485
485
  const [start, stop, withClauses] = this.window[frame.index];
486
486
  point = new Point('resolve', frame, env.mark(), goal, {
487
487
  facts: this.facts.get(goalKey) || NO_NODES,
@@ -564,9 +564,9 @@ export class Solver {
564
564
  this.factIndex.set(goalKey, positions);
565
565
  }
566
566
  const keys = node.goal.args.map((arg) => indexKey(arg));
567
- keys.forEach((argument, position) => {
568
- if (argument !== undefined) addToBucket(positions[position], argument, number);
569
- });
567
+ for (let position = 0; position < arity; position++) {
568
+ if (keys[position] !== undefined) addToBucket(positions[position], keys[position], number);
569
+ }
570
570
  if (arity > 1) {
571
571
  let pairs = this.pairIndex.get(goalKey);
572
572
  if (pairs === undefined) {
@@ -574,7 +574,8 @@ export class Solver {
574
574
  this.pairIndex.set(goalKey, pairs);
575
575
  }
576
576
  for (let position = 0; position + 1 < arity; position++) {
577
- const [first, second] = [keys[position], keys[position + 1]];
577
+ const first = keys[position];
578
+ const second = keys[position + 1];
578
579
  if (first === undefined || second === undefined) continue;
579
580
  let inner = pairs[position].get(first);
580
581
  if (inner === undefined) pairs[position].set(first, inner = new Map());
@@ -584,18 +585,11 @@ export class Solver {
584
585
  }
585
586
  }
586
587
 
587
- // RDF rules often derive only IRI tuples. Small per-run identifiers avoid
588
- // retaining a second copy of every IRI in each fact's duplicate key.
588
+ // A ground fact's number from the run's TermIds, and identity() for
589
+ // anything else, so duplicates are found without building a string.
589
590
  factKey(term) {
590
- if (!(term instanceof Struct) || !term.args.length ||
591
- !term.args.every((arg) => isTerm(arg, 'iri', 1) && typeof arg.args[0] === 'string')) return identity(term);
592
- const ids = term.args.map((arg) => {
593
- const iri = arg.args[0];
594
- let id = this.iriIds.get(iri);
595
- if (id === undefined) this.iriIds.set(iri, id = this.iriIds.size);
596
- return id;
597
- });
598
- return `@${term.name.length}:${term.name}:${ids.length}:${ids.join(',')}`;
591
+ const id = this.termIds.of(term);
592
+ return id < 0 ? identity(term) : id;
599
593
  }
600
594
 
601
595
  // The indexes of the derived facts a goal could match, in order, when an
@@ -668,8 +662,9 @@ export class Solver {
668
662
  let index = point.start + position;
669
663
  if (point.order !== null) index = point.order[index];
670
664
  let fact = point.facts[index];
671
- if (fact.generic) fact = freshNode(fact, ++this.serial);
672
- if (unify(point.goal, fact.goal, env)) {
665
+ const generic = fact.generic;
666
+ if (generic) fact = freshNode(fact, ++this.serial);
667
+ if (generic ? unify(point.goal, fact.goal, env) : match(point.goal, fact.goal, env)) {
673
668
  if (windowed) this.chosen[point.frame.index] = [0, index];
674
669
  return this.advance(point.frame, fact);
675
670
  }
@@ -729,9 +724,10 @@ export class Solver {
729
724
  }
730
725
 
731
726
  // For a rule semi-naive search can take, the key of each body goal answered
732
- // by facts alone, or null for a primitive or a negation or collection; null
733
- // for other rules. Negations and collections consult lower strata only
734
- // (Section 6.1), so they do not change within one.
727
+ // by facts alone, or null for a primitive, a negation or collection, or a
728
+ // goal whose answers no forward rule can change; null for other rules.
729
+ // Negations and collections consult lower strata only (Section 6.1), so
730
+ // they do not change within one.
735
731
  directKeys(clause) {
736
732
  if (this.direct.has(clause)) return this.direct.get(clause);
737
733
  let keys = [];
@@ -743,6 +739,10 @@ export class Solver {
743
739
  goalKey === 'findall_sorted/3') {
744
740
  keys.push(null);
745
741
  } else if (CONTROL_KEYS.has(goalKey) || (this.program.groups.get(goalKey) || []).some((item) => item.body.length)) {
742
+ if (this.fixed(goal)) {
743
+ keys.push(null);
744
+ continue;
745
+ }
746
746
  keys = null;
747
747
  break;
748
748
  } else {
@@ -753,6 +753,42 @@ export class Solver {
753
753
  return keys;
754
754
  }
755
755
 
756
+ // Whether a goal has the same answers throughout reasoning: it calls only
757
+ // primitives and backward clauses, through control, and no forward rule
758
+ // concludes anything it calls. A rule's goal of this kind narrows its
759
+ // firings as a primitive does, so it leaves the rule to semi-naive search.
760
+ // A derived rule or an inspection may change, so neither is fixed.
761
+ fixed(goal) {
762
+ if (this.program.hasTemplates || this.program.inspectionEnabled) return false;
763
+ if (this.fixedKeys === undefined) {
764
+ this.fixedKeys = new Map();
765
+ this.concluded = new Set();
766
+ for (const clause of this.program.forward) for (const head of clause.heads) if (isCallable(head)) this.concluded.add(key(head));
767
+ }
768
+ const pending = [goal];
769
+ const visiting = new Set();
770
+ while (pending.length) {
771
+ const item = pending.pop();
772
+ if (!isCallable(item)) return false;
773
+ const goalKey = key(item);
774
+ if (CONTROL_KEYS.has(goalKey)) {
775
+ if (goalKey === 'findall/3' || goalKey === 'findall_sorted/3') pending.push(item.args[1]);
776
+ else for (const arg of item.args) pending.push(arg);
777
+ continue;
778
+ }
779
+ if (PRIMITIVE_KEYS.has(goalKey)) continue;
780
+ if (INSPECTION_KEYS.has(goalKey) || this.concluded.has(goalKey)) return false;
781
+ const known = this.fixedKeys.get(goalKey);
782
+ if (known === false) return false;
783
+ if (known === true || visiting.has(goalKey)) continue;
784
+ visiting.add(goalKey);
785
+ for (const clause of this.program.groups.get(goalKey) || NO_NODES) for (const body of clause.body) pending.push(body);
786
+ }
787
+ // Every key reached depends only on fixed keys, cycles included.
788
+ for (const goalKey of visiting) this.fixedKeys.set(goalKey, true);
789
+ return true;
790
+ }
791
+
756
792
  // The firings of a forward rule against the current state, in the
757
793
  // order a full search of its body finds them. After a rule's first search,
758
794
  // a rule whose body goals are answered by facts alone is searched
@@ -789,7 +825,9 @@ export class Solver {
789
825
  const prefix = this.context(clause, names, env);
790
826
  // The firings of one call share their duplicate check (see scan).
791
827
  this.pendingFirings = new Map();
792
- if (previous === null) return this.scan(clause, head, body, names, env, prefix).map(([found]) => found);
828
+ const joined = this.joinable(clause, keys);
829
+ const solve = joined ? () => this.join(body, keys, env) : () => this.solve(body, env);
830
+ if (previous === null) return this.scan(clause, head, body, names, env, prefix, solve).map(([found]) => found);
793
831
  const found = [];
794
832
  for (const delta of positions) {
795
833
  const window = keys.map((goalKey, i) => {
@@ -803,7 +841,7 @@ export class Solver {
803
841
  this.chosen = new Array(body.length).fill(null);
804
842
  try {
805
843
  // One push each: a scan can find more firings than a call takes arguments.
806
- for (const item of this.scan(clause, head, body, names, env, prefix)) found.push(item);
844
+ for (const item of this.scan(clause, head, body, names, env, prefix, solve)) found.push(item);
807
845
  } finally {
808
846
  this.window = this.windowGoals = this.chosen = null;
809
847
  }
@@ -833,7 +871,7 @@ export class Solver {
833
871
  const found = [];
834
872
  const env = new Env();
835
873
  const add = (fact) => {
836
- if (unify(goal, fact, env)) {
874
+ if (match(goal, fact, env)) {
837
875
  const conclusions = flattenConjunction(copyResolved(clause.head, env));
838
876
  const claim = conclusions.includes('true') ? copyResolved(goal, env) : null;
839
877
  found.push([conclusions, NO_NODES, NO_NODES, claim, null]);
@@ -854,6 +892,125 @@ export class Solver {
854
892
  return found;
855
893
  }
856
894
 
895
+ // Whether a rule's body goals that consult facts are answered by them
896
+ // alone: derived facts and ground source facts. Without a proof, templates
897
+ // or inspections, such a body is a join, and join() searches it without
898
+ // the search machine's frames and choice points.
899
+ joinable(clause, keys) {
900
+ if (this.recording || keys === null || clause.parentId !== null || clause.templates.length ||
901
+ clause.captures !== null || this.program.hasTemplates || this.program.inspectionEnabled) return false;
902
+ return keys.every((goalKey) => {
903
+ if (goalKey === null) return true;
904
+ let ground = this.groundCalls.get(goalKey);
905
+ if (ground === undefined) {
906
+ ground = (this.program.groups.get(goalKey) || []).every((candidate) => isGround(candidate.head));
907
+ this.groundCalls.set(goalKey, ground);
908
+ }
909
+ return ground;
910
+ });
911
+ }
912
+
913
+ // The solutions of a joinable body, as solve() finds them: each goal tries
914
+ // the derived facts in its window, through the best index, and then the
915
+ // source facts, counting inferences, serials and the alternatives chosen
916
+ // just as step() and retry() do. Any other goal is solved on its own, and
917
+ // its solutions are chosen in the order they come.
918
+ *join(goals, keys, env) {
919
+ const count = goals.length;
920
+ const windowed = this.window !== null && goals === this.windowGoals;
921
+ const stats = this.stats;
922
+ const levels = new Array(count);
923
+ const entry = env.mark();
924
+ let level = 0;
925
+ let entering = true;
926
+ try {
927
+ while (level >= 0) {
928
+ if (level === count) {
929
+ yield [env, NO_NODES];
930
+ level--;
931
+ entering = false;
932
+ continue;
933
+ }
934
+ const goal = goals[level];
935
+ if (keys[level] === null) {
936
+ if (entering) levels[level] = { solutions: this.solve([goal], env, 0), chosen: 0 };
937
+ const state = levels[level];
938
+ if (state.solutions.next().done) {
939
+ levels[level] = null;
940
+ level--;
941
+ entering = false;
942
+ } else {
943
+ if (windowed) this.chosen[level] = [0, state.chosen];
944
+ state.chosen++;
945
+ level++;
946
+ entering = true;
947
+ }
948
+ continue;
949
+ }
950
+ let state;
951
+ if (entering) {
952
+ if (++stats.inferences > this.maxInferences) throw new EyemindError('reasoning exceeded max_inferences');
953
+ if (windowed) this.chosen[level] = [0, 0];
954
+ const goalKey = keys[level];
955
+ const facts = this.facts.get(goalKey) || NO_NODES;
956
+ const order = this.factOrder(goal, env, goalKey);
957
+ let start = 0;
958
+ let stop = null;
959
+ let clauses;
960
+ if (windowed) {
961
+ const window = this.window[level];
962
+ start = window[0];
963
+ stop = window[1];
964
+ clauses = window[2] ? this.program.candidates(goal, env, goalKey) : NO_NODES;
965
+ } else {
966
+ clauses = this.program.candidates(goal, env, goalKey);
967
+ }
968
+ if (order === null) {
969
+ if (stop === null) stop = facts.length;
970
+ } else {
971
+ start = bisectLeft(order, start);
972
+ stop = stop === null ? order.length : bisectLeft(order, stop);
973
+ }
974
+ state = levels[level] = { mark: env.mark(), facts, order, next: start, stop, clauses, clause: 0 };
975
+ } else {
976
+ state = levels[level];
977
+ env.undo(state.mark);
978
+ }
979
+ let found = false;
980
+ while (state.next < state.stop) {
981
+ const index = state.order === null ? state.next : state.order[state.next];
982
+ state.next++;
983
+ if (match(goal, state.facts[index].goal, env)) {
984
+ if (windowed) this.chosen[level] = [0, index];
985
+ found = true;
986
+ break;
987
+ }
988
+ env.undo(state.mark);
989
+ }
990
+ while (!found && state.clause < state.clauses.length) {
991
+ const clause = state.clauses[state.clause++];
992
+ if (windowed) this.chosen[level] = [1, clause.id];
993
+ this.serial++;
994
+ if (match(goal, clause.head, env)) {
995
+ found = true;
996
+ break;
997
+ }
998
+ env.undo(state.mark);
999
+ }
1000
+ if (found) {
1001
+ level++;
1002
+ entering = true;
1003
+ } else {
1004
+ level--;
1005
+ entering = false;
1006
+ }
1007
+ }
1008
+ } finally {
1009
+ for (let i = count - 1; i >= 0; i--) levels[i]?.solutions?.return();
1010
+ env.undo(entry);
1011
+ }
1012
+ }
1013
+
857
1014
  // Whether a body goal, as the rule writes it, could match a fact derived
858
1015
  // since the rule's last search. The goal's own atoms and numbers narrow the
859
1016
  // facts down before the rule is renamed and searched.
@@ -885,13 +1042,69 @@ export class Solver {
885
1042
  // Bindings last only until the next answer is requested, and adding facts
886
1043
  // mid-scan would extend a live search, so each firing is copied out
887
1044
  // first and concluded afterwards.
888
- scan(clause, head, body, names, env, prefix) {
1045
+ scan(clause, head, body, names, env, prefix, solve) {
889
1046
  const found = [];
890
- for (const [answerEnv, nodes] of this.guarded(clause, body[body.length - 1], this.solve(body, env))) {
1047
+ // Without a proof, a firing that only concludes ground facts is the same
1048
+ // whichever of its duplicates publishes it. Keeping only the first in
1049
+ // publication order, and none whose facts are already known, bounds
1050
+ // memory by the new facts rather than the firings, as in a closure
1051
+ // where many firings derive each fact.
1052
+ const plain = !this.recording && !clause.templates.length && clause.guard === null && !this.program.inspectionEnabled;
1053
+ // Whether a firing with these keys, chosen so, would publish nothing:
1054
+ // its facts are known, or an earlier duplicate was chosen no later.
1055
+ const redundant = (keys, chosen) => {
1056
+ if (keys.every((k) => this.factKeys.has(k))) return true;
1057
+ const earlier = this.pendingFirings.get(keys.length === 1 ? keys[0] : keys.join('\u0000'));
1058
+ return earlier !== undefined && !(chosen !== null && earlier[1] !== null && compareChosen(chosen, earlier[1]) < 0);
1059
+ };
1060
+ const publish = (keys, firing, chosen) => {
1061
+ if (keys.every((k) => this.factKeys.has(k))) return;
1062
+ const id = keys.length === 1 ? keys[0] : keys.join('\u0000');
1063
+ const earlier = this.pendingFirings.get(id);
1064
+ if (earlier) {
1065
+ if (chosen !== null && earlier[1] !== null && compareChosen(chosen, earlier[1]) < 0) {
1066
+ earlier[0] = firing;
1067
+ earlier[1] = chosen;
1068
+ }
1069
+ return;
1070
+ }
1071
+ const entry = [firing, chosen];
1072
+ this.pendingFirings.set(id, entry);
1073
+ found.push(entry);
1074
+ };
1075
+ // The heads as the rule writes them, renamed: whether a firing is
1076
+ // redundant shows in the numbers its conclusions already have, without
1077
+ // copying them.
1078
+ const heads = plain ? flattenConjunction(head) : null;
1079
+ const known = heads !== null && !heads.includes('true') && !heads.includes('false');
1080
+ const numbers = known ? new Array(heads.length) : null;
1081
+ const numbered = (env) => {
1082
+ for (let i = 0; i < heads.length; i++) if ((numbers[i] = this.termIds.find(heads[i], env)) < 0) return false;
1083
+ return true;
1084
+ };
1085
+ for (const [answerEnv, nodes] of this.guarded(clause, body[body.length - 1], solve())) {
1086
+ if (known && numbered(answerEnv) && redundant(numbers, this.chosen)) continue;
891
1087
  const mark = answerEnv.mark();
1088
+ const resolved = copyResolved(head, answerEnv);
1089
+ if (plain) {
1090
+ // Ground conclusions, none of them true or false, need no Skolem
1091
+ // terms, claim or guard: their numbers are their keys.
1092
+ const conclusions = flattenConjunction(resolved);
1093
+ const keys = new Array(conclusions.length);
1094
+ let ground = true;
1095
+ for (let i = 0; i < conclusions.length && ground; i++) {
1096
+ const item = conclusions[i];
1097
+ keys[i] = item === 'true' || item === 'false' ? -1 : this.termIds.of(item);
1098
+ ground = keys[i] >= 0;
1099
+ }
1100
+ if (ground) {
1101
+ publish(keys, [conclusions, NO_NODES, NO_NODES, null, null], this.chosen !== null ? [...this.chosen] : null);
1102
+ answerEnv.undo(mark);
1103
+ continue;
1104
+ }
1105
+ }
892
1106
  // Head variables the body leaves unbound become Skolem terms, shared
893
1107
  // between the heads of one conclusion.
894
- const resolved = copyResolved(head, answerEnv);
895
1108
  const unresolved = variables(resolved);
896
1109
  const captured = clause.captures === null ? null : listFromItems(
897
1110
  clause.captures.map((name) => copyResolved(names.get(name), answerEnv)));
@@ -926,28 +1139,10 @@ export class Solver {
926
1139
  // A restricted firing keeps its guard, checked again once reasoning ends.
927
1140
  const guard = clause.guard === null || !unresolved.size ? null : copyResolved(body[body.length - 1], answerEnv);
928
1141
  const chosen = this.chosen !== null ? [...this.chosen] : null;
929
- // Without a proof, a firing that only concludes ground facts is the same
930
- // whichever of its duplicates publishes it. Keeping only the first in
931
- // publication order, and none whose facts are already known, bounds
932
- // memory by the new facts rather than the firings, as in a closure
933
- // where many firings derive each fact.
934
- const plain = !this.recording && !clause.templates.length && guard === null && claim === null && !this.program.inspectionEnabled &&
935
- conclusions.every((item) => item !== 'false' && isGround(item));
936
- if (plain) {
937
- const keys = conclusions.map((item) => this.factKey(item));
938
- if (keys.every((k) => this.factKeys.has(k))) { answerEnv.undo(mark); continue; }
939
- const id = keys.join('\u0000'), earlier = this.pendingFirings.get(id);
940
- if (earlier) {
941
- if (chosen !== null && earlier[1] !== null && compareChosen(chosen, earlier[1]) < 0) {
942
- earlier[0] = [conclusions, children, bindings, claim, guard];
943
- earlier[1] = chosen;
944
- }
945
- answerEnv.undo(mark);
946
- continue;
947
- }
948
- const entry = [[conclusions, children, bindings, claim, guard], chosen];
949
- this.pendingFirings.set(id, entry);
950
- found.push(entry);
1142
+ const keys = !this.recording && !clause.templates.length && guard === null && claim === null && !this.program.inspectionEnabled &&
1143
+ !conclusions.includes('false') ? conclusions.map((item) => this.termIds.of(item)) : null;
1144
+ if (keys !== null && !keys.includes(-1)) {
1145
+ publish(keys, [conclusions, children, bindings, claim, guard], chosen);
951
1146
  answerEnv.undo(mark);
952
1147
  continue;
953
1148
  }
@@ -1049,9 +1244,10 @@ export class Solver {
1049
1244
  // bodies and their observable order.
1050
1245
  for (const [clause, [conclusions, children, bindings, claim, guard]] of firings) {
1051
1246
  if (guard) this.guards.push([clause, guard, conclusions]);
1052
- const by = new Struct('clause', [BigInt(clause.id)]);
1053
- for (const [position, conclusion] of conclusions.entries()) {
1054
- const template = clause.templates.find((item) => item.position === position);
1247
+ const by = clause.citation ??= new Struct('clause', [BigInt(clause.id)]);
1248
+ for (let position = 0; position < conclusions.length; position++) {
1249
+ const conclusion = conclusions[position];
1250
+ const template = clause.templates.length ? clause.templates.find((item) => item.position === position) : undefined;
1055
1251
  if (template) {
1056
1252
  if (this.deriveRules(template, conclusion, bindings, children)) changed = true;
1057
1253
  continue;
@@ -1061,17 +1257,18 @@ export class Solver {
1061
1257
  if (!this.reported.has(claimId)) this.reported.set(claimId, [claim, children, clause.id]);
1062
1258
  continue;
1063
1259
  }
1064
- const node = new Node(conclusion, by, bindings, children, null, true);
1065
1260
  if (conclusion === 'false') {
1066
- this.derived.push(node);
1261
+ this.derived.push(new Node(conclusion, by, bindings, children, null, true));
1067
1262
  this.haltCode = 65;
1068
1263
  return 'halt';
1069
1264
  }
1070
- node.generic = this.program.inspectionEnabled && !isGround(conclusion);
1071
- const conclusionId = node.generic ? variant(conclusion) : this.factKey(conclusion);
1072
- const factKeys = node.generic ? this.genericKeys : this.factKeys;
1265
+ const generic = this.program.inspectionEnabled && !isGround(conclusion);
1266
+ const conclusionId = generic ? variant(conclusion) : this.factKey(conclusion);
1267
+ const factKeys = generic ? this.genericKeys : this.factKeys;
1073
1268
  if (factKeys.has(conclusionId)) continue;
1074
1269
  factKeys.add(conclusionId);
1270
+ const node = new Node(conclusion, by, bindings, children, null, true);
1271
+ node.generic = generic;
1075
1272
  this.addFact(key(conclusion), node);
1076
1273
  this.derived.push(node);
1077
1274
  this.stats.derived++;
package/src/formats.js CHANGED
@@ -20,7 +20,7 @@
20
20
  // The compiled program is ordinary LS: proofs, checking and --unused
21
21
  // apply to it. SRL execution functions capture a context that a saved proof
22
22
  // retains; compiling with that context reproduces the same program later.
23
- import { EyemindError, Struct, Var } from './terms.js';
23
+ import { EyemindError, Struct, Var, identity, isGround } from './terms.js';
24
24
  import { loadSources } from './lang.js';
25
25
  import { readTerms } from './reader.js';
26
26
  import { DEFAULT_GRAPH, parseRdf, rdfDocument, rdfFormat, writeRdf } from './rdf.js';
@@ -225,19 +225,26 @@ export function writeConclusions(loaded, result, { format, all = false, blankNod
225
225
  return resultToN3(loaded.compiled.doc, result, { mode: all ? 'all' : 'new', blankNodePrefix }).n3;
226
226
  }
227
227
  let quads;
228
- if (loaded.kind === 'srl') quads = srlQuads(loaded.compiled, srlAnswers(result), { all });
229
- else quads = conclusionQuads(result.answers, all ? loaded.text : null);
228
+ if (loaded.kind === 'srl') {
229
+ quads = srlQuads(loaded.compiled, srlAnswers(result), { all });
230
+ } else {
231
+ // Ground conclusions need not be written and read back.
232
+ const terms = result.conclusions?.every((term) => isGround(term)) ? result.conclusions : null;
233
+ quads = conclusionQuads(terms ?? result.answers, all ? loaded.text : null, [], terms !== null);
234
+ }
230
235
  return writeRdf(quads, { format, prefixes: loaded.kind === 'n3' ? Object.fromEntries(loaded.prefixes) : loaded.prefixes, blankNodePrefix });
231
236
  }
232
237
 
233
238
  // Conclusions that are triples, rdf/3 or result/3, or quads, rdf/4 or
234
239
  // result_rdf/4, as quads; given, the program's own rdf facts come first.
235
- function conclusionQuads(answers, given, facts = []) {
240
+ // The answers are terms, or else their texts, which name their variables as
241
+ // the run's answers do.
242
+ function conclusionQuads(answers, given, facts = [], terms = false) {
236
243
  const quads = [];
237
244
  const seen = new Set();
238
245
  const add = (t) => {
239
246
  const quad = t.args.length === 3 ? [...t.args, DEFAULT_GRAPH] : t.args;
240
- const key = quad.map((x) => (x === DEFAULT_GRAPH ? x : write(x))).join(' ');
247
+ const key = identity(new Struct('quad', quad));
241
248
  if (!seen.has(key)) {
242
249
  seen.add(key);
243
250
  quads.push(quad);
@@ -250,11 +257,11 @@ function conclusionQuads(answers, given, facts = []) {
250
257
  }
251
258
  for (const fact of facts) add(fact);
252
259
  for (const answer of answers) {
253
- const [[t]] = readTerms(answer);
260
+ const t = terms ? answer : readTerms(answer)[0][0];
254
261
  if (t === 'false') continue;
255
262
  const triple = t instanceof Struct && ['rdf', 'result', 'inf'].includes(t.name) && t.args.length === 3;
256
263
  const quad = t instanceof Struct && ['rdf', 'result_rdf'].includes(t.name) && t.args.length === 4;
257
- if (!triple && !quad) throw new EyemindError(`${answer} is no triple; write rdf(S, P, O) or rdf(S, P, O, G) conclusions, or leave out --to`);
264
+ if (!triple && !quad) throw new EyemindError(`${terms ? write(answer) : answer} is no triple; write rdf(S, P, O) or rdf(S, P, O, G) conclusions, or leave out --to`);
258
265
  add(t);
259
266
  }
260
267
  return quads;