eyemind 0.5.13 → 0.5.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/engine.js CHANGED
@@ -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) {
@@ -826,58 +828,88 @@ export class Solver {
826
828
  if (!layers.has(rank)) layers.set(rank, []);
827
829
  layers.get(rank).push(clause);
828
830
  }
831
+ const ranks = [...layers.keys()].sort((a, b) => a - b);
829
832
  const maxIterations = this.options.maxIterations || 1000;
830
- for (const rank of [...layers.keys()].sort((a, b) => a - b)) {
831
- const rules = layers.get(rank);
833
+ let rounds = 0;
834
+ const round = (rules) => {
835
+ rounds++;
836
+ if (rounds > maxIterations) throw new EyemindError('forward reasoning exceeded max_iterations');
837
+ this.stats.rounds++;
838
+ return this.round(rules, reporting);
839
+ };
840
+ if (this.program.layered) {
841
+ // Chain strata (SPEC Section 6.4): a layer runs a round only when
842
+ // every lower layer's last round derived nothing, and after a round
843
+ // that derives something the lowest layer runs again.
844
+ for (let i = 0; i < ranks.length;) {
845
+ const changed = round(layers.get(ranks[i]));
846
+ if (changed === 'halt') return;
847
+ i = changed ? 0 : i + 1;
848
+ }
849
+ return;
850
+ }
851
+ for (const rank of ranks) {
852
+ rounds = 0;
853
+ const all = layers.get(rank);
854
+ const restricted = all.filter((clause) => clause.restricted);
855
+ const ordinary = restricted.length ? all.filter((clause) => !clause.restricted) : all;
832
856
  let changed = true;
833
- let rounds = 0;
834
- while (changed) {
835
- rounds++;
836
- if (rounds > maxIterations) throw new EyemindError('forward reasoning exceeded max_iterations');
837
- this.stats.rounds++;
838
- changed = false;
839
- for (const original of rules) {
840
- const instances = original.parentId === null ? [original] : this.rules.get(original.id) || NO_NODES;
841
- const firings = [];
842
- for (const clause of instances) {
843
- if (!reporting && clause.heads.every((item) => item === 'true')) continue;
844
- for (const firing of this.firings(clause)) firings.push([clause, firing]);
857
+ let lean = false;
858
+ while (changed || (!lean && restricted.length)) {
859
+ // After a round of the other rules that derives nothing, a round of
860
+ // the restricted ones; after one of those that derives nothing, done.
861
+ lean = !changed && restricted.length > 0;
862
+ changed = round(lean ? restricted : ordinary);
863
+ if (changed === 'halt') return;
864
+ }
865
+ }
866
+ }
867
+
868
+ // One round of rules in clause order: true when it derived something,
869
+ // 'halt' when a contradiction stopped reasoning.
870
+ round(rules, reporting) {
871
+ let changed = false;
872
+ for (const original of rules) {
873
+ const instances = original.parentId === null ? [original] : this.rules.get(original.id) || NO_NODES;
874
+ const firings = [];
875
+ for (const clause of instances) {
876
+ if (!reporting && clause.heads.every((item) => item === 'true')) continue;
877
+ for (const firing of this.firings(clause)) firings.push([clause, firing]);
878
+ }
879
+ // All instances of this template see the same state. Publishing one
880
+ // instance's conclusions during another's search changes recursive
881
+ // bodies and their observable order.
882
+ for (const [clause, [conclusions, children, bindings, claim]] of firings) {
883
+ for (const [position, conclusion] of conclusions.entries()) {
884
+ const template = clause.templates.find((item) => item.position === position);
885
+ if (template) {
886
+ if (this.deriveRules(template, conclusion, bindings, children)) changed = true;
887
+ continue;
888
+ }
889
+ if (conclusion === 'true') {
890
+ const claimId = this.program.inspectionEnabled ? variant(claim) : text(claim);
891
+ if (!this.reported.has(claimId)) this.reported.set(claimId, [claim, children, clause.id]);
892
+ continue;
845
893
  }
846
- // All instances of this template see the same state. Publishing one
847
- // instance's conclusions during another's search changes recursive
848
- // bodies and their observable order.
849
- for (const [clause, [conclusions, children, bindings, claim]] of firings) {
850
- for (const [position, conclusion] of conclusions.entries()) {
851
- const template = clause.templates.find((item) => item.position === position);
852
- if (template) {
853
- if (this.deriveRules(template, conclusion, bindings, children)) changed = true;
854
- continue;
855
- }
856
- if (conclusion === 'true') {
857
- const claimId = this.program.inspectionEnabled ? variant(claim) : text(claim);
858
- if (!this.reported.has(claimId)) this.reported.set(claimId, [claim, children, clause.id]);
859
- continue;
860
- }
861
- const node = new Node(conclusion, new Struct('clause', [BigInt(clause.id)]), bindings, children, null, true);
862
- if (conclusion === 'false') {
863
- this.derived.push(node);
864
- this.haltCode = 65;
865
- return;
866
- }
867
- node.generic = this.program.inspectionEnabled && !isGround(conclusion);
868
- const conclusionId = node.generic ? variant(conclusion) : identity(conclusion);
869
- const factKeys = node.generic ? this.genericKeys : this.factKeys;
870
- if (factKeys.has(conclusionId)) continue;
871
- factKeys.add(conclusionId);
872
- this.addFact(key(conclusion), node);
873
- this.derived.push(node);
874
- this.stats.derived++;
875
- changed = true;
876
- }
894
+ const node = new Node(conclusion, new Struct('clause', [BigInt(clause.id)]), bindings, children, null, true);
895
+ if (conclusion === 'false') {
896
+ this.derived.push(node);
897
+ this.haltCode = 65;
898
+ return 'halt';
877
899
  }
900
+ node.generic = this.program.inspectionEnabled && !isGround(conclusion);
901
+ const conclusionId = node.generic ? variant(conclusion) : identity(conclusion);
902
+ const factKeys = node.generic ? this.genericKeys : this.factKeys;
903
+ if (factKeys.has(conclusionId)) continue;
904
+ factKeys.add(conclusionId);
905
+ this.addFact(key(conclusion), node);
906
+ this.derived.push(node);
907
+ this.stats.derived++;
908
+ changed = true;
878
909
  }
879
910
  }
880
911
  }
912
+ return changed;
881
913
  }
882
914
  }
883
915
 
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();