eyemind 0.8.52 → 0.9.1

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,1364 @@
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 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;
134
+ }
135
+
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
+ }
195
+ }
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;
203
+ }
204
+
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
+ }
74
315
  }
75
316
 
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];
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;
81
324
  }
82
- return term === EMPTY ? items : null;
325
+ return -1;
83
326
  }
84
327
 
85
- class Parser {
86
- constructor(text, file) {
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
+ // LE2's explicit variable: *a name*.
370
+ if (first.text === '*' && tokens.at(-1).text === '*' && tokens.length > 2 && tokens.slice(1, -1).every((t) => t.kind === 'word')) {
371
+ const words = tokens.slice(1, -1), named = INTRODUCING.has(lower(words[0])) || isWord(words[0], 'the') ? words.slice(1) : words;
372
+ return this.mark(scope, scope.find(named) ?? scope.introduce(named.length ? named : words), this.offset(tokens), tokens.length);
373
+ }
374
+ if (!tokens.every((t) => t.kind === 'word' || t.kind === 'number' || t.text === '&')) return null;
375
+ // A lone which, what, who, when or where asks for a value.
376
+ if (tokens.length === 1 && isWord(first, 'which', 'what', 'who', 'when', 'where')) {
377
+ return this.mark(scope, scope.introduce([{ ...first, text: first.text[0].toUpperCase() + first.text.slice(1) }]), this.offset(tokens), 1);
251
378
  }
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));
379
+ const head = lower(first), rest = tokens.slice(1);
380
+ // A kind is a name, unless a phrase such as "which type" asks for it.
381
+ if (type && !(INTRODUCING.has(head) && rest.length && scope.find(rest) === undefined && rest.length <= 2)) return tokens.map((t) => t.text).join(' ');
382
+ const at = this.offset(tokens);
383
+ 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'))) {
384
+ return this.mark(scope, scope.introduce(rest), at, tokens.length);
256
385
  }
257
- return left;
386
+ const constant = this.constants?.get(tokens.map((t) => t.text.toLowerCase()).join(' '));
387
+ if (head === 'the' && rest.length) {
388
+ const found = scope.find(rest);
389
+ if (found) return this.mark(scope, found, at, tokens.length);
390
+ if (constant !== undefined) return constant;
391
+ return ['the', ...rest.map((t) => t.text)].join(' ');
392
+ }
393
+ const found = scope.find(tokens);
394
+ if (found) return this.mark(scope, found, at, tokens.length);
395
+ if (constant !== undefined) return constant;
396
+ if (tokens.length === 1 && BARE_ID.test(first.text) && !this.fact) return this.mark(scope, scope.introduce(tokens), at, 1);
397
+ return tokens.map((t) => t.text).join(' ');
258
398
  }
