diff --git a/src/jasinta.py b/src/jasinta.py --- a/src/jasinta.py +++ b/src/jasinta.py @@ -1,4 +1,4 @@ -from std import lib as stdlib +from std import lib as stdlib, Number class Undefined: @@ -10,12 +10,14 @@ def evaluate(node, context): return None node_type = node["type"] + # retrieve an already existing object from the context if node_type == "Identifier": for ctx in reversed(context): if node["name"] in ctx: return ctx[node["name"]] return Undefined + # create a new object cls = node_index[node_type] obj = cls(node) return obj.eval(context) @@ -69,7 +71,7 @@ class BinaryExpression: # in fact this doesn't follow JavaScript "+" semantics if self.node["operator"] == "+": - return left+right + return Number(left.val+right.val) else: raise NotImplementedError @@ -110,7 +112,15 @@ class Literal: self.node = node def eval(self, context): - return self.node["value"] + val = self.node["value"] + + if isinstance(val, float): + if int(val) == val: + return Number(int(val)) + else: + return Number(val) + else: + raise NotImplementedError node_index = {cls.__name__: cls for cls in [ diff --git a/src/std.py b/src/std.py --- a/src/std.py +++ b/src/std.py @@ -1,3 +1,8 @@ +class Number: + def __init__(self, x): + self.val = x + + lib = { - "document": {"write": print} + "document": {"write": lambda x: print(x.val)} } diff --git a/tests/test_jasinta.py b/tests/test_jasinta.py --- a/tests/test_jasinta.py +++ b/tests/test_jasinta.py @@ -1,22 +1,18 @@ from unittest import TestCase -from unittest.mock import MagicMock +from unittest.mock import patch from pyjsparser import parse from jasinta import interpret -import std as jasinta_std class TestBasicAddition(TestCase): - def setUp(self): - self.mock_print = MagicMock() - jasinta_std.lib["document"]["write"] = self.mock_print - - def test_interpret(self): + @patch("builtins.print") + def test_interpret(self, mock_print): s = """var a=3; var b=1; var c=a+b; document.write(c);""" interpret(parse(s)) - self.mock_print.assert_called_with(4.0) + mock_print.assert_called_with(4)