| 1 |
import type { Handler } from "gensync"; |
| 2 |
import { parse } from "@babel/parser"; |
| 3 |
import { codeFrameColumns } from "@babel/code-frame"; |
| 4 |
import generateMissingPluginMessage from "./util/missing-plugin-helper"; |
| 5 |
import type { PluginPasses } from "../config"; |
| 6 |
|
| 7 |
export type ParseResult = ReturnType<typeof parse>; |
| 8 |
|
| 9 |
export default function* parser( |
| 10 |
pluginPasses: PluginPasses, |
| 11 |
{ parserOpts, highlightCode = true, filename = "unknown" }: any, |
| 12 |
code: string, |
| 13 |
): Handler<ParseResult> { |
| 14 |
try { |
| 15 |
const results = []; |
| 16 |
for (const plugins of pluginPasses) { |
| 17 |
for (const plugin of plugins) { |
| 18 |
const { parserOverride } = plugin; |
| 19 |
if (parserOverride) { |
| 20 |
const ast = parserOverride(code, parserOpts, parse); |
| 21 |
|
| 22 |
if (ast !== undefined) results.push(ast); |
| 23 |
} |
| 24 |
} |
| 25 |
} |
| 26 |
|
| 27 |
if (results.length === 0) { |
| 28 |
return parse(code, parserOpts); |
| 29 |
} else if (results.length === 1) { |
| 30 |
// @ts-expect-error - If we want to allow async parsers |
| 31 |
yield* []; |
| 32 |
if (typeof results[0].then === "function") { |
| 33 |
throw new Error( |
| 34 |
`You appear to be using an async parser plugin, ` + |
| 35 |
`which your current version of Babel does not support. ` + |
| 36 |
`If you're using a published plugin, you may need to upgrade ` + |
| 37 |
`your @babel/core version.`, |
| 38 |
); |
| 39 |
} |
| 40 |
return results[0]; |
| 41 |
} |
| 42 |
// TODO: Add an error code |
| 43 |
throw new Error("More than one plugin attempted to override parsing."); |
| 44 |
} catch (err) { |
| 45 |
if (err.code === "BABEL_PARSER_SOURCETYPE_MODULE_REQUIRED") { |
| 46 |
err.message += |
| 47 |
"\nConsider renaming the file to '.mjs', or setting sourceType:module " + |
| 48 |
"or sourceType:unambiguous in your Babel config for this file."; |
| 49 |
// err.code will be changed to BABEL_PARSE_ERROR later. |
| 50 |
} |
| 51 |
|
| 52 |
const { loc, missingPlugin } = err; |
| 53 |
if (loc) { |
| 54 |
const codeFrame = codeFrameColumns( |
| 55 |
code, |
| 56 |
{ |
| 57 |
start: { |
| 58 |
line: loc.line, |
| 59 |
column: loc.column + 1, |
| 60 |
}, |
| 61 |
}, |
| 62 |
{ |
| 63 |
highlightCode, |
| 64 |
}, |
| 65 |
); |
| 66 |
if (missingPlugin) { |
| 67 |
err.message = |
| 68 |
`${filename}: ` + |
| 69 |
generateMissingPluginMessage(missingPlugin[0], loc, codeFrame); |
| 70 |
} else { |
| 71 |
err.message = `${filename}: ${err.message}\n\n` + codeFrame; |
| 72 |
} |
| 73 |
err.code = "BABEL_PARSE_ERROR"; |
| 74 |
} |
| 75 |
throw err; |
| 76 |
} |
| 77 |
} |