259
399
 
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());
400
+ // Where a slice starts in the sentence a query renders its answers from.
401
+ offset(tokens) { return this.sentence ? this.sentence.indexOf(tokens[0]) : -1; }
402
+
403
+ mark(scope, variable, at, length) {
404
+ if (at >= 0) scope.marks.push({ at, length, variable });
405
+ return variable;
406
+ }
407
+
408
+ // An arithmetic formula or a term: { term, goals, formula }.
409
+ expression(tokens, scope) {
410
+ // In a formula, ET-P is ET - P when its parts are variables.
411
+ tokens = tokens.flatMap((t) => {
412
+ if (t.kind !== 'word' || !t.text.includes('-') || scope.find([t])) return [t];
413
+ const parts = t.text.split('-').map((text) => ({ ...t, text }));
414
+ if (!parts.every((part) => scope.find([part]))) return [t];
415
+ return parts.flatMap((part, i) => i ? [{ ...t, text: '-', kind: 'punct' }, part] : [part]);
416
+ });
417
+ const level = depths(tokens);
418
+ if (!tokens.some((t, i) => level[i] === 0 && (OPERATORS.has(lower(t)) && !(t.kind === 'word' && t.text !== 'mod')) || t.text === '(')) {
419
+ const term = this.term(tokens, scope);
420
+ return term === null ? null : { term, goals: [], formula: false };
269
421
  }
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);
422
+ const goals = [];
423
+ let at = 0;
424
+ const peek = () => tokens[at];
425
+ const operand = () => {
426
+ const start = at;
427
+ let depth = 0;
428
+ while (at < tokens.length) {
429
+ const t = tokens[at];
430
+ if (t.text === '[') depth++;
431
+ if (t.text === ']') depth--;
432
+ if (depth === 0 && (OPERATORS.has(lower(t)) && (t.kind !== 'word' || t.text === 'mod') || t.text === '(' || t.text === ')' || t.text === ',')) break;
433
+ at++;
434
+ }
435
+ if (at === start) return null;
436
+ return this.term(tokens.slice(start, at), scope);
437
+ };
438
+ const factor = () => {
439
+ const t = peek();
440
+ if (!t) return null;
441
+ if (t.text === '-') { at++; const f = factor(); return f === null ? null : st('neg', f); }
442
+ if (t.text === '(') {
443
+ at++;
444
+ const e = sum();
445
+ if (e === null || peek()?.text !== ')') return null;
446
+ at++;
447
+ return e;
448
+ }
449
+ if (t.kind === 'word' && FUNCTIONS[lower(t)] && tokens[at + 1]?.text === '(') {
450
+ at += 2;
451
+ const e = sum();
452
+ if (e === null || peek()?.text !== ')') return null;
453
+ at++;
454
+ return st(FUNCTIONS[lower(t)], e);
455
+ }
456
+ return operand();
457
+ };
458
+ const product = () => {
459
+ let left = factor();
460
+ while (left !== null && peek() && ['*', '/', '//'].includes(peek().text) || (left !== null && peek() && peek().kind === 'word' && peek().text === 'mod')) {
461
+ const op = peek().text;
462
+ at++;
463
+ const right = factor();
464
+ if (right === null) return null;
465
+ if (op === '/') {
466
+ const quotient = new Var(`Q${this.quotients = (this.quotients ?? 0) + 1}`);
467
+ goals.push(this.helper('le:divide', left, right, quotient));
468
+ left = quotient;
469
+ } else left = st(op === '*' ? 'mul' : op === '//' ? 'floordiv' : 'mod', left, right);
470
+ }
471
+ return left;
472
+ };
473
+ const sum = () => {
474
+ let left = product();
475
+ while (left !== null && peek() && (peek().text === '+' || peek().text === '-')) {
476
+ const op = peek().text;
477
+ at++;
478
+ const right = product();
479
+ if (right === null) return null;
480
+ left = st(op === '+' ? 'add' : 'sub', left, right);
276
481
  }
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());
482
+ return left;
483
+ };
484
+ const term = sum();
485
+ if (term === null || at !== tokens.length) return null;
486
+ return { term, goals, formula: true };
487
+ }
488
+
489
+ equal(a, b) {
490
+ if (!a.formula && !b.formula) return [...a.goals, ...b.goals, st('unify', a.term, b.term)];
491
+ if (!a.formula) return [...b.goals, st('is', a.term, b.term)];
492
+ if (!b.formula) return [...a.goals, st('is', b.term, a.term)];
493
+ return [...a.goals, ...b.goals, st('eq', a.term, b.term)];
494
+ }
495
+
496
+ different(a, b) {
497
+ if (!a.formula && !b.formula) return [st('not_unify', a.term, b.term)];
498
+ return [...a.goals, ...b.goals, st('ne', a.term, b.term)];
499
+ }
500
+
501
+ compare(op, a, b) { return [...a.goals, ...b.goals, st(op, a.term, b.term)]; }
502
+
503
+ // One condition: a comparison, or a sentence of a template.
504
+ condition(tokens, scope) {
505
+ const level = depths(tokens);
506
+ const at = tokens.findIndex((t, i) => level[i] === 0 && t.kind === 'punct' && COMPARISONS.has(t.text));
507
+ if (at > 0) {
508
+ const a = this.expression(tokens.slice(0, at), scope), b = a && this.expression(tokens.slice(at + 1), scope);
509
+ if (!a || !b) return null;
510
+ const op = tokens[at].text;
511
+ if (op === '=' || op === '==') return this.equal(a, b);
512
+ if (op === '!=' || op === '\\=') return this.different(a, b);
513
+ if (op === '\\==') return [st('not_identical', a.term, b.term)];
514
+ return this.compare({ '<': 'lt', '>': 'gt', '<=': 'le', '=<': 'le', '>=': 'ge' }[op], a, b);
515
+ }
516
+ const sentence = this.sentenceOf(tokens, scope);
517
+ if (!sentence) return null;
518
+ if (sentence.builtin) return sentence.goals;
519
+ return [this.relation(sentence.name, sentence.args)];
520
+ }
521
+
522
+ // The best template for a sentence: as in LE, one with a "that" place
523
+ // first, then the one with the most words, a declared template before a
524
+ // built-in one. Its arguments are the places' terms.
525
+ sentenceOf(tokens, scope, { data = false } = {}) {
526
+ const meta = (t) => t.parts.some((p) => p.meta) ? 1 : 0;
527
+ const candidates = [...this.templates, ...(data ? [] : BUILTINS), ...TYPE_TEMPLATES].sort((a, b) => meta(b) - meta(a) || b.words - a.words);
528
+ for (const template of candidates) {
529
+ for (const fills of matches(template.parts, tokens)) {
530
+ const saved = scope.save();
531
+ const args = [];
532
+ const places = template.parts.filter((p) => p.place);
533
+ for (let i = 0; i < fills.length && args.length === i; i++) {
534
+ const place = places[i];
535
+ let value = null;
536
+ if (place.meta) {
537
+ const inner = this.sentenceOf(fills[i], scope, { data: true });
538
+ if (inner) value = inner.builtin ? null : st(inner.name, ...inner.args);
539
+ }
540
+ if (value === null && place.expr) value = this.expression(fills[i], scope);
541
+ else if (value === null) value = this.term(fills[i], scope, { type: place.type });
542
+ if (value !== null) args.push(value);
284
543
  }
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());
544
+ if (args.length === fills.length) {
545
+ // A built-in template with formula places takes { term, goals, formula }.
546
+ const goals = template.builtin ? template.compile(this, args) : null;
547
+ if (goals) return { builtin: true, goals };
548
+ if (!template.builtin) return { name: template.name, args };
296
549
  }
550
+ scope.restore(saved);
297
551
  }
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 ..."`);
552
+ }
553
+ return null;
554
+ }
555
+
556
+ // ------------------------------------------------------------ Conditions
557
+
558
+ // A body of conditions: lines joined by "and" and "or", where a deeper
559
+ // indentation binds tighter, as in LE. Negations, universals and aggregates
560
+ // take the deeper lines that follow them.
561
+ body(tokens, scope) {
562
+ const entries = this.entries(tokens, scope);
563
+ return this.combine(entries);
564
+ }
565
+
566
+ // The conditions of a slice as entries { op, indent, goals }.
567
+ entries(tokens, scope) {
568
+ const entries = [];
569
+ let i = 0;
570
+ let op = null, indent = tokens[0]?.indent ?? 0;
571
+ while (i < tokens.length) {
572
+ // A construct starts here: it runs to the next line that starts with a
573
+ // connective at its own indentation or less.
574
+ const t = tokens[i];
575
+ const lineIndent = t.indent;
576
+ const end = (from) => {
577
+ for (let k = from; k < tokens.length; k++) {
578
+ if (tokens[k].bol && isWord(tokens[k], 'and', 'or') && tokens[k].indent <= lineIndent) return k;
579
+ }
580
+ return tokens.length;
581
+ };
582
+ let construct = null, next = i;
583
+ const negation = startsWith(tokens, ['it', 'is', 'not', 'the', 'case', 'that'], i) ? 6 : startsWith(tokens, ['not', 'the', 'case', 'that'], i) ? 4 : 0;
584
+ if (negation) {
585
+ next = end(i + negation);
586
+ const inner = tokens.slice(i + negation, next);
587
+ if (!inner.length) this.error('"it is not the case that" needs a condition', t.line);
588
+ construct = [st('not', conjunction(this.body(inner, scope)))];
589
+ } else if (startsWith(tokens, ['for', 'all', 'cases', 'in', 'which'], i)) {
590
+ next = end(i + 5);
591
+ const inner = tokens.slice(i + 5, next);
592
+ const split = indexOfWords(inner, ['it', 'is', 'the', 'case', 'that']);
593
+ if (split < 0) this.error('"for all cases in which" needs "it is the case that"', t.line);
594
+ const then = inner.slice(split + 5 + (inner[split + 5]?.text === ':' ? 1 : 0));
595
+ const conditions = this.body(inner.slice(0, split), scope), consequence = this.body(then, scope);
596
+ construct = [st('not', conjunction([...conditions, st('not', conjunction(consequence))]))];
597
+ } else {
598
+ const aggregate = this.aggregate(tokens, i, scope, end);
599
+ if (aggregate) [construct, next] = aggregate;
331
600
  }
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);
601
+ if (construct) {
602
+ entries.push({ op, indent, goals: construct });
603
+ i = next;
604
+ } else {
605
+ // A segment of plain conditions runs to the next line that starts
606
+ // with a connective, or a construct.
607
+ let k = i + 1;
608
+ while (k < tokens.length && !(tokens[k].bol && isWord(tokens[k], 'and', 'or'))) k++;
609
+ // A construct inside the segment, after a connective, ends it there.
610
+ let cut = k;
611
+ for (let m = i + 1; m < k; m++) {
612
+ if (isWord(tokens[m - 1], 'and', 'or') && (startsWith(tokens, ['it', 'is', 'not', 'the', 'case', 'that'], m) ||
613
+ startsWith(tokens, ['for', 'all', 'cases', 'in', 'which'], m) || aggregateAt(tokens, m) >= 0)) { cut = m - 1; break; }
362
614
  }
363
- this.checkOrder(flattenConjunction(goal.args[1]), inner, line);
364
- bound.add(goal.args[2].name);
365
- continue;
615
+ const pieces = this.split(tokens.slice(i, cut), scope);
616
+ if (!pieces) this.error(`no template matches "${phrase(tokens.slice(i, cut))}"`, t.line);
617
+ pieces[0].op = op; pieces[0].indent = indent;
618
+ entries.push(...pieces);
619
+ i = cut;
366
620
  }
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');
621
+ if (i < tokens.length) {
622
+ if (!isWord(tokens[i], 'and', 'or')) this.error(`expected "and" or "or" before "${phrase(tokens.slice(i, i + 6))}"`, tokens[i].line);
623
+ op = lower(tokens[i]);
624
+ indent = tokens[i].indent;
625
+ i++;
431
626
  }
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']]; }
627
+ }
628
+ if (!entries.length) this.error('a condition is missing', tokens[0]?.line ?? 0);
629
+ return entries;
630
+ }
631
+
632
+ // An aggregate at i: "R is the sum of each V such that" or LE's
633
+ // "R is a collection of V where", followed by its conditions.
634
+ aggregate(tokens, i, scope, end) {
635
+ const k = aggregateAt(tokens, i);
636
+ if (k >= 0) {
637
+ if (startsWith(tokens, ['is', 'the'], k) && AGGREGATES[lower(tokens[k + 2] ?? {})] !== undefined && startsWith(tokens, ['of', 'each'], k + 3)) {
638
+ const thatAt = indexOfWords(tokens, ['such', 'that'], k + 5);
639
+ if (thatAt < 0) return null;
640
+ const next = end(thatAt + 2);
641
+ return [this.collect(tokens.slice(i, k), tokens.slice(k + 4, thatAt), tokens.slice(thatAt + 2, next), lower(tokens[k + 2]), scope), next];
442
642
  }
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);
643
+ if (startsWith(tokens, ['is', 'a', 'collection', 'of'], k)) {
644
+ const whereAt = tokens.findIndex((t, m) => m > k + 4 && isWord(t, 'where'));
645
+ if (whereAt < 0) return null;
646
+ const next = end(whereAt + 1);
647
+ return [this.collect(tokens.slice(i, k), tokens.slice(k + 4, whereAt), tokens.slice(whereAt + 1, next), 'list', scope), next];
453
648
  }
454
649
  }
