eyemind 0.8.0 → 0.8.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/README.md CHANGED
@@ -605,24 +605,38 @@ records carrying focus node, source shape, constraint component and severity,
605
605
  plus path, value and supplied messages where applicable. Complex result
606
606
  paths retain their RDF definitions in the report.
607
607
 
608
- Implemented SHACL Core families include all four explicit targets and
609
- implicit class targets; class, datatype and node-kind constraints; counts,
610
- bounds, lengths, patterns and language constraints; sets, property pairs and
611
- closed shapes; nested properties, node/not/and/or/xone, and qualified counts
612
- with disjoint siblings. Predicate, inverse, sequence, alternative and repeated
613
- paths compute distinct values and terminate on data cycles. Repeated `xone`
614
- members count separately. Deactivated shapes conform without validation.
615
-
616
- This is a documented Core subset, not a claim of full W3C SHACL conformance.
608
+ SHACL 1.2 Core is implemented: node, class, subjects-of, objects-of and where
609
+ targets, `sh:shape` links in the data, and implicit class targets including
610
+ `sh:ShapeClass`; class, datatype, node-kind and root-class constraints, each
611
+ also with a list of alternatives; counts, bounds, lengths, patterns, single
612
+ lines and language constraints; SHACL list members, lengths and uniqueness;
613
+ sets, unique values for targets, property pairs over any path, and closed
614
+ shapes, also `sh:ByTypes`; nested properties, node/not/and/or/xone,
615
+ `sh:someValue`, reifier shapes and qualified counts with disjoint siblings.
616
+ Constant `sh:values` and `sh:defaultValue` add value nodes. Predicate,
617
+ inverse, sequence, alternative and repeated paths compute distinct values and
618
+ terminate on data cycles. Repeated `xone` members count separately.
619
+
620
+ A reifier of a constraint triple can deactivate that constraint or give it its
621
+ own `sh:severity` and `sh:message`. Each validation of a focus node is a
622
+ separate result, so a nested shape reached by two routes reports twice, and
623
+ `sh:lessThan` reports each incomparable pair. Results whose severity is outside
624
+ the conformance-disallow set (`sh:Violation`, `sh:Warning` and `sh:Info` by
625
+ default) are reported but do not make a node or the report nonconforming; a
626
+ library caller can pass another set as `disallows`, which the report then
627
+ lists as `sh:conformanceDisallows`. Only the boolean `true` activates a
628
+ boolean parameter. Deactivated shapes conform without validation.
629
+
617
630
  Shapes and path definitions must be present in the input; inference may add
618
631
  data and targets, but cannot dynamically define new constraints. Recursive
619
- shape dependencies, SHACL-SPARQL, JavaScript constraints, rules, custom
620
- targets and SHACL 1.2 additions are rejected when used by active shapes.
632
+ shape dependencies, node expressions beyond constants, SHACL-SPARQL,
633
+ JavaScript constraints and rules are outside the implementation. Active
634
+ shapes with unsupported constraint predicates are rejected.
621
635
 
622
636
  Datatype checks support XSD integer subtypes, decimal, float/double, boolean,
623
637
  string/normalizedString/token/language/anyURI, hex/base64 binary,
624
- date/dateTime/dateTimeStamp/time and RDF language strings. Other requested
625
- datatypes raise an error. Numeric bounds use exact integers/decimals with
638
+ date/dateTime/dateTimeStamp/time and RDF language strings; a literal of
639
+ another datatype matches that datatype's IRI. Numeric bounds use exact integers/decimals with
626
640
  SPARQL promotion for binary floats; string and same-kind temporal bounds
627
641
  are also supported. Temporal fractions remain exact. Timezones compare
628
642
  when both values have one or both omit one; a mixed pair is incomparable.
