eyemind 0.8.0 → 0.8.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/src/shacl.js CHANGED
@@ -1,10 +1,11 @@
1
1
  // SHACL Core shapes compile to separate LS predicates. Each dependency is
2
2
  // explicit before LS stratification; a nested sh:not/or/node is not a test
3
3
  // against an incompletely materialized generic conformance relation.
4
- // https://www.w3.org/TR/shacl/
4
+ // https://www.w3.org/TR/shacl12-core/
5
5
  import { EyemindError, Struct } from './terms.js';
6
6
  import { write } from './writer.js';
7
7
  import { RDF_DATATYPES } from './rdf-values.js';
8
+ import { NODE_COMMON, nodeExpressions } from './shacl-expr.js';
8
9
 
9
10
  const SH = 'http://www.w3.org/ns/shacl#';
10
11
  const RDF = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#';
@@ -14,34 +15,56 @@ const uri = (u) => new Struct('iri', [u]);
14
15
  const iri = (u) => write(uri(u));
15
16
  const sh = (n) => iri(SH + n);
16
17
  const NONE = "'sh_none'";
17
- const TARGETS = ['targetNode', 'targetClass', 'targetSubjectsOf', 'targetObjectsOf'];
18
+ const TARGETS = ['targetNode', 'targetClass', 'targetSubjectsOf', 'targetObjectsOf', 'targetWhere'];
18
19
  const CONSTRAINTS = ['class', 'datatype', 'nodeKind', 'minCount', 'maxCount', 'minExclusive', 'minInclusive',
19
- 'maxExclusive', 'maxInclusive', 'minLength', 'maxLength', 'pattern', 'languageIn', 'uniqueLang',
20
- 'equals', 'disjoint', 'lessThan', 'lessThanOrEquals', 'not', 'and', 'or', 'xone', 'node', 'property',
21
- 'qualifiedValueShape', 'qualifiedMinCount', 'qualifiedMaxCount', 'qualifiedValueShapesDisjoint', 'closed', 'hasValue', 'in'];
22
- const ANNOTATIONS = ['severity', 'message', 'deactivated', 'name', 'description', 'order', 'group', 'defaultValue', 'unit'];
23
- const ALLOWED = new Set([...TARGETS, ...CONSTRAINTS, ...ANNOTATIONS, 'path', 'flags', 'ignoredProperties']);
24
- const BOOL = (t, v) => t instanceof Struct && t.name === 'literal' && t.args[1]?.name === 'datatype' &&
25
- t.args[1].args[0] === XSD + 'boolean' && (v ? ['true', '1'] : ['false', '0']).includes(t.args[0]);
20
+ 'maxExclusive', 'maxInclusive', 'minLength', 'maxLength', 'pattern', 'singleLine', 'languageIn', 'uniqueLang',
21
+ 'memberShape', 'minListLength', 'maxListLength', 'uniqueMembers', 'equals', 'disjoint', 'subsetOf', 'lessThan',
22
+ 'lessThanOrEquals', 'not', 'and', 'or', 'xone', 'node', 'property', 'someValue', 'qualifiedValueShape',
23
+ 'qualifiedMinCount', 'qualifiedMaxCount', 'qualifiedValueShapesDisjoint', 'reifierShape', 'reificationRequired',
24
+ 'closed', 'hasValue', 'in', 'rootClass', 'uniqueValuesFor', 'expression', 'nodeByExpression'];
25
+ const ANNOTATIONS = ['severity', 'message', 'deactivated', 'name', 'description', 'order', 'group', 'defaultValue', 'unit',
26
+ 'intent', 'agentInstruction', 'codeIdentifier', 'codeType', 'keyParameter', 'optional'];
27
+ const ALLOWED = new Set([...TARGETS, ...CONSTRAINTS, ...ANNOTATIONS, 'path', 'values', 'flags', 'ignoredProperties']);
28
+ // Shape-expecting parameters, whose values are compiled as shapes and checked for recursion.
29
+ const SHAPE_PARAMETERS = ['node', 'not', 'qualifiedValueShape', 'property', 'memberShape', 'reifierShape', 'someValue', 'targetWhere'];
30
+ const PATH_OPERATORS = ['inversePath', 'alternativePath', 'zeroOrMorePath', 'oneOrMorePath', 'zeroOrOnePath'];
31
+ // The default conformance-disallow set of SHACL 1.2.
32
+ export const SHACL_DISALLOWS = ['Violation', 'Warning', 'Info'].map((n) => SH + n);
33
+ const literal = (t, datatype) => t instanceof Struct && t.name === 'literal' && t.args[1]?.name === 'datatype' && t.args[1].args[0] === datatype;
34
+ const BOOL = (t) => literal(t, XSD + 'boolean') && ['true', 'false', '1', '0'].includes(t.args[0]);
35
+ // Only the boolean true activates a constraint; the suite reads "1" as not true.
36
+ const TRUE = (t) => literal(t, XSD + 'boolean') && t.args[0] === 'true';
26
37
  const isIri = (t) => t instanceof Struct && t.name === 'iri';
27
38
  const resource = (t) => t instanceof Struct && ['iri', 'bnode', 'triple'].includes(t.name);
39
+ const typeNames = (types) => types.map((t) => t.args?.[0]);
40
+ const TRUE_TERM = `literal('true', datatype('${XSD}boolean'))`;
28
41
 
