eyemind 0.5.1 → 0.5.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,106 @@
1
+ /**
2
+ * Eyeling Reasoner — rules
3
+ *
4
+ * Built-in rule helpers and utilities used by the engine. This is not the
5
+ * inference engine itself, but shared rule-related machinery.
6
+ */
7
+
8
+
9
+ import {
10
+ LOG_NS,
11
+ Iri,
12
+ Var,
13
+ Blank,
14
+ ListTerm,
15
+ OpenListTerm,
16
+ GraphTerm,
17
+ Triple,
18
+ copyQuotedGraphMetadata,
19
+ INTERNAL_BLANK_VAR_PREFIX,
20
+ } from './rdf-prelude.js';
21
+
22
+ function liftBlankRuleVars(premise, conclusion) {
23
+ function isLogIncludesLikePredicate(p) {
24
+ return p instanceof Iri && (p.value === LOG_NS + 'includes' || p.value === LOG_NS + 'notIncludes');
25
+ }
26
+
27
+ // Map blank labels to stable rule-local variable names.
28
+ // This runs at rule construction time; keep it simple and allocation-light.
29
+ const mapping = Object.create(null);
30
+ let counter = 0;
31
+
32
+ // These variables are implementation details used to correlate one blank
33
+ // node across the lifted rule body. Their names must not be spellable by
34
+ // user input; otherwise a user variable such as ?_b1 can capture the
35
+ // lifted blank node and leak it into the rule head. The public custom
36
+ // builtin API maps these names back to ordinary-looking ?_bN variables.
37
+ function blankToVar(label) {
38
+ let name = mapping[label];
39
+ if (name === undefined) {
40
+ counter += 1;
41
+ name = `${INTERNAL_BLANK_VAR_PREFIX}${counter}`;
42
+ mapping[label] = name;
43
+ }
44
+ return new Var(name);
45
+ }
46
+
47
+ function copyQuotedTerm(t) {
48
+ // Quoted formulas are data terms with their own local blank scope.
49
+ // Copy them structurally so later in-place rewrites cannot mutate shared AST,
50
+ // but do not lift their blank nodes into rule-body variables.
51
+ if (t instanceof ListTerm) return new ListTerm(t.elems.map(copyQuotedTerm));
52
+ if (t instanceof OpenListTerm) return new OpenListTerm(t.prefix.map(copyQuotedTerm), t.tailVar);
53
+ if (t instanceof GraphTerm) {
54
+ const triples = t.triples.map(
55
+ (tr) => new Triple(copyQuotedTerm(tr.s), copyQuotedTerm(tr.p), copyQuotedTerm(tr.o)),
56
+ );
57
+ return copyQuotedGraphMetadata(t, new GraphTerm(triples));
58
+ }
59
+ return t;
60
+ }
61
+
62
+ function convertQuotedPatternTerm(t) {
63
+ if (t instanceof Blank) return blankToVar(t.label);
64
+ if (t instanceof ListTerm) return new ListTerm(t.elems.map(convertQuotedPatternTerm));
65
+ if (t instanceof OpenListTerm) return new OpenListTerm(t.prefix.map(convertQuotedPatternTerm), t.tailVar);
66
+ if (t instanceof GraphTerm) {
67
+ const triples = t.triples.map(
68
+ (tr) =>
69
+ new Triple(convertQuotedPatternTerm(tr.s), convertQuotedPatternTerm(tr.p), convertQuotedPatternTerm(tr.o)),
70
+ );
71
+ return copyQuotedGraphMetadata(t, new GraphTerm(triples));
72
+ }
73
+ return t;
74
+ }
75
+
76
+ function convertTerm(t, allowDirectQuotedPattern = false) {
77
+ if (t instanceof Blank) return blankToVar(t.label);
78
+ if (t instanceof ListTerm) return new ListTerm(t.elems.map((e) => convertTerm(e, false)));
79
+ if (t instanceof OpenListTerm)
80
+ return new OpenListTerm(
81
+ t.prefix.map((e) => convertTerm(e, false)),
82
+ t.tailVar,
83
+ );
84
+ if (t instanceof GraphTerm) return allowDirectQuotedPattern ? convertQuotedPatternTerm(t) : copyQuotedTerm(t);
85
+ return t;
86
+ }
87
+
88
+ const newPremise = premise.map((tr) => {
89
+ // In log:includes / log:notIncludes, quoted formula operands are formulas
90
+ // consumed by the builtin rather than ordinary triple patterns. Keep their
91
+ // local blank nodes as Blank terms so the builtin can treat them as local
92
+ // existentials, and bindings returned from an explicit scope are blank nodes
93
+ // instead of synthetic rule variables.
94
+ const keepFormulaBlanks = isLogIncludesLikePredicate(tr.p);
95
+ return new Triple(
96
+ keepFormulaBlanks && tr.s instanceof GraphTerm ? copyQuotedTerm(tr.s) : convertTerm(tr.s, true),
97
+ convertTerm(tr.p, true),
98
+ keepFormulaBlanks && tr.o instanceof GraphTerm ? copyQuotedTerm(tr.o) : convertTerm(tr.o, true),
99
+ );
100
+ });
101
+ return [newPremise, conclusion];
102
+ }
103
+
104
+ export {
105
+ liftBlankRuleVars,
106
+ };
@@ -0,0 +1,249 @@
1
+ // The RDF 1.2 grammars of Turtle, TriG, N-Triples and N-Quads, checked token
2
+ // by token before eyeling's parser reads a document.
3
+ //
4
+ // eyeling's parser reads N3, a superset of these formats, so on its own it
5
+ // would accept what they forbid: N3 operators and formulas, ?variables,
6
+ // keywords, unknown escapes, malformed names. This pass reads the document
7
+ // with the formats' own token rules and the statement shapes the parser
8
+ // cannot tell apart from N3, and throws a SyntaxError naming the problem.
9
+
10
+ const PN_CHARS_BASE = 'A-Za-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D' +
11
+ '\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD\\u{10000}-\\u{EFFFF}';
12
+ const PN_CHARS_U = `${PN_CHARS_BASE}_`;
13
+ const PN_CHARS = `${PN_CHARS_U}\\-0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040`;
14
+ const PLX = '%[0-9A-Fa-f]{2}|\\\\[_~.\\-!$&\'()*+,;=/?#@%]';
15
+ const PN_PREFIX = `[${PN_CHARS_BASE}](?:[${PN_CHARS}.]*[${PN_CHARS}])?`;
16
+ const PN_LOCAL = `(?:[${PN_CHARS_U}:0-9]|${PLX})(?:(?:[${PN_CHARS}.:]|${PLX})*(?:[${PN_CHARS}:]|${PLX}))?`;
17
+ const PNAME = new RegExp(`^(?:${PN_PREFIX})?:(?:${PN_LOCAL})?`, 'u');
18
+ const BLANK = new RegExp(`^_:[${PN_CHARS_U}0-9](?:[${PN_CHARS}.]*[${PN_CHARS}])?`, 'u');
19
+ const LANGTAG = /^@[A-Za-z]+(?:-[A-Za-z0-9]+)*(?:--[A-Za-z]+)?/;
20
+ const NUMBER = /^[+-]?(?:[0-9]+(?:\.[0-9]*)?[eE][+-]?[0-9]+|\.[0-9]+[eE][+-]?[0-9]+|[0-9]*\.[0-9]+|[0-9]+)/;
21
+ const UCHAR = /^\\(?:u[0-9A-Fa-f]{4}|U[0-9A-Fa-f]{8})/;
22
+ const PUNCT = ['<<(', ')>>', '<<', '>>', '{|', '|}', '^^', '.', ';', ',', '[', ']', '(', ')', '{', '}', '~'];
23
+ const KEYWORDS = new Set(['a', 'true', 'false', 'PREFIX', 'BASE', 'VERSION', 'GRAPH']);
24
+ const DIRECTIVES = new Set(['@prefix', '@base', '@version']);
25
+
26
+ // The tokens of a document: { k: kind, v: text }.
27
+ function tokens(text, line) {
28
+ const out = [];
29
+ let i = 0;
30
+ const fail = (message) => {
31
+ throw new SyntaxError(message);
32
+ };
33
+ while (i < text.length) {
34
+ const ch = text[i];
35
+ if (/\s/.test(ch)) {
36
+ i += 1;
37
+ continue;
38
+ }
39
+ if (ch === '#') {
40
+ while (i < text.length && text[i] !== '\n' && text[i] !== '\r') i += 1;
41
+ continue;
42
+ }
43
+ const rest = text.slice(i, i + 3);
44
+ if (ch === '<' && !rest.startsWith('<<')) {
45
+ // An IRI: no spaces, no <>"{}|^`\ but escapes \u and \U.
46
+ let j = i + 1;
47
+ while (j < text.length && text[j] !== '>') {
48
+ if (text[j] === '\\') {
49
+ const m = UCHAR.exec(text.slice(j));
50
+ if (!m) fail(`invalid escape in an IRI: ${text.slice(j, j + 2)}`);
51
+ j += m[0].length;
52
+ } else if (/[\u0000-\u0020<"{}|^`]/.test(text[j])) fail(`invalid character in an IRI: ${JSON.stringify(text[j])}`);
53
+ else j += 1;
54
+ }
55
+ if (j >= text.length) fail('an IRI is not closed with >');
56
+ out.push({ k: 'iri', v: text.slice(i, j + 1) });
57
+ i = j + 1;
58
+ continue;
59
+ }
60
+ if (ch === '"' || ch === "'") {
61
+ const long = text.startsWith(ch.repeat(3), i);
62
+ if (line && (long || ch === "'")) fail('only "..." strings are allowed in RDF line syntax');
63
+ let j = i + (long ? 3 : 1);
64
+ for (;;) {
65
+ if (j >= text.length) fail('a string is not closed');
66
+ if (long ? text.startsWith(ch.repeat(3), j) : text[j] === ch) break;
67
+ if (!long && (text[j] === '\n' || text[j] === '\r')) fail('a short string cannot hold a line break');
68
+ if (text[j] === '\\') {
69
+ const m = UCHAR.exec(text.slice(j));
70
+ if (m) j += m[0].length;
71
+ else if (/[tbnrf"'\\]/.test(text[j + 1] ?? '')) j += 2;
72
+ else fail(`invalid escape in a string: ${text.slice(j, j + 2)}`);
73
+ } else j += 1;
74
+ }
75
+ j += long ? 3 : 1;
76
+ out.push({ k: 'string', v: text.slice(i, j) });
77
+ i = j;
78
+ const tag = LANGTAG.exec(text.slice(i));
79
+ if (text[i] === '@') {
80
+ if (!tag) fail('invalid language tag');
81
+ if (/--/.test(tag[0]) && !/--(?:ltr|rtl)$/.test(tag[0])) fail(`invalid base direction ${tag[0]}`);
82
+ out.push({ k: 'langtag', v: tag[0] });
83
+ i += tag[0].length;
84
+ }
85
+ continue;
86
+ }
87
+ const punct = PUNCT.find((p) => text.startsWith(p, i));
88
+ if (punct && !(punct === '.' && /[0-9]/.test(text[i + 1] ?? '') && !/[0-9A-Za-z_:]/.test(text[i - 1] ?? ''))) {
89
+ out.push({ k: punct, v: punct });
90
+ i += punct.length;
91
+ continue;
92
+ }
93
+ if (text.startsWith('_:', i)) {
94
+ const m = BLANK.exec(text.slice(i));
95
+ if (!m) fail(`invalid blank node label ${text.slice(i, i + 12)}`);
96
+ out.push({ k: 'bnode', v: m[0] });
97
+ i += m[0].length;
98
+ continue;
99
+ }
100
+ if (/[0-9+\-.]/.test(ch)) {
101
+ const m = NUMBER.exec(text.slice(i));
102
+ if (!m) fail(`invalid number ${text.slice(i, i + 12)}`);
103
+ out.push({ k: 'number', v: m[0] });
104
+ i += m[0].length;
105
+ continue;
106
+ }
107
+ if (ch === '@') {
108
+ const m = /^@[A-Za-z]+/.exec(text.slice(i));
109
+ if (!m || !DIRECTIVES.has(m[0])) fail(`unknown directive ${m ? m[0] : '@'}`);
110
+ out.push({ k: m[0], v: m[0] });
111
+ i += m[0].length;
112
+ continue;
113
+ }
114
+ const pname = PNAME.exec(text.slice(i));
115
+ if (pname && pname[0].includes(':')) {
116
+ out.push({ k: 'pname', v: pname[0] });
117
+ i += pname[0].length;
118
+ continue;
119
+ }
120
+ const word = /^[A-Za-z]+/.exec(text.slice(i));
121
+ if (word && (KEYWORDS.has(word[0]) || /^(?:prefix|base|version|graph)$/i.test(word[0]))) {
122
+ const upper = word[0].toUpperCase();
123
+ out.push({ k: KEYWORDS.has(word[0]) && word[0] !== upper ? word[0] : upper, v: word[0] });
124
+ i += word[0].length;
125
+ continue;
126
+ }
127
+ fail(`unexpected ${JSON.stringify(text.slice(i, i + 12))}`);
128
+ }
129
+ return out;
130
+ }
131
+
132
+ const OPENS = { '[': ']', '(': ')', '<<': '>>', '<<(': ')>>', '{|': '|}' };
133
+ const CLOSES = new Set(Object.values(OPENS));
134
+
135
+ // Check a document of the given format; throws a SyntaxError.
136
+ export function checkRdfSyntax(text, format) {
137
+ const line = format === 'n-triples' || format === 'n-quads';
138
+ const trig = format === 'trig';
139
+ const ts = tokens(text, line);
140
+ const allowed = line ? new Set(['iri', 'bnode', 'string', 'langtag', '^^', '.', '<<(', ')>>', 'VERSION']) : null;
141
+ const declared = new Set();
142
+ const nesting = []; // open brackets, parentheses, reified triples and annotation blocks
143
+ let graph = false; // inside a TriG graph's braces
144
+ let items = 0; // top-level items of the statement so far
145
+ let first = null; // the statement's first item: 'term', 'list', '[]', '[...]' or '<<'
146
+ let directive = 0; // tokens left of a directive
147
+ const fail = (message) => {
148
+ throw new SyntaxError(message);
149
+ };
150
+ // A statement ends: one that is only a subject is an error, unless it is
151
+ // a blank node property list [ ... ] or a reified triple << ... >>.
152
+ const endStatement = (what) => {
153
+ if (items === 1 && first !== '[...]' && first !== '<<') fail(`${what} has no predicate`);
154
+ items = 0;
155
+ first = null;
156
+ };
157
+ for (let k = 0; k < ts.length; k++) {
158
+ const t = ts[k];
159
+ const prev = ts[k - 1];
160
+ const next = ts[k + 1];
161
+ if (allowed && !allowed.has(t.k)) fail(`${t.v} is not allowed in ${format}`);
162
+ if (line && t.k === 'iri' && !/^<[A-Za-z][A-Za-z0-9+.-]*:/.test(t.v)) fail(`an IRI in ${format} must be absolute: ${t.v}`);
163
+ if (t.k === 'pname') {
164
+ const name = t.v.slice(0, t.v.indexOf(':'));
165
+ if (['@prefix', 'PREFIX'].includes(prev?.k)) declared.add(name);
166
+ else if (!declared.has(name)) fail(`the prefix ${name}: is not declared`);
167
+ }
168
+ if (directive > 0) {
169
+ directive -= 1;
170
+ continue;
171
+ }
172
+ const inReified = nesting.some((n) => n === '<<' || n === '<<(');
173
+ const between = () => {
174
+ if (graph || nesting.length || items) fail(`${t.v} is only allowed between statements`);
175
+ };
176
+ switch (t.k) {
177
+ case '@prefix':
178
+ case 'PREFIX':
179
+ between();
180
+ if (next?.k !== 'pname' || !next.v.endsWith(':') || ts[k + 2]?.k !== 'iri') fail(`${t.v} takes a prefix name and an IRI`);
181
+ if ((ts[k + 3]?.k === '.') !== (t.k === '@prefix')) fail(t.k === '@prefix' ? '@prefix ends with a dot' : 'PREFIX has no dot');
182
+ directive = t.k === '@prefix' ? 3 : 2;
183
+ continue;
184
+ case '@base':
185
+ case 'BASE':
186
+ between();
187
+ if (next?.k !== 'iri') fail(`${t.v} takes an IRI`);
188
+ if ((ts[k + 2]?.k === '.') !== (t.k === '@base')) fail(t.k === '@base' ? '@base ends with a dot' : 'BASE has no dot');
189
+ directive = t.k === '@base' ? 2 : 1;
190
+ continue;
191
+ case '@version':
192
+ case 'VERSION':
193
+ between();
194
+ if (next?.k !== 'string' || next.v.startsWith(next.v[0].repeat(3))) fail(`${t.v} takes a short string`);
195
+ if ((ts[k + 2]?.k === '.') !== (t.k === '@version')) fail(t.k === '@version' ? '@version ends with a dot' : 'VERSION has no dot');
196
+ directive = t.k === '@version' ? 2 : 1;
197
+ continue;
198
+ case 'GRAPH':
199
+ if (!trig) fail(`GRAPH is not allowed in ${format}`);
200
+ between();
201
+ continue;
202
+ case 'a':
203
+ // a is a predicate: never a subject or an object.
204
+ if (items === 0 || (prev && ['(', '<<', '<<(', '^^'].includes(prev.k)) ||
205
+ (next && ['.', ';', ',', ']', ')', '}', '|}', '>>', ')>>'].includes(next.k))) fail('a is only a predicate');
206
+ break;
207
+ case '{':
208
+ if (!trig) fail(`{ is not allowed in ${format}`);
209
+ if (graph || nesting.length) fail('TriG graphs do not nest');
210
+ // A graph is named by at most one term: GRAPH g { or g { or {.
211
+ if (items > 1 || (items === 1 && !['term', '[]'].includes(first))) fail('a TriG graph is named by an IRI or a blank node');
212
+ graph = true;
213
+ items = 0;
214
+ first = null;
215
+ continue;
216
+ case '}':
217
+ if (!graph || nesting.length) fail('} closes no graph');
218
+ if (items) endStatement(prev.v);
219
+ graph = false;
220
+ if (next?.k === '.') fail('a TriG graph is not followed by a dot');
221
+ continue;
222
+ case '.':
223
+ if (nesting.length) fail('. inside brackets');
224
+ if (items === 0) fail('a statement is empty');
225
+ endStatement(prev.v);
226
+ continue;
227
+ default:
228
+ }
229
+ if (OPENS[t.k]) {
230
+ if (inReified && (t.k === '(' || (t.k === '[' && next?.k !== ']'))) {
231
+ fail('a reified triple or triple term holds no lists or blank node property lists');
232
+ }
233
+ if (nesting.length === 0) {
234
+ if (items === 0) first = t.k === '(' ? 'list' : t.k === '[' ? (next?.k === ']' ? '[]' : '[...]') : t.k === '<<' ? '<<' : 'term';
235
+ items += 1;
236
+ }
237
+ nesting.push(t.k);
238
+ } else if (CLOSES.has(t.k)) {
239
+ const open = nesting.pop();
240
+ if (OPENS[open] !== t.k) fail(`${t.v} closes nothing`);
241
+ } else if (nesting.length === 0) {
242
+ if (items === 0) first = 'term';
243
+ items += 1;
244
+ }
245
+ }
246
+ if (nesting.length) fail('a bracket is not closed');
247
+ if (graph) fail('a TriG graph is not closed');
248
+ if (items) fail('the last statement does not end');
249
+ }