Commit 8a55840a authored by Tom Niget's avatar Tom Niget

Add `with` block desugaring

parent c8d6c8db
......@@ -2,6 +2,7 @@
import ast
from transpiler.consts import MAPPINGS
from transpiler.phases.desugar_with import DesugarWith
#from transpiler.phases import initial_pytype
from transpiler.phases.emit_cpp.file import FileVisitor
from transpiler.phases.if_main import IfMainVisitor
......@@ -12,6 +13,7 @@ from transpiler.phases.typing.scope import Scope
def transpile(source):
res = ast.parse(source, type_comments=True)
#res = initial_pytype.run(source, res)
res = DesugarWith().visit(res)
IfMainVisitor().visit(res)
ScoperBlockVisitor().visit(res)
#print(res.scope)
......
# coding: utf-8
import ast
from transpiler.phases.utils import PlainBlock
def process(items: list[ast.withitem], body: list[ast.stmt]) -> PlainBlock:
first, *rest = items
val, name = first.context_expr, first.optional_vars
cm_name = ast.Name(id=f"cm_{hash(first)}")
res = [
ast.Assign(targets=[cm_name], value=val)
]
enter_call = ast.Call(func=ast.Attribute(value=cm_name, attr="__enter__"), args=[], keywords=[])
if name:
res.append(ast.Assign(targets=[name], value=enter_call))
else:
res.append(ast.Expr(value=enter_call))
if rest:
res.append(process(rest, body))
else:
res.append(PlainBlock(body))
res.append(ast.Expr(value=ast.Call(func=ast.Attribute(value=cm_name, attr="__exit__"), args=[], keywords=[])))
return PlainBlock(res)
class DesugarWith(ast.NodeTransformer):
def visit_With(self, node: ast.With):
return process(node.items, node.body)
\ No newline at end of file
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment