eyemind 0.6.6 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/MATHEMATICAL-ENGLISH.md +229 -0
- package/README.md +47 -6
- package/SPEC.md +1 -1
- package/package.json +2 -1
- package/src/cli.js +5 -4
- package/src/formats.js +18 -8
- package/src/index.js +1 -0
- package/src/me.js +344 -0
- package/src/version.js +1 -1
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
# Controlled Mathematical English
|
|
2
|
+
|
|
3
|
+
eyemind reads `.me` files as the controlled language defined here and compiles
|
|
4
|
+
them to ordinary Logic Script (LS). This is an input extension; the meaning of
|
|
5
|
+
the compiled program is defined by the [LS specification](https://eyereasoner.github.io/eyemind/SPEC).
|
|
6
|
+
It supports statements and computations in a fixed grammar. It does not parse
|
|
7
|
+
arbitrary mathematical prose or check textbook proof arguments.
|
|
8
|
+
|
|
9
|
+
## Documents and names
|
|
10
|
+
|
|
11
|
+
A document is a sequence of sentences, each ending in `.`. Whitespace and line
|
|
12
|
+
breaks separate tokens; a sentence can span lines. `#` starts a comment through
|
|
13
|
+
the end of the line, except inside a quoted name. Examples separate their header
|
|
14
|
+
comments from the body and put an empty line before each body comment block.
|
|
15
|
+
|
|
16
|
+
Keywords are case-insensitive. Names are case-sensitive. Class and relation
|
|
17
|
+
names start with a lowercase ASCII letter, followed by ASCII letters, digits or
|
|
18
|
+
underscores. Names of LS primitives and controls are reserved as relation names.
|
|
19
|
+
There is no implicit vocabulary, pluralization, pronoun resolution or spelling
|
|
20
|
+
normalization. `integer`, for example, is a user-defined class whose facts supply
|
|
21
|
+
its members; it does not enumerate all mathematical integers.
|
|
22
|
+
|
|
23
|
+
An individual can be an unquoted name such as `Socrates` or `alice`. A variable
|
|
24
|
+
is one capital ASCII letter optionally followed by digits, such as `X` or `Y1`.
|
|
25
|
+
Variables must be declared in their sentence; a quoted `"X"` is an individual.
|
|
26
|
+
Names containing spaces, punctuation or non-ASCII characters use JSON double
|
|
27
|
+
quotes, as in `"René Descartes"`. JSON escapes retain their usual meanings.
|
|
28
|
+
Quote names that would introduce a sentence, such as `"Every"` or `"If"`.
|
|
29
|
+
|
|
30
|
+
Terms also include integers, floats, closed lists and compounds:
|
|
31
|
+
|
|
32
|
+
```text
|
|
33
|
+
9007199254740993
|
|
34
|
+
-0.0
|
|
35
|
+
[Alice, Bob, [1, 2]]
|
|
36
|
+
pair(Alice, Bob)
|
|
37
|
+
"a compound name"(Alice, 1)
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
Integers have optional leading `-`, no leading zero except `0`, and arbitrary
|
|
41
|
+
precision. A decimal point with digits on both sides, or an exponent, denotes a
|
|
42
|
+
finite binary64 float: `1.0`, `0.25`, `1e3`. Integers and floats remain distinct
|
|
43
|
+
terms. `1.` is integer `1` followed by the sentence terminator. Nonfinite numeric
|
|
44
|
+
tokens are rejected. A compound has at least one argument. A closed list may be
|
|
45
|
+
empty; there is no open-list surface syntax, although a `"."(Head, Tail)` compound
|
|
46
|
+
can retain an LS list with a nonempty tail as data. Term and expression
|
|
47
|
+
nesting is limited to 256 levels.
|
|
48
|
+
|
|
49
|
+
## Positive statements
|
|
50
|
+
|
|
51
|
+
The following forms have the indicated LS meanings. `T`, `U` and the arguments
|
|
52
|
+
stand for terms; `class` and `relation` stand for names as defined above.
|
|
53
|
+
|
|
54
|
+
| ME form | LS term |
|
|
55
|
+
| --- | --- |
|
|
56
|
+
| `T is a class` | `class(T)` |
|
|
57
|
+
| `T is an class` | `class(T)` |
|
|
58
|
+
| `T is class` | `class(T)` |
|
|
59
|
+
| `T is a relation of U` | `relation(T, U)` |
|
|
60
|
+
| `T is an relation of U` | `relation(T, U)` |
|
|
61
|
+
| `relation(T, U, ...)` | The corresponding compound goal. |
|
|
62
|
+
| `relation` | An atom used as a goal, with arity zero. |
|
|
63
|
+
|
|
64
|
+
The articles `a` and `an` have the same semantics. They do not introduce an
|
|
65
|
+
existential variable. For example, `Socrates is a human.` states
|
|
66
|
+
`fact(human('Socrates'))`. Write an existential declaration to introduce an
|
|
67
|
+
unnamed individual.
|
|
68
|
+
|
|
69
|
+
`and` joins positive statements. A sentence containing only positive statements
|
|
70
|
+
states them as facts. A universally quantified fact is explicit:
|
|
71
|
+
|
|
72
|
+
```text
|
|
73
|
+
Ada is a human and Ada is a mathematician.
|
|
74
|
+
For every X, matching(pair(X, X)).
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
Variables declared by `For every` are universal within that sentence. Each
|
|
78
|
+
sentence has its own scope. Repeating a declaration in one scope is an error.
|
|
79
|
+
|
|
80
|
+
## Rules and calculations
|
|
81
|
+
|
|
82
|
+
```text
|
|
83
|
+
Every human is mortal.
|
|
84
|
+
Every human is mortal and animal.
|
|
85
|
+
For every X and Y, if X is a parent of Y then X is an ancestor of Y.
|
|
86
|
+
If Alice is a person then Alice is a participant.
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
`Every A is B.` compiles to `implies(A(X), B(X))`, with a fresh clause-local
|
|
90
|
+
variable. An if/then sentence compiles its premises and conclusions to one
|
|
91
|
+
forward LS rule. Both sides may contain conjunctions. A conclusion variable
|
|
92
|
+
must be supplied by a premise or explicitly declared existentially. The
|
|
93
|
+
compiler checks the stated order of premises for calculations and absence tests;
|
|
94
|
+
actual values must also satisfy LS's runtime requirements.
|
|
95
|
+
|
|
96
|
+
These additional forms are available in premises and questions:
|
|
97
|
+
|
|
98
|
+
| ME form | LS goal |
|
|
99
|
+
| --- | --- |
|
|
100
|
+
| `Y is the value of E` | `is(Y, E)` |
|
|
101
|
+
| `X is greater than E` | `gt(X, E)` |
|
|
102
|
+
| `X is less than E` | `lt(X, E)` |
|
|
103
|
+
| `X is at least E` | `ge(X, E)` |
|
|
104
|
+
| `X is at most E` | `le(X, E)` |
|
|
105
|
+
| `X is equal to E` | `eq(X, E)` |
|
|
106
|
+
| `X is different from E` | `ne(X, E)` |
|
|
107
|
+
|
|
108
|
+
Expressions contain numbers, declared variables, parentheses, unary `-` and
|
|
109
|
+
binary `+`, `-`, `*`, `/`. Unary minus binds most tightly, then multiplication
|
|
110
|
+
and division, then addition and subtraction. Binary operators associate left.
|
|
111
|
+
They compile to `neg`, `add`, `sub`, `mul` and `div`. Only the value-of form
|
|
112
|
+
binds its left variable; comparisons require their inputs beforehand.
|
|
113
|
+
|
|
114
|
+
```text
|
|
115
|
+
4 is an integer.
|
|
116
|
+
For every X and Y, if X is an integer and Y is the value of X * X
|
|
117
|
+
then Y is a square of X.
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
Arithmetic follows LS: integer addition, subtraction and multiplication are
|
|
121
|
+
exact; division returns a float; mixed integer/float arithmetic returns a
|
|
122
|
+
float. Numeric equality compares values, while ordinary relation matching
|
|
123
|
+
keeps integer and float terms distinct. Calculations belong in premises,
|
|
124
|
+
followed by relational conclusions. These calculations do not prove arbitrary
|
|
125
|
+
algebraic identities or supply induction.
|
|
126
|
+
|
|
127
|
+
## Absence and existential conclusions
|
|
128
|
+
|
|
129
|
+
An absence test has exactly this form, followed by one positive statement:
|
|
130
|
+
|
|
131
|
+
```text
|
|
132
|
+
For every X, if X is a person and it is not known that X is blocked
|
|
133
|
+
then X is an applicant.
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
It compiles to `not(blocked(X))`. Its variables must be supplied by earlier
|
|
137
|
+
positive premises or calculations. LS stratification decides when the tested
|
|
138
|
+
relation is complete. This means absence of a proof in this program, rather
|
|
139
|
+
than classical mathematical negation. Ordinary `not` is rejected. Explicit
|
|
140
|
+
negative evidence can use its own positive relation, such as `not_human`.
|
|
141
|
+
|
|
142
|
+
```text
|
|
143
|
+
For every X, if X is a person then there exists Y such that
|
|
144
|
+
Y is a record and X is an owner of Y.
|
|
145
|
+
There exists X such that X is a record.
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
`there exists` introduces fresh variables for a conclusion, after any universal
|
|
149
|
+
declarations. Every introduced variable must occur in that conclusion. The
|
|
150
|
+
compiler uses an ordinary LS forward rule with head-only variables; a standalone
|
|
151
|
+
existential sentence uses premise `'true'`. LS supplies Skolem witnesses. The
|
|
152
|
+
same variable shares one witness across the heads of that firing. A witness
|
|
153
|
+
does not assert a distinct real-world object or a minimum number of objects.
|
|
154
|
+
|
|
155
|
+
## Questions and contradictions
|
|
156
|
+
|
|
157
|
+
```text
|
|
158
|
+
Find every X such that X is mortal.
|
|
159
|
+
Find every X and Y such that X is an ancestor of Y.
|
|
160
|
+
Find whether Socrates is mortal.
|
|
161
|
+
For every X, it is impossible that X is a person and X is blocked.
|
|
162
|
+
It is impossible that Alice is blocked.
|
|
163
|
+
Contradiction.
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
Questions compile to `query(...)`; their declarations establish variable scope,
|
|
167
|
+
and the answers are instances of the whole question, without a separate
|
|
168
|
+
projection. `Find whether` introduces no variables. A question can use a
|
|
169
|
+
conjunction, calculations and absence tests. Without questions the run reports
|
|
170
|
+
derived conclusions, following LS's default; given facts alone are not printed.
|
|
171
|
+
|
|
172
|
+
`It is impossible that` compiles to an LS contradiction with the stated body.
|
|
173
|
+
`Contradiction.` is an unconditional contradiction, also used to serialize a
|
|
174
|
+
run's `'false'` conclusion. Contradictions halt reasoning with exit code 65;
|
|
175
|
+
they do not produce the continuing RDF conflict reports of `--owl-rl`.
|
|
176
|
+
|
|
177
|
+
## Output, compilation and checking
|
|
178
|
+
|
|
179
|
+
ME inputs default to `.me` conclusions. Each answer becomes a sentence:
|
|
180
|
+
|
|
181
|
+
```text
|
|
182
|
+
Socrates is a mortal.
|
|
183
|
+
16 is a square of 4.
|
|
184
|
+
Alice is an owner of witness(rule 4, Y, Alice).
|
|
185
|
+
```
|
|
186
|
+
|
|
187
|
+
`witness(rule 4, Y, Alice)` names the witness for existential variable `Y` of
|
|
188
|
+
rule 4 with argument Alice. It reads back as `skolem(4, 'Y', ['Alice'])` in LS.
|
|
189
|
+
The label `Y` in this position is a name, independent of any declared ME
|
|
190
|
+
variable. A label outside the variable-name syntax is quoted. Additional
|
|
191
|
+
arguments follow as more comma-separated terms; a witness without arguments
|
|
192
|
+
is `witness(rule 4, Y)`. The rule number, label and arguments all contribute
|
|
193
|
+
to its identity. Ordinary compounds named witness retain their quoted spelling.
|
|
194
|
+
|
|
195
|
+
Unary and binary relations use the class and relation-of forms; relations with
|
|
196
|
+
more arguments use calls. Names are quoted when required to preserve their
|
|
197
|
+
meaning. Compound names are quoted. Variable answers use `For every X0 and X1,
|
|
198
|
+
...`, consistently renaming their variables while retaining sharing. A conjunctive
|
|
199
|
+
answer uses `and`. These sentences can be loaded as facts in another `.me`
|
|
200
|
+
program. An empty answer set is `# No conclusions.`. The writer rejects goals
|
|
201
|
+
outside these relational forms instead of silently changing their meaning.
|
|
202
|
+
|
|
203
|
+
```sh
|
|
204
|
+
eyemind examples/socrates-me.me
|
|
205
|
+
eyemind --program examples/socrates-me.me > /tmp/socrates-me.js
|
|
206
|
+
eyemind --to me /tmp/socrates-me.js
|
|
207
|
+
eyemind --proof examples/socrates-me.me > /tmp/socrates-me-proof.js
|
|
208
|
+
eyemind --check-proof /tmp/socrates-me-proof.js examples/socrates-me.me
|
|
209
|
+
```
|
|
210
|
+
|
|
211
|
+
Multiple `.me` files form one program in file order; they do not mix with other
|
|
212
|
+
input formats or the RDF logic switches. Standard input remains LS; `--to me`
|
|
213
|
+
can write supported LS conclusions as ME. `--goal` uses LS goal syntax and
|
|
214
|
+
defaults to LS output; add `--to me` for ME output. `--all` applies to RDF and N3
|
|
215
|
+
output, without changing ME's selected conclusions.
|
|
216
|
+
|
|
217
|
+
The compiler reads data without executing it and emits standalone `.js` LS
|
|
218
|
+
using explicit constructors to retain names and numeric types. Comments in the
|
|
219
|
+
compiled text identify the source file and sentence line. Parser errors name
|
|
220
|
+
that location. ME runs use LS's usual work bounds, which can be overridden by
|
|
221
|
+
the CLI. Existential or recursive rules can still have an infinite closure.
|
|
222
|
+
|
|
223
|
+
Proofs and check reports are `.js` documents and use the existing LS checker.
|
|
224
|
+
Checking establishes the compiled LS result. It does not independently validate
|
|
225
|
+
the English-to-LS translation; that contract is this grammar and its tests.
|
|
226
|
+
|
|
227
|
+
Supported sentences have no disjunctive conclusions, pronouns, implicit
|
|
228
|
+
assumptions, set comprehension, higher-order quantification or proof blocks.
|
|
229
|
+
Unsupported syntax is an error, with no approximate translation.
|
package/README.md
CHANGED
|
@@ -3,11 +3,11 @@
|
|
|
3
3
|
[](https://doi.org/10.5281/zenodo.23824021)
|
|
4
4
|
[](https://www.npmjs.com/package/eyemind)
|
|
5
5
|
|
|
6
|
-
eyemind is a dependency-free reasoner for **Logic Script (LS)**, a rule language with JavaScript syntax. LS programs state facts, rules, and queries; eyemind draws conclusions using forward and backward reasoning, and can produce proofs that a separate checker verifies against your program. It interoperates with **RDF 1.2**, **Notation3 (N3)** and **SPARQL 1.2 RL (SRL)**: RDF supplies data, and N3 and SRL compile to LS programs whose proofs use the same checker. It runs as a command-line program, a JavaScript library, and a browser application.
|
|
6
|
+
eyemind is a dependency-free reasoner for **Logic Script (LS)**, a rule language with JavaScript syntax. LS programs state facts, rules, and queries; eyemind draws conclusions using forward and backward reasoning, and can produce proofs that a separate checker verifies against your program. It interoperates with **RDF 1.2**, **Notation3 (N3)** and **SPARQL 1.2 RL (SRL)**: RDF supplies data, and N3 and SRL compile to LS programs whose proofs use the same checker. Controlled **Mathematical English (ME)** also compiles to LS and writes `.me` conclusions. It runs as a command-line program, a JavaScript library, and a browser application.
|
|
7
7
|
|
|
8
8
|
[Playground](https://eyereasoner.github.io/eyemind/playground/) · [Specification](https://eyereasoner.github.io/eyemind/SPEC) · [Conformance](https://eyereasoner.github.io/eyemind/conformance/) · [Examples](https://eyereasoner.github.io/eyemind/examples/)
|
|
9
9
|
|
|
10
|
-
The playground runs programs in your browser; the specification defines the language, its canonical text, the proof format and how a proof is checked. The examples are
|
|
10
|
+
The playground runs programs in your browser; the specification defines the language, its canonical text, the proof format and how a proof is checked. The examples are 141 runnable programs, each with a card deck and saved conclusions, proofs and check reports. The conformance suite has 1246 cases that test language and proof behavior through a command adapter, together with implementation interface checks; run it [in your browser](https://eyereasoner.github.io/eyemind/playground/conformance).
|
|
11
11
|
|
|
12
12
|
## Contents
|
|
13
13
|
|
|
@@ -18,6 +18,7 @@ The playground runs programs in your browser; the specification defines the lang
|
|
|
18
18
|
- [Terms and names](#terms-and-names)
|
|
19
19
|
- [Deriving rules](#deriving-rules)
|
|
20
20
|
- [Inspecting rules](#inspecting-rules)
|
|
21
|
+
- [Mathematical English](#mathematical-english)
|
|
21
22
|
- [RDF 1.2](#rdf-12)
|
|
22
23
|
- [Notation3](#notation3)
|
|
23
24
|
- [RDF Messages](#rdf-messages)
|
|
@@ -179,6 +180,46 @@ query(test(X, Y))
|
|
|
179
180
|
|
|
180
181
|
The answer is `test(a(A), c(A))`, with the shared variable preserved. Inspection sees ordinary source rules only, not facts, queries, generators or itself, and its proof step names the source rule it matched. See the [rule inspection deck](https://eyereasoner.github.io/eyemind/examples/deck/rule-inspection) and [SPEC §6.3](https://eyereasoner.github.io/eyemind/SPEC#63-source-rule-inspection).
|
|
181
182
|
|
|
183
|
+
### Mathematical English
|
|
184
|
+
|
|
185
|
+
A `.me` file is [controlled Mathematical English](https://eyereasoner.github.io/eyemind/MATHEMATICAL-ENGLISH),
|
|
186
|
+
compiled deterministically into LS. Facts, class rules, quantified if/then rules,
|
|
187
|
+
calculations, explicit absence tests, existential conclusions, questions and
|
|
188
|
+
contradictions have a fixed grammar. Unsupported prose is an error.
|
|
189
|
+
|
|
190
|
+
```text
|
|
191
|
+
Socrates is a human.
|
|
192
|
+
Every human is mortal.
|
|
193
|
+
Find every X such that X is mortal.
|
|
194
|
+
```
|
|
195
|
+
|
|
196
|
+
```sh
|
|
197
|
+
eyemind examples/socrates-me.me > /tmp/socrates-me.me
|
|
198
|
+
eyemind --program examples/socrates-me.me > /tmp/socrates-me.js
|
|
199
|
+
eyemind --to me /tmp/socrates-me.js
|
|
200
|
+
eyemind --proof examples/socrates-me.me > /tmp/socrates-me-proof.js
|
|
201
|
+
eyemind --check-proof /tmp/socrates-me-proof.js examples/socrates-me.me
|
|
202
|
+
```
|
|
203
|
+
|
|
204
|
+
Conclusions default to `.me`: `Socrates is a mortal.`. They can supply facts to
|
|
205
|
+
another ME program. `--to me` also writes supported LS conclusions in this
|
|
206
|
+
format. Proofs and check reports remain `.js`, and the standalone compilation
|
|
207
|
+
contains all its LS clauses with source sentence locations. The existing checker
|
|
208
|
+
checks the compiled LS; the documented grammar and compiler tests define the
|
|
209
|
+
English translation.
|
|
210
|
+
|
|
211
|
+
Multiple `.me` files form one program. Names are case-sensitive, variables such
|
|
212
|
+
as `X` and `Y1` are explicitly declared within each sentence, and integers stay
|
|
213
|
+
exact. Arithmetic and absence tests require their inputs from earlier premises;
|
|
214
|
+
absence is written `it is not known that`, with LS's stratified meaning. A rule
|
|
215
|
+
can introduce witnesses with `there exists`. ME uses the ordinary LS resource
|
|
216
|
+
bounds; recursive and existential rules can still have an infinite closure.
|
|
217
|
+
|
|
218
|
+
The playground loads ME examples and downloads conclusions as `output.me`.
|
|
219
|
+
Try [Socrates](https://eyereasoner.github.io/eyemind/examples/deck/socrates-me),
|
|
220
|
+
[exact squares](https://eyereasoner.github.io/eyemind/examples/deck/squares-me)
|
|
221
|
+
and [record creation](https://eyereasoner.github.io/eyemind/examples/deck/records-me).
|
|
222
|
+
|
|
182
223
|
### RDF 1.2
|
|
183
224
|
|
|
184
225
|
eyemind reads RDF 1.2 itself, with no dependency: a file ending in `.ttl`, `.trig`, `.nt` or `.nq` is Turtle, TriG, N-Triples or N-Quads, read with the formats' own grammars, and given with a program its quads become `rdf(Subject, Predicate, Object, Graph)` facts, read as data through `facts_from` and never run. `--to turtle`, `trig`, `n-triples` or `n-quads` writes a run's `rdf` and `result_rdf` conclusions back as RDF:
|
|
@@ -670,7 +711,7 @@ eyemind [OPTION ...] [FILE ...]
|
|
|
670
711
|
|
|
671
712
|
| Option | Meaning |
|
|
672
713
|
| --- | --- |
|
|
673
|
-
| (none) | Load the files, or standard input, as one program and print its conclusions. `.js` files and standard input are Logic Script, `.ttl`, `.trig`, `.nt` and `.nq` files RDF data, `.n3` Notation3
|
|
714
|
+
| (none) | Load the files, or standard input, as one program and print its conclusions. `.js` files and standard input are Logic Script, `.ttl`, `.trig`, `.nt` and `.nq` files RDF data, `.n3` Notation3, `.srl` a SPARQL 1.2 RL rule set and `.me` controlled Mathematical English. |
|
|
674
715
|
| `-p`, `--proof` | Print the proof instead. |
|
|
675
716
|
| `-c`, `--prove-and-check` | Generate a proof, check it, and print the checked answers with the report. |
|
|
676
717
|
| `--check-proof FILE` | Check a saved proof (`-` for standard input) against the program. |
|
|
@@ -680,7 +721,7 @@ eyemind [OPTION ...] [FILE ...]
|
|
|
680
721
|
| `--stream-messages` | Read an RDF Message Log and run the rules independently per message; Node reads files, stdin and HTTP(S) incrementally. |
|
|
681
722
|
| `--stats` | Print reasoning statistics as JSON to standard error. |
|
|
682
723
|
| `--max-depth N`, `--max-iterations N`, `--max-inferences N` | Bound backward depth (1000000), forward rounds per stratum (1000) and goals started (1000000); a compiled N3, SRL, ODRL, RDFS or OWL-RL program has 1000000, 100000 and 1000000000. |
|
|
683
|
-
| `--to FORMAT` | Write the conclusions as `turtle`, `trig`, `n-triples`, `n-quads`, `n3` or `eyemind`; by default N3 for N3, Turtle for SRL, ODRL, RDFS and OWL-RL, eyemind otherwise. |
|
|
724
|
+
| `--to FORMAT` | Write the conclusions as `turtle`, `trig`, `n-triples`, `n-quads`, `n3`, `me` or `eyemind`; by default ME for ME, N3 for N3, Turtle for SRL, ODRL, RDFS and OWL-RL, eyemind otherwise. |
|
|
684
725
|
| `--all` | With RDF or N3 output, write the given data too. |
|
|
685
726
|
| `--program` | Print the program the inputs compile to. |
|
|
686
727
|
| `--odrl` | Add the ODRL snapshot profile's validation and evaluation LS to one Turtle input. |
|
|
@@ -695,7 +736,7 @@ each goal as a data document, with an array denoting conjunction. With
|
|
|
695
736
|
`--check-proof`, supply the original goals the proof answers.
|
|
696
737
|
An option that takes a value requires it immediately afterward; another
|
|
697
738
|
option, including a short alias such as `-v`, is reported as a missing value.
|
|
698
|
-
With `--goal`, answers default to eyemind terms even for N3, SRL, ODRL, RDFS and OWL-RL inputs;
|
|
739
|
+
With `--goal`, answers default to eyemind terms even for ME, N3, SRL, ODRL, RDFS and OWL-RL inputs;
|
|
699
740
|
use `--to` to request another output format.
|
|
700
741
|
|
|
701
742
|
With `--prove-and-check`, reasoning bounds and `--stats` apply to proof
|
|
@@ -796,7 +837,7 @@ console.log(result.bindings);
|
|
|
796
837
|
console.log(checkProof(socrates, result.proof, { goals }).valid);
|
|
797
838
|
```
|
|
798
839
|
|
|
799
|
-
`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.
|
|
840
|
+
`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. `compileMe([[text, filename], ...])` returns the compiled LS `program` and standalone JavaScript `text`; `writeMe(run(program))` writes its conclusions as ME.
|
|
800
841
|
|
|
801
842
|
## What is deliberately absent
|
|
802
843
|
|
package/SPEC.md
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "eyemind",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.7.0",
|
|
4
4
|
"description": "A dependency-free Logic Script (LS) reasoner with forward and backward reasoning, checkable proofs, and RDF 1.2, Notation3 (N3) and SPARQL 1.2 RL (SRL) interoperability.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./src/index.js",
|
|
@@ -17,6 +17,7 @@
|
|
|
17
17
|
"src/",
|
|
18
18
|
"README.md",
|
|
19
19
|
"SPEC.md",
|
|
20
|
+
"MATHEMATICAL-ENGLISH.md",
|
|
20
21
|
"LICENSE.md"
|
|
21
22
|
],
|
|
22
23
|
"scripts": {
|
package/src/cli.js
CHANGED
|
@@ -10,7 +10,8 @@ import { srlContextFromProof } from './srl.js';
|
|
|
10
10
|
export const HELP = `Usage: eyemind [OPTION ...] [FILE ...]
|
|
11
11
|
Logic Script (LS) programs use JavaScript syntax. Forward rules run to a fixpoint.
|
|
12
12
|
Files are read by extension: .js as LS, .ttl, .trig, .nt and .nq as RDF 1.2 data,
|
|
13
|
-
.n3 as Notation3
|
|
13
|
+
.n3 as Notation3, .srl as SPARQL 1.2 RL and .me as controlled Mathematical English,
|
|
14
|
+
all compiled to LS.
|
|
14
15
|
-p, --proof Print a proof of the conclusions
|
|
15
16
|
-c, --prove-and-check Generate a proof and check it against the input program
|
|
16
17
|
--check-proof FILE Check a proof and print its answers and verdict (- for stdin)
|
|
@@ -23,7 +24,7 @@ Files are read by extension: .js as LS, .ttl, .trig, .nt and .nq as RDF 1.2 data
|
|
|
23
24
|
--max-iterations N Bound forward rounds per stratum (default 1000)
|
|
24
25
|
--max-inferences N Bound reasoning work (default 1000000)
|
|
25
26
|
--to FORMAT Write the conclusions as turtle, trig, n-triples,
|
|
26
|
-
n-quads, n3 or eyemind (default: n3 for N3, turtle
|
|
27
|
+
n-quads, n3, me or eyemind (default: me for ME, n3 for N3, turtle
|
|
27
28
|
for SRL, ODRL, RDFS or OWL-RL, eyemind otherwise or with --goal)
|
|
28
29
|
--all With RDF or N3 output, write the given data too
|
|
29
30
|
--program Print the program the inputs compile to
|
|
@@ -198,8 +199,8 @@ export function main(argv, io) {
|
|
|
198
199
|
stdout(loaded.text);
|
|
199
200
|
return 0;
|
|
200
201
|
}
|
|
201
|
-
//
|
|
202
|
-
if (loaded.kind
|
|
202
|
+
// N3, SRL and the RDF logic extensions have larger default bounds.
|
|
203
|
+
if (!['js', 'me'].includes(loaded.kind)) for (const [name, value] of Object.entries(COMPILED_LIMITS)) options[name] ??= value;
|
|
203
204
|
if (proofFile !== null) {
|
|
204
205
|
const report = checkProof(program, document, { goals });
|
|
205
206
|
stdout(asJson ? `${JSON.stringify(publicReport(report), null, 2)}\n` : checkReport(report));
|
package/src/formats.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// The inputs of a run in other formats than Logic Script, and its output as
|
|
2
|
-
// RDF or
|
|
2
|
+
// RDF, N3 or controlled Mathematical English.
|
|
3
3
|
//
|
|
4
4
|
// A file's extension says what it holds:
|
|
5
5
|
//
|
|
@@ -10,6 +10,7 @@
|
|
|
10
10
|
// rule set, its base graph
|
|
11
11
|
// .n3 Notation3, compiled to an LS program
|
|
12
12
|
// .srl a SPARQL 1.2 RL rule set, compiled to one
|
|
13
|
+
// .me controlled Mathematical English, compiled to LS
|
|
13
14
|
//
|
|
14
15
|
// The odrl option adds the snapshot profile's validation and evaluation LS
|
|
15
16
|
// to one Turtle input. Its vocabulary alone never enables the evaluator.
|
|
@@ -26,16 +27,18 @@ import { resultToN3, compileSources } from './n3.js';
|
|
|
26
27
|
import { compileSrl, srlAnswers, srlQuads } from './srl.js';
|
|
27
28
|
import { compileOdrl } from './odrl.js';
|
|
28
29
|
import { compileEntailment } from './entailment.js';
|
|
30
|
+
import { compileMe, writeMe } from './me.js';
|
|
29
31
|
import { write } from './writer.js';
|
|
30
32
|
import { isRdfMessageLog, parseRdfMessages } from './messages.js';
|
|
31
33
|
|
|
32
|
-
export const OUTPUT_FORMATS = ['eyemind', 'turtle', 'trig', 'n-triples', 'n-quads', 'n3'];
|
|
34
|
+
export const OUTPUT_FORMATS = ['eyemind', 'turtle', 'trig', 'n-triples', 'n-quads', 'n3', 'me'];
|
|
33
35
|
|
|
34
|
-
// What a file holds: 'js', 'rdf', 'n3' or '
|
|
36
|
+
// What a file holds: 'js', 'rdf', 'n3', 'srl' or 'me'.
|
|
35
37
|
export function inputKind(name) {
|
|
36
38
|
if (rdfFormat(name)) return 'rdf';
|
|
37
39
|
if (/\.n3$/i.test(name)) return 'n3';
|
|
38
40
|
if (/\.srl$/i.test(name)) return 'srl';
|
|
41
|
+
if (/\.me$/i.test(name)) return 'me';
|
|
39
42
|
return 'js';
|
|
40
43
|
}
|
|
41
44
|
|
|
@@ -47,7 +50,7 @@ export function rdfMessageFormat(name) {
|
|
|
47
50
|
// Load inputs, given as [text, name] pairs, as one program. io may supply
|
|
48
51
|
// readFile, for the documents N3 and IMPORTS name, and fileIri(name), the
|
|
49
52
|
// base IRI of a file. Returns { kind, program, text, prefixes, compiled }:
|
|
50
|
-
// kind is 'js', 'n3', 'srl', 'odrl', 'rdfs' or 'owl-rl', text the compiled program,
|
|
53
|
+
// kind is 'js', 'n3', 'srl', 'me', 'odrl', 'rdfs' or 'owl-rl', text the compiled program,
|
|
51
54
|
// and compiled what writing the conclusions needs.
|
|
52
55
|
export function loadInputs(inputs, io = null, options = {}) {
|
|
53
56
|
try {
|
|
@@ -68,6 +71,12 @@ function load(inputs, io, { base = null, messageInputs = null, srlContext = null
|
|
|
68
71
|
format: rdfFormat(name) ?? 'trig', base: baseOf(name), scope: scopeOf(inputs, name, k),
|
|
69
72
|
});
|
|
70
73
|
// These rule sets are added only when requested, never from vocabulary.
|
|
74
|
+
if (kinds.includes('me')) {
|
|
75
|
+
if (kinds.some((kind) => kind !== 'me') || odrl || rdfs || owlRl) {
|
|
76
|
+
throw new EyemindError('a Mathematical English run takes .me files without RDF logic switches or other input formats');
|
|
77
|
+
}
|
|
78
|
+
return compileMe(inputs);
|
|
79
|
+
}
|
|
71
80
|
if ((rdfs || owlRl) && odrl) throw new EyemindError('--odrl cannot be combined with --rdfs or --owl-rl');
|
|
72
81
|
if (rdfs || owlRl) {
|
|
73
82
|
if (inputs.some(([, name], k) => kinds[k] !== 'rdf' && name !== '<stdin>')) {
|
|
@@ -144,14 +153,15 @@ function importResolver(io) {
|
|
|
144
153
|
};
|
|
145
154
|
}
|
|
146
155
|
|
|
147
|
-
//
|
|
148
|
-
// extensions, and eyemind's own text for
|
|
149
|
-
export const defaultFormat = (kind) => ({ n3: 'n3', srl: 'turtle', odrl: 'turtle', rdfs: 'turtle', 'owl-rl': 'turtle' })[kind] ?? 'eyemind';
|
|
156
|
+
// Default output: ME for ME, N3 for N3, Turtle for SRL and the RDF logic
|
|
157
|
+
// extensions, and eyemind's own text for an LS program.
|
|
158
|
+
export const defaultFormat = (kind) => ({ me: 'me', n3: 'n3', srl: 'turtle', odrl: 'turtle', rdfs: 'turtle', 'owl-rl': 'turtle' })[kind] ?? 'eyemind';
|
|
150
159
|
|
|
151
160
|
// The conclusions of a run in an output format; null for eyemind's own text.
|
|
152
|
-
// all also writes
|
|
161
|
+
// all also writes given RDF or N3 data. Rejects conclusions the format cannot represent.
|
|
153
162
|
export function writeConclusions(loaded, result, { format, all = false, blankNodePrefix = '' } = {}) {
|
|
154
163
|
if (format === 'eyemind') return null;
|
|
164
|
+
if (format === 'me') return writeMe(result);
|
|
155
165
|
if (format === 'n3') {
|
|
156
166
|
if (loaded.kind !== 'n3') throw new EyemindError('--to n3 writes the conclusions of an N3 run');
|
|
157
167
|
return resultToN3(loaded.compiled.doc, result, { mode: all ? 'all' : 'new', blankNodePrefix }).n3;
|
package/src/index.js
CHANGED
package/src/me.js
ADDED
|
@@ -0,0 +1,344 @@
|
|
|
1
|
+
// Controlled Mathematical English: an explicit grammar, ordinary LS clauses,
|
|
2
|
+
// and conclusions that can be read back as facts. No input text is executed.
|
|
3
|
+
import { PRIMITIVE_KEYS } from './builtins.js';
|
|
4
|
+
import { CONTROL_KEYS, Program, RESERVED_KEYS, Source } from './program.js';
|
|
5
|
+
import { readTerm } from './reader.js';
|
|
6
|
+
import { EMPTY, EyemindError, Struct, Var, conjunction, flattenConjunction } from './terms.js';
|
|
7
|
+
import { write } from './writer.js';
|
|
8
|
+
|
|
9
|
+
const st = (name, ...args) => new Struct(name, args);
|
|
10
|
+
const VARIABLE = /^[A-Z][0-9]*$/;
|
|
11
|
+
const NAME = /^[a-z][A-Za-z0-9_]*$/;
|
|
12
|
+
const SENTENCE_WORDS = new Set(['every', 'for', 'if', 'find', 'there', 'it', 'contradiction']);
|
|
13
|
+
const RESERVED = new Set([...PRIMITIVE_KEYS, ...CONTROL_KEYS, ...RESERVED_KEYS].map((key) => key.split('/')[0]));
|
|
14
|
+
for (const name of ['true', 'false', 'fail']) RESERVED.add(name);
|
|
15
|
+
const OPERATORS = { '+': ['add', 1], '-': ['sub', 1], '*': ['mul', 2], '/': ['div', 2] };
|
|
16
|
+
const list = (items) => items.reduceRight((tail, head) => st('.', head, tail), EMPTY);
|
|
17
|
+
|
|
18
|
+
function listItems(term) {
|
|
19
|
+
const items = [];
|
|
20
|
+
while (term instanceof Struct && term.name === '.' && term.args.length === 2) {
|
|
21
|
+
items.push(term.args[0]);
|
|
22
|
+
term = term.args[1];
|
|
23
|
+
}
|
|
24
|
+
return term === EMPTY ? items : null;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
class Parser {
|
|
28
|
+
constructor(text, file) {
|
|
29
|
+
this.file = file;
|
|
30
|
+
this.tokens = [];
|
|
31
|
+
this.at = 0;
|
|
32
|
+
this.scope = new Map();
|
|
33
|
+
this.depth = 0;
|
|
34
|
+
let line = 1, pos = 0;
|
|
35
|
+
while (pos < text.length) {
|
|
36
|
+
const tail = text.slice(pos);
|
|
37
|
+
const whitespace = /^\s+/.exec(tail);
|
|
38
|
+
if (whitespace) { line += (whitespace[0].match(/\n/g) ?? []).length; pos += whitespace[0].length; continue; }
|
|
39
|
+
if (tail[0] === '#') { const end = text.indexOf('\n', pos); pos = end < 0 ? text.length : end; continue; }
|
|
40
|
+
const match = /^("(?:[^"\\\r\n]|\\.)*"|(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?|[A-Za-z][A-Za-z0-9_]*|[()[\],.+*/-])/.exec(tail);
|
|
41
|
+
if (!match) this.error(`unexpected character ${JSON.stringify(tail[0])}`, line);
|
|
42
|
+
const raw = match[0];
|
|
43
|
+
let value = raw, kind = 'word';
|
|
44
|
+
if (raw[0] === '"') {
|
|
45
|
+
try { value = JSON.parse(raw); } catch { this.error('invalid quoted name; use a JSON string', line); }
|
|
46
|
+
kind = 'string';
|
|
47
|
+
} else if (/^[0-9]/.test(raw)) kind = 'number';
|
|
48
|
+
else if (!/^[A-Za-z]/.test(raw)) kind = 'punct';
|
|
49
|
+
this.tokens.push({ value, raw, kind, line });
|
|
50
|
+
pos += raw.length;
|
|
51
|
+
}
|
|
52
|
+
this.tokens.push({ value: '', raw: '', kind: 'end', line });
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
get token() { return this.tokens[this.at]; }
|
|
56
|
+
error(message, line = this.token?.line ?? 1) { throw new EyemindError(`${this.file}: line ${line}: Mathematical English: ${message}`); }
|
|
57
|
+
is(word) { return this.token.kind !== 'string' && this.token.value.toLowerCase() === word; }
|
|
58
|
+
take(word) { if (!this.is(word)) return false; this.at++; return true; }
|
|
59
|
+
need(word) { if (!this.take(word)) this.error(`expected ${JSON.stringify(word)}, found ${JSON.stringify(this.token.raw || 'end of input')}`); }
|
|
60
|
+
|
|
61
|
+
name() {
|
|
62
|
+
const token = this.token;
|
|
63
|
+
if (token.kind !== 'word' || !NAME.test(token.value) || RESERVED.has(token.value)) {
|
|
64
|
+
this.error('a relation or class name must start with a lowercase letter and must not name an LS primitive or control');
|
|
65
|
+
}
|
|
66
|
+
this.at++;
|
|
67
|
+
return token.value;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
declarations() {
|
|
71
|
+
const vars = [];
|
|
72
|
+
do {
|
|
73
|
+
const name = this.token.value;
|
|
74
|
+
if (this.token.kind !== 'word' || !VARIABLE.test(name)) this.error('a variable is one capital letter, optionally followed by digits, such as X or Y1');
|
|
75
|
+
if (this.scope.has(name)) this.error(`variable ${name} is already declared in this sentence`);
|
|
76
|
+
const variable = new Var(name);
|
|
77
|
+
this.scope.set(name, variable);
|
|
78
|
+
vars.push(variable);
|
|
79
|
+
this.at++;
|
|
80
|
+
} while (this.take('and'));
|
|
81
|
+
return vars;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
nested(read) {
|
|
85
|
+
if (this.depth >= 256) this.error('terms and expressions may nest at most 256 levels');
|
|
86
|
+
this.depth++;
|
|
87
|
+
try { return read(); } finally { this.depth--; }
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
term() { return this.nested(() => this.termValue()); }
|
|
91
|
+
|
|
92
|
+
termValue() {
|
|
93
|
+
if (this.take('-')) {
|
|
94
|
+
if (this.token.kind !== 'number') this.error('a minus sign in a term needs a number; use the value-of form for arithmetic');
|
|
95
|
+
return this.number(true);
|
|
96
|
+
}
|
|
97
|
+
if (this.token.kind === 'number') return this.number(false);
|
|
98
|
+
if (this.take('[')) {
|
|
99
|
+
const items = [];
|
|
100
|
+
if (!this.take(']')) { do { items.push(this.term()); } while (this.take(',')); this.need(']'); }
|
|
101
|
+
return list(items);
|
|
102
|
+
}
|
|
103
|
+
// The explicit "rule N" marker distinguishes a generated witness from
|
|
104
|
+
// an ordinary compound named witness. Its label is data, not a variable.
|
|
105
|
+
if (this.is('witness') && this.tokens[this.at + 1]?.value === '(' &&
|
|
106
|
+
this.tokens[this.at + 2]?.kind === 'word' && this.tokens[this.at + 2].value.toLowerCase() === 'rule' &&
|
|
107
|
+
(this.tokens[this.at + 3]?.kind === 'number' || this.tokens[this.at + 3]?.value === '-')) {
|
|
108
|
+
this.at += 3;
|
|
109
|
+
const rule = this.term();
|
|
110
|
+
if (typeof rule !== 'bigint' || rule < 1n) this.error('a witness rule number must be a positive integer');
|
|
111
|
+
this.need(',');
|
|
112
|
+
const label = this.token;
|
|
113
|
+
if (label.kind !== 'string' && !(label.kind === 'word' && VARIABLE.test(label.value))) {
|
|
114
|
+
this.error('a witness label must be a variable name such as Y or a quoted name');
|
|
115
|
+
}
|
|
116
|
+
this.at++;
|
|
117
|
+
const args = [];
|
|
118
|
+
while (this.take(',')) args.push(this.term());
|
|
119
|
+
this.need(')');
|
|
120
|
+
return st('skolem', rule, label.value, list(args));
|
|
121
|
+
}
|
|
122
|
+
const token = this.token;
|
|
123
|
+
if (!['word', 'string'].includes(token.kind)) this.error('expected a name, number, variable, list or compound term');
|
|
124
|
+
this.at++;
|
|
125
|
+
if (this.take('(')) {
|
|
126
|
+
const args = [];
|
|
127
|
+
if (!this.take(')')) { do { args.push(this.term()); } while (this.take(',')); this.need(')'); }
|
|
128
|
+
if (!args.length) this.error('a compound term needs at least one argument', token.line);
|
|
129
|
+
return st(token.value, ...args);
|
|
130
|
+
}
|
|
131
|
+
if (token.kind === 'word' && VARIABLE.test(token.value)) {
|
|
132
|
+
if (!this.scope.has(token.value)) this.error(`variable ${token.value} is undeclared; introduce it with "For every", "Find every" or "there exists", or quote it as a name`, token.line);
|
|
133
|
+
return this.scope.get(token.value);
|
|
134
|
+
}
|
|
135
|
+
return token.value;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
number(negative) {
|
|
139
|
+
const token = this.token;
|
|
140
|
+
this.at++;
|
|
141
|
+
try { return readTerm((negative ? '-' : '') + token.raw); }
|
|
142
|
+
catch { this.error(`invalid or nonfinite number ${(negative ? '-' : '') + token.raw}`, token.line); }
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
expression(min = 0) { return this.nested(() => this.expressionValue(min)); }
|
|
146
|
+
|
|
147
|
+
expressionValue(min) {
|
|
148
|
+
let left;
|
|
149
|
+
if (this.take('-')) left = st('neg', this.expression(3));
|
|
150
|
+
else if (this.take('(')) { left = this.expression(); this.need(')'); }
|
|
151
|
+
else {
|
|
152
|
+
left = this.term();
|
|
153
|
+
if (!(left instanceof Var) && !['bigint', 'number'].includes(typeof left)) this.error('arithmetic operands must be numbers or declared variables');
|
|
154
|
+
}
|
|
155
|
+
while (OPERATORS[this.token.value]?.[1] > min) {
|
|
156
|
+
const [name, precedence] = OPERATORS[this.token.value];
|
|
157
|
+
this.at++;
|
|
158
|
+
left = st(name, left, this.expression(precedence));
|
|
159
|
+
}
|
|
160
|
+
return left;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
atomic(body) {
|
|
164
|
+
if (body && this.take('it')) {
|
|
165
|
+
this.need('is'); this.need('not'); this.need('known'); this.need('that');
|
|
166
|
+
return st('not', this.atomic(false));
|
|
167
|
+
}
|
|
168
|
+
const subject = this.term();
|
|
169
|
+
if (this.take('is')) {
|
|
170
|
+
if (this.is('not')) this.error('ordinary "not" is unsupported; use "it is not known that" in a premise for absence, or a separate relation for explicit negative evidence');
|
|
171
|
+
if (!body && this.is('the')) this.error('put calculations in a premise, as in "Y is the value of X + 1", then state the result relation');
|
|
172
|
+
if (this.take('a') || this.take('an')) {
|
|
173
|
+
const name = this.name();
|
|
174
|
+
return this.take('of') ? st(name, subject, this.term()) : st(name, subject);
|
|
175
|
+
}
|
|
176
|
+
if (body) {
|
|
177
|
+
if (this.take('the')) {
|
|
178
|
+
this.need('value'); this.need('of');
|
|
179
|
+
if (!(subject instanceof Var) && !['bigint', 'number'].includes(typeof subject)) this.error('a calculation needs a variable or number on its left');
|
|
180
|
+
return st('is', subject, this.expression());
|
|
181
|
+
}
|
|
182
|
+
let comparison;
|
|
183
|
+
if (this.take('greater')) { this.need('than'); comparison = 'gt'; }
|
|
184
|
+
else if (this.take('less')) { this.need('than'); comparison = 'lt'; }
|
|
185
|
+
else if (this.take('at')) {
|
|
186
|
+
if (this.take('least')) comparison = 'ge';
|
|
187
|
+
else { this.need('most'); comparison = 'le'; }
|
|
188
|
+
} else if (this.take('equal')) { this.need('to'); comparison = 'eq'; }
|
|
189
|
+
else if (this.take('different')) { this.need('from'); comparison = 'ne'; }
|
|
190
|
+
if (comparison) {
|
|
191
|
+
if (!(subject instanceof Var) && !['bigint', 'number'].includes(typeof subject)) this.error('a comparison needs a variable or number on its left');
|
|
192
|
+
return st(comparison, subject, this.expression());
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
// Adjectival class form, as in "Every human is mortal".
|
|
196
|
+
return st(this.name(), subject);
|
|
197
|
+
}
|
|
198
|
+
if (subject instanceof Struct && subject.name !== '.' && NAME.test(subject.name) && !RESERVED.has(subject.name)) return subject;
|
|
199
|
+
if (typeof subject === 'string' && NAME.test(subject) && !RESERVED.has(subject)) return subject;
|
|
200
|
+
this.error('expected "is a class", "is a relation of", or a relation call such as parent(Alice, Bob)');
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
goals(body) {
|
|
204
|
+
const goals = [this.atomic(body)];
|
|
205
|
+
while (this.take('and')) goals.push(this.atomic(body));
|
|
206
|
+
return goals;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
sentence() {
|
|
210
|
+
const line = this.token.line;
|
|
211
|
+
this.scope = new Map();
|
|
212
|
+
if (this.take('every')) {
|
|
213
|
+
const from = this.name(); this.need('is');
|
|
214
|
+
const x = new Var('X'), heads = [];
|
|
215
|
+
do { this.take('a') || this.take('an'); heads.push(st(this.name(), x)); } while (this.take('and'));
|
|
216
|
+
this.need('.');
|
|
217
|
+
return { kind: 'forward', heads, body: [st(from, x)], line };
|
|
218
|
+
}
|
|
219
|
+
let quantified = false;
|
|
220
|
+
if (this.take('for')) { this.need('every'); this.declarations(); this.need(','); quantified = true; }
|
|
221
|
+
let kind = 'fact', body = [], heads = [], witnesses = [];
|
|
222
|
+
if (this.take('find')) {
|
|
223
|
+
if (quantified) this.error('a question introduces its variables with "Find every"');
|
|
224
|
+
if (this.take('every')) { this.declarations(); this.need('such'); this.need('that'); }
|
|
225
|
+
else this.need('whether');
|
|
226
|
+
kind = 'query'; body = this.goals(true);
|
|
227
|
+
} else if (this.take('contradiction')) {
|
|
228
|
+
kind = 'contradiction'; body = ['true'];
|
|
229
|
+
} else if (this.take('it')) {
|
|
230
|
+
this.need('is'); this.need('impossible'); this.need('that');
|
|
231
|
+
kind = 'contradiction'; body = this.goals(true);
|
|
232
|
+
} else {
|
|
233
|
+
if (this.take('if')) { kind = 'forward'; body = this.goals(true); this.need('then'); }
|
|
234
|
+
if (this.take('there')) {
|
|
235
|
+
this.need('exists'); witnesses = this.declarations(); this.need('such'); this.need('that');
|
|
236
|
+
if (kind === 'fact') { kind = 'forward'; body = ['true']; }
|
|
237
|
+
}
|
|
238
|
+
heads = this.goals(false);
|
|
239
|
+
}
|
|
240
|
+
this.need('.');
|
|
241
|
+
const headVars = variablesIn(heads), bound = new Set(), witnessNames = new Set(witnesses.map((v) => v.name));
|
|
242
|
+
for (const goal of body) {
|
|
243
|
+
const required = goal instanceof Struct && RESERVED.has(goal.name) ? variablesIn(goal.name === 'is' ? [goal.args[1]] : [goal]) : new Set();
|
|
244
|
+
for (const name of required) if (!bound.has(name)) this.error(`${name} must be supplied by an earlier positive premise or calculation`, line);
|
|
245
|
+
if (!(goal instanceof Struct && goal.name === 'not')) for (const name of variablesIn([goal])) bound.add(name);
|
|
246
|
+
}
|
|
247
|
+
if (witnesses.some((v) => !headVars.has(v.name))) this.error('every existential variable must occur in its conclusion', line);
|
|
248
|
+
if (kind === 'forward' && [...headVars].some((name) => !bound.has(name) && !witnessNames.has(name))) {
|
|
249
|
+
this.error('a conclusion variable must occur in a premise or be introduced with "there exists"', line);
|
|
250
|
+
}
|
|
251
|
+
return { kind, heads, body, line };
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
function variablesIn(terms) {
|
|
256
|
+
const result = new Set(), pending = [...terms];
|
|
257
|
+
while (pending.length) {
|
|
258
|
+
const term = pending.pop();
|
|
259
|
+
if (term instanceof Var) result.add(term.name);
|
|
260
|
+
else if (term instanceof Struct) pending.push(...term.args);
|
|
261
|
+
}
|
|
262
|
+
return result;
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
// Explicit constructors keep quoted names, floats and reserved JS names safe.
|
|
266
|
+
function javascript(term) {
|
|
267
|
+
if (term instanceof Var) return `vars(${JSON.stringify(term.name)})`;
|
|
268
|
+
if (term instanceof Struct) return `struct(${JSON.stringify(term.name)}, ${term.args.map(javascript).join(', ')})`;
|
|
269
|
+
if (typeof term === 'bigint') return `${term}n`;
|
|
270
|
+
if (typeof term === 'number') return `float(${write(term)})`;
|
|
271
|
+
return JSON.stringify(term);
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
export function compileMe(inputs) {
|
|
275
|
+
const clauses = [], statements = [], sources = [];
|
|
276
|
+
for (const [text, file] of inputs) {
|
|
277
|
+
const parser = new Parser(String(text), file);
|
|
278
|
+
while (parser.token.kind !== 'end') {
|
|
279
|
+
const sentence = parser.sentence(), { kind, heads, body, line } = sentence;
|
|
280
|
+
statements.push({ ...sentence, file });
|
|
281
|
+
clauses.push(`// ${String(file).replace(/[\r\n\u2028\u2029]/g, ' ')}: line ${line}`);
|
|
282
|
+
if (kind === 'fact') {
|
|
283
|
+
for (const head of heads) {
|
|
284
|
+
clauses.push(`fact(${javascript(head)})`);
|
|
285
|
+
sources.push(new Source('fact', head, [], line, file));
|
|
286
|
+
}
|
|
287
|
+
} else if (kind === 'forward') {
|
|
288
|
+
clauses.push(`implies(${javascript(conjunction(body))}, ${javascript(conjunction(heads))})`);
|
|
289
|
+
sources.push(new Source('forward', conjunction(heads), body, line, file));
|
|
290
|
+
} else {
|
|
291
|
+
clauses.push(`${kind}(${body.map(javascript).join(', ')})`);
|
|
292
|
+
sources.push(new Source(kind, kind === 'query' ? 'true' : 'false', body, line, file));
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
return { kind: 'me', text: '// Compiled from controlled Mathematical English to Logic Script.\n\n' + clauses.join('\n') + '\n',
|
|
297
|
+
program: new Program(sources), prefixes: {}, compiled: { statements } };
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
function meTerm(term, names) {
|
|
301
|
+
if (term instanceof Var) return names.get(term.name);
|
|
302
|
+
if (term === EMPTY) return '[]';
|
|
303
|
+
if (typeof term === 'string') {
|
|
304
|
+
return /^[A-Za-z][A-Za-z0-9_]*$/.test(term) && !VARIABLE.test(term) && !SENTENCE_WORDS.has(term.toLowerCase()) ? term : JSON.stringify(term);
|
|
305
|
+
}
|
|
306
|
+
if (typeof term === 'bigint' || typeof term === 'number') return write(term);
|
|
307
|
+
if (!(term instanceof Struct)) throw new EyemindError('cannot write this term as Mathematical English');
|
|
308
|
+
if (term.name === 'skolem' && term.args.length === 3) {
|
|
309
|
+
const [rule, label, bindings] = term.args, args = listItems(bindings);
|
|
310
|
+
if (typeof rule === 'bigint' && rule > 0n && typeof label === 'string' && args !== null) {
|
|
311
|
+
const name = VARIABLE.test(label) ? label : JSON.stringify(label);
|
|
312
|
+
return `witness(rule ${rule}, ${name}${args.map((arg) => ', ' + meTerm(arg, names)).join('')})`;
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
if (term.name === '.') {
|
|
316
|
+
const items = listItems(term);
|
|
317
|
+
if (items !== null) return `[${items.map((item) => meTerm(item, names)).join(', ')}]`;
|
|
318
|
+
// Improper lists remain explicit compounds.
|
|
319
|
+
}
|
|
320
|
+
return `${JSON.stringify(term.name)}(${term.args.map((arg) => meTerm(arg, names)).join(', ')})`;
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
function meGoal(term, names) {
|
|
324
|
+
if (term === 'false') return 'Contradiction';
|
|
325
|
+
if (typeof term === 'string' && NAME.test(term) && !RESERVED.has(term)) return meTerm(term, names);
|
|
326
|
+
if (!(term instanceof Struct) || !NAME.test(term.name) || RESERVED.has(term.name)) {
|
|
327
|
+
throw new EyemindError(`${write(term)} is not a Mathematical English relation; use --to eyemind`);
|
|
328
|
+
}
|
|
329
|
+
const article = /^[aeiou]/.test(term.name) ? 'an' : 'a';
|
|
330
|
+
if (term.args.length === 1) return `${meTerm(term.args[0], names)} is ${article} ${term.name}`;
|
|
331
|
+
if (term.args.length === 2) return `${meTerm(term.args[0], names)} is ${article} ${term.name} of ${meTerm(term.args[1], names)}`;
|
|
332
|
+
return `${term.name}(${term.args.map((arg) => meTerm(arg, names)).join(', ')})`;
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
export function writeMe(result) {
|
|
336
|
+
const lines = [];
|
|
337
|
+
for (const answer of result.answers) {
|
|
338
|
+
const term = readTerm(answer);
|
|
339
|
+
const names = new Map([...variablesIn([term])].map((name, i) => [name, `X${i}`]));
|
|
340
|
+
const quantifier = names.size ? `For every ${[...names.values()].join(' and ')}, ` : '';
|
|
341
|
+
lines.push(quantifier + flattenConjunction(term).map((goal) => meGoal(goal, names)).join(' and ') + '.');
|
|
342
|
+
}
|
|
343
|
+
return lines.length ? lines.join('\n') + '\n' : '# No conclusions.\n';
|
|
344
|
+
}
|
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.
|
|
2
|
+
export const VERSION = '0.7.0';
|