forked from babel/babel
/
parse.js
81 lines (65 loc) · 1.98 KB
/
parse.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
// @flow
import loadConfig, { type InputOptions } from "./config";
import parser from "./parser";
import type { ParseResult } from "./parser";
import normalizeOptions from "./transformation/normalize-opts";
type FileParseCallback = {
(Error, null): any,
(null, ParseResult | null): any,
};
type Parse = {
(code: string, callback: FileParseCallback): void,
(code: string, opts: ?InputOptions, callback: FileParseCallback): void,
// Here for backward-compatibility. Ideally use ".parseSync" if you want
// a synchronous API.
(code: string, opts: ?InputOptions): ParseResult | null,
};
export const parse: Parse = (function parse(code, opts, callback) {
if (typeof opts === "function") {
callback = opts;
opts = undefined;
}
// For backward-compat with Babel 7's early betas, we allow sync parsing when
// no callback is given. Will be dropped in some future Babel major version.
if (callback === undefined) return parseSync(code, opts);
const config = loadConfig(opts);
if (config === null) {
return null;
}
// Reassign to keep Flowtype happy.
const cb = callback;
// Just delaying the transform one tick for now to simulate async behavior
// but more async logic may land here eventually.
process.nextTick(() => {
let ast = null;
try {
const cfg = loadConfig(opts);
if (cfg === null) return cb(null, null);
ast = parser(cfg.passes, normalizeOptions(cfg), code);
} catch (err) {
return cb(err);
}
cb(null, ast);
});
}: Function);
export function parseSync(
code: string,
opts?: InputOptions,
): ParseResult | null {
const config = loadConfig(opts);
if (config === null) {
return null;
}
return parser(config.passes, normalizeOptions(config), code);
}
export function parseAsync(
code: string,
opts?: InputOptions,
): Promise<ParseResult | null> {
return new Promise((res, rej) => {
parse(code, opts, (err, result) => {
if (err == null) res(result);
else rej(err);
});
});
}