eyemind 0.5.6 → 0.5.8

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.
@@ -0,0 +1,84 @@
1
+ // Node's incremental RDF Message input. The shared CLI supplies the operation
2
+ // to run for each message; this adapter owns only file/HTTP/stdin access.
3
+ import { createReadStream } from 'node:fs';
4
+ import { pathToFileURL } from 'node:url';
5
+ import { resolve } from 'node:path';
6
+ import { rdfMessageFormat } from './formats.js';
7
+ import { replayMessages, RdfMessageReader } from './messages.js';
8
+
9
+ const remote = (name) => /^https?:/.test(name);
10
+
11
+ async function messageFile(name) {
12
+ if (name === '-' || remote(name)) return true;
13
+ if (/\.js$/i.test(name)) return false;
14
+ const probe = new RdfMessageReader({ probe: true });
15
+ for await (const text of createReadStream(name, { encoding: 'utf8' })) {
16
+ probe.write(text);
17
+ if (probe.isLog) return true;
18
+ if (probe.version || probe.hasPayload) return false;
19
+ }
20
+ probe.finish();
21
+ return probe.isLog;
22
+ }
23
+
24
+ async function openSource(name) {
25
+ if (name === '-') {
26
+ process.stdin.setEncoding('utf8');
27
+ return { body: process.stdin, base: null };
28
+ }
29
+ if (!remote(name)) return { body: createReadStream(name, { encoding: 'utf8' }), base: pathToFileURL(resolve(name)).href };
30
+ const controller = new AbortController();
31
+ const timer = setTimeout(() => controller.abort(), 10000);
32
+ let response;
33
+ try {
34
+ response = await fetch(name, { signal: controller.signal });
35
+ } finally {
36
+ clearTimeout(timer);
37
+ }
38
+ if (!response.ok) {
39
+ await response.body?.cancel();
40
+ throw new Error(`${name}: HTTP ${response.status}`);
41
+ }
42
+ const decoder = new TextDecoder();
43
+ async function* text() {
44
+ if (response.body) for await (const bytes of response.body) yield decoder.decode(bytes, { stream: true });
45
+ const tail = decoder.decode();
46
+ if (tail) yield tail;
47
+ }
48
+ const mediaType = response.headers.get('content-type')?.split(';')[0].trim();
49
+ const format = { 'application/n-triples': 'n-triples', 'application/n-quads': 'n-quads',
50
+ 'text/turtle': 'turtle', 'application/trig': 'trig' }[mediaType] ?? rdfMessageFormat(response.url);
51
+ return { body: text(), base: response.url, format };
52
+ }
53
+
54
+ export async function streamMessages(request, io) {
55
+ try {
56
+ const inputs = [];
57
+ const logs = [];
58
+ for (const [index, name] of request.files.entries()) {
59
+ if (await messageFile(name)) logs.push({ name, index });
60
+ else inputs.push([name, io.readFile(name)]);
61
+ }
62
+ if (!logs.length) throw new Error('--stream-messages needs an RDF Message Log with VERSION "*-messages"');
63
+ for (const { name, index } of logs) {
64
+ const source = await openSource(name);
65
+ const scope = request.scope(name, index);
66
+ let code = 0;
67
+ const reader = new RdfMessageReader({ format: source.format ?? rdfMessageFormat(name), base: request.base ?? source.base, scope,
68
+ onMessage: (message) => {
69
+ code = request.run(inputs, name, replayMessages([message], { scope }));
70
+ return code === 0;
71
+ } });
72
+ for await (const text of source.body) {
73
+ reader.write(text);
74
+ if (reader.stopped) break;
75
+ }
76
+ reader.finish();
77
+ if (code) return code;
78
+ }
79
+ return 0;
80
+ } catch (error) {
81
+ io.stderr(`eyemind: ${error.message}\n`);
82
+ return 1;
83
+ }
84
+ }
package/src/proof.js CHANGED
@@ -6,6 +6,8 @@
6
6
  // implied_by(...)), then one step(Goal, By, Bindings, Uses) per inference,
