~nch/python-compiler

1a3570732272f5ecb65f02943f92bbab9726d7f6 — nc 2 months ago 25ad11e
first full program compiling from source!
2 files changed, 11 insertions(+), 5 deletions(-)

M compiler.py
M test_compiler.py
M compiler.py => compiler.py +3 -3
@@ 438,15 438,15 @@ assign_stmt_body: ParserT = convert(seq(identifier, space, discard(char("=")), s
# <return-stmt-body> := 'return' <space> <expr>
return_stmt_body: ParserT = seq('return', space, expr)

if_stmt: ParserT = seq('if', space, expr, discard(char(':')),
if_stmt: ParserT = convert(seq('if', space, expr, discard(char(':')),
        lambda x: block(x),
        indentation('same'), 'else', discard(char(':')),
        lambda x: block(x))
        lambda x: block(x)), lambda x: If(x[1], x[2], x[4]))

# <stmt> := (<if-stmt> | <return-stmt-body> | <assign-stmt-body | <expr>) <newline>
stmt: ParserT = convert(seq(oneof(if_stmt, return_stmt_body, assign_stmt_body, expr), newline), lambda x: x[0])
# <block> := <newline> (<indent> <stmt>)+
block: ParserT = convert(seq(newline, one_or_more(convert(seq(indentation('indent'), stmt), lambda x: x[0]))), lambda x: x[0])
block: ParserT = convert(seq(newline, one_or_more(convert(seq(indentation('indent'), stmt), lambda x: x[0]))), lambda x: Block(*x[0]))
#import tmp; block = tmp.trace_function(block)
# <function> := 'def' <space> <identifier> '(' (<identifier> (',' <space> <identifier>)*) ')' ':' <newline> <block>
function: ParserT = seq('def', space, identifier, char('('), intersperse(identifier, discard(seq(char(','), space))), char(')'), char(':'), block)

M test_compiler.py => test_compiler.py +8 -2
@@ 340,10 340,16 @@ on some lines''')
            jne l
            '''))

    def test_codegen(self):
    def test_compiler(self):
        t = If(1, 7, 4)
        g = []
        code_gen(normalize_stmt(t), None, g)
        code_gen(normalize_stmt(parse(textwrap.dedent(
        '''\
        if 1:
            7
        else:
            4
        '''), if_stmt)), None, g)

        postlude = emit('rdi <- rax') +\
                   emit('rax <- 60') +\