eyemind 0.9.16 → 0.9.18

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/rdf-parser.js CHANGED
@@ -8,28 +8,18 @@
8
8
 
9
9
  import {
10
10
  RDF_NS,
11
- OWL_NS,
12
- LOG_NS,
13
11
  resolveIriRef,
14
12
  Literal,
15
- Var,
16
13
  Blank,
17
14
  ListTerm,
18
15
  GraphTerm,
19
16
  Triple,
20
- Rule,
21
17
  internIri,
22
18
  internLiteral,
23
19
  PrefixEnv,
24
- collectBlankLabelsInTriples,
25
- isLogImplies,
26
- isLogImpliedBy,
27
- isLogQuery,
28
- annotateQuotedGraphTerm,
29
20
  } from './rdf-prelude.js';
30
21
 
31
22
  import { N3SyntaxError } from './rdf-lexer.js';
32
- import { liftBlankRuleVars } from './rdf-rules.js';
33
23
 
34
24
  function assertValidQNamePrefix(prefixName, fail, tok, context = 'prefixed name') {
35
25
  if (typeof prefixName === 'string' && prefixName.endsWith('.')) {
@@ -56,7 +46,8 @@ class Parser {
56
46
  constructor(tokens, options = {}) {
57
47
  this.toks = tokens;
58
48
  this.pos = 0;
59
- this.prefixes = PrefixEnv.newDefault();
49
+ // RDF declares every prefix it uses; none is predeclared.
50
+ this.prefixes = new PrefixEnv();
60
51
  this.blankCounter = 0;
61
52
  // Helper triples that must be emitted *before* the triple that consumes them.
62
53
  // Used primarily for N3 path expansion (e.g. :a :p/:q :b .).
@@ -172,9 +163,6 @@ class Parser {
172
163
 
173
164
  parseDocument() {
174
165
  const triples = [];
175
- const forwardRules = [];
176
- const backwardRules = [];
177
- const logQueries = [];
178
166
 
179
167
  while (this.peek().typ !== 'EOF') {
180
168
  if (this.parseDirectiveIfPresent({ allowIdentBaseIri: true })) {
@@ -184,52 +172,21 @@ class Parser {
184
172
  const statementToken = this.peek();
185
173
  const statementOffset = statementToken && typeof statementToken.offset === 'number' ? statementToken.offset : null;
186
174
  const first = this.parseTerm();
187
- if (this.peek().typ === 'OpImplies') {
188
- this.next();
189
- const second = this.parseTerm();
190
- this.expectDot();
191
- forwardRules.push(this.annotateSourceOffset(this.makeRule(first, second, true), statementOffset));
192
- } else if (this.peek().typ === 'OpImpliedBy') {
193
- this.next();
194
- const second = this.parseTerm();
195
- this.expectDot();
196
- backwardRules.push(this.annotateSourceOffset(this.makeRule(first, second, false), statementOffset));
175
+ let more;
176
+ if (this.peek().typ === 'Dot') {
177
+ // A bare subject followed by '.' contributes only the triples of its
178
+ // reified triples or blank node property lists, if any.
179
+ more = [];
180
+ this.flushPendingTriples(more);
181
+ this.next(); // consume '.'
197
182
  } else {
198
- let more;
199
-
200
- if (this.peek().typ === 'Dot') {
201
- // N3 grammar allows: triples ::= subject predicateObjectList?
202
- // So a bare subject followed by '.' is syntactically valid.
203
- // If the subject was a path / property-list that generated helper triples,
204
- // we emit those; otherwise this statement contributes no triples.
205
- more = [];
206
- this.flushPendingTriples(more);
207
- this.next(); // consume '.'
208
- } else {
209
- more = this.parsePredicateObjectList(first);
210
- this.expectDot();
211
- }
212
-
213
- // normalize explicit log:implies / log:impliedBy at top-level
214
- for (const tr0 of more) {
215
- const tr = this.annotateSourceOffset(tr0, statementOffset);
216
- if (isLogImplies(tr.p) && tr.s instanceof GraphTerm && tr.o instanceof GraphTerm) {
217
- forwardRules.push(this.annotateSourceOffset(this.makeRule(tr.s, tr.o, true), statementOffset));
218
- } else if (isLogImpliedBy(tr.p) && tr.s instanceof GraphTerm && tr.o instanceof GraphTerm) {
219
- backwardRules.push(this.annotateSourceOffset(this.makeRule(tr.s, tr.o, false), statementOffset));
220
- } else if (isLogQuery(tr.p) && tr.s instanceof GraphTerm && tr.o instanceof GraphTerm) {
221
- // Output-selection directive: { premise } log:query { conclusion }.
222
- // eyemind: select only the instantiated conclusion
223
- // triples (unique) instead of all newly derived facts.
224
- logQueries.push(this.annotateSourceOffset(this.makeRule(tr.s, tr.o, true), statementOffset));
225
- } else {
226
- triples.push(tr);
227
- }
228
- }
183
+ more = this.parsePredicateObjectList(first);
184
+ this.expectDot();
229
185
  }
186
+ for (const triple of more) triples.push(this.annotateSourceOffset(triple, statementOffset));
230
187
  }
231
188
 
232
- return [this.prefixes, triples, forwardRules, backwardRules, logQueries];
189
+ return [this.prefixes, triples];
233
190
  }
234
191
 
235
192
  parsePrefixDirective() {
@@ -253,34 +210,14 @@ class Parser {
253
210
  }
254
211
 
255
212
  const tok2 = this.next();
256
- let iri;
257
- if (tok2.typ === 'IriRef') {
258
- iri = resolveIriRef(tok2.value || '', this.prefixes.baseIri || '');
259
- } else if (tok2.typ === 'Ident') {
260
- const qn = tok2.value || '';
261
- if (!qn.includes(':')) failInvalidKeywordLikeIdent(this.fail.bind(this), tok2, qn);
262
- assertValidQNamePrefix(qn.slice(0, qn.indexOf(':')), this.fail.bind(this), tok2, '@prefix directive IRI');
263
- iri = this.prefixes.expandQName(qn);
264
- } else {
265
- this.fail(`Expected IRI after @prefix, got ${tok2.toString()}`, tok2);
266
- }
213
+ const iri = this.directiveIri(tok2, '@prefix', '@prefix directive IRI');
267
214
  this.expectDot();
268
215
  this.prefixes.set(prefName, iri);
269
216
  }
270
217
 
271
218
  parseBaseDirective() {
272
219
  const tok = this.next();
273
- let iri;
274
- if (tok.typ === 'IriRef') {
275
- iri = resolveIriRef(tok.value || '', this.prefixes.baseIri || '');
276
- } else if (tok.typ === 'Ident') {
277
- const qn = tok.value || '';
278
- if (!qn.includes(':')) failInvalidKeywordLikeIdent(this.fail.bind(this), tok, qn);
279
- assertValidQNamePrefix(qn.slice(0, qn.indexOf(':')), this.fail.bind(this), tok, '@base directive IRI');
280
- iri = this.prefixes.expandQName(qn);
281
- } else {
282
- this.fail(`Expected IRI after @base, got ${tok.toString()}`, tok);
283
- }
220
+ const iri = this.directiveIri(tok, '@base', '@base directive IRI');
284
221
  this.expectDot();
285
222
  this.prefixes.setBase(iri);
286
223
  }
@@ -299,17 +236,7 @@ class Parser {
299
236
  assertValidQNamePrefix(prefName, this.fail.bind(this), tok, 'PREFIX directive');
300
237
 
301
238
  const tok2 = this.next();
302
- let iri;
303
- if (tok2.typ === 'IriRef') {
304
- iri = resolveIriRef(tok2.value || '', this.prefixes.baseIri || '');
305
- } else if (tok2.typ === 'Ident') {
306
- const qn = tok2.value || '';
307
- if (!qn.includes(':')) failInvalidKeywordLikeIdent(this.fail.bind(this), tok2, qn);
308
- assertValidQNamePrefix(qn.slice(0, qn.indexOf(':')), this.fail.bind(this), tok2, '@prefix directive IRI');
309
- iri = this.prefixes.expandQName(qn);
310
- } else {
311
- this.fail(`Expected IRI after PREFIX, got ${tok2.toString()}`, tok2);
312
- }
239
+ const iri = this.directiveIri(tok2, 'PREFIX', '@prefix directive IRI');
313
240
 
314
241
  // N3/Turtle: PREFIX directives do not have a trailing '.', but accept it permissively.
315
242
  if (this.peek().typ === 'Dot') this.next();
@@ -320,17 +247,7 @@ class Parser {
320
247
  parseSparqlBaseDirective() {
321
248
  // SPARQL/Turtle-style BASE directive: BASE <iri> (no trailing '.')
322
249
  const tok = this.next();
323
- let iri;
324
- if (tok.typ === 'IriRef') {
325
- iri = resolveIriRef(tok.value || '', this.prefixes.baseIri || '');
326
- } else if (tok.typ === 'Ident') {
327
- const qn = tok.value || '';
328
- if (!qn.includes(':')) failInvalidKeywordLikeIdent(this.fail.bind(this), tok, qn);
329
- assertValidQNamePrefix(qn.slice(0, qn.indexOf(':')), this.fail.bind(this), tok, 'BASE directive IRI');
330
- iri = this.prefixes.expandQName(qn);
331
- } else {
332
- this.fail(`Expected IRI after BASE, got ${tok.toString()}`, tok);
333
- }
250
+ const iri = this.directiveIri(tok, 'BASE', 'BASE directive IRI');
334
251
 
335
252
  // N3/Turtle: BASE directives do not have a trailing '.', but accept it permissively.
336
253
  if (this.peek().typ === 'Dot') this.next();
@@ -338,33 +255,22 @@ class Parser {
338
255
  this.prefixes.setBase(iri);
339
256
  }
340
257
 
341
- parseTerm() {
342
- let t = this.parsePathItem();
343
-
344
- while (this.peek().typ === 'OpPathFwd' || this.peek().typ === 'OpPathRev') {
345
- const dir = this.next().typ; // OpPathFwd | OpPathRev
346
- const pred = this.parsePathItem();
347
-
348
- this.blankCounter += 1;
349
- const bn = new Blank(`_:b${this.blankCounter}`, 'unlabeled');
350
-
351
- this.pendingTriples.push(dir === 'OpPathFwd' ? new Triple(t, pred, bn) : new Triple(bn, pred, t));
352
-
353
- t = bn;
354
- }
355
-
356
- return t;
258
+ // A directive's IRI: an IRI reference, resolved against the base, or a
259
+ // prefixed name.
260
+ directiveIri(tok, after, context) {
261
+ if (tok.typ === 'IriRef') return resolveIriRef(tok.value || '', this.prefixes.baseIri || '');
262
+ if (tok.typ !== 'Ident') this.fail(`Expected IRI after ${after}, got ${tok.toString()}`, tok);
263
+ const qn = tok.value || '';
264
+ if (!qn.includes(':')) failInvalidKeywordLikeIdent(this.fail.bind(this), tok, qn);
265
+ assertValidQNamePrefix(qn.slice(0, qn.indexOf(':')), this.fail.bind(this), tok, context);
266
+ return this.prefixes.expandQName(qn);
357
267
  }
358
268
 
359
- parsePathItem() {
269
+ parseTerm() {
360
270
  const tok = this.next();
361
271
  const typ = tok.typ;
362
272
  const val = tok.value;
363
273
 
364
- if (typ === 'Equals') {
365
- return internIri(OWL_NS + 'sameAs');
366
- }
367
-
368
274
  if (typ === 'LtLt') return this.parseReifiedTriple();
369
275
 
370
276
  if (typ === 'IriRef') {
@@ -427,7 +333,6 @@ class Parser {
427
333
  return internLiteral(s);
428
334
  }
429
335
 
430
- if (typ === 'Var') return new Var(val || '');
431
336
  if (typ === 'LParen') return this.parseList();
432
337
  if (typ === 'LBracket') return this.parseBlank();
433
338
  if (typ === 'LBrace') return this.parseGraph();
@@ -490,43 +395,20 @@ class Parser {
490
395
  return new Blank(id, 'unlabeled');
491
396
  }
492
397
 
493
- parsePropertyVerb() {
494
- let pred;
495
- let invert = false;
496
-
398
+ // A verb: a, or a predicate term.
399
+ parseVerb() {
497
400
  if (this.peek().typ === 'Ident' && (this.peek().value || '') === 'a') {
498
401
  this.next();
499
- pred = internIri(RDF_NS + 'type');
500
- } else if (this.peek().typ === 'Ident' && (this.peek().value || '') === 'has') {
501
- // N3 syntactic sugar is also valid in predicate-object lists,
502
- // including blank node property lists: [ has :p :o ] means _:b :p :o.
503
- this.next();
504
- pred = this.parseTerm();
505
- } else if (this.peek().typ === 'Ident' && (this.peek().value || '') === 'is') {
506
- // N3 syntactic sugar: [ is :p of :s ] means :s :p _:b.
507
- this.next();
508
- pred = this.parseTerm();
509
- if (!(this.peek().typ === 'Ident' && (this.peek().value || '') === 'of')) {
510
- this.fail(`Expected 'of' after 'is <expr>', got ${this.peek().toString()}`);
511
- }
512
- this.next();
513
- invert = true;
514
- } else if (this.peek().typ === 'OpPredInvert') {
515
- this.next();
516
- pred = this.parseTerm();
517
- invert = true;
518
- } else {
519
- pred = this.parseTerm();
402
+ return internIri(RDF_NS + 'type');
520
403
  }
521
-
522
- return { pred, invert };
404
+ return this.parseTerm();
523
405
  }
524
406
 
525
407
  parsePropertyListTriples(subject, closingTyp, contextLabel) {
526
408
  const localTriples = [];
527
409
 
528
410
  while (true) {
529
- const { pred, invert } = this.parsePropertyVerb();
411
+ const pred = this.parseVerb();
530
412
 
531
413
  // If a pathological predicate term produced post-triples, don't let them leak.
532
414
  this.flushPendingTriples(localTriples, { includeBefore: false, includeAfter: true });
@@ -536,7 +418,7 @@ class Parser {
536
418
  const term = this.parseTerm();
537
419
  const postTriples = this.pendingTriplesAfter;
538
420
  this.pendingTriplesAfter = [];
539
- const annotations = this.parseAnnotations(invert ? new Triple(term, pred, subject) : new Triple(subject, pred, term));
421
+ const annotations = this.parseAnnotations(new Triple(subject, pred, term));
540
422
  objs.push({ term, postTriples, annotations });
541
423
  };
542
424
 
@@ -549,7 +431,7 @@ class Parser {
549
431
  for (const { term: o, postTriples, annotations } of objs) {
550
432
  // Path helper triples must come before the triple that consumes the path result.
551
433
  this.flushPendingTriples(localTriples, { includeBefore: true, includeAfter: false });
552
- localTriples.push(invert ? new Triple(o, pred, subject) : new Triple(subject, pred, o));
434
+ localTriples.push(new Triple(subject, pred, o));
553
435
  if (postTriples && postTriples.length) localTriples.push(...postTriples);
554
436
  if (annotations && annotations.length) localTriples.push(...annotations);
555
437
  }
@@ -581,79 +463,19 @@ class Parser {
581
463
  }
582
464
 
583
465
  const left = this.parseTerm();
584
- if (this.peek().typ === 'OpImplies') {
585
- this.next();
586
- const right = this.parseTerm();
587
- const pred = internIri(LOG_NS + 'implies');
588
- triples.push(new Triple(left, pred, right));
589
- if (this.peek().typ === 'Dot') this.next();
590
- else if (this.peek().typ === 'RBrace') {
591
- // ok
592
- } else {
593
- this.fail(`Expected '.' or '}', got ${this.peek().toString()}`);
594
- }
595
- } else if (this.peek().typ === 'OpImpliedBy') {
596
- this.next();
597
- const right = this.parseTerm();
598
- const pred = internIri(LOG_NS + 'impliedBy');
599
- triples.push(new Triple(left, pred, right));
600
- if (this.peek().typ === 'Dot') this.next();
601
- else if (this.peek().typ === 'RBrace') {
602
- // ok
603
- } else {
604
- this.fail(`Expected '.' or '}', got ${this.peek().toString()}`);
605
- }
606
- } else {
607
- // N3 grammar allows: triples ::= subject predicateObjectList?
608
- // So a bare subject (optionally producing helper triples) is allowed inside formulas as well.
609
- if (this.peek().typ === 'Dot' || this.peek().typ === 'RBrace') {
610
- this.flushPendingTriples(triples);
611
- if (this.peek().typ === 'Dot') this.next();
612
- continue;
613
- }
614
-
615
- triples.push(...this.parsePredicateObjectList(left));
466
+ // A bare subject contributes only the triples it produced, if any.
467
+ if (this.peek().typ === 'Dot' || this.peek().typ === 'RBrace') {
468
+ this.flushPendingTriples(triples);
616
469
  if (this.peek().typ === 'Dot') this.next();
617
- else if (this.peek().typ === 'RBrace') {
618
- // ok
619
- } else {
620
- this.fail(`Expected '.' or '}', got ${this.peek().toString()}`);
621
- }
470
+ continue;
622
471
  }
623
- }
624
- this.next(); // consume '}'
625
- return annotateQuotedGraphTerm(new GraphTerm(triples));
626
- }
627
472
 
628
- parseStatementVerb() {
629
- let verb;
630
- let invert = false;
631
-
632
- if (this.peek().typ === 'Ident' && (this.peek().value || '') === 'a') {
633
- this.next();
634
- verb = internIri(RDF_NS + 'type');
635
- } else if (this.peek().typ === 'Ident' && (this.peek().value || '') === 'has') {
636
- // N3 syntactic sugar: "S has P O." means "S P O."
637
- this.next();
638
- verb = this.parseTerm();
639
- } else if (this.peek().typ === 'Ident' && (this.peek().value || '') === 'is') {
640
- // N3 syntactic sugar: "S is P of O." means "O P S." (inverse; equivalent to "<-")
641
- this.next();
642
- verb = this.parseTerm();
643
- if (!(this.peek().typ === 'Ident' && (this.peek().value || '') === 'of')) {
644
- this.fail(`Expected 'of' after 'is <expr>', got ${this.peek().toString()}`);
645
- }
646
- this.next();
647
- invert = true;
648
- } else if (this.peek().typ === 'OpPredInvert') {
649
- this.next();
650
- verb = this.parseTerm();
651
- invert = true;
652
- } else {
653
- verb = this.parseTerm();
473
+ triples.push(...this.parsePredicateObjectList(left));
474
+ if (this.peek().typ === 'Dot') this.next();
475
+ else if (this.peek().typ !== 'RBrace') this.fail(`Expected '.' or '}', got ${this.peek().toString()}`);
654
476
  }
655
-
656
- return { verb, invert };
477
+ this.next(); // consume '}'
478
+ return new GraphTerm(triples);
657
479
  }
658
480
 
659
481
  parsePredicateObjectList(subject) {
@@ -663,17 +485,17 @@ class Parser {
663
485
  this.flushPendingTriples(out);
664
486
 
665
487
  while (true) {
666
- const { verb, invert } = this.parseStatementVerb();
488
+ const verb = this.parseVerb();
667
489
 
668
490
  while (true) {
669
491
  const o = this.parseTerm();
670
492
  const postTriples = this.pendingTriplesAfter;
671
493
  this.pendingTriplesAfter = [];
672
- const triple = new Triple(invert ? o : subject, verb, invert ? subject : o);
494
+ const triple = new Triple(subject, verb, o);
673
495
  const annotations = this.parseAnnotations(triple);
674
496
 
675
- // If VERB or OBJECT contained paths, their helper triples must come
676
- // before the triple that consumes the path result (Easter depends on this).
497
+ // The triples of reified triples in the verb or object come before
498
+ // the triple that uses them.
677
499
  this.flushPendingTriples(out);
678
500
 
679
501
  out.push(triple);
@@ -743,85 +565,6 @@ class Parser {
743
565
  }
744
566
  return out;
745
567
  }
746
-
747
- makeRule(left, right, isForward) {
748
- let premiseTerm, conclTerm;
749
-
750
- if (isForward) {
751
- premiseTerm = left;
752
- conclTerm = right;
753
- } else {
754
- premiseTerm = right;
755
- conclTerm = left;
756
- }
757
-
758
- let isFuse = false;
759
- if (isForward) {
760
- if (conclTerm instanceof Literal && conclTerm.value === 'false') {
761
- isFuse = true;
762
- }
763
- }
764
-
765
- let rawPremise;
766
- if (premiseTerm instanceof GraphTerm) {
767
- rawPremise = premiseTerm.triples;
768
- } else if (premiseTerm instanceof Literal && premiseTerm.value === 'true') {
769
- rawPremise = [];
770
- } else {
771
- rawPremise = [];
772
- }
773
-
774
- // In standard N3, the right-hand side of a rule is a formula term.
775
- // eyemind: a conclusion can be an explicit quoted formula `{ ... }` (GraphTerm)
776
- // or the special literals true/false.
777
- //
778
- // However, some programs use a *variable* in rule head position to mean:
779
- // "prove the body, bind ?C to a quoted formula, and then assert that formula".
780
- // Example:
781
- // { :a :b ?C } => ?C.
782
- //
783
- // To support this, we allow a forward rule to carry a dynamic head term.
784
- // The engine will resolve it per-solution and, if it becomes a GraphTerm,
785
- // will emit its triples as the instantiated head.
786
- let rawConclusion;
787
- let dynamicConclusionTerm = null;
788
- if (conclTerm instanceof GraphTerm) {
789
- rawConclusion = conclTerm.triples;
790
- } else if (conclTerm instanceof Literal && conclTerm.value === 'false') {
791
- rawConclusion = [];
792
- } else if (conclTerm instanceof Literal && conclTerm.value === 'true') {
793
- // `=> true.` is a no-op (empty head)
794
- rawConclusion = [];
795
- } else {
796
- rawConclusion = [];
797
- // Only forward rules can meaningfully "emit" a dynamic head.
798
- // Backward rules with dynamic heads are not supported.
799
- if (isForward && conclTerm) dynamicConclusionTerm = conclTerm;
800
- }
801
-
802
- // Blank nodes that occur explicitly in the head (conclusion)
803
- const headBlankLabels = collectBlankLabelsInTriples(rawConclusion);
804
-
805
- const [premise0, conclusion] = liftBlankRuleVars(rawPremise, rawConclusion);
806
-
807
- // Keep premise order as written; the engine may defer some builtins in
808
- // forward rules when they cannot yet run due to unbound variables.
809
- const premise = premise0;
810
-
811
- const r = new Rule(premise, conclusion, isForward, isFuse, headBlankLabels);
812
-
813
- if (dynamicConclusionTerm) {
814
- // Non-enumerable to keep AST output stable unless explicitly requested.
815
- Object.defineProperty(r, '__dynamicConclusionTerm', {
816
- value: dynamicConclusionTerm,
817
- enumerable: false,
818
- writable: false,
819
- configurable: true,
820
- });
821
- }
822
-
823
- return r;
824
- }
825
568
  }
826
569
 
827
570
  export { Parser };