/
findIdentifiers.ts
91 lines (75 loc) · 2.54 KB
/
findIdentifiers.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
import type { NodePath } from '@babel/traverse';
import type { Node, Identifier, JSXIdentifier } from '@babel/types';
import { getScope } from './getScope';
type FindType = 'binding' | 'both' | 'referenced';
function isInVoid(path: NodePath): boolean {
return path.parentPath?.isUnaryExpression({ operator: 'void' }) ?? false;
}
function isBindingIdentifier(path: NodePath): path is NodePath<Identifier> {
return path.isBindingIdentifier() && !isInVoid(path);
}
function isReferencedIdentifier(
path: NodePath
): path is NodePath<Identifier | JSXIdentifier> {
return path.isReferencedIdentifier() || isInVoid(path);
}
// For some reasons, `isBindingIdentifier` returns true for identifiers inside `void` expressions.
const checkers: Record<FindType, (ex: NodePath) => boolean> = {
binding: (ex) => isBindingIdentifier(ex),
both: (ex) => isBindingIdentifier(ex) || isReferencedIdentifier(ex),
referenced: (ex) => isReferencedIdentifier(ex),
};
export function nonType(path: NodePath): boolean {
return !path.find(
(p) =>
p.isTSTypeReference() ||
p.isTSTypeQuery() ||
p.isFlowType() ||
p.isFlowDeclaration()
);
}
export default function findIdentifiers(
expressions: NodePath<Node | null | undefined>[],
type: FindType = 'referenced'
): NodePath<Identifier | JSXIdentifier>[] {
const identifiers: NodePath<Identifier | JSXIdentifier>[] = [];
expressions.forEach((ex) => {
const emit = (path: NodePath<Identifier | JSXIdentifier>) => {
if (!path.node || path.removed || !checkers[type](path)) {
return;
}
if (!nonType(path)) {
// If skip in TSTypeAnnotation visitor doesn't work
return;
}
// TODO: Is there a better way to check that it's a local variable?
const binding = getScope(path).getBinding(path.node.name);
if (!binding) {
return;
}
if (type === 'referenced' && ex.isAncestor(binding.path)) {
// This identifier is declared inside the expression. We don't need it.
return;
}
identifiers.push(path);
};
if (ex.isIdentifier() || ex.isJSXIdentifier()) {
emit(ex);
} else {
ex.traverse({
TSTypeAnnotation(path) {
// We ignore identifiers in type annotations
// It will produce broken TS code, but we don't care
path.skip();
},
Identifier(path: NodePath<Identifier>) {
emit(path);
},
JSXIdentifier(path: NodePath<JSXIdentifier>) {
emit(path);
},
});
}
});
return identifiers;
}