eyemind 0.9.15 → 0.9.17

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/LE-SPEC.md CHANGED
@@ -183,17 +183,27 @@ indentation of that line, and a line break without a connective joins the lines
183
183
  with `and` where both lines are conditions. eyemind reads the connectives as
184
184
  LE's indentation does: the conditions are split at the least indented
185
185
  connectives, joined from the top down, and each part is read in the same way.
186
- So a deeper indentation binds tighter:
186
+ So a deeper indentation binds tighter. These two rules differ only in the
187
+ indentation of `and`. With every connective at one indentation, this rule
188
+ means *(resident or citizen) and adult*:
187
189
 
188
190
  ```text
189
- a person is eligible a person is eligible
190
- if the person is a resident if the person is a resident
191
- or the person is a citizen or the person is a citizen
192
- and the person is an adult. and the person is an adult.
191
+ a person is eligible
192
+ if the person is a resident
193
+ or the person is a citizen
194
+ and the person is an adult.
193
195
  ```
194
196
 
195
- The left rule means *(resident or citizen) and adult*, the right one *resident
196
- or (citizen and adult)*. LE1 rejects different connectives at one indentation;
197
+ With `and` indented deeper, this one means *resident or (citizen and adult)*:
198
+
199
+ ```text
200
+ a person is eligible
201
+ if the person is a resident
202
+ or the person is a citizen
203
+ and the person is an adult.
204
+ ```
205
+
206
+ LE1 rejects different connectives at one indentation;
197
207
  eyemind reads them from the top down, as LE2 does. A body may start with `and`
198
208
  after `if`, as some LE1 programs write it.
