vxx2 / vlib / v / gen / c / utils.v
2195 lines · 2123 sloc · 73.55 KB · 0b1ee86f742567f2fcb3c534b0a49a6dddba36ab
Raw
1// Copyright (c) 2019-2024 Alexander Medvednikov. All rights reserved.
2// Use of this source code is governed by an MIT license
3// that can be found in the LICENSE file.
4module c
5
6import hash.fnv1a
7import v.ast
8
9const cgen_resolution_hash_prime = u64(1099511628211)
10const cgen_resolution_hash_seed = u64(14695981039346656037)
11const cgen_unwrap_generic_cache_salt = u64(0x9e3779b185ebca87)
12const cgen_scope_var_type_cache_salt = u64(0xc2b2ae3d27d4eb4f)
13
14// stable_type_symbol_hash returns a deterministic hash for generated helper names.
15fn (mut g Gen) stable_type_symbol_hash(typ ast.Type) u64 {
16 mut seen := map[string]bool{}
17 return fnv1a.sum64_string(g.stable_type_symbol_key(typ, mut seen))
18}
19
20// stable_type_symbol_key builds a stable type descriptor without using table registration ids.
21fn (mut g Gen) stable_type_symbol_key(typ ast.Type, mut seen map[string]bool) string {
22 if typ == 0 {
23 return '0'
24 }
25 mut resolved_typ := g.unwrap_generic(g.recheck_concrete_type(typ))
26 if resolved_typ == 0 {
27 resolved_typ = g.unwrap_generic(typ)
28 }
29 if resolved_typ == 0 {
30 return '0'
31 }
32 sym := g.table.final_sym(resolved_typ)
33 if sym.info is ast.Alias {
34 parent_type := sym.info.parent_type.derive(resolved_typ)
35 if parent_type.idx() != resolved_typ.idx() {
36 return g.stable_type_symbol_key(parent_type, mut seen)
37 }
38 }
39 flags := stable_type_symbol_flags(resolved_typ)
40 base := '${sym.kind}:${stable_type_symbol_nominal_name(sym)}:${flags}'
41 if seen[base] {
42 return 'recursive:${base}'
43 }
44 seen[base] = true
45 mut parts := [base]
46 match sym.info {
47 ast.Array {
48 parts << 'array:${sym.info.nr_dims}:${g.stable_type_symbol_key(sym.info.elem_type, mut seen)}'
49 }
50 ast.ArrayFixed {
51 parts << 'array_fixed:${sym.info.size}:${g.stable_type_symbol_key(sym.info.elem_type, mut seen)}'
52 }
53 ast.Chan {
54 parts << 'chan:${sym.info.is_mut}:${g.stable_type_symbol_key(sym.info.elem_type, mut seen)}'
55 }
56 ast.Enum {
57 parts << 'enum:${sym.info.vals.join(',')}:${g.stable_type_symbol_key(sym.info.typ, mut seen)}:${sym.info.is_flag}:${sym.info.is_multi_allowed}:${sym.info.is_typedef}'
58 }
59 ast.FnType {
60 parts << 'fn:${sym.info.func.is_variadic}:${g.stable_type_symbol_key(sym.info.func.return_type, mut seen)}'
61 for param in sym.info.func.params {
62 parts << 'param:${param.is_mut}:${param.is_shared}:${param.is_atomic}:${g.stable_type_symbol_key(param.typ, mut seen)}'
63 }
64 }
65 ast.GenericInst {
66 parent_sym := g.table.sym(ast.new_type(sym.info.parent_idx))
67 parts << 'generic_inst:${parent_sym.kind}:${stable_type_symbol_nominal_name(parent_sym)}'
68 for concrete_type in sym.info.concrete_types {
69 parts << g.stable_type_symbol_key(concrete_type, mut seen)
70 }
71 }
72 ast.Interface {
73 parts << 'interface:${sym.info.is_generic}'
74 for embed in sym.info.embeds {
75 parts << 'embed:${g.stable_type_symbol_key(embed, mut seen)}'
76 }
77 for field in sym.info.fields {
78 parts << stable_type_symbol_field_key(mut g, field, mut seen)
79 }
80 for method in sym.info.methods {
81 parts << stable_type_symbol_method_key(mut g, method, mut seen)
82 }
83 }
84 ast.Map {
85 parts << 'map:${g.stable_type_symbol_key(sym.info.key_type, mut seen)}:${g.stable_type_symbol_key(sym.info.value_type, mut seen)}'
86 }
87 ast.MultiReturn {
88 for return_type in sym.info.types {
89 parts << 'return:${g.stable_type_symbol_key(return_type, mut seen)}'
90 }
91 }
92 ast.Struct {
93 parts << 'struct:${sym.info.is_typedef}:${sym.info.is_union}:${sym.info.is_heap}:${sym.info.is_shared}:${sym.info.is_generic}'
94 for embed in sym.info.embeds {
95 parts << 'embed:${g.stable_type_symbol_key(embed, mut seen)}'
96 }
97 for field in sym.info.fields {
98 parts << stable_type_symbol_field_key(mut g, field, mut seen)
99 }
100 }
101 ast.SumType {
102 parts << 'sum_type:${sym.info.is_anon}:${sym.info.is_generic}'
103 for variant in sym.info.variants {
104 parts << 'variant:${g.stable_type_symbol_key(variant, mut seen)}'
105 }
106 for field in sym.info.fields {
107 parts << stable_type_symbol_field_key(mut g, field, mut seen)
108 }
109 }
110 ast.Thread {
111 parts << 'thread:${g.stable_type_symbol_key(sym.info.return_type, mut seen)}'
112 }
113 else {}
114 }
115
116 return parts.join('|')
117}
118
119// stable_type_symbol_nominal_name serializes source-level identity for named types.
120fn stable_type_symbol_nominal_name(sym &ast.TypeSymbol) string {
121 if sym.name.starts_with('_VAnonStruct') || sym.name.starts_with('_VAnonUnion') {
122 return ''
123 }
124 return match sym.kind {
125 .alias, .enum, .interface, .struct, .sum_type, .aggregate {
126 '${sym.language}:${sym.mod}:${sym.name}'
127 }
128 else {
129 ''
130 }
131 }
132}
133
134// stable_type_symbol_flags serializes the type flags that affect generated helper identity.
135fn stable_type_symbol_flags(typ ast.Type) string {
136 mut flags := []string{cap: 8}
137 if typ.has_flag(.option) {
138 flags << 'option'
139 }
140 if typ.has_flag(.result) {
141 flags << 'result'
142 }
143 if typ.has_flag(.variadic) {
144 flags << 'variadic'
145 }
146 if typ.has_flag(.generic) {
147 flags << 'generic'
148 }
149 if typ.has_flag(.shared_f) {
150 flags << 'shared'
151 }
152 if typ.has_flag(.atomic_f) {
153 flags << 'atomic'
154 }
155 if typ.has_flag(.option_mut_param_t) {
156 flags << 'option_mut_param'
157 }
158 flags << 'muls:${typ.nr_muls()}'
159 return flags.join(',')
160}
161
162// stable_type_symbol_field_key adds field identity and type information to a type descriptor.
163fn stable_type_symbol_field_key(mut g Gen, field ast.StructField, mut seen map[string]bool) string {
164 return 'field:${field.name}:${field.is_embed}:${field.is_part_of_union}:${field.is_volatile}:${g.stable_type_symbol_key(field.typ, mut
165 seen)}'
166}
167
168// stable_type_symbol_method_key adds method signature information to a type descriptor.
169fn stable_type_symbol_method_key(mut g Gen, method ast.Fn, mut seen map[string]bool) string {
170 mut parts := [
171 'method:${method.name}:${method.is_variadic}:${g.stable_type_symbol_key(method.return_type, mut seen)}',
172 ]
173 for param in method.params {
174 parts << 'param:${param.is_mut}:${param.is_shared}:${param.is_atomic}:${g.stable_type_symbol_key(param.typ, mut seen)}'
175 }
176 return parts.join(',')
177}
178
179@[inline]
180fn cgen_resolution_hash_mix(key u64, value u64) u64 {
181 return (key ^ value) * cgen_resolution_hash_prime
182}
183
184fn (mut g Gen) clear_type_resolution_caches() {
185 g.unwrap_generic_cache.clear()
186 g.resolved_scope_var_type_cache.clear()
187}
188
189fn (mut g Gen) current_sumtype_match_variant_type(ident ast.Ident, sumtype_type ast.Type) ast.Type {
190 if g.cur_fn == unsafe { nil } || g.cur_concrete_types.len == 0 {
191 return ast.Type(0)
192 }
193 mut branch_type := ast.Type(0)
194 if typ := g.type_resolver.type_map[ident.name] {
195 branch_type = typ
196 }
197 if branch_type == 0 {
198 cname := c_name(ident.name)
199 if cname != ident.name {
200 if typ := g.type_resolver.type_map[cname] {
201 branch_type = typ
202 }
203 }
204 }
205 if branch_type == 0 || branch_type == ast.void_type {
206 return ast.Type(0)
207 }
208 variant_type := g.unwrap_generic(g.recheck_concrete_type(branch_type))
209 if variant_type == 0 || variant_type == ast.void_type || variant_type.has_flag(.generic)
210 || g.type_has_unresolved_generic_parts(variant_type) {
211 return ast.Type(0)
212 }
213 mut parent_type := g.unwrap_generic(g.recheck_concrete_type(sumtype_type)).set_nr_muls(0)
214 if parent_type != 0 && g.table.final_sym(parent_type).kind == .sum_type
215 && g.table.sumtype_has_variant(parent_type, variant_type, false) {
216 return variant_type
217 }
218 parent_type = g.resolve_current_fn_generic_param_type(ident.name).set_nr_muls(0)
219 if parent_type == 0 || g.table.final_sym(parent_type).kind != .sum_type
220 || !g.table.sumtype_has_variant(parent_type, variant_type, false) {
221 return ast.Type(0)
222 }
223 return variant_type
224}
225
226fn (g &Gen) type_resolution_context_key() u64 {
227 mut key := cgen_resolution_hash_seed
228 if g.inside_struct_init {
229 key = cgen_resolution_hash_mix(key, 1)
230 }
231 key = cgen_resolution_hash_mix(key, u64(g.cur_struct_init_typ))
232 key = cgen_resolution_hash_mix(key, u64(g.cur_concrete_types.len))
233 for concrete_type in g.cur_concrete_types {
234 key = cgen_resolution_hash_mix(key, u64(concrete_type))
235 }
236 key = cgen_resolution_hash_mix(key, u64(g.active_call_concrete_types.len))
237 for concrete_type in g.active_call_concrete_types {
238 key = cgen_resolution_hash_mix(key, u64(concrete_type))
239 }
240 if g.comptime != unsafe { nil } {
241 key = cgen_resolution_hash_mix(key, u64(g.comptime.comptime_loop_id))
242 key = cgen_resolution_hash_mix(key, u64(g.comptime.comptime_for_field_type))
243 key = cgen_resolution_hash_mix(key, u64(g.comptime.comptime_for_method_ret_type))
244 }
245 return key
246}
247
248@[inline]
249fn (g &Gen) type_resolution_cache_key(typ ast.Type, salt u64) u64 {
250 return cgen_resolution_hash_mix(g.type_resolution_context_key(), u64(typ)) ^ salt
251}
252
253@[inline]
254fn (g &Gen) expr_resolution_cache_key(pos int, default_typ ast.Type, salt u64) u64 {
255 if pos <= 0 {
256 return 0
257 }
258 mut key := g.type_resolution_context_key()
259 key = cgen_resolution_hash_mix(key, u64(g.fid + 2))
260 key = cgen_resolution_hash_mix(key, u64(pos))
261 key = cgen_resolution_hash_mix(key, u64(default_typ))
262 return key ^ salt
263}
264
265@[inline]
266fn (g &Gen) type_is_known_concrete(typ ast.Type) bool {
267 if typ == 0 || typ.has_flag(.generic) {
268 return false
269 }
270 idx := typ.idx()
271 return idx <= ast.nil_type_idx
272 || (idx < g.generic_parts_cache.len && g.generic_parts_cache[idx] == 1)
273}
274
275@[inline]
276fn (mut g Gen) unwrap_generic(typ ast.Type) ast.Type {
277 if typ == 0 {
278 return typ
279 }
280 if !typ.has_flag(.generic) {
281 idx := typ.idx()
282 if idx <= ast.nil_type_idx
283 || (idx < g.generic_parts_cache.len && g.generic_parts_cache[idx] == 1) {
284 return typ
285 }
286 }
287 return g.unwrap_generic_slow(typ)
288}
289
290fn (mut g Gen) unwrap_generic_slow(typ ast.Type) ast.Type {
291 cache_key := g.type_resolution_cache_key(typ, cgen_unwrap_generic_cache_salt)
292 if cached := g.unwrap_generic_cache[cache_key] {
293 return cached
294 }
295 mut resolved_typ := g.recheck_concrete_type(typ)
296 if resolved_typ == 0 {
297 resolved_typ = typ
298 }
299 if !resolved_typ.has_flag(.generic) {
300 resolved_idx := resolved_typ.idx()
301 if resolved_idx <= ast.nil_type_idx
302 || (resolved_idx < g.generic_parts_cache.len
303 && g.generic_parts_cache[resolved_idx] == 1)
304 || !g.type_has_unresolved_generic_parts(resolved_typ) {
305 g.unwrap_generic_cache[cache_key] = resolved_typ
306 return resolved_typ
307 }
308 }
309 // NOTE: `convert_generic_type` should not mutate the table.
310 //
311 // It mutates if the generic type is for example `[]T` and the concrete
312 // type is an array type that has not been registered yet.
313 //
314 // This should have already happened in the checker, since it also calls
315 // `convert_generic_type`. `g.table` is made non-mut to make sure
316 // no one else can accidentally mutates the table.
317 current_generic_names := g.current_fn_generic_names()
318 if current_generic_names.len > 0 && current_generic_names.len == g.cur_concrete_types.len {
319 if t_typ := g.table.convert_generic_type(resolved_typ, current_generic_names,
320 g.cur_concrete_types)
321 {
322 g.unwrap_generic_cache[cache_key] = t_typ
323 return t_typ
324 }
325 } else if g.inside_struct_init {
326 if g.cur_struct_init_typ != 0 {
327 sym := g.table.sym(g.cur_struct_init_typ)
328 if sym.info is ast.Struct {
329 if sym.info.generic_types.len > 0 {
330 generic_names := sym.info.generic_types.map(g.table.sym(it).name)
331 mut concrete_types := sym.info.concrete_types.clone()
332 if concrete_types.len == 0 && sym.generic_types.len == generic_names.len
333 && sym.generic_types != sym.info.generic_types {
334 concrete_types = sym.generic_types.clone()
335 }
336 if t_typ := g.table.convert_generic_type(resolved_typ, generic_names,
337 concrete_types)
338 {
339 g.unwrap_generic_cache[cache_key] = t_typ
340 return t_typ
341 }
342 }
343 }
344 }
345 } else if resolved_typ != 0 && g.table.sym(resolved_typ).kind == .struct {
346 // resolve selector `a.foo` where `a` is struct[T] on non generic function
347 sym := g.table.sym(resolved_typ)
348 if sym.info is ast.Struct {
349 if sym.info.generic_types.len > 0 {
350 generic_names := sym.info.generic_types.map(g.table.sym(it).name)
351 mut concrete_types := sym.info.concrete_types.clone()
352 if concrete_types.len == 0 && sym.generic_types.len == generic_names.len
353 && sym.generic_types != sym.info.generic_types {
354 concrete_types = sym.generic_types.clone()
355 }
356 if t_typ := g.table.convert_generic_type(resolved_typ, generic_names,
357 concrete_types)
358 {
359 g.unwrap_generic_cache[cache_key] = t_typ
360 return t_typ
361 }
362
363 if t_typ := g.table.convert_generic_type(resolved_typ, generic_names,
364 g.cur_concrete_types)
365 {
366 g.unwrap_generic_cache[cache_key] = t_typ
367 return t_typ
368 }
369 }
370 }
371 }
372 if typ.has_flag(.generic) {
373 if t_typ := g.type_resolver.resolve_bound_generic_type(typ) {
374 g.unwrap_generic_cache[cache_key] = t_typ
375 return t_typ
376 }
377 }
378 g.unwrap_generic_cache[cache_key] = resolved_typ
379 return resolved_typ
380}
381
382// Promotes literal element types in arrays (e.g. []int_literal -> []int, []float_literal -> []f64)
383// so that array comparisons use the correct registered array type.
384fn (mut g Gen) promote_literal_array_type(typ ast.Type) ast.Type {
385 sym := g.table.sym(typ)
386 if sym.info is ast.Array {
387 promoted_elem := ast.mktyp(sym.info.elem_type)
388 if promoted_elem != sym.info.elem_type {
389 idx := g.table.find_or_register_array(promoted_elem)
390 if idx > 0 {
391 return ast.new_type(idx).derive(typ)
392 }
393 }
394 }
395 return typ
396}
397
398fn (mut g Gen) infer_branch_expr_type(stmts []ast.Stmt) ast.Type {
399 if stmts.len == 0 {
400 return ast.void_type
401 }
402 last_stmt := stmts.last()
403 if last_stmt !is ast.ExprStmt {
404 return ast.void_type
405 }
406 expr_stmt := last_stmt as ast.ExprStmt
407 mut default_typ := expr_stmt.typ
408 if default_typ == 0 || default_typ == ast.void_type {
409 default_typ = expr_stmt.expr.type()
410 }
411 mut resolved_typ := g.resolved_expr_type(expr_stmt.expr, default_typ)
412 if resolved_typ == 0 || resolved_typ == ast.void_type {
413 resolved_typ = g.type_resolver.get_type_or_default(expr_stmt.expr, default_typ)
414 }
415 if resolved_typ == 0 || resolved_typ == ast.void_type {
416 resolved_typ = default_typ
417 }
418 if resolved_typ == 0 || resolved_typ == ast.void_type {
419 return ast.void_type
420 }
421 return g.unwrap_generic(g.recheck_concrete_type(resolved_typ))
422}
423
424fn (mut g Gen) expected_rhs_type_for_expr(pos int, node_type ast.Type) ast.Type {
425 if pos < 0 || node_type == 0 || node_type == ast.void_type || !node_type.has_option_or_result() {
426 return ast.void_type
427 }
428 expected_type := g.expected_rhs_type_by_pos[pos] or { return ast.void_type }
429 if expected_type == 0 || expected_type == ast.void_type || expected_type.has_option_or_result() {
430 return ast.void_type
431 }
432 resolved_expected_type := g.unwrap_generic(g.recheck_concrete_type(expected_type))
433 if resolved_expected_type == 0 || resolved_expected_type == ast.void_type
434 || resolved_expected_type.has_option_or_result() {
435 return ast.void_type
436 }
437 return resolved_expected_type
438}
439
440fn (mut g Gen) infer_if_expr_type(node ast.IfExpr) ast.Type {
441 if g.inside_return && g.inside_struct_init {
442 for branch in node.branches {
443 branch_typ := g.infer_branch_expr_type(branch.stmts)
444 if branch_typ != 0 && branch_typ != ast.void_type {
445 return branch_typ
446 }
447 }
448 }
449 if node.typ != 0 && node.typ != ast.void_type {
450 expected_rhs_type := g.expected_rhs_type_for_expr(node.pos.pos, node.typ)
451 if expected_rhs_type != ast.void_type {
452 return expected_rhs_type
453 }
454 resolved := g.unwrap_generic(g.recheck_concrete_type(node.typ))
455 // In generic functions, node.typ may have been mutated by the checker
456 // to a concrete type from the last processed instantiation. When the
457 // if-expr is used as a return expression, use the function's
458 // return type instead, which correctly resolves via cur_concrete_types.
459 // Only apply this override when the function's return type is actually
460 // generic — otherwise the if-expression type is concrete and correct.
461 if g.inside_return_expr && !g.inside_struct_init && g.cur_fn != unsafe { nil }
462 && g.cur_concrete_types.len > 0 && g.cur_fn.return_type.has_flag(.generic) {
463 fn_ret := g.unwrap_generic(g.recheck_concrete_type(g.cur_fn.return_type))
464 if fn_ret != 0 && fn_ret != ast.void_type {
465 if node.typ.has_flag(.result) && !fn_ret.has_flag(.result) {
466 return fn_ret.set_flag(.result)
467 } else if node.typ.has_flag(.option) && !fn_ret.has_flag(.option) {
468 return fn_ret.set_flag(.option)
469 }
470 return fn_ret
471 }
472 }
473 return resolved
474 }
475 for branch in node.branches {
476 branch_typ := g.infer_branch_expr_type(branch.stmts)
477 if branch_typ != 0 && branch_typ != ast.void_type {
478 return branch_typ
479 }
480 }
481 return ast.void_type
482}
483
484fn (mut g Gen) infer_match_expr_type(node ast.MatchExpr) ast.Type {
485 if g.inside_return && g.inside_struct_init {
486 for branch in node.branches {
487 branch_typ := g.infer_branch_expr_type(branch.stmts)
488 if branch_typ != 0 && branch_typ != ast.void_type {
489 return branch_typ
490 }
491 }
492 }
493 if node.return_type != 0 && node.return_type != ast.void_type {
494 expected_rhs_type := g.expected_rhs_type_for_expr(node.pos.pos, node.return_type)
495 if expected_rhs_type != ast.void_type {
496 return expected_rhs_type
497 }
498 resolved := g.unwrap_generic(g.recheck_concrete_type(node.return_type))
499 // In generic functions, node.return_type may have been mutated by the checker
500 // to a concrete type from the last processed instantiation. When the match is
501 // used as a return expression, use the function's return type
502 // instead, which correctly resolves via cur_concrete_types.
503 // Only apply this override when the function's return type is actually
504 // generic — otherwise the match expression type is concrete and correct.
505 if g.inside_return_expr && !g.inside_struct_init && g.cur_fn != unsafe { nil }
506 && g.cur_concrete_types.len > 0 && g.cur_fn.return_type.has_flag(.generic) {
507 fn_ret := g.unwrap_generic(g.recheck_concrete_type(g.cur_fn.return_type))
508 if fn_ret != 0 && fn_ret != ast.void_type {
509 // Preserve option/result flags from the match's return_type
510 if node.return_type.has_flag(.result) && !fn_ret.has_flag(.result) {
511 return fn_ret.set_flag(.result)
512 } else if node.return_type.has_flag(.option) && !fn_ret.has_flag(.option) {
513 return fn_ret.set_flag(.option)
514 }
515 return fn_ret
516 }
517 }
518 return resolved
519 }
520 for branch in node.branches {
521 branch_typ := g.infer_branch_expr_type(branch.stmts)
522 if branch_typ != 0 && branch_typ != ast.void_type {
523 return branch_typ
524 }
525 }
526 return ast.void_type
527}
528
529fn (mut g Gen) recheck_concrete_type(typ ast.Type) ast.Type {
530 if typ == 0 {
531 return typ
532 }
533 if g.cur_fn == unsafe { nil } || g.cur_concrete_types.len == 0 {
534 return typ
535 }
536 idx := typ.idx()
537 if idx <= ast.nil_type_idx || (!typ.has_flag(.generic) && idx < g.generic_parts_cache.len
538 && g.generic_parts_cache[idx] == 1) {
539 return typ
540 }
541 sym := g.table.sym(typ)
542 match sym.info {
543 ast.Struct, ast.Interface, ast.SumType {
544 if sym.info.concrete_types.len > 0
545 && !sym.info.concrete_types.any(it.has_flag(.generic)) {
546 return typ
547 }
548 }
549 ast.GenericInst {
550 if sym.info.concrete_types.len > 0
551 && !sym.info.concrete_types.any(it.has_flag(.generic)) {
552 return typ
553 }
554 }
555 else {}
556 }
557
558 if !typ.has_flag(.generic) && !g.type_has_unresolved_generic_parts(typ) {
559 return typ
560 }
561 if g.cur_fn == unsafe { nil } || g.cur_concrete_types.len == 0 {
562 return typ
563 }
564 generic_names := g.current_fn_generic_names()
565 if generic_names.len == 0 || generic_names.len != g.cur_concrete_types.len {
566 return typ
567 }
568 concrete_types := g.cur_concrete_types
569 if resolved_typ := g.table.convert_generic_type(typ, generic_names, concrete_types) {
570 return resolved_typ
571 }
572 mut muttable := unsafe { &ast.Table(g.table) }
573 unwrapped_typ := muttable.unwrap_generic_type_ex(typ, generic_names, concrete_types, true)
574 if unwrapped_typ != typ {
575 return unwrapped_typ
576 }
577 return typ
578}
579
580@[inline]
581fn (g &Gen) has_current_generic_context() bool {
582 return g.cur_fn != unsafe { nil } && g.cur_concrete_types.len > 0
583}
584
585@[inline]
586fn (mut g Gen) type_needs_generic_resolution(typ ast.Type) bool {
587 if typ == 0 {
588 return false
589 }
590 if typ.has_flag(.generic) {
591 return true
592 }
593 if typ.idx() <= ast.nil_type_idx {
594 return false
595 }
596 if (g.cur_fn == unsafe { nil } || g.cur_concrete_types.len == 0)
597 && !g.has_active_call_generic_context() {
598 return false
599 }
600 idx := typ.idx()
601 if idx <= ast.nil_type_idx
602 || (idx < g.generic_parts_cache.len && g.generic_parts_cache[idx] == 1) {
603 return false
604 }
605 return g.type_has_unresolved_generic_parts(typ)
606}
607
608// is_expr_smartcast_to_sumtype checks if expr is a smartcast variable/field
609// whose original type is the given sumtype. This is used to prevent sumtype
610// variant unwrapping when passing a smartcast expression to a function
611// that expects the original sumtype.
612fn (mut g Gen) is_expr_smartcast_to_sumtype(expr ast.Expr, expected_sumtype ast.Type) bool {
613 scope := g.file.scope.innermost(expr.pos().pos)
614 if expr is ast.SelectorExpr {
615 v := scope.find_struct_field(expr.expr.str(), expr.expr_type, expr.field_name)
616 if v != unsafe { nil } && v.smartcasts.len > 0 {
617 orig_type := g.unwrap_generic(g.recheck_concrete_type(v.orig_type))
618 resolved_expected_sumtype := g.unwrap_generic(g.recheck_concrete_type(expected_sumtype))
619 return orig_type == resolved_expected_sumtype
620 }
621 } else if expr is ast.Ident {
622 if v := scope.find_var(expr.name) {
623 if v.smartcasts.len > 0 && v.orig_type == expected_sumtype {
624 return true
625 }
626 }
627 }
628 return false
629}
630
631// expr_has_or_block checks if an expression has an `or {}` block that
632// unwraps an option/result type.
633fn (g Gen) expr_has_or_block(expr ast.Expr) bool {
634 return match expr {
635 ast.CallExpr { expr.or_block.kind != .absent }
636 ast.Ident { expr.or_expr.kind != .absent }
637 ast.IndexExpr { expr.or_expr.kind != .absent }
638 ast.SelectorExpr { expr.or_block.kind != .absent }
639 ast.PrefixExpr { expr.or_block.kind != .absent }
640 ast.InfixExpr { expr.or_block.kind != .absent }
641 ast.ComptimeCall { expr.or_block.kind != .absent }
642 ast.ComptimeSelector { expr.or_block.kind != .absent }
643 else { false }
644 }
645}
646
647fn (g &Gen) is_auto_deref_source_ident(expr ast.Expr) bool {
648 if expr is ast.Ident {
649 ident := expr as ast.Ident
650 if ident.obj is ast.Var && ident.obj.is_auto_deref {
651 return true
652 }
653 if source_var := ident.scope.find_var(ident.name) {
654 return source_var.is_auto_deref
655 }
656 }
657 return false
658}
659
660fn (g &Gen) auto_deref_source_type_is_pointer(expr ast.Expr) bool {
661 if expr !is ast.Ident || g.cur_fn == unsafe { nil } || !expr.is_auto_deref_var() {
662 return false
663 }
664 ident := expr as ast.Ident
665 for param in g.cur_fn.params {
666 if param.name == ident.name {
667 source_typ := if param.orig_typ != 0 { param.orig_typ } else { param.typ }
668 return source_typ.is_any_kind_of_pointer()
669 }
670 }
671 return false
672}
673
674fn (mut g Gen) resolved_scope_var_type(expr ast.Ident) ast.Type {
675 if g.has_active_call_generic_context() {
676 return g.resolved_scope_var_type_uncached(expr)
677 }
678 cache_key := g.expr_resolution_cache_key(expr.pos.pos, 0, cgen_scope_var_type_cache_salt)
679 if cache_key != 0 {
680 if cached := g.resolved_scope_var_type_cache[cache_key] {
681 return cached
682 }
683 }
684 resolved := g.resolved_scope_var_type_uncached(expr)
685 if cache_key != 0 && resolved != 0 {
686 g.resolved_scope_var_type_cache[cache_key] = resolved
687 }
688 return resolved
689}
690
691// type_alias_chain_idxs returns the idxs of `typ` and of every type it aliases,
692// transitively, down to the first non-alias type. Comparison is by idx only,
693// so flags and pointer levels are ignored.
694fn (g &Gen) type_alias_chain_idxs(typ ast.Type) []int {
695 mut idxs := [typ.idx()]
696 mut cur := typ
697 for {
698 sym := g.table.sym(cur)
699 if sym.info is ast.Alias {
700 parent := sym.info.parent_type
701 pidx := parent.idx()
702 if pidx in idxs {
703 break
704 }
705 idxs << pidx
706 cur = parent
707 } else {
708 break
709 }
710 }
711 return idxs
712}
713
714// alias_chain_equivalent reports whether `a` and `b` denote the same type modulo
715// alias naming: one type's alias chain (the type itself plus the types it
716// aliases, transitively) contains the other. This is stricter than comparing
717// fully unaliased base types, so distinct aliases that merely share an
718// underlying representation (e.g. `type String = u8` and `type Void = u8`) are
719// NOT treated as equivalent, while genuine alias/original pairs (e.g. a variant
720// `Bar` together with `type Foo = Bar`) still match by runtime tag.
721fn (g &Gen) alias_chain_equivalent(a ast.Type, b ast.Type) bool {
722 if a.nr_muls() != b.nr_muls() || a.has_flag(.option) != b.has_flag(.option) {
723 return false
724 }
725 if a.idx() == b.idx() {
726 return true
727 }
728 return b.idx() in g.type_alias_chain_idxs(a) || a.idx() in g.type_alias_chain_idxs(b)
729}
730
731fn (mut g Gen) type_idx_exprs_for_types(types []ast.Type) []string {
732 mut matches := []string{}
733 mut seen := map[string]bool{}
734 for typ in types {
735 index_expr := g.type_sidx(typ)
736 if index_expr !in seen {
737 seen[index_expr] = true
738 matches << index_expr
739 }
740 }
741 return matches
742}
743
744fn (mut g Gen) matching_sumtype_variant_types(parent_type ast.Type, target_type ast.Type) []ast.Type {
745 variants := g.sumtype_runtime_variants(parent_type)
746 target := g.unwrap_generic(target_type)
747 mut matches := []ast.Type{}
748 mut seen := map[string]bool{}
749 for variant in variants {
750 if g.alias_chain_equivalent(g.unwrap_generic(variant), target) {
751 index_expr := g.type_sidx(variant)
752 if index_expr !in seen {
753 seen[index_expr] = true
754 matches << variant
755 }
756 }
757 }
758 if matches.len > 0 {
759 return matches
760 }
761 for variant in variants {
762 if g.is_exact_sumtype_variant_match(variant, target_type) {
763 return [variant]
764 }
765 }
766 return [target_type]
767}
768
769fn (mut g Gen) matching_sumtype_variant_type_idx_exprs(parent_type ast.Type, target_type ast.Type) []string {
770 return g.type_idx_exprs_for_types(g.matching_sumtype_variant_types(parent_type, target_type))
771}
772
773fn (mut g Gen) matching_interface_variant_types(interface_sym ast.TypeSymbol, target_type ast.Type) []ast.Type {
774 if interface_sym.info !is ast.Interface {
775 return []
776 }
777 target := g.unwrap_generic(target_type)
778 info := interface_sym.info as ast.Interface
779 mut matches := []ast.Type{}
780 mut seen := map[string]bool{}
781 for variant in g.runtime_interface_variants(info) {
782 variant_sym := g.table.sym(variant)
783 if variant_sym.kind in [.interface, .aggregate] {
784 continue
785 }
786 if variant_sym.info is ast.Struct && variant_sym.info.is_unresolved_generic() {
787 continue
788 }
789 if !g.alias_chain_equivalent(g.unwrap_generic(variant), target) {
790 continue
791 }
792 index_expr := g.type_sidx(variant)
793 if index_expr !in seen {
794 seen[index_expr] = true
795 matches << variant
796 }
797 }
798 if matches.len > 0 {
799 return matches
800 }
801 return [target_type]
802}
803
804fn (mut g Gen) matching_interface_variant_index_exprs(interface_sym ast.TypeSymbol, target_type ast.Type) []string {
805 if interface_sym.info !is ast.Interface {
806 return []
807 }
808 matching_variants := g.matching_interface_variant_types(interface_sym, target_type)
809 mut matches := []string{}
810 mut seen := map[string]bool{}
811 for variant in matching_variants {
812 cctype := g.cc_type(ast.mktyp(variant), true)
813 index_expr := '_${interface_sym.cname}_${cctype}_index'
814 if index_expr !in seen {
815 seen[index_expr] = true
816 matches << index_expr
817 }
818 }
819 if matches.len > 0 {
820 return matches
821 }
822 cctype := g.cc_type(ast.mktyp(target_type), true)
823 return ['_${interface_sym.cname}_${cctype}_index']
824}
825
826fn (mut g Gen) matching_interface_variant_type_idx_exprs(interface_sym ast.TypeSymbol, target_type ast.Type) []string {
827 if interface_sym.info !is ast.Interface {
828 return []
829 }
830 return g.type_idx_exprs_for_types(g.matching_interface_variant_types(interface_sym, target_type))
831}
832
833fn (mut g Gen) write_type_tag_condition(tag_expr string, cmp_op string, index_exprs []string) {
834 if index_exprs.len == 0 {
835 g.write(if cmp_op == '==' { 'false' } else { 'true' })
836 return
837 }
838 if index_exprs.len > 1 {
839 g.write('(')
840 }
841 joiner := if cmp_op == '==' { ' || ' } else { ' && ' }
842 for i, index_expr in index_exprs {
843 if i > 0 {
844 g.write(joiner)
845 }
846 g.write('${tag_expr} ${cmp_op} ${index_expr}')
847 }
848 if index_exprs.len > 1 {
849 g.write(')')
850 }
851}
852
853fn (mut g Gen) resolved_scope_var_type_uncached(expr ast.Ident) ast.Type {
854 mut scope := if expr.scope != unsafe { nil } {
855 expr.scope.innermost(expr.pos.pos)
856 } else {
857 expr.scope
858 }
859 if scope == unsafe { nil } || scope.find_var(expr.name) == none {
860 scope = if g.file.scope != unsafe { nil } {
861 g.file.scope.innermost(expr.pos.pos)
862 } else {
863 expr.scope
864 }
865 }
866 if scope == unsafe { nil } {
867 return 0
868 }
869 if mut v := scope.find_var(expr.name) {
870 mut refreshed_expr_type := ast.Type(0)
871 if v.generic_typ != 0 {
872 refreshed_generic_type := g.unwrap_generic(g.recheck_concrete_type(v.generic_typ))
873 if refreshed_generic_type != 0 {
874 v.typ = refreshed_generic_type
875 v.orig_type = ast.no_type
876 v.smartcasts = []
877 v.is_unwrapped = false
878 }
879 }
880 if !v.is_arg && v.expr !is ast.EmptyExpr && v.pos.pos > 0 && v.pos.pos < expr.pos.pos
881 && !(v.expr is ast.Ident && v.expr.name == expr.name)
882 && ((g.cur_fn != unsafe { nil } && g.cur_concrete_types.len > 0)
883 || v.typ.has_flag(.generic)
884 || g.type_has_unresolved_generic_parts(v.typ)) {
885 resolved_expr_type := g.resolved_expr_type(v.expr, v.typ)
886 if resolved_expr_type != 0 {
887 refreshed_expr_type = g.unwrap_generic(g.recheck_concrete_type(resolved_expr_type))
888 if g.type_has_unresolved_generic_parts(refreshed_expr_type) {
889 call_like_type := g.resolved_call_like_expr_type(v.expr)
890 if call_like_type != 0 && !call_like_type.has_flag(.generic)
891 && !g.type_has_unresolved_generic_parts(call_like_type) {
892 refreshed_expr_type = call_like_type
893 }
894 }
895 // Keep `mut x := param` as a value copy when re-resolving locals,
896 // unless the original mut parameter type was already a pointer.
897 if g.is_auto_deref_source_ident(v.expr) && refreshed_expr_type.is_ptr()
898 && !g.auto_deref_source_type_is_pointer(v.expr) {
899 refreshed_expr_type = refreshed_expr_type.deref()
900 }
901 // If the variable was initialized with an `or {}` block that
902 // unwraps the option/result, clear the flag from the resolved type
903 if refreshed_expr_type.has_option_or_result() && g.expr_has_or_block(v.expr) {
904 refreshed_expr_type = refreshed_expr_type.clear_option_and_result()
905 }
906 $if trace_ci_fixes ? {
907 if g.file.path.contains('comptime_for_in_options_struct_test.v')
908 && expr.name in ['v', 'w'] {
909 current_name := if v.typ == 0 { '0' } else { g.table.type_to_str(v.typ) }
910 resolved_name := if refreshed_expr_type == 0 {
911 '0'
912 } else {
913 g.table.type_to_str(refreshed_expr_type)
914 }
915 orig_name := if v.orig_type == 0 {
916 '0'
917 } else {
918 g.table.type_to_str(v.orig_type)
919 }
920 eprintln('resolved_scope_var_type refresh ${expr.name}: current=${current_name} expr=${typeof(v.expr).name} resolved=${resolved_name} unwrapped=${v.is_unwrapped} orig=${orig_name}')
921 }
922 }
923 if v.is_unwrapped && refreshed_expr_type.has_option_or_result() {
924 v.orig_type = refreshed_expr_type
925 v.typ = refreshed_expr_type.clear_option_and_result()
926 } else {
927 v.typ = refreshed_expr_type
928 if !v.is_unwrapped && v.smartcasts.len == 0 {
929 v.orig_type = ast.no_type
930 }
931 }
932 }
933 }
934 if (v.is_unwrapped || v.smartcasts.len > 0) && scope.parent != unsafe { nil } {
935 if mut parent_v := scope.parent.find_var(expr.name) {
936 if parent_v.generic_typ != 0 {
937 refreshed_parent_type :=
938 g.unwrap_generic(g.recheck_concrete_type(parent_v.generic_typ))
939 if refreshed_parent_type != 0 {
940 parent_v.typ = refreshed_parent_type
941 }
942 }
943 if !parent_v.is_arg && parent_v.expr !is ast.EmptyExpr && parent_v.pos.pos > 0
944 && parent_v.pos.pos < expr.pos.pos && !(parent_v.expr is ast.Ident
945 && parent_v.expr.name == expr.name)
946 && ((g.cur_fn != unsafe { nil } && g.cur_concrete_types.len > 0)
947 || parent_v.typ.has_flag(.generic)
948 || g.type_has_unresolved_generic_parts(parent_v.typ)) {
949 resolved_parent_expr_type := g.resolved_expr_type(parent_v.expr, parent_v.typ)
950 if resolved_parent_expr_type != 0 {
951 mut refreshed_parent_type :=
952 g.unwrap_generic(g.recheck_concrete_type(resolved_parent_expr_type))
953 if g.type_has_unresolved_generic_parts(parent_v.typ) {
954 call_like_type := g.resolved_call_like_expr_type(parent_v.expr)
955 if call_like_type != 0 && !call_like_type.has_flag(.generic)
956 && !g.type_has_unresolved_generic_parts(call_like_type) {
957 parent_v.typ = call_like_type
958 }
959 }
960 if g.is_auto_deref_source_ident(parent_v.expr)
961 && refreshed_parent_type.is_ptr()
962 && !g.auto_deref_source_type_is_pointer(parent_v.expr) {
963 refreshed_parent_type = refreshed_parent_type.deref()
964 }
965 parent_v.typ = refreshed_parent_type
966 }
967 }
968 if v.is_unwrapped {
969 parent_orig_type := if parent_v.orig_type != ast.no_type
970 && parent_v.orig_type.has_option_or_result() {
971 parent_v.orig_type
972 } else {
973 parent_v.typ
974 }
975 if parent_orig_type.has_option_or_result() {
976 v.orig_type = parent_orig_type
977 v.typ = parent_orig_type.clear_option_and_result()
978 }
979 } else if v.smartcasts.len > 0 && parent_v.typ != 0 && v.orig_type == ast.no_type {
980 v.orig_type = if parent_v.orig_type != ast.no_type {
981 parent_v.orig_type
982 } else {
983 parent_v.typ
984 }
985 }
986 }
987 }
988 if v.is_inherited && scope.parent != unsafe { nil } {
989 if mut parent_v := scope.parent.find_var(expr.name) {
990 by_value_auto_deref_capture := !v.is_auto_deref && parent_v.is_auto_deref
991 && parent_v.typ.is_ptr()
992 if by_value_auto_deref_capture {
993 if parent_v.generic_typ != 0 {
994 refreshed_parent_type :=
995 g.unwrap_generic(g.recheck_concrete_type(parent_v.generic_typ))
996 if refreshed_parent_type != 0 {
997 parent_v.typ = refreshed_parent_type
998 }
999 }
1000 if parent_v.expr !is ast.EmptyExpr
1001 && ((g.cur_fn != unsafe { nil } && g.cur_concrete_types.len > 0)
1002 || parent_v.typ.has_flag(.generic)
1003 || g.type_has_unresolved_generic_parts(parent_v.typ)) {
1004 resolved_parent_type := g.resolved_expr_type(parent_v.expr, parent_v.typ)
1005 if resolved_parent_type != 0 {
1006 parent_v.typ =
1007 g.unwrap_generic(g.recheck_concrete_type(resolved_parent_type))
1008 }
1009 }
1010 if parent_v.typ != 0 {
1011 resolved_parent_type :=
1012 g.unwrap_generic(g.recheck_concrete_type(parent_v.typ))
1013 if resolved_parent_type != 0 {
1014 return if resolved_parent_type.is_ptr() {
1015 resolved_parent_type.deref()
1016 } else {
1017 resolved_parent_type
1018 }
1019 }
1020 }
1021 } else {
1022 if parent_v.generic_typ != 0 {
1023 refreshed_parent_type :=
1024 g.unwrap_generic(g.recheck_concrete_type(parent_v.generic_typ))
1025 if refreshed_parent_type != 0 {
1026 parent_v.typ = refreshed_parent_type
1027 }
1028 }
1029 if parent_v.smartcasts.len > 0 {
1030 smartcast_type := if parent_v.ct_type_var == .smartcast {
1031 g.type_resolver.get_type(expr)
1032 } else {
1033 g.exposed_smartcast_type(parent_v.orig_type,
1034 parent_v.smartcasts.last(), parent_v.is_mut)
1035 }
1036 return g.unwrap_generic(g.recheck_concrete_type(smartcast_type))
1037 }
1038 if parent_v.expr !is ast.EmptyExpr
1039 && ((g.cur_fn != unsafe { nil } && g.cur_concrete_types.len > 0)
1040 || parent_v.typ.has_flag(.generic)
1041 || g.type_has_unresolved_generic_parts(parent_v.typ)) {
1042 resolved_parent_type := g.resolved_expr_type(parent_v.expr, parent_v.typ)
1043 if resolved_parent_type != 0 {
1044 resolved_parent :=
1045 g.unwrap_generic(g.recheck_concrete_type(resolved_parent_type))
1046 if g.type_has_unresolved_generic_parts(resolved_parent) {
1047 call_like_type := g.resolved_call_like_expr_type(parent_v.expr)
1048 if call_like_type != 0 && !call_like_type.has_flag(.generic)
1049 && !g.type_has_unresolved_generic_parts(call_like_type) {
1050 return call_like_type
1051 }
1052 }
1053 return resolved_parent
1054 }
1055 }
1056 if parent_v.typ != 0 {
1057 return g.unwrap_generic(g.recheck_concrete_type(parent_v.typ))
1058 }
1059 }
1060 }
1061 }
1062 if v.smartcasts.len > 0 {
1063 smartcast_type := if v.ct_type_var == .smartcast {
1064 g.type_resolver.get_type(expr)
1065 } else {
1066 g.exposed_smartcast_type(v.orig_type, v.smartcasts.last(), v.is_mut)
1067 }
1068 return g.unwrap_generic(g.recheck_concrete_type(smartcast_type))
1069 }
1070 if v.is_unwrapped {
1071 $if trace_ci_fixes ? {
1072 if g.file.path.contains('comptime_for_in_options_struct_test.v')
1073 && expr.name in ['v', 'w'] {
1074 typ_name := if v.typ == 0 { '0' } else { g.table.type_to_str(v.typ) }
1075 orig_name := if v.orig_type == 0 {
1076 '0'
1077 } else {
1078 g.table.type_to_str(v.orig_type)
1079 }
1080 refreshed_name := if refreshed_expr_type == 0 {
1081 '0'
1082 } else {
1083 g.table.type_to_str(refreshed_expr_type)
1084 }
1085 eprintln('resolved_scope_var_type unwrapped ${expr.name}: typ=${typ_name} orig=${orig_name} refreshed=${refreshed_name}')
1086 }
1087 }
1088 if refreshed_expr_type != 0 && refreshed_expr_type.has_option_or_result() {
1089 return g.unwrap_generic(g.recheck_concrete_type(refreshed_expr_type.clear_option_and_result()))
1090 }
1091 unwrapped_type := if v.orig_type != ast.no_type && v.orig_type.has_option_or_result() {
1092 v.orig_type.clear_option_and_result()
1093 } else {
1094 v.typ.clear_option_and_result()
1095 }
1096 if unwrapped_type != 0 && unwrapped_type != ast.void_type {
1097 return g.unwrap_generic(g.recheck_concrete_type(unwrapped_type))
1098 }
1099 }
1100 if v.typ != 0 {
1101 return g.unwrap_generic(g.recheck_concrete_type(v.typ))
1102 }
1103 }
1104 return 0
1105}
1106
1107fn (mut g Gen) resolved_ident_is_auto_heap_not_stack(expr ast.Ident) bool {
1108 if expr.obj is ast.Var {
1109 if expr.obj.is_auto_heap && !expr.obj.is_stack_obj {
1110 return true
1111 }
1112 }
1113 if expr.scope != unsafe { nil } {
1114 if v := expr.scope.find_var(expr.name) {
1115 return v.is_auto_heap && !v.is_stack_obj
1116 }
1117 }
1118 return false
1119}
1120
1121fn (mut g Gen) resolved_ident_is_auto_heap(expr ast.Ident) bool {
1122 if expr.obj is ast.Var && expr.obj.is_auto_heap {
1123 return true
1124 }
1125 if expr.scope != unsafe { nil } {
1126 if v := expr.scope.find_var(expr.name) {
1127 return v.is_auto_heap
1128 }
1129 }
1130 return false
1131}
1132
1133fn (g &Gen) resolved_ident_is_auto_deref(expr ast.Ident) bool {
1134 if expr.scope != unsafe { nil } {
1135 if v := expr.scope.find_var(expr.name) {
1136 return v.is_auto_deref
1137 }
1138 }
1139 if expr.obj is ast.Var {
1140 return expr.obj.is_auto_deref
1141 }
1142 return false
1143}
1144
1145fn (g &Gen) resolved_ident_is_by_value_auto_deref_capture(expr ast.Ident) bool {
1146 if expr.scope == unsafe { nil } || expr.scope.parent == unsafe { nil } {
1147 return false
1148 }
1149 scope_var := expr.scope.find_var(expr.name) or { return false }
1150 if !scope_var.is_inherited || scope_var.is_auto_deref {
1151 return false
1152 }
1153 parent_var := expr.scope.parent.find_var(expr.name) or { return false }
1154 return parent_var.is_auto_deref && parent_var.typ.is_ptr()
1155}
1156
1157fn (g &Gen) expr_is_auto_deref_var(expr ast.Expr) bool {
1158 return match expr {
1159 ast.Ident { g.resolved_ident_is_auto_deref(expr) }
1160 else { expr.is_auto_deref_var() }
1161 }
1162}
1163
1164// scope_ident_is_auto_heap reports whether `expr`'s scope variable has
1165// is_auto_heap set. Unlike `resolved_ident_is_auto_heap`, this ignores
1166// `expr.obj.is_auto_heap` because a use-site Ident's obj copy may have been
1167// toggled by `mark_as_referenced` even when the declaration was emitted as
1168// a value (e.g. vars declared inside nested scopes where fn_scope.find_var
1169// misses them).
1170fn (mut g Gen) scope_ident_is_auto_heap(expr ast.Ident) bool {
1171 if expr.scope != unsafe { nil } {
1172 if v := expr.scope.find_var(expr.name) {
1173 return v.is_auto_heap
1174 }
1175 }
1176 return false
1177}
1178
1179fn (mut g Gen) resolved_ident_array_elem_type(expr ast.Ident) ast.Type {
1180 scope_type := g.resolved_scope_var_type(expr)
1181 if scope_type != 0 {
1182 elem_type := g.recheck_concrete_type(g.table.value_type(g.unwrap_generic(scope_type)))
1183 if elem_type != 0 {
1184 return g.unwrap_generic(elem_type)
1185 }
1186 }
1187 if expr.obj !is ast.Var {
1188 return 0
1189 }
1190 var_obj := expr.obj as ast.Var
1191 if var_obj.expr is ast.ArrayInit {
1192 array_init := var_obj.expr as ast.ArrayInit
1193 if array_init.elem_type != 0 {
1194 return g.unwrap_generic(g.recheck_concrete_type(array_init.elem_type))
1195 }
1196 if array_init.typ != 0 {
1197 elem_type :=
1198 g.recheck_concrete_type(g.table.value_type(g.unwrap_generic(array_init.typ)))
1199 if elem_type != 0 {
1200 return g.unwrap_generic(elem_type)
1201 }
1202 }
1203 }
1204 if var_obj.typ != 0 {
1205 elem_type := g.recheck_concrete_type(g.table.value_type(g.unwrap_generic(var_obj.typ)))
1206 if elem_type != 0 {
1207 return g.unwrap_generic(elem_type)
1208 }
1209 }
1210 return 0
1211}
1212
1213fn (mut g Gen) resolved_ident_map_key_type(expr ast.Ident) ast.Type {
1214 scope_type := g.resolved_scope_var_type(expr)
1215 if scope_type != 0 {
1216 typ_sym := g.table.final_sym(g.unwrap_generic(scope_type))
1217 if typ_sym.kind == .map {
1218 key_type := g.recheck_concrete_type(typ_sym.map_info().key_type)
1219 if key_type != 0 {
1220 return g.unwrap_generic(key_type)
1221 }
1222 }
1223 }
1224 if expr.obj !is ast.Var {
1225 return 0
1226 }
1227 var_obj := expr.obj as ast.Var
1228 if var_obj.expr is ast.MapInit {
1229 map_init := var_obj.expr as ast.MapInit
1230 if map_init.key_type != 0 {
1231 return g.unwrap_generic(g.recheck_concrete_type(map_init.key_type))
1232 }
1233 }
1234 if var_obj.typ != 0 {
1235 typ_sym := g.table.final_sym(g.unwrap_generic(var_obj.typ))
1236 if typ_sym.kind == .map {
1237 key_type := g.recheck_concrete_type(typ_sym.map_info().key_type)
1238 if key_type != 0 {
1239 return g.unwrap_generic(key_type)
1240 }
1241 }
1242 }
1243 return 0
1244}
1245
1246fn (mut g Gen) resolved_ident_map_value_type(expr ast.Ident) ast.Type {
1247 scope_type := g.resolved_scope_var_type(expr)
1248 if scope_type != 0 {
1249 typ_sym := g.table.final_sym(g.unwrap_generic(scope_type))
1250 if typ_sym.kind == .map {
1251 val_type := g.recheck_concrete_type(typ_sym.map_info().value_type)
1252 if val_type != 0 {
1253 return g.unwrap_generic(val_type)
1254 }
1255 }
1256 }
1257 if expr.obj !is ast.Var {
1258 return 0
1259 }
1260 var_obj := expr.obj as ast.Var
1261 if var_obj.expr is ast.MapInit {
1262 map_init := var_obj.expr as ast.MapInit
1263 if map_init.value_type != 0 {
1264 return g.unwrap_generic(g.recheck_concrete_type(map_init.value_type))
1265 }
1266 }
1267 if var_obj.typ != 0 {
1268 typ_sym := g.table.final_sym(g.unwrap_generic(var_obj.typ))
1269 if typ_sym.kind == .map {
1270 val_type := g.recheck_concrete_type(typ_sym.map_info().value_type)
1271 if val_type != 0 {
1272 return g.unwrap_generic(val_type)
1273 }
1274 }
1275 }
1276 return 0
1277}
1278
1279fn (mut g Gen) resolved_map_key_value_types(map_type ast.Type, fallback_key_type ast.Type, fallback_value_type ast.Type) (ast.Type, ast.Type) {
1280 mut key_type := g.unwrap_generic(g.recheck_concrete_type(fallback_key_type))
1281 mut value_type := g.unwrap_generic(g.recheck_concrete_type(fallback_value_type))
1282 resolved_map_type := g.unwrap_generic(g.recheck_concrete_type(map_type))
1283 map_sym := g.table.final_sym(resolved_map_type)
1284 if map_sym.kind == .map {
1285 map_info := map_sym.map_info()
1286 resolved_key := g.unwrap_generic(g.recheck_concrete_type(map_info.key_type))
1287 resolved_value := g.unwrap_generic(g.recheck_concrete_type(map_info.value_type))
1288 if resolved_key != 0 {
1289 key_type = resolved_key
1290 }
1291 if resolved_value != 0 {
1292 value_type = resolved_value
1293 }
1294 if key_type == ast.usize_type || value_type == ast.usize_type {
1295 name_key_type, name_value_type := g.resolved_map_types_from_name(map_sym.name)
1296 if key_type == ast.usize_type && name_key_type != 0 {
1297 key_type = name_key_type
1298 }
1299 if value_type == ast.usize_type && name_value_type != 0 {
1300 value_type = name_value_type
1301 }
1302 }
1303 }
1304 if key_type == 0 {
1305 key_type = fallback_key_type
1306 }
1307 if value_type == 0 {
1308 value_type = fallback_value_type
1309 }
1310 return key_type, value_type
1311}
1312
1313fn (mut g Gen) resolved_map_type_from_expr(expr ast.Expr, default_type ast.Type) ast.Type {
1314 mut map_type := g.recheck_concrete_type(default_type)
1315 resolved_type := g.recheck_concrete_type(g.resolved_expr_type(expr, default_type))
1316 if resolved_type != 0
1317 && (g.cur_concrete_types.len > 0 || map_type == 0 || map_type.has_flag(.generic)
1318 || g.type_has_unresolved_generic_parts(map_type)
1319 || g.unwrap_generic(resolved_type) != g.unwrap_generic(map_type)) {
1320 map_type = resolved_type
1321 }
1322 return map_type
1323}
1324
1325fn (mut g Gen) resolved_array_elem_type_from_name(name string) ast.Type {
1326 if !name.starts_with('[]') {
1327 return 0
1328 }
1329 elem_type := g.table.find_type(name[2..])
1330 if elem_type != 0 {
1331 return g.unwrap_generic(g.recheck_concrete_type(elem_type))
1332 }
1333 return 0
1334}
1335
1336fn split_map_type_name(name string) (string, string) {
1337 if !name.starts_with('map[') {
1338 return '', ''
1339 }
1340 mut depth := 1
1341 mut i := 4
1342 for i < name.len {
1343 ch := name[i]
1344 if ch == `[` {
1345 depth++
1346 } else if ch == `]` {
1347 depth--
1348 if depth == 0 {
1349 break
1350 }
1351 }
1352 i++
1353 }
1354 if depth != 0 || i >= name.len {
1355 return '', ''
1356 }
1357 return name[4..i], name[i + 1..]
1358}
1359
1360fn (mut g Gen) resolved_map_types_from_name(name string) (ast.Type, ast.Type) {
1361 key_name, val_name := split_map_type_name(name)
1362 if key_name.len == 0 || val_name.len == 0 {
1363 return ast.Type(0), ast.Type(0)
1364 }
1365 key_type := g.table.find_type(key_name)
1366 val_type := g.table.find_type(val_name)
1367 return g.unwrap_generic(g.recheck_concrete_type(key_type)), g.unwrap_generic(g.recheck_concrete_type(val_type))
1368}
1369
1370fn (mut g Gen) resolved_call_like_expr_type(expr ast.Expr) ast.Type {
1371 match expr {
1372 ast.CallExpr {
1373 resolved := g.resolve_return_type(expr)
1374 if resolved != ast.void_type {
1375 return g.unwrap_generic(g.recheck_concrete_type(resolved)).clear_option_and_result()
1376 }
1377 }
1378 ast.PostfixExpr {
1379 resolved := g.resolved_call_like_expr_type(expr.expr)
1380 if resolved != 0 {
1381 return g.unwrap_generic(resolved).clear_option_and_result()
1382 }
1383 }
1384 ast.UnsafeExpr {
1385 return g.resolved_call_like_expr_type(expr.expr)
1386 }
1387 else {}
1388 }
1389
1390 return 0
1391}
1392
1393// resolved_expr_type recomputes the concrete type for expr nodes that can keep
1394// stale generic metadata across concrete rechecks/codegen.
1395fn (mut g Gen) resolved_or_block_value_type(or_expr ast.OrExpr) ast.Type {
1396 if or_expr.stmts.len == 0 {
1397 return 0
1398 }
1399 last_or_stmt := or_expr.stmts.last()
1400 if last_or_stmt is ast.ExprStmt && last_or_stmt.typ != ast.void_type {
1401 resolved_or_type := g.resolved_expr_type(last_or_stmt.expr, last_or_stmt.typ)
1402 if resolved_or_type != 0 && resolved_or_type != ast.void_type {
1403 return g.unwrap_generic(g.recheck_concrete_type(resolved_or_type))
1404 }
1405 }
1406 return 0
1407}
1408
1409// resolve_selector_smartcast_type resolves the final smartcast type for a
1410// selector expression in generic contexts. When a field like `val.field` has
1411// nested smartcasts (e.g., option unwrap then sumtype variant), the scope
1412// stores these smartcasts but they may reference stale types from a previous
1413// generic instantiation. This function re-resolves them using current concrete
1414// types to determine the correct final type.
1415fn (mut g Gen) resolve_selector_smartcast_type(node ast.SelectorExpr) ast.Type {
1416 scope := g.file.scope.innermost(node.pos.pos)
1417 field := scope.find_struct_field(node.expr.str(), node.expr_type, node.field_name)
1418 if field != unsafe { nil } && field.smartcasts.len > 0 {
1419 smartcast_type := field.smartcasts.last()
1420 field_unwrapped_type := field.orig_type.clear_option_and_result()
1421 if field.orig_type.has_option_or_result() && !smartcast_type.has_option_or_result()
1422 && smartcast_type == field_unwrapped_type {
1423 left_default := if node.expr_type != 0 { node.expr_type } else { field.struct_type }
1424 left_type := g.resolved_expr_type(node.expr, left_default)
1425 resolved_field_type := g.resolved_selector_field_type(node, left_type)
1426 if resolved_field_type != 0 {
1427 return resolved_field_type.clear_option_and_result()
1428 }
1429 }
1430 resolved_sc := g.unwrap_generic(g.recheck_concrete_type(g.exposed_smartcast_type(field.orig_type,
1431 smartcast_type, field.is_mut)))
1432 if resolved_sc != 0 {
1433 return resolved_sc
1434 }
1435 }
1436 return 0
1437}
1438
1439fn (mut g Gen) resolved_selector_field_type(node ast.SelectorExpr, receiver_type ast.Type) ast.Type {
1440 if receiver_type == 0 {
1441 return 0
1442 }
1443 sym := g.table.sym(g.unwrap_generic(receiver_type))
1444 if field := g.table.find_field_with_embeds(sym, node.field_name) {
1445 mut field_type := field.typ
1446 match sym.info {
1447 ast.Struct, ast.Interface, ast.SumType {
1448 mut generic_names := sym.info.generic_types.map(g.table.sym(it).name)
1449 mut concrete_types := sym.info.concrete_types.clone()
1450 if concrete_types.len == 0 && sym.generic_types.len == generic_names.len
1451 && sym.generic_types != sym.info.generic_types {
1452 concrete_types = sym.generic_types.clone()
1453 }
1454 mut source_field_type := field.typ
1455 if sym.info.parent_type.has_flag(.generic) {
1456 parent_sym := g.table.sym(sym.info.parent_type)
1457 if parent_field := g.table.find_field_with_embeds(parent_sym, node.field_name) {
1458 source_field_type = parent_field.typ
1459 match parent_sym.info {
1460 ast.Struct, ast.Interface, ast.SumType {
1461 generic_names =
1462 parent_sym.info.generic_types.map(g.table.sym(it).name)
1463 }
1464 else {}
1465 }
1466 }
1467 }
1468 if generic_names.len == concrete_types.len && concrete_types.len > 0 {
1469 mut muttable := unsafe { &ast.Table(g.table) }
1470 resolved_field_type := muttable.unwrap_generic_type_ex(source_field_type,
1471 generic_names, concrete_types, true)
1472 if resolved_field_type != source_field_type {
1473 field_type = resolved_field_type
1474 } else {
1475 if converted_field_type := muttable.convert_generic_type(source_field_type,
1476 generic_names, concrete_types)
1477 {
1478 field_type = converted_field_type
1479 }
1480 }
1481 }
1482 }
1483 ast.GenericInst {
1484 parent_sym := g.table.sym(ast.new_type(sym.info.parent_idx))
1485 mut source_field_type := field.typ
1486 if parent_field := g.table.find_field_with_embeds(parent_sym, node.field_name) {
1487 source_field_type = parent_field.typ
1488 }
1489 match parent_sym.info {
1490 ast.Struct, ast.Interface, ast.SumType {
1491 generic_names := parent_sym.info.generic_types.map(g.table.sym(it).name)
1492 if generic_names.len == sym.info.concrete_types.len
1493 && sym.info.concrete_types.len > 0 {
1494 mut muttable := unsafe { &ast.Table(g.table) }
1495 resolved_field_type := muttable.unwrap_generic_type_ex(source_field_type,
1496 generic_names, sym.info.concrete_types, true)
1497 if resolved_field_type != source_field_type {
1498 field_type = resolved_field_type
1499 } else {
1500 if converted_field_type := muttable.convert_generic_type(source_field_type,
1501 generic_names, sym.info.concrete_types)
1502 {
1503 field_type = converted_field_type
1504 }
1505 }
1506 }
1507 }
1508 else {}
1509 }
1510 }
1511 else {}
1512 }
1513
1514 $if trace_ci_fixes ? {
1515 if g.file.path.contains('binary_search_tree.v') && node.expr is ast.Ident
1516 && node.expr.name == 'tree' {
1517 eprintln('resolved selector ${node.expr.name}.${node.field_name} left=${g.table.type_to_str(receiver_type)} field=${g.table.type_to_str(field.typ)} final=${g.table.type_to_str(field_type)} expr_typ=${g.table.type_to_str(node.typ)}')
1518 }
1519 }
1520 return g.unwrap_generic(g.recheck_concrete_type(field_type))
1521 }
1522 return 0
1523}
1524
1525fn (mut g Gen) resolved_expr_type(expr ast.Expr, default_typ ast.Type) ast.Type {
1526 match expr {
1527 ast.ParExpr {
1528 return g.resolved_expr_type(expr.expr, default_typ)
1529 }
1530 ast.CTempVar {
1531 if expr.typ != 0 {
1532 return g.unwrap_generic(g.recheck_concrete_type(expr.typ))
1533 }
1534 return g.resolved_expr_type(expr.orig, default_typ)
1535 }
1536 ast.Ident {
1537 if expr.obj is ast.Var {
1538 if expr.obj.typ != 0 && expr.obj.generic_typ == 0 && !expr.obj.is_inherited
1539 && !expr.obj.is_unwrapped && !expr.obj.is_assignment_smartcast
1540 && !expr.obj.is_or && expr.obj.orig_type == ast.no_type
1541 && expr.obj.smartcasts.len == 0 && expr.obj.ct_type_var == .no_comptime
1542 && !g.has_current_generic_context() && !g.has_active_call_generic_context() {
1543 if g.type_is_known_concrete(expr.obj.typ) {
1544 return expr.obj.typ
1545 }
1546 }
1547 if g.cur_fn != unsafe { nil } && g.cur_fn.is_method
1548 && expr.name == g.cur_fn.receiver.name {
1549 // In generic contexts, prefer resolving from the receiver declaration
1550 // since scope types may be stale from a previous checker instantiation
1551 if g.cur_concrete_types.len > 0 && (g.cur_fn.receiver.typ.has_flag(.generic)
1552 || g.type_has_unresolved_generic_parts(g.cur_fn.receiver.typ)) {
1553 resolved_receiver_type :=
1554 g.unwrap_generic(g.recheck_concrete_type(g.cur_fn.receiver.typ))
1555 if resolved_receiver_type != 0 {
1556 return resolved_receiver_type
1557 }
1558 }
1559 scope_type := g.resolved_scope_var_type(expr)
1560 if scope_type != 0 {
1561 return scope_type
1562 }
1563 resolved_receiver_type :=
1564 g.unwrap_generic(g.recheck_concrete_type(g.cur_fn.receiver.typ))
1565 if resolved_receiver_type != 0 {
1566 return resolved_receiver_type
1567 }
1568 }
1569 if g.cur_fn != unsafe { nil } && g.cur_concrete_types.len > 0
1570 && expr.obj.expr is ast.Ident {
1571 ident_expr := expr.obj.expr as ast.Ident
1572 if ident_expr.or_expr.kind != .absent {
1573 resolved_or_type := g.resolved_or_block_value_type(ident_expr.or_expr)
1574 if resolved_or_type != 0 {
1575 return resolved_or_type
1576 }
1577 }
1578 }
1579 if expr.obj.ct_type_var == .generic_param {
1580 resolved := g.resolve_current_fn_generic_param_type(expr.name)
1581 if resolved != 0 {
1582 return g.unwrap_generic(g.recheck_concrete_type(resolved))
1583 }
1584 }
1585 // In generic contexts, if the variable has smartcasts with generic
1586 // types (preserved in node.obj), resolve from those instead of
1587 // relying on scope types which may be stale from a different
1588 // generic instantiation.
1589 if g.cur_fn != unsafe { nil } && g.cur_concrete_types.len > 0
1590 && expr.obj.smartcasts.len > 0 && expr.obj.smartcasts.any(it.has_flag(.generic)
1591 || g.type_has_unresolved_generic_parts(it)) {
1592 obj_smartcast_type := g.exposed_smartcast_type(expr.obj.orig_type,
1593 expr.obj.smartcasts.last(), expr.obj.is_mut)
1594 resolved_sc := g.unwrap_generic(g.recheck_concrete_type(obj_smartcast_type))
1595 if resolved_sc != 0 {
1596 return resolved_sc
1597 }
1598 }
1599 scope_type := g.resolved_scope_var_type(expr)
1600 if scope_type != 0 && !scope_type.has_flag(.generic)
1601 && !g.type_has_unresolved_generic_parts(scope_type) {
1602 if !expr.obj.is_arg
1603 || (g.cur_fn != unsafe { nil } && g.cur_concrete_types.len > 0) {
1604 // For generic_var in generic contexts, prefer expression-based
1605 // resolution first (scope types may be stale from a previous
1606 // instantiation), but fall back to scope type if expr resolution
1607 // fails.
1608 if g.cur_fn != unsafe { nil } && g.cur_concrete_types.len > 0
1609 && expr.obj.ct_type_var == .generic_var
1610 && expr.obj.typ.has_flag(.generic) {
1611 // Try expression-based resolution first
1612 if expr.obj.expr !is ast.EmptyExpr && !(expr.obj.expr is ast.Ident
1613 && expr.obj.expr.name == expr.name) {
1614 resolved := g.resolved_expr_type(expr.obj.expr, expr.obj.typ)
1615 if resolved != 0 {
1616 return g.unwrap_generic(resolved)
1617 }
1618 }
1619 }
1620 // In generic contexts, scope types may be stale from a previous
1621 // checker instantiation. If the variable's init expression is a
1622 // struct init whose type name matches a generic parameter, re-resolve
1623 // using the current concrete types.
1624 if g.cur_fn != unsafe { nil } && g.cur_concrete_types.len > 0
1625 && expr.obj.expr is ast.StructInit {
1626 generic_names := g.current_fn_generic_names()
1627 struct_init_typ_str := expr.obj.expr.typ_str.all_after_last('.')
1628 idx := generic_names.index(struct_init_typ_str)
1629 if idx >= 0 && idx < g.cur_concrete_types.len {
1630 return g.cur_concrete_types[idx]
1631 }
1632 }
1633 return scope_type
1634 }
1635 }
1636 if expr.obj.expr !is ast.EmptyExpr
1637 && (expr.obj.ct_type_var == .generic_var || expr.obj.typ.has_flag(.generic)
1638 || g.type_has_unresolved_generic_parts(expr.obj.typ)
1639 || ((g.cur_fn != unsafe { nil } && g.cur_concrete_types.len > 0)
1640 && expr.obj.expr !in [ast.IntegerLiteral, ast.FloatLiteral, ast.StringLiteral, ast.BoolLiteral, ast.CharLiteral])) {
1641 if !(expr.obj.expr is ast.Ident && expr.obj.expr.name == expr.name) {
1642 mut resolved := g.resolved_expr_type(expr.obj.expr, expr.obj.typ)
1643 if resolved != 0 {
1644 resolved = g.unwrap_generic(g.recheck_concrete_type(resolved))
1645 if expr.obj.typ != 0 {
1646 resolved_obj_type :=
1647 g.unwrap_generic(g.recheck_concrete_type(expr.obj.typ))
1648 if resolved_obj_type != 0
1649 && !g.type_has_unresolved_generic_parts(resolved_obj_type)
1650 && resolved.has_option_or_result()
1651 && resolved.clear_option_and_result() == resolved_obj_type {
1652 return resolved_obj_type
1653 }
1654 }
1655 if g.type_has_unresolved_generic_parts(resolved) {
1656 call_like_type := g.resolved_call_like_expr_type(expr.obj.expr)
1657 if call_like_type != 0 && !call_like_type.has_flag(.generic)
1658 && !g.type_has_unresolved_generic_parts(call_like_type) {
1659 return call_like_type
1660 }
1661 }
1662 return g.unwrap_generic(resolved)
1663 }
1664 }
1665 }
1666 if expr.obj.ct_type_var != .no_comptime && expr.obj.ct_type_var != .generic_param {
1667 ctyp := g.type_resolver.get_type(expr)
1668 if ctyp != ast.void_type {
1669 return g.unwrap_generic(ctyp)
1670 }
1671 }
1672 }
1673 if g.cur_fn != unsafe { nil } && g.cur_fn.generic_names.len > 0
1674 && g.cur_concrete_types.len > 0 {
1675 resolved := g.resolve_current_fn_generic_param_type(expr.name)
1676 if resolved != 0 {
1677 return g.unwrap_generic(g.recheck_concrete_type(resolved))
1678 }
1679 }
1680 if expr.obj is ast.Var && expr.obj.typ != 0 {
1681 resolved_obj_type := g.unwrap_generic(g.recheck_concrete_type(expr.obj.typ))
1682 if resolved_obj_type != 0 && (expr.obj.is_arg || expr.obj.typ.has_flag(.generic)
1683 || g.type_has_unresolved_generic_parts(expr.obj.typ)) {
1684 return resolved_obj_type
1685 }
1686 }
1687 scope_type := g.resolved_scope_var_type(expr)
1688 if scope_type != 0 && expr.obj is ast.Var
1689 && (expr.obj.is_unwrapped || expr.obj.orig_type != 0 || expr.obj.smartcasts.len > 0) {
1690 return scope_type
1691 }
1692 default_resolved_type := g.unwrap_generic(g.recheck_concrete_type(default_typ))
1693 resolver_type := g.unwrap_generic(g.recheck_concrete_type(g.type_resolver.get_type_or_default(expr,
1694 default_typ)))
1695 if resolver_type != 0 && !g.type_has_unresolved_generic_parts(resolver_type)
1696 && (resolver_type != default_resolved_type || (expr.obj is ast.Var
1697 && (expr.obj.is_unwrapped || expr.obj.orig_type != 0
1698 || expr.obj.smartcasts.len > 0))) {
1699 return resolver_type
1700 }
1701 if scope_type != 0 {
1702 return scope_type
1703 }
1704 }
1705 ast.SelectorExpr {
1706 // If this selector has been smart-cast in the current scope (e.g.
1707 // `if mut w.face is X { ... w.face ... }`), use the smart-cast type
1708 // rather than the field's declared type.
1709 smartcast_typ := g.resolve_selector_smartcast_type(expr)
1710 if smartcast_typ != 0 {
1711 return smartcast_typ
1712 }
1713 left_default := if expr.expr_type != 0 { expr.expr_type } else { default_typ }
1714 left_type := g.recheck_concrete_type(g.resolved_expr_type(expr.expr, left_default))
1715 if left_type != 0 {
1716 mut resolved_type := g.resolved_selector_field_type(expr, left_type)
1717 if resolved_type != 0 {
1718 if expr.or_block.kind != .absent {
1719 resolved_type = resolved_type.clear_option_and_result()
1720 }
1721 return resolved_type
1722 }
1723 }
1724 if expr.typ != 0 {
1725 mut resolved_type := g.unwrap_generic(g.recheck_concrete_type(expr.typ))
1726 if expr.or_block.kind != .absent {
1727 resolved_type = resolved_type.clear_option_and_result()
1728 }
1729 return resolved_type
1730 }
1731 }
1732 ast.IndexExpr {
1733 left_default := if expr.left_type != 0 { expr.left_type } else { default_typ }
1734 left_type := g.recheck_concrete_type(g.resolved_expr_type(expr.left, left_default))
1735 if left_type != 0 {
1736 if expr.index is ast.RangeExpr {
1737 mut slice_type := ast.Type(0)
1738 if expr.left is ast.Ident {
1739 resolved_left_type :=
1740 g.resolve_current_fn_generic_param_type(expr.left.name)
1741 if resolved_left_type != 0 {
1742 slice_type = g.unwrap_generic(resolved_left_type)
1743 }
1744 }
1745 if slice_type == 0 {
1746 slice_type = g.unwrap_generic(left_type)
1747 }
1748 // Slicing returns a new array by value; strip pointer
1749 // from mut params.
1750 slice_type = slice_type.set_nr_muls(0)
1751 // Slicing a fixed array yields a dynamic array.
1752 slice_sym := g.table.final_sym(slice_type)
1753 if slice_sym.info is ast.ArrayFixed {
1754 return ast.new_type(g.table.find_or_register_array(slice_sym.info.elem_type))
1755 }
1756 return slice_type
1757 }
1758 if expr.left is ast.Ident {
1759 resolved_value_type :=
1760 g.resolve_current_fn_generic_param_value_type(expr.left.name)
1761 if resolved_value_type != 0 {
1762 return g.unwrap_generic(resolved_value_type)
1763 }
1764 }
1765 value_type :=
1766 g.recheck_concrete_type(g.table.value_type(g.unwrap_generic(left_type)))
1767 if value_type != 0 {
1768 return g.unwrap_generic(value_type)
1769 }
1770 if expr.typ != 0 && !expr.typ.has_flag(.generic)
1771 && !g.type_has_unresolved_generic_parts(expr.typ) {
1772 return g.unwrap_generic(expr.typ)
1773 }
1774 }
1775 }
1776 ast.InfixExpr {
1777 if expr.op in [.eq, .ne, .gt, .ge, .lt, .le, .logical_or, .and, .key_in, .not_in, .key_is,
1778 .not_is] {
1779 return ast.bool_type
1780 }
1781 // In generic contexts, promoted_type may be stale from a different
1782 // checker instantiation pass. Compute from operand types instead.
1783 if expr.promoted_type != 0 && !expr.promoted_type.has_flag(.generic)
1784 && !g.type_has_unresolved_generic_parts(expr.promoted_type)
1785 && (g.cur_fn == unsafe { nil } || g.cur_concrete_types.len == 0) {
1786 return g.unwrap_generic(g.recheck_concrete_type(expr.promoted_type))
1787 }
1788 left_default := if expr.left_type != 0 { expr.left_type } else { default_typ }
1789 right_default := if expr.right_type != 0 { expr.right_type } else { default_typ }
1790 left_type := g.resolved_expr_type(expr.left, left_default)
1791 right_type := g.resolved_expr_type(expr.right, right_default)
1792 if expr.op in [.plus, .minus, .mul, .power, .div, .mod] {
1793 if left_type == right_type && left_type != 0
1794 && left_type !in [ast.int_literal_type, ast.float_literal_type] {
1795 return g.unwrap_generic(left_type)
1796 }
1797 promoted := g.type_resolver.promote_type(g.unwrap_generic(left_type),
1798 g.unwrap_generic(right_type))
1799 if promoted != ast.void_type {
1800 return g.unwrap_generic(promoted)
1801 }
1802 }
1803 if expr.op in [.left_shift, .right_shift, .amp, .pipe, .xor] && left_type != 0 {
1804 return g.unwrap_generic(left_type)
1805 }
1806 }
1807 ast.IfGuardExpr {
1808 // A variable bound by an `if x := opt() {` guard stores the whole
1809 // `IfGuardExpr` as its init expression. Resolve from the guard's source
1810 // expression so the variable's type follows the current generic
1811 // instantiation, instead of a stale type baked from a different one
1812 // (see issue #27205). Only single-var guards map to one value type.
1813 if expr.vars.len == 1 {
1814 resolved := g.resolved_expr_type(expr.expr, if expr.expr_type != 0 {
1815 expr.expr_type
1816 } else {
1817 default_typ
1818 })
1819 if resolved != 0 {
1820 return g.unwrap_generic(g.recheck_concrete_type(resolved)).clear_option_and_result()
1821 }
1822 }
1823 }
1824 ast.IfExpr {
1825 inferred_typ := g.infer_if_expr_type(expr)
1826 if inferred_typ != 0 && inferred_typ != ast.void_type {
1827 return inferred_typ
1828 }
1829 }
1830 ast.MatchExpr {
1831 inferred_typ := g.infer_match_expr_type(expr)
1832 if inferred_typ != 0 && inferred_typ != ast.void_type {
1833 return inferred_typ
1834 }
1835 }
1836 ast.CallExpr {
1837 if expr.kind == .type_name {
1838 return ast.string_type
1839 }
1840 if expr.kind == .type_idx {
1841 return ast.int_type
1842 }
1843 resolved := g.resolve_return_type(expr)
1844 if resolved != ast.void_type {
1845 return if expr.or_block.kind == .absent {
1846 g.unwrap_generic(g.recheck_concrete_type(resolved))
1847 } else {
1848 g.unwrap_generic(g.recheck_concrete_type(resolved)).clear_option_and_result()
1849 }
1850 }
1851 // When resolve_return_type fails (e.g. fn field call where no method exists),
1852 // try resolving from return_type_generic using receiver generic type names.
1853 // This handles cases like Procedure[T,U].handle() calling p.function(p.value)
1854 // where return_type is contaminated from the last checker pass but
1855 // return_type_generic preserves the original generic return type (!U).
1856 if expr.return_type_generic != 0 && expr.return_type_generic.has_flag(.generic)
1857 && g.cur_fn != unsafe { nil } && g.cur_fn.is_method
1858 && g.cur_fn.receiver.typ.has_flag(.generic) && g.cur_concrete_types.len > 0 {
1859 receiver_generic_names := g.table.generic_type_names(g.cur_fn.receiver.typ)
1860 if receiver_generic_names.len == g.cur_concrete_types.len {
1861 if gen_type := g.table.convert_generic_type(expr.return_type_generic,
1862 receiver_generic_names, g.cur_concrete_types)
1863 {
1864 if !gen_type.has_flag(.generic) {
1865 return if expr.or_block.kind == .absent {
1866 gen_type
1867 } else {
1868 gen_type.clear_option_and_result()
1869 }
1870 }
1871 }
1872 }
1873 }
1874 if expr.return_type != 0 {
1875 return if expr.or_block.kind == .absent {
1876 g.unwrap_generic(g.recheck_concrete_type(expr.return_type))
1877 } else {
1878 g.unwrap_generic(g.recheck_concrete_type(expr.return_type)).clear_option_and_result()
1879 }
1880 }
1881 }
1882 ast.ComptimeCall {
1883 if expr.kind == .method && g.comptime.comptime_for_method != unsafe { nil } {
1884 sym := g.table.sym(g.unwrap_generic(expr.left_type))
1885 if m := sym.find_method(g.comptime.comptime_for_method.name) {
1886 return m.return_type
1887 }
1888 }
1889 }
1890 ast.ComptimeSelector {
1891 if expr.is_method {
1892 ctyp := g.type_resolver.get_comptime_selector_type(expr, ast.void_type)
1893 if ctyp != ast.void_type {
1894 return g.unwrap_generic(ctyp)
1895 }
1896 if expr.typ != ast.void_type && expr.typ != 0 {
1897 return g.unwrap_generic(expr.typ)
1898 }
1899 } else if expr.typ_key != '' {
1900 ctyp := g.type_resolver.get_ct_type_or_default(expr.typ_key, default_typ)
1901 if ctyp != ast.void_type {
1902 return g.unwrap_generic(ctyp)
1903 }
1904 }
1905 if expr.left_type != 0 {
1906 return g.unwrap_generic(expr.left_type)
1907 }
1908 }
1909 ast.CastExpr {
1910 if expr.typ != 0 {
1911 return g.unwrap_generic(g.recheck_concrete_type(expr.typ))
1912 }
1913 }
1914 ast.ArrayInit {
1915 base_array_typ := if expr.generic_typ != 0 { expr.generic_typ } else { expr.typ }
1916 base_elem_typ := if expr.generic_elem_type != 0 {
1917 expr.generic_elem_type
1918 } else {
1919 expr.elem_type
1920 }
1921 if g.cur_fn != unsafe { nil } && g.cur_concrete_types.len > 0 && base_array_typ != 0
1922 && expr.exprs.len > 0 && !expr.is_fixed {
1923 array_type := g.unwrap_generic(g.recheck_concrete_type(base_array_typ))
1924 if g.table.final_sym(array_type).kind == .array {
1925 mut inferred_elem_type := ast.void_type
1926 for i, elem_expr in expr.exprs {
1927 mut default_elem_type := base_elem_typ
1928 if default_elem_type == 0 {
1929 default_elem_type = g.table.value_type(array_type)
1930 }
1931 if inferred_elem_type != ast.void_type {
1932 default_elem_type = inferred_elem_type
1933 }
1934 mut resolved_elem_type := ast.void_type
1935 if elem_expr is ast.Ident {
1936 resolved_elem_type = g.resolved_scope_var_type(elem_expr)
1937 }
1938 if resolved_elem_type == ast.void_type {
1939 expr_default_type := if expr.expr_types.len > i
1940 && expr.expr_types[i] != 0 {
1941 expr.expr_types[i]
1942 } else {
1943 default_elem_type
1944 }
1945 resolved_elem_type = g.unwrap_generic(g.recheck_concrete_type(g.resolved_expr_type(elem_expr,
1946 expr_default_type)))
1947 }
1948 if resolved_elem_type != 0 && resolved_elem_type != ast.void_type {
1949 inferred_elem_type = resolved_elem_type
1950 }
1951 }
1952 if inferred_elem_type != ast.void_type {
1953 return g.table.find_or_register_array(g.unwrap_generic(inferred_elem_type))
1954 }
1955 }
1956 }
1957 if base_array_typ != 0 {
1958 return g.unwrap_generic(g.recheck_concrete_type(base_array_typ))
1959 }
1960 }
1961 ast.StructInit {
1962 // For `T{}` where T is a generic parameter, typ_str preserves the
1963 // original name (e.g. 'main.T') even after the type has been resolved
1964 // to a concrete type. Use it to look up the current concrete type.
1965 if expr.typ_str.len > 0 && g.cur_fn != unsafe { nil } && g.cur_concrete_types.len > 0 {
1966 generic_names := g.current_fn_generic_names()
1967 short_name := expr.typ_str.all_after_last('.')
1968 idx := generic_names.index(short_name)
1969 if idx >= 0 && idx < g.cur_concrete_types.len {
1970 return g.cur_concrete_types[idx]
1971 }
1972 }
1973 // In generic contexts, use generic_typ to allow resolution via
1974 // recheck_concrete_type/unwrap_generic only when the struct init type
1975 // itself still has unresolved generic parts (short syntax or generic flag).
1976 // For explicitly typed inits (e.g. LinkedList[StructFieldInfo]{}),
1977 // preserve expr.typ to avoid incorrectly substituting the inner struct's
1978 // generic parameter with the enclosing function's concrete type.
1979 base_struct_typ := if expr.generic_typ != 0 && g.cur_fn != unsafe { nil }
1980 && g.cur_concrete_types.len > 0 {
1981 if expr.is_short_syntax || expr.typ.has_flag(.generic) || expr.typ == ast.void_type {
1982 expr.generic_typ
1983 } else {
1984 expr.typ
1985 }
1986 } else if expr.typ != 0 {
1987 expr.typ
1988 } else {
1989 expr.generic_typ
1990 }
1991 if base_struct_typ != 0 {
1992 return g.unwrap_generic(g.recheck_concrete_type(base_struct_typ))
1993 }
1994 }
1995 ast.MapInit {
1996 if expr.typ != 0 {
1997 return g.unwrap_generic(g.recheck_concrete_type(expr.typ))
1998 }
1999 }
2000 ast.AsCast {
2001 return g.unwrap_generic(g.recheck_concrete_type(expr.typ))
2002 }
2003 ast.UnsafeExpr {
2004 return g.resolved_expr_type(expr.expr, default_typ)
2005 }
2006 ast.PrefixExpr {
2007 right_default := if expr.right_type != 0 { expr.right_type } else { default_typ }
2008 inner_type := g.resolved_expr_type(expr.right, right_default)
2009 return match expr.op {
2010 .amp {
2011 // When the inner expr is an auto-deref var (e.g. mut param),
2012 // codegen skips emitting & since the var is already a pointer.
2013 // Don't add .ref() to match.
2014 if expr.right.is_auto_deref_var() {
2015 g.unwrap_generic(inner_type)
2016 } else {
2017 g.unwrap_generic(inner_type).ref()
2018 }
2019 }
2020 .mul {
2021 resolved_inner_type := g.unwrap_generic(inner_type)
2022 if resolved_inner_type.is_ptr() {
2023 resolved_inner_type.deref()
2024 } else {
2025 resolved_right_type :=
2026 g.unwrap_generic(g.recheck_concrete_type(right_default))
2027 if resolved_right_type.is_ptr() {
2028 resolved_right_type.deref()
2029 } else {
2030 resolved_inner_type
2031 }
2032 }
2033 }
2034 .arrow {
2035 right_sym := g.table.final_sym(g.unwrap_generic(inner_type))
2036 if right_sym.kind == .chan {
2037 g.unwrap_generic(right_sym.chan_info().elem_type)
2038 } else {
2039 g.unwrap_generic(inner_type)
2040 }
2041 }
2042 else {
2043 g.unwrap_generic(inner_type)
2044 }
2045 }
2046 }
2047 ast.PostfixExpr {
2048 inner_default := if expr.typ != 0 { expr.typ } else { default_typ }
2049 inner_type := g.resolved_expr_type(expr.expr, inner_default)
2050 return if expr.op == .question {
2051 mut resolved_postfix_type := g.unwrap_generic(inner_type)
2052 if resolved_postfix_type != 0 && g.table.sym(resolved_postfix_type).kind == .alias {
2053 unaliased_postfix_type := g.table.unaliased_type(resolved_postfix_type)
2054 if unaliased_postfix_type.has_option_or_result() {
2055 resolved_postfix_type = g.unwrap_generic(unaliased_postfix_type)
2056 }
2057 }
2058 resolved_postfix_type.clear_option_and_result()
2059 } else {
2060 g.unwrap_generic(inner_type)
2061 }
2062 }
2063 else {}
2064 }
2065
2066 resolved := g.type_resolver.get_type_or_default(expr, default_typ)
2067 if resolved != 0 {
2068 return g.unwrap_generic(resolved)
2069 }
2070 return g.unwrap_generic(default_typ)
2071}
2072
2073struct Type {
2074 // typ is the original type
2075 typ ast.Type @[required]
2076 sym &ast.TypeSymbol @[required]
2077 // unaliased is `typ` once aliased have been resolved
2078 // it may not contain information such as flags and nr_muls
2079 unaliased ast.Type @[required]
2080 unaliased_sym &ast.TypeSymbol @[required]
2081}
2082
2083// unwrap returns the following variants of a type:
2084// * generics unwrapped
2085// * alias unwrapped
2086fn (mut g Gen) unwrap(typ ast.Type) Type {
2087 no_generic := g.unwrap_generic(typ)
2088 no_generic_sym := g.table.sym(no_generic)
2089 if no_generic_sym.kind != .alias {
2090 return Type{
2091 typ: no_generic
2092 sym: no_generic_sym
2093 unaliased: no_generic
2094 unaliased_sym: no_generic_sym
2095 }
2096 }
2097 return Type{
2098 typ: no_generic
2099 sym: no_generic_sym
2100 unaliased: no_generic_sym.parent_idx
2101 unaliased_sym: g.table.sym(ast.idx_to_type(no_generic_sym.parent_idx))
2102 }
2103}
2104
2105// generate function variable definition, e.g. `void (*var_name) (int, string)`
2106fn (mut g Gen) fn_var_signature(var_type ast.Type, return_type ast.Type, arg_types []ast.Type, var_name string) string {
2107 if var_type.has_flag(.option) || var_type.has_flag(.result) {
2108 return '${g.styp(var_type)} ${c_fn_name(var_name)}'
2109 }
2110 ret_styp := g.styp(return_type)
2111 nr_muls := var_type.nr_muls()
2112 mut sig := '${ret_styp} (${'*'.repeat(nr_muls + 1)}${c_fn_name(var_name)}) ('
2113 for j, arg_typ in arg_types {
2114 arg_sym := g.table.sym(arg_typ)
2115 if arg_sym.info is ast.FnType {
2116 func := arg_sym.info.func
2117 arg_sig := g.fn_var_signature(arg_typ, func.return_type, func.params.map(it.typ), '')
2118 sig += arg_sig
2119 } else {
2120 arg_styp := g.styp(arg_typ)
2121 sig += arg_styp
2122 }
2123 if j < arg_types.len - 1 {
2124 sig += ', '
2125 }
2126 }
2127 sig += ')'
2128 return sig
2129}
2130
2131// generate anon fn cname, e.g. `anon_fn_void_int_string`, `anon_fn_void_int_ptr_string`
2132fn (mut g Gen) anon_fn_cname(return_type ast.Type, arg_types []ast.Type) string {
2133 ret_styp := g.styp(return_type).replace('*', '_ptr')
2134 mut sig := 'anon_fn_${ret_styp}_'
2135 for j, arg_typ in arg_types {
2136 arg_sym := g.table.sym(arg_typ)
2137 if arg_sym.info is ast.FnType {
2138 sig += g.anon_fn_cname(arg_sym.info.func.return_type,
2139 arg_sym.info.func.params.map(it.typ))
2140 } else {
2141 sig += g.styp(arg_typ).replace('*', '_ptr')
2142 }
2143 if j < arg_types.len - 1 {
2144 sig += '_'
2145 }
2146 }
2147 return sig
2148}
2149
2150// escape quotes for string
2151fn escape_quotes(val string) string {
2152 bs := '\\'
2153 unescaped_val := val.replace('${bs}${bs}', '\x01').replace_each([
2154 "${bs}'",
2155 "'",
2156 '${bs}"',
2157 '"',
2158 ])
2159 return unescaped_val.replace_each(['\x01', '${bs}${bs}', "'", "${bs}'", '"', '${bs}"'])
2160}
2161
2162@[inline]
2163fn (mut g Gen) dot_or_ptr(val_type ast.Type) string {
2164 return if val_type.has_flag(.shared_f) {
2165 '->val.'
2166 } else if val_type.is_ptr() {
2167 '->'
2168 } else {
2169 '.'
2170 }
2171}
2172
2173fn (mut g Gen) unwrap_option_type(typ ast.Type, name string, is_auto_heap bool) {
2174 styp := g.base_type(typ)
2175 if is_auto_heap {
2176 g.write('(*(${styp}*)${name}->data)')
2177 } else {
2178 type_sym := g.table.sym(typ)
2179 if type_sym.kind == .alias {
2180 // Alias to Option type
2181 parent_typ := (type_sym.info as ast.Alias).parent_type
2182 if parent_typ.has_flag(.option) {
2183 g.write('*((${g.base_type(parent_typ)}*)')
2184 }
2185 g.write('(*(${styp}*)${name}.data)')
2186 if parent_typ.has_flag(.option) {
2187 g.write('.data)')
2188 }
2189 } else if typ.has_flag(.option_mut_param_t) {
2190 g.write('(*(${styp}*)${name}->data)')
2191 } else {
2192 g.write('(*(${styp}*)${name}.data)')
2193 }
2194 }
2195}
2196