Better try/else/finally for 3.x

This commit is contained in:
rocky
2020-01-11 21:33:22 -05:00
parent aaf8729772
commit aaba4ecb2b
3 changed files with 28 additions and 2 deletions

View File

@@ -429,8 +429,11 @@ TABLE_DIRECT = {
'tryelsestmt': ( '%|try:\n%+%c%-%c%|else:\n%+%c%-\n\n', 1, 3, 4 ),
'tryelsestmtc': ( '%|try:\n%+%c%-%c%|else:\n%+%c%-', 1, 3, 4 ),
'tryelsestmtl': ( '%|try:\n%+%c%-%c%|else:\n%+%c%-', 1, 3, 4 ),
# Note: this is generated generated by grammar rules but in this phase.
'tf_try_except': ( '%c%-%c%+', 1, 3 ),
'tf_tryelsestmt': ( '%c%-%c%|else:\n%+%c', 1, 3, 4 ),
'tryfinallystmt': ( '%|try:\n%+%c%-%|finally:\n%+%c%-\n\n', 1, 5 ),
'except': ( '%|except:\n%+%c%-', 3 ),
'except_cond1': ( '%|except %c:\n', 1 ),

View File

@@ -1,4 +1,4 @@
# Copyright (c) 2019 by Rocky Bernstein
# Copyright (c) 2019-2020 by Rocky Bernstein
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
@@ -37,7 +37,9 @@ def customize_for_version25(self, version):
# In 2.5+ "except" handlers and the "finally" can appear in one
# "try" statement. So the below has the effect of combining the
# "tryfinally" with statement with the "try_except" statement
# "tryfinally" with statement with the "try_except" statement.
# FIXME: something doesn't smell right, since the semantics
# are different. See test_fileio.py for an example that shows this.
def tryfinallystmt(node):
if len(node[1][0]) == 1 and node[1][0][0] == 'stmt':
if node[1][0][0][0] == 'try_except':

View File

@@ -51,6 +51,7 @@ def customize_for_version3(self, version):
"import_cont": (", %c", 2),
"kwarg": ("%[0]{attr}=%c", 1),
"raise_stmt2": ("%|raise %c from %c\n", 0, 1),
"tf_tryelsestmtl3": ( '%c%-%c%|else:\n%+%c', 1, 3, 5 ),
"store_locals": ("%|# inspect.currentframe().f_locals = __locals__\n",),
"withstmt": ("%|with %c:\n%+%c%-", 0, 3),
"withasstmt": ("%|with %c as (%c):\n%+%c%-", 0, 2, 3),
@@ -59,6 +60,26 @@ def customize_for_version3(self, version):
assert version >= 3.0
# In 2.5+ and 3.0+ "except" handlers and the "finally" can appear in one
# "try" statement. So the below has the effect of combining the
# "tryfinally" with statement with the "try_except" statement.
# FIXME: something doesn't smell right, since the semantics
# are different. See test_fileio.py for an example that shows this.
def tryfinallystmt(node):
suite_stmts = node[1][0]
if len(suite_stmts) == 1 and suite_stmts[0] == 'stmt':
stmt = suite_stmts[0]
try_something = stmt[0]
if try_something == "try_except":
try_something.kind = "tf_try_except"
if try_something.kind.startswith("tryelsestmt"):
if try_something == "tryelsestmtl3":
try_something.kind = 'tf_tryelsestmtl3'
else:
try_something.kind = 'tf_tryelsestmt'
self.default(node)
self.n_tryfinallystmt = tryfinallystmt
def listcomp_closure3(node):
"""List comprehensions in Python 3 when handled as a closure.
See if we can combine code.