From 19112cef493d0fbf6a80eb286ca680c4fe0034b7 Mon Sep 17 00:00:00 2001 From: Windel Bouwman Date: Mon, 19 Aug 2019 09:00:08 +0200 Subject: [PATCH] Require at least finally or except on a try statement. --- parser/src/python.lalrpop | 23 +++++++++++++++-------- tests/snippets/try_exceptions.py | 19 ++++++++++++++----- 2 files changed, 29 insertions(+), 13 deletions(-) diff --git a/parser/src/python.lalrpop b/parser/src/python.lalrpop index f6ac629bc..2ee1e90d9 100644 --- a/parser/src/python.lalrpop +++ b/parser/src/python.lalrpop @@ -365,8 +365,8 @@ ForStatement: ast::Statement = { }; TryStatement: ast::Statement = { - "try" ":" => { - let (handlers, orelse) = handlers.unwrap_or_default(); + "try" ":" => { + let orelse = else_suite.map(|s| s.2); let finalbody = finally.map(|s| s.2); ast::Statement { location, @@ -378,12 +378,19 @@ TryStatement: ast::Statement = { }, } }, -}; - -ExceptionHandlers: (Vec, Option) = { - => { - let orelse = else_suite.map(|s| s.2); - (handlers, orelse) + "try" ":" => { + let handlers = vec![]; + let orelse = None; + let finalbody = Some(finally.2); + ast::Statement { + location, + node: ast::StatementType::Try { + body, + handlers, + orelse, + finalbody, + }, + } }, }; diff --git a/tests/snippets/try_exceptions.py b/tests/snippets/try_exceptions.py index 40100cb72..9ff56da77 100644 --- a/tests/snippets/try_exceptions.py +++ b/tests/snippets/try_exceptions.py @@ -240,10 +240,19 @@ except NameError as ex2: pass +# the else clause requires at least one except clause: with assertRaises(SyntaxError): - exec("""if True: - try: - pass - else: - pass + exec(""" +try: + pass +else: + pass """) + + +# Try requires at least except or finally (or both) +with assertRaises(SyntaxError): + exec(""" +try: + pass +""")