eyemind 0.8.0 → 0.8.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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
+ `;