-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
106 lines (87 loc) · 2.25 KB
/
index.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
// @flow
'use strict';
/*::
type Node = {
type: string,
[key: string]: any,
};
type Path = {
type: string,
node: Node,
[key: string]: any,
};
type Binding = {
kind: 'import' | 'declaration' | 'expression' | 'param',
path: Path,
};
type Bindings = {
[name: string]: Binding,
};
type Visitor = {
[method: string]: (path: Path, state: { bindings: Bindings }) => void;
};
*/
let getId = (kind, path, bindings) => {
if (path.node.id) {
let id = path.get('id');
bindings[id.node.name] = {kind, path: id};
}
};
let visitor /*: Visitor */ = {
Scope(path) {
path.skip();
},
Declaration(path, state) {
if (
path.isInterfaceDeclaration() ||
path.isTypeAlias() ||
path.isClassDeclaration()
) {
getId('declaration', path, state.bindings);
}
if (!path.isImportDeclaration() && !path.isExportDeclaration()) {
path.skip();
}
},
TypeParameter(path, state) {
state.bindings[path.node.name] = {kind: 'param', path};
},
'ImportSpecifier|ImportDefaultSpecifier'(path, state) {
let importKind = path.node.importKind || path.parent.importKind;
if (importKind !== 'type' && importKind !== 'typeof') return;
let local = path.get('local');
state.bindings[local.node.name] = {kind: 'import', path: local};
},
};
function getFlowScopePath(path /*: Path */) /*: Path */ {
return path.find(p => {
return (
p.isScope() ||
p.isTypeAlias() ||
p.isInterfaceDeclaration()
);
});
}
function getFlowBindingsInScope(path /*: Path */) /*: Bindings */ {
let scopePath = getFlowScopePath(path);
let bindings = {};
if (scopePath.isClassExpression()) {
getId('expression', scopePath, bindings);
} else {
scopePath.traverse(visitor, { bindings });
}
return bindings;
}
function findFlowBinding(path /*: Path */, name /*: string */) /*: Binding | null */ {
let scopePath = path;
let binding;
do {
scopePath = getFlowScopePath(scopePath);
let bindings = getFlowBindingsInScope(scopePath);
if (bindings[name]) return bindings[name];
} while (scopePath = scopePath.parentPath);
return null;
}
exports.getFlowScopePath = getFlowScopePath;
exports.getFlowBindingsInScope = getFlowBindingsInScope;
exports.findFlowBinding = findFlowBinding;