-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlexer.cpp
82 lines (75 loc) · 1.58 KB
/
lexer.cpp
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 "lexer.hpp"
void whitespaceT(std::string &msg)
{
int i = 0;
char c = msg[0];
while (isspace(c)) {
c = msg[++i];
}
msg.erase(0, i);
}
bool integerT(Token *&token, std::string &msg)
{
std::string temp_str = "";
int i = 0;
char c = msg[0];
while (isdigit(c)) {
temp_str += c;
c = msg[++i];
}
if (i > 0) {
msg.erase(0, i);
token = new IntToken(temp_str);
//std::cout << "new int" << std::endl;
return true;
}
return false;
}
bool parenT(Token *&token, std::string &msg)
{
char c = msg[0];
if (c == '(' || c == ')') {
msg.erase(0, 1);
token = new ParenToken({c});
//std::cout << "new paren" << std::endl;
return true;
}
return false;
}
bool binaryOpT(Token *&token, std::string &msg)
{
char c = msg[0];
std::vector<char> ops = {'+', '-', '*', '/', '^', '%'};
if (std::find(ops.begin(), ops.end(), c) != ops.end()) {
token = new BinaryOpToken({c});
//std::cout << "new binop" << std::endl;
msg.erase(0, 1);
return true;
}
return false;
}
Token* getToken(std::string &msg)
{
Token* token;
whitespaceT(msg);
if (integerT(token, msg))
goto tokenized;
if (parenT(token, msg))
goto tokenized;
if (binaryOpT(token, msg))
goto tokenized;
printf("Could not tokenize char > %c < \n", msg[0]);
exit(EXIT_FAILURE);
tokenized:
whitespaceT(msg);
return token;
}
std::vector<Token*> tokenize(const std::string& msg)
{
std::string temp_string = msg;
std::vector<Token*> tokens = {};
while (!temp_string.empty()) {
tokens.push_back(getToken(temp_string));
}
return tokens;
}