eyemind 0.9.2 → 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/LS-SPEC.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  ```text
4
4
  Title: The Logic Script (LS) Language and Proof Format
5
- Version: eyemind 0.9.2
5
+ Version: eyemind 0.9.3
6
6
  ```
7
7
 
8
8
  This document specifies Logic Script (LS): the syntax and meaning of its
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "eyemind",
3
- "version": "0.9.2",
3
+ "version": "0.9.3",
4
4
  "description": "A dependency-free Logic Script (LS) reasoner with forward and backward reasoning, checkable proofs, and RDF 1.2, Notation3 (N3), SPARQL 1.2 RL (SRL) and Logical English (LE) interoperability.",
5
5
  "type": "module",
6
6
  "main": "./src/index.js",
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;
package/src/program.js CHANGED
@@ -36,6 +36,7 @@ export class Clause {
36
36
  this.scopeIds = [];
37
37
  this.extraTerms = [];
38
38
  this.renaming = null; // how to rename it apart, worked out once it is used often
39
+ this.citation = null; // clause(Id), cited by the facts it derives, made once it derives one
39
40
  this.uses = 0;
40
41
  this.witnessed = null;
41
42
  }
@@ -501,8 +502,14 @@ function stratify(clauses, stratifying) {
501
502
  const named = !(depGoal instanceof Var);
502
503
  if (!named) dynamic.add(clause.id);
503
504
  const candidates = named ? headCandidates(index.get(key(depGoal)), depGoal) : everyHead;
505
+ // A source fact depends on nothing, so its rank stays 0: one matching
506
+ // fact ranks the goal as all of them would.
507
+ let factMatched = false;
504
508
  for (const [candidateClause, head] of candidates) {
509
+ const fact = !candidateClause.forward && !candidateClause.body.length && candidateClause.parentId === null;
510
+ if (fact && factMatched) continue;
505
511
  if (unify(freshTerm(depGoal, 'dependency'), freshTerm(head, 'head'), new Env())) {
512
+ if (fact) factMatched = true;
506
513
  const edge = [clause.id, candidateClause.id, closed];
507
514
  edges.push(edge);
508
515
  if (!outgoing.has(clause.id)) outgoing.set(clause.id, []);
package/src/terms.js CHANGED
@@ -42,6 +42,9 @@ export class Struct {
42
42
  constructor(name, args) {
43
43
  this.name = name;
44
44
  this.args = args;
45
+ // The number the TermIds numbering gave this term, which never changes.
46
+ this.numbering = null;
47
+ this.number = -1;
45
48
  }
46
49
 
47
50
  *[Symbol.iterator]() {
@@ -278,6 +281,39 @@ export function unify(left, right, env) {
278
281
  return true;
279
282
  }
280
283
 
284
+ // Unify a term with a ground one, such as a fact. No variable can occur in a
285
+ // ground term, so this skips the occurs check, and every binding it makes
286
+ // is to a part of the ground term.
287
+ export function match(term, ground, env) {
288
+ const pending = [term, ground];
289
+ while (pending.length) {
290
+ const b = pending.pop();
291
+ let a = pending.pop();
292
+ if (a instanceof Var) a = deref(a, env);
293
+ if (a === b) continue;
294
+ if (a instanceof Var) {
295
+ env.bind(a, b);
296
+ } else if (a instanceof Struct) {
297
+ if (!(b instanceof Struct) || a.name !== b.name || a.args.length !== b.args.length) return false;
298
+ const argsA = a.args;
299
+ const argsB = b.args;
300
+ for (let i = argsA.length - 1; i >= 0; i--) {
301
+ const argA = argsA[i];
302
+ const argB = argsB[i];
303
+ if (argA === argB) continue;
304
+ if (!(argA instanceof Var) && !(argA instanceof Struct)) {
305
+ if (!sameConstant(argA, argB)) return false;
306
+ continue;
307
+ }
308
+ pending.push(argA, argB);
309
+ }
310
+ } else if (b instanceof Struct || !sameConstant(a, b)) {
311
+ return false;
312
+ }
313
+ }
314
+ return true;
315
+ }
316
+
281
317
  // Rename a term's variables apart. A subterm without variables is shared.
282
318
  // unique says no other variable of the run gets this suffix (see Var).
283
319
  export function freshTerm(term, suffix, names = new Map(), unique = false) {
@@ -482,6 +518,206 @@ export function identity(term) {
482
518
  return out.join('\u0001');
483
519
  }
484
520
 
521
+ // Small integers for ground terms, so that two terms get one number exactly
522
+ // when identity() keys them alike: hash-consing. Atoms and numbers are kept
523
+ // in maps; a compound is a row of name, arity and argument numbers in typed
524
+ // arrays, found again through an open-addressing table of row numbers, so
525
+ // keying a fact builds no string and no object. Integers, floats, 0.0 and
526
+ // -0.0 stay apart. A term holding a variable has no number: -1.
527
+ export class TermIds {
528
+ constructor() {
529
+ this.count = 0;
530
+ this.atoms = new Map();
531
+ this.ints = new Map();
532
+ this.floats = new Map();
533
+ this.negativeZero = -1;
534
+ // Rows of compounds, by number: name, arity and where their arguments
535
+ // start in args. Atoms and numbers have rows too, left unused.
536
+ this.names = new Int32Array(1024);
537
+ this.arities = new Int32Array(1024);
538
+ this.starts = new Int32Array(1024);
539
+ this.args = new Int32Array(4096);
540
+ this.used = 0;
541
+ // The table holds number + 1 of each compound, 0 marking a free slot.
542
+ this.table = new Int32Array(2048);
543
+ this.filled = 0;
544
+ this.stack = [];
545
+ this.ids = [];
546
+ }
547
+
548
+ next() {
549
+ const id = this.count++;
550
+ if (id === this.names.length) {
551
+ this.names = grown(this.names);
552
+ this.arities = grown(this.arities);
553
+ this.starts = grown(this.starts);
554
+ }
555
+ this.arities[id] = -1;
556
+ return id;
557
+ }
558
+
559
+ leaf(term) {
560
+ let map;
561
+ if (typeof term === 'string') map = this.atoms;
562
+ else if (typeof term === 'bigint') map = this.ints;
563
+ else if (Object.is(term, -0)) return this.negativeZero < 0 ? (this.negativeZero = this.next()) : this.negativeZero;
564
+ else map = this.floats;
565
+ let id = map.get(term);
566
+ if (id === undefined) map.set(term, id = this.next());
567
+ return id;
568
+ }
569
+
570
+ // The table slot of a compound with this name number and these argument
571
+ // numbers, the last arity entries of ids: the slot holding it, or the free
572
+ // slot it would take.
573
+ slot(nameId, arity, ids) {
574
+ const base = ids.length - arity;
575
+ let hash = Math.imul(nameId ^ 0x9e3779b9, 0x85ebca6b) ^ arity;
576
+ for (let i = base; i < ids.length; i++) hash = Math.imul(hash ^ ids[i], 0x01000193);
577
+ const mask = this.table.length - 1;
578
+ let slot = (hash ^ (hash >>> 15)) & mask;
579
+ for (let entry; (entry = this.table[slot]) !== 0; slot = (slot + 1) & mask) {
580
+ const id = entry - 1;
581
+ if (this.names[id] !== nameId || this.arities[id] !== arity) continue;
582
+ const start = this.starts[id];
583
+ let same = true;
584
+ for (let i = 0; i < arity && same; i++) same = this.args[start + i] === ids[base + i];
585
+ if (same) return slot;
586
+ }
587
+ return slot;
588
+ }
589
+
590
+ // The number of a compound with this name and these argument numbers,
591
+ // the last arity entries of ids, which it takes off.
592
+ compound(name, arity, ids) {
593
+ const nameId = this.leaf(name);
594
+ const base = ids.length - arity;
595
+ const slot = this.slot(nameId, arity, ids);
596
+ if (this.table[slot] !== 0) {
597
+ ids.length = base;
598
+ return this.table[slot] - 1;
599
+ }
600
+ const id = this.next();
601
+ this.names[id] = nameId;
602
+ this.arities[id] = arity;
603
+ while (this.used + arity > this.args.length) this.args = grown(this.args);
604
+ this.starts[id] = this.used;
605
+ for (let i = base; i < ids.length; i++) this.args[this.used++] = ids[i];
606
+ ids.length = base;
607
+ this.table[slot] = id + 1;
608
+ if (++this.filled * 2 > this.table.length) this.rehash();
609
+ return id;
610
+ }
611
+
612
+ rehash() {
613
+ const table = new Int32Array(this.table.length * 2);
614
+ const mask = table.length - 1;
615
+ for (const entry of this.table) {
616
+ if (entry === 0) continue;
617
+ const id = entry - 1;
618
+ const start = this.starts[id];
619
+ let hash = Math.imul(this.names[id] ^ 0x9e3779b9, 0x85ebca6b) ^ this.arities[id];
620
+ for (let i = 0; i < this.arities[id]; i++) hash = Math.imul(hash ^ this.args[start + i], 0x01000193);
621
+ let slot = (hash ^ (hash >>> 15)) & mask;
622
+ while (table[slot] !== 0) slot = (slot + 1) & mask;
623
+ table[slot] = entry;
624
+ }
625
+ this.table = table;
626
+ }
627
+
628
+ // The number a term has, read through env, without numbering anything: -1
629
+ // when it holds an unbound variable, -2 when it has no number yet.
630
+ find(term, env) {
631
+ const { stack, ids } = this;
632
+ stack.length = 0;
633
+ ids.length = 0;
634
+ stack.push(term, false);
635
+ while (stack.length) {
636
+ const done = stack.pop();
637
+ let item = stack.pop();
638
+ if (done) {
639
+ const nameId = this.atoms.get(item.name);
640
+ const arity = item.args.length;
641
+ const slot = nameId === undefined ? -1 : this.slot(nameId, arity, ids);
642
+ if (slot < 0 || this.table[slot] === 0) {
643
+ stack.length = 0;
644
+ return -2;
645
+ }
646
+ ids.length -= arity;
647
+ ids.push(this.table[slot] - 1);
648
+ continue;
649
+ }
650
+ if (item instanceof Var) {
651
+ item = deref(item, env);
652
+ if (item instanceof Var) {
653
+ stack.length = 0;
654
+ return -1;
655
+ }
656
+ }
657
+ if (item instanceof Struct) {
658
+ if (item.numbering === this) {
659
+ ids.push(item.number);
660
+ continue;
661
+ }
662
+ stack.push(item, true);
663
+ for (let i = item.args.length - 1; i >= 0; i--) stack.push(item.args[i], false);
664
+ continue;
665
+ }
666
+ let id;
667
+ if (typeof item === 'string') id = this.atoms.get(item);
668
+ else if (typeof item === 'bigint') id = this.ints.get(item);
669
+ else if (Object.is(item, -0)) id = this.negativeZero < 0 ? undefined : this.negativeZero;
670
+ else id = this.floats.get(item);
671
+ if (id === undefined) {
672
+ stack.length = 0;
673
+ return -2;
674
+ }
675
+ ids.push(id);
676
+ }
677
+ return ids.pop();
678
+ }
679
+
680
+ // The number of a ground term, or -1 when it holds a variable. Compounds
681
+ // are numbered after their arguments, without recursion, so a long list
682
+ // cannot overflow the stack.
683
+ of(term) {
684
+ if (!(term instanceof Struct)) return term instanceof Var ? -1 : this.leaf(term);
685
+ const { stack, ids } = this;
686
+ stack.length = 0;
687
+ ids.length = 0;
688
+ stack.push(term, false);
689
+ while (stack.length) {
690
+ const done = stack.pop();
691
+ const item = stack.pop();
692
+ if (done) {
693
+ const id = this.compound(item.name, item.args.length, ids);
694
+ item.numbering = this;
695
+ item.number = id;
696
+ ids.push(id);
697
+ } else if (item instanceof Struct) {
698
+ if (item.numbering === this) {
699
+ ids.push(item.number);
700
+ continue;
701
+ }
702
+ stack.push(item, true);
703
+ for (let i = item.args.length - 1; i >= 0; i--) stack.push(item.args[i], false);
704
+ } else if (item instanceof Var) {
705
+ stack.length = 0;
706
+ return -1;
707
+ } else {
708
+ ids.push(this.leaf(item));
709
+ }
710
+ }
711
+ return ids.pop();
712
+ }
713
+ }
714
+
715
+ function grown(array) {
716
+ const larger = new Int32Array(array.length * 2);
717
+ larger.set(array);
718
+ return larger;
719
+ }
720
+
485
721
  // The key an argument index files a term under: an atom or a number is its
486
722
  // own key, an IRI uses its string, and another small ground compound the text
487
723
  // of its structure. Signed zeros share a key, as they unify. A variable, a
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.9.2';
2
+ export const VERSION = '0.9.3';