aboutsummaryrefslogtreecommitdiff
path: root/ProjectBrussel/CodegenCompiler/CodegenLexer.cpp
blob: dab6aea9d2e7e857f1fdcfecb401b7e478e9cbc9 (plain)
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
#include "CodegenLexer.hpp"

#include <cassert>

bool StbTokenIsSingleChar(int lexerToken) {
	return lexerToken >= 0 && lexerToken < 256;
}

bool StbTokenIsMultiChar(int lexerToken) {
	return !StbTokenIsMultiChar(lexerToken);
}

std::string CombineTokens(std::span<const StbLexerToken> tokens) {
	size_t length = 0;
	for (auto& token : tokens) {
		length += token.text.size();
	}
	std::string result;
	result.reserve(length);
	for (auto& token : tokens) {
		result += token.text;
	}
	return result;
}

const StbLexerToken& CodegenLexer::Current() const {
	assert(idx < tokens.size());
	return tokens[idx];
}

void CodegenLexer::InitializeFrom(std::string_view source) {
	this->tokens = {};
	this->idx = 0;

	stb_lexer lexer;
	char stringStorage[65536];
	const char* srcBegin = source.data();
	const char* srcEnd = srcBegin + source.length();
	stb_c_lexer_init(&lexer, srcBegin, srcEnd, stringStorage, sizeof(stringStorage));

	struct TokenCombiningPattern {
		StbLexerToken result;
		char matchChars[16];
	};

	const TokenCombiningPattern kDoubleColon = {
		.result = {
			.text = "::",
			.type = CLEX_ext_double_colon,
		},
		.matchChars = { ':', ':', '\0' },
	};
	const TokenCombiningPattern kDotDotDot = {
		.result = {
			.text = "...",
			.type = CLEX_ext_dot_dot_dot,
		},
		.matchChars = { '.', '.', '.', '\0' },
	};

	const TokenCombiningPattern* currentState = nullptr;
	int currentStateCharIdx = 0;

	while (true) {
		// See stb_c_lexer.h's comments, here are a few additinos that aren't made clear in the file:
		// - `lexer->token` (noted as "token" below) after calling stb_c_lexer_get_token() contains either:
		//     1. 0 <= token < 256:          an ASCII character (more precisely a single char that the lexer ate; technically can be an incomplete code unit)
		//     2. token < 0:                 an unknown token
		//     3. One of the `CLEX_*` enums: a special, recognized token such as an operator

		int stbToken = stb_c_lexer_get_token(&lexer);
		if (stbToken == 0) {
			// EOF
			break;
		}

		if (lexer.token == CLEX_parse_error) {
			printf("[ERROR] stb_c_lexer countered a parse error.\n");
			// TODO how to handle?
			continue;
		}

		StbLexerToken token;
		if (StbTokenIsSingleChar(lexer.token)) {
			char c = lexer.token;

			token.type = CLEX_ext_single_char;
			token.text = std::string(1, c);

			if (!currentState) {
#define TRY_START_MATCH(states)      \
	if (states.matchChars[0] == c) { \
		currentState = &states;      \
		currentStateCharIdx = 1;     \
	}
				TRY_START_MATCH(kDoubleColon);
				TRY_START_MATCH(kDotDotDot);
#undef TRY_START_MATCH
			} else {
				if (currentState->matchChars[currentStateCharIdx] == c) {
					// Match success
					++currentStateCharIdx;

					// If we matched all of the chars...
					if (currentState->matchChars[currentStateCharIdx] == '\0') {
						// We matched (currentStateCharIdx) tokens though this one is pushed into the vector, leaving (currentStateCharIdx - 1) tokens to be removed
						for (int i = 0, count = currentStateCharIdx - 1; i < count; ++i) {
							tokens.pop_back();
						}

						// Set the current token to desired result
						token = currentState->result;

						currentState = nullptr;
						currentStateCharIdx = 0;
					}
				} else {
					// Match fail, reset

					currentState = nullptr;
					currentStateCharIdx = 0;
				}
			}
		} else {
			token.type = lexer.token;
			// WORKAROUND: use null terminated string, stb_c_lexer doens't set string_len properly when parsing identifiers
			token.text = std::string(lexer.string);

			switch (token.type) {
				case CLEX_intlit:
					token.lexerIntNumber = lexer.int_number;
					break;

				case CLEX_floatlit:
					token.lexerRealNumber = lexer.real_number;
					break;
			}
		}
		tokens.push_back(std::move(token));
		token = {};
	}
}

const StbLexerToken* CodegenLexer::TryConsumeToken(int type) {
	auto& token = tokens[idx];
	if (token.type == type) {
		++idx;
		return &token;
	}
	return nullptr;
}

const StbLexerToken* CodegenLexer::TryConsumeSingleCharToken(char c) {
	auto& token = tokens[idx];
	if (token.type == CLEX_ext_single_char &&
		token.text[0] == c)
	{
		++idx;
		return &token;
	}
	return nullptr;
}

void CodegenLexer::SkipUntilToken(int type) {
	while (idx < tokens.size()) {
		if (Current().type == type) {
			break;
		}
		++idx;
	}
}

void CodegenLexer::SkipUntilTokenSingleChar(char c) {
	while (idx < tokens.size()) {
		auto& curr = Current();
		if (curr.type == CLEX_ext_single_char &&
			curr.text[0] == c)
		{
			break;
		}
		++idx;
	}
}