Website Summary Files Commits Branches @commit @diff @stats
path: root / JSImpl / test / ASTInterpreterTests.cpp
blob: d431de0b438f7519d4ecfbe5a44b65bdca7ae616 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#include <gtest/gtest.h>

#include <src/CommonTypes.h>
#include <src/Lexer.h>
#include <src/Parser.h>
#include <src/ASTPrinter.h>
#include <src/ASTInterpreter.h>

struct ASTInterpret : ::testing::Test
{
	void Run(const char* program)
	{
		auto tokens = Tokenize(program).tokens;
		auto expr = Parse(tokens);
		Interpreter.Run(expr.get());
	}

	bool HasVariable(const char* name)
	{
		return Interpreter.HasVariable(name);
	}

	double ValueAsNumber(const char* name)
	{
		return std::get<double>(*Interpreter.ModifyVariable(name));
	}

	bool ValueAsBool(const char* name)
	{
		return std::get<bool>(*Interpreter.ModifyVariable(name));
	}

	IPLString ValueAsString(const char* name)
	{
		return std::get<IPLString>(*Interpreter.ModifyVariable(name));
	}

	ASTInterpreter Interpreter;
};

TEST_F(ASTInterpret, VarNumber)
{
	Run("var answer = 6 * 7");
	ASSERT_TRUE(HasVariable("answer"));
	ASSERT_DOUBLE_EQ(ValueAsNumber("answer"), 42.0);
}

TEST_F(ASTInterpret, VarString)
{
	Run("var name = 'John' + ' ' + 'Doe'");
	ASSERT_TRUE(HasVariable("name"));
	ASSERT_EQ(ValueAsString("name"), "John Doe");
}

TEST_F(ASTInterpret, StringPlusNumberNotSupported)
{
	ASSERT_THROW(Run("var data = 'John Doe' + 42"), std::runtime_error);
}

TEST_F(ASTInterpret, StringMinusString)
{
	ASSERT_THROW(Run("var data = 'John' - 'Doe'"), std::runtime_error);
}

TEST_F(ASTInterpret, LessNumber)
{
	Run("var answer = 6 < 7");
	ASSERT_TRUE(HasVariable("answer"));
	ASSERT_TRUE(ValueAsBool("answer"));
}

TEST_F(ASTInterpret, LessString)
{
	Run("var name = 'John' < 'Doe'");
	ASSERT_TRUE(HasVariable("name"));
	ASSERT_FALSE(ValueAsBool("name"));
}

TEST_F(ASTInterpret, StringLessNumber)
{
	ASSERT_THROW(Run("var data = 'John' < 42"), std::runtime_error);
}