use crate::{
syntax::{
ast::{
node::{self, Identifier},
Keyword, Punctuator,
},
parser::{
statement::{block::Block, BindingIdentifier},
AllowAwait, AllowReturn, AllowYield, Cursor, ParseError, TokenParser,
},
},
BoaProfiler,
};
use std::io::Read;
#[derive(Debug, Clone, Copy)]
pub(super) struct Catch {
allow_yield: AllowYield,
allow_await: AllowAwait,
allow_return: AllowReturn,
}
impl Catch {
pub(super) fn new<Y, A, R>(allow_yield: Y, allow_await: A, allow_return: R) -> Self
where
Y: Into<AllowYield>,
A: Into<AllowAwait>,
R: Into<AllowReturn>,
{
Self {
allow_yield: allow_yield.into(),
allow_await: allow_await.into(),
allow_return: allow_return.into(),
}
}
}
impl<R> TokenParser<R> for Catch
where
R: Read,
{
type Output = node::Catch;
fn parse(self, cursor: &mut Cursor<R>) -> Result<Self::Output, ParseError> {
let _timer = BoaProfiler::global().start_event("Catch", "Parsing");
cursor.expect(Keyword::Catch, "try statement")?;
let catch_param = if cursor.next_if(Punctuator::OpenParen)?.is_some() {
let catch_param =
CatchParameter::new(self.allow_yield, self.allow_await).parse(cursor)?;
cursor.expect(Punctuator::CloseParen, "catch in try statement")?;
Some(catch_param)
} else {
None
};
Ok(node::Catch::new::<_, Identifier, _>(
catch_param,
Block::new(self.allow_yield, self.allow_await, self.allow_return).parse(cursor)?,
))
}
}
#[derive(Debug, Clone, Copy)]
pub(super) struct CatchParameter {
allow_yield: AllowYield,
allow_await: AllowAwait,
}
impl CatchParameter {
pub(super) fn new<Y, A>(allow_yield: Y, allow_await: A) -> Self
where
Y: Into<AllowYield>,
A: Into<AllowAwait>,
{
Self {
allow_yield: allow_yield.into(),
allow_await: allow_await.into(),
}
}
}
impl<R> TokenParser<R> for CatchParameter
where
R: Read,
{
type Output = Identifier;
fn parse(self, cursor: &mut Cursor<R>) -> Result<Identifier, ParseError> {
BindingIdentifier::new(self.allow_yield, self.allow_await)
.parse(cursor)
.map(Identifier::from)
}
}