eyemind 0.8.51 → 0.9.0

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/src/le.js CHANGED
@@ -1,656 +1,1212 @@
1
- // Logical English: an explicit grammar, ordinary LS clauses,
2
- // and conclusions that can be read back as facts. No input text is executed.
1
+ // Logical English, the controlled natural language of Robert Kowalski and his
2
+ // colleagues, compiled to ordinary LS clauses. eyemind reads the core that the
3
+ // original implementation and Logical English 2 share: templates, a knowledge
4
+ // base of facts and rules, scenarios, queries and their expected answers.
5
+ // LE-SPEC.md describes what it accepts. No input text is executed.
6
+ //
7
+ // A template is a predicate whose name joins the template's words. Rules are
8
+ // backward clauses, as in LE's Prolog target. When a document has scenarios,
9
+ // every relation gets the scenario as its first argument: the knowledge base
10
+ // holds in every scenario, a scenario's facts only in that one, so a single
11
+ // program answers every query in every scenario.
3
12
  import { PRIMITIVE_KEYS } from './builtins.js';
4
13
  import { CONTROL_KEYS, Program, RESERVED_KEYS, Source } from './program.js';
14
+ import { loadText } from './lang.js';
5
15
  import { readTerm } from './reader.js';
6
- import { EMPTY, EyemindError, Struct, Var, conjunction, flattenConjunction } from './terms.js';
16
+ import { EMPTY, EyemindError, Struct, Var, conjunction } from './terms.js';
7
17
  import { write } from './writer.js';
8
- import { compileOdrlLe, odrlLeReport, snapshotGoal } from './le-odrl.js';
9
- import { dpvRules } from './dpv.js';
10
- import { loadText } from './lang.js';
11
- import { ARITHMETIC_NAMES, CONSTANTS, takes } from './arith.js';
12
18
 
13
19
  const st = (name, ...args) => new Struct(name, args);
14
- const VARIABLE = /^[A-Z][0-9]*$/;
15
- const NAME = /^[a-z][A-Za-z0-9_]*$/;
16
- const PREFIX = /^[A-Za-z][A-Za-z0-9_]*$/;
17
- const LOCAL = /^[A-Za-z0-9_][A-Za-z0-9_-]*$/;
18
- const RDF_TYPE = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#type';
19
- const SENTENCE_WORDS = new Set(['every', 'for', 'if', 'find', 'there', 'it', 'contradiction', 'use']);
20
- const RESERVED = new Set([...PRIMITIVE_KEYS, ...CONTROL_KEYS, ...RESERVED_KEYS].map((key) => key.split('/')[0]));
21
- for (const name of ['true', 'false', 'fail']) RESERVED.add(name);
22
- const OPERATORS = { '+': ['add', 1], '-': ['sub', 1], '*': ['mul', 2], '/': ['div', 2] };
23
- // LS arithmetic functions an expression can call, as exp(X) or gcd(A, B);
24
- // and, or and not are LE words.
25
- const CALLS = new Set([...ARITHMETIC_NAMES].filter((name) => !['and', 'or', 'not'].includes(name)));
26
20
  const list = (items) => items.reduceRight((tail, head) => st('.', head, tail), EMPTY);
27
- const cons = (head, tail) => st('.', head, tail);
28
- const AGGREGATES = { number: 'le:count', sum: 'le:sum', maximum: 'le:max', minimum: 'le:min' };
21
+ const RESERVED = new Set([...PRIMITIVE_KEYS, ...CONTROL_KEYS, ...RESERVED_KEYS].map((key) => key.split('/')[0]));
22
+ const SCENARIO = 'le:scenario', ANSWER = 'le:answer';
23
+ const INTRODUCING = new Set(['a', 'an', 'some', 'each', 'which']);
24
+ const OPERATORS = new Set(['+', '-', '*', '/', '//', 'mod']);
25
+ const COMPARISONS = new Set(['=', '==', '!=', '\\=', '\\==', '<', '>', '<=', '=<', '>=']);
26
+ // LE arithmetic functions and the LS functions they are.
27
+ const FUNCTIONS = { ceiling: 'ceil', floor: 'floor', round: 'round', truncate: 'trunc', integer: 'round', abs: 'abs', sqrt: 'sqrt' };
28
+ const AGGREGATES = { sum: 'le:sum', count: 'le:count', average: 'le:average', min: 'le:min', minimum: 'le:min', max: 'le:max', maximum: 'le:max', list: null };
29
+ const SECTIONS = [
30
+ 'the constants are', 'the functions are', 'the fluents are', 'the events are',
31
+ 'the event predicates are', 'the meta predicates are', 'the meta templates are', 'the facts background includes',
32
+ ];
29
33
 
30
- // Aggregates collect t(...) tuples with findall_sorted, drop repeated tuples
31
- // with le:distinct and fold the rest with these backward rules. Their names
32
- // contain ':', which no LE name can, so they never meet a user's relation.
33
- // Each clause is a function so that every use has its own variables.
34
+ // The helper relations of aggregates, divisions, lists and dates. Their names
35
+ // contain ':', which no template name can, so they never meet a user's relation.
34
36
  const HELPERS = {
35
- 'le:distinct': [
36
- () => [st('le:distinct', EMPTY, EMPTY), []],
37
- () => { const X = new Var('X'); return [st('le:distinct', list([X]), list([X])), []]; },
38
- () => {
39
- const X = new Var('X'), Y = new Var('Y'), T = new Var('T'), R = new Var('R');
40
- return [st('le:distinct', cons(X, cons(Y, T)), R), [st('identical', X, Y), st('le:distinct', cons(Y, T), R)]];
41
- },
42
- () => {
43
- const X = new Var('X'), Y = new Var('Y'), T = new Var('T'), R = new Var('R');
44
- return [st('le:distinct', cons(X, cons(Y, T)), cons(X, R)), [st('not_identical', X, Y), st('le:distinct', cons(Y, T), R)]];
45
- },
46
- ],
47
- 'le:count': [
48
- () => [st('le:count', EMPTY, 0n), []],
49
- () => {
50
- const H = new Var('H'), T = new Var('T'), N = new Var('N'), M = new Var('M');
51
- return [st('le:count', cons(H, T), N), [st('le:count', T, M), st('is', N, st('add', M, 1n))]];
52
- },
53
- ],
54
- 'le:sum': [
55
- () => [st('le:sum', EMPTY, 0n), []],
56
- () => {
57
- const H = new Var('H'), T = new Var('T'), S = new Var('S'), S0 = new Var('S0'), V = new Var('V');
58
- return [st('le:sum', cons(H, T), S), [st('arg', 1n, H, V), st('le:sum', T, S0), st('is', S, st('add', S0, V))]];
59
- },
60
- ],
61
- 'le:max': extremum('le:max', 'ge', 'lt'),
62
- 'le:min': extremum('le:min', 'le', 'gt'),
37
+ 'le:sum': `implied_by(struct('le:sum', [], 0), 'true')
38
+ implied_by(struct('le:sum', [H, ...T], S), [struct('le:sum', T, S0), is(S, add(S0, H))])`,
39
+ 'le:count': `implied_by(struct('le:count', [], 0), 'true')
40
+ implied_by(struct('le:count', [H, ...T], N), [struct('le:count', T, M), is(N, add(M, 1))])`,
41
+ 'le:min': `implied_by(struct('le:min', [X], X), 'true')
42
+ implied_by(struct('le:min', [X, Y, ...T], M), [struct('le:min', [Y, ...T], M0), is(M, min(X, M0))])`,
43
+ 'le:max': `implied_by(struct('le:max', [X], X), 'true')
44
+ implied_by(struct('le:max', [X, Y, ...T], M), [struct('le:max', [Y, ...T], M0), is(M, max(X, M0))])`,
45
+ 'le:average': `implied_by(struct('le:average', [X, ...T], A), [struct('le:sum', [X, ...T], S), struct('le:count', [X, ...T], N), struct('le:divide', S, N, A)])`,
46
+ // Prolog's division: exact for integers that divide, a float otherwise.
47
+ 'le:divide': `implied_by(struct('le:divide', A, B, Q), [is(X, A), is(Y, B), struct('le:quotient', X, Y, Q)])
48
+ implied_by(struct('le:quotient', X, Y, Q), [is_int(X), is_int(Y), eq(mod(X, Y), 0), is(Q, floordiv(X, Y))])
49
+ implied_by(struct('le:quotient', X, Y, Q), [not([is_int(X), is_int(Y), eq(mod(X, Y), 0)]), is(Q, div(X, Y))])`,
50
+ 'le:reverse': `implied_by(struct('le:reverse', L, R), struct('le:reverse', L, [], R))
51
+ implied_by(struct('le:reverse', [], R, R), 'true')
52
+ implied_by(struct('le:reverse', [H, ...T], A, R), struct('le:reverse', T, [H, ...A], R))`,
53
+ 'le:append': `implied_by(struct('le:append', [], L, L), 'true')
54
+ implied_by(struct('le:append', [H, ...T], L, [H, ...R]), struct('le:append', T, L, R))`,
55
+ 'le:member': `implied_by(struct('le:member', X, [X, ..._]), 'true')
56
+ implied_by(struct('le:member', X, [_, ...T]), struct('le:member', X, T))`,
57
+ // Days since 1970-01-01 in the proleptic Gregorian calendar, and back.
58
+ 'le:days_after': `implied_by(struct('le:days_after', A, N, B), [is_nonvar(B), is_nonvar(N), struct('le:day_number', B, K), is(J, add(K, N)), struct('le:date_of', J, A)])
59
+ implied_by(struct('le:days_after', A, N, B), [is_nonvar(A), is_nonvar(B), is_var(N), struct('le:day_number', A, J), struct('le:day_number', B, K), is(N, sub(J, K))])
60
+ implied_by(struct('le:days_after', A, N, B), [is_nonvar(A), is_nonvar(N), is_var(B), struct('le:day_number', A, J), is(K, sub(J, N)), struct('le:date_of', K, B)])
61
+ implied_by(struct('le:day_number', date(Y, M, D), N), [
62
+ is(Y1, sub(Y, floordiv(sub(14, M), 12))), is(Era, floordiv(Y1, 400)), is(Yoe, sub(Y1, mul(Era, 400))),
63
+ is(Doy, add(sub(floordiv(add(mul(153, mod(add(M, 9), 12)), 2), 5), 1), D)),
64
+ is(Doe, add(sub(add(mul(Yoe, 365), floordiv(Yoe, 4)), floordiv(Yoe, 100)), Doy)),
65
+ is(N, sub(add(mul(Era, 146097), Doe), 719468))])
66
+ implied_by(struct('le:date_of', N, date(Y, M, D)), [
67
+ is(Z, add(N, 719468)), is(Era, floordiv(Z, 146097)), is(Doe, sub(Z, mul(Era, 146097))),
68
+ is(Yoe, floordiv(sub(add(sub(Doe, floordiv(Doe, 1460)), floordiv(Doe, 36524)), floordiv(Doe, 146096)), 365)),
69
+ is(Doy, sub(Doe, sub(add(mul(365, Yoe), floordiv(Yoe, 4)), floordiv(Yoe, 100)))),
70
+ is(Mp, floordiv(add(mul(5, Doy), 2), 153)), is(D, add(sub(Doy, floordiv(add(mul(153, Mp), 2), 5)), 1)),
71
+ is(M, sub(add(Mp, 3), mul(12, floordiv(Mp, 10)))), is(Y, add(add(Yoe, mul(Era, 400)), floordiv(sub(14, M), 12)))])`,
63
72
  };
73
+ // The helpers each helper calls.
74
+ const NEEDS = { 'le:average': ['le:sum', 'le:count', 'le:divide'] };
64
75
 
