The Nuclide codebase uses features that are still proposals which require a flag to be enabled. Babylon parses them fine without any flags. Let's enable them by default as it doesn't cost much, you either are using those features and you don't want the parser to break, or you are not and you don't care. After this and #218, none of the nuclide files are throwing exceptions! (yay!)
76 lines
1.7 KiB
JavaScript
76 lines
1.7 KiB
JavaScript
"use strict";
|
|
const babylon = require("babylon");
|
|
const Printer = require("./src/printer").Printer;
|
|
const flowParser = require("flow-parser");
|
|
const comments = require("./src/comments");
|
|
|
|
var babylonOptions = {
|
|
sourceType: "module",
|
|
allowImportExportEverywhere: false,
|
|
allowReturnOutsideFunction: false,
|
|
plugins: [
|
|
"jsx",
|
|
"flow",
|
|
"doExpressions",
|
|
"objectRestSpread",
|
|
"decorators",
|
|
"classProperties",
|
|
"exportExtensions",
|
|
"asyncGenerators",
|
|
"functionBind",
|
|
"functionSent",
|
|
"dynamicImport"
|
|
]
|
|
};
|
|
|
|
function format(text, opts) {
|
|
opts = opts || {};
|
|
let ast;
|
|
|
|
if (opts.useFlowParser) {
|
|
ast = flowParser.parse(text, {
|
|
esproposal_class_instance_fields: true,
|
|
esproposal_class_static_fields: true,
|
|
esproposal_export_star_as: true,
|
|
});
|
|
if (ast.errors.length > 0) {
|
|
let msg = ast.errors[(0)].message + " on line " +
|
|
ast.errors[(0)].loc.start.line;
|
|
if (opts.filename) {
|
|
msg += " in file " + opts.filename;
|
|
}
|
|
throw new Error(msg);
|
|
}
|
|
} else {
|
|
ast = babylon.parse(text, babylonOptions);
|
|
}
|
|
|
|
// Interleave comment nodes
|
|
if (ast.comments) {
|
|
comments.attach(ast.comments, ast, text);
|
|
ast.comments = [];
|
|
}
|
|
ast.tokens = [];
|
|
opts.originalText = text;
|
|
|
|
const printer = new Printer(opts);
|
|
return printer.print(ast);
|
|
}
|
|
|
|
function formatWithShebang(text, opts) {
|
|
if (!text.startsWith("#!")) {
|
|
return format(text, opts);
|
|
}
|
|
|
|
const index = text.indexOf("\n");
|
|
const shebang = text.slice(0, index + 1);
|
|
const programText = text.slice(index + 1);
|
|
return shebang + format(programText, opts);
|
|
}
|
|
|
|
module.exports = {
|
|
format: function(text, opts) {
|
|
return formatWithShebang(text, opts);
|
|
}
|
|
};
|