eyemind 0.6.7 → 0.7.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/LOGICAL-ENGLISH.md +302 -0
- package/README.md +51 -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/le-odrl.js +145 -0
- package/src/le.js +373 -0
- package/src/version.js +1 -1
|
@@ -0,0 +1,302 @@
|
|
|
1
|
+
# Logical English
|
|
2
|
+
|
|
3
|
+
eyemind reads `.le` files as the 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
|
+
| LE 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
|
+
| `T has relation U` | `relation(T, U)` |
|
|
62
|
+
| `relation(T, U, ...)` | The corresponding compound goal. |
|
|
63
|
+
| `relation` | An atom used as a goal, with arity zero. |
|
|
64
|
+
|
|
65
|
+
The articles `a` and `an` have the same semantics. They do not introduce an
|
|
66
|
+
existential variable. For example, `Socrates is a human.` states
|
|
67
|
+
`fact(human('Socrates'))`. Write an existential declaration to introduce an
|
|
68
|
+
unnamed individual.
|
|
69
|
+
|
|
70
|
+
`and` joins positive statements. A sentence containing only positive statements
|
|
71
|
+
states them as facts. A universally quantified fact is explicit:
|
|
72
|
+
|
|
73
|
+
```text
|
|
74
|
+
Ada is a human and Ada is a mathematician.
|
|
75
|
+
For every X, matching(pair(X, X)).
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
Variables declared by `For every` are universal within that sentence. Each
|
|
79
|
+
sentence has its own scope. Repeating a declaration in one scope is an error.
|
|
80
|
+
|
|
81
|
+
## Rules and calculations
|
|
82
|
+
|
|
83
|
+
```text
|
|
84
|
+
Every human is mortal.
|
|
85
|
+
Every human is mortal and animal.
|
|
86
|
+
For every X and Y, if X is a parent of Y then X is an ancestor of Y.
|
|
87
|
+
If Alice is a person then Alice is a participant.
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
`Every A is B.` compiles to `implies(A(X), B(X))`, with a fresh clause-local
|
|
91
|
+
variable. An if/then sentence compiles its premises and conclusions to one
|
|
92
|
+
forward LS rule. Both sides may contain conjunctions. A conclusion variable
|
|
93
|
+
must be supplied by a premise or explicitly declared existentially. The
|
|
94
|
+
compiler checks the stated order of premises for calculations and absence tests;
|
|
95
|
+
actual values must also satisfy LS's runtime requirements.
|
|
96
|
+
|
|
97
|
+
These additional forms are available in premises and questions:
|
|
98
|
+
|
|
99
|
+
| LE form | LS goal |
|
|
100
|
+
| --- | --- |
|
|
101
|
+
| `Y is the value of E` | `is(Y, E)` |
|
|
102
|
+
| `X is greater than E` | `gt(X, E)` |
|
|
103
|
+
| `X is less than E` | `lt(X, E)` |
|
|
104
|
+
| `X is at least E` | `ge(X, E)` |
|
|
105
|
+
| `X is at most E` | `le(X, E)` |
|
|
106
|
+
| `X is equal to E` | `eq(X, E)` |
|
|
107
|
+
| `X is different from E` | `ne(X, E)` |
|
|
108
|
+
|
|
109
|
+
Expressions contain numbers, declared variables, parentheses, unary `-` and
|
|
110
|
+
binary `+`, `-`, `*`, `/`. Unary minus binds most tightly, then multiplication
|
|
111
|
+
and division, then addition and subtraction. Binary operators associate left.
|
|
112
|
+
They compile to `neg`, `add`, `sub`, `mul` and `div`. Only the value-of form
|
|
113
|
+
binds its left variable; comparisons require their inputs beforehand.
|
|
114
|
+
|
|
115
|
+
```text
|
|
116
|
+
4 is an integer.
|
|
117
|
+
For every X and Y, if X is an integer and Y is the value of X * X
|
|
118
|
+
then Y is a square of X.
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
Arithmetic follows LS: integer addition, subtraction and multiplication are
|
|
122
|
+
exact; division returns a float; mixed integer/float arithmetic returns a
|
|
123
|
+
float. Numeric equality compares values, while ordinary relation matching
|
|
124
|
+
keeps integer and float terms distinct. Calculations belong in premises,
|
|
125
|
+
followed by relational conclusions. These calculations do not prove arbitrary
|
|
126
|
+
algebraic identities or supply induction.
|
|
127
|
+
|
|
128
|
+
## Absence and existential conclusions
|
|
129
|
+
|
|
130
|
+
An absence test has exactly this form, followed by one positive statement:
|
|
131
|
+
|
|
132
|
+
```text
|
|
133
|
+
For every X, if X is a person and it is not known that X is blocked
|
|
134
|
+
then X is an applicant.
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
It compiles to `not(blocked(X))`. Its variables must be supplied by earlier
|
|
138
|
+
positive premises or calculations. LS stratification decides when the tested
|
|
139
|
+
relation is complete. This means absence of a proof in this program, rather
|
|
140
|
+
than classical mathematical negation. Ordinary `not` is rejected. Explicit
|
|
141
|
+
negative evidence can use its own positive relation, such as `not_human`.
|
|
142
|
+
|
|
143
|
+
```text
|
|
144
|
+
For every X, if X is a person then there exists Y such that
|
|
145
|
+
Y is a record and X is an owner of Y.
|
|
146
|
+
There exists X such that X is a record.
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
`there exists` introduces fresh variables for a conclusion, after any universal
|
|
150
|
+
declarations. Every introduced variable must occur in that conclusion. The
|
|
151
|
+
compiler uses an ordinary LS forward rule with head-only variables; a standalone
|
|
152
|
+
existential sentence uses premise `'true'`. LS supplies Skolem witnesses. The
|
|
153
|
+
same variable shares one witness across the heads of that firing. A witness
|
|
154
|
+
does not assert a distinct real-world object or a minimum number of objects.
|
|
155
|
+
|
|
156
|
+
## Questions and contradictions
|
|
157
|
+
|
|
158
|
+
```text
|
|
159
|
+
Find every X such that X is mortal.
|
|
160
|
+
Find every X and Y such that X is an ancestor of Y.
|
|
161
|
+
Find whether Socrates is mortal.
|
|
162
|
+
For every X, it is impossible that X is a person and X is blocked.
|
|
163
|
+
It is impossible that Alice is blocked.
|
|
164
|
+
Contradiction.
|
|
165
|
+
```
|
|
166
|
+
|
|
167
|
+
Questions compile to `query(...)`; their declarations establish variable scope,
|
|
168
|
+
and the answers are instances of the whole question, without a separate
|
|
169
|
+
projection. `Find whether` introduces no variables. A question can use a
|
|
170
|
+
conjunction, calculations and absence tests. Without questions the run reports
|
|
171
|
+
derived conclusions, following LS's default; given facts alone are not printed.
|
|
172
|
+
|
|
173
|
+
`It is impossible that` compiles to an LS contradiction with the stated body.
|
|
174
|
+
`Contradiction.` is an unconditional contradiction, also used to serialize a
|
|
175
|
+
run's `'false'` conclusion. Contradictions halt reasoning with exit code 65;
|
|
176
|
+
they do not produce the continuing RDF conflict reports of `--owl-rl`.
|
|
177
|
+
|
|
178
|
+
## ODRL snapshots
|
|
179
|
+
|
|
180
|
+
An LE file can explicitly select the existing ODRL snapshot evaluator:
|
|
181
|
+
|
|
182
|
+
```text
|
|
183
|
+
Use ODRL snapshot logic with namespace "https://example.org/handicap-card#".
|
|
184
|
+
|
|
185
|
+
evaluation is an evaluation.
|
|
186
|
+
evaluation has policy eligibility.
|
|
187
|
+
evaluation has request issueAlice.
|
|
188
|
+
evaluation has conflictStrategy prohibit.
|
|
189
|
+
```
|
|
190
|
+
|
|
191
|
+
This directive must be the first sentence of one file. The remainder contains
|
|
192
|
+
ground facts using the snapshot vocabulary, without rules or questions. The
|
|
193
|
+
compiler maps those facts to RDF and includes the validation, evaluation and
|
|
194
|
+
reporting LS of `src/odrl.js`. The same
|
|
195
|
+
[snapshot profile](https://eyereasoner.github.io/eyemind/#odrl-snapshots) applies
|
|
196
|
+
to Turtle and LE, including missing observations, unsupported policy features
|
|
197
|
+
and conflict strategies. Vocabulary by itself does not enable evaluation.
|
|
198
|
+
|
|
199
|
+
Names expand as follows, with case preserved:
|
|
200
|
+
|
|
201
|
+
| LE form or name | RDF mapping |
|
|
202
|
+
| --- | --- |
|
|
203
|
+
| An ordinary individual name | An IRI formed by appending it to the declared namespace. |
|
|
204
|
+
| Classes `evaluation`, `request`, `state` | `eval:Evaluation`, `eval:Request`, `eval:State`. |
|
|
205
|
+
| Classes `policy`, `agreement`, `permission`, `prohibition`, `constraint`, `action` | `odrl:Set`, `odrl:Agreement`, `odrl:Permission`, `odrl:Prohibition`, `odrl:Constraint`, `odrl:Action`. |
|
|
206
|
+
| Classes `assetCollection`, `partyCollection` | ODRL collection classes, rejected by the snapshot profile. |
|
|
207
|
+
| Properties `policy`, `request`, `state`, `subject`, `conflictStrategy` | The corresponding `eval:` properties. |
|
|
208
|
+
| Properties `profile`, `permission`, `prohibition`, `assignee`, `assigner`, `action`, `target`, `constraint`, `leftOperand`, `operator`, `rightOperand` | The corresponding `odrl:` properties. |
|
|
209
|
+
| Property `policyConflict` | `odrl:conflict`, the policy-local strategy. |
|
|
210
|
+
| Property `type` | `rdf:type`. |
|
|
211
|
+
| An otherwise unknown class or property | An IRI in the declared namespace; validation still applies. |
|
|
212
|
+
| Values `snapshotProfile`, `perm`, `prohibit`, `invalid`, `eq`, `neq`, `gt`, `gteq`, `lt`, `lteq` | `eval:SnapshotProfile` or the corresponding ODRL strategy/operator IRIs. |
|
|
213
|
+
| Values `true`, `false` | Boolean RDF literals. Quoting does not change an LE name into an RDF string literal. |
|
|
214
|
+
| An integer or float | An exact RDF integer or an `xsd:double` literal. |
|
|
215
|
+
|
|
216
|
+
The unsupported ODRL properties `duty`, `obligation`, `inheritFrom`, `includedIn`,
|
|
217
|
+
`partOf` and `refinement` retain their ODRL IRIs so the shared validator can
|
|
218
|
+
report them. Explicit RDF values such as `iri("https://example.org/item")` and
|
|
219
|
+
`literal("text", datatype("http://www.w3.org/2001/XMLSchema#string"))` retain
|
|
220
|
+
their terms. `rdf(S, P, O)` facts allow any explicit RDF predicate without an
|
|
221
|
+
abbreviation. A snapshot still has one default graph.
|
|
222
|
+
|
|
223
|
+
The [handicap-card LE example](https://eyereasoner.github.io/eyemind/examples/deck/handicap-card-le)
|
|
224
|
+
contains the complete policies, requests and SOTW. Run it without CLI switches:
|
|
225
|
+
|
|
226
|
+
```sh
|
|
227
|
+
eyemind examples/handicap-card-le.le
|
|
228
|
+
eyemind --program examples/handicap-card-le.le > /tmp/handicap-card-le.js
|
|
229
|
+
eyemind --to turtle /tmp/handicap-card-le.js
|
|
230
|
+
```
|
|
231
|
+
|
|
232
|
+
Its default output is an LE report whose first sentence is
|
|
233
|
+
`Use ODRL vocabulary with namespace "https://example.org/handicap-card#".`.
|
|
234
|
+
That directive reads RDF data without evaluating policies. This makes the report
|
|
235
|
+
readable as input again, preserving every RDF fact and witness. Report properties
|
|
236
|
+
use `has`; for example `issueAlice has decision allowed.`. Status values
|
|
237
|
+
`allowed`, `prohibited`, `notApplicable`, `undetermined`, `valid` and
|
|
238
|
+
`invalidReport` name the corresponding `eval:` IRIs. Report classes include
|
|
239
|
+
`evaluationReport`, `conflict`, `validationError` and `uncertainty`.
|
|
240
|
+
`conflict` as a property means `eval:conflict`; `applicablePermission`,
|
|
241
|
+
`applicableProhibition` and `reportConstraint` distinguish the report's
|
|
242
|
+
`eval:permission`, `eval:prohibition` and `eval:constraint` links from ODRL
|
|
243
|
+
input properties. Other report fields retain their `eval:` names. An IRI with
|
|
244
|
+
no unambiguous abbreviation stays explicit, including IRIs inside witness keys.
|
|
245
|
+
|
|
246
|
+
Both ODRL directives take a single LE file and reject mixed-in ordinary LE
|
|
247
|
+
rules or questions. `--goal` can query their compiled LS program. The normal
|
|
248
|
+
`--odrl` switch continues to select the Turtle snapshot compiler.
|
|
249
|
+
|
|
250
|
+
## Output, compilation and checking
|
|
251
|
+
|
|
252
|
+
LE inputs default to `.le` conclusions. Each answer becomes a sentence:
|
|
253
|
+
|
|
254
|
+
```text
|
|
255
|
+
Socrates is a mortal.
|
|
256
|
+
16 is a square of 4.
|
|
257
|
+
Alice is an owner of witness(rule 4, Y, Alice).
|
|
258
|
+
```
|
|
259
|
+
|
|
260
|
+
`witness(rule 4, Y, Alice)` names the witness for existential variable `Y` of
|
|
261
|
+
rule 4 with argument Alice. It reads back as `skolem(4, 'Y', ['Alice'])` in LS.
|
|
262
|
+
The label `Y` in this position is a name, independent of any declared LE
|
|
263
|
+
variable. A label outside the variable-name syntax is quoted. Additional
|
|
264
|
+
arguments follow as more comma-separated terms; a witness without arguments
|
|
265
|
+
is `witness(rule 4, Y)`. The rule number, label and arguments all contribute
|
|
266
|
+
to its identity. Ordinary compounds named witness retain their quoted spelling.
|
|
267
|
+
|
|
268
|
+
Unary and binary relations use the class and relation-of forms; relations with
|
|
269
|
+
more arguments use calls. Names are quoted when required to preserve their
|
|
270
|
+
meaning. Compound names are quoted. Variable answers use `For every X0 and X1,
|
|
271
|
+
...`, consistently renaming their variables while retaining sharing. A conjunctive
|
|
272
|
+
answer uses `and`. These sentences can be loaded as facts in another `.le`
|
|
273
|
+
program. An empty answer set is `# No conclusions.`. The writer rejects goals
|
|
274
|
+
outside these relational forms instead of silently changing their meaning.
|
|
275
|
+
|
|
276
|
+
```sh
|
|
277
|
+
eyemind examples/socrates-le.le
|
|
278
|
+
eyemind --program examples/socrates-le.le > /tmp/socrates-le.js
|
|
279
|
+
eyemind --to le /tmp/socrates-le.js
|
|
280
|
+
eyemind --proof examples/socrates-le.le > /tmp/socrates-le-proof.js
|
|
281
|
+
eyemind --check-proof /tmp/socrates-le-proof.js examples/socrates-le.le
|
|
282
|
+
```
|
|
283
|
+
|
|
284
|
+
Multiple `.le` files form one program in file order; they do not mix with other
|
|
285
|
+
input formats or the RDF logic switches. Standard input remains LS; `--to le`
|
|
286
|
+
can write supported LS conclusions as LE. `--goal` uses LS goal syntax and
|
|
287
|
+
defaults to LS output; add `--to le` for LE output. `--all` applies to RDF and N3
|
|
288
|
+
output, without changing LE's selected conclusions.
|
|
289
|
+
|
|
290
|
+
The compiler reads data without executing it and emits standalone `.js` LS
|
|
291
|
+
using explicit constructors to retain names and numeric types. Comments in the
|
|
292
|
+
compiled text identify the source file and sentence line. Parser errors name
|
|
293
|
+
that location. LE runs use LS's usual work bounds, which can be overridden by
|
|
294
|
+
the CLI. Existential or recursive rules can still have an infinite closure.
|
|
295
|
+
|
|
296
|
+
Proofs and check reports are `.js` documents and use the existing LS checker.
|
|
297
|
+
Checking establishes the compiled LS result. It does not independently validate
|
|
298
|
+
the English-to-LS translation; that contract is this grammar and its tests.
|
|
299
|
+
|
|
300
|
+
Supported sentences have no disjunctive conclusions, pronouns, implicit
|
|
301
|
+
assumptions, set comprehension, higher-order quantification or proof blocks.
|
|
302
|
+
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. **Logical English (LE)** also compiles to LS and writes `.le` 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 142 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
|
+
- [Logical English](#logical-english)
|
|
21
22
|
- [RDF 1.2](#rdf-12)
|
|
22
23
|
- [Notation3](#notation3)
|
|
23
24
|
- [RDF Messages](#rdf-messages)
|
|
@@ -179,6 +180,50 @@ 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
|
+
### Logical English
|
|
184
|
+
|
|
185
|
+
A `.le` file is [Logical English](https://eyereasoner.github.io/eyemind/LOGICAL-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-le.le > /tmp/socrates-le.le
|
|
198
|
+
eyemind --program examples/socrates-le.le > /tmp/socrates-le.js
|
|
199
|
+
eyemind --to le /tmp/socrates-le.js
|
|
200
|
+
eyemind --proof examples/socrates-le.le > /tmp/socrates-le-proof.js
|
|
201
|
+
eyemind --check-proof /tmp/socrates-le-proof.js examples/socrates-le.le
|
|
202
|
+
```
|
|
203
|
+
|
|
204
|
+
Conclusions default to `.le`: `Socrates is a mortal.`. They can supply facts to
|
|
205
|
+
another LE program. `--to le` 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 `.le` 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`. LE uses the ordinary LS resource
|
|
216
|
+
bounds; recursive and existential rules can still have an infinite closure.
|
|
217
|
+
|
|
218
|
+
The playground loads LE examples and downloads conclusions as `output.le`.
|
|
219
|
+
Try [Socrates](https://eyereasoner.github.io/eyemind/examples/deck/socrates-le),
|
|
220
|
+
[exact squares](https://eyereasoner.github.io/eyemind/examples/deck/squares-le)
|
|
221
|
+
and [record creation](https://eyereasoner.github.io/eyemind/examples/deck/records-le).
|
|
222
|
+
The [handicap-card LE snapshot](https://eyereasoner.github.io/eyemind/examples/deck/handicap-card-le)
|
|
223
|
+
explicitly selects the shared ODRL evaluator with `Use ODRL snapshot logic with
|
|
224
|
+
namespace ...`. It expresses the Turtle example's policies and SOTW as English
|
|
225
|
+
property facts and writes the same decisions and conflicts as an LE report.
|
|
226
|
+
|
|
182
227
|
### RDF 1.2
|
|
183
228
|
|
|
184
229
|
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 +715,7 @@ eyemind [OPTION ...] [FILE ...]
|
|
|
670
715
|
|
|
671
716
|
| Option | Meaning |
|
|
672
717
|
| --- | --- |
|
|
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
|
|
718
|
+
| (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 `.le` Logical English. |
|
|
674
719
|
| `-p`, `--proof` | Print the proof instead. |
|
|
675
720
|
| `-c`, `--prove-and-check` | Generate a proof, check it, and print the checked answers with the report. |
|
|
676
721
|
| `--check-proof FILE` | Check a saved proof (`-` for standard input) against the program. |
|
|
@@ -680,7 +725,7 @@ eyemind [OPTION ...] [FILE ...]
|
|
|
680
725
|
| `--stream-messages` | Read an RDF Message Log and run the rules independently per message; Node reads files, stdin and HTTP(S) incrementally. |
|
|
681
726
|
| `--stats` | Print reasoning statistics as JSON to standard error. |
|
|
682
727
|
| `--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. |
|
|
728
|
+
| `--to FORMAT` | Write the conclusions as `turtle`, `trig`, `n-triples`, `n-quads`, `n3`, `le` or `eyemind`; by default LE for LE, N3 for N3, Turtle for SRL, ODRL, RDFS and OWL-RL, eyemind otherwise. |
|
|
684
729
|
| `--all` | With RDF or N3 output, write the given data too. |
|
|
685
730
|
| `--program` | Print the program the inputs compile to. |
|
|
686
731
|
| `--odrl` | Add the ODRL snapshot profile's validation and evaluation LS to one Turtle input. |
|
|
@@ -695,7 +740,7 @@ each goal as a data document, with an array denoting conjunction. With
|
|
|
695
740
|
`--check-proof`, supply the original goals the proof answers.
|
|
696
741
|
An option that takes a value requires it immediately afterward; another
|
|
697
742
|
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;
|
|
743
|
+
With `--goal`, answers default to eyemind terms even for LE, N3, SRL, ODRL, RDFS and OWL-RL inputs;
|
|
699
744
|
use `--to` to request another output format.
|
|
700
745
|
|
|
701
746
|
With `--prove-and-check`, reasoning bounds and `--stats` apply to proof
|
|
@@ -796,7 +841,7 @@ console.log(result.bindings);
|
|
|
796
841
|
console.log(checkProof(socrates, result.proof, { goals }).valid);
|
|
797
842
|
```
|
|
798
843
|
|
|
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.
|
|
844
|
+
`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(program))` writes its conclusions as LE.
|
|
800
845
|
|
|
801
846
|
## What is deliberately absent
|
|
802
847
|
|
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.1",
|
|
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
|
+
"LOGICAL-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 .le as Logical 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, le or eyemind (default: le for LE, 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', 'le'].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 Logical 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
|
+
// .le Logical 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 { compileLe, writeLe } from './le.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', 'le'];
|
|
33
35
|
|
|
34
|
-
// What a file holds: 'js', 'rdf', 'n3' or '
|
|
36
|
+
// What a file holds: 'js', 'rdf', 'n3', 'srl' or 'le'.
|
|
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 (/\.le$/i.test(name)) return 'le';
|
|
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', 'le', '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('le')) {
|
|
75
|
+
if (kinds.some((kind) => kind !== 'le') || odrl || rdfs || owlRl) {
|
|
76
|
+
throw new EyemindError('a Logical English run takes .le files without RDF logic switches or other input formats');
|
|
77
|
+
}
|
|
78
|
+
return compileLe(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: LE for LE, 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) => ({ le: 'le', 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 === 'le') return writeLe(result, { odrl: loaded.compiled?.odrl ?? null });
|
|
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/le-odrl.js
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
// LE names for the existing ODRL snapshot profile. This module maps data and
|
|
2
|
+
// reports; validation and evaluation remain the rules of odrl.js.
|
|
3
|
+
import { compileOdrl, ODRL_EVAL } from './odrl.js';
|
|
4
|
+
import { loadText } from './lang.js';
|
|
5
|
+
import { DEFAULT_GRAPH, writeRdf } from './rdf.js';
|
|
6
|
+
import { EyemindError, Struct, isGround } from './terms.js';
|
|
7
|
+
import { readTerm } from './reader.js';
|
|
8
|
+
import { write } from './writer.js';
|
|
9
|
+
|
|
10
|
+
const ODRL = 'http://www.w3.org/ns/odrl/2/';
|
|
11
|
+
const RDF = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#';
|
|
12
|
+
const XSD = 'http://www.w3.org/2001/XMLSchema#';
|
|
13
|
+
const iri = (value) => new Struct('iri', [value]);
|
|
14
|
+
const literal = (value, type) => new Struct('literal', [value, new Struct('datatype', [XSD + type])]);
|
|
15
|
+
const NAME = /^[a-z][A-Za-z0-9_]*$/;
|
|
16
|
+
const TYPES = new Map(Object.entries({
|
|
17
|
+
evaluation: ODRL_EVAL + 'Evaluation', policy: ODRL + 'Set', agreement: ODRL + 'Agreement',
|
|
18
|
+
permission: ODRL + 'Permission', prohibition: ODRL + 'Prohibition', constraint: ODRL + 'Constraint',
|
|
19
|
+
request: ODRL_EVAL + 'Request', state: ODRL_EVAL + 'State', action: ODRL + 'Action',
|
|
20
|
+
assetCollection: ODRL + 'AssetCollection', partyCollection: ODRL + 'PartyCollection',
|
|
21
|
+
evaluationReport: ODRL_EVAL + 'EvaluationReport', conflict: ODRL_EVAL + 'Conflict',
|
|
22
|
+
validationError: ODRL_EVAL + 'ValidationError', uncertainty: ODRL_EVAL + 'Uncertainty',
|
|
23
|
+
}));
|
|
24
|
+
const PROPERTIES = new Map();
|
|
25
|
+
for (const name of ['profile', 'permission', 'prohibition', 'assignee', 'assigner', 'action', 'target',
|
|
26
|
+
'constraint', 'leftOperand', 'operator', 'rightOperand', 'duty', 'obligation', 'inheritFrom',
|
|
27
|
+
'includedIn', 'partOf', 'refinement']) PROPERTIES.set(name, ODRL + name);
|
|
28
|
+
for (const name of ['policy', 'request', 'state', 'subject', 'conflictStrategy', 'decision', 'canHappen',
|
|
29
|
+
'validationStatus', 'invalidPolicy', 'reason', 'unmetConstraint', 'uncertainty', 'rule', 'property',
|
|
30
|
+
'validationError', 'focus', 'code', 'permissionPolicy', 'permissionRule', 'prohibitionPolicy',
|
|
31
|
+
'prohibitionRule', 'conflictCount']) PROPERTIES.set(name, ODRL_EVAL + name);
|
|
32
|
+
// A conflict is an evaluation report link; policy-local conflict has a
|
|
33
|
+
// separate name so neither meaning silently replaces the other.
|
|
34
|
+
PROPERTIES.set('conflict', ODRL_EVAL + 'conflict');
|
|
35
|
+
PROPERTIES.set('policyConflict', ODRL + 'conflict');
|
|
36
|
+
PROPERTIES.set('applicablePermission', ODRL_EVAL + 'permission');
|
|
37
|
+
PROPERTIES.set('applicableProhibition', ODRL_EVAL + 'prohibition');
|
|
38
|
+
PROPERTIES.set('reportConstraint', ODRL_EVAL + 'constraint');
|
|
39
|
+
PROPERTIES.set('type', RDF + 'type');
|
|
40
|
+
const VALUES = new Map(Object.entries({
|
|
41
|
+
snapshotProfile: ODRL_EVAL + 'SnapshotProfile',
|
|
42
|
+
perm: ODRL + 'perm', prohibit: ODRL + 'prohibit', invalid: ODRL + 'invalid',
|
|
43
|
+
eq: ODRL + 'eq', neq: ODRL + 'neq', gt: ODRL + 'gt', gteq: ODRL + 'gteq', lt: ODRL + 'lt', lteq: ODRL + 'lteq',
|
|
44
|
+
allowed: ODRL_EVAL + 'Allowed', prohibited: ODRL_EVAL + 'Prohibited',
|
|
45
|
+
notApplicable: ODRL_EVAL + 'NotApplicable', undetermined: ODRL_EVAL + 'Undetermined',
|
|
46
|
+
valid: ODRL_EVAL + 'Valid', invalidReport: ODRL_EVAL + 'Invalid',
|
|
47
|
+
}));
|
|
48
|
+
const reverse = (map) => new Map([...map].map(([name, value]) => [value, name]));
|
|
49
|
+
const TYPE_NAMES = reverse(TYPES), PROPERTY_NAMES = reverse(PROPERTIES), VALUE_NAMES = reverse(VALUES);
|
|
50
|
+
|
|
51
|
+
function rdfValue(term, namespace) {
|
|
52
|
+
if (typeof term === 'string') {
|
|
53
|
+
if (term === 'true' || term === 'false') return literal(term, 'boolean');
|
|
54
|
+
return iri(VALUES.get(term) ?? namespace + term);
|
|
55
|
+
}
|
|
56
|
+
if (typeof term === 'bigint') return term;
|
|
57
|
+
if (typeof term === 'number') return literal(write(term), 'double');
|
|
58
|
+
if (term instanceof Struct && ['iri', 'bnode', 'literal', 'triple', 'skolem'].includes(term.name)) return term;
|
|
59
|
+
throw new EyemindError('LE ODRL values need names, numbers or explicit RDF terms such as iri(...) and literal(...)');
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function resource(term) {
|
|
63
|
+
return term instanceof Struct && ['iri', 'bnode', 'triple', 'skolem'].includes(term.name);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export function compileOdrlLe(statements, profile, source) {
|
|
67
|
+
const { namespace, evaluate } = profile;
|
|
68
|
+
const quads = [];
|
|
69
|
+
for (const statement of statements) {
|
|
70
|
+
if (statement.kind !== 'fact') throw new EyemindError(`${statement.file}: line ${statement.line}: an LE ODRL snapshot or report contains ground facts, not rules or questions`);
|
|
71
|
+
for (const head of statement.heads) {
|
|
72
|
+
if (!(head instanceof Struct) || !isGround(head)) throw new EyemindError(`${statement.file}: line ${statement.line}: an LE ODRL fact needs a ground class or property statement`);
|
|
73
|
+
let s, p, o;
|
|
74
|
+
if (head.name === 'rdf' && head.args.length === 3) [s, p, o] = head.args;
|
|
75
|
+
else if (head.args.length === 1) {
|
|
76
|
+
s = rdfValue(head.args[0], namespace); p = iri(RDF + 'type');
|
|
77
|
+
o = iri(TYPES.get(head.name) ?? namespace + head.name);
|
|
78
|
+
} else if (head.args.length === 2) {
|
|
79
|
+
s = rdfValue(head.args[0], namespace); p = iri(PROPERTIES.get(head.name) ?? namespace + head.name);
|
|
80
|
+
o = rdfValue(head.args[1], namespace);
|
|
81
|
+
} else throw new EyemindError(`${statement.file}: line ${statement.line}: use class facts, binary properties or explicit rdf(S, P, O) facts in LE ODRL`);
|
|
82
|
+
if (!resource(s) || !(p instanceof Struct && p.name === 'iri' && p.args.length === 1)) {
|
|
83
|
+
throw new EyemindError(`${statement.file}: line ${statement.line}: an LE ODRL triple needs a resource subject and an IRI property`);
|
|
84
|
+
}
|
|
85
|
+
quads.push([s, p, o, DEFAULT_GRAPH]);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
// Validate RDF constructors without rewriting terms or witness identities.
|
|
89
|
+
const pending = quads.flatMap((quad) => quad.slice(0, 3));
|
|
90
|
+
while (pending.length) {
|
|
91
|
+
const term = pending.pop();
|
|
92
|
+
if (!(term instanceof Struct) || ['skolem', 'bnode'].includes(term.name)) continue;
|
|
93
|
+
if (term.name === 'iri' || term.name === 'datatype') {
|
|
94
|
+
const [value] = term.args;
|
|
95
|
+
if (term.args.length !== 1 || typeof value !== 'string' || !/^[A-Za-z][A-Za-z0-9+.-]*:/.test(value) || /[\s<>"{}|^`\\]/u.test(value)) {
|
|
96
|
+
throw new EyemindError('LE ODRL IRIs and datatype IRIs must be absolute, without whitespace or forbidden characters');
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
pending.push(...term.args);
|
|
100
|
+
}
|
|
101
|
+
writeRdf(quads, { format: 'n-triples' });
|
|
102
|
+
const prefixes = { '': namespace, odrl: ODRL, eval: ODRL_EVAL };
|
|
103
|
+
let loaded;
|
|
104
|
+
if (evaluate) loaded = compileOdrl({ quads, prefixes }, { source });
|
|
105
|
+
else {
|
|
106
|
+
const facts = quads.map(([s, p, o]) => write(new Struct('rdf', [s, p, o]))).join('\n');
|
|
107
|
+
const text = `// RDF facts from an LE ODRL vocabulary document.\nfacts_from({ text: ${JSON.stringify(facts)} })\n`;
|
|
108
|
+
loaded = { text, program: loadText(text, source), prefixes };
|
|
109
|
+
}
|
|
110
|
+
return { ...loaded, kind: 'le', compiled: { statements, odrl: profile, quads } };
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function leValue(term, namespace) {
|
|
114
|
+
if (term instanceof Struct && term.name === 'iri' && term.args.length === 1) {
|
|
115
|
+
const value = term.args[0], known = VALUE_NAMES.get(value);
|
|
116
|
+
if (known) return known;
|
|
117
|
+
if (value.startsWith(namespace)) {
|
|
118
|
+
const name = value.slice(namespace.length);
|
|
119
|
+
if (/^[A-Za-z][A-Za-z0-9_]*$/.test(name) && !VALUES.has(name) && name !== 'true' && name !== 'false') return name;
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
if (term instanceof Struct && term.name === 'literal' && term.args.length === 2 &&
|
|
123
|
+
term.args[1] instanceof Struct && term.args[1].name === 'datatype' && term.args[1].args[0] === XSD + 'boolean' &&
|
|
124
|
+
['true', 'false'].includes(term.args[0])) return term.args[0];
|
|
125
|
+
return term;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
export function odrlLeReport(result, namespace) {
|
|
129
|
+
const answers = result.answers.map((answer) => {
|
|
130
|
+
const term = readTerm(answer);
|
|
131
|
+
if (!(term instanceof Struct) || term.name !== 'rdf' || term.args.length !== 3) throw new EyemindError('LE ODRL reports need rdf(S, P, O) conclusions');
|
|
132
|
+
const [s, p, o] = term.args;
|
|
133
|
+
if (p instanceof Struct && p.name === 'iri') {
|
|
134
|
+
if (p.args[0] === RDF + 'type' && o instanceof Struct && o.name === 'iri' && TYPE_NAMES.has(o.args[0])) {
|
|
135
|
+
return write(new Struct(TYPE_NAMES.get(o.args[0]), [leValue(s, namespace)]));
|
|
136
|
+
}
|
|
137
|
+
const name = PROPERTY_NAMES.get(p.args[0]) ?? (p.args[0].startsWith(namespace) ? p.args[0].slice(namespace.length) : null);
|
|
138
|
+
if (name && NAME.test(name) && (PROPERTIES.get(name) ?? namespace + name) === p.args[0]) {
|
|
139
|
+
return write(new Struct(name, [leValue(s, namespace), leValue(o, namespace)]));
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
return answer;
|
|
143
|
+
});
|
|
144
|
+
return { answers };
|
|
145
|
+
}
|
package/src/le.js
ADDED
|
@@ -0,0 +1,373 @@
|
|
|
1
|
+
// Logical 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
|
+
import { compileOdrlLe, odrlLeReport } from './le-odrl.js';
|
|
9
|
+
|
|
10
|
+
const st = (name, ...args) => new Struct(name, args);
|
|
11
|
+
const VARIABLE = /^[A-Z][0-9]*$/;
|
|
12
|
+
const NAME = /^[a-z][A-Za-z0-9_]*$/;
|
|
13
|
+
const SENTENCE_WORDS = new Set(['every', 'for', 'if', 'find', 'there', 'it', 'contradiction', 'use']);
|
|
14
|
+
const RESERVED = new Set([...PRIMITIVE_KEYS, ...CONTROL_KEYS, ...RESERVED_KEYS].map((key) => key.split('/')[0]));
|
|
15
|
+
for (const name of ['true', 'false', 'fail']) RESERVED.add(name);
|
|
16
|
+
const OPERATORS = { '+': ['add', 1], '-': ['sub', 1], '*': ['mul', 2], '/': ['div', 2] };
|
|
17
|
+
const list = (items) => items.reduceRight((tail, head) => st('.', head, tail), EMPTY);
|
|
18
|
+
|
|
19
|
+
function listItems(term) {
|
|
20
|
+
const items = [];
|
|
21
|
+
while (term instanceof Struct && term.name === '.' && term.args.length === 2) {
|
|
22
|
+
items.push(term.args[0]);
|
|
23
|
+
term = term.args[1];
|
|
24
|
+
}
|
|
25
|
+
return term === EMPTY ? items : null;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
class Parser {
|
|
29
|
+
constructor(text, file) {
|
|
30
|
+
this.file = file;
|
|
31
|
+
this.tokens = [];
|
|
32
|
+
this.at = 0;
|
|
33
|
+
this.scope = new Map();
|
|
34
|
+
this.depth = 0;
|
|
35
|
+
let line = 1, pos = 0;
|
|
36
|
+
while (pos < text.length) {
|
|
37
|
+
const tail = text.slice(pos);
|
|
38
|
+
const whitespace = /^\s+/.exec(tail);
|
|
39
|
+
if (whitespace) { line += (whitespace[0].match(/\n/g) ?? []).length; pos += whitespace[0].length; continue; }
|
|
40
|
+
if (tail[0] === '#') { const end = text.indexOf('\n', pos); pos = end < 0 ? text.length : end; continue; }
|
|
41
|
+
const match = /^("(?:[^"\\\r\n]|\\.)*"|(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?|[A-Za-z][A-Za-z0-9_]*|[()[\],.+*/-])/.exec(tail);
|
|
42
|
+
if (!match) this.error(`unexpected character ${JSON.stringify(tail[0])}`, line);
|
|
43
|
+
const raw = match[0];
|
|
44
|
+
let value = raw, kind = 'word';
|
|
45
|
+
if (raw[0] === '"') {
|
|
46
|
+
try { value = JSON.parse(raw); } catch { this.error('invalid quoted name; use a JSON string', line); }
|
|
47
|
+
kind = 'string';
|
|
48
|
+
} else if (/^[0-9]/.test(raw)) kind = 'number';
|
|
49
|
+
else if (!/^[A-Za-z]/.test(raw)) kind = 'punct';
|
|
50
|
+
this.tokens.push({ value, raw, kind, line });
|
|
51
|
+
pos += raw.length;
|
|
52
|
+
}
|
|
53
|
+
this.tokens.push({ value: '', raw: '', kind: 'end', line });
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
get token() { return this.tokens[this.at]; }
|
|
57
|
+
error(message, line = this.token?.line ?? 1) { throw new EyemindError(`${this.file}: line ${line}: Logical English: ${message}`); }
|
|
58
|
+
is(word) { return this.token.kind !== 'string' && this.token.value.toLowerCase() === word; }
|
|
59
|
+
take(word) { if (!this.is(word)) return false; this.at++; return true; }
|
|
60
|
+
need(word) { if (!this.take(word)) this.error(`expected ${JSON.stringify(word)}, found ${JSON.stringify(this.token.raw || 'end of input')}`); }
|
|
61
|
+
|
|
62
|
+
name() {
|
|
63
|
+
const token = this.token;
|
|
64
|
+
if (token.kind !== 'word' || !NAME.test(token.value) || RESERVED.has(token.value)) {
|
|
65
|
+
this.error('a relation or class name must start with a lowercase letter and must not name an LS primitive or control');
|
|
66
|
+
}
|
|
67
|
+
this.at++;
|
|
68
|
+
return token.value;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
declarations() {
|
|
72
|
+
const vars = [];
|
|
73
|
+
do {
|
|
74
|
+
const name = this.token.value;
|
|
75
|
+
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');
|
|
76
|
+
if (this.scope.has(name)) this.error(`variable ${name} is already declared in this sentence`);
|
|
77
|
+
const variable = new Var(name);
|
|
78
|
+
this.scope.set(name, variable);
|
|
79
|
+
vars.push(variable);
|
|
80
|
+
this.at++;
|
|
81
|
+
} while (this.take('and'));
|
|
82
|
+
return vars;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
nested(read) {
|
|
86
|
+
if (this.depth >= 256) this.error('terms and expressions may nest at most 256 levels');
|
|
87
|
+
this.depth++;
|
|
88
|
+
try { return read(); } finally { this.depth--; }
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
term() { return this.nested(() => this.termValue()); }
|
|
92
|
+
|
|
93
|
+
termValue() {
|
|
94
|
+
if (this.take('-')) {
|
|
95
|
+
if (this.token.kind !== 'number') this.error('a minus sign in a term needs a number; use the value-of form for arithmetic');
|
|
96
|
+
return this.number(true);
|
|
97
|
+
}
|
|
98
|
+
if (this.token.kind === 'number') return this.number(false);
|
|
99
|
+
if (this.take('[')) {
|
|
100
|
+
const items = [];
|
|
101
|
+
if (!this.take(']')) { do { items.push(this.term()); } while (this.take(',')); this.need(']'); }
|
|
102
|
+
return list(items);
|
|
103
|
+
}
|
|
104
|
+
// The explicit "rule N" marker distinguishes a generated witness from
|
|
105
|
+
// an ordinary compound named witness. Its label is data, not a variable.
|
|
106
|
+
if (this.is('witness') && this.tokens[this.at + 1]?.value === '(' &&
|
|
107
|
+
this.tokens[this.at + 2]?.kind === 'word' && this.tokens[this.at + 2].value.toLowerCase() === 'rule' &&
|
|
108
|
+
(this.tokens[this.at + 3]?.kind === 'number' || this.tokens[this.at + 3]?.value === '-')) {
|
|
109
|
+
this.at += 3;
|
|
110
|
+
const rule = this.term();
|
|
111
|
+
if (typeof rule !== 'bigint' || rule < 1n) this.error('a witness rule number must be a positive integer');
|
|
112
|
+
this.need(',');
|
|
113
|
+
const label = this.token;
|
|
114
|
+
if (label.kind !== 'string' && !(label.kind === 'word' && VARIABLE.test(label.value))) {
|
|
115
|
+
this.error('a witness label must be a variable name such as Y or a quoted name');
|
|
116
|
+
}
|
|
117
|
+
this.at++;
|
|
118
|
+
const args = [];
|
|
119
|
+
while (this.take(',')) args.push(this.term());
|
|
120
|
+
this.need(')');
|
|
121
|
+
return st('skolem', rule, label.value, list(args));
|
|
122
|
+
}
|
|
123
|
+
const token = this.token;
|
|
124
|
+
if (!['word', 'string'].includes(token.kind)) this.error('expected a name, number, variable, list or compound term');
|
|
125
|
+
this.at++;
|
|
126
|
+
if (this.take('(')) {
|
|
127
|
+
const args = [];
|
|
128
|
+
if (!this.take(')')) { do { args.push(this.term()); } while (this.take(',')); this.need(')'); }
|
|
129
|
+
if (!args.length) this.error('a compound term needs at least one argument', token.line);
|
|
130
|
+
return st(token.value, ...args);
|
|
131
|
+
}
|
|
132
|
+
if (token.kind === 'word' && VARIABLE.test(token.value)) {
|
|
133
|
+
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);
|
|
134
|
+
return this.scope.get(token.value);
|
|
135
|
+
}
|
|
136
|
+
return token.value;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
number(negative) {
|
|
140
|
+
const token = this.token;
|
|
141
|
+
this.at++;
|
|
142
|
+
try { return readTerm((negative ? '-' : '') + token.raw); }
|
|
143
|
+
catch { this.error(`invalid or nonfinite number ${(negative ? '-' : '') + token.raw}`, token.line); }
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
expression(min = 0) { return this.nested(() => this.expressionValue(min)); }
|
|
147
|
+
|
|
148
|
+
expressionValue(min) {
|
|
149
|
+
let left;
|
|
150
|
+
if (this.take('-')) left = st('neg', this.expression(3));
|
|
151
|
+
else if (this.take('(')) { left = this.expression(); this.need(')'); }
|
|
152
|
+
else {
|
|
153
|
+
left = this.term();
|
|
154
|
+
if (!(left instanceof Var) && !['bigint', 'number'].includes(typeof left)) this.error('arithmetic operands must be numbers or declared variables');
|
|
155
|
+
}
|
|
156
|
+
while (OPERATORS[this.token.value]?.[1] > min) {
|
|
157
|
+
const [name, precedence] = OPERATORS[this.token.value];
|
|
158
|
+
this.at++;
|
|
159
|
+
left = st(name, left, this.expression(precedence));
|
|
160
|
+
}
|
|
161
|
+
return left;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
atomic(body) {
|
|
165
|
+
if (body && this.take('it')) {
|
|
166
|
+
this.need('is'); this.need('not'); this.need('known'); this.need('that');
|
|
167
|
+
return st('not', this.atomic(false));
|
|
168
|
+
}
|
|
169
|
+
const subject = this.term();
|
|
170
|
+
if (this.take('has')) {
|
|
171
|
+
const name = this.name();
|
|
172
|
+
return st(name, subject, this.term());
|
|
173
|
+
}
|
|
174
|
+
if (this.take('is')) {
|
|
175
|
+
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');
|
|
176
|
+
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');
|
|
177
|
+
if (this.take('a') || this.take('an')) {
|
|
178
|
+
const name = this.name();
|
|
179
|
+
return this.take('of') ? st(name, subject, this.term()) : st(name, subject);
|
|
180
|
+
}
|
|
181
|
+
if (body) {
|
|
182
|
+
if (this.take('the')) {
|
|
183
|
+
this.need('value'); this.need('of');
|
|
184
|
+
if (!(subject instanceof Var) && !['bigint', 'number'].includes(typeof subject)) this.error('a calculation needs a variable or number on its left');
|
|
185
|
+
return st('is', subject, this.expression());
|
|
186
|
+
}
|
|
187
|
+
let comparison;
|
|
188
|
+
if (this.take('greater')) { this.need('than'); comparison = 'gt'; }
|
|
189
|
+
else if (this.take('less')) { this.need('than'); comparison = 'lt'; }
|
|
190
|
+
else if (this.take('at')) {
|
|
191
|
+
if (this.take('least')) comparison = 'ge';
|
|
192
|
+
else { this.need('most'); comparison = 'le'; }
|
|
193
|
+
} else if (this.take('equal')) { this.need('to'); comparison = 'eq'; }
|
|
194
|
+
else if (this.take('different')) { this.need('from'); comparison = 'ne'; }
|
|
195
|
+
if (comparison) {
|
|
196
|
+
if (!(subject instanceof Var) && !['bigint', 'number'].includes(typeof subject)) this.error('a comparison needs a variable or number on its left');
|
|
197
|
+
return st(comparison, subject, this.expression());
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
// Adjectival class form, as in "Every human is mortal".
|
|
201
|
+
return st(this.name(), subject);
|
|
202
|
+
}
|
|
203
|
+
if (subject instanceof Struct && subject.name !== '.' && NAME.test(subject.name) && !RESERVED.has(subject.name)) return subject;
|
|
204
|
+
if (typeof subject === 'string' && NAME.test(subject) && !RESERVED.has(subject)) return subject;
|
|
205
|
+
this.error('expected "is a class", "is a relation of", or a relation call such as parent(Alice, Bob)');
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
goals(body) {
|
|
209
|
+
const goals = [this.atomic(body)];
|
|
210
|
+
while (this.take('and')) goals.push(this.atomic(body));
|
|
211
|
+
return goals;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
sentence() {
|
|
215
|
+
const line = this.token.line;
|
|
216
|
+
this.scope = new Map();
|
|
217
|
+
if (this.is('use') && this.tokens[this.at + 1]?.kind === 'word' && this.tokens[this.at + 1].value.toLowerCase() === 'odrl') {
|
|
218
|
+
this.at++;
|
|
219
|
+
this.need('odrl');
|
|
220
|
+
let evaluate = false;
|
|
221
|
+
if (this.take('snapshot')) { this.need('logic'); evaluate = true; }
|
|
222
|
+
else this.need('vocabulary');
|
|
223
|
+
this.need('with'); this.need('namespace');
|
|
224
|
+
if (this.token.kind !== 'string') this.error('an ODRL namespace must be a quoted absolute IRI');
|
|
225
|
+
const namespace = this.token.value;
|
|
226
|
+
try { new URL(namespace); } catch { this.error('an ODRL namespace must be an absolute IRI'); }
|
|
227
|
+
if (/[\s<>"{}|^`\\]/u.test(namespace)) this.error('an ODRL namespace must be an absolute IRI without whitespace or forbidden characters');
|
|
228
|
+
this.at++; this.need('.');
|
|
229
|
+
return { kind: 'odrl', namespace, evaluate, line };
|
|
230
|
+
}
|
|
231
|
+
if (this.take('every')) {
|
|
232
|
+
const from = this.name(); this.need('is');
|
|
233
|
+
const x = new Var('X'), heads = [];
|
|
234
|
+
do { this.take('a') || this.take('an'); heads.push(st(this.name(), x)); } while (this.take('and'));
|
|
235
|
+
this.need('.');
|
|
236
|
+
return { kind: 'forward', heads, body: [st(from, x)], line };
|
|
237
|
+
}
|
|
238
|
+
let quantified = false;
|
|
239
|
+
if (this.take('for')) { this.need('every'); this.declarations(); this.need(','); quantified = true; }
|
|
240
|
+
let kind = 'fact', body = [], heads = [], witnesses = [];
|
|
241
|
+
if (this.take('find')) {
|
|
242
|
+
if (quantified) this.error('a question introduces its variables with "Find every"');
|
|
243
|
+
if (this.take('every')) { this.declarations(); this.need('such'); this.need('that'); }
|
|
244
|
+
else this.need('whether');
|
|
245
|
+
kind = 'query'; body = this.goals(true);
|
|
246
|
+
} else if (this.take('contradiction')) {
|
|
247
|
+
kind = 'contradiction'; body = ['true'];
|
|
248
|
+
} else if (this.take('it')) {
|
|
249
|
+
this.need('is'); this.need('impossible'); this.need('that');
|
|
250
|
+
kind = 'contradiction'; body = this.goals(true);
|
|
251
|
+
} else {
|
|
252
|
+
if (this.take('if')) { kind = 'forward'; body = this.goals(true); this.need('then'); }
|
|
253
|
+
if (this.take('there')) {
|
|
254
|
+
this.need('exists'); witnesses = this.declarations(); this.need('such'); this.need('that');
|
|
255
|
+
if (kind === 'fact') { kind = 'forward'; body = ['true']; }
|
|
256
|
+
}
|
|
257
|
+
heads = this.goals(false);
|
|
258
|
+
}
|
|
259
|
+
this.need('.');
|
|
260
|
+
const headVars = variablesIn(heads), bound = new Set(), witnessNames = new Set(witnesses.map((v) => v.name));
|
|
261
|
+
for (const goal of body) {
|
|
262
|
+
const required = goal instanceof Struct && RESERVED.has(goal.name) ? variablesIn(goal.name === 'is' ? [goal.args[1]] : [goal]) : new Set();
|
|
263
|
+
for (const name of required) if (!bound.has(name)) this.error(`${name} must be supplied by an earlier positive premise or calculation`, line);
|
|
264
|
+
if (!(goal instanceof Struct && goal.name === 'not')) for (const name of variablesIn([goal])) bound.add(name);
|
|
265
|
+
}
|
|
266
|
+
if (witnesses.some((v) => !headVars.has(v.name))) this.error('every existential variable must occur in its conclusion', line);
|
|
267
|
+
if (kind === 'forward' && [...headVars].some((name) => !bound.has(name) && !witnessNames.has(name))) {
|
|
268
|
+
this.error('a conclusion variable must occur in a premise or be introduced with "there exists"', line);
|
|
269
|
+
}
|
|
270
|
+
return { kind, heads, body, line };
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
function variablesIn(terms) {
|
|
275
|
+
const result = new Set(), pending = [...terms];
|
|
276
|
+
while (pending.length) {
|
|
277
|
+
const term = pending.pop();
|
|
278
|
+
if (term instanceof Var) result.add(term.name);
|
|
279
|
+
else if (term instanceof Struct) pending.push(...term.args);
|
|
280
|
+
}
|
|
281
|
+
return result;
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
// Explicit constructors keep quoted names, floats and reserved JS names safe.
|
|
285
|
+
function javascript(term) {
|
|
286
|
+
if (term instanceof Var) return `vars(${JSON.stringify(term.name)})`;
|
|
287
|
+
if (term instanceof Struct) return `struct(${JSON.stringify(term.name)}, ${term.args.map(javascript).join(', ')})`;
|
|
288
|
+
if (typeof term === 'bigint') return `${term}n`;
|
|
289
|
+
if (typeof term === 'number') return `float(${write(term)})`;
|
|
290
|
+
return JSON.stringify(term);
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
export function compileLe(inputs) {
|
|
294
|
+
const clauses = [], statements = [], sources = [];
|
|
295
|
+
let profile = null;
|
|
296
|
+
for (const [text, file] of inputs) {
|
|
297
|
+
const parser = new Parser(String(text), file);
|
|
298
|
+
while (parser.token.kind !== 'end') {
|
|
299
|
+
const sentence = parser.sentence(), { kind, heads, body, line } = sentence;
|
|
300
|
+
if (kind === 'odrl') {
|
|
301
|
+
if (profile || statements.length || inputs.length !== 1) parser.error('an ODRL directive must be the first sentence of one LE file', line);
|
|
302
|
+
profile = { namespace: sentence.namespace, evaluate: sentence.evaluate };
|
|
303
|
+
continue;
|
|
304
|
+
}
|
|
305
|
+
statements.push({ ...sentence, file });
|
|
306
|
+
clauses.push(`// ${String(file).replace(/[\r\n\u2028\u2029]/g, ' ')}: line ${line}`);
|
|
307
|
+
if (kind === 'fact') {
|
|
308
|
+
for (const head of heads) {
|
|
309
|
+
clauses.push(`fact(${javascript(head)})`);
|
|
310
|
+
sources.push(new Source('fact', head, [], line, file));
|
|
311
|
+
}
|
|
312
|
+
} else if (kind === 'forward') {
|
|
313
|
+
clauses.push(`implies(${javascript(conjunction(body))}, ${javascript(conjunction(heads))})`);
|
|
314
|
+
sources.push(new Source('forward', conjunction(heads), body, line, file));
|
|
315
|
+
} else {
|
|
316
|
+
clauses.push(`${kind}(${body.map(javascript).join(', ')})`);
|
|
317
|
+
sources.push(new Source(kind, kind === 'query' ? 'true' : 'false', body, line, file));
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
if (profile) return compileOdrlLe(statements, profile, inputs[0][1]);
|
|
322
|
+
return { kind: 'le', text: '// Compiled from Logical English to Logic Script.\n\n' + clauses.join('\n') + '\n',
|
|
323
|
+
program: new Program(sources), prefixes: {}, compiled: { statements } };
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
function leTerm(term, names) {
|
|
327
|
+
if (term instanceof Var) return names.get(term.name);
|
|
328
|
+
if (term === EMPTY) return '[]';
|
|
329
|
+
if (typeof term === 'string') {
|
|
330
|
+
return /^[A-Za-z][A-Za-z0-9_]*$/.test(term) && !VARIABLE.test(term) && !SENTENCE_WORDS.has(term.toLowerCase()) ? term : JSON.stringify(term);
|
|
331
|
+
}
|
|
332
|
+
if (typeof term === 'bigint' || typeof term === 'number') return write(term);
|
|
333
|
+
if (!(term instanceof Struct)) throw new EyemindError('cannot write this term as Logical English');
|
|
334
|
+
if (term.name === 'skolem' && term.args.length === 3) {
|
|
335
|
+
const [rule, label, bindings] = term.args, args = listItems(bindings);
|
|
336
|
+
if (typeof rule === 'bigint' && rule > 0n && typeof label === 'string' && args !== null) {
|
|
337
|
+
const name = VARIABLE.test(label) ? label : JSON.stringify(label);
|
|
338
|
+
return `witness(rule ${rule}, ${name}${args.map((arg) => ', ' + leTerm(arg, names)).join('')})`;
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
if (term.name === '.') {
|
|
342
|
+
const items = listItems(term);
|
|
343
|
+
if (items !== null) return `[${items.map((item) => leTerm(item, names)).join(', ')}]`;
|
|
344
|
+
// Improper lists remain explicit compounds.
|
|
345
|
+
}
|
|
346
|
+
return `${JSON.stringify(term.name)}(${term.args.map((arg) => leTerm(arg, names)).join(', ')})`;
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
function leGoal(term, names, properties) {
|
|
350
|
+
if (term === 'false') return 'Contradiction';
|
|
351
|
+
if (typeof term === 'string' && NAME.test(term) && !RESERVED.has(term)) return leTerm(term, names);
|
|
352
|
+
if (!(term instanceof Struct) || !NAME.test(term.name) || RESERVED.has(term.name)) {
|
|
353
|
+
throw new EyemindError(`${write(term)} is not a Logical English relation; use --to eyemind`);
|
|
354
|
+
}
|
|
355
|
+
const article = /^[aeiou]/.test(term.name) ? 'an' : 'a';
|
|
356
|
+
if (term.args.length === 1) return `${leTerm(term.args[0], names)} is ${article} ${term.name}`;
|
|
357
|
+
if (properties && term.args.length === 2) return `${leTerm(term.args[0], names)} has ${term.name} ${leTerm(term.args[1], names)}`;
|
|
358
|
+
if (term.args.length === 2) return `${leTerm(term.args[0], names)} is ${article} ${term.name} of ${leTerm(term.args[1], names)}`;
|
|
359
|
+
return `${term.name}(${term.args.map((arg) => leTerm(arg, names)).join(', ')})`;
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
export function writeLe(result, { odrl = null } = {}) {
|
|
363
|
+
if (odrl) result = odrlLeReport(result, odrl.namespace);
|
|
364
|
+
const lines = [];
|
|
365
|
+
for (const answer of result.answers) {
|
|
366
|
+
const term = readTerm(answer);
|
|
367
|
+
const names = new Map([...variablesIn([term])].map((name, i) => [name, `X${i}`]));
|
|
368
|
+
const quantifier = names.size ? `For every ${[...names.values()].join(' and ')}, ` : '';
|
|
369
|
+
lines.push(quantifier + flattenConjunction(term).map((goal) => leGoal(goal, names, odrl !== null)).join(' and ') + '.');
|
|
370
|
+
}
|
|
371
|
+
const header = odrl ? `Use ODRL vocabulary with namespace ${JSON.stringify(odrl.namespace)}.\n\n` : '';
|
|
372
|
+
return header + (lines.length ? lines.join('\n') + '\n' : '# No conclusions.\n');
|
|
373
|
+
}
|
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.1';
|