65
- // The value of a list's best tuple; an empty list has none.
66
- function extremum(name, keep, pass) {
67
- const one = () => { const H = new Var('H'), V = new Var('V'); return [st(name, list([H]), V), [st('arg', 1n, H, V)]]; };
68
- const more = (test, chosen) => () => {
69
- const H = new Var('H'), I = new Var('I'), T = new Var('T'), M = new Var('M'), M0 = new Var('M0'), V = new Var('V');
70
- return [st(name, cons(H, cons(I, T)), M),
71
- [st(name, cons(I, T), M0), st('arg', 1n, H, V), st(test, V, M0), st('unify', M, chosen(V, M0))]];
72
- };
73
- return [one, more(keep, (V) => V), more(pass, (V, M0) => M0)];
76
+ // ---------------------------------------------------------------- Tokens
77
+
78
+ // A word may join parts with hyphens and apostrophes; a final 's is a word of
79
+ // its own, so that "the person's" meets a template's "*a person*'s".
80
+ const WORD = /^(?:\p{N}+\p{L}|[\p{L}_])[\p{L}\p{N}_]*(?:-[\p{L}\p{N}_]+|['’](?!s(?![\p{L}\p{N}_]))[\p{L}\p{N}_]+)*/u;
81
+ const POSSESSIVE = /^['’]s(?![\p{L}\p{N}_])/u;
82
+ const DATE = /^(\d{4})-(\d{2})-(\d{2})(?![\p{L}\p{N}_])/u;
83
+ // Numbers may group thousands with commas, as in 1,000,000.
84
+ const NUMBER = /^(?:\d{1,3}(?:,\d{3})+|\d+)(?:\.\d+)?(?:[eE][+-]?\d+)?(?![\p{L}\p{N}_])/u;
85
+ const SYMBOLS = ['\\==', '>=', '=<', '<=', '==', '!=', '\\=', '//'];
86
+
87
+ // Tokens carry their line, the indentation of that line (a tab counts four
88
+ // spaces, as LE's editor shows it) and whether they begin it.
89
+ function tokenize(text, file) {
90
+ const tokens = [];
91
+ let line = 1, indent = 0, bol = true, pos = 0;
92
+ const fail = (message) => { throw new EyemindError(`${file}: line ${line}: Logical English: ${message}`); };
93
+ while (pos < text.length) {
94
+ const c = text[pos];
95
+ if (c === '\n') { line++; indent = 0; bol = true; pos++; continue; }
96
+ if (c === ' ' || c === '\t' || c === '\r') { if (bol) indent += c === '\t' ? 4 : c === ' ' ? 1 : 0; pos++; continue; }
97
+ if (c === '%' || c === '#') { while (pos < text.length && text[pos] !== '\n') pos++; continue; }
98
+ if (text.startsWith('/*', pos)) {
99
+ const end = text.indexOf('*/', pos + 2);
100
+ if (end < 0) fail('a block comment is not closed with */');
101
+ line += (text.slice(pos, end).match(/\n/g) ?? []).length;
102
+ pos = end + 2;
103
+ continue;
104
+ }
105
+ const tail = text.slice(pos);
106
+ let token;
107
+ if (POSSESSIVE.test(tail) && pos > 0 && !/\s/.test(text[pos - 1])) {
108
+ token = { text: tail.slice(0, 2), kind: 'word' };
109
+ } else if (c === '"' || c === "'") {
110
+ const match = (c === '"' ? /^"(?:[^"\\\n]|\\.)*"/ : /^'(?:[^'\\\n]|\\.)*'/).exec(tail);
111
+ if (!match) fail('a quoted text is not closed on its line');
112
+ token = { text: match[0], kind: 'string', value: match[0].slice(1, -1).replace(/\\(.)/g, '$1') };
113
+ } else if (DATE.test(tail)) {
114
+ const [raw, y, m, d] = DATE.exec(tail);
115
+ token = { text: raw, kind: 'date', value: [BigInt(y), BigInt(m), BigInt(d)] };
116
+ } else if (WORD.test(tail)) {
117
+ token = { text: WORD.exec(tail)[0], kind: 'word' };
118
+ } else if (NUMBER.test(tail)) {
119
+ const raw = NUMBER.exec(tail)[0];
120
+ const digits = raw.replaceAll(',', '');
121
+ token = { text: raw, kind: 'number', value: /[.eE]/.test(digits) ? Number(digits) : BigInt(digits) };
122
+ } else {
123
+ const symbol = SYMBOLS.find((s) => tail.startsWith(s)) ?? c;
124
+ token = { text: symbol, kind: 'punct' };
125
+ // A full stop ends a sentence when white space or the end follows it.
126
+ if (symbol === '.' && (pos + 1 === text.length || /\s/.test(text[pos + 1]))) token.kind = 'stop';
127
+ }
128
+ tokens.push({ ...token, line, indent, bol });
129
+ bol = false;
130
+ pos += token.text.length;
131
+ }
132
+ tokens.push({ text: '', kind: 'end', line, indent: 0, bol: true });
133
+ return tokens;
74
134
  }
75
135
 
76
- function listItems(term) {
77
- const items = [];
78
- while (term instanceof Struct && term.name === '.' && term.args.length === 2) {
79
- items.push(term.args[0]);
80
- term = term.args[1];
136
+ const lower = (token) => token.kind === 'word' ? token.text.toLowerCase() : token.text;
137
+ const isWord = (token, ...words) => token.kind === 'word' && words.includes(token.text.toLowerCase());
138
+ // Words joined as written: no space before a comma, a closing bracket or 's.
139
+ const joined = (words) => words.join(' ').replace(/ ([,:\])]) ?/g, '$1 ').replace(/([[(]) /g, '$1').replace(/ (['’]s)(?= |$)/g, '$1').replace(/ +$/, '');
140
+ const phrase = (tokens) => joined(tokens.map((t) => t.text));
141
+ // Whether tokens start with these words, compared without case.
142
+ const startsWith = (tokens, words, at = 0) => words.every((word, i) => tokens[at + i] && lower(tokens[at + i]) === word);
143
+ const indexOfWords = (tokens, words, from = 0) => {
144
+ for (let i = from; i + words.length <= tokens.length; i++) if (startsWith(tokens, words, i)) return i;
145
+ return -1;
146
+ };
147
+
148
+ // Brackets balance in a slice, and its words lie outside them.
149
+ function balanced(tokens) {
150
+ let depth = 0;
151
+ for (const token of tokens) {
152
+ if (token.text === '[' || token.text === '(') depth++;
153
+ else if (token.text === ']' || token.text === ')') { if (--depth < 0) return false; }
154
+ }
155
+ return depth === 0;
156
+ }
157
+
158
+ function depths(tokens) {
159
+ const out = [];
160
+ let depth = 0;
161
+ for (const token of tokens) {
162
+ if (token.kind === 'punct' && (token.text === ']' || token.text === ')')) depth--;
163
+ out.push(depth);
164
+ if (token.kind === 'punct' && (token.text === '[' || token.text === '(')) depth++;
165
+ }
166
+ return out;
167
+ }
168
+
169
+ // ---------------------------------------------------------------- Templates
170
+
171
+ // A template's parts are words and places. A place after "that" holds a
172
+ // sentence; a place after "is a" in the built-in type template holds a type.
173
+ function readTemplate(tokens, error, starred = true) {
174
+ const parts = [];
175
+ // In a document without asterisks, as LE1 also writes templates, "a" or
176
+ // "an" and the word after it make a place.
177
+ for (let i = 0; i < tokens.length; i++) {
178
+ const token = tokens[i];
179
+ if (!starred && isWord(token, 'a', 'an') && tokens[i + 1]?.kind === 'word') {
180
+ parts.push({ place: true, name: tokens[i + 1].text, meta: parts.at(-1)?.word === 'that' });
181
+ i++;
182
+ } else if (token.text === '*') {
183
+ const end = tokens.findIndex((t, j) => j > i && t.text === '*');
184
+ if (end < 0) error('a place in a template needs a closing *', token.line);
185
+ const words = tokens.slice(i + 1, end);
186
+ if (!words.length || !words.every((t) => t.kind === 'word')) error('a place in a template is a phrase such as *a person*', token.line);
187
+ const named = INTRODUCING.has(lower(words[0])) || lower(words[0]) === 'the' ? words.slice(1) : words;
188
+ parts.push({ place: true, name: named.map((t) => t.text).join(' ') || words[0].text, meta: parts.at(-1)?.word === 'that' });
189
+ i = end;
190
+ } else if (token.text === ';') {
191
+ error('template additions after ";" belong to Logical English 2 and are not supported', token.line);
192
+ } else {
193
+ parts.push({ word: lower(token), text: token.text });
194
+ }
81
195
  }
82
- return term === EMPTY ? items : null;
196
+ if (!parts.some((part) => part.word)) error('a template needs at least one word', tokens[0]?.line);
197
+ return parts;
198
+ }
199
+
200
+ function templateName(parts) {
201
+ const name = parts.filter((part) => part.word).map((part) => part.text).join('_');
202
+ return RESERVED.has(name) || name === 'date' ? `le_${name}` : name;
83
203
  }
84
204
 
85
- class Parser {
86
- constructor(text, file) {
205
+ // Built-in templates. Each compiles its arguments to goals; expr marks a
206
+ // place that also takes an arithmetic formula.
207
+ const BUILTINS = [
208
+ ['*a* is equal to *b*', (c, [a, b]) => c.equal(a, b), true],
209
+ ['*a* is different from *b*', (c, [a, b]) => c.different(a, b), true],
210
+ ['*a* is not equal to *b*', (c, [a, b]) => c.different(a, b), true],
211
+ ['*a* is greater than or equal to *b*', (c, [a, b]) => c.compare('ge', a, b), true],
212
+ ['*a* is greater or equal to *b*', (c, [a, b]) => c.compare('ge', a, b), true],
213
+ ['*a* is less than or equal to *b*', (c, [a, b]) => c.compare('le', a, b), true],
214
+ ['*a* is less or equal to *b*', (c, [a, b]) => c.compare('le', a, b), true],
215
+ ['*a* is greater than *b*', (c, [a, b]) => c.compare('gt', a, b), true],
216
+ ['*a* is less than *b*', (c, [a, b]) => c.compare('lt', a, b), true],
217
+ ['*a* is after or equal to *b*', (c, [a, b]) => [st('or', st('compare', '>', a, b), st('compare', '=', a, b))]],
218
+ ['*a* is before or equal to *b*', (c, [a, b]) => [st('or', st('compare', '<', a, b), st('compare', '=', a, b))]],
219
+ ['*a* is not before *b*', (c, [a, b]) => [st('or', st('compare', '>', a, b), st('compare', '=', a, b))]],
220
+ ['*a* is after *b*', (c, [a, b]) => [st('compare', '>', a, b)]],
221
+ ['*a* is before *b*', (c, [a, b]) => [st('compare', '<', a, b)]],
222
+ ['*a* is *n* days after *b*', (c, [a, n, b]) => [c.helper('le:days_after', a, n, b)]],
223
+ ['*a* is *n* day after *b*', (c, [a, n, b]) => [c.helper('le:days_after', a, n, b)]],
224
+ ['*a* is in *b*', (c, [a, b]) => [c.helper('le:member', a, b)]],
225
+ ['*a* is known', (c, [a]) => [st('is_nonvar', a)]],
226
+ ['the minimum of *a* and *b* is *c*', (c, [a, b, m]) => [st('is', m, st('min', a, b))]],
227
+ ['the maximum of *a* and *b* is *c*', (c, [a, b, m]) => [st('is', m, st('max', a, b))]],
228
+ ['the length of *a* is *b*', (c, [a, n]) => [c.helper('le:count', a, n)]],
229
+ ['*a* is the reverse of *b*', (c, [a, b]) => [c.helper('le:reverse', b, a)]],
230
+ ['appending *a* then *b* gives *c*', (c, [a, b, d]) => [c.helper('le:append', a, b, d)]],
231
+ ['*a* has *b* as head before *c*', (c, [a, b, d]) => [st('unify', a, st('.', b, d))]],
232
+ // LE1's "X is Y" equates, or evaluates a formula; it yields to any other
233
+ // template. Between two names it would only fail, so it does not apply,
234
+ // and a sentence no template matches is reported.
235
+ ['*a* is *b*', (c, [a, b]) => a.formula || b.formula || a.term instanceof Var || b.term instanceof Var ? c.equal(a, b) : null, true],
236
+ ].map(([text, compile, expr]) => {
237
+ const parts = readTemplate(tokenize(text, 'built-in').slice(0, -1), (m) => { throw new Error(m); });
238
+ for (const part of parts) if (part.place) part.expr = expr;
239
+ return { parts, compile, builtin: true, words: parts.filter((p) => p.word).length };
240
+ });
241
+ // "X is a T" names a type when no template says more; it is the relation is_a.
242
+ // LE1 also writes "X is of type T".
243
+ const TYPE_TEMPLATES = ['*an object* is a *type*', '*an object* is an *type*', '*an object* is of type *type*'].map((text) => {
244
+ const parts = readTemplate(tokenize(text, 'built-in').slice(0, -1), (m) => { throw new Error(m); });
245
+ parts.at(-1).type = true;
246
+ return { parts, name: 'is_a', arity: 2, typed: true, words: parts.filter((p) => p.word).length };
247
+ });
248
+
249
+ // Every way a template's words meet the tokens, as the slices of its places:
250
+ // each place takes at least one token, and its brackets balance.
251
+ function* matches(parts, tokens, i = 0, j = 0, fills = []) {
252
+ if (i === parts.length) { if (j === tokens.length) yield fills; return; }
253
+ const part = parts[i];
254
+ if (part.word) {
255
+ if (j < tokens.length && sameWord(tokens[j], part)) yield* matches(parts, tokens, i + 1, j + 1, fills);
256
+ return;
257
+ }
258
+ const last = i === parts.length - 1;
259
+ for (let k = last ? tokens.length : j + 1; k <= tokens.length; k++) {
260
+ const slice = tokens.slice(j, k);
261
+ if (!balanced(slice)) continue;
262
+ yield* matches(parts, tokens, i + 1, k, [...fills, slice]);
263
+ if (last) break;
264
+ }
265
+ }
266
+
267
+ function sameWord(token, part) {
268
+ const word = lower(token);
269
+ return word === part.word || (part.word === 'a' && word === 'an') || (part.word === 'an' && word === 'a');
270
+ }
271
+
272
+ // ---------------------------------------------------------------- Variables
273
+
274
+ // An id names a variable: "a person X", or X alone. As in LE2, an id is one
275
+ // capital letter, possibly with digits, or a word of at most six capitals
276
+ // other than UK; eyemind reads short names such as Bob as names, as LE1 does.
277
+ // Alone, before any phrase introduces it, only a capital letter with
278
+ // possibly digits is a variable: LE1 programs use acronyms such as GST and
279
+ // CET as names.
280
+ const ID = /^(?:[A-Z][0-9]*|(?!UK$)[A-Z][A-Z0-9_]{1,5})$/;
281
+ const BARE_ID = /^[A-Z][0-9]*$/;
282
+
283
+ // The variables of one clause, by the phrase that introduced them and by
284
+ // their id. A scope can be saved and restored while conditions are tried.
285
+ class Scope {
286
+ constructor() {
287
+ this.names = new Map();
288
+ this.used = new Set(['Scenario']);
289
+ this.marks = [];
290
+ }
291
+
292
+ save() { return [new Map(this.names), new Set(this.used), this.marks.length]; }
293
+ restore([names, used, marks]) { this.names = names; this.used = used; this.marks.length = marks; }
294
+
295
+ find(words) {
296
+ return this.names.get(words.map((t) => t.text.toLowerCase()).join(' ')) ??
297
+ (words.length === 1 && ID.test(words[0].text) ? this.names.get(`#${words[0].text}`) : undefined);
298
+ }
299
+
300
+ introduce(words) {
301
+ const existing = this.find(words);
302
+ if (existing) return existing;
303
+ const id = words.length > 1 && ID.test(words.at(-1).text) ? words.at(-1).text : words.length === 1 && ID.test(words[0].text) ? words[0].text : null;
304
+ if (id && this.names.has(`#${id}`)) return this.names.get(`#${id}`);
305
+ let base = id ?? words.map((t) => t.text[0].toUpperCase() + t.text.slice(1)).join('').replace(/[^\p{L}\p{N}]/gu, '');
306
+ if (!/^\p{Lu}/u.test(base)) base = `V${base}`;
307
+ let name = base;
308
+ for (let n = 2; this.used.has(name); n++) name = `${base}${n}`;
309
+ this.used.add(name);
310
+ const variable = new Var(name);
311
+ this.names.set(words.map((t) => t.text.toLowerCase()).join(' '), variable);
312
+ if (id) this.names.set(`#${id}`, variable);
313
+ return variable;
314
+ }
315
+ }
316
+
317
+ // Where the words of an aggregate start, after its result phrase at i:
318
+ // "is the sum of each" or "is a collection of". The result phrase holds no
319
+ // connective, so an aggregate after an "and" starts after it.
320
+ function aggregateAt(tokens, i) {
321
+ for (let k = i; k < tokens.length && !(k > i && isWord(tokens[k], 'and', 'or')); k++) {
322
+ if (startsWith(tokens, ['is', 'the'], k) && AGGREGATES[lower(tokens[k + 2] ?? {})] !== undefined && startsWith(tokens, ['of', 'each'], k + 3)) return k;
323
+ if (startsWith(tokens, ['is', 'a', 'collection', 'of'], k)) return k;
324
+ }
325
+ return -1;
326
+ }
327
+
328
+ // ---------------------------------------------------------------- Compiler
329
+
330
+ class Compiler {
331
+ constructor(file, templates) {
87
332
  this.file = file;
88
- this.tokens = [];
89
- this.at = 0;
90
- this.scope = new Map();
91
- this.closed = new Set();
333
+ this.templates = templates;
92
334
  this.helpers = new Set();
93
- this.prefixes = new Map();
94
- this.aggregates = 0;
95
- this.depth = 0;
96
- let line = 1, pos = 0;
97
- while (pos < text.length) {
98
- const tail = text.slice(pos);
99
- const whitespace = /^\s+/.exec(tail);
100
- if (whitespace) { line += (whitespace[0].match(/\n/g) ?? []).length; pos += whitespace[0].length; continue; }
101
- if (tail[0] === '#') { const end = text.indexOf('\n', pos); pos = end < 0 ? text.length : end; continue; }
102
- const match = /^("(?:[^"\\\r\n]|\\.)*"|(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?|[A-Za-z][A-Za-z0-9_]*(?::[A-Za-z0-9_][A-Za-z0-9_-]*)?|[()[\],.+*/-])/.exec(tail);
103
- if (!match) this.error(`unexpected character ${JSON.stringify(tail[0])}`, line);
104
- const raw = match[0];
105
- let value = raw, kind = 'word';
106
- if (raw[0] === '"') {
107
- try { value = JSON.parse(raw); } catch { this.error('invalid quoted name; use a JSON string', line); }
108
- kind = 'string';
109
- } else if (/^[0-9]/.test(raw)) kind = 'number';
110
- else if (!/^[A-Za-z]/.test(raw)) kind = 'punct';
111
- else if (raw.includes(':')) kind = 'qualified';
112
- this.tokens.push({ value, raw, kind, line });
113
- pos += raw.length;
114
- }
115
- this.tokens.push({ value: '', raw: '', kind: 'end', line });
116
- }
117
-
118
- get token() { return this.tokens[this.at]; }
119
- error(message, line = this.token?.line ?? 1) { throw new EyemindError(`${this.file}: line ${line}: Logical English: ${message}`); }
120
- is(word) { return this.token.kind !== 'string' && this.token.value.toLowerCase() === word; }
121
- take(word) { if (!this.is(word)) return false; this.at++; return true; }
122
- need(word) { if (!this.take(word)) this.error(`expected ${JSON.stringify(word)}, found ${JSON.stringify(this.token.raw || 'end of input')}`); }
123
-
124
- name() {
125
- const token = this.token;
126
- if (token.kind === 'qualified') return this.qualifiedName();
127
- if (token.kind !== 'word' || !NAME.test(token.value) || RESERVED.has(token.value)) {
128
- this.error('a relation or class name must start with a lowercase letter and must not name an LS primitive or control');
129
- }
130
- this.at++;
131
- return token.value;
132
- }
133
-
134
- qualifiedName() {
135
- const token = this.token, [prefix, local] = token.value.split(':');
136
- if (!this.prefixes.has(prefix)) this.error(`prefix ${prefix} is undeclared; introduce it with "Use prefix ${prefix} with namespace …"`, token.line);
137
- this.at++;
138
- return st('iri', this.prefixes.get(prefix) + local);
139
- }
140
-
141
- statement(name, subject, ...objects) {
142
- if (typeof name === 'string') return st(name, subject, ...objects);
143
- // After an ODRL directive, qualified statements take the names, true,
144
- // false and operand lists the short forms take; le-odrl.js maps them.
145
- const name_ = (term) => this.odrl && typeof term === 'string';
146
- if (!rdfResource(subject) && !name_(subject)) this.error('a qualified RDF statement needs a resource subject such as ex:item, iri(...) or a variable');
147
- if (!objects.length) return st('rdf', subject, st('iri', RDF_TYPE), name);
148
- const [object] = objects, items = this.odrl ? listItems(object) : null;
149
- if (!rdfValue(object) && !name_(object) && !(items?.length && items.every((item) => rdfValue(item) || name_(item)))) {
150
- this.error('a qualified RDF property needs an RDF value such as a qualified name, number or literal(...)');
151
- }
152
- return st('rdf', subject, name, object);
153
- }
154
-
155
- declarations() {
156
- const vars = [];
157
- do {
158
- const name = this.token.value;
159
- if (this.token.kind !== 'word' || !VARIABLE.test(name)) this.error('a variable is one capital letter, optionally followed by digits, such as X or Y1');
160
- if (this.scope.has(name)) this.error(`variable ${name} is already declared in this sentence`);
161
- const variable = new Var(name);
162
- this.scope.set(name, variable);
163
- vars.push(variable);
164
- this.at++;
165
- } while (this.take('and'));
166
- return vars;
167
- }
168
-
169
- nested(read) {
170
- if (this.depth >= 256) this.error('terms and expressions may nest at most 256 levels');
171
- this.depth++;
172
- try { return read(); } finally { this.depth--; }
173
- }
174
-
175
- term() { return this.nested(() => this.termValue()); }
176
-
177
- termValue() {
178
- if (this.take('-')) {
179
- if (this.token.kind !== 'number') this.error('a minus sign in a term needs a number; use the value-of form for arithmetic');
180
- return this.number(true);
181
- }
182
- if (this.token.kind === 'number') return this.number(false);
183
- if (this.take('[')) {
184
- const items = [];
185
- if (!this.take(']')) { do { items.push(this.term()); } while (this.take(',')); this.need(']'); }
335
+ }
336
+
337
+ error(message, line) { throw new EyemindError(`${this.file}: line ${line}: Logical English: ${message}`); }
338
+
339
+ helper(name, ...args) {
340
+ for (const needed of [name, ...(NEEDS[name] ?? [])]) this.helpers.add(needed);
341
+ return st(name, ...args);
342
+ }
343
+
344
+ // A relation's goal: the scenario comes first when the document has any.
345
+ relation(name, args) { return this.scenario === null ? st(name, ...args) : st(name, this.scenario, ...args); }
346
+
347
+ // The term a slice of tokens names, or null when it names none.
348
+ term(tokens, scope, { type = false } = {}) {
349
+ if (!tokens.length) return null;
350
+ const [first] = tokens;
351
+ if (tokens.length === 1 && first.kind === 'string') return first.value;
352
+ if (tokens.length === 1 && first.kind === 'date') return st('date', ...first.value);
353
+ if (tokens.length === 1 && first.kind === 'number') return first.value;
354
+ if (tokens.length === 2 && first.text === '-' && tokens[1].kind === 'number') return -tokens[1].value;
355
+ if (first.text === '[' && tokens.at(-1).text === ']' && balanced(tokens.slice(1, -1))) {
356
+ const inner = tokens.slice(1, -1), items = [];
357
+ if (!inner.length) return EMPTY;
358
+ const level = depths(inner);
359
+ let start = 0;
360
+ for (let i = 0; i <= inner.length; i++) {
361
+ if (i < inner.length && !(inner[i].text === ',' && level[i] === 0)) continue;
362
+ const item = this.term(inner.slice(start, i), scope);
363
+ if (item === null) return null;
364
+ items.push(item);
365
+ start = i + 1;
366
+ }
186
367
  return list(items);
187
368
  }
188
- // The explicit "rule N" marker distinguishes a generated witness from
189
- // an ordinary compound named witness. Its label is data, not a variable.
190
- if (this.is('witness') && this.tokens[this.at + 1]?.value === '(' &&
191
- this.tokens[this.at + 2]?.kind === 'word' && this.tokens[this.at + 2].value.toLowerCase() === 'rule' &&
192
- (this.tokens[this.at + 3]?.kind === 'number' || this.tokens[this.at + 3]?.value === '-')) {
193
- this.at += 3;
194
- const rule = this.term();
195
- if (typeof rule !== 'bigint' || rule < 1n) this.error('a witness rule number must be a positive integer');
196
- this.need(',');
197
- const label = this.token;
198
- if (label.kind !== 'string' && !(label.kind === 'word' && VARIABLE.test(label.value))) {
199
- this.error('a witness label must be a variable name such as Y or a quoted name');
200
- }
201
- this.at++;
202
- const args = [];
203
- while (this.take(',')) args.push(this.term());
204
- this.need(')');
205
- return st('skolem', rule, label.value, list(args));
206
- }
207
- const token = this.token;
208
- if (token.kind === 'qualified') return this.qualifiedName();
209
- if (!['word', 'string'].includes(token.kind)) this.error('expected a name, number, variable, list or compound term');
210
- this.at++;
211
- if (this.take('(')) {
212
- const args = [];
213
- if (!this.take(')')) { do { args.push(this.term()); } while (this.take(',')); this.need(')'); }
214
- if (!args.length) this.error('a compound term needs at least one argument', token.line);
215
- return st(token.value, ...args);
216
- }
217
- if (token.kind === 'word' && VARIABLE.test(token.value)) {
218
- if (this.closed.has(token.value)) this.error(`variable ${token.value} belongs to the aggregate that declares it and cannot be used outside it`, token.line);
219
- if (!this.scope.has(token.value)) this.error(`variable ${token.value} is undeclared; introduce it with "For every", "Find every" or "there exists", or quote it as a name`, token.line);
220
- return this.scope.get(token.value);
221
- }
222
- return token.value;
223
- }
224
-
225
- number(negative) {
226
- const token = this.token;
227
- this.at++;
228
- try { return readTerm((negative ? '-' : '') + token.raw); }
229
- catch { this.error(`invalid or nonfinite number ${(negative ? '-' : '') + token.raw}`, token.line); }
230
- }
231
-
232
- expression(min = 0) { return this.nested(() => this.expressionValue(min)); }
233
-
234
- expressionValue(min) {
235
- let left;
236
- const token = this.token, next = this.tokens[this.at + 1];
237
- if (this.take('-')) left = st('neg', this.expression(3));
238
- else if (this.take('(')) { left = this.expression(); this.need(')'); }
239
- else if (token.kind === 'word' && CALLS.has(token.value) && next?.value === '(') {
240
- this.at += 2;
241
- const args = [];
242
- if (!this.take(')')) { do { args.push(this.expression()); } while (this.take(',')); this.need(')'); }
243
- if (!takes(token.value, args.length)) this.error(`${token.value} does not take ${args.length} argument${args.length === 1 ? '' : 's'}`, token.line);
244
- left = st(token.value, ...args);
245
- } else if (token.kind === 'word' && Object.hasOwn(CONSTANTS, token.value)) {
246
- this.at++;
247
- left = token.value;
248
- } else {
249
- left = this.term();
250
- if (!(left instanceof Var) && !['bigint', 'number'].includes(typeof left)) this.error('arithmetic operands must be numbers or declared variables');
369
+ if (!tokens.every((t) => t.kind === 'word' || t.kind === 'number' || t.text === '&')) return null;
370
+ const head = lower(first), rest = tokens.slice(1);
371
+ // A kind is a name, unless a phrase such as "which type" asks for it.
372
+ if (type && !(INTRODUCING.has(head) && rest.length && scope.find(rest) === undefined && rest.length <= 2)) return tokens.map((t) => t.text).join(' ');
373
+ const at = this.offset(tokens);
374
+ if (INTRODUCING.has(head) && !(first.text === 'A' && tokens.length === 1) && rest.length && rest.length <= 6 && rest.every((t) => t.kind === 'word' && !isWord(t, 'that', 'if'))) {
375
+ return this.mark(scope, scope.introduce(rest), at, tokens.length);
251
376
  }
252
- while (OPERATORS[this.token.value]?.[1] > min) {
253
- const [name, precedence] = OPERATORS[this.token.value];
254
- this.at++;
255
- left = st(name, left, this.expression(precedence));
377
+ if (head === 'the' && rest.length) {
378
+ const found = scope.find(rest);
379
+ if (found) return this.mark(scope, found, at, tokens.length);
380
+ return ['the', ...rest.map((t) => t.text)].join(' ');
256
381
  }
257
- return left;
382
+ const found = scope.find(tokens);
383
+ if (found) return this.mark(scope, found, at, tokens.length);
384
+ if (tokens.length === 1 && BARE_ID.test(first.text) && !this.fact) return this.mark(scope, scope.introduce(tokens), at, 1);
385
+ return tokens.map((t) => t.text).join(' ');
258
386
  }
259
387
 
260
- atomic(body) {
261
- if (body && this.take('it')) {
262
- this.need('is'); this.need('not'); this.need('known'); this.need('that');
263
- return st('not', this.atomic(false));
264
- }
265
- const subject = this.term();
266
- if (this.take('has')) {
267
- const name = this.name();
268
- return this.statement(name, subject, this.term());
388
+ // Where a slice starts in the sentence a query renders its answers from.
389
+ offset(tokens) { return this.sentence ? this.sentence.indexOf(tokens[0]) : -1; }
390
+
391
+ mark(scope, variable, at, length) {
392
+ if (at >= 0) scope.marks.push({ at, length, variable });
393
+ return variable;
394
+ }
395
+
396
+ // An arithmetic formula or a term: { term, goals, formula }.
397
+ expression(tokens, scope) {
398
+ // In a formula, ET-P is ET - P when its parts are variables.
399
+ tokens = tokens.flatMap((t) => {
400
+ if (t.kind !== 'word' || !t.text.includes('-') || scope.find([t])) return [t];
401
+ const parts = t.text.split('-').map((text) => ({ ...t, text }));
402
+ if (!parts.every((part) => scope.find([part]))) return [t];
403
+ return parts.flatMap((part, i) => i ? [{ ...t, text: '-', kind: 'punct' }, part] : [part]);
404
+ });
405
+ const level = depths(tokens);
406
+ if (!tokens.some((t, i) => level[i] === 0 && (OPERATORS.has(lower(t)) && !(t.kind === 'word' && t.text !== 'mod')) || t.text === '(')) {
407
+ const term = this.term(tokens, scope);
408
+ return term === null ? null : { term, goals: [], formula: false };
269
409
  }
270
- if (this.take('is')) {
271
- if (this.is('not')) this.error('ordinary "not" is unsupported; use "it is not known that" in a premise for absence, or a separate relation for explicit negative evidence');
272
- if (!body && this.is('the')) this.error('put calculations in a premise, as in "Y is the value of X + 1", then state the result relation');
273
- if (this.take('a') || this.take('an')) {
274
- const name = this.name();
275
- return this.take('of') ? this.statement(name, subject, this.term()) : this.statement(name, subject);
410
+ const goals = [];
411
+ let at = 0;
412
+ const peek = () => tokens[at];
413
+ const operand = () => {
414
+ const start = at;
415
+ let depth = 0;
416
+ while (at < tokens.length) {
417
+ const t = tokens[at];
418
+ if (t.text === '[') depth++;
419
+ if (t.text === ']') depth--;
420
+ if (depth === 0 && (OPERATORS.has(lower(t)) && (t.kind !== 'word' || t.text === 'mod') || t.text === '(' || t.text === ')' || t.text === ',')) break;
421
+ at++;
422
+ }
423
+ if (at === start) return null;
424
+ return this.term(tokens.slice(start, at), scope);
425
+ };
426
+ const factor = () => {
427
+ const t = peek();
428
+ if (!t) return null;
429
+ if (t.text === '-') { at++; const f = factor(); return f === null ? null : st('neg', f); }
430
+ if (t.text === '(') {
431
+ at++;
432
+ const e = sum();
433
+ if (e === null || peek()?.text !== ')') return null;
434
+ at++;
435
+ return e;
276
436
  }
277
- if (body) {
278
- if (this.take('the')) {
279
- if (!(subject instanceof Var) && !['bigint', 'number'].includes(typeof subject)) this.error('a calculation needs a variable or number on its left');
280
- const kind = Object.keys(AGGREGATES).find((word) => this.is(word));
281
- if (kind) return this.aggregate(subject, kind);
282
- this.need('value'); this.need('of');
283
- return st('is', subject, this.expression());
437
+ if (t.kind === 'word' && FUNCTIONS[lower(t)] && tokens[at + 1]?.text === '(') {
438
+ at += 2;
439
+ const e = sum();
440
+ if (e === null || peek()?.text !== ')') return null;
441
+ at++;
442
+ return st(FUNCTIONS[lower(t)], e);
443
+ }
444
+ return operand();
445
+ };
446
+ const product = () => {
447
+ let left = factor();
448
+ while (left !== null && peek() && ['*', '/', '//'].includes(peek().text) || (left !== null && peek() && peek().kind === 'word' && peek().text === 'mod')) {
449
+ const op = peek().text;
450
+ at++;
451
+ const right = factor();
452
+ if (right === null) return null;
453
+ if (op === '/') {
454
+ const quotient = new Var(`Q${this.quotients = (this.quotients ?? 0) + 1}`);
455
+ goals.push(this.helper('le:divide', left, right, quotient));
456
+ left = quotient;
457
+ } else left = st(op === '*' ? 'mul' : op === '//' ? 'floordiv' : 'mod', left, right);
458
+ }
459
+ return left;
460
+ };
461
+ const sum = () => {
462
+ let left = product();
463
+ while (left !== null && peek() && (peek().text === '+' || peek().text === '-')) {
464
+ const op = peek().text;
465
+ at++;
466
+ const right = product();
467
+ if (right === null) return null;
468
+ left = st(op === '+' ? 'add' : 'sub', left, right);
469
+ }
470
+ return left;
471
+ };
472
+ const term = sum();
473
+ if (term === null || at !== tokens.length) return null;
474
+ return { term, goals, formula: true };
475
+ }
476
+
477
+ equal(a, b) {
478
+ if (!a.formula && !b.formula) return [...a.goals, ...b.goals, st('unify', a.term, b.term)];
479
+ if (!a.formula) return [...b.goals, st('is', a.term, b.term)];
480
+ if (!b.formula) return [...a.goals, st('is', b.term, a.term)];
481
+ return [...a.goals, ...b.goals, st('eq', a.term, b.term)];
482
+ }
483
+
484
+ different(a, b) {
485
+ if (!a.formula && !b.formula) return [st('not_unify', a.term, b.term)];
486
+ return [...a.goals, ...b.goals, st('ne', a.term, b.term)];
487
+ }
488
+
489
+ compare(op, a, b) { return [...a.goals, ...b.goals, st(op, a.term, b.term)]; }
490
+
491
+ // One condition: a comparison, or a sentence of a template.
492
+ condition(tokens, scope) {
493
+ const level = depths(tokens);
494
+ const at = tokens.findIndex((t, i) => level[i] === 0 && t.kind === 'punct' && COMPARISONS.has(t.text));
495
+ if (at > 0) {
496
+ const a = this.expression(tokens.slice(0, at), scope), b = a && this.expression(tokens.slice(at + 1), scope);
497
+ if (!a || !b) return null;
498
+ const op = tokens[at].text;
499
+ if (op === '=' || op === '==') return this.equal(a, b);
500
+ if (op === '!=' || op === '\\=') return this.different(a, b);
501
+ if (op === '\\==') return [st('not_identical', a.term, b.term)];
502
+ return this.compare({ '<': 'lt', '>': 'gt', '<=': 'le', '=<': 'le', '>=': 'ge' }[op], a, b);
503
+ }
504
+ const sentence = this.sentenceOf(tokens, scope);
505
+ if (!sentence) return null;
506
+ if (sentence.builtin) return sentence.goals;
507
+ return [this.relation(sentence.name, sentence.args)];
508
+ }
509
+
510
+ // The best template for a sentence: as in LE, one with a "that" place
511
+ // first, then the one with the most words, a declared template before a
512
+ // built-in one. Its arguments are the places' terms.
513
+ sentenceOf(tokens, scope, { data = false } = {}) {
514
+ const meta = (t) => t.parts.some((p) => p.meta) ? 1 : 0;
515
+ const candidates = [...this.templates, ...(data ? [] : BUILTINS), ...TYPE_TEMPLATES].sort((a, b) => meta(b) - meta(a) || b.words - a.words);
516
+ for (const template of candidates) {
517
+ for (const fills of matches(template.parts, tokens)) {
518
+ const saved = scope.save();
519
+ const args = [];
520
+ const places = template.parts.filter((p) => p.place);
521
+ for (let i = 0; i < fills.length && args.length === i; i++) {
522
+ const place = places[i];
523
+ let value = null;
524
+ if (place.meta) {
525
+ const inner = this.sentenceOf(fills[i], scope, { data: true });
526
+ if (inner) value = inner.builtin ? null : st(inner.name, ...inner.args);
527
+ }
528
+ if (value === null && place.expr) value = this.expression(fills[i], scope);
529
+ else if (value === null) value = this.term(fills[i], scope, { type: place.type });
530
+ if (value !== null) args.push(value);
284
531
  }
285
- let comparison;
286
- if (this.take('greater')) { this.need('than'); comparison = 'gt'; }
287
- else if (this.take('less')) { this.need('than'); comparison = 'lt'; }
288
- else if (this.take('at')) {
289
- if (this.take('least')) comparison = 'ge';
290
- else { this.need('most'); comparison = 'le'; }
291
- } else if (this.take('equal')) { this.need('to'); comparison = 'eq'; }
292
- else if (this.take('different')) { this.need('from'); comparison = 'ne'; }
293
- if (comparison) {
294
- if (!(subject instanceof Var) && !['bigint', 'number'].includes(typeof subject)) this.error('a comparison needs a variable or number on its left');
295
- return st(comparison, subject, this.expression());
532
+ if (args.length === fills.length) {
533
+ // A built-in template with formula places takes { term, goals, formula }.
534
+ const goals = template.builtin ? template.compile(this, args) : null;
535
+ if (goals) return { builtin: true, goals };
536
+ if (!template.builtin) return { name: template.name, args };
296
537
  }
538
+ scope.restore(saved);
297
539
  }
298
- // Adjectival class form, as in "Every human is mortal".
299
- return this.statement(this.name(), subject);
300
- }
301
- if (subject instanceof Struct && subject.name !== '.' && NAME.test(subject.name) && !RESERVED.has(subject.name)) return subject;
302
- if (typeof subject === 'string' && NAME.test(subject) && !RESERVED.has(subject)) return subject;
303
- this.error('expected "is a class", "is a relation of", or a relation call such as parent(Alice, Bob)');
304
- }
305
-
306
- // An aggregate statement stands for several goals, so goals are flattened.
307
- goals(body) {
308
- const goals = [this.atomic(body)];
309
- while (this.take('and')) goals.push(this.atomic(body));
310
- return goals.flat();
311
- }
312
-
313
- // Premises joined by "or", with "and" binding more tightly; each
314
- // alternative becomes a clause of its own.
315
- alternatives() {
316
- const result = [this.goals(true)];
317
- while (this.take('or')) result.push(this.goals(true));
318
- return result;
319
- }
320
-
321
- // "N is the number of X and Y such that ..." counts the distinct
322
- // combinations of the declared variables; sum, maximum and minimum fold the
323
- // value V over them. The condition is one statement or a conjunction in
324
- // parentheses, and its declared variables stay inside it.
325
- aggregate(result, kind) {
326
- this.at++; this.need('of');
327
- let value = null;
328
- if (kind !== 'number') {
329
- if (this.token.kind !== 'word' || !VARIABLE.test(this.token.value)) {
330
- this.error(`"the ${kind} of" needs a variable, as in "the ${kind} of V for every X and V such that ..."`);
540
+ }
541
+ return null;
542
+ }
543
+
544
+ // ------------------------------------------------------------ Conditions
545
+
546
+ // A body of conditions: lines joined by "and" and "or", where a deeper
547
+ // indentation binds tighter, as in LE. Negations, universals and aggregates
548
+ // take the deeper lines that follow them.
549
+ body(tokens, scope) {
550
+ const entries = this.entries(tokens, scope);
551
+ return this.combine(entries);
552
+ }
553
+
554
+ // The conditions of a slice as entries { op, indent, goals }.
555
+ entries(tokens, scope) {
556
+ const entries = [];
557
+ let i = 0;
558
+ let op = null, indent = tokens[0]?.indent ?? 0;
559
+ while (i < tokens.length) {
560
+ // A construct starts here: it runs to the next line that starts with a
561
+ // connective at its own indentation or less.
562
+ const t = tokens[i];
563
+ const lineIndent = t.indent;
564
+ const end = (from) => {
565
+ for (let k = from; k < tokens.length; k++) {
566
+ if (tokens[k].bol && isWord(tokens[k], 'and', 'or') && tokens[k].indent <= lineIndent) return k;
567
+ }
568
+ return tokens.length;
569
+ };
570
+ let construct = null, next = i;
571
+ const negation = startsWith(tokens, ['it', 'is', 'not', 'the', 'case', 'that'], i) ? 6 : startsWith(tokens, ['not', 'the', 'case', 'that'], i) ? 4 : 0;
572
+ if (negation) {
573
+ next = end(i + negation);
574
+ const inner = tokens.slice(i + negation, next);
575
+ if (!inner.length) this.error('"it is not the case that" needs a condition', t.line);
576
+ construct = [st('not', conjunction(this.body(inner, scope)))];
577
+ } else if (startsWith(tokens, ['for', 'all', 'cases', 'in', 'which'], i)) {
578
+ next = end(i + 5);
579
+ const inner = tokens.slice(i + 5, next);
580
+ const split = indexOfWords(inner, ['it', 'is', 'the', 'case', 'that']);
581
+ if (split < 0) this.error('"for all cases in which" needs "it is the case that"', t.line);
582
+ const then = inner.slice(split + 5 + (inner[split + 5]?.text === ':' ? 1 : 0));
583
+ const conditions = this.body(inner.slice(0, split), scope), consequence = this.body(then, scope);
584
+ construct = [st('not', conjunction([...conditions, st('not', conjunction(consequence))]))];
585
+ } else {
586
+ const aggregate = this.aggregate(tokens, i, scope, end);
587
+ if (aggregate) [construct, next] = aggregate;
331
588
  }
332
- value = this.token.value;
333
- this.at++; this.need('for'); this.need('every');
334
- }
335
- const locals = this.declarations();
336
- if (value !== null && !locals.some((v) => v.name === value)) this.error(`${value} must be declared after "for every" in its aggregate`);
337
- this.need('such'); this.need('that');
338
- let condition;
339
- if (this.take('(')) { condition = this.goals(true); this.need(')'); }
340
- else condition = [this.atomic(true)].flat();
341
- if (condition.some((goal) => goal instanceof Struct && goal.name === 'findall_sorted')) {
342
- this.error('an aggregate cannot contain another aggregate; derive the inner one in a rule and use its conclusion');
343
- }
344
- for (const v of locals) this.closed.add(v.name);
345
- const ordered = value === null ? locals : [locals.find((v) => v.name === value), ...locals.filter((v) => v.name !== value)];
346
- const n = ++this.aggregates, all = new Var(`Agg${n}`), distinct = new Var(`Agg${n}d`), helper = AGGREGATES[kind];
347
- this.helpers.add('le:distinct');
348
- this.helpers.add(helper);
349
- return [st('findall_sorted', st('t', ...ordered), conjunction(condition), all),
350
- st('le:distinct', all, distinct), st(helper, distinct, result)];
351
- }
352
-
353
- // Calculations, comparisons and absence tests need their inputs from
354
- // earlier premises; an aggregate needs those of its condition other than
355
- // its own variables, and checks its condition in the same way.
356
- checkOrder(goals, bound, line) {
357
- for (const goal of goals) {
358
- if (goal instanceof Struct && goal.name === 'findall_sorted') {
359
- const locals = variablesIn([goal.args[0]]), inner = new Set(bound);
360
- for (const name of variablesIn([goal.args[1]])) {
361
- if (!locals.has(name) && !bound.has(name)) this.error(`${name} must be supplied by an earlier premise before the aggregate that uses it`, line);
589
+ if (construct) {
590
+ entries.push({ op, indent, goals: construct });
591
+ i = next;
592
+ } else {
593
+ // A segment of plain conditions runs to the next line that starts
594
+ // with a connective, or a construct.
595
+ let k = i + 1;
596
+ while (k < tokens.length && !(tokens[k].bol && isWord(tokens[k], 'and', 'or'))) k++;
597
+ // A construct inside the segment, after a connective, ends it there.
598
+ let cut = k;
599
+ for (let m = i + 1; m < k; m++) {
600
+ if (isWord(tokens[m - 1], 'and', 'or') && (startsWith(tokens, ['it', 'is', 'not', 'the', 'case', 'that'], m) ||
601
+ startsWith(tokens, ['for', 'all', 'cases', 'in', 'which'], m) || aggregateAt(tokens, m) >= 0)) { cut = m - 1; break; }
362
602
  }
363
- this.checkOrder(flattenConjunction(goal.args[1]), inner, line);
364
- bound.add(goal.args[2].name);
365
- continue;
603
+ const pieces = this.split(tokens.slice(i, cut), scope);
604
+ if (!pieces) this.error(`no template matches "${phrase(tokens.slice(i, cut))}"`, t.line);
605
+ pieces[0].op = op; pieces[0].indent = indent;
606
+ entries.push(...pieces);
607
+ i = cut;
366
608
  }
367
- const required = goal instanceof Struct && RESERVED.has(goal.name) ? variablesIn(goal.name === 'is' ? [goal.args[1]] : [goal]) : new Set();
368
- for (const name of required) if (!bound.has(name)) this.error(`${name} must be supplied by an earlier positive premise or calculation`, line);
369
- if (!(goal instanceof Struct && goal.name === 'not')) for (const name of variablesIn([goal])) bound.add(name);
370
- }
371
- return bound;
372
- }
373
-
374
- namespace(label) {
375
- this.need('with'); this.need('namespace');
376
- if (this.token.kind !== 'string') this.error(`${label} namespace must be a quoted absolute IRI`);
377
- const namespace = this.token.value;
378
- try { new URL(namespace); } catch { this.error(`${label} namespace must be an absolute IRI`); }
379
- if (/[\s<>"{}|^`\\]/u.test(namespace)) this.error(`${label} namespace must be an absolute IRI without whitespace or forbidden characters`);
380
- this.at++; this.need('.');
381
- return namespace;
382
- }
383
-
384
- sentence() {
385
- const line = this.token.line;
386
- this.scope = new Map();
387
- this.closed = new Set();
388
- if (this.is('use') && this.tokens[this.at + 1]?.kind === 'word' && this.tokens[this.at + 1].value.toLowerCase() === 'dpv') {
389
- this.at += 2;
390
- this.need('hierarchy'); this.need('logic'); this.need('.');
391
- return { kind: 'dpv', line };
392
- }
393
- if (this.is('use') && this.tokens[this.at + 1]?.kind === 'word' && this.tokens[this.at + 1].value.toLowerCase() === 'prefix') {
394
- this.at += 2;
395
- const prefix = this.token.value;
396
- if (this.token.kind !== 'word' || !PREFIX.test(prefix)) this.error('expected a prefix name such as dpv');
397
- if (this.prefixes.has(prefix)) this.error(`prefix ${prefix} is already declared in this file`);
398
- this.at++;
399
- this.prefixes.set(prefix, this.namespace('a prefix'));
400
- return { kind: 'prefix', line };
401
- }
402
- if (this.is('use') && this.tokens[this.at + 1]?.kind === 'word' && this.tokens[this.at + 1].value.toLowerCase() === 'odrl') {
403
- this.at++;
404
- this.need('odrl');
405
- let evaluate = false;
406
- if (this.take('snapshot')) { this.need('logic'); evaluate = true; }
407
- else this.need('vocabulary');
408
- const namespace = this.namespace('an ODRL');
409
- this.odrl = true;
410
- return { kind: 'odrl', namespace, evaluate, line };
411
- }
412
- if (this.take('every')) {
413
- const x = new Var('X'), froms = [this.name()], heads = [];
414
- while (this.take('or')) froms.push(this.name());
415
- this.need('is');
416
- do { this.take('a') || this.take('an'); heads.push(this.statement(this.name(), x)); } while (this.take('and'));
417
- this.need('.');
418
- return { kind: 'forward', heads, bodies: froms.map((from) => [this.statement(from, x)]), line };
419
- }
420
- let quantified = false;
421
- if (this.take('for')) { this.need('every'); this.declarations(); this.need(','); quantified = true; }
422
- let kind = 'fact', bodies = [[]], heads = [], witnesses = [];
423
- if (this.take('find')) {
424
- if (quantified) this.error('a question introduces its variables with "Find every"');
425
- if (this.take('every')) { this.declarations(); this.need('such'); this.need('that'); }
426
- else this.need('whether');
427
- kind = 'query'; bodies = [this.goals(true)];
428
- if (this.is('or')) this.error('a question has no "or"; ask one question per alternative, or derive a relation with an "or" rule and ask for it');
429
- if (bodies[0].some((goal) => goal instanceof Struct && goal.name === 'findall_sorted')) {
430
- this.error('a question cannot aggregate; derive the aggregate in a rule and ask for its conclusion');
609
+ if (i < tokens.length) {
610
+ if (!isWord(tokens[i], 'and', 'or')) this.error(`expected "and" or "or" before "${phrase(tokens.slice(i, i + 6))}"`, tokens[i].line);
611
+ op = lower(tokens[i]);
612
+ indent = tokens[i].indent;
613
+ i++;
431
614
  }
432
- } else if (this.take('contradiction')) {
433
- kind = 'contradiction'; bodies = [['true']];
434
- } else if (this.take('it')) {
435
- this.need('is'); this.need('impossible'); this.need('that');
436
- kind = 'contradiction'; bodies = this.alternatives();
437
- } else {
438
- if (this.take('if')) { kind = 'forward'; bodies = this.alternatives(); this.need('then'); }
439
- if (this.take('there')) {
440
- this.need('exists'); witnesses = this.declarations(); this.need('such'); this.need('that');
441
- if (kind === 'fact') { kind = 'forward'; bodies = [['true']]; }
615
+ }
616
+ if (!entries.length) this.error('a condition is missing', tokens[0]?.line ?? 0);
617
+ return entries;
618
+ }
619
+
620
+ // An aggregate at i: "R is the sum of each V such that" or LE's
621
+ // "R is a collection of V where", followed by its conditions.
622
+ aggregate(tokens, i, scope, end) {
623
+ const k = aggregateAt(tokens, i);
624
+ if (k >= 0) {
625
+ if (startsWith(tokens, ['is', 'the'], k) && AGGREGATES[lower(tokens[k + 2] ?? {})] !== undefined && startsWith(tokens, ['of', 'each'], k + 3)) {
626
+ const thatAt = indexOfWords(tokens, ['such', 'that'], k + 5);
627
+ if (thatAt < 0) return null;
628
+ const next = end(thatAt + 2);
629
+ return [this.collect(tokens.slice(i, k), tokens.slice(k + 4, thatAt), tokens.slice(thatAt + 2, next), lower(tokens[k + 2]), scope), next];
442
630
  }
443
- heads = this.goals(false);
444
- }
445
- this.need('.');
446
- const headVars = variablesIn(heads), witnessNames = new Set(witnesses.map((v) => v.name));
447
- if (witnesses.some((v) => !headVars.has(v.name))) this.error('every existential variable must occur in its conclusion', line);
448
- for (const body of bodies) {
449
- const bound = this.checkOrder(body, new Set(), line);
450
- if (kind === 'forward' && [...headVars].some((name) => !bound.has(name) && !witnessNames.has(name))) {
451
- this.error(bodies.length > 1 ? 'a conclusion variable must occur in every alternative of an "or" premise, or be introduced with "there exists"'
452
- : 'a conclusion variable must occur in a premise or be introduced with "there exists"', line);
631
+ if (startsWith(tokens, ['is', 'a', 'collection', 'of'], k)) {
632
+ const whereAt = tokens.findIndex((t, m) => m > k + 4 && isWord(t, 'where'));
633
+ if (whereAt < 0) return null;
634
+ const next = end(whereAt + 1);
635
+ return [this.collect(tokens.slice(i, k), tokens.slice(k + 4, whereAt), tokens.slice(whereAt + 1, next), 'list', scope), next];
453
636
  }
454
637
  }
455
- return { kind, heads, bodies, line };
638
+ return null;
639
+ }
640
+
641
+ collect(result, each, conditions, op, scope) {
642
+ const line = (result[0] ?? each[0]).line;
643
+ const total = this.term(result, scope);
644
+ if (total === null) this.error(`the result of an aggregate is a variable such as "a number N", not "${phrase(result)}"`, line);
645
+ const template = this.term(each, scope);
646
+ if (template === null) this.error(`an aggregate collects a variable, not "${phrase(each)}"`, line);
647
+ if (!conditions.length) this.error('an aggregate needs conditions after "such that"', line);
648
+ const goals = this.body(conditions, scope);
649
+ const items = new Var(`L${this.lists = (this.lists ?? 0) + 1}`);
650
+ const found = st('findall', template, conjunction(goals), items);
651
+ return AGGREGATES[op] === null ? [found, st('unify', total, items)] : [found, this.helper(AGGREGATES[op], items, total)];
652
+ }
653
+
654
+ // Splits a segment into conditions at an inline "and" or "or", or a line
655
+ // break, wherever every piece is a condition; fewer tokens first.
656
+ split(tokens, scope) {
657
+ const cuts = [];
658
+ for (let i = 1; i < tokens.length; i++) {
659
+ if (isWord(tokens[i], 'and', 'or') && i + 1 < tokens.length) cuts.push({ at: i, skip: 1, op: lower(tokens[i]), indent: tokens[i].indent });
660
+ else if (tokens[i].bol && !isWord(tokens[i - 1], 'and', 'or')) cuts.push({ at: i, skip: 0, op: 'and', indent: tokens[i].indent });
661
+ }
662
+ const attempt = (from, start) => {
663
+ const options = [...cuts.filter((c) => c.at > start), { at: tokens.length, skip: 0 }];
664
+ for (const cut of options) {
665
+ const saved = scope.save();
666
+ const goals = this.condition(tokens.slice(start, cut.at), scope);
667
+ if (goals) {
668
+ if (cut.at === tokens.length) return [{ goals }];
669
+ const rest = attempt(cut, cut.at + cut.skip);
670
+ if (rest) { rest[0].op = cut.op; rest[0].indent = cut.indent; return [{ goals }, ...rest]; }
671
+ }
672
+ scope.restore(saved);
673
+ }
674
+ return null;
675
+ };
676
+ return attempt(null, 0);
677
+ }
678
+
679
+ // Entries joined by their connectives: the shallowest connectives last,
680
+ // and connectives at one indentation from the top down.
681
+ combine(entries) {
682
+ if (entries.length === 1) return entries[0].goals;
683
+ const least = Math.min(...entries.slice(1).map((e) => e.indent));
684
+ const groups = [[entries[0]]];
685
+ for (const entry of entries.slice(1)) {
686
+ if (entry.indent === least) groups.push([entry]);
687
+ else groups.at(-1).push(entry);
688
+ }
689
+ let goals = this.combine([{ ...groups[0][0], op: null }, ...groups[0].slice(1)]);
690
+ for (const group of groups.slice(1)) {
691
+ const right = this.combine([{ ...group[0], op: null }, ...group.slice(1)]);
692
+ goals = group[0].op === 'or' ? [st('or', conjunction(goals), conjunction(right))] : [...goals, ...right];
693
+ }
694
+ return goals;
456
695
  }
457
696
  }
458
697
 
459
- function rdfResource(term) {
460
- return term instanceof Var || term instanceof Struct &&
461
- (term.name === 'iri' && term.args.length === 1 && typeof term.args[0] === 'string' ||
462
- term.name === 'bnode' && term.args.length === 2 || term.name === 'skolem' && term.args.length === 3);
698
+ // Variables that occur only inside negations stand for any value there: they
699
+ // are renamed _0, _1, ..., which LS negation treats as anonymous.
700
+ function anonymize(head, goals) {
701
+ const outside = new Set(), inside = new Set();
702
+ const visit = (term, negated) => {
703
+ if (term instanceof Var) (negated ? inside : outside).add(term);
704
+ else if (term instanceof Struct) {
705
+ const deeper = negated || (term.name === 'not' && term.args.length === 1);
706
+ for (const arg of term.args) visit(arg, deeper);
707
+ }
708
+ };
709
+ visit(head, false);
710
+ for (const goal of goals) visit(goal, false);
711
+ let n = 0;
712
+ for (const variable of inside) if (!outside.has(variable)) variable.name = `_${n++}`;
713
+ return n;
463
714
  }
464
715
 
465
- function rdfValue(term) {
466
- return rdfResource(term) || typeof term === 'bigint' || typeof term === 'number' ||
467
- term instanceof Struct && (term.name === 'literal' && term.args.length === 2 || term.name === 'triple' && term.args.length === 3);
716
+ const varsOf = (term, out = new Set()) => {
717
+ if (term instanceof Var) out.add(term);
718
+ else if (term instanceof Struct) for (const arg of term.args) varsOf(arg, out);
719
+ return out;
720
+ };
721
+
722
+ function substitute(term, map) {
723
+ if (term instanceof Var) return map.get(term) ?? term;
724
+ if (term instanceof Struct) return new Struct(term.name, term.args.map((arg) => substitute(arg, map)));
725
+ return term;
468
726
  }
469
727
 
470
- function variablesIn(terms) {
471
- const result = new Set(), pending = [...terms];
472
- while (pending.length) {
473
- const term = pending.pop();
474
- if (term instanceof Var) result.add(term.name);
475
- else if (term instanceof Struct) pending.push(...term.args);
728
+ // Prolog's negation, which LE's rules are written for, succeeds when no
729
+ // instance of its goal holds if a variable of the goal is still unbound. LS
730
+ // requires the variables of a negation to be bound, so a negation whose
731
+ // variable no earlier condition binds tests at run time: while the variable
732
+ // is unbound, the negation stands for any value there.
733
+ function guardNegations(goals, bound, counter, open = false) {
734
+ const out = [];
735
+ for (const goal of goals) {
736
+ if (goal instanceof Struct && goal.name === 'not' && goal.args.length === 1) {
737
+ const inner = guardInner(goal.args[0], bound, counter, open);
738
+ const unbound = [...varsOf(inner)].filter((v) => !/^_\d+$/.test(v.name) && !bound.has(v));
739
+ if (!unbound.length || unbound.length > 3) out.push(st('not', inner));
740
+ else {
741
+ const cases = [];
742
+ for (let mask = 0; mask < 1 << unbound.length; mask++) {
743
+ const map = new Map(), tests = [];
744
+ unbound.forEach((v, i) => {
745
+ if (mask & (1 << i)) { tests.push(st('is_var', v)); map.set(v, new Var(`_${counter.n++}`)); }
746
+ else tests.push(st('is_nonvar', v));
747
+ });
748
+ cases.push(conjunction([...tests, st('not', substitute(inner, map))]));
749
+ }
750
+ out.push(cases.reduce((a, b) => st('or', a, b)));
751
+ }
752
+ continue;
753
+ }
754
+ if (goal instanceof Struct && goal.name === 'or' && goal.args.length === 2) {
755
+ const branches = goal.args.map((branch) => conjunction(guardNegations(flatten(branch), new Set(bound), counter, open)));
756
+ out.push(st('or', ...branches));
757
+ if (!open) varsOf(goal, bound);
758
+ continue;
759
+ }
760
+ out.push(goal);
761
+ if (open) continue;
762
+ if (goal instanceof Struct && goal.name === 'findall' && goal.args.length === 3) varsOf(goal.args[2], bound);
763
+ else varsOf(goal, bound);
476
764
  }
477
- return result;
765
+ return out;
478
766
  }
479
767
 
480
- // Explicit constructors keep quoted names, floats and reserved JS names safe.
481
- function javascript(term) {
482
- if (term instanceof Var) return `vars(${JSON.stringify(term.name)})`;
483
- if (term instanceof Struct) return `struct(${JSON.stringify(term.name)}, ${term.args.map(javascript).join(', ')})`;
484
- if (typeof term === 'bigint') return `${term}n`;
485
- if (typeof term === 'number') return `float(${write(term)})`;
486
- return JSON.stringify(term);
768
+ function guardInner(goal, bound, counter, open) {
769
+ return conjunction(guardNegations(flatten(goal), new Set(bound), counter, open));
487
770
  }
488
771
 
489
- export function compileLe(inputs) {
490
- const clauses = [], statements = [], sources = [], helpers = new Set(), prefixes = new Map();
491
- let profile = null, dpv = false;
492
- for (const [text, file] of inputs) {
493
- const parser = new Parser(String(text), file);
494
- while (parser.token.kind !== 'end') {
495
- const sentence = parser.sentence(), { kind, heads, bodies, line } = sentence;
496
- if (kind === 'prefix') continue;
497
- if (kind === 'dpv') {
498
- if (profile) parser.error('the DPV hierarchy directive belongs to ordinary LE; an ODRL snapshot uses its withinCategory operator', line);
499
- dpv = true;
500
- continue;
772
+ function flatten(goal) {
773
+ if (goal instanceof Struct && goal.name === 'and' && goal.args.length === 2) return [...flatten(goal.args[0]), ...flatten(goal.args[1])];
774
+ return [goal];
775
+ }
776
+
777
+ // Variables outside negations and collections, in order: a query's answer.
778
+ function openVariables(goals) {
779
+ const out = [];
780
+ const visit = (term) => {
781
+ if (term instanceof Var) { if (!out.includes(term)) out.push(term); }
782
+ else if (term instanceof Struct && !(term.name === 'not' && term.args.length === 1) && !(term.name === 'findall' && term.args.length === 3)) {
783
+ for (const arg of term.args) visit(arg);
784
+ } else if (term instanceof Struct && term.name === 'findall') visit(term.args[2]);
785
+ };
786
+ for (const goal of goals) visit(goal);
787
+ return out;
788
+ }
789
+
790
+ // ---------------------------------------------------------------- Documents
791
+
792
+ // The sections of one document as sentences: [kind, name, tokens, line].
793
+ function sections(tokens, file) {
794
+ const error = (message, line) => { throw new EyemindError(`${file}: line ${line}: Logical English: ${message}`); };
795
+ const out = [];
796
+ let i = 0, section = null;
797
+ const colon = (from) => {
798
+ for (let k = from; k < tokens.length && tokens[k].kind !== 'stop' && tokens[k].kind !== 'end'; k++) if (tokens[k].text === ':') return k;
799
+ return -1;
800
+ };
801
+ while (tokens[i].kind !== 'end') {
802
+ const line = tokens[i].line;
803
+ if (startsWith(tokens, ['the', 'target', 'language', 'is'], i)) {
804
+ while (tokens[i].kind !== 'stop' && tokens[i].kind !== 'end') i++;
805
+ i++;
806
+ continue;
807
+ }
808
+ if (startsWith(tokens, ['the', 'templates', 'are'], i) || startsWith(tokens, ['the', 'predicates', 'are'], i)) {
809
+ if (tokens[i + 3]?.text !== ':') error('expected ":" after "the templates are"', line);
810
+ section = { kind: 'templates' };
811
+ i += 4;
812
+ continue;
813
+ }
814
+ // An ontology states what kinds of thing are kinds of other things.
815
+ if (startsWith(tokens, ['the', 'ontology', 'is', ':'], i)) {
816
+ section = { kind: 'ontology' };
817
+ i += 4;
818
+ continue;
819
+ }
820
+ // LE2 also opens a knowledge base with "the contract NAME states that:".
821
+ if (startsWith(tokens, ['the', 'contract'], i) && colon(i) > 0 && startsWith(tokens, ['states', 'that'], colon(i) - 2)) {
822
+ section = { kind: 'kb', name: tokens.slice(i + 2, colon(i) - 2).map((t) => t.text).join(' ') };
823
+ i = colon(i) + 1;
824
+ continue;
825
+ }
826
+ if (startsWith(tokens, ['the', 'knowledge', 'base'], i)) {
827
+ const at = colon(i);
828
+ const includes = at > 0 && isWord(tokens[at - 1], 'includes');
829
+ if (!includes) {
830
+ if (at > 0 && startsWith(tokens, ['includes', 'these'], at - 3)) error('included resources and scenarios belong to Logical English 2 and are not supported', line);
831
+ error('expected "the knowledge base NAME includes:"', line);
501
832
  }
502
- if (kind === 'odrl') {
503
- if (profile || dpv || statements.length || parser.prefixes.size || inputs.length !== 1) parser.error('an ODRL directive must be the first sentence of one LE file', line);
504
- profile = { namespace: sentence.namespace, evaluate: sentence.evaluate };
833
+ section = { kind: 'kb', name: tokens.slice(i + 3, at - 1).map((t) => t.text).join(' ') };
834
+ i = at + 1;
835
+ continue;
836
+ }
837
+ if (isWord(tokens[i], 'scenario', 'query') && tokens[i].bol) {
838
+ const at = colon(i);
839
+ if (at > i + 2 && isWord(tokens[at - 1], 'is')) {
840
+ const name = tokens.slice(i + 1, at - 1).map((t) => t.text).join(' ');
841
+ section = { kind: lower(tokens[i]), name, line };
842
+ if (section.kind === 'scenario') out.push(['scenario', name, [], line]);
843
+ i = at + 1;
505
844
  continue;
506
845
  }
507
- clauses.push(`// ${String(file).replace(/[\r\n\u2028\u2029]/g, ' ')}: line ${line}`);
508
- for (const body of bodies) {
509
- statements.push({ kind, heads, body, line, file });
510
- if (kind === 'fact') {
511
- for (const head of heads) {
512
- clauses.push(`fact(${javascript(head)})`);
513
- sources.push(new Source('fact', head, [], line, file));
514
- }
515
- } else if (kind === 'forward') {
516
- clauses.push(`implies(${javascript(conjunction(body))}, ${javascript(conjunction(heads))})`);
517
- sources.push(new Source('forward', conjunction(heads), body, line, file));
518
- } else {
519
- clauses.push(`${kind}(${body.map(javascript).join(', ')})`);
520
- sources.push(new Source(kind, kind === 'query' ? 'true' : 'false', body, line, file));
846
+ if (at > 0) error(`the header "${phrase(tokens.slice(i, at + 1))}" belongs to Logical English 2 and is not supported`, line);
847
+ }
848
+ // LE2 labels a rule with "rule NAME:".
849
+ if (isWord(tokens[i], 'rule') && colon(i) > i + 1 && colon(i) < i + 5 && tokens.slice(i + 1, colon(i)).every((t) => t.kind === 'word')) {
850
+ error('rule labels belong to Logical English 2 and are not supported', line);
851
+ }
852
+ const unsupported = SECTIONS.find((words) => startsWith(tokens, words.split(' '), i));
853
+ if (unsupported || (startsWith(tokens, ['section'], i) && tokens[i].bol && colon(i) > 0)) {
854
+ error(`the section "${unsupported ?? 'section'}" belongs to Logical English 2 and is not supported`, line);
855
+ }
856
+ let end = i;
857
+ while (tokens[end].kind !== 'stop' && tokens[end].kind !== 'end') end++;
858
+ if (tokens[end].kind === 'end') error(`a sentence must end with a full stop: "${phrase(tokens.slice(i, Math.min(end, i + 12)))}"`, line);
859
+ const sentence = tokens.slice(i, end);
860
+ if (!section) error('a sentence comes before any section; start with "the templates are:"', line);
861
+ if (section.kind === 'templates') {
862
+ // Templates are separated by full stops, and by commas that end a
863
+ // line or come before a place: a template's own words may hold commas.
864
+ // A part without words of its own belongs to the template before it.
865
+ const level = depths(sentence), parts = [];
866
+ let start = 0;
867
+ for (let k = 0; k <= sentence.length; k++) {
868
+ const separates = sentence[k]?.text === ',' && level[k] === 0 && (k + 1 === sentence.length || sentence[k + 1].bol || sentence[k + 1].text === '*');
869
+ if (k < sentence.length && !separates) continue;
870
+ if (k > start) {
871
+ const part = sentence.slice(start, k);
872
+ let inside = false;
873
+ const words = part.some((t) => { if (t.text === '*') inside = !inside; return !inside && t.kind === 'word'; });
874
+ if (!words && parts.length && sentence[start - 1]?.text === ',') parts.at(-1).push(sentence[start - 1], ...part);
875
+ else parts.push(part);
521
876
  }
877
+ start = k + 1;
522
878
  }
879
+ for (const part of parts) out.push(['template', null, part, part[0].line]);
880
+ } else if (section.kind === 'query') {
881
+ out.push(['query', section.name, sentence, line]);
882
+ section = { kind: 'after query' };
883
+ } else if (section.kind === 'after query') {
884
+ error('a query has one sentence; start a new section after it', line);
885
+ } else {
886
+ out.push([{ kb: 'clause', ontology: 'ontology clause' }[section.kind] ?? 'scenario clause', section.name ?? null, sentence, line]);
523
887
  }
524
- for (const name of parser.helpers) helpers.add(name);
525
- for (const [prefix, namespace] of parser.prefixes) prefixes.set(prefix, namespace);
526
- }
527
- if (profile) {
528
- // A snapshot's rules derive input triples for its evaluation, with the
529
- // aggregation helpers they use; its facts remain RDF data.
530
- const map = (goal) => snapshotGoal(goal, profile.namespace);
531
- const rules = [];
532
- for (const { kind, heads, body, line, file } of statements.filter((s) => s.kind === 'forward' || s.kind === 'contradiction')) {
533
- rules.push(`// ${String(file).replace(/[\r\n\u2028\u2029]/g, ' ')}: line ${line}`);
534
- rules.push(kind === 'forward' ? `implies(${javascript(conjunction(body.map(map)))}, ${javascript(conjunction(heads.map(map)))})`
535
- : `contradiction(${body.map(map).map(javascript).join(', ')})`);
536
- }
537
- for (const name of Object.keys(HELPERS).filter((key) => helpers.has(key))) {
538
- for (const make of HELPERS[name]) {
539
- const [head, body] = make();
540
- rules.push(`implied_by(${javascript(head)}, ${body.length ? javascript(conjunction(body)) : "'true'"})`);
541
- }
888
+ i = end + 1;
889
+ }
890
+ return out;
891
+ }
892
+
893
+ export function compileLe(inputs) {
894
+ const items = [];
895
+ for (const [text, file] of inputs) {
896
+ for (const item of sections(tokenize(String(text), file), file)) items.push([...item, file]);
897
+ }
898
+ // Templates first: a sentence can use a template declared after it.
899
+ const templates = [], byName = new Map();
900
+ const starred = items.some((item) => item[0] === 'template' && item[2].some((t) => t.text === '*'));
901
+ for (const [kind, , tokens, line, file] of items.filter((item) => item[0] === 'template')) {
902
+ const error = (message, at = line) => { throw new EyemindError(`${file}: line ${at}: Logical English: ${message}`); };
903
+ const parts = readTemplate(tokens, error, starred);
904
+ const name = templateName(parts), arity = parts.filter((p) => p.place).length, key = `${name}/${arity}`;
905
+ if (byName.has(key)) {
906
+ const other = byName.get(key);
907
+ if (other.parts.map((p) => p.word ?? '*').join(' ') === parts.map((p) => p.word ?? '*').join(' ')) continue;
908
+ error(`the templates "${other.text}" and "${phrase(tokens)}" both name the relation ${name}/${arity}; change a word of one`);
542
909
  }
543
- const loaded = compileOdrlLe(statements.filter((s) => s.kind !== 'forward' && s.kind !== 'contradiction'), profile, inputs[0][1],
544
- rules.length ? rules.join('\n') + '\n' : '');
545
- return { ...loaded, prefixes: { ...loaded.prefixes, ...Object.fromEntries(prefixes) } };
910
+ const template = { parts, name, arity, words: parts.filter((p) => p.word).length, text: phrase(tokens) };
911
+ byName.set(key, template);
912
+ templates.push(template);
913
+ }
914
+ const scenarios = [];
915
+ for (const [kind, name, , line, file] of items) {
916
+ if (kind !== 'scenario') continue;
917
+ if (scenarios.includes(name)) throw new EyemindError(`${file}: line ${line}: Logical English: scenario ${name} is stated twice`);
918
+ scenarios.push(name);
546
919
  }
547
- // The helpers follow every stated clause, so a witness's rule number is
548
- // the same whether or not the program aggregates.
549
- if (helpers.size) clauses.push('// Aggregation helpers.');
550
- for (const name of Object.keys(HELPERS).filter((key) => helpers.has(key))) {
551
- for (const make of HELPERS[name]) {
552
- const [head, body] = make();
920
+ const threaded = scenarios.length > 0;
921
+ const clauses = [], sources = [], queries = [], expectations = [], helpers = new Set(), pending = [];
922
+ // Clauses wait until every one is read: their negations depend on whether
923
+ // any fact or rule leaves a variable of its conclusion open.
924
+ const emit = (kind, head, body, line, file, guard = null) => pending.push({ kind, head, body, line, file, guard });
925
+ const write = ({ kind, head, body, line, file }) => {
926
+ clauses.push(`// ${String(file).replace(/[\r\n\u2028\u2029]/g, ' ')}: line ${line}`);
927
+ if (kind === 'fact') {
928
+ clauses.push(`fact(${javascript(head)})`);
929
+ sources.push(new Source('fact', head, [], line, file));
930
+ } else if (kind === 'query') {
931
+ clauses.push(`query(${javascript(head)})`);
932
+ sources.push(new Source('query', 'true', [head], line, file));
933
+ } else if (kind === 'forward') {
934
+ clauses.push(`implies(${javascript(conjunction(body))}, ${javascript(head)})`);
935
+ sources.push(new Source('forward', head, body, line, file));
936
+ } else {
553
937
  clauses.push(`implied_by(${javascript(head)}, ${body.length ? javascript(conjunction(body)) : "'true'"})`);
554
- sources.push(new Source('backward', head, body.length ? body : ['true'], null, null));
938
+ sources.push(new Source('backward', head, body.length ? body : ['true'], line, file));
555
939
  }
940
+ };
941
+ for (const name of scenarios) {
942
+ const [, , , line, file] = items.find((item) => item[0] === 'scenario' && item[1] === name);
943
+ emit('fact', st(SCENARIO, name), [], line, file);
944
+ }
945
+ // An ontology's kinds are transitive: what is a b is a c when the ontology
946
+ // says that b is a c. One rule per such fact keeps the dependencies of
947
+ // rules that negate other kinds apart.
948
+ const kinds = [];
949
+ for (const [kind, name, tokens, line, file] of items) {
950
+ if (kind === 'template' || kind === 'scenario') continue;
951
+ const compiler = new Compiler(file, templates);
952
+ const scope = new Scope();
953
+ if (kind === 'query') {
954
+ compiler.scenario = threaded ? new Var('Scenario') : null;
955
+ let body = tokens;
956
+ // LE's "for which event:" names the thing a query asks for.
957
+ if (startsWith(body, ['for', 'which'])) {
958
+ const at = body.findIndex((t) => t.text === ':');
959
+ if (at < 0) compiler.error('expected ":" after "for which ..."', line);
960
+ compiler.term([{ text: 'which', kind: 'word' }, ...body.slice(2, at)], scope);
961
+ body = body.slice(at + 1);
962
+ }
963
+ compiler.sentence = body;
964
+ const goals = compiler.body(body, scope);
965
+ const counter = { n: anonymize(st('true'), goals) };
966
+ const answer = openVariables(goals).filter((v) => !/^_\d+$/.test(v.name) && v !== compiler.scenario);
967
+ const head = st(ANSWER, name, ...(threaded ? [compiler.scenario] : []), ...answer);
968
+ emit('backward', head, threaded ? [st(SCENARIO, compiler.scenario), ...goals] : goals, line, file, { counter, scenario: compiler.scenario });
969
+ emit('query', head, [], line, file);
970
+ queries.push({ name, tokens: body.map((t) => t.text), marks: scope.marks.map(({ at, length, variable }) => ({ at, length, slot: answer.indexOf(variable) })) });
971
+ for (const h of compiler.helpers) helpers.add(h);
972
+ continue;
973
+ }
974
+ const inScenario = kind === 'scenario clause';
975
+ // An expected answer: "one expects answers [...] and unknowns [...]."
976
+ const expects = tokens.findIndex((t, k) => isWord(t, 'expects') && (tokens[k + 1]?.text === '[' || (isWord(tokens[k + 1] ?? {}, 'answers') && tokens[k + 2]?.text === '[')));
977
+ if (tokens.some((t, k) => isWord(t, 'expects') && isWord(tokens[k + 1] ?? {}, 'changes'))) {
978
+ compiler.error('flip queries ("expects changes") belong to Logical English 2 and are not supported', line);
979
+ }
980
+ if (expects > 0) {
981
+ if (!inScenario) compiler.error('an expectation belongs to a scenario', line);
982
+ const list = (at) => {
983
+ const close = tokens.findIndex((t, k) => k > at && t.text === ']');
984
+ if (tokens[at]?.text !== '[' || close < 0) compiler.error('expected answers are a list of sentences, as in one expects answers ["..."]', line);
985
+ // Each item is a quoted sentence, or its words up to a comma.
986
+ const items = [];
987
+ let words = [];
988
+ for (const t of [...tokens.slice(at + 1, close), { text: ',' }]) {
989
+ if (t.text !== ',') { words.push(t); continue; }
990
+ if (words.length === 1 && words[0].kind === 'string') items.push(words[0].value);
991
+ else if (words.length) items.push(phrase(words));
992
+ words = [];
993
+ }
994
+ return [items, close];
995
+ };
996
+ const [answers, close] = list(expects + 1 + (isWord(tokens[expects + 1] ?? {}, 'answers') ? 1 : 0));
997
+ // Expected unknowns are assumptions eyemind does not make.
998
+ const unknowns = startsWith(tokens, ['and', 'unknowns'], close + 1) ? list(close + 3)[0] : [];
999
+ expectations.push({ scenario: name, query: tokens.slice(0, expects).map((t) => t.text).join(' '), answers, unknowns, line });
1000
+ continue;
1001
+ }
1002
+ if (startsWith(tokens, ['it', 'is', 'unknown', 'whether']) || startsWith(tokens, ['it', 'must', 'not', 'be', 'true', 'that']) ||
1003
+ (startsWith(tokens, ['it', 'is', 'not', 'the', 'case', 'that']) && inScenario)) {
1004
+ compiler.error('unknowns, constraints and negated facts belong to Logical English 2 and are not supported', line);
1005
+ }
1006
+ compiler.scenario = !threaded ? null : inScenario ? name : new Var('Scenario');
1007
+ const level = depths(tokens);
1008
+ const ifAt = tokens.findIndex((t, k) => level[k] === 0 && isWord(t, 'if'));
1009
+ let headTokens = ifAt < 0 ? tokens : tokens.slice(0, ifAt);
1010
+ // In an ontology, "a student is a person" is about the kinds themselves.
1011
+ if (kind === 'ontology clause' && ifAt < 0 && isWord(headTokens[0], 'a', 'an') && !isWord(headTokens[1] ?? {}, 'is')) headTokens = headTokens.slice(1);
1012
+ if (!headTokens.length) compiler.error('a rule needs a conclusion before "if"', line);
1013
+ // In a fact, an id that no phrase introduces is a name, as in Q1.
1014
+ compiler.fact = ifAt < 0;
1015
+ const head = compiler.sentenceOf(headTokens, scope, { data: true });
1016
+ if (!head) {
1017
+ const builtin = compiler.sentenceOf(headTokens, new Scope());
1018
+ if (builtin?.builtin) compiler.error(`"${phrase(headTokens)}" is a built-in condition and cannot be concluded`, line);
1019
+ compiler.error(`no template matches "${phrase(headTokens)}"`, line);
1020
+ }
1021
+ const headTerm = compiler.relation(head.name, head.args);
1022
+ if (kind === 'ontology clause' && ifAt < 0 && head.name === 'is_a' && head.args.every(isGround)) kinds.push({ term: headTerm, line, file });
1023
+ if (ifAt < 0) {
1024
+ const body = compiler.scenario instanceof Var ? [st(SCENARIO, compiler.scenario)] : [];
1025
+ if (!body.length && isGround(headTerm)) emit('fact', headTerm, [], line, file);
1026
+ else emit('backward', headTerm, body, line, file);
1027
+ continue;
1028
+ }
1029
+ if (ifAt === tokens.length - 1) compiler.error('a rule needs conditions after "if"', line);
1030
+ // LE1 also writes "if" followed by a line that starts with "and".
1031
+ const goals = compiler.body(tokens.slice(ifAt + (isWord(tokens[ifAt + 1], 'and') ? 2 : 1)), scope);
1032
+ const counter = { n: anonymize(headTerm, goals) };
1033
+ emit('backward', headTerm, goals, line, file, { counter, scenario: compiler.scenario, rule: true });
1034
+ for (const h of compiler.helpers) helpers.add(h);
1035
+ }
1036
+ // A fact or rule may leave a variable of its conclusion open. Then no
1037
+ // earlier condition surely binds a variable, and every negation tests its
1038
+ // variables at run time.
1039
+ const open = pending.some(({ kind, head, body, guard }) => kind !== 'query' && (guard ? guard.rule : true) &&
1040
+ [...varsOf(head)].some((v) => !/^_\d+$/.test(v.name) && v.name !== 'Scenario' && !openVariables(body).includes(v)));
1041
+ for (const { term, line, file } of kinds) {
1042
+ const S = new Var('Scenario'), X = new Var('X'), [sub, kind] = term.args.slice(-2);
1043
+ const isA = (a, b) => threaded ? st('is_a', S, a, b) : st('is_a', a, b);
1044
+ emit('backward', isA(X, kind), [isA(X, sub)], line, file, { counter: { n: 0 }, scenario: threaded ? S : null, rule: true });
1045
+ }
1046
+ forwardRecursion(pending, templates, threaded);
1047
+ for (const clause of pending) {
1048
+ if (clause.guard) {
1049
+ const { counter, scenario } = clause.guard;
1050
+ clause.body = guardNegations(clause.body, new Set(scenario instanceof Var ? [scenario] : []), counter, open);
1051
+ }
1052
+ write(clause);
556
1053
  }
557
- if (dpv) {
558
- const rules = dpvRules('rdf', true);
559
- sources.push(...loadText(rules, 'DPV hierarchy rules').sources);
560
- clauses.push(rules);
1054
+ // The helpers follow every stated clause.
1055
+ const used = Object.keys(HELPERS).filter((name) => helpers.has(name));
1056
+ if (used.length) {
1057
+ const text = used.map((name) => HELPERS[name]).join('\n');
1058
+ clauses.push('// Logical English helpers.', text);
1059
+ sources.push(...loadText(text, 'Logical English helpers').sources.map((s) => Object.assign(s, { line: null, file: null })));
561
1060
  }
562
1061
  return { kind: 'le', text: '// Compiled from Logical English to Logic Script.\n\n' + clauses.join('\n') + '\n',
563
- program: new Program(sources), prefixes: Object.fromEntries(prefixes), compiled: { statements } };
1062
+ program: new Program(sources), compiled: { templates, scenarios, threaded, queries, expectations } };
564
1063
  }
565
1064
 
566
- function leTerm(term, names, compact) {
567
- if (term instanceof Var) return names.get(term.name);
568
- if (term === EMPTY) return '[]';
569
- if (typeof term === 'string') {
570
- return /^[A-Za-z][A-Za-z0-9_]*$/.test(term) && !VARIABLE.test(term) && !SENTENCE_WORDS.has(term.toLowerCase()) ? term : JSON.stringify(term);
1065
+ // LE runs recursive rules with tabling (LE1) or a loop check (LE2), so a rule
1066
+ // that depends on itself, directly or through others, ends where Prolog's
1067
+ // search would not. LS forward rules reach the least fixpoint that tabling
1068
+ // computes. A recursive group of rules therefore becomes forward rules when
1069
+ // each of its rules binds every variable of its conclusion through the
1070
+ // relations of its conditions; a rule whose conclusion depends on how it is
1071
+ // called, such as a counter that goes down, stays backward.
1072
+ function forwardRecursion(pending, templates, threaded) {
1073
+ const keys = new Set([...templates.map((t) => `${t.name}/${t.arity + (threaded ? 1 : 0)}`), `is_a/${threaded ? 3 : 2}`]);
1074
+ const keyOf = (term) => term instanceof Struct ? `${term.name}/${term.args.length}` : null;
1075
+ const calls = (term, out = new Set()) => {
1076
+ if (term instanceof Struct) {
1077
+ if (keys.has(keyOf(term))) out.add(keyOf(term));
1078
+ else for (const arg of term.args) calls(arg, out);
1079
+ }
1080
+ return out;
1081
+ };
1082
+ const rules = pending.filter((clause) => clause.kind === 'backward' && clause.guard?.rule);
1083
+ const edges = new Map();
1084
+ for (const rule of rules) {
1085
+ const from = keyOf(rule.head);
1086
+ if (!edges.has(from)) edges.set(from, new Set());
1087
+ for (const goal of rule.body) for (const to of calls(goal)) edges.get(from).add(to);
1088
+ }
1089
+ // Tarjan's strongly connected components of the relations.
1090
+ const index = new Map(), low = new Map(), stack = [], onStack = new Set(), component = new Map();
1091
+ let counter = 0;
1092
+ const visit = (v) => {
1093
+ index.set(v, counter); low.set(v, counter++); stack.push(v); onStack.add(v);
1094
+ for (const w of edges.get(v) ?? []) {
1095
+ if (!index.has(w)) { visit(w); low.set(v, Math.min(low.get(v), low.get(w))); }
1096
+ else if (onStack.has(w)) low.set(v, Math.min(low.get(v), index.get(w)));
1097
+ }
1098
+ if (low.get(v) === index.get(v)) {
1099
+ const members = [];
1100
+ let w;
1101
+ do { w = stack.pop(); onStack.delete(w); members.push(w); } while (w !== v);
1102
+ for (const m of members) component.set(m, members);
1103
+ }
1104
+ };
1105
+ for (const v of edges.keys()) if (!index.has(v)) visit(v);
1106
+ const recursive = (key) => component.get(key)?.length > 1 || edges.get(key)?.has(key);
1107
+ const bound = (rule) => {
1108
+ const relations = new Set();
1109
+ for (const goal of rule.body) if (keys.has(keyOf(goal)) || keyOf(goal) === `${SCENARIO}/1`) varsOf(goal, relations);
1110
+ return [...varsOf(rule.head)].every((v) => /^_\d+$/.test(v.name) || relations.has(v));
1111
+ };
1112
+ for (const members of new Set(component.values())) {
1113
+ if (!recursive(members[0])) continue;
1114
+ const group = rules.filter((rule) => members.includes(keyOf(rule.head)));
1115
+ if (group.every(bound)) for (const rule of group) rule.kind = 'forward';
571
1116
  }
572
- if (typeof term === 'bigint' || typeof term === 'number') return write(term);
573
- if (!(term instanceof Struct)) throw new EyemindError('cannot write this term as Logical English');
574
- const qualified = compact(term);
575
- if (qualified) return qualified;
576
- const render = (arg) => leTerm(arg, names, compact);
577
- if (term.name === 'skolem' && term.args.length === 3) {
578
- const [rule, label, bindings] = term.args, args = listItems(bindings);
579
- if (typeof rule === 'bigint' && rule > 0n && typeof label === 'string' && args !== null) {
580
- const name = VARIABLE.test(label) ? label : JSON.stringify(label);
581
- return `witness(rule ${rule}, ${name}${args.map((arg) => ', ' + render(arg)).join('')})`;
582
- }
583
- }
584
- if (term.name === '.') {
585
- const items = listItems(term);
586
- if (items !== null) return `[${items.map(render).join(', ')}]`;
587
- // Improper lists remain explicit compounds.
588
- }
589
- return `${JSON.stringify(term.name)}(${term.args.map(render).join(', ')})`;
590
1117
  }
591
1118
 
592
- function leGoal(term, render, properties, compact) {
593
- if (term === 'false') return 'Contradiction';
594
- if (typeof term === 'string' && NAME.test(term) && !RESERVED.has(term)) return render(term);
595
- if (!(term instanceof Struct) || !NAME.test(term.name) || RESERVED.has(term.name)) {
596
- throw new EyemindError(`${write(term)} is not a Logical English relation; use --to eyemind`);
597
- }
598
- if (term.name === 'rdf' && term.args.length === 3) {
599
- const [s, p, o] = term.args;
600
- if (rdfResource(s) && rdfValue(o)) {
601
- if (p instanceof Struct && p.name === 'iri' && p.args.length === 1 && p.args[0] === RDF_TYPE) {
602
- const type = compact(o);
603
- if (type) return `${render(s)} is a ${type}`;
604
- }
605
- const property = compact(p);
606
- if (property) return `${render(s)} has ${property} ${render(o)}`;
1119
+ function isGround(term) {
1120
+ if (term instanceof Var) return false;
1121
+ if (term instanceof Struct) return term.args.every(isGround);
1122
+ return true;
1123
+ }
1124
+
1125
+ // Explicit constructors keep quoted names, floats and reserved JS names safe.
1126
+ function javascript(term) {
1127
+ if (term instanceof Var) return `vars(${JSON.stringify(term.name)})`;
1128
+ if (term instanceof Struct) return `struct(${JSON.stringify(term.name)}, ${term.args.map(javascript).join(', ')})`;
1129
+ if (typeof term === 'bigint') return `${term}n`;
1130
+ if (typeof term === 'number') return `float(${write(term)})`;
1131
+ return JSON.stringify(term);
1132
+ }
1133
+
1134
+ // ---------------------------------------------------------------- Answers
1135
+
1136
+ // A value as LE writes it: names as they are, dates as YYYY-MM-DD, lists in
1137
+ // brackets and a sentence through its template.
1138
+ function leValue(term, templates) {
1139
+ if (typeof term === 'string') return term === EMPTY ? '[]' : term;
1140
+ if (typeof term === 'bigint' || typeof term === 'number') return write(term);
1141
+ if (term instanceof Struct) {
1142
+ if (term.name === 'date' && term.args.length === 3 && term.args.every((a) => typeof a === 'bigint')) {
1143
+ const [y, m, d] = term.args.map(String);
1144
+ return `${y.padStart(4, '0')}-${m.padStart(2, '0')}-${d.padStart(2, '0')}`;
1145
+ }
1146
+ if (term.name === '.' && term.args.length === 2) {
1147
+ const items = [];
1148
+ let rest = term;
1149
+ while (rest instanceof Struct && rest.name === '.' && rest.args.length === 2) { items.push(rest.args[0]); rest = rest.args[1]; }
1150
+ if (rest === EMPTY) return `[${items.map((item) => leValue(item, templates)).join(', ')}]`;
1151
+ }
1152
+ const template = templates.find((t) => t.name === term.name && t.arity === term.args.length);
1153
+ if (template) {
1154
+ let n = 0;
1155
+ return template.parts.map((p) => p.place ? leValue(term.args[n++], templates) : p.text).join(' ');
607
1156
  }
608
1157
  }
609
- const article = /^[aeiou]/.test(term.name) ? 'an' : 'a';
610
- if (term.args.length === 1) return `${render(term.args[0])} is ${article} ${term.name}`;
611
- if (properties && term.args.length === 2) return `${render(term.args[0])} has ${term.name} ${render(term.args[1])}`;
612
- if (term.args.length === 2) return `${render(term.args[0])} is ${article} ${term.name} of ${render(term.args[1])}`;
613
- return `${term.name}(${term.args.map(render).join(', ')})`;
1158
+ return write(term);
614
1159
  }
615
1160
 
616
- export function writeLe(result, { odrl = null, prefixes = {} } = {}) {
617
- if (odrl) result = odrlLeReport(result, odrl.namespace);
618
- // A prefix LE cannot spell, such as Turtle's empty one, gets the first free
619
- // name of ns, ns2, ...; the output declares each prefix it uses.
620
- // An ODRL report names its own namespace's resources bare where a name
621
- // reads back as that IRI; inside a witness key a prefix keeps it an IRI.
622
- const valid = Object.entries(prefixes).filter(([prefix, namespace]) => PREFIX.test(prefix) && typeof namespace === 'string');
623
- const taken = new Set(valid.map(([prefix]) => prefix)), stated = new Set(valid.map(([, namespace]) => namespace));
624
- for (const [prefix, namespace] of Object.entries(prefixes)) {
625
- if (PREFIX.test(prefix) || typeof namespace !== 'string' || stated.has(namespace)) continue;
626
- let name = 'ns';
627
- for (let n = 2; taken.has(name); n++) name = `ns${n}`;
628
- taken.add(name); stated.add(namespace);
629
- valid.push([name, namespace]);
630
- }
631
- const namespaces = valid.sort((a, b) => b[1].length - a[1].length);
632
- const used = new Map();
633
- const compact = (term) => {
634
- if (!(term instanceof Struct) || term.name !== 'iri' || term.args.length !== 1 || typeof term.args[0] !== 'string') return null;
635
- for (const [prefix, namespace] of namespaces) {
636
- if (!term.args[0].startsWith(namespace)) continue;
637
- const local = term.args[0].slice(namespace.length);
638
- if (!LOCAL.test(local)) continue;
639
- used.set(prefix, namespace);
640
- return `${prefix}:${local}`;
641
- }
642
- return null;
643
- };
644
- const lines = [];
1161
+ // The answers of a query as sentences: the query's words, with each variable
1162
+ // it found a value for written as that value.
1163
+ function sentence(query, values, templates) {
1164
+ const words = [];
1165
+ for (let i = 0; i < query.tokens.length; i++) {
1166
+ const mark = query.marks.find((m) => m.at === i);
1167
+ const value = mark && mark.slot >= 0 ? values[mark.slot] : undefined;
1168
+ // An answer that leaves a variable open writes _ there, as LE does.
1169
+ if (value !== undefined) {
1170
+ words.push(value instanceof Var ? '_' : leValue(value, templates));
1171
+ i += mark.length - 1;
1172
+ } else words.push(query.tokens[i]);
1173
+ }
1174
+ return joined(words);
1175
+ }
1176
+
1177
+ // The conclusions of a run: each query's answers in each scenario, as
1178
+ // sentences, and any expected answers that differ from them.
1179
+ export function writeLe(result, loaded) {
1180
+ const { templates, scenarios, threaded, queries, expectations } = loaded.compiled;
1181
+ const found = new Map();
645
1182
  for (const answer of result.answers) {
646
1183
  const term = readTerm(answer);
647
- const names = new Map([...variablesIn([term])].map((name, i) => [name, `X${i}`]));
648
- const quantifier = names.size ? `For every ${[...names.values()].join(' and ')}, ` : '';
649
- const render = (arg) => leTerm(arg, names, compact);
650
- lines.push(quantifier + flattenConjunction(term).map((goal) => leGoal(goal, render, odrl !== null, compact)).join(' and ') + '.');
651
- }
652
- const declarations = [...used].sort().map(([prefix, namespace]) => `Use prefix ${prefix} with namespace ${JSON.stringify(namespace)}.`);
653
- const header = (odrl ? `Use ODRL vocabulary with namespace ${JSON.stringify(odrl.namespace)}.\n` : '') +
654
- (declarations.length ? `${declarations.join('\n')}\n` : '') + (odrl || declarations.length ? '\n' : '');
655
- return header + (lines.length ? lines.join('\n') + '\n' : '# No conclusions.\n');
1184
+ if (!(term instanceof Struct) || term.name !== ANSWER) continue;
1185
+ const [name, ...rest] = term.args;
1186
+ const scenario = threaded ? rest.shift() : null;
1187
+ const query = queries.find((q) => q.name === name);
1188
+ if (!query) continue;
1189
+ const key = `${scenario}\u0000${name}`;
1190
+ if (!found.has(key)) found.set(key, []);
1191
+ const text = sentence(query, rest, templates);
1192
+ if (!found.get(key).includes(text)) found.get(key).push(text);
1193
+ }
1194
+ const blocks = [];
1195
+ for (const scenario of threaded ? scenarios : [null]) {
1196
+ for (const query of queries) {
1197
+ const answers = found.get(`${scenario}\u0000${query.name}`) ?? [];
1198
+ const title = scenario === null ? `% query ${query.name}` : `% query ${query.name} with scenario ${scenario}`;
1199
+ const lines = [title, ...(answers.length ? answers.map((a) => `${a}.`) : ['% no answers'])];
1200
+ const expected = expectations.find((e) => e.scenario === scenario && e.query === query.name && !e.unknowns.length);
1201
+ // LE2 writes the underscores of names as spaces and repeats an answer
1202
+ // for each proof; expected answers are compared as a set, either way.
1203
+ const same = (a) => a.replaceAll('_', ' ').replace(/\s*-\s*/g, '-').replace(/\s+/g, ' ').trim();
1204
+ const want = new Set(expected?.answers.map(same)), got = new Set(answers.map(same));
1205
+ if (expected && (want.size !== got.size || [...want].some((a) => !got.has(a)))) {
1206
+ lines.push(`% not as expected: ${query.name} expects answers [${expected.answers.map((a) => JSON.stringify(a)).join(', ')}]`);
1207
+ }
1208
+ blocks.push(lines.join('\n'));
1209
+ }
1210
+ }
1211
+ return blocks.length ? blocks.join('\n\n') + '\n' : '% no queries\n';
656
1212
  }