-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscanner.cpp
70 lines (60 loc) · 1.54 KB
/
scanner.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
#include <iostream>
#include <string>
#include <vector>
#include <scanner.h>
#include <tokens.h>
extern "C" {
extern int yylex(void);
}
extern int yylineno;
extern char *yytext;
// ============================================================================
// Scanner/lexer
// ============================================================================
namespace scanner {
token_t scanner_t::next_token()
{
if (tokens_.empty()) {
return {0, ""};
}
auto token = tokens_.back();
tokens_.pop_back();
return token;
}
token_t scanner_t::lookahead(size_t n)
{
if (tokens_.size() <= n) {
return {0, ""};
}
return tokens_.at(tokens_.size() - n - 1);
}
void scanner_t::check_and_consume(int type)
{
if (tokens_.empty()) {
std::cerr << "Unexpected end of file" << std::endl;
exit(1);
}
if (tokens_.back().type != type) {
std::cerr << "Expected token " << type << " but got " << tokens_.back().type
<< std::endl;
std::cerr << "Unexpected token " << tokens_.back().value << std::endl;
// Print all tokens
for (auto token : tokens_) {
std::cerr << token.value << std::endl;
}
exit(1);
}
tokens_.pop_back();
}
scanner_t create_scanner(void)
{
std::vector<token_t> tokens;
int ntoken;
while ((ntoken = yylex())) {
tokens.push_back({ntoken, std::string{yytext}});
}
std::reverse(tokens.begin(), tokens.end());
scanner_t scanner{std::move(tokens)};
return scanner;
}
} // namespace scanner