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/n3.js ADDED
@@ -0,0 +1,814 @@
1
+ // N3 documents compiled to eyemind programs.
2
+ //
3
+ // Every N3 statement becomes rdf(Subject, Predicate, Object): the document's
4
+ // own triples are facts, and a run concludes the triples its forward rules
5
+ // derive that were not already facts. Rules become eyemind rules:
6
+ //
7
+ // { B } => { H }. implies(B, H) forward
8
+ // { H } <= { B }. implied_by(H, B) backward, one per head triple
9
+ // { B } log:query { H }. implies(B, result(H)) selects the output
10
+ // { B } => false. contradiction(B) an inference fuse
11
+ //
12
+ // A rule's ?variables and blank nodes are eyemind variables; a blank node
13
+ // only the conclusion mentions is the Skolem term of that firing. Built-in
14
+ // predicates of a body become goals defined in eyemind itself (builtins.mjs).
15
+ import { run } from './engine.js';
16
+ import { loadText } from './lang.js';
17
+ import { Struct } from './terms.js';
18
+ import { write } from './writer.js';
19
+ import { N3SyntaxError, parseN3, typedLiteral, LOG, XSD } from './n3-parser.js';
20
+ import { triplesFromEyemind, tripleToEyemind, writeN3 } from './n3-writer.js';
21
+ import { documentIris, readDocuments } from './n3-documents.js';
22
+
23
+ const MATH = 'http://www.w3.org/2000/10/swap/math#';
24
+ const STRING = 'http://www.w3.org/2000/10/swap/string#';
25
+ const LIST = 'http://www.w3.org/2000/10/swap/list#';
26
+ import { BUILTINS, HELPERS, UNSUPPORTED } from './n3-builtins.js';
27
+
28
+ export class N3CompileError extends Error {}
29
+
30
+ // A term or atom text as a JavaScript string literal.
31
+ const q = (text) => JSON.stringify(text);
32
+
33
+ const RESERVED = new Set(['Math', 'JSON', 'BigInt', 'Infinity', 'NaN', 'undefined', 'console', 'globalThis',
34
+ 'parseInt', 'parseFloat', 'isNaN', 'isFinite']);
35
+
36
+ // Compile an N3 document. Options: base (IRI), source (a name for the
37
+ // header). Returns { program, prefixes, queries } where queries counts the
38
+ // log:query rules; with any, the program concludes their result/3 triples.
39
+ export function compileN3(text, { base = '', source = 'input', documents } = {}) {
40
+ const doc = parseN3(text, { base });
41
+ return compileN3Document(doc, { source, documents });
42
+ }
43
+
44
+ export function compileN3Document(doc, { source = 'input', documents = new Map() } = {}) {
45
+ const facts = [];
46
+ const rules = [];
47
+ const needed = new Set();
48
+ let queries = 0;
49
+ // Only a document that mentions rdf:first, rdf:rest or rdf:nil can write a
50
+ // list out as triples, so only its built-ins read lists that way.
51
+ const views = ['first', 'rest', 'nil'].some((name) => mentions(doc.triples, `${RDF_NS}${name}`));
52
+ const rulesAsTriples = doc.triples.some((x) => {
53
+ if (x.p.t !== 'iri' || (!RULE_PREDICATES.has(x.p.v) && x.p.v !== `${LOG}query`) || !isFormulaLike(x.s) || !isFormulaLike(x.o)) return false;
54
+ const body = triplesOf(x.p.v === `${LOG}impliedBy` ? x.o : x.s);
55
+ return (x.p.v !== `${LOG}query` && variablePredicate(body)) || [...RULE_PREDICATES].some((p) => usesPredicate(body, p));
56
+ });
57
+ for (const triple of doc.triples) {
58
+ const p = triple.p.t === 'iri' ? triple.p.v : null;
59
+ // A rule is also a triple of the document, its variables quoted, which
60
+ // a rule predicate or a variable predicate can find.
61
+ if (rulesAsTriples && RULE_PREDICATES.has(p) && isFormulaLike(triple.s) && isFormulaLike(triple.o)) facts.push(`fact(${new Context(false).rdf(triple)})`);
62
+ if (p === `${LOG}implies` && isFormulaLike(triple.s) && isFormulaLike(triple.o)) {
63
+ rules.push(compileRule(triple.s, triple.o, 'forward', needed, views));
64
+ } else if (p === `${LOG}impliedBy` && isFormulaLike(triple.s) && isFormulaLike(triple.o)) {
65
+ rules.push(compileRule(triple.o, triple.s, 'backward', needed, views));
66
+ } else if (p === `${LOG}query` && isFormulaLike(triple.s) && isFormulaLike(triple.o)) {
67
+ queries++;
68
+ rules.push(compileRule(triple.s, triple.o, 'query', needed, views));
69
+ } else {
70
+ const ctx = new Context(false);
71
+ facts.push(`fact(${ctx.rdf(triple)})`);
72
+ }
73
+ }
74
+ // The documents log:semantics and log:content read, fetched beforehand.
75
+ let documentNumber = 0;
76
+ const fetchedFormulas = [];
77
+ for (const [iri, document] of documents) {
78
+ const ctx = new Context(false);
79
+ const subject = `iri(${q(iri)})`;
80
+ // Errors are written as N3 reasoners write them:
81
+ // error(dereference_failed,IRI) and error(parse_error,Message).
82
+ if (document.error !== undefined) {
83
+ facts.push(`fact(n3_document_error(${subject}, ${q(`error(dereference_failed,${iri.replace(/#.*$/, '')})`)}))`);
84
+ continue;
85
+ }
86
+ facts.push(`fact(n3_content(${subject}, ${q(document.text)}))`);
87
+ try {
88
+ const parsed = parseN3(document.text, { base: iri.replace(/#.*$/, '') });
89
+ // Its blank nodes are its own, apart from any other document's.
90
+ const label = `d${++documentNumber}`;
91
+ const own = (t) => (t.t === 'bnode' ? { ...t, scope: `${label}.${t.scope}` } : t.t === 'list' ? { ...t, items: t.items.map(own) }
92
+ : t.t === 'graph' ? { ...t, triples: t.triples.map(ownTriple) } : t.t === 'triple' ? ownTriple(t) : t);
93
+ const ownTriple = (x) => ({ ...x, s: own(x.s), p: own(x.p), o: own(x.o) });
94
+ const formula = { t: 'graph', triples: parsed.triples.map(ownTriple), scope: 0 };
95
+ facts.push(`fact(n3_semantics(${subject}, ${ctx.term(formula)}))`);
96
+ fetchedFormulas.push(formula);
97
+ } catch (error) {
98
+ if (!(error instanceof N3SyntaxError)) throw error;
99
+ facts.push(`fact(n3_document_error(${subject}, ${q(`error(parse_error,${error.message})`)}))`);
100
+ }
101
+ }
102
+ // log:conclusion reads the closure of a formula the document states, worked
103
+ // out now by running the formula as a program of its own.
104
+ // A fetched document's formula counts as stated, but a closure eyemind
105
+ // cannot work out, as for an unstratified document, is left out.
106
+ if (usesPredicate(doc.triples, `${LOG}conclusion`)) {
107
+ for (const formula of statedFormulas(doc.triples)) {
108
+ const ctx = new Context(false);
109
+ facts.push(`fact(n3_conclusion_of(${ctx.term(formula)}, ${ctx.term(closure(formula))}))`);
110
+ }
111
+ for (const formula of fetchedFormulas) {
112
+ let closed;
113
+ try {
114
+ closed = closure(formula);
115
+ } catch (error) {
116
+ if (error instanceof N3CompileError || error?.name === 'EyemindError') continue;
117
+ throw error;
118
+ }
119
+ const ctx = new Context(false);
120
+ facts.push(`fact(n3_conclusion_of(${ctx.term(formula)}, ${ctx.term(closed)}))`);
121
+ }
122
+ }
123
+ // log:parsedAsN3 reads the strings the document states that are N3, parsed
124
+ // now.
125
+ if (usesPredicate(doc.triples, `${LOG}parsedAsN3`)) {
126
+ for (const literal of statedStrings(doc.triples)) {
127
+ let parsed;
128
+ try {
129
+ parsed = parseN3(literal.v);
130
+ } catch (error) {
131
+ if (error instanceof N3SyntaxError) continue;
132
+ throw error;
133
+ }
134
+ const ctx = new Context(false);
135
+ facts.push(`fact(n3_parsed(${ctx.term(literal)}, ${ctx.term({ t: 'graph', triples: parsed.triples, scope: 0 })}))`);
136
+ }
137
+ }
138
+ const lines = [
139
+ `// Generated by eyemind from ${source.replace(/[\r\n]/g, ' ')}, Notation3.`,
140
+ '// Each N3 triple is rdf(Subject, Predicate, Object). Without a log:query',
141
+ '// the conclusions are the triples the forward rules derive.',
142
+ ...facts,
143
+ ...rules.flat(),
144
+ ];
145
+ if (queries > 0) lines.push('query(result(S, P, O))');
146
+ const library = libraryText(needed);
147
+ if (library) lines.push('', '// N3 built-ins.', library);
148
+ return { program: `${lines.join('\n')}\n`, prefixes: doc.prefixes, queries };
149
+ }
150
+
151
+ // The deductive closure of a formula: its own triples, rules included, and
152
+ // those its rules derive, run as a program of its own.
153
+ const CLOSURE_LIMITS = { maxDepth: 1000000, maxIterations: 100000, maxInferences: 100000000 };
154
+
155
+ export function closure(formula) {
156
+ const { program } = compileN3Document({ triples: formula.triples, prefixes: new Map() }, { source: 'a formula' });
157
+ const result = run(loadText(program, 'formula.js'), CLOSURE_LIMITS);
158
+ const derived = triplesFromEyemind(result.answers.join('\n')).triples;
159
+ return { t: 'graph', triples: [...formula.triples, ...derived.map(([s, p, o]) => ({ s: fromEyemind(s), p: fromEyemind(p), o: fromEyemind(o) }))], scope: formula.scope };
160
+ }
161
+
162
+ // An eyemind conclusion as the parsed term n3-to-eyemind wrote it from. A
163
+ // blank node keeps its label, and a Skolem term becomes one labelled by its
164
+ // text, the same for the same firing.
165
+ function fromEyemind(t) {
166
+ if (typeof t === 'bigint') return { t: 'int', v: t };
167
+ if (typeof t === 'number') return { t: 'float', v: t };
168
+ if (t === '[]') return { t: 'list', items: [] };
169
+ if (!(t instanceof Struct)) throw new N3CompileError(`a closure holds a term N3 cannot state: ${write(t)}`);
170
+ const [a, b, c] = t.args;
171
+ switch (`${t.name}/${t.args.length}`) {
172
+ case 'iri/1': return { t: 'iri', v: a };
173
+ case 'bnode/2': return { t: 'bnode', v: b, scope: 0 };
174
+ case 'skolem/3': return { t: 'bnode', v: write(t), scope: 0 };
175
+ case 'qvar/1': return { t: 'var', v: a };
176
+ case 'qbnode/1': return { t: 'bnode', v: a, scope: 0 };
177
+ case 'triple/3': return { t: 'triple', s: fromEyemind(a), p: fromEyemind(b), o: fromEyemind(c) };
178
+ case 'literal/2':
179
+ if (b instanceof Struct && b.name === 'lang') return { t: 'literal', v: a, lang: b.args[0], dir: b.args[1] ?? null, dt: '' };
180
+ return { t: 'literal', v: a, dt: b.args[0] };
181
+ case 'graph/1': return { t: 'graph', triples: listOf(a).map((x) => ({ s: fromEyemind(x.args[0]), p: fromEyemind(x.args[1]), o: fromEyemind(x.args[2]) })), scope: 0 };
182
+ case './2': return { t: 'list', items: listOf(t).map(fromEyemind) };
183
+ default: throw new N3CompileError(`a closure holds a term N3 cannot state: ${write(t)}`);
184
+ }
185
+ }
186
+
187
+ function listOf(t) {
188
+ const items = [];
189
+ for (; t instanceof Struct && t.name === '.'; t = t.args[1]) items.push(t.args[0]);
190
+ return items;
191
+ }
192
+
193
+ // Whether any term of the triples, at any depth, is the IRI.
194
+ function mentions(triples, iri) {
195
+ const term = (t) => (t.t === 'iri' ? t.v === iri : t.t === 'graph' ? mentions(t.triples, iri)
196
+ : t.t === 'list' ? t.items.some(term) : t.t === 'triple' ? [t.s, t.p, t.o].some(term) : false);
197
+ return triples.some((x) => [x.s, x.p, x.o].some(term));
198
+ }
199
+
200
+ function usesPredicate(triples, iri) {
201
+ return triples.some((x) => (x.p.t === 'iri' && x.p.v === iri) || [x.s, x.o].some((t) => termUses(t, iri)));
202
+ }
203
+ function termUses(t, iri) {
204
+ if (t.t === 'graph') return usesPredicate(t.triples, iri);
205
+ if (t.t === 'list') return t.items.some((x) => termUses(x, iri));
206
+ return false;
207
+ }
208
+
209
+ // The plain strings the document's own facts state, each once.
210
+ function statedStrings(triples) {
211
+ const found = new Map();
212
+ const visit = (t) => {
213
+ if (t.t === 'literal' && t.dt === `${XSD}string`) found.set(t.v, t);
214
+ else if (t.t === 'list') t.items.forEach(visit);
215
+ };
216
+ for (const x of triples) [x.s, x.o].forEach(visit);
217
+ return [...found.values()];
218
+ }
219
+
220
+ // The formulas the document's own facts state, each once, outermost first.
221
+ function statedFormulas(triples) {
222
+ const found = [];
223
+ const visit = (t) => {
224
+ if (t.t === 'graph') found.push(t);
225
+ else if (t.t === 'list') t.items.forEach(visit);
226
+ };
227
+ for (const x of triples) {
228
+ const rule = x.p.t === 'iri' && [`${LOG}implies`, `${LOG}impliedBy`, `${LOG}query`].includes(x.p.v) && isFormulaLike(x.s) && isFormulaLike(x.o);
229
+ if (!rule) [x.s, x.o].forEach(visit);
230
+ }
231
+ return found;
232
+ }
233
+
234
+ const RULE_PREDICATES = new Set([`${LOG}implies`, `${LOG}impliedBy`]);
235
+
236
+ // Whether a pattern, at any depth of quoted formulas, has a variable predicate.
237
+ function variablePredicate(triples) {
238
+ const term = (t) => (t.t === 'graph' ? variablePredicate(t.triples) : t.t === 'list' ? t.items.some(term) : false);
239
+ return triples.some((x) => x.p.t === 'var' || x.p.t === 'bnode' || term(x.s) || term(x.o));
240
+ }
241
+
242
+ const isFormulaLike = (t) => t.t === 'graph' || (t.t === 'literal' && t.dt === `${XSD}boolean`);
243
+ const isTrue = (t) => t.t === 'literal' && t.dt === `${XSD}boolean` && t.v === 'true';
244
+ const isFalse = (t) => t.t === 'literal' && t.dt === `${XSD}boolean` && t.v === 'false';
245
+ const triplesOf = (t) => (t.t === 'graph' ? t.triples : []);
246
+
247
+ // The definitions a program's built-ins need, each once, helpers first.
248
+ function libraryText(needed) {
249
+ const done = new Set();
250
+ const out = [];
251
+ const visit = (name, entry) => {
252
+ if (done.has(name)) return;
253
+ done.add(name);
254
+ for (const dep of entry.needs ?? []) visit(dep, HELPERS[dep]);
255
+ if (entry.text) out.push(entry.text.trim());
256
+ };
257
+ for (const name of [...needed].sort()) visit(name, BUILTINS.get(name) ?? HELPERS[name]);
258
+ return out.join('\n');
259
+ }
260
+
261
+ // Naming for one clause: variables for ?names and, in rules, blank nodes.
262
+ class Context {
263
+ constructor(inRule) {
264
+ this.inRule = inRule;
265
+ this.names = new Map();
266
+ this.used = new Set();
267
+ this.anonymous = new Set();
268
+ this.anonCount = 0;
269
+ this.quoted = null;
270
+ }
271
+
272
+ name(key, hint) {
273
+ if (this.names.has(key)) return this.names.get(key);
274
+ let base;
275
+ if (this.anonymous.has(key)) {
276
+ // A variable only a negation mentions: _N names are anonymous to it.
277
+ do base = `_${++this.anonCount}`; while (this.used.has(base));
278
+ } else {
279
+ base = hint.replace(/[^A-Za-z0-9_]/g, '_');
280
+ if (/^[a-z]/.test(base)) base = base[0].toUpperCase() + base.slice(1);
281
+ if (!/^[A-Z]/.test(base) || RESERVED.has(base) || base.startsWith('VAR_')) base = `V${base}`;
282
+ let name = base;
283
+ for (let k = 2; this.used.has(name); k++) name = `${base}_${k}`;
284
+ base = name;
285
+ }
286
+ this.used.add(base);
287
+ this.names.set(key, base);
288
+ return base;
289
+ }
290
+
291
+ term(t) {
292
+ if (this.quoted && (t.t === 'var' || (t.t === 'bnode' && this.inRule))) {
293
+ const key = t.t === 'var' ? `v:${t.v}` : bnodeKey(t);
294
+ if (this.quoted.has(key)) return t.t === 'var' ? `qvar(${q(t.v)})` : `qbnode(${q(t.v.replace(/^#/, 'b'))})`;
295
+ }
296
+ switch (t.t) {
297
+ case 'iri': return `iri(${q(t.v)})`;
298
+ // Outside rules a variable belongs to a quoted formula: a constant.
299
+ case 'var': return this.inRule ? this.name(`v:${t.v}`, t.v) : `qvar(${q(t.v)})`;
300
+ case 'bnode':
301
+ if (this.inRule) return this.name(bnodeKey(t), `B${t.v.replace(/^#/, '')}`);
302
+ return `bnode('n3', ${q(bnodeLabel(t))})`;
303
+ case 'int': return t.v >= -(2n ** 53n) && t.v <= 2n ** 53n ? String(t.v) : `${t.v}n`;
304
+ case 'float': return `float(${Object.is(t.v, -0) ? '-0' : String(t.v)})`;
305
+ case 'literal':
306
+ if (t.lang) return `literal(${q(t.v)}, ${t.dir ? `lang(${q(t.lang)}, ${q(t.dir)})` : `lang(${q(t.lang)})`})`;
307
+ return `literal(${q(t.v)}, datatype(${q(t.dt)}))`;
308
+ case 'list': return `[${t.items.map((x) => this.term(x)).join(', ')}]`;
309
+ case 'graph': return `graph([${t.triples.map((x) => this.rdf(x)).join(', ')}])`;
310
+ case 'triple': return `triple(${this.term(t.s)}, ${this.term(t.p)}, ${this.term(t.o)})`;
311
+ default: throw new N3CompileError(`unknown term ${t.t}`);
312
+ }
313
+ }
314
+
315
+ rdf(x, name = 'rdf') {
316
+ return `${name}(${this.term(x.s)}, ${this.term(x.p)}, ${this.term(x.o)})`;
317
+ }
318
+ }
319
+
320
+ const bnodeKey = (t) => `b:${t.scope}:${t.v}`;
321
+ const bnodeLabel = (t) => (t.scope === 0 ? t.v : `${t.v}.${t.scope}`);
322
+
323
+ // Variable keys a term mentions, rule blank nodes included.
324
+ function keysOf(t, out = new Set()) {
325
+ if (t.t === 'var') out.add(`v:${t.v}`);
326
+ else if (t.t === 'bnode') out.add(bnodeKey(t));
327
+ else if (t.t === 'list') t.items.forEach((x) => keysOf(x, out));
328
+ else if (t.t === 'graph') t.triples.forEach((x) => keysOfTriple(x, out));
329
+ else if (t.t === 'triple') keysOfTriple(t, out);
330
+ return out;
331
+ }
332
+ function keysOfTriple(x, out = new Set()) {
333
+ keysOf(x.s, out);
334
+ keysOf(x.p, out);
335
+ keysOf(x.o, out);
336
+ return out;
337
+ }
338
+
339
+ // Where a regular-expression built-in takes its pattern: the object, or an
340
+ // item of the subject list.
341
+ const REGEX_PATTERN = new Map([
342
+ [`${STRING}matches`, 'o'], [`${STRING}notMatches`, 'o'], [`${STRING}replace`, 1], [`${STRING}scrape`, 1],
343
+ ]);
344
+
345
+ // N3 patterns are often written for regular expressions that let any
346
+ // character be escaped, as in "\\:", and a brace stand for itself; eyemind
347
+ // reads ECMAScript patterns in Unicode mode, where neither is allowed. A
348
+ // constant pattern loses the backslash before other punctuation and has a
349
+ // brace that is no quantifier escaped, which means the same.
350
+ function unicodePattern(pattern) {
351
+ let out = '';
352
+ let inClass = false;
353
+ for (let i = 0; i < pattern.length; i++) {
354
+ const c = pattern[i];
355
+ if (c === '\\' && i + 1 < pattern.length) {
356
+ const next = pattern[++i];
357
+ // \p{L}, \P{L} and \u{1F600} keep their braces.
358
+ const braced = /^[pPu]\{[^}]*\}/.exec(pattern.slice(i));
359
+ if (braced) {
360
+ out += `\\${braced[0]}`;
361
+ i += braced[0].length - 1;
362
+ } else out += /[A-Za-z0-9^$.*+?()[\]{}|/\\-]/.test(next) ? `\\${next}` : next;
363
+ } else if (inClass) {
364
+ if (c === ']') inClass = false;
365
+ out += c;
366
+ } else if (c === '[') {
367
+ inClass = true;
368
+ out += c;
369
+ } else if (c === '{') {
370
+ const quantifier = /^\{[0-9]+(,[0-9]*)?\}/.exec(pattern.slice(i));
371
+ if (quantifier) {
372
+ out += quantifier[0];
373
+ i += quantifier[0].length - 1;
374
+ } else out += '\\{';
375
+ } else out += c === '}' ? '\\}' : c;
376
+ }
377
+ return out;
378
+ }
379
+
380
+ function withPattern(x, where) {
381
+ const fix = (t) => (t.t === 'literal' ? { ...t, v: unicodePattern(t.v) } : t);
382
+ if (where === 'o') return { ...x, o: fix(x.o) };
383
+ if (x.s.t !== 'list' || x.s.items.length <= where) return x;
384
+ const items = [...x.s.items];
385
+ items[where] = fix(items[where]);
386
+ return { ...x, s: { ...x.s, items } };
387
+ }
388
+
389
+ const SCOPED_SUBJECT = new Set([`${LOG}includes`, `${LOG}notIncludes`]);
390
+ const RDF_NS = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#';
391
+ // The argument positions where a built-in takes a list, which may be written
392
+ // out as rdf:first and rdf:rest triples.
393
+ const LIST_SUBJECT = new Set([
394
+ ...['sum', 'product', 'difference', 'quotient', 'integerQuotient', 'remainder', 'exponentiation', 'atan2', 'logarithm',
395
+ 'min', 'max'].map((n) => `${MATH}${n}`),
396
+ ...['concatenation', 'format', 'replace', 'scrape', 'substring'].map((n) => `${STRING}${n}`),
397
+ ...['dtlit', 'langlit', 'conjunction', 'skolem', 'equalTo', 'notEqualTo'].map((n) => `${LOG}${n}`),
398
+ ]);
399
+ const LIST_OBJECT = new Set([`${LOG}equalTo`, `${LOG}notEqualTo`]);
400
+ function takesList(p, position) {
401
+ // list: built-ins take lists on both sides, but for the element of
402
+ // list:in and list:member.
403
+ if (p.startsWith(LIST)) return !(position === 's' && p === `${LIST}in`) && !(position === 'o' && p === `${LIST}member`);
404
+ return position === 's' ? LIST_SUBJECT.has(p) : LIST_OBJECT.has(p);
405
+ }
406
+ const SCOPED_OBJECT = new Set([`${LOG}collectAllIn`, `${LOG}forAllIn`]);
407
+
408
+ function compileRule(body, head, kind, needed, views = true) {
409
+ const ctx = new Context(true);
410
+ if (!isFormulaLike(body)) throw new N3CompileError('a rule premise must be a formula');
411
+ const bodyTriples = triplesOf(body);
412
+ const headKeys = keysOf(head);
413
+ // A ?variable or blank node that stands only as the scope of a scoped
414
+ // built-in means the whole store, as in ?SCOPE log:notIncludes { ... }.
415
+ const scopes = scopeTerms(bodyTriples, headKeys);
416
+ const outside = (skip) => {
417
+ const keys = new Set(headKeys);
418
+ for (const x of bodyTriples) if (x !== skip) keysOfTriple(x, keys);
419
+ return keys;
420
+ };
421
+ const goals = (triples, negated) => triples.flatMap((x) => goal(x, negated));
422
+ // A body triple with variables, none of which another body triple, or an
423
+ // enclosing rule, can bind.
424
+ const unconstrained = (x) => {
425
+ const keys = keysOfTriple(x);
426
+ if (!keys.size || bodyTriples.indexOf(x) < 0 || ![x.s, x.o].every((t) => t.t === 'var' || t.t === 'bnode')) return false;
427
+ // A backward rule's caller binds its conclusion's variables.
428
+ if (kind === 'backward' && [...keys].some((key) => headKeys.has(key))) return false;
429
+ for (const y of bodyTriples) if (y !== x) for (const key of keysOfTriple(y)) if (keys.has(key)) return false;
430
+ return true;
431
+ };
432
+ // How many negations or collections the goal being compiled is inside.
433
+ let closed = 0;
434
+ let listViews = 0;
435
+ const conj = (gs) => (gs.length === 0 ? "'true'" : gs.length === 1 ? gs[0] : `[${gs.join(', ')}]`);
436
+
437
+ // Name a negated formula's own variables anonymously, so negation lets
438
+ // them stand for any value.
439
+ const markAnonymous = (formulaTerms, skip) => {
440
+ const out = outside(skip);
441
+ for (const t of formulaTerms) for (const key of keysOf(t)) if (!out.has(key) && !ctx.names.has(key)) ctx.anonymous.add(key);
442
+ };
443
+
444
+ function goal(x, negated) {
445
+ const p = x.p.t === 'iri' ? x.p.v : null;
446
+ if (p === null) return [ctx.rdf(x)];
447
+ if (UNSUPPORTED.has(p)) throw new N3CompileError(`${shortName(p)} is not supported: eyemind has no ${UNSUPPORTED.get(p)}`);
448
+ if (SCOPED_SUBJECT.has(p)) {
449
+ const neg = p === `${LOG}notIncludes`;
450
+ if (x.o.t !== 'graph') {
451
+ // A formula only known when the rule runs; anything else, or the
452
+ // store against a formula not written out, includes nothing.
453
+ if (x.o.t !== 'var' || isScope(x.s, scopes)) return ["'fail'"];
454
+ needed.add('n3_includes');
455
+ return [`${neg ? 'n3_not_includes' : 'n3_includes'}(${ctx.term(x.s)}, ${ctx.term(x.o)})`];
456
+ }
457
+ if (neg && !negated) markAnonymous([x.o], x);
458
+ if (isScope(x.s, scopes)) {
459
+ if (neg) closed++;
460
+ const inner = goals(x.o.triples, negated || neg);
461
+ if (neg) closed--;
462
+ return neg ? [`not(${conj(inner)})`] : inner;
463
+ }
464
+ needed.add('n3_includes');
465
+ return [`${neg ? 'n3_not_includes' : 'n3_includes'}(${ctx.term(x.s)}, graph([${x.o.triples.map((y) => ctx.rdf(y)).join(', ')}]))`];
466
+ }
467
+ if (SCOPED_OBJECT.has(p)) {
468
+ // The formulas must be written in the rule: eyemind cannot call a
469
+ // formula only known when the rule runs, so such a goal fails.
470
+ const count = p === `${LOG}forAllIn` ? 2 : 3;
471
+ if (x.s.t !== 'list' || x.s.items.length !== count || x.s.items[count === 2 ? 0 : 1].t !== 'graph' ||
472
+ x.s.items[1].t !== 'graph') return ["'fail'"];
473
+ closed++;
474
+ try {
475
+ if (p === `${LOG}collectAllIn`) {
476
+ const [template, where, list] = x.s.items;
477
+ return [`findall(${ctx.term(template)}, ${conj(goals(where.triples, negated))}, ${ctx.term(list)})`];
478
+ }
479
+ const [where, then] = x.s.items;
480
+ if (!negated) markAnonymous([where, then], x);
481
+ return [`not(${conj([...goals(where.triples, true), `not(${conj(goals(then.triples, true))})`])})`];
482
+ } finally {
483
+ closed--;
484
+ }
485
+ }
486
+ if (p === `${LIST}map`) {
487
+ // ((L) P) list:map R: the objects of P for each member of L, in order,
488
+ // with the predicate inlined so its dependencies stay precise.
489
+ if (x.s.t !== 'list' || x.s.items.length !== 2) throw new N3CompileError('list:map needs a subject (List Predicate)');
490
+ needed.add('n3_member');
491
+ const [list, pred] = x.s.items.map((t) => ctx.term(t));
492
+ const [e, y] = [ctx.name(`map:e:${++ctx.anonCount}`, 'E_map'), ctx.name(`map:y:${ctx.anonCount}`, 'Y_map')];
493
+ return [`findall(${y}, [n3_member(${e}, ${list}), rdf(${e}, ${pred}, ${y})], ${ctx.term(x.o)})`];
494
+ }
495
+ if (p === `${LOG}parsedAsN3`) {
496
+ // A string written in the rule is parsed now, and compared with the
497
+ // object as a formula; one known when the rule runs is looked up among
498
+ // the strings the document states, parsed now too; text that is not
499
+ // N3 gives no formula.
500
+ if (x.s.t !== 'literal') {
501
+ needed.add(p);
502
+ return [`n3_log_parsedAsN3(${ctx.term(x.s)}, ${ctx.term(x.o)})`];
503
+ }
504
+ let parsed;
505
+ try {
506
+ parsed = parseN3(x.s.v);
507
+ } catch (error) {
508
+ if (error instanceof N3SyntaxError) return ["'fail'"];
509
+ throw error;
510
+ }
511
+ needed.add(`${LOG}equalTo`);
512
+ return [`n3_log_equalTo(${new Context(false).term({ t: 'graph', triples: parsed.triples, scope: 1 })}, ${ctx.term(x.o)})`];
513
+ }
514
+ if ((p === `${LOG}equalTo` || p === `${LOG}notEqualTo`) && [x.s, x.o].some((t) => !['var', 'bnode', 'graph', 'list'].includes(t.t))) {
515
+ // A constant that is no formula: equality is unification.
516
+ return [`${p === `${LOG}equalTo` ? 'unify' : 'not_unify'}(${ctx.term(x.s)}, ${ctx.term(x.o)})`];
517
+ }
518
+ if (p === `${LOG}conclusion` && x.s.t === 'graph') {
519
+ // A formula written in the rule, sharing no variable with it, has its
520
+ // closure worked out now.
521
+ const out = outside(x);
522
+ if (![...keysOf(x.s)].some((key) => out.has(key))) {
523
+ needed.add(p);
524
+ return [`n3_conclusion_result(${new Context(false).term(closure(x.s))}, ${ctx.term(x.o)})`];
525
+ }
526
+ }
527
+ if (REGEX_PATTERN.has(p)) x = withPattern(x, REGEX_PATTERN.get(p));
528
+ const builtin = BUILTINS.get(p);
529
+ if (builtin && !negated && !closed && unconstrained(x)) {
530
+ // Every variable of the built-in is unbound and no other goal of the
531
+ // premise mentions it: nothing can be computed, and the goal holds
532
+ // without binding anything, as in N3 reasoners.
533
+ return [];
534
+ }
535
+ if (builtin) {
536
+ if (builtin.text) needed.add(p);
537
+ // A list a built-in receives may be written out as rdf:first and
538
+ // rdf:rest triples; n3_as_list reads it as a list, and passes anything
539
+ // else on as it is. Inside a negation or collection it would make the
540
+ // rule depend on every rule that concludes such triples, so there it
541
+ // is left out.
542
+ const viewGoals = [];
543
+ const arg = (t, item = false) => {
544
+ // The items of a written list may be written-out lists too.
545
+ if (t.t === 'list' && views && !item && !closed && takesList(p, position)) return `[${t.items.map((i) => arg(i, true)).join(', ')}]`;
546
+ if (!views || closed || !takesList(p, position) || (t.t !== 'var' && t.t !== 'bnode')) return ctx.term(t);
547
+ needed.add('n3_as_list');
548
+ const key = `list:${++listViews}`;
549
+ ctx.anonymous.add(key);
550
+ const view = ctx.name(key, 'L');
551
+ viewGoals.push(`n3_as_list(${ctx.term(t)}, ${view})`);
552
+ return view;
553
+ };
554
+ let position = 's';
555
+ const s = arg(x.s);
556
+ position = 'o';
557
+ const o = arg(x.o);
558
+ return [...viewGoals, `${builtin.goal}(${s}, ${o})`];
559
+ }
560
+ return [ctx.rdf(x)];
561
+ }
562
+
563
+ // A backward rule's conclusion arrives bound from the goal that calls it.
564
+ const premise = conj(goals(reorder(bodyTriples, outside, kind === 'backward' ? headKeys : new Set()), false));
565
+
566
+ if (isFalse(head)) return [`contradiction(${premise})`];
567
+ const headTriples = triplesOf(head);
568
+ if (headTriples.length === 0) return [];
569
+ if (kind === 'backward') {
570
+ return headTriples.map((h) => `implied_by(${ctx.rdf(h)}, ${premise})`);
571
+ }
572
+ const heads = headTriples.flatMap((h) => headTerm(h, kind));
573
+ return [`implies(${premise}, ${heads.length === 1 ? heads[0] : `[${heads.join(', ')}]`})`];
574
+
575
+ // A conclusion: a triple, or a rule the firing states. captured holds the
576
+ // variables the enclosing premises bind; a derived rule's conclusion may
577
+ // state rules in turn.
578
+ function headTerm(h, k, captured = null) {
579
+ const p = h.p.t === 'iri' ? h.p.v : null;
580
+ if (k === 'forward' && (p === `${LOG}implies` || p === `${LOG}impliedBy`) && isFormulaLike(h.s) && isFormulaLike(h.o)) {
581
+ const [b, c] = p === `${LOG}implies` ? [h.s, h.o] : [h.o, h.s];
582
+ const inner = conj(goals(triplesOf(b), false));
583
+ const cs = triplesOf(c);
584
+ if (cs.length === 0) throw new N3CompileError('a derived rule needs a conclusion');
585
+ if (captured === null) {
586
+ captured = new Set();
587
+ for (const x of bodyTriples) if (!(BUILTINS.has(x.p.v) && unconstrained(x))) keysOfTriple(x, captured);
588
+ }
589
+ // The firing also concludes the rule as a triple, its own variables
590
+ // quoted as qvar(Name) and qbnode(Label), as N3 reasoners report derived rules.
591
+ ctx.quoted = new Set([...keysOfTriple(h)].filter((key) => !captured.has(key)));
592
+ const asTriple = ctx.rdf(h);
593
+ ctx.quoted = null;
594
+ if (p === `${LOG}impliedBy`) return [...cs.map((y) => `implied_by(${ctx.rdf(y)}, ${inner})`), asTriple];
595
+ const within = new Set(captured);
596
+ keysOf(b, within);
597
+ const conclusions = cs.flatMap((y) => headTerm(y, k, within));
598
+ return [`implies(${inner}, ${conclusions.length === 1 ? conclusions[0] : `[${conclusions.join(', ')}]`})`, asTriple];
599
+ }
600
+ return [ctx.rdf(h, k === 'query' ? 'result' : 'rdf')];
601
+ }
602
+ }
603
+
604
+ // Built-ins that only test their arguments; the others compute their object
605
+ // from their subject.
606
+ const TESTS = new Set([
607
+ ...['greaterThan', 'lessThan', 'notGreaterThan', 'notLessThan', 'equalTo', 'notEqualTo'].map((n) => `${MATH}${n}`),
608
+ ...['greaterThan', 'lessThan', 'notGreaterThan', 'notLessThan', 'equalTo', 'notEqualTo', 'contains', 'containsIgnoringCase',
609
+ 'startsWith', 'endsWith', 'equalIgnoringCase', 'notEqualIgnoringCase'].map((n) => `${STRING}${n}`),
610
+ `${LOG}notEqualTo`, `${LOG}notIncludes`, `${LOG}forAllIn`, `${LIST}notMember`,
611
+ ]);
612
+ const INLINE = new Set([`${LIST}map`]);
613
+ // Built-ins that also run from a bound object to their subject.
614
+ const REVERSIBLE = new Set([`${LIST}firstRest`, `${LIST}append`, `${LOG}uri`, `${LOG}dtlit`, `${LOG}langlit`,
615
+ ...['negation', 'sin', 'cos', 'tan', 'asin', 'acos', 'atan', 'sinh', 'cosh', 'tanh', 'degrees', 'radians'].map((n) => `${MATH}${n}`)]);
616
+
617
+ // Body triples in evaluation order. A built-in waits for the goals after it
618
+ // that bind its inputs (a test's every variable, another built-in's
619
+ // subject): ordinary triples, and built-ins that compute their object, so
620
+ // { ?a log:notEqualTo ?b. ?x :p ?a. ?y :p ?b } compares bound values and
621
+ // { (?x 1) math:sum ?y. (1 2 3) list:iterate (?i ?x) } adds to a bound ?x.
622
+ // Otherwise the written order stays.
623
+ function reorder(triples, outside, given) {
624
+ const isPlain = (x) => x.p.t !== 'iri' || (!BUILTINS.has(x.p.v) && !INLINE.has(x.p.v) && !TESTS.has(x.p.v) && !SCOPED_SUBJECT.has(x.p.v) && !SCOPED_OBJECT.has(x.p.v));
625
+ const inputs = (x) => {
626
+ if (isPlain(x)) return new Set();
627
+ const p = x.p.v;
628
+ if (p === `${LOG}includes` || p === `${LOG}equalTo`) return new Set();
629
+ // Only variables shared with the rest of the rule are inputs; a
630
+ // collection's are those of its template and formula.
631
+ const out = outside(x);
632
+ const keys = TESTS.has(p) ? keysOfTriple(x) : p === `${LOG}collectAllIn` ? keysOf({ t: 'list', items: x.s.items?.slice(0, 2) ?? [] }) : keysOf(x.s);
633
+ return new Set([...keys].filter((k) => out.has(k)));
634
+ };
635
+ const order = [];
636
+ const bound = new Set(given);
637
+ // What the premise itself binds: a backward rule's conclusion is usually,
638
+ // but not always, bound by its caller, too weak a ground to run a
639
+ // built-in backward on.
640
+ const placed = new Set();
641
+ const pending = [];
642
+ // What a goal binds: an ordinary triple its variables, a test nothing, a
643
+ // collection its list, and another built-in its object.
644
+ const binds = (x, keys) => {
645
+ if (isPlain(x)) return keysOfTriple(x, keys);
646
+ const p = x.p.v;
647
+ if (TESTS.has(p) || SCOPED_SUBJECT.has(p)) return keys;
648
+ if (p === `${LOG}collectAllIn`) return x.s.t === 'list' && x.s.items[2] ? keysOf(x.s.items[2], keys) : keys;
649
+ // One that also runs backward binds in the direction the premise
650
+ // supports: its object once its subject is bound, its subject once
651
+ // other goals of the premise bind its object, and otherwise nothing.
652
+ if (REVERSIBLE.has(p)) {
653
+ const others = later(0, x);
654
+ const known = (key) => bound.has(key) || others.has(key);
655
+ if ([...keysOf(x.s)].every(known)) return keysOf(x.o, keys);
656
+ if ([...keysOf(x.o)].every((key) => placed.has(key) || others.has(key))) return keysOf(x.s, keys);
657
+ return keys;
658
+ }
659
+ return keysOf(x.o, keys);
660
+ };
661
+ // What the goals from position i bind, leaving one out and leaving out
662
+ // those that also run backward, which keeps this from looping.
663
+ const later = (i, skip = null) => {
664
+ const keys = new Set();
665
+ for (let k = i; k < triples.length; k++) {
666
+ const y = triples[k];
667
+ if (y !== skip && !(REVERSIBLE.has(y.p.v ?? '') && !isPlain(y))) binds(y, keys);
668
+ }
669
+ return keys;
670
+ };
671
+ const place = (x) => {
672
+ order.push(x);
673
+ keysOfTriple(x, bound);
674
+ keysOfTriple(x, placed);
675
+ };
676
+ triples.forEach((x, i) => {
677
+ if (isPlain(x)) place(x);
678
+ else pending.push(x);
679
+ const rest = new Set();
680
+ for (let k = i + 1; k < triples.length; k++) binds(triples[k], rest);
681
+ for (let k = 0; k < pending.length;) {
682
+ const x = pending[k];
683
+ // It waits for later goals, and for pending ones, that bind its inputs.
684
+ const binders = new Set(rest);
685
+ for (const y of pending) if (y !== x) binds(y, binders);
686
+ const coming = (keys) => [...keys].some((key) => !bound.has(key) && binders.has(key));
687
+ // One that also runs backward is ready once either side is bound,
688
+ // and otherwise waits for whatever binds either side.
689
+ const reversible = REVERSIBLE.has(x.p.v);
690
+ const ready = reversible && ([...keysOf(x.s)].every((key) => bound.has(key)) || [...keysOf(x.o)].every((key) => placed.has(key)));
691
+ const waiting = !ready && (coming(inputs(x)) || (reversible && coming(keysOf(x.o))));
692
+ if (waiting) { k++; continue; }
693
+ place(pending.splice(k, 1)[0]);
694
+ k = 0;
695
+ }
696
+ });
697
+ return [...order, ...pending];
698
+ }
699
+
700
+ function scopeTerms(triples, headKeys) {
701
+ const candidates = new Map();
702
+ const elsewhere = new Set(headKeys);
703
+ for (const x of triples) {
704
+ const p = x.p.t === 'iri' ? x.p.v : null;
705
+ let scope = null;
706
+ if (SCOPED_SUBJECT.has(p) && (x.s.t === 'var' || x.s.t === 'bnode')) scope = x.s;
707
+ if (SCOPED_OBJECT.has(p) && (x.o.t === 'var' || x.o.t === 'bnode')) scope = x.o;
708
+ for (const t of [x.s, x.p, x.o]) {
709
+ if (t === scope) candidates.set([...keysOf(t)][0], true);
710
+ else keysOf(t, elsewhere);
711
+ }
712
+ }
713
+ return new Set([...candidates.keys()].filter((k) => !elsewhere.has(k)));
714
+ }
715
+
716
+ // A number or other constant scope, as in 1 log:notIncludes { ... }, also
717
+ // means the store.
718
+ const isScope = (t, scopes) => ((t.t === 'var' || t.t === 'bnode') ? scopes.has([...keysOf(t)][0]) : !['graph', 'list'].includes(t.t));
719
+
720
+ const SHORT = [['http://www.w3.org/2000/10/swap/', ''], [XSD, 'xsd:']];
721
+ function shortName(iri) {
722
+ for (const [ns, pre] of SHORT) {
723
+ if (iri.startsWith(ns)) {
724
+ const rest = iri.slice(ns.length);
725
+ return pre ? pre + rest : rest.replace('#', ':');
726
+ }
727
+ }
728
+ return `<${iri}>`;
729
+ }
730
+
731
+ // N3 sources, given as [text, name] pairs, read as one document: { triples,
732
+ // prefixes }. base resolves relative IRIs; blank-node labels are local to
733
+ // each source. RDF sources, given as { quads, prefixes }, join as triples.
734
+ export function readSources(sources, { base = '', baseOf = () => '' } = {}) {
735
+ if (typeof sources === 'string') sources = [[sources, 'input']];
736
+ const docs = sources.map((source) => (Array.isArray(source)
737
+ ? parseN3(source[0], { base: base || baseOf(source[1]) })
738
+ : { triples: source.quads.map(rdfQuadToN3), prefixes: new Map(Object.entries(source.prefixes ?? {})) }));
739
+ const doc = { triples: [], prefixes: new Map() };
740
+ docs.forEach((d, k) => {
741
+ doc.triples.push(...(docs.length > 1 ? relabel(d.triples, `s${k}.`) : d.triples));
742
+ for (const [name, ns] of d.prefixes) if (!doc.prefixes.has(name)) doc.prefixes.set(name, ns);
743
+ });
744
+ return doc;
745
+ }
746
+
747
+ // A document's program: { program, documents }; readFile reads the
748
+ // documents it names for log:semantics and log:content.
749
+ export function compileSources(sources, { base = '', baseOf, readFile = null, source } = {}) {
750
+ const doc = readSources(sources, { base, baseOf });
751
+ const documents = readDocuments(documentIris(doc.triples), readFile);
752
+ const { program } = compileN3Document(doc, { source: source ?? sourceNames(sources), documents });
753
+ return { doc, program };
754
+ }
755
+
756
+ const sourceNames = (sources) => (typeof sources === 'string' ? 'input' : sources.map((s) => (Array.isArray(s) ? s[1] : 'data')).join(', '));
757
+
758
+ // The triples of eyemind answers as N3: the derived ones, every triple with
759
+ // mode 'all', and the document's own log:outputString strings when the
760
+ // result writes strings.
761
+ export function answersToN3(doc, answers, { mode = 'new', strings = 'auto' } = {}) {
762
+ let { triples, contradiction } = triplesFromEyemind(answers.join('\n'));
763
+ const given = doc.triples.filter((x) => !isRule(x)).map(tripleToEyemind);
764
+ if (mode === 'all') triples = [...given, ...triples];
765
+ else if (strings !== false && triples.some(isOutputString)) triples = [...given.filter(isOutputString), ...triples];
766
+ return { n3: writeN3(triples, { prefixes: doc.prefixes, strings }), triples, contradiction };
767
+ }
768
+
769
+ // Generous bounds: N3 programs often run longer than eyemind's defaults.
770
+ export const N3_LIMITS = { maxDepth: 1000000, maxIterations: 100000, maxInferences: 1000000000 };
771
+
772
+ // Reason over N3 sources. Returns { n3, triples, contradiction, program,
773
+ // result }; with proof, result.proof is eyemind's checked proof of the
774
+ // compiled program.
775
+ export function reasonN3(sources, { base = '', mode = 'new', strings = 'auto', limits = {}, proof = false, goals = [], readFile = null } = {}) {
776
+ const { doc, program } = compileSources(sources, { base, readFile });
777
+ const result = run(loadText(program, 'compiled.js'), { ...N3_LIMITS, ...limits, proof, goals });
778
+ return { ...answersToN3(doc, result.answers, { mode, strings }), program, result };
779
+ }
780
+
781
+ const RULE_IRIS = new Set([`${LOG}implies`, `${LOG}impliedBy`, `${LOG}query`]);
782
+ const isRule = (x) => x.p.t === 'iri' && RULE_IRIS.has(x.p.v) && (x.s.t === 'graph' || x.s.t === 'literal') && (x.o.t === 'graph' || x.o.t === 'literal');
783
+ const isOutputString = ([, p]) => p instanceof Struct && p.name === 'iri' && p.args[0] === `${LOG}outputString`;
784
+
785
+ function relabel(triples, prefix) {
786
+ const term = (t) => {
787
+ if (t.t === 'bnode') return { ...t, v: prefix + t.v };
788
+ if (t.t === 'list') return { ...t, items: t.items.map(term) };
789
+ if (t.t === 'graph') return { ...t, triples: t.triples.map(triple) };
790
+ if (t.t === 'triple') return triple(t);
791
+ return t;
792
+ };
793
+ const triple = (x) => ({ ...x, s: term(x.s), p: term(x.p), o: term(x.o) });
794
+ return triples.map(triple);
795
+ }
796
+
797
+ // An RDF quad, read by rdf.js, as an N3 triple; N3 has no named graphs.
798
+ function rdfQuadToN3([s, p, o, g]) {
799
+ if (g !== 'default_graph') throw new N3CompileError('N3 has no named graphs; give the data as Turtle or N-Triples');
800
+ const term = (t) => {
801
+ if (typeof t === 'bigint') return { t: 'int', v: t };
802
+ const [a, b, c] = t.args;
803
+ switch (t.name) {
804
+ case 'iri': return { t: 'iri', v: a };
805
+ case 'bnode': return { t: 'bnode', v: `${a}.${b}`, scope: 0 };
806
+ case 'triple': return { t: 'triple', s: term(a), p: term(b), o: term(c) };
807
+ case 'literal':
808
+ if (b.name === 'lang') return { t: 'literal', v: a, lang: b.args[0], dir: b.args[1] ?? null, dt: `${RDF_NS}langString` };
809
+ return typedLiteral(a, b.args[0]);
810
+ default: throw new N3CompileError(`${write(t)} is no RDF term`);
811
+ }
812
+ };
813
+ return { s: term(s), p: term(p), o: term(o) };
814
+ }