eyemind 0.8.10 → 0.8.12
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/LE-SPEC.md +76 -0
- package/LS-SPEC.md +1 -1
- package/README.md +51 -8
- package/package.json +1 -1
- package/src/cli.js +30 -6
- package/src/formats.js +52 -14
- package/src/le.js +167 -33
- package/src/node-messages.js +1 -1
- package/src/program.js +31 -0
- package/src/rdf-logic.js +60 -5
- package/src/specialize.js +643 -0
- package/src/version.js +1 -1
|
@@ -0,0 +1,643 @@
|
|
|
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
|
+
// wanted: patterns of the new facts asked for, or null for all; rules that
|
|
133
|
+
// cannot contribute to one are left out.
|
|
134
|
+
constructor(program, { quads = [], wanted = null } = {}) {
|
|
135
|
+
this.quads = new Set(quads);
|
|
136
|
+
this.wanted = wanted;
|
|
137
|
+
this.cache = new Map();
|
|
138
|
+
this.reason = null;
|
|
139
|
+
try {
|
|
140
|
+
this.prepare(program);
|
|
141
|
+
} catch (error) {
|
|
142
|
+
if (!(error instanceof Unsupported)) throw error;
|
|
143
|
+
this.reason = error.message;
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
prepare(program) {
|
|
148
|
+
if (program.inspectionEnabled) throw new Unsupported('it inspects rules');
|
|
149
|
+
const bodied = new Set(program.clauses.filter((c) => !c.forward && c.body.length).map((c) => key(c.head)));
|
|
150
|
+
this.data = new Set();
|
|
151
|
+
for (const clause of program.clauses) {
|
|
152
|
+
if (clause.restricted || clause.templates.length || clause.parentId !== null || clause.captures !== null) {
|
|
153
|
+
throw new Unsupported('it has restricted rules or rule templates');
|
|
154
|
+
}
|
|
155
|
+
if (clause.forward) {
|
|
156
|
+
for (const head of clause.heads) if (head !== 'true' && head !== 'false') this.data.add(key(head));
|
|
157
|
+
if (clause.body.some((goal) => goal instanceof Var)) throw new Unsupported('a forward rule calls a variable');
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
for (const clause of program.clauses) {
|
|
161
|
+
if (!clause.forward && !clause.body.length && !bodied.has(key(clause.head))) this.data.add(key(clause.head));
|
|
162
|
+
}
|
|
163
|
+
for (const k of this.data) {
|
|
164
|
+
if (bodied.has(k)) throw new Unsupported(`${k} has forward and backward clauses`);
|
|
165
|
+
if (program.groups.has(`old_${k}`) || this.data.has(`old_${k}`)) throw new Unsupported(`it names old_${k}`);
|
|
166
|
+
}
|
|
167
|
+
// Backward clauses and the facts of backward relations stay as they are.
|
|
168
|
+
this.backward = program.clauses.filter((c) => !c.forward && !this.data.has(key(c.head)));
|
|
169
|
+
this.backwardKeys = new Set(this.backward.map((c) => key(c.head)));
|
|
170
|
+
this.clausesOf = new Map();
|
|
171
|
+
for (const clause of this.backward) {
|
|
172
|
+
const k = key(clause.head);
|
|
173
|
+
if (!this.clausesOf.has(k)) this.clausesOf.set(k, []);
|
|
174
|
+
this.clausesOf.get(k).push(clause);
|
|
175
|
+
}
|
|
176
|
+
this.rules = program.clauses.filter((c) => c.forward && !c.heads.every((head) => head === 'true'));
|
|
177
|
+
const result = run(program);
|
|
178
|
+
if (result.haltCode !== null) throw new Unsupported('its own facts are contradictory');
|
|
179
|
+
const facts = program.clauses.filter((c) => !c.forward && !c.body.length && this.data.has(key(c.head))).map((c) => c.head);
|
|
180
|
+
for (const node of result.derived) if (this.data.has(key(node.goal))) facts.push(node.goal);
|
|
181
|
+
if (!facts.every((fact) => isGround(fact))) throw new Unsupported('it has facts with variables');
|
|
182
|
+
this.oldIds = new Set(facts.map(identity));
|
|
183
|
+
this.index = new Map();
|
|
184
|
+
for (const fact of facts) {
|
|
185
|
+
for (const at of this.indexKeys(fact)) {
|
|
186
|
+
let list = this.index.get(at);
|
|
187
|
+
if (list === undefined) this.index.set(at, list = []);
|
|
188
|
+
list.push(fact);
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
// The index keys of a term from least to most specific: its key, and for
|
|
194
|
+
// a quad its property, and the class of an rdf:type statement.
|
|
195
|
+
indexKeys(goal, env = null) {
|
|
196
|
+
const k = key(goal);
|
|
197
|
+
const keys = [k];
|
|
198
|
+
if (!this.quads.has(k)) return keys;
|
|
199
|
+
const p = env === null ? goal.args[1] : copyResolved(goal.args[1], env);
|
|
200
|
+
if (!isGround(p)) return keys;
|
|
201
|
+
keys.push(`${k}|${identity(p)}`);
|
|
202
|
+
if (!isType(p)) return keys;
|
|
203
|
+
const o = env === null ? goal.args[2] : copyResolved(goal.args[2], env);
|
|
204
|
+
if (isGround(o)) keys.push(`${k}|${identity(p)}|${identity(o)}`);
|
|
205
|
+
return keys;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
// The old facts a goal matches.
|
|
209
|
+
matches(goal, env, limit = Infinity) {
|
|
210
|
+
const bucket = this.index.get(this.indexKeys(goal, env).at(-1)) ?? [];
|
|
211
|
+
if (bucket.length > limit) return null;
|
|
212
|
+
return bucket.filter((fact) => {
|
|
213
|
+
const mark = env.mark();
|
|
214
|
+
const matches = unify(goal, fact, env);
|
|
215
|
+
env.undo(mark);
|
|
216
|
+
return matches;
|
|
217
|
+
});
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
// A program for these arriving facts, or null when this program cannot be
|
|
221
|
+
// specialized; old holds the identities of the old facts.
|
|
222
|
+
specialize(facts) {
|
|
223
|
+
if (this.reason !== null) return null;
|
|
224
|
+
const arriving = facts.filter((fact) => !this.oldIds.has(identity(fact)));
|
|
225
|
+
this.patterns = new Map();
|
|
226
|
+
for (const fact of arriving) {
|
|
227
|
+
const k = key(fact);
|
|
228
|
+
// A relation without facts or forward rules of its own may be read
|
|
229
|
+
// anywhere, under negation too: the whole program runs.
|
|
230
|
+
if (!this.data.has(k)) return null;
|
|
231
|
+
this.addPattern(this.quads.has(k)
|
|
232
|
+
? 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]])
|
|
233
|
+
: shape(fact));
|
|
234
|
+
}
|
|
235
|
+
const id = [...this.patterns.values()].flatMap((group) => [...group.values()].map(canonical)).sort().join('\n');
|
|
236
|
+
let compiled = this.cache.get(id);
|
|
237
|
+
if (compiled === undefined) {
|
|
238
|
+
try {
|
|
239
|
+
compiled = this.compile();
|
|
240
|
+
} catch (error) {
|
|
241
|
+
if (!(error instanceof Unsupported)) throw error;
|
|
242
|
+
compiled = { reason: error.message };
|
|
243
|
+
}
|
|
244
|
+
this.cache.set(id, compiled);
|
|
245
|
+
}
|
|
246
|
+
if (compiled.reason) return null;
|
|
247
|
+
const first = compiled.program === undefined;
|
|
248
|
+
compiled.program ??= new Program(compiled.sources);
|
|
249
|
+
return { program: compiled.program.withFacts(arriving), sources: compiled.sources, old: this.oldIds, fresh: first };
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
// Add a pattern of new facts, generalizing the one of its relation,
|
|
253
|
+
// property and class; true when that changes what can be new.
|
|
254
|
+
addPattern(pattern) {
|
|
255
|
+
const k = key(pattern);
|
|
256
|
+
// With new facts of any property, as owl:sameAs between individuals
|
|
257
|
+
// makes, nearly every rule is a variant: the whole program runs instead.
|
|
258
|
+
if (this.quads.has(k) && !isGround(pattern.args[1])) throw new Unsupported('new facts can have any property');
|
|
259
|
+
let group = this.patterns.get(k);
|
|
260
|
+
if (group === undefined) this.patterns.set(k, group = new Map());
|
|
261
|
+
const at = `${this.indexKeys(pattern).at(-1)}|${skeleton(pattern, 4)}`;
|
|
262
|
+
const known = group.get(at);
|
|
263
|
+
if (known !== undefined && instance(known, pattern)) return false;
|
|
264
|
+
group.set(at, known === undefined ? pattern : generalize([known, pattern]));
|
|
265
|
+
return true;
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
// The patterns of new facts a goal can match.
|
|
269
|
+
newPatterns(goal, env) {
|
|
270
|
+
const found = [];
|
|
271
|
+
const args = goal.args.map((arg) => deref(arg, env));
|
|
272
|
+
for (const pattern of this.patterns.get(key(goal))?.values() ?? []) {
|
|
273
|
+
if (pattern.args.some((arg, i) => clashes(args[i], arg, env))) continue;
|
|
274
|
+
const copy = renamed(pattern);
|
|
275
|
+
const mark = env.mark();
|
|
276
|
+
if (unify(goal, copy, env)) found.push(copy);
|
|
277
|
+
env.undo(mark);
|
|
278
|
+
}
|
|
279
|
+
return found;
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
mayBeNew(goal, env = new Env()) {
|
|
283
|
+
return this.newPatterns(goal, env).length > 0;
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
compile() {
|
|
287
|
+
this.readsMemo = new Map();
|
|
288
|
+
this.steps = 0;
|
|
289
|
+
// The patterns of new facts, to a fixpoint.
|
|
290
|
+
for (let changed = true; changed;) {
|
|
291
|
+
changed = false;
|
|
292
|
+
for (const rule of this.rules) {
|
|
293
|
+
this.variants(rule, (heads) => {
|
|
294
|
+
for (const head of heads) if (head !== 'false' && this.addPattern(head)) changed = true;
|
|
295
|
+
});
|
|
296
|
+
}
|
|
297
|
+
if (changed) this.readsMemo = new Map();
|
|
298
|
+
}
|
|
299
|
+
const variants = [];
|
|
300
|
+
for (const rule of this.rules) this.variants(rule, (heads, body, newIndex, free) => variants.push([heads, body, newIndex, free]));
|
|
301
|
+
const sources = [];
|
|
302
|
+
const needed = new Map();
|
|
303
|
+
const need = (goal) => {
|
|
304
|
+
for (const fact of this.matches(goal, new Env())) needed.set(identity(fact), fact);
|
|
305
|
+
};
|
|
306
|
+
for (const [heads, body, newIndex] of this.relevant(variants)) {
|
|
307
|
+
const goals = body.map(([goal, mode]) => {
|
|
308
|
+
if (mode === 'old') {
|
|
309
|
+
need(goal);
|
|
310
|
+
return old(goal);
|
|
311
|
+
}
|
|
312
|
+
return mode === 'new' ? goal : this.rewrite(goal, false, need);
|
|
313
|
+
});
|
|
314
|
+
// A new premise first: it has the fewest facts to try.
|
|
315
|
+
const ordered = newIndex < 0 ? goals : [goals[newIndex], ...goals.filter((_, i) => i !== newIndex)];
|
|
316
|
+
const inBody = new Set();
|
|
317
|
+
for (const goal of ordered) for (const name of variables(goal).keys()) inBody.add(name);
|
|
318
|
+
if (heads.some((head) => [...variables(head).keys()].some((name) => !inBody.has(name)))) {
|
|
319
|
+
// Witnesses are shared by the conclusions of one firing.
|
|
320
|
+
sources.push(new Source('forward', conjunction(heads), ordered));
|
|
321
|
+
continue;
|
|
322
|
+
}
|
|
323
|
+
for (const head of heads) {
|
|
324
|
+
if (head === 'false') {
|
|
325
|
+
sources.push(new Source('contradiction', 'false', ordered));
|
|
326
|
+
continue;
|
|
327
|
+
}
|
|
328
|
+
// An old conclusion is not new: say so when the old facts it
|
|
329
|
+
// could be are few enough to copy.
|
|
330
|
+
const could = this.matches(head, new Env(), MANY);
|
|
331
|
+
if (could !== null && could.length) {
|
|
332
|
+
need(head);
|
|
333
|
+
sources.push(new Source('forward', head, [...ordered, new Struct('not', [old(head)])]));
|
|
334
|
+
} else {
|
|
335
|
+
sources.push(new Source('forward', head, ordered));
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
for (const clause of this.backward) {
|
|
340
|
+
sources.push(clause.body.length
|
|
341
|
+
? new Source('backward', clause.head, clause.body.map((goal) => this.rewrite(goal, false, need)))
|
|
342
|
+
: new Source('fact', clause.head, []));
|
|
343
|
+
}
|
|
344
|
+
for (const fact of needed.values()) sources.push(new Source('fact', old(fact), []));
|
|
345
|
+
return { sources };
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
// The variants that can contribute to a wanted fact: one with a wanted
|
|
349
|
+
// conclusion, or a contradiction, and then those concluding what its new
|
|
350
|
+
// premises and the goals it calls read, to a fixpoint. Each wanted fact
|
|
351
|
+
// says which of its positions matter to its reader: a value matters when
|
|
352
|
+
// it reaches a position some reader uses, or joins goals. A conclusion
|
|
353
|
+
// does not serve a reader when the variant reading it would conclude only
|
|
354
|
+
// its own premises, as reflexive owl:sameAs does in replacement rules, or
|
|
355
|
+
// when one of its own premises already agrees with it wherever the reader
|
|
356
|
+
// looks, as a triple owl:sameAs copies to an equal object has the subject
|
|
357
|
+
// its original has. All variants without wanted patterns.
|
|
358
|
+
relevant(variants) {
|
|
359
|
+
if (this.wanted === null) return variants;
|
|
360
|
+
const wanted = this.wanted.map((pattern) => ({ goal: renamed(pattern), heads: null, premises: null, positions: pattern.args.map(() => true) }));
|
|
361
|
+
const want = (goal, heads, premises, positions, free = null) => {
|
|
362
|
+
const names = new Map();
|
|
363
|
+
const suffix = `r${++fresh}`;
|
|
364
|
+
const copy = freshTerm(goal, suffix, names);
|
|
365
|
+
// The premise open where the rule has a variable whose value does
|
|
366
|
+
// not matter: any value there serves alike.
|
|
367
|
+
const open = free === null ? copy : new Struct(copy.name, copy.args.map((arg, i) => free[i] && !positions[i] ? variable() : arg));
|
|
368
|
+
wanted.push({ goal: copy, open, heads: heads && heads.map((head) => freshTerm(head, suffix, names)),
|
|
369
|
+
premises: premises && premises.map((premise) => freshTerm(premise, suffix, names)), positions });
|
|
370
|
+
};
|
|
371
|
+
const env = new Env();
|
|
372
|
+
const serves = (head, own, { goal, open, heads, premises, positions }) => {
|
|
373
|
+
const mark = env.mark();
|
|
374
|
+
try {
|
|
375
|
+
if (!unify(head, goal, env)) return false;
|
|
376
|
+
if (heads === null) return true;
|
|
377
|
+
// Every firing whose conclusion is read here has such a premise when
|
|
378
|
+
// the premise, as the firing binds it, is an instance of the read one.
|
|
379
|
+
if (own.some((premise) => {
|
|
380
|
+
const bound = copyResolved(premise, env);
|
|
381
|
+
return bound instanceof Struct && instance(open, bound) &&
|
|
382
|
+
positions.every((matters, i) => !matters || identical(bound.args[i], head.args[i], env));
|
|
383
|
+
})) return false;
|
|
384
|
+
return heads.some((item) => item === 'false' || !premises.some((premise) => identical(premise, item, env)));
|
|
385
|
+
} finally {
|
|
386
|
+
env.undo(mark);
|
|
387
|
+
}
|
|
388
|
+
};
|
|
389
|
+
// For each kept variant, the positions of each conclusion some reader uses.
|
|
390
|
+
const usage = new Map();
|
|
391
|
+
const checked = new Map();
|
|
392
|
+
for (let changed = true; changed;) {
|
|
393
|
+
changed = false;
|
|
394
|
+
for (const variant of variants) {
|
|
395
|
+
const [heads, body, , free] = variant;
|
|
396
|
+
const own = body.filter(([, mode]) => mode === 'new' || mode === 'old').map(([goal]) => goal);
|
|
397
|
+
let use = usage.get(variant);
|
|
398
|
+
let grew = false;
|
|
399
|
+
const from = checked.get(variant) ?? 0;
|
|
400
|
+
checked.set(variant, wanted.length);
|
|
401
|
+
heads.forEach((head, h) => {
|
|
402
|
+
if (head === 'false') {
|
|
403
|
+
if (use === undefined) usage.set(variant, use = heads.map((item) => item instanceof Struct ? item.args.map(() => false) : []));
|
|
404
|
+
if (from === 0) grew = true;
|
|
405
|
+
return;
|
|
406
|
+
}
|
|
407
|
+
for (let w = from; w < wanted.length; w++) {
|
|
408
|
+
if (!serves(head, own, wanted[w])) continue;
|
|
409
|
+
if (use === undefined) usage.set(variant, use = heads.map((item) => item instanceof Struct ? item.args.map(() => false) : []));
|
|
410
|
+
wanted[w].positions.forEach((matters, i) => {
|
|
411
|
+
if (matters && !use[h][i]) use[h][i] = grew = true;
|
|
412
|
+
});
|
|
413
|
+
if (!use[h].length) grew = true;
|
|
414
|
+
}
|
|
415
|
+
});
|
|
416
|
+
if (!grew) continue;
|
|
417
|
+
changed = true;
|
|
418
|
+
// The values that matter: those at used positions of the
|
|
419
|
+
// conclusions, and those shared with another goal of the body.
|
|
420
|
+
const values = (except) => {
|
|
421
|
+
const names = new Set();
|
|
422
|
+
heads.forEach((head, h) => {
|
|
423
|
+
if (head instanceof Struct) head.args.forEach((arg, i) => { if (use[h][i]) for (const name of variables(arg).keys()) names.add(name); });
|
|
424
|
+
});
|
|
425
|
+
for (const [goal] of body) if (goal !== except) for (const name of variables(goal).keys()) names.add(name);
|
|
426
|
+
return names;
|
|
427
|
+
};
|
|
428
|
+
for (const [at, [goal, mode]] of body.entries()) {
|
|
429
|
+
if (mode === 'new') {
|
|
430
|
+
const names = values(goal);
|
|
431
|
+
const counts = new Map();
|
|
432
|
+
for (const arg of goal.args) for (const name of variables(arg).keys()) counts.set(name, (counts.get(name) ?? 0) + 1);
|
|
433
|
+
want(goal, heads, own, goal.args.map((arg) => [...variables(arg).keys()].some((name) => names.has(name) || counts.get(name) > 1)), free[at]);
|
|
434
|
+
} else if (mode === null) {
|
|
435
|
+
for (const read of this.reads(goal)) want(read, null, null, read.args.map(() => true));
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
return variants.filter((variant) => usage.has(variant));
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
// The data goals that a goal which is no premise reads and that can be
|
|
444
|
+
// new: inside control goals, and in the backward clauses it calls.
|
|
445
|
+
reads(goal, seen = new Set()) {
|
|
446
|
+
if (!(goal instanceof Struct)) return [];
|
|
447
|
+
const goalKey = key(goal);
|
|
448
|
+
if (this.data.has(goalKey)) return this.mayBeNew(goal) ? [goal] : [];
|
|
449
|
+
if (CONTROL_KEYS.has(goalKey)) return goal.args.flatMap((arg) => this.reads(arg, seen));
|
|
450
|
+
if (!this.backwardKeys.has(goalKey) || seen.has(goalKey)) return [];
|
|
451
|
+
seen.add(goalKey);
|
|
452
|
+
return this.clausesOf.get(goalKey).flatMap((clause) => clause.body.flatMap((item) => this.reads(item, seen)));
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
// Whether a goal that is no premise may hold: false when no clause can
|
|
456
|
+
// answer it within depth steps, or a type test fails. A goal only one fact
|
|
457
|
+
// can answer is bound to it in env, so the goals after it see its values.
|
|
458
|
+
holds(goal, depth, env) {
|
|
459
|
+
const resolved = copyResolved(goal, env);
|
|
460
|
+
if (!(resolved instanceof Struct)) return true;
|
|
461
|
+
const goalKey = key(resolved);
|
|
462
|
+
if (TYPE_TESTS.has(goalKey)) return resolved.args[0] instanceof Var || TYPE_TESTS.get(goalKey)(resolved.args[0]);
|
|
463
|
+
if (goalKey === 'and/2') return resolved.args.every((arg) => this.holds(arg, depth, env));
|
|
464
|
+
if (goalKey === 'or/2') return resolved.args.some((arg) => this.holds(arg, depth, new Env()));
|
|
465
|
+
if (!this.backwardKeys.has(goalKey)) return true;
|
|
466
|
+
let only = null;
|
|
467
|
+
let count = 0;
|
|
468
|
+
for (const clause of this.clausesOf.get(goalKey)) {
|
|
469
|
+
const names = new Map();
|
|
470
|
+
const suffix = `h${++fresh}`;
|
|
471
|
+
const head = freshTerm(clause.head, suffix, names);
|
|
472
|
+
const local = new Env();
|
|
473
|
+
if (!unify(resolved, head, local)) continue;
|
|
474
|
+
if (depth && !clause.body.every((item) => this.holds(freshTerm(item, suffix, names), depth - 1, local))) continue;
|
|
475
|
+
if (++count > 1) return true;
|
|
476
|
+
only = clause.body.length ? null : copyResolved(head, local);
|
|
477
|
+
}
|
|
478
|
+
if (only !== null) unify(resolved, only, env);
|
|
479
|
+
return count > 0;
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
// Whether a goal that is no premise reads facts that can be new: a data
|
|
483
|
+
// goal inside a control goal, or a backward relation that reads them.
|
|
484
|
+
readsNew(goal) {
|
|
485
|
+
if (!(goal instanceof Struct || typeof goal === 'string')) return goal instanceof Var;
|
|
486
|
+
const goalKey = key(goal);
|
|
487
|
+
if (this.data.has(goalKey)) return this.mayBeNew(goal);
|
|
488
|
+
if (CONTROL_KEYS.has(goalKey)) return goal.args.some((arg) => this.readsNew(arg));
|
|
489
|
+
if (!this.backwardKeys.has(goalKey)) return false;
|
|
490
|
+
let reads = this.readsMemo.get(goalKey);
|
|
491
|
+
if (reads !== undefined) return reads;
|
|
492
|
+
const seen = new Set([goalKey]);
|
|
493
|
+
const walk = (item) => {
|
|
494
|
+
if (!(item instanceof Struct || typeof item === 'string')) return item instanceof Var;
|
|
495
|
+
const itemKey = key(item);
|
|
496
|
+
if (this.data.has(itemKey)) return this.mayBeNew(item);
|
|
497
|
+
if (CONTROL_KEYS.has(itemKey)) return item.args.some(walk);
|
|
498
|
+
if (!this.backwardKeys.has(itemKey) || seen.has(itemKey)) return false;
|
|
499
|
+
seen.add(itemKey);
|
|
500
|
+
return this.clausesOf.get(itemKey).some((c) => c.body.some(walk));
|
|
501
|
+
};
|
|
502
|
+
reads = this.clausesOf.get(goalKey).some((c) => c.body.some(walk));
|
|
503
|
+
this.readsMemo.set(goalKey, reads);
|
|
504
|
+
return reads;
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
// A goal that is not a premise of a variant, with its data goals reading
|
|
508
|
+
// old facts, or old and new ones; negating or collecting new facts is not
|
|
509
|
+
// specialized.
|
|
510
|
+
rewrite(goal, negated, need) {
|
|
511
|
+
if (goal instanceof Var) throw new Unsupported('a goal is a variable');
|
|
512
|
+
if (!(goal instanceof Struct || typeof goal === 'string')) return goal;
|
|
513
|
+
const goalKey = key(goal);
|
|
514
|
+
if (this.data.has(goalKey)) {
|
|
515
|
+
const may = this.mayBeNew(goal);
|
|
516
|
+
if (may && negated) throw new Unsupported(`it negates or collects ${goalKey} facts that can be new`);
|
|
517
|
+
need(goal);
|
|
518
|
+
return may ? new Struct('or', [old(goal), goal]) : old(goal);
|
|
519
|
+
}
|
|
520
|
+
if (NEGATING.has(goalKey)) {
|
|
521
|
+
const at = goalKey === 'not/1' ? 0 : 1;
|
|
522
|
+
return new Struct(goal.name, goal.args.map((arg, i) => i === at ? this.rewrite(arg, true, need) : arg));
|
|
523
|
+
}
|
|
524
|
+
if (CONTROL_KEYS.has(goalKey)) return new Struct(goal.name, goal.args.map((arg) => this.rewrite(arg, negated, need)));
|
|
525
|
+
if (negated && this.readsNew(goal)) {
|
|
526
|
+
throw new Unsupported(`it negates or collects ${goalKey}, which reads facts that can be new`);
|
|
527
|
+
}
|
|
528
|
+
return goal;
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
// Each variant of a forward rule: emit(heads, body, newIndex), the body a
|
|
532
|
+
// list of [goal, mode], mode 'new', 'old' or null for a goal that is no
|
|
533
|
+
// premise, and newIndex the position of the first new premise.
|
|
534
|
+
variants(rule, emit) {
|
|
535
|
+
const names = new Map();
|
|
536
|
+
const suffix = `s${++fresh}`;
|
|
537
|
+
const heads = rule.heads.filter((head) => head !== 'true').map((head) => freshTerm(head, suffix, names));
|
|
538
|
+
const body = rule.body.map((goal) => freshTerm(goal, suffix, names));
|
|
539
|
+
const data = body.map((goal, i) => this.data.has(key(goal)) ? i : -1).filter((i) => i >= 0);
|
|
540
|
+
// A negation or collection of what can be new is refused whether or not
|
|
541
|
+
// a variant survives: more facts could retract an old conclusion.
|
|
542
|
+
for (const goal of body) if (!this.data.has(key(goal))) this.rewrite(goal, false, () => {});
|
|
543
|
+
// A goal that is no premise but reads new facts makes a variant new.
|
|
544
|
+
const reading = body.some((goal) => !this.data.has(key(goal)) && this.readsNew(goal));
|
|
545
|
+
const modes = new Array(body.length).fill(null);
|
|
546
|
+
const env = new Env();
|
|
547
|
+
let leaves = 0;
|
|
548
|
+
const leaf = (count) => {
|
|
549
|
+
if (!count && !reading) return;
|
|
550
|
+
const mark = env.mark();
|
|
551
|
+
try {
|
|
552
|
+
for (const [i, goal] of body.entries()) if (modes[i] === null && !this.holds(goal, DEPTH, env)) return;
|
|
553
|
+
settled(count);
|
|
554
|
+
} finally {
|
|
555
|
+
env.undo(mark);
|
|
556
|
+
}
|
|
557
|
+
};
|
|
558
|
+
const settled = () => {
|
|
559
|
+
const resolved = body.map((goal) => copyResolved(goal, env));
|
|
560
|
+
const premises = resolved.filter((_, i) => modes[i] === 'new' || modes[i] === 'old');
|
|
561
|
+
const kept = heads.map((head) => copyResolved(head, env)).filter((head) => head === 'false' ||
|
|
562
|
+
(!premises.some((goal) => identical(goal, head)) && !(isGround(head) && this.oldIds.has(identity(head)))));
|
|
563
|
+
if (!kept.length) return;
|
|
564
|
+
const list = [];
|
|
565
|
+
let newIndex = -1;
|
|
566
|
+
resolved.forEach((goal, i) => {
|
|
567
|
+
if (modes[i] === 'fact') return;
|
|
568
|
+
if (modes[i] === 'new' && newIndex < 0) newIndex = list.length;
|
|
569
|
+
list.push([goal, modes[i], body[i]]);
|
|
570
|
+
});
|
|
571
|
+
emit(kept, list, newIndex, list.map(([, , original]) => original instanceof Struct ? original.args.map((arg) => arg instanceof Var) : []));
|
|
572
|
+
};
|
|
573
|
+
// The variables in the property, or rdf:type class, of the conclusions
|
|
574
|
+
// and the other premises: unfolding an old premise that binds one makes
|
|
575
|
+
// a pattern specific.
|
|
576
|
+
const keyed = (i) => {
|
|
577
|
+
const found = new Set();
|
|
578
|
+
for (const term of [...heads, ...data.filter((j) => j !== i).map((j) => body[j])]) {
|
|
579
|
+
if (!(term instanceof Struct) || !this.quads.has(key(term))) continue;
|
|
580
|
+
const [, p, o] = term.args.map((arg) => copyResolved(arg, env));
|
|
581
|
+
for (const name of variables(p).keys()) found.add(name);
|
|
582
|
+
if (p instanceof Var || isType(p)) for (const name of variables(o).keys()) found.add(name);
|
|
583
|
+
}
|
|
584
|
+
return found;
|
|
585
|
+
};
|
|
586
|
+
const visit = (pending, count) => {
|
|
587
|
+
if (++this.steps > STEPS) throw new Unsupported('its messages need too many specialized rules');
|
|
588
|
+
if (!pending.length) return leaf(count);
|
|
589
|
+
if (!count && !reading && !pending.some((i) => this.mayBeNew(body[i], env))) return;
|
|
590
|
+
// The premise with the fewest alternatives first; none ends the search.
|
|
591
|
+
let choice = null;
|
|
592
|
+
for (const [at, i] of pending.entries()) {
|
|
593
|
+
const goal = body[i];
|
|
594
|
+
const patterns = this.newPatterns(goal, env);
|
|
595
|
+
const facts = this.matches(goal, env, MANY);
|
|
596
|
+
const any = facts === null || facts.length > 0;
|
|
597
|
+
let unfold = facts !== null && facts.length > 0 && facts.length <= UNFOLD;
|
|
598
|
+
if (unfold) {
|
|
599
|
+
const names = keyed(i);
|
|
600
|
+
unfold = [...variables(copyResolved(goal, env)).keys()].some((name) => names.has(name));
|
|
601
|
+
}
|
|
602
|
+
const branches = patterns.length + (unfold ? facts.length : any ? 1 : 0);
|
|
603
|
+
if (!branches) return;
|
|
604
|
+
if (choice === null || branches < choice.branches) choice = { at, i, patterns, facts, any, unfold, branches };
|
|
605
|
+
}
|
|
606
|
+
const { at, i, patterns, facts, any, unfold } = choice;
|
|
607
|
+
const rest = pending.filter((_, k) => k !== at);
|
|
608
|
+
const goal = body[i];
|
|
609
|
+
for (const pattern of patterns) {
|
|
610
|
+
const mark = env.mark();
|
|
611
|
+
if (unify(goal, pattern, env)) {
|
|
612
|
+
modes[i] = 'new';
|
|
613
|
+
visit(rest, count + 1);
|
|
614
|
+
}
|
|
615
|
+
env.undo(mark);
|
|
616
|
+
}
|
|
617
|
+
// Old: possible only if a later premise can still be new.
|
|
618
|
+
if (any && (count || reading || rest.some((j) => this.mayBeNew(body[j], env)))) {
|
|
619
|
+
if (unfold) {
|
|
620
|
+
for (const fact of facts) {
|
|
621
|
+
const mark = env.mark();
|
|
622
|
+
if (unify(goal, fact, env)) {
|
|
623
|
+
modes[i] = 'fact';
|
|
624
|
+
if (++leaves > LEAVES) throw new Unsupported(`rule ${rule.id} has too many specialized instances`);
|
|
625
|
+
visit(rest, count);
|
|
626
|
+
}
|
|
627
|
+
env.undo(mark);
|
|
628
|
+
}
|
|
629
|
+
} else {
|
|
630
|
+
// What all the old facts it matches share, such as the same
|
|
631
|
+
// subject and object, still binds the premise.
|
|
632
|
+
const mark = env.mark();
|
|
633
|
+
if (facts !== null) unify(goal, generalize(facts), env);
|
|
634
|
+
modes[i] = 'old';
|
|
635
|
+
visit(rest, count);
|
|
636
|
+
env.undo(mark);
|
|
637
|
+
}
|
|
638
|
+
}
|
|
639
|
+
modes[i] = null;
|
|
640
|
+
};
|
|
641
|
+
visit(data, 0);
|
|
642
|
+
}
|
|
643
|
+
}
|
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.
|
|
2
|
+
export const VERSION = '0.8.12';
|