From c33d4aefc3eb1d91d90c55b4d18e6b972fd8d6eb Mon Sep 17 00:00:00 2001 From: Andreas Kling Date: Tue, 24 Mar 2020 14:03:55 +0100 Subject: LibJS: Parse "try", "catch" and "finally" This is the first step towards support exceptions. :^) --- Libraries/LibJS/Parser.cpp | 37 ++++++++++++++++++++++++++++++++++++- 1 file changed, 36 insertions(+), 1 deletion(-) (limited to 'Libraries/LibJS/Parser.cpp') diff --git a/Libraries/LibJS/Parser.cpp b/Libraries/LibJS/Parser.cpp index 082f83f457..77e892e553 100644 --- a/Libraries/LibJS/Parser.cpp +++ b/Libraries/LibJS/Parser.cpp @@ -197,6 +197,8 @@ NonnullRefPtr Parser::parse_statement() return parse_for_statement(); case TokenType::If: return parse_if_statement(); + case TokenType::Try: + return parse_try_statement(); default: if (match_expression()) return adopt(*new ExpressionStatement(parse_expression(0))); @@ -518,6 +520,40 @@ NonnullRefPtr Parser::parse_variable_declaration() return create_ast_node(create_ast_node(name), move(initializer), declaration_type); } +NonnullRefPtr Parser::parse_try_statement() +{ + consume(TokenType::Try); + + auto block = parse_block_statement(); + + RefPtr handler; + if (match(TokenType::Catch)) + handler = parse_catch_clause(); + + RefPtr finalizer; + if (match(TokenType::Finally)) { + consume(); + finalizer = parse_block_statement(); + } + + return create_ast_node(move(block), move(handler), move(finalizer)); +} + +NonnullRefPtr Parser::parse_catch_clause() +{ + consume(TokenType::Catch); + + String parameter; + if (match(TokenType::ParenOpen)) { + consume(); + parameter = consume(TokenType::Identifier).value(); + consume(TokenType::ParenClose); + } + + auto body = parse_block_statement(); + return create_ast_node(parameter, move(body)); +} + NonnullRefPtr Parser::parse_if_statement() { consume(TokenType::If); @@ -660,7 +696,6 @@ bool Parser::match_statement() const || type == TokenType::Function || type == TokenType::Return || type == TokenType::Let - || type == TokenType::Catch || type == TokenType::Class || type == TokenType::Delete || type == TokenType::Do -- cgit v1.2.3