eyemind 0.8.1 → 0.8.3
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 +25 -7
- package/SPEC.md +2 -2
- package/package.json +1 -1
- package/src/builtins.js +2 -2
- package/src/digest.js +13 -5
- package/src/rdf-logic.js +12 -4
- package/src/rdf-values.js +4 -1
- package/src/shacl-expr.js +382 -0
- package/src/shacl.js +81 -26
- package/src/srl.js +1 -1
- package/src/version.js +1 -1
package/README.md
CHANGED
|
@@ -613,7 +613,8 @@ lines and language constraints; SHACL list members, lengths and uniqueness;
|
|
|
613
613
|
sets, unique values for targets, property pairs over any path, and closed
|
|
614
614
|
shapes, also `sh:ByTypes`; nested properties, node/not/and/or/xone,
|
|
615
615
|
`sh:someValue`, reifier shapes and qualified counts with disjoint siblings.
|
|
616
|
-
|
|
616
|
+
Node expressions in `sh:values`, `sh:defaultValue`, `sh:targetNode` and
|
|
617
|
+
`sh:deactivated` compute value nodes, targets and deactivation. Predicate,
|
|
617
618
|
inverse, sequence, alternative and repeated paths compute distinct values and
|
|
618
619
|
terminate on data cycles. Repeated `xone` members count separately.
|
|
619
620
|
|
|
@@ -627,11 +628,29 @@ library caller can pass another set as `disallows`, which the report then
|
|
|
627
628
|
lists as `sh:conformanceDisallows`. Only the boolean `true` activates a
|
|
628
629
|
boolean parameter. Deactivated shapes conform without validation.
|
|
629
630
|
|
|
631
|
+
SHACL 1.2 node expressions compile to LS as well: constants, lists, variables,
|
|
632
|
+
paths, `exists`, `if`, distinct, intersection, concat, remove, filter,
|
|
633
|
+
limit, offset, order, flat map, find-first and match-all, counts and other
|
|
634
|
+
aggregates, `instancesOf`, `nodesMatching` and `conformsToShape`, the
|
|
635
|
+
`sparql:` functions, and custom named and list parameter functions. An
|
|
636
|
+
expression gives its output nodes in order, or an evaluation failure that the
|
|
637
|
+
enclosing expression propagates. `sh:expression` and `sh:nodeByExpression`
|
|
638
|
+
constrain value nodes with them, and report the expression or shape as
|
|
639
|
+
`sh:sourceConstraint`. A library caller can evaluate one expression with
|
|
640
|
+
`compileRdfLogic(graph, { profiles: ['shacl'], evaluate: { expression, focus,
|
|
641
|
+
scope } })`, which answers `sh_evaluation(nodes(List))` or
|
|
642
|
+
`sh_evaluation('failure')`. `sparql:now`, `rand`, `uuid` and `struuid` read a
|
|
643
|
+
captured clock and seed, so checking such a proof from its source recompiles
|
|
644
|
+
another context and fails.
|
|
645
|
+
|
|
630
646
|
Shapes and path definitions must be present in the input; inference may add
|
|
631
|
-
data and targets, but cannot dynamically define new constraints.
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
647
|
+
data and targets, but cannot dynamically define new constraints. A shape
|
|
648
|
+
selected at evaluation time, by `sh:nodeByExpression` or `conformsToShape`,
|
|
649
|
+
cannot itself use `sh:expression`, `sh:nodeByExpression` or expression-valued
|
|
650
|
+
parameters. Recursive shape dependencies, SHACL-SPARQL, JavaScript
|
|
651
|
+
constraints and rules are outside the implementation. An evaluation failure
|
|
652
|
+
in validation is not reported separately. Active shapes with unsupported
|
|
653
|
+
constraint predicates are rejected.
|
|
635
654
|
|
|
636
655
|
Datatype checks support XSD integer subtypes, decimal, float/double, boolean,
|
|
637
656
|
string/normalizedString/token/language/anyURI, hex/base64 binary,
|
|
@@ -656,8 +675,7 @@ is scored on every `npm test`, including filtered runs. eyemind targets its
|
|
|
656
675
|
Core and node-expression groups; SHACL-SPARQL and inference rules are out of
|
|
657
676
|
scope and not scored. At upstream revision
|
|
658
677
|
`0ed3f9b4273c2debba0125a7ed5c9dc3cd4b741c`, **all 162 Core tests pass
|
|
659
|
-
complete-report comparison
|
|
660
|
-
implemented, so the 284 node-expression tests do not pass yet.
|
|
678
|
+
complete-report comparison**, as do all 284 node-expression tests.
|
|
661
679
|
|
|
662
680
|
The two groups are reported separately in
|
|
663
681
|
[REPORT.md](REPORT.md) and [SHACL EARL](reports/w3c-shacl-earl.ttl). The runner
|
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.
|
|
5
|
+
Version: eyemind 0.8.3
|
|
6
6
|
```
|
|
7
7
|
|
|
8
8
|
This document specifies Logic Script (LS): the syntax and meaning of its
|
|
@@ -559,7 +559,7 @@ primitive called outside its patterns raises an error.
|
|
|
559
559
|
| `number_chars` | `number_chars(?N, +L)`, `number_chars(+N, -L)` | A bound `L` is read as a number: an optional sign and decimal digits give an integer, and with a fraction or an exponent a float, as in `'007'`, `'-21.5'`, `'.5'`, `'1.'` and `'2E-2'`; other text fails, as does text whose value is too large for a finite float, such as `'1e400'`. Otherwise `L` spells `N` in its canonical text ([Section 9.2](#92-canonical-atoms-numbers-variables-and-lists)). |
|
|
560
560
|
| `atom_concat` | `atom_concat(+A, +B, ?AB)`, `atom_concat(?A, ?B, +AB)` | `AB` is `A` followed by `B`; with `AB` given, every split, shortest `A` first. |
|
|
561
561
|
| `atom_lower`, `atom_upper` | `atom_lower(+A, ?L)`, `atom_upper(+A, ?U)` | `L` is `A` in lower case, `U` in upper case, by Unicode default case conversion: the full mappings, independent of locale, with the final sigma of a word lowered to `'ς'`, so `atom_upper('straße', 'STRASSE')` holds. |
|
|
562
|
-
| `digest` | `digest(+H, +A, ?D)` | `D` is the digest of the UTF-8 encoding of the atom `A` by the hash function `H`, one of `'md5'`, `'sha1'`, `'sha256'` and `'sha512'`, as lowercase hexadecimal. A lone surrogate is encoded as U+FFFD. Another `H` raises an error. |
|
|
562
|
+
| `digest` | `digest(+H, +A, ?D)` | `D` is the digest of the UTF-8 encoding of the atom `A` by the hash function `H`, one of `'md5'`, `'sha1'`, `'sha256'`, `'sha384'` and `'sha512'`, as lowercase hexadecimal. A lone surrogate is encoded as U+FFFD. Another `H` raises an error. |
|
|
563
563
|
| `term_text` | `term_text(+T, ?A)` | `A` is the canonical text of `T` ([Section 9.2](#92-canonical-atoms-numbers-variables-and-lists)), which MUST be ground: `term_text(f('a', [1, 2.0]), "f('a', [1, 2.0])")` holds. |
|
|
564
564
|
| `float64` | `float64(+Op, +A, +B, ?R)` | Explicit IEEE-754 binary64 computation, including exceptional values represented as atoms, as defined below. |
|
|
565
565
|
| `regex_match` | `regex_match(+P, +T)` | Some part of the atom `T` matches the regular expression `P`. |
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "eyemind",
|
|
3
|
-
"version": "0.8.
|
|
3
|
+
"version": "0.8.3",
|
|
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/builtins.js
CHANGED
|
@@ -199,10 +199,10 @@ function caseConversion(name, convert) {
|
|
|
199
199
|
}
|
|
200
200
|
|
|
201
201
|
// digest(+Algorithm, +A, ?Hex): the lowercase hexadecimal digest of A's UTF-8
|
|
202
|
-
// bytes, by md5, sha1, sha256 or sha512.
|
|
202
|
+
// bytes, by md5, sha1, sha256, sha384 or sha512.
|
|
203
203
|
function digest(args, resolved, env, bind) {
|
|
204
204
|
const algorithm = DIGESTS.get(resolved[0]);
|
|
205
|
-
if (algorithm === undefined) throw new EyemindError(`digest/3 needs md5, sha1, sha256 or sha512, not ${write(resolved[0])}`);
|
|
205
|
+
if (algorithm === undefined) throw new EyemindError(`digest/3 needs md5, sha1, sha256, sha384 or sha512, not ${write(resolved[0])}`);
|
|
206
206
|
return bind(args[2], algorithm(utf8(text('digest/3', resolved[1], 'atom'))));
|
|
207
207
|
}
|
|
208
208
|
|
package/src/digest.js
CHANGED
|
@@ -132,10 +132,18 @@ bef9a3f7b2c67915 c67178f2e372532b ca273eceea26619c d186b8c721c0c207 eada7dd6cde0
|
|
|
132
132
|
4cc5d4becb3e42b6 597f299cfc657e2a 5fcb6fab3ad6faec 6c44198c4a475817`.split(/\s+/).map((x) => BigInt(`0x${x}`));
|
|
133
133
|
const rotr64 = (x, n) => ((x >> n) | (x << (64n - n))) & MASK64;
|
|
134
134
|
|
|
135
|
-
|
|
136
|
-
const m = pad(bytes, 128, 16, false);
|
|
137
|
-
let h = `6a09e667f3bcc908 bb67ae8584caa73b 3c6ef372fe94f82b a54ff53a5f1d36f1 510e527fade682d1 9b05688c2b3e6c1f
|
|
135
|
+
const SHA512_IV = `6a09e667f3bcc908 bb67ae8584caa73b 3c6ef372fe94f82b a54ff53a5f1d36f1 510e527fade682d1 9b05688c2b3e6c1f
|
|
138
136
|
1f83d9abfb41bd6b 5be0cd19137e2179`.split(/\s+/).map((x) => BigInt(`0x${x}`));
|
|
137
|
+
// SHA-384 is SHA-512 from other initial values, truncated to six words.
|
|
138
|
+
const SHA384_IV = `cbbb9d5dc1059ed8 629a292a367cd507 9159015a3070dd17 152fecd8f70e5939 67332667ffc00b31 8eb44a8768581511
|
|
139
|
+
db0c2e0d64f98fa7 47b5481dbefa4fa4`.split(/\s+/).map((x) => BigInt(`0x${x}`));
|
|
140
|
+
|
|
141
|
+
const sha512 = (bytes) => sha512Words(bytes, SHA512_IV, 8);
|
|
142
|
+
const sha384 = (bytes) => sha512Words(bytes, SHA384_IV, 6);
|
|
143
|
+
|
|
144
|
+
function sha512Words(bytes, iv, words) {
|
|
145
|
+
const m = pad(bytes, 128, 16, false);
|
|
146
|
+
let h = iv;
|
|
139
147
|
for (let offset = 0; offset < m.length; offset += 128) {
|
|
140
148
|
const w = [];
|
|
141
149
|
for (let i = 0; i < 16; i++) {
|
|
@@ -156,7 +164,7 @@ function sha512(bytes) {
|
|
|
156
164
|
}
|
|
157
165
|
h = h.map((x, i) => (x + [a, b, c, d, e, f, g, k][i]) & MASK64);
|
|
158
166
|
}
|
|
159
|
-
return h.map((x) => x.toString(16).padStart(16, '0')).join('');
|
|
167
|
+
return h.slice(0, words).map((x) => x.toString(16).padStart(16, '0')).join('');
|
|
160
168
|
}
|
|
161
169
|
|
|
162
|
-
export const DIGESTS = new Map([['md5', md5], ['sha1', sha1], ['sha256', sha256], ['sha512', sha512]]);
|
|
170
|
+
export const DIGESTS = new Map([['md5', md5], ['sha1', sha1], ['sha256', sha256], ['sha384', sha384], ['sha512', sha512]]);
|
package/src/rdf-logic.js
CHANGED
|
@@ -7,24 +7,32 @@ import { owl2rlRules } from './owl2rl.js';
|
|
|
7
7
|
import { skosRules } from './skos.js';
|
|
8
8
|
import { qudtRules } from './qudt.js';
|
|
9
9
|
import { compileShacl } from './shacl.js';
|
|
10
|
+
import { NODE_FUNCTIONS } from './shacl-expr.js';
|
|
11
|
+
import { executionContext } from './srl.js';
|
|
10
12
|
import { rdfValueRules } from './rdf-values.js';
|
|
11
13
|
|
|
12
14
|
export const ENTAILMENT = 'https://eyereasoner.github.io/eyemind/entailment#';
|
|
13
15
|
export const RDF_PROFILES = ['owl2rl', 'qudt', 'skos', 'shacl'];
|
|
14
16
|
|
|
15
|
-
export function compileRdfLogic({ quads, prefixes, shapes = quads }, { profiles, source = '<input>', disallows }) {
|
|
17
|
+
export function compileRdfLogic({ quads, prefixes, shapes = quads }, { profiles, source = '<input>', disallows, evaluate, context }) {
|
|
16
18
|
quads = [...new Map(quads.map((q) => [q.map((t) => write(t)).join(' '), q])).values()];
|
|
17
|
-
const selected = new Set(profiles);
|
|
19
|
+
const selected = new Set(profiles), needs = new Set();
|
|
20
|
+
// SHACL node expressions may call SPARQL functions beyond the value rules.
|
|
21
|
+
const shacl = selected.has('shacl') ? compileShacl(shapes, { disallows, needs, evaluate }) : '';
|
|
22
|
+
const own = [...needs].filter((n) => NODE_FUNCTIONS[n]);
|
|
23
|
+
const execution = ['srl_now', 'srl_uuid', 'sh_ne_rand'].some((n) => needs.has(n)) ? executionContext(context ?? null) : null;
|
|
18
24
|
const text = `// Generated by eyemind from ${String(source).replace(/[\r\n\u2028\u2029]/g, ' ')}, with ${profiles.map((p) => '--' + p).join(' ')}.\n` +
|
|
19
25
|
'// rdf(S, P, O, G) is the working graph; result_rdf contains conclusions and reports.\n' +
|
|
20
26
|
`facts_from({ text: ${JSON.stringify(rdfDocument(quads))} })\n` +
|
|
21
27
|
`facts_from({ text: ${JSON.stringify(rdfDocument(quads, 'ent_base'))} })\n` + COMMON +
|
|
22
28
|
(quads.length ? '' : "fact(ent_graph('default_graph'));\n") +
|
|
23
|
-
(profiles.some((p) => p !== 'skos') ? rdfValueRules : '') +
|
|
29
|
+
(profiles.some((p) => p !== 'skos') ? rdfValueRules([...needs].filter((n) => !NODE_FUNCTIONS[n])) : '') +
|
|
30
|
+
own.map((n) => NODE_FUNCTIONS[n] + '\n').join('') +
|
|
31
|
+
(execution ? `implied_by(srl_execution(${JSON.stringify(execution.now)}, ${JSON.stringify(execution.seed)}), 'true');\n` : '') +
|
|
24
32
|
(selected.has('owl2rl') ? owl2rlRules : '') +
|
|
25
33
|
(selected.has('skos') ? skosRules : '') +
|
|
26
34
|
(selected.has('qudt') ? qudtRules : '') +
|
|
27
|
-
|
|
35
|
+
shacl + (evaluate ? "query(sh_evaluation(R));\n" : OUTPUT);
|
|
28
36
|
return { kind: profiles[0], text, program: loadText(text, source),
|
|
29
37
|
prefixes: { ...prefixes, ent: ENTAILMENT, ...(selected.has('skos') ? { skos: 'http://www.w3.org/2004/02/skos/core#' } : {}),
|
|
30
38
|
...(selected.has('qudt') ? { qconv: 'https://eyereasoner.github.io/eyemind/qudt#', qudt: 'http://qudt.org/schema/qudt/', unit: 'http://qudt.org/vocab/unit/' } : {}),
|
package/src/rdf-values.js
CHANGED
|
@@ -55,7 +55,10 @@ implied_by(rv_order(A, B, O), [rv_temporal(A, T, K, X), rv_temporal(B, T, K, Y),
|
|
|
55
55
|
implied_by(rv_member(T, iri(rvXsd + 'dateTime')), [rv_datatype(T, iri(rvXsd + 'dateTimeStamp')), rv_valid(T)]);
|
|
56
56
|
`;
|
|
57
57
|
|
|
58
|
-
|
|
58
|
+
// The SPARQL definitions the value rules use; a profile may add more.
|
|
59
|
+
const VALUE_LIBRARY = ['srl_num', 'srl_make', 'srl_add', 'srl_sub', 'srl_mul', 'srl_div', 'srl_order', 'srl_str', 'srl_lang'];
|
|
60
|
+
export const rdfValueRules = (extra = []) => '\n' + libraryText(new Set([...VALUE_LIBRARY, ...extra])) + '\n' + VALUE_RULES;
|
|
61
|
+
const VALUE_RULES = String.raw`
|
|
59
62
|
const rvXsd = 'http://www.w3.org/2001/XMLSchema#';
|
|
60
63
|
const rvRdf = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#';
|
|
61
64
|
implied_by(rv_datatype(N, iri(rvXsd + 'integer')), is_int(N));
|
|
@@ -0,0 +1,382 @@
|
|
|
1
|
+
// SHACL 1.2 node expressions compile to LS backward rules. An expression is a
|
|
2
|
+
// predicate E(Focus, Scope, Result): Focus is a node or 'sh_none', Scope a
|
|
3
|
+
// list of [Key, Value] pairs, and Result either nodes(List), the ordered
|
|
4
|
+
// output nodes, or failure, an evaluation failure. Every expression has
|
|
5
|
+
// exactly one result, so an enclosing expression decides from it whether to
|
|
6
|
+
// propagate a failure, as the specification requires.
|
|
7
|
+
// https://www.w3.org/TR/shacl12-node-expr/
|
|
8
|
+
import { EyemindError, Struct } from './terms.js';
|
|
9
|
+
import { write } from './writer.js';
|
|
10
|
+
import { DEFINITIONS } from './srl-functions.js';
|
|
11
|
+
|
|
12
|
+
const SH = 'http://www.w3.org/ns/shacl#';
|
|
13
|
+
const RDF = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#';
|
|
14
|
+
const XSD = 'http://www.w3.org/2001/XMLSchema#';
|
|
15
|
+
export const SHNEX = 'http://www.w3.org/ns/shacl-node-expr#';
|
|
16
|
+
export const SPARQL = 'http://www.w3.org/ns/sparql#';
|
|
17
|
+
const TRUE = `literal('true', datatype('${XSD}boolean'))`;
|
|
18
|
+
const FALSE = `literal('false', datatype('${XSD}boolean'))`;
|
|
19
|
+
const isIri = (t) => t instanceof Struct && t.name === 'iri';
|
|
20
|
+
const isBlank = (t) => t instanceof Struct && t.name === 'bnode';
|
|
21
|
+
|
|
22
|
+
// sparql:<name> to its SRL function goal and the library definition it needs.
|
|
23
|
+
const FUNCTIONS = {
|
|
24
|
+
abs: ['srl_abs'], ceil: ['srl_ceil', 'srl_abs'], floor: ['srl_floor', 'srl_abs'], round: ['srl_round', 'srl_abs'],
|
|
25
|
+
concat: ['srl_concat'], contains: ['srl_contains', 'srl_strstarts'], datatype: ['srl_datatype'],
|
|
26
|
+
day: ['srl_day', 'srl_datetime'], divide: ['srl_div'], 'encode-for-uri': ['srl_encode_for_uri'],
|
|
27
|
+
equals: ['srl_eq'], 'not-equals': ['srl_ne'], 'greater-than': ['srl_gt', 'srl_order'],
|
|
28
|
+
'greater-than-or-equal': ['srl_ge', 'srl_order'], 'less-than': ['srl_lt', 'srl_order'],
|
|
29
|
+
'less-than-or-equal': ['srl_le', 'srl_order'], hasLang: ['srl_has_lang', 'srl_kind_tests'],
|
|
30
|
+
hasLangdir: ['srl_has_langdir', 'srl_kind_tests'], hours: ['srl_hours', 'srl_datetime'], iri: ['srl_iri'],
|
|
31
|
+
uri: ['srl_iri'], isBlank: ['srl_is_blank', 'srl_kind_tests'], isIRI: ['srl_is_iri', 'srl_kind_tests'],
|
|
32
|
+
isURI: ['srl_is_iri', 'srl_kind_tests'], isLiteral: ['srl_is_literal', 'srl_kind_tests'],
|
|
33
|
+
isNumeric: ['srl_is_numeric', 'srl_kind_tests'], isTriple: ['srl_is_triple', 'srl_kind_tests'],
|
|
34
|
+
lang: ['srl_lang'], langdir: ['srl_langdir', 'srl_lang'], langMatches: ['srl_langmatches'],
|
|
35
|
+
lcase: ['srl_lcase', 'srl_ucase'], ucase: ['srl_ucase'], 'logical-not': ['srl_not'], minutes: ['srl_minutes', 'srl_datetime'],
|
|
36
|
+
month: ['srl_month', 'srl_datetime'], multiply: ['srl_mul'], plus: ['srl_add'], subtract: ['srl_sub'],
|
|
37
|
+
'unary-minus': ['srl_neg'], 'unary-plus': ['srl_pos', 'srl_neg'], now: ['srl_now'], object: ['srl_object', 'srl_triple'],
|
|
38
|
+
predicate: ['srl_predicate', 'srl_triple'], subject: ['srl_subject', 'srl_triple'], triple: ['srl_triple'],
|
|
39
|
+
regex: ['srl_regex'], replace: ['srl_replace'], sameTerm: ['srl_same_term'], seconds: ['srl_seconds', 'srl_datetime'],
|
|
40
|
+
str: ['srl_str'], strafter: ['srl_strafter', 'srl_strbefore'], strbefore: ['srl_strbefore'], strdt: ['srl_strdt'],
|
|
41
|
+
strends: ['srl_strends', 'srl_strstarts'], strlang: ['srl_strlang'], strlangdir: ['srl_strlangdir', 'srl_strlang'],
|
|
42
|
+
strlen: ['srl_strlen'], strstarts: ['srl_strstarts'], substr: ['srl_substr'], timezone: ['srl_timezone', 'srl_datetime'],
|
|
43
|
+
tz: ['srl_tz', 'srl_datetime'], year: ['srl_year', 'srl_datetime'],
|
|
44
|
+
md5: ['sh_ne_md5'], sha1: ['sh_ne_sha1'], sha256: ['sh_ne_sha256'], sha384: ['sh_ne_sha384'], sha512: ['sh_ne_sha512'],
|
|
45
|
+
sameValue: ['sh_ne_same_value', 'srl_equal'], rand: ['sh_ne_rand'], uuid: ['sh_ne_uuid', 'srl_uuid'],
|
|
46
|
+
struuid: ['sh_ne_struuid', 'srl_uuid'], bnode: ['sh_ne_bnode'],
|
|
47
|
+
};
|
|
48
|
+
// Functions that receive unbound arguments and errors themselves.
|
|
49
|
+
const UNBOUND = new Set(['bound', 'coalesce', 'if', 'logical-and', 'logical-or']);
|
|
50
|
+
// Execution functions read the captured clock and seed.
|
|
51
|
+
export const EXECUTION = new Set(['now', 'rand', 'uuid', 'struuid', 'bnode']);
|
|
52
|
+
// Built-in named parameter functions by their key parameter.
|
|
53
|
+
const NAMED = ['var', 'pathValues', 'exists', 'if', 'distinct', 'intersection', 'concat', 'remove', 'filterShape', 'limit',
|
|
54
|
+
'offset', 'orderBy', 'flatMap', 'findFirst', 'matchAll', 'count', 'min', 'max', 'sum', 'instancesOf', 'nodesMatching', 'arg'];
|
|
55
|
+
|
|
56
|
+
// The expressions of one graph. The shapes compiler supplies its graph
|
|
57
|
+
// access, its paths and the conformance predicates of its shapes.
|
|
58
|
+
export function nodeExpressions({ G, lines, needs, index, rdfList, path, conforms, error }) {
|
|
59
|
+
const memo = new Map(), compiling = new Set();
|
|
60
|
+
let next = 0;
|
|
61
|
+
const fresh = (kind) => `sh_expr_${kind}_${next++}`;
|
|
62
|
+
// Custom functions declared in the shapes graph by sh:bodyExpression.
|
|
63
|
+
const custom = { list: new Map(), named: new Map() };
|
|
64
|
+
for (const [key, properties] of index) {
|
|
65
|
+
const body = properties.get(SH + 'bodyExpression');
|
|
66
|
+
if (!body) continue;
|
|
67
|
+
const types = (properties.get(RDF + 'type') ?? []).map((t) => t.args?.[0]);
|
|
68
|
+
if (body.length !== 1) throw new EyemindError(`--shacl: ${key} needs one sh:bodyExpression`);
|
|
69
|
+
if (types.includes(SH + 'ListParameterExpressionFunction')) custom.list.set(key, body[0]);
|
|
70
|
+
else if (types.includes(SH + 'NamedParameterExpressionFunction')) {
|
|
71
|
+
const parameters = (properties.get(SH + 'parameter') ?? []).map((p) => {
|
|
72
|
+
const paths = index.get(write(p))?.get(SH + 'path') ?? [];
|
|
73
|
+
if (paths.length !== 1 || !isIri(paths[0])) throw new EyemindError(`--shacl: ${key} declares a parameter without an IRI sh:path`);
|
|
74
|
+
const flag = index.get(write(p))?.get(SH + 'keyParameter')?.[0];
|
|
75
|
+
return { path: paths[0].args[0], key: flag?.args?.[0] === 'true' };
|
|
76
|
+
});
|
|
77
|
+
for (const p of parameters.filter((q) => q.key)) custom.named.set(p.path, { body: body[0], parameters });
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
const properties = (t) => index.get(write(t)) ?? new Map();
|
|
81
|
+
const single = (t, p) => {
|
|
82
|
+
const list = properties(t).get(p) ?? [];
|
|
83
|
+
if (list.length > 1) error(t, `has multiple <${p}> values`);
|
|
84
|
+
return list[0];
|
|
85
|
+
};
|
|
86
|
+
// The arguments of a list parameter function: a SHACL list, or one argument.
|
|
87
|
+
const argumentsOf = (o) => (isIri(o) && o.args[0] === RDF + 'nil') || (isBlank(o) && properties(o).has(RDF + 'first')) ? rdfList(o) : [o];
|
|
88
|
+
|
|
89
|
+
// compile(term, env) names the predicate of an expression; env maps the
|
|
90
|
+
// parameters of an enclosing custom named function to their arguments.
|
|
91
|
+
const compile = (term, env = null) => {
|
|
92
|
+
const key = `${write(term)}|${env?.id ?? ''}`;
|
|
93
|
+
if (memo.has(key)) return memo.get(key);
|
|
94
|
+
if (compiling.has(key)) error(term, 'is a recursive node expression');
|
|
95
|
+
compiling.add(key);
|
|
96
|
+
const name = fresh('e');
|
|
97
|
+
memo.set(key, name);
|
|
98
|
+
const rule = (body, result = 'R') => lines.push(`implied_by(${name}(F, S, ${result}), [${body.join(', ')}]);`);
|
|
99
|
+
const own = properties(term);
|
|
100
|
+
if (!isBlank(term)) lines.push(`fact(${name}(_, _, nodes([${write(term)}])));`);
|
|
101
|
+
else if (!own.size) lines.push(`fact(${name}(_, _, nodes([])));`);
|
|
102
|
+
else if (own.has(RDF + 'first')) lines.push(`fact(${name}(_, _, nodes([${rdfList(term).map((t) => write(t)).join(', ')}])));`);
|
|
103
|
+
else {
|
|
104
|
+
const named = NAMED.filter((n) => own.has(SHNEX + n));
|
|
105
|
+
const listed = [...own.keys()].filter((p) => p === SHNEX + 'conformsToShape' || p.startsWith(SPARQL) || custom.list.has(write(new Struct('iri', [p]))));
|
|
106
|
+
const keyed = [...own.keys()].filter((p) => custom.named.has(p));
|
|
107
|
+
if (named.length + listed.length + keyed.length !== 1)
|
|
108
|
+
error(term, named.length + listed.length + keyed.length ? 'mixes the key parameters of several node expression functions' : 'is not a supported node expression');
|
|
109
|
+
const sub = (p, fallback) => {
|
|
110
|
+
const t = single(term, SHNEX + p);
|
|
111
|
+
return t === undefined ? fallback : compile(t, env);
|
|
112
|
+
};
|
|
113
|
+
// Input nodes: shnex:nodes when given, otherwise the focus node.
|
|
114
|
+
const input = (required) => {
|
|
115
|
+
const nodes = single(term, SHNEX + 'nodes');
|
|
116
|
+
if (nodes === undefined) {
|
|
117
|
+
if (required) error(term, 'needs shnex:nodes');
|
|
118
|
+
return 'sh_ne_focus_nodes(F, R0)';
|
|
119
|
+
}
|
|
120
|
+
return `${compile(nodes, env)}(F, S, R0)`;
|
|
121
|
+
};
|
|
122
|
+
const integer = (p) => {
|
|
123
|
+
const t = single(term, SHNEX + p);
|
|
124
|
+
if (typeof t !== 'bigint' || t < 0n) error(term, `needs a nonnegative integer shnex:${p}`);
|
|
125
|
+
return write(t);
|
|
126
|
+
};
|
|
127
|
+
if (named.length) {
|
|
128
|
+
const fn = named[0];
|
|
129
|
+
switch (fn) {
|
|
130
|
+
case 'var': {
|
|
131
|
+
const v = single(term, SHNEX + 'var');
|
|
132
|
+
if (!(v instanceof Struct && v.name === 'literal' && typeof v.args[0] === 'string' && v.args[0])) error(term, 'needs a nonempty string shnex:var');
|
|
133
|
+
rule([`sh_ne_var(${JSON.stringify(v.args[0])}, F, S, R)`]);
|
|
134
|
+
break;
|
|
135
|
+
}
|
|
136
|
+
case 'arg': {
|
|
137
|
+
const a = single(term, SHNEX + 'arg');
|
|
138
|
+
if (typeof a === 'bigint') rule([`sh_ne_var(${write(a)}, 'sh_none', S, R)`]);
|
|
139
|
+
else if (isIri(a) && env?.args.has(a.args[0])) {
|
|
140
|
+
const argument = env.args.get(a.args[0]);
|
|
141
|
+
rule([`${compile(argument.term, argument.env)}(F, [], R)`]);
|
|
142
|
+
} else if (isIri(a)) lines.push(`fact(${name}(_, _, nodes([])));`);
|
|
143
|
+
else error(term, 'needs an IRI or integer shnex:arg');
|
|
144
|
+
break;
|
|
145
|
+
}
|
|
146
|
+
case 'pathValues': {
|
|
147
|
+
const p = path(single(term, SHNEX + 'pathValues')), values = fresh('path');
|
|
148
|
+
const focus = single(term, SHNEX + 'focusNode');
|
|
149
|
+
rule([focus === undefined ? 'sh_ne_own_focus(F, N)' : `${compile(focus, env)}(F, S, R0), sh_ne_focus(R0, N)`, `${values}(N, R)`]);
|
|
150
|
+
lines.push(`fact(${values}(failure, failure), ${values}(none, nodes([])));`);
|
|
151
|
+
lines.push(`implied_by(${values}(one(X), nodes(L)), findall(Y, ${p}(X, Y), L));`);
|
|
152
|
+
break;
|
|
153
|
+
}
|
|
154
|
+
case 'exists': rule([`${sub('exists')}(F, S, R0)`, 'sh_ne_exists(R0, R)']); break;
|
|
155
|
+
case 'if': {
|
|
156
|
+
const condition = sub('if'), then = sub('then', null), otherwise = sub('else', null);
|
|
157
|
+
if (!then && !otherwise) error(term, 'needs shnex:then or shnex:else');
|
|
158
|
+
const branch = (b) => b ? `${b}(F, S, R)` : 'unify(R, nodes([]))';
|
|
159
|
+
rule([`${condition}(F, S, C)`, 'unify(C, failure)', 'unify(R, failure)']);
|
|
160
|
+
rule([`${condition}(F, S, C)`, `unify(C, nodes([${TRUE}]))`, branch(then)]);
|
|
161
|
+
rule([`${condition}(F, S, C)`, 'unify(C, nodes(L))', `not(unify(L, [${TRUE}]))`, branch(otherwise)]);
|
|
162
|
+
break;
|
|
163
|
+
}
|
|
164
|
+
case 'distinct': rule([`${sub('distinct')}(F, S, R0)`, 'sh_ne_distinct(R0, R)']); break;
|
|
165
|
+
case 'count': rule([`${sub('count')}(F, S, R0)`, 'sh_ne_count(R0, R)']); break;
|
|
166
|
+
case 'min': case 'max': case 'sum':
|
|
167
|
+
needs.add('srl_aggregates');
|
|
168
|
+
rule([`${sub(fn)}(F, S, R0)`, `sh_ne_aggregate('${fn}', R0, R)`]);
|
|
169
|
+
break;
|
|
170
|
+
case 'intersection': case 'concat': {
|
|
171
|
+
const members = rdfList(single(term, SHNEX + fn)).map((t) => compile(t, env));
|
|
172
|
+
rule([...members.map((m, i) => `${m}(F, S, R${i})`), `sh_ne_all([${members.map((_, i) => 'R' + i).join(', ')}], A)`, `sh_ne_${fn}(A, R)`]);
|
|
173
|
+
break;
|
|
174
|
+
}
|
|
175
|
+
case 'remove': rule([`${sub('remove')}(F, S, M)`, input(true), 'sh_ne_remove(M, R0, R)']); break;
|
|
176
|
+
case 'limit': case 'offset': rule([input(true), `sh_ne_${fn}(R0, ${integer(fn)}, R)`]); break;
|
|
177
|
+
case 'filterShape': case 'findFirst': case 'matchAll': {
|
|
178
|
+
const filter = fresh('filter'), ok = conforms(single(term, SHNEX + fn));
|
|
179
|
+
lines.push(`fact(${filter}([], []));`);
|
|
180
|
+
lines.push(`implied_by(${filter}([X, ...T], [X, ...R]), [${ok}(X), ${filter}(T, R)]);`);
|
|
181
|
+
lines.push(`implied_by(${filter}([X, ...T], R), [not(${ok}(X)), ${filter}(T, R)]);`);
|
|
182
|
+
rule([input(fn === 'filterShape'), `sh_ne_${fn}(R0, ${filter}, R)`]);
|
|
183
|
+
lines.push(`fact(sh_ne_${fn}(failure, ${filter}, failure));`);
|
|
184
|
+
const kept = `${filter}(L, K)`;
|
|
185
|
+
if (fn === 'filterShape') lines.push(`implied_by(sh_ne_filterShape(nodes(L), ${filter}, nodes(K)), ${kept});`);
|
|
186
|
+
if (fn === 'findFirst') lines.push(`implied_by(sh_ne_findFirst(nodes(L), ${filter}, R), [${kept}, sh_ne_first(K, R)]);`);
|
|
187
|
+
if (fn === 'matchAll') lines.push(`implied_by(sh_ne_matchAll(nodes(L), ${filter}, R), [${kept}, or([unify(L, K), unify(R, nodes([${TRUE}]))], [not(unify(L, K)), unify(R, nodes([${FALSE}]))])]);`);
|
|
188
|
+
break;
|
|
189
|
+
}
|
|
190
|
+
case 'nodesMatching': {
|
|
191
|
+
const ok = conforms(single(term, SHNEX + 'nodesMatching'));
|
|
192
|
+
rule([`findall(X, [sh_graph_node(X, ${G}), ${ok}(X)], L)`, 'unify(R, nodes(L))']);
|
|
193
|
+
break;
|
|
194
|
+
}
|
|
195
|
+
case 'instancesOf': rule([`${sub('instancesOf')}(F, S, R0)`, `once(sh_ne_instances(R0, ${G}, R))`]); break;
|
|
196
|
+
case 'flatMap': case 'orderBy': {
|
|
197
|
+
const each = fresh('each'), inner = sub(fn);
|
|
198
|
+
if (fn === 'flatMap') {
|
|
199
|
+
lines.push(`fact(${each}([], _, nodes([])));`);
|
|
200
|
+
lines.push(`implied_by(${each}([N, ...T], S, R), [${inner}(N, S, R1), ${each}(T, S, R2), sh_ne_join(R1, R2, R)]);`);
|
|
201
|
+
rule([input(false), `sh_ne_each(R0, ${each}, S, R)`]);
|
|
202
|
+
} else {
|
|
203
|
+
const desc = single(term, SHNEX + 'desc');
|
|
204
|
+
lines.push(`fact(${each}([], _, pairs([])));`);
|
|
205
|
+
lines.push(`implied_by(${each}([N, ...T], S, R), [${inner}(N, S, R1), ${each}(T, S, R2), sh_ne_keyed(N, R1, R2, R)]);`);
|
|
206
|
+
needs.add('srl_aggregates');
|
|
207
|
+
rule([input(true), `sh_ne_each(R0, ${each}, S, P)`, `sh_ne_sorted(P, ${desc?.args?.[0] === 'true' ? "'desc'" : "'asc'"}, R)`]);
|
|
208
|
+
}
|
|
209
|
+
lines.push(`fact(sh_ne_each(failure, ${each}, _, failure));`);
|
|
210
|
+
lines.push(`implied_by(sh_ne_each(nodes(L), ${each}, S, R), ${each}(L, S, R));`);
|
|
211
|
+
break;
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
} else if (keyed.length) {
|
|
215
|
+
// A custom named parameter function evaluates its body with the
|
|
216
|
+
// argument expressions of this call bound to its parameters.
|
|
217
|
+
const { body, parameters } = custom.named.get(keyed[0]);
|
|
218
|
+
const args = new Map();
|
|
219
|
+
for (const p of parameters) {
|
|
220
|
+
const a = single(term, p.path);
|
|
221
|
+
if (a !== undefined) args.set(p.path, { term: a, env });
|
|
222
|
+
}
|
|
223
|
+
rule([`${compile(body, { id: name, args })}(F, [], R)`]);
|
|
224
|
+
} else {
|
|
225
|
+
// A list parameter function evaluates each argument to one node,
|
|
226
|
+
// none (unbound) or an error before it applies.
|
|
227
|
+
const p = listed[0], fn = p.startsWith(SPARQL) ? p.slice(SPARQL.length) : null;
|
|
228
|
+
const args = argumentsOf(single(term, p)).map((t) => compile(t, env));
|
|
229
|
+
const evaluated = [...args.map((a, i) => `${a}(F, S, R${i}), sh_ne_arg(R${i}, A${i})`)];
|
|
230
|
+
const list = `[${args.map((_, i) => 'A' + i).join(', ')}]`;
|
|
231
|
+
if (p === SHNEX + 'conformsToShape') {
|
|
232
|
+
if (args.length !== 2) error(term, 'needs two arguments for shnex:conformsToShape');
|
|
233
|
+
rule([...evaluated, `sh_ne_status(${list}, T)`, 'sh_ne_conforms(T, A0, A1, R)']);
|
|
234
|
+
} else if (fn === null) {
|
|
235
|
+
// A custom list parameter function: its body sees only its arguments.
|
|
236
|
+
const body = compile(custom.list.get(write(new Struct('iri', [p]))));
|
|
237
|
+
const scope = `[${args.map((_, i) => `[${i}, X${i}]`).join(', ')}]`;
|
|
238
|
+
rule([...evaluated, `sh_ne_status(${list}, T)`, `sh_ne_custom(T, ${list}, ${scope}, ${body}, F, R)`]);
|
|
239
|
+
lines.push(`fact(sh_ne_custom('error', _, _, ${body}, _, failure), sh_ne_custom('unbound', _, _, ${body}, _, nodes([])));`);
|
|
240
|
+
lines.push(`implied_by(sh_ne_custom('ok', [${args.map((_, i) => `v(X${i})`).join(', ')}], ${scope}, ${body}, F, R), [${body}(F, ${scope}, R0), sh_ne_at_most_one(R0, R)]);`);
|
|
241
|
+
} else if (UNBOUND.has(fn)) {
|
|
242
|
+
if (fn === 'bound') rule([...evaluated, `sh_ne_bound(${list}, R)`]);
|
|
243
|
+
if (fn === 'coalesce') rule([...evaluated, `sh_ne_coalesce(${list}, R)`]);
|
|
244
|
+
if (fn === 'if') {
|
|
245
|
+
needs.add('srl_ebv');
|
|
246
|
+
if (args.length !== 3) error(term, 'needs three arguments for sparql:if');
|
|
247
|
+
rule([...evaluated, 'sh_ne_choose(A0, A1, A2, R)']);
|
|
248
|
+
}
|
|
249
|
+
if (fn === 'logical-and' || fn === 'logical-or') {
|
|
250
|
+
needs.add('srl_ebv'); needs.add(fn === 'logical-and' ? 'srl_and' : 'srl_or');
|
|
251
|
+
rule([...evaluated, `sh_ne_truth(${list}, Bs)`, `sh_ne_${fn === 'logical-and' ? 'and' : 'or'}(Bs, R)`]);
|
|
252
|
+
}
|
|
253
|
+
} else {
|
|
254
|
+
const entry = FUNCTIONS[fn];
|
|
255
|
+
if (!entry) error(term, `uses the unsupported SPARQL function <${p}>`);
|
|
256
|
+
const [goal] = entry;
|
|
257
|
+
for (const d of entry) if (DEFINITIONS[d] || NODE_FUNCTIONS[d]) needs.add(d);
|
|
258
|
+
let call = `${goal}(${args.map((_, i) => 'X' + i).join(', ')}${args.length ? ', ' : ''}Y)`;
|
|
259
|
+
if (fn === 'concat') call = `srl_concat([${args.map((_, i) => 'X' + i).join(', ')}], Y)`;
|
|
260
|
+
if (fn === 'now') call = 'srl_now(Y)';
|
|
261
|
+
else if (EXECUTION.has(fn)) call = `${goal}(${write(term)}, F, S, [${args.map((_, i) => 'X' + i).join(', ')}], Y)`;
|
|
262
|
+
const apply = fresh('apply');
|
|
263
|
+
rule([...evaluated, `sh_ne_status(${list}, T)`, `${apply}(T, ${list}, F, S, R)`]);
|
|
264
|
+
lines.push(`fact(${apply}('error', _, _, _, failure), ${apply}('unbound', _, _, _, nodes([])));`);
|
|
265
|
+
lines.push(`implied_by(${apply}('ok', [${args.map((_, i) => `v(X${i})`).join(', ')}], F, S, R), once(or([${call}, unify(R, nodes([Y]))], unify(R, failure))));`);
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
compiling.delete(key);
|
|
270
|
+
return name;
|
|
271
|
+
};
|
|
272
|
+
return { compile };
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
// Definitions of functions SRL lacks, keyed like the SRL library.
|
|
276
|
+
export const NODE_FUNCTIONS = {
|
|
277
|
+
...Object.fromEntries(['md5', 'sha1', 'sha256', 'sha384', 'sha512'].map((h) => [`sh_ne_${h}`,
|
|
278
|
+
`implied_by(sh_ne_${h}(literal(A, datatype('${XSD}string')), literal(D, datatype('${XSD}string'))), digest('${h}', A, D));`])),
|
|
279
|
+
sh_ne_same_value: `implied_by(sh_ne_same_value(A, B, R), once(or([identical(A, B), unify(R, ${TRUE})], [srl_equal(A, B, 'true'), unify(R, ${TRUE})], [sh_ne_nan(A), sh_ne_nan(B), unify(R, ${TRUE})], unify(R, ${FALSE}))));
|
|
280
|
+
implied_by(sh_ne_nan(literal(L, datatype(D))), [srl_numeric_type(D, K), srl_float_kind(K), srl_read_number(K, L, 'nan')]);`,
|
|
281
|
+
// Execution functions derive their values from the captured seed, the
|
|
282
|
+
// expression and its evaluation context, so a proof can replay them.
|
|
283
|
+
// A double in [0, 1) whose fraction digits are the decimal digits of a digest.
|
|
284
|
+
sh_ne_rand: `implied_by(sh_ne_rand(E, F, S, [], literal(L, datatype('${XSD}double'))), [srl_execution(_, Seed), term_text([Seed, E, F, S], Text), digest('sha256', Text, Hex), regex_replace('[a-f]', Hex, '', D), atom_concat('0.', D, M), atom_concat(M, 'e0', L)]);`,
|
|
285
|
+
sh_ne_uuid: `implied_by(sh_ne_uuid(E, F, S, [], iri(I)), [srl_uuid(E, F, S, Id), atom_concat('urn:uuid:', Id, I)]);`,
|
|
286
|
+
sh_ne_struuid: `implied_by(sh_ne_struuid(E, F, S, [], literal(Id, datatype('${XSD}string'))), srl_uuid(E, F, S, Id));`,
|
|
287
|
+
sh_ne_bnode: `implied_by(sh_ne_bnode(E, F, S, Args, bnode('shnex', Text)), term_text([E, F, S, Args], Text));`,
|
|
288
|
+
};
|
|
289
|
+
|
|
290
|
+
export const NODE_COMMON = String.raw`
|
|
291
|
+
// Node expression results: nodes(List) or failure.
|
|
292
|
+
implied_by(sh_ne_var('focusNode', F, _, R), or([identical(F, 'sh_none'), unify(R, failure)], [not_identical(F, 'sh_none'), unify(R, nodes([F]))]));
|
|
293
|
+
implied_by(sh_ne_var(N, _, S, R), [not_identical(N, 'focusNode'), once(or([ent_member([N, V], S), unify(R, nodes([V]))], unify(R, nodes([]))))]);
|
|
294
|
+
implied_by(sh_ne_own_focus(F, N), or([identical(F, 'sh_none'), unify(N, failure)], [not_identical(F, 'sh_none'), unify(N, one(F))]));
|
|
295
|
+
implied_by(sh_ne_focus_nodes(F, R), or([identical(F, 'sh_none'), unify(R, failure)], [not_identical(F, 'sh_none'), unify(R, nodes([F]))]));
|
|
296
|
+
fact(sh_ne_focus(failure, failure), sh_ne_focus(nodes([]), none), sh_ne_focus(nodes([X]), one(X)), sh_ne_focus(nodes([_, _, ..._]), failure));
|
|
297
|
+
fact(sh_ne_at_most_one(failure, failure), sh_ne_at_most_one(nodes([]), nodes([])), sh_ne_at_most_one(nodes([X]), nodes([X])), sh_ne_at_most_one(nodes([_, _, ..._]), failure));
|
|
298
|
+
fact(sh_ne_first([], nodes([])), sh_ne_first([X, ..._], nodes([X])));
|
|
299
|
+
fact(sh_ne_exists(failure, failure), sh_ne_exists(nodes([]), nodes([${FALSE}])), sh_ne_exists(nodes([_, ..._]), nodes([${TRUE}])));
|
|
300
|
+
fact(sh_ne_count(failure, failure));
|
|
301
|
+
implied_by(sh_ne_count(nodes(L), nodes([N])), ent_count(L, N));
|
|
302
|
+
fact(sh_ne_append([], L, L));
|
|
303
|
+
implied_by(sh_ne_append([X, ...T], L, [X, ...R]), sh_ne_append(T, L, R));
|
|
304
|
+
fact(sh_ne_join(failure, _, failure), sh_ne_join(nodes(_), failure, failure));
|
|
305
|
+
implied_by(sh_ne_join(nodes(A), nodes(B), nodes(C)), sh_ne_append(A, B, C));
|
|
306
|
+
// Term equality: nodes are ground, so identity decides.
|
|
307
|
+
implied_by(sh_ne_in(X, [Y, ..._]), identical(X, Y));
|
|
308
|
+
implied_by(sh_ne_in(X, [_, ...T]), sh_ne_in(X, T));
|
|
309
|
+
fact(sh_ne_dedup([], _, []));
|
|
310
|
+
implied_by(sh_ne_dedup([X, ...T], Seen, R), [once(sh_ne_in(X, Seen)), sh_ne_dedup(T, Seen, R)]);
|
|
311
|
+
implied_by(sh_ne_dedup([X, ...T], Seen, [X, ...R]), [not(sh_ne_in(X, Seen)), sh_ne_dedup(T, [X, ...Seen], R)]);
|
|
312
|
+
fact(sh_ne_distinct(failure, failure));
|
|
313
|
+
implied_by(sh_ne_distinct(nodes(L), nodes(D)), sh_ne_dedup(L, [], D));
|
|
314
|
+
fact(sh_ne_without([], _, []));
|
|
315
|
+
implied_by(sh_ne_without([X, ...T], M, R), [once(sh_ne_in(X, M)), sh_ne_without(T, M, R)]);
|
|
316
|
+
implied_by(sh_ne_without([X, ...T], M, [X, ...R]), [not(sh_ne_in(X, M)), sh_ne_without(T, M, R)]);
|
|
317
|
+
fact(sh_ne_remove(failure, _, failure), sh_ne_remove(nodes(_), failure, failure));
|
|
318
|
+
implied_by(sh_ne_remove(nodes(M), nodes(N), nodes(R)), sh_ne_without(N, M, R));
|
|
319
|
+
fact(sh_ne_take([], _, []));
|
|
320
|
+
implied_by(sh_ne_take([X, ...T], N, R), or([eq(N, 0), unify(R, [])], [gt(N, 0), is(M, sub(N, 1)), sh_ne_take(T, M, R1), unify(R, [X, ...R1])]));
|
|
321
|
+
fact(sh_ne_drop([], _, []));
|
|
322
|
+
implied_by(sh_ne_drop([X, ...T], N, R), or([eq(N, 0), unify(R, [X, ...T])], [gt(N, 0), is(M, sub(N, 1)), sh_ne_drop(T, M, R)]));
|
|
323
|
+
fact(sh_ne_limit(failure, _, failure), sh_ne_offset(failure, _, failure));
|
|
324
|
+
implied_by(sh_ne_limit(nodes(L), N, nodes(R)), sh_ne_take(L, N, R));
|
|
325
|
+
implied_by(sh_ne_offset(nodes(L), N, nodes(R)), sh_ne_drop(L, N, R));
|
|
326
|
+
// sh_ne_all(Results, A): failure when any result fails, else nodes(Lists).
|
|
327
|
+
fact(sh_ne_all([], nodes([])));
|
|
328
|
+
implied_by(sh_ne_all([failure, ..._], failure), 'true');
|
|
329
|
+
implied_by(sh_ne_all([nodes(L), ...T], R), [sh_ne_all(T, A), or([unify(A, failure), unify(R, failure)], [unify(A, nodes(Ls)), unify(R, nodes([L, ...Ls]))])]);
|
|
330
|
+
fact(sh_ne_concat(failure, failure), sh_ne_concat(nodes([]), nodes([])));
|
|
331
|
+
implied_by(sh_ne_concat(nodes([L, ...Ls]), nodes(R)), [sh_ne_concat(nodes(Ls), nodes(M)), sh_ne_append(L, M, R)]);
|
|
332
|
+
fact(sh_ne_intersection(failure, failure), sh_ne_intersection(nodes([]), nodes([])));
|
|
333
|
+
implied_by(sh_ne_intersection(nodes([L, ...Ls]), nodes(R)), [sh_ne_dedup(L, [], D), sh_ne_within(D, Ls, R)]);
|
|
334
|
+
fact(sh_ne_within([], _, []));
|
|
335
|
+
implied_by(sh_ne_within([X, ...T], Ls, R), or([sh_ne_everywhere(X, Ls), sh_ne_within(T, Ls, R1), unify(R, [X, ...R1])], [not(sh_ne_everywhere(X, Ls)), sh_ne_within(T, Ls, R)]));
|
|
336
|
+
fact(sh_ne_everywhere(_, []));
|
|
337
|
+
implied_by(sh_ne_everywhere(X, [L, ...Ls]), [once(sh_ne_in(X, L)), sh_ne_everywhere(X, Ls)]);
|
|
338
|
+
fact(sh_ne_aggregate(_, failure, failure), sh_ne_aggregate('min', nodes([]), nodes([])), sh_ne_aggregate('max', nodes([]), nodes([])), sh_ne_aggregate('sum', nodes([]), nodes([0])));
|
|
339
|
+
implied_by(sh_ne_aggregate(K, nodes([X, ...T]), R), sh_ne_fold(K, [X, ...T], R));
|
|
340
|
+
implied_by(sh_ne_fold('min', L, R), once(or([srl_min(L, M), unify(R, nodes([M]))], unify(R, failure))));
|
|
341
|
+
implied_by(sh_ne_fold('max', L, R), once(or([srl_max(L, M), unify(R, nodes([M]))], unify(R, failure))));
|
|
342
|
+
implied_by(sh_ne_fold('sum', L, R), once(or([srl_sum(L, M), unify(R, nodes([M]))], unify(R, failure))));
|
|
343
|
+
// instancesOf fails for a type that is not an IRI.
|
|
344
|
+
fact(sh_ne_instances(failure, _, failure));
|
|
345
|
+
implied_by(sh_ne_instances(nodes(Ts), _, failure), not(sh_ne_iris(Ts)));
|
|
346
|
+
implied_by(sh_ne_instances(nodes(Ts), G, nodes(L)), [sh_ne_iris(Ts), findall(X, [ent_member(T, Ts), sh_instance(X, T, G)], L0), sh_ne_dedup(L0, [], L)]);
|
|
347
|
+
fact(sh_ne_iris([]));
|
|
348
|
+
implied_by(sh_ne_iris([iri(_), ...T]), sh_ne_iris(T));
|
|
349
|
+
// orderBy pairs each node with its first key, none when it has none.
|
|
350
|
+
fact(sh_ne_keyed(_, failure, _, failure), sh_ne_keyed(_, nodes(_), failure, failure));
|
|
351
|
+
implied_by(sh_ne_keyed(N, nodes([]), pairs(Ps), pairs([p(none, N), ...Ps])), 'true');
|
|
352
|
+
implied_by(sh_ne_keyed(N, nodes([K, ..._]), pairs(Ps), pairs([p(k(K), N), ...Ps])), 'true');
|
|
353
|
+
fact(sh_ne_sorted(failure, _, failure));
|
|
354
|
+
implied_by(sh_ne_sorted(pairs(Ps), D, nodes(R)), [sh_ne_sort(Ps, [], S), sh_ne_direction(D, S, Q), findall(N, ent_member(p(_, N), Q), R)]);
|
|
355
|
+
fact(sh_ne_direction('asc', S, S));
|
|
356
|
+
implied_by(sh_ne_direction('desc', S, Q), sh_ne_reverse(S, [], Q));
|
|
357
|
+
fact(sh_ne_reverse([], A, A));
|
|
358
|
+
implied_by(sh_ne_reverse([X, ...T], A, R), sh_ne_reverse(T, [X, ...A], R));
|
|
359
|
+
fact(sh_ne_sort([], A, A));
|
|
360
|
+
implied_by(sh_ne_sort([P, ...T], A, R), [sh_ne_insert(P, A, B), sh_ne_sort(T, B, R)]);
|
|
361
|
+
fact(sh_ne_insert(P, [], [P]));
|
|
362
|
+
implied_by(sh_ne_insert(P, [Q, ...T], R), or([sh_ne_before(P, Q), unify(R, [P, Q, ...T])], [not(sh_ne_before(P, Q)), sh_ne_insert(P, T, R1), unify(R, [Q, ...R1])]));
|
|
363
|
+
implied_by(sh_ne_before(p(none, _), p(k(_), _)), 'true');
|
|
364
|
+
// The order is computed before it is tested: srl_rank_order falls back to
|
|
365
|
+
// the term order when a bound order does not match.
|
|
366
|
+
implied_by(sh_ne_before(p(k(A), _), p(k(B), _)), [srl_rank_order(A, B, O), identical(O, '<')]);
|
|
367
|
+
// List parameter arguments: v(Node), unbound, or error.
|
|
368
|
+
fact(sh_ne_arg(failure, error), sh_ne_arg(nodes([]), unbound), sh_ne_arg(nodes([X]), v(X)), sh_ne_arg(nodes([_, _, ..._]), error));
|
|
369
|
+
implied_by(sh_ne_status(As, T), once(or([ent_member(error, As), unify(T, 'error')], [ent_member(unbound, As), unify(T, 'unbound')], unify(T, 'ok'))));
|
|
370
|
+
fact(sh_ne_conforms('error', _, _, failure), sh_ne_conforms('unbound', _, _, nodes([])));
|
|
371
|
+
implied_by(sh_ne_conforms('ok', v(X), v(Shape), R), once(or([sh_shape(Shape), sh_conforms(Shape, X), unify(R, nodes([${TRUE}]))], [sh_shape(Shape), not(sh_conforms(Shape, X)), unify(R, nodes([${FALSE}]))], unify(R, failure))));
|
|
372
|
+
implied_by(sh_ne_bound([A], R), or([unify(A, v(_)), unify(R, nodes([${TRUE}]))], [unify(A, unbound), unify(R, nodes([${FALSE}]))], [unify(A, error), unify(R, failure)]));
|
|
373
|
+
implied_by(sh_ne_coalesce(As, R), once(or([ent_member(v(X), As), unify(R, nodes([X]))], unify(R, failure))));
|
|
374
|
+
implied_by(sh_ne_choose(v(C), A, B, R), once(or([srl_ebv(C, 'true'), sh_ne_value(A, R)], [srl_ebv(C, 'false'), sh_ne_value(B, R)], unify(R, failure))));
|
|
375
|
+
fact(sh_ne_choose(unbound, _, _, failure), sh_ne_choose(error, _, _, failure));
|
|
376
|
+
fact(sh_ne_value(v(X), nodes([X])), sh_ne_value(unbound, failure), sh_ne_value(error, failure));
|
|
377
|
+
fact(sh_ne_truth([], []));
|
|
378
|
+
implied_by(sh_ne_truth([v(X), ...T], [B, ...Bs]), [once(or(srl_ebv(X, B), unify(B, 'error'))), sh_ne_truth(T, Bs)]);
|
|
379
|
+
implied_by(sh_ne_truth([A, ...T], ['error', ...Bs]), [not(unify(A, v(_))), sh_ne_truth(T, Bs)]);
|
|
380
|
+
implied_by(sh_ne_and([A, B], R), once(or([srl_and(A, B, Y), unify(R, nodes([Y]))], unify(R, failure))));
|
|
381
|
+
implied_by(sh_ne_or([A, B], R), once(or([srl_or(A, B, Y), unify(R, nodes([Y]))], unify(R, failure))));
|
|
382
|
+
`;
|
package/src/shacl.js
CHANGED
|
@@ -5,6 +5,7 @@
|
|
|
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#';
|
|
@@ -20,9 +21,9 @@ const CONSTRAINTS = ['class', 'datatype', 'nodeKind', 'minCount', 'maxCount', 'm
|
|
|
20
21
|
'memberShape', 'minListLength', 'maxListLength', 'uniqueMembers', 'equals', 'disjoint', 'subsetOf', 'lessThan',
|
|
21
22
|
'lessThanOrEquals', 'not', 'and', 'or', 'xone', 'node', 'property', 'someValue', 'qualifiedValueShape',
|
|
22
23
|
'qualifiedMinCount', 'qualifiedMaxCount', 'qualifiedValueShapesDisjoint', 'reifierShape', 'reificationRequired',
|
|
23
|
-
'closed', 'hasValue', 'in', 'rootClass', 'uniqueValuesFor'];
|
|
24
|
+
'closed', 'hasValue', 'in', 'rootClass', 'uniqueValuesFor', 'expression', 'nodeByExpression'];
|
|
24
25
|
const ANNOTATIONS = ['severity', 'message', 'deactivated', 'name', 'description', 'order', 'group', 'defaultValue', 'unit',
|
|
25
|
-
'intent', 'agentInstruction', 'codeIdentifier', 'codeType'];
|
|
26
|
+
'intent', 'agentInstruction', 'codeIdentifier', 'codeType', 'keyParameter', 'optional'];
|
|
26
27
|
const ALLOWED = new Set([...TARGETS, ...CONSTRAINTS, ...ANNOTATIONS, 'path', 'values', 'flags', 'ignoredProperties']);
|
|
27
28
|
// Shape-expecting parameters, whose values are compiled as shapes and checked for recursion.
|
|
28
29
|
const SHAPE_PARAMETERS = ['node', 'not', 'qualifiedValueShape', 'property', 'memberShape', 'reifierShape', 'someValue', 'targetWhere'];
|
|
@@ -36,9 +37,13 @@ const TRUE = (t) => literal(t, XSD + 'boolean') && t.args[0] === 'true';
|
|
|
36
37
|
const isIri = (t) => t instanceof Struct && t.name === 'iri';
|
|
37
38
|
const resource = (t) => t instanceof Struct && ['iri', 'bnode', 'triple'].includes(t.name);
|
|
38
39
|
const typeNames = (types) => types.map((t) => t.args?.[0]);
|
|
40
|
+
const TRUE_TERM = `literal('true', datatype('${XSD}boolean'))`;
|
|
39
41
|
|
|
40
|
-
|
|
41
|
-
|
|
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);
|
|
42
47
|
for (const severity of disallows) lines.push(`fact(sh_disallowed(${iri(severity)}));`);
|
|
43
48
|
if (disallows.length !== SHACL_DISALLOWS.length || disallows.some((d) => !SHACL_DISALLOWS.includes(d)))
|
|
44
49
|
lines.push('fact(sh_custom_disallows);');
|
|
@@ -123,6 +128,19 @@ export function compileShacl(quads, { disallows = SHACL_DISALLOWS } = {}) {
|
|
|
123
128
|
checking.add(node.id); node.refs.forEach(acyclic); checking.delete(node.id); checked.add(node.id);
|
|
124
129
|
};
|
|
125
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
|
+
};
|
|
126
144
|
const paths = new Map(), parsing = new Set();
|
|
127
145
|
const path = (term) => {
|
|
128
146
|
const key = write(term);
|
|
@@ -160,6 +178,9 @@ export function compileShacl(quads, { disallows = SHACL_DISALLOWS } = {}) {
|
|
|
160
178
|
}
|
|
161
179
|
parsing.delete(key); paths.set(key, name); return name;
|
|
162
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);
|
|
163
184
|
// sh:closed sh:ByTypes permits, for each rdf:type T of a value node, the
|
|
164
185
|
// properties that collectProperties(T) reaches in the shapes graph.
|
|
165
186
|
let byTypes = null;
|
|
@@ -194,24 +215,30 @@ export function compileShacl(quads, { disallows = SHACL_DISALLOWS } = {}) {
|
|
|
194
215
|
for (const node of shapes.values()) {
|
|
195
216
|
const { term: s, id, inactive } = node, S = write(s), v = `sh_values_${id}`, ok = `sh_ok_${id}`, bad = `sh_bad_${id}`;
|
|
196
217
|
const issue = `sh_issue_${id}`, focus = `sh_focus_${id}`, target = `sh_target_${id}`;
|
|
197
|
-
if (inactive) {
|
|
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
|
+
}
|
|
198
223
|
const p = one(s, 'path'), P = p ? write(p) : NONE;
|
|
199
224
|
if (p && types(s).includes(SH + 'NodeShape')) error(s, 'is a NodeShape with sh:path');
|
|
200
225
|
if (!p && types(s).includes(SH + 'PropertyShape')) error(s, 'is a PropertyShape without sh:path');
|
|
201
226
|
if (p) lines.push(`implied_by(${v}(F, V), ${path(p)}(F, V));`);
|
|
202
|
-
else lines.push(`
|
|
203
|
-
//
|
|
204
|
-
// sh:defaultValue supplies
|
|
205
|
-
const
|
|
206
|
-
if (!isIri(t) && !(t instanceof Struct && t.name === 'literal') && typeof t !== 'bigint') error(s, `needs an IRI or literal sh:${property}`);
|
|
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) => {
|
|
207
231
|
if (!p) error(s, `uses sh:${property} without a property path`);
|
|
208
|
-
return
|
|
209
|
-
};
|
|
210
|
-
const added =
|
|
211
|
-
for (const
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
lines.push(`implied_by(${
|
|
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
|
+
}
|
|
215
242
|
// A complex resultPath must remain interpretable in the standalone report.
|
|
216
243
|
const describePath = (term, seen = new Set()) => {
|
|
217
244
|
if (isIri(term) || seen.has(write(term))) return;
|
|
@@ -252,10 +279,16 @@ export function compileShacl(quads, { disallows = SHACL_DISALLOWS } = {}) {
|
|
|
252
279
|
const each = (property, fn) => values(s, property).forEach((t) => fn(t, constraint([property, t])));
|
|
253
280
|
const scalar = (property, fn) => { const t = one(s, property); if (t !== undefined) fn(t, constraint([property, t])); };
|
|
254
281
|
const helper = (name) => `sh_${name}_${id}_${nextHelper++}`;
|
|
255
|
-
|
|
256
|
-
|
|
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
|
+
}
|
|
257
288
|
const all = (property, fn) => values(s, property).forEach(fn);
|
|
258
|
-
all('targetNode', (t) => lines.push(
|
|
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}));`));
|
|
259
292
|
all('targetClass', (t) => lines.push(`implies(sh_instance(F, ${requireIri('targetClass', t)}, ${G}), ${target}(F));`));
|
|
260
293
|
all('targetSubjectsOf', (t) => lines.push(`implies([rdf(F, ${requireIri('targetSubjectsOf', t)}, _, ${G}), ent_resource(F)], ${target}(F));`));
|
|
261
294
|
all('targetObjectsOf', (t) => lines.push(`implies([rdf(X, ${requireIri('targetObjectsOf', t)}, F, ${G}), ent_resource(X)], ${target}(F));`));
|
|
@@ -344,7 +377,7 @@ export function compileShacl(quads, { disallows = SHACL_DISALLOWS } = {}) {
|
|
|
344
377
|
for (const item of rdfList(t)) lines.push(`fact(${allowed}(${write(item)}));`);
|
|
345
378
|
emit(c, [`${v}(F, V)`, `not(${allowed}(V))`], 'In');
|
|
346
379
|
});
|
|
347
|
-
each('hasValue', (t, c) => emit(c, [`
|
|
380
|
+
each('hasValue', (t, c) => emit(c, [`not(${v}(F, ${write(t)}))`], 'HasValue', NONE, P, write(t)));
|
|
348
381
|
each('rootClass', (t, c) => {
|
|
349
382
|
const member = helper('root');
|
|
350
383
|
for (const root of iris(s, 'rootClass', t)) {
|
|
@@ -374,15 +407,15 @@ export function compileShacl(quads, { disallows = SHACL_DISALLOWS } = {}) {
|
|
|
374
407
|
for (const child of node.properties) {
|
|
375
408
|
if (!child.inactive && !one(child.term, 'path')) error(child.term, 'is referenced by sh:property without sh:path');
|
|
376
409
|
if (!constraint(['property', child.term])) continue;
|
|
377
|
-
lines.push(`implied_by(${bad}(F), [${v}(F, V), not(sh_ok_${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)));`);
|
|
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)));`);
|
|
379
412
|
}
|
|
380
413
|
each('node', (t, c) => emit(c, [`${v}(F, V)`, `not(sh_ok_${shape(t).id}(V))`], 'Node', 'V', P, write(t)));
|
|
381
414
|
each('not', (t, c) => emit(c, [`${v}(F, V)`, `sh_ok_${shape(t).id}(V)`], 'Not', 'V', P, write(t)));
|
|
382
415
|
each('someValue', (t, c) => {
|
|
383
416
|
const some = helper('some');
|
|
384
417
|
lines.push(`implied_by(${some}(F), [${v}(F, V), sh_ok_${shape(t).id}(V)]);`);
|
|
385
|
-
emit(c, [`
|
|
418
|
+
emit(c, [`not(${some}(F))`], 'SomeValue', NONE, P, write(t));
|
|
386
419
|
});
|
|
387
420
|
for (const [name, children] of node.lists) {
|
|
388
421
|
const c = constraint([name, one(s, name)]);
|
|
@@ -428,6 +461,21 @@ export function compileShacl(quads, { disallows = SHACL_DISALLOWS } = {}) {
|
|
|
428
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)]);`);
|
|
429
462
|
emit(c, [`${v}(F, V)`, `${duplicate}(V)`], 'UniqueValuesFor', NONE, P, 'V');
|
|
430
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)'));
|
|
431
479
|
scalar('closed', (t, c) => {
|
|
432
480
|
const types = isIri(t) && t.args[0] === SH + 'ByTypes';
|
|
433
481
|
if (!types && !boolean('closed', t)) return;
|
|
@@ -440,9 +488,14 @@ export function compileShacl(quads, { disallows = SHACL_DISALLOWS } = {}) {
|
|
|
440
488
|
}
|
|
441
489
|
emit(c, [`${v}(F, X)`, 'ent_resource(X)', `rdf(X, Predicate, V, ${G})`, `not(${allowed}(X, Predicate))`], 'Closed', 'V', 'Predicate', 'X');
|
|
442
490
|
});
|
|
443
|
-
lines.push(`implied_by(${bad}(F), [${issue}(F, _, _, _, _, C), sh_blocking(C)]);`);
|
|
491
|
+
lines.push(`implied_by(${bad}(F), [${issue}(F, _, _, _, _, C), sh_blocking(C)${guard.map((g) => ', ' + g).join('')}]);`);
|
|
444
492
|
lines.push(`implied_by(${ok}(F), not(${bad}(F)));`);
|
|
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}));`);
|
|
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));`);
|
|
446
499
|
}
|
|
447
500
|
}
|
|
448
501
|
return lines.join('\n') + '\n';
|
|
@@ -549,4 +602,6 @@ implies([sh_result(R, S, F, P, V, C, K, I, X, G), not_identical(P, 'sh_none')],
|
|
|
549
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));
|
|
550
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));
|
|
551
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));
|
|
552
607
|
`;
|
package/src/srl.js
CHANGED
|
@@ -191,7 +191,7 @@ function nativeProgram(parts) {
|
|
|
191
191
|
// Clock and entropy are inputs captured once when the rule set is compiled.
|
|
192
192
|
// A saved proof carries this one fact; replay validates its shape and then
|
|
193
193
|
// recompiles the source. No other clause display becomes source authority.
|
|
194
|
-
function executionContext(context) {
|
|
194
|
+
export function executionContext(context) {
|
|
195
195
|
if (context === null) {
|
|
196
196
|
const bytes = new Uint8Array(32);
|
|
197
197
|
if (globalThis.crypto?.getRandomValues) globalThis.crypto.getRandomValues(bytes);
|
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.
|
|
2
|
+
export const VERSION = '0.8.3';
|