Changeset - 18037ac0f6b4
[Not reviewed]
default
0 3 0
Laman - 2 years ago 2023-01-01 21:04:50

wrapped numbers in an object
3 files changed with 23 insertions and 12 deletions:
0 comments (0 inline, 0 general)
src/jasinta.py
Show inline comments
 
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 [
src/std.py
Show inline comments
 
class Number:
 
	def __init__(self, x):
 
		self.val = x
 

	
 

	
 
lib = {
 
	"document": {"write": print}
 
	"document": {"write": lambda x: print(x.val)}
 
}
tests/test_jasinta.py
Show inline comments
 
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)
0 comments (0 inline, 0 general)