eyemind 0.5.13 → 0.5.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -7,7 +7,7 @@ eyemind is a **JavaScript rule language** with forward and backward reasoning an
7
7
 
8
8
  [Playground](https://eyereasoner.github.io/eyemind/playground/) · [Specification](https://eyereasoner.github.io/eyemind/SPEC) · [Conformance](https://eyereasoner.github.io/eyemind/conformance/) · [Examples](https://eyereasoner.github.io/eyemind/examples/)
9
9
 
10
- The playground runs programs in your browser; the specification defines the language, its canonical text, the proof format and the C1–C10 checks. The examples are 128 runnable programs, each with a card deck and saved conclusions, proofs and check reports. The conformance suite has 1356 cases that test any implementation of the specification through its command line; run it [in your browser](https://eyereasoner.github.io/eyemind/playground/conformance).
10
+ The playground runs programs in your browser; the specification defines the language, its canonical text, the proof format and the C1–C10 checks. The examples are 134 runnable programs, each with a card deck and saved conclusions, proofs and check reports. The conformance suite has 1363 cases that test any implementation of the specification through its command line; run it [in your browser](https://eyereasoner.github.io/eyemind/playground/conformance).
11
11
 
12
12
  ## Contents
13
13
 
@@ -120,6 +120,7 @@ Now add `fact(parent('carol', 'dave'))`, or remove a rule, and watch which answe
120
120
  | `fact(...Heads)` | Each head holds. |
121
121
  | `implies(Premise, Conclusion)` | A forward rule: whenever `Premise` holds, conclude `Conclusion`. |
122
122
  | `implied_by(Conclusion, Premise)` | A backward rule: `Conclusion` holds when `Premise` does, decided when a goal asks. |
123
+ | `restricted(Premise, Conclusion)` | A forward rule whose new values are made only where no known ones satisfy `Conclusion`. |
123
124
  | `query(...Body)` | Publish every instance of `Body` that holds. |
124
125
  | `contradiction(...Body)` | Stop with exit code 65 when `Body` holds: an integrity constraint. |
125
126
  | `facts_from(path)`, `facts_from({text})` | State every expression of a document as a fact, without running it. |
@@ -204,7 +205,44 @@ eyemind --program examples/family.n3 > /tmp/family.js # the compiled program,
204
205
  eyemind -c examples/family.n3 # a proof of it, checked
205
206
  ```
206
207
 
207
- Triples are `rdf(Subject, Predicate, Object)`, with IRIs, blank nodes and literals written as in the RDF table above. N3 integers and decimals become eyemind numbers; float and double literals retain their RDF datatype, including numbers written with an exponent. Decimals use binary64 storage; `math:sum` adds their canonical decimal values before rounding its result. `=>` becomes `implies`, `<=` becomes `implied_by`, `{ ... } => false` becomes `contradiction`, and scoped negation and collection become `not` and `findall`, so an N3 run has a proof that eyemind checks like any other. Derived rules can trigger inference fuses too.
208
+ Triples are `rdf(Subject, Predicate, Object)`, with IRIs, blank nodes and literals written as in the RDF table above. N3 integers and decimals become eyemind numbers; float and double literals retain their RDF datatype, including numbers written with an exponent. Decimals use binary64 storage; `math:sum` adds their canonical decimal values before rounding its result. `=>` becomes `implies`, or `restricted` when the conclusion has blank nodes of its own, `<=` becomes `implied_by`, `{ ... } => false` becomes `contradiction`, and scoped negation and collection become `not` and `findall`, so an N3 run has a proof that eyemind checks like any other. Derived rules can trigger inference fuses too.
209
+
210
+ Quoted formulas are graph terms, read as in D. Arndt and P.-A. Champin,
211
+ ["Notation3: Graph Terms for RDF"](https://arxiv.org/abs/2610.31266).
212
+ `@forAll` and `@forSome` declare IRIs as universal and existential variables
213
+ of the formula they open, before its first statement and with `@forAll`
214
+ first. A declaration reaches the formulas inside it unless one declares the
215
+ same IRI again. A `?x` belongs to the whole document, and a blank node to the
216
+ innermost formula that holds it. So `@forAll :x . :x :p :o .` and
217
+ `?x :says { ?x :is :wise } .` are facts about everything. A document
218
+ existential is one individual, in rules and quoted formulas alike. Within the
219
+ scope of universals it becomes a witness of them, so
220
+ `?x :loves _:y .` gives each individual its own beloved. A rule whose
221
+ conclusion has existentials is restricted: a firing makes Skolem witnesses
222
+ only where no known individuals satisfy the conclusion. A
223
+ conclusion that declares universals of its own becomes backward rules, which
224
+ state it for every individual, and `{ ... } => ?g .` asserts the formula bound
225
+ to `?g`.
226
+
227
+ A graph term is opaque: `owl:sameAs` does not rewrite it. It is closed and
228
+ compared as a set, up to a one-to-one renaming of its own variables, each
229
+ kind to its own kind. A rule's graph pattern therefore matches only formulas
230
+ with the same triples, and its own blank nodes match only the formula's own
231
+ blank nodes. A rule variable never stands for one of them, but it can stand
232
+ for a quoted universal, as rules stated as data quote their variables.
233
+ `log:includes` never instantiates the universals of its subject. Matching in
234
+ nested graph terms below the first level is by unification, so it depends on
235
+ the order of their triples. See
236
+ [universal instances](https://eyereasoner.github.io/eyemind/examples/deck/universal-instances),
237
+ [a shared existential](https://eyereasoner.github.io/eyemind/examples/deck/shared-existential),
238
+ [an existential rule](https://eyereasoner.github.io/eyemind/examples/deck/explicit-existential-rule),
239
+ [quantifier scopes](https://eyereasoner.github.io/eyemind/examples/deck/quantifier-scopes) and
240
+ [graph terms](https://eyereasoner.github.io/eyemind/examples/deck/graph-terms).
241
+
242
+ The Notation3 test suite case `static/success-literal-22.n3` expects the
243
+ pattern `{ _:X :B :C }` to match `{ :A :B :C }`. eyemind's scorer checks
244
+ instead that the conclusion is absent, because a quoted blank node is the
245
+ formula's own variable.
208
246
 
209
247
  N3 has no named-graph syntax. When RDF data joins an N3 run, eyemind represents
210
248
  each named graph as a quoted formula through `graph:content`, where `graph:`
@@ -351,10 +389,10 @@ The statement chooses the direction:
351
389
 
352
390
  | Strategy | Stated with | How it works |
353
391
  | --- | --- | --- |
354
- | **Forward** | `implies`, `query`, `contradiction` | From the facts, round after round, until a round adds nothing new. |
392
+ | **Forward** | `implies`, `restricted`, `query`, `contradiction` | From the facts, round after round, until a round adds nothing new. |
355
393
  | **Backward** | `implied_by`, `fact` | When a goal asks: depth-first, left to right, in the order the clauses are written. |
356
394
 
357
- Forward rules suit closures and classifications: `implies([path(X, Y), edge(Y, Z)], path(X, Z))` terminates on a cyclic graph. Backward rules suit computations driven by their inputs, such as arithmetic recursion and list processing. Backward chaining keeps no table of answers, so a backward rule that calls itself with the same goal runs until a bound stops it; such recursion belongs in a forward rule.
395
+ Forward rules suit closures and classifications: `implies([path(X, Y), edge(Y, Z)], path(X, Z))` terminates on a cyclic graph. A variable only a forward rule's conclusion mentions gets a fresh value, a Skolem term, for each firing. `restricted` makes one only where none is known: `restricted(human(X), [father(X, F), man(F)])` gives no new father to a human whose known father is a man. Its other rules run first in each stratum, and its proof shows each new value is needed, as the restricted chase of N. Küchenmeister, A. Ivliev, D. Arndt and M. Krötzsch, ["Stratified Negation in RDF Rules"](https://arxiv.org/abs/2607.28778), requires. Which firings it makes can depend on the order of rule applications, so call fidelity stays an obligation. Backward rules suit computations driven by their inputs, such as arithmetic recursion and list processing. Backward chaining keeps no table of answers, so a backward rule that calls itself with the same goal runs until a bound stops it; such recursion belongs in a forward rule.
358
396
 
359
397
  The two work together: a forward rule's premise can call a backward definition, and a backward goal sees the facts forward rules derived. Forward rules run stratum by stratum, so a negation or collection waits until everything it inspects is final. `--max-depth`, `--max-iterations` and `--max-inferences` bound a run, and exceeding one is an error, never a partial answer. [SPEC §8](https://eyereasoner.github.io/eyemind/SPEC#8-evaluation-and-conclusions) defines the details.
360
398
 
package/SPEC.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  ```text
4
4
  Title: The eyemind Rule Language and Proof Format
5
- Version: eyemind 0.5.13
5
+ Version: eyemind 0.5.14
6
6
  ```
7
7
 
8
8
  This document specifies the syntax and meaning of eyemind programs and data
@@ -413,12 +413,13 @@ The basic statement forms are:
413
413
  | `fact(T)` | State one fact with head `T` and no body. |
414
414
  | `implies(Body, Head)` | State a forward rule. `Body` is a goal or a non-empty array of goals; `Head` is one head or a non-empty array of heads. |
415
415
  | `implied_by(Head, Body)` | State a backward rule with one head. `Body` is a goal or a non-empty array of goals. |
416
+ | `restricted(Body, Head)` | State a restricted forward rule: as `implies`, but a firing whose heads some known values already satisfy is not applied ([Section 7.2](#72-variables-and-witnesses)). |
416
417
  | `query(G)` | Report the successful instances of `G`. An array denotes one conjunction. |
417
418
  | `contradiction(G)` | Halt with conclusion `'false'` when `G` succeeds. An array denotes one conjunction. |
418
419
  | `facts_from(Path)` | Read a document from a path and state one fact per expression. |
419
420
  | `facts_from({text: Text})` | Read a document from a string and state one fact per expression. |
420
421
 
421
- `implies` and `implied_by` require exactly two arguments. The variadic forms
422
+ `implies`, `implied_by` and `restricted` require exactly two arguments. The variadic forms
422
423
  of `fact`, `query` and `contradiction` are also defined:
423
424
 
424
425
  ```js
@@ -727,6 +728,11 @@ A program MUST be rejected when:
727
728
  Because dependencies compare whole terms, two relations sharing a predicate
728
729
  name MAY have different ranks.
729
730
 
731
+ The guard of a restricted rule ([Section 7.2](#72-variables-and-witnesses)) is a body goal whose
732
+ dependencies are open, though it is a negation: the rule ranks at least as
733
+ high as every clause that derives its heads, itself included, without a
734
+ closed dependency on itself.
735
+
730
736
  ### 6.2 Inline rule templates
731
737
 
732
738
  Nested `implies(Body, Head)` and `implied_by(Head, Body)` calls construct rule
@@ -876,6 +882,35 @@ unless it is a scoped inspection variable ([Section 6.3](#63-source-rule-inspect
876
882
  including captured template values. Body variables absent from that context
877
883
  do not distinguish witnesses; shared head variables share a witness.
878
884
 
885
+ A restricted rule, `restricted(Body, Head)`, with head-only variables
886
+ `W1, ..., Wk` has one more body goal after `Body`, its **guard**:
887
+
888
+ ```js
889
+ not([H1', ..., Hm', not_unify([_A1, ..., _Ak], [S1, ..., Sk])])
890
+ ```
891
+
892
+ `H1', ..., Hm'` are its heads with each `Wi` replaced by a distinct
893
+ anonymous variable `_Ai`, numbered `_0`, `_1`, ... as the first such names
894
+ the clause does not use; `Si` is `skolem(N, 'Wi', Frontier)`, the witness a
895
+ firing of clause `N` gives `Wi` ([Section 8.2](#82-forward-evaluation-and-witnesses)), where `Frontier` is the list of
896
+ the heads' other variables in order of first occurrence. The guard holds when
897
+ nothing but the firing's own witnesses satisfies its heads. Before a
898
+ firing, that is when no known values satisfy them, so a satisfied rule does
899
+ not invent new values, as the restricted chase does; after it, that is when
900
+ the firing's witnesses are needed, which the search certificate shows like
901
+ any negation. A restricted rule without head-only variables has no guard and
902
+ behaves as `implies`. For example:
903
+
904
+ ```js
905
+ fact(human('jo'), father('jo', 'bob'))
906
+ restricted(human(X), [father(X, F), man(F)])
907
+ implies(father(X, Y), man(Y))
908
+ ```
909
+
910
+ concludes `man('bob')` and invents no father for `'jo'`, since `'bob'`
911
+ already satisfies the heads once the third rule has run. A restricted
912
+ rule's display omits its guard ([Section 10.2](#102-clause-displays)).
913
+
879
914
  This gives the specified Skolemized reading of existential conclusions.
880
915
  The original existential rule need not have a least model over its original
881
916
  vocabulary. A witness is an ordinary compound in subsequent reasoning; it
@@ -1007,6 +1042,14 @@ and `p(2)` publishes `a(1)`, `b(1)`, `a(2)`, `b(2)`. For each head:
1007
1042
  When the run asks its own goals ([Section 8.4](#84-external-goals)), rules whose heads are all
1008
1043
  `'true'` are not run.
1009
1044
 
1045
+ A stratum with restricted rules alternates two kinds of round. Its other
1046
+ rules run in rounds as above; a round of its restricted rules, in clause
1047
+ order, follows only a round of the other rules that adds nothing, and is
1048
+ followed by rounds of the other rules again when it adds something. The
1049
+ stratum ends with a round of its restricted rules that adds nothing. The
1050
+ other rules of a stratum thus run before its restricted rules, whose guards
1051
+ see what they derive.
1052
+
1010
1053
  For a generator, use its scope projection ([Section 6.2](#62-inline-rule-templates)) as its head when
1011
1054
  constructing witnesses. For an appended forward clause of [Section 6.2](#62-inline-rule-templates),
1012
1055
  prepend one element to
@@ -1259,8 +1302,9 @@ A checker MUST treat every statement that is neither `clause/2`, `step/4`,
1259
1302
  ### 10.2 Clause displays
1260
1303
 
1261
1304
  `Display` shows clause `N` in normalized statement form: `fact(Head)`,
1262
- `implies(Body, Head)`, `implied_by(Head, Body)`, `query(G1, ...)` or
1263
- `contradiction(G1, ...)`, where `Body` is the clause's one body goal, or the
1305
+ `implies(Body, Head)`, `restricted(Body, Head)`, `implied_by(Head, Body)`,
1306
+ `query(G1, ...)` or `contradiction(G1, ...)`, where `Body` is the clause's
1307
+ one body goal without a restricted rule's guard, or the
1264
1308
  array of its body goals when it has several, `Head` likewise the head or the
1265
1309
  array of heads, and `G1, ...` are the body goals themselves. Displays are not
1266
1310
  authority: a checker MUST compare each with the program it checks against.
@@ -1984,6 +2028,9 @@ in that closure. To use a listing for C10:
1984
2028
  - Every backward head variable MUST be grounded by its body.
1985
2029
  - Every forward head variable MUST either be grounded by its body or be a
1986
2030
  head-only witness checked by C8.
2031
+ - A restricted rule's guard is a negation, so a closure with a restricted
2032
+ rule that has head-only variables is not supported: which firings a
2033
+ restricted rule makes can depend on the order of rule applications.
1987
2034
 
1988
2035
  Supported facts and closed listings then establish the least ground
1989
2036
  positive closure. More general forward execution requires publication
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "eyemind",
3
- "version": "0.5.13",
3
+ "version": "0.5.14",
4
4
  "description": "A dependency-free JavaScript rule language with forward and backward reasoning and checkable proofs.",
5
5
  "type": "module",
6
6
  "main": "./src/index.js",
package/src/engine.js CHANGED
@@ -818,7 +818,9 @@ export class Solver {
818
818
 
819
819
  // Run the forward rules to a fixpoint, one stratum after another. A rule
820
820
  // whose heads are all 'true' only publishes output; when the caller asks its
821
- // own question that output is discarded, so the rule is skipped.
821
+ // own question that output is discarded, so the rule is skipped. In a
822
+ // stratum, restricted rules run only in a round where the other rules
823
+ // derive nothing, so their guards see what those rules derive.
822
824
  forward(reporting = true) {
823
825
  const layers = new Map();
824
826
  for (const clause of this.program.forward) {
@@ -828,10 +830,17 @@ export class Solver {
828
830
  }
829
831
  const maxIterations = this.options.maxIterations || 1000;
830
832
  for (const rank of [...layers.keys()].sort((a, b) => a - b)) {
831
- const rules = layers.get(rank);
833
+ const all = layers.get(rank);
834
+ const restricted = all.filter((clause) => clause.restricted);
835
+ const ordinary = restricted.length ? all.filter((clause) => !clause.restricted) : all;
832
836
  let changed = true;
833
837
  let rounds = 0;
834
- while (changed) {
838
+ let lean = false;
839
+ while (changed || (!lean && restricted.length)) {
840
+ // After a round of the other rules that derives nothing, a round of
841
+ // the restricted ones; after one of those that derives nothing, done.
842
+ lean = !changed && restricted.length > 0;
843
+ const rules = lean ? restricted : ordinary;
835
844
  rounds++;
836
845
  if (rounds > maxIterations) throw new EyemindError('forward reasoning exceeded max_iterations');
837
846
  this.stats.rounds++;
package/src/lang.js CHANGED
@@ -193,13 +193,13 @@ class Builder {
193
193
 
194
194
  rule(name, args) {
195
195
  if (args.length !== 2) throw new EyemindError(`${name} takes 2 arguments, got ${args.length}`);
196
- const forward = name === 'implies';
196
+ const forward = name === 'implies' || name === 'restricted';
197
197
  const head = forward ? goalOf(args[1]) : toTerm(args[0]);
198
198
  const premise = goalOf(args[forward ? 0 : 1]);
199
199
  // Keep the returned value's anonymous variables untouched: each enclosing
200
200
  // clause names its own occurrences, including those inside templates.
201
201
  const value = new Struct(name, forward ? [premise, head] : [normalizeGoal(head), premise]);
202
- const source = this.add(forward ? 'forward' : 'backward', head, [premise]);
202
+ const source = this.add(name === 'restricted' ? 'restricted' : forward ? 'forward' : 'backward', head, [premise]);
203
203
  this.rules.set(value, source);
204
204
  return value;
205
205
  }
@@ -296,6 +296,7 @@ function exportsFor(io) {
296
296
  },
297
297
  implies: (...args) => active().rule('implies', args),
298
298
  implied_by: (...args) => active().rule('implied_by', args),
299
+ restricted: (...args) => active().rule('restricted', args),
299
300
  forward: (...args) => template('forward', args),
300
301
  backward: (...args) => template('backward', args),
301
302
  query: (...body) => builder.add('query', TRUE_ATOM, body.map(goalOf)),
@@ -462,7 +463,7 @@ function lineOffset() {
462
463
 
463
464
  const AT = '__eyemind_at__';
464
465
  const SCOPE = '__eyemind_scope__';
465
- const STATEMENT_NAMES = ['fact', 'implies', 'implied_by', 'query', 'contradiction', 'facts_from'];
466
+ const STATEMENT_NAMES = ['fact', 'implies', 'implied_by', 'restricted', 'query', 'contradiction', 'facts_from'];
466
467
  const STATEMENT_SET = new Set(STATEMENT_NAMES);
467
468
  const IDENTIFIER = /[A-Za-z0-9_$]/;
468
469
  // Words after which a slash starts a regular expression rather than a division.
@@ -181,6 +181,27 @@ implied_by(n3_not_includes(G, F), [is_nonvar(G), is_nonvar(F), findall('found',
181
181
  implied_by(n3_includes_(graph(Ts), graph(Ps)), n3_all_members(Ps, Ts))
182
182
  fact(n3_all_members([], _))
183
183
  implied_by(n3_all_members([P, ...Ps], Ts), [n3_member(P, Ts), n3_all_members(Ps, Ts)])`,
184
+ },
185
+ n3_unquote: {
186
+ needs: ['n3_member'],
187
+ text: `
188
+ // n3_unquote(G): the triples of the formula G hold.
189
+ implies([n3_unquote(graph(Ts)), n3_member(rdf(S, P, O), Ts)], rdf(S, P, O))`,
190
+ },
191
+ n3_graph_match: {
192
+ needs: ['n3_includes', 'n3_sort', 'n3_length'],
193
+ text: `
194
+ // n3_graph_match(G, P, Ls): the formula G holds the triples of the pattern P,
195
+ // as sets. Ls lists P's variables: e(V) its blank nodes and u(V) its
196
+ // universals, matched one to one by the formula's own, and f(V) the rule's
197
+ // variables, which no blank node of the formula can stand for. A rule's
198
+ // variable can stand for a quoted universal, as rules stated as data quote
199
+ // their variables.
200
+ implied_by(n3_graph_match(graph(Ts), graph(Ps), Ls), [n3_all_members(Ps, Ts), n3_all_members(Ts, Ps), n3_locals(Ls, [], _)])
201
+ implied_by(n3_locals([], Vs, Vs), [n3_sort(Vs, S), n3_length(Vs, N), n3_length(S, N)])
202
+ implied_by(n3_locals([e(V), ...R], A, Vs), [is_nonvar(V), unify(V, qbnode(_)), n3_locals(R, [V, ...A], Vs)])
203
+ implied_by(n3_locals([u(V), ...R], A, Vs), [is_nonvar(V), unify(V, qvar(_)), n3_locals(R, [V, ...A], Vs)])
204
+ implied_by(n3_locals([f(V), ...R], A, Vs), [once(or(is_var(V), not_unify(V, qbnode(_)))), n3_locals(R, A, Vs)])`,
184
205
  },
185
206
  n3_round: {
186
207
  text: `
package/src/n3-parser.js CHANGED
@@ -3,7 +3,8 @@
3
3
  // The parser accepts the N3 syntax used by rule programs: prefixes and base,
4
4
  // IRIs and prefixed names, literals with language or datatype, numbers and
5
5
  // booleans, blank nodes, collections, quoted formulas, universal variables,
6
- // the verbs a, =, =>, <=, has and is ... of, inverse <-, and the paths ! and ^.
6
+ // the explicit quantifiers @forAll and @forSome, the verbs a, =, =>, <=, has
7
+ // and is ... of, inverse <-, and the paths ! and ^.
7
8
  // It never evaluates anything; rules are triples whose predicate is
8
9
  // log:implies, log:impliedBy or log:query.
9
10
  //
@@ -12,7 +13,8 @@
12
13
  // { t: 'bnode', v, scope } a blank node, labelled within a formula scope
13
14
  // { t: 'literal', v, dt, lang, dir } a literal; dt is an IRI text
14
15
  // { t: 'int', v } / { t: 'float', v } numbers: a BigInt, a finite binary64
15
- // { t: 'var', v } a universal variable, ?name
16
+ // { t: 'var', v, scope? } a universal variable, ?name, or one
17
+ // @forAll declares in formula scope
16
18
  // { t: 'list', items } a collection
17
19
  // { t: 'graph', triples, scope } a quoted formula
18
20
  // { t: 'triple', s, p, o } an RDF 1.2 triple term
@@ -244,7 +246,9 @@ export function parseN3(src, { base = '', preserveNumericLiterals = false } = {}
244
246
  const prefixes = new Map();
245
247
  let bnodeCount = 0;
246
248
  let scopeCount = 0;
247
- const top = { id: 0, triples: [] };
249
+ const top = { id: 0, triples: [], parent: null, bound: new Map(), started: false, existential: false };
250
+ // Names for declared variables, apart from those the document writes.
251
+ const taken = new Set(toks.filter((t) => t.k === 'var' || t.k === 'bnode').map((t) => `${t.k}:${t.v}`));
248
252
  let scope = top;
249
253
  const peek = (k = 0) => toks[pos + k];
250
254
  const next = () => toks[pos++];
@@ -312,11 +316,46 @@ export function parseN3(src, { base = '', preserveNumericLiterals = false } = {}
312
316
  throw fail(`expected an IRI, found ${describe(tok)}`, tok);
313
317
  }
314
318
 
319
+ // @forAll and @forSome bind IRIs in their formula and the formulas it
320
+ // holds, unless an inner declaration binds the same IRI again. A universal
321
+ // is a variable, an existential a blank node of the declaring formula.
322
+ function quantifier() {
323
+ const tok = next();
324
+ const universal = tok.v === '@forAll';
325
+ if (scope.started) throw fail(`${tok.v} must precede the first statement of its formula`, tok);
326
+ if (universal && scope.existential) throw fail('@forAll must precede @forSome in the same formula', tok);
327
+ if (!universal) scope.existential = true;
328
+ for (;;) {
329
+ const t = peek();
330
+ const written = t.k === 'var' ? `'?${t.v}'` : t.k === 'bnode' ? `'_:${t.v}'` : describe(t);
331
+ if (t.k !== 'iri' && t.k !== 'pname') throw fail(`${tok.v} declares IRIs, as in ${tok.v} :x; found ${written}`, t);
332
+ const name = iriTerm().v;
333
+ if (scope.bound.has(name)) throw fail(`<${name}> is already quantified in this formula`, t);
334
+ const local = /[A-Za-z_][A-Za-z0-9_]*$/.exec(name.replace(/[#/]+$/, ''))?.[0] ?? 'q';
335
+ const kind = universal ? 'var' : 'bnode';
336
+ let v = local;
337
+ for (let k = 2; taken.has(`${kind}:${v}`); k++) v = `${local}_${k}`;
338
+ taken.add(`${kind}:${v}`);
339
+ scope.bound.set(name, { t: kind, v, scope: scope.id });
340
+ if (!isP(',')) break;
341
+ next();
342
+ }
343
+ if (scope === top) expectP('.');
344
+ else if (isP('.')) next();
345
+ else if (!isP('}')) throw fail(`expected '.' after ${tok.v}, found ${describe(peek())}`);
346
+ }
347
+
348
+ function quantified(t) {
349
+ for (let s = scope; s; s = s.parent) if (s.bound.has(t.v)) return s.bound.get(t.v);
350
+ return t;
351
+ }
352
+
315
353
  function term() {
316
354
  const tok = peek();
317
- if (tok.k === 'iri' || tok.k === 'pname') return iriTerm();
355
+ if (tok.k === 'iri' || tok.k === 'pname') return quantified(iriTerm());
318
356
  next();
319
- if (tok.k === 'var') return { t: 'var', v: tok.v };
357
+ // A ?variable belongs to the outermost formula (scope 0).
358
+ if (tok.k === 'var') return { t: 'var', v: tok.v, scope: 0 };
320
359
  if (tok.k === 'bnode') return { t: 'bnode', v: tok.v, scope: scope.id };
321
360
  if (tok.k === 'string') return literalTail(tok.v);
322
361
  if (tok.k === 'number') return numberTerm(tok.v, preserveNumericLiterals);
@@ -355,7 +394,7 @@ export function parseN3(src, { base = '', preserveNumericLiterals = false } = {}
355
394
  }
356
395
  if (isP('{', tok)) {
357
396
  const outer = scope;
358
- scope = { id: ++scopeCount, triples: [] };
397
+ scope = { id: ++scopeCount, triples: [], parent: outer, bound: new Map(), started: false, existential: false };
359
398
  while (!isP('}')) {
360
399
  if (peek().k === 'eof') throw fail("unterminated formula; expected '}'");
361
400
  if (statement(true) === 'directive') continue;
@@ -426,7 +465,11 @@ export function parseN3(src, { base = '', preserveNumericLiterals = false } = {}
426
465
  directive();
427
466
  return 'directive';
428
467
  }
429
- if (tok.k === 'word' && (tok.v === '@forAll' || tok.v === '@forSome')) throw fail(`${tok.v} is not supported; use ?variables and blank nodes`, tok);
468
+ if (tok.k === 'word' && (tok.v === '@forAll' || tok.v === '@forSome')) {
469
+ quantifier();
470
+ return 'directive';
471
+ }
472
+ scope.started = true;
430
473
  // { true } is the empty formula.
431
474
  if (inFormula && tok.k === 'word' && tok.v === 'true' && (isP('.', peek(1)) || isP('}', peek(1)))) { next(); return 'triples'; }
432
475
  const s = pathTerm();
package/src/n3.js CHANGED
@@ -4,13 +4,22 @@
4
4
  // own triples are facts, and a run concludes the triples its forward rules
5
5
  // derive that were not already facts. Rules become eyemind rules:
6
6
  //
7
- // { B } => { H }. implies(B, H) forward
8
- // { H } <= { B }. implied_by(H, B) backward, one per head triple
9
- // { B } log:query { H }. implies(B, result(H)) selects the output
10
- // { B } => false. contradiction(B) an inference fuse
7
+ // { B } => { H }. implies(B, H) forward; restricted(B, H)
8
+ // when H has blank nodes
9
+ // { H } <= { B }. implied_by(H, B) backward, one per head triple
10
+ // { B } log:query { H }. implies(B, result(H)) selects the output
11
+ // { B } => false. contradiction(B) an inference fuse
12
+ // { B } => ?G. implies(B, n3_unquote(G)) asserts the formula G
11
13
  //
12
14
  // A rule's ?variables and blank nodes are eyemind variables; a blank node
13
- // only the conclusion mentions is the Skolem term of that firing. Built-in
15
+ // only the conclusion mentions is the Skolem term of that firing. A variable
16
+ // @forAll declares for the document is a variable of each statement that
17
+ // mentions it, so a fact stating it is universal; an existential of the
18
+ // document is one individual, its witness a function of the universals it
19
+ // stands in their scope with. A conclusion with universals of its own states
20
+ // backward rules. A quoted formula is a graph term: its own blank nodes and
21
+ // universals are qbnode(Label) and qvar(Name), and a rule's graph pattern
22
+ // matches it as a set, up to a one-to-one renaming of those. Built-in
14
23
  // predicates of a body become goals defined in eyemind itself (builtins.mjs).
15
24
  import { run } from './engine.js';
16
25
  import { loadText } from './lang.js';
@@ -51,25 +60,26 @@ export function compileN3Document(doc, { source = 'input', documents = new Map()
51
60
  // Only a document that mentions rdf:first, rdf:rest or rdf:nil can write a
52
61
  // list out as triples, so only its built-ins read lists that way.
53
62
  const views = ['first', 'rest', 'nil'].some((name) => mentions(doc.triples, `${RDF_NS}${name}`));
63
+ const { triples, term: witnessed } = withWitnesses(doc.triples);
54
64
  const rulesAsTriples = doc.triples.some((x) => {
55
65
  if (x.p.t !== 'iri' || (!RULE_PREDICATES.has(x.p.v) && x.p.v !== `${LOG}query`) || !isFormulaLike(x.s) || !isFormulaLike(x.o)) return false;
56
66
  const body = triplesOf(x.p.v === `${LOG}impliedBy` ? x.o : x.s);
57
67
  return (x.p.v !== `${LOG}query` && variablePredicate(body)) || [...RULE_PREDICATES].some((p) => usesPredicate(body, p));
58
68
  });
59
- for (const triple of doc.triples) {
69
+ for (const triple of triples) {
60
70
  const p = triple.p.t === 'iri' ? triple.p.v : null;
61
71
  // A rule is also a triple of the document, its variables quoted, which
62
72
  // a rule predicate or a variable predicate can find.
63
73
  if (rulesAsTriples && RULE_PREDICATES.has(p) && isFormulaLike(triple.s) && isFormulaLike(triple.o)) facts.push(`fact(${new Context(false).rdf(triple)})`);
64
- if (p === `${LOG}implies` && isFormulaLike(triple.s) && isFormulaLike(triple.o)) {
65
- rules.push(compileRule(triple.s, triple.o, 'forward', needed, views, values));
74
+ if (p === `${LOG}implies` && isFormulaLike(triple.s) && (isFormulaLike(triple.o) || triple.o.t === 'var')) {
75
+ rules.push(compileRule(triple.s, triple.o, 'forward', needed, views, values, witnessed));
66
76
  } else if (p === `${LOG}impliedBy` && isFormulaLike(triple.s) && isFormulaLike(triple.o)) {
67
- rules.push(compileRule(triple.o, triple.s, 'backward', needed, views, values));
77
+ rules.push(compileRule(triple.o, triple.s, 'backward', needed, views, values, witnessed));
68
78
  } else if (p === `${LOG}query` && isFormulaLike(triple.s) && isFormulaLike(triple.o)) {
69
79
  queries++;
70
- rules.push(compileRule(triple.s, triple.o, 'query', needed, views, values));
80
+ rules.push(compileRule(triple.s, triple.o, 'query', needed, views, values, witnessed));
71
81
  } else {
72
- const ctx = new Context(false);
82
+ const ctx = new Context(false, true);
73
83
  facts.push(`fact(${ctx.rdf(triple)})`);
74
84
  }
75
85
  }
@@ -184,7 +194,7 @@ function fromEyemind(t) {
184
194
  const [a, b, c] = t.args;
185
195
  switch (`${t.name}/${t.args.length}`) {
186
196
  case 'iri/1': return { t: 'iri', v: a };
187
- case 'bnode/2': return { t: 'bnode', v: b, scope: 0 };
197
+ case 'bnode/2': return { t: 'bnode', v: typeof b === 'string' ? b : write(t), scope: 0 };
188
198
  case 'skolem/3': return { t: 'bnode', v: write(t), scope: 0 };
189
199
  case 'qvar/1': return { t: 'var', v: a };
190
200
  case 'qbnode/1': return { t: 'bnode', v: a, scope: 0 };
@@ -308,10 +318,64 @@ function libraryText(needed) {
308
318
  return out.join('\n');
309
319
  }
310
320
 
321
+ // The document's blank nodes, at any depth, as witness terms: { t: 'witness',
322
+ // label, deps }, deps the universals @forAll declares for the document that
323
+ // statements connected through such blank nodes mention, in order. Without
324
+ // any, a witness is the blank node itself. Returns { triples, term }, term
325
+ // rewriting any term of the document the same way.
326
+ function withWitnesses(triples) {
327
+ const isOwn = (t) => (t.t === 'bnode' || t.t === 'var') && t.scope === 0;
328
+ const owns = triples.map((x) => {
329
+ const own = [];
330
+ const visit = (t) => {
331
+ if (isOwn(t)) own.push(t);
332
+ else if (t.t === 'list') t.items.forEach(visit);
333
+ else if (t.t === 'graph') t.triples.forEach((y) => [y.s, y.p, y.o].forEach(visit));
334
+ else if (t.t === 'triple') [t.s, t.p, t.o].forEach(visit);
335
+ };
336
+ [x.s, x.p, x.o].forEach(visit);
337
+ return own;
338
+ });
339
+ if (!owns.some((own) => own.length)) return { triples, term: (t) => t };
340
+ const parent = new Map();
341
+ const find = (k) => {
342
+ let root = k;
343
+ while (parent.get(root) !== root) root = parent.get(root);
344
+ for (let next; k !== root; k = next) { next = parent.get(k); parent.set(k, root); }
345
+ return root;
346
+ };
347
+ const universals = new Map();
348
+ // Only a document that declares universals connects its blank nodes.
349
+ const declared = owns.some((own) => own.some((t) => t.t === 'var'));
350
+ for (const own of declared ? owns : []) {
351
+ const blanks = own.filter((t) => t.t === 'bnode').map(bnodeKey);
352
+ for (const k of blanks) if (!parent.has(k)) { parent.set(k, k); universals.set(k, new Map()); }
353
+ for (const k of blanks.slice(1)) {
354
+ const [a, b] = [find(blanks[0]), find(k)];
355
+ if (a !== b) { parent.set(b, a); for (const [key, v] of universals.get(b)) universals.get(a).set(key, v); }
356
+ }
357
+ if (blanks.length) for (const t of own) if (t.t === 'var') universals.get(find(blanks[0])).set(t.v, t);
358
+ }
359
+ const term = (t) => {
360
+ if (t.t === 'bnode' && t.scope === 0) {
361
+ const deps = declared ? [...universals.get(find(bnodeKey(t))).values()] : [];
362
+ return { t: 'witness', label: bnodeLabel(t), deps };
363
+ }
364
+ if (t.t === 'list') return { ...t, items: t.items.map(term) };
365
+ if (t.t === 'graph') return { ...t, triples: t.triples.map(triple) };
366
+ if (t.t === 'triple') return triple(t);
367
+ return t;
368
+ };
369
+ const triple = (x) => ({ ...x, s: term(x.s), p: term(x.p), o: term(x.o) });
370
+ return { triples: triples.map((x, i) => (owns[i].length ? triple(x) : x)), term };
371
+ }
372
+
311
373
  // Naming for one clause: variables for ?names and, in rules, blank nodes.
374
+ // A fact's universals are the variables @forAll declares for the document.
312
375
  class Context {
313
- constructor(inRule) {
376
+ constructor(inRule, universals = false) {
314
377
  this.inRule = inRule;
378
+ this.universals = universals;
315
379
  this.names = new Map();
316
380
  this.used = new Set();
317
381
  this.anonymous = new Set();
@@ -346,10 +410,15 @@ class Context {
346
410
  switch (t.t) {
347
411
  case 'iri': return `iri(${q(t.v)})`;
348
412
  // Outside rules a variable belongs to a quoted formula: a constant.
349
- case 'var': return this.inRule ? this.name(`v:${t.v}`, t.v) : `qvar(${q(t.v)})`;
413
+ case 'var': return this.inRule || (this.universals && t.scope === 0) ? this.name(`v:${t.v}`, t.v) : `qvar(${q(t.v)})`;
414
+ case 'witness':
415
+ return t.deps.length ? `bnode('n3', [${[q(t.label), ...t.deps.map((x) => this.term(x))].join(', ')}])` : `bnode('n3', ${q(t.label)})`;
350
416
  case 'bnode':
351
417
  if (this.inRule) return this.name(bnodeKey(t), `B${t.v.replace(/^#/, '')}`);
352
- return `bnode('n3', ${q(bnodeLabel(t))})`;
418
+ // A quoted formula's own blank node is a variable of that formula.
419
+ return t.scope === 0 ? `bnode('n3', ${q(bnodeLabel(t))})` : `qbnode(${q(bnodeLabel(t))})`;
420
+ case 'local': return `${t.kind}(${q(t.label)})`;
421
+ case 'compiled': return t.text;
353
422
  case 'int': return t.v >= -(2n ** 53n) && t.v <= 2n ** 53n ? String(t.v) : `${t.v}n`;
354
423
  case 'float': return `float(${Object.is(t.v, -0) ? '-0' : String(t.v)})`;
355
424
  case 'literal':
@@ -374,6 +443,7 @@ const bnodeLabel = (t) => (t.scope === 0 ? t.v : `${t.v}.${t.scope}`);
374
443
  function keysOf(t, out = new Set()) {
375
444
  if (t.t === 'var') out.add(`v:${t.v}`);
376
445
  else if (t.t === 'bnode') out.add(bnodeKey(t));
446
+ else if (t.t === 'witness') t.deps.forEach((x) => keysOf(x, out));
377
447
  else if (t.t === 'list') t.items.forEach((x) => keysOf(x, out));
378
448
  else if (t.t === 'graph') t.triples.forEach((x) => keysOfTriple(x, out));
379
449
  else if (t.t === 'triple') keysOfTriple(t, out);
@@ -455,7 +525,7 @@ function takesList(p, position) {
455
525
  }
456
526
  const SCOPED_OBJECT = new Set([`${LOG}collectAllIn`, `${LOG}forAllIn`]);
457
527
 
458
- function compileRule(body, head, kind, needed, views = true, values = []) {
528
+ function compileRule(body, head, kind, needed, views = true, values = [], witnessed = (t) => t) {
459
529
  const ctx = new Context(true);
460
530
  if (!isFormulaLike(body)) throw new N3CompileError('a rule premise must be a formula');
461
531
  const bodyTriples = triplesOf(body);
@@ -493,7 +563,7 @@ function compileRule(body, head, kind, needed, views = true, values = []) {
493
563
 
494
564
  function goal(x, negated) {
495
565
  const p = x.p.t === 'iri' ? x.p.v : null;
496
- if (p === null) return [ctx.rdf(x)];
566
+ if (p === null) return pattern(x, negated);
497
567
  if (UNSUPPORTED.has(p)) throw new N3CompileError(`${shortName(p)} is not supported: eyemind has no ${UNSUPPORTED.get(p)}`);
498
568
  if (SCOPED_SUBJECT.has(p)) {
499
569
  const neg = p === `${LOG}notIncludes`;
@@ -512,7 +582,14 @@ function compileRule(body, head, kind, needed, views = true, values = []) {
512
582
  return neg ? [`not(${conj(inner)})`] : inner;
513
583
  }
514
584
  needed.add('n3_includes');
515
- return [`${neg ? 'n3_not_includes' : 'n3_includes'}(${ctx.term(x.s)}, graph([${x.o.triples.map((y) => ctx.rdf(y)).join(', ')}]))`];
585
+ // The subject's own variables stand for themselves: inclusion never
586
+ // instantiates them. The object's universals are the subject's.
587
+ const subject = x.s.t === 'graph' ? quotedLocals(x.s) : x.s;
588
+ const call = `${neg ? 'n3_not_includes' : 'n3_includes'}(${ctx.term(subject)}, graph([${x.o.triples.map((y) => ctx.rdf(y)).join(', ')}]))`;
589
+ const universals = graphLocals(x.o).filter((l) => l.kind === 'u');
590
+ if (neg || !universals.length) return [call];
591
+ needed.add('n3_graph_match');
592
+ return [call, `n3_locals([${universals.map((l) => `u(${ctx.term(l.term)})`).join(', ')}], [], _)`];
516
593
  }
517
594
  if (SCOPED_OBJECT.has(p)) {
518
595
  // A call supplied as data is specialized to the stated values. Its
@@ -526,7 +603,12 @@ function compileRule(body, head, kind, needed, views = true, values = []) {
526
603
  : t.t === 'var' ? { ...t, v: `call${call}.${i}.${t.v}` }
527
604
  : t.t === 'list' ? { ...t, items: t.items.map(own) }
528
605
  : t.t === 'graph' ? { ...t, triples: t.triples.map((y) => ({ s: own(y.s), p: own(y.p), o: own(y.o) })) } : t;
529
- return conj([`unify(${ctx.term(x.s)}, ${new Context(false).term(term)})`, ...goal({ ...x, s: own(value) }, negated)]);
606
+ // The stated term as its fact states it, the document's universals
607
+ // as variables that only select this branch.
608
+ const stated = (t) => t.t === 'var' && t.scope === 0 ? { ...t, v: `stated${call}.${i}.${t.v}` } : t.t === 'witness' ? { ...t, deps: t.deps.map(stated) }
609
+ : t.t === 'list' ? { ...t, items: t.items.map(stated) }
610
+ : t.t === 'graph' ? { ...t, triples: t.triples.map((y) => ({ s: stated(y.s), p: stated(y.p), o: stated(y.o) })) } : t;
611
+ return conj([`unify(${ctx.term(x.s)}, ${ctx.term(stated(witnessed(term)))})`, ...goal({ ...x, s: own(value) }, negated)]);
530
612
  });
531
613
  return branches.length ? [`or(${branches.join(', ')})`] : ["'fail'"];
532
614
  }
@@ -619,20 +701,65 @@ function compileRule(body, head, kind, needed, views = true, values = []) {
619
701
  const o = arg(x.o);
620
702
  return [...viewGoals, `${builtin.goal}(${s}, ${o})`];
621
703
  }
622
- return [ctx.rdf(x)];
704
+ return pattern(x, negated);
705
+ }
706
+
707
+ // An ordinary triple goal. A quoted formula in it matches a formula as a set
708
+ // of triples, up to a one-to-one renaming of the formula's own variables,
709
+ // each kind to its own kind; a rule variable never stands for one of them.
710
+ function pattern(x, negated) {
711
+ const extra = [];
712
+ const rewrite = (t) => {
713
+ if (t.t === 'list') return { ...t, items: t.items.map(rewrite) };
714
+ if (t.t !== 'graph') return t;
715
+ const locals = graphLocals(t);
716
+ const free = [...keysOf(t)].filter((key) => !locals.some((l) => l.key === key));
717
+ // One triple without variables matches by unification alone.
718
+ if (!locals.length && !free.length && t.triples.length <= 1) return t;
719
+ const key = `graph:${++listViews}`;
720
+ if (negated || closed) ctx.anonymous.add(key);
721
+ const name = ctx.name(key, 'G');
722
+ const triples = t.triples.map((y) => ctx.rdf(y)).join(', ');
723
+ const terms = [...locals.map((l) => `${l.kind}(${ctx.term(l.term)})`), ...free.map((k) => `f(${ctx.names.get(k)})`)];
724
+ needed.add('n3_graph_match');
725
+ extra.push(`n3_graph_match(${name}, graph([${triples}]), [${terms.join(', ')}])`);
726
+ return { t: 'compiled', text: name };
727
+ };
728
+ return [ctx.rdf({ s: rewrite(x.s), p: x.p, o: rewrite(x.o) }), ...extra];
623
729
  }
624
730
 
625
731
  // A backward rule's conclusion arrives bound from the goal that calls it.
626
732
  const premise = conj(goals(reorder(bodyTriples, outside, kind === 'backward' ? headKeys : new Set()), false));
627
733
 
628
734
  if (isFalse(head)) return [`contradiction(${premise})`];
735
+ // { B } => ?G. asserts the formula B binds ?G to: unquoting.
736
+ if (head.t === 'var') {
737
+ needed.add('n3_unquote');
738
+ return [`implies(${premise}, n3_unquote(${ctx.term(head)}))`];
739
+ }
629
740
  const headTriples = triplesOf(head);
630
741
  if (headTriples.length === 0) return [];
631
742
  if (kind === 'backward') {
632
743
  return headTriples.map((h) => `implied_by(${ctx.rdf(h)}, ${premise})`);
633
744
  }
745
+ // A conclusion's own universals hold of everything: the triples that
746
+ // mention them, or a blank node in their scope, are backward rules, whose
747
+ // blank nodes are witnesses of the universals and the premise's values.
748
+ const own = kind === 'forward' ? headUniversals(head) : new Set();
749
+ if (own.size) {
750
+ const triples = headWitnesses(head, keysOf(body));
751
+ const universal = (h) => !isRuleTriple(h) && [...keysOfTriple(h)].some((key) => own.has(key));
752
+ const backward = triples.filter(universal).map((h) => `implied_by(${ctx.rdf(h)}, ${premise})`);
753
+ const heads = triples.filter((h) => !universal(h)).flatMap((h) => headTerm(h, kind));
754
+ return heads.length ? [`implies(${premise}, ${heads.length === 1 ? heads[0] : `[${heads.join(', ')}]`})`, ...backward] : backward;
755
+ }
634
756
  const heads = headTriples.flatMap((h) => headTerm(h, kind));
635
- return [`implies(${premise}, ${heads.length === 1 ? heads[0] : `[${heads.join(', ')}]`})`];
757
+ // A conclusion with blank nodes of its own is existential: the rule is
758
+ // restricted, firing only where no known values satisfy the conclusion.
759
+ const premiseKeys = keysOf(body);
760
+ const existential = kind === 'forward' && !headTriples.some(isRuleTriple) &&
761
+ headTriples.some((h) => [...keysOfTriple(quotedLocals(h))].some((key) => !premiseKeys.has(key)));
762
+ return [`${existential ? 'restricted' : 'implies'}(${premise}, ${heads.length === 1 ? heads[0] : `[${heads.join(', ')}]`})`];
636
763
 
637
764
  // A conclusion: a triple, or a rule the firing states. captured holds the
638
765
  // variables the enclosing premises bind; a derived rule's conclusion may
@@ -665,8 +792,93 @@ function compileRule(body, head, kind, needed, views = true, values = []) {
665
792
  const conclusions = cs.flatMap((y) => headTerm(y, k, within));
666
793
  return [`implies(${inner}, ${conclusions.length === 1 ? conclusions[0] : `[${conclusions.join(', ')}]`})`, asTriple];
667
794
  }
668
- return [ctx.rdf(h, k === 'query' ? 'result' : 'rdf')];
795
+ return [ctx.rdf(quotedLocals(h), k === 'query' ? 'result' : 'rdf')];
796
+ }
797
+ }
798
+
799
+ // The scopes of a quoted formula and the formulas inside it.
800
+ function graphScopes(t, out = new Set()) {
801
+ if (t.t === 'graph') { out.add(t.scope); t.triples.forEach((y) => [y.s, y.p, y.o].forEach((z) => graphScopes(z, out))); }
802
+ else if (t.t === 'list') t.items.forEach((z) => graphScopes(z, out));
803
+ else if (t.t === 'triple') [t.s, t.p, t.o].forEach((z) => graphScopes(z, out));
804
+ return out;
805
+ }
806
+
807
+ // A quoted formula's own variables, each once: { kind: 'e' or 'u', key, term }.
808
+ function graphLocals(g) {
809
+ const scopes = graphScopes(g);
810
+ const found = new Map();
811
+ const visit = (t) => {
812
+ if ((t.t === 'bnode' || t.t === 'var') && scopes.has(t.scope)) {
813
+ const key = t.t === 'var' ? `v:${t.v}` : bnodeKey(t);
814
+ if (!found.has(key)) found.set(key, { kind: t.t === 'var' ? 'u' : 'e', key, term: t });
815
+ } else if (t.t === 'list') t.items.forEach(visit);
816
+ else if (t.t === 'graph') t.triples.forEach((y) => [y.s, y.p, y.o].forEach(visit));
817
+ else if (t.t === 'triple') [t.s, t.p, t.o].forEach(visit);
818
+ };
819
+ visit(g);
820
+ return [...found.values()];
821
+ }
822
+
823
+ // The quoted formulas of a term with their own variables written as quoted
824
+ // variables, qbnode(Label) and qvar(Name), as a fact states them.
825
+ function quotedLocals(t) {
826
+ const local = (scopes) => (u) => {
827
+ if ((u.t === 'bnode' || u.t === 'var') && scopes.has(u.scope)) {
828
+ return { t: 'local', kind: u.t === 'var' ? 'qvar' : 'qbnode', label: u.t === 'var' ? u.v : bnodeLabel(u) };
829
+ }
830
+ if (u.t === 'list') return { ...u, items: u.items.map(local(scopes)) };
831
+ if (u.t === 'graph') return { ...u, triples: u.triples.map((y) => ({ ...y, s: local(scopes)(y.s), p: local(scopes)(y.p), o: local(scopes)(y.o) })) };
832
+ if (u.t === 'triple') return { ...u, s: local(scopes)(u.s), p: local(scopes)(u.p), o: local(scopes)(u.o) };
833
+ return u;
834
+ };
835
+ const top = (u) => (u.t === 'graph' ? local(graphScopes(u))(u) : u.t === 'list' ? { ...u, items: u.items.map(top) } : u);
836
+ return t.t === 'graph' ? top(t) : { ...t, s: top(t.s), p: top(t.p), o: top(t.o) };
837
+ }
838
+
839
+ const isRuleTriple = (h) => h.p.t === 'iri' && RULE_PREDICATES.has(h.p.v) && isFormulaLike(h.s);
840
+
841
+ // The keys of the universals a conclusion's @forAll declares.
842
+ function headUniversals(head) {
843
+ const out = new Set();
844
+ const visit = (t) => {
845
+ if (t.t === 'var' && t.scope === head.scope) out.add(`v:${t.v}`);
846
+ else if (t.t === 'list') t.items.forEach(visit);
847
+ else if (t.t === 'graph') t.triples.forEach((y) => [y.s, y.p, y.o].forEach(visit));
848
+ else if (t.t === 'triple') [t.s, t.p, t.o].forEach(visit);
849
+ };
850
+ for (const h of triplesOf(head)) if (!isRuleTriple(h)) [h.s, h.p, h.o].forEach(visit);
851
+ return out;
852
+ }
853
+
854
+ // A conclusion's triples with its own blank nodes as witnesses of the
855
+ // variables that the triples connected through them mention, in order.
856
+ function headWitnesses(head, premiseKeys) {
857
+ const isOwn = (t) => t.t === 'bnode' && t.scope === head.scope && !premiseKeys.has(bnodeKey(t));
858
+ const triples = triplesOf(head);
859
+ const parent = new Map();
860
+ const find = (k) => (parent.get(k) === k ? k : find(parent.get(k)));
861
+ const deps = new Map();
862
+ const variables = (t, out) => {
863
+ if (t.t === 'var') out.set(`v:${t.v}`, t);
864
+ else if (t.t === 'witness') t.deps.forEach((x) => variables(x, out));
865
+ else if (t.t === 'list') t.items.forEach((x) => variables(x, out));
866
+ else if (t.t === 'graph') t.triples.forEach((y) => [y.s, y.p, y.o].forEach((x) => variables(x, out)));
867
+ else if (t.t === 'triple') [t.s, t.p, t.o].forEach((x) => variables(x, out));
868
+ return out;
869
+ };
870
+ for (const h of triples) {
871
+ if (isRuleTriple(h)) continue;
872
+ const blanks = [h.s, h.p, h.o].filter(isOwn).map(bnodeKey);
873
+ for (const k of blanks) if (!parent.has(k)) { parent.set(k, k); deps.set(k, new Map()); }
874
+ for (const k of blanks.slice(1)) {
875
+ const [a, b] = [find(blanks[0]), find(k)];
876
+ if (a !== b) { parent.set(b, a); for (const [key, v] of deps.get(b)) deps.get(a).set(key, v); }
877
+ }
878
+ if (blanks.length) for (const [key, v] of [h.s, h.p, h.o].reduce((m, t) => variables(t, m), new Map())) deps.get(find(blanks[0])).set(key, v);
669
879
  }
880
+ const term = (t) => (isOwn(t) && parent.has(bnodeKey(t)) ? { t: 'witness', label: bnodeLabel(t), deps: [...deps.get(find(bnodeKey(t))).values()] } : t);
881
+ return triples.map((h) => (isRuleTriple(h) ? h : { ...h, s: term(h.s), p: term(h.p), o: term(h.o) }));
670
882
  }
671
883
 
672
884
  // Built-ins that only test their arguments; the others compute their object
package/src/program.js CHANGED
@@ -4,8 +4,8 @@ import { containsTemplate, expandTemplates } from './templates.js';
4
4
  import { subgoals } from './goals.js';
5
5
  import { hasInspection, inspectionTerm } from './inspection.js';
6
6
  import {
7
- EMPTY, Env, EyemindError, Struct, Var, deref, flattenConjunction, freshTerm, identity, indexKey, isCallable,
8
- isGround, isTerm, key, keyArity, unify, variables,
7
+ EMPTY, Env, EyemindError, Struct, Var, conjunction, deref, flattenConjunction, freshTerm, identity, indexKey, isCallable,
8
+ isGround, isTerm, key, keyArity, listFromItems, unify, variables,
9
9
  } from './terms.js';
10
10
  import { write } from './writer.js';
11
11
 
@@ -13,7 +13,7 @@ export const CONTROL_KEYS = new Set(['and/2', 'or/2', 'not/1', 'call/1', 'once/1
13
13
  export const RESERVED_KEYS = new Set(['step/4', 'clause/2', 'searched/2', 'derived/2', 'called/2', 'activated/2', 'implies/2', 'implied_by/2', 'forward/2', 'backward/2']);
14
14
 
15
15
  // The statements that state a forward rule, and how an error names them.
16
- const FORWARD_KINDS = { forward: 'a forward rule', query: 'query()', contradiction: 'contradiction()' };
16
+ const FORWARD_KINDS = { forward: 'a forward rule', restricted: 'restricted()', query: 'query()', contradiction: 'contradiction()' };
17
17
 
18
18
  export class Clause {
19
19
  constructor(id, head, heads, body, forward, line, captures = null) {
@@ -26,6 +26,9 @@ export class Clause {
26
26
  this.line = line;
27
27
  this.captures = captures;
28
28
  this.parentId = null;
29
+ this.restricted = false;
30
+ this.guard = null;
31
+ this.statedBody = body;
29
32
  this.prefixLength = 0;
30
33
  this.localBody = body;
31
34
  this.templates = [];
@@ -50,7 +53,8 @@ export class Clause {
50
53
  }
51
54
 
52
55
  // One clause as a program states it, before validation. kind is 'fact',
53
- // 'backward', 'forward', 'query' or 'contradiction'; body is a list of goals.
56
+ // 'backward', 'forward', 'restricted', 'query' or 'contradiction'; body is a
57
+ // list of goals.
54
58
  export class Source {
55
59
  constructor(kind, head, body, line = null, file = null) {
56
60
  this.kind = kind;
@@ -116,9 +120,9 @@ export class Program {
116
120
  }
117
121
  if (source.kind === 'fact' && body.length) throw new EyemindError(`line ${source.line}: a fact has no body`);
118
122
  const heads = forward ? flattenConjunction(source.head) : [source.head];
119
- if (source.kind === 'forward' && heads.some((item) => item === 'true' || item === 'false')) {
123
+ if ((source.kind === 'forward' || source.kind === 'restricted') && heads.some((item) => item === 'true' || item === 'false')) {
120
124
  // query() and contradiction() state these, and say so.
121
- throw new EyemindError(`line ${source.line}: implies() cannot conclude 'true' or 'false'; ` +
125
+ throw new EyemindError(`line ${source.line}: ${source.kind === 'forward' ? 'implies' : 'restricted'}() cannot conclude 'true' or 'false'; ` +
122
126
  'write query(Premise) or contradiction(Premise)');
123
127
  }
124
128
  for (const goal of body) {
@@ -148,8 +152,15 @@ export class Program {
148
152
  }
149
153
  allowed.add(itemKey);
150
154
  }
155
+ const stated = body.length;
156
+ const guard = source.kind === 'restricted' ? restriction(ordinal, source.head, heads, body) : null;
157
+ if (guard !== null) body.push(guard);
151
158
  const clause = new Clause(ordinal, source.head, forward ? heads : null, body, forward, source.line, source.captures ?? null);
159
+ clause.guard = guard;
160
+ clause.statedBody = guard === null ? body : body.slice(0, stated);
152
161
  clause.parentId = source.parentId ?? null;
162
+ // A restricted rule does not fire where its conclusion already holds.
163
+ clause.restricted = source.kind === 'restricted';
153
164
  clause.prefixLength = source.prefixLength ?? 0;
154
165
  clause.localBody = clause.prefixLength ? body.slice(clause.prefixLength) : body;
155
166
  clause.templates = source.templates || [];
@@ -316,6 +327,34 @@ function dependencies(goal, closed = false, out = []) {
316
327
  return out;
317
328
  }
318
329
 
330
+ // The guard of a restricted rule with witnesses, or null:
331
+ // not([Heads', not_unify(Witnesses', Skolems)]), where Heads' are its heads
332
+ // with each witness an anonymous variable of the guard and Skolems the terms
333
+ // a firing gives them (SPEC Section 8.2). It holds when nothing but the
334
+ // firing's own witnesses satisfies the heads: before the firing, when no
335
+ // known values do; after it, when the witnesses are needed.
336
+ function restriction(ordinal, head, heads, body) {
337
+ const inBody = new Set();
338
+ for (const goal of body) for (const name of variables(goal).keys()) inBody.add(name);
339
+ const all = variables(head);
340
+ const witnesses = [...all.values()].filter((variable) => !inBody.has(variable.name));
341
+ if (!witnesses.length) return null;
342
+ const used = new Set(all.keys());
343
+ for (const name of inBody) used.add(name);
344
+ let next = 0;
345
+ const anonymous = new Map(witnesses.map((variable) => {
346
+ while (used.has(`_${next}`)) next++;
347
+ used.add(`_${next}`);
348
+ return [variable.name, new Var(`_${next}`)];
349
+ }));
350
+ const rename = (term) => (term instanceof Var ? anonymous.get(term.name) ?? term
351
+ : term instanceof Struct ? new Struct(term.name, term.args.map(rename)) : term);
352
+ const frontier = listFromItems([...all.values()].filter((variable) => !anonymous.has(variable.name)));
353
+ const skolems = witnesses.map((variable) => new Struct('skolem', [BigInt(ordinal), variable.name, frontier]));
354
+ const other = new Struct('not_unify', [listFromItems([...anonymous.values()]), listFromItems(skolems)]);
355
+ return new Struct('not', [conjunction([...heads.map(rename), other])]);
356
+ }
357
+
319
358
  // Whether a goal could contribute a closed dependency or a dynamic call.
320
359
  function mayNeedStratifying(goal) {
321
360
  if (goal instanceof Var || isTerm(goal, 'not', 1) || isTerm(goal, 'findall', 3)) return true;
@@ -372,7 +411,10 @@ function stratify(clauses, stratifying) {
372
411
  outgoing.set(clause.id, [edge]);
373
412
  }
374
413
  for (const goal of clause.localBody) {
375
- for (const [depGoal, closed] of dependencies(goal)) {
414
+ // A restricted rule's guard reads its heads once the rules deriving
415
+ // them have run: it depends on them as on a premise.
416
+ for (const [depGoal, inside] of dependencies(goal)) {
417
+ const closed = inside && goal !== clause.guard;
376
418
  const named = !(depGoal instanceof Var);
377
419
  if (!named) dynamic.add(clause.id);
378
420
  const candidates = named ? headCandidates(index.get(key(depGoal)), depGoal) : everyHead;
package/src/proof.js CHANGED
@@ -45,7 +45,7 @@ export function clauseDisplay(clause) {
45
45
  if (clause.head === 'true') return new Struct('query', clause.body);
46
46
  if (clause.head === 'false') return new Struct('contradiction', clause.body);
47
47
  const heads = flattenConjunction(clause.originalHead ?? clause.head);
48
- return new Struct('implies', [goalsDisplay(clause.body), goalsDisplay(clause.templates.length ? heads.map(templateDisplay) : heads)]);
48
+ return new Struct(clause.restricted ? 'restricted' : 'implies', [goalsDisplay(clause.statedBody ?? clause.body), goalsDisplay(clause.templates.length ? heads.map(templateDisplay) : heads)]);
49
49
  }
50
50
  if (clause.body.length) return new Struct('implied_by', [clause.head, goalsDisplay(clause.body)]);
51
51
  return new Struct('fact', [clause.head]);
package/src/version.js CHANGED
@@ -1,2 +1,2 @@
1
1
  // The release this checkout is; ./release keeps it in step with package.json.
2
- export const VERSION = '0.5.13';
2
+ export const VERSION = '0.5.14';