(source, comments, typescript, is_script)
| 23 | * @param {boolean} [is_script] |
| 24 | */ |
| 25 | export function parse(source, comments, typescript, is_script) { |
| 26 | const acorn = typescript ? TSParser : JSParser; |
| 27 | |
| 28 | const { onComment, add_comments } = get_comment_handlers( |
| 29 | source, |
| 30 | /** @type {CommentWithLocation[]} */ (comments) |
| 31 | ); |
| 32 | |
| 33 | // @ts-expect-error |
| 34 | const parse_statement = acorn.prototype.parseStatement; |
| 35 | |
| 36 | // If we're dealing with a <script> then it might contain an export |
| 37 | // for something that doesn't exist directly inside but is inside the |
| 38 | // component instead, so we need to ensure that Acorn doesn't throw |
| 39 | // an error in these cases |
| 40 | if (is_script) { |
| 41 | // @ts-ignore |
| 42 | acorn.prototype.parseStatement = function (...args) { |
| 43 | const v = parse_statement.call(this, ...args); |
| 44 | // @ts-ignore |
| 45 | this.undefinedExports = {}; |
| 46 | return v; |
| 47 | }; |
| 48 | } |
| 49 | |
| 50 | try { |
| 51 | const ast = acorn.parse(source, { |
| 52 | onComment, |
| 53 | sourceType: 'module', |
| 54 | ecmaVersion: 16, |
| 55 | locations: true |
| 56 | }); |
| 57 | |
| 58 | add_comments(ast); |
| 59 | |
| 60 | return /** @type {Program} */ (ast); |
| 61 | } catch (err) { |
| 62 | // TODO the `return` in necessary for TS<7 due to a bug; otherwise |
| 63 | // the `finally` block is regarded as unreachable |
| 64 | return handle_parse_error(err); |
| 65 | } finally { |
| 66 | if (is_script) { |
| 67 | // @ts-expect-error |
| 68 | acorn.prototype.parseStatement = parse_statement; |
| 69 | } |
| 70 | } |
| 71 | } |
| 72 | |
| 73 | /** |
| 74 | * @param {Parser} parser |
no test coverage detected