File: tokenizer.h

package info (click to toggle)
libpog 0.5.3-3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, forky, sid, trixie
  • size: 3,644 kB
  • sloc: cpp: 51,038; ansic: 239; makefile: 14; python: 11; sh: 11
file content (260 lines) | stat: -rw-r--r-- 7,339 bytes parent folder | download
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
#pragma once

#include <memory>
#include <vector>

#include <fmt/format.h>
#include <re2/set.h>

#ifdef POG_DEBUG
#define POG_DEBUG_TOKENIZER 1
#endif

#ifdef POG_DEBUG_TOKENIZER
#define debug_tokenizer(...) fmt::print(stderr, "[tokenizer] {}\n", fmt::format(__VA_ARGS__))
#else
#define debug_tokenizer(...)
#endif

#include <pog/grammar.h>
#include <pog/token.h>

namespace pog {

template <typename ValueT>
struct TokenMatch
{
	TokenMatch(const Symbol<ValueT>* sym) : symbol(sym), value(), match_length(0) {}
	template <typename T>
	TokenMatch(const Symbol<ValueT>* sym, T&& v, std::size_t len) : symbol(sym), value(std::forward<T>(v)), match_length(len) {}
	TokenMatch(const TokenMatch&) = default;
	TokenMatch(TokenMatch&&) noexcept = default;

	TokenMatch& operator=(const TokenMatch&) = default;
	TokenMatch& operator=(TokenMatch&&) noexcept = default;

	const Symbol<ValueT>* symbol;
	ValueT value;
	std::size_t match_length;
};

struct InputStream
{
	std::unique_ptr<std::string> content;
	re2::StringPiece stream;
	bool at_end;
};

template <typename ValueT>
struct StateInfo
{
	std::string name;
	std::unique_ptr<re2::RE2::Set> re_set;
	std::vector<Token<ValueT>*> tokens;
};

template <typename ValueT>
class Tokenizer
{
public:
	using CallbackType = std::function<void(std::string_view)>;

	static constexpr std::string_view DefaultState = "@default";

	using GrammarType = Grammar<ValueT>;
	using StateInfoType = StateInfo<ValueT>;
	using SymbolType = Symbol<ValueT>;
	using TokenType = Token<ValueT>;
	using TokenMatchType = TokenMatch<ValueT>;

	Tokenizer(const GrammarType* grammar) : _grammar(grammar), _tokens(), _state_info(), _input_stack(), _current_state(nullptr), _global_action()
	{
		_current_state = get_or_make_state_info(std::string{DefaultState});
		add_token("$", nullptr, std::vector<std::string>{std::string{DefaultState}});
	}

	void prepare()
	{
		std::string error;

		for (const auto& token : _tokens)
		{
			for (const auto& state : token->get_active_in_states())
			{
				error.clear();
				auto* state_info = get_or_make_state_info(state);
				state_info->re_set->Add(token->get_pattern(), &error);
				state_info->tokens.push_back(token.get());
				assert(error.empty() && "Error when compiling token regexp");
			}
		}

		for (auto&& [name, info] : _state_info)
			info.re_set->Compile();
	}

	const std::vector<std::unique_ptr<TokenType>>& get_tokens() const
	{
		return _tokens;
	}

	TokenType* get_end_token() const
	{
		return _tokens[0].get();
	}

	TokenType* add_token(const std::string& pattern, const SymbolType* symbol, const std::vector<std::string>& states)
	{
		_tokens.push_back(std::make_unique<TokenType>(static_cast<std::uint32_t>(_tokens.size()), pattern, states, symbol));
		return _tokens.back().get();
	}

	void push_input_stream(std::istream& stream)
	{
		std::string input;
		std::vector<char> block(4096);
		while (stream.good())
		{
			stream.read(block.data(), block.size());
			input.append(std::string_view(block.data(), stream.gcount()));
		}

		_input_stack.emplace_back(InputStream{std::make_unique<std::string>(std::move(input)), re2::StringPiece{}, false});
		_input_stack.back().stream = re2::StringPiece{_input_stack.back().content->c_str()};
	}

	void pop_input_stream()
	{
		_input_stack.pop_back();
	}

