-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlexer.cpp
More file actions
44 lines (36 loc) · 1.18 KB
/
Copy pathlexer.cpp
File metadata and controls
44 lines (36 loc) · 1.18 KB
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
#include "lexer.hpp"
#include <map>
#include <string>
#include "defaults.hpp"
#include "token.hpp"
using Type = Token::Type;
// Maps words to token types.
static const std::map<std::string, Type> str_to_type = {
{"exit", Type::EXIT},
{"cd", Type::CD},
{"|", Type::PIPE},
};
// Attempts to convert a word to a token type by
// searching in the dictionary. Returns UNDEF token if
// it fails to find a known word.
static inline Token search_dict(std::string& word) {
auto type = str_to_type.find(word);
if (type != str_to_type.end()) return Token(type->second, type->first);
return Token(Type::UNDEF);
}
// Returns the next token in the expression and pops if called with pop = true.
template <bool pop>
static inline Token next_token(CPPArgList& expr) {
if (!expr.size()) return Token(Type::EOE);
std::string word = expr.back();
if constexpr (pop) expr.pop_back();
Token attempt_dict = search_dict(word);
if (attempt_dict.type != Type::UNDEF)
return attempt_dict;
else
return Token(word);
}
// Returns next token.
Token lexer::peek(CPPArgList& expr) { return next_token<false>(expr); }
// Returns next token and pops.
Token lexer::pop(CPPArgList& expr) { return next_token<true>(expr); }