455
- return { kind, heads, bodies, line };
650
+ return null;
651
+ }
652
+
653
+ collect(result, each, conditions, op, scope) {
654
+ const line = (result[0] ?? each[0]).line;
655
+ const total = this.term(result, scope);
656
+ if (total === null) this.error(`the result of an aggregate is a variable such as "a number N", not "${phrase(result)}"`, line);
657
+ const template = this.term(each, scope);
658
+ if (template === null) this.error(`an aggregate collects a variable, not "${phrase(each)}"`, line);
659
+ if (!conditions.length) this.error('an aggregate needs conditions after "such that"', line);
660
+ const goals = this.body(conditions, scope);
661
+ const items = new Var(`L${this.lists = (this.lists ?? 0) + 1}`);
662
+ const found = st('findall', template, conjunction(goals), items);
663
+ return AGGREGATES[op] === null ? [found, st('unify', total, items)] : [found, this.helper(AGGREGATES[op], items, total)];
664
+ }
665
+
666
+ // Splits a segment into conditions at an inline "and" or "or", or a line
667
+ // break, wherever every piece is a condition; fewer tokens first.
668
+ split(tokens, scope) {
669
+ const cuts = [];
670
+ for (let i = 1; i < tokens.length; i++) {
671
+ if (isWord(tokens[i], 'and', 'or') && i + 1 < tokens.length) cuts.push({ at: i, skip: 1, op: lower(tokens[i]), indent: tokens[i].indent });
672
+ else if (tokens[i].bol && !isWord(tokens[i - 1], 'and', 'or')) cuts.push({ at: i, skip: 0, op: 'and', indent: tokens[i].indent });
673
+ }
674
+ const attempt = (from, start) => {
675
+ const options = [...cuts.filter((c) => c.at > start), { at: tokens.length, skip: 0 }];
676
+ for (const cut of options) {
677
+ const saved = scope.save();
678
+ const goals = this.condition(tokens.slice(start, cut.at), scope);
679
+ if (goals) {
680
+ if (cut.at === tokens.length) return [{ goals }];
681
+ const rest = attempt(cut, cut.at + cut.skip);
682
+ if (rest) { rest[0].op = cut.op; rest[0].indent = cut.indent; return [{ goals }, ...rest]; }
683
+ }
684
+ scope.restore(saved);
685
+ }
686
+ return null;
687
+ };
688
+ return attempt(null, 0);
689
+ }
690
+
691
+ // Entries joined by their connectives: the shallowest connectives last,
692
+ // and connectives at one indentation from the top down.
693
+ combine(entries) {
694
+ if (entries.length === 1) return entries[0].goals;
695
+ const least = Math.min(...entries.slice(1).map((e) => e.indent));
696
+ const groups = [[entries[0]]];
697
+ for (const entry of entries.slice(1)) {
698
+ if (entry.indent === least) groups.push([entry]);
699
+ else groups.at(-1).push(entry);
700
+ }
701
+ let goals = this.combine([{ ...groups[0][0], op: null }, ...groups[0].slice(1)]);
702
+ for (const group of groups.slice(1)) {
703
+ const right = this.combine([{ ...group[0], op: null }, ...group.slice(1)]);
704
+ goals = group[0].op === 'or' ? [st('or', conjunction(goals), conjunction(right))] : [...goals, ...right];
705
+ }
706
+ return goals;
456
707
  }
457
708
  }
458
709
 
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);
710
+ // Variables that occur only inside negations stand for any value there: they
711
+ // are renamed _0, _1, ..., which LS negation treats as anonymous.
712
+ function anonymize(head, goals) {
713
+ const outside = new Set(), inside = new Set();
714
+ const visit = (term, negated) => {
715
+ if (term instanceof Var) (negated ? inside : outside).add(term);
716
+ else if (term instanceof Struct) {
717
+ const deeper = negated || (term.name === 'not' && term.args.length === 1);
718
+ for (const arg of term.args) visit(arg, deeper);
719
+ }
720
+ };
721
+ visit(head, false);
722
+ for (const goal of goals) visit(goal, false);
723
+ let n = 0;
724
+ for (const variable of inside) if (!outside.has(variable)) variable.name = `_${n++}`;
725
+ return n;
463
726
  }
464
727
 
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);
728
+ const varsOf = (term, out = new Set()) => {
729
+ if (term instanceof Var) out.add(term);
730
+ else if (term instanceof Struct) for (const arg of term.args) varsOf(arg, out);
731
+ return out;
732
+ };
733
+
734
+ function substitute(term, map) {
735
+ if (term instanceof Var) return map.get(term) ?? term;
736
+ if (term instanceof Struct) return new Struct(term.name, term.args.map((arg) => substitute(arg, map)));
737
+ return term;
468
738
  }
469
739
 
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);
740
+ // Prolog's negation, which LE's rules are written for, succeeds when no
741
+ // instance of its goal holds if a variable of the goal is still unbound. LS
742
+ // requires the variables of a negation to be bound, so a negation whose
743
+ // variable no earlier condition binds tests at run time: while the variable
744
+ // is unbound, the negation stands for any value there.
745
+ function guardNegations(goals, bound, counter, open = false) {
746
+ const out = [];
747
+ for (const goal of goals) {
748
+ if (goal instanceof Struct && goal.name === 'not' && goal.args.length === 1) {
749
+ const inner = guardInner(goal.args[0], bound, counter, open);
750
+ const unbound = [...varsOf(inner)].filter((v) => !/^_\d+$/.test(v.name) && !bound.has(v));
751
+ if (!unbound.length || unbound.length > 3) out.push(st('not', inner));
752
+ else {
753
+ const cases = [];
754
+ for (let mask = 0; mask < 1 << unbound.length; mask++) {
755
+ const map = new Map(), tests = [];
756
+ unbound.forEach((v, i) => {
757
+ if (mask & (1 << i)) { tests.push(st('is_var', v)); map.set(v, new Var(`_${counter.n++}`)); }
758
+ else tests.push(st('is_nonvar', v));
759
+ });
760
+ cases.push(conjunction([...tests, st('not', substitute(inner, map))]));
761
+ }
762
+ out.push(cases.reduce((a, b) => st('or', a, b)));
763
+ }
764
+ continue;
765
+ }
766
+ if (goal instanceof Struct && goal.name === 'or' && goal.args.length === 2) {
767
+ const branches = goal.args.map((branch) => conjunction(guardNegations(flatten(branch), new Set(bound), counter, open)));
768
+ out.push(st('or', ...branches));
769
+ if (!open) varsOf(goal, bound);
770
+ continue;
771
+ }
772
+ out.push(goal);
773
+ if (open) continue;
774
+ if (goal instanceof Struct && goal.name === 'findall' && goal.args.length === 3) varsOf(goal.args[2], bound);
775
+ else varsOf(goal, bound);
476
776
  }
477
- return result;
777
+ return out;
478
778
  }
