-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTokenizer.h
More file actions
77 lines (66 loc) · 1.75 KB
/
Copy pathTokenizer.h
File metadata and controls
77 lines (66 loc) · 1.75 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
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
#ifndef __TOKENIZER_H__
#define __TOKENIZER_H__
#include "Token.h"
#include "VList.h"
namespace ds {
class Tokenizer {
public:
explicit Tokenizer(const std::string &code) { m_beg = code.begin(); }
/**
* Next token
*/
Token next() {
while (isspace(peek()))
forward();
if (isalpha(peek())) {
return variable();
} else if (isdigit(peek())) {
return number();
} else if ('(' == peek()) {
return atom(Token::Kind::LeftParen);
} else if (')' == peek()) {
return atom(Token::Kind::RightParen);
} else if ('=' == peek()) {
return atom(Token::Kind::Equal);
} else if ('+' == peek()) {
return atom(Token::Kind::Plus);
} else if ('-' == peek()) {
return atom(Token::Kind::Minus);
} else if ('*' == peek()) {
return atom(Token::Kind::Asterisk);
} else if (';' == peek()) {
return atom(Token::Kind::Semicolon);
} else if ('\0' == peek()) {
return Token(Token::Kind::End, m_beg, 1);
} else {
return atom(Token::Kind::Unexpected);
}
}
private:
/**
* A sequence of digits is a number token
*/
Token number() {
std::string::const_iterator start = m_beg;
forward();
while (isdigit(peek()))
forward();
return Token(Token::Kind::Number, start, m_beg);
}
/**
* A sequence of letters is a variable token
*/
Token variable() noexcept {
std::string::const_iterator start = m_beg;
forward();
while (isalpha(peek()))
forward();
return Token(Token::Kind::Variable, start, m_beg);
}
Token atom(Token::Kind kind) { return Token(kind, m_beg++, 1); }
char peek() const { return *m_beg; }
void forward() { m_beg++; }
std::string::const_iterator m_beg{};
};
} // namespace ds
#endif // __TOKENIZER_H__