eyemind 0.9.0 → 0.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LE-SPEC.md CHANGED
@@ -20,15 +20,26 @@ ends with `:`:
20
20
 
21
21
  | Header | Section |
22
22
  | --- | --- |
23
- | `the templates are:`, `the predicates are:` | Templates, separated by commas or full stops. |
23
+ | `the templates are:`, `the predicates are:` | Templates, separated by full stops, and by commas at the end of a line or before a place. |
24
24
  | `the knowledge base NAME includes:`, `the contract NAME states that:` | Facts and rules. |
25
25
  | `the ontology is:` | Facts and rules; a fact `a student is a person.` relates the kinds `student` and `person`. |
26
+ | `the constants are:` | Named values, one sentence each: `the fee is 5.` |
27
+ | `the knowledge base NAME includes these resources:` | Other files, separated by commas, whose templates, facts, rules, ontologies and constants join the document. |
28
+ | `the knowledge base NAME includes these scenarios:` | Other files, as resources, whose scenarios and queries join the document too. |
26
29
  | `scenario NAME is:` | Facts and rules of one scenario, and its expected answers. |
27
30
  | `query NAME is:` | One query. |
28
31
 
29
- `the target language is: prolog.` is accepted and ignored. The sections can
30
- come in any order, and a template can be used before it is declared. Several
31
- `.le` files are read as one document.
32
+ `the target language is: prolog.` is accepted and ignored, and so are LE2's
33
+ section markers, `section NAME is:` and `the annexes to the contract are:`,
34
+ and its rule labels, `rule NAME:` before a rule. The sections can come in any
35
+ order, and a template can be used before it is declared. Several `.le` files
36
+ are read as one document.
37
+
38
+ An included file is named as in LE2: a path relative to the file that
39
+ includes it, without `.le` if one likes. It is read once, and a chain of
40
+ includes stops at five. The command line reads included files; the library
41
+ reads them through `io.readFile` when `compileLe(inputs, io)` is given one.
42
+ Web addresses and Prolog resources (`.pl`) are not read.
32
43
 
33
44
  Sentences end with a full stop followed by white space or the end of the file;
34
45
  a sentence can span lines. `%` or `#` starts a comment through the end of the
@@ -57,7 +68,20 @@ Each template is a relation whose name joins its words with underscores and
57
68
  whose arguments are its places in order: `acquires_British_citizenship_on/2`,
58
69
  `says_that/2`, `has/2`. A name that is an LS primitive or control, or `date`,
59
70
  gets the prefix `le_`. Two templates with different words for one name and
60
- arity are an error. A place after the word `that` holds a sentence.
71
+ arity are an error. A place after the word `that` holds a sentence. A document
72
+ with an asterisk in any template reads `a` and `an` in its other templates as
73
+ words.
74
+
75
+ LE2's additions follow a template after `;`:
76
+
77
+ | Addition | Meaning in eyemind |
78
+ | --- | --- |
79
+ | `; synonym TEMPLATE` | A second wording of the same relation, with its places in the same order. |
80
+ | `; opposite: TEMPLATE`, `; opposite TEMPLATE` | The wording of a separate relation, concluded only by its own rules and by `only if` rules. |
81
+ | `; assumable`, `; unknown`, `; assumed`, `; judged`, `; open textured`, `; evaluative` | eyemind makes no assumptions: a sentence that is not stated or concluded is false. A negated assumable sentence is an error, because it would hold only as an assumption. |
82
+ | `; memorable`, `; memoised`, `; memoized`, `; cached`, `; undefined`, `; scenario element`, `; one value`, `; single valued`, `; image ...` | Nothing that eyemind computes changes. |
83
+
84
+ Other additions, such as `; prepositional` and `; via service NAME`, are errors.
61
85
 
62
86
  ## Sentences
63
87
 
@@ -90,6 +114,11 @@ The tokens in a place are a term:
90
114
  - A single capital letter with optional digits, such as `L` or `T1`, is a
91
115
  variable even when no phrase introduced it. Longer ids need an introducing
92
116
  phrase, because LE1 programs use acronyms such as `GST` as names.
117
+ - `*a name*` between asterisks, LE2's explicit variable, is the variable of
118
+ that phrase, introduced or referred to.
119
+ - A lone `which`, `what`, `who`, `when` or `where` introduces a variable.
120
+ - A phrase that names a constant of `the constants are:` is its value, unless a
121
+ variable of the clause has that name.
93
122
  - Other words are a name, written as they are, such as `Socrates` or
94
123
  `cash at bank`.
95
124
 
