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,816 @@
1
+
2
+ import { tokenize, SyntaxErrorWithLocation } from './srl-tokenizer.js';
3
+ import { isBuiltinName } from './srl-builtin-names.js';
4
+ import { ruleNeedsRunOnce } from './srl-assignments.js';
5
+ import {
6
+ iri,
7
+ variable,
8
+ blankNode,
9
+ literal,
10
+ tripleTerm,
11
+ RDF_TYPE,
12
+ RDF_FIRST,
13
+ RDF_REST,
14
+ RDF_NIL,
15
+ RDF_REIFIES,
16
+ XSD_STRING,
17
+ XSD_BOOLEAN,
18
+ XSD_INTEGER,
19
+ XSD_DECIMAL,
20
+ XSD_DOUBLE,
21
+ } from './srl-term.js';
22
+
23
+ class Parser {
24
+ constructor(source, options = {}) {
25
+ this.tokens = Array.isArray(source) ? source : tokenize(source, options);
26
+ this.pos = 0;
27
+ this.options = options;
28
+ this.baseIRI = options.baseIRI || null;
29
+ this.version = null;
30
+ this.imports = [];
31
+ this.bnodeCounter = 0;
32
+ this.bodyBnodeLabels = null;
33
+ // Body blank nodes must become variables not used anywhere in the rule,
34
+ // including in the head or in expressions that occur later in the body.
35
+ this.usedVariableNames = new Set(this.tokens.filter((token) => token.type === 'variable').map((token) => token.value));
36
+ this.prefixes = {
37
+ rdf: 'http://www.w3.org/1999/02/22-rdf-syntax-ns#',
38
+ srl: 'http://www.w3.org/ns/sparql-rl#',
39
+ xsd: 'http://www.w3.org/2001/XMLSchema#',
40
+ ...options.prefixes,
41
+ };
42
+ }
43
+
44
+ parseProgram() {
45
+ const data = [];
46
+ const rules = [];
47
+ while (!this.is('eof')) {
48
+ if (this.matchWord('PREFIX')) {
49
+ this.parsePrefix(false);
50
+ } else if (this.matchWord('BASE')) {
51
+ this.parseBase(false);
52
+ } else if (this.matchWord('VERSION')) {
53
+ this.parseVersion();
54
+ } else if (this.matchWord('IMPORTS')) {
55
+ this.parseImports();
56
+ } else if (this.matchWord('DATA')) {
57
+ this.expectValue('{');
58
+ data.push(...this.parseTriplesBlock({ allowPath: false, context: 'data' }));
59
+ } else if (this.matchWord('RULE')) {
60
+ rules.push(this.parseRule());
61
+ } else {
62
+ throw this.error(`Expected PREFIX, BASE, VERSION, IMPORTS, DATA, or RULE; got ${this.peek().value}`);
63
+ }
64
+ }
65
+ return {
66
+ baseIRI: this.baseIRI,
67
+ version: this.version,
68
+ imports: this.imports.slice(),
69
+ prefixes: { ...this.prefixes },
70
+ data,
71
+ rules,
72
+ };
73
+ }
74
+
75
+ parseBase(wasAtBase = false) {
76
+ const iriToken = this.expectType('iri');
77
+ this.baseIRI = iriToken.value;
78
+ if (wasAtBase) this.consumeOptionalDot();
79
+ }
80
+
81
+ parsePrefix(wasAtPrefix = false) {
82
+ const nameToken = this.advance();
83
+ if (nameToken.type !== 'word') throw this.error('Expected prefix name', nameToken);
84
+ let name = nameToken.value;
85
+ if (!name.endsWith(':')) throw this.error('Prefix name must end with :', nameToken);
86
+ name = name.slice(0, -1);
87
+ if (this.strictGrammar() && !isValidPNPrefix(name)) throw this.error(`Invalid prefix name ${nameToken.value}`, nameToken);
88
+ const iriToken = this.expectType('iri');
89
+ this.prefixes[name] = this.resolveIRI(iriToken.value, iriToken);
90
+ if (wasAtPrefix) this.consumeOptionalDot();
91
+ }
92
+
93
+ parseVersion() {
94
+ const token = this.expectType('string');
95
+ if (this.strictGrammar()) {
96
+ if (token.long) throw this.error('VERSION must use a short string literal', token);
97
+ if (token.value !== '1.2') throw this.error('VERSION must be the SPARQL-RL version label \"1.2\"', token);
98
+ }
99
+ this.version = token.value;
100
+ }
101
+
102
+ parseImports() {
103
+ const target = this.parseIRIValue();
104
+ this.imports.push(target.value);
105
+ this.consumeOptionalDot();
106
+ }
107
+
108
+ parseRule() {
109
+ let name = null;
110
+ if (!this.checkValue('{')) name = this.parseIRIValue().value;
111
+ this.expectValue('{');
112
+ const head = this.parseTriplesBlock({ allowPath: false, context: 'head' });
113
+ this.expectWord('WHERE');
114
+ const groundData = this.matchWord('DATA');
115
+ this.expectValue('{');
116
+ const body = this.parseRuleBodyWithBlankNodeScope();
117
+ return { name, head, body, groundData, runOnce: ruleNeedsRunOnce(head, body, this.options) };
118
+ }
119
+
120
+ parseRuleBodyWithBlankNodeScope() {
121
+ const previous = this.bodyBnodeLabels;
122
+ this.bodyBnodeLabels = new Map();
123
+ try {
124
+ return this.parseBodyBlockAlreadyOpen();
125
+ } finally {
126
+ this.bodyBnodeLabels = previous;
127
+ }
128
+ }
129
+
130
+ bodyBlankNodeVariable(label) {
131
+ if (!this.bodyBnodeLabels) this.bodyBnodeLabels = new Map();
132
+ if (!this.bodyBnodeLabels.has(label)) {
133
+ this.bodyBnodeLabels.set(label, this.freshGraphNode({ context: 'body' }));
134
+ }
135
+ return this.bodyBnodeLabels.get(label);
136
+ }
137
+
138
+ parseIRIValue() {
139
+ const token = this.advance();
140
+ if (token.type === 'iri') return { value: this.resolveIRI(token.value, token), lexical: `<${token.value}>` };
141
+ if (token.type === 'word') {
142
+ if (token.value === 'a') return { value: RDF_TYPE, lexical: 'a' };
143
+ if (!token.value.includes(':')) throw this.error(`Expected IRI or prefixed name, got ${token.value}`, token);
144
+ return { value: this.expandPrefixedName(token.value, token), lexical: token.value };
145
+ }
146
+ throw this.error(`Expected IRI or prefixed name, got ${token.value}`, token);
147
+ }
148
+
149
+ parseTriplesBlock(options = {}) {
150
+ const triples = [];
151
+ while (!this.matchValue('}')) {
152
+ triples.push(...this.parseTripleStatement(options));
153
+ this.consumeOptionalDot();
154
+ }
155
+ return triples;
156
+ }
157
+
158
+ parseTripleStatement(options = {}) {
159
+ const subjectNode = this.parseGraphNode({ ...options, position: 'subject' });
160
+ const triples = [...subjectNode.triples];
161
+ triples.push(...this.parsePropertyListForSubject(subjectNode.term, options));
162
+ return triples;
163
+ }
164
+
165
+ parsePropertyListForSubject(subject, options = {}, terminators = ['}', '|}', ']']) {
166
+ const triples = [];
167
+ let keepParsingPredicates = true;
168
+
169
+ while (keepParsingPredicates) {
170
+ if (terminators.some((value) => this.checkValue(value)) || this.checkValue('.')) break;
171
+ const predicate = options.allowPath ? this.parseVerbPathOrSimple(options) : this.parseVerbTerm(options);
172
+ do {
173
+ const objectNode = this.parseGraphNode({ ...options, position: 'object' });
174
+ triples.push(...objectNode.triples);
175
+ const baseTriple = { s: subject, p: predicate, o: objectNode.term };
176
+ triples.push(baseTriple);
177
+ triples.push(...this.parseAnnotationsForTriple(baseTriple, options));
178
+ } while (this.matchValue(','));
179
+
180
+ if (this.matchValue(';')) {
181
+ keepParsingPredicates = !(this.checkValue('.') || terminators.some((value) => this.checkValue(value)));
182
+ } else {
183
+ keepParsingPredicates = false;
184
+ }
185
+ }
186
+
187
+ return triples;
188
+ }
189
+
190
+ parseGraphNode(options = {}) {
191
+ if (this.checkValue('[')) return this.parseBlankNodePropertyList(options);
192
+ if (this.checkValue('(')) return this.parseCollection(options);
193
+ if (this.checkValue('<<')) return this.parseReifiedTripleNode(options);
194
+ return { term: this.parseTerm(options), triples: [] };
195
+ }
196
+
197
+ parseBlankNodePropertyList(options = {}) {
198
+ this.expectValue('[');
199
+ const node = this.freshGraphNode(options);
200
+ if (this.matchValue(']')) return { term: node, triples: [] };
201
+ const triples = this.parsePropertyListForSubject(node, options, [']']);
202
+ this.expectValue(']');
203
+ return { term: node, triples };
204
+ }
205
+
206
+ parseCollection(options = {}) {
207
+ this.expectValue('(');
208
+ if (this.matchValue(')')) return { term: iri(RDF_NIL), triples: [] };
209
+
210
+ const head = this.freshGraphNode(options);
211
+ let current = head;
212
+ const triples = [];
213
+ while (true) {
214
+ const item = this.parseGraphNode(options);
215
+ triples.push(...item.triples);
216
+ triples.push({ s: current, p: iri(RDF_FIRST), o: item.term });
217
+ if (this.matchValue(')')) {
218
+ triples.push({ s: current, p: iri(RDF_REST), o: iri(RDF_NIL) });
219
+ break;
220
+ }
221
+ const rest = this.freshGraphNode(options);
222
+ triples.push({ s: current, p: iri(RDF_REST), o: rest });
223
+ current = rest;
224
+ }
225
+ return { term: head, triples };
226
+ }
227
+
228
+ freshGraphNode(options = {}) {
229
+ do {
230
+ this.bnodeCounter += 1;
231
+ } while (options.context === 'body' && this.usedVariableNames.has(`__b${this.bnodeCounter}`));
232
+ const id = `b${this.bnodeCounter}`;
233
+ if (options.context !== 'body') return blankNode(id);
234
+ this.usedVariableNames.add(`__${id}`);
235
+ return variable(`__${id}`);
236
+ }
237
+
238
+ parseAnnotationsForTriple(baseTriple, options = {}) {
239
+ const triples = [];
240
+ const reified = tripleTerm(baseTriple.s, baseTriple.p, baseTriple.o);
241
+ let currentReifier = null;
242
+
243
+ while (this.checkValue('~') || this.checkValue('{|')) {
244
+ if (this.matchValue('~')) {
245
+ currentReifier = this.parseOptionalReifier(options);
246
+ triples.push({ s: currentReifier, p: iri(RDF_REIFIES), o: reified });
247
+ } else if (this.matchValue('{|')) {
248
+ if (this.checkValue('|}')) throw this.error('Annotation blocks may not be empty');
249
+ const annotationSubject = currentReifier || this.freshGraphNode(options);
250
+ triples.push({ s: annotationSubject, p: iri(RDF_REIFIES), o: reified });
251
+ triples.push(...this.parsePropertyListForSubject(annotationSubject, options, ['|}']));
252
+ this.expectValue('|}');
253
+ }
254
+ }
255
+ return triples;
256
+ }
257
+
258
+ parseOptionalReifier(options = {}) {
259
+ if (this.checkValue('{|') || this.checkValue('.') || this.checkValue(';') || this.checkValue(',') || this.checkValue('}') || this.checkValue('|}') || this.checkValue('>>')) {
260
+ return this.freshGraphNode(options);
261
+ }
262
+ return this.parseVarOrReifierId(options);
263
+ }
264
+
265
+ parseVarOrReifierId(options = {}) {
266
+ const token = this.peek();
267
+ if (token.type === 'variable') return this.parseTerm(options);
268
+ if (token.type === 'iri') return this.parseTerm(options);
269
+ if (token.type === 'word' && (token.value.startsWith('_:') || token.value.includes(':'))) return this.parseTerm(options);
270
+ throw this.error(`Expected variable, IRI, or blank node after ~; got ${token.value}`, token);
271
+ }
272
+
273
+ parseReifiedTripleNode(options = {}) {
274
+ this.expectValue('<<');
275
+ const subjectNode = this.parseReifiedTripleComponent(options);
276
+ const p = this.parseVerbTerm(options);
277
+ const objectNode = this.parseReifiedTripleComponent(options);
278
+ let reifier = null;
279
+ if (this.matchValue('~')) reifier = this.parseOptionalReifier(options);
280
+ this.expectValue('>>');
281
+ reifier = reifier || this.freshGraphNode(options);
282
+ return {
283
+ term: reifier,
284
+ triples: [
285
+ ...subjectNode.triples,
286
+ ...objectNode.triples,
287
+ { s: reifier, p: iri(RDF_REIFIES), o: tripleTerm(subjectNode.term, p, objectNode.term) },
288
+ ],
289
+ };
290
+ }
291
+
292
+ parseReifiedTripleComponent(options = {}) {
293
+ if (this.checkValue('<<')) return this.parseReifiedTripleNode(options);
294
+ return { term: this.parseTerm(options), triples: [] };
295
+ }
296
+
297
+ parseVerbTerm(options = {}) {
298
+ const term = this.parseTerm({ ...options, position: 'predicate' });
299
+ if (term.type !== 'iri' && term.type !== 'var') throw this.error('Expected IRI or variable as predicate');
300
+ return term;
301
+ }
302
+
303
+ parseVerbPathOrSimple(options = {}) {
304
+ if (this.checkType('variable')) return this.parseTerm(options);
305
+ return this.parsePathSequence();
306
+ }
307
+
308
+ parsePathSequence() {
309
+ const parts = [this.parsePathEltOrInverse()];
310
+ while (this.matchValue('/')) parts.push(this.parsePathEltOrInverse());
311
+ return parts.length === 1 ? parts[0] : { type: 'path', kind: 'sequence', parts };
312
+ }
313
+
314
+ parsePathEltOrInverse() {
315
+ if (this.matchValue('^')) return { type: 'path', kind: 'inverse', path: this.parsePathPrimary() };
316
+ return this.parsePathPrimary();
317
+ }
318
+
319
+ parsePathPrimary() {
320
+ if (this.matchValue('(')) {
321
+ const path = this.parsePathSequence();
322
+ this.expectValue(')');
323
+ return path;
324
+ }
325
+ const token = this.peek();
326
+ if (token.type === 'iri' || token.type === 'word') {
327
+ const value = this.parseIRIValue();
328
+ return iri(value.value);
329
+ }
330
+ throw this.error(`Expected path IRI, a, ^, or (, got ${token.value}`, token);
331
+ }
332
+
333
+ parseFilterClause() {
334
+ // SRL FILTER accepts a bracketted expression, a built-in call, or an IRI-named function call.
335
+ // The bracketted-expression form is the familiar FILTER(?x > 10).
336
+ const expr = this.parseExpression();
337
+ return { type: 'filter', expr };
338
+ }
339
+
340
+ parseSetClause() {
341
+ this.expectValue('(');
342
+ const variableToken = this.expectType('variable');
343
+ this.expectValue(':=');
344
+ const expr = this.parseExpression();
345
+ this.expectValue(')');
346
+ return { type: 'set', variable: variableToken.value, expr };
347
+ }
348
+
349
+ parseBindClause() {
350
+ this.expectValue('(');
351
+ const expr = this.parseExpression();
352
+ this.expectWord('AS');
353
+ const variableToken = this.expectType('variable');
354
+ this.expectValue(')');
355
+ return { type: 'bind', variable: variableToken.value, expr };
356
+ }
357
+
358
+ parseBodyBlockAlreadyOpen() {
359
+ const clauses = [];
360
+ while (!this.matchValue('}')) {
361
+ if (this.matchWord('FILTER')) {
362
+ clauses.push(this.parseFilterClause());
363
+ } else if (this.matchWord('SET')) {
364
+ clauses.push(this.parseSetClause());
365
+ } else if (this.matchWord('GROUP')) {
366
+ clauses.push(this.parseGroupClause());
367
+ } else if (this.matchWord('BIND')) {
368
+ throw this.error('BIND is not part of the SPARQL 1.2 RL grammar; use SET');
369
+ } else if (this.matchWord('NOT')) {
370
+ const groundData = this.matchWord('DATA');
371
+ this.expectValue('{');
372
+ const body = this.parseBodyBasicAlreadyOpen();
373
+ clauses.push({ type: 'not', body, groundData });
374
+ } else {
375
+ for (const triple of this.parseTripleStatement({ allowPath: true, context: 'body' })) {
376
+ if (triple.p && triple.p.type === 'path') clauses.push({ type: 'path', triple });
377
+ else clauses.push({ type: 'triple', triple });
378
+ }
379
+ }
380
+ this.consumeOptionalDot();
381
+ }
382
+ return clauses;
383
+ }
384
+
385
+ parseGroupClause() {
386
+ const keys = [];
387
+ if (this.matchWord('BY')) {
388
+ keys.push(this.expectType('variable').value);
389
+ while (this.is('variable')) keys.push(this.advance().value);
390
+ }
391
+ this.expectValue('{');
392
+ const pattern = this.parseBodyBasicAlreadyOpen('GROUP');
393
+ this.expectValue('[');
394
+ const aggregations = [];
395
+ if (!this.matchValue(']')) {
396
+ do {
397
+ const variable = this.expectType('variable').value;
398
+ this.expectValue(':=');
399
+ const name = this.expectType('word').value.toUpperCase();
400
+ if (!['COUNT', 'MIN', 'MAX', 'SUM'].includes(name)) throw this.error(`Unsupported aggregation function ${name}`);
401
+ this.expectValue('(');
402
+ const distinct = name === 'COUNT' && this.matchWord('DISTINCT');
403
+ const argument = name === 'COUNT' && this.matchValue('*') ? '*' : this.expectType('variable').value;
404
+ this.expectValue(')');
405
+ aggregations.push({ variable, function: { name, argument, distinct } });
406
+ } while (this.matchValue(','));
407
+ this.expectValue(']');
408
+ }
409
+ return { type: 'group', keys: [...new Set(keys)], pattern, aggregations };
410
+ }
411
+
412
+ parseBodyBasicAlreadyOpen(context = 'NOT') {
413
+ const clauses = [];
414
+ while (!this.matchValue('}')) {
415
+ if (this.matchWord('FILTER')) {
416
+ clauses.push(this.parseFilterClause());
417
+ } else if (this.matchWord('SET')) {
418
+ if (context !== 'GROUP') throw this.error('SET is not allowed inside NOT blocks by the SRL grammar');
419
+ clauses.push(this.parseSetClause());
420
+ } else if (this.matchWord('BIND')) {
421
+ throw this.error(`BIND is not allowed inside ${context} blocks by the SRL grammar`);
422
+ } else if (this.matchWord('NOT')) {
423
+ throw this.error(`NOT is not allowed inside ${context} blocks by the SRL grammar`);
424
+ } else if (this.matchWord('GROUP')) {
425
+ throw this.error(`GROUP is not allowed inside ${context} blocks by the SRL grammar`);
426
+ } else {
427
+ for (const triple of this.parseTripleStatement({ allowPath: true, context: 'body' })) {
428
+ if (triple.p && triple.p.type === 'path') clauses.push({ type: 'path', triple });
429
+ else clauses.push({ type: 'triple', triple });
430
+ }
431
+ }
432
+ this.consumeOptionalDot();
433
+ }
434
+ return clauses;
435
+ }
436
+
437
+ parseTerm(options = {}) {
438
+ const token = this.advance();
439
+ if (token.type === 'operator' && (token.value === '+' || token.value === '-') && this.peek().type === 'number') {
440
+ const numberToken = this.advance();
441
+ return numericLiteral(token.value === '-' ? -numberToken.value : numberToken.value, token.value === '-' ? `-${numberToken.lexical}` : numberToken.lexical); // eyemind: the sign is part of the lexical form
442
+ }
443
+ if (token.type === 'variable') {
444
+ if (options.context === 'data') throw this.error('DATA blocks may not contain variables', token);
445
+ return variable(token.value);
446
+ }
447
+ if (token.type === 'iri') return iri(this.resolveIRI(token.value, token));
448
+ if (token.type === 'string') return this.parseLiteralAfterToken(token);
449
+ if (token.type === 'number') return numericLiteral(token.value, token.lexical);
450
+ if (token.value === '<<(') return this.parseTripleTermAfterOpen(options);
451
+ if (token.value === '<<') throw this.error('Use << s p o >> as a graph node reifier; use <<( s p o )>> for a triple term', token);
452
+ if (token.type === 'word') {
453
+ if (token.value === 'a') {
454
+ if (options.position !== 'predicate') throw this.error('a is only allowed as a predicate', token);
455
+ return iri(RDF_TYPE);
456
+ }
457
+ if (token.value === 'true') return literal(true, XSD_BOOLEAN);
458
+ if (token.value === 'false') return literal(false, XSD_BOOLEAN);
459
+ if (token.value.startsWith('_:')) {
460
+ const label = token.value.slice(2);
461
+ return options.context === 'body' ? this.bodyBlankNodeVariable(label) : blankNode(label);
462
+ }
463
+ return iri(this.expandPrefixedName(token.value, token));
464
+ }
465
+ throw this.error(`Expected term, got ${token.value}`, token);
466
+ }
467
+
468
+ parseTripleTermAfterOpen(options = {}) {
469
+ const s = this.parseTerm(options);
470
+ const p = this.parseVerbTerm(options);
471
+ const o = this.parseTerm(options);
472
+ this.expectValue(')>>');
473
+ return tripleTerm(s, p, o);
474
+ }
475
+
476
+ parseReifiedTripleAfterOpen(options = {}) {
477
+ const s = this.parseTerm(options);
478
+ const p = this.parseVerbTerm(options);
479
+ const o = this.parseTerm(options);
480
+ if (this.matchValue('~')) {
481
+ if (!this.checkValue('>>')) this.parseVarOrReifierId(options);
482
+ }
483
+ this.expectValue('>>');
484
+ return tripleTerm(s, p, o);
485
+ }
486
+
487
+ parseLiteralAfterToken(token) {
488
+ if (this.matchValue('^^')) {
489
+ const datatype = this.parseDatatypeIRI();
490
+ // eyemind: a typed literal keeps its lexical form.
491
+ return { ...literal(coerceLexicalLiteral(token.value, datatype), datatype, null), lexical: token.value };
492
+ }
493
+ if (this.checkType('word') && /^@[A-Za-z]+(?:-[A-Za-z0-9]+)*(?:--[A-Za-z]+)?$/.test(this.peek().value)) {
494
+ const tagToken = this.advance();
495
+ const rawTag = tagToken.value.slice(1);
496
+ const direction = rawTag.includes('--') ? rawTag.slice(rawTag.lastIndexOf('--') + 2) : null;
497
+ if (direction && direction !== 'ltr' && direction !== 'rtl') {
498
+ throw this.error(`Invalid base direction --${direction}; expected --ltr or --rtl`, tagToken);
499
+ }
500
+ const tag = rawTag.toLowerCase();
501
+ const [lang, langDir = null] = tag.split('--');
502
+ return literal(token.value, null, lang, langDir);
503
+ }
504
+ return literal(token.value);
505
+ }
506
+
507
+ parseDatatypeIRI() {
508
+ const token = this.advance();
509
+ if (token.type === 'iri') return this.resolveIRI(token.value, token);
510
+ if (token.type === 'word') return this.expandPrefixedName(token.value, token);
511
+ throw this.error(`Expected datatype IRI, got ${token.value}`, token);
512
+ }
513
+
514
+ expandPrefixedName(value, token) {
515
+ const colon = value.indexOf(':');
516
+ if (colon < 0) throw this.error(`Expected IRI, prefixed name, literal, blank node, or variable; got ${value}`, token);
517
+ const prefix = value.slice(0, colon);
518
+ const local = value.slice(colon + 1);
519
+ if (this.strictGrammar()) validatePrefixedName(prefix, local, value, token, (message, errToken) => this.error(message, errToken));
520
+ if (!(prefix in this.prefixes)) throw this.error(`Unknown prefix ${prefix}:`, token);
521
+ return this.prefixes[prefix] + decodePNLocalEscapes(local);
522
+ }
523
+
524
+ resolveIRI(value, token = null) {
525
+ if (!this.baseIRI || /^[A-Za-z][A-Za-z0-9+.-]*:/.test(value)) return value;
526
+ try {
527
+ return new URL(value, this.baseIRI).href;
528
+ } catch (_) {
529
+ if (token) throw this.error(`Could not resolve IRI ${value} against BASE ${this.baseIRI}`, token);
530
+ return value;
531
+ }
532
+ }
533
+
534
+ parseExpression(minPrec = 0) {
535
+ let left = this.parseUnaryExpression();
536
+ while (true) {
537
+ const info = this.peekBinaryOperator();
538
+ if (!info || info.prec < minPrec) break;
539
+ this.consumeBinaryOperator(info.op);
540
+ if (info.op === 'IN' || info.op === 'NOT IN') {
541
+ const items = this.parseExpressionListItems();
542
+ left = { type: 'binary', op: info.op, left, right: { type: 'list', items } };
543
+ } else {
544
+ const right = this.parseExpression(info.prec + 1);
545
+ left = { type: 'binary', op: info.op, left, right };
546
+ }
547
+ }
548
+ return left;
549
+ }
550
+
551
+ parseExpressionListItems() {
552
+ this.expectValue('(');
553
+ const items = [];
554
+ if (!this.checkValue(')')) {
555
+ do { items.push(this.parseExpression()); }
556
+ while (this.matchValue(','));
557
+ }
558
+ this.expectValue(')');
559
+ return items;
560
+ }
561
+
562
+ peekBinaryOperator() {
563
+ const token = this.peek();
564
+ if (token.type === 'operator') {
565
+ const prec = binaryPrecedence(token.value);
566
+ return prec >= 0 ? { op: token.value, prec } : null;
567
+ }
568
+ if (token.type === 'word' && token.value.toUpperCase() === 'IN') return { op: 'IN', prec: 3 };
569
+ if (token.type === 'word' && token.value.toUpperCase() === 'NOT' && this.peekN(1).type === 'word' && this.peekN(1).value.toUpperCase() === 'IN') return { op: 'NOT IN', prec: 3 };
570
+ return null;
571
+ }
572
+
573
+ consumeBinaryOperator(op) {
574
+ if (op === 'NOT IN') { this.expectWord('NOT'); this.expectWord('IN'); return; }
575
+ if (op === 'IN') { this.expectWord('IN'); return; }
576
+ this.expectValue(op);
577
+ }
578
+
579
+ parseUnaryExpression() {
580
+ if (this.peek().type === 'operator' && (this.peek().value === '!' || this.peek().value === '-' || this.peek().value === '+')) {
581
+ const op = this.advance().value;
582
+ return { type: 'unary', op, expr: this.parseUnaryExpression() };
583
+ }
584
+ return this.parsePrimaryExpression();
585
+ }
586
+
587
+ parsePrimaryExpression() {
588
+ const token = this.advance();
589
+ if (token.type === 'variable') return { type: 'var', name: token.value };
590
+ if (token.type === 'string') return this.parseLiteralExpressionAfterToken(token);
591
+ // eyemind: a number keeps its datatype and lexical form.
592
+ if (token.type === 'number') return { type: 'literal', value: token.value, term: numericLiteral(token.value, token.lexical) };
593
+ if (token.type === 'iri') {
594
+ const name = this.resolveIRI(token.value, token);
595
+ if (this.checkValue('(')) return this.parseFunctionCallAfterName(name);
596
+ return { type: 'term', value: iri(name) };
597
+ }
598
+ if (token.value === '<<(') return { type: 'term', value: this.parseTripleTermAfterOpen() };
599
+ if (token.value === '<<') throw this.error('Use <<( s p o )>> for triple terms inside expressions', token);
600
+ if (token.type === 'word') {
601
+ if (token.value === 'true') return { type: 'literal', value: true };
602
+ if (token.value === 'false') return { type: 'literal', value: false };
603
+ if (token.value.startsWith('_:')) return { type: 'term', value: blankNode(token.value.slice(2)) };
604
+ if (this.checkValue('(')) {
605
+ if (token.value.includes(':') && token.value !== 'a') {
606
+ const name = this.expandPrefixedName(token.value, token);
607
+ return this.parseFunctionCallAfterName(name);
608
+ }
609
+ if (isBuiltinName(token.value)) return this.parseFunctionCallAfterName(token.value);
610
+ throw this.error(`Unknown built-in or unprefixed function call ${token.value}; use an IRI such as :${token.value} for custom functions`, token);
611
+ }
612
+ if (token.value.includes(':') || token.value === 'a') {
613
+ const value = token.value === 'a' ? RDF_TYPE : this.expandPrefixedName(token.value, token);
614
+ return { type: 'term', value: iri(value) };
615
+ }
616
+ }
617
+ if (token.value === '(') {
618
+ const expr = this.parseExpression();
619
+ this.expectValue(')');
620
+ return expr;
621
+ }
622
+ throw this.error(`Expected expression, got ${token.value}`, token);
623
+ }
624
+
625
+ parseFunctionCallAfterName(name) {
626
+ this.expectValue('(');
627
+ const args = [];
628
+ if (!this.checkValue(')')) {
629
+ do { args.push(this.parseExpression()); }
630
+ while (this.matchValue(','));
631
+ }
632
+ this.expectValue(')');
633
+ return { type: 'call', name, args };
634
+ }
635
+
636
+ parseLiteralExpressionAfterToken(token) {
637
+ const term = this.parseLiteralAfterToken(token);
638
+ if (term.datatype || term.lang) return { type: 'term', value: term };
639
+ return { type: 'literal', value: term.value };
640
+ }
641
+
642
+ consumeOptionalDot() { this.matchValue('.'); }
643
+
644
+ checkWord(value) {
645
+ return this.checkType('word') && this.peek().value.toUpperCase() === value.toUpperCase();
646
+ }
647
+
648
+ matchWord(value) {
649
+ if (this.checkType('word') && this.peek().value.toUpperCase() === value.toUpperCase()) {
650
+ this.advance();
651
+ return true;
652
+ }
653
+ return false;
654
+ }
655
+
656
+ expectWord(value) {
657
+ if (this.matchWord(value)) return this.previous();
658
+ throw this.error(`Expected ${value}, got ${this.peek().value}`);
659
+ }
660
+
661
+ matchValue(value) {
662
+ const token = this.peek();
663
+ if ((token.type === 'punct' || token.type === 'operator') && token.value === value) { this.advance(); return true; }
664
+ return false;
665
+ }
666
+
667
+ expectValue(value) {
668
+ if (this.matchValue(value)) return this.previous();
669
+ throw this.error(`Expected ${value}, got ${this.peek().value}`);
670
+ }
671
+
672
+ checkValue(value) { const token = this.peek(); return (token.type === 'punct' || token.type === 'operator') && token.value === value; }
673
+ checkType(type) { return this.peek().type === type; }
674
+ is(type) { return this.peek().type === type; }
675
+
676
+ expectType(type) {
677
+ if (this.peek().type === type) return this.advance();
678
+ throw this.error(`Expected ${type}, got ${this.peek().value}`);
679
+ }
680
+
681
+ advance() { if (!this.is('eof')) this.pos += 1; return this.previous(); }
682
+ peek() { return this.tokens[this.pos]; }
683
+ peekN(n) { return this.tokens[this.pos + n] || this.tokens[this.tokens.length - 1]; }
684
+ previous() { return this.tokens[this.pos - 1]; }
685
+ strictGrammar() { return this.options.strictGrammar !== false; }
686
+ error(message, token = this.peek()) { return new SyntaxErrorWithLocation(message, token && token.filename ? token : { ...token, filename: this.options.filename || '<input>' }); }
687
+ }
688
+
689
+
690
+ function isPnCharsBase(ch) {
691
+ if (!ch) return false;
692
+ return /[A-Za-z]/.test(ch) || ch.codePointAt(0) >= 0x00C0;
693
+ }
694
+
695
+ function isPnCharsU(ch) {
696
+ return isPnCharsBase(ch) || ch === '_';
697
+ }
698
+
699
+ function isPnChars(ch) {
700
+ return isPnCharsU(ch) || /[0-9-]/.test(ch) || ch === '\u00B7' || /[\u0300-\u036F\u203F-\u2040]/u.test(ch);
701
+ }
702
+
703
+ function isValidPNPrefix(prefix) {
704
+ if (prefix === '') return true;
705
+ const chars = Array.from(prefix);
706
+ if (!isPnCharsBase(chars[0])) return false;
707
+ if (chars.length > 1 && chars.at(-1) === '.') return false;
708
+ return chars.slice(1).every((ch) => isPnChars(ch) || ch === '.');
709
+ }
710
+
711
+ function plxLength(text, index) {
712
+ const ch = text[index];
713
+ if (ch === '%' && /[0-9A-Fa-f]/.test(text[index + 1] || '') && /[0-9A-Fa-f]/.test(text[index + 2] || '')) return 3;
714
+ if (ch === '\\' && /[_~.!$&'()*+,;=/?#@%-]/.test(text[index + 1] || '')) return 2;
715
+ return 0;
716
+ }
717
+
718
+ function isPNLocalStartAt(text, index) {
719
+ const ch = text[index];
720
+ return isPnCharsU(ch) || /[0-9:]/.test(ch || '') || plxLength(text, index) > 0;
721
+ }
722
+
723
+ function isPNLocalBodyAt(text, index) {
724
+ const ch = text[index];
725
+ return isPnChars(ch) || ch === '.' || ch === ':' || plxLength(text, index) > 0;
726
+ }
727
+
728
+ function isPNLocalEndAt(text, index) {
729
+ const ch = text[index];
730
+ return isPnChars(ch) || ch === ':' || plxLength(text, index) > 0;
731
+ }
732
+
733
+ function validatePNLocal(local) {
734
+ if (local === '') return true;
735
+ if (!isPNLocalStartAt(local, 0)) return false;
736
+ let lastStart = 0;
737
+ for (let i = 0; i < local.length;) {
738
+ const len = plxLength(local, i) || 1;
739
+ if (i > 0 && !isPNLocalBodyAt(local, i)) return false;
740
+ lastStart = i;
741
+ i += len;
742
+ }
743
+ return isPNLocalEndAt(local, lastStart);
744
+ }
745
+
746
+ function validatePrefixedName(prefix, local, value, token, makeError) {
747
+ if (!isValidPNPrefix(prefix)) throw makeError(`Invalid prefixed name ${value}: invalid prefix`, token);
748
+ if (!validatePNLocal(local)) throw makeError(`Invalid prefixed name ${value}: invalid local name`, token);
749
+ }
750
+
751
+ function decodePNLocalEscapes(local) {
752
+ return String(local).replace(/\\([_~.!$&'()*+,;=/?#@%-])/g, '$1');
753
+ }
754
+
755
+ // [95]-[97]: an INTEGER has neither `.` nor exponent, a DECIMAL has a `.`,
756
+ // a DOUBLE has an exponent. The datatype follows the way the number was
757
+ // written, not its value — `72.0` is an xsd:decimal and `7.2e1` an
758
+ // xsd:double even though both are numerically the integer 72.
759
+ function numericLiteral(value, lexical) {
760
+ const text = lexical === undefined ? String(value) : String(lexical);
761
+ // eyemind: a number keeps its lexical form.
762
+ if (/[eE]/.test(text)) return { ...literal(value, XSD_DOUBLE), lexical: text };
763
+ if (text.includes('.')) return { ...literal(value, XSD_DECIMAL), lexical: text };
764
+ return { ...literal(value, XSD_INTEGER), lexical: text };
765
+ }
766
+
767
+ function parseIntegerLiteral(value) {
768
+ const text = String(value);
769
+ const asNumber = Number.parseInt(text, 10);
770
+ return Number.isSafeInteger(asNumber) && String(asNumber) === text.replace(/^\+/, '') ? asNumber : BigInt(text);
771
+ }
772
+
773
+ function coerceLexicalLiteral(value, datatype) {
774
+ if (datatype === XSD_INTEGER) return parseIntegerLiteral(value);
775
+ if (datatype === XSD_DECIMAL || datatype === XSD_DOUBLE) return Number.parseFloat(value);
776
+ if (datatype === XSD_BOOLEAN) return value === 'true' || value === '1';
777
+ return value;
778
+ }
779
+
780
+ function binaryPrecedence(op) {
781
+ return {
782
+ '||': 1,
783
+ '&&': 2,
784
+ '=': 3,
785
+ '!=': 3,
786
+ 'IN': 3,
787
+ 'NOT IN': 3,
788
+ '<': 4,
789
+ '<=': 4,
790
+ '>': 4,
791
+ '>=': 4,
792
+ '+': 5,
793
+ '-': 5,
794
+ '*': 6,
795
+ '/': 6,
796
+ }[op] ?? -1;
797
+ }
798
+
799
+ function parse(source, options = {}) {
800
+ return new Parser(source, options).parseProgram();
801
+ }
802
+
803
+ function parseQuery(source, options = {}) {
804
+ if (/^\s*(QUERY|SELECT)\b/i.test(source)) {
805
+ throw new Error('QUERY/SELECT concrete syntax is not part of the SPARQL-RL rule-set grammar; pass a raw body pattern instead');
806
+ }
807
+ const trimmed = String(source).trim();
808
+ const text = trimmed.startsWith('{') ? `RULE { } WHERE ${trimmed}` : `RULE { } WHERE { ${source} }`;
809
+ const program = new Parser(text, options).parseProgram();
810
+ if (program.rules.length !== 1 || program.data.length !== 0) {
811
+ throw new Error('Expected exactly one raw body pattern');
812
+ }
813
+ return { select: null, body: program.rules[0].body, prefixes: program.prefixes, baseIRI: program.baseIRI };
814
+ }
815
+
816
+ export { Parser, parse, parseQuery };