Maciej Fijalkowski avatar Maciej Fijalkowski committed 20842ba

bytecode boilerplate

Comments (0)

Files changed (2)

kermit/bytecode.py

+
+bytecodes = ['LOAD_CONSTANT', 'LOAD_VARIABLE', 'ASSIGN', 'DISCARD_TOP',
+             'JUMP_IF_FALSE', 'JUMP_BACKWARD', 'BINARY_ADD', 'BINARY_SUB',
+             'BINARY_EQ']
+for i, bytecode in enumerate(bytecodes):
+    globals()[bytecode] = i
+
+class CompilerContext(object):
+    def __init__(self):
+        self.data = []
+        self.constants = []
+        self.names = []
+        self.names_to_numbers = {}
+
+    def register_constant(self, v):
+        self.constants.append(v)
+        return len(self.constants) - 1
+
+    def register_var(self, name):
+        try:
+            return self.names_to_numbers[name]
+        except KeyError:
+            self.names_to_numbers[name] = len(self.names)
+            self.names.append(name)
+            return len(self.names) - 1
+
+    def emit(self, bc, arg=0):
+        self.data.append(chr(bc))
+        self.data.append(chr(arg))
+
+class ByteCode(object):
+    def __init__(self, code, constants):
+        self.code = code
+        self.constants = constants
+
+    def dump(self):
+        lines = []
+        i = 0
+        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)]))
+        return '\n'.join(lines)
+
+def compile_ast(astnode):
+    c = CompilerContext()
+    astnode.compile(c)
+    return c.create_bytecode()

kermit/test/test_compiler.py

+
+from kermit.sourceparser import parse
+from kermit.bytecode import compile_ast
+
+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()
+
+    def test_basic(self):
+        self.check_compile("1;", '''
+        LOAD_CONSTANT 0
+        DISCARD_TOP
+        ''')
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.