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.
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).
@@ -335,7 +366,7 @@ class Bucket {
335
366
  const NO_ENTRIES = Object.freeze([]);
336
367
 
337
368
  // The entries a positionIndexes map gives for a value, as a list.
338
- function bucketEntries(found) {
369
+ export function bucketEntries(found) {
339
370
  if (found === undefined) return NO_ENTRIES;
340
371
  return found instanceof Bucket ? found.entries : [found];
341
372
  }
package/src/rdf-logic.js CHANGED
@@ -10,11 +10,14 @@ 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 { Struct, identity } 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
+ export function compileRdfLogic({ quads, prefixes, shapes = quads }, { profiles, source = '<input>', disallows, evaluate, context, stream = false }) {
18
21
  quads = [...new Map(quads.map((q) => [q.map((t) => write(t)).join(' '), q])).values()];
19
22
  const selected = new Set(profiles), needs = new Set();
20
23
  // SHACL node expressions may call SPARQL functions beyond the value rules.
@@ -32,13 +35,52 @@ export function compileRdfLogic({ quads, prefixes, shapes = quads }, { profiles,
32
35
  (selected.has('owl2rl') ? owl2rlRules : '') +
33
36
  (selected.has('skos') ? skosRules : '') +
34
37
  (selected.has('qudt') ? qudtRules : '') +
35
- shacl + (evaluate ? "query(sh_evaluation(R));\n" : OUTPUT);
38
+ shacl + (evaluate ? "query(sh_evaluation(R));\n" : REPORTS + (stream ? '' : RESULT));
36
39
  return { kind: profiles[0], text, program: loadText(text, source),
37
40
  prefixes: { ...prefixes, ent: ENTAILMENT, ...(selected.has('skos') ? { skos: 'http://www.w3.org/2004/02/skos/core#' } : {}),
38
41
  ...(selected.has('qudt') ? { qconv: 'https://eyereasoner.github.io/eyemind/qudt#', qudt: 'http://qudt.org/schema/qudt/', unit: 'http://qudt.org/vocab/unit/' } : {}),
39
42
  ...(selected.has('shacl') ? { sh: 'http://www.w3.org/ns/shacl#' } : {}) }, compiled: null };
40
43
  }
41
44
 
45
+ // Reasoning over messages one at a time, each with the same background
46
+ // graph: infer(quads) gives the triples a message adds to what the background
47
+ // alone concludes. The background is closed once and the rules are
48
+ // specialized to the kinds of triples a message has (specialize.js); a
49
+ // program that cannot be specialized runs whole for every message instead.
50
+ export function messageReasoner({ quads, prefixes }, { profiles, source = '<input>' }) {
51
+ const options = { profiles, source };
52
+ const background = compileRdfLogic({ quads, prefixes }, { ...options, stream: true });
53
+ const specializer = new Specializer(background.program, { quads: ['rdf/4', 'ent_base/4'] });
54
+ let alone = null;
55
+ const answers = (program, limits) => run(program, limits).conclusions.filter((t) => t instanceof Struct && t.name === 'result_rdf');
56
+ return {
57
+ prefixes: background.prefixes,
58
+ reason: specializer.reason,
59
+ specializer,
60
+ // limits are run()'s bounds. The result has the added quads, whether
61
+ // the rules were specialized, and the specialized program's sources the
62
+ // first time a message has its shape.
63
+ infer(message, limits = {}) {
64
+ const facts = message.flatMap((q) => [new Struct('rdf', q), new Struct('ent_base', q)]);
65
+ const special = specializer.specialize(facts);
66
+ if (special !== null) {
67
+ const result = run(special.program, limits);
68
+ const added = result.derived.map((node) => node.goal).filter((t) => !special.old.has(identity(t)) &&
69
+ (t.name === 'ent_report' || (t.name === 'rdf' && RESOURCES.has(t.args[0].name) && t.args[1].name === 'iri')));
70
+ return { quads: added.map((t) => t.args), specialized: true, stats: result.stats, haltCode: result.haltCode,
71
+ sources: special.fresh ? special.sources : null };
72
+ }
73
+ alone ??= new Set(answers(compileRdfLogic({ quads, prefixes }, options).program, limits).map(identity));
74
+ const result = run(compileRdfLogic({ quads: [...quads, ...message], prefixes, shapes: quads }, options).program, limits);
75
+ const added = result.conclusions.filter((t) => t instanceof Struct && t.name === 'result_rdf' && !alone.has(identity(t)));
76
+ return { quads: added.map((t) => t.args), specialized: false, stats: result.stats, haltCode: result.haltCode, sources: null };
77
+ },
78
+ };
79
+ }
80
+
81
+ // The subjects ent_resource/1 accepts.
82
+ const RESOURCES = new Set(['iri', 'bnode', 'skolem', 'triple']);
83
+
42
84
  const COMMON = String.raw`
43
85
  implied_by(ent_resource(iri(A)), is_atom(A));
44
86
  implied_by(ent_resource(bnode(A, B)), [is_atom(A), is_atom(B)]);
@@ -52,7 +94,7 @@ fact(ent_member(X, [X, ..._]));
52
94
  implied_by(ent_member(X, [_, ...T]), ent_member(X, T));
53
95
  `;
54
96
 
55
- const OUTPUT = String.raw`
97
+ const REPORTS = String.raw`
56
98
  // A report cannot create more ontology consequences or affect a constraint.
57
99
  implies(ent_conflict(R, X, P, Y, G), [
58
100
  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 +103,9 @@ implies(ent_conflict(R, X, P, Y, G), [
61
103
  ent_report(B, iri('https://eyereasoner.github.io/eyemind/entailment#left'), P, G),
62
104
  ent_report(B, iri('https://eyereasoner.github.io/eyemind/entailment#right'), Y, G)
63
105
  ]);
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));
106
+ `;
107
+
108
+ 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
109
  implies(ent_report(S, P, O, G), result_rdf(S, P, O, G));
66
110
  query(result_rdf(S, P, O, G));
67
111
  `;
package/src/rdf-values.js CHANGED
@@ -97,15 +97,7 @@ implied_by(rv_lexical(rvXsd + 'NCName', L), regex_match('^[\\p{L}_][\\p{L}\\p{N}
97
97
  implied_by(rv_lexical(rvXsd + 'NMTOKEN', L), regex_match('^[\\p{L}\\p{N}._:\\-]+$', L));
98
98
  // rdf:PlainLiteral: text, then @ and an empty or well-formed language tag.
99
99
  implied_by(rv_lexical(rvRdf + 'PlainLiteral', L), regex_match('@(?:[A-Za-z]{1,8}(?:-[A-Za-z0-9]{1,8})*)?$', L));
100
- implied_by(rv_lexical(rvRdf + 'XMLLiteral', L), rv_xml(L));
101
- // A well-formed XML fragment, as far as its tags: each opened tag closes in
102
- // order, and no markup character is left outside a tag.
103
- implied_by(rv_xml(L), [findall([C, N, E], regex_find('<(/?)([\\p{L}_:][\\p{L}\\p{N}._:\\-]*)(?:\\s[^<>]*?)?(/?)>', L, [_, C, N, E]), Tags),
104
- regex_replace('<(/?)([\\p{L}_:][\\p{L}\\p{N}._:\\-]*)(?:\\s[^<>]*?)?(/?)>', L, '', Rest), not(regex_match('[<>]', Rest)), rv_xml_balanced(Tags, [])]);
105
- fact(rv_xml_balanced([], []));
106
- implied_by(rv_xml_balanced([['', _, '/'], ...T], S), rv_xml_balanced(T, S));
107
- implied_by(rv_xml_balanced([['', N, ''], ...T], S), rv_xml_balanced(T, [N, ...S]));
108
- implied_by(rv_xml_balanced([['/', N, ''], ...T], [N, ...S]), rv_xml_balanced(T, S));
100
+ implied_by(rv_lexical(rvRdf + 'XMLLiteral', L), xml_content(L));
109
101
  implied_by(rv_lexical(rvXsd + 'hexBinary', L), regex_match('^[ \\t\\r\\n]*(?:[0-9A-Fa-f]{2})*[ \\t\\r\\n]*$', L));
110
102
  implied_by(rv_lexical(rvXsd + 'base64Binary', L), [regex_replace('[ \\t\\r\\n]', L, '', S), regex_match('^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/][AQgw]==|[A-Za-z0-9+/]{2}[AEIMQUYcgkosw048]=)?$', S)]);
111
103
  implied_by(rv_exact(T), [rv_valid(T), srl_num(T, K, _), rv_exact_kind(K)]);
package/src/shacl-expr.js CHANGED
@@ -55,10 +55,8 @@ const NAMED = ['var', 'pathValues', 'exists', 'if', 'distinct', 'intersection',
55
55
 
56
56
  // The expressions of one graph. The shapes compiler supplies its graph
57
57
  // access, its paths and the conformance predicates of its shapes.
58
- export function nodeExpressions({ G, lines, needs, index, rdfList, path, conforms, error }) {
58
+ export function nodeExpressions({ G, lines, needs, index, rdfList, path, conforms, error, fresh }) {
59
59
  const memo = new Map(), compiling = new Set();
60
- let next = 0;
61
- const fresh = (kind) => `sh_expr_${kind}_${next++}`;
62
60
  // Custom functions declared in the shapes graph by sh:bodyExpression.
63
61
  const custom = { list: new Map(), named: new Map() };
64
62
  for (const [key, properties] of index) {
@@ -230,7 +228,7 @@ export function nodeExpressions({ G, lines, needs, index, rdfList, path, conform
230
228
  const list = `[${args.map((_, i) => 'A' + i).join(', ')}]`;
231
229
  if (p === SHNEX + 'conformsToShape') {
232
230
  if (args.length !== 2) error(term, 'needs two arguments for shnex:conformsToShape');
233
- rule([...evaluated, `sh_ne_status(${list}, T)`, 'sh_ne_conforms(T, A0, A1, R)']);
231
+ rule([...evaluated, `sh_ne_status(${list}, T)`, `sh_ne_conforms(T, A0, A1, ${G}, R)`]);
234
232
  } else if (fn === null) {
235
233
  // A custom list parameter function: its body sees only its arguments.
236
234
  const body = compile(custom.list.get(write(new Struct('iri', [p]))));
@@ -367,8 +365,8 @@ implied_by(sh_ne_before(p(k(A), _), p(k(B), _)), [srl_rank_order(A, B, O), ident
367
365
  // List parameter arguments: v(Node), unbound, or error.
368
366
  fact(sh_ne_arg(failure, error), sh_ne_arg(nodes([]), unbound), sh_ne_arg(nodes([X]), v(X)), sh_ne_arg(nodes([_, _, ..._]), error));
369
367
  implied_by(sh_ne_status(As, T), once(or([ent_member(error, As), unify(T, 'error')], [ent_member(unbound, As), unify(T, 'unbound')], unify(T, 'ok'))));
370
- fact(sh_ne_conforms('error', _, _, failure), sh_ne_conforms('unbound', _, _, nodes([])));
371
- implied_by(sh_ne_conforms('ok', v(X), v(Shape), R), once(or([sh_shape(Shape), sh_conforms(Shape, X), unify(R, nodes([${TRUE}]))], [sh_shape(Shape), not(sh_conforms(Shape, X)), unify(R, nodes([${FALSE}]))], unify(R, failure))));
368
+ fact(sh_ne_conforms('error', _, _, _, failure), sh_ne_conforms('unbound', _, _, _, nodes([])));
369
+ implied_by(sh_ne_conforms('ok', v(X), v(Shape), G, R), once(or([sh_shape(Shape, G), sh_conforms(Shape, X, G), unify(R, nodes([${TRUE}]))], [sh_shape(Shape, G), not(sh_conforms(Shape, X, G)), unify(R, nodes([${FALSE}]))], unify(R, failure))));
372
370
  implied_by(sh_ne_bound([A], R), or([unify(A, v(_)), unify(R, nodes([${TRUE}]))], [unify(A, unbound), unify(R, nodes([${FALSE}]))], [unify(A, error), unify(R, failure)]));
373
371
  implied_by(sh_ne_coalesce(As, R), once(or([ent_member(v(X), As), unify(R, nodes([X]))], unify(R, failure))));
374
372
  implied_by(sh_ne_choose(v(C), A, B, R), once(or([srl_ebv(C, 'true'), sh_ne_value(A, R)], [srl_ebv(C, 'false'), sh_ne_value(B, R)], unify(R, failure))));
package/src/shacl.js CHANGED
@@ -53,6 +53,8 @@ export function compileShacl(quads, { disallows = SHACL_DISALLOWS, needs = new S
53
53
  graphs.get(key).triples.push([s, p, o]);
54
54
  }
55
55
  let nextShape = 0, nextPath = 0, nextConstraint = 0, nextHelper = 0;
56
+ let nextExpression = 0;
57
+ const freshExpression = (kind) => `sh_expr_${kind}_${nextExpression++}`;
56
58
  for (const { graph, triples } of graphs.values()) {
57
59
  const G = write(graph), index = new Map(), terms = new Map(), reifiers = new Map();
58
60
  for (const [s, p, o] of triples) {
@@ -178,7 +180,7 @@ export function compileShacl(quads, { disallows = SHACL_DISALLOWS, needs = new S
178
180
  }
179
181
  parsing.delete(key); paths.set(key, name); return name;
180
182
  };
181
- const expressions = nodeExpressions({ G, lines, needs, index, rdfList, path, error,
183
+ const expressions = nodeExpressions({ G, lines, needs, index, rdfList, path, error, fresh: freshExpression,
182
184
  conforms: (t) => `sh_ok_${shape(t).id}` });
183
185
  const expression = (t) => expressions.compile(t);
184
186
  // sh:closed sh:ByTypes permits, for each rdf:type T of a value node, the
@@ -217,7 +219,7 @@ export function compileShacl(quads, { disallows = SHACL_DISALLOWS, needs = new S
217
219
  const issue = `sh_issue_${id}`, focus = `sh_focus_${id}`, target = `sh_target_${id}`;
218
220
  if (inactive) {
219
221
  lines.push(`fact(${ok}(_));`);
220
- if (isIri(s)) lines.push(`fact(sh_shape(${S}));`, `implied_by(sh_conforms(${S}, X), ${ok}(X));`);
222
+ if (isIri(s)) lines.push(`fact(sh_shape(${S}, ${G}));`, `implied_by(sh_conforms(${S}, X, ${G}), ${ok}(X));`);
221
223
  continue;
222
224
  }
223
225
  const p = one(s, 'path'), P = p ? write(p) : NONE;
@@ -474,7 +476,7 @@ export function compileShacl(quads, { disallows = SHACL_DISALLOWS, needs = new S
474
476
  values(s, 'expression').forEach((t) => copy(t));
475
477
  each('expression', (t, c) => emit(c, [`${v}(F, V)`, `${expression(t)}(F, [['value', V]], R)`, `not(unify(R, nodes([${TRUE_TERM}])))`],
476
478
  'Expression', 'V', P, `source(${write(t)})`));
477
- each('nodeByExpression', (t, c) => emit(c, [`${v}(F, V)`, `${expression(t)}(V, [], nodes(L))`, 'ent_member(Shape, L)', 'sh_shape(Shape)', 'not(sh_conforms(Shape, V))'],
479
+ each('nodeByExpression', (t, c) => emit(c, [`${v}(F, V)`, `${expression(t)}(V, [], nodes(L))`, 'ent_member(Shape, L)', `sh_shape(Shape, ${G})`, `not(sh_conforms(Shape, V, ${G}))`],
478
480
  'NodeByExpression', 'V', P, 'source(Shape)'));
479
481
  scalar('closed', (t, c) => {
480
482
  const types = isIri(t) && t.args[0] === SH + 'ByTypes';
@@ -491,7 +493,7 @@ export function compileShacl(quads, { disallows = SHACL_DISALLOWS, needs = new S
491
493
  lines.push(`implied_by(${bad}(F), [${issue}(F, _, _, _, _, C), sh_blocking(C)${guard.map((g) => ', ' + g).join('')}]);`);
492
494
  lines.push(`implied_by(${ok}(F), not(${bad}(F)));`);
493
495
  lines.push(`implies([${focus}(F, X), ${issue}(F, P, V, C, K, I)${guard.map((g) => ', ' + g).join('')}], sh_violation(${S}, F, P, V, C, K, I, X, ${G}));`);
494
- if (isIri(s) && !dynamic(node)) lines.push(`fact(sh_shape(${S}));`, `implied_by(sh_conforms(${S}, X), ${ok}(X));`);
496
+ if (isIri(s) && !dynamic(node)) lines.push(`fact(sh_shape(${S}, ${G}));`, `implied_by(sh_conforms(${S}, X, ${G}), ${ok}(X));`);
495
497
  }
496
498
  if (evaluate && G === "'default_graph'") {
497
499
  const scope = [...evaluate.scope ?? []].map(([k, t]) => `[${JSON.stringify(k)}, ${write(t)}]`);