eyemind 0.8.7 → 0.8.10

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/LS-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.7
5
+ Version: eyemind 0.8.10
6
6
  ```
7
7
 
8
8
  This document specifies Logic Script (LS): the syntax and meaning of its
@@ -565,6 +565,7 @@ primitive called outside its patterns raises an error.
565
565
  | `regex_match` | `regex_match(+P, +T)` | Some part of the atom `T` matches the regular expression `P`. |
566
566
  | `regex_find` | `regex_find(+P, +T, ?G)` | One solution per match of `P` in `T`, from left to right: `G` is the list of the matched text followed by each capture group's text, `''` for a group that took no part in the match. |
567
567
  | `regex_replace` | `regex_replace(+P, +T, +R, ?U)` | `U` is `T` with every match of `P` replaced by `R`. |
568
+ | `xml_content` | `xml_content(+T)` | The atom `T` is self-contained XML content, as defined below. |
568
569
 
569
570
  A character is a Unicode code point. Every primitive except `atom_concat`
570
571
  and `regex_find` has at most one solution.
@@ -603,6 +604,15 @@ their arguments. A primitive given an argument of the wrong kind for its
603
604
  patterns raises an error, as `atom_length(123, N)` does; one given arguments
604
605
  of the right kinds that has no solution fails, as `arg(5, f(1), A)` does.
605
606
 
607
+ `xml_content/1` tests the lexical space of [`rdf:XMLLiteral`](https://www.w3.org/TR/rdf12-concepts/#section-XMLLiteral).
608
+ The atom MUST be well-balanced, self-contained content as defined by
609
+ [XML 1.1](https://www.w3.org/TR/xml11/#NT-content) and conform to
610
+ [Namespaces in XML 1.0](https://www.w3.org/TR/xml-names/#Conformance) when
611
+ embedded inside an element with no namespace declarations. Empty content and
612
+ multiple top-level nodes are allowed. Only the predefined entities and
613
+ numeric character references are available. XML declarations and DTDs are
614
+ outside the content grammar. The test performs no I/O.
615
+
606
616
  All primitives take exactly the displayed number of arguments. `functor`
607
617
  and `univ` expose list structure as specified in [Section 2.2](#22-lists); use bracket
608
618
  syntax when writing lists.
package/README.md CHANGED
@@ -15,7 +15,7 @@ program, a JavaScript library and a browser application.
15
15
  The examples are 152 runnable programs, each with a card deck and saved
16
16
  conclusions, proofs and check reports. The specification defines the language,
17
17
  the proof format and how a proof is checked; its conformance suite has
18
- 1246 cases that test language and proof behavior, and runs
18
+ 1247 cases that test language and proof behavior, and runs
19
19
  [in your browser](https://eyereasoner.github.io/eyemind/playground/conformance).
20
20
 
21
21
  ## Contents
@@ -301,9 +301,11 @@ A `.srl` file is a [SPARQL 1.2 RL](https://www.w3.org/TR/sparql12-rl/) rule
301
301
  set over the RDF data given with it; the result is the inference graph, as
302
302
  Turtle (`--all` adds the base graph). Rules become `implies`, `NOT` becomes
303
303
  `not`, `GROUP` becomes `findall_sorted`, and a SPARQL error is a goal that
304
- fails. Decimals are exact (`0.1 + 0.2` is `0.3`) and floats are binary64.
304
+ fails. Local variable names in `NOT` and `GROUP` cannot be bound again
305
+ elsewhere in the same rule. Decimals are exact (`0.1 + 0.2` is `0.3`) and
306
+ floats are binary64.
305
307
  `NOW()` and `UUID()` use a clock and seed captured at compilation, which a
306
- saved proof retains. All 342 W3C SPARQL 1.2 RL tests pass.
308
+ saved proof retains. All 368 W3C SPARQL 1.2 RL tests pass.
307
309
 
308
310
  ```sh
309
311
  eyemind -c rules.srl facts.ttl # the inference graph, with a checked proof
@@ -319,7 +321,9 @@ is Turtle with the new triples and reports.
319
321
  rules, including the datatype map of its table 8: value equality and
320
322
  difference, membership across lexical forms, and ill-typed literals for the
321
323
  XSD numeric, string, temporal and binary types, `rdf:PlainLiteral` and
322
- `rdf:XMLLiteral`. It reports contradictions as `ent:Conflict` records
324
+ `rdf:XMLLiteral`. XML literal validation checks well-formed content and
325
+ namespaces. Equality and difference for XML literals use their lexical forms.
326
+ It reports contradictions as `ent:Conflict` records
323
327
  instead of inferring everything from them, and passes all 273 cases of the
