eyemind 0.1.37 → 0.2.0

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
@@ -9,7 +9,7 @@ draws conclusions, and every conclusion can come with a proof that a separate
9
9
  checker verifies against your program. It runs as a command-line program, a
10
10
  JavaScript library, and a browser application, with no dependencies.
11
11
 
12
- - **[Playground](https://eyereasoner.github.io/eyemind/playground)**: run
12
+ - **[Playground](https://eyereasoner.github.io/eyemind/playground/)**: run
13
13
  programs in your browser.
14
14
  - **[Guide](https://eyereasoner.github.io/eyemind/GUIDE)**: run programs,
15
15
  write rules, check proofs, use the library, and develop eyemind.
@@ -18,8 +18,9 @@ JavaScript library, and a browser application, with no dependencies.
18
18
  - **[Examples](https://eyereasoner.github.io/eyemind/examples/)**:
19
19
  94 runnable programs, each with a card deck and saved conclusions, proofs
20
20
  and check reports.
21
- - **[Conformance suite](conformance/)**: 400 cases that test any
21
+ - **[Conformance suite](conformance/)**: 553 cases that test any
22
22
  implementation of the specification through its command line.
23
+ Run the suite [in your browser](https://eyereasoner.github.io/eyemind/playground/conformance).
23
24
 
24
25
  ```js
25
26
  fact(type('socrates', 'human'))
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.1.37
5
+ Version: eyemind 0.2.0
6
6
  ```
7
7
 
8
8
  This document specifies the syntax and meaning of eyemind programs and data
@@ -348,7 +348,7 @@ A clause MUST be rejected when:
348
348
 
349
349
  - a head is not an atom or compound;
350
350
  - a head uses `step/4` or `clause/2`, reserved for proof documents, or
351
- explicitly states `activated/2`, reserved for template activations;
351
+ explicitly states the reserved predicate `activated/2`;
352
352
  - a head is a primitive or control, except the head `'true'` of a query or
353
353
  `'false'` of a contradiction; `implies` MUST NOT conclude either atom;
354
354
  - a body goal is neither a variable, atom nor compound, or is an empty or
@@ -573,7 +573,7 @@ MUST be rejected. The conclusion MAY combine ordinary heads and several
573
573
  templates. Each template's
574
574
  body and head MAY themselves be conjunctions, written as arrays. A backward
575
575
  template with several heads defines one backward clause per head, sharing
576
- the same activation and body. Empty and open lists are not goals or heads.
576
+ the same captures and body. Empty and open lists are not goals or heads.
577
577
 
578
578
  A rule call embedded in another statement of the same program contributes
579
579
  only its rule value, not a standalone clause. This exclusion precedes clause
@@ -598,36 +598,54 @@ MUST be statically named; a variable in a term's argument is permitted, but a
598
598
  variable used as a goal is not. A forward template MAY conclude further inline
599
599
  templates. A backward template MUST NOT conclude templates.
600
600
 
601
- Template expansion is part of the language and precedes validation and
602
- stratification. Starting with all stated clauses, in clause order, replace
603
- each template conjunct,
604
- left to right, with `activated(N, Captures)`. `Captures` is a list of its
605
- captured variables in order of first occurrence in the template as written;
606
- `N` is the number of the first clause appended for it. Append a forward or
607
- backward clause as specified by the template, with the activation as its first
608
- body goal, followed by the template's body goals. A forward template keeps its
609
- head conjunction; a backward template appends one clause per head in order.
610
- Continue processing the appended clauses in order, lowering any nested
611
- templates the same way. Original clause numbers are kept; appended clauses
612
- are numbered consecutively after them and inherit the generator's source line.
613
- Each appended clause retains its capture list, including when its head
614
- contains another template.
601
+ Template compilation precedes validation and stratification. Starting with
602
+ all stated clauses in order, append a potential clause for each template,
603
+ left to right. Its body is the generating clause's full body followed by the
604
+ template's body; its head and direction are those of the template. A forward
605
+ template keeps its head conjunction; a backward template appends one clause
606
+ per head. Continue processing appended clauses in order, compiling nested
607
+ forward templates in the same way. Original clause numbers are kept;
608
+ appended clauses are numbered consecutively and inherit the generator's
609
+ source line. `forward` and `backward` are displayed as `implies` and
610
+ `implied_by`. The original generating clause retains its template heads.
615
611
 
616
612
  For example, `implies(cat(X), implies(dog(Y), test('yes')))` as the only
617
- stated clause gives these expanded clause displays:
613
+ stated clause has these displays:
618
614
 
619
615
  ```js
620
- clause(1, implies(cat(X), activated(2, [])))
621
- clause(2, implies([activated(2, []), dog(Y)], test('yes')))
616
+ clause(1, implies(cat(X), implies(dog(Y), test('yes'))))
617
+ clause(2, implies([cat(X), dog(Y)], test('yes')))
622
618
  ```
623
619
 
624
- `Y` stays local to the second clause. Its activation is required even though
625
- the template does not capture `X`. A generator with several solutions but
626
- identical captures enables the same rule instance. All potential generated
627
- clauses and their activation dependencies participate in Section 6.1,
628
- including clauses whose
629
- generators never fire. A closed dependency cycle MUST therefore be rejected
630
- even if its template would remain inactive.
620
+ The appended body describes the premises a certificate must justify. It is
621
+ not a prescription to reevaluate the generator when the appended rule is
622
+ called. During forward evaluation, each solution of the generator creates a
623
+ rule instance with its captures bound to that solution and its generator's
624
+ evidence retained. Identical captures of the same template create one
625
+ instance. The rule instance searches only the template's own body; a
626
+ backward caller cannot change how the generator's body was evaluated.
627
+ Template-local variables remain universal and are renamed apart on each use.
628
+ The run derives no synthetic enabling facts, and certificates have no
629
+ intermediate enabling steps: the generator's premises are direct uses of
630
+ the derived rule's step. A nested instance retains all enclosing premises.
631
+
632
+ For witness construction, a generating head's **scope projection** replaces
633
+ each template conjunct by the list of its captured variables, leaving ordinary
634
+ heads in place. These lists are compiler data and are never concluded as
635
+ facts. Only variables of this projection participate in that firing's witness
636
+ construction (Section 8.2). A witness introduced by the generator remains
637
+ shared across every use of the derived rule; a witness introduced by a derived
638
+ forward rule additionally depends on its captured context. An existential
639
+ variable is a feature of a forward rule, not a third rule direction.
640
+
641
+ All potential clauses participate in Section 6.1, including clauses whose
642
+ generators never succeed. Each appended clause has an open dependency on its
643
+ generator as well as the dependencies of its own body. Consequently, negation
644
+ and collection wait for both the generator and all potential rules they may
645
+ consult to finish. A closed dependency cycle MUST be rejected even if its
646
+ generator would never succeed. Only a forward clause can generate templates;
647
+ backward generators and backward templates that conclude templates are
648
+ rejected.
631
649
 
632
650
  ### 6.3 Source rule inspection
633
651
 
@@ -775,14 +793,19 @@ Goals are solved depth-first, left to right. A goal is solved, in order:
775
793
  goal; a rule's body is then solved in its place.
776
794
 
777
795
  Each clause attempt MUST rename its variables apart before unification.
796
+ An appended backward clause is eligible only through its derived instances,
797
+ tried in their creation order. Each instance binds its captures before its
798
+ head meets the goal, and searches only its own body.
778
799
 
779
800
  ### 8.2 Forward evaluation and witnesses
780
801
 
781
802
  Forward rules run stratum by stratum, in increasing rank (Section 6.1). Within
782
- a stratum, rounds are repeated until a round adds no new fact. In a round,
783
- each rule in clause order is renamed apart and its body solved against the
784
- current state; all solutions of the body are collected first, then each is
785
- concluded:
803
+ a stratum, rounds are repeated until a round adds no new fact or rule instance.
804
+ In a round, clauses run in clause order. An appended clause runs its derived
805
+ instances in the order they were created; a potential clause with no instance
806
+ is skipped. Each instance searches only its own body with its captures bound.
807
+ All instances of one clause search the same current state, and all solutions
808
+ are collected before any conclusion of that clause is published:
786
809
 
787
810
  - a head variable the solution leaves unbound is bound to a **Skolem term**
788
811
  `skolem(Rule, Variable, Arguments)`: `Rule` is the clause number of the
@@ -791,15 +814,15 @@ concluded:
791
814
  `Arguments` the list of
792
815
  the ground values the solution gives the heads' other variables, in order
793
816
  of their first occurrence in the heads. A Skolem term is thus a function of
794
- the activation: the rule and the instance of its heads. The same activation
817
+ the firing: the rule and the instance of its heads. The same firing
795
818
  gives the same terms, in any round and in any run, and different
796
- activations give different terms; variables shared between heads stay
819
+ firings give different terms; variables shared between heads stay
797
820
  shared. When several head variables stand for one term, the first of them
798
821
  in the heads names it, whichever way unification bound them. A variable
799
822
  that a value of the solution brought in, which no head variable stands
800
- for, keeps its own name when no other term of the activation has it; the
823
+ for, keeps its own name when no other term of the firing has it; the
801
824
  others take that name followed by the first of `1`, `2`, ... that is
802
- free, in order of first occurrence in the heads. A rule that keeps meeting new activations does
825
+ free, in order of first occurrence in the heads. A rule that keeps meeting new firings does
803
826
  not terminate (Section 8.3). Derived facts other than scoped inspection
804
827
  patterns (Section 6.3) are therefore ground. A
805
828
  checker verifies the Skolem terms of a proof (C8, Section 11.9);
@@ -807,14 +830,17 @@ concluded:
807
830
  once per distinct instance (by identity of canonical text);
808
831
  - a head `'false'` records the conclusion `'false'` and stops all reasoning
809
832
  with halt code 65;
833
+ - a template head derives a rule instance as specified in Section 6.2;
810
834
  - any other head is added as a derived fact unless an identical fact is
811
835
  already derived or is a ground fact of the program.
812
836
 
813
837
  When the run asks its own goals (Section 8.4), rules whose heads are all
814
838
  `'true'` are not run.
815
839
 
816
- For an appended forward clause of Section 6.2, prepend one element to
817
- `Arguments`: the grounded capture list of its activation. This distinguishes
840
+ For a generator, use its scope projection (Section 6.2) as its head when
841
+ constructing witnesses. For an appended forward clause of Section 6.2,
842
+ prepend one element to
843
+ `Arguments`: the grounded capture list of its rule instance. This distinguishes
818
844
  witnesses of different captured contexts even when a head does not mention
819
845
  those values. An empty capture list still contributes one element, `[]`.
820
846
  Original clauses, including generators, use the ordinary witness convention.
@@ -850,16 +876,15 @@ A run that concluded `'false'` has halt code 65; otherwise it has none.
850
876
 
851
877
  The conclusions of a run are, in order:
852
878
 
853
- 1. when it halted: every derived fact except template activations, in the order derived, ending with
879
+ 1. when it halted: every derived fact, in the order derived, ending with
854
880
  `'false'`;
855
881
  2. otherwise, when it was given goals: the reported instances of its goals;
856
882
  3. otherwise, when the program has a forward rule with a head `'true'`: the
857
883
  reported instances, in order of first report, which MAY be none;
858
- 4. otherwise: every derived fact except template activations, in the order derived.
884
+ 4. otherwise: every derived fact, in the order derived.
859
885
 
860
- An explicit goal MAY ask for an activation. Activations remain available as
861
- premises and proof steps. The
862
- `derived` statistic counts them as facts added during reasoning.
886
+ Rule instances are not facts and cannot be queried as enabling predicates.
887
+ The `derived` statistic counts only facts added during reasoning.
863
888
 
864
889
  The output of a run is a comment line saying which of these the conclusions
865
890
  are, followed by the canonical text (Section 9) of each conclusion, one per
@@ -1033,12 +1058,13 @@ Each argument of a multi-argument `fact` has its own `fact(Head)` display.
1033
1058
  Conjunctive query and contradiction bodies are displayed as separate goal
1034
1059
  arguments: `query([p(X), q(X)])` has display `query(p(X), q(X))`.
1035
1060
 
1036
- For a program with templates, displays show the deterministically lowered
1037
- clauses of Section 6.2, including activation heads and premises. The program
1038
- supplied to the checker MUST be lowered from the source as Section 6.2
1039
- requires; displays cannot authorize extra generated rules. Each use of a
1040
- generated clause requires its activation as the first use, with a justified
1041
- step of its own. All existing checks apply.
1061
+ For a program with templates, displays show the original generators and the
1062
+ potential appended clauses of Section 6.2. A derived rule's body includes all
1063
+ enclosing generator premises. The source program is the authority for its
1064
+ origin, captures and scope projections; a display cannot introduce a new
1065
+ rule. A reasoner displays the enclosing generators as well as the clauses its
1066
+ steps cite. Each derived rule step lists its generator's premise evidence
1067
+ before its own body evidence, with no intermediate enabling step.
1042
1068
 
1043
1069
  ### 10.3 Steps
1044
1070
 
@@ -1065,9 +1091,13 @@ order. `By` is one of:
1065
1091
  the program wrote it, to its value in this step: `{X: 'socrates'}`. A
1066
1092
  reasoner writes every variable of the clause, in the order the clause display
1067
1093
  first shows them (for `implies`, the premise first);
1068
- a checker MUST accept any subset, since the goal and uses determine the
1069
- rest. A primitive has no variables of its own, so `'builtin'` steps have
1070
- empty bindings.
1094
+ a checker MUST accept partial bindings when the goal and uses determine the
1095
+ omitted values needed by C1 and C8. Values needed only by an enclosing
1096
+ witness scope must be supplied when those terms do not determine them.
1097
+ A primitive has no variables of its own, so `'builtin'` steps have
1098
+ empty bindings. A derived clause's bindings also include variables of its
1099
+ enclosing generators' scope projections, so their witnesses can be checked.
1100
+ These variables are renamed together with the clause's head and full body.
1071
1101
 
1072
1102
  ## 11. Proof Checking
1073
1103
 
@@ -1098,8 +1128,13 @@ that afterwards the head is identical to `Goal` and each body goal to its
1098
1128
  use. A step's own terms MUST NOT need further instantiation to match: a
1099
1129
  source clause `same(X, X)` cannot justify `same('a', 'b')`.
1100
1130
 
1131
+ For a derived clause step, each enclosing generator MUST belong to the
1132
+ program. Its bindings may name variables of those generators' scope
1133
+ projections as well as of the clause itself. The checker renames these
1134
+ projections together with the clause before applying the bindings.
1135
+
1101
1136
  For a `source(N)` step, `N` MUST identify an eligible source rule of Section
1102
- 4.7. Bindings and uses MUST both be empty. The rule's inspection term,
1137
+ 6.3. Bindings and uses MUST both be empty. The rule's inspection term,
1103
1138
  renamed apart, MUST unify with `Goal` and resolve exactly
1104
1139
  to it without instantiating the step's own terms. This checks variable
1105
1140
  sharing as well as the rule's direction and structure. The source rule is
@@ -1155,8 +1190,8 @@ A boundary that is not refuted remains an obligation (Section 12).
1155
1190
  ### 11.8 C7 Relevance
1156
1191
 
1157
1192
  When goals were given and no claim is `'false'`, the questions are the goals.
1158
- Otherwise the questions are, for each forward rule, each head other than
1159
- `'true'` or a template activation, and the rule's body as a conjunction when one of its heads is
1193
+ Otherwise the questions are, for each forward rule, each ordinary head other
1194
+ than `'true'`, and the rule's body as a conjunction when one of its heads is
1160
1195
  `'true'` and no claim is `'false'`. Each claim MUST be an instance of a
1161
1196
  question. Each step MUST be reachable from a conjunct of a claim through the
1162
1197
  conjuncts of uses.
@@ -1180,6 +1215,13 @@ When a forward clause has any such variables, its full head under the step's
1180
1215
  substitution MUST be ground. A generic inspection pattern cannot share one
1181
1216
  existential witness across all its instances (Section 6.3).
1182
1217
 
1218
+ For a generator, use its scope projection (Section 6.2) as the head for this
1219
+ check. For every derived clause step, including a backward clause step, the
1220
+ checker MUST also perform C8 for each enclosing generator under the same
1221
+ substitution. A forged outer witness cannot be authorized by using it in a
1222
+ backward conclusion. Variables supplied by the instance's captures are not
1223
+ new witnesses of the derived clause.
1224
+
1183
1225
  For an appended forward clause of Section 6.2, prepend the capture list,
1184
1226
  instantiated under the step's substitution, as one element of `Args`, as
1185
1227
  required by Section 8.2. The checker MUST compute this from the source
@@ -1187,8 +1229,8 @@ template's capture list and the substitution, not from the witness term.
1187
1229
 
1188
1230
  A variable of the head that also occurs in the body is not checked by C8,
1189
1231
  even when the body leaves it unbound; its value comes from the uses, which
1190
- other conditions check. A step citing a rule without such variables is not
1191
- covered by C8.
1232
+ other conditions check. A step with no witnesses in its own forward head or enclosing generators is
1233
+ not covered by C8.
1192
1234
 
1193
1235
  ### 11.10 Counts and validity
1194
1236
 
@@ -1201,7 +1243,7 @@ covered by C8.
1201
1243
  | C5 re_decision | `'builtin'` and `'control'` steps that passed C5 |
1202
1244
  | C6 boundary_consistency | boundaries decided |
1203
1245
  | C7 relevance | claims plus steps |
1204
- | C8 witness_integrity | `clause` steps of forward rules with witnesses that passed C8 |
1246
+ | C8 witness_integrity | `clause` steps with witnesses in their forward head or enclosing generators that passed C8 |
1205
1247
 
1206
1248
  A check also counts the **steps** it read, the **claims**, the `clause` steps
1207
1249
  **verified** by C1, the `source` inspection steps also **verified** by C1,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "eyemind",
3
- "version": "0.1.37",
3
+ "version": "0.2.0",
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/common.js CHANGED
@@ -24,6 +24,7 @@ export function freshClause(clause, suffix, unique = false) {
24
24
  head = freshTerm(clause.head, suffix, names, unique);
25
25
  body = clause.body.map((goal) => freshTerm(goal, suffix, names, unique));
26
26
  }
27
+ for (const term of clause.extraTerms || []) freshTerm(term, suffix, names, unique);
27
28
  return [head, body, names];
28
29
  }
29
30
  const tag = String(suffix);
@@ -73,6 +74,7 @@ function workOut(clause) {
73
74
  collectNames([clause.head], index);
74
75
  const headCount = index.size;
75
76
  collectNames(clause.body, index);
77
+ collectNames(clause.extraTerms || [], index);
76
78
  const names = [...index.keys()];
77
79
  const pattern = compile(clause.head, index);
78
80
  const patterns = clause.body.map((goal) => compile(goal, index));
@@ -81,7 +83,7 @@ function workOut(clause) {
81
83
  // A forward rule is written premise first, implies(Body, Head), and its
82
84
  // variables are listed in that order.
83
85
  const order = new Map();
84
- collectNames([...clause.body, clause.head], order);
86
+ collectNames([...clause.body, clause.head, ...(clause.extraTerms || [])], order);
85
87
  written = [...order.keys()];
86
88
  }
87
89
  return {
package/src/engine.js CHANGED
@@ -5,7 +5,6 @@ import { goalTerm, subgoals } from './goals.js';
5
5
  import { INSPECTION_KEYS } from './inspection.js';
6
6
  import { checkRendered, clauseDisplay, renderProof } from './proof.js';
7
7
  import { CONTROL_KEYS, Program } from './program.js';
8
- import { isActivation } from './templates.js';
9
8
  import {
10
9
  Env, EyemindError, Struct, Var, conjunction, copyResolved, deref, flattenConjunction, freshTerm,
11
10
  identity, isAnonymous, isCallable, isGround, isGroundButAnonymous, isTerm, key, keyArity, listFromItems,
@@ -38,11 +37,12 @@ export class Node {
38
37
 
39
38
  // The step a frame's body will justify once it is finished.
40
39
  class Pending {
41
- constructor(goal, by, bindings, cut) {
40
+ constructor(goal, by, bindings, cut, prefix = NO_NODES) {
42
41
  this.goal = goal;
43
42
  this.by = by;
44
43
  this.bindings = bindings;
45
44
  this.cut = cut;
45
+ this.prefix = prefix;
46
46
  }
47
47
  }
48
48
 
@@ -130,8 +130,7 @@ function scopedVariables(nodes, env) {
130
130
 
131
131
  // A universal derived pattern is renamed together with its evidence at each
132
132
  // use. Renaming just its head would disconnect the certificate's variables.
133
- function freshNode(node, suffix) {
134
- const names = new Map();
133
+ function freshNode(node, suffix, names = new Map()) {
135
134
  const copies = new Map();
136
135
  const make = (source) => new Node(freshTerm(source.goal, suffix, names, true), source.by,
137
136
  source.bindings.map(([name, value]) => [name, freshTerm(value, suffix, names, true)]),
@@ -250,6 +249,7 @@ export function clausesBehindBoundaries(program, roots) {
250
249
  }
251
250
  for (const clause of byKey.get(goalKey) || []) {
252
251
  reached.add(clause.id);
252
+ for (const parent of clause.scopeIds) if (program.byId.has(parent)) reached.add(parent);
253
253
  for (const goal of clause.body) visit(goal);
254
254
  }
255
255
  }
@@ -295,6 +295,8 @@ export class Solver {
295
295
  this.chosen = null;
296
296
  this.snapshots = new Map();
297
297
  this.direct = new Map();
298
+ this.rules = new Map();
299
+ this.ruleKeys = new Map();
298
300
  this.maxInferences = options.maxInferences || 1000000;
299
301
  }
300
302
 
@@ -334,7 +336,7 @@ export class Solver {
334
336
  nodes = [...parent.nodes, ...frame.nodes];
335
337
  } else {
336
338
  const pending = frame.pending;
337
- nodes = [...parent.nodes, new Node(pending.goal, pending.by, pending.bindings, [...frame.nodes])];
339
+ nodes = [...parent.nodes, new Node(pending.goal, pending.by, pending.bindings, [...pending.prefix, ...frame.nodes])];
338
340
  }
339
341
  return new Frame(parent.goals, parent.index + 1, nodes, parent.parent, parent.pending, parent.depth);
340
342
  }
@@ -458,7 +460,7 @@ export class Solver {
458
460
  const [start, stop, withClauses] = this.window[frame.index];
459
461
  point = new Point('resolve', frame, env.mark(), goal, {
460
462
  facts: this.facts.get(goalKey) || NO_NODES,
461
- clauses: withClauses ? this.program.candidates(goal, env, goalKey) : NO_NODES,
463
+ clauses: withClauses ? this.candidates(goal, env, goalKey) : NO_NODES,
462
464
  start, stop, order: this.factOrder(goal, env, goalKey),
463
465
  });
464
466
  } else {
@@ -466,7 +468,7 @@ export class Solver {
466
468
  // while a search runs.
467
469
  point = new Point('resolve', frame, env.mark(), goal, {
468
470
  facts: this.facts.get(goalKey) || NO_NODES,
469
- clauses: this.program.candidates(goal, env, goalKey),
471
+ clauses: this.candidates(goal, env, goalKey),
470
472
  order: this.factOrder(goal, env, goalKey),
471
473
  });
472
474
  }
@@ -476,6 +478,50 @@ export class Solver {
476
478
  return next;
477
479
  }
478
480
 
481
+ candidates(goal, env, goalKey) {
482
+ const candidates = this.program.candidates(goal, env, goalKey);
483
+ if (!this.program.hasTemplates) return candidates;
484
+ if (!candidates.some((clause) => clause.parentId !== null)) return candidates;
485
+ return candidates.flatMap((clause) => clause.parentId === null ? [clause] : this.rules.get(clause.id) || NO_NODES);
486
+ }
487
+
488
+ // A derived rule's captures are bound before its head meets the caller.
489
+ // Its generator has already been solved; only its own body is searched.
490
+ context(clause, names, env) {
491
+ if (!clause.instance) return NO_NODES;
492
+ const instance = clause.instance;
493
+ const fresh = new Map();
494
+ for (const [name, value] of instance.bindings) {
495
+ if (names.has(name)) unify(names.get(name), instance.generic ? freshTerm(value, this.serial, fresh, true) : value, env);
496
+ }
497
+ return instance.generic ? instance.children.map((node) => freshNode(node, this.serial, fresh)) : instance.children;
498
+ }
499
+
500
+ deriveRules(template, captures, bindings, children) {
501
+ const first = template.ids[0];
502
+ let known = this.ruleKeys.get(first);
503
+ if (known === undefined) this.ruleKeys.set(first, known = new Set());
504
+ const generic = this.program.inspectionEnabled && !isGround(captures);
505
+ const id = generic ? variant(captures) : identity(captures);
506
+ if (known.has(id)) return false;
507
+ known.add(id);
508
+ // Ground captures cannot be changed by a caller. Their already-resolved
509
+ // generator evidence can be shared by every use of the derived rule.
510
+ if (!generic) for (const node of children) node.final = true;
511
+ let derived = false;
512
+ for (const ruleId of template.ids) {
513
+ const original = this.program.byId.get(ruleId);
514
+ if (!original) continue;
515
+ const rule = Object.create(original);
516
+ rule.instance = { bindings, children, generic };
517
+ let instances = this.rules.get(ruleId);
518
+ if (instances === undefined) this.rules.set(ruleId, instances = []);
519
+ instances.push(rule);
520
+ derived = true;
521
+ }
522
+ return derived;
523
+ }
524
+
479
525
  addFact(goalKey, node) {
480
526
  if (node.generic) this.genericPredicates.add(goalKey);
481
527
  let facts = this.facts.get(goalKey);
@@ -571,6 +617,18 @@ export class Solver {
571
617
  const clause = point.clauses[position - inWindow];
572
618
  if (windowed) this.chosen[point.frame.index] = [1, clause.id];
573
619
  this.serial++;
620
+ if (clause.instance) {
621
+ const [head, body, names] = freshClause(clause, this.serial, true);
622
+ const prefix = this.context(clause, names, env);
623
+ if (!unify(point.goal, head, env)) {
624
+ env.undo(point.mark);
625
+ continue;
626
+ }
627
+ const pending = recording
628
+ ? new Pending(point.goal, new Struct('clause', [BigInt(clause.id)]), [...names], null, prefix)
629
+ : QUIET;
630
+ return this.childFrame(point.frame, body.slice(clause.prefixLength), pending, point.frame.depth + 1);
631
+ }
574
632
  // The body is renamed only once the head unifies: many candidate
575
633
  // clauses of a goal fail on their head.
576
634
  const renamed = clause.renaming || renaming(clause);
@@ -613,11 +671,11 @@ export class Solver {
613
671
  // for other rules. Negations and collections consult lower strata only
614
672
  // (Section 6.1), so they do not change within one.
615
673
  directKeys(clause) {
616
- if (this.direct.has(clause.id)) return this.direct.get(clause.id);
674
+ if (this.direct.has(clause)) return this.direct.get(clause);
617
675
  let keys = [];
618
676
  // A forward rule's body goals are all callable: Program rejects numbers,
619
677
  // and stratification rejects variables a forward rule can reach.
620
- for (const goal of clause.body) {
678
+ for (const goal of clause.localBody) {
621
679
  const goalKey = key(goal);
622
680
  if (PRIMITIVE_KEYS.has(goalKey) || INSPECTION_KEYS.has(goalKey) || goalKey === 'not/1' || goalKey === 'findall/3') {
623
681
  keys.push(null);
@@ -628,27 +686,27 @@ export class Solver {
628
686
  keys.push(goalKey);
629
687
  }
630
688
  }
631
- this.direct.set(clause.id, keys);
689
+ this.direct.set(clause, keys);
632
690
  return keys;
633
691
  }
634
692
 
635
- // The activations of a forward rule against the current state, in the
693
+ // The firings of a forward rule against the current state, in the
636
694
  // order a full search of its body finds them. After a rule's first search,
637
695
  // a rule whose body goals are answered by facts alone is searched
638
- // semi-naively: only activations that use a fact derived since its last
696
+ // semi-naively: only firings that use a fact derived since its last
639
697
  // search can conclude anything new, so the body is searched once for each
640
698
  // goal that has such facts, that goal limited to them and the goals before
641
- // it to the older ones. The activations are then put back in the order a
699
+ // it to the older ones. The firings are then put back in the order a
642
700
  // full search would find them.
643
- activations(clause) {
701
+ firings(clause) {
644
702
  const keys = this.directKeys(clause);
645
703
  let now = null;
646
704
  let previous = null;
647
705
  if (keys !== null) {
648
706
  now = new Map();
649
707
  for (const goalKey of keys) if (goalKey) now.set(goalKey, (this.facts.get(goalKey) || NO_NODES).length);
650
- previous = this.snapshots.get(clause.id) || null;
651
- this.snapshots.set(clause.id, now);
708
+ previous = this.snapshots.get(clause) || null;
709
+ this.snapshots.set(clause, now);
652
710
  }
653
711
  let positions = null;
654
712
  if (previous !== null) {
@@ -656,13 +714,16 @@ export class Solver {
656
714
  keys.forEach((goalKey, i) => {
657
715
  if (goalKey && now.get(goalKey) > previous.get(goalKey)) positions.push(i);
658
716
  });
659
- if (!positions.some((i) => this.mayMatchNew(clause.body[i], keys[i], previous, now))) {
717
+ if (!positions.some((i) => this.mayMatchNew(clause.localBody[i], keys[i], previous, now))) {
660
718
  return []; // nothing derived since its last search can be used, so nothing new follows
661
719
  }
662
720
  }
663
721
  this.serial++;
664
- const [head, body, names] = freshClause(clause, this.serial, true);
665
- if (previous === null) return this.scan(clause, head, body, names).map(([found]) => found);
722
+ const [head, fullBody, names] = freshClause(clause, this.serial, true);
723
+ const body = fullBody.slice(clause.prefixLength);
724
+ const env = new Env();
725
+ const prefix = this.context(clause, names, env);
726
+ if (previous === null) return this.scan(clause, head, body, names, env, prefix).map(([found]) => found);
666
727
  const found = [];
667
728
  for (const delta of positions) {
668
729
  const window = keys.map((goalKey, i) => {
@@ -675,13 +736,13 @@ export class Solver {
675
736
  this.windowGoals = body;
676
737
  this.chosen = new Array(body.length).fill(null);
677
738
  try {
678
- found.push(...this.scan(clause, head, body, names));
739
+ found.push(...this.scan(clause, head, body, names, env, prefix));
679
740
  } finally {
680
741
  this.window = this.windowGoals = this.chosen = null;
681
742
  }
682
743
  }
683
744
  found.sort((a, b) => compareChosen(a[1], b[1]));
684
- return found.map(([activation]) => activation);
745
+ return found.map(([firing]) => firing);
685
746
  }
686
747
 
687
748
  // Whether a body goal, as the rule writes it, could match a fact derived
@@ -697,24 +758,25 @@ export class Solver {
697
758
  // Each solution of a renamed rule's body, as what it concludes, with the
698
759
  // alternatives its goals took when the body is searched in a window.
699
760
  // Bindings last only until the next answer is requested, and adding facts
700
- // mid-scan would extend a live search, so each activation is copied out
761
+ // mid-scan would extend a live search, so each firing is copied out
701
762
  // first and concluded afterwards.
702
- scan(clause, head, body, names) {
763
+ scan(clause, head, body, names, env, prefix) {
703
764
  const found = [];
704
- for (const [answerEnv, nodes] of this.solve(body)) {
765
+ for (const [answerEnv, nodes] of this.solve(body, env)) {
705
766
  const mark = answerEnv.mark();
706
767
  // Head variables the body leaves unbound become Skolem terms, shared
707
768
  // between the heads of one conclusion.
708
769
  const resolved = copyResolved(head, answerEnv);
709
770
  const unresolved = variables(resolved);
710
- const captured = clause.captures === null ? null : copyResolved(body[0].args[1], answerEnv);
771
+ const captured = clause.captures === null ? null : listFromItems(
772
+ clause.captures.map((name) => copyResolved(names.get(name), answerEnv)));
711
773
  const relevant = this.program.inspectionEnabled
712
774
  ? [...unresolved.keys(), ...(captured === null ? [] : variables(captured).keys())]
713
775
  : [];
714
776
  // Walking the evidence is linear in its size, so do it only when the
715
777
  // conclusion or captures still have variables an inspection could scope.
716
778
  if (relevant.length) {
717
- const scoped = scopedVariables(nodes, answerEnv);
779
+ const scoped = scopedVariables([...prefix, ...nodes], answerEnv);
718
780
  if (clause.witnessNames.length && relevant.some((name) => scoped.has(name))) {
719
781
  throw new EyemindError('bind inspected rule variables before deriving existential witnesses');
720
782
  }
@@ -732,9 +794,9 @@ export class Solver {
732
794
  let children = NO_NODES;
733
795
  let bindings = NO_NODES;
734
796
  if (this.recording) {
735
- children = nodes.map((node) => resolveNode(node, answerEnv));
736
- bindings = [...names].map(([name, value]) => [name, copyResolved(value, answerEnv)]);
797
+ children = [...prefix, ...nodes].map((node) => resolveNode(node, answerEnv));
737
798
  }
799
+ if (this.recording || clause.templates.length) bindings = [...names].map(([name, value]) => [name, copyResolved(value, answerEnv)]);
738
800
  const claim = conclusions.some((item) => item === 'true') ? copyResolved(conjunction(body), answerEnv) : null;
739
801
  found.push([[conclusions, children, bindings, claim], this.chosen !== null ? [...this.chosen] : null]);
740
802
  answerEnv.undo(mark);
@@ -762,10 +824,23 @@ export class Solver {
762
824
  if (rounds > maxIterations) throw new EyemindError('forward reasoning exceeded max_iterations');
763
825
  this.stats.rounds++;
764
826
  changed = false;
765
- for (const clause of rules) {
766
- if (!reporting && clause.heads.every((item) => item === 'true')) continue;
767
- for (const [conclusions, children, bindings, claim] of this.activations(clause)) {
768
- for (const conclusion of conclusions) {
827
+ for (const original of rules) {
828
+ const instances = original.parentId === null ? [original] : this.rules.get(original.id) || NO_NODES;
829
+ const firings = [];
830
+ for (const clause of instances) {
831
+ if (!reporting && clause.heads.every((item) => item === 'true')) continue;
832
+ for (const firing of this.firings(clause)) firings.push([clause, firing]);
833
+ }
834
+ // All instances of this template see the same state. Publishing one
835
+ // instance's conclusions during another's search changes recursive
836
+ // bodies and their observable order.
837
+ for (const [clause, [conclusions, children, bindings, claim]] of firings) {
838
+ for (const [position, conclusion] of conclusions.entries()) {
839
+ const template = clause.templates.find((item) => item.position === position);
840
+ if (template) {
841
+ if (this.deriveRules(template, conclusion, bindings, children)) changed = true;
842
+ continue;
843
+ }
769
844
  if (conclusion === 'true') {
770
845
  const claimId = this.program.inspectionEnabled ? variant(claim) : text(claim);
771
846
  if (!this.reported.has(claimId)) this.reported.set(claimId, [claim, children, clause.id]);
@@ -797,7 +872,7 @@ export class Solver {
797
872
  // The Skolem terms for the variables a solution leaves unbound in a rule's
798
873
  // heads: skolem(Rule, Variable, Arguments), a function of the rule, the
799
874
  // variable and the values the solution gave the heads' other variables. The
800
- // same activation thus always gives the same terms, and a different one
875
+ // same firing thus always gives the same terms, and a different one
801
876
  // different terms.
802
877
  export function skolemTerms(clause, head, unresolved, env, context = null) {
803
878
  const values = context === null ? [] : [context];
@@ -855,7 +930,7 @@ export class Result {
855
930
 
856
931
  // The derived facts as text, written only when asked for.
857
932
  get inferred() {
858
- return this.derived.filter((node) => !isActivation(node.goal)).map((node) => text(node.goal));
933
+ return this.derived.map((node) => text(node.goal));
859
934
  }
860
935
  }
861
936
 
@@ -932,7 +1007,6 @@ function reason(program, goalInputs, options) {
932
1007
  }
933
1008
  } else {
934
1009
  for (const node of solver.derived) {
935
- if (isActivation(node.goal)) continue;
936
1010
  roots.push(node);
937
1011
  claims.push(node.goal);
938
1012
  }
@@ -957,6 +1031,9 @@ function reason(program, goalInputs, options) {
957
1031
  if (used !== null && solver.haltCode === null && !goals.length) {
958
1032
  for (const [, , clauseId] of solver.reported.values()) used.add(clauseId);
959
1033
  }
1034
+ if (used !== null) {
1035
+ for (const id of [...used]) for (const parent of program.byId.get(id)?.scopeIds || []) used.add(parent);
1036
+ }
960
1037
  let report = null;
961
1038
  if (document !== null) {
962
1039
  // The generated proof is checked before it is returned.
package/src/goals.js CHANGED
@@ -4,7 +4,7 @@
4
4
  // is and(p(X), q(X)). A goal position is a statement's goal, an argument of
5
5
  // and, or, not, call or once, either part of a rule template, or the goal of
6
6
  // findall. Anywhere else an array is a list.
7
- import { EMPTY, Env, Struct, conjunction, properListItems } from './terms.js';
7
+ import { EMPTY, Env, EyemindError, Struct, Var, conjunction, properListItems } from './terms.js';
8
8
  import { readTerm } from './reader.js';
9
9
 
10
10
  const EMPTY_ENV = new Env();
@@ -32,8 +32,12 @@ function isList(term) {
32
32
  export function normalizeGoal(term) {
33
33
  if (isList(term)) {
34
34
  const items = properListItems(term, EMPTY_ENV);
35
- // An empty or open list stays a list; a goal position rejects it later.
36
- if (items === null || !items.length) return term;
35
+ if (items === null) {
36
+ let tail = term;
37
+ while (isList(tail) && tail !== EMPTY) tail = tail.args[1];
38
+ throw new EyemindError(tail instanceof Var ? 'an open list is not a goal' : 'an improper list is not a goal');
39
+ }
40
+ if (!items.length) throw new EyemindError('an empty array is not a goal');
37
41
  return conjunction(items.map(normalizeGoal));
38
42
  }
39
43
  if (!(term instanceof Struct)) return term;
@@ -61,5 +65,5 @@ export function readGoal(text) {
61
65
 
62
66
  // A goal given either as text or as a term already.
63
67
  export function goalTerm(goal) {
64
- return typeof goal === 'string' ? readGoal(goal) : goal;
68
+ return typeof goal === 'string' ? readGoal(goal) : normalizeGoal(goal);
65
69
  }
package/src/program.js CHANGED
@@ -1,6 +1,6 @@
1
1
  // A program: its clauses, validated, indexed and stratified.
2
2
  import { PRIMITIVE_KEYS } from './builtins.js';
3
- import { ACTIVATION_KEY, containsTemplate, expandTemplates } from './templates.js';
3
+ import { containsTemplate, expandTemplates } from './templates.js';
4
4
  import { subgoals } from './goals.js';
5
5
  import { hasInspection, inspectionTerm } from './inspection.js';
6
6
  import {
@@ -9,7 +9,7 @@ import {
9
9
  } from './terms.js';
10
10
 
11
11
  export const CONTROL_KEYS = new Set(['and/2', 'or/2', 'not/1', 'call/1', 'once/1', 'findall/3']);
12
- export const RESERVED_KEYS = new Set(['step/4', 'clause/2', ACTIVATION_KEY, 'implies/2', 'implied_by/2', 'forward/2', 'backward/2']);
12
+ export const RESERVED_KEYS = new Set(['step/4', 'clause/2', 'activated/2', 'implies/2', 'implied_by/2', 'forward/2', 'backward/2']);
13
13
 
14
14
  // The statements that state a forward rule, and how an error names them.
15
15
  const FORWARD_KINDS = { forward: 'a forward rule', query: 'query()', contradiction: 'contradiction()' };
@@ -25,6 +25,12 @@ export class Clause {
25
25
  this.forward = forward;
26
26
  this.line = line;
27
27
  this.captures = captures;
28
+ this.parentId = null;
29
+ this.prefixLength = 0;
30
+ this.localBody = body;
31
+ this.templates = [];
32
+ this.scopeIds = [];
33
+ this.extraTerms = [];
28
34
  this.renaming = null; // how to rename it apart, worked out once it is used often
29
35
  this.uses = 0;
30
36
  this.witnessed = null;
@@ -36,6 +42,7 @@ export class Clause {
36
42
  if (this.witnessed === null) {
37
43
  const inBody = new Set();
38
44
  for (const goal of this.body) for (const name of variables(goal).keys()) inBody.add(name);
45
+ for (const name of this.captures || []) inBody.add(name);
39
46
  this.witnessed = [...variables(this.head).keys()].filter((name) => !inBody.has(name));
40
47
  }
41
48
  return this.witnessed;
@@ -85,6 +92,7 @@ export class Program {
85
92
  constructor(sources, without = null) {
86
93
  this.sources = [...sources];
87
94
  const expanded = expandTemplates(this.sources);
95
+ this.hasTemplates = expanded.some((source) => source.parentId !== undefined);
88
96
  this.maxClauseId = expanded.length;
89
97
  this.clauses = [];
90
98
  this.byId = new Map();
@@ -122,12 +130,14 @@ export class Program {
122
130
  if (!stratifying && mayNeedStratifying(goal)) stratifying = true;
123
131
  }
124
132
  let headKey = null;
125
- for (const item of heads) {
133
+ const templatePositions = new Set((source.templates || []).map((item) => item.position));
134
+ for (const [position, item] of heads.entries()) {
135
+ if (templatePositions.has(position)) continue;
126
136
  if (!isCallable(item)) throw new EyemindError(`line ${source.line}: a head must be an atom or a compound term`);
127
137
  const itemKey = keys.of(item);
128
138
  headKey = itemKey;
129
139
  if (allowed.has(itemKey)) continue;
130
- if ((RESERVED_KEYS.has(itemKey) && itemKey !== ACTIVATION_KEY) ||
140
+ if (RESERVED_KEYS.has(itemKey) ||
131
141
  ((PRIMITIVE_KEYS.has(itemKey) || CONTROL_KEYS.has(itemKey)) &&
132
142
  !(forward && (item === 'true' || item === 'false')))) {
133
143
  throw new EyemindError(`line ${source.line}: unsupported or reserved head ${itemKey}`);
@@ -135,6 +145,17 @@ export class Program {
135
145
  allowed.add(itemKey);
136
146
  }
137
147
  const clause = new Clause(ordinal, source.head, forward ? heads : null, body, forward, source.line, source.captures ?? null);
148
+ clause.parentId = source.parentId ?? null;
149
+ clause.prefixLength = source.prefixLength ?? 0;
150
+ clause.localBody = clause.prefixLength ? body.slice(clause.prefixLength) : body;
151
+ clause.templates = source.templates || [];
152
+ clause.originalHead = source.originalHead ?? source.head;
153
+ clause.plainHeads = templatePositions.size ? heads.filter((_, position) => !templatePositions.has(position)) : heads;
154
+ for (let parent = clause.parentId; parent !== null;) {
155
+ clause.scopeIds.unshift(parent);
156
+ clause.extraTerms.unshift(expanded[parent - 1].head);
157
+ parent = expanded[parent - 1].parentId ?? null;
158
+ }
138
159
  this.clauses.push(clause);
139
160
  this.byId.set(ordinal, clause);
140
161
  if (forward) {
@@ -302,7 +323,7 @@ function mayNeedStratifying(goal) {
302
323
  function headIndex(clauses) {
303
324
  const index = new Map();
304
325
  for (const clause of clauses) {
305
- for (const head of clause.heads || [clause.head]) {
326
+ for (const head of clause.plainHeads) {
306
327
  const headKey = key(head);
307
328
  let entry = index.get(headKey);
308
329
  if (entry === undefined) {
@@ -339,9 +360,14 @@ function stratify(clauses, stratifying) {
339
360
  const dynamic = new Set();
340
361
  const index = headIndex(clauses);
341
362
  const everyHead = [];
342
- for (const clause of clauses) for (const head of clause.heads || [clause.head]) everyHead.push([clause, head]);
363
+ for (const clause of clauses) for (const head of clause.plainHeads) everyHead.push([clause, head]);
343
364
  for (const clause of clauses) {
344
- for (const goal of clause.body) {
365
+ if (clause.parentId !== null && ranks.has(clause.parentId)) {
366
+ const edge = [clause.id, clause.parentId, false];
367
+ edges.push(edge);
368
+ outgoing.set(clause.id, [edge]);
369
+ }
370
+ for (const goal of clause.localBody) {
345
371
  for (const [depGoal, closed] of dependencies(goal)) {
346
372
  const named = !(depGoal instanceof Var);
347
373
  if (!named) dynamic.add(clause.id);
package/src/proof.js CHANGED
@@ -14,7 +14,6 @@ import { goalTerm } from './goals.js';
14
14
  import { INSPECTION_KEYS, isInspection } from './inspection.js';
15
15
  import { CONTROL_KEYS, Program } from './program.js';
16
16
  import { readTerms } from './reader.js';
17
- import { isActivation } from './templates.js';
18
17
  import {
19
18
  Env, EyemindError, Struct, Var, conjunction, copyResolved, deref, flattenConjunction, freshTerm,
20
19
  isCallable, isGround, isTerm, key, listFromItems, properListItems, unify, variables,
@@ -27,13 +26,21 @@ function goalsDisplay(goals) {
27
26
  return goals.length === 1 ? goals[0] : listFromItems(goals);
28
27
  }
29
28
 
29
+ function templateDisplay(term) {
30
+ if (!(term instanceof Struct)) return term;
31
+ const name = term.args.length === 2 && term.name === 'forward' ? 'implies'
32
+ : term.args.length === 2 && term.name === 'backward' ? 'implied_by' : term.name;
33
+ return new Struct(name, term.args.map(templateDisplay));
34
+ }
35
+
30
36
  // A clause as the program states it.
31
37
  export function clauseDisplay(clause) {
32
38
  if (clause.forward) {
33
39
  // A query or a contradiction is displayed as the statement that wrote it.
34
40
  if (clause.head === 'true') return new Struct('query', clause.body);
35
41
  if (clause.head === 'false') return new Struct('contradiction', clause.body);
36
- return new Struct('implies', [goalsDisplay(clause.body), goalsDisplay(clause.heads)]);
42
+ const heads = flattenConjunction(clause.originalHead ?? clause.head);
43
+ return new Struct('implies', [goalsDisplay(clause.body), goalsDisplay(clause.templates.length ? heads.map(templateDisplay) : heads)]);
37
44
  }
38
45
  if (clause.body.length) return new Struct('implied_by', [clause.head, goalsDisplay(clause.body)]);
39
46
  return new Struct('fact', [clause.head]);
@@ -130,7 +137,11 @@ export function renderProof(program, claims, roots, checkable = false, heading =
130
137
  const nodeId = spellings.spell(node.goal);
131
138
  if (steps.has(nodeId)) continue;
132
139
  steps.set(nodeId, node);
133
- if (node.by instanceof Struct) cited.add(Number(node.by.args[0]));
140
+ if (node.by instanceof Struct) {
141
+ const id = Number(node.by.args[0]);
142
+ cited.add(id);
143
+ for (const parent of program.byId.get(id)?.scopeIds || []) cited.add(parent);
144
+ }
134
145
  for (let i = node.children.length - 1; i >= 0; i--) pending.push(node.children[i]);
135
146
  }
136
147
  // Variables are named A, B, ... in the order the document first shows
@@ -393,7 +404,7 @@ export const shortcuts = { flatResolution: true };
393
404
  // general unifier. Flat ground steps need neither renamed terms nor a
394
405
  // substitution trail: source variables can be matched directly.
395
406
  function flatResolution(clause, goal, bindings, uses) {
396
- if (clause.forward) return null;
407
+ if (clause.forward || clause.scopeIds.length) return null;
397
408
  const values = new Map();
398
409
  for (const binding of bindings) {
399
410
  if (!isTerm(binding, '=', 2) || typeof binding.args[0] !== 'string' || values.has(binding.args[0])) return false;
@@ -446,6 +457,10 @@ function checkResolution(program, step, fail, tally) {
446
457
  fail.add('C1', `unknown clause ${text(by)}`, goal);
447
458
  return false;
448
459
  }
460
+ if (clause.scopeIds.some((id) => !program.byId.has(id))) {
461
+ fail.add('C1', `missing generator of clause ${clauseId}`, goal);
462
+ return false;
463
+ }
449
464
  const flat = shortcuts.flatResolution ? flatResolution(clause, goal, bindings, uses) : null;
450
465
  if (flat !== null) {
451
466
  if (!flat) fail.add('C1', `not an instance of source clause ${clauseId}: ${text(goal)}`, goal);
@@ -476,7 +491,14 @@ function checkResolution(program, step, fail, tally) {
476
491
  if (matches && resolvesTo(candidate, env, goal) && body.every((item, i) => resolvesTo(item, env, uses[i]))) {
477
492
  resolution = true;
478
493
  // Any head the step can be an instance of decides; a verified witness wins.
479
- const found = clause.forward ? checkWitnesses(clause, head, names, env) : null;
494
+ let found = clause.forward ? checkWitnesses(clause, head, names, env) : null;
495
+ for (const parentId of clause.scopeIds) {
496
+ const parent = program.byId.get(parentId);
497
+ const scopeHead = freshTerm(parent.head, `check${clauseId}`, names);
498
+ const checked = checkWitnesses(parent, scopeHead, names, env);
499
+ if (checked === false) found = false;
500
+ else if (checked === true && found === null) found = true;
501
+ }
480
502
  if (found !== null && witnesses !== true) witnesses = found;
481
503
  }
482
504
  env.undo(mark);
@@ -485,7 +507,7 @@ function checkResolution(program, step, fail, tally) {
485
507
  fail.add('C1', `not an instance of source clause ${clauseId}: ${text(goal)}`, goal);
486
508
  return false;
487
509
  }
488
- if (witnesses === false) fail.add('C8', `not the witness of this firing of clause ${clauseId}: ${text(goal)}`, goal);
510
+ if (witnesses === false) fail.add('C8', `witnesses do not match the source scopes of clause ${clauseId}: ${text(goal)}`, goal);
489
511
  else if (witnesses === true) tally.witnessed++;
490
512
  return true;
491
513
  }
@@ -636,7 +658,7 @@ function checkRelevance(program, claims, steps, goals, fail, spellings) {
636
658
  if (clause.heads.some((head) => head === 'true')) {
637
659
  if (!halted && clause.body.length) questions.push(conjunction(clause.body));
638
660
  }
639
- for (const head of clause.heads) if (head !== 'true' && !isActivation(head)) questions.push(head);
661
+ for (const head of clause.plainHeads) if (head !== 'true') questions.push(head);
640
662
  }
641
663
  }
642
664
  for (const claim of claims) {
package/src/templates.js CHANGED
@@ -1,13 +1,11 @@
1
- // Inline rule templates become statically visible clauses whose first
2
- // premise records the generating activation. No rule is installed at run time.
1
+ // Compile every potential derived rule before validation and stratification.
2
+ // Generators derive scoped rule instances, rather than synthetic facts.
3
3
  import { RULE_NAMES, normalizeGoal, subgoals } from './goals.js';
4
4
  import { isInspection } from './inspection.js';
5
5
  import {
6
6
  EMPTY, EyemindError, Struct, Var, conjunction, flattenConjunction, isCallable, isTerm, listFromItems, variables,
7
7
  } from './terms.js';
8
8
 
9
- export const ACTIVATION_KEY = 'activated/2';
10
- export const isActivation = (term) => isTerm(term, 'activated', 2);
11
9
  const isTemplate = (term) => term instanceof Struct && term.args.length === 2 && RULE_NAMES.has(term.name);
12
10
 
13
11
  export function containsTemplate(term) {
@@ -42,28 +40,31 @@ function checkGoal(goal, line, generated = false) {
42
40
  export function expandTemplates(sources) {
43
41
  const expanded = [...sources];
44
42
  for (let index = 0; index < expanded.length; index++) {
45
- const source = expanded[index];
43
+ let source = expanded[index];
46
44
  for (const goal of source.body) checkGoal(goal, source.line, source.captures !== undefined);
47
45
  const heads = flattenConjunction(source.head);
48
46
  for (const head of heads) {
49
- if (isActivation(head)) throw new EyemindError(`line ${source.line}: activated/2 is reserved for generated rules`);
47
+ if (isTerm(head, 'activated', 2)) throw new EyemindError(`line ${source.line}: activated/2 is reserved`);
50
48
  }
51
49
  const templates = heads.filter(isTemplate);
52
50
  if (!templates.length) {
53
51
  if (containsTemplate(source.head)) {
54
52
  throw new EyemindError(`line ${source.line}: rule templates must be top-level conjuncts of an implies() conclusion`);
55
53
  }
54
+ expanded[index] = source;
56
55
  continue;
57
56
  }
58
57
  if (source.kind !== 'forward') {
59
58
  throw new EyemindError(`line ${source.line}: rule templates belong in an implies() conclusion`);
60
59
  }
60
+ source = { ...source, body: source.body.flatMap(flattenConjunction) };
61
61
  // Variables occurring outside a template are captured. Other variables
62
62
  // belong to that generated rule and are freshened by ordinary resolution.
63
63
  const outer = new Map();
64
64
  for (const goal of source.body) variables(goal, outer);
65
65
  for (const head of heads) if (!isTemplate(head)) variables(head, outer);
66
- const lowered = heads.map((head) => {
66
+ const derived = [];
67
+ const lowered = heads.map((head, position) => {
67
68
  if (!isTemplate(head)) {
68
69
  if (containsTemplate(head)) throw new EyemindError(`line ${source.line}: a rule template cannot be nested inside an ordinary term`);
69
70
  return head;
@@ -79,17 +80,23 @@ export function expandTemplates(sources) {
79
80
  const body = flattenConjunction(premise);
80
81
  for (const goal of body) checkGoal(goal, source.line, true);
81
82
  const captured = [...variables(head).values()].filter((variable) => outer.has(variable.name));
82
- const activation = new Struct('activated', [BigInt(expanded.length + 1), listFromItems(captured)]);
83
+ const rule = { position, ids: [], captures: captured.map((variable) => variable.name) };
83
84
  const conclusions = forward ? [conclusion] : flattenConjunction(conclusion);
84
85
  for (const generated of conclusions) {
86
+ rule.ids.push(expanded.length + 1);
85
87
  expanded.push({
86
- kind: forward ? 'forward' : 'backward', head: generated, body: [activation, ...body],
87
- line: source.line, file: source.file, captures: captured.map((variable) => variable.name),
88
+ kind: forward ? 'forward' : 'backward', head: generated, body: [...source.body, ...body],
89
+ line: source.line, file: source.file, captures: rule.captures,
90
+ parentId: index + 1, prefixLength: source.body.length,
88
91
  });
89
92
  }
90
- return activation;
93
+ derived.push(rule);
94
+ // Only captures belong to this firing's head. Template-local variables
95
+ // stay universal until a derived rule is used. This list is compiler
96
+ // data; it is never a fact or a goal of a certificate.
97
+ return listFromItems(captured);
91
98
  });
92
- expanded[index] = { ...source, head: conjunction(lowered) };
99
+ expanded[index] = { ...source, head: conjunction(lowered), originalHead: source.head, templates: derived };
93
100
  }
94
101
  return expanded;
95
102
  }
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.1.37';
2
+ export const VERSION = '0.2.0';