/
family.ts
565 lines (516 loc) 路 16.6 KB
/
family.ts
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
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
// This file contains methods responsible for dealing with/retrieving children or siblings.
import type TraversalContext from "../context";
import NodePath from "./index";
import * as t from "@babel/types";
const NORMAL_COMPLETION = 0;
const BREAK_COMPLETION = 1;
type Completion = {
path: NodePath;
type: 0 | 1;
};
type CompletionContext = {
// whether the current context allows `break` statement. When it allows, we have
// to search all the statements for potential `break`
canHaveBreak: boolean;
// whether the statement is an immediate descendant of a switch case clause
inCaseClause: boolean;
// whether the `break` statement record should be populated to upper level
// when a `break` statement is an immediate descendant of a block statement, e.g.
// `{ break }`, it can influence the control flow in the upper levels.
shouldPopulateBreak: boolean;
};
function NormalCompletion(path: NodePath) {
return { type: NORMAL_COMPLETION, path };
}
function BreakCompletion(path: NodePath) {
return { type: BREAK_COMPLETION, path };
}
export function getOpposite(this: NodePath): NodePath | null {
if (this.key === "left") {
return this.getSibling("right");
} else if (this.key === "right") {
return this.getSibling("left");
}
return null;
}
function addCompletionRecords(
path: NodePath | null | undefined,
records: Completion[],
context: CompletionContext,
): Completion[] {
if (path) {
Array.prototype.push.apply(records, _getCompletionRecords(path, context));
}
return records;
}
function completionRecordForSwitch(
cases: NodePath<t.SwitchCase>[],
records: Completion[],
context: CompletionContext,
): Completion[] {
// https://tc39.es/ecma262/#sec-runtime-semantics-caseblockevaluation
let lastNormalCompletions = [];
for (let i = 0; i < cases.length; i++) {
const casePath = cases[i];
const caseCompletions = _getCompletionRecords(casePath, context);
const normalCompletions = [];
const breakCompletions = [];
for (const c of caseCompletions) {
if (c.type === NORMAL_COMPLETION) {
normalCompletions.push(c);
}
if (c.type === BREAK_COMPLETION) {
breakCompletions.push(c);
}
}
if (normalCompletions.length) {
lastNormalCompletions = normalCompletions;
}
Array.prototype.push.apply(records, breakCompletions);
}
Array.prototype.push.apply(records, lastNormalCompletions);
return records;
}
function normalCompletionToBreak(completions: Completion[]) {
completions.forEach(c => {
c.type = BREAK_COMPLETION;
});
}
/**
* Determine how we should handle the break statement for break completions
*
* @param {Completion[]} completions
* @param {boolean} reachable Whether the break statement is reachable after
we mark the normal completions _before_ the given break completions as the final
completions. For example,
`{ 0 }; break;` is transformed to `{ return 0 }; break;`, the `break` here is unreachable
and thus can be removed without consequences. We may in the future reserve them instead since
we do not consistently remove unreachable statements _after_ break
`{ var x = 0 }; break;` is transformed to `{ var x = 0 }; return void 0;`, the `break` is reachable
because we can not wrap variable declaration under a return statement
*/
function replaceBreakStatementInBreakCompletion(
completions: Completion[],
reachable: boolean,
) {
completions.forEach(c => {
if (c.path.isBreakStatement({ label: null })) {
if (reachable) {
c.path.replaceWith(t.unaryExpression("void", t.numericLiteral(0)));
} else {
c.path.remove();
}
}
});
}
function getStatementListCompletion(
paths: NodePath[],
context: CompletionContext,
): Completion[] {
const completions = [];
if (context.canHaveBreak) {
let lastNormalCompletions = [];
for (let i = 0; i < paths.length; i++) {
const path = paths[i];
const newContext = { ...context, inCaseClause: false };
if (
path.isBlockStatement() &&
(context.inCaseClause || // case test: { break }
context.shouldPopulateBreak) // case test: { { break } }
) {
newContext.shouldPopulateBreak = true;
} else {
newContext.shouldPopulateBreak = false;
}
const statementCompletions = _getCompletionRecords(path, newContext);
if (
statementCompletions.length > 0 &&
// we can stop search `paths` when we have seen a `path` that is
// effectively a `break` statement. Examples are
// - `break`
// - `if (true) { 1; break } else { 2; break }`
// - `{ break }```
// In other words, the paths after this `path` are unreachable
statementCompletions.every(c => c.type === BREAK_COMPLETION)
) {
if (
lastNormalCompletions.length > 0 &&
statementCompletions.every(c =>
c.path.isBreakStatement({ label: null }),
)
) {
// when a break completion has a path as BreakStatement, it must be `{ break }`
// whose completion value we can not determine, otherwise it would have been
// replaced by `replaceBreakStatementInBreakCompletion`
// When we have seen normal completions from the last statement
// it is safe to stop populating break and mark normal completions as break
normalCompletionToBreak(lastNormalCompletions);
Array.prototype.push.apply(completions, lastNormalCompletions);
// Declarations have empty completion record, however they can not be nested
// directly in return statement, i.e. `return (var a = 1)` is invalid.
if (lastNormalCompletions.some(c => c.path.isDeclaration())) {
Array.prototype.push.apply(completions, statementCompletions);
replaceBreakStatementInBreakCompletion(
statementCompletions,
/* reachable */ true,
);
}
replaceBreakStatementInBreakCompletion(
statementCompletions,
/* reachable */ false,
);
} else {
Array.prototype.push.apply(completions, statementCompletions);
if (!context.shouldPopulateBreak) {
replaceBreakStatementInBreakCompletion(
statementCompletions,
/* reachable */ true,
);
}
}
break;
}
if (i === paths.length - 1) {
Array.prototype.push.apply(completions, statementCompletions);
} else {
Array.prototype.push.apply(
completions,
statementCompletions.filter(c => c.type === BREAK_COMPLETION),
);
lastNormalCompletions = statementCompletions.filter(
c => c.type === NORMAL_COMPLETION,
);
}
}
} else if (paths.length) {
// When we are in a context where `break` must not exist, we can skip linear
// search on statement lists and assume that the last
// non-variable-declaration statement determines the completion.
for (let i = paths.length - 1; i >= 0; i--) {
const pathCompletions = _getCompletionRecords(paths[i], context);
if (
pathCompletions.length > 1 ||
(pathCompletions.length === 1 &&
!pathCompletions[0].path.isVariableDeclaration())
) {
Array.prototype.push.apply(completions, pathCompletions);
break;
}
}
}
return completions;
}
function _getCompletionRecords(
path: NodePath,
context: CompletionContext,
): Completion[] {
let records = [];
if (path.isIfStatement()) {
records = addCompletionRecords(path.get("consequent"), records, context);
records = addCompletionRecords(path.get("alternate"), records, context);
} else if (
path.isDoExpression() ||
path.isFor() ||
path.isWhile() ||
path.isLabeledStatement()
) {
// @ts-expect-error(flow->ts): todo
records = addCompletionRecords(path.get("body"), records, context);
} else if (path.isProgram() || path.isBlockStatement()) {
Array.prototype.push.apply(
records,
// @ts-expect-error(flow->ts): todo
getStatementListCompletion(path.get("body"), context),
);
} else if (path.isFunction()) {
return _getCompletionRecords(path.get("body"), context);
} else if (path.isTryStatement()) {
records = addCompletionRecords(path.get("block"), records, context);
records = addCompletionRecords(path.get("handler"), records, context);
} else if (path.isCatchClause()) {
records = addCompletionRecords(path.get("body"), records, context);
} else if (path.isSwitchStatement()) {
records = completionRecordForSwitch(path.get("cases"), records, context);
} else if (path.isSwitchCase()) {
Array.prototype.push.apply(
records,
getStatementListCompletion(path.get("consequent"), {
canHaveBreak: true,
shouldPopulateBreak: false,
inCaseClause: true,
}),
);
} else if (path.isBreakStatement()) {
records.push(BreakCompletion(path));
} else {
records.push(NormalCompletion(path));
}
return records;
}
/**
* Retrieve the completion records of a given path.
* Note: to ensure proper support on `break` statement, this method
* will manipulate the AST around the break statement. Do not call the method
* twice for the same path.
*
* @export
* @param {NodePath} this
* @returns {NodePath[]} Completion records
*/
export function getCompletionRecords(this: NodePath): NodePath[] {
const records = _getCompletionRecords(this, {
canHaveBreak: false,
shouldPopulateBreak: false,
inCaseClause: false,
});
return records.map(r => r.path);
}
export function getSibling(this: NodePath, key: string | number): NodePath {
return NodePath.get({
parentPath: this.parentPath,
parent: this.parent,
container: this.container,
listKey: this.listKey,
key: key,
}).setContext(this.context);
}
export function getPrevSibling(this: NodePath): NodePath {
// @ts-expect-error todo(flow->ts) this.key could be a string
return this.getSibling(this.key - 1);
}
export function getNextSibling(this: NodePath): NodePath {
// @ts-expect-error todo(flow->ts) this.key could be a string
return this.getSibling(this.key + 1);
}
export function getAllNextSiblings(this: NodePath): NodePath[] {
// @ts-expect-error todo(flow->ts) this.key could be a string
let _key: number = this.key;
let sibling = this.getSibling(++_key);
const siblings = [];
while (sibling.node) {
siblings.push(sibling);
sibling = this.getSibling(++_key);
}
return siblings;
}
export function getAllPrevSiblings(this: NodePath): NodePath[] {
// @ts-expect-error todo(flow->ts) this.key could be a string
let _key: number = this.key;
let sibling = this.getSibling(--_key);
const siblings = [];
while (sibling.node) {
siblings.push(sibling);
sibling = this.getSibling(--_key);
}
return siblings;
}
// convert "1" to 1 (string index to number index)
type MaybeToIndex<T extends string> = T extends `${bigint}` ? number : T;
type Pattern<Obj extends string, Prop extends string> = `${Obj}.${Prop}`;
// split "body.body.1" to ["body", "body", 1]
type Split<P extends string> = P extends Pattern<infer O, infer U>
? [MaybeToIndex<O>, ...Split<U>]
: [MaybeToIndex<P>];
// get all K with Node[K] is t.Node | t.Node[]
type NodeKeyOf<Node extends t.Node | t.Node[]> = keyof Pick<
Node,
{
[Key in keyof Node]-?: Node[Key] extends t.Node | t.Node[] ? Key : never;
}[keyof Node]
>;
// traverse the Node with tuple path ["body", "body", 1]
// Path should be created with Split
type Trav<
Node extends t.Node | t.Node[],
Path extends unknown[],
> = Path extends [infer K, ...infer R]
? K extends NodeKeyOf<Node>
? R extends []
? Node[K]
: // @ts-expect-error ignore since TS is not smart enough
Trav<Node[K], R>
: never
: never;
type ToNodePath<T> = T extends Array<t.Node | null | undefined>
? Array<NodePath<T[number]>>
: T extends t.Node | null | undefined
? NodePath<T>
: never;
function get<T extends t.Node, K extends keyof T>(
this: NodePath<T>,
key: K,
context?: boolean | TraversalContext,
): T[K] extends Array<t.Node | null | undefined>
? Array<NodePath<T[K][number]>>
: T[K] extends t.Node | null | undefined
? NodePath<T[K]>
: never;
function get<T extends t.Node, K extends string>(
this: NodePath<T>,
key: K,
context?: boolean | TraversalContext,
): ToNodePath<Trav<T, Split<K>>>;
function get<T extends t.Node>(
this: NodePath<T>,
key: string,
context?: true | TraversalContext,
): NodePath | NodePath[];
function get<T extends t.Node>(
this: NodePath<T>,
key: string,
context: true | TraversalContext = true,
): NodePath | NodePath[] {
if (context === true) context = this.context;
const parts = key.split(".");
if (parts.length === 1) {
// "foo"
return this._getKey(key, context);
} else {
// "foo.bar"
return this._getPattern(parts, context);
}
}
export { get };
export function _getKey<T extends t.Node>(
this: NodePath<T>,
key: string,
context?: TraversalContext,
): NodePath | NodePath[] {
const node = this.node;
const container = node[key];
if (Array.isArray(container)) {
// requested a container so give them all the paths
return container.map((_, i) => {
return NodePath.get({
listKey: key,
parentPath: this,
parent: node,
container: container,
key: i,
}).setContext(context);
});
} else {
return NodePath.get({
parentPath: this,
parent: node,
container: node,
key: key,
}).setContext(context);
}
}
export function _getPattern(
this: NodePath,
parts: string[],
context?: TraversalContext,
): NodePath | NodePath[] {
let path: NodePath | NodePath[] = this;
for (const part of parts) {
if (part === ".") {
// @ts-expect-error todo(flow-ts): Can path be an array here?
path = path.parentPath;
} else {
if (Array.isArray(path)) {
path = path[part];
} else {
path = path.get(part, context);
}
}
}
return path;
}
function getBindingIdentifiers(
duplicates: true,
): Record<string, t.Identifier[]>;
function getBindingIdentifiers(
duplicates?: false,
): Record<string, t.Identifier>;
function getBindingIdentifiers(
duplicates: boolean,
): Record<string, t.Identifier[] | t.Identifier>;
function getBindingIdentifiers(
duplicates?: boolean,
): Record<string, t.Identifier[] | t.Identifier> {
return t.getBindingIdentifiers(this.node, duplicates);
}
export { getBindingIdentifiers };
function getOuterBindingIdentifiers(
duplicates: true,
): Record<string, t.Identifier[]>;
function getOuterBindingIdentifiers(
duplicates?: false,
): Record<string, t.Identifier>;
function getOuterBindingIdentifiers(
duplicates: boolean,
): Record<string, t.Identifier[] | t.Identifier>;
function getOuterBindingIdentifiers(
duplicates?: boolean,
): Record<string, t.Identifier[] | t.Identifier> {
return t.getOuterBindingIdentifiers(this.node, duplicates);
}
export { getOuterBindingIdentifiers };
// original source - https://github.com/babel/babel/blob/main/packages/babel-types/src/retrievers/getBindingIdentifiers.js
// path.getBindingIdentifiers returns nodes where the following re-implementation
// returns paths
export function getBindingIdentifierPaths(
this: NodePath,
duplicates: boolean = false,
outerOnly: boolean = false,
): {
[x: string]: NodePath;
} {
const path = this;
const search = [path];
const ids = Object.create(null);
while (search.length) {
const id = search.shift();
if (!id) continue;
if (!id.node) continue;
const keys = t.getBindingIdentifiers.keys[id.node.type];
if (id.isIdentifier()) {
if (duplicates) {
const _ids = (ids[id.node.name] = ids[id.node.name] || []);
_ids.push(id);
} else {
ids[id.node.name] = id;
}
continue;
}
if (id.isExportDeclaration()) {
const declaration = id.get("declaration");
if (t.isDeclaration(declaration)) {
search.push(declaration);
}
continue;
}
if (outerOnly) {
if (id.isFunctionDeclaration()) {
search.push(id.get("id"));
continue;
}
if (id.isFunctionExpression()) {
continue;
}
}
if (keys) {
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
const child = id.get(key);
if (Array.isArray(child)) {
Array.prototype.push.apply(search, child);
} else if (child.node) {
search.push(child);
}
}
}
}
// $FlowIssue Object.create() is object type
return ids;
}
export function getOuterBindingIdentifierPaths(
this: NodePath,
duplicates?: boolean,
): {
[x: string]: NodePath;
} {
return this.getBindingIdentifierPaths(duplicates, true);
}