@@ -103,7 +132,15 @@ In a knowledge base or a scenario, a sentence is a fact, or a rule
103
132
  type template `*an object* is a *type*` (the relation `is_a/2`, whose type is a
104
133
  name). A fact with a variable holds for every value. In an ontology, a fact
105
134
  whose subject starts with `a` or `an` is about the kind: `a student is a person.`
106
- states `is_a('student', 'person')`.
135
+ states `is_a('student', 'person')`. An ontology's kinds are transitive: for
136
+ each such ground fact `b is a c`, whatever is a `b` is a `c`. A fact or rule
137
+ may end with LE2's `; image ...`, which is ignored.
138
+
139
+ `Head only if Body.` makes Body necessary for Head, as in LE2: it concludes the
140
+ opposite of Head, the template's `; opposite` wording or else an internal
141
+ relation, when it is not the case that Body. The other rules of Head's relation
142
+ then conclude a base relation, and Head holds when the base holds and its
143
+ opposite does not.
107
144
 
108
145
  The conditions are joined by `and` and `or`. Each connective has the
109
146
  indentation of its line; a connective in the middle of a line has the
@@ -204,7 +241,10 @@ scenario alice is:
204
241
  ```
205
242
 
206
243
  `NAME expects answers [...]` and `NAME expects [...]` state the answers the
207
- query `NAME` gives in the scenario; a trailing `and unknowns [...]` is ignored.
244
+ query `NAME` gives in the scenario. The answers may be quoted sentences or, as
245
+ some examples write them, words up to a comma. An expectation with
246
+ `and unknowns [...]` that lists unknowns, or with `and any unknowns`, rests on
247
+ assumptions and is not compared; `and unknowns []` is.
208
248
  Each query is answered in each scenario, or once when the document has none.
209
249
 
210
250
  ## Compilation to LS
@@ -261,12 +301,15 @@ establishes the answers under the compiled rules.
261
301
  ## Not supported
262
302
 
263
303
  These belong to Logical English 2, or to the Prolog that LE1 can embed, and
264
- are errors: template additions after `;`, `the constants are:`,
304
+ are errors: the template additions the table above leaves out,
265
305
  `the functions are:`, `the fluents are:`, `the events are:` and the other
266
- dynamic and meta sections, included resources and scenarios, section markers,
267
- rule labels, `it is unknown whether`, `it must not be true that`, negated
268
- facts in scenarios, flip queries (`expects changes`), `otherwise`, `unless`,
269
- `according to`, decision tables, services, LPS and s(CASP). eyemind does not
306
+ dynamic and meta sections, facts backgrounds, included web addresses and
307
+ Prolog resources, embedded `prolog` goals, numbered conditions, provenance
308
+ trailers and document locations, `it is unknown whether`,
309
+ `it must not be true that`, negated facts in scenarios, negated assumable
310
+ sentences (abduction), flip queries (`expects changes`), scenario headers with
311
+ provenance, `otherwise`, `unless`, `according to`, decision tables, services,
312
+ LPS and s(CASP). eyemind does not
270
313
  check types: the head noun of a place is not a type constraint. A program whose
271
314
  negation lies on a dependency cycle compiles, and the LS program is then
272
315
  rejected unless it is chain-stratified (LS-SPEC Section 6.4), where Prolog would
package/LS-SPEC.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  ```text
4
4
  Title: The Logic Script (LS) Language and Proof Format
5
- Version: eyemind 0.9.0
5
+ Version: eyemind 0.9.1
6
6
  ```
7
7
 
8
8
  This document specifies Logic Script (LS): the syntax and meaning of its
package/README.md CHANGED
@@ -253,9 +253,10 @@ the program reads the English as intended is a matter of the compiler. Several
253
253
  `.le` files form one document, without other input formats or RDF logic
254
254
  switches.
255
255
 
256
- Template additions, constants, functions, ontologies with type checking,
257
- unknowns, constraints, sections, included resources, LPS and s(CASP) belong to
258
- Logical English 2 and are reported as unsupported. Every `npm test` scores the
256
+ Of Logical English 2, eyemind also reads constants, included files, rule labels,
257
+ `only if` rules and the template additions `synonym`, `opposite` and those that
258
+ change nothing it computes. Abduction (assumptions and constraints), functions,
259
+ type checking, embedded Prolog, LPS and s(CASP) are reported as unsupported. Every `npm test` scores the
259
260
  [Logical English 2 examples](test/UPSTREAM.md) that state their expected
260
261
  answers, as coverage: a wrong answer fails the run, a file that uses an
261
262
  unsupported feature is counted as not passed.
@@ -758,7 +759,7 @@ console.log(result.bindings);
758
759
  console.log(checkProof(socrates, result.proof, { goals }).valid);
759
760
  ```
