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.
- package/README.md +47 -13
- package/SPEC.md +598 -343
- package/package.json +1 -1
- package/src/cli.js +37 -5
- package/src/formats.js +149 -0
- package/src/n3-builtins.js +590 -0
- package/src/n3-documents.js +66 -0
- package/src/n3-parser.js +463 -0
- package/src/n3-writer.js +199 -0
- package/src/n3.js +814 -0
- package/src/node.js +4 -0
- package/src/proof.js +1 -1
- package/src/rdf-lexer.js +2025 -0
- package/src/rdf-parser.js +827 -0
- package/src/rdf-prelude.js +808 -0
- package/src/rdf-rules.js +106 -0
- package/src/rdf-syntax.js +249 -0
- package/src/rdf.js +429 -0
- package/src/srl-analyze.js +703 -0
- package/src/srl-assignments.js +40 -0
- package/src/srl-builtin-names.js +78 -0
- package/src/srl-functions.js +584 -0
- package/src/srl-parser.js +816 -0
- package/src/srl-term.js +288 -0
- package/src/srl-tokenizer.js +341 -0
- package/src/srl.js +649 -0
- package/src/version.js +1 -1
package/src/rdf-lexer.js
ADDED
|
@@ -0,0 +1,2025 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Eyeling Reasoner — lexer
|
|
3
|
+
*
|
|
4
|
+
* Tokenizer for the supported N3/Turtle-like syntax. Produces a token stream
|
|
5
|
+
* consumed by lib/parser.js.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class Token {
|
|
10
|
+
constructor(typ, value = null, offset = null) {
|
|
11
|
+
this.typ = typ;
|
|
12
|
+
this.value = value;
|
|
13
|
+
// Codepoint offset in the original source (Array.from(text) index).
|
|
14
|
+
this.offset = offset;
|
|
15
|
+
}
|
|
16
|
+
toString() {
|
|
17
|
+
const loc = typeof this.offset === 'number' ? `@${this.offset}` : '';
|
|
18
|
+
if (this.value == null) return `Token(${this.typ}${loc})`;
|
|
19
|
+
return `Token(${this.typ}${loc}, ${JSON.stringify(this.value)})`;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
class N3SyntaxError extends SyntaxError {
|
|
24
|
+
constructor(message, offset = null) {
|
|
25
|
+
super(message);
|
|
26
|
+
this.name = 'N3SyntaxError';
|
|
27
|
+
this.offset = offset;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function isWs(c) {
|
|
32
|
+
if (c === null || c === undefined) return false;
|
|
33
|
+
const code = c.charCodeAt(0);
|
|
34
|
+
// Fast path for the whitespace used by N3/Turtle inputs.
|
|
35
|
+
return code === 0x20 || code === 0x09 || code === 0x0a || code === 0x0d || code === 0x0c;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function isAsciiAlphaCode(code) {
|
|
39
|
+
return (code >= 65 && code <= 90) || (code >= 97 && code <= 122);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function isAsciiDigitCode(code) {
|
|
43
|
+
return code >= 48 && code <= 57;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function isAsciiAlpha(c) {
|
|
47
|
+
return c !== null && c !== undefined && isAsciiAlphaCode(c.charCodeAt(0));
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function isAsciiDigit(c) {
|
|
51
|
+
return c !== null && c !== undefined && isAsciiDigitCode(c.charCodeAt(0));
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// Turtle/N3 prefixed names (PNAME_*) allow many Unicode letters and certain
|
|
55
|
+
// punctuation, plus %-escapes and backslash escapes in PN_LOCAL.
|
|
56
|
+
//
|
|
57
|
+
// The original lexer only accepted ASCII in identifiers, which incorrectly
|
|
58
|
+
// rejected valid N3 such as:
|
|
59
|
+
// res:COUNTRY_United%20States rdfs:label "United States".
|
|
60
|
+
// res:CITY_Chañaral rdfs:label "Chañaral".
|
|
61
|
+
//
|
|
62
|
+
// We implement a grammar-aligned matcher for PN_CHARS* and PLX fragments.
|
|
63
|
+
function isHexDigit(c) {
|
|
64
|
+
if (c === null || c === undefined) return false;
|
|
65
|
+
const code = c.charCodeAt(0);
|
|
66
|
+
return (code >= 48 && code <= 57) || (code >= 65 && code <= 70) || (code >= 97 && code <= 102);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function isPnCharsBase(c) {
|
|
70
|
+
// eyemind: PN_CHARS_BASE exactly as the Turtle and N3 grammars give it.
|
|
71
|
+
if (c === null || c === undefined) return false;
|
|
72
|
+
const cp = c.codePointAt(0);
|
|
73
|
+
return isAsciiAlphaCode(cp) || (cp >= 0xc0 && cp <= 0xd6) || (cp >= 0xd8 && cp <= 0xf6) || (cp >= 0xf8 && cp <= 0x2ff) ||
|
|
74
|
+
(cp >= 0x370 && cp <= 0x37d) || (cp >= 0x37f && cp <= 0x1fff) || (cp >= 0x200c && cp <= 0x200d) ||
|
|
75
|
+
(cp >= 0x2070 && cp <= 0x218f) || (cp >= 0x2c00 && cp <= 0x2fef) || (cp >= 0x3001 && cp <= 0xd7ff) ||
|
|
76
|
+
(cp >= 0xf900 && cp <= 0xfdcf) || (cp >= 0xfdf0 && cp <= 0xfffd) || (cp >= 0x10000 && cp <= 0xeffff);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function isPnCharsU(c) {
|
|
80
|
+
// PN_CHARS_U ::= PN_CHARS_BASE | '_'
|
|
81
|
+
return c === '_' || isPnCharsBase(c);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function isPnChars(c) {
|
|
85
|
+
// PN_CHARS ::= PN_CHARS_U | '-' | [0-9] | U+00B7 | [U+0300-U+036F] | [U+203F-U+2040]
|
|
86
|
+
if (c === null || c === undefined) return false;
|
|
87
|
+
const code = c.charCodeAt(0);
|
|
88
|
+
if (isAsciiAlphaCode(code) || isAsciiDigitCode(code) || code === 95 || code === 45) return true;
|
|
89
|
+
if (isPnCharsU(c)) return true;
|
|
90
|
+
if (c === '\u00B7') return true;
|
|
91
|
+
const cp = c.codePointAt(0);
|
|
92
|
+
return (cp >= 0x0300 && cp <= 0x036f) || (cp >= 0x203f && cp <= 0x2040);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// PN_LOCAL_ESC from the N3/Turtle grammar.
|
|
96
|
+
const PN_LOCAL_ESC_SET = new Set([
|
|
97
|
+
'_',
|
|
98
|
+
'~',
|
|
99
|
+
'.',
|
|
100
|
+
'-',
|
|
101
|
+
'!',
|
|
102
|
+
'$',
|
|
103
|
+
'&',
|
|
104
|
+
"'",
|
|
105
|
+
'(',
|
|
106
|
+
')',
|
|
107
|
+
'*',
|
|
108
|
+
'+',
|
|
109
|
+
',',
|
|
110
|
+
';',
|
|
111
|
+
'=',
|
|
112
|
+
'/',
|
|
113
|
+
'?',
|
|
114
|
+
'#',
|
|
115
|
+
'@',
|
|
116
|
+
'%',
|
|
117
|
+
]);
|
|
118
|
+
|
|
119
|
+
function isIdentChar(c) {
|
|
120
|
+
// Allowed raw chars in PNAME tokens beyond PN_CHARS*: ':' is allowed in PN_LOCAL.
|
|
121
|
+
return c === ':' || isPnChars(c);
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function isForbiddenNoncharacterCodePoint(cp) {
|
|
125
|
+
return (cp & 0xffff) === 0xfffe || (cp & 0xffff) === 0xffff;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function validateEscapedCodePoint(cp, offset = null, escapeKind = 'escape') {
|
|
129
|
+
// eyemind: RDF strings may hold U+0000.
|
|
130
|
+
if (cp >= 0xd800 && cp <= 0xdfff) {
|
|
131
|
+
throw new N3SyntaxError(`Invalid string literal: ${escapeKind} surrogate code points are not allowed`, offset);
|
|
132
|
+
}
|
|
133
|
+
if (isForbiddenNoncharacterCodePoint(cp)) {
|
|
134
|
+
throw new N3SyntaxError(
|
|
135
|
+
`Invalid string literal: ${escapeKind} noncharacter U+${cp
|
|
136
|
+
.toString(16)
|
|
137
|
+
.toUpperCase()
|
|
138
|
+
.padStart(cp <= 0xffff ? 4 : 6, '0')} is not allowed`,
|
|
139
|
+
offset,
|
|
140
|
+
);
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
function decodeN3StringEscapes(s, offset = null) {
|
|
145
|
+
let out = '';
|
|
146
|
+
for (let i = 0; i < s.length; i++) {
|
|
147
|
+
const c = s[i];
|
|
148
|
+
if (c !== '\\') {
|
|
149
|
+
out += c;
|
|
150
|
+
continue;
|
|
151
|
+
}
|
|
152
|
+
if (i + 1 >= s.length) {
|
|
153
|
+
out += '\\';
|
|
154
|
+
continue;
|
|
155
|
+
}
|
|
156
|
+
const e = s[++i];
|
|
157
|
+
switch (e) {
|
|
158
|
+
case 't':
|
|
159
|
+
out += '\t';
|
|
160
|
+
break;
|
|
161
|
+
case 'n':
|
|
162
|
+
out += '\n';
|
|
163
|
+
break;
|
|
164
|
+
case 'r':
|
|
165
|
+
out += '\r';
|
|
166
|
+
break;
|
|
167
|
+
case 'b':
|
|
168
|
+
out += '\b';
|
|
169
|
+
break;
|
|
170
|
+
case 'f':
|
|
171
|
+
out += '\f';
|
|
172
|
+
break;
|
|
173
|
+
case '"':
|
|
174
|
+
out += '"';
|
|
175
|
+
break;
|
|
176
|
+
case "'":
|
|
177
|
+
out += "'";
|
|
178
|
+
break;
|
|
179
|
+
case '\\':
|
|
180
|
+
out += '\\';
|
|
181
|
+
break;
|
|
182
|
+
|
|
183
|
+
case 'u': {
|
|
184
|
+
const hex = s.slice(i + 1, i + 5);
|
|
185
|
+
if (/^[0-9A-Fa-f]{4}$/.test(hex)) {
|
|
186
|
+
const cp = parseInt(hex, 16);
|
|
187
|
+
validateEscapedCodePoint(cp, offset, '\\u');
|
|
188
|
+
out += String.fromCharCode(cp);
|
|
189
|
+
i += 4;
|
|
190
|
+
} else {
|
|
191
|
+
out += '\\u';
|
|
192
|
+
}
|
|
193
|
+
break;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
case 'U': {
|
|
197
|
+
const hex = s.slice(i + 1, i + 9);
|
|
198
|
+
if (/^[0-9A-Fa-f]{8}$/.test(hex)) {
|
|
199
|
+
const cp = parseInt(hex, 16);
|
|
200
|
+
if (cp >= 0 && cp <= 0x10ffff) {
|
|
201
|
+
validateEscapedCodePoint(cp, offset, '\\U');
|
|
202
|
+
out += String.fromCodePoint(cp);
|
|
203
|
+
} else out += '\\U' + hex;
|
|
204
|
+
i += 8;
|
|
205
|
+
} else {
|
|
206
|
+
out += '\\U';
|
|
207
|
+
}
|
|
208
|
+
break;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
default:
|
|
212
|
+
// preserve unknown escapes
|
|
213
|
+
out += '\\' + e;
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
return out;
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
function formatCodePoint(cp) {
|
|
220
|
+
return cp
|
|
221
|
+
.toString(16)
|
|
222
|
+
.toUpperCase()
|
|
223
|
+
.padStart(cp <= 0xffff ? 4 : 6, '0');
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
function isForbiddenIriRefChar(c) {
|
|
227
|
+
return (
|
|
228
|
+
c === '<' || c === '>' || c === '"' || c === '{' || c === '}' || c === '|' || c === '^' || c === '`' || c === '\\'
|
|
229
|
+
);
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
function assertValidIriRefCodePoint(cp, offset = null) {
|
|
233
|
+
if (cp <= 0x20) {
|
|
234
|
+
throw new N3SyntaxError(`Invalid IRIREF: character U+${formatCodePoint(cp)} is not allowed inside <...>`, offset);
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
if (cp >= 0xd800 && cp <= 0xdfff) {
|
|
238
|
+
throw new N3SyntaxError(
|
|
239
|
+
`Invalid IRIREF: surrogate code point U+${formatCodePoint(cp)} is not allowed inside <...>`,
|
|
240
|
+
offset,
|
|
241
|
+
);
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
if (isForbiddenNoncharacterCodePoint(cp)) {
|
|
245
|
+
throw new N3SyntaxError(
|
|
246
|
+
`Invalid IRIREF: noncharacter U+${formatCodePoint(cp)} is not allowed inside <...>`,
|
|
247
|
+
offset,
|
|
248
|
+
);
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
const c = String.fromCodePoint(cp);
|
|
252
|
+
if (isForbiddenIriRefChar(c)) {
|
|
253
|
+
throw new N3SyntaxError(`Invalid IRIREF: character ${JSON.stringify(c)} is not allowed inside <...>`, offset);
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
function decodeIriRefEscapes(s, offset = null) {
|
|
258
|
+
let out = '';
|
|
259
|
+
for (let i = 0; i < s.length; i++) {
|
|
260
|
+
const c = s[i];
|
|
261
|
+
if (c !== '\\') {
|
|
262
|
+
const cp = c.codePointAt(0);
|
|
263
|
+
assertValidIriRefCodePoint(cp, offset);
|
|
264
|
+
out += c;
|
|
265
|
+
continue;
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
if (i + 1 >= s.length) {
|
|
269
|
+
throw new N3SyntaxError('Invalid IRIREF: bare backslash is not allowed inside <...>', offset);
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
const e = s[++i];
|
|
273
|
+
if (e === 'u') {
|
|
274
|
+
const hex = s.slice(i + 1, i + 5);
|
|
275
|
+
if (!/^[0-9A-Fa-f]{4}$/.test(hex)) {
|
|
276
|
+
throw new N3SyntaxError('Invalid IRIREF: malformed \\u escape inside <...>', offset);
|
|
277
|
+
}
|
|
278
|
+
const cp = parseInt(hex, 16);
|
|
279
|
+
assertValidIriRefCodePoint(cp, offset);
|
|
280
|
+
out += String.fromCodePoint(cp);
|
|
281
|
+
i += 4;
|
|
282
|
+
continue;
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
if (e === 'U') {
|
|
286
|
+
const hex = s.slice(i + 1, i + 9);
|
|
287
|
+
if (!/^[0-9A-Fa-f]{8}$/.test(hex)) {
|
|
288
|
+
throw new N3SyntaxError('Invalid IRIREF: malformed \\U escape inside <...>', offset);
|
|
289
|
+
}
|
|
290
|
+
const cp = parseInt(hex, 16);
|
|
291
|
+
if (cp < 0 || cp > 0x10ffff) {
|
|
292
|
+
throw new N3SyntaxError(`Invalid IRIREF: code point U+${hex.toUpperCase()} is out of range`, offset);
|
|
293
|
+
}
|
|
294
|
+
assertValidIriRefCodePoint(cp, offset);
|
|
295
|
+
out += String.fromCodePoint(cp);
|
|
296
|
+
i += 8;
|
|
297
|
+
continue;
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
throw new N3SyntaxError(
|
|
301
|
+
`Invalid IRIREF: character ${JSON.stringify('\\' + e)} is not allowed inside <...>`,
|
|
302
|
+
offset,
|
|
303
|
+
);
|
|
304
|
+
}
|
|
305
|
+
return out;
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
function assertValidStringLiteralValue(s, offset = null) {
|
|
309
|
+
for (let i = 0; i < s.length; i++) {
|
|
310
|
+
const cu = s.charCodeAt(i);
|
|
311
|
+
|
|
312
|
+
// Reject lone UTF-16 surrogates. Valid astral characters appear as a
|
|
313
|
+
// well-formed high+low surrogate pair and are accepted.
|
|
314
|
+
if (cu >= 0xd800 && cu <= 0xdbff) {
|
|
315
|
+
const next = i + 1 < s.length ? s.charCodeAt(i + 1) : -1;
|
|
316
|
+
if (!(next >= 0xdc00 && next <= 0xdfff)) {
|
|
317
|
+
throw new N3SyntaxError('Invalid string literal: unpaired high surrogate is not allowed', offset);
|
|
318
|
+
}
|
|
319
|
+
const cp = ((cu - 0xd800) << 10) + (next - 0xdc00) + 0x10000;
|
|
320
|
+
if (isForbiddenNoncharacterCodePoint(cp)) {
|
|
321
|
+
throw new N3SyntaxError(
|
|
322
|
+
`Invalid string literal: noncharacter U+${cp.toString(16).toUpperCase().padStart(6, '0')} is not allowed`,
|
|
323
|
+
offset,
|
|
324
|
+
);
|
|
325
|
+
}
|
|
326
|
+
i += 1;
|
|
327
|
+
continue;
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
if (cu >= 0xdc00 && cu <= 0xdfff) {
|
|
331
|
+
throw new N3SyntaxError('Invalid string literal: unpaired low surrogate is not allowed', offset);
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
if (isForbiddenNoncharacterCodePoint(cu)) {
|
|
335
|
+
throw new N3SyntaxError(
|
|
336
|
+
`Invalid string literal: noncharacter U+${cu.toString(16).toUpperCase().padStart(4, '0')} is not allowed`,
|
|
337
|
+
offset,
|
|
338
|
+
);
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
// In the monolithic build, stripQuotes() is defined later in the file and
|
|
344
|
+
// function-hoisting makes it available to lex(). In the modular build the
|
|
345
|
+
// lexer must provide it locally.
|
|
346
|
+
function stripQuotes(lex) {
|
|
347
|
+
if (typeof lex !== 'string') return lex;
|
|
348
|
+
// Handle both short ('...' / "...") and long ('''...''' / """...""") forms.
|
|
349
|
+
if (lex.length >= 6) {
|
|
350
|
+
if (lex.startsWith('"""') && lex.endsWith('"""')) return lex.slice(3, -3);
|
|
351
|
+
if (lex.startsWith("'''") && lex.endsWith("'''")) return lex.slice(3, -3);
|
|
352
|
+
}
|
|
353
|
+
if (lex.length >= 2) {
|
|
354
|
+
const a = lex[0];
|
|
355
|
+
const b = lex[lex.length - 1];
|
|
356
|
+
if ((a === '"' && b === '"') || (a === "'" && b === "'")) return lex.slice(1, -1);
|
|
357
|
+
}
|
|
358
|
+
return lex;
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
|
|
362
|
+
// RDF/TriG compatibility is an opt-in syntax-normalization layer, not a new
|
|
363
|
+
// reasoning model. Eyeling remains strict N3 by default and N3 internally:
|
|
364
|
+
// - RDF 1.2 triple terms <<( s p o )>> become singleton graph terms { s p o }.
|
|
365
|
+
// - TriG named graph blocks g { ... } become g log:nameOf { ... } .
|
|
366
|
+
// - A top-level default graph block { ... } is unwrapped into ordinary triples.
|
|
367
|
+
// This keeps all downstream parsing/reasoning N3-only.
|
|
368
|
+
const LOG_NAME_OF_IRI = '<http://www.w3.org/2000/10/swap/log#nameOf>';
|
|
369
|
+
const RDF_REIFIES_IRI = '<http://www.w3.org/1999/02/22-rdf-syntax-ns#reifies>';
|
|
370
|
+
const RDF_TYPE_IRI = '<http://www.w3.org/1999/02/22-rdf-syntax-ns#type>';
|
|
371
|
+
const XSD_INTEGER_IRI = '<http://www.w3.org/2001/XMLSchema#integer>';
|
|
372
|
+
const EYMSG_NS = 'https://eyereasoner.github.io/eyeling/vocab/message#';
|
|
373
|
+
const EYMSG = Object.freeze({
|
|
374
|
+
RDFMessageStream: `<${EYMSG_NS}RDFMessageStream>`,
|
|
375
|
+
MessageEnvelope: `<${EYMSG_NS}MessageEnvelope>`,
|
|
376
|
+
envelope: `<${EYMSG_NS}envelope>`,
|
|
377
|
+
firstEnvelope: `<${EYMSG_NS}firstEnvelope>`,
|
|
378
|
+
lastEnvelope: `<${EYMSG_NS}lastEnvelope>`,
|
|
379
|
+
orderedEnvelopes: `<${EYMSG_NS}orderedEnvelopes>`,
|
|
380
|
+
messageCount: `<${EYMSG_NS}messageCount>`,
|
|
381
|
+
offset: `<${EYMSG_NS}offset>`,
|
|
382
|
+
nextEnvelope: `<${EYMSG_NS}nextEnvelope>`,
|
|
383
|
+
payloadGraph: `<${EYMSG_NS}payloadGraph>`,
|
|
384
|
+
payloadKind: `<${EYMSG_NS}payloadKind>`,
|
|
385
|
+
empty: `<${EYMSG_NS}empty>`,
|
|
386
|
+
nonEmpty: `<${EYMSG_NS}nonEmpty>`,
|
|
387
|
+
});
|
|
388
|
+
|
|
389
|
+
function normalizeRdfCompatibility(inputText, { trig = false } = {}) {
|
|
390
|
+
let text = String(inputText ?? '');
|
|
391
|
+
|
|
392
|
+
// Fast path: most Eyeling inputs are ordinary N3 and do not need RDF/TriG
|
|
393
|
+
// surface-syntax normalization. Avoid scanning large files character-by-character
|
|
394
|
+
// unless they actually contain RDF 1.2 triple terms, VERSION directives, or a
|
|
395
|
+
// plausible top-level TriG named graph block.
|
|
396
|
+
const hasTripleTerms = text.includes('<<');
|
|
397
|
+
const hasVersionDirective = /^\s*(?:@version|VERSION)\s+(["'])(?:1\.1|1\.2|1\.2-basic)\1\s*\.?\s*(?:#.*)?$/im.test(text);
|
|
398
|
+
const hasMessageVersionDirective = /^\s*(?:@version|VERSION)\s+(["'])(?:1\.1|1\.2|1\.2-basic)-messages\1\s*\.?\s*(?:#.*)?$/im.test(text);
|
|
399
|
+
const hasNamedGraphCandidate = /(?:^|[.\r\n])\s*(?:GRAPH\s+)?(?:<[^>\r\n]*>|_:[A-Za-z][A-Za-z0-9_-]*|[A-Za-z][A-Za-z0-9_-]*:[^\s{};,.()[\]]*|:[^\s{};,.()[\]]+)\s*\{/m.test(text);
|
|
400
|
+
const hasAnnotationSyntax = /(?:^|\s)~|\{\|/.test(text);
|
|
401
|
+
|
|
402
|
+
if (!trig && !hasTripleTerms && !hasVersionDirective && !hasMessageVersionDirective && !hasNamedGraphCandidate && !hasAnnotationSyntax) return text;
|
|
403
|
+
|
|
404
|
+
function isWordChar(ch) {
|
|
405
|
+
return ch != null && /[A-Za-z0-9_:-]/.test(ch);
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
function startsWordAt(s, word, at) {
|
|
409
|
+
return s.startsWith(word, at) && !isWordChar(s[at - 1]) && !isWordChar(s[at + word.length]);
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
function readStringAt(s, at) {
|
|
413
|
+
const quote = s[at];
|
|
414
|
+
let i = at;
|
|
415
|
+
let out = quote;
|
|
416
|
+
const long = s.startsWith(quote.repeat(3), i);
|
|
417
|
+
if (long) {
|
|
418
|
+
out = quote.repeat(3);
|
|
419
|
+
i += 3;
|
|
420
|
+
while (i < s.length) {
|
|
421
|
+
if (s.startsWith(quote.repeat(3), i)) {
|
|
422
|
+
out += quote.repeat(3);
|
|
423
|
+
i += 3;
|
|
424
|
+
return { text: out, end: i };
|
|
425
|
+
}
|
|
426
|
+
if (s[i] === '\\' && i + 1 < s.length) {
|
|
427
|
+
out += s.slice(i, i + 2);
|
|
428
|
+
i += 2;
|
|
429
|
+
} else {
|
|
430
|
+
out += s[i++];
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
return { text: out, end: i };
|
|
434
|
+
}
|
|
435
|
+
i += 1;
|
|
436
|
+
let escaped = false;
|
|
437
|
+
while (i < s.length) {
|
|
438
|
+
const ch = s[i++];
|
|
439
|
+
out += ch;
|
|
440
|
+
if (escaped) {
|
|
441
|
+
escaped = false;
|
|
442
|
+
} else if (ch === '\\') {
|
|
443
|
+
escaped = true;
|
|
444
|
+
} else if (ch === quote) {
|
|
445
|
+
break;
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
return { text: out, end: i };
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
function readIriAt(s, at) {
|
|
452
|
+
let i = at + 1;
|
|
453
|
+
let out = '<';
|
|
454
|
+
while (i < s.length) {
|
|
455
|
+
const ch = s[i++];
|
|
456
|
+
out += ch;
|
|
457
|
+
if (ch === '>') break;
|
|
458
|
+
}
|
|
459
|
+
return { text: out, end: i };
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
function convertTripleTerms(s) {
|
|
463
|
+
let i = 0;
|
|
464
|
+
const reifierTriples = [];
|
|
465
|
+
|
|
466
|
+
function startsAt(needle, at = i) {
|
|
467
|
+
return s.startsWith(needle, at);
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
function splitTopLevelReifier(body) {
|
|
471
|
+
let depthBrace = 0;
|
|
472
|
+
let depthBracket = 0;
|
|
473
|
+
let depthParen = 0;
|
|
474
|
+
for (let j = 0; j < body.length; j++) {
|
|
475
|
+
const ch = body[j];
|
|
476
|
+
if (ch === '"' || ch === "'") {
|
|
477
|
+
const str = readStringAt(body, j);
|
|
478
|
+
j = str.end - 1;
|
|
479
|
+
continue;
|
|
480
|
+
}
|
|
481
|
+
if (ch === '<') {
|
|
482
|
+
const iri = readIriAt(body, j);
|
|
483
|
+
j = iri.end - 1;
|
|
484
|
+
continue;
|
|
485
|
+
}
|
|
486
|
+
if (ch === '#') {
|
|
487
|
+
while (j < body.length && body[j] !== '\n' && body[j] !== '\r') j += 1;
|
|
488
|
+
continue;
|
|
489
|
+
}
|
|
490
|
+
if (ch === '{') depthBrace += 1;
|
|
491
|
+
else if (ch === '}' && depthBrace > 0) depthBrace -= 1;
|
|
492
|
+
else if (ch === '[') depthBracket += 1;
|
|
493
|
+
else if (ch === ']' && depthBracket > 0) depthBracket -= 1;
|
|
494
|
+
else if (ch === '(') depthParen += 1;
|
|
495
|
+
else if (ch === ')' && depthParen > 0) depthParen -= 1;
|
|
496
|
+
else if (ch === '~' && depthBrace === 0 && depthBracket === 0 && depthParen === 0) {
|
|
497
|
+
return { triple: body.slice(0, j).trim(), reifier: body.slice(j + 1).trim() };
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
return { triple: body.trim(), reifier: '' };
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
function firstTerm(text) {
|
|
504
|
+
const at = skipWsAndComments(text, 0);
|
|
505
|
+
if (at >= text.length) return '';
|
|
506
|
+
if (text[at] === '<') return readIriAt(text, at).text;
|
|
507
|
+
let j = at;
|
|
508
|
+
while (j < text.length && !/\s/.test(text[j]) && !'{}[](),;.'.includes(text[j])) j += 1;
|
|
509
|
+
return text.slice(at, j);
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
function readBalancedTermAt(text, at) {
|
|
513
|
+
const open = text[at];
|
|
514
|
+
const matching = { '{': '}', '[': ']', '(': ')' };
|
|
515
|
+
if (!matching[open]) return null;
|
|
516
|
+
|
|
517
|
+
const stack = [matching[open]];
|
|
518
|
+
let j = at + 1;
|
|
519
|
+
while (j < text.length) {
|
|
520
|
+
const ch = text[j];
|
|
521
|
+
if (ch === '"' || ch === "'") {
|
|
522
|
+
const str = readStringAt(text, j);
|
|
523
|
+
j = str.end;
|
|
524
|
+
continue;
|
|
525
|
+
}
|
|
526
|
+
if (ch === '<' && !text.startsWith('<<', j)) {
|
|
527
|
+
const iri = readIriAt(text, j);
|
|
528
|
+
j = iri.end;
|
|
529
|
+
continue;
|
|
530
|
+
}
|
|
531
|
+
if (ch === '#') {
|
|
532
|
+
while (j < text.length && text[j] !== '\n' && text[j] !== '\r') j += 1;
|
|
533
|
+
continue;
|
|
534
|
+
}
|
|
535
|
+
if (matching[ch]) {
|
|
536
|
+
stack.push(matching[ch]);
|
|
537
|
+
j += 1;
|
|
538
|
+
continue;
|
|
539
|
+
}
|
|
540
|
+
if (ch === stack[stack.length - 1]) {
|
|
541
|
+
stack.pop();
|
|
542
|
+
j += 1;
|
|
543
|
+
if (stack.length === 0) return { text: text.slice(at, j), end: j };
|
|
544
|
+
continue;
|
|
545
|
+
}
|
|
546
|
+
j += 1;
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
throw new N3SyntaxError(`Unterminated term inside RDF 1.2 triple term, expected ${stack[stack.length - 1]}`);
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
function readRdfTripleTermComponent(text, at) {
|
|
553
|
+
const j = skipWsAndComments(text, at);
|
|
554
|
+
if (j >= text.length) return null;
|
|
555
|
+
const ch = text[j];
|
|
556
|
+
|
|
557
|
+
if (ch === '<') return readIriAt(text, j);
|
|
558
|
+
|
|
559
|
+
if (ch === '"' || ch === "'") {
|
|
560
|
+
const str = readStringAt(text, j);
|
|
561
|
+
let end = str.end;
|
|
562
|
+
let termText = str.text;
|
|
563
|
+
if (text.startsWith('^^', end)) {
|
|
564
|
+
const datatype = readRdfTripleTermComponent(text, end + 2);
|
|
565
|
+
if (datatype) {
|
|
566
|
+
termText += '^^' + datatype.text;
|
|
567
|
+
end = datatype.end;
|
|
568
|
+
}
|
|
569
|
+
} else if (text[end] === '@') {
|
|
570
|
+
let k = end + 1;
|
|
571
|
+
if (/[A-Za-z]/.test(text[k] || '')) {
|
|
572
|
+
while (k < text.length && /[A-Za-z0-9-]/.test(text[k])) k += 1;
|
|
573
|
+
termText += text.slice(end, k);
|
|
574
|
+
end = k;
|
|
575
|
+
}
|
|
576
|
+
}
|
|
577
|
+
return { text: termText, end };
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
if (ch === '{' || ch === '[' || ch === '(') return readBalancedTermAt(text, j);
|
|
581
|
+
|
|
582
|
+
let k = j;
|
|
583
|
+
while (k < text.length && !/\s/.test(text[k]) && !'{}[](),;'.includes(text[k])) k += 1;
|
|
584
|
+
if (k === j) return null;
|
|
585
|
+
const value = text.slice(j, k);
|
|
586
|
+
if (!value || value.startsWith('@')) return null;
|
|
587
|
+
return { text: value, end: k };
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
function validateSingleRdfTripleTerm(rawTriple) {
|
|
591
|
+
const triple = rawTriple.trim();
|
|
592
|
+
if (!triple) throw new N3SyntaxError('RDF 1.2 triple term must contain exactly one subject, predicate, and object');
|
|
593
|
+
|
|
594
|
+
let pos = 0;
|
|
595
|
+
for (const label of ['subject', 'predicate', 'object']) {
|
|
596
|
+
const term = readRdfTripleTermComponent(triple, pos);
|
|
597
|
+
if (!term) throw new N3SyntaxError(`RDF 1.2 triple term is missing a ${label}`);
|
|
598
|
+
pos = term.end;
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
const rest = skipWsAndComments(triple, pos);
|
|
602
|
+
if (rest >= triple.length) return;
|
|
603
|
+
|
|
604
|
+
const found = triple[rest];
|
|
605
|
+
if (found === ',') {
|
|
606
|
+
throw new N3SyntaxError("RDF 1.2 triple terms must contain exactly one object; object lists using ',' are not valid inside <<( ... )>>");
|
|
607
|
+
}
|
|
608
|
+
if (found === ';') {
|
|
609
|
+
throw new N3SyntaxError("RDF 1.2 triple terms must contain exactly one predicate-object pair; ';' is not valid inside <<( ... )>>");
|
|
610
|
+
}
|
|
611
|
+
throw new N3SyntaxError(`RDF 1.2 triple term must contain exactly one subject, predicate, and object; unexpected ${JSON.stringify(triple.slice(rest, rest + 20))}`);
|
|
612
|
+
}
|
|
613
|
+
|
|
614
|
+
// eyemind: a reified triple << s p o >> stands for its reifier, given
|
|
615
|
+
// with ~ or a fresh blank node, which rdf:reifies the triple term.
|
|
616
|
+
let generatedReifier = 0;
|
|
617
|
+
function graphTermFromTripleBody(rawBody, parenthesized, reified = false) {
|
|
618
|
+
let body = rawBody.trim();
|
|
619
|
+
if (parenthesized && body.startsWith('(') && body.endsWith(')')) body = body.slice(1, -1).trim();
|
|
620
|
+
const split = splitTopLevelReifier(body);
|
|
621
|
+
const triple = split.triple;
|
|
622
|
+
validateSingleRdfTripleTerm(triple);
|
|
623
|
+
const graph = '{ ' + triple + ' }';
|
|
624
|
+
let reifier = split.reifier ? firstTerm(split.reifier) : null;
|
|
625
|
+
if (reified && !reifier) reifier = `_:rdfReifier${++generatedReifier}`;
|
|
626
|
+
if (reifier) reifierTriples.push(`${reifier} ${RDF_REIFIES_IRI} ${graph} .`);
|
|
627
|
+
return reified ? reifier : graph;
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
function convertUntil(stopToken) {
|
|
631
|
+
let out = '';
|
|
632
|
+
while (i < s.length) {
|
|
633
|
+
if (stopToken && startsAt(stopToken)) {
|
|
634
|
+
i += stopToken.length;
|
|
635
|
+
return out;
|
|
636
|
+
}
|
|
637
|
+
if (startsAt('<<(')) {
|
|
638
|
+
i += 3;
|
|
639
|
+
out += graphTermFromTripleBody(convertUntil(')>>'), false);
|
|
640
|
+
continue;
|
|
641
|
+
}
|
|
642
|
+
if (startsAt('<<')) {
|
|
643
|
+
// eyemind: a reified triple is read by the parser, in its graph.
|
|
644
|
+
out += '<<';
|
|
645
|
+
i += 2;
|
|
646
|
+
continue;
|
|
647
|
+
}
|
|
648
|
+
const ch = s[i];
|
|
649
|
+
if (ch === '"' || ch === "'") {
|
|
650
|
+
const str = readStringAt(s, i);
|
|
651
|
+
out += str.text;
|
|
652
|
+
i = str.end;
|
|
653
|
+
continue;
|
|
654
|
+
}
|
|
655
|
+
if (ch === '<') {
|
|
656
|
+
const iri = readIriAt(s, i);
|
|
657
|
+
out += iri.text;
|
|
658
|
+
i = iri.end;
|
|
659
|
+
continue;
|
|
660
|
+
}
|
|
661
|
+
if (ch === '#') {
|
|
662
|
+
while (i < s.length) {
|
|
663
|
+
const c = s[i++];
|
|
664
|
+
out += c;
|
|
665
|
+
if (c === '\n' || c === '\r') break;
|
|
666
|
+
}
|
|
667
|
+
continue;
|
|
668
|
+
}
|
|
669
|
+
out += ch;
|
|
670
|
+
i += 1;
|
|
671
|
+
}
|
|
672
|
+
if (stopToken) throw new N3SyntaxError(`Unterminated RDF 1.2 triple term, expected ${stopToken}`);
|
|
673
|
+
return out;
|
|
674
|
+
}
|
|
675
|
+
|
|
676
|
+
const converted = convertUntil(null);
|
|
677
|
+
if (reifierTriples.length === 0) return converted;
|
|
678
|
+
return converted + (converted.endsWith('\n') ? '' : '\n') + reifierTriples.join('\n') + '\n';
|
|
679
|
+
}
|
|
680
|
+
|
|
681
|
+
|
|
682
|
+
function convertAnnotations(s) {
|
|
683
|
+
let out = '';
|
|
684
|
+
let i = 0;
|
|
685
|
+
let statementStart = true;
|
|
686
|
+
let generatedBlank = 0;
|
|
687
|
+
|
|
688
|
+
function readBalancedDelimited(s, at, open, close) {
|
|
689
|
+
if (!s.startsWith(open, at)) return null;
|
|
690
|
+
let j = at + open.length;
|
|
691
|
+
let depth = 1;
|
|
692
|
+
while (j < s.length) {
|
|
693
|
+
const ch = s[j];
|
|
694
|
+
if (ch === '"' || ch === "'") {
|
|
695
|
+
j = readStringAt(s, j).end;
|
|
696
|
+
continue;
|
|
697
|
+
}
|
|
698
|
+
if (ch === '<' && !s.startsWith('<<', j)) {
|
|
699
|
+
j = readIriAt(s, j).end;
|
|
700
|
+
continue;
|
|
701
|
+
}
|
|
702
|
+
if (ch === '#') {
|
|
703
|
+
while (j < s.length && s[j] !== '\n' && s[j] !== '\r') j += 1;
|
|
704
|
+
continue;
|
|
705
|
+
}
|
|
706
|
+
if (s.startsWith(open, j)) {
|
|
707
|
+
depth += 1;
|
|
708
|
+
j += open.length;
|
|
709
|
+
continue;
|
|
710
|
+
}
|
|
711
|
+
if (s.startsWith(close, j)) {
|
|
712
|
+
depth -= 1;
|
|
713
|
+
j += close.length;
|
|
714
|
+
if (depth === 0) return { text: s.slice(at, j), inner: s.slice(at + open.length, j - close.length), end: j };
|
|
715
|
+
continue;
|
|
716
|
+
}
|
|
717
|
+
j += 1;
|
|
718
|
+
}
|
|
719
|
+
throw new N3SyntaxError(`Unterminated RDF annotation block, expected ${close}`);
|
|
720
|
+
}
|
|
721
|
+
|
|
722
|
+
function readTermLikeAt(s, at) {
|
|
723
|
+
const j = skipWsAndComments(s, at);
|
|
724
|
+
if (j >= s.length) return null;
|
|
725
|
+
if (s[j] === '<') return readIriAt(s, j);
|
|
726
|
+
if (s[j] === '"' || s[j] === "'") {
|
|
727
|
+
const str = readStringAt(s, j);
|
|
728
|
+
let end = str.end;
|
|
729
|
+
let text = str.text;
|
|
730
|
+
if (s.startsWith('^^', end)) {
|
|
731
|
+
const dt = readTermAt(s, end + 2);
|
|
732
|
+
if (dt) {
|
|
733
|
+
text += '^^' + dt.text;
|
|
734
|
+
end = dt.end;
|
|
735
|
+
}
|
|
736
|
+
} else if (s[end] === '@') {
|
|
737
|
+
let k = end + 1;
|
|
738
|
+
if (/[A-Za-z]/.test(s[k] || '')) {
|
|
739
|
+
while (k < s.length && /[A-Za-z0-9-]/.test(s[k])) k += 1;
|
|
740
|
+
text += s.slice(end, k);
|
|
741
|
+
end = k;
|
|
742
|
+
}
|
|
743
|
+
}
|
|
744
|
+
return { text, end };
|
|
745
|
+
}
|
|
746
|
+
if (s[j] === '{') return readBalancedBlock(s, j);
|
|
747
|
+
if (s[j] === '[') return readBalancedDelimited(s, j, '[', ']');
|
|
748
|
+
if (s[j] === '(') return readBalancedDelimited(s, j, '(', ')');
|
|
749
|
+
return readTermAt(s, j);
|
|
750
|
+
}
|
|
751
|
+
|
|
752
|
+
function readAnnotationBlockAt(s, at) {
|
|
753
|
+
if (!s.startsWith('{|', at)) return null;
|
|
754
|
+
return readBalancedDelimited(s, at, '{|', '|}');
|
|
755
|
+
}
|
|
756
|
+
|
|
757
|
+
function tryReadAnnotatedTriple(at) {
|
|
758
|
+
const start = skipWsAndComments(s, at);
|
|
759
|
+
if (start >= s.length) return null;
|
|
760
|
+
if (s[start] === '@') return null;
|
|
761
|
+
if (startsWordAt(s, 'PREFIX', start) || startsWordAt(s, 'BASE', start) || startsWordAt(s, 'VERSION', start)) return null;
|
|
762
|
+
if (startsWordAt(s, 'GRAPH', start)) return null;
|
|
763
|
+
|
|
764
|
+
const subj = readTermLikeAt(s, start);
|
|
765
|
+
if (!subj) return null;
|
|
766
|
+
let j = skipWsAndComments(s, subj.end);
|
|
767
|
+
const pred = readTermLikeAt(s, j);
|
|
768
|
+
if (!pred) return null;
|
|
769
|
+
j = skipWsAndComments(s, pred.end);
|
|
770
|
+
const obj = readTermLikeAt(s, j);
|
|
771
|
+
if (!obj) return null;
|
|
772
|
+
j = skipWsAndComments(s, obj.end);
|
|
773
|
+
if (s[j] !== '~' && !s.startsWith('{|', j)) return null;
|
|
774
|
+
|
|
775
|
+
let reifier = '';
|
|
776
|
+
const annotationBlocks = [];
|
|
777
|
+
while (j < s.length) {
|
|
778
|
+
j = skipWsAndComments(s, j);
|
|
779
|
+
if (s[j] === '~') {
|
|
780
|
+
j += 1;
|
|
781
|
+
j = skipWsAndComments(s, j);
|
|
782
|
+
const term = readTermAt(s, j);
|
|
783
|
+
if (term) {
|
|
784
|
+
reifier = term.text;
|
|
785
|
+
j = term.end;
|
|
786
|
+
} else if (!reifier) {
|
|
787
|
+
reifier = `_:rdfAnnotation${++generatedBlank}`;
|
|
788
|
+
}
|
|
789
|
+
continue;
|
|
790
|
+
}
|
|
791
|
+
if (s.startsWith('{|', j)) {
|
|
792
|
+
const block = readAnnotationBlockAt(s, j);
|
|
793
|
+
const inner = block.inner.trim();
|
|
794
|
+
if (!inner) throw new N3SyntaxError('Empty RDF annotation block is not allowed');
|
|
795
|
+
if (!reifier) reifier = `_:rdfAnnotation${++generatedBlank}`;
|
|
796
|
+
annotationBlocks.push(inner);
|
|
797
|
+
j = block.end;
|
|
798
|
+
continue;
|
|
799
|
+
}
|
|
800
|
+
break;
|
|
801
|
+
}
|
|
802
|
+
|
|
803
|
+
const after = skipWsAndComments(s, j);
|
|
804
|
+
if (!['.', ';', ',', '}'].includes(s[after])) return null;
|
|
805
|
+
if (!reifier && annotationBlocks.length === 0) return null;
|
|
806
|
+
|
|
807
|
+
const baseTriple = `${subj.text} ${pred.text} ${obj.text}`;
|
|
808
|
+
const graph = `{ ${baseTriple} }`;
|
|
809
|
+
const extra = [];
|
|
810
|
+
if (reifier) extra.push(`${reifier} ${RDF_REIFIES_IRI} ${graph} .`);
|
|
811
|
+
for (const inner of annotationBlocks) {
|
|
812
|
+
if (inner) extra.push(`${reifier} ${inner} .`);
|
|
813
|
+
}
|
|
814
|
+
|
|
815
|
+
let continuation = '';
|
|
816
|
+
if (s[after] === ';') continuation = `\n${subj.text} `;
|
|
817
|
+
else if (s[after] === ',') continuation = `\n${subj.text} ${pred.text} `;
|
|
818
|
+
|
|
819
|
+
return {
|
|
820
|
+
start,
|
|
821
|
+
end: s[after] === '}' ? after : after + 1,
|
|
822
|
+
text: `${baseTriple} .${extra.length ? '\n' + extra.join('\n') : ''}${continuation}`,
|
|
823
|
+
};
|
|
824
|
+
}
|
|
825
|
+
|
|
826
|
+
while (i < s.length) {
|
|
827
|
+
if (statementStart) {
|
|
828
|
+
const converted = tryReadAnnotatedTriple(i);
|
|
829
|
+
if (converted) {
|
|
830
|
+
out += s.slice(i, converted.start) + converted.text;
|
|
831
|
+
i = converted.end;
|
|
832
|
+
statementStart = true;
|
|
833
|
+
continue;
|
|
834
|
+
}
|
|
835
|
+
}
|
|
836
|
+
|
|
837
|
+
const ch = s[i];
|
|
838
|
+
if (ch === '"' || ch === "'") {
|
|
839
|
+
const str = readStringAt(s, i);
|
|
840
|
+
out += str.text;
|
|
841
|
+
i = str.end;
|
|
842
|
+
continue;
|
|
843
|
+
}
|
|
844
|
+
if (ch === '<' && !s.startsWith('<<', i)) {
|
|
845
|
+
const iri = readIriAt(s, i);
|
|
846
|
+
out += iri.text;
|
|
847
|
+
i = iri.end;
|
|
848
|
+
continue;
|
|
849
|
+
}
|
|
850
|
+
if (ch === '#') {
|
|
851
|
+
while (i < s.length) {
|
|
852
|
+
const c = s[i++];
|
|
853
|
+
out += c;
|
|
854
|
+
if (c === '\n' || c === '\r') break;
|
|
855
|
+
}
|
|
856
|
+
statementStart = true;
|
|
857
|
+
continue;
|
|
858
|
+
}
|
|
859
|
+
out += ch;
|
|
860
|
+
if (ch === '.' || ch === '{' || ch === '}' || ch === '\n' || ch === '\r') statementStart = true;
|
|
861
|
+
else if (!/\s/.test(ch)) statementStart = false;
|
|
862
|
+
i += 1;
|
|
863
|
+
}
|
|
864
|
+
|
|
865
|
+
return out;
|
|
866
|
+
}
|
|
867
|
+
|
|
868
|
+
function stripVersionDirectives(s) {
|
|
869
|
+
return s.replace(/^\s*(?:@version|VERSION)\s+(["'])(?:1\.1|1\.2|1\.2-basic)(?:-messages)?\1\s*\.?\s*(?:#.*)?$/gim, '');
|
|
870
|
+
}
|
|
871
|
+
|
|
872
|
+
function skipWsAndComments(s, at) {
|
|
873
|
+
let i = at;
|
|
874
|
+
while (i < s.length) {
|
|
875
|
+
if (/\s/.test(s[i])) {
|
|
876
|
+
i += 1;
|
|
877
|
+
continue;
|
|
878
|
+
}
|
|
879
|
+
if (s[i] === '#') {
|
|
880
|
+
while (i < s.length && s[i] !== '\n' && s[i] !== '\r') i += 1;
|
|
881
|
+
continue;
|
|
882
|
+
}
|
|
883
|
+
break;
|
|
884
|
+
}
|
|
885
|
+
return i;
|
|
886
|
+
}
|
|
887
|
+
|
|
888
|
+
function readTermAt(s, at) {
|
|
889
|
+
if (s[at] === '<') return readIriAt(s, at);
|
|
890
|
+
// eyemind: [] names a TriG graph too.
|
|
891
|
+
if (s[at] === '[') {
|
|
892
|
+
const close = skipWsAndComments(s, at + 1);
|
|
893
|
+
return s[close] === ']' ? { text: '[]', end: close + 1 } : null;
|
|
894
|
+
}
|
|
895
|
+
let i = at;
|
|
896
|
+
// eyemind: an escaped character belongs to the name, as in :a\.b.
|
|
897
|
+
while (i < s.length && !/\s/.test(s[i]) && !'{}[](),;.'.includes(s[i])) i += s[i] === '\\' ? 2 : 1;
|
|
898
|
+
if (i === at) return null;
|
|
899
|
+
const value = s.slice(at, i);
|
|
900
|
+
if (!value || value.startsWith('@')) return null;
|
|
901
|
+
return { text: value, end: i };
|
|
902
|
+
}
|
|
903
|
+
|
|
904
|
+
// The text without the comments that end it, for finding its last token.
|
|
905
|
+
function stripTrailingComments(text) {
|
|
906
|
+
return text.split(/\r?\n/).map((line) => {
|
|
907
|
+
let quote = null;
|
|
908
|
+
for (let k = 0; k < line.length; k++) {
|
|
909
|
+
const c = line[k];
|
|
910
|
+
if (quote) {
|
|
911
|
+
if (c === '\\') k += 1;
|
|
912
|
+
else if (c === quote) quote = null;
|
|
913
|
+
} else if (c === '"' || c === "'") quote = c;
|
|
914
|
+
else if (c === '<') k = line.indexOf('>', k) < 0 ? line.length : line.indexOf('>', k);
|
|
915
|
+
else if (c === '\\') k += 1;
|
|
916
|
+
else if (c === '#') return line.slice(0, k);
|
|
917
|
+
}
|
|
918
|
+
return line;
|
|
919
|
+
}).join('\n');
|
|
920
|
+
}
|
|
921
|
+
|
|
922
|
+
function readBalancedBlock(s, at) {
|
|
923
|
+
if (s[at] !== '{') return null;
|
|
924
|
+
let i = at;
|
|
925
|
+
let depth = 0;
|
|
926
|
+
while (i < s.length) {
|
|
927
|
+
const ch = s[i];
|
|
928
|
+
if (ch === '"' || ch === "'") {
|
|
929
|
+
i = readStringAt(s, i).end;
|
|
930
|
+
continue;
|
|
931
|
+
}
|
|
932
|
+
if (ch === '<') {
|
|
933
|
+
i = readIriAt(s, i).end;
|
|
934
|
+
continue;
|
|
935
|
+
}
|
|
936
|
+
// eyemind: an escaped character in a name, such as \# or \}.
|
|
937
|
+
if (ch === '\\') {
|
|
938
|
+
i += 2;
|
|
939
|
+
continue;
|
|
940
|
+
}
|
|
941
|
+
if (ch === '#') {
|
|
942
|
+
while (i < s.length && s[i] !== '\n' && s[i] !== '\r') i += 1;
|
|
943
|
+
continue;
|
|
944
|
+
}
|
|
945
|
+
if (s.startsWith('{|', i)) {
|
|
946
|
+
i += 2;
|
|
947
|
+
// eyemind: annotation blocks nest.
|
|
948
|
+
let blocks = 1;
|
|
949
|
+
while (i < s.length) {
|
|
950
|
+
if (s.startsWith('{|', i)) {
|
|
951
|
+
blocks += 1;
|
|
952
|
+
i += 2;
|
|
953
|
+
continue;
|
|
954
|
+
}
|
|
955
|
+
if (s[i] === '"' || s[i] === "'") {
|
|
956
|
+
i = readStringAt(s, i).end;
|
|
957
|
+
continue;
|
|
958
|
+
}
|
|
959
|
+
if (s[i] === '<' && !s.startsWith('<<', i)) {
|
|
960
|
+
i = readIriAt(s, i).end;
|
|
961
|
+
continue;
|
|
962
|
+
}
|
|
963
|
+
if (s[i] === '#') {
|
|
964
|
+
while (i < s.length && s[i] !== '\n' && s[i] !== '\r') i += 1;
|
|
965
|
+
continue;
|
|
966
|
+
}
|
|
967
|
+
if (s.startsWith('|}', i)) {
|
|
968
|
+
i += 2;
|
|
969
|
+
if (--blocks === 0) break;
|
|
970
|
+
continue;
|
|
971
|
+
}
|
|
972
|
+
i += 1;
|
|
973
|
+
}
|
|
974
|
+
continue;
|
|
975
|
+
}
|
|
976
|
+
if (ch === '{') depth += 1;
|
|
977
|
+
if (ch === '}') {
|
|
978
|
+
depth -= 1;
|
|
979
|
+
i += 1;
|
|
980
|
+
if (depth === 0) return { text: s.slice(at, i), inner: s.slice(at + 1, i - 1), end: i };
|
|
981
|
+
continue;
|
|
982
|
+
}
|
|
983
|
+
i += 1;
|
|
984
|
+
}
|
|
985
|
+
throw new N3SyntaxError('Unterminated RDF/TriG graph block, expected }');
|
|
986
|
+
}
|
|
987
|
+
|
|
988
|
+
function normalizeNamedGraphs(s) {
|
|
989
|
+
let out = '';
|
|
990
|
+
let i = 0;
|
|
991
|
+
let statementStart = true;
|
|
992
|
+
let braceDepth = 0;
|
|
993
|
+
|
|
994
|
+
while (i < s.length) {
|
|
995
|
+
if (statementStart && braceDepth === 0) {
|
|
996
|
+
const termStart = skipWsAndComments(s, i);
|
|
997
|
+
out += s.slice(i, termStart);
|
|
998
|
+
i = termStart;
|
|
999
|
+
|
|
1000
|
+
// Preserve directives and keep the scanner at statement-start for
|
|
1001
|
+
// following TriG graph blocks. SPARQL-style PREFIX/BASE/VERSION lines
|
|
1002
|
+
// have no trailing '.', while @prefix/@base/@version directives do.
|
|
1003
|
+
// eyemind: SPARQL-style directives are case-insensitive.
|
|
1004
|
+
const word = /^[A-Za-z]+/.exec(s.slice(i, i + 8))?.[0]?.toUpperCase();
|
|
1005
|
+
if ((word === 'PREFIX' || word === 'BASE' || word === 'VERSION') && !isWordChar(s[i + word.length])) {
|
|
1006
|
+
let end = i;
|
|
1007
|
+
while (end < s.length && s[end] !== '\n' && s[end] !== '\r') end += 1;
|
|
1008
|
+
out += s.slice(i, end);
|
|
1009
|
+
i = end;
|
|
1010
|
+
statementStart = true;
|
|
1011
|
+
continue;
|
|
1012
|
+
}
|
|
1013
|
+
if (s[i] === '@') {
|
|
1014
|
+
const lower = s.slice(i, i + 9).toLowerCase();
|
|
1015
|
+
if (lower.startsWith('@prefix') || lower.startsWith('@base') || lower.startsWith('@version')) {
|
|
1016
|
+
const end = skipOldStyleDirective(s, i);
|
|
1017
|
+
out += s.slice(i, end);
|
|
1018
|
+
i = end;
|
|
1019
|
+
statementStart = true;
|
|
1020
|
+
continue;
|
|
1021
|
+
}
|
|
1022
|
+
}
|
|
1023
|
+
|
|
1024
|
+
// Top-level TriG default graph block: { ... } .
|
|
1025
|
+
if (s[i] === '{') {
|
|
1026
|
+
const block = readBalancedBlock(s, i);
|
|
1027
|
+
const after = skipWsAndComments(s, block.end);
|
|
1028
|
+
// eyemind: in a TriG document every top-level block is a graph.
|
|
1029
|
+
if (trig || after >= s.length || s[after] === '.') {
|
|
1030
|
+
out += block.inner.trim();
|
|
1031
|
+
// eyemind: a graph's last triple needs no dot before its }.
|
|
1032
|
+
if (trig && block.inner.trim() && !/\.\s*$/.test(stripTrailingComments(block.inner))) out += ' .';
|
|
1033
|
+
// eyemind: always end the line, so a comment ending the block ends there.
|
|
1034
|
+
if (block.inner.trim()) out += '\n';
|
|
1035
|
+
i = after < s.length && s[after] === '.' ? after + 1 : after;
|
|
1036
|
+
statementStart = true;
|
|
1037
|
+
continue;
|
|
1038
|
+
}
|
|
1039
|
+
// It is an ordinary N3 formula subject, not a TriG default graph.
|
|
1040
|
+
out += block.text;
|
|
1041
|
+
i = block.end;
|
|
1042
|
+
statementStart = false;
|
|
1043
|
+
continue;
|
|
1044
|
+
}
|
|
1045
|
+
|
|
1046
|
+
let graphKeyword = false;
|
|
1047
|
+
if (startsWordAt(s, 'GRAPH', i)) {
|
|
1048
|
+
graphKeyword = true;
|
|
1049
|
+
i += 'GRAPH'.length;
|
|
1050
|
+
i = skipWsAndComments(s, i);
|
|
1051
|
+
}
|
|
1052
|
+
|
|
1053
|
+
const term = readTermAt(s, i);
|
|
1054
|
+
if (term && !['@prefix', '@base', 'PREFIX', 'BASE', 'VERSION'].includes(term.text)) {
|
|
1055
|
+
const afterTerm = skipWsAndComments(s, term.end);
|
|
1056
|
+
if (s[afterTerm] === '{') {
|
|
1057
|
+
const block = readBalancedBlock(s, afterTerm);
|
|
1058
|
+
const afterBlock = skipWsAndComments(s, block.end);
|
|
1059
|
+
out += `${term.text} ${LOG_NAME_OF_IRI} ${block.text} .`;
|
|
1060
|
+
i = afterBlock < s.length && s[afterBlock] === '.' ? afterBlock + 1 : block.end;
|
|
1061
|
+
statementStart = true;
|
|
1062
|
+
continue;
|
|
1063
|
+
}
|
|
1064
|
+
}
|
|
1065
|
+
|
|
1066
|
+
// Not TriG named-graph syntax after all; copy the first character and
|
|
1067
|
+
// continue as ordinary N3.
|
|
1068
|
+
if (graphKeyword) {
|
|
1069
|
+
out += 'GRAPH ';
|
|
1070
|
+
statementStart = false;
|
|
1071
|
+
} else if (i < s.length) {
|
|
1072
|
+
const copied = s[i++];
|
|
1073
|
+
out += copied;
|
|
1074
|
+
if (!/\s/.test(copied)) statementStart = false;
|
|
1075
|
+
}
|
|
1076
|
+
} else {
|
|
1077
|
+
const ch = s[i];
|
|
1078
|
+
out += ch;
|
|
1079
|
+
// eyemind: an escaped character in a name is no comment or dot.
|
|
1080
|
+
if (ch === '\\') {
|
|
1081
|
+
out += s[i + 1] ?? '';
|
|
1082
|
+
i += 2;
|
|
1083
|
+
continue;
|
|
1084
|
+
}
|
|
1085
|
+
if (ch === '"' || ch === "'") {
|
|
1086
|
+
const str = readStringAt(s, i);
|
|
1087
|
+
out = out.slice(0, -1) + str.text;
|
|
1088
|
+
i = str.end;
|
|
1089
|
+
continue;
|
|
1090
|
+
}
|
|
1091
|
+
if (ch === '<') {
|
|
1092
|
+
const iri = readIriAt(s, i);
|
|
1093
|
+
out = out.slice(0, -1) + iri.text;
|
|
1094
|
+
i = iri.end;
|
|
1095
|
+
continue;
|
|
1096
|
+
}
|
|
1097
|
+
if (ch === '#') {
|
|
1098
|
+
i += 1;
|
|
1099
|
+
while (i < s.length) {
|
|
1100
|
+
const c = s[i++];
|
|
1101
|
+
out += c;
|
|
1102
|
+
if (c === '\n' || c === '\r') break;
|
|
1103
|
+
}
|
|
1104
|
+
continue;
|
|
1105
|
+
}
|
|
1106
|
+
if (ch === '{') braceDepth += 1;
|
|
1107
|
+
else if (ch === '}' && braceDepth > 0) braceDepth -= 1;
|
|
1108
|
+
else if (ch === '.' && braceDepth === 0) statementStart = true;
|
|
1109
|
+
else if (!/\s/.test(ch)) statementStart = false;
|
|
1110
|
+
i += 1;
|
|
1111
|
+
}
|
|
1112
|
+
}
|
|
1113
|
+
|
|
1114
|
+
return out;
|
|
1115
|
+
}
|
|
1116
|
+
|
|
1117
|
+
|
|
1118
|
+
function isOnlyWhitespaceAndComments(s) {
|
|
1119
|
+
return skipWsAndComments(s, 0) >= s.length;
|
|
1120
|
+
}
|
|
1121
|
+
|
|
1122
|
+
|
|
1123
|
+
function skipOldStyleDirective(s, at) {
|
|
1124
|
+
let i = at;
|
|
1125
|
+
while (i < s.length) {
|
|
1126
|
+
const ch = s[i];
|
|
1127
|
+
if (ch === '"' || ch === "'") {
|
|
1128
|
+
i = readStringAt(s, i).end;
|
|
1129
|
+
continue;
|
|
1130
|
+
}
|
|
1131
|
+
if (ch === '<') {
|
|
1132
|
+
i = readIriAt(s, i).end;
|
|
1133
|
+
continue;
|
|
1134
|
+
}
|
|
1135
|
+
if (ch === '#') {
|
|
1136
|
+
while (i < s.length && s[i] !== '\n' && s[i] !== '\r') i += 1;
|
|
1137
|
+
continue;
|
|
1138
|
+
}
|
|
1139
|
+
i += 1;
|
|
1140
|
+
if (ch === '.') return i;
|
|
1141
|
+
}
|
|
1142
|
+
return i;
|
|
1143
|
+
}
|
|
1144
|
+
|
|
1145
|
+
function stripDirectivesAndCommentsForEmptiness(s) {
|
|
1146
|
+
let out = '';
|
|
1147
|
+
let i = 0;
|
|
1148
|
+
let statementStart = true;
|
|
1149
|
+
while (i < s.length) {
|
|
1150
|
+
const ch = s[i];
|
|
1151
|
+
if (ch === '"' || ch === "'") {
|
|
1152
|
+
const str = readStringAt(s, i);
|
|
1153
|
+
out += str.text;
|
|
1154
|
+
i = str.end;
|
|
1155
|
+
statementStart = false;
|
|
1156
|
+
continue;
|
|
1157
|
+
}
|
|
1158
|
+
if (ch === '<') {
|
|
1159
|
+
const iri = readIriAt(s, i);
|
|
1160
|
+
out += iri.text;
|
|
1161
|
+
i = iri.end;
|
|
1162
|
+
statementStart = false;
|
|
1163
|
+
continue;
|
|
1164
|
+
}
|
|
1165
|
+
if (ch === '#') {
|
|
1166
|
+
while (i < s.length && s[i] !== '\n' && s[i] !== '\r') i += 1;
|
|
1167
|
+
statementStart = true;
|
|
1168
|
+
continue;
|
|
1169
|
+
}
|
|
1170
|
+
if (statementStart) {
|
|
1171
|
+
const start = skipWsAndComments(s, i);
|
|
1172
|
+
out += s.slice(i, start);
|
|
1173
|
+
i = start;
|
|
1174
|
+
if (startsWordAt(s, 'PREFIX', i) || startsWordAt(s, 'BASE', i) || startsWordAt(s, 'VERSION', i)) {
|
|
1175
|
+
while (i < s.length && s[i] !== '\n' && s[i] !== '\r') i += 1;
|
|
1176
|
+
statementStart = true;
|
|
1177
|
+
continue;
|
|
1178
|
+
}
|
|
1179
|
+
if (s[i] === '@') {
|
|
1180
|
+
const lower = s.slice(i, i + 9).toLowerCase();
|
|
1181
|
+
if (lower.startsWith('@prefix') || lower.startsWith('@base') || lower.startsWith('@version')) {
|
|
1182
|
+
i = skipOldStyleDirective(s, i);
|
|
1183
|
+
statementStart = true;
|
|
1184
|
+
continue;
|
|
1185
|
+
}
|
|
1186
|
+
}
|
|
1187
|
+
}
|
|
1188
|
+
out += ch;
|
|
1189
|
+
if (ch === '.' || ch === '}' || ch === '\n' || ch === '\r') statementStart = true;
|
|
1190
|
+
else if (!/\s/.test(ch)) statementStart = false;
|
|
1191
|
+
i += 1;
|
|
1192
|
+
}
|
|
1193
|
+
return out;
|
|
1194
|
+
}
|
|
1195
|
+
|
|
1196
|
+
function simpleHashText(s) {
|
|
1197
|
+
let h = 0x811c9dc5;
|
|
1198
|
+
for (let i = 0; i < s.length; i += 1) {
|
|
1199
|
+
h ^= s.charCodeAt(i);
|
|
1200
|
+
h = Math.imul(h, 0x01000193) >>> 0;
|
|
1201
|
+
}
|
|
1202
|
+
return h.toString(16).padStart(8, '0');
|
|
1203
|
+
}
|
|
1204
|
+
|
|
1205
|
+
function rewriteMessageBlankLabels(s, messageIndex) {
|
|
1206
|
+
let out = '';
|
|
1207
|
+
let i = 0;
|
|
1208
|
+
const prefix = `_:eyeling_m${String(messageIndex).padStart(3, '0')}_`;
|
|
1209
|
+
while (i < s.length) {
|
|
1210
|
+
const ch = s[i];
|
|
1211
|
+
if (ch === '"' || ch === "'") {
|
|
1212
|
+
const str = readStringAt(s, i);
|
|
1213
|
+
out += str.text;
|
|
1214
|
+
i = str.end;
|
|
1215
|
+
continue;
|
|
1216
|
+
}
|
|
1217
|
+
if (ch === '<' && !s.startsWith('<<', i)) {
|
|
1218
|
+
const iri = readIriAt(s, i);
|
|
1219
|
+
out += iri.text;
|
|
1220
|
+
i = iri.end;
|
|
1221
|
+
continue;
|
|
1222
|
+
}
|
|
1223
|
+
if (ch === '#') {
|
|
1224
|
+
while (i < s.length) {
|
|
1225
|
+
const c = s[i++];
|
|
1226
|
+
out += c;
|
|
1227
|
+
if (c === '\n' || c === '\r') break;
|
|
1228
|
+
}
|
|
1229
|
+
continue;
|
|
1230
|
+
}
|
|
1231
|
+
if (s.startsWith('_:', i)) {
|
|
1232
|
+
let j = i + 2;
|
|
1233
|
+
while (j < s.length && !/\s/.test(s[j]) && !'{}[](),;.'.includes(s[j])) j += 1;
|
|
1234
|
+
const label = s.slice(i + 2, j);
|
|
1235
|
+
if (label) {
|
|
1236
|
+
out += prefix + label.replace(/[^A-Za-z0-9_]/g, '_');
|
|
1237
|
+
i = j;
|
|
1238
|
+
continue;
|
|
1239
|
+
}
|
|
1240
|
+
}
|
|
1241
|
+
out += ch;
|
|
1242
|
+
i += 1;
|
|
1243
|
+
}
|
|
1244
|
+
return out;
|
|
1245
|
+
}
|
|
1246
|
+
|
|
1247
|
+
function findMessageDirectiveAt(s, at) {
|
|
1248
|
+
if (startsWordAt(s, 'MESSAGE', at)) return { start: at, end: at + 'MESSAGE'.length };
|
|
1249
|
+
if (s.slice(at, at + 8).toLowerCase() === '@message' && !isWordChar(s[at + 8])) {
|
|
1250
|
+
let end = at + 8;
|
|
1251
|
+
end = skipWsAndComments(s, end);
|
|
1252
|
+
if (s[end] === '.') end += 1;
|
|
1253
|
+
return { start: at, end };
|
|
1254
|
+
}
|
|
1255
|
+
return null;
|
|
1256
|
+
}
|
|
1257
|
+
|
|
1258
|
+
function splitRdfMessageLog(s) {
|
|
1259
|
+
const chunks = [];
|
|
1260
|
+
let i = 0;
|
|
1261
|
+
let start = 0;
|
|
1262
|
+
let braceDepth = 0;
|
|
1263
|
+
let bracketDepth = 0;
|
|
1264
|
+
let parenDepth = 0;
|
|
1265
|
+
let statementStart = true;
|
|
1266
|
+
let sawDelimiter = false;
|
|
1267
|
+
|
|
1268
|
+
while (i < s.length) {
|
|
1269
|
+
const ch = s[i];
|
|
1270
|
+
if (ch === '"' || ch === "'") {
|
|
1271
|
+
i = readStringAt(s, i).end;
|
|
1272
|
+
statementStart = false;
|
|
1273
|
+
continue;
|
|
1274
|
+
}
|
|
1275
|
+
if (ch === '<' && !s.startsWith('<<', i)) {
|
|
1276
|
+
i = readIriAt(s, i).end;
|
|
1277
|
+
statementStart = false;
|
|
1278
|
+
continue;
|
|
1279
|
+
}
|
|
1280
|
+
if (ch === '#') {
|
|
1281
|
+
while (i < s.length && s[i] !== '\n' && s[i] !== '\r') i += 1;
|
|
1282
|
+
statementStart = true;
|
|
1283
|
+
continue;
|
|
1284
|
+
}
|
|
1285
|
+
if (statementStart && braceDepth === 0 && bracketDepth === 0 && parenDepth === 0) {
|
|
1286
|
+
const termStart = skipWsAndComments(s, i);
|
|
1287
|
+
const msg = findMessageDirectiveAt(s, termStart);
|
|
1288
|
+
if (msg) {
|
|
1289
|
+
chunks.push(s.slice(start, termStart));
|
|
1290
|
+
start = msg.end;
|
|
1291
|
+
i = msg.end;
|
|
1292
|
+
statementStart = true;
|
|
1293
|
+
sawDelimiter = true;
|
|
1294
|
+
continue;
|
|
1295
|
+
}
|
|
1296
|
+
if (termStart !== i) {
|
|
1297
|
+
i = termStart;
|
|
1298
|
+
continue;
|
|
1299
|
+
}
|
|
1300
|
+
}
|
|
1301
|
+
if (ch === '{') braceDepth += 1;
|
|
1302
|
+
else if (ch === '}' && braceDepth > 0) braceDepth -= 1;
|
|
1303
|
+
else if (ch === '[') bracketDepth += 1;
|
|
1304
|
+
else if (ch === ']' && bracketDepth > 0) bracketDepth -= 1;
|
|
1305
|
+
else if (ch === '(') parenDepth += 1;
|
|
1306
|
+
else if (ch === ')' && parenDepth > 0) parenDepth -= 1;
|
|
1307
|
+
|
|
1308
|
+
if (ch === '.' && braceDepth === 0 && bracketDepth === 0 && parenDepth === 0) statementStart = true;
|
|
1309
|
+
else if (ch === '\n' || ch === '\r') statementStart = true;
|
|
1310
|
+
else if (!/\s/.test(ch)) statementStart = false;
|
|
1311
|
+
i += 1;
|
|
1312
|
+
}
|
|
1313
|
+
|
|
1314
|
+
const tail = s.slice(start);
|
|
1315
|
+
if (!sawDelimiter || !isOnlyWhitespaceAndComments(tail)) chunks.push(tail);
|
|
1316
|
+
return chunks;
|
|
1317
|
+
}
|
|
1318
|
+
|
|
1319
|
+
function normalizeMessageChunk(chunk, messageIndex) {
|
|
1320
|
+
let body = String(chunk || '');
|
|
1321
|
+
if (hasTripleTerms || body.includes('<<')) body = convertTripleTerms(body);
|
|
1322
|
+
if (hasAnnotationSyntax || /(?:^|\s)~|\{\|/.test(body)) {
|
|
1323
|
+
// eyemind: annotations are read by the parser.
|
|
1324
|
+
}
|
|
1325
|
+
body = normalizeNamedGraphs(body);
|
|
1326
|
+
body = rewriteMessageBlankLabels(body, messageIndex);
|
|
1327
|
+
return body.trim();
|
|
1328
|
+
}
|
|
1329
|
+
|
|
1330
|
+
function messageChunkHasRdf(body) {
|
|
1331
|
+
return !isOnlyWhitespaceAndComments(stripDirectivesAndCommentsForEmptiness(body));
|
|
1332
|
+
}
|
|
1333
|
+
|
|
1334
|
+
function normalizeRdfMessageLog(s) {
|
|
1335
|
+
const withoutVersion = stripVersionDirectives(s);
|
|
1336
|
+
const chunks = splitRdfMessageLog(withoutVersion);
|
|
1337
|
+
const hash = simpleHashText(s);
|
|
1338
|
+
const base = `urn:eyeling:message-log:${hash}`;
|
|
1339
|
+
const stream = `<${base}#stream>`;
|
|
1340
|
+
const envelopeIris = chunks.map((unused, idx) => `<${base}#m${String(idx + 1).padStart(3, '0')}>`);
|
|
1341
|
+
const payloadIris = chunks.map((unused, idx) => `<${base}#m${String(idx + 1).padStart(3, '0')}/payload>`);
|
|
1342
|
+
const out = [];
|
|
1343
|
+
|
|
1344
|
+
out.push(`${stream} ${RDF_TYPE_IRI} ${EYMSG.RDFMessageStream} .`);
|
|
1345
|
+
out.push(`${stream} ${EYMSG.messageCount} "${chunks.length}"^^${XSD_INTEGER_IRI} .`);
|
|
1346
|
+
if (envelopeIris.length) {
|
|
1347
|
+
out.push(`${stream} ${EYMSG.orderedEnvelopes} (${envelopeIris.join(' ')}) .`);
|
|
1348
|
+
out.push(`${stream} ${EYMSG.firstEnvelope} ${envelopeIris[0]} .`);
|
|
1349
|
+
out.push(`${stream} ${EYMSG.lastEnvelope} ${envelopeIris[envelopeIris.length - 1]} .`);
|
|
1350
|
+
}
|
|
1351
|
+
|
|
1352
|
+
for (let idx = 0; idx < chunks.length; idx += 1) {
|
|
1353
|
+
const n = idx + 1;
|
|
1354
|
+
const envelope = envelopeIris[idx];
|
|
1355
|
+
const payload = payloadIris[idx];
|
|
1356
|
+
const body = normalizeMessageChunk(chunks[idx], n);
|
|
1357
|
+
const hasBody = messageChunkHasRdf(body);
|
|
1358
|
+
|
|
1359
|
+
out.push(`${stream} ${EYMSG.envelope} ${envelope} .`);
|
|
1360
|
+
out.push(`${envelope} ${RDF_TYPE_IRI} ${EYMSG.MessageEnvelope} .`);
|
|
1361
|
+
out.push(`${envelope} ${EYMSG.offset} "${n}"^^${XSD_INTEGER_IRI} .`);
|
|
1362
|
+
out.push(`${envelope} ${EYMSG.payloadKind} ${hasBody ? EYMSG.nonEmpty : EYMSG.empty} .`);
|
|
1363
|
+
if (idx + 1 < envelopeIris.length) out.push(`${envelope} ${EYMSG.nextEnvelope} ${envelopeIris[idx + 1]} .`);
|
|
1364
|
+
if (hasBody) {
|
|
1365
|
+
out.push(`${envelope} ${EYMSG.payloadGraph} ${payload} .`);
|
|
1366
|
+
out.push(`${payload} ${LOG_NAME_OF_IRI} {`);
|
|
1367
|
+
out.push(body);
|
|
1368
|
+
out.push(`} .`);
|
|
1369
|
+
}
|
|
1370
|
+
}
|
|
1371
|
+
|
|
1372
|
+
return out.join('\n') + '\n';
|
|
1373
|
+
}
|
|
1374
|
+
|
|
1375
|
+
if (hasMessageVersionDirective) return normalizeRdfMessageLog(text);
|
|
1376
|
+
|
|
1377
|
+
if (hasTripleTerms) text = convertTripleTerms(text);
|
|
1378
|
+
// eyemind: annotations are read by the parser, after their triple.
|
|
1379
|
+
if (hasVersionDirective || hasMessageVersionDirective) text = stripVersionDirectives(text);
|
|
1380
|
+
if (trig || hasVersionDirective || hasMessageVersionDirective || hasNamedGraphCandidate) text = normalizeNamedGraphs(text);
|
|
1381
|
+
return text;
|
|
1382
|
+
}
|
|
1383
|
+
|
|
1384
|
+
|
|
1385
|
+
function isNumericLikeIdentifier(word) {
|
|
1386
|
+
if (typeof word !== 'string' || word.length === 0) return false;
|
|
1387
|
+
for (let j = 0; j < word.length; j++) {
|
|
1388
|
+
const code = word.charCodeAt(j);
|
|
1389
|
+
if (!((code >= 48 && code <= 57) || code === 46 || code === 45)) return false;
|
|
1390
|
+
}
|
|
1391
|
+
return true;
|
|
1392
|
+
}
|
|
1393
|
+
|
|
1394
|
+
function lex(inputText, opts = {}) {
|
|
1395
|
+
const rdf = !!(opts && opts.rdf);
|
|
1396
|
+
if (rdf) inputText = normalizeRdfCompatibility(inputText, { trig: !!opts.trig });
|
|
1397
|
+
// Avoid copying large ASCII/BMP inputs into an Array. Array.from() is
|
|
1398
|
+
// only needed when the text contains surrogate pairs and we want the old
|
|
1399
|
+
// code-point iteration behavior for non-BMP characters.
|
|
1400
|
+
const hasSurrogates = /[\uD800-\uDFFF]/.test(inputText);
|
|
1401
|
+
const inputMayContainInvalidStringChar = hasSurrogates || /[\u0000\uFFFE\uFFFF]/.test(inputText);
|
|
1402
|
+
const chars = hasSurrogates ? Array.from(inputText) : inputText;
|
|
1403
|
+
const n = chars.length;
|
|
1404
|
+
let i = 0;
|
|
1405
|
+
const tokens = [];
|
|
1406
|
+
|
|
1407
|
+
function peek(offset = 0) {
|
|
1408
|
+
const j = i + offset;
|
|
1409
|
+
return j >= 0 && j < n ? chars[j] : null;
|
|
1410
|
+
}
|
|
1411
|
+
|
|
1412
|
+
// Read an identifier-like token (prefixed name / blank node id / keyword).
|
|
1413
|
+
// Implements the relevant bits of the N3/Turtle grammar for PNAME_*:
|
|
1414
|
+
// - Accepts Unicode PN_CHARS*, ':' in local part, and '_' etc.
|
|
1415
|
+
// - Accepts percent escapes (%HH) as PLX fragments.
|
|
1416
|
+
// - Accepts PN_LOCAL_ESC backslash escapes and decodes them ("\\." -> ".").
|
|
1417
|
+
// - Accepts '.' inside a name only when it is not terminal.
|
|
1418
|
+
function sliceChars(start, end) {
|
|
1419
|
+
return typeof chars === 'string' ? chars.slice(start, end) : chars.slice(start, end).join('');
|
|
1420
|
+
}
|
|
1421
|
+
|
|
1422
|
+
function readIdentText(startOffsetForErrors) {
|
|
1423
|
+
const start = i;
|
|
1424
|
+
let out = null;
|
|
1425
|
+
|
|
1426
|
+
function appendRawUntilHere() {
|
|
1427
|
+
if (out === null) out = [sliceChars(start, i)];
|
|
1428
|
+
}
|
|
1429
|
+
|
|
1430
|
+
while (i < n) {
|
|
1431
|
+
const cc = chars[i];
|
|
1432
|
+
if (cc === null || cc === undefined || isWs(cc)) break;
|
|
1433
|
+
|
|
1434
|
+
// Hard stops: delimiters cannot appear unescaped inside PNAME tokens.
|
|
1435
|
+
if (cc === '{' || cc === '}' || cc === '(' || cc === ')' || cc === '[' || cc === ']' || cc === ';' || cc === ',') break;
|
|
1436
|
+
|
|
1437
|
+
const code = cc.charCodeAt(0);
|
|
1438
|
+
|
|
1439
|
+
// eyemind: in RDF a blank node label has no colon after its _: prefix,
|
|
1440
|
+
// so _:s:p is _:s followed by :p.
|
|
1441
|
+
if (rdf && code === 58 && i > start + 1 && chars[start] === '_' && chars[start + 1] === ':') break;
|
|
1442
|
+
|
|
1443
|
+
// Common ASCII QName/identifier characters. Keep this branch inline so
|
|
1444
|
+
// ordinary N3 files do not call through the full Unicode PN_CHARS predicate
|
|
1445
|
+
// for every character.
|
|
1446
|
+
if (
|
|
1447
|
+
code === 58 || // ':'
|
|
1448
|
+
code === 95 || // '_'
|
|
1449
|
+
code === 45 || // '-'
|
|
1450
|
+
(code >= 48 && code <= 57) ||
|
|
1451
|
+
(code >= 65 && code <= 90) ||
|
|
1452
|
+
(code >= 97 && code <= 122)
|
|
1453
|
+
) {
|
|
1454
|
+
if (out !== null) out.push(cc);
|
|
1455
|
+
i++;
|
|
1456
|
+
continue;
|
|
1457
|
+
}
|
|
1458
|
+
|
|
1459
|
+
// Dot is allowed inside PN_LOCAL, but not at the end.
|
|
1460
|
+
if (cc === '.') {
|
|
1461
|
+
// eyemind: a run of dots stays in the name when a name character follows it.
|
|
1462
|
+
let run = 1;
|
|
1463
|
+
while (peek(run) === '.') run++;
|
|
1464
|
+
const next = peek(run);
|
|
1465
|
+
if (next === null) break;
|
|
1466
|
+
const ncode = next.charCodeAt(0);
|
|
1467
|
+
if (
|
|
1468
|
+
next === '%' ||
|
|
1469
|
+
next === '\\' ||
|
|
1470
|
+
ncode === 58 ||
|
|
1471
|
+
ncode === 95 ||
|
|
1472
|
+
ncode === 45 ||
|
|
1473
|
+
(ncode >= 48 && ncode <= 57) ||
|
|
1474
|
+
(ncode >= 65 && ncode <= 90) ||
|
|
1475
|
+
(ncode >= 97 && ncode <= 122) ||
|
|
1476
|
+
isIdentChar(next)
|
|
1477
|
+
) {
|
|
1478
|
+
if (out !== null) out.push('.'.repeat(run));
|
|
1479
|
+
i += run;
|
|
1480
|
+
continue;
|
|
1481
|
+
}
|
|
1482
|
+
break;
|
|
1483
|
+
}
|
|
1484
|
+
|
|
1485
|
+
// Percent escape: %HH
|
|
1486
|
+
if (cc === '%') {
|
|
1487
|
+
const h1 = peek(1);
|
|
1488
|
+
const h2 = peek(2);
|
|
1489
|
+
if (!isHexDigit(h1) || !isHexDigit(h2)) {
|
|
1490
|
+
throw new N3SyntaxError(
|
|
1491
|
+
'Invalid percent escape in prefixed name (expected %HH)',
|
|
1492
|
+
typeof startOffsetForErrors === 'number' ? startOffsetForErrors : i,
|
|
1493
|
+
);
|
|
1494
|
+
}
|
|
1495
|
+
appendRawUntilHere();
|
|
1496
|
+
out.push('%', h1, h2);
|
|
1497
|
+
i += 3;
|
|
1498
|
+
continue;
|
|
1499
|
+
}
|
|
1500
|
+
|
|
1501
|
+
// Backslash escape in PN_LOCAL (PN_LOCAL_ESC)
|
|
1502
|
+
if (cc === '\\') {
|
|
1503
|
+
const esc = peek(1);
|
|
1504
|
+
if (esc !== null && PN_LOCAL_ESC_SET.has(esc)) {
|
|
1505
|
+
appendRawUntilHere();
|
|
1506
|
+
out.push(esc); // decoded form
|
|
1507
|
+
i += 2;
|
|
1508
|
+
continue;
|
|
1509
|
+
}
|
|
1510
|
+
throw new N3SyntaxError(
|
|
1511
|
+
'Invalid local name escape (use \\_ \\~ \\. \\- ... per N3 grammar)',
|
|
1512
|
+
typeof startOffsetForErrors === 'number' ? startOffsetForErrors : i,
|
|
1513
|
+
);
|
|
1514
|
+
}
|
|
1515
|
+
|
|
1516
|
+
if (isIdentChar(cc)) {
|
|
1517
|
+
if (out !== null) out.push(cc);
|
|
1518
|
+
i++;
|
|
1519
|
+
continue;
|
|
1520
|
+
}
|
|
1521
|
+
|
|
1522
|
+
break;
|
|
1523
|
+
}
|
|
1524
|
+
return out === null ? sliceChars(start, i) : out.join('');
|
|
1525
|
+
}
|
|
1526
|
+
|
|
1527
|
+
while (i < n) {
|
|
1528
|
+
const c = peek();
|
|
1529
|
+
if (c === null) break;
|
|
1530
|
+
|
|
1531
|
+
// 1) Whitespace
|
|
1532
|
+
if (isWs(c)) {
|
|
1533
|
+
i++;
|
|
1534
|
+
continue;
|
|
1535
|
+
}
|
|
1536
|
+
|
|
1537
|
+
// 2) Comments starting with '#'
|
|
1538
|
+
if (c === '#') {
|
|
1539
|
+
while (i < n && chars[i] !== '\n' && chars[i] !== '\r') i++;
|
|
1540
|
+
continue;
|
|
1541
|
+
}
|
|
1542
|
+
|
|
1543
|
+
// 3) Two-character operators: => and <=
|
|
1544
|
+
if (c === '=') {
|
|
1545
|
+
if (peek(1) === '>') {
|
|
1546
|
+
tokens.push(new Token('OpImplies', null, i));
|
|
1547
|
+
i += 2;
|
|
1548
|
+
continue;
|
|
1549
|
+
} else {
|
|
1550
|
+
// N3 syntactic sugar: '=' means owl:sameAs
|
|
1551
|
+
tokens.push(new Token('Equals', null, i));
|
|
1552
|
+
i += 1;
|
|
1553
|
+
continue;
|
|
1554
|
+
}
|
|
1555
|
+
}
|
|
1556
|
+
|
|
1557
|
+
// eyemind: RDF 1.2 reified triples << ... >>, reifiers ~ and annotation
|
|
1558
|
+
// blocks {| ... |} are tokens the parser reads in RDF mode.
|
|
1559
|
+
if (rdf) {
|
|
1560
|
+
const two = c + (peek(1) ?? '');
|
|
1561
|
+
const kind = { '<<': 'LtLt', '>>': 'GtGt', '{|': 'AnnotOpen', '|}': 'AnnotClose' }[two];
|
|
1562
|
+
if (kind) {
|
|
1563
|
+
tokens.push(new Token(kind, null, i));
|
|
1564
|
+
i += 2;
|
|
1565
|
+
continue;
|
|
1566
|
+
}
|
|
1567
|
+
if (c === '~') {
|
|
1568
|
+
tokens.push(new Token('Tilde', null, i));
|
|
1569
|
+
i += 1;
|
|
1570
|
+
continue;
|
|
1571
|
+
}
|
|
1572
|
+
}
|
|
1573
|
+
|
|
1574
|
+
if (c === '<') {
|
|
1575
|
+
if (peek(1) === '=') {
|
|
1576
|
+
tokens.push(new Token('OpImpliedBy', null, i));
|
|
1577
|
+
i += 2;
|
|
1578
|
+
continue;
|
|
1579
|
+
}
|
|
1580
|
+
// N3 predicate inversion: "<-" (swap subject/object for this predicate)
|
|
1581
|
+
if (peek(1) === '-') {
|
|
1582
|
+
tokens.push(new Token('OpPredInvert', null, i));
|
|
1583
|
+
i += 2;
|
|
1584
|
+
continue;
|
|
1585
|
+
}
|
|
1586
|
+
// Otherwise IRIREF <...>
|
|
1587
|
+
const start = i;
|
|
1588
|
+
i++; // skip '<'
|
|
1589
|
+
const iriChars = [];
|
|
1590
|
+
while (i < n && chars[i] !== '>') {
|
|
1591
|
+
iriChars.push(chars[i]);
|
|
1592
|
+
i++;
|
|
1593
|
+
}
|
|
1594
|
+
if (i >= n || chars[i] !== '>') {
|
|
1595
|
+
throw new N3SyntaxError('Unterminated IRI <...>', start);
|
|
1596
|
+
}
|
|
1597
|
+
i++; // skip '>'
|
|
1598
|
+
const iri = decodeIriRefEscapes(iriChars.join(''), start);
|
|
1599
|
+
tokens.push(new Token('IriRef', iri, start));
|
|
1600
|
+
continue;
|
|
1601
|
+
}
|
|
1602
|
+
|
|
1603
|
+
// 4) Path + datatype operators: !, ^, ^^
|
|
1604
|
+
if (c === '!') {
|
|
1605
|
+
tokens.push(new Token('OpPathFwd', null, i));
|
|
1606
|
+
i += 1;
|
|
1607
|
+
continue;
|
|
1608
|
+
}
|
|
1609
|
+
if (c === '^') {
|
|
1610
|
+
if (peek(1) === '^') {
|
|
1611
|
+
tokens.push(new Token('HatHat', null, i));
|
|
1612
|
+
i += 2;
|
|
1613
|
+
continue;
|
|
1614
|
+
}
|
|
1615
|
+
tokens.push(new Token('OpPathRev', null, i));
|
|
1616
|
+
i += 1;
|
|
1617
|
+
continue;
|
|
1618
|
+
}
|
|
1619
|
+
|
|
1620
|
+
// 5) Numeric literal (integer, decimal, or double). Turtle/N3 numeric
|
|
1621
|
+
// literals may have a leading sign and decimals may start with '.', e.g.
|
|
1622
|
+
// '+42' and '.5'. Reject repeated decimal points so '1.2.3'
|
|
1623
|
+
// cannot be misread as one impossible numeric-like token.
|
|
1624
|
+
if (
|
|
1625
|
+
isAsciiDigit(c) ||
|
|
1626
|
+
((c === '+' || c === '-') && (isAsciiDigit(peek(1)) || (peek(1) === '.' && isAsciiDigit(peek(2))))) ||
|
|
1627
|
+
(c === '.' && isAsciiDigit(peek(1)) && !isAsciiDigit(peek(-1)))
|
|
1628
|
+
) {
|
|
1629
|
+
const start = i;
|
|
1630
|
+
const numChars = [];
|
|
1631
|
+
|
|
1632
|
+
if (chars[i] === '+' || chars[i] === '-') {
|
|
1633
|
+
numChars.push(chars[i]);
|
|
1634
|
+
i++;
|
|
1635
|
+
}
|
|
1636
|
+
|
|
1637
|
+
if (chars[i] === '.') {
|
|
1638
|
+
numChars.push('.');
|
|
1639
|
+
i++;
|
|
1640
|
+
while (i < n && isAsciiDigit(chars[i])) {
|
|
1641
|
+
numChars.push(chars[i]);
|
|
1642
|
+
i++;
|
|
1643
|
+
}
|
|
1644
|
+
} else {
|
|
1645
|
+
while (i < n && isAsciiDigit(chars[i])) {
|
|
1646
|
+
numChars.push(chars[i]);
|
|
1647
|
+
i++;
|
|
1648
|
+
}
|
|
1649
|
+
if (i < n && chars[i] === '.') {
|
|
1650
|
+
const next = i + 1 < n ? chars[i + 1] : null;
|
|
1651
|
+
let exponentAfterDot = false;
|
|
1652
|
+
if (next === 'e' || next === 'E') {
|
|
1653
|
+
let j = i + 2;
|
|
1654
|
+
if (j < n && (chars[j] === '+' || chars[j] === '-')) j++;
|
|
1655
|
+
exponentAfterDot = j < n && isAsciiDigit(chars[j]);
|
|
1656
|
+
}
|
|
1657
|
+
if (isAsciiDigit(next) || exponentAfterDot) {
|
|
1658
|
+
numChars.push('.');
|
|
1659
|
+
i++;
|
|
1660
|
+
while (i < n && isAsciiDigit(chars[i])) {
|
|
1661
|
+
numChars.push(chars[i]);
|
|
1662
|
+
i++;
|
|
1663
|
+
}
|
|
1664
|
+
}
|
|
1665
|
+
}
|
|
1666
|
+
}
|
|
1667
|
+
|
|
1668
|
+
if (i < n && chars[i] === '.' && i + 1 < n && isAsciiDigit(chars[i + 1])) {
|
|
1669
|
+
throw new N3SyntaxError('Malformed numeric literal: multiple decimal points', start);
|
|
1670
|
+
}
|
|
1671
|
+
|
|
1672
|
+
// Optional exponent part: e.g., 1e0, 1.1e-3, .5E+0.
|
|
1673
|
+
if (i < n && (chars[i] === 'e' || chars[i] === 'E')) {
|
|
1674
|
+
let j = i + 1;
|
|
1675
|
+
if (j < n && (chars[j] === '+' || chars[j] === '-')) j++;
|
|
1676
|
+
if (j < n && isAsciiDigit(chars[j])) {
|
|
1677
|
+
numChars.push(chars[i]); // e/E
|
|
1678
|
+
i++;
|
|
1679
|
+
if (i < n && (chars[i] === '+' || chars[i] === '-')) {
|
|
1680
|
+
numChars.push(chars[i]);
|
|
1681
|
+
i++;
|
|
1682
|
+
}
|
|
1683
|
+
while (i < n && isAsciiDigit(chars[i])) {
|
|
1684
|
+
numChars.push(chars[i]);
|
|
1685
|
+
i++;
|
|
1686
|
+
}
|
|
1687
|
+
}
|
|
1688
|
+
}
|
|
1689
|
+
|
|
1690
|
+
if (i < n && chars[i] === '.' && i + 1 < n && isAsciiDigit(chars[i + 1])) {
|
|
1691
|
+
throw new N3SyntaxError('Malformed numeric literal: multiple decimal points', start);
|
|
1692
|
+
}
|
|
1693
|
+
|
|
1694
|
+
tokens.push(new Token('Literal', numChars.join(''), start));
|
|
1695
|
+
continue;
|
|
1696
|
+
}
|
|
1697
|
+
|
|
1698
|
+
// 6) Single-character punctuation. Use a switch rather than allocating a
|
|
1699
|
+
// mapping object for every punctuation token in large inputs.
|
|
1700
|
+
switch (c) {
|
|
1701
|
+
case '{':
|
|
1702
|
+
tokens.push(new Token('LBrace', null, i));
|
|
1703
|
+
i++;
|
|
1704
|
+
continue;
|
|
1705
|
+
case '}':
|
|
1706
|
+
tokens.push(new Token('RBrace', null, i));
|
|
1707
|
+
i++;
|
|
1708
|
+
continue;
|
|
1709
|
+
case '(':
|
|
1710
|
+
tokens.push(new Token('LParen', null, i));
|
|
1711
|
+
i++;
|
|
1712
|
+
continue;
|
|
1713
|
+
case ')':
|
|
1714
|
+
tokens.push(new Token('RParen', null, i));
|
|
1715
|
+
i++;
|
|
1716
|
+
continue;
|
|
1717
|
+
case '[':
|
|
1718
|
+
tokens.push(new Token('LBracket', null, i));
|
|
1719
|
+
i++;
|
|
1720
|
+
continue;
|
|
1721
|
+
case ']':
|
|
1722
|
+
tokens.push(new Token('RBracket', null, i));
|
|
1723
|
+
i++;
|
|
1724
|
+
continue;
|
|
1725
|
+
case ';':
|
|
1726
|
+
tokens.push(new Token('Semicolon', null, i));
|
|
1727
|
+
i++;
|
|
1728
|
+
continue;
|
|
1729
|
+
case ',':
|
|
1730
|
+
tokens.push(new Token('Comma', null, i));
|
|
1731
|
+
i++;
|
|
1732
|
+
continue;
|
|
1733
|
+
case '.':
|
|
1734
|
+
tokens.push(new Token('Dot', null, i));
|
|
1735
|
+
i++;
|
|
1736
|
+
continue;
|
|
1737
|
+
default:
|
|
1738
|
+
break;
|
|
1739
|
+
}
|
|
1740
|
+
|
|
1741
|
+
// String literal: short "..." or long """..."""
|
|
1742
|
+
if (c === '"') {
|
|
1743
|
+
const start = i;
|
|
1744
|
+
|
|
1745
|
+
// Long string literal """ ... """
|
|
1746
|
+
if (peek(1) === '"' && peek(2) === '"') {
|
|
1747
|
+
i += 3; // consume opening """
|
|
1748
|
+
const sChars = [];
|
|
1749
|
+
let closed = false;
|
|
1750
|
+
while (i < n) {
|
|
1751
|
+
const cc = chars[i];
|
|
1752
|
+
|
|
1753
|
+
// Preserve escapes verbatim (same behavior as short strings)
|
|
1754
|
+
if (cc === '\\') {
|
|
1755
|
+
i++;
|
|
1756
|
+
if (i < n) {
|
|
1757
|
+
const esc = chars[i];
|
|
1758
|
+
i++;
|
|
1759
|
+
sChars.push('\\');
|
|
1760
|
+
sChars.push(esc);
|
|
1761
|
+
} else {
|
|
1762
|
+
sChars.push('\\');
|
|
1763
|
+
}
|
|
1764
|
+
continue;
|
|
1765
|
+
}
|
|
1766
|
+
|
|
1767
|
+
// In long strings, a run of >= 3 delimiter quotes terminates the literal.
|
|
1768
|
+
// Any extra quotes beyond the final 3 are part of the content.
|
|
1769
|
+
if (cc === '"') {
|
|
1770
|
+
let run = 0;
|
|
1771
|
+
while (i + run < n && chars[i + run] === '"') run++;
|
|
1772
|
+
|
|
1773
|
+
if (run >= 3) {
|
|
1774
|
+
for (let k = 0; k < run - 3; k++) sChars.push('"');
|
|
1775
|
+
i += run; // consume content quotes (if any) + closing delimiter
|
|
1776
|
+
closed = true;
|
|
1777
|
+
break;
|
|
1778
|
+
}
|
|
1779
|
+
|
|
1780
|
+
for (let k = 0; k < run; k++) sChars.push('"');
|
|
1781
|
+
i += run;
|
|
1782
|
+
continue;
|
|
1783
|
+
}
|
|
1784
|
+
|
|
1785
|
+
sChars.push(cc);
|
|
1786
|
+
i++;
|
|
1787
|
+
}
|
|
1788
|
+
if (!closed) throw new N3SyntaxError('Unterminated long string literal """..."""', start);
|
|
1789
|
+
const raw = '"""' + sChars.join('') + '"""';
|
|
1790
|
+
const decoded = decodeN3StringEscapes(stripQuotes(raw), start);
|
|
1791
|
+
assertValidStringLiteralValue(decoded, start);
|
|
1792
|
+
const s = JSON.stringify(decoded); // canonical short quoted form
|
|
1793
|
+
tokens.push(new Token('Literal', s, start));
|
|
1794
|
+
continue;
|
|
1795
|
+
}
|
|
1796
|
+
|
|
1797
|
+
// Short string literal " ... ". Most data files contain plain
|
|
1798
|
+
// unescaped labels; keep that path slice-based and avoid building an
|
|
1799
|
+
// intermediate character array + raw quoted string.
|
|
1800
|
+
i++; // consume opening "
|
|
1801
|
+
const contentStart = i;
|
|
1802
|
+
let sChars = null;
|
|
1803
|
+
let closed = false;
|
|
1804
|
+
while (i < n) {
|
|
1805
|
+
const cc = chars[i];
|
|
1806
|
+
i++;
|
|
1807
|
+
if (cc === '\\') {
|
|
1808
|
+
if (sChars === null) sChars = [sliceChars(contentStart, i - 1)];
|
|
1809
|
+
if (i < n) {
|
|
1810
|
+
const esc = chars[i];
|
|
1811
|
+
i++;
|
|
1812
|
+
sChars.push('\\');
|
|
1813
|
+
sChars.push(esc);
|
|
1814
|
+
} else {
|
|
1815
|
+
sChars.push('\\');
|
|
1816
|
+
}
|
|
1817
|
+
continue;
|
|
1818
|
+
}
|
|
1819
|
+
if (cc === '\n' || cc === '\r') {
|
|
1820
|
+
throw new N3SyntaxError('Unescaped newline in short string literal', start);
|
|
1821
|
+
}
|
|
1822
|
+
if (cc === '"') {
|
|
1823
|
+
closed = true;
|
|
1824
|
+
break;
|
|
1825
|
+
}
|
|
1826
|
+
if (sChars !== null) sChars.push(cc);
|
|
1827
|
+
}
|
|
1828
|
+
if (!closed) throw new N3SyntaxError('Unterminated short string literal "..."', start);
|
|
1829
|
+
const rawContent = sChars === null ? sliceChars(contentStart, i - 1) : sChars.join('');
|
|
1830
|
+
const decoded = sChars === null ? rawContent : decodeN3StringEscapes(rawContent, start);
|
|
1831
|
+
if (sChars !== null || inputMayContainInvalidStringChar) assertValidStringLiteralValue(decoded, start);
|
|
1832
|
+
const s = JSON.stringify(decoded); // canonical short quoted form
|
|
1833
|
+
tokens.push(new Token('Literal', s, start));
|
|
1834
|
+
continue;
|
|
1835
|
+
}
|
|
1836
|
+
|
|
1837
|
+
// String literal: short '...' or long '''...'''
|
|
1838
|
+
if (c === "'") {
|
|
1839
|
+
const start = i;
|
|
1840
|
+
|
|
1841
|
+
// Long string literal ''' ... '''
|
|
1842
|
+
if (peek(1) === "'" && peek(2) === "'") {
|
|
1843
|
+
i += 3; // consume opening '''
|
|
1844
|
+
const sChars = [];
|
|
1845
|
+
let closed = false;
|
|
1846
|
+
while (i < n) {
|
|
1847
|
+
const cc = chars[i];
|
|
1848
|
+
|
|
1849
|
+
// Preserve escapes verbatim (same behavior as short strings)
|
|
1850
|
+
if (cc === '\\') {
|
|
1851
|
+
i++;
|
|
1852
|
+
if (i < n) {
|
|
1853
|
+
const esc = chars[i];
|
|
1854
|
+
i++;
|
|
1855
|
+
sChars.push('\\');
|
|
1856
|
+
sChars.push(esc);
|
|
1857
|
+
} else {
|
|
1858
|
+
sChars.push('\\');
|
|
1859
|
+
}
|
|
1860
|
+
continue;
|
|
1861
|
+
}
|
|
1862
|
+
|
|
1863
|
+
// In long strings, a run of >= 3 delimiter quotes terminates the literal.
|
|
1864
|
+
// Any extra quotes beyond the final 3 are part of the content.
|
|
1865
|
+
if (cc === "'") {
|
|
1866
|
+
let run = 0;
|
|
1867
|
+
while (i + run < n && chars[i + run] === "'") run++;
|
|
1868
|
+
|
|
1869
|
+
if (run >= 3) {
|
|
1870
|
+
for (let k = 0; k < run - 3; k++) sChars.push("'");
|
|
1871
|
+
i += run; // consume content quotes (if any) + closing delimiter
|
|
1872
|
+
closed = true;
|
|
1873
|
+
break;
|
|
1874
|
+
}
|
|
1875
|
+
|
|
1876
|
+
for (let k = 0; k < run; k++) sChars.push("'");
|
|
1877
|
+
i += run;
|
|
1878
|
+
continue;
|
|
1879
|
+
}
|
|
1880
|
+
|
|
1881
|
+
sChars.push(cc);
|
|
1882
|
+
i++;
|
|
1883
|
+
}
|
|
1884
|
+
if (!closed) throw new N3SyntaxError("Unterminated long string literal '''...'''", start);
|
|
1885
|
+
const raw = "'''" + sChars.join('') + "'''";
|
|
1886
|
+
const decoded = decodeN3StringEscapes(stripQuotes(raw), start);
|
|
1887
|
+
assertValidStringLiteralValue(decoded, start);
|
|
1888
|
+
const s = JSON.stringify(decoded); // canonical short quoted form
|
|
1889
|
+
tokens.push(new Token('Literal', s, start));
|
|
1890
|
+
continue;
|
|
1891
|
+
}
|
|
1892
|
+
|
|
1893
|
+
// Short string literal ' ... '
|
|
1894
|
+
i++; // consume opening '
|
|
1895
|
+
const contentStart = i;
|
|
1896
|
+
let sChars = null;
|
|
1897
|
+
let closed = false;
|
|
1898
|
+
while (i < n) {
|
|
1899
|
+
const cc = chars[i];
|
|
1900
|
+
i++;
|
|
1901
|
+
if (cc === '\\') {
|
|
1902
|
+
if (sChars === null) sChars = [sliceChars(contentStart, i - 1)];
|
|
1903
|
+
if (i < n) {
|
|
1904
|
+
const esc = chars[i];
|
|
1905
|
+
i++;
|
|
1906
|
+
sChars.push('\\');
|
|
1907
|
+
sChars.push(esc);
|
|
1908
|
+
} else {
|
|
1909
|
+
sChars.push('\\');
|
|
1910
|
+
}
|
|
1911
|
+
continue;
|
|
1912
|
+
}
|
|
1913
|
+
if (cc === '\n' || cc === '\r') {
|
|
1914
|
+
throw new N3SyntaxError('Unescaped newline in short string literal', start);
|
|
1915
|
+
}
|
|
1916
|
+
if (cc === "'") {
|
|
1917
|
+
closed = true;
|
|
1918
|
+
break;
|
|
1919
|
+
}
|
|
1920
|
+
if (sChars !== null) sChars.push(cc);
|
|
1921
|
+
}
|
|
1922
|
+
if (!closed) throw new N3SyntaxError("Unterminated short string literal '...'", start);
|
|
1923
|
+
const rawContent = sChars === null ? sliceChars(contentStart, i - 1) : sChars.join('');
|
|
1924
|
+
const decoded = sChars === null ? rawContent : decodeN3StringEscapes(rawContent, start);
|
|
1925
|
+
if (sChars !== null || inputMayContainInvalidStringChar) assertValidStringLiteralValue(decoded, start);
|
|
1926
|
+
const s = JSON.stringify(decoded); // canonical short quoted form
|
|
1927
|
+
tokens.push(new Token('Literal', s, start));
|
|
1928
|
+
continue;
|
|
1929
|
+
}
|
|
1930
|
+
|
|
1931
|
+
// Variable ?name
|
|
1932
|
+
if (c === '?') {
|
|
1933
|
+
const start = i;
|
|
1934
|
+
i++;
|
|
1935
|
+
const name = readIdentText(start);
|
|
1936
|
+
if (!name) {
|
|
1937
|
+
throw new N3SyntaxError("Expected variable name after '?'.", start);
|
|
1938
|
+
}
|
|
1939
|
+
tokens.push(new Token('Var', name, start));
|
|
1940
|
+
continue;
|
|
1941
|
+
}
|
|
1942
|
+
|
|
1943
|
+
// Directives: @prefix, @base (and language tags after string literals)
|
|
1944
|
+
if (c === '@') {
|
|
1945
|
+
const start = i;
|
|
1946
|
+
const prevTok = tokens.length ? tokens[tokens.length - 1] : null;
|
|
1947
|
+
const prevWasQuotedLiteral =
|
|
1948
|
+
prevTok && prevTok.typ === 'Literal' && typeof prevTok.value === 'string' && prevTok.value.startsWith('"');
|
|
1949
|
+
|
|
1950
|
+
i++; // consume '@'
|
|
1951
|
+
|
|
1952
|
+
if (prevWasQuotedLiteral) {
|
|
1953
|
+
// N3 grammar production LANGTAG:
|
|
1954
|
+
// "@" [a-zA-Z]+ ("-" [a-zA-Z0-9]+)*
|
|
1955
|
+
const tagChars = [];
|
|
1956
|
+
let cc = peek();
|
|
1957
|
+
if (cc === null || !isAsciiAlpha(cc)) {
|
|
1958
|
+
throw new N3SyntaxError("Invalid language tag (expected [A-Za-z] after '@')", start);
|
|
1959
|
+
}
|
|
1960
|
+
while ((cc = peek()) !== null && isAsciiAlpha(cc)) {
|
|
1961
|
+
tagChars.push(cc);
|
|
1962
|
+
i++;
|
|
1963
|
+
}
|
|
1964
|
+
while (peek() === '-') {
|
|
1965
|
+
if (peek(1) === '-') {
|
|
1966
|
+
const dir = sliceChars(i + 2, i + 5);
|
|
1967
|
+
const afterDir = peek(5);
|
|
1968
|
+
if ((dir === 'ltr' || dir === 'rtl') && (afterDir === null || !/[A-Za-z0-9-]/.test(afterDir))) {
|
|
1969
|
+
tagChars.push('--', dir);
|
|
1970
|
+
i += 5;
|
|
1971
|
+
break;
|
|
1972
|
+
}
|
|
1973
|
+
throw new N3SyntaxError('Invalid language direction (expected --ltr or --rtl)', start);
|
|
1974
|
+
}
|
|
1975
|
+
|
|
1976
|
+
tagChars.push('-');
|
|
1977
|
+
i++; // consume '-'
|
|
1978
|
+
const segChars = [];
|
|
1979
|
+
while ((cc = peek()) !== null && /[A-Za-z0-9]/.test(cc)) {
|
|
1980
|
+
segChars.push(cc);
|
|
1981
|
+
i++;
|
|
1982
|
+
}
|
|
1983
|
+
if (!segChars.length) {
|
|
1984
|
+
throw new N3SyntaxError("Invalid language tag (expected [A-Za-z0-9]+ after '-')", start);
|
|
1985
|
+
}
|
|
1986
|
+
tagChars.push(...segChars);
|
|
1987
|
+
}
|
|
1988
|
+
tokens.push(new Token('LangTag', tagChars.join(''), start));
|
|
1989
|
+
continue;
|
|
1990
|
+
}
|
|
1991
|
+
|
|
1992
|
+
// Otherwise, treat as a directive (@prefix, @base)
|
|
1993
|
+
const wordChars = [];
|
|
1994
|
+
let cc;
|
|
1995
|
+
while ((cc = peek()) !== null && isAsciiAlpha(cc)) {
|
|
1996
|
+
wordChars.push(cc);
|
|
1997
|
+
i++;
|
|
1998
|
+
}
|
|
1999
|
+
const word = wordChars.join('');
|
|
2000
|
+
if (word === 'prefix') tokens.push(new Token('AtPrefix', null, start));
|
|
2001
|
+
else if (word === 'base') tokens.push(new Token('AtBase', null, start));
|
|
2002
|
+
else throw new N3SyntaxError(`Unknown directive @${word}`, start);
|
|
2003
|
+
continue;
|
|
2004
|
+
}
|
|
2005
|
+
|
|
2006
|
+
// 7) Identifiers / keywords / QNames
|
|
2007
|
+
const start = i;
|
|
2008
|
+
const word = readIdentText(start);
|
|
2009
|
+
if (!word) {
|
|
2010
|
+
throw new N3SyntaxError(`Unexpected char: ${JSON.stringify(c)}`, i);
|
|
2011
|
+
}
|
|
2012
|
+
if (word === 'true' || word === 'false') {
|
|
2013
|
+
tokens.push(new Token('Literal', word, start));
|
|
2014
|
+
} else if (isNumericLikeIdentifier(word)) {
|
|
2015
|
+
tokens.push(new Token('Literal', word, start));
|
|
2016
|
+
} else {
|
|
2017
|
+
tokens.push(new Token('Ident', word, start));
|
|
2018
|
+
}
|
|
2019
|
+
}
|
|
2020
|
+
|
|
2021
|
+
tokens.push(new Token('EOF', null, n));
|
|
2022
|
+
return tokens;
|
|
2023
|
+
}
|
|
2024
|
+
|
|
2025
|
+
export { Token, N3SyntaxError, lex, normalizeRdfCompatibility, decodeN3StringEscapes };
|