eyemind 0.5.0 → 0.5.2

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "eyemind",
3
- "version": "0.5.0",
3
+ "version": "0.5.2",
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/cli.js CHANGED
@@ -1,12 +1,14 @@
1
1
  // The eyemind command line.
2
2
  import { run, unusedClauses } from './engine.js';
3
- import { loadSources } from './lang.js';
3
+ import { OUTPUT_FORMATS, defaultFormat, loadInputs, writeConclusions } from './formats.js';
4
4
  import { checkProof, checkReport, publicReport } from './proof.js';
5
5
  import { EyemindError } from './terms.js';
6
6
  import { VERSION } from './version.js';
7
7
 
8
8
  export const HELP = `Usage: eyemind [OPTION ...] [FILE ...]
9
- Programs are JavaScript; forward rules run to a fixpoint.
9
+ Programs are JavaScript; forward rules run to a fixpoint. Other files are read
10
+ by their extension: .ttl, .trig, .nt and .nq as RDF 1.2 data, .n3 as Notation3
11
+ and .srl as a SPARQL 1.2 RL rule set, both compiled to an eyemind program.
10
12
  -p, --proof Print the claims with clause(...) and step(...) records
11
13
  -c, --prove-and-check Generate a proof and check it against the input program
12
14
  --check-proof FILE Print checked answers and a proof check report (- for stdin)
@@ -19,6 +21,12 @@ Programs are JavaScript; forward rules run to a fixpoint.
19
21
  --max-depth N Bound backward recursion (default 1000000)
20
22
  --max-iterations N Bound forward rounds per stratum (default 1000)
21
23
  --max-inferences N Bound reasoning work (default 1000000)
24
+ --to FORMAT Write the conclusions as turtle, trig, n-triples,
25
+ n-quads, n3 or eyemind (default: n3 for N3, turtle
26
+ for a rule set, eyemind otherwise)
27
+ --all With RDF output, write the given data too
28
+ --program Print the program the inputs compile to
29
+ --base IRI Resolve relative IRIs of the inputs against IRI
22
30
  -v, --version Print the version
23
31
  -h, --help Print this help
24
32
  Source defaults to stdin; multiple files form one program.
@@ -26,6 +34,8 @@ Exit codes: 0 success, 1 error, 2 invalid proof, 65 contradiction.
26
34
  `;
27
35
 
28
36
  const LIMITS = { '--max-depth': 'maxDepth', '--max-iterations': 'maxIterations', '--max-inferences': 'maxInferences' };
37
+ // N3 and SPARQL 1.2 RL programs run longer than eyemind's defaults allow.
38
+ const COMPILED_LIMITS = { maxDepth: 1000000, maxIterations: 100000, maxInferences: 1000000000 };
29
39
 
30
40
  class UsageError extends Error {}
31
41
 
