-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathToken.h
115 lines (97 loc) · 2.75 KB
/
Token.h
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
#pragma once
#include <vector>
#include <variant>
#include <string>
#include <iostream>
#include "CommonTypes.h"
#define TOKEN_LIST(MACRO) \
MACRO(INVALID) \
MACRO(FUNCTION) \
MACRO(FOR) \
MACRO(LET) \
MACRO(ARROW) \
MACRO(RETURN) \
MACRO(EQUALS) \
MACRO(PLUS) \
MACRO(MINUS) \
MACRO(STAR) \
MACRO(SLASH) \
MACRO(LPAREN) \
MACRO(RPAREN) \
MACRO(LCURLY) \
MACRO(RCURLY) \
MACRO(INT_LITERAL) \
MACRO(STR_LITERAL) \
MACRO(SEMI_COLON) \
MACRO(COLON) \
MACRO(DOT) \
MACRO(COMMA) \
MACRO(IDENTIFIER) \
MACRO(END_OF_FILE)
// Tokens that don't have any more
// state except for the type of token
// (used for generating parsing functions)
#define MONOSTATE_TOKEN_LIST(MACRO) \
MACRO("fn", FUNCTION) \
MACRO("for", FOR) \
MACRO("let", LET) \
MACRO("=", EQUALS) \
MACRO("->", ARROW) \
MACRO("return", RETURN) \
MACRO("+", PLUS) \
MACRO("-", MINUS) \
MACRO("*", STAR) \
MACRO("/", SLASH) \
MACRO("(", LPAREN) \
MACRO(")", RPAREN) \
MACRO("{", LCURLY) \
MACRO("}", RCURLY) \
MACRO(";", SEMI_COLON) \
MACRO(":", COLON) \
MACRO(".", DOT) \
MACRO(",", COMMA)
#define DECLARE_TOKENS(NAME) NAME,
enum class TokenType {
TOKEN_LIST(DECLARE_TOKENS)
};
#undef DECLARE_TOKENS
using TokenData = std::variant<std::monostate, String, int>;
using TokenList = Vector<struct Token>;
struct Location {
int line;
int column;
};
struct Token {
TokenType type;
TokenData data;
Location location;
};
template <TokenType TType>
Token CreateToken(Location location) {
Token token;
token.type = TType;
token.location = location;
return token;
}
template <TokenType TType, typename ValueType>
Token CreateTokenData(ValueType value, Location location) {
Token token = CreateToken<TType>(location);
token.data = std::move(value);
return token;
}
struct DebugValueVisitor {
void operator()(const std::string& value) {
std::cout << "(String: " << value << ')';
}
void operator()(int value) {
std::cout << "(Integer: " << value << ')';
}
void operator()(std::monostate value) {}
};
static const char* GetTokenName(TokenType token) {
#define RETURN_TOKEN_NAME(NAME) case TokenType::NAME: return #NAME;
switch (token) {
TOKEN_LIST(RETURN_TOKEN_NAME);
}
return nullptr;
};