Debian Codegraph @

src/N3Lexer.js

raw
1 // **N3Lexer** tokenizes N3 documents.
2 import namespaces from './IRIs';
3 import queueMicrotask from 'queue-microtask';
4
5 const { xsd } = namespaces;
6
7 // Regular expression and replacement string to escape N3 strings
8 const escapeSequence = /\\u([a-fA-F0-9]{4})|\\U([a-fA-F0-9]{8})|\\([^])/g;
9 const escapeReplacements = {
10 '\\': '\\', "'": "'", '"': '"',
11 'n': '\n', 'r': '\r', 't': '\t', 'f': '\f', 'b': '\b',
12 '_': '_', '~': '~', '.': '.', '-': '-', '!': '!', '$': '$', '&': '&',
13 '(': '(', ')': ')', '*': '*', '+': '+', ',': ',', ';': ';', '=': '=',
14 '/': '/', '?': '?', '#': '#', '@': '@', '%': '%',
15 };
16 const illegalIriChars = /[\x00-\x20<>\\"\{\}\|\^\`]/;
17
18 const lineModeRegExps = {
19 _iri: true,
20 _unescapedIri: true,
21 _simpleQuotedString: true,
22 _langcode: true,
23 _blank: true,
24 _newline: true,
25 _comment: true,
26 _whitespace: true,
27 _endOfFile: true,
28 };
29 const invalidRegExp = /$0^/;
30
31 // ## Constructor
32 export default class N3Lexer {
33 constructor(options) {
34 // ## Regular expressions
35 // It's slightly faster to have these as properties than as in-scope variables
36 this._iri = /^<((?:[^ <>{}\\]|\\[uU])+)>[ \t]*/; // IRI with escape sequences; needs sanity check after unescaping
37 this._unescapedIri = /^<([^\x00-\x20<>\\"\{\}\|\^\`]*)>[ \t]*/; // IRI without escape sequences; no unescaping
38 this._simpleQuotedString = /^"([^"\\\r\n]*)"(?=[^"])/; // string without escape sequences
39 this._simpleApostropheString = /^'([^'\\\r\n]*)'(?=[^'])/;
40 this._langcode = /^@([a-z]+(?:-[a-z0-9]+)*)(?=[^a-z0-9\-])/i;
41 this._prefix = /^((?:[A-Za-z\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])(?:\.?[\-0-9A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])*)?:(?=[#\s<])/;
42 this._prefixed = /^((?:[A-Za-z\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])(?:\.?[\-0-9A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])*)?:((?:(?:[0-:A-Z_a-z\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff]|%[0-9a-fA-F]{2}|\\[!#-\/;=?\-@_~])(?:(?:[\.\-0-:A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff]|%[0-9a-fA-F]{2}|\\[!#-\/;=?\-@_~])*(?:[\-0-:A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff]|%[0-9a-fA-F]{2}|\\[!#-\/;=?\-@_~]))?)?)(?:[ \t]+|(?=\.?[,;!\^\s#()\[\]\{\}"'<>]))/;
43 this._variable = /^\?(?:(?:[A-Z_a-z\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])(?:[\-0-:A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])*)(?=[.,;!\^\s#()\[\]\{\}"'<>])/;
44 this._blank = /^_:((?:[0-9A-Z_a-z\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])(?:\.?[\-0-9A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])*)(?:[ \t]+|(?=\.?[,;:\s#()\[\]\{\}"'<>]))/;
45 this._number = /^[\-+]?(?:(\d+\.\d*|\.?\d+)[eE][\-+]?|\d*(\.)?)\d+(?=\.?[,;:\s#()\[\]\{\}"'<>])/;
46 this._boolean = /^(?:true|false)(?=[.,;\s#()\[\]\{\}"'<>])/;
47 this._keyword = /^@[a-z]+(?=[\s#<:])/i;
48 this._sparqlKeyword = /^(?:PREFIX|BASE|GRAPH)(?=[\s#<])/i;
49 this._shortPredicates = /^a(?=[\s#()\[\]\{\}"'<>])/;
50 this._newline = /^[ \t]*(?:#[^\n\r]*)?(?:\r\n|\n|\r)[ \t]*/;
51 this._comment = /#([^\n\r]*)/;
52 this._whitespace = /^[ \t]+/;
53 this._endOfFile = /^(?:#[^\n\r]*)?$/;
54 options = options || {};
55
56 // In line mode (N-Triples or N-Quads), only simple features may be parsed
57 if (this._lineMode = !!options.lineMode) {
58 this._n3Mode = false;
59 // Don't tokenize special literals
60 for (const key in this) {
61 if (!(key in lineModeRegExps) && this[key] instanceof RegExp)
62 this[key] = invalidRegExp;
63 }
64 }
65 // When not in line mode, enable N3 functionality by default
66 else {
67 this._n3Mode = options.n3 !== false;
68 }
69 // Don't output comment tokens by default
70 this._comments = !!options.comments;
71 // Cache the last tested closing position of long literals
72 this._literalClosingPos = 0;
73 }
74
75 // ## Private methods
76
77 // ### `_tokenizeToEnd` tokenizes as for as possible, emitting tokens through the callback
78 _tokenizeToEnd(callback, inputFinished) {
79 // Continue parsing as far as possible; the loop will return eventually
80 let input = this._input;
81 let currentLineLength = input.length;
82 while (true) {
83 // Count and skip whitespace lines
84 let whiteSpaceMatch, comment;
85 while (whiteSpaceMatch = this._newline.exec(input)) {
86 // Try to find a comment
87 if (this._comments && (comment = this._comment.exec(whiteSpaceMatch[0])))
88 emitToken('comment', comment[1], '', this._line, whiteSpaceMatch[0].length);
89 // Advance the input
90 input = input.substr(whiteSpaceMatch[0].length, input.length);
91 currentLineLength = input.length;
92 this._line++;
93 }
94 // Skip whitespace on current line
95 if (!whiteSpaceMatch && (whiteSpaceMatch = this._whitespace.exec(input)))
96 input = input.substr(whiteSpaceMatch[0].length, input.length);
97
98 // Stop for now if we're at the end
99 if (this._endOfFile.test(input)) {
100 // If the input is finished, emit EOF
101 if (inputFinished) {
102 // Try to find a final comment
103 if (this._comments && (comment = this._comment.exec(input)))
104 emitToken('comment', comment[1], '', this._line, input.length);
105 input = null;
106 emitToken('eof', '', '', this._line, 0);
107 }
108 return this._input = input;
109 }
110
111 // Look for specific token types based on the first character
112 const line = this._line, firstChar = input[0];
113 let type = '', value = '', prefix = '',
114 match = null, matchLength = 0, inconclusive = false;
115 switch (firstChar) {
116 case '^':
117 // We need at least 3 tokens lookahead to distinguish ^^<IRI> and ^^pre:fixed
118 if (input.length < 3)
119 break;
120 // Try to match a type
121 else if (input[1] === '^') {
122 this._previousMarker = '^^';
123 // Move to type IRI or prefixed name
124 input = input.substr(2);
125 if (input[0] !== '<') {
126 inconclusive = true;
127 break;
128 }
129 }
130 // If no type, it must be a path expression
131 else {
132 if (this._n3Mode) {
133 matchLength = 1;
134 type = '^';
135 }
136 break;
137 }
138 // Fall through in case the type is an IRI
139 case '<':
140 // Try to find a full IRI without escape sequences
141 if (match = this._unescapedIri.exec(input))
142 type = 'IRI', value = match[1];
143 // Try to find a full IRI with escape sequences
144 else if (match = this._iri.exec(input)) {
145 value = this._unescape(match[1]);
146 if (value === null || illegalIriChars.test(value))
147 return reportSyntaxError(this);
148 type = 'IRI';
149 }
150 // Try to find a nested triple
151 else if (input.length > 1 && input[1] === '<')
152 type = '<<', matchLength = 2;
153 // Try to find a backwards implication arrow
154 else if (this._n3Mode && input.length > 1 && input[1] === '=')
155 type = 'inverse', matchLength = 2, value = '>';
156 break;
157
158 case '>':
159 if (input.length > 1 && input[1] === '>')
160 type = '>>', matchLength = 2;
161 break;
162
163 case '_':
164 // Try to find a blank node. Since it can contain (but not end with) a dot,
165 // we always need a non-dot character before deciding it is a blank node.
166 // Therefore, try inserting a space if we're at the end of the input.
167 if ((match = this._blank.exec(input)) ||
168 inputFinished && (match = this._blank.exec(`${input} `)))
169 type = 'blank', prefix = '_', value = match[1];
170 break;
171
172 case '"':
173 // Try to find a literal without escape sequences
174 if (match = this._simpleQuotedString.exec(input))
175 value = match[1];
176 // Try to find a literal wrapped in three pairs of quotes
177 else {
178 ({ value, matchLength } = this._parseLiteral(input));
179 if (value === null)
180 return reportSyntaxError(this);
181 }
182 if (match !== null || matchLength !== 0) {
183 type = 'literal';
184 this._literalClosingPos = 0;
185 }
186 break;
187
188 case "'":
189 if (!this._lineMode) {
190 // Try to find a literal without escape sequences
191 if (match = this._simpleApostropheString.exec(input))
192 value = match[1];
193 // Try to find a literal wrapped in three pairs of quotes
194 else {
195 ({ value, matchLength } = this._parseLiteral(input));
196 if (value === null)
197 return reportSyntaxError(this);
198 }
199 if (match !== null || matchLength !== 0) {
200 type = 'literal';
201 this._literalClosingPos = 0;
202 }
203 }
204 break;
205
206 case '?':
207 // Try to find a variable
208 if (this._n3Mode && (match = this._variable.exec(input)))
209 type = 'var', value = match[0];
210 break;
211
212 case '@':
213 // Try to find a language code
214 if (this._previousMarker === 'literal' && (match = this._langcode.exec(input)))
215 type = 'langcode', value = match[1];
216 // Try to find a keyword
217 else if (match = this._keyword.exec(input))
218 type = match[0];
219 break;
220
221 case '.':
222 // Try to find a dot as punctuation
223 if (input.length === 1 ? inputFinished : (input[1] < '0' || input[1] > '9')) {
224 type = '.';
225 matchLength = 1;
226 break;
227 }
228 // Fall through to numerical case (could be a decimal dot)
229
230 case '0':
231 case '1':
232 case '2':
233 case '3':
234 case '4':
235 case '5':
236 case '6':
237 case '7':
238 case '8':
239 case '9':
240 case '+':
241 case '-':
242 // Try to find a number. Since it can contain (but not end with) a dot,
243 // we always need a non-dot character before deciding it is a number.
244 // Therefore, try inserting a space if we're at the end of the input.
245 if (match = this._number.exec(input) ||
246 inputFinished && (match = this._number.exec(`${input} `))) {
247 type = 'literal', value = match[0];
248 prefix = (typeof match[1] === 'string' ? xsd.double :
249 (typeof match[2] === 'string' ? xsd.decimal : xsd.integer));
250 }
251 break;
252
253 case 'B':
254 case 'b':
255 case 'p':
256 case 'P':
257 case 'G':
258 case 'g':
259 // Try to find a SPARQL-style keyword
260 if (match = this._sparqlKeyword.exec(input))
261 type = match[0].toUpperCase();
262 else
263 inconclusive = true;
264 break;
265
266 case 'f':
267 case 't':
268 // Try to match a boolean
269 if (match = this._boolean.exec(input))
270 type = 'literal', value = match[0], prefix = xsd.boolean;
271 else
272 inconclusive = true;
273 break;
274
275 case 'a':
276 // Try to find an abbreviated predicate
277 if (match = this._shortPredicates.exec(input))
278 type = 'abbreviation', value = 'a';
279 else
280 inconclusive = true;
281 break;
282
283 case '=':
284 // Try to find an implication arrow or equals sign
285 if (this._n3Mode && input.length > 1) {
286 type = 'abbreviation';
287 if (input[1] !== '>')
288 matchLength = 1, value = '=';
289 else
290 matchLength = 2, value = '>';
291 }
292 break;
293
294 case '!':
295 if (!this._n3Mode)
296 break;
297 case ',':
298 case ';':
299 case '[':
300 case ']':
301 case '(':
302 case ')':
303 case '{':
304 case '}':
305 if (!this._lineMode) {
306 matchLength = 1;
307 type = firstChar;
308 }
309 break;
310
311 default:
312 inconclusive = true;
313 }
314
315 // Some first characters do not allow an immediate decision, so inspect more
316 if (inconclusive) {
317 // Try to find a prefix
318 if ((this._previousMarker === '@prefix' || this._previousMarker === 'PREFIX') &&
319 (match = this._prefix.exec(input)))
320 type = 'prefix', value = match[1] || '';
321 // Try to find a prefixed name. Since it can contain (but not end with) a dot,
322 // we always need a non-dot character before deciding it is a prefixed name.
323 // Therefore, try inserting a space if we're at the end of the input.
324 else if ((match = this._prefixed.exec(input)) ||
325 inputFinished && (match = this._prefixed.exec(`${input} `)))
326 type = 'prefixed', prefix = match[1] || '', value = this._unescape(match[2]);
327 }
328
329 // A type token is special: it can only be emitted after an IRI or prefixed name is read
330 if (this._previousMarker === '^^') {
331 switch (type) {
332 case 'prefixed': type = 'type'; break;
333 case 'IRI': type = 'typeIRI'; break;
334 default: type = '';
335 }
336 }
337
338 // What if nothing of the above was found?
339 if (!type) {
340 // We could be in streaming mode, and then we just wait for more input to arrive.
341 // Otherwise, a syntax error has occurred in the input.
342 // One exception: error on an unaccounted linebreak (= not inside a triple-quoted literal).
343 if (inputFinished || (!/^'''|^"""/.test(input) && /\n|\r/.test(input)))
344 return reportSyntaxError(this);
345 else
346 return this._input = input;
347 }
348
349 // Emit the parsed token
350 const length = matchLength || match[0].length;
351 const token = emitToken(type, value, prefix, line, length);
352 this.previousToken = token;
353 this._previousMarker = type;
354
355 // Advance to next part to tokenize
356 input = input.substr(length, input.length);
357 }
358
359 // Emits the token through the callback
360 function emitToken(type, value, prefix, line, length) {
361 const start = input ? currentLineLength - input.length : currentLineLength;
362 const end = start + length;
363 const token = { type, value, prefix, line, start, end };
364 callback(null, token);
365 return token;
366 }
367 // Signals the syntax error through the callback
368 function reportSyntaxError(self) { callback(self._syntaxError(/^\S*/.exec(input)[0])); }
369 }
370
371 // ### `_unescape` replaces N3 escape codes by their corresponding characters
372 _unescape(item) {
373 let invalid = false;
374 const replaced = item.replace(escapeSequence, (sequence, unicode4, unicode8, escapedChar) => {
375 // 4-digit unicode character
376 if (typeof unicode4 === 'string')
377 return String.fromCharCode(Number.parseInt(unicode4, 16));
378 // 8-digit unicode character
379 if (typeof unicode8 === 'string') {
380 let charCode = Number.parseInt(unicode8, 16);
381 return charCode <= 0xFFFF ? String.fromCharCode(Number.parseInt(unicode8, 16)) :
382 String.fromCharCode(0xD800 + ((charCode -= 0x10000) >> 10), 0xDC00 + (charCode & 0x3FF));
383 }
384 // fixed escape sequence
385 if (escapedChar in escapeReplacements)
386 return escapeReplacements[escapedChar];
387 // invalid escape sequence
388 invalid = true;
389 return '';
390 });
391 return invalid ? null : replaced;
392 }
393
394 // ### `_parseLiteral` parses a literal into an unescaped value
395 _parseLiteral(input) {
396 // Ensure we have enough lookahead to identify triple-quoted strings
397 if (input.length >= 3) {
398 // Identify the opening quote(s)
399 const opening = input.match(/^(?:"""|"|'''|'|)/)[0];
400 const openingLength = opening.length;
401
402 // Find the next candidate closing quotes
403 let closingPos = Math.max(this._literalClosingPos, openingLength);
404 while ((closingPos = input.indexOf(opening, closingPos)) > 0) {
405 // Count backslashes right before the closing quotes
406 let backslashCount = 0;
407 while (input[closingPos - backslashCount - 1] === '\\')
408 backslashCount++;
409
410 // An even number of backslashes (in particular 0)
411 // means these are actual, non-escaped closing quotes
412 if (backslashCount % 2 === 0) {
413 // Extract and unescape the value
414 const raw = input.substring(openingLength, closingPos);
415 const lines = raw.split(/\r\n|\r|\n/).length - 1;
416 const matchLength = closingPos + openingLength;
417 // Only triple-quoted strings can be multi-line
418 if (openingLength === 1 && lines !== 0 ||
419 openingLength === 3 && this._lineMode)
420 break;
421 this._line += lines;
422 return { value: this._unescape(raw), matchLength };
423 }
424 closingPos++;
425 }
426 this._literalClosingPos = input.length - openingLength + 1;
427 }
428 return { value: '', matchLength: 0 };
429 }
430
431 // ### `_syntaxError` creates a syntax error for the given issue
432 _syntaxError(issue) {
433 this._input = null;
434 const err = new Error(`Unexpected "${issue}" on line ${this._line}.`);
435 err.context = {
436 token: undefined,
437 line: this._line,
438 previousToken: this.previousToken,
439 };
440 return err;
441 }
442
443 // ### Strips off any starting UTF BOM mark.
444 _readStartingBom(input) {
445 return input.startsWith('\ufeff') ? input.substr(1) : input;
446 }
447
448 // ## Public methods
449
450 // ### `tokenize` starts the transformation of an N3 document into an array of tokens.
451 // The input can be a string or a stream.
452 tokenize(input, callback) {
453 this._line = 1;
454
455 // If the input is a string, continuously emit tokens through the callback until the end
456 if (typeof input === 'string') {
457 this._input = this._readStartingBom(input);
458 // If a callback was passed, asynchronously call it
459 if (typeof callback === 'function')
460 queueMicrotask(() => this._tokenizeToEnd(callback, true));
461 // If no callback was passed, tokenize synchronously and return
462 else {
463 const tokens = [];
464 let error;
465 this._tokenizeToEnd((e, t) => e ? (error = e) : tokens.push(t), true);
466 if (error) throw error;
467 return tokens;
468 }
469 }
470 // Otherwise, the input must be a stream
471 else {
472 this._pendingBuffer = null;
473 if (typeof input.setEncoding === 'function')
474 input.setEncoding('utf8');
475 // Adds the data chunk to the buffer and parses as far as possible
476 input.on('data', data => {
477 if (this._input !== null && data.length !== 0) {
478 // Prepend any previous pending writes
479 if (this._pendingBuffer) {
480 data = Buffer.concat([this._pendingBuffer, data]);
481 this._pendingBuffer = null;
482 }
483 // Hold if the buffer ends in an incomplete unicode sequence
484 if (data[data.length - 1] & 0x80) {
485 this._pendingBuffer = data;
486 }
487 // Otherwise, tokenize as far as possible
488 else {
489 // Only read a BOM at the start
490 if (typeof this._input === 'undefined')
491 this._input = this._readStartingBom(typeof data === 'string' ? data : data.toString());
492 else
493 this._input += data;
494 this._tokenizeToEnd(callback, false);
495 }
496 }
497 });
498 // Parses until the end
499 input.on('end', () => {
500 if (typeof this._input === 'string')
501 this._tokenizeToEnd(callback, true);
502 });
503 input.on('error', callback);
504 }
505 }
506 }