/
espree.js
57 lines (47 loc) · 1.44 KB
/
espree.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
"use strict";
const createError = require("../../common/parser-create-error.js");
const tryCombinations = require("../../utils/try-combinations.js");
const createParser = require("./utils/create-parser.js");
const replaceHashbang = require("./utils/replace-hashbang.js");
const postprocess = require("./postprocess/index.js");
/** @type {import("espree").Options} */
const parseOptions = {
ecmaVersion: "latest",
range: true,
loc: true,
comment: true,
tokens: true,
sourceType: "module",
ecmaFeatures: {
jsx: true,
globalReturn: true,
impliedStrict: false,
},
};
function createParseError(error) {
const { message, lineNumber, column } = error;
/* istanbul ignore next */
if (typeof lineNumber !== "number") {
return error;
}
return createError(message, { start: { line: lineNumber, column } });
}
function parse(originalText, parsers, options = {}) {
const { parse } = require("espree");
const textToParse = replaceHashbang(originalText);
const { result: ast, error: moduleParseError } = tryCombinations(
() => parse(textToParse, { ...parseOptions, sourceType: "module" }),
() => parse(textToParse, { ...parseOptions, sourceType: "script" })
);
if (!ast) {
// throw the error for `module` parsing
throw createParseError(moduleParseError);
}
options.originalText = originalText;
return postprocess(ast, options);
}
module.exports = {
parsers: {
espree: createParser(parse),
},
};