-
Notifications
You must be signed in to change notification settings - Fork 87
Expand file tree
/
Copy pathcompiler.cpp
More file actions
2199 lines (1921 loc) · 62.9 KB
/
compiler.cpp
File metadata and controls
2199 lines (1921 loc) · 62.9 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 "compiler.h"
#include "scanner.h"
#include "parser.h"
#include "resolver.h"
using namespace febcode;
void febcode::CompileSource(Program& prg, const std::string& source)
{
// 1. Tokenize
Scanner scanner(source);
std::vector<Token> tokens = scanner.scanTokens();
// 2. Parse -> AST
Parser parser(prg);
parser.parse(tokens);
// Optional safety check
if (prg.ast->empty())
throw std::runtime_error("Parser produced no statements.");
// 3. semantic analysis
Resolver resolve(prg);
resolve.resolve();
// 4. Compile -> bytecode
Compiler compiler(prg);
compiler.compile();
}
//
// ================= IMPLEMENTATION =================
//
Compiler::Compiler(Program& prg) : prg(prg)
{
}
//
// ===== Scope =====
//
void Compiler::beginScope()
{
m_scopeDepth++;
}
void Compiler::endScope()
{
while (!m_locals.empty() && m_locals.back().depth == m_scopeDepth)
{
Local& local = m_locals.back();
switch (local.type->kind)
{
case TypeKind::Bool : emit(OpCode::POP_BOOL ); break;
case TypeKind::Int : emit(OpCode::POP_INT ); break;
case TypeKind::Double: emit(OpCode::POP_DOUBLE); break;
case TypeKind::Vec2 : emit(OpCode::POP_VEC2 ); break;
case TypeKind::Vec3 : emit(OpCode::POP_VEC3 ); break;
case TypeKind::Mat2 : emit(OpCode::POP_MAT2 ); break;
case TypeKind::Mat3 : emit(OpCode::POP_MAT3 ); break;
case TypeKind::Array :
if (local.type->size() > 255)
throw std::runtime_error("Array size exceeds maximum of 255.");
emit(OpCode::POP_ARRAY, (int)local.type->size());
emitUint8((uint8_t)local.type->size());
break;
case TypeKind::Struct:
emit(OpCode::POP_STRUCT, (int)local.type->size());
emitUint8((uint8_t)local.type->typeIndex);
break;
default:
throw std::runtime_error("Unknown type kind in endScope.");
break;
}
m_locals.pop_back();
localStackSize -= local.type->size();
}
m_scopeDepth--;
}
int Compiler::resolveLocal(const std::string& name)
{
for (int i = (int)m_locals.size() - 1; i >= 0; --i)
if (m_locals[i].name == name)
return i;
return -1;
}
int Compiler::resolveGlobal(const std::string& name)
{
auto it = prg.globalIndices.find(name);
if (it != prg.globalIndices.end())
return (int)it->second;
return -1;
}
Type Compiler::resolveVariableType(const std::string& name)
{
int localIndex = resolveLocal(name);
if (localIndex != -1)
return m_locals[localIndex].type;
int globalIndex = resolveGlobal(name);
if (globalIndex != -1)
return prg.globals[globalIndex].type;
throw std::runtime_error("Undefined variable: " + name);
}
//
// ===== Bytecode Helpers =====
//
void Compiler::emit(OpCode op, int arg)
{
prg.code.push_back((uint8_t)op);
stackDepth += stackEffect(op, arg); assert(stackDepth >= 0);
if (stackDepth > maxStackDepth)
maxStackDepth = stackDepth;
}
void Compiler::emitUint8(uint8_t v)
{
prg.code.push_back(v);
}
void Compiler::emitUint16(uint16_t v)
{
prg.code.push_back((v >> 8) & 0xff);
prg.code.push_back(v & 0xff);
}
int Compiler::stackEffect(OpCode op, int arg)
{
switch (op)
{
case OpCode::PUSH_VOID:
case OpCode::PUSH_BOOL:
case OpCode::PUSH_INT:
case OpCode::PUSH_DOUBLE:
return +1;
case OpCode::PUSH_VEC2: return +2;
case OpCode::PUSH_VEC3: return +3;
case OpCode::PUSH_MAT2: return +4;
case OpCode::PUSH_MAT3: return +9;
case OpCode::GET_GLOBAL_BOOL : return +1;
case OpCode::GET_GLOBAL_INT : return +1;
case OpCode::GET_GLOBAL_DOUBLE: return +1;
case OpCode::GET_GLOBAL_VEC2 : return +2;
case OpCode::GET_GLOBAL_VEC3 : return +3;
case OpCode::GET_GLOBAL_MAT2 : return +4;
case OpCode::GET_GLOBAL_MAT3 : return +9;
case OpCode::GET_GLOBAL_ARRAY : return +arg;
case OpCode::GET_GLOBAL_STRUCT: return +arg;
case OpCode::SET_GLOBAL_BOOL:
case OpCode::SET_GLOBAL_INT:
case OpCode::SET_GLOBAL_DOUBLE:
case OpCode::SET_GLOBAL_VEC2:
case OpCode::SET_GLOBAL_VEC3:
case OpCode::SET_GLOBAL_MAT2:
case OpCode::SET_GLOBAL_MAT3:
case OpCode::SET_GLOBAL_ARRAY:
case OpCode::SET_GLOBAL_STRUCT:
return 0;
case OpCode::GET_GLOBAL_REF : return +1;
case OpCode::GET_LOCAL_BOOL : return +1;
case OpCode::GET_LOCAL_INT : return +1;
case OpCode::GET_LOCAL_DOUBLE: return +1;
case OpCode::GET_LOCAL_VEC2 : return +2;
case OpCode::GET_LOCAL_VEC3 : return +3;
case OpCode::GET_LOCAL_MAT2 : return +4;
case OpCode::GET_LOCAL_MAT3 : return +9;
case OpCode::GET_LOCAL_ARRAY : return +arg;
case OpCode::GET_LOCAL_STRUCT: return +arg;
case OpCode::GET_LOCAL_REF : return +1;
case OpCode::GET_PROPERTY_BOOL : return +1;
case OpCode::GET_PROPERTY_INT : return +1;
case OpCode::GET_PROPERTY_DOUBLE: return +1;
case OpCode::GET_PROPERTY_VEC2 : return +2;
case OpCode::GET_PROPERTY_VEC3 : return +3;
case OpCode::GET_PROPERTY_MAT2 : return +4;
case OpCode::GET_PROPERTY_MAT3 : return +9;
case OpCode::GET_PROPERTY_ARRAY : return +1;
case OpCode::GET_PROPERTY_STRUCT: return +1;
case OpCode::GET_MEMBER_REF: return 0;
case OpCode::GET_INDEX_BOOL : return +arg;
case OpCode::GET_INDEX_INT : return +arg;
case OpCode::GET_INDEX_DOUBLE: return +arg;
case OpCode::GET_INDEX_VEC2 : return +arg;
case OpCode::GET_INDEX_VEC3 : return +arg;
case OpCode::GET_INDEX_MAT2 : return +arg;
case OpCode::GET_INDEX_MAT3 : return +arg;
case OpCode::GET_INDEX_ARRAY : return +arg;
case OpCode::GET_INDEX_STRUCT: return +arg;
case OpCode::GET_GLOBAL_INDEX_DOUBLE: return +1;
case OpCode::GET_INDEX_REF:
case OpCode::GET_INDEX_REF_BOOL:
case OpCode::GET_INDEX_REF_INT:
case OpCode::GET_INDEX_REF_DOUBLE:
case OpCode::GET_INDEX_REF_VEC2:
case OpCode::GET_INDEX_REF_VEC3:
case OpCode::GET_INDEX_REF_MAT2:
case OpCode::GET_INDEX_REF_MAT3:
return 0;
case OpCode::GET_VEC2_X: return -1;
case OpCode::GET_VEC2_Y: return -1;
case OpCode::GET_VEC2_X_REF: return 0;
case OpCode::GET_VEC2_Y_REF: return 0;
case OpCode::GET_VEC2_SWIZZLE: return +1; // in case the swizzle returns a vec3
case OpCode::GET_VEC2_INDEX: return -2; // pops the index and vec2, and pushes the component
case OpCode::GET_VEC3_X: return 0;
case OpCode::GET_VEC3_Y: return 0;
case OpCode::GET_VEC3_Z: return 0;
case OpCode::GET_VEC3_X_REF: return 0;
case OpCode::GET_VEC3_Y_REF: return 0;
case OpCode::GET_VEC3_Z_REF: return 0;
case OpCode::GET_VEC3_SWIZZLE: return +1;
case OpCode::GET_VEC3_INDEX: return -3; // pops the index and vec3, and pushes the component
case OpCode::NEG_INT: return 0;
case OpCode::ADD_INT: return -1;
case OpCode::SUB_INT: return -1;
case OpCode::MUL_INT: return -1;
case OpCode::DIV_INT: return -1;
case OpCode::EXP_INT: return -1;
case OpCode::GT_INT: return -1;
case OpCode::LT_INT: return -1;
case OpCode::GE_INT: return -1;
case OpCode::LE_INT: return -1;
case OpCode::NEG_DOUBLE: return 0;
case OpCode::SQR_DOUBLE: return 0;
case OpCode::SQRT_DOUBLE: return 0;
case OpCode::ADD_DOUBLE: return -1;
case OpCode::SUB_DOUBLE: return -1;
case OpCode::MUL_DOUBLE: return -1;
case OpCode::DIV_DOUBLE: return -1;
case OpCode::EXP_DOUBLE: return -1;
case OpCode::GT_DOUBLE: return -1;
case OpCode::LT_DOUBLE: return -1;
case OpCode::GE_DOUBLE: return -1;
case OpCode::LE_DOUBLE: return -1;
case OpCode::CREATE_VEC2_1ARG: return +1; // pops the double, pushes the vec2
case OpCode::NEG_VEC2: return 0;
case OpCode::ADD_VEC2: return -2;
case OpCode::SUB_VEC2: return -2;
case OpCode::DOT_VEC2: return -3;
case OpCode::MUL_VEC2_DOUBLE: return -1;
case OpCode::MUL_DOUBLE_VEC2: return -1;
case OpCode::DIV_VEC2_DOUBLE: return -1;
case OpCode::CREATE_VEC3_1ARG: return +2; // pops the double, pushes the vec3
case OpCode::NEG_VEC3: return 0;
case OpCode::ADD_VEC3: return -3;
case OpCode::SUB_VEC3: return -3;
case OpCode::DOT_VEC3: return -5;
case OpCode::MUL_VEC3_DOUBLE: return -1;
case OpCode::MUL_DOUBLE_VEC3: return -1;
case OpCode::DIV_VEC3_DOUBLE: return -1;
case OpCode::NEG_MAT2: return 0;
case OpCode::ADD_MAT2: return -4;
case OpCode::SUB_MAT2: return -4;
case OpCode::MUL_MAT2: return -4;
case OpCode::MUL_MAT2_DOUBLE: return -1;
case OpCode::MUL_DOUBLE_MAT2: return -1;
case OpCode::DIV_MAT2_DOUBLE: return -1;
case OpCode::MUL_MAT2_VEC2 : return -4;
case OpCode::GET_MAT2_INDEX: return -3;
case OpCode::CREATE_MAT2_DIAG: return +3;
case OpCode::NEG_MAT3: return 0;
case OpCode::ADD_MAT3: return -9;
case OpCode::SUB_MAT3: return -9;
case OpCode::MUL_MAT3: return -9;
case OpCode::MUL_MAT3_DOUBLE: return -1;
case OpCode::DIV_MAT3_DOUBLE: return -1;
case OpCode::MUL_DOUBLE_MAT3: return -1;
case OpCode::MUL_MAT3_VEC3 : return -9;
case OpCode::GET_MAT3_INDEX : return -7;
case OpCode::ADD_GLOBAL_MAT3: return +9;
case OpCode::SUB_GLOBAL_MAT3: return +9;
case OpCode::MUL_GLOBAL_MAT3: return +9;
case OpCode::CREATE_MAT3_DIAG: return +8;
case OpCode::CREATE_MAT3_VEC3: return +0;
case OpCode::NOT: return 0;
case OpCode::EQUAL_BOOL:
case OpCode::EQUAL_INT:
case OpCode::EQUAL_DOUBLE:
return -1;
case OpCode::NEQ_BOOL:
case OpCode::NEQ_INT:
case OpCode::NEQ_DOUBLE:
return -1;
case OpCode::JUMP: return 0;
case OpCode::JUMP_IF_FALSE: return +1; // technically +0, but each jump adds two pops (one for each branch)
case OpCode::JUMP_IF_TRUE: return +1; // technically +0, but each jump adds two pops (one for each branch)
case OpCode::LOOP: return 0;
case OpCode::STORE_BOOL:
case OpCode::STORE_INT:
case OpCode::STORE_DOUBLE:
case OpCode::STORE_VEC2:
case OpCode::STORE_VEC3:
case OpCode::STORE_MAT2:
case OpCode::STORE_MAT3:
case OpCode::STORE_ARRAY:
case OpCode::STORE_STRUCT:
return -1;
case OpCode::POP_VOID : return -1;
case OpCode::POP_BOOL : return -1;
case OpCode::POP_INT : return -1;
case OpCode::POP_DOUBLE: return -1;
case OpCode::POP_VEC2 : return -2;
case OpCode::POP_VEC3 : return -3;
case OpCode::POP_MAT2 : return -4;
case OpCode::POP_MAT3 : return -9;
case OpCode::POP_ARRAY : return -arg;
case OpCode::POP_STRUCT: return -arg;
case OpCode::CALL: return arg; // this is the net stack effect calculated when compiling.
case OpCode::RETURN_VOID:
case OpCode::RETURN_BOOL:
case OpCode::RETURN_INT:
case OpCode::RETURN_DOUBLE:
case OpCode::RETURN_VEC2:
case OpCode::RETURN_VEC3:
case OpCode::RETURN_MAT2:
case OpCode::RETURN_MAT3:
case OpCode::RETURN_ARRAY:
case OpCode::RETURN_STRUCT:
return 0;
default:
assert(false);
return 0;
}
}
uint8_t Compiler::addConstant(const Value& v)
{
prg.constants.push_back(v);
return (uint8_t)(prg.constants.size() - 1);
}
int Compiler::emitJump(OpCode op)
{
emit(op);
emitUint16(0xffff);
return (int)prg.code.size() - 2;
}
void Compiler::patchJump(int offset)
{
int jump = (int)prg.code.size() - offset - 2;
prg.code[offset] = (jump >> 8) & 0xff;
prg.code[offset + 1] = jump & 0xff;
}
void Compiler::emitLoop(int loopStart)
{
emit(OpCode::LOOP);
int offset = (int)prg.code.size() - loopStart + 2;
emitUint16(offset);
}
//
// ===== Program =====
//
void Compiler::compile()
{
prg.functions[0].entry = 0;
hasReturn = false;
expectedReturnType = prg.returnType;
for (auto& stmt : prg.ast->root.statements)
compileStatement(stmt.get());
// only add return if no return was encountered.
if (!hasReturn)
emit(OpCode::RETURN_VOID);
prg.maxStackSize = maxStackDepth;
}
//
// ===== Statements =====
//
void Compiler::compileStatement(Statement* stmt)
{
if (auto b = dynamic_cast<ExpressionStmt*>(stmt)) compileExprStmt(b);
else if (auto b = dynamic_cast<BlockStmt* >(stmt)) compileBlock(b);
else if (auto v = dynamic_cast<VarDeclStmt* >(stmt)) compileVarDecl(v);
else if (auto f = dynamic_cast<FunctionStmt* >(stmt)) compileFunction(f);
else if (auto i = dynamic_cast<IfStmt* >(stmt)) compileIf(i);
else if (auto w = dynamic_cast<WhileStmt* >(stmt)) compileWhile(w);
else if (auto l = dynamic_cast<ForStmt* >(stmt)) compileFor(l);
else if (auto r = dynamic_cast<ReturnStmt* >(stmt)) compileReturn(r);
else if (auto s = dynamic_cast<StructStmt* >(stmt)) compileStruct(s);
else
throw std::runtime_error("Unsupported statement type");
}
void Compiler::compileExprStmt(ExpressionStmt* stmt)
{
Type type = compileExpression(stmt->expr.get());
pop(type);
}
void Compiler::pop(Type type)
{
switch (type->kind)
{
case TypeKind::Void : emit(OpCode::POP_VOID ); break;
case TypeKind::Bool : emit(OpCode::POP_BOOL ); break;
case TypeKind::Int : emit(OpCode::POP_INT ); break;
case TypeKind::Double: emit(OpCode::POP_DOUBLE); break;
case TypeKind::Vec2 : emit(OpCode::POP_VEC2 ); break;
case TypeKind::Vec3 : emit(OpCode::POP_VEC3 ); break;
case TypeKind::Mat2 : emit(OpCode::POP_MAT2 ); break;
case TypeKind::Mat3 : emit(OpCode::POP_MAT3 ); break;
case TypeKind::Array :
if (type->size() > 255)
throw std::runtime_error("Array size exceeds maximum of 255.");
emit(OpCode::POP_ARRAY, (int)type->size());
emitUint8((uint8_t)type->size());
break;
case TypeKind::Struct:
emit(OpCode::POP_STRUCT, (int)type->size());
emitUint8((uint8_t)type->typeIndex);
break;
default:
throw std::runtime_error("Unsupported expression type in expression statement");
}
}
void Compiler::compileBlock(BlockStmt* stmt)
{
beginScope();
for (auto& s : stmt->statements)
compileStatement(s.get());
endScope();
}
Type Compiler::compileInitializer(InitExpr* init)
{
if (init->elements.empty())
throw std::runtime_error("Initializer cannot be empty.");
// deduce the array type from the first element
Type elemType = compileExpression(init->elements[0].get());
Type arrayType = prg.types.getArrayType(elemType, { init->elements.size() });
// compile the rest of the elements and check that they match the deduced type
for (size_t i = 1; i < init->elements.size(); ++i)
{
Type type = coerce(compileExpression(init->elements[i].get()), elemType);
if (type != elemType)
throw std::runtime_error("Initializer element type mismatch.");
}
return arrayType;
}
Type Compiler::compileConstructor(ConstructorExpr* construct)
{
// check the number of arguments for the constructor
int nargs = (int)construct->args.size();
switch (construct->valType->kind)
{
case TypeKind::Vec2:
if ((nargs != 1) && (nargs != 2))
throw std::runtime_error("Vec2 constructor must have 1 or 2 arguments.");
break;
case TypeKind::Vec3:
if ((nargs != 1) && (nargs != 3))
throw std::runtime_error("Vec3 constructor must have 1 or 3 arguments.");
break;
case TypeKind::Mat2:
if (nargs != 1 && nargs != 4)
throw std::runtime_error("Mat2 constructor must have either 1 or 4 arguments.");
break;
case TypeKind::Mat3:
if (nargs != 1 && nargs != 3 && nargs != 9)
throw std::runtime_error("Mat3 constructor must have either 1, 3, or 9 arguments.");
break;
case TypeKind::Struct:
if (nargs != construct->valType->fields.size())
throw std::runtime_error("Struct constructor must have exactly " + std::to_string(construct->valType->fields.size()) + " arguments.");
break;
default:
break;
}
// process each argument and check their types
std::vector<Type> argTypes;
for (int i = 0; i < construct->args.size(); ++i)
{
Type argType = compileExpression(construct->args[i].get());
argTypes.push_back(argType);
// check the argument type against the expected type for the constructor
switch (construct->valType->kind)
{
case TypeKind::Vec2:
case TypeKind::Vec3:
case TypeKind::Mat2:
argType = coerce(argType, prg.types.Double());
if (argType != prg.types.Double())
throw std::runtime_error("Vec2 constructor arguments must be of type double.");
break;
case TypeKind::Mat3:
if (!isScalarType(argType) && argType != prg.types.Vec3())
throw std::runtime_error("Mat3 constructor arguments must be of type int, double or vec3.");
break;
case TypeKind::Struct:
argType = coerce(argType, construct->valType->fields[i].first);
if (argType != construct->valType->fields[i].first)
throw std::runtime_error("Struct constructor argument type mismatch.");
break;
default:
throw std::runtime_error("Unsupported constructor type");
}
}
// emit special codes for matrix constructors
if (nargs == 1)
{
if (construct->valType->kind == TypeKind::Vec2)
emit(CREATE_VEC2_1ARG);
else if (construct->valType->kind == TypeKind::Vec3)
emit(CREATE_VEC3_1ARG);
else if (construct->valType->kind == TypeKind::Mat2)
emit(CREATE_MAT2_DIAG);
else if (construct->valType->kind == TypeKind::Mat3)
emit(CREATE_MAT3_DIAG);
}
if (nargs == 3)
{
if (construct->valType->kind == TypeKind::Mat3)
emit(CREATE_MAT3_VEC3);
}
return construct->valType;
}
Type Compiler::expressionType(Expression* expr)
{
if (auto l = dynamic_cast<LiteralExpr*>(expr))
{
return prg.types.getBuiltinType(l->value);
}
if (auto v = dynamic_cast<VariableExpr*>(expr))
{
return resolveVariableType(v->name);
}
if (auto u = dynamic_cast<UnaryExpr*>(expr))
{
return expressionType(u->right.get());
}
if (auto b = dynamic_cast<BinaryExpr*>(expr))
{
Type leftType = expressionType(b->left.get());
Type rightType = expressionType(b->right.get());
// this is only supported for multiplications!
if (b->op == BinaryOp::Multiply)
{
// scalar * scalar --> scalar
if (isScalarType(leftType) && isScalarType(rightType))
return commonType(leftType, rightType);
// scalar * type --> type
if (isScalarType(leftType) && isVec2Type(rightType))
return rightType;
if (isScalarType(leftType) && isVec3Type(rightType))
return rightType;
if (isScalarType(leftType) && isMat2Type(rightType))
return rightType;
if (isScalarType(leftType) && isMat3Type(rightType))
return rightType;
// vec2 * type
if (isVec2Type(leftType) && isScalarType(rightType))
return leftType;
if (isVec2Type(leftType) && isVec2Type(rightType)) // dot product
return prg.types.Double();
// vec3 * type
if (isVec3Type(leftType) && isScalarType(rightType))
return leftType;
if (isVec3Type(leftType) && isVec3Type(rightType)) // dot product
return prg.types.Double();
// mat2 * type
if (isMat2Type(leftType) && isScalarType(rightType))
return leftType;
if (isMat2Type(leftType) && isVec2Type(rightType))
return rightType;
if (isMat2Type(leftType) && isMat2Type(rightType))
return leftType;
// mat3 * type
if (isMat3Type(leftType) && isScalarType(rightType))
return leftType;
if (isMat3Type(leftType) && isVec3Type(rightType))
return rightType;
if (isMat3Type(leftType) && isMat3Type(rightType))
return leftType;
}
}
if (auto c = dynamic_cast<CallExpr*>(expr))
{
std::vector<Type> args;
for (auto& arg : c->arguments)
args.push_back(expressionType(arg.get()));
int index = prg.resolveFunction(c->name, args);
if (index >=0 )
{
FunctionInfo& func = prg.functions[index];
return func.returnType;
}
}
if (auto i = dynamic_cast<ConstructorExpr*>(expr))
{
return i->valType;
}
throw std::runtime_error("Unsupported expression type in expressionType");
}
void Compiler::compileVarDecl(VarDeclStmt* decl)
{
Type baseType = decl->type;
for (auto& var : decl->vars)
{
Type type = baseType;
if (var.arraySizes.size() > 0)
{
type = prg.types.getArrayType(baseType, var.arraySizes);
}
if (!decl->input && var.initializer)
{
Type initType = coerce(compileExpression(var.initializer.get()), type);
}
if (m_scopeDepth == 0)
{
if (decl->input)
prg.addInput(var.name, type);
else
{
prg.addGlobal(var.name, type);
if (var.initializer)
{
auto it = prg.globalIndices.find(var.name);
Program::Global& global = prg.globals[it->second];
switch (type->kind)
{
case TypeKind::Bool : emit(OpCode::SET_GLOBAL_BOOL ); break;
case TypeKind::Int : emit(OpCode::SET_GLOBAL_INT ); break;
case TypeKind::Double: emit(OpCode::SET_GLOBAL_DOUBLE); break;
case TypeKind::Vec2 : emit(OpCode::SET_GLOBAL_VEC2 ); break;
case TypeKind::Vec3 : emit(OpCode::SET_GLOBAL_VEC3 ); break;
case TypeKind::Mat2 : emit(OpCode::SET_GLOBAL_MAT2 ); break;
case TypeKind::Mat3 : emit(OpCode::SET_GLOBAL_MAT3 ); break;
case TypeKind::Array :
emit(OpCode::SET_GLOBAL_ARRAY);
emitUint8((uint8_t)type->size());
break;
case TypeKind::Struct:
emit(OpCode::SET_GLOBAL_STRUCT);
emitUint8((uint8_t)type->size());
break;
default:
throw std::runtime_error("Unsupported global variable type");
}
emitUint8((uint8_t)global.slot);
switch (type->kind)
{
case TypeKind::Bool : emit(OpCode::POP_BOOL ); break;
case TypeKind::Int : emit(OpCode::POP_INT ); break;
case TypeKind::Double: emit(OpCode::POP_DOUBLE); break;
case TypeKind::Vec2 : emit(OpCode::POP_VEC2 ); break;
case TypeKind::Vec3 : emit(OpCode::POP_VEC3 ); break;
case TypeKind::Mat2 : emit(OpCode::POP_MAT2 ); break;
case TypeKind::Mat3 : emit(OpCode::POP_MAT3 ); break;
case TypeKind::Array :
if (type->size() > 255)
throw std::runtime_error("Array size exceeds maximum of 255.");
emit(OpCode::POP_ARRAY, type->size());
emitUint8((uint8_t)type->size());
break;
case TypeKind::Struct:
emit(OpCode::POP_STRUCT, type->size());
emitUint8((uint8_t)type->typeIndex);
break;
default:
throw std::runtime_error("Unsupported global variable type");
}
}
}
}
else
{
// make sure the variable isn't already declared in this scope
for (int i = (int)m_locals.size() - 1; i >= 0; --i)
{
if (m_locals[i].depth < m_scopeDepth)
break;
if (m_locals[i].name == var.name)
throw std::runtime_error("Variable '" + var.name + "' is already declared in this scope.");
}
m_locals.push_back({ var.name, type, m_scopeDepth, localStackSize });
localStackSize += (int)type->size();
}
}
}
//
// ===== If / While =====
//
void Compiler::compileIf(IfStmt* stmt)
{
Type type = compileExpression(stmt->condition.get());
if (!isScalarType(type) && !isBoolType(type))
throw std::runtime_error("Condition expression must be of type bool.");
int thenJump = emitJump(OpCode::JUMP_IF_FALSE);
switch (type->kind)
{
case TypeKind::Bool : emit(OpCode::POP_BOOL ); break;
case TypeKind::Int : emit(OpCode::POP_INT ); break;
case TypeKind::Double: emit(OpCode::POP_DOUBLE); break;
default:
throw std::runtime_error("Unsupported condition type in while statement");
}
compileStatement(stmt->thenBranch.get());
int elseJump = emitJump(OpCode::JUMP);
patchJump(thenJump);
switch (type->kind)
{
case TypeKind::Bool : emit(OpCode::POP_BOOL ); break;
case TypeKind::Int : emit(OpCode::POP_INT ); break;
case TypeKind::Double: emit(OpCode::POP_DOUBLE); break;
default:
throw std::runtime_error("Unsupported condition type in while statement");
}
if (stmt->elseBranch)
compileStatement(stmt->elseBranch.get());
patchJump(elseJump);
}
void Compiler::compileWhile(WhileStmt* stmt)
{
int loopStart = (int)prg.code.size();
Type type = compileExpression(stmt->condition.get());
if (!isLogicalType(type))
throw std::runtime_error("Condition expression must be of a numeric type or bool.");
int exitJump = emitJump(OpCode::JUMP_IF_FALSE);
emit(OpCode::POP_BOOL);
compileStatement(stmt->body.get());
emitLoop(loopStart);
patchJump(exitJump);
emit(OpCode::POP_BOOL);
}
void Compiler::compileFor(ForStmt* stmt)
{
if (stmt->initializer) compileStatement(stmt->initializer.get());
int loopStart = (int)prg.code.size();
Type type = compileExpression(stmt->condition.get());
if (!isScalarType(type) && type != prg.types.Bool())
throw std::runtime_error("Condition expression must be of a numeric type or bool.");
int exitJump = emitJump(OpCode::JUMP_IF_FALSE);
emit(OpCode::POP_BOOL);
compileStatement(stmt->body.get());
Type incrType = compileExpression(stmt->increment.get());
pop(incrType);
emitLoop(loopStart);
patchJump(exitJump);
emit(OpCode::POP_BOOL);
}
void Compiler::compileReturn(ReturnStmt* stmt)
{
if (stmt->value)
{
Type returnType = expectedReturnType;
returnType = compileExpression(stmt->value.get());
if (expectedReturnType)
{
Type coerceType = coerce(returnType, expectedReturnType);
if (coerceType)
returnType = coerceType;
if (returnType != expectedReturnType)
throw std::runtime_error("Return type mismatch. Expected " + TypeToString(expectedReturnType) + " but got " + TypeToString(returnType));
}
switch (returnType->kind)
{
case TypeKind::Bool : emit(OpCode::RETURN_BOOL ); break;
case TypeKind::Int : emit(OpCode::RETURN_INT ); break;
case TypeKind::Double: emit(OpCode::RETURN_DOUBLE); break;
case TypeKind::Vec2 : emit(OpCode::RETURN_VEC2 ); break;
case TypeKind::Vec3 : emit(OpCode::RETURN_VEC3 ); break;
case TypeKind::Mat2 : emit(OpCode::RETURN_MAT2 ); break;
case TypeKind::Mat3 : emit(OpCode::RETURN_MAT3 ); break;
case TypeKind::Array :
emit(OpCode::RETURN_ARRAY );
emitUint8(returnType->typeIndex);
break;
case TypeKind::Struct:
emit(OpCode::RETURN_STRUCT);
emitUint8(returnType->typeIndex);
break;
default:
throw std::runtime_error("Unsupported return type");
};
}
else
{
if (expectedReturnType != nullptr && expectedReturnType != prg.types.Void())
throw std::runtime_error("Missing return value in function with non-void return type.");
// return without value -> push monostate
emit(OpCode::PUSH_VOID);
emit(OpCode::RETURN_VOID);
}
// Mark that a return statement was encountered.
// This is used to determine whether we need to emit an implicit return at the end of a function/program.
hasReturn = true;
}
void Compiler::compileStruct(StructStmt* stmt)
{
// nothing to do here since struct definitions are handled during parsing and type registration.
}
//
// ===== Functions =====
//
void Compiler::compileFunction(FunctionStmt* fn)
{
// Emit jump over function body
int jumpOver = emitJump(OpCode::JUMP);
std::vector<Type> argTypes;
for (auto& p : fn->params)
argTypes.push_back(p.first);
int fnIndex = prg.resolveFunction(fn->name, argTypes);
if (fnIndex < 0)
throw std::runtime_error("Compiler error: function not found after resolution.");
FunctionInfo& info = prg.functions[fnIndex];
info.entry = prg.code.size();
currentFunction = fnIndex;
Type currentReturnType = expectedReturnType;
expectedReturnType = fn->returnType;
bool hasReturnBefore = hasReturn;
hasReturn = false;
beginScope();
for (auto& p : fn->params)
{
m_locals.push_back({ p.second, p.first, m_scopeDepth, localStackSize });
localStackSize += (int)p.first->size();
info.argSize += (int)p.first->size();
stackDepth += (int)p.first->size();
}
size_t currentStackSize = stackDepth;
BlockStmt* body = dynamic_cast<BlockStmt*>(fn->body.get());
for (auto& stmt : body->statements)
compileStatement(stmt.get());
if (!hasReturn)
{
if (fn->returnType != nullptr && fn->returnType != prg.types.Void())
throw std::runtime_error("Missing return statement in function with non-void return type.");
emit(OpCode::RETURN_VOID);
}
// We don't call endScope() here since the function body must end with a return, this will never pop the function's locals.
// Instead, just clear locals and reset the scope depth.
while (!m_locals.empty() && m_locals.back().depth == m_scopeDepth)
{
Local& local = m_locals.back();
switch (local.type->kind)
{
case TypeKind::Bool : emit(OpCode::POP_BOOL ); break;
case TypeKind::Int : emit(OpCode::POP_INT ); break;
case TypeKind::Double: emit(OpCode::POP_DOUBLE); break;
case TypeKind::Vec2 : emit(OpCode::POP_VEC2 ); break;
case TypeKind::Vec3 : emit(OpCode::POP_VEC3 ); break;
case TypeKind::Mat2 : emit(OpCode::POP_MAT2 ); break;
case TypeKind::Mat3 : emit(OpCode::POP_MAT3 ); break;
case TypeKind::Array :
if (local.type->size() > 255)
throw std::runtime_error("Array size exceeds maximum of 255.");
emit(OpCode::POP_ARRAY, local.type->size());
emitUint8(local.type->size());
break;
case TypeKind::Struct:
emit(OpCode::POP_STRUCT, local.type->size());
emitUint8(local.type->typeIndex);
break;
default:
throw std::runtime_error("Unsupported local variable type");
break;
}
m_locals.pop_back();
localStackSize -= (int)local.type->size();
}
m_scopeDepth--;
// Patch jump so execution skips function body
patchJump(jumpOver);
expectedReturnType = currentReturnType;
hasReturn = hasReturnBefore;
info.maxStackSize = maxStackDepth - currentStackSize;
currentFunction = -1;
}
//
// ===== Expressions =====
//
Type Compiler::compileExpression(Expression* expr)
{
Type type;
if (auto b = dynamic_cast<BinaryExpr* >(expr)) type = compileBinary(b);
else if (auto u = dynamic_cast<UnaryExpr* >(expr)) type = compileUnary(u);
else if (auto l = dynamic_cast<LiteralExpr* >(expr)) type = compileLiteral(l);
else if (auto v = dynamic_cast<VariableExpr* >(expr)) type = compileVariable(v);
else if (auto a = dynamic_cast<AssignExpr* >(expr)) type = compileAssign(a);
else if (auto c = dynamic_cast<CallExpr* >(expr)) type = compileCall(c);
else if (auto m = dynamic_cast<MemberExpr* >(expr)) type = compileMember(m);