-
Notifications
You must be signed in to change notification settings - Fork 1
/
smallfolk.cpp
688 lines (647 loc) · 16.8 KB
/
smallfolk.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
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
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
#include "smallfolk.h"
#include <map>
#include <iomanip> // std::setprecision
#include <sstream> // std::stringstream
#include <cmath> // std::floor
#include <stdarg.h> // va_start
#include <functional> // std::hash
namespace Serializer
{
typedef std::vector<LuaVal> TABLES;
typedef std::unordered_map<LuaVal, unsigned int, LuaVal::LuaValHasher> MEMO;
typedef std::stringstream ACC;
// sprintf is ~50% faster than other solutions
inline std::string tostring(const double d)
{
char arr[128];
sprintf(arr, "%.17g", d);
return arr;
}
inline std::string tostring(LuaVal::TblPtr const & ptr)
{
char arr[128];
sprintf(arr, "table: %p", static_cast<void*>(ptr.get()));
return arr;
}
unsigned int dump_type_table(LuaVal const & object, unsigned int nmemo, MEMO& memo, ACC& acc);
unsigned int dump_object(LuaVal const & object, unsigned int nmemo, MEMO& memo, ACC& acc);
std::string escape_quotes(const std::string &before, char quote);
std::string unescape_quotes(const std::string &before, char quote);
bool nonzero_digit(char c);
bool is_digit(char c);
char strat(std::string const & string, std::string::size_type i);
LuaVal expect_number(std::string const & string, size_t& start);
LuaVal expect_object(std::string const & string, size_t& i, TABLES& tables);
}
LuaVal const LuaVal::nil(TNIL);
std::string LuaVal::tostring() const
{
switch (tag)
{
case TBOOL:
if (b)
return "true";
else
return "false";
case TNIL:
return "nil";
case TSTRING:
return s;
case TNUMBER:
return Serializer::tostring(d);
case TTABLE:
return Serializer::tostring(tbl_ptr);
}
throw smallfolk_exception("tostring invalid or unhandled tag %i", tag);
}
size_t LuaVal::LuaValHasher::operator()(LuaVal const & v) const
{
return LuaValHash(v);
}
size_t LuaValHash(LuaVal const & v)
{
switch (v.tag)
{
case TBOOL:
return std::hash<bool>()(v.b);
case TNIL:
return std::hash<int>()(0);
case TSTRING:
return std::hash<std::string>()(v.s);
case TNUMBER:
return std::hash<double>()(v.d);
case TTABLE:
return std::hash<LuaVal::TblPtr>()(v.tbl_ptr);
}
return std::hash<std::string>()(v.tostring());
}
LuaVal & LuaVal::operator[](LuaVal const & k)
{
if (!istable())
throw smallfolk_exception("using [] on non table object");
if (k.isnil())
throw smallfolk_exception("using [] with nil key");
LuaTable & tbl = (*tbl_ptr);
return tbl[k];
}
LuaVal const & LuaVal::operator[](LuaVal const & k) const
{
return get(k);
}
LuaVal const & LuaVal::get(LuaVal const & k) const
{
if (!istable())
throw smallfolk_exception("using get on non table object");
if (k.isnil())
throw smallfolk_exception("using get with nil key");
LuaTable & tbl = (*tbl_ptr);
auto it = tbl.find(k);
if (it != tbl.end())
return it->second;
return nil;
}
bool LuaVal::has(LuaVal const & k) const
{
if (!istable())
throw smallfolk_exception("using has on non table object");
if (k.isnil())
throw smallfolk_exception("using has with nil key");
LuaTable & tbl = (*tbl_ptr);
auto it = tbl.find(k);
return it != tbl.end();
}
LuaVal & LuaVal::set(LuaVal const & k, LuaVal const & v)
{
if (!istable())
throw smallfolk_exception("using set on non table object");
if (k.isnil())
throw smallfolk_exception("using set with nil key");
LuaTable & tbl = (*tbl_ptr);
if (v.isnil()) // on nil value erase key
tbl.erase(k);
else
tbl[k] = v; // normally set pair
return *this;
}
LuaVal & LuaVal::setignore(LuaVal const & k, LuaVal const & v)
{
if (!istable())
throw smallfolk_exception("using setignore on non table object");
if (k.isnil())
throw smallfolk_exception("using setignore with nil key");
if (v.isnil())
return *this;
LuaTable & tbl = (*tbl_ptr);
tbl.emplace(k, v);
return *this;
}
LuaVal & LuaVal::rem(LuaVal const & k)
{
if (!istable())
throw smallfolk_exception("using rem on non table object");
if (k.isnil())
throw smallfolk_exception("using set with nil key");
LuaTable & tbl = (*tbl_ptr);
tbl.erase(k);
return *this;
}
unsigned int LuaVal::len() const
{
if (!istable())
throw smallfolk_exception("using len on non table object");
LuaTable & tbl = (*tbl_ptr);
unsigned int i = 0;
while (++i)
{
auto it = tbl.find(i);
if (it == tbl.end() || it->second.isnil())
break;
}
return i - 1;
}
LuaVal & LuaVal::insert(LuaVal const & v, LuaVal const & pos)
{
if (!istable())
throw smallfolk_exception("using insert on non table object");
LuaTable & tbl = (*tbl_ptr);
if (pos.isnil())
{
if (!v.isnil())
tbl[len() + 1] = v;
return *this;
}
if (!pos.isnumber())
throw smallfolk_exception("using insert with non number pos");
if (std::floor(pos.num()) != pos.num())
throw smallfolk_exception("using insert with invalid number key");
unsigned int max = len() + 1;
unsigned int val = static_cast<unsigned int>(pos.num());
if (val <= 0 || val > max)
throw smallfolk_exception("using insert with out of bounds key");
for (unsigned int i = max; i > val; --i)
tbl[i] = tbl[i - 1];
if (v.isnil())
tbl.erase(val);
else
tbl[val] = v;
return *this;
}
LuaVal & LuaVal::remove(LuaVal const & pos)
{
if (!istable())
throw smallfolk_exception("using remove on non table object");
LuaTable & tbl = (*tbl_ptr);
if (pos.isnil())
{
if (unsigned int i = len())
tbl.erase(i);
return *this;
}
if (!pos.isnumber())
throw smallfolk_exception("using remove with non number key");
if (std::floor(pos.num()) != pos.num())
throw smallfolk_exception("using remove with invalid number key");
unsigned int max = len();
unsigned int val = static_cast<unsigned int>(pos.num());
if (val <= 0 || val > max + 1)
throw smallfolk_exception("using remove with out of bounds key");
for (unsigned int i = val; i < max; ++i)
tbl[i] = tbl[i + 1];
tbl.erase(max);
return *this;
}
std::string LuaVal::type(LuaTypeTag tag)
{
switch (tag)
{
case TBOOL:
return "boolean";
case TNIL:
return "nil";
case TSTRING:
return "string";
case TNUMBER:
return "number";
case TTABLE:
return "table";
}
throw smallfolk_exception("tostring invalid or unhandled tag %i", tag);
}
std::string LuaVal::dumps(std::string * errmsg) const
{
try
{
Serializer::ACC acc;
acc << std::setprecision(17); // min lua percision
unsigned int nmemo = 0;
Serializer::MEMO memo;
Serializer::dump_object(*this, nmemo, memo, acc);
return acc.str();
}
catch (smallfolk_exception const & e)
{
if (errmsg)
*errmsg += e.what();
}
return std::string();
}
LuaVal LuaVal::loads(std::string const & string, std::string * errmsg)
{
try
{
Serializer::TABLES tables;
size_t i = 0;
return Serializer::expect_object(string, i, tables);
}
catch (smallfolk_exception const & e)
{
if (errmsg)
*errmsg += e.what();
}
return LuaVal::nil;
}
bool LuaVal::operator==(LuaVal const& rhs) const
{
if (tag != rhs.tag)
return false;
switch (tag)
{
case TBOOL:
return b == rhs.b;
case TNIL:
return true;
case TSTRING:
return s == rhs.s;
case TNUMBER:
return d == rhs.d;
case TTABLE:
return tbl_ptr == rhs.tbl_ptr;
}
throw smallfolk_exception("operator== invalid or unhandled tag %i", tag);
}
LuaVal::operator bool() const
{
return !isnil() && (!isbool() || boolean());
}
LuaVal& LuaVal::operator=(LuaVal const& val)
{
tag = val.tag;
if (istable())
tbl_ptr.reset(new LuaTable(*val.tbl_ptr));
else
tbl_ptr = nullptr;
s = val.s;
d = val.d;
b = val.b;
return *this;
}
unsigned int Serializer::dump_type_table(LuaVal const & object, unsigned int nmemo, MEMO & memo, ACC & acc)
{
if (!object.istable())
throw smallfolk_exception("using dump_type_table on non table object");
/*
auto it = memo.find(object);
if (it != memo.end())
{
acc << '@' << it->second;
return nmemo;
}
memo[object] = ++nmemo;
*/
acc << '{';
std::map<unsigned int, const LuaVal*> arr;
std::unordered_map<const LuaVal*, const LuaVal*> hash;
for (auto&& v : object.tbl())
{
if (v.first.isnumber() && v.first.num() >= 1 && std::floor(v.first.num()) == v.first.num())
arr[static_cast<unsigned int>(v.first.num())] = &v.second;
else
hash[&v.first] = &v.second;
}
unsigned int i = 1;
for (auto&& v : arr)
{
if (v.first != i)
{
nmemo = dump_object(v.first, nmemo, memo, acc);
acc << ':';
}
else
++i;
nmemo = dump_object(*v.second, nmemo, memo, acc);
acc << ',';
}
for (auto&& v : hash)
{
nmemo = dump_object(*v.first, nmemo, memo, acc);
acc << ':';
nmemo = dump_object(*v.second, nmemo, memo, acc);
acc << ',';
}
std::string l = acc.str();
char c = strat(l, l.length() - 1);
if (c != '{')
{
// remove last char
l.pop_back();
acc.clear();
acc.str(std::string());
acc << l;
}
acc << '}';
return nmemo;
}
unsigned int Serializer::dump_object(LuaVal const & object, unsigned int nmemo, MEMO & memo, ACC & acc)
{
switch (object.typetag())
{
case TBOOL:
acc << (object.boolean() ? 't' : 'f');
break;
case TNIL:
acc << 'n';
break;
case TSTRING:
acc << '"';
acc << escape_quotes(object.str(), '"'); // change to std::quote() in c++14?
acc << '"';
break;
case TNUMBER:
if (!std::isfinite(object.num()))
{
// slightly ugly :(
std::string nn = tostring(object.num());
if (nn == "inf")
acc << 'I';
else if (nn == "-inf")
acc << 'i';
else if (nn == "-nan(ind)")
acc << 'N';
else if (nn == "nan")
acc << 'Q';
else
acc << 'I';
}
else
acc << object.num();
break;
case TTABLE:
return dump_type_table(object, nmemo, memo, acc);
break;
default:
throw smallfolk_exception("dump_object invalid or unhandled tag %i", object.typetag());
break;
}
return nmemo;
}
std::string Serializer::escape_quotes(const std::string & before, char quote)
{
std::string after;
after.reserve(before.length() + 4);
for (std::string::size_type i = 0; i < before.length(); ++i)
{
if (before[i] == quote)
after += quote; // no break
else
after += before[i];
}
return after;
}
std::string Serializer::unescape_quotes(const std::string & before, char quote)
{
std::string after;
after.reserve(before.length());
for (std::string::size_type i = 0; i < before.length(); ++i)
{
if (before[i] == quote)
{
if (i + 1 < before.length() && before[i + 1] == quote)
++i;
}
else
after += before[i];
}
return after;
}
bool Serializer::nonzero_digit(char c)
{
switch (c)
{
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
return true;
}
return false;
}
bool Serializer::is_digit(char c)
{
switch (c)
{
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
return true;
}
return false;
}
char Serializer::strat(std::string const & string, std::string::size_type i)
{
if (i != std::string::npos &&
i < string.length())
return string.at(i);
return '\0'; // bad?
}
LuaVal Serializer::expect_number(std::string const & string, size_t & start)
{
size_t i = start;
char head = strat(string, i);
if (head == '-')
head = strat(string, ++i);
if (nonzero_digit(head))
{
do
{
head = strat(string, ++i);
} while (is_digit(head));
}
else if (head == '0')
head = strat(string, ++i);
else
throw smallfolk_exception("expect_number at %u unexpected character %c", i, head);
if (head == '.')
{
size_t oldi = i;
do
{
head = strat(string, ++i);
} while (is_digit(head));
if (i == oldi + 1)
throw smallfolk_exception("expect_number at %u no numbers after decimal", i);
}
if (head == 'e' || head == 'E')
{
head = strat(string, ++i);
if (head == '+' || head == '-')
head = strat(string, ++i);
if (!is_digit(head))
throw smallfolk_exception("expect_number at %u not a digit part %c", i, head);
do
{
head = strat(string, ++i);
} while (is_digit(head));
}
size_t temp = start;
start = i;
return std::atof(string.substr(temp, i).c_str());
}
LuaVal Serializer::expect_object(std::string const & string, size_t & i, Serializer::TABLES & tables)
{
static double _zero = 0.0;
char cc = strat(string, i++);
switch (cc)
{
case ' ':
case '\t':
// skip whitespace
return expect_object(string, i, tables);
case 't':
return true;
case 'f':
return false;
case 'n':
return LuaVal::nil;
case 'Q':
return -(0 / _zero);
case 'N':
return (0 / _zero);
case 'I':
return (1 / _zero);
case 'i':
return -(1 / _zero);
case '\'':
case '"':
{
size_t nexti = i - 1;
do
{
nexti = string.find(cc, nexti + 1);
if (nexti == std::string::npos)
{
throw smallfolk_exception("expect_object at %u was %c eof before string ends", i, cc);
}
++nexti;
} while (strat(string, nexti) == cc);
size_t temp = i;
i = nexti;
return unescape_quotes(string.substr(temp, nexti - temp - 1), cc);
}
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '-':
case '.':
return expect_number(string, --i);
case '{':
{
LuaVal nt(TTABLE);
unsigned int j = 1;
tables.push_back(nt);
if (strat(string, i) == '}')
{
++i;
return nt;
}
while (true)
{
LuaVal k = expect_object(string, i, tables);
char at = strat(string, i);
while (at == ' ')
at = strat(string, ++i);
if (at == ':')
{
nt.set(k, expect_object(string, ++i, tables));
}
else
{
nt.set(j, k);
++j;
}
char head = strat(string, i);
while (head == ' ')
head = strat(string, ++i);
if (head == ',')
++i;
else if (head == '}')
{
++i;
return nt;
}
else
{
throw smallfolk_exception("expect_object at %u was %c unexpected character %c", i, cc, head);
}
}
break;
}
/*
case '@':
{
std::string::size_type x = i;
for (; x < string.length(); ++x)
{
if (!isdigit(string[x]))
break;
}
std::string substr = string.substr(i, x - i);
size_t index = std::stoul(substr.c_str());
if (index >= 1 && index <= tables.size())
{
i += substr.length();
return tables[index - 1];
}
throw smallfolk_exception("expect_object at %u was %c invalid index %u", i, cc, index);
break;
}
*/
default:
{
throw smallfolk_exception("expect_object at %u was %c", i, cc);
break;
}
}
return LuaVal::nil;
}
smallfolk_exception::smallfolk_exception(const char * format, ...) : std::logic_error("Smallfolk exception")
{
char buffer[size];
va_list args;
va_start(args, format);
vsnprintf(buffer, size, format, args);
errmsg = std::string("Smallfolk: ") + buffer;
va_end(args);
}
const char * smallfolk_exception::what() const throw()
{
return errmsg.c_str();
}