eyemind 0.9.16 → 0.9.18

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/src/rdf-lexer.js CHANGED
@@ -340,25 +340,6 @@ function assertValidStringLiteralValue(s, offset = null) {
340
340
  }
341
341
  }
342
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
343
  // eyemind: RDF/TriG syntax is normalized to the parser's N3 representation:
363
344
  // - RDF 1.2 triple terms <<( s p o )>> become singleton graph terms { s p o }.
364
345
  // - TriG named graph blocks g { ... } become g log:nameOf { ... } .
@@ -366,26 +347,8 @@ function stripQuotes(lex) {
366
347
  // This keeps all downstream parsing/reasoning N3-only.
367
348
  const LOG_NAME_OF_IRI = '<http://www.w3.org/2000/10/swap/log#nameOf>';
368
349
  const RDF_REIFIES_IRI = '<http://www.w3.org/1999/02/22-rdf-syntax-ns#reifies>';
369
- const RDF_TYPE_IRI = '<http://www.w3.org/1999/02/22-rdf-syntax-ns#type>';
370
- const XSD_INTEGER_IRI = '<http://www.w3.org/2001/XMLSchema#integer>';
371
- const EYMSG_NS = 'https://eyereasoner.github.io/eyeling/vocab/message#';
372
- const EYMSG = Object.freeze({
373
- RDFMessageStream: `<${EYMSG_NS}RDFMessageStream>`,
374
- MessageEnvelope: `<${EYMSG_NS}MessageEnvelope>`,
375
- envelope: `<${EYMSG_NS}envelope>`,
376
- firstEnvelope: `<${EYMSG_NS}firstEnvelope>`,
377
- lastEnvelope: `<${EYMSG_NS}lastEnvelope>`,
378
- orderedEnvelopes: `<${EYMSG_NS}orderedEnvelopes>`,
379
- messageCount: `<${EYMSG_NS}messageCount>`,
380
- offset: `<${EYMSG_NS}offset>`,
381
- nextEnvelope: `<${EYMSG_NS}nextEnvelope>`,
382
- payloadGraph: `<${EYMSG_NS}payloadGraph>`,
383
- payloadKind: `<${EYMSG_NS}payloadKind>`,
384
- empty: `<${EYMSG_NS}empty>`,
385
- nonEmpty: `<${EYMSG_NS}nonEmpty>`,
386
- });
387
-
388
- function normalizeRdfCompatibility(inputText, { trig = false, messages = true } = {}) {
350
+
351
+ function normalizeRdfCompatibility(inputText, { trig = false } = {}) {
389
352
  let text = String(inputText ?? '');
390
353
 
391
354
  // eyemind: ordinary N3 input does not need RDF/TriG
@@ -394,11 +357,10 @@ function normalizeRdfCompatibility(inputText, { trig = false, messages = true }
394
357
  // plausible top-level TriG named graph block.
395
358
  const hasTripleTerms = text.includes('<<');
396
359
  const hasVersionDirective = /^\s*(?:@version|VERSION)\s+(["'])(?:1\.1|1\.2|1\.2-basic)\1\s*\.?\s*(?:#.*)?$/im.test(text);
397
- const hasMessageVersionDirective = messages && /^\s*(?:@version|VERSION)\s+(["'])(?:1\.1|1\.2|1\.2-basic)-messages\1\s*\.?\s*(?:#.*)?$/im.test(text);
398
360
  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);
399
361
  const hasAnnotationSyntax = /(?:^|\s)~|\{\|/.test(text);
400
362
 
401
- if (!trig && !hasTripleTerms && !hasVersionDirective && !hasMessageVersionDirective && !hasNamedGraphCandidate && !hasAnnotationSyntax) return text;
363
+ if (!trig && !hasTripleTerms && !hasVersionDirective && !hasNamedGraphCandidate && !hasAnnotationSyntax) return text;
402
364
 
403
365
  function isWordChar(ch) {
404
366
  return ch != null && /[A-Za-z0-9_:-]/.test(ch);
@@ -678,192 +640,6 @@ function normalizeRdfCompatibility(inputText, { trig = false, messages = true }
678
640
  }
679
641
 
680
642
 
681
- function convertAnnotations(s) {
682
- let out = '';
683
- let i = 0;
684
- let statementStart = true;
685
- let generatedBlank = 0;
686
-
687
- function readBalancedDelimited(s, at, open, close) {
688
- if (!s.startsWith(open, at)) return null;
689
- let j = at + open.length;
690
- let depth = 1;
691
- while (j < s.length) {
692
- const ch = s[j];
693
- if (ch === '"' || ch === "'") {
694
- j = readStringAt(s, j).end;
695
- continue;
696
- }
697
- if (ch === '<' && !s.startsWith('<<', j)) {
698
- j = readIriAt(s, j).end;
699
- continue;
700
- }
701
- if (ch === '#') {
702
- while (j < s.length && s[j] !== '\n' && s[j] !== '\r') j += 1;
703
- continue;
704
- }
705
- if (s.startsWith(open, j)) {
706
- depth += 1;
707
- j += open.length;
708
- continue;
709
- }
710
- if (s.startsWith(close, j)) {
711
- depth -= 1;
712
- j += close.length;
713
- if (depth === 0) return { text: s.slice(at, j), inner: s.slice(at + open.length, j - close.length), end: j };
714
- continue;
715
- }
716
- j += 1;
717
- }
718
- throw new N3SyntaxError(`Unterminated RDF annotation block, expected ${close}`);
719
- }
720
-
721
- function readTermLikeAt(s, at) {
722
- const j = skipWsAndComments(s, at);
723
- if (j >= s.length) return null;
724
- if (s[j] === '<') return readIriAt(s, j);
725
- if (s[j] === '"' || s[j] === "'") {
726
- const str = readStringAt(s, j);
727
- let end = str.end;
728
- let text = str.text;
729
- if (s.startsWith('^^', end)) {
730
- const dt = readTermAt(s, end + 2);
731
- if (dt) {
732
- text += '^^' + dt.text;
733
- end = dt.end;
734
- }
735
- } else if (s[end] === '@') {
736
- let k = end + 1;
737
- if (/[A-Za-z]/.test(s[k] || '')) {
738
- while (k < s.length && /[A-Za-z0-9-]/.test(s[k])) k += 1;
739
- text += s.slice(end, k);
740
- end = k;
741
- }
742
- }
743
- return { text, end };
744
- }
745
- if (s[j] === '{') return readBalancedBlock(s, j);
746
- if (s[j] === '[') return readBalancedDelimited(s, j, '[', ']');
747
- if (s[j] === '(') return readBalancedDelimited(s, j, '(', ')');
748
- return readTermAt(s, j);
749
- }
750
-
751
- function readAnnotationBlockAt(s, at) {
752
- if (!s.startsWith('{|', at)) return null;
753
- return readBalancedDelimited(s, at, '{|', '|}');
754
- }
755
-
756
- function tryReadAnnotatedTriple(at) {
757
- const start = skipWsAndComments(s, at);
758
- if (start >= s.length) return null;
759
- if (s[start] === '@') return null;
760
- if (startsWordAt(s, 'PREFIX', start) || startsWordAt(s, 'BASE', start) || startsWordAt(s, 'VERSION', start)) return null;
761
- if (startsWordAt(s, 'GRAPH', start)) return null;
762
-
763
- const subj = readTermLikeAt(s, start);
764
- if (!subj) return null;
765
- let j = skipWsAndComments(s, subj.end);
766
- const pred = readTermLikeAt(s, j);
767
- if (!pred) return null;
768
- j = skipWsAndComments(s, pred.end);
769
- const obj = readTermLikeAt(s, j);
770
- if (!obj) return null;
771
- j = skipWsAndComments(s, obj.end);
772
- if (s[j] !== '~' && !s.startsWith('{|', j)) return null;
773
-
774
- let reifier = '';
775
- const annotationBlocks = [];
776
- while (j < s.length) {
777
- j = skipWsAndComments(s, j);
778
- if (s[j] === '~') {
779
- j += 1;
780
- j = skipWsAndComments(s, j);
781
- const term = readTermAt(s, j);
782
- if (term) {
783
- reifier = term.text;
784
- j = term.end;
785
- } else if (!reifier) {
786
- reifier = `_:rdfAnnotation${++generatedBlank}`;
787
- }
788
- continue;
789
- }
790
- if (s.startsWith('{|', j)) {
791
- const block = readAnnotationBlockAt(s, j);
792
- const inner = block.inner.trim();
793
- if (!inner) throw new N3SyntaxError('Empty RDF annotation block is not allowed');
794
- if (!reifier) reifier = `_:rdfAnnotation${++generatedBlank}`;
795
- annotationBlocks.push(inner);
796
- j = block.end;
797
- continue;
798
- }
799
- break;
800
- }
801
-
802
- const after = skipWsAndComments(s, j);
803
- if (!['.', ';', ',', '}'].includes(s[after])) return null;
804
- if (!reifier && annotationBlocks.length === 0) return null;
805
-
806
- const baseTriple = `${subj.text} ${pred.text} ${obj.text}`;
807
- const graph = `{ ${baseTriple} }`;
808
- const extra = [];
809
- if (reifier) extra.push(`${reifier} ${RDF_REIFIES_IRI} ${graph} .`);
810
- for (const inner of annotationBlocks) {
811
- if (inner) extra.push(`${reifier} ${inner} .`);
812
- }
813
-
814
- let continuation = '';
815
- if (s[after] === ';') continuation = `\n${subj.text} `;
816
- else if (s[after] === ',') continuation = `\n${subj.text} ${pred.text} `;
817
-
818
- return {
819
- start,
820
- end: s[after] === '}' ? after : after + 1,
821
- text: `${baseTriple} .${extra.length ? '\n' + extra.join('\n') : ''}${continuation}`,
822
- };
823
- }
824
-
825
- while (i < s.length) {
826
- if (statementStart) {
827
- const converted = tryReadAnnotatedTriple(i);
828
- if (converted) {
829
- out += s.slice(i, converted.start) + converted.text;
830
- i = converted.end;
831
- statementStart = true;
832
- continue;
833
- }
834
- }
835
-
836
- const ch = s[i];
837
- if (ch === '"' || ch === "'") {
838
- const str = readStringAt(s, i);
839
- out += str.text;
840
- i = str.end;
841
- continue;
842
- }
843
- if (ch === '<' && !s.startsWith('<<', i)) {
844
- const iri = readIriAt(s, i);
845
- out += iri.text;
846
- i = iri.end;
847
- continue;
848
- }
849
- if (ch === '#') {
850
- while (i < s.length) {
851
- const c = s[i++];
852
- out += c;
853
- if (c === '\n' || c === '\r') break;
854
- }
855
- statementStart = true;
856
- continue;
857
- }
858
- out += ch;
859
- if (ch === '.' || ch === '{' || ch === '}' || ch === '\n' || ch === '\r') statementStart = true;
860
- else if (!/\s/.test(ch)) statementStart = false;
861
- i += 1;
862
- }
863
-
864
- return out;
865
- }
866
-
867
643
  function stripVersionDirectives(s) {
868
644
  // eyemind: a line in a long literal can look exactly like a directive.
869
645
  // Only strip tokens outside literals, IRIs and comments.
@@ -1145,11 +921,6 @@ function normalizeRdfCompatibility(inputText, { trig = false, messages = true }
1145
921
  }
1146
922
 
1147
923
 
1148
- function isOnlyWhitespaceAndComments(s) {
1149
- return skipWsAndComments(s, 0) >= s.length;
1150
- }
1151
-
1152
-
1153
924
  function skipOldStyleDirective(s, at) {
1154
925
  let i = at;
1155
926
  while (i < s.length) {
@@ -1172,242 +943,10 @@ function normalizeRdfCompatibility(inputText, { trig = false, messages = true }
1172
943
  return i;
1173
944
  }
1174
945
 
1175
- function stripDirectivesAndCommentsForEmptiness(s) {
1176
- let out = '';
1177
- let i = 0;
1178
- let statementStart = true;
1179
- while (i < s.length) {
1180
- const ch = s[i];
1181
- if (ch === '"' || ch === "'") {
1182
- const str = readStringAt(s, i);
1183
- out += str.text;
1184
- i = str.end;
1185
- statementStart = false;
1186
- continue;
1187
- }
1188
- if (ch === '<') {
1189
- const iri = readIriAt(s, i);
1190
- out += iri.text;
1191
- i = iri.end;
1192
- statementStart = false;
1193
- continue;
1194
- }
1195
- if (ch === '#') {
1196
- while (i < s.length && s[i] !== '\n' && s[i] !== '\r') i += 1;
1197
- statementStart = true;
1198
- continue;
1199
- }
1200
- if (statementStart) {
1201
- const start = skipWsAndComments(s, i);
1202
- out += s.slice(i, start);
1203
- i = start;
1204
- if (startsWordAt(s, 'PREFIX', i) || startsWordAt(s, 'BASE', i) || startsWordAt(s, 'VERSION', i)) {
1205
- while (i < s.length && s[i] !== '\n' && s[i] !== '\r') i += 1;
1206
- statementStart = true;
1207
- continue;
1208
- }
1209
- if (s[i] === '@') {
1210
- const lower = s.slice(i, i + 9).toLowerCase();
1211
- if (lower.startsWith('@prefix') || lower.startsWith('@base') || lower.startsWith('@version')) {
1212
- i = skipOldStyleDirective(s, i);
1213
- statementStart = true;
1214
- continue;
1215
- }
1216
- }
1217
- }
1218
- out += ch;
1219
- if (ch === '.' || ch === '}' || ch === '\n' || ch === '\r') statementStart = true;
1220
- else if (!/\s/.test(ch)) statementStart = false;
1221
- i += 1;
1222
- }
1223
- return out;
1224
- }
1225
-
1226
- function simpleHashText(s) {
1227
- let h = 0x811c9dc5;
1228
- for (let i = 0; i < s.length; i += 1) {
1229
- h ^= s.charCodeAt(i);
1230
- h = Math.imul(h, 0x01000193) >>> 0;
1231
- }
1232
- return h.toString(16).padStart(8, '0');
1233
- }
1234
-
1235
- function rewriteMessageBlankLabels(s, messageIndex) {
1236
- let out = '';
1237
- let i = 0;
1238
- const prefix = `_:eyeling_m${String(messageIndex).padStart(3, '0')}_`;
1239
- while (i < s.length) {
1240
- const ch = s[i];
1241
- if (ch === '"' || ch === "'") {
1242
- const str = readStringAt(s, i);
1243
- out += str.text;
1244
- i = str.end;
1245
- continue;
1246
- }
1247
- if (ch === '<' && !s.startsWith('<<', i)) {
1248
- const iri = readIriAt(s, i);
1249
- out += iri.text;
1250
- i = iri.end;
1251
- continue;
1252
- }
1253
- if (ch === '#') {
1254
- while (i < s.length) {
1255
- const c = s[i++];
1256
- out += c;
1257
- if (c === '\n' || c === '\r') break;
1258
- }
1259
- continue;
1260
- }
1261
- if (s.startsWith('_:', i)) {
1262
- let j = i + 2;
1263
- while (j < s.length && !/\s/.test(s[j]) && !'{}[](),;.'.includes(s[j])) j += 1;
1264
- const label = s.slice(i + 2, j);
1265
- if (label) {
1266
- out += prefix + label.replace(/[^A-Za-z0-9_]/g, '_');
1267
- i = j;
1268
- continue;
1269
- }
1270
- }
1271
- out += ch;
1272
- i += 1;
1273
- }
1274
- return out;
1275
- }
1276
-
1277
- function findMessageDirectiveAt(s, at) {
1278
- if (startsWordAt(s, 'MESSAGE', at)) return { start: at, end: at + 'MESSAGE'.length };
1279
- if (s.slice(at, at + 8).toLowerCase() === '@message' && !isWordChar(s[at + 8])) {
1280
- let end = at + 8;
1281
- end = skipWsAndComments(s, end);
1282
- if (s[end] === '.') end += 1;
1283
- return { start: at, end };
1284
- }
1285
- return null;
1286
- }
1287
-
1288
- function splitRdfMessageLog(s) {
1289
- const chunks = [];
1290
- let i = 0;
1291
- let start = 0;
1292
- let braceDepth = 0;
1293
- let bracketDepth = 0;
1294
- let parenDepth = 0;
1295
- let statementStart = true;
1296
- let sawDelimiter = false;
1297
-
1298
- while (i < s.length) {
1299
- const ch = s[i];
1300
- if (ch === '"' || ch === "'") {
1301
- i = readStringAt(s, i).end;
1302
- statementStart = false;
1303
- continue;
1304
- }
1305
- if (ch === '<' && !s.startsWith('<<', i)) {
1306
- i = readIriAt(s, i).end;
1307
- statementStart = false;
1308
- continue;
1309
- }
1310
- if (ch === '#') {
1311
- while (i < s.length && s[i] !== '\n' && s[i] !== '\r') i += 1;
1312
- statementStart = true;
1313
- continue;
1314
- }
1315
- if (statementStart && braceDepth === 0 && bracketDepth === 0 && parenDepth === 0) {
1316
- const termStart = skipWsAndComments(s, i);
1317
- const msg = findMessageDirectiveAt(s, termStart);
1318
- if (msg) {
1319
- chunks.push(s.slice(start, termStart));
1320
- start = msg.end;
1321
- i = msg.end;
1322
- statementStart = true;
1323
- sawDelimiter = true;
1324
- continue;
1325
- }
1326
- if (termStart !== i) {
1327
- i = termStart;
1328
- continue;
1329
- }
1330
- }
1331
- if (ch === '{') braceDepth += 1;
1332
- else if (ch === '}' && braceDepth > 0) braceDepth -= 1;
1333
- else if (ch === '[') bracketDepth += 1;
1334
- else if (ch === ']' && bracketDepth > 0) bracketDepth -= 1;
1335
- else if (ch === '(') parenDepth += 1;
1336
- else if (ch === ')' && parenDepth > 0) parenDepth -= 1;
1337
-
1338
- if (ch === '.' && braceDepth === 0 && bracketDepth === 0 && parenDepth === 0) statementStart = true;
1339
- else if (ch === '\n' || ch === '\r') statementStart = true;
1340
- else if (!/\s/.test(ch)) statementStart = false;
1341
- i += 1;
1342
- }
1343
-
1344
- const tail = s.slice(start);
1345
- if (!sawDelimiter || !isOnlyWhitespaceAndComments(tail)) chunks.push(tail);
1346
- return chunks;
1347
- }
1348
-
1349
- function normalizeMessageChunk(chunk, messageIndex) {
1350
- let body = String(chunk || '');
1351
- if (hasTripleTerms || body.includes('<<')) body = convertTripleTerms(body);
1352
- if (hasAnnotationSyntax || /(?:^|\s)~|\{\|/.test(body)) {
1353
- // eyemind: annotations are read by the parser.
1354
- }
1355
- body = normalizeNamedGraphs(body);
1356
- body = rewriteMessageBlankLabels(body, messageIndex);
1357
- return body.trim();
1358
- }
1359
-
1360
- function messageChunkHasRdf(body) {
1361
- return !isOnlyWhitespaceAndComments(stripDirectivesAndCommentsForEmptiness(body));
1362
- }
1363
-
1364
- function normalizeRdfMessageLog(s) {
1365
- const withoutVersion = stripVersionDirectives(s);
1366
- const chunks = splitRdfMessageLog(withoutVersion);
1367
- const hash = simpleHashText(s);
1368
- const base = `urn:eyeling:message-log:${hash}`;
1369
- const stream = `<${base}#stream>`;
1370
- const envelopeIris = chunks.map((unused, idx) => `<${base}#m${String(idx + 1).padStart(3, '0')}>`);
1371
- const payloadIris = chunks.map((unused, idx) => `<${base}#m${String(idx + 1).padStart(3, '0')}/payload>`);
1372
- const out = [];
1373
-
1374
- out.push(`${stream} ${RDF_TYPE_IRI} ${EYMSG.RDFMessageStream} .`);
1375
- out.push(`${stream} ${EYMSG.messageCount} "${chunks.length}"^^${XSD_INTEGER_IRI} .`);
1376
- if (envelopeIris.length) {
1377
- out.push(`${stream} ${EYMSG.orderedEnvelopes} (${envelopeIris.join(' ')}) .`);
1378
- out.push(`${stream} ${EYMSG.firstEnvelope} ${envelopeIris[0]} .`);
1379
- out.push(`${stream} ${EYMSG.lastEnvelope} ${envelopeIris[envelopeIris.length - 1]} .`);
1380
- }
1381
-
1382
- for (let idx = 0; idx < chunks.length; idx += 1) {
1383
- const n = idx + 1;
1384
- const envelope = envelopeIris[idx];
1385
- const payload = payloadIris[idx];
1386
- const body = normalizeMessageChunk(chunks[idx], n);
1387
- const hasBody = messageChunkHasRdf(body);
1388
-
1389
- out.push(`${stream} ${EYMSG.envelope} ${envelope} .`);
1390
- out.push(`${envelope} ${RDF_TYPE_IRI} ${EYMSG.MessageEnvelope} .`);
1391
- out.push(`${envelope} ${EYMSG.offset} "${n}"^^${XSD_INTEGER_IRI} .`);
1392
- out.push(`${envelope} ${EYMSG.payloadKind} ${hasBody ? EYMSG.nonEmpty : EYMSG.empty} .`);
1393
- if (idx + 1 < envelopeIris.length) out.push(`${envelope} ${EYMSG.nextEnvelope} ${envelopeIris[idx + 1]} .`);
1394
- if (hasBody) {
1395
- out.push(`${envelope} ${EYMSG.payloadGraph} ${payload} .`);
1396
- out.push(`${payload} ${LOG_NAME_OF_IRI} {`);
1397
- out.push(body);
1398
- out.push(`} .`);
1399
- }
1400
- }
1401
-
1402
- return out.join('\n') + '\n';
1403
- }
1404
-
1405
- if (hasMessageVersionDirective) return normalizeRdfMessageLog(text);
1406
-
1407
946
  if (hasTripleTerms) text = convertTripleTerms(text);
1408
947
  // eyemind: annotations are read by the parser, after their triple.
1409
- if (hasVersionDirective || hasMessageVersionDirective) text = stripVersionDirectives(text);
1410
- if (trig || hasVersionDirective || hasMessageVersionDirective || hasNamedGraphCandidate) text = normalizeNamedGraphs(text);
948
+ if (hasVersionDirective) text = stripVersionDirectives(text);
949
+ if (trig || hasVersionDirective || hasNamedGraphCandidate) text = normalizeNamedGraphs(text);
1411
950
  return text;
1412
951
  }
1413
952
 
@@ -1422,8 +961,7 @@ function isNumericLikeIdentifier(word) {
1422
961
  }
1423
962
 
1424
963
  function lex(inputText, opts = {}) {
1425
- const rdf = !!(opts && opts.rdf);
1426
- if (rdf) inputText = normalizeRdfCompatibility(inputText, { trig: !!opts.trig, messages: opts.messages !== false });
964
+ inputText = normalizeRdfCompatibility(inputText, { trig: !!opts.trig });
1427
965
  // Avoid copying large ASCII/BMP inputs into an Array. Array.from() is
1428
966
  // only needed when the text contains surrogate pairs and we want the old
1429
967
  // code-point iteration behavior for non-BMP characters.
@@ -1468,7 +1006,7 @@ function lex(inputText, opts = {}) {
1468
1006
 
1469
1007
  // eyemind: in RDF a blank node label has no colon after its _: prefix,
1470
1008
  // so _:s:p is _:s followed by :p.
1471
- if (rdf && code === 58 && i > start + 1 && chars[start] === '_' && chars[start + 1] === ':') break;
1009
+ if (code === 58 && i > start + 1 && chars[start] === '_' && chars[start + 1] === ':') break;
1472
1010
 
1473
1011
  // Common ASCII QName/identifier characters. Keep this branch inline so
1474
1012
  // ordinary N3 files do not call through the full Unicode PN_CHARS predicate
@@ -1570,50 +1108,23 @@ function lex(inputText, opts = {}) {
1570
1108
  continue;
1571
1109
  }
1572
1110
 
1573
- // 3) Two-character operators: => and <=
1574
- if (c === '=') {
1575
- if (peek(1) === '>') {
1576
- tokens.push(new Token('OpImplies', null, i));
1577
- i += 2;
1578
- continue;
1579
- } else {
1580
- // N3 syntactic sugar: '=' means owl:sameAs
1581
- tokens.push(new Token('Equals', null, i));
1582
- i += 1;
1583
- continue;
1584
- }
1585
- }
1586
-
1587
1111
  // eyemind: RDF 1.2 reified triples << ... >>, reifiers ~ and annotation
1588
- // blocks {| ... |} are tokens the parser reads in RDF mode.
1589
- if (rdf) {
1590
- const two = c + (peek(1) ?? '');
1591
- const kind = { '<<': 'LtLt', '>>': 'GtGt', '{|': 'AnnotOpen', '|}': 'AnnotClose' }[two];
1592
- if (kind) {
1593
- tokens.push(new Token(kind, null, i));
1594
- i += 2;
1595
- continue;
1596
- }
1597
- if (c === '~') {
1598
- tokens.push(new Token('Tilde', null, i));
1599
- i += 1;
1600
- continue;
1601
- }
1112
+ // blocks {| ... |} are tokens of their own.
1113
+ const two = c + (peek(1) ?? '');
1114
+ const kind = { '<<': 'LtLt', '>>': 'GtGt', '{|': 'AnnotOpen', '|}': 'AnnotClose' }[two];
1115
+ if (kind) {
1116
+ tokens.push(new Token(kind, null, i));
1117
+ i += 2;
1118
+ continue;
1119
+ }
1120
+ if (c === '~') {
1121
+ tokens.push(new Token('Tilde', null, i));
1122
+ i += 1;
1123
+ continue;
1602
1124
  }
1603
1125
 
1126
+ // IRIREF <...>
1604
1127
  if (c === '<') {
1605
- if (peek(1) === '=') {
1606
- tokens.push(new Token('OpImpliedBy', null, i));
1607
- i += 2;
1608
- continue;
1609
- }
1610
- // N3 predicate inversion: "<-" (swap subject/object for this predicate)
1611
- if (peek(1) === '-') {
1612
- tokens.push(new Token('OpPredInvert', null, i));
1613
- i += 2;
1614
- continue;
1615
- }
1616
- // Otherwise IRIREF <...>
1617
1128
  const start = i;
1618
1129
  i++; // skip '<'
1619
1130
  const iriChars = [];
@@ -1630,20 +1141,10 @@ function lex(inputText, opts = {}) {
1630
1141
  continue;
1631
1142
  }
1632
1143
 
1633
- // 4) Path + datatype operators: !, ^, ^^
1634
- if (c === '!') {
1635
- tokens.push(new Token('OpPathFwd', null, i));
1636
- i += 1;
1637
- continue;
1638
- }
1639
- if (c === '^') {
1640
- if (peek(1) === '^') {
1641
- tokens.push(new Token('HatHat', null, i));
1642
- i += 2;
1643
- continue;
1644
- }
1645
- tokens.push(new Token('OpPathRev', null, i));
1646
- i += 1;
1144
+ // The datatype operator ^^
1145
+ if (c === '^' && peek(1) === '^') {
1146
+ tokens.push(new Token('HatHat', null, i));
1147
+ i += 2;
1647
1148
  continue;
1648
1149
  }
1649
1150
 
@@ -1768,13 +1269,14 @@ function lex(inputText, opts = {}) {
1768
1269
  break;
1769
1270
  }
1770
1271
 
1771
- // String literal: short "..." or long """..."""
1772
- if (c === '"') {
1272
+ // String literal: short "..." or '...', long """...""" or '''...'''
1273
+ if (c === '"' || c === "'") {
1773
1274
  const start = i;
1275
+ const quote = c;
1774
1276
 
1775
- // Long string literal """ ... """
1776
- if (peek(1) === '"' && peek(2) === '"') {
1777
- i += 3; // consume opening """
1277
+ // Long string literal
1278
+ if (peek(1) === quote && peek(2) === quote) {
1279
+ i += 3; // consume opening delimiter
1778
1280
  const sChars = [];
1779
1281
  let closed = false;
1780
1282
  while (i < n) {
@@ -1796,18 +1298,18 @@ function lex(inputText, opts = {}) {
1796
1298
 
1797
1299
  // In long strings, a run of >= 3 delimiter quotes terminates the literal.
1798
1300
  // Any extra quotes beyond the final 3 are part of the content.
1799
- if (cc === '"') {
1301
+ if (cc === quote) {
1800
1302
  let run = 0;
1801
- while (i + run < n && chars[i + run] === '"') run++;
1303
+ while (i + run < n && chars[i + run] === quote) run++;
1802
1304
 
1803
1305
  if (run >= 3) {
1804
- for (let k = 0; k < run - 3; k++) sChars.push('"');
1306
+ for (let k = 0; k < run - 3; k++) sChars.push(quote);
1805
1307
  i += run; // consume content quotes (if any) + closing delimiter
1806
1308
  closed = true;
1807
1309
  break;
1808
1310
  }
1809
1311
 
1810
- for (let k = 0; k < run; k++) sChars.push('"');
1312
+ for (let k = 0; k < run; k++) sChars.push(quote);
1811
1313
  i += run;
1812
1314
  continue;
1813
1315
  }
@@ -1815,113 +1317,18 @@ function lex(inputText, opts = {}) {
1815
1317
  sChars.push(cc);
1816
1318
  i++;
1817
1319
  }
1818
- if (!closed) throw new N3SyntaxError('Unterminated long string literal """..."""', start);
1819
- const raw = '"""' + sChars.join('') + '"""';
1820
- const decoded = decodeN3StringEscapes(stripQuotes(raw), start);
1320
+ if (!closed) throw new N3SyntaxError(`Unterminated long string literal ${quote.repeat(3)}...${quote.repeat(3)}`, start);
1321
+ const decoded = decodeN3StringEscapes(sChars.join(''), start);
1821
1322
  assertValidStringLiteralValue(decoded, start);
1822
1323
  const s = JSON.stringify(decoded); // canonical short quoted form
1823
1324
  tokens.push(new Token('Literal', s, start));
1824
1325
  continue;
1825
1326
  }
1826
1327
 
1827
- // Short string literal " ... ". Most data files contain plain
1328
+ // Short string literal. Most data files contain plain
1828
1329
  // unescaped labels; keep that path slice-based and avoid building an
1829
1330
  // intermediate character array + raw quoted string.
1830
- i++; // consume opening "
1831
- const contentStart = i;
1832
- let sChars = null;
1833
- let closed = false;
1834
- while (i < n) {
1835
- const cc = chars[i];
1836
- i++;
1837
- if (cc === '\\') {
1838
- if (sChars === null) sChars = [sliceChars(contentStart, i - 1)];
1839
- if (i < n) {
1840
- const esc = chars[i];
1841
- i++;
1842
- sChars.push('\\');
1843
- sChars.push(esc);
1844
- } else {
1845
- sChars.push('\\');
1846
- }
1847
- continue;
1848
- }
1849
- if (cc === '\n' || cc === '\r') {
1850
- throw new N3SyntaxError('Unescaped newline in short string literal', start);
1851
- }
1852
- if (cc === '"') {
1853
- closed = true;
1854
- break;
1855
- }
1856
- if (sChars !== null) sChars.push(cc);
1857
- }
1858
- if (!closed) throw new N3SyntaxError('Unterminated short string literal "..."', start);
1859
- const rawContent = sChars === null ? sliceChars(contentStart, i - 1) : sChars.join('');
1860
- const decoded = sChars === null ? rawContent : decodeN3StringEscapes(rawContent, start);
1861
- if (sChars !== null || inputMayContainInvalidStringChar) assertValidStringLiteralValue(decoded, start);
1862
- const s = JSON.stringify(decoded); // canonical short quoted form
1863
- tokens.push(new Token('Literal', s, start));
1864
- continue;
1865
- }
1866
-
1867
- // String literal: short '...' or long '''...'''
1868
- if (c === "'") {
1869
- const start = i;
1870
-
1871
- // Long string literal ''' ... '''
1872
- if (peek(1) === "'" && peek(2) === "'") {
1873
- i += 3; // consume opening '''
1874
- const sChars = [];
1875
- let closed = false;
1876
- while (i < n) {
1877
- const cc = chars[i];
1878
-
1879
- // Preserve escapes verbatim (same behavior as short strings)
1880
- if (cc === '\\') {
1881
- i++;
1882
- if (i < n) {
1883
- const esc = chars[i];
1884
- i++;
1885
- sChars.push('\\');
1886
- sChars.push(esc);
1887
- } else {
1888
- sChars.push('\\');
1889
- }
1890
- continue;
1891
- }
1892
-
1893
- // In long strings, a run of >= 3 delimiter quotes terminates the literal.
1894
- // Any extra quotes beyond the final 3 are part of the content.
1895
- if (cc === "'") {
1896
- let run = 0;
1897
- while (i + run < n && chars[i + run] === "'") run++;
1898
-
1899
- if (run >= 3) {
1900
- for (let k = 0; k < run - 3; k++) sChars.push("'");
1901
- i += run; // consume content quotes (if any) + closing delimiter
1902
- closed = true;
1903
- break;
1904
- }
1905
-
1906
- for (let k = 0; k < run; k++) sChars.push("'");
1907
- i += run;
1908
- continue;
1909
- }
1910
-
1911
- sChars.push(cc);
1912
- i++;
1913
- }
1914
- if (!closed) throw new N3SyntaxError("Unterminated long string literal '''...'''", start);
1915
- const raw = "'''" + sChars.join('') + "'''";
1916
- const decoded = decodeN3StringEscapes(stripQuotes(raw), start);
1917
- assertValidStringLiteralValue(decoded, start);
1918
- const s = JSON.stringify(decoded); // canonical short quoted form
1919
- tokens.push(new Token('Literal', s, start));
1920
- continue;
1921
- }
1922
-
1923
- // Short string literal ' ... '
1924
- i++; // consume opening '
1331
+ i++; // consume opening quote
1925
1332
  const contentStart = i;
1926
1333
  let sChars = null;
1927
1334
  let closed = false;
@@ -1943,13 +1350,13 @@ function lex(inputText, opts = {}) {
1943
1350
  if (cc === '\n' || cc === '\r') {
1944
1351
  throw new N3SyntaxError('Unescaped newline in short string literal', start);
1945
1352
  }
1946
- if (cc === "'") {
1353
+ if (cc === quote) {
1947
1354
  closed = true;
1948
1355
  break;
1949
1356
  }
1950
1357
  if (sChars !== null) sChars.push(cc);
1951
1358
  }
1952
- if (!closed) throw new N3SyntaxError("Unterminated short string literal '...'", start);
1359
+ if (!closed) throw new N3SyntaxError(`Unterminated short string literal ${quote}...${quote}`, start);
1953
1360
  const rawContent = sChars === null ? sliceChars(contentStart, i - 1) : sChars.join('');
1954
1361
  const decoded = sChars === null ? rawContent : decodeN3StringEscapes(rawContent, start);
1955
1362
  if (sChars !== null || inputMayContainInvalidStringChar) assertValidStringLiteralValue(decoded, start);
@@ -1958,18 +1365,6 @@ function lex(inputText, opts = {}) {
1958
1365
  continue;
1959
1366
  }
1960
1367
 
1961
- // Variable ?name
1962
- if (c === '?') {
1963
- const start = i;
1964
- i++;
1965
- const name = readIdentText(start);
1966
- if (!name) {
1967
- throw new N3SyntaxError("Expected variable name after '?'.", start);
1968
- }
1969
- tokens.push(new Token('Var', name, start));
1970
- continue;
1971
- }
1972
-
1973
1368
  // Directives: @prefix, @base (and language tags after string literals)
1974
1369
  if (c === '@') {
1975
1370
  const start = i;