eyemind 0.5.17 → 0.5.19
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 +1 -1
- package/SPEC.md +1 -1
- package/package.json +1 -1
- package/src/engine.js +98 -25
- package/src/formats.js +10 -9
- package/src/lang.js +61 -0
- package/src/n3-parser.js +49 -26
- package/src/n3-writer.js +12 -5
- package/src/n3.js +73 -10
- package/src/rdf.js +5 -3
- package/src/srl-analyze.js +1 -1
- package/src/srl.js +161 -30
- package/src/terms.js +14 -2
- package/src/version.js +1 -1
- package/src/writer.js +1 -0
package/README.md
CHANGED
|
@@ -565,7 +565,7 @@ console.log(result.bindings);
|
|
|
565
565
|
console.log(checkProof(socrates, result.proof, { goals }).valid);
|
|
566
566
|
```
|
|
567
567
|
|
|
568
|
-
`run()` returns `answers`, `bindings`, `inferred`, `stdout`, `proof`, `proofReport`, `stats` and `haltCode`, and takes `goal`, `goals`, `proof`, `maxDepth`, `maxIterations` and `maxInferences`; exceeding a bound throws an `EyemindError`. `loadSources([[text, filename], ...], io)` loads several sources as one program; pass `nodeIO` from `eyemind/node` as `io` to let `facts_from(path)` read files. `checkProof(program, document, { goals, allowTrusted })` checks C1–C10, and `allowTrusted: false` rejects every obligation. `checkReport`, `readTerm`, `readTerms` and `write` format reports and read and write the canonical text.
|
|
568
|
+
`run()` returns `conclusions`, `answers`, `bindings`, `inferred`, `stdout`, `proof`, `proofReport`, `stats` and `haltCode`, and takes `goal`, `goals`, `proof`, `maxDepth`, `maxIterations` and `maxInferences`; exceeding a bound throws an `EyemindError`. `conclusions` holds the answer terms; `answers`, `bindings` and `stdout` are rendered when first read. Ground N3 conclusions are written directly from their terms. `loadSources([[text, filename], ...], io)` loads several sources as one program; pass `nodeIO` from `eyemind/node` as `io` to let `facts_from(path)` read files. `checkProof(program, document, { goals, allowTrusted })` checks C1–C10, and `allowTrusted: false` rejects every obligation. `checkReport`, `readTerm`, `readTerms` and `write` format reports and read and write the canonical text.
|
|
569
569
|
|
|
570
570
|
The core library's `result.proof` is the JavaScript certificate.
|
|
571
571
|
`writeNativeProof(result.proof, { format: 'n3', prefixes })` writes its N3
|
package/SPEC.md
CHANGED
package/package.json
CHANGED
package/src/engine.js
CHANGED
|
@@ -285,6 +285,10 @@ export class Solver {
|
|
|
285
285
|
// of the facts with that value there.
|
|
286
286
|
this.factIndex = new Map();
|
|
287
287
|
this.factKeys = new Set(program.groundFactKeys);
|
|
288
|
+
this.iriIds = new Map();
|
|
289
|
+
for (const clause of program.clauses) {
|
|
290
|
+
if (!clause.forward && !clause.body.length && isGround(clause.head)) this.factKeys.add(this.factKey(clause.head));
|
|
291
|
+
}
|
|
288
292
|
this.genericKeys = new Set();
|
|
289
293
|
this.genericPredicates = new Set();
|
|
290
294
|
this.derived = [];
|
|
@@ -301,6 +305,7 @@ export class Solver {
|
|
|
301
305
|
this.chosen = null;
|
|
302
306
|
this.snapshots = new Map();
|
|
303
307
|
this.direct = new Map();
|
|
308
|
+
this.groundCalls = new Map();
|
|
304
309
|
this.rules = new Map();
|
|
305
310
|
this.ruleKeys = new Map();
|
|
306
311
|
this.maxInferences = options.maxInferences || 1000000;
|
|
@@ -548,13 +553,28 @@ export class Solver {
|
|
|
548
553
|
const argument = indexKey(arg);
|
|
549
554
|
if (argument !== undefined) {
|
|
550
555
|
const bucket = positions[position].get(argument);
|
|
551
|
-
if (bucket === undefined) positions[position].set(argument,
|
|
556
|
+
if (bucket === undefined) positions[position].set(argument, number);
|
|
557
|
+
else if (typeof bucket === 'number') positions[position].set(argument, [bucket, number]);
|
|
552
558
|
else bucket.push(number);
|
|
553
559
|
}
|
|
554
560
|
});
|
|
555
561
|
}
|
|
556
562
|
}
|
|
557
563
|
|
|
564
|
+
// RDF rules often derive only IRI tuples. Small per-run identifiers avoid
|
|
565
|
+
// retaining a second copy of every IRI in each fact's duplicate key.
|
|
566
|
+
factKey(term) {
|
|
567
|
+
if (!(term instanceof Struct) || !term.args.length ||
|
|
568
|
+
!term.args.every((arg) => isTerm(arg, 'iri', 1) && typeof arg.args[0] === 'string')) return identity(term);
|
|
569
|
+
const ids = term.args.map((arg) => {
|
|
570
|
+
const iri = arg.args[0];
|
|
571
|
+
let id = this.iriIds.get(iri);
|
|
572
|
+
if (id === undefined) this.iriIds.set(iri, id = this.iriIds.size);
|
|
573
|
+
return id;
|
|
574
|
+
});
|
|
575
|
+
return `@${term.name.length}:${term.name}:${ids.length}:${ids.join(',')}`;
|
|
576
|
+
}
|
|
577
|
+
|
|
558
578
|
// The indexes of the derived facts a goal could match, in order, when an
|
|
559
579
|
// argument of the goal narrows them down; null to try them all.
|
|
560
580
|
factOrder(goal, env, goalKey) {
|
|
@@ -566,7 +586,8 @@ export class Solver {
|
|
|
566
586
|
for (let position = 0; position < goal.args.length; position++) {
|
|
567
587
|
const arg = indexKey(goal.args[position], env);
|
|
568
588
|
if (arg !== undefined) {
|
|
569
|
-
const
|
|
589
|
+
const stored = positions[position].get(arg);
|
|
590
|
+
const bucket = typeof stored === 'number' ? [stored] : stored ?? NO_NODES;
|
|
570
591
|
if (bucket.length < size) {
|
|
571
592
|
best = bucket;
|
|
572
593
|
size = bucket.length;
|
|
@@ -718,8 +739,7 @@ export class Solver {
|
|
|
718
739
|
let now = null;
|
|
719
740
|
let previous = null;
|
|
720
741
|
if (keys !== null) {
|
|
721
|
-
now =
|
|
722
|
-
for (const goalKey of keys) if (goalKey) now.set(goalKey, (this.facts.get(goalKey) || NO_NODES).length);
|
|
742
|
+
now = keys.map((goalKey) => goalKey === null ? null : (this.facts.get(goalKey) || NO_NODES).length);
|
|
723
743
|
previous = this.snapshots.get(clause) || null;
|
|
724
744
|
this.snapshots.set(clause, now);
|
|
725
745
|
}
|
|
@@ -727,13 +747,15 @@ export class Solver {
|
|
|
727
747
|
if (previous !== null) {
|
|
728
748
|
positions = [];
|
|
729
749
|
keys.forEach((goalKey, i) => {
|
|
730
|
-
if (goalKey && now
|
|
750
|
+
if (goalKey && now[i] > previous[i]) positions.push(i);
|
|
731
751
|
});
|
|
732
|
-
if (!positions.some((i) => this.mayMatchNew(clause.localBody[i], keys[i], previous, now))) {
|
|
752
|
+
if (!positions.some((i) => this.mayMatchNew(clause.localBody[i], keys[i], previous[i], now[i]))) {
|
|
733
753
|
return []; // nothing derived since its last search can be used, so nothing new follows
|
|
734
754
|
}
|
|
735
755
|
}
|
|
736
756
|
this.serial++;
|
|
757
|
+
const direct = this.directFirings(clause, keys, previous);
|
|
758
|
+
if (direct !== null) return direct;
|
|
737
759
|
const [head, fullBody, names] = freshClause(clause, this.serial, true);
|
|
738
760
|
const body = fullBody.slice(clause.prefixLength);
|
|
739
761
|
const env = new Env();
|
|
@@ -743,15 +765,16 @@ export class Solver {
|
|
|
743
765
|
for (const delta of positions) {
|
|
744
766
|
const window = keys.map((goalKey, i) => {
|
|
745
767
|
if (goalKey === null) return null;
|
|
746
|
-
if (i < delta) return [0, previous
|
|
747
|
-
if (i === delta) return [previous
|
|
748
|
-
return [0, now
|
|
768
|
+
if (i < delta) return [0, previous[i], true];
|
|
769
|
+
if (i === delta) return [previous[i], now[i], false];
|
|
770
|
+
return [0, now[i], true];
|
|
749
771
|
});
|
|
750
772
|
this.window = window;
|
|
751
773
|
this.windowGoals = body;
|
|
752
774
|
this.chosen = new Array(body.length).fill(null);
|
|
753
775
|
try {
|
|
754
|
-
|
|
776
|
+
// One push each: a scan can find more firings than a call takes arguments.
|
|
777
|
+
for (const item of this.scan(clause, head, body, names, env, prefix)) found.push(item);
|
|
755
778
|
} finally {
|
|
756
779
|
this.window = this.windowGoals = this.chosen = null;
|
|
757
780
|
}
|
|
@@ -760,14 +783,56 @@ export class Solver {
|
|
|
760
783
|
return found.map(([firing]) => firing);
|
|
761
784
|
}
|
|
762
785
|
|
|
786
|
+
// A single ordinary call over ground facts needs only a substitution.
|
|
787
|
+
// Keep the search machine for proofs, templates, witnesses and nonground
|
|
788
|
+
// source facts; otherwise no renamed clause or choice-point frames escape.
|
|
789
|
+
directFirings(clause, keys, previous) {
|
|
790
|
+
if (this.recording || keys === null || keys.length !== 1 || keys[0] === null ||
|
|
791
|
+
clause.parentId !== null || clause.templates.length || clause.captures !== null || clause.witnessNames.length) return null;
|
|
792
|
+
const goalKey = keys[0];
|
|
793
|
+
let ground = this.groundCalls.get(goalKey);
|
|
794
|
+
if (ground === undefined) {
|
|
795
|
+
ground = (this.program.groups.get(goalKey) || []).every((candidate) => isGround(candidate.head));
|
|
796
|
+
this.groundCalls.set(goalKey, ground);
|
|
797
|
+
}
|
|
798
|
+
if (!ground) return null;
|
|
799
|
+
if (++this.stats.inferences > this.maxInferences) throw new EyemindError('reasoning exceeded max_inferences');
|
|
800
|
+
const goal = clause.localBody[0];
|
|
801
|
+
const facts = this.facts.get(goalKey) || NO_NODES;
|
|
802
|
+
const order = this.factOrder(goal, null, goalKey);
|
|
803
|
+
const start = previous === null ? 0 : previous[0];
|
|
804
|
+
const found = [];
|
|
805
|
+
const env = new Env();
|
|
806
|
+
const add = (fact) => {
|
|
807
|
+
if (unify(goal, fact, env)) {
|
|
808
|
+
const conclusions = flattenConjunction(copyResolved(clause.head, env));
|
|
809
|
+
const claim = conclusions.includes('true') ? copyResolved(goal, env) : null;
|
|
810
|
+
found.push([conclusions, NO_NODES, NO_NODES, claim, null]);
|
|
811
|
+
}
|
|
812
|
+
env.undo(0);
|
|
813
|
+
};
|
|
814
|
+
if (order === null) {
|
|
815
|
+
for (let i = start; i < facts.length; i++) add(facts[i].goal);
|
|
816
|
+
} else {
|
|
817
|
+
for (let i = bisectLeft(order, start); i < order.length; i++) add(facts[order[i]].goal);
|
|
818
|
+
}
|
|
819
|
+
if (previous === null) {
|
|
820
|
+
for (const candidate of this.program.candidates(goal, null, goalKey)) {
|
|
821
|
+
this.serial++;
|
|
822
|
+
add(candidate.head);
|
|
823
|
+
}
|
|
824
|
+
}
|
|
825
|
+
return found;
|
|
826
|
+
}
|
|
827
|
+
|
|
763
828
|
// Whether a body goal, as the rule writes it, could match a fact derived
|
|
764
829
|
// since the rule's last search. The goal's own atoms and numbers narrow the
|
|
765
830
|
// facts down before the rule is renamed and searched.
|
|
766
831
|
mayMatchNew(goal, goalKey, previous, now) {
|
|
767
832
|
const order = this.factOrder(goal, null, goalKey);
|
|
768
833
|
if (order === null) return true;
|
|
769
|
-
const first = bisectLeft(order, previous
|
|
770
|
-
return first < order.length && order[first] < now
|
|
834
|
+
const first = bisectLeft(order, previous);
|
|
835
|
+
return first < order.length && order[first] < now;
|
|
771
836
|
}
|
|
772
837
|
|
|
773
838
|
// The solutions of a rule's body. A restricted rule's guard is a negation
|
|
@@ -929,6 +994,7 @@ export class Solver {
|
|
|
929
994
|
// bodies and their observable order.
|
|
930
995
|
for (const [clause, [conclusions, children, bindings, claim, guard]] of firings) {
|
|
931
996
|
if (guard) this.guards.push([clause, guard, conclusions]);
|
|
997
|
+
const by = new Struct('clause', [BigInt(clause.id)]);
|
|
932
998
|
for (const [position, conclusion] of conclusions.entries()) {
|
|
933
999
|
const template = clause.templates.find((item) => item.position === position);
|
|
934
1000
|
if (template) {
|
|
@@ -936,18 +1002,18 @@ export class Solver {
|
|
|
936
1002
|
continue;
|
|
937
1003
|
}
|
|
938
1004
|
if (conclusion === 'true') {
|
|
939
|
-
const claimId = this.program.inspectionEnabled ? variant(claim) :
|
|
1005
|
+
const claimId = this.program.inspectionEnabled ? variant(claim) : this.factKey(claim);
|
|
940
1006
|
if (!this.reported.has(claimId)) this.reported.set(claimId, [claim, children, clause.id]);
|
|
941
1007
|
continue;
|
|
942
1008
|
}
|
|
943
|
-
const node = new Node(conclusion,
|
|
1009
|
+
const node = new Node(conclusion, by, bindings, children, null, true);
|
|
944
1010
|
if (conclusion === 'false') {
|
|
945
1011
|
this.derived.push(node);
|
|
946
1012
|
this.haltCode = 65;
|
|
947
1013
|
return 'halt';
|
|
948
1014
|
}
|
|
949
1015
|
node.generic = this.program.inspectionEnabled && !isGround(conclusion);
|
|
950
|
-
const conclusionId = node.generic ? variant(conclusion) :
|
|
1016
|
+
const conclusionId = node.generic ? variant(conclusion) : this.factKey(conclusion);
|
|
951
1017
|
const factKeys = node.generic ? this.genericKeys : this.factKeys;
|
|
952
1018
|
if (factKeys.has(conclusionId)) continue;
|
|
953
1019
|
factKeys.add(conclusionId);
|
|
@@ -1144,7 +1210,7 @@ class Missing extends Error {
|
|
|
1144
1210
|
// of clauses only searches behind a trusted boundary could consult.
|
|
1145
1211
|
export class Result {
|
|
1146
1212
|
constructor(fields) {
|
|
1147
|
-
Object.
|
|
1213
|
+
Object.defineProperties(this, Object.getOwnPropertyDescriptors(fields));
|
|
1148
1214
|
}
|
|
1149
1215
|
|
|
1150
1216
|
// The derived facts as text, written only when asked for.
|
|
@@ -1236,12 +1302,9 @@ function reason(program, goalInputs, options) {
|
|
|
1236
1302
|
// Variables are named A, B, ... in the order the conclusions show them; the
|
|
1237
1303
|
// bindings of each answer name them as its conclusion does.
|
|
1238
1304
|
const lettering = new Lettering();
|
|
1239
|
-
|
|
1240
|
-
|
|
1241
|
-
|
|
1242
|
-
for (const [name, value] of answer) out[name] = write(value, null, lettering);
|
|
1243
|
-
return out;
|
|
1244
|
-
});
|
|
1305
|
+
let answers = null;
|
|
1306
|
+
let answerBindings = null;
|
|
1307
|
+
let stdout = null;
|
|
1245
1308
|
const rendered = options.proof
|
|
1246
1309
|
? renderProof(program, claims, roots, true, heading, (boundaries) => {
|
|
1247
1310
|
const ordinary = certify(solver, boundaries);
|
|
@@ -1271,12 +1334,22 @@ function reason(program, goalInputs, options) {
|
|
|
1271
1334
|
behind = [...clausesBehindBoundaries(program, roots)].filter((id) => !used.has(id)).sort((a, b) => a - b);
|
|
1272
1335
|
}
|
|
1273
1336
|
return new Result({
|
|
1274
|
-
|
|
1275
|
-
|
|
1337
|
+
conclusions: claims,
|
|
1338
|
+
// Native writers consume terms directly. Canonical text is made only
|
|
1339
|
+
// when asked for, with conclusions named before their bindings.
|
|
1340
|
+
get answers() { return answers ??= claims.map((claim) => write(claim, null, lettering)); },
|
|
1341
|
+
get bindings() {
|
|
1342
|
+
this.answers;
|
|
1343
|
+
return answerBindings ??= bindings.map((answer) => {
|
|
1344
|
+
const out = {};
|
|
1345
|
+
for (const [name, value] of answer) out[name] = write(value, null, lettering);
|
|
1346
|
+
return out;
|
|
1347
|
+
});
|
|
1348
|
+
},
|
|
1276
1349
|
derived: solver.derived,
|
|
1277
1350
|
clausesUsed: used !== null ? [...used].sort((a, b) => a - b) : null,
|
|
1278
1351
|
clausesBehindBoundaries: behind,
|
|
1279
|
-
stdout
|
|
1352
|
+
get stdout() { return stdout ??= document ?? [heading, ...this.answers].map((line) => `${line}\n`).join(''); },
|
|
1280
1353
|
proof: document,
|
|
1281
1354
|
proofReport: report,
|
|
1282
1355
|
stats: solver.stats,
|
package/src/formats.js
CHANGED
|
@@ -18,8 +18,8 @@ import { EyemindError, Struct } from './terms.js';
|
|
|
18
18
|
import { loadSources } from './lang.js';
|
|
19
19
|
import { readTerms } from './reader.js';
|
|
20
20
|
import { DEFAULT_GRAPH, parseRdf, rdfDocument, rdfFormat, writeRdf } from './rdf.js';
|
|
21
|
-
import {
|
|
22
|
-
import { compileSrl, srlQuads } from './srl.js';
|
|
21
|
+
import { resultToN3, compileSources } from './n3.js';
|
|
22
|
+
import { compileSrl, srlAnswers, srlQuads } from './srl.js';
|
|
23
23
|
import { write } from './writer.js';
|
|
24
24
|
import { isRdfMessageLog, parseRdfMessages } from './messages.js';
|
|
25
25
|
import { writeNativeProof } from './native-proof.js';
|
|
@@ -77,14 +77,16 @@ function load(inputs, io, { base = null, messageInputs = null, srlContext = null
|
|
|
77
77
|
});
|
|
78
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
|
-
return { kind: 'srl', program: loadSources([[compiled.program, name]], io),
|
|
80
|
+
return { kind: 'srl', program: compiled.nativeProgram ?? loadSources([[compiled.program, name]], io),
|
|
81
|
+
get text() { return compiled.program; }, prefixes: compiled.prefixes, compiled };
|
|
81
82
|
}
|
|
82
83
|
if (kinds.includes('n3')) {
|
|
83
84
|
if (kinds.includes('js')) throw new EyemindError('an N3 run takes .n3 documents and RDF data, not JavaScript programs');
|
|
84
85
|
const sources = inputs.map(([t, n], k) => (kinds[k] === 'rdf' ? rdf(t, n, k) : [t, n]));
|
|
85
86
|
const compiled = compileSources(sources, { base: base ?? '', baseOf: (n) => baseOf(n) ?? '', readFile: io?.readFile ?? null, readDocument: io?.readDocument ?? null,
|
|
86
|
-
source: inputs.map(([, n]) => n).join(', ') });
|
|
87
|
-
return { kind: 'n3', program: loadSources([[compiled.program, inputs[kinds.indexOf('n3')][1]]], io),
|
|
87
|
+
source: inputs.map(([, n]) => n).join(', '), native: true });
|
|
88
|
+
return { kind: 'n3', program: compiled.nativeProgram ?? loadSources([[compiled.program, inputs[kinds.indexOf('n3')][1]]], io),
|
|
89
|
+
get text() { return compiled.program; }, prefixes: compiled.doc.prefixes, compiled };
|
|
88
90
|
}
|
|
89
91
|
// RDF data joins a program as rdf/4 facts, read without running anything.
|
|
90
92
|
const prefixes = {};
|
|
@@ -136,14 +138,13 @@ export function writeProof(loaded, result, { goals = null } = {}) {
|
|
|
136
138
|
// all also writes the given data. Throws when a conclusion is no triple.
|
|
137
139
|
export function writeConclusions(loaded, result, { format, all = false, blankNodePrefix = '' } = {}) {
|
|
138
140
|
if (format === 'eyemind') return null;
|
|
139
|
-
const answers = result.answers;
|
|
140
141
|
if (format === 'n3') {
|
|
141
142
|
if (loaded.kind !== 'n3') throw new EyemindError('--to n3 writes the conclusions of an N3 run');
|
|
142
|
-
return
|
|
143
|
+
return resultToN3(loaded.compiled.doc, result, { mode: all ? 'all' : 'new', blankNodePrefix }).n3;
|
|
143
144
|
}
|
|
144
145
|
let quads;
|
|
145
|
-
if (loaded.kind === 'srl') quads = srlQuads(loaded.
|
|
146
|
-
else quads = conclusionQuads(answers, all ? loaded.text : null);
|
|
146
|
+
if (loaded.kind === 'srl') quads = srlQuads(loaded.compiled, srlAnswers(result), { all });
|
|
147
|
+
else quads = conclusionQuads(result.answers, all ? loaded.text : null);
|
|
147
148
|
return writeRdf(quads, { format, prefixes: loaded.kind === 'n3' ? Object.fromEntries(loaded.prefixes) : loaded.prefixes, blankNodePrefix });
|
|
148
149
|
}
|
|
149
150
|
|
package/src/lang.js
CHANGED
|
@@ -739,6 +739,67 @@ export function loadSources(sources, io = null) {
|
|
|
739
739
|
return builder.program();
|
|
740
740
|
}
|
|
741
741
|
|
|
742
|
+
// The clauses of statements that are document terms, read and never run:
|
|
743
|
+
// fact, implies, implied_by and query, and facts_from({ text: ... }), given
|
|
744
|
+
// the program line text starts on. A compiler's generated program has only
|
|
745
|
+
// these; they state the clauses loadText states from the same text, without
|
|
746
|
+
// the cost of compiling and running a large program as JavaScript. Null for
|
|
747
|
+
// any other text, which the caller runs instead.
|
|
748
|
+
export function statementSources(text, first = 1) {
|
|
749
|
+
let terms;
|
|
750
|
+
try {
|
|
751
|
+
terms = readTerms(text);
|
|
752
|
+
} catch {
|
|
753
|
+
return null;
|
|
754
|
+
}
|
|
755
|
+
const builder = new Builder(() => null);
|
|
756
|
+
try {
|
|
757
|
+
for (const [statement, at] of terms) {
|
|
758
|
+
if (!(statement instanceof Struct)) return null;
|
|
759
|
+
const { name } = statement;
|
|
760
|
+
const line = at + first - 1;
|
|
761
|
+
// A program's _ is one name each clause numbers; a document numbers it.
|
|
762
|
+
const args = statement.args.map(unnumbered);
|
|
763
|
+
if (name === 'fact') {
|
|
764
|
+
for (const term of args) builder.add('fact', term, [], line);
|
|
765
|
+
} else if (name === 'implies' && args.length === 2) {
|
|
766
|
+
builder.add('forward', normalizeGoal(args[1]), [normalizeGoal(args[0])], line);
|
|
767
|
+
} else if (name === 'implied_by' && args.length === 2) {
|
|
768
|
+
builder.add('backward', args[0], [normalizeGoal(args[1])], line);
|
|
769
|
+
} else if (name === 'query') {
|
|
770
|
+
builder.add('query', TRUE_ATOM, args.map(normalizeGoal), line);
|
|
771
|
+
} else if (name === 'facts_from' && args.length === 1 && args[0] instanceof Struct && args[0].name === '.' &&
|
|
772
|
+
args[0].args[1] === EMPTY && args[0].args[0] instanceof Struct && args[0].args[0].name === '=' &&
|
|
773
|
+
args[0].args[0].args[0] === 'text' && typeof args[0].args[0].args[1] === 'string') {
|
|
774
|
+
for (const [term] of readTerms(args[0].args[0].args[1])) builder.add('fact', term, [], line, false);
|
|
775
|
+
} else {
|
|
776
|
+
return null;
|
|
777
|
+
}
|
|
778
|
+
}
|
|
779
|
+
return builder.sources;
|
|
780
|
+
} catch {
|
|
781
|
+
// Run as JavaScript, it reports the error with its line.
|
|
782
|
+
return null;
|
|
783
|
+
}
|
|
784
|
+
}
|
|
785
|
+
|
|
786
|
+
const ANONYMOUS = new Var('_');
|
|
787
|
+
|
|
788
|
+
function unnumbered(term) {
|
|
789
|
+
if (term instanceof Var) return term.name.startsWith('_#') ? ANONYMOUS : term;
|
|
790
|
+
if (!(term instanceof Struct)) return term;
|
|
791
|
+
let args = null;
|
|
792
|
+
for (let index = 0; index < term.args.length; index++) {
|
|
793
|
+
const arg = term.args[index];
|
|
794
|
+
const plain = arg instanceof Struct || arg instanceof Var ? unnumbered(arg) : arg;
|
|
795
|
+
if (plain !== arg) {
|
|
796
|
+
if (args === null) args = [...term.args];
|
|
797
|
+
args[index] = plain;
|
|
798
|
+
}
|
|
799
|
+
}
|
|
800
|
+
return args === null ? term : new Struct(term.name, args);
|
|
801
|
+
}
|
|
802
|
+
|
|
742
803
|
// A Program from a function that states clauses when called: a function of a
|
|
743
804
|
// program, which states them with the names the program uses, or one of
|
|
744
805
|
// library code, which is handed those names.
|
package/src/n3-parser.js
CHANGED
|
@@ -34,13 +34,21 @@ export class N3SyntaxError extends SyntaxError {
|
|
|
34
34
|
|
|
35
35
|
const NUMBER = /[+-]?(?:[0-9]+\.[0-9]*[eE][+-]?[0-9]+|\.[0-9]+[eE][+-]?[0-9]+|[0-9]+[eE][+-]?[0-9]+|[0-9]*\.[0-9]+|[0-9]+)/y;
|
|
36
36
|
const PUNCT = ['^^', '=>', '<=', '<-', '.', ';', ',', '[', ']', '(', ')', '{', '}', '=', '!', '^'];
|
|
37
|
+
const punctuation = new Map();
|
|
38
|
+
for (const p of PUNCT) punctuation.set(p[0], [...(punctuation.get(p[0]) || []), p]);
|
|
37
39
|
|
|
38
40
|
function isPnCharsBase(c) {
|
|
41
|
+
const code = c.charCodeAt(0);
|
|
42
|
+
if (code < 128) return (code >= 65 && code <= 90) || (code >= 97 && code <= 122);
|
|
39
43
|
return /[A-Za-zÀ-ÖØ-öø-˿Ͱ-ͽͿ--⁰-Ⰰ-、-豈-﷏ﷰ-�]/u.test(c) ||
|
|
40
44
|
(c.codePointAt(0) >= 0x10000 && c.codePointAt(0) <= 0xEFFFF);
|
|
41
45
|
}
|
|
42
46
|
const isPnCharsU = (c) => isPnCharsBase(c) || c === '_';
|
|
43
|
-
const isPnChars = (c) =>
|
|
47
|
+
const isPnChars = (c) => {
|
|
48
|
+
const code = c.charCodeAt(0);
|
|
49
|
+
if (code < 128) return (code >= 65 && code <= 90) || (code >= 97 && code <= 122) || (code >= 48 && code <= 57) || c === '_' || c === '-';
|
|
50
|
+
return isPnCharsU(c) || /[·̀-ͯ‿-⁀]/u.test(c);
|
|
51
|
+
};
|
|
44
52
|
|
|
45
53
|
function decodeEscapes(text, line) {
|
|
46
54
|
let out = '';
|
|
@@ -69,11 +77,16 @@ function decodeEscapes(text, line) {
|
|
|
69
77
|
// Tokens: { k: kind, v: text, line }. Kinds: iri, pname, bnode, var, string,
|
|
70
78
|
// lang, number, word, punct, eof.
|
|
71
79
|
export function tokenize(src) {
|
|
72
|
-
|
|
80
|
+
return [...tokens(src)];
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
// The parser needs only two tokens of lookahead, even for a large document.
|
|
84
|
+
function* tokens(src) {
|
|
85
|
+
let previous = null;
|
|
73
86
|
let i = 0;
|
|
74
87
|
let line = 1;
|
|
75
88
|
const n = src.length;
|
|
76
|
-
const push = (k, v) =>
|
|
89
|
+
const push = (k, v) => (previous = { k, v, line });
|
|
77
90
|
while (i < n) {
|
|
78
91
|
const c = src[i];
|
|
79
92
|
if (c === '\n') { line++; i++; continue; }
|
|
@@ -81,7 +94,7 @@ export function tokenize(src) {
|
|
|
81
94
|
if (c === '#') { while (i < n && src[i] !== '\n') i++; continue; }
|
|
82
95
|
if (src.startsWith('<<', i) || src.startsWith('>>', i) || src.startsWith(')>>', i)) {
|
|
83
96
|
const v = src.startsWith('<<(', i) ? '<<(' : src.startsWith(')>>', i) ? ')>>' : src.slice(i, i + 2);
|
|
84
|
-
push('punct', v);
|
|
97
|
+
yield push('punct', v);
|
|
85
98
|
i += v.length;
|
|
86
99
|
continue;
|
|
87
100
|
}
|
|
@@ -93,7 +106,7 @@ export function tokenize(src) {
|
|
|
93
106
|
const decoded = decodeEscapes(raw, line);
|
|
94
107
|
// An escape may not bring in what the IRI could not hold as written.
|
|
95
108
|
if (/[\u0000-\u0020<>"{}|^`\\]/.test(decoded)) throw new N3SyntaxError(`invalid character in IRI <${raw}>`, line);
|
|
96
|
-
push('iri', decoded);
|
|
109
|
+
yield push('iri', decoded);
|
|
97
110
|
i = end + 1;
|
|
98
111
|
continue;
|
|
99
112
|
}
|
|
@@ -114,7 +127,7 @@ export function tokenize(src) {
|
|
|
114
127
|
if (src[j] === '\n') { if (!long) throw new N3SyntaxError('line break in a short string', line); line++; }
|
|
115
128
|
raw += src[j++];
|
|
116
129
|
}
|
|
117
|
-
push('string', decodeEscapes(raw, start));
|
|
130
|
+
yield push('string', decodeEscapes(raw, start));
|
|
118
131
|
i = j + q.length;
|
|
119
132
|
continue;
|
|
120
133
|
}
|
|
@@ -122,10 +135,10 @@ export function tokenize(src) {
|
|
|
122
135
|
const m = /^@([A-Za-z]+(?:-[A-Za-z0-9]+)*(?:--(?:ltr|rtl))?)/.exec(src.slice(i, i + 100));
|
|
123
136
|
if (!m) throw new N3SyntaxError('expected a language tag or keyword after @', line);
|
|
124
137
|
const word = m[1];
|
|
125
|
-
const prev =
|
|
126
|
-
if (['prefix', 'base', 'version', 'keywords', 'forAll', 'forSome'].includes(word) && !(prev && prev.k === 'string')) push('word', `@${word}`);
|
|
127
|
-
else if (['a', 'is', 'of', 'has'].includes(word) && !(prev && prev.k === 'string')) push('word', word);
|
|
128
|
-
else push('lang', word);
|
|
138
|
+
const prev = previous;
|
|
139
|
+
if (['prefix', 'base', 'version', 'keywords', 'forAll', 'forSome'].includes(word) && !(prev && prev.k === 'string')) yield push('word', `@${word}`);
|
|
140
|
+
else if (['a', 'is', 'of', 'has'].includes(word) && !(prev && prev.k === 'string')) yield push('word', word);
|
|
141
|
+
else yield push('lang', word);
|
|
129
142
|
i += m[0].length;
|
|
130
143
|
continue;
|
|
131
144
|
}
|
|
@@ -136,7 +149,7 @@ export function tokenize(src) {
|
|
|
136
149
|
if (!isPnChars(ch)) break;
|
|
137
150
|
j += ch.length;
|
|
138
151
|
}
|
|
139
|
-
push('var', src.slice(i + 1, j));
|
|
152
|
+
yield push('var', src.slice(i + 1, j));
|
|
140
153
|
i = j;
|
|
141
154
|
continue;
|
|
142
155
|
}
|
|
@@ -148,20 +161,20 @@ export function tokenize(src) {
|
|
|
148
161
|
j += ch.length;
|
|
149
162
|
}
|
|
150
163
|
while (src[j - 1] === '.') j--;
|
|
151
|
-
push('bnode', src.slice(i + 2, j));
|
|
164
|
+
yield push('bnode', src.slice(i + 2, j));
|
|
152
165
|
i = j;
|
|
153
166
|
continue;
|
|
154
167
|
}
|
|
155
168
|
NUMBER.lastIndex = i;
|
|
156
169
|
const num = NUMBER.exec(src);
|
|
157
170
|
if (num && (/[0-9]/.test(c) || ((c === '+' || c === '-' || c === '.') && /[0-9.]/.test(src[i + 1] ?? '')))) {
|
|
158
|
-
push('number', num[0]);
|
|
171
|
+
yield push('number', num[0]);
|
|
159
172
|
i += num[0].length;
|
|
160
173
|
continue;
|
|
161
174
|
}
|
|
162
|
-
const punct =
|
|
175
|
+
const punct = punctuation.get(c)?.find((p) => src.startsWith(p, i));
|
|
163
176
|
if (punct && !(punct === '.' && /[0-9]/.test(src[i + 1] ?? ''))) {
|
|
164
|
-
push('punct', punct);
|
|
177
|
+
yield push('punct', punct);
|
|
165
178
|
i += punct.length;
|
|
166
179
|
continue;
|
|
167
180
|
}
|
|
@@ -180,15 +193,14 @@ export function tokenize(src) {
|
|
|
180
193
|
}
|
|
181
194
|
while (src[j - 1] === '.' && j > i) j--;
|
|
182
195
|
const text = src.slice(i, j);
|
|
183
|
-
if (prefix === null) push('word', text);
|
|
184
|
-
else push('pname', text);
|
|
196
|
+
if (prefix === null) yield push('word', text);
|
|
197
|
+
else yield push('pname', text);
|
|
185
198
|
i = j;
|
|
186
199
|
continue;
|
|
187
200
|
}
|
|
188
201
|
throw new N3SyntaxError(`unexpected character ${JSON.stringify(c)}`, line);
|
|
189
202
|
}
|
|
190
|
-
push('eof', '');
|
|
191
|
-
return toks;
|
|
203
|
+
yield push('eof', '');
|
|
192
204
|
}
|
|
193
205
|
|
|
194
206
|
// Resolve a relative IRI reference against a base (RFC 3986, Section 5.2).
|
|
@@ -221,8 +233,6 @@ function removeDots(path) {
|
|
|
221
233
|
return out.join('/');
|
|
222
234
|
}
|
|
223
235
|
|
|
224
|
-
const iri = (v) => ({ t: 'iri', v });
|
|
225
|
-
|
|
226
236
|
// Prefixes a document may use without declaring them.
|
|
227
237
|
export const DEFAULT_PREFIXES = {
|
|
228
238
|
rdf: RDF,
|
|
@@ -241,17 +251,30 @@ export const DEFAULT_PREFIXES = {
|
|
|
241
251
|
// in declaration order. Native proof validation preserves numeric literal
|
|
242
252
|
// text, so two different decimal displays cannot agree through rounding.
|
|
243
253
|
export function parseN3(src, { base = '', preserveNumericLiterals = false } = {}) {
|
|
244
|
-
|
|
245
|
-
|
|
254
|
+
src = String(src);
|
|
255
|
+
const input = tokens(src);
|
|
256
|
+
const ahead = [];
|
|
257
|
+
const iris = new Map();
|
|
258
|
+
const iri = (v) => {
|
|
259
|
+
let term = iris.get(v);
|
|
260
|
+
if (term === undefined) iris.set(v, term = { t: 'iri', v });
|
|
261
|
+
return term;
|
|
262
|
+
};
|
|
246
263
|
const prefixes = new Map();
|
|
247
264
|
let bnodeCount = 0;
|
|
248
265
|
let scopeCount = 0;
|
|
249
266
|
const top = { id: 0, triples: [], parent: null, bound: new Map(), started: false, existential: false };
|
|
250
267
|
// Names for declared variables, apart from those the document writes.
|
|
251
|
-
const taken = new Set(
|
|
268
|
+
const taken = new Set();
|
|
269
|
+
if (src.includes('@forAll') || src.includes('@forSome')) {
|
|
270
|
+
for (const t of tokens(src)) if (t.k === 'var' || t.k === 'bnode') taken.add(`${t.k}:${t.v}`);
|
|
271
|
+
}
|
|
252
272
|
let scope = top;
|
|
253
|
-
const peek = (k = 0) =>
|
|
254
|
-
|
|
273
|
+
const peek = (k = 0) => {
|
|
274
|
+
while (ahead.length <= k) ahead.push(input.next().value);
|
|
275
|
+
return ahead[k];
|
|
276
|
+
};
|
|
277
|
+
const next = () => { const t = peek(); ahead.shift(); return t; };
|
|
255
278
|
const fail = (message, tok = peek()) => new N3SyntaxError(message, tok.line);
|
|
256
279
|
const isP = (v, tok = peek()) => tok.k === 'punct' && tok.v === v;
|
|
257
280
|
const expectP = (v) => {
|
package/src/n3-writer.js
CHANGED
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
// Skolem term skolem(Rule, Variable, Arguments) is a blank node, the same one
|
|
6
6
|
// for the same rule firing.
|
|
7
7
|
import { readTerms } from './reader.js';
|
|
8
|
-
import { Struct, Var } from './terms.js';
|
|
8
|
+
import { Struct, Var, identity } from './terms.js';
|
|
9
9
|
import { write } from './writer.js';
|
|
10
10
|
import { LOG, RDF, XSD } from './n3-parser.js';
|
|
11
11
|
|
|
@@ -14,16 +14,23 @@ export class N3WriteError extends Error {}
|
|
|
14
14
|
// The triples of an eyemind conclusions document, in order and without
|
|
15
15
|
// duplicates. Also reports whether a contradiction halted the run.
|
|
16
16
|
export function triplesFromEyemind(text) {
|
|
17
|
+
return triplesFromTerms(readTerms(String(text)).map(([term]) => term));
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
// Native conclusions need no canonical-text round trip.
|
|
21
|
+
export function triplesFromTerms(terms, distinct = false) {
|
|
17
22
|
const triples = [];
|
|
18
23
|
const seen = new Set();
|
|
19
24
|
let contradiction = false;
|
|
20
|
-
for (const
|
|
25
|
+
for (const term of terms) {
|
|
21
26
|
if (term === 'false') { contradiction = true; continue; }
|
|
22
27
|
const t = tripleTerm(term);
|
|
23
28
|
if (!t) continue;
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
29
|
+
if (!distinct) {
|
|
30
|
+
const k = identity(t);
|
|
31
|
+
if (seen.has(k)) continue;
|
|
32
|
+
seen.add(k);
|
|
33
|
+
}
|
|
27
34
|
triples.push(t.args);
|
|
28
35
|
}
|
|
29
36
|
return { triples, contradiction };
|
package/src/n3.js
CHANGED
|
@@ -23,10 +23,11 @@
|
|
|
23
23
|
// predicates of a body become goals defined in eyemind itself (builtins.mjs).
|
|
24
24
|
import { run } from './engine.js';
|
|
25
25
|
import { loadText } from './lang.js';
|
|
26
|
-
import {
|
|
26
|
+
import { Program, Source } from './program.js';
|
|
27
|
+
import { Struct, Var, conjunction, isGround } from './terms.js';
|
|
27
28
|
import { write } from './writer.js';
|
|
28
29
|
import { N3SyntaxError, parseN3, typedLiteral, LOG, XSD } from './n3-parser.js';
|
|
29
|
-
import { triplesFromEyemind, tripleToEyemind, writeN3 } from './n3-writer.js';
|
|
30
|
+
import { triplesFromEyemind, triplesFromTerms, termToEyemind, tripleToEyemind, writeN3 } from './n3-writer.js';
|
|
30
31
|
import { documentIris, readDocuments } from './n3-documents.js';
|
|
31
32
|
|
|
32
33
|
const MATH = 'http://www.w3.org/2000/10/swap/math#';
|
|
@@ -1026,7 +1027,7 @@ export function readSources(sources, { base = '', baseOf = () => '' } = {}) {
|
|
|
1026
1027
|
if (!Array.isArray(sources[k]) && triple.p.v === GRAPH_CONTENT && triple.o.t === 'graph') {
|
|
1027
1028
|
const key = `${triple.s.t}:${triple.s.v}`;
|
|
1028
1029
|
if (graphs.has(key)) {
|
|
1029
|
-
graphs.get(key).triples.push(
|
|
1030
|
+
for (const item of triple.o.triples) graphs.get(key).triples.push(item);
|
|
1030
1031
|
continue;
|
|
1031
1032
|
}
|
|
1032
1033
|
graphs.set(key, triple.o);
|
|
@@ -1040,11 +1041,63 @@ export function readSources(sources, { base = '', baseOf = () => '' } = {}) {
|
|
|
1040
1041
|
|
|
1041
1042
|
// A document's program: { program, documents }; readFile reads the
|
|
1042
1043
|
// documents it names for log:semantics and log:content.
|
|
1043
|
-
export function compileSources(sources, { base = '', baseOf, readFile = null, readDocument = null, source } = {}) {
|
|
1044
|
+
export function compileSources(sources, { base = '', baseOf, readFile = null, readDocument = null, source, native = false } = {}) {
|
|
1044
1045
|
const doc = readSources(sources, { base, baseOf });
|
|
1045
1046
|
const documents = readDocuments(documentIris(doc.triples), readFile, readDocument);
|
|
1046
|
-
|
|
1047
|
-
|
|
1047
|
+
let program;
|
|
1048
|
+
const compiled = native && !documents.size ? plainProgram(doc) : null;
|
|
1049
|
+
const display = () => compileN3Document(doc, { source: source ?? sourceNames(sources), documents }).program;
|
|
1050
|
+
if (compiled === null) program = display();
|
|
1051
|
+
return { doc, nativeProgram: compiled, get program() { return program ??= display(); } };
|
|
1052
|
+
}
|
|
1053
|
+
|
|
1054
|
+
// Ordinary triple rules already are clauses. Build them without generating
|
|
1055
|
+
// and executing a second language. Other N3 constructs use the full compiler;
|
|
1056
|
+
// the JavaScript display remains available and keeps the same clause lines.
|
|
1057
|
+
function plainProgram(doc) {
|
|
1058
|
+
const listIris = new Set(['first', 'rest', 'nil'].map((name) => `${RDF_NS}${name}`));
|
|
1059
|
+
const constant = (t) => ['iri', 'literal', 'int', 'float'].includes(t.t) && !(t.t === 'iri' && listIris.has(t.v));
|
|
1060
|
+
const ordinary = (x) => x.p.t === 'iri' && [x.s, x.p, x.o].every((t) => constant(t) || (t.t === 'var' && (t.scope ?? 0) === 0));
|
|
1061
|
+
const facts = [];
|
|
1062
|
+
const rules = [];
|
|
1063
|
+
for (const x of doc.triples) {
|
|
1064
|
+
if (x.p.t === 'iri' && x.p.v === `${LOG}implies` && x.s.t === 'graph' && x.o.t === 'graph') {
|
|
1065
|
+
if (!x.s.triples.every((b) => ordinary(b) && !BUILTINS.has(b.p.v) && !UNSUPPORTED.has(b.p.v) &&
|
|
1066
|
+
!INLINE.has(b.p.v) && !TESTS.has(b.p.v) && !SCOPED_SUBJECT.has(b.p.v) && !SCOPED_OBJECT.has(b.p.v) && !RULE_PREDICATES.has(b.p.v))) return null;
|
|
1067
|
+
if (!x.o.triples.every(ordinary)) return null;
|
|
1068
|
+
const bound = keysOf(x.s);
|
|
1069
|
+
if ([...keysOf(x.o)].some((name) => !bound.has(name))) return null;
|
|
1070
|
+
if (x.o.triples.length) rules.push(x);
|
|
1071
|
+
} else {
|
|
1072
|
+
if (![x.s, x.p, x.o].every(constant)) return null;
|
|
1073
|
+
facts.push(x);
|
|
1074
|
+
}
|
|
1075
|
+
}
|
|
1076
|
+
const iris = new Map();
|
|
1077
|
+
const named = new Map();
|
|
1078
|
+
const term = (t, ctx) => {
|
|
1079
|
+
if (t.t === 'var') {
|
|
1080
|
+
const name = ctx.name(`v:${t.v}`, t.v);
|
|
1081
|
+
let value = named.get(name);
|
|
1082
|
+
if (value === undefined) named.set(name, value = new Var(name));
|
|
1083
|
+
return value;
|
|
1084
|
+
}
|
|
1085
|
+
if (t.t === 'iri') {
|
|
1086
|
+
let value = iris.get(t.v);
|
|
1087
|
+
if (value === undefined) iris.set(t.v, value = new Struct('iri', [t.v]));
|
|
1088
|
+
return value;
|
|
1089
|
+
}
|
|
1090
|
+
return termToEyemind(t);
|
|
1091
|
+
};
|
|
1092
|
+
const triple = (x, ctx) => new Struct('rdf', [term(x.s, ctx), term(x.p, ctx), term(x.o, ctx)]);
|
|
1093
|
+
const sources = facts.map((x, i) => new Source('fact', triple(x), [], i + 4));
|
|
1094
|
+
for (const x of rules) {
|
|
1095
|
+
const ctx = new Context(true);
|
|
1096
|
+
const body = x.s.triples.map((b) => triple(b, ctx));
|
|
1097
|
+
const head = conjunction(x.o.triples.map((h) => triple(h, ctx)));
|
|
1098
|
+
sources.push(new Source('forward', head, body.length ? body : ['true'], sources.length + 4));
|
|
1099
|
+
}
|
|
1100
|
+
return new Program(sources);
|
|
1048
1101
|
}
|
|
1049
1102
|
|
|
1050
1103
|
const sourceNames = (sources) => (typeof sources === 'string' ? 'input' : sources.map((s) => (Array.isArray(s) ? s[1] : 'data')).join(', '));
|
|
@@ -1053,7 +1106,17 @@ const sourceNames = (sources) => (typeof sources === 'string' ? 'input' : source
|
|
|
1053
1106
|
// mode 'all', and the document's own log:outputString strings when the
|
|
1054
1107
|
// result writes strings.
|
|
1055
1108
|
export function answersToN3(doc, answers, { mode = 'new', strings = 'auto', blankNodePrefix = '' } = {}) {
|
|
1056
|
-
|
|
1109
|
+
return conclusionsToN3(doc, triplesFromEyemind(answers.join('\n')), { mode, strings, blankNodePrefix });
|
|
1110
|
+
}
|
|
1111
|
+
|
|
1112
|
+
export function resultToN3(doc, result, options = {}) {
|
|
1113
|
+
// Nonground answers retain the document-wide variable names of their
|
|
1114
|
+
// canonical text. Forward ground conclusions are already distinct.
|
|
1115
|
+
if (!result.conclusions || result.conclusions.some((term) => !isGround(term))) return answersToN3(doc, result.answers, options);
|
|
1116
|
+
return conclusionsToN3(doc, triplesFromTerms(result.conclusions, true), options);
|
|
1117
|
+
}
|
|
1118
|
+
|
|
1119
|
+
function conclusionsToN3(doc, { triples, contradiction }, { mode = 'new', strings = 'auto', blankNodePrefix = '' } = {}) {
|
|
1057
1120
|
const given = doc.triples.filter((x) => !isRule(x)).map(tripleToEyemind);
|
|
1058
1121
|
if (mode === 'all') triples = [...given, ...triples];
|
|
1059
1122
|
else if (strings !== false && triples.some(isOutputString)) triples = [...given.filter(isOutputString), ...triples];
|
|
@@ -1067,9 +1130,9 @@ export const N3_LIMITS = { maxDepth: 1000000, maxIterations: 100000, maxInferenc
|
|
|
1067
1130
|
// result }; with proof, result.proof is eyemind's checked proof of the
|
|
1068
1131
|
// compiled program.
|
|
1069
1132
|
export function reasonN3(sources, { base = '', mode = 'new', strings = 'auto', limits = {}, proof = false, goals = [], readFile = null, readDocument = null } = {}) {
|
|
1070
|
-
const
|
|
1071
|
-
const result = run(loadText(program, 'compiled.js'), { ...N3_LIMITS, ...limits, proof, goals });
|
|
1072
|
-
return { ...
|
|
1133
|
+
const compiled = compileSources(sources, { base, readFile, readDocument, native: true });
|
|
1134
|
+
const result = run(compiled.nativeProgram ?? loadText(compiled.program, 'compiled.js'), { ...N3_LIMITS, ...limits, proof, goals });
|
|
1135
|
+
return { ...resultToN3(compiled.doc, result, { mode, strings }), get program() { return compiled.program; }, result };
|
|
1073
1136
|
}
|
|
1074
1137
|
|
|
1075
1138
|
const RULE_IRIS = new Set([`${LOG}implies`, `${LOG}impliedBy`, `${LOG}query`]);
|
package/src/rdf.js
CHANGED
|
@@ -359,9 +359,11 @@ export function writeRdf(quads, { format = 'turtle', prefixes = {}, blankNodePre
|
|
|
359
359
|
graphs.get(key)[1].push(q);
|
|
360
360
|
}
|
|
361
361
|
for (const [key, [g, qs]] of graphs) {
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
362
|
+
// One push per line: a graph can have more lines than a call takes arguments.
|
|
363
|
+
const indent = key === DEFAULT_GRAPH ? '' : ' ';
|
|
364
|
+
if (indent) body.push(`${w.term(g)} {`);
|
|
365
|
+
for (const [s, p, o] of qs) body.push(`${indent}${w.term(s)} ${w.predicate(p)} ${w.term(o)} .`);
|
|
366
|
+
if (indent) body.push('}');
|
|
365
367
|
}
|
|
366
368
|
const head = [...w.used].sort().map((name) => `PREFIX ${name}: <${w.prefixes.get(name)}>`);
|
|
367
369
|
if (head.length && body.length) head.push('');
|
package/src/srl-analyze.js
CHANGED
|
@@ -269,7 +269,7 @@ function stratificationLayers(ruleCount, components, componentOf, edges) {
|
|
|
269
269
|
}
|
|
270
270
|
}
|
|
271
271
|
}
|
|
272
|
-
const max = Math.max(
|
|
272
|
+
const max = levels.reduce((a, b) => Math.max(a, b), 0); // eyemind: more levels than a call takes as arguments
|
|
273
273
|
const layers = Array.from({ length: max + 1 }, () => []);
|
|
274
274
|
levels.forEach((level, index) => layers[level].push(index));
|
|
275
275
|
return layers;
|
package/src/srl.js
CHANGED
|
@@ -36,10 +36,11 @@ import { BUILTIN_SIGNATURES, canonicalBuiltinName } from './srl-builtin-names.js
|
|
|
36
36
|
import { libraryText } from './srl-functions.js';
|
|
37
37
|
import { Parser } from './srl-parser.js';
|
|
38
38
|
import { run } from './engine.js';
|
|
39
|
-
import { loadText } from './lang.js';
|
|
39
|
+
import { loadText, statementSources } from './lang.js';
|
|
40
|
+
import { Program, Source } from './program.js';
|
|
40
41
|
import { DEFAULT_GRAPH } from './rdf.js';
|
|
41
42
|
import { readTerms } from './reader.js';
|
|
42
|
-
import { Struct } from './terms.js';
|
|
43
|
+
import { Struct, Var, conjunction, identity, isGround } from './terms.js';
|
|
43
44
|
import { readProofTerms } from './native-proof.js';
|
|
44
45
|
import { write } from './writer.js';
|
|
45
46
|
|
|
@@ -79,12 +80,12 @@ function withImports(program, { filename, resolve, seen }) {
|
|
|
79
80
|
const imported = withImports(new Parser(String(source), { baseIRI: target, filename: target, strictGrammar: true }).parseProgram(),
|
|
80
81
|
{ filename: target, resolve, seen });
|
|
81
82
|
Object.assign(merged.prefixes, imported.prefixes);
|
|
82
|
-
merged.data.
|
|
83
|
-
merged.rules.
|
|
83
|
+
merged.data = merged.data.concat(imported.data);
|
|
84
|
+
merged.rules = merged.rules.concat(imported.rules);
|
|
84
85
|
}
|
|
85
86
|
Object.assign(merged.prefixes, program.prefixes);
|
|
86
|
-
merged.data.
|
|
87
|
-
merged.rules.
|
|
87
|
+
merged.data = merged.data.concat(program.data);
|
|
88
|
+
merged.rules = merged.rules.concat(program.rules);
|
|
88
89
|
return merged;
|
|
89
90
|
}
|
|
90
91
|
|
|
@@ -100,40 +101,90 @@ const RESERVED = new Set(['Math', 'JSON', 'BigInt', 'Infinity', 'NaN', 'undefine
|
|
|
100
101
|
// Compile a rule set's text. Options: base (IRI), filename, resolve (for
|
|
101
102
|
// IMPORTS, see readRuleSet), data (the base graph, as RDF quads from
|
|
102
103
|
// parseRdf, in its default graph), context (a recorded execution's now and
|
|
103
|
-
// seed). Returns { program, prefixes, warnings, context
|
|
104
|
+
// seed). Returns { program, nativeProgram, prefixes, warnings, context,
|
|
105
|
+
// data, given }; see compileRuleSet.
|
|
104
106
|
export function compileSrl(text, { base = null, filename = '<input>', resolve = null, data = [], context = null } = {}) {
|
|
105
107
|
const ruleSet = readRuleSet(text, { base, filename, resolve });
|
|
106
108
|
return compileRuleSet(ruleSet, { data, source: filename, context });
|
|
107
109
|
}
|
|
108
110
|
|
|
109
|
-
// Compile a parsed rule set over a base graph of RDF quads.
|
|
111
|
+
// Compile a parsed rule set over a base graph of RDF quads. program is the
|
|
112
|
+
// compiled JavaScript text, written when first asked for; nativeProgram the
|
|
113
|
+
// Program it states, made without generating and running that text: data,
|
|
114
|
+
// DATA blocks and rules of triple patterns become clauses directly, and the
|
|
115
|
+
// text of other rules and of the function library is read as statements.
|
|
116
|
+
// data is the base graph and given the DATA triples, as inf/3 terms.
|
|
110
117
|
export function compileRuleSet(ruleSet, { data = [], source = '<input>', context = null } = {}) {
|
|
111
118
|
const needed = new Set();
|
|
112
119
|
const warnings = [];
|
|
113
|
-
|
|
120
|
+
// Each part is a line of the text, or clauses made directly, which can
|
|
121
|
+
// also write their line: { text(), sources(line) }.
|
|
122
|
+
const parts = [
|
|
114
123
|
`// Generated by eyemind from ${String(source).replace(/[\r\n]/g, ' ')}, a SPARQL 1.2 RL rule set.`,
|
|
115
124
|
'// Each RDF triple is rdf(Subject, Predicate, Object); base(S, P, O) is the',
|
|
116
125
|
'// base graph and inf(S, P, O) the inference graph, the conclusions.',
|
|
117
126
|
];
|
|
118
127
|
if (data.some((q) => q[3] !== DEFAULT_GRAPH)) throw new SrlError('the base graph is one graph; give the data as Turtle or N-Triples');
|
|
119
128
|
if (data.length) {
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
129
|
+
parts.push({
|
|
130
|
+
// Through facts_from, as document text, so integers of any size are exact.
|
|
131
|
+
text: () => `facts_from({ text: ${JSON.stringify(data.flatMap(([S, P, O]) =>
|
|
132
|
+
[write(new Struct('rdf', [S, P, O])), write(new Struct('base', [S, P, O]))]).join('\n'))} })`,
|
|
133
|
+
sources: (line) => data.flatMap(([S, P, O]) =>
|
|
134
|
+
[new Source('fact', new Struct('rdf', [S, P, O]), [], line), new Source('fact', new Struct('base', [S, P, O]), [], line)]),
|
|
135
|
+
});
|
|
123
136
|
}
|
|
124
137
|
const terms = new Terms('srl');
|
|
125
|
-
|
|
138
|
+
const native = new NativeTerms('srl');
|
|
139
|
+
const given = ruleSet.data.map((t) => native.rdf(t, 'inf'));
|
|
140
|
+
ruleSet.data.forEach((t, k) => parts.push({
|
|
141
|
+
text: () => `fact(${terms.rdf(t, 'rdf')}, ${terms.rdf(t, 'inf')})`,
|
|
142
|
+
sources: (line) => [new Source('fact', native.rdf(t, 'rdf'), [], line), new Source('fact', given[k], [], line)],
|
|
143
|
+
}));
|
|
126
144
|
ruleSet.rules.forEach((rule, index) => {
|
|
127
|
-
|
|
145
|
+
const compiler = new RuleCompiler(rule, index + 1, { needed, warnings });
|
|
146
|
+
const clause = compiler.plain(native);
|
|
147
|
+
if (clause === null) {
|
|
148
|
+
for (const line of compiler.compile()) parts.push(line);
|
|
149
|
+
} else {
|
|
150
|
+
parts.push({
|
|
151
|
+
text: () => new RuleCompiler(rule, index + 1, { needed: new Set(), warnings: [] }).compile()[0],
|
|
152
|
+
sources: (line) => [new Source('forward', clause[0], clause[1], line)],
|
|
153
|
+
});
|
|
154
|
+
}
|
|
128
155
|
});
|
|
129
156
|
if (needed.has('srl_now') || needed.has('srl_uuid')) {
|
|
130
157
|
context = executionContext(context);
|
|
131
|
-
|
|
158
|
+
parts.push(`fact(srl_execution(${q(context.now)}, ${q(context.seed)}))`);
|
|
132
159
|
}
|
|
133
|
-
|
|
160
|
+
parts.push('query(inf(S, P, O))');
|
|
134
161
|
const library = libraryText(needed);
|
|
135
|
-
if (library)
|
|
136
|
-
|
|
162
|
+
if (library) parts.push('', '// SPARQL functions and aggregates.', library);
|
|
163
|
+
let program = null;
|
|
164
|
+
return {
|
|
165
|
+
get program() { return program ??= `${parts.map((part) => (typeof part === 'string' ? part : part.text())).join('\n')}\n`; },
|
|
166
|
+
nativeProgram: nativeProgram(parts),
|
|
167
|
+
prefixes: ruleSet.prefixes, warnings, context, data, given,
|
|
168
|
+
};
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
// The Program of a compiled rule set's parts, each on the line its text
|
|
172
|
+
// would start on; null when a part's text is not plain statements.
|
|
173
|
+
function nativeProgram(parts) {
|
|
174
|
+
const sources = [];
|
|
175
|
+
let line = 1;
|
|
176
|
+
for (const part of parts) {
|
|
177
|
+
if (typeof part === 'string') {
|
|
178
|
+
const stated = part === '' || part.startsWith('// ') && !part.includes('\n') ? [] : statementSources(part, line);
|
|
179
|
+
if (stated === null) return null;
|
|
180
|
+
for (const item of stated) sources.push(item);
|
|
181
|
+
line += part.split('\n').length;
|
|
182
|
+
} else {
|
|
183
|
+
for (const item of part.sources(line)) sources.push(item);
|
|
184
|
+
line++;
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
return new Program(sources);
|
|
137
188
|
}
|
|
138
189
|
|
|
139
190
|
// Clock and entropy are inputs captured once when the rule set is compiled.
|
|
@@ -192,6 +243,35 @@ class Terms {
|
|
|
192
243
|
}
|
|
193
244
|
}
|
|
194
245
|
|
|
246
|
+
// The same RDF terms, made directly: what the text of Terms reads as.
|
|
247
|
+
class NativeTerms {
|
|
248
|
+
constructor(scope) {
|
|
249
|
+
this.scope = scope;
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
term(t) {
|
|
253
|
+
switch (t.type) {
|
|
254
|
+
case 'iri': return new Struct('iri', [t.value]);
|
|
255
|
+
case 'blank': return new Struct('bnode', [this.scope, t.value]);
|
|
256
|
+
case 'literal': return literalTerm(t);
|
|
257
|
+
case 'triple': return new Struct('triple', [this.term(t.s), this.term(t.p), this.term(t.o)]);
|
|
258
|
+
default: throw new SrlError(`a ${t.type} cannot appear in data`);
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
rdf(t, name) {
|
|
263
|
+
return new Struct(name, [this.term(t.s), this.term(t.p), this.term(t.o)]);
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
function literalTerm(t) {
|
|
268
|
+
if (t.lang) return new Struct('literal', [String(t.value), new Struct('lang', t.langDir ? [t.lang, t.langDir] : [t.lang])]);
|
|
269
|
+
const datatype = t.datatype || `${XSD}string`;
|
|
270
|
+
const lexical = t.lexical ?? String(t.value);
|
|
271
|
+
if (datatype === `${XSD}integer` && /^(?:0|-?[1-9][0-9]*)$/.test(lexical)) return BigInt(lexical);
|
|
272
|
+
return new Struct('literal', [lexical, new Struct('datatype', [datatype])]);
|
|
273
|
+
}
|
|
274
|
+
|
|
195
275
|
// A literal: an xsd:integer with a canonical lexical form is an integer,
|
|
196
276
|
// any other literal keeps its lexical form and datatype or language tag.
|
|
197
277
|
function literalText(t) {
|
|
@@ -260,6 +340,41 @@ class RuleCompiler {
|
|
|
260
340
|
return [...this.helpers, ...out];
|
|
261
341
|
}
|
|
262
342
|
|
|
343
|
+
// A rule of triple patterns whose head has no blank node and only
|
|
344
|
+
// predicates that are IRIs is one clause, made directly with terms: the
|
|
345
|
+
// conclusion and body of the statement compile() writes. Null for another
|
|
346
|
+
// rule.
|
|
347
|
+
plain(terms) {
|
|
348
|
+
const { rule } = this;
|
|
349
|
+
if (rule.head.length === 0 || !rule.body.every((c) => c.type === 'triple')) return null;
|
|
350
|
+
const predicates = new Set(rule.body.filter((c) => c.triple.p.type === 'var').map((c) => c.triple.p.value));
|
|
351
|
+
if (rule.head.some((t) => (t.p.type === 'var' && !predicates.has(t.p.value)) || hasBlank(t))) return null;
|
|
352
|
+
const scope = new Scope(this, null, rule.groundData ? 'base' : 'rdf');
|
|
353
|
+
const vars = new Map();
|
|
354
|
+
// Names in the order compile() gives them: body terms bind, head terms do not.
|
|
355
|
+
const term = (t, binds) => {
|
|
356
|
+
if (t.type === 'var') {
|
|
357
|
+
if (binds) scope.bind(t.value);
|
|
358
|
+
const name = scope.name(t.value);
|
|
359
|
+
let v = vars.get(name);
|
|
360
|
+
if (v === undefined) vars.set(name, v = new Var(name));
|
|
361
|
+
return v;
|
|
362
|
+
}
|
|
363
|
+
if (t.type === 'triple') return new Struct('triple', [term(t.s, binds), term(t.p, binds), term(t.o, binds)]);
|
|
364
|
+
return terms.term(t);
|
|
365
|
+
};
|
|
366
|
+
try {
|
|
367
|
+
const body = rule.body.map(({ triple: t }) => new Struct(scope.graph, [term(t.s, true), term(t.p, true), term(t.o, true)]));
|
|
368
|
+
const heads = rule.head.flatMap((t) => {
|
|
369
|
+
const args = [term(t.s, false), term(t.p, false), term(t.o, false)];
|
|
370
|
+
return [new Struct('rdf', args), new Struct('inf', [...args])];
|
|
371
|
+
});
|
|
372
|
+
return [conjunction(heads), body.length ? [conjunction(body)] : ['true']];
|
|
373
|
+
} catch {
|
|
374
|
+
return null; // compile() reports it
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
|
|
263
378
|
fresh(hint) {
|
|
264
379
|
let base = hint.replace(/[^A-Za-z0-9_]/g, '_');
|
|
265
380
|
if (/^[a-z]/.test(base)) base = base[0].toUpperCase() + base.slice(1);
|
|
@@ -642,6 +757,11 @@ class Scope {
|
|
|
642
757
|
}
|
|
643
758
|
}
|
|
644
759
|
|
|
760
|
+
function hasBlank(t) {
|
|
761
|
+
if (t.type === 'blank') return true;
|
|
762
|
+
return (t.type === 'triple' || t.s !== undefined) && [t.s, t.p, t.o].some(hasBlank);
|
|
763
|
+
}
|
|
764
|
+
|
|
645
765
|
function collectClauseVars(clauses, out) {
|
|
646
766
|
const term = (t) => {
|
|
647
767
|
if (!t) return;
|
|
@@ -675,32 +795,43 @@ export const SRL_LIMITS = { maxDepth: 1000000, maxIterations: 100000, maxInferen
|
|
|
675
795
|
// inference graph's, and with proof, result.proof is eyemind's checked
|
|
676
796
|
// proof of the compiled program.
|
|
677
797
|
export function reasonSrl(text, { base = null, filename = '<input>', resolve = null, data = [], all = false, limits = {}, proof = false, context = null } = {}) {
|
|
678
|
-
const
|
|
679
|
-
const result = run(loadText(program, 'compiled.js'), { ...SRL_LIMITS, ...limits, proof });
|
|
680
|
-
|
|
798
|
+
const compiled = compileSrl(text, { base, filename, resolve, data, context });
|
|
799
|
+
const result = run(compiled.nativeProgram ?? loadText(compiled.program, 'compiled.js'), { ...SRL_LIMITS, ...limits, proof });
|
|
800
|
+
const { prefixes, warnings, context: execution } = compiled;
|
|
801
|
+
return { quads: srlQuads(compiled, srlAnswers(result), { all }), get program() { return compiled.program; }, prefixes, warnings, result, context: execution };
|
|
681
802
|
}
|
|
682
803
|
|
|
804
|
+
// A run's answers as terms when they are ground, as forward conclusions
|
|
805
|
+
// over RDF are; otherwise as text, which names their variables.
|
|
806
|
+
export const srlAnswers = (result) => (result.conclusions?.every((term) => isGround(term)) ? result.conclusions : result.answers);
|
|
807
|
+
|
|
683
808
|
// The inference graph of a run's answers, as quads in the default graph:
|
|
684
|
-
// the rule set's DATA triples, then the derived ones.
|
|
685
|
-
//
|
|
809
|
+
// the rule set's DATA triples, then the derived ones. program is a compiled
|
|
810
|
+
// rule set or its text, answers are terms or their text. With all, the base
|
|
811
|
+
// graph comes first.
|
|
686
812
|
export function srlQuads(program, answers, { all = false } = {}) {
|
|
687
813
|
const seen = new Set();
|
|
688
814
|
const out = [];
|
|
689
815
|
const add = (terms, name) => {
|
|
690
816
|
for (const t of terms) {
|
|
691
817
|
if (!(t instanceof Struct) || t.name !== name || t.args.length !== 3) continue;
|
|
692
|
-
const key =
|
|
818
|
+
const key = identity(new Struct('t', t.args));
|
|
693
819
|
if (seen.has(key)) continue;
|
|
694
820
|
seen.add(key);
|
|
695
821
|
out.push([...t.args, DEFAULT_GRAPH]);
|
|
696
822
|
}
|
|
697
823
|
};
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
824
|
+
if (typeof program !== 'string') {
|
|
825
|
+
if (all) add(program.data.map(([S, P, O]) => new Struct('base', [S, P, O])), 'base');
|
|
826
|
+
add(program.given, 'inf');
|
|
827
|
+
} else {
|
|
828
|
+
const lines = program.split('\n');
|
|
829
|
+
if (all) {
|
|
830
|
+
const line = lines.find((l) => l.startsWith('facts_from({ text: '));
|
|
831
|
+
if (line) add(readTerms(JSON.parse(line.slice('facts_from({ text: '.length, -' })'.length))).map(([t]) => t), 'base');
|
|
832
|
+
}
|
|
833
|
+
add(readTerms(lines.filter((l) => l.startsWith('fact(rdf(') && l.includes(', inf(')).join('\n')).map(([t]) => t.args[1]), 'inf');
|
|
702
834
|
}
|
|
703
|
-
add(
|
|
704
|
-
add(answers.map((a) => readTerms(a)[0][0]), 'inf');
|
|
835
|
+
add(answers.map((a) => (typeof a === 'string' ? readTerms(a)[0][0] : a)), 'inf');
|
|
705
836
|
return out;
|
|
706
837
|
}
|
package/src/terms.js
CHANGED
|
@@ -483,12 +483,14 @@ export function identity(term) {
|
|
|
483
483
|
}
|
|
484
484
|
|
|
485
485
|
// The key an argument index files a term under: an atom or a number is its
|
|
486
|
-
// own key, and
|
|
486
|
+
// own key, an IRI uses its string, and another small ground compound the text
|
|
487
487
|
// of its structure. Signed zeros share a key, as they unify. A variable, a
|
|
488
488
|
// compound holding one, or one of more than INDEX_NODES nodes has none and
|
|
489
489
|
// constrains nothing. A key is only a filter, so an atom whose text happens
|
|
490
490
|
// to equal a compound's key could at most add candidates, never lose one.
|
|
491
491
|
const INDEX_NODES = 64;
|
|
492
|
+
// Only variable-free terms have a key independent of later bindings.
|
|
493
|
+
const indexKeys = new WeakMap();
|
|
492
494
|
|
|
493
495
|
export function indexKey(term, env = null) {
|
|
494
496
|
if (term instanceof Var) {
|
|
@@ -497,12 +499,20 @@ export function indexKey(term, env = null) {
|
|
|
497
499
|
if (term instanceof Var) return undefined;
|
|
498
500
|
}
|
|
499
501
|
if (!(term instanceof Struct)) return term;
|
|
502
|
+
if (term.name === 'iri' && term.args.length === 1) {
|
|
503
|
+
const value = env === null ? term.args[0] : deref(term.args[0], env);
|
|
504
|
+
if (typeof value === 'string') return value;
|
|
505
|
+
}
|
|
506
|
+
const known = indexKeys.get(term);
|
|
507
|
+
if (known !== undefined) return known;
|
|
500
508
|
const out = ['\u0000k'];
|
|
501
509
|
const pending = [term];
|
|
502
510
|
let nodes = 0;
|
|
511
|
+
let ground = true;
|
|
503
512
|
while (pending.length) {
|
|
504
513
|
let item = pending.pop();
|
|
505
514
|
if (item instanceof Var) {
|
|
515
|
+
ground = false;
|
|
506
516
|
if (env === null) return undefined;
|
|
507
517
|
item = deref(item, env);
|
|
508
518
|
if (item instanceof Var) return undefined;
|
|
@@ -519,7 +529,9 @@ export function indexKey(term, env = null) {
|
|
|
519
529
|
out.push('f', String(item));
|
|
520
530
|
}
|
|
521
531
|
}
|
|
522
|
-
|
|
532
|
+
const result = out.join('\u0001');
|
|
533
|
+
if (ground) indexKeys.set(term, result);
|
|
534
|
+
return result;
|
|
523
535
|
}
|
|
524
536
|
|
|
525
537
|
// The variables of a term by name, in order of first appearance.
|
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.19';
|
package/src/writer.js
CHANGED
|
@@ -91,6 +91,7 @@ const ESCAPES = { '\\': '\\\\', "'": "\\'", '\n': '\\n', '\r': '\\r', '\t': '\\t
|
|
|
91
91
|
// separators and lone surrogates are escaped; any other character is written
|
|
92
92
|
// as it is.
|
|
93
93
|
export function quote(text) {
|
|
94
|
+
if (!/['\\\u0000-\u001f\u007f-\u009f\u2028\u2029\ud800-\udfff]/.test(text)) return `'${text}'`;
|
|
94
95
|
let out = "'";
|
|
95
96
|
for (let i = 0; i < text.length; i++) {
|
|
96
97
|
const ch = text[i];
|