760
761
 
761
- `run()` returns `conclusions`, `answers`, `bindings`, `inferred`, `stdout`, `proof`, `proofReport`, `stats` and `haltCode`, and takes `goal`, `goals`, `proof`, `maxDepth`, `maxIterations` and `maxInferences`; exceeding a bound throws an `EyemindError`. `conclusions` holds the answer terms; `answers`, `bindings` and `stdout` are rendered when first read. Ground N3 conclusions are written directly from their terms. `loadSources([[text, filename], ...], io)` loads several sources as one program; pass `nodeIO` from `eyemind/node` as `io` to let `facts_from(path)` read files. `checkProof(program, document, { goals })` checks a proof. `checkReport`, `readTerm`, `readTerms` and `write` format reports and read and write the canonical text. `compileLe([[text, filename], ...])` returns the compiled LS `program` and standalone JavaScript `text`; `writeLe(run(loaded.program), loaded)` writes the answers as LE sentences, given the value `loaded` that `compileLe` returned.
762
+ `run()` returns `conclusions`, `answers`, `bindings`, `inferred`, `stdout`, `proof`, `proofReport`, `stats` and `haltCode`, and takes `goal`, `goals`, `proof`, `maxDepth`, `maxIterations` and `maxInferences`; exceeding a bound throws an `EyemindError`. `conclusions` holds the answer terms; `answers`, `bindings` and `stdout` are rendered when first read. Ground N3 conclusions are written directly from their terms. `loadSources([[text, filename], ...], io)` loads several sources as one program; pass `nodeIO` from `eyemind/node` as `io` to let `facts_from(path)` read files. `checkProof(program, document, { goals })` checks a proof. `checkReport`, `readTerm`, `readTerms` and `write` format reports and read and write the canonical text. `compileLe([[text, filename], ...], io)` returns the compiled LS `program` and standalone JavaScript `text`, reading included files with `io.readFile` when given; `writeLe(run(loaded.program), loaded)` writes the answers as LE sentences, given the value `loaded` that `compileLe` returned.
762
763
 
763
764
  Further entry points serve applications built on the formats and profiles:
764
765
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "eyemind",
3
- "version": "0.9.0",
3
+ "version": "0.9.1",
4
4
  "description": "A dependency-free Logic Script (LS) reasoner with forward and backward reasoning, checkable proofs, and RDF 1.2, Notation3 (N3), SPARQL 1.2 RL (SRL) and Logical English (LE) interoperability.",
5
5
  "type": "module",
6
6
  "main": "./src/index.js",
package/src/formats.js CHANGED
@@ -124,7 +124,7 @@ function load(inputs, io, { base = null, messageInputs = null, srlContext = null
124
124
  if (kinds.some((kind) => kind !== 'le') || odrl || profiles.length) {
125
125
  throw new EyemindError('a Logical English run takes .le files without RDF logic switches or other input formats');
126
126
  }
127
- return compileLe(inputs);
127
+ return compileLe(inputs, io);
128
128
  }
129
129
  if (profiles.length && odrl) {
130
130
  if (inputs.length !== 1) throw new EyemindError(`--odrl with ${switches} takes one Turtle snapshot containing policies, requests and SOTW`);
package/src/le.js CHANGED
@@ -27,7 +27,7 @@ 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
- 'the constants are', 'the functions are', 'the fluents are', 'the events are',
30
+ 'the functions are', 'the fluents are', 'the events are',
31
31
  'the event predicates are', 'the meta predicates are', 'the meta templates are', 'the facts background includes',
32
32
  ];
33
33
 
@@ -366,7 +366,16 @@ class Compiler {
366
366
  }
367
367
  return list(items);
368
368
  }
369
+ // LE2's explicit variable: *a name*.
370
+ if (first.text === '*' && tokens.at(-1).text === '*' && tokens.length > 2 && tokens.slice(1, -1).every((t) => t.kind === 'word')) {
371
+ const words = tokens.slice(1, -1), named = INTRODUCING.has(lower(words[0])) || isWord(words[0], 'the') ? words.slice(1) : words;
372
+ return this.mark(scope, scope.find(named) ?? scope.introduce(named.length ? named : words), this.offset(tokens), tokens.length);
373
+ }
369
374
  if (!tokens.every((t) => t.kind === 'word' || t.kind === 'number' || t.text === '&')) return null;
375
+ // A lone which, what, who, when or where asks for a value.
376
+ if (tokens.length === 1 && isWord(first, 'which', 'what', 'who', 'when', 'where')) {
377
+ return this.mark(scope, scope.introduce([{ ...first, text: first.text[0].toUpperCase() + first.text.slice(1) }]), this.offset(tokens), 1);
378
+ }
370
379
  const head = lower(first), rest = tokens.slice(1);
