eyemind 0.8.8 → 0.8.11

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.
@@ -0,0 +1,533 @@
1
+ // Specializing a program for facts that arrive again and again, such as RDF
2
+ // Messages: the program's own facts are closed once, and each shape of
3
+ // arriving facts gets only the rule instances that can use one of them.
4
+ //
5
+ // The closure of the program's own facts are the old facts; facts not among
6
+ // them are new. A rule instance whose premises are all old concludes an old
7
+ // fact, so for each forward rule every choice of which data premises are
8
+ // new, at least one, is a variant. An old premise is unfolded into the old
9
+ // facts it matches when they are few and bind a property or class that makes
10
+ // another premise or a conclusion specific; otherwise it is kept, bound to
11
+ // what all those facts share, and reads old_NAME, a copy of the old facts it
12
+ // needs. A new premise reads NAME, the arriving and the derived new facts,
13
+ // and is specialized to each pattern new facts can have: the arriving facts
14
+ // with their values made variables, and the conclusions of the variants,
15
+ // generalized per relation, property and class until no variant adds one. A
16
+ // conclusion that is one of its premises or an old fact is never new and is
17
+ // dropped. The variants, the backward clauses and the old facts they read
18
+ // form an ordinary program, cached per shape of arriving facts, and the
19
+ // arriving facts complete it.
20
+ //
21
+ // Negation and collection are not monotone: more facts can retract an old
22
+ // conclusion. A program that negates or collects what can be new, or that
23
+ // has restricted rules, rule templates or inspection, is not specialized.
24
+ import { CONTROL_KEYS, Program, Source } from './program.js';
25
+ import { run } from './engine.js';
26
+ import { Env, Struct, Var, conjunction, copyResolved, deref, freshTerm, flattenConjunction, identical, identity, isGround, isTerm, key, listFromItems, unify, variables } from './terms.js';
27
+ import { Lettering, write } from './writer.js';
28
+
29
+ const RDF_TYPE = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#type';
30
+ const NEGATING = new Set(['not/1', 'findall/3', 'findall_sorted/3']);
31
+ // Unfold an old premise into at most this many facts.
32
+ const UNFOLD = 256;
33
+ // Generalize, or guard a conclusion against, at most this many old facts.
34
+ const MANY = 4096;
35
+ // How deep to look into backward clauses for a goal that cannot hold.
36
+ const DEPTH = 4;
37
+ // Give up on specializing a rule that unfolds into more instances than this,
38
+ // or on a shape of messages that takes more search steps than STEPS.
39
+ const LEAVES = 100000;
40
+ const STEPS = 60000;
41
+
42
+ class Unsupported extends Error {}
43
+
44
+ let fresh = 0;
45
+ const variable = () => new Var(`G#${++fresh}`);
46
+ const renamed = (term) => freshTerm(term, `p${++fresh}`);
47
+ const isType = (term) => term instanceof Struct && term.name === 'iri' && term.args[0] === RDF_TYPE;
48
+ // Type tests a pattern can decide once its argument is bound.
49
+ const TYPE_TESTS = new Map([
50
+ ['is_atom/1', (t) => typeof t === 'string'], ['is_int/1', (t) => typeof t === 'bigint'],
51
+ ['is_float/1', (t) => typeof t === 'number'], ['is_number/1', (t) => typeof t === 'bigint' || typeof t === 'number' || t instanceof Struct],
52
+ ]);
53
+ const old = (goal) => new Struct(`old_${goal.name}`, goal.args);
54
+
55
+ // The most specific term every one of these terms is an instance of: where
56
+ // two differ, a variable, the same one for the same pair of subterms.
57
+ export function generalize(terms) {
58
+ let general = terms[0];
59
+ for (const term of terms.slice(1)) {
60
+ const pairs = new Map();
61
+ const walk = (a, b) => {
62
+ if (a instanceof Struct && b instanceof Struct && a.name === b.name && a.args.length === b.args.length) {
63
+ return new Struct(a.name, a.args.map((arg, i) => walk(arg, b.args[i])));
64
+ }
65
+ if (!(a instanceof Var) && !(a instanceof Struct) && typeof a === typeof b && a === b) return a;
66
+ const pair = `${identity(a)}\u0001${identity(b)}`;
67
+ let found = pairs.get(pair);
68
+ if (found === undefined) pairs.set(pair, found = variable());
69
+ return found;
70
+ };
71
+ general = walk(general, term);
72
+ }
73
+ return general;
74
+ }
75
+
76
+ // Whether term is an instance of pattern.
77
+ function instance(pattern, term) {
78
+ const env = new Env();
79
+ const frozen = new Map();
80
+ for (const [name] of variables(term)) frozen.set(name, `\u0000${name}`);
81
+ const freeze = (t) => t instanceof Var ? frozen.get(t.name) : t instanceof Struct ? new Struct(t.name, t.args.map(freeze)) : t;
82
+ return unify(renamed(pattern), freeze(term), env);
83
+ }
84
+
85
+ // Whether two terms differ in a constant or functor near their roots, so
86
+ // they cannot unify; false is no promise that they do.
87
+ function clashes(a, b, env, depth = 2) {
88
+ a = deref(a, env);
89
+ if (a instanceof Var || b instanceof Var) return false;
90
+ if (!(a instanceof Struct) || !(b instanceof Struct)) return a !== b || typeof a !== typeof b;
91
+ if (a.name !== b.name || a.args.length !== b.args.length) return true;
92
+ return depth > 1 && a.args.some((arg, i) => clashes(arg, b.args[i], env, depth - 1));
93
+ }
94
+
95
+ // The identity of a pattern with its variables named in order.
96
+ function canonical(pattern) {
97
+ const names = new Map();
98
+ const walk = (t) => {
99
+ if (t instanceof Var) {
100
+ if (!names.has(t.name)) names.set(t.name, new Var(`V${names.size}`));
101
+ return names.get(t.name);
102
+ }
103
+ return t instanceof Struct ? new Struct(t.name, t.args.map(walk)) : t;
104
+ };
105
+ return identity(walk(pattern));
106
+ }
107
+
108
+ // A term with its atoms and numbers made variables: the shape of a value.
109
+ // A literal keeps its datatype.
110
+ const shape = (term) => term instanceof Var ? term : !(term instanceof Struct) ? variable()
111
+ : term.name === 'datatype' && term.args.length === 1 ? term : new Struct(term.name, term.args.map(shape));
112
+ // The functors of a term to a depth, and the datatypes of its literals:
113
+ // patterns with the same skeleton are generalized into one.
114
+ const skeleton = (term, depth) => term instanceof Var || !depth ? '*' : !(term instanceof Struct) ? typeof term
115
+ : term.name === 'datatype' && term.args.length === 1 ? identity(term)
116
+ : `${term.name}(${term.args.map((arg) => skeleton(arg, depth - 1)).join(',')})`;
117
+
118
+ // Sources as Logic Script statements.
119
+ export function programText(sources) {
120
+ return sources.map((source) => {
121
+ const body = listFromItems(source.body);
122
+ const statement = source.kind === 'fact' ? new Struct('fact', [source.head])
123
+ : source.kind === 'backward' ? new Struct('implied_by', [source.head, body])
124
+ : source.kind === 'contradiction' ? new Struct('contradiction', [body])
125
+ : new Struct('implies', [body, isTerm(source.head, 'and', 2) ? listFromItems(flattenConjunction(source.head)) : source.head]);
126
+ return `${write(statement, null, new Lettering())};\n`;
127
+ }).join('');
128
+ }
129
+
130
+ export class Specializer {
131
+ // quads: the keys whose arguments are subject, property, object and graph.
132
+ constructor(program, { quads = [] } = {}) {
133
+ this.quads = new Set(quads);
134
+ this.cache = new Map();
135
+ this.reason = null;
136
+ try {
137
+ this.prepare(program);
138
+ } catch (error) {
139
+ if (!(error instanceof Unsupported)) throw error;
140
+ this.reason = error.message;
141
+ }
142
+ }
143
+
144
+ prepare(program) {
145
+ if (program.inspectionEnabled) throw new Unsupported('it inspects rules');
146
+ const bodied = new Set(program.clauses.filter((c) => !c.forward && c.body.length).map((c) => key(c.head)));
147
+ this.data = new Set();
148
+ for (const clause of program.clauses) {
149
+ if (clause.restricted || clause.templates.length || clause.parentId !== null || clause.captures !== null) {
150
+ throw new Unsupported('it has restricted rules or rule templates');
151
+ }
152
+ if (clause.forward) {
153
+ for (const head of clause.heads) if (head !== 'true' && head !== 'false') this.data.add(key(head));
154
+ if (clause.body.some((goal) => goal instanceof Var)) throw new Unsupported('a forward rule calls a variable');
155
+ }
156
+ }
157
+ for (const clause of program.clauses) {
158
+ if (!clause.forward && !clause.body.length && !bodied.has(key(clause.head))) this.data.add(key(clause.head));
159
+ }
160
+ for (const k of this.data) {
161
+ if (bodied.has(k)) throw new Unsupported(`${k} has forward and backward clauses`);
162
+ if (program.groups.has(`old_${k}`) || this.data.has(`old_${k}`)) throw new Unsupported(`it names old_${k}`);
163
+ }
164
+ // Backward clauses and the facts of backward relations stay as they are.
165
+ this.backward = program.clauses.filter((c) => !c.forward && !this.data.has(key(c.head)));
166
+ this.backwardKeys = new Set(this.backward.map((c) => key(c.head)));
167
+ this.clausesOf = new Map();
168
+ for (const clause of this.backward) {
169
+ const k = key(clause.head);
170
+ if (!this.clausesOf.has(k)) this.clausesOf.set(k, []);
171
+ this.clausesOf.get(k).push(clause);
172
+ }
173
+ this.rules = program.clauses.filter((c) => c.forward && !c.heads.every((head) => head === 'true'));
174
+ const result = run(program);
175
+ if (result.haltCode !== null) throw new Unsupported('its own facts are contradictory');
176
+ const facts = program.clauses.filter((c) => !c.forward && !c.body.length && this.data.has(key(c.head))).map((c) => c.head);
177
+ for (const node of result.derived) if (this.data.has(key(node.goal))) facts.push(node.goal);
178
+ if (!facts.every((fact) => isGround(fact))) throw new Unsupported('it has facts with variables');
179
+ this.oldIds = new Set(facts.map(identity));
180
+ this.index = new Map();
181
+ for (const fact of facts) {
182
+ for (const at of this.indexKeys(fact)) {
183
+ let list = this.index.get(at);
184
+ if (list === undefined) this.index.set(at, list = []);
185
+ list.push(fact);
186
+ }
187
+ }
188
+ }
189
+
190
+ // The index keys of a term from least to most specific: its key, and for
191
+ // a quad its property, and the class of an rdf:type statement.
192
+ indexKeys(goal, env = null) {
193
+ const k = key(goal);
194
+ const keys = [k];
195
+ if (!this.quads.has(k)) return keys;
196
+ const p = env === null ? goal.args[1] : copyResolved(goal.args[1], env);
197
+ if (!isGround(p)) return keys;
198
+ keys.push(`${k}|${identity(p)}`);
199
+ if (!isType(p)) return keys;
200
+ const o = env === null ? goal.args[2] : copyResolved(goal.args[2], env);
201
+ if (isGround(o)) keys.push(`${k}|${identity(p)}|${identity(o)}`);
202
+ return keys;
203
+ }
204
+
205
+ // The old facts a goal matches.
206
+ matches(goal, env, limit = Infinity) {
207
+ const bucket = this.index.get(this.indexKeys(goal, env).at(-1)) ?? [];
208
+ if (bucket.length > limit) return null;
209
+ return bucket.filter((fact) => {
210
+ const mark = env.mark();
211
+ const matches = unify(goal, fact, env);
212
+ env.undo(mark);
213
+ return matches;
214
+ });
215
+ }
216
+
217
+ // A program for these arriving facts, or null when this program cannot be
218
+ // specialized; old holds the identities of the old facts.
219
+ specialize(facts) {
220
+ if (this.reason !== null) return null;
221
+ const arriving = facts.filter((fact) => !this.oldIds.has(identity(fact)));
222
+ this.patterns = new Map();
223
+ for (const fact of arriving) {
224
+ const k = key(fact);
225
+ // A relation without facts or forward rules of its own may be read
226
+ // anywhere, under negation too: the whole program runs.
227
+ if (!this.data.has(k)) return null;
228
+ this.addPattern(this.quads.has(k)
229
+ ? new Struct(fact.name, [shape(fact.args[0]), fact.args[1], isType(fact.args[1]) ? fact.args[2] : shape(fact.args[2]), fact.args[3]])
230
+ : shape(fact));
231
+ }
232
+ const id = [...this.patterns.values()].flatMap((group) => [...group.values()].map(canonical)).sort().join('\n');
233
+ let compiled = this.cache.get(id);
234
+ if (compiled === undefined) {
235
+ try {
236
+ compiled = this.compile();
237
+ } catch (error) {
238
+ if (!(error instanceof Unsupported)) throw error;
239
+ compiled = { reason: error.message };
240
+ }
241
+ this.cache.set(id, compiled);
242
+ }
243
+ if (compiled.reason) return null;
244
+ const first = compiled.program === undefined;
245
+ compiled.program ??= new Program(compiled.sources);
246
+ return { program: compiled.program.withFacts(arriving), sources: compiled.sources, old: this.oldIds, fresh: first };
247
+ }
248
+
249
+ // Add a pattern of new facts, generalizing the one of its relation,
250
+ // property and class; true when that changes what can be new.
251
+ addPattern(pattern) {
252
+ const k = key(pattern);
253
+ // With new facts of any property, as owl:sameAs between individuals
254
+ // makes, nearly every rule is a variant: the whole program runs instead.
255
+ if (this.quads.has(k) && !isGround(pattern.args[1])) throw new Unsupported('new facts can have any property');
256
+ let group = this.patterns.get(k);
257
+ if (group === undefined) this.patterns.set(k, group = new Map());
258
+ const at = `${this.indexKeys(pattern).at(-1)}|${skeleton(pattern, 4)}`;
259
+ const known = group.get(at);
260
+ if (known !== undefined && instance(known, pattern)) return false;
261
+ group.set(at, known === undefined ? pattern : generalize([known, pattern]));
262
+ return true;
263
+ }
264
+
265
+ // The patterns of new facts a goal can match.
266
+ newPatterns(goal, env) {
267
+ const found = [];
268
+ const args = goal.args.map((arg) => deref(arg, env));
269
+ for (const pattern of this.patterns.get(key(goal))?.values() ?? []) {
270
+ if (pattern.args.some((arg, i) => clashes(args[i], arg, env))) continue;
271
+ const copy = renamed(pattern);
272
+ const mark = env.mark();
273
+ if (unify(goal, copy, env)) found.push(copy);
274
+ env.undo(mark);
275
+ }
276
+ return found;
277
+ }
278
+
279
+ mayBeNew(goal, env = new Env()) {
280
+ return this.newPatterns(goal, env).length > 0;
281
+ }
282
+
283
+ compile() {
284
+ this.readsMemo = new Map();
285
+ this.steps = 0;
286
+ // The patterns of new facts, to a fixpoint.
287
+ for (let changed = true; changed;) {
288
+ changed = false;
289
+ for (const rule of this.rules) {
290
+ this.variants(rule, (heads) => {
291
+ for (const head of heads) if (head !== 'false' && this.addPattern(head)) changed = true;
292
+ });
293
+ }
294
+ if (changed) this.readsMemo = new Map();
295
+ }
296
+ const sources = [];
297
+ const needed = new Map();
298
+ const need = (goal) => {
299
+ for (const fact of this.matches(goal, new Env())) needed.set(identity(fact), fact);
300
+ };
301
+ for (const rule of this.rules) {
302
+ this.variants(rule, (heads, body, newIndex) => {
303
+ const goals = body.map(([goal, mode]) => {
304
+ if (mode === 'old') {
305
+ need(goal);
306
+ return old(goal);
307
+ }
308
+ return mode === 'new' ? goal : this.rewrite(goal, false, need);
309
+ });
310
+ // A new premise first: it has the fewest facts to try.
311
+ const ordered = newIndex < 0 ? goals : [goals[newIndex], ...goals.filter((_, i) => i !== newIndex)];
312
+ const inBody = new Set();
313
+ for (const goal of ordered) for (const name of variables(goal).keys()) inBody.add(name);
314
+ if (heads.some((head) => [...variables(head).keys()].some((name) => !inBody.has(name)))) {
315
+ // Witnesses are shared by the conclusions of one firing.
316
+ sources.push(new Source('forward', conjunction(heads), ordered));
317
+ return;
318
+ }
319
+ for (const head of heads) {
320
+ if (head === 'false') {
321
+ sources.push(new Source('contradiction', 'false', ordered));
322
+ continue;
323
+ }
324
+ // An old conclusion is not new: say so when the old facts it
325
+ // could be are few enough to copy.
326
+ const could = this.matches(head, new Env(), MANY);
327
+ if (could !== null && could.length) {
328
+ need(head);
329
+ sources.push(new Source('forward', head, [...ordered, new Struct('not', [old(head)])]));
330
+ } else {
331
+ sources.push(new Source('forward', head, ordered));
332
+ }
333
+ }
334
+ });
335
+ }
336
+ for (const clause of this.backward) {
337
+ sources.push(clause.body.length
338
+ ? new Source('backward', clause.head, clause.body.map((goal) => this.rewrite(goal, false, need)))
339
+ : new Source('fact', clause.head, []));
340
+ }
341
+ for (const fact of needed.values()) sources.push(new Source('fact', old(fact), []));
342
+ return { sources };
343
+ }
344
+
345
+ // Whether a goal that is no premise may hold: false when no clause can
346
+ // answer it within depth steps, or a type test fails. A goal only one fact
347
+ // can answer is bound to it in env, so the goals after it see its values.
348
+ holds(goal, depth, env) {
349
+ const resolved = copyResolved(goal, env);
350
+ if (!(resolved instanceof Struct)) return true;
351
+ const goalKey = key(resolved);
352
+ if (TYPE_TESTS.has(goalKey)) return resolved.args[0] instanceof Var || TYPE_TESTS.get(goalKey)(resolved.args[0]);
353
+ if (goalKey === 'and/2') return resolved.args.every((arg) => this.holds(arg, depth, env));
354
+ if (goalKey === 'or/2') return resolved.args.some((arg) => this.holds(arg, depth, new Env()));
355
+ if (!this.backwardKeys.has(goalKey)) return true;
356
+ let only = null;
357
+ let count = 0;
358
+ for (const clause of this.clausesOf.get(goalKey)) {
359
+ const names = new Map();
360
+ const suffix = `h${++fresh}`;
361
+ const head = freshTerm(clause.head, suffix, names);
362
+ const local = new Env();
363
+ if (!unify(resolved, head, local)) continue;
364
+ if (depth && !clause.body.every((item) => this.holds(freshTerm(item, suffix, names), depth - 1, local))) continue;
365
+ if (++count > 1) return true;
366
+ only = clause.body.length ? null : copyResolved(head, local);
367
+ }
368
+ if (only !== null) unify(resolved, only, env);
369
+ return count > 0;
370
+ }
371
+
372
+ // Whether a goal that is no premise reads facts that can be new: a data
373
+ // goal inside a control goal, or a backward relation that reads them.
374
+ readsNew(goal) {
375
+ if (!(goal instanceof Struct || typeof goal === 'string')) return goal instanceof Var;
376
+ const goalKey = key(goal);
377
+ if (this.data.has(goalKey)) return this.mayBeNew(goal);
378
+ if (CONTROL_KEYS.has(goalKey)) return goal.args.some((arg) => this.readsNew(arg));
379
+ if (!this.backwardKeys.has(goalKey)) return false;
380
+ let reads = this.readsMemo.get(goalKey);
381
+ if (reads !== undefined) return reads;
382
+ const seen = new Set([goalKey]);
383
+ const walk = (item) => {
384
+ if (!(item instanceof Struct || typeof item === 'string')) return item instanceof Var;
385
+ const itemKey = key(item);
386
+ if (this.data.has(itemKey)) return this.mayBeNew(item);
387
+ if (CONTROL_KEYS.has(itemKey)) return item.args.some(walk);
388
+ if (!this.backwardKeys.has(itemKey) || seen.has(itemKey)) return false;
389
+ seen.add(itemKey);
390
+ return this.clausesOf.get(itemKey).some((c) => c.body.some(walk));
391
+ };
392
+ reads = this.clausesOf.get(goalKey).some((c) => c.body.some(walk));
393
+ this.readsMemo.set(goalKey, reads);
394
+ return reads;
395
+ }
396
+
397
+ // A goal that is not a premise of a variant, with its data goals reading
398
+ // old facts, or old and new ones; negating or collecting new facts is not
399
+ // specialized.
400
+ rewrite(goal, negated, need) {
401
+ if (goal instanceof Var) throw new Unsupported('a goal is a variable');
402
+ if (!(goal instanceof Struct || typeof goal === 'string')) return goal;
403
+ const goalKey = key(goal);
404
+ if (this.data.has(goalKey)) {
405
+ const may = this.mayBeNew(goal);
406
+ if (may && negated) throw new Unsupported(`it negates or collects ${goalKey} facts that can be new`);
407
+ need(goal);
408
+ return may ? new Struct('or', [old(goal), goal]) : old(goal);
409
+ }
410
+ if (NEGATING.has(goalKey)) {
411
+ const at = goalKey === 'not/1' ? 0 : 1;
412
+ return new Struct(goal.name, goal.args.map((arg, i) => i === at ? this.rewrite(arg, true, need) : arg));
413
+ }
414
+ if (CONTROL_KEYS.has(goalKey)) return new Struct(goal.name, goal.args.map((arg) => this.rewrite(arg, negated, need)));
415
+ if (negated && this.readsNew(goal)) {
416
+ throw new Unsupported(`it negates or collects ${goalKey}, which reads facts that can be new`);
417
+ }
418
+ return goal;
419
+ }
420
+
421
+ // Each variant of a forward rule: emit(heads, body, newIndex), the body a
422
+ // list of [goal, mode], mode 'new', 'old' or null for a goal that is no
423
+ // premise, and newIndex the position of the first new premise.
424
+ variants(rule, emit) {
425
+ const names = new Map();
426
+ const suffix = `s${++fresh}`;
427
+ const heads = rule.heads.filter((head) => head !== 'true').map((head) => freshTerm(head, suffix, names));
428
+ const body = rule.body.map((goal) => freshTerm(goal, suffix, names));
429
+ const data = body.map((goal, i) => this.data.has(key(goal)) ? i : -1).filter((i) => i >= 0);
430
+ // A negation or collection of what can be new is refused whether or not
431
+ // a variant survives: more facts could retract an old conclusion.
432
+ for (const goal of body) if (!this.data.has(key(goal))) this.rewrite(goal, false, () => {});
433
+ // A goal that is no premise but reads new facts makes a variant new.
434
+ const reading = body.some((goal) => !this.data.has(key(goal)) && this.readsNew(goal));
435
+ const modes = new Array(body.length).fill(null);
436
+ const env = new Env();
437
+ let leaves = 0;
438
+ const leaf = (count) => {
439
+ if (!count && !reading) return;
440
+ const mark = env.mark();
441
+ try {
442
+ for (const [i, goal] of body.entries()) if (modes[i] === null && !this.holds(goal, DEPTH, env)) return;
443
+ settled(count);
444
+ } finally {
445
+ env.undo(mark);
446
+ }
447
+ };
448
+ const settled = () => {
449
+ const resolved = body.map((goal) => copyResolved(goal, env));
450
+ const premises = resolved.filter((_, i) => modes[i] === 'new' || modes[i] === 'old');
451
+ const kept = heads.map((head) => copyResolved(head, env)).filter((head) => head === 'false' ||
452
+ (!premises.some((goal) => identical(goal, head)) && !(isGround(head) && this.oldIds.has(identity(head)))));
453
+ if (!kept.length) return;
454
+ const list = [];
455
+ let newIndex = -1;
456
+ resolved.forEach((goal, i) => {
457
+ if (modes[i] === 'fact') return;
458
+ if (modes[i] === 'new' && newIndex < 0) newIndex = list.length;
459
+ list.push([goal, modes[i]]);
460
+ });
461
+ emit(kept, list, newIndex);
462
+ };
463
+ // The variables in the property, or rdf:type class, of the conclusions
464
+ // and the other premises: unfolding an old premise that binds one makes
465
+ // a pattern specific.
466
+ const keyed = (i) => {
467
+ const found = new Set();
468
+ for (const term of [...heads, ...data.filter((j) => j !== i).map((j) => body[j])]) {
469
+ if (!(term instanceof Struct) || !this.quads.has(key(term))) continue;
470
+ const [, p, o] = term.args.map((arg) => copyResolved(arg, env));
471
+ for (const name of variables(p).keys()) found.add(name);
472
+ if (p instanceof Var || isType(p)) for (const name of variables(o).keys()) found.add(name);
473
+ }
474
+ return found;
475
+ };
476
+ const visit = (pending, count) => {
477
+ if (++this.steps > STEPS) throw new Unsupported('its messages need too many specialized rules');
478
+ if (!pending.length) return leaf(count);
479
+ if (!count && !reading && !pending.some((i) => this.mayBeNew(body[i], env))) return;
480
+ // The premise with the fewest alternatives first; none ends the search.
481
+ let choice = null;
482
+ for (const [at, i] of pending.entries()) {
483
+ const goal = body[i];
484
+ const patterns = this.newPatterns(goal, env);
485
+ const facts = this.matches(goal, env, MANY);
486
+ const any = facts === null || facts.length > 0;
487
+ let unfold = facts !== null && facts.length > 0 && facts.length <= UNFOLD;
488
+ if (unfold) {
489
+ const names = keyed(i);
490
+ unfold = [...variables(copyResolved(goal, env)).keys()].some((name) => names.has(name));
491
+ }
492
+ const branches = patterns.length + (unfold ? facts.length : any ? 1 : 0);
493
+ if (!branches) return;
494
+ if (choice === null || branches < choice.branches) choice = { at, i, patterns, facts, any, unfold, branches };
495
+ }
496
+ const { at, i, patterns, facts, any, unfold } = choice;
497
+ const rest = pending.filter((_, k) => k !== at);
498
+ const goal = body[i];
499
+ for (const pattern of patterns) {
500
+ const mark = env.mark();
501
+ if (unify(goal, pattern, env)) {
502
+ modes[i] = 'new';
503
+ visit(rest, count + 1);
504
+ }
505
+ env.undo(mark);
506
+ }
507
+ // Old: possible only if a later premise can still be new.
508
+ if (any && (count || reading || rest.some((j) => this.mayBeNew(body[j], env)))) {
509
+ if (unfold) {
510
+ for (const fact of facts) {
511
+ const mark = env.mark();
512
+ if (unify(goal, fact, env)) {
513
+ modes[i] = 'fact';
514
+ if (++leaves > LEAVES) throw new Unsupported(`rule ${rule.id} has too many specialized instances`);
515
+ visit(rest, count);
516
+ }
517
+ env.undo(mark);
518
+ }
519
+ } else {
520
+ // What all the old facts it matches share, such as the same
521
+ // subject and object, still binds the premise.
522
+ const mark = env.mark();
523
+ if (facts !== null) unify(goal, generalize(facts), env);
524
+ modes[i] = 'old';
525
+ visit(rest, count);
526
+ env.undo(mark);
527
+ }
528
+ }
529
+ modes[i] = null;
530
+ };
531
+ visit(data, 0);
532
+ }
533
+ }
@@ -332,12 +332,28 @@ function stronglyConnectedComponents(size, edges) {
332
332
 
333
333
  function sequentialWellFormednessDiagnostics(clauses, ruleNameValue, prefixes = {}, initialBound = new Set()) {
334
334
  const diagnostics = [];
335
+ const error = (code, message) => diagnostics.push({
336
+ code, severity: 'error', rule: ruleNameValue,
337
+ message: `${displayRuleName(ruleNameValue, prefixes)} ${message}`,
338
+ });
335
339
 
336
- function visit(items, initialBound, scopeLabel) {
340
+ function visit(items, initialBound, initialInUse, scopeLabel) {
337
341
  const bound = new Set(initialBound);
342
+ const inUse = new Set(initialInUse);
343
+ // Local names from a nested sequence remain reserved after it finishes.
344
+ const reserveLocals = (inner) => {
345
+ for (const names of [inner.bound, inner.inUse]) {
346
+ for (const name of names) if (!bound.has(name)) inUse.add(name);
347
+ }
348
+ };
338
349
  for (const clause of items) {
339
350
  if (clause.type === 'triple' || clause.type === 'path') {
340
- collectTripleVars(clause.triple, bound);
351
+ const names = new Set();
352
+ collectTripleVars(clause.triple, names);
353
+ for (const name of names) {
354
+ if (inUse.has(name)) error('variable-already-in-use', `pattern reuses ?${name}, which is already in use${scopeLabel}`);
355
+ bound.add(name);
356
+ }
341
357
  } else if (clause.type === 'filter') {
342
358
  for (const variable of expressionVariables(clause.expr)) {
343
359
  if (!bound.has(variable)) {
@@ -357,6 +373,8 @@ function sequentialWellFormednessDiagnostics(clauses, ruleNameValue, prefixes =
357
373
  rule: ruleNameValue,
358
374
  message: `${displayRuleName(ruleNameValue, prefixes)} SET assigns ?${clause.variable}, but that variable is already bound${scopeLabel}`,
359
375
  });
376
+ } else if (inUse.has(clause.variable)) {
377
+ error('variable-already-in-use', `SET assigns ?${clause.variable}, but that variable is already in use${scopeLabel}`);
360
378
  }
361
379
  for (const variable of expressionVariables(clause.expr)) {
362
380
  if (!bound.has(variable)) {
@@ -370,34 +388,35 @@ function sequentialWellFormednessDiagnostics(clauses, ruleNameValue, prefixes =
370
388
  }
371
389
  bound.add(clause.variable);
372
390
  } else if (clause.type === 'not') {
373
- visit(clause.body, bound, ' inside NOT');
391
+ reserveLocals(visit(clause.body, bound, inUse, ' inside NOT'));
374
392
  } else if (clause.type === 'group') {
375
393
  // Only keys correlate the group pattern with the incoming mapping.
394
+ const keys = new Set(clause.keys);
376
395
  const initial = new Set(clause.keys.filter((key) => bound.has(key)));
377
- const inner = visit(clause.pattern, initial, ' inside GROUP');
378
- const error = (code, message) => diagnostics.push({
379
- code, severity: 'error', rule: ruleNameValue,
380
- message: `${displayRuleName(ruleNameValue, prefixes)} ${message}`,
381
- });
396
+ const reserved = new Set(inUse);
397
+ for (const name of bound) if (!keys.has(name)) reserved.add(name);
398
+ const inner = visit(clause.pattern, initial, reserved, ' inside GROUP');
382
399
  for (const key of clause.keys) {
383
- if (!inner.has(key)) error('unbound-group-key', `GROUP key ?${key} is not bound in the group pattern`);
400
+ if (!inner.bound.has(key)) error('unbound-group-key', `GROUP key ?${key} is not bound in the group pattern`);
384
401
  }
385
402
  const assigned = new Set();
386
403
  for (const aggregation of clause.aggregations) {
387
404
  const { variable, function: fn } = aggregation;
388
- if (inner.has(variable) || bound.has(variable)) error('aggregation-variable-already-bound', `GROUP assigns ?${variable}, but that variable is already bound`);
405
+ if (inner.bound.has(variable) || bound.has(variable)) error('aggregation-variable-already-bound', `GROUP assigns ?${variable}, but that variable is already bound`);
406
+ else if (inner.inUse.has(variable)) error('variable-already-in-use', `GROUP assigns ?${variable}, but that variable is already in use`);
389
407
  if (assigned.has(variable)) error('duplicate-aggregation-variable', `GROUP assigns ?${variable} more than once`);
390
- if (fn.argument !== '*' && !inner.has(fn.argument)) error('unbound-aggregation-argument', `GROUP aggregate uses unbound variable ?${fn.argument}`);
408
+ if (fn.argument !== '*' && !inner.bound.has(fn.argument)) error('unbound-aggregation-argument', `GROUP aggregate uses unbound variable ?${fn.argument}`);
391
409
  assigned.add(variable);
392
410
  }
393
411
  for (const key of clause.keys) bound.add(key);
394
412
  for (const variable of assigned) bound.add(variable);
413
+ reserveLocals(inner);
395
414
  }
396
415
  }
397
- return bound;
416
+ return { bound, inUse };
398
417
  }
399
418
 
400
- visit(clauses, initialBound, '');
419
+ visit(clauses, initialBound, new Set(), '');
401
420
  return diagnostics;
402
421
  }
403
422
 
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.8.8';
2
+ export const VERSION = '0.8.11';