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/README.md +43 -5
- package/SPEC.md +155 -5
- package/package.json +1 -1
- package/src/chains.js +333 -0
- package/src/engine.js +78 -46
- package/src/lang.js +4 -3
- package/src/n3-builtins.js +21 -0
- package/src/n3-parser.js +50 -7
- package/src/n3.js +234 -22
- package/src/program.js +57 -8
- package/src/proof.js +1 -1
- package/src/version.js +1 -1
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)
|
|
8
|
-
//
|
|
9
|
-
// {
|
|
10
|
-
// { B }
|
|
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.
|
|
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
|
|
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
|
-
|
|
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
|
|
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
|
-
|
|
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
|
-
|
|
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
|
|
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
|
-
|
|
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
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
// A program: its clauses, validated, indexed and stratified.
|
|
2
2
|
import { PRIMITIVE_KEYS } from './builtins.js';
|
|
3
3
|
import { containsTemplate, expandTemplates } from './templates.js';
|
|
4
|
+
import { chainStrata } from './chains.js';
|
|
4
5
|
import { subgoals } from './goals.js';
|
|
5
6
|
import { hasInspection, inspectionTerm } from './inspection.js';
|
|
6
7
|
import {
|
|
7
|
-
EMPTY, Env, EyemindError, Struct, Var, deref, flattenConjunction, freshTerm, identity, indexKey, isCallable,
|
|
8
|
-
isGround, isTerm, key, keyArity, unify, variables,
|
|
8
|
+
EMPTY, Env, EyemindError, Struct, Var, conjunction, deref, flattenConjunction, freshTerm, identity, indexKey, isCallable,
|
|
9
|
+
isGround, isTerm, key, keyArity, listFromItems, unify, variables,
|
|
9
10
|
} from './terms.js';
|
|
10
11
|
import { write } from './writer.js';
|
|
11
12
|
|
|
@@ -13,7 +14,7 @@ export const CONTROL_KEYS = new Set(['and/2', 'or/2', 'not/1', 'call/1', 'once/1
|
|
|
13
14
|
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
15
|
|
|
15
16
|
// 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()' };
|
|
17
|
+
const FORWARD_KINDS = { forward: 'a forward rule', restricted: 'restricted()', query: 'query()', contradiction: 'contradiction()' };
|
|
17
18
|
|
|
18
19
|
export class Clause {
|
|
19
20
|
constructor(id, head, heads, body, forward, line, captures = null) {
|
|
@@ -26,6 +27,9 @@ export class Clause {
|
|
|
26
27
|
this.line = line;
|
|
27
28
|
this.captures = captures;
|
|
28
29
|
this.parentId = null;
|
|
30
|
+
this.restricted = false;
|
|
31
|
+
this.guard = null;
|
|
32
|
+
this.statedBody = body;
|
|
29
33
|
this.prefixLength = 0;
|
|
30
34
|
this.localBody = body;
|
|
31
35
|
this.templates = [];
|
|
@@ -50,7 +54,8 @@ export class Clause {
|
|
|
50
54
|
}
|
|
51
55
|
|
|
52
56
|
// One clause as a program states it, before validation. kind is 'fact',
|
|
53
|
-
// 'backward', 'forward', 'query' or 'contradiction'; body is a
|
|
57
|
+
// 'backward', 'forward', 'restricted', 'query' or 'contradiction'; body is a
|
|
58
|
+
// list of goals.
|
|
54
59
|
export class Source {
|
|
55
60
|
constructor(kind, head, body, line = null, file = null) {
|
|
56
61
|
this.kind = kind;
|
|
@@ -116,9 +121,9 @@ export class Program {
|
|
|
116
121
|
}
|
|
117
122
|
if (source.kind === 'fact' && body.length) throw new EyemindError(`line ${source.line}: a fact has no body`);
|
|
118
123
|
const heads = forward ? flattenConjunction(source.head) : [source.head];
|
|
119
|
-
if (source.kind === 'forward' && heads.some((item) => item === 'true' || item === 'false')) {
|
|
124
|
+
if ((source.kind === 'forward' || source.kind === 'restricted') && heads.some((item) => item === 'true' || item === 'false')) {
|
|
120
125
|
// query() and contradiction() state these, and say so.
|
|
121
|
-
throw new EyemindError(`line ${source.line}: implies() cannot conclude 'true' or 'false'; ` +
|
|
126
|
+
throw new EyemindError(`line ${source.line}: ${source.kind === 'forward' ? 'implies' : 'restricted'}() cannot conclude 'true' or 'false'; ` +
|
|
122
127
|
'write query(Premise) or contradiction(Premise)');
|
|
123
128
|
}
|
|
124
129
|
for (const goal of body) {
|
|
@@ -148,8 +153,15 @@ export class Program {
|
|
|
148
153
|
}
|
|
149
154
|
allowed.add(itemKey);
|
|
150
155
|
}
|
|
156
|
+
const stated = body.length;
|
|
157
|
+
const guard = source.kind === 'restricted' ? restriction(ordinal, source.head, heads, body) : null;
|
|
158
|
+
if (guard !== null) body.push(guard);
|
|
151
159
|
const clause = new Clause(ordinal, source.head, forward ? heads : null, body, forward, source.line, source.captures ?? null);
|
|
160
|
+
clause.guard = guard;
|
|
161
|
+
clause.statedBody = guard === null ? body : body.slice(0, stated);
|
|
152
162
|
clause.parentId = source.parentId ?? null;
|
|
163
|
+
// A restricted rule does not fire where its conclusion already holds.
|
|
164
|
+
clause.restricted = source.kind === 'restricted';
|
|
153
165
|
clause.prefixLength = source.prefixLength ?? 0;
|
|
154
166
|
clause.localBody = clause.prefixLength ? body.slice(clause.prefixLength) : body;
|
|
155
167
|
clause.templates = source.templates || [];
|
|
@@ -184,6 +196,8 @@ export class Program {
|
|
|
184
196
|
if (!clause.forward && !clause.body.length && isGround(clause.head)) this.groundFactKeys.add(identity(clause.head));
|
|
185
197
|
}
|
|
186
198
|
this.strata = stratify(this.clauses, stratifying);
|
|
199
|
+
// Chain strata run layer by layer, a lower layer again after each change.
|
|
200
|
+
this.layered = this.strata.layered === true;
|
|
187
201
|
}
|
|
188
202
|
|
|
189
203
|
prepareInspections() {
|
|
@@ -316,6 +330,34 @@ function dependencies(goal, closed = false, out = []) {
|
|
|
316
330
|
return out;
|
|
317
331
|
}
|
|
318
332
|
|
|
333
|
+
// The guard of a restricted rule with witnesses, or null:
|
|
334
|
+
// not([Heads', not_unify(Witnesses', Skolems)]), where Heads' are its heads
|
|
335
|
+
// with each witness an anonymous variable of the guard and Skolems the terms
|
|
336
|
+
// a firing gives them (SPEC Section 8.2). It holds when nothing but the
|
|
337
|
+
// firing's own witnesses satisfies the heads: before the firing, when no
|
|
338
|
+
// known values do; after it, when the witnesses are needed.
|
|
339
|
+
function restriction(ordinal, head, heads, body) {
|
|
340
|
+
const inBody = new Set();
|
|
341
|
+
for (const goal of body) for (const name of variables(goal).keys()) inBody.add(name);
|
|
342
|
+
const all = variables(head);
|
|
343
|
+
const witnesses = [...all.values()].filter((variable) => !inBody.has(variable.name));
|
|
344
|
+
if (!witnesses.length) return null;
|
|
345
|
+
const used = new Set(all.keys());
|
|
346
|
+
for (const name of inBody) used.add(name);
|
|
347
|
+
let next = 0;
|
|
348
|
+
const anonymous = new Map(witnesses.map((variable) => {
|
|
349
|
+
while (used.has(`_${next}`)) next++;
|
|
350
|
+
used.add(`_${next}`);
|
|
351
|
+
return [variable.name, new Var(`_${next}`)];
|
|
352
|
+
}));
|
|
353
|
+
const rename = (term) => (term instanceof Var ? anonymous.get(term.name) ?? term
|
|
354
|
+
: term instanceof Struct ? new Struct(term.name, term.args.map(rename)) : term);
|
|
355
|
+
const frontier = listFromItems([...all.values()].filter((variable) => !anonymous.has(variable.name)));
|
|
356
|
+
const skolems = witnesses.map((variable) => new Struct('skolem', [BigInt(ordinal), variable.name, frontier]));
|
|
357
|
+
const other = new Struct('not_unify', [listFromItems([...anonymous.values()]), listFromItems(skolems)]);
|
|
358
|
+
return new Struct('not', [conjunction([...heads.map(rename), other])]);
|
|
359
|
+
}
|
|
360
|
+
|
|
319
361
|
// Whether a goal could contribute a closed dependency or a dynamic call.
|
|
320
362
|
function mayNeedStratifying(goal) {
|
|
321
363
|
if (goal instanceof Var || isTerm(goal, 'not', 1) || isTerm(goal, 'findall', 3)) return true;
|
|
@@ -372,7 +414,10 @@ function stratify(clauses, stratifying) {
|
|
|
372
414
|
outgoing.set(clause.id, [edge]);
|
|
373
415
|
}
|
|
374
416
|
for (const goal of clause.localBody) {
|
|
375
|
-
|
|
417
|
+
// A restricted rule's guard reads its heads once the rules deriving
|
|
418
|
+
// them have run: it depends on them as on a premise.
|
|
419
|
+
for (const [depGoal, inside] of dependencies(goal)) {
|
|
420
|
+
const closed = inside && goal !== clause.guard;
|
|
376
421
|
const named = !(depGoal instanceof Var);
|
|
377
422
|
if (!named) dynamic.add(clause.id);
|
|
378
423
|
const candidates = named ? headCandidates(index.get(key(depGoal)), depGoal) : everyHead;
|
|
@@ -407,5 +452,9 @@ function stratify(clauses, stratifying) {
|
|
|
407
452
|
}
|
|
408
453
|
if (!changed) return ranks;
|
|
409
454
|
}
|
|
410
|
-
|
|
455
|
+
// A program classic stratification rejects may still be chain-stratified.
|
|
456
|
+
const chained = chainStrata(clauses);
|
|
457
|
+
if (chained === null) throw new EyemindError('unstratified negation or collection dependency');
|
|
458
|
+
chained.layered = true;
|
|
459
|
+
return chained;
|
|
411
460
|
}
|
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.
|
|
2
|
+
export const VERSION = '0.5.15';
|