forked from shexjs/shex.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patheval-threaded-nerr.js
438 lines (417 loc) · 17.3 KB
/
eval-threaded-nerr.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
const EvalThreadedNErrCjsModule = (function () {
const ShExTerm = require("@shexjs/term");
const UNBOUNDED = -1;
function vpEngine (schema, shape, index) {
const outerExpression = shape.expression;
return {
match:match
};
function match (graph, node, constraintList, constraintToTripleMapping, tripleToConstraintMapping, neighborhood, semActHandler, trace) {
/*
* returns: list of passing or failing threads (no heterogeneous lists)
*/
function validateExpr (expr, thread) {
if (typeof expr === "string") { // Inclusion
const included = index.tripleExprs[expr];
return validateExpr(included, thread);
}
const constraintNo = constraintList.indexOf(expr);
let min = "min" in expr ? expr.min : 1;
let max = "max" in expr ? expr.max === UNBOUNDED ? Infinity : expr.max : 1;
function validateRept (type, val) {
let repeated = 0, errOut = false;
let newThreads = [thread];
const minmax = { };
if ("min" in expr && expr.min !== 1 || "max" in expr && expr.max !== 1) {
minmax.min = expr.min;
minmax.max = expr.max;
}
if ("semActs" in expr)
minmax.semActs = expr.semActs;
if ("annotations" in expr)
minmax.annotations = expr.annotations;
for (; repeated < max && !errOut; ++repeated) {
let inner = [];
for (let t = 0; t < newThreads.length; ++t) {
const newt = newThreads[t];
const sub = val(newt);
if (sub.length > 0 && sub[0].errors.length === 0) { // all subs pass or all fail
sub.forEach(newThread => {
const solutions =
"expression" in newt ? newt.expression.solutions.slice() : [];
if ("solution" in newThread)
solutions.push(newThread.solution);
delete newThread.solution;
newThread.expression = extend({
type: type,
solutions: solutions
}, minmax);
});
}
if (sub.length === 0 /* min:0 */ || sub[0].errors.length > 0)
return repeated < min ? sub : newThreads;
else
inner = inner.concat(sub);
// newThreads.expressions.push(sub);
}
newThreads = inner;
}
if (newThreads.length > 0 && newThreads[0].errors.length === 0 && "semActs" in expr) {
const passes = [];
const failures = [];
newThreads.forEach(newThread => {
const semActErrors = semActHandler.dispatchAll(expr.semActs, "???", newThread)
if (semActErrors.length === 0) {
passes.push(newThread)
} else {
[].push.apply(newThread.errors, semActErrors);
failures.push(newThread);
}
});
newThreads = passes.length > 0 ? passes : failures;
}
return newThreads;
}
if (expr.type === "TripleConstraint") {
const negated = "negated" in expr && expr.negated || max === 0;
if (negated)
min = max = Infinity;
if (thread.avail[constraintNo] === undefined)
thread.avail[constraintNo] = constraintToTripleMapping[constraintNo].map(pair => pair.tNo);
const minmax = { };
if ("min" in expr && expr.min !== 1 || "max" in expr && expr.max !== 1) {
minmax.min = expr.min;
minmax.max = expr.max;
}
if ("semActs" in expr)
minmax.semActs = expr.semActs;
if ("annotations" in expr)
minmax.annotations = expr.annotations;
const taken = thread.avail[constraintNo].splice(0, min);
const passed = negated ? taken.length === 0 : taken.length >= min;
const ret = [];
const matched = thread.matched;
if (passed) {
do {
const passFail = taken.reduce((acc, tripleNo) => {
const t = neighborhood[tripleNo]
const tested = {
type: "TestedTriple",
subject: t.subject,
predicate: t.predicate,
object: ldify(t.object)
}
const hit = constraintToTripleMapping[constraintNo].find(x => x.tNo === tripleNo);
if (hit.res && Object.keys(hit.res).length > 0)
tested.referenced = hit.res;
const semActErrors = thread.errors.concat(
"semActs" in expr
? semActHandler.dispatchAll(expr.semActs, tested, tested)
: []
)
if (semActErrors.length > 0)
acc.fail.push({tripleNo, tested, semActErrors})
else
acc.pass.push({tripleNo, tested, semActErrors})
return acc
}, {pass: [], fail: []})
// return an empty solution if min card was 0
if (passFail.fail.length === 0) {
// If we didn't take anything, fall back to old errors.
// Could do something fancy here with a semAct registration for negative matches.
const totalErrors = taken.length === 0 ? thread.errors.slice() : []
const myThread = makeThread(passFail.pass, totalErrors)
ret.push(myThread);
} else {
passFail.fail.forEach(
f => ret.push(makeThread([f], f.semActErrors))
)
}
function makeThread (tests, errors) {
return {
avail: thread.avail.map(a => { // copy parent thread's avail vector
return a.slice();
}),
errors: errors,
matched: matched.concat({
tNos: tests.map(p => p.tripleNo)
}),
expression: extend(
{
type: "TripleConstraintSolutions",
predicate: expr.predicate
},
"valueExpr" in expr ? { valueExpr: expr.valueExpr } : {},
"id" in expr ? { productionLabel: expr.id } : {},
minmax,
{
solutions: tests.map(p => p.tested)
}
)
}
}
} while ((function () {
if (thread.avail[constraintNo].length > 0 && taken.length < max) {
// build another thread.
taken.push(thread.avail[constraintNo].shift());
return true;
} else {
// no more threads
return false;
}
})());
} else {
let valueExpr = null;
if (typeof expr.valueExpr === "string") { // ShapeRef
valueExpr = expr.valueExpr;
if (ShExTerm.isBlank(valueExpr))
valueExpr = index.shapeExprs[valueExpr];
} else if (expr.valueExpr) {
valueExpr = extend({}, expr.valueExpr)
}
ret.push({
avail: thread.avail,
errors: thread.errors.concat([
extend({
type: negated ? "NegatedProperty" : "MissingProperty",
property: expr.predicate
}, valueExpr ? { valueExpr: valueExpr } : {})
]),
matched: matched
});
}
return ret;
}
else if (expr.type === "OneOf") {
return validateRept("OneOfSolutions", (th) => {
// const accept = null;
const matched = [];
const failed = [];
expr.expressions.forEach(nested => {
const thcopy = {
avail: th.avail.map(a => { return a.slice(); }),
errors: th.errors,
matched: th.matched//.slice() ever needed??
};
const sub = validateExpr(nested, thcopy);
if (sub[0].errors.length === 0) { // all subs pass or all fail
[].push.apply(matched, sub);
sub.forEach(newThread => {
const expressions =
"solution" in thcopy ? thcopy.solution.expressions : [];
if ("expression" in newThread) // undefined for no matches on min card:0
expressions.push(newThread.expression);
delete newThread.expression;
newThread.solution = {
type: "OneOfSolution",
expressions: expressions
};
});
} else
[].push.apply(failed, sub);
});
return matched.length > 0 ? matched : failed;
});
}
else if (expr.type === "EachOf") {
return homogenize(validateRept("EachOfSolutions", (th) => {
// Iterate through nested expressions, exprThreads starts as [th].
return expr.expressions.reduce((exprThreads, nested) => {
// Iterate through current thread list composing nextThreads.
// Consider e.g.
// <S1> { <p1> . | <p2> .; <p3> . } / { <x> <p2> 2; <p3> 3 } (should pass)
// <S1> { <p1> .; <p2> . } / { <s1> <p1> 1 } (should fail)
return homogenize(exprThreads.reduce((nextThreads, exprThread) => {
const sub = validateExpr(nested, exprThread);
// Move newThread.expression into a hierarchical solution structure.
sub.forEach(newThread => {
if (newThread.errors.length === 0) {
const expressions =
"solution" in exprThread ? exprThread.solution.expressions.slice() : [];
if ("expression" in newThread) // undefined for no matches on min card:0
expressions.push(newThread.expression);
delete newThread.expression;
newThread.solution = {
type: "EachOfSolution",
expressions: expressions // exprThread.expression + newThread.expression
};
}
});
return nextThreads.concat(sub);
}, []));
}, [th]);
}));
}
runtimeError("unexpected expr type: " + expr.type);
function homogenize (list) {
return list.reduce((acc, elt) => {
if (elt.errors.length === 0) {
if (acc.errors) {
return { errors: false, l: [elt] };
} else {
return { errors: false, l: acc.l.concat(elt) };
}
} else {
if (acc.errors) {
return { errors: true, l: acc.l.concat(elt) };
} else {
return acc; }
}
}, {errors: true, l: []}).l;
}
}
const startingThread = {
avail:[], // triples remaining by constraint number
matched:[], // triples matched in this thread
errors:[] // errors encounted
};
if (!outerExpression)
return { }; // vapid match if no expression
const ret = validateExpr(outerExpression, startingThread);
// console.log(JSON.stringify(ret));
// note: don't return if ret.length === 1 because it might fail the unmatchedTriples test.
const longerChosen =
ret.reduce((ret, elt) => {
if (elt.errors.length > 0)
return ret; // early return
const unmatchedTriples = {};
// Collect triples assigned to some constraint.
Object.keys(tripleToConstraintMapping).forEach(k => {
if (tripleToConstraintMapping[k] !== "NO_TRIPLE_CONSTRAINT")
unmatchedTriples[k] = tripleToConstraintMapping[k];
});
// Removed triples matched in this thread.
elt.matched.forEach(m => {
m.tNos.forEach(t => {
delete unmatchedTriples[t];
});
});
// Remaining triples are unaccounted for.
Object.keys(unmatchedTriples).forEach(t => {
elt.errors.push({
type: "ExcessTripleViolation",
triple: neighborhood[t],
constraint: constraintList[unmatchedTriples[t]]
});
});
return ret !== null ? ret : // keep first solution
// Accept thread with no unmatched triples.
Object.keys(unmatchedTriples).length > 0 ? null : elt;
}, null);
return longerChosen !== null ?
finish(longerChosen.expression, constraintList,
neighborhood, semActHandler) :
ret.length > 1 ? {
type: "PossibleErrors",
errors: ret.reduce((all, e) => {
return all.concat([e.errors]);
}, [])
} : ret[0];
}
function ldify (term) {
if (term[0] !== "\"")
return term;
const ret = { value: ShExTerm.getLiteralValue(term) };
const dt = ShExTerm.getLiteralType(term);
if (dt &&
dt !== "http://www.w3.org/2001/XMLSchema#string" &&
dt !== "http://www.w3.org/1999/02/22-rdf-syntax-ns#langString")
ret.type = dt;
const lang = ShExTerm.getLiteralLanguage(term)
if (lang)
ret.language = lang;
return ret;
}
function finish (fromValidatePoint, constraintList, neighborhood, semActHandler) {
function _dive (solns) {
if (solns.type === "OneOfSolutions" ||
solns.type === "EachOfSolutions") {
solns.solutions.forEach(s => {
s.expressions.forEach(e => {
_dive(e);
});
});
} else if (solns.type === "TripleConstraintSolutions") {
solns.solutions = solns.solutions.map(x => {
if (x.type === "TestedTriple") // already done
return x; // c.f. validation/3circularRef1_pass-open
const t = neighborhood[x.tripleNo];
const expr = constraintList[x.constraintNo];
const ret = {
type: "TestedTriple", subject: t.subject, predicate: t.predicate, object: ldify(t.object)
};
function diver (focus, shapeLabel, dive) {
const sub = dive(focus, shapeLabel);
if ("errors" in sub) {
// console.dir(sub);
const err = {
type: "ReferenceError", focus: focus,
shape: shapeLabel
};
if (typeof shapeLabel === "string" && ShExTerm.isBlank(shapeLabel))
err.referencedShape = shape;
err.errors = sub;
return [err];
}
if (("solution" in sub || "solutions" in sub)&& Object.keys(sub.solution || sub.solutions).length !== 0 ||
sub.type === "Recursion")
ret.referenced = sub; // !!! needs to aggregate errors and solutions
return [];
}
function diveRecurse (focus, shapeLabel) {
return diver(focus, shapeLabel, recurse);
}
function diveDirect (focus, shapeLabel) {
return diver(focus, shapeLabel, direct);
}
const subErrors = "valueExpr" in expr ?
checkValueExpr(expr.inverse ? t.subject : t.object, expr.valueExpr, diveRecurse, diveDirect) :
[];
if (subErrors.length === 0 && "semActs" in expr)
[].push.apply(subErrors, semActHandler.dispatchAll(expr.semActs, ret, ret))
if (subErrors.length > 0) {
fromValidatePoint.errors = fromValidatePoint.errors || [];
fromValidatePoint.errors = fromValidatePoint.errors.concat(subErrors);
}
return ret;
});
} else {
throw Error("unexpected expr type in " + JSON.stringify(solns));
}
}
if (Object.keys(fromValidatePoint).length > 0) // guard against {}
_dive(fromValidatePoint);
if ("semActs" in shape)
fromValidatePoint.semActs = shape.semActs;
return fromValidatePoint;
}
}
function ldify (term) {
if (term[0] !== "\"")
return term;
const ret = { value: N3Util.getLiteralValue(term) };
const dt = N3Util.getLiteralType(term);
if (dt &&
dt !== "http://www.w3.org/2001/XMLSchema#string" &&
dt !== "http://www.w3.org/1999/02/22-rdf-syntax-ns#langString")
ret.type = dt;
const lang = N3Util.getLiteralLanguage(term)
if (lang)
ret.language = lang;
return ret;
}
function extend(base) {
if (!base) base = {};
for (let i = 1, l = arguments.length, arg; i < l && (arg = arguments[i] || {}); i++)
for (let name in arg)
base[name] = arg[name];
return base;
}
return {
name: "eval-threaded-nerr",
description: "emulation of regular expression engine with error permutations",
compile: vpEngine
};
})();
if (typeof require !== "undefined" && typeof exports !== "undefined")
module.exports = EvalThreadedNErrCjsModule;