	void clear_input_streams()
	{
		_input_stack.clear();
	}

	void global_action(CallbackType&& global_action)
	{
		_global_action = std::move(global_action);
	}

	std::optional<TokenMatchType> next_token()
	{
		bool repeat = true;
		while (repeat)
		{
			// We've emptied the stack so that means return end symbol to parser
			if (_input_stack.empty())
			{
				debug_tokenizer("Input stack empty - returing end of input");
				return _grammar->get_end_of_input_symbol();
			}

			auto& current_input = _input_stack.back();
			if (!current_input.at_end)
			{
				// Matched patterns doesn't have to be sorted (used to be in older re2 versions) but we shouldn't count on that
				std::vector<int> matched_patterns;
				_current_state->re_set->Match(current_input.stream, &matched_patterns);

				// Haven't matched anything, tokenization failure, we will get into endless loop
				if (matched_patterns.empty())
				{
					debug_tokenizer("Nothing matched on the current input");
					return std::nullopt;
				}

				re2::StringPiece submatch;
				const TokenType* best_match = nullptr;
				int longest_match = -1;
				for (auto pattern_index : matched_patterns)
				{
					_current_state->tokens[pattern_index]->get_regexp()->Match(current_input.stream, 0, current_input.stream.size(), re2::RE2::Anchor::ANCHOR_START, &submatch, 1);
					if (longest_match < static_cast<int>(submatch.size()))
					{
						best_match = _current_state->tokens[pattern_index];
						longest_match = static_cast<int>(submatch.size());
					}
					// In case of equal matches, index of tokens chooses which one is it (lower index has higher priority)
					else if (longest_match == static_cast<int>(submatch.size()))
					{
						if (!best_match || static_cast<int>(best_match->get_index()) > pattern_index)
							best_match = _current_state->tokens[pattern_index];
					}
				}

				if (current_input.stream.size() == 0)
				{
					debug_tokenizer("Reached end of input");
					current_input.at_end = true;
				}

				if (best_match->has_transition_to_state())
				{
					enter_state(best_match->get_transition_to_state());
					debug_tokenizer("Entered state \'{}\'", best_match->get_transition_to_state());
				}

				std::string_view token_str{current_input.stream.data(), static_cast<std::size_t>(longest_match)};
				current_input.stream.remove_prefix(longest_match);
				debug_tokenizer("Matched \'{}\' with token \'{}\' (index {})", token_str, best_match->get_pattern(), best_match->get_index());

				if (_global_action)
					_global_action(token_str);

				ValueT value{};
				if (best_match->has_action())
					value = best_match->perform_action(token_str);

				if (!best_match->has_symbol())
					continue;

				return TokenMatchType{best_match->get_symbol(), std::move(value), static_cast<std::size_t>(longest_match)};
			}
			else
				debug_tokenizer("At the end of input");

			// There is still something on stack but we've reached the end and noone popped it so return end symbol to parser
			return _grammar->get_end_of_input_symbol();
		}

		return std::nullopt;
	}

	void enter_state(const std::string& state)
	{
		_current_state = get_state_info(state);
		assert(_current_state && "Transition to unknown state in tokenizer");
	}

private:
	StateInfoType* get_or_make_state_info(const std::string& name)
	{
		auto itr = _state_info.find(name);
		if (itr == _state_info.end())
			std::tie(itr, std::ignore) = _state_info.emplace(name, StateInfoType{
				name,
				std::make_unique<re2::RE2::Set>(re2::RE2::DefaultOptions, re2::RE2::Anchor::ANCHOR_START),
				std::vector<TokenType*>{}
			});
		return &itr->second;
	}

	StateInfoType* get_state_info(const std::string& name)
	{
		auto itr = _state_info.find(name);
		if (itr == _state_info.end())
			return nullptr;
		return &itr->second;
	}

	const GrammarType* _grammar;
	std::vector<std::unique_ptr<TokenType>> _tokens;

	std::unordered_map<std::string, StateInfoType> _state_info;
	std::vector<InputStream> _input_stack;
	StateInfoType* _current_state;
	CallbackType _global_action;
};

} // namespace pog