-
Notifications
You must be signed in to change notification settings - Fork 0
/
parser.hpp
1275 lines (1094 loc) · 47.1 KB
/
parser.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
#ifndef _PARSERTOY_HPP_
#define _PARSERTOY_HPP_
/*****************************************************************************
Programmable, extensible recursive descent parser for small/simple tasks
In a sense, this is just an inefficient reimplementation of some common
regex functionality -- using regexes... (And, for better or worse, it's
also like a sort of embryonic LISP... I only noticed that after it has
kinda become one all by itself, so not my fault! ;) )
(I'm not even sure it still qualifies as a rec. desc. parser... I don't
know much about parsing at all, as you may see.)
The main feature would be actually building an AST, and supporting user
hooks for matching constructs etc., I just haven't got 'round to it yet.
At least this is a "structured regex engine" (or "programmable regexes"
is also echoing in my mind); i.e. _regular_ regular expressions tend to
dislike structured text (while this thing can handle nested (recursive)
constructs in a more straightforward yet also more expressive manner).
Also, the regex syntax kinda sucks. It's like eating thistle, while
hugging a hedgehog. Consider this to be a blanket around regexes, and
also an exoskeleton, to not only proxy, but extend some of their abilities
(while admittedly limiting some others).
Another point is that with the extensible set of operators can implement
support for non-regular languages.
NOTE:
- It copies the source text, so that it can be kept a little more clean
& robust (e.g. for threading), instead of trying to be copyless (with
a brittle and ugly impl. using pointers, or offering a false sense of
security with a string_view). It's still a toy, not for huge texts...
- If you need to #include this in more than one translation units, then
#define PARSERTOY_DEDUP for all but the first one. (This way the most
common use case of only including it once can be kept the simplest.)
-----------------------------------------------------------------------------
TODO:
- WTF is wrong with the move semantics?! Rule's move-ctor is sometimes
not triggered, when I think it should be (i.e. moving them into the Prod
vector implicitly).
- multi-emplace _prod_append(...); -- and a similar ctor?? (possible?)
- Rule("") should create a *valid* empty rule, and and Rule(NIL) should
keep creating just an opcode!
(And then there could be a default ctor, too?... But I don't want to
encourage that. Everything works without it so far, and there's no clear
benefit to it.)
*****************************************************************************/
//!! Force-disable (the anyway useless) COPYLESS_GRAMMAR.
#ifdef COPYLESS_GRAMMAR
#warning COPYLESS_GRAMMAR is not properly implemented yet; disabled. (See #19!)
#undef COPYLESS_GRAMMAR
#endif
//=============================================================================
//---------------------------------------------------------------------------
// My ad-hoc "ground-levelling" base language layer...
//---------------------------------------------------------------------------
#include <cassert>
#include <exception>
#include <stdexcept>
#include <format>
using std::format;
//#include <print> //!! Sigh... 2023 Sep: still can't use this yet... Wow.
// using std::print;
#include <string>
using std::string;
using namespace std::literals::string_literals;
#ifndef NDEBUG
#include <iostream>
using std::cerr, std::cout, std::endl;
#endif
//!!
//!! My plain, undecorated toy macros conflict with the Windows headers (included by DocTest), and who knows what else...
//!!
#define CONST constexpr static auto
#define OUT
/*
#define IGNORE // To silence unused fn. arg warnings. Usage: IGNORE arg1, arg2;
// This macro can't just be [[maybe_unused]], unfortunately. :)
// MSVC is fine with just a var list, and so was GCC 12 -Wall, but v13
// started complaining about "left operand of comma operator has no effect".
*/
//! For variadic macros, e.g. for calling std::format(...):
//!
//! The old MSVC preproc. suppresses the extra ',' when no more args... But, it
//! doesn't understand __VA_OPT__, so the std. c++20 way of
//!
//! __VA_OPT__(,) __VA_ARGS__ approach can't be unified... Welcome to 2023!
//!
//! (GCC is OK with that, as is the new MCVC preproc, activated by /Zc:preprocessor)
#if defined(__GNUC__) \
|| defined(_MSC_VER) && (!defined(_MSVC_TRADITIONAL) || !_MSVC_TRADITIONAL)
# define _Sz_CONFORMANT_PREPROCESSOR 1
#elif defined(_MSC_VER) && defined(_MSVC_TRADITIONAL) && _MSVC_TRADITIONAL // Old MS prep.
# define _Sz_OLD_MSVC_PREPROCESSOR 1
#endif
#ifndef NDEBUG
//# //!! These empty preproc. lines would throw off GCC's error reporting line refs! :-o
# if defined(_Sz_CONFORMANT_PREPROCESSOR)
# define DBG(msg, ...) std::cerr << std::format("DBG> {}", std::format(msg __VA_OPT__(,) __VA_ARGS__)) << std::endl
// Same as DBG(), but with no trailing \n (for continuation lines)
# define DBG_(msg, ...) std::cerr << std::format("DBG> {}", std::format(msg __VA_OPT__(,) __VA_ARGS__))
// Continuation lines -- same as DBG(), but without the DBG prefix
# define _DBG(msg, ...) std::cerr << std::format(msg __VA_OPT__(,) __VA_ARGS__) << std::endl
// Line fragment -- neither DBG prefix, no trailing \n
# define _DBG_(msg, ...) std::cerr << std::format(msg __VA_OPT__(,) __VA_ARGS__)
# elif defined(_Sz_OLD_MSVC_PREPROCESSOR)
# define DBG(msg, ...) std::cerr << std::format("DBG> {}", std::format(msg, __VA_ARGS__)) << std::endl
# define DBG_(msg, ...) std::cerr << std::format("DBG> {}", std::format(msg, __VA_ARGS__))
# define _DBG(msg, ...) std::cerr << std::format(msg, __VA_ARGS__) << std::endl
# define _DBG_(msg, ...) std::cerr << std::format(msg, __VA_ARGS__)
# else
# error Unsupported compiler toolset (not MSVC or GCC/CLANG)!
# endif
# define DBG_DEFAULT_TRIM_LEN 30
// Trim length is ignored as yet, just using the default:
#define DBG_TRIM(str, ...) (std::string_view(str).length() > DBG_DEFAULT_TRIM_LEN - 3 ? \
(std::string(std::string_view(str).substr(0, DBG_DEFAULT_TRIM_LEN - 3))) + "..." : \
str)
//#
#else
# define DBG(msg, ...)
# define DBG_(msg, ...)
# define DBG_(msg, ...)
# define DBG_TRIM(str, ...) (str)
#endif
// Note: ERROR() below is _not_ a debug feature!
#if defined(_Sz_CONFORMANT_PREPROCESSOR)
# define ERROR(msg, ...) throw std::runtime_error(std::format("- ERROR: {}", std::format(msg __VA_OPT__(,) __VA_ARGS__)))
#elif defined(_Sz_OLD_MSVC_PREPROCESSOR)
# define ERROR(msg, ...) throw std::runtime_error(std::format("- ERROR: {}", std::format(msg, __VA_ARGS__)))
#else
# error Unsupported compiler toolset (not MSVC or GCC/CLANG)!
#endif
// Tame MSVC -Wall just a little
#ifdef _MSC_VER
# pragma warning(disable:5045) // Compiler will insert Spectre mitigation for memory load if /Qspectre switch specified
# pragma warning(disable:4514) // unreferenced inline function has been removed
# pragma warning(disable:4582) // constructor is not implicitly called
# pragma warning(disable:4583) // destructor is not implicitly called
// Too late here, though (use -wd4464 on the command-line):
# pragma warning(disable:4464) // relative include path contains '..'
#endif
//---------------------------------------------------------------------------
//=============================================================================
//---------------------------------------------------------------------------
#include <string_view>
using std::string_view;
#include <regex>
using namespace std::regex_constants; //!! refine (filter)
#include <functional> // function, reference_wrapper, ...
#include <utility> // move
//!!#include <variant> //!!Replace that horrid manual union in Rule! (#22)
#include <vector>
#include <unordered_map>
#include <map>
//---------------------------------------------------------------------------
namespace Parsing {
void init(); // Call this first, unless you start with a Parser() constructor!
CONST EMPTY_STRING = ""s;
using Atom = string; // direct literal or "terminal regex"
using REGEX = std::regex; //!! When changing it (e.g. to PCRE2), a light adapter class would be nice!
using STRING_MAP = std::unordered_map<string, string>;
using PATTERN_MAP = STRING_MAP;
//using PATTERN_MAP = std::unordered_map<string, REGEX>;
extern PATTERN_MAP NAMED_PATTERNS;
//!! Alas, no constexpr init for dynamic containers... :-/
//!! See init() and the Parser ctor!
//!! Must be initialized (sigh: later..., at least to {}) to avoid
//!! silent crashes, when creating rules before a Parser!
//-------------------------------------------------------------------
// Built-in meta-grammar operators (terminal rules)...
// Opcodes... (regex-inspired)
//
// Can be referred to either as Parser::_SOME_OP, or as the 'literal' names.
// Can be freely extended by users (in sync with the ::$OP map below).
using OPCODE = int;
CONST _NIL = OPCODE('0'); // never matches; ignores any subsequent items in the production
CONST _T = OPCODE('1'); // always matches; ignores any subsequent items in the production
CONST _ATOM = OPCODE('#'); // Fake opcode for matching atoms (which are not opeators; only defined for a cleaner Parser::match() impl.)
CONST _SEQ = OPCODE(',');
CONST _SEQ_IMPLIED = OPCODE(';'); // SEQ can be omitted; it will be implied for a list of rules that don't start with an opcode
// (This is to unify some processing: Prod. rules are /internally/ supposed to start with an opcode.)
CONST _OR = OPCODE('|'); // Expects 2 or more arguments
// - Note: adding _AND, too, would make little sense, I guess.
// Albeit... ->conjunctive grammars, or e.g.: https://stackoverflow.com/questions/2385762/how-do-i-include-a-boolean-and-within-a-regex
// (The key is "non-consuming" rules (like regex lookarounds) -- which is not yet supported by Rule directly.)
CONST _MANY = OPCODE('+'); // 1 or more (greedy!); expects 1 argument
CONST _ANY = OPCODE('*'); // 0 or more (greedy!); shortcut to [_OR [_MANY X] EMPTY]; expects 1 argument
// - Note: "greedy" above means that [A...]A will never match! Be careful!
CONST _OPT = OPCODE('?'); // 0 or 1; expects 1 argument
CONST _NOT = OPCODE('!'); // Expects 1 argument (Beware of using it with patterns!... ;) )
// Meta-operators
CONST _SAVE = OPCODE('('); // Save matched text to unnamed capture results
CONST _SAVE_AS = OPCODE('['); // Save matched text to named capture results
// - Its 1st arg must be an Atom (USER_LITERAL) for the name
CONST _DEF = OPCODE(':'); // Define a named rule (expects 2 arguments: "Name", {Rule}
// - To trigger Rule later, use _USE...
CONST _USE = OPCODE('`'); // Invoke named rule (expects 1 argument: "Name")
//!!?? CONST _SELF = OPCODE('@'); // Invoke the enclosing DEF-target rule, or NIL if none
//-------------------------------------------------------------------
// Operator functions...
struct Rule;
class Parser;
using CONST_OPERATOR = std::function<bool(Parser&, size_t src_pos, const Rule&, OUT size_t& matched_len)>;
//!! using OPERATOR = std::function<bool(Parser&, size_t src_pos, Rule&, OUT size_t& matched_len)>;
// Operator lookup table...
using CONSTOP_MAP = std::unordered_map<OPCODE, CONST_OPERATOR>;
//!! using OP_MAP = std::unordered_map<OPCODE, OPERATOR>;
extern CONSTOP_MAP CONST_OPERATORS;
//!! extern OP_MAP OPERATORS;
// These will be populated later, as e.g.:
// OPERATORS[SOME_OPCODE] = [](Parser&, input_pos, rule&) { ... return match-length or 0; }
// Can be freely extended by users (respecting the opcode list above).
void define(OPCODE opcode, CONST_OPERATOR op) {
CONST_OPERATORS[opcode] = op;
}
/*!!
void define(OPCODE opcode, OPERATOR op) { //!! This won't work: C++ still won't dispatch on c-v-different op types,
//!! *despite* refusing to accept them as interchangeable! :-/
void ddefine(OPCODE opcode, OPERATOR op) {
OPERATORS[opcode] = op;
}
!!*/
//---------------------------------------------------------------------------
// Grammar rules...
//---------------------------------------------------------------------------
struct Rule
// User Grammar (syntax) rule expression, as a recursive Rule tree
//
// A Rule can be:
// - an ATOM: string literal or regex pattern,
// - a PRODUCTION: an operator followed by 0 or more operands (all wrapped into a Production list (std::vector))
// - or, as a special case for internal use: an operator itself (i.e. an OPCODE), alone.
// (This is just so we can put an operator into the Production list, which can only hold Rule objects.)
//
// For the sake of simplifying/unifying processing, if an empty rule is being created,
// it'll be transformed into a production consisting of the NIL operator.
//!!TBD: THIS MIGHT CHANGE TO BE AN EMPTY LITERAL ATOM (""). There's already an "_EMPTY" pattern anyway.
// (However, a NIL rule actually bails out of the processing faster than matching an empty-string.)
//!!WOW: Just found this; it seems like this dilemma isn't just bothering me! :)
//!! https://stackoverflow.com/a/16620973/1479945
//!!
// !!TBD: Since every rule is boolean, it's also kinda a question whether an empty rule should be
// TRUE or FALSE... Hitting an empty rule could cancel the entire syntax, if NIL, rather than
// just being redundant, as one might expect it, and as is with an EMPTY atom!...
{
//!! Can't define this outside of Rule, sadly. But shipping with a `using Rule::Production` can help!
using Production = std::vector<Rule>;
enum {
OP,
PROD,
CURATED_REGEX, // built-in "atomic" regex pattern
CURATED_LITERAL, // built-in "atomic" literal
USER_REGEX,
USER_LITERAL,
// Disagnostics support (mostly for the C++ hackery)...
// See _copy(), _move(), _destruct()!
_MOVED_FROM_,
_DESTROYED_,
} type;
#ifndef NDEBUG
const char* _type_to_cstr(auto t) const {
switch (t) {
case OP: return "OP";
case PROD: return "PROD";
case CURATED_REGEX: return "CURATED_REGEX";
case CURATED_LITERAL: return "CURATED_LITERAL";
case USER_REGEX: return "USER_REGEX";
case USER_LITERAL: return "USER_LITERAL";
case _MOVED_FROM_: return "_MOVED_FROM_";
case _DESTROYED_: return "_DESTROYED_";
default:
return "!!BUG: MISSING NAME FOR Rule TYPE!!";
}
}
const char* _type_cstr() const { return _type_to_cstr(type); }
#endif
union { //!! variant<Atom, OPCODE, Production> val;
//!!Well, making it const didn't help with the mysterious double copy at "COPYLESS" creation!...
//!! -> TC "PROD: directly from Atom-Rule"
const Atom atom; //!! Should be extended later to support optional name + regex pairs! (See d_memo, currently!)
//!! Or, actually, better to have patterns as non-atomic types instead (finally)?
//!! Also: extend to support precompiled regexes!
OPCODE opcode;
// .prod is treated specially: use prod() for (always const) access!
// Since Rule is in a union, we'd have to copy it no matter what,
// because you can't have references in C++ unions. But using
// std::reference_wrapper, it could still work...
#ifdef COPYLESS_GRAMMAR
std::reference_wrapper<const Production> _prod;
#else
/*const*/ Production _prod; //! See the const_cast in _copy() etc. to support constness...
#endif
};
mutable string name; // Optional user-assigned symbolic name
mutable string d_memo; // Diagnostic note (e.g. NAMED_PATTERNS key, opcode)
//!!string d_as_str // (placeholder to) "uniform string representation" of a rule
//!! (could even evolve to sg. useful for #9)
//-----------------------------------------------------------
// Queries...
bool is_atom() const { return type == CURATED_REGEX || type == CURATED_LITERAL
|| type == USER_REGEX || type == USER_LITERAL; }
bool is_prod() const { return type == PROD && !prod().empty(); }
bool is_opcode() const { return type == OP; }
const Production& prod() const { assert(type == PROD);
#ifdef COPYLESS_GRAMMAR
return _prod.get();
#else
return _prod;
#endif
}
Production& prod() { assert(type == PROD);
#ifdef COPYLESS_GRAMMAR
return _prod.get();
#else
return _prod;
#endif
}
const Rule* lookup(const string& n) const {
if (name == n) return this;
if (is_prod()) for(auto& r : prod()) {
if (auto res = r.lookup(n); res) return res;
}
return nullptr;
}
//-----------------------------------------------------------
// C++ boilerplate...
//------------------------
// Construction...
Rule(const Atom& atom);
Rule(Atom&& atom);
Rule(const char* atom) : Rule(Atom(atom)) {} // C++ will do all things evil with autoconversions, but not this, so... added.
// Also, this should stop the bizarra "vector too long" range
// misinterpretation errors (with arrays of 2 items), too, as a bonus!
Rule(OPCODE opcode): type(OP), opcode(opcode) {
DBG("Rule::OPCODE-ctor creating [{}] as: {} ('{}')...", (void*)this, opcode, (char)opcode);
}
Rule(const Production& expr): type(PROD), _prod(expr) { //! Constructs _prod as ref_wrap(expr) in COPYLESS_GRAMMAR mode.
DBG("Rule::Prod-copy-ctor creating [{}] from [{}] as prod[0].type: {}...",
(void*)this, (void*)&expr, expr.empty() ? "<!!EMPTY!!>" : expr[0]._type_cstr());
assert(prod().size() == expr.size());
if (prod().size()) assert(expr[0].type == prod()[0].type);
//! See also the move-Prod ctor!
if (prod().empty()) {
_destruct(); // Clean up the empty Prod we've just created...
_init_as_nil();
}
//DBG("Rule::Prod-ctor creating [{}] done.", (void*)this);
}
#if 0 //!!CRASHES, ACTUALLY, SO DISABLED!
#if !defined (COPYLESS_GRAMMAR)
template<class... ArgsT>
void append(ArgsT&&... args)
{
int dummy[] [[maybe_unused]] = { 0, (_prod.emplace_back(std::forward<ArgsT>(args)), 0)... };
}
#endif
#endif
//------------------------
// Copy(-construction)...
Rule(const Rule& other): type(_DESTROYED_) {
DBG("Rule::copy-ctor creating [{}] from [{}] as type: {}...",
(void*)this, (void*)&other, other._type_cstr());
_copy(other); //! Works with COPYLESS_GRAMMAR transparently, because
//! it's a reference_wrapper, which can be rebound!
//DBG("Rule::copy-ctor creating [{}] from type: {} done.", (void*)this, (int)type);
}
// Handles COPYLESS_GRAMMAR transparently
Rule& operator=(const Rule& other) {
DBG("Rule assigmnet invoked... Could it be spared?");
assert(type != _DESTROYED_);
if (&other != this) {
_destruct();
_copy(other);
}
assert(type != _DESTROYED_);
return *this;
}
//------------------------
// Move...
#ifdef COPYLESS_GRAMMAR
// Refuse to take references of temporaries!
//!! Could be re-enabled, doing copy, with a "smart-destruct" flag
//!! to know that `*this` is now a copy that can be destructed, plus
//!! also keeping a whole "spare" value-type _prod ready for this case...
//!! IOW: GRAND PITA!...
Rule(Rule&& tmp) = delete;
Rule(Production&& expr) = delete;
Rule& operator=(Rule&& tmp) = delete;
#else
Rule(Rule&& tmp) noexcept : type(_DESTROYED_) {
DBG("Rule::move-ctor creating [{}] from: [{}]...", (void*)this, (void*)&tmp);
_move(std::move(tmp));
}
Rule(Production&& expr) noexcept : type(PROD), _prod(std::move(expr)) { //!!?? Why is move() still needed here?! :-o
DBG("Rule::Prod-move-ctor created [{}] from prod[0].type: {}...", (void*)this, prod().empty() ? "<!!EMPTY!!>" : prod()[0]._type_cstr());
//! See also the copy-Prod ctor!
if (prod().empty()) {
_destruct(); // Clean up the empty Prod we've just created...
_init_as_nil();
}
}
Rule& operator=(Rule&& tmp) noexcept {
DBG("Rule (move-)assigmnet invoked... Could it be spared?");
assert(type != _DESTROYED_);
assert (&tmp != this); //!!?? Why is move() still needed here?! :-o
_destruct();
_move(std::move(tmp));
assert(type != _DESTROYED_);
return *this;
}
#endif
//------------------------
// Destruction...
~Rule() {
DBG("~Rule destructing [{}] (type: {})...", (void*)this, _type_cstr());
_destruct();
}
private:
//-----------------------------------------------------------
// Construction/destruction/copy/move helpers...
void _init_as_nil() {
DBG("- Setting up empty rule...");
assert(type == _DESTROYED_); // Must be called from a ctor(-like context)
#ifdef COPYLESS_GRAMMAR
//! Hehh, GCC has a (bogus) warning even for #error (missing terminating '), so I can't write "can't" there... :-o :)
# error Sorry, empty COPYLESS_GRAMMAR cannot properly replace the entrails of an empty rule...
#else
new (const_cast<Production*>(&_prod)) Production(); //!! Call the ctor manually!... :-o
_prod.emplace_back(_NIL);
#endif
type = PROD;
d_memo = "<EMPTY>";
}
void _init_atom(auto&& s);
private:
void _destruct() {
//DBG("Rule::destruc (type: {})...", _type_cstr()); //DUMP();
assert (type != _DESTROYED_);
if (is_atom()) atom.~string();
#if !defined(COPYLESS_GRAMMAR)
else if (type == PROD) _prod.~Production(); //! Can't use is_prod() here: it's false if empty()!
#endif
type = _DESTROYED_;
//DBG("Rule::destruct (type: {}) done.", _type_cstr());
}
void _copy(const Rule& other) {
//DBG("Rule::_copy...");
//!! Assumes not being constructed already!
assert(type == _DESTROYED_);
assert(other.type != _DESTROYED_);
assert(other.type != _MOVED_FROM_);
type = other.type;
name = other.name;
d_memo = other.d_memo;
if (is_atom()) new (const_cast<Atom*>(&atom)) Atom(other.atom);
#ifdef COPYLESS_GRAMMAR
else if (type == PROD) new (&_prod) decltype(_prod)(other._prod); //! Copying ref_wrap will only bind other's!
#else
else if (type == PROD) new (const_cast<Production*>(&_prod)) Production(other.prod()); //! Can't use is_prod() here: it's false if empty()!
#endif
else opcode = other.opcode; // just a number...
DBG("Rule::_copy (type == {}) done.", _type_cstr());
}
void _move(Rule&& tmp) {
#ifdef COPYLESS_GRAMMAR
ERROR("BUG? Rule::_move called in COPYLESS_GRAMMAR mode!"); // See below...
#endif
//DBG("Rule::_move...");
//!! Assumes not being constructed already!
assert(type == _DESTROYED_);
assert(tmp.type != _DESTROYED_);
assert(tmp.type != _MOVED_FROM_);
type = tmp.type;
std::swap(name, tmp.name);
std::swap(d_memo, tmp.d_memo);
if (is_atom()) new (const_cast<Atom*>(&atom)) Atom(std::move(tmp.atom));
#ifdef COPYLESS_GRAMMAR
else if (type == PROD) new (&_prod) decltype(_prod)(std::move(tmp._prod)); //!!?? Will this do what I hope?
//!! I don't think so!...
#else
else if (type == PROD) new (const_cast<Production*>(&_prod)) Production(std::move(tmp._prod)); //! Can't use is_prod() here: it's false if empty()!
#endif
else opcode = std::move(tmp.opcode); // just a number...
tmp.type = _MOVED_FROM_;
DBG("Rule::_move (type == {}) done.", _type_cstr());
}
//-----------------------------------------------------------
// Diagnostics...
#ifndef NDEBUG
void _dump(unsigned level = 0) const {
/*!!
template <typename ... Types> auto f(Types&& ... args) {
f(x, std::forward<Types>(args)...);
}
template <typename ... Types> auto f(Types&& ... args) {
return [... args = std::forward<Types>(args)] {
// use args
};
}
auto s = [&](auto x, auto... args) { string prefix(level * 2, ' ');
return format(" {}{}", prefix, x); //!! Ignores all the opt. args yet! :-/
};
auto p_ = [&](auto x, auto... args) { cerr << s(x, ...args);
};
auto p = [&](auto x, auto... args) { p_(x, ...args); };
!!*/
//!! No multiple args & forwarding yet! :-/
auto p [[maybe_unused]] = [&](auto x, auto... args) { string prefix(level * 2, ' ');
cerr << " " << prefix << x << endl; };
auto p_ [[maybe_unused]] = [&](auto x, auto... args) { string prefix(level * 2, ' ');
cerr << " " << prefix << x; };
auto _p_ [[maybe_unused]] = [&](auto x, auto... args) {cerr << x; };
auto _p [[maybe_unused]] = [&](auto x, auto... args) {cerr << x << endl; };
if (!level) p("/------------------------------------------------------------------\\");
if (name.empty()) p_(format("[{}] {} (type #{}):", (void*)this, _type_cstr(), (int)type));
else p_(format("[{}] {} (type #{}) '{}':", (void*)this, _type_cstr(), (int)type, name));
if (type == _DESTROYED_) p(" !!! INVALID (DESTROYED) OBJECT !!!");
if (type == _MOVED_FROM_) p(" !!! INVALID (MOVED-FROM) OBJECT !!!");
if (is_atom()) { _p_(format(" \"{}\"", atom));
} else if (type == PROD) { //! Can't use is_prod() here: it's false if empty()!
_p(""); p("{"); // New line for the {
for (auto& r : prod()) { r._dump(level + 1); }
p_("}");
} else if (type == OP) { _p_(format(" opcode = {} ('{}')", opcode, char(opcode)));
} else if (type == _DESTROYED_) { p("!!! _DESTROYED_ !!!");
} else p("*** UNKNOWN/INVALID Rule TYPE! ***");
_p(d_memo.empty() ? "" : format(" // {} ", d_memo));
if (!level) p("\\------------------------------------------------------------------/\n");
}
public: void DUMP() const { _dump(); }
#else
public: void DUMP() const {}
#endif
};
//---------------------------------------------------------------------------
class Parser
//---------------------------------------------------------------------------
{
public:
//-------------------------------------------------------------------
// Parser state...
// Input:
#ifdef COPYLESS_GRAMMAR
const Rule& syntax;
#else
const Rule syntax;
#endif
string text;
size_t text_length;
// Results of capture ops.; valid only after a successful parse():
STRING_MAP named_captures; //!! My initial guess is that SSO makes it pretty much useless to keep string_views here.
std::map<size_t, /*!!const!!*/ string> unnamed_captures; // Ordered map! Now we only have to make sure that its order kinda makes sense! :)
// Diagnostics:
int loopguard;
int depth_reached;
int rules_tried;
int terminals_tried;
CONST RECURSION_LIMIT = 300; // Hopefully this'd be hit before a stack overflow... (500 was too high for me)
void _reset_counters()
{
loopguard = RECURSION_LIMIT;
depth_reached = RECURSION_LIMIT;
rules_tried = 0;
terminals_tried = 0;
}
void _reset_results()
{
_reset_counters();
named_captures = {};
unnamed_captures = {};
}
// Must be called before (i.e. by) each parse()!
void _reset()
{
_reset_results();
}
void _set_text(const string& txt)
{
_reset(); // First this, to ensure `captures` or any other saved results (like
// error messages etc.) can never refer to removed text, esp. if
// they store string_views or positions etc. instead of copies!
text = txt;
text_length = txt.length();
}
//-------------------------------------------------------------------
Parser(const Rule& syntax, int maxnest = RECURSION_LIMIT):
// Sync with _reset*()!
syntax(syntax),
loopguard(maxnest),
depth_reached(maxnest),
rules_tried(0),
terminals_tried(0)
{
Parsing::init(); //!! Legacy init-once location -- but makes no sense here; now done in Rule()!
}
Parser(const Parser& other) = delete;
Parser& operator=(const Parser& other) = delete;
Parser(Parser&&) = delete;
//-------------------------------------------------------------------
// Convenience front-ends to match(...)
bool parse(const string& txt)
{
_set_text(txt);
size_t matched_length_ignored;
return match(0, syntax, matched_length_ignored);
}
bool parse(const string& txt, OUT size_t& matched_length)
{
_set_text(txt);
return match(0, syntax, matched_length);
}
//!!bool run(/*runtime_context { const string& input, OUT string output}*/)
bool run() { return parse(""); }
//!! Move these to a `results` (or directly to `captures` or `saves`) objects
//!! instead, for more (versatile) queries like unnamed_captures() or saves.count()
//!! etc. to begin with!
const string& operator[](const string& name) const;
const string& operator[](size_t index_of_unnamed) const;
//-------------------------------------------------------------------
bool match(size_t pos, const Rule& rule, OUT size_t& len)
// pos is the source position
// rule is a syntax rule (tree node)
// If matches, returns the length of the matched input, otherwise 0.
//-------------------------------------------------------------------
{
DBG("match({}, {} [{}]: '{}')... // loopguard: {}", pos,
rule._type_cstr(), (void*)&rule,
rule.type == Rule::USER_LITERAL ? rule.atom :
rule.is_opcode() ? string(1, (char)rule.opcode) : "",
loopguard);
--loopguard;
if (depth_reached > loopguard)
depth_reached = loopguard;
if (!loopguard) {
ERROR("Recursion level {} is too deep (in match())!", RECURSION_LIMIT);
}
CONST_OPERATOR f;
//++rules_tried; //!! #_of_tried_matches, FFS
if (rule.is_atom()) // "curated regex", literal (or user regex, if still supported...)
{
assert(!CONST_OPERATORS.empty());
assert(CONST_OPERATORS.find(_ATOM) != CONST_OPERATORS.end());
f = CONST_OPERATORS[_ATOM];
//!! Should be dispatched further across the various atom types, instead:
//!!f = atom_handler(rule);
}
else if (rule.is_prod())
{
f = prod_handler(rule); // First item is the op. of the rule, or else _SEQ is implied:
// Throws via ERROR() if not found!
}
else if (rule.is_opcode()) //!! But _SELF and other nullaries!... :-/ -> #26
{
ERROR("Invalid grammar at rule {}: OPCODE '{}' outside of Production", (void*)&rule, rule.opcode);
}
else
{
ERROR("Invalid grammar at rule {}: '{}'", (void*)&rule, rule.d_memo);
}
#ifdef NDEBUG
len = 0; //! This doesn't help (it's even bad, for false sense of sec., and
//! easily masking bugs with that benign-looking 0 in the output),
//! as 0 is a valid output, which should still be ignored -- as any
//! others! -- if match() returned false!
//! OK, disabling it in debug builds for better diagnostics, but
//! enabling in release mode for some cushioning!...
#else
len = (unsigned)-666; // And indeed, this *did* crash! :) (e.g. #29)
#endif
auto res = f(*this, pos, rule, len); //! Remember: `len` is OUT!
++loopguard;
return res;
}
private:
const CONST_OPERATOR& prod_handler(const Rule& rule) const
{
//DBG("CONST_OPERATORS in prod_handler: {}", (void*)&CONST_OPERATORS); // Remnant from hunting as accidental shadow copies of it...
//DBG("CONST_OPERATORS.size in prod_handler: {}", CONST_OPERATORS.size());
assert(!CONST_OPERATORS.empty());
assert(rule.type == Rule::PROD); //! Shouldn't be asking any other types (not even an opcode-type Rule object directly)
assert(!rule.prod().empty());
OPCODE opcode;
// First item of a "compound" Rule is the op., or else _SEQ is implied.
if (!rule.prod()[0].is_opcode()) { // Not an opcode, imply a sequence
opcode = _SEQ_IMPLIED; //!! Will expect a headless rule!
//!!OPTIM: Shouldn't even be a lookup, just return the handler directly!
} else {
opcode = rule.prod()[0].opcode;
}
if (auto it = CONST_OPERATORS.find(opcode); it != CONST_OPERATORS.end()) {
decltype(CONST_OPERATORS.cbegin()) cit = it; //!!?? better one-liner for iter -> const-iter?
return cit->second;
} else {
ERROR("Unimplemented opcode: {} ('{}')", opcode, (char)opcode);
}
}
};
//===========================================================================
inline Rule::Rule(const Atom& s) {
DBG("Rule::Atom-copy-ctor creating [{}] from \"{}\"...", (void*)this, s);
_init_atom(s);
}
inline Rule::Rule(Atom&& s) {
DBG("Rule::Atom-move-ctor creating [{}] from \"{}\"...", (void*)this, s);
_init_atom(s);
}
inline void Rule::_init_atom(auto&& s)
// A `string` arg. can mean:
// a) symbol: the name of a curated item (either regex or literal)
// b) direct ("user") string literal
// c) direct ("user") regex
// For efficiency, the actual type (`type`) and it's "actual value" (e.g. the
// regex of a named pattern) is resolved and recorded (cached) here.
{
DBG("Rule::_init_atom from: \"{}\"...", s);
// Sneak in the once-only implicit init here...
Parsing::init();
type = _DESTROYED_; // Let's not burden the calling *empty* ctors with this...
// ...But in case I may still move it there, and add some other ctors,
// but forget to add it to those, here's this assert, too:
assert(type == _DESTROYED_);
if (s.empty()) { _init_as_nil(); return; }
auto set_type_and_adjust_regex = [&](string_view pattern, decltype(type) TYPE_if_literal,
decltype(type) TYPE_if_regex) {
// If "/.../" then it's a regex, so unwrap & mark it as such:
if (pattern.length() >= 2 && pattern[0] == '/' && pattern[pattern.length()-1] == '/')
{
type = TYPE_if_regex;
pattern = pattern.substr(1, pattern.length() - 2);
}
else type = TYPE_if_literal;
return pattern;
};
if (auto it = NAMED_PATTERNS.find(s); it != NAMED_PATTERNS.end())
{
auto pattern = set_type_and_adjust_regex(it->second, CURATED_LITERAL, CURATED_REGEX);
new (const_cast<Atom*>(&atom)) Atom(pattern); // Replace the atom name with the actual pattern (that's what that lame `second` is)
d_memo = s; // Save the pattern name for diagnostics
DBG("Rule initialized as named pattern '{}' ('{}') (type: {})", d_memo, atom, _type_cstr());
} else {
auto pattern = set_type_and_adjust_regex(s, USER_LITERAL, USER_REGEX);
new (const_cast<Atom*>(&atom)) Atom(pattern);
DBG("Rule initialized as string literal '{}' (type: {}).", atom, _type_cstr());
}
if (type == CURATED_REGEX || type == USER_REGEX) {
//!! atom = ...; // compile it!
}
assert(is_atom());
// Let's just also check if it's still doing what it was paid for... ;)
assert(type == CURATED_REGEX || type == CURATED_LITERAL
|| type == USER_REGEX || type == USER_LITERAL);
}
/*!!
CONST_OPERATOR Rule::op(OPCODE code) const
{
assert(type == PROD); //! Never asking the opcode directly! :)
auto it = CONST_OPERATORS.find(code);
return it != CONST_OPERATORS.end() ? *it : false; //!!?? CONST_OPERATORS[NIL] // -- but that can't be (!op)'ed... :-/
}
!!*/
// Simple painkillers for grammar-building:
using Prod = Rule::Production;
using _ = Rule::Production; // Even this! ;) For init. lists like Rule r = _{ ... _{...} }
// But this isn't OK for declaring Prod vars, so keeping both.
} // namespace
//
//--------------------------------------------<< C U T H E R E ! >>--------------------------------------------
//
#ifndef PARSERTOY_DEDUP
//===========================================================================
namespace Parsing {
PATTERN_MAP NAMED_PATTERNS = {};
CONSTOP_MAP CONST_OPERATORS = {};
//!! OP_MAP OPERATORS = {};
void init()
{
static auto initialized = false;
if (initialized) return;
//-------------------------------------------------------------------
// Initialize the predefined "atomic" patterns
//-------------------------------------------------------------------
// "Curated atoms" (named terminal pattens) are "metasyntactic sugar" only,
// as they could as well be just literal patterns. But fancy random regex
// literals could confuse the parsing, so these "officially" nicely behaving
// ones are just named & groomed here.
// (BTW, a user pattern that's not anchored to the left is guaranteed to
// fail, as the relevant regex_search() call doesn't anchor it itself!)
//
#define PATTERN(name, rx) {name, "/^" rx "/"} // ".*" added to allow using std::regex_match for left-anchored partial matching!
//#define PATTERN(name, rx) {name, REGEX(rx, std::regex::extended)}
assert(NAMED_PATTERNS.empty());
NAMED_PATTERNS = { //!! Alas, no constexpr init for dynamic containers; have to do it here...
PATTERN( "_EMPTY" , "" ),
PATTERN( "_SPACE" , " " ), // No \s, and [\s] didn't match ' ' in POSIX2 "extended") for some reason! :-o
PATTERN( "_TAB" , "\t" ), // No \t or [\t] (at least in POSIX2 "extended"?)
PATTERN( "_QUOTE" , "\"" ), // Not a special char
PATTERN( "_APOSTROPHE" , "'" ),
PATTERN( "_SLASH" , "/" ),
PATTERN( "_BACKSLASH" , "\\\\" ),
PATTERN( "_IDCHAR" , "[[:alpha:][:alnum:]_]" ),
PATTERN( "_ID" , "([[:alpha:]_])([[:alnum:]_])*" ),
PATTERN( "_DIGIT" , "[[:digit:]]]" ),
PATTERN( "_DIGITS" , "[[:digit:]]+" ),
PATTERN( "_HEXDIGIT" , "[[:xdigit:]]" ),
PATTERN( "_HEXDIGITS" , "[[:xdigit:]]+" ),
PATTERN( "_LETTER" , "[[:alpha:]]" ),
PATTERN( "_LETTERS" , "[[:alpha:]]+" ),
PATTERN( "_ALNUM" , "[[:alnum:]]" ),
PATTERN( "_ALNUMS" , "[[:alnum:]]+" ),
PATTERN( "_WHITESPACE" , "[[:space:]]" ),
PATTERN( "_WHITESPACES", "[[:space:]]+" ),
};
#undef PATTERN
//-------------------------------------------------------------------
// Initialize the operation map
//-------------------------------------------------------------------
assert(CONST_OPERATORS.empty());
//-------------------------------------------------------------------
define(_NIL, [](Parser&, size_t, const Rule&, OUT size_t&) {
DBG("NIL: no op. (returning false)");
return false;
});
//-------------------------------------------------------------------
define(_T, [](Parser&, size_t, const Rule&, OUT size_t&) {
DBG("T: 'true' op. (returning true)");
return true;
});
//-------------------------------------------------------------------
define(_ATOM, [](Parser& p, size_t pos, const Rule& rule, OUT size_t& len) {
assert(rule.is_atom());
static_assert(std::is_same<Atom, string>::value);
string atom = rule.atom;
++p.terminals_tried;
if (rule.type == Rule::CURATED_REGEX || rule.type == Rule::USER_REGEX)
{
try {
REGEX regx(atom); //!!PRECOMPILE!...
// REGEX regx(atom, std::regex::extended); //!!PRECOMPILE!...
// REGEX regx(atom, std::regex::extended | std::regex_constants::multiline); //!!PRECOMPILE!...
std::smatch m;
//!!?? WTF, C++? if (std::regex_search(string_view(p.text).substr(pos), m, regx)
//!!?? WTF, C++? if (std::regex_search(p.text.begin(), p.text.begin() + pos, m, regx)
//!!?? WTF, C++? if (std::regex_search(p.text.substr(pos), m, regx)
//!!?? WTF, C++? string_view target = string_view(p.text).substr(pos);
//OK: string target = p.text.substr(pos);
// if (std::regex_search(target, m, regx))
if (std::regex_search(p.text.cbegin() + ptrdiff_t(pos), p.text.cend(), m, regx))
// if ( std::regex_match(p.text.cbegin() + ptrdiff_t(pos), p.text.cend(), m, regx))
// NOTE: regex_match would enforce a complete (^...$-anchored)
// match, so can't be used to eat *some* of the text.
// OTOH, regex_search matches *anywhere*, so then the
// position of the result must be checked explicitly!
//
// But this also means that regex_search won't stop
// when failing to match at the start, and will go
// ahead happily playing with all the possible combinations
// in the entire string! Which is basically unacceptable
// for larger texts and/or complex grammars...
//
// So, still using regex_match with a wildcard suffix
// of .* would then seem to look viable after all,
//!![-- But not here! When precompiling!... :) ]
// but then again, there would be a misunderstanding
// between it and us about what a "real match" is,
// and it would always return the full text length for