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
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
// The documents log:semantics, log:semanticsOrError and log:content read.
|
|
2
|
+
//
|
|
3
|
+
// eyemind reads no files and no network while it reasons, so the documents
|
|
4
|
+
// a program names are read before compiling: every IRI written as the
|
|
5
|
+
// subject of one of those built-ins. The compiled program states each one's
|
|
6
|
+
// text, formula or error as facts, and reasoning stays a function of them.
|
|
7
|
+
// Only local files are read, through the host's readFile.
|
|
8
|
+
import { LOG } from './n3-parser.js';
|
|
9
|
+
|
|
10
|
+
export const DOCUMENT_PREDICATES = new Set([`${LOG}semantics`, `${LOG}semanticsOrError`, `${LOG}content`]);
|
|
11
|
+
|
|
12
|
+
// The IRIs a document's triples name as documents to read: the subject of
|
|
13
|
+
// such a built-in, and, when a rule finds that subject with a pattern whose
|
|
14
|
+
// predicate is an IRI, as in { :doc :source ?d. ?d log:semantics ?f }, each
|
|
15
|
+
// IRI the document's facts state at that place.
|
|
16
|
+
export function documentIris(triples, found = new Set()) {
|
|
17
|
+
named(triples, found);
|
|
18
|
+
const places = [];
|
|
19
|
+
for (const x of triples) {
|
|
20
|
+
if (!(x.s.t === 'graph' && x.p.t === 'iri' && (x.p.v === `${LOG}implies` || x.p.v === `${LOG}impliedBy` || x.p.v === `${LOG}query`))) continue;
|
|
21
|
+
const body = x.p.v === `${LOG}impliedBy` ? x.o : x.s;
|
|
22
|
+
if (body.t !== 'graph') continue;
|
|
23
|
+
for (const b of body.triples) {
|
|
24
|
+
if (!(b.p.t === 'iri' && DOCUMENT_PREDICATES.has(b.p.v) && b.s.t === 'var')) continue;
|
|
25
|
+
for (const pattern of body.triples) {
|
|
26
|
+
if (pattern === b || pattern.p.t !== 'iri') continue;
|
|
27
|
+
if (pattern.o.t === 'var' && pattern.o.v === b.s.v) places.push([pattern.p.v, 'o']);
|
|
28
|
+
if (pattern.s.t === 'var' && pattern.s.v === b.s.v) places.push([pattern.p.v, 's']);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
for (const [predicate, position] of places) {
|
|
33
|
+
for (const x of triples) if (x.p.t === 'iri' && x.p.v === predicate && x[position].t === 'iri') found.add(x[position].v);
|
|
34
|
+
}
|
|
35
|
+
return found;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function named(triples, found) {
|
|
39
|
+
const term = (t) => {
|
|
40
|
+
if (t.t === 'graph') named(t.triples, found);
|
|
41
|
+
else if (t.t === 'list') t.items.forEach(term);
|
|
42
|
+
};
|
|
43
|
+
for (const x of triples) {
|
|
44
|
+
if (x.p.t === 'iri' && DOCUMENT_PREDICATES.has(x.p.v) && x.s.t === 'iri') found.add(x.s.v);
|
|
45
|
+
term(x.s);
|
|
46
|
+
term(x.o);
|
|
47
|
+
}
|
|
48
|
+
return found;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
// Read the documents: a Map from IRI to { text } or { error }. readFile
|
|
52
|
+
// reads a local path; without it, or for another IRI, the document is an
|
|
53
|
+
// error, and the built-ins find nothing.
|
|
54
|
+
export function readDocuments(iris, readFile = null) {
|
|
55
|
+
const documents = new Map();
|
|
56
|
+
for (const iri of iris) {
|
|
57
|
+
const location = iri.replace(/#.*$/, '');
|
|
58
|
+
try {
|
|
59
|
+
if (!location.startsWith('file:') || !readFile) throw new Error('only local files are read');
|
|
60
|
+
documents.set(iri, { text: readFile(decodeURIComponent(new URL(location).pathname)) });
|
|
61
|
+
} catch (error) {
|
|
62
|
+
documents.set(iri, { error: `${location}: ${error.message}` });
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
return documents;
|
|
66
|
+
}
|
package/src/n3-parser.js
ADDED
|
@@ -0,0 +1,463 @@
|
|
|
1
|
+
// Notation3 documents read into plain terms and triples.
|
|
2
|
+
//
|
|
3
|
+
// The parser accepts the N3 syntax used by rule programs: prefixes and base,
|
|
4
|
+
// IRIs and prefixed names, literals with language or datatype, numbers and
|
|
5
|
+
// booleans, blank nodes, collections, quoted formulas, universal variables,
|
|
6
|
+
// the verbs a, =, =>, <=, has and is ... of, inverse <-, and the paths ! and ^.
|
|
7
|
+
// It never evaluates anything; rules are triples whose predicate is
|
|
8
|
+
// log:implies, log:impliedBy or log:query.
|
|
9
|
+
//
|
|
10
|
+
// Terms:
|
|
11
|
+
// { t: 'iri', v } an IRI
|
|
12
|
+
// { t: 'bnode', v, scope } a blank node, labelled within a formula scope
|
|
13
|
+
// { t: 'literal', v, dt, lang, dir } a literal; dt is an IRI text
|
|
14
|
+
// { t: 'int', v } / { t: 'float', v } numbers: a BigInt, a finite binary64
|
|
15
|
+
// { t: 'var', v } a universal variable, ?name
|
|
16
|
+
// { t: 'list', items } a collection
|
|
17
|
+
// { t: 'graph', triples, scope } a quoted formula
|
|
18
|
+
// { t: 'triple', s, p, o } an RDF 1.2 triple term
|
|
19
|
+
// A triple is { s, p, o }.
|
|
20
|
+
|
|
21
|
+
export const XSD = 'http://www.w3.org/2001/XMLSchema#';
|
|
22
|
+
export const RDF = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#';
|
|
23
|
+
export const LOG = 'http://www.w3.org/2000/10/swap/log#';
|
|
24
|
+
export const OWL = 'http://www.w3.org/2002/07/owl#';
|
|
25
|
+
|
|
26
|
+
export class N3SyntaxError extends SyntaxError {
|
|
27
|
+
constructor(message, line) {
|
|
28
|
+
super(`N3 syntax, line ${line}: ${message}`);
|
|
29
|
+
this.line = line;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
const NUMBER = /[+-]?(?:[0-9]+\.[0-9]*[eE][+-]?[0-9]+|\.[0-9]+[eE][+-]?[0-9]+|[0-9]+[eE][+-]?[0-9]+|[0-9]*\.[0-9]+|[0-9]+)/y;
|
|
34
|
+
const PUNCT = ['^^', '=>', '<=', '<-', '.', ';', ',', '[', ']', '(', ')', '{', '}', '=', '!', '^'];
|
|
35
|
+
|
|
36
|
+
function isPnCharsBase(c) {
|
|
37
|
+
return /[A-Za-zÀ-ÖØ-öø-˿Ͱ-ͽͿ--⁰-Ⰰ-、-豈-﷏ﷰ-�]/u.test(c) ||
|
|
38
|
+
(c.codePointAt(0) >= 0x10000 && c.codePointAt(0) <= 0xEFFFF);
|
|
39
|
+
}
|
|
40
|
+
const isPnCharsU = (c) => isPnCharsBase(c) || c === '_';
|
|
41
|
+
const isPnChars = (c) => isPnCharsU(c) || c === '-' || /[0-9·̀-ͯ‿-⁀]/u.test(c);
|
|
42
|
+
|
|
43
|
+
function decodeEscapes(text, line) {
|
|
44
|
+
let out = '';
|
|
45
|
+
for (let i = 0; i < text.length; i++) {
|
|
46
|
+
const c = text[i];
|
|
47
|
+
if (c !== '\\') { out += c; continue; }
|
|
48
|
+
const e = text[++i];
|
|
49
|
+
const simple = { t: '\t', b: '\b', n: '\n', r: '\r', f: '\f', '"': '"', "'": "'", '\\': '\\' };
|
|
50
|
+
if (simple[e] !== undefined) out += simple[e];
|
|
51
|
+
else if (e === 'u' || e === 'U') {
|
|
52
|
+
const n = e === 'u' ? 4 : 8;
|
|
53
|
+
const hex = text.slice(i + 1, i + 1 + n);
|
|
54
|
+
if (!new RegExp(`^[0-9A-Fa-f]{${n}}$`).test(hex)) throw new N3SyntaxError(`bad \\${e} escape`, line);
|
|
55
|
+
const code = parseInt(hex, 16);
|
|
56
|
+
// Escapes name characters: not U+0000, a surrogate or a noncharacter.
|
|
57
|
+
if (code === 0 || (code >= 0xd800 && code <= 0xdfff) || (code & 0xfffe) === 0xfffe || code > 0x10ffff) {
|
|
58
|
+
throw new N3SyntaxError(`\\${e}${hex} does not name a character a document may hold`, line);
|
|
59
|
+
}
|
|
60
|
+
out += String.fromCodePoint(code);
|
|
61
|
+
i += n;
|
|
62
|
+
} else throw new N3SyntaxError(`unknown string escape \\${e}`, line);
|
|
63
|
+
}
|
|
64
|
+
return out;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
// Tokens: { k: kind, v: text, line }. Kinds: iri, pname, bnode, var, string,
|
|
68
|
+
// lang, number, word, punct, eof.
|
|
69
|
+
export function tokenize(src) {
|
|
70
|
+
const toks = [];
|
|
71
|
+
let i = 0;
|
|
72
|
+
let line = 1;
|
|
73
|
+
const n = src.length;
|
|
74
|
+
const push = (k, v) => toks.push({ k, v, line });
|
|
75
|
+
while (i < n) {
|
|
76
|
+
const c = src[i];
|
|
77
|
+
if (c === '\n') { line++; i++; continue; }
|
|
78
|
+
if (c === ' ' || c === '\t' || c === '\r' || c === '') { i++; continue; }
|
|
79
|
+
if (c === '#') { while (i < n && src[i] !== '\n') i++; continue; }
|
|
80
|
+
if (src.startsWith('<<', i) || src.startsWith('>>', i) || src.startsWith(')>>', i)) {
|
|
81
|
+
const v = src.startsWith('<<(', i) ? '<<(' : src.startsWith(')>>', i) ? ')>>' : src.slice(i, i + 2);
|
|
82
|
+
push('punct', v);
|
|
83
|
+
i += v.length;
|
|
84
|
+
continue;
|
|
85
|
+
}
|
|
86
|
+
if (c === '<' && src[i + 1] !== '=' && src[i + 1] !== '-') {
|
|
87
|
+
const end = src.indexOf('>', i + 1);
|
|
88
|
+
if (end < 0) throw new N3SyntaxError('unterminated IRI', line);
|
|
89
|
+
const raw = src.slice(i + 1, end);
|
|
90
|
+
if (/[\s<"{}|^`]/.test(raw)) throw new N3SyntaxError(`invalid character in IRI <${raw}>`, line);
|
|
91
|
+
const decoded = decodeEscapes(raw, line);
|
|
92
|
+
// An escape may not bring in what the IRI could not hold as written.
|
|
93
|
+
if (/[\u0000-\u0020<>"{}|^`\\]/.test(decoded)) throw new N3SyntaxError(`invalid character in IRI <${raw}>`, line);
|
|
94
|
+
push('iri', decoded);
|
|
95
|
+
i = end + 1;
|
|
96
|
+
continue;
|
|
97
|
+
}
|
|
98
|
+
if (c === '"' || c === "'") {
|
|
99
|
+
const long = src.startsWith(c.repeat(3), i);
|
|
100
|
+
const q = long ? c.repeat(3) : c;
|
|
101
|
+
let j = i + q.length;
|
|
102
|
+
let raw = '';
|
|
103
|
+
const start = line;
|
|
104
|
+
for (;;) {
|
|
105
|
+
if (j >= n) throw new N3SyntaxError('unterminated string', start);
|
|
106
|
+
if (src[j] === '\\') { raw += src[j] + src[j + 1]; j += 2; continue; }
|
|
107
|
+
if (src.startsWith(q, j)) {
|
|
108
|
+
// A long string may end in quotes: """a"""" is the text a".
|
|
109
|
+
if (long) while (src[j + 3] === c) { raw += c; j++; }
|
|
110
|
+
break;
|
|
111
|
+
}
|
|
112
|
+
if (src[j] === '\n') { if (!long) throw new N3SyntaxError('line break in a short string', line); line++; }
|
|
113
|
+
raw += src[j++];
|
|
114
|
+
}
|
|
115
|
+
push('string', decodeEscapes(raw, start));
|
|
116
|
+
i = j + q.length;
|
|
117
|
+
continue;
|
|
118
|
+
}
|
|
119
|
+
if (c === '@') {
|
|
120
|
+
const m = /^@([A-Za-z]+(?:-[A-Za-z0-9]+)*(?:--(?:ltr|rtl))?)/.exec(src.slice(i, i + 100));
|
|
121
|
+
if (!m) throw new N3SyntaxError('expected a language tag or keyword after @', line);
|
|
122
|
+
const word = m[1];
|
|
123
|
+
const prev = toks[toks.length - 1];
|
|
124
|
+
if (['prefix', 'base', 'version', 'keywords', 'forAll', 'forSome'].includes(word) && !(prev && prev.k === 'string')) push('word', `@${word}`);
|
|
125
|
+
else if (['a', 'is', 'of', 'has'].includes(word) && !(prev && prev.k === 'string')) push('word', word);
|
|
126
|
+
else push('lang', word);
|
|
127
|
+
i += m[0].length;
|
|
128
|
+
continue;
|
|
129
|
+
}
|
|
130
|
+
if (c === '?' && i + 1 < n && isPnChars(String.fromCodePoint(src.codePointAt(i + 1)))) {
|
|
131
|
+
let j = i + 1;
|
|
132
|
+
while (j < n) {
|
|
133
|
+
const ch = String.fromCodePoint(src.codePointAt(j));
|
|
134
|
+
if (!isPnChars(ch)) break;
|
|
135
|
+
j += ch.length;
|
|
136
|
+
}
|
|
137
|
+
push('var', src.slice(i + 1, j));
|
|
138
|
+
i = j;
|
|
139
|
+
continue;
|
|
140
|
+
}
|
|
141
|
+
if (c === '_' && src[i + 1] === ':') {
|
|
142
|
+
let j = i + 2;
|
|
143
|
+
while (j < n) {
|
|
144
|
+
const ch = String.fromCodePoint(src.codePointAt(j));
|
|
145
|
+
if (!(isPnChars(ch) || ch === '.')) break;
|
|
146
|
+
j += ch.length;
|
|
147
|
+
}
|
|
148
|
+
while (src[j - 1] === '.') j--;
|
|
149
|
+
push('bnode', src.slice(i + 2, j));
|
|
150
|
+
i = j;
|
|
151
|
+
continue;
|
|
152
|
+
}
|
|
153
|
+
NUMBER.lastIndex = i;
|
|
154
|
+
const num = NUMBER.exec(src);
|
|
155
|
+
if (num && (/[0-9]/.test(c) || ((c === '+' || c === '-' || c === '.') && /[0-9.]/.test(src[i + 1] ?? '')))) {
|
|
156
|
+
push('number', num[0]);
|
|
157
|
+
i += num[0].length;
|
|
158
|
+
continue;
|
|
159
|
+
}
|
|
160
|
+
const punct = PUNCT.find((p) => src.startsWith(p, i));
|
|
161
|
+
if (punct && !(punct === '.' && /[0-9]/.test(src[i + 1] ?? ''))) {
|
|
162
|
+
push('punct', punct);
|
|
163
|
+
i += punct.length;
|
|
164
|
+
continue;
|
|
165
|
+
}
|
|
166
|
+
// A prefixed name or a bare word.
|
|
167
|
+
const startCh = String.fromCodePoint(src.codePointAt(i));
|
|
168
|
+
if (isPnCharsBase(startCh) || c === ':' || c === '_') {
|
|
169
|
+
let j = i;
|
|
170
|
+
let prefix = null;
|
|
171
|
+
while (j < n) {
|
|
172
|
+
const ch = String.fromCodePoint(src.codePointAt(j));
|
|
173
|
+
if (ch === ':' && prefix === null) { prefix = src.slice(i, j); j++; continue; }
|
|
174
|
+
if (prefix !== null && ch === '\\' && j + 1 < n) { j += 2; continue; }
|
|
175
|
+
if (prefix !== null && ch === '%' && /^[0-9A-Fa-f]{2}$/.test(src.slice(j + 1, j + 3))) { j += 3; continue; }
|
|
176
|
+
if (isPnChars(ch) || ch === '.' || (prefix !== null && ch === ':')) { j += ch.length; continue; }
|
|
177
|
+
break;
|
|
178
|
+
}
|
|
179
|
+
while (src[j - 1] === '.' && j > i) j--;
|
|
180
|
+
const text = src.slice(i, j);
|
|
181
|
+
if (prefix === null) push('word', text);
|
|
182
|
+
else push('pname', text);
|
|
183
|
+
i = j;
|
|
184
|
+
continue;
|
|
185
|
+
}
|
|
186
|
+
throw new N3SyntaxError(`unexpected character ${JSON.stringify(c)}`, line);
|
|
187
|
+
}
|
|
188
|
+
push('eof', '');
|
|
189
|
+
return toks;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
// Resolve a relative IRI reference against a base (RFC 3986, Section 5.2).
|
|
193
|
+
export function resolveIri(ref, base) {
|
|
194
|
+
if (!base || /^[A-Za-z][A-Za-z0-9+.-]*:/.test(ref)) return ref;
|
|
195
|
+
const m = /^([A-Za-z][A-Za-z0-9+.-]*:)(\/\/[^/?#]*)?([^?#]*)(\?[^#]*)?(#.*)?$/.exec(base);
|
|
196
|
+
if (!m) return ref;
|
|
197
|
+
const [, scheme, authority = '', path, query = ''] = m;
|
|
198
|
+
if (ref === '') return scheme + authority + path + query;
|
|
199
|
+
if (ref.startsWith('#')) return scheme + authority + path + query + ref;
|
|
200
|
+
if (ref.startsWith('//')) return scheme + ref;
|
|
201
|
+
if (ref.startsWith('?')) return scheme + authority + path + ref;
|
|
202
|
+
const [refPath, rest = ''] = ref.split(/(?=[?#])/, 2).length === 2 ? [ref.slice(0, ref.search(/[?#]/)), ref.slice(ref.search(/[?#]/))] : [ref, ''];
|
|
203
|
+
let merged;
|
|
204
|
+
if (refPath.startsWith('/')) merged = refPath;
|
|
205
|
+
else if (authority && path === '') merged = `/${refPath}`;
|
|
206
|
+
else merged = path.slice(0, path.lastIndexOf('/') + 1) + refPath;
|
|
207
|
+
return scheme + authority + removeDots(merged) + rest;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
function removeDots(path) {
|
|
211
|
+
const out = [];
|
|
212
|
+
const segs = path.split('/');
|
|
213
|
+
for (let k = 0; k < segs.length; k++) {
|
|
214
|
+
const s = segs[k];
|
|
215
|
+
if (s === '.') { if (k === segs.length - 1) out.push(''); continue; }
|
|
216
|
+
if (s === '..') { if (out.length > 1) out.pop(); if (k === segs.length - 1) out.push(''); continue; }
|
|
217
|
+
out.push(s);
|
|
218
|
+
}
|
|
219
|
+
return out.join('/');
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
const iri = (v) => ({ t: 'iri', v });
|
|
223
|
+
|
|
224
|
+
// Prefixes a document may use without declaring them.
|
|
225
|
+
export const DEFAULT_PREFIXES = {
|
|
226
|
+
rdf: RDF,
|
|
227
|
+
rdfs: 'http://www.w3.org/2000/01/rdf-schema#',
|
|
228
|
+
xsd: XSD,
|
|
229
|
+
owl: OWL,
|
|
230
|
+
log: LOG,
|
|
231
|
+
math: 'http://www.w3.org/2000/10/swap/math#',
|
|
232
|
+
string: 'http://www.w3.org/2000/10/swap/string#',
|
|
233
|
+
list: 'http://www.w3.org/2000/10/swap/list#',
|
|
234
|
+
time: 'http://www.w3.org/2000/10/swap/time#',
|
|
235
|
+
crypto: 'http://www.w3.org/2000/10/swap/crypto#',
|
|
236
|
+
};
|
|
237
|
+
|
|
238
|
+
// Parse a document: { triples, prefixes, base }. Prefixes map names to IRIs
|
|
239
|
+
// in declaration order.
|
|
240
|
+
export function parseN3(src, { base = '' } = {}) {
|
|
241
|
+
const toks = tokenize(String(src));
|
|
242
|
+
let pos = 0;
|
|
243
|
+
const prefixes = new Map();
|
|
244
|
+
let bnodeCount = 0;
|
|
245
|
+
let scopeCount = 0;
|
|
246
|
+
const top = { id: 0, triples: [] };
|
|
247
|
+
let scope = top;
|
|
248
|
+
const peek = (k = 0) => toks[pos + k];
|
|
249
|
+
const next = () => toks[pos++];
|
|
250
|
+
const fail = (message, tok = peek()) => new N3SyntaxError(message, tok.line);
|
|
251
|
+
const isP = (v, tok = peek()) => tok.k === 'punct' && tok.v === v;
|
|
252
|
+
const expectP = (v) => {
|
|
253
|
+
const tok = next();
|
|
254
|
+
if (!(tok.k === 'punct' && tok.v === v)) throw fail(`expected '${v}', found ${describe(tok)}`, tok);
|
|
255
|
+
};
|
|
256
|
+
const describe = (tok) => (tok.k === 'eof' ? 'the end' : `'${tok.v}'`);
|
|
257
|
+
const freshBnode = () => ({ t: 'bnode', v: `#${++bnodeCount}`, scope: scope.id });
|
|
258
|
+
const emit = (s, p, o) => scope.triples.push({ s, p, o });
|
|
259
|
+
|
|
260
|
+
function pname(text, tok) {
|
|
261
|
+
const k = text.indexOf(':');
|
|
262
|
+
const pre = text.slice(0, k);
|
|
263
|
+
const ns = prefixes.has(pre) ? prefixes.get(pre) : DEFAULT_PREFIXES[pre];
|
|
264
|
+
if (ns === undefined) throw fail(`undeclared prefix '${pre}:'`, tok);
|
|
265
|
+
const local = text.slice(k + 1).replace(/\\(.)/g, '$1');
|
|
266
|
+
return iri(ns + local);
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
function directive() {
|
|
270
|
+
const tok = next();
|
|
271
|
+
const word = tok.v.replace(/^@/, '').toLowerCase();
|
|
272
|
+
if (word === 'prefix') {
|
|
273
|
+
const p = next();
|
|
274
|
+
if (p.k !== 'pname' || !p.v.endsWith(':') || p.v.indexOf(':') !== p.v.length - 1 || p.v.endsWith('.:')) throw fail('expected a prefix name such as ex:, not ending in a dot', p);
|
|
275
|
+
const i = next();
|
|
276
|
+
if (i.k !== 'iri') throw fail('expected an IRI for the prefix', i);
|
|
277
|
+
prefixes.set(p.v.slice(0, -1), resolveIri(i.v, base));
|
|
278
|
+
} else if (word === 'base') {
|
|
279
|
+
const i = next();
|
|
280
|
+
if (i.k !== 'iri') throw fail('expected an IRI for the base', i);
|
|
281
|
+
base = resolveIri(i.v, base);
|
|
282
|
+
} else if (word === 'version') {
|
|
283
|
+
const v = next();
|
|
284
|
+
if (v.k !== 'string') throw fail('expected a version string', v);
|
|
285
|
+
} else {
|
|
286
|
+
throw fail(`${tok.v} is not supported`, tok);
|
|
287
|
+
}
|
|
288
|
+
if (tok.v.startsWith('@')) expectP('.');
|
|
289
|
+
else if (isP('.')) next();
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
function literalTail(text) {
|
|
293
|
+
const tok = peek();
|
|
294
|
+
if (tok.k === 'lang') {
|
|
295
|
+
next();
|
|
296
|
+
const [lang, dir] = tok.v.split('--');
|
|
297
|
+
return { t: 'literal', v: text, lang: lang.toLowerCase(), dir: dir ?? null, dt: dir ? `${RDF}dirLangString` : `${RDF}langString` };
|
|
298
|
+
}
|
|
299
|
+
if (isP('^^')) {
|
|
300
|
+
next();
|
|
301
|
+
const dt = iriTerm();
|
|
302
|
+
return typedLiteral(text, dt.v);
|
|
303
|
+
}
|
|
304
|
+
return { t: 'literal', v: text, dt: `${XSD}string` };
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
function iriTerm() {
|
|
308
|
+
const tok = next();
|
|
309
|
+
if (tok.k === 'iri') return iri(resolveIri(tok.v, base));
|
|
310
|
+
if (tok.k === 'pname') return pname(tok.v, tok);
|
|
311
|
+
throw fail(`expected an IRI, found ${describe(tok)}`, tok);
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
function term() {
|
|
315
|
+
const tok = peek();
|
|
316
|
+
if (tok.k === 'iri' || tok.k === 'pname') return iriTerm();
|
|
317
|
+
next();
|
|
318
|
+
if (tok.k === 'var') return { t: 'var', v: tok.v };
|
|
319
|
+
if (tok.k === 'bnode') return { t: 'bnode', v: tok.v, scope: scope.id };
|
|
320
|
+
if (tok.k === 'string') return literalTail(tok.v);
|
|
321
|
+
if (tok.k === 'number') return numberTerm(tok.v);
|
|
322
|
+
if (tok.k === 'word') {
|
|
323
|
+
if (tok.v === 'true' || tok.v === 'false') return { t: 'literal', v: tok.v, dt: `${XSD}boolean` };
|
|
324
|
+
throw fail(`unexpected word '${tok.v}'; prefixed names need a colon, as in :${tok.v}`, tok);
|
|
325
|
+
}
|
|
326
|
+
if (isP('<<(', tok) || isP('<<', tok)) {
|
|
327
|
+
const s = pathTerm();
|
|
328
|
+
const p = verb();
|
|
329
|
+
const o = pathTerm();
|
|
330
|
+
if (p.inverse) throw fail('a triple term cannot use an inverse verb', tok);
|
|
331
|
+
const close = next();
|
|
332
|
+
if (!(close.k === 'punct' && close.v === (tok.v === '<<(' ? ')>>' : '>>'))) throw fail(`expected '${tok.v === '<<(' ? ')>>' : '>>'}'`, close);
|
|
333
|
+
return { t: 'triple', s, p: p.p, o };
|
|
334
|
+
}
|
|
335
|
+
if (isP('[', tok)) {
|
|
336
|
+
// [ id :x :p :o ] describes :x itself.
|
|
337
|
+
let b;
|
|
338
|
+
if (peek().k === 'word' && peek().v === 'id') {
|
|
339
|
+
next();
|
|
340
|
+
b = pathTerm();
|
|
341
|
+
} else b = freshBnode();
|
|
342
|
+
if (!isP(']')) predicateObjectList(b);
|
|
343
|
+
expectP(']');
|
|
344
|
+
return b;
|
|
345
|
+
}
|
|
346
|
+
if (isP('(', tok)) {
|
|
347
|
+
const items = [];
|
|
348
|
+
while (!isP(')')) {
|
|
349
|
+
if (peek().k === 'eof') throw fail("unterminated collection; expected ')'");
|
|
350
|
+
items.push(pathTerm());
|
|
351
|
+
}
|
|
352
|
+
next();
|
|
353
|
+
return { t: 'list', items };
|
|
354
|
+
}
|
|
355
|
+
if (isP('{', tok)) {
|
|
356
|
+
const outer = scope;
|
|
357
|
+
scope = { id: ++scopeCount, triples: [] };
|
|
358
|
+
while (!isP('}')) {
|
|
359
|
+
if (peek().k === 'eof') throw fail("unterminated formula; expected '}'");
|
|
360
|
+
if (statement(true) === 'directive') continue;
|
|
361
|
+
if (isP('.')) next();
|
|
362
|
+
else if (!isP('}')) throw fail(`expected '.' or '}', found ${describe(peek())}`);
|
|
363
|
+
}
|
|
364
|
+
next();
|
|
365
|
+
const g = { t: 'graph', triples: scope.triples, scope: scope.id };
|
|
366
|
+
scope = outer;
|
|
367
|
+
return g;
|
|
368
|
+
}
|
|
369
|
+
throw fail(`expected a term, found ${describe(tok)}`, tok);
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
// A term followed by any number of paths: x!p is the object of x p,
|
|
373
|
+
// x^p the subject of something p x.
|
|
374
|
+
function pathTerm() {
|
|
375
|
+
let t = term();
|
|
376
|
+
while (isP('!') || isP('^')) {
|
|
377
|
+
const forward = next().v === '!';
|
|
378
|
+
const p = term();
|
|
379
|
+
const b = freshBnode();
|
|
380
|
+
if (forward) emit(t, p, b);
|
|
381
|
+
else emit(b, p, t);
|
|
382
|
+
t = b;
|
|
383
|
+
}
|
|
384
|
+
return t;
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
// A verb: { p, inverse }.
|
|
388
|
+
function verb() {
|
|
389
|
+
const tok = peek();
|
|
390
|
+
if (tok.k === 'word' && tok.v === 'a') { next(); return { p: iri(`${RDF}type`), inverse: false }; }
|
|
391
|
+
if (tok.k === 'word' && tok.v === 'has') { next(); return { p: pathTerm(), inverse: false }; }
|
|
392
|
+
if (tok.k === 'word' && tok.v === 'is') {
|
|
393
|
+
next();
|
|
394
|
+
const p = pathTerm();
|
|
395
|
+
const of = next();
|
|
396
|
+
if (!(of.k === 'word' && of.v === 'of')) throw fail("expected 'of' after 'is ...'", of);
|
|
397
|
+
return { p, inverse: true };
|
|
398
|
+
}
|
|
399
|
+
if (isP('=')) { next(); return { p: iri(`${OWL}sameAs`), inverse: false }; }
|
|
400
|
+
if (isP('=>')) { next(); return { p: iri(`${LOG}implies`), inverse: false }; }
|
|
401
|
+
if (isP('<=')) { next(); return { p: iri(`${LOG}impliedBy`), inverse: false }; }
|
|
402
|
+
if (isP('<-')) { next(); return { p: pathTerm(), inverse: true }; }
|
|
403
|
+
return { p: pathTerm(), inverse: false };
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
function predicateObjectList(s) {
|
|
407
|
+
for (;;) {
|
|
408
|
+
const { p, inverse } = verb();
|
|
409
|
+
for (;;) {
|
|
410
|
+
const o = pathTerm();
|
|
411
|
+
if (inverse) emit(o, p, s);
|
|
412
|
+
else emit(s, p, o);
|
|
413
|
+
if (!isP(',')) break;
|
|
414
|
+
next();
|
|
415
|
+
}
|
|
416
|
+
if (!isP(';')) return;
|
|
417
|
+
while (isP(';')) next();
|
|
418
|
+
if (isP('.') || isP(']') || isP('}') || peek().k === 'eof') return;
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
function statement(inFormula) {
|
|
423
|
+
const tok = peek();
|
|
424
|
+
if (tok.k === 'word' && /^(@prefix|@base|prefix|base|version)$/i.test(tok.v)) {
|
|
425
|
+
directive();
|
|
426
|
+
return 'directive';
|
|
427
|
+
}
|
|
428
|
+
if (tok.k === 'word' && (tok.v === '@forAll' || tok.v === '@forSome')) throw fail(`${tok.v} is not supported; use ?variables and blank nodes`, tok);
|
|
429
|
+
// { true } is the empty formula.
|
|
430
|
+
if (inFormula && tok.k === 'word' && tok.v === 'true' && (isP('.', peek(1)) || isP('}', peek(1)))) { next(); return 'triples'; }
|
|
431
|
+
const s = pathTerm();
|
|
432
|
+
// A bracketed blank node may stand alone: [ :p :o ].
|
|
433
|
+
if (s.t === 'bnode' && (isP('.') || isP('}') || peek().k === 'eof')) return 'triples';
|
|
434
|
+
predicateObjectList(s);
|
|
435
|
+
return 'triples';
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
while (peek().k !== 'eof') {
|
|
439
|
+
const kind = statement(false);
|
|
440
|
+
if (kind === 'directive') continue;
|
|
441
|
+
expectP('.');
|
|
442
|
+
}
|
|
443
|
+
return { triples: top.triples, prefixes, base };
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
function numberTerm(text) {
|
|
447
|
+
if (/^[+-]?[0-9]+$/.test(text)) return { t: 'int', v: BigInt(text) };
|
|
448
|
+
return { t: 'float', v: Number(text) };
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
const INTEGER_TYPES = new Set(['integer']);
|
|
452
|
+
const FLOAT_TYPES = new Set(['decimal', 'double', 'float']);
|
|
453
|
+
|
|
454
|
+
// A typed literal; xsd:integer, xsd:decimal and xsd:double with a valid
|
|
455
|
+
// lexical form become numbers, as the N3 shorthands 1, 1.5 and 1.5e0 do.
|
|
456
|
+
export function typedLiteral(text, dt) {
|
|
457
|
+
if (dt.startsWith(XSD)) {
|
|
458
|
+
const local = dt.slice(XSD.length);
|
|
459
|
+
if (INTEGER_TYPES.has(local) && /^[+-]?[0-9]+$/.test(text)) return { t: 'int', v: BigInt(text) };
|
|
460
|
+
if (FLOAT_TYPES.has(local) && /^[+-]?([0-9]+(\.[0-9]*)?|\.[0-9]+)([eE][+-]?[0-9]+)?$/.test(text)) return { t: 'float', v: Number(text) };
|
|
461
|
+
}
|
|
462
|
+
return { t: 'literal', v: text, dt };
|
|
463
|
+
}
|