324
328
  [MobiBench](https://github.com/william-vw/mobibench) OWL 2 RL suite.
325
329
  - `--qudt` normalizes QUDT quantity values and CDT literals to SI units from
@@ -652,7 +656,7 @@ EYEMIND_PROPERTY_SCALE=20 npm test -- -k properties # deeper generated tests
652
656
  node tools/update-examples.js # regenerate example artifacts after an intended change
653
657
  npm run sync # refresh the cached upstream test suites
654
658
  node conformance/run.js --command "my-eyemind" # run the conformance suite against another implementation
655
- node bench/run.js # the RDF reasoning benchmark; see bench/README.md
659
+ npm run bench # the RDF reasoning benchmark; see bench/README.md
656
660
  ./release patch "Describe the changes" # test, tag and publish a release
657
661
  ```
658
662
 
@@ -662,6 +666,11 @@ The playground tests need Chrome (`CHROME` names it). A full run writes
662
666
  [REPORT.md](REPORT.md) and the [W3C EARL reports](reports/README.md); the
663
667
  [upstream suites](test/UPSTREAM.md) are cached in Git-ignored `.cache/`.
664
668
 
669
+ The example tests reproduce every saved conclusion and proof, then check
670
+ the proofs from disk. The deck tests check the documented claims and run
671
+ commands with extra goals, conversions or redirects. The corpus and CLI
672
+ tests cover the standard example commands.
673
+
665
674
  ## The name
666
675
 
667
676
  **eyemind** joins *eye* and *mind*: facts and rules lead to conclusions whose reasoning can be inspected and checked.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "eyemind",
3
- "version": "0.8.7",
3
+ "version": "0.8.10",
4
4
  "description": "A dependency-free Logic Script (LS) reasoner with forward and backward reasoning, checkable proofs, and RDF 1.2, Notation3 (N3), SPARQL 1.2 RL (SRL) and Logical English (LE) interoperability.",
5
5
  "type": "module",
6
6
  "main": "./src/index.js",
@@ -22,7 +22,8 @@
22
22
  ],
23
23
  "scripts": {
24
24
  "test": "node test/run.js",
25
- "sync": "node tools/sync.js"
25
+ "sync": "node tools/sync.js",
26
+ "bench": "node bench/run.js"
26
27
  },
27
28
  "engines": {
28
29
  "node": ">=18"
package/src/builtins.js CHANGED
@@ -17,6 +17,7 @@ import {
17
17
  } from './terms.js';
18
18
  import { DIGESTS, utf8 } from './digest.js';
19
19
  import { floatText, write } from './writer.js';
20
+ import { isXmlContent } from './xml.js';
20
21
 
21
22
  function comparison(holds) {
22
23
  return (args, resolved, env) => holds(arith.compare(args[0], args[1], env));
@@ -280,6 +281,7 @@ export const TESTS = new Map([
280
281
  ['term_text/2', termText],
281
282
  ['float64/4', float64],
282
283
  ['regex_match/2', regexMatch],
284
+ ['xml_content/1', (args, resolved) => isXmlContent(text('xml_content/1', resolved[0]))],
283
285
  ['regex_replace/4', regexReplace],
284
286
  ]);
285
287
 
package/src/cli.js CHANGED
@@ -192,7 +192,7 @@ export function main(argv, io) {
192
192
  const document = proofFile === null ? null : readSource(proofFile, io);
193
193
  const loaded = loadInputs(files.map((file) => [readSource(file, io), file === '-' ? '<stdin>' : file]), io,
194
194
  { base, messageInputs: io.messageInputs, odrl, ...rdfLogic,
195
- srlContext: document !== null && files.some((file) => inputKind(file) === 'srl') ? srlContextFromProof(document) : null });
195
+ srlContext: document !== null && (rdfLogic.shacl || files.some((file) => inputKind(file) === 'srl')) ? srlContextFromProof(document) : null });
196
196
  const program = loaded.program;
197
197
  if (printProgram) {
198
198
  stdout(loaded.text);
package/src/closure.js CHANGED
@@ -15,10 +15,11 @@
15
15
  import { PRIMITIVE_KEYS, primitive } from './builtins.js';
16
16
  import { freshClause, sameVariant, text, variant } from './common.js';
17
17
  import { INSPECTION_KEYS } from './inspection.js';
18
+ import { bucketEntries, positionIndexes } from './program.js';
18
19
  import { Lettering, write } from './writer.js';
19
20
  import {
20
- Env, EyemindError, Struct, Var, copyResolved, deref, flattenConjunction, freshTerm, identity, isCallable, isGround, key,
21
- isGroundButAnonymous, listFromItems, sortCollected, unify, variables,
21
+ Env, EyemindError, Struct, Var, copyResolved, deref, flattenConjunction, freshTerm, identity, indexKey, isCallable, isGround,
22
+ isGroundButAnonymous, key, keyArity, listFromItems, sortCollected, unify, variables,
22
23
  } from './terms.js';
23
24
 
24
25
  // Terms as a failure message shows them, variables lettered A, B, ... across
@@ -243,12 +244,23 @@ export class Settler {
243
244
  const goalKey = key(call);
244
245
  const mark = env.mark();
245
246
  if (this.derivedKeys.has(goalKey)) {
246
- const facts = this.listing(goalKey);
247
+ const entry = this.listing(goalKey);
247
248
  reliance.listings.add(goalKey);
249
+ let facts = entry.facts;
250
+ for (const [position, index] of entry.positions.entries()) {
251
+ // Only use buckets that leave no potentially matching facts out.
252
+ if (index === null || index[1].length) continue;
253
+ const argument = indexKey(call.args[position], env);
254
+ if (argument === undefined) continue;
255
+ const candidates = bucketEntries(index[0].get(argument));
256
+ if (candidates.length < facts.length) facts = candidates;
257
+ if (!facts.length) break;
258
+ }
248
259
  for (const fact of facts) {
249
260
  // A derived pattern is freshened at every use.
250
- if (!isGround(fact)) reliance.inspected = true;
251
- if (unify(call, isGround(fact) ? fact : freshTerm(fact, `pattern${++this.serial}`), env)) yield;
261
+ const ground = entry.ground || isGround(fact);
262
+ if (!ground) reliance.inspected = true;
263
+ if (unify(call, ground ? fact : freshTerm(fact, `pattern${++this.serial}`), env)) yield;
252
264
  env.undo(mark);
253
265
  }
254
266
  }
@@ -308,10 +320,18 @@ export class Settler {
308
320
  if (entry === undefined) {
309
321
  const facts = this.source.facts(goalKey);
310
322
  if (facts === null) throw new Unsettled();
311
- entry = { facts, checked: false, failure: null, subject: null, unsettled: false, reported: false, reliance: null };
323
+ const ground = facts.every((fact) => isGround(fact));
324
+ const arity = keyArity(goalKey);
325
+ // Large ground listings are read many times while expanding tables.
326
+ // The buckets retain listing order. Leave patterns and malformed facts
327
+ // on the ordinary scan path.
328
+ const positions = ground && arity && facts.length >= 16 &&
329
+ facts.every((fact) => fact instanceof Struct && key(fact) === goalKey)
330
+ ? positionIndexes(facts, (fact) => fact, arity) : [];
331
+ entry = { facts, ground, positions, checked: false, failure: null, subject: null, unsettled: false, reported: false, reliance: null };
312
332
  this.listings.set(goalKey, entry);
313
333
  }
314
- return entry.facts;
334
+ return entry;
315
335
  }
316
336
 
317
337
  // A table holds when expanding its call gives exactly its answers, in order.
package/src/fidelity.js CHANGED
@@ -50,6 +50,7 @@ export function callQuestions(program, goals, claims) {
50
50
  export function replayer(program, settler, stepOf, used) {
51
51
  const confirmed = new Map();
52
52
  const active = new Set();
53
+ const settledCalls = new Map();
53
54
  // The steps a firing's replay followed, each as [replayed, recorded]: once
54
55
  // the whole firing has replayed, each must be its step up to renaming.
55
56
  let followed = [];
@@ -104,10 +105,24 @@ export function replayer(program, settler, stepOf, used) {
104
105
  // an answer agrees with the use; null when its search consults derived
105
106
  // facts, whose support only steps show.
106
107
  function answered(goal, use, env) {
107
- const outcome = settler.answers(copyResolved(goal, env));
108
- if (outcome.status === 'unsettled' || (outcome.status === 'settled' && outcome.listings.length)) return null;
109
- for (const item of outcome.tables) used.tables.add(item);
110
- if (outcome.status !== 'settled') return false;
108
+ const call = copyResolved(goal, env);
109
+ const id = variant(call, true);
110
+ let outcome = settledCalls.get(id);
111
+ if (outcome === undefined) {
112
+ const checked = settler.answers(call);
113
+ if (checked.status === 'unsettled') return null;
114
+ if (checked.status === 'settled' && checked.listings.length) {
115
+ // The table depends on derived facts. Each use still follows its step.
116
+ settledCalls.set(id, null);
117
+ return null;
118
+ }
119
+ for (const item of checked.tables) used.tables.add(item);
120
+ if (checked.status !== 'settled') return false;
121
+ // Dependencies have already been checked and marked used for this call.
122
+ outcome = { answers: checked.answers, inspected: checked.inspected };
123
+ settledCalls.set(id, outcome);
124
+ }
125
+ if (outcome === null) return null;
111
126
  // The answer that is the use, up to renaming, is the one the firing
112
127
  // took; failing that, the first that can still become it.
113
128
  const target = variant(use);
package/src/formats.js CHANGED
@@ -92,7 +92,7 @@ function load(inputs, io, { base = null, messageInputs = null, srlContext = null
92
92
  Object.assign(prefixes, parsed.prefixes);
93
93
  quads.push(...parsed.quads);
94
94
  });
95
- return compileRdfLogic({ quads, prefixes }, { profiles, source: inputs.map(([, n]) => n).join(', ') });
95
+ return compileRdfLogic({ quads, prefixes }, { profiles, source: inputs.map(([, n]) => n).join(', '), context: srlContext });
96
96
  }
97
97
  if (odrl) {
98
98
  if (inputs.length !== 1) throw new EyemindError('--odrl takes one Turtle snapshot containing policies, requests and SOTW');
package/src/program.js CHANGED
@@ -335,7 +335,7 @@ class Bucket {
335
335
  const NO_ENTRIES = Object.freeze([]);
336
336
 
337
337
  // The entries a positionIndexes map gives for a value, as a list.
338
- function bucketEntries(found) {
338
+ export function bucketEntries(found) {
339
339
  if (found === undefined) return NO_ENTRIES;
340
340
  return found instanceof Bucket ? found.entries : [found];
341
341
  }
package/src/rdf-values.js CHANGED
@@ -97,15 +97,7 @@ implied_by(rv_lexical(rvXsd + 'NCName', L), regex_match('^[\\p{L}_][\\p{L}\\p{N}
97
97
  implied_by(rv_lexical(rvXsd + 'NMTOKEN', L), regex_match('^[\\p{L}\\p{N}._:\\-]+$', L));
98
98
  // rdf:PlainLiteral: text, then @ and an empty or well-formed language tag.
99
99
  implied_by(rv_lexical(rvRdf + 'PlainLiteral', L), regex_match('@(?:[A-Za-z]{1,8}(?:-[A-Za-z0-9]{1,8})*)?$', L));
100
- implied_by(rv_lexical(rvRdf + 'XMLLiteral', L), rv_xml(L));
101
- // A well-formed XML fragment, as far as its tags: each opened tag closes in
102
- // order, and no markup character is left outside a tag.
103
- implied_by(rv_xml(L), [findall([C, N, E], regex_find('<(/?)([\\p{L}_:][\\p{L}\\p{N}._:\\-]*)(?:\\s[^<>]*?)?(/?)>', L, [_, C, N, E]), Tags),
104
- regex_replace('<(/?)([\\p{L}_:][\\p{L}\\p{N}._:\\-]*)(?:\\s[^<>]*?)?(/?)>', L, '', Rest), not(regex_match('[<>]', Rest)), rv_xml_balanced(Tags, [])]);
105
- fact(rv_xml_balanced([], []));
106
- implied_by(rv_xml_balanced([['', _, '/'], ...T], S), rv_xml_balanced(T, S));
107
- implied_by(rv_xml_balanced([['', N, ''], ...T], S), rv_xml_balanced(T, [N, ...S]));
108
- implied_by(rv_xml_balanced([['/', N, ''], ...T], [N, ...S]), rv_xml_balanced(T, S));
100
+ implied_by(rv_lexical(rvRdf + 'XMLLiteral', L), xml_content(L));
109
101
  implied_by(rv_lexical(rvXsd + 'hexBinary', L), regex_match('^[ \\t\\r\\n]*(?:[0-9A-Fa-f]{2})*[ \\t\\r\\n]*$', L));
110
102
  implied_by(rv_lexical(rvXsd + 'base64Binary', L), [regex_replace('[ \\t\\r\\n]', L, '', S), regex_match('^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/][AQgw]==|[A-Za-z0-9+/]{2}[AEIMQUYcgkosw048]=)?$', S)]);
111
103
  implied_by(rv_exact(T), [rv_valid(T), srl_num(T, K, _), rv_exact_kind(K)]);
package/src/shacl-expr.js CHANGED
@@ -55,10 +55,8 @@ const NAMED = ['var', 'pathValues', 'exists', 'if', 'distinct', 'intersection',
55
55
 
56
56
  // The expressions of one graph. The shapes compiler supplies its graph
57
57
  // access, its paths and the conformance predicates of its shapes.
58
- export function nodeExpressions({ G, lines, needs, index, rdfList, path, conforms, error }) {
58
+ export function nodeExpressions({ G, lines, needs, index, rdfList, path, conforms, error, fresh }) {
59
59
  const memo = new Map(), compiling = new Set();
60
- let next = 0;
61
- const fresh = (kind) => `sh_expr_${kind}_${next++}`;
62
60
  // Custom functions declared in the shapes graph by sh:bodyExpression.
63
61
  const custom = { list: new Map(), named: new Map() };
64
62
  for (const [key, properties] of index) {
@@ -230,7 +228,7 @@ export function nodeExpressions({ G, lines, needs, index, rdfList, path, conform
230
228
  const list = `[${args.map((_, i) => 'A' + i).join(', ')}]`;
231
229
  if (p === SHNEX + 'conformsToShape') {
232
230
  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)']);
231
+ rule([...evaluated, `sh_ne_status(${list}, T)`, `sh_ne_conforms(T, A0, A1, ${G}, R)`]);
234
232
  } else if (fn === null) {
235
233
  // A custom list parameter function: its body sees only its arguments.
236
234
  const body = compile(custom.list.get(write(new Struct('iri', [p]))));
@@ -367,8 +365,8 @@ implied_by(sh_ne_before(p(k(A), _), p(k(B), _)), [srl_rank_order(A, B, O), ident
367
365
  // List parameter arguments: v(Node), unbound, or error.
368
366
  fact(sh_ne_arg(failure, error), sh_ne_arg(nodes([]), unbound), sh_ne_arg(nodes([X]), v(X)), sh_ne_arg(nodes([_, _, ..._]), error));
369
367
  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))));
368
+ fact(sh_ne_conforms('error', _, _, _, failure), sh_ne_conforms('unbound', _, _, _, nodes([])));
369
+ implied_by(sh_ne_conforms('ok', v(X), v(Shape), G, R), once(or([sh_shape(Shape, G), sh_conforms(Shape, X, G), unify(R, nodes([${TRUE}]))], [sh_shape(Shape, G), not(sh_conforms(Shape, X, G)), unify(R, nodes([${FALSE}]))], unify(R, failure))));
372
370
  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
371
  implied_by(sh_ne_coalesce(As, R), once(or([ent_member(v(X), As), unify(R, nodes([X]))], unify(R, failure))));
374
372
  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))));
package/src/shacl.js CHANGED
@@ -53,6 +53,8 @@ export function compileShacl(quads, { disallows = SHACL_DISALLOWS, needs = new S
53
53
  graphs.get(key).triples.push([s, p, o]);
54
54
  }
55
55
  let nextShape = 0, nextPath = 0, nextConstraint = 0, nextHelper = 0;
56
+ let nextExpression = 0;
57
+ const freshExpression = (kind) => `sh_expr_${kind}_${nextExpression++}`;
56
58
  for (const { graph, triples } of graphs.values()) {
57
59
  const G = write(graph), index = new Map(), terms = new Map(), reifiers = new Map();
58
60
  for (const [s, p, o] of triples) {
@@ -178,7 +180,7 @@ export function compileShacl(quads, { disallows = SHACL_DISALLOWS, needs = new S
178
180
  }
179
181
  parsing.delete(key); paths.set(key, name); return name;
180
182
  };
181
- const expressions = nodeExpressions({ G, lines, needs, index, rdfList, path, error,
183
+ const expressions = nodeExpressions({ G, lines, needs, index, rdfList, path, error, fresh: freshExpression,
182
184
  conforms: (t) => `sh_ok_${shape(t).id}` });
183
185
  const expression = (t) => expressions.compile(t);
184
186
  // sh:closed sh:ByTypes permits, for each rdf:type T of a value node, the
@@ -217,7 +219,7 @@ export function compileShacl(quads, { disallows = SHACL_DISALLOWS, needs = new S
217
219
  const issue = `sh_issue_${id}`, focus = `sh_focus_${id}`, target = `sh_target_${id}`;
218
220
  if (inactive) {
219
221
  lines.push(`fact(${ok}(_));`);
220
- if (isIri(s)) lines.push(`fact(sh_shape(${S}));`, `implied_by(sh_conforms(${S}, X), ${ok}(X));`);
222
+ if (isIri(s)) lines.push(`fact(sh_shape(${S}, ${G}));`, `implied_by(sh_conforms(${S}, X, ${G}), ${ok}(X));`);
221
223
  continue;
222
224
  }
223
225
  const p = one(s, 'path'), P = p ? write(p) : NONE;
@@ -474,7 +476,7 @@ export function compileShacl(quads, { disallows = SHACL_DISALLOWS, needs = new S
474
476
  values(s, 'expression').forEach((t) => copy(t));
475
477
  each('expression', (t, c) => emit(c, [`${v}(F, V)`, `${expression(t)}(F, [['value', V]], R)`, `not(unify(R, nodes([${TRUE_TERM}])))`],
476
478
  '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))'],
479
+ each('nodeByExpression', (t, c) => emit(c, [`${v}(F, V)`, `${expression(t)}(V, [], nodes(L))`, 'ent_member(Shape, L)', `sh_shape(Shape, ${G})`, `not(sh_conforms(Shape, V, ${G}))`],
478
480
  'NodeByExpression', 'V', P, 'source(Shape)'));
479
481
  scalar('closed', (t, c) => {
480
482
  const types = isIri(t) && t.args[0] === SH + 'ByTypes';
@@ -491,7 +493,7 @@ export function compileShacl(quads, { disallows = SHACL_DISALLOWS, needs = new S
491
493
  lines.push(`implied_by(${bad}(F), [${issue}(F, _, _, _, _, C), sh_blocking(C)${guard.map((g) => ', ' + g).join('')}]);`);
492
494
  lines.push(`implied_by(${ok}(F), not(${bad}(F)));`);
493
495
  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));`);
