-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerator.cpp
More file actions
3172 lines (2765 loc) · 109 KB
/
generator.cpp
File metadata and controls
3172 lines (2765 loc) · 109 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 <sstream>
#include "main.h"
//////////////////////////////////////////////////////////////////////
const GeneratorKeywordSpec Generator::m_keywordspecs[] =
{
{ KeywordBEEP, &Generator::GenerateBeep },
{ KeywordBLOAD, &Generator::GenerateIgnoredStatement },
{ KeywordBSAVE, &Generator::GenerateIgnoredStatement },
{ KeywordCIRCLE, &Generator::GenerateCircle },
{ KeywordCLEAR, &Generator::GenerateClear },
{ KeywordCLOAD, &Generator::GenerateIgnoredStatement },
{ KeywordCLOSE, &Generator::GenerateClose },
{ KeywordCLS, &Generator::GenerateCls },
{ KeywordCOLOR, &Generator::GenerateColor },
{ KeywordCSAVE, &Generator::GenerateIgnoredStatement },
{ KeywordDATA, &Generator::GenerateData },
{ KeywordDIM, &Generator::GenerateDim },
{ KeywordDRAW, &Generator::GenerateDraw },
{ KeywordEND, &Generator::GenerateEnd },
{ KeywordFOR, &Generator::GenerateFor },
{ KeywordGOSUB, &Generator::GenerateGosub },
{ KeywordGOTO, &Generator::GenerateGoto },
{ KeywordIF, &Generator::GenerateIf },
{ KeywordINPUT, &Generator::GenerateInput },
{ KeywordKEY, &Generator::GenerateIgnoredStatement },
{ KeywordLET, &Generator::GenerateLet },
{ KeywordLINE, &Generator::GenerateLine },
{ KeywordLOAD, &Generator::GenerateIgnoredStatement },
{ KeywordLOCATE, &Generator::GenerateLocate },
{ KeywordNEXT, &Generator::GenerateNext },
{ KeywordON, &Generator::GenerateOn },
{ KeywordOPEN, &Generator::GenerateOpen },
{ KeywordOUT, &Generator::GenerateOut },
{ KeywordPAINT, &Generator::GeneratePaint },
{ KeywordPOKE, &Generator::GeneratePoke },
{ KeywordPRINT, &Generator::GeneratePrint },
{ KeywordPSET, &Generator::GeneratePset },
{ KeywordPRESET, &Generator::GeneratePreset },
{ KeywordREAD, &Generator::GenerateRead },
{ KeywordREM, &Generator::GenerateRem },
{ KeywordRESTORE, &Generator::GenerateRestore },
{ KeywordRETURN, &Generator::GenerateReturn },
{ KeywordSAVE, &Generator::GenerateIgnoredStatement },
{ KeywordSCREEN, &Generator::GenerateScreen },
{ KeywordSTOP, &Generator::GenerateStop },
{ KeywordTRON, &Generator::GenerateIgnoredStatement },
{ KeywordTROFF, &Generator::GenerateIgnoredStatement },
{ KeywordWIDTH, &Generator::GenerateWidth },
{ KeywordCALL, &Generator::GenerateCall },
};
GeneratorMethodRef Generator::FindGeneratorMethodRef(KeywordIndex keyword)
{
for (auto it = std::begin(m_keywordspecs); it != std::end(m_keywordspecs); ++it)
{
if (keyword == it->keyword)
return it->methodref;
}
return nullptr;
}
const GeneratorOperSpec Generator::m_operspecs[] =
{
{ "+", &Generator::GenerateOperPlus },
{ "-", &Generator::GenerateOperMinus },
{ "*", &Generator::GenerateOperMul },
{ "/", &Generator::GenerateOperDiv },
{ "\\", &Generator::GenerateOperDivInt },
{ "MOD", &Generator::GenerateOperMod },
{ "^", &Generator::GenerateOperPower },
{ "=", &Generator::GenerateOperEqual },
{ "<>", &Generator::GenerateOperNotEqual },
{ "><", &Generator::GenerateOperNotEqual },
{ "<", &Generator::GenerateOperLess },
{ ">", &Generator::GenerateOperGreater },
{ "<=", &Generator::GenerateOperLessOrEqual },
{ ">=", &Generator::GenerateOperGreaterOrEqual },
{ "=<", &Generator::GenerateOperLessOrEqual },
{ "=>", &Generator::GenerateOperGreaterOrEqual },
{ "AND", &Generator::GenerateOperAnd },
{ "OR", &Generator::GenerateOperOr },
{ "XOR", &Generator::GenerateOperXor },
{ "EQV", &Generator::GenerateOperEqv },
//TODO: IMP
};
const GeneratorFuncSpec Generator::m_funcspecs[] =
{
{ KeywordABS, &Generator::GenerateFuncAbs },
{ KeywordRND, &Generator::GenerateFuncRnd },
{ KeywordPEEK, &Generator::GenerateFuncPeek },
{ KeywordINP, &Generator::GenerateFuncInp },
{ KeywordLEN, &Generator::GenerateFuncLen },
{ KeywordINKEY, &Generator::GenerateFuncInkey },
{ KeywordCSRLIN, &Generator::GenerateFuncCsrlin },
{ KeywordPOS, &Generator::GenerateFuncPos },
{ KeywordSQR, &Generator::GenerateFuncSqr },
{ KeywordSIN, &Generator::GenerateFuncSin },
{ KeywordCOS, &Generator::GenerateFuncCos },
{ KeywordTAN, &Generator::GenerateFuncTan },
{ KeywordATN, &Generator::GenerateFuncAtn },
{ KeywordEXP, &Generator::GenerateFuncExp },
{ KeywordLOG, &Generator::GenerateFuncLog },
{ KeywordCINT, &Generator::GenerateFuncCint },
{ KeywordFIX, &Generator::GenerateFuncFix },
{ KeywordINT, &Generator::GenerateFuncInt },
{ KeywordSGN, &Generator::GenerateFuncSgn },
{ KeywordCSNG, &Generator::GenerateFuncCsng },
{ KeywordASC, &Generator::GenerateFuncAsc },
{ KeywordIIF, &Generator::GenerateFuncIif },
};
// Comparison function to sort variables by decorated names
static bool CompareVariables(const VariableModel& a, const VariableModel& b)
{
string deconamea = a.GetVariableDecoratedName();
string deconameb = b.GetVariableDecoratedName();
return deconamea < deconameb;
}
static string to_string_octal(uint16_t value)
{
string result;
for (int i = 0; i < 6; i++)
{
result.insert(0, 1, '0' + (value & 7));
value >>= 3;
}
return result;
}
static string to_string_float(float value)
{
string result = std::to_string(value);
while (result[result.size() - 1] == '0') // trim ending zeroes
result.erase(result.size() - 1);
return result;
}
static uint32_t float_to_dec_float(float fvalue)
{
uint32_t bits; std::memcpy(&bits, &fvalue, sizeof(uint32_t));
if (bits != 0)
{
int exp = (((bits >> 24) & 0x7F) + 1) & 0x7F;
bits = (bits & 0x80FFFFFF) | (exp << 24);
}
return bits;
}
//////////////////////////////////////////////////////////////////////
// Get expression value as integer, put in register R0.
// Use only when we know expr.IsConstExpression() == true, and it can't be ValueTypeString.
#define GET_CONSTEXPR_INT_VALUE_IN_R0(expr) { \
int ivalue = (int)std::floor(expr.GetConstExpressionDValue()); \
if (ivalue == 0) \
AddLine("\tCLR\tR0"); \
else \
AddLine("\tMOV\t#" + std::to_string(ivalue) + "., R0"); \
}
// Get expression value as integer, put in register R1.
// Use only when we know expr.IsConstExpression() == true, and it can't be ValueTypeString.
#define GET_CONSTEXPR_INT_VALUE_IN_R1(expr) { \
int ivalue = (int)std::floor(expr.GetConstExpressionDValue()); \
if (ivalue == 0) \
AddLine("\tCLR\tR1"); \
else \
AddLine("\tMOV\t#" + std::to_string(ivalue) + "., R1"); \
}
// For constant Integer/Single expression expr, returns one of:
// " CLR "
// " MOV #NNNNN, "
static string GET_CONSTEXPR_INT_VALUE_AS_CLRMOV(ExpressionModel expr)
{
int ivalue = (int)std::floor(expr.GetConstExpressionDValue());
if (ivalue == 0)
return "\tCLR\t";
else \
return "\tMOV\t#" + std::to_string(ivalue) + "., ";
}
//////////////////////////////////////////////////////////////////////
Generator::Generator(SourceModel* source, FinalModel* final,
const std::vector<string>* initlines, const std::vector<string>* termlines)
: m_source(source), m_final(final), m_initlines(initlines), m_termlines(termlines),
m_lineindex(-1), m_line(nullptr), m_local(0), m_runtimeneeds(), m_notimplemented()
{
assert(source != nullptr);
assert(final != nullptr);
assert(initlines != nullptr);
assert(termlines != nullptr);
}
void Generator::AddRuntimeCall(RuntimeSymbol rtsymbol, string comment)
{
string rtsymbolname = GetRuntimeSymbolName(rtsymbol);
// FIS implemented on hardware
bool hardwarefis = (g_platform == PlatformUKNC) &&
(rtsymbol >= RuntimeFADD && rtsymbol <= RuntimeFDIV);
string statement = hardwarefis
? "\t" + rtsymbolname + "\tSP"
: "\tCALL\t" + rtsymbolname;
if (comment.empty())
m_final->AddLine(statement);
else
m_final->AddLine(statement + "\t; " + comment);
if (!hardwarefis)
m_runtimeneeds.insert(rtsymbol);
}
void Generator::ProcessBegin()
{
AddLine("START:");
// Copy initialization code from the runtime template
for (const string& line : *m_initlines)
m_final->AddLine(line);
}
void Generator::ProcessEnd()
{
// Enumerate all the prepared lines to format them properly
for (string& line : m_final->lines)
{
int pos = 0;
for (size_t i = 0; i < line.size(); i++)
{
char ch = line[i];
if (ch == '\t')
{
pos = (pos + 8) / 8 * 8;
if (pos == 24)
{
line.insert(i, 1, '\t');
i++;
}
else if (pos > 32)
{
line[i] = ' '; // replace tab with space char
}
}
else
pos++;
}
}
AddLine("LEND:");
// Copy termination code from the runtime template
for (const string& line : *m_termlines)
m_final->AddLine(line);
GenerateStrings();
GenerateVariables();
GenerateDataBlock();
GenerateRuntimeNeeds();
//NOTE: .END instruction will be generated in main.cpp
// Show list of statements/functions not implemented yet
if (!m_notimplemented.empty())
{
std::cerr << "WARNING: The following statements/functions have not yet been implemented:" << std::endl;
bool needcomma = false;
for (KeywordIndex keyword : m_notimplemented)
{
if (needcomma)
std::cerr << ", ";
std::cerr << GetKeywordString(keyword);
needcomma = true;
}
std::cerr << std::endl;
}
}
void Generator::GenerateConstString(string label, string str)
{
string strlen = std::to_string(str.length());
if (str.length() > 7) strlen += '.';
if (str.length() % 2 == 0) str += '\0'; // to align strings to word boundary
// Mask special symbols, mask '/'
std::ostringstream oss;
if (!label.empty())
oss << label << ":";
oss << "\t.ASCII\t<" << strlen << ">";
bool mode = false; // false = out of brackets, true = inside brackets
for (size_t i = 0; i < str.length(); i++)
{
char ch = str[i];
if ((ch >= 0 && ch < 32) || ch == '/')
{
if (mode)
{
oss << "/";
mode = false;
}
oss << "<" << std::oct << (unsigned int)ch << ">";
}
else
{
if (!mode)
{
oss << "/";
mode = true;
}
oss << ch;
}
if (oss.tellp() >= 93 - 6)
{
if (mode)
{
oss << "/";
mode = false;
}
AddLine(oss.str());
oss.str("");
oss.clear();
if (i < str.length() - 1)
oss << "\t.ASCII\t";
}
}
if (oss.tellp() > 0)
{
if (mode)
oss << "/";
AddLine(oss.str());
}
}
void Generator::GenerateStrings()
{
if (m_source->conststrings.empty())
return;
AddComment("STRINGS");
AddLine("\t.EVEN");
AddLine("ST0:\t.WORD\t0\t; empty string");
for (size_t stno = 0; stno < m_source->conststrings.size(); ++stno)
{
string strdeco = "ST" + std::to_string(stno + 1);
string& str = m_source->conststrings[stno];
GenerateConstString(strdeco, str);
}
}
void Generator::GenerateVariables()
{
if (m_source->vars.empty())
return;
AddComment("VARIABLES");
AddLine("\t.EVEN");
std::sort(m_source->vars.begin(), m_source->vars.end(), CompareVariables);
for (auto it = std::begin(m_source->vars); it != std::end(m_source->vars); ++it)
{
string deconame = DecorateVariableName(it->name);
//TODO: Calculate number of array elements multiplying all indices
ValueType vtype = it->GetValueType();
switch (vtype)
{
case ValueTypeInteger:
AddLine(deconame + ":\t.WORD\t0\t; " + it->name);
break;
case ValueTypeString:
AddLine(deconame + ":\t.BLKB\t256.\t; " + it->name);
break;
default: // Single
AddLine(deconame + ":\t.WORD\t0,0\t; " + it->name);
break;
}
}
}
void Generator::GenerateDataBlock()
{
if (m_source->data.empty())
return;
AddComment("DATA BLOCK");
AddLine("\t.EVEN");
size_t firstdatacount = 0;
ValueType firstdatatype = ValueTypeNone;
size_t datacount = 0;
for (size_t i = 0; i < m_source->data.size(); i++)
{
const DataElementModel& dataelem = m_source->data[i];
string label;
if (datacount == 0)
AddLine("D" + std::to_string(i) + ":");
datacount++;
if (datacount >= 8000 ||
i == m_source->data.size() - 1 ||
(m_source->data[i + 1].vtype != dataelem.vtype || m_source->data[i + 1].fixed))
{
if (firstdatacount == 0)
{
firstdatacount = datacount; // for DATACN initialization
firstdatatype = dataelem.vtype; // for DATATY
}
// write data descriptor
uint16_t descriptor = (uint16_t)((dataelem.vtype << 13) | datacount);
AddLine("\t.WORD\t" + to_string_octal(descriptor) + "\t\t; " + GetValueTypeStr(dataelem.vtype) + " * " + std::to_string(datacount));
string line;
for (size_t k = 0; k < datacount; k++)
{
const DataElementModel& elem = m_source->data[i + 1 - datacount + k];
switch (elem.vtype)
{
case ValueTypeInteger:
if (line.empty()) line = "\t.WORD\t"; else line += ", ";
line += std::to_string((int)std::floor(elem.dvalue)) + ".";
if (k % 8 == 7)
{
AddLine(line);
line.clear();
}
break;
case ValueTypeSingle:
{
if (line.empty()) line = "\t.WORD\t"; else line += ", ";
uint32_t wvalue = float_to_dec_float((float)elem.dvalue);
line += to_string_octal(wvalue & 0xFFFF) + "," + to_string_octal(wvalue >> 16);
if (k % 4 == 3)
{
AddLine(line);
line.clear();
}
break;
}
case ValueTypeString:
GenerateConstString("", elem.svalue);
break;
}
if (!line.empty() && k == datacount - 1)
{
AddLine(line);
line.clear();
}
}
datacount = 0;
}
}
AddLine("\t.WORD\t0\t\t; End of DATA");
if (!g_turbo8)
AddLine("\t.GLOBL\tDATAPT, DATATY, DATACN");
AddLine("DATAPT:\t.WORD\tD0+2\t\t; Data pointer");
AddLine("DATATY:\t.WORD\t" + to_string_octal(firstdatatype << 13) + "\t\t; Data type");
AddLine("DATACN:\t.WORD\t" + std::to_string(firstdatacount) + ".\t\t; Data counter");
}
void Generator::GenerateRuntimeNeeds()
{
AddComment("RUNTIME CALLS");
int countinline = 0;
string line;
for (RuntimeSymbol need : m_runtimeneeds)
{
if (line.empty())
line = g_turbo8 ? ";\t" : "\t.GLOBL\t";
if (countinline > 0)
line += ", ";
line += GetRuntimeSymbolName(need);
countinline++;
if (countinline >= 4)
{
AddLine(line);
line.clear();
countinline = 0;
}
}
if (!line.empty())
AddLine(line);
}
bool Generator::ProcessLine()
{
if (m_lineindex == INT_MAX)
return false;
if (m_lineindex < 0)
{
ProcessBegin();
m_lineindex = 0;
}
else
m_lineindex++;
if (m_lineindex >= (int)m_source->lines.size())
{
ProcessEnd();
m_lineindex = INT_MAX;
return false;
}
m_line = &(m_source->lines[m_lineindex]);
m_local = 0; // reset local labels counter
// Skip DATA lines completely, will process them in GenerateDataBlock
if (m_line->statement.token.keyword == KeywordDATA)
return true;
// Show the line text and line number, unless it's a comment line without line number
if (m_line->linenum != 0 ||
m_line->statement.token.keyword != KeywordREM)
{
AddComment(m_line->text);
string linenumlabel = m_line->GetLineNumberLabel() + ":";
AddLine(linenumlabel);
}
GenerateStatement(m_line->statement);
return true;
}
void Generator::Error(const string& message)
{
std::cerr << "ERROR ";
if (m_line->linenum == 0)
std::cerr << "at " << m_line->srclinenum;
else
std::cerr << "in line " << m_line->linenum;
std::cerr << " - " << message << std::endl;
m_line->error = true;
RegisterError();
}
void Generator::Warning(const Token& token, const string& message)
{
std::cerr << "WARNING: at " << token.line << ":" << token.pos;
if (m_line->linenum != 0)
std::cerr << " line " << m_line->linenum;
std::cerr << " - " << message << std::endl;
}
void Generator::GenerateStatement(StatementModel& statement)
{
// Find keyword generator implementation
KeywordIndex keyword = statement.token.keyword;
GeneratorMethodRef methodref = FindGeneratorMethodRef(keyword);
if (methodref == nullptr)
{
Error("Generator for keyword " + GetKeywordString(keyword) + " not found.");
return;
}
(this->*methodref)(statement);
}
void Generator::GenerateExpression(const ExpressionModel& expr)
{
assert(!expr.IsEmpty());
const ExpressionNode& root = expr.nodes[expr.root];
GenerateExpression(expr, root);
}
// Generate code to calculate the expression; result will be in register R0
void Generator::GenerateExpression(const ExpressionModel& expr, const ExpressionNode& node)
{
assert(!expr.IsEmpty());
if (node.constval)
{
switch (node.vtype)
{
case ValueTypeInteger:
{
int ivalue = (int)std::floor(node.token.dvalue);
if (ivalue == 0)
AddLine("\tCLR\tR0");
else
{
string svalue = "#" + std::to_string(ivalue) + ".";
AddLine("\tMOV\t" + svalue + ", R0");
}
return;
}
case ValueTypeSingle:
{
float fvalue = static_cast<float>(node.token.dvalue);
string comment = "const " + to_string_float(fvalue);
uint32_t bits = float_to_dec_float(fvalue);
uint16_t wordlo = bits & 0xFFFF;
uint16_t wordhi = bits >> 16;
AddLine((wordlo == 0 ? "\tCLR\t" : "\tMOV\t#" + to_string_octal(wordlo) + ", ") + "-(SP)\t; " + comment);
AddLine((wordhi == 0 ? "\tCLR\t" : "\tMOV\t#" + to_string_octal(wordhi) + ", ") + "-(SP)");
return;
}
case ValueTypeString:
AddComment("TODO constval String");
return;
}
}
// Function
if (node.token.type == TokenTypeKeyword && IsFunctionKeyword(node.token.keyword))
{
GenerateExprFunction(expr, node);
return;
}
// Variable
if (node.token.type == TokenTypeIdentifier)
{
string canoname = GetCanonicVariableName(node.token.text);
string deconame = DecorateVariableName(canoname);
if (node.vtype == ValueTypeSingle)
{
AddLine("\tMOV\t" + deconame + ", -(SP)\t; var " + canoname); // lower
AddLine("\tMOV\t" + deconame + "+2, -(SP)"); // higher
}
else // Integer, String
{
AddLine("\tMOV\t" + deconame + ", R0\t; var " + canoname);
}
return;
}
if (node.vtype == ValueTypeString)
{
AddComment("TODO calculate string expression");
return;
}
// Binary operation
if (node.token.type == TokenTypeOperation && node.left >= 0 && node.right >= 0)
{
GenerateExprBinaryOperation(expr, node);
return;
}
// Unary operation
else if (node.token.type == TokenTypeOperation && node.left == -1 && node.right >= 0)
{
if (node.token.keyword == KeywordNOT)
GenerateExprUnaryNot(expr, node);
else if (node.token.text == "-") // unary '-'
GenerateExprUnaryMinus(expr, node);
//TODO: unary +
else
AddComment("TODO generate unary operation " + node.token.text);
return;
}
if (node.left != -1 || node.right != -1)
{
AddComment("TODO generate complex expression");
return;
}
}
void Generator::GenerateExprUnaryNot(const ExpressionModel& expr, const ExpressionNode& node)
{
assert(node.left == -1);
assert(node.right >= 0);
const ExpressionNode& noderight = expr.nodes[node.right];
assert(noderight.vtype != ValueTypeString);
GenerateExpression(expr, noderight);
AddLine("\tCOM\tR0\t; NOT");
}
void Generator::GenerateExprUnaryMinus(const ExpressionModel& expr, const ExpressionNode& node)
{
assert(node.left == -1);
assert(node.right >= 0);
const string comment = "\t; unary \'-\'";
const ExpressionNode& noderight = expr.nodes[node.right];
assert(noderight.vtype != ValueTypeString);
GenerateExpression(expr, noderight);
if (noderight.vtype == ValueTypeInteger)
AddLine("\tNEG\tR0" + comment);
else if (noderight.vtype == ValueTypeSingle)
AddLine("\tADD\t#100000, (SP)" + comment); // invert sign
}
void Generator::GenerateExprBinaryOperation(const ExpressionModel& expr, const ExpressionNode& node)
{
const ExpressionNode& nodeleft = expr.nodes[node.left];
const ExpressionNode& noderight = expr.nodes[node.right];
if (nodeleft.vtype == ValueTypeNone || noderight.vtype == ValueTypeNone)
{
std::cerr << "ERROR in expression at " << node.token.line << ":" << node.token.pos << " - Cannot calculate value type for the node." << std::endl;
m_line->error = true;
RegisterError();
return;
}
// Find operator implementation
string text = node.token.text;
GeneratorOperMethodRef methodref = nullptr;
for (auto it = std::begin(m_operspecs); it != std::end(m_operspecs); ++it)
{
if (text == it->text)
{
methodref = it->methodref;
break;
}
}
if (methodref != nullptr)
(this->*methodref)(expr, node, nodeleft, noderight);
else
{
std::cerr << "ERROR in expression at " << node.token.line << ":" << node.token.pos << " - TODO generate operator \'" + text + "\'." << std::endl;
m_line->error = true;
RegisterError();
return;
}
}
void Generator::GenerateExprFunction(const ExpressionModel& expr, const ExpressionNode& node)
{
assert(!node.constval);
assert(node.token.keyword != KeywordNone);
assert(node.token.type == TokenTypeKeyword && IsFunctionKeyword(node.token.keyword));
KeywordIndex keyword = node.token.keyword;
GeneratorFuncMethodRef methodref = nullptr;
for (auto it = std::begin(m_funcspecs); it != std::end(m_funcspecs); ++it)
{
if (keyword == it->keyword)
{
methodref = it->methodref;
break;
}
}
if (methodref == nullptr)
{
AddComment("TODO generate function expression for " + GetKeywordString(keyword));
m_notimplemented.insert(keyword);
return;
}
(this->*methodref)(expr, node);
}
// Calculate expression and assign the result to variable
// To use in LET and FOR
void Generator::GenerateAssignment(VariableExpressionModel& var, ExpressionModel& expr)
{
ValueType vtype = var.GetValueType();
string canoname = var.GetVariableCanonicName();
string deconame = var.GetVariableDecoratedName();
const string comment = "\t; var " + canoname + " assignment";
if (expr.IsConstExpression())
{
if (vtype == ValueTypeInteger)
{
int ivalue = (int)std::floor(expr.GetConstExpressionDValue());
if (ivalue == 0)
{
AddLine("\tCLR\t" + deconame + comment);
}
else {
string svalue = "#" + std::to_string(ivalue) + ".";
AddLine("\tMOV\t" + svalue + ", " + deconame + comment);
}
}
else if (vtype == ValueTypeSingle) // const Single
{
float fvalue = static_cast<float>(expr.GetConstExpressionDValue());
string comment = "\t; var " + canoname + " = const " + to_string_float(static_cast<float>(expr.GetConstExpressionDValue()));
uint32_t bits = float_to_dec_float(fvalue);
uint16_t wordlo = bits & 0xFFFF;
uint16_t wordhi = bits >> 16;
AddLine((wordlo == 0 ? "\tCLR\t" : "\tMOV\t#" + to_string_octal(wordlo) + ", ") + deconame + comment);
AddLine((wordhi == 0 ? "\tCLR\t" : "\tMOV\t#" + to_string_octal(wordhi) + ", ") + deconame + "+2");
}
else if (vtype == ValueTypeString) // const String
{
string svalue = expr.GetConstExpressionSValue();
int sindex = m_source->GetConstStringIndex(svalue);
//TODO: Special case for one-char string
AddLine("\tMOV\t#ST" + std::to_string(sindex) + ", R0");
AddLine("\tMOV\t#" + deconame + ", R1");
AddRuntimeCall(RuntimeSTCP, "var " + canoname + " assignment");
}
}
else if (expr.IsVariableExpression())
{
string svalue = expr.GetVariableExpressionDecoratedName();
AddLine("\tMOV\t" + svalue + ", " + deconame + comment);
}
else // non-const, non-variable
{
ExpressionNode& root = expr.nodes[expr.root];
// Convert "A% = A% + N" and "A% = A% - N" assignments into INC/DEC/ADD/SUB
if (vtype == ValueTypeInteger && root.token.IsBinaryOperation() &&
(root.token.text == "-" || root.token.text == "+") &&
expr.nodes[root.left].token.type == TokenTypeIdentifier &&
GetCanonicVariableName(expr.nodes[root.left].token.text) == var.name &&
expr.nodes[root.right].constval &&
(expr.nodes[root.right].vtype == ValueTypeInteger || expr.nodes[root.right].vtype == ValueTypeSingle))
{
bool plusminus = (root.token.text == "+");
int ivalue = (int)std::floor(expr.nodes[root.right].token.dvalue);
if (plusminus && ivalue == 1)
AddLine("\tINC\t" + deconame + comment);
else if (!plusminus && ivalue == 1)
AddLine("\tDEC\t" + deconame + comment);
else if (plusminus && ivalue != 1)
AddLine("\tADD\t#" + std::to_string(ivalue) + "., " + deconame + comment);
else //if (!plusminus && ivalue != 1)
AddLine("\tSUB\t#" + std::to_string(ivalue) + "., " + deconame + comment);
}
else if (vtype == ValueTypeSingle) // non-const Single
{
GenerateExpression(expr);
if (expr.GetExpressionValueType() == ValueTypeInteger)
AddRuntimeCall(RuntimeITOF, "to Single"); // result on stack
AddLine("\tMOV\t(SP)+, " + deconame + "+2" + comment);
AddLine("\tMOV\t(SP)+, " + deconame);
}
else if (vtype == ValueTypeInteger) // non-const non-variable Integer
{
GenerateExpression(expr);
if (expr.GetExpressionValueType() == ValueTypeSingle)
AddRuntimeCall(RuntimeFTOI, "to Integer"); // result in R0
AddLine("\tMOV\tR0, " + deconame + comment);
}
else // non-const non-variable String
{
GenerateExpression(expr);
AddLine("\tMOV\t" + deconame + ", R1");
AddRuntimeCall(RuntimeSTCP, "var " + canoname + " assignment");
}
}
}
void Generator::GenerateIgnoredStatement(StatementModel& statement)
{
AddComment(statement.token.text + " statement is ignored");
Warning(statement.token, statement.token.text + " statement is ignored");
}
void Generator::GenerateBeep(StatementModel&)
{
AddLine("\tMOV\t#7, R0\t; bell");
AddRuntimeCall(RuntimeWRCH, "PRINT char");
}
void Generator::GenerateClear(StatementModel& statement)
{
AddComment("CLEAR statement is ignored");
Warning(statement.token, "CLEAR statement is ignored");
}
void Generator::GenerateCls(StatementModel&)
{
AddLine("\tMOV\t#14, R0");
AddRuntimeCall(RuntimeWRCH, "PRINT char");
}
void Generator::GenerateColor(StatementModel& statement)
{
assert(statement.args.size() > 0);
ExpressionModel& expr1 = statement.args[0]; // foreground color number
assert(expr1.GetExpressionValueType() != ValueTypeString);
string stat1;
if (expr1.IsEmpty())
stat1 = "\tMOV\t#-1, ";
else
{
if (expr1.IsConstExpression())
stat1 = GET_CONSTEXPR_INT_VALUE_AS_CLRMOV(expr1);
else if (expr1.IsVariableExpression() && expr1.GetExpressionValueType() == ValueTypeInteger)
stat1 = "\tMOV\t" + expr1.GetVariableExpressionDecoratedName() + ", ";
else
{
GenerateExpression(expr1);
stat1 = "\tMOV\tR0, ";
}
}
string stat2;
if (statement.args.size() < 2 || statement.args[1].IsEmpty())
stat2 = "\tMOV\t#-1, ";
else
{
ExpressionModel& expr2 = statement.args[1];
assert(expr2.GetExpressionValueType() != ValueTypeString);
if (expr2.IsConstExpression())
stat2 = GET_CONSTEXPR_INT_VALUE_AS_CLRMOV(expr2);
else if (expr2.IsVariableExpression() && expr2.GetExpressionValueType() == ValueTypeInteger)
stat2 = "\tMOV\t" + expr2.GetVariableExpressionDecoratedName() + ", ";
else
{
AddLine(stat1 + "-(SP)"); // PUSH
stat1 = "\tMOV\t(SP)+, ";
GenerateExpression(expr2); // result in R0
stat2 = "\tMOV\tR0, ";
}
}
if (statement.args.size() < 3 || statement.args[2].IsEmpty())
{
AddLine(stat1 + "R0");
AddLine(stat2 + "R1");
AddLine("\tMOV\t#-1, R2");
}
else
{
ExpressionModel& expr3 = statement.args[2];
assert(expr3.GetExpressionValueType() != ValueTypeString);
if (expr3.IsConstExpression())
{
AddLine(stat1 + "R0");
AddLine(stat2 + "R1");
AddLine(GET_CONSTEXPR_INT_VALUE_AS_CLRMOV(expr3) + "R2");
}
else if (expr3.IsVariableExpression() && expr3.GetExpressionValueType() == ValueTypeInteger)
{
AddLine(stat1 + "R0");
AddLine(stat2 + "R1");
AddLine("\tMOV\t" + expr3.GetVariableExpressionDecoratedName() + ", R2");
}
else
{
AddLine(stat2 + "-(SP)"); // PUSH
GenerateExpression(expr3); // result in R0
AddLine("\tMOV\tR0, R2");
AddLine("\tMOV\t(SP)+, R1"); // POP R1
AddLine(stat1 + "R0");
}
}
AddRuntimeCall(RuntimeCOLR, "COLOR");
}
void Generator::GenerateData(StatementModel& statement)
{
//NOTE: Data elements generated in DATA BLOCK
assert(false); // should never fall down here
}
void Generator::GenerateDim(StatementModel&)
{
// Nothing to generate, DIM variables declared in ProcessEnd()
}
void Generator::GenerateDraw(StatementModel& statement)
{
//TODO
AddComment("TODO DRAW");
m_notimplemented.insert(KeywordDRAW);
}
void Generator::GenerateEnd(StatementModel&)
{
// END generates JMP LEND, but only if END is not on the last line
string nextlinelabel = m_source->GetNextLineLabel(m_line->linenum);
if (nextlinelabel != "LEND")
AddLine("\tJMP\tLEND");
}