-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathxcp.cpp
5783 lines (5334 loc) · 236 KB
/
xcp.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
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
/// @file
/// @brief xcp - xxx c++ compiler.
/// It is a C++23 compiler written in C++20. [ISO/IEC14882:2024]
/// It is just for hobby and does not take care of performance.
/// @author Mura
/// @copyright (c) 2023-, Mura.
#include <source_location>
#include <string_view>
#include <unordered_map>
#include <unordered_set>
#include <algorithm>
#include <chrono>
#include <exception>
#include <filesystem>
#include <fstream>
#include <functional>
#include <iomanip>
#include <iostream>
#include <list>
#include <locale>
#include <mutex>
#include <numeric>
#include <optional>
#include <ranges>
#include <regex>
#include <set>
#include <sstream>
#include <stack>
#include <stdexcept>
#include <string>
#include <tuple>
#include <variant>
#include <vector>
namespace xxx {
using namespace std::string_literals;
using namespace std::string_view_literals;
using svmatch = std::match_results<std::string_view::const_iterator>;
class finalizer_t {
public:
template<typename T>
requires std::invocable<T>
explicit finalizer_t(T&& t) :
t_(std::move(t)) {}
~finalizer_t() {
if constexpr (noexcept(t_())) {
t_();
} else {
try {
t_();
} catch (...) {}
}
}
private:
std::function<void()> t_;
};
template<typename E = std::invalid_argument>
inline void check(bool result, std::string const& message = std::string{}, std::source_location const& sl = std::source_location::current()) {
if (! result) throw E{sl.function_name() + std::to_string(sl.line()) + message};
}
inline std::string escape(std::string_view const& s, std::string_view::size_type limit = std::string_view::npos) {
std::unordered_map<char, std::string_view> const escaped{
{'\r', "$r"sv},
{'\n', "$n"sv},
{'\t', "$t"sv},
{'\f', "$f"sv},
{'\v', "$v"sv},
{'\a', "$a"sv},
{'\b', "$b"sv},
{'\\', "$$"sv},
};
if (limit == std::string_view::npos) {
return std::accumulate(s.begin(), s.end(), std::ostringstream(), [&escaped](auto&& o, auto const& a) { if (escaped.contains(a)) { o << escaped.at(a); } else { o << a; } return std::move(o); }).str();
} else {
auto const str = s | std::views::take(std::min(limit, s.length()));
return std::accumulate(str.begin(), str.end(), std::ostringstream(), [&escaped](auto&& o, auto const& a) { if (escaped.contains(a)) { o << escaped.at(a); } else { o << a; } return std::move(o); }).str();
}
}
template<typename C, typename T>
requires std::ranges::range<C> && std::equality_comparable_with<std::ranges::range_value_t<C>, T>
inline bool contains(C& container, T const& value) {
return std::ranges::find(container, value) != container.end();
}
namespace uc {
inline std::string to_utf8(char32_t ch) {
std::string s;
if (ch < 0x80) {
s.push_back(static_cast<char>(ch));
} else if (ch < 0x800) {
s.push_back(static_cast<char>(0xC0 | (ch >> 6)));
s.push_back(static_cast<char>(0x80 | (ch & 0x3F)));
} else if (ch < 0x10000) {
s.push_back(static_cast<char>(0xE0 | (ch >> 12)));
s.push_back(static_cast<char>(0x80 | ((ch >> 6) & 0x3F)));
s.push_back(static_cast<char>(0x80 | (ch & 0x3F)));
} else if (ch < 0x110000) {
s.push_back(static_cast<char>(0xF0 | (ch >> 18)));
s.push_back(static_cast<char>(0x80 | ((ch >> 12) & 0x3F)));
s.push_back(static_cast<char>(0x80 | ((ch >> 6) & 0x3F)));
s.push_back(static_cast<char>(0x80 | (ch & 0x3F)));
}
return s;
}
constexpr inline bool validate_utf8(std::string_view const& sv) {
// [ISO/IEC 14882:2024] 5.2 Phases of translation [lex.phases]
// An implementation shall support input files that are a sequence of UTF-8 code units (UTF-8 files).
// {{-- snip --}}
// If an input file is determined to be a UTF-8 file,
// then it shall be a well-formed UTF-8 code unit sequence and it is decoded to produce a sequence of Unicode scalar values.
// A sequence of translation character set elements is then formed by mapping each Unicode scalar value to the corresponding translation character set element.
for (auto pos = sv.begin(); pos != sv.end(); ++pos) {
auto const c = static_cast<unsigned char>(*pos);
if (c < 0x80) {
// 0xxxxxxx
continue;
} else if (c < 0xC0) {
// 10xxxxxx
return false;
} else if (c < 0xE0) {
// 110xxxxx 10xxxxxx
if (++pos == sv.end() || (*pos & 0xC0) != 0x80) return false;
} else if (c < 0xF0) {
// 1110xxxx 10xxxxxx 10xxxxxx
if (++pos == sv.end() || (*pos & 0xC0) != 0x80) return false;
if (++pos == sv.end() || (*pos & 0xC0) != 0x80) return false;
} else if (c < 0xF8) {
// 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
if (++pos == sv.end() || (*pos & 0xC0) != 0x80) return false;
if (++pos == sv.end() || (*pos & 0xC0) != 0x80) return false;
if (++pos == sv.end() || (*pos & 0xC0) != 0x80) return false;
} else {
return false;
}
}
return true;
}
} // namespace uc
namespace impl {
inline std::string vector_to_string(std::vector<std::string>::const_iterator const& itr, std::vector<std::string>::const_iterator const& end, std::string const& lp = "{", std::string const& rp = "}", std::size_t limit = 255u) {
return lp + std::accumulate(itr, end, std::string{}, [limit](auto&& o, auto const& a) { if (!o.empty()){ o += ", "; } o += escape(a, limit); return std::move(o); }) + rp;
}
inline std::string vector_to_string(std::vector<std::string> const& strs, std::string const& lp = "{", std::string const& rp = "}", std::size_t limit = 255u) {
return vector_to_string(strs.cbegin(), strs.cend(), lp, rp, limit);
}
} // namespace impl
namespace log {
enum class level_t {
Verbose,
Trace,
Info,
Error,
Silent
};
static std::mutex mutex_s;
static level_t level_s = level_t::Silent;
namespace impl {
char const* Lv[]{"[*]", "[T]", "[I]", "[E]", "[S]"};
std::regex const function_name_re{R"(^(?:[^ ]+[ ])*((?:[`]?[A-Za-z_{][-A-Za-z_0-9<>'}]*::)*[~]?[A-Za-z_<][A-Za-z_0-9<>]*)[ ]?\(.*$)"};
inline std::tm local_tm(std::chrono::system_clock::time_point const& now) {
std::tm tm{};
auto const tt{std::chrono::system_clock::to_time_t(now)};
// ::localtime_s(&tm, &tt); for xxx_win32
// ::localtime_r(&tt, &tm); for xxx_posix
// NOTE: It is always called with lock of mutex currently.
tm = *std::localtime(&tt);
return tm;
}
inline std::string location(std::source_location const& sl) {
std::ostringstream oss;
oss << "[" << std::filesystem::path{sl.file_name()}.filename().string() << ":" << std::setfill('_') << std::setw(5) << sl.line() << ":" << std::setw(3) << sl.column() << "]";
std::string_view fn{sl.function_name()};
if (svmatch m; std::regex_match(fn.cbegin(), fn.cend(), m, function_name_re)) {
oss << m.str(1);
} else {
oss << sl.function_name();
}
oss << " ";
return oss.str();
}
inline std::string datetime(std::chrono::system_clock::time_point const& dt) {
std::ostringstream oss;
using namespace std::chrono_literals;
auto const lt = local_tm(dt);
auto const ms = std::chrono::duration_cast<std::chrono::microseconds>(dt.time_since_epoch()) % 1s;
oss << std::put_time(<, "%FT%T.") << std::setfill('0') << std::setw(6) << ms.count() << std::put_time(<, "%z");
return oss.str();
}
} // namespace impl
inline void log(level_t level, std::string_view const& message, std::source_location sl = std::source_location::current()) {
if (level < level_s) return;
if (static_cast<int>(level) < 0 || (sizeof impl::Lv / sizeof impl::Lv[0]) <= static_cast<unsigned>(level)) return;
std::lock_guard lock{mutex_s};
std::clog << impl::datetime(std::chrono::system_clock::now()) << impl::Lv[static_cast<unsigned>(level)] << impl::location(sl) << std::string{message} << std::endl;
}
inline void trace(std::string_view const& message, std::source_location sl = std::source_location::current()) { log(level_t::Trace, message, sl); }
inline void info(std::string_view const& message, std::source_location sl = std::source_location::current()) { log(level_t::Info, message, sl); }
inline void err(std::string_view const& message, std::source_location sl = std::source_location::current()) { log(level_t::Error, message, sl); }
class tracer_t {
public:
explicit tracer_t(std::vector<std::string> const& args, bool silent = false, std::source_location sl = std::source_location::current()) :
tracer_t(level_t::Trace, args, silent, sl) {}
tracer_t(level_t level, std::vector<std::string> const& args, bool silent = false, std::source_location sl = std::source_location::current()) :
level_{level}, sl_{sl}, result_{}, silent_{silent} {
if (! silent_ && level_s <= level_) log(level_, xxx::impl::vector_to_string(args, ">>>>(", ")"), sl_);
}
~tracer_t() {
if (! silent_ && level_s <= level_) log(level_, "<<<<(" + result_ + ") ", sl_);
}
template<typename T>
void trace(T const& v, bool force = false, std::source_location sl = std::source_location::current()) {
if (! force && (silent_ || level_ < level_s)) return;
if constexpr (std::is_integral_v<T>) {
log(level_, "----" + std::to_string(sl.line()) + "|" + std::to_string(v) + "|", sl_);
} else {
std::ostringstream oss;
oss << v;
log(level_, "----" + std::to_string(sl.line()) + "|" + oss.str() + "|", sl_);
}
}
template<typename T>
void set_result(T const& v) {
if constexpr (std::is_integral_v<T>) {
result_ = std::to_string(v);
} else {
std::ostringstream oss;
oss << v;
result_ = oss.str();
}
}
private:
level_t level_;
std::source_location sl_;
std::string result_;
bool silent_;
};
template<>
inline void tracer_t::set_result(std::string const& v) { result_ = v; }
template<>
inline void tracer_t::set_result(std::string_view const& v) { result_ = std::string{v}; }
template<>
inline void tracer_t::set_result(std::vector<std::string> const& v) { result_ = xxx::impl::vector_to_string(v, "", ""); }
template<>
inline void tracer_t::trace(std::string const& v, bool force, std::source_location sl) {
if (! force && (silent_ || level_ < level_s)) return;
log(level_, "----" + std::to_string(sl.line()) + "|" + v + "|", sl_);
}
template<>
inline void tracer_t::trace(std::string_view const& v, bool force, std::source_location sl) {
if (! force && (silent_ || level_ < level_s)) return;
log(level_, "----" + std::to_string(sl.line()) + "|" + std::string{v} + "|", sl_);
}
template<>
inline void tracer_t::trace(std::vector<std::string> const& v, bool force, std::source_location sl) {
if (! force && (silent_ || level_ < level_s)) return;
auto const vs = xxx::impl::vector_to_string(v, "", "");
log(level_, "----" + std::to_string(sl.line()) + "|" + vs + "|", sl_);
}
} // namespace log
namespace lex {
namespace def {
auto const include_s_ = "include"s;
auto const ifdef_s_ = "ifdef"s;
auto const ifndef_s_ = "ifndef"s;
auto const elif_s_ = "elif"s;
auto const elifdef_s_ = "elifdef"s;
auto const elifndef_s_ = "elifndef"s;
auto const endif_s_ = "endif"s;
auto const define_s_ = "define"s;
auto const defined_s_ = "defined"s;
auto const undef_s_ = "undef"s;
auto const line_s_ = "line"s;
auto const error_s_ = "error"s;
auto const warning_s_ = "warning"s;
auto const pragma_s_ = "pragma"s;
auto const Pragma_s_ = "_Pragma"s;
auto const and_s_ = "and"s;
auto const and_eq_s_ = "and_eq"s;
auto const or_s_ = "or"s;
auto const or_eq_s_ = "or_eq"s;
auto const xor_s_ = "xor"s;
auto const xor_eq_s_ = "xor_eq"s;
auto const not_s_ = "not"s;
auto const not_eq_s_ = "not_eq"s;
auto const compl_s_ = "compl"s;
auto const bitand_s_ = "bitand"s;
auto const bitor_s_ = "bitor"s;
auto const alignas_s_ = "alignas"s;
auto const alignof_s_ = "alignof"s;
auto const asm_s_ = "asm"s;
auto const auto_s_ = "auto"s;
auto const bool_s_ = "bool"s;
auto const break_s_ = "break"s;
auto const case_s_ = "case"s;
auto const catch_s_ = "catch"s;
auto const char_s_ = "char"s;
auto const char8_t_s_ = "char8_t"s;
auto const char16_t_s_ = "char16_t"s;
auto const char32_t_s_ = "char32_t"s;
auto const class_s_ = "class"s;
auto const concept_s_ = "concept"s;
auto const const_s_ = "const"s;
auto const consteval_s_ = "consteval"s;
auto const constexpr_s_ = "constexpr"s;
auto const constinit_s_ = "constinit"s;
auto const const_cast_s_ = "const_cast"s;
auto const co_await_s_ = "co_await"s;
auto const co_return_s_ = "co_return"s;
auto const co_yield_s_ = "co_yield"s;
auto const continue_s_ = "continue"s;
auto const decltype_s_ = "decltype"s;
auto const default_s_ = "default"s;
auto const delete_s_ = "delete"s;
auto const do_s_ = "do"s;
auto const double_s_ = "double"s;
auto const dynamic_cast_s_ = "dynamic_cast"s;
auto const else_s_ = "else"s;
auto const enum_s_ = "enum"s;
auto const explicit_s_ = "explicit"s;
auto const export_s_ = "export"s;
auto const extern_s_ = "extern"s;
auto const false_s_ = "false"s;
auto const float_s_ = "float"s;
auto const for_s_ = "for"s;
auto const friend_s_ = "friend"s;
auto const goto_s_ = "goto"s;
auto const if_s_ = "if"s;
auto const inline_s_ = "inline"s;
auto const int_s_ = "int"s;
auto const long_s_ = "long"s;
auto const mutable_s_ = "mutable"s;
auto const namespace_s_ = "namespace"s;
auto const new_s_ = "new"s;
auto const noexcept_s_ = "noexcept"s;
auto const nullptr_s_ = "nullptr"s;
auto const operator_s_ = "operator"s;
auto const private_s_ = "private"s;
auto const protected_s_ = "protected"s;
auto const public_s_ = "public"s;
auto const register_s_ = "register"s;
auto const reinterpret_cast_s_ = "reinterpret_cast"s;
auto const requires_s_ = "requires"s;
auto const return_s_ = "return"s;
auto const short_s_ = "short"s;
auto const signed_s_ = "signed"s;
auto const sizeof_s_ = "sizeof"s;
auto const static_s_ = "static"s;
auto const static_assert_s_ = "static_assert"s;
auto const static_cast_s_ = "static_cast"s;
auto const struct_s_ = "struct"s;
auto const switch_s_ = "switch"s;
auto const template_s_ = "template"s;
auto const this_s_ = "this"s;
auto const thread_local_s_ = "thread_local"s;
auto const throw_s_ = "throw"s;
auto const true_s_ = "true"s;
auto const try_s_ = "try"s;
auto const typedef_s_ = "typedef"s;
auto const typeid_s_ = "typeid"s;
auto const typename_s_ = "typename"s;
auto const union_s_ = "union"s;
auto const unsigned_s_ = "unsigned"s;
auto const using_s_ = "using"s;
auto const virtual_s_ = "virtual"s;
auto const void_s_ = "void"s;
auto const volatile_s_ = "volatile"s;
auto const wchar_t_s_ = "wchar_t"s;
auto const while_s_ = "while"s;
auto const override_s_ = "override"s;
auto const final_s_ = "final"s;
auto const bom_s_ = "\xEF\xBB\xBF"sv; // 0xFEFF
auto const VA_ARGS_s_ = "__VA_ARGS__"s;
auto const VA_OPT_s_ = "__VA_OPT__"s;
// literal list
std::unordered_set<std::string_view> const alternative_expressions{and_s_, and_eq_s_, bitand_s_, bitor_s_, compl_s_, not_s_, not_eq_s_, or_s_, or_eq_s_, xor_s_, xor_eq_s_};
std::unordered_set<std::string_view> const preprocessing_directives{
include_s_,
if_s_,
ifdef_s_,
ifndef_s_,
elif_s_,
elifdef_s_,
elifndef_s_,
else_s_,
endif_s_,
define_s_,
defined_s_, // is not directive exactly.
undef_s_,
line_s_,
error_s_,
warning_s_,
pragma_s_,
VA_ARGS_s_, // is not directive exactly.
VA_OPT_s_, // is not directive exactly.
};
std::unordered_set<std::string_view> const keywords{
alignas_s_,
alignof_s_,
asm_s_,
auto_s_,
bool_s_,
break_s_,
case_s_,
catch_s_,
char_s_,
char8_t_s_,
char16_t_s_,
char32_t_s_,
class_s_,
concept_s_,
const_s_,
consteval_s_,
constexpr_s_,
constinit_s_,
const_cast_s_,
continue_s_,
co_await_s_,
co_return_s_,
co_yield_s_,
decltype_s_,
default_s_,
delete_s_,
do_s_,
double_s_,
dynamic_cast_s_,
else_s_,
enum_s_,
explicit_s_,
export_s_,
extern_s_,
false_s_,
float_s_,
for_s_,
friend_s_,
goto_s_,
if_s_,
inline_s_,
int_s_,
long_s_,
mutable_s_,
namespace_s_,
new_s_,
noexcept_s_,
nullptr_s_,
operator_s_,
private_s_,
protected_s_,
public_s_,
register_s_,
reinterpret_cast_s_,
requires_s_,
return_s_,
short_s_,
signed_s_,
sizeof_s_,
static_s_,
static_assert_s_,
static_cast_s_,
struct_s_,
switch_s_,
template_s_,
this_s_,
thread_local_s_,
throw_s_,
true_s_,
try_s_,
typedef_s_,
typeid_s_,
typename_s_,
union_s_,
unsigned_s_,
using_s_,
virtual_s_,
void_s_,
volatile_s_,
wchar_t_s_,
while_s_,
};
} // namespace def
enum class pp_type_t {
Terminated,
Failure,
Identifier,
Number,
Raw_string,
String,
Character,
Keyword,
Block_comment,
Line_comment,
Whitespace,
Newline,
Header,
s_quote, // ' : single quote
d_quote, // " : double quote
pp_directive,
plus2, // ++ : increment
plus_eq, // += : add assignment
plus, // + : add / plus
minus2, // -- : decrement
minus_eq, // -= : subtract assignment
minus, // - : subtract / minus
arrow_star, // ->* : arrow & asterisk
arrow, // -> : arrow
star, // * : multiple / asterisk
star_eq, // *= : multiple assignment
spaceship, // <=> : spaceship
slash, // / : divide / slash
slash_eq, // /= : divide assignment
percent, // % : surplus / percent
percent_eq, // %= : surplus assignment
amp2, // && : logical and
amp_eq, // &= : bitwise and assignment
amp, // & : bitwise and
vert2, // || : logical or
vert_eq, // |= : bitwise or assignment
vert, // | : bitwise or
caret, // ^ : bitwise xor
caret_eq, // ^= : bitwise xor assignment
tilde, // ~ : bitwise not
exclaim, // ! : logical not
exclaim_eq, // != : not equal
eq, // = : equal
eq2, // == : equal
lt2, // << : shift left
lt_eq, // <= : less than or equal
lt, // < : less than
lt2_eq, // <<= : shift left assignment
gt2, // >> : shift right
gt_eq, // >= : greater than or equal
gt, // > : greater than
gt2_eq, // >>= : shift right assignment
question, // ? : conditional
colon, // : : colon
colon2, // :: : scope
semi, // ; : semicolon
comma, // , : comma
dot, // . : dot
dot_star, // .* : dot & asterisk
dot3, // ... : ellipsis
l_paren, // ( : left parenthesis
r_paren, // ) : right parenthesis
l_bracket, // [ : left bracket
r_bracket, // ] : right bracket
l_brace, // { : left brace
r_brace, // } : right brace
hash, // # : hash
hash2, // ## : hash & hash
dollar, // $ : dollar
};
namespace def {
// character set
std::string_view const basic_source_character_set{"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_{}[]#()<>%:;.?*+-/^&|~!=,\\\"’ \t\v\f\r\n"};
std::unordered_set<pp_type_t> const unary_op_set{lex::pp_type_t::plus, lex::pp_type_t::minus, lex::pp_type_t::tilde, lex::pp_type_t::star, lex::pp_type_t::amp, lex::pp_type_t::hash, lex::pp_type_t::plus2, lex::pp_type_t::minus2, lex::pp_type_t::exclaim};
std::unordered_set<pp_type_t> const binary_op_set{lex::pp_type_t::hash2, lex::pp_type_t::amp2, lex::pp_type_t::amp, lex::pp_type_t::vert2, lex::pp_type_t::vert, lex::pp_type_t::minus, lex::pp_type_t::plus, lex::pp_type_t::plus_eq, lex::pp_type_t::minus_eq, lex::pp_type_t::lt2_eq, lex::pp_type_t::gt2_eq, lex::pp_type_t::lt2, lex::pp_type_t::gt2, lex::pp_type_t::lt_eq, lex::pp_type_t::gt_eq, lex::pp_type_t::lt, lex::pp_type_t::gt, lex::pp_type_t::star_eq, lex::pp_type_t::slash_eq, lex::pp_type_t::percent_eq, lex::pp_type_t::caret_eq, lex::pp_type_t::amp_eq, lex::pp_type_t::vert_eq, lex::pp_type_t::exclaim_eq, lex::pp_type_t::eq2, lex::pp_type_t::star, lex::pp_type_t::slash, lex::pp_type_t::percent, lex::pp_type_t::caret, lex::pp_type_t::amp, lex::pp_type_t::eq};
std::unordered_set<pp_type_t> const trinary_op_set{lex::pp_type_t::question, lex::pp_type_t::colon};
std::unordered_set<pp_type_t> const operators{
pp_type_t::plus2,
pp_type_t::plus_eq,
pp_type_t::plus,
pp_type_t::minus2,
pp_type_t::minus_eq,
pp_type_t::minus,
pp_type_t::arrow_star,
pp_type_t::arrow,
pp_type_t::star,
pp_type_t::star_eq,
pp_type_t::spaceship,
pp_type_t::slash,
pp_type_t::slash_eq,
pp_type_t::percent,
pp_type_t::percent_eq,
pp_type_t::amp2,
pp_type_t::amp_eq,
pp_type_t::amp,
pp_type_t::vert2,
pp_type_t::vert_eq,
pp_type_t::vert,
pp_type_t::caret,
pp_type_t::caret_eq,
pp_type_t::tilde,
pp_type_t::exclaim,
pp_type_t::exclaim_eq,
pp_type_t::eq,
pp_type_t::eq2,
pp_type_t::lt2,
pp_type_t::lt_eq,
pp_type_t::lt,
pp_type_t::lt2_eq,
pp_type_t::gt2,
pp_type_t::gt_eq,
pp_type_t::gt,
pp_type_t::gt2_eq,
pp_type_t::question,
pp_type_t::colon,
pp_type_t::colon2,
pp_type_t::semi,
pp_type_t::comma,
pp_type_t::dot,
pp_type_t::dot_star,
pp_type_t::dot3,
pp_type_t::hash,
pp_type_t::hash2,
};
std::unordered_set<pp_type_t> const separators{
pp_type_t::l_paren,
pp_type_t::r_paren,
pp_type_t::l_bracket,
pp_type_t::r_bracket,
pp_type_t::l_brace,
pp_type_t::r_brace,
};
std::unordered_map<pp_type_t, std::string> const type_names{
{pp_type_t::Terminated, "Terminated"},
{pp_type_t::Failure, "Failure"},
{pp_type_t::Identifier, "Identifier"},
{pp_type_t::Number, "Number"},
{pp_type_t::Raw_string, "Raw_string"},
{pp_type_t::String, "String"},
{pp_type_t::Character, "Character"},
{pp_type_t::Keyword, "Keyword"},
{pp_type_t::Block_comment, "Block_comment"},
{pp_type_t::Line_comment, "Line_comment"},
{pp_type_t::Whitespace, "Whitespace"},
{pp_type_t::Newline, "Newline"},
{pp_type_t::Header, "Header"},
{pp_type_t::s_quote, "s_quote"},
{pp_type_t::d_quote, "d_quote"},
{pp_type_t::pp_directive, "pp_directive"},
{pp_type_t::plus2, "++"},
{pp_type_t::plus_eq, "+="},
{pp_type_t::plus, "+"},
{pp_type_t::minus2, "--"},
{pp_type_t::minus_eq, "-="},
{pp_type_t::minus, "-"},
{pp_type_t::arrow_star, "->*"},
{pp_type_t::arrow, "->"},
{pp_type_t::star, "*"},
{pp_type_t::star_eq, "*="},
{pp_type_t::spaceship, "<=>"},
{pp_type_t::slash, "/"},
{pp_type_t::slash_eq, "/="},
{pp_type_t::percent, "%"},
{pp_type_t::percent_eq, "%="},
{pp_type_t::amp2, "&&"},
{pp_type_t::amp_eq, "&="},
{pp_type_t::amp, "&"},
{pp_type_t::vert2, "||"},
{pp_type_t::vert_eq, "|="},
{pp_type_t::vert, "|"},
{pp_type_t::caret, "^"},
{pp_type_t::caret_eq, "^="},
{pp_type_t::tilde, "~"},
{pp_type_t::exclaim, "!"},
{pp_type_t::exclaim_eq, "!="},
{pp_type_t::eq, "="},
{pp_type_t::eq2, "=="},
{pp_type_t::lt2, "<<"},
{pp_type_t::lt_eq, "<="},
{pp_type_t::lt, "<"},
{pp_type_t::lt2_eq, "<<="},
{pp_type_t::gt2, ">>"},
{pp_type_t::gt_eq, ">="},
{pp_type_t::gt, ">"},
{pp_type_t::gt2_eq, ">>="},
{pp_type_t::question, "?"},
{pp_type_t::colon, ":"},
{pp_type_t::colon2, "::"},
{pp_type_t::semi, ";"},
{pp_type_t::comma, ","},
{pp_type_t::dot, "."},
{pp_type_t::dot_star, ".*"},
{pp_type_t::dot3, "..."},
{pp_type_t::l_paren, "("},
{pp_type_t::r_paren, ")"},
{pp_type_t::l_bracket, "["},
{pp_type_t::r_bracket, "]"},
{pp_type_t::l_brace, "{"},
{pp_type_t::r_brace, "}"},
{pp_type_t::hash, "#"},
{pp_type_t::hash2, "##"},
{pp_type_t::dollar, "$"},
};
} // namespace def
inline std::string to_string(pp_type_t t) {
using enum pp_type_t;
return "<{" + def::type_names.find(t)->second + "("s + std::to_string(static_cast<int>(t)) + ")}>"s;
}
inline std::ostream& operator<<(std::ostream& os, pp_type_t t) {
os << to_string(t);
return os;
}
class pos_t {
public:
auto line() const noexcept { return line_; }
auto column() const noexcept { return column_; }
auto file() const { return file_; }
void set_line(std::size_t value) noexcept { line_ = value; }
void set_column(std::size_t value) noexcept { column_ = value; }
void set_file(std::shared_ptr<std::filesystem::path const> const& value) { file_ = value; }
[[nodiscard]] pos_t moved(std::size_t length) const { return {line_, column_ + length, file_}; }
pos_t() :
line_{}, column_{}, file_{} {}
pos_t(std::size_t line, std::size_t column) :
line_{line}, column_{column}, file_{} {}
pos_t(std::size_t line, std::size_t column, std::shared_ptr<std::filesystem::path const> file) :
line_{line}, column_{column}, file_{file} {}
private:
std::size_t line_;
std::size_t column_;
std::shared_ptr<std::filesystem::path const> file_;
};
inline bool operator==(pos_t const& lhs, pos_t const& rhs) { return lhs.line() == rhs.line() && lhs.column() == rhs.column() && lhs.file() == rhs.file(); }
inline bool operator!=(pos_t const& lhs, pos_t const& rhs) { return ! (lhs == rhs); }
inline std::string to_string(pos_t const& pos) {
if (! pos.file()) { return "{no position}"; }
std::ostringstream oss;
oss << "[" << pos.file()->string() << "(l:" << std::to_string(pos.line()) << " c:" << std::to_string(pos.column()) << ")" << "]";
return oss.str();
}
class syntax_error_t : public std::runtime_error {
public:
auto const& pos() const noexcept { return pos_; }
syntax_error_t(pos_t const& pos, std::string const& message) :
std::runtime_error(message), pos_{pos} {}
private:
pos_t pos_;
};
template<typename I>
inline I skip_ws(I pos, I const& end) {
log::tracer_t tr{{}, true};
using enum pp_type_t;
for (; pos != end; ++pos) {
switch (pos->type()) {
// -------------------------------
// Terminates this line.
case Failure: [[fallthrough]];
case Terminated: [[fallthrough]];
case Newline: return end;
// -------------------------------
// Skips whitespaces.
case Block_comment: [[fallthrough]];
case Line_comment: [[fallthrough]];
case Whitespace: continue;
// -------------------------------
// Returns the next available token.
default: return pos;
}
}
return pos;
}
/// @brief Lexical token.
class pp_token_t {
public:
using hideset_t = std::unordered_set<pp_token_t>;
auto token() const noexcept { return token_; }
auto type() const noexcept { return type_; }
auto line() const noexcept { return pos_.line(); }
auto column() const noexcept { return pos_.column(); }
auto file() const noexcept { return pos_.file(); }
auto& hideset() noexcept { return hideset_; }
auto const& hideset() const noexcept { return hideset_; }
auto const& pos() const noexcept { return pos_; }
void pos(std::size_t line, std::shared_ptr<std::filesystem::path const> path = std::shared_ptr<std::filesystem::path const>{}) {
log::tracer_t tr{{std::to_string(line), path ? path->string() : "{none}"}, true};
pos_.set_line(line);
pos_.set_column(0u);
pos_.set_file(path);
}
bool is(pp_type_t type, std::string_view token) const noexcept { return type_ == type && token_ == token; }
bool is(pp_type_t type) const noexcept { return type_ == type; }
pp_token_t(pp_type_t type, std::string_view token) :
type_{type}, token_{token}, pos_{0, 0}, hideset_{} {}
pp_token_t(pp_type_t type, std::string_view token, pos_t const& pos) :
type_{type}, token_{token}, pos_{pos}, hideset_{} {
if (! file()) throw std::logic_error(__func__);
}
pp_token_t(pp_type_t type, std::string_view token, std::set<pp_token_t> const& hideset) :
type_{type}, token_{token}, pos_{0, 0}, hideset_{hideset} {}
pp_token_t(pp_type_t type, std::string_view token, std::set<pp_token_t> const& hideset, pos_t const& pos) :
type_{type}, token_{token}, pos_{pos}, hideset_{hideset} {
if (! file()) throw std::logic_error(__func__);
}
private:
pp_type_t type_;
std::string_view token_;
pos_t pos_;
std::set<pp_token_t> hideset_;
};
using tokens_t = std::vector<pp_token_t>;
using lines_t = std::vector<tokens_t>;
using tokens_itr_t = tokens_t::const_iterator;
using lines_itr_t = lines_t::const_iterator;
inline bool operator==(pp_token_t const& lhs, pp_token_t const& rhs) { return lhs.type() == rhs.type() && lhs.token() == rhs.token(); }
inline bool operator<(pp_token_t const& lhs, pp_token_t const& rhs) { return lhs.type() < rhs.type() || (lhs.token() < rhs.token()); }
inline std::string to_string(pp_token_t const& token) {
std::ostringstream oss;
oss << to_string(token.pos()) << token.type() << "(" << token.token().length() << ")=[" << xxx::escape(token.token()) << "]=";
return oss.str();
}
inline std::string to_token_string(pp_token_t const& token) {
using enum pp_type_t;
switch (token.type()) {
case Terminated: return "{EOF}";
case Failure: return "{Failure}";
case Header: return "{Header}";
case Identifier: [[fallthrough]];
case Raw_string: [[fallthrough]];
case String: [[fallthrough]];
case Number: [[fallthrough]];
case Character: [[fallthrough]];
case Keyword: [[fallthrough]];
case pp_directive: return std::string{token.token()};
case Block_comment: [[fallthrough]];
case Line_comment: [[fallthrough]];
case Whitespace: return " ";
case Newline: return "\n";
case s_quote: return "'";
case d_quote: return "\"";
case plus2: return "++";
case plus_eq: return "+=";
case plus: return "+";
case minus2: return "--";
case minus_eq: return "-=";
case minus: return "-";
case arrow_star: return "->*";
case arrow: return "->";
case star: return "*";
case star_eq: return "*=";
case spaceship: return "<=>";
case slash: return "/";
case slash_eq: return "/=";
case percent: return "%";
case percent_eq: return "%=";
case amp2: return "&&";
case amp_eq: return "&=";
case amp: return "&";
case vert2: return "||";
case vert_eq: return "|=";
case vert: return "|";
case caret: return "^";
case caret_eq: return "^=";
case tilde: return "~";
case exclaim: return "!";
case exclaim_eq: return "!=";
case eq: return "=";
case eq2: return "==";
case lt2: return "<<";
case lt_eq: return "<=";
case lt: return "<";
case lt2_eq: return "<<=";
case gt2: return ">>";
case gt_eq: return ">=";
case gt: return ">";
case gt2_eq: return ">>=";
case question: return "?";
case colon: return ":";
case colon2: return "::";
case semi: return ";";
case comma: return ",";
case dot: return ".";
case dot_star: return ".*";
case dot3: return "...";
case l_paren: return "(";
case r_paren: return ")";
case l_bracket: return "[";
case r_bracket: return "]";
case l_brace: return "{";
case r_brace: return "}";
case hash: return "#";
case hash2: return "##";
case dollar: return "$";
default: break;
};
throw std::logic_error(__func__);
}
inline std::string vector_to_string(tokens_t::const_iterator const& itr, tokens_t::const_iterator const& end, std::string const& lp = "{", std::string const& rp = "}", std::function<std::string(pp_token_t const&)> const& f = to_token_string, std::size_t limit = 255u) {
auto const strs = std::ranges::subrange(itr, end) | std::views::transform(f) | std::views::common;
return xxx::impl::vector_to_string({strs.begin(), strs.end()}, lp, rp, limit);
}
inline std::string vector_to_string(tokens_t const& tokens, std::string const& lp = "{", std::string const& rp = "}", std::function<std::string(pp_token_t const&)> const& f = to_token_string, std::size_t limit = 255u) {
auto const strs = tokens | std::views::transform(f) | std::views::common;
return xxx::impl::vector_to_string({strs.begin(), strs.end()}, lp, rp, limit);
}
inline tokens_itr_t next_token(tokens_itr_t pos, tokens_itr_t end) { return pos == end ? end : skip_ws(++pos, end); }
inline std::tuple<std::vector<tokens_itr_t>, tokens_itr_t> seq_match(tokens_itr_t itr, tokens_itr_t const& end, std::vector<std::function<bool(lex::pp_token_t const&)>> const& expected) {
log::tracer_t tr{{std::to_string(expected.size())}, true};
std::vector<tokens_itr_t> matched;
for (auto const& check: expected) {
if (itr == end) return {std::vector<tokens_itr_t>{}, itr};
itr = lex::skip_ws(itr, end);
if (itr == end) return {std::vector<tokens_itr_t>{}, itr};
if (! check(*itr)) return {std::vector<tokens_itr_t>{}, itr};
matched.push_back(itr);
++itr;
}
tr.set_result(std::to_string(matched.size()));
return {matched, itr};
}
class is_ {
public:
bool operator()(lex::pp_token_t const& a) const { return check(a); }