eyemind 0.9.17 → 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() {
@@ -310,32 +267,10 @@ class Parser {
310
267
  }
311
268
 
312
269
  parseTerm() {
313
- let t = this.parsePathItem();
314
-
315
- while (this.peek().typ === 'OpPathFwd' || this.peek().typ === 'OpPathRev') {
316
- const dir = this.next().typ; // OpPathFwd | OpPathRev
317
- const pred = this.parsePathItem();
318
-
319
- this.blankCounter += 1;
320
- const bn = new Blank(`_:b${this.blankCounter}`, 'unlabeled');
321
-
322
- this.pendingTriples.push(dir === 'OpPathFwd' ? new Triple(t, pred, bn) : new Triple(bn, pred, t));
323
-
324
- t = bn;
325
- }
326
-
327
- return t;
328
- }
329
-
330
- parsePathItem() {
331
270
  const tok = this.next();
332
271
  const typ = tok.typ;
333
272
  const val = tok.value;
334
273
 
335
- if (typ === 'Equals') {
336
- return internIri(OWL_NS + 'sameAs');
337
- }
338
-
339
274
  if (typ === 'LtLt') return this.parseReifiedTriple();
340
275
 
341
276
  if (typ === 'IriRef') {
@@ -398,7 +333,6 @@ class Parser {
398
333
  return internLiteral(s);
399
334
  }
400
335
 
401
- if (typ === 'Var') return new Var(val || '');
402
336
  if (typ === 'LParen') return this.parseList();
403
337
  if (typ === 'LBracket') return this.parseBlank();
404
338
  if (typ === 'LBrace') return this.parseGraph();
@@ -461,43 +395,20 @@ class Parser {
461
395
  return new Blank(id, 'unlabeled');
462
396
  }
463
397
 
464
- parsePropertyVerb() {
465
- let pred;
466
- let invert = false;
467
-
398
+ // A verb: a, or a predicate term.
399
+ parseVerb() {
468
400
  if (this.peek().typ === 'Ident' && (this.peek().value || '') === 'a') {
469
401
  this.next();
470
- pred = internIri(RDF_NS + 'type');
471
- } else if (this.peek().typ === 'Ident' && (this.peek().value || '') === 'has') {
472
- // N3 syntactic sugar is also valid in predicate-object lists,
473
- // including blank node property lists: [ has :p :o ] means _:b :p :o.
474
- this.next();
475
- pred = this.parseTerm();
476
- } else if (this.peek().typ === 'Ident' && (this.peek().value || '') === 'is') {
477
- // N3 syntactic sugar: [ is :p of :s ] means :s :p _:b.
478
- this.next();
479
- pred = this.parseTerm();
480
- if (!(this.peek().typ === 'Ident' && (this.peek().value || '') === 'of')) {
481
- this.fail(`Expected 'of' after 'is <expr>', got ${this.peek().toString()}`);
482
- }
483
- this.next();
484
- invert = true;
485
- } else if (this.peek().typ === 'OpPredInvert') {
486
- this.next();
487
- pred = this.parseTerm();
488
- invert = true;
489
- } else {
490
- pred = this.parseTerm();
402
+ return internIri(RDF_NS + 'type');
491
403
  }
492
-
493
- return { pred, invert };
404
+ return this.parseTerm();
494
405
  }
495
406
 
496
407
  parsePropertyListTriples(subject, closingTyp, contextLabel) {
497
408
  const localTriples = [];
498
409
 
499
410
  while (true) {
500
- const { pred, invert } = this.parsePropertyVerb();
411
+ const pred = this.parseVerb();
501
412
 
502
413
  // If a pathological predicate term produced post-triples, don't let them leak.
503
414
  this.flushPendingTriples(localTriples, { includeBefore: false, includeAfter: true });
@@ -507,7 +418,7 @@ class Parser {
507
418
  const term = this.parseTerm();
508
419
  const postTriples = this.pendingTriplesAfter;
509
420
  this.pendingTriplesAfter = [];
510
- 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));
511
422
  objs.push({ term, postTriples, annotations });
512
423
  };
513
424
 
@@ -520,7 +431,7 @@ class Parser {
520
431
  for (const { term: o, postTriples, annotations } of objs) {
521
432
  // Path helper triples must come before the triple that consumes the path result.
522
433
  this.flushPendingTriples(localTriples, { includeBefore: true, includeAfter: false });
523
- localTriples.push(invert ? new Triple(o, pred, subject) : new Triple(subject, pred, o));
434
+ localTriples.push(new Triple(subject, pred, o));
524
435
  if (postTriples && postTriples.length) localTriples.push(...postTriples);
525
436
  if (annotations && annotations.length) localTriples.push(...annotations);
526
437
  }
@@ -552,79 +463,19 @@ class Parser {
552
463
  }
553
464
 
554
465
  const left = this.parseTerm();
555
- if (this.peek().typ === 'OpImplies') {
556
- this.next();
557
- const right = this.parseTerm();
558
- const pred = internIri(LOG_NS + 'implies');
559
- triples.push(new Triple(left, pred, right));
560
- if (this.peek().typ === 'Dot') this.next();
561
- else if (this.peek().typ === 'RBrace') {
562
- // ok
563
- } else {
564
- this.fail(`Expected '.' or '}', got ${this.peek().toString()}`);
565
- }
566
- } else if (this.peek().typ === 'OpImpliedBy') {
567
- this.next();
568
- const right = this.parseTerm();
569
- const pred = internIri(LOG_NS + 'impliedBy');
570
- triples.push(new Triple(left, pred, right));
571
- if (this.peek().typ === 'Dot') this.next();
572
- else if (this.peek().typ === 'RBrace') {
573
- // ok
574
- } else {
575
- this.fail(`Expected '.' or '}', got ${this.peek().toString()}`);
576
- }
577
- } else {
578
- // N3 grammar allows: triples ::= subject predicateObjectList?
579
- // So a bare subject (optionally producing helper triples) is allowed inside formulas as well.
580
- if (this.peek().typ === 'Dot' || this.peek().typ === 'RBrace') {
581
- this.flushPendingTriples(triples);
582
- if (this.peek().typ === 'Dot') this.next();
583
- continue;
584
- }
585
-
586
- 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);
587
469
  if (this.peek().typ === 'Dot') this.next();
588
- else if (this.peek().typ === 'RBrace') {
589
- // ok
590
- } else {
591
- this.fail(`Expected '.' or '}', got ${this.peek().toString()}`);
592
- }
470
+ continue;
593
471
  }
594
- }
595
- this.next(); // consume '}'
596
- return annotateQuotedGraphTerm(new GraphTerm(triples));
597
- }
598
-
599
- parseStatementVerb() {
600
- let verb;
601
- let invert = false;
602
472
 
603
- if (this.peek().typ === 'Ident' && (this.peek().value || '') === 'a') {
604
- this.next();
605
- verb = internIri(RDF_NS + 'type');
606
- } else if (this.peek().typ === 'Ident' && (this.peek().value || '') === 'has') {
607
- // N3 syntactic sugar: "S has P O." means "S P O."
608
- this.next();
609
- verb = this.parseTerm();
610
- } else if (this.peek().typ === 'Ident' && (this.peek().value || '') === 'is') {
611
- // N3 syntactic sugar: "S is P of O." means "O P S." (inverse; equivalent to "<-")
612
- this.next();
613
- verb = this.parseTerm();
614
- if (!(this.peek().typ === 'Ident' && (this.peek().value || '') === 'of')) {
615
- this.fail(`Expected 'of' after 'is <expr>', got ${this.peek().toString()}`);
616
- }
617
- this.next();
618
- invert = true;
619
- } else if (this.peek().typ === 'OpPredInvert') {
620
- this.next();
621
- verb = this.parseTerm();
622
- invert = true;
623
- } else {
624
- 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()}`);
625
476
  }
626
-
627
- return { verb, invert };
477
+ this.next(); // consume '}'
478
+ return new GraphTerm(triples);
628
479
  }
629
480
 
630
481
  parsePredicateObjectList(subject) {
@@ -634,17 +485,17 @@ class Parser {
634
485
  this.flushPendingTriples(out);
635
486
 
636
487
  while (true) {
637
- const { verb, invert } = this.parseStatementVerb();
488
+ const verb = this.parseVerb();
638
489
 
639
490
  while (true) {
640
491
  const o = this.parseTerm();
641
492
  const postTriples = this.pendingTriplesAfter;
642
493
  this.pendingTriplesAfter = [];
643
- const triple = new Triple(invert ? o : subject, verb, invert ? subject : o);
494
+ const triple = new Triple(subject, verb, o);
644
495
  const annotations = this.parseAnnotations(triple);
645
496
 
646
- // If VERB or OBJECT contained paths, their helper triples must come
647
- // 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.
648
499
  this.flushPendingTriples(out);
649
500
 
650
501
  out.push(triple);
@@ -714,85 +565,6 @@ class Parser {
714
565
  }
715
566
  return out;
716
567
  }
717
-
718
- makeRule(left, right, isForward) {
719
- let premiseTerm, conclTerm;
720
-
721
- if (isForward) {
722
- premiseTerm = left;
723
- conclTerm = right;
724
- } else {
725
- premiseTerm = right;
726
- conclTerm = left;
727
- }
728
-
729
- let isFuse = false;
730
- if (isForward) {
731
- if (conclTerm instanceof Literal && conclTerm.value === 'false') {
732
- isFuse = true;
733
- }
734
- }
735
-
736
- let rawPremise;
737
- if (premiseTerm instanceof GraphTerm) {
738
- rawPremise = premiseTerm.triples;
739
- } else if (premiseTerm instanceof Literal && premiseTerm.value === 'true') {
740
- rawPremise = [];
741
- } else {
742
- rawPremise = [];
743
- }
744
-
745
- // In standard N3, the right-hand side of a rule is a formula term.
746
- // eyemind: a conclusion can be an explicit quoted formula `{ ... }` (GraphTerm)
747
- // or the special literals true/false.
748
- //
749
- // However, some programs use a *variable* in rule head position to mean:
750
- // "prove the body, bind ?C to a quoted formula, and then assert that formula".
751
- // Example:
752
- // { :a :b ?C } => ?C.
753
- //
754
- // To support this, we allow a forward rule to carry a dynamic head term.
755
- // The engine will resolve it per-solution and, if it becomes a GraphTerm,
756
- // will emit its triples as the instantiated head.
757
- let rawConclusion;
758
- let dynamicConclusionTerm = null;
759
- if (conclTerm instanceof GraphTerm) {
760
- rawConclusion = conclTerm.triples;
761
- } else if (conclTerm instanceof Literal && conclTerm.value === 'false') {
762
- rawConclusion = [];
763
- } else if (conclTerm instanceof Literal && conclTerm.value === 'true') {
764
- // `=> true.` is a no-op (empty head)
765
- rawConclusion = [];
766
- } else {
767
- rawConclusion = [];
768
- // Only forward rules can meaningfully "emit" a dynamic head.
769
- // Backward rules with dynamic heads are not supported.
770
- if (isForward && conclTerm) dynamicConclusionTerm = conclTerm;
771
- }
772
-
773
- // Blank nodes that occur explicitly in the head (conclusion)
774
- const headBlankLabels = collectBlankLabelsInTriples(rawConclusion);
775
-
776
- const [premise0, conclusion] = liftBlankRuleVars(rawPremise, rawConclusion);
777
-
778
- // Keep premise order as written; the engine may defer some builtins in
779
- // forward rules when they cannot yet run due to unbound variables.
780
- const premise = premise0;
781
-
782
- const r = new Rule(premise, conclusion, isForward, isFuse, headBlankLabels);
783
-
784
- if (dynamicConclusionTerm) {
785
- // Non-enumerable to keep AST output stable unless explicitly requested.
786
- Object.defineProperty(r, '__dynamicConclusionTerm', {
787
- value: dynamicConclusionTerm,
788
- enumerable: false,
789
- writable: false,
790
- configurable: true,
791
- });
792
- }
793
-
794
- return r;
795
- }
796
568
  }
797
569
 
798
570
  export { Parser };