-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinterpreter.cpp
159 lines (121 loc) · 2.58 KB
/
interpreter.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
/**
* Grammar:
* expr : factor ((MUL | DIV) factor ) *
* factor: INTEGER
*/
#include <string>
#include <cctype>
#include <stdexcept>
#include <iostream>
namespace lsbasi {
enum TokenType {
_INTEGER,
_MUL,
_DIV,
_EOF
};
class Token{
public:
TokenType type;
std::string value;
Token(TokenType type, std::string value): type(type), value(value){}
};
class Lexer {
private:
std::string text;
int pos;
char current_char;
int error () {
throw std::runtime_error("Invalid character");
}
void advance () {
pos++;
if (pos > text.size() - 1)
current_char = 0;
else
current_char = text[pos];
}
void skip_whitespace () {
while((current_char != 0) && (current_char == ' '))
advance();
}
std::string integer () {
std::string result;
while((current_char != 0) && std::isdigit(current_char)){
result += current_char;
advance();
}
return result;
}
public:
Token * get_next_token () {
while(current_char != 0){
skip_whitespace();
if (std::isdigit(current_char))
return new Token (_INTEGER, integer());
if (current_char == '*'){
advance();
return new Token (_MUL, "*");
}
if (current_char == '/'){
advance();
return new Token (_DIV, "/");
}
error();
}
return new Token(_EOF, "");
}
Lexer(std::string text): text(text), pos(0), current_char(text[pos]) {}
};
class Interpreter {
private:
Token * current_token;
Lexer lexer;
int error () {
throw std::runtime_error("Invalid Syntax");
}
void eat (TokenType type){
if (current_token->type == type){
delete current_token;
current_token = lexer.get_next_token();
}else
error();
}
int factor(){
std::string res = current_token->value;
eat(_INTEGER);
return std::stoi(res);
}
public:
Interpreter(lsbasi::Lexer& lexer): lexer(lexer) {
current_token = this->lexer.get_next_token();
}
int expr(){
int result = factor();
while((current_token->type == _MUL) || (current_token->type == _DIV)){
Token * tk = current_token;
if (tk->type == _MUL){
eat(_MUL);
result *= factor();
}
if (tk->type == _DIV){
eat(_DIV);
result /= factor();
}
}
return result;
}
};
};
int main (){
while(true){
std::string text;
std::cout << "calc> ";
std::cin >> text;
lsbasi::Lexer lexer(text);
lsbasi::Interpreter interpreter(lexer);
std::cout << interpreter.expr() << std::endl;
//ctrl+c to exit
}
return 0;
}