-
Notifications
You must be signed in to change notification settings - Fork 2
/
preprocessor.cpp
113 lines (95 loc) · 3.17 KB
/
preprocessor.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
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
#include <sstream>
#include <fstream>
#include <streambuf>
#include <experimental/filesystem>
#include "../stringutil.h"
#include "preprocessor.h"
namespace LangUMS
{
std::string Preprocessor::Process(const std::string& input)
{
std::istringstream iss(input);
std::string output;
for (std::string line; std::getline(iss, line); )
{
line = ProcessLine(line);
output.append(line);
output.append("\n");
}
return output;
}
std::string Preprocessor::ProcessLine(const std::string& line)
{
using namespace std::experimental;
auto trimmed = trim(line);
if (trimmed[0] == '#')
{
auto space = trimmed.find_first_of(' ');
auto cmd = trimmed.substr(0, space);
if (cmd == "#define")
{
trimmed = trim(trimmed.substr(space));
space = trimmed.find_first_of(' ');
auto key = trimmed.substr(0, space);
auto value = trim(trimmed.substr(space));
m_Defines.erase(key);
m_Defines.insert(std::make_pair(key, value));
return "";
}
else if (cmd == "#undef")
{
trimmed = trim(trimmed.substr(space));
space = trimmed.find_first_of(' ');
auto key = trimmed.substr(0, space);
m_Defines.erase(key);
}
else if (cmd == "#include")
{
trimmed = trim(trimmed.substr(space));
auto path = filesystem::path(m_RootFolder);
path.append(trimmed);
if (!filesystem::is_regular_file(path))
{
throw new PreprocessorException(SafePrintf("Failed to #include from \"%\"", trimmed));
}
return ReadIncludeFile(path.generic_u8string());
}
else if (cmd == "#src")
{
trimmed = trim(trimmed.substr(space));
m_HasMapName = true;
m_MapName = trimmed;
return "";
}
else if (cmd == "#dst")
{
trimmed = trim(trimmed.substr(space));
m_HasOutMapName = true;
m_OutMapName = trimmed;
return "";
}
}
auto outLine = line;
for (auto& pair : m_Defines)
{
auto& search = pair.first;
auto& replace = pair.second;
auto pos = 0u;
while ((pos = outLine.find(search, pos)) != std::string::npos)
{
outLine.replace(pos, search.length(), replace);
pos += replace.length();
}
}
auto commentStart = outLine.find("//");
if (commentStart == std::string::npos)
{
return outLine;
}
return outLine.substr(0, commentStart);
}
std::string Preprocessor::ReadIncludeFile(const std::string& path)
{
return Process(std::string((std::istreambuf_iterator<char>(std::ifstream(path))), std::istreambuf_iterator<char>()));
}
}