This repository has been archived by the owner on Nov 9, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathtoml.h
2050 lines (1746 loc) · 53.1 KB
/
toml.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
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
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#ifndef TINYTOML_H_
#define TINYTOML_H_
#include <algorithm>
#include <cassert>
#include <cctype>
#include <chrono>
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <ctime>
#include <fstream>
#include <iomanip>
#include <istream>
#include <sstream>
#include <stdexcept>
#include <string>
#include <map>
#include <memory>
#include <utility>
#include <vector>
namespace toml {
// ----------------------------------------------------------------------
// Declarations
class Value;
typedef std::chrono::system_clock::time_point Time;
typedef std::vector<Value> Array;
typedef std::map<std::string, Value> Table;
namespace internal {
template<typename T> struct call_traits_value {
typedef T return_type;
};
template<typename T> struct call_traits_ref {
typedef const T& return_type;
};
} // namespace internal
template<typename T> struct call_traits;
template<> struct call_traits<bool> : public internal::call_traits_value<bool> {};
template<> struct call_traits<int> : public internal::call_traits_value<int> {};
template<> struct call_traits<int64_t> : public internal::call_traits_value<int64_t> {};
template<> struct call_traits<double> : public internal::call_traits_value<double> {};
template<> struct call_traits<std::string> : public internal::call_traits_ref<std::string> {};
template<> struct call_traits<Time> : public internal::call_traits_ref<Time> {};
template<> struct call_traits<Array> : public internal::call_traits_ref<Array> {};
template<> struct call_traits<Table> : public internal::call_traits_ref<Table> {};
// A value is returned for std::vector<T>. Not reference.
// This is because a fresh vector is made.
template<typename T> struct call_traits<std::vector<T>> : public internal::call_traits_value<std::vector<T>> {};
// Formatting flags
enum FormatFlag {
FORMAT_NONE = 0,
FORMAT_INDENT = 1
};
class Value {
public:
enum Type {
NULL_TYPE,
BOOL_TYPE,
INT_TYPE,
DOUBLE_TYPE,
STRING_TYPE,
TIME_TYPE,
ARRAY_TYPE,
TABLE_TYPE,
};
Value() : type_(NULL_TYPE), null_(nullptr) {}
Value(bool v) : type_(BOOL_TYPE), bool_(v) {}
Value(int v) : type_(INT_TYPE), int_(v) {}
Value(int64_t v) : type_(INT_TYPE), int_(v) {}
Value(double v) : type_(DOUBLE_TYPE), double_(v) {}
Value(const std::string& v) : type_(STRING_TYPE), string_(new std::string(v)) {}
Value(const char* v) : type_(STRING_TYPE), string_(new std::string(v)) {}
Value(const Time& v) : type_(TIME_TYPE), time_(new Time(v)) {}
Value(const Array& v) : type_(ARRAY_TYPE), array_(new Array(v)) {}
Value(const Table& v) : type_(TABLE_TYPE), table_(new Table(v)) {}
Value(std::string&& v) : type_(STRING_TYPE), string_(new std::string(std::move(v))) {}
Value(Array&& v) : type_(ARRAY_TYPE), array_(new Array(std::move(v))) {}
Value(Table&& v) : type_(TABLE_TYPE), table_(new Table(std::move(v))) {}
Value(const Value& v);
Value(Value&& v) noexcept;
Value& operator=(const Value& v);
Value& operator=(Value&& v) noexcept;
// Guards from unexpected Value construction.
// Someone might use a value like this:
// toml::Value v = x->find("foo");
// But this is wrong. Without this constructor,
// value will be unexpectedly initialized with bool.
Value(const void* v) = delete;
~Value();
// Retruns Value size.
// 0 for invalid value.
// The number of inner elements for array or table.
// 1 for other types.
size_t size() const;
bool empty() const;
Type type() const { return type_; }
bool valid() const { return type_ != NULL_TYPE; }
template<typename T> bool is() const;
template<typename T> typename call_traits<T>::return_type as() const;
friend bool operator==(const Value& lhs, const Value& rhs);
friend bool operator!=(const Value& lhs, const Value& rhs) { return !(lhs == rhs); }
// ----------------------------------------------------------------------
// For integer/floating value
// Returns true if the value is int or double.
bool isNumber() const;
// Returns number. Convert to double.
double asNumber() const;
// ----------------------------------------------------------------------
// For Time value
// Converts to time_t if the internal value is Time.
// We don't have as<std::time_t>(). Since time_t is basically signed long,
// it's something like a method to converting to (normal) integer.
std::time_t as_time_t() const;
// ----------------------------------------------------------------------
// For Table value
template<typename T> typename call_traits<T>::return_type get(const std::string&) const;
Value* set(const std::string& key, const Value& v);
// Finds a Value with |key|. |key| can contain '.'
// Note: if you would like to find a child value only, you need to use findChild.
const Value* find(const std::string& key) const;
Value* find(const std::string& key);
bool has(const std::string& key) const { return find(key) != nullptr; }
bool erase(const std::string& key);
Value& operator[](const std::string& key);
// Merge table. Returns true if succeeded. Otherwise, |this| might be corrupted.
// When the same key exists, it will be overwritten.
bool merge(const Value&);
// Finds a value with |key|. It searches only children.
Value* findChild(const std::string& key);
const Value* findChild(const std::string& key) const;
// Sets a value, and returns the pointer to the created value.
// When the value having the same key exists, it will be overwritten.
Value* setChild(const std::string& key, const Value& v);
Value* setChild(const std::string& key, Value&& v);
bool eraseChild(const std::string& key);
// ----------------------------------------------------------------------
// For Array value
template<typename T> typename call_traits<T>::return_type get(size_t index) const;
const Value* find(size_t index) const;
Value* find(size_t index);
Value* push(const Value& v);
Value* push(Value&& v);
// ----------------------------------------------------------------------
// Others
// Writer.
static std::string spaces(int num);
static std::string escapeKey(const std::string& key);
void write(std::ostream*, const std::string& keyPrefix = std::string(), int indent = -1) const;
void writeFormatted(std::ostream*, FormatFlag flags) const;
friend std::ostream& operator<<(std::ostream&, const Value&);
private:
static const char* typeToString(Type);
template<typename T> void assureType() const;
Value* ensureValue(const std::string& key);
template<typename T> struct ValueConverter;
Type type_;
union {
void* null_;
bool bool_;
int64_t int_;
double double_;
std::string* string_;
Time* time_;
Array* array_;
Table* table_;
};
template<typename T> friend struct ValueConverter;
};
// parse() returns ParseResult.
struct ParseResult {
ParseResult(toml::Value v, std::string er) :
value(std::move(v)),
errorReason(std::move(er)) {}
bool valid() const { return value.valid(); }
toml::Value value;
std::string errorReason;
};
// Parses from std::istream.
ParseResult parse(std::istream&);
// Parses a file.
ParseResult parseFile(const std::string& filename);
// ----------------------------------------------------------------------
// Declarations for Implementations
// You don't need to understand the below to use this library.
#if defined(_WIN32)
// Windows does not have timegm but have _mkgmtime.
inline time_t timegm(std::tm* timeptr)
{
return _mkgmtime(timeptr);
}
// On Windows, Visual Studio does not define gmtime_r. However, mingw might
// do (or might not do). See https://github.com/mayah/tinytoml/issues/25,
#ifndef gmtime_r
inline struct tm* gmtime_r(const time_t* t, struct tm* r)
{
// gmtime is threadsafe in windows because it uses TLS
struct tm *theTm = gmtime(t);
if (theTm) {
*r = *theTm;
return r;
} else {
return 0;
}
}
#endif // gmtime_r
#endif // _WIN32
namespace internal {
enum class TokenType {
ERROR_TOKEN,
END_OF_FILE,
END_OF_LINE,
IDENT,
STRING,
MULTILINE_STRING,
BOOL,
INT,
DOUBLE,
TIME,
COMMA,
DOT,
EQUAL,
LBRACKET,
RBRACKET,
LBRACE,
RBRACE,
};
class Token {
public:
explicit Token(TokenType tokenType) : type_(tokenType) {}
Token(TokenType tokenType, const std::string& v) : type_(tokenType), str_value_(v) {}
Token(TokenType tokenType, bool v) : type_(tokenType), int_value_(v) {}
Token(TokenType tokenType, std::int64_t v) : type_(tokenType), int_value_(v) {}
Token(TokenType tokenType, double v) : type_(tokenType), double_value_(v) {}
Token(TokenType tokenType, std::chrono::system_clock::time_point tp) : type_(tokenType), time_value_(tp) {}
TokenType type() const { return type_; }
const std::string& strValue() const { return str_value_; }
bool boolValue() const { return int_value_ != 0; }
std::int64_t intValue() const { return int_value_; }
double doubleValue() const { return double_value_; }
std::chrono::system_clock::time_point timeValue() const { return time_value_; }
private:
TokenType type_;
std::string str_value_;
std::int64_t int_value_;
double double_value_;
std::chrono::system_clock::time_point time_value_;
};
class Lexer {
public:
explicit Lexer(std::istream& is) : is_(is), lineNo_(1) {}
Token nextKeyToken();
Token nextValueToken();
int lineNo() const { return lineNo_; }
// Skips if UTF8BOM is found.
// Returns true if success. Returns false if intermediate state is left.
bool skipUTF8BOM();
private:
bool current(char* c);
void next();
bool consume(char c);
Token nextToken(bool isValueToken);
void skipUntilNewLine();
Token nextStringDoubleQuote();
Token nextStringSingleQuote();
Token nextKey();
Token nextValue();
Token parseAsTime(const std::string&);
std::istream& is_;
int lineNo_;
};
class Parser {
public:
explicit Parser(std::istream& is) : lexer_(is), token_(TokenType::ERROR_TOKEN)
{
if (!lexer_.skipUTF8BOM()) {
token_ = Token(TokenType::ERROR_TOKEN, std::string("Invalid UTF8 BOM"));
} else {
nextKey();
}
}
// Parses. If failed, value should be invalid value.
// You can get the error by calling errorReason().
Value parse();
const std::string& errorReason();
private:
const Token& token() const { return token_; }
void nextKey() { token_ = lexer_.nextKeyToken(); }
void nextValue() { token_ = lexer_.nextValueToken(); }
void skipForKey();
void skipForValue();
bool consumeForKey(TokenType);
bool consumeForValue(TokenType);
bool consumeEOLorEOFForKey();
Value* parseGroupKey(Value* root);
bool parseKeyValue(Value*);
bool parseKey(std::string*);
bool parseValue(Value*);
bool parseBool(Value*);
bool parseNumber(Value*);
bool parseArray(Value*);
bool parseInlineTable(Value*);
void addError(const std::string& reason);
Lexer lexer_;
Token token_;
std::string errorReason_;
};
} // namespace internal
// ----------------------------------------------------------------------
// Implementations
inline ParseResult parse(std::istream& is)
{
if (!is) {
return ParseResult(toml::Value(), "stream is in bad state. file does not exist?");
}
internal::Parser parser(is);
toml::Value v = parser.parse();
if (v.valid())
return ParseResult(std::move(v), std::string());
return ParseResult(std::move(v), std::move(parser.errorReason()));
}
inline ParseResult parseFile(const std::string& filename)
{
std::ifstream ifs(filename);
if (!ifs) {
return ParseResult(toml::Value(),
std::string("could not open file: ") + filename);
}
return parse(ifs);
}
inline std::string format(std::stringstream& ss)
{
return ss.str();
}
template<typename T, typename... Args>
std::string format(std::stringstream& ss, T&& t, Args&&... args)
{
ss << std::forward<T>(t);
return format(ss, std::forward<Args>(args)...);
}
// If you want to compile without exception,
// 1. Define TOML_HAVE_FAILWITH_REPLACEMENT
// 2. Define your own toml::failwith.
// e.g. You can just abort here instead of exception.
#ifndef TOML_HAVE_FAILWITH_REPLACEMENT
template<typename... Args>
#if defined(_MSC_VER)
__declspec(noreturn)
#else
[[noreturn]]
#endif
void failwith(Args&&... args)
{
std::stringstream ss;
throw std::runtime_error(format(ss, std::forward<Args>(args)...));
}
#endif
namespace internal {
inline std::string removeDelimiter(const std::string& s)
{
std::string r;
for (char c : s) {
if (c == '_')
continue;
r += c;
}
return r;
}
inline std::string unescape(const std::string& codepoint)
{
std::uint32_t x;
std::uint8_t buf[8];
std::stringstream ss(codepoint);
ss >> std::hex >> x;
if (x <= 0x7FUL) {
// 0xxxxxxx
buf[0] = 0x00 | ((x >> 0) & 0x7F);
buf[1] = '\0';
} else if (x <= 0x7FFUL) {
// 110yyyyx 10xxxxxx
buf[0] = 0xC0 | ((x >> 6) & 0xDF);
buf[1] = 0x80 | ((x >> 0) & 0xBF);
buf[2] = '\0';
} else if (x <= 0xFFFFUL) {
// 1110yyyy 10yxxxxx 10xxxxxx
buf[0] = 0xE0 | ((x >> 12) & 0xEF);
buf[1] = 0x80 | ((x >> 6) & 0xBF);
buf[2] = 0x80 | ((x >> 0) & 0xBF);
buf[3] = '\0';
} else if (x <= 0x10FFFFUL) {
// 11110yyy 10yyxxxx 10xxxxxx 10xxxxxx
buf[0] = 0xF0 | ((x >> 18) & 0xF7);
buf[1] = 0x80 | ((x >> 12) & 0xBF);
buf[2] = 0x80 | ((x >> 6) & 0xBF);
buf[3] = 0x80 | ((x >> 0) & 0xBF);
buf[4] = '\0';
} else {
buf[0] = '\0';
}
return reinterpret_cast<char*>(buf);
}
// Returns true if |s| is integer.
// [+-]?\d+(_\d+)*
inline bool isInteger(const std::string& s)
{
if (s.empty())
return false;
std::string::size_type p = 0;
if (s[p] == '+' || s[p] == '-')
++p;
while (p < s.size() && '0' <= s[p] && s[p] <= '9') {
++p;
if (p < s.size() && s[p] == '_') {
++p;
if (!(p < s.size() && '0' <= s[p] && s[p] <= '9'))
return false;
}
}
return p == s.size();
}
// Returns true if |s| is double.
// [+-]? (\d+(_\d+)*)? (\.\d+(_\d+)*)? ([eE] [+-]? \d+(_\d+)*)?
// 1----------- 2------------- 3----------------------
// 2 or (1 and 3) should exist.
inline bool isDouble(const std::string& s)
{
if (s.empty())
return false;
std::string::size_type p = 0;
if (s[p] == '+' || s[p] == '-')
++p;
bool ok = false;
while (p < s.size() && '0' <= s[p] && s[p] <= '9') {
++p;
ok = true;
if (p < s.size() && s[p] == '_') {
++p;
if (!(p < s.size() && '0' <= s[p] && s[p] <= '9'))
return false;
}
}
if (p < s.size() && s[p] == '.')
++p;
while (p < s.size() && '0' <= s[p] && s[p] <= '9') {
++p;
ok = true;
if (p < s.size() && s[p] == '_') {
++p;
if (!(p < s.size() && '0' <= s[p] && s[p] <= '9'))
return false;
}
}
if (!ok)
return false;
ok = false;
if (p < s.size() && (s[p] == 'e' || s[p] == 'E')) {
++p;
if (p < s.size() && (s[p] == '+' || s[p] == '-'))
++p;
while (p < s.size() && '0' <= s[p] && s[p] <= '9') {
++p;
ok = true;
if (p < s.size() && s[p] == '_') {
++p;
if (!(p < s.size() && '0' <= s[p] && s[p] <= '9'))
return false;
}
}
if (!ok)
return false;
}
return p == s.size();
}
// static
inline std::string escapeString(const std::string& s)
{
std::stringstream ss;
for (size_t i = 0; i < s.size(); ++i) {
switch (s[i]) {
case '\n': ss << "\\n"; break;
case '\r': ss << "\\r"; break;
case '\t': ss << "\\t"; break;
case '\"': ss << "\\\""; break;
case '\'': ss << "\\\'"; break;
case '\\': ss << "\\\\"; break;
default: ss << s[i]; break;
}
}
return ss.str();
}
} // namespace internal
// ----------------------------------------------------------------------
// Lexer
namespace internal {
inline bool Lexer::skipUTF8BOM()
{
// Check [EF, BB, BF]
int x1 = is_.peek();
if (x1 != 0xEF) {
// When the first byte is not 0xEF, it's not UTF8 BOM.
// Just return true.
return true;
}
is_.get();
int x2 = is_.get();
if (x2 != 0xBB) {
return false;
}
int x3 = is_.get();
if (x3 != 0xBF) {
return false;
}
return true;
}
inline bool Lexer::current(char* c)
{
int x = is_.peek();
if (x == EOF)
return false;
*c = static_cast<char>(x);
return true;
}
inline void Lexer::next()
{
int x = is_.get();
if (x == '\n')
++lineNo_;
}
inline bool Lexer::consume(char c)
{
char x;
if (!current(&x))
return false;
if (x != c)
return false;
next();
return true;
}
inline void Lexer::skipUntilNewLine()
{
char c;
while (current(&c)) {
if (c == '\n')
return;
next();
}
}
inline Token Lexer::nextStringDoubleQuote()
{
if (!consume('"'))
return Token(TokenType::ERROR_TOKEN, std::string("string didn't start with '\"'"));
std::string s;
char c;
bool multiline = false;
if (current(&c) && c == '"') {
next();
if (!current(&c) || c != '"') {
// OK. It's empty string.
return Token(TokenType::STRING, std::string());
}
next();
// raw string literal started.
// Newline just after """ should be ignored.
while (current(&c) && (c == ' ' || c == '\t'))
next();
if (current(&c) && c == '\n')
next();
multiline = true;
}
while (current(&c)) {
next();
if (c == '\\') {
if (!current(&c))
return Token(TokenType::ERROR_TOKEN, std::string("string has unknown escape sequence"));
next();
switch (c) {
case 't': c = '\t'; break;
case 'n': c = '\n'; break;
case 'r': c = '\r'; break;
case 'u':
case 'U': {
int size = c == 'u' ? 4 : 8;
std::string codepoint;
for (int i = 0; i < size; ++i) {
if (current(&c) && (('0' <= c && c <= '9') || ('A' <= c && c <= 'F') || ('a' <= c && c <= 'f'))) {
codepoint += c;
next();
} else {
return Token(TokenType::ERROR_TOKEN, std::string("string has unknown escape sequence"));
}
}
s += unescape(codepoint);
continue;
}
case '"': c = '"'; break;
case '\'': c = '\''; break;
case '\\': c = '\\'; break;
case '\n':
while (current(&c) && (c == ' ' || c == '\t' || c == '\r' || c == '\n')) {
next();
}
continue;
default:
return Token(TokenType::ERROR_TOKEN, std::string("string has unknown escape sequence"));
}
} else if (c == '"') {
if (multiline) {
if (current(&c) && c == '"') {
next();
if (current(&c) && c == '"') {
next();
return Token(TokenType::MULTILINE_STRING, s);
} else {
s += '"';
s += '"';
continue;
}
} else {
s += '"';
continue;
}
} else {
return Token(TokenType::STRING, s);
}
}
s += c;
}
return Token(TokenType::ERROR_TOKEN, std::string("string didn't end"));
}
inline Token Lexer::nextStringSingleQuote()
{
if (!consume('\''))
return Token(TokenType::ERROR_TOKEN, std::string("string didn't start with '\''?"));
std::string s;
char c;
if (current(&c) && c == '\'') {
next();
if (!current(&c) || c != '\'') {
// OK. It's empty string.
return Token(TokenType::STRING, std::string());
}
next();
// raw string literal started.
// Newline just after """ should be ignored.
if (current(&c) && c == '\n')
next();
while (current(&c)) {
if (c == '\'') {
next();
if (current(&c) && c == '\'') {
next();
if (current(&c) && c == '\'') {
next();
return Token(TokenType::MULTILINE_STRING, s);
} else {
s += '\'';
s += '\'';
continue;
}
} else {
s += '\'';
continue;
}
}
next();
s += c;
continue;
}
return Token(TokenType::ERROR_TOKEN, std::string("string didn't end with '\'\'\'' ?"));
}
while (current(&c)) {
next();
if (c == '\'') {
return Token(TokenType::STRING, s);
}
s += c;
}
return Token(TokenType::ERROR_TOKEN, std::string("string didn't end with '\''?"));
}
inline Token Lexer::nextKey()
{
std::string s;
char c;
while (current(&c) && (isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '-')) {
s += c;
next();
}
if (s.empty())
return Token(TokenType::ERROR_TOKEN, std::string("Unknown key format"));
return Token(TokenType::IDENT, s);
}
inline Token Lexer::nextValue()
{
std::string s;
char c;
if (current(&c) && isalpha(static_cast<unsigned char>(c))) {
s += c;
next();
while (current(&c) && isalpha(static_cast<unsigned char>(c))) {
s += c;
next();
}
if (s == "true")
return Token(TokenType::BOOL, true);
if (s == "false")
return Token(TokenType::BOOL, false);
return Token(TokenType::ERROR_TOKEN, std::string("Unknown ident: ") + s);
}
while (current(&c) && (('0' <= c && c <= '9') || c == '.' || c == 'e' || c == 'E' ||
c == 'T' || c == 'Z' || c == '_' || c == ':' || c == '-' || c == '+')) {
next();
s += c;
}
if (isInteger(s)) {
std::stringstream ss(removeDelimiter(s));
std::int64_t x;
ss >> x;
return Token(TokenType::INT, x);
}
if (isDouble(s)) {
std::stringstream ss(removeDelimiter(s));
double d;
ss >> d;
return Token(TokenType::DOUBLE, d);
}
return parseAsTime(s);
}
inline Token Lexer::parseAsTime(const std::string& str)
{
const char* s = str.c_str();
int n;
int YYYY, MM, DD;
#if defined(_MSC_VER)
if (sscanf_s(s, "%d-%d-%d%n", &YYYY, &MM, &DD, &n) != 3)
return Token(TokenType::ERROR_TOKEN, std::string("Invalid token"));
#else
if (sscanf(s, "%d-%d-%d%n", &YYYY, &MM, &DD, &n) != 3)
return Token(TokenType::ERROR_TOKEN, std::string("Invalid token"));
#endif
if (!(1 <= MM && MM <= 12)) {
return Token(TokenType::ERROR_TOKEN, std::string("Invalid token"));
}
if (YYYY < 1900) {
return Token(TokenType::ERROR_TOKEN, std::string("Invalid token"));
}
if (s[n] == '\0') {
std::tm t;
t.tm_sec = 0;
t.tm_min = 0;
t.tm_hour = 0;
t.tm_mday = DD;
t.tm_mon = MM - 1;
t.tm_year = YYYY - 1900;
auto tp = std::chrono::system_clock::from_time_t(timegm(&t));
return Token(TokenType::TIME, tp);
}
if (s[n] != 'T')
return Token(TokenType::ERROR_TOKEN, std::string("Invalid token"));
s = s + n + 1;
int hh, mm;
double ss; // double for fraction
#if defined(_MSC_VER)
if (sscanf_s(s, "%d:%d:%lf%n", &hh, &mm, &ss, &n) != 3)
return Token(TokenType::ERROR_TOKEN, std::string("Invalid token"));
#else
if (sscanf(s, "%d:%d:%lf%n", &hh, &mm, &ss, &n) != 3)
return Token(TokenType::ERROR_TOKEN, std::string("Invalid token"));
#endif
std::tm t;
t.tm_sec = static_cast<int>(ss);
t.tm_min = mm;
t.tm_hour = hh;
t.tm_mday = DD;
t.tm_mon = MM - 1;
t.tm_year = YYYY - 1900;
auto tp = std::chrono::system_clock::from_time_t(timegm(&t));
ss -= static_cast<int>(ss);
// TODO(mayah): workaround GCC 4.9.3 on cygwin does not have std::round, but round().
tp += std::chrono::microseconds(static_cast<std::int64_t>(round(ss * 1000000)));
if (s[n] == '\0')
return Token(TokenType::TIME, tp);
if (s[n] == 'Z' && s[n + 1] == '\0')
return Token(TokenType::TIME, tp);
s = s + n;
// offset
// [+/-]%d:%d
char pn;
int oh, om;
#if defined(_MSC_VER)
if (sscanf_s(s, "%c%d:%d", &pn, static_cast<unsigned>(sizeof(pn)), &oh, &om) != 3)
return Token(TokenType::ERROR_TOKEN, std::string("Invalid token"));
#else
if (sscanf(s, "%c%d:%d", &pn, &oh, &om) != 3)
return Token(TokenType::ERROR_TOKEN, std::string("Invalid token"));
#endif
if (pn != '+' && pn != '-')
return Token(TokenType::ERROR_TOKEN, std::string("Invalid token"));
if (pn == '+') {
tp -= std::chrono::hours(oh);
tp -= std::chrono::minutes(om);
} else {
tp += std::chrono::hours(oh);
tp += std::chrono::minutes(om);
}
return Token(TokenType::TIME, tp);
}
inline Token Lexer::nextKeyToken()
{
return nextToken(false);
}
inline Token Lexer::nextValueToken()
{
return nextToken(true);
}
inline Token Lexer::nextToken(bool isValueToken)
{
char c;
while (current(&c)) {
if (c == ' ' || c == '\t' || c == '\r') {
next();
continue;
}
if (c == '#') {
skipUntilNewLine();
continue;
}
switch (c) {
case '\n':
next();
return Token(TokenType::END_OF_LINE);
case '=':
next();
return Token(TokenType::EQUAL);
case '{':
next();
return Token(TokenType::LBRACE);
case '}':
next();
return Token(TokenType::RBRACE);
case '[':
next();
return Token(TokenType::LBRACKET);
case ']':