-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMasfix.cpp
1773 lines (1706 loc) · 56.9 KB
/
Masfix.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 <iostream>
#include <fstream>
#include <filesystem>
namespace fs = std::filesystem;
#include <string>
#include <map>
#include <set>
#include <vector>
#include <list>
#include <stack>
#include <optional>
#include <algorithm>
#include <numeric>
#include <math.h>
#include <assert.h>
#include <functional>
#include <cctype>
#include <locale>
using namespace std;
// constants -------------------------------
#define TOP_MODULE_NAME "__main"
#define MAX_EXPANSION_DEPTH 1024
#define STDOUT_BUFF_SIZE 256
#define STDIN_BUFF_SIZE 256
#define WORD_MAX_VAL 65535
#define CELLS WORD_MAX_VAL+1
// enums --------------------------------
enum TokenTypes {
Tnumeric,
Talpha,
Tstring,
Tspecial,
Tcolon,
Tseparator,
Tlist,
// intermediate preprocess tokens
TImodule,
TIexpansion,
TInamespace,
TIarglist,
TokenCount
};
constexpr int DefiningDirectivesCount = 3;
const set<string> DefiningDirectivesSet = {
"define",
"macro",
"namespace"
};
constexpr int BuiltinDirectivesCount = 2;
const set<string> BuiltinDirectivesSet = {
"using",
"include"
};
enum RegNames {
Rh,
Rm,
Rr,
Rp,
Rno,
RegisterCount
};
static_assert(RegisterCount == 5, "Exhaustive CharToReg definition");
map<char, RegNames> CharToReg = {
{'h', Rh},
{'m', Rm},
{'r', Rr},
{'p', Rp},
};
enum OpNames {
OPa,
OPs,
OPt,
OPand, // bitwise
OPor,
OPxor,
OPshl,
OPshr,
OPbit,
OPno,
OperationCount
};
static_assert(OperationCount == 10, "Exhaustive CharToOp definition");
map<char, OpNames> CharToOp = {
{'a', OPa}, // TODO: add +, - as suffixes
{'s', OPs},
{'t', OPt},
{'&', OPand},
{'|', OPor},
{'^', OPxor},
{'<', OPshl},
{'>', OPshr},
{'.', OPbit},
};
enum CondNames {
Ceq,
Cne,
Clt,
Cle,
Cgt,
Cge,
Cno,
ConditionCount
};
static_assert(ConditionCount == 7, "Exhaustive StrToCond definition");
map<string, CondNames> StrToCond = {
{"eq", Ceq},
{"ne", Cne},
{"lt", Clt},
{"le", Cle},
{"gt", Cgt},
{"ge", Cge},
};
enum InstrNames {
Imov,
Istr,
Ild ,
Ijmp,
Ib,
Il,
Is,
Iswap,
Ioutu,
Ioutc,
Iinc,
Iipc,
Iinu,
Iinl,
InstructionCount
};
static_assert(InstructionCount == 14, "Exhaustive StrToInstr definition");
map<string, InstrNames> StrToInstr {
{"mov", Imov},
{"str", Istr},
{"ld" , Ild },
{"jmp", Ijmp},
{"b", Ib},
{"l", Il},
{"s", Is},
{"swap", Iswap},
{"outu", Ioutu},
{"outc", Ioutc},
{"inc", Iinc},
{"ipc", Iipc},
{"inu", Iinu},
{"inl", Iinl},
};
map<InstrNames, RegNames> InstrToModReg = {
{Imov, Rh},
{Istr, Rm},
{Ild , Rr},
{Ijmp, Rp},
// others don't have modifiable destination
};
// checks --------------------------------------------------------------------
#define errorQuoted(s) " '" + (s) + "'"
#define unreachable() assert(("Unreachable", false));
#define continueOnFalse(cond) if (!(cond)) continue;
#define returnOnFalse(cond) if (!(cond)) return false;
#define check(cond, message, obj) ((cond) || raiseError(message, obj))
#define checkContinueOnFail(cond, message, obj) if(!check(cond, message, obj)) continue;
#define checkReturnOnFail(cond, message, obj) if(!check(cond, message, obj)) return false;
// structs -------------------------------
struct Loc {
string file;
int row;
int col;
Loc() {}
Loc(string file, int row, int col) {
this->file = file;
this->row = row;
this->col = col;
}
string toStr() {
return file + ":" + to_string(row) + ":" + to_string(col);
}
};
struct Token {
TokenTypes type;
string data;
list<Token> tlist;
Loc loc;
bool continued; // continues meaning of previous token
bool firstOnLine;
Token() {}
Token(TokenTypes type, string data, Loc loc, bool continued, bool firstOnLine) {
this->type = type;
this->data = data;
this->loc = loc;
this->continued = continued;
this->firstOnLine = firstOnLine;
}
char tlistCloseChar() {
assert(type == Tlist);
return data.at(0) + 2 - (data.at(0) == '(');
}
string toStr() {
string out = data;
if (type == Tlist) {
if (isSeparated()) out.push_back(',');
out.push_back(tlistCloseChar());
}
// } else if (type == Tstring && quotedStr) {
// return '"' + data + '"';
// }
return out;
}
bool isSeparated() {
assert(type == Tlist);
for (Token t : tlist) {
if (t.type == Tseparator) return true;
}
return false;
}
};
struct Define {
string name;
Loc loc;
string value;
Define() {}
Define(string name, Loc loc, string value) {
this->name = name;
this->loc = loc;
this->value = value;
}
};
struct MacroArg {
string name;
Loc loc;
stack<list<Token>> value; // TODO test multiple expansions inside each other
MacroArg() {}
MacroArg(string name, Loc loc) {
this->name = name;
this->loc = loc;
}
};
struct Macro {
string name;
Loc loc;
map<string, int> nameToArgIdx;
vector<MacroArg> argList;
list<Token> body;
Macro() {}
Macro(string name, Loc loc) {
this->name = name;
this->loc = loc;
}
bool hasArg(string name) {
return nameToArgIdx.count(name);
}
void addArg(string name, Loc loc) {
nameToArgIdx[name] = argList.size();
argList.push_back(MacroArg(name, loc));
}
MacroArg& nameToArg(string name) {
assert(nameToArgIdx.count(name));
return argList[nameToArgIdx[name]];
}
void addExpansionArgs(vector<pair<list<Token>::iterator, list<Token>::iterator>>& argSpans) {
assert(argSpans.size() == argList.size());
for (int idx = 0; idx < argSpans.size(); ++idx) {
argList[idx].value.push(list<Token>(argSpans[idx].first, argSpans[idx].second));
}
}
void closeExpansionScope() {
for (int i = 0; i < argList.size(); ++i) {
argList[i].value.pop();
}
}
};
struct Namespace {
string name;
Loc loc;
map<string, Define> defines;
map<string, Macro> macros;
map<string, int> innerNamespaces;
set<int> usedNamespaces;
int upperNamespaceId;
bool isUpperAccesible;
Namespace() {}
Namespace(string name, Loc loc, int upperNamespaceId, bool isUpperAccesible) {
this->name = name;
this->loc = loc;
this->upperNamespaceId = upperNamespaceId;
this->isUpperAccesible = isUpperAccesible;
}
};
map<int, Namespace> IdToNamespace;
struct Module {
fs::path abspath;
Token contents; // TImodule
int namespaceId;
Module(fs::path path, int namespaceId) {
abspath = path;
this->namespaceId = namespaceId;
}
};
bool raiseError(string message, Token token, bool strict=false);
bool raiseError(string message, Loc loc, bool strict=false);
/// responsible for iterating tokens and nested tlists,
/// keeping track of current module, namespace, expansion scope, arglist situation
struct Scope {
private:
stack<int> namespaces;
stack<pair<int, string>> macros;
// TODO better max depth checks - maybe add depth counter
stack<reference_wrapper<Token>> tlists;
stack<list<Token>::iterator> itrs;
list<Module> modules;
list<Module>::iterator currModule = modules.begin();
bool isPreprocessing = true;
/// opens new tlist for iteration
void openList(Token& tlist) {
tlists.push(tlist);
itrs.push(tlist.tlist.begin());
}
/// closes single list
void closeList() {
static_assert(TokenCount == 11, "Exhaustive closeList definition");
if (tlists.top().get().type == TIexpansion) {
if (isPreprocessing) endMacroExpansion();
} else if (tlists.top().get().type == TInamespace) {
if (isPreprocessing) {
assert(currNamespace().isUpperAccesible);
exitNamespace();
}
} else if (tlists.top().get().type == TImodule) {
if (isPreprocessing) exitNamespace();
currModule++;
}
tlists.pop(); itrs.pop();
}
public:
Scope() {}
list<Token>& currList() {
return tlists.top().get().tlist;
}
Token& currToken() {
return *itrs.top();
}
Token* operator->() {
return &currToken();
}
void prepareForCompile() {
static_assert(sizeof(Scope) == 360, "Exhaustive Scope sanity checks definition");
assert(!tlists.size());
assert(!itrs.size());
assert(!macros.size());
assert(!namespaces.size());
assert(currModule == modules.end());
currModule = modules.begin();
isPreprocessing = false;
for (list<Module>::reverse_iterator itr = modules.rbegin(); itr != modules.rend(); ++itr) {
openList(itr->contents);
}
}
// iteration ----------------------------------------------------------
/// whether currList has any next token
bool hasNext() {
return itrs.top() != currList().end();
}
/// closes ended lists if necessary, returns if iteration can continue in this situation
bool advanceIteration() {
while (tlists.size() && !hasNext() && !insideArglist()) closeList();
return tlists.size() && hasNext();
}
/// advances iteration inside current list
list<Token>::iterator& next() {
return ++itrs.top();
}
/// advances iteration, opens new nested list if provided
list<Token>::iterator& next(Token& tlist) {
++itrs.top();
if (tlist.type == Tlist || tlist.type == TIexpansion || tlist.type == TInamespace) {
openList(tlist);
}
return itrs.top();
}
// situation checks -----------------------------------------
bool insideMacro() {
return macros.size();
}
/// is closest tlist an arglist
bool insideArglist() {
return tlists.top().get().type == TIarglist;
}
int currNamespaceId() {
assert(namespaces.size());
return insideMacro() ? macros.top().first : namespaces.top();
}
Namespace& currNamespace() {
return IdToNamespace[currNamespaceId()];
}
Macro& currMacro() {
assert(insideMacro());
return currNamespace().macros[macros.top().second];
}
fs::path currModuleFolder() {
return currModule->abspath.parent_path();
}
bool hasMacroArg(string& name) {
return insideMacro() && currMacro().hasArg(name);
}
void addMacroExpansion(int namespaceId, Token& expansionToken) {
if (macros.size() > MAX_EXPANSION_DEPTH) { // TODO?
raiseError("Maximum expansion depth exceeded", expansionToken.loc, true);
}
macros.push(pair(namespaceId, expansionToken.data));
}
void endMacroExpansion() {
currMacro().closeExpansionScope();
macros.pop();
}
int addNewNamespace(string& name, Loc loc, bool isModuleDefinition) {
assert(!insideMacro());
int newId = IdToNamespace.size();
if (newId != 0) {
if (isModuleDefinition) currNamespace().usedNamespaces.insert(newId);
else currNamespace().innerNamespaces[name] = newId;
}
IdToNamespace[newId] = Namespace(name, loc, isModuleDefinition ? -1 : currNamespaceId(), !isModuleDefinition);
namespaces.push(newId);
return newId;
}
void exitNamespace() {
assert(namespaces.size() >= 1);
namespaces.pop();
}
void enterArglist(Token& tlist) {
assert(!insideArglist());
tlist.type = TIarglist;
openList(tlist);
}
void exitArglist() {
assert(insideArglist());
closeList();
}
// tokenization -----------------------------------------
bool tokenizeHasTlist() {
return tlists.size() && tlists.top().get().type == Tlist;
}
bool tokenizeCloseList(char closeChar, Loc& loc) {
checkReturnOnFail(tokenizeHasTlist(), "Unexpected token list termination" errorQuoted(string(1, closeChar)), loc);
checkReturnOnFail(closeChar == tlists.top().get().tlistCloseChar(), "Unmatched token list delimiters" errorQuoted(string(1, closeChar)), loc);
closeList();
return true;
}
void tokenizeEnd() {
while (tokenizeHasTlist()) {
raiseError("Unclosed token list", tlists.top().get());
closeList();
}
assert(tlists.size() >= 1 && tlists.top().get().type == TImodule);
itrs.top() = currList().begin();
}
// modules -------------------------------------------------
Module* getCurrModule() {
return &*currModule;
}
bool newModuleIncluded(fs::path abspath) {
for (list<Module>::iterator module = modules.begin(); module != modules.end(); ++module) {
if (fs::equivalent(module->abspath, abspath)) {
currNamespace().usedNamespaces.insert(module->namespaceId);
return false;
}
}
return true;
}
void addNewModule(fs::path abspath, string relPath, string moduleName) {
Loc loc = Loc(relPath, 1, 1);
int namespaceId = addNewNamespace(moduleName, loc, true);
currModule = modules.insert(currModule, Module(abspath, namespaceId));
currModule->contents = Token(TImodule, moduleName, loc, false, true);
openList(currModule->contents);
}
// helpers -------------------------------------------------
void insertToken(Token& token) {
itrs.top() = currList().insert(itrs.top(), token);
}
void insertToken(Token&& token) {
itrs.top() = currList().insert(itrs.top(), token);
}
void insertList(list<Token>& tlist, Token& percentToken) {
assert(tlist.size());
itrs.top() = currList().insert(itrs.top(), tlist.begin(), tlist.end());
itrs.top()->continued = percentToken.continued;
itrs.top()->firstOnLine = percentToken.firstOnLine;
}
Token eatenToken() {
Token t = currToken();
itrs.top() = currList().erase(itrs.top());
return t;
}
/// eats tokens upto EOL or separator
void eatLine(bool surelyEat=false) {
while (hasNext() && (surelyEat || !currToken().firstOnLine) && !(insideArglist() && currToken().type == Tseparator)) {
eatenToken();
surelyEat = false;
}
}
bool _addMacroArg(vector<pair<list<Token>::iterator, list<Token>::iterator>>& argSpans, list<Token>::iterator& argStart, Loc loc) {
checkReturnOnFail(argStart != itrs.top(), "Argument expected", loc);
argSpans.push_back(pair(argStart, itrs.top()));
return true;
}
bool sliceArglist(Macro& mac, Loc loc, bool retval=true) {
itrs.top() = currList().begin(); list<Token>::iterator argStart = itrs.top();
vector<pair<list<Token>::iterator, list<Token>::iterator>> argSpans;
while (hasNext()) {
loc = currToken().loc;
checkReturnOnFail(mac.argList.size(), "Excesive expansion argument", loc);
if (currToken().type == Tseparator) {
checkReturnOnFail(argSpans.size()+1 < mac.argList.size(), "Excesive expansion argument", loc);
retval &= _addMacroArg(argSpans, argStart, loc);
argStart = next();
} else next();
}
retval &= _addMacroArg(argSpans, argStart, loc);
returnOnFalse(retval && check(argSpans.size() == mac.argList.size(), "Missing expansion arguments", loc));
mac.addExpansionArgs(argSpans);
return true;
}
int expansionDepth() {
return tlists.size();
}
};
struct Suffix {
// dest ?<operation>= <reg>/<imm>
RegNames condReg;
CondNames cond;
OpNames modifier;
RegNames reg;
Suffix() {
condReg = Rno;
cond = Cno;
modifier = OPno;
reg = Rno;
}
};
struct Instr {
InstrNames instr = InstructionCount;
Suffix suffixes;
int immediate;
string opcodeStr;
Loc opcodeLoc;
vector<string> immFields;
Instr() {}
Instr(string opcodeStr, Loc opcodeLoc) {
this->opcodeStr = opcodeStr;
this->opcodeLoc = opcodeLoc;
}
bool hasImm() { return immFields.size() != 0; }
bool hasCond() { return suffixes.cond != Cno; }
bool hasMod() { return suffixes.modifier != OPno; }
bool hasReg() { return suffixes.reg != Rno; }
string toStr() {
string out = opcodeStr;
for (string s : immFields) {
out.push_back(' ');
out.append(s);
}
return out;
}
};
struct Label {
string name;
int addr;
Loc loc;
Label() { name=""; }
Label(string name, int addr, Loc loc) {
this->name = name;
this->addr = addr;
this->loc = loc;
}
string toStr() {
return ":" + name;
}
};
// checks implementation ----------------------------------------------
map<string, Label> StrToLabel;
bool FLAG_strictErrors = false;
bool SupressErrors = false;
#define returnOnErrSupress() if (SupressErrors) return false;
vector<string> errors;
void raiseErrors() { // TODO sort errors based on line and file
for (string s : errors) {
cerr << s;
}
if (errors.size()) exit(1);
}
void addError(string message, bool strict=true) {
errors.push_back(message);
if (strict || FLAG_strictErrors) {
raiseErrors();
}
}
bool raiseError(string message, Token token, bool strict) {
returnOnErrSupress();
string err = token.loc.toStr() + " ERROR: " + message + errorQuoted(token.toStr()) "\n";
addError(err, strict);
return false;
}
bool raiseError(string message, Instr instr, bool strict=false) {
returnOnErrSupress();
string err = instr.opcodeLoc.toStr() + " ERROR: " + message + errorQuoted(instr.toStr()) "\n";
addError(err, strict);
return false;
}
bool raiseError(string message, Loc loc, bool strict) {
returnOnErrSupress();
string err = loc.toStr() + " ERROR: " + message + "\n";
addError(err, strict);
return false;
}
// tokenization -----------------------------------------------------------------
string getCharRun(string s) {
bool num = isdigit(s.at(0)), alpha = isalpha(s.at(0)), space = isspace(s.at(0));
if (!num && !alpha && !space) return string(1, s.at(0));
string out;
int i = 0;
do {
out.push_back(s.at(i));
i++;
} while (i < s.size() && !!isdigit(s.at(i)) == num && !!isalpha(s.at(i)) == alpha && !!isspace(s.at(i)) == space);
return out;
}
#define addToken(type) scope.insertToken(Token(type, run, loc, continued, firstOnLine)); \
scope.next(scope.currToken());
void tokenize(ifstream& ifs, string relPath, Scope& scope) {
static_assert(TokenCount == 11, "Exhaustive tokenize definition");
string line;
bool continued, firstOnLine, keepContinued;
for (int lineNum = 1; getline(ifs, line); ++lineNum) {
continued = false; firstOnLine = true;
line = line.substr(0, line.find(';'));
int col = 1;
while (line.size()) {
char first = line.at(0);
string run = getCharRun(line);
line = line.substr(run.size());
Loc loc = Loc(relPath, lineNum, col);
col += run.size();
keepContinued = true;
if (isspace(first)) {
continued = false;
continue;
}
if (isdigit(first)) {
addToken(Tnumeric);
} else if (isalpha(first)) {
addToken(Talpha);
} else if (run.size() == 1) {
if (first == '(' || first == '[' || first == '{') {
addToken(Tlist);
keepContinued = false;
} else if (first == ')' || first == ']' || first == '}') {
continueOnFalse(scope.tokenizeCloseList(first, loc));
} else if (first == ':') {
addToken(Tcolon);
} else if (first == ',') {
continued = false;
addToken(Tseparator);
keepContinued = false;
} else if (first == '"') {
size_t quotePos = line.find('"');
if (!check(quotePos != string::npos, "Expected string termination", loc)) {
line = ""; continue;
}
run = line.substr(0, quotePos);
col +=++ quotePos;
continued = false; keepContinued = false;
addToken(Tstring);
line = line.substr(quotePos);
} else {
addToken(Tspecial);
}
} else {
assert(false);
}
continued = keepContinued;
firstOnLine = false;
}
}
scope.tokenizeEnd();
}
// preprocess helpers -------------------------------------------------------------------------
bool _validIdentChar(char c) { return isalnum(c) || c == '_'; }
bool verifyNotInstrOpcode(string name);
bool isValidIdentifier(string name, string errInvalid, Loc& loc) {
checkReturnOnFail(name.size() > 0 && find_if_not(name.begin(), name.end(), _validIdentChar) == name.end(), errInvalid, loc)
return check(isalpha(name.at(0)) || name.at(0) == '_', errInvalid, loc);
}
bool checkIdentRedefinitions(string name, Loc& loc, bool label, Namespace* currNamespace=nullptr) {
checkReturnOnFail(verifyNotInstrOpcode(name), "Name shadows an instruction" errorQuoted(name), loc);
checkReturnOnFail(!DefiningDirectivesSet.count(name) && !BuiltinDirectivesSet.count(name), "Name shadows a builtin directive" errorQuoted(name), loc)
if (label) {
checkReturnOnFail(StrToLabel.count(name) == 0, "Label redefinition" errorQuoted(name), loc);
} else {
assert(currNamespace);
checkReturnOnFail(currNamespace->defines.count(name) == 0, "Define redefinition" errorQuoted(name), loc);
checkReturnOnFail(currNamespace->macros.count(name) == 0, "Macro redefinition" errorQuoted(name), loc);
checkReturnOnFail(currNamespace->innerNamespaces.count(name) == 0, "Namespace redefinition" errorQuoted(name), loc);
}
return true;
}
#define processArglistWrapper(body) \
scope.enterArglist(token); \
body \
scope.exitArglist(); \
returnOnFalse(retval);
bool eatToken(Scope& scope, Loc& loc, Token& outToken, TokenTypes type, string errMissing, bool sameLine) {
checkReturnOnFail(scope.hasNext(), errMissing, loc);
if (sameLine) checkReturnOnFail(!scope->firstOnLine, errMissing, loc);
outToken = scope.eatenToken(); loc = outToken.loc;
return check(outToken.type == type, "Unexpected token type", outToken); // TODO more specific err message here
}
void eatTokenRun(Scope& scope, string& name, Loc& loc, bool canStartLine=true, int eatAnything=0) {
static_assert(TokenCount == 11, "Exhaustive eatTokenRun definition");
if (scope.hasNext()) loc = scope->loc;
bool first = true; name = "";
set<TokenTypes> allowedTypes = {Tnumeric, Talpha, Tspecial};
if (eatAnything >= 1) allowedTypes.insert(Tcolon);
if (eatAnything >= 2) allowedTypes.insert(Tstring);
if (eatAnything >= 3) allowedTypes.insert(Tlist);
while (scope.hasNext() && (!scope->firstOnLine || (canStartLine && first)) && (first || scope->continued) && allowedTypes.count(scope->type)) {
name += scope.eatenToken().toStr();
first = false;
}
}
bool eatIdentifier(Scope& scope, string& name, Loc& loc, string identPurpose, bool canStartLine=false, int eatAnything=0) {
Loc prevLoc = loc;
eatTokenRun(scope, name, loc, canStartLine, eatAnything);
return check(name != "", "Missing " + identPurpose + " name", prevLoc);
}
#define directiveEatIdentifier(identPurpose, definition, eatAnything) \
returnOnFalse(eatIdentifier(scope, name, loc, identPurpose, false, eatAnything)); \
returnOnFalse(isValidIdentifier(name, "Invalid " + string(identPurpose) + " name" errorQuoted(name), loc)); \
if (definition) returnOnFalse(checkIdentRedefinitions(name, loc, false, &scope.currNamespace()));
#define directiveEatToken(type, missingErr, sameLine) returnOnFalse(eatToken(scope, loc, token, type, missingErr, sameLine));
string relPathFromMasfix(fs::path p) {
fs::path out;
bool found = false;
for (fs::path part : p) {
string s = part.string();
if (found) out.append(s);
if (s == "Masfix") {
found = true;
}
}
return (found ? out : p).string();
}
ifstream openInputFile(fs::path path);
string tokenizeNewModule(fs::path abspath, Scope& scope, bool mainModule=false) {
string relPath = relPathFromMasfix(abspath);
string moduleName = mainModule ? TOP_MODULE_NAME : abspath.filename().replace_extension("").string(); // TODO name sanitazion, module name redefs?
scope.addNewModule(abspath, relPath, moduleName);
ifstream ifs = openInputFile(abspath);
tokenize(ifs, relPath, scope);
ifs.close();
return relPath;
}
// preprocess -------------------------------------------------------------------------
bool arglistFromTlist(Scope& scope, Loc& loc, Macro& mac) {
string name; bool first = true;
while (scope.hasNext()) {
if (!first) {
Token sep = scope.eatenToken(); loc = sep.loc;
checkReturnOnFail(sep.type == Tseparator, "Separator expected", loc);
}
first = false;
directiveEatIdentifier("macro arg", true, 1);
checkReturnOnFail(mac.nameToArgIdx.count(name) == 0, "Macro argument redefinition" errorQuoted(name), loc);
mac.addArg(name, loc); // TODO macArg.loc not checked nor used
}
return true;
}
bool processMacroDef(Scope& scope, string name, Loc loc, Loc percentLoc) {
Token token;
scope.currNamespace().macros[name] = Macro(name, percentLoc);
Macro& mac = scope.currNamespace().macros[name];
directiveEatToken(Tlist, "Macro arglist expected", true);
if (token.tlist.size()) {
processArglistWrapper( bool retval = arglistFromTlist(scope, loc, mac); )
}
directiveEatToken(Tlist, "Macro body expected", false);
checkReturnOnFail(!token.isSeparated(), "No separators expected in macro body", loc);
mac.body = list(token.tlist.begin(), token.tlist.end());
return true;
}
bool processNamespaceDef(string name, Loc loc, Loc percentLoc, Scope& scope) {
Token token; // TODO no seps in namespace body
directiveEatToken(Tlist, "Namespace body expected", false);
scope.insertToken(Token(TInamespace, name, percentLoc, false, true));
scope->tlist = token.tlist;
scope.addNewNamespace(name, percentLoc, false);
return true;
}
bool processDirectiveDef(string directive, Scope& scope, Token percentToken, Loc loc) {
static_assert(DefiningDirectivesCount == 3, "Exhaustive processDirectiveDef definition");
string name; Token token;
directiveEatIdentifier(directive, true, 1);
if (directive == "define") {
directiveEatToken(Tnumeric, "Define value expected", true);
scope.currNamespace().defines[name] = Define(name, percentToken.loc, token.data);
} else if (directive == "macro") {
returnOnFalse(processMacroDef(scope, name, loc, percentToken.loc));
} else if (directive == "namespace") {
returnOnFalse(processNamespaceDef(name, loc, percentToken.loc, scope));
} else {
unreachable();
}
return check(!scope.hasNext() || scope->firstOnLine, "Unexpected token after directive", scope.currToken());
}
void expandDefineUse(Token percentToken, Scope& scope, int namespaceId, string defineName) {
Define& define = IdToNamespace[namespaceId].defines[defineName];
Token expanded = Token(Tnumeric, define.value, percentToken.loc, false, percentToken.firstOnLine);
scope.insertToken(expanded);
}
bool preprocess(Scope& scope);
bool processExpansionArglist(Token& token, Scope& scope, Macro& mac, Loc& loc) {
assert(token.type == Tlist);
if (token.tlist.size()) {
processArglistWrapper(
bool retval = preprocess(scope);
retval = retval && scope.sliceArglist(mac, loc);
);
} else return check(mac.argList.size() == 0, "Missing expansion arguments", loc);
return true;
;
}
bool expandMacroUse(Loc loc, Scope& scope, int namespaceId, string macroName) {
Macro& mac = IdToNamespace[namespaceId].macros[macroName]; Token token;
directiveEatToken(Tlist, "Expansion arglist expected", true);
returnOnFalse(processExpansionArglist(token, scope, mac, loc));
checkReturnOnFail(!scope.hasNext() || scope->firstOnLine, "Unexpected token after macro use", scope.currToken());
Token expanded = Token(TIexpansion, macroName, mac.loc, false, true);
expanded.tlist = list(mac.body.begin(), mac.body.end());
scope.addMacroExpansion(namespaceId, expanded);
scope.insertToken(expanded);
return true;
}
bool getDirectivePrefixes(string& firstName, list<string>& prefixes, list<Loc>& locs, Loc& loc, Scope& scope, bool& notContinued, string identPurpose="directive") {
static_assert(TokenCount == 11, "Exhaustive getDirectivePrefixes definition");
string name; bool first = true;
while (true) {
directiveEatIdentifier(identPurpose, false, 0);
if (first) {
firstName = name; first = false;
} else prefixes.push_back(name);
locs.push_back(loc);
if (!scope.hasNext() || scope->type != Tcolon || scope->firstOnLine) break;
loc = scope.eatenToken().loc;
}
notContinued = !scope.hasNext() || !scope->continued;
return true;
}
bool defineDefined(string& name, int& namespaceId, bool firstPrefix=false) {
if (IdToNamespace[namespaceId].defines.count(name)) return true;
if (firstPrefix) for (int id : IdToNamespace[namespaceId].usedNamespaces) {
if (IdToNamespace[id].defines.count(name)) {
namespaceId = id;
return true;
}
}
return false;
}
bool macroDefined(string& name, int& namespaceId, bool firstPrefix=false) {
if (IdToNamespace[namespaceId].macros.count(name)) return true;
if (firstPrefix) for (int id : IdToNamespace[namespaceId].usedNamespaces) {
if (IdToNamespace[id].macros.count(name)) {
namespaceId = id;
return true;
}
}
return false;
}
bool namespaceDefined(string& name, int& namespaceId, bool firstPrefix=false) {
if (IdToNamespace[namespaceId].innerNamespaces.count(name)) {
namespaceId = IdToNamespace[namespaceId].innerNamespaces[name];
return true;
}
if (firstPrefix) for (int id : IdToNamespace[namespaceId].usedNamespaces) {
if (IdToNamespace[id].innerNamespaces.count(name)) {
namespaceId = IdToNamespace[id].innerNamespaces[name];
return true;
}
}
return false;
}
void lookupFinalAbove(string directiveName, int& namespaceId, bool& namespaceSeen) {
Namespace* currNamespace;
while (true) {
currNamespace = &IdToNamespace[namespaceId];
if (defineDefined(directiveName, namespaceId, true) || macroDefined(directiveName, namespaceId, true)) return;
namespaceSeen = namespaceSeen || currNamespace->innerNamespaces.count(directiveName);
if (!currNamespace->isUpperAccesible) return;
namespaceId = currNamespace->upperNamespaceId;
}
}
bool lookupNamespaceAbove(string directiveName, int& namespaceId, Loc& loc) {
Namespace* currNamespace;
while (true) {
currNamespace = &IdToNamespace[namespaceId];
if (namespaceDefined(directiveName, namespaceId, true)) return true;
if (!currNamespace->isUpperAccesible) break;
namespaceId = currNamespace->upperNamespaceId;
}
return check(false, "Namespace not found" errorQuoted(directiveName), loc);
}
bool processUseDirective(string directiveName, Token& percentToken, Loc lastLoc, int namespaceId, bool notContinued, bool namespaceSeen, Scope& scope) {
if (defineDefined(directiveName, namespaceId)) {
checkReturnOnFail(notContinued, "Unexpected continued token", scope.currToken());
expandDefineUse(percentToken, scope, namespaceId, directiveName);
return true;
} else if (macroDefined(directiveName, namespaceId)) {
checkReturnOnFail(percentToken.firstOnLine && !scope.insideArglist(), "Unexpected macro use", percentToken.loc);
return expandMacroUse(percentToken.loc, scope, namespaceId, directiveName);
}
checkReturnOnFail(!namespaceSeen && !namespaceDefined(directiveName, namespaceId, true), "Namespace used as directive" errorQuoted(directiveName), lastLoc);
return check(false, "Undeclared identifier" errorQuoted(directiveName), lastLoc);
}
bool lookupName(Token& percentToken, string directiveName, list<string>& prefixes, list<Loc>& locs, bool notContinued, Scope& scope) {
int namespaceId = scope.currNamespaceId(); bool namespaceSeen = false;
if (prefixes.size()) {
returnOnFalse(lookupNamespaceAbove(directiveName, namespaceId, locs.front()));
directiveName = prefixes.front(); prefixes.pop_front(); locs.pop_front();
} else {
lookupFinalAbove(directiveName, namespaceId, namespaceSeen);
}
while (prefixes.size()) {
checkReturnOnFail(namespaceDefined(directiveName, namespaceId), "Namespace not found" errorQuoted(directiveName), locs.front());
directiveName = prefixes.front(); prefixes.pop_front(); locs.pop_front();
}
return processUseDirective(directiveName, percentToken, locs.front(), namespaceId, notContinued, namespaceSeen, scope);
}
bool processUsing(Loc loc, Scope& scope) {
int namespaceId = scope.currNamespaceId();
string firstName; list<string> prefixes; list<Loc> locs; bool notContinued;
returnOnFalse(getDirectivePrefixes(firstName, prefixes, locs, loc, scope, notContinued, "namespace"));
// NOTE the first namespace can be used, others down the using chain must be defined inside one another
returnOnFalse(lookupNamespaceAbove(firstName, namespaceId, locs.front()));
while (prefixes.size()) {
firstName = prefixes.front(); prefixes.pop_front(); locs.pop_front();
checkReturnOnFail(namespaceDefined(firstName, namespaceId), "Namespace not found" errorQuoted(firstName), locs.front());
}
check(scope.currNamespace().usedNamespaces.insert(namespaceId).second, "Namespace already imported" errorQuoted(firstName), locs.back());
return true;