eyemind 0.5.12 → 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/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
@@ -236,14 +238,17 @@ export const DEFAULT_PREFIXES = {
236
238
  };
237
239
 
238
240
  // Parse a document: { triples, prefixes, base }. Prefixes map names to IRIs
239
- // in declaration order.
240
- export function parseN3(src, { base = '' } = {}) {
241
+ // in declaration order. Native proof validation preserves numeric literal
242
+ // text, so two different decimal displays cannot agree through rounding.
243
+ export function parseN3(src, { base = '', preserveNumericLiterals = false } = {}) {
241
244
  const toks = tokenize(String(src));
242
245
  let pos = 0;
243
246
  const prefixes = new Map();
244
247
  let bnodeCount = 0;
245
248
  let scopeCount = 0;
246
- 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}`));
247
252
  let scope = top;
248
253
  const peek = (k = 0) => toks[pos + k];
249
254
  const next = () => toks[pos++];
@@ -299,7 +304,7 @@ export function parseN3(src, { base = '' } = {}) {
299
304
  if (isP('^^')) {
300
305
  next();
301
306
  const dt = iriTerm();
302
- return typedLiteral(text, dt.v);
307
+ return typedLiteral(text, dt.v, preserveNumericLiterals);
303
308
  }
304
309
  return { t: 'literal', v: text, dt: `${XSD}string` };
305
310
  }
@@ -311,14 +316,49 @@ export function parseN3(src, { base = '' } = {}) {
311
316
  throw fail(`expected an IRI, found ${describe(tok)}`, tok);
312
317
  }
313
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
+
314
353
  function term() {
315
354
  const tok = peek();
316
- if (tok.k === 'iri' || tok.k === 'pname') return iriTerm();
355
+ if (tok.k === 'iri' || tok.k === 'pname') return quantified(iriTerm());
317
356
  next();
318
- 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 };
319
359
  if (tok.k === 'bnode') return { t: 'bnode', v: tok.v, scope: scope.id };
320
360
  if (tok.k === 'string') return literalTail(tok.v);
321
- if (tok.k === 'number') return numberTerm(tok.v);
361
+ if (tok.k === 'number') return numberTerm(tok.v, preserveNumericLiterals);
322
362
  if (tok.k === 'word') {
323
363
  if (tok.v === 'true' || tok.v === 'false') return { t: 'literal', v: tok.v, dt: `${XSD}boolean` };
324
364
  throw fail(`unexpected word '${tok.v}'; prefixed names need a colon, as in :${tok.v}`, tok);
@@ -354,7 +394,7 @@ export function parseN3(src, { base = '' } = {}) {
354
394
  }
355
395
  if (isP('{', tok)) {
356
396
  const outer = scope;
357
- scope = { id: ++scopeCount, triples: [] };
397
+ scope = { id: ++scopeCount, triples: [], parent: outer, bound: new Map(), started: false, existential: false };
358
398
  while (!isP('}')) {
359
399
  if (peek().k === 'eof') throw fail("unterminated formula; expected '}'");
360
400
  if (statement(true) === 'directive') continue;
@@ -425,7 +465,11 @@ export function parseN3(src, { base = '' } = {}) {
425
465
  directive();
426
466
  return 'directive';
427
467
  }
428
- 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;
429
473
  // { true } is the empty formula.
430
474
  if (inFormula && tok.k === 'word' && tok.v === 'true' && (isP('.', peek(1)) || isP('}', peek(1)))) { next(); return 'triples'; }
431
475
  const s = pathTerm();
@@ -443,8 +487,9 @@ export function parseN3(src, { base = '' } = {}) {
443
487
  return { triples: top.triples, prefixes, base };
444
488
  }
445
489
 
446
- function numberTerm(text) {
490
+ function numberTerm(text, preserve = false) {
447
491
  if (/^[+-]?[0-9]+$/.test(text)) return { t: 'int', v: BigInt(text) };
492
+ if (preserve) return { t: 'literal', v: text, dt: `${XSD}${/[eE]/.test(text) ? 'double' : 'decimal'}` };
448
493
  if (/[eE]/.test(text)) return { t: 'literal', v: String(Number(text)), dt: `${XSD}double` };
449
494
  return { t: 'float', v: Number(text) };
450
495
  }
@@ -454,9 +499,10 @@ const FLOAT_TYPES = new Set(['decimal']);
454
499
 
455
500
  // Native numbers represent integer and decimal. Float and double retain
456
501
  // their datatype so triple matching and log:equalTo distinguish them.
457
- export function typedLiteral(text, dt) {
502
+ export function typedLiteral(text, dt, preserve = false) {
458
503
  if (dt.startsWith(XSD)) {
459
504
  const local = dt.slice(XSD.length);
505
+ if (preserve && ['decimal', 'float', 'double'].includes(local)) return { t: 'literal', v: text, dt };
460
506
  if (INTEGER_TYPES.has(local) && /^[+-]?[0-9]+$/.test(text)) return { t: 'int', v: BigInt(text) };
461
507
  if (FLOAT_TYPES.has(local) && /^[+-]?([0-9]+(\.[0-9]*)?|\.[0-9]+)([eE][+-]?[0-9]+)?$/.test(text)) return { t: 'float', v: Number(text) };
462
508
  if ((local === 'double' || local === 'float') && Number.isFinite(Number(text)) && /^[+-]?([0-9]+(\.[0-9]*)?|\.[0-9]+)([eE][+-]?[0-9]+)?$/.test(text)) return { t: 'literal', v: String(Number(text)), dt };
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
@@ -167,9 +167,11 @@ function srlData(document) {
167
167
  if (t.type === 'iri') return { t: 'iri', v: t.value };
168
168
  if (t.type === 'blank') return { t: 'bnode', v: t.value, scope: 0 };
169
169
  if (t.type === 'literal') {
170
- const value = Object.is(t.value, -0) ? '-0' : String(t.value);
170
+ // A displayed decimal must not lose digits before its record is
171
+ // compared: adjacent exact values can round to the same binary64.
172
+ const value = t.lexical ?? (Object.is(t.value, -0) ? '-0' : String(t.value));
171
173
  return t.lang ? { t: 'literal', v: value, dt: `${RDF}langString`, lang: t.lang, dir: t.langDir }
172
- : typedLiteral(value, t.datatype ?? `${XSD}string`);
174
+ : typedLiteral(value, t.datatype ?? `${XSD}string`, true);
173
175
  }
174
176
  if (t.type === 'triple') return { t: 'triple', s: term(t.s), p: term(t.p), o: term(t.o) };
175
177
  fail('an SRL proof must be ground RDF data');
@@ -246,7 +248,7 @@ function compare(actual, expected) {
246
248
 
247
249
  function readNative(document) {
248
250
  let parsed, format;
249
- try { parsed = parseN3(document); format = 'n3'; }
251
+ try { parsed = parseN3(document, { preserveNumericLiterals: true }); format = 'n3'; }
250
252
  catch (n3Error) {
251
253
  try { parsed = srlData(document); format = 'srl'; }
252
254
  catch (error) { throw new EyemindError(`native proof: ${error.message}`); }
@@ -269,7 +271,7 @@ function readNative(document) {
269
271
  if (id.t !== 'iri' || id.v !== `${ROOT}#record${i + 1}`) fail('proof records must be numbered in document order');
270
272
  return decode(property(id.v, `${TERM_NS}term`));
271
273
  });
272
- const expected = format === 'n3' ? parseN3(render(terms, format)) : srlData(render(terms, format));
274
+ const expected = format === 'n3' ? parseN3(render(terms, format), { preserveNumericLiterals: true }) : srlData(render(terms, format));
273
275
  compare(parsed.triples, expected.triples);
274
276
  return terms;
275
277
  }