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/srl.js ADDED
@@ -0,0 +1,649 @@
1
+ // SPARQL 1.2 RL rule sets compiled to eyemind programs.
2
+ //
3
+ // Rule sets are read by eyeleng's tokenizer, parser and analysis (the
4
+ // srl-*.js files): parsing gives the rule set's data blocks and rules, and the
5
+ // analysis checks sequential variable scope and stratification by the
6
+ // specification's open and closed dependencies.
7
+ //
8
+ // Every RDF triple is rdf(Subject, Predicate, Object), the union of the two
9
+ // graphs a rule body matches. base(S, P, O) marks the base graph, the RDF
10
+ // data a run is given, and inf(S, P, O) the inference graph, which starts
11
+ // with the rule set's DATA blocks and grows with rule conclusions; the
12
+ // conclusions of a run are the inference graph:
13
+ //
14
+ // DATA { T } fact(rdf(T), inf(T))
15
+ // base data T rdf(T) and base(T), by facts_from
16
+ // RULE { H } WHERE { B } implies(B, [rdf(H), inf(H)])
17
+ // RULE { H } WHERE DATA { B } B matches base(T) instead of rdf(T)
18
+ // NOT { P } not(srl_not_N(Bound...)), with
19
+ // implied_by(srl_not_N(Bound...), P)
20
+ // FILTER(E), SET(?v := E) goals that bind E's value
21
+ // GROUP BY ?k { P } [ ?a := F ] findall over P, then the aggregate
22
+ //
23
+ // A blank node in a rule head is a variable only the conclusion mentions,
24
+ // so eyemind makes it the Skolem term of the firing; the extra conclusion
25
+ // srl_solution([Values...]) makes every solution of the body its own firing.
26
+ // eyemind's stratification orders negations and collections after what
27
+ // they inspect. A run-once rule (one with SET, GROUP, a head blank node or a
28
+ // head triple term with variables) needs no more: the rule set's analysis
29
+ // has rejected those that depend on their own conclusions, and the others
30
+ // conclude the same when they run alongside what they read, because SET and
31
+ // Skolem terms give the same values in every round.
32
+ import { analyze } from './srl-analyze.js';
33
+ import { BUILTIN_SIGNATURES, canonicalBuiltinName } from './srl-builtin-names.js';
34
+ import { libraryText } from './srl-functions.js';
35
+ import { Parser } from './srl-parser.js';
36
+ import { run } from './engine.js';
37
+ import { loadText } from './lang.js';
38
+ import { DEFAULT_GRAPH } from './rdf.js';
39
+ import { readTerms } from './reader.js';
40
+ import { Struct } from './terms.js';
41
+ import { write } from './writer.js';
42
+
43
+ export class SrlError extends Error {}
44
+
45
+ // A rule set as data blocks and rules: { baseIRI, prefixes, imports, data,
46
+ // rules }. strictGrammar follows the SPARQL 1.2 RL grammar exactly.
47
+ export function parseRuleSet(text, { base = null, filename = '<input>' } = {}) {
48
+ return new Parser(String(text), { baseIRI: base, filename, strictGrammar: true }).parseProgram();
49
+ }
50
+
51
+ // A rule set with its imports resolved and its rules analyzed. resolve(IRI,
52
+ // from) returns an imported rule set's text, or null; without it a rule set
53
+ // with IMPORTS is an error. Analysis errors (an unbound variable, a
54
+ // recursive closed dependency) throw an SrlError listing them.
55
+ export function readRuleSet(text, { base = null, filename = '<input>', resolve = null, checkStratification = true } = {}) {
56
+ const program = withImports(parseRuleSet(text, { base, filename }), { filename, resolve, seen: new Set() });
57
+ const analysis = analyze(program, { checkStratification });
58
+ if (analysis.errors.length > 0) {
59
+ throw new SrlError(analysis.errors.map((d) => d.message).join('; '));
60
+ }
61
+ return program;
62
+ }
63
+
64
+ // IMPORTS incorporates other rule sets, their data blocks included; each is
65
+ // read once, so cyclic imports end.
66
+ function withImports(program, { filename, resolve, seen }) {
67
+ seen.add(program.baseIRI || filename);
68
+ if (program.imports.length === 0) return program;
69
+ if (!resolve) throw new SrlError(`${filename} has IMPORTS, but no import resolver is given`);
70
+ const merged = { ...program, imports: [], prefixes: {}, data: [], rules: [] };
71
+ for (const target of program.imports) {
72
+ if (seen.has(target)) continue;
73
+ seen.add(target);
74
+ const source = resolve(target, program.baseIRI || filename);
75
+ if (source == null) throw new SrlError(`IMPORTS <${target}> could not be read`);
76
+ const imported = withImports(new Parser(String(source), { baseIRI: target, filename: target, strictGrammar: true }).parseProgram(),
77
+ { filename: target, resolve, seen });
78
+ Object.assign(merged.prefixes, imported.prefixes);
79
+ merged.data.push(...imported.data);
80
+ merged.rules.push(...imported.rules);
81
+ }
82
+ Object.assign(merged.prefixes, program.prefixes);
83
+ merged.data.push(...program.data);
84
+ merged.rules.push(...program.rules);
85
+ return merged;
86
+ }
87
+
88
+ const XSD = 'http://www.w3.org/2001/XMLSchema#';
89
+
90
+ // A term or atom text as a JavaScript string literal.
91
+ const q = (text) => JSON.stringify(text);
92
+
93
+ const RESERVED = new Set(['Math', 'JSON', 'BigInt', 'Infinity', 'NaN', 'undefined', 'console', 'globalThis',
94
+ 'parseInt', 'parseFloat', 'isNaN', 'isFinite', 'Object', 'Array', 'String', 'Number', 'Boolean', 'Symbol',
95
+ 'Date', 'RegExp', 'Error', 'Map', 'Set', 'Promise', 'Reflect', 'Proxy']);
96
+
97
+ // Compile a rule set's text. Options: base (IRI), filename, resolve (for
98
+ // IMPORTS, see readRuleSet), data (the base graph, as RDF quads from
99
+ // parseRdf, in its default graph). Returns { program, prefixes, warnings }.
100
+ export function compileSrl(text, { base = null, filename = '<input>', resolve = null, data = [] } = {}) {
101
+ const ruleSet = readRuleSet(text, { base, filename, resolve });
102
+ return compileRuleSet(ruleSet, { data, source: filename });
103
+ }
104
+
105
+ // Compile a parsed rule set over a base graph of RDF quads.
106
+ export function compileRuleSet(ruleSet, { data = [], source = '<input>' } = {}) {
107
+ const needed = new Set();
108
+ const warnings = [];
109
+ const lines = [
110
+ `// Generated by eyemind from ${String(source).replace(/[\r\n]/g, ' ')}, a SPARQL 1.2 RL rule set.`,
111
+ '// Each RDF triple is rdf(Subject, Predicate, Object); base(S, P, O) is the',
112
+ '// base graph and inf(S, P, O) the inference graph, the conclusions.',
113
+ ];
114
+ if (data.some((q) => q[3] !== DEFAULT_GRAPH)) throw new SrlError('the base graph is one graph; give the data as Turtle or N-Triples');
115
+ if (data.length) {
116
+ // Through facts_from, as document text, so integers of any size are exact.
117
+ const document = data.flatMap(([S, P, O]) => [write(new Struct('rdf', [S, P, O])), write(new Struct('base', [S, P, O]))]);
118
+ lines.push(`facts_from({ text: ${JSON.stringify(document.join('\n'))} })`);
119
+ }
120
+ const terms = new Terms('srl');
121
+ for (const t of ruleSet.data) lines.push(`fact(${terms.rdf(t, 'rdf')}, ${terms.rdf(t, 'inf')})`);
122
+ ruleSet.rules.forEach((rule, index) => {
123
+ lines.push(...new RuleCompiler(rule, index + 1, { needed, warnings }).compile());
124
+ });
125
+ lines.push('query(inf(S, P, O))');
126
+ const library = libraryText(needed);
127
+ if (library) lines.push('', '// SPARQL functions and aggregates.', library);
128
+ return { program: `${lines.join('\n')}\n`, prefixes: ruleSet.prefixes, warnings };
129
+ }
130
+
131
+ // RDF terms as eyemind terms. Blank nodes of data are bnode(Scope, Label).
132
+ class Terms {
133
+ constructor(scope) {
134
+ this.scope = scope;
135
+ }
136
+
137
+ term(t) {
138
+ switch (t.type) {
139
+ case 'iri': return `iri(${q(t.value)})`;
140
+ case 'blank': return `bnode(${q(this.scope)}, ${q(t.value)})`;
141
+ case 'literal': return literalText(t);
142
+ case 'triple': return `triple(${this.term(t.s)}, ${this.term(t.p)}, ${this.term(t.o)})`;
143
+ default: throw new SrlError(`a ${t.type} cannot appear in data`);
144
+ }
145
+ }
146
+
147
+ rdf(t, name) {
148
+ return `${name}(${this.term(t.s)}, ${this.term(t.p)}, ${this.term(t.o)})`;
149
+ }
150
+ }
151
+
152
+ // A literal: an xsd:integer with a canonical lexical form is an integer,
153
+ // any other literal keeps its lexical form and datatype or language tag.
154
+ function literalText(t) {
155
+ if (t.lang) return `literal(${q(String(t.value))}, ${t.langDir ? `lang(${q(t.lang)}, ${q(t.langDir)})` : `lang(${q(t.lang)})`})`;
156
+ const datatype = t.datatype || `${XSD}string`;
157
+ const lexical = t.lexical ?? String(t.value);
158
+ if (datatype === `${XSD}integer` && /^(?:0|-?[1-9][0-9]*)$/.test(lexical)) {
159
+ const n = BigInt(lexical);
160
+ return n >= -(2n ** 53n) && n <= 2n ** 53n ? lexical : `${lexical}n`;
161
+ }
162
+ return `literal(${q(lexical)}, datatype(${q(datatype)}))`;
163
+ }
164
+
165
+ // One rule: its body as goals, its head as conclusions.
166
+ class RuleCompiler {
167
+ constructor(rule, number, { needed, warnings }) {
168
+ this.rule = rule;
169
+ this.number = number;
170
+ this.needed = needed;
171
+ this.warnings = warnings;
172
+ this.used = new Set();
173
+ this.helpers = [];
174
+ this.helperCount = 0;
175
+ this.terms = new Terms('srl');
176
+ }
177
+
178
+ compile() {
179
+ const { rule } = this;
180
+ if (rule.head.length === 0) return [`// Rule ${this.number} concludes nothing.`];
181
+ const scope = new Scope(this, null, rule.groundData ? 'base' : 'rdf');
182
+ const goals = this.body(rule.body, scope);
183
+ const solution = [...scope.bound].sort().map((v) => scope.name(v));
184
+ const headBlanks = new Map();
185
+ const blank = (label) => {
186
+ if (!headBlanks.has(label)) headBlanks.set(label, this.fresh(`B${label.replace(/[^A-Za-z0-9_]/g, '_')}`));
187
+ return headBlanks.get(label);
188
+ };
189
+ const term = (t) => {
190
+ if (t.type === 'var') return scope.name(t.value);
191
+ if (t.type === 'blank') return blank(t.value);
192
+ if (t.type === 'triple') return `triple(${term(t.s)}, ${term(t.p)}, ${term(t.o)})`;
193
+ return this.terms.term(t);
194
+ };
195
+ // A head triple whose predicate is no IRI is not concluded. A variable
196
+ // a body triple matched as a predicate is an IRI already.
197
+ const predicates = new Set(rule.body.filter((c) => c.type === 'triple' && c.triple.p.type === 'var').map((c) => c.triple.p.value));
198
+ const guarded = rule.head.filter((t) => t.p.type === 'var' && !predicates.has(t.p.value));
199
+ const heads = rule.head.map((t) => [`rdf(${term(t.s)}, ${term(t.p)}, ${term(t.o)})`, `inf(${term(t.s)}, ${term(t.p)}, ${term(t.o)})`]);
200
+ const out = [];
201
+ const emit = (extra, conclusions) => {
202
+ const body = [...goals, ...extra];
203
+ const conclusion = conclusions.flat();
204
+ if (headBlanks.size > 0) conclusion.push(`srl_solution([${solution.join(', ')}])`);
205
+ out.push(`implies(${body.length ? `[${body.join(', ')}]` : "'true'"}, [${conclusion.join(', ')}])`);
206
+ };
207
+ const check = (t) => `unify(${term(t.p)}, iri(_))`;
208
+ if (guarded.length === 0) emit([], heads);
209
+ else if (headBlanks.size > 0 || rule.head.length === 1) {
210
+ // Blank nodes shared between head triples need one firing.
211
+ emit([...new Set(guarded.map(check))], heads);
212
+ } else {
213
+ // Each head triple is concluded on its own, guarded when needed.
214
+ rule.head.forEach((t, k) => emit(guarded.includes(t) ? [check(t)] : [], [heads[k]]));
215
+ }
216
+ return [...this.helpers, ...out];
217
+ }
218
+
219
+ fresh(hint) {
220
+ let base = hint.replace(/[^A-Za-z0-9_]/g, '_');
221
+ if (/^[a-z]/.test(base)) base = base[0].toUpperCase() + base.slice(1);
222
+ if (!/^[A-Z]/.test(base) || RESERVED.has(base)) base = `V${base}`;
223
+ let name = base;
224
+ for (let k = 2; this.used.has(name); k++) name = `${base}_${k}`;
225
+ this.used.add(name);
226
+ return name;
227
+ }
228
+
229
+ need(name) {
230
+ this.needed.add(name);
231
+ }
232
+
233
+ // Body clauses in order, each seeing the variables earlier ones bound.
234
+ body(clauses, scope) {
235
+ const goals = [];
236
+ for (const clause of clauses) {
237
+ switch (clause.type) {
238
+ case 'triple':
239
+ goals.push(scope.pattern(clause.triple.s, clause.triple.p, clause.triple.o));
240
+ break;
241
+ case 'path':
242
+ goals.push(...scope.path(clause.triple.s, clause.triple.p, clause.triple.o));
243
+ break;
244
+ case 'filter': {
245
+ const { goals: g, value } = this.expression(clause.expr, scope);
246
+ this.need('srl_ebv');
247
+ goals.push(...g, `srl_true(${value})`);
248
+ break;
249
+ }
250
+ case 'set': {
251
+ const { goals: g, value } = this.expression(clause.expr, scope);
252
+ goals.push(...g, `unify(${scope.name(clause.variable)}, ${value})`);
253
+ scope.bind(clause.variable);
254
+ break;
255
+ }
256
+ case 'not':
257
+ goals.push(this.negation(clause, scope));
258
+ break;
259
+ case 'group':
260
+ goals.push(...this.group(clause, scope));
261
+ break;
262
+ default:
263
+ throw new SrlError(`unsupported body clause ${clause.type}`);
264
+ }
265
+ }
266
+ return goals;
267
+ }
268
+
269
+ // NOT { P } is not(srl_not_N(V...)) for the variables of P bound before
270
+ // it; the others are local to P.
271
+ negation(clause, scope) {
272
+ const name = `srl_not_${this.number}_${++this.helperCount}`;
273
+ const inner = new Scope(this, null, clause.groundData || scope.graph === 'base' ? 'base' : 'rdf');
274
+ const mentioned = new Set();
275
+ collectClauseVars(clause.body, mentioned);
276
+ const shared = [...mentioned].filter((v) => scope.bound.has(v)).sort();
277
+ for (const v of shared) inner.bind(v);
278
+ const goals = this.body(clause.body, inner);
279
+ const args = (s) => shared.map((v) => s.name(v)).join(', ');
280
+ this.helpers.push(`implied_by(${name}(${args(inner)}), ${goals.length === 1 ? goals[0] : `[${goals.join(', ')}]`})`);
281
+ return `not(${name}(${args(scope)}))`;
282
+ }
283
+
284
+ // GROUP: the pattern sees only the incoming values of its keys. Without
285
+ // BY there is one group, even when the pattern has no solutions; with BY
286
+ // there is a group per distinct value of the keys.
287
+ group(clause, scope) {
288
+ const inner = new Scope(this, scope, scope.graph, new Set(clause.keys));
289
+ for (const k of clause.keys) if (scope.bound.has(k)) inner.bind(k);
290
+ const pattern = this.body(clause.pattern, inner);
291
+ const conj = pattern.length === 0 ? "'true'" : pattern.length === 1 ? pattern[0] : `[${pattern.join(', ')}]`;
292
+ const columns = clause.aggregations.filter((a) => a.function.argument !== '*').map((a) => a.function.argument);
293
+ const distinctColumns = [...new Set(columns)];
294
+ const goals = [];
295
+ const keys = `[${clause.keys.map((k) => scope.name(k)).join(', ')}]`;
296
+ if (clause.keys.length > 0) {
297
+ // The key values are collected under names of their own, so the
298
+ // collection a proof records is the one searched.
299
+ const incoming = new Set(clause.keys.filter((k) => scope.bound.has(k)));
300
+ const own = new Scope(this, scope, scope.graph, incoming);
301
+ for (const k of incoming) own.bind(k);
302
+ const ownPattern = this.body(clause.pattern, own);
303
+ const ownConj = ownPattern.length === 0 ? "'true'" : ownPattern.length === 1 ? ownPattern[0] : `[${ownPattern.join(', ')}]`;
304
+ const all = this.fresh('Keys');
305
+ const distinct = this.fresh('Groups');
306
+ this.need('srl_distinct');
307
+ this.need('srl_member');
308
+ goals.push(`findall([${clause.keys.map((k) => own.name(k)).join(', ')}], ${ownConj}, ${all})`,
309
+ `srl_distinct(${all}, ${distinct})`, `srl_member(${keys}, ${distinct})`);
310
+ }
311
+ const rows = this.fresh('Rows');
312
+ goals.push(`findall([${distinctColumns.map((v) => inner.name(v)).join(', ')}], ${conj}, ${rows})`);
313
+ this.need('srl_aggregates');
314
+ this.need('srl_column');
315
+ for (const k of clause.keys) scope.bind(k);
316
+ for (const { variable, function: fn } of clause.aggregations) {
317
+ const target = scope.name(variable);
318
+ if (fn.argument === '*') {
319
+ goals.push(`srl_count(${rows}, ${target})`);
320
+ } else {
321
+ const column = this.fresh('Values');
322
+ goals.push(`srl_column(${rows}, ${distinctColumns.indexOf(fn.argument) + 1}, ${column})`);
323
+ const name = fn.name === 'COUNT' ? (fn.distinct ? 'srl_count_distinct' : 'srl_count') : `srl_${fn.name.toLowerCase()}`;
324
+ goals.push(`${name}(${column}, ${target})`);
325
+ }
326
+ scope.bind(variable);
327
+ }
328
+ return goals;
329
+ }
330
+
331
+ // An expression as { goals, value }: the goals bind the value's variable.
332
+ expression(expr, scope) {
333
+ switch (expr.type) {
334
+ case 'var':
335
+ return { goals: [], value: scope.name(expr.name) };
336
+ case 'literal':
337
+ if (expr.term) return { goals: [], value: literalText(expr.term) };
338
+ if (typeof expr.value === 'boolean') return { goals: [], value: `literal(${q(String(expr.value))}, datatype(${q(`${XSD}boolean`)}))` };
339
+ return { goals: [], value: `literal(${q(String(expr.value))}, datatype(${q(`${XSD}string`)}))` };
340
+ case 'term':
341
+ if (expr.value.type === 'triple' || expr.value.type === 'var') {
342
+ const term = (t) => (t.type === 'var' ? scope.name(t.value) : t.type === 'triple'
343
+ ? `triple(${term(t.s)}, ${term(t.p)}, ${term(t.o)})` : this.terms.term(t));
344
+ return { goals: [], value: term(expr.value) };
345
+ }
346
+ return { goals: [], value: this.terms.term(expr.value) };
347
+ case 'unary': {
348
+ const a = this.expression(expr.expr, scope);
349
+ const name = { '!': 'srl_not', '-': 'srl_neg', '+': 'srl_pos' }[expr.op];
350
+ return this.call(name, [a]);
351
+ }
352
+ case 'binary':
353
+ return this.binary(expr, scope);
354
+ case 'call':
355
+ return this.functionCall(expr, scope);
356
+ default:
357
+ throw new SrlError(`unsupported expression ${expr.type}`);
358
+ }
359
+ }
360
+
361
+ // A function goal over evaluated arguments.
362
+ call(name, args, need = name) {
363
+ this.need(need);
364
+ const value = this.fresh('R');
365
+ return { goals: [...args.flatMap((a) => a.goals), `${name}(${[...args.map((a) => a.value), value].join(', ')})`], value };
366
+ }
367
+
368
+ binary(expr, scope) {
369
+ const { op } = expr;
370
+ if (op === '&&' || op === '||') {
371
+ // Each side is its effective boolean value or 'error'.
372
+ const side = (e) => {
373
+ const { goals, value } = this.expression(e, scope);
374
+ const b = this.fresh('E');
375
+ this.need('srl_ebv');
376
+ const goal = goals.length === 0 ? `srl_ebv3(${value}, ${b})` : `once(or([${goals.join(', ')}, srl_ebv(${value}, ${b})], unify(${b}, 'error')))`;
377
+ return { goal, b };
378
+ };
379
+ const left = side(expr.left);
380
+ const right = side(expr.right);
381
+ const name = op === '&&' ? 'srl_and' : 'srl_or';
382
+ this.need(name);
383
+ const value = this.fresh('R');
384
+ return { goals: [left.goal, right.goal, `${name}(${left.b}, ${right.b}, ${value})`], value };
385
+ }
386
+ if (op === 'IN' || op === 'NOT IN') {
387
+ const left = this.expression(expr.left, scope);
388
+ this.need('srl_in');
389
+ const items = expr.right.items.map((item) => {
390
+ const { goals, value } = this.expression(item, scope);
391
+ const t = this.fresh('E');
392
+ return { goal: `once(or([${[...goals, `srl_equal(${left.value}, ${value}, ${t})`].join(', ')}], unify(${t}, 'error')))`, t };
393
+ });
394
+ const value = this.fresh('R');
395
+ return {
396
+ goals: [...left.goals, ...items.map((i) => i.goal), `${op === 'IN' ? 'srl_in' : 'srl_not_in'}([${items.map((i) => i.t).join(', ')}], ${value})`],
397
+ value,
398
+ };
399
+ }
400
+ const name = {
401
+ '+': 'srl_add', '-': 'srl_sub', '*': 'srl_mul', '/': 'srl_div',
402
+ '=': 'srl_eq', '!=': 'srl_ne', '<': 'srl_lt', '<=': 'srl_le', '>': 'srl_gt', '>=': 'srl_ge',
403
+ }[op];
404
+ if (!name) throw new SrlError(`unsupported operator ${op}`);
405
+ return this.call(name, [this.expression(expr.left, scope), this.expression(expr.right, scope)]);
406
+ }
407
+
408
+ functionCall(expr, scope) {
409
+ const builtin = canonicalBuiltinName(expr.name);
410
+ const args = () => expr.args.map((a) => this.expression(a, scope));
411
+ if (builtin) {
412
+ const { min, max } = BUILTIN_SIGNATURES[builtin];
413
+ if (expr.args.length < min || expr.args.length > max) {
414
+ throw new SrlError(`${builtin} takes ${min === max ? min : `${min} to ${max === Infinity ? 'any number of' : max}`} arguments, not ${expr.args.length}`);
415
+ }
416
+ return this.builtin(builtin, expr, scope, args);
417
+ }
418
+ if (expr.name.startsWith(XSD) && CASTS.has(expr.name.slice(XSD.length))) {
419
+ if (expr.args.length !== 1) throw new SrlError(`the cast ${expr.name} takes one argument`);
420
+ this.need('srl_cast');
421
+ const [a] = args();
422
+ const value = this.fresh('R');
423
+ return { goals: [...a.goals, `srl_cast(${q(expr.name)}, ${a.value}, ${value})`], value };
424
+ }
425
+ // An unknown function is an error, so its expression has no value.
426
+ this.warnings.push(`rule ${this.number}: the function <${expr.name}> is not known, so its expression is an error`);
427
+ return { goals: ["'fail'"], value: this.fresh('R') };
428
+ }
429
+
430
+ builtin(name, expr, scope, args) {
431
+ const simple = {
432
+ STR: 'srl_str', LANG: 'srl_lang', LANGDIR: 'srl_langdir', LANGMATCHES: 'srl_langmatches', DATATYPE: 'srl_datatype',
433
+ IRI: 'srl_iri', URI: 'srl_iri', ABS: 'srl_abs', CEIL: 'srl_ceil', FLOOR: 'srl_floor', ROUND: 'srl_round',
434
+ STRLEN: 'srl_strlen', UCASE: 'srl_ucase', LCASE: 'srl_lcase', ENCODE_FOR_URI: 'srl_encode_for_uri',
435
+ CONTAINS: 'srl_contains', STRSTARTS: 'srl_strstarts', STRENDS: 'srl_strends', STRBEFORE: 'srl_strbefore',
436
+ STRAFTER: 'srl_strafter', YEAR: 'srl_year', MONTH: 'srl_month', DAY: 'srl_day', HOURS: 'srl_hours',
437
+ MINUTES: 'srl_minutes', SECONDS: 'srl_seconds', TIMEZONE: 'srl_timezone', TZ: 'srl_tz', STRLANG: 'srl_strlang',
438
+ STRLANGDIR: 'srl_strlangdir', STRDT: 'srl_strdt', sameTerm: 'srl_same_term', isIRI: 'srl_is_iri',
439
+ isURI: 'srl_is_iri', isBLANK: 'srl_is_blank', isLITERAL: 'srl_is_literal', isNUMERIC: 'srl_is_numeric',
440
+ hasLANG: 'srl_has_lang', hasLANGDIR: 'srl_has_langdir', isTRIPLE: 'srl_is_triple', TRIPLE: 'srl_triple',
441
+ SUBJECT: 'srl_subject', PREDICATE: 'srl_predicate', OBJECT: 'srl_object', SUBSTR: 'srl_substr',
442
+ };
443
+ const library = {
444
+ srl_langdir: 'srl_lang', srl_ceil: 'srl_abs', srl_floor: 'srl_abs', srl_round: 'srl_abs', srl_lcase: 'srl_ucase',
445
+ srl_contains: 'srl_strstarts', srl_strends: 'srl_strstarts', srl_strafter: 'srl_strbefore',
446
+ srl_year: 'srl_datetime', srl_month: 'srl_datetime', srl_day: 'srl_datetime', srl_hours: 'srl_datetime',
447
+ srl_minutes: 'srl_datetime', srl_seconds: 'srl_datetime', srl_timezone: 'srl_datetime', srl_tz: 'srl_datetime',
448
+ srl_strlangdir: 'srl_strlang', srl_is_iri: 'srl_kind_tests', srl_is_blank: 'srl_kind_tests',
449
+ srl_is_literal: 'srl_kind_tests', srl_is_numeric: 'srl_kind_tests', srl_has_lang: 'srl_kind_tests',
450
+ srl_has_langdir: 'srl_kind_tests', srl_is_triple: 'srl_kind_tests', srl_subject: 'srl_triple',
451
+ srl_predicate: 'srl_triple', srl_object: 'srl_triple',
452
+ };
453
+ if (simple[name]) {
454
+ const fn = simple[name];
455
+ return this.call(fn, args(), library[fn] ?? fn);
456
+ }
457
+ switch (name) {
458
+ case 'IF': {
459
+ const [c, a, b] = args();
460
+ this.need('srl_ebv');
461
+ const flag = this.fresh('C');
462
+ const value = this.fresh('R');
463
+ const branch = (x, v) => [...x.goals, `unify(${value}, ${x.value})`];
464
+ return {
465
+ goals: [...c.goals, `srl_ebv(${c.value}, ${flag})`,
466
+ `or([unify(${flag}, 'true'), ${branch(a).join(', ')}], [unify(${flag}, 'false'), ${branch(b).join(', ')}])`],
467
+ value,
468
+ };
469
+ }
470
+ case 'CONCAT': {
471
+ const items = args();
472
+ this.need('srl_concat');
473
+ const value = this.fresh('R');
474
+ return { goals: [...items.flatMap((a) => a.goals), `srl_concat([${items.map((a) => a.value).join(', ')}], ${value})`], value };
475
+ }
476
+ case 'REGEX':
477
+ case 'REPLACE': {
478
+ const items = args();
479
+ const flags = items.length === (name === 'REGEX' ? 3 : 4) ? expr.args.at(-1) : null;
480
+ const fn = name === 'REGEX' ? 'srl_regex' : 'srl_replace';
481
+ if (flags === null) return this.call(fn, items);
482
+ const text = flags.type === 'literal' && typeof flags.value === 'string' ? flags.value : null;
483
+ if (text === null || !/^i?$/.test(text)) {
484
+ this.warnings.push(`rule ${this.number}: ${name} supports no flags but i, so its expression is an error`);
485
+ return { goals: ["'fail'"], value: this.fresh('R') };
486
+ }
487
+ const rest = items.slice(0, -1);
488
+ if (text === '') return this.call(fn, rest);
489
+ // Case-insensitive matching lowers the text and a constant pattern.
490
+ const pattern = expr.args[1];
491
+ if (!(pattern.type === 'literal' && typeof pattern.value === 'string')) {
492
+ this.warnings.push(`rule ${this.number}: ${name} with the i flag needs a constant pattern, so its expression is an error`);
493
+ return { goals: ["'fail'"], value: this.fresh('R') };
494
+ }
495
+ rest[1] = { goals: [], value: `literal(${q(lowerPattern(pattern.value))}, datatype(${q(`${XSD}string`)}))` };
496
+ return this.call(`${fn}_i`, rest, fn);
497
+ }
498
+ case 'BNODE': {
499
+ // A blank node for this solution, and for the string when given.
500
+ const items = args();
501
+ const solution = [...scope.allBound()].sort().map((v) => scope.name(v));
502
+ const text = this.fresh('Text');
503
+ const value = this.fresh('R');
504
+ return {
505
+ goals: [...items.flatMap((a) => a.goals), `term_text([${this.number}, ${q(`bnode${++this.helperCount}`)}, [${items.map((a) => a.value).join(', ')}], [${solution.join(', ')}]], ${text})`, `unify(${value}, bnode('srl', ${text}))`],
506
+ value,
507
+ };
508
+ }
509
+ case 'NOW':
510
+ throw new SrlError('NOW is not supported: eyemind has no clock');
511
+ case 'UUID':
512
+ case 'STRUUID':
513
+ throw new SrlError(`${name} is not supported: eyemind has no source of random identifiers`);
514
+ default:
515
+ throw new SrlError(`${name} is not supported`);
516
+ }
517
+ }
518
+ }
519
+
520
+ const CASTS = new Set(['string', 'integer', 'decimal', 'float', 'double', 'boolean', 'dateTime', 'date']);
521
+
522
+ // A pattern for case-insensitive matching against lowered text: letters
523
+ // outside escapes become lower case.
524
+ function lowerPattern(pattern) {
525
+ return pattern.replace(/\\[pPu]\{[^}]*\}|\\.|[A-Z]/gu, (m) => (m.length === 1 ? m.toLowerCase() : m));
526
+ }
527
+
528
+ // The variables of a rule body, a scope over them, and the patterns that
529
+ // match its graph.
530
+ class Scope {
531
+ constructor(compiler, parent, graph, keys = null) {
532
+ this.compiler = compiler;
533
+ this.parent = parent;
534
+ this.graph = graph;
535
+ // A group pattern shares only its keys with the enclosing scope.
536
+ this.keys = keys;
537
+ this.names = new Map();
538
+ this.bound = new Set();
539
+ }
540
+
541
+ name(v) {
542
+ if (this.names.has(v)) return this.names.get(v);
543
+ if (this.parent && this.keys?.has(v)) return this.parent.name(v);
544
+ const name = this.compiler.fresh(v.startsWith('__b') ? `B${v.slice(3)}` : v);
545
+ this.names.set(v, name);
546
+ return name;
547
+ }
548
+
549
+ bind(v) {
550
+ this.bound.add(v);
551
+ }
552
+
553
+ allBound() {
554
+ return new Set([...(this.parent ? this.parent.allBound() : []), ...this.bound]);
555
+ }
556
+
557
+ term(t) {
558
+ if (t.type === 'var') {
559
+ this.bind(t.value);
560
+ return this.name(t.value);
561
+ }
562
+ if (t.type === 'triple') return `triple(${this.term(t.s)}, ${this.term(t.p)}, ${this.term(t.o)})`;
563
+ return this.compiler.terms.term(t);
564
+ }
565
+
566
+ pattern(s, p, o) {
567
+ return `${this.graph}(${this.term(s)}, ${this.term(p)}, ${this.term(o)})`;
568
+ }
569
+
570
+ // A property path of sequences and inverses as triple patterns.
571
+ path(s, path, o) {
572
+ if (path.type !== 'path') return [this.pattern(s, path, o)];
573
+ if (path.kind === 'inverse') return this.path(o, path.path, s);
574
+ if (path.kind === 'sequence') {
575
+ const goals = [];
576
+ let from = s;
577
+ path.parts.forEach((part, k) => {
578
+ const to = k === path.parts.length - 1 ? o : { type: 'var', value: `__path${this.compiler.helperCount++}` };
579
+ goals.push(...this.path(from, part, to));
580
+ from = to;
581
+ });
582
+ return goals;
583
+ }
584
+ throw new SrlError(`unsupported path ${path.kind}`);
585
+ }
586
+ }
587
+
588
+ function collectClauseVars(clauses, out) {
589
+ const term = (t) => {
590
+ if (!t) return;
591
+ if (t.type === 'var') out.add(t.value);
592
+ else if (t.type === 'triple') [t.s, t.p, t.o].forEach(term);
593
+ else if (t.type === 'path') (t.kind === 'inverse' ? [t.path] : t.parts ?? []).forEach(term);
594
+ };
595
+ const expr = (e) => {
596
+ if (!e) return;
597
+ if (e.type === 'var') out.add(e.name);
598
+ else if (e.type === 'unary') expr(e.expr);
599
+ else if (e.type === 'binary') { expr(e.left); expr(e.right); }
600
+ else if (e.type === 'call') e.args.forEach(expr);
601
+ else if (e.type === 'list') e.items.forEach(expr);
602
+ else if (e.type === 'term') term(e.value);
603
+ };
604
+ for (const c of clauses) {
605
+ if (c.type === 'triple' || c.type === 'path') [c.triple.s, c.triple.p, c.triple.o].forEach(term);
606
+ else if (c.type === 'filter') expr(c.expr);
607
+ else if (c.type === 'set') { out.add(c.variable); expr(c.expr); }
608
+ }
609
+ }
610
+
611
+
612
+ // Generous bounds: rule sets over real data run longer than eyemind's defaults.
613
+ export const SRL_LIMITS = { maxDepth: 1000000, maxIterations: 100000, maxInferences: 1000000000 };
614
+
615
+ // Reason over a rule set. Options: base, filename, resolve (IMPORTS), data
616
+ // (the base graph as RDF quads), all (the base graph too), limits and proof.
617
+ // Returns { quads, program, prefixes, warnings, result }: the quads are the
618
+ // inference graph's, and with proof, result.proof is eyemind's checked
619
+ // proof of the compiled program.
620
+ export function reasonSrl(text, { base = null, filename = '<input>', resolve = null, data = [], all = false, limits = {}, proof = false } = {}) {
621
+ const { program, prefixes, warnings } = compileSrl(text, { base, filename, resolve, data });
622
+ const result = run(loadText(program, 'compiled.js'), { ...SRL_LIMITS, ...limits, proof });
623
+ return { quads: srlQuads(program, result.answers, { all }), program, prefixes, warnings, result };
624
+ }
625
+
626
+ // The inference graph of a run's answers, as quads in the default graph:
627
+ // the rule set's DATA triples, then the derived ones. With all, the base
628
+ // graph the compiled program states comes first.
629
+ export function srlQuads(program, answers, { all = false } = {}) {
630
+ const seen = new Set();
631
+ const out = [];
632
+ const add = (terms, name) => {
633
+ for (const t of terms) {
634
+ if (!(t instanceof Struct) || t.name !== name || t.args.length !== 3) continue;
635
+ const key = write(new Struct('t', t.args));
636
+ if (seen.has(key)) continue;
637
+ seen.add(key);
638
+ out.push([...t.args, DEFAULT_GRAPH]);
639
+ }
640
+ };
641
+ const lines = program.split('\n');
642
+ if (all) {
643
+ const line = lines.find((l) => l.startsWith('facts_from({ text: '));
644
+ if (line) add(readTerms(JSON.parse(line.slice('facts_from({ text: '.length, -' })'.length))).map(([t]) => t), 'base');
645
+ }
646
+ add(readTerms(lines.filter((l) => l.startsWith('fact(rdf(') && l.includes(', inf(')).join('\n')).map(([t]) => t.args[1]), 'inf');
647
+ add(answers.map((a) => readTerms(a)[0][0]), 'inf');
648
+ return out;
649
+ }
package/src/version.js CHANGED
@@ -1,2 +1,2 @@
1
1
  // The release this checkout is; ./release keeps it in step with package.json.
2
- export const VERSION = '0.5.0';
2
+ export const VERSION = '0.5.2';