eyemind 0.5.0 → 0.5.2

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.
@@ -0,0 +1,827 @@
1
+ /**
2
+ * Eyeling Reasoner — parser
3
+ *
4
+ * Parser for the supported N3 syntax. Turns tokens into the internal term and
5
+ * formula representation used by the engine.
6
+ */
7
+
8
+
9
+ import {
10
+ RDF_NS,
11
+ OWL_NS,
12
+ LOG_NS,
13
+ resolveIriRef,
14
+ Literal,
15
+ Var,
16
+ Blank,
17
+ ListTerm,
18
+ GraphTerm,
19
+ Triple,
20
+ Rule,
21
+ internIri,
22
+ internLiteral,
23
+ PrefixEnv,
24
+ collectBlankLabelsInTriples,
25
+ isLogImplies,
26
+ isLogImpliedBy,
27
+ isLogQuery,
28
+ annotateQuotedGraphTerm,
29
+ } from './rdf-prelude.js';
30
+
31
+ import { N3SyntaxError } from './rdf-lexer.js';
32
+ import { liftBlankRuleVars } from './rdf-rules.js';
33
+
34
+ function assertValidQNamePrefix(prefixName, fail, tok, context = 'prefixed name') {
35
+ if (typeof prefixName === 'string' && prefixName.endsWith('.')) {
36
+ fail(`Invalid ${context}: prefix names cannot end with '.'`, tok);
37
+ }
38
+ }
39
+
40
+ function failInvalidKeywordLikeIdent(fail, tok, name) {
41
+ fail(`invalid_keyword(${name})`, tok);
42
+ }
43
+
44
+ function annotateSourceOffset(obj, offset) {
45
+ if (!obj || typeof offset !== 'number') return obj;
46
+ Object.defineProperty(obj, '__sourceOffset', {
47
+ value: offset,
48
+ enumerable: false,
49
+ writable: false,
50
+ configurable: true,
51
+ });
52
+ return obj;
53
+ }
54
+
55
+ class Parser {
56
+ constructor(tokens, options = {}) {
57
+ this.toks = tokens;
58
+ this.pos = 0;
59
+ this.prefixes = PrefixEnv.newDefault();
60
+ this.blankCounter = 0;
61
+ // Helper triples that must be emitted *before* the triple that consumes them.
62
+ // Used primarily for N3 path expansion (e.g. :a :p/:q :b .).
63
+ this.pendingTriples = [];
64
+
65
+ // Helper triples that should be emitted *after* the triple that references
66
+ // the described term (used for [...] blank-node / IRI property lists). This
67
+ // makes derived output read naturally, e.g. ':s :p _:b.' preceding
68
+ // '_:b :q :r.'
69
+ this.pendingTriplesAfter = [];
70
+ this.trackSourceOffsets = !!(options && options.sourceOffsets);
71
+ }
72
+
73
+ peek() {
74
+ return this.toks[this.pos];
75
+ }
76
+
77
+ next() {
78
+ const tok = this.toks[this.pos];
79
+ this.pos += 1;
80
+ return tok;
81
+ }
82
+
83
+ annotateSourceOffset(obj, offset) {
84
+ return this.trackSourceOffsets ? annotateSourceOffset(obj, offset) : obj;
85
+ }
86
+
87
+ fail(message, tok = this.peek()) {
88
+ const off = tok && typeof tok.offset === 'number' ? tok.offset : null;
89
+ throw new N3SyntaxError(message, off);
90
+ }
91
+
92
+ expectDot() {
93
+ const tok = this.next();
94
+ if (tok.typ !== 'Dot') {
95
+ this.fail(`Expected '.', got ${tok.toString()}`, tok);
96
+ }
97
+ }
98
+
99
+ peekAt(offset) {
100
+ return this.toks[this.pos + offset];
101
+ }
102
+
103
+ isIdentKeyword(tok, keyword) {
104
+ if (!tok || tok.typ !== 'Ident' || typeof tok.value !== 'string') return false;
105
+ const v = tok.value;
106
+ if (v.length !== keyword.length) return false;
107
+ for (let i = 0; i < keyword.length; i++) {
108
+ const code = v.charCodeAt(i);
109
+ const lower = code >= 65 && code <= 90 ? code + 32 : code;
110
+ if (lower !== keyword.charCodeAt(i)) return false;
111
+ }
112
+ return true;
113
+ }
114
+
115
+ canStartSparqlPrefixDirective() {
116
+ const prefixNameTok = this.peekAt(1);
117
+ const iriTok = this.peekAt(2);
118
+ return (
119
+ this.isIdentKeyword(this.peek(), 'prefix') &&
120
+ prefixNameTok &&
121
+ prefixNameTok.typ === 'Ident' &&
122
+ typeof prefixNameTok.value === 'string' &&
123
+ prefixNameTok.value.endsWith(':') &&
124
+ iriTok &&
125
+ (iriTok.typ === 'IriRef' || iriTok.typ === 'Ident')
126
+ );
127
+ }
128
+
129
+ canStartSparqlBaseDirective(allowIdentIri = false) {
130
+ const iriTok = this.peekAt(1);
131
+ return (
132
+ this.isIdentKeyword(this.peek(), 'base') &&
133
+ iriTok &&
134
+ (iriTok.typ === 'IriRef' || (allowIdentIri && iriTok.typ === 'Ident'))
135
+ );
136
+ }
137
+
138
+ parseDirectiveIfPresent({ allowIdentBaseIri = false } = {}) {
139
+ if (this.peek().typ === 'AtPrefix') {
140
+ this.next();
141
+ this.parsePrefixDirective();
142
+ return true;
143
+ }
144
+ if (this.peek().typ === 'AtBase') {
145
+ this.next();
146
+ this.parseBaseDirective();
147
+ return true;
148
+ }
149
+ if (this.canStartSparqlPrefixDirective()) {
150
+ this.next();
151
+ this.parseSparqlPrefixDirective();
152
+ return true;
153
+ }
154
+ if (this.canStartSparqlBaseDirective(allowIdentBaseIri)) {
155
+ this.next();
156
+ this.parseSparqlBaseDirective();
157
+ return true;
158
+ }
159
+ return false;
160
+ }
161
+
162
+ flushPendingTriples(out, { includeBefore = true, includeAfter = true } = {}) {
163
+ if (includeBefore && this.pendingTriples.length > 0) {
164
+ out.push(...this.pendingTriples);
165
+ this.pendingTriples = [];
166
+ }
167
+ if (includeAfter && this.pendingTriplesAfter.length > 0) {
168
+ out.push(...this.pendingTriplesAfter);
169
+ this.pendingTriplesAfter = [];
170
+ }
171
+ }
172
+
173
+ parseDocument() {
174
+ const triples = [];
175
+ const forwardRules = [];
176
+ const backwardRules = [];
177
+ const logQueries = [];
178
+
179
+ while (this.peek().typ !== 'EOF') {
180
+ if (this.parseDirectiveIfPresent({ allowIdentBaseIri: true })) {
181
+ continue;
182
+ }
183
+
184
+ const statementToken = this.peek();
185
+ const statementOffset = statementToken && typeof statementToken.offset === 'number' ? statementToken.offset : null;
186
+ 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));
197
+ } 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
+ // When present at top-level, eyeling prints 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
+ }
229
+ }
230
+ }
231
+
232
+ return [this.prefixes, triples, forwardRules, backwardRules, logQueries];
233
+ }
234
+
235
+ parsePrefixDirective() {
236
+ const tok = this.next();
237
+ if (tok.typ !== 'Ident') {
238
+ this.fail(`Expected prefix name, got ${tok.toString()}`, tok);
239
+ }
240
+ const pref = tok.value || '';
241
+ if (!pref.endsWith(':')) {
242
+ this.fail("Invalid @prefix directive: prefix name must end with ':'", tok);
243
+ }
244
+ const prefName = pref.endsWith(':') ? pref.slice(0, -1) : pref;
245
+ assertValidQNamePrefix(prefName, this.fail.bind(this), tok, '@prefix directive');
246
+
247
+ if (this.peek().typ === 'Dot') {
248
+ this.next();
249
+ if (!Object.prototype.hasOwnProperty.call(this.prefixes.map, prefName)) {
250
+ this.prefixes.set(prefName, '');
251
+ }
252
+ return;
253
+ }
254
+
255
+ 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
+ }
267
+ this.expectDot();
268
+ this.prefixes.set(prefName, iri);
269
+ }
270
+
271
+ parseBaseDirective() {
272
+ 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
+ }
284
+ this.expectDot();
285
+ this.prefixes.setBase(iri);
286
+ }
287
+
288
+ parseSparqlPrefixDirective() {
289
+ // SPARQL/Turtle-style PREFIX directive: PREFIX pfx: <iri> (no trailing '.')
290
+ const tok = this.next();
291
+ if (tok.typ !== 'Ident') {
292
+ this.fail(`Expected prefix name after PREFIX, got ${tok.toString()}`, tok);
293
+ }
294
+ const pref = tok.value || '';
295
+ if (!pref.endsWith(':')) {
296
+ this.fail("Invalid PREFIX directive: prefix name must end with ':'", tok);
297
+ }
298
+ const prefName = pref.endsWith(':') ? pref.slice(0, -1) : pref;
299
+ assertValidQNamePrefix(prefName, this.fail.bind(this), tok, 'PREFIX directive');
300
+
301
+ 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
+ }
313
+
314
+ // N3/Turtle: PREFIX directives do not have a trailing '.', but accept it permissively.
315
+ if (this.peek().typ === 'Dot') this.next();
316
+
317
+ this.prefixes.set(prefName, iri);
318
+ }
319
+
320
+ parseSparqlBaseDirective() {
321
+ // SPARQL/Turtle-style BASE directive: BASE <iri> (no trailing '.')
322
+ 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
+ }
334
+
335
+ // N3/Turtle: BASE directives do not have a trailing '.', but accept it permissively.
336
+ if (this.peek().typ === 'Dot') this.next();
337
+
338
+ this.prefixes.setBase(iri);
339
+ }
340
+
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;
357
+ }
358
+
359
+ parsePathItem() {
360
+ const tok = this.next();
361
+ const typ = tok.typ;
362
+ const val = tok.value;
363
+
364
+ if (typ === 'Equals') {
365
+ return internIri(OWL_NS + 'sameAs');
366
+ }
367
+
368
+ if (typ === 'LtLt') return this.parseReifiedTriple();
369
+
370
+ if (typ === 'IriRef') {
371
+ const base = this.prefixes.baseIri || '';
372
+ return internIri(resolveIriRef(val || '', base));
373
+ }
374
+ if (typ === 'Ident') {
375
+ const name = val || '';
376
+ if (name === 'a') {
377
+ return internIri(RDF_NS + 'type');
378
+ }
379
+ const sep = name.indexOf(':');
380
+ if (sep === 1 && name.charCodeAt(0) === 95) {
381
+ return new Blank(name);
382
+ }
383
+ if (sep >= 0) {
384
+ const prefixName = name.slice(0, sep);
385
+ assertValidQNamePrefix(prefixName, this.fail.bind(this), tok);
386
+ const base = this.prefixes.map[prefixName] || '';
387
+ return internIri(base ? base + name.slice(sep + 1) : name);
388
+ }
389
+ failInvalidKeywordLikeIdent(this.fail.bind(this), tok, name);
390
+ }
391
+
392
+ if (typ === 'Literal') {
393
+ let s = val || '';
394
+
395
+ // Optional language tag: "..."@en, per N3 LANGTAG production.
396
+ if (this.peek().typ === 'LangTag') {
397
+ // Only quoted string literals can carry a language tag.
398
+ if (!(s.startsWith('"') && s.endsWith('"'))) {
399
+ this.fail('Language tag is only allowed on quoted string literals', this.peek());
400
+ }
401
+ const langTok = this.next();
402
+ const lang = langTok.value || '';
403
+ s = `${s}@${lang}`;
404
+
405
+ // N3/Turtle: language tags and datatypes are mutually exclusive.
406
+ if (this.peek().typ === 'HatHat') {
407
+ this.fail('A literal cannot have both a language tag (@...) and a datatype (^^...)', this.peek());
408
+ }
409
+ }
410
+
411
+ if (this.peek().typ === 'HatHat') {
412
+ this.next();
413
+ const dtTok = this.next();
414
+ let dtIri;
415
+ if (dtTok.typ === 'IriRef') {
416
+ dtIri = dtTok.value || '';
417
+ } else if (dtTok.typ === 'Ident') {
418
+ const qn = dtTok.value || '';
419
+ if (!qn.includes(':')) failInvalidKeywordLikeIdent(this.fail.bind(this), dtTok, qn);
420
+ assertValidQNamePrefix(qn.slice(0, qn.indexOf(':')), this.fail.bind(this), dtTok, 'datatype prefixed name');
421
+ dtIri = this.prefixes.expandQName(qn);
422
+ } else {
423
+ this.fail(`Expected datatype after ^^, got ${dtTok.toString()}`, dtTok);
424
+ }
425
+ s = `${s}^^<${dtIri}>`;
426
+ }
427
+ return internLiteral(s);
428
+ }
429
+
430
+ if (typ === 'Var') return new Var(val || '');
431
+ if (typ === 'LParen') return this.parseList();
432
+ if (typ === 'LBracket') return this.parseBlank();
433
+ if (typ === 'LBrace') return this.parseGraph();
434
+
435
+ this.fail(`Unexpected term token: ${tok.toString()}`, tok);
436
+ }
437
+
438
+ parseList() {
439
+ const elems = [];
440
+ while (this.peek().typ !== 'RParen') {
441
+ elems.push(this.parseTerm());
442
+ }
443
+ this.next(); // consume ')'
444
+ return new ListTerm(elems);
445
+ }
446
+
447
+ parseBlank() {
448
+ // [] or [ ... ] property list
449
+ if (this.peek().typ === 'RBracket') {
450
+ this.next();
451
+ this.blankCounter += 1;
452
+ return new Blank(`_:b${this.blankCounter}`, 'unlabeled');
453
+ }
454
+
455
+ // IRI property list: [ id <IRI> predicateObjectList? ]
456
+ // Lets you embed descriptions of an IRI directly in object position.
457
+ if (this.peek().typ === 'Ident' && (this.peek().value || '') === 'id') {
458
+ const iriTok = this.next(); // consume 'id'
459
+ const iriTerm = this.parseTerm();
460
+
461
+ // N3 note: 'id' form is not meant to be used with blank node identifiers.
462
+ if (iriTerm instanceof Blank && iriTerm.label.startsWith('_:')) {
463
+ this.fail("Cannot use 'id' keyword with a blank node identifier inside [...]", iriTok);
464
+ }
465
+
466
+ // Optional ';' right after the id IRI (tolerated).
467
+ if (this.peek().typ === 'Semicolon') this.next();
468
+
469
+ // Empty IRI property list: [ id :iri ]
470
+ if (this.peek().typ === 'RBracket') {
471
+ this.next();
472
+ return iriTerm;
473
+ }
474
+
475
+ const localTriples = this.parsePropertyListTriples(iriTerm, 'RBracket', 'IRI property list');
476
+
477
+ // Defer the embedded description until after the triple that references the IRI.
478
+ if (localTriples.length) this.pendingTriplesAfter.push(...localTriples);
479
+ return iriTerm;
480
+ }
481
+
482
+ // [ predicateObjectList ]
483
+ this.blankCounter += 1;
484
+ const id = `_:b${this.blankCounter}`;
485
+ const subj = new Blank(id, 'unlabeled');
486
+ const localTriples = this.parsePropertyListTriples(subj, 'RBracket', 'blank node property list');
487
+
488
+ // Defer the blank-node description until after the triple that references it.
489
+ if (localTriples.length) this.pendingTriplesAfter.push(...localTriples);
490
+ return new Blank(id, 'unlabeled');
491
+ }
492
+
493
+ parsePropertyVerb() {
494
+ let pred;
495
+ let invert = false;
496
+
497
+ if (this.peek().typ === 'Ident' && (this.peek().value || '') === 'a') {
498
+ 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();
520
+ }
521
+
522
+ return { pred, invert };
523
+ }
524
+
525
+ parsePropertyListTriples(subject, closingTyp, contextLabel) {
526
+ const localTriples = [];
527
+
528
+ while (true) {
529
+ const { pred, invert } = this.parsePropertyVerb();
530
+
531
+ // If a pathological predicate term produced post-triples, don't let them leak.
532
+ this.flushPendingTriples(localTriples, { includeBefore: false, includeAfter: true });
533
+
534
+ const objs = [];
535
+ const readObj = () => {
536
+ const term = this.parseTerm();
537
+ const postTriples = this.pendingTriplesAfter;
538
+ this.pendingTriplesAfter = [];
539
+ const annotations = this.parseAnnotations(invert ? new Triple(term, pred, subject) : new Triple(subject, pred, term));
540
+ objs.push({ term, postTriples, annotations });
541
+ };
542
+
543
+ readObj();
544
+ while (this.peek().typ === 'Comma') {
545
+ this.next();
546
+ readObj();
547
+ }
548
+
549
+ for (const { term: o, postTriples, annotations } of objs) {
550
+ // Path helper triples must come before the triple that consumes the path result.
551
+ this.flushPendingTriples(localTriples, { includeBefore: true, includeAfter: false });
552
+ localTriples.push(invert ? new Triple(o, pred, subject) : new Triple(subject, pred, o));
553
+ if (postTriples && postTriples.length) localTriples.push(...postTriples);
554
+ if (annotations && annotations.length) localTriples.push(...annotations);
555
+ }
556
+
557
+ if (this.peek().typ === 'Semicolon') {
558
+ while (this.peek().typ === 'Semicolon') this.next();
559
+ if (this.peek().typ === closingTyp) break;
560
+ continue;
561
+ }
562
+ break;
563
+ }
564
+
565
+ if (this.peek().typ !== closingTyp) {
566
+ this.fail(`Expected ']' at end of ${contextLabel}, got ${this.peek().toString()}`);
567
+ }
568
+ this.next();
569
+
570
+ return localTriples;
571
+ }
572
+
573
+ parseGraph() {
574
+ const triples = [];
575
+ while (this.peek().typ !== 'RBrace') {
576
+ // N3 allows @prefix/@base and SPARQL-style PREFIX/BASE directives anywhere
577
+ // outside of a triple. This includes inside quoted graph terms.
578
+ // These directives affect parsing (prefix/base resolution) but do not emit triples.
579
+ if (this.parseDirectiveIfPresent()) {
580
+ continue;
581
+ }
582
+
583
+ 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));
616
+ 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
+ }
622
+ }
623
+ }
624
+ this.next(); // consume '}'
625
+ return annotateQuotedGraphTerm(new GraphTerm(triples));
626
+ }
627
+
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();
654
+ }
655
+
656
+ return { verb, invert };
657
+ }
658
+
659
+ parsePredicateObjectList(subject) {
660
+ const out = [];
661
+
662
+ // If the SUBJECT was a path or property-list, emit its helper triples first.
663
+ this.flushPendingTriples(out);
664
+
665
+ while (true) {
666
+ const { verb, invert } = this.parseStatementVerb();
667
+
668
+ while (true) {
669
+ const o = this.parseTerm();
670
+ const postTriples = this.pendingTriplesAfter;
671
+ this.pendingTriplesAfter = [];
672
+ const triple = new Triple(invert ? o : subject, verb, invert ? subject : o);
673
+ const annotations = this.parseAnnotations(triple);
674
+
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).
677
+ this.flushPendingTriples(out);
678
+
679
+ out.push(triple);
680
+ if (postTriples.length) out.push(...postTriples);
681
+ if (annotations.length) out.push(...annotations);
682
+
683
+ if (this.peek().typ !== 'Comma') break;
684
+ this.next();
685
+ }
686
+
687
+ if (this.peek().typ === 'Semicolon') {
688
+ while (this.peek().typ === 'Semicolon') this.next();
689
+ // eyemind: a graph's last triple may end with ; before its }.
690
+ if (this.peek().typ === 'Dot' || this.peek().typ === 'RBrace') break;
691
+ continue;
692
+ }
693
+ break;
694
+ }
695
+
696
+ return out;
697
+ }
698
+
699
+ // eyemind: RDF 1.2 reification. A reified triple << s p o ~ r >> stands
700
+ // for its reifier r, or a fresh blank node, which rdf:reifies the triple
701
+ // term; that triple comes before the statement that uses it.
702
+ parseReifiedTriple() {
703
+ const s = this.parseTerm();
704
+ const p = this.parseTerm();
705
+ const o = this.parseTerm();
706
+ let reifier = null;
707
+ if (this.peek().typ === 'Tilde') {
708
+ this.next();
709
+ if (this.peek().typ !== 'GtGt') reifier = this.parseTerm();
710
+ }
711
+ if (this.peek().typ !== 'GtGt') this.fail(`Expected '>>' to close a reified triple, got ${this.peek().toString()}`);
712
+ this.next();
713
+ reifier = reifier ?? this.freshBlank();
714
+ this.pendingTriples.push(new Triple(reifier, internIri(RDF_NS + 'reifies'), new GraphTerm([new Triple(s, p, o)])));
715
+ return reifier;
716
+ }
717
+
718
+ freshBlank() {
719
+ this.blankCounter += 1;
720
+ return new Blank(`_:b${this.blankCounter}`, 'unlabeled');
721
+ }
722
+
723
+ // eyemind: RDF 1.2 annotations after a triple's object: each ~ names a
724
+ // reifier (a fresh blank node when none follows), and each {| ... |}
725
+ // describes the reifier just named, or a fresh one. Returns the triples.
726
+ parseAnnotations(triple) {
727
+ const out = [];
728
+ let current = null;
729
+ const reifies = (reifier) => out.push(new Triple(reifier, internIri(RDF_NS + 'reifies'), new GraphTerm([triple])));
730
+ while (this.peek().typ === 'Tilde' || this.peek().typ === 'AnnotOpen') {
731
+ if (this.next().typ === 'Tilde') {
732
+ const end = ['Tilde', 'AnnotOpen', 'Dot', 'Semicolon', 'Comma', 'RBracket', 'RBrace', 'AnnotClose', 'GtGt', 'EOF'];
733
+ current = end.includes(this.peek().typ) ? this.freshBlank() : this.parseTerm();
734
+ this.flushPendingTriples(out, { includeAfter: false });
735
+ reifies(current);
736
+ } else {
737
+ if (this.peek().typ === 'AnnotClose') this.fail('An annotation block may not be empty');
738
+ const reifier = current ?? this.freshBlank();
739
+ if (!current) reifies(reifier);
740
+ current = null;
741
+ out.push(...this.parsePropertyListTriples(reifier, 'AnnotClose', 'annotation block'));
742
+ }
743
+ }
744
+ return out;
745
+ }
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
+ // Eyeling primarily supports 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
+ }
826
+
827
+ export { Parser };