1. Alex Gaynor
  2. example-vm

Commits

Alex Gaynor  committed 438e001

Added a new print statement.

  • Participants
  • Parent commits 247a9d2
  • Branches master

Comments (0)

Files changed (5)

File minijs/consts.py

View file
     ("BINARY_DIV", 0, -1),
     ("BINARY_LT", 0, -1),
 
+    ("PRINT_ITEM", 0, -1),
+
     ("JUMP", 1, 0),
     ("JUMP_IF_FALSE", 1, -1),
 

File minijs/grammar.txt

View file
 
 statement: expr ";" |
            "if" "(" expr ")" "{" statement* "}" |
-           "while" "(" expr ")" "{" statement* "}";
+           "while" "(" expr ")" "{" statement* "}" |
+           "print" expr ";";
 
 expr: assignment | comparison;
 

File minijs/parser.py

View file
         ctx.emit(consts.JUMP, back_jump_target)
         ctx.patch_jump(pos)
 
+class Print(Node):
+    def __init__(self, expr):
+        self.expr = expr
+
+    def compile(self, ctx):
+        self.expr.compile(ctx)
+        ctx.emit(consts.PRINT_ITEM)
 
 class BinOp(Node):
     def __init__(self, op, lhs, rhs):
             return self.visit_if(node)
         elif info == "while":
             return self.visit_while(node)
+        elif info == "print":
+            return self.visit_print(node)
         raise NotImplementedError
 
     def visit_if(self, node):
             self.visit_block(node.children[5]),
         )
 
+    def visit_print(self, node):
+        return Print(
+            self.visit_expr(node.children[1])
+        )
+
     def visit_expr(self, node):
         if node.symbol == "expr":
             node = node.children[0]

File tests/test_compiler.py

View file
         DISCARD_TOP
         JUMP 5
         RETURN_NULL
+        """)
+
+    def test_print(self, space):
+        self.assert_compiles(space, "print 3;", """
+        LOAD_CONST 0
+        PRINT_ITEM
+        RETURN_NULL
         """)

File tests/test_parser.py

View file
-from minijs.parser import (Block, Stmt, If, While, Assignment, BinOp, Variable,
-    ConstantFloat)
+from minijs.parser import (Block, Stmt, If, While, Print, Assignment, BinOp,
+    Variable, ConstantFloat)
 
 
 class TestParser(object):
                     Stmt(Assignment("i", BinOp("+", Variable("i"), ConstantFloat(1))))
                 ])
             ),
-        ])
+        ])
+
+    def test_print(self, space):
+        assert space.parse("print 3;") == Block([Print(ConstantFloat(3))])