forked from estools/esquery
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathesquery.js
418 lines (378 loc) · 16.9 KB
/
esquery.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
/* vim: set sw=4 sts=4 : */
(function () {
var estraverse = require('estraverse');
var parser = require('./parser');
var isArray = Array.isArray || function isArray(array) {
return {}.toString.call(array) === '[object Array]';
};
var LEFT_SIDE = {};
var RIGHT_SIDE = {};
function esqueryModule() {
/**
* Get the value of a property which may be multiple levels down in the object.
*/
function getPath(obj, key) {
var i, keys = key.split(".");
for (i = 0; i < keys.length; i++) {
if (obj == null) { return obj; }
obj = obj[keys[i]];
}
return obj;
}
/**
* Determine whether `node` can be reached by following `path`, starting at `ancestor`.
*/
function inPath(node, ancestor, path) {
var field, remainingPath, i;
if (path.length === 0) { return node === ancestor; }
if (ancestor == null) { return false; }
field = ancestor[path[0]];
remainingPath = path.slice(1);
if (isArray(field)) {
for (i = 0, l = field.length; i < l; ++i) {
if (inPath(node, field[i], remainingPath)) { return true; }
}
return false;
} else {
return inPath(node, field, remainingPath);
}
}
/**
* Given a `node` and its ancestors, determine if `node` is matched by `selector`.
*/
function matches(node, selector, ancestry, scope) {
var path, ancestor, i, l, p;
if (!selector) { return true; }
if (!node) { return false; }
if (!ancestry) { ancestry = []; }
switch(selector.type) {
case 'wildcard':
return true;
case 'identifier':
return selector.value.toLowerCase() === node.type.toLowerCase();
case 'field':
path = selector.name.split('.');
ancestor = ancestry[path.length - 1];
return inPath(node, ancestor, path);
case 'matches':
for (i = 0, l = selector.selectors.length; i < l; ++i) {
if (matches(node, selector.selectors[i], ancestry, scope)) { return true; }
}
return false;
case 'compound':
for (i = 0, l = selector.selectors.length; i < l; ++i) {
if (!matches(node, selector.selectors[i], ancestry, scope)) { return false; }
}
return true;
case 'not':
for (i = 0, l = selector.selectors.length; i < l; ++i) {
if (matches(node, selector.selectors[i], ancestry, scope)) { return false; }
}
return true;
case 'has':
var a, collector = [], parent = ancestry[0];
for (i = 0, l = selector.selectors.length; i < l; ++i) {
a = ancestry.slice(parent ? 1 : 0);
estraverse.traverse(parent || node, {
enter: function (child, parent) {
if (parent == null) { return; }
a.unshift(parent);
if (matches(child, selector.selectors[i], a, node)) {
collector.push(child);
}
},
leave: function () { a.shift(); }
});
}
return collector.length !== 0;
case 'child':
if (matches(node, selector.right, ancestry, scope)) {
return matches(ancestry[0], selector.left, ancestry.slice(1), scope);
}
return false;
case 'descendant':
if (matches(node, selector.right, ancestry, scope)) {
for (i = 0, l = ancestry.length; i < l; ++i) {
if (matches(ancestry[i], selector.left, ancestry.slice(i + 1), scope)) {
return true;
}
}
}
return false;
case 'attribute':
p = getPath(node, selector.name);
switch (selector.operator) {
case null:
case void 0:
return p != null;
case '=':
switch (selector.value.type) {
case 'regexp': return selector.value.value.test(p);
case 'literal': return '' + selector.value.value === '' + p;
case 'type': return selector.value.value === typeof p;
}
case '!=':
switch (selector.value.type) {
case 'regexp': return !selector.value.value.test(p);
case 'literal': return '' + selector.value.value !== '' + p;
case 'type': return selector.value.value !== typeof p;
}
case '<=': return p <= selector.value.value;
case '<': return p < selector.value.value;
case '>': return p > selector.value.value;
case '>=': return p >= selector.value.value;
}
case 'sibling':
return matches(node, selector.right, ancestry, scope) &&
sibling(node, selector.left, ancestry, LEFT_SIDE, scope) ||
selector.left.subject &&
matches(node, selector.left, ancestry, scope) &&
sibling(node, selector.right, ancestry, RIGHT_SIDE, scope);
case 'adjacent':
return matches(node, selector.right, ancestry, scope) &&
adjacent(node, selector.left, ancestry, LEFT_SIDE, scope) ||
selector.right.subject &&
matches(node, selector.left, ancestry, scope) &&
adjacent(node, selector.right, ancestry, RIGHT_SIDE, scope);
case 'nth-child':
return matches(node, selector.right, ancestry, scope) &&
nthChild(node, ancestry, function (length) {
return selector.index.value - 1;
});
case 'nth-last-child':
return matches(node, selector.right, ancestry, scope) &&
nthChild(node, ancestry, function (length) {
return length - selector.index.value;
});
case 'class':
if(!node.type) return false;
switch(selector.name.toLowerCase()){
case 'statement':
if(node.type.slice(-9) === 'Statement') return true;
// fallthrough: interface Declaration <: Statement { }
case 'declaration':
return node.type.slice(-11) === 'Declaration';
case 'pattern':
if(node.type.slice(-7) === 'Pattern') return true;
// fallthrough: interface Expression <: Node, Pattern { }
case 'expression':
return node.type.slice(-10) === 'Expression' ||
node.type === 'Literal' ||
node.type === 'Identifier';
case 'function':
return node.type.slice(0, 8) === 'Function' ||
node.type === 'ArrowFunctionExpression';
}
throw new Error('Unknown class name: ' + selector.name);
case 'scope':
return scope ? node === scope : ancestry.length === 0;
case 'root':
return ancestry.length === 0;
}
throw new Error('Unknown selector type: ' + selector.type);
}
/*
* Determines if the given node has a sibling that matches the given selector.
*/
function sibling(node, selector, ancestry, side, scope) {
var parent = ancestry[0], listProp, startIndex, keys, i, l, k, lowerBound, upperBound;
if (!parent) { return false; }
keys = estraverse.VisitorKeys[parent.type];
for (i = 0, l = keys.length; i < l; ++i) {
listProp = parent[keys[i]];
if (isArray(listProp)) {
startIndex = listProp.indexOf(node);
if (startIndex < 0) { continue; }
if (side === LEFT_SIDE) {
lowerBound = 0;
upperBound = startIndex;
} else {
lowerBound = startIndex + 1;
upperBound = listProp.length;
}
for (k = lowerBound; k < upperBound; ++k) {
if (matches(listProp[k], selector, ancestry, scope)) {
return true;
}
}
}
}
return false;
}
/*
* Determines if the given node has an asjacent sibling that matches the given selector.
*/
function adjacent(node, selector, ancestry, side, scope) {
var parent = ancestry[0], listProp, keys, i, l, idx;
if (!parent) { return false; }
keys = estraverse.VisitorKeys[parent.type];
for (i = 0, l = keys.length; i < l; ++i) {
listProp = parent[keys[i]];
if (isArray(listProp)) {
idx = listProp.indexOf(node);
if (idx < 0) { continue; }
if (side === LEFT_SIDE && idx > 0 && matches(listProp[idx - 1], selector, ancestry, scope)) {
return true;
}
if (side === RIGHT_SIDE && idx < listProp.length - 1 && matches(listProp[idx + 1], selector, ancestry, scope)) {
return true;
}
}
}
return false;
}
/*
* Determines if the given node is the nth child, determined by idxFn, which is given the containing list's length.
*/
function nthChild(node, ancestry, idxFn) {
var parent = ancestry[0], listProp, keys, i, l, idx;
if (!parent) { return false; }
keys = estraverse.VisitorKeys[parent.type];
for (i = 0, l = keys.length; i < l; ++i) {
listProp = parent[keys[i]];
if (isArray(listProp)) {
idx = listProp.indexOf(node);
if (idx >= 0 && idx === idxFn(listProp.length)) { return true; }
}
}
return false;
}
/*
* For each selector node marked as a subject, find the portion of the selector that the subject must match.
*/
function subjects(selector, ancestor) {
var results, p;
if (selector == null || typeof selector != 'object') { return []; }
if (ancestor == null) { ancestor = selector; }
results = selector.subject ? [ancestor] : [];
for(p in selector) {
if(!{}.hasOwnProperty.call(selector, p)) { continue; }
[].push.apply(results, subjects(selector[p], p === 'left' ? selector[p] : ancestor));
}
return results;
}
/*
* Clones a selector AST
*/
function clone(selector) {
if (typeof selector !== 'object' || selector instanceof RegExp) {
return selector;
}
var clonedSelector = selector instanceof Array ? [] : {};
for (var key in selector) {
if (!selector.hasOwnProperty(key)) { continue; }
clonedSelector[key] = clone(selector[key]);
}
return clonedSelector;
}
/*
* Transforms this query so that subject indicators are replaced with :has selectors
*/
function transform(selector) {
var root = { },
current = selector,
previous = root,
subjects = [ ];
if (!selector) { return selector; }
while ('left' in current && 'right' in current) {
if (current.right.subject) {
previous.type = 'scope';
subjects.push([ clone(current), clone(root) ]);
}
previous.type = current.type;
previous.right = current.right;
previous = previous.left = { }
current = current.left;
}
if (current.subject) {
previous.type = 'scope';
subjects.push([ clone(current), clone(root) ]);
}
if (subjects.length === 0) {
return selector;
} else {
var matches = {
type: 'matches',
selectors: subjects.map(function (subject) {
var result = subject[0], has = {
type: 'has',
selectors: [ subject[1] ]
};
if ('right' in subject[0]) {
delete result.right.subject;
result.right = {
type: 'compound',
selectors: result.right.type === 'compound'
? result.right.selectors.concat(has)
: [ result.right, has ]
};
} else {
delete result.subject;
result = {
type: 'compound',
selectors: result.type === 'compound'
? result.selectors.concat(has)
: [ result, has ]
};
}
return result;
})
};
return matches.selectors.length === 1
? matches.selectors[0] : matches;
}
}
/**
* From a JS AST and a selector AST, collect all JS AST nodes that match the selector.
*/
function match(ast, selector) {
var ancestry = [], results = [], altSubjects, i, l, k, m;
if (!selector) { return results; }
altSubjects = subjects(selector);
estraverse.traverse(ast, {
enter: function (node, parent) {
if (parent != null) { ancestry.unshift(parent); }
if (matches(node, selector, ancestry)) {
if (altSubjects.length) {
for (i = 0, l = altSubjects.length; i < l; ++i) {
if (matches(node, altSubjects[i], ancestry)) { results.push(node); }
for (k = 0, m = ancestry.length; k < m; ++k) {
if (matches(ancestry[k], altSubjects[i], ancestry.slice(k + 1))) {
results.push(ancestry[k]);
}
}
}
} else {
results.push(node);
}
}
},
leave: function () { ancestry.shift(); }
});
return results;
}
/**
* Parse a selector string and return its AST.
*/
function parse(selector) {
return transform(parser.parse(selector));
}
/**
* Query the code AST using the selector string.
*/
function query(ast, selector) {
return match(ast, parse(selector));
}
query.parse = parse;
query.match = match;
query.matches = matches;
return query.query = query;
}
if (typeof define === "function" && define.amd) {
define(esqueryModule);
} else if (typeof module !== 'undefined' && module.exports) {
module.exports = esqueryModule();
} else {
this.esquery = esqueryModule();
}
})();