-
Notifications
You must be signed in to change notification settings - Fork 0
/
tokenizer.cpp
60 lines (54 loc) · 1.21 KB
/
tokenizer.cpp
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
#include "tokenizer.h"
#include <cassert>
#include <iostream>
Tokenizer::Tokenizer(std::istream& input)
: m_input(input)
{
}
std::string Tokenizer::next()
{
int symbol = '\0';
while (true)
{
symbol = m_input.get();
if (!std::isspace(symbol))
break;
}
if (symbol == EOF)
return {};
std::string token;
if (std::isalpha(symbol) || symbol == '\'')
{
do
{
token.push_back(static_cast<char>(symbol));
symbol = m_input.get();
}
while (std::isalpha(symbol) || symbol == '\'');
}
else if (std::isdigit(symbol))
{
do
{
token.push_back(static_cast<char>(symbol));
symbol = m_input.get();
}
while (std::isdigit(symbol));
}
else if (std::ispunct(symbol))
{
do
{
token.push_back(static_cast<char>(symbol));
symbol = m_input.get();
}
while (std::ispunct(symbol));
}
else
{
std::cerr << "Unexpected character: 0x" << std::hex << symbol << " (" << static_cast<char>(symbol) << ")" << std::endl;
assert(false);
}
m_input.unget();
return token;
}