eyemind 0.5.1 → 0.5.2
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/README.md +37 -15
- package/SPEC.md +11 -1
- package/package.json +1 -1
- package/src/cli.js +37 -5
- package/src/formats.js +149 -0
- package/src/n3-builtins.js +590 -0
- package/src/n3-documents.js +66 -0
- package/src/n3-parser.js +463 -0
- package/src/n3-writer.js +199 -0
- package/src/n3.js +814 -0
- package/src/node.js +4 -0
- package/src/rdf-lexer.js +2025 -0
- package/src/rdf-parser.js +827 -0
- package/src/rdf-prelude.js +808 -0
- package/src/rdf-rules.js +106 -0
- package/src/rdf-syntax.js +249 -0
- package/src/rdf.js +429 -0
- package/src/srl-analyze.js +703 -0
- package/src/srl-assignments.js +40 -0
- package/src/srl-builtin-names.js +78 -0
- package/src/srl-functions.js +584 -0
- package/src/srl-parser.js +816 -0
- package/src/srl-term.js +288 -0
- package/src/srl-tokenizer.js +341 -0
- package/src/srl.js +649 -0
- package/src/version.js +1 -1
|
@@ -0,0 +1,703 @@
|
|
|
1
|
+
|
|
2
|
+
import { compactIRI, iri, variable, termEquals } from './srl-term.js';
|
|
3
|
+
import { tripleHasBlankNode, tripleHasVariableTripleTerm } from './srl-assignments.js';
|
|
4
|
+
|
|
5
|
+
function analyze(program, options = {}) {
|
|
6
|
+
const diagnostics = [];
|
|
7
|
+
const dependency = dependencyGraph(program, options);
|
|
8
|
+
|
|
9
|
+
program.rules.forEach((rule, index) => {
|
|
10
|
+
const name = ruleName(rule, index);
|
|
11
|
+
const initialBound = new Set();
|
|
12
|
+
|
|
13
|
+
const bound = boundVariables(rule.body, initialBound);
|
|
14
|
+
const head = new Set();
|
|
15
|
+
for (const triple of rule.head) collectTripleVars(triple, head);
|
|
16
|
+
for (const variableName of head) {
|
|
17
|
+
if (!bound.has(variableName)) diagnostics.push({
|
|
18
|
+
code: 'unsafe-head-variable', severity: 'error', rule: name,
|
|
19
|
+
message: `${displayRuleName(name, program.prefixes || {})} has unbound head variable ?${variableName}`,
|
|
20
|
+
});
|
|
21
|
+
}
|
|
22
|
+
for (const triple of rule.head) {
|
|
23
|
+
if (triple.p.type !== 'iri' && triple.p.type !== 'var') diagnostics.push({
|
|
24
|
+
code: 'invalid-head-predicate', severity: 'error', rule: name,
|
|
25
|
+
message: `${displayRuleName(name, program.prefixes || {})} has a non-IRI/non-variable predicate in the head`,
|
|
26
|
+
});
|
|
27
|
+
}
|
|
28
|
+
diagnostics.push(...sequentialWellFormednessDiagnostics(rule.body, name, program.prefixes || {}, initialBound));
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
if (options.checkStratification !== false) {
|
|
32
|
+
for (const cycle of dependency.unstratifiedCycles) diagnostics.push({
|
|
33
|
+
code: 'unstratified-closed-dependency', severity: 'error', rules: cycle.rules,
|
|
34
|
+
message: `Stratification condition violated by a recursive closed dependency through ${cycle.rules.map((name) => displayRuleName(name, program.prefixes || {})).join(' -> ')}`,
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
return {
|
|
39
|
+
warnings: diagnostics.filter((d) => d.severity === 'warning'),
|
|
40
|
+
errors: diagnostics.filter((d) => d.severity === 'error'),
|
|
41
|
+
diagnostics,
|
|
42
|
+
dependency,
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function ruleName(rule, index) { return rule.name || `rule#${index + 1}`; }
|
|
47
|
+
function displayRuleName(name, prefixes = {}) { return /^https?:/.test(name) ? compactIRI(name, prefixes) : name; }
|
|
48
|
+
|
|
49
|
+
function dependencyGraph(program, options = {}) {
|
|
50
|
+
const rules = program.rules.map((rule, index) => {
|
|
51
|
+
// WHERE DATA and NOT DATA read the immutable base graph. Rule heads can
|
|
52
|
+
// never add triples to that graph, so those patterns do not create rule
|
|
53
|
+
// dependencies (§4.3 dependency is about possible head/body matching in
|
|
54
|
+
// the inference graph).
|
|
55
|
+
const positivePatterns = rule.groundData ? [] : bodyTriplePatterns(rule.body, false);
|
|
56
|
+
const negativePatterns = rule.groundData ? [] : bodyTriplePatterns(rule.body, true);
|
|
57
|
+
const headTemplates = effectiveHeadTemplates(rule);
|
|
58
|
+
return {
|
|
59
|
+
index, name: ruleName(rule, index), headTemplates, positivePatterns, negativePatterns,
|
|
60
|
+
headPredicates: new Set(headTemplates.map((triple) => predicateIRI(triple)).filter(Boolean)),
|
|
61
|
+
positivePredicates: new Set(positivePatterns.flatMap((triple) => predicateIRIs(triple))),
|
|
62
|
+
negativePredicates: new Set(negativePatterns.flatMap((triple) => predicateIRIs(triple))),
|
|
63
|
+
runOnce: !!rule.runOnce,
|
|
64
|
+
hasAssignment: ruleHasAssignment(rule, options),
|
|
65
|
+
hasGroup: (rule.body || []).some((clause) => clause.type === 'group'),
|
|
66
|
+
hasTermGeneratingAssignment: ruleHasTermGeneratingAssignment(rule, options),
|
|
67
|
+
headHasBlankNode: ruleHeadHasBlankNode(rule),
|
|
68
|
+
headHasVariableTripleTerm: (rule.head || []).some(tripleHasVariableTripleTerm),
|
|
69
|
+
createsTerms: ruleCreatesTerms(rule, options),
|
|
70
|
+
};
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
const edgeMap = new Map();
|
|
74
|
+
function addEdge(from, to, kind, predicate) {
|
|
75
|
+
const key = `${from.index}->${to.index}`;
|
|
76
|
+
const negated = kind === 'negated';
|
|
77
|
+
// Per §4.3, every dependency from a run-once rule is closed, even when
|
|
78
|
+
// the matching pattern itself is positive.
|
|
79
|
+
const runOnceConstraint = from.runOnce;
|
|
80
|
+
const closed = negated || runOnceConstraint;
|
|
81
|
+
const existing = edgeMap.get(key);
|
|
82
|
+
if (existing) {
|
|
83
|
+
existing.closed = existing.closed || closed;
|
|
84
|
+
existing.negative = existing.closed;
|
|
85
|
+
existing.negated = existing.negated || negated;
|
|
86
|
+
existing.runOnceConstraint = existing.runOnceConstraint || runOnceConstraint;
|
|
87
|
+
if (predicate && !existing.predicates.includes(predicate)) existing.predicates.push(predicate);
|
|
88
|
+
if (!existing.predicate && predicate) existing.predicate = predicate;
|
|
89
|
+
return;
|
|
90
|
+
}
|
|
91
|
+
edgeMap.set(key, {
|
|
92
|
+
from: from.index, to: to.index, label: closed ? 'closed' : 'open', closed, negative: closed,
|
|
93
|
+
negated, runOnceConstraint, predicate: predicate || null, predicates: predicate ? [predicate] : [],
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
const headIndex = buildHeadTemplateIndex(rules);
|
|
98
|
+
for (const from of rules) {
|
|
99
|
+
for (const pattern of from.positivePatterns) {
|
|
100
|
+
for (const candidate of candidateHeadTemplates(headIndex, pattern)) {
|
|
101
|
+
if (canPossiblyGenerate(candidate.template, pattern)) addEdge(from, rules[candidate.ruleIndex], 'positive', dependencyPredicateLabel(pattern));
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
for (const pattern of from.negativePatterns) {
|
|
105
|
+
for (const candidate of candidateHeadTemplates(headIndex, pattern)) {
|
|
106
|
+
if (canPossiblyGenerate(candidate.template, pattern)) addEdge(from, rules[candidate.ruleIndex], 'negated', dependencyPredicateLabel(pattern));
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
const edges = Array.from(edgeMap.values()).sort((a,b) => a.from-b.from || a.to-b.to);
|
|
112
|
+
for (const edge of edges) edge.label = edge.closed ? 'closed' : 'open';
|
|
113
|
+
const components = stronglyConnectedComponents(rules.length, edges);
|
|
114
|
+
const componentOf = new Map();
|
|
115
|
+
components.forEach((component, i) => component.forEach((ruleIndex) => componentOf.set(ruleIndex, i)));
|
|
116
|
+
|
|
117
|
+
const unstratifiedCycles = [];
|
|
118
|
+
const seen = new Set();
|
|
119
|
+
for (const edge of edges) {
|
|
120
|
+
if (!edge.closed || componentOf.get(edge.from) !== componentOf.get(edge.to)) continue;
|
|
121
|
+
const component = components[componentOf.get(edge.from)];
|
|
122
|
+
const isCycle = component.length > 1 || edge.from === edge.to;
|
|
123
|
+
if (!isCycle) continue;
|
|
124
|
+
const key = component.join(',');
|
|
125
|
+
if (seen.has(key)) continue;
|
|
126
|
+
seen.add(key);
|
|
127
|
+
unstratifiedCycles.push({ rules: component.map((i) => rules[i].name) });
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
const layers = unstratifiedCycles.length ? [rules.map((r) => r.index)] : stratificationLayers(rules.length, components, componentOf, edges);
|
|
131
|
+
return {
|
|
132
|
+
rules: rules.map((rule) => ({
|
|
133
|
+
index: rule.index, name: rule.name,
|
|
134
|
+
headPredicates: Array.from(rule.headPredicates), positivePredicates: Array.from(rule.positivePredicates), negativePredicates: Array.from(rule.negativePredicates),
|
|
135
|
+
runOnce: rule.runOnce, hasAssignment: rule.hasAssignment, hasGroup: rule.hasGroup, hasTermGeneratingAssignment: rule.hasTermGeneratingAssignment,
|
|
136
|
+
headHasBlankNode: rule.headHasBlankNode, headHasVariableTripleTerm: rule.headHasVariableTripleTerm, createsTerms: rule.createsTerms,
|
|
137
|
+
})),
|
|
138
|
+
edges,
|
|
139
|
+
components: components.map((component) => component.map((i) => rules[i].name)),
|
|
140
|
+
layers: layers.map((layer) => layer.map((i) => rules[i].name)),
|
|
141
|
+
layerIndexes: layers,
|
|
142
|
+
unstratifiedCycles,
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
function buildHeadTemplateIndex(rules) {
|
|
147
|
+
const templates = [];
|
|
148
|
+
const positions = ['s', 'p', 'o'];
|
|
149
|
+
const byPosition = {
|
|
150
|
+
s: new Map(),
|
|
151
|
+
p: new Map(),
|
|
152
|
+
o: new Map(),
|
|
153
|
+
};
|
|
154
|
+
const flexibleByPosition = {
|
|
155
|
+
s: new Set(),
|
|
156
|
+
p: new Set(),
|
|
157
|
+
o: new Set(),
|
|
158
|
+
};
|
|
159
|
+
|
|
160
|
+
for (const rule of rules) {
|
|
161
|
+
for (const template of rule.headTemplates) {
|
|
162
|
+
const entry = { id: templates.length, ruleIndex: rule.index, template };
|
|
163
|
+
templates.push(entry);
|
|
164
|
+
for (const position of positions) {
|
|
165
|
+
const key = fixedTermIndexKey(template[position]);
|
|
166
|
+
if (key === null) flexibleByPosition[position].add(entry.id);
|
|
167
|
+
else {
|
|
168
|
+
let bucket = byPosition[position].get(key);
|
|
169
|
+
if (!bucket) {
|
|
170
|
+
bucket = new Set();
|
|
171
|
+
byPosition[position].set(key, bucket);
|
|
172
|
+
}
|
|
173
|
+
bucket.add(entry.id);
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
return { templates, byPosition, flexibleByPosition };
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
function candidateHeadTemplates(index, pattern) {
|
|
183
|
+
const positions = ['s', 'p', 'o'];
|
|
184
|
+
let selected = null;
|
|
185
|
+
|
|
186
|
+
for (const position of positions) {
|
|
187
|
+
const key = fixedTermIndexKey(pattern[position]);
|
|
188
|
+
if (key === null) continue;
|
|
189
|
+
const exact = index.byPosition[position].get(key) || null;
|
|
190
|
+
const flexible = index.flexibleByPosition[position];
|
|
191
|
+
const estimatedSize = (exact ? exact.size : 0) + flexible.size;
|
|
192
|
+
if (selected === null || estimatedSize < selected.estimatedSize) selected = { exact, flexible, estimatedSize };
|
|
193
|
+
if (estimatedSize === 0) break;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
if (selected === null) return index.templates;
|
|
197
|
+
const ids = [];
|
|
198
|
+
if (selected.exact) for (const id of selected.exact) ids.push(id);
|
|
199
|
+
for (const id of selected.flexible) ids.push(id);
|
|
200
|
+
const out = [];
|
|
201
|
+
const seen = new Set();
|
|
202
|
+
for (const id of ids) {
|
|
203
|
+
if (seen.has(id)) continue;
|
|
204
|
+
seen.add(id);
|
|
205
|
+
out.push(index.templates[id]);
|
|
206
|
+
}
|
|
207
|
+
return out;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
function fixedTermIndexKey(term) {
|
|
211
|
+
if (!term) return null;
|
|
212
|
+
if (term.type === 'var') return null;
|
|
213
|
+
if (term.type === 'path') return null;
|
|
214
|
+
if (term.type === 'triple' && containsVariableTerm(term)) return null;
|
|
215
|
+
return termIndexKey(term);
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
function containsVariableTerm(term) {
|
|
219
|
+
if (!term) return false;
|
|
220
|
+
if (term.type === 'var') return true;
|
|
221
|
+
if (term.type === 'triple') return containsVariableTerm(term.s) || containsVariableTerm(term.p) || containsVariableTerm(term.o);
|
|
222
|
+
if (term.type === 'path') {
|
|
223
|
+
if (term.kind === 'inverse') return containsVariableTerm(term.path);
|
|
224
|
+
if (term.kind === 'sequence') return term.parts.some(containsVariableTerm);
|
|
225
|
+
}
|
|
226
|
+
return false;
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
function literalIndexValue(value) {
|
|
230
|
+
if (typeof value === 'bigint') return `${value.toString()}n`;
|
|
231
|
+
return JSON.stringify(value);
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
function termIndexKey(term) {
|
|
235
|
+
if (!term) return 'null';
|
|
236
|
+
if (term.type === 'iri') return `I:${term.value}`;
|
|
237
|
+
if (term.type === 'blank') return `B:${term.value}`;
|
|
238
|
+
if (term.type === 'literal') return `L:${literalIndexValue(term.value)}^^${term.datatype || ''}@${term.lang || ''}--${term.langDir || ''}`;
|
|
239
|
+
if (term.type === 'triple') return `T:${termIndexKey(term.s)} ${termIndexKey(term.p)} ${termIndexKey(term.o)}`;
|
|
240
|
+
return JSON.stringify(term);
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
function unionSets(a, b) {
|
|
244
|
+
const out = new Set();
|
|
245
|
+
if (a) for (const value of a) out.add(value);
|
|
246
|
+
if (b) for (const value of b) out.add(value);
|
|
247
|
+
return out;
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
function allTemplateIds(length) {
|
|
251
|
+
const out = new Set();
|
|
252
|
+
for (let i = 0; i < length; i += 1) out.add(i);
|
|
253
|
+
return out;
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
function stratificationLayers(ruleCount, components, componentOf, edges) {
|
|
257
|
+
if (ruleCount === 0) return [];
|
|
258
|
+
const levels = Array(ruleCount).fill(0);
|
|
259
|
+
const limit = ruleCount + 1;
|
|
260
|
+
let changed = true;
|
|
261
|
+
while (changed) {
|
|
262
|
+
changed = false;
|
|
263
|
+
for (const edge of edges) {
|
|
264
|
+
const required = levels[edge.to] + (edge.closed ? 1 : 0);
|
|
265
|
+
if (levels[edge.from] < required) {
|
|
266
|
+
levels[edge.from] = required;
|
|
267
|
+
if (levels[edge.from] > limit) throw new Error('Stratification error');
|
|
268
|
+
changed = true;
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
const max = Math.max(0, ...levels);
|
|
273
|
+
const layers = Array.from({ length: max + 1 }, () => []);
|
|
274
|
+
levels.forEach((level, index) => layers[level].push(index));
|
|
275
|
+
return layers;
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
function stronglyConnectedComponents(size, edges) {
|
|
279
|
+
const adjacency = Array.from({ length: size }, () => []);
|
|
280
|
+
const reverse = Array.from({ length: size }, () => []);
|
|
281
|
+
for (const edge of edges) {
|
|
282
|
+
adjacency[edge.from].push(edge.to);
|
|
283
|
+
reverse[edge.to].push(edge.from);
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
const visited = Array(size).fill(false);
|
|
287
|
+
const order = [];
|
|
288
|
+
for (let start = 0; start < size; start += 1) {
|
|
289
|
+
if (visited[start]) continue;
|
|
290
|
+
const stack = [[start, 0]];
|
|
291
|
+
visited[start] = true;
|
|
292
|
+
while (stack.length > 0) {
|
|
293
|
+
const frame = stack[stack.length - 1];
|
|
294
|
+
const v = frame[0];
|
|
295
|
+
let nextIndex = frame[1];
|
|
296
|
+
if (nextIndex < adjacency[v].length) {
|
|
297
|
+
const w = adjacency[v][nextIndex];
|
|
298
|
+
frame[1] = nextIndex + 1;
|
|
299
|
+
if (!visited[w]) {
|
|
300
|
+
visited[w] = true;
|
|
301
|
+
stack.push([w, 0]);
|
|
302
|
+
}
|
|
303
|
+
} else {
|
|
304
|
+
order.push(v);
|
|
305
|
+
stack.pop();
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
const assigned = Array(size).fill(false);
|
|
311
|
+
const components = [];
|
|
312
|
+
for (let i = order.length - 1; i >= 0; i -= 1) {
|
|
313
|
+
const start = order[i];
|
|
314
|
+
if (assigned[start]) continue;
|
|
315
|
+
const component = [];
|
|
316
|
+
const stack = [start];
|
|
317
|
+
assigned[start] = true;
|
|
318
|
+
while (stack.length > 0) {
|
|
319
|
+
const v = stack.pop();
|
|
320
|
+
component.push(v);
|
|
321
|
+
for (const w of reverse[v]) {
|
|
322
|
+
if (!assigned[w]) {
|
|
323
|
+
assigned[w] = true;
|
|
324
|
+
stack.push(w);
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
components.push(component.sort((a, b) => a - b));
|
|
329
|
+
}
|
|
330
|
+
return components;
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
function sequentialWellFormednessDiagnostics(clauses, ruleNameValue, prefixes = {}, initialBound = new Set()) {
|
|
334
|
+
const diagnostics = [];
|
|
335
|
+
|
|
336
|
+
function visit(items, initialBound, scopeLabel) {
|
|
337
|
+
const bound = new Set(initialBound);
|
|
338
|
+
for (const clause of items) {
|
|
339
|
+
if (clause.type === 'triple' || clause.type === 'path') {
|
|
340
|
+
collectTripleVars(clause.triple, bound);
|
|
341
|
+
} else if (clause.type === 'filter') {
|
|
342
|
+
for (const variable of expressionVariables(clause.expr)) {
|
|
343
|
+
if (!bound.has(variable)) {
|
|
344
|
+
diagnostics.push({
|
|
345
|
+
code: 'unbound-filter-variable',
|
|
346
|
+
severity: 'error',
|
|
347
|
+
rule: ruleNameValue,
|
|
348
|
+
message: `${displayRuleName(ruleNameValue, prefixes)} FILTER uses ?${variable} before it is bound${scopeLabel}`,
|
|
349
|
+
});
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
} else if ((clause.type === 'set' || clause.type === 'bind')) {
|
|
353
|
+
if (bound.has(clause.variable)) {
|
|
354
|
+
diagnostics.push({
|
|
355
|
+
code: 'assignment-variable-already-bound',
|
|
356
|
+
severity: 'error',
|
|
357
|
+
rule: ruleNameValue,
|
|
358
|
+
message: `${displayRuleName(ruleNameValue, prefixes)} SET assigns ?${clause.variable}, but that variable is already bound${scopeLabel}`,
|
|
359
|
+
});
|
|
360
|
+
}
|
|
361
|
+
for (const variable of expressionVariables(clause.expr)) {
|
|
362
|
+
if (!bound.has(variable)) {
|
|
363
|
+
diagnostics.push({
|
|
364
|
+
code: 'unbound-assignment-variable',
|
|
365
|
+
severity: 'error',
|
|
366
|
+
rule: ruleNameValue,
|
|
367
|
+
message: `${displayRuleName(ruleNameValue, prefixes)} SET expression uses ?${variable} before it is bound${scopeLabel}`,
|
|
368
|
+
});
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
bound.add(clause.variable);
|
|
372
|
+
} else if (clause.type === 'not') {
|
|
373
|
+
visit(clause.body, bound, ' inside NOT');
|
|
374
|
+
} else if (clause.type === 'group') {
|
|
375
|
+
// Only keys correlate the group pattern with the incoming mapping.
|
|
376
|
+
const initial = new Set(clause.keys.filter((key) => bound.has(key)));
|
|
377
|
+
const inner = visit(clause.pattern, initial, ' inside GROUP');
|
|
378
|
+
const error = (code, message) => diagnostics.push({
|
|
379
|
+
code, severity: 'error', rule: ruleNameValue,
|
|
380
|
+
message: `${displayRuleName(ruleNameValue, prefixes)} ${message}`,
|
|
381
|
+
});
|
|
382
|
+
for (const key of clause.keys) {
|
|
383
|
+
if (!inner.has(key)) error('unbound-group-key', `GROUP key ?${key} is not bound in the group pattern`);
|
|
384
|
+
}
|
|
385
|
+
const assigned = new Set();
|
|
386
|
+
for (const aggregation of clause.aggregations) {
|
|
387
|
+
const { variable, function: fn } = aggregation;
|
|
388
|
+
if (inner.has(variable) || bound.has(variable)) error('aggregation-variable-already-bound', `GROUP assigns ?${variable}, but that variable is already bound`);
|
|
389
|
+
if (assigned.has(variable)) error('duplicate-aggregation-variable', `GROUP assigns ?${variable} more than once`);
|
|
390
|
+
if (fn.argument !== '*' && !inner.has(fn.argument)) error('unbound-aggregation-argument', `GROUP aggregate uses unbound variable ?${fn.argument}`);
|
|
391
|
+
assigned.add(variable);
|
|
392
|
+
}
|
|
393
|
+
for (const key of clause.keys) bound.add(key);
|
|
394
|
+
for (const variable of assigned) bound.add(variable);
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
return bound;
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
visit(clauses, initialBound, '');
|
|
401
|
+
return diagnostics;
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
function bodyTriplePatterns(clauses, wantNegative, inNegativeContext = false) {
|
|
405
|
+
const out = [];
|
|
406
|
+
for (const clause of clauses) {
|
|
407
|
+
if ((clause.type === 'triple' || clause.type === 'path') && wantNegative === inNegativeContext) {
|
|
408
|
+
if (clause.type === 'path') out.push(...pathTriplePatterns(clause.triple));
|
|
409
|
+
else out.push(clause.triple);
|
|
410
|
+
} else if (clause.type === 'not') {
|
|
411
|
+
if (!clause.groundData) out.push(...bodyTriplePatterns(clause.body, wantNegative, true));
|
|
412
|
+
} else if (clause.type === 'group') {
|
|
413
|
+
out.push(...bodyTriplePatterns(clause.pattern, wantNegative, inNegativeContext));
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
return out;
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
function pathTriplePatterns(triple) {
|
|
420
|
+
const predicates = predicateIRIs(triple);
|
|
421
|
+
if (predicates.length === 0) return [];
|
|
422
|
+
return predicates.map((predicate, index) => ({
|
|
423
|
+
s: variable(`__path_s_${index}`),
|
|
424
|
+
p: iri(predicate),
|
|
425
|
+
o: variable(`__path_o_${index}`),
|
|
426
|
+
}));
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
function dependencyPredicateLabel(pattern) {
|
|
430
|
+
return pattern && pattern.p && pattern.p.type === 'iri' ? pattern.p.value : null;
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
function canPossiblyGenerate(template, pattern) {
|
|
434
|
+
if (!template || !pattern) return false;
|
|
435
|
+
if (!compatibleTerm(template.s, pattern.s)) return false;
|
|
436
|
+
if (!compatibleTerm(template.p, pattern.p)) return false;
|
|
437
|
+
if (!compatibleTerm(template.o, pattern.o)) return false;
|
|
438
|
+
|
|
439
|
+
const constraints = new Map();
|
|
440
|
+
if (!recordTemplateVariableConstraints(template.s, pattern.s, constraints)) return false;
|
|
441
|
+
if (!recordTemplateVariableConstraints(template.p, pattern.p, constraints)) return false;
|
|
442
|
+
if (!recordTemplateVariableConstraints(template.o, pattern.o, constraints)) return false;
|
|
443
|
+
return true;
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
function compatibleTerm(templateTerm, patternTerm) {
|
|
447
|
+
if (!templateTerm || !patternTerm) return false;
|
|
448
|
+
if (templateTerm.type === 'var' || patternTerm.type === 'var') return true;
|
|
449
|
+
if (templateTerm.type === 'triple' || patternTerm.type === 'triple') {
|
|
450
|
+
if (templateTerm.type !== 'triple' || patternTerm.type !== 'triple') return false;
|
|
451
|
+
return compatibleTerm(templateTerm.s, patternTerm.s)
|
|
452
|
+
&& compatibleTerm(templateTerm.p, patternTerm.p)
|
|
453
|
+
&& compatibleTerm(templateTerm.o, patternTerm.o);
|
|
454
|
+
}
|
|
455
|
+
return termEquals(templateTerm, patternTerm);
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
function recordTemplateVariableConstraints(templateTerm, patternTerm, constraints) {
|
|
459
|
+
if (!templateTerm || !patternTerm) return false;
|
|
460
|
+
if (templateTerm.type === 'var') {
|
|
461
|
+
const existing = constraints.get(templateTerm.value);
|
|
462
|
+
if (!existing) {
|
|
463
|
+
constraints.set(templateTerm.value, patternTerm);
|
|
464
|
+
return true;
|
|
465
|
+
}
|
|
466
|
+
return possiblySameTerm(existing, patternTerm);
|
|
467
|
+
}
|
|
468
|
+
if (templateTerm.type === 'triple' && patternTerm.type === 'triple') {
|
|
469
|
+
return recordTemplateVariableConstraints(templateTerm.s, patternTerm.s, constraints)
|
|
470
|
+
&& recordTemplateVariableConstraints(templateTerm.p, patternTerm.p, constraints)
|
|
471
|
+
&& recordTemplateVariableConstraints(templateTerm.o, patternTerm.o, constraints);
|
|
472
|
+
}
|
|
473
|
+
return true;
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
function possiblySameTerm(a, b) {
|
|
477
|
+
if (!a || !b) return false;
|
|
478
|
+
if (a.type === 'var' || b.type === 'var') return true;
|
|
479
|
+
if (a.type === 'triple' || b.type === 'triple') {
|
|
480
|
+
if (a.type !== 'triple' || b.type !== 'triple') return false;
|
|
481
|
+
return possiblySameTerm(a.s, b.s) && possiblySameTerm(a.p, b.p) && possiblySameTerm(a.o, b.o);
|
|
482
|
+
}
|
|
483
|
+
return termEquals(a, b);
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
function bodyPredicates(clauses, wantNegative, inNegativeContext = false) {
|
|
487
|
+
const out = [];
|
|
488
|
+
for (const clause of clauses) {
|
|
489
|
+
if ((clause.type === 'triple' || clause.type === 'path') && wantNegative === inNegativeContext) {
|
|
490
|
+
out.push(...predicateIRIs(clause.triple));
|
|
491
|
+
} else if (clause.type === 'not') {
|
|
492
|
+
out.push(...bodyPredicates(clause.body, wantNegative, true));
|
|
493
|
+
} else if (clause.type === 'group') {
|
|
494
|
+
out.push(...bodyPredicates(clause.pattern, wantNegative, inNegativeContext));
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
return out;
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
function predicateIRI(triple) {
|
|
501
|
+
return triple && triple.p && triple.p.type === 'iri' ? triple.p.value : null;
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
function predicateIRIs(triple) {
|
|
505
|
+
if (!triple || !triple.p) return [];
|
|
506
|
+
if (triple.p.type === 'iri') return [triple.p.value];
|
|
507
|
+
if (triple.p.type === 'path') return pathPredicateIRIs(triple.p);
|
|
508
|
+
return [];
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
function pathPredicateIRIs(path) {
|
|
512
|
+
if (!path) return [];
|
|
513
|
+
if (path.type === 'iri') return [path.value];
|
|
514
|
+
if (path.type !== 'path') return [];
|
|
515
|
+
if (path.kind === 'inverse') return pathPredicateIRIs(path.path);
|
|
516
|
+
if (path.kind === 'sequence') return path.parts.flatMap(pathPredicateIRIs);
|
|
517
|
+
if (path.kind === 'iri') return pathPredicateIRIs(path.iri);
|
|
518
|
+
return [];
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
function effectiveHeadTemplates(rule) {
|
|
522
|
+
const constants = assignmentConstantTerms(rule.body || []);
|
|
523
|
+
if (constants.size === 0) return rule.head.slice();
|
|
524
|
+
return rule.head.map((triple) => ({
|
|
525
|
+
s: substituteAssignedConstant(triple.s, constants),
|
|
526
|
+
p: substituteAssignedConstant(triple.p, constants),
|
|
527
|
+
o: substituteAssignedConstant(triple.o, constants),
|
|
528
|
+
}));
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
function assignmentConstantTerms(clauses) {
|
|
532
|
+
const constants = new Map();
|
|
533
|
+
const bound = new Set();
|
|
534
|
+
for (const clause of clauses) {
|
|
535
|
+
if (clause.type === 'triple' || clause.type === 'path') {
|
|
536
|
+
collectTripleVars(clause.triple, bound);
|
|
537
|
+
continue;
|
|
538
|
+
}
|
|
539
|
+
if (clause.type === 'filter') continue;
|
|
540
|
+
if (clause.type === 'not') continue;
|
|
541
|
+
if (clause.type === 'group') {
|
|
542
|
+
for (const key of clause.keys) bound.add(key);
|
|
543
|
+
for (const aggregation of clause.aggregations) bound.add(aggregation.variable);
|
|
544
|
+
continue;
|
|
545
|
+
}
|
|
546
|
+
if (clause.type === 'set' || clause.type === 'bind') {
|
|
547
|
+
const value = constantExpressionTerm(clause.expr);
|
|
548
|
+
if (value && !bound.has(clause.variable)) constants.set(clause.variable, value);
|
|
549
|
+
bound.add(clause.variable);
|
|
550
|
+
}
|
|
551
|
+
}
|
|
552
|
+
return constants;
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
function constantExpressionTerm(expr) {
|
|
556
|
+
if (!expr || expressionVariables(expr).size > 0) return null;
|
|
557
|
+
if (expr.type === 'term') return expr.value;
|
|
558
|
+
return null;
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
function substituteAssignedConstant(term, constants) {
|
|
562
|
+
if (!term) return term;
|
|
563
|
+
if (term.type === 'var' && constants.has(term.value)) return constants.get(term.value);
|
|
564
|
+
if (term.type === 'triple') {
|
|
565
|
+
return {
|
|
566
|
+
type: 'triple',
|
|
567
|
+
s: substituteAssignedConstant(term.s, constants),
|
|
568
|
+
p: substituteAssignedConstant(term.p, constants),
|
|
569
|
+
o: substituteAssignedConstant(term.o, constants),
|
|
570
|
+
};
|
|
571
|
+
}
|
|
572
|
+
return term;
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
function ruleHasAssignment(rule, options = {}) {
|
|
576
|
+
return (rule.body || []).some((clause) => clause.type === 'set' || clause.type === 'bind'
|
|
577
|
+
|| (clause.type === 'group' && ruleHasAssignment({ body: clause.pattern }, options)));
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
function ruleHasTermGeneratingAssignment(rule, options = {}) {
|
|
581
|
+
return (rule.body || []).some((clause) => ((clause.type === 'set' || clause.type === 'bind') && assignmentMayCreateNewTerm(clause.expr))
|
|
582
|
+
|| (clause.type === 'group' && ruleHasTermGeneratingAssignment({ body: clause.pattern }, options)));
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
function ruleCreatesTerms(rule, options = {}) {
|
|
586
|
+
return ruleHeadHasBlankNode(rule)
|
|
587
|
+
|| (rule.head || []).some(tripleHasVariableTripleTerm)
|
|
588
|
+
|| (rule.body || []).some((clause) => clause.type === 'group')
|
|
589
|
+
|| ruleHasTermGeneratingAssignment(rule, options);
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
function assignmentMayCreateNewTerm(expr) {
|
|
593
|
+
// Simple aliases and constants are not term generators: they select from a
|
|
594
|
+
// fixed term or from already-bound terms. Expressions that compute values
|
|
595
|
+
// through operators or functions may create an unbounded sequence when used
|
|
596
|
+
// recursively, e.g. SET(?v1 := ?v + 1), so they remain part of the strict
|
|
597
|
+
// recursive-new-terms check.
|
|
598
|
+
if (!expr) return false;
|
|
599
|
+
if (expr.type === 'var' || expr.type === 'term' || expr.type === 'literal') return false;
|
|
600
|
+
return true;
|
|
601
|
+
}
|
|
602
|
+
|
|
603
|
+
function ruleHeadHasBlankNode(rule) {
|
|
604
|
+
return (rule.head || []).some(tripleHasBlankNode);
|
|
605
|
+
}
|
|
606
|
+
|
|
607
|
+
function boundVariables(clauses, initialBound = new Set()) {
|
|
608
|
+
const vars = new Set(initialBound);
|
|
609
|
+
for (const clause of clauses) {
|
|
610
|
+
if (clause.type === 'triple' || clause.type === 'path') collectTripleVars(clause.triple, vars);
|
|
611
|
+
if ((clause.type === 'set' || clause.type === 'bind')) vars.add(clause.variable);
|
|
612
|
+
if (clause.type === 'group') {
|
|
613
|
+
for (const key of clause.keys) vars.add(key);
|
|
614
|
+
for (const aggregation of clause.aggregations) vars.add(aggregation.variable);
|
|
615
|
+
}
|
|
616
|
+
}
|
|
617
|
+
return vars;
|
|
618
|
+
}
|
|
619
|
+
|
|
620
|
+
function positiveVariables(clauses) {
|
|
621
|
+
const vars = new Set();
|
|
622
|
+
for (const clause of clauses) {
|
|
623
|
+
if (clause.type === 'triple' || clause.type === 'path') collectTripleVars(clause.triple, vars);
|
|
624
|
+
if ((clause.type === 'set' || clause.type === 'bind')) vars.add(clause.variable);
|
|
625
|
+
if (clause.type === 'group') {
|
|
626
|
+
for (const key of clause.keys) vars.add(key);
|
|
627
|
+
for (const aggregation of clause.aggregations) vars.add(aggregation.variable);
|
|
628
|
+
}
|
|
629
|
+
if (clause.type === 'filter') for (const v of expressionVariables(clause.expr)) vars.add(v);
|
|
630
|
+
}
|
|
631
|
+
return vars;
|
|
632
|
+
}
|
|
633
|
+
|
|
634
|
+
function bodyVariables(clauses) {
|
|
635
|
+
const vars = new Set();
|
|
636
|
+
for (const clause of clauses) {
|
|
637
|
+
if (clause.type === 'triple' || clause.type === 'path') collectTripleVars(clause.triple, vars);
|
|
638
|
+
if ((clause.type === 'set' || clause.type === 'bind')) {
|
|
639
|
+
vars.add(clause.variable);
|
|
640
|
+
for (const v of expressionVariables(clause.expr)) vars.add(v);
|
|
641
|
+
}
|
|
642
|
+
if (clause.type === 'filter') for (const v of expressionVariables(clause.expr)) vars.add(v);
|
|
643
|
+
if (clause.type === 'not') for (const v of bodyVariables(clause.body)) vars.add(v);
|
|
644
|
+
if (clause.type === 'group') {
|
|
645
|
+
for (const key of clause.keys) vars.add(key);
|
|
646
|
+
for (const aggregation of clause.aggregations) {
|
|
647
|
+
vars.add(aggregation.variable);
|
|
648
|
+
if (aggregation.function.argument !== '*') vars.add(aggregation.function.argument);
|
|
649
|
+
}
|
|
650
|
+
for (const v of bodyVariables(clause.pattern)) vars.add(v);
|
|
651
|
+
}
|
|
652
|
+
}
|
|
653
|
+
return vars;
|
|
654
|
+
}
|
|
655
|
+
|
|
656
|
+
function collectTripleVars(triple, vars) {
|
|
657
|
+
for (const term of [triple.s, triple.p, triple.o]) collectTermVars(term, vars);
|
|
658
|
+
}
|
|
659
|
+
|
|
660
|
+
function collectTermVars(term, vars) {
|
|
661
|
+
if (!term) return;
|
|
662
|
+
if (term.type === 'var') vars.add(term.value);
|
|
663
|
+
if (term.type === 'triple') {
|
|
664
|
+
collectTermVars(term.s, vars);
|
|
665
|
+
collectTermVars(term.p, vars);
|
|
666
|
+
collectTermVars(term.o, vars);
|
|
667
|
+
}
|
|
668
|
+
if (term.type === 'path') {
|
|
669
|
+
if (term.kind === 'inverse') collectTermVars(term.path, vars);
|
|
670
|
+
if (term.kind === 'sequence') for (const part of term.parts) collectTermVars(part, vars);
|
|
671
|
+
}
|
|
672
|
+
}
|
|
673
|
+
|
|
674
|
+
function expressionVariables(expr, vars = new Set()) {
|
|
675
|
+
if (!expr) return vars;
|
|
676
|
+
if (expr.type === 'var') vars.add(expr.name);
|
|
677
|
+
else if (expr.type === 'unary') expressionVariables(expr.expr, vars);
|
|
678
|
+
else if (expr.type === 'binary') {
|
|
679
|
+
expressionVariables(expr.left, vars);
|
|
680
|
+
expressionVariables(expr.right, vars);
|
|
681
|
+
} else if (expr.type === 'call') {
|
|
682
|
+
for (const arg of expr.args) expressionVariables(arg, vars);
|
|
683
|
+
} else if (expr.type === 'list') {
|
|
684
|
+
for (const item of expr.items) expressionVariables(item, vars);
|
|
685
|
+
} else if (expr.type === 'term') {
|
|
686
|
+
collectTermVars(expr.value, vars);
|
|
687
|
+
}
|
|
688
|
+
return vars;
|
|
689
|
+
}
|
|
690
|
+
|
|
691
|
+
export {
|
|
692
|
+
analyze,
|
|
693
|
+
dependencyGraph,
|
|
694
|
+
stratificationLayers,
|
|
695
|
+
boundVariables,
|
|
696
|
+
positiveVariables,
|
|
697
|
+
bodyVariables,
|
|
698
|
+
collectTripleVars,
|
|
699
|
+
expressionVariables,
|
|
700
|
+
pathPredicateIRIs,
|
|
701
|
+
bodyTriplePatterns,
|
|
702
|
+
canPossiblyGenerate,
|
|
703
|
+
};
|