@@ -637,6 +651,34 @@ errors instead of a conforming report.
637
651
  Try the [directory](https://eyereasoner.github.io/eyemind/examples/deck/people-shacl)
638
652
  and [normalized speed readings](https://eyereasoner.github.io/eyemind/examples/deck/measurement-shacl).
639
653
 
654
+ The [W3C SHACL 1.2 manifest](https://w3c.github.io/data-shapes/shacl12-test-suite/tests/manifest.ttl)
655
+ is scored on every `npm test`, including filtered runs. eyemind targets its
656
+ Core and node-expression groups; SHACL-SPARQL and inference rules are out of
657
+ scope and not scored. At upstream revision
658
+ `0ed3f9b4273c2debba0125a7ed5c9dc3cd4b741c`, **all 162 Core tests pass
659
+ complete-report comparison**. Node expressions beyond constants are not yet
660
+ implemented, so the 284 node-expression tests do not pass yet.
661
+
662
+ The two groups are reported separately in
663
+ [REPORT.md](REPORT.md) and [SHACL EARL](reports/w3c-shacl-earl.ttl). The runner
664
+ preserves separate data and shapes graphs, follows manifest includes and
665
+ compares complete top-level results, their multiplicity, messages and paths.
666
+ A matching conformance boolean alone is not a pass. Unimplemented processor
667
+ families are explicitly untested in EARL; attempted validation cases that
668
+ reject unsupported constraints or produce wrong reports are failed.
669
+
670
+ ```sh
671
+ node tools/shacltests.js
672
+ node tools/shacltests.js --json > /tmp/shacl-coverage.json
673
+ node tools/shacltests.js --strict
674
+ ```
675
+
676
+ The default scorer and `npm test` report SHACL coverage without making missing
677
+ support fail the release checks, as with the Notation3 scorer. `--strict` exits
678
+ with code 1 for any non-passing SHACL case. Broken manifests and missing test
679
+ resources always fail the run. These commands reuse the cached suite; an
680
+ optional suite directory can select a different copy.
681
+
640
682
  ### ODRL snapshots
641
683
 
642
684
  Use `--odrl` to add ODRL validation and evaluation to one Turtle file
@@ -1013,7 +1055,8 @@ EYEMIND_PROPERTY_SCALE=20 npm test -- -k properties # deeper generated tests
1013
1055
  node tools/update-examples.js # regenerate example artifacts after an intended change
1014
1056
  node tools/report.js # run the full suite and write REPORT.md
1015
1057
  node tools/notation3tests.js # the cached Notation3 suite
1016
- npm run sync # refresh all three upstream test suites
1058
+ node tools/shacltests.js # SHACL 1.2 coverage; --strict fails for missing support
1059
+ npm run sync # refresh all four upstream test suites
1017
1060
  node conformance/run.js --command "my-eyemind" # run the conformance suite against another implementation
1018
1061
  ```
1019
1062
 
@@ -1023,16 +1066,18 @@ A full `npm test` writes `REPORT.md` from the summary table it prints.
1023
1066
 
1024
1067
  Every `npm test` invocation, including a filtered run, also runs both cached
1025
1068
  W3C format suites and rewrites [reports/w3c-rdf-earl.ttl](reports/w3c-rdf-earl.ttl)
1026
- and [reports/w3c-sparql-rl-earl.ttl](reports/w3c-sparql-rl-earl.ttl).
1069
+ and [reports/w3c-sparql-rl-earl.ttl](reports/w3c-sparql-rl-earl.ttl). It also scores
1070
+ the Core and node-expression groups of the SHACL 1.2 manifest and writes
1071
+ [reports/w3c-shacl-earl.ttl](reports/w3c-shacl-earl.ttl).
1027
1072
  These [EARL](https://www.w3.org/TR/EARL10-Schema/) reports contain one
1028
1073
  assertion per manifest case, its actual outcome and diagnostic, the eyemind
1029
- version and the run date. A W3C failure makes the command fail. A negative
1074
+ version and the run date. An RDF or SRL failure makes the command fail; SHACL is reported as coverage. A negative
1030
1075
  syntax test passes when the parser rejects its input as required.
1031
1076
 
1032
1077
  The [upstream suites](test/UPSTREAM.md) live in Git-ignored `.cache/`.
1033
1078
  `npm test` reuses them without fetching. If the cache is missing or incomplete,
1034
1079
  it downloads the suites first; that first run needs Git and network access.
1035
- `npm run sync` explicitly refreshes all three suites and the Notation3 document
1080
+ `npm run sync` explicitly refreshes all four suites and the Notation3 document
1036
1081
  fixtures. Downloads and manifest resource checks finish before the cached
1037
1082
  suites are replaced; a failed refresh retains the old set. Upstream licensing
1038
1083
  and documentation stay with the cached files. The small tracked
@@ -1045,6 +1090,9 @@ Local Git checkouts can supply any of the sources:
1045
1090
  npm run sync -- --notation3tests /path/to/notation3tests --w3c-rdf /path/to/rdf-tests --w3c-sparql-rl /path/to/data-shapes
1046
1091
  ```
1047
1092
 
1093
+ The data-shapes checkout supplies both SRL and SHACL; `--w3c-shacl PATH` can
1094
+ select a separate checkout for SHACL.
1095
+
1048
1096
  `node tools/sync-notation3tests.js [UPSTREAM_CHECKOUT]` still refreshes only
1049
1097
  Notation3 in `.cache/`. Once cached, tests use saved documents with no network fallback;
1050
1098
  the scorer's `--live` option checks the current remote resources instead.
package/SPEC.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  ```text
4
4
  Title: The Logic Script (LS) Language and Proof Format
5
- Version: eyemind 0.8.0
5
+ Version: eyemind 0.8.1
6
6
  ```
7
7
 
8
8
  This document specifies Logic Script (LS): the syntax and meaning of its
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "eyemind",
3
- "version": "0.8.0",
3
+ "version": "0.8.1",
4
4
  "description": "A dependency-free Logic Script (LS) reasoner with forward and backward reasoning, checkable proofs, and RDF 1.2, Notation3 (N3) and SPARQL 1.2 RL (SRL) interoperability.",
5
5
  "type": "module",
6
6
  "main": "./src/index.js",
package/src/rdf-logic.js CHANGED
@@ -12,7 +12,7 @@ import { rdfValueRules } from './rdf-values.js';
12
12
  export const ENTAILMENT = 'https://eyereasoner.github.io/eyemind/entailment#';
13
13
  export const RDF_PROFILES = ['owl2rl', 'qudt', 'skos', 'shacl'];
14
14
 
15
- export function compileRdfLogic({ quads, prefixes }, { profiles, source = '<input>' }) {
15
+ export function compileRdfLogic({ quads, prefixes, shapes = quads }, { profiles, source = '<input>', disallows }) {
16
16
  quads = [...new Map(quads.map((q) => [q.map((t) => write(t)).join(' '), q])).values()];
17
17
  const selected = new Set(profiles);
18
18
  const text = `// Generated by eyemind from ${String(source).replace(/[\r\n\u2028\u2029]/g, ' ')}, with ${profiles.map((p) => '--' + p).join(' ')}.\n` +
@@ -24,7 +24,7 @@ export function compileRdfLogic({ quads, prefixes }, { profiles, source = '<inpu
24
24
  (selected.has('owl2rl') ? owl2rlRules : '') +
25
25
  (selected.has('skos') ? skosRules : '') +
26
26
  (selected.has('qudt') ? qudtRules : '') +
27
- (selected.has('shacl') ? compileShacl(quads) : '') + OUTPUT;
27
+ (selected.has('shacl') ? compileShacl(shapes, { disallows }) : '') + OUTPUT;
28
28
  return { kind: profiles[0], text, program: loadText(text, source),
29
29
  prefixes: { ...prefixes, ent: ENTAILMENT, ...(selected.has('skos') ? { skos: 'http://www.w3.org/2004/02/skos/core#' } : {}),
30
30
  ...(selected.has('qudt') ? { qconv: 'https://eyereasoner.github.io/eyemind/qudt#', qudt: 'http://qudt.org/schema/qudt/', unit: 'http://qudt.org/vocab/unit/' } : {}),
package/src/shacl.js CHANGED
@@ -1,7 +1,7 @@
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';
@@ -14,34 +14,52 @@ const uri = (u) => new Struct('iri', [u]);
14
14
  const iri = (u) => write(uri(u));
15
15
  const sh = (n) => iri(SH + n);
16
16
  const NONE = "'sh_none'";
17
- const TARGETS = ['targetNode', 'targetClass', 'targetSubjectsOf', 'targetObjectsOf'];
17
+ const TARGETS = ['targetNode', 'targetClass', 'targetSubjectsOf', 'targetObjectsOf', 'targetWhere'];
18
18
  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]);
19
+ 'maxExclusive', 'maxInclusive', 'minLength', 'maxLength', 'pattern', 'singleLine', 'languageIn', 'uniqueLang',
20
+ 'memberShape', 'minListLength', 'maxListLength', 'uniqueMembers', 'equals', 'disjoint', 'subsetOf', 'lessThan',
21
+ 'lessThanOrEquals', 'not', 'and', 'or', 'xone', 'node', 'property', 'someValue', 'qualifiedValueShape',
22
+ 'qualifiedMinCount', 'qualifiedMaxCount', 'qualifiedValueShapesDisjoint', 'reifierShape', 'reificationRequired',
23
+ 'closed', 'hasValue', 'in', 'rootClass', 'uniqueValuesFor'];
24
+ const ANNOTATIONS = ['severity', 'message', 'deactivated', 'name', 'description', 'order', 'group', 'defaultValue', 'unit',
25
+ 'intent', 'agentInstruction', 'codeIdentifier', 'codeType'];
26
+ const ALLOWED = new Set([...TARGETS, ...CONSTRAINTS, ...ANNOTATIONS, 'path', 'values', 'flags', 'ignoredProperties']);
27
+ // Shape-expecting parameters, whose values are compiled as shapes and checked for recursion.
28
+ const SHAPE_PARAMETERS = ['node', 'not', 'qualifiedValueShape', 'property', 'memberShape', 'reifierShape', 'someValue', 'targetWhere'];
29
+ const PATH_OPERATORS = ['inversePath', 'alternativePath', 'zeroOrMorePath', 'oneOrMorePath', 'zeroOrOnePath'];
30
+ // The default conformance-disallow set of SHACL 1.2.
31
+ export const SHACL_DISALLOWS = ['Violation', 'Warning', 'Info'].map((n) => SH + n);
32
+ const literal = (t, datatype) => t instanceof Struct && t.name === 'literal' && t.args[1]?.name === 'datatype' && t.args[1].args[0] === datatype;
33
+ const BOOL = (t) => literal(t, XSD + 'boolean') && ['true', 'false', '1', '0'].includes(t.args[0]);
34
+ // Only the boolean true activates a constraint; the suite reads "1" as not true.
35
+ const TRUE = (t) => literal(t, XSD + 'boolean') && t.args[0] === 'true';
26
36
  const isIri = (t) => t instanceof Struct && t.name === 'iri';
27
37
  const resource = (t) => t instanceof Struct && ['iri', 'bnode', 'triple'].includes(t.name);
38
+ const typeNames = (types) => types.map((t) => t.args?.[0]);
28
39
 
29
- export function compileShacl(quads) {
30
- const graphs = new Map(), lines = [COMMON];
40
+ export function compileShacl(quads, { disallows = SHACL_DISALLOWS } = {}) {
41
+ const graphs = new Map(), lines = [COMMON], blocked = new Set(disallows);
42
+ for (const severity of disallows) lines.push(`fact(sh_disallowed(${iri(severity)}));`);
43
+ if (disallows.length !== SHACL_DISALLOWS.length || disallows.some((d) => !SHACL_DISALLOWS.includes(d)))
44
+ lines.push('fact(sh_custom_disallows);');
31
45
  for (const [s, p, o, g] of quads) {
32
46
  const key = write(g);
33
47
  if (!graphs.has(key)) graphs.set(key, { graph: g, triples: [] });
34
48
  graphs.get(key).triples.push([s, p, o]);
35
49
  }
36
- let nextShape = 0, nextPath = 0;
50
+ let nextShape = 0, nextPath = 0, nextConstraint = 0, nextHelper = 0;
37
51
  for (const { graph, triples } of graphs.values()) {
38
- const G = write(graph), index = new Map(), subjects = new Map();
52
+ const G = write(graph), index = new Map(), terms = new Map(), reifiers = new Map();
39
53
  for (const [s, p, o] of triples) {
40
54
  const key = write(s);
41
- if (!index.has(key)) { index.set(key, new Map()); subjects.set(key, s); }
55
+ if (!index.has(key)) { index.set(key, new Map()); terms.set(key, s); }
42
56
  const properties = index.get(key), name = p.args[0];
43
57
  if (!properties.has(name)) properties.set(name, []);
44
58
  if (!properties.get(name).some((v) => write(v) === write(o))) properties.get(name).push(o);
59
+ if (name === RDF + 'reifies' && o instanceof Struct && o.name === 'triple') {
60
+ if (!reifiers.has(write(o))) reifiers.set(write(o), []);
61
+ reifiers.get(write(o)).push(s);
62
+ }
45
63
  }
46
64
  const values = (s, p) => index.get(write(s))?.get(p.startsWith('http') ? p : SH + p) ?? [];
47
65
  const error = (s, message) => { throw new EyemindError(`--shacl: ${write(s)} ${message}`); };
@@ -62,17 +80,26 @@ export function compileShacl(quads) {
62
80
  }
63
81
  return items;
64
82
  };
83
+ // sh:class, sh:datatype, sh:nodeKind and sh:rootClass take an IRI or a list of IRIs.
84
+ const iris = (s, property, t) => {
85
+ const items = isIri(t) ? [t] : t.name === 'bnode' ? rdfList(t) : [];
86
+ if (!items.length || !items.every(isIri)) error(s, `needs an IRI or a list of IRIs as sh:${property}`);
87
+ return items;
88
+ };
89
+ const types = (s) => typeNames(values(s, RDF + 'type'));
90
+ const isClass = (s) => types(s).some((t) => t === RDFS + 'Class' || t === SH + 'ShapeClass');
91
+ const isNodeShape = (s) => types(s).some((t) => t === SH + 'NodeShape' || t === SH + 'ShapeClass');
65
92
  const shapes = new Map();
66
93
  const shape = (s, depth = 0) => {
67
94
  if (!resource(s)) error(s, 'is not a shape resource');
68
95
  const key = write(s);
69
96
  if (shapes.has(key)) return shapes.get(key);
70
97
  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) };
98
+ const node = { term: s, id: nextShape++, refs: [], properties: [], lists: new Map(), inactive: TRUE(one(s, 'deactivated')) };
72
99
  shapes.set(key, node);
73
100
  if (node.inactive) return node;
74
101
  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)) {
102
+ for (const p of SHAPE_PARAMETERS) for (const child of values(s, p)) {
76
103
  const target = shape(child, depth + 1); node.refs.push(target);
77
104
  if (p === 'property') node.properties.push(target);
78
105
  }
@@ -87,7 +114,7 @@ export function compileShacl(quads) {
87
114
  };
88
115
  for (const [s, p, o] of triples) {
89
116
  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);
117
+ if (p.args[0] === RDF + 'type' && [SH + 'NodeShape', SH + 'PropertyShape', SH + 'ShapeClass'].includes(o.args?.[0])) shape(s);
91
118
  }
92
119
  const checked = new Set(), checking = new Set();
93
120
  const acyclic = (node) => {
@@ -106,7 +133,7 @@ export function compileShacl(quads) {
106
133
  const name = `sh_path_${nextPath++}`;
107
134
  if (isIri(term)) lines.push(`implies([rdf(X, ${write(term)}, Y, ${G}), ent_resource(X)], ${name}(X, Y));`);
108
135
  else {
109
- const operators = ['inversePath', 'alternativePath', 'zeroOrMorePath', 'oneOrMorePath', 'zeroOrOnePath'].filter((op) => values(term, op).length);
136
+ const operators = PATH_OPERATORS.filter((op) => values(term, op).length);
110
137
  if (values(term, RDF + 'first').length) {
111
138
  if (operators.length) error(term, 'mixes a sequence path with another path operator');
112
139
  const steps = rdfList(term);
@@ -133,19 +160,64 @@ export function compileShacl(quads) {
133
160
  }
134
161
  parsing.delete(key); paths.set(key, name); return name;
135
162
  };
163
+ // sh:closed sh:ByTypes permits, for each rdf:type T of a value node, the
164
+ // properties that collectProperties(T) reaches in the shapes graph.
165
+ let byTypes = null;
166
+ const closedByTypes = () => {
167
+ if (byTypes) return byTypes;
168
+ byTypes = 'sh_by_types';
169
+ const targeting = new Map();
170
+ for (const [s, p, o] of triples) if (p.args[0] === SH + 'targetClass') {
171
+ if (!targeting.has(write(o))) targeting.set(write(o), []);
172
+ targeting.get(write(o)).push(s);
173
+ }
174
+ const collect = (s, out, seen) => {
175
+ if (seen.has(write(s))) return;
176
+ seen.add(write(s));
177
+ for (const property of values(s, 'property')) for (const p of values(property, 'path')) if (isIri(p)) out.set(write(p), p);
178
+ if (isClass(s)) {
179
+ for (const o of values(s, RDFS + 'subClassOf')) collect(o, out, seen);
180
+ for (const o of targeting.get(write(s)) ?? []) collect(o, out, seen);
181
+ }
182
+ if (isNodeShape(s)) for (const o of values(s, 'node')) collect(o, out, seen);
183
+ };
184
+ const candidates = new Map(terms);
185
+ for (const [, , o] of triples) if (targeting.has(write(o))) candidates.set(write(o), o);
186
+ for (const [key, s] of candidates) {
187
+ if (!isIri(s)) continue;
188
+ const out = new Map();
189
+ collect(s, out, new Set());
190
+ for (const p of out.keys()) lines.push(`fact(${byTypes}(${key}, ${p}, ${G}));`);
191
+ }
192
+ return byTypes;
193
+ };
136
194
  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}`;
195
+ const { term: s, id, inactive } = node, S = write(s), v = `sh_values_${id}`, ok = `sh_ok_${id}`, bad = `sh_bad_${id}`;
196
+ const issue = `sh_issue_${id}`, focus = `sh_focus_${id}`, target = `sh_target_${id}`;
138
197
  if (inactive) { lines.push(`fact(${ok}(_));`); continue; }
139
198
  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}));`);
199
+ if (p && types(s).includes(SH + 'NodeShape')) error(s, 'is a NodeShape with sh:path');
200
+ if (!p && types(s).includes(SH + 'PropertyShape')) error(s, 'is a PropertyShape without sh:path');
201
+ if (p) lines.push(`implied_by(${v}(F, V), ${path(p)}(F, V));`);
202
+ else lines.push(`implied_by(${v}(F, F), ent_node(F, ${G}));`);
203
+ // Core node expressions are constants: sh:values adds them, and
204
+ // sh:defaultValue supplies them when there is no other value node.
205
+ const constant = (property, t) => {
206
+ if (!isIri(t) && !(t instanceof Struct && t.name === 'literal') && typeof t !== 'bigint') error(s, `needs an IRI or literal sh:${property}`);
207
+ if (!p) error(s, `uses sh:${property} without a property path`);
208
+ return write(t);
209
+ };
210
+ const added = values(s, 'values').map((t) => constant('values', t));
211
+ for (const t of added) lines.push(`implied_by(${v}(F, ${t}), ent_node(F, ${G}));`);
212
+ const fallback = one(s, 'defaultValue');
213
+ if (fallback !== undefined && !added.length)
214
+ lines.push(`implied_by(${v}(F, ${constant('defaultValue', fallback)}), [ent_node(F, ${G}), not(${path(p)}(F, _))]);`);
143
215
  // A complex resultPath must remain interpretable in the standalone report.
144
216
  const describePath = (term, seen = new Set()) => {
145
217
  if (isIri(term) || seen.has(write(term))) return;
146
218
  seen.add(write(term));
147
219
  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;
220
+ if (![RDF + 'first', RDF + 'rest', ...PATH_OPERATORS.map((n) => SH + n)].includes(predicate)) continue;
149
221
  for (const object of objects) {
150
222
  lines.push(`fact(sh_path_statement(${P}, ${write(term)}, ${iri(predicate)}, ${write(object)}, ${G}));`);
151
223
  describePath(object, seen);
@@ -153,54 +225,85 @@ export function compileShacl(quads) {
153
225
  }
154
226
  };
155
227
  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
228
  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); };
229
+ const boolean = (property, t) => { if (!BOOL(t)) error(s, `needs a boolean sh:${property}`); return TRUE(t); };
161
230
  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
231
  const severity = one(s, 'severity') ?? uri(SH + 'Violation');
164
232
  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}));`);
233
+ const messages = values(s, 'message');
234
+ for (const message of messages) if (!(message instanceof Struct && message.name === 'literal')) error(s, 'needs literal sh:message values');
235
+ // A constraint is the set of triples of its parameters. Their reifiers
236
+ // may deactivate it or give it its own severity and messages.
237
+ const constraint = (...pairs) => {
238
+ const annotations = pairs.flatMap(([property, t]) => reifiers.get(write(new Struct('triple', [s, uri(SH + property), t]))) ?? []);
239
+ if (annotations.some((r) => TRUE(one(r, 'deactivated')))) return null;
240
+ const own = annotations.flatMap((r) => values(r, 'severity')), texts = annotations.flatMap((r) => values(r, 'message'));
241
+ if (own.length > 1) error(s, 'has multiple reified sh:severity values for one constraint');
242
+ const level = own[0] ?? severity, cid = `'sh_c_${nextConstraint++}'`;
243
+ requireIri('severity', level);
244
+ lines.push(`fact(sh_constraint(${cid}, ${write(level)}));`);
245
+ for (const message of texts.length ? texts : messages) lines.push(`fact(sh_constraint_message(${cid}, ${write(message)}));`);
246
+ if (blocked.has(level.args[0])) lines.push(`fact(sh_blocking(${cid}));`);
247
+ return cid;
248
+ };
249
+ const emit = (cid, body, component, value = 'V', resultPath = P, key = NONE) => {
250
+ if (cid) lines.push(`implied_by(${issue}(F, ${resultPath}, ${value}, ${sh(component + 'ConstraintComponent')}, ${key}, ${cid}), [${body.join(', ')}]);`);
251
+ };
252
+ const each = (property, fn) => values(s, property).forEach((t) => fn(t, constraint([property, t])));
253
+ const scalar = (property, fn) => { const t = one(s, property); if (t !== undefined) fn(t, constraint([property, t])); };
254
+ const helper = (name) => `sh_${name}_${id}_${nextHelper++}`;
255
+ const deactivated = one(s, 'deactivated');
256
+ if (deactivated !== undefined) boolean('deactivated', deactivated);
257
+ const all = (property, fn) => values(s, property).forEach(fn);
258
+ all('targetNode', (t) => lines.push(`fact(${target}(${write(t)}), ent_node(${write(t)}, ${G}));`));
259
+ all('targetClass', (t) => lines.push(`implies(sh_instance(F, ${requireIri('targetClass', t)}, ${G}), ${target}(F));`));
260
+ all('targetSubjectsOf', (t) => lines.push(`implies([rdf(F, ${requireIri('targetSubjectsOf', t)}, _, ${G}), ent_resource(F)], ${target}(F));`));
261
+ all('targetObjectsOf', (t) => lines.push(`implies([rdf(X, ${requireIri('targetObjectsOf', t)}, F, ${G}), ent_resource(X)], ${target}(F));`));
262
+ all('targetWhere', (t) => lines.push(`implies([sh_graph_node(F, ${G}), sh_ok_${shape(t).id}(F)], ${target}(F));`));
263
+ if (isClass(s)) {
264
+ if (!isIri(s)) error(s, 'is a shape and a class but not an IRI');
265
+ lines.push(`implies(sh_instance(F, ${S}, ${G}), ${target}(F));`);
169
266
  }
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');
267
+ if (isIri(s)) lines.push(`implies(rdf(F, ${sh('shape')}, ${S}, ${G}), ${target}(F));`);
268
+ lines.push(`implies(${target}(F), ${focus}(F, 'sh_target'));`);
269
+ each('class', (t, c) => {
270
+ const member = helper('class');
271
+ for (const type of iris(s, 'class', t)) lines.push(`implied_by(${member}(V), sh_instance(V, ${write(type)}, ${G}));`);
272
+ emit(c, [`${v}(F, V)`, `not(${member}(V))`], 'Class', 'V', P, write(t));
180
273
  });
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');
274
+ scalar('datatype', (t, c) => {
275
+ const member = helper('datatype');
276
+ for (const type of iris(s, 'datatype', t)) lines.push(RDF_DATATYPES.has(type.args[0]) ?
277
+ `implied_by(${member}(V), rv_valid_as(V, ${write(type)}));` :
278
+ `fact(${member}(literal(_, datatype(${JSON.stringify(type.args[0])}))));`);
279
+ emit(c, [`${v}(F, V)`, `not(${member}(V))`], 'Datatype');
280
+ });
281
+ scalar('nodeKind', (t, c) => {
282
+ const kinds = iris(s, 'nodeKind', t), allowed = isIri(t) ? ['IRI', 'BlankNode', 'Literal', 'BlankNodeOrIRI', 'BlankNodeOrLiteral', 'IRIOrLiteral', 'TripleTerm'] : ['IRI', 'BlankNode', 'Literal', 'TripleTerm'];
283
+ if (!kinds.every((k) => allowed.some((n) => k.args[0] === SH + n))) error(s, 'has an unsupported sh:nodeKind');
284
+ const member = helper('kind');
285
+ for (const kind of kinds) lines.push(`implied_by(${member}(V), sh_kind(V, ${write(kind)}));`);
286
+ emit(c, [`${v}(F, V)`, `not(${member}(V))`], 'NodeKind');
184
287
  });
185
288
  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) => {
289
+ for (const [name, cmp] of [['minCount', 'lt'], ['maxCount', 'gt']]) scalar(name, (t, c) => {
187
290
  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);
291
+ emit(c, [...collected, `${cmp}(N, ${integer(name, t)})`], name[0].toUpperCase() + name.slice(1), NONE);
189
292
  });
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));
293
+ for (const [name, signs] of [['minExclusive', ['>']], ['minInclusive', ['>', '=']], ['maxExclusive', ['<']], ['maxInclusive', ['<', '=']]]) scalar(name, (t, c) => {
294
+ const pass = helper('bound');
295
+ for (const sign of signs) lines.push(`implied_by(${pass}(V), rv_order(V, ${write(t)}, '${sign}'));`);
296
+ emit(c, [`${v}(F, V)`, `not(${pass}(V))`], name[0].toUpperCase() + name.slice(1));
194
297
  });
195
- for (const [name, cmp] of [['minLength', 'lt'], ['maxLength', 'gt']]) scalar(name, (t) => {
196
- const limit = integer(name, t), pass = `sh_length_${id}_${name}`;
298
+ for (const [name, cmp] of [['minLength', 'lt'], ['maxLength', 'gt']]) scalar(name, (t, c) => {
299
+ const limit = integer(name, t), pass = helper('length');
197
300
  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));
301
+ emit(c, [`${v}(F, V)`, `not(${pass}(V))`], name[0].toUpperCase() + name.slice(1));
199
302
  });
200
- scalar('pattern', (t) => {
201
- if (t.name !== 'literal' || t.args[1]?.args[0] !== XSD + 'string') error(s, 'needs an xsd:string sh:pattern');
303
+ scalar('pattern', (t, c) => {
304
+ if (!literal(t, XSD + 'string')) error(s, 'needs an xsd:string sh:pattern');
202
305
  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');
306
+ if (flags && (!literal(flags, XSD + 'string') || /[^imsx]/.test(flags.args[0]))) error(s, 'has unsupported sh:flags');
204
307
  let expression = t.args[0];
205
308
  // The LS regex primitive uses ECMAScript Unicode syntax. Translate the
206
309
  // portable SHACL flags at compilation, without executing input patterns.
@@ -210,59 +313,90 @@ export function compileShacl(quads) {
210
313
  if (f.includes('m')) error(s, 'uses sh:flags m, which is not supported by the LS regex primitive');
211
314
  if (f.includes('i')) expression = caseInsensitivePattern(expression);
212
315
  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');
316
+ emit(c, [`${v}(F, V)`, `not(sh_pattern(V, ${JSON.stringify(expression)}))`], 'Pattern');
317
+ });
318
+ scalar('singleLine', (t, c) => {
319
+ 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
320
  });
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');
321
+ scalar('languageIn', (t, c) => {
322
+ const allowed = helper('language');
323
+ for (const tag of rdfList(t)) {
324
+ if (!literal(tag, XSD + 'string')) error(s, 'needs strings in sh:languageIn');
220
325
  lines.push(`implied_by(${allowed}(V), [sh_language(V, L), sh_language_matches(L, ${JSON.stringify(tag.args[0].toLowerCase())})]);`);
221
326
  }
222
- emit([`${v}(F, V)`, `not(${allowed}(V))`], 'LanguageIn');
327
+ emit(c, [`${v}(F, V)`, `not(${allowed}(V))`], 'LanguageIn');
223
328
  });
224
- scalar('uniqueLang', (t) => {
329
+ scalar('uniqueLang', (t, c) => {
225
330
  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');
331
+ 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
332
  });
228
- scalar('in', (t) => {
229
- const allowed = `sh_in_${id}`;
333
+ // List constraints read SHACL lists of the data graph; any other value node is a result.
334
+ const lists = (name, c, body) => {
335
+ emit(c, [`${v}(F, V)`, `not(sh_list(V, _, ${G}))`], name);
336
+ emit(c, [`${v}(F, V)`, `sh_list(V, Members, ${G})`, ...body], name);
337
+ };
338
+ each('memberShape', (t, c) => lists('MemberShape', c, ['ent_member(M, Members)', `not(sh_ok_${shape(t).id}(M))`]));
339
+ for (const [name, cmp] of [['minListLength', 'lt'], ['maxListLength', 'gt']]) scalar(name, (t, c) =>
340
+ lists(name[0].toUpperCase() + name.slice(1), c, ['ent_count(Members, N)', `${cmp}(N, ${integer(name, t)})`]));
341
+ scalar('uniqueMembers', (t, c) => { if (boolean('uniqueMembers', t)) lists('UniqueMembers', c, ['sh_duplicate(Members)']); });
342
+ scalar('in', (t, c) => {
343
+ const allowed = helper('in');
230
344
  for (const item of rdfList(t)) lines.push(`fact(${allowed}(${write(item)}));`);
231
- emit([`${v}(F, V)`, `not(${allowed}(V))`], 'In');
345
+ emit(c, [`${v}(F, V)`, `not(${allowed}(V))`], 'In');
232
346
  });
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);
347
+ each('hasValue', (t, c) => emit(c, [`ent_node(F, ${G})`, `not(${v}(F, ${write(t)}))`], 'HasValue', NONE, P, write(t)));
348
+ each('rootClass', (t, c) => {
349
+ const member = helper('root');
350
+ for (const root of iris(s, 'rootClass', t)) {
351
+ lines.push(`fact(${member}(${write(root)}));`);
352
+ lines.push(`implied_by(${member}(V), sh_subclass(V, ${write(root)}, ${G}));`);
353
+ }
354
+ emit(c, [`${v}(F, V)`, 'not(unify(V, iri(_)))'], 'RootClass', 'V', P, write(t));
355
+ emit(c, [`${v}(F, V)`, 'unify(V, iri(_))', `not(${member}(V))`], 'RootClass', 'V', P, write(t));
356
+ });
357
+ // Property pairs compare the value nodes with the nodes of another path.
358
+ for (const name of ['equals', 'disjoint', 'subsetOf', 'lessThan', 'lessThanOrEquals']) each(name, (t, c) => {
359
+ const other = path(t), component = name[0].toUpperCase() + name.slice(1);
360
+ if (name.startsWith('lessThan') && !p) error(s, `uses sh:${name} without a property path`);
236
361
  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);
362
+ emit(c, [`${v}(F, V)`, `not(${other}(F, V))`], component, 'V', P, write(t));
363
+ emit(c, [`${other}(F, V)`, `not(${v}(F, V))`], component, 'V', P, write(t));
364
+ } else if (name === 'disjoint') emit(c, [`${v}(F, V)`, `${other}(F, V)`], component, 'V', P, write(t));
365
+ else if (name === 'subsetOf') emit(c, [`${v}(F, V)`, `not(${other}(F, V))`], component, 'V', P, write(t));
240
366
  else {
241
- const ordered = `sh_pair_${id}_${name}`;
367
+ // Each value node and other node that do not compare is its own result.
368
+ const ordered = helper('pair');
242
369
  lines.push(`implied_by(${ordered}(V, W), rv_order(V, W, '<'));`);
243
370
  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);
371
+ emit(c, [`${v}(F, V)`, `${other}(F, W)`, `not(${ordered}(V, W))`], component, 'V', P, `k(${write(t)}, W)`);
245
372
  }
246
373
  });
247
374
  for (const child of node.properties) {
248
375
  if (!child.inactive && !one(child.term, 'path')) error(child.term, 'is referenced by sh:property without sh:path');
376
+ if (!constraint(['property', child.term])) continue;
249
377
  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));`);
378
+ if (!child.inactive) lines.push(`implies([${focus}(F, X), ${v}(F, V)], sh_focus_${child.id}(V, sh_via(${id}, F, X)));`);
251
379
  }
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)));
380
+ each('node', (t, c) => emit(c, [`${v}(F, V)`, `not(sh_ok_${shape(t).id}(V))`], 'Node', 'V', P, write(t)));
381
+ each('not', (t, c) => emit(c, [`${v}(F, V)`, `sh_ok_${shape(t).id}(V)`], 'Not', 'V', P, write(t)));
382
+ each('someValue', (t, c) => {
383
+ const some = helper('some');
384
+ lines.push(`implied_by(${some}(F), [${v}(F, V), sh_ok_${shape(t).id}(V)]);`);
385
+ emit(c, [`ent_node(F, ${G})`, `not(${some}(F))`], 'SomeValue', NONE, P, write(t));
386
+ });
254
387
  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');