371
380
  // A kind is a name, unless a phrase such as "which type" asks for it.
372
381
  if (type && !(INTRODUCING.has(head) && rest.length && scope.find(rest) === undefined && rest.length <= 2)) return tokens.map((t) => t.text).join(' ');
@@ -374,13 +383,16 @@ class Compiler {
374
383
  if (INTRODUCING.has(head) && !(first.text === 'A' && tokens.length === 1) && rest.length && rest.length <= 6 && rest.every((t) => t.kind === 'word' && !isWord(t, 'that', 'if'))) {
375
384
  return this.mark(scope, scope.introduce(rest), at, tokens.length);
376
385
  }
386
+ const constant = this.constants?.get(tokens.map((t) => t.text.toLowerCase()).join(' '));
377
387
  if (head === 'the' && rest.length) {
378
388
  const found = scope.find(rest);
379
389
  if (found) return this.mark(scope, found, at, tokens.length);
390
+ if (constant !== undefined) return constant;
380
391
  return ['the', ...rest.map((t) => t.text)].join(' ');
381
392
  }
382
393
  const found = scope.find(tokens);
383
394
  if (found) return this.mark(scope, found, at, tokens.length);
395
+ if (constant !== undefined) return constant;
384
396
  if (tokens.length === 1 && BARE_ID.test(first.text) && !this.fact) return this.mark(scope, scope.introduce(tokens), at, 1);
385
397
  return tokens.map((t) => t.text).join(' ');
386
398
  }
@@ -825,11 +837,24 @@ function sections(tokens, file) {
825
837
  }
