eyemind 0.5.12 → 0.5.14

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 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 126 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).
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 134 runnable programs, each with a card deck and saved conclusions, proofs and check reports. The conformance suite has 1363 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
 
@@ -120,6 +120,7 @@ Now add `fact(parent('carol', 'dave'))`, or remove a rule, and watch which answe
120
120
  | `fact(...Heads)` | Each head holds. |
121
121
  | `implies(Premise, Conclusion)` | A forward rule: whenever `Premise` holds, conclude `Conclusion`. |
122
122
  | `implied_by(Conclusion, Premise)` | A backward rule: `Conclusion` holds when `Premise` does, decided when a goal asks. |
123
+ | `restricted(Premise, Conclusion)` | A forward rule whose new values are made only where no known ones satisfy `Conclusion`. |
123
124
  | `query(...Body)` | Publish every instance of `Body` that holds. |
124
125
  | `contradiction(...Body)` | Stop with exit code 65 when `Body` holds: an integrity constraint. |
125
126
  | `facts_from(path)`, `facts_from({text})` | State every expression of a document as a fact, without running it. |
@@ -204,7 +205,44 @@ eyemind --program examples/family.n3 > /tmp/family.js # the compiled program,
204
205
  eyemind -c examples/family.n3 # a proof of it, checked
205
206
  ```
206
207
 
207
- Triples are `rdf(Subject, Predicate, Object)`, with IRIs, blank nodes and literals written as in the RDF table above. N3 integers and decimals become eyemind numbers; float and double literals retain their RDF datatype, including numbers written with an exponent. Decimals use binary64 storage; `math:sum` adds their canonical decimal values before rounding its result. `=>` becomes `implies`, `<=` becomes `implied_by`, `{ ... } => false` becomes `contradiction`, and scoped negation and collection become `not` and `findall`, so an N3 run has a proof that eyemind checks like any other. Derived rules can trigger inference fuses too.
208
+ Triples are `rdf(Subject, Predicate, Object)`, with IRIs, blank nodes and literals written as in the RDF table above. N3 integers and decimals become eyemind numbers; float and double literals retain their RDF datatype, including numbers written with an exponent. Decimals use binary64 storage; `math:sum` adds their canonical decimal values before rounding its result. `=>` becomes `implies`, or `restricted` when the conclusion has blank nodes of its own, `<=` becomes `implied_by`, `{ ... } => false` becomes `contradiction`, and scoped negation and collection become `not` and `findall`, so an N3 run has a proof that eyemind checks like any other. Derived rules can trigger inference fuses too.
209
+
210
+ Quoted formulas are graph terms, read as in D. Arndt and P.-A. Champin,
211
+ ["Notation3: Graph Terms for RDF"](https://arxiv.org/abs/2610.31266).
212
+ `@forAll` and `@forSome` declare IRIs as universal and existential variables
213
+ of the formula they open, before its first statement and with `@forAll`
214
+ first. A declaration reaches the formulas inside it unless one declares the
215
+ same IRI again. A `?x` belongs to the whole document, and a blank node to the
216
+ innermost formula that holds it. So `@forAll :x . :x :p :o .` and
217
+ `?x :says { ?x :is :wise } .` are facts about everything. A document
218
+ existential is one individual, in rules and quoted formulas alike. Within the
219
+ scope of universals it becomes a witness of them, so
220
+ `?x :loves _:y .` gives each individual its own beloved. A rule whose
221
+ conclusion has existentials is restricted: a firing makes Skolem witnesses
222
+ only where no known individuals satisfy the conclusion. A
223
+ conclusion that declares universals of its own becomes backward rules, which
224
+ state it for every individual, and `{ ... } => ?g .` asserts the formula bound
225
+ to `?g`.
226
+
227
+ A graph term is opaque: `owl:sameAs` does not rewrite it. It is closed and
228
+ compared as a set, up to a one-to-one renaming of its own variables, each
229
+ kind to its own kind. A rule's graph pattern therefore matches only formulas
230
+ with the same triples, and its own blank nodes match only the formula's own
231
+ blank nodes. A rule variable never stands for one of them, but it can stand
232
+ for a quoted universal, as rules stated as data quote their variables.
233
+ `log:includes` never instantiates the universals of its subject. Matching in
234
+ nested graph terms below the first level is by unification, so it depends on
235
+ the order of their triples. See
236
+ [universal instances](https://eyereasoner.github.io/eyemind/examples/deck/universal-instances),
237
+ [a shared existential](https://eyereasoner.github.io/eyemind/examples/deck/shared-existential),
238
+ [an existential rule](https://eyereasoner.github.io/eyemind/examples/deck/explicit-existential-rule),
239
+ [quantifier scopes](https://eyereasoner.github.io/eyemind/examples/deck/quantifier-scopes) and
240
+ [graph terms](https://eyereasoner.github.io/eyemind/examples/deck/graph-terms).
241
+
242
+ The Notation3 test suite case `static/success-literal-22.n3` expects the
243
+ pattern `{ _:X :B :C }` to match `{ :A :B :C }`. eyemind's scorer checks
244
+ instead that the conclusion is absent, because a quoted blank node is the
245
+ formula's own variable.
208
246
 
209
247
  N3 has no named-graph syntax. When RDF data joins an N3 run, eyemind represents
210
248
  each named graph as a quoted formula through `graph:content`, where `graph:`
@@ -309,7 +347,36 @@ eyemind --all rules.srl facts.ttl # the base graph too
309
347
  eyemind -c rules.srl facts.ttl # a proof of it, checked
310
348
  ```