388
+ const c = constraint([name, one(s, name)]);
389
+ if (name === 'and') for (const child of children) emit(c, [`${v}(F, V)`, `not(sh_ok_${child.id}(V))`], 'And');
390
+ if (name === 'or') emit(c, [`${v}(F, V)`, ...children.map((child) => `not(sh_ok_${child.id}(V))`)], 'Or');
257
391
  if (name === 'xone') {
258
- const match = `sh_xone_${id}`;
392
+ const match = helper('xone');
259
393
  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');
394
+ emit(c, [`${v}(F, V)`, `findall_sorted(I, ${match}(V, I), Matches)`, 'ent_count(Matches, N)', 'ne(N, 1)'], 'Xone');
261
395
  }
262
396
  }
263
397
  const qualified = one(s, 'qualifiedValueShape');
264
398
  if (qualified) {
265
- const child = shape(qualified), match = `sh_qualified_${id}`, siblings = new Map();
399
+ const child = shape(qualified), match = helper('qualified'), siblings = new Map();
266
400
  const disjoint = one(s, 'qualifiedValueShapesDisjoint');
267
401
  if (disjoint && boolean('qualifiedValueShapesDisjoint', disjoint)) for (const parent of shapes.values()) if (parent.properties.includes(node)) {
268
402
  for (const sibling of parent.properties) if (sibling !== node) {
@@ -271,21 +405,44 @@ export function compileShacl(quads) {
271
405
  }
272
406
  }
273
407
  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) => {
408
+ for (const [name, cmp] of [['qualifiedMinCount', 'lt'], ['qualifiedMaxCount', 'gt']]) {
409
+ const t = one(s, name);
410
+ if (t === undefined) continue;
275
411
  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');
412
+ 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);
413
+ }
414
+ }
415
+ // Each reifier of a value triple must conform; sh:reificationRequired needs one.
416
+ each('reifierShape', (t, c) => {
417
+ if (!p || !isIri(p)) error(s, 'uses sh:reifierShape without an IRI sh:path');
418
+ 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');
419
+ const required = one(s, 'reificationRequired');
420
+ if (required !== undefined && boolean('reificationRequired', required))
421
+ emit(constraint(['reifierShape', t], ['reificationRequired', required]), [`${v}(F, V)`, `not(rdf(_, ${iri(RDF + 'reifies')}, triple(F, ${P}, V), ${G}))`], 'ReifierShape');
422
+ });
423
+ each('uniqueValuesFor', (t, c) => {
424
+ const properties = isIri(t) ? [t] : rdfList(t);
425
+ if (!properties.length || !properties.every(isIri)) error(s, 'needs an IRI or a list of IRIs as sh:uniqueValuesFor');
426
+ const key = helper('key'), duplicate = helper('duplicate');
427
+ 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(', ')}]);`);
428
+ lines.push(`implied_by(${duplicate}(V), [${key}(V, K), not(unify(K, [${properties.map(() => '[]').join(', ')}])), ${target}(T), not_identical(T, V), ${key}(T, K)]);`);
429
+ emit(c, [`${v}(F, V)`, `${duplicate}(V)`], 'UniqueValuesFor', NONE, P, 'V');
430
+ });
431
+ scalar('closed', (t, c) => {
432
+ const types = isIri(t) && t.args[0] === SH + 'ByTypes';
433
+ if (!types && !boolean('closed', t)) return;
434
+ const allowed = helper('closed'), ignored = one(s, 'ignoredProperties');
435
+ const predicates = [...(types ? [] : node.properties.map((child) => one(child.term, 'path')).filter(isIri)), ...(ignored ? rdfList(ignored) : [])];
436
+ for (const property of predicates) lines.push(`fact(${allowed}(_, ${requireIri('ignoredProperties', property)}));`);
437
+ if (types) {
438
+ lines.push(`fact(${allowed}(_, ${iri(RDF + 'type')}));`);
439
+ lines.push(`implied_by(${allowed}(X, P), [rdf(X, ${iri(RDF + 'type')}, T, ${G}), ${closedByTypes()}(T, P, ${G})]);`);
440
+ }
441
+ emit(c, [`${v}(F, X)`, 'ent_resource(X)', `rdf(X, Predicate, V, ${G})`, `not(${allowed}(X, Predicate))`], 'Closed', 'V', 'Predicate', 'X');
285
442
  });
286
- lines.push(`implied_by(${bad}(F), ${issue}(F, _, _, _, _));`);
443
+ lines.push(`implied_by(${bad}(F), [${issue}(F, _, _, _, _, C), sh_blocking(C)]);`);
287
444
  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}));`);
