eyemind 0.9.0 → 0.9.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LE-SPEC.md +238 -24
- package/LS-SPEC.md +1 -1
- package/README.md +7 -4
- package/package.json +1 -1
- package/src/formats.js +1 -1
- package/src/le.js +1139 -84
- package/src/version.js +1 -1
package/src/le.js
CHANGED
|
@@ -27,8 +27,8 @@ const COMPARISONS = new Set(['=', '==', '!=', '\\=', '\\==', '<', '>', '<=', '=<
|
|
|
27
27
|
const FUNCTIONS = { ceiling: 'ceil', floor: 'floor', round: 'round', truncate: 'trunc', integer: 'round', abs: 'abs', sqrt: 'sqrt' };
|
|
28
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
29
|
const SECTIONS = [
|
|
30
|
-
|
|
31
|
-
'the event predicates are', 'the meta predicates are', 'the meta templates are',
|
|
30
|
+
'the fluents are', 'the events are',
|
|
31
|
+
'the event predicates are', 'the meta predicates are', 'the meta templates are',
|
|
32
32
|
];
|
|
33
33
|
|
|
34
34
|
// The helper relations of aggregates, divisions, lists and dates. Their names
|
|
@@ -52,6 +52,34 @@ implied_by(struct('le:reverse', [], R, R), 'true')
|
|
|
52
52
|
implied_by(struct('le:reverse', [H, ...T], A, R), struct('le:reverse', T, [H, ...A], R))`,
|
|
53
53
|
'le:append': `implied_by(struct('le:append', [], L, L), 'true')
|
|
54
54
|
implied_by(struct('le:append', [H, ...T], L, [H, ...R]), struct('le:append', T, L, R))`,
|
|
55
|
+
// The assumptions that the facts and rules do not settle: a proved
|
|
56
|
+
// sentence is not assumed, and a proved sentence cannot be assumed false.
|
|
57
|
+
'le:unknowns': `implied_by(struct('le:unknowns', [], []), 'true')
|
|
58
|
+
implied_by(struct('le:unknowns', [G, ...T], R), [is_ground(G), findall('x', unify(G, struct('le:not', _)), []), once(struct('le:holds', G)), struct('le:unknowns', T, R)])
|
|
59
|
+
implied_by(struct('le:unknowns', [G, ...T], [G, ...R]), [is_ground(G), findall('x', unify(G, struct('le:not', _)), []), not(struct('le:holds', G)), struct('le:unknowns', T, R)])
|
|
60
|
+
implied_by(struct('le:unknowns', [struct('le:not', S), ...T], [struct('le:not', S), ...R]), [is_ground(S), not(struct('le:holds', S)), struct('le:unknowns', T, R)])
|
|
61
|
+
implied_by(struct('le:unknowns', [G, ...T], [G, ...R]), [findall('x', is_ground(G), []), struct('le:unknowns', T, R)])`,
|
|
62
|
+
'le:coherent': `implied_by(struct('le:coherent', U), findall('x', [struct('le:member', struct('le:not', S), U), struct('le:member', S, U)], []))`,
|
|
63
|
+
// For each way, in order, a negation assumes one assumption of the way
|
|
64
|
+
// false, unless the way contradicts what is assumed already.
|
|
65
|
+
'le:negate': `implied_by(struct('le:negate', [], A, []), 'true')
|
|
66
|
+
implied_by(struct('le:negate', [W, ...Ws], A, N), [findall('x', struct('le:conflicts', W, A), [X, ..._]), struct('le:negate', Ws, A, N)])
|
|
67
|
+
implied_by(struct('le:negate', [W, ...Ws], A, [M, ...N]), [findall('x', struct('le:conflicts', W, A), []), struct('le:member', L, W), struct('le:complement', L, M), struct('le:negate', Ws, [M, ...A], N)])
|
|
68
|
+
implied_by(struct('le:conflicts', W, A), [struct('le:member', L, W), struct('le:complement', L, M), struct('le:member', M, A)])
|
|
69
|
+
implied_by(struct('le:complement', struct('le:not', S), S), 'true')
|
|
70
|
+
implied_by(struct('le:complement', S, struct('le:not', S)), findall('x', unify(S, struct('le:not', _)), []))`,
|
|
71
|
+
'le:choose': `implied_by(struct('le:choose', 0, _, []), 'true')
|
|
72
|
+
implied_by(struct('le:choose', K, [X, ...Xs], [X, ...Ys]), [gt(K, 0), is(K1, sub(K, 1)), struct('le:choose', K1, Xs, Ys)])
|
|
73
|
+
implied_by(struct('le:choose', K, [_, ...Xs], Ys), [gt(K, 0), struct('le:choose', K, Xs, Ys)])`,
|
|
74
|
+
'le:no_empty': `implied_by(struct('le:no_empty', []), 'true')
|
|
75
|
+
implied_by(struct('le:no_empty', [[X, ..._], ...T]), struct('le:no_empty', T))`,
|
|
76
|
+
'le:union': `implied_by(struct('le:union', [], []), 'true')
|
|
77
|
+
implied_by(struct('le:union', [W, ...Ws], U), [struct('le:union', Ws, U0), struct('le:append', W, U0, U)])`,
|
|
78
|
+
'le:pairs': `implied_by(struct('le:pairs', [], [], []), 'true')
|
|
79
|
+
implied_by(struct('le:pairs', [struct('le:pair', T, W), ...Ps], [T, ...Ts], [W, ...Ws]), struct('le:pairs', Ps, Ts, Ws))`,
|
|
80
|
+
// A violated constraint that one more assumption repairs is repaired.
|
|
81
|
+
'le:consistent': `implied_by(struct('le:consistent', S, U, U), findall('x', struct('le:violation', S, U, _), []))
|
|
82
|
+
implied_by(struct('le:consistent', S, U, V), [once(struct('le:violation', S, U, F)), not_unify(F, 'none'), struct('le:consistent', S, [F, ...U], V)])`,
|
|
55
83
|
'le:member': `implied_by(struct('le:member', X, [X, ..._]), 'true')
|
|
56
84
|
implied_by(struct('le:member', X, [_, ...T]), struct('le:member', X, T))`,
|
|
57
85
|
// Days since 1970-01-01 in the proleptic Gregorian calendar, and back.
|
|
@@ -79,6 +107,10 @@ const NEEDS = { 'le:average': ['le:sum', 'le:count', 'le:divide'] };
|
|
|
79
107
|
// its own, so that "the person's" meets a template's "*a person*'s".
|
|
80
108
|
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
109
|
const POSSESSIVE = /^['’]s(?![\p{L}\p{N}_])/u;
|
|
110
|
+
const DESIGNATOR = /^\d+(?:\.\d+)*\.(?=[ \t]*\p{L})/u;
|
|
111
|
+
// LE2's grouped alternatives, before ":" or a line break, and how they join
|
|
112
|
+
// the conditions below them.
|
|
113
|
+
const GROUPS = [[['at', 'least', 'one', 'of'], 'or'], [['any', 'of'], 'or'], [['either'], 'or'], [['all', 'of'], 'and']];
|
|
82
114
|
const DATE = /^(\d{4})-(\d{2})-(\d{2})(?![\p{L}\p{N}_])/u;
|
|
83
115
|
// Numbers may group thousands with commas, as in 1,000,000.
|
|
84
116
|
const NUMBER = /^(?:\d{1,3}(?:,\d{3})+|\d+)(?:\.\d+)?(?:[eE][+-]?\d+)?(?![\p{L}\p{N}_])/u;
|
|
@@ -110,6 +142,9 @@ function tokenize(text, file) {
|
|
|
110
142
|
const match = (c === '"' ? /^"(?:[^"\\\n]|\\.)*"/ : /^'(?:[^'\\\n]|\\.)*'/).exec(tail);
|
|
111
143
|
if (!match) fail('a quoted text is not closed on its line');
|
|
112
144
|
token = { text: match[0], kind: 'string', value: match[0].slice(1, -1).replace(/\\(.)/g, '$1') };
|
|
145
|
+
} else if (bol && DESIGNATOR.test(tail)) {
|
|
146
|
+
// A numbered condition starts its line with a designator such as 4.2.1.
|
|
147
|
+
token = { text: DESIGNATOR.exec(tail)[0], kind: 'designator' };
|
|
113
148
|
} else if (DATE.test(tail)) {
|
|
114
149
|
const [raw, y, m, d] = DATE.exec(tail);
|
|
115
150
|
token = { text: raw, kind: 'date', value: [BigInt(y), BigInt(m), BigInt(d)] };
|
|
@@ -173,7 +208,10 @@ function depths(tokens) {
|
|
|
173
208
|
function readTemplate(tokens, error, starred = true) {
|
|
174
209
|
const parts = [];
|
|
175
210
|
// In a document without asterisks, as LE1 also writes templates, "a" or
|
|
176
|
-
// "an" and the word after it make a place
|
|
211
|
+
// "an" and the word after it make a place, in a template that starts with
|
|
212
|
+
// one; a sentence such as "the applicant has a good credit score" keeps its
|
|
213
|
+
// words.
|
|
214
|
+
if (!isWord(tokens[0] ?? {}, 'a', 'an')) starred = true;
|
|
177
215
|
for (let i = 0; i < tokens.length; i++) {
|
|
178
216
|
const token = tokens[i];
|
|
179
217
|
if (!starred && isWord(token, 'a', 'an') && tokens[i + 1]?.kind === 'word') {
|
|
@@ -245,6 +283,11 @@ const TYPE_TEMPLATES = ['*an object* is a *type*', '*an object* is an *type*', '
|
|
|
245
283
|
parts.at(-1).type = true;
|
|
246
284
|
return { parts, name: 'is_a', arity: 2, typed: true, words: parts.filter((p) => p.word).length };
|
|
247
285
|
});
|
|
286
|
+
// LE2's admissibility of evidence: a source is admissible under itself, and
|
|
287
|
+
// under what the program's facts and rules say.
|
|
288
|
+
const ADMISSIBLE = 'is_admissible_under';
|
|
289
|
+
TYPE_TEMPLATES.push({ parts: readTemplate(tokenize('*a source* is admissible under *a scope*', 'built-in').slice(0, -1), (m) => { throw new Error(m); }),
|
|
290
|
+
name: ADMISSIBLE, arity: 2, words: 3 });
|
|
248
291
|
|
|
249
292
|
// Every way a template's words meet the tokens, as the slices of its places:
|
|
250
293
|
// each place takes at least one token, and its brackets balance.
|
|
@@ -277,6 +320,7 @@ function sameWord(token, part) {
|
|
|
277
320
|
// Alone, before any phrase introduces it, only a capital letter with
|
|
278
321
|
// possibly digits is a variable: LE1 programs use acronyms such as GST and
|
|
279
322
|
// CET as names.
|
|
323
|
+
const key = (words) => words.map((t) => t.text.toLowerCase()).join(' ').replaceAll('_', ' ');
|
|
280
324
|
const ID = /^(?:[A-Z][0-9]*|(?!UK$)[A-Z][A-Z0-9_]{1,5})$/;
|
|
281
325
|
const BARE_ID = /^[A-Z][0-9]*$/;
|
|
282
326
|
|
|
@@ -287,20 +331,30 @@ class Scope {
|
|
|
287
331
|
this.names = new Map();
|
|
288
332
|
this.used = new Set(['Scenario']);
|
|
289
333
|
this.marks = [];
|
|
334
|
+
// The goals that function calls in the condition being read need first,
|
|
335
|
+
// and the calls made so far, so that one call is asked once.
|
|
336
|
+
this.pre = [];
|
|
337
|
+
this.calls = new Map();
|
|
290
338
|
}
|
|
291
339
|
|
|
292
|
-
save() { return [new Map(this.names), new Set(this.used), this.marks.length]; }
|
|
293
|
-
restore([names, used, marks]) {
|
|
340
|
+
save() { return [new Map(this.names), new Set(this.used), this.marks.length, this.pre.length, new Map(this.calls)]; }
|
|
341
|
+
restore([names, used, marks, pre, calls]) {
|
|
342
|
+
this.names = names; this.used = used; this.marks.length = marks; this.pre.length = pre; this.calls = calls;
|
|
343
|
+
}
|
|
294
344
|
|
|
345
|
+
// A name's underscores are spaces, as LE2 reads them: the phrase
|
|
346
|
+
// "Sales Associates" refers to "a Sales_Associates".
|
|
295
347
|
find(words) {
|
|
296
|
-
return this.names.get(words
|
|
297
|
-
(words.length === 1
|
|
348
|
+
return this.names.get(key(words)) ??
|
|
349
|
+
(words.length === 1 ? this.names.get(`#${words[0].text}`) : undefined);
|
|
298
350
|
}
|
|
299
351
|
|
|
300
352
|
introduce(words) {
|
|
301
353
|
const existing = this.find(words);
|
|
302
354
|
if (existing) return existing;
|
|
303
|
-
|
|
355
|
+
// After a type, LE2 also reads a short capitalized word as the id, as in
|
|
356
|
+
// "a number MyD" or "an account Acc".
|
|
357
|
+
const id = words.length > 1 && (ID.test(words.at(-1).text) || /^[A-Z][A-Za-z0-9]{0,2}$/.test(words.at(-1).text)) ? words.at(-1).text : words.length === 1 && ID.test(words[0].text) ? words[0].text : null;
|
|
304
358
|
if (id && this.names.has(`#${id}`)) return this.names.get(`#${id}`);
|
|
305
359
|
let base = id ?? words.map((t) => t.text[0].toUpperCase() + t.text.slice(1)).join('').replace(/[^\p{L}\p{N}]/gu, '');
|
|
306
360
|
if (!/^\p{Lu}/u.test(base)) base = `V${base}`;
|
|
@@ -308,7 +362,7 @@ class Scope {
|
|
|
308
362
|
for (let n = 2; this.used.has(name); n++) name = `${base}${n}`;
|
|
309
363
|
this.used.add(name);
|
|
310
364
|
const variable = new Var(name);
|
|
311
|
-
this.names.set(words
|
|
365
|
+
this.names.set(key(words), variable);
|
|
312
366
|
if (id) this.names.set(`#${id}`, variable);
|
|
313
367
|
return variable;
|
|
314
368
|
}
|
|
@@ -348,7 +402,7 @@ class Compiler {
|
|
|
348
402
|
term(tokens, scope, { type = false } = {}) {
|
|
349
403
|
if (!tokens.length) return null;
|
|
350
404
|
const [first] = tokens;
|
|
351
|
-
if (tokens.length === 1 && first.kind === 'string') return first.value;
|
|
405
|
+
if (tokens.length === 1 && (first.kind === 'string' || first.kind === 'value')) return first.value;
|
|
352
406
|
if (tokens.length === 1 && first.kind === 'date') return st('date', ...first.value);
|
|
353
407
|
if (tokens.length === 1 && first.kind === 'number') return first.value;
|
|
354
408
|
if (tokens.length === 2 && first.text === '-' && tokens[1].kind === 'number') return -tokens[1].value;
|
|
@@ -366,7 +420,18 @@ class Compiler {
|
|
|
366
420
|
}
|
|
367
421
|
return list(items);
|
|
368
422
|
}
|
|
369
|
-
|
|
423
|
+
// LE2's explicit variable: *a name*.
|
|
424
|
+
if (first.text === '*' && tokens.at(-1).text === '*' && tokens.length > 2 && tokens.slice(1, -1).every((t) => t.kind === 'word')) {
|
|
425
|
+
const words = tokens.slice(1, -1), named = INTRODUCING.has(lower(words[0])) || isWord(words[0], 'the') ? words.slice(1) : words;
|
|
426
|
+
return this.mark(scope, scope.find(named) ?? scope.introduce(named.length ? named : words), this.offset(tokens), tokens.length);
|
|
427
|
+
}
|
|
428
|
+
if (!tokens.every((t) => t.kind === 'word' || t.kind === 'number' || t.text === '&')) {
|
|
429
|
+
return tokens.some((t) => t.kind === 'value') ? this.call(tokens, scope) : null;
|
|
430
|
+
}
|
|
431
|
+
// A lone which, what, who, when or where asks for a value.
|
|
432
|
+
if (tokens.length === 1 && isWord(first, 'which', 'what', 'who', 'when', 'where')) {
|
|
433
|
+
return this.mark(scope, scope.introduce([{ ...first, text: first.text[0].toUpperCase() + first.text.slice(1) }]), this.offset(tokens), 1);
|
|
434
|
+
}
|
|
370
435
|
const head = lower(first), rest = tokens.slice(1);
|
|
371
436
|
// A kind is a name, unless a phrase such as "which type" asks for it.
|
|
372
437
|
if (type && !(INTRODUCING.has(head) && rest.length && scope.find(rest) === undefined && rest.length <= 2)) return tokens.map((t) => t.text).join(' ');
|
|
@@ -374,13 +439,18 @@ class Compiler {
|
|
|
374
439
|
if (INTRODUCING.has(head) && !(first.text === 'A' && tokens.length === 1) && rest.length && rest.length <= 6 && rest.every((t) => t.kind === 'word' && !isWord(t, 'that', 'if'))) {
|
|
375
440
|
return this.mark(scope, scope.introduce(rest), at, tokens.length);
|
|
376
441
|
}
|
|
442
|
+
const constant = this.constants?.get(tokens.map((t) => t.text.toLowerCase()).join(' '));
|
|
377
443
|
if (head === 'the' && rest.length) {
|
|
378
444
|
const found = scope.find(rest);
|
|
379
445
|
if (found) return this.mark(scope, found, at, tokens.length);
|
|
380
|
-
|
|
446
|
+
if (constant !== undefined) return constant;
|
|
447
|
+
return this.call(tokens, scope) ?? ['the', ...rest.map((t) => t.text)].join(' ');
|
|
381
448
|
}
|
|
382
449
|
const found = scope.find(tokens);
|
|
383
450
|
if (found) return this.mark(scope, found, at, tokens.length);
|
|
451
|
+
if (constant !== undefined) return constant;
|
|
452
|
+
const called = this.call(tokens, scope);
|
|
453
|
+
if (called !== null) return called;
|
|
384
454
|
if (tokens.length === 1 && BARE_ID.test(first.text) && !this.fact) return this.mark(scope, scope.introduce(tokens), at, 1);
|
|
385
455
|
return tokens.map((t) => t.text).join(' ');
|
|
386
456
|
}
|
|
@@ -421,6 +491,20 @@ class Compiler {
|
|
|
421
491
|
at++;
|
|
422
492
|
}
|
|
423
493
|
if (at === start) return null;
|
|
494
|
+
// A function with its last argument in brackets: the double of (N + 1).
|
|
495
|
+
if (peek()?.text === '(' && this.templates.some((t) => t.function)) {
|
|
496
|
+
const words = tokens.slice(start, at), open = at;
|
|
497
|
+
at++;
|
|
498
|
+
const inner = sum();
|
|
499
|
+
if (inner !== null && peek()?.text === ')') {
|
|
500
|
+
at++;
|
|
501
|
+
const value = new Var(`V${scope.pre.length + 1}_`);
|
|
502
|
+
scope.pre.push(st('is', value, inner));
|
|
503
|
+
const call = this.call([...words, { text: '(…)', kind: 'value', value, line: words[0].line }], scope);
|
|
504
|
+
if (call !== null) return call;
|
|
505
|
+
}
|
|
506
|
+
at = open;
|
|
507
|
+
}
|
|
424
508
|
return this.term(tokens.slice(start, at), scope);
|
|
425
509
|
};
|
|
426
510
|
const factor = () => {
|
|
@@ -451,7 +535,7 @@ class Compiler {
|
|
|
451
535
|
const right = factor();
|
|
452
536
|
if (right === null) return null;
|
|
453
537
|
if (op === '/') {
|
|
454
|
-
const quotient = new Var(`Q${this.quotients = (this.quotients ?? 0) + 1}`);
|
|
538
|
+
const quotient = new Var(`Q${this.quotients = (this.quotients ?? 0) + 1}_`);
|
|
455
539
|
goals.push(this.helper('le:divide', left, right, quotient));
|
|
456
540
|
left = quotient;
|
|
457
541
|
} else left = st(op === '*' ? 'mul' : op === '//' ? 'floordiv' : 'mod', left, right);
|
|
@@ -471,6 +555,10 @@ class Compiler {
|
|
|
471
555
|
};
|
|
472
556
|
const term = sum();
|
|
473
557
|
if (term === null || at !== tokens.length) return null;
|
|
558
|
+
// Prolog stops a formula over a name with an error, which LE2 reads as
|
|
559
|
+
// no answer; such a condition fails.
|
|
560
|
+
const names = (t) => typeof t === 'string' ? !['pi', 'e', 'tau'].includes(t) : t instanceof Struct && t.name !== 'date' && t.args.some(names);
|
|
561
|
+
if (names(term)) return { term: 0n, goals: [...goals, 'fail'], formula: true };
|
|
474
562
|
return { term, goals, formula: true };
|
|
475
563
|
}
|
|
476
564
|
|
|
@@ -489,7 +577,36 @@ class Compiler {
|
|
|
489
577
|
compare(op, a, b) { return [...a.goals, ...b.goals, st(op, a.term, b.term)]; }
|
|
490
578
|
|
|
491
579
|
// One condition: a comparison, or a sentence of a template.
|
|
580
|
+
// A condition, after the goals its function calls need.
|
|
492
581
|
condition(tokens, scope) {
|
|
582
|
+
const start = scope.pre.length;
|
|
583
|
+
const goals = this.conditionOnly(tokens, scope);
|
|
584
|
+
return goals && [...scope.pre.splice(start), ...goals];
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
// A function phrase without its value, as in "the price of a cup with
|
|
588
|
+
// capacity 200 ml": a variable that a call of the function binds.
|
|
589
|
+
call(tokens, scope) {
|
|
590
|
+
const functions = this.templates.filter((t) => t.function).sort((a, b) => b.words - a.words);
|
|
591
|
+
for (const template of functions) {
|
|
592
|
+
for (const fills of matches(template.function, tokens)) {
|
|
593
|
+
const saved = scope.save();
|
|
594
|
+
const args = fills.map((fill) => this.term(fill, scope));
|
|
595
|
+
if (args.every((arg) => arg !== null)) {
|
|
596
|
+
const key = `${template.name}(${args.map((arg) => write(arg)).join(', ')})`;
|
|
597
|
+
if (scope.calls.has(key)) return scope.calls.get(key);
|
|
598
|
+
const value = new Var(`F${scope.calls.size + 1}_`);
|
|
599
|
+
scope.pre.push(this.relation(template.name, [...args, value]));
|
|
600
|
+
scope.calls.set(key, value);
|
|
601
|
+
return value;
|
|
602
|
+
}
|
|
603
|
+
scope.restore(saved);
|
|
604
|
+
}
|
|
605
|
+
}
|
|
606
|
+
return null;
|
|
607
|
+
}
|
|
608
|
+
|
|
609
|
+
conditionOnly(tokens, scope) {
|
|
493
610
|
const level = depths(tokens);
|
|
494
611
|
const at = tokens.findIndex((t, i) => level[i] === 0 && t.kind === 'punct' && COMPARISONS.has(t.text));
|
|
495
612
|
if (at > 0) {
|
|
@@ -574,6 +691,22 @@ class Compiler {
|
|
|
574
691
|
const inner = tokens.slice(i + negation, next);
|
|
575
692
|
if (!inner.length) this.error('"it is not the case that" needs a condition', t.line);
|
|
576
693
|
construct = [st('not', conjunction(this.body(inner, scope)))];
|
|
694
|
+
} else if (isWord(t, 'prolog') && i + 1 < tokens.length && !tokens[i + 1].bol) {
|
|
695
|
+
next = end(i + 1);
|
|
696
|
+
construct = this.prologGoal(tokens.slice(i + 1, next), scope);
|
|
697
|
+
} else if (this.group(tokens, i)) {
|
|
698
|
+
const [words, op] = this.group(tokens, i);
|
|
699
|
+
let from = i + words.length + (tokens[i + words.length]?.text === ':' ? 1 : 0);
|
|
700
|
+
next = end(from);
|
|
701
|
+
// Each line at the least indentation below starts one condition.
|
|
702
|
+
const inner = tokens.slice(from, next), items = [];
|
|
703
|
+
const least = Math.min(...inner.filter((u) => u.bol).map((u) => u.indent));
|
|
704
|
+
for (const u of inner) {
|
|
705
|
+
if (u.bol && u.indent === least) items.push([]);
|
|
706
|
+
items.at(-1)?.push(u);
|
|
707
|
+
}
|
|
708
|
+
if (!items.length) this.error(`"${words.join(' ')}" needs conditions on the lines below it`, t.line);
|
|
709
|
+
construct = this.join(items.map((item) => this.body(item, scope)), op);
|
|
577
710
|
} else if (startsWith(tokens, ['for', 'all', 'cases', 'in', 'which'], i)) {
|
|
578
711
|
next = end(i + 5);
|
|
579
712
|
const inner = tokens.slice(i + 5, next);
|
|
@@ -600,7 +733,28 @@ class Compiler {
|
|
|
600
733
|
if (isWord(tokens[m - 1], 'and', 'or') && (startsWith(tokens, ['it', 'is', 'not', 'the', 'case', 'that'], m) ||
|
|
601
734
|
startsWith(tokens, ['for', 'all', 'cases', 'in', 'which'], m) || aggregateAt(tokens, m) >= 0)) { cut = m - 1; break; }
|
|
602
735
|
}
|
|
603
|
-
|
|
736
|
+
// "C according to S" proves C from the evidence admissible under S.
|
|
737
|
+
// When a template's own words say "according to", the whole segment
|
|
738
|
+
// is read as conditions first.
|
|
739
|
+
const own = this.templates.some((t) => t.parts.some((p, k) => p.word === 'according' && t.parts[k + 1]?.word === 'to'));
|
|
740
|
+
let according = indexOfWords(tokens.slice(i, cut), ['according', 'to']), whole = null;
|
|
741
|
+
if (according < 0 || own) {
|
|
742
|
+
const saved = scope.save();
|
|
743
|
+
whole = this.split(tokens.slice(i, cut), scope);
|
|
744
|
+
if (whole) according = -1;
|
|
745
|
+
else scope.restore(saved);
|
|
746
|
+
}
|
|
747
|
+
if (according > 0) {
|
|
748
|
+
const scopeTerm = this.term(tokens.slice(i + according + 2, cut), scope);
|
|
749
|
+
if (scopeTerm === null) this.error(`"according to" needs a source, not "${phrase(tokens.slice(i + according + 2, cut))}"`, t.line);
|
|
750
|
+
const inner = this.split(tokens.slice(i, i + according), scope);
|
|
751
|
+
if (!inner) this.error(`no template matches "${phrase(tokens.slice(i, i + according))}"`, t.line);
|
|
752
|
+
entries.push({ op, indent, goals: [st('le:according', conjunction(this.combine(inner)), scopeTerm)] });
|
|
753
|
+
i = cut;
|
|
754
|
+
if (i < tokens.length) { op = lower(tokens[i]); indent = tokens[i].indent; i++; }
|
|
755
|
+
continue;
|
|
756
|
+
}
|
|
757
|
+
const pieces = whole ?? this.split(tokens.slice(i, cut), scope);
|
|
604
758
|
if (!pieces) this.error(`no template matches "${phrase(tokens.slice(i, cut))}"`, t.line);
|
|
605
759
|
pieces[0].op = op; pieces[0].indent = indent;
|
|
606
760
|
entries.push(...pieces);
|
|
@@ -617,6 +771,157 @@ class Compiler {
|
|
|
617
771
|
return entries;
|
|
618
772
|
}
|
|
619
773
|
|
|
774
|
+
// An embedded Prolog goal, as LE2 writes one after "prolog": conjunctions
|
|
775
|
+
// with ",", disjunctions with ";", "\\+" for negation and Module:Goal, over
|
|
776
|
+
// LE2's system predicates, a few Prolog tests and the relations of Prolog
|
|
777
|
+
// resources. An argument may be an LE phrase such as "the person".
|
|
778
|
+
prologGoal(tokens, scope) {
|
|
779
|
+
const fail = (message) => this.error(message, tokens[0]?.line ?? 0);
|
|
780
|
+
const level = depths(tokens);
|
|
781
|
+
const split = (sep) => {
|
|
782
|
+
const parts = [];
|
|
783
|
+
let start = 0;
|
|
784
|
+
for (let k = 0; k <= tokens.length; k++) {
|
|
785
|
+
if (k < tokens.length && !(tokens[k].text === sep && level[k] === 0)) continue;
|
|
786
|
+
parts.push(tokens.slice(start, k));
|
|
787
|
+
start = k + 1;
|
|
788
|
+
}
|
|
789
|
+
return parts;
|
|
790
|
+
};
|
|
791
|
+
if (!tokens.length) fail('a prolog goal is missing');
|
|
792
|
+
const alternatives = split(';');
|
|
793
|
+
if (alternatives.length > 1) return [alternatives.map((part) => conjunction(this.prologGoal(part, scope))).reduce((a, b) => st('or', a, b))];
|
|
794
|
+
const parts = split(',');
|
|
795
|
+
if (parts.length > 1) return parts.flatMap((part) => this.prologGoal(part, scope));
|
|
796
|
+
if (tokens[0].text === '(' && tokens.at(-1).text === ')' && balanced(tokens.slice(1, -1))) return this.prologGoal(tokens.slice(1, -1), scope);
|
|
797
|
+
if (tokens[0].text === '\\' && tokens[1]?.text === '+') return [st('not', conjunction(this.prologGoal(tokens.slice(2), scope)))];
|
|
798
|
+
const colon = tokens.findIndex((t, k) => level[k] === 0 && t.text === ':' && tokens[k + 1]?.text !== '-');
|
|
799
|
+
if (colon > 0) return this.prologGoal(tokens.slice(colon + 1), scope);
|
|
800
|
+
const tests = { '=': 'unify', '\\=': 'not_unify', '==': 'identical', '\\==': 'not_identical', '<': 'lt', '>': 'gt', '=<': 'le', '>=': 'ge' };
|
|
801
|
+
const op = tokens.findIndex((t, k) => level[k] === 0 && t.kind === 'punct' && tests[t.text]);
|
|
802
|
+
if (op > 0) return [st(tests[tokens[op].text], this.prologArg(tokens.slice(0, op), scope), this.prologArg(tokens.slice(op + 1), scope))];
|
|
803
|
+
const goal = this.prologArg(tokens, scope, true);
|
|
804
|
+
const [name, args] = goal instanceof Struct ? [goal.name, goal.args] : [goal, []];
|
|
805
|
+
const system = {
|
|
806
|
+
'le_my_kb/1': () => this.kb === null ? 'fail' : st('unify', args[0], this.kb),
|
|
807
|
+
'le_kb/1': () => this.kb === null ? 'fail' : st('unify', args[0], this.kb),
|
|
808
|
+
'le_my_id/1': () => this.label === null ? 'fail' : st('unify', args[0], this.label),
|
|
809
|
+
'atom/1': () => st('is_atom', args[0]), 'number/1': () => st('is_number', args[0]), 'integer/1': () => st('is_int', args[0]),
|
|
810
|
+
'var/1': () => st('is_var', args[0]), 'nonvar/1': () => st('is_nonvar', args[0]), 'true/0': () => 'true', 'fail/0': () => 'fail',
|
|
811
|
+
}[`${name}/${args.length}`];
|
|
812
|
+
if (system) return [system()];
|
|
813
|
+
if (typeof name !== 'string' || RESERVED.has(name)) fail(`the Prolog goal "${phrase(tokens)}" is not supported`);
|
|
814
|
+
return [goal];
|
|
815
|
+
}
|
|
816
|
+
|
|
817
|
+
// A Prolog argument: a variable, atom, number, list or compound, or an LE
|
|
818
|
+
// phrase. An LE definite phrase that refers to no variable starts one.
|
|
819
|
+
prologArg(tokens, scope, callable = false) {
|
|
820
|
+
const fail = () => this.error(`"${phrase(tokens)}" is not a Prolog term`, tokens[0]?.line ?? 0);
|
|
821
|
+
if (!tokens.length) fail();
|
|
822
|
+
const [first] = tokens;
|
|
823
|
+
if (tokens.length === 1 && first.kind === 'word') {
|
|
824
|
+
if (/^[A-Z_]/.test(first.text)) return first.text === '_' ? new Var('_') : this.mark(scope, scope.find([first]) ?? scope.introduce([first]), this.offset(tokens), 1);
|
|
825
|
+
return first.text;
|
|
826
|
+
}
|
|
827
|
+
if (first.kind === 'word' && tokens[1]?.text === '(' && tokens.at(-1).text === ')' && balanced(tokens.slice(2, -1))) {
|
|
828
|
+
const inner = tokens.slice(2, -1), level = depths(inner), args = [];
|
|
829
|
+
let start = 0;
|
|
830
|
+
for (let k = 0; k <= inner.length; k++) {
|
|
831
|
+
if (k < inner.length && !(inner[k].text === ',' && level[k] === 0)) continue;
|
|
832
|
+
args.push(this.prologArg(inner.slice(start, k), scope));
|
|
833
|
+
start = k + 1;
|
|
834
|
+
}
|
|
835
|
+
return new Struct(first.text, args);
|
|
836
|
+
}
|
|
837
|
+
if (callable) fail();
|
|
838
|
+
if (first.text === '[' && tokens.at(-1).text === ']') {
|
|
839
|
+
const inner = tokens.slice(1, -1), level = depths(inner);
|
|
840
|
+
const bar = inner.findIndex((t, k) => t.text === '|' && level[k] === 0);
|
|
841
|
+
const items = [], body = bar < 0 ? inner : inner.slice(0, bar);
|
|
842
|
+
const bodyLevel = depths(body);
|
|
843
|
+
let start = 0;
|
|
844
|
+
for (let k = 0; k <= body.length && body.length; k++) {
|
|
845
|
+
if (k < body.length && !(body[k].text === ',' && bodyLevel[k] === 0)) continue;
|
|
846
|
+
items.push(this.prologArg(body.slice(start, k), scope));
|
|
847
|
+
start = k + 1;
|
|
848
|
+
}
|
|
849
|
+
const tail = bar < 0 ? EMPTY : this.prologArg(inner.slice(bar + 1), scope);
|
|
850
|
+
return items.reduceRight((t, h) => st('.', h, t), tail);
|
|
851
|
+
}
|
|
852
|
+
const term = this.term(tokens, scope);
|
|
853
|
+
if (term === null) fail();
|
|
854
|
+
if (typeof term === 'string' && isWord(first, 'the') && tokens.length > 1) return this.mark(scope, scope.introduce(tokens.slice(1)), this.offset(tokens), tokens.length);
|
|
855
|
+
return term;
|
|
856
|
+
}
|
|
857
|
+
|
|
858
|
+
// A grouped alternative at i: its words and how it joins its conditions.
|
|
859
|
+
group(tokens, i) {
|
|
860
|
+
for (const [words, op] of GROUPS) {
|
|
861
|
+
const after = tokens[i + words.length];
|
|
862
|
+
if (startsWith(tokens, words, i) && after && (after.text === ':' || after.bol)) return [words, op];
|
|
863
|
+
}
|
|
864
|
+
return null;
|
|
865
|
+
}
|
|
866
|
+
|
|
867
|
+
// Conditions joined by one connective.
|
|
868
|
+
join(parts, op) {
|
|
869
|
+
if (op === 'and') return parts.flat();
|
|
870
|
+
return [parts.map((goals) => conjunction(goals)).reduce((a, b) => st('or', a, b))];
|
|
871
|
+
}
|
|
872
|
+
|
|
873
|
+
// LE2's numbered body: items such as "4.2.1. the A is connected to an E;
|
|
874
|
+
// and". An item's connective joins it to the next item of its level; an item
|
|
875
|
+
// "either:", "all of:" or "it is not the case that:" groups the items
|
|
876
|
+
// numbered below it.
|
|
877
|
+
numbered(tokens, scope) {
|
|
878
|
+
const items = [];
|
|
879
|
+
for (const t of tokens) {
|
|
880
|
+
if (t.kind === 'designator') {
|
|
881
|
+
items.push({ depth: t.text.split('.').length - 1, tokens: [], line: t.line });
|
|
882
|
+
this.designators?.push(t.text.slice(0, -1));
|
|
883
|
+
}
|
|
884
|
+
else if (items.length) items.at(-1).tokens.push(t);
|
|
885
|
+
else this.error('a numbered condition starts with its number, such as 1.', t.line);
|
|
886
|
+
}
|
|
887
|
+
for (const item of items) {
|
|
888
|
+
let words = item.tokens;
|
|
889
|
+
if (isWord(words.at(-1) ?? {}, 'and', 'or')) { item.op = lower(words.at(-1)); words = words.slice(0, -1); }
|
|
890
|
+
if (words.at(-1)?.text === ';') words = words.slice(0, -1);
|
|
891
|
+
if (words.at(-1)?.text === ':') { item.opens = true; words = words.slice(0, -1); }
|
|
892
|
+
item.words = words;
|
|
893
|
+
}
|
|
894
|
+
const level = (from, depth) => {
|
|
895
|
+
const parts = [];
|
|
896
|
+
let i = from;
|
|
897
|
+
while (i < items.length && items[i].depth >= depth) {
|
|
898
|
+
const item = items[i];
|
|
899
|
+
let j = i + 1;
|
|
900
|
+
while (j < items.length && items[j].depth > item.depth) j++;
|
|
901
|
+
let goals;
|
|
902
|
+
const group = item.opens ? this.group([...item.words, { text: ':' }], 0) : null;
|
|
903
|
+
if (group && group[0].length === item.words.length) goals = this.join(level(i + 1, item.depth + 1).map((p) => p.goals), group[1]);
|
|
904
|
+
else if (item.opens && startsWith(item.words, ['it', 'is', 'not', 'the', 'case', 'that']) && item.words.length === 6) {
|
|
905
|
+
goals = [st('not', conjunction(this.join(level(i + 1, item.depth + 1).map((p) => p.goals), 'and')))];
|
|
906
|
+
} else {
|
|
907
|
+
if (j > i + 1) this.error(`the numbered condition "${phrase(item.words)}" has conditions below it; end it with "either:", "all of:" or "it is not the case that:"`, item.line);
|
|
908
|
+
if (!item.words.length) this.error('a numbered condition is missing', item.line);
|
|
909
|
+
goals = this.body(item.words, scope);
|
|
910
|
+
}
|
|
911
|
+
parts.push({ goals, op: item.op });
|
|
912
|
+
i = j;
|
|
913
|
+
}
|
|
914
|
+
return parts;
|
|
915
|
+
};
|
|
916
|
+
const parts = level(0, items[0]?.depth ?? 1);
|
|
917
|
+
if (!parts.length) this.error('a numbered body needs numbered conditions', tokens[0]?.line ?? 0);
|
|
918
|
+
let goals = parts[0].goals;
|
|
919
|
+
for (let k = 1; k < parts.length; k++) {
|
|
920
|
+
goals = (parts[k - 1].op ?? 'and') === 'or' ? [st('or', conjunction(goals), conjunction(parts[k].goals))] : [...goals, ...parts[k].goals];
|
|
921
|
+
}
|
|
922
|
+
return goals;
|
|
923
|
+
}
|
|
924
|
+
|
|
620
925
|
// An aggregate at i: "R is the sum of each V such that" or LE's
|
|
621
926
|
// "R is a collection of V where", followed by its conditions.
|
|
622
927
|
aggregate(tokens, i, scope, end) {
|
|
@@ -646,8 +951,11 @@ class Compiler {
|
|
|
646
951
|
if (template === null) this.error(`an aggregate collects a variable, not "${phrase(each)}"`, line);
|
|
647
952
|
if (!conditions.length) this.error('an aggregate needs conditions after "such that"', line);
|
|
648
953
|
const goals = this.body(conditions, scope);
|
|
649
|
-
const items = new Var(`L${this.lists = (this.lists ?? 0) + 1}`);
|
|
650
|
-
|
|
954
|
+
const items = new Var(`L${this.lists = (this.lists ?? 0) + 1}_`);
|
|
955
|
+
// A sum, count, average, minimum or maximum does not depend on the order
|
|
956
|
+
// of its values, so it collects them sorted, which a proof can certify
|
|
957
|
+
// even when they rest on derived facts; a list keeps the order found.
|
|
958
|
+
const found = st(AGGREGATES[op] === null ? 'findall' : 'findall_sorted', template, conjunction(goals), items);
|
|
651
959
|
return AGGREGATES[op] === null ? [found, st('unify', total, items)] : [found, this.helper(AGGREGATES[op], items, total)];
|
|
652
960
|
}
|
|
653
961
|
|
|
@@ -759,7 +1067,7 @@ function guardNegations(goals, bound, counter, open = false) {
|
|
|
759
1067
|
}
|
|
760
1068
|
out.push(goal);
|
|
761
1069
|
if (open) continue;
|
|
762
|
-
if (goal instanceof Struct && goal.name === 'findall' && goal.args.length === 3) varsOf(goal.args[2], bound);
|
|
1070
|
+
if (goal instanceof Struct && (goal.name === 'findall' || goal.name === 'findall_sorted') && goal.args.length === 3) varsOf(goal.args[2], bound);
|
|
763
1071
|
else varsOf(goal, bound);
|
|
764
1072
|
}
|
|
765
1073
|
return out;
|
|
@@ -779,9 +1087,9 @@ function openVariables(goals) {
|
|
|
779
1087
|
const out = [];
|
|
780
1088
|
const visit = (term) => {
|
|
781
1089
|
if (term instanceof Var) { if (!out.includes(term)) out.push(term); }
|
|
782
|
-
else if (term instanceof Struct && !(term.name === 'not' && term.args.length === 1) && !(term.name === 'findall' && term.args.length === 3)) {
|
|
1090
|
+
else if (term instanceof Struct && !(term.name === 'not' && term.args.length === 1) && !((term.name === 'findall' || term.name === 'findall_sorted') && term.args.length === 3)) {
|
|
783
1091
|
for (const arg of term.args) visit(arg);
|
|
784
|
-
} else if (term instanceof Struct && term.name === 'findall') visit(term.args[2]);
|
|
1092
|
+
} else if (term instanceof Struct && (term.name === 'findall' || term.name === 'findall_sorted')) visit(term.args[2]);
|
|
785
1093
|
};
|
|
786
1094
|
for (const goal of goals) visit(goal);
|
|
787
1095
|
return out;
|
|
@@ -790,10 +1098,16 @@ function openVariables(goals) {
|
|
|
790
1098
|
// ---------------------------------------------------------------- Documents
|
|
791
1099
|
|
|
792
1100
|
// The sections of one document as sentences: [kind, name, tokens, line].
|
|
1101
|
+
// A source or document named in a trailer: its words, or a quoted text.
|
|
1102
|
+
function sourceTerm(words) {
|
|
1103
|
+
if (words.length === 1 && words[0].kind === 'string') return words[0].value;
|
|
1104
|
+
return words.map((t) => t.text).join(' ');
|
|
1105
|
+
}
|
|
1106
|
+
|
|
793
1107
|
function sections(tokens, file) {
|
|
794
1108
|
const error = (message, line) => { throw new EyemindError(`${file}: line ${line}: Logical English: ${message}`); };
|
|
795
1109
|
const out = [];
|
|
796
|
-
let i = 0, section = null;
|
|
1110
|
+
let i = 0, section = null, label = null, part = 'main';
|
|
797
1111
|
const colon = (from) => {
|
|
798
1112
|
for (let k = from; k < tokens.length && tokens[k].kind !== 'stop' && tokens[k].kind !== 'end'; k++) if (tokens[k].text === ':') return k;
|
|
799
1113
|
return -1;
|
|
@@ -805,9 +1119,9 @@ function sections(tokens, file) {
|
|
|
805
1119
|
i++;
|
|
806
1120
|
continue;
|
|
807
1121
|
}
|
|
808
|
-
if (startsWith(tokens, ['the', 'templates', 'are'], i) || startsWith(tokens, ['the', 'predicates', 'are'], i)) {
|
|
809
|
-
if (tokens[i + 3]?.text !== ':') error(
|
|
810
|
-
section = { kind: 'templates' };
|
|
1122
|
+
if (startsWith(tokens, ['the', 'templates', 'are'], i) || startsWith(tokens, ['the', 'predicates', 'are'], i) || startsWith(tokens, ['the', 'functions', 'are'], i)) {
|
|
1123
|
+
if (tokens[i + 3]?.text !== ':') error(`expected ":" after "the ${lower(tokens[i + 1])} are"`, line);
|
|
1124
|
+
section = { kind: 'templates', functions: isWord(tokens[i + 1], 'functions') };
|
|
811
1125
|
i += 4;
|
|
812
1126
|
continue;
|
|
813
1127
|
}
|
|
@@ -825,34 +1139,81 @@ function sections(tokens, file) {
|
|
|
825
1139
|
}
|
|
826
1140
|
if (startsWith(tokens, ['the', 'knowledge', 'base'], i)) {
|
|
827
1141
|
const at = colon(i);
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
1142
|
+
// "includes these resources:" or "includes these scenarios:" names other
|
|
1143
|
+
// files, separated by commas, up to a full stop.
|
|
1144
|
+
if (at > 0 && startsWith(tokens, ['includes', 'these'], at - 3) && isWord(tokens[at - 1], 'resources', 'scenarios')) {
|
|
1145
|
+
let end = at + 1;
|
|
1146
|
+
while (tokens[end].kind !== 'stop' && tokens[end].kind !== 'end') end++;
|
|
1147
|
+
const names = [];
|
|
1148
|
+
let name = [];
|
|
1149
|
+
for (const t of [...tokens.slice(at + 1, end), { text: ',' }]) {
|
|
1150
|
+
if (t.text !== ',') { name.push(t.text); continue; }
|
|
1151
|
+
if (name.length) names.push(name.join(''));
|
|
1152
|
+
name = [];
|
|
1153
|
+
}
|
|
1154
|
+
out.push(['include', lower(tokens[at - 1]), names, line]);
|
|
1155
|
+
i = end + 1;
|
|
1156
|
+
continue;
|
|
832
1157
|
}
|
|
1158
|
+
const includes = at > 0 && isWord(tokens[at - 1], 'includes');
|
|
1159
|
+
if (!includes) error('expected "the knowledge base NAME includes:"', line);
|
|
833
1160
|
section = { kind: 'kb', name: tokens.slice(i + 3, at - 1).map((t) => t.text).join(' ') };
|
|
834
1161
|
i = at + 1;
|
|
835
1162
|
continue;
|
|
836
1163
|
}
|
|
837
1164
|
if (isWord(tokens[i], 'scenario', 'query') && tokens[i].bol) {
|
|
838
1165
|
const at = colon(i);
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
1166
|
+
// LE2's "scenario NAME is, as stated in DOCUMENT:" names the default
|
|
1167
|
+
// document of the scenario's facts.
|
|
1168
|
+
const stated = indexOfWords(tokens.slice(i, at), [',', 'as', 'stated', 'in'].map((w) => w));
|
|
1169
|
+
const isAt = stated > 0 ? i + stated - 1 : at - 1;
|
|
1170
|
+
if (at > i + 2 && isWord(tokens[isAt], 'is') && (stated < 0 || tokens[i + stated]?.text === ',')) {
|
|
1171
|
+
const name = tokens.slice(i + 1, isAt).map((t) => t.text).join(' ');
|
|
1172
|
+
const document = stated > 0 ? sourceTerm(tokens.slice(i + stated + 4, at)) : null;
|
|
1173
|
+
section = { kind: lower(tokens[i]), name, line, document };
|
|
842
1174
|
if (section.kind === 'scenario') out.push(['scenario', name, [], line]);
|
|
843
1175
|
i = at + 1;
|
|
844
1176
|
continue;
|
|
845
1177
|
}
|
|
846
1178
|
if (at > 0) error(`the header "${phrase(tokens.slice(i, at + 1))}" belongs to Logical English 2 and is not supported`, line);
|
|
847
1179
|
}
|
|
848
|
-
// LE2 labels a rule with "rule NAME:"
|
|
849
|
-
|
|
850
|
-
|
|
1180
|
+
// LE2 labels a rule with "rule NAME:", and marks sections of rules with
|
|
1181
|
+
// "section NAME is:" or "the annexes to the contract are:". Neither
|
|
1182
|
+
// changes what the rules mean.
|
|
1183
|
+
// A label may give the rule's provenance, "rule NAME with provenance
|
|
1184
|
+
// DOCUMENT, confer ...:", which changes nothing in the proof.
|
|
1185
|
+
const provenance = isWord(tokens[i], 'rule') ? indexOfWords(tokens.slice(i, Math.max(colon(i), i)), ['with', 'provenance']) : -1;
|
|
1186
|
+
const labelEnd = provenance > 1 ? i + provenance : colon(i);
|
|
1187
|
+
if (isWord(tokens[i], 'rule') && colon(i) > i + 1 && labelEnd < i + 5 && tokens.slice(i + 1, labelEnd).every((t) => t.kind === 'word' || t.kind === 'number')) {
|
|
1188
|
+
label = tokens.slice(i + 1, labelEnd).map((t) => t.text).join(' ');
|
|
1189
|
+
i = colon(i) + 1;
|
|
1190
|
+
continue;
|
|
851
1191
|
}
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
1192
|
+
// A facts background helps an assistant read facts from a text; the
|
|
1193
|
+
// answers are the same without it.
|
|
1194
|
+
if (startsWith(tokens, ['the', 'facts', 'background', 'includes', 'these', 'resources', ':'], i)) {
|
|
1195
|
+
while (tokens[i].kind !== 'stop' && tokens[i].kind !== 'end') i++;
|
|
1196
|
+
i++;
|
|
1197
|
+
continue;
|
|
1198
|
+
}
|
|
1199
|
+
if (isWord(tokens[i], 'section') && tokens[i].bol && colon(i) > 0 && isWord(tokens[colon(i) - 1], 'is')) {
|
|
1200
|
+
part = tokens.slice(i + 1, colon(i) - 1).map((t) => t.text).join(' ');
|
|
1201
|
+
i = colon(i) + 1;
|
|
1202
|
+
continue;
|
|
1203
|
+
}
|
|
1204
|
+
if (startsWith(tokens, ['the', 'annexes', 'to', 'the'], i) && colon(i) > 0 && isWord(tokens[colon(i) - 1], 'are')) {
|
|
1205
|
+
part = 'annexes';
|
|
1206
|
+
i = colon(i) + 1;
|
|
1207
|
+
continue;
|
|
855
1208
|
}
|
|
1209
|
+
// LE2's named constants: "the fee is 5."
|
|
1210
|
+
if (startsWith(tokens, ['the', 'constants', 'are', ':'], i)) {
|
|
1211
|
+
section = { kind: 'constants' };
|
|
1212
|
+
i += 4;
|
|
1213
|
+
continue;
|
|
1214
|
+
}
|
|
1215
|
+
const unsupported = SECTIONS.find((words) => startsWith(tokens, words.split(' '), i));
|
|
1216
|
+
if (unsupported) error(`the section "${unsupported}" belongs to Logical English 2 and is not supported`, line);
|
|
856
1217
|
let end = i;
|
|
857
1218
|
while (tokens[end].kind !== 'stop' && tokens[end].kind !== 'end') end++;
|
|
858
1219
|
if (tokens[end].kind === 'end') error(`a sentence must end with a full stop: "${phrase(tokens.slice(i, Math.min(end, i + 12)))}"`, line);
|
|
@@ -876,40 +1237,162 @@ function sections(tokens, file) {
|
|
|
876
1237
|
}
|
|
877
1238
|
start = k + 1;
|
|
878
1239
|
}
|
|
879
|
-
for (const part of parts) out.push(['template', null, part, part[0].line]);
|
|
1240
|
+
for (const part of parts) out.push(['template', section.functions ? 'function' : null, part, part[0].line]);
|
|
1241
|
+
} else if (section.kind === 'constants') {
|
|
1242
|
+
out.push(['constant', null, sentence, line]);
|
|
880
1243
|
} else if (section.kind === 'query') {
|
|
881
1244
|
out.push(['query', section.name, sentence, line]);
|
|
882
1245
|
section = { kind: 'after query' };
|
|
883
1246
|
} else if (section.kind === 'after query') {
|
|
884
1247
|
error('a query has one sentence; start a new section after it', line);
|
|
885
1248
|
} else {
|
|
886
|
-
|
|
1249
|
+
// The location of a document changes nothing in the proof.
|
|
1250
|
+
const quoted = sentence.at(-1)?.kind === 'string';
|
|
1251
|
+
if (quoted && (startsWith(sentence, ['is', 'published', 'at'], sentence.length - 4) ||
|
|
1252
|
+
(startsWith(sentence, ['the', 'text', 'of']) && startsWith(sentence, ['is', 'at'], sentence.length - 3)))) {
|
|
1253
|
+
i = end + 1;
|
|
1254
|
+
continue;
|
|
1255
|
+
}
|
|
1256
|
+
// A fact's trailers, ", according to SOURCE", ", as stated in DOCUMENT
|
|
1257
|
+
// at LOCATOR", ", because ..." and ", confer ...", keep its source.
|
|
1258
|
+
let fact = sentence, source = section.document ?? null;
|
|
1259
|
+
const level = depths(sentence), trailer = (k) => sentence[k]?.text === ',' && level[k] === 0 &&
|
|
1260
|
+
(startsWith(sentence, ['according', 'to'], k + 1) || startsWith(sentence, ['as', 'stated', 'in'], k + 1) || isWord(sentence[k + 1] ?? {}, 'because', 'confer'));
|
|
1261
|
+
const first = sentence.findIndex((t, k) => trailer(k));
|
|
1262
|
+
if (first > 0 && !sentence.slice(0, first).some((t, k) => level[k] === 0 && isWord(t, 'if'))) {
|
|
1263
|
+
fact = sentence.slice(0, first);
|
|
1264
|
+
let according = null, document = null;
|
|
1265
|
+
for (let k = first; k < sentence.length; k++) {
|
|
1266
|
+
if (!trailer(k)) continue;
|
|
1267
|
+
let stop = k + 1;
|
|
1268
|
+
while (stop < sentence.length && !trailer(stop)) stop++;
|
|
1269
|
+
const words = sentence.slice(k + 1, stop);
|
|
1270
|
+
if (startsWith(words, ['according', 'to'])) according = sourceTerm(words.slice(2));
|
|
1271
|
+
if (startsWith(words, ['as', 'stated', 'in'])) {
|
|
1272
|
+
const at = words.findIndex((t, m) => m > 3 && isWord(t, 'at'));
|
|
1273
|
+
document = sourceTerm(words.slice(3, at > 0 ? at : words.length));
|
|
1274
|
+
}
|
|
1275
|
+
}
|
|
1276
|
+
source = according ?? document ?? source;
|
|
1277
|
+
}
|
|
1278
|
+
// A rule's label and section, which LE2's system predicates report.
|
|
1279
|
+
Object.assign(fact, { label, part, source });
|
|
1280
|
+
const sentence_ = fact;
|
|
1281
|
+
label = null;
|
|
1282
|
+
out.push([{ kb: 'clause', ontology: 'ontology clause' }[section.kind] ?? 'scenario clause', section.name ?? null, sentence_, line]);
|
|
887
1283
|
}
|
|
888
1284
|
i = end + 1;
|
|
889
1285
|
}
|
|
890
1286
|
return out;
|
|
891
1287
|
}
|
|
892
1288
|
|
|
893
|
-
|
|
894
|
-
|
|
1289
|
+
// The ways LE2 lets a template be read, after ";": additions that change
|
|
1290
|
+
// nothing eyemind computes, and additions that make a sentence assumable.
|
|
1291
|
+
const IGNORED = ['memorable', 'memoised', 'memoized', 'cached', 'undefined', 'scenario element', 'one value', 'single valued'];
|
|
1292
|
+
const ASSUMABLE = ['assumable', 'unknown', 'assumed', 'judged', 'open textured', 'evaluative'];
|
|
1293
|
+
|
|
1294
|
+
// io.readFile reads an included file. The paths of an included file's own
|
|
1295
|
+
// includes are relative to it; a chain of includes stops at five.
|
|
1296
|
+
export function compileLe(inputs, io = null) {
|
|
1297
|
+
const items = [], read = new Set();
|
|
1298
|
+
const load = (text, file, keep, depth) => {
|
|
1299
|
+
for (const item of sections(tokenize(String(text), file), file)) {
|
|
1300
|
+
if (item[0] === 'include') {
|
|
1301
|
+
const [, kind, names, line] = item;
|
|
1302
|
+
const fail = (message) => { throw new EyemindError(`${file}: line ${line}: Logical English: ${message}`); };
|
|
1303
|
+
for (const name of names) {
|
|
1304
|
+
// A web address is read with io.readDocument; a path, relative to
|
|
1305
|
+
// the including file or web address, with io.readFile.
|
|
1306
|
+
const web = /^https?:/i.test(name), base = String(file);
|
|
1307
|
+
if (/^[a-z]+:/i.test(name) && !web) fail(`cannot include ${name}; include a file or an HTTP(S) address`);
|
|
1308
|
+
const dir = web ? '' : base.includes('/') ? base.slice(0, base.lastIndexOf('/') + 1) : '';
|
|
1309
|
+
const path = dir + name + (/\.(le|pl)$/.test(name) ? '' : '.le');
|
|
1310
|
+
if (read.has(path)) continue;
|
|
1311
|
+
if (depth >= 5) fail(`including ${name} makes a chain of more than five includes`);
|
|
1312
|
+
const reader = /^https?:/i.test(path) ? io?.readDocument : io?.readFile;
|
|
1313
|
+
if (!reader) fail(`including ${name} needs ${/^https?:/i.test(path) ? 'network' : 'file'} access`);
|
|
1314
|
+
let included;
|
|
1315
|
+
try { included = reader(path); } catch (error) { fail(`cannot read the included ${path}: ${error.message}`); }
|
|
1316
|
+
read.add(path);
|
|
1317
|
+
// A Prolog resource gives its facts and rules.
|
|
1318
|
+
if (path.endsWith('.pl')) {
|
|
1319
|
+
const tokens = tokenize(included, path);
|
|
1320
|
+
for (let start = 0, k = 0; k < tokens.length; k++) {
|
|
1321
|
+
if (tokens[k].kind !== 'stop' && tokens[k].kind !== 'end') continue;
|
|
1322
|
+
if (k > start) items.push(['prolog', null, tokens.slice(start, k), tokens[start].line, path]);
|
|
1323
|
+
start = k + 1;
|
|
1324
|
+
}
|
|
1325
|
+
continue;
|
|
1326
|
+
}
|
|
1327
|
+
// A resource gives its templates, rules, facts and ontology; an
|
|
1328
|
+
// included scenario file also gives its scenarios and queries.
|
|
1329
|
+
load(included, path, kind === 'scenarios', depth + 1);
|
|
1330
|
+
}
|
|
1331
|
+
continue;
|
|
1332
|
+
}
|
|
1333
|
+
if (!keep && ['scenario', 'scenario clause', 'query'].includes(item[0])) continue;
|
|
1334
|
+
items.push([...item, file]);
|
|
1335
|
+
}
|
|
1336
|
+
};
|
|
895
1337
|
for (const [text, file] of inputs) {
|
|
896
|
-
|
|
1338
|
+
read.add(String(file));
|
|
1339
|
+
load(text, file, true, 0);
|
|
897
1340
|
}
|
|
898
1341
|
// Templates first: a sentence can use a template declared after it.
|
|
899
1342
|
const templates = [], byName = new Map();
|
|
900
1343
|
const starred = items.some((item) => item[0] === 'template' && item[2].some((t) => t.text === '*'));
|
|
901
|
-
|
|
902
|
-
const error = (message, at = line) => { throw new EyemindError(`${file}: line ${at}: Logical English: ${message}`); };
|
|
1344
|
+
const declare = (tokens, error, relation = null) => {
|
|
903
1345
|
const parts = readTemplate(tokens, error, starred);
|
|
904
|
-
const
|
|
905
|
-
if (
|
|
1346
|
+
const arity = parts.filter((p) => p.place).length;
|
|
1347
|
+
if (relation && relation.arity !== arity) error(`a synonym needs the ${relation.arity} places of "${relation.text}"`);
|
|
1348
|
+
const name = relation?.name ?? templateName(parts), key = `${name}/${arity}`;
|
|
1349
|
+
if (!relation && byName.has(key)) {
|
|
906
1350
|
const other = byName.get(key);
|
|
907
|
-
if (other.parts.map((p) => p.word ?? '*').join(' ') === parts.map((p) => p.word ?? '*').join(' '))
|
|
1351
|
+
if (other.parts.map((p) => p.word ?? '*').join(' ') === parts.map((p) => p.word ?? '*').join(' ')) return other;
|
|
908
1352
|
error(`the templates "${other.text}" and "${phrase(tokens)}" both name the relation ${name}/${arity}; change a word of one`);
|
|
909
1353
|
}
|
|
910
1354
|
const template = { parts, name, arity, words: parts.filter((p) => p.word).length, text: phrase(tokens) };
|
|
911
|
-
byName.set(key, template);
|
|
1355
|
+
if (!relation) byName.set(key, template);
|
|
912
1356
|
templates.push(template);
|
|
1357
|
+
return template;
|
|
1358
|
+
};
|
|
1359
|
+
for (const [, role, tokens, line, file] of items.filter((item) => item[0] === 'template')) {
|
|
1360
|
+
const error = (message, at = line) => { throw new EyemindError(`${file}: line ${at}: Logical English: ${message}`); };
|
|
1361
|
+
// A template, then its additions after ";".
|
|
1362
|
+
const pieces = [[]];
|
|
1363
|
+
let inside = false;
|
|
1364
|
+
for (const t of tokens) {
|
|
1365
|
+
if (t.text === '*') inside = !inside;
|
|
1366
|
+
if (t.text === ';' && !inside) pieces.push([]);
|
|
1367
|
+
else pieces.at(-1).push(t);
|
|
1368
|
+
}
|
|
1369
|
+
const template = declare(pieces[0], error);
|
|
1370
|
+
// A function "... is *a value*" can be written without its value.
|
|
1371
|
+
if (role === 'function') {
|
|
1372
|
+
const parts = template.parts;
|
|
1373
|
+
if (parts.length < 2 || !parts.at(-1).place || parts.at(-2).word !== 'is') error('a function has the form "... is *a value*"');
|
|
1374
|
+
template.function = parts.slice(0, -2);
|
|
1375
|
+
}
|
|
1376
|
+
for (const addition of pieces.slice(1)) {
|
|
1377
|
+
const words = addition.map((t) => t.text.toLowerCase()).join(' ');
|
|
1378
|
+
if (['undefined', 'scenario element'].includes(words)) template.scenarioElement = true;
|
|
1379
|
+
if (IGNORED.includes(words) || isWord(addition[0] ?? {}, 'image')) continue;
|
|
1380
|
+
if (ASSUMABLE.includes(words)) { template.assumable = true; if (['judged', 'open textured', 'evaluative'].includes(words)) template.scenarioElement = true; continue; }
|
|
1381
|
+
// A synonym is another wording of the same relation; an opposite is the
|
|
1382
|
+
// wording of a separate relation, which only its own rules conclude.
|
|
1383
|
+
if (isWord(addition[0] ?? {}, 'synonym')) { declare(addition.slice(1), error, template); continue; }
|
|
1384
|
+
if (isWord(addition[0] ?? {}, 'opposite')) { template.opposite = declare(addition.slice(addition[1]?.text === ':' ? 2 : 1), error); continue; }
|
|
1385
|
+
error(`the template addition "; ${phrase(addition)}" belongs to Logical English 2 and is not supported`);
|
|
1386
|
+
}
|
|
1387
|
+
}
|
|
1388
|
+
// Named constants: "the fee is 5." The name stands for the value wherever
|
|
1389
|
+
// no variable of the clause has that name.
|
|
1390
|
+
const constants = new Map();
|
|
1391
|
+
for (const [, , tokens, line, file] of items.filter((item) => item[0] === 'constant')) {
|
|
1392
|
+
const at = tokens.findLastIndex((t) => isWord(t, 'is'));
|
|
1393
|
+
const value = at > 0 ? new Compiler(file, []).term(tokens.slice(at + 1), new Scope()) : null;
|
|
1394
|
+
if (value === null || value instanceof Var) throw new EyemindError(`${file}: line ${line}: Logical English: a constant is written "the fee is 5."`);
|
|
1395
|
+
constants.set(tokens.slice(0, at).map((t) => t.text.toLowerCase()).join(' '), value);
|
|
913
1396
|
}
|
|
914
1397
|
const scenarios = [];
|
|
915
1398
|
for (const [kind, name, , line, file] of items) {
|
|
@@ -918,12 +1401,12 @@ export function compileLe(inputs) {
|
|
|
918
1401
|
scenarios.push(name);
|
|
919
1402
|
}
|
|
920
1403
|
const threaded = scenarios.length > 0;
|
|
921
|
-
const clauses = [], sources = [], queries = [], expectations = [], helpers = new Set(), pending = [];
|
|
1404
|
+
const clauses = [], sources = [], queries = [], expectations = [], helpers = new Set(), pending = [], necessary = new Map(), abducibles = [], constraints = [], denials = [], flips = [];
|
|
922
1405
|
// Clauses wait until every one is read: their negations depend on whether
|
|
923
1406
|
// any fact or rule leaves a variable of its conclusion open.
|
|
924
1407
|
const emit = (kind, head, body, line, file, guard = null) => pending.push({ kind, head, body, line, file, guard });
|
|
925
1408
|
const write = ({ kind, head, body, line, file }) => {
|
|
926
|
-
clauses.push(`// ${String(file).replace(/[\r\n\u2028\u2029]/g, ' ')}: line ${line}`);
|
|
1409
|
+
if (line !== null) clauses.push(`// ${String(file).replace(/[\r\n\u2028\u2029]/g, ' ')}: line ${line}`);
|
|
927
1410
|
if (kind === 'fact') {
|
|
928
1411
|
clauses.push(`fact(${javascript(head)})`);
|
|
929
1412
|
sources.push(new Source('fact', head, [], line, file));
|
|
@@ -946,9 +1429,23 @@ export function compileLe(inputs) {
|
|
|
946
1429
|
// says that b is a c. One rule per such fact keeps the dependencies of
|
|
947
1430
|
// rules that negate other kinds apart.
|
|
948
1431
|
const kinds = [];
|
|
949
|
-
for (
|
|
950
|
-
if (kind === 'template' || kind === 'scenario') continue;
|
|
1432
|
+
for (let [kind, name, tokens, line, file] of items) {
|
|
1433
|
+
if (kind === 'template' || kind === 'scenario' || kind === 'constant') continue;
|
|
951
1434
|
const compiler = new Compiler(file, templates);
|
|
1435
|
+
compiler.constants = constants;
|
|
1436
|
+
Object.assign(compiler, { kb: kind === 'clause' ? name : null, label: tokens.label ?? null, designators: [] });
|
|
1437
|
+
if (kind === 'prolog') {
|
|
1438
|
+
const local = new Scope();
|
|
1439
|
+
// A clause of a Prolog resource; directives are left out.
|
|
1440
|
+
if (tokens[0]?.text === ':' && tokens[1]?.text === '-') continue;
|
|
1441
|
+
const neck = tokens.findIndex((t, k) => t.text === ':' && tokens[k + 1]?.text === '-');
|
|
1442
|
+
const head = compiler.prologArg(neck < 0 ? tokens : tokens.slice(0, neck), local, true);
|
|
1443
|
+
if (!(head instanceof Struct) && typeof head !== 'string') compiler.error('a Prolog clause needs a head such as p(X)', line);
|
|
1444
|
+
const body = neck < 0 ? [] : compiler.prologGoal(tokens.slice(neck + 2), local);
|
|
1445
|
+
if (!body.length && isGround(head)) emit('fact', head, [], line, file);
|
|
1446
|
+
else emit('backward', head, body, line, file, body.length ? { counter: { n: anonymize(head, body) }, scenario: null, rule: true } : null);
|
|
1447
|
+
continue;
|
|
1448
|
+
}
|
|
952
1449
|
const scope = new Scope();
|
|
953
1450
|
if (kind === 'query') {
|
|
954
1451
|
compiler.scenario = threaded ? new Var('Scenario') : null;
|
|
@@ -960,6 +1457,20 @@ export function compileLe(inputs) {
|
|
|
960
1457
|
compiler.term([{ text: 'which', kind: 'word' }, ...body.slice(2, at)], scope);
|
|
961
1458
|
body = body.slice(at + 1);
|
|
962
1459
|
}
|
|
1460
|
+
// LE2's flip query: "which minimal change to the scenario makes it the
|
|
1461
|
+
// case that GOAL". Its goal runs in the world of a scenario with changes.
|
|
1462
|
+
const FLIP = ['which', 'minimal', 'change', 'to', 'the', 'scenario', 'makes', 'it', 'the', 'case', 'that'];
|
|
1463
|
+
if (startsWith(body, FLIP)) {
|
|
1464
|
+
if (!threaded) compiler.error('a flip query changes a scenario; the document has none', line);
|
|
1465
|
+
const S = new Var('Scenario'), changes = new Var('Changes_');
|
|
1466
|
+
compiler.scenario = st('le:flip', S, changes);
|
|
1467
|
+
const goals = compiler.body(body.slice(FLIP.length), scope);
|
|
1468
|
+
anonymize(st('le:flip', S, changes), goals);
|
|
1469
|
+
flips.push({ name, goals, S, changes, line, file });
|
|
1470
|
+
queries.push({ name, flip: true });
|
|
1471
|
+
for (const h of compiler.helpers) helpers.add(h);
|
|
1472
|
+
continue;
|
|
1473
|
+
}
|
|
963
1474
|
compiler.sentence = body;
|
|
964
1475
|
const goals = compiler.body(body, scope);
|
|
965
1476
|
const counter = { n: anonymize(st('true'), goals) };
|
|
@@ -967,15 +1478,28 @@ export function compileLe(inputs) {
|
|
|
967
1478
|
const head = st(ANSWER, name, ...(threaded ? [compiler.scenario] : []), ...answer);
|
|
968
1479
|
emit('backward', head, threaded ? [st(SCENARIO, compiler.scenario), ...goals] : goals, line, file, { counter, scenario: compiler.scenario });
|
|
969
1480
|
emit('query', head, [], line, file);
|
|
970
|
-
|
|
1481
|
+
// A quoted name is written as the name, as LE writes its answers.
|
|
1482
|
+
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) })) });
|
|
971
1483
|
for (const h of compiler.helpers) helpers.add(h);
|
|
972
1484
|
continue;
|
|
973
1485
|
}
|
|
974
1486
|
const inScenario = kind === 'scenario clause';
|
|
975
1487
|
// An expected answer: "one expects answers [...] and unknowns [...]."
|
|
976
1488
|
const expects = tokens.findIndex((t, k) => isWord(t, 'expects') && (tokens[k + 1]?.text === '[' || (isWord(tokens[k + 1] ?? {}, 'answers') && tokens[k + 2]?.text === '[')));
|
|
977
|
-
|
|
978
|
-
|
|
1489
|
+
// "NAME expects changes [[...], ...]": the minimal change sets of a flip.
|
|
1490
|
+
const changesAt = tokens.findIndex((t, k) => isWord(t, 'expects') && isWord(tokens[k + 1] ?? {}, 'changes'));
|
|
1491
|
+
if (changesAt > 0) {
|
|
1492
|
+
if (!inScenario) compiler.error('an expectation belongs to a scenario', line);
|
|
1493
|
+
const sets = [];
|
|
1494
|
+
let current = null;
|
|
1495
|
+
for (const t of tokens.slice(changesAt + 2)) {
|
|
1496
|
+
if (t.text === '[' && current === null && sets.started) current = [];
|
|
1497
|
+
else if (t.text === '[') sets.started = true;
|
|
1498
|
+
else if (t.text === ']' && current !== null) { sets.push(current); current = null; }
|
|
1499
|
+
else if (t.kind === 'string' && current !== null) current.push(t.value);
|
|
1500
|
+
}
|
|
1501
|
+
expectations.push({ scenario: name, query: tokens.slice(0, changesAt).map((t) => t.text).join(' '), changes: [...sets], line });
|
|
1502
|
+
continue;
|
|
979
1503
|
}
|
|
980
1504
|
if (expects > 0) {
|
|
981
1505
|
if (!inScenario) compiler.error('an expectation belongs to a scenario', line);
|
|
@@ -995,42 +1519,109 @@ export function compileLe(inputs) {
|
|
|
995
1519
|
};
|
|
996
1520
|
const [answers, close] = list(expects + 1 + (isWord(tokens[expects + 1] ?? {}, 'answers') ? 1 : 0));
|
|
997
1521
|
// Expected unknowns are assumptions eyemind does not make.
|
|
998
|
-
|
|
1522
|
+
// Without "and unknowns", the answers must rest on no unknowns.
|
|
1523
|
+
const unknowns = startsWith(tokens, ['and', 'unknowns'], close + 1) ? list(close + 3)[0]
|
|
1524
|
+
: startsWith(tokens, ['and', 'any', 'unknowns'], close + 1) ? 'any' : [];
|
|
999
1525
|
expectations.push({ scenario: name, query: tokens.slice(0, expects).map((t) => t.text).join(' '), answers, unknowns, line });
|
|
1000
1526
|
continue;
|
|
1001
1527
|
}
|
|
1002
|
-
if (startsWith(tokens, ['it', 'is', 'unknown', 'whether']) || startsWith(tokens, ['it', 'must', 'not', 'be', 'true', 'that']) ||
|
|
1003
|
-
(startsWith(tokens, ['it', 'is', 'not', 'the', 'case', 'that']) && inScenario)) {
|
|
1004
|
-
compiler.error('unknowns, constraints and negated facts belong to Logical English 2 and are not supported', line);
|
|
1005
|
-
}
|
|
1006
1528
|
compiler.scenario = !threaded ? null : inScenario ? name : new Var('Scenario');
|
|
1529
|
+
// An integrity constraint, "it must not be true that C": no answer's
|
|
1530
|
+
// assumptions may make C true.
|
|
1531
|
+
if (startsWith(tokens, ['it', 'must', 'not', 'be', 'true', 'that'])) {
|
|
1532
|
+
const goals = compiler.body(tokens.slice(6), scope);
|
|
1533
|
+
anonymize(st('true'), goals);
|
|
1534
|
+
constraints.push({ goals, line, file, scenario: compiler.scenario });
|
|
1535
|
+
for (const h of compiler.helpers) helpers.add(h);
|
|
1536
|
+
continue;
|
|
1537
|
+
}
|
|
1538
|
+
// A scenario may deny a sentence: it is then neither stated nor assumed.
|
|
1539
|
+
if (startsWith(tokens, ['it', 'is', 'not', 'the', 'case', 'that'])) {
|
|
1540
|
+
if (!inScenario) compiler.error('a negated fact belongs to a scenario', line);
|
|
1541
|
+
const sentence = compiler.sentenceOf(tokens.slice(6), scope, { data: true });
|
|
1542
|
+
if (!sentence) compiler.error(`no template matches "${phrase(tokens.slice(6))}"`, line);
|
|
1543
|
+
denials.push({ term: compiler.relation(sentence.name, sentence.args), line, file });
|
|
1544
|
+
continue;
|
|
1545
|
+
}
|
|
1546
|
+
// "it is unknown whether S" makes the sentences S describes assumable,
|
|
1547
|
+
// in the knowledge base or in one scenario.
|
|
1548
|
+
if (['unknown', 'assumed', 'assumable'].some((word) => startsWith(tokens, ['it', 'is', word, 'whether']))) {
|
|
1549
|
+
const sentence = compiler.sentenceOf(tokens.slice(4), scope, { data: true });
|
|
1550
|
+
if (!sentence) compiler.error(`no template matches "${phrase(tokens.slice(4))}"`, line);
|
|
1551
|
+
abducibles.push({ term: compiler.relation(sentence.name, sentence.args), line, file });
|
|
1552
|
+
continue;
|
|
1553
|
+
}
|
|
1554
|
+
// A fact may carry LE2's picture, "; image ...", which changes nothing.
|
|
1555
|
+
const semicolon = tokens.findIndex((t) => t.text === ';');
|
|
1556
|
+
if (semicolon > 0 && isWord(tokens[semicolon + 1] ?? {}, 'image')) tokens = tokens.slice(0, semicolon);
|
|
1007
1557
|
const level = depths(tokens);
|
|
1008
1558
|
const ifAt = tokens.findIndex((t, k) => level[k] === 0 && isWord(t, 'if'));
|
|
1009
|
-
|
|
1559
|
+
// "Head only if Body" makes Body necessary: the opposite of the head holds
|
|
1560
|
+
// when Body does not, and the head then fails.
|
|
1561
|
+
const onlyIf = ifAt > 0 && isWord(tokens[ifAt - 1], 'only');
|
|
1562
|
+
let headTokens = ifAt < 0 ? tokens : tokens.slice(0, onlyIf ? ifAt - 1 : ifAt);
|
|
1010
1563
|
// In an ontology, "a student is a person" is about the kinds themselves.
|
|
1011
1564
|
if (kind === 'ontology clause' && ifAt < 0 && isWord(headTokens[0], 'a', 'an') && !isWord(headTokens[1] ?? {}, 'is')) headTokens = headTokens.slice(1);
|
|
1012
1565
|
if (!headTokens.length) compiler.error('a rule needs a conclusion before "if"', line);
|
|
1013
1566
|
// In a fact, an id that no phrase introduces is a name, as in Q1.
|
|
1014
1567
|
compiler.fact = ifAt < 0;
|
|
1015
|
-
|
|
1568
|
+
let head = compiler.sentenceOf(headTokens, scope, { data: true });
|
|
1569
|
+
// A scenario may state "A is B" with no template for it, as LE2 accepts;
|
|
1570
|
+
// it is a fact of the relation le_is.
|
|
1571
|
+
const isAt = headTokens.findIndex((t) => isWord(t, 'is'));
|
|
1572
|
+
if (!head && inScenario && ifAt < 0 && isAt > 0) {
|
|
1573
|
+
const a = compiler.term(headTokens.slice(0, isAt), scope), b = compiler.term(headTokens.slice(isAt + 1), scope);
|
|
1574
|
+
if (a !== null && b !== null) head = { name: 'le_is', args: [a, b] };
|
|
1575
|
+
}
|
|
1016
1576
|
if (!head) {
|
|
1017
1577
|
const builtin = compiler.sentenceOf(headTokens, new Scope());
|
|
1018
1578
|
if (builtin?.builtin) compiler.error(`"${phrase(headTokens)}" is a built-in condition and cannot be concluded`, line);
|
|
1019
1579
|
compiler.error(`no template matches "${phrase(headTokens)}"`, line);
|
|
1020
1580
|
}
|
|
1021
1581
|
const headTerm = compiler.relation(head.name, head.args);
|
|
1582
|
+
// A function in the conclusion is asked after the conditions.
|
|
1583
|
+
const headCalls = scope.pre.splice(0);
|
|
1022
1584
|
if (kind === 'ontology clause' && ifAt < 0 && head.name === 'is_a' && head.args.every(isGround)) kinds.push({ term: headTerm, line, file });
|
|
1023
1585
|
if (ifAt < 0) {
|
|
1024
|
-
|
|
1586
|
+
// A ground fact of the knowledge base is stated in every scenario.
|
|
1587
|
+
if (compiler.scenario instanceof Var && !headCalls.length && head.args.every(isGround)) {
|
|
1588
|
+
for (const scenario of scenarios) {
|
|
1589
|
+
emit('fact', new Struct(headTerm.name, [scenario, ...headTerm.args.slice(1)]), [], line, file);
|
|
1590
|
+
pending.at(-1).kb = true;
|
|
1591
|
+
}
|
|
1592
|
+
continue;
|
|
1593
|
+
}
|
|
1594
|
+
const body = [...(compiler.scenario instanceof Var ? [st(SCENARIO, compiler.scenario)] : []), ...headCalls];
|
|
1025
1595
|
if (!body.length && isGround(headTerm)) emit('fact', headTerm, [], line, file);
|
|
1026
1596
|
else emit('backward', headTerm, body, line, file);
|
|
1597
|
+
// A scenario fact is evidence of its source; one without is never
|
|
1598
|
+
// admissible in a source-scoped proof.
|
|
1599
|
+
if (inScenario) pending.at(-1).evidence = tokens.source ?? null;
|
|
1027
1600
|
continue;
|
|
1028
1601
|
}
|
|
1029
1602
|
if (ifAt === tokens.length - 1) compiler.error('a rule needs conditions after "if"', line);
|
|
1030
1603
|
// LE1 also writes "if" followed by a line that starts with "and".
|
|
1031
|
-
const goals =
|
|
1604
|
+
const goals = tokens[ifAt + 1]?.text === ':' ? compiler.numbered(tokens.slice(ifAt + 2), scope)
|
|
1605
|
+
: compiler.body(tokens.slice(ifAt + (isWord(tokens[ifAt + 1], 'and') ? 2 : 1)), scope);
|
|
1606
|
+
if (onlyIf) {
|
|
1607
|
+
const template = templates.find((t) => t.name === head.name && t.arity === head.args.length && t.opposite);
|
|
1608
|
+
const opposite = compiler.relation(template ? template.opposite.name : `${head.name}:not`, head.args);
|
|
1609
|
+
const body = [st('not', conjunction(goals))];
|
|
1610
|
+
const counter = { n: anonymize(opposite, body) };
|
|
1611
|
+
emit('backward', opposite, body, line, file, { counter, scenario: compiler.scenario, rule: true });
|
|
1612
|
+
necessary.set(`${head.name}/${headTerm.args.length}`, { name: head.name, opposite: opposite.name, arity: headTerm.args.length, line, file });
|
|
1613
|
+
for (const h of compiler.helpers) helpers.add(h);
|
|
1614
|
+
continue;
|
|
1615
|
+
}
|
|
1616
|
+
goals.push(...headCalls);
|
|
1032
1617
|
const counter = { n: anonymize(headTerm, goals) };
|
|
1033
1618
|
emit('backward', headTerm, goals, line, file, { counter, scenario: compiler.scenario, rule: true });
|
|
1619
|
+
// LE2's system predicates: the section of a labelled rule, and the
|
|
1620
|
+
// designators of its numbered conditions.
|
|
1621
|
+
if (compiler.label !== null) {
|
|
1622
|
+
emit('fact', st('le_source_section', tokens.part ?? 'main', compiler.label), [], line, file);
|
|
1623
|
+
for (const designator of compiler.designators) emit('fact', st('le_source_element', compiler.label, designator, 'true'), [], line, file);
|
|
1624
|
+
}
|
|
1034
1625
|
for (const h of compiler.helpers) helpers.add(h);
|
|
1035
1626
|
}
|
|
1036
1627
|
// A fact or rule may leave a variable of its conclusion open. Then no
|
|
@@ -1038,19 +1629,36 @@ export function compileLe(inputs) {
|
|
|
1038
1629
|
// variables at run time.
|
|
1039
1630
|
const open = pending.some(({ kind, head, body, guard }) => kind !== 'query' && (guard ? guard.rule : true) &&
|
|
1040
1631
|
[...varsOf(head)].some((v) => !/^_\d+$/.test(v.name) && v.name !== 'Scenario' && !openVariables(body).includes(v)));
|
|
1632
|
+
// A relation with "only if" rules holds by its other rules, through a base
|
|
1633
|
+
// relation, unless its opposite holds.
|
|
1634
|
+
for (const [key, { name, opposite, arity, line, file }] of necessary) {
|
|
1635
|
+
const base = `${name}:if`;
|
|
1636
|
+
for (const clause of pending) {
|
|
1637
|
+
if (clause.head instanceof Struct && `${clause.head.name}/${clause.head.args.length}` === key) clause.head = new Struct(base, clause.head.args);
|
|
1638
|
+
}
|
|
1639
|
+
const args = Array.from({ length: arity }, (_, i) => new Var(i === 0 && threaded ? 'Scenario' : `A${i}`));
|
|
1640
|
+
emit('backward', new Struct(name, args), [new Struct(base, args), st('not', new Struct(opposite, args))], line, file,
|
|
1641
|
+
{ counter: { n: 0 }, scenario: threaded ? args[0] : null, rule: true });
|
|
1642
|
+
}
|
|
1041
1643
|
for (const { term, line, file } of kinds) {
|
|
1042
1644
|
const S = new Var('Scenario'), X = new Var('X'), [sub, kind] = term.args.slice(-2);
|
|
1043
1645
|
const isA = (a, b) => threaded ? st('is_a', S, a, b) : st('is_a', a, b);
|
|
1044
1646
|
emit('backward', isA(X, kind), [isA(X, sub)], line, file, { counter: { n: 0 }, scenario: threaded ? S : null, rule: true });
|
|
1045
1647
|
}
|
|
1046
|
-
|
|
1648
|
+
if (flips.length) flipWorlds(pending, { templates, flips, scenarios, helpers, emit });
|
|
1649
|
+
scopeProofs(pending, { templates, threaded, emit });
|
|
1650
|
+
const assumable = new Set([...templates.filter((t) => t.assumable).map((t) => `${t.name}/${t.arity + (threaded ? 1 : 0)}`),
|
|
1651
|
+
...abducibles.map(({ term }) => `${term.name}/${term.args.length}`)]);
|
|
1652
|
+
unfold(pending, templates, threaded);
|
|
1653
|
+
forwardRecursion(pending, templates, threaded, assumable);
|
|
1654
|
+
const abductive = assumable.size > 0 || constraints.length > 0;
|
|
1655
|
+
if (abductive) abduce(pending, { templates, threaded, assumable, abducibles, constraints, denials, helpers, emit });
|
|
1047
1656
|
for (const clause of pending) {
|
|
1048
|
-
if (clause.guard)
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
}
|
|
1052
|
-
write(clause);
|
|
1657
|
+
if (!clause.guard) continue;
|
|
1658
|
+
const { counter, scenario } = clause.guard;
|
|
1659
|
+
clause.body = guardNegations(clause.body, new Set(scenario instanceof Var ? [scenario] : []), counter, open);
|
|
1053
1660
|
}
|
|
1661
|
+
for (const clause of pending) write(clause);
|
|
1054
1662
|
// The helpers follow every stated clause.
|
|
1055
1663
|
const used = Object.keys(HELPERS).filter((name) => helpers.has(name));
|
|
1056
1664
|
if (used.length) {
|
|
@@ -1059,7 +1667,7 @@ export function compileLe(inputs) {
|
|
|
1059
1667
|
sources.push(...loadText(text, 'Logical English helpers').sources.map((s) => Object.assign(s, { line: null, file: null })));
|
|
1060
1668
|
}
|
|
1061
1669
|
return { kind: 'le', text: '// Compiled from Logical English to Logic Script.\n\n' + clauses.join('\n') + '\n',
|
|
1062
|
-
program: new Program(sources), compiled: { templates, scenarios, threaded, queries, expectations } };
|
|
1670
|
+
program: new Program(sources), compiled: { templates, scenarios, threaded, queries, expectations, abductive } };
|
|
1063
1671
|
}
|
|
1064
1672
|
|
|
1065
1673
|
// LE runs recursive rules with tabling (LE1) or a loop check (LE2), so a rule
|
|
@@ -1069,7 +1677,7 @@ export function compileLe(inputs) {
|
|
|
1069
1677
|
// each of its rules binds every variable of its conclusion through the
|
|
1070
1678
|
// relations of its conditions; a rule whose conclusion depends on how it is
|
|
1071
1679
|
// called, such as a counter that goes down, stays backward.
|
|
1072
|
-
function forwardRecursion(pending, templates, threaded) {
|
|
1680
|
+
function forwardRecursion(pending, templates, threaded, assumable = new Set()) {
|
|
1073
1681
|
const keys = new Set([...templates.map((t) => `${t.name}/${t.arity + (threaded ? 1 : 0)}`), `is_a/${threaded ? 3 : 2}`]);
|
|
1074
1682
|
const keyOf = (term) => term instanceof Struct ? `${term.name}/${term.args.length}` : null;
|
|
1075
1683
|
const calls = (term, out = new Set()) => {
|
|
@@ -1116,6 +1724,403 @@ function forwardRecursion(pending, templates, threaded) {
|
|
|
1116
1724
|
}
|
|
1117
1725
|
}
|
|
1118
1726
|
|
|
1727
|
+
// LE2's flip queries. A changed scenario is the world le:flip(S, Changes): its
|
|
1728
|
+
// stated facts are those of S, without the removed ones, with the added ones,
|
|
1729
|
+
// and the rules run in it as in any scenario. A change adds or removes a fact
|
|
1730
|
+
// of a template that no rule concludes, or one marked undefined or judged,
|
|
1731
|
+
// filled with individuals the scenario names; an answer is a smallest set of
|
|
1732
|
+
// at most three changes that makes the goal hold.
|
|
1733
|
+
const FLIP_LIMIT = 3;
|
|
1734
|
+
function flipWorlds(pending, { templates, flips, scenarios, helpers, emit }) {
|
|
1735
|
+
const keyOf = (term) => term instanceof Struct ? `${term.name}/${term.args.length}` : null;
|
|
1736
|
+
const concluded = new Set(pending.filter((c) => c.guard?.rule).map((c) => keyOf(c.head)));
|
|
1737
|
+
const marked = templates.filter((t) => t.scenarioElement);
|
|
1738
|
+
const changeable = (marked.length ? marked : templates.filter((t) => !t.function && !concluded.has(`${t.name}/${t.arity + 1}`)))
|
|
1739
|
+
.filter((t, i, all) => all.findIndex((u) => u.name === t.name && u.arity === t.arity) === i);
|
|
1740
|
+
const isChangeable = (name, arity) => changeable.some((t) => t.name === name && t.arity === arity);
|
|
1741
|
+
// The facts each scenario states, and the knowledge base's facts, which
|
|
1742
|
+
// hold in every world.
|
|
1743
|
+
const stated = new Map(scenarios.map((s) => [s, []]));
|
|
1744
|
+
for (const clause of pending) {
|
|
1745
|
+
const head = clause.head;
|
|
1746
|
+
if (clause.kind === 'query' || !(head instanceof Struct) || head.args.length === 0 || head.name.startsWith('le:')) continue;
|
|
1747
|
+
const world = head.args[0];
|
|
1748
|
+
if (clause.kind === 'fact' && typeof world === 'string' && stated.has(world)) {
|
|
1749
|
+
const fact = new Struct(head.name, head.args.slice(1));
|
|
1750
|
+
fact.kb = clause.kb === true;
|
|
1751
|
+
stated.get(world).push(fact);
|
|
1752
|
+
}
|
|
1753
|
+
// A knowledge-base fact holds in a changed world too.
|
|
1754
|
+
if (world instanceof Var && clause.body?.length === 1 && clause.body[0] instanceof Struct && clause.body[0].name === SCENARIO) {
|
|
1755
|
+
clause.body = [st('le:world', world)];
|
|
1756
|
+
}
|
|
1757
|
+
}
|
|
1758
|
+
// The changed worlds are finite: each set of at most FLIP_LIMIT candidate
|
|
1759
|
+
// changes of a scenario. Each world states its facts: the scenario's, without
|
|
1760
|
+
// the removed ones, with the added ones, so that every rule runs in it.
|
|
1761
|
+
const S = new Var('Scenario');
|
|
1762
|
+
emit('backward', st('le:world', S), [st(SCENARIO, S)], null, null);
|
|
1763
|
+
let size = 0;
|
|
1764
|
+
for (const [scenario, facts] of stated) {
|
|
1765
|
+
// A place is filled with the individuals of its type, or with every
|
|
1766
|
+
// individual when the scenario names none of that type; a kind is no
|
|
1767
|
+
// individual.
|
|
1768
|
+
const kinds = new Set(facts.filter((f) => f.name === 'is_a').map((f) => f.args[1]));
|
|
1769
|
+
const individuals = [...new Set(facts.flatMap((f) => f.name === 'is_a' ? [f.args[0]] : f.args).filter((a) => typeof a === 'string' && !kinds.has(a)))];
|
|
1770
|
+
const ofType = (place) => {
|
|
1771
|
+
const typed = facts.filter((f) => f.name === 'is_a' && f.args[1] === place.name.split(' ').at(-1)).map((f) => f.args[0]);
|
|
1772
|
+
return typed.length ? typed : individuals;
|
|
1773
|
+
};
|
|
1774
|
+
const candidates = [];
|
|
1775
|
+
for (const fact of facts) if (!fact.kb && isChangeable(fact.name, fact.args.length)) candidates.push(st('remove', fact));
|
|
1776
|
+
for (const t of changeable) {
|
|
1777
|
+
if (t.arity > 2) continue;
|
|
1778
|
+
const places = t.parts.filter((part) => part.place).map(ofType);
|
|
1779
|
+
const fills = t.arity === 0 ? [[]] : t.arity === 1 ? places[0].map((a) => [a]) : places[0].flatMap((a) => places[1].map((b) => [a, b]));
|
|
1780
|
+
for (const fill of fills) {
|
|
1781
|
+
const sentence = new Struct(t.name, fill);
|
|
1782
|
+
if (!facts.some((f) => write(f) === write(sentence))) candidates.push(st('add', sentence));
|
|
1783
|
+
}
|
|
1784
|
+
}
|
|
1785
|
+
emit('fact', st('le:candidates', scenario, list(candidates)), [], null, null);
|
|
1786
|
+
const subsets = (from, k) => k === 0 ? [[]] : candidates.slice(from).flatMap((c, i) => subsets(from + i + 1, k - 1).map((rest) => [c, ...rest]));
|
|
1787
|
+
for (let k = 0; k <= FLIP_LIMIT; k++) {
|
|
1788
|
+
for (const changes of subsets(0, k)) {
|
|
1789
|
+
const world = st('le:flip', scenario, list(changes));
|
|
1790
|
+
const removed = new Set(changes.filter((c) => c.name === 'remove').map((c) => write(c.args[0])));
|
|
1791
|
+
const worldFacts = [...facts.filter((f) => !removed.has(write(f))), ...changes.filter((c) => c.name === 'add').map((c) => c.args[0])];
|
|
1792
|
+
size += worldFacts.length + 1;
|
|
1793
|
+
if (size > 200000) throw new EyemindError(`a flip query's search is larger than eyemind states: ${candidates.length} candidate changes in scenario ${scenario}`);
|
|
1794
|
+
emit('fact', st('le:world', world), [], null, null);
|
|
1795
|
+
for (const fact of worldFacts) emit('fact', new Struct(fact.name, [world, ...fact.args]), [], null, null);
|
|
1796
|
+
}
|
|
1797
|
+
}
|
|
1798
|
+
}
|
|
1799
|
+
helpers.add('le:choose');
|
|
1800
|
+
helpers.add('le:member');
|
|
1801
|
+
const sizes = list(Array.from({ length: FLIP_LIMIT + 1 }, (_, k) => BigInt(k)));
|
|
1802
|
+
for (const { name, goals, S: world, changes, line, file } of flips) {
|
|
1803
|
+
const size = new Var('K_'), candidates = new Var('Candidates_');
|
|
1804
|
+
emit('backward', st('le:flips', name, world, size, changes),
|
|
1805
|
+
[st('le:candidates', world, candidates), st('le:choose', size, candidates, changes), ...goals], line, file,
|
|
1806
|
+
{ counter: { n: 100 }, scenario: st('le:flip', world, changes), rule: false });
|
|
1807
|
+
const smaller = new Var('J_');
|
|
1808
|
+
emit('backward', st('le:smaller', name, world, size), [st('le:member', smaller, sizes), st('lt', smaller, size), st('le:flips', name, world, smaller, new Var('_'))], line, file);
|
|
1809
|
+
const answer = st(ANSWER, name, world, changes);
|
|
1810
|
+
emit('backward', answer, [st(SCENARIO, world), st('le:member', size, sizes), st('le:flips', name, world, size, changes),
|
|
1811
|
+
st('not', st('le:smaller', name, world, size))], line, file);
|
|
1812
|
+
emit('query', answer, [], line, file);
|
|
1813
|
+
}
|
|
1814
|
+
}
|
|
1815
|
+
|
|
1816
|
+
// LE2's source-scoped proof: "C according to S" proves C from the rules and
|
|
1817
|
+
// facts of the program and only the scenario facts whose source is
|
|
1818
|
+
// admissible under S. Every relation C can reach gets a second version,
|
|
1819
|
+
// NAME:sc, with the scope as one more argument; in it, a scenario fact holds
|
|
1820
|
+
// when its source is admissible under the scope.
|
|
1821
|
+
function scopeProofs(pending, { templates, threaded, emit }) {
|
|
1822
|
+
const keyOf = (term) => term instanceof Struct ? `${term.name}/${term.args.length}` : null;
|
|
1823
|
+
const user = new Set([...templates.map((t) => `${t.name}/${t.arity + (threaded ? 1 : 0)}`), `is_a/${threaded ? 3 : 2}`, `${ADMISSIBLE}/${threaded ? 3 : 2}`]);
|
|
1824
|
+
const placeholders = [];
|
|
1825
|
+
const find = (term) => {
|
|
1826
|
+
if (!(term instanceof Struct)) return;
|
|
1827
|
+
if (term.name === 'le:according' && term.args.length === 2) placeholders.push(term);
|
|
1828
|
+
for (const arg of term.args) find(arg);
|
|
1829
|
+
};
|
|
1830
|
+
for (const clause of pending) for (const goal of clause.body ?? []) find(goal);
|
|
1831
|
+
if (!placeholders.length) return;
|
|
1832
|
+
const calls = (term, out = new Set()) => {
|
|
1833
|
+
if (term instanceof Struct) {
|
|
1834
|
+
if (user.has(keyOf(term))) out.add(keyOf(term));
|
|
1835
|
+
for (const arg of term.args) calls(arg, out);
|
|
1836
|
+
}
|
|
1837
|
+
return out;
|
|
1838
|
+
};
|
|
1839
|
+
const reach = new Set();
|
|
1840
|
+
for (const p of placeholders) for (const k of calls(p.args[0])) reach.add(k);
|
|
1841
|
+
for (let changed = true; changed;) {
|
|
1842
|
+
changed = false;
|
|
1843
|
+
for (const clause of pending) {
|
|
1844
|
+
if (!reach.has(keyOf(clause.head))) continue;
|
|
1845
|
+
for (const goal of clause.body ?? []) for (const k of calls(goal)) if (!reach.has(k)) { reach.add(k); changed = true; }
|
|
1846
|
+
}
|
|
1847
|
+
}
|
|
1848
|
+
const scoped = (term, scope) => {
|
|
1849
|
+
if (!(term instanceof Struct)) return term;
|
|
1850
|
+
if (term.name === 'le:according' && term.args.length === 2) return scoped(term.args[0], term.args[1]);
|
|
1851
|
+
if (scope !== null && reach.has(keyOf(term))) return new Struct(`${term.name}:sc`, [...term.args, scope]);
|
|
1852
|
+
return new Struct(term.name, term.args.map((arg) => scoped(arg, scope)));
|
|
1853
|
+
};
|
|
1854
|
+
const admissible = (scenario, source, scope) => new Struct(ADMISSIBLE, [...(threaded ? [scenario] : []), source, scope]);
|
|
1855
|
+
for (const clause of [...pending]) {
|
|
1856
|
+
if (!reach.has(keyOf(clause.head)) || clause.kind === 'query') continue;
|
|
1857
|
+
const scope = new Var('Scope_');
|
|
1858
|
+
if (clause.evidence === null) continue;
|
|
1859
|
+
const head = new Struct(`${clause.head.name}:sc`, [...clause.head.args, scope]);
|
|
1860
|
+
if (clause.evidence !== undefined) {
|
|
1861
|
+
emit('backward', head, [admissible(clause.head.args[0], clause.evidence, scope)], clause.line, clause.file);
|
|
1862
|
+
} else {
|
|
1863
|
+
emit('backward', head, (clause.body ?? []).map((goal) => scoped(goal, scope)), clause.line, clause.file,
|
|
1864
|
+
clause.guard && { ...clause.guard, counter: { n: clause.guard.counter.n } });
|
|
1865
|
+
}
|
|
1866
|
+
}
|
|
1867
|
+
for (const clause of pending) if (clause.body) clause.body = clause.body.map((goal) => scoped(goal, null));
|
|
1868
|
+
// A source is admissible under itself.
|
|
1869
|
+
const S = new Var('Scenario'), X = new Var('X');
|
|
1870
|
+
emit('backward', admissible(S, X, X), threaded ? [st(SCENARIO, S)] : [], null, null);
|
|
1871
|
+
}
|
|
1872
|
+
|
|
1873
|
+
// LE runs a rule top-down, so a negation or a collection may reach the rule's
|
|
1874
|
+
// own relation, through other rules, as long as the data never closes the
|
|
1875
|
+
// cycle. LS stratifies statically, so such a group of relations is unfolded
|
|
1876
|
+
// into levels: a negation or collection at level k calls level k + 1, a
|
|
1877
|
+
// relation of its own. The answers are exact up to DEPTH levels; a program
|
|
1878
|
+
// that needs more stops with an error that says so.
|
|
1879
|
+
const DEPTH = 8;
|
|
1880
|
+
function unfold(pending, templates, threaded) {
|
|
1881
|
+
const keys = new Set([...templates.map((t) => `${t.name}/${t.arity + (threaded ? 1 : 0)}`), `is_a/${threaded ? 3 : 2}`, `le_is/${threaded ? 3 : 2}`]);
|
|
1882
|
+
const keyOf = (term) => term instanceof Struct ? `${term.name}/${term.args.length}` : null;
|
|
1883
|
+
const closedControl = (term) => term instanceof Struct && ((term.name === 'not' && term.args.length === 1) || ((term.name === 'findall' || term.name === 'findall_sorted') && term.args.length === 3));
|
|
1884
|
+
const edges = new Map();
|
|
1885
|
+
const visitCalls = (term, from, closed) => {
|
|
1886
|
+
if (!(term instanceof Struct)) return;
|
|
1887
|
+
if (keys.has(keyOf(term))) edges.get(from).push([keyOf(term), closed]);
|
|
1888
|
+
for (const arg of term.args) visitCalls(arg, from, closed || closedControl(term));
|
|
1889
|
+
};
|
|
1890
|
+
const rules = pending.filter((c) => c.kind !== 'query' && c.head instanceof Struct && keys.has(keyOf(c.head)));
|
|
1891
|
+
for (const rule of rules) {
|
|
1892
|
+
if (!edges.has(keyOf(rule.head))) edges.set(keyOf(rule.head), []);
|
|
1893
|
+
for (const goal of rule.body ?? []) visitCalls(goal, keyOf(rule.head), false);
|
|
1894
|
+
}
|
|
1895
|
+
// The strongly connected components, and those with a closed edge inside.
|
|
1896
|
+
const index = new Map(), low = new Map(), stack = [], onStack = new Set(), component = new Map();
|
|
1897
|
+
let counter = 0;
|
|
1898
|
+
const visit = (v) => {
|
|
1899
|
+
index.set(v, counter); low.set(v, counter++); stack.push(v); onStack.add(v);
|
|
1900
|
+
for (const [w] of edges.get(v) ?? []) {
|
|
1901
|
+
if (!index.has(w)) { visit(w); low.set(v, Math.min(low.get(v), low.get(w))); }
|
|
1902
|
+
else if (onStack.has(w)) low.set(v, Math.min(low.get(v), index.get(w)));
|
|
1903
|
+
}
|
|
1904
|
+
if (low.get(v) === index.get(v)) {
|
|
1905
|
+
const members = [];
|
|
1906
|
+
let w;
|
|
1907
|
+
do { w = stack.pop(); onStack.delete(w); members.push(w); } while (w !== v);
|
|
1908
|
+
for (const m of members) component.set(m, members);
|
|
1909
|
+
}
|
|
1910
|
+
};
|
|
1911
|
+
for (const v of edges.keys()) if (!index.has(v)) visit(v);
|
|
1912
|
+
const unfolded = new Set();
|
|
1913
|
+
for (const [from, list] of edges) {
|
|
1914
|
+
for (const [to, closed] of list) if (closed && component.get(from)?.includes(to)) for (const m of component.get(from)) unfolded.add(m);
|
|
1915
|
+
}
|
|
1916
|
+
if (!unfolded.size) return;
|
|
1917
|
+
const named = (term, level) => level === 0 ? term : new Struct(`${term.name}#${level}`, term.args);
|
|
1918
|
+
const rename = (term, level, closed) => {
|
|
1919
|
+
if (!(term instanceof Struct)) return term;
|
|
1920
|
+
if (unfolded.has(keyOf(term))) {
|
|
1921
|
+
const target = closed ? level + 1 : level;
|
|
1922
|
+
// Past the last level, the call stops the run and says why.
|
|
1923
|
+
if (target >= DEPTH) return st('is', new Var('_'), `Logical English: a negation or collection through recursion deeper than ${DEPTH} levels`);
|
|
1924
|
+
return named(term, target);
|
|
1925
|
+
}
|
|
1926
|
+
return new Struct(term.name, term.args.map((arg) => rename(arg, level, closed || closedControl(term))));
|
|
1927
|
+
};
|
|
1928
|
+
const copies = [];
|
|
1929
|
+
for (const clause of pending) {
|
|
1930
|
+
if (clause.kind === 'query' || !unfolded.has(keyOf(clause.head))) {
|
|
1931
|
+
if (clause.body) clause.body = clause.body.map((goal) => rename(goal, 0, false));
|
|
1932
|
+
continue;
|
|
1933
|
+
}
|
|
1934
|
+
for (let level = 1; level < DEPTH; level++) {
|
|
1935
|
+
copies.push({ ...clause, head: named(clause.head, level), body: clause.body?.map((goal) => rename(goal, level, false)),
|
|
1936
|
+
guard: clause.guard && { ...clause.guard, counter: { n: clause.guard.counter.n } } });
|
|
1937
|
+
}
|
|
1938
|
+
if (clause.body) clause.body = clause.body.map((goal) => rename(goal, 0, false));
|
|
1939
|
+
}
|
|
1940
|
+
pending.push(...copies);
|
|
1941
|
+
}
|
|
1942
|
+
|
|
1943
|
+
// Abduction, as LE2 does it. When the program cannot prove a sentence of an
|
|
1944
|
+
// assumable template, or of an "it is unknown whether" pattern, an answer can
|
|
1945
|
+
// rest on the assumption that it holds; a negation of such a sentence holds by
|
|
1946
|
+
// assuming it false. Every relation that can reach one gets a second version,
|
|
1947
|
+
// NAME:ab, with one more argument: the list of its assumptions, a sentence or
|
|
1948
|
+
// 'le:not'(sentence). A negation finds every way its goal holds and assumes,
|
|
1949
|
+
// for each, one of its assumptions false, leaving out a way that contradicts
|
|
1950
|
+
// what the answer already assumes; a collection or a universal counts every
|
|
1951
|
+
// way, and assumes all their assumptions. Each answer gets its list, without
|
|
1952
|
+
// the sentences the facts and rules prove after all, and is rejected when it
|
|
1953
|
+
// assumes a sentence and its negation, denies a proved sentence, or breaks a
|
|
1954
|
+
// constraint that more assumptions cannot repair.
|
|
1955
|
+
function abduce(pending, { templates, threaded, assumable, abducibles, constraints, denials, helpers, emit }) {
|
|
1956
|
+
const keyOf = (term) => term instanceof Struct ? `${term.name}/${term.args.length}` : null;
|
|
1957
|
+
const user = new Set([...templates.map((t) => `${t.name}/${t.arity + (threaded ? 1 : 0)}`), `is_a/${threaded ? 3 : 2}`,
|
|
1958
|
+
`le_is/${threaded ? 3 : 2}`, ...assumable]);
|
|
1959
|
+
const calls = (term, out = new Set()) => {
|
|
1960
|
+
if (term instanceof Struct) {
|
|
1961
|
+
if (user.has(keyOf(term))) out.add(keyOf(term));
|
|
1962
|
+
for (const arg of term.args) calls(arg, out);
|
|
1963
|
+
}
|
|
1964
|
+
return out;
|
|
1965
|
+
};
|
|
1966
|
+
const clauses = pending.filter((c) => c.kind !== 'query');
|
|
1967
|
+
const closure = (start) => {
|
|
1968
|
+
const set = new Set(start);
|
|
1969
|
+
for (let changed = true; changed;) {
|
|
1970
|
+
changed = false;
|
|
1971
|
+
for (const clause of clauses) {
|
|
1972
|
+
const key = keyOf(clause.head);
|
|
1973
|
+
if (set.has(key) || !clause.body) continue;
|
|
1974
|
+
if (clause.body.some((goal) => [...calls(goal)].some((k) => set.has(k)))) { set.add(key); changed = true; }
|
|
1975
|
+
}
|
|
1976
|
+
}
|
|
1977
|
+
return set;
|
|
1978
|
+
};
|
|
1979
|
+
const reach = closure(assumable);
|
|
1980
|
+
const reaches = (goal) => [...calls(goal)].some((k) => reach.has(k));
|
|
1981
|
+
let n = 0;
|
|
1982
|
+
const fresh = () => new Var(`U${++n}_`);
|
|
1983
|
+
for (const name of ['le:append', 'le:member', 'le:unknowns', 'le:negate', 'le:union', 'le:pairs', 'le:no_empty']) helpers.add(name);
|
|
1984
|
+
const fail = (clause) => { throw new EyemindError(`${clause.file}: line ${clause.line}: Logical English: this combination of assumptions, negation and collection belongs to Logical English 2 and is not supported`); };
|
|
1985
|
+
// The goals of a body in the abductive version, given the list of what is
|
|
1986
|
+
// assumed before them; and the list after them.
|
|
1987
|
+
const transform = (goals, clause, before) => {
|
|
1988
|
+
const out = [];
|
|
1989
|
+
let acc = before;
|
|
1990
|
+
const add = (list) => {
|
|
1991
|
+
if (acc === EMPTY) { acc = list; return; }
|
|
1992
|
+
const next = fresh();
|
|
1993
|
+
out.push(st('le:append', acc, list, next));
|
|
1994
|
+
acc = next;
|
|
1995
|
+
};
|
|
1996
|
+
for (const goal of goals) {
|
|
1997
|
+
if (!reaches(goal)) { out.push(goal); continue; }
|
|
1998
|
+
if (goal instanceof Struct && reach.has(keyOf(goal))) {
|
|
1999
|
+
const u = fresh();
|
|
2000
|
+
out.push(new Struct(`${goal.name}:ab`, [...goal.args, u]));
|
|
2001
|
+
add(u);
|
|
2002
|
+
} else if (goal instanceof Struct && goal.name === 'or' && goal.args.length === 2) {
|
|
2003
|
+
const v = fresh();
|
|
2004
|
+
const branch = (g) => { const [body, w] = transform(flattenGoal(g), clause, acc); return conjunction([...body, st('unify', v, w)]); };
|
|
2005
|
+
out.push(st('or', branch(goal.args[0]), branch(goal.args[1])));
|
|
2006
|
+
acc = v;
|
|
2007
|
+
} else if (goal instanceof Struct && goal.name === 'not' && goal.args.length === 1) {
|
|
2008
|
+
const inner = flattenGoal(goal.args[0]), last = inner.at(-1);
|
|
2009
|
+
if (inner.length > 1 && last instanceof Struct && last.name === 'not' && last.args.length === 1 && !reaches(last)) {
|
|
2010
|
+
// A universal: every way its conditions hold, with all their
|
|
2011
|
+
// assumptions, must meet the consequence.
|
|
2012
|
+
const [body, w] = transform(inner.slice(0, -1), clause, EMPTY);
|
|
2013
|
+
const local = renameApart(conjunction([...body, last]));
|
|
2014
|
+
out.push(st('not', local));
|
|
2015
|
+
const ways = fresh(), union = fresh();
|
|
2016
|
+
out.push(st('findall', w, conjunction(body), ways), st('le:union', ways, union));
|
|
2017
|
+
add(union);
|
|
2018
|
+
} else {
|
|
2019
|
+
const [body, w] = transform(inner, clause, EMPTY);
|
|
2020
|
+
const ways = fresh(), denied = fresh();
|
|
2021
|
+
out.push(st('findall', w, conjunction(body), ways), st('le:no_empty', ways), st('le:negate', ways, acc, denied));
|
|
2022
|
+
add(denied);
|
|
2023
|
+
}
|
|
2024
|
+
} else if (goal instanceof Struct && (goal.name === 'findall' || goal.name === 'findall_sorted') && goal.args.length === 3) {
|
|
2025
|
+
const [template, inner, list] = goal.args;
|
|
2026
|
+
const [body, w] = transform(flattenGoal(inner), clause, EMPTY);
|
|
2027
|
+
const pairs = fresh(), ways = fresh(), union = fresh();
|
|
2028
|
+
out.push(st('findall', st('le:pair', template, w), conjunction(body), pairs), st('le:pairs', pairs, list, ways), st('le:union', ways, union));
|
|
2029
|
+
add(union);
|
|
2030
|
+
} else fail(clause);
|
|
2031
|
+
}
|
|
2032
|
+
return [out, acc];
|
|
2033
|
+
};
|
|
2034
|
+
const guardOf = (clause) => clause.guard ? { ...clause.guard, counter: { n: clause.guard.counter.n }, rule: false } : null;
|
|
2035
|
+
for (const clause of clauses) {
|
|
2036
|
+
if (!reach.has(keyOf(clause.head)) || clause.head.name === ANSWER) continue;
|
|
2037
|
+
const [body, u] = transform(clause.body ?? [], clause, EMPTY);
|
|
2038
|
+
emit('backward', new Struct(`${clause.head.name}:ab`, [...clause.head.args, u]), body, clause.line, clause.file, guardOf(clause));
|
|
2039
|
+
}
|
|
2040
|
+
// The assumptions themselves. A sentence is assumed when it is not proved
|
|
2041
|
+
// and not denied when it is asked, or when it is asked open.
|
|
2042
|
+
const assume = (sentence, line, file) => {
|
|
2043
|
+
const open = st('findall', 'x', st('is_ground', sentence), EMPTY);
|
|
2044
|
+
const closed = conjunction([st('is_ground', sentence), st('not', sentence), st('not', st('le:denied', sentence))]);
|
|
2045
|
+
emit('backward', new Struct(`${sentence.name}:ab`, [...sentence.args, list([sentence])]), [st('or', closed, open)], line, file);
|
|
2046
|
+
};
|
|
2047
|
+
for (const template of templates.filter((t) => t.assumable)) {
|
|
2048
|
+
const args = Array.from({ length: template.arity + (threaded ? 1 : 0) }, (_, i) => new Var(i === 0 && threaded ? 'Scenario' : `A${i}`));
|
|
2049
|
+
assume(new Struct(template.name, args), null, null);
|
|
2050
|
+
}
|
|
2051
|
+
for (const { term, line, file } of abducibles) assume(term, line, file);
|
|
2052
|
+
for (const { term, line, file } of denials) emit('fact', st('le:denied', term), [], line, file);
|
|
2053
|
+
// Whether an assumed sentence holds after all, relation by relation.
|
|
2054
|
+
for (const key of assumable) {
|
|
2055
|
+
const [name, arity] = [key.slice(0, key.lastIndexOf('/')), Number(key.slice(key.lastIndexOf('/') + 1))];
|
|
2056
|
+
const sentence = new Struct(name, Array.from({ length: arity }, (_, i) => new Var(`A${i}`)));
|
|
2057
|
+
emit('backward', st('le:holds', sentence), [sentence], null, null);
|
|
2058
|
+
}
|
|
2059
|
+
// Constraints: the relations they reach, with an answer's assumptions as
|
|
2060
|
+
// the only assumptions, NAME:w; a violation, and the sentence whose
|
|
2061
|
+
// assumption repairs it, or 'none'.
|
|
2062
|
+
if (constraints.length) {
|
|
2063
|
+
helpers.add('le:consistent');
|
|
2064
|
+
const world = closure(new Set([...constraints.flatMap((c) => c.goals.flatMap((g) => [...calls(g)]))]));
|
|
2065
|
+
const worldly = (goal, u) => {
|
|
2066
|
+
if (!(goal instanceof Struct)) return goal;
|
|
2067
|
+
if (world.has(keyOf(goal))) return new Struct(`${goal.name}:w`, [...goal.args, u]);
|
|
2068
|
+
return new Struct(goal.name, goal.args.map((arg) => worldly(arg, u)));
|
|
2069
|
+
};
|
|
2070
|
+
for (const clause of clauses) {
|
|
2071
|
+
if (!world.has(keyOf(clause.head)) || clause.head.name === ANSWER) continue;
|
|
2072
|
+
const u = new Var('U_');
|
|
2073
|
+
emit('backward', new Struct(`${clause.head.name}:w`, [...clause.head.args, u]), (clause.body ?? []).map((g) => worldly(g, u)), clause.line, clause.file, guardOf(clause));
|
|
2074
|
+
}
|
|
2075
|
+
for (const key of world) {
|
|
2076
|
+
if (!assumable.has(key)) continue;
|
|
2077
|
+
const [name, arity] = [key.slice(0, key.lastIndexOf('/')), Number(key.slice(key.lastIndexOf('/') + 1))];
|
|
2078
|
+
const args = Array.from({ length: arity }, (_, i) => new Var(`A${i}`)), u = new Var('U_');
|
|
2079
|
+
emit('backward', new Struct(`${name}:w`, [...args, u]), [st('le:member', new Struct(name, args), u)], null, null);
|
|
2080
|
+
}
|
|
2081
|
+
for (const constraint of constraints) {
|
|
2082
|
+
const u = new Var('U_');
|
|
2083
|
+
const negated = constraint.goals.find((g) => g instanceof Struct && g.name === 'not' && g.args.length === 1 && assumable.has(keyOf(g.args[0])));
|
|
2084
|
+
const fix = negated ? negated.args[0] : 'none';
|
|
2085
|
+
emit('backward', st('le:violation', constraint.scenario ?? 'none', u, fix), [...(constraint.scenario instanceof Var ? [st(SCENARIO, constraint.scenario)] : []),
|
|
2086
|
+
...constraint.goals.map((g) => worldly(g, u))], constraint.line, constraint.file,
|
|
2087
|
+
{ counter: { n: 0 }, scenario: constraint.scenario, rule: false });
|
|
2088
|
+
}
|
|
2089
|
+
}
|
|
2090
|
+
// Every answer gets the list of its unknowns, empty when it needs none.
|
|
2091
|
+
for (const clause of pending.filter((c) => c.head instanceof Struct && c.head.name === ANSWER)) {
|
|
2092
|
+
const final = fresh();
|
|
2093
|
+
if (clause.kind !== 'query') {
|
|
2094
|
+
const [body, u] = transform(clause.body, clause, EMPTY);
|
|
2095
|
+
const checked = constraints.length ? fresh() : final;
|
|
2096
|
+
clause.body = [...body, st('le:unknowns', u, checked), st('le:coherent', checked),
|
|
2097
|
+
...(constraints.length ? [st('le:consistent', threaded ? clause.head.args[1] : 'none', checked, final)] : [])];
|
|
2098
|
+
helpers.add('le:coherent');
|
|
2099
|
+
}
|
|
2100
|
+
clause.head = new Struct(ANSWER, [...clause.head.args, final]);
|
|
2101
|
+
}
|
|
2102
|
+
}
|
|
2103
|
+
|
|
2104
|
+
// A universal's check inside a negation: the variables of its assumption
|
|
2105
|
+
// lists stand for any value there, so they become anonymous, _100000 on.
|
|
2106
|
+
function renameApart(goal) {
|
|
2107
|
+
const map = new Map();
|
|
2108
|
+
const visit = (term) => {
|
|
2109
|
+
if (term instanceof Var && /^U\d+_$/.test(term.name)) {
|
|
2110
|
+
if (!map.has(term)) map.set(term, new Var(`_${100000 + map.size}`));
|
|
2111
|
+
return map.get(term);
|
|
2112
|
+
}
|
|
2113
|
+
if (term instanceof Struct) return new Struct(term.name, term.args.map(visit));
|
|
2114
|
+
return term;
|
|
2115
|
+
};
|
|
2116
|
+
return visit(goal);
|
|
2117
|
+
}
|
|
2118
|
+
|
|
2119
|
+
function flattenGoal(goal) {
|
|
2120
|
+
if (goal instanceof Struct && goal.name === 'and' && goal.args.length === 2) return [...flattenGoal(goal.args[0]), ...flattenGoal(goal.args[1])];
|
|
2121
|
+
return [goal];
|
|
2122
|
+
}
|
|
2123
|
+
|
|
1119
2124
|
function isGround(term) {
|
|
1120
2125
|
if (term instanceof Var) return false;
|
|
1121
2126
|
if (term instanceof Struct) return term.args.every(isGround);
|
|
@@ -1136,6 +2141,7 @@ function javascript(term) {
|
|
|
1136
2141
|
// A value as LE writes it: names as they are, dates as YYYY-MM-DD, lists in
|
|
1137
2142
|
// brackets and a sentence through its template.
|
|
1138
2143
|
function leValue(term, templates) {
|
|
2144
|
+
if (term instanceof Var) return '_';
|
|
1139
2145
|
if (typeof term === 'string') return term === EMPTY ? '[]' : term;
|
|
1140
2146
|
if (typeof term === 'bigint' || typeof term === 'number') return write(term);
|
|
1141
2147
|
if (term instanceof Struct) {
|
|
@@ -1177,36 +2183,85 @@ function sentence(query, values, templates) {
|
|
|
1177
2183
|
// The conclusions of a run: each query's answers in each scenario, as
|
|
1178
2184
|
// sentences, and any expected answers that differ from them.
|
|
1179
2185
|
export function writeLe(result, loaded) {
|
|
1180
|
-
const { templates, scenarios, threaded, queries, expectations } = loaded.compiled;
|
|
2186
|
+
const { templates, scenarios, threaded, queries, expectations, abductive } = loaded.compiled;
|
|
2187
|
+
// Per scenario and query, each answer with the sets of unknowns it rests
|
|
2188
|
+
// on; an answer that also holds without any is definite.
|
|
1181
2189
|
const found = new Map();
|
|
2190
|
+
// A negative assumption reads "it is not the case that S".
|
|
2191
|
+
const unknown = (term) => term instanceof Struct && term.name === 'le:not' && term.args.length === 1 ? `it is not the case that ${unknown(term.args[0])}`
|
|
2192
|
+
: leValue(threaded && term instanceof Struct ? new Struct(term.name, term.args.slice(1)) : term, templates);
|
|
1182
2193
|
for (const answer of result.answers) {
|
|
1183
2194
|
const term = readTerm(answer);
|
|
1184
2195
|
if (!(term instanceof Struct) || term.name !== ANSWER) continue;
|
|
1185
2196
|
const [name, ...rest] = term.args;
|
|
1186
2197
|
const scenario = threaded ? rest.shift() : null;
|
|
2198
|
+
const assumed = abductive ? listTerms(rest.pop()).map(unknown) : [];
|
|
1187
2199
|
const query = queries.find((q) => q.name === name);
|
|
1188
2200
|
if (!query) continue;
|
|
1189
2201
|
const key = `${scenario}\u0000${name}`;
|
|
1190
|
-
if (!found.has(key)) found.set(key,
|
|
1191
|
-
|
|
1192
|
-
|
|
2202
|
+
if (!found.has(key)) found.set(key, new Map());
|
|
2203
|
+
// A flip's answer is its changes: "add: S and remove: T".
|
|
2204
|
+
const flip = (changes) => listTerms(changes).map((c) => `${c.name}: ${leValue(c.args[0], templates)}`).sort().join(' and ') || 'no change is needed';
|
|
2205
|
+
const text = query.flip ? flip(rest[0]) : sentence(query, rest, templates), answers = found.get(key);
|
|
2206
|
+
if (!answers.has(text)) answers.set(text, []);
|
|
2207
|
+
const sets = answers.get(text), set = [...new Set(assumed)].sort();
|
|
2208
|
+
if (!sets.some((other) => other.join('\u0000') === set.join('\u0000'))) sets.push(set);
|
|
1193
2209
|
}
|
|
2210
|
+
// LE2 writes the underscores of names as spaces and repeats an answer for
|
|
2211
|
+
// each proof; expected answers are compared as a set, either way.
|
|
2212
|
+
// An expected number with decimals matches an answer's number rounded to
|
|
2213
|
+
// as many decimals, as LE2 compares them.
|
|
2214
|
+
const same = (a) => a.replaceAll('_', ' ').replace(/\s*-\s*/g, '-').replace(/\s+/g, ' ').trim();
|
|
2215
|
+
const matches = (want, got) => {
|
|
2216
|
+
const w = want.split(' '), g = got.split(' ');
|
|
2217
|
+
return w.length === g.length && w.every((word, i) => {
|
|
2218
|
+
if (word === g[i]) return true;
|
|
2219
|
+
const decimals = /^-?\d+\.(\d+)$/.exec(word);
|
|
2220
|
+
return decimals !== null && /^-?\d+(\.\d+)?(e[+-]?\d+)?$/.test(g[i]) && Number(g[i]).toFixed(decimals[1].length) === word;
|
|
2221
|
+
});
|
|
2222
|
+
};
|
|
2223
|
+
const equal = (a, b) => {
|
|
2224
|
+
const x = [...new Set(a.map(same))], y = [...new Set(b.map(same))];
|
|
2225
|
+
return x.every((w) => y.some((g) => matches(w, g))) && y.every((g) => x.some((w) => matches(w, g)));
|
|
2226
|
+
};
|
|
1194
2227
|
const blocks = [];
|
|
1195
2228
|
for (const scenario of threaded ? scenarios : [null]) {
|
|
1196
2229
|
for (const query of queries) {
|
|
1197
|
-
const answers = found.get(`${scenario}\u0000${query.name}`) ??
|
|
2230
|
+
const answers = found.get(`${scenario}\u0000${query.name}`) ?? new Map();
|
|
1198
2231
|
const title = scenario === null ? `% query ${query.name}` : `% query ${query.name} with scenario ${scenario}`;
|
|
1199
|
-
const lines = [title
|
|
1200
|
-
const
|
|
1201
|
-
|
|
1202
|
-
|
|
1203
|
-
|
|
1204
|
-
|
|
1205
|
-
|
|
1206
|
-
|
|
2232
|
+
const lines = [title];
|
|
2233
|
+
const unknowns = new Set();
|
|
2234
|
+
for (const [text, sets] of answers) {
|
|
2235
|
+
lines.push(`${text}.`);
|
|
2236
|
+
if (sets.some((set) => !set.length)) continue;
|
|
2237
|
+
sets.forEach((set, i) => lines.push(`% ${i ? 'or assuming' : 'assuming'} that ${set.join(' and ')}`));
|
|
2238
|
+
for (const set of sets) for (const u of set) unknowns.add(u);
|
|
2239
|
+
}
|
|
2240
|
+
if (!answers.size) lines.push('% no answers');
|
|
2241
|
+
// An expectation without "and unknowns", or with an empty list, wants
|
|
2242
|
+
// answers that rest on nothing; "and any unknowns" compares the answers.
|
|
2243
|
+
for (const expected of expectations.filter((e) => e.scenario === scenario && e.query === query.name)) {
|
|
2244
|
+
if (expected.changes) {
|
|
2245
|
+
const sets = expected.changes.map((set) => [...set].sort().join(' and ') || 'no change is needed');
|
|
2246
|
+
if (!equal(sets, [...answers.keys()])) {
|
|
2247
|
+
lines.push(`% not as expected: ${query.name} expects changes [${expected.changes.map((set) => `[${set.map((c) => JSON.stringify(c)).join(', ')}]`).join(', ')}]`);
|
|
2248
|
+
}
|
|
2249
|
+
continue;
|
|
2250
|
+
}
|
|
2251
|
+
const ok = equal(expected.answers, [...answers.keys()]) && (expected.unknowns === 'any' || equal(expected.unknowns, [...unknowns]));
|
|
2252
|
+
if (ok) continue;
|
|
2253
|
+
const quoted = (items) => `[${items.map((a) => JSON.stringify(a)).join(', ')}]`;
|
|
2254
|
+
const tail = expected.unknowns === 'any' ? ' and any unknowns' : expected.unknowns.length ? ` and unknowns ${quoted(expected.unknowns)}` : '';
|
|
2255
|
+
lines.push(`% not as expected: ${query.name} expects answers ${quoted(expected.answers)}${tail}`);
|
|
1207
2256
|
}
|
|
1208
2257
|
blocks.push(lines.join('\n'));
|
|
1209
2258
|
}
|
|
1210
2259
|
}
|
|
1211
2260
|
return blocks.length ? blocks.join('\n\n') + '\n' : '% no queries\n';
|
|
1212
2261
|
}
|
|
2262
|
+
|
|
2263
|
+
function listTerms(term) {
|
|
2264
|
+
const items = [];
|
|
2265
|
+
while (term instanceof Struct && term.name === '.' && term.args.length === 2) { items.push(term.args[0]); term = term.args[1]; }
|
|
2266
|
+
return items;
|
|
2267
|
+
}
|