-
Notifications
You must be signed in to change notification settings - Fork 2
/
generator.cpp
1816 lines (1747 loc) · 67.8 KB
/
generator.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
//
// Created by Alex on 8/24/2020.
//
#include <sstream>
#include <fstream>
#include <algorithm>
#include "lalr.h"
using namespace alex;
enum OptionType {
TypeJson,
TypeAst
};
struct Options {
const char *input;
const char *output;
const char *prefix;
const char *ast_header;
int type;
};
inline std::ostream &indent(std::ostream &os, int count = 0) {
os << std::string(' ', count * 4);
return os;
}
inline std::string string_escape(std::string_view view) {
std::string result;
result.reserve(view.length());
for (auto &chr : view) {
switch (chr) {
case '\t':
result += "\\t";
break;
case '\'':
result += "\\'";
break;
case '\"':
result += "\\\"";
break;
case '\n':
result += "\\n";
break;
case '\\':
result += "\\\\";
break;
case '\a':
result += "\\a";
break;
case '\b':
result += "\\b";
break;
case '\f':
result += "\\f";
break;
case '\r':
result += "\\r";
break;
default:
result += chr;
break;
}
}
return std::move(result);
}
inline std::string string_upper(const std::string &type) {
std::string string(type);
std::transform(type.begin(), type.end(), string.begin(), std::toupper);
return string;
}
inline std::string get_file_name(const std::string &file) {
auto pos = file.find_last_of('/');
if (pos == std::string::npos) {
return file;
}
return file.substr(pos + 1);
}
inline std::string drop_file_ext(const std::string &file) {
auto pos = file.find_last_of('.');
if (pos == std::string::npos) {
return file;
}
return file.substr(0, pos);
}
std::string parser_emit_symbols(LALRGenerator &generator) {
std::stringstream out;
out << "ParserSymbol ParserSymbols[] = {\n";
for (auto &symbol : generator.get_symbols()) {
out << " {"
<< symbol->is_nonterminal() << ", "
<< symbol->index << ", "
<< "\"" << string_escape(symbol->to_str()) << "\""
<< "},\n";
}
out << "};\n";
return out.str();
}
std::string parser_emit_action(LALRGenerator &generator) {
std::stringstream out;
if (generator.grammar.merge_create && generator.grammar.merge_insert) {
out << "\nint ParserMergeCreate = " << generator.grammar.merge_create->index << ";\n";
out << "int ParserMergeCreateCount = " << generator.grammar.merge_create->size() << ";\n";
out << "int ParserMergeInsert = " << generator.grammar.merge_insert->index << ";\n";
out << "int ParserMergeInsertCount = " << generator.grammar.merge_insert->size() << ";\n\n";
} else {
out << "\nint ParserMergeCreate = 0;\n";
out << "int ParserMergeCreateCount = 0;\n";
out << "int ParserMergeInsert = 0;\n";
out << "int ParserMergeInsertCount = 0;\n\n";
}
out << "ReduceAction ParserActions[] = {\n";
for (auto &action : generator.get_actions()) {
for (auto &inst: action->insts) {
out << " {"
<< inst.opcode << ", "
<< inst.value_int << ", ";
out << '\"' << inst.value_str << '\"';
out << "},\n";
}
}
out << "};\n";
return out.str();
}
std::string parser_emit_lexer_states(LALRGenerator &generator) {
std::stringstream out;
Lexer<> lexer;
//lexer.set_whitespace("[ \t\n\r]+");
for (auto &symbol : generator.get_symbols()) {
if (!symbol->is_nonterminal()) {
std::string_view pattern = symbol->terminal()->pattern;
bool literal = pattern.front() == '\'';
pattern.remove_prefix(1);
pattern.remove_suffix(1);
if (literal) {
lexer.add_literal(pattern, symbol->index);
} else {
lexer.add_pattern(pattern, symbol->index);
}
}
}
lexer.generate_states();
out << "int LexerWhitespaceSymbol = " << (generator.get_whitespace() ? generator.get_whitespace()->index : -1)
<< ";\n";
out << "LexerTransition LexerTransitions[] = {\n";
for (auto &state : lexer.state_machine) {
for (auto &trans : state->transitions) {
out << " {"
<< trans.begin << ", "
<< trans.end << ", ";
if (trans.state) {
out << "&LexerStates[" << trans.state->index << "]";
} else {
out << "nullptr";
}
out << "},\n";
}
}
out << "};\n";
int index = 0;
out << "LexerState LexerStates[] = {\n";
for (auto &state : lexer.state_machine) {
out << " {"
<< "&LexerTransitions[" << index << "], "
<< state->transitions.size() << ", ";
out << (int) state->symbol;
out << "},\n";
index += state->transitions.size();
}
out << "};\n";
return out.str();
}
std::string parser_emit_parser_states(LALRGenerator &generator) {
std::stringstream out;
out << "ParserTransition ParserTransitions[] = {\n";
for (auto &state : generator.get_states()) {
for (auto &trans : state->transitions) {
out << " {"
<< trans.type << ", "
<< trans.symbol->index << ", ";
if (trans.state) {
out << "&ParserStates[" << trans.state->index << "], ";
} else {
out << "nullptr, ";
}
out << (trans.reduce_symbol ? trans.reduce_symbol->index : 0) << ", "
<< trans.reduce_length << ", "
<< trans.precedence << ", ";
if (trans.reduce_action) {
out << "&ParserActions[" << trans.reduce_action->index << "], "
<< trans.reduce_action->size();
} else {
out << "nullptr, 0";
}
out << "},\n";
}
}
out << "};\n";
int index = 0;
out << "ParserState ParserStates[] = {\n";
int state_index = 0;
for (auto &state : generator.get_states()) {
out << " {" << state_index++ << ", "
<< "&ParserTransitions[" << index << "], "
<< state->transitions.size() << ", "
<< state->conflict << ", ";
if (state->error) {
out << "&ParserTransitions[" << state->error->index << "]";
} else {
out << "nullptr";
}
out << "},\n";
index += state->transitions.size();
}
out << "};\n";
return out.str();
}
class Generator {
public:
Generator(Options &opts) : options(opts) {}
~Generator() {}
void parse_from_options() {
// parse the input file
std::fstream input(options.input, std::ios::in);
parse_from_istream(input);
}
void parse_from_istream(std::istream &is) {
// clear grammar data
grammar.clear();
LALRGrammarParser<StreamIter> lalr(grammar);
// parse the input
lalr.parse(is);
// new generator
generator = std::make_unique<LALRGenerator>(grammar);
generator->generate();
}
/// generate all files
void generate() {
std::fstream fs;
// generate parser.cpp
fs.open(options.output, std::ios::trunc | std::ios::out);
generate_cpp_to_stream(fs);
fs.close();
// generate parser.h
std::string header = drop_file_ext(options.output) + ".h";
fs.open(header, std::ios::trunc | std::ios::out);
generate_common_header(fs);
fs.close();
// generate ast.h
if (options.type == TypeAst) {
fs.open(options.ast_header, std::ios::trunc | std::ios::out);
generate_ast_header(fs);
fs.close();
}
}
/// generate(parser.cpp) to stream
void generate_cpp_to_stream(std::ostream &os) {
os << "//\n"
<< "// Created by Alex's tiny lr.\n"
<< "//\n"
<< "#include \"" << drop_file_ext(get_file_name(options.output)) << ".h" << "\"\n";
generate_state_machine(os);
}
/// generate lexer states and parser states
void generate_state_machine(std::ostream &os) {
os << parser_emit_symbols(*generator)
<< parser_emit_lexer_states(*generator)
<< parser_emit_action(*generator)
<< parser_emit_parser_states(*generator);
}
/// generate common header(parser.h)
void generate_common_header(std::ostream &os) {
os << "//\n"
"// Created by Alex\n"
"//\n"
"\n"
"#ifndef TINYLALR_PARSER_H\n"
"#define TINYLALR_PARSER_H\n";
os << "#include <string>\n"
"#include <iostream>\n"
"#include <map>\n"
"#include <queue>\n"
"#include <cassert>\n"
"#include <functional>\n"
"#include <algorithm>\n\n";
os << "#define LR_ASSERT(x) assert(x)\n"
"#define LR_UNREACHED() assert(!\"unreached here\")\n"
"#define LR_TYPESPEC(TYPE) virtual TYPE\n\n";
os << "#define CONFLICT_NONE 0\n"
"#define CONFLICT_SHIFT_REDUCE 1\n"
"#define CONFLICT_REDUCE_REDUCE 2\n"
"#define SYMBOL_TYPE_TERMINAL 0\n"
"#define SYMBOL_TYPE_NONTERMINAL 1\n"
"#define TRANSITION_SHIFT 1\n"
"#define TRANSITION_REDUCE 2\n\n";
os << "enum ActionOpcode {\n"
" OpcodeCreateObj,\n"
" OpcodeCreateArr,\n"
" OpcodePushValue, /// $n\n"
" OpcodePushInt, /// int\n"
" OpcodePushStr, /// str\n"
" OpcodePushBool, /// bool\n"
" OpcodePushToken, /// token\n"
" OpcodePopSet,\n"
" OpcodePopInsertArr,\n"
" OpcodePopInsertObj,\n"
"};";
// emit common structs
os << R"cpp(
struct ParserSymbol {
int type;
int symbol;
const char *text;
};
struct LexerState;
struct LexerTransition {
int begin;
int end;
LexerState *state;
};
struct LexerState {
LexerTransition *transitions;
int transition_count;
int symbol;
inline LexerTransition *begin() { return transitions; }
inline LexerTransition *end() { return transitions + transition_count; }
inline LexerTransition *find(int chr) {
LexerTransition trans{0, chr};
if (auto *iter = std::upper_bound(begin(), end(), trans, [](const LexerTransition &LHS, const LexerTransition &RHS) {
return LHS.end < RHS.end;
})) {
if (iter && iter->begin <= chr && chr < iter->end) {
return iter;
}
}
return nullptr;
}
};
struct ReduceAction {
int opcode;
int index;
const char *value;
};
struct ParserState;
struct ParserTransition {
int type;
int symbol;
ParserState *state;
int reduce_symbol;
int reduce_length;
int precedence;
ReduceAction *actions;
int action_count;
inline bool accept() const { return reduce_symbol == 0 && type == TRANSITION_REDUCE; }
inline bool error() const { return symbol == 2 && type == TRANSITION_SHIFT; }
};
struct ParserState {
int index;
ParserTransition *transitions;
int transition_count;
int conflict;
ParserTransition *error;
inline ParserTransition *begin() { return transitions; }
inline ParserTransition *end() { return transitions + transition_count; }
inline ParserTransition *find(int symbol) {
ParserTransition trans{0, symbol};
return std::lower_bound(begin(), end(), trans, [](const ParserTransition &LHS, const ParserTransition &RHS) {
return LHS.symbol < RHS.symbol;
});
}
};
extern int LexerWhitespaceSymbol;
extern ParserSymbol ParserSymbols[];
extern LexerState LexerStates[];
extern LexerTransition LexerTransitions[];
extern ParserState ParserStates[];
extern ReduceAction ParserActions[];
extern ParserTransition ParserTransitions[];
struct Location {
int line_start = 0;
int line_end = 0;
int column_start = 0;
int column_end = 0;
bool empty() const { return line_start == line_end && column_start == column_end; }
Location merge(const Location &rhs) const {
if (rhs.empty()) {
return *this;
}
if (empty()) {
return rhs;
}
return {
std::min(line_start, rhs.line_start),
std::max(line_end, rhs.line_end),
std::min(column_start, rhs.column_start),
std::max(column_end, rhs.column_end)
};
}
};
template <class iter_t = const char *,
class char_t = typename std::iterator_traits<iter_t>::value_type,
class char_traits = std::char_traits<char_t>>
class ParserLexer {
public:
using string_t = std::basic_string<char_t, char_traits>;
private:
LexerState *lexer_state /* = &LexerStates[0]*/;
int whitespace /*= LexerWhitespaceSymbol*/;
iter_t current;
iter_t end;
int line_ = 0;
int line_start_position_ = 0;
int position_ = 0;
int token_line_start_ = 0;
int token_column_start_ = 0;
int token_symbol = 0;
string_t lexeme_;
private:
auto advance_symbol() {
LexerState *state = lexer_state;
lexeme_.clear();
do {
if (current == end) {
return state->symbol;
}
if (auto *trans = state->find(*current)) {
lexeme_ += *current;
state = trans->state;
++position_;
if (*current == '\n') {
++line_;
line_start_position_ = position_;
}
++current;
} else {
break;
}
} while (true);
if (state == lexer_state && *current != '\0') {
std::cout << "Unexpect char: " << *current << " line:" << line_end() << std::endl;
++current;
return 2; // error symbol
}
return state->symbol;
}
public:
ParserLexer(LexerState *state, int whitespace = -1) : lexer_state(state), whitespace(whitespace) {}
void reset(iter_t first, iter_t last) {
current = first;
end = last;
}
void advance() {
do {
token_line_start_ = line_end();
token_column_start_ = column_end();
token_symbol = advance_symbol();
} while (token_symbol == whitespace);
}
int symbol() { return token_symbol; }
inline int line_start() const { return token_line_start_; }
inline int line_end() const { return line_; }
inline int column_start() const { return token_column_start_; }
inline int column_end() const { return position_ - line_start_position_; }
inline Location location() const { return {line_start(), line_end(), column_start(), column_end()}; }
inline string_t &lexeme() { return lexeme_; }
void dump() {
do {
advance();
std::cout << lexeme_ << " " << token_symbol
<< "[" << line_start() << ", " << column_start() << "]" << std::endl;
if (token_symbol == 0) {
break;
}
} while (symbol() != 0);
exit(0);
}
};)cpp" << std::endl << std::endl;
if (options.type == TypeJson) {
generate_json_parser(os);
} else {
generate_ast_parser(os);
}
os << "#endif //TINYLALR_PARSER_H";
}
void generate_json_parser(std::ostream &os) {
os << "#include \"json.hpp\"\n"
<< "using value_t = nlohmann::json;\n\n";
// type dispatcher
if (grammar.types.size() > 0) {
// generate type enum
os << "enum {\n";
os << " " << options.prefix << "NONE = 0,\n";
for (auto &type : grammar.types) {
os << " " << options.prefix << string_upper(type);
os << " = " << grammar.type_info[type].index;
os << ",\n";
}
os << "};\n";
// generate base type
os << "class JsonASTBase {\n"
"protected:\n"
" value_t &value_;\n"
"public:\n"
" using float_t = value_t::number_float_t;\n"
" using int_t = value_t::number_integer_t;\n"
" using uint_t = value_t::number_unsigned_t;\n"
" using string_t = value_t::string_t;\n"
" using iter_t = value_t::iterator;\n"
" using const_iter_t = value_t::const_iterator;\n"
" using size_t = value_t::size_type;\n"
" JsonASTBase(value_t &value) : value_(value) {}\n"
" int getID() { return value_[\"id\"].get<int>(); }\n"
" string_t &getKind() { return value_[\"kind\"].get_ref<string_t &>(); }\n"
" operator value_t &() { return value_; }\n"
"};\n";
// generate derived type
for (auto &[name, type]: grammar.type_info) {
if (name.empty()) {
continue;
}
os << "class " << name << " : public JsonASTBase {\n"
"public:\n";
//output constructor
os << " "
<< name << "(value_t &value) : JsonASTBase(value) { LR_ASSERT(value[\"id\"] == " << options.prefix
<< string_upper(name) << "); }\n";
// os << " using JsonASTBase::JsonASTBase;\n";
// Number(value_t &value) : JsonASTBase(value) { LR_ASSERT(value["id"] == TYPE_NUMBER); }
for (auto &[field, index]: type.fields) {
auto output = field;
if (output.substr(0, 2) != "is") {
output[0] = std::toupper(output[0]);
output = "get" + output;
}
auto field_type = type.fields_type[field];
if (field_type.empty()) { // non type
os << " " << "value_t &";
os << output << "() { return value_[\"" << field << "\"]; }\n";
} else if (field_type.back() == '&') { // get_ref
field_type = field_type.substr(0, field_type.size() - 1) + " &";
os << " " << field_type;
os << output << "() { return value_[\"" << field << "\"].get_ref<" << field_type << ">(); }\n";
} else { // get
os << " " << field_type << " ";
os << output << "() { return value_[\"" << field << "\"]; }\n";
}
}
os << "};\n";
}
// generate visitor
os << "template<typename SubTy, typename RetTy = void>\n"
"struct Visitor {\n"
" RetTy visit(value_t &value) {\n"
" if (value.is_null()) {\n"
" return RetTy();\n"
" }\n"
" if (value.is_array()) {\n"
" for (auto &val : value) {\n"
" visit(val);\n"
" }\n"
" return RetTy();\n"
" }\n"
" switch (value[\"id\"].get<int>()) {\n";
for (auto &[name, type]: grammar.type_info) {
if (name.empty()) {
continue;
}
os << " case " << options.prefix << string_upper(name) << ":\n"
<< " return static_cast<SubTy *>(this)->visit" << name << "(value);\n";
}
os << " default:\n"
" LR_UNREACHED();\n"
" }\n"
" }\n";
for (auto &[name, type]: grammar.type_info) {
if (name.empty()) {
continue;
}
os << " LR_TYPESPEC(RetTy) visit" << name << "(" << name << " value) {\n"
<< " return RetTy();\n"
<< " }\n";
}
os << "};\n";
}
// HandleReduceAction
os << R"cpp(
template<bool Move = true, typename NodeGetter>
inline void HandleReduceAction(ReduceAction &action, std::vector<value_t> &arr, NodeGetter nodes) {
switch (action.opcode) {
default:
LR_UNREACHED();
case OpcodeCreateObj:
if (action.index)
arr.push_back(value_t::object_t(
{{"kind", value_t::string_t(action.value)},
{"id", value_t::number_integer_t(action.index)}}));
else
arr.push_back(value_t::object_t());
break;
case OpcodeCreateArr:
arr.push_back(value_t::array_t());
break;
case OpcodePushValue:
arr.push_back(Move ? std::move(nodes[action.index].value) : nodes[action.index].value);
break;
case OpcodePushInt:
arr.push_back(value_t::number_integer_t(action.index));
break;
case OpcodePushStr:
arr.push_back(value_t::string_t(action.value));
break;
case OpcodePushBool:
arr.push_back(value_t::boolean_t(action.index));
break;
case OpcodePushToken:
arr.push_back(value_t::string_t(nodes[action.index].lexeme));
break;
case OpcodePopSet: {
auto poped = std::move(arr.back());
arr.pop_back();
auto &top = arr.back();
top[std::string(action.value)] = std::move(poped);
break;
}
case OpcodePopInsertArr: {
auto poped = std::move(arr.back());
arr.pop_back();
auto &top = arr.back();
top.insert(top.end(), std::move(poped));
break;
}
case OpcodePopInsertObj: {
auto poped = std::move(arr.back());
arr.pop_back();
auto &top = arr.back()[std::string(action.value)];
top.insert(top.end(), std::move(poped));
break;
}
}
}
)cpp";
// LRParser
os << R"cpp(
template<class iter_t = const char *,
class char_t = typename std::iterator_traits<iter_t>::value_type,
class char_traits = std::char_traits<char_t>>
class LRParser {
public:
using Lexer = ParserLexer<iter_t>;
using string_t = typename Lexer::string_t;
private:
struct ParserNode {
ParserState *state;
int symbol;
value_t value;
string_t lexeme;
Location location;
ParserNode(ParserState *state, int symbol, const value_t &value, Location loc) : state(state), symbol(symbol),
value(value), location(loc) {
#ifdef DEBUG
lexeme = ParserSymbols[symbol].text;
#endif
}
ParserNode(ParserState *state, int symbol, const string_t &lexeme, Location loc) : state(state), symbol(symbol),
lexeme(lexeme), location(loc) {}
};
using Node = ParserNode;
public:
ParserState *parser_state = &ParserStates[0];
Lexer parser_lexer = Lexer(&LexerStates[0], LexerWhitespaceSymbol);
bool position = false;
inline ParserTransition *find_trans(ParserState *state, int symbol) {
for (auto &trans: *state) {
if (trans.symbol == symbol) {
return &trans;
}
}
return nullptr;
}
public:
std::vector<Node> stack;
std::vector<value_t> values;
LRParser() = default;
explicit LRParser(bool position) : position(position) {}
void set_position(bool sp) {
position = sp;
}
void reset(iter_t first, iter_t last = iter_t()) {
parser_lexer.reset(first, last);
}
void parse() {
parser_lexer.advance();
stack.reserve(32);
stack.push_back(Node(parser_state));
do {
if (auto *trans = find_trans(stack.back().state, parser_lexer.symbol())) {
if (trans->type == TRANSITION_SHIFT) { // Shift
shift(trans);
} else { // Reduce
reduce(trans);
if (trans->accept()) {
break;
}
}
} else {
if (!handle_error()) {
break;
}
}
} while (true);
}
value_t &value() { return stack[0].value; }
inline void shift(ParserTransition *trans) {
// debug_shift(trans);
stack.emplace_back(trans->state, parser_lexer.symbol(), parser_lexer.lexeme(), parser_lexer.location());
parser_lexer.advance();
}
inline void reduce(ParserTransition *trans) {
values.clear();
// if the reduce length is zero, the location is the lexer current location.
Location loc = parser_lexer.location();
if (trans->reduce_length) {
auto first = stack.size() - trans->reduce_length;
// merge the locations
loc = std::accumulate(stack.begin() + first, stack.end(), Location(), [](Location &i, Node *node) {
return i.merge(node->location);
});
// handle `reduce` action
handle_action(trans->actions, trans->action_count, &stack[first]);
// record the position
value_t &reduce_value = values.back();
if (position && reduce_value.is_object()) {
reduce_value["position"] = {{"line", loc.line_start},
{"column", loc.column_start}};
}
stack.erase(stack.begin() + first, stack.end());
if (trans->accept()) {
stack.back().value = std::move(values.back());
return;
}
}
// goto a new state by the reduced symbol
if (auto *Goto = find_trans(stack.back().state, trans->reduce_symbol)) {
stack.emplace_back(Goto->state, trans->reduce_symbol, std::move(values.back()), loc);
values.pop_back();
} else {
expect();
}
}
inline void expect() {
Node &node = stack.back();
std::cout << "Shift Reduce Error "
"line: " << node.location.line_start + 1 << " "
<< "column: " << node.location.column_start + 1 << " "
<< "token: " << parser_lexer.lexeme()
<< std::endl;
std::cout << "Expect: ";
for (auto &trans: *node.state) {
std::cout << "\"" << ParserSymbols[trans.symbol].text << "\"";
if (&trans != (node.state->end() - 1)) {
std::cout << ", ";
}
}
std::cout << std::endl;
}
inline void debug_shift(ParserTransition *trans) {
std::cout << "shift: " << stack.size() << " "
<< "[state " << (stack.back().state - ParserStates) << " -> " << (trans->state - ParserStates)
<< "] [" << ParserSymbols[parser_lexer.symbol()].text << "] "
<< parser_lexer.lexeme()
<< std::endl << std::endl;
}
inline void debug_reduce(ParserTransition *trans, int start) {
ParserTransition *goto_trans = find_trans(stack[start - 1].state, trans->reduce_symbol);
if (!goto_trans) {
return;
}
std::cout << "reduce: "
<< start << " "
<< "[back to " /*<< (stack.back().state - ParserStates) << " -> "*/
<< (stack[start - 1].state - ParserStates) << " -> "
<< (goto_trans->state - ParserStates) << "] "
<< ParserSymbols[trans->reduce_symbol].text << " <- ";
for (int i = start; i < start + trans->reduce_length; ++i) {
std::cout << "[" << stack[i].lexeme << "] " << stack[i].value << " | ";
}
std::cout << std::endl << std::endl;
}
inline void handle_action(ReduceAction *actions, int action_count, Node *nodes) {
if (action_count == 0) {
values.push_back(std::move(nodes->value));
return;
}
struct Getter {
Node *nodes;
Getter(Node *nodes) : nodes(nodes) {}
inline Node &operator[](size_t index) {
return nodes[index];
}
} getter{nodes};
for (int i = 0; i < action_count; ++i) {
HandleReduceAction(actions[i], values, getter);
}
}
inline bool handle_error() {
auto *trans = find_trans(stack.back().state, 2);
if (trans == nullptr) {
expect();
return false;
}
value_t value = value_t::array();
ParserState *state = trans->state;
do {
value.push_back({{"lexeme", parser_lexer.lexeme()},
{"line", parser_lexer.line_start()},
{"column", parser_lexer.column_start()}});
parser_lexer.advance();
if (ParserTransition *Goto = find_trans(state, parser_lexer.symbol())) {
stack.emplace_back(trans->state, 2, std::move(value), parser_lexer.location());
if (Goto->type == TRANSITION_SHIFT) {
shift(Goto);
} else {
reduce(Goto);
}
break;
}
} while (true);
return true;
}
};
)cpp" << std::endl;
os << "extern int ParserMergeCreate;\n";
os << "extern int ParserMergeCreateCount;\n";
os << "extern int ParserMergeInsert;\n";
os << "extern int ParserMergeInsertCount;\n\n";
// GLRParser
os << R"cpp(template <class iter_t = const char *,
class char_t = typename std::iterator_traits<iter_t>::value_type,
class char_traits = std::char_traits<char_t>>
class GLRParser {
using Lexer = ParserLexer<iter_t>;
using string_t = typename Lexer::string_t;
struct ParserGraphNode {
using NodePtr = std::shared_ptr<ParserGraphNode>;
static auto Create(ParserState *state) {
return std::make_shared<ParserGraphNode>(state);
}
static auto Create(ParserState *state, const NodePtr &prev) {
return std::make_shared<ParserGraphNode>(state, prev);
}
std::vector<NodePtr> prevs;
ParserState *state = nullptr;
int symbol = 0;
value_t value;
string_t lexeme;
Location location;
int depth = 0;
int merge = 0;
bool error = false;
ParserGraphNode() {}
ParserGraphNode(ParserState *state) : state(state) {}
ParserGraphNode(ParserState *state, const NodePtr &prev) : state(state), prevs({prev}) {}
void add_prev(const NodePtr &previous) {
prevs.push_back(previous);
}
bool need_lr_reduce(ParserTransition *trans) {
return state->conflict == CONFLICT_NONE && trans->reduce_length <= depth;
}
};
private:
using Node = ParserGraphNode;
using NodePtr = std::shared_ptr<Node>;
struct ReduceNode {
std::vector<NodePtr> paths;
ParserTransition *trans;
NodePtr prev;
ReduceNode(const std::vector<NodePtr> &paths, ParserTransition *trans, const NodePtr &prev) : paths(paths.rbegin(), paths.rend()),
trans(trans), prev(prev) {}
inline bool operator<(const ReduceNode &rhs) const {
return trans->precedence < rhs.trans->precedence;
}
inline NodePtr get_last() const {
return paths.back();
}
};
ParserState *parser_state = &ParserStates[0];
Lexer lexer_ = Lexer(&LexerStates[0], LexerWhitespaceSymbol);
bool position = false;
bool accepted = false;
std::map<ParserState *, NodePtr> frontier;
std::vector<NodePtr> shift_list;
std::vector<value_t> values;
std::priority_queue<ReduceNode> reduce_list;
public:
GLRParser() = default;
explicit GLRParser(bool position) : position(position) {}
explicit GLRParser(iter_t first, iter_t last = iter_t()) {
reset(first, last);
}
void set_position(bool sp) {
position = sp;
}
void reset(iter_t first, iter_t last = iter_t()) {
accepted = false;
frontier.clear();
lexer_.reset(first, last);
}
void parse() {
frontier.insert(std::pair(parser_state, Node::Create(parser_state)));
lexer_.advance();
do {
shift();
reduce();
if (frontier.size() == 0 || accepted) {
break;
}
} while (true);
}
bool accept() {
return accepted && frontier.size() > 0;
}
value_t &value() {
return std::get<1>(*frontier.begin())->value;
}
void shift() {
shift_list.clear();
for (auto &[state, node] : frontier) {
int shift_count = 0;
for (auto *trans = state->find(lexer_.symbol()); trans < state->end(); trans++) {
if (trans->symbol != lexer_.symbol()) {
break;
}
if (trans->type == TRANSITION_SHIFT) {
NodePtr shift_node = Node::Create(trans->state, node);
shift_node->symbol = lexer_.symbol();
shift_node->lexeme = lexer_.lexeme();
shift_node->location = lexer_.location();
shift_node->depth = node->depth + 1;
shift_list.push_back(shift_node);
shift_count++;
}
}
if (state->error && shift_count == 0 || node->error) {
do_error(node, state->error);
}
}
if (shift_list.size() == 0) {
handle_error();
}
frontier.clear();
for (auto &node : shift_list) {
if (frontier.count(node->state)) {
// merge the previous nodes if they are the same state
auto &prevs = frontier[node->state]->prevs;
prevs.insert(prevs.end(), node->prevs.begin(), node->prevs.end());
frontier[node->state]->depth = 0;
} else {
frontier.insert(std::pair(node->state, node));
}
}