445
+ lines.push(`implies([${focus}(F, X), ${issue}(F, P, V, C, K, I)], sh_violation(${S}, F, P, V, C, K, I, X, ${G}));`);
289
446
  }
290
447
  }
291
448
  return lines.join('\n') + '\n';
@@ -344,8 +501,13 @@ const shR = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#';
344
501
  const shX = 'http://www.w3.org/2001/XMLSchema#';
345
502
  implies([rdf(X, iri(shR + 'type'), C, G), ent_resource(X)], sh_instance(X, C, G));
346
503
  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));
504
+ implies(rdf(C, iri('http://www.w3.org/2000/01/rdf-schema#subClassOf'), D, G), sh_subclass(C, D, G));
505
+ 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));
506
+ // The nodes of a data graph are its subjects and objects.
507
+ implies(rdf(S, _, O, G), [sh_graph_node(S, G), sh_graph_node(O, G)]);
347
508
  fact(sh_kind(iri(_), iri(shN + 'IRI')));
348
509
  fact(sh_kind(bnode(_, _), iri(shN + 'BlankNode')), sh_kind(skolem(_, _, _), iri(shN + 'BlankNode')));
510
+ fact(sh_kind(triple(_, _, _), iri(shN + 'TripleTerm')));
349
511
  implied_by(sh_kind(T, iri(shN + 'Literal')), rv_literal(T));
