-
Notifications
You must be signed in to change notification settings - Fork 7
/
edn.hpp
454 lines (387 loc) · 12.1 KB
/
edn.hpp
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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
#include <list>
#include <string>
#include <cstring>
#include <iostream>
#include <algorithm>
namespace edn {
using std::cout;
using std::endl;
using std::string;
using std::list;
string validSymbolChars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ.*+!-_?$%&=:#/";
enum TokenType {
TokenString,
TokenAtom,
TokenParen
};
struct EdnToken {
TokenType type;
int line;
string value;
};
enum NodeType {
EdnNil,
EdnSymbol,
EdnKeyword,
EdnBool,
EdnInt,
EdnFloat,
EdnString,
EdnChar,
EdnList,
EdnVector,
EdnMap,
EdnSet,
EdnDiscard,
EdnTagged
};
struct EdnNode {
NodeType type;
int line;
string value;
list<EdnNode> values;
};
void createToken(TokenType type, int line, string value, list<EdnToken> &tokens) {
EdnToken token;
token.type = type;
token.line = line;
token.value = value;
tokens.push_back(token);
}
string typeToString(NodeType type) {
string output;
switch (type) {
case EdnSymbol: output = "EdnSymbol"; break;
case EdnKeyword: output = "EdnKeyword"; break;
case EdnInt: output = "EdnInt"; break;
case EdnFloat: output = "EdnFloat"; break;
case EdnChar: output = "EdnChar"; break;
case EdnBool: output = "EdnBool"; break;
case EdnNil: output = "EdnNil"; break;
case EdnString: output = "EdnString"; break;
case EdnTagged: output = "EdnTagged"; break;
case EdnList: output = "EdnList"; break;
case EdnVector: output = "EdnVector"; break;
case EdnSet: output = "EdnSet"; break;
case EdnMap: output = "EdnMap"; break;
case EdnDiscard: output = "EdnDiscard"; break;
}
return output;
}
//by default checks if first char is in range of chars
bool strRangeIn(string str, const char* range, int start = 0, int stop = 1) {
string strRange = str.substr(start, stop);
return (std::strspn(strRange.c_str(), range) == strRange.length());
}
list<EdnToken> lex(string edn) {
string::iterator it;
int line = 1;
char escapeChar = '\\';
bool escaping = false;
bool inString = false;
string stringContent = "";
bool inComment = false;
string token = "";
string paren = "";
list<EdnToken> tokens;
for (it = edn.begin(); it != edn.end(); ++it) {
if (*it == '\n' || *it == '\r') line++;
if (!inString && *it == ';' && !escaping) inComment = true;
if (inComment) {
if (*it == '\n') {
inComment = false;
if (token != "") {
createToken(TokenAtom, line, token, tokens);
token = "";
}
continue;
}
}
if (*it == '"' && !escaping) {
if (inString) {
createToken(TokenString, line, stringContent, tokens);
inString = false;
} else {
stringContent = "";
inString = true;
}
continue;
}
if (inString) {
if (*it == escapeChar && !escaping) {
escaping = true;
continue;
}
if (escaping) {
escaping = false;
if (*it == 't' || *it == 'n' || *it == 'f' || *it == 'r') stringContent += escapeChar;
}
stringContent += *it;
} else if (*it == '(' || *it == ')' || *it == '[' || *it == ']' || *it == '{' ||
*it == '}' || *it == '\t' || *it == '\n' || *it == '\r' || *it == ' ' || *it == ',') {
if (token != "") {
createToken(TokenAtom, line, token, tokens);
token = "";
}
if (*it == '(' || *it == ')' || *it == '[' || *it == ']' || *it == '{' || *it == '}') {
paren = "";
paren += *it;
createToken(TokenParen, line, paren, tokens);
}
} else {
if (escaping) {
escaping = false;
} else if (*it == escapeChar) {
escaping = true;
}
if (token == "#_" || (token.length() == 2 && token[0] == escapeChar)) {
createToken(TokenAtom, line, token, tokens);
token = "";
}
token += *it;
}
}
if (token != "") {
createToken(TokenAtom, line, token, tokens);
}
return tokens;
}
void uppercase(string &str) {
std::transform(str.begin(), str.end(), str.begin(), ::toupper);
}
bool validSymbol(string value) {
//first we uppercase the value
uppercase(value);
if (std::strspn(value.c_str(), validSymbolChars.c_str()) != value.length())
return false;
//if the value starts with a number that is not ok
if (strRangeIn(value, "0123456789"))
return false;
//first char can not start with : # or / - but / by itself is valid
if (strRangeIn(value, ":#/") && !(value.length() == 1 && value[0] == '/'))
return false;
//if the first car is - + or . then the next char must NOT be numeric, by by themselves they are valid
if (strRangeIn(value, "-+.") && value.length() > 1 && strRangeIn(value, "0123456789", 1))
return false;
if (std::count(value.begin(), value.end(), '/') > 1)
return false;
return true;
}
bool validKeyword(string value) {
return (value[0] == ':' && validSymbol(value.substr(1,value.length() - 1)));
}
bool validNil(string value) {
return (value == "nil");
}
bool validBool(string value) {
return (value == "true" || value == "false");
}
bool validInt(string value, bool allowSign = true) {
//if we have a positive or negative symbol that is ok but remove it for testing
if (strRangeIn(value, "-+") && value.length() > 1 && allowSign)
value = value.substr(1, value.length() - 1);
//if string ends with N or M that is ok, but remove it for testing
if (strRangeIn(value, "NM", value.length() - 1, 1))
value = value.substr(0, value.length() - 2);
if (std::strspn(value.c_str(), "0123456789") != value.length())
return false;
return true;
}
bool validFloat(string value) {
uppercase(value);
string front;
string back;
int epos;
int periodPos = value.find_first_of('.');
if (periodPos) {
front = value.substr(0, periodPos);
back = value.substr(periodPos + 1);
} else {
front = "";
back = value;
}
if(front == "" || validInt(front)) {
epos = back.find_first_of('E');
if(epos > -1) {
//ends with E which is invalid
if ((unsigned)epos == back.length() - 1) return false;
//both the decimal and exponent should be valid - do not allow + or - on dec (pass false as arg to validInt)
if (!validInt(back.substr(0, epos), false) || !validInt(back.substr(epos + 1))) return false;
} else {
//if back ends with M remove for validation
if (strRangeIn(back, "M", back.length() - 1, 1))
back = back.substr(0, back.length() - 1);
if (!validInt(back, false)) return false;
}
return true;
}
return false;
}
bool validChar(string value) {
return (value.at(0) == '\\' && value.length() == 2);
}
EdnNode handleAtom(EdnToken token) {
EdnNode node;
node.line = token.line;
node.value = token.value;
if (validNil(token.value))
node.type = EdnNil;
else if (token.type == TokenString)
node.type = EdnString;
else if (validChar(token.value))
node.type = EdnChar;
else if (validBool(token.value))
node.type = EdnBool;
else if (validInt(token.value))
node.type = EdnInt;
else if (validFloat(token.value))
node.type = EdnFloat;
else if (validKeyword(token.value))
node.type = EdnKeyword;
else if (validSymbol(token.value))
node.type = EdnSymbol;
else
throw "Could not parse atom";
return node;
}
EdnNode handleCollection(EdnToken token, list<EdnNode> values) {
EdnNode node;
node.line = token.line;
node.values = values;
if (token.value == "(") {
node.type = EdnList;
}
else if (token.value == "[") {
node.type = EdnVector;
}
if (token.value == "{") {
node.type = EdnMap;
}
return node;
}
EdnNode handleTagged(EdnToken token, EdnNode value) {
EdnNode node;
node.line = token.line;
string tagName = token.value.substr(1, token.value.length() - 1);
if (tagName == "_") {
node.type = EdnDiscard;
} else if (tagName == "") {
//special case where we return early as # { is a set - thus tagname is empty
node.type = EdnSet;
if (value.type != EdnMap) {
throw "Was expection a { } after hash to build set";
}
node.values = value.values;
return node;
} else {
node.type = EdnTagged;
}
if (!validSymbol(tagName)) {
throw "Invalid tag name";
}
EdnToken symToken;
symToken.type = TokenAtom;
symToken.line = token.line;
symToken.value = tagName;
list<EdnNode> values;
values.push_back(handleAtom(symToken));
values.push_back(value);
node.values = values;
return node;
}
EdnToken shiftToken(list<EdnToken> &tokens) {
EdnToken nextToken = tokens.front();
tokens.pop_front();
return nextToken;
}
EdnNode readAhead(EdnToken token, list<EdnToken> &tokens) {
if (token.type == TokenParen) {
EdnToken nextToken;
list<EdnNode> L;
string closeParen;
if (token.value == "(") closeParen = ")";
if (token.value == "[") closeParen = "]";
if (token.value == "{") closeParen = "}";
while (true) {
if (tokens.empty()) throw "unexpected end of list";
nextToken = shiftToken(tokens);
if (nextToken.value == closeParen) {
return handleCollection(token, L);
} else {
L.push_back(readAhead(nextToken, tokens));
}
}
} else if (token.value == ")" || token.value == "]" || token.value == "}") {
throw "Unexpected " + token.value;
} else {
if (token.value.size() && token.value.at(0) == '#') {
return handleTagged(token, readAhead(shiftToken(tokens), tokens));
} else {
return handleAtom(token);
}
}
}
string escapeQuotes(const string &before) {
string after;
after.reserve(before.length() + 4);
for (string::size_type i = 0; i < before.length(); ++i) {
switch (before[i]) {
case '"':
case '\\':
after += '\\';
default:
after += before[i];
}
}
return after;
}
string pprint(EdnNode &node, int indent = 1) {
string prefix("");
if (indent) {
prefix.insert(0, indent, ' ');
}
string output;
if (node.type == EdnList || node.type == EdnSet || node.type == EdnVector || node.type == EdnMap) {
string vals = "";
for (list<EdnNode>::iterator it=node.values.begin(); it != node.values.end(); ++it) {
if (vals.length() > 0) vals += prefix;
vals += pprint(*it, indent + 1);
if (node.type == EdnMap) {
++it;
vals += " " + pprint(*it, 1);
}
if (std::distance(it, node.values.end()) != 1) vals += "\n";
}
if (node.type == EdnList) output = "(" + vals + ")";
else if (node.type == EdnVector) output = "[" + vals + "]";
else if (node.type == EdnMap) output = "{" + vals + "}";
else if (node.type == EdnSet) output = "#{" + vals + "}";
#ifdef DEBUG
return "<" + typeToString(node.type) + " " + output + ">";
#endif
} else if (node.type == EdnTagged) {
output = "#" + pprint(node.values.front()) + " " + pprint(node.values.back());
#ifdef DEBUG
return "<EdnTagged " + output + ">";
#endif
} else if (node.type == EdnString) {
output = "\"" + escapeQuotes(node.value) + "\"";
#ifdef DEBUG
return "<EdnString " + output + ">";
#endif
} else {
#ifdef DEBUG
return "<" + typeToString(node.type) + " " + node.value + ">";
#endif
output = node.value;
}
return output;
}
EdnNode read(string edn) {
list<EdnToken> tokens = lex(edn);
if (tokens.size() == 0) {
throw "No parsable tokens found in string";
}
return readAhead(shiftToken(tokens), tokens);
}
}