use oxc_allocator::{ArenaBox, ArenaVec};
use oxc_ast::ast::*;
use oxc_span::{GetSpan, Span};
use oxc_str::Str;

use super::{VariableDeclarationParent, grammar::CoverGrammar};
use crate::{
    Context, ParserConfig as Config, ParserImpl, StatementContext, diagnostics,
    lexer::Kind,
    modifiers::{ModifierKind, Modifiers},
};

impl<'a, C: Config> ParserImpl<'a, C> {
    // Section 12
    // The InputElementHashbangOrRegExp goal is used at the start of a Script
    // or Module.
    pub(crate) fn parse_hashbang(&mut self) -> Option<Hashbang<'a>> {
        if self.cur_kind() == Kind::HashbangComment {
            let span = self.start_span();
            self.bump_any();
            let span = self.end_span(span);
            let src = &self.source_text[span.start as usize + 2..span.end as usize];
            Some(Hashbang::new(span, Str::from(src), self))
        } else {
            None
        }
    }

    /// <https://tc39.es/ecma262/#prod-StatementList>
    /// `StatementList`[Yield, Await, Return] :
    ///     `StatementListItem`[?Yield, ?Await, ?Return]
    ///     `StatementList`[?Yield, ?Await, ?Return] `StatementListItem`[?Yield, ?Await, ?Return]
    pub(crate) fn parse_directives_and_statements(
        &mut self,
        in_ts_namespace_body: bool,
    ) -> (ArenaVec<'a, Directive<'a>>, ArenaVec<'a, Statement<'a>>) {
        let mut directives = ArenaVec::new_in(self);
        let mut statements = ArenaVec::new_in(self);

        let is_top_level = self.ctx.has_top_level();
        let stmt_ctx = StatementContext::StatementList;
        let is_ambient_block = (is_top_level || in_ts_namespace_body) && self.ctx.has_ambient();
        let mut reported_ambient_statement = false;

        // In unambiguous mode, top-level `await` parses as an identifier until ESM
        // syntax commits to the Module goal.
        let track_await_reparse = is_top_level && self.source_type.is_unambiguous();

        let mut expecting_directives = true;
        while !self.has_fatal_error() {
            if !is_top_level && self.at(Kind::RCurly) {
                break;
            }

            // Commit once module syntax is detected (`export` commits eagerly in
            // `parse_export_declaration`; `has_module_syntax()` excludes TS's
            // script-compatible `import x = ns.foo`). Until committed, checkpoint each
            // statement so an `await` identifier in it can be reparsed.
            let checkpoint = if track_await_reparse && !self.ctx.has_await() {
                if self.module_record_builder.has_module_syntax() {
                    self.ctx = self.ctx.and_await(true);
                    None
                } else {
                    self.state.encountered_await_identifier = false;
                    Some((statements.len(), self.checkpoint()))
                }
            } else {
                None
            };

            let stmt = self.parse_statement_list_item(stmt_ctx);

            // Don't reparse a module declaration: `export` already committed to the
            // Module goal while parsing, so reparsing would record the export twice.
            // e.g. `@foo export default class C { x = await + 1 }`
            if let Some((stmt_index, checkpoint)) = checkpoint
                && self.state.encountered_await_identifier
                && !stmt.is_module_declaration()
            {
                self.state.potential_await_reparse.push((stmt_index, checkpoint));
            }

            // Section 11.2.1 Directive Prologue
            // The only way to get a correct directive is to parse the statement first and check if it is a string literal.
            // All other method are flawed, see test cases in [babel](https://github.com/babel/babel/blob/v7.26.2/packages/babel-parser/test/fixtures/core/categorized/not-directive/input.js)
            if expecting_directives {
                if let Statement::ExpressionStatement(expr) = &stmt
                    && let Expression::StringLiteral(string) = &expr.expression
                {
                    // span start will mismatch if they are parenthesized when `preserve_parens = false`
                    if expr.span.start == string.span.start {
                        let src = &self.source_text
                            [string.span.start as usize + 1..string.span.end as usize - 1];
                        let directive =
                            Directive::new(expr.span, (*string).clone(), Str::from(src), self);
                        directives.push(directive);
                        continue;
                    }
                }
                expecting_directives = false;
            }
            // In an internal namespace body, module-referencing `import`/`export` statements are
            // not permitted. Validated here as each direct statement is parsed (no second pass).
            if in_ts_namespace_body {
                self.check_namespace_body_statement(&stmt);
            }
            if is_ambient_block
                && !reported_ambient_statement
                && !stmt.is_declaration()
                && !stmt.is_module_declaration()
            {
                self.error(diagnostics::statement_in_ambient_context(stmt.span()));
                reported_ambient_statement = true;
            }
            statements.push(stmt);
        }

        (directives, statements)
    }

    /// `StatementListItem`[Yield, Await, Return] :
    ///     Statement[?Yield, ?Await, ?Return]
    ///     Declaration[?Yield, ?Await]
    pub(crate) fn parse_statement_list_item(
        &mut self,
        stmt_ctx: StatementContext,
    ) -> Statement<'a> {
        let has_no_side_effects_comment =
            self.lexer.trivia_builder.previous_token_has_no_side_effects_comment();
        let pure_comment_index = self.lexer.trivia_builder.previous_token_has_pure_comment();

        let mut stmt = match self.cur_kind() {
            Kind::LCurly => self.parse_block_statement(),
            Kind::Semicolon => self.parse_empty_statement(),
            Kind::If => self.parse_if_statement(),
            Kind::Do => self.parse_do_while_statement(),
            Kind::While => self.parse_while_statement(),
            Kind::For => self.parse_for_statement(),
            Kind::Continue => self.parse_continue_statement(),
            Kind::Break => self.parse_break_statement(),
            Kind::With => self.parse_with_statement(),
            Kind::Switch => self.parse_switch_statement(),
            Kind::Throw => self.parse_throw_statement(),
            Kind::Try => self.parse_try_statement(),
            Kind::Debugger => self.parse_debugger_statement(),
            Kind::Class => self.parse_class_statement(
                self.start_span(),
                stmt_ctx,
                &Modifiers::empty(),
                ArenaVec::new_in(self),
            ),
            Kind::Export => {
                self.parse_export_declaration(self.start_span(), ArenaVec::new_in(self))
            }
            // [+Return] ReturnStatement[?Yield, ?Await]
            Kind::Return => self.parse_return_statement(),
            Kind::Var => {
                let span = self.start_span();
                self.bump_any();
                self.parse_variable_statement(span, VariableDeclarationKind::Var, stmt_ctx)
            }
            // Fast path
            Kind::Function => {
                self.parse_function_declaration(self.start_span(), /* async */ false, stmt_ctx)
            }
            Kind::At => self.parse_decorated_statement(stmt_ctx),
            Kind::Let if !self.cur_token().escaped() => self.parse_let(stmt_ctx),
            Kind::Async => self.parse_async_statement(self.start_span(), stmt_ctx),
            Kind::Import => self.parse_import_statement(),
            Kind::Const => self.parse_const_statement(stmt_ctx),
            Kind::Using if self.is_using_declaration() => self.parse_using_statement(stmt_ctx),
            Kind::Await if self.is_using_statement() => self.parse_using_statement(stmt_ctx),
            Kind::Interface
            | Kind::Type
            | Kind::Module
            | Kind::Namespace
            | Kind::Declare
            | Kind::Enum
            | Kind::Private
            | Kind::Protected
            | Kind::Public
            | Kind::Abstract
            | Kind::Accessor
            | Kind::Static
            | Kind::Readonly
            | Kind::Global
                if self.is_ts && self.at_start_of_ts_declaration() =>
            {
                self.parse_ts_declaration_statement(self.start_span(), stmt_ctx)
            }
            _ => self.parse_expression_or_labeled_statement(),
        };

        // `/* #__PURE__ */ function foo() {}` - pure comment before non-expression statements cannot be applied.
        // Expression statements handle pure comments internally in `parse_assignment_expression_or_higher_impl`.
        if let Some(index) = pure_comment_index
            && !matches!(stmt, Statement::ExpressionStatement(_))
        {
            self.lexer.trivia_builder.mark_pure_comment_not_applied(index);
        }

        if has_no_side_effects_comment {
            Self::set_pure_on_function_stmt(&mut stmt);
        }

        stmt
    }

    fn set_pure_on_function_stmt(stmt: &mut Statement<'a>) {
        match stmt {
            Statement::FunctionDeclaration(func) => {
                func.pure = true;
            }
            Statement::ExportDefaultDeclaration(decl) => match &mut decl.declaration {
                ExportDefaultDeclarationKind::FunctionExpression(func)
                | ExportDefaultDeclarationKind::FunctionDeclaration(func) => {
                    func.pure = true;
                }
                ExportDefaultDeclarationKind::ArrowFunctionExpression(func) => {
                    func.pure = true;
                }
                _ => {}
            },
            Statement::ExportNamedDeclaration(decl) => match &mut decl.declaration {
                Some(Declaration::FunctionDeclaration(func)) => {
                    func.pure = true;
                }
                Some(Declaration::VariableDeclaration(var_decl)) if var_decl.kind.is_const() => {
                    if let Some(Some(expr)) = var_decl.declarations.first_mut().map(|d| &mut d.init)
                    {
                        Self::set_pure_on_function_expr(expr);
                    }
                }
                _ => {}
            },
            Statement::VariableDeclaration(var_decl) if var_decl.kind.is_const() => {
                if let Some(Some(expr)) = var_decl.declarations.first_mut().map(|d| &mut d.init) {
                    Self::set_pure_on_function_expr(expr);
                }
            }
            _ => {}
        }
    }

    fn parse_expression_or_labeled_statement(&mut self) -> Statement<'a> {
        let span = self.start_span();
        let expr = self.parse_expr();
        if let Expression::Identifier(ident) = &expr {
            // Section 14.13 Labelled Statement
            // Avoids lookahead for a labeled statement, which is on a hot path
            if self.eat(Kind::Colon) {
                let label = LabelIdentifier::new(ident.span, ident.name, self);
                let body = self.parse_statement_list_item(StatementContext::Label);
                return Statement::new_labeled_statement(self.end_span(span), label, body, self);
            }
        }
        self.parse_expression_statement(span, expr)
    }

    /// Section 14.2 Block Statement
    pub(crate) fn parse_block(&mut self) -> ArenaBox<'a, BlockStatement<'a>> {
        let span = self.start_span();
        let body = self.parse_normal_list(Kind::LCurly, Kind::RCurly, |p| {
            p.parse_statement_list_item(StatementContext::StatementList)
        });
        BlockStatement::boxed(self.end_span(span), body, self)
    }

    pub(crate) fn parse_block_statement(&mut self) -> Statement<'a> {
        let block = self.parse_block();
        Statement::BlockStatement(block)
    }

    /// Section 14.3.2 Variable Statement
    pub(crate) fn parse_variable_statement(
        &mut self,
        start_span: u32,
        kind: VariableDeclarationKind,
        stmt_ctx: StatementContext,
    ) -> Statement<'a> {
        let decl = self.parse_variable_declaration(
            start_span,
            kind,
            VariableDeclarationParent::Statement,
            false,
        );

        if stmt_ctx.is_single_statement() && decl.kind.is_lexical() {
            self.error(diagnostics::lexical_declaration_single_statement(decl.span));
        }

        Statement::VariableDeclaration(decl)
    }

    /// Section 14.4 Empty Statement
    fn parse_empty_statement(&mut self) -> Statement<'a> {
        let span = self.start_span();
        self.bump_any(); // bump `;`
        Statement::new_empty_statement(self.end_span(span), self)
    }

    /// Section 14.5 Expression Statement
    pub(crate) fn parse_expression_statement(
        &mut self,
        span: u32,
        expression: Expression<'a>,
    ) -> Statement<'a> {
        self.asi();
        Statement::new_expression_statement(self.end_span(span), expression, self)
    }

    /// Section 14.6 If Statement
    fn parse_if_statement(&mut self) -> Statement<'a> {
        let span = self.start_span();
        self.bump_any(); // bump `if`
        let test = self.parse_paren_expression();
        let consequent = self.parse_statement_list_item(StatementContext::If);
        let alternate =
            self.eat(Kind::Else).then(|| self.parse_statement_list_item(StatementContext::If));
        Statement::new_if_statement(self.end_span(span), test, consequent, alternate, self)
    }

    /// Section 14.7.2 Do-While Statement
    fn parse_do_while_statement(&mut self) -> Statement<'a> {
        let span = self.start_span();
        self.bump_any(); // advance `do`
        let body = self.parse_statement_list_item(StatementContext::Do);
        self.expect(Kind::While);
        let test = self.parse_paren_expression();
        self.bump(Kind::Semicolon);
        Statement::new_do_while_statement(self.end_span(span), body, test, self)
    }

    /// Section 14.7.3 While Statement
    fn parse_while_statement(&mut self) -> Statement<'a> {
        let span = self.start_span();
        self.bump_any(); // bump `while`
        let test = self.parse_paren_expression();
        let body = self.parse_statement_list_item(StatementContext::While);
        Statement::new_while_statement(self.end_span(span), test, body, self)
    }

    /// Section 14.7.4 For Statement
    fn parse_for_statement(&mut self) -> Statement<'a> {
        let span = self.start_span();
        self.bump_any(); // bump `for`

        // [+Await]
        let r#await = if self.at(Kind::Await) {
            if !self.ctx.has_await() {
                // For `ModuleKind::Unambiguous`, defer the error until we know whether
                // this is a Module (where for-await is valid at top-level) or Script.
                self.error_on_script(diagnostics::await_expression(self.cur_token().span()));
            }
            self.bump_any();
            true
        } else {
            false
        };

        let parenthesis_opening_span = self.cur_token().span();
        self.expect(Kind::LParen);

        // for (;..
        if self.at(Kind::Semicolon) {
            return self.parse_for_loop(span, parenthesis_opening_span, None, r#await);
        }

        // `for (const` | `for (var`
        match self.cur_kind() {
            Kind::Const => {
                let start_span = self.start_span();
                self.bump_any();
                return self.parse_variable_declaration_for_statement(
                    span,
                    start_span,
                    parenthesis_opening_span,
                    VariableDeclarationKind::Const,
                    r#await,
                );
            }
            Kind::Var => {
                let start_span = self.start_span();
                self.bump_any();
                return self.parse_variable_declaration_for_statement(
                    span,
                    start_span,
                    parenthesis_opening_span,
                    VariableDeclarationKind::Var,
                    r#await,
                );
            }
            Kind::Let => {
                // `for (let`
                let start_span = self.start_span();
                // disallow `for (let in ...`
                if self.lexer.peek_token().kind().is_after_let() {
                    self.bump_any(); // bump `let`
                    return self.parse_variable_declaration_for_statement(
                        span,
                        start_span,
                        parenthesis_opening_span,
                        VariableDeclarationKind::Let,
                        r#await,
                    );
                }
                // Should be a relatively cold branch, since most tokens after `let` will be allowed in most files
            }
            _ => {}
        }

        // [+Using, +Await] await [no LineTerminator here] using [no LineTerminator here]
        if self.at(Kind::Await)
            && self.lookahead(|p| {
                p.bump_any();
                if !p.at(Kind::Using) || p.cur_token().is_on_new_line() {
                    return false;
                }
                p.bump_any();
                !p.cur_token().is_on_new_line()
            })
        {
            return self.parse_using_declaration_for_statement(
                span,
                parenthesis_opening_span,
                r#await,
            );
        }

        // [+Using] using [no LineTerminator here] ForBinding[?Yield, ?Await, ~Pattern]
        if self.at(Kind::Using)
            && self.lookahead(|p| {
                p.bump_any(); // bump `using`
                let token = p.cur_token();
                if token.is_on_new_line() {
                    return false;
                }
                let kind = token.kind();
                // `for (using of` is only a using declaration if followed by `=`, `;`, or `:`
                // to distinguish from `for (using of collection)` which is a for-of loop
                if kind == Kind::Of {
                    p.bump_any(); // bump `of`
                    return matches!(p.cur_kind(), Kind::Eq | Kind::Semicolon | Kind::Colon);
                }
                kind.is_binding_identifier()
            })
        {
            return self.parse_using_declaration_for_statement(
                span,
                parenthesis_opening_span,
                r#await,
            );
        }

        if self.at(Kind::RParen) {
            return self.parse_for_loop(span, parenthesis_opening_span, None, r#await);
        }

        let is_let = self.at(Kind::Let);
        // `async` is allowed as `for (async of ...)` if `async` is escaped
        let is_async = self.at(Kind::Async) && !self.cur_token().escaped();
        let expr_span = self.start_span();

        let init_expression = self.context_remove(Context::In, ParserImpl::parse_expr);

        match self.cur_kind() {
            Kind::In => {
                let target = AssignmentTarget::cover(init_expression, self);
                let for_stmt_left = ForStatementLeft::from(target);
                self.parse_for_in_loop(span, parenthesis_opening_span, r#await, for_stmt_left)
            }
            Kind::Of => {
                if !r#await && is_async && init_expression.is_identifier_reference() {
                    // `for (async of ...)` is not allowed
                    self.error(diagnostics::for_loop_async_of(self.end_span(expr_span)));
                }
                if is_let {
                    // `for (let of ...)`, `for (let.something of ...)` is not allowed
                    self.error(diagnostics::for_loop_let_reserved_word(self.end_span(expr_span)));
                }
                let target = AssignmentTarget::cover(init_expression, self);
                let for_stmt_left = ForStatementLeft::from(target);
                self.parse_for_of_loop(span, parenthesis_opening_span, r#await, for_stmt_left)
            }
            _ => self.parse_for_loop(
                span,
                parenthesis_opening_span,
                Some(ForStatementInit::from(init_expression)),
                r#await,
            ),
        }
    }

    fn parse_variable_declaration_for_statement(
        &mut self,
        span: u32,
        start_span: u32,
        parenthesis_opening_span: Span,
        decl_kind: VariableDeclarationKind,
        r#await: bool,
    ) -> Statement<'a> {
        let init_declaration = self.context_remove(Context::In, |p| {
            p.parse_variable_declaration(
                start_span,
                decl_kind,
                VariableDeclarationParent::For,
                false,
            )
        });

        self.parse_any_for_loop(span, parenthesis_opening_span, init_declaration, r#await)
    }

    pub(crate) fn is_using_declaration(&mut self) -> bool {
        let token = self.lexer.peek_token();
        let kind = token.kind();
        (kind.is_binding_identifier() || kind == Kind::LCurly) && !token.is_on_new_line()
    }

    fn parse_using_declaration_for_statement(
        &mut self,
        span: u32,
        parenthesis_opening_span: Span,
        r#await: bool,
    ) -> Statement<'a> {
        let using_decl = self.parse_using_declaration(StatementContext::For);

        if matches!(self.cur_kind(), Kind::In) {
            if using_decl.kind.is_await() {
                self.error(diagnostics::await_using_declaration_not_allowed_in_for_in_statement(
                    using_decl.span,
                ));
            } else {
                self.error(diagnostics::using_declaration_not_allowed_in_for_in_statement(
                    using_decl.span,
                ));
            }
        }

        self.parse_any_for_loop(span, parenthesis_opening_span, using_decl, r#await)
    }

    fn parse_any_for_loop(
        &mut self,
        span: u32,
        parenthesis_opening_span: Span,
        init_declaration: ArenaBox<'a, VariableDeclaration<'a>>,
        r#await: bool,
    ) -> Statement<'a> {
        match self.cur_kind() {
            Kind::In => self.parse_for_in_loop(
                span,
                parenthesis_opening_span,
                r#await,
                ForStatementLeft::VariableDeclaration(init_declaration),
            ),
            Kind::Of => self.parse_for_of_loop(
                span,
                parenthesis_opening_span,
                r#await,
                ForStatementLeft::VariableDeclaration(init_declaration),
            ),
            _ => self.parse_for_loop(
                span,
                parenthesis_opening_span,
                Some(ForStatementInit::VariableDeclaration(init_declaration)),
                r#await,
            ),
        }
    }

    fn parse_for_loop(
        &mut self,
        span: u32,
        parenthesis_opening_span: Span,
        init: Option<ForStatementInit<'a>>,
        r#await: bool,
    ) -> Statement<'a> {
        self.expect(Kind::Semicolon);
        if let Some(ForStatementInit::VariableDeclaration(decl)) = &init {
            for d in &decl.declarations {
                self.check_missing_initializer(d);
            }
        }
        let test = if matches!(self.cur_kind(), Kind::Semicolon | Kind::RParen) {
            None
        } else {
            Some(self.context_add(Context::In, ParserImpl::parse_expr))
        };
        self.expect(Kind::Semicolon);
        let update = if self.at(Kind::RParen) {
            None
        } else {
            Some(self.context_add(Context::In, ParserImpl::parse_expr))
        };
        self.expect_closing(Kind::RParen, parenthesis_opening_span);
        if r#await {
            self.error(diagnostics::for_await(self.end_span(span)));
        }
        let body = self.parse_statement_list_item(StatementContext::For);
        Statement::new_for_statement(self.end_span(span), init, test, update, body, self)
    }

    fn parse_for_in_loop(
        &mut self,
        span: u32,
        parenthesis_opening_span: Span,
        r#await: bool,
        left: ForStatementLeft<'a>,
    ) -> Statement<'a> {
        self.bump_any(); // bump `in`
        let right = self.parse_expr();
        self.expect_closing(Kind::RParen, parenthesis_opening_span);

        if r#await {
            self.error(diagnostics::for_await(self.end_span(span)));
        }

        let body = self.parse_statement_list_item(StatementContext::For);
        let span = self.end_span(span);
        Statement::new_for_in_statement(span, left, right, body, self)
    }

    fn parse_for_of_loop(
        &mut self,
        span: u32,
        parenthesis_opening_span: Span,
        r#await: bool,
        left: ForStatementLeft<'a>,
    ) -> Statement<'a> {
        self.bump_any(); // bump `of`
        let right = self.parse_assignment_expression_or_higher();
        self.expect_closing(Kind::RParen, parenthesis_opening_span);

        let body = self.parse_statement_list_item(StatementContext::For);
        let span = self.end_span(span);
        Statement::new_for_of_statement(span, r#await, left, right, body, self)
    }

    /// Section 14.8 Continue Statement
    fn parse_continue_statement(&mut self) -> Statement<'a> {
        let span = self.start_span();
        self.bump_any(); // bump `continue`
        let label =
            if self.can_insert_semicolon() { None } else { Some(self.parse_label_identifier()) };
        self.asi();
        Statement::new_continue_statement(self.end_span(span), label, self)
    }

    /// Section 14.9 Break Statement
    fn parse_break_statement(&mut self) -> Statement<'a> {
        let span = self.start_span();
        self.bump_any(); // bump `break`
        let label =
            if self.can_insert_semicolon() { None } else { Some(self.parse_label_identifier()) };
        self.asi();
        Statement::new_break_statement(self.end_span(span), label, self)
    }

    /// Section 14.10 Return Statement
    /// `ReturnStatement`[Yield, Await] :
    ///   return ;
    ///   return [no `LineTerminator` here] Expression[+In, ?Yield, ?Await] ;
    fn parse_return_statement(&mut self) -> Statement<'a> {
        let span = self.start_span();
        self.bump_any(); // advance `return`
        let argument = if self.eat(Kind::Semicolon) || self.can_insert_semicolon() {
            None
        } else {
            let expr = self.context_add(Context::In, ParserImpl::parse_expr);
            self.asi();
            Some(expr)
        };
        if !self.ctx.has_return() {
            self.error(diagnostics::return_statement_only_in_function_body(Span::sized(span, 6)));
        }
        Statement::new_return_statement(self.end_span(span), argument, self)
    }

    /// Section 14.11 With Statement
    fn parse_with_statement(&mut self) -> Statement<'a> {
        let span = self.start_span();
        self.bump_any(); // bump `with`
        let object = self.parse_paren_expression();
        let body = self.parse_statement_list_item(StatementContext::With);
        let span = self.end_span(span);
        Statement::new_with_statement(span, object, body, self)
    }

    /// Section 14.12 Switch Statement
    fn parse_switch_statement(&mut self) -> Statement<'a> {
        let span = self.start_span();
        self.bump_any(); // advance `switch`
        let discriminant = self.parse_paren_expression();
        // A `switch` may contain at most one `default` clause. Track the first one
        // and report only the first duplicate, all in the single parsing pass.
        let mut first_default: Option<Span> = None;
        let mut reported_duplicate = false;
        let cases = self.parse_normal_list(Kind::LCurly, Kind::RCurly, |p| {
            let case = p.parse_switch_case();
            if case.test.is_none() {
                match first_default {
                    None => first_default = Some(case.span),
                    Some(first_span) if !reported_duplicate => {
                        p.error(diagnostics::switch_multiple_default_clause(first_span, case.span));
                        reported_duplicate = true;
                    }
                    Some(_) => {}
                }
            }
            case
        });
        Statement::new_switch_statement(self.end_span(span), discriminant, cases, self)
    }

    pub(crate) fn parse_switch_case(&mut self) -> SwitchCase<'a> {
        let span = self.start_span();
        let test = match self.cur_kind() {
            Kind::Default => {
                self.bump_any();
                None
            }
            Kind::Case => {
                self.bump_any();
                let expression = self.parse_expr();
                Some(expression)
            }
            _ => {
                return self
                    .fatal_error(diagnostics::expect_switch_clause(self.cur_token().span()));
            }
        };
        self.expect(Kind::Colon);
        let mut consequent = ArenaVec::new_in(self);
        loop {
            let kind = self.cur_kind();
            if matches!(
                kind,
                Kind::Case | Kind::Default | Kind::RCurly | Kind::Eof | Kind::Undetermined
            ) || self.fatal_error.is_some()
            {
                break;
            }
            let stmt = self.parse_statement_list_item(StatementContext::StatementList);
            if let Statement::VariableDeclaration(var_decl) = &stmt
                && var_decl.kind.is_using()
            {
                // It is a Syntax Error if UsingDeclaration is contained directly within the StatementList of either a CaseClause or DefaultClause.
                // It is a Syntax Error if AwaitUsingDeclaration is contained directly within the StatementList of either a CaseClause or DefaultClause.
                self.error(diagnostics::using_declaration_not_allowed_in_switch_bare_case(
                    stmt.span(),
                ));
            }
            consequent.push(stmt);
        }
        SwitchCase::new(self.end_span(span), test, consequent, self)
    }

    /// Section 14.14 Throw Statement
    fn parse_throw_statement(&mut self) -> Statement<'a> {
        let span = self.start_span();
        self.bump_any(); // advance `throw`
        if self.cur_token().is_on_new_line() {
            self.error(diagnostics::illegal_newline(
                "throw",
                self.end_span(span),
                self.cur_token().span(),
            ));
        }
        let argument = self.parse_expr();
        self.asi();
        Statement::new_throw_statement(self.end_span(span), argument, self)
    }

    /// Section 14.15 Try Statement
    fn parse_try_statement(&mut self) -> Statement<'a> {
        let span = self.start_span();
        self.bump_any(); // bump `try`

        let block = self.parse_block();

        let handler = self.at(Kind::Catch).then(|| self.parse_catch_clause());

        let finalizer = self.eat(Kind::Finally).then(|| self.parse_block());

        if handler.is_none() && finalizer.is_none() {
            let range = Span::empty(block.span.end);
            self.error(diagnostics::expect_catch_finally(range));
        }

        Statement::new_try_statement(self.end_span(span), block, handler, finalizer, self)
    }

    fn parse_catch_clause(&mut self) -> ArenaBox<'a, CatchClause<'a>> {
        let span = self.start_span();
        self.bump_any(); // advance `catch`
        let pattern = if self.eat(Kind::LParen) {
            let (pattern, type_annotation) = self.parse_binding_pattern_with_type_annotation();
            self.expect(Kind::RParen);
            Some((pattern, type_annotation))
        } else {
            None
        };
        let body = self.parse_block();
        let param = pattern.map(|(pattern, type_annotation)| {
            CatchParameter::new(
                Span::new(
                    pattern.span().start,
                    type_annotation.as_ref().map_or(pattern.span().end, |ta| ta.span.end),
                ),
                pattern,
                type_annotation,
                self,
            )
        });
        CatchClause::boxed(self.end_span(span), param, body, self)
    }

    /// Section 14.16 Debugger Statement
    fn parse_debugger_statement(&mut self) -> Statement<'a> {
        let span = self.start_span();
        self.bump_any();
        self.asi();
        Statement::new_debugger_statement(self.end_span(span), self)
    }

    /// Parse const declaration or `const enum`.
    fn parse_const_statement(&mut self, stmt_ctx: StatementContext) -> Statement<'a> {
        let span = self.start_span();
        self.bump_any();
        if self.is_ts && self.at(Kind::Enum) {
            let modifiers = Modifiers::new_single(ModifierKind::Const, span);
            Statement::from(self.parse_ts_enum_declaration(span, &modifiers))
        } else {
            self.parse_variable_statement(span, VariableDeclarationKind::Const, stmt_ctx)
        }
    }

    /// Parse import statement or import expression.
    fn parse_import_statement(&mut self) -> Statement<'a> {
        let span = self.start_span();
        if matches!(self.lexer.peek_token().kind(), Kind::Dot | Kind::LParen) {
            // Parse the whole expression `import.meta.url`.
            self.parse_expression_or_labeled_statement()
        } else {
            self.bump_any(); // bump `import`
            self.parse_import_declaration(span, self.ctx.has_top_level())
        }
    }

    /// Parse statements that start with `sync`.
    fn parse_async_statement(&mut self, span: u32, stmt_ctx: StatementContext) -> Statement<'a> {
        let token = self.lexer.peek_token();
        if token.kind() == Kind::Function && !token.is_on_new_line() {
            self.bump_any(); // bump `async`
            return self.parse_function_declaration(span, /* async */ true, stmt_ctx);
        }
        if self.is_ts && self.at_start_of_ts_declaration() {
            return self.parse_ts_declaration_statement(span, stmt_ctx);
        }
        self.parse_expression_or_labeled_statement()
    }

    /// Parse statements that start with `@`.
    fn parse_decorated_statement(&mut self, stmt_ctx: StatementContext) -> Statement<'a> {
        let span = self.start_span();
        let decorators = self.parse_decorators();
        let kind = self.cur_kind();
        if kind == Kind::Export {
            // Export span.start starts after decorators.
            return self.parse_export_declaration(self.start_span(), decorators);
        }
        let modifiers = self.parse_modifiers(false, false);
        if self.at(Kind::Class) {
            // Class span.start starts before decorators.
            return self.parse_class_statement(span, stmt_ctx, &modifiers, decorators);
        }
        self.unexpected()
    }
}
