/
introspection.js
431 lines (347 loc) 路 11.9 KB
/
introspection.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
// This file contains methods responsible for introspecting the current path for certain values.
import type NodePath from "./index";
import includes from "lodash/includes";
import * as t from "babel-types";
/**
* Match the current node if it matches the provided `pattern`.
*
* For example, given the match `React.createClass` it would match the
* parsed nodes of `React.createClass` and `React["createClass"]`.
*/
export function matchesPattern(pattern: string, allowPartial?: boolean): boolean {
// not a member expression
if (!this.isMemberExpression()) return false;
let parts = pattern.split(".");
let search = [this.node];
let i = 0;
function matches(name) {
let part = parts[i];
return part === "*" || name === part;
}
while (search.length) {
let node = search.shift();
if (allowPartial && i === parts.length) {
return true;
}
if (t.isIdentifier(node)) {
// this part doesn't match
if (!matches(node.name)) return false;
} else if (t.isLiteral(node)) {
// this part doesn't match
if (!matches(node.value)) return false;
} else if (t.isMemberExpression(node)) {
if (node.computed && !t.isLiteral(node.property)) {
// we can't deal with this
return false;
} else {
search.unshift(node.property);
search.unshift(node.object);
continue;
}
} else if (t.isThisExpression(node)) {
if (!matches("this")) return false;
} else {
// we can't deal with this
return false;
}
// too many parts
if (++i > parts.length) {
return false;
}
}
return i === parts.length;
}
/**
* Check whether we have the input `key`. If the `key` references an array then we check
* if the array has any items, otherwise we just check if it's falsy.
*/
export function has(key): boolean {
let val = this.node && this.node[key];
if (val && Array.isArray(val)) {
return !!val.length;
} else {
return !!val;
}
}
/**
* Description
*/
export function isStatic() {
return this.scope.isStatic(this.node);
}
/**
* Alias of `has`.
*/
export let is = has;
/**
* Opposite of `has`.
*/
export function isnt(key): boolean {
return !this.has(key);
}
/**
* Check whether the path node `key` strict equals `value`.
*/
export function equals(key, value): boolean {
return this.node[key] === value;
}
/**
* Check the type against our stored internal type of the node. This is handy when a node has
* been removed yet we still internally know the type and need it to calculate node replacement.
*/
export function isNodeType(type: string): boolean {
return t.isType(this.type, type);
}
/**
* This checks whether or not we're in one of the following positions:
*
* for (KEY in right);
* for (KEY;;);
*
* This is because these spots allow VariableDeclarations AND normal expressions so we need
* to tell the path replacement that it's ok to replace this with an expression.
*/
export function canHaveVariableDeclarationOrExpression() {
return (this.key === "init" || this.key === "left") && this.parentPath.isFor();
}
/**
* This checks whether we are swapping an arrow function's body between an
* expression and a block statement (or vice versa).
*
* This is because arrow functions may implicitly return an expression, which
* is the same as containing a block statement.
*/
export function canSwapBetweenExpressionAndStatement(replacement) {
if (this.key !== "body" || !this.parentPath.isArrowFunctionExpression()) {
return false;
}
if (this.isExpression()) {
return t.isBlockStatement(replacement);
} else if (this.isBlockStatement()) {
return t.isExpression(replacement);
}
return false;
}
/**
* Check whether the current path references a completion record
*/
export function isCompletionRecord(allowInsideFunction?) {
let path = this;
let first = true;
do {
let container = path.container;
// we're in a function so can't be a completion record
if (path.isFunction() && !first) {
return !!allowInsideFunction;
}
first = false;
// check to see if we're the last item in the container and if we are
// we're a completion record!
if (Array.isArray(container) && path.key !== container.length - 1) {
return false;
}
} while ((path = path.parentPath) && !path.isProgram());
return true;
}
/**
* Check whether or not the current `key` allows either a single statement or block statement
* so we can explode it if necessary.
*/
export function isStatementOrBlock() {
if (this.parentPath.isLabeledStatement() || t.isBlockStatement(this.container)) {
return false;
} else {
return includes(t.STATEMENT_OR_BLOCK_KEYS, this.key);
}
}
/**
* Check if the currently assigned path references the `importName` of `moduleSource`.
*/
export function referencesImport(moduleSource, importName) {
if (!this.isReferencedIdentifier()) return false;
let binding = this.scope.getBinding(this.node.name);
if (!binding || binding.kind !== "module") return false;
let path = binding.path;
let parent = path.parentPath;
if (!parent.isImportDeclaration()) return false;
// check moduleSource
if (parent.node.source.value === moduleSource) {
if (!importName) return true;
} else {
return false;
}
if (path.isImportDefaultSpecifier() && importName === "default") {
return true;
}
if (path.isImportNamespaceSpecifier() && importName === "*") {
return true;
}
if (path.isImportSpecifier() && path.node.imported.name === importName) {
return true;
}
return false;
}
/**
* Get the source code associated with this node.
*/
export function getSource() {
let node = this.node;
if (node.end) {
const code = this.hub.getCode();
if (code) {
return code.slice(node.start, node.end);
} else {
return "";
}
} else {
return "";
}
}
export function willIMaybeExecuteBefore(target) {
return this._guessExecutionStatusRelativeTo(target) !== "after";
}
/**
* Given a `target` check the execution status of it relative to the current path.
*
* "Execution status" simply refers to where or not we **think** this will execuete
* before or after the input `target` element.
*/
export function _guessExecutionStatusRelativeTo(target) {
// check if the two paths are in different functions, we can't track execution of these
let targetFuncParent = target.scope.getFunctionParent();
let selfFuncParent = this.scope.getFunctionParent();
// here we check the `node` equality as sometimes we may have different paths for the
// same node due to path thrashing
if (targetFuncParent.node !== selfFuncParent.node) {
let status = this._guessExecutionStatusRelativeToDifferentFunctions(targetFuncParent);
if (status) {
return status;
} else {
target = targetFuncParent.path;
}
}
let targetPaths = target.getAncestry();
if (targetPaths.indexOf(this) >= 0) return "after";
let selfPaths = this.getAncestry();
// get ancestor where the branches intersect
let commonPath;
let targetIndex;
let selfIndex;
for (selfIndex = 0; selfIndex < selfPaths.length; selfIndex++) {
let selfPath = selfPaths[selfIndex];
targetIndex = targetPaths.indexOf(selfPath);
if (targetIndex >= 0) {
commonPath = selfPath;
break;
}
}
if (!commonPath) {
return "before";
}
// get the relationship paths that associate these nodes to their common ancestor
let targetRelationship = targetPaths[targetIndex - 1];
let selfRelationship = selfPaths[selfIndex - 1];
if (!targetRelationship || !selfRelationship) {
return "before";
}
// container list so let's see which one is after the other
if (targetRelationship.listKey && targetRelationship.container === selfRelationship.container) {
return targetRelationship.key > selfRelationship.key ? "before" : "after";
}
// otherwise we're associated by a parent node, check which key comes before the other
let targetKeyPosition = t.VISITOR_KEYS[targetRelationship.type].indexOf(targetRelationship.key);
let selfKeyPosition = t.VISITOR_KEYS[selfRelationship.type].indexOf(selfRelationship.key);
return targetKeyPosition > selfKeyPosition ? "before" : "after";
}
export function _guessExecutionStatusRelativeToDifferentFunctions(targetFuncParent) {
let targetFuncPath = targetFuncParent.path;
if (!targetFuncPath.isFunctionDeclaration()) return;
// so we're in a completely different function, if this is a function declaration
// then we can be a bit smarter and handle cases where the function is either
// a. not called at all (part of an export)
// b. called directly
let binding = targetFuncPath.scope.getBinding(targetFuncPath.node.id.name);
// no references!
if (!binding.references) return "before";
let referencePaths: Array<NodePath> = binding.referencePaths;
// verify that all of the references are calls
for (let path of referencePaths) {
if (path.key !== "callee" || !path.parentPath.isCallExpression()) {
return;
}
}
let allStatus;
// verify that all the calls have the same execution status
for (let path of referencePaths) {
// if a reference is a child of the function we're checking against then we can
// safelty ignore it
let childOfFunction = !!path.find((path) => path.node === targetFuncPath.node);
if (childOfFunction) continue;
let status = this._guessExecutionStatusRelativeTo(path);
if (allStatus) {
if (allStatus !== status) return;
} else {
allStatus = status;
}
}
return allStatus;
}
/**
* Resolve a "pointer" `NodePath` to it's absolute path.
*/
export function resolve(dangerous, resolved) {
return this._resolve(dangerous, resolved) || this;
}
export function _resolve(dangerous?, resolved?): ?NodePath {
// detect infinite recursion
// todo: possibly have a max length on this just to be safe
if (resolved && resolved.indexOf(this) >= 0) return;
// we store all the paths we've "resolved" in this array to prevent infinite recursion
resolved = resolved || [];
resolved.push(this);
if (this.isVariableDeclarator()) {
if (this.get("id").isIdentifier()) {
return this.get("init").resolve(dangerous, resolved);
} else {
// otherwise it's a request for a pattern and that's a bit more tricky
}
} else if (this.isReferencedIdentifier()) {
let binding = this.scope.getBinding(this.node.name);
if (!binding) return;
// reassigned so we can't really resolve it
if (!binding.constant) return;
// todo - lookup module in dependency graph
if (binding.kind === "module") return;
if (binding.path !== this) {
let ret = binding.path.resolve(dangerous, resolved);
// If the identifier resolves to parent node then we can't really resolve it.
if (this.find((parent) => parent.node === ret.node)) return;
return ret;
}
} else if (this.isTypeCastExpression()) {
return this.get("expression").resolve(dangerous, resolved);
} else if (dangerous && this.isMemberExpression()) {
// this is dangerous, as non-direct target assignments will mutate it's state
// making this resolution inaccurate
let targetKey = this.toComputedKey();
if (!t.isLiteral(targetKey)) return;
let targetName = targetKey.value;
let target = this.get("object").resolve(dangerous, resolved);
if (target.isObjectExpression()) {
let props = target.get("properties");
for (let prop of (props: Array)) {
if (!prop.isProperty()) continue;
let key = prop.get("key");
// { foo: obj }
let match = prop.isnt("computed") && key.isIdentifier({ name: targetName });
// { "foo": "obj" } or { ["foo"]: "obj" }
match = match || key.isLiteral({ value: targetName });
if (match) return prop.get("value").resolve(dangerous, resolved);
}
} else if (target.isArrayExpression() && !isNaN(+targetName)) {
let elems = target.get("elements");
let elem = elems[targetName];
if (elem) return elem.resolve(dangerous, resolved);
}
}
}