-
Notifications
You must be signed in to change notification settings - Fork 113
/
peglib.h
4937 lines (4223 loc) · 154 KB
/
peglib.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
//
// peglib.h
//
// Copyright (c) 2022 Yuji Hirose. All rights reserved.
// MIT License
//
#pragma once
/*
* Configuration
*/
#ifndef CPPPEGLIB_HEURISTIC_ERROR_TOKEN_MAX_CHAR_COUNT
#define CPPPEGLIB_HEURISTIC_ERROR_TOKEN_MAX_CHAR_COUNT 32
#endif
#include <algorithm>
#include <any>
#include <cassert>
#include <cctype>
#if __has_include(<charconv>)
#include <charconv>
#endif
#include <cstring>
#include <functional>
#include <initializer_list>
#include <iostream>
#include <limits>
#include <map>
#include <memory>
#include <mutex>
#include <set>
#include <sstream>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#if !defined(__cplusplus) || __cplusplus < 201703L
#error "Requires complete C++17 support"
#endif
namespace peg {
/*-----------------------------------------------------------------------------
* scope_exit
*---------------------------------------------------------------------------*/
// This is based on
// "http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4189".
template <typename EF> struct scope_exit {
explicit scope_exit(EF &&f)
: exit_function(std::move(f)), execute_on_destruction{true} {}
scope_exit(scope_exit &&rhs)
: exit_function(std::move(rhs.exit_function)),
execute_on_destruction{rhs.execute_on_destruction} {
rhs.release();
}
~scope_exit() {
if (execute_on_destruction) { this->exit_function(); }
}
void release() { this->execute_on_destruction = false; }
private:
scope_exit(const scope_exit &) = delete;
void operator=(const scope_exit &) = delete;
scope_exit &operator=(scope_exit &&) = delete;
EF exit_function;
bool execute_on_destruction;
};
/*-----------------------------------------------------------------------------
* UTF8 functions
*---------------------------------------------------------------------------*/
inline size_t codepoint_length(const char *s8, size_t l) {
if (l) {
auto b = static_cast<uint8_t>(s8[0]);
if ((b & 0x80) == 0) {
return 1;
} else if ((b & 0xE0) == 0xC0 && l >= 2) {
return 2;
} else if ((b & 0xF0) == 0xE0 && l >= 3) {
return 3;
} else if ((b & 0xF8) == 0xF0 && l >= 4) {
return 4;
}
}
return 0;
}
inline size_t codepoint_count(const char *s8, size_t l) {
size_t count = 0;
for (size_t i = 0; i < l; i += codepoint_length(s8 + i, l - i)) {
count++;
}
return count;
}
inline size_t encode_codepoint(char32_t cp, char *buff) {
if (cp < 0x0080) {
buff[0] = static_cast<char>(cp & 0x7F);
return 1;
} else if (cp < 0x0800) {
buff[0] = static_cast<char>(0xC0 | ((cp >> 6) & 0x1F));
buff[1] = static_cast<char>(0x80 | (cp & 0x3F));
return 2;
} else if (cp < 0xD800) {
buff[0] = static_cast<char>(0xE0 | ((cp >> 12) & 0xF));
buff[1] = static_cast<char>(0x80 | ((cp >> 6) & 0x3F));
buff[2] = static_cast<char>(0x80 | (cp & 0x3F));
return 3;
} else if (cp < 0xE000) {
// D800 - DFFF is invalid...
return 0;
} else if (cp < 0x10000) {
buff[0] = static_cast<char>(0xE0 | ((cp >> 12) & 0xF));
buff[1] = static_cast<char>(0x80 | ((cp >> 6) & 0x3F));
buff[2] = static_cast<char>(0x80 | (cp & 0x3F));
return 3;
} else if (cp < 0x110000) {
buff[0] = static_cast<char>(0xF0 | ((cp >> 18) & 0x7));
buff[1] = static_cast<char>(0x80 | ((cp >> 12) & 0x3F));
buff[2] = static_cast<char>(0x80 | ((cp >> 6) & 0x3F));
buff[3] = static_cast<char>(0x80 | (cp & 0x3F));
return 4;
}
return 0;
}
inline std::string encode_codepoint(char32_t cp) {
char buff[4];
auto l = encode_codepoint(cp, buff);
return std::string(buff, l);
}
inline bool decode_codepoint(const char *s8, size_t l, size_t &bytes,
char32_t &cp) {
if (l) {
auto b = static_cast<uint8_t>(s8[0]);
if ((b & 0x80) == 0) {
bytes = 1;
cp = b;
return true;
} else if ((b & 0xE0) == 0xC0) {
if (l >= 2) {
bytes = 2;
cp = ((static_cast<char32_t>(s8[0] & 0x1F)) << 6) |
(static_cast<char32_t>(s8[1] & 0x3F));
return true;
}
} else if ((b & 0xF0) == 0xE0) {
if (l >= 3) {
bytes = 3;
cp = ((static_cast<char32_t>(s8[0] & 0x0F)) << 12) |
((static_cast<char32_t>(s8[1] & 0x3F)) << 6) |
(static_cast<char32_t>(s8[2] & 0x3F));
return true;
}
} else if ((b & 0xF8) == 0xF0) {
if (l >= 4) {
bytes = 4;
cp = ((static_cast<char32_t>(s8[0] & 0x07)) << 18) |
((static_cast<char32_t>(s8[1] & 0x3F)) << 12) |
((static_cast<char32_t>(s8[2] & 0x3F)) << 6) |
(static_cast<char32_t>(s8[3] & 0x3F));
return true;
}
}
}
return false;
}
inline size_t decode_codepoint(const char *s8, size_t l, char32_t &cp) {
size_t bytes;
if (decode_codepoint(s8, l, bytes, cp)) { return bytes; }
return 0;
}
inline char32_t decode_codepoint(const char *s8, size_t l) {
char32_t cp = 0;
decode_codepoint(s8, l, cp);
return cp;
}
inline std::u32string decode(const char *s8, size_t l) {
std::u32string out;
size_t i = 0;
while (i < l) {
auto beg = i++;
while (i < l && (s8[i] & 0xc0) == 0x80) {
i++;
}
out += decode_codepoint(&s8[beg], (i - beg));
}
return out;
}
template <typename T> const char *u8(const T *s) {
return reinterpret_cast<const char *>(s);
}
/*-----------------------------------------------------------------------------
* escape_characters
*---------------------------------------------------------------------------*/
inline std::string escape_characters(const char *s, size_t n) {
std::string str;
for (size_t i = 0; i < n; i++) {
auto c = s[i];
switch (c) {
case '\f': str += "\\f"; break;
case '\n': str += "\\n"; break;
case '\r': str += "\\r"; break;
case '\t': str += "\\t"; break;
case '\v': str += "\\v"; break;
default: str += c; break;
}
}
return str;
}
inline std::string escape_characters(std::string_view sv) {
return escape_characters(sv.data(), sv.size());
}
/*-----------------------------------------------------------------------------
* resolve_escape_sequence
*---------------------------------------------------------------------------*/
inline bool is_hex(char c, int &v) {
if ('0' <= c && c <= '9') {
v = c - '0';
return true;
} else if ('a' <= c && c <= 'f') {
v = c - 'a' + 10;
return true;
} else if ('A' <= c && c <= 'F') {
v = c - 'A' + 10;
return true;
}
return false;
}
inline bool is_digit(char c, int &v) {
if ('0' <= c && c <= '9') {
v = c - '0';
return true;
}
return false;
}
inline std::pair<int, size_t> parse_hex_number(const char *s, size_t n,
size_t i) {
int ret = 0;
int val;
while (i < n && is_hex(s[i], val)) {
ret = static_cast<int>(ret * 16 + val);
i++;
}
return std::pair(ret, i);
}
inline std::pair<int, size_t> parse_octal_number(const char *s, size_t n,
size_t i) {
int ret = 0;
int val;
while (i < n && is_digit(s[i], val)) {
ret = static_cast<int>(ret * 8 + val);
i++;
}
return std::pair(ret, i);
}
inline std::string resolve_escape_sequence(const char *s, size_t n) {
std::string r;
r.reserve(n);
size_t i = 0;
while (i < n) {
auto ch = s[i];
if (ch == '\\') {
i++;
if (i == n) { throw std::runtime_error("Invalid escape sequence..."); }
switch (s[i]) {
case 'f':
r += '\f';
i++;
break;
case 'n':
r += '\n';
i++;
break;
case 'r':
r += '\r';
i++;
break;
case 't':
r += '\t';
i++;
break;
case 'v':
r += '\v';
i++;
break;
case '\'':
r += '\'';
i++;
break;
case '"':
r += '"';
i++;
break;
case '[':
r += '[';
i++;
break;
case ']':
r += ']';
i++;
break;
case '\\':
r += '\\';
i++;
break;
case 'x':
case 'u': {
char32_t cp;
std::tie(cp, i) = parse_hex_number(s, n, i + 1);
r += encode_codepoint(cp);
break;
}
default: {
char32_t cp;
std::tie(cp, i) = parse_octal_number(s, n, i);
r += encode_codepoint(cp);
break;
}
}
} else {
r += ch;
i++;
}
}
return r;
}
/*-----------------------------------------------------------------------------
* token_to_number_ - This function should be removed eventually
*---------------------------------------------------------------------------*/
template <typename T> T token_to_number_(std::string_view sv) {
T n = 0;
#if __has_include(<charconv>)
if constexpr (!std::is_floating_point<T>::value) {
std::from_chars(sv.data(), sv.data() + sv.size(), n);
#else
if constexpr (false) {
#endif
} else {
auto s = std::string(sv);
std::istringstream ss(s);
ss >> n;
}
return n;
}
/*-----------------------------------------------------------------------------
* Trie
*---------------------------------------------------------------------------*/
class Trie {
public:
Trie(const std::vector<std::string> &items, bool ignore_case)
: ignore_case_(ignore_case) {
size_t id = 0;
for (const auto &item : items) {
const auto &s = ignore_case ? to_lower(item) : item;
for (size_t len = 1; len <= item.size(); len++) {
auto last = len == item.size();
std::string_view sv(s.data(), len);
auto it = dic_.find(sv);
if (it == dic_.end()) {
dic_.emplace(sv, Info{last, last, id});
} else if (last) {
it->second.match = true;
} else {
it->second.done = false;
}
}
id++;
}
}
size_t match(const char *text, size_t text_len, size_t &id) const {
std::string lower_text;
if (ignore_case_) {
lower_text = to_lower(text);
text = lower_text.data();
}
size_t match_len = 0;
auto done = false;
size_t len = 1;
while (!done && len <= text_len) {
std::string_view sv(text, len);
auto it = dic_.find(sv);
if (it == dic_.end()) {
done = true;
} else {
if (it->second.match) {
match_len = len;
id = it->second.id;
}
if (it->second.done) { done = true; }
}
len += 1;
}
return match_len;
}
size_t size() const { return dic_.size(); }
private:
std::string to_lower(std::string s) const {
for (char &c : s) {
c = std::tolower(c);
}
return s;
}
struct Info {
bool done;
bool match;
size_t id;
};
// TODO: Use unordered_map when heterogeneous lookup is supported in C++20
// std::unordered_map<std::string, Info> dic_;
std::map<std::string, Info, std::less<>> dic_;
bool ignore_case_;
};
/*-----------------------------------------------------------------------------
* PEG
*---------------------------------------------------------------------------*/
/*
* Line information utility function
*/
inline std::pair<size_t, size_t> line_info(const char *start, const char *cur) {
auto p = start;
auto col_ptr = p;
auto no = 1;
while (p < cur) {
if (*p == '\n') {
no++;
col_ptr = p + 1;
}
p++;
}
auto col = codepoint_count(col_ptr, p - col_ptr) + 1;
return std::pair(no, col);
}
/*
* String tag
*/
inline constexpr unsigned int str2tag_core(const char *s, size_t l,
unsigned int h) {
return (l == 0) ? h
: str2tag_core(s + 1, l - 1,
(h * 33) ^ static_cast<unsigned char>(*s));
}
inline constexpr unsigned int str2tag(std::string_view sv) {
return str2tag_core(sv.data(), sv.size(), 0);
}
namespace udl {
inline constexpr unsigned int operator"" _(const char *s, size_t l) {
return str2tag_core(s, l, 0);
}
} // namespace udl
/*
* Semantic values
*/
class Context;
struct SemanticValues : protected std::vector<std::any> {
SemanticValues() = default;
SemanticValues(Context *c) : c_(c) {}
// Input text
const char *path = nullptr;
const char *ss = nullptr;
// Matched string
std::string_view sv() const { return sv_; }
// Definition name
const std::string &name() const { return name_; }
std::vector<unsigned int> tags;
// Line number and column at which the matched string is
std::pair<size_t, size_t> line_info() const;
// Choice count
size_t choice_count() const { return choice_count_; }
// Choice number (0 based index)
size_t choice() const { return choice_; }
// Tokens
std::vector<std::string_view> tokens;
std::string_view token(size_t id = 0) const {
if (tokens.empty()) { return sv_; }
assert(id < tokens.size());
return tokens[id];
}
// Token conversion
std::string token_to_string(size_t id = 0) const {
return std::string(token(id));
}
template <typename T> T token_to_number() const {
return token_to_number_<T>(token());
}
// Transform the semantic value vector to another vector
template <typename T>
std::vector<T> transform(size_t beg = 0,
size_t end = static_cast<size_t>(-1)) const {
std::vector<T> r;
end = (std::min)(end, size());
for (size_t i = beg; i < end; i++) {
r.emplace_back(std::any_cast<T>((*this)[i]));
}
return r;
}
void append(SemanticValues &chvs) {
sv_ = chvs.sv_;
for (auto &v : chvs) {
emplace_back(std::move(v));
}
for (auto &tag : chvs.tags) {
tags.emplace_back(std::move(tag));
}
for (auto &tok : chvs.tokens) {
tokens.emplace_back(std::move(tok));
}
}
using std::vector<std::any>::iterator;
using std::vector<std::any>::const_iterator;
using std::vector<std::any>::size;
using std::vector<std::any>::empty;
using std::vector<std::any>::assign;
using std::vector<std::any>::begin;
using std::vector<std::any>::end;
using std::vector<std::any>::rbegin;
using std::vector<std::any>::rend;
using std::vector<std::any>::operator[];
using std::vector<std::any>::at;
using std::vector<std::any>::resize;
using std::vector<std::any>::front;
using std::vector<std::any>::back;
using std::vector<std::any>::push_back;
using std::vector<std::any>::pop_back;
using std::vector<std::any>::insert;
using std::vector<std::any>::erase;
using std::vector<std::any>::clear;
using std::vector<std::any>::swap;
using std::vector<std::any>::emplace;
using std::vector<std::any>::emplace_back;
private:
friend class Context;
friend class Dictionary;
friend class Sequence;
friend class PrioritizedChoice;
friend class Repetition;
friend class Holder;
friend class PrecedenceClimbing;
Context *c_ = nullptr;
std::string_view sv_;
size_t choice_count_ = 0;
size_t choice_ = 0;
std::string name_;
};
/*
* Semantic action
*/
template <typename F, typename... Args> std::any call(F fn, Args &&...args) {
using R = decltype(fn(std::forward<Args>(args)...));
if constexpr (std::is_void<R>::value) {
fn(std::forward<Args>(args)...);
return std::any();
} else if constexpr (std::is_same<typename std::remove_cv<R>::type,
std::any>::value) {
return fn(std::forward<Args>(args)...);
} else {
return std::any(fn(std::forward<Args>(args)...));
}
}
template <typename T>
struct argument_count : argument_count<decltype(&T::operator())> {};
template <typename R, typename... Args>
struct argument_count<R (*)(Args...)>
: std::integral_constant<unsigned, sizeof...(Args)> {};
template <typename R, typename C, typename... Args>
struct argument_count<R (C::*)(Args...)>
: std::integral_constant<unsigned, sizeof...(Args)> {};
template <typename R, typename C, typename... Args>
struct argument_count<R (C::*)(Args...) const>
: std::integral_constant<unsigned, sizeof...(Args)> {};
class Action {
public:
Action() = default;
Action(Action &&rhs) = default;
template <typename F> Action(F fn) : fn_(make_adaptor(fn)) {}
template <typename F> void operator=(F fn) { fn_ = make_adaptor(fn); }
Action &operator=(const Action &rhs) = default;
operator bool() const { return bool(fn_); }
std::any operator()(SemanticValues &vs, std::any &dt) const {
return fn_(vs, dt);
}
private:
using Fty = std::function<std::any(SemanticValues &vs, std::any &dt)>;
template <typename F> Fty make_adaptor(F fn) {
if constexpr (argument_count<F>::value == 1) {
return [fn](auto &vs, auto & /*dt*/) { return call(fn, vs); };
} else {
return [fn](auto &vs, auto &dt) { return call(fn, vs, dt); };
}
}
Fty fn_;
};
/*
* Parse result helper
*/
inline bool success(size_t len) { return len != static_cast<size_t>(-1); }
inline bool fail(size_t len) { return len == static_cast<size_t>(-1); }
/*
* Log
*/
using Log = std::function<void(size_t line, size_t col, const std::string &msg,
const std::string &rule)>;
/*
* ErrorInfo
*/
class Definition;
struct ErrorInfo {
const char *error_pos = nullptr;
std::vector<std::pair<const char *, const Definition *>> expected_tokens;
const char *message_pos = nullptr;
std::string message;
std::string label;
const char *last_output_pos = nullptr;
bool keep_previous_token = false;
void clear() {
error_pos = nullptr;
expected_tokens.clear();
message_pos = nullptr;
message.clear();
}
void add(const char *error_literal, const Definition *error_rule) {
for (const auto &[t, r] : expected_tokens) {
if (t == error_literal && r == error_rule) { return; }
}
expected_tokens.emplace_back(error_literal, error_rule);
}
void output_log(const Log &log, const char *s, size_t n);
private:
int cast_char(char c) const { return static_cast<unsigned char>(c); }
std::string heuristic_error_token(const char *s, size_t n,
const char *pos) const {
auto len = n - std::distance(s, pos);
if (len) {
size_t i = 0;
auto c = cast_char(pos[i++]);
if (!std::ispunct(c) && !std::isspace(c)) {
while (i < len && !std::ispunct(cast_char(pos[i])) &&
!std::isspace(cast_char(pos[i]))) {
i++;
}
}
size_t count = CPPPEGLIB_HEURISTIC_ERROR_TOKEN_MAX_CHAR_COUNT;
size_t j = 0;
while (count > 0 && j < i) {
j += codepoint_length(&pos[j], i - j);
count--;
}
return escape_characters(pos, j);
}
return std::string();
}
std::string replace_all(std::string str, const std::string &from,
const std::string &to) const {
size_t pos = 0;
while ((pos = str.find(from, pos)) != std::string::npos) {
str.replace(pos, from.length(), to);
pos += to.length();
}
return str;
}
};
/*
* Context
*/
class Ope;
using TracerEnter = std::function<void(
const Ope &name, const char *s, size_t n, const SemanticValues &vs,
const Context &c, const std::any &dt, std::any &trace_data)>;
using TracerLeave = std::function<void(
const Ope &ope, const char *s, size_t n, const SemanticValues &vs,
const Context &c, const std::any &dt, size_t, std::any &trace_data)>;
using TracerStartOrEnd = std::function<void(std::any &trace_data)>;
class Context {
public:
const char *path;
const char *s;
const size_t l;
ErrorInfo error_info;
bool recovered = false;
std::vector<std::shared_ptr<SemanticValues>> value_stack;
size_t value_stack_size = 0;
std::vector<Definition *> rule_stack;
std::vector<std::vector<std::shared_ptr<Ope>>> args_stack;
size_t in_token_boundary_count = 0;
std::shared_ptr<Ope> whitespaceOpe;
bool in_whitespace = false;
std::shared_ptr<Ope> wordOpe;
std::vector<std::map<std::string_view, std::string>> capture_scope_stack;
size_t capture_scope_stack_size = 0;
std::vector<bool> cut_stack;
const size_t def_count;
const bool enablePackratParsing;
std::vector<bool> cache_registered;
std::vector<bool> cache_success;
std::map<std::pair<size_t, size_t>, std::tuple<size_t, std::any>>
cache_values;
TracerEnter tracer_enter;
TracerLeave tracer_leave;
std::any trace_data;
const bool verbose_trace;
Log log;
Context(const char *path, const char *s, size_t l, size_t def_count,
std::shared_ptr<Ope> whitespaceOpe, std::shared_ptr<Ope> wordOpe,
bool enablePackratParsing, TracerEnter tracer_enter,
TracerLeave tracer_leave, std::any trace_data, bool verbose_trace,
Log log)
: path(path), s(s), l(l), whitespaceOpe(whitespaceOpe), wordOpe(wordOpe),
def_count(def_count), enablePackratParsing(enablePackratParsing),
cache_registered(enablePackratParsing ? def_count * (l + 1) : 0),
cache_success(enablePackratParsing ? def_count * (l + 1) : 0),
tracer_enter(tracer_enter), tracer_leave(tracer_leave),
trace_data(trace_data), verbose_trace(verbose_trace), log(log) {
push_args({});
push_capture_scope();
}
~Context() {
pop_capture_scope();
assert(!value_stack_size);
assert(!capture_scope_stack_size);
assert(cut_stack.empty());
}
Context(const Context &) = delete;
Context(Context &&) = delete;
Context operator=(const Context &) = delete;
template <typename T>
void packrat(const char *a_s, size_t def_id, size_t &len, std::any &val,
T fn) {
if (!enablePackratParsing) {
fn(val);
return;
}
auto col = a_s - s;
auto idx = def_count * static_cast<size_t>(col) + def_id;
if (cache_registered[idx]) {
if (cache_success[idx]) {
auto key = std::pair(col, def_id);
std::tie(len, val) = cache_values[key];
return;
} else {
len = static_cast<size_t>(-1);
return;
}
} else {
fn(val);
cache_registered[idx] = true;
cache_success[idx] = success(len);
if (success(len)) {
auto key = std::pair(col, def_id);
cache_values[key] = std::pair(len, val);
}
return;
}
}
SemanticValues &push() {
push_capture_scope();
return push_semantic_values_scope();
}
void pop() {
pop_capture_scope();
pop_semantic_values_scope();
}
// Semantic values
SemanticValues &push_semantic_values_scope() {
assert(value_stack_size <= value_stack.size());
if (value_stack_size == value_stack.size()) {
value_stack.emplace_back(std::make_shared<SemanticValues>(this));
} else {
auto &vs = *value_stack[value_stack_size];
if (!vs.empty()) {
vs.clear();
if (!vs.tags.empty()) { vs.tags.clear(); }
}
vs.sv_ = std::string_view();
vs.choice_count_ = 0;
vs.choice_ = 0;
if (!vs.tokens.empty()) { vs.tokens.clear(); }
}
auto &vs = *value_stack[value_stack_size++];
vs.path = path;
vs.ss = s;
return vs;
}
void pop_semantic_values_scope() { value_stack_size--; }
// Arguments
void push_args(std::vector<std::shared_ptr<Ope>> &&args) {
args_stack.emplace_back(args);
}
void pop_args() { args_stack.pop_back(); }
const std::vector<std::shared_ptr<Ope>> &top_args() const {
return args_stack[args_stack.size() - 1];
}
// Capture scope
void push_capture_scope() {
assert(capture_scope_stack_size <= capture_scope_stack.size());
if (capture_scope_stack_size == capture_scope_stack.size()) {
capture_scope_stack.emplace_back(
std::map<std::string_view, std::string>());
} else {
auto &cs = capture_scope_stack[capture_scope_stack_size];
if (!cs.empty()) { cs.clear(); }
}
capture_scope_stack_size++;
}
void pop_capture_scope() { capture_scope_stack_size--; }
void shift_capture_values() {
assert(capture_scope_stack_size >= 2);
auto curr = &capture_scope_stack[capture_scope_stack_size - 1];
auto prev = curr - 1;
for (const auto &[k, v] : *curr) {
(*prev)[k] = v;
}
}
// Error
void set_error_pos(const char *a_s, const char *literal = nullptr);
// Trace
void trace_enter(const Ope &ope, const char *a_s, size_t n,
const SemanticValues &vs, std::any &dt);
void trace_leave(const Ope &ope, const char *a_s, size_t n,
const SemanticValues &vs, std::any &dt, size_t len);
bool is_traceable(const Ope &ope) const;
// Line info
std::pair<size_t, size_t> line_info(const char *cur) const {
std::call_once(source_line_index_init_, [this]() {
for (size_t pos = 0; pos < l; pos++) {
if (s[pos] == '\n') { source_line_index.push_back(pos); }
}
source_line_index.push_back(l);
});
auto pos = static_cast<size_t>(std::distance(s, cur));
auto it = std::lower_bound(
source_line_index.begin(), source_line_index.end(), pos,
[](size_t element, size_t value) { return element < value; });
auto id = static_cast<size_t>(std::distance(source_line_index.begin(), it));
auto off = pos - (id == 0 ? 0 : source_line_index[id - 1] + 1);
return std::pair(id + 1, off + 1);
}
size_t next_trace_id = 0;
std::vector<size_t> trace_ids;
bool ignore_trace_state = false;
mutable std::once_flag source_line_index_init_;
mutable std::vector<size_t> source_line_index;
};
/*
* Parser operators
*/
class Ope {
public:
struct Visitor;
virtual ~Ope() = default;
size_t parse(const char *s, size_t n, SemanticValues &vs, Context &c,
std::any &dt) const;
virtual size_t parse_core(const char *s, size_t n, SemanticValues &vs,
Context &c, std::any &dt) const = 0;
virtual void accept(Visitor &v) = 0;
};
class Sequence : public Ope {
public:
template <typename... Args>
Sequence(const Args &...args)
: opes_{static_cast<std::shared_ptr<Ope>>(args)...} {}
Sequence(const std::vector<std::shared_ptr<Ope>> &opes) : opes_(opes) {}
Sequence(std::vector<std::shared_ptr<Ope>> &&opes) : opes_(opes) {}
size_t parse_core(const char *s, size_t n, SemanticValues &vs, Context &c,
std::any &dt) const override {
auto &chvs = c.push_semantic_values_scope();
auto se = scope_exit([&]() { c.pop_semantic_values_scope(); });
size_t i = 0;
for (const auto &ope : opes_) {