This repository was archived by the owner on Mar 14, 2026. It is now read-only.
Repository navigation
Expand file tree
/
Copy pathmain.cpp
More file actions
2488 lines (2028 loc) · 86.5 KB
/
Copy pathmain.cpp
File metadata and controls
2488 lines (2028 loc) · 86.5 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
#include <cassert>
#include <cstring>
#include <fstream>
#include <iostream>
#include <list>
#include <memory>
#include <sstream>
#include <string>
#include <unordered_map>
#include <vector>
using namespace std;
using integer = int64_t;
template<typename Derived, typename Base,
typename enable_if<is_base_of<Base, Derived>::value>::type* = nullptr>
inline bool typeis(Base& a1) {
return typeid(a1) == typeid(Derived);
}
template<typename Exception, typename... Args,
typename enable_if<is_base_of<runtime_error, Exception>::value>::type* = nullptr>
inline void assert_throw(bool expr, Args&&... args) { if (!expr) throw Exception(args...); }
namespace WS {
enum struct Chr {
SP = 0, // space
TB, // tab
LF // line feed
};
struct WhiteSpace {
vector<Chr> raw;
WhiteSpace() :raw() {}
inline void push(Chr c) {
raw.push_back(c);
}
inline void push(initializer_list<Chr> cl) {
for (auto c : cl) push(c);
}
template<size_t size>
inline void push(const Chr(&cl)[size]) {
for (auto c : cl) push(c);
}
inline void push(int c) {
raw.push_back(static_cast<Chr>(c));
}
inline void push(initializer_list<int> cl) {
for (auto c : cl) push(static_cast<Chr>(c));
}
inline void push(const WhiteSpace& ws) {
raw.insert(raw.end(), ws.raw.begin(), ws.raw.end());
}
inline void print(ostream& os) const {
static const char convert[] = { 32,9,10,0,0,0,0,0 };
for (auto c : raw)
os << convert[static_cast<size_t>(c)];
}
};
inline ostream& operator <<(ostream& os, WhiteSpace& ws) { ws.print(os); return os; }
namespace Instruments {
namespace Stack {
const Chr push[] = { Chr::SP, Chr::SP }; // prm
const Chr duplicate[] = { Chr::SP, Chr::LF, Chr::SP };
const Chr copy[] = { Chr::SP, Chr::TB, Chr::SP }; // prm
const Chr swap[] = { Chr::SP, Chr::LF, Chr::TB };
const Chr discard[] = { Chr::SP, Chr::LF, Chr::LF };
// const Chr slide[] = { Chr::SP, Chr::TB, Chr::LF }; // prm
}
namespace Arithmetic {
const Chr add[] = { Chr::TB, Chr::SP, Chr::SP, Chr::SP };
const Chr sub[] = { Chr::TB, Chr::SP, Chr::SP, Chr::TB };
const Chr mul[] = { Chr::TB, Chr::SP, Chr::SP, Chr::LF };
const Chr div[] = { Chr::TB, Chr::SP, Chr::TB, Chr::SP };
const Chr mod[] = { Chr::TB, Chr::SP, Chr::TB, Chr::TB };
}
namespace Heap {
const Chr store[] = { Chr::TB, Chr::TB, Chr::SP }; // push the address then the value and run the store command.
const Chr retrieve[] = { Chr::TB, Chr::TB, Chr::TB };
}
namespace Flow {
const Chr label[] = { Chr::LF, Chr::SP, Chr::SP }; // prm
const Chr call[] = { Chr::LF, Chr::SP, Chr::TB }; // prm
const Chr jump[] = { Chr::LF, Chr::SP, Chr::LF }; // prm
const Chr zerojump[] = { Chr::LF, Chr::TB, Chr::SP }; // prm
const Chr negativejump[] = { Chr::LF, Chr::TB, Chr::TB }; // prm
const Chr retun[] = { Chr::LF, Chr::TB, Chr::LF };
const Chr exit[] = { Chr::LF, Chr::LF, Chr::LF };
}
namespace IO {
const Chr putchar[] = { Chr::TB, Chr::LF, Chr::SP, Chr::SP };
const Chr putnumber[] = { Chr::TB, Chr::LF, Chr::SP, Chr::TB };
const Chr getchar[] = { Chr::TB, Chr::LF, Chr::TB, Chr::SP };
const Chr getnumber[] = { Chr::TB, Chr::LF, Chr::TB, Chr::TB };
}
}
WhiteSpace& pushInteger(WhiteSpace& whitesp, integer val) {
if (val < 0) {
whitesp.push(Chr::TB);
val = -val;
}
else {
whitesp.push(Chr::SP);
}
uint64_t uval = val, rev = 0;
int len = 0;
while (uval) {
rev = (rev << 1) | (uval & 1);
uval >>= 1;
++len;
}
while (len--) {
whitesp.push(rev & 1);
rev >>= 1;
}
whitesp.push(Chr::LF);
return whitesp;
}
}
namespace Parser {
struct ParseException : runtime_error {
ParseException(const char* msg = "") :runtime_error(msg) { }
};
struct Token {
virtual ~Token() {}
virtual bool operator==(const Token&) const = 0;
virtual bool operator==(const string&) const = 0;
virtual bool operator==(char) const = 0;
virtual void print(ostream&) const = 0;
};
inline ostream& operator<<(ostream& os, const Token& token) {
token.print(os); return os;
}
class TokenStream {
vector<unique_ptr<Token>> tokens_;
size_t ptr;
public:
TokenStream() :ptr(0) {}
TokenStream(vector<unique_ptr<Token>>&& _tokens) :tokens_(move(_tokens)), ptr(0) { }
const Token& get() { return *tokens_[ptr++]; }
TokenStream& seekg(size_t pos) { ptr = pos; return *this; }
const Token& peek() const { return *tokens_[ptr]; }
const bool eof() const { return ptr >= tokens_.size(); }
void print(ostream& os, int front = 0, int back = 0) const {
int head = max((int)ptr - front, 0);
int tail = min((int)ptr + back, (int)(tokens_.size()) - 1);
for (; head <= tail; ++head)
os << *tokens_[head] << ' ';
}
};
class TokenInteger : public Token {
const integer value_;
public:
TokenInteger(integer _val) :value_(_val) {}
inline integer get() const { return value_; }
inline bool operator==(const TokenInteger& t) const {
return value_ == t.value_;
}
inline bool operator==(const string& str) const override {
return false;
}
inline bool operator==(char) const override {
return false;
}
inline bool operator==(const Token& t) const override {
try {
return operator==(dynamic_cast<const TokenInteger&>(t));
}
catch (const bad_cast& _) {
return false;
}
}
inline void print(ostream& os) const override {
os << value_;
}
};
class TokenKeyword : public Token {
const string keyword_;
public:
TokenKeyword(string _keyword) :keyword_(_keyword) {}
inline const string& str() const { return keyword_; }
inline bool operator==(const TokenKeyword& t) const {
return keyword_ == t.keyword_;
}
inline bool operator==(const string& str) const override {
return keyword_ == str;
}
inline bool operator==(char c) const override {
return keyword_.size() == (size_t)1 && keyword_[0] == c;
}
inline bool operator==(const Token& t) const override {
try {
return operator==(dynamic_cast<const TokenKeyword&>(t));
}
catch (const bad_cast& _) {
return false;
}
}
inline void print(ostream& os) const override {
os << keyword_;
}
};
class TokenSymbol : public Token {
const char _symbol[4];
public:
TokenSymbol(char _s1) :_symbol{ _s1,0,0,0 } {}
TokenSymbol(char _s1, char _s2) :_symbol{ _s1,_s2,0 } {}
TokenSymbol(char _s1, char _s2, char _s3) :_symbol{ _s1,_s2,_s3,0 } {}
inline bool operator==(const TokenSymbol& t) const {
return strcmp(_symbol, t._symbol) == 0;
}
inline bool operator==(char c) const override {
return _symbol[0] == c && _symbol[1] == 0;
}
inline bool operator==(const string& str) const override {
return _symbol == str;
}
inline bool operator==(const Token& t) const override {
try {
return operator==(dynamic_cast<const TokenSymbol&>(t));
}
catch (const bad_cast& _) {
return false;
}
}
inline void print(ostream& os) const override {
for (int i = 0; i < 4 && _symbol[i]; ++i)
os << _symbol[i];
}
};
TokenInteger parseInteger(istream& is) {
integer var = 0;
int cc = is.peek();
for (; isdigit(cc) && cc != istream::traits_type::eof(); is.get(), cc = is.peek())
var = (var << 3) + (var << 1) + cc - '0';
return TokenInteger(var);
}
TokenKeyword parseKeyword(istream& is) {
string str;
int cc = is.peek();
for (; (isdigit(cc) || isalpha(cc) || cc == '_') &&
cc != istream::traits_type::eof(); is.get(), cc = is.peek())
str.push_back(cc);
return TokenKeyword(str);
}
TokenSymbol parseSymbol(istream& is) {
int c1 = is.get();
int c2 = is.peek();
if (c1 == '|' && c2 == '|') {
is.get(); return TokenSymbol('|', '|');
}
if (c1 == '&') {
if (c2 == '&') { is.get(); return TokenSymbol('&', '&'); }
return TokenSymbol('&');
}
if (c1 == '+' || c1 == '-' || c1 == '*' || c1 == '/' || c1 == '%' ||
c1 == '=' || c1 == '!' || c1 == '<' || c1 == '>') {
if (c2 == '=') {
is.get(); return TokenSymbol(c1, '=');
}
return TokenSymbol(c1);
}
if (c1 == '(' || c1 == ')' || c1 == '[' || c1 == ']' ||
c1 == '{' || c1 == '}' || c1 == ':' || c1 == ';' || c1 == ',') {
return TokenSymbol(c1);
}
throw ParseException("invalid symbol");
}
TokenInteger parseChar(istream& is) {
is.get(); // '
integer var = 0;
int cc;
bool escape = false;
while (cc = is.get(), escape || cc != '\'') {
if (is.eof()) throw ParseException("missing [']");
if (!escape) {
if (cc == '\\') escape = true;
else if (cc == '\t') throw ParseException("unescaped tab");
else if (cc == '\n') throw ParseException("unescaped LF");
else if (cc == ' ') throw ParseException("unescaped space");
else var = (var << 8ll) | integer(cc);
}
else {
if (cc == '\\') var = (var << 8ll) | '\\';
else if (cc == 't') var = (var << 8ll) | '\t';
else if (cc == 'n') var = (var << 8ll) | '\n';
else if (cc == 's') var = (var << 8ll) | ' ';
else if (cc == '\'') var = (var << 8ll) | '\'';
else throw ParseException("unknown escape char");
escape = false;
}
}
return TokenInteger(var);
}
void parseCommentOut(istream& is) {
is.get(); // #
while (is.get() != '#') {
if (is.eof()) throw ParseException("missing [#]");
}
}
vector<unique_ptr<Token>> parseToTokens(istream& is) {
vector<unique_ptr<Token>> tokens;
tokens.reserve(24);
while (true) {
int cc = is.peek();
if (is.eof()) {
break;
}
if (cc == '#') {
parseCommentOut(is);
}
else if (isspace(cc)) {
is.get();
}
else if (isdigit(cc)) {
tokens.emplace_back(new TokenInteger(parseInteger(is)));
}
else if (isalpha(cc) || cc == '_') {
tokens.emplace_back(new TokenKeyword(parseKeyword(is)));
}
else if (cc == '\'') {
tokens.emplace_back(new TokenInteger(parseChar(is)));
}
else {
tokens.emplace_back(new TokenSymbol(parseSymbol(is)));
}
}
return tokens;
}
}
namespace Compiler {
using namespace Parser;
namespace Embedded {
namespace Function {
const signed IDaadd = -10;
const signed IDasub = -11;
const signed IDamul = -12;
const signed IDadiv = -13;
const signed IDamod = -14;
const signed IDaminus = -15; // 単項
const signed IDand = -30;
const signed IDor = -31;
const signed IDnot = -35;
const signed IDnotnot = -36;
const signed IDequal = -40;
const signed IDnotequal = -41;
const signed IDless = -42;
const signed IDlesseq = -43;
const signed IDgreater = -44;
const signed IDgreatereq = -45;
const signed IDassign = -60;
const signed IDassignadd = -61;
const signed IDassignsub = -62;
const signed IDassignmul = -63;
const signed IDassigndiv = -64;
const signed IDassignmod = -65;
const signed IDdereference = -70;
const signed IDindexer = -75;
const signed IDputi = -100;
const signed IDputc = -101;
const signed IDgeti = -110;
const signed IDgetc = -111;
const signed IDgetiv = -112;
const signed IDgetcv = -113;
}
}
struct CompileException : runtime_error {
CompileException(const TokenStream& ts, const char* msg = "") :runtime_error(
[&ts, &msg]() {stringstream s; s << "at: "; ts.print(s, 8, 8); s << "\n" << msg; return s.str(); }()) {
}
CompileException(const TokenStream& ts, string msg) :runtime_error(
[&ts, &msg]() {stringstream s; s << "at: "; ts.print(s, 8, 8); s << "\n" << msg; return s.str(); }()) {
}
CompileException(const char* msg = "") :runtime_error(msg) {
}
CompileException(string msg) :runtime_error(msg) {
}
};
struct NameException : CompileException {
NameException(const char* msg = "") :CompileException(msg) { }
NameException(string msg) :CompileException(msg) { }
};
// usage: assert_token<TokenSymbol, CompileException>(token, ':', stream, ":(");
template<typename ExpectedToken, typename Exception,
typename... Args,
typename enable_if<is_base_of<runtime_error, Exception>::value>::type* = nullptr>
inline void assert_token(const Token& token, char expected, Args&&... args) {
if (!(typeis<ExpectedToken>(token) && static_cast<const ExpectedToken&>(token) == expected))
throw Exception(args...);
}
// usage: assert_token<TokenSymbol, CompileException>(token, "+=", stream, ":(");
template<typename ExpectedToken, typename Exception,
typename... Args,
typename enable_if<is_base_of<runtime_error, Exception>::value>::type* = nullptr>
inline void assert_token(const Token& token, string expected, Args&&... args) {
if (!(typeis<ExpectedToken>(token) && static_cast<const ExpectedToken&>(token) == expected))
throw Exception(args...);
}
//
enum struct EntryType {
Variable,
Function,
Keyword
};
class NameEntry {
protected:
string name_;
integer addr_;
public:
NameEntry(const string& _name, integer _addr)
:name_(_name), addr_(_addr) { }
virtual ~NameEntry() {}
virtual inline const string& name() const { return name_; }
virtual inline integer address() const { return addr_; }
};
class NameEntryVariable : public NameEntry {
int length_;
public:
NameEntryVariable(const string& _name, integer _addr, int _length = 1)
:NameEntry(_name, _addr), length_(_length) { }
inline int length() const { return length_; }
};
class NameEntryFunction : public NameEntry {
int argLength_;
public:
NameEntryFunction(const string& _name, integer _addr, int _argLength = 1)
:NameEntry(_name, _addr), argLength_(_argLength) { }
inline int argLength() const { return argLength_; }
};
class NameEntryKeyword : public NameEntry {
public:
NameEntryKeyword(const string& _name, integer _addr)
:NameEntry(_name, _addr) { }
};
// TODO: parentNameTable
class NameTable {
protected:
unordered_map<string, unique_ptr<NameEntry>> entries_;
shared_ptr<NameTable> parent_;
private:
integer addrH_; // heap
integer addrL_; // label
public:
NameTable()
:entries_(), parent_(), addrH_(0), addrL_(0) { }
NameTable(shared_ptr<NameTable>& _parent)
:entries_(), parent_(_parent), addrH_(0), addrL_(_parent->addrL_) { }
// 何かと制限が多い
// void merge(NameTable&& _nameTable) {
// auto nameTable = _nameTable;
// assert(!nameTable.parent_);
// for (auto& p : nameTable.entries_) {
// auto& entry = p.second;
// assert(!entries_.count(p.first));
// entries_[p.first] = move(p.second);
// }
// }
NameTable& parent() { return *parent_; }
const NameTable& parent() const { return *parent_; }
const NameEntry& trymakeVariableAddr(const string& name, int length) {
auto& p = entries_[name];
if (p) {
if (!typeis<NameEntryVariable>(*p))
throw NameException([&name]() {stringstream s; s << name << " is not a variable name"; return s.str(); }());
}
else {
p.reset(new NameEntryVariable(name, addrH_, length));
addrH_ += length;
}
return *p;
}
const NameEntry& trymakeFunctionAddr(const string& name, int argLen = 0) {
auto& p = entries_[name];
if (p) {
if (!typeis<NameEntryFunction>(*p))
throw NameException([&name]() {stringstream s; s << name << " is not a function name"; return s.str(); }());
}
else {
p.reset(new NameEntryFunction(name, addrL_, argLen));
addrL_ += 2; // memo: beginとend
}
return *p;
}
// 無名スコープのジャンプ(ifなど)に必要なラベルを確保する.
inline integer reserveLabelAddr(int size) {
integer a = addrL_; addrL_ += size;
return a;
}
// ラベルIDをtableと同じ進捗にする.ローカルで使用した分進めるために使う.
inline void seekLabelAddr(const NameTable& table) {
addrL_ = table.addrL_;
}
inline integer localHeapSize() const { return addrH_; }
inline bool isGlobal() const { return !parent_; }
inline const NameEntry& getLocal(const string& name) const {
return *(entries_.find(name)->second);
}
inline pair<const NameEntry&, const NameTable*> getEntire(const string& name) const {
if (includeLocal(name))
return pair<const NameEntry&, const NameTable*>(*(entries_.find(name)->second), this);
if (!parent_) return pair<const NameEntry&, const NameTable*>(*entries_.end()->second, this);
return parent_->getEntire(name);
}
inline bool includeLocal(const string& name) const {
return entries_.count(name);
}
inline bool includeEntire(const string& name) const {
return
includeLocal(name) ? true :
!parent_ ? false :
parent_->includeEntire(name);
}
};
class ReservedNameTable : private NameTable {
public:
ReservedNameTable() :NameTable() { }
integer trymakeVariableAddr(const string&, int) = delete;
integer trymakeFunctionAddr(const string&) = delete;
// @return =0: 存在しない
inline integer getId(const string& name) const {
auto it = entries_.find(name);
return it == entries_.end() ? 0 : it->second->address();
}
static inline bool isFunction(integer id) { return id < 0; }
static inline bool isKeyword(integer id) { return id > 0; }
inline void defineKeyword(const string& name, integer id) {
assert(isKeyword(id)); // memo: 製作者のミスによってのみraiseするのでassert
entries_[name].reset(new NameEntryKeyword(name, id));
}
inline void defineEmbeddedFunction(const string& name, integer id, int argLength = 1) {
assert(isFunction(id));
entries_[name].reset(new NameEntryFunction(name, id, argLength));
}
inline const NameEntry& get(const string& name) const {
return NameTable::getLocal(name);
}
inline bool include(const string& name) const {
return NameTable::includeLocal(name);
}
};
ReservedNameTable reservedNameTable; // TODO: 変な場所にstatic変数
struct Statement {
virtual ~Statement() { }
};
enum struct OperationMode {
Value,
Call
};
// inline int OperationLevel(OperationMode mode) {
// static const int lev[] = { 0,4,4,5,5,2 };
// return lev[size_t(mode)];
// }
struct Expression : public Statement {
};
class Operation : public Expression {
integer funcid_;
vector<unique_ptr<Expression>> args_;
public:
Operation(integer _f) :funcid_(_f) { }
Operation(integer _f, int _argSize) :funcid_(_f), args_(_argSize) { }
//Operation(integer _f, initializer_list<decltype(args_)::value_type> _args)
// :funcid_(_f), args_(_args) { }
inline integer& id() { return funcid_; }
inline integer id() const { return funcid_; }
inline decltype(args_)::value_type& args(int i) { return args_[i]; }
inline const decltype(args_)::value_type& args(int i) const { return args_[i]; }
inline Expression& operator[](int i) { return *args_[i]; }
inline const Expression& operator[](int i) const { return *args_[i]; }
inline int argSize() const { return (int)args_.size(); }
inline void resizeArgs(int size) { args_.resize(size); }
};
struct Factor : public Expression {
virtual bool isLValue() const = 0;
};
class FactorValue : public Factor {
integer val_;
public:
FactorValue(integer _val) :val_(_val) { }
inline integer& get() { return val_; }
inline integer get() const { return val_; }
inline bool isLValue() const override { return false; }
};
class FactorVariable : public Factor {
integer scope_; // global?: 0 else 1
integer addr_;
public:
FactorVariable(integer _scope, integer _addr) :scope_(_scope), addr_(_addr) { }
// inline integer& get() { return addr_; }
inline integer get() const { return addr_; }
inline integer scope() const { return scope_; }
inline bool isLValue() const override { return true; }
};
class FactorAddress : public FactorVariable {
public:
FactorAddress(integer _scope, integer _addr) :FactorVariable(_scope, _addr) { }
FactorAddress(const FactorVariable& _var) :FactorVariable(_var) { }
FactorAddress(FactorVariable&& _var) :FactorVariable(move(_var)) { }
};
unique_ptr<Expression> getExpression(TokenStream& stream, NameTable& nameTable);
// elem
unique_ptr<Expression> getExpressionVal(TokenStream& stream, NameTable& nameTable) {
const Token& token = stream.peek();
if (typeis<TokenInteger>(token)) {
integer val = static_cast<const TokenInteger&>(token).get();
stream.get();
return make_unique<FactorValue>(val);
}
else if (typeis<TokenKeyword>(token)) {
const auto& tokenKeyword = static_cast<const TokenKeyword&>(token);
if (reservedNameTable.include(tokenKeyword.str())) {
auto& entry = reservedNameTable.get(tokenKeyword.str());
if (typeis<NameEntryKeyword>(entry)) {
throw CompileException(stream, "it is a reserved keyword");
}
else if (typeis<NameEntryFunction>(entry)) {
auto& funcEntry = static_cast<const NameEntryFunction&>(entry);
Operation exps(funcEntry.address(), funcEntry.argLength());
try {
stream.get();
assert_token<TokenSymbol, CompileException>(stream.get(), '(', stream, "expected (");
for (int i = 0; i < funcEntry.argLength(); ++i) {
exps.args(i) = getExpression(stream, nameTable);
if (i + 1 < funcEntry.argLength())
assert_token<TokenSymbol, CompileException>(stream.get(), ',', stream, "expected ,");
}
assert_token<TokenSymbol, CompileException>(stream.get(), ')', stream, "expected )");
}
catch (const bad_cast& _) {
throw CompileException(stream, "invalid function call syntax");
}
return make_unique<Operation>(move(exps));
}
}
else {
stream.get();
const Token& nextToken = stream.peek();
if (nextToken == "(") {
// function
if (!nameTable.includeEntire(tokenKeyword.str()))
throw CompileException(stream, "undefined identifier");
const auto& ref = nameTable.getEntire(tokenKeyword.str());
if (!typeis<NameEntryFunction>(ref.first))
throw CompileException(stream, "it is not a function");
const auto& funcEntry = static_cast<const NameEntryFunction&>(ref.first);
Operation exps(funcEntry.address(), funcEntry.argLength());
assert_token<TokenSymbol, CompileException>(stream.get(), '(', stream, "expected (");
for (int i = 0; i < funcEntry.argLength(); ++i) {
exps.args(i) = getExpression(stream, nameTable);
if (i + 1 < funcEntry.argLength())
assert_token<TokenSymbol, CompileException>(stream.get(), ',', stream, "expected ,");
}
assert_token<TokenSymbol, CompileException>(stream.get(), ')', stream, "expected )");
return make_unique<Operation>(move(exps));
}
else {
// variable
if (!nameTable.includeEntire(tokenKeyword.str()))
throw CompileException(stream, "undefined identifier");
const auto& ref = nameTable.getEntire(tokenKeyword.str());
if (!typeis<NameEntryVariable>(ref.first))
throw CompileException(stream, "it is not a variable");
return make_unique<FactorVariable>(ref.second->isGlobal() ? 0 : 1, ref.first.address());
}
}
}
else if (typeis<TokenSymbol>(token)) {
const auto& tokenSymbol = static_cast<const TokenSymbol&>(token);
if (tokenSymbol == '(') {
stream.get();
auto exps = getExpression(stream, nameTable);
if (stream.get() == ")") return exps;
throw CompileException(stream, "expected )");
}
else if (tokenSymbol == '&') {
stream.get();
auto stV = getExpressionVal(stream, nameTable);
if (typeis<FactorVariable>(*stV)) {
return make_unique<FactorAddress>(static_cast<FactorVariable&>(*stV));
}
else {
throw CompileException(stream, "it's not a variable");
}
}
}
throw CompileException(stream, "syntax error");
}
// '-'
// TODO: 優先順位.`-*p[1]`は`(-*p)[1]`.`-((*p)[1])`にするには,getExpressionIndexerの前後に分割する必要がある.
unique_ptr<Expression> getExpressionUnary(TokenStream& stream, NameTable& nameTable) {
const Token& token = stream.peek();
if (typeis<TokenSymbol>(token)) {
const TokenSymbol& tokenSymbol = static_cast<const TokenSymbol&>(token);
if (tokenSymbol == '-') {
stream.get();
auto stV = getExpressionUnary(stream, nameTable);
if (typeis<FactorValue>(*stV)) {
// optimization
static_cast<FactorValue&>(*stV).get() *= -1;
return stV;
}
else {
Operation stOp(Embedded::Function::IDaminus, 1);
stOp.args(0) = move(stV);
return make_unique<Operation>(move(stOp));
}
}
else if (tokenSymbol == '!') {
stream.get();
auto stV = getExpressionUnary(stream, nameTable);
if (typeis<Operation>(*stV)) {
auto& stvRef = static_cast<Operation&>(*stV);
if (stvRef.id() == Embedded::Function::IDnot) {
// optimization
static_cast<Operation&>(*stV).id() = Embedded::Function::IDnotnot;
return stV;
}
else if (stvRef.id() == Embedded::Function::IDnotnot) {
// optimization(`!!!`)
static_cast<Operation&>(*stV).id() = Embedded::Function::IDnot;
return stV;
}
}
{
Operation stOp(Embedded::Function::IDnot, 1);
stOp.args(0) = move(stV);
return make_unique<Operation>(move(stOp));
}
}
else if (tokenSymbol == '*') {
stream.get();
Operation stOp(Embedded::Function::IDdereference, 1);
stOp.args(0) = getExpressionUnary(stream, nameTable);
return make_unique<Operation>(move(stOp));
}
else {
return getExpressionVal(stream, nameTable);
}
}
else {
return getExpressionVal(stream, nameTable);
}
}
// a[1]
unique_ptr<Expression> getExpressionIndexer(TokenStream& stream, NameTable& nameTable) {
auto stV = getExpressionUnary(stream, nameTable);
const Token& token = stream.peek();
if (token == "[") {
// a[1] => op(&a, 1)
stream.get();
auto index = getExpression(stream, nameTable);
assert_token<TokenSymbol, CompileException>(stream.get(), ']', stream, "expected ]");
if (typeis<FactorVariable>(*stV)) {
// variable
auto stOp = make_unique<Operation>(Embedded::Function::IDindexer, 2);
stOp->args(0) = make_unique<FactorAddress>(static_cast<FactorVariable&>(*stV));
stOp->args(1) = move(index);
return stOp;
}
else if (typeis<Operation>(*stV)) {
// dereference
auto& o = static_cast<Operation&>(*stV);
assert_throw<CompileException>(
o.id() == Embedded::Function::IDdereference,
stream, "must be a variable or a dereference");
auto stOp = make_unique<Operation>(Embedded::Function::IDindexer, 2);
stOp->args(0) = move(o.args(0));
stOp->args(1) = move(index);
return stOp;
}
throw CompileException(stream, "must be a variable or a dereference");
}
else {
return stV;
}
}
// '*'
unique_ptr<Expression> getExpressionMul(TokenStream& stream, NameTable& nameTable) {
unique_ptr<Expression> root;
unique_ptr<Expression>* curr = &root;
*curr = getExpressionIndexer(stream, nameTable);
while (!stream.eof()) {
const Token& token = stream.peek();
if (typeis<TokenSymbol>(token)) {
const auto& tokenSymbol = static_cast<const TokenSymbol&>(token);
if (tokenSymbol == '*' || tokenSymbol == '/' || tokenSymbol == '%') {
auto new_ex = new Operation(
tokenSymbol == '/' ? Embedded::Function::IDadiv :
tokenSymbol == '%' ? Embedded::Function::IDamod :
Embedded::Function::IDamul, 2);
new_ex->args(0) = move(root);
root.reset(new_ex);
curr = &(*new_ex).args(1);
stream.get();
}
else {
break;
}
}
else {
throw CompileException(stream, "syntax error");
}
*curr = getExpressionIndexer(stream, nameTable);
}
return root;
}
// '+'
unique_ptr<Expression> getExpressionPls(TokenStream& stream, NameTable& nameTable) {
unique_ptr<Expression> root;
unique_ptr<Expression>* curr = &root;
*curr = getExpressionMul(stream, nameTable);
while (!stream.eof()) {
const Token& token = stream.peek();
if (typeis<TokenSymbol>(token)) {
const auto& tokenSymbol = static_cast<const TokenSymbol&>(token);
if (tokenSymbol == '+' || tokenSymbol == '-') {
auto new_ex = new Operation(