/
ESParser.js
97 lines (80 loc) · 2.32 KB
/
ESParser.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
import fs from 'fs-extra';
import espree from 'espree';
import Plugin from '../Plugin/Plugin.js';
import * as babylon from 'babylon';
/**
* ECMAScript Parser class.
*
* @example
* let ast = ESParser.parse('./src/foo.js');
*/
export default class ESParser {
/**
* parse ECMAScript source code.
* @param {string} filePath - source code file path.
* @returns {AST} AST of source code.
*/
static parse(filePath) {
return this.parseWithBabylon(filePath);
// return this.parseWithEspree(filePath);
}
static parseWithEspree(filePath) {
let code = fs.readFileSync(filePath, {encode: 'utf8'}).toString();
code = Plugin.onHandleCode(code, filePath);
if (code.charAt(0) === '#') {
code = code.replace(/^#!/, '//');
}
let option = {
comments: true,
attachComment: true,
loc: true,
ecmaFeatures: {
arrowFunctions: true,
blockBindings: true,
destructuring: true,
regexYFlag: true,
regexUFlag: true,
templateStrings: true,
binaryLiterals: true,
octalLiterals: true,
unicodeCodePointEscapes: true,
defaultParams: true,
restParams: true,
forOf: true,
objectLiteralComputedProperties: true,
objectLiteralShorthandMethods: true,
objectLiteralShorthandProperties: true,
objectLiteralDuplicateProperties: true,
generators: true,
spread: true,
classes: true,
modules: true,
jsx: true,
globalReturn: true
}
};
let parser = (code) => {
return espree.parse(code, option);
};
parser = Plugin.onHandleCodeParser(parser, option, filePath, code);
let ast = parser(code);
ast = Plugin.onHandleAST(ast, filePath, code);
return ast;
}
static parseWithBabylon(filePath) {
let code = fs.readFileSync(filePath, {encode: 'utf8'}).toString();
code = Plugin.onHandleCode(code, filePath);
if (code.charAt(0) === '#') code = code.replace(/^#!/, '//');
const option = {
sourceType: 'module',
plugins: ['jsx']
};
let parser = (code) => {
return babylon.parse(code, option);
};
parser = Plugin.onHandleCodeParser(parser, option, filePath, code);
let ast = parser(code);
ast = Plugin.onHandleAST(ast, filePath, code);
return ast;
}
}