parse.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. "use strict";
  2. var babylonToEspree = require("./babylon-to-espree");
  3. var parse = require("@babel/parser").parse;
  4. var tt = require("@babel/parser").tokTypes;
  5. var traverse = require("@babel/traverse").default;
  6. var codeFrameColumns = require("@babel/code-frame").codeFrameColumns;
  7. module.exports = function(code, options) {
  8. const legacyDecorators =
  9. options.ecmaFeatures && options.ecmaFeatures.legacyDecorators;
  10. var opts = {
  11. codeFrame: options.hasOwnProperty("codeFrame") ? options.codeFrame : true,
  12. sourceType: options.sourceType,
  13. allowImportExportEverywhere: options.allowImportExportEverywhere, // consistent with espree
  14. allowReturnOutsideFunction: true,
  15. allowSuperOutsideMethod: true,
  16. ranges: true,
  17. tokens: true,
  18. plugins: [
  19. ["flow", { all: true }],
  20. "jsx",
  21. "estree",
  22. "asyncFunctions",
  23. "asyncGenerators",
  24. "classConstructorCall",
  25. "classProperties",
  26. legacyDecorators
  27. ? "decorators-legacy"
  28. : ["decorators", { decoratorsBeforeExport: false }],
  29. "doExpressions",
  30. "exponentiationOperator",
  31. "exportDefaultFrom",
  32. "exportNamespaceFrom",
  33. "functionBind",
  34. "functionSent",
  35. "objectRestSpread",
  36. "trailingFunctionCommas",
  37. "dynamicImport",
  38. "numericSeparator",
  39. "optionalChaining",
  40. "importMeta",
  41. "classPrivateProperties",
  42. "bigInt",
  43. "optionalCatchBinding",
  44. "throwExpressions",
  45. ["pipelineOperator", { proposal: "minimal" }],
  46. "nullishCoalescingOperator",
  47. "logicalAssignment",
  48. ],
  49. };
  50. var ast;
  51. try {
  52. ast = parse(code, opts);
  53. } catch (err) {
  54. if (err instanceof SyntaxError) {
  55. err.lineNumber = err.loc.line;
  56. err.column = err.loc.column;
  57. if (opts.codeFrame) {
  58. err.lineNumber = err.loc.line;
  59. err.column = err.loc.column + 1;
  60. // remove trailing "(LINE:COLUMN)" acorn message and add in esprima syntax error message start
  61. err.message =
  62. "Line " +
  63. err.lineNumber +
  64. ": " +
  65. err.message.replace(/ \((\d+):(\d+)\)$/, "") +
  66. // add codeframe
  67. "\n\n" +
  68. codeFrameColumns(
  69. code,
  70. {
  71. start: {
  72. line: err.lineNumber,
  73. column: err.column,
  74. },
  75. },
  76. { highlightCode: true }
  77. );
  78. }
  79. }
  80. throw err;
  81. }
  82. babylonToEspree(ast, traverse, tt, code);
  83. return ast;
  84. };