199
209
 
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.9.15
5
+ Version: eyemind 0.9.17
6
6
  ```
7
7
 
8
8
  This document specifies Logic Script (LS): the syntax and meaning of its
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "eyemind",
3
- "version": "0.9.15",
3
+ "version": "0.9.17",
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",
package/src/cli.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // The eyemind command line.
2
- import { run, unusedClauses } from './engine.js';
2
+ import { COMPILED_LIMITS, run, unusedClauses } from './engine.js';
3
3
  import { OUTPUT_FORMATS, RDF_PROFILES, defaultFormat, inputKind, loadInputs, loadMessageReasoner, rdfMessageFormat, scopeOf, writeConclusions } from './formats.js';
4
4
  import { explainLe } from './le-explain.js';
5
5
  import { isRdfMessageLog, replayMessages, RdfMessageReader } from './messages.js';
@@ -52,8 +52,6 @@ Exit codes: 0 success, 1 error, 2 invalid proof, 65 contradiction.
52
52
 
53
53
  const LIMITS = { '--max-depth': 'maxDepth', '--max-iterations': 'maxIterations', '--max-inferences': 'maxInferences' };
54
54
  const ALIASES = new Map([['-p', '--proof'], ['-c', '--prove-and-check'], ['-v', '--version'], ['-h', '--help']]);
55
- // N3 and SPARQL 1.2 RL programs run longer than eyemind's defaults allow.
56
- const COMPILED_LIMITS = { maxDepth: 1000000, maxIterations: 100000, maxInferences: 1000000000 };
57
55
 
58
56
  const RDF_FORMATS = ['turtle', 'trig', 'n-triples', 'n-quads'];
59
57
 
package/src/engine.js CHANGED
@@ -19,6 +19,10 @@ const CONTROL = 'control';
19
19
  const ABSENT = 'absent';
20
20
  const COLLECTED = 'collected';
21
21
 
22
+ // Programs compiled from RDF, N3 and SPARQL 1.2 RL run longer than eyemind's
23
+ // defaults allow.
24
+ export const COMPILED_LIMITS = { maxDepth: 1000000, maxIterations: 100000, maxInferences: 1000000000 };
25
+
22
26
  // One proof step: a goal, how it was justified, and the steps it used.
23
27
  export class Node {
24
28
  constructor(goal, by, bindings = NO_NODES, children = NO_NODES, collectedUses = null, final = false, scoped = NO_NODES) {
@@ -857,12 +861,7 @@ export class Solver {
857
861
  if (this.recording || keys === null || keys.length !== 1 || keys[0] === null ||
858
862
  clause.parentId !== null || clause.templates.length || clause.captures !== null || clause.witnessNames.length) return null;
859
863
  const goalKey = keys[0];
860
- let ground = this.groundCalls.get(goalKey);
861
- if (ground === undefined) {
862
- ground = (this.program.groups.get(goalKey) || []).every((candidate) => isGround(candidate.head));
863
- this.groundCalls.set(goalKey, ground);
864
- }
865
- if (!ground) return null;
864
+ if (!this.groundHeads(goalKey)) return null;
866
865
  if (++this.stats.inferences > this.maxInferences) throw new EyemindError('reasoning exceeded max_inferences');
867
866
  const goal = clause.localBody[0];
868
867
  const facts = this.facts.get(goalKey) || NO_NODES;
@@ -899,15 +898,17 @@ export class Solver {
899
898
  joinable(clause, keys) {
900
899
  if (this.recording || keys === null || clause.parentId !== null || clause.templates.length ||
901
900
  clause.captures !== null || this.program.hasTemplates || this.program.inspectionEnabled) return false;
902
- return keys.every((goalKey) => {
903
- if (goalKey === null) return true;
904
- let ground = this.groundCalls.get(goalKey);
905
- if (ground === undefined) {
906
- ground = (this.program.groups.get(goalKey) || []).every((candidate) => isGround(candidate.head));
907
- this.groundCalls.set(goalKey, ground);
908
- }
909
- return ground;
910
- });
901
+ return keys.every((goalKey) => goalKey === null || this.groundHeads(goalKey));
902
+ }
903
+
904
+ // Whether every clause of a relation has a ground head, cached per relation.
905
+ groundHeads(goalKey) {
906
+ let ground = this.groundCalls.get(goalKey);
907
+ if (ground === undefined) {
908
+ ground = (this.program.groups.get(goalKey) || []).every((candidate) => isGround(candidate.head));
909
+ this.groundCalls.set(goalKey, ground);
910
+ }
911
+ return ground;
911
912
  }
912
913
 
913
914
  // The solutions of a joinable body, as solve() finds them: each goal tries
package/src/le.js CHANGED
@@ -13,11 +13,10 @@ import { PRIMITIVE_KEYS } from './builtins.js';
13
13
  import { CONTROL_KEYS, Program, RESERVED_KEYS, Source } from './program.js';
14
14
  import { loadText } from './lang.js';
15
15
  import { readTerm } from './reader.js';
16
- import { EMPTY, EyemindError, Struct, Var, conjunction } from './terms.js';
16
+ import { EMPTY, EyemindError, Struct, Var, conjunction, listFromItems } from './terms.js';
17
17
  import { write } from './writer.js';
18
18
 
19
19
  const st = (name, ...args) => new Struct(name, args);
20
- const list = (items) => items.reduceRight((tail, head) => st('.', head, tail), EMPTY);
21
20
  const RESERVED = new Set([...PRIMITIVE_KEYS, ...CONTROL_KEYS, ...RESERVED_KEYS].map((key) => key.split('/')[0]));
22
21
  const SCENARIO = 'le:scenario', ANSWER = 'le:answer';
23
22
  const INTRODUCING = new Set(['a', 'an', 'some', 'each', 'which']);
@@ -439,7 +438,7 @@ class Compiler {
439
438
  items.push(item);
440
439
  start = i + 1;
441
440
  }
442
- return list(items);
441
+ return listFromItems(items);
443
442
  }
444
443
  // LE2's explicit variable: *a name*.
445
444
  if (first.text === '*' && tokens.at(-1).text === '*' && tokens.length > 2 && tokens.slice(1, -1).every((t) => t.kind === 'word')) {
@@ -1691,6 +1690,31 @@ export function compileLe(inputs, io = null) {
1691
1690
  program: new Program(sources), compiled: { templates, scenarios, threaded, queries, expectations, abductive } };
1692
1691
  }
1693
1692
 
1693
+ // The relation of a goal, as name/arity, or null for a variable.
1694
+ const keyOf = (term) => term instanceof Struct ? `${term.name}/${term.args.length}` : null;
1695
+
1696
+ // Tarjan's strongly connected components of a graph, given its nodes and the
1697
+ // nodes each one leads to: each node maps to the members of its component.
1698
+ function components(nodes, next) {
1699
+ const index = new Map(), low = new Map(), stack = [], onStack = new Set(), component = new Map();
1700
+ let counter = 0;
1701
+ const visit = (v) => {
1702
+ index.set(v, counter); low.set(v, counter++); stack.push(v); onStack.add(v);
1703
+ for (const w of next(v)) {
1704
+ if (!index.has(w)) { visit(w); low.set(v, Math.min(low.get(v), low.get(w))); }
1705
+ else if (onStack.has(w)) low.set(v, Math.min(low.get(v), index.get(w)));
1706
+ }
1707
+ if (low.get(v) === index.get(v)) {
1708
+ const members = [];
1709
+ let w;
1710
+ do { w = stack.pop(); onStack.delete(w); members.push(w); } while (w !== v);
1711
+ for (const m of members) component.set(m, members);
1712
+ }
1713
+ };
1714
+ for (const v of nodes) if (!index.has(v)) visit(v);
1715
+ return component;
1716
+ }
1717
+
1694
1718
  // LE runs recursive rules with tabling (LE1) or a loop check (LE2), so a rule
1695
1719
  // that depends on itself, directly or through others, ends where Prolog's
1696
1720
  // search would not. LS forward rules reach the least fixpoint that tabling
@@ -1700,7 +1724,6 @@ export function compileLe(inputs, io = null) {
1700
1724
  // called, such as a counter that goes down, stays backward.
1701
1725
  function forwardRecursion(pending, templates, threaded, assumable = new Set()) {
1702
1726
  const keys = new Set([...templates.map((t) => `${t.name}/${t.arity + (threaded ? 1 : 0)}`), `is_a/${threaded ? 3 : 2}`]);
1703
- const keyOf = (term) => term instanceof Struct ? `${term.name}/${term.args.length}` : null;
1704
1727
  const calls = (term, out = new Set()) => {
1705
1728
  if (term instanceof Struct) {
1706
1729
  if (keys.has(keyOf(term))) out.add(keyOf(term));
@@ -1715,23 +1738,7 @@ function forwardRecursion(pending, templates, threaded, assumable = new Set()) {
1715
1738
  if (!edges.has(from)) edges.set(from, new Set());
1716
1739
  for (const goal of rule.body) for (const to of calls(goal)) edges.get(from).add(to);
1717
1740
  }
1718
- // Tarjan's strongly connected components of the relations.
1719
- const index = new Map(), low = new Map(), stack = [], onStack = new Set(), component = new Map();
1720
- let counter = 0;
1721
- const visit = (v) => {
1722
- index.set(v, counter); low.set(v, counter++); stack.push(v); onStack.add(v);
1723
- for (const w of edges.get(v) ?? []) {
1724
- if (!index.has(w)) { visit(w); low.set(v, Math.min(low.get(v), low.get(w))); }
1725
- else if (onStack.has(w)) low.set(v, Math.min(low.get(v), index.get(w)));
1726
- }
1727
- if (low.get(v) === index.get(v)) {
1728
- const members = [];
1729
- let w;
1730
- do { w = stack.pop(); onStack.delete(w); members.push(w); } while (w !== v);
1731
- for (const m of members) component.set(m, members);
1732
- }
1733
- };
1734
- for (const v of edges.keys()) if (!index.has(v)) visit(v);
1741
+ const component = components(edges.keys(), (v) => edges.get(v) ?? []);
1735
1742
  const recursive = (key) => component.get(key)?.length > 1 || edges.get(key)?.has(key);
1736
1743
  const bound = (rule) => {
1737
1744
  const relations = new Set();
@@ -1753,7 +1760,6 @@ function forwardRecursion(pending, templates, threaded, assumable = new Set()) {
1753
1760
  // at most three changes that makes the goal hold.
1754
1761
  const FLIP_LIMIT = 3;
1755
1762
  function flipWorlds(pending, { templates, flips, scenarios, helpers, emit }) {
1756
- const keyOf = (term) => term instanceof Struct ? `${term.name}/${term.args.length}` : null;
1757
1763
  const concluded = new Set(pending.filter((c) => c.guard?.rule).map((c) => keyOf(c.head)));
1758
1764
  const marked = templates.filter((t) => t.scenarioElement);
1759
1765
  const changeable = (marked.length ? marked : templates.filter((t) => !t.function && !concluded.has(`${t.name}/${t.arity + 1}`)))
@@ -1803,11 +1809,11 @@ function flipWorlds(pending, { templates, flips, scenarios, helpers, emit }) {
1803
1809
  if (!facts.some((f) => write(f) === write(sentence))) candidates.push(st('add', sentence));
1804
1810
  }
1805
1811
  }
1806
- emit('fact', st('le:candidates', scenario, list(candidates)), [], null, null);
1812
+ emit('fact', st('le:candidates', scenario, listFromItems(candidates)), [], null, null);
1807
1813
  const subsets = (from, k) => k === 0 ? [[]] : candidates.slice(from).flatMap((c, i) => subsets(from + i + 1, k - 1).map((rest) => [c, ...rest]));
1808
1814
  for (let k = 0; k <= FLIP_LIMIT; k++) {
1809
1815
  for (const changes of subsets(0, k)) {
1810
- const world = st('le:flip', scenario, list(changes));
1816
+ const world = st('le:flip', scenario, listFromItems(changes));
1811
1817
  const removed = new Set(changes.filter((c) => c.name === 'remove').map((c) => write(c.args[0])));
1812
1818
  const worldFacts = [...facts.filter((f) => !removed.has(write(f))), ...changes.filter((c) => c.name === 'add').map((c) => c.args[0])];
1813
1819
  size += worldFacts.length + 1;
@@ -1819,7 +1825,7 @@ function flipWorlds(pending, { templates, flips, scenarios, helpers, emit }) {
1819
1825
  }
1820
1826
  helpers.add('le:choose');
1821
1827
  helpers.add('le:member');
1822
- const sizes = list(Array.from({ length: FLIP_LIMIT + 1 }, (_, k) => BigInt(k)));
1828
+ const sizes = listFromItems(Array.from({ length: FLIP_LIMIT + 1 }, (_, k) => BigInt(k)));
1823
1829
  for (const { name, goals, S: world, changes, line, file } of flips) {
1824
1830
  const size = new Var('K_'), candidates = new Var('Candidates_');
1825
1831
  emit('backward', st('le:flips', name, world, size, changes),
@@ -1840,7 +1846,6 @@ function flipWorlds(pending, { templates, flips, scenarios, helpers, emit }) {
1840
1846
  // NAME:sc, with the scope as one more argument; in it, a scenario fact holds
1841
1847
  // when its source is admissible under the scope.
1842
1848
  function scopeProofs(pending, { templates, threaded, emit }) {
1843
- const keyOf = (term) => term instanceof Struct ? `${term.name}/${term.args.length}` : null;
1844
1849
  const user = new Set([...templates.map((t) => `${t.name}/${t.arity + (threaded ? 1 : 0)}`), `is_a/${threaded ? 3 : 2}`, `${ADMISSIBLE}/${threaded ? 3 : 2}`]);
1845
1850
  const placeholders = [];
1846
1851
  const find = (term) => {
@@ -1900,7 +1905,6 @@ function scopeProofs(pending, { templates, threaded, emit }) {
1900
1905
  const DEPTH = 8;
1901
1906
  function unfold(pending, templates, threaded) {
1902
1907
  const keys = new Set([...templates.map((t) => `${t.name}/${t.arity + (threaded ? 1 : 0)}`), `is_a/${threaded ? 3 : 2}`, `le_is/${threaded ? 3 : 2}`]);
1903
- const keyOf = (term) => term instanceof Struct ? `${term.name}/${term.args.length}` : null;
1904
1908
  const closedControl = (term) => term instanceof Struct && ((term.name === 'not' && term.args.length === 1) || ((term.name === 'findall' || term.name === 'findall_sorted') && term.args.length === 3));
1905
1909
  const edges = new Map();
1906
1910
  const visitCalls = (term, from, closed) => {
@@ -1914,22 +1918,7 @@ function unfold(pending, templates, threaded) {
1914
1918
  for (const goal of rule.body ?? []) visitCalls(goal, keyOf(rule.head), false);
1915
1919
  }
1916
1920
  // The strongly connected components, and those with a closed edge inside.
1917
- const index = new Map(), low = new Map(), stack = [], onStack = new Set(), component = new Map();
1918
- let counter = 0;
1919
- const visit = (v) => {
1920
- index.set(v, counter); low.set(v, counter++); stack.push(v); onStack.add(v);
1921
- for (const [w] of edges.get(v) ?? []) {
1922
- if (!index.has(w)) { visit(w); low.set(v, Math.min(low.get(v), low.get(w))); }
1923
- else if (onStack.has(w)) low.set(v, Math.min(low.get(v), index.get(w)));
1924
- }
1925
- if (low.get(v) === index.get(v)) {
1926
- const members = [];
1927
- let w;
1928
- do { w = stack.pop(); onStack.delete(w); members.push(w); } while (w !== v);
1929
- for (const m of members) component.set(m, members);
1930
- }
1931
- };
1932
- for (const v of edges.keys()) if (!index.has(v)) visit(v);
1921
+ const component = components(edges.keys(), (v) => (edges.get(v) ?? []).map(([w]) => w));
1933
1922
  const unfolded = new Set();
1934
1923
  for (const [from, list] of edges) {
1935
1924
  for (const [to, closed] of list) if (closed && component.get(from)?.includes(to)) for (const m of component.get(from)) unfolded.add(m);
@@ -1974,7 +1963,6 @@ function unfold(pending, templates, threaded) {
1974
1963
  // assumes a sentence and its negation, denies a proved sentence, or breaks a
1975
1964
  // constraint that more assumptions cannot repair.
1976
1965
  function abduce(pending, { templates, threaded, assumable, abducibles, constraints, denials, helpers, emit }) {
1977
- const keyOf = (term) => term instanceof Struct ? `${term.name}/${term.args.length}` : null;
1978
1966
  const user = new Set([...templates.map((t) => `${t.name}/${t.arity + (threaded ? 1 : 0)}`), `is_a/${threaded ? 3 : 2}`,
1979
1967
  `le_is/${threaded ? 3 : 2}`, ...assumable]);
1980
1968
  const calls = (term, out = new Set()) => {
@@ -2063,7 +2051,7 @@ function abduce(pending, { templates, threaded, assumable, abducibles, constrain
2063
2051
  const assume = (sentence, line, file) => {
2064
2052
  const open = st('findall', 'x', st('is_ground', sentence), EMPTY);
2065
2053
  const closed = conjunction([st('is_ground', sentence), st('not', sentence), st('not', st('le:denied', sentence))]);
2066
- emit('backward', new Struct(`${sentence.name}:ab`, [...sentence.args, list([sentence])]), [st('or', closed, open)], line, file);
2054
+ emit('backward', new Struct(`${sentence.name}:ab`, [...sentence.args, listFromItems([sentence])]), [st('or', closed, open)], line, file);
2067
2055
  };
2068
2056
  for (const template of templates.filter((t) => t.assumable)) {
2069
2057
  const args = Array.from({ length: template.arity + (threaded ? 1 : 0) }, (_, i) => new Var(i === 0 && threaded ? 'Scenario' : `A${i}`));
package/src/n3.js CHANGED
@@ -21,7 +21,7 @@
21
21
  // universals are qbnode(Label) and qvar(Name), and a rule's graph pattern
22
22
  // matches it as a set, up to a one-to-one renaming of those. Built-in
23
23
  // predicates of a body become goals defined in LS (n3-builtins.js).
24
- import { run } from './engine.js';
24
+ import { COMPILED_LIMITS, run } from './engine.js';
25
25
  import { loadText } from './lang.js';
26
26
  import { Program, Source } from './program.js';
27
27
  import { Struct, Var, conjunction, isGround } from './terms.js';
@@ -1135,15 +1135,12 @@ function conclusionsToN3(doc, { triples, contradiction }, { mode = 'new', string
1135
1135
  return { n3: writeN3(triples, { prefixes: doc.prefixes, strings, blankNodePrefix }), triples, contradiction };
1136
1136
  }
1137
1137
 
1138
- // Generous bounds: N3 programs often run longer than eyemind's defaults.
1139
- const N3_LIMITS = { maxDepth: 1000000, maxIterations: 100000, maxInferences: 1000000000 };
1140
-
1141
1138
  // Reason over N3 sources. Returns { n3, triples, contradiction, program,
1142
1139
  // result }; with proof, result.proof is eyemind's checked proof of the
1143
1140
  // compiled program.
1144
1141
  export function reasonN3(sources, { base = '', mode = 'new', strings = 'auto', limits = {}, proof = false, goals = [], readFile = null, readDocument = null } = {}) {
1145
1142
  const compiled = compileSources(sources, { base, readFile, readDocument, native: true });
1146
- const result = run(compiled.nativeProgram ?? loadText(compiled.program, 'compiled.js'), { ...N3_LIMITS, ...limits, proof, goals });
1143
+ const result = run(compiled.nativeProgram ?? loadText(compiled.program, 'compiled.js'), { ...COMPILED_LIMITS, ...limits, proof, goals });
1147
1144
  return { ...resultToN3(compiled.doc, result, { mode, strings }), get program() { return compiled.program; }, result };
1148
1145
  }
1149
1146
 
package/src/rdf-lexer.js CHANGED
@@ -340,25 +340,6 @@ function assertValidStringLiteralValue(s, offset = null) {
340
340
  }
341
341
  }
342
342
 
343
- // In the monolithic build, stripQuotes() is defined later in the file and
344
- // function-hoisting makes it available to lex(). In the modular build the
345
- // lexer must provide it locally.
346
- function stripQuotes(lex) {
347
- if (typeof lex !== 'string') return lex;
348
- // Handle both short ('...' / "...") and long ('''...''' / """...""") forms.
349
- if (lex.length >= 6) {
350
- if (lex.startsWith('"""') && lex.endsWith('"""')) return lex.slice(3, -3);
351
- if (lex.startsWith("'''") && lex.endsWith("'''")) return lex.slice(3, -3);
352
- }
353
- if (lex.length >= 2) {
354
- const a = lex[0];
355
- const b = lex[lex.length - 1];
356
- if ((a === '"' && b === '"') || (a === "'" && b === "'")) return lex.slice(1, -1);
357
- }
358
- return lex;
359
- }
360
-
361
-
362
343
  // eyemind: RDF/TriG syntax is normalized to the parser's N3 representation:
363
344
  // - RDF 1.2 triple terms <<( s p o )>> become singleton graph terms { s p o }.
364
345
  // - TriG named graph blocks g { ... } become g log:nameOf { ... } .
@@ -1768,13 +1749,14 @@ function lex(inputText, opts = {}) {
1768
1749
  break;
1769
1750
  }
1770
1751
 
1771
- // String literal: short "..." or long """..."""
1772
- if (c === '"') {
1752
+ // String literal: short "..." or '...', long """...""" or '''...'''
1753
+ if (c === '"' || c === "'") {
1773
1754
  const start = i;
1755
+ const quote = c;
1774
1756
 
1775
- // Long string literal """ ... """
1776
- if (peek(1) === '"' && peek(2) === '"') {
1777
- i += 3; // consume opening """
1757
+ // Long string literal
1758
+ if (peek(1) === quote && peek(2) === quote) {
1759
+ i += 3; // consume opening delimiter
1778
1760
  const sChars = [];
1779
1761
  let closed = false;
1780
1762
  while (i < n) {
@@ -1796,18 +1778,18 @@ function lex(inputText, opts = {}) {
1796
1778
 
1797
1779
  // In long strings, a run of >= 3 delimiter quotes terminates the literal.
1798
1780
  // Any extra quotes beyond the final 3 are part of the content.
1799
- if (cc === '"') {
1781
+ if (cc === quote) {
1800
1782
  let run = 0;
1801
- while (i + run < n && chars[i + run] === '"') run++;
1783
+ while (i + run < n && chars[i + run] === quote) run++;
1802
1784
 
1803
1785
  if (run >= 3) {
1804
- for (let k = 0; k < run - 3; k++) sChars.push('"');
1786
+ for (let k = 0; k < run - 3; k++) sChars.push(quote);
1805
1787
  i += run; // consume content quotes (if any) + closing delimiter
1806
1788
  closed = true;
1807
1789
  break;
1808
1790
  }
1809
1791
 
1810
- for (let k = 0; k < run; k++) sChars.push('"');
1792
+ for (let k = 0; k < run; k++) sChars.push(quote);
1811
1793
  i += run;
1812
1794
  continue;
1813
1795
  }
@@ -1815,113 +1797,18 @@ function lex(inputText, opts = {}) {
1815
1797
  sChars.push(cc);
1816
1798
  i++;
1817
1799
  }
1818
- if (!closed) throw new N3SyntaxError('Unterminated long string literal """..."""', start);
1819
- const raw = '"""' + sChars.join('') + '"""';
1820
- const decoded = decodeN3StringEscapes(stripQuotes(raw), start);
1800
+ if (!closed) throw new N3SyntaxError(`Unterminated long string literal ${quote.repeat(3)}...${quote.repeat(3)}`, start);
1801
+ const decoded = decodeN3StringEscapes(sChars.join(''), start);
1821
1802
  assertValidStringLiteralValue(decoded, start);
1822
1803
  const s = JSON.stringify(decoded); // canonical short quoted form
1823
1804
  tokens.push(new Token('Literal', s, start));
1824
1805
  continue;
1825
1806
  }
1826
1807
 
1827
- // Short string literal " ... ". Most data files contain plain
1808
+ // Short string literal. Most data files contain plain
1828
1809
  // unescaped labels; keep that path slice-based and avoid building an
1829
1810
  // intermediate character array + raw quoted string.
1830
- i++; // consume opening "
1831
- const contentStart = i;
1832
- let sChars = null;
1833
- let closed = false;
1834
- while (i < n) {
1835
- const cc = chars[i];
1836
- i++;
1837
- if (cc === '\\') {
1838
- if (sChars === null) sChars = [sliceChars(contentStart, i - 1)];
1839
- if (i < n) {
1840
- const esc = chars[i];
1841
- i++;
1842
- sChars.push('\\');
1843
- sChars.push(esc);
1844
- } else {
1845
- sChars.push('\\');
1846
- }
1847
- continue;
1848
- }
1849
- if (cc === '\n' || cc === '\r') {
1850
- throw new N3SyntaxError('Unescaped newline in short string literal', start);
1851
- }
1852
- if (cc === '"') {
1853
- closed = true;
1854
- break;
1855
- }
1856
- if (sChars !== null) sChars.push(cc);
1857
- }
1858
- if (!closed) throw new N3SyntaxError('Unterminated short string literal "..."', start);
1859
- const rawContent = sChars === null ? sliceChars(contentStart, i - 1) : sChars.join('');
1860
- const decoded = sChars === null ? rawContent : decodeN3StringEscapes(rawContent, start);
1861
- if (sChars !== null || inputMayContainInvalidStringChar) assertValidStringLiteralValue(decoded, start);
1862
- const s = JSON.stringify(decoded); // canonical short quoted form
1863
- tokens.push(new Token('Literal', s, start));
1864
- continue;
1865
- }
1866
-
1867
- // String literal: short '...' or long '''...'''
1868
- if (c === "'") {
1869
- const start = i;
1870
-
1871
- // Long string literal ''' ... '''
1872
- if (peek(1) === "'" && peek(2) === "'") {
1873
- i += 3; // consume opening '''
1874
- const sChars = [];
1875
- let closed = false;
1876
- while (i < n) {
1877
- const cc = chars[i];
1878
-
1879
- // Preserve escapes verbatim (same behavior as short strings)
1880
- if (cc === '\\') {
1881
- i++;
1882
- if (i < n) {
1883
- const esc = chars[i];
1884
- i++;
1885
- sChars.push('\\');
1886
- sChars.push(esc);
1887
- } else {
1888
- sChars.push('\\');
1889
- }
1890
- continue;
1891
- }
1892
-
1893
- // In long strings, a run of >= 3 delimiter quotes terminates the literal.
1894
- // Any extra quotes beyond the final 3 are part of the content.
1895
- if (cc === "'") {
1896
- let run = 0;
1897
- while (i + run < n && chars[i + run] === "'") run++;
1898
-
1899
- if (run >= 3) {
1900
- for (let k = 0; k < run - 3; k++) sChars.push("'");
1901
- i += run; // consume content quotes (if any) + closing delimiter
1902
- closed = true;
1903
- break;
1904
- }
1905
-
1906
- for (let k = 0; k < run; k++) sChars.push("'");
1907
- i += run;
1908
- continue;
1909
- }
1910
-
1911
- sChars.push(cc);
1912
- i++;
1913
- }
1914
- if (!closed) throw new N3SyntaxError("Unterminated long string literal '''...'''", start);
1915
- const raw = "'''" + sChars.join('') + "'''";
1916
- const decoded = decodeN3StringEscapes(stripQuotes(raw), start);
1917
- assertValidStringLiteralValue(decoded, start);
1918
- const s = JSON.stringify(decoded); // canonical short quoted form
1919
- tokens.push(new Token('Literal', s, start));
1920
- continue;
1921
- }
1922
-
1923
- // Short string literal ' ... '
1924
- i++; // consume opening '
1811
+ i++; // consume opening quote
1925
1812
  const contentStart = i;
1926
1813
  let sChars = null;
1927
1814
  let closed = false;
@@ -1943,13 +1830,13 @@ function lex(inputText, opts = {}) {
1943
1830
  if (cc === '\n' || cc === '\r') {
1944
1831
  throw new N3SyntaxError('Unescaped newline in short string literal', start);
1945
1832
  }
1946
- if (cc === "'") {
1833
+ if (cc === quote) {
1947
1834
  closed = true;
1948
1835
  break;
1949
1836
  }
1950
1837
  if (sChars !== null) sChars.push(cc);
1951
1838
  }
1952
- if (!closed) throw new N3SyntaxError("Unterminated short string literal '...'", start);
1839
+ if (!closed) throw new N3SyntaxError(`Unterminated short string literal ${quote}...${quote}`, start);
1953
1840
  const rawContent = sChars === null ? sliceChars(contentStart, i - 1) : sChars.join('');
1954
1841
  const decoded = sChars === null ? rawContent : decodeN3StringEscapes(rawContent, start);
1955
1842
  if (sChars !== null || inputMayContainInvalidStringChar) assertValidStringLiteralValue(decoded, start);
package/src/rdf-parser.js CHANGED
@@ -253,34 +253,14 @@ class Parser {
253
253
  }
254
254
 
255
255
  const tok2 = this.next();
256
- let iri;
257
- if (tok2.typ === 'IriRef') {
258
- iri = resolveIriRef(tok2.value || '', this.prefixes.baseIri || '');
259
- } else if (tok2.typ === 'Ident') {
260
- const qn = tok2.value || '';
261
- if (!qn.includes(':')) failInvalidKeywordLikeIdent(this.fail.bind(this), tok2, qn);
262
- assertValidQNamePrefix(qn.slice(0, qn.indexOf(':')), this.fail.bind(this), tok2, '@prefix directive IRI');
263
- iri = this.prefixes.expandQName(qn);
264
- } else {
265
- this.fail(`Expected IRI after @prefix, got ${tok2.toString()}`, tok2);
266
- }
256
+ const iri = this.directiveIri(tok2, '@prefix', '@prefix directive IRI');
267
257
  this.expectDot();
268
258
  this.prefixes.set(prefName, iri);
269
259
  }
270
260
 
271
261
  parseBaseDirective() {
272
262
  const tok = this.next();
273
- let iri;
274
- if (tok.typ === 'IriRef') {
275
- iri = resolveIriRef(tok.value || '', this.prefixes.baseIri || '');
276
- } else if (tok.typ === 'Ident') {
277
- const qn = tok.value || '';
278
- if (!qn.includes(':')) failInvalidKeywordLikeIdent(this.fail.bind(this), tok, qn);
279
- assertValidQNamePrefix(qn.slice(0, qn.indexOf(':')), this.fail.bind(this), tok, '@base directive IRI');
280
- iri = this.prefixes.expandQName(qn);
281
- } else {
282
- this.fail(`Expected IRI after @base, got ${tok.toString()}`, tok);
283
- }
263
+ const iri = this.directiveIri(tok, '@base', '@base directive IRI');
284
264
  this.expectDot();
285
265
  this.prefixes.setBase(iri);
286
266
  }
@@ -299,17 +279,7 @@ class Parser {
299
279
  assertValidQNamePrefix(prefName, this.fail.bind(this), tok, 'PREFIX directive');
300
280
 
301
281
  const tok2 = this.next();
302
- let iri;
303
- if (tok2.typ === 'IriRef') {
304
- iri = resolveIriRef(tok2.value || '', this.prefixes.baseIri || '');
305
- } else if (tok2.typ === 'Ident') {
306
- const qn = tok2.value || '';
307
- if (!qn.includes(':')) failInvalidKeywordLikeIdent(this.fail.bind(this), tok2, qn);
308
- assertValidQNamePrefix(qn.slice(0, qn.indexOf(':')), this.fail.bind(this), tok2, '@prefix directive IRI');
309
- iri = this.prefixes.expandQName(qn);
310
- } else {
311
- this.fail(`Expected IRI after PREFIX, got ${tok2.toString()}`, tok2);
312
- }
282
+ const iri = this.directiveIri(tok2, 'PREFIX', '@prefix directive IRI');
313
283
 
314
284
  // N3/Turtle: PREFIX directives do not have a trailing '.', but accept it permissively.
315
285
  if (this.peek().typ === 'Dot') this.next();
@@ -320,17 +290,7 @@ class Parser {
320
290
  parseSparqlBaseDirective() {
321
291
  // SPARQL/Turtle-style BASE directive: BASE <iri> (no trailing '.')
322
292
  const tok = this.next();
323
- let iri;
324
- if (tok.typ === 'IriRef') {
325
- iri = resolveIriRef(tok.value || '', this.prefixes.baseIri || '');
326
- } else if (tok.typ === 'Ident') {
327
- const qn = tok.value || '';
328
- if (!qn.includes(':')) failInvalidKeywordLikeIdent(this.fail.bind(this), tok, qn);
329
- assertValidQNamePrefix(qn.slice(0, qn.indexOf(':')), this.fail.bind(this), tok, 'BASE directive IRI');
330
- iri = this.prefixes.expandQName(qn);
331
- } else {
332
- this.fail(`Expected IRI after BASE, got ${tok.toString()}`, tok);
333
- }
293
+ const iri = this.directiveIri(tok, 'BASE', 'BASE directive IRI');
334
294
 
335
295
  // N3/Turtle: BASE directives do not have a trailing '.', but accept it permissively.
336
296
  if (this.peek().typ === 'Dot') this.next();
@@ -338,6 +298,17 @@ class Parser {
338
298
  this.prefixes.setBase(iri);
339
299
  }
340
300
 
301
+ // A directive's IRI: an IRI reference, resolved against the base, or a
302
+ // prefixed name.
303
+ directiveIri(tok, after, context) {
304
+ if (tok.typ === 'IriRef') return resolveIriRef(tok.value || '', this.prefixes.baseIri || '');
305
+ if (tok.typ !== 'Ident') this.fail(`Expected IRI after ${after}, got ${tok.toString()}`, tok);
306
+ const qn = tok.value || '';
307
+ if (!qn.includes(':')) failInvalidKeywordLikeIdent(this.fail.bind(this), tok, qn);
308
+ assertValidQNamePrefix(qn.slice(0, qn.indexOf(':')), this.fail.bind(this), tok, context);
309
+ return this.prefixes.expandQName(qn);
310
+ }
311
+
341
312
  parseTerm() {
342
313
  let t = this.parsePathItem();
343
314
 
package/src/shacl-expr.js CHANGED
@@ -16,7 +16,7 @@ const SHNEX = 'http://www.w3.org/ns/shacl-node-expr#';
16
16
  export const SPARQL = 'http://www.w3.org/ns/sparql#';
17
17
  const TRUE = `literal('true', datatype('${XSD}boolean'))`;
18
18
  const FALSE = `literal('false', datatype('${XSD}boolean'))`;
19
- const isIri = (t) => t instanceof Struct && t.name === 'iri';
19
+ export const isIri = (t) => t instanceof Struct && t.name === 'iri';
20
20
  const isBlank = (t) => t instanceof Struct && t.name === 'bnode';
21
21
 
22
22
  // sparql:<name> to its SRL function goal and the library definition it needs.
package/src/shacl.js CHANGED
@@ -5,7 +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
+ import { NODE_COMMON, isIri, nodeExpressions } from './shacl-expr.js';
9
9
 
10
10
  const SH = 'http://www.w3.org/ns/shacl#';
11
11
  const RDF = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#';
@@ -34,7 +34,6 @@ const literal = (t, datatype) => t instanceof Struct && t.name === 'literal' &&
34
34
  const BOOL = (t) => literal(t, XSD + 'boolean') && ['true', 'false', '1', '0'].includes(t.args[0]);
35
35
  // Only the boolean true activates a constraint; the suite reads "1" as not true.
36
36
  const TRUE = (t) => literal(t, XSD + 'boolean') && t.args[0] === 'true';
37
- const isIri = (t) => t instanceof Struct && t.name === 'iri';
38
37
  const resource = (t) => t instanceof Struct && ['iri', 'bnode', 'triple'].includes(t.name);
39
38
  const typeNames = (types) => types.map((t) => t.args?.[0]);
40
39
  const TRUE_TERM = `literal('true', datatype('${XSD}boolean'))`;
@@ -362,8 +361,9 @@ export function compileShacl(quads, { disallows = SHACL_DISALLOWS, needs = new S
362
361
  // The LS regex primitive uses ECMAScript Unicode syntax. Translate the
363
362
  // portable SHACL flags at compilation, without executing input patterns.
364
363
  const f = flags?.args[0] ?? '';
365
- if (f.includes('x')) expression = extendedPattern(expression);
366
- if (f.includes('s')) expression = dotAllPattern(expression);
364
+ // x drops whitespace and s lets a dot match newlines, outside classes.
365
+ if (f.includes('x')) expression = rewritePattern(expression, (c) => /[ \t\r\n]/.test(c) ? '' : c);
366
+ if (f.includes('s')) expression = rewritePattern(expression, (c) => c === '.' ? '[\\s\\S]' : c);
367
367
  if (f.includes('m')) error(s, 'uses sh:flags m, which is not supported by the LS regex primitive');
368
368
  if (f.includes('i')) expression = caseInsensitivePattern(expression);
369
369
  try { new RegExp(expression, 'u'); } catch { error(s, 'has an invalid or unsupported regular expression'); }
@@ -523,27 +523,16 @@ export function compileShacl(quads, { disallows = SHACL_DISALLOWS, needs = new S
523
523
  }
524
524
 
525
525
  // Flag translation is deliberately conservative: unsupported regex syntax is
526
- // rejected rather than changing a constraint's meaning silently.
527
- function extendedPattern(pattern) {
526
+ // rejected rather than changing a constraint's meaning silently. This
527
+ // rewrites each character of a pattern outside escapes and character classes.
528
+ function rewritePattern(pattern, rewrite) {
528
529
  let out = '', escaped = false, inClass = false;
529
530
  for (const c of pattern) {
530
531
  if (escaped) { out += '\\' + c; escaped = false; continue; }
531
532
  if (c === '\\') { escaped = true; continue; }
532
533
  if (c === '[') inClass = true;
533
534
  if (c === ']') inClass = false;
534
- if (inClass || !/[ \t\r\n]/.test(c)) out += c;
535
- }
536
- return out + (escaped ? '\\' : '');
537
- }
538
-
539
- function dotAllPattern(pattern) {
540
- let out = '', escaped = false, inClass = false;
541
- for (const c of pattern) {
542
- if (escaped) { out += '\\' + c; escaped = false; continue; }
543
- if (c === '\\') { escaped = true; continue; }
544
- if (c === '[') inClass = true;
545
- if (c === ']') inClass = false;
546
- out += c === '.' && !inClass ? '[\\s\\S]' : c;
535
+ out += inClass ? c : rewrite(c);
547
536
  }
548
537
  return out + (escaped ? '\\' : '');
549
538
  }
@@ -1,5 +1,5 @@
1
1
 
2
- import { compactIRI, iri, variable, termEquals } from './srl-term.js';
2
+ import { compactIRI, iri, variable, termEquals, termKey } from './srl-term.js';
3
3
  import { tripleHasBlankNode, tripleHasVariableTripleTerm } from './srl-assignments.js';
4
4
 
5
5
  function analyze(program, options = {}) {
@@ -212,7 +212,7 @@ function fixedTermIndexKey(term) {
212
212
  if (term.type === 'var') return null;
213
213
  if (term.type === 'path') return null;
214
214
  if (term.type === 'triple' && containsVariableTerm(term)) return null;
215
- return termIndexKey(term);
215
+ return termKey(term);
216
216
  }
217
217
 
218
218
  function containsVariableTerm(term) {
@@ -226,20 +226,6 @@ function containsVariableTerm(term) {
226
226
  return false;
227
227
  }
228
228
 
229
- function literalIndexValue(value) {
230
- if (typeof value === 'bigint') return `${value.toString()}n`;
231
- return JSON.stringify(value);
232
- }
233
-
234
- function termIndexKey(term) {
235
- if (!term) return 'null';
236
- if (term.type === 'iri') return `I:${term.value}`;
237
- if (term.type === 'blank') return `B:${term.value}`;
238
- if (term.type === 'literal') return `L:${literalIndexValue(term.value)}^^${term.datatype || ''}@${term.lang || ''}--${term.langDir || ''}`;
239
- if (term.type === 'triple') return `T:${termIndexKey(term.s)} ${termIndexKey(term.p)} ${termIndexKey(term.o)}`;
240
- return JSON.stringify(term);
241
- }
242
-
243
229
  function stratificationLayers(ruleCount, components, componentOf, edges) {
244
230
  if (ruleCount === 0) return [];
245
231
  const levels = Array(ruleCount).fill(0);
package/src/srl-term.js CHANGED
@@ -131,6 +131,7 @@ function formatTerm(term, prefixes = {}) {
131
131
  }
132
132
 
133
133
  export {
134
+ termKey,
134
135
  RDF_NS,
135
136
  RDF_TYPE,
136
137
  RDF_FIRST,
@@ -76,21 +76,24 @@ function tokenize(source, filenameOrOptions = '<input>') {
76
76
  return value;
77
77
  }
78
78
 
79
+ // The character of a \u or \U escape, whose hex digits follow.
80
+ function readHexEscape(esc, startLine, startColumn) {
81
+ const length = esc === 'u' ? 4 : 8;
82
+ let hex = '';
83
+ for (let j = 0; j < length; j += 1) {
84
+ if (!isHexCode(source.charCodeAt(i))) syntax(`Invalid \\${esc} escape`, startLine, startColumn);
85
+ hex += advance();
86
+ }
87
+ const codePoint = Number.parseInt(hex, 16);
88
+ if (codePoint >= 0xD800 && codePoint <= 0xDFFF) syntax(`Invalid \\${esc} escape: surrogate code point`, startLine, startColumn);
89
+ try { return String.fromCodePoint(codePoint); }
90
+ catch { syntax(`Invalid \\${esc} escape`, startLine, startColumn); }
91
+ }
92
+
79
93
  function readEscape(startLine, startColumn) {
80
94
  advance(); // consume backslash
81
95
  const esc = advance();
82
- if (esc === 'u' || esc === 'U') {
83
- const length = esc === 'u' ? 4 : 8;
84
- let hex = '';
85
- for (let j = 0; j < length; j += 1) {
86
- if (!isHexCode(source.charCodeAt(i))) syntax(`Invalid \\${esc} escape`, startLine, startColumn);
87
- hex += advance();
88
- }
89
- const codePoint = Number.parseInt(hex, 16);
90
- if (codePoint >= 0xD800 && codePoint <= 0xDFFF) syntax(`Invalid \\${esc} escape: surrogate code point`, startLine, startColumn);
91
- try { return String.fromCodePoint(codePoint); }
92
- catch { syntax(`Invalid \\${esc} escape`, startLine, startColumn); }
93
- }
96
+ if (esc === 'u' || esc === 'U') return readHexEscape(esc, startLine, startColumn);
94
97
  if (strictGrammar && !Object.hasOwn(escapeMap, esc)) syntax(`Invalid escape \\${esc}`, startLine, startColumn);
95
98
  return escapeValue(esc);
96
99
  }
@@ -100,16 +103,7 @@ function tokenize(source, filenameOrOptions = '<input>') {
100
103
  advance();
101
104
  const esc = advance();
102
105
  if (esc !== 'u' && esc !== 'U') syntax(`Invalid IRI escape \\${esc}`, startLine, startColumn);
103
- const length = esc === 'u' ? 4 : 8;
104
- let hex = '';
105
- for (let j = 0; j < length; j += 1) {
106
- if (!isHexCode(source.charCodeAt(i))) syntax(`Invalid \\${esc} escape`, startLine, startColumn);
107
- hex += advance();
108
- }
109
- const codePoint = Number.parseInt(hex, 16);
110
- if (codePoint >= 0xD800 && codePoint <= 0xDFFF) syntax(`Invalid \\${esc} escape: surrogate code point`, startLine, startColumn);
111
- try { return String.fromCodePoint(codePoint); }
112
- catch { syntax(`Invalid \\${esc} escape`, startLine, startColumn); }
106
+ return readHexEscape(esc, startLine, startColumn);
113
107
  }
114
108
  const c = current();
115
109
  if (strictGrammar && (/[\u0000-\u0020]/.test(c) || /[<>"{}|^`]/.test(c))) syntax(`Invalid character in IRI reference ${JSON.stringify(c)}`, startLine, startColumn);
