-
Notifications
You must be signed in to change notification settings - Fork 0
/
scanner.hpp
106 lines (86 loc) · 1.92 KB
/
scanner.hpp
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
#pragma once
#include <string>
#include <utility>
#include <vector>
namespace lox {
enum TokenType {
// Single-character tokens.
TOKEN_LEFT_PAREN,
TOKEN_RIGHT_PAREN,
TOKEN_LEFT_BRACE,
TOKEN_RIGHT_BRACE,
TOKEN_COMMA,
TOKEN_DOT,
TOKEN_MINUS,
TOKEN_PLUS,
TOKEN_SEMICOLON,
TOKEN_SLASH,
TOKEN_STAR,
// One or two character tokens.
TOKEN_BANG,
TOKEN_BANG_EQUAL,
TOKEN_EQUAL,
TOKEN_EQUAL_EQUAL,
TOKEN_GREATER,
TOKEN_GREATER_EQUAL,
TOKEN_LESS,
TOKEN_LESS_EQUAL,
// Literals.
TOKEN_IDENTIFIER,
TOKEN_STRING,
TOKEN_NUMBER,
// Keywords.
TOKEN_AND,
TOKEN_CLASS,
TOKEN_ELSE,
TOKEN_FALSE,
TOKEN_FOR,
TOKEN_FUN,
TOKEN_IF,
TOKEN_NIL,
TOKEN_OR,
TOKEN_PRINT,
TOKEN_RETURN,
TOKEN_SUPER,
TOKEN_THIS,
TOKEN_TRUE,
TOKEN_VAR,
TOKEN_WHILE,
TOKEN_ERROR,
TOKEN_EOF,
TOKEN_COUNT
};
struct Token {
Token() = default;
Token(TokenType type, std::string lexeme, int line)
: type{type}, lexeme{std::move(lexeme)}, line{line} {}
TokenType type{TOKEN_ERROR};
std::string lexeme{};
int line{};
};
class Scanner {
public:
explicit Scanner(const std::string& source)
: start_{source.c_str()}, current_{source.c_str()} {}
Token scan_token();
std::vector<Token> scan_tokens();
private:
[[nodiscard]] Token make_token(TokenType type) const {
return {type, {start_, static_cast<size_t>(current_ - start_)}, line_};
}
[[nodiscard]] Token error_token(std::string message) const {
return {TOKEN_ERROR, std::move(message), line_};
}
Token identifier();
[[nodiscard]] TokenType identifier_type() const;
Token number();
Token string();
[[nodiscard]] char peek() const { return *current_; }
[[nodiscard]] char peek_next() const;
bool match(char expected);
char advance() { return *current_++; }
[[nodiscard]] bool is_at_end() const { return *current_ == '\0'; }
const char *start_{}, *current_{};
int line_{1};
};
} // namespace lox