-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTinyExpr.hpp
More file actions
351 lines (304 loc) · 12.7 KB
/
TinyExpr.hpp
File metadata and controls
351 lines (304 loc) · 12.7 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
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
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
#ifndef TINYEXPR_HPP
#define TINYEXPR_HPP
#define TINYEXPR_VERSION_MAJOR 0
#define TINYEXPR_VERSION_MINOR 1
#define TINYEXPR_VERSION_PATCH 0
#define TINYEXPR_VERSION "0.1.0"
#include <cstdint>
#include <string>
#include <vector>
#include <map>
#include <cctype>
#include <stdexcept>
namespace tinyexpr {
template<typename T>
class TinyExprT {
public:
using Type = T;
using Vars = std::map<std::string, T>;
T evaluate(const std::string& expression, const Vars& vars) {
tokens = tokenize(expression);
pos = 0;
this->vars = vars;
return parseTernary();
}
private:
enum class TokenType {
Number, Variable, Plus, Minus, Mul, Div,
And, Or, Xor, Tilde, Not, Shl, Shr,
LogicalAnd, LogicalOr,
Question, Colon, Eq, Ne, Lt, Gt, Le, Ge, LParen, RParen, End
};
struct Token { TokenType type; std::string value; };
std::vector<Token> tokens;
size_t pos;
Vars vars;
std::vector<Token> tokenize(const std::string& str) {
std::vector<Token> res;
// helper to push tokens in a C++11-safe way
auto push = [&](TokenType t, const std::string &v) {
res.push_back(Token{t, v});
};
for (size_t i = 0; i < str.length(); ++i) {
char c = str[i];
if (std::isspace(static_cast<unsigned char>(c))) continue;
if (std::isdigit(static_cast<unsigned char>(c))) {
std::string s;
if (c == '0' && i + 1 < str.length() && (std::tolower(str[i+1]) == 'x')) {
s += str[i++]; s += str[i++];
while (i < str.length() && std::isxdigit(static_cast<unsigned char>(str[i]))) s += str[i++];
} else {
while (i < str.length() && std::isdigit(static_cast<unsigned char>(str[i]))) s += str[i++];
}
push(TokenType::Number, s);
--i;
continue;
}
if (std::isalpha(static_cast<unsigned char>(c)) || c == '_' || c == '$') {
std::string s; s += c; ++i;
while (i < str.length() && (std::isalnum(static_cast<unsigned char>(str[i])) || str[i] == '_' || str[i] == '$')) s += str[i++];
push(TokenType::Variable, s);
--i;
continue;
}
// two-char operators
if (c == '<' && i + 1 < str.length() && str[i+1] == '<') { push(TokenType::Shl, "<<"); ++i; continue; }
if (c == '>' && i + 1 < str.length() && str[i+1] == '>') { push(TokenType::Shr, ">>"); ++i; continue; }
if (c == '<' && i + 1 < str.length() && str[i+1] == '=') { push(TokenType::Le, "<="); ++i; continue; }
if (c == '>' && i + 1 < str.length() && str[i+1] == '=') { push(TokenType::Ge, ">="); ++i; continue; }
if (c == '=' && i + 1 < str.length() && str[i+1] == '=') { push(TokenType::Eq, "=="); ++i; continue; }
if (c == '!' && i + 1 < str.length() && str[i+1] == '=') { push(TokenType::Ne, "!="); ++i; continue; }
if (c == '&' && i + 1 < str.length() && str[i+1] == '&') { push(TokenType::LogicalAnd, "&&"); ++i; continue; }
if (c == '|' && i + 1 < str.length() && str[i+1] == '|') { push(TokenType::LogicalOr, "||"); ++i; continue; }
// single-char operators
switch (c) {
case '!': push(TokenType::Not, "!"); break;
case '+': push(TokenType::Plus, "+"); break;
case '-': push(TokenType::Minus, "-"); break;
case '*': push(TokenType::Mul, "*"); break;
case '/': push(TokenType::Div, "/"); break;
case '&': push(TokenType::And, "&"); break;
case '|': push(TokenType::Or, "|"); break;
case '^': push(TokenType::Xor, "^"); break;
case '~': push(TokenType::Tilde, "~"); break;
case '?': push(TokenType::Question, "?"); break;
case ':': push(TokenType::Colon, ":"); break;
case '<': push(TokenType::Lt, "<"); break;
case '>': push(TokenType::Gt, ">"); break;
case '(': push(TokenType::LParen, "("); break;
case ')': push(TokenType::RParen, ")"); break;
default: throw std::runtime_error("Unknown char: " + std::string(1, c));
}
}
push(TokenType::End, "");
return res;
}
T parseTernary() {
T cond = parseLogicalOr();
if (tokens[pos].type == TokenType::Question) {
pos++;
T trueVal = parseTernary();
if (tokens[pos++].type != TokenType::Colon) throw std::runtime_error("Expected ':'");
T falseVal = parseTernary();
return cond ? trueVal : falseVal;
}
return cond;
}
// Logical OR (||)
T parseLogicalOr() {
T res = parseLogicalAnd();
while (tokens[pos].type == TokenType::LogicalOr) {
if (res != 0) {
// short-circuit: consume RHS without evaluating
pos++; skipLogicalAnd();
res = 1;
} else {
pos++; T right = parseLogicalAnd();
res = (right != 0) ? 1 : 0;
}
}
return res;
}
// Logical AND (&&)
T parseLogicalAnd() {
T res = parseBitOr();
while (tokens[pos].type == TokenType::LogicalAnd) {
if (res == 0) {
// short-circuit: consume RHS without evaluating
pos++; skipBitOr();
res = 0;
} else {
pos++; T right = parseBitOr();
res = (right != 0) ? 1 : 0;
}
}
return res;
}
T parseBitOr() {
T res = parseBitXor();
while (tokens[pos].type == TokenType::Or) { pos++; res |= parseBitXor(); }
return res;
}
// --- Skipping helpers: consume tokens for an expression without evaluating ---
void skipPrimary() {
Token t = tokens[pos++];
if (t.type == TokenType::LParen) {
skipTernary();
if (tokens[pos++].type != TokenType::RParen) throw std::runtime_error("Missing ')'");
}
// Number or Variable are consumed already; nothing else to do
}
void skipUnary() {
if (tokens[pos].type == TokenType::Minus || tokens[pos].type == TokenType::Tilde || tokens[pos].type == TokenType::Not) {
pos++; skipUnary();
} else skipPrimary();
}
void skipMultiplicative() {
skipUnary();
while (tokens[pos].type == TokenType::Mul || tokens[pos].type == TokenType::Div) {
pos++; skipUnary();
}
}
void skipAdditive() {
skipMultiplicative();
while (tokens[pos].type == TokenType::Plus || tokens[pos].type == TokenType::Minus) {
pos++; skipMultiplicative();
}
}
void skipShift() {
skipAdditive();
while (tokens[pos].type == TokenType::Shl || tokens[pos].type == TokenType::Shr) {
pos++; skipAdditive();
}
}
void skipRelational() {
skipShift();
while (tokens[pos].type == TokenType::Lt || tokens[pos].type == TokenType::Gt || tokens[pos].type == TokenType::Le || tokens[pos].type == TokenType::Ge) {
pos++; skipShift();
}
}
void skipEquality() {
skipRelational();
while (tokens[pos].type == TokenType::Eq || tokens[pos].type == TokenType::Ne) {
pos++; skipRelational();
}
}
void skipBitAnd() { skipEquality(); while (tokens[pos].type == TokenType::And) { pos++; skipEquality(); } }
void skipBitXor() { skipBitAnd(); while (tokens[pos].type == TokenType::Xor) { pos++; skipBitAnd(); } }
void skipBitOr() { skipBitXor(); while (tokens[pos].type == TokenType::Or) { pos++; skipBitXor(); } }
void skipLogicalAnd() { skipBitOr(); while (tokens[pos].type == TokenType::LogicalAnd) { pos++; skipBitOr(); } }
void skipLogicalOr() { skipLogicalAnd(); while (tokens[pos].type == TokenType::LogicalOr) { pos++; skipLogicalAnd(); } }
void skipTernary() {
skipLogicalOr();
if (tokens[pos].type == TokenType::Question) {
pos++; skipTernary();
if (tokens[pos++].type != TokenType::Colon) throw std::runtime_error("Expected ':'");
skipTernary();
}
}
T parseBitXor() {
T res = parseBitAnd();
while (tokens[pos].type == TokenType::Xor) { pos++; res ^= parseBitAnd(); }
return res;
}
T parseBitAnd() {
T res = parseEquality();
while (tokens[pos].type == TokenType::And) { pos++; res &= parseEquality(); }
return res;
}
T parseEquality() {
T res = parseRelational();
while (tokens[pos].type == TokenType::Eq || tokens[pos].type == TokenType::Ne) {
TokenType op = tokens[pos++].type;
T right = parseRelational();
res = (op == TokenType::Eq) ? (res == right) : (res != right);
}
return res;
}
T parseRelational() {
T res = parseShift();
while (tokens[pos].type == TokenType::Lt || tokens[pos].type == TokenType::Gt ||
tokens[pos].type == TokenType::Le || tokens[pos].type == TokenType::Ge) {
TokenType op = tokens[pos++].type;
T right = parseShift();
if (op == TokenType::Lt) res = (res < right);
else if (op == TokenType::Gt) res = (res > right);
else if (op == TokenType::Le) res = (res <= right);
else res = (res >= right);
}
return res;
}
T parseShift() {
T res = parseAdditive();
while (tokens[pos].type == TokenType::Shl || tokens[pos].type == TokenType::Shr) {
TokenType op = tokens[pos++].type;
T right = parseAdditive();
if (op == TokenType::Shl) res <<= right; else res >>= right;
}
return res;
}
T parseAdditive() {
T res = parseMultiplicative();
while (tokens[pos].type == TokenType::Plus || tokens[pos].type == TokenType::Minus) {
TokenType op = tokens[pos++].type;
T right = parseMultiplicative();
if (op == TokenType::Plus) res += right; else res -= right;
}
return res;
}
T parseMultiplicative() {
T res = parseUnary();
while (tokens[pos].type == TokenType::Mul || tokens[pos].type == TokenType::Div) {
TokenType op = tokens[pos++].type;
T right = parseUnary();
if (op == TokenType::Mul) res *= right;
else { if (right == 0) throw std::runtime_error("Div by zero"); res /= right; }
}
return res;
}
T parseUnary() {
if (tokens[pos].type == TokenType::Minus) { pos++; return -parseUnary(); }
if (tokens[pos].type == TokenType::Tilde) { pos++; return ~parseUnary(); }
if (tokens[pos].type == TokenType::Not) { pos++; return parseUnary() == 0 ? 1 : 0; }
return parsePrimary();
}
T parsePrimary() {
Token t = tokens[pos++];
if (t.type == TokenType::Number) {
try {
unsigned long long v = std::stoull(t.value, nullptr, 0);
return static_cast<T>(v);
} catch (const std::exception &e) {
throw std::runtime_error(std::string("Number parse error: ") + e.what());
}
}
if (t.type == TokenType::Variable) {
if (vars.find(t.value) == vars.end()) throw std::runtime_error(std::string("Undefined variable: ") + t.value);
return vars.at(t.value);
}
if (t.type == TokenType::LParen) {
T res = parseTernary();
if (tokens[pos++].type != TokenType::RParen) throw std::runtime_error("Missing ')'");
return res;
}
throw std::runtime_error("Unexpected token: " + t.value);
}
};
using TinyExpr64 = TinyExprT<int64_t>;
using TinyExpr32 = TinyExprT<int32_t>;
using TinyExpr16 = TinyExprT<int16_t>;
using TinyExpr8 = TinyExprT<int8_t>;
using TinyExpr = TinyExpr64; // default 64-bit evaluator
using value64 = TinyExpr64::Type; // int64_t
using vars64 = TinyExpr64::Vars; // std::map<std::string, int64_t>
using value32 = TinyExpr32::Type; // int32_t
using vars32 = TinyExpr32::Vars; // std::map<std::string, int32_t>
using value16 = TinyExpr16::Type; // int16_t
using vars16 = TinyExpr16::Vars; // std::map<std::string, int16_t>
using value8 = TinyExpr8::Type; // int8_t
using vars8 = TinyExpr8::Vars; // std::map<std::string, int8_t>
// Convenience aliases for the default (64-bit) evaluator
using value = value64; // int64_t
using vars = vars64; // std::map<std::string, int64_t>
} // namespace tinyexpr
#endif