7
7
  // then the search certificate that settles its negations and collections. The
8
8
  // document reader parses it as data; it never executes it.
9
+ // Native N3 and SRL documents decode to these same records and validate their
10
+ // displayed evidence before the unchanged C1–C10 checks consume it.
9
11
  //
10
12
  // Verification follows recorded uses; it never asks the solver to find a
11
13
  // missing derivation. Only pure primitives are independently recomputed.
@@ -16,7 +18,7 @@ import { goalTerm } from './goals.js';
16
18
  import { checkCalls } from './fidelity.js';
17
19
  import { INSPECTION_KEYS, isInspection } from './inspection.js';
18
20
  import { CONTROL_KEYS, Program } from './program.js';
19
- import { readTerms } from './reader.js';
21
+ import { readProofTerms } from './native-proof.js';
20
22
  import {
21
23
  Env, EyemindError, Struct, Var, conjunction, copyResolved, deref, flattenConjunction, freshTerm,
22
24
  isCallable, isFloat, isGround, isTerm, key, keyArity, keyName, listFromItems, properListItems, unify, variables,
@@ -402,7 +404,7 @@ function readDocument(program, document, fail, spellings) {
402
404
  const certificate = { tables: new Map(), calls: new Map(), listings: new Map(), order: [] };
403
405
  const empty = new Env();
404
406
  try {
405
- for (const [term] of readTerms(document)) {
407
+ for (const [term] of readProofTerms(document)) {
406
408
  if (isTerm(term, 'searched', 2) || isTerm(term, 'derived', 2) || isTerm(term, 'called', 2)) {
407
409
  readCertificate(term, certificate, fail, empty);
408
410
  continue;
package/src/rdf-lexer.js CHANGED
@@ -385,7 +385,7 @@ const EYMSG = Object.freeze({
385
385
  nonEmpty: `<${EYMSG_NS}nonEmpty>`,
386
386
  });
387
387
 
388
- function normalizeRdfCompatibility(inputText, { trig = false } = {}) {
388
+ function normalizeRdfCompatibility(inputText, { trig = false, messages = true } = {}) {
389
389
  let text = String(inputText ?? '');
390
390
 
391
391
  // eyemind: ordinary N3 input does not need RDF/TriG
@@ -394,7 +394,7 @@ function normalizeRdfCompatibility(inputText, { trig = false } = {}) {
394
394
  // plausible top-level TriG named graph block.
395
395
  const hasTripleTerms = text.includes('<<');
396
396
  const hasVersionDirective = /^\s*(?:@version|VERSION)\s+(["'])(?:1\.1|1\.2|1\.2-basic)\1\s*\.?\s*(?:#.*)?$/im.test(text);
397
- const hasMessageVersionDirective = /^\s*(?:@version|VERSION)\s+(["'])(?:1\.1|1\.2|1\.2-basic)-messages\1\s*\.?\s*(?:#.*)?$/im.test(text);
397
+ const hasMessageVersionDirective = messages && /^\s*(?:@version|VERSION)\s+(["'])(?:1\.1|1\.2|1\.2-basic)-messages\1\s*\.?\s*(?:#.*)?$/im.test(text);
398
398
  const hasNamedGraphCandidate = /(?:^|[.\r\n])\s*(?:GRAPH\s+)?(?:<[^>\r\n]*>|_:[A-Za-z][A-Za-z0-9_-]*|[A-Za-z][A-Za-z0-9_-]*:[^\s{};,.()[\]]*|:[^\s{};,.()[\]]+)\s*\{/m.test(text);
399
399
  const hasAnnotationSyntax = /(?:^|\s)~|\{\|/.test(text);
400
400
 
@@ -865,7 +865,38 @@ function normalizeRdfCompatibility(inputText, { trig = false } = {}) {
865
865
  }
866
866
 
867
867
  function stripVersionDirectives(s) {
868
- return s.replace(/^\s*(?:@version|VERSION)\s+(["'])(?:1\.1|1\.2|1\.2-basic)(?:-messages)?\1\s*\.?\s*(?:#.*)?$/gim, '');
868
+ // eyemind: a line in a long literal can look exactly like a directive.
869
+ // Only strip tokens outside literals, IRIs and comments.
870
+ let out = '';
871
+ let i = 0;
872
+ while (i < s.length) {
873
+ if (s[i] === '"' || s[i] === "'") {
874
+ const token = readStringAt(s, i);
875
+ out += token.text;
876
+ i = token.end;
877
+ } else if (s[i] === '<' && !s.startsWith('<<', i)) {
878
+ const token = readIriAt(s, i);
879
+ out += token.text;
880
+ i = token.end;
881
+ } else if (s[i] === '#') {
882
+ const end = s.slice(i).search(/[\r\n]/);
883
+ const stop = end < 0 ? s.length : i + end + 1;
884
+ out += s.slice(i, stop);
885
+ i = stop;
886
+ } else {
887
+ const match = /^(?:@version|VERSION)\s+(["'])(?:1\.1|1\.2|1\.2-basic)(?:-messages)?\1/i.exec(s.slice(i));
888
+ if (match && (i === 0 || !isWordChar(s[i - 1]))) {
889
+ let end = i + match[0].length;
890
+ if (s.slice(i, i + 8).toLowerCase() === '@version') {
891
+ end = skipWsAndComments(s, end);
892
+ if (s[end] === '.') end++;
893
+ }
894
+ out += s.slice(i, end).replace(/[^\r\n]/g, ' ');
895
+ i = end;
896
+ } else out += s[i++];
897
+ }
898
+ }
899
+ return out;
869
900
  }
870
901
 
871
902
  function skipWsAndComments(s, at) {
@@ -1392,7 +1423,7 @@ function isNumericLikeIdentifier(word) {
1392
1423
 
1393
1424
  function lex(inputText, opts = {}) {
1394
1425
  const rdf = !!(opts && opts.rdf);
1395
- if (rdf) inputText = normalizeRdfCompatibility(inputText, { trig: !!opts.trig });
1426
+ if (rdf) inputText = normalizeRdfCompatibility(inputText, { trig: !!opts.trig, messages: opts.messages !== false });
1396
1427
  // Avoid copying large ASCII/BMP inputs into an Array. Array.from() is
1397
1428
  // only needed when the text contains surrogate pairs and we want the old
1398
1429
  // code-point iteration behavior for non-BMP characters.
@@ -471,6 +471,13 @@ class DerivedFact {
471
471
  const __iriIntern = new Map();
472
472
  const __literalIntern = new Map();
473
473
 
474
+ // eyemind: conversion produces independent eyemind terms. Keeping parser
475
+ // intern tables after that would retain every term in an unbounded log.
476
+ function clearParserCaches() {
477
+ for (const cache of [__literalPartsCache, __tidIntern, __iriTidIntern, __blankTidIntern,
478
+ __literalTidIntern, __iriIntern, __literalIntern]) cache.clear();
479
+ }
480
+
474
481
  // Do not intern extremely large literal strings (e.g., huge numeric intermediates).
475
482
  // Interning them creates global strong references that prevent GC.
476
483
  const MAX_LITERAL_INTERN_LEN = 1024;
@@ -794,6 +801,7 @@ export {
794
801
  DerivedFact,
795
802
  internIri,
796
803
  internLiteral,
804
+ clearParserCaches,
797
805
  isRdfTypePred,
798
806
  isOwlSameAsPred,
799
807
  isLogImplies,
package/src/rdf-syntax.js CHANGED
@@ -192,6 +192,7 @@ export function checkRdfSyntax(text, format) {
192
192
  case 'VERSION':
193
193
  between();
194
194
  if (next?.k !== 'string' || next.v.startsWith(next.v[0].repeat(3))) fail(`${t.v} takes a short string`);
195
+ if (/-messages["']$/.test(next.v)) fail('RDF Message Logs need parseRdfMessages, which preserves message boundaries');
195
196
  if ((ts[k + 2]?.k === '.') !== (t.k === '@version')) fail(t.k === '@version' ? '@version ends with a dot' : 'VERSION has no dot');
196
197
  directive = t.k === '@version' ? 2 : 1;
197
198
  continue;
package/src/rdf.js CHANGED
@@ -18,7 +18,7 @@
18
18
  import { lex } from './rdf-lexer.js';
19
19
  import { checkRdfSyntax } from './rdf-syntax.js';
20
20
  import { Parser } from './rdf-parser.js';
21
- import { Blank, GraphTerm, Iri, ListTerm, Literal, LOG_NS, RDF_NS, literalParts } from './rdf-prelude.js';
21
+ import { Blank, GraphTerm, Iri, ListTerm, Literal, LOG_NS, RDF_NS, clearParserCaches, literalParts } from './rdf-prelude.js';
22
22
  import { EyemindError, Struct } from './terms.js';
23
23
  import { write } from './writer.js';
24
24
 
@@ -46,7 +46,7 @@ export function parseRdf(text, { format = 'turtle', base = null, scope = 'rdf' }
46
46
  try {
47
47
  checkRdfSyntax(text, format);
48
48
  assertRdf12SurfaceSyntax(text, format);
49
- const parser = new Parser(lex(text, { rdf: true, trig: format === 'trig' }));
49
+ const parser = new Parser(lex(text, { rdf: true, trig: format === 'trig', messages: false }));
50
50
  // RDF declares every prefix it uses; N3's predeclared ones do not apply.
51
51
  parser.prefixes.map = {};
52
52
  if (base) parser.prefixes.setBase(base);
@@ -74,10 +74,12 @@ export function parseRdf(text, { format = 'turtle', base = null, scope = 'rdf' }
74
74
  if (format !== 'trig' && format !== 'n-quads' && state.out.some((q) => q[3] !== DEFAULT_GRAPH)) {
75
75
  throw new SyntaxError(`${format} has no named graphs`);
76
76
  }
77
- return { quads: state.out, prefixes: prefixesOf(parser.prefixes) };
77
+ return { quads: state.out, prefixes: prefixesOf(parser.prefixes), base: parser.prefixes.baseIri || null };
78
78
  } catch (error) {
79
79
  if (error instanceof EyemindError) throw error;
80
80
  throw new EyemindError(`${format}: ${error.message}`);
81
+ } finally {
82
+ clearParserCaches();
81
83
  }
82
84
  }
83
85
 
@@ -133,9 +135,13 @@ function literalTerm(raw) {
133
135
  const tagged = /^(".*")@([A-Za-z]+(?:-[A-Za-z0-9]+)*)(?:--(ltr|rtl))?$/s.exec(text);
134
136
  if (tagged) {
135
137
  const lang = tagged[2].toLowerCase();
138
+ if (!/^[A-Za-z]{1,8}(?:-[A-Za-z0-9]{1,8})*$/.test(lang)) throw new SyntaxError(`invalid RDF 1.2 language tag @${tagged[2]}`);
136
139
  return st('literal', unquote(tagged[1]), tagged[3] ? st('lang', lang, tagged[3]) : st('lang', lang));
137
140
  }
138
141
  const [lexical, datatype] = literalParts(text);
142
+ if (datatype === `${RDF_NS}langString` || datatype === `${RDF_NS}dirLangString`) {
143
+ throw new SyntaxError(`RDF datatype ${datatype} requires a language tag`);
144
+ }
139
145
  const quoted = typeof lexical === 'string' && lexical.length >= 2 && lexical[0] === '"' && lexical.at(-1) === '"';
140
146
  const value = quoted ? unquote(lexical) : lexical;
141
147
  return literalOf(value, datatype ?? (quoted ? `${XSD}string` : bareDatatype(value)));
@@ -335,9 +341,9 @@ function assertLineSyntax(text) {
335
341
 
336
342
  // Write quads, [S, P, O, G] eyemind terms, as Turtle (or TriG when a quad is
337
343
  // in a named graph) with the prefixes it uses, or as N-Triples or N-Quads.
338
- export function writeRdf(quads, { format = 'turtle', prefixes = {} } = {}) {
344
+ export function writeRdf(quads, { format = 'turtle', prefixes = {}, blankNodePrefix = '' } = {}) {
339
345
  const line = format === 'n-triples' || format === 'n-quads';
340
- const w = new RdfWriter(line ? {} : prefixes, line);
346
+ const w = new RdfWriter(line ? {} : prefixes, line, blankNodePrefix);
341
347
  const body = [];
342
348
  if (line) {
343
349
  for (const [s, p, o, g] of quads) {
@@ -365,12 +371,13 @@ export function writeRdf(quads, { format = 'turtle', prefixes = {} } = {}) {
365
371
  const PN_LOCAL = /^(?:[A-Za-z_0-9À-�]|:)(?:[A-Za-z_0-9·À-�.:-]*[A-Za-z_0-9·À-�:-])?$/u;
366
372
 
367
373
  class RdfWriter {
368
- constructor(prefixes, line) {
374
+ constructor(prefixes, line, blankNodePrefix) {
369
375
  this.prefixes = new Map(Object.entries(prefixes));
370
376
  this.ordered = [...this.prefixes].sort((a, b) => b[1].length - a[1].length);
371
377
  this.line = line;
372
378
  this.used = new Set();
373
379
  this.bnodes = new Map();
380
+ this.blankNodePrefix = blankNodePrefix;
374
381
  }
375
382
 
376
383
  iri(v) {
@@ -399,7 +406,7 @@ class RdfWriter {
399
406
  if (t.name === 'iri' && t.args.length === 1 && typeof a === 'string') return this.iri(a);
400
407
  if ((t.name === 'bnode' && t.args.length === 2) || (t.name === 'skolem' && t.args.length === 3)) {
401
408
  const key = write(t);
402
- if (!this.bnodes.has(key)) this.bnodes.set(key, `_:b${this.bnodes.size}`);
409
+ if (!this.bnodes.has(key)) this.bnodes.set(key, `_:${this.blankNodePrefix}b${this.bnodes.size}`);
403
410
  return this.bnodes.get(key);
404
411
  }
405
412
  if (t.name === 'literal' && t.args.length === 2) return this.literal(a, b);
package/src/srl-parser.js CHANGED
@@ -29,6 +29,10 @@ class Parser {
29
29
  this.version = null;
30
30
  this.imports = [];
31
31
  this.bnodeCounter = 0;
32
+ // eyemind: collection/property-list nodes must not capture an explicit
33
+ // blank-node label, including a label appearing later in the document.
34
+ this.usedBlankNodeLabels = new Set(this.tokens.filter((token) => token.type === 'word' && token.value.startsWith('_:'))
35
+ .map((token) => token.value.slice(2)));
32
36
  this.bodyBnodeLabels = null;
33
37
  // Body blank nodes must become variables not used anywhere in the rule,
34
38
  // including in the head or in expressions that occur later in the body.
@@ -228,7 +232,8 @@ class Parser {
228
232
  freshGraphNode(options = {}) {
229
233
  do {
230
234
  this.bnodeCounter += 1;
231
- } while (options.context === 'body' && this.usedVariableNames.has(`__b${this.bnodeCounter}`));
235
+ } while (this.usedBlankNodeLabels.has(`b${this.bnodeCounter}`) ||
236
+ (options.context === 'body' && this.usedVariableNames.has(`__b${this.bnodeCounter}`)));
232
237
  const id = `b${this.bnodeCounter}`;
233
238
  if (options.context !== 'body') return blankNode(id);
234
239
  this.usedVariableNames.add(`__${id}`);
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.6';
2
+ export const VERSION = '0.5.8';