-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlexer.cpp
299 lines (266 loc) · 10.1 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
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
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
#include "lexer.h"
#include <algorithm>
#include <charconv>
#include <unordered_map>
#include <cassert>
#include <cctype>
using namespace std;
namespace parse {
bool operator==(const Token &lhs, const Token &rhs) {
using namespace token_type;
if (lhs.index() != rhs.index()) {
return false;
}
if (lhs.Is<Char>()) {
return lhs.As<Char>().value == rhs.As<Char>().value;
}
if (lhs.Is<Number>()) {
return lhs.As<Number>().value == rhs.As<Number>().value;
}
if (lhs.Is<String>()) {
return lhs.As<String>().value == rhs.As<String>().value;
}
if (lhs.Is<Id>()) {
return lhs.As<Id>().value == rhs.As<Id>().value;
}
return true;
}
bool operator!=(const Token &lhs, const Token &rhs) {
return !(lhs == rhs);
}
std::ostream &operator<<(std::ostream &os, const Token &rhs) {
using namespace token_type;
#define VALUED_OUTPUT(type) \
if (auto p = rhs.TryAs<type>()) return os << #type << '{' << p->value << '}';
VALUED_OUTPUT(Number);
VALUED_OUTPUT(Id);
VALUED_OUTPUT(String);
VALUED_OUTPUT(Char);
#undef VALUED_OUTPUT
#define UNVALUED_OUTPUT(type) \
if (rhs.Is<type>()) return os << #type;
UNVALUED_OUTPUT(Class);
UNVALUED_OUTPUT(Return);
UNVALUED_OUTPUT(If);
UNVALUED_OUTPUT(Else);
UNVALUED_OUTPUT(Def);
UNVALUED_OUTPUT(Newline);
UNVALUED_OUTPUT(Print);
UNVALUED_OUTPUT(Indent);
UNVALUED_OUTPUT(Dedent);
UNVALUED_OUTPUT(And);
UNVALUED_OUTPUT(Or);
UNVALUED_OUTPUT(Not);
UNVALUED_OUTPUT(Eq);
UNVALUED_OUTPUT(NotEq);
UNVALUED_OUTPUT(LessOrEq);
UNVALUED_OUTPUT(GreaterOrEq);
UNVALUED_OUTPUT(None);
UNVALUED_OUTPUT(True);
UNVALUED_OUTPUT(False);
UNVALUED_OUTPUT(Eof);
#undef UNVALUED_OUTPUT
return os << "Unknown token :("sv;
}
Lexer::Lexer(std::istream &input)
: in_(input) {
NextToken();
}
const Token &Lexer::CurrentToken() const {
assert(!tokens_.empty());
return tokens_.at(curr_pos_);
}
Token Lexer::NextToken() {
if (static_cast<size_t>(++curr_pos_) == tokens_.size()) {
if (!tokens_.empty() && tokens_.back().Is<token_type::Eof>()) {
--curr_pos_;
return tokens_.back();
}
TextLine line;
for (line = TextLine::ReadLine(in_);
line.IsEmpty();
line = TextLine::ReadLine(in_));
if (line.indent_ % 2 != 0) throw LexerError("Bad indent size.");
if (!line.IsEofOnly() && line.indent_ > current_indent_) {
for (int i = 0; i < (line.indent_ - current_indent_) / 2; ++i) {
tokens_.emplace_back(token_type::Indent{});
}
current_indent_ = line.indent_;
}
if (!line.IsEofOnly() && line.indent_ < current_indent_) {
for (int i = 0; i < (current_indent_ - line.indent_) / 2; ++i) {
tokens_.emplace_back(token_type::Dedent{});
}
current_indent_ = line.indent_;
}
if (line.IsEofOnly() && current_indent_ > 0) {
for (int i = 0; i < current_indent_ / 2; ++i) {
tokens_.emplace_back(token_type::Dedent{});
}
current_indent_ = line.indent_;
}
for (const auto &t: line.tokens_) {
tokens_.emplace_back(t);
}
}
return tokens_.at(curr_pos_);
}
Lexer::TextLine Lexer::TextLine::ReadLine(std::istream &in) {
TextLine line;
line.indent_ = SkipSpaces(in);
int ch;
do {
ch = in.get();
if (ch == ' ') {
SkipSpaces(in);
} else if (ch == '#') {
SkipComment(in);
} else if (ch == '\n') {
line.tokens_.emplace_back(token_type::Newline{});
} else if (ch == EOF) {
if (!line.IsEmpty() && !line.tokens_.back().Is<token_type::Newline>()) {
line.tokens_.emplace_back(token_type::Newline{});
}
line.tokens_.emplace_back(token_type::Eof{});
} else if (ch == '"' || ch == '\'') {
line.ReadString(in, ch);
} else if (isdigit(ch)) {
line.ReadNumber(in, ch);
} else if (isalpha(ch) || ch == '_') {
line.ReadIdentifier(in, ch);
} else if ((ch == '!' || ch == '=' || ch == '<' || ch == '>') && in.peek() == '=') {
line.ReadComparison(in, ch);
} else {
line.tokens_.emplace_back(token_type::Char{static_cast<char>(ch)});
}
} while (!(ch == '\n' || ch == EOF));
return line;
}
int Lexer::TextLine::SkipSpaces(std::istream &in) {
int space_count = 0;
for (; in.get() == ' '; ++space_count);
in.unget(); // вернем последний считанный символ (не пробельный) в поток
return space_count;
}
void Lexer::TextLine::SkipComment(std::istream &in) {
for (; !(in.get() == '\n' || in.eof()););
in.unget(); // вернем последний считанный символ (\n) в поток
}
void Lexer::TextLine::ReadString(std::istream &in, const int begin_quote) {
auto it = std::istreambuf_iterator<char>(in);
auto end = std::istreambuf_iterator<char>();
std::string s;
while (true) {
if (it == end) {
throw LexerError("String parsing error");
}
const char ch = *it;
if (ch == begin_quote) {
++it;
break;
} else if (ch == '\\') {
++it;
if (it == end) {
throw LexerError("String parsing error");
}
const char escaped_char = *(it);
switch (escaped_char) {
case 'n':
s.push_back('\n');
break;
case 't':
s.push_back('\t');
break;
case 'r':
s.push_back('\r');
break;
case '"':
s.push_back('"');
break;
case '\'':
s.push_back('\'');
break;
case '\\':
s.push_back('\\');
break;
default:
throw LexerError("Unrecognized escape sequence \\"s + escaped_char);
}
} else if (ch == '\n' || ch == '\r') {
throw LexerError("Unexpected end of line"s);
} else {
s.push_back(ch);
}
++it;
}
tokens_.emplace_back(token_type::String{std::move(s)});
}
void Lexer::TextLine::ReadNumber(std::istream &in, const int first_dig) {
std::string s{static_cast<char>(first_dig)};
for (int ch = in.get(); in && isdigit(ch); ch = in.get()) {
s += static_cast<char>(ch);
}
in.unget(); // вернем последний считанный символ (не цифру) в поток
tokens_.emplace_back(token_type::Number{stoi(s)});
}
void Lexer::TextLine::ReadIdentifier(std::istream &in, const int first_sym) {
std::string s{static_cast<char>(first_sym)};
for (int ch = in.get();
in && (isalpha(ch) || ch == '_' || isdigit(ch));
ch = in.get()) {
s += static_cast<char>(ch);
}
in.unget(); // вернем последний считанный символ в поток
if (s == "class"sv) {
tokens_.emplace_back(token_type::Class{});
} else if (s == "return"sv) {
tokens_.emplace_back(token_type::Return{});
} else if (s == "if"sv) {
tokens_.emplace_back(token_type::If{});
} else if (s == "else"sv) {
tokens_.emplace_back(token_type::Else{});
} else if (s == "def"sv) {
tokens_.emplace_back(token_type::Def{});
} else if (s == "print"sv) {
tokens_.emplace_back(token_type::Print{});
} else if (s == "and"sv) {
tokens_.emplace_back(token_type::And{});
} else if (s == "or"sv) {
tokens_.emplace_back(token_type::Or{});
} else if (s == "not"sv) {
tokens_.emplace_back(token_type::Not{});
} else if (s == "None"sv) {
tokens_.emplace_back(token_type::None{});
} else if (s == "True"sv) {
tokens_.emplace_back(token_type::True{});
} else if (s == "False"sv) {
tokens_.emplace_back(token_type::False{});
} else {
tokens_.emplace_back(token_type::Id{std::move(s)});
}
}
void Lexer::TextLine::ReadComparison(std::istream &in, const int ch) {
if (ch == '!') {
tokens_.emplace_back(token_type::NotEq{});
} else if (ch == '=') {
tokens_.emplace_back(token_type::Eq{});
} else if (ch == '<') {
tokens_.emplace_back(token_type::LessOrEq{});
} else if (ch == '>') {
tokens_.emplace_back(token_type::GreaterOrEq{});
}
in.get(); // считаем второй символ
}
bool Lexer::TextLine::IsEmpty() const {
return tokens_.empty()
|| std::all_of(tokens_.cbegin(), tokens_.cend(), [](const auto &t) {
return t.template Is<token_type::Newline>();
});
}
bool Lexer::TextLine::IsEofOnly() const {
return tokens_.empty()
|| std::all_of(tokens_.cbegin(), tokens_.cend(), [](const auto &t) {
return t.template Is<token_type::Eof>();
});
}
} // namespace parse