@@ -48,6 +58,10 @@ export function main(argv, io) {
48
58
  let asJson = false;
49
59
  let unused = false;
50
60
  let proveAndCheck = false;
61
+ let format = null;
62
+ let all = false;
63
+ let printProgram = false;
64
+ let base = null;
51
65
  for (let i = 0; i < argv.length; i++) {
52
66
  const arg = argv[i];
53
67
  if (arg === '--help' || arg === '-h') {
@@ -70,7 +84,11 @@ export function main(argv, io) {
70
84
  asJson = true;
71
85
  } else if (arg === '--unused') {
72
86
  unused = true;
73
- } else if (arg === '--check-proof' || arg === '--goal' || Object.hasOwn(LIMITS, arg)) {
87
+ } else if (arg === '--all') {
88
+ all = true;
89
+ } else if (arg === '--program') {
90
+ printProgram = true;
91
+ } else if (arg === '--check-proof' || arg === '--goal' || arg === '--to' || arg === '--base' || Object.hasOwn(LIMITS, arg)) {
74
92
  i++;
75
93
  if (i >= argv.length) throw new UsageError(`${arg} needs a value`);
76
94
  const value = argv[i];
@@ -82,6 +100,11 @@ export function main(argv, io) {
82
100
  }
83
101
  if (arg === '--check-proof') {
84
102
  proofFile = value;
103
+ } else if (arg === '--to') {
104
+ if (!OUTPUT_FORMATS.includes(value)) throw new UsageError(`--to takes one of ${OUTPUT_FORMATS.join(', ')}, not ${value}`);
105
+ format = value;
106
+ } else if (arg === '--base') {
107
+ base = value;
85
108
  } else if (arg === '--goal') {
86
109
  goals.push(value);
87
110
  } else {
@@ -109,7 +132,14 @@ export function main(argv, io) {
109
132
  }
110
133
  if (!files.length) files.push('-');
111
134
  if (files.filter((file) => file === '-').length > 1) throw new UsageError('stdin can only be read once');
112
- const program = loadSources(files.map((file) => [readSource(file, io), file === '-' ? '<stdin>' : file]), io);
135
+ const loaded = loadInputs(files.map((file) => [readSource(file, io), file === '-' ? '<stdin>' : file]), io, { base });
136
+ const program = loaded.program;
137
+ if (printProgram) {
138
+ stdout(loaded.text);
139
+ return 0;
140
+ }
141
+ // A compiled program has the larger bounds, unless they are given.
142
+ if (loaded.kind !== 'js') for (const [name, value] of Object.entries(COMPILED_LIMITS)) options[name] ??= value;
113
143
  if (proofFile !== null) {
114
144
  const document = readSource(proofFile, io);
115
145
  const report = checkProof(program, document, { goals, allowTrusted: !strictProof });
@@ -130,7 +160,9 @@ export function main(argv, io) {
130
160
  if (stats) stderr(`${JSON.stringify(result.stats)}\n`);
131
161
  return report.valid ? result.haltCode || 0 : 2;
132
162
  }
133
- stdout(result.stdout);
163
+ // Answers to goals are eyemind terms unless an output format is asked.
164
+ const written = options.proof ? null : writeConclusions(loaded, result, { format: format ?? (goals.length ? 'eyemind' : defaultFormat(loaded.kind)), all });
165
+ stdout(written ?? result.stdout);
134
166
  if (stats) stderr(`${JSON.stringify(result.stats)}\n`);
135
167
  return result.haltCode || 0;
136
168
  } catch (error) {
package/src/formats.js ADDED
@@ -0,0 +1,149 @@
1
+ // The inputs of a run in other formats than JavaScript, and its output as
2
+ // RDF or N3.
3
+ //
4
+ // A file's extension says what it holds:
5
+ //
6
+ // .js and standard input an eyemind program
7
+ // .ttl .trig .nt .nq RDF 1.2 data: with a program, rdf(S, P, O, G)
8
+ // facts; with an N3 document, its triples; with a
9
+ // rule set, its base graph
10
+ // .n3 Notation3, compiled to an eyemind program
11
+ // .srl a SPARQL 1.2 RL rule set, compiled to one
12
+ //
13
+ // The compiled program is ordinary eyemind: proofs, checking and --unused
14
+ // apply to it, and compiling is deterministic, so a saved proof checks later
15
+ // against the same inputs.
16
+ import { EyemindError, Struct } from './terms.js';
17
+ import { loadSources } from './lang.js';
18
+ import { readTerms } from './reader.js';
19
+ import { DEFAULT_GRAPH, parseRdf, rdfDocument, rdfFormat, writeRdf } from './rdf.js';
20
+ import { answersToN3, compileSources } from './n3.js';
21
+ import { compileSrl, srlQuads } from './srl.js';
22
+ import { write } from './writer.js';
23
+
24
+ export const OUTPUT_FORMATS = ['eyemind', 'turtle', 'trig', 'n-triples', 'n-quads', 'n3'];
25
+
26
+ // What a file holds: 'js', 'rdf', 'n3' or 'srl'.
27
+ export function inputKind(name) {
28
+ if (rdfFormat(name)) return 'rdf';
29
+ if (/\.n3$/i.test(name)) return 'n3';
30
+ if (/\.srl$/i.test(name)) return 'srl';
31
+ return 'js';
32
+ }
33
+
34
+ // Load inputs, given as [text, name] pairs, as one program. io may supply
35
+ // readFile, for the documents N3 and IMPORTS name, and fileIri(name), the
36
+ // base IRI of a file. Returns { kind, program, text, prefixes, compiled }:
37
+ // kind is 'js', 'n3' or 'srl', text the compiled program for N3 and SRL,
38
+ // and compiled what writing the conclusions needs.
39
+ export function loadInputs(inputs, io = null, options = {}) {
40
+ try {
41
+ return load(inputs, io, options);
42
+ } catch (error) {
43
+ // The N3 and SPARQL 1.2 RL readers report errors of their own kinds.
44
+ if (error instanceof EyemindError || !(error instanceof Error) || error instanceof TypeError || error instanceof ReferenceError) throw error;
45
+ throw new EyemindError(error.message);
46
+ }
47
+ }
48
+
49
+ function load(inputs, io, { base = null }) {
50
+ const kinds = inputs.map(([, name]) => inputKind(name));
51
+ const baseOf = (name) => base ?? io?.fileIri?.(name) ?? null;
52
+ const rdf = (text, name, k) => parseRdf(text, { format: rdfFormat(name), base: baseOf(name), scope: scopeOf(inputs, name, k) });
53
+ if (kinds.includes('srl')) {
54
+ const others = kinds.filter((k) => k !== 'srl' && k !== 'rdf');
55
+ if (kinds.filter((k) => k === 'srl').length > 1 || others.length) {
56
+ throw new EyemindError('a SPARQL 1.2 RL run takes one .srl rule set, and RDF data for its base graph');
57
+ }
58
+ const [text, name] = inputs[kinds.indexOf('srl')];
59
+ const data = inputs.flatMap(([t, n], k) => (kinds[k] === 'rdf' ? rdf(t, n, k).quads : []));
60
+ const compiled = compileSrl(text, { base: baseOf(name), filename: name, resolve: importResolver(io), data });
61
+ for (const warning of compiled.warnings) io?.stderr?.(`eyemind: warning: ${warning}\n`);
62
+ return { kind: 'srl', program: loadSources([[compiled.program, name]], io), text: compiled.program, prefixes: compiled.prefixes, compiled };
63
+ }
64
+ if (kinds.includes('n3')) {
65
+ if (kinds.includes('js')) throw new EyemindError('an N3 run takes .n3 documents and RDF data, not JavaScript programs');
66
+ const sources = inputs.map(([t, n], k) => (kinds[k] === 'rdf' ? rdf(t, n, k) : [t, n]));
67
+ const compiled = compileSources(sources, { base: base ?? '', baseOf: (n) => baseOf(n) ?? '', readFile: io?.readFile ?? null,
68
+ source: inputs.map(([, n]) => n).join(', ') });
69
+ return { kind: 'n3', program: loadSources([[compiled.program, inputs[kinds.indexOf('n3')][1]]], io), text: compiled.program, prefixes: compiled.doc.prefixes, compiled };
70
+ }
71
+ // RDF data joins a program as rdf/4 facts, read without running anything.
72
+ const prefixes = {};
73
+ const sources = inputs.map(([t, n], k) => {
74
+ if (kinds[k] !== 'rdf') return [t, n];
75
+ const parsed = rdf(t, n, k);
76
+ Object.assign(prefixes, parsed.prefixes);
77
+ return [`facts_from({ text: ${JSON.stringify(rdfDocument(parsed.quads))} })\n`, n];
78
+ });
79
+ const text = sources.map(([t]) => t).join('\n');
80
+ return { kind: 'js', program: loadSources(sources, io), text, prefixes, compiled: null };
81
+ }
82
+
83
+ // A blank-node scope per data file: its name, numbered when names repeat.
84
+ function scopeOf(inputs, name, k) {
85
+ const base = String(name).replace(/^.*[\\/]/, '');
86
+ const same = inputs.filter(([, n]) => String(n).replace(/^.*[\\/]/, '') === base);
87
+ return same.length > 1 ? `${base}#${inputs.slice(0, k).filter(([, n]) => String(n).replace(/^.*[\\/]/, '') === base).length + 1}` : base;
88
+ }
89
+
90
+ // IMPORTS of local files, read by the host.
91
+ function importResolver(io) {
92
+ if (!io?.readFile) return null;
93
+ return (target) => {
94
+ if (!target.startsWith('file:')) return null;
95
+ try {
96
+ return io.readFile(decodeURIComponent(new URL(target).pathname));
97
+ } catch {
98
+ return null;
99
+ }
100
+ };
101
+ }
102
+
103
+ // The default output format of a run: N3 for N3, Turtle for SRL, and
104
+ // eyemind's own text for a program.
105
+ export const defaultFormat = (kind) => ({ n3: 'n3', srl: 'turtle' })[kind] ?? 'eyemind';
106
+
107
+ // The conclusions of a run in an output format; null for eyemind's own text.
108
+ // all also writes the given data. Throws when a conclusion is no triple.
109
+ export function writeConclusions(loaded, result, { format, all = false } = {}) {
110
+ if (format === 'eyemind') return null;
111
+ const answers = result.answers;
112
+ if (format === 'n3') {
113
+ if (loaded.kind !== 'n3') throw new EyemindError('--to n3 writes the conclusions of an N3 run');
114
+ return answersToN3(loaded.compiled.doc, answers, { mode: all ? 'all' : 'new' }).n3;
115
+ }
116
+ let quads;
117
+ if (loaded.kind === 'srl') quads = srlQuads(loaded.text, answers, { all });
118
+ else quads = conclusionQuads(answers, all ? loaded.text : null);
119
+ return writeRdf(quads, { format, prefixes: loaded.kind === 'n3' ? Object.fromEntries(loaded.prefixes) : loaded.prefixes });
120
+ }
121
+
122
+ // Conclusions that are triples, rdf/3 or result/3, or quads, rdf/4 or
123
+ // result_rdf/4, as quads; given, the program's own rdf facts come first.
124
+ function conclusionQuads(answers, given) {
125
+ const quads = [];
126
+ const seen = new Set();
127
+ const add = (t) => {
128
+ const quad = t.args.length === 3 ? [...t.args, DEFAULT_GRAPH] : t.args;
129
+ const key = quad.map((x) => (x === DEFAULT_GRAPH ? x : write(x))).join(' ');
130
+ if (!seen.has(key)) {
131
+ seen.add(key);
132
+ quads.push(quad);
133
+ }
134
+ };
135
+ if (given) {
136
+ for (const match of given.matchAll(/^facts_from\(\{ text: (".*") \}\)$/gm)) {
137
+ for (const [t] of readTerms(JSON.parse(match[1]))) add(t);
138
+ }
139
+ }
140
+ for (const answer of answers) {
141
+ const [[t]] = readTerms(answer);
142
+ if (t === 'false') continue;
143
+ const triple = t instanceof Struct && ['rdf', 'result', 'inf'].includes(t.name) && t.args.length === 3;
144
+ const quad = t instanceof Struct && ['rdf', 'result_rdf'].includes(t.name) && t.args.length === 4;
145
+ if (!triple && !quad) throw new EyemindError(`${answer} is no triple; write rdf(S, P, O) or rdf(S, P, O, G) conclusions, or leave out --to`);
146
+ add(t);
147
+ }
148
+ return quads;
149
+ }