-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInterpreter.cpp
More file actions
87 lines (75 loc) · 1.8 KB
/
Copy pathInterpreter.cpp
File metadata and controls
87 lines (75 loc) · 1.8 KB
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
83
84
85
86
87
#include "Interpreter.h"
#include <fstream>
#include <sstream>
#include <iostream>
#include <vector>
Interpreter::Interpreter() {
pLexer = new Lexer();
pParser = new Parser();
pEvaluator = new Evaluator();
pSyntaxChecker = new SyntaxChecker();
}
Interpreter::~Interpreter() {
astRoot->cleanSyntaxTree();
if (astRoot) delete astRoot;
if (pParser) delete pParser;
if (pLexer) delete pLexer;
if (pEvaluator) delete pEvaluator;
if (pSyntaxChecker) delete pSyntaxChecker;
}
int Interpreter::loadCode(const std::string &code) {
if (code.size() == 0) {
std::cout << "Error. Source code is empty.\n";
return -1;
}
_code = code;
return 0;
}
int Interpreter::loadFile(const std::string &path) {
std::ifstream fd;
fd.open(path);
std::stringstream buf;
if (fd.is_open()) {
buf << fd.rdbuf();
} else {
return -1;
}
fd.close();
_code = buf.str();
if (_code.size() == 0) {
std::cout << "Error. Source code is empty.\n";
return -1;
}
return 0;
}
int Interpreter::lex() {
pLexer->lex(_code, _tokens);
return 0;
}
int Interpreter::checkSyntax() {
return pSyntaxChecker->checkSyntax(_code);
}
int Interpreter::parse() {
if (astRoot) {
astRoot->cleanSyntaxTree();
delete astRoot;
}
astRoot = new SyntaxTreeNode();
pParser->setTokens(_tokens);
pParser->parse(astRoot);
return 0;
}
DataType Interpreter::eval() {
return pEvaluator->eval(astRoot);
}
int Interpreter::run(DataType& result) {
// Check basic syntax.
if (checkSyntax() < 0) return -1;
// Split source into word tokens.
if (lex() < 0) return -2;
// Parse tokens into AST.
if (parse() < 0) return -3;
// Evaluate AST.
result = eval();
return 0;
}