479
779
 
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);
780
+ function guardInner(goal, bound, counter, open) {
781
+ return conjunction(guardNegations(flatten(goal), new Set(bound), counter, open));
487
782
  }
488
783
 
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;
784
+ function flatten(goal) {
785
+ if (goal instanceof Struct && goal.name === 'and' && goal.args.length === 2) return [...flatten(goal.args[0]), ...flatten(goal.args[1])];
786
+ return [goal];
787
+ }
788
+
789
+ // Variables outside negations and collections, in order: a query's answer.
790
+ function openVariables(goals) {
791
+ const out = [];
792
+ const visit = (term) => {
793
+ if (term instanceof Var) { if (!out.includes(term)) out.push(term); }
794
+ else if (term instanceof Struct && !(term.name === 'not' && term.args.length === 1) && !(term.name === 'findall' && term.args.length === 3)) {
795
+ for (const arg of term.args) visit(arg);
796
+ } else if (term instanceof Struct && term.name === 'findall') visit(term.args[2]);
797
+ };
798
+ for (const goal of goals) visit(goal);
799
+ return out;
800
+ }
801
+
802
+ // ---------------------------------------------------------------- Documents
803
+
804
+ // The sections of one document as sentences: [kind, name, tokens, line].
805
+ function sections(tokens, file) {
806
+ const error = (message, line) => { throw new EyemindError(`${file}: line ${line}: Logical English: ${message}`); };
807
+ const out = [];
808
+ let i = 0, section = null;
809
+ const colon = (from) => {
810
+ for (let k = from; k < tokens.length && tokens[k].kind !== 'stop' && tokens[k].kind !== 'end'; k++) if (tokens[k].text === ':') return k;
811
+ return -1;
812
+ };
813
+ while (tokens[i].kind !== 'end') {
814
+ const line = tokens[i].line;
815
+ if (startsWith(tokens, ['the', 'target', 'language', 'is'], i)) {
816
+ while (tokens[i].kind !== 'stop' && tokens[i].kind !== 'end') i++;
817
+ i++;
818
+ continue;
819
+ }
820
+ if (startsWith(tokens, ['the', 'templates', 'are'], i) || startsWith(tokens, ['the', 'predicates', 'are'], i)) {
821
+ if (tokens[i + 3]?.text !== ':') error('expected ":" after "the templates are"', line);
822
+ section = { kind: 'templates' };
823
+ i += 4;
824
+ continue;
825
+ }
826
+ // An ontology states what kinds of thing are kinds of other things.
827
+ if (startsWith(tokens, ['the', 'ontology', 'is', ':'], i)) {
828
+ section = { kind: 'ontology' };
829
+ i += 4;
830
+ continue;
831
+ }
832
+ // LE2 also opens a knowledge base with "the contract NAME states that:".
833
+ if (startsWith(tokens, ['the', 'contract'], i) && colon(i) > 0 && startsWith(tokens, ['states', 'that'], colon(i) - 2)) {
834
+ section = { kind: 'kb', name: tokens.slice(i + 2, colon(i) - 2).map((t) => t.text).join(' ') };
835
+ i = colon(i) + 1;
836
+ continue;
837
+ }
838
+ if (startsWith(tokens, ['the', 'knowledge', 'base'], i)) {
839
+ const at = colon(i);
840
+ // "includes these resources:" or "includes these scenarios:" names other
841
+ // files, separated by commas, up to a full stop.
842
+ if (at > 0 && startsWith(tokens, ['includes', 'these'], at - 3) && isWord(tokens[at - 1], 'resources', 'scenarios')) {
843
+ let end = at + 1;
844
+ while (tokens[end].kind !== 'stop' && tokens[end].kind !== 'end') end++;
845
+ const names = [];
846
+ let name = [];
847
+ for (const t of [...tokens.slice(at + 1, end), { text: ',' }]) {
848
+ if (t.text !== ',') { name.push(t.text); continue; }
849
+ if (name.length) names.push(name.join(''));
850
+ name = [];
851
+ }
852
+ out.push(['include', lower(tokens[at - 1]), names, line]);
853
+ i = end + 1;
500
854
  continue;
501
855
  }
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 };
856
+ const includes = at > 0 && isWord(tokens[at - 1], 'includes');
857
+ if (!includes) error('expected "the knowledge base NAME includes:"', line);
858
+ section = { kind: 'kb', name: tokens.slice(i + 3, at - 1).map((t) => t.text).join(' ') };
859
+ i = at + 1;
860
+ continue;
861
+ }
862
+ if (isWord(tokens[i], 'scenario', 'query') && tokens[i].bol) {
863
+ const at = colon(i);
864
+ if (at > i + 2 && isWord(tokens[at - 1], 'is')) {
865
+ const name = tokens.slice(i + 1, at - 1).map((t) => t.text).join(' ');
866
+ section = { kind: lower(tokens[i]), name, line };
867
+ if (section.kind === 'scenario') out.push(['scenario', name, [], line]);
868
+ i = at + 1;
505
869
  continue;
506
870
  }
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));
871
+ if (at > 0) error(`the header "${phrase(tokens.slice(i, at + 1))}" belongs to Logical English 2 and is not supported`, line);
872
+ }
873
+ // LE2 labels a rule with "rule NAME:", and marks sections of rules with
874
+ // "section NAME is:" or "the annexes to the contract are:". Neither
875
+ // changes what the rules mean.
876
+ if (isWord(tokens[i], 'rule') && colon(i) > i + 1 && colon(i) < i + 5 && tokens.slice(i + 1, colon(i)).every((t) => t.kind === 'word' || t.kind === 'number')) {
877
+ i = colon(i) + 1;
878
+ continue;
879
+ }
880
+ if ((isWord(tokens[i], 'section') && tokens[i].bol && colon(i) > 0 && isWord(tokens[colon(i) - 1], 'is')) ||
881
+ (startsWith(tokens, ['the', 'annexes', 'to', 'the'], i) && colon(i) > 0 && isWord(tokens[colon(i) - 1], 'are'))) {
882
+ i = colon(i) + 1;
883
+ continue;
884
+ }
885
+ // LE2's named constants: "the fee is 5."
886
+ if (startsWith(tokens, ['the', 'constants', 'are', ':'], i)) {
887
+ section = { kind: 'constants' };
888
+ i += 4;
889
+ continue;
890
+ }
891
+ const unsupported = SECTIONS.find((words) => startsWith(tokens, words.split(' '), i));
892
+ if (unsupported) error(`the section "${unsupported}" belongs to Logical English 2 and is not supported`, line);
893
+ let end = i;
894
+ while (tokens[end].kind !== 'stop' && tokens[end].kind !== 'end') end++;
895
+ if (tokens[end].kind === 'end') error(`a sentence must end with a full stop: "${phrase(tokens.slice(i, Math.min(end, i + 12)))}"`, line);
896
+ const sentence = tokens.slice(i, end);
897
+ if (!section) error('a sentence comes before any section; start with "the templates are:"', line);
898
+ if (section.kind === 'templates') {
899
+ // Templates are separated by full stops, and by commas that end a
900
+ // line or come before a place: a template's own words may hold commas.
901
+ // A part without words of its own belongs to the template before it.
902
+ const level = depths(sentence), parts = [];
903
+ let start = 0;
904
+ for (let k = 0; k <= sentence.length; k++) {
905
+ const separates = sentence[k]?.text === ',' && level[k] === 0 && (k + 1 === sentence.length || sentence[k + 1].bol || sentence[k + 1].text === '*');
906
+ if (k < sentence.length && !separates) continue;
907
+ if (k > start) {
908
+ const part = sentence.slice(start, k);
909
+ let inside = false;
910
+ const words = part.some((t) => { if (t.text === '*') inside = !inside; return !inside && t.kind === 'word'; });
911
+ if (!words && parts.length && sentence[start - 1]?.text === ',') parts.at(-1).push(sentence[start - 1], ...part);
912
+ else parts.push(part);
521
913
  }
914
+ start = k + 1;
522
915
  }
916
+ for (const part of parts) out.push(['template', null, part, part[0].line]);
917
+ } else if (section.kind === 'constants') {
918
+ out.push(['constant', null, sentence, line]);
919
+ } else if (section.kind === 'query') {
920
+ out.push(['query', section.name, sentence, line]);
921
+ section = { kind: 'after query' };
922
+ } else if (section.kind === 'after query') {
923
+ error('a query has one sentence; start a new section after it', line);
924
+ } else {
925
+ out.push([{ kb: 'clause', ontology: 'ontology clause' }[section.kind] ?? 'scenario clause', section.name ?? null, sentence, line]);
523
926
  }
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'"})`);
927
+ i = end + 1;
928
+ }
929
+ return out;
930
+ }
931
+
932
+ // The ways LE2 lets a template be read, after ";": additions that change
933
+ // nothing eyemind computes, and additions that make a sentence assumable.
934
+ const IGNORED = ['memorable', 'memoised', 'memoized', 'cached', 'undefined', 'scenario element', 'one value', 'single valued'];
935
+ const ASSUMABLE = ['assumable', 'unknown', 'assumed', 'judged', 'open textured', 'evaluative'];
936
+
937
+ // io.readFile reads an included file. The paths of an included file's own
938
+ // includes are relative to it; a chain of includes stops at five.
939
+ export function compileLe(inputs, io = null) {
940
+ const items = [], read = new Set();
941
+ const load = (text, file, keep, depth) => {
942
+ for (const item of sections(tokenize(String(text), file), file)) {
943
+ if (item[0] === 'include') {
944
+ const [, kind, names, line] = item;
945
+ const fail = (message) => { throw new EyemindError(`${file}: line ${line}: Logical English: ${message}`); };
946
+ for (const name of names) {
947
+ if (/^[a-z]+:/i.test(name)) fail(`including the web address ${name} belongs to Logical English 2 and is not supported; include a local file`);
948
+ if (/\.pl$/.test(name)) fail(`including the Prolog resource ${name} belongs to Logical English 2 and is not supported`);
949
+ const dir = String(file).includes('/') ? String(file).slice(0, String(file).lastIndexOf('/') + 1) : '';
950
+ const path = dir + name + (name.endsWith('.le') ? '' : '.le');
951
+ if (read.has(path)) continue;
952
+ if (depth >= 5) fail(`including ${name} makes a chain of more than five includes`);
953
+ if (!io?.readFile) fail(`including ${name} needs file access`);
954
+ let included;
955
+ try { included = io.readFile(path); } catch { fail(`cannot read the included file ${path}`); }
956
+ read.add(path);
957
+ // A resource gives its templates, rules, facts and ontology; an
958
+ // included scenario file also gives its scenarios and queries.
959
+ load(included, path, kind === 'scenarios', depth + 1);
960
+ }
961
+ continue;
541
962
  }
963
+ if (!keep && ['scenario', 'scenario clause', 'query'].includes(item[0])) continue;
964
+ items.push([...item, file]);
965
+ }
966
+ };
967
+ for (const [text, file] of inputs) {
968
+ read.add(String(file));
969
+ load(text, file, true, 0);
970
+ }
971
+ // Templates first: a sentence can use a template declared after it.
972
+ const templates = [], byName = new Map();
973
+ const starred = items.some((item) => item[0] === 'template' && item[2].some((t) => t.text === '*'));
974
+ const declare = (tokens, error, relation = null) => {
975
+ const parts = readTemplate(tokens, error, starred);
976
+ const arity = parts.filter((p) => p.place).length;
977
+ if (relation && relation.arity !== arity) error(`a synonym needs the ${relation.arity} places of "${relation.text}"`);
978
+ const name = relation?.name ?? templateName(parts), key = `${name}/${arity}`;
979
+ if (!relation && byName.has(key)) {
980
+ const other = byName.get(key);
981
+ if (other.parts.map((p) => p.word ?? '*').join(' ') === parts.map((p) => p.word ?? '*').join(' ')) return other;
982
+ error(`the templates "${other.text}" and "${phrase(tokens)}" both name the relation ${name}/${arity}; change a word of one`);
983
+ }
984
+ const template = { parts, name, arity, words: parts.filter((p) => p.word).length, text: phrase(tokens) };
985
+ if (!relation) byName.set(key, template);
986
+ templates.push(template);
987
+ return template;
988
+ };
989
+ for (const [, , tokens, line, file] of items.filter((item) => item[0] === 'template')) {
990
+ const error = (message, at = line) => { throw new EyemindError(`${file}: line ${at}: Logical English: ${message}`); };
991
+ // A template, then its additions after ";".
992
+ const pieces = [[]];
993
+ let inside = false;
994
+ for (const t of tokens) {
995
+ if (t.text === '*') inside = !inside;
996
+ if (t.text === ';' && !inside) pieces.push([]);
997
+ else pieces.at(-1).push(t);
998
+ }
999
+ const template = declare(pieces[0], error);
1000
+ for (const addition of pieces.slice(1)) {
1001
+ const words = addition.map((t) => t.text.toLowerCase()).join(' ');
1002
+ if (IGNORED.includes(words) || isWord(addition[0] ?? {}, 'image')) continue;
1003
+ if (ASSUMABLE.includes(words)) { template.assumable = true; continue; }
1004
+ // A synonym is another wording of the same relation; an opposite is the
1005
+ // wording of a separate relation, which only its own rules conclude.
1006
+ if (isWord(addition[0] ?? {}, 'synonym')) { declare(addition.slice(1), error, template); continue; }
1007
+ if (isWord(addition[0] ?? {}, 'opposite')) { template.opposite = declare(addition.slice(addition[1]?.text === ':' ? 2 : 1), error); continue; }
1008
+ error(`the template addition "; ${phrase(addition)}" belongs to Logical English 2 and is not supported`);
542
1009
  }
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) } };
546
1010
  }
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();
1011
+ // Named constants: "the fee is 5." The name stands for the value wherever
1012
+ // no variable of the clause has that name.
1013
+ const constants = new Map();
1014
+ for (const [, , tokens, line, file] of items.filter((item) => item[0] === 'constant')) {
1015
+ const at = tokens.findLastIndex((t) => isWord(t, 'is'));
1016
+ const value = at > 0 ? new Compiler(file, []).term(tokens.slice(at + 1), new Scope()) : null;
1017
+ if (value === null || value instanceof Var) throw new EyemindError(`${file}: line ${line}: Logical English: a constant is written "the fee is 5."`);
1018
+ constants.set(tokens.slice(0, at).map((t) => t.text.toLowerCase()).join(' '), value);
1019
+ }
1020
+ const scenarios = [];
1021
+ for (const [kind, name, , line, file] of items) {
1022
+ if (kind !== 'scenario') continue;
1023
+ if (scenarios.includes(name)) throw new EyemindError(`${file}: line ${line}: Logical English: scenario ${name} is stated twice`);
1024
+ scenarios.push(name);
1025
+ }
1026
+ const threaded = scenarios.length > 0;
1027
+ const clauses = [], sources = [], queries = [], expectations = [], helpers = new Set(), pending = [], necessary = new Map();
1028
+ // Clauses wait until every one is read: their negations depend on whether
1029
+ // any fact or rule leaves a variable of its conclusion open.
1030
+ const emit = (kind, head, body, line, file, guard = null) => pending.push({ kind, head, body, line, file, guard });
1031
+ const write = ({ kind, head, body, line, file }) => {
1032
+ clauses.push(`// ${String(file).replace(/[\r\n\u2028\u2029]/g, ' ')}: line ${line}`);
1033
+ if (kind === 'fact') {
1034
+ clauses.push(`fact(${javascript(head)})`);
1035
+ sources.push(new Source('fact', head, [], line, file));
1036
+ } else if (kind === 'query') {
1037
+ clauses.push(`query(${javascript(head)})`);
1038
+ sources.push(new Source('query', 'true', [head], line, file));
1039
+ } else if (kind === 'forward') {
1040
+ clauses.push(`implies(${javascript(conjunction(body))}, ${javascript(head)})`);
1041
+ sources.push(new Source('forward', head, body, line, file));
1042
+ } else {
553
1043
  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));
