This repository has been archived by the owner on Apr 5, 2024. It is now read-only.
forked from ocen-lang/ocen
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcode_generator.oc
1118 lines (985 loc) · 30.7 KB
/
code_generator.oc
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
//* Generate C code from the AST
import std::buffer::Buffer
import std::vector::Vector
import std::libc::free
import std::span::Span
import @types::{ Type, BaseType }
import @ast::nodes::*
import @ast::program::{ Program, Namespace }
import @ast::scopes::Scope
import @errors::Error
import @passes::generic_pass::GenericPass
struct CodeGenerator {
o: &GenericPass
out: Buffer
indent: u32
yield_vars: &Vector<str>
}
def CodeGenerator::gen_indent(&this) {
for let i = 0; i < .indent; i += 1 {
.out.puts(" ")
}
}
def str::replace(&this, other: str) {
let s: str = *this
free(s)
*this = other
}
// Some convenience accessors from the GenericPass
def CodeGenerator::error(&this, err: &Error): &Error => .o.error(err)
def CodeGenerator::scope(&this): &Scope => .o.scope()
def CodeGenerator::gen_debug_info(&this, span: Span, force: bool = false) {
if not .o.program.gen_debug_info and not force return
let loc = span.start
.out.putsf(`\n#line {loc.line} "{loc.filename}"\n`)
}
def CodeGenerator::get_op(&this, type: ASTType): str => match type {
And => "&&",
Assignment => "=",
BitwiseAnd => "&",
BitwiseOr => "|",
BitwiseXor => "^",
Divide => "/",
Equals => "==",
GreaterThan => ">",
GreaterThanEquals => ">=",
LeftShift => "<<",
LessThan => "<",
LessThanEquals => "<=",
Minus => "-",
Modulus => "%",
Multiply => "*",
NotEquals => "!=",
Or => "||",
Plus => "+",
PlusEquals => "+=",
MinusEquals => "-=",
MultiplyEquals => "*=",
DivideEquals => "/=",
RightShift => ">>",
PreDecrement => "--",
PreIncrement => "++",
PostDecrement => "--",
PostIncrement => "++",
else => std::panic(`Unknown op type in get_op: {type}`)
}
def CodeGenerator::gen_internal_print(&this, node: &AST) {
let callee = node.u.call.callee
let newline_after = callee.u.ident.name.eq("println")
.out.puts("printf(")
let args = node.u.call.args
let first = args.at(0)
if first.expr.type == FormatStringLiteral {
.gen_format_string_variadic(first.expr, newline_after)
.out.puts(")")
return
}
for let i = 0; i < args.size; i += 1 {
if i > 0 then .out.puts(", ")
let arg = args.at(i)
.gen_expression(arg.expr)
if i == 0 and newline_after then .out.puts("\"\\n\"")
}
.out.puts(")")
}
//* Generate all the escape sequences in format string part
def CodeGenerator::gen_format_string_part(&this, part: str) {
let len = part.len()
for let i = 0; i < len; i += 1 {
if part[i] == '\\' {
// This should be safe
i += 1
match part[i] {
// We want to unescape these
'`' | '{' | '}' => {}
// Anything else should remain escaped
else => .out.putc('\\')
}
} else if part[i] == '"' {
// If we have double quotes in a string we should escape it
.out.putc('\\')
} else if part[i] == '%' {
// Percent signs are special in printf, we need to do "%%"
.out.putc('%')
}
.out.putc(part[i])
}
}
def CodeGenerator::gen_format_string_variadic(&this, node: &AST, newline_after: bool) {
let parts = node.u.fmt_str.parts
let exprs = node.u.fmt_str.exprs
let specs = node.u.fmt_str.specs
.out.putc('"')
for let i = 0; i < exprs.size; i += 1 {
let part = parts.at(i)
let expr = exprs.at(i)
.gen_format_string_part(part)
let spec = specs.at(i)
if spec? {
.out.puts("%")
.out.puts(spec)
continue
}
let expr_type = expr.etype.unaliased()
match expr_type.base {
I8 | I16 | I32 => .out.puts("%d")
U8 | U16 | U32 => .out.puts("%u")
I64 => .out.puts("%lld")
U64 => .out.puts("%llu")
Bool => .out.puts("%s")
F32 | F64 => .out.puts("%f")
Char => .out.puts("%c")
Pointer => match expr_type.u.ptr.base {
Char => .out.puts("%s")
else => .out.puts("%p")
}
else => {
.error(Error::new(
expr.span, "Invalid type for format string"
))
.out.puts("%s")
}
}
}
// Put the last part:
let part = parts.back()
.gen_format_string_part(part)
if newline_after then .out.puts("\\n")
.out.putc('"')
for expr : exprs.iter() {
.out.puts(", ")
.gen_expression(expr)
}
}
def CodeGenerator::gen_format_string(&this, node: &AST) {
.out.puts("format_string(")
.gen_format_string_variadic(node, newline_after: false)
.out.puts(")")
}
def CodeGenerator::gen_yield_expression(&this, expr: &AST) {
let yield_var = .yield_vars.back()
.gen_indent()
.out.puts(yield_var)
.out.puts(" = ")
.gen_expression(expr)
.out.puts(";\n")
}
def CodeGenerator::gen_constant(&this, node: &AST) {
let const_ = node.u.var_decl.var
if not const_.sym.is_extern {
.gen_indent()
.out.puts("#define ")
.out.puts(const_.sym.out_name())
.out.puts(" (")
.gen_expression(node.u.var_decl.init)
.out.puts(")\n")
}
}
def CodeGenerator::gen_constants(&this, ns: &Namespace) {
for const_ : ns.constants.iter() {
.gen_constant(const_)
}
for child : ns.namespaces.iter_values() {
.gen_constants(child)
}
}
def CodeGenerator::gen_global_variables(&this, ns: &Namespace) {
for node : ns.variables.iter() {
let var = node.u.var_decl.var
if not var.sym.is_extern {
.gen_var_declaration(node)
.out.puts(";\n")
}
}
for child : ns.namespaces.iter_values() {
.gen_global_variables(child)
}
}
def CodeGenerator::gen_control_body(&this, node: &AST, body: &AST) {
if body.type == ASTType::Block {
.gen_block(body)
.out.puts(" ")
} else {
if body.type != ASTType::If {
.out.puts("\n")
}
// In this case, we're implicitly yielding the result of the body.
if node.etype? and body.type != ASTType::Yield {
.gen_yield_expression(body)
} else {
.gen_statement(body)
}
.gen_indent()
}
}
def CodeGenerator::gen_in_yield_context(&this, node: &AST) {
// Using a GCC extension for statement expressions
// https://gcc.gnu.org/onlinedocs/gcc/Statement-Exprs.html
let yield_var = `__yield_{.yield_vars.size}`
.yield_vars.push(yield_var)
let ret_type = node.etype
.out.puts("({ ")
.gen_type_and_name(ret_type, yield_var)
.out.puts(";\n")
if node.type == Block {
.gen_block(node, with_braces: false)
} else {
.indent += 1
.gen_statement(node)
.indent -= 1
}
.out.puts(";")
.out.puts(yield_var)
.out.puts("; })")
.yield_vars.pop()
}
def CodeGenerator::gen_constructor(&this, node: &AST, struc: &Structure) {
.out.putsf(`({struc.sym.out_name()})\{`)
let fields = struc.fields
let args = node.u.call.args
for let i = 0; i < args.size; i += 1 {
if i != 0 then .out.puts(", ")
let arg = args.at(i)
let field = fields.at(i)
.out.putsf(`.{field.sym.out_name()}=`)
.gen_expression(arg.expr)
}
.out.puts("}")
}
def CodeGenerator::gen_expression(&this, node: &AST) {
match node.type {
IntLiteral => {
let num_lit = &node.u.num_literal
if node.etype.base != I32 {
.out.puts("((")
.gen_type(node.etype)
.out.puts(")")
.out.puts(num_lit.text)
.out.puts(")")
} else {
.out.puts(num_lit.text)
}
}
FloatLiteral => {
let num_lit = &node.u.num_literal
.out.puts(num_lit.text)
if node.etype.base == F32 {
.out.puts("f")
}
}
FormatStringLiteral => .gen_format_string(node)
StringLiteral => {
let str_lit = node.u.string_literal
.out.puts("\"")
.out.puts(str_lit)
.out.puts("\"")
}
CharLiteral => {
let char_lit = node.u.char_literal
.out.puts("'")
.out.puts(char_lit)
.out.puts("'")
}
If => {
let a = node.u.if_stmt.body
let b = node.u.if_stmt.els
// If we've gotten past type checking, this should only be a block/match/if/expression
if a.type != ASTType::Block and b.type != ASTType::Block {
.out.puts("(")
.gen_expression(node.u.if_stmt.cond)
.out.puts(" ? ")
.gen_expression(a)
.out.puts(" : ")
.gen_expression(b)
.out.puts(")")
// We tried our best, let's fall back:
} else {
.gen_in_yield_context(node)
}
}
Match => .gen_in_yield_context(node)
Block => .gen_in_yield_context(node)
Member => {
if node.resolved_symbol? {
// Method call
let sym = node.resolved_symbol
match sym.type {
Function => .out.puts(sym.out_name())
else => {
.error(Error::new(
node.span, `Unhandled symbol type in CodeGenerator::gen_expression: {sym.type}`
))
}
}
return
}
let lhs = node.u.member.lhs
.gen_expression(lhs)
if node.u.member.is_pointer {
.out.puts("->")
} else {
.out.puts(".")
}
.out.puts(node.u.member.rhs_name)
}
Identifier | NSLookup | Specialization => {
let sym = node.resolved_symbol
if not sym? {
.error(Error::new(node.span, "Symbol not found in CodeGenerator::gen_expression"))
return
}
match sym.type {
Function | Variable | Constant => .out.puts(sym.out_name())
else => std::panic(`Unhandled symbol type: {sym.type}`)
}
}
Call => {
let callee = node.u.call.callee
// FIXME: Re-do abomination of hacky-IO with some sort of variadics?
if callee.type == Identifier and (callee.u.ident.name.eq("print") or callee.u.ident.name.eq("println")) {
.gen_internal_print(node)
return
}
let sym = callee.symbol()
if sym? and sym.type == Structure and node.u.call.is_constructor {
.gen_constructor(node, sym.u.struc)
return
}
.gen_expression(callee)
.out.puts("(")
let args = node.u.call.args
for let i = 0; i < args.size; i += 1 {
if i != 0 then .out.puts(", ")
let arg = args.at(i)
.gen_expression(arg.expr)
}
.out.puts(")")
}
BoolLiteral => {
let bool_lit = node.u.bool_literal
.out.puts(if bool_lit then "true" else "false")
}
Address => {
let expr = node.u.unary
.out.puts("&")
.gen_expression(expr)
}
Dereference => {
let expr = node.u.unary
.out.puts("*")
.gen_expression(expr)
}
Negate => {
let expr = node.u.unary
.out.puts("-")
.gen_expression(expr)
}
BitwiseNot => {
let expr = node.u.unary
.out.puts("~")
.gen_expression(expr)
}
Not => {
let expr = node.u.unary
.out.puts("!")
.gen_expression(expr)
}
IsNotNull => {
let expr = node.u.unary
.out.puts("((bool)")
.gen_expression(expr)
.out.puts(")")
}
Cast => {
let expr = node.u.unary
let type = node.etype
.out.puts("((")
.out.puts(.get_type_name_string(type, name: "", is_func_def: false))
.out.puts(")")
.gen_expression(expr)
.out.puts(")")
}
SizeOf => {
.out.puts("((u32)sizeof(")
.gen_type(node.u.size_of_type)
.out.puts("))")
}
Null => .out.puts("NULL")
And |
BitwiseAnd |
BitwiseOr |
BitwiseXor |
Divide |
GreaterThan |
GreaterThanEquals |
LeftShift |
LessThan |
LessThanEquals |
Minus |
Modulus |
Multiply |
NotEquals |
Or |
Plus |
RightShift => {
let lhs = node.u.binary.lhs
let rhs = node.u.binary.rhs
.out.puts("(")
.gen_expression(lhs)
.out.puts(" ")
.out.puts(.get_op(node.type))
.out.puts(" ")
.gen_expression(rhs)
.out.puts(")")
}
Index => {
let lhs = node.u.binary.lhs
let rhs = node.u.binary.rhs
.gen_expression(lhs)
.out.puts("[")
.gen_expression(rhs)
.out.puts("]")
}
Equals |
Assignment |
PlusEquals |
MinusEquals |
DivideEquals |
MultiplyEquals => {
.gen_expression(node.u.binary.lhs)
.out.puts(.get_op(node.type))
.gen_expression(node.u.binary.rhs)
}
PreIncrement | PreDecrement => {
.out.puts(.get_op(node.type))
.gen_expression(node.u.unary)
}
PostIncrement | PostDecrement => {
.gen_expression(node.u.unary)
.out.puts(.get_op(node.type))
}
else => .error(Error::new(node.span, `Unhandled expression type in CodeGenerator: {node.type}`))
}
}
def CodeGenerator::gen_var_declaration(&this, node: &AST) {
let var = node.u.var_decl.var
.gen_type_and_name(var.type, var.sym.out_name())
if node.u.var_decl.init? {
.out.puts(" = ")
.gen_expression(node.u.var_decl.init)
}
}
def CodeGenerator::gen_match_case_body(&this, node: &AST, body: &AST) {
if body.type == ASTType::Block {
.out.puts(" ")
.gen_block(body)
// The body is a call that exits, we don't need to yield it
} else if body.type == ASTType::Call and body.returns {
.out.puts(" ")
.gen_expression(body)
.out.puts(";")
// In this case, we're implicitly yielding the result of the body.
} else if node.etype? and body.type != ASTType::Yield {
.out.puts(" {\n")
.indent += 1
.gen_yield_expression(body)
.indent -= 1
.gen_indent()
.out.puts("}")
} else {
.out.puts(" {\n")
.indent += 1
.gen_statement(body)
.indent -= 1
.gen_indent()
.out.puts("}")
}
}
def CodeGenerator::gen_match_string(&this, node: &AST) {
let stmt = node.u.match_stmt
.gen_indent()
.out.puts("{\n")
.indent += 1
.gen_indent()
.out.puts("char *__match_str = ")
.gen_expression(stmt.expr)
.out.puts(";\n")
let cases = stmt.cases
.gen_indent()
.out.puts("if (")
for let i = 0; i < cases.size; i += 1 {
let _case = cases.at(i)
.out.puts("!strcmp(__match_str, ")
.gen_expression(_case.cond)
.out.puts(")")
if _case.body? {
.out.puts(")")
.gen_match_case_body(node, _case.body)
.out.puts(" else ")
if i != cases.size - 1 {
.out.puts("if (")
}
} else {
.out.puts(" || ")
}
}
if stmt.defolt? {
.gen_match_case_body(node, stmt.defolt)
}
.out.puts("\n")
.indent -= 1
.gen_indent()
.out.puts("}\n")
}
def CodeGenerator::gen_match(&this, node: &AST) {
let stmt = node.u.match_stmt
if stmt.expr.etype.is_str() {
.gen_match_string(node)
return
}
.gen_indent()
.out.puts("switch (")
.gen_expression(stmt.expr)
.out.puts(") {\n")
let cases = stmt.cases
.indent += 1
for _case : cases.iter() {
.gen_indent()
.out.puts("case ")
.gen_expression(_case.cond)
.out.puts(":")
if _case.body? {
.gen_match_case_body(node, _case.body)
.out.puts(" break;\n")
} else {
.out.puts("\n")
}
}
if stmt.defolt? {
.gen_indent()
.out.puts("default:")
.gen_match_case_body(node, stmt.defolt)
.out.puts(" break;\n")
}
.indent -= 1
.gen_indent()
.out.puts("}\n")
}
def CodeGenerator::gen_defers_upto(&this, end_scope: &Scope) {
let first = true
for let cur = .scope(); cur?; cur = cur.parent {
for let i = 0; i < cur.defers.size; i += 1 {
if first {
first = false
.gen_indent()
.out.puts("/* defers */\n")
}
// Note: We want to run the defers in reverse order
let idx = cur.defers.size - i - 1
let stmt = cur.defers.at(idx)
.gen_statement(stmt)
}
if cur == end_scope then break
}
}
def CodeGenerator::gen_statement(&this, node: &AST) {
.gen_debug_info(node.span)
match node.type {
ASTType::Return => {
let upto = .scope()
for let cur = .scope(); cur? and cur.cur_func?; cur = cur.parent {
upto = cur
}
.gen_defers_upto(upto)
.gen_indent()
.out.puts("return ")
if node.u.unary? {
.gen_expression(node.u.unary)
}
.out.puts(";\n")
}
ASTType::Yield => .gen_yield_expression(node.u.unary)
ASTType::Import => {}
ASTType::Break | ASTType::Continue => {
let loop_count = .scope().loop_count
let upto = .scope()
for let cur = .scope(); cur? and cur.loop_count == loop_count; cur = cur.parent {
upto = cur
}
.gen_defers_upto(upto)
.gen_indent()
if node.type == ASTType::Break {
.out.puts("break;\n")
} else {
.out.puts("continue;\n")
}
}
ASTType::VarDeclaration => {
.gen_indent()
.gen_var_declaration(node)
.out.puts(";\n")
}
ASTType::Block => {
.gen_indent()
.gen_block(node)
.out.puts("\n")
}
ASTType::Defer => {
.scope().defers.push(node.u.unary)
}
ASTType::If => {
let cond = node.u.if_stmt.cond
let body = node.u.if_stmt.body
let else_body = node.u.if_stmt.els
.gen_indent()
.out.puts("if (")
.gen_expression(cond)
.out.puts(") ")
.gen_control_body(node, body)
if else_body? {
.out.puts(" else ")
.gen_control_body(node, else_body)
.out.puts("\n")
} else {
.out.puts("\n")
}
}
ASTType::Match => .gen_match(node)
ASTType::While => {
let cond = node.u.loop.cond
let body = node.u.loop.body
.gen_indent()
.out.puts("while (")
.gen_expression(cond)
.out.puts(") ")
.gen_block(body)
.out.puts("\n")
}
ASTType::For => {
let init = node.u.loop.init
let cond = node.u.loop.cond
let step = node.u.loop.step
let body = node.u.loop.body
.gen_indent()
.out.puts("for (")
if init? {
if init.type == ASTType::VarDeclaration {
.gen_var_declaration(init)
} else {
.gen_expression(init)
}
}
.out.puts("; ")
if cond? then .gen_expression(cond)
.out.puts("; ")
if step? then .gen_expression(step)
.out.puts(") ")
.gen_block(body)
.out.puts("\n")
}
ASTType::Assert => {
let expr = node.u.assertion.expr
.gen_indent()
.out.puts("ae_assert(")
.gen_expression(expr)
.out.puts(", ")
{
.out.puts("\"")
.out.putsf(expr.span.start.str())
let expr_str = .o.program.get_source_text(expr.span)
.out.puts(": Assertion failed: `")
let len = expr_str.len()
for let i = 0; i < len; i += 1 {
match expr_str[i] {
'"' => .out.puts("\\\"")
else => .out.putc(expr_str[i])
}
}
.out.puts("`\"")
}
.out.puts(", ")
if node.u.assertion.msg? {
.gen_expression(node.u.assertion.msg)
} else {
.out.puts("NULL")
}
.out.puts(");")
// If we have an explicit `assert false`, insert an exit after it to
// make GCCs static analyzer happy
if expr.type == BoolLiteral and expr.u.bool_literal == false {
.out.puts(" exit(1);")
}
}
else => {
.gen_indent()
.gen_expression(node)
.out.puts(";\n")
}
}
}
def CodeGenerator::gen_block(&this, node: &AST, with_braces: bool = true) {
if with_braces then .out.puts("{\n")
let scope = node.u.block.scope
.o.push_scope(node.u.block.scope)
let statements = node.u.block.statements
.indent += 1
for statement : statements.iter() {
.gen_statement(statement)
}
if not node.returns {
.gen_defers_upto(scope)
}
.indent -= 1
.gen_indent()
if with_braces then .out.puts("}")
.o.pop_scope()
}
def CodeGenerator::helper_gen_type(&this, top: &Type, cur: &Type, acc: str, is_func_def: bool): str {
match cur.base {
// These should all be terminal types
Void | Bool | Char |
I8 | I16 | I32 | I64 |
U8 | U16 | U32 | U64 |
F32 | F64 => acc.replace(`{cur.base.str()} {acc}`)
Structure => acc.replace(`{cur.u.struc.sym.out_name()} {acc}`)
Enum => acc.replace(`{cur.u.enum_.sym.out_name()} {acc}`)
Alias => acc = .helper_gen_type(top, cur.u.ptr, acc, is_func_def: false)
Function => {
let args_str = Buffer::make()
let params = cur.u.func.params
if params.size == 0 then args_str.puts("void")
for let i = 0; i < params.size; i += 1 {
if i != 0 then args_str.puts(", ")
let var = params.at(i)
let arg_str = .get_type_name_string(var.type, var.sym.out_name(), is_func_def: false)
args_str.putsf(arg_str)
}
if is_func_def and cur == top {
// This allows us to also create function declarations
acc.replace(`{acc}({args_str.str()})`)
} else {
acc.replace(`(*{acc})({args_str.str()})`)
}
free(args_str.data)
acc = .helper_gen_type(
top,
cur.u.func.return_type,
acc,
is_func_def: false
)
}
Pointer => {
let needs_parens = (cur.u.ptr? and
(cur.u.ptr.base == BaseType::Function or
cur.u.ptr.base == BaseType::Array))
if needs_parens {
acc.replace(`(*{acc})`)
} else {
acc.replace(`*{acc}`)
}
acc = .helper_gen_type(top, cur.u.ptr, acc, is_func_def: false)
}
Array => {
// Need to evaluate the expression into a string...
let prev_buffer: Buffer = .out
.out = Buffer::make()
.gen_expression(cur.u.arr.size_expr)
acc.replace(`{acc}[{.out.str()}]`)
free(.out.data)
.out = prev_buffer
acc = .helper_gen_type(top, cur.u.arr.elem_type, acc, is_func_def: false)
}
else => .error(Error::new(cur.span, `Unhandled type found in CodeGenerator::helper_gen_type: {cur.base}: {cur.str()}`))
}
return acc
}
def CodeGenerator::get_type_name_string(&this, type: &Type, name: str, is_func_def: bool): str {
assert type != null
let final = .helper_gen_type(type, type, name.copy(), is_func_def)
final.strip_trailing_whitespace()
return final
}
def CodeGenerator::gen_type_and_name(&this, type: &Type, name: str) {
.out.putsf(.get_type_name_string(type, name, is_func_def: false))
}
def CodeGenerator::gen_type(&this, type: &Type) {
.gen_type_and_name(type, name: "")
}
def CodeGenerator::gen_function(&this, func: &Function) {
if func.is_method and func.parent_type.base == Structure {
let struc = func.parent_type.u.struc
if struc.sym.is_templated() then return
}
if func.sym.is_templated() then return
.gen_debug_info(func.sym.span)
.gen_function_decl(func)
.out.puts(" ")
.gen_block(func.body)
.out.puts("\n\n")
}
def CodeGenerator::gen_function_decl(&this, func: &Function) {
let funfull_name = func.sym.out_name()
let s = .get_type_name_string(func.type, funfull_name, true)
.out.putsf(s)
}
def CodeGenerator::gen_functions(&this, ns: &Namespace) {
let functions = ns.functions;
.o.push_scope(ns.scope)
for func : functions.iter() {
if func.sym.is_extern then continue
if func.sym.is_templated() then {
for instance : func.sym.template.instances.iter() {
let sym = instance.resolved
assert sym.type == Function
let func = sym.u.func
.gen_function(func)
}
} else {
.gen_function(func)
}
}
for child : ns.namespaces.iter_values() {
.gen_functions(child)
}
.o.pop_scope()
}
def CodeGenerator::gen_function_decls(&this, ns: &Namespace) {
for func : ns.functions.iter() {
if func.sym.is_extern continue
if func.is_method and func.parent_type.base == Structure {
let struc = func.parent_type.u.struc
if struc.sym.is_templated() then continue
}
if func.sym.is_templated() then {
for instance : func.sym.template.instances.iter() {
let sym = instance.resolved
assert sym.type == Function
let func = sym.u.func
.gen_function_decl(func)
if func.exits then .out.puts(" __attribute__((noreturn))")
.out.puts(";\n")
}
continue
}
.gen_function_decl(func)
if func.exits then .out.puts(" __attribute__((noreturn))")
.out.puts(";\n")
}
for child : ns.namespaces.iter_values() {
.gen_function_decls(child)
}
}
def CodeGenerator::gen_enum_types(&this, ns: &Namespace) {
for enum_ : ns.enums.iter() {
.gen_enum(enum_)
}
for child : ns.namespaces.iter_values() {
.gen_enum_types(child)
}
}
//* Auto-generate `dbg()` method for enums
def CodeGenerator::gen_enum_dbg_method(&this, enum_: &Enum) {
let dbg = enum_.type.methods.at("dbg")
.gen_function_decl(dbg)
.out.puts(" {\n")
.indent += 1
.gen_indent()
.out.puts("switch (this) {\n")
.indent += 1
for field : enum_.fields.iter() {