Commits

Maciej Fijalkowski committed e75d7cc

pass the first test

  • Participants
  • Parent commits a62a631
  • Tags compiler-start

Comments (0)

Files changed (3)

File kermit/bytecode.py

         self.data.append(chr(bc))
         self.data.append(chr(arg))
 
+    def create_bytecode(self):
+        return ByteCode("".join(self.data), self.constants[:], len(self.names))
+
 class ByteCode(object):
-    def __init__(self, code, constants):
+    def __init__(self, code, constants, numvars):
         self.code = code
         self.constants = constants
+        self.numvars = numvars
 
     def dump(self):
         lines = []
         for i in range(0, len(self.code), 2):
             c = self.code[i]
             c2 = self.code[i + 1]
-            lines.append(bytecodes[ord(c)] + " " + str(bytecodes[ord(c2)]))
+            lines.append(bytecodes[ord(c)] + " " + str(ord(c2)))
         return '\n'.join(lines)
 
 def compile_ast(astnode):

File kermit/sourceparser.py

 import py
 from pypy.rlib.parsing.ebnfparse import parse_ebnf, make_parse_function
 from kermit import kermitdir
+from kermit import bytecode
 
 grammar = py.path.local(kermitdir).join('grammar.txt').read("rt")
 regexs, rules, ToAST = parse_ebnf(grammar)
     def __init__(self, stmts):
         self.stmts = stmts
 
+    def compile(self, ctx):
+        for stmt in self.stmts:
+            stmt.compile(ctx)
+
 class Stmt(Node):
     """ A single statement
     """
     def __init__(self, expr):
         self.expr = expr
 
+    def compile(self, ctx):
+        self.expr.compile(ctx)
+        ctx.emit(bytecode.DISCARD_TOP)
+
 class ConstantInt(Node):
     """ Represent a constant
     """
     def __init__(self, intval):
         self.intval = intval
 
+    def compile(self, ctx):
+        ctx.emit(bytecode.LOAD_CONSTANT, ctx.register_constant(self.intval))
+
 class BinOp(Node):
     """ A binary operation
     """

File kermit/test/test_compiler.py

 class TestCompiler(object):
     def check_compile(self, source, expected):
         bc = compile_ast(parse(source))
-        assert [i.strip() for i in expected if i] == bc.dump()
+        assert [i.strip() for i in expected.splitlines() if i.strip()] == bc.dump().splitlines()
 
     def test_basic(self):
         self.check_compile("1;", '''
         LOAD_CONSTANT 0
-        DISCARD_TOP
+        DISCARD_TOP 0
         ''')