1044
+ sources.push(new Source('backward', head, body.length ? body : ['true'], line, file));
555
1045
  }
1046
+ };
1047
+ for (const name of scenarios) {
1048
+ const [, , , line, file] = items.find((item) => item[0] === 'scenario' && item[1] === name);
1049
+ emit('fact', st(SCENARIO, name), [], line, file);
556
1050
  }
557
- if (dpv) {
558
- const rules = dpvRules('rdf', true);
559
- sources.push(...loadText(rules, 'DPV hierarchy rules').sources);
560
- clauses.push(rules);
1051
+ // An ontology's kinds are transitive: what is a b is a c when the ontology
1052
+ // says that b is a c. One rule per such fact keeps the dependencies of
1053
+ // rules that negate other kinds apart.
1054
+ const kinds = [];
1055
+ for (let [kind, name, tokens, line, file] of items) {
1056
+ if (kind === 'template' || kind === 'scenario' || kind === 'constant') continue;
1057
+ const compiler = new Compiler(file, templates);
1058
+ compiler.constants = constants;
1059
+ const scope = new Scope();
1060
+ if (kind === 'query') {
1061
+ compiler.scenario = threaded ? new Var('Scenario') : null;
1062
+ let body = tokens;
1063
+ // LE's "for which event:" names the thing a query asks for.
1064
+ if (startsWith(body, ['for', 'which'])) {
1065
+ const at = body.findIndex((t) => t.text === ':');
1066
+ if (at < 0) compiler.error('expected ":" after "for which ..."', line);
1067
+ compiler.term([{ text: 'which', kind: 'word' }, ...body.slice(2, at)], scope);
1068
+ body = body.slice(at + 1);
1069
+ }
1070
+ compiler.sentence = body;
1071
+ const goals = compiler.body(body, scope);
1072
+ const counter = { n: anonymize(st('true'), goals) };
1073
+ const answer = openVariables(goals).filter((v) => !/^_\d+$/.test(v.name) && v !== compiler.scenario);
1074
+ const head = st(ANSWER, name, ...(threaded ? [compiler.scenario] : []), ...answer);
1075
+ emit('backward', head, threaded ? [st(SCENARIO, compiler.scenario), ...goals] : goals, line, file, { counter, scenario: compiler.scenario });
1076
+ emit('query', head, [], line, file);
1077
+ // A quoted name is written as the name, as LE writes its answers.
1078
+ queries.push({ name, tokens: body.map((t) => t.kind === 'string' ? t.value : t.text), marks: scope.marks.map(({ at, length, variable }) => ({ at, length, slot: answer.indexOf(variable) })) });
1079
+ for (const h of compiler.helpers) helpers.add(h);
1080
+ continue;
1081
+ }
1082
+ const inScenario = kind === 'scenario clause';
1083
+ // An expected answer: "one expects answers [...] and unknowns [...]."
1084
+ const expects = tokens.findIndex((t, k) => isWord(t, 'expects') && (tokens[k + 1]?.text === '[' || (isWord(tokens[k + 1] ?? {}, 'answers') && tokens[k + 2]?.text === '[')));
1085
+ if (tokens.some((t, k) => isWord(t, 'expects') && isWord(tokens[k + 1] ?? {}, 'changes'))) {
1086
+ compiler.error('flip queries ("expects changes") belong to Logical English 2 and are not supported', line);
1087
+ }
1088
+ if (expects > 0) {
1089
+ if (!inScenario) compiler.error('an expectation belongs to a scenario', line);
1090
+ const list = (at) => {
1091
+ const close = tokens.findIndex((t, k) => k > at && t.text === ']');
1092
+ if (tokens[at]?.text !== '[' || close < 0) compiler.error('expected answers are a list of sentences, as in one expects answers ["..."]', line);
1093
+ // Each item is a quoted sentence, or its words up to a comma.
1094
+ const items = [];
1095
+ let words = [];
1096
+ for (const t of [...tokens.slice(at + 1, close), { text: ',' }]) {
1097
+ if (t.text !== ',') { words.push(t); continue; }
1098
+ if (words.length === 1 && words[0].kind === 'string') items.push(words[0].value);
1099
+ else if (words.length) items.push(phrase(words));
1100
+ words = [];
1101
+ }
1102
+ return [items, close];
1103
+ };
1104
+ const [answers, close] = list(expects + 1 + (isWord(tokens[expects + 1] ?? {}, 'answers') ? 1 : 0));
1105
+ // Expected unknowns are assumptions eyemind does not make.
1106
+ const unknowns = startsWith(tokens, ['and', 'unknowns'], close + 1) ? list(close + 3)[0]
1107
+ : startsWith(tokens, ['and', 'any', 'unknowns'], close + 1) ? ['any'] : [];
1108
+ expectations.push({ scenario: name, query: tokens.slice(0, expects).map((t) => t.text).join(' '), answers, unknowns, line });
1109
+ continue;
1110
+ }
1111
+ if (startsWith(tokens, ['it', 'is', 'unknown', 'whether']) || startsWith(tokens, ['it', 'must', 'not', 'be', 'true', 'that']) ||
1112
+ (startsWith(tokens, ['it', 'is', 'not', 'the', 'case', 'that']) && inScenario)) {
1113
+ compiler.error('unknowns, constraints and negated facts belong to Logical English 2 and are not supported', line);
1114
+ }
1115
+ compiler.scenario = !threaded ? null : inScenario ? name : new Var('Scenario');
1116
+ // A fact may carry LE2's picture, "; image ...", which changes nothing.
1117
+ const semicolon = tokens.findIndex((t) => t.text === ';');
1118
+ if (semicolon > 0 && isWord(tokens[semicolon + 1] ?? {}, 'image')) tokens = tokens.slice(0, semicolon);
1119
+ const level = depths(tokens);
1120
+ const ifAt = tokens.findIndex((t, k) => level[k] === 0 && isWord(t, 'if'));
1121
+ for (const [words, what] of [[['prolog'], 'embedded Prolog goals'], [['with', 'provenance'], 'provenance trailers'], [['is', 'published', 'at'], 'document locations']]) {
1122
+ if (indexOfWords(tokens, words) >= 0) compiler.error(`${what} belong to Logical English 2 and are not supported`, line);
1123
+ }
1124
+ if (ifAt >= 0 && tokens[ifAt + 1]?.text === ':') compiler.error('numbered conditions belong to Logical English 2 and are not supported', line);
1125
+ // "Head only if Body" makes Body necessary: the opposite of the head holds
1126
+ // when Body does not, and the head then fails.
1127
+ const onlyIf = ifAt > 0 && isWord(tokens[ifAt - 1], 'only');
1128
+ let headTokens = ifAt < 0 ? tokens : tokens.slice(0, onlyIf ? ifAt - 1 : ifAt);
1129
+ // In an ontology, "a student is a person" is about the kinds themselves.
1130
+ if (kind === 'ontology clause' && ifAt < 0 && isWord(headTokens[0], 'a', 'an') && !isWord(headTokens[1] ?? {}, 'is')) headTokens = headTokens.slice(1);
1131
+ if (!headTokens.length) compiler.error('a rule needs a conclusion before "if"', line);
1132
+ // In a fact, an id that no phrase introduces is a name, as in Q1.
1133
+ compiler.fact = ifAt < 0;
1134
+ const head = compiler.sentenceOf(headTokens, scope, { data: true });
1135
+ if (!head) {
1136
+ const builtin = compiler.sentenceOf(headTokens, new Scope());
1137
+ if (builtin?.builtin) compiler.error(`"${phrase(headTokens)}" is a built-in condition and cannot be concluded`, line);
1138
+ compiler.error(`no template matches "${phrase(headTokens)}"`, line);
1139
+ }
1140
+ const headTerm = compiler.relation(head.name, head.args);
1141
+ if (kind === 'ontology clause' && ifAt < 0 && head.name === 'is_a' && head.args.every(isGround)) kinds.push({ term: headTerm, line, file });
1142
+ if (ifAt < 0) {
1143
+ const body = compiler.scenario instanceof Var ? [st(SCENARIO, compiler.scenario)] : [];
1144
+ if (!body.length && isGround(headTerm)) emit('fact', headTerm, [], line, file);
1145
+ else emit('backward', headTerm, body, line, file);
1146
+ continue;
1147
+ }
1148
+ if (ifAt === tokens.length - 1) compiler.error('a rule needs conditions after "if"', line);
1149
+ // LE1 also writes "if" followed by a line that starts with "and".
1150
+ const goals = compiler.body(tokens.slice(ifAt + (isWord(tokens[ifAt + 1], 'and') ? 2 : 1)), scope);
1151
+ if (onlyIf) {
1152
+ const template = templates.find((t) => t.name === head.name && t.arity === head.args.length && t.opposite);
1153
+ const opposite = compiler.relation(template ? template.opposite.name : `${head.name}:not`, head.args);
1154
+ const body = [st('not', conjunction(goals))];
1155
+ const counter = { n: anonymize(opposite, body) };
1156
+ emit('backward', opposite, body, line, file, { counter, scenario: compiler.scenario, rule: true });
1157
+ necessary.set(`${head.name}/${headTerm.args.length}`, { name: head.name, opposite: opposite.name, arity: headTerm.args.length, line, file });
1158
+ for (const h of compiler.helpers) helpers.add(h);
1159
+ continue;
1160
+ }
1161
+ const counter = { n: anonymize(headTerm, goals) };
1162
+ emit('backward', headTerm, goals, line, file, { counter, scenario: compiler.scenario, rule: true });
1163
+ for (const h of compiler.helpers) helpers.add(h);
1164
+ }
1165
+ // A fact or rule may leave a variable of its conclusion open. Then no
1166
+ // earlier condition surely binds a variable, and every negation tests its
1167
+ // variables at run time.
1168
+ const open = pending.some(({ kind, head, body, guard }) => kind !== 'query' && (guard ? guard.rule : true) &&
1169
+ [...varsOf(head)].some((v) => !/^_\d+$/.test(v.name) && v.name !== 'Scenario' && !openVariables(body).includes(v)));
1170
+ // A relation with "only if" rules holds by its other rules, through a base
1171
+ // relation, unless its opposite holds.
1172
+ for (const [key, { name, opposite, arity, line, file }] of necessary) {
1173
+ const base = `${name}:if`;
1174
+ for (const clause of pending) {
1175
+ if (clause.head instanceof Struct && `${clause.head.name}/${clause.head.args.length}` === key) clause.head = new Struct(base, clause.head.args);
1176
+ }
1177
+ const args = Array.from({ length: arity }, (_, i) => new Var(i === 0 && threaded ? 'Scenario' : `A${i}`));
1178
+ emit('backward', new Struct(name, args), [new Struct(base, args), st('not', new Struct(opposite, args))], line, file,
1179
+ { counter: { n: 0 }, scenario: threaded ? args[0] : null, rule: true });
1180
+ }
1181
+ // eyemind makes no assumptions: an answer that needs one is not given, and
1182
+ // expected answers with unknowns are not compared. A negated assumable
1183
+ // sentence would hold only as an assumption, which needs abduction.
1184
+ const assumable = new Set(templates.filter((t) => t.assumable).map((t) => `${t.name}/${t.arity + (threaded ? 1 : 0)}`));
1185
+ const negates = (term, negated = false) => term instanceof Struct &&
1186
+ ((negated && assumable.has(`${term.name}/${term.args.length}`)) ||
1187
+ term.args.some((arg) => negates(arg, negated || (term.name === 'not' && term.args.length === 1))));
1188
+ for (const clause of pending) {
1189
+ if (clause.body?.some((goal) => negates(goal))) {
1190
+ throw new EyemindError(`${clause.file}: line ${clause.line}: Logical English: a negated assumable sentence holds only as an assumption, which needs abduction; abduction belongs to Logical English 2 and is not supported`);
1191
+ }
1192
+ }
1193
+ for (const { term, line, file } of kinds) {
1194
+ const S = new Var('Scenario'), X = new Var('X'), [sub, kind] = term.args.slice(-2);
1195
+ const isA = (a, b) => threaded ? st('is_a', S, a, b) : st('is_a', a, b);
1196
+ emit('backward', isA(X, kind), [isA(X, sub)], line, file, { counter: { n: 0 }, scenario: threaded ? S : null, rule: true });
1197
+ }
1198
+ forwardRecursion(pending, templates, threaded);
1199
+ for (const clause of pending) {
1200
+ if (clause.guard) {
1201
+ const { counter, scenario } = clause.guard;
1202
+ clause.body = guardNegations(clause.body, new Set(scenario instanceof Var ? [scenario] : []), counter, open);
1203
+ }
1204
+ write(clause);
1205
+ }
1206
+ // The helpers follow every stated clause.
1207
+ const used = Object.keys(HELPERS).filter((name) => helpers.has(name));
1208
+ if (used.length) {
1209
+ const text = used.map((name) => HELPERS[name]).join('\n');
1210
+ clauses.push('// Logical English helpers.', text);
1211
+ sources.push(...loadText(text, 'Logical English helpers').sources.map((s) => Object.assign(s, { line: null, file: null })));
561
1212
  }
562
1213
  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 } };
