Debian Codegraph @

src/N3Parser.js

raw
1 // **N3Parser** parses N3 documents.
2 import N3Lexer from './N3Lexer';
3 import N3DataFactory from './N3DataFactory';
4 import namespaces from './IRIs';
5
6 let blankNodePrefix = 0;
7
8 // ## Constructor
9 export default class N3Parser {
10 constructor(options) {
11 this._contextStack = [];
12 this._graph = null;
13
14 // Set the document IRI
15 options = options || {};
16 this._setBase(options.baseIRI);
17 options.factory && initDataFactory(this, options.factory);
18
19 // Set supported features depending on the format
20 const format = (typeof options.format === 'string') ?
21 options.format.match(/\w*$/)[0].toLowerCase() : '',
22 isTurtle = /turtle/.test(format), isTriG = /trig/.test(format),
23 isNTriples = /triple/.test(format), isNQuads = /quad/.test(format),
24 isN3 = this._n3Mode = /n3/.test(format),
25 isLineMode = isNTriples || isNQuads;
26 if (!(this._supportsNamedGraphs = !(isTurtle || isN3)))
27 this._readPredicateOrNamedGraph = this._readPredicate;
28 // Support triples in other graphs
29 this._supportsQuads = !(isTurtle || isTriG || isNTriples || isN3);
30 // Support nesting of triples
31 this._supportsRDFStar = format === '' || /star|\*$/.test(format);
32 // Disable relative IRIs in N-Triples or N-Quads mode
33 if (isLineMode)
34 this._resolveRelativeIRI = iri => { return null; };
35 this._blankNodePrefix = typeof options.blankNodePrefix !== 'string' ? '' :
36 options.blankNodePrefix.replace(/^(?!_:)/, '_:');
37 this._lexer = options.lexer || new N3Lexer({ lineMode: isLineMode, n3: isN3 });
38 // Disable explicit quantifiers by default
39 this._explicitQuantifiers = !!options.explicitQuantifiers;
40 }
41
42 // ## Static class methods
43
44 // ### `_resetBlankNodePrefix` restarts blank node prefix identification
45 static _resetBlankNodePrefix() {
46 blankNodePrefix = 0;
47 }
48
49 // ## Private methods
50
51 // ### `_setBase` sets the base IRI to resolve relative IRIs
52 _setBase(baseIRI) {
53 if (!baseIRI) {
54 this._base = '';
55 this._basePath = '';
56 }
57 else {
58 // Remove fragment if present
59 const fragmentPos = baseIRI.indexOf('#');
60 if (fragmentPos >= 0)
61 baseIRI = baseIRI.substr(0, fragmentPos);
62 // Set base IRI and its components
63 this._base = baseIRI;
64 this._basePath = baseIRI.indexOf('/') < 0 ? baseIRI :
65 baseIRI.replace(/[^\/?]*(?:\?.*)?$/, '');
66 baseIRI = baseIRI.match(/^(?:([a-z][a-z0-9+.-]*:))?(?:\/\/[^\/]*)?/i);
67 this._baseRoot = baseIRI[0];
68 this._baseScheme = baseIRI[1];
69 }
70 }
71
72 // ### `_saveContext` stores the current parsing context
73 // when entering a new scope (list, blank node, formula)
74 _saveContext(type, graph, subject, predicate, object) {
75 const n3Mode = this._n3Mode;
76 this._contextStack.push({
77 type,
78 subject, predicate, object, graph,
79 inverse: n3Mode ? this._inversePredicate : false,
80 blankPrefix: n3Mode ? this._prefixes._ : '',
81 quantified: n3Mode ? this._quantified : null,
82 });
83 // The settings below only apply to N3 streams
84 if (n3Mode) {
85 // Every new scope resets the predicate direction
86 this._inversePredicate = false;
87 // In N3, blank nodes are scoped to a formula
88 // (using a dot as separator, as a blank node label cannot start with it)
89 this._prefixes._ = (this._graph ? `${this._graph.id.substr(2)}.` : '.');
90 // Quantifiers are scoped to a formula
91 this._quantified = Object.create(this._quantified);
92 }
93 }
94
95 // ### `_restoreContext` restores the parent context
96 // when leaving a scope (list, blank node, formula)
97 _restoreContext(type, token) {
98 // Obtain the previous context
99 const context = this._contextStack.pop();
100 if (!context || context.type !== type)
101 return this._error(`Unexpected ${token.type}`, token);
102
103 // Restore the quad of the previous context
104 this._subject = context.subject;
105 this._predicate = context.predicate;
106 this._object = context.object;
107 this._graph = context.graph;
108
109 // Restore N3 context settings
110 if (this._n3Mode) {
111 this._inversePredicate = context.inverse;
112 this._prefixes._ = context.blankPrefix;
113 this._quantified = context.quantified;
114 }
115 }
116
117 // ### `_readInTopContext` reads a token when in the top context
118 _readInTopContext(token) {
119 switch (token.type) {
120 // If an EOF token arrives in the top context, signal that we're done
121 case 'eof':
122 if (this._graph !== null)
123 return this._error('Unclosed graph', token);
124 delete this._prefixes._;
125 return this._callback(null, null, this._prefixes);
126 // It could be a prefix declaration
127 case 'PREFIX':
128 this._sparqlStyle = true;
129 case '@prefix':
130 return this._readPrefix;
131 // It could be a base declaration
132 case 'BASE':
133 this._sparqlStyle = true;
134 case '@base':
135 return this._readBaseIRI;
136 // It could be a graph
137 case '{':
138 if (this._supportsNamedGraphs) {
139 this._graph = '';
140 this._subject = null;
141 return this._readSubject;
142 }
143 case 'GRAPH':
144 if (this._supportsNamedGraphs)
145 return this._readNamedGraphLabel;
146 // Otherwise, the next token must be a subject
147 default:
148 return this._readSubject(token);
149 }
150 }
151
152 // ### `_readEntity` reads an IRI, prefixed name, blank node, or variable
153 _readEntity(token, quantifier) {
154 let value;
155 switch (token.type) {
156 // Read a relative or absolute IRI
157 case 'IRI':
158 case 'typeIRI':
159 const iri = this._resolveIRI(token.value);
160 if (iri === null)
161 return this._error('Invalid IRI', token);
162 value = this._namedNode(iri);
163 break;
164 // Read a prefixed name
165 case 'type':
166 case 'prefixed':
167 const prefix = this._prefixes[token.prefix];
168 if (prefix === undefined)
169 return this._error(`Undefined prefix "${token.prefix}:"`, token);
170 value = this._namedNode(prefix + token.value);
171 break;
172 // Read a blank node
173 case 'blank':
174 value = this._blankNode(this._prefixes[token.prefix] + token.value);
175 break;
176 // Read a variable
177 case 'var':
178 value = this._variable(token.value.substr(1));
179 break;
180 // Everything else is not an entity
181 default:
182 return this._error(`Expected entity but got ${token.type}`, token);
183 }
184 // In N3 mode, replace the entity if it is quantified
185 if (!quantifier && this._n3Mode && (value.id in this._quantified))
186 value = this._quantified[value.id];
187 return value;
188 }
189
190 // ### `_readSubject` reads a quad's subject
191 _readSubject(token) {
192 this._predicate = null;
193 switch (token.type) {
194 case '[':
195 // Start a new quad with a new blank node as subject
196 this._saveContext('blank', this._graph,
197 this._subject = this._blankNode(), null, null);
198 return this._readBlankNodeHead;
199 case '(':
200 // Start a new list
201 this._saveContext('list', this._graph, this.RDF_NIL, null, null);
202 this._subject = null;
203 return this._readListItem;
204 case '{':
205 // Start a new formula
206 if (!this._n3Mode)
207 return this._error('Unexpected graph', token);
208 this._saveContext('formula', this._graph,
209 this._graph = this._blankNode(), null, null);
210 return this._readSubject;
211 case '}':
212 // No subject; the graph in which we are reading is closed instead
213 return this._readPunctuation(token);
214 case '@forSome':
215 if (!this._n3Mode)
216 return this._error('Unexpected "@forSome"', token);
217 this._subject = null;
218 this._predicate = this.N3_FORSOME;
219 this._quantifier = this._blankNode;
220 return this._readQuantifierList;
221 case '@forAll':
222 if (!this._n3Mode)
223 return this._error('Unexpected "@forAll"', token);
224 this._subject = null;
225 this._predicate = this.N3_FORALL;
226 this._quantifier = this._variable;
227 return this._readQuantifierList;
228 case 'literal':
229 if (!this._n3Mode)
230 return this._error('Unexpected literal', token);
231
232 if (token.prefix.length === 0) {
233 this._literalValue = token.value;
234 return this._completeSubjectLiteral;
235 }
236 else
237 this._subject = this._literal(token.value, this._namedNode(token.prefix));
238
239 break;
240 case '<<':
241 if (!this._supportsRDFStar)
242 return this._error('Unexpected RDF* syntax', token);
243 this._saveContext('<<', this._graph, null, null, null);
244 this._graph = null;
245 return this._readSubject;
246 default:
247 // Read the subject entity
248 if ((this._subject = this._readEntity(token)) === undefined)
249 return;
250 // In N3 mode, the subject might be a path
251 if (this._n3Mode)
252 return this._getPathReader(this._readPredicateOrNamedGraph);
253 }
254
255 // The next token must be a predicate,
256 // or, if the subject was actually a graph IRI, a named graph
257 return this._readPredicateOrNamedGraph;
258 }
259
260 // ### `_readPredicate` reads a quad's predicate
261 _readPredicate(token) {
262 const type = token.type;
263 switch (type) {
264 case 'inverse':
265 this._inversePredicate = true;
266 case 'abbreviation':
267 this._predicate = this.ABBREVIATIONS[token.value];
268 break;
269 case '.':
270 case ']':
271 case '}':
272 // Expected predicate didn't come, must have been trailing semicolon
273 if (this._predicate === null)
274 return this._error(`Unexpected ${type}`, token);
275 this._subject = null;
276 return type === ']' ? this._readBlankNodeTail(token) : this._readPunctuation(token);
277 case ';':
278 // Additional semicolons can be safely ignored
279 return this._predicate !== null ? this._readPredicate :
280 this._error('Expected predicate but got ;', token);
281 case '[':
282 if (this._n3Mode) {
283 // Start a new quad with a new blank node as subject
284 this._saveContext('blank', this._graph, this._subject,
285 this._subject = this._blankNode(), null);
286 return this._readBlankNodeHead;
287 }
288 case 'blank':
289 if (!this._n3Mode)
290 return this._error('Disallowed blank node as predicate', token);
291 default:
292 if ((this._predicate = this._readEntity(token)) === undefined)
293 return;
294 }
295 // The next token must be an object
296 return this._readObject;
297 }
298
299 // ### `_readObject` reads a quad's object
300 _readObject(token) {
301 switch (token.type) {
302 case 'literal':
303 // Regular literal, can still get a datatype or language
304 if (token.prefix.length === 0) {
305 this._literalValue = token.value;
306 return this._readDataTypeOrLang;
307 }
308 // Pre-datatyped string literal (prefix stores the datatype)
309 else
310 this._object = this._literal(token.value, this._namedNode(token.prefix));
311 break;
312 case '[':
313 // Start a new quad with a new blank node as subject
314 this._saveContext('blank', this._graph, this._subject, this._predicate,
315 this._subject = this._blankNode());
316 return this._readBlankNodeHead;
317 case '(':
318 // Start a new list
319 this._saveContext('list', this._graph, this._subject, this._predicate, this.RDF_NIL);
320 this._subject = null;
321 return this._readListItem;
322 case '{':
323 // Start a new formula
324 if (!this._n3Mode)
325 return this._error('Unexpected graph', token);
326 this._saveContext('formula', this._graph, this._subject, this._predicate,
327 this._graph = this._blankNode());
328 return this._readSubject;
329 case '<<':
330 if (!this._supportsRDFStar)
331 return this._error('Unexpected RDF* syntax', token);
332 this._saveContext('<<', this._graph, this._subject, this._predicate, null);
333 this._graph = null;
334 return this._readSubject;
335 default:
336 // Read the object entity
337 if ((this._object = this._readEntity(token)) === undefined)
338 return;
339 // In N3 mode, the object might be a path
340 if (this._n3Mode)
341 return this._getPathReader(this._getContextEndReader());
342 }
343 return this._getContextEndReader();
344 }
345
346 // ### `_readPredicateOrNamedGraph` reads a quad's predicate, or a named graph
347 _readPredicateOrNamedGraph(token) {
348 return token.type === '{' ? this._readGraph(token) : this._readPredicate(token);
349 }
350
351 // ### `_readGraph` reads a graph
352 _readGraph(token) {
353 if (token.type !== '{')
354 return this._error(`Expected graph but got ${token.type}`, token);
355 // The "subject" we read is actually the GRAPH's label
356 this._graph = this._subject, this._subject = null;
357 return this._readSubject;
358 }
359
360 // ### `_readBlankNodeHead` reads the head of a blank node
361 _readBlankNodeHead(token) {
362 if (token.type === ']') {
363 this._subject = null;
364 return this._readBlankNodeTail(token);
365 }
366 else {
367 this._predicate = null;
368 return this._readPredicate(token);
369 }
370 }
371
372 // ### `_readBlankNodeTail` reads the end of a blank node
373 _readBlankNodeTail(token) {
374 if (token.type !== ']')
375 return this._readBlankNodePunctuation(token);
376
377 // Store blank node quad
378 if (this._subject !== null)
379 this._emit(this._subject, this._predicate, this._object, this._graph);
380
381 // Restore the parent context containing this blank node
382 const empty = this._predicate === null;
383 this._restoreContext('blank', token);
384 // If the blank node was the object, restore previous context and read punctuation
385 if (this._object !== null)
386 return this._getContextEndReader();
387 // If the blank node was the predicate, continue reading the object
388 else if (this._predicate !== null)
389 return this._readObject;
390 // If the blank node was the subject, continue reading the predicate
391 else
392 // If the blank node was empty, it could be a named graph label
393 return empty ? this._readPredicateOrNamedGraph : this._readPredicateAfterBlank;
394 }
395
396 // ### `_readPredicateAfterBlank` reads a predicate after an anonymous blank node
397 _readPredicateAfterBlank(token) {
398 switch (token.type) {
399 case '.':
400 case '}':
401 // No predicate is coming if the triple is terminated here
402 this._subject = null;
403 return this._readPunctuation(token);
404 default:
405 return this._readPredicate(token);
406 }
407 }
408
409 // ### `_readListItem` reads items from a list
410 _readListItem(token) {
411 let item = null, // The item of the list
412 list = null, // The list itself
413 next = this._readListItem; // The next function to execute
414 const previousList = this._subject, // The previous list that contains this list
415 stack = this._contextStack, // The stack of parent contexts
416 parent = stack[stack.length - 1]; // The parent containing the current list
417
418 switch (token.type) {
419 case '[':
420 // Stack the current list quad and start a new quad with a blank node as subject
421 this._saveContext('blank', this._graph,
422 list = this._blankNode(), this.RDF_FIRST,
423 this._subject = item = this._blankNode());
424 next = this._readBlankNodeHead;
425 break;
426 case '(':
427 // Stack the current list quad and start a new list
428 this._saveContext('list', this._graph,
429 list = this._blankNode(), this.RDF_FIRST, this.RDF_NIL);
430 this._subject = null;
431 break;
432 case ')':
433 // Closing the list; restore the parent context
434 this._restoreContext('list', token);
435 // If this list is contained within a parent list, return the membership quad here.
436 // This will be `<parent list element> rdf:first <this list>.`.
437 if (stack.length !== 0 && stack[stack.length - 1].type === 'list')
438 this._emit(this._subject, this._predicate, this._object, this._graph);
439 // Was this list the parent's subject?
440 if (this._predicate === null) {
441 // The next token is the predicate
442 next = this._readPredicate;
443 // No list tail if this was an empty list
444 if (this._subject === this.RDF_NIL)
445 return next;
446 }
447 // The list was in the parent context's object
448 else {
449 next = this._getContextEndReader();
450 // No list tail if this was an empty list
451 if (this._object === this.RDF_NIL)
452 return next;
453 }
454 // Close the list by making the head nil
455 list = this.RDF_NIL;
456 break;
457 case 'literal':
458 // Regular literal, can still get a datatype or language
459 if (token.prefix.length === 0) {
460 this._literalValue = token.value;
461 next = this._readListItemDataTypeOrLang;
462 }
463 // Pre-datatyped string literal (prefix stores the datatype)
464 else {
465 item = this._literal(token.value, this._namedNode(token.prefix));
466 next = this._getContextEndReader();
467 }
468 break;
469 case '{':
470 // Start a new formula
471 if (!this._n3Mode)
472 return this._error('Unexpected graph', token);
473 this._saveContext('formula', this._graph, this._subject, this._predicate,
474 this._graph = this._blankNode());
475 return this._readSubject;
476 default:
477 if ((item = this._readEntity(token)) === undefined)
478 return;
479 }
480
481 // Create a new blank node if no item head was assigned yet
482 if (list === null)
483 this._subject = list = this._blankNode();
484
485 // Is this the first element of the list?
486 if (previousList === null) {
487 // This list is either the subject or the object of its parent
488 if (parent.predicate === null)
489 parent.subject = list;
490 else
491 parent.object = list;
492 }
493 else {
494 // Continue the previous list with the current list
495 this._emit(previousList, this.RDF_REST, list, this._graph);
496 }
497 // If an item was read, add it to the list
498 if (item !== null) {
499 // In N3 mode, the item might be a path
500 if (this._n3Mode && (token.type === 'IRI' || token.type === 'prefixed')) {
501 // Create a new context to add the item's path
502 this._saveContext('item', this._graph, list, this.RDF_FIRST, item);
503 this._subject = item, this._predicate = null;
504 // _readPath will restore the context and output the item
505 return this._getPathReader(this._readListItem);
506 }
507 // Output the item
508 this._emit(list, this.RDF_FIRST, item, this._graph);
509 }
510 return next;
511 }
512
513 // ### `_readDataTypeOrLang` reads an _optional_ datatype or language
514 _readDataTypeOrLang(token) {
515 return this._completeObjectLiteral(token, false);
516 }
517
518
519 // ### `_readListItemDataTypeOrLang` reads an _optional_ datatype or language in a list
520 _readListItemDataTypeOrLang(token) {
521 return this._completeObjectLiteral(token, true);
522 }
523
524 // ### `_completeLiteral` completes a literal with an optional datatype or language
525 _completeLiteral(token) {
526 // Create a simple string literal by default
527 let literal = this._literal(this._literalValue);
528
529 switch (token.type) {
530 // Create a datatyped literal
531 case 'type':
532 case 'typeIRI':
533 const datatype = this._readEntity(token);
534 if (datatype === undefined) return; // No datatype means an error occurred
535 literal = this._literal(this._literalValue, datatype);
536 token = null;
537 break;
538 // Create a language-tagged string
539 case 'langcode':
540 literal = this._literal(this._literalValue, token.value);
541 token = null;
542 break;
543 }
544
545 return { token, literal };
546 }
547
548 // Completes a literal in subject position
549 _completeSubjectLiteral(token) {
550 this._subject = this._completeLiteral(token).literal;
551 return this._readPredicateOrNamedGraph;
552 }
553
554 // Completes a literal in object position
555 _completeObjectLiteral(token, listItem) {
556 const completed = this._completeLiteral(token);
557 if (!completed)
558 return;
559 this._object = completed.literal;
560
561 // If this literal was part of a list, write the item
562 // (we could also check the context stack, but passing in a flag is faster)
563 if (listItem)
564 this._emit(this._subject, this.RDF_FIRST, this._object, this._graph);
565 // If the token was consumed, continue with the rest of the input
566 if (completed.token === null)
567 return this._getContextEndReader();
568 // Otherwise, consume the token now
569 else {
570 this._readCallback = this._getContextEndReader();
571 return this._readCallback(completed.token);
572 }
573 }
574
575 // ### `_readFormulaTail` reads the end of a formula
576 _readFormulaTail(token) {
577 if (token.type !== '}')
578 return this._readPunctuation(token);
579
580 // Store the last quad of the formula
581 if (this._subject !== null)
582 this._emit(this._subject, this._predicate, this._object, this._graph);
583
584 // Restore the parent context containing this formula
585 this._restoreContext('formula', token);
586 // If the formula was the subject, continue reading the predicate.
587 // If the formula was the object, read punctuation.
588 return this._object === null ? this._readPredicate : this._getContextEndReader();
589 }
590
591 // ### `_readPunctuation` reads punctuation between quads or quad parts
592 _readPunctuation(token) {
593 let next, graph = this._graph;
594 const subject = this._subject, inversePredicate = this._inversePredicate;
595 switch (token.type) {
596 // A closing brace ends a graph
597 case '}':
598 if (this._graph === null)
599 return this._error('Unexpected graph closing', token);
600 if (this._n3Mode)
601 return this._readFormulaTail(token);
602 this._graph = null;
603 // A dot just ends the statement, without sharing anything with the next
604 case '.':
605 this._subject = null;
606 next = this._contextStack.length ? this._readSubject : this._readInTopContext;
607 if (inversePredicate) this._inversePredicate = false;
608 break;
609 // Semicolon means the subject is shared; predicate and object are different
610 case ';':
611 next = this._readPredicate;
612 break;
613 // Comma means both the subject and predicate are shared; the object is different
614 case ',':
615 next = this._readObject;
616 break;
617 default:
618 // An entity means this is a quad (only allowed if not already inside a graph)
619 if (this._supportsQuads && this._graph === null && (graph = this._readEntity(token)) !== undefined) {
620 next = this._readQuadPunctuation;
621 break;
622 }
623 return this._error(`Expected punctuation to follow "${this._object.id}"`, token);
624 }
625 // A quad has been completed now, so return it
626 if (subject !== null) {
627 const predicate = this._predicate, object = this._object;
628 if (!inversePredicate)
629 this._emit(subject, predicate, object, graph);
630 else
631 this._emit(object, predicate, subject, graph);
632 }
633 return next;
634 }
635
636 // ### `_readBlankNodePunctuation` reads punctuation in a blank node
637 _readBlankNodePunctuation(token) {
638 let next;
639 switch (token.type) {
640 // Semicolon means the subject is shared; predicate and object are different
641 case ';':
642 next = this._readPredicate;
643 break;
644 // Comma means both the subject and predicate are shared; the object is different
645 case ',':
646 next = this._readObject;
647 break;
648 default:
649 return this._error(`Expected punctuation to follow "${this._object.id}"`, token);
650 }
651 // A quad has been completed now, so return it
652 this._emit(this._subject, this._predicate, this._object, this._graph);
653 return next;
654 }
655
656 // ### `_readQuadPunctuation` reads punctuation after a quad
657 _readQuadPunctuation(token) {
658 if (token.type !== '.')
659 return this._error('Expected dot to follow quad', token);
660 return this._readInTopContext;
661 }
662
663 // ### `_readPrefix` reads the prefix of a prefix declaration
664 _readPrefix(token) {
665 if (token.type !== 'prefix')
666 return this._error('Expected prefix to follow @prefix', token);
667 this._prefix = token.value;
668 return this._readPrefixIRI;
669 }
670
671 // ### `_readPrefixIRI` reads the IRI of a prefix declaration
672 _readPrefixIRI(token) {
673 if (token.type !== 'IRI')
674 return this._error(`Expected IRI to follow prefix "${this._prefix}:"`, token);
675 const prefixNode = this._readEntity(token);
676 this._prefixes[this._prefix] = prefixNode.value;
677 this._prefixCallback(this._prefix, prefixNode);
678 return this._readDeclarationPunctuation;
679 }
680
681 // ### `_readBaseIRI` reads the IRI of a base declaration
682 _readBaseIRI(token) {
683 const iri = token.type === 'IRI' && this._resolveIRI(token.value);
684 if (!iri)
685 return this._error('Expected valid IRI to follow base declaration', token);
686 this._setBase(iri);
687 return this._readDeclarationPunctuation;
688 }
689
690 // ### `_readNamedGraphLabel` reads the label of a named graph
691 _readNamedGraphLabel(token) {
692 switch (token.type) {
693 case 'IRI':
694 case 'blank':
695 case 'prefixed':
696 return this._readSubject(token), this._readGraph;
697 case '[':
698 return this._readNamedGraphBlankLabel;
699 default:
700 return this._error('Invalid graph label', token);
701 }
702 }
703
704 // ### `_readNamedGraphLabel` reads a blank node label of a named graph
705 _readNamedGraphBlankLabel(token) {
706 if (token.type !== ']')
707 return this._error('Invalid graph label', token);
708 this._subject = this._blankNode();
709 return this._readGraph;
710 }
711
712 // ### `_readDeclarationPunctuation` reads the punctuation of a declaration
713 _readDeclarationPunctuation(token) {
714 // SPARQL-style declarations don't have punctuation
715 if (this._sparqlStyle) {
716 this._sparqlStyle = false;
717 return this._readInTopContext(token);
718 }
719
720 if (token.type !== '.')
721 return this._error('Expected declaration to end with a dot', token);
722 return this._readInTopContext;
723 }
724
725 // Reads a list of quantified symbols from a @forSome or @forAll statement
726 _readQuantifierList(token) {
727 let entity;
728 switch (token.type) {
729 case 'IRI':
730 case 'prefixed':
731 if ((entity = this._readEntity(token, true)) !== undefined)
732 break;
733 default:
734 return this._error(`Unexpected ${token.type}`, token);
735 }
736 // Without explicit quantifiers, map entities to a quantified entity
737 if (!this._explicitQuantifiers)
738 this._quantified[entity.id] = this._quantifier(this._blankNode().value);
739 // With explicit quantifiers, output the reified quantifier
740 else {
741 // If this is the first item, start a new quantifier list
742 if (this._subject === null)
743 this._emit(this._graph || this.DEFAULTGRAPH, this._predicate,
744 this._subject = this._blankNode(), this.QUANTIFIERS_GRAPH);
745 // Otherwise, continue the previous list
746 else
747 this._emit(this._subject, this.RDF_REST,
748 this._subject = this._blankNode(), this.QUANTIFIERS_GRAPH);
749 // Output the list item
750 this._emit(this._subject, this.RDF_FIRST, entity, this.QUANTIFIERS_GRAPH);
751 }
752 return this._readQuantifierPunctuation;
753 }
754
755 // Reads punctuation from a @forSome or @forAll statement
756 _readQuantifierPunctuation(token) {
757 // Read more quantifiers
758 if (token.type === ',')
759 return this._readQuantifierList;
760 // End of the quantifier list
761 else {
762 // With explicit quantifiers, close the quantifier list
763 if (this._explicitQuantifiers) {
764 this._emit(this._subject, this.RDF_REST, this.RDF_NIL, this.QUANTIFIERS_GRAPH);
765 this._subject = null;
766 }
767 // Read a dot
768 this._readCallback = this._getContextEndReader();
769 return this._readCallback(token);
770 }
771 }
772
773 // ### `_getPathReader` reads a potential path and then resumes with the given function
774 _getPathReader(afterPath) {
775 this._afterPath = afterPath;
776 return this._readPath;
777 }
778
779 // ### `_readPath` reads a potential path
780 _readPath(token) {
781 switch (token.type) {
782 // Forward path
783 case '!': return this._readForwardPath;
784 // Backward path
785 case '^': return this._readBackwardPath;
786 // Not a path; resume reading where we left off
787 default:
788 const stack = this._contextStack, parent = stack.length && stack[stack.length - 1];
789 // If we were reading a list item, we still need to output it
790 if (parent && parent.type === 'item') {
791 // The list item is the remaining subejct after reading the path
792 const item = this._subject;
793 // Switch back to the context of the list
794 this._restoreContext('item', token);
795 // Output the list item
796 this._emit(this._subject, this.RDF_FIRST, item, this._graph);
797 }
798 return this._afterPath(token);
799 }
800 }
801
802 // ### `_readForwardPath` reads a '!' path
803 _readForwardPath(token) {
804 let subject, predicate;
805 const object = this._blankNode();
806 // The next token is the predicate
807 if ((predicate = this._readEntity(token)) === undefined)
808 return;
809 // If we were reading a subject, replace the subject by the path's object
810 if (this._predicate === null)
811 subject = this._subject, this._subject = object;
812 // If we were reading an object, replace the subject by the path's object
813 else
814 subject = this._object, this._object = object;
815 // Emit the path's current quad and read its next section
816 this._emit(subject, predicate, object, this._graph);
817 return this._readPath;
818 }
819
820 // ### `_readBackwardPath` reads a '^' path
821 _readBackwardPath(token) {
822 const subject = this._blankNode();
823 let predicate, object;
824 // The next token is the predicate
825 if ((predicate = this._readEntity(token)) === undefined)
826 return;
827 // If we were reading a subject, replace the subject by the path's subject
828 if (this._predicate === null)
829 object = this._subject, this._subject = subject;
830 // If we were reading an object, replace the subject by the path's subject
831 else
832 object = this._object, this._object = subject;
833 // Emit the path's current quad and read its next section
834 this._emit(subject, predicate, object, this._graph);
835 return this._readPath;
836 }
837
838 // ### `_readRDFStarTailOrGraph` reads the graph of a nested RDF* quad or the end of a nested RDF* triple
839 _readRDFStarTailOrGraph(token) {
840 if (token.type !== '>>') {
841 // An entity means this is a quad (only allowed if not already inside a graph)
842 if (this._supportsQuads && this._graph === null && (this._graph = this._readEntity(token)) !== undefined)
843 return this._readRDFStarTail;
844 return this._error(`Expected >> to follow "${this._object.id}"`, token);
845 }
846 return this._readRDFStarTail(token);
847 }
848
849 // ### `_readRDFStarTail` reads the end of a nested RDF* triple
850 _readRDFStarTail(token) {
851 if (token.type !== '>>')
852 return this._error(`Expected >> but got ${token.type}`, token);
853 // Read the quad and restore the previous context
854 const quad = this._quad(this._subject, this._predicate, this._object,
855 this._graph || this.DEFAULTGRAPH);
856 this._restoreContext('<<', token);
857 // If the triple was the subject, continue by reading the predicate.
858 if (this._subject === null) {
859 this._subject = quad;
860 return this._readPredicate;
861 }
862 // If the triple was the object, read context end.
863 else {
864 this._object = quad;
865 return this._getContextEndReader();
866 }
867 }
868
869 // ### `_getContextEndReader` gets the next reader function at the end of a context
870 _getContextEndReader() {
871 const contextStack = this._contextStack;
872 if (!contextStack.length)
873 return this._readPunctuation;
874
875 switch (contextStack[contextStack.length - 1].type) {
876 case 'blank':
877 return this._readBlankNodeTail;
878 case 'list':
879 return this._readListItem;
880 case 'formula':
881 return this._readFormulaTail;
882 case '<<':
883 return this._readRDFStarTailOrGraph;
884 }
885 }
886
887 // ### `_emit` sends a quad through the callback
888 _emit(subject, predicate, object, graph) {
889 this._callback(null, this._quad(subject, predicate, object, graph || this.DEFAULTGRAPH));
890 }
891
892 // ### `_error` emits an error message through the callback
893 _error(message, token) {
894 const err = new Error(`${message} on line ${token.line}.`);
895 err.context = {
896 token: token,
897 line: token.line,
898 previousToken: this._lexer.previousToken,
899 };
900 this._callback(err);
901 this._callback = noop;
902 }
903
904 // ### `_resolveIRI` resolves an IRI against the base path
905 _resolveIRI(iri) {
906 return /^[a-z][a-z0-9+.-]*:/i.test(iri) ? iri : this._resolveRelativeIRI(iri);
907 }
908
909 // ### `_resolveRelativeIRI` resolves an IRI against the base path,
910 // assuming that a base path has been set and that the IRI is indeed relative
911 _resolveRelativeIRI(iri) {
912 // An empty relative IRI indicates the base IRI
913 if (!iri.length)
914 return this._base;
915 // Decide resolving strategy based in the first character
916 switch (iri[0]) {
917 // Resolve relative fragment IRIs against the base IRI
918 case '#': return this._base + iri;
919 // Resolve relative query string IRIs by replacing the query string
920 case '?': return this._base.replace(/(?:\?.*)?$/, iri);
921 // Resolve root-relative IRIs at the root of the base IRI
922 case '/':
923 // Resolve scheme-relative IRIs to the scheme
924 return (iri[1] === '/' ? this._baseScheme : this._baseRoot) + this._removeDotSegments(iri);
925 // Resolve all other IRIs at the base IRI's path
926 default:
927 // Relative IRIs cannot contain a colon in the first path segment
928 return (/^[^/:]*:/.test(iri)) ? null : this._removeDotSegments(this._basePath + iri);
929 }
930 }
931
932 // ### `_removeDotSegments` resolves './' and '../' path segments in an IRI as per RFC3986
933 _removeDotSegments(iri) {
934 // Don't modify the IRI if it does not contain any dot segments
935 if (!/(^|\/)\.\.?($|[/#?])/.test(iri))
936 return iri;
937
938 // Start with an imaginary slash before the IRI in order to resolve trailing './' and '../'
939 const length = iri.length;
940 let result = '', i = -1, pathStart = -1, segmentStart = 0, next = '/';
941
942 while (i < length) {
943 switch (next) {
944 // The path starts with the first slash after the authority
945 case ':':
946 if (pathStart < 0) {
947 // Skip two slashes before the authority
948 if (iri[++i] === '/' && iri[++i] === '/')
949 // Skip to slash after the authority
950 while ((pathStart = i + 1) < length && iri[pathStart] !== '/')
951 i = pathStart;
952 }
953 break;
954 // Don't modify a query string or fragment
955 case '?':
956 case '#':
957 i = length;
958 break;
959 // Handle '/.' or '/..' path segments
960 case '/':
961 if (iri[i + 1] === '.') {
962 next = iri[++i + 1];
963 switch (next) {
964 // Remove a '/.' segment
965 case '/':
966 result += iri.substring(segmentStart, i - 1);
967 segmentStart = i + 1;
968 break;
969 // Remove a trailing '/.' segment
970 case undefined:
971 case '?':
972 case '#':
973 return result + iri.substring(segmentStart, i) + iri.substr(i + 1);
974 // Remove a '/..' segment
975 case '.':
976 next = iri[++i + 1];
977 if (next === undefined || next === '/' || next === '?' || next === '#') {
978 result += iri.substring(segmentStart, i - 2);
979 // Try to remove the parent path from result
980 if ((segmentStart = result.lastIndexOf('/')) >= pathStart)
981 result = result.substr(0, segmentStart);
982 // Remove a trailing '/..' segment
983 if (next !== '/')
984 return `${result}/${iri.substr(i + 1)}`;
985 segmentStart = i + 1;
986 }
987 }
988 }
989 }
990 next = iri[++i];
991 }
992 return result + iri.substring(segmentStart);
993 }
994
995 // ## Public methods
996
997 // ### `parse` parses the N3 input and emits each parsed quad through the callback
998 parse(input, quadCallback, prefixCallback) {
999 // The read callback is the next function to be executed when a token arrives.
1000 // We start reading in the top context.
1001 this._readCallback = this._readInTopContext;
1002 this._sparqlStyle = false;
1003 this._prefixes = Object.create(null);
1004 this._prefixes._ = this._blankNodePrefix ? this._blankNodePrefix.substr(2)
1005 : `b${blankNodePrefix++}_`;
1006 this._prefixCallback = prefixCallback || noop;
1007 this._inversePredicate = false;
1008 this._quantified = Object.create(null);
1009
1010 // Parse synchronously if no quad callback is given
1011 if (!quadCallback) {
1012 const quads = [];
1013 let error;
1014 this._callback = (e, t) => { e ? (error = e) : t && quads.push(t); };
1015 this._lexer.tokenize(input).every(token => {
1016 return this._readCallback = this._readCallback(token);
1017 });
1018 if (error) throw error;
1019 return quads;
1020 }
1021
1022 // Parse asynchronously otherwise, executing the read callback when a token arrives
1023 this._callback = quadCallback;
1024 this._lexer.tokenize(input, (error, token) => {
1025 if (error !== null)
1026 this._callback(error), this._callback = noop;
1027 else if (this._readCallback)
1028 this._readCallback = this._readCallback(token);
1029 });
1030 }
1031 }
1032
1033 // The empty function
1034 function noop() {}
1035
1036 // Initializes the parser with the given data factory
1037 function initDataFactory(parser, factory) {
1038 // Set factory methods
1039 const namedNode = factory.namedNode;
1040 parser._namedNode = namedNode;
1041 parser._blankNode = factory.blankNode;
1042 parser._literal = factory.literal;
1043 parser._variable = factory.variable;
1044 parser._quad = factory.quad;
1045 parser.DEFAULTGRAPH = factory.defaultGraph();
1046
1047 // Set common named nodes
1048 parser.RDF_FIRST = namedNode(namespaces.rdf.first);
1049 parser.RDF_REST = namedNode(namespaces.rdf.rest);
1050 parser.RDF_NIL = namedNode(namespaces.rdf.nil);
1051 parser.N3_FORALL = namedNode(namespaces.r.forAll);
1052 parser.N3_FORSOME = namedNode(namespaces.r.forSome);
1053 parser.ABBREVIATIONS = {
1054 'a': namedNode(namespaces.rdf.type),
1055 '=': namedNode(namespaces.owl.sameAs),
1056 '>': namedNode(namespaces.log.implies),
1057 };
1058 parser.QUANTIFIERS_GRAPH = namedNode('urn:n3:quantifiers');
1059 }
1060 initDataFactory(N3Parser.prototype, N3DataFactory);