forked from openenclave/oeedger8r-cpp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpreprocessor.h
137 lines (117 loc) · 3.15 KB
/
preprocessor.h
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
// Copyright (c) Open Enclave SDK contributors.
// Licensed under the MIT License.
#ifndef PREPROCESSOR_H
#define PREPROCESSOR_H
#include <string>
#include <vector>
#include "ast.h"
struct DirectiveState
{
Directive command;
bool condition;
DirectiveState(Directive command_, bool condition_)
{
command = command_;
condition = condition_;
}
};
class Preprocessor
{
std::vector<DirectiveState> stack_;
const std::vector<std::string> defines_;
public:
Preprocessor(const std::vector<std::string>& defines) : defines_(defines)
{
}
~Preprocessor()
{
stack_.clear();
}
bool process(Directive cmd, const std::string& arg = "")
{
bool result = false;
switch (cmd)
{
case Ifdef:
{
DirectiveState state(cmd, false);
if (is_defined(arg))
state.condition = true;
stack_.push_back(state);
result = true;
break;
}
case Ifndef:
{
DirectiveState state(cmd, false);
if (!is_defined(arg))
state.condition = true;
stack_.push_back(state);
result = true;
break;
}
case Else:
{
DirectiveState& current_state = stack_.back();
/* Verify that the current state is ifdef or ifndef. */
if (current_state.command != Ifdef &&
current_state.command != Ifndef)
break;
current_state.command = cmd;
current_state.condition = !current_state.condition;
result = true;
break;
}
case Endif:
{
/* Ensure the stack is not empty. */
if (stack_.empty())
break;
DirectiveState& current_state = stack_.back();
/* Verify that the current state is ifdef, ifndef, or else. */
if (current_state.command != Ifdef &&
current_state.command != Ifndef &&
current_state.command != Else)
break;
stack_.pop_back();
result = true;
break;
}
default:
{
/* Do nothing. */
}
}
return result;
}
bool is_defined(const std::string& name)
{
bool found = false;
for (auto& define : defines_)
{
if (name == define)
{
found = true;
break;
}
}
return found;
}
/* Determine if the code needs to be included based on the state of
* preprocessor. */
bool is_included()
{
for (auto& s : stack_)
{
if (!s.condition)
return false;
}
return true;
}
/* Determine if there is an open control block. */
bool is_closed()
{
return stack_.empty();
}
};
#endif // PREPROCESSOR_H