350
512
  for (const [kind, left, right] of [['BlankNodeOrIRI', 'BlankNode', 'IRI'], ['BlankNodeOrLiteral', 'BlankNode', 'Literal'], ['IRIOrLiteral', 'IRI', 'Literal']]) {
351
513
  implied_by(sh_kind(T, iri(shN + kind)), sh_kind(T, iri(shN + left)));
@@ -356,23 +518,35 @@ implied_by(sh_string(T, S), [rv_literal(T), srl_str(T, literal(S, datatype(shX +
356
518
  implied_by(sh_pattern(T, Pattern), [sh_string(T, Text), regex_match(Pattern, Text)]);
357
519
  implied_by(sh_language(literal(_, lang(L)), Tag), atom_lower(L, Tag));
358
520
  implied_by(sh_language(literal(_, lang(L, _)), Tag), atom_lower(L, Tag));
521
+ // sh:uniqueLang distinguishes a base direction as part of the language tag.
522
+ implied_by(sh_language_key(literal(_, lang(L)), Tag), atom_lower(L, Tag));
523
+ implied_by(sh_language_key(literal(_, lang(L, D)), tag(Tag, D)), atom_lower(L, Tag));
359
524
  implied_by(sh_language_matches(L, '*'), ne(L, ''));
360
525
  fact(sh_language_matches(L, L));
361
526
  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.
527
+ // SHACL lists grow from rdf:nil, so a cycle or a branching cell never forms one.
528
+ 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));
529
+ 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), [_]),
530
+ findall(X, rdf(L, iri(shR + 'first'), X, G), [X])], sh_list(L, [X, ...Members], G));
531
+ implied_by(sh_duplicate([X, ...T]), ent_member(X, T));
532
+ implied_by(sh_duplicate([_, ...T]), sh_duplicate(T));
533
+ fact(sh_blocking('sh_none'));
534
+ // One report per graph, with conformance decided from the completed results
535
+ // whose severity is in the conformance-disallow set.
363
536
  implies(ent_graph(G), sh_report(Report, G));
