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/src/rdf.js ADDED
@@ -0,0 +1,429 @@
1
+ // RDF 1.2 in and out of eyemind: Turtle, TriG, N-Triples and N-Quads.
2
+ //
3
+ // Documents are read by eyeling's lexer and parser (rdf-lexer.js,
4
+ // rdf-parser.js, rdf-prelude.js and rdf-rules.js) in its RDF mode, with the
5
+ // surface checks eyeling applies for RDF 1.2 below. Each quad becomes the
6
+ // eyemind term rdf(Subject, Predicate, Object, Graph):
7
+ //
8
+ // IRI iri('https://example.org/a')
9
+ // blank node bnode(Scope, Label), Scope naming the document
10
+ // canonical xsd:integer an integer, exact at any size
11
+ // other literal literal(Lexical, datatype(IRI))
12
+ // language string literal(Text, lang(Tag)), or lang(Tag, Direction)
13
+ // triple term triple(S, P, O)
14
+ // default graph, named graph 'default_graph', the graph's IRI or blank node
15
+ //
16
+ // Writing goes the other way; a Skolem term is a blank node, the same one for
17
+ // the same rule firing.
18
+ import { lex } from './rdf-lexer.js';
19
+ import { checkRdfSyntax } from './rdf-syntax.js';
20
+ import { Parser } from './rdf-parser.js';
21
+ import { Blank, GraphTerm, Iri, ListTerm, Literal, LOG_NS, RDF_NS, literalParts } from './rdf-prelude.js';
22
+ import { EyemindError, Struct } from './terms.js';
23
+ import { write } from './writer.js';
24
+
25
+ const XSD = 'http://www.w3.org/2001/XMLSchema#';
26
+ const RDF_TYPE = `${RDF_NS}type`;
27
+ export const DEFAULT_GRAPH = 'default_graph';
28
+
29
+ const FORMATS = { ttl: 'turtle', turtle: 'turtle', trig: 'trig', nt: 'n-triples', ntriples: 'n-triples', nq: 'n-quads', nquads: 'n-quads' };
30
+
31
+ // The RDF format a file name names by its extension, or null.
32
+ export function rdfFormat(name) {
33
+ const m = /\.([A-Za-z]+)$/.exec(String(name));
34
+ return m ? FORMATS[m[1].toLowerCase()] ?? null : null;
35
+ }
36
+
37
+ const st = (name, ...args) => new Struct(name, args);
38
+ const iri = (v) => st('iri', v);
39
+
40
+ // Read an RDF document. Options: format ('turtle', 'trig', 'n-triples' or
41
+ // 'n-quads'), base (IRI) and scope (for blank nodes). Returns { quads,
42
+ // prefixes }: quads are [S, P, O, G] eyemind terms, prefixes maps names to
43
+ // namespaces.
44
+ export function parseRdf(text, { format = 'turtle', base = null, scope = 'rdf' } = {}) {
45
+ text = String(text);
46
+ try {
47
+ checkRdfSyntax(text, format);
48
+ assertRdf12SurfaceSyntax(text, format);
49
+ const parser = new Parser(lex(text, { rdf: true, trig: format === 'trig' }));
50
+ // RDF declares every prefix it uses; N3's predeclared ones do not apply.
51
+ parser.prefixes.map = {};
52
+ if (base) parser.prefixes.setBase(base);
53
+ const state = { scope, lists: 0, out: [] };
54
+ if (format === 'n-quads') {
55
+ while (parser.peek().typ !== 'EOF') {
56
+ if (parser.parseDirectiveIfPresent({ allowIdentBaseIri: true })) continue;
57
+ const s = parser.parseTerm();
58
+ const p = parser.parseTerm();
59
+ const o = parser.parseTerm();
60
+ const g = parser.peek().typ === 'Dot' ? DEFAULT_GRAPH : convert(parser.parseTerm(), 'graph', DEFAULT_GRAPH, state);
61
+ parser.expectDot();
62
+ quad(s, p, o, g, state);
63
+ }
64
+ } else {
65
+ const [, triples, forward, backward, queries] = parser.parseDocument();
66
+ if (forward.length || backward.length || queries.length) throw new SyntaxError('an RDF document has no rules');
67
+ for (const t of triples) {
68
+ if (format === 'trig' && t.p instanceof Iri && t.p.value === `${LOG_NS}nameOf` && t.o instanceof GraphTerm) {
69
+ const g = convert(t.s, 'graph', DEFAULT_GRAPH, state);
70
+ for (const inner of t.o.triples) quad(inner.s, inner.p, inner.o, g, state);
71
+ } else quad(t.s, t.p, t.o, DEFAULT_GRAPH, state);
72
+ }
73
+ }
74
+ if (format !== 'trig' && format !== 'n-quads' && state.out.some((q) => q[3] !== DEFAULT_GRAPH)) {
75
+ throw new SyntaxError(`${format} has no named graphs`);
76
+ }
77
+ return { quads: state.out, prefixes: prefixesOf(parser.prefixes) };
78
+ } catch (error) {
79
+ if (error instanceof EyemindError) throw error;
80
+ throw new EyemindError(`${format}: ${error.message}`);
81
+ }
82
+ }
83
+
84
+ function prefixesOf(env) {
85
+ const out = {};
86
+ for (const [name, ns] of Object.entries(env.map ?? {})) if (typeof ns === 'string' && ns !== '') out[name] = ns;
87
+ return out;
88
+ }
89
+
90
+ function quad(s, p, o, g, state) {
91
+ const S = convert(s, 'subject', g, state);
92
+ const P = convert(p, 'predicate', g, state);
93
+ const O = convert(o, 'object', g, state);
94
+ if (!(S instanceof Struct && ['iri', 'bnode', 'triple'].includes(S.name))) throw new SyntaxError('an RDF subject is an IRI, a blank node or a triple term');
95
+ if (!(P instanceof Struct && P.name === 'iri')) throw new SyntaxError('an RDF predicate is an IRI');
96
+ state.out.push([S, P, O, g]);
97
+ }
98
+
99
+ function convert(term, position, graph, state, list = true) {
100
+ if (term instanceof Iri) return iri(term.value);
101
+ if (term instanceof Blank) return st('bnode', state.scope, String(term.label).replace(/^_:/, ''));
102
+ if (term instanceof Literal) {
103
+ if (position !== 'object') throw new SyntaxError(`a literal cannot be an RDF ${position}`);
104
+ return literalTerm(term.value);
105
+ }
106
+ if (term instanceof GraphTerm) {
107
+ // In RDF mode a quoted graph of one triple is a triple term.
108
+ if (position === 'predicate' || position === 'graph' || term.triples.length !== 1) {
109
+ throw new SyntaxError(`a quoted graph cannot be an RDF ${position}`);
110
+ }
111
+ const t = term.triples[0];
112
+ const p = convert(t.p, 'predicate', graph, state, false);
113
+ if (p.name !== 'iri') throw new SyntaxError('the predicate of a triple term is an IRI');
114
+ return st('triple', convert(t.s, 'subject', graph, state, false), p, convert(t.o, 'object', graph, state, false));
115
+ }
116
+ if (term instanceof ListTerm && list) {
117
+ if (term.elems.length === 0) return iri(`${RDF_NS}nil`);
118
+ const nodes = term.elems.map(() => st('bnode', state.scope, `list${++state.lists}`));
119
+ term.elems.forEach((elem, i) => {
120
+ const value = convert(elem, 'object', graph, state);
121
+ state.out.push([nodes[i], iri(`${RDF_NS}first`), value, graph]);
122
+ state.out.push([nodes[i], iri(`${RDF_NS}rest`), i + 1 < nodes.length ? nodes[i + 1] : iri(`${RDF_NS}nil`), graph]);
123
+ });
124
+ return nodes[0];
125
+ }
126
+ throw new SyntaxError(`${term?.constructor?.name ?? typeof term} is no RDF term`);
127
+ }
128
+
129
+ // A literal of eyeling's parser: its raw form is a quoted lexical form with a
130
+ // language tag or datatype, or a bare number or boolean.
131
+ function literalTerm(raw) {
132
+ const text = String(raw);
133
+ const tagged = /^(".*")@([A-Za-z]+(?:-[A-Za-z0-9]+)*)(?:--(ltr|rtl))?$/s.exec(text);
134
+ if (tagged) {
135
+ const lang = tagged[2].toLowerCase();
136
+ return st('literal', unquote(tagged[1]), tagged[3] ? st('lang', lang, tagged[3]) : st('lang', lang));
137
+ }
138
+ const [lexical, datatype] = literalParts(text);
139
+ const quoted = typeof lexical === 'string' && lexical.length >= 2 && lexical[0] === '"' && lexical.at(-1) === '"';
140
+ const value = quoted ? unquote(lexical) : lexical;
141
+ return literalOf(value, datatype ?? (quoted ? `${XSD}string` : bareDatatype(value)));
142
+ }
143
+
144
+ function unquote(lexical) {
145
+ try {
146
+ return JSON.parse(lexical);
147
+ } catch {
148
+ return lexical.slice(1, -1);
149
+ }
150
+ }
151
+
152
+ function bareDatatype(value) {
153
+ if (value === 'true' || value === 'false') return `${XSD}boolean`;
154
+ if (/^[+-]?[0-9]+$/.test(value)) return `${XSD}integer`;
155
+ if (/^[+-]?(?:[0-9]*\.[0-9]+|[0-9]+\.)$/.test(value)) return `${XSD}decimal`;
156
+ return `${XSD}double`;
157
+ }
158
+
159
+ // A literal term: a canonical xsd:integer is an integer, any other literal
160
+ // keeps its lexical form and datatype.
161
+ export function literalOf(lexical, datatype) {
162
+ if (datatype === `${XSD}integer` && /^(?:0|-?[1-9][0-9]*)$/.test(lexical)) return BigInt(lexical);
163
+ return st('literal', lexical, st('datatype', datatype));
164
+ }
165
+
166
+ // The quads of a document as eyemind document text, one rdf/4 term a line,
167
+ // for facts_from.
168
+ export function rdfDocument(quads, name = 'rdf') {
169
+ return quads.map(([s, p, o, g]) => write(st(name, s, p, o, g))).join('\n');
170
+ }
171
+
172
+ // eyeling's RDF 1.2 surface checks, which its parser leaves to a separate
173
+ // pass: escaped surrogates, triple terms as subjects, and the stricter line
174
+ // syntax of N-Triples and N-Quads.
175
+ function assertRdf12SurfaceSyntax(text, format) {
176
+ if (/\\u[dD][89a-fA-F][0-9a-fA-F]{2}/.test(text)) {
177
+ throw new SyntaxError('RDF 1.2 numeric escape sequences must not encode UTF-16 surrogate code points');
178
+ }
179
+ assertNoParenthesizedTripleTermSubject(text);
180
+ if (format === 'n-triples' || format === 'n-quads') assertLineSyntax(text);
181
+ }
182
+
183
+ function readStringAt(s, at) {
184
+ const quote = s[at];
185
+ let i = at;
186
+ const long = s.startsWith(quote.repeat(3), i);
187
+ i += long ? 3 : 1;
188
+ while (i < s.length) {
189
+ if (long && s.startsWith(quote.repeat(3), i)) return i + 3;
190
+ const ch = s[i++];
191
+ if (ch === '\\' && i < s.length) i += 1;
192
+ else if (!long && ch === quote) return i;
193
+ }
194
+ return i;
195
+ }
196
+
197
+ function readIriAt(s, at) {
198
+ let i = at + 1;
199
+ while (i < s.length) {
200
+ const ch = s[i++];
201
+ if (ch === '\\' && i < s.length) i += 1;
202
+ else if (ch === '>') return i;
203
+ }
204
+ return i;
205
+ }
206
+
207
+ const isWordChar = (ch) => ch != null && /[A-Za-z0-9_:-]/.test(ch);
208
+ const startsWordAt = (s, word, at) => s.startsWith(word, at) && !isWordChar(s[at - 1]) && !isWordChar(s[at + word.length]);
209
+
210
+ function skipWsAndComments(s, at) {
211
+ let i = at;
212
+ while (i < s.length) {
213
+ if (/\s/.test(s[i])) i += 1;
214
+ else if (s[i] === '#') while (i < s.length && s[i] !== '\n' && s[i] !== '\r') i += 1;
215
+ else break;
216
+ }
217
+ return i;
218
+ }
219
+
220
+ function skipDirectiveAt(s, at) {
221
+ if (s[at] === '@') {
222
+ const lower = s.slice(at, at + 9).toLowerCase();
223
+ if (!(lower.startsWith('@prefix') || lower.startsWith('@base') || lower.startsWith('@version'))) return null;
224
+ let i = at;
225
+ while (i < s.length) {
226
+ const ch = s[i];
227
+ if (ch === '"' || ch === "'") i = readStringAt(s, i);
228
+ else if (ch === '<') i = readIriAt(s, i);
229
+ else {
230
+ i += 1;
231
+ if (ch === '.') return i;
232
+ }
233
+ }
234
+ return i;
235
+ }
236
+ if (!(startsWordAt(s, 'PREFIX', at) || startsWordAt(s, 'BASE', at) || startsWordAt(s, 'VERSION', at))) return null;
237
+ // A SPARQL-style directive has no dot; it ends with its line.
238
+ let i = at;
239
+ while (i < s.length && s[i] !== '\n' && s[i] !== '\r') {
240
+ if (s[i] === '"' || s[i] === "'") i = readStringAt(s, i);
241
+ else if (s[i] === '<') i = readIriAt(s, i);
242
+ else i += 1;
243
+ }
244
+ return i;
245
+ }
246
+
247
+ function assertNoParenthesizedTripleTermSubject(text) {
248
+ let i = 0;
249
+ let statementStart = true;
250
+ while (i < text.length) {
251
+ if (statementStart) {
252
+ const start = skipWsAndComments(text, i);
253
+ const directiveEnd = skipDirectiveAt(text, start);
254
+ if (directiveEnd !== null) {
255
+ i = directiveEnd;
256
+ continue;
257
+ }
258
+ i = start;
259
+ if (text.startsWith('<<(', i)) throw new SyntaxError('RDF 1.2 triple terms are not allowed in subject position');
260
+ statementStart = false;
261
+ continue;
262
+ }
263
+ const ch = text[i];
264
+ if (ch === '"' || ch === "'") {
265
+ i = readStringAt(text, i);
266
+ continue;
267
+ }
268
+ if (ch === '<' && !text.startsWith('<<', i)) {
269
+ i = readIriAt(text, i);
270
+ continue;
271
+ }
272
+ if (ch === '#') {
273
+ while (i < text.length && text[i] !== '\n' && text[i] !== '\r') i += 1;
274
+ continue;
275
+ }
276
+ if (ch === '.' || ch === '{' || ch === '}') statementStart = true;
277
+ i += 1;
278
+ }
279
+ }
280
+
281
+ function assertLineSyntax(text) {
282
+ let i = 0;
283
+ while (i < text.length) {
284
+ const ch = text[i];
285
+ if (ch === '#') {
286
+ while (i < text.length && text[i] !== '\n' && text[i] !== '\r') i += 1;
287
+ continue;
288
+ }
289
+ if (ch === '"' || ch === "'") {
290
+ let j = readStringAt(text, i);
291
+ if (text.startsWith('@', j)) {
292
+ j += 1;
293
+ const tagStart = j;
294
+ while (j < text.length && /[A-Za-z0-9-]/.test(text[j])) j += 1;
295
+ const tag = text.slice(tagStart, j);
296
+ if (!/^[A-Za-z]{1,8}(?:-[A-Za-z0-9]{1,8})*(?:--(?:ltr|rtl))?$/.test(tag)) throw new SyntaxError(`invalid RDF 1.2 language tag @${tag}`);
297
+ } else if (text.startsWith('^^<', j)) {
298
+ const end = readIriAt(text, j + 2);
299
+ const datatype = text.slice(j + 3, end - 1);
300
+ if (datatype === `${RDF_NS}langString` || datatype === `${RDF_NS}dirLangString`) {
301
+ throw new SyntaxError(`RDF datatype ${datatype} requires a language tag in RDF line syntax`);
302
+ }
303
+ }
304
+ i = j;
305
+ continue;
306
+ }
307
+ if (ch === '<') {
308
+ if (text.startsWith('<<', i)) {
309
+ if (text[skipWsAndComments(text, i + 2)] !== '(') {
310
+ throw new SyntaxError('RDF 1.2 line syntax only allows parenthesized triple terms <<(...)>>');
311
+ }
312
+ i += 2;
313
+ continue;
314
+ }
315
+ const end = readIriAt(text, i);
316
+ const ref = text.slice(i + 1, end - 1);
317
+ if (!/^[A-Za-z][A-Za-z0-9+.-]*:/.test(ref)) throw new SyntaxError(`an IRI in RDF line syntax must be absolute: <${ref}>`);
318
+ i = end;
319
+ continue;
320
+ }
321
+ if (text.startsWith('{|', i) || text.startsWith('|}', i)) throw new SyntaxError('RDF line syntax has no annotation syntax');
322
+ if (text.startsWith('_:', i)) {
323
+ i += 2;
324
+ while (i < text.length && /[^\s<>"'(){}]/.test(text[i])) i += 1;
325
+ continue;
326
+ }
327
+ if (startsWordAt(text, 'VERSION', i)) {
328
+ i += 'VERSION'.length;
329
+ continue;
330
+ }
331
+ if (/[A-Za-z@]/.test(ch)) throw new SyntaxError('RDF line syntax only allows the directive VERSION "..."');
332
+ i += 1;
333
+ }
334
+ }
335
+
336
+ // Write quads, [S, P, O, G] eyemind terms, as Turtle (or TriG when a quad is
337
+ // in a named graph) with the prefixes it uses, or as N-Triples or N-Quads.
338
+ export function writeRdf(quads, { format = 'turtle', prefixes = {} } = {}) {
339
+ const line = format === 'n-triples' || format === 'n-quads';
340
+ const w = new RdfWriter(line ? {} : prefixes, line);
341
+ const body = [];
342
+ if (line) {
343
+ for (const [s, p, o, g] of quads) {
344
+ if (format === 'n-triples' && g !== DEFAULT_GRAPH) continue;
345
+ body.push(`${w.term(s)} ${w.term(p)} ${w.term(o)}${g === DEFAULT_GRAPH ? '' : ` ${w.term(g)}`} .`);
346
+ }
347
+ return body.map((l) => `${l}\n`).join('');
348
+ }
349
+ const graphs = new Map();
350
+ for (const q of quads) {
351
+ const key = q[3] === DEFAULT_GRAPH ? DEFAULT_GRAPH : write(q[3]);
352
+ if (!graphs.has(key)) graphs.set(key, [q[3], []]);
353
+ graphs.get(key)[1].push(q);
354
+ }
355
+ for (const [key, [g, qs]] of graphs) {
356
+ const lines = qs.map(([s, p, o]) => `${w.term(s)} ${w.predicate(p)} ${w.term(o)} .`);
357
+ if (key === DEFAULT_GRAPH) body.push(...lines);
358
+ else body.push(`${w.term(g)} {`, ...lines.map((l) => ` ${l}`), '}');
359
+ }
360
+ const head = [...w.used].sort().map((name) => `PREFIX ${name}: <${w.prefixes.get(name)}>`);
361
+ if (head.length && body.length) head.push('');
362
+ return [...head, ...body].map((l) => `${l}\n`).join('');
363
+ }
364
+
365
+ const PN_LOCAL = /^(?:[A-Za-z_0-9À-�]|:)(?:[A-Za-z_0-9·À-�.:-]*[A-Za-z_0-9·À-�:-])?$/u;
366
+
367
+ class RdfWriter {
368
+ constructor(prefixes, line) {
369
+ this.prefixes = new Map(Object.entries(prefixes));
370
+ this.ordered = [...this.prefixes].sort((a, b) => b[1].length - a[1].length);
371
+ this.line = line;
372
+ this.used = new Set();
373
+ this.bnodes = new Map();
374
+ }
375
+
376
+ iri(v) {
377
+ if (!this.line) {
378
+ for (const [name, ns] of this.ordered) {
379
+ if (!v.startsWith(ns)) continue;
380
+ const local = v.slice(ns.length);
381
+ if (local === '' || PN_LOCAL.test(local)) {
382
+ this.used.add(name);
383
+ return `${name}:${local}`;
384
+ }
385
+ }
386
+ }
387
+ return `<${v.replace(/[\u0000- <>"{}|^`\\]/g, (c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, '0').toUpperCase()}`)}>`;
388
+ }
389
+
390
+ predicate(p) {
391
+ return p instanceof Struct && p.name === 'iri' && p.args[0] === RDF_TYPE ? 'a' : this.term(p);
392
+ }
393
+
394
+ term(t) {
395
+ if (typeof t === 'bigint') return this.line ? `"${t}"^^<${XSD}integer>` : String(t);
396
+ if (typeof t === 'number') return this.literal(String(t), st('datatype', `${XSD}double`));
397
+ if (!(t instanceof Struct)) throw new EyemindError(`${write(t)} is not an RDF term`);
398
+ const [a, b, c] = t.args;
399
+ if (t.name === 'iri' && t.args.length === 1 && typeof a === 'string') return this.iri(a);
400
+ if ((t.name === 'bnode' && t.args.length === 2) || (t.name === 'skolem' && t.args.length === 3)) {
401
+ const key = write(t);
402
+ if (!this.bnodes.has(key)) this.bnodes.set(key, `_:b${this.bnodes.size}`);
403
+ return this.bnodes.get(key);
404
+ }
405
+ if (t.name === 'literal' && t.args.length === 2) return this.literal(a, b);
406
+ if (t.name === 'triple' && t.args.length === 3) return `<<( ${this.term(a)} ${this.term(b)} ${this.term(c)} )>>`;
407
+ throw new EyemindError(`${write(t)} is not an RDF term`);
408
+ }
409
+
410
+ literal(text, annotation) {
411
+ if (typeof text !== 'string') throw new EyemindError(`a literal's text must be an atom, not ${write(text)}`);
412
+ const lex = `"${text.replace(/[\\"\n\r]/g, (c) => ({ '\\': '\\\\', '"': '\\"', '\n': '\\n', '\r': '\\r' })[c])}"`;
413
+ if (annotation instanceof Struct && annotation.name === 'lang') {
414
+ const [lang, dir] = annotation.args;
415
+ return `${lex}@${lang}${dir ? `--${dir}` : ''}`;
416
+ }
417
+ if (annotation instanceof Struct && annotation.name === 'datatype' && typeof annotation.args[0] === 'string') {
418
+ const dt = annotation.args[0];
419
+ if (dt === `${XSD}string`) return lex;
420
+ if (!this.line) {
421
+ if (dt === `${XSD}boolean` && (text === 'true' || text === 'false')) return text;
422
+ if (dt === `${XSD}decimal` && /^[+-]?[0-9]*\.[0-9]+$/.test(text)) return text;
423
+ if (dt === `${XSD}double` && /^[+-]?(?:[0-9]+\.?[0-9]*|\.[0-9]+)[eE][+-]?[0-9]+$/.test(text)) return text;
424
+ }
425
+ return `${lex}^^${this.iri(dt)}`;
426
+ }
427
+ throw new EyemindError('a literal needs datatype(IRI) or lang(Tag)');
428
+ }
429
+ }