-
-
Notifications
You must be signed in to change notification settings - Fork 2.2k
Expand file tree
/
Copy pathstruct.v
More file actions
1717 lines (1659 loc) · 47.2 KB
/
struct.v
File metadata and controls
1717 lines (1659 loc) · 47.2 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
// Copyright (c) 2026 Alexander Medvednikov. All rights reserved.
// Use of this source code is governed by an MIT license
// that can be found in the LICENSE file.
module transformer
import v2.ast
import v2.types
import v2.token
fn (mut t Transformer) synth_selector(lhs ast.Expr, field_name string, typ types.Type) ast.Expr {
pos := t.next_synth_pos()
t.register_synth_type(pos, typ)
return ast.Expr(ast.SelectorExpr{
lhs: lhs
rhs: ast.Ident{
name: field_name
}
pos: pos
})
}
// synth_selector_from_struct creates a typed SelectorExpr by looking up the field type
// from the named struct in the environment. Falls back to a pos-only synth node if
// the field type cannot be resolved.
fn (mut t Transformer) synth_selector_from_struct(lhs ast.Expr, field_name string, struct_name string) ast.Expr {
pos := t.next_synth_pos()
if field_typ := t.lookup_struct_field_type(struct_name, field_name) {
t.register_synth_type(pos, field_typ)
}
return ast.Expr(ast.SelectorExpr{
lhs: lhs
rhs: ast.Ident{
name: field_name
}
pos: pos
})
}
// lookup_struct_field_type returns the raw types.Type for a struct field.
fn (t &Transformer) lookup_struct_field_type(struct_name string, field_name string) ?types.Type {
mut sname := struct_name
mut mod := ''
if struct_name.contains('__') {
mod = struct_name.all_before_last('__')
sname = struct_name.all_after_last('__')
}
lock t.env.scopes {
// Try module scope first if qualified
if mod != '' {
if scope := t.env.scopes[mod] {
if obj := scope.objects[sname] {
if obj is types.Type {
typ := types.Type(obj)
if typ is types.Struct {
for field in typ.fields {
if field.name == field_name {
return field.typ
}
}
}
}
}
}
}
// Fallback: scan all scopes
scope_names := t.env.scopes.keys()
for scope_name in scope_names {
scope := t.env.scopes[scope_name] or { continue }
for name in [struct_name, sname] {
if obj := scope.objects[name] {
if obj is types.Type {
typ := types.Type(obj)
if typ is types.Struct {
for field in typ.fields {
if field.name == field_name {
return field.typ
}
}
}
}
}
}
}
}
return none
}
// open_scope creates a new nested scope
fn (mut t Transformer) apply_smartcast_field_access_ctx(sumtype_expr ast.Expr, field_name string, ctx SmartcastContext) ast.Expr {
// variant (short name) is used for union member access
// variant_full (full name) is used for type cast
variant_short := ctx.variant
// Extract simple variant name for _data._ accessor (strip module prefix)
// But preserve composite type prefixes like Array_, Map_, Array_fixed_
variant_simple := if variant_short.starts_with('Array_') || variant_short.starts_with('Map_') {
// For composite types, use the short name to match union member
variant_short
} else if variant_short.contains('__') {
variant_short.all_after_last('__')
} else {
variant_short
}
// Use full variant name for type cast from context
mangled_variant := if ctx.variant_full != '' {
ctx.variant_full
} else if variant_short.contains('__') {
variant_short // Already has module prefix
} else if t.cur_module != '' && t.cur_module != 'main' && t.cur_module != 'builtin' {
'${t.cur_module}__${variant_short}'
} else {
variant_short
}
// For nested smartcasts, we need to transform the base of sumtype_expr to apply outer smartcasts
// E.g., for stmt.receiver.typ with outer smartcast on stmt, we need to transform stmt.receiver first.
// Temporarily remove this exact context to avoid applying it recursively.
removed_ctxs := t.remove_matching_smartcasts(ctx)
transformed_base := t.transform_expr(sumtype_expr)
t.restore_smartcasts(removed_ctxs)
if t.expr_is_casted_to_type(transformed_base, '${mangled_variant}*') {
return t.synth_selector_from_struct(transformed_base, field_name, mangled_variant)
}
// Already concretely casted to this variant by an outer smartcast context.
if t.expr_is_casted_to_type(transformed_base, mangled_variant) {
return t.synth_selector_from_struct(transformed_base, field_name, mangled_variant)
}
// Create data access.
// For native backends (arm64/x64): _data is a plain i64 (void pointer) in the SSA struct.
// No union variant sub-field exists, so just use _data directly.
// For C backends: _data is a union, so access _data._variant for the specific member.
is_native_backend := t.pref != unsafe { nil }
&& (t.pref.backend == .arm64 || t.pref.backend == .x64)
data_access := t.synth_selector(transformed_base, '_data', types.Type(types.voidptr_))
variant_access := if is_native_backend {
data_access
} else {
t.synth_selector(data_access, '_${variant_simple}', types.Type(types.voidptr_))
}
// Create: (mangled_variant*)variant_access
cast_expr := ast.CastExpr{
typ: ast.Ident{
name: '${mangled_variant}*'
}
expr: variant_access
}
// Create: cast_expr->field_name (cleanc will handle pointer arrow vs dot)
return t.synth_selector_from_struct(ast.Expr(cast_expr), field_name, mangled_variant)
}
fn (mut t Transformer) transform_array_init_expr(expr ast.ArrayInitExpr) ast.Expr {
// Transform value expressions
mut exprs := []ast.Expr{cap: expr.exprs.len}
for e in expr.exprs {
exprs << t.transform_expr(e)
}
// Check if this is a fixed-size array
mut is_fixed := false
mut array_typ := expr.typ
mut elem_type_expr := ast.empty_expr
// Check for ArrayFixedType or ArrayType (expr.typ is ast.Type sum type)
if expr.typ is ast.Type {
if expr.typ is ast.ArrayFixedType {
is_fixed = true
} else if expr.typ is ast.ArrayType {
elem_type_expr = expr.typ.elem_type
}
}
// For untyped `[]` literals, use checker-inferred type from context (assign/call/return).
if array_typ is ast.EmptyExpr {
if inferred := t.get_expr_type(ast.Expr(expr)) {
inferred_base := t.unwrap_alias_and_pointer_type(inferred)
match inferred_base {
types.Array {
array_typ = t.type_to_ast_type_expr(inferred_base)
elem_type_expr = t.type_to_ast_type_expr(inferred_base.elem_type)
}
types.ArrayFixed {
array_typ = t.type_to_ast_type_expr(inferred_base)
elem_type_expr = t.type_to_ast_type_expr(inferred_base.elem_type)
is_fixed = true
}
else {}
}
}
}
// Also check for [x, y, z]! syntax - parser marks this with len: PostfixExpr{op: .not}
if expr.len is ast.PostfixExpr {
postfix := expr.len as ast.PostfixExpr
if postfix.op == .not && postfix.expr is ast.EmptyExpr {
is_fixed = true
}
}
if is_fixed {
// Fixed-size array: keep as ArrayInitExpr
return ast.ArrayInitExpr{
typ: array_typ
exprs: exprs
init: t.transform_expr(expr.init)
cap: if expr.cap !is ast.EmptyExpr { t.transform_expr(expr.cap) } else { expr.cap }
len: if expr.len !is ast.EmptyExpr { t.transform_expr(expr.len) } else { expr.len }
pos: expr.pos
}
}
// Dynamic array: transform to builtin__new_array_from_c_array_noscan(len, cap, sizeof(elem), values)
arr_len := exprs.len
// Handle empty dynamic arrays: lower to __new_array_with_default_noscan(len, cap, sizeof(elem), init)
if arr_len == 0 {
sizeof_expr := if elem_type_expr !is ast.EmptyExpr {
elem_type_expr
} else {
ast.Expr(ast.Ident{
name: 'int'
})
}
len_expr := ast.Expr(if expr.len !is ast.EmptyExpr {
t.transform_expr(expr.len)
} else {
ast.Expr(ast.BasicLiteral{
kind: .number
value: '0'
})
})
cap_expr := ast.Expr(if expr.cap !is ast.EmptyExpr {
t.transform_expr(expr.cap)
} else {
ast.Expr(ast.BasicLiteral{
kind: .number
value: '0'
})
})
init_expr := ast.Expr(if expr.init !is ast.EmptyExpr {
t.transform_expr(expr.init)
} else {
ast.Expr(ast.Ident{
name: 'nil'
})
})
// If init expression uses `index`, expand to a for-loop that assigns each element.
if expr.init !is ast.EmptyExpr && t.expr_contains_ident_named(init_expr, 'index') {
return t.expand_array_init_with_index(len_expr, cap_expr, sizeof_expr, init_expr,
expr.pos)
}
return ast.CallExpr{
lhs: ast.Ident{
name: '__new_array_with_default_noscan'
}
args: [
len_expr,
cap_expr,
ast.Expr(ast.KeywordOperator{
op: .key_sizeof
exprs: [sizeof_expr]
}),
init_expr,
]
pos: expr.pos
}
}
// Determine element type name and sizeof argument
// First, try to get the array type from the type checker's annotations
mut elem_type_name := 'int'
mut elem_type_expr_resolved := elem_type_expr
if elem_type_expr_resolved is ast.EmptyExpr && exprs.len > 0 {
if arr_type := t.env.get_expr_type(expr.pos.id) {
match arr_type {
types.Array {
tn := t.type_to_c_name(arr_type.elem_type)
if tn != '' {
elem_type_name = tn
elem_type_expr_resolved = ast.Expr(ast.Ident{
name: tn
})
}
}
types.ArrayFixed {
tn := t.type_to_c_name(arr_type.elem_type)
if tn != '' {
elem_type_name = tn
elem_type_expr_resolved = ast.Expr(ast.Ident{
name: tn
})
}
}
else {}
}
}
// If env lookup failed, try getting element type from the ORIGINAL (untransformed)
// first expression, which preserves CastExpr and other type-annotated nodes
if elem_type_expr_resolved is ast.EmptyExpr {
orig_first := expr.exprs[0]
if elem_type := t.get_expr_type(orig_first) {
tn := t.type_to_c_name(elem_type)
if tn != '' {
elem_type_name = tn
elem_type_expr_resolved = ast.Expr(ast.Ident{
name: tn
})
}
} else {
}
// If still not resolved, check if first expr is a CallExpr and look up its return type
if elem_type_expr_resolved is ast.EmptyExpr {
first := exprs[0]
if first is ast.CallExpr || first is ast.CallOrCastExpr {
if ret_type := t.get_method_return_type(first) {
tn := t.type_to_c_name(ret_type)
if tn != '' {
elem_type_name = tn
elem_type_expr_resolved = ast.Expr(ast.Ident{
name: tn
})
}
} else if first is ast.CallExpr {
// Try looking up by function name for plain function calls
fn_name := if first.lhs is ast.Ident {
first.lhs.name
} else {
''
}
if fn_name != '' {
if ret_type2 := t.get_fn_return_type(fn_name) {
tn := t.type_to_c_name(ret_type2)
if tn != '' {
elem_type_name = tn
elem_type_expr_resolved = ast.Expr(ast.Ident{
name: tn
})
}
}
}
}
}
}
}
}
sizeof_arg := if elem_type_expr_resolved !is ast.EmptyExpr {
elem_type_name = t.expr_to_type_name(elem_type_expr_resolved)
elem_type_expr_resolved
} else if exprs.len > 0 {
// Infer from first element
first := exprs[0]
if first is ast.BasicLiteral {
if first.kind == .number {
if first.value.contains('.') || first.value.contains('e')
|| first.value.contains('E') {
elem_type_name = 'f64'
} else {
elem_type_name = 'int'
}
} else if first.kind == .string {
elem_type_name = 'string'
}
ast.Expr(ast.Ident{
name: elem_type_name
})
} else if first is ast.StringLiteral {
elem_type_name = 'string'
ast.Expr(ast.Ident{
name: 'string'
})
} else if first is ast.SelectorExpr {
// For enum values like .trim_left, use int for sizeof
// Try to get actual enum type from environment
if enum_type := t.get_expr_type(first) {
type_name := t.type_to_c_name(enum_type)
if type_name != '' {
elem_type_name = type_name
ast.Expr(ast.Ident{
name: type_name
})
} else {
elem_type_name = 'int'
ast.Expr(ast.Ident{
name: 'int'
})
}
} else {
elem_type_name = 'int'
ast.Expr(ast.Ident{
name: 'int'
})
}
} else if first is ast.Ident {
// Try to get type from scope
var_type := t.get_var_type_name(first.name)
if var_type != '' {
elem_type_name = var_type
ast.Expr(ast.Ident{
name: var_type
})
} else {
// Default: use int
ast.Expr(ast.Ident{
name: 'int'
})
}
} else if first is ast.CallOrCastExpr {
// Handle cast expressions like u8(`0`) - infer element type from cast type
if first.lhs is ast.Ident {
cast_type := first.lhs.name
// Check if this is a primitive type cast
if cast_type in ['u8', 'i8', 'u16', 'i16', 'u32', 'i32', 'u64', 'i64', 'f32', 'f64',
'int', 'bool', 'byte', 'rune', 'voidptr', 'charptr', 'byteptr', 'usize', 'isize',
'string'] {
elem_type_name = cast_type
ast.Expr(ast.Ident{
name: cast_type
})
} else {
// Could be a struct cast - use the type name
elem_type_name = cast_type
ast.Expr(ast.Ident{
name: cast_type
})
}
} else {
// Default: use int
ast.Expr(ast.Ident{
name: 'int'
})
}
} else if first is ast.CastExpr {
// Handle explicit CastExpr nodes
elem_type_name = t.expr_to_type_name(first.typ)
ast.Expr(first.typ)
} else if first is ast.IndexExpr {
// Handle index expressions like s[i] - try to infer element type from the indexed container
// Also handle slice expressions like s[..i] which become IndexExpr with RangeExpr
// Extract first.lhs to avoid double smartcast in if-guard expansions
first_lhs := first.lhs
mut idx_sizeof := ast.Expr(ast.Ident{
name: 'int'
})
if first.expr is ast.RangeExpr {
// Slicing: s[a..b] returns the same type as s
if expr_type := t.get_expr_type(first_lhs) {
type_name := t.type_to_c_name(expr_type)
if type_name != '' {
elem_type_name = type_name
idx_sizeof = ast.Expr(ast.Ident{
name: type_name
})
}
}
} else if expr_type := t.get_expr_type(first_lhs) {
type_name := t.type_to_c_name(expr_type)
if type_name == 'string' {
// String indexing returns u8
elem_type_name = 'u8'
idx_sizeof = ast.Expr(ast.Ident{
name: 'u8'
})
} else if type_name.starts_with('Array_') {
// Array indexing returns element type
arr_elem := type_name[6..] // Remove 'Array_' prefix
elem_type_name = arr_elem
idx_sizeof = ast.Expr(ast.Ident{
name: arr_elem
})
}
}
idx_sizeof
} else if first is ast.CallExpr {
// Handle function calls - try to infer return type
if expr_type := t.get_expr_type(first) {
type_name := t.type_to_c_name(expr_type)
if type_name != '' {
elem_type_name = type_name
ast.Expr(ast.Ident{
name: type_name
})
} else {
ast.Expr(ast.Ident{
name: 'int'
})
}
} else {
// Try to infer from function name for common patterns
mut fn_name := ''
if first.lhs is ast.Ident {
fn_name = first.lhs.name
} else if first.lhs is ast.SelectorExpr {
fn_name = first.lhs.rhs.name
}
// Dynamic array construction functions return 'array' type
if fn_name in ['builtin__new_array_from_c_array_noscan',
'builtin__new_array_from_c_array', '__new_array_with_default_noscan',
'new_array_from_c_array'] {
elem_type_name = 'array'
ast.Expr(ast.Ident{
name: 'array'
})
} else if fn_name in ['substr', 'substr_unsafe', 'trim', 'trim_left', 'trim_right',
'to_upper', 'to_lower', 'replace', 'reverse', 'clone', 'repeat'] {
// String methods that return string
elem_type_name = 'string'
ast.Expr(ast.Ident{
name: 'string'
})
} else {
ast.Expr(ast.Ident{
name: 'int'
})
}
}
} else if first is ast.InitExpr {
// Struct literal - get the type name from the struct type
init_type_name := t.expr_to_type_name(first.typ)
if init_type_name != '' {
elem_type_name = init_type_name
ast.Expr(ast.Ident{
name: init_type_name
})
} else {
ast.Expr(ast.Ident{
name: 'int'
})
}
} else {
// Default: use int
ast.Expr(ast.Ident{
name: 'int'
})
}
} else {
ast.Expr(ast.Ident{
name: 'int'
})
}
// Create proper array type for the inner ArrayInitExpr
inner_array_typ := ast.Type(ast.ArrayType{
elem_type: ast.Ident{
name: elem_type_name
}
})
return ast.CallExpr{
lhs: ast.Ident{
name: 'builtin__new_array_from_c_array_noscan'
}
args: [
ast.Expr(ast.BasicLiteral{
kind: .number
value: '${arr_len}'
}),
ast.Expr(ast.BasicLiteral{
kind: .number
value: '${arr_len}'
}),
ast.Expr(ast.KeywordOperator{
op: .key_sizeof
exprs: [sizeof_arg]
}),
ast.Expr(ast.ArrayInitExpr{
typ: ast.Expr(inner_array_typ)
exprs: exprs
}),
]
pos: expr.pos
}
}
fn (mut t Transformer) transform_map_init_expr(expr ast.MapInitExpr) ast.Expr {
// Determine key/value types from the explicit map type when available.
mut key_type_expr := ast.Expr(ast.Ident{
name: 'int'
})
mut val_type_expr := ast.Expr(ast.Ident{
name: 'int'
})
mut key_type_name := 'int'
mut have_explicit_map_type := false
match expr.typ {
ast.Type {
if expr.typ is ast.MapType {
mt := expr.typ as ast.MapType
key_type_expr = mt.key_type
val_type_expr = mt.value_type
key_type_name = t.expr_to_type_name(mt.key_type)
have_explicit_map_type = true
}
}
else {}
}
// Empty map literals `{}` rely on checker-provided expected type.
// Use the inferred map type from the environment when the AST node doesn't carry one.
if !have_explicit_map_type {
if inferred := t.get_expr_type(ast.Expr(expr)) {
if inferred_map := t.unwrap_map_type(inferred) {
key_type_expr = t.type_to_ast_type_expr(inferred_map.key_type)
val_type_expr = t.type_to_ast_type_expr(inferred_map.value_type)
key_type_name = t.type_to_c_name(inferred_map.key_type)
}
}
}
// Transform key and value expressions (if any).
mut keys := []ast.Expr{cap: expr.keys.len}
mut vals := []ast.Expr{cap: expr.vals.len}
for k in expr.keys {
keys << t.transform_expr(k)
}
for v in expr.vals {
vals << t.transform_expr(v)
}
// Infer map type from first entry when the checker didn't provide one.
if key_type_name == 'int' && keys.len > 0 {
first_key := keys[0]
first_val := vals[0]
if first_key is ast.BasicLiteral && first_key.kind == .string {
key_type_name = 'string'
key_type_expr = ast.Expr(ast.Ident{
name: 'string'
})
} else if first_key is ast.StringLiteral {
key_type_name = 'string'
key_type_expr = ast.Expr(ast.Ident{
name: 'string'
})
}
if first_val is ast.BasicLiteral && first_val.kind == .string {
val_type_expr = ast.Expr(ast.Ident{
name: 'string'
})
} else if first_val is ast.StringLiteral {
val_type_expr = ast.Expr(ast.Ident{
name: 'string'
})
}
}
hash_fn, eq_fn, clone_fn, free_fn := map_runtime_key_fns_from_type_name(key_type_name)
// Empty map literal `{}`: lower to `new_map(sizeof(K), sizeof(V), &hash, &eq, &clone, &free)`.
if keys.len == 0 {
return ast.CallExpr{
lhs: ast.Ident{
name: 'new_map'
}
args: [
ast.Expr(ast.KeywordOperator{
op: .key_sizeof
exprs: [key_type_expr]
}),
ast.Expr(ast.KeywordOperator{
op: .key_sizeof
exprs: [val_type_expr]
}),
ast.Expr(ast.PrefixExpr{
op: .amp
expr: ast.Ident{
name: hash_fn
}
}),
ast.Expr(ast.PrefixExpr{
op: .amp
expr: ast.Ident{
name: eq_fn
}
}),
ast.Expr(ast.PrefixExpr{
op: .amp
expr: ast.Ident{
name: clone_fn
}
}),
ast.Expr(ast.PrefixExpr{
op: .amp
expr: ast.Ident{
name: free_fn
}
}),
]
pos: expr.pos
}
}
n := keys.len
// Create array types for keys and values.
key_array_typ := ast.Type(ast.ArrayType{
elem_type: key_type_expr
})
val_array_typ := ast.Type(ast.ArrayType{
elem_type: val_type_expr
})
// new_map_init_noscan_value(hash_fn, eq_fn, clone_fn, free_fn, n, key_size, val_size, keys, vals)
return ast.CallExpr{
lhs: ast.Ident{
name: 'new_map_init_noscan_value'
}
args: [
ast.Expr(ast.PrefixExpr{
op: .amp
expr: ast.Ident{
name: hash_fn
}
}),
ast.Expr(ast.PrefixExpr{
op: .amp
expr: ast.Ident{
name: eq_fn
}
}),
ast.Expr(ast.PrefixExpr{
op: .amp
expr: ast.Ident{
name: clone_fn
}
}),
ast.Expr(ast.PrefixExpr{
op: .amp
expr: ast.Ident{
name: free_fn
}
}),
ast.Expr(ast.BasicLiteral{
kind: .number
value: '${n}'
}),
ast.Expr(ast.KeywordOperator{
op: .key_sizeof
exprs: [key_type_expr]
}),
ast.Expr(ast.KeywordOperator{
op: .key_sizeof
exprs: [val_type_expr]
}),
ast.Expr(ast.ArrayInitExpr{
typ: ast.Expr(key_array_typ)
exprs: keys
}),
ast.Expr(ast.ArrayInitExpr{
typ: ast.Expr(val_array_typ)
exprs: vals
}),
]
pos: expr.pos
}
}
fn (mut t Transformer) transform_init_expr(expr ast.InitExpr) ast.Expr {
// Typed empty map init: `map[K]V{}`.
// Lower here so backends do not need to special-case map InitExpr nodes.
if expr.fields.len == 0 {
match expr.typ {
ast.Type {
if expr.typ is ast.MapType {
mt := expr.typ as ast.MapType
key_type_name := t.expr_to_type_name(mt.key_type)
hash_fn, eq_fn, clone_fn, free_fn := map_runtime_key_fns_from_type_name(key_type_name)
return ast.Expr(ast.CallExpr{
lhs: ast.Ident{
name: 'new_map'
}
args: [
ast.Expr(ast.KeywordOperator{
op: .key_sizeof
exprs: [mt.key_type]
}),
ast.Expr(ast.KeywordOperator{
op: .key_sizeof
exprs: [mt.value_type]
}),
ast.Expr(ast.PrefixExpr{
op: .amp
expr: ast.Ident{
name: hash_fn
}
}),
ast.Expr(ast.PrefixExpr{
op: .amp
expr: ast.Ident{
name: eq_fn
}
}),
ast.Expr(ast.PrefixExpr{
op: .amp
expr: ast.Ident{
name: clone_fn
}
}),
ast.Expr(ast.PrefixExpr{
op: .amp
expr: ast.Ident{
name: free_fn
}
}),
]
pos: expr.pos
})
}
}
else {}
}
}
// Get the struct type name for field type lookups
struct_type_name := t.get_init_expr_type_name(expr.typ)
// Transform field values recursively
// Note: ArrayInitExpr is NOT transformed here because cleanc uses field type info
// to determine if it's a fixed-size array (which transformer doesn't have access to)
mut fields := []ast.FieldInit{cap: expr.fields.len}
for field in expr.fields {
// Check if this field is a sum type and needs wrapping
mut field_type_name := t.get_struct_field_type_name(struct_type_name, field.name)
if field_type_name == '' {
// Fallback to direct type lookup from the init expression type.
field_type_name = t.get_init_expr_field_type_name(expr.typ, field.name)
}
if t.is_sum_type(field_type_name) {
// If the value is a variable whose declared type is already this sum type
// (e.g., `expr: ast.Expr` used in `GenericArgOrIndexExpr{expr: expr}`),
// skip wrapping. At the C level, the variable is already a tagged union
// of the correct type, so wrapping would produce invalid C.
if field.value is ast.Ident {
if var_type := t.lookup_var_type(field.value.name) {
if var_type is types.SumType {
var_st_name := types.sum_type_name(var_type)
if var_st_name == field_type_name
|| match_sumtype_variant_name(var_st_name, [field_type_name]) != '' {
// Variable is already the target sum type. Remove any
// smartcast context temporarily so transform_expr returns
// the raw variable (tagged union value) without deref.
if sc_ctx := t.find_smartcast_for_expr(field.value.name) {
removed := t.remove_matching_smartcasts(sc_ctx)
transformed_direct := t.transform_expr(field.value)
t.restore_smartcasts(removed)
fields << ast.FieldInit{
name: field.name
value: transformed_direct
}
} else {
fields << ast.FieldInit{
name: field.name
value: t.transform_expr(field.value)
}
}
continue
}
}
}
}
// This is a sum type field - wrap the value in sum type initialization
if wrapped := t.wrap_sumtype_value(field.value, field_type_name) {
fields << ast.FieldInit{
name: field.name
value: wrapped
}
continue
}
}
transformed_value := if field.value is ast.ArrayInitExpr {
// If the array has len/cap but no literal elements (e.g., []int{len: 4}),
// use the normal transform_expr path which handles __new_array_with_default_noscan
if field.value.exprs.len == 0
&& (field.value.len !is ast.EmptyExpr || field.value.cap !is ast.EmptyExpr) {
t.transform_expr(field.value)
} else {
// Transform array elements with sumtype wrapping if needed.
elem_sumtype := t.get_field_array_elem_sumtype_name(struct_type_name,
field.name)
mut new_exprs := []ast.Expr{cap: field.value.exprs.len}
for e in field.value.exprs {
transformed := t.transform_expr(e)
if elem_sumtype != '' {
if wrapped := t.wrap_sumtype_value_transformed(transformed, elem_sumtype) {
new_exprs << wrapped
continue
}
}
new_exprs << transformed
}
// Set elem type from struct field so
// transform_array_init_with_exprs uses the correct element type.
// This is critical when elements were wrapped in a sum type above,
// as the C array type must match the wrapped (sum type) elements.
mut arr_with_type := field.value
elem_c_name := t.get_field_array_elem_c_name(struct_type_name, field.name)
if elem_c_name != '' {
arr_with_type = ast.ArrayInitExpr{
typ: ast.Expr(ast.Type(ast.ArrayType{
elem_type: ast.Ident{
name: elem_c_name
}
}))
exprs: arr_with_type.exprs
init: arr_with_type.init
cap: arr_with_type.cap
len: arr_with_type.len
pos: arr_with_type.pos
}
}
// Use transform_array_init_with_exprs which handles both fixed and dynamic:
// - Fixed arrays stay as ArrayInitExpr for cleanc
// - Dynamic arrays are lowered to builtin__new_array_from_c_array_noscan
t.transform_array_init_with_exprs(arr_with_type, new_exprs)
}
} else {
t.transform_expr(field.value)
}
final_value := t.deref_init_field_value_if_needed(transformed_value, field_type_name)
fields << ast.FieldInit{
name: field.name
value: final_value
}
}
fields = t.add_missing_struct_field_defaults(struct_type_name, fields)
// Check if this is an error struct literal that needs IError boxing
type_name := t.get_init_expr_type_name(expr.typ)
if t.is_error_type_name(type_name) {
// Transform to IError struct init with explicit boxing
// Generate: IError{ ._object = &ErrorType{...}, ._type_id = __type_id_ErrorType,
// .type_name = IError_WrapperType_type_name_wrapper,
// .msg = IError_WrapperType_msg_wrapper,
// .code = IError_WrapperType_code_wrapper }
c_type_name := t.get_c_type_name(type_name)
// Determine wrapper type - types that embed Error use Error wrappers,
// types with custom msg/code methods use their own wrappers
wrapper_type := t.get_error_wrapper_type(type_name)
// Create &ErrorType{...} - heap-allocated error object
inner_init := ast.InitExpr{
typ: expr.typ
fields: fields
}
heap_alloc := ast.PrefixExpr{
op: .amp
expr: inner_init
}
return ast.InitExpr{
typ: ast.Ident{
name: 'IError'
}
fields: [
ast.FieldInit{
name: '_object'
value: heap_alloc
},
ast.FieldInit{
name: '_type_id'
value: ast.Ident{
name: '__type_id_${c_type_name}'
}
},
ast.FieldInit{
name: 'type_name'
value: ast.Ident{
name: 'IError_${wrapper_type}_type_name_wrapper'
}
},
ast.FieldInit{
name: 'msg'
value: ast.Ident{
name: 'IError_${wrapper_type}_msg_wrapper'
}
},
ast.FieldInit{
name: 'code'
value: ast.Ident{
name: 'IError_${wrapper_type}_code_wrapper'
}
},
]
}
}
return ast.InitExpr{
typ: expr.typ
fields: fields
}
}
fn (t &Transformer) deref_init_field_value_if_needed(value ast.Expr, expected_field_type_name string) ast.Expr {
if expected_field_type_name == '' {
return value
}
// Pointer-typed fields already expect an address.
if expected_field_type_name.starts_with('&') || expected_field_type_name.ends_with('*') {
return value
}
mut expected_base_c := ''
if expected_typ := t.lookup_type(expected_field_type_name) {
if expected_typ is types.Pointer {
return value
}
expected_base := t.unwrap_alias_and_pointer_type(expected_typ)
expected_base_c = t.type_to_c_name(expected_base)