1214
+ program: new Program(sources), compiled: { templates, scenarios, threaded, queries, expectations } };
564
1215
  }
565
1216
 
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);
1217
+ // LE runs recursive rules with tabling (LE1) or a loop check (LE2), so a rule
1218
+ // that depends on itself, directly or through others, ends where Prolog's
1219
+ // search would not. LS forward rules reach the least fixpoint that tabling
1220
+ // computes. A recursive group of rules therefore becomes forward rules when
1221
+ // each of its rules binds every variable of its conclusion through the
1222
+ // relations of its conditions; a rule whose conclusion depends on how it is
1223
+ // called, such as a counter that goes down, stays backward.
1224
+ function forwardRecursion(pending, templates, threaded) {
1225
+ const keys = new Set([...templates.map((t) => `${t.name}/${t.arity + (threaded ? 1 : 0)}`), `is_a/${threaded ? 3 : 2}`]);
1226
+ const keyOf = (term) => term instanceof Struct ? `${term.name}/${term.args.length}` : null;
1227
+ const calls = (term, out = new Set()) => {
1228
+ if (term instanceof Struct) {
1229
+ if (keys.has(keyOf(term))) out.add(keyOf(term));
1230
+ else for (const arg of term.args) calls(arg, out);
1231
+ }
1232
+ return out;
1233
+ };
1234
+ const rules = pending.filter((clause) => clause.kind === 'backward' && clause.guard?.rule);
1235
+ const edges = new Map();
1236
+ for (const rule of rules) {
1237
+ const from = keyOf(rule.head);
1238
+ if (!edges.has(from)) edges.set(from, new Set());
1239
+ for (const goal of rule.body) for (const to of calls(goal)) edges.get(from).add(to);
1240
+ }
1241
+ // Tarjan's strongly connected components of the relations.
1242
+ const index = new Map(), low = new Map(), stack = [], onStack = new Set(), component = new Map();
1243
+ let counter = 0;
1244
+ const visit = (v) => {
1245
+ index.set(v, counter); low.set(v, counter++); stack.push(v); onStack.add(v);
1246
+ for (const w of edges.get(v) ?? []) {
1247
+ if (!index.has(w)) { visit(w); low.set(v, Math.min(low.get(v), low.get(w))); }
1248
+ else if (onStack.has(w)) low.set(v, Math.min(low.get(v), index.get(w)));
1249
+ }
1250
+ if (low.get(v) === index.get(v)) {
1251
+ const members = [];
1252
+ let w;
1253
+ do { w = stack.pop(); onStack.delete(w); members.push(w); } while (w !== v);
1254
+ for (const m of members) component.set(m, members);
1255
+ }
1256
+ };
1257
+ for (const v of edges.keys()) if (!index.has(v)) visit(v);
1258
+ const recursive = (key) => component.get(key)?.length > 1 || edges.get(key)?.has(key);
1259
+ const bound = (rule) => {
1260
+ const relations = new Set();
1261
+ for (const goal of rule.body) if (keys.has(keyOf(goal)) || keyOf(goal) === `${SCENARIO}/1`) varsOf(goal, relations);
1262
+ return [...varsOf(rule.head)].every((v) => /^_\d+$/.test(v.name) || relations.has(v));
1263
+ };
1264
+ for (const members of new Set(component.values())) {
1265
+ if (!recursive(members[0])) continue;
1266
+ const group = rules.filter((rule) => members.includes(keyOf(rule.head)));
1267
+ if (group.every(bound)) for (const rule of group) rule.kind = 'forward';
571
1268
  }
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
1269
  }
