eyemind 0.5.12 → 0.5.13
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 +31 -2
- package/SPEC.md +34 -1
- package/package.json +1 -1
- package/src/builtins.js +30 -0
- package/src/cli.js +6 -3
- package/src/formats.js +4 -4
- package/src/n3-parser.js +9 -6
- package/src/native-proof.js +6 -4
- package/src/srl-decimal.js +66 -0
- package/src/srl-functions.js +67 -54
- package/src/srl-parser.js +9 -7
- package/src/srl.js +70 -13
- 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
|
|
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 128 runnable programs, each with a card deck and saved conclusions, proofs and check reports. The conformance suite has 1356 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
|
|
|
@@ -309,7 +309,36 @@ eyemind --all rules.srl facts.ttl # the base graph too
|
|
|
309
309
|
eyemind -c rules.srl facts.ttl # a proof of it, checked
|
|
310
310
|
```
|
|
311
311
|
|
|
312
|
-
Triples are `rdf(Subject, Predicate, Object)`, with `base/3` marking the base graph and `inf/3` the inference graph. A rule becomes `implies`, `NOT` becomes `not` of a helper, `GROUP` becomes `findall`, a blank node in a rule head becomes the Skolem term of its firing, and a SPARQL error is a goal that fails, so `FILTER` rejects the solution and `SET` drops it. The W3C SPARQL 1.2 RL test suite runs in `npm test` from `.cache/w3c/sparql-rl`: all 241 tests pass.
|
|
312
|
+
Triples are `rdf(Subject, Predicate, Object)`, with `base/3` marking the base graph and `inf/3` the inference graph. A rule becomes `implies`, `NOT` becomes `not` of a helper, `GROUP` becomes `findall`, a blank node in a rule head becomes the Skolem term of its firing, and a SPARQL error is a goal that fails, so `FILTER` rejects the solution and `SET` drops it. The W3C SPARQL 1.2 RL test suite runs in `npm test` from `.cache/w3c/sparql-rl`: all 241 tests pass.
|
|
313
|
+
|
|
314
|
+
SRL integers and decimals use exact integer arithmetic. Decimal addition,
|
|
315
|
+
subtraction, multiplication, comparison, rounding and terminating division
|
|
316
|
+
preserve decimal values, including values beyond the exact integer range of
|
|
317
|
+
a double: `0.1 + 0.2` is `0.3`. Nonterminating division retains at least 34
|
|
318
|
+
significant digits and rounds to nearest with ties to even. Floats and doubles
|
|
319
|
+
use binary64 arithmetic: `0.1e0 + 0.2e0` is
|
|
320
|
+
`"0.30000000000000004"^^xsd:double`. Floating-point overflow and division by
|
|
321
|
+
zero follow IEEE-754, including `INF`, `-INF`, `NaN` and signed zero; decimal
|
|
322
|
+
division by zero is an expression error. Mixed numeric expressions use
|
|
323
|
+
SPARQL type promotion. The [exact decimals example](https://eyereasoner.github.io/eyemind/examples/deck/exact-decimals)
|
|
324
|
+
shows both arithmetic models.
|
|
325
|
+
|
|
326
|
+
`NOW()` returns one UTC `xsd:dateTime` throughout a rule set evaluation.
|
|
327
|
+
`UUID()` produces a `urn:uuid:` IRI and `STRUUID()` a UUID string, distinct
|
|
328
|
+
for each expression occurrence and incoming solution. Compilation captures
|
|
329
|
+
the clock and a fresh random seed once; UUIDs are derived from that seed,
|
|
330
|
+
the rule, the expression and the solution, so later reasoning rounds keep
|
|
331
|
+
the same identifiers. A new compilation captures a new execution context.
|
|
332
|
+
The compiled program states this context as one `srl_execution` fact.
|
|
333
|
+
Saved proofs retain it, and `--check-proof` restores only that validated
|
|
334
|
+
context before recompiling the source. Checking proves consequences of the
|
|
335
|
+
recorded context; it does not attest the wall-clock time or the randomness
|
|
336
|
+
of the seed. Library calls to `compileSrl` and `reasonSrl` accept
|
|
337
|
+
`context: { now, seed }`, with an ISO UTC timestamp including milliseconds
|
|
338
|
+
and 64 lowercase hexadecimal seed digits, to reproduce an execution.
|
|
339
|
+
The [execution identifiers example](https://eyereasoner.github.io/eyemind/examples/deck/execution-identifiers)
|
|
340
|
+
has a fixed context in the example manifest for its saved artifacts;
|
|
341
|
+
ordinary command-line and playground runs capture fresh values.
|
|
313
342
|
|
|
314
343
|
The [example catalog](https://eyereasoner.github.io/eyemind/examples/) includes
|
|
315
344
|
SRL programs for deployment dependencies, route distances, ancestry, inventory,
|
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.
|
|
5
|
+
Version: eyemind 0.5.13
|
|
6
6
|
```
|
|
7
7
|
|
|
8
8
|
This document specifies the syntax and meaning of eyemind programs and data
|
|
@@ -578,6 +578,7 @@ primitive called outside its patterns raises an error.
|
|
|
578
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
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
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
|
+
| `float64` | `float64(+Op, +A, +B, ?R)` | Explicit IEEE-754 binary64 computation, including exceptional values represented as atoms, as defined below. |
|
|
581
582
|
| `regex_match` | `regex_match(+P, +T)` | Some part of the atom `T` matches the regular expression `P`. |
|
|
582
583
|
| `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
584
|
| `regex_replace` | `regex_replace(+P, +T, +R, ?U)` | `U` is `T` with every match of `P` replaced by `R`. |
|
|
@@ -585,6 +586,25 @@ primitive called outside its patterns raises an error.
|
|
|
585
586
|
A character is a Unicode code point. Every primitive except `atom_concat`
|
|
586
587
|
and `regex_find` has at most one solution.
|
|
587
588
|
|
|
589
|
+
`float64/4` converts numeric operands explicitly to binary64, rounding an
|
|
590
|
+
integer to nearest with ties to even. Exceptional values are the atoms
|
|
591
|
+
`'INF'`, `'-INF'` and `'NaN'`; they are not additional core numbers.
|
|
592
|
+
`Op` is `'add'`, `'sub'`, `'mul'` or `'div'`, with IEEE-754 results,
|
|
593
|
+
including overflow, underflow and division by zero. Signed zero is retained.
|
|
594
|
+
For `'compare'`, `R` is `'<'`, `'='`, `'>'`, or `'unordered'` if either
|
|
595
|
+
operand is NaN. Operations `'convert'`, `'neg'`, `'abs'`, `'ceil'`, `'floor'`
|
|
596
|
+
and `'round'` use only `A`; `'round'` rounds halves toward positive infinity
|
|
597
|
+
and retains negative zero. `'trunc'` returns an exact integer for a finite
|
|
598
|
+
converted `A` and fails otherwise. The unused `B` is still an input.
|
|
599
|
+
|
|
600
|
+
For `'parse'`, `A` is an atom with an XSD float/double lexical form: an
|
|
601
|
+
optionally signed decimal with an optional exponent, `'INF'`, `'+INF'`,
|
|
602
|
+
`'-INF'` or `'NaN'`, optionally surrounded by XML whitespace. Parsing rounds
|
|
603
|
+
once to binary64 and allows overflow and underflow. An invalid lexical
|
|
604
|
+
form or operand fails; another `Op` raises an error. Finite numeric results
|
|
605
|
+
are floats; exceptional results are the atoms above. C5 re-decides these
|
|
606
|
+
operations, including signed zeros and exceptional results.
|
|
607
|
+
|
|
588
608
|
A regular expression `P` is an atom read as an ECMAScript pattern
|
|
589
609
|
(ECMA-262, the `RegExp` pattern grammar and matching semantics) with only the
|
|
590
610
|
`u` flag, so it matches by code point: `.` matches `'\u{1F600}'` as one
|
|
@@ -2192,10 +2212,23 @@ or `pe:called` and an ordered `pe:answers` collection. Clause numbers name
|
|
|
2192
2212
|
the compiled program's clauses, whose authority is still the source input.
|
|
2193
2213
|
SRL proofs contain only `DATA` and declarations, never rules or imports.
|
|
2194
2214
|
|
|
2215
|
+
When an SRL rule set uses `NOW`, `UUID` or `STRUUID`, its compiled program
|
|
2216
|
+
includes one ground `srl_execution(Now, Seed)` fact. `Now` is an ISO UTC
|
|
2217
|
+
timestamp with milliseconds and `Seed` contains 64 lowercase hexadecimal
|
|
2218
|
+
digits. The compiler captures these external inputs once per compilation;
|
|
2219
|
+
they remain fixed throughout evaluation. To check a saved SRL proof, the
|
|
2220
|
+
format loader may recover this fact from its clause records, validate its
|
|
2221
|
+
two fields, and recompile the source with that execution context. All other
|
|
2222
|
+
clauses still come from the source, and all displays undergo C1–C10 as
|
|
2223
|
+
usual. This establishes consequences of the recorded context, without
|
|
2224
|
+
certifying a clock observation or the entropy of the seed.
|
|
2225
|
+
|
|
2195
2226
|
The reader decodes every record, verifies all displays and properties against
|
|
2196
2227
|
those records, and applies the unchanged checks of
|
|
2197
2228
|
[Section 11](#11-proof-checking) to the decoded
|
|
2198
2229
|
certificate. A missing, extra, duplicate or inconsistent property fails C3.
|
|
2230
|
+
Numeric literal displays retain their decimal digits during this comparison;
|
|
2231
|
+
distinct decimal literals MUST NOT agree merely by rounding to binary64.
|
|
2199
2232
|
Prefix aliases and reordering top-level properties are accepted, as is
|
|
2200
2233
|
consistent blank-node renaming; the order of collections and formula triples
|
|
2201
2234
|
is retained. Displayed claims cannot replace encoded claims, and neither
|
package/package.json
CHANGED
package/src/builtins.js
CHANGED
|
@@ -212,6 +212,35 @@ function termText(args, resolved, env, bind) {
|
|
|
212
212
|
return bind(args[1], write(copyResolved(args[0], env)));
|
|
213
213
|
}
|
|
214
214
|
|
|
215
|
+
// IEEE-754 exceptional values are atoms, keeping core numbers finite.
|
|
216
|
+
// The conversion is explicit, like float(N) in arithmetic expressions.
|
|
217
|
+
function float64(args, resolved, env, bind) {
|
|
218
|
+
const [op, a, b] = resolved;
|
|
219
|
+
if (!['parse', 'compare', 'trunc', 'convert', 'add', 'sub', 'mul', 'div', 'neg', 'abs', 'ceil', 'floor', 'round'].includes(op)) {
|
|
220
|
+
throw new EyemindError(`float64/4: unknown operation ${write(op)}`);
|
|
221
|
+
}
|
|
222
|
+
const special = { INF: Infinity, '-INF': -Infinity, NaN: NaN };
|
|
223
|
+
const decode = (v) => typeof v === 'number' || typeof v === 'bigint' ? Number(v)
|
|
224
|
+
: typeof v === 'string' && Object.hasOwn(special, v) ? special[v] : undefined;
|
|
225
|
+
const encode = (v) => Number.isNaN(v) ? 'NaN' : v === Infinity ? 'INF' : v === -Infinity ? '-INF' : v;
|
|
226
|
+
const y = decode(b);
|
|
227
|
+
if (y === undefined) return false;
|
|
228
|
+
if (op === 'parse') {
|
|
229
|
+
if (typeof a !== 'string' || !/^[\t\n\r ]*(?:[+-]?(?:INF|(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)(?:[eE][+-]?[0-9]+)?)|NaN)[\t\n\r ]*$/.test(a)) return false;
|
|
230
|
+
const text = a.trim();
|
|
231
|
+
return bind(args[3], encode(/^[+]?INF$/.test(text) ? Infinity : text === '-INF' ? -Infinity : Number(text)));
|
|
232
|
+
}
|
|
233
|
+
const x = decode(a);
|
|
234
|
+
if (x === undefined) return false;
|
|
235
|
+
if (op === 'compare') return bind(args[3], Number.isNaN(x) || Number.isNaN(y) ? 'unordered' : x < y ? '<' : x > y ? '>' : '=');
|
|
236
|
+
if (op === 'trunc') return Number.isFinite(x) && bind(args[3], BigInt(Math.trunc(x)));
|
|
237
|
+
const operations = {
|
|
238
|
+
convert: () => x, add: () => x + y, sub: () => x - y, mul: () => x * y, div: () => x / y,
|
|
239
|
+
neg: () => -x, abs: () => Math.abs(x), ceil: () => Math.ceil(x), floor: () => Math.floor(x), round: () => Math.round(x),
|
|
240
|
+
};
|
|
241
|
+
return bind(args[3], encode(operations[op]()));
|
|
242
|
+
}
|
|
243
|
+
|
|
215
244
|
const isNumberValue = (term) => typeof term === 'bigint' || typeof term === 'number';
|
|
216
245
|
|
|
217
246
|
export const TESTS = new Map([
|
|
@@ -249,6 +278,7 @@ export const TESTS = new Map([
|
|
|
249
278
|
['atom_upper/2', caseConversion('atom_upper/2', (a) => a.toUpperCase())],
|
|
250
279
|
['digest/3', digest],
|
|
251
280
|
['term_text/2', termText],
|
|
281
|
+
['float64/4', float64],
|
|
252
282
|
['regex_match/2', regexMatch],
|
|
253
283
|
['regex_replace/4', regexReplace],
|
|
254
284
|
]);
|
package/src/cli.js
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
// The eyemind command line.
|
|
2
2
|
import { run, unusedClauses } from './engine.js';
|
|
3
|
-
import { OUTPUT_FORMATS, defaultFormat, loadInputs, rdfMessageFormat, scopeOf, writeConclusions, writeProof } from './formats.js';
|
|
3
|
+
import { OUTPUT_FORMATS, defaultFormat, inputKind, loadInputs, rdfMessageFormat, scopeOf, writeConclusions, writeProof } from './formats.js';
|
|
4
4
|
import { isRdfMessageLog, replayMessages, RdfMessageReader } from './messages.js';
|
|
5
5
|
import { checkProof, checkReport, publicReport } from './proof.js';
|
|
6
6
|
import { EyemindError } from './terms.js';
|
|
7
7
|
import { VERSION } from './version.js';
|
|
8
|
+
import { srlContextFromProof } from './srl.js';
|
|
8
9
|
|
|
9
10
|
export const HELP = `Usage: eyemind [OPTION ...] [FILE ...]
|
|
10
11
|
Programs are JavaScript; forward rules run to a fixpoint. Other files are read
|
|
@@ -178,7 +179,10 @@ export function main(argv, io) {
|
|
|
178
179
|
}
|
|
179
180
|
return 0;
|
|
180
181
|
}
|
|
181
|
-
const
|
|
182
|
+
const document = proofFile === null ? null : readSource(proofFile, io);
|
|
183
|
+
const loaded = loadInputs(files.map((file) => [readSource(file, io), file === '-' ? '<stdin>' : file]), io,
|
|
184
|
+
{ base, messageInputs: io.messageInputs,
|
|
185
|
+
srlContext: document !== null && files.some((file) => inputKind(file) === 'srl') ? srlContextFromProof(document) : null });
|
|
182
186
|
const program = loaded.program;
|
|
183
187
|
if (printProgram) {
|
|
184
188
|
stdout(loaded.text);
|
|
@@ -187,7 +191,6 @@ export function main(argv, io) {
|
|
|
187
191
|
// A compiled program has the larger bounds, unless they are given.
|
|
188
192
|
if (loaded.kind !== 'js') for (const [name, value] of Object.entries(COMPILED_LIMITS)) options[name] ??= value;
|
|
189
193
|
if (proofFile !== null) {
|
|
190
|
-
const document = readSource(proofFile, io);
|
|
191
194
|
const report = checkProof(program, document, { goals, allowTrusted: !strictProof });
|
|
192
195
|
stdout(asJson ? `${JSON.stringify(publicReport(report), null, 2)}\n` : checkReport(report));
|
|
193
196
|
// An invalid proof is a result, not an error: it has its own exit code.
|
package/src/formats.js
CHANGED
|
@@ -12,8 +12,8 @@
|
|
|
12
12
|
// .srl a SPARQL 1.2 RL rule set, compiled to one
|
|
13
13
|
//
|
|
14
14
|
// The compiled program is ordinary eyemind: proofs, checking and --unused
|
|
15
|
-
// apply to it
|
|
16
|
-
//
|
|
15
|
+
// apply to it. SRL execution functions capture a context that a saved proof
|
|
16
|
+
// retains; compiling with that context reproduces the same program later.
|
|
17
17
|
import { EyemindError, Struct } from './terms.js';
|
|
18
18
|
import { loadSources } from './lang.js';
|
|
19
19
|
import { readTerms } from './reader.js';
|
|
@@ -55,7 +55,7 @@ export function loadInputs(inputs, io = null, options = {}) {
|
|
|
55
55
|
}
|
|
56
56
|
}
|
|
57
57
|
|
|
58
|
-
function load(inputs, io, { base = null, messageInputs = null }) {
|
|
58
|
+
function load(inputs, io, { base = null, messageInputs = null, srlContext = null }) {
|
|
59
59
|
const kinds = inputs.map(([text, name]) => messageInputs?.has(name) ||
|
|
60
60
|
(inputKind(name) === 'n3' && isRdfMessageLog(text)) ? 'rdf' : inputKind(name));
|
|
61
61
|
const baseOf = (name) => base ?? io?.fileIri?.(name) ?? null;
|
|
@@ -75,7 +75,7 @@ function load(inputs, io, { base = null, messageInputs = null }) {
|
|
|
75
75
|
if (parsed.triples) throw new EyemindError('RDF Message Log replay needs N3 or JavaScript rules; a SPARQL rule set takes an RDF base graph');
|
|
76
76
|
return parsed.quads;
|
|
77
77
|
});
|
|
78
|
-
const compiled = compileSrl(text, { base: baseOf(name), filename: name, resolve: importResolver(io), data });
|
|
78
|
+
const compiled = compileSrl(text, { base: baseOf(name), filename: name, resolve: importResolver(io), data, context: srlContext });
|
|
79
79
|
for (const warning of compiled.warnings) io?.stderr?.(`eyemind: warning: ${warning}\n`);
|
|
80
80
|
return { kind: 'srl', program: loadSources([[compiled.program, name]], io), text: compiled.program, prefixes: compiled.prefixes, compiled };
|
|
81
81
|
}
|
package/src/n3-parser.js
CHANGED
|
@@ -236,8 +236,9 @@ export const DEFAULT_PREFIXES = {
|
|
|
236
236
|
};
|
|
237
237
|
|
|
238
238
|
// Parse a document: { triples, prefixes, base }. Prefixes map names to IRIs
|
|
239
|
-
// in declaration order.
|
|
240
|
-
|
|
239
|
+
// in declaration order. Native proof validation preserves numeric literal
|
|
240
|
+
// text, so two different decimal displays cannot agree through rounding.
|
|
241
|
+
export function parseN3(src, { base = '', preserveNumericLiterals = false } = {}) {
|
|
241
242
|
const toks = tokenize(String(src));
|
|
242
243
|
let pos = 0;
|
|
243
244
|
const prefixes = new Map();
|
|
@@ -299,7 +300,7 @@ export function parseN3(src, { base = '' } = {}) {
|
|
|
299
300
|
if (isP('^^')) {
|
|
300
301
|
next();
|
|
301
302
|
const dt = iriTerm();
|
|
302
|
-
return typedLiteral(text, dt.v);
|
|
303
|
+
return typedLiteral(text, dt.v, preserveNumericLiterals);
|
|
303
304
|
}
|
|
304
305
|
return { t: 'literal', v: text, dt: `${XSD}string` };
|
|
305
306
|
}
|
|
@@ -318,7 +319,7 @@ export function parseN3(src, { base = '' } = {}) {
|
|
|
318
319
|
if (tok.k === 'var') return { t: 'var', v: tok.v };
|
|
319
320
|
if (tok.k === 'bnode') return { t: 'bnode', v: tok.v, scope: scope.id };
|
|
320
321
|
if (tok.k === 'string') return literalTail(tok.v);
|
|
321
|
-
if (tok.k === 'number') return numberTerm(tok.v);
|
|
322
|
+
if (tok.k === 'number') return numberTerm(tok.v, preserveNumericLiterals);
|
|
322
323
|
if (tok.k === 'word') {
|
|
323
324
|
if (tok.v === 'true' || tok.v === 'false') return { t: 'literal', v: tok.v, dt: `${XSD}boolean` };
|
|
324
325
|
throw fail(`unexpected word '${tok.v}'; prefixed names need a colon, as in :${tok.v}`, tok);
|
|
@@ -443,8 +444,9 @@ export function parseN3(src, { base = '' } = {}) {
|
|
|
443
444
|
return { triples: top.triples, prefixes, base };
|
|
444
445
|
}
|
|
445
446
|
|
|
446
|
-
function numberTerm(text) {
|
|
447
|
+
function numberTerm(text, preserve = false) {
|
|
447
448
|
if (/^[+-]?[0-9]+$/.test(text)) return { t: 'int', v: BigInt(text) };
|
|
449
|
+
if (preserve) return { t: 'literal', v: text, dt: `${XSD}${/[eE]/.test(text) ? 'double' : 'decimal'}` };
|
|
448
450
|
if (/[eE]/.test(text)) return { t: 'literal', v: String(Number(text)), dt: `${XSD}double` };
|
|
449
451
|
return { t: 'float', v: Number(text) };
|
|
450
452
|
}
|
|
@@ -454,9 +456,10 @@ const FLOAT_TYPES = new Set(['decimal']);
|
|
|
454
456
|
|
|
455
457
|
// Native numbers represent integer and decimal. Float and double retain
|
|
456
458
|
// their datatype so triple matching and log:equalTo distinguish them.
|
|
457
|
-
export function typedLiteral(text, dt) {
|
|
459
|
+
export function typedLiteral(text, dt, preserve = false) {
|
|
458
460
|
if (dt.startsWith(XSD)) {
|
|
459
461
|
const local = dt.slice(XSD.length);
|
|
462
|
+
if (preserve && ['decimal', 'float', 'double'].includes(local)) return { t: 'literal', v: text, dt };
|
|
460
463
|
if (INTEGER_TYPES.has(local) && /^[+-]?[0-9]+$/.test(text)) return { t: 'int', v: BigInt(text) };
|
|
461
464
|
if (FLOAT_TYPES.has(local) && /^[+-]?([0-9]+(\.[0-9]*)?|\.[0-9]+)([eE][+-]?[0-9]+)?$/.test(text)) return { t: 'float', v: Number(text) };
|
|
462
465
|
if ((local === 'double' || local === 'float') && Number.isFinite(Number(text)) && /^[+-]?([0-9]+(\.[0-9]*)?|\.[0-9]+)([eE][+-]?[0-9]+)?$/.test(text)) return { t: 'literal', v: String(Number(text)), dt };
|
package/src/native-proof.js
CHANGED
|
@@ -167,9 +167,11 @@ function srlData(document) {
|
|
|
167
167
|
if (t.type === 'iri') return { t: 'iri', v: t.value };
|
|
168
168
|
if (t.type === 'blank') return { t: 'bnode', v: t.value, scope: 0 };
|
|
169
169
|
if (t.type === 'literal') {
|
|
170
|
-
|
|
170
|
+
// A displayed decimal must not lose digits before its record is
|
|
171
|
+
// compared: adjacent exact values can round to the same binary64.
|
|
172
|
+
const value = t.lexical ?? (Object.is(t.value, -0) ? '-0' : String(t.value));
|
|
171
173
|
return t.lang ? { t: 'literal', v: value, dt: `${RDF}langString`, lang: t.lang, dir: t.langDir }
|
|
172
|
-
: typedLiteral(value, t.datatype ?? `${XSD}string
|
|
174
|
+
: typedLiteral(value, t.datatype ?? `${XSD}string`, true);
|
|
173
175
|
}
|
|
174
176
|
if (t.type === 'triple') return { t: 'triple', s: term(t.s), p: term(t.p), o: term(t.o) };
|
|
175
177
|
fail('an SRL proof must be ground RDF data');
|
|
@@ -246,7 +248,7 @@ function compare(actual, expected) {
|
|
|
246
248
|
|
|
247
249
|
function readNative(document) {
|
|
248
250
|
let parsed, format;
|
|
249
|
-
try { parsed = parseN3(document); format = 'n3'; }
|
|
251
|
+
try { parsed = parseN3(document, { preserveNumericLiterals: true }); format = 'n3'; }
|
|
250
252
|
catch (n3Error) {
|
|
251
253
|
try { parsed = srlData(document); format = 'srl'; }
|
|
252
254
|
catch (error) { throw new EyemindError(`native proof: ${error.message}`); }
|
|
@@ -269,7 +271,7 @@ function readNative(document) {
|
|
|
269
271
|
if (id.t !== 'iri' || id.v !== `${ROOT}#record${i + 1}`) fail('proof records must be numbered in document order');
|
|
270
272
|
return decode(property(id.v, `${TERM_NS}term`));
|
|
271
273
|
});
|
|
272
|
-
const expected = format === 'n3' ? parseN3(render(terms, format)) : srlData(render(terms, format));
|
|
274
|
+
const expected = format === 'n3' ? parseN3(render(terms, format), { preserveNumericLiterals: true }) : srlData(render(terms, format));
|
|
273
275
|
compare(parsed.triples, expected.triples);
|
|
274
276
|
return terms;
|
|
275
277
|
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
// Exact decimal values as decimal(Coefficient, Scale), meaning C / 10^S.
|
|
2
|
+
// These are ordinary rules: the proof checker re-decides their integer
|
|
3
|
+
// arithmetic without a decimal implementation or calls to the reasoner.
|
|
4
|
+
export const decimalRules = String.raw`
|
|
5
|
+
implied_by(srl_decimal_text(L, decimal(C, S)), [regex_find('^[ \\t\\n\\r]*([+-]?)([0-9]*)(?:\\.([0-9]*))?[ \\t\\n\\r]*$', L, [_, Sign, I, F]), atom_concat(I, F, Ds), atom_length(Ds, N), gt(N, 0), atom_chars(Ds, Cs), number_chars(A, Cs), atom_length(F, S), srl_decimal_sign(Sign, A, C)])
|
|
6
|
+
implied_by(srl_decimal_sign('', A, A), 'true')
|
|
7
|
+
implied_by(srl_decimal_sign('+', A, A), 'true')
|
|
8
|
+
implied_by(srl_decimal_sign('-', A, C), is(C, neg(A)))
|
|
9
|
+
implied_by(srl_decimal_normal(decimal(C, S), decimal(N, T)), once(srl_decimal_normal_(C, S, N, T)))
|
|
10
|
+
implied_by(srl_decimal_normal_(0, _, 0, 0), 'true')
|
|
11
|
+
implied_by(srl_decimal_normal_(C, S, N, T), [ne(C, 0), gt(S, 0), eq(mod(C, 10), 0), is(A, floordiv(C, 10)), is(B, sub(S, 1)), srl_decimal_normal_(A, B, N, T)])
|
|
12
|
+
implied_by(srl_decimal_normal_(C, S, C, S), or(eq(S, 0), ne(mod(C, 10), 0)))
|
|
13
|
+
implied_by(srl_decimal_lexical(V, L), [srl_decimal_normal(V, decimal(C, S)), is(A, abs(C)), number_chars(A, Cs), atom_chars(Ds, Cs), atom_length(Ds, N), is(P, sub(N, S)), srl_point(Ds, N, P, B), srl_decimal_prefix(C, Sign), atom_concat(Sign, B, L)])
|
|
14
|
+
implied_by(srl_decimal_prefix(C, '-'), lt(C, 0))
|
|
15
|
+
implied_by(srl_decimal_prefix(C, ''), ge(C, 0))
|
|
16
|
+
implied_by(srl_decimal_value(N, decimal(N, 0)), is_int(N))
|
|
17
|
+
implied_by(srl_decimal_value(decimal(C, S), decimal(C, S)), 'true')
|
|
18
|
+
implied_by(srl_decimal_value(F, D), [is_float(F), number_chars(F, Cs), atom_chars(A, Cs), srl_float_text('decimal', A, L), srl_decimal_text(L, D)])
|
|
19
|
+
implied_by(srl_float_value(N, F), [srl_float_operand(N), float64('convert', N, 0, F)])
|
|
20
|
+
implied_by(srl_float_operand(N), is_number(N))
|
|
21
|
+
implied_by(srl_float_operand(N), srl_float_special(N))
|
|
22
|
+
fact(srl_float_special('INF'), srl_float_special('-INF'), srl_float_special('NaN'))
|
|
23
|
+
implied_by(srl_float_lexical(N, L), [is_float(N), number_chars(N, Cs), atom_chars(L, Cs)])
|
|
24
|
+
implied_by(srl_float_lexical(N, N), srl_float_special(N))
|
|
25
|
+
implied_by(srl_float_value(D, F), [unify(D, decimal(_, _)), srl_decimal_lexical(D, L), float64('parse', L, 0, F)])
|
|
26
|
+
implied_by(srl_numeric_value('integer', N, N), is_int(N))
|
|
27
|
+
implied_by(srl_numeric_value('decimal', V, D), srl_decimal_value(V, D))
|
|
28
|
+
implied_by(srl_numeric_value(K, V, F), [srl_float_kind(K), srl_float_value(V, F)])
|
|
29
|
+
implied_by(srl_pair(A, B, K, X, Y), [srl_num(A, KA, VA), srl_num(B, KB, VB), srl_promote(KA, KB, K), srl_numeric_value(K, VA, X), srl_numeric_value(K, VB, Y)])
|
|
30
|
+
implied_by(srl_decimal_align(decimal(A, S), decimal(B, T), X, Y, U), [is(U, max(S, T)), is(X, mul(A, pow(10, sub(U, S)))), is(Y, mul(B, pow(10, sub(U, T))))])
|
|
31
|
+
implied_by(srl_calculate('add', decimal(A, S), decimal(B, T), decimal(C, U)), [srl_decimal_align(decimal(A, S), decimal(B, T), X, Y, U), is(C, add(X, Y))])
|
|
32
|
+
implied_by(srl_calculate('sub', decimal(A, S), decimal(B, T), decimal(C, U)), [srl_decimal_align(decimal(A, S), decimal(B, T), X, Y, U), is(C, sub(X, Y))])
|
|
33
|
+
implied_by(srl_calculate('mul', decimal(A, S), decimal(B, T), decimal(C, U)), [is(C, mul(A, B)), is(U, add(S, T))])
|
|
34
|
+
// Reduce a quotient first. Terminating division is exact; otherwise keep
|
|
35
|
+
// at least 34 significant digits, rounded to nearest with ties to even.
|
|
36
|
+
implied_by(srl_calculate('div', decimal(A, S), decimal(B, T), decimal(C, U)), [ne(B, 0), is(N, mul(A, pow(10, T))), is(D, mul(B, pow(10, S))), is(G, gcd(N, D)), is(P, floordiv(abs(N), G)), is(Q, floordiv(abs(D), G)), srl_decimal_places(Q, P, U), is(Z, mul(P, pow(10, U))), is(H, floordiv(Z, Q)), is(R, mod(Z, Q)), srl_decimal_round(H, R, Q, V), srl_decimal_quotient_sign(N, D, V, C)])
|
|
37
|
+
implied_by(srl_decimal_places(Q, P, U), [srl_decimal_factors(Q, 2, 0, A, I), srl_decimal_factors(A, 5, 0, B, J), srl_decimal_precision(B, P, Q, I, J, U)])
|
|
38
|
+
implied_by(srl_decimal_factors(N, D, I, R, K), once(srl_decimal_factors_(N, D, I, R, K)))
|
|
39
|
+
implied_by(srl_decimal_factors_(N, D, I, R, K), [eq(mod(N, D), 0), is(M, floordiv(N, D)), is(J, add(I, 1)), srl_decimal_factors_(M, D, J, R, K)])
|
|
40
|
+
implied_by(srl_decimal_factors_(N, D, I, N, I), ne(mod(N, D), 0))
|
|
41
|
+
implied_by(srl_decimal_precision(1, _, _, I, J, U), is(U, max(I, J)))
|
|
42
|
+
implied_by(srl_decimal_precision(B, P, Q, _, _, U), [ne(B, 1), number_chars(P, Ps), number_chars(Q, Qs), srl_length(Ps, NP), srl_length(Qs, NQ), is(U, max(0, add(34, sub(NQ, NP))))])
|
|
43
|
+
implied_by(srl_decimal_round(H, R, Q, V), [is(D, sub(mul(R, 2), Q)), srl_decimal_round_(D, H, V)])
|
|
44
|
+
implied_by(srl_decimal_round_(D, H, H), lt(D, 0))
|
|
45
|
+
implied_by(srl_decimal_round_(D, H, V), [gt(D, 0), is(V, add(H, 1))])
|
|
46
|
+
implied_by(srl_decimal_round_(0, H, V), is(V, add(H, mod(H, 2))))
|
|
47
|
+
implied_by(srl_decimal_quotient_sign(N, D, V, C), [lt(mul(N, D), 0), is(C, neg(V))])
|
|
48
|
+
implied_by(srl_decimal_quotient_sign(N, D, V, V), ge(mul(N, D), 0))
|
|
49
|
+
implied_by(srl_value_compare(decimal(A, S), decimal(B, T), O), [srl_decimal_align(decimal(A, S), decimal(B, T), X, Y, _), srl_compare(X, Y, O)])
|
|
50
|
+
implied_by(srl_value_compare(X, Y, O), [is_int(X), is_int(Y), srl_compare(X, Y, O)])
|
|
51
|
+
implied_by(srl_value_compare(X, Y, O), [srl_float_operand(X), srl_float_operand(Y), not(and(is_int(X), is_int(Y))), float64('compare', X, Y, O)])
|
|
52
|
+
implied_by(srl_value_zero(decimal(C, _), C), 'true')
|
|
53
|
+
implied_by(srl_value_zero(N, N), is_number(N))
|
|
54
|
+
fact(srl_value_zero('NaN', 0), srl_value_zero('INF', 1), srl_value_zero('-INF', 1))
|
|
55
|
+
implied_by(srl_unary('neg', decimal(C, S), decimal(N, S)), is(N, neg(C)))
|
|
56
|
+
implied_by(srl_unary('abs', decimal(C, S), decimal(N, S)), is(N, abs(C)))
|
|
57
|
+
implied_by(srl_unary('floor', decimal(C, S), N), is(N, floordiv(C, pow(10, S))))
|
|
58
|
+
implied_by(srl_unary('ceil', decimal(C, S), N), is(N, neg(floordiv(neg(C), pow(10, S)))))
|
|
59
|
+
implied_by(srl_unary('trunc', decimal(C, S), N), [is(A, floordiv(abs(C), pow(10, S))), srl_decimal_quotient_sign(C, 1, A, N)])
|
|
60
|
+
implied_by(srl_unary('round', decimal(C, S), N), [is(D, pow(10, S)), is(N, floordiv(add(mul(C, 2), D), mul(D, 2)))])
|
|
61
|
+
${['neg', 'abs', 'floor', 'ceil', 'trunc'].map((op) => `implied_by(srl_unary('${op}', X, V), [is_int(X), is(V, ${op}(X))])`).join('\n')}
|
|
62
|
+
implied_by(srl_unary('round', X, X), is_int(X))
|
|
63
|
+
implied_by(srl_unary(Op, X, V), [srl_float_operand(X), not(is_int(X)), float64(Op, X, 0, V)])
|
|
64
|
+
${['add', 'sub', 'mul'].map((op) => `implied_by(srl_calculate('${op}', X, Y, V), [is_int(X), is_int(Y), is(V, ${op}(X, Y))])`).join('\n')}
|
|
65
|
+
implied_by(srl_calculate(Op, X, Y, V), [srl_float_operand(X), srl_float_operand(Y), not(and(is_int(X), is_int(Y))), float64(Op, X, Y, V)])
|
|
66
|
+
`;
|
package/src/srl-functions.js
CHANGED
|
@@ -10,9 +10,11 @@
|
|
|
10
10
|
//
|
|
11
11
|
// Values are RDF terms as the compiler writes them: an xsd:integer with a
|
|
12
12
|
// canonical lexical form is an eyemind integer, every other literal is
|
|
13
|
-
// literal(Lexical, datatype(IRI)) or literal(Text, lang(Tag)).
|
|
14
|
-
//
|
|
15
|
-
// their datatype.
|
|
13
|
+
// literal(Lexical, datatype(IRI)) or literal(Text, lang(Tag)). Exact
|
|
14
|
+
// decimals use integer coefficients and scales; floats and doubles
|
|
15
|
+
// use binary64 values. Results retain their promoted datatype.
|
|
16
|
+
|
|
17
|
+
import { decimalRules } from './srl-decimal.js';
|
|
16
18
|
|
|
17
19
|
const XSD = 'http://www.w3.org/2001/XMLSchema#';
|
|
18
20
|
const RDF = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#';
|
|
@@ -30,28 +32,38 @@ const tested = (name, args) => String.raw`
|
|
|
30
32
|
implied_by(${name}_t(${args}, T), or([${name}_(${args}), unify(T, 'true')], [not(${name}_(${args})), unify(T, 'false')]))`;
|
|
31
33
|
|
|
32
34
|
export const DEFINITIONS = {
|
|
35
|
+
srl_now: {
|
|
36
|
+
text: String.raw`
|
|
37
|
+
implied_by(srl_now(literal(Now, datatype('${XSD}dateTime'))), srl_execution(Now, _))`,
|
|
38
|
+
},
|
|
39
|
+
srl_uuid: {
|
|
40
|
+
text: String.raw`
|
|
41
|
+
// A random execution seed, a call site and its incoming solution identify
|
|
42
|
+
// one UUID. Repeated reasoning rounds and certificate checks keep it fixed.
|
|
43
|
+
implied_by(srl_uuid(Rule, Site, Solution, Id), [srl_execution(_, Seed), term_text([Seed, Rule, Site, Solution], Text), digest('sha256', Text, Hex), regex_find('^(.{8})(.{4}).(.{3})(.)(.{3})(.{12})', Hex, [_, A, B, C, V, D, E]), srl_uuid_variant(V, W), srl_atoms_concat([A, '-', B, '-4', C, '-', W, D, '-', E], Id)])
|
|
44
|
+
${[...'0123456789abcdef'].map((c, i) => `fact(srl_uuid_variant('${c}', '${'89ab'[i % 4]}'))`).join('\n')}`,
|
|
45
|
+
needs: ['srl_atoms_concat'],
|
|
46
|
+
},
|
|
33
47
|
// Numbers.
|
|
34
48
|
srl_num: {
|
|
35
49
|
text: String.raw`
|
|
36
50
|
// srl_num(T, K, V): T is a number of kind K (integer, decimal, float or
|
|
37
|
-
// double) with value V;
|
|
51
|
+
// double) with value V; a decimal is decimal(Coefficient, Scale).
|
|
38
52
|
implied_by(srl_num(T, 'integer', T), is_int(T))
|
|
39
|
-
implied_by(srl_num(literal(L, datatype(D)), K, V), [srl_numeric_type(D, K),
|
|
53
|
+
implied_by(srl_num(literal(L, datatype(D)), K, V), [srl_numeric_type(D, K), srl_read_number(K, L, V)])
|
|
54
|
+
implied_by(srl_read_number('decimal', L, V), srl_decimal_text(L, V))
|
|
55
|
+
implied_by(srl_read_number('integer', L, V), [regex_find('^[ \\t\\n\\r]*([+-]?[0-9]+)[ \\t\\n\\r]*$', L, [_, I]), atom_chars(I, Cs), number_chars(V, Cs)])
|
|
56
|
+
implied_by(srl_read_number(K, L, V), [srl_float_kind(K), float64('parse', L, 0, V)])
|
|
40
57
|
${INTEGER_TYPES.map((t) => `fact(srl_numeric_type('${XSD}${t}', 'integer'))`).join('\n')}
|
|
41
58
|
fact(srl_numeric_type('${XSD}decimal', 'decimal'), srl_numeric_type('${XSD}float', 'float'), srl_numeric_type('${XSD}double', 'double'))
|
|
42
|
-
|
|
43
|
-
implied_by(srl_num_value(K, N, V), [srl_float_kind(K), is(V, float(N))])
|
|
44
|
-
fact(srl_float_kind('decimal'), srl_float_kind('float'), srl_float_kind('double'))
|
|
59
|
+
fact(srl_float_kind('float'), srl_float_kind('double'))
|
|
45
60
|
// Numeric type promotion: integer, decimal, float, double.
|
|
46
61
|
fact(srl_rank('integer', 0), srl_rank('decimal', 1), srl_rank('float', 2), srl_rank('double', 3))
|
|
47
62
|
implied_by(srl_promote(A, B, K), [srl_rank(A, I), srl_rank(B, J), is(M, max(I, J)), srl_rank(K, M)])`,
|
|
63
|
+
needs: ['srl_decimal'],
|
|
48
64
|
},
|
|
49
|
-
|
|
50
|
-
text: String.raw`
|
|
51
|
-
// srl_make(K, V, T): T is the term for the value V of kind K. A float is
|
|
52
|
-
// written as its shortest text; a decimal never has an exponent.
|
|
53
|
-
implied_by(srl_make('integer', V, V), is_int(V))
|
|
54
|
-
implied_by(srl_make(K, V, literal(L, datatype(D))), [srl_float_kind(K), srl_numeric_type(D, K), lt(abs(V), float(1.7976931348623157e308)), is(F, float(V)), number_chars(F, Cs), atom_chars(A, Cs), srl_float_text(K, A, L)])
|
|
65
|
+
srl_decimal: {
|
|
66
|
+
text: decimalRules + String.raw`
|
|
55
67
|
implied_by(srl_float_text('double', A, A), 'true')
|
|
56
68
|
implied_by(srl_float_text('float', A, A), 'true')
|
|
57
69
|
implied_by(srl_float_text('decimal', A, A), not(regex_match('e', A)))
|
|
@@ -61,36 +73,34 @@ implied_by(srl_point(Ds, N, P, B), [ge(P, N), is(Z, sub(P, N)), srl_zeros(Z, Zs)
|
|
|
61
73
|
implied_by(srl_point(Ds, N, P, B), [le(P, 0), is(Z, neg(P)), srl_zeros(Z, Zs), atom_concat('0.', Zs, H), atom_concat(H, Ds, B)])
|
|
62
74
|
implied_by(srl_point(Ds, N, P, B), [gt(P, 0), lt(P, N), once([atom_concat(H, T, Ds), atom_length(H, P)]), atom_concat(H, '.', H1), atom_concat(H1, T, B)])
|
|
63
75
|
fact(srl_zeros(0, ''))
|
|
64
|
-
implied_by(srl_zeros(N, Z), [gt(N, 0), is(M, sub(N, 1)), srl_zeros(M, Z0), atom_concat('0', Z0, Z)])
|
|
76
|
+
implied_by(srl_zeros(N, Z), [gt(N, 0), is(M, sub(N, 1)), srl_zeros(M, Z0), atom_concat('0', Z0, Z)])
|
|
77
|
+
implied_by(srl_compare(X, Y, O), or([lt(X, Y), unify(O, '<')], [eq(X, Y), unify(O, '=')], [gt(X, Y), unify(O, '>')]))`,
|
|
78
|
+
needs: ['srl_length'],
|
|
79
|
+
},
|
|
80
|
+
srl_make: {
|
|
81
|
+
text: String.raw`
|
|
82
|
+
// srl_make(K, V, T): T is the term for the value V of kind K. A float is
|
|
83
|
+
// written as its shortest text; a decimal never has an exponent.
|
|
84
|
+
implied_by(srl_make('integer', V, V), is_int(V))
|
|
85
|
+
implied_by(srl_make('decimal', V, literal(L, datatype('${XSD}decimal'))), [srl_decimal_value(V, D), srl_decimal_lexical(D, L)])
|
|
86
|
+
implied_by(srl_make(K, V, literal(L, datatype(D))), [srl_float_kind(K), srl_numeric_type(D, K), srl_float_value(V, N), srl_float_lexical(N, L)])
|
|
87
|
+
`,
|
|
65
88
|
needs: ['srl_num'],
|
|
66
89
|
},
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
// raises no error; a float result that would overflow is a SPARQL error.
|
|
71
|
-
implied_by(srl_finite(Op, X, Y), once(srl_finite_(Op, X, Y)))
|
|
72
|
-
implied_by(srl_finite_(_, X, Y), [is_int(X), is_int(Y)])
|
|
73
|
-
implied_by(srl_finite_('add', X, Y), [lt(abs(X), 8e307), lt(abs(Y), 8e307)])
|
|
74
|
-
implied_by(srl_finite_('sub', X, Y), [lt(abs(X), 8e307), lt(abs(Y), 8e307)])
|
|
75
|
-
implied_by(srl_finite_('mul', X, Y), or(eq(X, 0), eq(Y, 0)))
|
|
76
|
-
implied_by(srl_finite_('mul', X, Y), [srl_magnitude(X, M), srl_magnitude(Y, N), lt(add(M, N), 308)])
|
|
77
|
-
implied_by(srl_finite_('div', X, Y), eq(X, 0))
|
|
78
|
-
implied_by(srl_finite_('div', X, Y), [srl_magnitude(X, M), srl_magnitude(Y, N), lt(sub(M, N), 308)])
|
|
79
|
-
implied_by(srl_magnitude(X, M), [ne(X, 0), lt(abs(X), 1e308), is(M, log10(abs(X)))])`,
|
|
80
|
-
},
|
|
81
|
-
srl_add: { text: arith('srl_add', 'add'), needs: ['srl_make', 'srl_finite'] },
|
|
82
|
-
srl_sub: { text: arith('srl_sub', 'sub'), needs: ['srl_make', 'srl_finite'] },
|
|
83
|
-
srl_mul: { text: arith('srl_mul', 'mul'), needs: ['srl_make', 'srl_finite'] },
|
|
90
|
+
srl_add: { text: arith('srl_add', 'add'), needs: ['srl_make'] },
|
|
91
|
+
srl_sub: { text: arith('srl_sub', 'sub'), needs: ['srl_make'] },
|
|
92
|
+
srl_mul: { text: arith('srl_mul', 'mul'), needs: ['srl_make'] },
|
|
84
93
|
srl_div: {
|
|
85
94
|
text: String.raw`
|
|
86
|
-
//
|
|
87
|
-
|
|
95
|
+
// Integers divide to a decimal. Decimal division by zero is an error;
|
|
96
|
+
// floats and doubles retain their IEEE-754 exceptional results.
|
|
97
|
+
implied_by(srl_div(A, B, R), [srl_pair(A, B, K0, X0, Y0), srl_div_kind(K0, K), srl_numeric_value(K, X0, X), srl_numeric_value(K, Y0, Y), srl_calculate('div', X, Y, V), srl_make(K, V, R)])
|
|
88
98
|
fact(srl_div_kind('integer', 'decimal'), srl_div_kind('decimal', 'decimal'), srl_div_kind('float', 'float'), srl_div_kind('double', 'double'))`,
|
|
89
|
-
needs: ['srl_make'
|
|
99
|
+
needs: ['srl_make'],
|
|
90
100
|
},
|
|
91
101
|
srl_neg: {
|
|
92
102
|
text: String.raw`
|
|
93
|
-
implied_by(srl_neg(A, R), [srl_num(A, K, X),
|
|
103
|
+
implied_by(srl_neg(A, R), [srl_num(A, K, X), srl_unary('neg', X, V), srl_make(K, V, R)])`,
|
|
94
104
|
needs: ['srl_make'],
|
|
95
105
|
},
|
|
96
106
|
srl_pos: {
|
|
@@ -112,7 +122,7 @@ fact(srl_flip('true', 'false'), srl_flip('false', 'true'))`,
|
|
|
112
122
|
// a term without one, such as an IRI, has none.
|
|
113
123
|
implied_by(srl_ebv(T, B), once(srl_ebv_(T, B)))
|
|
114
124
|
implied_by(srl_ebv_(literal(L, datatype('${XSD}boolean')), B), srl_boolean_text(L, B))
|
|
115
|
-
implied_by(srl_ebv_(T, B), [srl_num(T, _, V), or([eq(V, 0), unify(B, 'false')], [ne(V, 0), unify(B, 'true')])])
|
|
125
|
+
implied_by(srl_ebv_(T, B), [srl_num(T, _, X), srl_value_zero(X, V), or([eq(V, 0), unify(B, 'false')], [ne(V, 0), unify(B, 'true')])])
|
|
116
126
|
implied_by(srl_ebv_(literal(L, datatype('${XSD}string')), B), srl_nonempty(L, B))
|
|
117
127
|
implied_by(srl_ebv_(literal(L, lang(_)), B), srl_nonempty(L, B))
|
|
118
128
|
implied_by(srl_ebv_(literal(L, lang(_, _)), B), srl_nonempty(L, B))
|
|
@@ -151,7 +161,7 @@ fact(srl_or3('false', 'false', 'false'), srl_or3('true', _, 'true'), srl_or3('fa
|
|
|
151
161
|
// srl_equal(A, B, T): T is 'true' when A and B are equal and 'false' when
|
|
152
162
|
// they are not; literals that cannot be compared have no answer, an error.
|
|
153
163
|
implied_by(srl_equal(A, B, T), once(srl_equal_(A, B, T)))
|
|
154
|
-
implied_by(srl_equal_(A, B, T), [
|
|
164
|
+
implied_by(srl_equal_(A, B, T), [srl_pair(A, B, _, X, Y), srl_value_compare(X, Y, O), or([identical(O, '='), unify(T, 'true')], [not_identical(O, '='), unify(T, 'false')])])
|
|
155
165
|
implied_by(srl_equal_(A, B, 'true'), identical(A, B))
|
|
156
166
|
implied_by(srl_equal_(A, B, T), [srl_boolean(A, X), srl_boolean(B, Y), or([identical(X, Y), unify(T, 'true')], [not_identical(X, Y), unify(T, 'false')])])
|
|
157
167
|
implied_by(srl_equal_(A, B, 'false'), [srl_text_kind(A, _), srl_text_kind(B, _)])
|
|
@@ -193,14 +203,18 @@ implied_by(srl_ne(A, B, R), [srl_equal(A, B, T), srl_flip(T, F), srl_bool(F, R)]
|
|
|
193
203
|
// numbers by value, simple strings by code point, booleans with false
|
|
194
204
|
// first, and date and time values of one datatype by their lexical forms.
|
|
195
205
|
implied_by(srl_order(A, B, O), once(srl_order_(A, B, O)))
|
|
196
|
-
implied_by(srl_order_(A, B, O), [
|
|
206
|
+
implied_by(srl_order_(A, B, O), [srl_pair(A, B, _, X, Y), srl_value_compare(X, Y, O)])
|
|
197
207
|
implied_by(srl_order_(literal(X, datatype('${XSD}string')), literal(Y, datatype('${XSD}string')), O), compare(O, X, Y))
|
|
198
208
|
implied_by(srl_order_(A, B, O), [srl_boolean(A, X), srl_boolean(B, Y), compare(O, X, Y)])
|
|
199
209
|
implied_by(srl_order_(literal(X, datatype(D)), literal(Y, datatype(D)), O), [srl_ordered_type(D), compare(O, X, Y)])
|
|
200
210
|
implied_by(srl_compare(X, Y, O), or([lt(X, Y), unify(O, '<')], [eq(X, Y), unify(O, '=')], [gt(X, Y), unify(O, '>')]))
|
|
211
|
+
fact(srl_lt_('unordered', 'false'))
|
|
201
212
|
fact(srl_lt_('<', 'true'), srl_lt_('=', 'false'), srl_lt_('>', 'false'))
|
|
213
|
+
fact(srl_le_('unordered', 'false'))
|
|
202
214
|
fact(srl_le_('<', 'true'), srl_le_('=', 'true'), srl_le_('>', 'false'))
|
|
215
|
+
fact(srl_gt_('unordered', 'false'))
|
|
203
216
|
fact(srl_gt_('<', 'false'), srl_gt_('=', 'false'), srl_gt_('>', 'true'))
|
|
217
|
+
fact(srl_ge_('unordered', 'false'))
|
|
204
218
|
fact(srl_ge_('<', 'false'), srl_ge_('=', 'true'), srl_ge_('>', 'true'))`,
|
|
205
219
|
needs: ['srl_equal'],
|
|
206
220
|
},
|
|
@@ -378,14 +392,14 @@ implied_by(srl_concat_kind(K, K), not_identical(K, 'none'))`,
|
|
|
378
392
|
srl_substr: {
|
|
379
393
|
text: String.raw`
|
|
380
394
|
// SUBSTR counts characters from 1, rounding its numeric arguments.
|
|
381
|
-
implied_by(srl_substr(T, S, literal(B, K)), [srl_string(T, A, K), srl_num(S, _, X),
|
|
382
|
-
implied_by(srl_substr(T, S, L, literal(B, K)), [srl_string(T, A, K), srl_num(S, _, X), srl_num(L, _, Y),
|
|
395
|
+
implied_by(srl_substr(T, S, literal(B, K)), [srl_string(T, A, K), srl_num(S, _, X), srl_unary('round', X, I), atom_chars(A, Cs), atom_length(A, N), is(E, add(N, 1)), srl_slice(Cs, 1, I, E, Bs), atom_chars(B, Bs)])
|
|
396
|
+
implied_by(srl_substr(T, S, L, literal(B, K)), [srl_string(T, A, K), srl_num(S, _, X), srl_num(L, _, Y), srl_unary('round', X, I), srl_unary('round', Y, J), is(E, add(I, J)), atom_chars(A, Cs), srl_slice(Cs, 1, I, E, Bs), atom_chars(B, Bs)])
|
|
383
397
|
// srl_slice(Cs, P, I, E, Bs): Bs are the characters of Cs, the first at
|
|
384
398
|
// position P, whose positions are at least I and below E.
|
|
385
399
|
fact(srl_slice([], _, _, _, []))
|
|
386
400
|
implied_by(srl_slice([C, ...Cs], P, I, E, [C, ...Bs]), [ge(P, I), lt(P, E), is(Q, add(P, 1)), srl_slice(Cs, Q, I, E, Bs)])
|
|
387
401
|
implied_by(srl_slice([_, ...Cs], P, I, E, Bs), [or(lt(P, I), ge(P, E)), is(Q, add(P, 1)), srl_slice(Cs, Q, I, E, Bs)])
|
|
388
|
-
|
|
402
|
+
`,
|
|
389
403
|
needs: ['srl_string', 'srl_num'],
|
|
390
404
|
},
|
|
391
405
|
srl_replace: {
|
|
@@ -427,13 +441,12 @@ implied_by(srl_atoms_concat([A, ...As], C), [srl_atoms_concat(As, C0), atom_conc
|
|
|
427
441
|
// Numeric functions.
|
|
428
442
|
srl_abs: {
|
|
429
443
|
text: String.raw`
|
|
430
|
-
implied_by(srl_abs(T, R), [srl_num(T, K, X),
|
|
431
|
-
implied_by(srl_ceil(T, R), [srl_num(T, K, X),
|
|
432
|
-
implied_by(srl_floor(T, R), [srl_num(T, K, X),
|
|
444
|
+
implied_by(srl_abs(T, R), [srl_num(T, K, X), srl_unary('abs', X, V), srl_make(K, V, R)])
|
|
445
|
+
implied_by(srl_ceil(T, R), [srl_num(T, K, X), srl_unary('ceil', X, V), srl_make(K, V, R)])
|
|
446
|
+
implied_by(srl_floor(T, R), [srl_num(T, K, X), srl_unary('floor', X, V), srl_make(K, V, R)])
|
|
433
447
|
// ROUND rounds halves up, toward positive infinity.
|
|
434
|
-
implied_by(srl_round(T, R), [srl_num(T, K, X),
|
|
435
|
-
|
|
436
|
-
implied_by(srl_round_(K, X, V), [srl_float_kind(K), is(V, floor(add(X, float(0.5))))])`,
|
|
448
|
+
implied_by(srl_round(T, R), [srl_num(T, K, X), srl_unary('round', X, V), srl_make(K, V, R)])
|
|
449
|
+
`,
|
|
437
450
|
needs: ['srl_make'],
|
|
438
451
|
},
|
|
439
452
|
|
|
@@ -474,15 +487,15 @@ implied_by(srl_cast_('${XSD}string', T, ${str('A')}), srl_cast_text(T, A))
|
|
|
474
487
|
implied_by(srl_cast_text(iri(A), A), 'true')
|
|
475
488
|
implied_by(srl_cast_text(literal(A, _), A), 'true')
|
|
476
489
|
implied_by(srl_cast_text(T, A), [is_int(T), number_chars(T, Cs), atom_chars(A, Cs)])
|
|
477
|
-
implied_by(srl_cast_('${XSD}integer', T, V), [srl_num(T, _, X),
|
|
490
|
+
implied_by(srl_cast_('${XSD}integer', T, V), [srl_num(T, _, X), srl_unary('trunc', X, V)])
|
|
478
491
|
implied_by(srl_cast_('${XSD}integer', T, V), [srl_boolean(T, B), srl_bit(B, V)])
|
|
479
|
-
implied_by(srl_cast_('${XSD}integer', literal(L, datatype('${XSD}string')), V), [
|
|
492
|
+
implied_by(srl_cast_('${XSD}integer', literal(L, datatype('${XSD}string')), V), [regex_find('^[ \\t\\n\\r]*([+-]?[0-9]+)[ \\t\\n\\r]*$', L, [_, I]), atom_chars(I, Cs), number_chars(V, Cs)])
|
|
480
493
|
implied_by(srl_cast_(D, T, R), [srl_float_type(D, K), srl_num(T, _, X), srl_make(K, X, R)])
|
|
481
494
|
implied_by(srl_cast_(D, T, R), [srl_float_type(D, K), srl_boolean(T, B), srl_bit(B, V), srl_make(K, V, R)])
|
|
482
|
-
implied_by(srl_cast_('${XSD}decimal', literal(L, datatype('${XSD}string')), R), [
|
|
483
|
-
implied_by(srl_cast_(D, literal(L, datatype('${XSD}string')), R), [srl_float_type(D, K), srl_float_kind_double(K),
|
|
495
|
+
implied_by(srl_cast_('${XSD}decimal', literal(L, datatype('${XSD}string')), R), [srl_decimal_text(L, X), srl_make('decimal', X, R)])
|
|
496
|
+
implied_by(srl_cast_(D, literal(L, datatype('${XSD}string')), R), [srl_float_type(D, K), srl_float_kind_double(K), float64('parse', L, 0, X), srl_make(K, X, R)])
|
|
484
497
|
implied_by(srl_cast_('${XSD}boolean', T, R), [srl_boolean(T, B), srl_bool(B, R)])
|
|
485
|
-
implied_by(srl_cast_('${XSD}boolean', T, R), [srl_num(T, _, X), or([eq(X, 0), unify(B, 'false')], [ne(X, 0), unify(B, 'true')]), srl_bool(B, R)])
|
|
498
|
+
implied_by(srl_cast_('${XSD}boolean', T, R), [srl_num(T, _, V), srl_value_zero(V, X), or([eq(X, 0), unify(B, 'false')], [ne(X, 0), unify(B, 'true')]), srl_bool(B, R)])
|
|
486
499
|
implied_by(srl_cast_('${XSD}boolean', literal(L, datatype('${XSD}string')), R), [or([srl_true_text(L), unify(B, 'true')], [srl_false_text(L), unify(B, 'false')]), srl_bool(B, R)])
|
|
487
500
|
implied_by(srl_cast_('${XSD}dateTime', literal(L, datatype(D)), literal(L, datatype('${XSD}dateTime'))), [srl_text_or_datetime(D), regex_match('^-?\\d{4,}-\\d\\d-\\d\\dT\\d\\d:\\d\\d:\\d\\d(?:\\.\\d+)?(?:Z|[+-]\\d\\d:\\d\\d)?$', L)])
|
|
488
501
|
implied_by(srl_cast_('${XSD}date', literal(L, datatype(D)), literal(L, datatype('${XSD}date'))), [srl_text_or_date(D), regex_match('^-?\\d{4,}-\\d\\d-\\d\\d(?:Z|[+-]\\d\\d:\\d\\d)?$', L)])
|
|
@@ -555,7 +568,7 @@ implied_by(srl_column([R, ...Rs], I, [V, ...Vs]), [srl_nth(I, R, V), srl_column(
|
|
|
555
568
|
|
|
556
569
|
function arith(name, op) {
|
|
557
570
|
return String.raw`
|
|
558
|
-
implied_by(${name}(A, B, R), [
|
|
571
|
+
implied_by(${name}(A, B, R), [srl_pair(A, B, K, X, Y), srl_calculate('${op}', X, Y, V), srl_make(K, V, R)])`;
|
|
559
572
|
}
|
|
560
573
|
|
|
561
574
|
function compare(name) {
|
package/src/srl-parser.js
CHANGED
|
@@ -59,7 +59,9 @@ class Parser {
|
|
|
59
59
|
this.parseImports();
|
|
60
60
|
} else if (this.matchWord('DATA')) {
|
|
61
61
|
this.expectValue('{');
|
|
62
|
-
|
|
62
|
+
// eyemind: native certificates can expand into more triples than a
|
|
63
|
+
// host permits as function arguments to one push(...triples).
|
|
64
|
+
for (const triple of this.parseTriplesBlock({ allowPath: false, context: 'data' })) data.push(triple);
|
|
63
65
|
} else if (this.matchWord('RULE')) {
|
|
64
66
|
rules.push(this.parseRule());
|
|
65
67
|
} else {
|
|
@@ -153,7 +155,7 @@ class Parser {
|
|
|
153
155
|
parseTriplesBlock(options = {}) {
|
|
154
156
|
const triples = [];
|
|
155
157
|
while (!this.matchValue('}')) {
|
|
156
|
-
|
|
158
|
+
for (const triple of this.parseTripleStatement(options)) triples.push(triple);
|
|
157
159
|
this.consumeOptionalDot();
|
|
158
160
|
}
|
|
159
161
|
return triples;
|
|
@@ -162,7 +164,7 @@ class Parser {
|
|
|
162
164
|
parseTripleStatement(options = {}) {
|
|
163
165
|
const subjectNode = this.parseGraphNode({ ...options, position: 'subject' });
|
|
164
166
|
const triples = [...subjectNode.triples];
|
|
165
|
-
|
|
167
|
+
for (const triple of this.parsePropertyListForSubject(subjectNode.term, options)) triples.push(triple);
|
|
166
168
|
return triples;
|
|
167
169
|
}
|
|
168
170
|
|
|
@@ -175,10 +177,10 @@ class Parser {
|
|
|
175
177
|
const predicate = options.allowPath ? this.parseVerbPathOrSimple(options) : this.parseVerbTerm(options);
|
|
176
178
|
do {
|
|
177
179
|
const objectNode = this.parseGraphNode({ ...options, position: 'object' });
|
|
178
|
-
|
|
180
|
+
for (const triple of objectNode.triples) triples.push(triple);
|
|
179
181
|
const baseTriple = { s: subject, p: predicate, o: objectNode.term };
|
|
180
182
|
triples.push(baseTriple);
|
|
181
|
-
|
|
183
|
+
for (const triple of this.parseAnnotationsForTriple(baseTriple, options)) triples.push(triple);
|
|
182
184
|
} while (this.matchValue(','));
|
|
183
185
|
|
|
184
186
|
if (this.matchValue(';')) {
|
|
@@ -216,7 +218,7 @@ class Parser {
|
|
|
216
218
|
const triples = [];
|
|
217
219
|
while (true) {
|
|
218
220
|
const item = this.parseGraphNode(options);
|
|
219
|
-
|
|
221
|
+
for (const triple of item.triples) triples.push(triple);
|
|
220
222
|
triples.push({ s: current, p: iri(RDF_FIRST), o: item.term });
|
|
221
223
|
if (this.matchValue(')')) {
|
|
222
224
|
triples.push({ s: current, p: iri(RDF_REST), o: iri(RDF_NIL) });
|
|
@@ -253,7 +255,7 @@ class Parser {
|
|
|
253
255
|
if (this.checkValue('|}')) throw this.error('Annotation blocks may not be empty');
|
|
254
256
|
const annotationSubject = currentReifier || this.freshGraphNode(options);
|
|
255
257
|
triples.push({ s: annotationSubject, p: iri(RDF_REIFIES), o: reified });
|
|
256
|
-
|
|
258
|
+
for (const triple of this.parsePropertyListForSubject(annotationSubject, options, ['|}'])) triples.push(triple);
|
|
257
259
|
this.expectValue('|}');
|
|
258
260
|
}
|
|
259
261
|
}
|
package/src/srl.js
CHANGED
|
@@ -28,7 +28,9 @@
|
|
|
28
28
|
// head triple term with variables) needs no more: the rule set's analysis
|
|
29
29
|
// has rejected those that depend on their own conclusions, and the others
|
|
30
30
|
// conclude the same when they run alongside what they read, because SET and
|
|
31
|
-
// Skolem terms give the same values in every round.
|
|
31
|
+
// Skolem terms give the same values in every round. Execution functions
|
|
32
|
+
// retain their captured context and identify each UUID by its incoming
|
|
33
|
+
// solution and expression occurrence.
|
|
32
34
|
import { analyze } from './srl-analyze.js';
|
|
33
35
|
import { BUILTIN_SIGNATURES, canonicalBuiltinName } from './srl-builtin-names.js';
|
|
34
36
|
import { libraryText } from './srl-functions.js';
|
|
@@ -38,6 +40,7 @@ import { loadText } from './lang.js';
|
|
|
38
40
|
import { DEFAULT_GRAPH } from './rdf.js';
|
|
39
41
|
import { readTerms } from './reader.js';
|
|
40
42
|
import { Struct } from './terms.js';
|
|
43
|
+
import { readProofTerms } from './native-proof.js';
|
|
41
44
|
import { write } from './writer.js';
|
|
42
45
|
|
|
43
46
|
export class SrlError extends Error {}
|
|
@@ -96,14 +99,15 @@ const RESERVED = new Set(['Math', 'JSON', 'BigInt', 'Infinity', 'NaN', 'undefine
|
|
|
96
99
|
|
|
97
100
|
// Compile a rule set's text. Options: base (IRI), filename, resolve (for
|
|
98
101
|
// IMPORTS, see readRuleSet), data (the base graph, as RDF quads from
|
|
99
|
-
// parseRdf, in its default graph)
|
|
100
|
-
|
|
102
|
+
// parseRdf, in its default graph), context (a recorded execution's now and
|
|
103
|
+
// seed). Returns { program, prefixes, warnings, context }.
|
|
104
|
+
export function compileSrl(text, { base = null, filename = '<input>', resolve = null, data = [], context = null } = {}) {
|
|
101
105
|
const ruleSet = readRuleSet(text, { base, filename, resolve });
|
|
102
|
-
return compileRuleSet(ruleSet, { data, source: filename });
|
|
106
|
+
return compileRuleSet(ruleSet, { data, source: filename, context });
|
|
103
107
|
}
|
|
104
108
|
|
|
105
109
|
// Compile a parsed rule set over a base graph of RDF quads.
|
|
106
|
-
export function compileRuleSet(ruleSet, { data = [], source = '<input>' } = {}) {
|
|
110
|
+
export function compileRuleSet(ruleSet, { data = [], source = '<input>', context = null } = {}) {
|
|
107
111
|
const needed = new Set();
|
|
108
112
|
const warnings = [];
|
|
109
113
|
const lines = [
|
|
@@ -122,10 +126,49 @@ export function compileRuleSet(ruleSet, { data = [], source = '<input>' } = {})
|
|
|
122
126
|
ruleSet.rules.forEach((rule, index) => {
|
|
123
127
|
lines.push(...new RuleCompiler(rule, index + 1, { needed, warnings }).compile());
|
|
124
128
|
});
|
|
129
|
+
if (needed.has('srl_now') || needed.has('srl_uuid')) {
|
|
130
|
+
context = executionContext(context);
|
|
131
|
+
lines.push(`fact(srl_execution(${q(context.now)}, ${q(context.seed)}))`);
|
|
132
|
+
}
|
|
125
133
|
lines.push('query(inf(S, P, O))');
|
|
126
134
|
const library = libraryText(needed);
|
|
127
135
|
if (library) lines.push('', '// SPARQL functions and aggregates.', library);
|
|
128
|
-
return { program: `${lines.join('\n')}\n`, prefixes: ruleSet.prefixes, warnings };
|
|
136
|
+
return { program: `${lines.join('\n')}\n`, prefixes: ruleSet.prefixes, warnings, context };
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
// Clock and entropy are inputs captured once when the rule set is compiled.
|
|
140
|
+
// A saved proof carries this one fact; replay validates its shape and then
|
|
141
|
+
// recompiles the source. No other clause display becomes source authority.
|
|
142
|
+
function executionContext(context) {
|
|
143
|
+
if (context === null) {
|
|
144
|
+
const bytes = new Uint8Array(32);
|
|
145
|
+
if (globalThis.crypto?.getRandomValues) globalThis.crypto.getRandomValues(bytes);
|
|
146
|
+
else for (let i = 0; i < bytes.length; i++) bytes[i] = Math.floor(Math.random() * 256);
|
|
147
|
+
context = { now: new Date().toISOString(), seed: [...bytes].map((b) => b.toString(16).padStart(2, '0')).join('') };
|
|
148
|
+
}
|
|
149
|
+
if (typeof context?.now !== 'string' || !/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{3}Z$/.test(context.now) ||
|
|
150
|
+
!Number.isFinite(Date.parse(context.now)) || new Date(context.now).toISOString() !== context.now ||
|
|
151
|
+
typeof context.seed !== 'string' || !/^[0-9a-f]{64}$/.test(context.seed)) {
|
|
152
|
+
throw new SrlError('an SRL execution context needs a UTC now timestamp and a 64-digit lowercase hexadecimal seed');
|
|
153
|
+
}
|
|
154
|
+
return { now: context.now, seed: context.seed };
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
export function srlContextFromProof(document) {
|
|
158
|
+
try {
|
|
159
|
+
const contexts = readProofTerms(document).map(([term]) => term)
|
|
160
|
+
.filter((t) => t instanceof Struct && t.name === 'clause' && t.args.length === 2)
|
|
161
|
+
.map((t) => t.args[1])
|
|
162
|
+
.filter((t) => t instanceof Struct && t.name === 'fact' && t.args.length === 1)
|
|
163
|
+
.map((t) => t.args[0])
|
|
164
|
+
.filter((t) => t instanceof Struct && t.name === 'srl_execution' && t.args.length === 2);
|
|
165
|
+
if (contexts.length !== 1) return null;
|
|
166
|
+
return executionContext({ now: contexts[0].args[0], seed: contexts[0].args[1] });
|
|
167
|
+
} catch {
|
|
168
|
+
// The ordinary checker reports malformed certificates, including native
|
|
169
|
+
// displays that disagree with their complete encoded records.
|
|
170
|
+
return null;
|
|
171
|
+
}
|
|
129
172
|
}
|
|
130
173
|
|
|
131
174
|
// RDF terms as eyemind terms. Blank nodes of data are bnode(Scope, Label).
|
|
@@ -173,6 +216,7 @@ class RuleCompiler {
|
|
|
173
216
|
this.helpers = [];
|
|
174
217
|
this.helperCount = 0;
|
|
175
218
|
this.terms = new Terms('srl');
|
|
219
|
+
this.sites = new WeakMap();
|
|
176
220
|
}
|
|
177
221
|
|
|
178
222
|
compile() {
|
|
@@ -507,10 +551,22 @@ class RuleCompiler {
|
|
|
507
551
|
};
|
|
508
552
|
}
|
|
509
553
|
case 'NOW':
|
|
510
|
-
|
|
554
|
+
return this.call('srl_now', []);
|
|
511
555
|
case 'UUID':
|
|
512
|
-
case 'STRUUID':
|
|
513
|
-
|
|
556
|
+
case 'STRUUID': {
|
|
557
|
+
this.need('srl_uuid');
|
|
558
|
+
if (!this.sites.has(expr)) this.sites.set(expr, ++this.helperCount);
|
|
559
|
+
const site = this.sites.get(expr);
|
|
560
|
+
const solution = [...scope.allBound()].sort().map((v) => scope.name(v));
|
|
561
|
+
const id = this.fresh('Uuid');
|
|
562
|
+
const value = this.fresh('R');
|
|
563
|
+
const goals = [`srl_uuid(${this.number}, ${site}, [${solution.join(', ')}], ${id})`];
|
|
564
|
+
if (name === 'UUID') {
|
|
565
|
+
const iri = this.fresh('Iri');
|
|
566
|
+
goals.push(`atom_concat('urn:uuid:', ${id}, ${iri})`, `unify(${value}, iri(${iri}))`);
|
|
567
|
+
} else goals.push(`unify(${value}, literal(${id}, datatype('${XSD}string')))`);
|
|
568
|
+
return { goals, value };
|
|
569
|
+
}
|
|
514
570
|
default:
|
|
515
571
|
throw new SrlError(`${name} is not supported`);
|
|
516
572
|
}
|
|
@@ -551,7 +607,8 @@ class Scope {
|
|
|
551
607
|
}
|
|
552
608
|
|
|
553
609
|
allBound() {
|
|
554
|
-
|
|
610
|
+
const inherited = this.parent ? [...this.parent.allBound()].filter((v) => this.keys?.has(v)) : [];
|
|
611
|
+
return new Set([...inherited, ...this.bound]);
|
|
555
612
|
}
|
|
556
613
|
|
|
557
614
|
term(t) {
|
|
@@ -617,10 +674,10 @@ export const SRL_LIMITS = { maxDepth: 1000000, maxIterations: 100000, maxInferen
|
|
|
617
674
|
// Returns { quads, program, prefixes, warnings, result }: the quads are the
|
|
618
675
|
// inference graph's, and with proof, result.proof is eyemind's checked
|
|
619
676
|
// proof of the compiled program.
|
|
620
|
-
export function reasonSrl(text, { base = null, filename = '<input>', resolve = null, data = [], all = false, limits = {}, proof = false } = {}) {
|
|
621
|
-
const { program, prefixes, warnings } = compileSrl(text, { base, filename, resolve, data });
|
|
677
|
+
export function reasonSrl(text, { base = null, filename = '<input>', resolve = null, data = [], all = false, limits = {}, proof = false, context = null } = {}) {
|
|
678
|
+
const { program, prefixes, warnings, context: execution } = compileSrl(text, { base, filename, resolve, data, context });
|
|
622
679
|
const result = run(loadText(program, 'compiled.js'), { ...SRL_LIMITS, ...limits, proof });
|
|
623
|
-
return { quads: srlQuads(program, result.answers, { all }), program, prefixes, warnings, result };
|
|
680
|
+
return { quads: srlQuads(program, result.answers, { all }), program, prefixes, warnings, result, context: execution };
|
|
624
681
|
}
|
|
625
682
|
|
|
626
683
|
// The inference graph of a run's answers, as quads in the default graph:
|
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.5.
|
|
2
|
+
export const VERSION = '0.5.13';
|