parse.js 2.2 KB

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