forked from facebookarchive/flow-remove-types
-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
201 lines (176 loc) · 5.58 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
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
var babylon = require('babylon');
var MagicString = require('magic-string');
/**
* Given a string JavaScript source which contains Flow types, return a string
* which has removed those types.
*
* Options:
*
* - checkPragma: (default: true) looks for an @flow pragma before parsing.
*/
module.exports = function flowRemoveTypes(source, options) {
options = options || {};
var s = new MagicString(source);
// If there's no @flow or @noflow flag, then expect no annotation.
var pragmaStart = source.indexOf('@flow');
var pragmaEnd = pragmaStart + 5;
if (pragmaStart === -1) {
pragmaStart = source.indexOf('@noflow');
pragmaEnd = pragmaStart + 7;
if (pragmaStart === -1 && options.checkPragma !== false) {
return { code: source, map: s.generateMap({ hires: true }) };
}
}
var removedNodes = pragmaStart === -1 ?
[] :
[ { start: pragmaStart, end: pragmaEnd } ];
// Babylon is one of the sources of truth for Flow syntax. This parse
// configuration is intended to be as permissive as possible.
var ast = babylon.parse(source, {
allowImportExportEverywhere: true,
allowReturnOutsideFunction: true,
allowSuperOutsideMethod: true,
sourceType: 'module',
plugins: [ '*', 'jsx', 'flow' ],
});
visit(ast, removedNodes, removeFlowVisitor);
if (removedNodes.length === 0) {
return { code: source, map: s.generateMap({ hires: true }) };
}
// Step through the removed nodes, building up the resulting string.
for (var i = 0; i < removedNodes.length; i++) {
var node = removedNodes[i];
s.overwrite(node.start, node.end, '');
}
var result = { code: s.toString() };
if (options.sourceMap !== false) {
result.map = s.generateMap({ hires: true });
}
return result;
}
var LINE_RX = /(\r\n?|\n|\u2028|\u2029)/;
// A collection of methods for each AST type names which contain Flow types to
// be removed.
var removeFlowVisitor = {
DeclareClass: removeNode,
DeclareFunction: removeNode,
DeclareInterface:removeNode,
DeclareModule: removeNode,
DeclareTypeAlias: removeNode,
DeclareVariable: removeNode,
InterfaceDeclaration: removeNode,
TypeAlias: removeNode,
TypeAnnotation: removeNode,
TypeParameterDeclaration: removeNode,
TypeParameterInstantiation: removeNode,
ClassDeclaration: removeImplementedInterfaces,
ClassExpression: removeImplementedInterfaces,
Identifier: function (removedNodes, node, ast) {
if (node.optional) {
// Find the optional token.
var idx = findTokenIndex(ast.tokens, node.start);
do {
idx++;
} while (ast.tokens[idx].type.label !== '?');
removeNode(removedNodes, ast.tokens[idx]);
}
},
ClassProperty: function (removedNodes, node) {
if (!node.value) {
return removeNode(removedNodes, node)
}
},
ExportNamedDeclaration: function (removedNodes, node) {
if (node.exportKind === 'type') {
return removeNode(removedNodes, node);
}
},
ImportDeclaration: function (removedNodes, node) {
if (node.importKind === 'type') {
return removeNode(removedNodes, node);
}
}
};
// If this class declaration or expression implements interfaces, remove
// the associated tokens.
function removeImplementedInterfaces(removedNodes, node, ast) {
if (node.implements && node.implements.length > 0) {
var first = node.implements[0];
var last = node.implements[node.implements.length - 1];
var idx = findTokenIndex(ast.tokens, first.start);
do {
idx--;
} while (ast.tokens[idx].value !== 'implements');
var lastIdx = findTokenIndex(ast.tokens, last.start);
do {
if (ast.tokens[idx].type !== 'CommentBlock' &&
ast.tokens[idx].type !== 'CommentLine') {
removeNode(removedNodes, ast.tokens[idx]);
}
} while (idx++ !== lastIdx);
}
}
// Append node to the list of removed nodes, ensuring the order of the nodes
// in the list.
function removeNode(removedNodes, node) {
var length = removedNodes.length;
var index = length;
while (index > 0 && removedNodes[index - 1].end > node.start) {
index--;
}
if (index === length) {
removedNodes.push(node);
} else {
removedNodes.splice(index, 0, node);
}
return false;
}
// Given the AST output of babylon parse, walk through in a depth-first order,
// calling methods on the given visitor, providing context as the first argument.
function visit(ast, context, visitor) {
var stack;
var parent;
var keys = [];
var index = -1;
do {
index++;
if (stack && index === keys.length) {
parent = stack.parent;
keys = stack.keys;
index = stack.index;
stack = stack.prev;
} else {
var node = parent ? parent[keys[index]] : ast.program;
if (node && typeof node === 'object' && (node.type || node.length && node[0].type)) {
if (node.type) {
var visitFn = visitor[node.type];
if (visitFn && visitFn(context, node, ast) === false) {
continue;
}
}
stack = { parent: parent, keys: keys, index: index, prev: stack };
parent = node;
keys = Object.keys(node);
index = -1;
}
}
} while (stack);
}
// Given an array of sorted tokens, find the index of the token which contains
// the given offset. Uses binary search for O(log N) performance.
function findTokenIndex(tokens, offset) {
var min = 0;
var max = tokens.length - 1;
while (min <= max) {
var ptr = (min + max) / 2 | 0;
var token = tokens[ptr];
if (token.end <= offset) {
min = ptr + 1;
} else if (token.start > offset) {
max = ptr - 1;
} else {
return ptr;
}
}
return ptr;
}