-
Notifications
You must be signed in to change notification settings - Fork 2
/
compiler.cpp
1870 lines (1859 loc) · 96.1 KB
/
compiler.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
/*
* This is the core of the compiler, a part of the compiler that produces
* assembly code. The code is somewhat ugly (lots of else-if-s), but
* there doesn't appear to be an easy way to avoid that. Using inheritance
* would lead to countless classes and code that's even harder to understand
* and debug. Allegedly, compilers can be nicely structured using the
* visitor behavioral pattern, but, honestly, I don't understand it and
* I doubt it would help significantly.
*/
// TODO: Analyze and possibly apply what G. Sliepen has to say about this
// compiler: https://codereview.stackexchange.com/a/277104/219010
#include "bitManipulations.cpp"
#include "semanticAnalyzer.cpp"
#include <ciso646> // Necessary for Microsoft C++ Compiler (for `and` and `or`).
const char *throwNotImplementedException(std::string message) {
throw new NotImplementedException(message);
return NULL;
}
AssemblyCode convertToInteger32(
const TreeNode &
node, // HappySkeptic suggested me to use constant references to avoid
// Stack Overflow:
// https://atheistforums.org/thread-63150-post-2054368.html#pid2054368
const CompilationContext &context) {
auto originalCode = node.compile(context);
const AssemblyCode::AssemblyType i32 = AssemblyCode::AssemblyType::i32,
i64 = AssemblyCode::AssemblyType::i64,
f32 = AssemblyCode::AssemblyType::f32,
f64 = AssemblyCode::AssemblyType::f64,
null = AssemblyCode::AssemblyType::null;
if (originalCode.assemblyType == null) {
std::cerr
<< "Line " << node.lineNumber << ", Column " << node.columnNumber
<< ", Compiler error: Some part of the compiler attempted to convert \""
<< node.text
<< "\" to \"Integer32\", which makes no sense. This could be an "
"internal compiler error, or there could be something semantically "
"(though not grammatically) very wrong with your program."
<< std::endl;
exit(1);
}
if (originalCode.assemblyType == i32)
return originalCode;
if (originalCode.assemblyType == i64)
return AssemblyCode(
"(i32.wrap_i64\n" + std::string(originalCode.indentBy(1)) + "\n)", i32);
if (originalCode.assemblyType == f32)
return AssemblyCode(
"(i32.trunc_f32_s\n" + std::string(originalCode.indentBy(1)) + "\n)",
i32); // Makes little sense to me (that, when converting to an integer,
// the decimal part of the number is simply truncated), but that's
// how it is done in the vast majority of programming languages.
if (originalCode.assemblyType == f64)
return AssemblyCode("(i32.trunc_f64_s\n" +
std::string(originalCode.indentBy(1)) + "\n)",
i32);
std::cerr << "Line " << node.lineNumber << ", Column " << node.columnNumber
<< ", Compiler error: Internal compiler error, control reached the "
"end of the \"convertToInteger32\" function!"
<< std::endl;
throw std::runtime_error("Logic error in \"convertToInteger32\"");
return AssemblyCode("()");
}
AssemblyCode convertToInteger64(const TreeNode &node,
const CompilationContext &context) {
auto originalCode = node.compile(context);
const AssemblyCode::AssemblyType i32 = AssemblyCode::AssemblyType::i32,
i64 = AssemblyCode::AssemblyType::i64,
f32 = AssemblyCode::AssemblyType::f32,
f64 = AssemblyCode::AssemblyType::f64,
null = AssemblyCode::AssemblyType::null;
if (originalCode.assemblyType == null) {
std::cerr
<< "Line " << node.lineNumber << ", Column " << node.columnNumber
<< ", Compiler error: Some part of the compiler attempted to convert \""
<< node.text
<< "\" to \"Integer64\", which makes no sense. This could be an "
"internal compiler error, or there could be something semantically "
"(though not grammatically) very wrong with your program."
<< std::endl;
exit(1);
}
if (originalCode.assemblyType == i32)
return AssemblyCode(
"(i64.extend_i32_s\n" + // If you don't put "_s", JavaScript Virtual
// Machine is going to interpret the argument as
// unsigned, leading to huge positive numbers
// instead of negative ones.
std::string(originalCode.indentBy(1)) + "\n)",
i64);
if (originalCode.assemblyType == i64)
return originalCode;
if (originalCode.assemblyType == f32)
return AssemblyCode("(i64.trunc_f32_s\n" +
std::string(originalCode.indentBy(1)) + "\n)",
i64);
if (originalCode.assemblyType == f64)
return AssemblyCode("(i64.trunc_f64_s\n" +
std::string(originalCode.indentBy(1)) + "\n)",
i64);
std::cerr << "Line " << node.lineNumber << ", Column " << node.columnNumber
<< ", Compiler error: Internal compiler error, control reached the "
"end of the \"convertToInteger64\" function!"
<< std::endl;
throw std::runtime_error("Logic error in \"convertToInteger64\"");
return AssemblyCode("()");
}
AssemblyCode convertToDecimal32(const TreeNode &node,
const CompilationContext &context) {
auto originalCode = node.compile(context);
const AssemblyCode::AssemblyType i32 = AssemblyCode::AssemblyType::i32,
i64 = AssemblyCode::AssemblyType::i64,
f32 = AssemblyCode::AssemblyType::f32,
f64 = AssemblyCode::AssemblyType::f64,
null = AssemblyCode::AssemblyType::null;
if (originalCode.assemblyType == null) {
std::cerr
<< "Line " << node.lineNumber << ", Column " << node.columnNumber
<< ", Compiler error: Some part of the compiler attempted to convert \""
<< node.text
<< "\" to \"Decimal32\", which makes no sense. This could be an "
"internal compiler error, or there could be something semantically "
"(though not grammatically) very wrong with your program."
<< std::endl;
exit(1);
}
if (originalCode.assemblyType == i32)
return AssemblyCode(
"(f32.convert_i32_s\n" + // Again, those who designed JavaScript Virtual
// Machine had a weird idea that integers
// should be unsigned unless somebody makes
// them explicitly signed via "_s".
std::string(originalCode.indentBy(1)) + "\n)",
f32);
if (originalCode.assemblyType == i64)
return AssemblyCode("(f32.convert_i64_s\n" +
std::string(originalCode.indentBy(1)) + "\n)",
f32);
if (originalCode.assemblyType == f32)
return originalCode;
if (originalCode.assemblyType == f64)
return AssemblyCode("(f32.demote_f64\n" +
std::string(originalCode.indentBy(1)) + "\n)",
f32);
std::cerr << "Line " << node.lineNumber << ", Column " << node.columnNumber
<< ", Compiler error: Internal compiler error, control reached the "
"end of the \"convertToDecimal32\" function!"
<< std::endl;
throw std::runtime_error("Logic error in \"convertToDecimal32\"");
return AssemblyCode("()");
}
AssemblyCode convertToDecimal64(const TreeNode &node,
const CompilationContext &context) {
auto originalCode = node.compile(context);
const AssemblyCode::AssemblyType i32 = AssemblyCode::AssemblyType::i32,
i64 = AssemblyCode::AssemblyType::i64,
f32 = AssemblyCode::AssemblyType::f32,
f64 = AssemblyCode::AssemblyType::f64,
null = AssemblyCode::AssemblyType::null;
if (originalCode.assemblyType == null) {
std::cerr
<< "Line " << node.lineNumber << ", Column " << node.columnNumber
<< ", Compiler error: Some part of the compiler attempted to convert \""
<< node.text
<< "\" to \"Decimal64\", which makes no sense. This could be an "
"internal compiler error, or there could be something semantically "
"(though not grammatically) very wrong with your program."
<< std::endl;
exit(1);
}
if (originalCode.assemblyType == i32)
return AssemblyCode("(f64.convert_i32_s\n" +
std::string(originalCode.indentBy(1)) + "\n)",
f64);
if (originalCode.assemblyType == i64)
return AssemblyCode("(f64.convert_i64_s\n" +
std::string(originalCode.indentBy(1)) + "\n)",
f64);
if (originalCode.assemblyType == f32)
return AssemblyCode("(f64.promote_f32\n" +
std::string(originalCode.indentBy(1)) + "\n)",
f64);
if (originalCode.assemblyType == f64)
return originalCode;
std::cerr << "Line " << node.lineNumber << ", Column " << node.columnNumber
<< ", Compiler error: Internal compiler error, control reached the "
"end of the \"convertToDecimal64\" function!"
<< std::endl;
throw std::runtime_error("Logic error in \"convertToDecimal64\"");
return AssemblyCode("()");
}
AssemblyCode convertTo(const TreeNode &node, const std::string &type,
const CompilationContext &context) {
if (type == "Character" or type == "Integer16" or type == "Integer32" or
isPointerType(type)) // When, in JavaScript Virtual Machine, you can't
// push types of less than 4 bytes (32 bits) onto
// the system stack, you need to convert those to
// Integer32 (i32). Well, makes slightly more sense
// than the way it is in 64-bit x86 assembly, where
// you can put 16-bit values and 64-bit values onto
// the system stack, but you can't put 32-bit
// values.
return convertToInteger32(node, context);
if (type == "Integer64")
return convertToInteger64(node, context);
if (type == "Decimal32")
return convertToDecimal32(node, context);
if (type == "Decimal64")
return convertToDecimal64(node, context);
std::cerr << "Line " << node.lineNumber << ", Column " << node.columnNumber
<< ", Compiler error: Some part of the compiler attempted to get "
"the assembly code for converting \""
<< node.text << "\" into the type \"" << type
<< "\", which doesn't make sense. This could be an internal "
"compiler error, or there could be something semantically "
"(though not grammatically) very wrong with your program."
<< std::endl;
exit(-1);
return AssemblyCode("()");
}
AssemblyCode TreeNode::compile(CompilationContext context) const {
const std::string typeOfTheCurrentNode = getType(context);
AssemblyCode::AssemblyType returnType;
if (isPointerType(typeOfTheCurrentNode))
returnType = AssemblyCode::AssemblyType::i32;
else {
if (!mappingOfAECTypesToWebAssemblyTypes.count(typeOfTheCurrentNode)) {
std::cerr
<< "Line " << lineNumber << ", Column " << columnNumber
<< ", Internal compiler error: The function \"getType\" returned \""
<< typeOfTheCurrentNode
<< "\", which is an invalid name of type. It's for the node with AST "
<< getLispExpression() << ". Aborting the compilation!" << std::endl;
throw InvalidTypenameException();
}
returnType = mappingOfAECTypesToWebAssemblyTypes.at(typeOfTheCurrentNode);
}
auto iteratorPointingToFunctionBeingCompiled =
std::find_if(context.functions.begin(), context.functions.end(),
[=](function someFunction) {
return someFunction.name == context.currentFunctionName;
});
if (iteratorPointingToFunctionBeingCompiled == context.functions.end()) {
std::cerr
<< "Line " << lineNumber << ", Column " << columnNumber
<< ", Internal compiler error: The \"compile(CompilationContext)\" "
"function was called without setting the current function name, "
"aborting compilation (or else the compiler will segfault)!"
<< std::endl;
throw CorruptCompilationContextException(context);
}
function currentFunction = *iteratorPointingToFunctionBeingCompiled;
std::string assembly;
#ifdef OUTPUT_DEBUG_COMMENTS_IN_ASSEMBLY_COMMENTS
assembly += ";; Line " + std::to_string(lineNumber) + ", Column " +
std::to_string(columnNumber) + ", token " + JSONifyString(text) +
"\n";
#endif
if (text == "Does" or text == "Then" or text == "Loop" or
text == "Else") // Blocks of code are stored by the parser as child nodes
// of "Does", "Then", "Else" and "Loop".
{
#ifdef OUTPUT_DEBUG_COMMENTS_IN_ASSEMBLY_COMMENTS
std::string JSON = context.JSONify();
std::string commentedJSON = ";;\t";
for (size_t i = 0; i < JSON.length(); i++)
if (JSON[i] == '\n')
commentedJSON += "\n;;\t";
else
commentedJSON += JSON[i];
assembly += ";;The JSON of the current compilation context is:\n" +
commentedJSON + "\n";
#endif
if (text != "Does")
context.stackSizeOfThisScope =
0; //"TreeRootNode" is supposed to set up the arguments in the scope
// before passing the recursion onto the "Does" node.
for (auto childNode : children) {
if (childNode.text == "Nothing")
continue;
else if (basicDataTypeSizes.count(childNode.text) ||
isPointerType(childNode.text)) {
// Local variables declaration.
for (TreeNode variableName : childNode.children) {
if (context.variableTypes.count(variableName.text))
std::cerr << "Line " << variableName.lineNumber << ", Column "
<< variableName.columnNumber
<< ", Compiler warning: Variable named \""
<< variableName.text
<< "\" is already visible in this scope (to be of type \""
<< context.variableTypes.at(variableName.text) << "\""
<< (context.placesOfVariableDeclarations.count(
variableName.text)
? (", at the line " +
std::to_string(
context.placesOfVariableDeclarations.at(
variableName.text)))
: "")
<< "), this "
"declaration shadows it."
<< std::endl;
if (variableName.text.back() != '[') { // If it's not an array.
context.localVariables[variableName.text] = 0;
for (auto &pair : context.localVariables)
pair.second += isPointerType(childNode.text)
? 4
: basicDataTypeSizes.at(childNode.text);
context.variableTypes[variableName.text] = childNode.text;
context.placesOfVariableDeclarations[variableName.text] =
variableName.lineNumber;
context.stackSizeOfThisFunction +=
isPointerType(childNode.text)
? 4
: basicDataTypeSizes.at(childNode.text);
context.stackSizeOfThisScope +=
isPointerType(childNode.text)
? 4
: basicDataTypeSizes.at(childNode.text);
assembly +=
"(global.set $stack_pointer\n\t(i32.add (global.get "
"$stack_pointer) (i32.const " +
std::to_string(isPointerType(childNode.text)
? 4
: basicDataTypeSizes.at(childNode.text)) +
")) ;;Allocating the space for the local variable \"" +
variableName.text + "\".\n)\n";
if (variableName.children.size() and
variableName.children[0].text ==
":=") // Initial assignment to local variables.
{
TreeNode assignmentNode = variableName.children[0];
assignmentNode.children.insert(assignmentNode.children.begin(),
variableName);
assembly += assignmentNode.compile(context) + "\n";
}
} else { // If that's a local array declaration.
if (!variableName.children.size()) {
std::cerr << "Line " << variableName.lineNumber << ", Column "
<< variableName.columnNumber
<< ", Compiler error: Corrupt AST, the array named \""
<< variableName.text
<< "\" has no child node indicating size." << std::endl;
exit(1);
}
if (!basicDataTypeSizes.count(childNode.text) &&
!isPointerType(childNode.text)) {
std::cerr << "Line " << variableName.lineNumber << ", Column "
<< variableName.columnNumber
<< ", Compiler error: Corrupt AST, the variable is "
"supposed to be of the type \""
<< childNode.text << "\", but no such type exists."
<< std::endl;
exit(1);
}
int arraySizeInBytes =
(isPointerType(childNode.text)
? 4
: basicDataTypeSizes.at(childNode.text)) *
variableName.children[0]
.interpretAsACompileTimeIntegerConstant();
context.localVariables[variableName.text] = 0;
for (auto &pair : context.localVariables)
pair.second += arraySizeInBytes;
context.variableTypes[variableName.text] = childNode.text;
context.placesOfVariableDeclarations[variableName.text] =
childNode.lineNumber;
context.stackSizeOfThisFunction += arraySizeInBytes;
context.stackSizeOfThisScope += arraySizeInBytes;
assembly += "(global.set $stack_pointer\n\t(i32.add (global.get "
"$stack_pointer) (i32.const " +
std::to_string(arraySizeInBytes) +
")) ;;Allocating the space for the local array \"" +
variableName.text + "\".\n)\n";
if (variableName.children.size() == 2 and
variableName.children[1].text == ":=" and
variableName.children[1].children[0].text ==
"{}") // Initial assignments of local arrays.
{
TreeNode initialisationList =
variableName.children[1].children[0];
for (unsigned int i = 0; i < initialisationList.children.size();
i++) {
TreeNode element = initialisationList.children[i];
TreeNode assignmentNode(
":=", variableName.children[1].lineNumber,
variableName.children[1].columnNumber);
TreeNode whereToAssignTheElement(
variableName.text, variableName.lineNumber,
variableName
.columnNumber); // Damn, can you think up a language in
// which writing stuff like this isn't
// as tedious and error-prone as it is
// in C++ or JavaScript? Maybe some
// language in which you can switch
// between a C-like syntax and a
// Lisp-like syntax at will?
whereToAssignTheElement.children.push_back(TreeNode(
std::to_string(i), variableName.children[0].lineNumber,
variableName.children[1].columnNumber));
assignmentNode.children.push_back(whereToAssignTheElement);
assignmentNode.children.push_back(element);
assembly += assignmentNode.compile(context) + "\n";
}
}
}
}
#ifdef OUTPUT_DEBUG_COMMENTS_IN_ASSEMBLY_COMMENTS
std::string JSON =
JSONifyMapOfInts(context.localVariables) +
"\n"; //"\n" is added to make the output more comprehensible in case
// the next assembly directive is also a comment, to put an
// empty line between the two comments.
std::string commentedJSON = ";;\t";
for (size_t i = 0; i < JSON.length(); i++)
if (JSON[i] == '\n')
commentedJSON += "\n;;\t";
else
commentedJSON += JSON[i];
assembly += ";;The JSON of the new \"localVariables\" object in the "
"current compilation context is:\n" +
commentedJSON + "\n";
#endif
} else if (childNode.text == "InstantiateStructure") {
if (childNode.children.size() != 1) {
std::cerr << "Line " << childNode.lineNumber << ", Column "
<< childNode.columnNumber
<< ", Compiler error: Corrupt AST, the node "
"\"InstantiateStructure\" should "
"have exactly one child, but it has "
<< childNode.children.size()
<< ". Aborting the compilation!" << std::endl;
exit(1);
}
TreeNode nodeWithStructureName = childNode.children[0];
if (!isValidVariableName(nodeWithStructureName.text) ||
AECkeywords.count(nodeWithStructureName.text) ||
nodeWithStructureName.text.back() == '[') {
std::cerr << "Line " << nodeWithStructureName.lineNumber
<< ", Column " << nodeWithStructureName.columnNumber
<< ", Compiler error: The name \""
<< nodeWithStructureName.text
<< "\" is supposed to be a structure name, but it's not a "
"valid AEC name. Quitting now!"
<< std::endl;
exit(1);
}
auto iteratorPointingToTheStructure =
std::find_if(context.structures.begin(), context.structures.end(),
[=](structure str) {
return str.name == nodeWithStructureName.text;
});
if (iteratorPointingToTheStructure == context.structures.end() &&
!context.structureSizes.count(nodeWithStructureName.text)) {
std::cerr << "Line " << nodeWithStructureName.lineNumber
<< ", Column " << nodeWithStructureName.columnNumber
<< ", Compiler error: The structure named \""
<< nodeWithStructureName.text
<< "\" is not visible in the current scope. Quitting now!"
<< std::endl;
auto most_similar_structure_iterator = std::max_element(
context.structures.begin(), context.structures.end(),
[=](const structure first_potentially_similar_structure,
const structure second_potentially_similar_structure) {
return
#ifndef USING_LEVENSTEIN_DISTANCE
longest_common_subsequence_length(
first_potentially_similar_structure.name,
nodeWithStructureName.text) <
longest_common_subsequence_length(
second_potentially_similar_structure.name,
nodeWithStructureName.text);
#else
Levenstein_distance(
first_potentially_similar_structure.name,
nodeWithStructureName.text) >
Levenstein_distance(
second_potentially_similar_structure.name,
nodeWithStructureName.text);
#endif
});
if (most_similar_structure_iterator != context.structures.end() &&
longest_common_subsequence_length(
most_similar_structure_iterator->name,
nodeWithStructureName.text)) {
std::cerr << "By the way, maybe you meant \""
<< most_similar_structure_iterator->name << "\"?"
<< std::endl;
}
exit(1);
} else if (iteratorPointingToTheStructure == context.structures.end()) {
std::cerr
<< "Line " << nodeWithStructureName.lineNumber << ", Column "
<< nodeWithStructureName.columnNumber
<< ", Internal compiler error: Some part of the compiler has "
"corrupted the compilation context, the structure named \""
<< nodeWithStructureName.text
<< "\" isn't visible, but its size is. Aborting the compilation!"
<< std::endl;
throw CorruptCompilationContextException(context);
} else if (!context.structureSizes.count(nodeWithStructureName.text)) {
std::cerr
<< "Line " << nodeWithStructureName.lineNumber << ", Column "
<< nodeWithStructureName.columnNumber
<< ", Internal compiler error: Some part of the compiler has "
"corrupted the compilation context, the structure named \""
<< nodeWithStructureName.text
<< "\" is visible, but its size isn't. Aborting the compilation!"
<< std::endl;
throw CorruptCompilationContextException(context);
}
if (context.structureSizes[nodeWithStructureName.text] == 0) {
std::cerr << "Line " << nodeWithStructureName.lineNumber
<< ", Column " << nodeWithStructureName.columnNumber
<< ", Compiler error: Cannot instantiate an empty "
"structure as a local variable! The structure \""
<< nodeWithStructureName.text << "\" has the size of zero."
<< std::endl;
exit(1);
}
for (TreeNode instanceName : nodeWithStructureName.children) {
if (!isValidVariableName(instanceName.text) ||
AECkeywords.count(instanceName.text)) {
std::cerr << "Line " << instanceName.lineNumber << ", Column "
<< instanceName.columnNumber
<< ", Compiler error: The name \"" << instanceName.text
<< "\" is supposed to be an instance name, but it's not "
<< "a valid AEC name. Quitting now!" << std::endl;
exit(1);
}
context.variableTypes[instanceName.text] =
iteratorPointingToTheStructure->name;
context.placesOfVariableDeclarations[instanceName.text] =
instanceName.lineNumber;
context.localVariables[instanceName.text] = 0;
int arraySizeInBytes = 0, arraySizeInStructures = 0;
if (instanceName.text.back() == '[' &&
instanceName.children.size() == 1) {
arraySizeInStructures =
instanceName.children[0]
.interpretAsACompileTimeIntegerConstant();
arraySizeInBytes = iteratorPointingToTheStructure->sizeInBytes *
arraySizeInStructures;
} else {
if (instanceName.text.back() == '[') {
std::cerr
<< "Line " << instanceName.lineNumber << ", Column "
<< instanceName.columnNumber
<< ", Compiler error: Corrupt AST, the node with text \""
<< instanceName.text
<< "\" is supposed to have 1 child, but it has "
<< instanceName.children.size()
<< ". Aborting the compilation!" << std::endl;
exit(1);
} else {
arraySizeInBytes = iteratorPointingToTheStructure->sizeInBytes;
arraySizeInStructures = 1;
}
}
if (arraySizeInBytes < 1 || arraySizeInStructures < 1) {
std::cerr << "Line " << instanceName.lineNumber << ", Column "
<< instanceName.columnNumber
<< ", Internal compiler error: Some part of the "
"compiler attempted "
"to compile an array with size less than 1, which "
"doesn't make sense. "
"Throwing an exception!"
<< std::endl;
throw std::runtime_error("Compiling an array of negative size!");
}
for (auto bitand pair : context.localVariables)
pair.second += arraySizeInBytes;
context.stackSizeOfThisFunction += arraySizeInBytes;
context.stackSizeOfThisScope += arraySizeInBytes;
assembly +=
"(global.set $stack_pointer\n\t(i32.add (global.get "
"$stack_pointer) (i32.const " +
std::to_string(arraySizeInBytes) +
")) ;;Allocating the space for the local structure instance \"" +
instanceName.text + "\".\n)\n";
// Now we can set the default values. Let's set the members without
// specified default values to 0, this may avoid some bugs.
for (int i = 0; i < arraySizeInStructures; i++) {
for (std::string memberName :
iteratorPointingToTheStructure->memberNames) {
if (context.structureSizes.count(
iteratorPointingToTheStructure->memberTypes.at(
memberName))) { // Nested local strucrues.
for (unsigned int k = 0;
k < iteratorPointingToTheStructure->arraySize[memberName];
k++) {
// Let's solve this using S-expressions...
CompilationContext fakeContext =
context; // To avoid the internal compiler error in the
// semantic analyzer.
fakeContext.stackSizeOfThisFunction = 0;
fakeContext.stackSizeOfThisScope = 0;
std::string nameOfTheInnerStructure;
do {
nameOfTheInnerStructure = "innerStructureInstantiated" +
std::to_string(std::rand());
} while (
context.variableTypes.count(nameOfTheInnerStructure));
TreeNode innerStructureNameNode(
nameOfTheInnerStructure, // To silence useless warnings
// about supposed variable
// shadowing.
instanceName.lineNumber, instanceName.columnNumber);
TreeNode innerStructureTypeNode(
iteratorPointingToTheStructure->memberTypes.at(
memberName),
instanceName.lineNumber, instanceName.columnNumber);
innerStructureTypeNode.children.push_back(
innerStructureNameNode);
TreeNode instantiateStructureNode("InstantiateStructure",
instanceName.lineNumber,
instanceName.columnNumber);
instantiateStructureNode.children.push_back(
innerStructureTypeNode);
TreeNode instanceNameNode(instanceName.text,
instanceName.lineNumber,
instanceName.columnNumber);
instanceNameNode.children.push_back(TreeNode(
std::to_string(i), instanceName.lineNumber,
instanceName
.columnNumber)); // If we don't do this, the compiler
// will crash if somebody tries to
// instantiate local (inside a
// function, not global) array of
// nested structures.
TreeNode memberNameNode(memberName, instanceName.lineNumber,
instanceName.columnNumber);
TreeNode arrayIndexNode(std::to_string(k),
instanceName.lineNumber,
instanceName.columnNumber);
memberNameNode.children.push_back(arrayIndexNode);
TreeNode dotOperator(".", instanceName.lineNumber,
instanceName.columnNumber);
dotOperator.children = <% instanceNameNode, memberNameNode %>;
TreeNode assignmentOperator(":=", instanceName.lineNumber,
instanceName.columnNumber);
assignmentOperator.children =
<% dotOperator, innerStructureNameNode %>;
TreeNode fakeInnerFunctionNode(
"Does", instanceName.lineNumber,
instanceName
.columnNumber); // Again, to work around the
// hard-to-fix issue in the semantic
// analyzer which causes internal
// compiler errors.
fakeInnerFunctionNode.children =
<% instantiateStructureNode, assignmentOperator %>;
assembly += fakeInnerFunctionNode.compile(fakeContext) + "\n";
}
continue;
}
for (unsigned int k = 0;
k < iteratorPointingToTheStructure->arraySize[memberName];
k++) {
// And now we need to do that daunting task of constructing an
// S-expression in C++ again...
TreeNode nodeRepresentingIndex(std::to_string(i),
instanceName.lineNumber,
instanceName.columnNumber);
TreeNode nodeWithInstanceName(instanceName.text,
instanceName.lineNumber,
instanceName.columnNumber);
nodeWithInstanceName.children.push_back(nodeRepresentingIndex);
TreeNode dotOperator(".", instanceName.lineNumber,
instanceName.columnNumber);
TreeNode nodeWithMemberName(memberName, instanceName.lineNumber,
instanceName.columnNumber);
TreeNode nodeWithMemberArrayIndex(std::to_string(k),
instanceName.lineNumber,
instanceName.columnNumber);
nodeWithMemberName.children.push_back(nodeWithMemberArrayIndex);
dotOperator.children =
<% nodeWithInstanceName,
nodeWithMemberName %>; // Is this valid in standard C++? I
// am not sure. GCC (at least as
// early as 4.8.5) accepts that, and
// so does CLANG 10, and so does
// the C++ compiler that comes with
// Visual Studio 2019.
TreeNode assignmentOperator(":=", instanceName.lineNumber,
instanceName.columnNumber);
TreeNode nodeRepresentingDefaultValue(
!isPointerType(
iteratorPointingToTheStructure->memberTypes[memberName])
? std::to_string(
iteratorPointingToTheStructure
->defaultValuesOfMembers
[memberName]) // The operator[] of
// std::map returns 0 if we
// try to read a
// non-initialized field.
// That's different from the
// "at(key)" method, which
// throws an exception in
// that case.
: "CharacterPointer(",
instanceName.lineNumber, instanceName.columnNumber);
TreeNode zeroNode("0", instanceName.lineNumber,
instanceName.columnNumber);
nodeRepresentingDefaultValue.children.push_back(zeroNode);
assignmentOperator.children =
<% dotOperator, nodeRepresentingDefaultValue %>;
// So, finally, now we can compile that S-expression.
assembly += assignmentOperator.compile(context) + "\n";
}
}
}
if (instanceName.children.size() &&
instanceName.children[0].text ==
":=") // Initial assignment of local structures
{
TreeNode assignmentOperator(
":=", instanceName.children[0].lineNumber,
instanceName.children[0].columnNumber);
TreeNode leftHandSide(instanceName.text, instanceName.lineNumber,
instanceName.columnNumber);
assignmentOperator.children =
<% leftHandSide, instanceName.children[0].children[0] %>;
TreeNode nodeWithFakeDoesToken(
"Does", instanceName.lineNumber,
instanceName.columnNumber); // Let's, for now, avoid the
// Internal Compiler Error in the
// semantic analyzer this way.
nodeWithFakeDoesToken.children.push_back(assignmentOperator);
CompilationContext fakeContext = context;
fakeContext.stackSizeOfThisFunction = 0;
fakeContext.stackSizeOfThisScope = 0;
assembly += nodeWithFakeDoesToken.compile(fakeContext) + "\n";
}
}
#ifdef OUTPUT_DEBUG_COMMENTS_IN_ASSEMBLY_COMMENTS
std::string JSON = JSONifyMapOfInts(context.localVariables) + "\n";
std::string commentedJSON = ";;\t";
for (size_t i = 0; i < JSON.length(); i++)
if (JSON[i] == '\n')
commentedJSON += "\n;;\t";
else
commentedJSON += JSON[i];
assembly += ";;The JSON of the new \"localVariables\" object in the "
"current compilation context is:\n" +
commentedJSON + "\n";
#endif
} else if (childNode.text == ":=" &&
context.structureSizes.count(
childNode.getType(context))) { // Structure assignments.
const std::string structureName = childNode.getType(context);
TreeNode fakeInnerFunctionNode(
"Does", childNode.lineNumber,
childNode
.columnNumber); // Again, to avoid the internal compiler error
// in the semantic analyzer in case of nested
// structures. This isn't an elegant solution,
// but I can't think of any better.
TreeNode instantiateStructureNode("InstantiateStructure",
childNode.lineNumber,
childNode.columnNumber);
TreeNode structureNameNode(structureName, childNode.lineNumber,
childNode.columnNumber);
std::string nameOfTheTemporaryStructure;
do {
nameOfTheTemporaryStructure =
"temporaryAssignmentStructure" + std::to_string(std::rand());
} while (context.variableTypes.count(nameOfTheTemporaryStructure));
TreeNode temporaryStructureNode(nameOfTheTemporaryStructure,
childNode.lineNumber,
childNode.columnNumber);
structureNameNode.children.push_back(temporaryStructureNode);
instantiateStructureNode.children.push_back(structureNameNode);
fakeInnerFunctionNode.children.push_back(instantiateStructureNode);
std::vector<TreeNode> assignmentsToTemporary;
std::vector<TreeNode> assignmentsFromTemporary;
auto iteratorPointingToTheStructure = std::find_if(
context.structures.begin(), context.structures.end(),
[=](structure str) { return str.name == structureName; });
for (std::string memberName :
iteratorPointingToTheStructure->memberNames)
for (unsigned memberArrayIndex = 0;
memberArrayIndex <
iteratorPointingToTheStructure->arraySize.at(memberName);
memberArrayIndex++) {
// For every member of the structure, assume it's an array, so, for
// every element of that array, construct an S-expression for
// assigning the corresponding element of the righ-side structure to
// it, and then compile that S-expression.
TreeNode nodeWithMemberArrayIndex(std::to_string(memberArrayIndex),
childNode.lineNumber,
childNode.columnNumber);
TreeNode nodeWithMemberName(memberName, childNode.lineNumber,
childNode.columnNumber);
nodeWithMemberName.children.push_back(nodeWithMemberArrayIndex);
TreeNode leftDotOperator(".", childNode.lineNumber,
childNode.columnNumber);
leftDotOperator.children =
<% temporaryStructureNode, nodeWithMemberName %>;
TreeNode rightDotOperator(".", childNode.lineNumber,
childNode.columnNumber);
rightDotOperator.children =
<% childNode.children[1], nodeWithMemberName %>;
TreeNode assignmentOperator(":=", childNode.lineNumber,
childNode.columnNumber);
assignmentOperator.children =
<% leftDotOperator, rightDotOperator %>;
assignmentsToTemporary.push_back(assignmentOperator);
leftDotOperator.children =
<% childNode.children[0], nodeWithMemberName %>;
rightDotOperator.children =
<% temporaryStructureNode, nodeWithMemberName %>;
assignmentOperator.children =
<% leftDotOperator, rightDotOperator %>;
assignmentsFromTemporary.push_back(assignmentOperator);
}
fakeInnerFunctionNode.children.insert(
fakeInnerFunctionNode.children.end(),
assignmentsToTemporary.begin(), assignmentsToTemporary.end());
fakeInnerFunctionNode.children.insert(
fakeInnerFunctionNode.children.end(),
assignmentsFromTemporary.begin(), assignmentsFromTemporary.end());
CompilationContext fakeContext = context;
fakeContext.stackSizeOfThisScope = 0;
fakeContext.stackSizeOfThisFunction = 0;
assembly += fakeInnerFunctionNode.compile(fakeContext) + "\n";
} else if ((childNode.text.size() == 2 and childNode.text[1] == '=' and
childNode.text[0] != '<' and childNode.text[0] != '>') or
childNode.getType(context) == "Nothing")
assembly += std::string(childNode.compile(context)) + "\n";
else {
std::cerr
<< "Line " << childNode.lineNumber << ", Column "
<< childNode.columnNumber
<< ", Compiler error: Sorry about that, but WebAssembly doesn't "
"support expressions which aren't assigned to anything (the "
"assembler complains if you write something like that). The "
"compilation is going to be aborted now."
<< std::endl;
std::exit(1);
}
}
assembly += "(global.set $stack_pointer (i32.sub (global.get "
"$stack_pointer) (i32.const " +
std::to_string(context.stackSizeOfThisScope) + ")))";
} else if (text.front() == '"')
assembly += "(i32.const " +
std::to_string(context.globalVariables.at(text)) +
") ;;Pointer to " + text;
else if ((text == "asm(" or text == "asm_i32(" or text == "asm_i64(" or
text == "asm_f32(" or text == "asm_f64(") and
children.size() == 1) {
auto originalInlineAssembly =
convertInlineAssemblyToAssembly(children.at(0));
std::string adjustedInlineAssembly, variableName;
bool areWeInsideAVariableName = false, areWeInsideAComment = false,
areWeInsideAString = false;
int depthOfThePointerInSExpression = 0;
char howDidTheStringStart = '\"';
for (char currentCharacter : originalInlineAssembly) {
if (not(areWeInsideAComment) and not(areWeInsideAString) and
currentCharacter == '(')
depthOfThePointerInSExpression++;
if (not(areWeInsideAComment) and not(areWeInsideAString) and
currentCharacter == ')') {
depthOfThePointerInSExpression--;
if (depthOfThePointerInSExpression < 0)
std::cerr << "Line " << lineNumber << ", Column " << columnNumber
<< ", Compiler warning: Mismatched parantheses in the "
"inline assembly (there is an unexpected ')')."
<< std::endl;
}
if (not(areWeInsideAString) and not(areWeInsideAComment) and
(currentCharacter == '\'' or currentCharacter == '\"')) {
areWeInsideAString = true;
adjustedInlineAssembly += currentCharacter;
howDidTheStringStart = currentCharacter;
} else if (areWeInsideAString and
currentCharacter == howDidTheStringStart) {
areWeInsideAString = false;
adjustedInlineAssembly += currentCharacter;
} else if (areWeInsideAComment and currentCharacter != '\n')
adjustedInlineAssembly += currentCharacter;
else if (areWeInsideAComment and currentCharacter == '\n') {
adjustedInlineAssembly += '\n';
areWeInsideAComment = false;
} else if (not(areWeInsideAComment) and not(areWeInsideAString) and
currentCharacter == ';') {
areWeInsideAComment = true;
adjustedInlineAssembly += ';';
} else if (not(areWeInsideAVariableName) and currentCharacter != '%')
adjustedInlineAssembly += currentCharacter;
else if (not(areWeInsideAVariableName) and currentCharacter == '%' and
not(areWeInsideAComment) and not(areWeInsideAString)) {
variableName = "";
areWeInsideAVariableName = true;
} else if (areWeInsideAVariableName and
(std::isspace(currentCharacter) or currentCharacter == ')')) {
areWeInsideAVariableName = false;
TreeNode nodeRepresentingPointer(variableName, lineNumber,
columnNumber);
nodeRepresentingPointer.children.push_back(TreeNode(
"0", lineNumber,
columnNumber)); // What if somebody tries to insert a
// pointer to an array into inline assembly?
adjustedInlineAssembly +=
nodeRepresentingPointer.compileAPointer(context)
.indentBy(depthOfThePointerInSExpression)
.substr(depthOfThePointerInSExpression) +
"\n";
adjustedInlineAssembly += currentCharacter;
} else if (areWeInsideAVariableName and currentCharacter == '%') {
adjustedInlineAssembly += "%";
areWeInsideAVariableName = false;
if (variableName != "")
std::cerr << "Line " << lineNumber << ", Column " << columnNumber
<< ", Compiler warning: The string \"" << variableName
<< "\" will not be passed to the assembler!" << std::endl;
} else if (areWeInsideAVariableName) {
variableName += currentCharacter;
}
}
if (areWeInsideAVariableName) {
std::cerr
<< "Line " << lineNumber << ", Column " << columnNumber
<< ", Compiler error: In the inline assembly, the variable name "
<< JSONifyString(variableName) << " is not terminated!" << std::endl;
std::exit(1);
}
if (areWeInsideAString)
std::cerr << "Line " << lineNumber << ", Column " << columnNumber
<< ", Compiler warning: There is an unterminated string "
"literal inside the inline assembly, a mismatched `"
<< howDidTheStringStart << "` character." << std::endl;
if (depthOfThePointerInSExpression > 0)
std::cerr << "Line " << lineNumber << ", Column " << columnNumber
<< ", Compiler warning: Mismatched parantheses in the inline "
"assembly (there are too many '('-s)."
<< std::endl;
assembly += adjustedInlineAssembly + "\n";
} else if (text == "nan")
assembly += "(f32.reinterpret_i32\n\t(i32.const -1) ;;IEE754 for "
"not-a-number is 0xffffffff=-1.\n)";
else if (context.variableTypes.count(text) or text == "." || text == "->") {
if (typeOfTheCurrentNode == "Character")
assembly +=
"(i32.load8_s\n" + compileAPointer(context).indentBy(1) + "\n)";
else if (typeOfTheCurrentNode == "Integer16")
assembly +=
"(i32.load16_s\n" + compileAPointer(context).indentBy(1) + "\n)";
else if (typeOfTheCurrentNode == "Integer32" or
isPointerType(typeOfTheCurrentNode))
assembly += "(i32.load\n" + compileAPointer(context).indentBy(1) + "\n)";
else if (typeOfTheCurrentNode == "Integer64")
assembly += "(i64.load\n" + compileAPointer(context).indentBy(1) + "\n)";
else if (typeOfTheCurrentNode == "Decimal32")
assembly += "(f32.load\n" + compileAPointer(context).indentBy(1) + "\n)";
else if (typeOfTheCurrentNode == "Decimal64")
assembly += "(f64.load\n" + compileAPointer(context).indentBy(1) + "\n)";
else {
std::cerr << "Line " << lineNumber << ", Column " << columnNumber
<< ", Internal compiler error: Compiler got into a forbidden "
"state while compiling the token \""
<< text << "\", aborting the compilation!" << std::endl;
throw InvalidTypenameException();
}
} else if (text == ":=" &&
children[0].text ==
"?:") { // Left-hand-side conditional operators will be
// converted to if-else statements on the AST level...
TreeNode firstAssignmentNode(":=", lineNumber, columnNumber);
TreeNode secondAssignmentNode(firstAssignmentNode);
firstAssignmentNode.children.push_back(children[0].children.at(1));
firstAssignmentNode.children.push_back(children[1]);
secondAssignmentNode.children.push_back(children[0].children.at(2));
secondAssignmentNode.children.push_back(children[1]);
TreeNode thenNode("Then", lineNumber, columnNumber);
thenNode.children.push_back(firstAssignmentNode);
TreeNode elseNode("Else", lineNumber, columnNumber);
elseNode.children.push_back(secondAssignmentNode);
TreeNode ifNode("If", lineNumber, columnNumber);
ifNode.children = {children[0].children[0], thenNode, elseNode};
assembly += ifNode.compile(context);
} else if (text == ":=") {
TreeNode rightSide;
if (children.at(1).text ==
":=") { // Expressions such as "a:=b:=0" or similar.
TreeNode tmp = children[1]; // In case the "compile" changes the TreeNode.
assembly += children[1].compile(context) + "\n";
rightSide = tmp.children[0];
if (children[1].children[0].getLispExpression() !=