591
1270
 
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)}`;
1271
+ function isGround(term) {
1272
+ if (term instanceof Var) return false;
1273
+ if (term instanceof Struct) return term.args.every(isGround);
1274
+ return true;
1275
+ }
1276
+
1277
+ // Explicit constructors keep quoted names, floats and reserved JS names safe.
1278
+ function javascript(term) {
1279
+ if (term instanceof Var) return `vars(${JSON.stringify(term.name)})`;
1280
+ if (term instanceof Struct) return `struct(${JSON.stringify(term.name)}, ${term.args.map(javascript).join(', ')})`;
1281
+ if (typeof term === 'bigint') return `${term}n`;
1282
+ if (typeof term === 'number') return `float(${write(term)})`;
1283
+ return JSON.stringify(term);
1284
+ }
1285
+
1286
+ // ---------------------------------------------------------------- Answers
1287
+
1288
+ // A value as LE writes it: names as they are, dates as YYYY-MM-DD, lists in
1289
+ // brackets and a sentence through its template.
1290
+ function leValue(term, templates) {
1291
+ if (typeof term === 'string') return term === EMPTY ? '[]' : term;
1292
+ if (typeof term === 'bigint' || typeof term === 'number') return write(term);
1293
+ if (term instanceof Struct) {
1294
+ if (term.name === 'date' && term.args.length === 3 && term.args.every((a) => typeof a === 'bigint')) {
1295
+ const [y, m, d] = term.args.map(String);
1296
+ return `${y.padStart(4, '0')}-${m.padStart(2, '0')}-${d.padStart(2, '0')}`;
1297
+ }
1298
+ if (term.name === '.' && term.args.length === 2) {
1299
+ const items = [];
1300
+ let rest = term;
1301
+ while (rest instanceof Struct && rest.name === '.' && rest.args.length === 2) { items.push(rest.args[0]); rest = rest.args[1]; }
1302
+ if (rest === EMPTY) return `[${items.map((item) => leValue(item, templates)).join(', ')}]`;
1303
+ }
1304
+ const template = templates.find((t) => t.name === term.name && t.arity === term.args.length);
1305
+ if (template) {
1306
+ let n = 0;
1307
+ return template.parts.map((p) => p.place ? leValue(term.args[n++], templates) : p.text).join(' ');
607
1308
  }
608
1309
  }
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(', ')})`;
1310
+ return write(term);
614
1311
  }
