~nch/python-compiler

381d6b421bb754c2e69f8494f4ea5c286d06d750 — nc 1 year, 11 months ago 511ec7a
add anf transform for return stmt
2 files changed, 20 insertions(+), 0 deletions(-)

M compiler.py
M test_compiler.py
M compiler.py => compiler.py +13 -0
@@ 367,6 367,11 @@ class If(tuple):
    then = property(lambda s: s[2])
    otherwise = property(lambda s: s[3])

class Return(tuple):
    def __new__(cls, val):
        return super(Return, cls).__new__(cls, tuple(('return', val)))
    value = property(lambda s: s[1])

def intersperse(p, delimp):
    """
    Combinator.


@@ 462,6 467,14 @@ def _(ifnode: If):
    else:
        return norm_if

@normalize_stmt.register(Return)
def _(e: Return):
    n, hoisted = normalize_expr(e.value)
    if hoisted:
        return hoisted.add(Return(maybe_hoist(n, hoisted)))
    else:
        return n

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

M test_compiler.py => test_compiler.py +7 -0
@@ 90,5 90,12 @@ else:
                 ('=', 'tmp5', ('b', 'tmp4')),
                 ('if', 'tmp5', ['c'], [('d',)])])

        tree5 = Return(FunctionCall('a', FunctionCall('b')))
        self.assertEqual(normalize_stmt(tree5),
                [('=', 'tmp6', ('b',)),
                 ('=', 'tmp7', ('a', 'tmp6')),
                 ('return', 'tmp7')])


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