Repository navigation
Expand file tree
/
Copy pathparser_combined.cpp
More file actions
2036 lines (1833 loc) · 71.2 KB
/
Copy pathparser_combined.cpp
File metadata and controls
2036 lines (1833 loc) · 71.2 KB
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 ramizouari on 21/10/23.
//
#include <utility>
#include <variant>
#include <list>
#include <valarray>
//
// Created by ramizouari on 26/05/22.
//
#ifndef UTF8_LRPARSER_H
#define UTF8_LRPARSER_H
//
// Created by ramizouari on 23/05/22.
//
#ifndef UTF8_GRAMMAR_H
#define UTF8_GRAMMAR_H
#include <unordered_map>
#include <unordered_set>
#include <cstdint>
#include <vector>
#include <span>
#include <string>
#include <numeric>
#include <regex>
#include <iostream>
struct Hashable
{
std::uint64_t hash=0;
bool operator==(const Hashable & other) const=default;
auto operator<=>(const Hashable & other) const= default;
protected:
};
struct Symbol : public Hashable
{
std::uint64_t id;
explicit Symbol(std::uint64_t id=0);
bool operator==(const Symbol & other) const = default;
auto operator<=>(const Symbol & other) const = default;
std::uint64_t initHash();
private:
inline static constexpr std::hash<std::uint64_t> hasher{};
};
template<typename T>
concept isHashable = std::is_base_of_v<Hashable, std::remove_cvref_t<T>>;
template<isHashable H >
struct std::hash<H>
{
std::size_t operator()(const H & h) const
{
return h.hash;
}
};
template<typename T>
struct std::hash<std::vector<T>>
{
inline static constexpr std::hash<T> hasher{};
std::size_t operator()(const std::vector<T> & v) const
{
std::size_t hash=0;
for(auto & e : v)
hash^=hasher(e);
return hash;
}
};
template<typename A,typename B>
struct std::hash<std::pair<A,B>>
{
inline static constexpr std::hash<A> hasherA{};
inline static constexpr std::hash<B> hasherB{};
std::size_t operator()(const std::pair<A,B> & v) const
{
return hasherA(v.first)^hasherB(v.second);
}
};
template<typename T>
struct std::hash<std::unordered_set<T>>
{
inline static constexpr std::hash<T> hasher{};
std::size_t operator()(const std::unordered_set<T> & v) const
{
std::size_t hash=0;
for(auto & e : v)
hash^=hasher(e);
return hash;
}
};
struct Rule : public Hashable
{
Symbol left;
std::vector<Symbol> right;
Rule(Symbol left, const std::vector<Symbol>& right);
Rule(Symbol left, std::vector<Symbol>&& right);
bool operator==(const Rule & other) const = default;
auto operator<=>(const Rule & other) const = default;
std::uint64_t initHash();
private:
inline static constexpr std::hash<std::vector<Symbol>> hasher{};
};
class Grammar
{
protected:
std::vector<Rule> rules;
Symbol axiom;
std::vector<Symbol> symbols;
std::vector<std::vector<std::uint64_t>> ruleIdsBySymbolId;
public:
void addRule(const Rule &rule);
void addRule(Rule &&rule);
void setAxiom(const Symbol &_axiom);
virtual ~Grammar() = default;
template<typename Left, typename... Right>
void emplaceRule(Left &&left,Right &&... right)
{
rules.template emplace_back(std::forward(left),{std::forward(right)...});
}
template<typename Left,typename Right>
void addRule(Left &&left,Right &&right)
{
rules.template emplace_back(std::forward(left),std::forward(right));
}
[[nodiscard]] const std::vector<Rule> & getRules() const;
};
enum SpecialCharacter : std::uint64_t
{
Epsilon=std::numeric_limits<std::uint64_t>::max()-2,
EndOfString,
Empty=Epsilon,
EndOfFile=EndOfString
};
class GrammarWithFirstFollow : virtual public Grammar
{
protected:
std::vector<std::unordered_set<std::uint64_t>> firstIds,followIds;
virtual void buildFirst();
virtual void buildFollow();
};
template<typename CharType,typename Traits=std::char_traits<CharType>>
class StringParser : virtual protected Grammar
{
protected:
using stringType=std::basic_string<CharType,Traits>;
static std::vector<stringType> split(const stringType &S,const stringType ®ex)
{
std::basic_regex<CharType,std::regex_traits<CharType>> rgx(regex);
std::regex_token_iterator<typename stringType::const_iterator> iter(S.begin(),
S.end(),
rgx,
-1),
end;
std::vector<stringType> result(iter, end);
if(result.front().empty())
return {};
return result;
}
std::unordered_map<Symbol,std::uint64_t> symbolId;
std::unordered_map<stringType,std::uint64_t> symbolMap;
Symbol& addSymbol(const stringType & s)
{
auto it=symbolMap.find(s);
if(it==symbolMap.end())
{
Symbol S{symbolId.size()};
symbols.push_back(S);
symbolMap[s]=symbolId.size();
symbolId[S]=S.id;
return symbols.back();
}
else return symbols[it->second];
}
public:
void addRuleList(const stringType &left,const std::vector<stringType> &right)
{
Symbol L=addSymbol(left);
std::vector<Symbol> R;
for(const auto & s : right)
R.push_back(addSymbol(s));
Rule rule{L,R};
Grammar::addRule(std::move(rule));
}
template<typename Left,typename... Right>
void addRuleList(Left && left, Right && ... right)
{
auto S=addSymbol(std::forward<Left>(left));
std::vector<Symbol> rightVec{addSymbol(std::forward<Right>(right))...};
Rule rule(S,rightVec);
Grammar::addRule(std::move(rule));
}
virtual void addRule(const std::basic_string<CharType,Traits> &line)
{
std::basic_regex<CharType,std::regex_traits<CharType>> ruleRegex(R"(\s*([^\s]+)\s*(?:->|:|:==)\s*((?:[^\s]\s+)*(?:[^\s]+)|)\s*)");
std::match_results<typename stringType::const_iterator> ruleMatch;
if(std::regex_match(line,ruleMatch,ruleRegex))
{
std::vector<Symbol> rightSymbols;
Symbol leftSymbol=addSymbol(ruleMatch[1]);
std::cout << ruleMatch[2] << std::endl;
for(const auto &s : split(ruleMatch[2],R"(\s+)"))
rightSymbols.push_back(addSymbol(s));
Rule rule(leftSymbol,rightSymbols);
Grammar::addRule(std::move(rule));
}
else
throw std::runtime_error("Invalid rule");
}
//virtual void addRule(std::basic_string<CharType,Traits> &&line) = 0;
virtual bool parse(const std::basic_string<CharType,Traits> &line)=0;
};
#endif //UTF8_GRAMMAR_H
//
// Created by ramizouari on 20/10/23.
//
#ifndef CPLIBRARY_STATEFULPARSER_H
#define CPLIBRARY_STATEFULPARSER_H
namespace parser
{
struct Variable
{
virtual ~Variable() = default;
};
struct VariableReducer
{
virtual ~VariableReducer() = default;
virtual std::shared_ptr<Variable> combine(const std::vector<std::shared_ptr<Variable>>& symbols) const = 0;
};
namespace reducers
{
struct NullReducer final: public VariableReducer
{
[[nodiscard]] std::shared_ptr<Variable> combine(const std::vector<std::shared_ptr<Variable>>& symbols) const
{
return nullptr;
}
inline static std::shared_ptr<VariableReducer> instance = std::make_shared<NullReducer>();
};
struct Projection : public VariableReducer
{
std::int64_t index;
[[nodiscard]] std::shared_ptr<Variable> combine(const std::vector<std::shared_ptr<Variable>>& symbols) const
{
return symbols.at(index);
}
explicit Projection(std::int64_t index) : index(index){}
};
struct Identity : public Projection
{
Identity(): Projection(0){}
inline static std::shared_ptr<VariableReducer> instance = std::make_shared<Identity>();
};
struct IdentityOrNull : public VariableReducer
{
[[nodiscard]] std::shared_ptr<Variable> combine(const std::vector<std::shared_ptr<Variable>>& symbols) const
{
return symbols.empty() ? nullptr : symbols.front();
}
inline static std::shared_ptr<VariableReducer> instance = std::make_shared<IdentityOrNull>();
};
}
template<typename CharType,typename Traits=std::char_traits<CharType>>
class StatefulStringParser : virtual protected StringParser<CharType,Traits>
{
protected:
std::vector<std::shared_ptr<VariableReducer>> reducers;
public:
using stringType=StringParser<CharType,Traits>::stringType;
void addRuleList(std::shared_ptr<VariableReducer> reducer,const stringType &left,const std::vector<stringType> &right)
{
StringParser<CharType,Traits>::addRule(left,right);
reducers.push_back(reducer);
}
void addRuleList(const stringType &left,const std::vector<stringType> &right)
{
addRuleList(reducers::Identity::instance,left,right);
}
virtual void addRule(std::shared_ptr<VariableReducer> reducer, const std::basic_string<CharType,Traits> &line)
{
StringParser<CharType,Traits>::addRule(line);
reducers.push_back(reducer);
}
template<typename Left,typename... Right>
void addRuleList(std::shared_ptr<VariableReducer> reducer,Left && left, Right && ... right)
{
StringParser<CharType,Traits>::addRuleList(std::forward<Left>(left),std::forward<Right>(right)...);
reducers.push_back(reducer);
}
void addRule(const std::basic_string<CharType,Traits> &line) override
{
addRule(reducers::IdentityOrNull::instance,line);
}
//virtual void addRule(std::basic_string<CharType,Traits> &&line) = 0;
virtual std::shared_ptr<Variable> evaluate(const std::basic_string<CharType,Traits> &line)=0;
};
}
#endif //CPLIBRARY_STATEFULPARSER_H
/*
* This header contains the implementations of LR(1) family parsers.
* The implementation is based on the theory of the LR(1) parser.
*
* The supported parsers are:
* - SLR(1)
* - LALR(1)
* - LR(1)
* */
namespace parser {
struct LR0Item : public Hashable
{
std::uint64_t ruleId;
std::uint64_t dot;
explicit LR0Item(std::uint64_t ruleId,std::uint64_t dot);
bool operator==(const LR0Item & other) const = default;
auto operator<=>(const LR0Item & other) const = default;
std::uint64_t initHash();
private:
inline static constexpr std::hash<std::uint64_t> hasher{};
};
struct LR1Item : public Hashable
{
std::uint64_t ruleId;
std::uint64_t dot;
std::uint64_t lookahead;
explicit LR1Item(std::uint64_t ruleId,std::uint64_t dot,std::uint64_t lookahead);
bool operator==(const LR1Item & other) const = default;
auto operator<=>(const LR1Item & other) const = default;
std::uint64_t initHash();
private:
inline static constexpr std::hash<std::uint64_t> hasher{};
};
struct LALR1Item : public Hashable
{
std::uint64_t ruleId;
std::uint64_t dot;
mutable std::unordered_set<std::uint64_t> lookahead;
explicit LALR1Item(std::uint64_t ruleId,std::uint64_t dot,std::unordered_set<std::uint64_t>&& lookahead);
explicit LALR1Item(std::uint64_t ruleId,std::uint64_t dot,const std::unordered_set<std::uint64_t>& lookahead);
bool operator==(const LALR1Item & other) const;
std::uint64_t initHash();
};
namespace LRFamily
{
struct Action
{
enum Type
{
Shift,
Reduce,
Accept,
Error
};
Type type;
std::uint64_t value;
Action(Type type,std::uint64_t value);
};
struct LALR1ItemContext
{
std::uint64_t id;
std::unordered_set<std::uint64_t> lookaheads;
explicit LALR1ItemContext(std::uint64_t id,std::unordered_set<std::uint64_t> &&lookaheads);
explicit LALR1ItemContext(std::uint64_t id,const std::unordered_set<std::uint64_t> &lookaheads);
};
}
class ShiftReduceParser :virtual public StringParser<char>
{
public:
using Action=LRFamily::Action;
void printTable(std::ostream &H) const;
bool parse(const std::string &s) override;
//bool parse(std::uint64_t symbolId);
protected:
std::unordered_map<std::pair<std::uint64_t,std::uint64_t>,Action> gotoIds;
};
class LRFamilyBuilder
{
virtual LRFamilyBuilder& build() & = 0;
};
class LR0ParserBuilder: public ShiftReduceParser, public LRFamilyBuilder
{
std::unordered_map<std::unordered_set<LR0Item>,int> lr0ItemsIds;
std::vector<std::unordered_set<LR0Item>> lr0Items;
std::vector<bool> isTerminal;
std::unordered_set<LR0Item> closure(const std::unordered_set<LR0Item> &item);
public:
LR0ParserBuilder& build() &;
};
class SLRParserBuilder: protected GrammarWithFirstFollow, public ShiftReduceParser, public LRFamilyBuilder
{
using Action=LRFamily::Action;
std::unordered_map<std::unordered_set<LR0Item>,int> lr0ItemsIds;
std::vector<std::unordered_set<LR0Item>> lr0Items;
std::vector<bool> isTerminal;
std::unordered_set<LR0Item> closure(const std::unordered_set<LR0Item> &item);
public:
SLRParserBuilder& build() &;
};
class LRParserBuilder: virtual protected GrammarWithFirstFollow, virtual public ShiftReduceParser, public LRFamilyBuilder
{
using Action=LRFamily::Action;
std::unordered_map<std::unordered_set<LR1Item>,int> lr1ItemsIds;
std::vector<std::unordered_set<LR1Item>> lr1Items;
std::vector<bool> isTerminal;
std::unordered_set<LR1Item> closure(const std::unordered_set<LR1Item> &item);
public:
//bool parse(const std::string &s) override;
LRParserBuilder& build() &;
};
class LALRParserBuilder: virtual protected GrammarWithFirstFollow, virtual public ShiftReduceParser, public LRFamilyBuilder
{
using Action=LRFamily::Action;
using LRLALR1ItemContext=LRFamily::LALR1ItemContext;
std::unordered_map<std::unordered_set<LALR1Item>,std::uint64_t> lr1ItemsIds;
std::vector<std::unordered_set<LALR1Item>> lr1Items;
std::vector<bool> isTerminal;
std::unordered_set<LALR1Item> closure(const std::unordered_set<LALR1Item> &item);
public:
LALRParserBuilder& build() &;
};
class ArithmeticParser : public LRParserBuilder
{
public:
};
class StatefulShiftReduceParser : virtual public StatefulStringParser<char>
{
public:
using Action=LRFamily::Action;
std::shared_ptr<Variable> evaluate(const std::string &s) override;
using IdsMapType = std::unordered_map<std::pair<std::uint64_t,std::uint64_t>,Action>;
explicit StatefulShiftReduceParser(IdsMapType &gotoIds);
protected:
IdsMapType& gotoIds;
};
struct StatefulLR0ParserBuilder: public LR0ParserBuilder , public StatefulShiftReduceParser
{
StatefulLR0ParserBuilder();
};
struct StatefulSLRParserBuilder: public SLRParserBuilder , public StatefulShiftReduceParser
{
StatefulSLRParserBuilder();
};
struct StatefulLALRParserBuilder: virtual public LALRParserBuilder , virtual public StatefulShiftReduceParser
{
StatefulLALRParserBuilder();
};
struct StatefulLRParserBuilder: virtual public LRParserBuilder , virtual public StatefulShiftReduceParser
{
StatefulLRParserBuilder();
};
} // parser
#endif //UTF8_LRPARSER_H
#define NO_ASSIGNMENT ""
#define OUTPUT_CODE "output"
#define OUTPUT_SYMBOL "#"
#define RETURN_CODE "return"
#define RETURN_SYMBOL "@"
template<typename T>
struct Type : public parser::Variable
{
T value;
explicit Type(T value):value(std::move(value)){}
Type() = default;
};
using StringValue = Type<std::string>;
using IntValue = Type<std::int64_t>;
struct CharacterGenerator : public parser::VariableReducer
{
char c;
explicit CharacterGenerator(char c):c(c){}
[[nodiscard]] std::shared_ptr<parser::Variable> combine(const std::vector<std::shared_ptr<parser::Variable>> & variables) const override
{
return std::make_shared<StringValue>(std::string(1,c));
}
};
struct NameConcat : public parser::VariableReducer
{
char suffix;
explicit NameConcat(char suffix): suffix(suffix){}
[[nodiscard]] std::shared_ptr<parser::Variable> combine(const std::vector<std::shared_ptr<parser::Variable>> & variables) const override
{
auto name = std::dynamic_pointer_cast<StringValue>(variables.at(0));
name->value.push_back(suffix);
return name;
}
};
struct LastProjection : public parser::VariableReducer
{
[[nodiscard]] std::shared_ptr<parser::Variable> combine(const std::vector<std::shared_ptr<parser::Variable>> & variables) const override
{
return variables.back();
}
};
struct ListNames : public parser::VariableReducer
{
[[nodiscard]] std::shared_ptr<parser::Variable> combine(const std::vector<std::shared_ptr<parser::Variable>> &v) const override
{
using Vector = Type<std::vector<std::string>>;
auto& top = std::dynamic_pointer_cast<Vector>(v.front())->value;
auto& last= std::dynamic_pointer_cast<StringValue>(v.back())->value;
top.push_back(last);
return v.front();
}
};
template<typename T>
struct DefaultGenerator : public parser::VariableReducer
{
[[nodiscard]] std::shared_ptr<parser::Variable> combine(const std::vector<std::shared_ptr<parser::Variable>> &v) const override
{
return std::make_shared<T>();
}
};
template<typename T>
struct ToList : public parser::VariableReducer
{
[[nodiscard]] std::shared_ptr<parser::Variable> combine(const std::vector<std::shared_ptr<parser::Variable>> &v) const override
{
using Vector = Type<std::vector<T>>;
auto x= std::make_shared<Vector>();
x->value.push_back(std::dynamic_pointer_cast<Type<T>>(v.front())->value);
return x;
}
};
class ExecutionGraph;
class ExpressionTree;
struct FunctionDefinition : public parser::Variable
{
std::shared_ptr<StringValue> fn_name;
std::shared_ptr<Type<std::vector<std::string>>> formal_parameters;
std::shared_ptr<ExecutionGraph> graph;
std::int64_t evaluate(class Context & context);
};
struct FunctionCall : public parser::Variable
{
std::string name;
std::vector<std::shared_ptr<ExpressionTree>> parameters;
};
struct FnDefGenerator : public parser::VariableReducer
{
[[nodiscard]] std::shared_ptr<parser::Variable> combine(const std::vector<std::shared_ptr<parser::Variable>> &v) const override
{
auto x= std::make_shared<FunctionDefinition>();
x->fn_name = std::dynamic_pointer_cast<StringValue>(v.at(0));
x->formal_parameters = std::dynamic_pointer_cast<Type<std::vector<std::string>>>(v.at(1));
x->graph = std::dynamic_pointer_cast<ExecutionGraph>(v.at(2));
return x;
}
};
class ExpressionTree;
struct Context
{
std::vector<std::map<std::string, std::int64_t>> variables_stack;
std::map<std::string,std::vector<std::int64_t>> variables_index;
std::map<std::string, std::shared_ptr<FunctionDefinition>> functions;
Context() : variables_stack(1) {}
void push()
{
variables_stack.emplace_back();
}
void pop()
{
for(auto &x: variables_stack.back())
{
variables_index[x.first].pop_back();
if(variables_index[x.first].empty())
variables_index.erase(x.first);
}
variables_stack.pop_back();
}
std::int64_t& get_variable(const std::string &name)
{
return variables_stack[variables_index.at(name).back()].at(name);
}
std::int64_t& upsert_variable(const std::string &name, std::int64_t value=0)
{
if(variables_index.find(name)==variables_index.end())
variables_index[name]=std::vector<std::int64_t>(1,variables_stack.size()-1);
else if(variables_index.at(name).back()!=variables_stack.size()-1)
variables_index.at(name).push_back(variables_stack.size()-1);
variables_stack.back()[name]=value;
return variables_stack.back().at(name);
}
std::int64_t& get_variable(const std::string &name, int index)
{
return variables_stack[variables_index.at(name).at(index)].at(name);
}
};
class FunctionCall;
struct ExpressionNode
{
enum Operation
{
Add,
Sub,
Mul,
Div,
Mod,
Pow,
Concat,
Number,
Variable,
FunCall
};
Operation op;
std::shared_ptr<ExpressionNode> lhs,rhs;
std::variant<std::string, std::int64_t,FunctionCall> value;
std::int64_t evaluate(Context &context);
};
struct ExpressionTree : public parser::Variable
{
std::shared_ptr<ExpressionNode> root;
std::int64_t evaluate(Context &context)
{
return root->evaluate(context);
}
};
std::int64_t power(std::int64_t a, std::int64_t n)
{
if(n==0)
return 1;
else if(n==1)
return a;
auto s=power(a,n/2);
return n%2?s*s*a:s*s;
}
std::int64_t ExpressionNode::evaluate(Context &context)
{
switch(op)
{
case Add:
return lhs->evaluate(context)+rhs->evaluate(context);
case Sub:
return lhs->evaluate(context)-rhs->evaluate(context);
case Mul:
return lhs->evaluate(context)*rhs->evaluate(context);
case Div:
return lhs->evaluate(context)/rhs->evaluate(context);
case Mod:
return lhs->evaluate(context)%rhs->evaluate(context);
case Concat:
return lhs->evaluate(context)*std::pow(10,rhs->evaluate(context));
case Pow:
return power(lhs->evaluate(context),rhs->evaluate(context));
case Number:
return std::get<std::int64_t>(value);
case Variable:
return context.get_variable(std::get<std::string>(value));
case FunCall:
{
// Context new_context;
// new_context.functions = context.functions;
// auto fn_call = std::get<FunctionCall>(value);
// auto fn = new_context.functions.at(fn_call.name);
// for(int i=0;i<fn->formal_parameters->value.size();i++)
// new_context.variables[fn->formal_parameters->value[i]] = fn_call.parameters[i]->evaluate(context);
// return fn->evaluate(new_context);
auto fn_call = std::get<FunctionCall>(value);
auto fn = context.functions.at(fn_call.name);
std::vector<std::int64_t> parameters;
parameters.reserve(fn_call.parameters.size());
for(auto &x:fn_call.parameters)
parameters.push_back(x->evaluate(context));
context.push();
for(int i=0;i<fn->formal_parameters->value.size();i++)
context.upsert_variable(fn->formal_parameters->value[i],parameters[i]);
auto result = fn->evaluate(context);
context.pop();
return result;
}
}
}
struct CallParams : public parser::Variable
{
std::vector<std::shared_ptr<ExpressionTree>> parameters;
};
struct ConcatenateCallParams : public parser::VariableReducer
{
[[nodiscard]] std::shared_ptr<parser::Variable> combine(const std::vector<std::shared_ptr<parser::Variable>> &v) const override
{
auto x= std::dynamic_pointer_cast<CallParams>(v.at(0));
x->parameters.push_back(std::dynamic_pointer_cast<ExpressionTree>(v.at(2)));
return x;
}
};
struct Statement : public parser::Variable
{
std::string lhs;
std::shared_ptr<ExpressionTree> rhs;
std::int64_t evaluate(Context &context)
{
// auto result=context.variables[lhs] = rhs->evaluate(context);
auto result=context.upsert_variable(lhs) = rhs->evaluate(context);
if(lhs==OUTPUT_SYMBOL)
std::cout << result << '\n';
return result;
}
};
struct ExecutionGraph : public parser::Variable
{
std::vector<std::shared_ptr<Statement>> statements;
};
std::int64_t FunctionDefinition::evaluate(Context &context)
{
std::int64_t result;
for(auto statement : graph->statements)
result = statement->evaluate(context);
return result;
}
using Number = Type<std::int64_t>;
struct NumberGenerator : public parser::VariableReducer
{
std::int64_t v;
public:
NumberGenerator(std::int64_t v):v(v){}
[[nodiscard]] std::shared_ptr<parser::Variable> combine(const std::vector<std::shared_ptr<parser::Variable>> & variables) const override
{
return std::make_shared<Number>(v);
}
};
struct NumberConcatenation : public parser::VariableReducer
{
[[nodiscard]] std::shared_ptr<parser::Variable> combine(const std::vector<std::shared_ptr<parser::Variable>> & variables) const override
{
return std::make_shared<Number>(10*std::dynamic_pointer_cast<Number>(variables.at(0))->value + std::dynamic_pointer_cast<Number>(variables.at(1))->value);
}
};
struct ExpressionTreeBuilder : public parser::VariableReducer
{
ExpressionNode::Operation op;
explicit ExpressionTreeBuilder(ExpressionNode::Operation op):op(op){}
[[nodiscard]] std::shared_ptr<parser::Variable> combine(const std::vector<std::shared_ptr<parser::Variable>> & variables) const override
{
auto x= std::make_shared<ExpressionTree>();
x->root = std::make_shared<ExpressionNode>();
x->root->op = op;
x->root->lhs = std::dynamic_pointer_cast<ExpressionTree>(variables.at(0))->root;
x->root->rhs = std::dynamic_pointer_cast<ExpressionTree>(variables.at(2))->root;
return x;
}
};
struct FunctionCallBuilder : public parser::VariableReducer
{
[[nodiscard]] std::shared_ptr<parser::Variable> combine(const std::vector<std::shared_ptr<parser::Variable>> &v) const override
{
auto tree = std::make_shared<ExpressionTree>();
FunctionCall fn_call;
fn_call.name = std::dynamic_pointer_cast<StringValue>(v.at(0))->value;
if(v.size()==4)
fn_call.parameters = std::dynamic_pointer_cast<CallParams>(v.at(2))->parameters;
else if(v.size()!=3)
throw std::runtime_error("invalid function call");
tree->root = std::make_shared<ExpressionNode>();
tree->root->lhs=nullptr;
tree->root->rhs=nullptr;
tree->root->op = ExpressionNode::FunCall;
tree->root->value.emplace<FunctionCall>(std::move(fn_call));
return tree;
}
};
struct NumberToLeaf : public parser::VariableReducer
{
[[nodiscard]] std::shared_ptr<parser::Variable> combine(const std::vector<std::shared_ptr<parser::Variable>> &v) const override
{
auto x= std::make_shared<ExpressionTree>();
x->root = std::make_shared<ExpressionNode>();
x->root->op = ExpressionNode::Number;
x->root->value = std::dynamic_pointer_cast<Number>(v.at(0))->value;
return x;
}
};
struct VariableToLeaf : public parser::VariableReducer
{
[[nodiscard]] std::shared_ptr<parser::Variable> combine(const std::vector<std::shared_ptr<parser::Variable>> &v) const override
{
auto x= std::make_shared<ExpressionTree>();
x->root = std::make_shared<ExpressionNode>();
x->root->op = ExpressionNode::Variable;
x->root->value = std::dynamic_pointer_cast<StringValue>(v.at(0))->value;
return x;
}
};
struct StatementBuilder : public parser::VariableReducer
{
std::shared_ptr<parser::Variable> combine(const std::vector<std::shared_ptr<parser::Variable>> &v) const override
{
auto x= std::make_shared<Statement>();
x->lhs = std::dynamic_pointer_cast<StringValue>(v.at(0))->value;
x->rhs = std::dynamic_pointer_cast<ExpressionTree>(v.at(2));
return x;
}
};
struct StatementConcat : public parser::VariableReducer
{
[[nodiscard]] std::shared_ptr<parser::Variable> combine(const std::vector<std::shared_ptr<parser::Variable>> &v) const override
{
auto x= std::dynamic_pointer_cast<ExecutionGraph>(v.at(0));
x->statements.push_back(std::dynamic_pointer_cast<Statement>(v.at(2)));
return x;
}
};
struct FunctionsBlock : public parser::Variable
{
std::map<std::string, std::shared_ptr<FunctionDefinition>> functions;
};
struct FunctionsBlockConcat : public parser::VariableReducer
{
[[nodiscard]] std::shared_ptr<parser::Variable> combine(const std::vector<std::shared_ptr<parser::Variable>> &v) const override
{
auto x= std::dynamic_pointer_cast<FunctionsBlock>(v.at(0));
auto fn_def=std::dynamic_pointer_cast<FunctionDefinition>(v.at(2));
x->functions.insert(std::make_pair(fn_def->fn_name->value, fn_def));
return x;
}
};
struct FunctionsBlockBuilder : public parser::VariableReducer
{
std::shared_ptr<parser::Variable> combine(const std::vector<std::shared_ptr<parser::Variable>> &v) const override
{
auto x= std::make_shared<FunctionsBlock>();
x->functions.insert(std::make_pair(std::dynamic_pointer_cast<FunctionDefinition>(v.at(0))->fn_name->value, std::dynamic_pointer_cast<FunctionDefinition>(v.at(0))));
return x;
}
};
struct MainProgram : public parser::Variable
{
std::shared_ptr<ExecutionGraph> main;
std::shared_ptr<Context> context;
std::int64_t evaluate()
{
std::int64_t result;
for(auto statement : main->statements)
result = statement->evaluate(*context);
return result;
}
};
struct PrepareExecution : public parser::VariableReducer
{
[[nodiscard]] std::shared_ptr<parser::Variable> combine(const std::vector<std::shared_ptr<parser::Variable>> &v) const override
{
auto x= std::make_shared<MainProgram>();
x->context = std::make_shared<Context>();
if(v.size()==3)
{
x->main = std::dynamic_pointer_cast<ExecutionGraph>(v.at(2));
x->context->functions = std::move(std::dynamic_pointer_cast<FunctionsBlock>(v.at(0))->functions);
}
else x->main = std::dynamic_pointer_cast<ExecutionGraph>(v.at(0));
return x;
}
};
struct PrepareFunctionBody :public parser::VariableReducer
{
[[nodiscard]] std::shared_ptr<parser::Variable> combine(const std::vector<std::shared_ptr<parser::Variable>> &v) const override
{
std::shared_ptr<ExecutionGraph> x;
if(v.size()>1)
{
x=std::dynamic_pointer_cast<ExecutionGraph>(v.front());
x->statements.push_back(std::make_shared<Statement>());
x->statements.back()->lhs=NO_ASSIGNMENT;
x->statements.back()->rhs=std::dynamic_pointer_cast<ExpressionTree>(v.at(2));
}
else
{
x=std::make_shared<ExecutionGraph>();
x->statements.push_back(std::make_shared<Statement>());
x->statements.back()->lhs=NO_ASSIGNMENT;
x->statements.back()->rhs=std::dynamic_pointer_cast<ExpressionTree>(v.at(0));
}
return x;
}
};
struct ToListStatement : public parser::VariableReducer
{
[[nodiscard]] std::shared_ptr<parser::Variable> combine(const std::vector<std::shared_ptr<parser::Variable>> &v) const override
{