Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Modularize try statement parsing #390

Merged
merged 5 commits into from
May 11, 2020
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 61 additions & 0 deletions boa/src/syntax/parser/statement/try_stm/catch.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
use super::catchparam::CatchParameter;
use crate::syntax::{
ast::{keyword::Keyword, node::Node, punc::Punctuator},
parser::{
statement::block::Block, AllowAwait, AllowReturn, AllowYield, Cursor, ParseError,
TokenParser,
},
};

/// Catch parsing
///
/// More information:
/// - [MDN documentation][mdn]
/// - [ECMAScript specification][spec]
///
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch
/// [spec]: https://tc39.es/ecma262/#prod-Catch
#[derive(Debug, Clone, Copy)]
pub(super) struct Catch {
allow_yield: AllowYield,
allow_await: AllowAwait,
allow_return: AllowReturn,
}

impl Catch {
/// Creates a new `Catch` block parser.
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 TokenParser for Catch {
type Output = (Option<Node>, Option<Node>);

fn parse(self, cursor: &mut Cursor<'_>) -> Result<Self::Output, ParseError> {
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
};

// Catch block
Ok((
Some(Block::new(self.allow_yield, self.allow_await, self.allow_return).parse(cursor)?),
catch_param,
))
}
}
51 changes: 51 additions & 0 deletions boa/src/syntax/parser/statement/try_stm/catchparam.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
use crate::syntax::{
ast::{node::Node, token::TokenKind},
parser::{AllowAwait, AllowYield, Cursor, ParseError, ParseResult, TokenParser},
};

/// CatchParameter parsing
///
/// More information:
/// - [MDN documentation][mdn]
/// - [ECMAScript specification][spec]
///
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch
/// [spec]: https://tc39.es/ecma262/#prod-CatchParameter
#[derive(Debug, Clone, Copy)]
pub(super) struct CatchParameter {
allow_yield: AllowYield,
allow_await: AllowAwait,
}

impl CatchParameter {
/// Creates a new `CatchParameter` parser.
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 TokenParser for CatchParameter {
type Output = Node;

fn parse(self, cursor: &mut Cursor<'_>) -> ParseResult {
// TODO: should accept BindingPattern
let tok = cursor.next().ok_or(ParseError::AbruptEnd)?;
let catch_param = if let TokenKind::Identifier(s) = &tok.kind {
Node::local(s)
} else {
return Err(ParseError::Expected(
vec![TokenKind::identifier("identifier")],
tok.clone(),
"catch in try statement",
));
};
Ok(catch_param)
}
}
47 changes: 47 additions & 0 deletions boa/src/syntax/parser/statement/try_stm/finally.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
use crate::syntax::{
ast::{keyword::Keyword, node::Node},
parser::{
statement::block::Block, AllowAwait, AllowReturn, AllowYield, Cursor, ParseResult,
TokenParser,
},
};

/// Finally parsing
///
/// More information:
/// - [MDN documentation][mdn]
/// - [ECMAScript specification][spec]
///
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch
/// [spec]: https://tc39.es/ecma262/#prod-Finally
#[derive(Debug, Clone, Copy)]
pub(super) struct Finally {
allow_yield: AllowYield,
allow_await: AllowAwait,
allow_return: AllowReturn,
}

impl Finally {
/// Creates a new `Finally` block parser.
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 TokenParser for Finally {
type Output = Node;

fn parse(self, cursor: &mut Cursor<'_>) -> ParseResult {
cursor.expect(Keyword::Finally, "try statement")?;
Ok(Block::new(self.allow_yield, self.allow_await, self.allow_return).parse(cursor)?)
}
}
48 changes: 20 additions & 28 deletions boa/src/syntax/parser/statement/try_stm/mod.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,15 @@
mod catch;
mod catchparam;
mod finally;

#[cfg(test)]
mod tests;

use self::catch::Catch;
use self::finally::Finally;
use super::block::Block;
use crate::syntax::{
ast::{keyword::Keyword, node::Node, punc::Punctuator, token::TokenKind},
ast::{keyword::Keyword, node::Node, token::TokenKind},
parser::{AllowAwait, AllowReturn, AllowYield, Cursor, ParseError, ParseResult, TokenParser},
};

Expand Down Expand Up @@ -63,38 +69,24 @@ impl TokenParser for TryStatement {
));
}

