/
safe_json.hpp
2700 lines (2142 loc) · 73 KB
/
safe_json.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
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
#pragma once
#include <utility>
#include <cstdint>
#include <variant>
#include <vector>
#include <string>
#include <array>
#include <tuple>
#include <span>
#include <string_view>
#include <istream>
#include <ostream>
#include <iomanip>
#include <format>
#include <algorithm>
#include <stdexcept>
#include <cmath>
#include <bitset>
#ifndef ZTU_JSON_DETAIL
#define ZTU_JSON_DETAIL
namespace ztu::json_internal {
namespace literal_config {
constexpr char left_brace[] = "{";
constexpr char right_brace[] = "}";
constexpr char left_bracket[] = "[";
constexpr char right_bracket[] = "]";
constexpr char colon[] = ":";
constexpr char comma[] = ",";
constexpr char null[] = "null";
constexpr char boolean_false[] = "false";
constexpr char boolean_true[] = "true";
constexpr char string_begin = '"';
constexpr char string_end = '"';
constexpr char variant_type[] = "_type";
} // namespace literal_config
#define ztu_ic inline constexpr
#define ztu_nic [[nodiscard]] inline constexpr
namespace for_each {
template<auto Size>
ztu_ic bool index(auto &&f) {
return [&]<auto... Indices>(std::index_sequence<Indices...>) {
return (f.template operator()<Indices>() || ...);
}(std::make_index_sequence<Size>());
}
template<typename... Types>
ztu_ic bool type(auto &&f) {
return (f.template operator()<Types>() || ...);
}
template<auto... Values>
ztu_ic bool value(auto &&f) {
return (f.template operator()<Values>() || ...);
}
template<auto... Values>
ztu_ic bool indexed_value(auto &&f) {
return [&]<auto... Indices>(std::index_sequence<Indices...>) {
return (f.template operator()<Indices, Values>() || ...);
}(std::make_index_sequence<sizeof...(Values)>());
}
template<typename... Args>
ztu_ic bool indexed_argument(auto &&f, Args&&... args) {
return [&]<auto... Indices>(std::index_sequence<Indices...>) {
return (f.template operator()<Indices>(std::forward<Args>(args)) || ...);
}(std::make_index_sequence<sizeof...(Args)>());
}
} // namespace for_each
using std::size_t;
using ssize_t = std::make_signed_t<size_t>;
template<ssize_t N>
requires (N > 0)
struct string_literal {
static constexpr auto max_length = N - 1;
ztu_ic string_literal() = default;
ztu_ic string_literal(const char (&str)[N]);
template<ssize_t M> requires (M > 0 and M <= N)
ztu_ic string_literal(const char (&str)[M]);
template<typename... Chars> requires (sizeof...(Chars) == max_length)
ztu_ic string_literal(Chars... chars) : value{chars..., '\0' } {}
template<ssize_t M>
ztu_nic bool operator==(const string_literal<M> &other) const;
ztu_nic const char *c_str() const;
ztu_nic ssize_t size() const;
ztu_nic auto begin();
ztu_nic auto begin() const;
ztu_nic auto end();
ztu_nic auto end() const;
ztu_nic char& operator[](size_t index);
ztu_nic const char& operator[](size_t index) const;
template<ssize_t M>
inline friend std::ostream& operator<<(std::ostream &out, const string_literal<M>& str);
public:
std::array<char,N> value{};
};
template<ssize_t N>
requires (N > 0)
ztu_ic string_literal<N>::string_literal(const char (&str)[N]) {
std::copy_n(std::begin(str), N, value.begin());
}
template<ssize_t N> requires (N > 0)
template<ssize_t M> requires (M > 0 and M <= N)
ztu_ic string_literal<N>::string_literal(const char (&str)[M]) {
std::copy_n(std::begin(str), M, value.begin());
value[M-1] = '\0';
}
template<ssize_t N>
requires (N > 0)
template<ssize_t M>
ztu_ic bool string_literal<N>::operator==(const string_literal<M> &other) const {
const auto length = std::min(N,M);
for (ssize_t i = 0; i < length; i++) {
if (value[i] != other.value[i]) {
return false;
}
}
return true;
}
template<ssize_t N> requires (N > 0)
ztu_nic const char *string_literal<N>::c_str() const { return value.data(); }
template<ssize_t N> requires (N > 0)
ztu_nic ssize_t string_literal<N>::size() const {
ssize_t length = 0;
while (length < N && value[length] != '\0')
length++;
return length;
}
template<ssize_t N> requires (N > 0)
ztu_nic auto string_literal<N>::begin() { return value.begin(); }
template<ssize_t N> requires (N > 0)
ztu_nic auto string_literal<N>::begin() const { return value.begin(); }
template<ssize_t N> requires (N > 0)
ztu_nic auto string_literal<N>::end() { return value.begin() + size(); }
template<ssize_t N> requires (N > 0)
ztu_nic auto string_literal<N>::end() const { return value.begin() + size(); }
template<ssize_t M>
inline std::ostream& operator<<(std::ostream &out, const string_literal<M>& str) {
return out << str.c_str();
}
template<ssize_t N> requires (N > 0)
ztu_nic char& string_literal<N>::operator[](size_t index) {
return value[index];
}
template<ssize_t N> requires (N > 0)
ztu_nic const char& string_literal<N>::operator[](size_t index) const {
return value[index];
}
namespace string_literals {
template<string_literal Str>
constexpr auto operator"" _sl() {
return Str;
}
}
namespace transcoding_error {
enum class codes {
OK = 0,
WRONG_SPELLING,
UNKNOWN_SPELLING_INDEX,
NONE_HEX_CHAR_IN_UNICODE_ESCAPE,
UNKNOWN_ESCAPE_SEQUENCE,
UNESCAPED_CHARACTER,
CUT_OF_UTF8_CHARACTER,
EOF_IN_TOKEN
};
struct category : std::error_category {
const char* name() const noexcept override {
return "transcoding";
}
std::string message(int ev) const override {
switch (static_cast<codes>(ev)) {
case codes::WRONG_SPELLING:
return "Character sequence does not match any of the valid spellings for this token.";
case codes::UNKNOWN_SPELLING_INDEX:
return "The specified index does not correspond to a spelling.";
case codes::NONE_HEX_CHAR_IN_UNICODE_ESCAPE:
return "None hex character in unicode escape sequence.";
case codes::UNKNOWN_ESCAPE_SEQUENCE:
return "Unknown escape sequence.";
case codes::UNESCAPED_CHARACTER:
return "Unescaped character string literal.";
case codes::EOF_IN_TOKEN:
return "Reached end of file while parsing token.";
case codes::CUT_OF_UTF8_CHARACTER:
return "utf8 character begin without second byte.";
default:
using namespace std::string_literals;
return "unrecognized error ("s + std::to_string(ev) + ")";
}
}
};
} // namespace transcoding_error
inline std::error_category& transcoding_error_category() {
static transcoding_error::category category;
return category;
}
namespace transcoding_error {
inline std::error_code make_error_code(codes e) {
return { static_cast<int>(e), transcoding_error_category() };
}
} // namespace transcoding_error
} // ztu::json_internal
template <>
struct std::is_error_code_enum<ztu::json_internal::transcoding_error::codes> : public std::true_type {};
namespace ztu::json_internal::transcoding {
template<class T, typename Enum>
concept token_concept = (
std::same_as<Enum, typename T::enum_t> &&
requires(const T::value_t& value, std::vector<char>& buffer, std::istream& is, std::ostream& os, std::error_code& e) {
{ T::begins_with(is) } -> std::same_as<bool>;
{ T::read(is, buffer, e) } -> std::same_as<typename T::value_t>;
{ T::write(os, value, e) } -> std::same_as<void>;
{ T::name() } -> std::same_as<std::string_view>;
{ T::type() } -> std::same_as<typename T::enum_t>;
}
);
namespace token_internal {
template<typename Enum, Enum Type, string_literal Name, typename ValueType = std::monostate>
struct token_base {
using enum_t = Enum;
using value_t = ValueType;
constexpr static inline Enum type() {
return Type;
}
constexpr static inline std::string_view name() {
return { Name.c_str() };
}
};
template<auto Type, string_literal Name, string_literal Spelling>
struct literal_token : public token_base<decltype(Type), Type, Name> {
using base_t = token_base<decltype(Type), Type, Name> ;
using typename base_t::value_t;
inline static bool begins_with(std::istream &is) {
return is.peek() == Spelling[0U];
}
inline static value_t read(std::istream &is, std::vector<char> &, std::error_code& error) {
for (const auto& c : Spelling) {
if (is.peek() != c) {
using transcoding_error::make_error_code;
using enum transcoding_error::codes;
error = make_error_code(WRONG_SPELLING);
break;
}
is.get();
}
return {};
}
inline static void write(std::ostream &os, const value_t&, std::error_code& error) {
os.write(Spelling.c_str(), Spelling.size());
}
};
template<auto Type, string_literal Name, std::integral IndexType, string_literal... Spellings>
struct multi_literal_token : token_base<decltype(Type), Type, Name, IndexType> {
using base_t = token_base<decltype(Type), Type, Name, IndexType>;
using typename base_t::value_t;
inline static bool begins_with(std::istream &is) {
const auto c = is.peek();
return for_each::value<Spellings...>(
[&]<auto Spelling>() {
return c == Spelling[0U];
}
);
}
inline static value_t read(std::istream &is, std::vector<char> &, std::error_code& error) {
value_t index = -1;
const auto found_spelling = for_each::indexed_value<Spellings...>(
[&]<auto Index, auto Spelling>() {
for (const auto& c : Spelling) {
if (is.peek() != c) {
return false;
}
is.get();
}
index = Index;
return true;
}
);
if (not found_spelling) {
using transcoding_error::make_error_code;
using enum transcoding_error::codes;
error = make_error_code(WRONG_SPELLING);
}
return index;
}
inline static void write(std::ostream &os, const value_t &index, std::error_code& error) {
const auto found_spelling = for_each::indexed_value<Spellings...>(
[&]<auto Index, auto Spelling>() {
if (index == Index) {
os.write(Spelling.c_str(), Spelling.size());
return true;
}
return false;
}
);
if (not found_spelling) [[unlikely]] {
using transcoding_error::make_error_code;
using enum transcoding_error::codes;
error = make_error_code(UNKNOWN_SPELLING_INDEX);
}
}
};
template<auto Type, string_literal Name, char BeginChar, char EndChar>
struct string_literal_token : public token_base<decltype(Type), Type, Name, std::string_view> {
using base_t = token_base<decltype(Type), Type, Name, std::string_view>;
using typename base_t::value_t;
inline static bool begins_with(std::istream &is) {
return is.peek() == BeginChar;
}
inline static auto backslash_escape_chars = {
std::pair{ '\\', '\\' },
std::pair{ 'b', '\b' },
std::pair{ 'f', '\f' },
std::pair{ 'n', '\n' },
std::pair{ 'r', '\r' },
std::pair{ 't', '\t' },
std::pair{ 'v', '\v' },
std::pair{ '"', '"' },
std::pair{ '/', '/' }
};
inline static uint16_t parse_hex_short(std::istream& is, std::error_code& error) {
using transcoding_error::make_error_code;
using enum transcoding_error::codes;
uint16_t value = 0;
for (int i = 0; i < 4; i++) {
unsigned char c = is.get();
if ('0' <= c and c <= '9') {
c -= '0';
} else if ('a' <= c and c <= 'f') {
c -= ('a' - 10);
} else if ('A' <= c and c <= 'F') {
c -= ('A' - 10);
} else [[unlikely]] {
error = make_error_code(NONE_HEX_CHAR_IN_UNICODE_ESCAPE);
break;
}
value = (value << 4) | c;
}
return value;
}
inline static value_t read(std::istream &is, std::vector<char> &buffer, std::error_code& error) {
using transcoding_error::make_error_code;
using enum transcoding_error::codes;
char c;
const auto next = [&]() { c = is.get(); };
next(); // ignore BeginChar
while (true) {
next();
if (is.eof()) {
error = make_error_code(EOF_IN_TOKEN);
goto on_error;
}
if (c == '\\') [[unlikely]] {
next();
auto backslash_escape = false;
for (const auto& [ letter, replace ] : backslash_escape_chars) {
if (c == letter) {
c = replace;
backslash_escape = true;
break;
}
}
if (not backslash_escape) [[unlikely]] {
if (c == 'u') {
const auto raw_value = parse_hex_short(is, error);
if (error) goto on_error;
auto lsb = uint8_t(raw_value & 0xff);
auto msb = uint8_t(raw_value >> 8);
// encode to utf-8 multichar
if (raw_value < 0x80) {
buffer.push_back(char(lsb));
} else if (raw_value < 0x800) {
buffer.push_back(char(0xc0 | ((msb & 0x7) << 2) | (lsb >> 6)));
buffer.push_back(char(0x80 | (lsb & 0x3f)));
} else {
buffer.push_back(char(0xe0 | (msb >> 4)));
buffer.push_back(char(0x80 | ((msb & 0xf) << 2) | (lsb >> 6)));
buffer.push_back(char(0x80 | (lsb & 0x3f)));
}
continue;
} else {
error = make_error_code(UNKNOWN_ESCAPE_SEQUENCE);
goto on_error;
}
}
} else [[likely]] {
auto unescaped = false;
for (const auto& escape : {
'\b', '\f', '\n', '\r', '\t', '\v'
}) {
if (c == escape) {
unescaped = true;
break;
}
}
if (unescaped) [[unlikely]] {
error = make_error_code(UNESCAPED_CHARACTER);
goto on_error;
}
if (c == EndChar) [[unlikely]] {
break;
}
}
buffer.push_back(c);
}
return { buffer.data(), buffer.data() + buffer.size() };
on_error:
is.setstate(std::ios_base::failbit);
return { buffer.data(), buffer.data() };
}
inline static void write(std::ostream &os, const value_t &value, std::error_code& error) {
using transcoding_error::make_error_code;
using enum transcoding_error::codes;
os.put(BeginChar);
const auto length = static_cast<ssize_t>(value.length());
for (ssize_t i = 0; i < length; i++) {
auto c = value[i];
auto backslash_escape = false;
for (const auto& [ replace, letter ] : backslash_escape_chars) {
if (c == letter) {
c = replace;
backslash_escape = true;
break;
}
}
if (backslash_escape) {
os.put('\\');
os.put(c);
continue;
}
const auto first_bit = c & 0x80;
const auto third_bit = c & 0x20;
const auto fourth_bit = c & 0x10;
// check third and fourth prefix bit to distinguish encoding
const auto num_utf8_bytes = first_bit ? (third_bit ? (fourth_bit ? 4 : 3) : 2) : 1;
if ((i + num_utf8_bytes) > length) [[unlikely]] {
error = make_error_code(CUT_OF_UTF8_CHARACTER);
return;
}
uint32_t raw_value;
if (num_utf8_bytes == 1) {
raw_value = uint8_t(
value[i]
);
} else if (num_utf8_bytes == 2) {
raw_value = uint32_t(
((value[i] & 0x1f) << 6) | (value[i+1] & 0x3f)
);
} else if (num_utf8_bytes == 3) {
raw_value = uint32_t(
((value[i] & 0xf) << 12) | ((value[i+1] & 0x3f) << 6) | (value[i+2] & 0x3f)
);
} else if (num_utf8_bytes == 4) {
raw_value = uint32_t(
((value[i] & 0x7) << 18) | ((value[i+1] & 0x3f) << 12) | ((value[i+2] & 0x3f) << 6) | (value[i+3] & 0x3f)
);
}
if (
(0x0 <= raw_value and raw_value < 0x20 ) or
(0xd800 <= raw_value and raw_value < 0xe000)
) {
os << "\\u" << std::setw(4) << std::setfill('0') << std::hex << raw_value << std::dec;
} else {
os.write(&value[i], num_utf8_bytes);
}
// i is also incremented in loop expression
i += num_utf8_bytes - 1;
}
os.put(EndChar);
}
};
template<auto Type, string_literal Name>
struct number_literal_token : public token_base<decltype(Type), Type, Name, double> {
using base_t = token_base<decltype(Type), Type, Name, double>;
using typename base_t::value_t;
inline static bool begins_with(std::istream &is) {
const auto c = is.peek();
return std::isdigit(c) or c == '-' or c == '+';
}
inline static value_t read(std::istream &is, std::vector<char> &, std::error_code& error) {
value_t d;
is >> d;
return d;
}
inline static void write(std::ostream &os, const value_t &value, std::error_code& error) {
os << std::setprecision(std::numeric_limits<double>::max_digits10 - 1) << std::defaultfloat << value;
}
};
template<auto Type, string_literal Name>
struct end_token : public token_base<decltype(Type), Type, Name> {
using base_t = token_base<decltype(Type), Type, Name>;
using typename base_t::value_t;
inline static bool begins_with(std::istream &is) {
return is.eof();
}
value_t static read(std::istream &, std::vector<char> &, std::error_code& error) {
return {};
}
inline static void write(std::ostream &os, const value_t &, std::error_code& error) {
os.flush();
}
};
} // namespace token_internal
namespace tokens {
enum class type : unsigned char {
END,
LBRACE, RBRACE,
COLON, COMMA,
STRING, NUMBER, BOOLEAN,
LBRACKET, RBRACKET,
UNDEFINED,
};
using left_brace = token_internal::literal_token<type::LBRACE, "left-brace", literal_config::left_brace>;
using right_brace = token_internal::literal_token<type::RBRACE, "right-brace", literal_config::right_brace>;
using left_bracket = token_internal::literal_token<type::LBRACKET, "left-bracket", literal_config::left_bracket>;
using right_bracket = token_internal::literal_token<type::RBRACKET, "right-bracket", literal_config::right_bracket>;
using colon = token_internal::literal_token<type::COLON, "colon", literal_config::colon>;
using comma = token_internal::literal_token<type::COMMA, "comma", literal_config::comma>;
using null = token_internal::literal_token<type::UNDEFINED, "null", literal_config::null>;
using boolean = token_internal::multi_literal_token<type::BOOLEAN, "boolean", bool, literal_config::boolean_false, literal_config::boolean_true>;
using string = token_internal::string_literal_token<type::STRING, "string", literal_config::string_begin, literal_config::string_end>;
using number = token_internal::number_literal_token<type::NUMBER, "number">;
using end = token_internal::end_token<type::END, "end">;
} // namespace tokens
template<typename Types, token_concept<Types>... Tokens>
class token_instance {
public:
template<typename... Args>
ztu_ic token_instance(Args &&... args);
template<Types Type, typename... Args>
ztu_nic static decltype(auto) make(Args &&... args);
ztu_nic static std::string_view name_of(Types type);
template<Types Type, typename... Args>
ztu_ic void set(Args &&... args);
template<Types Type>
ztu_nic decltype(auto) get();
template<Types Type>
ztu_nic decltype(auto) get() const;
ztu_nic Types type() const;
private:
using enum_t = std::underlying_type_t<Types>;
inline constexpr static auto names = std::array{ Tokens::name()..., std::string_view("unknown") };
private:
using value_t = std::variant<typename Tokens::value_t...>;
value_t m_value;
};
template<typename Types, token_concept<Types>... Tokens>
template<typename... Args>
ztu_ic token_instance<Types, Tokens...>::token_instance(Args &&... args)
: m_value(std::forward<Args>(args)...) {}
template<typename Types, token_concept<Types>... Tokens>
template<Types Type, typename... Args>
ztu_nic decltype(auto) token_instance<Types, Tokens...>::make(Args &&... args) {
constexpr auto index = static_cast<size_t>(static_cast<enum_t>(Type));
return token_instance(std::in_place_index<index>, std::forward<Args>(args)...);
}
template<typename Types, token_concept<Types>... Tokens>
ztu_nic std::string_view token_instance<Types, Tokens...>::name_of(Types type) {
const auto index = static_cast<size_t>(static_cast<enum_t>(type));
return names[std::min(index, sizeof...(Tokens))];
}
template<typename Types, token_concept<Types>... Tokens>
template<Types Type, typename... Args>
ztu_ic void token_instance<Types, Tokens...>::set(Args &&... args) {
constexpr auto index = static_cast<size_t>(static_cast<enum_t>(Type));
m_value.template emplace<index>(std::forward<Args>(args)...);
}
template<typename Types, token_concept<Types>... Tokens>
template<Types Type>
ztu_nic decltype(auto) token_instance<Types, Tokens...>::get() {
constexpr auto index = static_cast<size_t>(static_cast<enum_t>(Type));
return std::get<index>(m_value);
}
template<typename Types, token_concept<Types>... Tokens>
template<Types Type>
ztu_nic decltype(auto) token_instance<Types, Tokens...>::get() const {
constexpr auto index = static_cast<size_t>(static_cast<enum_t>(Type));
return std::get<index>(m_value);
}
template<typename Types, token_concept<Types>... Tokens>
ztu_nic Types token_instance<Types, Tokens...>::type() const {
return static_cast<Types>(static_cast<enum_t>(m_value.index()));
}
using default_token_instance = token_instance<tokens::type,
tokens::end,
tokens::left_brace,
tokens::right_brace,
tokens::comma,
tokens::colon,
tokens::string,
tokens::number,
tokens::boolean,
tokens::left_bracket,
tokens::right_bracket,
tokens::null
>;
struct source_location {
size_t row, column;
inline friend std::ostream &operator<<(std::ostream &os, const source_location &location);
};
std::ostream &operator<<(std::ostream &os, const source_location &location) {
return os << '(' << location.row << ", " << location.column << ')';
}
template<typename Types, token_concept<Types>... Tokens>
class tokenizer {
private:
using token_instance_t = token_instance<Types, Tokens...>;
using this_t = tokenizer<Types, Tokens...>;
public:
ztu_ic tokenizer();
ztu_ic tokenizer(std::istream &is);
ztu_ic void set_is(std::istream &is);
ztu_ic this_t& operator>>(std::tuple<token_instance_t &, source_location &> dst);
ztu_ic void accept();
template<Types... Options>
ztu_nic ssize_t ignore_until();
private:
source_location m_location{ 1, 1 };
std::istream *m_is{ nullptr };
std::vector<char> m_buffer{};
};
template<typename Types, token_concept<Types>... Tokens>
ztu_ic tokenizer<Types, Tokens...>::tokenizer() = default;
template<typename Types, token_concept<Types>... Tokens>
ztu_ic tokenizer<Types, Tokens...>::tokenizer(std::istream &is) : m_is{ &is } {}
template<typename Types, token_concept<Types>... Tokens>
ztu_ic void tokenizer<Types, Tokens...>::set_is(std::istream &is) {
m_is = &is;
m_location = { 1, 1 };
}
template<typename Types, token_concept<Types>... Tokens>
ztu_ic tokenizer<Types, Tokens...>& tokenizer<Types, Tokens...>::operator>>(std::tuple<token_instance_t &, source_location &> dst) {
auto &[token, location] = dst;
while (not m_is->eof() and std::isspace(m_is->peek()))
accept();
// The guaranteed lifetime of the previous string token ends here
m_buffer.clear();
location = m_location;
const auto before_pos = m_is->tellg();
std::error_code token_error;
const auto found_token = for_each::type<Tokens...>([&]<class Token>() {
if (Token::begins_with(*m_is)) {
token.template set<Token::type()>(
Token::read(*m_is, m_buffer, token_error)
);
return true;
}
return false;
});
if (not found_token) {
throw std::runtime_error(
std::format(
"Unexpected character {} at position ({}, {})",
static_cast<char>(m_is->peek()),
m_location.row,
m_location.column
)
);
}
if (token_error) {
throw std::runtime_error(
std::format(
"Error while parsing token {} token starting at position ({}, {}): {}",
token_instance_t::name_of(token.type()),
m_location.row,
m_location.column,
token_error.message()
)
);
}
const auto after_pos = m_is->tellg();
if ((after_pos == -1 or m_is->fail()) and not (
m_is->eof() and (
token.type() == tokens::type::END or token.type() == tokens::type::NUMBER
)
)) {
throw std::runtime_error(
std::format(
"Error while parsing {} token starting at position ({}, {})",
token_instance_t::name_of(token.type()),
m_location.row,
m_location.column
)
);
}
// assuming there are no linebreaks within a token_concept
m_location.column += after_pos - before_pos;
return *this;
}
template<typename Types, token_concept<Types>... Tokens>
template<Types... Options>
ztu_nic ssize_t tokenizer<Types, Tokens...>::ignore_until() {
// This function only works if the first character of each literal is unique
// even across the rest of all other literals letters.
ssize_t index = -1;
while (true) {
auto found_token = false;
if (not std::isspace(m_is->peek())) {
found_token = json_internal::for_each::indexed_value<Options...>([&]<auto Index, auto Option>() {
return json_internal::for_each::type<Tokens...>([&]<typename Token>() {
if constexpr (Option == Token::type()) {
if (Token::begins_with(*m_is)) {
index = Index;
return true;
}
}
return false;
});
});
}
accept();
if (found_token) {
break;
}
}
return index;
}
template<typename Types, token_concept<Types>... Tokens>
ztu_ic void tokenizer<Types, Tokens...>::accept() {
++m_location.column;
if (m_is->get() == '\n') {
++m_location.row;
m_location.column = 1;
}
}
enum class detokenizer_instructions {
space, tab, indent, outdent, clear_indent, newline
};
struct detokenizer_format {
std::string_view space, tab, newline;
};
namespace detokenizer_formats {
constexpr detokenizer_format pretty_tab{
.space{ " " },
.tab{ "\t" },
.newline{ "\n" },
};
constexpr detokenizer_format pretty_space{
.space{ " " },
.tab{ " " },
.newline{ "\n" },
};
constexpr detokenizer_format minimal{
.space{ "" },
.tab{ "" },
.newline{ "" },
};
} // namespace detokenizer_formats
template<typename Types, token_concept<Types>... Tokens>
class detokenizer {
private:
using token_instance_t = token_instance<Types, Tokens...>;
using this_t = detokenizer<Types, Tokens...>;
public:
ztu_ic detokenizer(const detokenizer_format &fmt = detokenizer_formats::pretty_tab);
ztu_ic detokenizer(std::ostream &os, const detokenizer_format &fmt = detokenizer_formats::pretty_tab);
ztu_nic std::ostream*& os();
ztu_nic std::ostream*const& os() const;
ztu_nic detokenizer_format& format();
ztu_nic const detokenizer_format& format() const;
ztu_ic this_t& operator<<(const token_instance_t &token);
ztu_ic this_t& operator<<(const detokenizer_instructions &instruction);
private:
std::ostream *m_os{ nullptr };
detokenizer_format m_format;
int m_depth{ 0 };
};
template<typename Types, token_concept<Types>... Tokens>
ztu_ic detokenizer<Types, Tokens...>::detokenizer(const detokenizer_format &fmt)
: m_format{ fmt } {};
template<typename Types, token_concept<Types>... Tokens>
ztu_ic detokenizer<Types, Tokens...>::detokenizer(std::ostream &os, const detokenizer_format &fmt)
: m_os{ &os }, m_format{ fmt } {}
template<typename Types, token_concept<Types>... Tokens>
ztu_nic std::ostream*& detokenizer<Types, Tokens...>::os() {
return m_os;
}
template<typename Types, token_concept<Types>... Tokens>
ztu_nic std::ostream*const& detokenizer<Types, Tokens...>::os() const {
return m_os;
}
template<typename Types, token_concept<Types>... Tokens>
ztu_nic detokenizer_format& detokenizer<Types, Tokens...>::format() {
return m_format;
}
template<typename Types, token_concept<Types>... Tokens>
ztu_nic const detokenizer_format& detokenizer<Types, Tokens...>::format() const {
return m_format;
}
template<typename Types, token_concept<Types>... Tokens>
ztu_ic detokenizer<Types, Tokens...>::this_t& detokenizer<Types, Tokens...>::operator<<(const detokenizer_instructions &instruction) {
switch (instruction) {
using
enum detokenizer_instructions;
case space: {
(*m_os) << m_format.space;
break;
}
case tab: {
(*m_os) << m_format.tab;
break;
}
case indent: {
m_depth++;
break;
}
case outdent: {
if (m_depth > 0) {
m_depth--;
}
break;
}
case clear_indent: {
m_depth = 0;
break;
}
case newline: {
(*m_os) << m_format.newline;
for (int i = 0; i < m_depth; i++) {
(*m_os) << m_format.tab;
}
break;