-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.cpp
1867 lines (1586 loc) · 66.7 KB
/
main.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
#include <stdint.h>
#include <set>
#include <map>
#include <string>
#include <limits>
#include <vector>
#include <cstdio>
#include <cstdarg>
#include <cstring>
#include <sstream>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <stdexcept>
#include <algorithm>
#include <iterator>
#define json_assert(cond, message) if(!(cond)) throw std::runtime_error(message);
#define json_asserte(cond, exception_class, message) if(!(cond)) throw exception_class(message);
#define json_assertx(cond, format, ...) if(!(cond)) throw std::runtime_error(xsnprintf(128, format, __VA_ARGS__));
#define for_each(container_type, container_obj, iterator_name) \
for (container_type::iterator iterator_name = container_obj.begin(); iterator_name != container_obj.end(); ++iterator_name)
#define for_each_c(container_type, container_obj, iterator_name) \
for (container_type::const_iterator iterator_name = container_obj.begin(); iterator_name != container_obj.end(); ++iterator_name)
/* TODO
* Найти имя
* Символ конца потока токенов
* Билдер для грамматики
* Билдер для лексики
* Устранение неоднозначностей
* Обработка ошибок в лексере и парсере
* Переделать лексер
* Переделать класс Json для того чтобы он сам был и объектом и массивом
*
// flexify
// Yet another lexer and parser
// Yalp
// Lerser
*/
namespace common {
typedef std::vector<char> ByteBuffer;
template<typename T>
class clean_allocator {
public :
typedef T value_type;
typedef value_type* pointer;
typedef const value_type* const_pointer;
typedef value_type& reference;
typedef const value_type& const_reference;
typedef std::size_t size_type;
typedef std::ptrdiff_t difference_type;
public :
template<typename U>
struct rebind {
typedef clean_allocator<U> other;
};
public :
clean_allocator() {}
inline ~clean_allocator() {}
clean_allocator(clean_allocator const&) {}
template<typename U>
clean_allocator(clean_allocator<U> const&) {}
pointer address(reference r) { return &r; }
const_pointer address(const_reference r) { return &r; }
pointer allocate(size_type cnt, typename std::allocator<void>::const_pointer = 0) {
pointer new_memory = reinterpret_cast<pointer>(::operator new(cnt * sizeof (T)));
memset(new_memory, 0, cnt * sizeof(T));
return new_memory;
}
void deallocate(pointer p, size_type n) {
::operator delete(p);
}
// size
size_type max_size() const {
return std::numeric_limits<size_type>::max() / sizeof(T);
}
void construct(pointer p, T const& t) {
new(p) T(t);
}
void destroy(pointer p) {
p->~T();
}
bool operator==(clean_allocator const&) { return true; }
bool operator!=(clean_allocator const& a) { return !operator==(a); }
};
template <typename K, typename V>
class make_map {
private:
std::map<K, V> map;
public:
make_map(K const& key, V const& val) {
map[key] = val;
}
make_map<K, V>& operator()(K const& key, V const& val) {
map[key] = val;
return *this;
}
operator std::map<K, V>() {
return map;
}
};
template<typename T>
class make_vector {
public:
make_vector(T const& t) {
v.push_back(t);
}
make_vector& operator()(T const& t) {
v.push_back(t);
return *this;
}
operator std::vector<T>() const {
return v;
}
std::vector<T> v;
};
ByteBuffer vxsnprintf(size_t maxlen, const char* format, ...) {
std::vector<char> buffer(maxlen);
va_list args;
va_start(args, format);
vsnprintf(buffer.data(), maxlen, format, args);
va_end(args);
return buffer;
}
std::string xsnprintf(size_t maxlen, const char* format, ...) {
va_list args;
va_start(args, format);
std::vector<char> buffer = vxsnprintf(maxlen, format, args);
va_end(args);
return std::string(buffer.data());
}
template<typename T>
class XPtr {
public:
XPtr(T* t = NULL) : t(t) {}
~XPtr() { if (t) delete t; t = NULL; }
T* operator->() { return t ? t : throw std::runtime_error("pointer is null"); }
const T* operator->() const { return t ? t : throw std::runtime_error("pointer is null"); }
operator T*() { return t; }
operator const T*() const{ return t; }
template<typename U>
U* dcast() { return dynamic_cast<U*>(t); }
template<typename U>
const U* dcast() const { return dynamic_cast<const U*>(t); }
XPtr(const XPtr& rhs) { *this = rhs; }
XPtr& operator=(const XPtr& rhs) {
if (this != &rhs) {
if (t) {
delete t;
t = NULL;
}
t = rhs.t->clone();
}
return *this;
}
private:
T* t;
};
}
namespace lexer {
namespace new_lexer {
template<typename T>
class Matrix {
public:
explicit Matrix(int rows = 0, int cols = 0) : rows(rows), cols(cols), data(rows * cols) {}
T &at(int row, int col) {
return data.at(row * cols + col);
}
const T &at(int row, int col) const {
return data.at(row * cols + col);
}
int getRows() const {
return rows;
}
int getCols() const {
return cols;
}
private:
int rows;
int cols;
std::vector<T> data;
};
typedef std::string String;
typedef int Symbol;
typedef std::vector<Symbol> Language;
const Symbol Empty = ~0;
typedef int State;
typedef std::vector<State> States;
typedef Matrix<States> nFsmTransitions;
typedef Matrix<State> dFsmTransitions;
class nFSM {
public:
nFSM(Language const &language) : state(0), transitions(language.size(), language.size()) {
for (int i = 0; i < transitions.getRows(); ++i) {
for (int j = 0; j < transitions.getCols(); ++j) {
States states;
states.push_back(-1);
transitions.at(i, j) = states;
}
}
}
void reset() {
state = 0;
}
bool accept(String const &string) {
for_each_c(String, string, chr) {
Symbol symbol = *chr;
if (transitions.at(state, symbol).size() > 0) {
State nextState = transitions.at(state, symbol).at(0);
state = nextState;
} else {
return false;
}
}
for_each(States, finishStates, stt) if (state == *stt)
return true;
return false;
}
std::ostream &dotStringify(std::ostream &out) {
return out;
}
private:
nFsmTransitions transitions;
States finishStates;
State state;
};
class LanguageBuilder {
public:
LanguageBuilder() {}
LanguageBuilder &add(String const &string) {
return *this;
}
LanguageBuilder &add(Symbol symbol) {
return *this;
}
operator Language() const {
return language;
}
private:
Language language;
};
class RegularExpression {
public:
RegularExpression() {}
};
class Union : public RegularExpression {
public:
Union() {}
};
class Concatanation : public RegularExpression {
public:
Concatanation() {}
};
class KleeneStar : public RegularExpression {
public:
KleeneStar() {}
};
}
typedef int RuleId;
typedef int TokenId;
typedef int Increment;
typedef int Terminal;
const RuleId Initial = 0;
const RuleId InvalidRule = ~0;
const TokenId InvalidToken = ~0;
const TokenId Skip = ~0 - 1;
struct LexerError : std::runtime_error {
explicit LexerError(const std::string& __arg) : runtime_error(__arg) {}
};
struct Transition {
RuleId ruleId;
TokenId tokenId;
bool putChar;
Increment increment;
bool lookInSymbolTable;
explicit Transition(RuleId ruleId = InvalidRule, TokenId tokenId = InvalidToken, bool putChar = true, Increment increment = 1) :
ruleId(ruleId), tokenId(tokenId), putChar(putChar), increment(increment){}
friend bool operator==(Transition const& lhs, Transition const& rhs) {
return lhs.ruleId == rhs.ruleId &&
lhs.putChar == rhs.putChar &&
lhs.tokenId == rhs.tokenId &&
lhs.increment == rhs.increment;
}
friend bool operator!=(Transition const& lhs, Transition const& rhs) {
return !(rhs == lhs);
}
friend std::ostream& operator<<(std::ostream& os, const Transition& transition) {
os << "["
<< transition.ruleId
<< ", " << transition.putChar
<< ", " << transition.tokenId
<< ", " << transition.increment
<< "]";
return os;
}
};
struct Condition {
std::string chars;
bool inSet;
explicit Condition(std::string const& chars = "", bool inSet = true) : chars(chars), inSet(inSet) {}
friend bool operator<(Condition const& lhs, Condition const& rhs) {
if (lhs.chars < rhs.chars)
return true;
if (rhs.chars < lhs.chars)
return false;
return lhs.inSet < rhs.inSet;
}
};
typedef std::map<Condition, Transition> LexerRule;
typedef std::map<RuleId, LexerRule> LexerRules;
typedef std::vector<std::vector<Transition> > LexerStateMachine;
typedef std::map<std::string, Terminal> SymbolTable;
typedef common::make_map<std::string, Terminal> MakeSymbolTable;
typedef std::map<Terminal, std::string> TerminalNames;
typedef common::make_map<Terminal, std::string> MakeTerminalNames;
std::string terminalName(Terminal terminal, TerminalNames const& terminalNames) {
TerminalNames::const_iterator it = terminalNames.find(terminal);
if (it == terminalNames.end()) {
std::stringstream stringstream;
stringstream << terminal;
return stringstream.str();
}
return it->second;
}
struct Token {
explicit Token(TokenId tokenId = InvalidToken, std::string const& value = std::string(),
int startLine = -1, int endLine = -1, int startSymbol = -1, int endSymbol = -1)
: tokenId(tokenId), value(value),
startLine(startLine), endLine(endLine), startSymbol(startSymbol), endSymbol(endSymbol) {}
std::ostream& stringify(std::ostream& out, TerminalNames const& terminalNames, int maxTerminalNameLength) const {
return out << "("
<< std::setw(2) << startLine
<< ", " << std::setw(2) << endLine
<< ", " << std::setw(2) << startSymbol
<< ", " << std::setw(2) << endSymbol
<< "), "
<< "token: " << std::setw(maxTerminalNameLength)
<< terminalName(tokenId, terminalNames) << ", "
<< (value.empty() ? "" : " value: " + value);
}
friend std::ostream& operator<<(std::ostream& os, Token const& token);
TokenId tokenId;
std::string value;
int startLine, endLine, startSymbol, endSymbol;
};
typedef std::vector<Token> Tokens;
class Lexer {
public:
explicit Lexer(LexerRules const &lexerRules) {
lexerStateMachine.resize(lexerRules.size());
size_t maxChar = std::numeric_limits<uint8_t>::max();
for_each_c (LexerRules, lexerRules, rule) {
std::vector<Transition> lexerState;
lexerState.resize(static_cast<size_t>(maxChar));
for_each_c (LexerRule, rule->second, transition) {
if (transition->first.inSet)
for_each_c (std::string, transition->first.chars, c)
updateTransition(lexerState, transition->second, *c);
else
for (char c = 0; c < maxChar; ++c)
if (std::find(transition->first.chars.begin(),
transition->first.chars.end(), c) == transition->first.chars.end())
updateTransition(lexerState, transition->second, c);
}
lexerStateMachine.at(static_cast<size_t>(rule->first)) = lexerState;
}
}
Tokens analize(std::string const& string) {
RuleId currentState = Initial;
Tokens tokens;
std::string token;
int line = 1;
int column = 0;
int prevLine = line;
int prevColumn = column;
for (std::string::const_iterator c = string.begin(); c != string.end();) {
if (*c == '\n') {
++line;
column = 0;
} else {
++column;
}
Transition transition = lexerStateMachine.
at(static_cast<size_t>(currentState)).
at(static_cast<size_t>(*c));
if (transition.putChar)
token.push_back(*c);
if (transition.ruleId == InvalidRule)
throw LexerError(common::xsnprintf(64, "invalid char \"%c\" at %d:%d", *c, line, column));
else {
if (transition.ruleId == Initial) {
if (transition.tokenId != Skip)
tokens.push_back(Token(static_cast<TokenId>(transition.tokenId), token, prevLine, line, prevColumn, column));
prevLine = line;
prevColumn = column;
token.clear();
}
currentState = transition.ruleId;
}
c += transition.increment;
}
return tokens;
}
friend std::ostream& operator<<(std::ostream& os, Lexer const& lexer) {
os << "LexerStateMachine: \n";
for_each_c (LexerStateMachine, lexer.lexerStateMachine, lexerState) {
if (lexerState != lexer.lexerStateMachine.begin()) os << "\n";
for_each_c (std::vector<Transition>, (*lexerState), transition) {
if (transition != (*lexerState).begin()) os << ", ";
os << *transition;
}
}
os << "\n";
return os;
}
private:
void updateTransition(std::vector<Transition>& lexerState, Transition const& transition, char symbol) {
Transition &state = lexerState.at(static_cast<size_t>(symbol));
if (state != Transition())
throw LexerError("lexer rule is ambiguous");
state = transition;
}
private:
LexerStateMachine lexerStateMachine;
};
}
namespace parser {
typedef int NonTerminal;
typedef std::map<NonTerminal, std::string> NonTerminalNames;
std::string nonTerminalName(NonTerminal nonTerminal, NonTerminalNames const& nonTerminalNames) {
NonTerminalNames::const_iterator it = nonTerminalNames.find(nonTerminal);
if (it == nonTerminalNames.end()) {
std::stringstream stringstream;
stringstream << nonTerminal;
return stringstream.str();
}
return it->second;
}
struct GrammaticSymbol {
int value; // Terminal or NonTerminal
bool isTerminal;
explicit GrammaticSymbol(int value, bool isTerminal = true) : value(value), isTerminal(isTerminal) {}
friend bool operator==(const GrammaticSymbol& lhs, const GrammaticSymbol& rhs) {
return lhs.value == rhs.value &&
lhs.isTerminal == rhs.isTerminal;
}
friend bool operator!=(const GrammaticSymbol& lhs, const GrammaticSymbol& rhs) {
return !(rhs == lhs);
}
friend bool operator<(const GrammaticSymbol& lhs, const GrammaticSymbol& rhs) {
if (lhs.value < rhs.value)
return true;
if (rhs.value < lhs.value)
return false;
return lhs.isTerminal < rhs.isTerminal;
}
std::ostream& stringify(std::ostream& out, lexer::TerminalNames const& terminalNames, NonTerminalNames const& nonTerminalNames) const {
return out << std::setw(14)
<< (isTerminal ? "Terminal" : "NonTerminal") << ": "
<< (isTerminal ? lexer::terminalName(value, terminalNames) : nonTerminalName(value, nonTerminalNames));
}
};
typedef std::vector<GrammaticSymbol> GrammaticSymbols; // X, Y, Z
typedef std::vector<GrammaticSymbols> Alternative; // alpha | beta | gamma
typedef std::map<NonTerminal, Alternative> Grammar; // A -> alpha | beta | gamma
typedef common::make_vector<GrammaticSymbol> MakeGrammaticSymbols;
typedef common::make_vector<GrammaticSymbols> MakeAlternatives;
typedef common::make_map<NonTerminal, Alternative> MakeGrammar;
/*
class GrammarBuilder;
class ProductionBuilder : public GrammarBuilder;
class AlternativeBuilder : public ProductionBuilder {
public:
AlternativeBuilder(ProductionBuilder& productionBuilder, NonTerminal nonTerminal) :
ProductionBuilder(grammarBuilder, nonTerminal)
{}
AlternativeBuilder& term() {
return *this;
}
AlternativeBuilder& nonTerm() {
return *this;
}
virtual ~AlternativeBuilder()
{
}
};
class ProductionBuilder : public GrammarBuilder {
public:
ProductionBuilder(GrammarBuilder& grammarBuilder, NonTerminal nonTerminal) :
grammarBuilder(grammarBuilder), nonTerminal(nonTerminal) {
}
AlternativeBuilder alternative() {
return AlternativeBuilder(*this);
}
virtual ~ProductionBuilder() {
// grammar.insert(std::make_pair(nonTerminal, ))
}
protected:
GrammarBuilder& grammarBuilder;
NonTerminal nonTerminal;
// Alternative alternative;
};
class GrammarBuilder {
public:
ProductionBuilder production(NonTerminal nonTerminal) {
return ProductionBuilder(*this, nonTerminal);
}
operator Grammar() const {
return grammar;
}
protected:
private:
Grammar grammar;
};
*/
enum Action {
Shift,
Reduce,
Accept,
Error,
};
typedef int State;
typedef std::vector<State> StateStack;
typedef std::vector<State> StateTable;
const State StartState = 0;
const NonTerminal StartNonTerminal = 0;
const NonTerminal InitialNonTerminal = 1;
const NonTerminal Invalid = 0;
struct Convolution {
NonTerminal header;
GrammaticSymbols body;
explicit Convolution(NonTerminal header = Invalid, GrammaticSymbols const& body = GrammaticSymbols()) : header(header), body(body)
{}
virtual std::ostream& stringify(std::ostream& out, lexer::TerminalNames const& terminalNames, NonTerminalNames const& nonTerminalNames) {
out << nonTerminalName(header, nonTerminalNames) << " -> ";
for_each(GrammaticSymbols, body, item) {
if (item != body.begin()) out << ", ";
item->stringify(out, terminalNames, nonTerminalNames);
}
return out;
}
friend bool operator==(const Convolution& lhs, const Convolution& rhs) {
return lhs.header == rhs.header &&
lhs.body == rhs.body;
}
};
struct ParserError : std::runtime_error {
explicit ParserError(const std::string& __arg) : runtime_error(__arg) {}
};
struct ActionState {
Action action;
State state;
NonTerminal nonTerminal;
size_t reduceCount;
explicit ActionState(Action action = Error, State state = StartState, NonTerminal nonTerminal = Invalid, size_t reduceCount = 0) :
action(action), state(state), nonTerminal(nonTerminal), reduceCount(reduceCount)
{}
friend bool operator==(const ActionState& lhs, const ActionState& rhs) {
return lhs.action == rhs.action &&
lhs.state == rhs.state &&
lhs.nonTerminal == rhs.nonTerminal &&
lhs.reduceCount == rhs.reduceCount;
}
friend bool operator!=(const ActionState& lhs, const ActionState& rhs) {
return !(rhs == lhs);
}
std::ostream& stringify(std::ostream& out, NonTerminalNames const& nonTerminalNames) const {
out << "[" << (action == Shift ? "S" : action == Reduce ? "R" : action == Accept ? "A" : action == Error ? "E" : throw ParserError("invalid action"))
<< ", " << state;
if (nonTerminal == Invalid)
return out << "]";
return out << ", "
<< nonTerminalName(nonTerminal, nonTerminalNames) << ", "
<< reduceCount << "]";
}
std::string stringify(NonTerminalNames const& nonTerminalNames) const {
std::stringstream s;
stringify(s, nonTerminalNames);
return s.str();
}
};
typedef std::vector<std::vector<ActionState> > States;
class Node;
typedef std::vector<Node> Nodes;
struct Production {
NonTerminal nonTerminal; // Header
Nodes nodes; // Body
explicit Production(NonTerminal nonTerminal = Invalid, Nodes const& nodes = Nodes()) :
nonTerminal(nonTerminal), nodes(nodes) {}
};
typedef lexer::Token Token;
typedef lexer::Tokens Tokens;
class Node {
public:
explicit Node(Production const& production) : isProduction_(true), production(production) {}
explicit Node(Token const& token) : isProduction_(false), token(token) {}
bool isProduction() const {
return isProduction_;
}
Production const& getProduction() const {
return production;
}
Token const& getToken() const {
return token;
}
static std::string indent2string(int indent = 0) {
std::stringstream stream;
while (indent--)
stream << " ";
return stream.str();
}
std::ostream& stringify(std::ostream& out,
lexer::TerminalNames const& terminalNames,
NonTerminalNames const& nonTerminalNames,
int indent) const {
std::string indentation = indent2string(indent);
if (isProduction_) {
out << indentation << "+" << nonTerminalName(production.nonTerminal, nonTerminalNames) << std::endl;
for_each_c(Nodes, production.nodes, node) {
node->stringify(out, terminalNames, nonTerminalNames, indent + 1);
}
} else {
out << indentation << "+" << lexer::terminalName(token.tokenId, terminalNames) << " - " << token.value << std::endl;
}
return out;
}
std::ostream& stringify(std::ostream& out, lexer::TerminalNames const& terminalNames, NonTerminalNames const& nonTerminalNames) const {
return out << (isProduction_ ? nonTerminalName(production.nonTerminal, nonTerminalNames)
: lexer::terminalName(token.tokenId, terminalNames));
}
friend std::ostream& operator<<(std::ostream& os, const Node& node);
private:
bool isProduction_;
Production production;
Token token;
};
struct Situation : Convolution {
size_t point;
explicit Situation(NonTerminal nonTerminal = Invalid, GrammaticSymbols const& items = GrammaticSymbols()) : Convolution(nonTerminal, items), point(0) {
}
virtual std::ostream& stringify(std::ostream& out, lexer::TerminalNames const& terminalNames, NonTerminalNames const& nonTerminalNames) const {
out << nonTerminalName(header, nonTerminalNames) << " -> ";
for_each_c(GrammaticSymbols, body, item) {
if (std::distance(body.begin(), item) == point) out << "^";
out << " "
<< (item->isTerminal ? lexer::terminalName(item->value, terminalNames) : nonTerminalName(item->value, nonTerminalNames))
<< " ";
}
if (body.size() == point)
out << "^";
return out;
}
friend bool operator==(const Situation& lhs, const Situation& rhs) {
return static_cast<const Convolution&>(lhs) == static_cast<const Convolution&>(rhs) &&
lhs.point == rhs.point;
}
};
typedef std::vector<Situation> Situations;
typedef std::set<GrammaticSymbol> UniqueGrammaticSymbols;
struct CanonicalItem {
GrammaticSymbol terminal;
Situations situations;
CanonicalItem(GrammaticSymbol const& terminal, Situations const& situations) : terminal(terminal),
situations(situations) {}
std::ostream& stringify(std::ostream& out,
lexer::TerminalNames const& terminalNames,
NonTerminalNames const& nonTerminalNames) const {
terminal.stringify(out, terminalNames, nonTerminalNames) << "\n";
for_each_c(Situations, situations, s)
s->stringify(out, terminalNames, nonTerminalNames) << "\n";
return out;
}
};
typedef std::vector<CanonicalItem> CanonicalSet;
struct Pred {
Situations const& s;
explicit Pred(const Situations& s) : s(s) {}
bool operator()(CanonicalItem const& rhs) const { return s == rhs.situations; }
};
typedef std::set<lexer::Terminal> UniqueTerminals;
typedef std::set<NonTerminal> UniqueNonTerminals;
class Parser {
public:
explicit Parser(Grammar const& grammar = Grammar(),
bool debug = false,
lexer::TerminalNames const& terminalNames = lexer::TerminalNames(),
NonTerminalNames const& nonTerminalNames = NonTerminalNames()) :
states(0), terminals(0), nonTerminals(0), debug(debug), terminalNames(terminalNames),
nonTerminalNames(nonTerminalNames) {
UniqueGrammaticSymbols uniqueGrammaticSymbols;
for_each_c(Grammar, grammar, rule)
{
uniqueGrammaticSymbols.insert(GrammaticSymbol(rule->first, false));
for_each_c(Alternative, rule->second, variants)
for_each_c(GrammaticSymbols, (*variants), item)
uniqueGrammaticSymbols.insert(*item);
}
CanonicalSet canonicalSet = items(grammar, uniqueGrammaticSymbols);
UniqueTerminals uniqueTerminals;
for_each(UniqueGrammaticSymbols, uniqueGrammaticSymbols, symbol)
if (symbol->isTerminal)
uniqueTerminals.insert(symbol->value);
UniqueNonTerminals uniqueNonTerminals;
for_each(UniqueGrammaticSymbols, uniqueGrammaticSymbols, symbol)
if (!symbol->isTerminal)
uniqueNonTerminals.insert(symbol->value);
states = canonicalSet.size();
terminals = uniqueTerminals.size();
nonTerminals = uniqueNonTerminals.size();
actionTable.resize(states * terminals);
goToTable.resize(states * nonTerminals);
for_each(StateTable, goToTable, gt) *gt = -1;
for (size_t i = 0; i < canonicalSet.size(); ++i) {
for_each_c(Situations, canonicalSet.at(i).situations, situation) {
for_each(UniqueTerminals, uniqueTerminals, terminal) {
if (situation->body.size() == situation->point) {
getAction(i, *terminal).push_back(
situation->header == StartNonTerminal ? ActionState(Accept, 0, 0, 0)
: ActionState(Reduce, i, situation->header, situation->body.size()));
} else {
if (!situation->body.at(situation->point).isTerminal)
continue;
Situations goToSits = goTo(grammar, canonicalSet.at(i).situations, GrammaticSymbol(*terminal));
for (size_t j = 0; j < canonicalSet.size(); ++j) {
if (canonicalSet.at(j).situations == goToSits) {
ActionState actionState(Shift, j, 0, 0);
std::vector<ActionState>& actions = getAction(i, *terminal);
if (std::find(actions.begin(), actions.end(), actionState) == actions.end()) {
actions.push_back(actionState);
}
}
}
}
}
}
for_each(UniqueNonTerminals, uniqueNonTerminals, nonTerminal) {
Situations gts = goTo(grammar, canonicalSet.at(i).situations, GrammaticSymbol(*nonTerminal, false));
for (State j = 0; j < canonicalSet.size(); ++j) {
if (gts == canonicalSet.at(j).situations) {
getGoTo(i, *nonTerminal) = j;
}
}
}
}
if (debug) {
std::cout << "records in canonical set " << canonicalSet.size() << std::endl;
for_each(CanonicalSet, canonicalSet, item)
item->stringify(std::cout, terminalNames, nonTerminalNames) << std::endl;
dotStringify(std::cout, grammar, canonicalSet) << std::endl;
stringifyTables();
}
}
std::ostream& dotStringify(std::ostream& out, Grammar const& grammar,
CanonicalSet const& canonicalSet) {
out << "digraph CanonicalSet {" << std::endl;
for (size_t i = 0; i < canonicalSet.size(); ++i) {
out << "I" << i << "[label=\"";
for_each_c(Situations, canonicalSet.at(i).situations, sit) {
if (sit != canonicalSet.at(i).situations.begin()) out << "\n";
sit->stringify(out, terminalNames, nonTerminalNames);
}
out << "\"]\n";
}
for (size_t i = 0; i < canonicalSet.size(); ++i) {
UniqueGrammaticSymbols uniqueGrammaticSymbols;
for_each_c(Situations, canonicalSet.at(i).situations, situation) {
if (situation->body.size() == situation->point)
continue;
uniqueGrammaticSymbols.insert(situation->body.at(situation->point));
}
for_each(UniqueGrammaticSymbols, uniqueGrammaticSymbols, symbol) {
Situations goToSits = goTo(grammar, canonicalSet.at(i).situations, *symbol);
for (size_t j = 0; j < canonicalSet.size(); ++j) {
if (goToSits == canonicalSet.at(j).situations) {
out << "I" << i << " -> " << "I" << j << " [label=\""
<< (symbol->isTerminal ? lexer::terminalName(symbol->value, terminalNames)
: nonTerminalName(symbol->value, nonTerminalNames)) << "\"]" << std::endl;
}
}
}
}
out << "}";
return out;
}
CanonicalSet items(Grammar const& grammar, UniqueGrammaticSymbols const& uniqueGrammaticSymbols) {
CanonicalSet canonicalSet;
Situations situations;
Situation start(StartNonTerminal, MakeGrammaticSymbols(GrammaticSymbol(InitialNonTerminal, false)));
situations.push_back(start);
closure(situations, grammar, start);
canonicalSet.push_back(CanonicalItem(GrammaticSymbol(lexer::InvalidToken), situations));
int itemAdded;
do {
itemAdded = 0;
CanonicalSet t;
for_each(CanonicalSet, canonicalSet, canonicalItem) {
for_each(UniqueGrammaticSymbols, uniqueGrammaticSymbols, symbol) {
Situations goToSituation = goTo(grammar, canonicalItem->situations, *symbol);
if (goToSituation.empty())
continue;
if (std::find_if(canonicalSet.begin(), canonicalSet.end(), Pred(goToSituation)) == canonicalSet.end() &&
std::find_if(t.begin(), t.end(), Pred(goToSituation)) == t.end()) {
t.push_back(CanonicalItem(*symbol, goToSituation));
itemAdded++;
}
}
}
std::copy(t.begin(), t.end(), std::back_inserter(canonicalSet));
} while (itemAdded > 0);
return canonicalSet;
}
static void closure(Situations& situations, Grammar const& grammar, Situation const& situation) {
if (situation.body.size() == situation.point)
return;
if (situation.body.at(situation.point).isTerminal)
return;
Grammar::const_iterator rule = grammar.find(situation.body.at(situation.point).value);
for_each_c(Alternative, rule->second, v) {
Situation s(rule->first, *v);
if (std::find(situations.begin(), situations.end(), s) == situations.end()) {
situations.push_back(s);
closure(situations, grammar, s);
}
}
}