/
run_babel_parser_flow_tests.js
310 lines (273 loc) · 8.11 KB
/
run_babel_parser_flow_tests.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
"use strict";
const path = require("path");
const fs = require("fs");
const chalk = require("chalk");
const parse = require("../../../packages/babel-parser").parse;
const TESTS_FOLDER = path.join(
__dirname,
"../../../build/flow/src/parser/test/flow"
);
const WHITELIST_PATH = path.join(__dirname, "./flow_tests_whitelist.txt");
const shouldUpdateWhitelist = process.argv.indexOf("--update-whitelist") > 0;
function map_get_default(map, key, defaultConstructor) {
if (map.has(key)) {
return map.get(key);
}
const value = new defaultConstructor();
map.set(key, value);
return value;
}
function get_whitelist(filename) {
return fs
.readFileSync(filename, "utf8")
.split("\n")
.map(line => line.replace(/#.*$/, "").trim())
.filter(Boolean);
}
function list_files(root, dir) {
const files = fs.readdirSync(dir ? path.join(root, dir) : root);
let result = [];
for (let i = 0; i < files.length; i++) {
const file = dir ? path.join(dir, files[i]) : files[i];
const stats = fs.statSync(path.join(root, file));
if (stats.isDirectory()) {
result = result.concat(list_files(root, file));
} else {
result.push(file);
}
}
return result.sort();
}
function get_tests(root_dir) {
const files = list_files(root_dir);
const tests = new Map();
for (let i = 0; i < files.length; i++) {
const file = files[i];
const test_name = path.dirname(file);
const case_parts = path.basename(file).split(".");
const case_name = case_parts[0];
// Hack to ignore hidden files.
if (case_name === "") {
continue;
}
const cases = map_get_default(tests, test_name, Map);
const case_ = map_get_default(cases, case_name, Object);
const content = fs.readFileSync(path.join(root_dir, file), "utf8");
const ext = case_parts[case_parts.length - 1];
const kind =
case_parts.length > 2 ? case_parts[case_parts.length - 2] : null;
if (ext === "js") {
case_.file = file;
case_.content = content;
} else if (ext === "json" && kind === "tree") {
case_.expected_ast = JSON.parse(content);
} else if (ext === "json" && kind === "options") {
case_.options = JSON.parse(content);
}
}
return tests;
}
function update_whitelist(summary) {
const contains = (tests, file) =>
tests.some(({ test }) => test.file === file);
const disallowed = summary.disallowed.success.concat(
summary.disallowed.failure
);
const oldLines = fs
.readFileSync(WHITELIST_PATH, "utf8")
.trim()
.split("\n")
.filter(line => {
const file = line.replace(/#.*$/, "").trim();
return (
!contains(disallowed, file) && summary.unrecognized.indexOf(file) === -1
);
});
const newLines = summary.disallowed.failure
.map(({ test }) => test.file)
.filter(test => oldLines.indexOf(test) === -1);
const result = oldLines.concat(newLines).join("\n") + "\n";
fs.writeFileSync(WHITELIST_PATH, result);
}
const options = {
plugins: [
"dynamicImport",
["flow", { all: true }],
"flowComments",
"jsx",
"classProperties",
"classPrivateProperties",
"classPrivateMethods",
"bigInt",
],
sourceType: "module",
ranges: true,
};
const flowOptionsMapping = {
esproposal_class_instance_fields: "classProperties",
esproposal_class_static_fields: "classProperties",
esproposal_export_star_as: "exportNamespaceFrom",
esproposal_decorators: "decorators-legacy",
esproposal_nullish_coalescing: "nullishCoalescingOperator",
esproposal_optional_chaining: "optionalChaining",
types: "flowComments",
intern_comments: false,
};
const summary = {
passed: true,
allowed: {
success: [],
failure: [],
},
disallowed: {
success: [],
failure: [],
},
unrecognized: [],
};
const tests = get_tests(TESTS_FOLDER);
const whitelist = get_whitelist(WHITELIST_PATH);
const unrecognized = new Set(whitelist);
tests.forEach(section => {
section.forEach(test => {
const shouldSuccess =
test.expected_ast &&
(!Array.isArray(test.expected_ast.errors) ||
test.expected_ast.errors.length === 0);
const inWhitelist = whitelist.indexOf(test.file) > -1;
const babelParserOptions = Object.assign({}, options);
babelParserOptions.plugins = babelParserOptions.plugins.slice();
if (test.options) {
Object.keys(test.options).forEach(option => {
if (!test.options[option]) {
const idx = babelParserOptions.plugins.indexOf(
flowOptionsMapping[option]
);
if (idx) {
babelParserOptions.plugins.splice(idx, 1);
}
return;
}
if (!(option in flowOptionsMapping)) {
throw new Error("Parser options not mapped " + option);
}
if (flowOptionsMapping[option]) {
babelParserOptions.plugins.push(flowOptionsMapping[option]);
}
});
}
let failed = false;
let exception = null;
try {
parse(test.content, babelParserOptions);
} catch (e) {
exception = e;
failed = true;
// lets retry in script mode
if (shouldSuccess) {
try {
parse(
test.content,
Object.assign({}, babelParserOptions, { sourceType: "script" })
);
exception = null;
failed = false;
} catch (e) {}
}
}
const isSuccess = shouldSuccess !== failed;
const isAllowed = isSuccess !== inWhitelist;
summary[isAllowed ? "allowed" : "disallowed"][
isSuccess ? "success" : "failure"
].push({ test, exception, shouldSuccess, babelParserOptions });
summary.passed &= isAllowed;
unrecognized.delete(test.file);
process.stdout.write(chalk.gray("."));
});
});
summary.unrecognized = Array.from(unrecognized);
summary.passed &= summary.unrecognized.length === 0;
// This is needed because, after the dots written using
// `process.stdout.write(".")` there is no final newline
console.log();
if (summary.disallowed.failure.length || summary.disallowed.success.length) {
console.log("\n-- FAILED TESTS --");
summary.disallowed.failure.forEach(
({ test, shouldSuccess, exception, babelParserOptions }) => {
console.log(chalk.red(`✘ ${test.file}`));
if (shouldSuccess) {
console.log(chalk.yellow(" Should parse successfully, but did not"));
console.log(chalk.yellow(` Failed with: \`${exception.message}\``));
} else {
console.log(chalk.yellow(" Should fail parsing, but did not"));
}
console.log(
chalk.yellow(
` Active plugins: ${JSON.stringify(babelParserOptions.plugins)}`
)
);
}
);
summary.disallowed.success.forEach(
({ test, shouldSuccess, babelParserOptions }) => {
console.log(chalk.red(`✘ ${test.file}`));
if (shouldSuccess) {
console.log(
chalk.yellow(
" Correctly parsed successfully, but" +
" was disallowed by the whitelist"
)
);
} else {
console.log(
chalk.yellow(
" Correctly failed parsing, but" +
" was disallowed by the whitelist"
)
);
}
console.log(
chalk.yellow(
` Active plugins: ${JSON.stringify(babelParserOptions.plugins)}`
)
);
}
);
}
console.log("-- SUMMARY --");
console.log(
chalk.green("✔ " + summary.allowed.success.length + " tests passed")
);
console.log(
chalk.green(
"✔ " +
summary.allowed.failure.length +
" tests failed but were allowed in the whitelist"
)
);
console.log(
chalk.red("✘ " + summary.disallowed.failure.length + " tests failed")
);
console.log(
chalk.red(
"✘ " +
summary.disallowed.success.length +
" tests passed but were disallowed in the whitelist"
)
);
console.log(
chalk.red(
"✘ " +
summary.unrecognized.length +
" tests specified in the whitelist were not found"
)
);
// Some padding to separate the output from the message `make`
// adds at the end of failing scripts
console.log();
if (shouldUpdateWhitelist) {
update_whitelist(summary);
console.log("\nWhitelist updated");
} else {
process.exit(summary.passed ? 0 : 1);
}