496
+ if (isIri(s) && !dynamic(node)) lines.push(`fact(sh_shape(${S}, ${G}));`, `implied_by(sh_conforms(${S}, X, ${G}), ${ok}(X));`);
495
497
  }
496
498
  if (evaluate && G === "'default_graph'") {
497
499
  const scope = [...evaluate.scope ?? []].map(([k, t]) => `[${JSON.stringify(k)}, ${write(t)}]`);
@@ -332,12 +332,28 @@ function stronglyConnectedComponents(size, edges) {
332
332
 
333
333
  function sequentialWellFormednessDiagnostics(clauses, ruleNameValue, prefixes = {}, initialBound = new Set()) {
334
334
  const diagnostics = [];
335
+ const error = (code, message) => diagnostics.push({
336
+ code, severity: 'error', rule: ruleNameValue,
337
+ message: `${displayRuleName(ruleNameValue, prefixes)} ${message}`,
338
+ });
335
339
 
336
- function visit(items, initialBound, scopeLabel) {
340
+ function visit(items, initialBound, initialInUse, scopeLabel) {
337
341
  const bound = new Set(initialBound);
342
+ const inUse = new Set(initialInUse);
343
+ // Local names from a nested sequence remain reserved after it finishes.
344
+ const reserveLocals = (inner) => {
345
+ for (const names of [inner.bound, inner.inUse]) {
346
+ for (const name of names) if (!bound.has(name)) inUse.add(name);
347
+ }
348
+ };
338
349
  for (const clause of items) {
339
350
  if (clause.type === 'triple' || clause.type === 'path') {
340
- collectTripleVars(clause.triple, bound);
351
+ const names = new Set();
352
+ collectTripleVars(clause.triple, names);
353
+ for (const name of names) {
354
+ if (inUse.has(name)) error('variable-already-in-use', `pattern reuses ?${name}, which is already in use${scopeLabel}`);
355
+ bound.add(name);
356
+ }
341
357
  } else if (clause.type === 'filter') {
342
358
  for (const variable of expressionVariables(clause.expr)) {
343
359
  if (!bound.has(variable)) {
@@ -357,6 +373,8 @@ function sequentialWellFormednessDiagnostics(clauses, ruleNameValue, prefixes =
357
373
  rule: ruleNameValue,
358
374
  message: `${displayRuleName(ruleNameValue, prefixes)} SET assigns ?${clause.variable}, but that variable is already bound${scopeLabel}`,
359
375
  });
376
+ } else if (inUse.has(clause.variable)) {
377
+ error('variable-already-in-use', `SET assigns ?${clause.variable}, but that variable is already in use${scopeLabel}`);
360
378
  }
361
379
  for (const variable of expressionVariables(clause.expr)) {
362
380
  if (!bound.has(variable)) {
@@ -370,34 +388,35 @@ function sequentialWellFormednessDiagnostics(clauses, ruleNameValue, prefixes =
370
388
  }
371
389
  bound.add(clause.variable);
372
390
  } else if (clause.type === 'not') {
373
- visit(clause.body, bound, ' inside NOT');
391
+ reserveLocals(visit(clause.body, bound, inUse, ' inside NOT'));
374
392
  } else if (clause.type === 'group') {
375
393
  // Only keys correlate the group pattern with the incoming mapping.
394
+ const keys = new Set(clause.keys);
376
395
  const initial = new Set(clause.keys.filter((key) => bound.has(key)));
377
- const inner = visit(clause.pattern, initial, ' inside GROUP');
378
- const error = (code, message) => diagnostics.push({
379
- code, severity: 'error', rule: ruleNameValue,
380
- message: `${displayRuleName(ruleNameValue, prefixes)} ${message}`,
381
- });
396
+ const reserved = new Set(inUse);
397
+ for (const name of bound) if (!keys.has(name)) reserved.add(name);
398
+ const inner = visit(clause.pattern, initial, reserved, ' inside GROUP');
382
399
  for (const key of clause.keys) {
383
- if (!inner.has(key)) error('unbound-group-key', `GROUP key ?${key} is not bound in the group pattern`);
400
+ if (!inner.bound.has(key)) error('unbound-group-key', `GROUP key ?${key} is not bound in the group pattern`);
384
401
  }
385
402
  const assigned = new Set();
386
403
  for (const aggregation of clause.aggregations) {
387
404
  const { variable, function: fn } = aggregation;
388
- if (inner.has(variable) || bound.has(variable)) error('aggregation-variable-already-bound', `GROUP assigns ?${variable}, but that variable is already bound`);
405
+ if (inner.bound.has(variable) || bound.has(variable)) error('aggregation-variable-already-bound', `GROUP assigns ?${variable}, but that variable is already bound`);
406
+ else if (inner.inUse.has(variable)) error('variable-already-in-use', `GROUP assigns ?${variable}, but that variable is already in use`);
389
407
  if (assigned.has(variable)) error('duplicate-aggregation-variable', `GROUP assigns ?${variable} more than once`);
390
- if (fn.argument !== '*' && !inner.has(fn.argument)) error('unbound-aggregation-argument', `GROUP aggregate uses unbound variable ?${fn.argument}`);
408
+ if (fn.argument !== '*' && !inner.bound.has(fn.argument)) error('unbound-aggregation-argument', `GROUP aggregate uses unbound variable ?${fn.argument}`);
391
409
  assigned.add(variable);
392
410
  }
393
411
  for (const key of clause.keys) bound.add(key);
394
412
  for (const variable of assigned) bound.add(variable);
413
+ reserveLocals(inner);
395
414
  }
396
415
  }
397
- return bound;
416
+ return { bound, inUse };
398
417
  }
399
418
 
400
- visit(clauses, initialBound, '');
419
+ visit(clauses, initialBound, new Set(), '');
401
420
  return diagnostics;
402
421
  }
403
422
 
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.7';
2
+ export const VERSION = '0.8.10';
package/src/xml.js ADDED
@@ -0,0 +1,142 @@
1
+ // Self-contained XML 1.1 content (RDF 1.2 Concepts, Appendix A.2), with
2
+ // Namespaces in XML 1.0. The scanner needs no document wrapper, DTD or I/O.
3
+ // https://www.w3.org/TR/xml11/#sec-well-formed
4
+ // https://www.w3.org/TR/xml-names/#Conformance
5
+ const NC_START = String.raw`A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u{10000}-\u{EFFFF}`;
6
+ const NC_CHAR = NC_START + String.raw`0-9.\-\u00B7\u0300-\u036F\u203F-\u2040`;
7
+ const NC_NAME = `[${NC_START}][${NC_CHAR}]*`;
8
+ const QNAME = new RegExp(NC_NAME + '(?::' + NC_NAME + ')?', 'uy');
9
+ const PI_NAME = new RegExp(NC_NAME, 'uy');
10
+ const SPACE = /[ \t\n]+/y;
11
+ const DATA = /[^<&]+/y;
12
+ const REFERENCE = /&(?:(amp|lt|gt|apos|quot)|#([0-9]+)|#x([0-9a-fA-F]+));/y;
13
+ const ENTITIES = { amp: '&', lt: '<', gt: '>', apos: "'", quot: '"' };
14
+ const XML = 'http://www.w3.org/XML/1998/namespace';
15
+ const XMLNS = 'http://www.w3.org/2000/xmlns/';
16
+ const INVALID_RAW = /[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F-\u0084\u0086-\u009F\uD800-\uDFFF\uFFFE\uFFFF]/u;
17
+
18
+ function match(pattern, text, at) {
19
+ pattern.lastIndex = at;
20
+ return pattern.exec(text);
21
+ }
22
+
23
+ function reference(text, at) {
24
+ const ref = match(REFERENCE, text, at);
25
+ if (!ref) return null;
26
+ const [raw, name, decimal, hex] = ref;
27
+ if (name) return [raw.length, ENTITIES[name]];
28
+ const code = decimal === undefined ? Number.parseInt(hex, 16) : Number(decimal);
29
+ if (code === 0 || code > 0x10FFFF || (code >= 0xD800 && code <= 0xDFFF) || code === 0xFFFE || code === 0xFFFF) return null;
30
+ return [raw.length, String.fromCodePoint(code)];
31
+ }
32
+
33
+ export function isXmlContent(text) {
34
+ if (INVALID_RAW.test(text)) return false;
35
+ text = text.replace(/\r[\n\u0085]?|[\u0085\u2028]/gu, '\n');
36
+ const namespaces = new Map([['xml', XML]]), open = [];
37
+ let at = 0;
38
+ const take = (token) => {
39
+ if (!text.startsWith(token, at)) return false;
40
+ at += token.length;
41
+ return true;
42
+ };
43
+ const read = (pattern) => {
44
+ const found = match(pattern, text, at)?.[0];
45
+ if (found) at += found.length;
46
+ return found;
47
+ };
48
+ const attributes = () => {
49
+ const found = new Map();
50
+ while (read(SPACE) && text[at] !== '>' && text[at] !== '/') {
51
+ const name = read(QNAME);
52
+ if (!name || found.has(name)) return null;
53
+ read(SPACE);
54
+ if (!take('=')) return null;
55
+ read(SPACE);
56
+ const quote = text[at++];
57
+ if (quote !== '"' && quote !== "'") return null;
58
+ const end = text.indexOf(quote, at);
59
+ if (end < 0) return null;
60
+ const raw = text.slice(at, end);
61
+ if (raw.includes('<')) return null;
62
+ let value = '', start = 0;
63
+ for (let amp = raw.indexOf('&'); amp >= 0; amp = raw.indexOf('&', start)) {
64
+ const ref = reference(raw, amp);
65
+ if (!ref) return null;
66
+ value += raw.slice(start, amp).replace(/[\t\n]/g, ' ') + ref[1];
67
+ start = amp + ref[0];
68
+ }
69
+ found.set(name, value + raw.slice(start).replace(/[\t\n]/g, ' '));
70
+ at = end + 1;
71
+ }
72
+ return found;
73
+ };
74
+ const restore = (changes) => {
75
+ for (const [prefix, value] of changes) {
76
+ if (value === undefined) namespaces.delete(prefix);
77
+ else namespaces.set(prefix, value);
78
+ }
79
+ };
80
+ while (at < text.length) {
81
+ if (take('<!--')) {
82
+ const end = text.indexOf('--', at);
83
+ if (end < 0 || !text.startsWith('-->', end)) return false;
84
+ at = end + 3;
85
+ } else if (take('<![CDATA[')) {
86
+ const end = text.indexOf(']]>', at);
87
+ if (end < 0) return false;
88
+ at = end + 3;
89
+ } else if (take('<?')) {
90
+ const target = read(PI_NAME);
91
+ if (!target || target.toLowerCase() === 'xml') return false;
92
+ if (take('?>')) continue;
93
+ if (!read(SPACE)) return false;
94
+ const end = text.indexOf('?>', at);
95
+ if (end < 0) return false;
96
+ at = end + 2;
97
+ } else if (take('</')) {
98
+ const name = read(QNAME), frame = open.pop();
99
+ if (!frame || frame.name !== name) return false;
100
+ read(SPACE);
101
+ if (!take('>')) return false;
102
+ restore(frame.changes);
103
+ } else if (take('<')) {
104
+ const name = read(QNAME);
105
+ if (!name) return false;
106
+ const attrs = attributes();
107
+ if (!attrs) return false;
108
+ const empty = take('/>');
109
+ if (!empty && !take('>')) return false;
110
+ const changes = new Map();
111
+ // Declarations apply to the whole tag, including attributes before them.
112
+ for (const [key, value] of attrs) {
113
+ if (key !== 'xmlns' && !key.startsWith('xmlns:')) continue;
114
+ const prefix = key === 'xmlns' ? '' : key.slice(6);
115
+ if (prefix === 'xmlns' || value === XMLNS || (prefix === 'xml') !== (value === XML) || (prefix && !value)) return false;
116
+ changes.set(prefix, namespaces.get(prefix));
117
+ namespaces.set(prefix, value);
118
+ attrs.delete(key);
119
+ }
120
+ const [prefix, local] = name.split(':');
121
+ if (local && !namespaces.has(prefix)) return false;
122
+ const expanded = new Set();
123
+ for (const key of attrs.keys()) {
124
+ const [prefix, local] = key.split(':');
125
+ const namespace = local ? namespaces.get(prefix) : '';
126
+ if (namespace === undefined) return false;
127
+ const expandedName = namespace + '\0' + (local ?? prefix);
128
+ if (expanded.has(expandedName)) return false;
129
+ expanded.add(expandedName);
130
+ }
131
+ if (empty) restore(changes);
132
+ else open.push({ name, changes });
133
+ } else if (text[at] === '&') {
134
+ const ref = reference(text, at);
135
+ if (!ref) return false;
136
+ at += ref[0];
137
+ } else if (read(DATA).includes(']]>')) {
138
+ return false;
139
+ }
140
+ }
141
+ return open.length === 0;
142
+ }