This repository was archived by the owner on Mar 8, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathparser.js
60 lines (52 loc) · 1.44 KB
/
parser.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
const babylon = require('@babel/parser');
export const ALL_PLUGINS = [
'jsx',
'flow',
['decorators', {"decoratorsBeforeExport": true, "legacy": true}],
'doExpressions',
'objectRestSpread',
'decorators2',
'classProperties',
'classPrivateProperties',
'classPrivateMethods',
'exportExtensions',
'asyncGenerators',
'functionBind',
'functionSend',
'dynamicImport',
'numericSeparator',
'optionalChaining',
'importMeta',
'bigInt',
'optionalCatchBinding',
'throwExpressions',
['pipelineOperator', {"proposal": "minimal"}],
'nullishCoalescingOperator',
];
export function parse(code, options) {
return babylon.parse(code, Object.assign({ plugins: ALL_PLUGINS }, options));
}
export function parseExpression(code, option) {
return babylon.parseExpression(code, Object.assign({ plugins: ALL_PLUGINS }, options));
}
const GUESSING_ORDER = [
[parse, { sourceType: 'module', allowImportExportEverywhere: true, tokens: false }],
[parse, { sourceType: 'script', allowReturnOutsideFunction: true, tokens: false }],
];
export class GuessParsingError extends Error {
constructor(...messages) {
super(messages.join(', '));
this.allMessages = messages;
}
}
export function guessParsing(code) {
let exceptions = [];
for (let [fn, opts] of GUESSING_ORDER) {
try {
return fn(code, opts);
} catch (ex) {
exceptions.push(ex)
}
}
throw new GuessParsingError(exceptions.map((x) => x.message));
}