-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathselector.peg
378 lines (356 loc) · 14.7 KB
/
selector.peg
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
{
const MODE_NORMAL = 0;
const MODE_STRICT = 1;
const MODE_LENIENT = 2;
const PROHIBITED_KEYS = [ 'constructor', 'prototype', '__proto__', '__defineGetter__', '__lookupGetter__', '__defineSetter__', '__lookupSetter__' ]
}
Union_Selector = selectors:Selector|1.., _* Union_Operator _*| {
return Object.assign(function union(obj, references, mode, safe) {
// For some reason, this is WAY faster than doing selectors.flatMap():
let result = selectors[0](obj, references, mode, safe); // This is safe, because the grammar guarantees there is at least one selector
for (let i = 1; i < selectors.length; i++)
result = result.concat(selectors[i](obj, references, mode, safe));
return result;
}, {
// The selector is ambiguous if it is a union of more than one selectors,
// or if there is only one selector and that selector is ambiguous itself
ambiguous: selectors.length > 1 || selectors[0].ambiguous,
source: text()
});
};
Union_Operator = ",";
/*
* A selector is either the empty selector, or a series of property descriptors separated by the accessor operator ('.')
*/
Selector
= Empty_selector /
selector:(head:Property_descriptor tail:Accessor_selector* {
return head // head: property descriptors are parsed as arrays (because they might include conditions)
.concat(tail.flat()); // tail: the tail is an array of Accessor_selectors because of the asterisk operator
// flat(): accessor selectors are themselves arrays as well (see their parse return value)
}) {
// Return value is the function select, but we will set some meta-properties of the selector on it:
// - Whether or not the selector is ambiguous
// - The raw source text of the selector
return Object.assign(function select(obj, references, mode, safe) {
const resolution = [
{ target: obj, selection: [] }
]
resolution.root = obj;
selector?.forEach(element => element(resolution, references, mode, safe));
return resolution;
}, {
// The selector as a whole is ambiguous if at least one of its constituents is ambiguous (multi-valued)
ambiguous: selector.some(fn => fn.ambiguous),
source: text()
});
};
Empty_selector
= &{ return input === '' } {
console.warn('Using the empty selector is deprecated. Use ::root instead.');
return Object.assign(function empty(obj) {
return [ { target: { obj }, selection: [ 'obj' ] } ];
}, {
ambiguous: false,
source: text()
});
}
Accessor_selector
= accessor:Accessor property:Property_descriptor {
property.unshift(accessor); // Faster than [ accessor, ...property ]
return property;
};
Accessor
= _* "." _* {
return function access(resolution) {
let result = [];
for (let item of resolution) {
result = result.concat(item.selection.map(property => ({
target: item.target[property],
selection: []
})));
}
// Rebuild resolution in-place:
// (This is faster than doing resolution.splice() or pushing each result item to an empty array)
resolution.length = result.length;
for (let i = 0; i < result.length; i++) resolution[i] = result[i];
}
};
/*
* A property descriptor is a property name (which may include wildcards, see below) optionally followed by
* a series of conditions.
*/
Property_descriptor
= property:Property_name _* meta:Meta_property* _* condition:Condition* {
// This is faster than doing [ property, ...condition, validate ]
meta.unshift(property);
meta = meta.concat(condition);
meta.push(
function validate(resolution, references, mode = MODE_NORMAL) {
// Helper function that checks whether the target has a property of a given name
// Returns false if the target is null or undefined or a primitive,
// otherwise checks whether the property is an own OR INHERITED property
// (accessor properties are defined on the prototype and would not be caught by hasOwnProperty)
function hasProperty(tgt, prop) {
if (!tgt) return false;
else if (typeof tgt === 'object') return prop in tgt
else return false;
}
if (mode) {
// Run through the current resolutions backwards, because we may be changing them
for (let i = resolution.length - 1; i >= 0; i--) {
// There is an "invalid" resolution if
// - no matching selections were found (see below)
// - or a set selection does not exist on the target
for (let j = resolution[i].selection.length - 1; j >= 0; j--) {
if (!hasProperty(resolution[i].target, resolution[i].selection[j])) {
switch(mode) {
// In strict mode, throw an error
case MODE_STRICT: throw new TypeError(`Object has no properties matching ${text()}`);
// In lenient mode, remove the offending selection
case MODE_LENIENT: resolution[i].selection.splice(j, 1);
}
}
}
// If after removing all offending selections none are left, remove the entire resolution in lenient
// mode or throw in strict mode
if (resolution[i].selection.length === 0)
switch (mode) {
case MODE_STRICT: throw new TypeError(`Object has no properties matching ${text()}`)
case MODE_LENIENT: resolution.splice(i, 1);
}
}
}
});
return meta;
};
/*
* A property name is an identifier, or a property name with wildcards.
*/
Property_name
= regex:Property_name_with_wildcard {
// Wildcard selectors are always ambiguous
return Object.assign(function selectByRegex(resolution, references, mode, safe) {
for (let item of resolution) {
if (mode === MODE_LENIENT && item.target == null)
item.selection = [];
else {
if (item.target == undefined) throw new TypeError(`Cannot select ambiguously on ${item.target}`);
item.selection = [];
for (const key in item.target)
if (regex.test(key))
item.selection.push(key)
}
}
}, { ambiguous: true });
}
/ name:Identifier {
return function selectByName(resolution, references, mode, safe) {
if (safe && PROHIBITED_KEYS.includes(name))
throw new Error(`Unsafe access on ${resolution.root}: tried to access prohibited key ${name}`);
resolution.forEach(item => item.selection = [ name ]);
}
}
/ pseudo:Pseudo_Property {
function selectRoot(resolution) {
resolution.forEach(item => {
item.target = { '::root': resolution.root };
item.selection = [ '::root' ];
});
}
function selectFirst(resolution) {
resolution.forEach(item => {
if (Array.isArray(item.target) || typeof item.target === 'string')
item.selection = [ '0' ];
else if (typeof item.target === 'object' && item.target !== null)
// We have to do this via a for...in loop that we break from immediately,
// in order to catch INHERITED properties as well as own
for (let key in item.target) {
item.selection = [ key ];
break;
}
else
item.selection = [];
});
}
function selectLast(resolution) {
resolution.forEach(item => {
if (Array.isArray(item.target) || typeof item.target === 'string')
item.selection = [ String(item.target.length - 1) ];
else if (typeof item.target === 'object' && item.target !== null)
// We have to do this via a for...in loop that we break from immediately,
// in order to catch INHERITED properties as well as own
for (let key in item.target) {
item.selection = [ key ];
}
else
item.selection = [];
});
}
const PSEUDO_PROPERTIES = {
'::root': selectRoot,
'::first': selectFirst,
'::last': selectLast
}
return PSEUDO_PROPERTIES[pseudo];
}
/*
* Meta properties are virtual properties describing the characteristics of actual properties. They are similar to conditions in that
* they constrain previously selected properties. They are similar to CSS pseudo-classes.
*/
Meta_property
= ":" meta:("string" / "number" / "bigint" / "boolean" / "undefined" / "symbol" / "null" / "primitive" / "object" / "array" / "complex" / "existent" / "nonexistent" / "unique") {
// Helper function to create the type-selection function that filters out values for which the typeguard predicate is true
function createSelectFunction(typeguard) {
return function selectByType(resolution, references, mode) {
for (let item of resolution) {
for (let i = 0; i < item.selection.length; i++) {
if (typeguard(item.target[item.selection[i]]))
delete item.selection[i];
}
item.selection = item.selection.filter(sel => sel !== undefined);
}
}
}
const PRIMITIVES = [ 'string', 123, 123n, true, undefined, Symbol(), null ]
switch (meta) {
case 'string': return createSelectFunction(subject => typeof subject !== 'string');
case 'number': return createSelectFunction(subject => typeof subject !== 'number');
case 'bigint': return createSelectFunction(subject => typeof subject !== 'bigint');
case 'boolean': return createSelectFunction(subject => typeof subject !== 'boolean');
case 'undefined': return createSelectFunction(subject => typeof subject !== 'undefined');
case 'symbol': return createSelectFunction(subject => typeof subject !== 'symbol');
case 'null': return createSelectFunction(subject => subject !== null);
case 'primitive': return createSelectFunction(subject => typeof subject === 'object' && subject !== null);
case 'object': return createSelectFunction(subject => typeof subject !== 'object' || subject === null || Array.isArray(subject));
case 'array': return createSelectFunction(subject => !Array.isArray(subject));
case 'complex': return createSelectFunction(subject => typeof subject !== 'object' || subject === null);
case 'existent': return createSelectFunction(subject => subject == undefined);
case 'nonexistent': return createSelectFunction(subject => subject != undefined);
case 'unique':
return function selectUnique(resolution, references, mode) {
// Run through the resolutions and for all selections, remove any duplicates, as determined by the comparator function.
//
// For this, only check items' selections that come AFTER the current one, e.g. given the following resolutions:
// a b
// 0 1 2 0 1 a0 a1 a2 b0 b2
// ^ ^
// | |
// when (i,j) are here...
// ...start (k,l) checking from here
for (let i = 0; i < resolution.length; i++)
for (let j = 0; j < resolution[i].selection.length; j++)
for (let k = i; k < resolution.length; k++) {
for (let l = k === i ? j + 1 : 0; l < resolution[k].selection.length; l++) {
const a = resolution[i].target[resolution[i].selection[j]];
const b = resolution[k].target[resolution[k].selection[l]];
if (b !== undefined && a === b)
// Just delete for now, because that is faster than repeated splicing.
// We will remove all deleted entries at the end.
delete resolution[k].selection[l];
}
resolution[k].selection = resolution[k].selection.filter(sel => sel !== undefined);
}
}
}
}
/*
* A condition is a unary condition or a binary condition, enclosed in square brackets.
* There may be whitespace between the opening and closing brackets and the actual condition expression.
*/
Condition
= "[" _* condition:(UnaryCondition / BinaryCondition) _* "]" {
return function selectByCondition(resolution, references, mode) {
const { selector, operator, valueFn } = condition;
const value = valueFn(references);
for (let item of resolution)
item.selection = item.selection.filter(selectedProperty => {
// Normalize condition selector from tuples (target, multiple selections) to
// (target, single selection)
const conditionProperties = selector(item.target[selectedProperty], references, mode)
.flatMap(({ target, selection }) => selection.map(conditionProperty => ({ target, conditionProperty })));
return conditionProperties.length > 0 && conditionProperties.every(({ target, conditionProperty }) => operator(target[conditionProperty], value));
});
}
};
/*
* A unary condition is a condition that does not have an operator and a value.
* It consists only of a property name.
*/
UnaryCondition
= !BinaryCondition selector:Selector {
return { selector, operator: Boolean, valueFn: () => null };
};
/*
* A binary condition is a condition that has an operator and a value.
* It is of the form <property> <operator> <value>, where <operator> may be one of the
* following: ===, ==, !==, !=, $=, ^=, ~=, <, >=, <=, or <
*/
BinaryCondition
= selector:Selector _* operator:Operator _* valueFn:Value {
if (operator.name === '~=') {
let _valueFn = valueFn;
valueFn = references => new RegExp(_valueFn(references));
}
return { selector, operator, valueFn };
};
Operator
= operator:("===" / "==" / "!==" / "!=" / "$=" / "^=" / "~=" / ">=" / "<=" / ">" / "<") {
return {
'==': (a,b) => a == b,
'===': (a,b) => a === b,
'!=': (a,b) => a != b,
'!==': (a,b) => a !== b,
'$=': (a,b) => a?.endsWith(b),
'^=': (a,b) => a?.startsWith(b),
'~=': (a,b) => b.test(a),
'>': (a,b) => a > b,
'>=': (a,b) => a >= b,
'<=': (a,b) => a <= b,
'<': (a,b) => a < b
}[operator];
}
Value = ReferenceValue / LiteralValue;
ReferenceValue
= Reference_character reference:Identifier {
// Return a function that resolves the reference against the passed references object
return references => references[reference];
};
Reference_character = "@";
LiteralValue
= identifier: Identifier {
// Return a constant function that returns identifier, so as to present the same interface as a reference value
return () => identifier;
};
Identifier
= symbols:Symbol+ { return symbols.join(''); };
// Can't just do $Symbol because then we lose the ability to ignore the escape character
/*
* A property name is, conceptually, a series of identifiers separated by single wildcards, with an optional single
* wildcard at the beginning and the end. There must be at least one wildcard.
*/
Property_name_with_wildcard =
&(Identifier? Wildcard) // Make sure there is at least one wildcard to avoid ambiguity with rule Identifier
descriptor:(Wildcard? (Identifier Wildcard?)* Wildcard?)
{ return new RegExp('^' + descriptor.flat(Infinity).join('') + '$') };
Wildcard
= !"**" // Series of wildcards are allowed except series of asterisks
wildcard:("*" / "?") {
switch (wildcard) {
case '*': return '\\w*';
case '?': return '\\w';
}
}
Pseudo_Property = "::root" / "::first" / "::last";
Permitted_character
= [A-Za-z0-9_];
Reserved_character
= $(Accessor / "+" / "[" / "]" / ":" / Wildcard / Escape_character / Reference_character / Operator / Union_Operator / _);
Escape_character
= "\\";
/* A Symbol is a permitted character, or an escaped reserved character */
Symbol
= Escape_character char:Reserved_character { return char; }
/ Permitted_character;
_ "whitespace"
= [ \t\n] { return; }