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

ENH: Implement support for with-blocks. #59

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
134 changes: 131 additions & 3 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,10 @@ def mangle(self, name):

def var(self, name):
name = self.mangle(name)
sym = self.table.lookup(name)
try:
sym = self.table.lookup(name)
except KeyError:
return name
if sym.is_global() or (self.table.get_type() == 'module' and sym.is_local()):
return T('{}').format(name)
elif sym.is_local():
Expand All @@ -177,7 +180,10 @@ def var(self, name):

def store_var(self, name):
name = self.mangle(name)
sym = self.table.lookup(name)
try:
sym = self.table.lookup(name)
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These were needed because I'm inserting assignments to names that weren't in the original source, which means they aren't in the symbol table.

except KeyError:
return name
if sym.is_global():
return T('{__g}[{!r}]').format(name)
elif sym.is_local():
Expand Down Expand Up @@ -727,7 +733,129 @@ def visit_While(self, tree):
test, orelse))

def visit_With(self, tree):
raise NotImplementedError('Open problem: with')

# Rewrite with-blocks as try-except statements as follows:
# with <expr> as <name>
# <block>
# ----------------------
# __anonymous = <expr>
# bar = __anonymous.__enter__()
# try:
# <block>
# except:
# if __anonymous.__exit__(*sys.exc_info()):
# raise
# else:
# __anonymous.__exit__(None, None, None)
if tree.optional_vars is not None:
ctx_bind_name = tree.optional_vars.id
else:
ctx_bind_name = '__anonymous__enter__result'

ctx_manager_name = '__anonymous'

manager_assign = ast.Assign(
targets=[ast.Name(id=ctx_manager_name, ctx=ast.Store())],
value=tree.context_expr,
)
context_expr_assign = ast.Assign(
targets=[ast.Name(id=ctx_bind_name, ctx=ast.Store())],
value=ast.Call(
func=ast.Attribute(
value=ast.Name(id=ctx_manager_name, ctx=ast.Store()),
attr='__enter__',
ctx=ast.Load(),
),
args=[],
keywords=[],
starargs=None,
kwargs=None,
)
)
# Rewrite the with-block body as:
# try:
# <body>
# except:
# if not <ctx_bind_name>.__exit__(*sys.exc_info()):
# raise
sys_module = ast.Call(
func=ast.Name(id='__import__', ctx=ast.Load()),
args=[
ast.Str(s='sys'),
],
keywords=[],
starargs=None,
kwargs=None,
)
none_node = ast.Name(id='None', ctx=ast.Load())

block = ast.TryExcept(
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Much of this is generated using an adapted version of the ast pretty printer I wrote here.

body=tree.body,
handlers=[
ast.ExceptHandler(
type=None,
name=None,
body=[
ast.If(
test=ast.UnaryOp(
op=ast.Not(),
operand=ast.Call(
func=ast.Attribute(
value=ast.Name(
id=ctx_manager_name,
ctx=ast.Load(),
),
attr='__exit__',
ctx=ast.Load(),
),
args=[],
keywords=[],
starargs=ast.Call(
func=ast.Attribute(
value=sys_module,
attr='exc_info',
ctx=ast.Load(),
),
args=[],
keywords=[],
starargs=None,
kwargs=None,
),
kwargs=None,
),
),
body=[
ast.Raise(
type=None,
inst=None,
tback=None,
),
],
orelse=[],
),
],
),
],
orelse=[
ast.Expr(
value=ast.Call(
func=ast.Attribute(
value=ast.Name(
id=ctx_manager_name,
ctx=ast.Load(),
),
attr='__exit__',
ctx=ast.Load(),
),
args=[none_node, none_node, none_node],
keywords=[],
starargs=None,
kwargs=None,
),
),
],
)
return self.many_to_one([manager_assign, context_expr_assign, block])

def visit_Yield(self, tree):
raise NotImplementedError('Open problem: yield')
Expand Down
16 changes: 16 additions & 0 deletions tests/with.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
class ContextManager(object):

def __enter__(self):
print "Entering"
return "__enter__ value"

def __exit__(self, type, value, traceback):
print "Exiting"

print "Before"
with ContextManager() as c:
print "In Body"
print c

# This currently fails for reasons I don't quite understand.
# print "After"
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This print isn't executed in the oneline-ified code if it's uncommented.

15 changes: 15 additions & 0 deletions tests/with_raise.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
class ContextManager(object):

def __enter__(self):
print "Entering"

def __exit__(self, type, value, traceback):
print "Exiting"


print "Before"
with ContextManager() as c:
print "In Body"
raise ValueError("Raise")

print "After"
19 changes: 19 additions & 0 deletions tests/with_suppressed_raise.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
class ContextManager(object):

def __enter__(self):
print "Entering"
return "__enter__ value"

def __exit__(self, type, value, traceback):
print "Exiting"
# Suppress the exception.
return True


print "Before"
with ContextManager() as c:
print "Before Raise"
raise ValueError("Raise")

# This currently fails for reasons I don't quite understand.
# print "After"
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ditto this one.