311
349
 
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. `NOW`, `UUID` and `STRUUID` are not supported, as eyemind has no clock or randomness; decimals and doubles are computed as binary64 floats.
350
+ 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.
351
+
352
+ SRL integers and decimals use exact integer arithmetic. Decimal addition,
353
+ subtraction, multiplication, comparison, rounding and terminating division
354
+ preserve decimal values, including values beyond the exact integer range of
355
+ a double: `0.1 + 0.2` is `0.3`. Nonterminating division retains at least 34
356
+ significant digits and rounds to nearest with ties to even. Floats and doubles
357
+ use binary64 arithmetic: `0.1e0 + 0.2e0` is
358
+ `"0.30000000000000004"^^xsd:double`. Floating-point overflow and division by
359
+ zero follow IEEE-754, including `INF`, `-INF`, `NaN` and signed zero; decimal
360
+ division by zero is an expression error. Mixed numeric expressions use
361
+ SPARQL type promotion. The [exact decimals example](https://eyereasoner.github.io/eyemind/examples/deck/exact-decimals)
362
+ shows both arithmetic models.
363
+
364
+ `NOW()` returns one UTC `xsd:dateTime` throughout a rule set evaluation.
365
+ `UUID()` produces a `urn:uuid:` IRI and `STRUUID()` a UUID string, distinct
366
+ for each expression occurrence and incoming solution. Compilation captures
367
+ the clock and a fresh random seed once; UUIDs are derived from that seed,
368
+ the rule, the expression and the solution, so later reasoning rounds keep
369
+ the same identifiers. A new compilation captures a new execution context.
370
+ The compiled program states this context as one `srl_execution` fact.
371
+ Saved proofs retain it, and `--check-proof` restores only that validated
372
+ context before recompiling the source. Checking proves consequences of the
373
+ recorded context; it does not attest the wall-clock time or the randomness
374
+ of the seed. Library calls to `compileSrl` and `reasonSrl` accept
375
+ `context: { now, seed }`, with an ISO UTC timestamp including milliseconds
376
+ and 64 lowercase hexadecimal seed digits, to reproduce an execution.
377
+ The [execution identifiers example](https://eyereasoner.github.io/eyemind/examples/deck/execution-identifiers)
378
+ has a fixed context in the example manifest for its saved artifacts;
379
+ ordinary command-line and playground runs capture fresh values.
313
380
 
314
381
  The [example catalog](https://eyereasoner.github.io/eyemind/examples/) includes
315
382
  SRL programs for deployment dependencies, route distances, ancestry, inventory,
@@ -322,10 +389,10 @@ The statement chooses the direction:
322
389
 
323
390
  | Strategy | Stated with | How it works |
324
391
  | --- | --- | --- |
325
- | **Forward** | `implies`, `query`, `contradiction` | From the facts, round after round, until a round adds nothing new. |
392
+ | **Forward** | `implies`, `restricted`, `query`, `contradiction` | From the facts, round after round, until a round adds nothing new. |
326
393
  | **Backward** | `implied_by`, `fact` | When a goal asks: depth-first, left to right, in the order the clauses are written. |
327
394
 
328
- Forward rules suit closures and classifications: `implies([path(X, Y), edge(Y, Z)], path(X, Z))` terminates on a cyclic graph. Backward rules suit computations driven by their inputs, such as arithmetic recursion and list processing. Backward chaining keeps no table of answers, so a backward rule that calls itself with the same goal runs until a bound stops it; such recursion belongs in a forward rule.
395
+ Forward rules suit closures and classifications: `implies([path(X, Y), edge(Y, Z)], path(X, Z))` terminates on a cyclic graph. A variable only a forward rule's conclusion mentions gets a fresh value, a Skolem term, for each firing. `restricted` makes one only where none is known: `restricted(human(X), [father(X, F), man(F)])` gives no new father to a human whose known father is a man. Its other rules run first in each stratum, and its proof shows each new value is needed, as the restricted chase of N. Küchenmeister, A. Ivliev, D. Arndt and M. Krötzsch, ["Stratified Negation in RDF Rules"](https://arxiv.org/abs/2607.28778), requires. Which firings it makes can depend on the order of rule applications, so call fidelity stays an obligation. Backward rules suit computations driven by their inputs, such as arithmetic recursion and list processing. Backward chaining keeps no table of answers, so a backward rule that calls itself with the same goal runs until a bound stops it; such recursion belongs in a forward rule.
329
396
 
330
397
  The two work together: a forward rule's premise can call a backward definition, and a backward goal sees the facts forward rules derived. Forward rules run stratum by stratum, so a negation or collection waits until everything it inspects is final. `--max-depth`, `--max-iterations` and `--max-inferences` bound a run, and exceeding one is an error, never a partial answer. [SPEC §8](https://eyereasoner.github.io/eyemind/SPEC#8-evaluation-and-conclusions) defines the details.
331
398
 
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.12
5
+ Version: eyemind 0.5.14
6
6
  ```
7
7
 
8
8
  This document specifies the syntax and meaning of eyemind programs and data
@@ -413,12 +413,13 @@ The basic statement forms are:
413
413
  | `fact(T)` | State one fact with head `T` and no body. |
414
414
  | `implies(Body, Head)` | State a forward rule. `Body` is a goal or a non-empty array of goals; `Head` is one head or a non-empty array of heads. |
415
415
  | `implied_by(Head, Body)` | State a backward rule with one head. `Body` is a goal or a non-empty array of goals. |
416
+ | `restricted(Body, Head)` | State a restricted forward rule: as `implies`, but a firing whose heads some known values already satisfy is not applied ([Section 7.2](#72-variables-and-witnesses)). |
416
417
  | `query(G)` | Report the successful instances of `G`. An array denotes one conjunction. |
417
418
  | `contradiction(G)` | Halt with conclusion `'false'` when `G` succeeds. An array denotes one conjunction. |
418
419
  | `facts_from(Path)` | Read a document from a path and state one fact per expression. |
419
420
  | `facts_from({text: Text})` | Read a document from a string and state one fact per expression. |
420
421
 
421
- `implies` and `implied_by` require exactly two arguments. The variadic forms
422
+ `implies`, `implied_by` and `restricted` require exactly two arguments. The variadic forms
422
423
  of `fact`, `query` and `contradiction` are also defined:
423
424
 
424
425
  ```js
@@ -578,6 +579,7 @@ primitive called outside its patterns raises an error.
578
579
  | `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
580
  | `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
581
  | `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. |
582
+ | `float64` | `float64(+Op, +A, +B, ?R)` | Explicit IEEE-754 binary64 computation, including exceptional values represented as atoms, as defined below. |
581
583
  | `regex_match` | `regex_match(+P, +T)` | Some part of the atom `T` matches the regular expression `P`. |
582
584
  | `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
585
  | `regex_replace` | `regex_replace(+P, +T, +R, ?U)` | `U` is `T` with every match of `P` replaced by `R`. |
@@ -585,6 +587,25 @@ primitive called outside its patterns raises an error.
585
587
  A character is a Unicode code point. Every primitive except `atom_concat`
586
588
  and `regex_find` has at most one solution.
587
589
 
590
+ `float64/4` converts numeric operands explicitly to binary64, rounding an
591
+ integer to nearest with ties to even. Exceptional values are the atoms
592
+ `'INF'`, `'-INF'` and `'NaN'`; they are not additional core numbers.
593
+ `Op` is `'add'`, `'sub'`, `'mul'` or `'div'`, with IEEE-754 results,
594
+ including overflow, underflow and division by zero. Signed zero is retained.
595
+ For `'compare'`, `R` is `'<'`, `'='`, `'>'`, or `'unordered'` if either
596
+ operand is NaN. Operations `'convert'`, `'neg'`, `'abs'`, `'ceil'`, `'floor'`
597
+ and `'round'` use only `A`; `'round'` rounds halves toward positive infinity
598
+ and retains negative zero. `'trunc'` returns an exact integer for a finite
599
+ converted `A` and fails otherwise. The unused `B` is still an input.
600
+
601
+ For `'parse'`, `A` is an atom with an XSD float/double lexical form: an
602
+ optionally signed decimal with an optional exponent, `'INF'`, `'+INF'`,
603
+ `'-INF'` or `'NaN'`, optionally surrounded by XML whitespace. Parsing rounds
604
+ once to binary64 and allows overflow and underflow. An invalid lexical
605
+ form or operand fails; another `Op` raises an error. Finite numeric results
606
+ are floats; exceptional results are the atoms above. C5 re-decides these
607
+ operations, including signed zeros and exceptional results.
608
+
588
609
  A regular expression `P` is an atom read as an ECMAScript pattern
589
610
  (ECMA-262, the `RegExp` pattern grammar and matching semantics) with only the
590
611
  `u` flag, so it matches by code point: `.` matches `'\u{1F600}'` as one
@@ -707,6 +728,11 @@ A program MUST be rejected when:
707
728
  Because dependencies compare whole terms, two relations sharing a predicate
708
729
  name MAY have different ranks.
709
730
 
731
+ The guard of a restricted rule ([Section 7.2](#72-variables-and-witnesses)) is a body goal whose
732
+ dependencies are open, though it is a negation: the rule ranks at least as
733
+ high as every clause that derives its heads, itself included, without a
734
+ closed dependency on itself.
735
+
710
736
  ### 6.2 Inline rule templates
711
737
 
712
738
  Nested `implies(Body, Head)` and `implied_by(Head, Body)` calls construct rule
@@ -856,6 +882,35 @@ unless it is a scoped inspection variable ([Section 6.3](#63-source-rule-inspect
856
882
  including captured template values. Body variables absent from that context
857
883
  do not distinguish witnesses; shared head variables share a witness.
858
884
 
885
+ A restricted rule, `restricted(Body, Head)`, with head-only variables
886
+ `W1, ..., Wk` has one more body goal after `Body`, its **guard**:
887
+
888
+ ```js
889
+ not([H1', ..., Hm', not_unify([_A1, ..., _Ak], [S1, ..., Sk])])
890
+ ```
891
+
892
+ `H1', ..., Hm'` are its heads with each `Wi` replaced by a distinct
893
+ anonymous variable `_Ai`, numbered `_0`, `_1`, ... as the first such names
894
+ the clause does not use; `Si` is `skolem(N, 'Wi', Frontier)`, the witness a
895
+ firing of clause `N` gives `Wi` ([Section 8.2](#82-forward-evaluation-and-witnesses)), where `Frontier` is the list of
896
+ the heads' other variables in order of first occurrence. The guard holds when
897
+ nothing but the firing's own witnesses satisfies its heads. Before a
898
+ firing, that is when no known values satisfy them, so a satisfied rule does
899
+ not invent new values, as the restricted chase does; after it, that is when
900
+ the firing's witnesses are needed, which the search certificate shows like
901
+ any negation. A restricted rule without head-only variables has no guard and
902
+ behaves as `implies`. For example:
903
+
904
+ ```js
905
+ fact(human('jo'), father('jo', 'bob'))
906
+ restricted(human(X), [father(X, F), man(F)])
907
+ implies(father(X, Y), man(Y))
908
+ ```
909
+
910
+ concludes `man('bob')` and invents no father for `'jo'`, since `'bob'`
911
+ already satisfies the heads once the third rule has run. A restricted
912
+ rule's display omits its guard ([Section 10.2](#102-clause-displays)).
913
+
859
914
  This gives the specified Skolemized reading of existential conclusions.
860
915
  The original existential rule need not have a least model over its original
861
916
  vocabulary. A witness is an ordinary compound in subsequent reasoning; it
@@ -987,6 +1042,14 @@ and `p(2)` publishes `a(1)`, `b(1)`, `a(2)`, `b(2)`. For each head:
987
1042
  When the run asks its own goals ([Section 8.4](#84-external-goals)), rules whose heads are all
988
1043
  `'true'` are not run.
989
1044
 
1045
+ A stratum with restricted rules alternates two kinds of round. Its other
1046
+ rules run in rounds as above; a round of its restricted rules, in clause
1047
+ order, follows only a round of the other rules that adds nothing, and is
1048
+ followed by rounds of the other rules again when it adds something. The
1049
+ stratum ends with a round of its restricted rules that adds nothing. The
1050
+ other rules of a stratum thus run before its restricted rules, whose guards
1051
+ see what they derive.
1052
+
990
1053
  For a generator, use its scope projection ([Section 6.2](#62-inline-rule-templates)) as its head when
991
1054
  constructing witnesses. For an appended forward clause of [Section 6.2](#62-inline-rule-templates),
992
1055
  prepend one element to
@@ -1239,8 +1302,9 @@ A checker MUST treat every statement that is neither `clause/2`, `step/4`,
1239
1302
  ### 10.2 Clause displays
1240
1303
 
1241
1304
  `Display` shows clause `N` in normalized statement form: `fact(Head)`,
1242
- `implies(Body, Head)`, `implied_by(Head, Body)`, `query(G1, ...)` or
1243
- `contradiction(G1, ...)`, where `Body` is the clause's one body goal, or the
1305
+ `implies(Body, Head)`, `restricted(Body, Head)`, `implied_by(Head, Body)`,
1306
+ `query(G1, ...)` or `contradiction(G1, ...)`, where `Body` is the clause's
1307
+ one body goal without a restricted rule's guard, or the
1244
1308
  array of its body goals when it has several, `Head` likewise the head or the
1245
1309
  array of heads, and `G1, ...` are the body goals themselves. Displays are not
1246
1310
  authority: a checker MUST compare each with the program it checks against.
@@ -1964,6 +2028,9 @@ in that closure. To use a listing for C10:
1964
2028
  - Every backward head variable MUST be grounded by its body.
1965
2029
  - Every forward head variable MUST either be grounded by its body or be a
1966
2030
  head-only witness checked by C8.
2031
+ - A restricted rule's guard is a negation, so a closure with a restricted
2032
+ rule that has head-only variables is not supported: which firings a
2033
+ restricted rule makes can depend on the order of rule applications.
1967
2034
 
1968
2035
  Supported facts and closed listings then establish the least ground
1969
2036
  positive closure. More general forward execution requires publication
@@ -2192,10 +2259,23 @@ or `pe:called` and an ordered `pe:answers` collection. Clause numbers name
2192
2259
  the compiled program's clauses, whose authority is still the source input.
2193
2260
  SRL proofs contain only `DATA` and declarations, never rules or imports.
2194
2261
 
2262
+ When an SRL rule set uses `NOW`, `UUID` or `STRUUID`, its compiled program
2263
+ includes one ground `srl_execution(Now, Seed)` fact. `Now` is an ISO UTC
2264
+ timestamp with milliseconds and `Seed` contains 64 lowercase hexadecimal
2265
+ digits. The compiler captures these external inputs once per compilation;
2266
+ they remain fixed throughout evaluation. To check a saved SRL proof, the
2267
+ format loader may recover this fact from its clause records, validate its
2268
+ two fields, and recompile the source with that execution context. All other
2269
+ clauses still come from the source, and all displays undergo C1–C10 as
2270
+ usual. This establishes consequences of the recorded context, without
2271
+ certifying a clock observation or the entropy of the seed.
2272
+
2195
2273
  The reader decodes every record, verifies all displays and properties against
2196
2274
  those records, and applies the unchanged checks of
2197
2275
  [Section 11](#11-proof-checking) to the decoded
2198
2276
  certificate. A missing, extra, duplicate or inconsistent property fails C3.
2277
+ Numeric literal displays retain their decimal digits during this comparison;
2278
+ distinct decimal literals MUST NOT agree merely by rounding to binary64.
2199
2279
  Prefix aliases and reordering top-level properties are accepted, as is
2200
2280
  consistent blank-node renaming; the order of collections and formula triples
2201
2281
  is retained. Displayed claims cannot replace encoded claims, and neither
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "eyemind",
3
- "version": "0.5.12",
3
+ "version": "0.5.14",
4
4
  "description": "A dependency-free JavaScript rule language with forward and backward reasoning and checkable proofs.",
5
5
  "type": "module",
6
6
  "main": "./src/index.js",
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 loaded = loadInputs(files.map((file) => [readSource(file, io), file === '-' ? '<stdin>' : file]), io, { base, messageInputs: io.messageInputs });
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/engine.js CHANGED
@@ -818,7 +818,9 @@ export class Solver {
818
818
 
819
819
  // Run the forward rules to a fixpoint, one stratum after another. A rule
820
820
  // whose heads are all 'true' only publishes output; when the caller asks its
821
- // own question that output is discarded, so the rule is skipped.
821
+ // own question that output is discarded, so the rule is skipped. In a
822
+ // stratum, restricted rules run only in a round where the other rules
823
+ // derive nothing, so their guards see what those rules derive.
822
824
  forward(reporting = true) {
823
825
  const layers = new Map();
824
826
  for (const clause of this.program.forward) {
@@ -828,10 +830,17 @@ export class Solver {
828
830
  }
829
831
  const maxIterations = this.options.maxIterations || 1000;
830
832
  for (const rank of [...layers.keys()].sort((a, b) => a - b)) {
831
- const rules = layers.get(rank);
833
+ const all = layers.get(rank);
834
+ const restricted = all.filter((clause) => clause.restricted);
835
+ const ordinary = restricted.length ? all.filter((clause) => !clause.restricted) : all;
832
836
  let changed = true;
833
837
  let rounds = 0;
834
- while (changed) {
838
+ let lean = false;
839
+ while (changed || (!lean && restricted.length)) {
840
+ // After a round of the other rules that derives nothing, a round of
841
+ // the restricted ones; after one of those that derives nothing, done.
842
+ lean = !changed && restricted.length > 0;
843
+ const rules = lean ? restricted : ordinary;
835
844
  rounds++;
836
845
  if (rounds > maxIterations) throw new EyemindError('forward reasoning exceeded max_iterations');
837
846
  this.stats.rounds++;
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, and compiling is deterministic, so a saved proof checks later
16
- // against the same inputs.
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/lang.js CHANGED
@@ -193,13 +193,13 @@ class Builder {
193
193
 
194
194
  rule(name, args) {
195
195
  if (args.length !== 2) throw new EyemindError(`${name} takes 2 arguments, got ${args.length}`);
196
- const forward = name === 'implies';
196
+ const forward = name === 'implies' || name === 'restricted';
197
197
  const head = forward ? goalOf(args[1]) : toTerm(args[0]);
198
198
  const premise = goalOf(args[forward ? 0 : 1]);
199
199
  // Keep the returned value's anonymous variables untouched: each enclosing
200
200
  // clause names its own occurrences, including those inside templates.
201
201
  const value = new Struct(name, forward ? [premise, head] : [normalizeGoal(head), premise]);
202
- const source = this.add(forward ? 'forward' : 'backward', head, [premise]);
202
+ const source = this.add(name === 'restricted' ? 'restricted' : forward ? 'forward' : 'backward', head, [premise]);
203
203
  this.rules.set(value, source);
204
204
  return value;
205
205
  }
@@ -296,6 +296,7 @@ function exportsFor(io) {
296
296
  },
297
297
  implies: (...args) => active().rule('implies', args),
298
298
  implied_by: (...args) => active().rule('implied_by', args),
299
+ restricted: (...args) => active().rule('restricted', args),
299
300
  forward: (...args) => template('forward', args),
300
301
  backward: (...args) => template('backward', args),
301
302
  query: (...body) => builder.add('query', TRUE_ATOM, body.map(goalOf)),
@@ -462,7 +463,7 @@ function lineOffset() {
462
463
 
463
464
  const AT = '__eyemind_at__';
464
465
  const SCOPE = '__eyemind_scope__';
465
- const STATEMENT_NAMES = ['fact', 'implies', 'implied_by', 'query', 'contradiction', 'facts_from'];
466
+ const STATEMENT_NAMES = ['fact', 'implies', 'implied_by', 'restricted', 'query', 'contradiction', 'facts_from'];
466
467
  const STATEMENT_SET = new Set(STATEMENT_NAMES);
467
468
  const IDENTIFIER = /[A-Za-z0-9_$]/;
468
469
  // Words after which a slash starts a regular expression rather than a division.
@@ -181,6 +181,27 @@ implied_by(n3_not_includes(G, F), [is_nonvar(G), is_nonvar(F), findall('found',
181
181
  implied_by(n3_includes_(graph(Ts), graph(Ps)), n3_all_members(Ps, Ts))
182
182
  fact(n3_all_members([], _))
183
183
  implied_by(n3_all_members([P, ...Ps], Ts), [n3_member(P, Ts), n3_all_members(Ps, Ts)])`,
184
+ },
185
+ n3_unquote: {
186
+ needs: ['n3_member'],
187
+ text: `
188
+ // n3_unquote(G): the triples of the formula G hold.
189
+ implies([n3_unquote(graph(Ts)), n3_member(rdf(S, P, O), Ts)], rdf(S, P, O))`,
190
+ },
191
+ n3_graph_match: {
192
+ needs: ['n3_includes', 'n3_sort', 'n3_length'],
193
+ text: `
194
+ // n3_graph_match(G, P, Ls): the formula G holds the triples of the pattern P,
195
+ // as sets. Ls lists P's variables: e(V) its blank nodes and u(V) its
196
+ // universals, matched one to one by the formula's own, and f(V) the rule's
197
+ // variables, which no blank node of the formula can stand for. A rule's
198
+ // variable can stand for a quoted universal, as rules stated as data quote
199
+ // their variables.
200
+ implied_by(n3_graph_match(graph(Ts), graph(Ps), Ls), [n3_all_members(Ps, Ts), n3_all_members(Ts, Ps), n3_locals(Ls, [], _)])
201
+ implied_by(n3_locals([], Vs, Vs), [n3_sort(Vs, S), n3_length(Vs, N), n3_length(S, N)])
202
+ implied_by(n3_locals([e(V), ...R], A, Vs), [is_nonvar(V), unify(V, qbnode(_)), n3_locals(R, [V, ...A], Vs)])
203
+ implied_by(n3_locals([u(V), ...R], A, Vs), [is_nonvar(V), unify(V, qvar(_)), n3_locals(R, [V, ...A], Vs)])
204
+ implied_by(n3_locals([f(V), ...R], A, Vs), [once(or(is_var(V), not_unify(V, qbnode(_)))), n3_locals(R, A, Vs)])`,
184
205
  },
185
206
  n3_round: {
186
207
  text: `