615
1312
 
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 = [];
1313
+ // The answers of a query as sentences: the query's words, with each variable
1314
+ // it found a value for written as that value.
1315
+ function sentence(query, values, templates) {
1316
+ const words = [];
1317
+ for (let i = 0; i < query.tokens.length; i++) {
1318
+ const mark = query.marks.find((m) => m.at === i);
1319
+ const value = mark && mark.slot >= 0 ? values[mark.slot] : undefined;
1320
+ // An answer that leaves a variable open writes _ there, as LE does.
1321
+ if (value !== undefined) {
1322
+ words.push(value instanceof Var ? '_' : leValue(value, templates));
1323
+ i += mark.length - 1;
1324
+ } else words.push(query.tokens[i]);
1325
+ }
1326
+ return joined(words);
1327
+ }
1328
+
1329
+ // The conclusions of a run: each query's answers in each scenario, as
1330
+ // sentences, and any expected answers that differ from them.
1331
+ export function writeLe(result, loaded) {
1332
+ const { templates, scenarios, threaded, queries, expectations } = loaded.compiled;
1333
+ const found = new Map();
645
1334
  for (const answer of result.answers) {
646
1335
  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');
1336
+ if (!(term instanceof Struct) || term.name !== ANSWER) continue;
1337
+ const [name, ...rest] = term.args;
1338
+ const scenario = threaded ? rest.shift() : null;
1339
+ const query = queries.find((q) => q.name === name);
1340
+ if (!query) continue;
1341
+ const key = `${scenario}\u0000${name}`;
1342
+ if (!found.has(key)) found.set(key, []);
1343
+ const text = sentence(query, rest, templates);
1344
+ if (!found.get(key).includes(text)) found.get(key).push(text);
1345
+ }
1346
+ const blocks = [];
1347
+ for (const scenario of threaded ? scenarios : [null]) {
1348
+ for (const query of queries) {
1349
+ const answers = found.get(`${scenario}\u0000${query.name}`) ?? [];
1350
+ const title = scenario === null ? `% query ${query.name}` : `% query ${query.name} with scenario ${scenario}`;
1351
+ const lines = [title, ...(answers.length ? answers.map((a) => `${a}.`) : ['% no answers'])];
1352
+ const expected = expectations.find((e) => e.scenario === scenario && e.query === query.name && !e.unknowns.length);
1353
+ // LE2 writes the underscores of names as spaces and repeats an answer
1354
+ // for each proof; expected answers are compared as a set, either way.
1355
+ const same = (a) => a.replaceAll('_', ' ').replace(/\s*-\s*/g, '-').replace(/\s+/g, ' ').trim();
1356
+ const want = new Set(expected?.answers.map(same)), got = new Set(answers.map(same));
1357
+ if (expected && (want.size !== got.size || [...want].some((a) => !got.has(a)))) {
1358
+ lines.push(`% not as expected: ${query.name} expects answers [${expected.answers.map((a) => JSON.stringify(a)).join(', ')}]`);
1359
+ }
1360
+ blocks.push(lines.join('\n'));
1361
+ }
1362
+ }
1363
+ return blocks.length ? blocks.join('\n\n') + '\n' : '% no queries\n';
656
1364
  }