826
838
  if (startsWith(tokens, ['the', 'knowledge', 'base'], i)) {
827
839
  const at = colon(i);
828
- const includes = at > 0 && isWord(tokens[at - 1], 'includes');
829
- if (!includes) {
830
- if (at > 0 && startsWith(tokens, ['includes', 'these'], at - 3)) error('included resources and scenarios belong to Logical English 2 and are not supported', line);
831
- error('expected "the knowledge base NAME includes:"', line);
840
+ // "includes these resources:" or "includes these scenarios:" names other
841
+ // files, separated by commas, up to a full stop.
842
+ if (at > 0 && startsWith(tokens, ['includes', 'these'], at - 3) && isWord(tokens[at - 1], 'resources', 'scenarios')) {
843
+ let end = at + 1;
844
+ while (tokens[end].kind !== 'stop' && tokens[end].kind !== 'end') end++;
845
+ const names = [];
846
+ let name = [];
847
+ for (const t of [...tokens.slice(at + 1, end), { text: ',' }]) {
848
+ if (t.text !== ',') { name.push(t.text); continue; }
849
+ if (name.length) names.push(name.join(''));
850
+ name = [];
851
+ }
852
+ out.push(['include', lower(tokens[at - 1]), names, line]);
853
+ i = end + 1;
854
+ continue;
832
855
  }
856
+ const includes = at > 0 && isWord(tokens[at - 1], 'includes');
857
+ if (!includes) error('expected "the knowledge base NAME includes:"', line);
833
858
  section = { kind: 'kb', name: tokens.slice(i + 3, at - 1).map((t) => t.text).join(' ') };
834
859
  i = at + 1;
835
860
  continue;
@@ -845,14 +870,26 @@ function sections(tokens, file) {
845
870
  }
846
871
  if (at > 0) error(`the header "${phrase(tokens.slice(i, at + 1))}" belongs to Logical English 2 and is not supported`, line);
847
872
  }
848
- // LE2 labels a rule with "rule NAME:".
849
- if (isWord(tokens[i], 'rule') && colon(i) > i + 1 && colon(i) < i + 5 && tokens.slice(i + 1, colon(i)).every((t) => t.kind === 'word')) {
850
- error('rule labels belong to Logical English 2 and are not supported', line);
873
+ // LE2 labels a rule with "rule NAME:", and marks sections of rules with
874
+ // "section NAME is:" or "the annexes to the contract are:". Neither
875
+ // changes what the rules mean.
876
+ if (isWord(tokens[i], 'rule') && colon(i) > i + 1 && colon(i) < i + 5 && tokens.slice(i + 1, colon(i)).every((t) => t.kind === 'word' || t.kind === 'number')) {
877
+ i = colon(i) + 1;
878
+ continue;
851
879
  }
852
- const unsupported = SECTIONS.find((words) => startsWith(tokens, words.split(' '), i));
853
- if (unsupported || (startsWith(tokens, ['section'], i) && tokens[i].bol && colon(i) > 0)) {
854
- error(`the section "${unsupported ?? 'section'}" belongs to Logical English 2 and is not supported`, line);
880
+ if ((isWord(tokens[i], 'section') && tokens[i].bol && colon(i) > 0 && isWord(tokens[colon(i) - 1], 'is')) ||
881
+ (startsWith(tokens, ['the', 'annexes', 'to', 'the'], i) && colon(i) > 0 && isWord(tokens[colon(i) - 1], 'are'))) {
882
+ i = colon(i) + 1;
883
+ continue;
884
+ }
885
+ // LE2's named constants: "the fee is 5."
886
+ if (startsWith(tokens, ['the', 'constants', 'are', ':'], i)) {
887
+ section = { kind: 'constants' };
888
+ i += 4;
889
+ continue;
855
890
  }
891
+ const unsupported = SECTIONS.find((words) => startsWith(tokens, words.split(' '), i));
892
+ if (unsupported) error(`the section "${unsupported}" belongs to Logical English 2 and is not supported`, line);
856
893
  let end = i;
857
894
  while (tokens[end].kind !== 'stop' && tokens[end].kind !== 'end') end++;
858
895
  if (tokens[end].kind === 'end') error(`a sentence must end with a full stop: "${phrase(tokens.slice(i, Math.min(end, i + 12)))}"`, line);
@@ -877,6 +914,8 @@ function sections(tokens, file) {
877
914
  start = k + 1;
878
915
  }
879
916
  for (const part of parts) out.push(['template', null, part, part[0].line]);
917
+ } else if (section.kind === 'constants') {
918
+ out.push(['constant', null, sentence, line]);
880
919
  } else if (section.kind === 'query') {
881
920
  out.push(['query', section.name, sentence, line]);
882
921
  section = { kind: 'after query' };
@@ -890,26 +929,93 @@ function sections(tokens, file) {
890
929
  return out;
891
930
  }
892
931
 
893
- export function compileLe(inputs) {
894
- const items = [];
932
+ // The ways LE2 lets a template be read, after ";": additions that change
933
+ // nothing eyemind computes, and additions that make a sentence assumable.
934
+ const IGNORED = ['memorable', 'memoised', 'memoized', 'cached', 'undefined', 'scenario element', 'one value', 'single valued'];
935
+ const ASSUMABLE = ['assumable', 'unknown', 'assumed', 'judged', 'open textured', 'evaluative'];
936
+
937
+ // io.readFile reads an included file. The paths of an included file's own
938
+ // includes are relative to it; a chain of includes stops at five.
939
+ export function compileLe(inputs, io = null) {
940
+ const items = [], read = new Set();
941
+ const load = (text, file, keep, depth) => {
942
+ for (const item of sections(tokenize(String(text), file), file)) {
943
+ if (item[0] === 'include') {
944
+ const [, kind, names, line] = item;
945
+ const fail = (message) => { throw new EyemindError(`${file}: line ${line}: Logical English: ${message}`); };
946
+ for (const name of names) {
947
+ if (/^[a-z]+:/i.test(name)) fail(`including the web address ${name} belongs to Logical English 2 and is not supported; include a local file`);
948
+ if (/\.pl$/.test(name)) fail(`including the Prolog resource ${name} belongs to Logical English 2 and is not supported`);
949
+ const dir = String(file).includes('/') ? String(file).slice(0, String(file).lastIndexOf('/') + 1) : '';
950
+ const path = dir + name + (name.endsWith('.le') ? '' : '.le');
951
+ if (read.has(path)) continue;
952
+ if (depth >= 5) fail(`including ${name} makes a chain of more than five includes`);
953
+ if (!io?.readFile) fail(`including ${name} needs file access`);
954
+ let included;
955
+ try { included = io.readFile(path); } catch { fail(`cannot read the included file ${path}`); }
956
+ read.add(path);
957
+ // A resource gives its templates, rules, facts and ontology; an
958
+ // included scenario file also gives its scenarios and queries.
959
+ load(included, path, kind === 'scenarios', depth + 1);
960
+ }
961
+ continue;
962
+ }
963
+ if (!keep && ['scenario', 'scenario clause', 'query'].includes(item[0])) continue;
964
+ items.push([...item, file]);
965
+ }
966
+ };
895
967
  for (const [text, file] of inputs) {
896
- for (const item of sections(tokenize(String(text), file), file)) items.push([...item, file]);
968
+ read.add(String(file));
969
+ load(text, file, true, 0);
897
970
  }
898
971
  // Templates first: a sentence can use a template declared after it.
899
972
  const templates = [], byName = new Map();
900
973
  const starred = items.some((item) => item[0] === 'template' && item[2].some((t) => t.text === '*'));
901
- for (const [kind, , tokens, line, file] of items.filter((item) => item[0] === 'template')) {
902
- const error = (message, at = line) => { throw new EyemindError(`${file}: line ${at}: Logical English: ${message}`); };
974
+ const declare = (tokens, error, relation = null) => {
903
975
  const parts = readTemplate(tokens, error, starred);
904
- const name = templateName(parts), arity = parts.filter((p) => p.place).length, key = `${name}/${arity}`;
905
- if (byName.has(key)) {
976
+ const arity = parts.filter((p) => p.place).length;
977
+ if (relation && relation.arity !== arity) error(`a synonym needs the ${relation.arity} places of "${relation.text}"`);
978
+ const name = relation?.name ?? templateName(parts), key = `${name}/${arity}`;
979
+ if (!relation && byName.has(key)) {
906
980
  const other = byName.get(key);
907
- if (other.parts.map((p) => p.word ?? '*').join(' ') === parts.map((p) => p.word ?? '*').join(' ')) continue;
981
+ if (other.parts.map((p) => p.word ?? '*').join(' ') === parts.map((p) => p.word ?? '*').join(' ')) return other;
908
982
  error(`the templates "${other.text}" and "${phrase(tokens)}" both name the relation ${name}/${arity}; change a word of one`);
909
983
  }
910
984
  const template = { parts, name, arity, words: parts.filter((p) => p.word).length, text: phrase(tokens) };
911
- byName.set(key, template);
985
+ if (!relation) byName.set(key, template);
912
986
  templates.push(template);
987
+ return template;
988
+ };
989
+ for (const [, , tokens, line, file] of items.filter((item) => item[0] === 'template')) {
990
+ const error = (message, at = line) => { throw new EyemindError(`${file}: line ${at}: Logical English: ${message}`); };
991
+ // A template, then its additions after ";".
992
+ const pieces = [[]];
993
+ let inside = false;
994
+ for (const t of tokens) {
995
+ if (t.text === '*') inside = !inside;
996
+ if (t.text === ';' && !inside) pieces.push([]);
997
+ else pieces.at(-1).push(t);
998
+ }
999
+ const template = declare(pieces[0], error);
1000
+ for (const addition of pieces.slice(1)) {
1001
+ const words = addition.map((t) => t.text.toLowerCase()).join(' ');
1002
+ if (IGNORED.includes(words) || isWord(addition[0] ?? {}, 'image')) continue;
1003
+ if (ASSUMABLE.includes(words)) { template.assumable = true; continue; }
1004
+ // A synonym is another wording of the same relation; an opposite is the
1005
+ // wording of a separate relation, which only its own rules conclude.
1006
+ if (isWord(addition[0] ?? {}, 'synonym')) { declare(addition.slice(1), error, template); continue; }
1007
+ if (isWord(addition[0] ?? {}, 'opposite')) { template.opposite = declare(addition.slice(addition[1]?.text === ':' ? 2 : 1), error); continue; }
1008
+ error(`the template addition "; ${phrase(addition)}" belongs to Logical English 2 and is not supported`);
1009
+ }
1010
+ }
1011
+ // Named constants: "the fee is 5." The name stands for the value wherever
1012
+ // no variable of the clause has that name.
1013
+ const constants = new Map();
1014
+ for (const [, , tokens, line, file] of items.filter((item) => item[0] === 'constant')) {
1015
+ const at = tokens.findLastIndex((t) => isWord(t, 'is'));
1016
+ const value = at > 0 ? new Compiler(file, []).term(tokens.slice(at + 1), new Scope()) : null;
1017
+ if (value === null || value instanceof Var) throw new EyemindError(`${file}: line ${line}: Logical English: a constant is written "the fee is 5."`);
1018
+ constants.set(tokens.slice(0, at).map((t) => t.text.toLowerCase()).join(' '), value);
913
1019
  }
914
1020
  const scenarios = [];
915
1021
  for (const [kind, name, , line, file] of items) {
@@ -918,7 +1024,7 @@ export function compileLe(inputs) {
918
1024
  scenarios.push(name);
919
1025
  }
920
1026
  const threaded = scenarios.length > 0;
921
- const clauses = [], sources = [], queries = [], expectations = [], helpers = new Set(), pending = [];
1027
+ const clauses = [], sources = [], queries = [], expectations = [], helpers = new Set(), pending = [], necessary = new Map();
922
1028
  // Clauses wait until every one is read: their negations depend on whether
923
1029
  // any fact or rule leaves a variable of its conclusion open.
924
1030
  const emit = (kind, head, body, line, file, guard = null) => pending.push({ kind, head, body, line, file, guard });
@@ -946,9 +1052,10 @@ export function compileLe(inputs) {
946
1052
  // says that b is a c. One rule per such fact keeps the dependencies of
947
1053
  // rules that negate other kinds apart.
948
1054
  const kinds = [];
949
- for (const [kind, name, tokens, line, file] of items) {
950
- if (kind === 'template' || kind === 'scenario') continue;
1055
+ for (let [kind, name, tokens, line, file] of items) {
1056
+ if (kind === 'template' || kind === 'scenario' || kind === 'constant') continue;
951
1057
  const compiler = new Compiler(file, templates);
1058
+ compiler.constants = constants;
952
1059
  const scope = new Scope();
953
1060
  if (kind === 'query') {
954
1061
  compiler.scenario = threaded ? new Var('Scenario') : null;
@@ -967,7 +1074,8 @@ export function compileLe(inputs) {
967
1074
  const head = st(ANSWER, name, ...(threaded ? [compiler.scenario] : []), ...answer);
968
1075
  emit('backward', head, threaded ? [st(SCENARIO, compiler.scenario), ...goals] : goals, line, file, { counter, scenario: compiler.scenario });
969
1076
  emit('query', head, [], line, file);
970
- queries.push({ name, tokens: body.map((t) => t.text), marks: scope.marks.map(({ at, length, variable }) => ({ at, length, slot: answer.indexOf(variable) })) });
1077
+ // A quoted name is written as the name, as LE writes its answers.
1078
+ queries.push({ name, tokens: body.map((t) => t.kind === 'string' ? t.value : t.text), marks: scope.marks.map(({ at, length, variable }) => ({ at, length, slot: answer.indexOf(variable) })) });
971
1079
  for (const h of compiler.helpers) helpers.add(h);
972
1080
  continue;
973
1081
  }
@@ -995,7 +1103,8 @@ export function compileLe(inputs) {
995
1103
  };
996
1104
  const [answers, close] = list(expects + 1 + (isWord(tokens[expects + 1] ?? {}, 'answers') ? 1 : 0));
997
1105
  // Expected unknowns are assumptions eyemind does not make.
998
- const unknowns = startsWith(tokens, ['and', 'unknowns'], close + 1) ? list(close + 3)[0] : [];
1106
+ const unknowns = startsWith(tokens, ['and', 'unknowns'], close + 1) ? list(close + 3)[0]
1107
+ : startsWith(tokens, ['and', 'any', 'unknowns'], close + 1) ? ['any'] : [];
999
1108
  expectations.push({ scenario: name, query: tokens.slice(0, expects).map((t) => t.text).join(' '), answers, unknowns, line });
1000
1109
  continue;
1001
1110
  }
@@ -1004,9 +1113,19 @@ export function compileLe(inputs) {
1004
1113
  compiler.error('unknowns, constraints and negated facts belong to Logical English 2 and are not supported', line);
1005
1114
  }
1006
1115
  compiler.scenario = !threaded ? null : inScenario ? name : new Var('Scenario');
1116
+ // A fact may carry LE2's picture, "; image ...", which changes nothing.
1117
+ const semicolon = tokens.findIndex((t) => t.text === ';');
1118
+ if (semicolon > 0 && isWord(tokens[semicolon + 1] ?? {}, 'image')) tokens = tokens.slice(0, semicolon);
1007
1119
  const level = depths(tokens);
1008
1120
  const ifAt = tokens.findIndex((t, k) => level[k] === 0 && isWord(t, 'if'));
1009
- let headTokens = ifAt < 0 ? tokens : tokens.slice(0, ifAt);
1121
+ for (const [words, what] of [[['prolog'], 'embedded Prolog goals'], [['with', 'provenance'], 'provenance trailers'], [['is', 'published', 'at'], 'document locations']]) {
1122
+ if (indexOfWords(tokens, words) >= 0) compiler.error(`${what} belong to Logical English 2 and are not supported`, line);
1123
+ }
1124
+ if (ifAt >= 0 && tokens[ifAt + 1]?.text === ':') compiler.error('numbered conditions belong to Logical English 2 and are not supported', line);
1125
+ // "Head only if Body" makes Body necessary: the opposite of the head holds
1126
+ // when Body does not, and the head then fails.
1127
+ const onlyIf = ifAt > 0 && isWord(tokens[ifAt - 1], 'only');
1128
+ let headTokens = ifAt < 0 ? tokens : tokens.slice(0, onlyIf ? ifAt - 1 : ifAt);
1010
1129
  // In an ontology, "a student is a person" is about the kinds themselves.
1011
1130
  if (kind === 'ontology clause' && ifAt < 0 && isWord(headTokens[0], 'a', 'an') && !isWord(headTokens[1] ?? {}, 'is')) headTokens = headTokens.slice(1);
1012
1131
  if (!headTokens.length) compiler.error('a rule needs a conclusion before "if"', line);
@@ -1029,6 +1148,16 @@ export function compileLe(inputs) {
1029
1148
  if (ifAt === tokens.length - 1) compiler.error('a rule needs conditions after "if"', line);
1030
1149
  // LE1 also writes "if" followed by a line that starts with "and".
1031
1150
  const goals = compiler.body(tokens.slice(ifAt + (isWord(tokens[ifAt + 1], 'and') ? 2 : 1)), scope);
1151
+ if (onlyIf) {
1152
+ const template = templates.find((t) => t.name === head.name && t.arity === head.args.length && t.opposite);
1153
+ const opposite = compiler.relation(template ? template.opposite.name : `${head.name}:not`, head.args);
1154
+ const body = [st('not', conjunction(goals))];
1155
+ const counter = { n: anonymize(opposite, body) };
1156
+ emit('backward', opposite, body, line, file, { counter, scenario: compiler.scenario, rule: true });
1157
+ necessary.set(`${head.name}/${headTerm.args.length}`, { name: head.name, opposite: opposite.name, arity: headTerm.args.length, line, file });
1158
+ for (const h of compiler.helpers) helpers.add(h);
1159
+ continue;
1160
+ }
1032
1161
  const counter = { n: anonymize(headTerm, goals) };
1033
1162
  emit('backward', headTerm, goals, line, file, { counter, scenario: compiler.scenario, rule: true });
1034
1163
  for (const h of compiler.helpers) helpers.add(h);
@@ -1038,6 +1167,29 @@ export function compileLe(inputs) {
1038
1167
  // variables at run time.
1039
1168
  const open = pending.some(({ kind, head, body, guard }) => kind !== 'query' && (guard ? guard.rule : true) &&
1040
1169
  [...varsOf(head)].some((v) => !/^_\d+$/.test(v.name) && v.name !== 'Scenario' && !openVariables(body).includes(v)));
1170
+ // A relation with "only if" rules holds by its other rules, through a base
1171
+ // relation, unless its opposite holds.
1172
+ for (const [key, { name, opposite, arity, line, file }] of necessary) {
1173
+ const base = `${name}:if`;
1174
+ for (const clause of pending) {
1175
+ if (clause.head instanceof Struct && `${clause.head.name}/${clause.head.args.length}` === key) clause.head = new Struct(base, clause.head.args);
1176
+ }
1177
+ const args = Array.from({ length: arity }, (_, i) => new Var(i === 0 && threaded ? 'Scenario' : `A${i}`));
1178
+ emit('backward', new Struct(name, args), [new Struct(base, args), st('not', new Struct(opposite, args))], line, file,
1179
+ { counter: { n: 0 }, scenario: threaded ? args[0] : null, rule: true });
1180
+ }
1181
+ // eyemind makes no assumptions: an answer that needs one is not given, and
1182
+ // expected answers with unknowns are not compared. A negated assumable
1183
+ // sentence would hold only as an assumption, which needs abduction.
1184
+ const assumable = new Set(templates.filter((t) => t.assumable).map((t) => `${t.name}/${t.arity + (threaded ? 1 : 0)}`));
1185
+ const negates = (term, negated = false) => term instanceof Struct &&
1186
+ ((negated && assumable.has(`${term.name}/${term.args.length}`)) ||
1187
+ term.args.some((arg) => negates(arg, negated || (term.name === 'not' && term.args.length === 1))));
1188
+ for (const clause of pending) {
1189
+ if (clause.body?.some((goal) => negates(goal))) {
1190
+ throw new EyemindError(`${clause.file}: line ${clause.line}: Logical English: a negated assumable sentence holds only as an assumption, which needs abduction; abduction belongs to Logical English 2 and is not supported`);
1191
+ }
1192
+ }
1041
1193
  for (const { term, line, file } of kinds) {
1042
1194
  const S = new Var('Scenario'), X = new Var('X'), [sub, kind] = term.args.slice(-2);
1043
1195
  const isA = (a, b) => threaded ? st('is_a', S, a, b) : st('is_a', a, b);
package/src/version.js CHANGED
@@ -1,2 +1,2 @@
1
1
  // The release this checkout is; ./release keeps it in step with package.json.
2
- export const VERSION = '0.9.0';
2
+ export const VERSION = '0.9.1';