29
- export function compileShacl(quads) {
30
- const graphs = new Map(), lines = [COMMON];
42
+ // needs collects the SPARQL library definitions that node expressions call;
43
+ // evaluate { expression, focus, scope } adds sh_evaluation(Result) for one
44
+ // node expression of the default graph.
45
+ export function compileShacl(quads, { disallows = SHACL_DISALLOWS, needs = new Set(), evaluate } = {}) {
46
+ const graphs = new Map(), lines = [COMMON, NODE_COMMON], blocked = new Set(disallows);
47
+ for (const severity of disallows) lines.push(`fact(sh_disallowed(${iri(severity)}));`);
48
+ if (disallows.length !== SHACL_DISALLOWS.length || disallows.some((d) => !SHACL_DISALLOWS.includes(d)))
49
+ lines.push('fact(sh_custom_disallows);');
31
50
  for (const [s, p, o, g] of quads) {
32
51
  const key = write(g);
33
52
  if (!graphs.has(key)) graphs.set(key, { graph: g, triples: [] });
34
53
  graphs.get(key).triples.push([s, p, o]);
35
54
  }
36
- let nextShape = 0, nextPath = 0;
55
+ let nextShape = 0, nextPath = 0, nextConstraint = 0, nextHelper = 0;
37
56
  for (const { graph, triples } of graphs.values()) {
38
- const G = write(graph), index = new Map(), subjects = new Map();
57
+ const G = write(graph), index = new Map(), terms = new Map(), reifiers = new Map();
39
58
  for (const [s, p, o] of triples) {
40
59
  const key = write(s);
41
- if (!index.has(key)) { index.set(key, new Map()); subjects.set(key, s); }
60
+ if (!index.has(key)) { index.set(key, new Map()); terms.set(key, s); }
42
61
  const properties = index.get(key), name = p.args[0];
43
62
  if (!properties.has(name)) properties.set(name, []);
44
63
  if (!properties.get(name).some((v) => write(v) === write(o))) properties.get(name).push(o);
64
+ if (name === RDF + 'reifies' && o instanceof Struct && o.name === 'triple') {
65
+ if (!reifiers.has(write(o))) reifiers.set(write(o), []);
66
+ reifiers.get(write(o)).push(s);
67
+ }
45
68
  }
46
69
  const values = (s, p) => index.get(write(s))?.get(p.startsWith('http') ? p : SH + p) ?? [];
47
70
  const error = (s, message) => { throw new EyemindError(`--shacl: ${write(s)} ${message}`); };
@@ -62,17 +85,26 @@ export function compileShacl(quads) {
62
85
  }
63
86
  return items;
64
87
  };
88
+ // sh:class, sh:datatype, sh:nodeKind and sh:rootClass take an IRI or a list of IRIs.
89
+ const iris = (s, property, t) => {
90
+ const items = isIri(t) ? [t] : t.name === 'bnode' ? rdfList(t) : [];
91
+ if (!items.length || !items.every(isIri)) error(s, `needs an IRI or a list of IRIs as sh:${property}`);
92
+ return items;
93
+ };
94
+ const types = (s) => typeNames(values(s, RDF + 'type'));
95
+ const isClass = (s) => types(s).some((t) => t === RDFS + 'Class' || t === SH + 'ShapeClass');
96
+ const isNodeShape = (s) => types(s).some((t) => t === SH + 'NodeShape' || t === SH + 'ShapeClass');
65
97
  const shapes = new Map();
66
98
  const shape = (s, depth = 0) => {
67
99
  if (!resource(s)) error(s, 'is not a shape resource');
68
100
  const key = write(s);
69
101
  if (shapes.has(key)) return shapes.get(key);
70
102
  if (depth >= 128) error(s, 'has shape references nested beyond 128 levels');
71
- const node = { term: s, id: nextShape++, refs: [], properties: [], lists: new Map(), inactive: BOOL(one(s, 'deactivated'), true) };
103
+ const node = { term: s, id: nextShape++, refs: [], properties: [], lists: new Map(), inactive: TRUE(one(s, 'deactivated')) };
72
104
  shapes.set(key, node);
73
105
  if (node.inactive) return node;
74
106
  for (const p of index.get(key)?.keys() ?? []) if (p.startsWith(SH) && !ALLOWED.has(p.slice(SH.length))) error(s, `uses unsupported SHACL feature <${p}>`);
75
- for (const p of ['node', 'not', 'qualifiedValueShape', 'property']) for (const child of values(s, p)) {
107
+ for (const p of SHAPE_PARAMETERS) for (const child of values(s, p)) {
76
108
  const target = shape(child, depth + 1); node.refs.push(target);
77
109
  if (p === 'property') node.properties.push(target);
78
110
  }
@@ -87,7 +119,7 @@ export function compileShacl(quads) {
87
119
  };
88
120
  for (const [s, p, o] of triples) {
89
121
  if (p.args[0].startsWith(SH) && [...TARGETS, ...CONSTRAINTS, 'path'].includes(p.args[0].slice(SH.length))) shape(s);
90
- if (p.args[0] === RDF + 'type' && [SH + 'NodeShape', SH + 'PropertyShape'].includes(o.args?.[0])) shape(s);
122
+ if (p.args[0] === RDF + 'type' && [SH + 'NodeShape', SH + 'PropertyShape', SH + 'ShapeClass'].includes(o.args?.[0])) shape(s);
91
123
  }
92
124
  const checked = new Set(), checking = new Set();
93
125
  const acyclic = (node) => {
@@ -96,6 +128,19 @@ export function compileShacl(quads) {
96
128
  checking.add(node.id); node.refs.forEach(acyclic); checking.delete(node.id); checked.add(node.id);
97
129
  };
98
130
  shapes.forEach(acyclic);
131
+ // A shape whose conformance may consult shapes chosen at evaluation time
132
+ // is dynamic. Dynamic dispatch (sh_conforms) lists only the other shapes,
133
+ // so that negation stays stratified.
134
+ const dynamics = new Map();
135
+ const dynamic = (node) => {
136
+ if (dynamics.has(node.id)) return dynamics.get(node.id);
137
+ dynamics.set(node.id, false);
138
+ const s = node.term, blank = (p) => values(s, p).some((t) => t instanceof Struct && t.name === 'bnode');
139
+ const result = !node.inactive && (values(s, 'expression').length > 0 || values(s, 'nodeByExpression').length > 0 ||
140
+ ['values', 'defaultValue', 'deactivated'].some(blank) || node.refs.some(dynamic));
141
+ dynamics.set(node.id, result);
142
+ return result;
143
+ };
99
144
  const paths = new Map(), parsing = new Set();
100
145
  const path = (term) => {
101
146
  const key = write(term);
@@ -106,7 +151,7 @@ export function compileShacl(quads) {
106
151
  const name = `sh_path_${nextPath++}`;
107
152
  if (isIri(term)) lines.push(`implies([rdf(X, ${write(term)}, Y, ${G}), ent_resource(X)], ${name}(X, Y));`);
108
153
  else {
109
- const operators = ['inversePath', 'alternativePath', 'zeroOrMorePath', 'oneOrMorePath', 'zeroOrOnePath'].filter((op) => values(term, op).length);
154
+ const operators = PATH_OPERATORS.filter((op) => values(term, op).length);
110
155
  if (values(term, RDF + 'first').length) {
111
156
  if (operators.length) error(term, 'mixes a sequence path with another path operator');
112
157
  const steps = rdfList(term);
@@ -133,19 +178,73 @@ export function compileShacl(quads) {
133
178
  }
134
179
  parsing.delete(key); paths.set(key, name); return name;
135
180
  };
181
+ const expressions = nodeExpressions({ G, lines, needs, index, rdfList, path, error,
182
+ conforms: (t) => `sh_ok_${shape(t).id}` });
183
+ const expression = (t) => expressions.compile(t);
184
+ // sh:closed sh:ByTypes permits, for each rdf:type T of a value node, the
185
+ // properties that collectProperties(T) reaches in the shapes graph.
186
+ let byTypes = null;
187
+ const closedByTypes = () => {
188
+ if (byTypes) return byTypes;
189
+ byTypes = 'sh_by_types';
190
+ const targeting = new Map();
191
+ for (const [s, p, o] of triples) if (p.args[0] === SH + 'targetClass') {
192
+ if (!targeting.has(write(o))) targeting.set(write(o), []);
193
+ targeting.get(write(o)).push(s);
194
+ }
195
+ const collect = (s, out, seen) => {
196
+ if (seen.has(write(s))) return;
197
+ seen.add(write(s));
198
+ for (const property of values(s, 'property')) for (const p of values(property, 'path')) if (isIri(p)) out.set(write(p), p);
199
+ if (isClass(s)) {
200
+ for (const o of values(s, RDFS + 'subClassOf')) collect(o, out, seen);
201
+ for (const o of targeting.get(write(s)) ?? []) collect(o, out, seen);
202
+ }
203
+ if (isNodeShape(s)) for (const o of values(s, 'node')) collect(o, out, seen);
204
+ };
205
+ const candidates = new Map(terms);
206
+ for (const [, , o] of triples) if (targeting.has(write(o))) candidates.set(write(o), o);
207
+ for (const [key, s] of candidates) {
208
+ if (!isIri(s)) continue;
209
+ const out = new Map();
210
+ collect(s, out, new Set());
211
+ for (const p of out.keys()) lines.push(`fact(${byTypes}(${key}, ${p}, ${G}));`);
212
+ }
213
+ return byTypes;
214
+ };
136
215
  for (const node of shapes.values()) {
137
- const { term: s, id, inactive } = node, S = write(s), v = `sh_values_${id}`, ok = `sh_ok_${id}`, bad = `sh_bad_${id}`, issue = `sh_issue_${id}`, focus = `sh_focus_${id}`;
138
- if (inactive) { lines.push(`fact(${ok}(_));`); continue; }
216
+ const { term: s, id, inactive } = node, S = write(s), v = `sh_values_${id}`, ok = `sh_ok_${id}`, bad = `sh_bad_${id}`;
217
+ const issue = `sh_issue_${id}`, focus = `sh_focus_${id}`, target = `sh_target_${id}`;
218
+ if (inactive) {
219
+ lines.push(`fact(${ok}(_));`);
220
+ if (isIri(s)) lines.push(`fact(sh_shape(${S}));`, `implied_by(sh_conforms(${S}, X), ${ok}(X));`);
221
+ continue;
222
+ }
139
223
  const p = one(s, 'path'), P = p ? write(p) : NONE;
140
- if (p && values(s, RDF + 'type').some((t) => t.args?.[0] === SH + 'NodeShape')) error(s, 'is a NodeShape with sh:path');
141
- if (!p && values(s, RDF + 'type').some((t) => t.args?.[0] === SH + 'PropertyShape')) error(s, 'is a PropertyShape without sh:path');
142
- lines.push(p ? `implied_by(${v}(F, V), ${path(p)}(F, V));` : `implied_by(${v}(F, F), ent_node(F, ${G}));`);
224
+ if (p && types(s).includes(SH + 'NodeShape')) error(s, 'is a NodeShape with sh:path');
225
+ if (!p && types(s).includes(SH + 'PropertyShape')) error(s, 'is a PropertyShape without sh:path');
226
+ if (p) lines.push(`implied_by(${v}(F, V), ${path(p)}(F, V));`);
227
+ else lines.push(`fact(${v}(F, F));`);
228
+ // sh:values adds the output nodes of its node expressions, and
229
+ // sh:defaultValue supplies its own when there is no other value node.
230
+ const produced = (property) => values(s, property).map((t) => {
231
+ if (!p) error(s, `uses sh:${property} without a property path`);
232
+ return expression(t);
233
+ });
234
+ const added = produced('values'), fallback = one(s, 'defaultValue');
235
+ for (const e of added) lines.push(`implied_by(${v}(F, V), [${e}(F, [], nodes(L)), ent_member(V, L)]);`);
236
+ if (fallback !== undefined) {
237
+ const own = `sh_own_${id}`;
238
+ lines.push(`implied_by(${own}(F), ${path(p)}(F, _));`);
239
+ for (const e of added) lines.push(`implied_by(${own}(F), [${e}(F, [], nodes([_, ..._]))]);`);
240
+ lines.push(`implied_by(${v}(F, V), [not(${own}(F)), ${produced('defaultValue')[0]}(F, [], nodes(L)), ent_member(V, L)]);`);
241
+ }
143
242
  // A complex resultPath must remain interpretable in the standalone report.
144
243
  const describePath = (term, seen = new Set()) => {
145
244
  if (isIri(term) || seen.has(write(term))) return;
146
245
  seen.add(write(term));
147
246
  for (const [predicate, objects] of index.get(write(term)) ?? []) {
148
- if (![RDF + 'first', RDF + 'rest', ...['inversePath', 'alternativePath', 'zeroOrMorePath', 'oneOrMorePath', 'zeroOrOnePath'].map((n) => SH + n)].includes(predicate)) continue;
247
+ if (![RDF + 'first', RDF + 'rest', ...PATH_OPERATORS.map((n) => SH + n)].includes(predicate)) continue;
149
248
  for (const object of objects) {
150
249
  lines.push(`fact(sh_path_statement(${P}, ${write(term)}, ${iri(predicate)}, ${write(object)}, ${G}));`);
151
250
  describePath(object, seen);
@@ -153,54 +252,91 @@ export function compileShacl(quads) {
153
252
  }
154
253
  };
155
254
  if (p) describePath(p);
156
- const emit = (body, component, value = 'V', resultPath = P, key = NONE) => lines.push(`implied_by(${issue}(F, ${resultPath}, ${value}, ${sh(component + 'ConstraintComponent')}, ${key}), [${body.join(', ')}]);`);
157
- const each = (property, fn) => values(s, property).forEach(fn);
158
- const scalar = (property, fn) => { const t = one(s, property); if (t !== undefined) fn(t); };
159
255
  const integer = (property, t) => { if (typeof t !== 'bigint' || t < 0n) error(s, `needs a nonnegative integer sh:${property}`); return write(t); };
160
- const boolean = (property, t) => { if (!BOOL(t, true) && !BOOL(t, false)) error(s, `needs a boolean sh:${property}`); return BOOL(t, true); };
256
+ const boolean = (property, t) => { if (!BOOL(t)) error(s, `needs a boolean sh:${property}`); return TRUE(t); };
161
257
  const requireIri = (property, t) => { if (!isIri(t)) error(s, `needs an IRI sh:${property}`); return write(t); };
162
- scalar('deactivated', (t) => boolean('deactivated', t));
163
258
  const severity = one(s, 'severity') ?? uri(SH + 'Violation');
164
259
  requireIri('severity', severity);
165
- lines.push(`fact(sh_severity(${S}, ${write(severity)}, ${G}));`);
166
- for (const message of values(s, 'message')) {
167
- if (!(message instanceof Struct && message.name === 'literal')) error(s, 'needs literal sh:message values');
168
- lines.push(`fact(sh_message(${S}, ${write(message)}, ${G}));`);
260
+ const messages = values(s, 'message');
261
+ for (const message of messages) if (!(message instanceof Struct && message.name === 'literal')) error(s, 'needs literal sh:message values');
262
+ // A constraint is the set of triples of its parameters. Their reifiers
263
+ // may deactivate it or give it its own severity and messages.
264
+ const constraint = (...pairs) => {
265
+ const annotations = pairs.flatMap(([property, t]) => reifiers.get(write(new Struct('triple', [s, uri(SH + property), t]))) ?? []);
266
+ if (annotations.some((r) => TRUE(one(r, 'deactivated')))) return null;
267
+ const own = annotations.flatMap((r) => values(r, 'severity')), texts = annotations.flatMap((r) => values(r, 'message'));
268
+ if (own.length > 1) error(s, 'has multiple reified sh:severity values for one constraint');
269
+ const level = own[0] ?? severity, cid = `'sh_c_${nextConstraint++}'`;
270
+ requireIri('severity', level);
271
+ lines.push(`fact(sh_constraint(${cid}, ${write(level)}));`);
272
+ for (const message of texts.length ? texts : messages) lines.push(`fact(sh_constraint_message(${cid}, ${write(message)}));`);
273
+ if (blocked.has(level.args[0])) lines.push(`fact(sh_blocking(${cid}));`);
274
+ return cid;
275
+ };
276
+ const emit = (cid, body, component, value = 'V', resultPath = P, key = NONE) => {
277
+ if (cid) lines.push(`implied_by(${issue}(F, ${resultPath}, ${value}, ${sh(component + 'ConstraintComponent')}, ${key}, ${cid}), [${body.join(', ')}]);`);
278
+ };
279
+ const each = (property, fn) => values(s, property).forEach((t) => fn(t, constraint([property, t])));
280
+ const scalar = (property, fn) => { const t = one(s, property); if (t !== undefined) fn(t, constraint([property, t])); };
281
+ const helper = (name) => `sh_${name}_${id}_${nextHelper++}`;
282
+ // A deactivation expression decides for each focus node.
283
+ const deactivated = one(s, 'deactivated'), guard = [];
284
+ if (deactivated !== undefined && !BOOL(deactivated)) {
285
+ lines.push(`implied_by(sh_inactive_${id}(F), ${expression(deactivated)}(F, [], nodes([${TRUE_TERM}])));`);
286
+ guard.push(`not(sh_inactive_${id}(F))`);
287
+ }
288
+ const all = (property, fn) => values(s, property).forEach(fn);
289
+ all('targetNode', (t) => lines.push(t instanceof Struct && t.name === 'bnode' ?
290
+ `implies([${expression(t)}('sh_none', [], nodes(L)), ent_member(T, L)], ${target}(T));` :
291
+ `fact(${target}(${write(t)}), ent_node(${write(t)}, ${G}));`));
292
+ all('targetClass', (t) => lines.push(`implies(sh_instance(F, ${requireIri('targetClass', t)}, ${G}), ${target}(F));`));
293
+ all('targetSubjectsOf', (t) => lines.push(`implies([rdf(F, ${requireIri('targetSubjectsOf', t)}, _, ${G}), ent_resource(F)], ${target}(F));`));
294
+ all('targetObjectsOf', (t) => lines.push(`implies([rdf(X, ${requireIri('targetObjectsOf', t)}, F, ${G}), ent_resource(X)], ${target}(F));`));
295
+ all('targetWhere', (t) => lines.push(`implies([sh_graph_node(F, ${G}), sh_ok_${shape(t).id}(F)], ${target}(F));`));
296
+ if (isClass(s)) {
297
+ if (!isIri(s)) error(s, 'is a shape and a class but not an IRI');
298
+ lines.push(`implies(sh_instance(F, ${S}, ${G}), ${target}(F));`);
169
299
  }
170
- each('targetNode', (t) => lines.push(`fact(${focus}(${write(t)}));`));
171
- each('targetClass', (t) => lines.push(`implies(sh_instance(F, ${requireIri('targetClass', t)}, ${G}), ${focus}(F));`));
172
- each('targetSubjectsOf', (t) => lines.push(`implies([rdf(F, ${requireIri('targetSubjectsOf', t)}, _, ${G}), ent_resource(F)], ${focus}(F));`));
173
- each('targetObjectsOf', (t) => lines.push(`implies([rdf(X, ${requireIri('targetObjectsOf', t)}, F, ${G}), ent_resource(X)], ${focus}(F));`));
174
- if (values(s, RDF + 'type').some((t) => t.args?.[0] === RDFS + 'Class')) lines.push(`implies(sh_instance(F, ${S}, ${G}), ${focus}(F));`);
175
- each('class', (t) => emit([`${v}(F, V)`, `not(sh_instance(V, ${requireIri('class', t)}, ${G}))`], 'Class', 'V', P, write(t)));
176
- scalar('datatype', (t) => {
177
- requireIri('datatype', t);
178
- if (!RDF_DATATYPES.has(t.args[0])) error(s, `uses unsupported datatype ${write(t)}`);
179
- emit([`${v}(F, V)`, `not(rv_valid_as(V, ${write(t)}))`], 'Datatype');
300
+ if (isIri(s)) lines.push(`implies(rdf(F, ${sh('shape')}, ${S}, ${G}), ${target}(F));`);
301
+ lines.push(`implies(${target}(F), ${focus}(F, 'sh_target'));`);
302
+ each('class', (t, c) => {
303
+ const member = helper('class');
304
+ for (const type of iris(s, 'class', t)) lines.push(`implied_by(${member}(V), sh_instance(V, ${write(type)}, ${G}));`);
305
+ emit(c, [`${v}(F, V)`, `not(${member}(V))`], 'Class', 'V', P, write(t));
180
306
  });
181
- scalar('nodeKind', (t) => {
182
- if (!['IRI', 'BlankNode', 'Literal', 'BlankNodeOrIRI', 'BlankNodeOrLiteral', 'IRIOrLiteral'].some((n) => t.args?.[0] === SH + n)) error(s, 'has an unsupported sh:nodeKind');
183
- emit([`${v}(F, V)`, `not(sh_kind(V, ${write(t)}))`], 'NodeKind');
307
+ scalar('datatype', (t, c) => {
308
+ const member = helper('datatype');
309
+ for (const type of iris(s, 'datatype', t)) lines.push(RDF_DATATYPES.has(type.args[0]) ?
310
+ `implied_by(${member}(V), rv_valid_as(V, ${write(type)}));` :
311
+ `fact(${member}(literal(_, datatype(${JSON.stringify(type.args[0])}))));`);
312
+ emit(c, [`${v}(F, V)`, `not(${member}(V))`], 'Datatype');
313
+ });
314
+ scalar('nodeKind', (t, c) => {
315
+ const kinds = iris(s, 'nodeKind', t), allowed = isIri(t) ? ['IRI', 'BlankNode', 'Literal', 'BlankNodeOrIRI', 'BlankNodeOrLiteral', 'IRIOrLiteral', 'TripleTerm'] : ['IRI', 'BlankNode', 'Literal', 'TripleTerm'];
316
+ if (!kinds.every((k) => allowed.some((n) => k.args[0] === SH + n))) error(s, 'has an unsupported sh:nodeKind');
317
+ const member = helper('kind');
318
+ for (const kind of kinds) lines.push(`implied_by(${member}(V), sh_kind(V, ${write(kind)}));`);
319
+ emit(c, [`${v}(F, V)`, `not(${member}(V))`], 'NodeKind');
184
320
  });
185
321
  const collected = [`findall_sorted(V, ${v}(F, V), Values)`, 'ent_count(Values, N)'];
186
- for (const [name, cmp] of [['minCount', 'lt'], ['maxCount', 'gt']]) scalar(name, (t) => {
322
+ for (const [name, cmp] of [['minCount', 'lt'], ['maxCount', 'gt']]) scalar(name, (t, c) => {
187
323
  if (!p) error(s, `uses sh:${name} without a property path`);
188
- emit([...collected, `${cmp}(N, ${integer(name, t)})`], name[0].toUpperCase() + name.slice(1), NONE);
324
+ emit(c, [...collected, `${cmp}(N, ${integer(name, t)})`], name[0].toUpperCase() + name.slice(1), NONE);
189
325
  });
190
- for (const [name, signs] of [['minExclusive', ['>']], ['minInclusive', ['>', '=']], ['maxExclusive', ['<']], ['maxInclusive', ['<', '=']]]) scalar(name, (t) => {
191
- const suffix = `sh_bound_${id}_${name}`;
192
- for (const sign of signs) lines.push(`implied_by(${suffix}(V), rv_order(V, ${write(t)}, '${sign}'));`);
193
- emit([`${v}(F, V)`, `not(${suffix}(V))`], name[0].toUpperCase() + name.slice(1));
326
+ for (const [name, signs] of [['minExclusive', ['>']], ['minInclusive', ['>', '=']], ['maxExclusive', ['<']], ['maxInclusive', ['<', '=']]]) scalar(name, (t, c) => {
327
+ const pass = helper('bound');
328
+ for (const sign of signs) lines.push(`implied_by(${pass}(V), rv_order(V, ${write(t)}, '${sign}'));`);
329
+ emit(c, [`${v}(F, V)`, `not(${pass}(V))`], name[0].toUpperCase() + name.slice(1));
194
330
  });
195
- for (const [name, cmp] of [['minLength', 'lt'], ['maxLength', 'gt']]) scalar(name, (t) => {
196
- const limit = integer(name, t), pass = `sh_length_${id}_${name}`;
331
+ for (const [name, cmp] of [['minLength', 'lt'], ['maxLength', 'gt']]) scalar(name, (t, c) => {
332
+ const limit = integer(name, t), pass = helper('length');
197
333
  lines.push(`implied_by(${pass}(V), [sh_string(V, Text), atom_length(Text, N), not(${cmp}(N, ${limit}))]);`);
198
- emit([`${v}(F, V)`, `not(${pass}(V))`], name[0].toUpperCase() + name.slice(1));
334
+ emit(c, [`${v}(F, V)`, `not(${pass}(V))`], name[0].toUpperCase() + name.slice(1));
199
335
  });
200
- scalar('pattern', (t) => {
201
- if (t.name !== 'literal' || t.args[1]?.args[0] !== XSD + 'string') error(s, 'needs an xsd:string sh:pattern');
336
+ scalar('pattern', (t, c) => {
337
+ if (!literal(t, XSD + 'string')) error(s, 'needs an xsd:string sh:pattern');
202
338
  const flags = one(s, 'flags');
203
- if (flags && (flags.name !== 'literal' || flags.args[1]?.args[0] !== XSD + 'string' || /[^imsx]/.test(flags.args[0]))) error(s, 'has unsupported sh:flags');
339
+ if (flags && (!literal(flags, XSD + 'string') || /[^imsx]/.test(flags.args[0]))) error(s, 'has unsupported sh:flags');
204
340
  let expression = t.args[0];
205
341
  // The LS regex primitive uses ECMAScript Unicode syntax. Translate the
206
342
  // portable SHACL flags at compilation, without executing input patterns.
@@ -210,59 +346,90 @@ export function compileShacl(quads) {
210
346
  if (f.includes('m')) error(s, 'uses sh:flags m, which is not supported by the LS regex primitive');
211
347
  if (f.includes('i')) expression = caseInsensitivePattern(expression);
212
348
  try { new RegExp(expression, 'u'); } catch { error(s, 'has an invalid or unsupported regular expression'); }
213
- emit([`${v}(F, V)`, `not(sh_pattern(V, ${JSON.stringify(expression)}))`], 'Pattern');
349
+ emit(c, [`${v}(F, V)`, `not(sh_pattern(V, ${JSON.stringify(expression)}))`], 'Pattern');
350
+ });
351
+ scalar('singleLine', (t, c) => {
352
+ if (boolean('singleLine', t)) emit(c, [`${v}(F, V)`, 'rv_literal(V)', 'sh_string(V, Text)', `regex_match(${JSON.stringify('[\n\u000b\f\r]')}, Text)`], 'SingleLine');
214
353
  });
215
- scalar('languageIn', (t) => {
216
- const tags = rdfList(t);
217
- const allowed = `sh_language_${id}`;
218
- for (const tag of tags) {
219
- if (tag.name !== 'literal' || tag.args[1]?.args[0] !== XSD + 'string') error(s, 'needs strings in sh:languageIn');
354
+ scalar('languageIn', (t, c) => {
355
+ const allowed = helper('language');
356
+ for (const tag of rdfList(t)) {
357
+ if (!literal(tag, XSD + 'string')) error(s, 'needs strings in sh:languageIn');
220
358
  lines.push(`implied_by(${allowed}(V), [sh_language(V, L), sh_language_matches(L, ${JSON.stringify(tag.args[0].toLowerCase())})]);`);
221
359
  }
222
- emit([`${v}(F, V)`, `not(${allowed}(V))`], 'LanguageIn');
360
+ emit(c, [`${v}(F, V)`, `not(${allowed}(V))`], 'LanguageIn');
223
361
  });
224
- scalar('uniqueLang', (t) => {
362
+ scalar('uniqueLang', (t, c) => {
225
363
  if (!p) error(s, 'uses sh:uniqueLang without a property path');
226
- if (boolean('uniqueLang', t)) emit([`${v}(F, V)`, `${v}(F, W)`, 'not_identical(V, W)', 'sh_language(V, L)', 'sh_language(W, L)'], 'UniqueLang', NONE, P, 'L');
364
+ if (boolean('uniqueLang', t)) emit(c, [`${v}(F, V)`, `${v}(F, W)`, 'not_identical(V, W)', 'sh_language_key(V, L)', 'sh_language_key(W, L)'], 'UniqueLang', NONE, P, 'L');
227
365
  });
228
- scalar('in', (t) => {
229
- const allowed = `sh_in_${id}`;
366
+ // List constraints read SHACL lists of the data graph; any other value node is a result.
367
+ const lists = (name, c, body) => {
368
+ emit(c, [`${v}(F, V)`, `not(sh_list(V, _, ${G}))`], name);
369
+ emit(c, [`${v}(F, V)`, `sh_list(V, Members, ${G})`, ...body], name);
370
+ };
371
+ each('memberShape', (t, c) => lists('MemberShape', c, ['ent_member(M, Members)', `not(sh_ok_${shape(t).id}(M))`]));
372
+ for (const [name, cmp] of [['minListLength', 'lt'], ['maxListLength', 'gt']]) scalar(name, (t, c) =>
373
+ lists(name[0].toUpperCase() + name.slice(1), c, ['ent_count(Members, N)', `${cmp}(N, ${integer(name, t)})`]));
374
+ scalar('uniqueMembers', (t, c) => { if (boolean('uniqueMembers', t)) lists('UniqueMembers', c, ['sh_duplicate(Members)']); });
375
+ scalar('in', (t, c) => {
376
+ const allowed = helper('in');
230
377
  for (const item of rdfList(t)) lines.push(`fact(${allowed}(${write(item)}));`);
231
- emit([`${v}(F, V)`, `not(${allowed}(V))`], 'In');
378
+ emit(c, [`${v}(F, V)`, `not(${allowed}(V))`], 'In');
379
+ });
380
+ each('hasValue', (t, c) => emit(c, [`not(${v}(F, ${write(t)}))`], 'HasValue', NONE, P, write(t)));
381
+ each('rootClass', (t, c) => {
382
+ const member = helper('root');
383
+ for (const root of iris(s, 'rootClass', t)) {
384
+ lines.push(`fact(${member}(${write(root)}));`);
385
+ lines.push(`implied_by(${member}(V), sh_subclass(V, ${write(root)}, ${G}));`);
386
+ }
387
+ emit(c, [`${v}(F, V)`, 'not(unify(V, iri(_)))'], 'RootClass', 'V', P, write(t));
388
+ emit(c, [`${v}(F, V)`, 'unify(V, iri(_))', `not(${member}(V))`], 'RootClass', 'V', P, write(t));
232
389
  });
233
- each('hasValue', (t) => emit([`ent_node(F, ${G})`, `not(${v}(F, ${write(t)}))`], 'HasValue', NONE, P, write(t)));
234
- for (const name of ['equals', 'disjoint', 'lessThan', 'lessThanOrEquals']) scalar(name, (t) => {
235
- const other = requireIri(name, t), component = name[0].toUpperCase() + name.slice(1);
390
+ // Property pairs compare the value nodes with the nodes of another path.
391
+ for (const name of ['equals', 'disjoint', 'subsetOf', 'lessThan', 'lessThanOrEquals']) each(name, (t, c) => {
392
+ const other = path(t), component = name[0].toUpperCase() + name.slice(1);
393
+ if (name.startsWith('lessThan') && !p) error(s, `uses sh:${name} without a property path`);
236
394
  if (name === 'equals') {
237
- emit([`${v}(F, V)`, `not(rdf(F, ${other}, V, ${G}))`], component);
238
- emit([`rdf(F, ${other}, V, ${G})`, `ent_resource(F)`, `not(${v}(F, V))`], component);
239
- } else if (name === 'disjoint') emit([`${v}(F, V)`, `rdf(F, ${other}, V, ${G})`], component);
395
+ emit(c, [`${v}(F, V)`, `not(${other}(F, V))`], component, 'V', P, write(t));
396
+ emit(c, [`${other}(F, V)`, `not(${v}(F, V))`], component, 'V', P, write(t));
397
+ } else if (name === 'disjoint') emit(c, [`${v}(F, V)`, `${other}(F, V)`], component, 'V', P, write(t));
398
+ else if (name === 'subsetOf') emit(c, [`${v}(F, V)`, `not(${other}(F, V))`], component, 'V', P, write(t));
240
399
  else {
241
- const ordered = `sh_pair_${id}_${name}`;
400
+ // Each value node and other node that do not compare is its own result.
401
+ const ordered = helper('pair');
242
402
  lines.push(`implied_by(${ordered}(V, W), rv_order(V, W, '<'));`);
243
403
  if (name === 'lessThanOrEquals') lines.push(`implied_by(${ordered}(V, W), rv_order(V, W, '='));`);
244
- emit([`${v}(F, V)`, `rdf(F, ${other}, W, ${G})`, `not(${ordered}(V, W))`], component);
404
+ emit(c, [`${v}(F, V)`, `${other}(F, W)`, `not(${ordered}(V, W))`], component, 'V', P, `k(${write(t)}, W)`);
245
405
  }
246
406
  });
247
407
  for (const child of node.properties) {
248
408
  if (!child.inactive && !one(child.term, 'path')) error(child.term, 'is referenced by sh:property without sh:path');
249
- lines.push(`implied_by(${bad}(F), [${v}(F, V), not(sh_ok_${child.id}(V))]);`);
250
- if (!child.inactive) lines.push(`implies([${focus}(F), ${v}(F, V)], sh_focus_${child.id}(V));`);
409
+ if (!constraint(['property', child.term])) continue;
410
+ lines.push(`implied_by(${bad}(F), [${v}(F, V), not(sh_ok_${child.id}(V))${guard.map((g) => ', ' + g).join('')}]);`);
411
+ if (!child.inactive) lines.push(`implies([${focus}(F, X), ${v}(F, V)${guard.map((g) => ', ' + g).join('')}], sh_focus_${child.id}(V, sh_via(${id}, F, X)));`);
251
412
  }
252
- each('node', (t) => emit([`${v}(F, V)`, `not(sh_ok_${shape(t).id}(V))`], 'Node', 'V', P, write(t)));
253
- each('not', (t) => emit([`${v}(F, V)`, `sh_ok_${shape(t).id}(V)`], 'Not', 'V', P, write(t)));
413
+ each('node', (t, c) => emit(c, [`${v}(F, V)`, `not(sh_ok_${shape(t).id}(V))`], 'Node', 'V', P, write(t)));
414
+ each('not', (t, c) => emit(c, [`${v}(F, V)`, `sh_ok_${shape(t).id}(V)`], 'Not', 'V', P, write(t)));
415
+ each('someValue', (t, c) => {
416
+ const some = helper('some');
417
+ lines.push(`implied_by(${some}(F), [${v}(F, V), sh_ok_${shape(t).id}(V)]);`);
418
+ emit(c, [`not(${some}(F))`], 'SomeValue', NONE, P, write(t));
419
+ });
254
420
  for (const [name, children] of node.lists) {
255
- if (name === 'and') for (const child of children) emit([`${v}(F, V)`, `not(sh_ok_${child.id}(V))`], 'And');
256
- if (name === 'or') emit([`${v}(F, V)`, ...children.map((child) => `not(sh_ok_${child.id}(V))`)], 'Or');
421
+ const c = constraint([name, one(s, name)]);
422
+ if (name === 'and') for (const child of children) emit(c, [`${v}(F, V)`, `not(sh_ok_${child.id}(V))`], 'And');
423
+ if (name === 'or') emit(c, [`${v}(F, V)`, ...children.map((child) => `not(sh_ok_${child.id}(V))`)], 'Or');
257
424
  if (name === 'xone') {
258
- const match = `sh_xone_${id}`;
425
+ const match = helper('xone');
259
426
  children.forEach((child, i) => lines.push(`implied_by(${match}(V, ${i}), sh_ok_${child.id}(V));`));
260
- emit([`${v}(F, V)`, `findall_sorted(I, ${match}(V, I), Matches)`, 'ent_count(Matches, N)', 'ne(N, 1)'], 'Xone');
427
+ emit(c, [`${v}(F, V)`, `findall_sorted(I, ${match}(V, I), Matches)`, 'ent_count(Matches, N)', 'ne(N, 1)'], 'Xone');
261
428
  }
262
429
  }
263
430
  const qualified = one(s, 'qualifiedValueShape');
264
431
  if (qualified) {
265
- const child = shape(qualified), match = `sh_qualified_${id}`, siblings = new Map();
432
+ const child = shape(qualified), match = helper('qualified'), siblings = new Map();
266
433
  const disjoint = one(s, 'qualifiedValueShapesDisjoint');
267
434
  if (disjoint && boolean('qualifiedValueShapesDisjoint', disjoint)) for (const parent of shapes.values()) if (parent.properties.includes(node)) {
268
435
  for (const sibling of parent.properties) if (sibling !== node) {
@@ -271,21 +438,64 @@ export function compileShacl(quads) {
271
438
  }
272
439
  }
273
440
  lines.push(`implied_by(${match}(F, V), [${v}(F, V), sh_ok_${child.id}(V)${[...siblings.values()].map((sib) => `, not(sh_ok_${sib.id}(V))`).join('')}]);`);
274
- for (const [name, cmp] of [['qualifiedMinCount', 'lt'], ['qualifiedMaxCount', 'gt']]) scalar(name, (t) => {
441
+ for (const [name, cmp] of [['qualifiedMinCount', 'lt'], ['qualifiedMaxCount', 'gt']]) {
442
+ const t = one(s, name);
443
+ if (t === undefined) continue;
275
444
  if (!p) error(s, `uses sh:${name} without a property path`);
276
- emit([`findall_sorted(V, ${match}(F, V), Matches)`, 'ent_count(Matches, N)', `${cmp}(N, ${integer(name, t)})`], name[0].toUpperCase() + name.slice(1), NONE);
277
- });
278
- } else if (one(s, 'qualifiedMinCount') !== undefined || one(s, 'qualifiedMaxCount') !== undefined) error(s, 'has qualified counts without sh:qualifiedValueShape');
279
- scalar('closed', (t) => {
280
- if (!boolean('closed', t)) return;
281
- const allowed = `sh_closed_${id}`, ignored = one(s, 'ignoredProperties');
282
- const predicates = [...node.properties.map((child) => one(child.term, 'path')).filter(isIri), ...(ignored ? rdfList(ignored) : [])];
283
- for (const property of predicates) lines.push(`fact(${allowed}(${requireIri('ignoredProperties', property)}));`);
284
- emit([`${v}(F, X)`, 'ent_resource(X)', `rdf(X, Predicate, V, ${G})`, `not(${allowed}(Predicate))`], 'Closed', 'V', 'Predicate', 'X');
445
+ emit(constraint(['qualifiedValueShape', qualified], [name, t]), [`findall_sorted(V, ${match}(F, V), Matches)`, 'ent_count(Matches, N)', `${cmp}(N, ${integer(name, t)})`], name[0].toUpperCase() + name.slice(1), NONE);
446
+ }
447
+ }
448
+ // Each reifier of a value triple must conform; sh:reificationRequired needs one.
449
+ each('reifierShape', (t, c) => {
450
+ if (!p || !isIri(p)) error(s, 'uses sh:reifierShape without an IRI sh:path');
451
+ emit(c, [`${v}(F, V)`, `rdf(R, ${iri(RDF + 'reifies')}, triple(F, ${P}, V), ${G})`, `not(sh_ok_${shape(t).id}(R))`], 'ReifierShape', 'V', P, 'R');
452
+ const required = one(s, 'reificationRequired');
453
+ if (required !== undefined && boolean('reificationRequired', required))
454
+ emit(constraint(['reifierShape', t], ['reificationRequired', required]), [`${v}(F, V)`, `not(rdf(_, ${iri(RDF + 'reifies')}, triple(F, ${P}, V), ${G}))`], 'ReifierShape');
285
455
  });
286
- lines.push(`implied_by(${bad}(F), ${issue}(F, _, _, _, _));`);
456
+ each('uniqueValuesFor', (t, c) => {
457
+ const properties = isIri(t) ? [t] : rdfList(t);
458
+ if (!properties.length || !properties.every(isIri)) error(s, 'needs an IRI or a list of IRIs as sh:uniqueValuesFor');
459
+ const key = helper('key'), duplicate = helper('duplicate');
460
+ lines.push(`implied_by(${key}(V, [${properties.map((_, i) => 'L' + i).join(', ')}]), [${properties.map((q, i) => `findall_sorted(X, rdf(V, ${write(q)}, X, ${G}), L${i})`).join(', ')}]);`);
461
+ lines.push(`implied_by(${duplicate}(V), [${key}(V, K), not(unify(K, [${properties.map(() => '[]').join(', ')}])), ${target}(T), not_identical(T, V), ${key}(T, K)]);`);
462
+ emit(c, [`${v}(F, V)`, `${duplicate}(V)`], 'UniqueValuesFor', NONE, P, 'V');
463
+ });
464
+ // sh:expression must give exactly true for each value node, bound to value.
465
+ // A blank node expression is copied into the report as sh:sourceConstraint.
466
+ const copy = (root, term = root, seen = new Set()) => {
467
+ if (!(term instanceof Struct && term.name === 'bnode') || seen.has(write(term))) return;
468
+ seen.add(write(term));
469
+ for (const [predicate, objects] of index.get(write(term)) ?? []) for (const object of objects) {
470
+ lines.push(`fact(sh_copy(${write(root)}, ${write(term)}, ${iri(predicate)}, ${write(object)}, ${G}));`);
471
+ copy(root, object, seen);
472
+ }
473
+ };
474
+ values(s, 'expression').forEach((t) => copy(t));
475
+ each('expression', (t, c) => emit(c, [`${v}(F, V)`, `${expression(t)}(F, [['value', V]], R)`, `not(unify(R, nodes([${TRUE_TERM}])))`],
476
+ '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))'],
478
+ 'NodeByExpression', 'V', P, 'source(Shape)'));
479
+ scalar('closed', (t, c) => {
480
+ const types = isIri(t) && t.args[0] === SH + 'ByTypes';
481
+ if (!types && !boolean('closed', t)) return;
482
+ const allowed = helper('closed'), ignored = one(s, 'ignoredProperties');
483
+ const predicates = [...(types ? [] : node.properties.map((child) => one(child.term, 'path')).filter(isIri)), ...(ignored ? rdfList(ignored) : [])];
484
+ for (const property of predicates) lines.push(`fact(${allowed}(_, ${requireIri('ignoredProperties', property)}));`);
485
+ if (types) {
486
+ lines.push(`fact(${allowed}(_, ${iri(RDF + 'type')}));`);
487
+ lines.push(`implied_by(${allowed}(X, P), [rdf(X, ${iri(RDF + 'type')}, T, ${G}), ${closedByTypes()}(T, P, ${G})]);`);
488
+ }
489
+ emit(c, [`${v}(F, X)`, 'ent_resource(X)', `rdf(X, Predicate, V, ${G})`, `not(${allowed}(X, Predicate))`], 'Closed', 'V', 'Predicate', 'X');
490
+ });
491
+ lines.push(`implied_by(${bad}(F), [${issue}(F, _, _, _, _, C), sh_blocking(C)${guard.map((g) => ', ' + g).join('')}]);`);
287
492
  lines.push(`implied_by(${ok}(F), not(${bad}(F)));`);
288
- lines.push(`implies([${focus}(F), ${issue}(F, P, V, C, K)], sh_violation(${S}, F, P, V, C, K, ${G}));`);
493
+ 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));`);
495
+ }
496
+ if (evaluate && G === "'default_graph'") {
497
+ const scope = [...evaluate.scope ?? []].map(([k, t]) => `[${JSON.stringify(k)}, ${write(t)}]`);
498
+ lines.push(`implied_by(sh_evaluation(R), ${expression(evaluate.expression)}(${evaluate.focus ? write(evaluate.focus) : "'sh_none'"}, [${scope.join(', ')}], R));`);
289
499
  }
290
500
  }
291
501
  return lines.join('\n') + '\n';
@@ -344,8 +554,13 @@ const shR = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#';
344
554
  const shX = 'http://www.w3.org/2001/XMLSchema#';
345
555
  implies([rdf(X, iri(shR + 'type'), C, G), ent_resource(X)], sh_instance(X, C, G));
346
556
  implies([sh_instance(X, C, G), rdf(C, iri('http://www.w3.org/2000/01/rdf-schema#subClassOf'), D, G)], sh_instance(X, D, G));
557
+ implies(rdf(C, iri('http://www.w3.org/2000/01/rdf-schema#subClassOf'), D, G), sh_subclass(C, D, G));
558
+ implies([sh_subclass(C, D, G), rdf(D, iri('http://www.w3.org/2000/01/rdf-schema#subClassOf'), E, G)], sh_subclass(C, E, G));
559
+ // The nodes of a data graph are its subjects and objects.
560
+ implies(rdf(S, _, O, G), [sh_graph_node(S, G), sh_graph_node(O, G)]);
347
561
  fact(sh_kind(iri(_), iri(shN + 'IRI')));
348
562
  fact(sh_kind(bnode(_, _), iri(shN + 'BlankNode')), sh_kind(skolem(_, _, _), iri(shN + 'BlankNode')));
563
+ fact(sh_kind(triple(_, _, _), iri(shN + 'TripleTerm')));
349
564
  implied_by(sh_kind(T, iri(shN + 'Literal')), rv_literal(T));
350
565
  for (const [kind, left, right] of [['BlankNodeOrIRI', 'BlankNode', 'IRI'], ['BlankNodeOrLiteral', 'BlankNode', 'Literal'], ['IRIOrLiteral', 'IRI', 'Literal']]) {
351
566
  implied_by(sh_kind(T, iri(shN + kind)), sh_kind(T, iri(shN + left)));
@@ -356,23 +571,37 @@ implied_by(sh_string(T, S), [rv_literal(T), srl_str(T, literal(S, datatype(shX +
356
571
  implied_by(sh_pattern(T, Pattern), [sh_string(T, Text), regex_match(Pattern, Text)]);
357
572
  implied_by(sh_language(literal(_, lang(L)), Tag), atom_lower(L, Tag));
358
573
  implied_by(sh_language(literal(_, lang(L, _)), Tag), atom_lower(L, Tag));
574
+ // sh:uniqueLang distinguishes a base direction as part of the language tag.
575
+ implied_by(sh_language_key(literal(_, lang(L)), Tag), atom_lower(L, Tag));
576
+ implied_by(sh_language_key(literal(_, lang(L, D)), tag(Tag, D)), atom_lower(L, Tag));
359
577
  implied_by(sh_language_matches(L, '*'), ne(L, ''));
360
578
  fact(sh_language_matches(L, L));
361
579
  implied_by(sh_language_matches(L, Prefix), [atom_concat(Prefix, '-', P), atom_concat(P, _, L)]);
362
- // One report per graph, with conformance decided from the completed violation set.
580
+ // SHACL lists grow from rdf:nil, so a cycle or a branching cell never forms one.
581
+ implies([ent_graph(G), not(rdf(iri(shR + 'nil'), iri(shR + 'first'), _, G)), not(rdf(iri(shR + 'nil'), iri(shR + 'rest'), _, G))], sh_list(iri(shR + 'nil'), [], G));
582
+ implies([sh_list(R, Members, G), rdf(L, iri(shR + 'rest'), R, G), ent_resource(L), findall(Y, rdf(L, iri(shR + 'rest'), Y, G), [_]),
583
+ findall(X, rdf(L, iri(shR + 'first'), X, G), [X])], sh_list(L, [X, ...Members], G));
584
+ implied_by(sh_duplicate([X, ...T]), ent_member(X, T));
585
+ implied_by(sh_duplicate([_, ...T]), sh_duplicate(T));
586
+ fact(sh_blocking('sh_none'));
587
+ // One report per graph, with conformance decided from the completed results
588
+ // whose severity is in the conformance-disallow set.
363
589
  implies(ent_graph(G), sh_report(Report, G));
364
- implied_by(sh_any(G), sh_violation(_, _, _, _, _, _, G));
590
+ implied_by(sh_any(G), [sh_violation(_, _, _, _, _, _, I, _, G), sh_constraint(I, Severity), sh_disallowed(Severity)]);
365
591
  implies(sh_report(Report, G), ent_report(Report, iri(shR + 'type'), iri(shN + 'ValidationReport'), G));
366
592
  implies([sh_report(Report, G), not(sh_any(G))], ent_report(Report, iri(shN + 'conforms'), literal('true', datatype(shX + 'boolean')), G));
367
593
  implies([sh_report(Report, G), sh_any(G)], ent_report(Report, iri(shN + 'conforms'), literal('false', datatype(shX + 'boolean')), G));
368
- implies(sh_violation(S, F, P, V, C, K, G), sh_result(Result, S, F, P, V, C, K, G));
369
- implies([sh_result(Result, S, F, P, V, C, K, G), sh_report(Report, G), sh_severity(S, Severity, G)], [
594
+ implies([sh_report(Report, G), sh_custom_disallows, sh_disallowed(Severity)], ent_report(Report, iri(shN + 'conformanceDisallows'), Severity, G));
595
+ implies(sh_violation(S, F, P, V, C, K, I, X, G), sh_result(Result, S, F, P, V, C, K, I, X, G));
596
+ implies([sh_result(Result, S, F, P, V, C, K, I, X, G), sh_report(Report, G), sh_constraint(I, Severity)], [
370
597
  ent_report(Report, iri(shN + 'result'), Result, G), ent_report(Result, iri(shR + 'type'), iri(shN + 'ValidationResult'), G),
371
598
  ent_report(Result, iri(shN + 'focusNode'), F, G), ent_report(Result, iri(shN + 'sourceShape'), S, G),
372
599
  ent_report(Result, iri(shN + 'sourceConstraintComponent'), C, G), ent_report(Result, iri(shN + 'resultSeverity'), Severity, G)
373
600
  ]);
374
- implies([sh_result(R, S, F, P, V, C, K, G), not_identical(P, 'sh_none')], ent_report(R, iri(shN + 'resultPath'), P, G));
375
- implies([sh_result(R, S, F, P, V, C, K, G), not_identical(V, 'sh_none')], ent_report(R, iri(shN + 'value'), V, G));
376
- implies([sh_result(R, S, F, P, V, C, K, G), sh_message(S, Message, G)], ent_report(R, iri(shN + 'resultMessage'), Message, G));
377
- implies([sh_result(_, _, _, Path, _, _, _, G), sh_path_statement(Path, S, P, O, G)], ent_report(S, P, O, G));
601
+ implies([sh_result(R, S, F, P, V, C, K, I, X, G), not_identical(P, 'sh_none')], ent_report(R, iri(shN + 'resultPath'), P, G));
602
+ implies([sh_result(R, S, F, P, V, C, K, I, X, G), not_identical(V, 'sh_none')], ent_report(R, iri(shN + 'value'), V, G));
603
+ implies([sh_result(R, S, F, P, V, C, K, I, X, G), sh_constraint_message(I, Message)], ent_report(R, iri(shN + 'resultMessage'), Message, G));
604
+ implies([sh_result(_, _, _, Path, _, _, _, _, _, G), sh_path_statement(Path, S, P, O, G)], ent_report(S, P, O, G));
605
+ implies(sh_result(R, _, _, _, _, _, source(T), _, _, G), ent_report(R, iri(shN + 'sourceConstraint'), T, G));
606
+ implies([sh_result(_, _, _, _, _, _, source(T), _, _, G), sh_copy(T, S, P, O, G)], ent_report(S, P, O, G));
378
607
  `;