~nch/python-compiler

4f6dd03f124508cd1231b19c70e3ad5821318265 — nc 1 year, 11 months ago 381d6b4
add anf transform for variable assignment
2 files changed, 16 insertions(+), 0 deletions(-)

M compiler.py
M test_compiler.py
M compiler.py => compiler.py +11 -0
@@ 1,4 1,6 @@
#!/usr/bin/env python3
# yank the following, and execute :@"
# set makeprg=python3\ ./compiler.py\ &&\ python3\ ./test_compiler.py

from dataclasses import dataclass
from functools import singledispatch


@@ 475,6 477,15 @@ def _(e: Return):
    else:
        return n

@normalize_stmt.register(Assign)
def _(e: Assign):
    n, hoisted = normalize_expr(e.rhs)
    norm_a = Assign(e.lhs, n)
    if hoisted:
        return hoisted.add(norm_a)
    else:
        return norm_a

@singledispatch
def normalize_expr(node):
    return node, Block()

M test_compiler.py => test_compiler.py +5 -0
@@ 96,6 96,11 @@ else:
                 ('=', 'tmp7', ('a', 'tmp6')),
                 ('return', 'tmp7')])

        tree6 = Assign('x', FunctionCall('a', FunctionCall('b')))
        self.assertEqual(normalize_stmt(tree6),
                [('=', 'tmp8', ('b',)),
                 ('=', 'x', ('a', 'tmp8'))])


if __name__ == '__main__':
    unittest.main()