* Add comments showing parser arguments Since this is how they are invoked, the comments make it easier to maintain. * Use babylon.parseExpression for JSON See https://github.com/prettier/prettier/issues/2378#issuecomment-314600778 Note that this doesn't yet print comments: echo '{/*comment*/"K":"V"}' | ./bin/prettier.js --parser json * Remove parser-json.js This reduces duplicate code in the built package. See https://github.com/prettier/prettier/pull/2476#pullrequestreview-50181398 * Add test with block comment in JSON * Fix test with block comment in JSON * Add test with line comment in JSON * Don't build now-redundant parser-json.js
68 lines
1.5 KiB
JavaScript
68 lines
1.5 KiB
JavaScript
"use strict";
|
|
|
|
const path = require("path");
|
|
|
|
const parsers = {
|
|
get flow() {
|
|
return eval("require")("./parser-flow");
|
|
},
|
|
get graphql() {
|
|
return eval("require")("./parser-graphql");
|
|
},
|
|
get parse5() {
|
|
return eval("require")("./parser-parse5");
|
|
},
|
|
get babylon() {
|
|
return eval("require")("./parser-babylon");
|
|
},
|
|
get typescript() {
|
|
return eval("require")("./parser-typescript");
|
|
},
|
|
get postcss() {
|
|
return eval("require")("./parser-postcss");
|
|
},
|
|
get json() {
|
|
return eval("require")("./parser-babylon");
|
|
}
|
|
};
|
|
|
|
function resolveParseFunction(opts) {
|
|
if (typeof opts.parser === "function") {
|
|
return opts.parser;
|
|
}
|
|
if (typeof opts.parser === "string") {
|
|
if (parsers.hasOwnProperty(opts.parser)) {
|
|
return parsers[opts.parser];
|
|
}
|
|
try {
|
|
return eval("require")(path.resolve(process.cwd(), opts.parser));
|
|
} catch (err) {
|
|
throw new Error(`Couldn't resolve parser "${opts.parser}"`);
|
|
}
|
|
}
|
|
return parsers.babylon;
|
|
}
|
|
|
|
function parse(text, opts) {
|
|
const parseFunction = resolveParseFunction(opts);
|
|
|
|
try {
|
|
return parseFunction(text, parsers, opts);
|
|
} catch (error) {
|
|
const loc = error.loc;
|
|
|
|
if (loc) {
|
|
const codeFrame = require("babel-code-frame");
|
|
error.codeFrame = codeFrame.codeFrameColumns(text, loc, {
|
|
highlightCode: true
|
|
});
|
|
error.message += "\n" + error.codeFrame;
|
|
throw error;
|
|
}
|
|
|
|
throw error.stack;
|
|
}
|
|
}
|
|
|
|
module.exports = { parse };
|