eyemind 0.3.11 → 0.5.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/README.md +17 -2
- package/SPEC.md +55 -14
- package/package.json +1 -1
- package/src/builtins.js +89 -2
- package/src/digest.js +162 -0
- package/src/engine.js +26 -14
- package/src/program.js +14 -15
- package/src/proof.js +33 -3
- package/src/terms.js +40 -0
- package/src/version.js +1 -1
package/README.md
CHANGED
|
@@ -7,7 +7,7 @@ eyemind is a **JavaScript rule language** with forward and backward reasoning an
|
|
|
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 the C1–C10 checks. The examples are 94 runnable programs, each with a card deck and saved conclusions, proofs and check reports. The conformance suite has
|
|
10
|
+
The playground runs programs in your browser; the specification defines the language, its canonical text, the proof format and the C1–C10 checks. The examples are 94 runnable programs, each with a card deck and saved conclusions, proofs and check reports. The conformance suite has 1353 cases that test any implementation of the specification through its command line; run it [in your browser](https://eyereasoner.github.io/eyemind/playground/conformance).
|
|
11
11
|
|
|
12
12
|
## Contents
|
|
13
13
|
|
|
@@ -19,6 +19,7 @@ The playground runs programs in your browser; the specification defines the lang
|
|
|
19
19
|
- [Deriving rules](#deriving-rules)
|
|
20
20
|
- [Inspecting rules](#inspecting-rules)
|
|
21
21
|
- [RDF 1.2](#rdf-12)
|
|
22
|
+
- [Notation3](#notation3)
|
|
22
23
|
- [How eyemind reasons](#how-eyemind-reasons)
|
|
23
24
|
- [Proofs, and what checking one means](#proofs-and-what-checking-one-means)
|
|
24
25
|
- [Why negation and collection are safe](#why-negation-and-collection-are-safe)
|
|
@@ -58,7 +59,7 @@ Prolog, Datalog, N3 and SRL already exist, and eyemind adds no new logic: rules
|
|
|
58
59
|
When eyemind is not the right tool:
|
|
59
60
|
|
|
60
61
|
- If you do not need proofs, use the mature tools: SWI-Prolog and XSB have tabling, and Soufflé is fast at scale.
|
|
61
|
-
- N3 and SRL are designed around RDF and Web data. eyemind does not compete there: RDF comes in as data (see [RDF 1.2](#rdf-12)).
|
|
62
|
+
- N3 and SRL are designed around RDF and Web data. eyemind does not compete there: RDF comes in as data (see [RDF 1.2](#rdf-12)), and N3 programs compile to eyemind (see [Notation3](#notation3)).
|
|
62
63
|
- eyemind is for cases where someone else has to be able to check why a conclusion holds: audits, compliance, and decisions between parties that do not trust each other.
|
|
63
64
|
|
|
64
65
|
## Install and run
|
|
@@ -123,6 +124,8 @@ Now add `fact(parent('carol', 'dave'))`, or remove a rule, and watch which answe
|
|
|
123
124
|
|
|
124
125
|
**An array is a conjunction:** `implies([p(X), q(X)], [r(X), s(X)])`. Disjunction is `or(A, B)`, negation is `not(G)`, and collection is `findall(T, G, L)`, alongside `call` and `once`.
|
|
125
126
|
|
|
127
|
+
**Text is atoms:** `atom_chars`, `atom_concat` and `atom_length` take them apart, `atom_lower` and `atom_upper` change their case, `regex_match(P, T)`, `regex_find(P, T, Groups)` and `regex_replace(P, T, R, U)` search them with ECMAScript regular expressions, `digest('sha256', A, Hex)` hashes them, and `term_text(T, A)` writes a ground term as its canonical text.
|
|
128
|
+
|
|
126
129
|
### Terms and names
|
|
127
130
|
|
|
128
131
|
- **Nothing to declare.** An undeclared name is a variable when it starts with a capital or `_` (`X`, `_Rest`) and a predicate otherwise (`parent`). `_` is a fresh variable at each use. JavaScript globals such as `Math` and `JSON` keep their meaning; `const range = preds('range')` declares a predicate whose name would otherwise clash. A misspelled statement such as `fcat(p(1))` states nothing, so eyemind stops with an error.
|
|
@@ -183,6 +186,18 @@ eyemind has no built-in RDF; RDF arrives as data through [rdf-interchange](https
|
|
|
183
186
|
|
|
184
187
|
A Skolem term becomes a blank node, the same one for the same rule firing. The `rdf12-*` examples show triple terms, annotations, directional strings, typed numbers and named graphs.
|
|
185
188
|
|
|
189
|
+
### Notation3
|
|
190
|
+
|
|
191
|
+
N3 programs run on eyemind through [n3-interchange](https://github.com/eyereasoner/n3-interchange). `n3-to-eyemind` compiles N3 facts and rules into an eyemind program, with the N3 built-ins it uses written as eyemind rules, and `eyemind-to-n3` writes the conclusions back as N3; `eyemind-n3` does both around a run:
|
|
192
|
+
|
|
193
|
+
```sh
|
|
194
|
+
npm install -g n3-interchange
|
|
195
|
+
eyemind-n3 socrates.n3 # the derived triples, as N3
|
|
196
|
+
n3-to-eyemind socrates.n3 -o socrates.js # or the program, to run, prove and check
|
|
197
|
+
```
|
|
198
|
+
|
|
199
|
+
Triples are `rdf(Subject, Predicate, Object)`, with IRIs, blank nodes and literals written as in the RDF table above and N3 numbers as eyemind numbers. `=>` becomes `implies`, `<=` becomes `implied_by`, and scoped negation and collection become `not` and `findall`, so an N3 run has a proof that eyemind checks like any other. Built-ins that need what eyemind leaves out, such as hashing or file access, stop the compiler with a message naming them; the n3-interchange README lists them and how much of the N3 test suite passes.
|
|
200
|
+
|
|
186
201
|
## How eyemind reasons
|
|
187
202
|
|
|
188
203
|
The statement chooses the direction:
|
package/SPEC.md
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
```text
|
|
4
4
|
Title: The eyemind Rule Language and Proof Format
|
|
5
|
-
Version: eyemind 0.
|
|
5
|
+
Version: eyemind 0.5.0
|
|
6
6
|
```
|
|
7
7
|
|
|
8
8
|
This document specifies the syntax and meaning of eyemind programs and data
|
|
@@ -575,9 +575,27 @@ primitive called outside its patterns raises an error.
|
|
|
575
575
|
| `atom_length` | `atom_length(+A, ?N)` | `N` is the number of characters of `A`. |
|
|
576
576
|
| `number_chars` | `number_chars(?N, +L)`, `number_chars(+N, -L)` | A bound `L` is read as a number: an optional sign and decimal digits give an integer, and with a fraction or an exponent a float, as in `'007'`, `'-21.5'`, `'.5'`, `'1.'` and `'2E-2'`; other text fails, as does text whose value is too large for a finite float, such as `'1e400'`. Otherwise `L` spells `N` in its canonical text ([Section 9.2](#92-canonical-atoms-numbers-variables-and-lists)). |
|
|
577
577
|
| `atom_concat` | `atom_concat(+A, +B, ?AB)`, `atom_concat(?A, ?B, +AB)` | `AB` is `A` followed by `B`; with `AB` given, every split, shortest `A` first. |
|
|
578
|
-
|
|
579
|
-
A
|
|
580
|
-
|
|
578
|
+
| `atom_lower`, `atom_upper` | `atom_lower(+A, ?L)`, `atom_upper(+A, ?U)` | `L` is `A` in lower case, `U` in upper case, by Unicode default case conversion: the full mappings, independent of locale, with the final sigma of a word lowered to `'ς'`, so `atom_upper('straße', 'STRASSE')` holds. |
|
|
579
|
+
| `digest` | `digest(+H, +A, ?D)` | `D` is the digest of the UTF-8 encoding of the atom `A` by the hash function `H`, one of `'md5'`, `'sha1'`, `'sha256'` and `'sha512'`, as lowercase hexadecimal. A lone surrogate is encoded as U+FFFD. Another `H` raises an error. |
|
|
580
|
+
| `term_text` | `term_text(+T, ?A)` | `A` is the canonical text of `T` ([Section 9.2](#92-canonical-atoms-numbers-variables-and-lists)), which MUST be ground: `term_text(f('a', [1, 2.0]), "f('a', [1, 2.0])")` holds. |
|
|
581
|
+
| `regex_match` | `regex_match(+P, +T)` | Some part of the atom `T` matches the regular expression `P`. |
|
|
582
|
+
| `regex_find` | `regex_find(+P, +T, ?G)` | One solution per match of `P` in `T`, from left to right: `G` is the list of the matched text followed by each capture group's text, `''` for a group that took no part in the match. |
|
|
583
|
+
| `regex_replace` | `regex_replace(+P, +T, +R, ?U)` | `U` is `T` with every match of `P` replaced by `R`. |
|
|
584
|
+
|
|
585
|
+
A character is a Unicode code point. Every primitive except `atom_concat`
|
|
586
|
+
and `regex_find` has at most one solution.
|
|
587
|
+
|
|
588
|
+
A regular expression `P` is an atom read as an ECMAScript pattern
|
|
589
|
+
(ECMA-262, the `RegExp` pattern grammar and matching semantics) with only the
|
|
590
|
+
`u` flag, so it matches by code point: `.` matches `'\u{1F600}'` as one
|
|
591
|
+
character, `^` and `$` match only at the ends of the text, and matching is
|
|
592
|
+
case-sensitive. A pattern that is not valid in that mode, such as `'('`,
|
|
593
|
+
raises an error. `regex_find` and `regex_replace` take the matches as a
|
|
594
|
+
global search does: after an empty match the search resumes one code point
|
|
595
|
+
later, so `regex_find('a*', 'baa', G)` gives `['']`, `['aa']` and `['']`. In
|
|
596
|
+
the replacement `R`, `$&` stands for the match, `$1` to `$99` and `$<Name>`
|
|
597
|
+
for its groups, `` $` `` and `$'` for the text before and after it, and `$$`
|
|
598
|
+
for `$`; any other `$` is itself. Primitives MUST be pure: their solutions depend only on
|
|
581
599
|
their arguments. A primitive given an argument of the wrong kind for its
|
|
582
600
|
patterns raises an error, as `atom_length(123, N)` does; one given arguments
|
|
583
601
|
of the right kinds that has no solution fails, as `arg(5, f(1), A)` does.
|
|
@@ -1051,15 +1069,19 @@ when supported. Each negation and collection of a proof gets the search certific
|
|
|
1051
1069
|
that settles it (Sections [10.4](#104-search-certificates) and [11.10](#1110-c9-search-closure)) whenever [Section 11.10](#1110-c9-search-closure) allows one. A
|
|
1052
1070
|
table holds every answer of its call, so it can search beyond where the run
|
|
1053
1071
|
stopped, as under `once`; a boundary whose tables would meet an error, or
|
|
1054
|
-
exceed `max_inferences` calls and answers ([Section 8.3](#83-resource-bounds)), stays trusted.
|
|
1072
|
+
exceed `max_inferences` calls and answers ([Section 8.3](#83-resource-bounds)), stays trusted. So does a
|
|
1073
|
+
boundary of a halted run ([Section 8.5](#85-contradictions)) whose listings a rule of a later stratum
|
|
1074
|
+
would extend: the run stopped before its fixpoint, so its derived facts need
|
|
1075
|
+
not be closed under the rules. A
|
|
1055
1076
|
reasoner MUST check every proof it generates ([Section 11](#11-proof-checking)) before returning it,
|
|
1056
1077
|
and MUST fail with an error rather than return a proof that does not pass. A
|
|
1057
1078
|
run without conclusions has a proof without claims, which is valid and
|
|
1058
1079
|
certifies nothing.
|
|
1059
1080
|
|
|
1060
|
-
A
|
|
1061
|
-
|
|
1062
|
-
|
|
1081
|
+
A **state test** is `is_var/1`, `not_identical/2` or `compare/3`: a test a
|
|
1082
|
+
later binding can make false. A goal such as `is_var(X)` followed by
|
|
1083
|
+
`unify(X, 'a')` holds when it runs, but its final instance `is_var('a')` does
|
|
1084
|
+
not, so the proof records it as it was called ([Section 10.3](#103-steps)).
|
|
1063
1085
|
|
|
1064
1086
|
## 9. Document Syntax and Canonical Text
|
|
1065
1087
|
|
|
@@ -1255,6 +1277,7 @@ order. `By` is one of:
|
|
|
1255
1277
|
| `clause(N)` | `Goal` is an instance of a head of clause `N`, a fact or a rule, whose body instance is `Uses`. | the clause's variables | the body instance, empty for a fact |
|
|
1256
1278
|
| `source(N)` | `Goal` is an instance of the inspectable source rule `N` as `implies(Body, Head)` or `implied_by(Head, Body)`. | empty | empty |
|
|
1257
1279
|
| `'builtin'` | `Goal` is a primitive that holds. | empty | empty |
|
|
1280
|
+
| `called(Called)` | `Goal` is a state test ([Section 8.7](#87-proof-generation)) that held as `Called`, the goal when it ran, its then unbound variables written as variables. | empty | empty |
|
|
1258
1281
|
| `'control'` | `Goal` is `call`, `once` or a disjunction, solved by `Uses`. | empty | the solved goals; for a disjunction, the side that was solved, so `or(or(A, B), C)` solved by `A` uses `or(A, B)`, which has a step of its own |
|
|
1259
1282
|
| `'absent'` | `Goal` is a negation, settled by the search certificate or taken on trust. | empty | empty |
|
|
1260
1283
|
| `'collected'` | `Goal` is a `findall`, settled by the search certificate or taken on trust. | empty | empty |
|
|
@@ -1268,8 +1291,17 @@ first shows them (for `implies`, the premise first);
|
|
|
1268
1291
|
a checker MUST accept partial bindings when the goal and uses determine the
|
|
1269
1292
|
omitted values needed by C1 and C8. Values needed only by an enclosing
|
|
1270
1293
|
witness scope must be supplied when those terms do not determine them.
|
|
1271
|
-
A primitive has no variables of its own, so `'builtin'`
|
|
1272
|
-
empty bindings. A
|
|
1294
|
+
A primitive has no variables of its own, so `'builtin'` and `called`
|
|
1295
|
+
steps have empty bindings. A reasoner writes `called(Called)` exactly for a
|
|
1296
|
+
state test whose goal, when it held, had a variable the solution later
|
|
1297
|
+
bound; `Called` is that goal after the test, so `compare(O, X, 'b')` run
|
|
1298
|
+
with `X` unbound is written `called(compare('<', A, 'b'))`. Every other
|
|
1299
|
+
primitive step, and a state test no later binding changed, is `'builtin'`:
|
|
1300
|
+
|
|
1301
|
+
```js
|
|
1302
|
+
implied_by(p(X), [is_var(X), unify(X, 'a')])
|
|
1303
|
+
// step(is_var('a'), called(is_var(A)), {}, [])
|
|
1304
|
+
``` A derived clause's bindings also include variables of its
|
|
1273
1305
|
enclosing generators' scope projections, so their witnesses can be checked.
|
|
1274
1306
|
These variables are renamed together with the clause's head and full body.
|
|
1275
1307
|
|
|
@@ -1395,7 +1427,8 @@ failure, whose conclusion is the goal of that step.
|
|
|
1395
1427
|
### 11.4 C3 Justification
|
|
1396
1428
|
|
|
1397
1429
|
`By` MUST be one of the forms of [Section 10.3](#103-steps). A `'builtin'` step MUST have
|
|
1398
|
-
no bindings and no uses and a goal that is a primitive;
|
|
1430
|
+
no bindings and no uses and a goal that is a primitive; a `called` step MUST
|
|
1431
|
+
have no bindings and no uses and a goal that is a state test; an `'absent'` or
|
|
1399
1432
|
`'collected'` step MUST have no bindings and no uses and a goal that is a
|
|
1400
1433
|
negation or a `findall`, respectively. A step that fails C3 is not a trusted
|
|
1401
1434
|
boundary: it counts in neither `trusted`, C6 nor C9.
|
|
@@ -1411,7 +1444,13 @@ nothing.
|
|
|
1411
1444
|
### 11.6 C5 Re-decision
|
|
1412
1445
|
|
|
1413
1446
|
A `'builtin'` step's goal, solved as a primitive with no prior bindings, MUST
|
|
1414
|
-
succeed without binding anything.
|
|
1447
|
+
succeed without binding anything. For a `called(Called)` step, `Called`
|
|
1448
|
+
MUST have the goal's name and arity; `Called`, renamed apart and solved as a
|
|
1449
|
+
primitive with no prior bindings, MUST succeed without binding anything; and
|
|
1450
|
+
the goal MUST be an instance of `Called`, so only the variables `Called`
|
|
1451
|
+
leaves unbound may differ. C5 does not establish that the test ran in that
|
|
1452
|
+
state: like the choice of a `once` step, the call state is operational
|
|
1453
|
+
([Section 11.13](#1113-operational-query-fidelity)), and C10 checks the original questions. A `'control'` step MUST have no bindings,
|
|
1415
1454
|
and its uses MUST be identical, in order, to the conjuncts of the argument of
|
|
1416
1455
|
`call` or `once`, or of one side of a disjunction. When trusted boundaries are
|
|
1417
1456
|
forbidden ("strict"), each `'absent'` or `'collected'` step fails C5.
|
|
@@ -1620,7 +1659,7 @@ settled nor refuted with the evidence ([Section 11.7](#117-c6-boundary-consisten
|
|
|
1620
1659
|
|
|
1621
1660
|
A check also counts the **steps** it read, the **claims**, the `clause` steps
|
|
1622
1661
|
**verified** by C1, the `source` inspection steps also **verified** by C1,
|
|
1623
|
-
the `'builtin'` steps **recomputed** by C5, the
|
|
1662
|
+
the `'builtin'` and `called` steps **recomputed** by C5, the
|
|
1624
1663
|
`'control'` steps **composed** by C5, and the `'absent'` and `'collected'`
|
|
1625
1664
|
steps **trusted**, those C9 did not settle, plus each claim whose call
|
|
1626
1665
|
fidelity remains unproved by C10.
|
|
@@ -1974,7 +2013,9 @@ Programs execute JavaScript and require the caller's trust. Documents,
|
|
|
1974
2013
|
including proofs, reports, goals and `facts_from` input, MUST be read as data
|
|
1975
2014
|
without executing code. A deployment accepting untrusted documents SHOULD
|
|
1976
2015
|
bound their size, nesting depth, processing time and memory, in addition to
|
|
1977
|
-
the reasoning bounds of [Section 8.3](#83-resource-bounds). A
|
|
2016
|
+
the reasoning bounds of [Section 8.3](#83-resource-bounds). A regular expression can take time exponential in
|
|
2017
|
+
the length of the text it searches ([Section 4.3](#43-primitives)), and no reasoning bound counts
|
|
2018
|
+
that time, so a deployment running untrusted programs SHOULD also bound it. A valid proof establishes only the
|
|
1978
2019
|
claims and assumptions described in [Section 11.12](#1112-scope-of-a-valid-proof).
|
|
1979
2020
|
|
|
1980
2021
|
## Appendix A. Document Grammar
|
package/package.json
CHANGED
package/src/builtins.js
CHANGED
|
@@ -15,7 +15,8 @@ import {
|
|
|
15
15
|
EyemindError, Struct, Var, codePoints, compareTerms, copyResolved, deref, identical, isGround, key,
|
|
16
16
|
listFromItems, properListItems, unify,
|
|
17
17
|
} from './terms.js';
|
|
18
|
-
import {
|
|
18
|
+
import { DIGESTS, utf8 } from './digest.js';
|
|
19
|
+
import { floatText, write } from './writer.js';
|
|
19
20
|
|
|
20
21
|
function comparison(holds) {
|
|
21
22
|
return (args, resolved, env) => holds(arith.compare(args[0], args[1], env));
|
|
@@ -149,6 +150,68 @@ function is(args, resolved, env, bind) {
|
|
|
149
150
|
return bind(args[0], arith.evaluate(args[1], env));
|
|
150
151
|
}
|
|
151
152
|
|
|
153
|
+
// Regular expressions use ECMAScript's syntax and matching (ECMA-262), always
|
|
154
|
+
// in its Unicode mode, so a pattern means the same on every host. A pattern
|
|
155
|
+
// compiles once.
|
|
156
|
+
const patterns = new Map();
|
|
157
|
+
|
|
158
|
+
function pattern(name, term, global) {
|
|
159
|
+
if (typeof term !== 'string') throw new EyemindError(`${name} needs an atom pattern`);
|
|
160
|
+
const cacheKey = `${global ? 'g' : '-'}${term}`;
|
|
161
|
+
let compiled = patterns.get(cacheKey);
|
|
162
|
+
if (compiled === undefined) {
|
|
163
|
+
try {
|
|
164
|
+
compiled = new RegExp(term, global ? 'gu' : 'u');
|
|
165
|
+
} catch (error) {
|
|
166
|
+
throw new EyemindError(`${name} needs a valid regular expression: ${error.message}`);
|
|
167
|
+
}
|
|
168
|
+
if (patterns.size > 1000) patterns.clear();
|
|
169
|
+
patterns.set(cacheKey, compiled);
|
|
170
|
+
}
|
|
171
|
+
compiled.lastIndex = 0;
|
|
172
|
+
return compiled;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
function text(name, term, what = 'text') {
|
|
176
|
+
if (typeof term !== 'string') throw new EyemindError(`${name} needs an atom ${what}`);
|
|
177
|
+
return term;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
// regex_match(+P, +T): some part of T matches P.
|
|
181
|
+
function regexMatch(args, resolved) {
|
|
182
|
+
return pattern('regex_match/2', resolved[0], false).test(text('regex_match/2', resolved[1]));
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
// regex_replace(+P, +T, +R, ?Out): Out is T with every match of P replaced
|
|
186
|
+
// by R, where $& is the match, $1 ... $99 and $<name> its groups, $` and $'
|
|
187
|
+
// the text before and after it, and $$ a dollar sign.
|
|
188
|
+
function regexReplace(args, resolved, env, bind) {
|
|
189
|
+
const compiled = pattern('regex_replace/4', resolved[0], true);
|
|
190
|
+
const source = text('regex_replace/4', resolved[1]);
|
|
191
|
+
const replacement = text('regex_replace/4', resolved[2], 'replacement');
|
|
192
|
+
return bind(args[3], source.replace(compiled, replacement));
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
// atom_lower(+A, ?L), atom_upper(+A, ?U): Unicode default case conversion,
|
|
196
|
+
// with its full mappings, so 'ß' becomes 'SS', and no locale.
|
|
197
|
+
function caseConversion(name, convert) {
|
|
198
|
+
return (args, resolved, env, bind) => bind(args[1], convert(text(name, resolved[0], 'atom')));
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
// digest(+Algorithm, +A, ?Hex): the lowercase hexadecimal digest of A's UTF-8
|
|
202
|
+
// bytes, by md5, sha1, sha256 or sha512.
|
|
203
|
+
function digest(args, resolved, env, bind) {
|
|
204
|
+
const algorithm = DIGESTS.get(resolved[0]);
|
|
205
|
+
if (algorithm === undefined) throw new EyemindError(`digest/3 needs md5, sha1, sha256 or sha512, not ${write(resolved[0])}`);
|
|
206
|
+
return bind(args[2], algorithm(utf8(text('digest/3', resolved[1], 'atom'))));
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
// term_text(+T, ?A): A is the canonical text of the ground term T.
|
|
210
|
+
function termText(args, resolved, env, bind) {
|
|
211
|
+
if (!isGround(args[0], env)) throw new EyemindError('term_text/2 needs a ground term');
|
|
212
|
+
return bind(args[1], write(copyResolved(args[0], env)));
|
|
213
|
+
}
|
|
214
|
+
|
|
152
215
|
const isNumberValue = (term) => typeof term === 'bigint' || typeof term === 'number';
|
|
153
216
|
|
|
154
217
|
export const TESTS = new Map([
|
|
@@ -182,6 +245,12 @@ export const TESTS = new Map([
|
|
|
182
245
|
['atom_length/2', atomLength],
|
|
183
246
|
['number_chars/2', numberChars],
|
|
184
247
|
['compare/3', compare],
|
|
248
|
+
['atom_lower/2', caseConversion('atom_lower/2', (a) => a.toLowerCase())],
|
|
249
|
+
['atom_upper/2', caseConversion('atom_upper/2', (a) => a.toUpperCase())],
|
|
250
|
+
['digest/3', digest],
|
|
251
|
+
['term_text/2', termText],
|
|
252
|
+
['regex_match/2', regexMatch],
|
|
253
|
+
['regex_replace/4', regexReplace],
|
|
185
254
|
]);
|
|
186
255
|
|
|
187
256
|
function* atomConcat(args, resolved, env, mark) {
|
|
@@ -199,7 +268,25 @@ function* atomConcat(args, resolved, env, mark) {
|
|
|
199
268
|
}
|
|
200
269
|
}
|
|
201
270
|
|
|
202
|
-
|
|
271
|
+
// regex_find(+P, +T, ?Groups): one solution per match of P in T, from left
|
|
272
|
+
// to right without overlaps; Groups is the match followed by its groups, a
|
|
273
|
+
// group that took no part in the match being ''.
|
|
274
|
+
function* regexFind(args, resolved, env, mark) {
|
|
275
|
+
const compiled = pattern('regex_find/3', resolved[0], true);
|
|
276
|
+
const source = text('regex_find/3', resolved[1]);
|
|
277
|
+
for (const match of source.matchAll(compiled)) {
|
|
278
|
+
if (unify(args[2], listFromItems(Array.from(match, (group) => group ?? '')), env)) yield env;
|
|
279
|
+
env.undo(mark);
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
export const RELATIONS = new Map([['atom_concat/3', atomConcat], ['regex_find/3', regexFind]]);
|
|
284
|
+
|
|
285
|
+
// Tests that a later binding can make false: is_var(X) holds while X is
|
|
286
|
+
// unbound, not_identical(X, a) until X is a, and compare orders a variable
|
|
287
|
+
// before every other term. A proof records such a step by the goal as it
|
|
288
|
+
// was called, called(Goal), since its final instance need not hold.
|
|
289
|
+
export const STATE_TESTS = new Set(['is_var/1', 'not_identical/2', 'compare/3']);
|
|
203
290
|
export const PRIMITIVE_KEYS = new Set([...TESTS.keys(), ...RELATIONS.keys()]);
|
|
204
291
|
|
|
205
292
|
// Solve a primitive goal: a generator yielding env once per solution.
|
package/src/digest.js
ADDED
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
// Message digests for digest/3: MD5, SHA-1, SHA-256 and SHA-512 of a text's
|
|
2
|
+
// UTF-8 bytes, as lowercase hexadecimal. Written out here, synchronous and
|
|
3
|
+
// without Node, so every host gives the same digest.
|
|
4
|
+
|
|
5
|
+
const encoder = new TextEncoder();
|
|
6
|
+
|
|
7
|
+
// A lone surrogate has no UTF-8 encoding; TextEncoder writes U+FFFD for it.
|
|
8
|
+
export function utf8(text) {
|
|
9
|
+
return encoder.encode(text);
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
const hex32 = (words, littleEndian = false) => words.map((w) => {
|
|
13
|
+
const value = littleEndian
|
|
14
|
+
? ((w & 0xff) << 24) | (((w >>> 8) & 0xff) << 16) | (((w >>> 16) & 0xff) << 8) | (w >>> 24)
|
|
15
|
+
: w;
|
|
16
|
+
return (value >>> 0).toString(16).padStart(8, '0');
|
|
17
|
+
}).join('');
|
|
18
|
+
|
|
19
|
+
// The message padded to a multiple of the block size, with its bit length
|
|
20
|
+
// at the end in lengthBytes bytes, big- or little-endian.
|
|
21
|
+
function pad(bytes, block, lengthBytes, littleEndian) {
|
|
22
|
+
const total = Math.ceil((bytes.length + 1 + lengthBytes) / block) * block;
|
|
23
|
+
const out = new Uint8Array(total);
|
|
24
|
+
out.set(bytes);
|
|
25
|
+
out[bytes.length] = 0x80;
|
|
26
|
+
let bits = BigInt(bytes.length) * 8n;
|
|
27
|
+
for (let i = 0; i < lengthBytes; i++) {
|
|
28
|
+
const position = littleEndian ? total - lengthBytes + i : total - 1 - i;
|
|
29
|
+
out[position] = Number(bits & 0xffn);
|
|
30
|
+
bits >>= 8n;
|
|
31
|
+
}
|
|
32
|
+
return out;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const rotl = (x, n) => (x << n) | (x >>> (32 - n));
|
|
36
|
+
const rotr = (x, n) => (x >>> n) | (x << (32 - n));
|
|
37
|
+
|
|
38
|
+
function md5(bytes) {
|
|
39
|
+
const s = [7, 12, 17, 22, 5, 9, 14, 20, 4, 11, 16, 23, 6, 10, 15, 21];
|
|
40
|
+
const k = Array.from({ length: 64 }, (_, i) => Math.floor(Math.abs(Math.sin(i + 1)) * 2 ** 32) | 0);
|
|
41
|
+
const m = pad(bytes, 64, 8, true);
|
|
42
|
+
let [a0, b0, c0, d0] = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476];
|
|
43
|
+
for (let offset = 0; offset < m.length; offset += 64) {
|
|
44
|
+
const w = Array.from({ length: 16 }, (_, i) => m[offset + 4 * i] | (m[offset + 4 * i + 1] << 8) |
|
|
45
|
+
(m[offset + 4 * i + 2] << 16) | (m[offset + 4 * i + 3] << 24));
|
|
46
|
+
let [a, b, c, d] = [a0, b0, c0, d0];
|
|
47
|
+
for (let i = 0; i < 64; i++) {
|
|
48
|
+
let f;
|
|
49
|
+
let g;
|
|
50
|
+
if (i < 16) [f, g] = [(b & c) | (~b & d), i];
|
|
51
|
+
else if (i < 32) [f, g] = [(d & b) | (~d & c), (5 * i + 1) % 16];
|
|
52
|
+
else if (i < 48) [f, g] = [b ^ c ^ d, (3 * i + 5) % 16];
|
|
53
|
+
else [f, g] = [c ^ (b | ~d), (7 * i) % 16];
|
|
54
|
+
const next = d;
|
|
55
|
+
d = c;
|
|
56
|
+
c = b;
|
|
57
|
+
b = (b + rotl((a + f + k[i] + w[g]) | 0, s[(i >> 4) * 4 + (i % 4)])) | 0;
|
|
58
|
+
a = next;
|
|
59
|
+
}
|
|
60
|
+
[a0, b0, c0, d0] = [(a0 + a) | 0, (b0 + b) | 0, (c0 + c) | 0, (d0 + d) | 0];
|
|
61
|
+
}
|
|
62
|
+
return hex32([a0, b0, c0, d0], true);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// Big-endian 32-bit words of a padded 64-byte block.
|
|
66
|
+
const words = (m, offset, count) => Array.from({ length: count }, (_, i) => (m[offset + 4 * i] << 24) |
|
|
67
|
+
(m[offset + 4 * i + 1] << 16) | (m[offset + 4 * i + 2] << 8) | m[offset + 4 * i + 3]);
|
|
68
|
+
|
|
69
|
+
function sha1(bytes) {
|
|
70
|
+
const m = pad(bytes, 64, 8, false);
|
|
71
|
+
let h = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0];
|
|
72
|
+
for (let offset = 0; offset < m.length; offset += 64) {
|
|
73
|
+
const w = words(m, offset, 16);
|
|
74
|
+
for (let i = 16; i < 80; i++) w[i] = rotl(w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16], 1);
|
|
75
|
+
let [a, b, c, d, e] = h;
|
|
76
|
+
for (let i = 0; i < 80; i++) {
|
|
77
|
+
const [f, k] = i < 20 ? [(b & c) | (~b & d), 0x5a827999] : i < 40 ? [b ^ c ^ d, 0x6ed9eba1]
|
|
78
|
+
: i < 60 ? [(b & c) | (b & d) | (c & d), 0x8f1bbcdc] : [b ^ c ^ d, 0xca62c1d6];
|
|
79
|
+
const t = (rotl(a, 5) + f + e + k + w[i]) | 0;
|
|
80
|
+
[e, d, c, b, a] = [d, c, rotl(b, 30), a, t];
|
|
81
|
+
}
|
|
82
|
+
h = h.map((x, i) => (x + [a, b, c, d, e][i]) | 0);
|
|
83
|
+
}
|
|
84
|
+
return hex32(h);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
const K256 = [
|
|
88
|
+
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
|
|
89
|
+
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
|
|
90
|
+
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
|
|
91
|
+
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
|
|
92
|
+
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
|
|
93
|
+
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
|
|
94
|
+
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
|
|
95
|
+
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
|
|
96
|
+
];
|
|
97
|
+
|
|
98
|
+
function sha256(bytes) {
|
|
99
|
+
const m = pad(bytes, 64, 8, false);
|
|
100
|
+
let h = [0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19];
|
|
101
|
+
for (let offset = 0; offset < m.length; offset += 64) {
|
|
102
|
+
const w = words(m, offset, 16);
|
|
103
|
+
for (let i = 16; i < 64; i++) {
|
|
104
|
+
const s0 = rotr(w[i - 15], 7) ^ rotr(w[i - 15], 18) ^ (w[i - 15] >>> 3);
|
|
105
|
+
const s1 = rotr(w[i - 2], 17) ^ rotr(w[i - 2], 19) ^ (w[i - 2] >>> 10);
|
|
106
|
+
w[i] = (w[i - 16] + s0 + w[i - 7] + s1) | 0;
|
|
107
|
+
}
|
|
108
|
+
let [a, b, c, d, e, f, g, k] = h;
|
|
109
|
+
for (let i = 0; i < 64; i++) {
|
|
110
|
+
const t1 = (k + (rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25)) + ((e & f) ^ (~e & g)) + K256[i] + w[i]) | 0;
|
|
111
|
+
const t2 = ((rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22)) + ((a & b) ^ (a & c) ^ (b & c))) | 0;
|
|
112
|
+
[k, g, f, e, d, c, b, a] = [g, f, e, (d + t1) | 0, c, b, a, (t1 + t2) | 0];
|
|
113
|
+
}
|
|
114
|
+
h = h.map((x, i) => (x + [a, b, c, d, e, f, g, k][i]) | 0);
|
|
115
|
+
}
|
|
116
|
+
return hex32(h);
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
// SHA-512 works on 64-bit words, kept as BigInts.
|
|
120
|
+
const MASK64 = (1n << 64n) - 1n;
|
|
121
|
+
const K512 = `428a2f98d728ae22 7137449123ef65cd b5c0fbcfec4d3b2f e9b5dba58189dbbc 3956c25bf348b538 59f111f1b605d019
|
|
122
|
+
923f82a4af194f9b ab1c5ed5da6d8118 d807aa98a3030242 12835b0145706fbe 243185be4ee4b28c 550c7dc3d5ffb4e2 72be5d74f27b896f
|
|
123
|
+
80deb1fe3b1696b1 9bdc06a725c71235 c19bf174cf692694 e49b69c19ef14ad2 efbe4786384f25e3 0fc19dc68b8cd5b5 240ca1cc77ac9c65
|
|
124
|
+
2de92c6f592b0275 4a7484aa6ea6e483 5cb0a9dcbd41fbd4 76f988da831153b5 983e5152ee66dfab a831c66d2db43210 b00327c898fb213f
|
|
125
|
+
bf597fc7beef0ee4 c6e00bf33da88fc2 d5a79147930aa725 06ca6351e003826f 142929670a0e6e70 27b70a8546d22ffc 2e1b21385c26c926
|
|
126
|
+
4d2c6dfc5ac42aed 53380d139d95b3df 650a73548baf63de 766a0abb3c77b2a8 81c2c92e47edaee6 92722c851482353b a2bfe8a14cf10364
|
|
127
|
+
a81a664bbc423001 c24b8b70d0f89791 c76c51a30654be30 d192e819d6ef5218 d69906245565a910 f40e35855771202a 106aa07032bbd1b8
|
|
128
|
+
19a4c116b8d2d0c8 1e376c085141ab53 2748774cdf8eeb99 34b0bcb5e19b48a8 391c0cb3c5c95a63 4ed8aa4ae3418acb 5b9cca4f7763e373
|
|
129
|
+
682e6ff3d6b2b8a3 748f82ee5defb2fc 78a5636f43172f60 84c87814a1f0ab72 8cc702081a6439ec 90befffa23631e28 a4506cebde82bde9
|
|
130
|
+
bef9a3f7b2c67915 c67178f2e372532b ca273eceea26619c d186b8c721c0c207 eada7dd6cde0eb1e f57d4f7fee6ed178 06f067aa72176fba
|
|
131
|
+
0a637dc5a2c898a6 113f9804bef90dae 1b710b35131c471b 28db77f523047d84 32caab7b40c72493 3c9ebe0a15c9bebc 431d67c49c100d4c
|
|
132
|
+
4cc5d4becb3e42b6 597f299cfc657e2a 5fcb6fab3ad6faec 6c44198c4a475817`.split(/\s+/).map((x) => BigInt(`0x${x}`));
|
|
133
|
+
const rotr64 = (x, n) => ((x >> n) | (x << (64n - n))) & MASK64;
|
|
134
|
+
|
|
135
|
+
function sha512(bytes) {
|
|
136
|
+
const m = pad(bytes, 128, 16, false);
|
|
137
|
+
let h = `6a09e667f3bcc908 bb67ae8584caa73b 3c6ef372fe94f82b a54ff53a5f1d36f1 510e527fade682d1 9b05688c2b3e6c1f
|
|
138
|
+
1f83d9abfb41bd6b 5be0cd19137e2179`.split(/\s+/).map((x) => BigInt(`0x${x}`));
|
|
139
|
+
for (let offset = 0; offset < m.length; offset += 128) {
|
|
140
|
+
const w = [];
|
|
141
|
+
for (let i = 0; i < 16; i++) {
|
|
142
|
+
let x = 0n;
|
|
143
|
+
for (let j = 0; j < 8; j++) x = (x << 8n) | BigInt(m[offset + 8 * i + j]);
|
|
144
|
+
w.push(x);
|
|
145
|
+
}
|
|
146
|
+
for (let i = 16; i < 80; i++) {
|
|
147
|
+
const s0 = rotr64(w[i - 15], 1n) ^ rotr64(w[i - 15], 8n) ^ (w[i - 15] >> 7n);
|
|
148
|
+
const s1 = rotr64(w[i - 2], 19n) ^ rotr64(w[i - 2], 61n) ^ (w[i - 2] >> 6n);
|
|
149
|
+
w[i] = (w[i - 16] + s0 + w[i - 7] + s1) & MASK64;
|
|
150
|
+
}
|
|
151
|
+
let [a, b, c, d, e, f, g, k] = h;
|
|
152
|
+
for (let i = 0; i < 80; i++) {
|
|
153
|
+
const t1 = (k + (rotr64(e, 14n) ^ rotr64(e, 18n) ^ rotr64(e, 41n)) + ((e & f) ^ (~e & MASK64 & g)) + K512[i] + w[i]) & MASK64;
|
|
154
|
+
const t2 = ((rotr64(a, 28n) ^ rotr64(a, 34n) ^ rotr64(a, 39n)) + ((a & b) ^ (a & c) ^ (b & c))) & MASK64;
|
|
155
|
+
[k, g, f, e, d, c, b, a] = [g, f, e, (d + t1) & MASK64, c, b, a, (t1 + t2) & MASK64];
|
|
156
|
+
}
|
|
157
|
+
h = h.map((x, i) => (x + [a, b, c, d, e, f, g, k][i]) & MASK64);
|
|
158
|
+
}
|
|
159
|
+
return h.map((x) => x.toString(16).padStart(16, '0')).join('');
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
export const DIGESTS = new Map([['md5', md5], ['sha1', sha1], ['sha256', sha256], ['sha512', sha512]]);
|
package/src/engine.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// Backward resolution, forward fixpoints and proof recording.
|
|
2
|
-
import { PRIMITIVE_KEYS, primitive } from './builtins.js';
|
|
2
|
+
import { PRIMITIVE_KEYS, STATE_TESTS, primitive } from './builtins.js';
|
|
3
3
|
import { Reliance, Settler, Unsettled } from './closure.js';
|
|
4
4
|
import { freshClause, matchHead, renaming, text, variant } from './common.js';
|
|
5
5
|
import { goalTerm, subgoals } from './goals.js';
|
|
@@ -9,7 +9,7 @@ import { checkRendered, clauseDisplay, renderProof } from './proof.js';
|
|
|
9
9
|
import { CONTROL_KEYS, Program } from './program.js';
|
|
10
10
|
import {
|
|
11
11
|
Env, EyemindError, Struct, Var, conjunction, copyResolved, deref, flattenConjunction, freshTerm,
|
|
12
|
-
identity, isAnonymous, isCallable, isGround, isGroundButAnonymous, isTerm, key, keyArity, listFromItems,
|
|
12
|
+
identity, indexKey, isAnonymous, isCallable, isGround, isGroundButAnonymous, isTerm, key, keyArity, listFromItems,
|
|
13
13
|
unify, variables,
|
|
14
14
|
} from './terms.js';
|
|
15
15
|
import { Lettering, SourceNaming, write } from './writer.js';
|
|
@@ -107,7 +107,10 @@ const QUIET = new Pending(null, null, NO_NODES, null);
|
|
|
107
107
|
const SPLICE = 'splice';
|
|
108
108
|
|
|
109
109
|
function resolveOne(node, env) {
|
|
110
|
-
|
|
110
|
+
const goal = copyResolved(node.goal, env);
|
|
111
|
+
// A state test whose goal no later binding changed is an ordinary builtin.
|
|
112
|
+
const by = isTerm(node.by, 'called', 1) && variant(goal) === variant(node.by.args[0]) ? BUILTIN : node.by;
|
|
113
|
+
return new Node(goal, by,
|
|
111
114
|
node.bindings.map(([name, value]) => [name, copyResolved(value, env)]),
|
|
112
115
|
new Array(node.children.length).fill(null), node.collectedUses, false,
|
|
113
116
|
node.scoped.map((term) => copyResolved(term, env)));
|
|
@@ -197,7 +200,7 @@ export function clausesUsed(nodes, used = new Set()) {
|
|
|
197
200
|
const node = pending.pop();
|
|
198
201
|
if (seen.has(node)) continue;
|
|
199
202
|
seen.add(node);
|
|
200
|
-
if (node.by
|
|
203
|
+
if (isTerm(node.by, 'clause', 1) || isTerm(node.by, 'source', 1)) used.add(Number(node.by.args[0]));
|
|
201
204
|
if (node.collectedUses) for (const id of node.collectedUses) used.add(id);
|
|
202
205
|
for (const child of node.children) pending.push(child);
|
|
203
206
|
}
|
|
@@ -268,8 +271,6 @@ function compareChosen(a, b) {
|
|
|
268
271
|
return a.length - b.length;
|
|
269
272
|
}
|
|
270
273
|
|
|
271
|
-
const isIndexable = (value) => typeof value === 'string' || typeof value === 'bigint' || typeof value === 'number';
|
|
272
|
-
|
|
273
274
|
export class Solver {
|
|
274
275
|
constructor(program, options) {
|
|
275
276
|
this.program = program;
|
|
@@ -541,9 +542,10 @@ export class Solver {
|
|
|
541
542
|
this.factIndex.set(goalKey, positions);
|
|
542
543
|
}
|
|
543
544
|
node.goal.args.forEach((arg, position) => {
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
545
|
+
const argument = indexKey(arg);
|
|
546
|
+
if (argument !== undefined) {
|
|
547
|
+
const bucket = positions[position].get(argument);
|
|
548
|
+
if (bucket === undefined) positions[position].set(argument, [number]);
|
|
547
549
|
else bucket.push(number);
|
|
548
550
|
}
|
|
549
551
|
});
|
|
@@ -559,9 +561,8 @@ export class Solver {
|
|
|
559
561
|
let best = null;
|
|
560
562
|
let size = this.facts.get(goalKey).length;
|
|
561
563
|
for (let position = 0; position < goal.args.length; position++) {
|
|
562
|
-
|
|
563
|
-
if (arg
|
|
564
|
-
if (isIndexable(arg)) {
|
|
564
|
+
const arg = indexKey(goal.args[position], env);
|
|
565
|
+
if (arg !== undefined) {
|
|
565
566
|
const bucket = positions[position].get(arg) || NO_NODES;
|
|
566
567
|
if (bucket.length < size) {
|
|
567
568
|
best = bucket;
|
|
@@ -573,6 +574,15 @@ export class Solver {
|
|
|
573
574
|
return best;
|
|
574
575
|
}
|
|
575
576
|
|
|
577
|
+
// How a solved primitive is justified: a state test whose goal still has a
|
|
578
|
+
// variable keeps its instance as called, renamed apart from later bindings.
|
|
579
|
+
primitiveBy(goal, env) {
|
|
580
|
+
if (!STATE_TESTS.has(key(goal))) return BUILTIN;
|
|
581
|
+
const called = copyResolved(goal, env);
|
|
582
|
+
if (isGround(called)) return BUILTIN;
|
|
583
|
+
return new Struct('called', [freshTerm(called, `called${++this.serial}`, new Map(), true)]);
|
|
584
|
+
}
|
|
585
|
+
|
|
576
586
|
// Take the next untried alternative of a choice point, or null. The caller
|
|
577
587
|
// has already undone the bindings of the previous one.
|
|
578
588
|
retry(point, env) {
|
|
@@ -584,7 +594,7 @@ export class Solver {
|
|
|
584
594
|
this.chosen[point.frame.index] = [0, point.position];
|
|
585
595
|
point.position++;
|
|
586
596
|
}
|
|
587
|
-
return this.advance(point.frame, recording ? new Node(point.goal,
|
|
597
|
+
return this.advance(point.frame, recording ? new Node(point.goal, this.primitiveBy(point.goal, env)) : null);
|
|
588
598
|
}
|
|
589
599
|
const count = point.count();
|
|
590
600
|
while (point.position < count) {
|
|
@@ -1021,9 +1031,11 @@ function certify(solver, boundaries, operational = false) {
|
|
|
1021
1031
|
if (outcome.status === 'settled' && (!operational || positiveListings(program, outcome.listings))) {
|
|
1022
1032
|
for (const item of outcome.tables) tables.add(item);
|
|
1023
1033
|
for (const item of outcome.listings) listings.add(item);
|
|
1024
|
-
} else if (outcome.status === 'failed') {
|
|
1034
|
+
} else if (outcome.status === 'failed' && solver.haltCode === null) {
|
|
1025
1035
|
throw new EyemindError(`cannot certify this result: ${outcome.failures[0]?.[0] ?? 'its search certificate fails'}`);
|
|
1026
1036
|
}
|
|
1037
|
+
// A halted run stopped before its fixpoint, so its derived facts need not
|
|
1038
|
+
// be closed under the rules; a boundary they cannot settle stays trusted.
|
|
1027
1039
|
}
|
|
1028
1040
|
return {
|
|
1029
1041
|
// Tables in the order their calls were first met.
|
package/src/program.js
CHANGED
|
@@ -4,7 +4,7 @@ import { containsTemplate, expandTemplates } from './templates.js';
|
|
|
4
4
|
import { subgoals } from './goals.js';
|
|
5
5
|
import { hasInspection, inspectionTerm } from './inspection.js';
|
|
6
6
|
import {
|
|
7
|
-
EMPTY, Env, EyemindError, Struct, Var, deref, flattenConjunction, freshTerm, identity, isCallable,
|
|
7
|
+
EMPTY, Env, EyemindError, Struct, Var, deref, flattenConjunction, freshTerm, identity, indexKey, isCallable,
|
|
8
8
|
isGround, isTerm, key, keyArity, unify, variables,
|
|
9
9
|
} from './terms.js';
|
|
10
10
|
import { write } from './writer.js';
|
|
@@ -14,7 +14,6 @@ export const RESERVED_KEYS = new Set(['step/4', 'clause/2', 'searched/2', 'deriv
|
|
|
14
14
|
|
|
15
15
|
// The statements that state a forward rule, and how an error names them.
|
|
16
16
|
const FORWARD_KINDS = { forward: 'a forward rule', query: 'query()', contradiction: 'contradiction()' };
|
|
17
|
-
const isIndexable = (value) => typeof value === 'string' || typeof value === 'bigint' || typeof value === 'number';
|
|
18
17
|
|
|
19
18
|
export class Clause {
|
|
20
19
|
constructor(id, head, heads, body, forward, line, captures = null) {
|
|
@@ -228,9 +227,8 @@ export class Program {
|
|
|
228
227
|
for (let position = 0; position < positions.length; position++) {
|
|
229
228
|
const index = positions[position];
|
|
230
229
|
if (index === null) continue;
|
|
231
|
-
|
|
232
|
-
if (argument
|
|
233
|
-
if (!isIndexable(argument)) continue;
|
|
230
|
+
const argument = indexKey(args[position], env);
|
|
231
|
+
if (argument === undefined) continue;
|
|
234
232
|
const bucket = bucketEntries(index[0].get(argument));
|
|
235
233
|
const size = bucket.length + index[1].length;
|
|
236
234
|
if (size < count) {
|
|
@@ -256,11 +254,11 @@ export class Program {
|
|
|
256
254
|
}
|
|
257
255
|
}
|
|
258
256
|
|
|
259
|
-
// An index per argument position where enough entries carry an
|
|
260
|
-
//
|
|
261
|
-
//
|
|
262
|
-
//
|
|
263
|
-
// unification does. A value with one entry maps to the entry itself, and one
|
|
257
|
+
// An index per argument position where enough entries carry an index key:
|
|
258
|
+
// an atom, a number or a small ground compound (indexKey). Each index is
|
|
259
|
+
// [keyed, other]: a map from key to the entries with that key there, and the
|
|
260
|
+
// entries with anything else there. Map keys keep integers and floats
|
|
261
|
+
// distinct while equating signed zeros, just as unification does. A value with one entry maps to the entry itself, and one
|
|
264
262
|
// with more to a Bucket of them: most values of a large program head a single
|
|
265
263
|
// clause, and an array for each would only be more for memory to keep.
|
|
266
264
|
export function positionIndexes(entries, headOf, arity) {
|
|
@@ -268,7 +266,7 @@ export function positionIndexes(entries, headOf, arity) {
|
|
|
268
266
|
if (arity) {
|
|
269
267
|
for (let i = 0; i < entries.length; i++) {
|
|
270
268
|
const args = headOf(entries[i]).args;
|
|
271
|
-
for (let position = 0; position < arity; position++) if (
|
|
269
|
+
for (let position = 0; position < arity; position++) if (indexKey(args[position]) !== undefined) counts[position]++;
|
|
272
270
|
}
|
|
273
271
|
}
|
|
274
272
|
const positions = counts.map((count) => (count * 2 < entries.length ? null : [new Map(), []]));
|
|
@@ -278,8 +276,8 @@ export function positionIndexes(entries, headOf, arity) {
|
|
|
278
276
|
for (let position = 0; position < arity; position++) {
|
|
279
277
|
const index = positions[position];
|
|
280
278
|
if (index === null) continue;
|
|
281
|
-
const argument = args[position];
|
|
282
|
-
if (
|
|
279
|
+
const argument = indexKey(args[position]);
|
|
280
|
+
if (argument === undefined) {
|
|
283
281
|
index[1].push(entry);
|
|
284
282
|
continue;
|
|
285
283
|
}
|
|
@@ -346,8 +344,9 @@ function headCandidates(entry, goal) {
|
|
|
346
344
|
if (entry === undefined) return [];
|
|
347
345
|
let chosen = entry.pairs;
|
|
348
346
|
entry.positions.forEach((bucket, position) => {
|
|
349
|
-
|
|
350
|
-
|
|
347
|
+
const argument = goal instanceof Struct ? indexKey(goal.args[position]) : undefined;
|
|
348
|
+
if (bucket === null || argument === undefined) return;
|
|
349
|
+
const matched = bucketEntries(bucket[0].get(argument));
|
|
351
350
|
if (matched.length + bucket[1].length < chosen.length) chosen = [...matched, ...bucket[1]];
|
|
352
351
|
});
|
|
353
352
|
return chosen;
|
package/src/proof.js
CHANGED
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
//
|
|
10
10
|
// Verification follows recorded uses; it never asks the solver to find a
|
|
11
11
|
// missing derivation. Only pure primitives are independently recomputed.
|
|
12
|
-
import { PRIMITIVE_KEYS, primitive } from './builtins.js';
|
|
12
|
+
import { PRIMITIVE_KEYS, STATE_TESTS, primitive } from './builtins.js';
|
|
13
13
|
import { Settler } from './closure.js';
|
|
14
14
|
import { freshClause, text, variant } from './common.js';
|
|
15
15
|
import { goalTerm } from './goals.js';
|
|
@@ -197,7 +197,7 @@ export function renderProof(program, claims, roots, checkable = false, heading =
|
|
|
197
197
|
const nodeId = spellings.spell(node.goal);
|
|
198
198
|
if (steps.has(nodeId)) continue;
|
|
199
199
|
steps.set(nodeId, node);
|
|
200
|
-
if (node.by
|
|
200
|
+
if (isTerm(node.by, 'clause', 1) || isTerm(node.by, 'source', 1)) {
|
|
201
201
|
const id = Number(node.by.args[0]);
|
|
202
202
|
cited.add(id);
|
|
203
203
|
for (const parent of program.byId.get(id)?.scopeIds || []) cited.add(parent);
|
|
@@ -228,7 +228,8 @@ export function renderProof(program, claims, roots, checkable = false, heading =
|
|
|
228
228
|
}
|
|
229
229
|
for (const node of steps.values()) {
|
|
230
230
|
const uses = `[${node.children.map((child) => spellings.lettered(child.goal, lettering)).join(', ')}]`;
|
|
231
|
-
|
|
231
|
+
const by = isTerm(node.by, 'called', 1) ? spellings.lettered(node.by, lettering) : text(node.by);
|
|
232
|
+
lines.push(`step(${spellings.lettered(node.goal, lettering)}, ${by}, ` +
|
|
232
233
|
`${bindingsText(node.bindings, lettering)}, ${uses})`);
|
|
233
234
|
}
|
|
234
235
|
const read = { tables: new Map(), calls: new Map(), listings: new Map(), order: [] };
|
|
@@ -510,6 +511,13 @@ function checkSteps(program, steps, allowTrusted, fail, spellings, name, outcome
|
|
|
510
511
|
const agrees = redecides(goal);
|
|
511
512
|
if (!agrees) fail.add('C5', `primitive disagrees: ${text(goal)}`, goal);
|
|
512
513
|
else tally.redecided++;
|
|
514
|
+
} else if (isTerm(by, 'called', 1)) {
|
|
515
|
+
if (bindings.length || uses.length || !isCallable(goal) || !STATE_TESTS.has(key(goal))) {
|
|
516
|
+
fail.add('C3', 'invalid called justification', goal);
|
|
517
|
+
continue;
|
|
518
|
+
}
|
|
519
|
+
if (!redecidesCalled(goal, by.args[0])) fail.add('C5', `primitive disagrees as called: ${text(by.args[0])}`, goal);
|
|
520
|
+
else tally.redecided++;
|
|
513
521
|
} else if (by === CONTROL_BY) {
|
|
514
522
|
let candidates = [];
|
|
515
523
|
if (isTerm(goal, 'call', 1) || isTerm(goal, 'once', 1)) candidates = [goal.args[0]];
|
|
@@ -551,6 +559,25 @@ function redecides(goal) {
|
|
|
551
559
|
return nearHostMath(goal);
|
|
552
560
|
}
|
|
553
561
|
|
|
562
|
+
// A state test recorded as called: the called goal, renamed apart, holds as
|
|
563
|
+
// a primitive without binding anything, and the step's goal is an instance
|
|
564
|
+
// of it, the same primitive with only its variables since bound.
|
|
565
|
+
function redecidesCalled(goal, called) {
|
|
566
|
+
if (!isCallable(called) || key(called) !== key(goal)) return false;
|
|
567
|
+
const renamed = freshTerm(called, 'calledCheck');
|
|
568
|
+
try {
|
|
569
|
+
let holds = false;
|
|
570
|
+
for (const env of primitive(renamed, new Env())) {
|
|
571
|
+
holds = resolvesTo(renamed, env, renamed);
|
|
572
|
+
break;
|
|
573
|
+
}
|
|
574
|
+
return holds && isInstance(goal, called, 'calledInstance');
|
|
575
|
+
} catch (error) {
|
|
576
|
+
if (!(error instanceof EyemindError)) throw error;
|
|
577
|
+
return false;
|
|
578
|
+
}
|
|
579
|
+
}
|
|
580
|
+
|
|
554
581
|
const isConstant = (term) => typeof term === 'string' || typeof term === 'bigint' || typeof term === 'number';
|
|
555
582
|
|
|
556
583
|
// Shortcuts the checker may take; tests turn them off to compare with the
|
|
@@ -818,6 +845,9 @@ class WitnessProvenance {
|
|
|
818
845
|
} else if (step.by === BUILTIN_BY) {
|
|
819
846
|
if (step.bindings.length || step.uses.length || !isCallable(goal) ||
|
|
820
847
|
!PRIMITIVE_KEYS.has(key(goal)) || !redecides(goal)) return false;
|
|
848
|
+
} else if (isTerm(step.by, 'called', 1)) {
|
|
849
|
+
if (step.bindings.length || step.uses.length || !isCallable(goal) ||
|
|
850
|
+
!STATE_TESTS.has(key(goal)) || !redecidesCalled(goal, step.by.args[0])) return false;
|
|
821
851
|
} else if (step.by === CONTROL_BY) {
|
|
822
852
|
const candidates = isTerm(goal, 'call', 1) || isTerm(goal, 'once', 1) ? [goal.args[0]]
|
|
823
853
|
: isTerm(goal, 'or', 2) ? goal.args : [];
|
package/src/terms.js
CHANGED
|
@@ -482,6 +482,46 @@ export function identity(term) {
|
|
|
482
482
|
return out.join('\u0001');
|
|
483
483
|
}
|
|
484
484
|
|
|
485
|
+
// The key an argument index files a term under: an atom or a number is its
|
|
486
|
+
// own key, and a small ground compound, such as iri('http://e/a'), the text
|
|
487
|
+
// of its structure. Signed zeros share a key, as they unify. A variable, a
|
|
488
|
+
// compound holding one, or one of more than INDEX_NODES nodes has none and
|
|
489
|
+
// constrains nothing. A key is only a filter, so an atom whose text happens
|
|
490
|
+
// to equal a compound's key could at most add candidates, never lose one.
|
|
491
|
+
const INDEX_NODES = 64;
|
|
492
|
+
|
|
493
|
+
export function indexKey(term, env = null) {
|
|
494
|
+
if (term instanceof Var) {
|
|
495
|
+
if (env === null) return undefined;
|
|
496
|
+
term = deref(term, env);
|
|
497
|
+
if (term instanceof Var) return undefined;
|
|
498
|
+
}
|
|
499
|
+
if (!(term instanceof Struct)) return term;
|
|
500
|
+
const out = ['\u0000k'];
|
|
501
|
+
const pending = [term];
|
|
502
|
+
let nodes = 0;
|
|
503
|
+
while (pending.length) {
|
|
504
|
+
let item = pending.pop();
|
|
505
|
+
if (item instanceof Var) {
|
|
506
|
+
if (env === null) return undefined;
|
|
507
|
+
item = deref(item, env);
|
|
508
|
+
if (item instanceof Var) return undefined;
|
|
509
|
+
}
|
|
510
|
+
if (++nodes > INDEX_NODES) return undefined;
|
|
511
|
+
if (item instanceof Struct) {
|
|
512
|
+
out.push('c', String(item.name.length), item.name, String(item.args.length));
|
|
513
|
+
for (let i = item.args.length - 1; i >= 0; i--) pending.push(item.args[i]);
|
|
514
|
+
} else if (typeof item === 'string') {
|
|
515
|
+
out.push('a', String(item.length), item);
|
|
516
|
+
} else if (typeof item === 'bigint') {
|
|
517
|
+
out.push('i', String(item));
|
|
518
|
+
} else {
|
|
519
|
+
out.push('f', String(item));
|
|
520
|
+
}
|
|
521
|
+
}
|
|
522
|
+
return out.join('\u0001');
|
|
523
|
+
}
|
|
524
|
+
|
|
485
525
|
// The variables of a term by name, in order of first appearance.
|
|
486
526
|
export function variables(term, result = new Map()) {
|
|
487
527
|
const pending = [term];
|
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.5.0';
|