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/src/le.js CHANGED
@@ -15,6 +15,54 @@ const RESERVED = new Set([...PRIMITIVE_KEYS, ...CONTROL_KEYS, ...RESERVED_KEYS].
15
15
  for (const name of ['true', 'false', 'fail']) RESERVED.add(name);
16
16
  const OPERATORS = { '+': ['add', 1], '-': ['sub', 1], '*': ['mul', 2], '/': ['div', 2] };
17
17
  const list = (items) => items.reduceRight((tail, head) => st('.', head, tail), EMPTY);
18
+ const cons = (head, tail) => st('.', head, tail);
19
+ const AGGREGATES = { number: 'le:count', sum: 'le:sum', maximum: 'le:max', minimum: 'le:min' };
20
+
21
+ // Aggregates collect t(...) tuples with findall_sorted, drop repeated tuples
22
+ // with le:distinct and fold the rest with these backward rules. Their names
23
+ // contain ':', which no LE name can, so they never meet a user's relation.
24
+ // Each clause is a function so that every use has its own variables.
25
+ const HELPERS = {
26
+ 'le:distinct': [
27
+ () => [st('le:distinct', EMPTY, EMPTY), []],
28
+ () => { const X = new Var('X'); return [st('le:distinct', list([X]), list([X])), []]; },
29
+ () => {
30
+ const X = new Var('X'), Y = new Var('Y'), T = new Var('T'), R = new Var('R');
31
+ return [st('le:distinct', cons(X, cons(Y, T)), R), [st('identical', X, Y), st('le:distinct', cons(Y, T), R)]];
32
+ },
33
+ () => {
34
+ const X = new Var('X'), Y = new Var('Y'), T = new Var('T'), R = new Var('R');
35
+ return [st('le:distinct', cons(X, cons(Y, T)), cons(X, R)), [st('not_identical', X, Y), st('le:distinct', cons(Y, T), R)]];
36
+ },
37
+ ],
38
+ 'le:count': [
39
+ () => [st('le:count', EMPTY, 0n), []],
40
+ () => {
41
+ const H = new Var('H'), T = new Var('T'), N = new Var('N'), M = new Var('M');
42
+ return [st('le:count', cons(H, T), N), [st('le:count', T, M), st('is', N, st('add', M, 1n))]];
43
+ },
44
+ ],
45
+ 'le:sum': [
46
+ () => [st('le:sum', EMPTY, 0n), []],
47
+ () => {
48
+ const H = new Var('H'), T = new Var('T'), S = new Var('S'), S0 = new Var('S0'), V = new Var('V');
49
+ return [st('le:sum', cons(H, T), S), [st('arg', 1n, H, V), st('le:sum', T, S0), st('is', S, st('add', S0, V))]];
50
+ },
51
+ ],
52
+ 'le:max': extremum('le:max', 'ge', 'lt'),
53
+ 'le:min': extremum('le:min', 'le', 'gt'),
54
+ };
55
+
56
+ // The value of a list's best tuple; an empty list has none.
57
+ function extremum(name, keep, pass) {
58
+ const one = () => { const H = new Var('H'), V = new Var('V'); return [st(name, list([H]), V), [st('arg', 1n, H, V)]]; };
59
+ const more = (test, chosen) => () => {
60
+ const H = new Var('H'), I = new Var('I'), T = new Var('T'), M = new Var('M'), M0 = new Var('M0'), V = new Var('V');
61
+ return [st(name, cons(H, cons(I, T)), M),
62
+ [st(name, cons(I, T), M0), st('arg', 1n, H, V), st(test, V, M0), st('unify', M, chosen(V, M0))]];
63
+ };
64
+ return [one, more(keep, (V) => V), more(pass, (V, M0) => M0)];
65
+ }
18
66
 
19
67
  function listItems(term) {
20
68
  const items = [];
@@ -31,6 +79,9 @@ class Parser {
31
79
  this.tokens = [];
32
80
  this.at = 0;
33
81
  this.scope = new Map();
82
+ this.closed = new Set();
83
+ this.helpers = new Set();
84
+ this.aggregates = 0;
34
85
  this.depth = 0;
35
86
  let line = 1, pos = 0;
36
87
  while (pos < text.length) {
@@ -130,6 +181,7 @@ class Parser {
130
181
  return st(token.value, ...args);
131
182
  }
132
183
  if (token.kind === 'word' && VARIABLE.test(token.value)) {
184
+ if (this.closed.has(token.value)) this.error(`variable ${token.value} belongs to the aggregate that declares it and cannot be used outside it`, token.line);
133
185
  if (!this.scope.has(token.value)) this.error(`variable ${token.value} is undeclared; introduce it with "For every", "Find every" or "there exists", or quote it as a name`, token.line);
134
186
  return this.scope.get(token.value);
135
187
  }
@@ -180,8 +232,10 @@ class Parser {
180
232
  }
181
233
  if (body) {
182
234
  if (this.take('the')) {
183
- this.need('value'); this.need('of');
184
235
  if (!(subject instanceof Var) && !['bigint', 'number'].includes(typeof subject)) this.error('a calculation needs a variable or number on its left');
236
+ const kind = Object.keys(AGGREGATES).find((word) => this.is(word));
237
+ if (kind) return this.aggregate(subject, kind);
238
+ this.need('value'); this.need('of');
185
239
  return st('is', subject, this.expression());
186
240
  }
187
241
  let comparison;
@@ -205,15 +259,78 @@ class Parser {
205
259
  this.error('expected "is a class", "is a relation of", or a relation call such as parent(Alice, Bob)');
206
260
  }
207
261
 
262
+ // An aggregate statement stands for several goals, so goals are flattened.
208
263
  goals(body) {
209
264
  const goals = [this.atomic(body)];
210
265
  while (this.take('and')) goals.push(this.atomic(body));
211
- return goals;
266
+ return goals.flat();
267
+ }
268
+
269
+ // Premises joined by "or", with "and" binding more tightly; each
270
+ // alternative becomes a clause of its own.
271
+ alternatives() {
272
+ const result = [this.goals(true)];
273
+ while (this.take('or')) result.push(this.goals(true));
274
+ return result;
275
+ }
276
+
277
+ // "N is the number of X and Y such that ..." counts the distinct
278
+ // combinations of the declared variables; sum, maximum and minimum fold the
279
+ // value V over them. The condition is one statement or a conjunction in
280
+ // parentheses, and its declared variables stay inside it.
281
+ aggregate(result, kind) {
282
+ this.at++; this.need('of');
283
+ let value = null;
284
+ if (kind !== 'number') {
285
+ if (this.token.kind !== 'word' || !VARIABLE.test(this.token.value)) {
286
+ this.error(`"the ${kind} of" needs a variable, as in "the ${kind} of V for every X and V such that ..."`);
287
+ }
288
+ value = this.token.value;
289
+ this.at++; this.need('for'); this.need('every');
290
+ }
291
+ const locals = this.declarations();
292
+ if (value !== null && !locals.some((v) => v.name === value)) this.error(`${value} must be declared after "for every" in its aggregate`);
293
+ this.need('such'); this.need('that');
294
+ let condition;
295
+ if (this.take('(')) { condition = this.goals(true); this.need(')'); }
296
+ else condition = [this.atomic(true)].flat();
297
+ if (condition.some((goal) => goal instanceof Struct && goal.name === 'findall_sorted')) {
298
+ this.error('an aggregate cannot contain another aggregate; derive the inner one in a rule and use its conclusion');
299
+ }
300
+ for (const v of locals) this.closed.add(v.name);
301
+ const ordered = value === null ? locals : [locals.find((v) => v.name === value), ...locals.filter((v) => v.name !== value)];
302
+ const n = ++this.aggregates, all = new Var(`Agg${n}`), distinct = new Var(`Agg${n}d`), helper = AGGREGATES[kind];
303
+ this.helpers.add('le:distinct');
304
+ this.helpers.add(helper);
305
+ return [st('findall_sorted', st('t', ...ordered), conjunction(condition), all),
306
+ st('le:distinct', all, distinct), st(helper, distinct, result)];
307
+ }
308
+
309
+ // Calculations, comparisons and absence tests need their inputs from
310
+ // earlier premises; an aggregate needs those of its condition other than
311
+ // its own variables, and checks its condition in the same way.
312
+ checkOrder(goals, bound, line) {
313
+ for (const goal of goals) {
314
+ if (goal instanceof Struct && goal.name === 'findall_sorted') {
315
+ const locals = variablesIn([goal.args[0]]), inner = new Set(bound);
316
+ for (const name of variablesIn([goal.args[1]])) {
317
+ if (!locals.has(name) && !bound.has(name)) this.error(`${name} must be supplied by an earlier premise before the aggregate that uses it`, line);
318
+ }
319
+ this.checkOrder(flattenConjunction(goal.args[1]), inner, line);
320
+ bound.add(goal.args[2].name);
321
+ continue;
322
+ }
323
+ const required = goal instanceof Struct && RESERVED.has(goal.name) ? variablesIn(goal.name === 'is' ? [goal.args[1]] : [goal]) : new Set();
324
+ for (const name of required) if (!bound.has(name)) this.error(`${name} must be supplied by an earlier positive premise or calculation`, line);
325
+ if (!(goal instanceof Struct && goal.name === 'not')) for (const name of variablesIn([goal])) bound.add(name);
326
+ }
327
+ return bound;
212
328
  }
213
329
 
214
330
  sentence() {
215
331
  const line = this.token.line;
216
332
  this.scope = new Map();
333
+ this.closed = new Set();
217
334
  if (this.is('use') && this.tokens[this.at + 1]?.kind === 'word' && this.tokens[this.at + 1].value.toLowerCase() === 'odrl') {
218
335
  this.at++;
219
336
  this.need('odrl');
@@ -229,45 +346,49 @@ class Parser {
229
346
  return { kind: 'odrl', namespace, evaluate, line };
230
347
  }
231
348
  if (this.take('every')) {
232
- const from = this.name(); this.need('is');
233
- const x = new Var('X'), heads = [];
349
+ const x = new Var('X'), froms = [this.name()], heads = [];
350
+ while (this.take('or')) froms.push(this.name());
351
+ this.need('is');
234
352
  do { this.take('a') || this.take('an'); heads.push(st(this.name(), x)); } while (this.take('and'));
235
353
  this.need('.');
236
- return { kind: 'forward', heads, body: [st(from, x)], line };
354
+ return { kind: 'forward', heads, bodies: froms.map((from) => [st(from, x)]), line };
237
355
  }
238
356
  let quantified = false;
239
357
  if (this.take('for')) { this.need('every'); this.declarations(); this.need(','); quantified = true; }
240
- let kind = 'fact', body = [], heads = [], witnesses = [];
358
+ let kind = 'fact', bodies = [[]], heads = [], witnesses = [];
241
359
  if (this.take('find')) {
242
360
  if (quantified) this.error('a question introduces its variables with "Find every"');
243
361
  if (this.take('every')) { this.declarations(); this.need('such'); this.need('that'); }
244
362
  else this.need('whether');
245
- kind = 'query'; body = this.goals(true);
363
+ kind = 'query'; bodies = [this.goals(true)];
364
+ if (this.is('or')) this.error('a question has no "or"; ask one question per alternative, or derive a relation with an "or" rule and ask for it');
365
+ if (bodies[0].some((goal) => goal instanceof Struct && goal.name === 'findall_sorted')) {
366
+ this.error('a question cannot aggregate; derive the aggregate in a rule and ask for its conclusion');
367
+ }
246
368
  } else if (this.take('contradiction')) {
247
- kind = 'contradiction'; body = ['true'];
369
+ kind = 'contradiction'; bodies = [['true']];
248
370
  } else if (this.take('it')) {
249
371
  this.need('is'); this.need('impossible'); this.need('that');
250
- kind = 'contradiction'; body = this.goals(true);
372
+ kind = 'contradiction'; bodies = this.alternatives();
251
373
  } else {
252
- if (this.take('if')) { kind = 'forward'; body = this.goals(true); this.need('then'); }
374
+ if (this.take('if')) { kind = 'forward'; bodies = this.alternatives(); this.need('then'); }
253
375
  if (this.take('there')) {
254
376
  this.need('exists'); witnesses = this.declarations(); this.need('such'); this.need('that');
255
- if (kind === 'fact') { kind = 'forward'; body = ['true']; }
377
+ if (kind === 'fact') { kind = 'forward'; bodies = [['true']]; }
256
378
  }
257
379
  heads = this.goals(false);
258
380
  }
259
381
  this.need('.');
260
- const headVars = variablesIn(heads), bound = new Set(), witnessNames = new Set(witnesses.map((v) => v.name));
261
- for (const goal of body) {
262
- const required = goal instanceof Struct && RESERVED.has(goal.name) ? variablesIn(goal.name === 'is' ? [goal.args[1]] : [goal]) : new Set();
263
- for (const name of required) if (!bound.has(name)) this.error(`${name} must be supplied by an earlier positive premise or calculation`, line);
264
- if (!(goal instanceof Struct && goal.name === 'not')) for (const name of variablesIn([goal])) bound.add(name);
265
- }
382
+ const headVars = variablesIn(heads), witnessNames = new Set(witnesses.map((v) => v.name));
266
383
  if (witnesses.some((v) => !headVars.has(v.name))) this.error('every existential variable must occur in its conclusion', line);
267
- if (kind === 'forward' && [...headVars].some((name) => !bound.has(name) && !witnessNames.has(name))) {
268
- this.error('a conclusion variable must occur in a premise or be introduced with "there exists"', line);
384
+ for (const body of bodies) {
385
+ const bound = this.checkOrder(body, new Set(), line);
386
+ if (kind === 'forward' && [...headVars].some((name) => !bound.has(name) && !witnessNames.has(name))) {
387
+ this.error(bodies.length > 1 ? 'a conclusion variable must occur in every alternative of an "or" premise, or be introduced with "there exists"'
388
+ : 'a conclusion variable must occur in a premise or be introduced with "there exists"', line);
389
+ }
269
390
  }
270
- return { kind, heads, body, line };
391
+ return { kind, heads, bodies, line };
271
392
  }
272
393
  }
273
394
 
@@ -291,34 +412,47 @@ function javascript(term) {
291
412
  }
292
413
 
293
414
  export function compileLe(inputs) {
294
- const clauses = [], statements = [], sources = [];
415
+ const clauses = [], statements = [], sources = [], helpers = new Set();
295
416
  let profile = null;
296
417
  for (const [text, file] of inputs) {
297
418
  const parser = new Parser(String(text), file);
298
419
  while (parser.token.kind !== 'end') {
299
- const sentence = parser.sentence(), { kind, heads, body, line } = sentence;
420
+ const sentence = parser.sentence(), { kind, heads, bodies, line } = sentence;
300
421
  if (kind === 'odrl') {
301
422
  if (profile || statements.length || inputs.length !== 1) parser.error('an ODRL directive must be the first sentence of one LE file', line);
302
423
  profile = { namespace: sentence.namespace, evaluate: sentence.evaluate };
303
424
  continue;
304
425
  }
305
- statements.push({ ...sentence, file });
306
426
  clauses.push(`// ${String(file).replace(/[\r\n\u2028\u2029]/g, ' ')}: line ${line}`);
307
- if (kind === 'fact') {
308
- for (const head of heads) {
309
- clauses.push(`fact(${javascript(head)})`);
310
- sources.push(new Source('fact', head, [], line, file));
427
+ for (const body of bodies) {
428
+ statements.push({ kind, heads, body, line, file });
429
+ if (kind === 'fact') {
430
+ for (const head of heads) {
431
+ clauses.push(`fact(${javascript(head)})`);
432
+ sources.push(new Source('fact', head, [], line, file));
433
+ }
434
+ } else if (kind === 'forward') {
435
+ clauses.push(`implies(${javascript(conjunction(body))}, ${javascript(conjunction(heads))})`);
436
+ sources.push(new Source('forward', conjunction(heads), body, line, file));
437
+ } else {
438
+ clauses.push(`${kind}(${body.map(javascript).join(', ')})`);
439
+ sources.push(new Source(kind, kind === 'query' ? 'true' : 'false', body, line, file));
311
440
  }
312
- } else if (kind === 'forward') {
313
- clauses.push(`implies(${javascript(conjunction(body))}, ${javascript(conjunction(heads))})`);
314
- sources.push(new Source('forward', conjunction(heads), body, line, file));
315
- } else {
316
- clauses.push(`${kind}(${body.map(javascript).join(', ')})`);
317
- sources.push(new Source(kind, kind === 'query' ? 'true' : 'false', body, line, file));
318
441
  }
319
442
  }
443
+ for (const name of parser.helpers) helpers.add(name);
320
444
  }
321
445
  if (profile) return compileOdrlLe(statements, profile, inputs[0][1]);
446
+ // The helpers follow every stated clause, so a witness's rule number is
447
+ // the same whether or not the program aggregates.
448
+ if (helpers.size) clauses.push('// Aggregation helpers.');
449
+ for (const name of Object.keys(HELPERS).filter((key) => helpers.has(key))) {
450
+ for (const make of HELPERS[name]) {
451
+ const [head, body] = make();
452
+ clauses.push(`implied_by(${javascript(head)}, ${body.length ? javascript(conjunction(body)) : "'true'"})`);
453
+ sources.push(new Source('backward', head, body.length ? body : ['true'], null, null));
454
+ }
455
+ }
322
456
  return { kind: 'le', text: '// Compiled from Logical English to Logic Script.\n\n' + clauses.join('\n') + '\n',
323
457
  program: new Program(sources), prefixes: {}, compiled: { statements } };
324
458
  }
@@ -66,7 +66,7 @@ export async function streamMessages(request, io) {
66
66
  let code = 0;
67
67
  const reader = new RdfMessageReader({ format: source.format ?? rdfMessageFormat(name), base: request.base ?? source.base, scope,
68
68
  onMessage: (message) => {
69
- code = request.run(inputs, name, replayMessages([message], { scope }));
69
+ code = request.run(inputs, name, replayMessages([message], { scope }), message);
70
70
  return code === 0;
71
71
  } });
72
72
  for await (const text of source.body) {
package/src/program.js CHANGED
@@ -200,6 +200,37 @@ export class Program {
200
200
  this.layered = this.strata.layered === true;
201
201
  }
202
202
 
203
+ // This program with more ground facts after its clauses, sharing its
204
+ // rules and strata: a fact changes no stratum. Programs specialized for
205
+ // RDF Messages (specialize.js) get each message's facts this way.
206
+ withFacts(facts) {
207
+ const program = Object.assign(Object.create(Program.prototype), this);
208
+ program.sources = [...this.sources];
209
+ program.clauses = [...this.clauses];
210
+ program.byId = new Map(this.byId);
211
+ program.groups = new Map(this.groups);
212
+ program.indexes = new Map(this.indexes);
213
+ program.groundFactKeys = new Set(this.groundFactKeys);
214
+ for (const fact of facts) {
215
+ if (!isCallable(fact) || !isGround(fact) || fact === EMPTY || isTerm(fact, '.', 2) || RESERVED_KEYS.has(key(fact)) ||
216
+ PRIMITIVE_KEYS.has(key(fact)) || CONTROL_KEYS.has(key(fact))) {
217
+ throw new EyemindError(`${write(fact)} is not a ground fact`);
218
+ }
219
+ const source = new Source('fact', fact, []);
220
+ const clause = new Clause(++program.maxClauseId, fact, null, [], false, null);
221
+ clause.originalHead = fact;
222
+ clause.plainHeads = [fact];
223
+ program.sources.push(source);
224
+ program.clauses.push(clause);
225
+ program.byId.set(clause.id, clause);
226
+ const factKey = key(fact);
227
+ program.groups.set(factKey, [...(program.groups.get(factKey) ?? []), clause]);
228
+ program.indexes.delete(factKey);
229
+ program.groundFactKeys.add(identity(fact));
230
+ }
231
+ return program;
232
+ }
233
+
203
234
  // Restricted rules in the order they run: one whose heads can satisfy
204
235
  // another's, its witnesses free, before that one, and otherwise, as on a
205
236
  // cycle of such rules, in clause order (SPEC Section 8.2).
package/src/rdf-logic.js CHANGED
@@ -2,7 +2,7 @@
2
2
  // feed back into it; LS stratification closes inference before validation.
3
3
  import { loadText } from './lang.js';
4
4
  import { rdfDocument } from './rdf.js';
5
- import { write } from './writer.js';
5
+ import { Lettering, write } from './writer.js';
6
6
  import { owl2rlRules } from './owl2rl.js';
7
7
  import { skosRules } from './skos.js';
8
8
  import { qudtRules } from './qudt.js';
@@ -10,11 +10,15 @@ import { compileShacl } from './shacl.js';
10
10
  import { NODE_FUNCTIONS } from './shacl-expr.js';
11
11
  import { executionContext } from './srl.js';
12
12
  import { rdfValueRules } from './rdf-values.js';
13
+ import { run } from './engine.js';
14
+ import { Specializer } from './specialize.js';
15
+ import { Env, Struct, freshTerm, identity, unify } from './terms.js';
13
16
 
14
17
  export const ENTAILMENT = 'https://eyereasoner.github.io/eyemind/entailment#';
15
18
  export const RDF_PROFILES = ['owl2rl', 'qudt', 'skos', 'shacl'];
16
19
 
17
- export function compileRdfLogic({ quads, prefixes, shapes = quads }, { profiles, source = '<input>', disallows, evaluate, context }) {
20
+ // wanted: rdf/4 patterns of the output contract, or null for every new triple.
21
+ export function compileRdfLogic({ quads, prefixes, shapes = quads, wanted = null }, { profiles, source = '<input>', disallows, evaluate, context, stream = false }) {
18
22
  quads = [...new Map(quads.map((q) => [q.map((t) => write(t)).join(' '), q])).values()];
19
23
  const selected = new Set(profiles), needs = new Set();
20
24
  // SHACL node expressions may call SPARQL functions beyond the value rules.
@@ -32,13 +36,58 @@ export function compileRdfLogic({ quads, prefixes, shapes = quads }, { profiles,
32
36
  (selected.has('owl2rl') ? owl2rlRules : '') +
33
37
  (selected.has('skos') ? skosRules : '') +
34
38
  (selected.has('qudt') ? qudtRules : '') +
35
- shacl + (evaluate ? "query(sh_evaluation(R));\n" : OUTPUT);
39
+ shacl + (evaluate ? "query(sh_evaluation(R));\n" : REPORTS + (stream ? '' : wanted === null ? RESULT : contracted(wanted)));
36
40
  return { kind: profiles[0], text, program: loadText(text, source),
37
41
  prefixes: { ...prefixes, ent: ENTAILMENT, ...(selected.has('skos') ? { skos: 'http://www.w3.org/2004/02/skos/core#' } : {}),
38
42
  ...(selected.has('qudt') ? { qconv: 'https://eyereasoner.github.io/eyemind/qudt#', qudt: 'http://qudt.org/schema/qudt/', unit: 'http://qudt.org/vocab/unit/' } : {}),
39
43
  ...(selected.has('shacl') ? { sh: 'http://www.w3.org/ns/shacl#' } : {}) }, compiled: null };
40
44
  }
41
45
 
46
+ // Reasoning over messages one at a time, each with the same background
47
+ // graph: infer(quads) gives the triples a message adds to what the background
48
+ // alone concludes. The background is closed once and the rules are
49
+ // specialized to the kinds of triples a message has (specialize.js); a
50
+ // program that cannot be specialized runs whole for every message instead.
51
+ // With an output contract, only the rules that can contribute to its
52
+ // patterns are specialized, and only triples matching one are written.
53
+ export function messageReasoner({ quads, prefixes, wanted = null }, { profiles, source = '<input>' }) {
54
+ const options = { profiles, source };
55
+ const background = compileRdfLogic({ quads, prefixes }, { ...options, stream: true });
56
+ const specializer = new Specializer(background.program, { quads: ['rdf/4', 'ent_base/4'],
57
+ wanted: wanted && wanted.flatMap((pattern) => [pattern, new Struct('ent_report', pattern.args)]) });
58
+ let serial = 0;
59
+ const kept = (quad) => wanted === null ||
60
+ wanted.some((pattern) => unify(new Struct('rdf', quad), freshTerm(pattern, `w${++serial}`), new Env()));
61
+ let alone = null;
62
+ const answers = (program, limits) => run(program, limits).conclusions.filter((t) => t instanceof Struct && t.name === 'result_rdf');
63
+ return {
64
+ prefixes: background.prefixes,
65
+ reason: specializer.reason,
66
+ specializer,
67
+ // limits are run()'s bounds. The result has the added quads, whether
68
+ // the rules were specialized, and the specialized program's sources the
69
+ // first time a message has its shape.
70
+ infer(message, limits = {}) {
71
+ const facts = message.flatMap((q) => [new Struct('rdf', q), new Struct('ent_base', q)]);
72
+ const special = specializer.specialize(facts);
73
+ if (special !== null) {
74
+ const result = run(special.program, limits);
75
+ const added = result.derived.map((node) => node.goal).filter((t) => !special.old.has(identity(t)) &&
76
+ (t.name === 'ent_report' || (t.name === 'rdf' && RESOURCES.has(t.args[0].name) && t.args[1].name === 'iri')));
77
+ return { quads: added.map((t) => t.args).filter(kept), specialized: true, stats: result.stats, haltCode: result.haltCode,
78
+ sources: special.fresh ? special.sources : null };
79
+ }
80
+ alone ??= new Set(answers(compileRdfLogic({ quads, prefixes }, options).program, limits).map(identity));
81
+ const result = run(compileRdfLogic({ quads: [...quads, ...message], prefixes, shapes: quads }, options).program, limits);
82
+ const added = result.conclusions.filter((t) => t instanceof Struct && t.name === 'result_rdf' && !alone.has(identity(t)));
83
+ return { quads: added.map((t) => t.args).filter(kept), specialized: false, stats: result.stats, haltCode: result.haltCode, sources: null };
84
+ },
85
+ };
86
+ }
87
+
88
+ // The subjects ent_resource/1 accepts.
89
+ const RESOURCES = new Set(['iri', 'bnode', 'skolem', 'triple']);
90
+
42
91
  const COMMON = String.raw`
43
92
  implied_by(ent_resource(iri(A)), is_atom(A));
44
93
  implied_by(ent_resource(bnode(A, B)), [is_atom(A), is_atom(B)]);
@@ -52,7 +101,7 @@ fact(ent_member(X, [X, ..._]));
52
101
  implied_by(ent_member(X, [_, ...T]), ent_member(X, T));
53
102
  `;
54
103
 
55
- const OUTPUT = String.raw`
104
+ const REPORTS = String.raw`
56
105
  // A report cannot create more ontology consequences or affect a constraint.
57
106
  implies(ent_conflict(R, X, P, Y, G), [
58
107
  ent_report(B, iri('http://www.w3.org/1999/02/22-rdf-syntax-ns#type'), iri('https://eyereasoner.github.io/eyemind/entailment#Conflict'), G),
@@ -61,7 +110,13 @@ implies(ent_conflict(R, X, P, Y, G), [
61
110
  ent_report(B, iri('https://eyereasoner.github.io/eyemind/entailment#left'), P, G),
62
111
  ent_report(B, iri('https://eyereasoner.github.io/eyemind/entailment#right'), Y, G)
63
112
  ]);
64
- implies([rdf(S, iri(P), O, G), ent_resource(S), not(ent_base(S, iri(P), O, G))], result_rdf(S, iri(P), O, G));
113
+ `;
114
+
115
+ // The result restricted to an output contract: one query per pattern.
116
+ const contracted = (wanted) => RESULT.replace(/^query\(.*\n/m, '') +
117
+ wanted.map((pattern) => `${write(new Struct('query', [new Struct('result_rdf', pattern.args)]), null, new Lettering())};\n`).join('');
118
+
119
+ const RESULT = String.raw`implies([rdf(S, iri(P), O, G), ent_resource(S), not(ent_base(S, iri(P), O, G))], result_rdf(S, iri(P), O, G));
65
120
  implies(ent_report(S, P, O, G), result_rdf(S, P, O, G));
66
121
  query(result_rdf(S, P, O, G));
67
122
  `;