v4 / vlib / v3 / gen / c / cleanc.v
4142 lines · 4003 sloc · 131.68 KB · 1498e02bf64c6e33255fc0d3055b6e72900af9a5
Raw
1module c
2
3import os
4import strings
5import v3.flat
6import v3.types
7
8// FlatGen emits flat gen output used by c.
9pub struct FlatGen {
10mut:
11 sb strings.Builder
12 indent int
13 a &flat.FlatAst = unsafe { nil }
14 used_fns map[string]bool
15 used_fn_names []string
16 test_files map[string]bool
17 str_lits []string
18 str_lit_ids map[string]int
19 global_types map[string]types.Type
20 enum_vals map[string]int
21 defers []flat.NodeId
22 fn_defers []flat.NodeId
23 fn_defer_counts map[int]string
24 defer_capture_names []string
25 defer_capture_types map[string]types.Type
26 interfaces map[string][]string
27 const_vals map[string]flat.NodeId
28 const_modules map[string]string
29 const_init_order []string
30 global_modules map[string]string
31 global_inits map[string]flat.NodeId // qualified global name -> initializer value node
32 global_init_order []string // qualified global names, in declaration order
33 iface_impls map[string][]string // interface name -> implementing concrete type names
34 iface_type_ids map[string]int // "${iface}::${concrete}" -> 1-based type id
35 module_init_fns []string // C names of module-level `init()` fns, in source order
36 module_init_fn_modules map[string]string // C init fn name -> V module name
37 module_imports map[string][]string // module -> imported modules
38 c_directives []CDirective
39 c_flags []string
40 libc_compat_fns map[string]bool
41 tc &types.TypeChecker = unsafe { nil }
42 has_builtins bool
43 has_stdatomic_header bool
44 has_stdatomic_compat_header bool
45 tmp_count int
46 line_start bool
47 field_name_set map[string]bool // every struct field's C name (lazy) — for const/field collision checks
48 modules map[string]string // alias -> full module name
49 fn_ptr_types map[string]string // fn_ptr:ret|params -> typedef name
50 fixed_array_ret_wrappers map[string]bool // bare fixed-array c_type name -> has a return wrapper struct
51 emitted_fixed_array_typedefs map[string]bool // bare fixed-array typedefs already written (shared across passes)
52 fn_decl_param_types map[string][]types.Type
53 fn_decl_ret_types map[string]types.Type // fn decl name (and qualified variants) -> return type
54 struct_decl_infos map[string]StructDeclInfo
55 struct_decl_short_infos map[string]StructDeclInfo
56 runtime_inits []string
57 compiler_vroot string
58 c99_mode bool
59 cur_fn_name string
60 cur_param_names []string
61 cur_param_type_values []types.Type
62 cur_param_types map[string]types.Type
63 cur_fn_ret types.Type = types.Type(types.void_)
64 cur_fn_ret_is_optional bool
65 cur_fn_ret_base types.Type = types.Type(types.void_)
66 // in_return is true only while generating a `return` statement's value, so a bare
67 // generic literal (`return Box{...}`) may adopt `cur_fn_ret`'s concrete instance —
68 // but a literal in a local decl / argument elsewhere in the body does not.
69 in_return bool
70 expected_expr_type types.Type = types.Type(types.void_)
71 expected_enum string
72 needed_optional_types map[string]string
73 emitted_optional_types map[string]bool
74 emitted_fns map[string]bool
75 array_method_cache map[string]string
76 param_types_cache map[string][]types.Type // (name|fallback) -> resolved param types
77 embedded_fields_by_type map[string][]types.StructField // type name -> its embedded fields (usually empty)
78 param_types_by_short map[string][]types.Type // method short-name suffix -> param types (fallback index)
79 spawn_wrapper_names map[string]string
80 spawn_wrapper_defs []string
81 callback_wrapper_names map[string]string
82 callback_wrapper_defs []string
83 parallel_used bool
84}
85
86struct FixedArrayTypedefInfo {
87 arr types.ArrayFixed
88 module string
89}
90
91struct CDirective {
92 module string
93 text string
94 before_import bool
95}
96
97// was_parallel reports whether the last fn codegen actually ran across threads.
98pub fn (g &FlatGen) was_parallel() bool {
99 return g.parallel_used
100}
101
102pub fn (g &FlatGen) c_flags() []string {
103 return g.c_flags.clone()
104}
105
106// set_c99_mode configures whether generated C should support strict C99 builds.
107pub fn (mut g FlatGen) set_c99_mode(enabled bool) {
108 g.c99_mode = enabled
109}
110
111// new creates a FlatGen value for c.
112pub fn FlatGen.new() FlatGen {
113 return FlatGen{
114 sb: strings.new_builder(4096)
115 used_fns: map[string]bool{}
116 test_files: map[string]bool{}
117 str_lit_ids: map[string]int{}
118 global_types: map[string]types.Type{}
119 enum_vals: map[string]int{}
120 interfaces: map[string][]string{}
121 const_vals: map[string]flat.NodeId{}
122 const_modules: map[string]string{}
123 const_init_order: []string{}
124 global_modules: map[string]string{}
125 global_inits: map[string]flat.NodeId{}
126 global_init_order: []string{}
127 iface_impls: map[string][]string{}
128 iface_type_ids: map[string]int{}
129 module_init_fns: []string{}
130 module_init_fn_modules: map[string]string{}
131 module_imports: map[string][]string{}
132 c_directives: []CDirective{}
133 c_flags: []string{}
134 libc_compat_fns: map[string]bool{}
135 modules: map[string]string{}
136 fn_ptr_types: map[string]string{}
137 fixed_array_ret_wrappers: map[string]bool{}
138 emitted_fixed_array_typedefs: map[string]bool{}
139 fn_decl_param_types: map[string][]types.Type{}
140 fn_decl_ret_types: map[string]types.Type{}
141 struct_decl_infos: map[string]StructDeclInfo{}
142 struct_decl_short_infos: map[string]StructDeclInfo{}
143 cur_param_names: []string{}
144 cur_param_type_values: []types.Type{}
145 cur_param_types: map[string]types.Type{}
146 needed_optional_types: map[string]string{}
147 emitted_optional_types: map[string]bool{}
148 emitted_fns: map[string]bool{}
149 array_method_cache: map[string]string{}
150 param_types_cache: map[string][]types.Type{}
151 embedded_fields_by_type: map[string][]types.StructField{}
152 param_types_by_short: map[string][]types.Type{}
153 spawn_wrapper_names: map[string]string{}
154 spawn_wrapper_defs: []string{}
155 callback_wrapper_names: map[string]string{}
156 callback_wrapper_defs: []string{}
157 str_lits: []string{}
158 defers: []flat.NodeId{}
159 fn_defers: []flat.NodeId{}
160 fn_defer_counts: map[int]string{}
161 defer_capture_names: []string{}
162 defer_capture_types: map[string]types.Type{}
163 runtime_inits: []string{}
164 compiler_vroot: ''
165 line_start: true
166 }
167}
168
169// gen supports gen handling for FlatGen.
170pub fn (mut g FlatGen) gen(a &flat.FlatAst) string {
171 tc := types.TypeChecker.new(a)
172 return g.gen_with_used(a, map[string]bool{}, &tc)
173}
174
175// gen_with_used emits with used output for c.
176pub fn (mut g FlatGen) gen_with_used(a &flat.FlatAst, used_fns map[string]bool, tc &types.TypeChecker) string {
177 return g.gen_with_used_options(a, used_fns, tc, false)
178}
179
180pub fn (mut g FlatGen) gen_with_used_test_options(a &flat.FlatAst, used_fns map[string]bool, tc &types.TypeChecker, no_parallel bool, test_files []string) string {
181 g.test_files = map[string]bool{}
182 for file in test_files {
183 g.test_files[file] = true
184 }
185 return g.gen_with_used_options(a, used_fns, tc, no_parallel)
186}
187
188// gen_with_used_options emits with used options output for c.
189pub fn (mut g FlatGen) gen_with_used_options(a &flat.FlatAst, used_fns map[string]bool, tc &types.TypeChecker, no_parallel bool) string {
190 g.a = a
191 g.used_fns = used_fns.clone()
192 g.used_fn_names = []string{}
193 g.str_lits = []string{}
194 g.defers = []flat.NodeId{}
195 g.fn_defers = []flat.NodeId{}
196 g.fn_defer_counts = map[int]string{}
197 g.defer_capture_names = []string{}
198 g.defer_capture_types = map[string]types.Type{}
199 g.runtime_inits = []string{}
200 g.compiler_vroot = ''
201 g.str_lit_ids = map[string]int{}
202 g.global_types = map[string]types.Type{}
203 g.enum_vals = map[string]int{}
204 g.interfaces = map[string][]string{}
205 g.const_vals = map[string]flat.NodeId{}
206 g.const_modules = map[string]string{}
207 g.const_init_order = []string{}
208 g.global_modules = map[string]string{}
209 g.global_inits = map[string]flat.NodeId{}
210 g.global_init_order = []string{}
211 g.iface_impls = map[string][]string{}
212 g.iface_type_ids = map[string]int{}
213 g.module_init_fns = []string{}
214 g.module_init_fn_modules = map[string]string{}
215 g.module_imports = map[string][]string{}
216 g.c_directives = []CDirective{}
217 g.c_flags = []string{}
218 g.libc_compat_fns = map[string]bool{}
219 g.has_stdatomic_header = false
220 g.has_stdatomic_compat_header = false
221 g.modules = map[string]string{}
222 g.fn_ptr_types = map[string]string{}
223 g.fixed_array_ret_wrappers = map[string]bool{}
224 g.emitted_fixed_array_typedefs = map[string]bool{}
225 g.fn_decl_param_types = map[string][]types.Type{}
226 g.fn_decl_ret_types = map[string]types.Type{}
227 g.struct_decl_infos = map[string]StructDeclInfo{}
228 g.struct_decl_short_infos = map[string]StructDeclInfo{}
229 g.cur_param_names = []string{}
230 g.cur_param_type_values = []types.Type{}
231 g.cur_param_types = map[string]types.Type{}
232 g.needed_optional_types = map[string]string{}
233 g.emitted_optional_types = map[string]bool{}
234 g.emitted_fns = map[string]bool{}
235 g.array_method_cache = map[string]string{}
236 g.param_types_cache = map[string][]types.Type{}
237 g.embedded_fields_by_type = map[string][]types.StructField{}
238 g.param_types_by_short = map[string][]types.Type{}
239 g.spawn_wrapper_names = map[string]string{}
240 g.spawn_wrapper_defs = []string{}
241 g.callback_wrapper_names = map[string]string{}
242 g.callback_wrapper_defs = []string{}
243 g.parallel_used = false
244 g.tc = unsafe { tc }
245 if g.tc.a == unsafe { nil } {
246 g.tc.collect(a)
247 }
248 g.has_builtins = g.tc.has_builtins
249 g.collect_gen_info()
250 g.precompute_embedded_fields()
251 g.precompute_param_type_index()
252 g.collect_interface_impls()
253 g.preseed_struct_fn_ptr_types()
254 g.preseed_global_fn_ptr_types()
255 // Decide fixed-array return wrappers before generating function bodies, so
256 // signatures, returns and call sites all agree on the wrapped types.
257 g.populate_fixed_array_ret_wrappers()
258 const_code := g.precompute_consts()
259 orig_sb := g.sb
260 orig_line_start := g.line_start
261 g.sb = strings.new_builder(4096)
262 g.line_start = true
263 g.gen_fns_dispatch(no_parallel)
264 fn_code := g.sb.str()
265 // `.str()` copies out of the builder; free the emptied backing array under -gc none.
266 unsafe { g.sb.free() }
267 g.sb = orig_sb
268 g.line_start = orig_line_start
269 g.preamble()
270 g.enum_decls()
271 g.type_alias_decls()
272 g.type_forward_decls()
273 // Forward-declare multi-return structs before fn-ptr typedefs, which may name a
274 // multi-return as a by-value return type (full bodies come after struct_decls).
275 g.multi_return_forward_decls()
276 // Bare typedefs for primitive-element fixed arrays and wrapper structs for
277 // fixed-array return types, before fn-ptr typedefs (which may name a fixed
278 // array in param or return position) and the function declarations.
279 g.fixed_array_early_typedefs()
280 g.fn_ptr_typedefs()
281 g.struct_decls()
282 g.fixed_array_typedefs()
283 g.builtin_abi_decls()
284 g.multi_return_typedefs()
285 g.optional_typedefs()
286 g.global_decls()
287 g.forward_decls()
288 g.enum_str_forward_decls()
289 g.callback_wrapper_decls()
290 g.spawn_wrapper_decls()
291 g.register_interface_strings()
292 g.string_literals()
293 g.interface_method_stubs()
294 g.enum_str_defs()
295 g.sb.write_string(const_code)
296 // The final builder now owns a copy of the const code.
297 unsafe { const_code.free() }
298 if g.runtime_inits.len > 0 || g.module_init_fns.len > 0 || g.global_inits.len > 0 {
299 g.writeln('void _vinit() {')
300 for ri in g.runtime_inits {
301 g.writeln(ri)
302 }
303 // Module-level init() functions run after const/global initialization.
304 for init_fn in g.ordered_module_init_fns() {
305 g.writeln('\t${init_fn}();')
306 }
307 g.writeln('}')
308 g.writeln('')
309 }
310 g.sb.write_string(fn_code)
311 // The final builder now owns a copy of the function code.
312 unsafe { fn_code.free() }
313 result := g.sb.str()
314 // Keep only the returned C string, not the builder's copied backing array.
315 unsafe { g.sb.free() }
316 return result
317}
318
319// node_kind_id supports node kind id handling for c.
320fn node_kind_id(node flat.Node) int {
321 mut kind_id := node.kind_id
322 if kind_id == 0 && int(node.kind) != 0 {
323 kind_id = int(node.kind)
324 }
325 return kind_id
326}
327
328// collect_gen_info updates collect gen info state for c.
329fn (mut g FlatGen) collect_gen_info() {
330 mut cur_module := ''
331 mut cur_file := ''
332 mut seen_import_in_file := false
333 for node_idx in 0 .. g.a.nodes.len {
334 node := g.a.nodes[node_idx]
335 kind_id := node_kind_id(node)
336 if kind_id == 77 {
337 cur_file = node.value
338 g.note_compiler_source_file(node.value)
339 g.tc.cur_file = cur_file
340 cur_module = ''
341 g.tc.cur_module = cur_module
342 seen_import_in_file = false
343 continue
344 }
345 if kind_id == 73 {
346 cur_module = node.value
347 g.tc.cur_file = cur_file
348 g.tc.cur_module = cur_module
349 continue
350 }
351 if kind_id == 61 {
352 full_name := qualify_name_in_module(cur_module, node.value)
353 mut ptypes := []types.Type{}
354 g.tc.cur_file = cur_file
355 g.tc.cur_module = cur_module
356 for i in 0 .. node.children_count {
357 child := g.a.child_node(&node, i)
358 if node_kind_id(child) == 75 {
359 raw_pt := g.tc.parse_type(child.typ)
360 pt := raw_pt
361 ptypes << raw_pt
362 if pt is types.FnType {
363 ct := g.tc.c_type(raw_pt)
364 g.resolve_fn_ptr_type(ct)
365 }
366 }
367 }
368 ptypes = g.fn_param_types_with_implicit_veb_ctx(node, ptypes)
369 g.register_fn_decl_param_types(node.value, full_name, ptypes)
370 g.register_fn_decl_ret_type(node.value, full_name, node.typ)
371 // Module-level `init()` functions run once at startup. Collect their C
372 // names so _vinit can invoke them (V semantics).
373 if node.value == 'init' && ptypes.len == 0 {
374 init_cname := qualified_fn_name_in_module(cur_module, 'init')
375 if init_cname !in g.module_init_fns {
376 g.module_init_fns << init_cname
377 }
378 g.module_init_fn_modules[init_cname] = cur_module
379 }
380 continue
381 }
382 if g.collect_c_directive(cur_module, node, cur_file, !seen_import_in_file) {
383 continue
384 }
385 if node.kind == .directive && node.value == 'flag' && node.typ.len > 0 {
386 flag := c_flag_arg(node.typ, g.compiler_vroot, cur_file)
387 if flag.len > 0 && flag !in g.c_flags {
388 g.c_flags << flag
389 }
390 continue
391 }
392 if node.kind == .directive && node.value == 'pkgconfig' && node.typ.len > 0 {
393 for flag in c_pkgconfig_flags(node.typ) {
394 if flag.len > 0 && flag !in g.c_flags {
395 g.c_flags << flag
396 }
397 }
398 continue
399 }
400 if kind_id == 62 {
401 full_name := qualify_name_in_module(cur_module, node.value)
402 g.register_struct_decl_info(node.value, full_name, cur_module, node)
403 continue
404 }
405 if kind_id == 64 {
406 g.tc.cur_file = cur_file
407 g.tc.cur_module = cur_module
408 for i in 0 .. node.children_count {
409 f := g.a.child_node(&node, i)
410 if f.value.starts_with('C.') {
411 continue
412 }
413 mut ft := g.tc.parse_type(f.typ)
414 if ft is types.Void && f.children_count > 0 {
415 ft = g.tc.resolve_type(g.a.child(f, 0))
416 }
417 qname := qualify_name_in_module(cur_module, f.value)
418 g.global_types[qname] = ft
419 g.global_modules[f.value] = cur_module
420 g.global_modules[qname] = cur_module
421 if f.children_count > 0 {
422 val_id := g.a.child(f, 0)
423 if int(val_id) >= 0 {
424 g.global_inits[qname] = val_id
425 g.global_init_order << qname
426 }
427 }
428 g.tc.file_scope.insert(f.value, ft)
429 if qname != f.value {
430 g.tc.file_scope.insert(qname, ft)
431 }
432 }
433 continue
434 }
435 if kind_id == 67 {
436 is_flag := node.typ == 'flag'
437 mut val := 0
438 enum_name := qualify_name_in_module(cur_module, node.value)
439 for i in 0 .. node.children_count {
440 f := g.a.child_node(&node, i)
441 if f.children_count > 0 {
442 if enum_val := g.enum_field_expr_value(g.a.child(f, 0)) {
443 val = enum_val
444 }
445 }
446 if is_flag {
447 g.enum_vals['${enum_name}.${f.value}'] = 1 << val
448 val++
449 } else {
450 g.enum_vals['${enum_name}.${f.value}'] = val
451 val++
452 }
453 }
454 continue
455 }
456 if kind_id == 70 {
457 iface_name := qualify_name_in_module(cur_module, node.value)
458 g.interfaces[iface_name] = g.tc.interface_abstract_method_names(iface_name)
459 continue
460 }
461 if kind_id == 65 {
462 for i in 0 .. node.children_count {
463 f := g.a.child_node(&node, i)
464 if node_kind_id(f) == 66 && f.children_count > 0 {
465 qname := g.const_storage_name(cur_module, f.value)
466 g.const_vals[qname] = g.a.child(f, 0)
467 g.const_modules[qname] = cur_module
468 if (cur_module.len == 0 || cur_module == 'main' || cur_module == 'builtin')
469 && f.value !in g.const_vals {
470 g.const_vals[f.value] = g.a.child(f, 0)
471 g.const_modules[f.value] = cur_module
472 }
473 }
474 }
475 continue
476 }
477 if kind_id == 72 {
478 seen_import_in_file = true
479 alias := node.typ.clone()
480 mod_name := node.value.clone()
481 if alias.len > 0 && mod_name.len > 0 {
482 g.modules[alias] = mod_name
483 }
484 if cur_module.len > 0 && mod_name.len > 0 {
485 dep_module := mod_name
486 if cur_module !in g.module_imports {
487 g.module_imports[cur_module] = []string{}
488 }
489 if dep_module !in g.module_imports[cur_module] {
490 g.module_imports[cur_module] << dep_module
491 }
492 }
493 continue
494 }
495 }
496 g.modules['strings'] = 'strings'
497 g.collect_const_init_order_from_files()
498}
499
500fn (mut g FlatGen) collect_c_directive(module_name string, node flat.Node, source_file string, before_import bool) bool {
501 if node.kind != .directive {
502 return false
503 }
504 if node.value in ['include', 'insert'] {
505 if node.typ.len == 0 {
506 return true
507 }
508 include_arg := c_include_arg(node.typ, g.compiler_vroot, source_file)
509 if include_arg.len == 0 {
510 return true
511 }
512 // These helper headers are superseded by the inline compiler helpers emitted in
513 // builtin_abi_decls(); also including them would redefine the helpers.
514 if include_arg.contains('prealloc_atomics.h') || include_arg.contains('filelock_helpers.h') {
515 return true
516 }
517 if is_stdatomic_header(include_arg) {
518 g.has_stdatomic_header = true
519 }
520 if is_stdatomic_compat_header(include_arg) {
521 g.has_stdatomic_compat_header = true
522 }
523 g.add_c_directive(module_name, '#include ${include_arg}', before_import)
524 return true
525 }
526 if node.value in ['define', 'undef', 'ifdef', 'ifndef', 'if', 'elif', 'else', 'endif', 'pragma',
527 'error', 'warning'] {
528 g.add_c_directive(module_name, c_preprocessor_directive_line(node.value, node.typ),
529 before_import)
530 return true
531 }
532 return false
533}
534
535fn is_stdatomic_header(include_arg string) bool {
536 normalized := include_arg.replace('\\', '/')
537 return normalized == '<stdatomic.h>' || normalized == '"stdatomic.h"'
538 || normalized.ends_with('/stdatomic.h"') || is_stdatomic_compat_header(normalized)
539}
540
541fn is_stdatomic_compat_header(include_arg string) bool {
542 normalized := include_arg.replace('\\', '/')
543 return normalized.contains('/thirdparty/stdatomic/') && normalized.ends_with('/atomic.h"')
544}
545
546fn (mut g FlatGen) add_c_directive(module_name string, text string, before_import bool) {
547 if text.len == 0 {
548 return
549 }
550 g.c_directives << CDirective{
551 module: module_name
552 text: text
553 before_import: before_import
554 }
555}
556
557fn c_preprocessor_directive_line(name string, raw string) string {
558 clean := raw.trim_space()
559 if clean.len == 0 {
560 return '#${name}'
561 }
562 return '#${name} ${clean}'
563}
564
565// note_compiler_source_file supports note compiler source file handling for FlatGen.
566fn (mut g FlatGen) note_compiler_source_file(path string) {
567 if g.compiler_vroot.len > 0 || path.len == 0 {
568 return
569 }
570 mut full_path := path
571 if !os.is_abs_path(full_path) {
572 full_path = os.abs_path(full_path)
573 }
574 full_path = os.real_path(full_path)
575 normalized := full_path.replace('\\', '/')
576 suffix := '/cmd/v/v.v'
577 if normalized.ends_with(suffix) {
578 g.compiler_vroot = normalized[..normalized.len - suffix.len]
579 return
580 }
581 vlib_idx := normalized.index('/vlib/') or { return }
582 if vlib_idx > 0 {
583 g.compiler_vroot = normalized[..vlib_idx]
584 }
585}
586
587// collect_const_init_order_from_files converts collect const init order from files data for c.
588fn (mut g FlatGen) collect_const_init_order_from_files() {
589 mut seen := map[string]bool{}
590 g.const_init_order = []string{}
591 for node in g.a.nodes {
592 if node_kind_id(node) != 77 || node.children_count == 0 {
593 continue
594 }
595 mut cur_module := ''
596 for i in 0 .. node.children_count {
597 child := g.a.child_node(&node, i)
598 kind_id := node_kind_id(child)
599 if kind_id == 73 {
600 cur_module = child.value
601 continue
602 }
603 if kind_id != 65 {
604 continue
605 }
606 for j in 0 .. child.children_count {
607 field := g.a.child_node(child, j)
608 if node_kind_id(field) != 66 || field.children_count == 0 {
609 continue
610 }
611 qname := g.const_storage_name(cur_module, field.value)
612 if qname in g.const_vals && !seen[qname] {
613 seen[qname] = true
614 g.const_init_order << qname
615 }
616 }
617 }
618 }
619}
620
621// ordered_module_init_fns supports ordered module init fns handling for FlatGen.
622fn (g &FlatGen) ordered_module_init_fns() []string {
623 mut module_to_init := map[string]string{}
624 for init_fn in g.module_init_fns {
625 mod := g.module_init_fn_modules[init_fn] or { '' }
626 module_to_init[mod] = init_fn
627 }
628 mut result := []string{}
629 mut visiting := map[string]bool{}
630 mut visited := map[string]bool{}
631 for init_fn in g.module_init_fns {
632 mod := g.module_init_fn_modules[init_fn] or { '' }
633 g.visit_module_init(mod, module_to_init, mut visiting, mut visited, mut result)
634 }
635 return result
636}
637
638// visit_module_init updates visit module init state for FlatGen.
639fn (g &FlatGen) visit_module_init(mod string, module_to_init map[string]string, mut visiting map[string]bool, mut visited map[string]bool, mut result []string) {
640 if mod in visited || mod in visiting {
641 return
642 }
643 visiting[mod] = true
644 for dep in g.module_imports[mod] or { []string{} } {
645 g.visit_module_init(dep, module_to_init, mut visiting, mut visited, mut result)
646 }
647 visiting.delete(mod)
648 visited[mod] = true
649 if init_fn := module_to_init[mod] {
650 result << init_fn
651 }
652}
653
654fn (g &FlatGen) ordered_c_directives() []string {
655 mut directives_by_module := map[string][]CDirective{}
656 mut module_order := []string{}
657 for directive in g.c_directives {
658 if directive.module !in directives_by_module {
659 directives_by_module[directive.module] = []CDirective{}
660 module_order << directive.module
661 }
662 directives_by_module[directive.module] << directive
663 }
664 mut result := []string{}
665 mut visiting := map[string]bool{}
666 mut visited := map[string]bool{}
667 for mod in module_order {
668 g.visit_c_directive_module(mod, directives_by_module, mut visiting, mut visited, mut result)
669 }
670 return dedupe_top_level_c_includes(result)
671}
672
673fn (g &FlatGen) visit_c_directive_module(mod string, directives_by_module map[string][]CDirective, mut visiting map[string]bool, mut visited map[string]bool, mut result []string) {
674 if mod in visited || mod in visiting {
675 return
676 }
677 visiting[mod] = true
678 directives := directives_by_module[mod] or { []CDirective{} }
679 for directive in directives {
680 if directive.before_import {
681 result << directive.text
682 }
683 }
684 for dep in g.module_imports[mod] or { []string{} } {
685 if dep in directives_by_module {
686 g.visit_c_directive_module(dep, directives_by_module, mut visiting, mut visited, mut
687 result)
688 }
689 }
690 visiting.delete(mod)
691 visited[mod] = true
692 for directive in directives {
693 if !directive.before_import {
694 result << directive.text
695 }
696 }
697}
698
699fn dedupe_top_level_c_includes(directives []string) []string {
700 mut result := []string{}
701 mut seen_includes := map[string]bool{}
702 mut depth := 0
703 for directive in directives {
704 clean := directive.trim_space()
705 if depth == 0 && c_directive_name(clean) == 'include' {
706 if clean in seen_includes {
707 continue
708 }
709 seen_includes[clean] = true
710 }
711 result << directive
712 name := c_directive_name(clean)
713 if name in ['if', 'ifdef', 'ifndef'] {
714 depth++
715 } else if name == 'endif' && depth > 0 {
716 depth--
717 }
718 }
719 return result
720}
721
722fn c_directive_name(text string) string {
723 if text.len == 0 || text[0] != `#` {
724 return ''
725 }
726 body := text[1..].trim_space()
727 if body.len == 0 {
728 return ''
729 }
730 idx := body.index_u8(` `)
731 if idx < 0 {
732 return body
733 }
734 return body[..idx]
735}
736
737fn c_include_arg(raw string, vroot string, source_file string) string {
738 mut clean := c_directive_arg_for_target(raw.trim_space()) or { return '' }
739 clean = c_resolve_pseudo_paths(clean.trim_space(), vroot, source_file)
740 if clean.len == 0 {
741 return ''
742 }
743 if clean[0] == `<` {
744 end := clean.index_u8(`>`)
745 if end > 0 {
746 return clean[..end + 1]
747 }
748 return clean
749 }
750 if clean[0] == `"` {
751 mut i := 1
752 for i < clean.len {
753 if clean[i] == `"` {
754 return clean[..i + 1]
755 }
756 i++
757 }
758 }
759 hash := clean.index_u8(`#`)
760 if hash > 0 {
761 return clean[..hash].trim_space()
762 }
763 return clean
764}
765
766fn c_flag_arg(raw string, vroot string, source_file string) string {
767 clean := c_directive_arg_for_target(raw.trim_space()) or { return '' }
768 if clean.len == 0 {
769 return ''
770 }
771 resolved := c_resolve_pseudo_paths(clean, vroot, source_file)
772 return c_resolve_relative_flag_paths(resolved, source_file)
773}
774
775// c_resolve_relative_flag_paths rewrites relative path arguments in a `#flag`
776// directive (e.g. `-I ./thirdparty`, or a bare `./foo.c`) to absolute paths,
777// resolved against the directory of the source file that carried the directive.
778// V1 does the same: a project's `#flag` paths are relative to its own module dir,
779// not to the compiler's build/working directory.
780fn c_resolve_relative_flag_paths(flag string, source_file string) string {
781 if source_file.len == 0 || !flag.contains('/') {
782 return flag
783 }
784 base_dir := os.dir(source_file)
785 if base_dir.len == 0 {
786 return flag
787 }
788 mut out := []string{}
789 for tok in flag.fields() {
790 out << c_resolve_flag_path_token(tok, base_dir)
791 }
792 return out.join(' ')
793}
794
795fn c_resolve_flag_path_token(tok string, base_dir string) string {
796 for prefix in ['-I', '-L'] {
797 if tok.starts_with(prefix) && tok.len > prefix.len {
798 path := tok[prefix.len..]
799 if c_flag_path_is_relative(path) {
800 return prefix + os.real_path(os.join_path_single(base_dir, path))
801 }
802 return tok
803 }
804 }
805 if !tok.starts_with('-') && c_flag_path_is_relative(tok) {
806 return os.real_path(os.join_path_single(base_dir, tok))
807 }
808 return tok
809}
810
811fn c_flag_path_is_relative(p string) bool {
812 if p.len == 0 || os.is_abs_path(p) {
813 return false
814 }
815 return p.starts_with('./') || p.starts_with('../') || p.contains('/')
816}
817
818fn c_directive_arg_for_target(raw string) ?string {
819 parts := raw.fields()
820 if parts.len == 0 {
821 return none
822 }
823 if c_flag_has_target_prefix(parts[0]) {
824 if !c_flag_target_enabled(parts[0]) || parts.len < 2 {
825 return none
826 }
827 return parts[1..].join(' ')
828 }
829 return raw
830}
831
832fn c_resolve_pseudo_paths(raw string, vroot string, source_file string) string {
833 mut result := raw
834 if result.contains('@VEXEROOT') && vroot.len > 0 {
835 result = result.replace('@VEXEROOT', vroot)
836 }
837 if result.contains('@VROOT') {
838 result = result.replace('@VROOT', '@VMODROOT')
839 }
840 if result.contains('@VMODROOT') {
841 result = result.replace('@VMODROOT', c_vmod_root_for_file(source_file))
842 }
843 if result.contains('@DIR') {
844 dir := if source_file.len > 0 { os.dir(source_file) } else { os.getwd() }
845 result = result.replace('@DIR', os.real_path(dir))
846 }
847 return result
848}
849
850fn c_vmod_root_for_file(source_file string) string {
851 mut dir := if source_file.len > 0 { os.dir(source_file) } else { os.getwd() }
852 if dir.len == 0 {
853 dir = os.getwd()
854 }
855 for {
856 if os.exists(os.join_path(dir, 'v.mod')) {
857 return os.real_path(dir)
858 }
859 parent := os.dir(dir)
860 if parent == dir || parent.len == 0 {
861 return os.real_path(dir)
862 }
863 dir = parent
864 }
865 return os.real_path(dir)
866}
867
868fn c_pkgconfig_flags(raw string) []string {
869 name := raw.trim_space()
870 if name.len == 0 {
871 return []string{}
872 }
873 // The package name comes straight from source text and is interpolated into a
874 // shell command, so reject anything that is not a plain pkg-config name/flag to
875 // avoid command injection (e.g. `#pkgconfig foo; touch /tmp/pwned`).
876 if !c_pkgconfig_arg_is_safe(name) {
877 return []string{}
878 }
879 result := os.execute('pkg-config --cflags --libs ${name}')
880 if result.exit_code != 0 {
881 return []string{}
882 }
883 return result.output.trim_space().fields()
884}
885
886fn c_pkgconfig_arg_is_safe(raw string) bool {
887 for ch in raw {
888 if (ch >= `a` && ch <= `z`) || (ch >= `A` && ch <= `Z`) || (ch >= `0` && ch <= `9`) {
889 continue
890 }
891 if ch in [` `, `\t`, `_`, `-`, `.`, `+`, `:`, `/`] {
892 continue
893 }
894 return false
895 }
896 return true
897}
898
899fn c_flag_has_target_prefix(target string) bool {
900 return target in ['darwin', 'macos', 'linux', 'windows', 'freebsd', 'openbsd', 'netbsd',
901 'solaris', 'wasm32_emscripten']
902}
903
904fn c_flag_target_enabled(target string) bool {
905 match target {
906 'darwin', 'macos' {
907 $if macos {
908 return true
909 }
910 return false
911 }
912 'linux' {
913 $if linux {
914 return true
915 }
916 return false
917 }
918 'windows' {
919 $if windows {
920 return true
921 }
922 return false
923 }
924 'freebsd' {
925 $if freebsd {
926 return true
927 }
928 return false
929 }
930 'openbsd' {
931 $if openbsd {
932 return true
933 }
934 return false
935 }
936 'netbsd' {
937 $if netbsd {
938 return true
939 }
940 return false
941 }
942 'solaris' {
943 $if solaris {
944 return true
945 }
946 return false
947 }
948 'wasm32_emscripten' {
949 $if wasm32_emscripten {
950 return true
951 }
952 return false
953 }
954 else {
955 return true
956 }
957 }
958}
959
960// register_fn_decl_param_types updates register fn decl param types state for c.
961fn (mut g FlatGen) register_fn_decl_param_types(name string, full_name string, ptypes []types.Type) {
962 if name !in g.fn_decl_param_types {
963 g.fn_decl_param_types[name] = ptypes.clone()
964 }
965 if g.tc.cur_module.len > 0 && g.tc.cur_module != 'main' && g.tc.cur_module != 'builtin' {
966 dotted_name := '${g.tc.cur_module}.${name}'
967 if dotted_name !in g.fn_decl_param_types {
968 g.fn_decl_param_types[dotted_name] = ptypes.clone()
969 }
970 }
971 if full_name !in g.fn_decl_param_types {
972 g.fn_decl_param_types[full_name] = ptypes.clone()
973 }
974}
975
976// register_fn_decl_ret_type indexes a fn decl's return type by its name (and qualified
977// variants), so the return type can be looked up in O(1) instead of scanning all AST
978// nodes per call (see fn_decl_return_type_for_call_name).
979fn (mut g FlatGen) register_fn_decl_ret_type(name string, full_name string, ret_typ string) {
980 rt := g.tc.parse_type(ret_typ)
981 if name !in g.fn_decl_ret_types {
982 g.fn_decl_ret_types[name] = rt
983 }
984 if g.tc.cur_module.len > 0 && g.tc.cur_module != 'main' && g.tc.cur_module != 'builtin' {
985 dotted_name := '${g.tc.cur_module}.${name}'
986 if dotted_name !in g.fn_decl_ret_types {
987 g.fn_decl_ret_types[dotted_name] = rt
988 }
989 }
990 if full_name !in g.fn_decl_ret_types {
991 g.fn_decl_ret_types[full_name] = rt
992 }
993 cname := c_name(name)
994 if cname != name && cname !in g.fn_decl_ret_types {
995 g.fn_decl_ret_types[cname] = rt
996 }
997}
998
999// register_struct_decl_info updates register struct decl info state for c.
1000fn (mut g FlatGen) register_struct_decl_info(name string, full_name string, module_name string, node flat.Node) {
1001 info := StructDeclInfo{
1002 node: node
1003 module: module_name
1004 full_name: full_name
1005 }
1006 g.struct_decl_infos[full_name] = info
1007 if name !in g.struct_decl_short_infos {
1008 g.struct_decl_short_infos[name] = info
1009 }
1010}
1011
1012// enum_value_for_type supports enum value for type handling for FlatGen.
1013fn (g &FlatGen) enum_value_for_type(type_name string, field_name string) ?int {
1014 if type_name.len == 0 || field_name.len == 0 {
1015 return none
1016 }
1017 key := '${type_name}.${field_name}'
1018 if val := g.enum_vals[key] {
1019 return val
1020 }
1021 if !type_name.contains('.') && g.tc.cur_module.len > 0 && g.tc.cur_module != 'main'
1022 && g.tc.cur_module != 'builtin' {
1023 qkey := '${g.tc.cur_module}.${type_name}.${field_name}'
1024 if val := g.enum_vals[qkey] {
1025 return val
1026 }
1027 }
1028 if !type_name.contains('.') {
1029 mut found := 0
1030 mut ok := false
1031 for ename, val in g.enum_vals {
1032 if !ename.ends_with('.${type_name}.${field_name}') {
1033 continue
1034 }
1035 if ok {
1036 return none
1037 }
1038 found = val
1039 ok = true
1040 }
1041 if ok {
1042 return found
1043 }
1044 }
1045 return none
1046}
1047
1048fn (g &FlatGen) enum_selector_base_name(name string) ?string {
1049 if name in g.tc.enum_names || name in g.tc.flag_enums {
1050 return name
1051 }
1052 qname := g.tc.qualify_name(name)
1053 if qname in g.tc.enum_names || qname in g.tc.flag_enums {
1054 return qname
1055 }
1056 if name.contains('.') || g.tc.cur_file.len == 0 {
1057 return none
1058 }
1059 candidates := g.tc.file_selective_imports['${g.tc.cur_file}\n${name}'] or { return none }
1060 for candidate in candidates {
1061 if candidate in g.tc.enum_names || candidate in g.tc.flag_enums {
1062 return candidate
1063 }
1064 }
1065 return none
1066}
1067
1068// expr_to_string converts expr to string data for c.
1069fn (mut g FlatGen) expr_to_string(id flat.NodeId) string {
1070 orig := g.sb
1071 orig_line_start := g.line_start
1072 g.sb = strings.new_builder(64)
1073 g.line_start = true
1074 g.gen_expr(id)
1075 result := g.sb.str()
1076 g.sb = orig
1077 g.line_start = orig_line_start
1078 return result
1079}
1080
1081// interface_value_to_string captures, as a string, the boxed interface value the direct return
1082// path emits (`(Iface){._typ = N, ._object = ...}`) — so a deferred return can save it into a
1083// temp without dropping `_typ`/`_object`. Mirrors that path: box a concrete value, else (already
1084// boxed by the transform) emit it as-is.
1085fn (mut g FlatGen) interface_value_to_string(id flat.NodeId, expected types.Type) string {
1086 orig := g.sb
1087 orig_line_start := g.line_start
1088 g.sb = strings.new_builder(64)
1089 // Box mid-statement (no leading indent), matching the direct return path.
1090 g.line_start = false
1091 if !g.gen_interface_value_expr(id, expected) {
1092 g.gen_expr(id)
1093 }
1094 result := g.sb.str()
1095 g.sb = orig
1096 g.line_start = orig_line_start
1097 return result
1098}
1099
1100// fixed_array_copy_source_string captures gen_fixed_array_copy_source as a string, so a deferred
1101// optional/fixed-array return can embed the memcpy source when saving the value into a temp.
1102fn (mut g FlatGen) fixed_array_copy_source_string(value_id flat.NodeId, field_type types.Type) string {
1103 orig := g.sb
1104 orig_line_start := g.line_start
1105 g.sb = strings.new_builder(64)
1106 // Emit mid-statement (no leading indent), matching the direct return path.
1107 g.line_start = false
1108 g.gen_fixed_array_copy_source(value_id, field_type)
1109 result := g.sb.str()
1110 g.sb = orig
1111 g.line_start = orig_line_start
1112 return result
1113}
1114
1115// expr_to_string_with_expected_type converts expr to string with expected type data for c.
1116fn (mut g FlatGen) expr_to_string_with_expected_type(id flat.NodeId, expected types.Type) string {
1117 orig := g.sb
1118 orig_line_start := g.line_start
1119 g.sb = strings.new_builder(64)
1120 g.line_start = true
1121 g.gen_expr_with_expected_type(id, expected)
1122 result := g.sb.str()
1123 g.sb = orig
1124 g.line_start = orig_line_start
1125 return result
1126}
1127
1128fn (mut g FlatGen) gen_amp_c_string_literal(id flat.NodeId, node flat.Node) bool {
1129 if node.kind == .char_literal && node.value.starts_with('c:') {
1130 g.gen_expr(id)
1131 return true
1132 }
1133 if node.kind != .char_literal && node.kind != .string_literal {
1134 return false
1135 }
1136 expr := g.expr_to_string(id)
1137 if expr.len >= 2 && expr[0] == `"` && expr[expr.len - 1] == `"` {
1138 g.write(expr)
1139 return true
1140 }
1141 return false
1142}
1143
1144// gen_expr_with_expected_type emits expr with expected type output for c.
1145fn (mut g FlatGen) gen_expr_with_expected_type(id flat.NodeId, expected types.Type) {
1146 old_expected := g.expected_expr_type
1147 old_expected_enum := g.expected_enum
1148 g.expected_expr_type = expected
1149 if expected is types.Enum {
1150 g.expected_enum = expected.name
1151 }
1152 node := g.a.nodes[int(id)]
1153 if node.kind == .dump_expr {
1154 if node.children_count > 0 {
1155 g.gen_expr_with_expected_type(g.a.child(&node, 0), expected)
1156 } else {
1157 g.write('0')
1158 }
1159 g.expected_expr_type = old_expected
1160 g.expected_enum = old_expected_enum
1161 return
1162 }
1163 mut actual := g.usable_expr_type(id)
1164 if node.kind == .ident {
1165 if param_type := g.current_param_type(node.value) {
1166 actual = param_type
1167 }
1168 }
1169 if _ := fn_type_from(expected) {
1170 if g.gen_callback_fn_value_for_expected_type(id, expected) {
1171 g.expected_expr_type = old_expected
1172 g.expected_enum = old_expected_enum
1173 return
1174 }
1175 if call_name := g.callback_direct_fn_value_name(id, expected) {
1176 g.write(g.callback_c_fn_name(call_name))
1177 g.expected_expr_type = old_expected
1178 g.expected_enum = old_expected_enum
1179 return
1180 }
1181 }
1182 if expected is types.Array && node.kind == .array_literal {
1183 elem_type := if node.children_count > 0 {
1184 g.tc.resolve_type(g.a.child(&node, 0))
1185 } else {
1186 expected.elem_type
1187 }
1188 g.gen_array_literal_value(node, elem_type)
1189 g.expected_expr_type = old_expected
1190 g.expected_enum = old_expected_enum
1191 return
1192 }
1193 if expected !is types.Pointer && expected !is types.Void && actual is types.Pointer
1194 && g.type_names_match(actual.base_type, expected) {
1195 needs_paren := node.kind !in [.ident, .selector, .call, .index]
1196 g.write('*')
1197 if needs_paren {
1198 g.write('(')
1199 }
1200 g.gen_expr(id)
1201 if needs_paren {
1202 g.write(')')
1203 }
1204 g.expected_expr_type = old_expected
1205 g.expected_enum = old_expected_enum
1206 return
1207 }
1208 if g.gen_interface_value_expr(id, expected) {
1209 g.expected_expr_type = old_expected
1210 g.expected_enum = old_expected_enum
1211 return
1212 }
1213 if g.gen_sum_value_expr(id, expected) {
1214 g.expected_expr_type = old_expected
1215 g.expected_enum = old_expected_enum
1216 return
1217 }
1218 g.gen_expr(id)
1219 g.expected_expr_type = old_expected
1220 g.expected_enum = old_expected_enum
1221}
1222
1223// gen_sum_value_expr emits sum value expr output for c.
1224fn (mut g FlatGen) gen_sum_value_expr(id flat.NodeId, expected types.Type) bool {
1225 sum_type0 := if expected is types.Alias { expected.base_type } else { expected }
1226 if sum_type0 !is types.SumType {
1227 return false
1228 }
1229 sum_type := sum_type0 as types.SumType
1230 raw_actual0 := g.sum_cast_actual_type(id)
1231 raw_actual_type := if raw_actual0 is types.Alias { raw_actual0.base_type } else { raw_actual0 }
1232 if raw_actual_type is types.SumType {
1233 return false
1234 }
1235 if declared := g.selector_declared_type(id) {
1236 declared0 := if declared is types.Alias { declared.base_type } else { declared }
1237 if declared0 is types.SumType && g.type_names_match(declared0, sum_type0) {
1238 return false
1239 }
1240 }
1241 actual0 := raw_actual0
1242 actual_type := if actual0 is types.Alias { actual0.base_type } else { actual0 }
1243 if actual_type is types.SumType {
1244 return false
1245 }
1246 sum_name := g.resolve_sum_name(sum_type.name)
1247 variant := g.resolve_variant(sum_name, actual_type.name())
1248 variants := g.tc.sum_types[sum_name] or { return false }
1249 if variant !in variants {
1250 return false
1251 }
1252 ct := g.tc.c_type(sum_type0)
1253 idx := g.sum_type_index(sum_name, variant)
1254 field := g.sum_field_name(variant)
1255 if g.variant_references_sum(variant, sum_name) {
1256 inner_ct := g.tc.c_type(g.tc.parse_type(variant))
1257 g.write('(${ct}){.typ = ${idx}, .${field} = (${inner_ct}*)memdup((${inner_ct}[]){')
1258 g.gen_expr(id)
1259 g.write('}, sizeof(${inner_ct}))}')
1260 return true
1261 }
1262 g.write('(${ct}){.typ = ${idx}, .${field} = ')
1263 g.gen_expr(id)
1264 g.write('}')
1265 return true
1266}
1267
1268fn (g &FlatGen) sum_cast_actual_type(id flat.NodeId) types.Type {
1269 mut actual_type := g.tc.resolve_type(id)
1270 if int(id) < 0 || int(id) >= g.a.nodes.len {
1271 return actual_type
1272 }
1273 node := g.a.nodes[int(id)]
1274 if node.kind == .ident {
1275 if param_type := g.current_param_type(node.value) {
1276 return param_type
1277 }
1278 if param_type := g.cur_param_types[node.value] {
1279 return param_type
1280 }
1281 }
1282 return actual_type
1283}
1284
1285// gen_sum_cast_expr emits sum cast expr output for c.
1286fn (mut g FlatGen) gen_sum_cast_expr(target_type types.SumType, inner_id flat.NodeId) {
1287 inner := g.a.nodes[int(inner_id)]
1288 actual_type := g.sum_cast_actual_type(inner_id)
1289 actual_clean := types.unwrap_pointer(actual_type)
1290 variant_name0 := if inner.kind == .struct_init {
1291 inner.value
1292 } else {
1293 actual_clean.name()
1294 }
1295 variant_name := g.resolve_variant(target_type.name, variant_name0)
1296 idx := g.sum_type_index(target_type.name, variant_name)
1297 field := g.sum_field_name(variant_name)
1298 ct := g.tc.c_type(target_type)
1299 variant_type := g.tc.parse_type(variant_name)
1300 variant_is_pointer_arg := actual_type is types.Pointer
1301 && g.type_names_match(actual_type.base_type, variant_type)
1302 if g.variant_references_sum(variant_name, target_type.name) {
1303 inner_ct := g.tc.c_type(variant_type)
1304 if variant_is_pointer_arg {
1305 g.write('(${ct}){.typ = ${idx}, .${field} = ')
1306 if g.pointer_variant_arg_needs_heap_copy(inner) {
1307 g.write('(${inner_ct}*)memdup(')
1308 g.gen_expr(inner_id)
1309 g.write(', sizeof(${inner_ct}))')
1310 } else {
1311 g.gen_expr(inner_id)
1312 }
1313 g.write('}')
1314 } else if inner.kind == .struct_init
1315 && g.resolve_sum_name(inner.value) == g.resolve_sum_name(target_type.name) {
1316 g.write('(${ct}){')
1317 for si in 0 .. inner.children_count {
1318 sf := g.a.child_node(&inner, si)
1319 if si > 0 {
1320 g.write(', ')
1321 }
1322 g.write('.${c_name(sf.value)} = ')
1323 g.gen_lowered_sum_field_value(target_type.name, sf)
1324 }
1325 g.write('}')
1326 } else if inner.kind == .struct_init {
1327 g.write('(${ct}){.typ = ${idx}, .${field} = (${inner_ct}*)memdup(&(${inner_ct}){')
1328 for si in 0 .. inner.children_count {
1329 sf := g.a.child_node(&inner, si)
1330 if si > 0 {
1331 g.write(', ')
1332 }
1333 g.write('.${c_name(sf.value)} = ')
1334 g.gen_expr(g.a.child(sf, 0))
1335 }
1336 g.write('}, sizeof(${inner_ct}))}')
1337 } else {
1338 g.write('(${ct}){.typ = ${idx}, .${field} = (${inner_ct}*)memdup((${inner_ct}[]){')
1339 g.gen_expr(inner_id)
1340 g.write('}, sizeof(${inner_ct}))}')
1341 }
1342 } else {
1343 g.write('(${ct}){.typ = ${idx}, .${field} = ')
1344 if variant_is_pointer_arg {
1345 g.write('*')
1346 }
1347 g.gen_expr(inner_id)
1348 g.write('}')
1349 }
1350}
1351
1352// pointer_variant_arg_needs_heap_copy supports pointer_variant_arg_needs_heap_copy handling in c.
1353fn (g &FlatGen) pointer_variant_arg_needs_heap_copy(node flat.Node) bool {
1354 if node.kind != .prefix || node.op != .amp || node.children_count == 0 {
1355 return false
1356 }
1357 child_id := g.a.child(&node, 0)
1358 child := g.a.nodes[int(child_id)]
1359 if child.kind != .ident {
1360 return false
1361 }
1362 if _ := g.current_param_type(child.value) {
1363 return true
1364 }
1365 if child.value in g.cur_param_types {
1366 return true
1367 }
1368 if _ := g.tc.cur_scope.lookup(child.value) {
1369 return true
1370 }
1371 return false
1372}
1373
1374// selector_declared_type supports selector declared type handling for FlatGen.
1375fn (g &FlatGen) selector_declared_type(id flat.NodeId) ?types.Type {
1376 if int(id) < 0 || int(id) >= g.a.nodes.len {
1377 return none
1378 }
1379 node := g.a.nodes[int(id)]
1380 if node.kind != .selector || node.children_count == 0 {
1381 return none
1382 }
1383 base_id := g.a.child(&node, 0)
1384 base_type0 := types.unwrap_pointer(g.tc.resolve_type(base_id))
1385 base_type := if base_type0 is types.Alias { base_type0.base_type } else { base_type0 }
1386 if base_type is types.Struct {
1387 return g.struct_field_type(base_type.name, node.value)
1388 }
1389 return none
1390}
1391
1392fn (g &FlatGen) c_typedef_cast_call_name(node flat.Node) string {
1393 if node.kind != .call || node.children_count == 0 {
1394 return ''
1395 }
1396 callee := g.a.child_node(&node, 0)
1397 match callee.kind {
1398 .ident {
1399 if callee.value.contains('__') {
1400 return callee.value
1401 }
1402 }
1403 .selector {
1404 if callee.children_count > 0 {
1405 base := g.a.child_node(callee, 0)
1406 if base.kind == .ident && base.value == 'C' {
1407 return callee.value
1408 }
1409 }
1410 }
1411 else {}
1412 }
1413
1414 return ''
1415}
1416
1417// gen_expr_with_possible_enum_type emits expr with possible enum type output for c.
1418fn (mut g FlatGen) gen_expr_with_possible_enum_type(id flat.NodeId, expected types.Type) {
1419 if expected is types.Enum {
1420 g.gen_expr_with_expected_type(id, expected)
1421 return
1422 }
1423 g.gen_expr(id)
1424}
1425
1426fn (g &FlatGen) expected_expr_is_optional_struct() bool {
1427 if g.expected_expr_type is types.Struct {
1428 return g.expected_expr_type.name.starts_with('Optional')
1429 }
1430 return false
1431}
1432
1433fn (mut g FlatGen) type_name_c_type(type_name string) string {
1434 if _ := g.tc.cur_scope.lookup(type_name) {
1435 return c_name(type_name)
1436 }
1437 t := g.tc.parse_type(type_name)
1438 return g.tc.c_type(t)
1439}
1440
1441fn (mut g FlatGen) sizeof_target(value string) string {
1442 if value.contains('.') {
1443 parts := value.split('.')
1444 if parts.len > 1 {
1445 if g.cur_scope_has_local_name(parts[0]) {
1446 return sizeof_selector_target(parts[0], parts[1..])
1447 }
1448 if global := g.sizeof_global_selector_base(parts[0]) {
1449 return sizeof_selector_target(global, parts[1..])
1450 }
1451 }
1452 }
1453 return g.type_name_c_type(value)
1454}
1455
1456fn sizeof_selector_target(base string, fields []string) string {
1457 mut expr := c_name(base)
1458 for field in fields {
1459 expr += '.${c_field_name(field)}'
1460 }
1461 return expr
1462}
1463
1464fn (g &FlatGen) cur_scope_has_local_name(name string) bool {
1465 mut scope := g.tc.cur_scope
1466 for scope != unsafe { nil } && scope != g.tc.file_scope {
1467 for existing in scope.names {
1468 if existing == name {
1469 return true
1470 }
1471 }
1472 scope = scope.parent
1473 }
1474 return false
1475}
1476
1477fn (g &FlatGen) sizeof_global_selector_base(name string) ?string {
1478 if name.len == 0 || name.contains('.') {
1479 return none
1480 }
1481 current_qname := qualify_name_in_module(g.tc.cur_module, name)
1482 if current_qname in g.global_types {
1483 return current_qname
1484 }
1485 if mod := g.global_modules[name] {
1486 if mod.len == 0 || mod == 'main' || mod == 'builtin' || mod == g.tc.cur_module {
1487 return if mod.len > 0 && mod != 'main' && mod != 'builtin' {
1488 '${mod}.${name}'
1489 } else {
1490 name
1491 }
1492 }
1493 }
1494 return none
1495}
1496
1497// optional_none_type supports optional none type handling for FlatGen.
1498fn (mut g FlatGen) optional_none_type(id flat.NodeId) types.Type {
1499 if g.expected_expr_type is types.OptionType || g.expected_expr_type is types.ResultType {
1500 return g.expected_expr_type
1501 }
1502 if typ := g.tc.expr_type(id) {
1503 if typ is types.OptionType || typ is types.ResultType {
1504 return typ
1505 }
1506 }
1507 if g.cur_fn_ret_is_optional {
1508 return g.cur_fn_ret
1509 }
1510 return types.Type(types.OptionType{
1511 base_type: types.Type(types.void_)
1512 })
1513}
1514
1515// array_index_info supports array index info handling for c.
1516fn array_index_info(t types.Type) (bool, bool, types.Array) {
1517 if t is types.Array {
1518 return true, false, t
1519 }
1520 if t is types.Alias {
1521 base := t.base_type
1522 if base is types.Array {
1523 return true, false, base
1524 }
1525 }
1526 if t is types.Pointer {
1527 base := t.base_type
1528 if base is types.Array {
1529 return true, true, base
1530 }
1531 if base is types.Alias {
1532 alias_base := base.base_type
1533 if alias_base is types.Array {
1534 return true, true, alias_base
1535 }
1536 }
1537 }
1538 return false, false, types.Array{}
1539}
1540
1541// valid_node_id supports valid node id handling for FlatGen.
1542fn (g &FlatGen) valid_node_id(id flat.NodeId) bool {
1543 return g.a != unsafe { nil } && int(id) >= 0 && int(id) < g.a.nodes.len
1544}
1545
1546// const_storage_name supports const storage name handling for FlatGen.
1547fn (g &FlatGen) const_storage_name(module_name string, name string) string {
1548 if module_name.len > 0 && module_name != 'main' && module_name != 'builtin'
1549 && !name.contains('.') {
1550 return '${module_name}.${name}'
1551 }
1552 return name
1553}
1554
1555// const_primary_name supports const primary name handling for FlatGen.
1556fn (g &FlatGen) const_primary_name(name string) string {
1557 mod := if name in g.const_modules { g.const_modules[name] } else { '' }
1558 qname := g.const_storage_name(mod, name)
1559 if qname != name && qname in g.const_vals {
1560 return qname
1561 }
1562 return name
1563}
1564
1565// is_const_alias_name reports whether is const alias name applies in c.
1566fn (g &FlatGen) is_const_alias_name(name string) bool {
1567 return g.const_primary_name(name) != name
1568}
1569
1570// const_ref_name supports const ref name handling for FlatGen.
1571fn (g &FlatGen) const_ref_name(name string) string {
1572 if !name.contains('.') && !name.contains('__') {
1573 cur_qname := g.const_storage_name(g.tc.cur_module, name)
1574 if cur_qname in g.const_vals {
1575 return cur_qname
1576 }
1577 if name in g.const_vals {
1578 mod := g.const_modules[name] or { '' }
1579 if mod.len == 0 || mod == g.tc.cur_module
1580 || (g.tc.cur_module in ['', 'main', 'builtin'] && mod in ['', 'main', 'builtin']) {
1581 return g.const_primary_name(name)
1582 }
1583 }
1584 return ''
1585 }
1586 if name in g.const_vals {
1587 return g.const_primary_name(name)
1588 }
1589 if name.contains('.') {
1590 if name in g.const_vals {
1591 return g.const_primary_name(name)
1592 }
1593 }
1594 sep := if name.contains('.') {
1595 '.'
1596 } else if name.contains('__') {
1597 '__'
1598 } else {
1599 return ''
1600 }
1601 short_name := name.all_after_last(sep)
1602 if short_name !in g.const_vals {
1603 return ''
1604 }
1605 resolved := g.const_primary_name(short_name)
1606 mod := if resolved in g.const_modules { g.const_modules[resolved] } else { '' }
1607 if mod.len == 0 {
1608 return resolved
1609 }
1610 ref_mod := name.all_before_last(sep)
1611 if ref_mod == mod || ref_mod == mod.all_after_last('.') {
1612 return resolved
1613 }
1614 return ''
1615}
1616
1617// const_ref_name_from_node converts const ref name from node data for c.
1618fn (g &FlatGen) const_ref_name_from_node(node flat.Node) string {
1619 if node.kind == .ident {
1620 return g.const_ref_name(node.value)
1621 }
1622 if node.kind == .selector && node.children_count > 0 {
1623 base := g.a.child_node(&node, 0)
1624 if base.kind == .ident {
1625 return g.const_ref_name('${base.value}.${node.value}')
1626 }
1627 }
1628 return ''
1629}
1630
1631// const_expr_to_string converts const expr to string data for c.
1632fn (mut g FlatGen) const_expr_to_string(id flat.NodeId, seen []string) string {
1633 if int(id) < 0 || int(id) >= g.a.nodes.len {
1634 return '0'
1635 }
1636 node := g.a.nodes[int(id)]
1637 return match node.kind {
1638 .ident, .selector {
1639 const_name := g.const_ref_name_from_node(node)
1640 if const_name.len > 0 && const_name !in seen {
1641 mut next_seen := seen.clone()
1642 next_seen << const_name
1643 old_module := g.tc.cur_module
1644 if mod := g.const_modules[const_name] {
1645 g.tc.cur_module = mod
1646 }
1647 dep_expr := g.const_expr_to_string(g.const_vals[const_name], next_seen)
1648 g.tc.cur_module = old_module
1649 if dep_expr.trim_space().len > 0 {
1650 return dep_expr
1651 }
1652 }
1653 g.expr_to_string(id)
1654 }
1655 .infix {
1656 lhs := g.const_expr_to_string(g.a.child(&node, 0), seen)
1657 rhs := g.const_expr_to_string(g.a.child(&node, 1), seen)
1658 '(${lhs}) ${g.op_str(node.op)} (${rhs})'
1659 }
1660 .prefix {
1661 child := g.const_expr_to_string(g.a.child(&node, 0), seen)
1662 '${g.op_str(node.op)}(${child})'
1663 }
1664 .paren {
1665 child := g.const_expr_to_string(g.a.child(&node, 0), seen)
1666 '(${child})'
1667 }
1668 .cast_expr {
1669 target_type := g.tc.parse_type(node.value)
1670 mut ct := g.tc.c_type(target_type)
1671 if ct.starts_with('fn_ptr:') {
1672 ct = g.resolve_fn_ptr_type(ct)
1673 }
1674 if node.value in g.interfaces || g.tc.qualify_name(node.value) in g.interfaces {
1675 return '(${ct}){0}'
1676 }
1677 if target_type is types.SumType {
1678 inner_id := g.a.child(&node, 0)
1679 inner := g.a.nodes[int(inner_id)]
1680 variant_name0 := if inner.kind == .struct_init {
1681 inner.value
1682 } else {
1683 g.tc.resolve_type(inner_id).name()
1684 }
1685 variant_name := g.resolve_variant(target_type.name, variant_name0)
1686 idx := g.sum_type_index(target_type.name, variant_name)
1687 field := g.sum_field_name(variant_name)
1688 inner_val := g.const_expr_to_string(inner_id, seen)
1689 inner_ct := g.tc.c_type(g.tc.parse_type(variant_name))
1690 payload := if inner_val.trim_space().len == 0 { '0' } else { inner_val }
1691 return '(${ct}){.typ = ${idx}, .${field} = (${inner_ct}[]){${payload}}}'
1692 }
1693 if target_type !is types.Primitive && target_type !is types.Char
1694 && target_type !is types.Rune && target_type !is types.ISize
1695 && target_type !is types.USize && target_type !is types.Pointer
1696 && target_type !is types.Enum {
1697 return g.expr_to_string(id)
1698 }
1699 child0 := g.const_expr_to_string(g.a.child(&node, 0), seen)
1700 child := if child0.trim_space().len == 0 { '0' } else { child0 }
1701 '(${ct})(${child})'
1702 }
1703 .array_literal {
1704 mut parts := []string{}
1705 for i in 0 .. node.children_count {
1706 parts << g.const_expr_to_string(g.a.child(&node, i), seen)
1707 }
1708 '{${parts.join(', ')}}'
1709 }
1710 .struct_init {
1711 ct := g.struct_init_c_type_name(node.value)
1712 sum_name := g.resolve_sum_name(node.value)
1713 is_sum_literal := sum_name in g.tc.sum_types
1714 mut parts := []string{}
1715 for i in 0 .. node.children_count {
1716 field := g.a.child_node(&node, i)
1717 if field.kind == .field_init && field.children_count > 0 {
1718 val_id := g.a.child(field, 0)
1719 val_node := g.a.nodes[int(val_id)]
1720 val := if field.value.len == 0 {
1721 const_val := g.const_expr_to_string(val_id, seen)
1722 if const_val.trim_space().len > 0 {
1723 const_val
1724 } else {
1725 if ftyp := g.struct_field_type_at(node.value, i) {
1726 g.expr_to_string_with_expected_type(val_id, ftyp)
1727 } else {
1728 g.expr_to_string(val_id)
1729 }
1730 }
1731 } else if is_sum_literal && field.value != 'typ' {
1732 mut variant := ''
1733 if field.typ.starts_with('&') {
1734 variant = field.typ[1..]
1735 } else if field.typ.len > 0 {
1736 variant = field.typ
1737 } else {
1738 for v in g.tc.sum_types[sum_name] {
1739 if g.sum_field_name(v) == field.value {
1740 variant = v
1741 break
1742 }
1743 }
1744 }
1745 variant = g.resolve_variant(sum_name, variant)
1746 inner_ct := g.tc.c_type(g.tc.parse_type(variant))
1747 const_val := g.const_expr_to_string(val_id, seen)
1748 payload := if const_val.trim_space().len > 0 {
1749 const_val
1750 } else {
1751 g.expr_to_string_with_expected_type(val_id, g.tc.parse_type(variant))
1752 }
1753 '(${inner_ct}[]){${payload}}'
1754 } else if ftyp := g.struct_field_type(node.value, field.value) {
1755 if val_node.kind == .enum_val {
1756 g.expr_to_string_with_expected_type(val_id, ftyp)
1757 } else {
1758 const_val := g.const_expr_to_string(val_id, seen)
1759 if const_val.trim_space().len > 0 {
1760 const_val
1761 } else {
1762 g.expr_to_string_with_expected_type(val_id, ftyp)
1763 }
1764 }
1765 } else {
1766 const_val := g.const_expr_to_string(val_id, seen)
1767 if const_val.trim_space().len > 0 {
1768 const_val
1769 } else {
1770 g.expr_to_string(val_id)
1771 }
1772 }
1773 if field.value.len == 0 {
1774 parts << val
1775 } else {
1776 parts << '.${c_name(field.value)} = ${val}'
1777 }
1778 } else {
1779 parts << g.const_expr_to_string(g.a.child(&node, i), seen)
1780 }
1781 }
1782 '(${ct}){${parts.join(', ')}}'
1783 }
1784 .string_literal {
1785 '{"${c_escape(node.value)}", ${node.value.len}, 1}'
1786 }
1787 .int_literal, .float_literal, .bool_literal, .char_literal, .enum_val, .sizeof_expr {
1788 g.expr_to_string(id)
1789 }
1790 .offsetof_expr {
1791 ct := g.sizeof_target(node.value)
1792 'offsetof(${ct}, ${c_name(node.typ)})'
1793 }
1794 else {
1795 g.expr_to_string(id)
1796 }
1797 }
1798}
1799
1800// const_ident_c_name converts const ident c name data for c.
1801fn (g &FlatGen) const_ident_c_name(name string) string {
1802 if name.contains('.') {
1803 return c_name(name)
1804 }
1805 mod := if name in g.const_modules { g.const_modules[name] } else { '' }
1806 if mod.len > 0 && mod != 'main' && mod != 'builtin' {
1807 return c_name('${mod}.${name}')
1808 }
1809 if (mod == '' || mod == 'main') && name in g.const_modules {
1810 return c_name('main.${name}')
1811 }
1812 return c_name(name)
1813}
1814
1815// fixed_array_len_expr supports fixed array len expr handling for FlatGen.
1816fn (mut g FlatGen) fixed_array_len_expr(type_name string, fallback int) string {
1817 if type_name.len > 0 {
1818 typ := g.tc.parse_type(type_name)
1819 if typ is types.ArrayFixed {
1820 return g.fixed_array_len_value(typ)
1821 }
1822 }
1823 mut raw_len := ''
1824 if type_name.starts_with('[') {
1825 idx := type_name.index_u8(`]`)
1826 if idx > 1 {
1827 raw_len = type_name[1..idx]
1828 }
1829 } else if type_name.contains('[') && type_name.ends_with(']') {
1830 idx := type_name.index_u8(`[`)
1831 if idx >= 0 && idx < type_name.len - 1 {
1832 raw_len = type_name[idx + 1..type_name.len - 1]
1833 }
1834 }
1835 return g.fixed_array_len_raw(raw_len, fallback)
1836}
1837
1838// fixed_array_len_value supports fixed array len value handling for FlatGen.
1839fn (mut g FlatGen) fixed_array_len_value(arr types.ArrayFixed) string {
1840 // Prefer the evaluated integer length: a const-expression size (`[segs + 1]f32`)
1841 // otherwise reaches the raw fallback and is c_name-mangled into garbage.
1842 if v := g.tc.fixed_array_len_value(arr) {
1843 return v.str()
1844 }
1845 return g.fixed_array_len_raw(arr.len_expr, arr.len)
1846}
1847
1848// fixed_array_len_is_zero supports fixed array len is zero handling for FlatGen.
1849fn (mut g FlatGen) fixed_array_len_is_zero(arr types.ArrayFixed) bool {
1850 if value := g.tc.fixed_array_len_value(arr) {
1851 return value == 0
1852 }
1853 return g.fixed_array_len_value(arr).trim_space() == '0'
1854}
1855
1856// fixed_array_len_raw supports fixed array len raw handling for FlatGen.
1857fn (mut g FlatGen) fixed_array_len_raw(raw_len string, fallback int) string {
1858 if raw_len.len == 0 {
1859 return '${fallback}'
1860 }
1861 // A literal or const-expression size (`8`, `SEGS + 1`, `1 << 2`, `8 >>> 1`) folds to an
1862 // integer; emit that literal so the C dimension is always valid — `>>>` has no C form,
1863 // so a digit-leading expression like `8 >>> 1` must not be passed through raw — and a
1864 // non-numeric expr isn't c_name-mangled (`SEGS_+_1`) into an undeclared identifier.
1865 if v := g.tc.const_int_value(raw_len, []string{}) {
1866 return v.str()
1867 }
1868 clean_len := raw_len.replace('_', '')
1869 if clean_len.len > 0 && clean_len[0] >= `0` && clean_len[0] <= `9` {
1870 return clean_len
1871 }
1872 const_name := g.const_ref_name(raw_len)
1873 if const_name.len > 0 {
1874 expr := g.const_expr_to_string(g.const_vals[const_name], []string{})
1875 if expr.trim_space().len > 0 {
1876 return expr
1877 }
1878 return g.const_ident_c_name(const_name)
1879 }
1880 return c_name(raw_len)
1881}
1882
1883fn (mut g FlatGen) fixed_array_decl_parts(arr types.ArrayFixed) (string, string) {
1884 len_expr := g.fixed_array_len_value(arr)
1885 if arr.elem_type is types.ArrayFixed {
1886 base_ct, suffix := g.fixed_array_decl_parts(arr.elem_type)
1887 return base_ct, '[${len_expr}]${suffix}'
1888 }
1889 return g.tc.c_type(arr.elem_type), '[${len_expr}]'
1890}
1891
1892// infix_can_skip_child_parens reports whether a child infix operand needs no
1893// surrounding parentheses. For associative logical chains (`||`, `&&`) a child of
1894// the same operator is safe unparenthesised; this keeps long lowered chains (e.g.
1895// a `match` over hundreds of enum values → `a || b || c || ...`) from nesting
1896// parentheses past the C compiler's bracket-depth limit.
1897fn infix_can_skip_child_parens(parent_op flat.Op, child_op flat.Op) bool {
1898 return (parent_op == .logical_or && child_op == .logical_or)
1899 || (parent_op == .logical_and && child_op == .logical_and)
1900}
1901
1902// assoc_infix_chain_len counts how many same-operator infix nodes hang off the left
1903// spine of `node` (its nesting depth). Capped early since only "very deep" matters.
1904fn (g &FlatGen) assoc_infix_chain_len(node flat.Node) int {
1905 op := node.op
1906 mut cur := node
1907 mut depth := 0
1908 for {
1909 if cur.children_count < 1 {
1910 break
1911 }
1912 lhs_id := g.a.child(&cur, 0)
1913 if !g.valid_node_id(lhs_id) {
1914 break
1915 }
1916 lhs := g.a.nodes[int(lhs_id)]
1917 if lhs.kind == .infix && lhs.op == op {
1918 depth++
1919 if depth > 101 {
1920 break
1921 }
1922 cur = lhs
1923 } else {
1924 break
1925 }
1926 }
1927 return depth
1928}
1929
1930// gen_assoc_infix_chain emits a left-nested `||`/`&&` chain iteratively, producing the
1931// same flat `a || b || c …` C as the recursive path but without growing the stack per
1932// link (a big match's condition chain can be hundreds deep).
1933fn (mut g FlatGen) gen_assoc_infix_chain(node flat.Node) {
1934 op := node.op
1935 op_s := g.op_str(op)
1936 mut operands := []flat.NodeId{cap: 256}
1937 mut cur := node
1938 for {
1939 operands << g.a.child(&cur, 1)
1940 lhs_id := g.a.child(&cur, 0)
1941 lhs := g.a.nodes[int(lhs_id)]
1942 if lhs.kind == .infix && lhs.op == op && g.valid_node_id(g.a.child(&lhs, 0)) {
1943 cur = lhs
1944 } else {
1945 operands << lhs_id
1946 break
1947 }
1948 }
1949 for i := operands.len - 1; i >= 0; i-- {
1950 if i != operands.len - 1 {
1951 g.write(' ${op_s} ')
1952 }
1953 oid := operands[i]
1954 onode := g.a.nodes[int(oid)]
1955 if onode.kind == .infix && !infix_can_skip_child_parens(op, onode.op) {
1956 g.write('(')
1957 g.gen_expr(oid)
1958 g.write(')')
1959 } else {
1960 g.gen_expr(oid)
1961 }
1962 }
1963}
1964
1965// gen_expr emits expr output for c.
1966fn (mut g FlatGen) gen_expr(id flat.NodeId) {
1967 if int(id) < 0 {
1968 g.write('0')
1969 return
1970 }
1971 node := g.a.nodes[int(id)]
1972 match node.kind {
1973 .int_literal {
1974 v := node.value.replace('_', '')
1975 if v.starts_with('0o') {
1976 g.write('0${v[2..]}')
1977 } else {
1978 g.write(v)
1979 }
1980 }
1981 .float_literal {
1982 g.write(node.value.replace('_', ''))
1983 }
1984 .bool_literal {
1985 g.write(node.value)
1986 }
1987 .char_literal {
1988 v := node.value
1989 if v.starts_with('c:') {
1990 cv := v[2..]
1991 g.write('"${cv}"')
1992 } else if v.len == 0 {
1993 g.write("' '")
1994 } else if v.len == 1 {
1995 if v[0] == `\\` {
1996 g.write("'\\\\'")
1997 } else if v[0] == `'` {
1998 g.write("'\\''")
1999 } else {
2000 g.write("'${v}'")
2001 }
2002 } else if v.starts_with('\\') {
2003 g.write("'${v}'")
2004 } else {
2005 g.write(v)
2006 }
2007 }
2008 .string_literal {
2009 sid := g.intern_string(node.value)
2010 g.write('_str_${sid}')
2011 }
2012 .string_interp {
2013 g.gen_string_interp(node)
2014 }
2015 .dump_expr {
2016 if node.children_count > 0 {
2017 g.gen_expr(g.a.child(&node, 0))
2018 } else {
2019 g.write('0')
2020 }
2021 }
2022 .ident {
2023 if c_fn_name := g.test_user_main_fn_value_c_name(id, node) {
2024 g.write(c_fn_name)
2025 return
2026 }
2027 looked_up := g.tc.cur_scope.lookup(node.value) or { types.Type(types.void_) }
2028 is_local := looked_up !is types.Void
2029 const_name := if !is_local { g.const_ref_name(node.value) } else { '' }
2030 if const_name.len > 0 {
2031 g.write(g.const_ident_c_name(const_name))
2032 } else if node.value in g.global_modules {
2033 mod := g.global_modules[node.value]
2034 if mod.len > 0 && mod != 'main' && mod != 'builtin' {
2035 g.write(c_name('${mod}.${node.value}'))
2036 } else {
2037 g.write(c_name(node.value))
2038 }
2039 } else {
2040 g.write(c_name(node.value))
2041 }
2042 }
2043 .enum_val {
2044 if node.value in g.enum_vals {
2045 eval := g.enum_vals[node.value]
2046 g.write('${eval}')
2047 return
2048 }
2049 if node.typ.len > 0 {
2050 short_name := node.value.trim_left('.').all_after_last('.')
2051 if eval := g.enum_value_for_type(node.typ, short_name) {
2052 g.write('${eval}')
2053 return
2054 }
2055 }
2056 if g.expected_enum.len > 0 {
2057 ekey := '${g.expected_enum}.${node.value}'
2058 if ekey in g.enum_vals {
2059 eval := g.enum_vals[ekey]
2060 g.write('${eval}')
2061 return
2062 }
2063 if !g.expected_enum.contains('.') && g.tc.cur_module.len > 0
2064 && g.tc.cur_module != 'main' && g.tc.cur_module != 'builtin' {
2065 qkey := '${g.tc.cur_module}.${g.expected_enum}.${node.value}'
2066 if qkey in g.enum_vals {
2067 eval := g.enum_vals[qkey]
2068 g.write('${eval}')
2069 return
2070 }
2071 }
2072 }
2073 for ename, eval in g.enum_vals {
2074 if ename.ends_with('.${node.value}') {
2075 g.write('${eval}')
2076 return
2077 }
2078 }
2079 g.write('0')
2080 }
2081 .call {
2082 // A call to a fixed-array-returning function yields the wrapper struct;
2083 // unwrap `.ret_arr` so the result behaves as the array value everywhere
2084 // (indexing, arg passing, memcpy into a destination).
2085 ret_t := g.declared_call_return_type(id)
2086 if ret_t is types.ArrayFixed && g.tc.c_type(ret_t) in g.fixed_array_ret_wrappers {
2087 g.write('(')
2088 g.gen_call(id, node)
2089 g.write(').ret_arr')
2090 } else {
2091 g.gen_call(id, node)
2092 }
2093 }
2094 .spawn_expr {
2095 g.gen_spawn_expr(node)
2096 }
2097 .infix {
2098 // A very long left-nested `||`/`&&` chain (e.g. from a big match condition or
2099 // a `!in [...]` over many values) would recurse once per link and overflow the
2100 // stack; emit those iteratively. Only pathologically long chains take this path,
2101 // so ordinary code keeps the existing per-node generation unchanged.
2102 if (node.op == .logical_or || node.op == .logical_and)
2103 && g.assoc_infix_chain_len(node) > 100 {
2104 g.gen_assoc_infix_chain(node)
2105 return
2106 }
2107 lhs_id := g.a.child(&node, 0)
2108 rhs_id := g.a.child(&node, 1)
2109 old_expected_enum := g.expected_enum
2110 lhs_type := g.usable_expr_type(lhs_id)
2111 rhs_type := g.usable_expr_type(rhs_id)
2112 if node.op == .arrow && lhs_type is types.Channel {
2113 elem_ct := g.tc.c_type(lhs_type.elem_type)
2114 g.write('sync__Channel__push(')
2115 g.gen_expr(lhs_id)
2116 g.write(', &(${elem_ct}[]){')
2117 g.gen_expr_with_expected_type(rhs_id, lhs_type.elem_type)
2118 g.write('})')
2119 g.expected_enum = old_expected_enum
2120 return
2121 }
2122 if lhs_type is types.String || rhs_type is types.String {
2123 if g.gen_string_infix_fallback(node, lhs_id, rhs_id) {
2124 g.expected_enum = old_expected_enum
2125 return
2126 }
2127 }
2128 if lhs_type is types.Enum {
2129 g.expected_enum = lhs_type.name
2130 } else if rhs_type is types.Enum {
2131 g.expected_enum = rhs_type.name
2132 }
2133 if lhs_type is types.Struct {
2134 op_name := match node.op {
2135 .minus { '__minus' }
2136 .plus { '__plus' }
2137 .eq { '__eq' }
2138 .ne { '__ne' }
2139 .lt { '__lt' }
2140 .gt { '__gt' }
2141 .le { '__le' }
2142 .ge { '__ge' }
2143 else { '' }
2144 }
2145
2146 if op_name.len > 0 {
2147 method_name := '${lhs_type.name}${op_name}'
2148 if method_name in g.tc.fn_param_types {
2149 panic('internal error: struct operator overload reached C backend after transform: ${lhs_type.name} op=${node.op}')
2150 }
2151 }
2152 g.gen_expr(lhs_id)
2153 g.write(' ${g.op_str(node.op)} ')
2154 g.gen_expr_with_possible_enum_type(rhs_id, lhs_type)
2155 } else {
2156 lhs_node := g.a.nodes[int(lhs_id)]
2157 rhs_node := g.a.nodes[int(rhs_id)]
2158 if lhs_node.kind == .infix && !infix_can_skip_child_parens(node.op, lhs_node.op) {
2159 g.write('(')
2160 g.gen_expr_with_possible_enum_type(lhs_id, rhs_type)
2161 g.write(')')
2162 } else {
2163 g.gen_expr_with_possible_enum_type(lhs_id, rhs_type)
2164 }
2165 g.write(' ${g.op_str(node.op)} ')
2166 if rhs_node.kind == .infix && !infix_can_skip_child_parens(node.op, rhs_node.op) {
2167 g.write('(')
2168 g.gen_expr_with_possible_enum_type(rhs_id, lhs_type)
2169 g.write(')')
2170 } else {
2171 g.gen_expr_with_possible_enum_type(rhs_id, lhs_type)
2172 }
2173 }
2174 g.expected_enum = old_expected_enum
2175 }
2176 .prefix {
2177 child_id := g.a.child(&node, 0)
2178 child := g.a.nodes[int(child_id)]
2179 if node.op == .arrow {
2180 child_type := g.usable_expr_type(child_id)
2181 if child_type is types.Channel {
2182 elem_ct := g.tc.c_type(child_type.elem_type)
2183 tmp := g.tmp_name()
2184 g.write('({${elem_ct} ${tmp} = (${elem_ct}){0}; sync__Channel__pop(')
2185 g.gen_expr(child_id)
2186 g.write(', &${tmp}); ${tmp};})')
2187 return
2188 }
2189 }
2190 if node.op == .mul && child.kind == .ident {
2191 if typ := g.current_param_type(child.value) {
2192 if typ !is types.Pointer {
2193 g.gen_expr(child_id)
2194 return
2195 }
2196 } else if typ := g.cur_param_types[child.value] {
2197 if typ !is types.Pointer {
2198 g.gen_expr(child_id)
2199 return
2200 }
2201 }
2202 }
2203 if node.op == .amp && g.gen_amp_c_string_literal(child_id, child) {
2204 return
2205 } else if node.op == .amp && child.kind == .struct_init {
2206 g.gen_heap_struct_init(child)
2207 } else if node.op == .amp && child.kind == .assoc {
2208 g.gen_heap_assoc_expr(child)
2209 } else if node.op == .amp && child.kind == .cast_expr {
2210 target_type := g.tc.parse_type(child.value)
2211 ct := g.cast_c_type(target_type)
2212 cast_arg := g.a.child_node(&child, 0)
2213 if cast_arg.kind == .nil_literal {
2214 g.write('(${ct}*)NULL')
2215 return
2216 }
2217 if target_type is types.SumType {
2218 g.write('(${ct}*)memdup(&')
2219 g.gen_sum_cast_expr(target_type, g.a.child(&child, 0))
2220 g.write(', sizeof(${ct}))')
2221 return
2222 }
2223 g.write('(${ct}*)(')
2224 g.gen_expr(g.a.child(&child, 0))
2225 g.write(')')
2226 } else if node.op == .amp && child.kind == .call {
2227 fn_child := g.a.child_node(&child, 0)
2228 if fn_child.kind == .selector {
2229 base_child := g.a.child_node(fn_child, 0)
2230 if base_child.kind == .ident && base_child.value == 'C' {
2231 c_struct_prefix := if fn_child.value.len > 0 && fn_child.value[0] >= `a`
2232 && fn_child.value[0] <= `z` && !fn_child.value.ends_with('_t') {
2233 'struct '
2234 } else {
2235 ''
2236 }
2237 g.write('(${c_struct_prefix}${fn_child.value}*)(')
2238 if child.children_count > 1 {
2239 g.gen_expr(g.a.child(&child, 1))
2240 } else {
2241 g.write('0')
2242 }
2243 g.write(')')
2244 } else {
2245 g.write(g.op_str(node.op))
2246 g.gen_expr(child_id)
2247 }
2248 } else {
2249 g.write(g.op_str(node.op))
2250 g.gen_expr(child_id)
2251 }
2252 } else {
2253 g.write(g.op_str(node.op))
2254 g.gen_expr(child_id)
2255 }
2256 }
2257 .in_expr {
2258 // NOTE: range membership, inline-array-literal membership, dynamic- and
2259 // fixed-array membership, and `!in` negation are lowered by the
2260 // transformer (transform.transform_in_expr). Map membership stays as an
2261 // in_expr so each backend can lower it directly.
2262 lhs_id := g.a.child(&node, 0)
2263 rhs_id := g.a.child(&node, 1)
2264 rhs := g.a.nodes[int(rhs_id)]
2265 rhs_type := g.usable_expr_type(rhs_id)
2266 clean_rhs := types.unwrap_pointer(rhs_type)
2267 if clean_rhs is types.Map {
2268 c_key := g.tc.c_type(clean_rhs.key_type)
2269 is_ptr := rhs_type is types.Pointer
2270 if is_ptr {
2271 g.write('map__exists(')
2272 } else {
2273 g.write('map__exists(&')
2274 }
2275 g.gen_expr(rhs_id)
2276 g.write(', &(${c_key}[]){')
2277 g.gen_expr(lhs_id)
2278 g.write('})')
2279 } else if rhs.kind == .array_literal {
2280 if rhs.children_count == 0 {
2281 g.write('false')
2282 } else {
2283 lhs_type := g.usable_expr_type(lhs_id)
2284 g.write('(')
2285 for i in 0 .. rhs.children_count {
2286 if i > 0 {
2287 g.write(' || ')
2288 }
2289 elem_id := g.a.child(&rhs, i)
2290 elem_type := g.usable_expr_type(elem_id)
2291 if lhs_type is types.String || elem_type is types.String {
2292 g.write('string__eq(')
2293 g.gen_expr(lhs_id)
2294 g.write(', ')
2295 g.gen_expr(elem_id)
2296 g.write(')')
2297 } else {
2298 g.gen_expr(lhs_id)
2299 g.write(' == ')
2300 g.gen_expr(elem_id)
2301 }
2302 }
2303 g.write(')')
2304 }
2305 } else if clean_rhs is types.Array {
2306 fn_name := array_membership_fn_name(clean_rhs.elem_type, false)
2307 g.write('${fn_name}(')
2308 // A `mut []T` param (or any `&[]T`) is a pointer in C; the membership
2309 // helper takes the array by value, so dereference it first.
2310 if rhs_type is types.Pointer {
2311 g.write('*')
2312 }
2313 g.gen_expr(rhs_id)
2314 g.write(', ')
2315 g.gen_expr(lhs_id)
2316 g.write(')')
2317 } else if clean_rhs is types.ArrayFixed {
2318 fn_name := array_membership_fn_name(clean_rhs.elem_type, true)
2319 len_expr := g.fixed_array_len_value(clean_rhs)
2320 g.write('${fn_name}(')
2321 g.gen_expr(rhs_id)
2322 g.write(', ${len_expr}, ')
2323 g.gen_expr(lhs_id)
2324 g.write(')')
2325 } else {
2326 panic('internal error: non-map membership reached C backend in ${g.cur_fn_name}: rhs=${rhs_type.name()} kind=${rhs.kind} value=${rhs.value}')
2327 }
2328 }
2329 .postfix {
2330 g.gen_expr(g.a.child(&node, 0))
2331 g.write(g.op_str(node.op))
2332 }
2333 .paren {
2334 g.write('(')
2335 g.gen_expr(g.a.child(&node, 0))
2336 g.write(')')
2337 }
2338 .selector {
2339 base_id := g.a.child(&node, 0)
2340 base := g.a.nodes[int(base_id)]
2341 base_type0 := g.tc.resolve_type(base_id)
2342 if base_type0 is types.Channel && node.value in ['closed', 'len'] {
2343 if node.value == 'closed' {
2344 g.write('(atomic_load_u16(&')
2345 g.gen_expr(base_id)
2346 g.write('->closed) != 0)')
2347 } else {
2348 g.write('sync__Channel__len(')
2349 g.gen_expr(base_id)
2350 g.write(')')
2351 }
2352 return
2353 }
2354 base_is_local := if base.kind == .ident {
2355 (g.tc.cur_scope.lookup(base.value) or { types.Type(types.void_) }) !is types.Void
2356 } else {
2357 false
2358 }
2359 // A method used as a value (e.g. `game.draw` passed as a callback) rather
2360 // than a field access — bind the receiver and yield a wrapper function.
2361 if g.gen_method_value_closure(base_id, base_type0, node.value) {
2362 return
2363 }
2364 enum_selector_qbase := if base.kind == .ident && base.value != 'C' && !base_is_local {
2365 g.enum_selector_base_name(base.value) or { '' }
2366 } else {
2367 ''
2368 }
2369 if base.kind == .ident && base.value == 'C' {
2370 g.write(node.value)
2371 } else if enum_selector_qbase.len > 0 {
2372 ekey := '${enum_selector_qbase}.${node.value}'
2373 if eval := g.enum_vals[ekey] {
2374 g.write('${eval}')
2375 } else {
2376 g.write('0')
2377 }
2378 } else if base.kind == .call && base.children_count == 2
2379 && g.c_typedef_cast_call_name(base).len > 0 {
2380 cast_name := g.c_typedef_cast_call_name(base)
2381 cast_arg_id := g.a.child(&base, 1)
2382 g.write('((${c_name(cast_name)}*)')
2383 g.gen_expr(cast_arg_id)
2384 g.write(')->${c_name(node.value)}')
2385 } else if base.kind == .cast_expr && base.children_count > 0
2386 && (base.value.starts_with('C.') || base.value.contains('__')) {
2387 cast_child_id := g.a.child(&base, 0)
2388 cast_name := if base.value.starts_with('C.') { base.value[2..] } else { base.value }
2389 g.write('((${c_name(cast_name)}*)')
2390 g.gen_expr(cast_child_id)
2391 g.write(')->${c_name(node.value)}')
2392 } else if base.kind == .cast_expr && base.children_count > 0 {
2393 needs_paren := base.kind !in [.ident, .selector]
2394 if needs_paren {
2395 g.write('(')
2396 }
2397 g.gen_expr(base_id)
2398 if needs_paren {
2399 g.write(')')
2400 }
2401 if node.op == .arrow || base_type0 is types.Pointer {
2402 g.write('->')
2403 } else {
2404 g.write('.')
2405 }
2406 g.write(c_name(node.value))
2407 } else if node.value == 'len' && base.kind == .ident {
2408 base_type := g.tc.resolve_type(base_id)
2409 if base_type is types.ArrayFixed {
2410 g.write(g.fixed_array_len_value(base_type))
2411 } else {
2412 raw_type := g.tc.cur_scope.lookup(base.value) or { base_type }
2413 g.gen_expr(base_id)
2414 if raw_type is types.Pointer {
2415 g.write('->len')
2416 } else {
2417 g.write('.len')
2418 }
2419 }
2420 } else if base.kind == .ident && !base_is_local && g.has_import_alias(base.value) {
2421 mod := g.import_alias_module(base.value) or { '' }
2422 short_mod := if mod.contains('.') {
2423 mod.all_after_last('.')
2424 } else {
2425 mod
2426 }
2427 // A module-level const is stored under the importing module's full path
2428 // (e.g. `v3.gen.wasm`), matching its function naming. Reference it by that
2429 // exact storage name rather than the short alias, otherwise we'd emit an
2430 // undeclared `wasm__x` for a const defined as `v3__gen__wasm__x`.
2431 full_qname := g.const_storage_name(mod, node.value)
2432 if full_qname in g.const_vals {
2433 g.write(c_name(full_qname))
2434 } else {
2435 g.write(c_name('${short_mod}.${node.value}'))
2436 }
2437 } else if base.kind == .selector && base.children_count > 0
2438 && g.is_module_qualified_enum(base) {
2439 inner_base := g.a.child_node(&base, 0)
2440 mod := g.import_alias_module(inner_base.value) or { inner_base.value }
2441 short_mod := if mod.contains('.') {
2442 mod.all_after_last('.')
2443 } else {
2444 mod
2445 }
2446 qname := '${short_mod}.${base.value}'
2447 if qname in g.tc.enum_names || base.value in g.tc.enum_names {
2448 ekey := '${qname}.${node.value}'
2449 ekey2 := '${base.value}.${node.value}'
2450 if ekey in g.enum_vals {
2451 eval := g.enum_vals[ekey]
2452 g.write('${eval}')
2453 } else if ekey2 in g.enum_vals {
2454 eval := g.enum_vals[ekey2]
2455 g.write('${eval}')
2456 } else {
2457 g.write(c_name('${qname}.${node.value}'))
2458 }
2459 } else {
2460 g.write(c_name('${qname}.${node.value}'))
2461 }
2462 } else if embedded := g.direct_embedded_field_for_selector(base_type0, node.value) {
2463 needs_paren := base.kind !in [.ident, .selector]
2464 if needs_paren {
2465 g.write('(')
2466 }
2467 g.gen_expr(base_id)
2468 if needs_paren {
2469 g.write(')')
2470 }
2471 if node.op == .arrow || base_type0 is types.Pointer {
2472 g.write('->')
2473 } else {
2474 g.write('.')
2475 }
2476 g.write(c_name(embedded.name))
2477 } else if embedded_path := g.embedded_field_path_for_promoted_selector(base_type0,
2478 node.value)
2479 {
2480 needs_paren := base.kind !in [.ident, .selector]
2481 if needs_paren {
2482 g.write('(')
2483 }
2484 g.gen_expr(base_id)
2485 if needs_paren {
2486 g.write(')')
2487 }
2488 mut is_ptr := node.op == .arrow || base_type0 is types.Pointer
2489 for embedded in embedded_path {
2490 op := if is_ptr { '->' } else { '.' }
2491 g.write('${op}${c_name(embedded.name)}')
2492 is_ptr = embedded.typ is types.Pointer
2493 }
2494 final_op := if is_ptr { '->' } else { '.' }
2495 g.write('${final_op}${c_name(node.value)}')
2496 } else {
2497 needs_paren := base.kind !in [.ident, .selector]
2498 if needs_paren {
2499 g.write('(')
2500 }
2501 g.gen_expr(base_id)
2502 if needs_paren {
2503 g.write(')')
2504 }
2505 mut is_ptr := false
2506 if base.kind == .ident {
2507 if typ := g.tc.cur_scope.lookup(base.value) {
2508 is_ptr = typ is types.Pointer
2509 }
2510 } else if base.kind == .selector {
2511 if declared := g.selector_declared_type(base_id) {
2512 is_ptr = declared is types.Pointer
2513 } else {
2514 resolved := g.tc.resolve_type(base_id)
2515 is_ptr = resolved is types.Pointer
2516 }
2517 } else {
2518 resolved := g.tc.resolve_type(base_id)
2519 is_ptr = resolved is types.Pointer
2520 }
2521 if node.op == .arrow || is_ptr {
2522 g.write('->')
2523 } else {
2524 g.write('.')
2525 }
2526 g.write(c_name(node.value))
2527 }
2528 }
2529 .index {
2530 base_id := g.a.child(&node, 0)
2531 base_type := g.tc.resolve_type(base_id)
2532 if node.value == 'range' {
2533 g.gen_slice_expr(node, base_id, base_type)
2534 } else if base_type is types.Map {
2535 c_key := g.value_c_type(base_type.key_type)
2536 c_val := g.value_c_type(base_type.value_type)
2537 g.write('(*(${c_val}*)map__get(&')
2538 g.gen_expr(base_id)
2539 g.write(', &(${c_key}[]){')
2540 g.gen_expr(g.a.child(&node, 1))
2541 g.write('}, &(${c_val}[]){0}))')
2542 } else {
2543 is_fixed_array_index, fixed_is_ptr, _ := fixed_array_index_info(base_type)
2544 if is_fixed_array_index {
2545 if fixed_is_ptr {
2546 g.write('(*')
2547 g.gen_expr(base_id)
2548 g.write(')')
2549 } else {
2550 g.gen_expr(base_id)
2551 }
2552 g.write('[')
2553 g.gen_expr(g.a.child(&node, 1))
2554 g.write(']')
2555 } else {
2556 is_array_index, is_ptr, arr_type := array_index_info(base_type)
2557 if is_array_index {
2558 index_type := if g.expected_expr_type is types.OptionType
2559 || g.expected_expr_type is types.ResultType
2560 || g.expected_expr_is_optional_struct() {
2561 g.expected_expr_type
2562 } else if node.typ.starts_with('?') || node.typ.starts_with('!') {
2563 g.tc.parse_type(node.typ)
2564 } else {
2565 arr_type.elem_type
2566 }
2567 c_elem := g.value_c_type(index_type)
2568 g.write('(*(${c_elem}*)array_get(')
2569 if is_ptr {
2570 g.write('*')
2571 }
2572 g.gen_expr(base_id)
2573 g.write(', ')
2574 g.gen_expr(g.a.child(&node, 1))
2575 g.write('))')
2576 } else if base_type is types.String {
2577 // Parenthesize the base: a smartcast sum variant yields a deref
2578 // like `*v._string`, and `*v._string.str[i]` would bind as
2579 // `*(v._string.str[i])`. `(*v._string).str[i]` is what we want.
2580 g.write('(')
2581 g.gen_expr(base_id)
2582 g.write(').str[')
2583 g.gen_expr(g.a.child(&node, 1))
2584 g.write(']')
2585 } else if base_type is types.Pointer {
2586 ptr_type := base_type
2587 if ptr_type.base_type is types.Void {
2588 g.write('((u8*)')
2589 g.gen_expr(base_id)
2590 g.write(')[')
2591 g.gen_expr(g.a.child(&node, 1))
2592 g.write(']')
2593 } else {
2594 g.gen_expr(base_id)
2595 g.write('[')
2596 g.gen_expr(g.a.child(&node, 1))
2597 g.write(']')
2598 }
2599 } else {
2600 g.gen_expr(base_id)
2601 g.write('[')
2602 g.gen_expr(g.a.child(&node, 1))
2603 g.write(']')
2604 }
2605 }
2606 }
2607 }
2608 .array_init {
2609 raw_init_type := g.tc.parse_type(node.value)
2610 init_type := raw_init_type
2611 if init_type is types.ArrayFixed {
2612 ct := g.tc.c_type(raw_init_type)
2613 g.write('(${ct}){0}')
2614 } else {
2615 c_elem := g.tc.c_type(init_type)
2616 g.write('array_new(sizeof(${c_elem}), 0, 0)')
2617 }
2618 }
2619 .map_init {
2620 g.gen_map_init(id, node)
2621 }
2622 .sql_expr {
2623 panic('internal error: SQL expression reached C backend after transform')
2624 }
2625 .cast_expr {
2626 target_type := g.tc.parse_type(node.value)
2627 mut ct := g.cast_c_type(target_type)
2628 if ct.starts_with('fn_ptr:') {
2629 ct = g.resolve_fn_ptr_type(ct)
2630 }
2631 if node.value in g.interfaces || g.tc.qualify_name(node.value) in g.interfaces {
2632 g.write('(${ct}){0}')
2633 } else if target_type is types.SumType {
2634 g.gen_sum_cast_expr(target_type, g.a.child(&node, 0))
2635 } else {
2636 g.write('(${ct})(')
2637 g.gen_expr(g.a.child(&node, 0))
2638 g.write(')')
2639 }
2640 }
2641 .struct_init {
2642 g.gen_struct_init(node)
2643 }
2644 .if_expr {
2645 g.gen_if_expr(node)
2646 }
2647 .array_literal {
2648 g.write('{')
2649 for i in 0 .. node.children_count {
2650 if i > 0 {
2651 g.write(', ')
2652 }
2653 g.gen_expr(g.a.child(&node, i))
2654 }
2655 g.write('}')
2656 }
2657 .nil_literal {
2658 g.write('NULL')
2659 }
2660 .none_expr {
2661 ct := g.optional_type_name(g.optional_none_type(id))
2662 g.write('(${ct}){.ok = false}')
2663 }
2664 .or_expr {
2665 g.gen_or_expr(node)
2666 }
2667 .block {
2668 if node.children_count > 1 {
2669 g.write('({')
2670 for bi in 0 .. node.children_count - 1 {
2671 g.gen_node(g.a.child(&node, bi))
2672 }
2673 last_id := g.a.child(&node, node.children_count - 1)
2674 last := g.a.nodes[int(last_id)]
2675 if last.kind == .expr_stmt {
2676 g.gen_expr(g.a.child(&last, 0))
2677 } else if last.kind == .if_expr {
2678 g.gen_expr(last_id)
2679 } else {
2680 g.gen_node(last_id)
2681 }
2682 g.write(';})')
2683 } else if node.children_count > 0 {
2684 last_id := g.a.child(&node, 0)
2685 last := g.a.nodes[int(last_id)]
2686 if last.kind == .expr_stmt {
2687 g.gen_expr(g.a.child(&last, 0))
2688 } else {
2689 g.gen_expr(last_id)
2690 }
2691 }
2692 }
2693 .is_expr {
2694 expr_id := g.a.child(&node, 0)
2695 expr_type := g.tc.resolve_type(expr_id)
2696 clean := types.unwrap_pointer(expr_type)
2697 if clean is types.SumType {
2698 idx := g.sum_type_index(clean.name, node.value)
2699 g.write('(')
2700 if expr_type.is_pointer() {
2701 g.gen_expr(expr_id)
2702 g.write('->typ == ${idx}')
2703 } else {
2704 g.gen_expr(expr_id)
2705 g.write('.typ == ${idx}')
2706 }
2707 g.write(')')
2708 } else {
2709 g.write('1')
2710 }
2711 }
2712 .as_expr {
2713 expr_id := g.a.child(&node, 0)
2714 expr_type := g.tc.resolve_type(expr_id)
2715 clean := types.unwrap_pointer(expr_type)
2716 if clean is types.SumType {
2717 qv := g.resolve_variant(clean.name, node.value)
2718 field := g.sum_field_name(qv)
2719 if g.variant_references_sum(qv, clean.name) {
2720 g.write('(*')
2721 if expr_type.is_pointer() {
2722 g.gen_expr(expr_id)
2723 g.write('->${field})')
2724 } else {
2725 g.gen_expr(expr_id)
2726 g.write('.${field})')
2727 }
2728 } else {
2729 if expr_type.is_pointer() {
2730 g.gen_expr(expr_id)
2731 g.write('->${field}')
2732 } else {
2733 g.gen_expr(expr_id)
2734 g.write('.${field}')
2735 }
2736 }
2737 } else {
2738 g.gen_expr(expr_id)
2739 }
2740 }
2741 .sizeof_expr {
2742 g.write('sizeof(${g.sizeof_target(node.value)})')
2743 }
2744 .offsetof_expr {
2745 ct := g.type_name_c_type(node.value)
2746 g.write('offsetof(${ct}, ${c_name(node.typ)})')
2747 }
2748 .assoc {
2749 g.gen_assoc_expr(node)
2750 }
2751 .empty {
2752 g.write('0')
2753 }
2754 else {}
2755 }
2756}
2757
2758fn (mut g FlatGen) gen_string_infix_fallback(node flat.Node, lhs_id flat.NodeId, rhs_id flat.NodeId) bool {
2759 match node.op {
2760 .plus {
2761 g.write('string__plus(')
2762 g.gen_expr(lhs_id)
2763 g.write(', ')
2764 g.gen_expr(rhs_id)
2765 g.write(')')
2766 }
2767 .eq {
2768 g.write('string__eq(')
2769 g.gen_expr(lhs_id)
2770 g.write(', ')
2771 g.gen_expr(rhs_id)
2772 g.write(')')
2773 }
2774 .ne {
2775 g.write('!string__eq(')
2776 g.gen_expr(lhs_id)
2777 g.write(', ')
2778 g.gen_expr(rhs_id)
2779 g.write(')')
2780 }
2781 .lt {
2782 g.write('string__lt(')
2783 g.gen_expr(lhs_id)
2784 g.write(', ')
2785 g.gen_expr(rhs_id)
2786 g.write(')')
2787 }
2788 .gt {
2789 g.write('string__lt(')
2790 g.gen_expr(rhs_id)
2791 g.write(', ')
2792 g.gen_expr(lhs_id)
2793 g.write(')')
2794 }
2795 .le {
2796 g.write('!string__lt(')
2797 g.gen_expr(rhs_id)
2798 g.write(', ')
2799 g.gen_expr(lhs_id)
2800 g.write(')')
2801 }
2802 .ge {
2803 g.write('!string__lt(')
2804 g.gen_expr(lhs_id)
2805 g.write(', ')
2806 g.gen_expr(rhs_id)
2807 g.write(')')
2808 }
2809 else {
2810 return false
2811 }
2812 }
2813
2814 return true
2815}
2816
2817fn array_membership_fn_name(elem_type types.Type, fixed bool) string {
2818 prefix := if fixed { 'fixed_array_contains_' } else { 'array_contains_' }
2819 elem_name := elem_type.name()
2820 suffix := match elem_name {
2821 'string' { 'string' }
2822 'u8', 'byte' { 'u8' }
2823 else { 'int' }
2824 }
2825
2826 return prefix + suffix
2827}
2828
2829fn (g &FlatGen) is_module_qualified_enum(base flat.Node) bool {
2830 if base.kind != .selector || base.children_count == 0 {
2831 return false
2832 }
2833 inner_base := g.a.child_node(&base, 0)
2834 if inner_base.kind != .ident || !g.has_import_alias(inner_base.value) {
2835 return false
2836 }
2837 mod := g.import_alias_module(inner_base.value) or { inner_base.value }
2838 short_mod := if mod.contains('.') { mod.all_after_last('.') } else { mod }
2839 qname := '${short_mod}.${base.value}'
2840 return qname in g.tc.enum_names || base.value in g.tc.enum_names
2841}
2842
2843fn (mut g FlatGen) preamble() {
2844 g.c99_feature_test_macros()
2845 g.writeln('#include <stdio.h>')
2846 g.writeln('#include <stdlib.h>')
2847 g.writeln('#include <string.h>')
2848 g.writeln('#include <stddef.h>')
2849 g.writeln('#include <float.h>')
2850 g.writeln('#include <stdint.h>') // guarantees UINTPTR_MAX for the pointer-width atomic helpers
2851 g.writeln('#include <math.h>')
2852 g.writeln('#include <unistd.h>')
2853 g.c99_atomic_compat_decls()
2854 if g.has_builtins {
2855 g.writeln('#include <time.h>')
2856 g.writeln('#include <sys/time.h>')
2857 g.writeln('#include <errno.h>')
2858 g.writeln('#include <signal.h>')
2859 g.writeln('#include <execinfo.h>')
2860 g.writeln('#include <dirent.h>')
2861 g.writeln('#include <sys/stat.h>')
2862 g.writeln('#include <fcntl.h>')
2863 g.writeln('#include <sys/ioctl.h>')
2864 g.writeln('#include <sys/utsname.h>')
2865 g.writeln('#include <pthread.h>')
2866 g.writeln('#include <semaphore.h>')
2867 g.writeln('#include <termios.h>')
2868 g.writeln('#include <unistd.h>')
2869 g.writeln('#include <arpa/inet.h>')
2870 g.writeln('#include <netdb.h>')
2871 g.writeln('#include <netinet/in.h>')
2872 g.writeln('#include <netinet/tcp.h>')
2873 g.writeln('#include <sys/socket.h>')
2874 g.writeln('#ifdef __APPLE__')
2875 g.writeln('#define panic mach_panic')
2876 g.writeln('#include <mach/mach.h>')
2877 g.writeln('#include <mach/task.h>')
2878 g.writeln('#include <mach/mach_time.h>')
2879 g.writeln('#include <mach-o/dyld.h>')
2880 g.writeln('#undef panic')
2881 g.writeln('#ifndef PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP')
2882 g.writeln('#define PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP 0')
2883 g.writeln('#define pthread_rwlockattr_setkind_np(attr, kind) 0')
2884 g.writeln('#endif')
2885 g.writeln('#endif')
2886 }
2887 if g.libc_compat_fns['gettid'] {
2888 g.writeln('#ifdef __linux__')
2889 g.writeln('#include <sys/syscall.h>')
2890 g.writeln('#endif')
2891 }
2892 for directive in g.ordered_c_directives() {
2893 g.writeln(directive)
2894 }
2895 g.writeln('')
2896 g.writeln('typedef signed char i8;')
2897 g.writeln('typedef short i16;')
2898 g.writeln('typedef int i32;')
2899 g.writeln('typedef long long i64;')
2900 g.writeln('typedef unsigned char u8;')
2901 g.writeln('typedef unsigned char byte;')
2902 g.writeln('typedef unsigned short u16;')
2903 g.writeln('typedef unsigned int u32;')
2904 g.writeln('typedef unsigned long long u64;')
2905 g.writeln('#ifndef __bool_true_false_are_defined')
2906 g.writeln('typedef int bool;')
2907 g.writeln('#endif')
2908 g.writeln('typedef void* voidptr;')
2909 g.writeln('typedef int int_literal;')
2910 g.writeln('typedef double float_literal;')
2911 g.writeln('struct sync__Channel;')
2912 g.writeln('typedef struct sync__Channel* chan;')
2913 g.writeln('#define true 1')
2914 g.writeln('#define false 0')
2915 g.write_arch_macros()
2916 g.writeln('')
2917 if !g.has_builtins {
2918 g.writeln('typedef struct {')
2919 g.writeln('\tchar* str;')
2920 g.writeln('\tint len;')
2921 g.writeln('\tint is_lit;')
2922 g.writeln('} string;')
2923 g.writeln('')
2924 }
2925 g.writeln('#define elem_size element_size')
2926 g.writeln('#define c_name types__c_name')
2927 if g.has_builtins {
2928 return
2929 }
2930 g.writeln('typedef struct Array { void* data; int len; int cap; int elem_size; } Array;')
2931 g.writeln('')
2932}
2933
2934fn (mut g FlatGen) c99_feature_test_macros() {
2935 if !g.c99_mode {
2936 return
2937 }
2938 g.writeln('#if defined(__linux__) && !defined(_GNU_SOURCE)')
2939 g.writeln('#define _GNU_SOURCE')
2940 g.writeln('#endif')
2941 g.writeln('#if defined(__linux__) && !defined(_POSIX_C_SOURCE)')
2942 g.writeln('#define _POSIX_C_SOURCE 200809L')
2943 g.writeln('#endif')
2944}
2945
2946fn (mut g FlatGen) c99_atomic_compat_decls() {
2947 if g.has_stdatomic_header {
2948 return
2949 }
2950 g.writeln('typedef volatile uintptr_t atomic_uintptr_t;')
2951 g.writeln('#ifndef memory_order_relaxed')
2952 g.writeln('#define memory_order_relaxed 0')
2953 g.writeln('#define memory_order_consume 1')
2954 g.writeln('#define memory_order_acquire 2')
2955 g.writeln('#define memory_order_release 3')
2956 g.writeln('#define memory_order_acq_rel 4')
2957 g.writeln('#define memory_order_seq_cst 5')
2958 g.writeln('#endif')
2959 g.writeln('#ifndef atomic_thread_fence')
2960 g.writeln('#define atomic_thread_fence(order) __sync_synchronize()')
2961 g.writeln('#endif')
2962}
2963
2964fn (mut g FlatGen) write_arch_macros() {
2965 g.writeln('#ifndef __V_architecture')
2966 g.writeln('#define __V_architecture 0')
2967 g.writeln('#endif')
2968 g.writeln('#if defined(__x86_64__) || defined(_M_AMD64)')
2969 g.writeln('#define __V_amd64 1')
2970 g.writeln('#undef __V_architecture')
2971 g.writeln('#define __V_architecture 1')
2972 g.writeln('#endif')
2973 g.writeln('#if defined(__aarch64__) || defined(__arm64__) || defined(_M_ARM64)')
2974 g.writeln('#define __V_arm64 1')
2975 g.writeln('#undef __V_architecture')
2976 g.writeln('#define __V_architecture 2')
2977 g.writeln('#endif')
2978 g.writeln('#if defined(__arm__) || defined(_M_ARM)')
2979 g.writeln('#define __V_arm32 1')
2980 g.writeln('#undef __V_architecture')
2981 g.writeln('#define __V_architecture 3')
2982 g.writeln('#endif')
2983 g.writeln('#if defined(__riscv) && __riscv_xlen == 64')
2984 g.writeln('#define __V_rv64 1')
2985 g.writeln('#undef __V_architecture')
2986 g.writeln('#define __V_architecture 4')
2987 g.writeln('#endif')
2988 g.writeln('#if defined(__riscv) && __riscv_xlen == 32')
2989 g.writeln('#define __V_rv32 1')
2990 g.writeln('#undef __V_architecture')
2991 g.writeln('#define __V_architecture 5')
2992 g.writeln('#endif')
2993 g.writeln('#if defined(__i386__) || defined(_M_IX86)')
2994 g.writeln('#define __V_x86 1')
2995 g.writeln('#undef __V_architecture')
2996 g.writeln('#define __V_architecture 6')
2997 g.writeln('#endif')
2998}
2999
3000fn (mut g FlatGen) libc_compat_decls() {
3001 if g.libc_compat_fns['gettid'] {
3002 g.writeln('#ifdef __linux__')
3003 g.writeln('#ifndef SYS_gettid')
3004 g.writeln('#define SYS_gettid __NR_gettid')
3005 g.writeln('#endif')
3006 g.writeln('static inline u32 v3_gettid(void) {')
3007 g.writeln('\treturn (u32)syscall(SYS_gettid);')
3008 g.writeln('}')
3009 g.writeln('#endif')
3010 g.writeln('')
3011 }
3012}
3013
3014fn (mut g FlatGen) prealloc_atomic_compat_decls() {
3015 g.writeln('static inline int v_prealloc_atomic_add_i32(int *ptr, int delta) { return __atomic_add_fetch(ptr, delta, 5); }')
3016 g.writeln('static inline int v_prealloc_atomic_load_i32(int *ptr) { return __atomic_add_fetch(ptr, 0, 5); }')
3017 g.writeln('#ifdef __TINYC__')
3018 g.writeln('static inline int v_prealloc_atomic_store_i32(int *ptr, int val) { return (int)__atomic_exchange_4((u32*)ptr, (u32)val, 5); }')
3019 g.writeln('static inline int v_prealloc_atomic_cas_i32(int *ptr, int expected, int desired) { u32 e = (u32)expected; return __atomic_compare_exchange_4((u32*)ptr, &e, (u32)desired, 5, 5); }')
3020 g.writeln('#else')
3021 g.writeln('static inline int v_prealloc_atomic_store_i32(int *ptr, int val) { return __atomic_exchange_n(ptr, val, 5); }')
3022 g.writeln('static inline int v_prealloc_atomic_cas_i32(int *ptr, int expected, int desired) { return __atomic_compare_exchange_n(ptr, &expected, desired, 0, 5, 5); }')
3023 g.writeln('#endif')
3024}
3025
3026fn (mut g FlatGen) atomic_builtin_compat_decls() {
3027 if g.has_stdatomic_compat_header {
3028 return
3029 }
3030 // Atomic helpers. We use compiler __atomic_* builtins (memory order 5 == __ATOMIC_SEQ_CST).
3031 // clang/gcc inline the generic _n / RMW builtins. tcc only implements the inline
3032 // __atomic_{add,sub,fetch}_* RMW builtins; for load/store/exchange/cas it has no generic
3033 // _n form, so we route those to the sized __atomic_*_N libcalls (resolved from libc).
3034 g.writeln('static inline u32 atomic_fetch_add_u32(void* ptr, u32 delta) { return __atomic_fetch_add((u32*)ptr, delta, 5); }')
3035 g.writeln('static inline u64 atomic_fetch_add_u64(void* ptr, u64 delta) { return __atomic_fetch_add((u64*)ptr, delta, 5); }')
3036 g.writeln('static inline u64 atomic_fetch_sub_u64(void* ptr, u64 delta) { return __atomic_fetch_sub((u64*)ptr, delta, 5); }')
3037 g.writeln('static inline byte atomic_load_byte(void* ptr) { return __atomic_fetch_add((byte*)ptr, 0, 5); }')
3038 g.writeln('static inline u16 atomic_load_u16(void* ptr) { return __atomic_fetch_add((u16*)ptr, 0, 5); }')
3039 g.writeln('static inline u32 atomic_load_u32(void* ptr) { return __atomic_fetch_add((u32*)ptr, 0, 5); }')
3040 g.writeln('static inline u64 atomic_load_u64(void* ptr) { return __atomic_fetch_add((u64*)ptr, 0, 5); }')
3041 g.writeln('static inline void* atomic_load_ptr(void* ptr) { return *(void* volatile*)ptr; }')
3042 g.writeln('#ifdef __TINYC__')
3043 g.writeln('static inline void atomic_store_byte(void* ptr, byte val) { __atomic_store_1((byte*)ptr, val, 5); }')
3044 g.writeln('static inline void atomic_store_u16(void* ptr, u16 val) { __atomic_store_2((u16*)ptr, val, 5); }')
3045 g.writeln('static inline void atomic_store_u32(void* ptr, u32 val) { __atomic_store_4((u32*)ptr, val, 5); }')
3046 g.writeln('static inline void atomic_store_u64(void* ptr, u64 val) { __atomic_store_8((u64*)ptr, val, 5); }')
3047 g.writeln('#if UINTPTR_MAX == 0xFFFFFFFF')
3048 g.writeln('static inline void atomic_store_ptr(void* ptr, void* val) { __atomic_store_4((u32*)ptr, (u32)(size_t)val, 5); }')
3049 g.writeln('#else')
3050 g.writeln('static inline void atomic_store_ptr(void* ptr, void* val) { __atomic_store_8((u64*)ptr, (u64)(size_t)val, 5); }')
3051 g.writeln('#endif')
3052 g.writeln('static inline bool atomic_compare_exchange_strong_u16(void* ptr, u16* expected, u16 desired) { return __atomic_compare_exchange_2((u16*)ptr, expected, desired, 5, 5); }')
3053 g.writeln('static inline bool atomic_compare_exchange_strong_u32(void* ptr, u32* expected, u32 desired) { return __atomic_compare_exchange_4((u32*)ptr, expected, desired, 5, 5); }')
3054 g.writeln('#if UINTPTR_MAX == 0xFFFFFFFF')
3055 g.writeln('static inline bool atomic_compare_exchange_strong_ptr(void* ptr, void* expected, ptrdiff_t desired) { return __atomic_compare_exchange_4((u32*)ptr, (u32*)expected, (u32)desired, 5, 5); }')
3056 g.writeln('#else')
3057 g.writeln('static inline bool atomic_compare_exchange_strong_ptr(void* ptr, void* expected, ptrdiff_t desired) { return __atomic_compare_exchange_8((u64*)ptr, (u64*)expected, (u64)desired, 5, 5); }')
3058 g.writeln('#endif')
3059 g.writeln('static inline bool atomic_compare_exchange_weak_byte(void* ptr, byte* expected, byte desired) { return __atomic_compare_exchange_1((byte*)ptr, expected, desired, 5, 5); }')
3060 g.writeln('static inline bool atomic_compare_exchange_weak_u16(void* ptr, u16* expected, u16 desired) { return __atomic_compare_exchange_2((u16*)ptr, expected, desired, 5, 5); }')
3061 g.writeln('static inline bool atomic_compare_exchange_weak_u32(void* ptr, u32* expected, u32 desired) { return __atomic_compare_exchange_4((u32*)ptr, expected, desired, 5, 5); }')
3062 g.writeln('static inline bool atomic_compare_exchange_weak_u64(void* ptr, u64* expected, u64 desired) { return __atomic_compare_exchange_8((u64*)ptr, expected, desired, 5, 5); }')
3063 g.writeln('#else')
3064 g.writeln('static inline void atomic_store_byte(void* ptr, byte val) { __atomic_store_n((byte*)ptr, val, 5); }')
3065 g.writeln('static inline void atomic_store_u16(void* ptr, u16 val) { __atomic_store_n((u16*)ptr, val, 5); }')
3066 g.writeln('static inline void atomic_store_u32(void* ptr, u32 val) { __atomic_store_n((u32*)ptr, val, 5); }')
3067 g.writeln('static inline void atomic_store_u64(void* ptr, u64 val) { __atomic_store_n((u64*)ptr, val, 5); }')
3068 g.writeln('static inline void atomic_store_ptr(void* ptr, void* val) { __atomic_store_n((void**)ptr, val, 5); }')
3069 g.writeln('static inline bool atomic_compare_exchange_strong_u16(void* ptr, u16* expected, u16 desired) { return __atomic_compare_exchange_n((u16*)ptr, expected, desired, 0, 5, 5); }')
3070 g.writeln('static inline bool atomic_compare_exchange_strong_u32(void* ptr, u32* expected, u32 desired) { return __atomic_compare_exchange_n((u32*)ptr, expected, desired, 0, 5, 5); }')
3071 g.writeln('static inline bool atomic_compare_exchange_strong_ptr(void* ptr, void* expected, ptrdiff_t desired) { return __atomic_compare_exchange_n((void**)ptr, (void**)expected, (void*)desired, 0, 5, 5); }')
3072 g.writeln('static inline bool atomic_compare_exchange_weak_byte(void* ptr, byte* expected, byte desired) { return __atomic_compare_exchange_n((byte*)ptr, expected, desired, 1, 5, 5); }')
3073 g.writeln('static inline bool atomic_compare_exchange_weak_u16(void* ptr, u16* expected, u16 desired) { return __atomic_compare_exchange_n((u16*)ptr, expected, desired, 1, 5, 5); }')
3074 g.writeln('static inline bool atomic_compare_exchange_weak_u32(void* ptr, u32* expected, u32 desired) { return __atomic_compare_exchange_n((u32*)ptr, expected, desired, 1, 5, 5); }')
3075 g.writeln('static inline bool atomic_compare_exchange_weak_u64(void* ptr, u64* expected, u64 desired) { return __atomic_compare_exchange_n((u64*)ptr, expected, desired, 1, 5, 5); }')
3076 g.writeln('#endif')
3077 g.writeln('static inline bool atomic_compare_exchange_weak_ptr(void* ptr, void* expected, ptrdiff_t desired) { return atomic_compare_exchange_strong_ptr(ptr, expected, desired); }')
3078 g.writeln('static inline void cpu_relax(void) { __asm__ __volatile__("" ::: "memory"); }')
3079}
3080
3081fn (mut g FlatGen) builtin_abi_decls() {
3082 if !g.has_builtins {
3083 return
3084 }
3085 g.libc_compat_decls()
3086 g.writeln('#define array_new(elem_size, len, cap) __new_array((len), (cap), (elem_size))')
3087 g.writeln('#define array_push array__push')
3088 g.writeln('void array__push_many(array* a, void* val, int size);')
3089 g.writeln('#define array_push_many_ptr(a, val, size) array__push_many((a), (void*)(val), (size))')
3090 g.writeln('#define array_get array__get')
3091 g.writeln('#define array_set(a, i, ...) array__set(&(a), (i), __VA_ARGS__)')
3092 g.writeln('array array__clone(array* a);')
3093 g.writeln('#define array_slice array__slice')
3094 g.writeln('#define array_delete array__delete')
3095 g.writeln('#define array_ensure_cap array__ensure_cap')
3096 g.writeln('#define map__get_or_set map__get_and_set')
3097 g.writeln('#ifndef V_COMMIT_HASH')
3098 g.writeln('#define V_COMMIT_HASH ""')
3099 g.writeln('#endif')
3100 // Weak fallbacks for the heap-tracking hooks. A program that provides real
3101 // implementations (e.g. a `vheap_alloc`/`vheap_free` from a linked C file, as
3102 // some projects do) overrides these without a redefinition/static-vs-non-static
3103 // clash against that file's own non-static prototype.
3104 g.writeln('__attribute__((weak)) void vheap_alloc(void* p, u64 n) { (void)p; (void)n; }')
3105 g.writeln('__attribute__((weak)) void vheap_free(void* p) { (void)p; }')
3106 g.filelock_compat_decls()
3107 g.prealloc_atomic_compat_decls()
3108 g.atomic_builtin_compat_decls()
3109 g.writeln('static inline double math__abs(double a) { return a < 0 ? -a : a; }')
3110 g.writeln('static inline double math__min(double a, double b) { return a < b ? a : b; }')
3111 g.writeln('static const u64 _wyp[4] = {0x2d358dccaa6c78a5ull, 0x8bb84b93962eacc9ull, 0x4b33a62ed433d4a3ull, 0x4d5a2da51de1aa47ull};')
3112 g.writeln('static inline u64 _wymix(u64 a, u64 b) { u64 ha = a >> 32, hb = b >> 32, la = (u32)a, lb = (u32)b, hi, lo; u64 rh = ha * hb, rm0 = ha * lb, rm1 = hb * la, rl = la * lb, t = rl + (rm0 << 32), c = t < rl; lo = t + (rm1 << 32); c += lo < t; hi = rh + (rm0 >> 32) + (rm1 >> 32) + c; return lo ^ hi; }')
3113 g.writeln('static inline u64 wyhash64(u64 a, u64 b) { a ^= _wyp[0]; b ^= _wyp[1]; a *= 0xa0761d6478bd642full; b *= 0xe7037ed1a0b428dbull; return (a ^ (a >> 32)) ^ (b ^ (b >> 32)); }')
3114 g.writeln('static inline u64 wyhash(const void* key, size_t len, u64 seed, const u64* secret) { const unsigned char* p = (const unsigned char*)key; u64 h = seed ^ secret[0] ^ (u64)len; for (size_t i = 0; i < len; i++) h = wyhash64(h ^ (u64)p[i], secret[(i + 1) & 3]); return h; }')
3115 g.writeln('#define v_signal_with_handler_cast(sig, handler) signal((sig), ((void (*)(int))(handler)))')
3116 g.writeln('string string__clone(string a);')
3117 g.writeln('void string__free(string* s);')
3118 g.writeln('static inline int array_index_int(Array a, int val) { for (int i = 0; i < a.len; i++) if (((int*)a.data)[i] == val) return i; return -1; }')
3119 g.writeln('static inline bool array_contains_int(Array a, int val) { return array_index_int(a, val) >= 0; }')
3120 g.writeln('static inline int array_index_u8(Array a, u8 val) { for (int i = 0; i < a.len; i++) if (((u8*)a.data)[i] == val) return i; return -1; }')
3121 g.writeln('static inline bool array_contains_u8(Array a, u8 val) { return array_index_u8(a, val) >= 0; }')
3122 g.writeln('static inline int array_index_string(Array a, string val) { string* data = (string*)a.data; for (int i = 0; i < a.len; i++) if (data[i].len == val.len && memcmp(data[i].str, val.str, val.len) == 0) return i; return -1; }')
3123 g.writeln('static inline bool array_contains_string(Array a, string val) { return array_index_string(a, val) >= 0; }')
3124 g.writeln('static inline bool array_eq_raw(Array a, Array b, int elem_size) { return a.len == b.len && (a.len == 0 || memcmp(a.data, b.data, (size_t)a.len * elem_size) == 0); }')
3125 g.writeln('static inline bool array_eq_string(Array a, Array b) { if (a.len != b.len) return false; string* ad = (string*)a.data; string* bd = (string*)b.data; for (int i = 0; i < a.len; i++) if (ad[i].len != bd[i].len || memcmp(ad[i].str, bd[i].str, ad[i].len) != 0) return false; return true; }')
3126 g.writeln('static inline bool fixed_array_contains_string(const string* a, int len, string val) { for (int i = 0; i < len; i++) if (a[i].len == val.len && memcmp(a[i].str, val.str, val.len) == 0) return true; return false; }')
3127 g.writeln('static inline bool fixed_array_contains_u8(const u8* a, int len, u8 val) { for (int i = 0; i < len; i++) if (a[i] == val) return true; return false; }')
3128 g.writeln('static inline bool fixed_array_contains_int(const int* a, int len, int val) { for (int i = 0; i < len; i++) if (a[i] == val) return true; return false; }')
3129 g.writeln('static inline string Array_str(Array a) { if (a.element_size == 1) { u8* buf = (u8*)malloc((size_t)a.len + 1); if (a.len > 0) memcpy(buf, a.data, (size_t)a.len); buf[a.len] = 0; return (string){buf, a.len, 0}; } return (string){(u8*)"[]", 2, 1}; }')
3130 g.writeln('#ifndef max_int')
3131 g.writeln('#define max_int max_i32')
3132 g.writeln('#endif')
3133 g.writeln('#ifndef min_int')
3134 g.writeln('#define min_int min_i32')
3135 g.writeln('#endif')
3136 g.writeln('')
3137}
3138
3139fn (mut g FlatGen) filelock_compat_decls() {
3140 g.writeln('#ifdef _WIN32')
3141 g.writeln('#include <windows.h>')
3142 g.writeln('int v_filelock_lock(void* handle, int exclusive, int immediate, u64 start, u64 len) {')
3143 g.writeln('\tOVERLAPPED overlap;')
3144 g.writeln('\tmemset(&overlap, 0, sizeof(overlap));')
3145 g.writeln('\toverlap.Offset = (DWORD)(start & 0xffffffffULL);')
3146 g.writeln('\toverlap.OffsetHigh = (DWORD)(start >> 32);')
3147 g.writeln('\tDWORD flags = immediate ? LOCKFILE_FAIL_IMMEDIATELY : 0;')
3148 g.writeln('\tif (exclusive) { flags |= LOCKFILE_EXCLUSIVE_LOCK; }')
3149 g.writeln('\tDWORD low = len == 0 ? MAXDWORD : (DWORD)(len & 0xffffffffULL);')
3150 g.writeln('\tDWORD high = len == 0 ? MAXDWORD : (DWORD)(len >> 32);')
3151 g.writeln('\treturn LockFileEx((HANDLE)handle, flags, 0, low, high, &overlap) ? 0 : -1;')
3152 g.writeln('}')
3153 g.writeln('int v_filelock_unlock(void* handle, u64 start, u64 len) {')
3154 g.writeln('\tOVERLAPPED overlap;')
3155 g.writeln('\tmemset(&overlap, 0, sizeof(overlap));')
3156 g.writeln('\toverlap.Offset = (DWORD)(start & 0xffffffffULL);')
3157 g.writeln('\toverlap.OffsetHigh = (DWORD)(start >> 32);')
3158 g.writeln('\tDWORD low = len == 0 ? MAXDWORD : (DWORD)(len & 0xffffffffULL);')
3159 g.writeln('\tDWORD high = len == 0 ? MAXDWORD : (DWORD)(len >> 32);')
3160 g.writeln('\treturn UnlockFileEx((HANDLE)handle, 0, low, high, &overlap) ? 0 : -1;')
3161 g.writeln('}')
3162 g.writeln('#else')
3163 g.writeln('int v_filelock_lock(i32 fd, i32 exclusive, i32 immediate, u64 start, u64 len) {')
3164 g.writeln('\tstruct flock fl;')
3165 g.writeln('\tmemset(&fl, 0, sizeof(fl));')
3166 g.writeln('\tfl.l_type = exclusive ? F_WRLCK : F_RDLCK;')
3167 g.writeln('\tfl.l_whence = SEEK_SET;')
3168 g.writeln('\tfl.l_start = (off_t)start;')
3169 g.writeln('\tfl.l_len = len == 0 ? 0 : (off_t)len;')
3170 g.writeln('\treturn fcntl(fd, immediate ? F_SETLK : F_SETLKW, &fl);')
3171 g.writeln('}')
3172 g.writeln('int v_filelock_unlock(i32 fd, u64 start, u64 len) {')
3173 g.writeln('\tstruct flock fl;')
3174 g.writeln('\tmemset(&fl, 0, sizeof(fl));')
3175 g.writeln('\tfl.l_type = F_UNLCK;')
3176 g.writeln('\tfl.l_whence = SEEK_SET;')
3177 g.writeln('\tfl.l_start = (off_t)start;')
3178 g.writeln('\tfl.l_len = len == 0 ? 0 : (off_t)len;')
3179 g.writeln('\treturn fcntl(fd, F_SETLK, &fl);')
3180 g.writeln('}')
3181 g.writeln('#endif')
3182}
3183
3184fn (mut g FlatGen) collect_fixed_array_typedefs_needed() map[string]FixedArrayTypedefInfo {
3185 mut needed := map[string]FixedArrayTypedefInfo{}
3186 old_module := g.tc.cur_module
3187 for name, ret_type in g.tc.fn_ret_types {
3188 g.tc.cur_module = module_from_qualified_name(name)
3189 g.collect_fixed_array_typedef(ret_type, mut needed)
3190 }
3191 for name, param_types in g.tc.fn_param_types {
3192 g.tc.cur_module = module_from_qualified_name(name)
3193 for param_type in param_types {
3194 g.collect_fixed_array_typedef(param_type, mut needed)
3195 }
3196 }
3197 for name, fields in g.tc.structs {
3198 g.tc.cur_module = g.fixed_array_typedef_type_module(name, old_module)
3199 for field in fields {
3200 g.collect_fixed_array_typedef(field.typ, mut needed)
3201 }
3202 }
3203 for name, fields in g.tc.interface_fields {
3204 g.tc.cur_module = module_from_qualified_name(name)
3205 for field in fields {
3206 g.collect_fixed_array_typedef(field.typ, mut needed)
3207 }
3208 }
3209 for name, typ in g.global_types {
3210 g.tc.cur_module = g.global_modules[name] or { old_module }
3211 g.collect_fixed_array_typedef(typ, mut needed)
3212 }
3213 for _, typ in g.tc.c_globals {
3214 g.tc.cur_module = old_module
3215 g.collect_fixed_array_typedef(typ, mut needed)
3216 }
3217 for name, typ in g.tc.const_types {
3218 g.tc.cur_module = g.const_modules[name] or { old_module }
3219 g.collect_fixed_array_typedef(typ, mut needed)
3220 }
3221 g.tc.cur_module = old_module
3222 return needed
3223}
3224
3225fn (mut g FlatGen) fixed_array_typedefs() {
3226 needed := g.collect_fixed_array_typedefs_needed()
3227 old_len := g.emitted_fixed_array_typedefs.len
3228 for name, info in needed {
3229 g.emit_fixed_array_typedef(name, info, needed, mut g.emitted_fixed_array_typedefs)
3230 }
3231 // Return wrappers for non-early element types (struct/`string`/nested fixed array):
3232 // their bare typedef (above) and element definitions are available now, so a C
3233 // function returning `[N]Foo`/`[N]string` can return the wrapper struct instead of the
3234 // raw array type C rejects. Sorted for deterministic output.
3235 mut wrapper_names := []string{}
3236 for name, _ in needed {
3237 wrapper_names << name
3238 }
3239 wrapper_names.sort()
3240 mut emitted_wrapper := false
3241 for name in wrapper_names {
3242 if name !in g.fixed_array_ret_wrappers {
3243 continue
3244 }
3245 info := needed[name] or { continue }
3246 if fixed_array_typedef_is_early(info.arr) {
3247 continue
3248 }
3249 // Completes the struct forward-declared in fixed_array_early_typedefs().
3250 g.emit_fixed_array_ret_wrapper(name, info, true)
3251 emitted_wrapper = true
3252 }
3253 if g.emitted_fixed_array_typedefs.len > old_len || emitted_wrapper {
3254 g.writeln('')
3255 }
3256}
3257
3258// fixed_array_typedef_is_early reports whether a fixed array's bare typedef can be
3259// emitted before struct definitions: its element chain must bottom out in a
3260// primitive/pointer/enum (not a struct or `string`, whose definitions come later).
3261fn fixed_array_typedef_is_early(arr types.ArrayFixed) bool {
3262 elem := arr.elem_type
3263 if elem is types.ArrayFixed {
3264 return fixed_array_typedef_is_early(elem)
3265 }
3266 return fixed_array_elem_is_early_complete(elem)
3267}
3268
3269// populate_fixed_array_ret_wrappers records which fixed-array types get a return
3270// wrapper struct. It must run before function bodies are generated, so that fn
3271// signatures, return statements and call sites all agree on whether a given
3272// fixed-array return is wrapped. EVERY fixed-array type is wrapped, because C
3273// functions and fn pointers cannot return a raw array type regardless of the element:
3274// primitive/pointer/enum element wrappers are emitted early (before structs), while
3275// struct/`string`/nested element wrappers are emitted by fixed_array_typedefs(), after
3276// the element type is defined.
3277fn (mut g FlatGen) populate_fixed_array_ret_wrappers() {
3278 needed := g.collect_fixed_array_typedefs_needed()
3279 for name, _ in needed {
3280 g.fixed_array_ret_wrappers[name] = true
3281 }
3282}
3283
3284// emit_fixed_array_ret_wrapper writes the one-field `struct { T ret_arr[N]; }` wrapper
3285// for a fixed-array return type. The element type's C definition must already be emitted.
3286// `tagged` completes a previously forward-declared named struct (`struct X { ... };`),
3287// used for non-early element types whose wrapper is referenced by an fn-pointer typedef
3288// emitted earlier; otherwise a fresh anonymous typedef is written.
3289fn (mut g FlatGen) emit_fixed_array_ret_wrapper(name string, info FixedArrayTypedefInfo, tagged bool) {
3290 arr := info.arr
3291 old_module := g.tc.cur_module
3292 g.tc.cur_module = info.module
3293 elem_ct := g.tc.c_type(arr.elem_type)
3294 len_expr := g.fixed_array_len_value(arr)
3295 g.tc.cur_module = old_module
3296 wname := fixed_array_ret_wrapper_name(name)
3297 if tagged {
3298 g.writeln('struct ${wname} { ${elem_ct} ret_arr[${len_expr}]; };')
3299 } else {
3300 g.writeln('typedef struct { ${elem_ct} ret_arr[${len_expr}]; } ${wname};')
3301 }
3302}
3303
3304// emit_fixed_array_ret_wrapper_forward forward-declares a named return-wrapper struct so an
3305// fn-pointer typedef can name it as a (by-value) return type before the wrapper's element
3306// type is defined; the struct body is completed later by emit_fixed_array_ret_wrapper.
3307fn (mut g FlatGen) emit_fixed_array_ret_wrapper_forward(name string) {
3308 wname := fixed_array_ret_wrapper_name(name)
3309 g.writeln('typedef struct ${wname} ${wname};')
3310}
3311
3312// fixed_array_early_typedefs emits, before the fn-ptr typedef block, the bare
3313// typedefs for fixed arrays whose element chain is a primitive/pointer/enum, plus
3314// a one-field struct wrapper `struct { T ret_arr[N]; }` for each fixed-array
3315// return type. fn-ptr typedefs may name a fixed array in param position (bare
3316// typedef) or return position (wrapper); both must therefore be defined first. C
3317// functions cannot return raw array types, hence the wrapper (as V1 does). Bare
3318// typedefs of struct/`string`-element fixed arrays are deferred to
3319// fixed_array_typedefs(), after the struct definitions.
3320fn (mut g FlatGen) fixed_array_early_typedefs() {
3321 needed := g.collect_fixed_array_typedefs_needed()
3322 mut names := []string{}
3323 for name, _ in needed {
3324 names << name
3325 }
3326 names.sort()
3327 mut emitted_any := false
3328 for name in names {
3329 info := needed[name] or { continue }
3330 if !fixed_array_typedef_is_early(info.arr) {
3331 continue
3332 }
3333 g.emit_fixed_array_typedef(name, info, needed, mut g.emitted_fixed_array_typedefs)
3334 emitted_any = true
3335 }
3336 // Wrapper structs for fixed-array return types. Primitive/pointer/enum element wrappers
3337 // are fully defined here. Struct/`string`/nested element wrappers can't be defined yet
3338 // (their element type comes later), but an fn-pointer typedef in the next block may name
3339 // one as a return type, so forward-declare the named struct now and complete it in
3340 // fixed_array_typedefs(), after the element definitions.
3341 for name in names {
3342 if name !in g.fixed_array_ret_wrappers {
3343 continue
3344 }
3345 info := needed[name] or { continue }
3346 if fixed_array_typedef_is_early(info.arr) {
3347 g.emit_fixed_array_ret_wrapper(name, info, false)
3348 } else {
3349 g.emit_fixed_array_ret_wrapper_forward(name)
3350 }
3351 emitted_any = true
3352 }
3353 if emitted_any {
3354 g.writeln('')
3355 }
3356}
3357
3358// fixed_array_ret_wrapper_name is the struct name wrapping a fixed-array return.
3359fn fixed_array_ret_wrapper_name(bare_c_name string) string {
3360 return '_v_ret_${bare_c_name}'
3361}
3362
3363// fixed_array_elem_is_early_complete reports whether a fixed-array element type's
3364// C definition is available before the fn_ptr/return-wrapper typedef block (i.e.
3365// it is a primitive, pointer, or enum — not a struct or nested fixed array, whose
3366// bare typedefs/definitions are emitted later).
3367fn fixed_array_elem_is_early_complete(elem types.Type) bool {
3368 return elem is types.Primitive || elem is types.Pointer || elem is types.Enum
3369}
3370
3371// fn_return_type_name is the C type to write for a function/fn-ptr return type,
3372// substituting the fixed-array wrapper struct when one exists.
3373fn (mut g FlatGen) fn_return_type_name(t types.Type) string {
3374 if t is types.ArrayFixed {
3375 bare := g.tc.c_type(t)
3376 if bare in g.fixed_array_ret_wrappers {
3377 return fixed_array_ret_wrapper_name(bare)
3378 }
3379 }
3380 ct := g.optional_type_name(t)
3381 // A function/fn-ptr-valued return (`fn f() fn () int`) has the internal `fn_ptr:...`
3382 // encoding for its C type; map it to the shared `_fn_ptr_N` typedef, since a C function
3383 // cannot be declared returning that raw encoding (it would emit invalid C).
3384 if ct.starts_with('fn_ptr:') {
3385 return g.resolve_fn_ptr_type(ct)
3386 }
3387 return ct
3388}
3389
3390// fn_ptr_return_ct maps a fixed-array return c_type name (string form, used by the
3391// fn-ptr typedef machinery) to its wrapper struct name when one exists.
3392fn (g &FlatGen) fn_ptr_return_ct(ct string) string {
3393 if ct.starts_with('Array_fixed_') && ct in g.fixed_array_ret_wrappers {
3394 return fixed_array_ret_wrapper_name(ct)
3395 }
3396 return ct
3397}
3398
3399// emit_ready_fixed_array_typedefs emits, during the topological struct emission,
3400// any fixed-array bare typedef whose element type is now fully defined (i.e. its
3401// element struct has been emitted). Struct fields reference the typedef name
3402// (`Array_fixed_vec__Vec4_f32 x`), so the typedef must precede any struct that
3403// uses it — which a single later pass cannot guarantee.
3404fn (mut g FlatGen) emit_ready_fixed_array_typedefs(needed map[string]FixedArrayTypedefInfo, emitted_structs map[string]bool) {
3405 for name, info in needed {
3406 if g.emitted_fixed_array_typedefs[name] {
3407 continue
3408 }
3409 if g.fixed_array_elem_defined(info.arr, emitted_structs) {
3410 g.emit_fixed_array_typedef(name, info, needed, mut g.emitted_fixed_array_typedefs)
3411 }
3412 }
3413}
3414
3415// fixed_array_elem_defined reports whether a fixed array's element type is fully
3416// available: a primitive/pointer/enum (always), or a struct/`string` already
3417// emitted. Aliases are unwrapped to their underlying type first (`SimdFloat4` ->
3418// `vec.Vec4[f32]` struct), so an alias to a not-yet-emitted struct is not treated
3419// as ready.
3420fn (g &FlatGen) fixed_array_elem_defined(arr types.ArrayFixed, emitted_structs map[string]bool) bool {
3421 return g.fixed_array_type_defined(arr.elem_type, emitted_structs)
3422}
3423
3424fn (g &FlatGen) fixed_array_type_defined(typ0 types.Type, emitted_structs map[string]bool) bool {
3425 mut typ := typ0
3426 for typ is types.Alias {
3427 typ = typ.base_type
3428 }
3429 if typ is types.ArrayFixed {
3430 return g.fixed_array_type_defined(typ.elem_type, emitted_structs)
3431 }
3432 if typ is types.Struct {
3433 return g.tc.c_type(typ) in emitted_structs
3434 }
3435 if typ is types.String {
3436 return 'string' in emitted_structs
3437 }
3438 return true
3439}
3440
3441fn (mut g FlatGen) fixed_array_typedef_type_module(name string, fallback string) string {
3442 if info := g.struct_decl_infos[name] {
3443 return info.module
3444 }
3445 mod := module_from_qualified_name(name)
3446 if mod.len > 0 {
3447 return mod
3448 }
3449 return fallback
3450}
3451
3452fn module_from_qualified_name(name string) string {
3453 if name.contains('.') {
3454 return name.all_before_last('.')
3455 }
3456 if name.contains('__') {
3457 return name.all_before_last('__').replace('__', '.')
3458 }
3459 return ''
3460}
3461
3462fn fixed_array_typedef_module_priority(module_name string) int {
3463 if module_name.len == 0 || module_name == 'C' {
3464 return 0
3465 }
3466 if module_name == 'main' || module_name == 'builtin' {
3467 return 1
3468 }
3469 return 2
3470}
3471
3472fn (mut g FlatGen) collect_fixed_array_typedef(typ types.Type, mut needed map[string]FixedArrayTypedefInfo) {
3473 if typ is types.ArrayFixed {
3474 name := g.tc.c_type(typ)
3475 existing_priority := if name in needed {
3476 fixed_array_typedef_module_priority(needed[name].module)
3477 } else {
3478 -1
3479 }
3480 current_priority := fixed_array_typedef_module_priority(g.tc.cur_module)
3481 if name !in needed || current_priority > existing_priority {
3482 needed[name] = FixedArrayTypedefInfo{
3483 arr: typ
3484 module: g.tc.cur_module
3485 }
3486 }
3487 g.collect_fixed_array_typedef(typ.elem_type, mut needed)
3488 } else if typ is types.Pointer {
3489 g.collect_fixed_array_typedef(typ.base_type, mut needed)
3490 } else if typ is types.Alias {
3491 g.collect_fixed_array_typedef(typ.base_type, mut needed)
3492 } else if typ is types.OptionType {
3493 g.collect_fixed_array_typedef(typ.base_type, mut needed)
3494 } else if typ is types.ResultType {
3495 g.collect_fixed_array_typedef(typ.base_type, mut needed)
3496 } else if typ is types.Array {
3497 g.collect_fixed_array_typedef(typ.elem_type, mut needed)
3498 } else if typ is types.Map {
3499 g.collect_fixed_array_typedef(typ.key_type, mut needed)
3500 g.collect_fixed_array_typedef(typ.value_type, mut needed)
3501 } else if typ is types.FnType {
3502 for param in typ.params {
3503 g.collect_fixed_array_typedef(param, mut needed)
3504 }
3505 g.collect_fixed_array_typedef(typ.return_type, mut needed)
3506 } else if typ is types.MultiReturn {
3507 for item in typ.types {
3508 g.collect_fixed_array_typedef(item, mut needed)
3509 }
3510 }
3511}
3512
3513fn (mut g FlatGen) emit_fixed_array_typedef(name string, info FixedArrayTypedefInfo, needed map[string]FixedArrayTypedefInfo, mut emitted map[string]bool) {
3514 if emitted[name] {
3515 return
3516 }
3517 arr := info.arr
3518 old_module := g.tc.cur_module
3519 g.tc.cur_module = info.module
3520 if arr.elem_type is types.ArrayFixed {
3521 inner_name := g.tc.c_type(arr.elem_type)
3522 if inner := needed[inner_name] {
3523 g.emit_fixed_array_typedef(inner_name, inner, needed, mut emitted)
3524 }
3525 }
3526 elem_ct := g.tc.c_type(arr.elem_type)
3527 len_expr := g.fixed_array_len_value(arr)
3528 g.writeln('typedef ${elem_ct} ${name}[${len_expr}];')
3529 g.tc.cur_module = old_module
3530 emitted[name] = true
3531}
3532
3533fn (mut g FlatGen) global_decls() {
3534 old_module := g.tc.cur_module
3535 for name, typ in g.global_types {
3536 if mod := g.global_modules[name] {
3537 g.tc.cur_module = mod
3538 } else {
3539 g.tc.cur_module = old_module
3540 }
3541 if typ is types.ArrayFixed {
3542 c_elem, dims := g.fixed_array_decl_parts(typ)
3543 init := if g.has_zero_sized_leading_init_slot(typ) { '' } else { ' = {0}' }
3544 g.writeln('${c_elem} ${c_name(name)}${dims}${init};')
3545 continue
3546 }
3547 ct := g.tc.c_type(typ)
3548 if ct == 'void' {
3549 continue
3550 }
3551 if name.starts_with('C.') {
3552 continue
3553 }
3554 init := if g.can_use_global_brace_zero_init(typ, ct) { ' = {0}' } else { '' }
3555 g.writeln('${ct} ${c_name(name)}${init};')
3556 }
3557 g.tc.cur_module = old_module
3558 if g.global_types.len > 0 {
3559 g.writeln('')
3560 }
3561 g.emit_global_inits()
3562}
3563
3564// emit_global_inits queues assignments for `__global x = expr` declarations into
3565// _vinit. The C globals are emitted zero-initialized above; their initializer
3566// expressions (often function calls like `new_timers(...)`) cannot be C static
3567// initializers, so they must run at startup. Without this, such globals stay
3568// NULL/zero and the first access segfaults.
3569//
3570// Plain initializers are emitted as `name = expr;`. Fixed-array globals are
3571// copied from a generated compound literal with `memmove`, since C arrays are
3572// not assignable. `&Struct{}` is emitted as a self-contained heap allocation
3573// (`(T*)memdup(&(T){...}, sizeof(T))`), so it is safe. Other prefix/array
3574// initializers that would need a dropped temporary are skipped, leaving the
3575// global zero/NULL -- no regression versus never initializing globals at all.
3576fn (mut g FlatGen) emit_global_inits() {
3577 old_module := g.tc.cur_module
3578 for qname in g.global_init_order {
3579 val_id := g.global_inits[qname] or { continue }
3580 if int(val_id) < 0 {
3581 continue
3582 }
3583 // g_main_argc/g_main_argv are filled in by main's preamble (from argc/argv)
3584 // *before* _vinit runs, and are zero by default in C anyway. Re-emitting their
3585 // `= 0` initializer here would clobber the real argv, leaving os.args empty.
3586 cqname := c_name(qname)
3587 if cqname == 'g_main_argc' || cqname == 'g_main_argv' {
3588 continue
3589 }
3590 if mod := g.global_modules[qname] {
3591 g.tc.cur_module = mod
3592 } else {
3593 g.tc.cur_module = old_module
3594 }
3595 if typ := g.global_types[qname] {
3596 if typ is types.ArrayFixed {
3597 target := c_name(qname)
3598 g.queue_fixed_array_runtime_init(target, val_id, typ)
3599 continue
3600 }
3601 }
3602 if !g.is_safe_global_init(val_id) {
3603 continue
3604 }
3605 tmp_sb := g.sb
3606 tmp_line_start := g.line_start
3607 g.sb = strings.new_builder(64)
3608 g.line_start = true
3609 g.gen_expr(val_id)
3610 expr_str := g.sb.str()
3611 g.sb = tmp_sb
3612 g.line_start = tmp_line_start
3613 if expr_str.trim_space().len == 0 {
3614 continue
3615 }
3616 target := c_name(qname)
3617 g.runtime_inits << '\t${target} = ${expr_str};'
3618 if typ := g.global_types[qname] {
3619 if typ is types.Map {
3620 g.queue_map_literal_sets(target, val_id, typ)
3621 }
3622 }
3623 }
3624 g.tc.cur_module = old_module
3625}
3626
3627// is_safe_global_init reports whether a global initializer can be emitted as a
3628// self-contained `name = expr;` assignment in _vinit, i.e. without auxiliary
3629// declarations/temporaries that the global context cannot host.
3630fn (g &FlatGen) is_safe_global_init(val_id flat.NodeId) bool {
3631 if int(val_id) < 0 {
3632 return false
3633 }
3634 node := g.a.nodes[int(val_id)]
3635 if node.kind == .prefix {
3636 // `&Struct{}` becomes an inline `(T*)memdup(&(T){...}, sizeof(T))`, which is
3637 // self-contained; allow it. Other prefixes (e.g. `&local`) would need a
3638 // dropped temporary, so skip them.
3639 if node.op == .amp && node.children_count > 0 {
3640 child := g.a.nodes[int(g.a.child(&node, 0))]
3641 return child.kind == .struct_init || child.kind == .assoc
3642 }
3643 return false
3644 }
3645 return match node.kind {
3646 .array_literal, .array_init {
3647 // Array literals need a backing temp the transformer drops for globals;
3648 // leave them zero/NULL instead of emitting a reference to an undeclared
3649 // symbol.
3650 false
3651 }
3652 else {
3653 true
3654 }
3655 }
3656}
3657
3658fn (g &FlatGen) const_get_deps(val_id flat.NodeId) []string {
3659 mut deps := []string{}
3660 g.const_collect_deps(val_id, mut deps)
3661 return deps
3662}
3663
3664fn (g &FlatGen) const_collect_deps(val_id flat.NodeId, mut deps []string) {
3665 if int(val_id) < 0 || int(val_id) >= g.a.nodes.len {
3666 return
3667 }
3668 node := g.a.nodes[int(val_id)]
3669 if node.kind == .ident || node.kind == .selector {
3670 const_name := g.const_ref_name_from_node(node)
3671 if const_name.len > 0 {
3672 deps << const_name
3673 }
3674 }
3675 for i in 0 .. node.children_count {
3676 g.const_collect_deps(g.a.child(&node, i), mut deps)
3677 }
3678}
3679
3680fn (g &FlatGen) const_refs_other_const(val_id flat.NodeId) bool {
3681 if int(val_id) < 0 || int(val_id) >= g.a.nodes.len {
3682 return false
3683 }
3684 node := g.a.nodes[int(val_id)]
3685 if node.kind == .ident || node.kind == .selector {
3686 return g.const_ref_name_from_node(node).len > 0
3687 }
3688 for i in 0 .. node.children_count {
3689 if g.const_refs_other_const(g.a.child(&node, i)) {
3690 return true
3691 }
3692 }
3693 return false
3694}
3695
3696fn (mut g FlatGen) emit_const(name string, val_id flat.NodeId) {
3697 old_module := g.tc.cur_module
3698 if name in g.const_modules {
3699 g.tc.cur_module = g.const_modules[name]
3700 }
3701 val_node := g.a.nodes[int(val_id)]
3702 if val_node.kind == .empty {
3703 g.tc.cur_module = old_module
3704 return
3705 }
3706 expr_str := if g.is_const_expr(val_id) {
3707 g.const_expr_to_string(val_id, []string{})
3708 } else {
3709 g.expr_to_string(val_id)
3710 }
3711 if expr_str.trim_space().len == 0 {
3712 g.tc.cur_module = old_module
3713 return
3714 }
3715 v_type := if val_node.kind == .offsetof_expr {
3716 types.Type(types.usize_)
3717 } else {
3718 g.tc.resolve_type(val_id)
3719 }
3720 ct := g.tc.c_type(v_type)
3721 qname := g.const_ident_c_name(name)
3722 mut is_static_const := g.is_const_expr(val_id) && !g.const_expr_needs_runtime_storage(expr_str)
3723 if v_type is types.ArrayFixed && v_type.elem_type is types.ArrayFixed {
3724 is_static_const = false
3725 }
3726 if !is_static_const {
3727 if v_type is types.ArrayFixed {
3728 c_elem, dims := g.fixed_array_decl_parts(v_type)
3729 g.writeln('${c_elem} ${qname}${dims};')
3730 g.queue_fixed_array_runtime_init(qname, val_id, v_type)
3731 } else if ct != 'void' {
3732 g.writeln('${ct} ${qname};')
3733 // The initializer is not a compile-time constant (e.g. `os.args =
3734 // arguments()`), so it cannot be a C static initializer. Run it at startup
3735 // in _vinit; otherwise the const stays zero/empty and first use is wrong.
3736 g.runtime_inits << '\t${qname} = ${expr_str};'
3737 if v_type is types.Map {
3738 g.queue_map_literal_sets(qname, val_id, v_type)
3739 }
3740 }
3741 g.tc.cur_module = old_module
3742 return
3743 }
3744 if v_type is types.String {
3745 g.writeln('string ${qname} = ${expr_str};')
3746 } else if v_type is types.ArrayFixed {
3747 c_elem, dims := g.fixed_array_decl_parts(v_type)
3748 g.writeln('const ${c_elem} ${qname}${dims} = ${expr_str};')
3749 } else if v_type is types.Primitive || v_type is types.Char || v_type is types.Rune
3750 || v_type is types.ISize || v_type is types.USize || v_type is types.Enum
3751 || ct in ['bool', 'char', 'i8', 'i16', 'i32', 'int', 'i64', 'u8', 'u16', 'u32', 'u64', 'f32', 'f64', 'float', 'double', 'isize', 'usize'] {
3752 if qname == 'max_len' && ct == 'int' {
3753 g.writeln('enum { ${qname} = ${expr_str} };')
3754 } else if g.name_collides_with_struct_field(qname) {
3755 // A `#define` whose name matches a struct field would wrongly expand every
3756 // `.field` access; emit a real `const` variable instead (C keeps member and
3757 // ordinary-identifier namespaces separate, so there is no collision).
3758 g.writeln('static const ${ct} ${qname} = ${expr_str};')
3759 } else {
3760 g.writeln('#define ${qname} (${expr_str})')
3761 }
3762 } else {
3763 g.writeln('const ${ct} ${qname} = ${expr_str};')
3764 }
3765 g.tc.cur_module = old_module
3766}
3767
3768// name_collides_with_struct_field reports whether a name is the C name of any struct
3769// field, building the set lazily on first use.
3770fn (mut g FlatGen) name_collides_with_struct_field(name string) bool {
3771 if g.field_name_set.len == 0 {
3772 for _, fields in g.tc.structs {
3773 for f in fields {
3774 g.field_name_set[c_field_name(f.name)] = true
3775 }
3776 }
3777 // Guard against an all-fieldless program re-scanning every call.
3778 g.field_name_set[''] = true
3779 }
3780 return name in g.field_name_set
3781}
3782
3783fn (g &FlatGen) const_expr_needs_runtime_storage(expr string) bool {
3784 return expr.contains('array_new(') || expr.contains('new_map(') || expr.contains('({')
3785 || expr.contains('__map_')
3786}
3787
3788fn (mut g FlatGen) queue_map_literal_sets(target string, val_id flat.NodeId, map_type types.Map) {
3789 if int(val_id) < 0 || int(val_id) >= g.a.nodes.len {
3790 return
3791 }
3792 node := g.a.nodes[int(val_id)]
3793 if node.kind != .map_init {
3794 return
3795 }
3796 c_key := g.tc.c_type(map_type.key_type)
3797 c_val := g.tc.c_type(map_type.value_type)
3798 for i := 0; i + 1 < node.children_count; i += 2 {
3799 key := g.expr_to_string_with_expected_type(g.a.child(&node, i), map_type.key_type)
3800 val := g.expr_to_string_with_expected_type(g.a.child(&node, i + 1), map_type.value_type)
3801 g.runtime_inits << '\tmap__set(&${target}, &(${c_key}[]){${key}}, &(${c_val}[]){${val}});'
3802 }
3803}
3804
3805fn (mut g FlatGen) queue_fixed_array_runtime_init(target string, val_id flat.NodeId, fixed types.ArrayFixed) bool {
3806 expr := g.fixed_array_compound_literal_expr(val_id, fixed)
3807 if expr.trim_space().len == 0 {
3808 return false
3809 }
3810 g.runtime_inits << '\tmemmove(${target}, ${expr}, sizeof(${target}));'
3811 return true
3812}
3813
3814fn (mut g FlatGen) fixed_array_compound_literal_expr(val_id flat.NodeId, fixed types.ArrayFixed) string {
3815 init := g.fixed_array_initializer_string(val_id, fixed)
3816 if init.trim_space().len == 0 {
3817 return ''
3818 }
3819 c_elem, dims := g.fixed_array_decl_parts(fixed)
3820 return '(${c_elem}${dims})${init}'
3821}
3822
3823fn (mut g FlatGen) fixed_array_initializer_string(val_id flat.NodeId, fixed types.ArrayFixed) string {
3824 if int(val_id) < 0 || int(val_id) >= g.a.nodes.len {
3825 return ''
3826 }
3827 node := g.a.nodes[int(val_id)]
3828 if node.kind == .postfix && node.children_count > 0 {
3829 return g.fixed_array_initializer_string(g.a.child(&node, 0), fixed)
3830 }
3831 if node.kind == .array_init && node.children_count == 0 {
3832 return '{0}'
3833 }
3834 if node.kind != .array_literal {
3835 return ''
3836 }
3837 mut parts := []string{}
3838 for i in 0 .. node.children_count {
3839 child_id := g.a.child(&node, i)
3840 if fixed.elem_type is types.ArrayFixed {
3841 parts << g.fixed_array_initializer_string(child_id, fixed.elem_type)
3842 } else {
3843 parts << g.fixed_array_elem_initializer_string(child_id, fixed.elem_type)
3844 }
3845 }
3846 return '{${parts.join(', ')}}'
3847}
3848
3849fn (mut g FlatGen) fixed_array_elem_initializer_string(val_id flat.NodeId, elem_type types.Type) string {
3850 if int(val_id) < 0 || int(val_id) >= g.a.nodes.len {
3851 return '0'
3852 }
3853 node := g.a.nodes[int(val_id)]
3854 if g.is_const_expr(val_id) && !(node.kind == .prefix && node.op == .amp) {
3855 const_val := g.const_expr_to_string(val_id, []string{})
3856 if const_val.trim_space().len > 0 {
3857 return const_val
3858 }
3859 }
3860 expr := g.expr_to_string_with_expected_type(val_id, elem_type)
3861 if expr.trim_space().len > 0 {
3862 return expr
3863 }
3864 return '0'
3865}
3866
3867fn (mut g FlatGen) precompute_consts() string {
3868 old_sb := g.sb
3869 old_line_start := g.line_start
3870 g.sb = strings.new_builder(1024)
3871 g.line_start = true
3872 mut emitted := map[string]bool{}
3873 mut deferred := []string{}
3874 mut names := g.const_init_order.clone()
3875 for name, _ in g.const_vals {
3876 if g.is_const_alias_name(name) || name in names {
3877 continue
3878 }
3879 names << name
3880 }
3881 for name in names {
3882 val_id := g.const_vals[name] or { continue }
3883 if g.is_const_alias_name(name) {
3884 continue
3885 }
3886 if int(val_id) < 0 || int(val_id) >= g.a.nodes.len {
3887 continue
3888 }
3889 old_module := g.tc.cur_module
3890 if name in g.const_modules {
3891 g.tc.cur_module = g.const_modules[name]
3892 }
3893 deps := g.const_get_deps(val_id)
3894 g.tc.cur_module = old_module
3895 mut all_met := true
3896 for dep in deps {
3897 if dep !in emitted {
3898 all_met = false
3899 break
3900 }
3901 }
3902 if !all_met {
3903 deferred << name
3904 } else {
3905 g.emit_const(name, val_id)
3906 emitted[name] = true
3907 }
3908 }
3909 for _ in 0 .. 20 {
3910 if deferred.len == 0 {
3911 break
3912 }
3913 mut remaining := []string{}
3914 for name in deferred {
3915 val_id := g.const_vals[name]
3916 deps := g.const_get_deps(val_id)
3917 mut all_met := true
3918 for dep in deps {
3919 if dep !in emitted {
3920 all_met = false
3921 break
3922 }
3923 }
3924 if all_met {
3925 g.emit_const(name, val_id)
3926 emitted[name] = true
3927 } else {
3928 remaining << name
3929 }
3930 }
3931 deferred = remaining.clone()
3932 }
3933 for name in deferred {
3934 g.emit_const(name, g.const_vals[name])
3935 }
3936 if g.const_vals.len > 0 {
3937 g.writeln('')
3938 }
3939 result := g.sb.str()
3940 // `.str()` copies out of the temporary const builder.
3941 unsafe { g.sb.free() }
3942 g.sb = old_sb
3943 g.line_start = old_line_start
3944 return result
3945}
3946
3947fn (g &FlatGen) is_const_expr(id flat.NodeId) bool {
3948 if int(id) < 0 || int(id) >= g.a.nodes.len {
3949 return false
3950 }
3951 node := g.a.nodes[int(id)]
3952 return match node.kind {
3953 .int_literal, .float_literal, .bool_literal, .char_literal, .string_literal, .enum_val,
3954 .sizeof_expr, .offsetof_expr {
3955 true
3956 }
3957 .prefix {
3958 if node.op == .amp {
3959 false
3960 } else {
3961 g.is_const_expr(g.a.child(&node, 0))
3962 }
3963 }
3964 .infix {
3965 g.is_const_expr(g.a.child(&node, 0)) && g.is_const_expr(g.a.child(&node, 1))
3966 }
3967 .paren {
3968 g.is_const_expr(g.a.child(&node, 0))
3969 }
3970 .cast_expr {
3971 g.is_const_expr(g.a.child(&node, 0))
3972 }
3973 .ident {
3974 g.const_ref_name(node.value).len > 0
3975 }
3976 .selector {
3977 const_name := g.const_ref_name_from_node(node)
3978 if const_name.len > 0 {
3979 true
3980 } else if node.children_count > 0 {
3981 base := g.a.child_node(&node, 0)
3982 base.kind == .ident && base.value == 'C'
3983 } else {
3984 false
3985 }
3986 }
3987 .array_literal {
3988 mut all_const := true
3989 for ci in 0 .. node.children_count {
3990 if !g.is_const_expr(g.a.child(&node, ci)) {
3991 all_const = false
3992 break
3993 }
3994 }
3995 all_const
3996 }
3997 .struct_init {
3998 mut all_const := true
3999 for ci in 0 .. node.children_count {
4000 child := g.a.child_node(&node, ci)
4001 if child.kind == .field_init {
4002 if ftyp := g.struct_field_type(node.value, child.value) {
4003 if ftyp is types.Array || ftyp is types.Map {
4004 all_const = false
4005 break
4006 }
4007 }
4008 }
4009 if child.children_count > 0 && !g.is_const_expr(g.a.child(child, 0)) {
4010 all_const = false
4011 break
4012 }
4013 }
4014 all_const
4015 }
4016 else {
4017 false
4018 }
4019 }
4020}
4021
4022fn (g &FlatGen) is_runtime_assignable(id flat.NodeId) bool {
4023 if int(id) < 0 || int(id) >= g.a.nodes.len {
4024 return false
4025 }
4026 node := g.a.nodes[int(id)]
4027 return match node.kind {
4028 .string_literal, .string_interp {
4029 true
4030 }
4031 .call {
4032 g.is_runtime_assignable_call(&node)
4033 }
4034 .ident {
4035 true
4036 }
4037 .or_expr {
4038 true
4039 }
4040 .infix {
4041 if node.children_count >= 2 {
4042 lhs_type := g.tc.resolve_type(g.a.child(&node, 0))
4043 rhs_type := g.tc.resolve_type(g.a.child(&node, 1))
4044 lhs_type is types.String || rhs_type is types.String
4045 } else {
4046 false
4047 }
4048 }
4049 .cast_expr, .prefix, .struct_init, .map_init {
4050 true
4051 }
4052 else {
4053 false
4054 }
4055 }
4056}
4057
4058fn (g &FlatGen) is_runtime_assignable_call(node &flat.Node) bool {
4059 if node.children_count == 0 {
4060 return false
4061 }
4062 callee_id := g.a.child(node, 0)
4063 if int(callee_id) < 0 {
4064 return false
4065 }
4066 callee := g.a.nodes[int(callee_id)]
4067 return callee.kind == .ident || callee.kind == .selector
4068}
4069
4070fn (g &FlatGen) op_str(op flat.Op) string {
4071 return match op {
4072 .plus { '+' }
4073 .minus { '-' }
4074 .mul { '*' }
4075 .div { '/' }
4076 .mod { '%' }
4077 .eq { '==' }
4078 .ne { '!=' }
4079 .lt { '<' }
4080 .gt { '>' }
4081 .le { '<=' }
4082 .ge { '>=' }
4083 .amp { '&' }
4084 .pipe { '|' }
4085 .xor { '^' }
4086 .left_shift { '<<' }
4087 .right_shift { '>>' }
4088 .right_shift_unsigned { '>>' }
4089 .logical_and { '&&' }
4090 .logical_or { '||' }
4091 .not { '!' }
4092 .bit_not { '~' }
4093 .assign { '=' }
4094 .plus_assign { '+=' }
4095 .minus_assign { '-=' }
4096 .mul_assign { '*=' }
4097 .div_assign { '/=' }
4098 .mod_assign { '%=' }
4099 .amp_assign { '&=' }
4100 .pipe_assign { '|=' }
4101 .xor_assign { '^=' }
4102 .left_shift_assign { '<<=' }
4103 .right_shift_assign { '>>=' }
4104 .right_shift_unsigned_assign { '>>=' }
4105 .inc { '++' }
4106 .dec { '--' }
4107 .dot { '.' }
4108 .arrow { '->' }
4109 .none { '' }
4110 }
4111}
4112
4113fn (mut g FlatGen) write(s string) {
4114 if g.line_start {
4115 g.write_indent()
4116 }
4117 if s.len == 0 {
4118 if g.indent > 0 {
4119 g.line_start = false
4120 }
4121 return
4122 }
4123 g.sb.write_string(s)
4124 g.line_start = s[s.len - 1] == `\n`
4125}
4126
4127fn (mut g FlatGen) writeln(s string) {
4128 if s.len > 0 {
4129 if g.line_start {
4130 g.write_indent()
4131 }
4132 g.sb.write_string(s)
4133 }
4134 g.sb.write_string('\n')
4135 g.line_start = true
4136}
4137
4138fn (mut g FlatGen) write_indent() {
4139 for _ in 0 .. g.indent {
4140 g.sb.write_string('\t')
4141 }
4142}
4143