364
- implied_by(sh_any(G), sh_violation(_, _, _, _, _, _, G));
537
+ implied_by(sh_any(G), [sh_violation(_, _, _, _, _, _, I, _, G), sh_constraint(I, Severity), sh_disallowed(Severity)]);
365
538
  implies(sh_report(Report, G), ent_report(Report, iri(shR + 'type'), iri(shN + 'ValidationReport'), G));
366
539
  implies([sh_report(Report, G), not(sh_any(G))], ent_report(Report, iri(shN + 'conforms'), literal('true', datatype(shX + 'boolean')), G));
367
540
  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)], [
541
+ implies([sh_report(Report, G), sh_custom_disallows, sh_disallowed(Severity)], ent_report(Report, iri(shN + 'conformanceDisallows'), Severity, G));
542
+ implies(sh_violation(S, F, P, V, C, K, I, X, G), sh_result(Result, S, F, P, V, C, K, I, X, G));
543
+ implies([sh_result(Result, S, F, P, V, C, K, I, X, G), sh_report(Report, G), sh_constraint(I, Severity)], [
370
544
  ent_report(Report, iri(shN + 'result'), Result, G), ent_report(Result, iri(shR + 'type'), iri(shN + 'ValidationResult'), G),
371
545
  ent_report(Result, iri(shN + 'focusNode'), F, G), ent_report(Result, iri(shN + 'sourceShape'), S, G),
372
546
  ent_report(Result, iri(shN + 'sourceConstraintComponent'), C, G), ent_report(Result, iri(shN + 'resultSeverity'), Severity, G)
373
547
  ]);
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));
548
+ 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));
549
+ 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));
550
+ 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));
551
+ implies([sh_result(_, _, _, Path, _, _, _, _, _, G), sh_path_statement(Path, S, P, O, G)], ent_report(S, P, O, G));
378
552
  `;
package/src/version.js CHANGED
@@ -1,2 +1,2 @@
1
1
  // The release this checkout is; ./release keeps it in step with package.json.
2
- export const VERSION = '0.8.0';
2
+ export const VERSION = '0.8.1';