eyeleng 1.0.13 → 1.1.1

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/api.js CHANGED
@@ -6,7 +6,7 @@ const { parseRdfMessageLog, looksLikeRdfMessageLog } = require('./rdfMessages.js
6
6
  const { evaluate } = require('./engine.js');
7
7
  const { analyze } = require('./analyze.js');
8
8
  const { formatTriples, sortTriples, toJSON, formatTrace, formatBindings } = require('./format.js');
9
- const { runQuery, queryResult } = require('./query.js');
9
+ const { runQuery, queryResult, queryProgram, queryRunOptions, shouldUseHybridForQuery } = require('./query.js');
10
10
  const { resultTriples } = require('./output.js');
11
11
 
12
12
  function parseInput(source, options = {}) {
@@ -120,6 +120,9 @@ module.exports = {
120
120
  runToString,
121
121
  runQuery,
122
122
  queryResult,
123
+ queryProgram,
124
+ queryRunOptions,
125
+ shouldUseHybridForQuery,
123
126
  formatTriples,
124
127
  formatBindings,
125
128
  sortTriples,
@@ -0,0 +1,535 @@
1
+ 'use strict';
2
+
3
+ const { TripleStore, bindingKey } = require('./store.js');
4
+ const { tripleKey, termKey, termEquals } = require('./term.js');
5
+ const { evalExpression, booleanValue, asTerm } = require('./builtins.js');
6
+
7
+ function backwardQuery(program, querySpec, options = {}) {
8
+ const planner = planBackwardQuery(program, querySpec, options);
9
+ if (!planner.ok) return { ok: false, reason: planner.reason };
10
+ const prover = new BackwardProver(program, { ...options, allowedRuleIndexes: planner.ruleIndexes });
11
+ const bindings = uniqueBindings(Array.from(prover.solveBody(querySpec.body, {})));
12
+ return { ok: true, bindings, stats: prover.stats, plan: planner };
13
+ }
14
+
15
+ function planBackwardQuery(program, querySpec, options = {}) {
16
+ const clauses = querySpec && Array.isArray(querySpec.body) ? querySpec.body : [];
17
+ if (!bodySupported(clauses, options)) return { ok: false, reason: 'query body contains clauses not supported by the backward prover yet' };
18
+
19
+ const reachable = reachableBackwardRuleIndexes(program, clauses, options);
20
+ for (const ruleIndex of reachable.ruleIndexes) {
21
+ const rule = (program.rules || [])[ruleIndex];
22
+ if (!ruleSupported(rule, options)) return { ok: false, reason: `reachable rule ${rule.name || '<anonymous>'} is not supported by the backward prover yet` };
23
+ }
24
+ return { ok: true, ruleIndexes: reachable.ruleIndexes, predicates: reachable.predicates };
25
+ }
26
+
27
+ function bodySupported(clauses, options = {}) {
28
+ for (const clause of clauses || []) {
29
+ if (clause.type === 'triple' || clause.type === 'filter' || clause.type === 'set' || clause.type === 'bind') continue;
30
+ if (clause.type === 'not') {
31
+ if (options.backwardNegation === false) return false;
32
+ if (!bodySupported(clause.body, options)) return false;
33
+ continue;
34
+ }
35
+ return false;
36
+ }
37
+ return true;
38
+ }
39
+
40
+ function ruleSupported(rule, options = {}) {
41
+ if (!Array.isArray(rule.head) || rule.head.length === 0) return false;
42
+ for (const head of rule.head) {
43
+ if (!head || !head.p || head.p.type !== 'iri') return false;
44
+ if (containsBlank(head.s) || containsBlank(head.p) || containsBlank(head.o)) return false;
45
+ }
46
+ return bodySupported(rule.body || [], options);
47
+ }
48
+
49
+ class BackwardProver {
50
+ constructor(program, options = {}) {
51
+ this.program = program;
52
+ this.options = options;
53
+ this.store = options.store || new TripleStore(program.data || []);
54
+ this.maxDepth = options.backwardMaxDepth || options.maxDepth || 10000;
55
+ this.solutionLimit = options.backwardSolutionLimit || options.solutionLimit || 1000000;
56
+ this.allowedPredicates = normalizePredicateSet(options.allowedPredicates || options.backwardPredicates || null);
57
+ this.allowedRuleIndexes = normalizeRuleIndexSet(options.allowedRuleIndexes || null);
58
+ this.ruleHeads = indexRuleHeads(program.rules || [], { allowedPredicates: this.allowedPredicates, allowedRuleIndexes: this.allowedRuleIndexes });
59
+ this.memo = new Map();
60
+ this.active = new Set();
61
+ this.freshCounter = 0;
62
+ this.solutionCount = 0;
63
+ this.stats = {
64
+ mode: 'backward',
65
+ goals: 0,
66
+ facts: 0,
67
+ rules: 0,
68
+ memoHits: 0,
69
+ memoStores: 0,
70
+ maxDepth: 0,
71
+ };
72
+ }
73
+
74
+ *solveBody(clauses, binding = {}, depth = 0, index = 0) {
75
+ if (depth > this.maxDepth) throw new Error(`Reached backwardMaxDepth=${this.maxDepth}; backward query may not terminate`);
76
+ this.stats.maxDepth = Math.max(this.stats.maxDepth, depth);
77
+ if (this.solutionCount >= this.solutionLimit) return;
78
+ if (index >= clauses.length) {
79
+ this.solutionCount += 1;
80
+ yield resolveBinding(binding);
81
+ return;
82
+ }
83
+
84
+ const clause = clauses[index];
85
+ if (clause.type === 'triple') {
86
+ for (const matched of this.solveTriple(clause.triple, binding, depth + 1)) {
87
+ yield* this.solveBody(clauses, matched, depth + 1, index + 1);
88
+ }
89
+ return;
90
+ }
91
+
92
+ if (clause.type === 'filter') {
93
+ try {
94
+ if (booleanValue(evalExpression(clause.expr, resolveBinding(binding), this.options))) {
95
+ yield* this.solveBody(clauses, binding, depth + 1, index + 1);
96
+ }
97
+ } catch (_) {
98
+ // SPARQL-style FILTER errors reject the current solution.
99
+ }
100
+ return;
101
+ }
102
+
103
+ if (clause.type === 'set' || clause.type === 'bind') {
104
+ try {
105
+ const resolved = resolveBinding(binding);
106
+ const value = asTerm(evalExpression(clause.expr, resolved, this.options));
107
+ const next = unifyTerms({ type: 'var', value: clause.variable }, value, binding);
108
+ if (next) yield* this.solveBody(clauses, next, depth + 1, index + 1);
109
+ } catch (_) {
110
+ // Assignment errors drop the current solution.
111
+ }
112
+ return;
113
+ }
114
+
115
+ if (clause.type === 'not') {
116
+ let found = false;
117
+ for (const _ of this.solveBody(clause.body, { ...binding }, depth + 1, 0)) { found = true; break; }
118
+ if (!found) yield* this.solveBody(clauses, binding, depth + 1, index + 1);
119
+ return;
120
+ }
121
+
122
+ throw new Error(`Unsupported backward body clause ${clause.type}`);
123
+ }
124
+
125
+ *solveTriple(pattern, binding = {}, depth = 0) {
126
+ if (depth > this.maxDepth) throw new Error(`Reached backwardMaxDepth=${this.maxDepth}; backward query may not terminate`);
127
+ this.stats.goals += 1;
128
+ const resolvedPattern = resolvePattern(pattern, binding);
129
+ const key = `${goalKey(resolvedPattern)}@store:${this.store.version || 0}`;
130
+ const entry = this.memo.get(key);
131
+ if (entry && entry.complete) {
132
+ this.stats.memoHits += 1;
133
+ yield* this.replayAnswers(pattern, binding, entry.answers);
134
+ return;
135
+ }
136
+ if (this.active.has(key)) return;
137
+
138
+ const answers = [];
139
+ const answerKeys = new Set();
140
+ this.active.add(key);
141
+ try {
142
+ for (const fact of this.factCandidates(resolvedPattern, binding)) {
143
+ const next = unifyTriples(pattern, fact, binding);
144
+ if (!next) continue;
145
+ rememberAnswer(answers, answerKeys, pattern, next);
146
+ this.stats.facts += 1;
147
+ }
148
+
149
+ for (const item of this.ruleCandidates(resolvedPattern)) {
150
+ const suffix = `__b${++this.freshCounter}_${item.ruleIndex}`;
151
+ const freshHead = freshTriple(item.head, suffix);
152
+ const next = unifyTriples(pattern, freshHead, binding);
153
+ if (!next) continue;
154
+ const freshBody = (item.rule.body || []).map((clause) => freshClause(clause, suffix));
155
+ for (const solved of this.solveBody(freshBody, next, depth + 1, 0)) {
156
+ rememberAnswer(answers, answerKeys, pattern, solved);
157
+ this.stats.rules += 1;
158
+ }
159
+ }
160
+ } finally {
161
+ this.active.delete(key);
162
+ }
163
+
164
+ this.memo.set(key, { complete: true, answers });
165
+ this.stats.memoStores += 1;
166
+ yield* this.replayAnswers(pattern, binding, answers);
167
+ }
168
+
169
+ *replayAnswers(pattern, binding, answers) {
170
+ for (const answer of answers) {
171
+ const next = unifyTriples(pattern, answer, binding);
172
+ if (next) yield next;
173
+ }
174
+ }
175
+
176
+ factCandidates(pattern, binding) {
177
+ return this.store.candidates(pattern, binding);
178
+ }
179
+
180
+ ruleCandidates(pattern) {
181
+ const predicate = pattern.p && pattern.p.type === 'iri' ? pattern.p.value : null;
182
+ if (predicate) return this.ruleHeads.byPredicate.get(predicate) || [];
183
+ return this.ruleHeads.all;
184
+ }
185
+ }
186
+
187
+ function indexRuleHeads(rules, options = {}) {
188
+ const allowedPredicates = options.allowedPredicates || null;
189
+ const allowedRuleIndexes = options.allowedRuleIndexes || null;
190
+ const byPredicate = new Map();
191
+ const all = [];
192
+ for (let ruleIndex = 0; ruleIndex < rules.length; ruleIndex += 1) {
193
+ if (allowedRuleIndexes && !allowedRuleIndexes.has(ruleIndex)) continue;
194
+ const rule = rules[ruleIndex];
195
+ for (let headIndex = 0; headIndex < (rule.head || []).length; headIndex += 1) {
196
+ const head = rule.head[headIndex];
197
+ if (!head || !head.p || head.p.type !== 'iri') continue;
198
+ if (allowedPredicates && !allowedPredicates.has(head.p.value)) continue;
199
+ const item = { ruleIndex, headIndex, rule, head };
200
+ all.push(item);
201
+ const bucket = byPredicate.get(head.p.value);
202
+ if (bucket) bucket.push(item);
203
+ else byPredicate.set(head.p.value, [item]);
204
+ }
205
+ }
206
+ return { byPredicate, all };
207
+ }
208
+
209
+ function freshClause(clause, suffix) {
210
+ if (clause.type === 'triple') return { ...clause, triple: freshTriple(clause.triple, suffix) };
211
+ if (clause.type === 'filter') return { ...clause, expr: freshExpr(clause.expr, suffix) };
212
+ if (clause.type === 'set' || clause.type === 'bind') return { ...clause, variable: freshVarName(clause.variable, suffix), expr: freshExpr(clause.expr, suffix) };
213
+ if (clause.type === 'not') return { ...clause, body: clause.body.map((item) => freshClause(item, suffix)) };
214
+ return clause;
215
+ }
216
+
217
+ function freshTriple(triple, suffix) {
218
+ return { s: freshTerm(triple.s, suffix), p: freshTerm(triple.p, suffix), o: freshTerm(triple.o, suffix) };
219
+ }
220
+
221
+ function freshTerm(term, suffix) {
222
+ if (!term) return term;
223
+ if (term.type === 'var') return { type: 'var', value: freshVarName(term.value, suffix) };
224
+ if (term.type === 'triple') return { type: 'triple', s: freshTerm(term.s, suffix), p: freshTerm(term.p, suffix), o: freshTerm(term.o, suffix) };
225
+ return term;
226
+ }
227
+
228
+ function freshExpr(expr, suffix) {
229
+ if (!expr) return expr;
230
+ if (expr.type === 'var') return { ...expr, name: freshVarName(expr.name, suffix) };
231
+ if (expr.type === 'term') return { ...expr, value: freshTerm(expr.value, suffix) };
232
+ if (expr.type === 'unary') return { ...expr, expr: freshExpr(expr.expr, suffix) };
233
+ if (expr.type === 'binary') return { ...expr, left: freshExpr(expr.left, suffix), right: freshExpr(expr.right, suffix) };
234
+ if (expr.type === 'call') return { ...expr, args: expr.args.map((arg) => freshExpr(arg, suffix)) };
235
+ if (expr.type === 'list') return { ...expr, items: expr.items.map((item) => freshExpr(item, suffix)) };
236
+ return expr;
237
+ }
238
+
239
+ function freshVarName(name, suffix) {
240
+ return `${name}${suffix}`;
241
+ }
242
+
243
+ function resolvePattern(pattern, binding) {
244
+ return { s: resolveTerm(pattern.s, binding, false), p: resolveTerm(pattern.p, binding, false), o: resolveTerm(pattern.o, binding, false) };
245
+ }
246
+
247
+ function resolveBinding(binding) {
248
+ const out = {};
249
+ for (const name of Object.keys(binding)) out[name] = resolveTerm(binding[name], binding, false);
250
+ return out;
251
+ }
252
+
253
+ function resolveTerm(term, binding, preserveUnbound = true, seen = new Set()) {
254
+ if (!term) return term;
255
+ if (term.type === 'var') {
256
+ const name = term.value;
257
+ if (seen.has(name)) return preserveUnbound ? term : { type: 'var', value: name };
258
+ if (!Object.prototype.hasOwnProperty.call(binding, name)) return preserveUnbound ? term : { type: 'var', value: name };
259
+ seen.add(name);
260
+ return resolveTerm(binding[name], binding, preserveUnbound, seen);
261
+ }
262
+ if (term.type === 'triple') {
263
+ return {
264
+ type: 'triple',
265
+ s: resolveTerm(term.s, binding, preserveUnbound, new Set(seen)),
266
+ p: resolveTerm(term.p, binding, preserveUnbound, new Set(seen)),
267
+ o: resolveTerm(term.o, binding, preserveUnbound, new Set(seen)),
268
+ };
269
+ }
270
+ return term;
271
+ }
272
+
273
+ function unifyTriples(left, right, binding) {
274
+ let next = unifyTerms(left.s, right.s, binding);
275
+ if (!next) return null;
276
+ next = unifyTerms(left.p, right.p, next);
277
+ if (!next) return null;
278
+ return unifyTerms(left.o, right.o, next);
279
+ }
280
+
281
+ function unifyTerms(left, right, binding) {
282
+ const a = resolveTerm(left, binding);
283
+ const b = resolveTerm(right, binding);
284
+ if (a.type === 'var' && b.type === 'var' && a.value === b.value) return binding;
285
+ if (a.type === 'var') return bindVariable(a.value, b, binding);
286
+ if (b.type === 'var') return bindVariable(b.value, a, binding);
287
+ if (a.type === 'triple' || b.type === 'triple') {
288
+ if (a.type !== 'triple' || b.type !== 'triple') return null;
289
+ let next = unifyTerms(a.s, b.s, binding);
290
+ if (!next) return null;
291
+ next = unifyTerms(a.p, b.p, next);
292
+ if (!next) return null;
293
+ return unifyTerms(a.o, b.o, next);
294
+ }
295
+ return termEquals(a, b) ? binding : null;
296
+ }
297
+
298
+ function bindVariable(name, term, binding) {
299
+ const existing = binding[name];
300
+ if (existing) return unifyTerms(existing, term, binding);
301
+ if (term.type === 'var' && term.value === name) return binding;
302
+ return { ...binding, [name]: term };
303
+ }
304
+
305
+ function rememberAnswer(answers, answerKeys, pattern, binding) {
306
+ const triple = {
307
+ s: resolveTerm(pattern.s, binding),
308
+ p: resolveTerm(pattern.p, binding),
309
+ o: resolveTerm(pattern.o, binding),
310
+ };
311
+ if (triple.s.type === 'var' || triple.p.type === 'var' || triple.o.type === 'var') return;
312
+ const key = tripleKey(triple);
313
+ if (answerKeys.has(key)) return;
314
+ answerKeys.add(key);
315
+ answers.push(triple);
316
+ }
317
+
318
+ function goalKey(pattern) {
319
+ return `${safeTermKey(pattern.s)} ${safeTermKey(pattern.p)} ${safeTermKey(pattern.o)}`;
320
+ }
321
+
322
+ function safeTermKey(term) {
323
+ return term && term.type === 'var' ? '_' : termKey(term);
324
+ }
325
+
326
+ function uniqueBindings(bindings) {
327
+ const seen = new Set();
328
+ const out = [];
329
+ for (const binding of bindings) {
330
+ const resolved = resolveBinding(binding);
331
+ const key = bindingKey(resolved);
332
+ if (seen.has(key)) continue;
333
+ seen.add(key);
334
+ out.push(resolved);
335
+ }
336
+ return out;
337
+ }
338
+
339
+ function containsBlank(term) {
340
+ if (!term) return false;
341
+ if (term.type === 'blank') return true;
342
+ if (term.type === 'triple') return containsBlank(term.s) || containsBlank(term.p) || containsBlank(term.o);
343
+ return false;
344
+ }
345
+
346
+
347
+
348
+ function reachableBackwardRuleIndexes(program, rootClauses, options = {}) {
349
+ const rules = program.rules || [];
350
+ const headIndex = new Map();
351
+ const allHeadPredicates = new Set();
352
+ const allRuleIndexes = new Set();
353
+ for (let ruleIndex = 0; ruleIndex < rules.length; ruleIndex += 1) {
354
+ const rule = rules[ruleIndex];
355
+ for (const head of rule.head || []) {
356
+ if (!head || !head.p || head.p.type !== 'iri') continue;
357
+ allRuleIndexes.add(ruleIndex);
358
+ allHeadPredicates.add(head.p.value);
359
+ if (!headIndex.has(head.p.value)) headIndex.set(head.p.value, new Set());
360
+ headIndex.get(head.p.value).add(ruleIndex);
361
+ }
362
+ }
363
+
364
+ const predicates = new Set();
365
+ const ruleIndexes = new Set();
366
+ const work = [];
367
+ const enqueue = (predicate) => {
368
+ if (!predicate) {
369
+ for (const item of allHeadPredicates) enqueue(item);
370
+ return;
371
+ }
372
+ if (predicates.has(predicate)) return;
373
+ predicates.add(predicate);
374
+ work.push(predicate);
375
+ };
376
+
377
+ for (const predicate of bodyPredicateDemands(rootClauses || [])) enqueue(predicate);
378
+
379
+ while (work.length > 0) {
380
+ const predicate = work.shift();
381
+ const indexes = headIndex.get(predicate);
382
+ if (!indexes) continue;
383
+ for (const ruleIndex of indexes) {
384
+ if (ruleIndexes.has(ruleIndex)) continue;
385
+ ruleIndexes.add(ruleIndex);
386
+ const rule = rules[ruleIndex];
387
+ for (const needed of bodyPredicateDemands(rule.body || [])) enqueue(needed);
388
+ }
389
+ }
390
+
391
+ return { ruleIndexes, predicates };
392
+ }
393
+
394
+ function bodyPredicateDemands(clauses) {
395
+ const out = [];
396
+ for (const clause of clauses || []) {
397
+ if (clause.type === 'triple') {
398
+ out.push(predicateDemand(clause.triple.p));
399
+ continue;
400
+ }
401
+ if (clause.type === 'not') {
402
+ out.push(...bodyPredicateDemands(clause.body || []));
403
+ }
404
+ }
405
+ return out;
406
+ }
407
+
408
+ function predicateDemand(term) {
409
+ return term && term.type === 'iri' ? term.value : null;
410
+ }
411
+
412
+ function normalizePredicateSet(value) {
413
+ if (!value) return null;
414
+ if (value instanceof Set) return value;
415
+ if (Array.isArray(value)) return new Set(value);
416
+ return new Set(String(value).split(',').map((item) => item.trim()).filter(Boolean));
417
+ }
418
+
419
+ function normalizeRuleIndexSet(value) {
420
+ if (!value) return null;
421
+ if (value instanceof Set) return value;
422
+ if (Array.isArray(value)) return new Set(value);
423
+ return null;
424
+ }
425
+
426
+ function supportedBackwardPredicates(program, options = {}) {
427
+ const explicit = normalizePredicateSet(options.backwardPredicates || options.hybridPredicates || null);
428
+ const byPredicate = new Map();
429
+ for (const rule of program.rules || []) {
430
+ const predicates = new Set();
431
+ for (const head of rule.head || []) {
432
+ if (head && head.p && head.p.type === 'iri') predicates.add(head.p.value);
433
+ }
434
+ for (const predicate of predicates) {
435
+ if (!byPredicate.has(predicate)) byPredicate.set(predicate, []);
436
+ byPredicate.get(predicate).push(rule);
437
+ }
438
+ }
439
+
440
+ const supported = new Set();
441
+ for (const [predicate, rules] of byPredicate) {
442
+ if (explicit && !explicit.has(predicate)) continue;
443
+ if (rules.length > 0 && rules.every((rule) => ruleSupported(rule, options))) supported.add(predicate);
444
+ }
445
+ return supported;
446
+ }
447
+
448
+ function preferredBackwardPredicates(program, options = {}) {
449
+ const explicit = normalizePredicateSet(options.hybridPredicates || null);
450
+ if (explicit) return supportedBackwardPredicates(program, { ...options, hybridPredicates: explicit });
451
+ const supported = supportedBackwardPredicates(program, options);
452
+ const preferred = new Set();
453
+ const force = options.hybrid === true || options.hybridMode === 'force';
454
+ const demanded = force ? null : demandedBodyPredicates(program);
455
+ for (const rule of program.rules || []) {
456
+ if (!ruleIsFunctionLike(rule)) continue;
457
+ if (!force && ruleCreatesHeadTerms(rule)) continue;
458
+ for (const head of rule.head || []) {
459
+ if (!head || !head.p || head.p.type !== 'iri' || !supported.has(head.p.value)) continue;
460
+ if (force || demanded.has(head.p.value)) preferred.add(head.p.value);
461
+ }
462
+ }
463
+ return preferred;
464
+ }
465
+
466
+ function demandedBodyPredicates(program) {
467
+ const out = new Set();
468
+ for (const rule of program.rules || []) {
469
+ for (const predicate of bodyPredicateDemands(rule.body || [])) if (predicate) out.add(predicate);
470
+ }
471
+ return out;
472
+ }
473
+
474
+
475
+ function ruleCreatesHeadTerms(rule) {
476
+ const headVars = new Set();
477
+ for (const triple of rule.head || []) {
478
+ for (const term of [triple.s, triple.p, triple.o]) {
479
+ if (!term) continue;
480
+ if (term.type === 'blank') return true;
481
+ if (term.type === 'var') headVars.add(term.value);
482
+ }
483
+ }
484
+ if (headVars.size === 0) return false;
485
+ for (const clause of rule.body || []) {
486
+ if ((clause.type === 'set' || clause.type === 'bind') && headVars.has(clause.variable) && expressionCreatesTerm(clause.expr)) return true;
487
+ }
488
+ return false;
489
+ }
490
+
491
+ function expressionCreatesTerm(expr) {
492
+ if (!expr) return false;
493
+ if (expr.type === 'call') {
494
+ const name = String(expr.name || '').toUpperCase();
495
+ if (name === 'BNODE' || name === 'IRI' || name === 'URI' || name === 'TRIPLE' || name === 'UUID' || name === 'STRUUID') return true;
496
+ return (expr.args || []).some(expressionCreatesTerm);
497
+ }
498
+ if (expr.type === 'binary') return expressionCreatesTerm(expr.left) || expressionCreatesTerm(expr.right);
499
+ if (expr.type === 'unary') return expressionCreatesTerm(expr.expr);
500
+ if (expr.type === 'in') return expressionCreatesTerm(expr.left) || (expr.values || []).some(expressionCreatesTerm);
501
+ return false;
502
+ }
503
+
504
+ function ruleIsFunctionLike(rule) {
505
+ return (rule.body || []).some((clause) => clause.type === 'set' || clause.type === 'bind');
506
+ }
507
+
508
+ function ruleHeadPredicates(rule) {
509
+ const predicates = new Set();
510
+ for (const head of rule.head || []) {
511
+ if (!head || !head.p || head.p.type !== 'iri') return null;
512
+ predicates.add(head.p.value);
513
+ }
514
+ return predicates;
515
+ }
516
+
517
+ function ruleIsBackwardOriented(rule, predicates) {
518
+ if (!predicates || predicates.size === 0) return false;
519
+ const heads = ruleHeadPredicates(rule);
520
+ if (!heads || heads.size === 0) return false;
521
+ for (const predicate of heads) if (!predicates.has(predicate)) return false;
522
+ return true;
523
+ }
524
+
525
+ module.exports = {
526
+ BackwardProver,
527
+ backwardQuery,
528
+ planBackwardQuery,
529
+ supportedBackwardPredicates,
530
+ preferredBackwardPredicates,
531
+ reachableBackwardRuleIndexes,
532
+ ruleIsBackwardOriented,
533
+ ruleSupported,
534
+ resolveBinding,
535
+ };
package/src/cli.js CHANGED
@@ -8,6 +8,8 @@ const {
8
8
  evaluate,
9
9
  parseQuery,
10
10
  queryResult,
11
+ queryProgram,
12
+ queryRunOptions,
11
13
  formatTriples,
12
14
  formatTrace,
13
15
  formatBindings,
@@ -34,7 +36,7 @@ function readPackageVersion() {
34
36
  const VERSION = readPackageVersion();
35
37
 
36
38
  function help() {
37
- return `eyeleng ${VERSION}\n\nA dependency-free JavaScript implementation experiment for the SHACL 1.2 Rules draft, including SRL and RDF Rules syntax front-ends.\n\nUsage:\n eyeleng [options] [file ...]\n\nOptions:\n --all Print the full closure, including input facts\n --json Print JSON instead of compact triples/bindings\n --trace Print derivation trace to stderr, or include it in JSON\n --stats Print iteration and triple counts to stderr\n --check Parse and analyze only; do not run rules\n --strict Treat static warnings as errors, including recursive term generation\n --deps Print rule dependency edges during --check\n --query TEXT Run a raw SRL body pattern over the closure\n --query-file FILE Read a raw SRL body pattern from a file\n --max-iterations N Stop after N fixpoint iterations within a recursive layer\n --no-imports Parse IMPORTS/owl:imports but do not load imported rule sets\n --rdf-messages Parse input as an RDF Message Log\n --stream-messages Replay RDF Message Log envelopes\n --include-message-facts Include payload facts while parsing RDF Message Logs\n --syntax MODE Use srl, rdf, or auto syntax detection (default auto)\n --ruleset TERM In RDF syntax, run only the selected srl:RuleSet\n --version Print version\n -h, --help Print this help\n\nWith no file arguments, eyeleng reads from stdin.\n`;
39
+ return `eyeleng ${VERSION}\n\nA dependency-free JavaScript implementation experiment for the SHACL 1.2 Rules draft, including SRL and RDF Rules syntax front-ends.\n\nUsage:\n eyeleng [options] [file ...]\n\nOptions:\n --all Print the full closure, including input facts\n --json Print JSON instead of compact triples/bindings\n --trace Print derivation trace to stderr, or include it in JSON\n --stats Print iteration and triple counts to stderr\n --check Parse and analyze only; do not run rules\n --strict Treat static warnings as errors, including recursive term generation\n --deps Print rule dependency edges during --check\n --query TEXT Run a raw SRL body pattern over the closure or backward planner\n --query-file FILE Read a raw SRL body pattern from a file\n --query-mode MODE Use auto, forward, or backward query planning (default auto)\n --hybrid Force aggressive hybrid orientation for function-like rules\n --no-hybrid Disable automatic hybrid forward/backward execution\n --max-iterations N Stop after N fixpoint iterations within a recursive layer\n --no-imports Parse IMPORTS/owl:imports but do not load imported rule sets\n --rdf-messages Parse input as an RDF Message Log\n --include-message-facts Include payload facts while parsing RDF Message Logs\n --syntax MODE Use srl, rdf, or auto syntax detection (default auto)\n --ruleset TERM In RDF syntax, run only the selected srl:RuleSet\n --version Print version\n -h, --help Print this help\n\nWith no file arguments, eyeleng reads from stdin.\n`;
38
40
  }
39
41
 
40
42
  function parseArgs(argv) {
@@ -48,6 +50,8 @@ function parseArgs(argv) {
48
50
  deps: false,
49
51
  query: null,
50
52
  queryFile: null,
53
+ queryMode: 'auto',
54
+ hybrid: 'auto',
51
55
  maxIterations: 10000,
52
56
  imports: true,
53
57
  syntax: 'auto',
@@ -66,7 +70,9 @@ function parseArgs(argv) {
66
70
  else if (arg === '--strict') options.strict = true;
67
71
  else if (arg === '--deps') options.deps = true;
68
72
  else if (arg === '--no-imports') options.imports = false;
69
- else if (arg === '--rdf-messages' || arg === '--stream-messages') options.rdfMessages = true;
73
+ else if (arg === '--hybrid') options.hybrid = true;
74
+ else if (arg === '--no-hybrid') options.hybrid = false;
75
+ else if (arg === '--rdf-messages') options.rdfMessages = true;
70
76
  else if (arg === '--include-message-facts') options.includeMessageFacts = true;
71
77
  else if (arg === '--syntax') {
72
78
  i += 1;
@@ -77,8 +83,12 @@ function parseArgs(argv) {
77
83
  i += 1;
78
84
  if (i >= argv.length) throw new Error('--ruleset requires an RDF term');
79
85
  options.ruleSet = argv[i];
80
- }
81
- else if (arg === '--query') {
86
+ } else if (arg === '--query-mode') {
87
+ i += 1;
88
+ if (i >= argv.length) throw new Error('--query-mode requires auto, forward, or backward');
89
+ options.queryMode = argv[i];
90
+ if (!['auto', 'forward', 'backward'].includes(options.queryMode)) throw new Error('--query-mode requires auto, forward, or backward');
91
+ } else if (arg === '--query') {
82
92
  i += 1;
83
93
  if (i >= argv.length) throw new Error('--query requires a value');
84
94
  options.query = argv[i];
@@ -191,15 +201,42 @@ function main(argv = process.argv.slice(2), io = process) {
191
201
  }
192
202
  if (fatal) return 1;
193
203
 
194
- const result = evaluate(compiled.program, { ...options, analysis: compiled.analysis });
195
- result.diagnostics = compiled.diagnostics;
196
- result.analysis = compiled.analysis;
197
-
198
204
  const queryText = options.queryFile ? fs.readFileSync(options.queryFile, 'utf8') : options.query;
199
205
  const querySpec = queryText
200
206
  ? parseQuery(queryText, { filename: options.queryFile || '<query>', prefixes: compiled.program.prefixes, baseIRI: compiled.program.baseIRI })
201
207
  : null;
202
- if (querySpec) result.query = queryResult(result, querySpec, options);
208
+
209
+ let result;
210
+ if (querySpec) {
211
+ const directQuery = queryProgram(compiled.program, querySpec, options);
212
+ if (directQuery) {
213
+ result = {
214
+ baseIRI: compiled.program.baseIRI,
215
+ prefixes: compiled.program.prefixes,
216
+ input: compiled.program.data.slice(),
217
+ inferred: [],
218
+ closure: compiled.program.data.slice(),
219
+ iterations: 0,
220
+ layers: [],
221
+ ruleApplications: 0,
222
+ perRule: [],
223
+ trace: [],
224
+ diagnostics: compiled.diagnostics,
225
+ analysis: compiled.analysis,
226
+ query: directQuery,
227
+ };
228
+ }
229
+ }
230
+
231
+ if (!result) {
232
+ const runOptions = querySpec
233
+ ? queryRunOptions(compiled.program, querySpec, options)
234
+ : { ...options, hybrid: options.hybrid };
235
+ result = evaluate(compiled.program, { ...runOptions, analysis: compiled.analysis });
236
+ result.diagnostics = compiled.diagnostics;
237
+ result.analysis = compiled.analysis;
238
+ if (querySpec) result.query = queryResult(result, querySpec, runOptions);
239
+ }
203
240
 
204
241
  if (options.json) {
205
242
  io.stdout.write(`${JSON.stringify(toJSON(result, { all: options.all, trace: options.trace, analysis: options.deps }), null, 2)}\n`);
@@ -214,7 +251,9 @@ function main(argv = process.argv.slice(2), io = process) {
214
251
  }
215
252
 
216
253
  if (options.stats) {
217
- io.stderr.write(`eyeleng: iterations=${result.iterations} layers=${result.layers.length} input=${result.input.length} inferred=${result.inferred.length} closure=${result.closure.length} ruleApplications=${result.ruleApplications}\n`);
254
+ io.stderr.write(`eyeleng: iterations=${result.iterations} layers=${result.layers.length} input=${result.input.length} inferred=${result.inferred.length} closure=${result.closure.length} ruleApplications=${result.ruleApplications}${result.query && result.query.mode ? ` queryMode=${result.query.mode}` : ''}\n`);
255
+ if (result.query && result.query.stats) io.stderr.write(`eyeleng: backward goals=${result.query.stats.goals} facts=${result.query.stats.facts} rules=${result.query.stats.rules} memoHits=${result.query.stats.memoHits} memoStores=${result.query.stats.memoStores}\n`);
256
+ if (result.hybridStats) io.stderr.write(`eyeleng: hybridBackward goals=${result.hybridStats.goals} facts=${result.hybridStats.facts} rules=${result.hybridStats.rules} memoHits=${result.hybridStats.memoHits} memoStores=${result.hybridStats.memoStores}\n`);
218
257
  for (const rule of result.perRule) {
219
258
  if (rule.applications > 0 || rule.added > 0) io.stderr.write(`eyeleng: rule ${rule.name}: applications=${rule.applications} added=${rule.added}${rule.runOnce ? ' runOnce=true' : ''}\n`);
220
259
  }