-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcodegen.bl
More file actions
2082 lines (1926 loc) · 59.8 KB
/
Copy pathcodegen.bl
File metadata and controls
2082 lines (1926 loc) · 59.8 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
// codegen.bl — Self-hosting C code generator for Blink
//
// Minimal subset: enough to compile hello_compiled.bl via the
// Python C backend. Reads the parallel-array AST node pool produced
// by parser.bl and emits C source as a list of strings.
//
// Constraints: same as lexer/parser — parallel arrays, no struct-in-list,
// no closures, no imports. Constants duplicated for self-contained compilation.
// ── AST node kind constants (from parser.bl) ──────────────────────
let ND_INT_LIT = 0
let ND_FLOAT_LIT = 1
let ND_IDENT = 2
let ND_CALL = 3
let ND_METHOD_CALL = 4
let ND_BIN_OP = 5
let ND_UNARY_OP = 6
let ND_INTERP_STRING = 7
let ND_BOOL_LIT = 8
let ND_TUPLE_LIT = 9
let ND_LIST_LIT = 10
let ND_STRUCT_LIT = 11
let ND_FIELD_ACCESS = 12
let ND_INDEX_EXPR = 13
let ND_RANGE_LIT = 14
let ND_IF_EXPR = 15
let ND_MATCH_EXPR = 16
let ND_LET_BINDING = 20
let ND_EXPR_STMT = 21
let ND_ASSIGNMENT = 22
let ND_COMPOUND_ASSIGN = 23
let ND_RETURN = 24
let ND_FOR_IN = 25
let ND_WHILE_LOOP = 26
let ND_LOOP_EXPR = 27
let ND_BREAK = 28
let ND_CONTINUE = 29
let ND_BLOCK = 35
let ND_FN_DEF = 36
let ND_PARAM = 37
let ND_PROGRAM = 38
let ND_TYPE_DEF = 40
let ND_TYPE_FIELD = 41
let ND_TYPE_VARIANT = 42
let ND_INT_PATTERN = 50
let ND_WILDCARD_PATTERN = 51
let ND_IDENT_PATTERN = 52
let ND_TUPLE_PATTERN = 53
let ND_MATCH_ARM = 60
let ND_STRUCT_LIT_FIELD = 61
let ND_TYPE_ANN = 75
// ── C type constants ────────────────────────────────────────────────
// Instead of enums, plain ints.
let CT_INT = 0
let CT_FLOAT = 1
let CT_BOOL = 2
let CT_STRING = 3
let CT_LIST = 4
let CT_VOID = 5
// ── Node pool (extern — set by caller before calling generate) ──────
// These are the same arrays from parser.bl. In the full compiler,
// they will be the SAME globals. For now, duplicated declarations.
let mut np_kind: List[Int] = []
let mut np_int_val: List[Int] = []
let mut np_str_val: List[Str] = []
let mut np_name: List[Str] = []
let mut np_op: List[Str] = []
let mut np_left: List[Int] = []
let mut np_right: List[Int] = []
let mut np_body: List[Int] = []
let mut np_condition: List[Int] = []
let mut np_then_body: List[Int] = []
let mut np_else_body: List[Int] = []
let mut np_scrutinee: List[Int] = []
let mut np_pattern: List[Int] = []
let mut np_guard: List[Int] = []
let mut np_value: List[Int] = []
let mut np_target: List[Int] = []
let mut np_iterable: List[Int] = []
let mut np_var_name: List[Str] = []
let mut np_is_mut: List[Int] = []
let mut np_is_pub: List[Int] = []
let mut np_inclusive: List[Int] = []
let mut np_start: List[Int] = []
let mut np_end: List[Int] = []
let mut np_obj: List[Int] = []
let mut np_method: List[Str] = []
let mut np_index: List[Int] = []
let mut np_return_type: List[Str] = []
let mut np_type_name: List[Str] = []
let mut np_params: List[Int] = []
let mut np_args: List[Int] = []
let mut np_stmts: List[Int] = []
let mut np_arms: List[Int] = []
let mut np_fields: List[Int] = []
let mut np_elements: List[Int] = []
// Sublists (same as parser.bl)
let mut sl_items: List[Int] = []
let mut sl_start: List[Int] = []
let mut sl_len: List[Int] = []
fn sublist_get(sl: Int, idx: Int) -> Int {
sl_items.get(sl_start.get(sl).unwrap() + idx).unwrap()
}
fn sublist_length(sl: Int) -> Int {
sl_len.get(sl).unwrap()
}
// ── Codegen state ───────────────────────────────────────────────────
let mut cg_lines: List[Str] = []
let mut cg_indent: Int = 0
let mut cg_temp_counter: Int = 0
let mut cg_global_inits: List[Str] = []
let mut struct_reg_names: List[Str] = []
let mut emitted_let_names: List[Str] = []
let mut emitted_fn_names: List[Str] = []
// Scope: parallel lists for variable names, types, and mutability.
// Each scope is a "frame" delimited by frame_starts.
let mut scope_names: List[Str] = []
let mut scope_types: List[Int] = []
let mut scope_muts: List[Int] = []
let mut scope_frame_starts: List[Int] = []
// Function registry: parallel lists (fn name -> return type, param count)
let mut fn_reg_names: List[Str] = []
let mut fn_reg_ret: List[Int] = []
let mut var_list_elem_names: List[Str] = []
let mut var_list_elem_types: List[Int] = []
// Scratch space for tuple match scrutinee temps
let mut match_scrut_strs: List[Str] = []
let mut match_scrut_types: List[Int] = []
fn push_scope() {
scope_frame_starts.push(scope_names.len())
}
fn pop_scope() {
let start = scope_frame_starts.get(scope_frame_starts.len() - 1).unwrap()
scope_frame_starts.pop()
while scope_names.len() > start {
scope_names.pop()
scope_types.pop()
scope_muts.pop()
}
}
fn set_var(name: Str, ctype: Int, is_mut: Int) {
scope_names.push(name)
scope_types.push(ctype)
scope_muts.push(is_mut)
}
fn get_var_type(name: Str) -> Int {
let mut i = scope_names.len() - 1
while i >= 0 {
if scope_names.get(i).unwrap() == name {
return scope_types.get(i).unwrap()
}
i = i - 1
}
CT_INT
}
fn reg_fn(name: Str, ret: Int) {
fn_reg_names.push(name)
fn_reg_ret.push(ret)
}
fn get_fn_ret(name: Str) -> Int {
let mut i = 0
while i < fn_reg_names.len() {
if fn_reg_names.get(i).unwrap() == name {
return fn_reg_ret.get(i).unwrap()
}
i = i + 1
}
CT_VOID
}
fn set_list_elem_type(name: Str, elem_type: Int) {
var_list_elem_names.push(name)
var_list_elem_types.push(elem_type)
}
fn get_list_elem_type(name: Str) -> Int {
let mut i = 0
while i < var_list_elem_names.len() {
if var_list_elem_names.get(i).unwrap() == name {
return var_list_elem_types.get(i).unwrap()
}
i = i + 1
}
CT_INT
}
fn is_struct_type(name: Str) -> Int {
let mut i = 0
while i < struct_reg_names.len() {
if struct_reg_names.get(i).unwrap() == name {
return 1
}
i = i + 1
}
0
}
fn is_emitted_let(name: Str) -> Int {
let mut i = 0
while i < emitted_let_names.len() {
if emitted_let_names.get(i).unwrap() == name {
return 1
}
i = i + 1
}
0
}
fn is_emitted_fn(name: Str) -> Int {
let mut i = 0
while i < emitted_fn_names.len() {
if emitted_fn_names.get(i).unwrap() == name {
return 1
}
i = i + 1
}
0
}
// ── Helpers ─────────────────────────────────────────────────────────
fn c_type_str(ct: Int) -> Str {
if ct == CT_INT { "int64_t" }
else if ct == CT_FLOAT { "double" }
else if ct == CT_BOOL { "int" }
else if ct == CT_STRING { "const char*" }
else if ct == CT_LIST { "blink_list*" }
else { "void" }
}
fn type_from_name(name: Str) -> Int {
if name == "Int" { CT_INT }
else if name == "Str" { CT_STRING }
else if name == "Float" { CT_FLOAT }
else if name == "Bool" { CT_BOOL }
else if name == "List" { CT_LIST }
else { CT_VOID }
}
fn fresh_temp(prefix: Str) -> Str {
let n = cg_temp_counter
cg_temp_counter = cg_temp_counter + 1
"{prefix}{n}"
}
fn emit_line(line: Str) {
if line == "" {
cg_lines.push("")
} else {
let mut pad = ""
let mut i = 0
while i < cg_indent {
pad = pad.concat(" ")
i = i + 1
}
cg_lines.push(pad.concat(line))
}
}
fn join_lines() -> Str {
let mut result = ""
let mut i = 0
while i < cg_lines.len() {
if i > 0 {
result = result.concat("\n")
}
result = result.concat(cg_lines.get(i).unwrap())
i = i + 1
}
result
}
// ── Expression codegen ──────────────────────────────────────────────
// Returns (expr_str, type) packed into parallel result slots.
// Since we can't return tuples in the C backend, we use mutable globals.
let mut expr_result_str: Str = ""
let mut expr_result_type: Int = 0
fn emit_expr(node: Int) {
let kind = np_kind.get(node).unwrap()
if kind == ND_INT_LIT {
let s = np_str_val.get(node).unwrap()
if s == "" {
expr_result_str = "{np_int_val.get(node).unwrap()}"
} else {
expr_result_str = s
}
expr_result_type = CT_INT
return
}
if kind == ND_FLOAT_LIT {
expr_result_str = np_str_val.get(node).unwrap()
expr_result_type = CT_FLOAT
return
}
if kind == ND_BOOL_LIT {
if np_int_val.get(node).unwrap() != 0 {
expr_result_str = "1"
} else {
expr_result_str = "0"
}
expr_result_type = CT_BOOL
return
}
if kind == ND_IDENT {
let name = np_name.get(node).unwrap()
expr_result_str = name
expr_result_type = get_var_type(name)
return
}
if kind == ND_BIN_OP {
emit_binop(node)
return
}
if kind == ND_UNARY_OP {
emit_unaryop(node)
return
}
if kind == ND_CALL {
emit_call(node)
return
}
if kind == ND_METHOD_CALL {
emit_method_call(node)
return
}
if kind == ND_INTERP_STRING {
emit_interp_string(node)
return
}
if kind == ND_IF_EXPR {
emit_if_expr(node)
return
}
if kind == ND_FIELD_ACCESS {
emit_expr(np_obj.get(node).unwrap())
let obj_str = expr_result_str
expr_result_str = "{obj_str}.{np_name.get(node).unwrap()}"
expr_result_type = CT_VOID
return
}
if kind == ND_INDEX_EXPR {
emit_expr(np_obj.get(node).unwrap())
let obj_str = expr_result_str
let obj_type = expr_result_type
emit_expr(np_index.get(node).unwrap())
let idx_str = expr_result_str
if obj_type == CT_STRING {
expr_result_str = "blink_str_char_at({obj_str}, {idx_str})"
expr_result_type = CT_INT
} else {
expr_result_str = "{obj_str}[{idx_str}]"
expr_result_type = CT_INT
}
return
}
if kind == ND_LIST_LIT {
emit_list_lit(node)
return
}
if kind == ND_RANGE_LIT {
expr_result_str = "0"
expr_result_type = CT_VOID
return
}
if kind == ND_MATCH_EXPR {
emit_match_expr(node)
return
}
if kind == ND_BLOCK {
emit_block_expr(node)
return
}
if kind == ND_RETURN {
if np_value.get(node).unwrap() != -1 {
emit_expr(np_value.get(node).unwrap())
let val_str = expr_result_str
emit_line("return {val_str};")
} else {
emit_line("return;")
}
expr_result_str = "0"
expr_result_type = CT_VOID
return
}
if kind == ND_STRUCT_LIT {
emit_struct_lit(node)
return
}
expr_result_str = "0"
expr_result_type = CT_VOID
}
fn emit_binop(node: Int) {
emit_expr(np_left.get(node).unwrap())
let left_str = expr_result_str
let left_type = expr_result_type
emit_expr(np_right.get(node).unwrap())
let right_str = expr_result_str
let right_type = expr_result_type
let op = np_op.get(node).unwrap()
if op == "==" && left_type == CT_STRING && right_type == CT_STRING {
expr_result_str = "blink_str_eq({left_str}, {right_str})"
expr_result_type = CT_BOOL
return
}
if op == "!=" && left_type == CT_STRING && right_type == CT_STRING {
expr_result_str = "(!blink_str_eq({left_str}, {right_str}))"
expr_result_type = CT_BOOL
return
}
if op == "+" && (left_type == CT_STRING || right_type == CT_STRING) {
expr_result_str = "blink_str_concat({left_str}, {right_str})"
expr_result_type = CT_STRING
return
}
expr_result_str = "({left_str} {op} {right_str})"
if op == "==" || op == "!=" || op == "<" || op == ">" || op == "<=" || op == ">=" || op == "&&" || op == "||" {
expr_result_type = CT_BOOL
} else {
expr_result_type = left_type
}
}
fn emit_unaryop(node: Int) {
emit_expr(np_left.get(node).unwrap())
let operand_str = expr_result_str
let operand_type = expr_result_type
let op = np_op.get(node).unwrap()
if op == "-" {
expr_result_str = "(-{operand_str})"
expr_result_type = operand_type
} else if op == "!" {
expr_result_str = "(!{operand_str})"
expr_result_type = CT_BOOL
} else {
expr_result_str = "({op}{operand_str})"
expr_result_type = operand_type
}
}
fn emit_call(node: Int) {
let func_node = np_left.get(node).unwrap()
let func_kind = np_kind.get(func_node).unwrap()
if func_kind == ND_IDENT {
let fn_name = np_name.get(func_node).unwrap()
let args_sl = np_args.get(node).unwrap()
let mut args_str = ""
if args_sl != -1 {
let mut i = 0
while i < sublist_length(args_sl) {
if i > 0 {
args_str = args_str.concat(", ")
}
emit_expr(sublist_get(args_sl, i))
args_str = args_str.concat(expr_result_str)
i = i + 1
}
}
expr_result_str = "blink_{fn_name}({args_str})"
expr_result_type = get_fn_ret(fn_name)
return
}
emit_expr(func_node)
let func_str = expr_result_str
let args_sl = np_args.get(node).unwrap()
let mut args_str = ""
if args_sl != -1 {
let mut i = 0
while i < sublist_length(args_sl) {
if i > 0 {
args_str = args_str.concat(", ")
}
emit_expr(sublist_get(args_sl, i))
args_str = args_str.concat(expr_result_str)
i = i + 1
}
}
expr_result_str = "{func_str}({args_str})"
expr_result_type = CT_VOID
}
fn emit_method_call(node: Int) {
let obj_node = np_obj.get(node).unwrap()
let method = np_method.get(node).unwrap()
// Special case: io.println
if np_kind.get(obj_node).unwrap() == ND_IDENT && np_name.get(obj_node).unwrap() == "io" && method == "println" {
let args_sl = np_args.get(node).unwrap()
if args_sl != -1 && sublist_length(args_sl) > 0 {
emit_expr(sublist_get(args_sl, 0))
let arg_str = expr_result_str
let arg_type = expr_result_type
if arg_type == CT_INT {
emit_line("printf(\"%%lld\\n\", (long long){arg_str});")
} else if arg_type == CT_FLOAT {
emit_line("printf(\"%%g\\n\", {arg_str});")
} else if arg_type == CT_BOOL {
emit_line("printf(\"%%s\\n\", {arg_str} ? \"true\" : \"false\");")
} else {
emit_line("printf(\"%%s\\n\", {arg_str});")
}
} else {
emit_line("printf(\"\\n\");")
}
expr_result_str = "0"
expr_result_type = CT_VOID
return
}
emit_expr(obj_node)
let obj_str = expr_result_str
let obj_type = expr_result_type
// String methods
if obj_type == CT_STRING {
if method == "len" {
expr_result_str = "blink_str_len({obj_str})"
expr_result_type = CT_INT
return
}
if method == "char_at" || method == "charAt" {
let args_sl = np_args.get(node).unwrap()
emit_expr(sublist_get(args_sl, 0))
let idx_str = expr_result_str
expr_result_str = "blink_str_char_at({obj_str}, {idx_str})"
expr_result_type = CT_INT
return
}
if method == "substring" || method == "substr" {
let args_sl = np_args.get(node).unwrap()
emit_expr(sublist_get(args_sl, 0))
let start_str = expr_result_str
emit_expr(sublist_get(args_sl, 1))
let len_str = expr_result_str
expr_result_str = "blink_str_substr({obj_str}, {start_str}, {len_str})"
expr_result_type = CT_STRING
return
}
if method == "contains" {
let args_sl = np_args.get(node).unwrap()
emit_expr(sublist_get(args_sl, 0))
let needle_str = expr_result_str
expr_result_str = "blink_str_contains({obj_str}, {needle_str})"
expr_result_type = CT_BOOL
return
}
if method == "starts_with" {
let args_sl = np_args.get(node).unwrap()
emit_expr(sublist_get(args_sl, 0))
let pfx_str = expr_result_str
expr_result_str = "blink_str_starts_with({obj_str}, {pfx_str})"
expr_result_type = CT_BOOL
return
}
if method == "concat" {
let args_sl = np_args.get(node).unwrap()
emit_expr(sublist_get(args_sl, 0))
let other_str = expr_result_str
expr_result_str = "blink_str_concat({obj_str}, {other_str})"
expr_result_type = CT_STRING
return
}
}
// List methods
if obj_type == CT_LIST {
if method == "push" {
let args_sl = np_args.get(node).unwrap()
emit_expr(sublist_get(args_sl, 0))
let val_str = expr_result_str
let val_type = expr_result_type
if val_type == CT_INT {
emit_line("blink_list_push({obj_str}, (void*)(intptr_t){val_str});")
} else {
emit_line("blink_list_push({obj_str}, (void*){val_str});")
}
expr_result_str = "0"
expr_result_type = CT_VOID
return
}
if method == "pop" {
emit_line("blink_list_pop({obj_str});")
expr_result_str = "0"
expr_result_type = CT_VOID
return
}
if method == "len" {
expr_result_str = "blink_list_len({obj_str})"
expr_result_type = CT_INT
return
}
if method == "get" {
let args_sl = np_args.get(node).unwrap()
emit_expr(sublist_get(args_sl, 0))
let idx_str = expr_result_str
let elem_type = get_list_elem_type(obj_str)
if elem_type == CT_STRING {
expr_result_str = "(const char*)blink_list_get({obj_str}, {idx_str})"
expr_result_type = CT_STRING
} else {
expr_result_str = "(int64_t)(intptr_t)blink_list_get({obj_str}, {idx_str})"
expr_result_type = CT_INT
}
return
}
if method == "set" {
let args_sl = np_args.get(node).unwrap()
emit_expr(sublist_get(args_sl, 0))
let idx_str = expr_result_str
emit_expr(sublist_get(args_sl, 1))
let val_str2 = expr_result_str
let val_type2 = expr_result_type
if val_type2 == CT_INT {
emit_line("blink_list_set({obj_str}, {idx_str}, (void*)(intptr_t){val_str2});")
} else {
emit_line("blink_list_set({obj_str}, {idx_str}, (void*){val_str2});")
}
expr_result_str = "0"
expr_result_type = CT_VOID
return
}
}
// Generic fallback
let args_sl = np_args.get(node).unwrap()
let mut args_str = ""
if args_sl != -1 {
let mut i = 0
while i < sublist_length(args_sl) {
if i > 0 {
args_str = args_str.concat(", ")
}
emit_expr(sublist_get(args_sl, i))
args_str = args_str.concat(expr_result_str)
i = i + 1
}
}
expr_result_str = "{obj_str}_{method}({args_str})"
expr_result_type = CT_VOID
}
fn escape_c_string(s: Str) -> Str {
let mut result = ""
let mut i = 0
while i < s.len() {
let ch = s.char_at(i)
if ch == 92 {
result = result.concat("\\\\")
} else if ch == 34 {
result = result.concat("\\\"")
} else if ch == 10 {
result = result.concat("\\n")
} else if ch == 9 {
result = result.concat("\\t")
} else {
result = result.concat(s.substring(i, 1))
}
i = i + 1
}
result
}
fn emit_interp_string(node: Int) {
let parts_sl = np_elements.get(node).unwrap()
if parts_sl == -1 {
expr_result_str = "\"\""
expr_result_type = CT_STRING
return
}
// Fast path: if all parts are literal, emit a simple string constant
let mut all_literal = 1
let mut ai = 0
while ai < sublist_length(parts_sl) {
let part = sublist_get(parts_sl, ai)
let pk = np_kind.get(part).unwrap()
if !(pk == ND_IDENT && np_str_val.get(part).unwrap() == np_name.get(part).unwrap()) {
all_literal = 0
}
ai = ai + 1
}
if all_literal != 0 {
let mut concat_str = ""
let mut ci = 0
while ci < sublist_length(parts_sl) {
let part = sublist_get(parts_sl, ci)
concat_str = concat_str.concat(escape_c_string(np_str_val.get(part).unwrap()))
ci = ci + 1
}
expr_result_str = "\"".concat(concat_str).concat("\"")
expr_result_type = CT_STRING
return
}
// Slow path: use snprintf for strings with expression parts
let buf_name = fresh_temp("_si_")
emit_line("char {buf_name}[4096];")
let mut fmt = ""
let mut args = ""
let mut has_args = 0
let mut i = 0
while i < sublist_length(parts_sl) {
let part = sublist_get(parts_sl, i)
let pk = np_kind.get(part).unwrap()
// Literal string parts: parser stores them as ND_IDENT with str_val == name
// Expression parts: ND_IDENT with str_val == "" (or other node kinds)
if pk == ND_IDENT && np_str_val.get(part).unwrap() == np_name.get(part).unwrap() {
fmt = fmt.concat(escape_c_string(np_str_val.get(part).unwrap()))
} else {
// Expression part
emit_expr(part)
let e_str = expr_result_str
let e_type = expr_result_type
if e_type == CT_INT {
fmt = fmt.concat("%lld")
if has_args {
args = args.concat(", ")
}
args = args.concat("(long long)")
args = args.concat(e_str)
has_args = 1
} else if e_type == CT_FLOAT {
fmt = fmt.concat("%g")
if has_args {
args = args.concat(", ")
}
args = args.concat(e_str)
has_args = 1
} else if e_type == CT_BOOL {
fmt = fmt.concat("%s")
if has_args {
args = args.concat(", ")
}
args = args.concat(e_str)
args = args.concat(" ? \"true\" : \"false\"")
has_args = 1
} else {
fmt = fmt.concat("%s")
if has_args {
args = args.concat(", ")
}
args = args.concat(e_str)
has_args = 1
}
}
i = i + 1
}
if has_args {
let line = "snprintf(".concat(buf_name).concat(", 4096, \"").concat(fmt).concat("\", ").concat(args).concat(");")
emit_line(line)
} else {
let line = "snprintf(".concat(buf_name).concat(", 4096, \"").concat(fmt).concat("\");")
emit_line(line)
}
expr_result_str = "strdup(".concat(buf_name).concat(")")
expr_result_type = CT_STRING
}
fn emit_list_lit(node: Int) {
let tmp = fresh_temp("_l")
emit_line("blink_list* {tmp} = blink_list_new();")
let elems_sl = np_elements.get(node).unwrap()
if elems_sl != -1 {
let mut i = 0
while i < sublist_length(elems_sl) {
emit_expr(sublist_get(elems_sl, i))
let e_str = expr_result_str
let e_type = expr_result_type
if e_type == CT_INT {
emit_line("blink_list_push({tmp}, (void*)(intptr_t){e_str});")
} else {
emit_line("blink_list_push({tmp}, (void*){e_str});")
}
i = i + 1
}
}
expr_result_str = tmp
expr_result_type = CT_LIST
}
fn emit_struct_lit(node: Int) {
let sname = np_type_name.get(node).unwrap()
let c_type = "blink_{sname}"
let tmp = fresh_temp("_s")
let flds_sl = np_fields.get(node).unwrap()
let mut inits = ""
if flds_sl != -1 {
let mut i = 0
while i < sublist_length(flds_sl) {
let sf = sublist_get(flds_sl, i)
let fname = np_name.get(sf).unwrap()
emit_expr(np_value.get(sf).unwrap())
let val_str = expr_result_str
if i > 0 {
inits = inits.concat(", ")
}
inits = inits.concat(".{fname} = {val_str}")
i = i + 1
}
}
emit_line("{c_type} {tmp} = \{ {inits} };")
expr_result_str = tmp
expr_result_type = CT_VOID
}
fn emit_if_expr(node: Int) {
let tmp = fresh_temp("_if_")
// Infer type from then branch
let then_type = infer_block_type(np_then_body.get(node).unwrap())
emit_line("{c_type_str(then_type)} {tmp};")
emit_expr(np_condition.get(node).unwrap())
let cond_str = expr_result_str
emit_line("if ({cond_str}) \{")
cg_indent = cg_indent + 1
let then_val = emit_block_value(np_then_body.get(node).unwrap())
emit_line("{tmp} = {then_val};")
cg_indent = cg_indent - 1
if np_else_body.get(node).unwrap() != -1 {
emit_line("} else \{")
cg_indent = cg_indent + 1
let else_val = emit_block_value(np_else_body.get(node).unwrap())
emit_line("{tmp} = {else_val};")
cg_indent = cg_indent - 1
}
emit_line("}")
set_var(tmp, then_type, 1)
expr_result_str = tmp
expr_result_type = then_type
}
fn emit_match_expr(node: Int) {
let scrut = np_scrutinee.get(node).unwrap()
// Build list of scrutinee values (multiple if tuple literal)
match_scrut_strs = []
match_scrut_types = []
if np_kind.get(scrut).unwrap() == ND_TUPLE_LIT {
let elems_sl = np_elements.get(scrut).unwrap()
if elems_sl != -1 {
let mut ei = 0
while ei < sublist_length(elems_sl) {
emit_expr(sublist_get(elems_sl, ei))
let tmp = fresh_temp("_tup_")
emit_line("{c_type_str(expr_result_type)} {tmp} = {expr_result_str};")
set_var(tmp, expr_result_type, 1)
match_scrut_strs.push(tmp)
match_scrut_types.push(expr_result_type)
ei = ei + 1
}
}
} else {
emit_expr(scrut)
match_scrut_strs.push(expr_result_str)
match_scrut_types.push(expr_result_type)
}
let arms_sl = np_arms.get(node).unwrap()
if arms_sl == -1 {
expr_result_str = "0"
expr_result_type = CT_VOID
return
}
let first_arm = sublist_get(arms_sl, 0)
let result_type = infer_arm_type(first_arm)
let result_var = fresh_temp("_match_")
emit_line("{c_type_str(result_type)} {result_var};")
let mut first = 1
let mut i = 0
while i < sublist_length(arms_sl) {
let arm = sublist_get(arms_sl, i)
let pat = np_pattern.get(arm).unwrap()
let cond = pattern_condition(pat, 0, match_scrut_strs.len())
let is_wildcard = cond == ""
if is_wildcard {
if first {
emit_line("\{")
} else {
emit_line("} else \{")
}
} else if first {
emit_line("if ({cond}) \{")
} else {
emit_line("} else if ({cond}) \{")
}
cg_indent = cg_indent + 1
bind_pattern_vars(pat, 0, match_scrut_strs.len())
let arm_val = emit_arm_value(np_body.get(arm).unwrap())
emit_line("{result_var} = {arm_val};")
cg_indent = cg_indent - 1
first = 0
i = i + 1
}
emit_line("}")
set_var(result_var, result_type, 1)
expr_result_str = result_var
expr_result_type = result_type
}
// Build a C condition string for a pattern.
// scrut_off/scrut_len index into match_scrut_strs/match_scrut_types.
// Returns "" when the pattern always matches (wildcard/ident).
fn pattern_condition(pat: Int, scrut_off: Int, scrut_len: Int) -> Str {
let pk = np_kind.get(pat).unwrap()
if pk == ND_WILDCARD_PATTERN || pk == ND_IDENT_PATTERN {
return ""
}
if pk == ND_INT_PATTERN {
let pat_val = np_str_val.get(pat).unwrap()
return "({match_scrut_strs.get(scrut_off).unwrap()} == {pat_val})"
}
if pk == ND_TUPLE_PATTERN {
let elems_sl = np_elements.get(pat).unwrap()
if elems_sl == -1 {
return ""
}
let mut parts = ""
let mut parts_n = 0
let mut j = 0
while j < sublist_length(elems_sl) {
let sub_pat = sublist_get(elems_sl, j)
let sub_cond = pattern_condition(sub_pat, scrut_off + j, 1)
if sub_cond != "" {
if parts_n > 0 {
parts = parts.concat(" && ")
}
parts = parts.concat(sub_cond)
parts_n = parts_n + 1
}
j = j + 1
}
return parts
}
""
}
// Emit C variable bindings for ident sub-patterns within a pattern.
// scrut_off/scrut_len index into match_scrut_strs/match_scrut_types.
fn bind_pattern_vars(pat: Int, scrut_off: Int, scrut_len: Int) {
let pk = np_kind.get(pat).unwrap()
if pk == ND_IDENT_PATTERN {
if scrut_len == 1 {
let bind_name = np_name.get(pat).unwrap()
let st = match_scrut_types.get(scrut_off).unwrap()
emit_line("{c_type_str(st)} {bind_name} = {match_scrut_strs.get(scrut_off).unwrap()};")
set_var(bind_name, st, 1)
}
return
}
if pk == ND_TUPLE_PATTERN {
let elems_sl = np_elements.get(pat).unwrap()
if elems_sl != -1 {