2017-05-29 07:06:09 +03:00
|
|
|
"use strict";
|
|
|
|
|
|
|
|
const createError = require("./parser-create-error");
|
2017-06-02 23:38:15 +03:00
|
|
|
const includeShebang = require("./parser-include-shebang");
|
2017-05-29 07:06:09 +03:00
|
|
|
|
|
|
|
function parse(text) {
|
|
|
|
const jsx = isProbablyJsx(text);
|
|
|
|
let ast;
|
|
|
|
try {
|
|
|
|
try {
|
|
|
|
// Try passing with our best guess first.
|
|
|
|
ast = tryParseTypeScript(text, jsx);
|
|
|
|
} catch (e) {
|
|
|
|
// But if we get it wrong, try the opposite.
|
|
|
|
ast = tryParseTypeScript(text, !jsx);
|
|
|
|
}
|
|
|
|
} catch (e) {
|
2017-06-03 00:11:05 +03:00
|
|
|
throw createError(e.message, {
|
|
|
|
start: { line: e.lineNumber, column: e.column + 1 }
|
|
|
|
});
|
2017-05-29 07:06:09 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
delete ast.tokens;
|
2017-06-02 23:38:15 +03:00
|
|
|
includeShebang(text, ast);
|
2017-05-29 07:06:09 +03:00
|
|
|
return ast;
|
|
|
|
}
|
|
|
|
|
|
|
|
function tryParseTypeScript(text, jsx) {
|
|
|
|
// While we are working on typescript, we are putting it in devDependencies
|
|
|
|
// so it shouldn't be picked up by static analysis
|
2017-05-29 07:49:41 +03:00
|
|
|
const parser = require("typescript-eslint-parser");
|
2017-05-29 07:06:09 +03:00
|
|
|
return parser.parse(text, {
|
|
|
|
loc: true,
|
|
|
|
range: true,
|
|
|
|
tokens: true,
|
|
|
|
comment: true,
|
|
|
|
useJSXTextNode: true,
|
2017-06-15 00:53:05 +03:00
|
|
|
ecmaFeatures: { jsx },
|
|
|
|
// Override logger function with noop,
|
|
|
|
// to avoid unsupported version errors being logged
|
|
|
|
loggerFn: () => {}
|
2017-05-29 07:06:09 +03:00
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Use a naive regular expression until we address
|
|
|
|
* https://github.com/prettier/prettier/issues/1538
|
|
|
|
*/
|
|
|
|
function isProbablyJsx(text) {
|
|
|
|
return new RegExp(
|
|
|
|
[
|
|
|
|
"(^[^\"'`]*</)", // Contains "</" when probably not in a string
|
|
|
|
"|",
|
2017-06-02 21:48:43 +03:00
|
|
|
"(^[^/]{2}.*/>)" // Contains "/>" on line not starting with "//"
|
2017-05-29 07:06:09 +03:00
|
|
|
].join(""),
|
|
|
|
"m"
|
|
|
|
).test(text);
|
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = parse;
|