// CATCH
let (catch, param) = if next_token.kind == TokenKind::Keyword(Keyword::Catch) {
// Catch binding
cursor.expect(Punctuator::OpenParen, "catch in try statement")?;
// TODO: should accept BindingPattern
let tok = cursor.next().ok_or(ParseError::AbruptEnd)?;
let catch_param = if let TokenKind::Identifier(s) = &tok.kind {
Node::local(s)
} else {
return Err(ParseError::Expected(
vec![TokenKind::identifier("identifier")],
tok.clone(),
"catch in try statement",
));
};
cursor.expect(Punctuator::CloseParen, "catch in try statement")?;

// Catch block
(
Some(
Block::new(self.allow_yield, self.allow_await, self.allow_return)
.parse(cursor)?,
),
Some(catch_param),
)
match Catch::new(self.allow_yield, self.allow_await, self.allow_return).parse(cursor) {
Ok((catch, param)) => (catch, param),
Err(e) => return Err(e),
}
abhijeetbhagat marked this conversation as resolved.
Show resolved Hide resolved
} else {
(None, None)
};

// FINALLY
let finally_block = if cursor.next_if(Keyword::Finally).is_some() {
Some(Block::new(self.allow_yield, self.allow_await, self.allow_return).parse(cursor)?)
let next_token = cursor.peek(0);
let finally_block = if next_token.is_some()
&& next_token.unwrap().kind == TokenKind::Keyword(Keyword::Finally)
abhijeetbhagat marked this conversation as resolved.
Show resolved Hide resolved
{
match Finally::new(self.allow_yield, self.allow_await, self.allow_return).parse(cursor)
{
Ok(finally) => Some(finally),
Err(e) => return Err(e),
}
abhijeetbhagat marked this conversation as resolved.
Show resolved Hide resolved
} else {
None
};
Expand Down
124 changes: 124 additions & 0 deletions boa/src/syntax/parser/statement/try_stm/tests.rs
Original file line number Diff line number Diff line change
@@ -1 +1,125 @@
use crate::syntax::{
ast::node::Node,
parser::tests::{check_invalid, check_parser},
};

#[test]
fn check_inline_with_empty_try_catch() {
check_parser(
"try { } catch(e) {}",
vec![Node::try_node::<_, _, _, _, Node, Node, Node>(
Node::block(vec![]),
Node::block(vec![]),
Node::local("e"),
None,
)],
);
}

#[test]
fn check_inline_with_var_decl_inside_try() {
check_parser(
"try { var x = 1; } catch(e) {}",
vec![Node::try_node::<_, _, _, _, Node, Node, Node>(
Node::block(vec![Node::var_decl(vec![(
String::from("x"),
Some(Node::const_node(1)),
)])]),
Node::block(vec![]),
Node::local("e"),
None,
)],
);
}

#[test]
fn check_inline_with_var_decl_inside_catch() {
check_parser(
"try { var x = 1; } catch(e) { var x = 1; }",
vec![Node::try_node::<_, _, _, _, Node, Node, Node>(
Node::block(vec![Node::var_decl(vec![(
String::from("x"),
Some(Node::const_node(1)),
)])]),
Node::block(vec![Node::var_decl(vec![(
String::from("x"),
Some(Node::const_node(1)),
)])]),
Node::local("e"),
None,
)],
);
}

#[test]
fn check_inline_with_empty_try_catch_finally() {
check_parser(
"try {} catch(e) {} finally {}",
vec![Node::try_node::<_, _, _, _, Node, Node, Node>(
Node::block(vec![]),
Node::block(vec![]),
Node::local("e"),
Node::block(vec![]),
)],
);
}

#[test]
fn check_inline_with_empty_try_finally() {
check_parser(
"try {} finally {}",
vec![Node::try_node::<_, _, _, _, Node, Node, Node>(
Node::block(vec![]),
None,
None,
Node::block(vec![]),
)],
);
}

#[test]
fn check_inline_with_empty_try_var_decl_in_finally() {
check_parser(
"try {} finally { var x = 1; }",
vec![Node::try_node::<_, _, _, _, Node, Node, Node>(
Node::block(vec![]),
None,
None,
Node::block(vec![Node::var_decl(vec![(
String::from("x"),
Some(Node::const_node(1)),
)])]),
)],
);
}

#[test]
fn check_inline_empty_try_paramless_catch() {
check_parser(
"try {} catch { var x = 1; }",
vec![Node::try_node::<_, _, _, _, Node, Node, Node>(
Node::block(vec![]),
Node::block(vec![Node::var_decl(vec![(
String::from("x"),
Some(Node::const_node(1)),
)])]),
None,
None,
)],
);
}

#[test]
fn check_inline_invalid_catch() {
check_invalid("try {} catch");
}

#[test]
fn check_inline_invalid_catch_without_closing_paren() {
check_invalid("try {} catch(e {}");
}

#[test]
fn check_inline_invalid_catch_parameter() {
check_invalid("try {} catch(1) {}");
}