package/src/srl.js CHANGED
@@ -35,7 +35,7 @@ import { analyze } from './srl-analyze.js';
35
35
  import { BUILTIN_SIGNATURES, canonicalBuiltinName } from './srl-builtin-names.js';
36
36
  import { libraryText } from './srl-functions.js';
37
37
  import { Parser } from './srl-parser.js';
38
- import { run } from './engine.js';
38
+ import { COMPILED_LIMITS, run } from './engine.js';
39
39
  import { loadText, statementSources } from './lang.js';
40
40
  import { Program, Source } from './program.js';
41
41
  import { DEFAULT_GRAPH } from './rdf.js';
@@ -786,10 +786,6 @@ function collectClauseVars(clauses, out) {
786
786
  }
787
787
  }
788
788
 
789
-
790
- // Generous bounds: rule sets over real data run longer than eyemind's defaults.
791
- const SRL_LIMITS = { maxDepth: 1000000, maxIterations: 100000, maxInferences: 1000000000 };
792
-
793
789
  // Reason over a rule set. Options: base, filename, resolve (IMPORTS), data
794
790
  // (the base graph as RDF quads), all (the base graph too), limits and proof.
795
791
  // Returns { quads, program, prefixes, warnings, result }: the quads are the
@@ -797,7 +793,7 @@ const SRL_LIMITS = { maxDepth: 1000000, maxIterations: 100000, maxInferences: 10
797
793
  // proof of the compiled program.
798
794
  export function reasonSrl(text, { base = null, filename = '<input>', resolve = null, data = [], all = false, limits = {}, proof = false, context = null } = {}) {
799
795
  const compiled = compileSrl(text, { base, filename, resolve, data, context });
800
- const result = run(compiled.nativeProgram ?? loadText(compiled.program, 'compiled.js'), { ...SRL_LIMITS, ...limits, proof });
796
+ const result = run(compiled.nativeProgram ?? loadText(compiled.program, 'compiled.js'), { ...COMPILED_LIMITS, ...limits, proof });
801
797
  const { prefixes, warnings, context: execution } = compiled;
802
798
  return { quads: srlQuads(compiled, srlAnswers(result), { all }), get program() { return compiled.program; }, prefixes, warnings, result, context: execution };
803
799
  }
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.9.15';
2
+ export const VERSION = '0.9.17';