v4 / vlib / v3 / types / checker.v
9632 lines · 9282 sloc · 270.64 KB · bd87753646a4c2ae1384399584858dc14cb90b28
Raw
1module types
2
3import v3.flat
4
5const export_c_reserved_words = {
6 'auto': true
7 'break': true
8 'case': true
9 'char': true
10 'const': true
11 'continue': true
12 'default': true
13 'do': true
14 'double': true
15 'else': true
16 'enum': true
17 'extern': true
18 'float': true
19 'for': true
20 'goto': true
21 'if': true
22 'inline': true
23 'int': true
24 'long': true
25 'register': true
26 'restrict': true
27 'return': true
28 'short': true
29 'signed': true
30 'sizeof': true
31 'static': true
32 'struct': true
33 'switch': true
34 'typedef': true
35 'union': true
36 'unsigned': true
37 'void': true
38 'volatile': true
39 'while': true
40}
41
42const export_v3_reserved_c_symbols = {
43 'i8': true
44 'i16': true
45 'i32': true
46 'i64': true
47 'u8': true
48 'byte': true
49 'u16': true
50 'u32': true
51 'u64': true
52 'bool': true
53 'voidptr': true
54 'int_literal': true
55 'float_literal': true
56 'chan': true
57 'string': true
58 'array': true
59 'Array': true
60 'map': true
61 'mapnode': true
62 'DenseArray': true
63 'SortedMap': true
64 'Optional': true
65 'IError': true
66 'true': true
67 'false': true
68 'elem_size': true
69 'c_name': true
70}
71
72const export_c_libc_collision_symbols = {
73 'rint': true
74 'y0': true
75 'y1': true
76 'yn': true
77 'j0': true
78 'j1': true
79 'jn': true
80 'drem': true
81 'scalb': true
82}
83
84// tarr1 supports tarr1 handling for types.
85fn tarr1(a Type) []Type {
86 mut r := []Type{}
87 r << a
88 return r
89}
90
91// tarr2 supports tarr2 handling for types.
92fn tarr2(a Type, b Type) []Type {
93 mut r := []Type{}
94 r << a
95 r << b
96 return r
97}
98
99// tarr3 supports tarr3 handling for types.
100fn tarr3(a Type, b Type, c Type) []Type {
101 mut r := []Type{}
102 r << a
103 r << b
104 r << c
105 return r
106}
107
108// unknown_type supports unknown type handling for types.
109fn unknown_type(reason string) Type {
110 return Type(Unknown{
111 reason: reason
112 })
113}
114
115// TypeError represents type error data used by types.
116pub struct TypeError {
117pub:
118 msg string
119 kind TypeErrorKind
120 node flat.NodeId
121}
122
123// TypeErrorKind lists type error kind values used by types.
124pub enum TypeErrorKind {
125 unknown_ident
126 unknown_type
127 unknown_fn
128 unknown_field
129 cannot_index
130 if_branch_mismatch
131 assignment_mismatch
132 return_mismatch
133 call_arg_mismatch
134 condition_mismatch
135 unhandled_node
136 unsupported_generic
137}
138
139// CallInfo stores call info metadata used by types.
140pub struct CallInfo {
141pub:
142 name string
143 params []Type
144 return_type Type
145 has_receiver bool
146 is_variadic bool
147 is_c_variadic bool
148 params_known bool
149 has_implicit_veb_ctx bool
150}
151
152// LocalBinding represents local binding data used by types.
153struct LocalBinding {
154 name string
155 typ Type
156}
157
158// TypeCache represents type cache data used by types.
159struct TypeCache {
160mut:
161 parse_enabled bool
162 parse_entries map[string]Type
163 c_entries map[string]string
164}
165
166// TypeChecker represents type checker data used by types.
167@[heap]
168pub struct TypeChecker {
169pub mut:
170 a &flat.FlatAst = unsafe { nil }
171 fn_ret_types map[string]Type
172 fn_param_types map[string][]Type
173 fn_ret_type_texts map[string]string // generic struct method key -> original return type text (e.g. `Box[T].clone` -> `Box[T]`)
174 fn_param_type_texts map[string][]string // generic struct method key -> original param type texts (receiver first)
175 fn_type_files map[string]string
176 fn_type_modules map[string]string
177 fn_generic_params map[string][]string
178 fn_variadic map[string]bool
179 c_variadic_fns map[string]bool
180 fn_implicit_veb_ctx map[string]bool
181 structs map[string][]StructField
182 struct_generic_params map[string][]string // generic struct base name -> type-param names (e.g. Vec4 -> [T])
183 struct_field_c_abi_fns map[string]string
184 // concrete `Box[int].method` -> substituted CallInfo for a method *value* on a
185 // generic receiver. The open `Box[T].method` registration is gone by cgen time, so
186 // the checker stashes the resolved signature here for gen_method_value_closure.
187 generic_method_value_info map[string]CallInfo
188 params_structs map[string]bool
189 unions map[string]bool
190 type_aliases map[string]string
191 type_alias_c_abi_fns map[string]string
192 sum_types map[string][]string
193 enum_names map[string]bool
194 enum_fields map[string][]string
195 flag_enums map[string]bool
196 interface_names map[string]bool
197 interface_fields map[string][]StructField
198 interface_embeds map[string][]string
199 interface_abstract_methods map[string][]string // iface -> abstract (declared) method names
200
201 c_globals map[string]Type
202 const_types map[string]Type
203 const_exprs map[string]flat.NodeId
204 const_modules map[string]string
205 const_suffixes map[string]string // dot-suffix -> full const key (O(1) lookup; '' if ambiguous)
206 imports map[string]string // alias -> short module name
207 file_imports map[string]string
208 file_selective_imports map[string][]string
209 file_modules map[string]string
210 file_scope &Scope = unsafe { nil }
211 cur_scope &Scope = unsafe { nil }
212 scope_pool []&Scope
213 scope_pool_index int
214 has_builtins bool
215 cur_module string
216 cur_file string
217 errors []TypeError
218 resolved_call_names []string // node_id -> resolved function name
219 resolved_call_set []bool
220 resolved_fn_value_names []string // node_id -> resolved function value name
221 resolved_fn_value_set []bool
222 // Methods used as *values* (`recv.method` passed as a callback), recorded per enclosing
223 // function during semantic checking — which has full scope/type info, runs before
224 // markused, and (unlike a call) routes a value-context selector through check_selector.
225 // markused seeds these (keeping the wrapper-only method out of the dead-code pruner)
226 // only when their enclosing function is reachable.
227 method_values_by_fn map[int][]string // enclosing fn node id -> method-value `Type.method` keys
228 // Local variables bound to a method value (`cb := c.report`) in the current function.
229 // Such an alias shares the same per-site static receiver slot as the bare selector, so it
230 // escapes (and corrupts other live callbacks) just like `return c.report`; the escape
231 // checks below treat a reference to one of these locals as a method value. Reset per fn.
232 method_value_locals map[string]bool
233 // Scope depth at which each method-value local was marked, so a reassignment to a
234 // non-method value only clears the marker when it dominates later uses (same-or-shallower
235 // scope); a reassignment in a deeper conditional/loop scope keeps the maybe-method marker.
236 method_value_local_depth map[string]int
237 cur_fn_node_id int = -1
238 expr_type_values []Type // node_id -> complex/contextual resolved type
239 expr_type_set []bool
240 checking_nodes []bool
241 diagnose_unknown_calls bool
242 reject_unlowered_map_mutation bool
243 reject_unsupported_generics bool
244 diagnostic_files map[string]bool
245 cur_fn_ret_type Type = Type(void_)
246 smartcasts map[string]Type
247 selfhost bool
248mut:
249 type_cache &TypeCache = unsafe { nil }
250}
251
252// new creates a TypeChecker value for types.
253pub fn TypeChecker.new(a &flat.FlatAst) TypeChecker {
254 fs := new_scope(unsafe { nil })
255 return TypeChecker{
256 a: a
257 fn_ret_types: map[string]Type{}
258 fn_param_types: map[string][]Type{}
259 fn_ret_type_texts: map[string]string{}
260 fn_param_type_texts: map[string][]string{}
261 fn_type_files: map[string]string{}
262 fn_type_modules: map[string]string{}
263 fn_generic_params: map[string][]string{}
264 fn_variadic: map[string]bool{}
265 c_variadic_fns: map[string]bool{}
266 fn_implicit_veb_ctx: map[string]bool{}
267 structs: map[string][]StructField{}
268 struct_generic_params: map[string][]string{}
269 struct_field_c_abi_fns: map[string]string{}
270 generic_method_value_info: map[string]CallInfo{}
271 params_structs: map[string]bool{}
272 unions: map[string]bool{}
273 type_aliases: map[string]string{}
274 type_alias_c_abi_fns: map[string]string{}
275 sum_types: map[string][]string{}
276 enum_names: map[string]bool{}
277 enum_fields: map[string][]string{}
278 flag_enums: map[string]bool{}
279 interface_names: map[string]bool{}
280 interface_fields: map[string][]StructField{}
281 interface_embeds: map[string][]string{}
282 interface_abstract_methods: map[string][]string{}
283 c_globals: map[string]Type{}
284 const_types: map[string]Type{}
285 const_exprs: map[string]flat.NodeId{}
286 const_modules: map[string]string{}
287 const_suffixes: map[string]string{}
288 imports: map[string]string{}
289 file_imports: map[string]string{}
290 file_selective_imports: map[string][]string{}
291 file_modules: map[string]string{}
292 file_scope: fs
293 cur_scope: fs
294 resolved_call_names: []string{len: a.nodes.len}
295 resolved_call_set: []bool{len: a.nodes.len}
296 resolved_fn_value_names: []string{len: a.nodes.len}
297 resolved_fn_value_set: []bool{len: a.nodes.len}
298 method_values_by_fn: map[int][]string{}
299 method_value_locals: map[string]bool{}
300 method_value_local_depth: map[string]int{}
301 expr_type_values: []Type{len: a.nodes.len, init: Type(void_)}
302 expr_type_set: []bool{len: a.nodes.len}
303 checking_nodes: []bool{len: a.nodes.len}
304 diagnostic_files: map[string]bool{}
305 smartcasts: map[string]Type{}
306 type_cache: &TypeCache{
307 parse_entries: map[string]Type{}
308 c_entries: map[string]string{}
309 }
310 }
311}
312
313// fork_for_parallel_transform returns a TypeChecker that shares all of `tc`'s
314// read-only data (semantic maps and node-indexed cache arrays, which the transform
315// pass only reads) but owns a fresh, private `type_cache` and a private AST view.
316// During transform the only hidden mutation a TypeChecker performs through its `&`
317// receiver is memoization into `type_cache` (parse_type / c_type); giving each
318// worker its own cache makes concurrent use race-free without cloning the large
319// semantic maps. `ast` must be the worker's own (cloned) FlatAst so that any
320// expr_type lookup on a freshly-created node id indexes a valid array.
321pub fn (tc &TypeChecker) fork_for_parallel_transform(ast &flat.FlatAst) &TypeChecker {
322 mut forked := *tc
323 forked.a = ast
324 forked.type_cache = &TypeCache{
325 parse_enabled: if tc.type_cache != unsafe { nil } {
326 tc.type_cache.parse_enabled
327 } else {
328 false
329 }
330 parse_entries: map[string]Type{}
331 c_entries: map[string]string{}
332 }
333 return &forked
334}
335
336// reset_node_caches updates reset node caches state for types.
337fn (mut tc TypeChecker) reset_node_caches(n int) {
338 tc.resolved_call_names = []string{len: n}
339 tc.resolved_call_set = []bool{len: n}
340 tc.resolved_fn_value_names = []string{len: n}
341 tc.resolved_fn_value_set = []bool{len: n}
342 tc.expr_type_values = []Type{len: n, init: Type(void_)}
343 tc.expr_type_set = []bool{len: n}
344 tc.checking_nodes = []bool{len: n}
345}
346
347fn (mut tc TypeChecker) extend_node_caches(n int) {
348 if n <= tc.resolved_call_names.len && n <= tc.resolved_fn_value_names.len
349 && n <= tc.expr_type_values.len && n <= tc.checking_nodes.len {
350 return
351 }
352 extend_string_cache(mut tc.resolved_call_names, n)
353 extend_bool_cache(mut tc.resolved_call_set, n)
354 extend_string_cache(mut tc.resolved_fn_value_names, n)
355 extend_bool_cache(mut tc.resolved_fn_value_set, n)
356 extend_type_cache(mut tc.expr_type_values, n)
357 extend_bool_cache(mut tc.expr_type_set, n)
358 extend_bool_cache(mut tc.checking_nodes, n)
359}
360
361fn extend_string_cache(mut values []string, n int) {
362 if n > values.len {
363 values << []string{len: n - values.len}
364 }
365}
366
367fn extend_bool_cache(mut values []bool, n int) {
368 if n > values.len {
369 values << []bool{len: n - values.len}
370 }
371}
372
373fn extend_type_cache(mut values []Type, n int) {
374 if n > values.len {
375 values << []Type{len: n - values.len, init: Type(void_)}
376 }
377}
378
379// push_scope updates push scope state for TypeChecker.
380pub fn (mut tc TypeChecker) push_scope() {
381 tc.cur_scope = tc.reuse_scope(tc.cur_scope)
382}
383
384// pop_scope updates pop scope state for TypeChecker.
385pub fn (mut tc TypeChecker) pop_scope() {
386 if tc.cur_scope == unsafe { nil } {
387 return
388 }
389 parent := tc.cur_scope.parent
390 if parent == unsafe { nil } {
391 return
392 }
393 if tc.scope_pool_index > 0 && tc.cur_scope == tc.scope_pool[tc.scope_pool_index - 1] {
394 tc.scope_pool_index--
395 }
396 tc.cur_scope = parent
397}
398
399// reuse_scope supports reuse scope handling for TypeChecker.
400fn (mut tc TypeChecker) reuse_scope(parent &Scope) &Scope {
401 if tc.scope_pool_index < tc.scope_pool.len {
402 mut scope := tc.scope_pool[tc.scope_pool_index]
403 scope.reset(parent)
404 tc.scope_pool_index++
405 return scope
406 }
407 scope := new_scope(parent)
408 tc.scope_pool << scope
409 tc.scope_pool_index++
410 return scope
411}
412
413// record_error supports record error handling for TypeChecker.
414fn (mut tc TypeChecker) record_error(kind TypeErrorKind, msg string, node flat.NodeId) {
415 if !tc.should_diagnose(node) {
416 return
417 }
418 tc.errors << TypeError{
419 msg: msg
420 kind: kind
421 node: node
422 }
423}
424
425fn (mut tc TypeChecker) record_error_unfiltered(kind TypeErrorKind, msg string, node flat.NodeId) {
426 tc.errors << TypeError{
427 msg: msg
428 kind: kind
429 node: node
430 }
431}
432
433fn (mut tc TypeChecker) record_unsupported_generic(msg string, node flat.NodeId) {
434 if !tc.should_diagnose_unsupported_generic(node) {
435 return
436 }
437 tc.errors << TypeError{
438 msg: msg
439 kind: .unsupported_generic
440 node: node
441 }
442}
443
444// collect supports collect handling for TypeChecker.
445pub fn (mut tc TypeChecker) collect(a &flat.FlatAst) {
446 tc.a = a
447 tc.file_scope = new_scope(unsafe { nil })
448 tc.cur_scope = tc.file_scope
449 tc.scope_pool_index = 0
450 tc.reset_node_caches(a.nodes.len)
451 tc.type_cache = &TypeCache{
452 parse_entries: map[string]Type{}
453 c_entries: map[string]string{}
454 }
455 for node in a.nodes {
456 if node.kind == .struct_decl && node.value == 'string' {
457 tc.has_builtins = true
458 break
459 }
460 }
461 // Pass 1: collect type-level names (aliases, enums, sum types)
462 for node in a.nodes {
463 match node.kind {
464 .file {
465 tc.enter_file(node.value)
466 }
467 .module_decl {
468 tc.enter_module(node.value)
469 }
470 .import_decl {
471 tc.imports[node.typ] = node.value
472 tc.file_imports[file_import_key(tc.cur_file, node.typ)] = node.value
473 tc.register_selective_imports(node)
474 }
475 .enum_decl {
476 qn := tc.qualify_name(node.value)
477 tc.enum_names[qn] = true
478 mut fields := []string{}
479 for i in 0 .. node.children_count {
480 f := a.child_node(&node, i)
481 if f.kind == .enum_field {
482 fields << f.value
483 }
484 }
485 tc.enum_fields[qn] = fields
486 if node.typ == 'flag' {
487 tc.flag_enums[qn] = true
488 }
489 }
490 .struct_decl {
491 qname := tc.qualify_name(node.value)
492 if qname !in tc.structs {
493 tc.structs[qname] = []StructField{}
494 }
495 if node.generic_params.len > 0 {
496 tc.struct_generic_params[qname] = node.generic_params.clone()
497 if qname != node.value {
498 tc.struct_generic_params[node.value] = node.generic_params.clone()
499 }
500 }
501 if node.typ.contains('union') {
502 tc.unions[qname] = true
503 }
504 if node.typ.contains('params') {
505 tc.params_structs[qname] = true
506 }
507 }
508 .type_decl {
509 if node.children_count > 0 {
510 mut variants := []string{}
511 for i in 0 .. node.children_count {
512 v := a.child_node(&node, i)
513 variants << tc.qualify_name(v.value)
514 }
515 tc.sum_types[tc.qualify_name(node.value)] = variants
516 } else if node.typ.len > 0 {
517 qname := tc.qualify_name(node.value)
518 tc.type_aliases[qname] = tc.qualify_type_text(node.typ)
519 if c_abi_fn := tc.c_abi_fn_ptr_type_from_text(node.typ) {
520 tc.type_alias_c_abi_fns[qname] = c_abi_fn
521 }
522 if tc.cur_module in ['', 'main', 'builtin'] && node.value !in tc.type_aliases {
523 tc.type_aliases[node.value] = tc.qualify_type_text(node.typ)
524 if c_abi_fn := tc.c_abi_fn_ptr_type_from_text(node.typ) {
525 tc.type_alias_c_abi_fns[node.value] = c_abi_fn
526 }
527 }
528 }
529 }
530 .interface_decl {
531 tc.interface_names[tc.qualify_name(node.value)] = true
532 }
533 else {}
534 }
535 }
536 // Pass 2: collect struct fields, function signatures (type aliases now available)
537 tc.type_cache.parse_enabled = true
538 tc.cur_module = ''
539 for node in a.nodes {
540 match node.kind {
541 .file {
542 tc.enter_file(node.value)
543 }
544 .module_decl {
545 tc.enter_module(node.value)
546 }
547 .fn_decl {
548 qname := tc.qualify_fn_name(node.value)
549 ret_type := tc.parse_type(node.typ)
550 mut ptypes := []Type{}
551 mut param_texts := []string{}
552 mut is_variadic := false
553 for i in 0 .. node.children_count {
554 child := a.child_node(&node, i)
555 if child.kind == .param {
556 if child.typ.starts_with('...') {
557 is_variadic = true
558 }
559 ptypes << tc.parse_type(child.typ)
560 param_texts << child.typ
561 }
562 }
563 needs_ctx := tc.fn_needs_implicit_veb_ctx(node)
564 ptypes = tc.fn_param_types_with_implicit_veb_ctx(node, ptypes)
565 tc.register_fn_signature(qname, ret_type, ptypes, is_variadic, needs_ctx)
566 if tc.cur_module in ['', 'main', 'builtin'] && qname != node.value
567 && node.value !in tc.fn_param_types {
568 tc.register_fn_signature(node.value, ret_type, ptypes, is_variadic, needs_ctx)
569 }
570 // A generic struct method (`Box[T].clone`) keeps its original signature
571 // TEXT: the parsed types collapse a non-concrete `Box[T]` to the bare base,
572 // so a concrete call must re-substitute the type arguments from the text to
573 // recover applications like the receiver type in the return position
574 // (`Box[T]` -> `Box[int]`). Only such methods carry `[` in their key.
575 if node.generic_params.len > 0 || node.value.contains('[') {
576 for name in [qname, node.value] {
577 tc.fn_ret_type_texts[name] = node.typ
578 tc.fn_param_type_texts[name] = param_texts.clone()
579 tc.fn_type_files[name] = tc.cur_file
580 tc.fn_type_modules[name] = tc.cur_module
581 if node.generic_params.len > 0 {
582 tc.fn_generic_params[name] = node.generic_params.clone()
583 }
584 }
585 }
586 }
587 .struct_decl {
588 mut fields := []StructField{}
589 mut field_c_abi_fns := map[string]string{}
590 for i in 0 .. node.children_count {
591 f := a.child_node(&node, i)
592 if f.kind != .field_decl {
593 continue
594 }
595 field_typ := if f.typ.len > 0 { f.typ } else { f.value }
596 mut typ := tc.parse_type(field_typ)
597 if f.value == field_typ {
598 typ = tc.resolve_known_field_type(field_typ, typ)
599 }
600 if c_abi_fn := tc.c_abi_fn_ptr_type_for_type_text(field_typ) {
601 field_c_abi_fns[f.value] = c_abi_fn
602 }
603 fields << StructField{
604 name: f.value
605 typ: typ
606 }
607 }
608 qname := tc.qualify_name(node.value)
609 tc.structs[qname] = fields
610 for field_name, c_abi_fn in field_c_abi_fns {
611 tc.struct_field_c_abi_fns[struct_field_c_abi_key(qname, field_name)] = c_abi_fn
612 }
613 if node.typ.contains('union') {
614 tc.unions[qname] = true
615 }
616 if node.typ.contains('params') {
617 tc.params_structs[qname] = true
618 }
619 }
620 .c_fn_decl {
621 ret_type := tc.parse_type(node.typ)
622 mut ptypes := []Type{}
623 mut is_variadic := false
624 for i in 0 .. node.children_count {
625 child := a.child_node(&node, i)
626 if child.kind == .param {
627 if child.typ.starts_with('...') {
628 is_variadic = true
629 }
630 ptypes << tc.parse_type(child.typ)
631 }
632 }
633 tc.register_fn_signature(node.value, ret_type, ptypes, is_variadic, false)
634 if is_variadic {
635 tc.register_c_variadic_fn(node.value)
636 }
637 if !node.value.starts_with('C.') {
638 tc.register_fn_signature('C.${node.value}', ret_type, ptypes, is_variadic,
639 false)
640 if is_variadic {
641 tc.register_c_variadic_fn('C.${node.value}')
642 }
643 }
644 }
645 .interface_decl {
646 iface_name := tc.qualify_name(node.value)
647 for i in 0 .. node.children_count {
648 f := a.child_node(&node, i)
649 if f.kind != .interface_field {
650 continue
651 }
652 if f.op == .dot {
653 mname := '${iface_name}.${f.value}'
654 mut absm := tc.interface_abstract_methods[iface_name] or { []string{} }
655 absm << f.value
656 tc.interface_abstract_methods[iface_name] = absm
657 tc.fn_ret_types[mname] = tc.parse_type(f.typ)
658 mut ptypes := []Type{}
659 mut is_variadic := false
660 ptypes << Type(Pointer{
661 base_type: Type(Interface{
662 name: iface_name
663 })
664 })
665 for j in 0 .. f.children_count {
666 child := a.child_node(f, j)
667 if child.kind == .param {
668 if child.typ.starts_with('...') {
669 is_variadic = true
670 }
671 ptypes << tc.parse_type(child.typ)
672 }
673 }
674 tc.fn_param_types[mname] = ptypes
675 tc.fn_variadic[mname] = is_variadic
676 } else if f.typ.len > 0 {
677 mut fields := tc.interface_fields[iface_name] or { []StructField{} }
678 fields << StructField{
679 name: f.value
680 typ: tc.parse_type(f.typ)
681 }
682 tc.interface_fields[iface_name] = fields
683 } else if f.value.len > 0 {
684 mut embeds := tc.interface_embeds[iface_name] or { []string{} }
685 embeds << tc.qualify_name(f.value)
686 tc.interface_embeds[iface_name] = embeds
687 }
688 }
689 }
690 .global_decl {
691 for i in 0 .. node.children_count {
692 f := a.child_node(&node, i)
693 if f.value.len > 0 && f.value.starts_with('C.') {
694 tc.c_globals[f.value] = tc.parse_type(f.typ)
695 } else if f.value.len > 0 {
696 mut ft := tc.parse_type(f.typ)
697 if ft is Void && f.children_count > 0 {
698 ft = tc.resolve_type(a.child(f, 0))
699 }
700 qname := tc.qualify_name(f.value)
701 tc.file_scope.insert(qname, ft)
702 }
703 }
704 }
705 .const_decl {
706 for i in 0 .. node.children_count {
707 f := a.child_node(&node, i)
708 if f.kind == .const_field && f.children_count > 0 {
709 qname := tc.qualify_name(f.value)
710 tc.const_types[qname] = unknown_type('pending const `${qname}`')
711 tc.const_exprs[qname] = a.child(f, 0)
712 tc.const_modules[qname] = tc.cur_module
713 } else if f.kind == .const_field && f.typ.len > 0 {
714 qname := tc.qualify_name(f.value)
715 tc.const_types[qname] = tc.parse_type(f.typ)
716 }
717 }
718 }
719 else {}
720 }
721 }
722 tc.resolve_const_types()
723 tc.build_const_suffixes()
724}
725
726// build_const_suffixes maps every dot-delimited suffix of each const key to that
727// key, so qualified const lookups resolve in O(1) instead of scanning all consts
728// (with per-iteration string building) on every selector/ident in module code.
729fn (mut tc TypeChecker) build_const_suffixes() {
730 for key, _ in tc.const_types {
731 mut i := 0
732 for i < key.len {
733 if key[i] == `.` {
734 suffix := key[i + 1..]
735 if existing := tc.const_suffixes[suffix] {
736 if existing != key {
737 tc.const_suffixes[suffix] = ''
738 }
739 } else {
740 tc.const_suffixes[suffix] = key
741 }
742 }
743 i++
744 }
745 }
746}
747
748// const_key_for_suffix returns the const key matching `.${name}` as a suffix,
749// equivalent to scanning const_types for `key.ends_with('.' + name)` but O(1).
750fn (tc &TypeChecker) const_key_for_suffix(name string) ?string {
751 if key := tc.const_suffixes[name] {
752 if key.len > 0 {
753 return key
754 }
755 }
756 return none
757}
758
759// resolve_const_types resolves resolve const types information for types.
760fn (mut tc TypeChecker) resolve_const_types() {
761 if tc.const_exprs.len == 0 {
762 return
763 }
764 saved_module := tc.cur_module
765 for _ in 0 .. tc.const_exprs.len {
766 mut changed := false
767 for name, expr_id in tc.const_exprs {
768 tc.cur_module = tc.const_modules[name] or { '' }
769 mut new_type := tc.resolve_type(expr_id)
770 new_type = tc.const_type_from_initializer(name, new_type)
771 if new_type is Unknown {
772 continue
773 }
774 expr := tc.a.nodes[int(expr_id)]
775 if new_type is ArrayFixed && expr.kind == .call {
776 new_type = Type(Array{
777 elem_type: new_type.elem_type
778 })
779 }
780 old_type := tc.const_types[name] or { Type(void_) }
781 if old_type.name() != new_type.name() {
782 tc.const_types[name] = new_type
783 changed = true
784 }
785 }
786 if !changed {
787 break
788 }
789 }
790 tc.cur_module = saved_module
791}
792
793// const_type_from_initializer converts const type from initializer data for types.
794fn (tc &TypeChecker) const_type_from_initializer(name string, typ Type) Type {
795 if typ !is Unknown {
796 return typ
797 }
798 expr_id := tc.const_exprs[name] or { return typ }
799 if int(expr_id) < 0 || int(expr_id) >= tc.a.nodes.len {
800 return typ
801 }
802 expr := tc.a.nodes[int(expr_id)]
803 if expr.kind != .call || expr.children_count == 0 {
804 return typ
805 }
806 fn_node := tc.a.child_node(&expr, 0)
807 if fn_node.kind != .ident || fn_node.value.len == 0 {
808 return typ
809 }
810 mod_name := tc.const_modules[name] or { '' }
811 mut candidates := []string{}
812 if mod_name.len > 0 && mod_name != 'main' && mod_name != 'builtin' {
813 candidates << '${mod_name}.${fn_node.value}'
814 }
815 candidates << fn_node.value
816 candidates << c_name(fn_node.value)
817 for candidate in candidates {
818 if ret := tc.fn_ret_types[candidate] {
819 return ret
820 }
821 }
822 if fn_node.value == 'new_keywords_matcher_trie' {
823 type_name := if mod_name.len > 0 && mod_name != 'main' && mod_name != 'builtin' {
824 '${mod_name}.KeywordsMatcherTrie'
825 } else {
826 'KeywordsMatcherTrie'
827 }
828 return Type(Struct{
829 name: type_name
830 })
831 }
832 return typ
833}
834
835// qualify_fn_name supports qualify fn name handling for TypeChecker.
836pub fn (tc &TypeChecker) qualify_fn_name(name string) string {
837 if tc.cur_module.len == 0 || tc.cur_module == 'main' || tc.cur_module == 'builtin' {
838 return name
839 }
840 return '${tc.cur_module}.${name}'
841}
842
843// qualify_name supports qualify name handling for TypeChecker.
844pub fn (tc &TypeChecker) qualify_name(name string) string {
845 if tc.cur_module.len == 0 || tc.cur_module == 'main' || tc.cur_module == 'builtin' {
846 return name
847 }
848 if name.starts_with('[]') {
849 return '[]' + tc.qualify_name(name[2..])
850 }
851 if name.starts_with('[') {
852 idx := name.index_u8(`]`)
853 if idx > 0 {
854 return name[..idx + 1] + tc.qualify_name(name[idx + 1..])
855 }
856 }
857 if name.starts_with('map[') {
858 bracket_end := find_matching_bracket(name, 3)
859 key_str := name[4..bracket_end]
860 val_str := name[bracket_end + 1..]
861 return 'map[${tc.qualify_name(key_str)}]${tc.qualify_name(val_str)}'
862 }
863 if name.starts_with('&') {
864 return '&' + tc.qualify_name(name[1..])
865 }
866 if name.starts_with('?') {
867 return '?' + tc.qualify_name(name[1..])
868 }
869 if name.contains('.') {
870 return tc.resolve_imported_type_text(name)
871 }
872 if is_builtin_type_name(name) {
873 return name
874 }
875 return tc.cur_module + '.' + name
876}
877
878// qualify_type_text supports qualify type text handling for TypeChecker.
879fn (tc &TypeChecker) qualify_type_text(typ string) string {
880 clean := typ.trim_space()
881 if clean.len == 0 {
882 return typ
883 }
884 if clean.starts_with('&') {
885 return '&' + tc.qualify_type_text(clean[1..])
886 }
887 if clean.starts_with('mut ') {
888 inner := tc.qualify_type_text(clean[4..])
889 if inner.starts_with('&') {
890 return inner
891 }
892 return '&' + inner
893 }
894 if clean.starts_with('shared ') {
895 return 'shared ' + tc.qualify_type_text(clean[7..])
896 }
897 if clean.starts_with('atomic ') {
898 return 'atomic ' + tc.qualify_type_text(clean[7..])
899 }
900 if clean.starts_with('?') {
901 return '?' + tc.qualify_type_text(clean[1..])
902 }
903 if clean.starts_with('!') {
904 return '!' + tc.qualify_type_text(clean[1..])
905 }
906 if clean.starts_with('...') {
907 return '...' + tc.qualify_type_text(clean[3..])
908 }
909 if clean.starts_with('[]') {
910 return '[]' + tc.qualify_type_text(clean[2..])
911 }
912 if clean.starts_with('map[') {
913 bracket_end := find_matching_bracket(clean, 3)
914 if bracket_end < clean.len {
915 key := tc.qualify_type_text(clean[4..bracket_end])
916 val := tc.qualify_type_text(clean[bracket_end + 1..])
917 return 'map[${key}]${val}'
918 }
919 }
920 if clean.starts_with('[') {
921 bracket_end := find_matching_bracket(clean, 0)
922 if bracket_end < clean.len {
923 return clean[..bracket_end + 1] + tc.qualify_type_text(clean[bracket_end + 1..])
924 }
925 }
926 if clean.starts_with('(') && clean.ends_with(')') && clean.contains(',') {
927 mut parts := []string{}
928 for part in split_params(clean[1..clean.len - 1]) {
929 parts << tc.qualify_type_text(part)
930 }
931 return '(' + parts.join(', ') + ')'
932 }
933 if clean.starts_with('fn(') || clean.starts_with('fn (') {
934 return tc.qualify_fn_type_text(clean)
935 }
936 bracket := clean.index_u8(`[`)
937 if bracket > 0 {
938 bracket_end := find_matching_bracket(clean, bracket)
939 if bracket_end < clean.len {
940 mut parts := []string{}
941 for part in split_params(clean[bracket + 1..bracket_end]) {
942 parts << tc.qualify_type_text(part)
943 }
944 return tc.qualify_name(clean[..bracket]) + '[' + parts.join(', ') + ']' +
945 clean[bracket_end + 1..]
946 }
947 }
948 return tc.qualify_name(clean)
949}
950
951// qualify_fn_type_text supports qualify fn type text handling for TypeChecker.
952fn (tc &TypeChecker) qualify_fn_type_text(typ string) string {
953 params_start := typ.index_u8(`(`) + 1
954 mut depth := 1
955 mut params_end := params_start
956 for params_end < typ.len {
957 if typ[params_end] == `(` {
958 depth++
959 } else if typ[params_end] == `)` {
960 depth--
961 if depth == 0 {
962 break
963 }
964 }
965 params_end++
966 }
967 params_str := typ[params_start..params_end]
968 mut params := []string{}
969 if params_str.trim_space().len > 0 {
970 for part in split_params(params_str) {
971 params << tc.qualify_type_text(normalize_fn_type_param_text(part))
972 }
973 }
974 ret_str := typ[params_end + 1..].trim_space()
975 if ret_str.len > 0 {
976 return 'fn(${params.join(', ')}) ${tc.qualify_type_text(ret_str)}'
977 }
978 return 'fn(${params.join(', ')})'
979}
980
981// file_import_key supports file import key handling for types.
982fn file_import_key(file string, alias string) string {
983 return '${file}\n${alias}'
984}
985
986// enter_file supports enter file handling for TypeChecker.
987fn (mut tc TypeChecker) enter_file(file string) {
988 tc.cur_file = file
989 tc.cur_module = tc.file_modules[file] or { '' }
990}
991
992// enter_module supports enter module handling for TypeChecker.
993fn (mut tc TypeChecker) enter_module(name string) {
994 tc.cur_module = name
995 if tc.cur_file.len > 0 {
996 tc.file_modules[tc.cur_file] = name
997 }
998}
999
1000fn (mut tc TypeChecker) register_selective_imports(node flat.Node) {
1001 if node.children_count == 0 {
1002 return
1003 }
1004 for i in 0 .. node.children_count {
1005 child_id := tc.a.child(&node, i)
1006 child := tc.a.nodes[int(child_id)]
1007 if child.kind != .ident {
1008 continue
1009 }
1010 key := file_import_key(tc.cur_file, child.value)
1011 if key in tc.file_selective_imports {
1012 tc.file_selective_imports[key] = []string{}
1013 tc.record_error_unfiltered(.unknown_fn, 'ambiguous selective import `${child.value}`',
1014 child_id)
1015 continue
1016 }
1017 mut candidates := []string{}
1018 path_name := '${node.value}.${child.value}'
1019 if path_name !in candidates {
1020 candidates << path_name
1021 }
1022 alias_name := '${node.typ}.${child.value}'
1023 if alias_name != path_name && alias_name !in candidates {
1024 candidates << alias_name
1025 }
1026 tc.file_selective_imports[key] = candidates
1027 }
1028}
1029
1030// resolve_import_alias resolves resolve import alias information for types.
1031fn (tc &TypeChecker) resolve_import_alias(alias string) ?string {
1032 if mod := tc.file_imports[file_import_key(tc.cur_file, alias)] {
1033 return mod
1034 }
1035 return none
1036}
1037
1038fn (tc &TypeChecker) resolve_selective_import_symbol(name string) ?string {
1039 candidates := tc.file_selective_imports[file_import_key(tc.cur_file, name)] or { return none }
1040 for candidate in candidates {
1041 if tc.fn_signature_known(candidate) {
1042 return candidate
1043 }
1044 }
1045 return none
1046}
1047
1048fn (tc &TypeChecker) resolve_selective_import_type_symbol(name string) ?string {
1049 candidates := tc.file_selective_imports[file_import_key(tc.cur_file, name)] or { return none }
1050 for candidate in candidates {
1051 if tc.type_symbol_known(candidate) {
1052 return candidate
1053 }
1054 }
1055 return none
1056}
1057
1058fn (tc &TypeChecker) type_symbol_known(name string) bool {
1059 return name in tc.type_aliases || name in tc.structs || name in tc.interface_names
1060 || name in tc.flag_enums || name in tc.enum_names || name in tc.sum_types
1061}
1062
1063fn (tc &TypeChecker) type_from_known_symbol(name string) ?Type {
1064 if name in tc.type_aliases {
1065 return Type(Alias{
1066 name: name
1067 base_type: tc.parse_type(tc.type_aliases[name])
1068 })
1069 }
1070 if name in tc.structs {
1071 return Type(Struct{
1072 name: name
1073 })
1074 }
1075 if name in tc.interface_names {
1076 return Type(Interface{
1077 name: name
1078 })
1079 }
1080 if name in tc.flag_enums {
1081 return Type(Enum{
1082 name: name
1083 is_flag: true
1084 })
1085 }
1086 if name in tc.enum_names {
1087 return Type(Enum{
1088 name: name
1089 })
1090 }
1091 if name in tc.sum_types {
1092 return Type(SumType{
1093 name: name
1094 })
1095 }
1096 return none
1097}
1098
1099fn (tc &TypeChecker) selective_import_symbol_is_ambiguous(name string) bool {
1100 candidates := tc.file_selective_imports[file_import_key(tc.cur_file, name)] or { return false }
1101 return candidates.len == 0
1102}
1103
1104fn (tc &TypeChecker) resolve_imported_type_text(typ string) string {
1105 if !typ.contains('.') || typ.starts_with('C.') {
1106 return typ
1107 }
1108 dot := typ.index_u8(`.`)
1109 if dot <= 0 {
1110 return typ
1111 }
1112 alias := typ[..dot]
1113 if resolved := tc.resolve_import_alias(alias) {
1114 if resolved != alias {
1115 return resolved + typ[dot..]
1116 }
1117 }
1118 return typ
1119}
1120
1121// has_active_import reports whether has active import applies in types.
1122fn (tc &TypeChecker) has_active_import(alias string) bool {
1123 return file_import_key(tc.cur_file, alias) in tc.file_imports
1124}
1125
1126// register_fn_signature updates register fn signature state for types.
1127fn (mut tc TypeChecker) register_fn_signature(name string, ret_type Type, params []Type, is_variadic bool, implicit_veb_ctx bool) {
1128 tc.register_fn_name_alias(name, ret_type, params, is_variadic, implicit_veb_ctx)
1129 lowered_name := c_name(name)
1130 if lowered_name != name {
1131 tc.register_fn_name_alias(lowered_name, ret_type, params, is_variadic, implicit_veb_ctx)
1132 }
1133 if name.ends_with('.str') {
1134 receiver := name.all_before_last('.')
1135 legacy_name := '${receiver}_str'
1136 if !legacy_name.contains('.') {
1137 tc.register_fn_name_alias(legacy_name, ret_type, params, is_variadic, implicit_veb_ctx)
1138 }
1139 }
1140}
1141
1142// register_fn_name_alias updates register fn name alias state for types.
1143fn (mut tc TypeChecker) register_fn_name_alias(name string, ret_type Type, params []Type, is_variadic bool, implicit_veb_ctx bool) {
1144 tc.fn_ret_types[name] = ret_type
1145 tc.fn_param_types[name] = params.clone()
1146 tc.fn_variadic[name] = is_variadic
1147 tc.fn_implicit_veb_ctx[name] = implicit_veb_ctx
1148}
1149
1150fn (mut tc TypeChecker) register_c_variadic_fn(name string) {
1151 if name.len == 0 {
1152 return
1153 }
1154 tc.c_variadic_fns[name] = true
1155 lowered_name := c_name(name)
1156 if lowered_name != name {
1157 tc.c_variadic_fns[lowered_name] = true
1158 }
1159 if !name.starts_with('C.') {
1160 tc.c_variadic_fns['C.${name}'] = true
1161 }
1162}
1163
1164// annotate_types performs a scope-aware walk over every function body, tracking
1165// local variable types as they are declared, and records complex/contextual
1166// expression types. This mirrors what the v2 transformer relies on: the type
1167// checker runs BEFORE the transformer and publishes per-expression types, so the
1168// transformer can own type-dependent lowering (string ops, `in` membership, ...)
1169// instead of the backend.
1170//
1171// It uses a single flat scope per function (an over-approximation: a local stays
1172// visible after its block ends), which is harmless for type lookup since variable
1173// names are effectively unique within a function.
1174pub fn (mut tc TypeChecker) annotate_types() {
1175 tc.annotate_types_with_used(map[string]bool{})
1176}
1177
1178// annotate_types_with_used annotates only functions that can be emitted when
1179// `used_fns` is non-empty. This mirrors transform/cgen pruning and avoids
1180// resolving types in dead, untransformed function bodies after markused.
1181pub fn (mut tc TypeChecker) annotate_types_with_used(used_fns map[string]bool) {
1182 tc.extend_node_caches(tc.a.nodes.len)
1183 tc.cur_module = ''
1184 for node in tc.a.nodes {
1185 if node.kind == .file {
1186 tc.enter_file(node.value)
1187 } else if node.kind == .module_decl {
1188 tc.enter_module(node.value)
1189 } else if node.kind == .fn_decl {
1190 if !tc.should_annotate_fn(node, used_fns) {
1191 continue
1192 }
1193 tc.cur_scope = tc.file_scope
1194 tc.push_scope()
1195 for pi in 0 .. node.children_count {
1196 p := tc.a.child_node(&node, pi)
1197 if p.kind == .param && p.value.len > 0 {
1198 tc.cur_scope.insert(p.value, tc.parse_type(p.typ))
1199 }
1200 }
1201 tc.insert_implicit_veb_ctx(node)
1202 for i in 0 .. node.children_count {
1203 child := tc.a.child_node(&node, i)
1204 if child.kind != .param {
1205 tc.annotate_node(tc.a.child(&node, i))
1206 }
1207 }
1208 tc.pop_scope()
1209 }
1210 }
1211}
1212
1213fn (tc &TypeChecker) should_annotate_fn(node flat.Node, used_fns map[string]bool) bool {
1214 if used_fns.len == 0 {
1215 return true
1216 }
1217 qname := checker_qualified_fn_name(tc.cur_module, node.value)
1218 if qname in tc.a.export_fn_names || tc.fn_needs_implicit_veb_ctx(node) {
1219 return true
1220 }
1221 if node.value in used_fns {
1222 return true
1223 }
1224 if qname in used_fns {
1225 return true
1226 }
1227 cname := c_name(qname)
1228 if cname != qname && cname in used_fns {
1229 return true
1230 }
1231 return false
1232}
1233
1234fn checker_qualified_fn_name(mod string, name string) string {
1235 if mod.len == 0 || mod == 'main' || mod == 'builtin' {
1236 return name
1237 }
1238 return '${mod}.${name}'
1239}
1240
1241// annotate_node supports annotate node handling for TypeChecker.
1242fn (mut tc TypeChecker) annotate_node(id flat.NodeId) {
1243 if int(id) < 0 {
1244 return
1245 }
1246 node := tc.a.nodes[int(id)]
1247 match node.kind {
1248 .decl_assign {
1249 // children are interleaved pairs [lhs0, rhs0, lhs1, rhs1, ...].
1250 // Multi-return (`a, b := f()`) yields an odd count; we only insert
1251 // locals for clean pairs and skip MultiReturn rhs values.
1252 mut i := 0
1253 for i + 1 < node.children_count {
1254 lhs_id := tc.a.child(&node, i)
1255 rhs_id := tc.a.child(&node, i + 1)
1256 tc.annotate_node(rhs_id)
1257 lhs := tc.a.nodes[int(lhs_id)]
1258 if lhs.kind == .ident && lhs.value.len > 0 {
1259 mut typ := Type(void_)
1260 if node.children_count == 2 && node.typ.len > 0 {
1261 typ = tc.parse_type(node.typ)
1262 tc.annotate_expected_expr(rhs_id, typ)
1263 } else {
1264 typ = tc.resolve_type(rhs_id)
1265 }
1266 if typ !is MultiReturn && typ !is Void {
1267 tc.cur_scope.insert(lhs.value, typ)
1268 tc.remember_expr_type(lhs_id, typ)
1269 }
1270 }
1271 i += 2
1272 }
1273 return
1274 }
1275 .for_in_stmt {
1276 tc.annotate_for_in(id, node)
1277 return
1278 }
1279 .assign, .selector_assign, .index_assign {
1280 tc.annotate_assign_expected_exprs(node)
1281 }
1282 .struct_init {
1283 tc.annotate_struct_init_expected_exprs(node)
1284 }
1285 .call {
1286 tc.annotate_call_expected_exprs(id, node)
1287 }
1288 else {}
1289 }
1290
1291 tc.remember_expr_type(id, tc.resolve_type(id))
1292 for i in 0 .. node.children_count {
1293 tc.annotate_node(tc.a.child(&node, i))
1294 }
1295}
1296
1297fn (mut tc TypeChecker) annotate_expected_expr(id flat.NodeId, expected Type) {
1298 if _ := fn_type_from_type(expected) {
1299 _ = tc.resolve_expr(id, expected)
1300 }
1301}
1302
1303fn (mut tc TypeChecker) annotate_assign_expected_exprs(node flat.Node) {
1304 if node.children_count < 2 {
1305 return
1306 }
1307 mut i := 0
1308 for i + 1 < node.children_count {
1309 lhs_id := tc.a.child(&node, i)
1310 rhs_id := tc.a.child(&node, i + 1)
1311 lhs_type := tc.resolve_lvalue_type(lhs_id)
1312 tc.annotate_expected_expr(rhs_id, lhs_type)
1313 i += 2
1314 }
1315}
1316
1317fn (mut tc TypeChecker) annotate_struct_init_expected_exprs(node flat.Node) {
1318 init_type := tc.parse_type(node.value)
1319 init_struct := struct_type_from_type(init_type) or { return }
1320 init_name := init_struct.name
1321 fields := tc.structs[init_name] or { []StructField{} }
1322 for i in 0 .. node.children_count {
1323 field := tc.a.child_node(&node, i)
1324 if field.kind != .field_init || field.children_count == 0 {
1325 continue
1326 }
1327 value_id := tc.a.child(field, 0)
1328 mut expected := Type(void_)
1329 if field.value.len > 0 {
1330 expected = tc.struct_field_type(init_name, field.value) or { Type(void_) }
1331 } else if i < fields.len {
1332 expected = fields[i].typ
1333 }
1334 tc.annotate_expected_expr(value_id, expected)
1335 }
1336}
1337
1338fn (mut tc TypeChecker) annotate_call_expected_exprs(id flat.NodeId, node flat.Node) {
1339 info := tc.resolve_call_info(id, node) or { return }
1340 if info.name.len > 0 && !is_array_dsl_call_name(info.name) {
1341 tc.remember_resolved_call(id, info.name)
1342 }
1343 if !info.params_known || info.params.len == 0 {
1344 return
1345 }
1346 mut field_init_args := 0
1347 for i in 1 .. node.children_count {
1348 if tc.a.child_node(&node, i).kind == .field_init {
1349 field_init_args++
1350 }
1351 }
1352 collapsed := if field_init_args > 0 { 1 } else { 0 }
1353 recv_extra := if info.has_receiver { 1 } else { 0 }
1354 actual_count := node.children_count - 1 - field_init_args + collapsed + recv_extra
1355 ctx_count := if info.has_implicit_veb_ctx { 1 } else { 0 }
1356 ctx_omitted := ctx_count > 0 && actual_count < info.params.len
1357 for i in 1 .. node.children_count {
1358 raw_arg := tc.a.child_node(&node, i)
1359 arg_id := tc.call_arg_value(tc.a.child(&node, i))
1360 if raw_arg.kind == .field_init {
1361 tc.annotate_params_field_expected_expr(arg_id, raw_arg.value, info)
1362 continue
1363 }
1364 arg_shift := if ctx_omitted { ctx_count } else { 0 }
1365 param_idx := (if info.has_receiver { i } else { i - 1 }) + arg_shift
1366 if info.is_c_variadic && param_idx >= c_variadic_fixed_param_count(info) {
1367 continue
1368 }
1369 if param_idx >= info.params.len {
1370 continue
1371 }
1372 expected := tc.call_arg_expected_type(info, param_idx)
1373 tc.annotate_expected_expr(arg_id, expected)
1374 }
1375}
1376
1377fn (tc &TypeChecker) call_arg_expected_type(info CallInfo, param_idx int) Type {
1378 expected := info.params[param_idx]
1379 if info.is_variadic && param_idx == info.params.len - 1 && expected is Array {
1380 return array_elem_type(expected)
1381 }
1382 return expected
1383}
1384
1385fn (mut tc TypeChecker) annotate_params_field_expected_expr(arg_id flat.NodeId, field_name string, info CallInfo) {
1386 if field_name.len == 0 {
1387 return
1388 }
1389 for param in info.params {
1390 clean := unwrap_pointer(param)
1391 if clean is Struct {
1392 if expected := tc.struct_field_type(clean.name, field_name) {
1393 tc.annotate_expected_expr(arg_id, expected)
1394 return
1395 }
1396 }
1397 }
1398}
1399
1400// annotate_for_in supports annotate for in handling for TypeChecker.
1401fn (mut tc TypeChecker) annotate_for_in(_id flat.NodeId, node flat.Node) {
1402 header := node.value.int()
1403 if header < 3 || node.children_count < 3 {
1404 return
1405 }
1406 key_id := tc.a.child(&node, 0)
1407 val_id := tc.a.child(&node, 1)
1408 container_id := tc.a.child(&node, 2)
1409 tc.annotate_node(container_id)
1410 has_val := int(val_id) >= 0
1411 if header == 4 {
1412 tc.insert_loop_var(key_id, Type(int_))
1413 tc.annotate_node(tc.a.child(&node, 3))
1414 } else {
1415 clean := unwrap_pointer(tc.resolve_type(container_id))
1416 if clean is Array {
1417 if has_val {
1418 tc.insert_loop_var(key_id, Type(int_))
1419 tc.insert_loop_var(val_id, clean.elem_type)
1420 } else {
1421 tc.insert_loop_var(key_id, clean.elem_type)
1422 }
1423 } else if clean is ArrayFixed {
1424 if has_val {
1425 tc.insert_loop_var(key_id, Type(int_))
1426 tc.insert_loop_var(val_id, clean.elem_type)
1427 } else {
1428 tc.insert_loop_var(key_id, clean.elem_type)
1429 }
1430 } else if clean is Map {
1431 if has_val {
1432 tc.insert_loop_var(key_id, clean.key_type)
1433 tc.insert_loop_var(val_id, clean.value_type)
1434 } else {
1435 tc.insert_loop_var(key_id, clean.value_type)
1436 }
1437 } else if clean is String {
1438 if has_val {
1439 tc.insert_loop_var(key_id, Type(int_))
1440 tc.insert_loop_var(val_id, Type(u8_))
1441 } else {
1442 tc.insert_loop_var(key_id, Type(u8_))
1443 }
1444 } else {
1445 container := tc.a.nodes[int(container_id)]
1446 if container.kind == .range {
1447 tc.insert_loop_var(key_id, Type(int_))
1448 }
1449 }
1450 }
1451 for i in header .. node.children_count {
1452 tc.annotate_node(tc.a.child(&node, i))
1453 }
1454}
1455
1456// insert_loop_var updates insert loop var state for types.
1457fn (mut tc TypeChecker) insert_loop_var(id flat.NodeId, typ Type) {
1458 if int(id) < 0 {
1459 return
1460 }
1461 v := tc.a.nodes[int(id)]
1462 if v.kind == .ident && v.value.len > 0 {
1463 tc.cur_scope.insert(v.value, typ)
1464 tc.remember_expr_type(id, typ)
1465 }
1466}
1467
1468// expr_type returns the resolved type recorded for a node during annotate_types.
1469pub fn (tc &TypeChecker) expr_type(id flat.NodeId) ?Type {
1470 if int(id) >= 0 {
1471 node := tc.a.nodes[int(id)]
1472 if node.kind == .call && node.typ.len > 0 {
1473 return tc.parse_type(node.typ)
1474 }
1475 }
1476 if t := tc.resolved_call_type(id) {
1477 return t
1478 }
1479 if t := tc.cached_expr_type(id) {
1480 return t
1481 }
1482 return none
1483}
1484
1485// resolved_call_type supports resolved call type handling for TypeChecker.
1486fn (tc &TypeChecker) resolved_call_type(id flat.NodeId) ?Type {
1487 if int(id) < 0 {
1488 return none
1489 }
1490 node := tc.a.nodes[int(id)]
1491 if node.kind != .call {
1492 return none
1493 }
1494 if t := tc.cached_expr_type(id) {
1495 return t
1496 }
1497 if name := tc.cached_resolved_call(id) {
1498 if t := tc.fn_ret_types[name] {
1499 return t
1500 }
1501 }
1502 return none
1503}
1504
1505// cached_expr_type supports cached expr type handling for TypeChecker.
1506fn (tc &TypeChecker) cached_expr_type(id flat.NodeId) ?Type {
1507 idx := int(id)
1508 if idx >= 0 && idx < tc.expr_type_set.len && tc.expr_type_set[idx] {
1509 return tc.expr_type_values[idx]
1510 }
1511 return none
1512}
1513
1514// cached_resolved_call supports cached resolved call handling for TypeChecker.
1515fn (tc &TypeChecker) cached_resolved_call(id flat.NodeId) ?string {
1516 idx := int(id)
1517 if idx >= 0 && idx < tc.resolved_call_set.len && tc.resolved_call_set[idx] {
1518 return tc.resolved_call_names[idx]
1519 }
1520 return none
1521}
1522
1523// resolved_call_name returns the checker-resolved function name for a call node.
1524pub fn (tc &TypeChecker) resolved_call_name(id flat.NodeId) ?string {
1525 return tc.cached_resolved_call(id)
1526}
1527
1528// resolved_fn_value_name returns the checker-resolved function name for a function value node.
1529pub fn (tc &TypeChecker) resolved_fn_value_name(id flat.NodeId) ?string {
1530 idx := int(id)
1531 if idx >= 0 && idx < tc.resolved_fn_value_set.len && tc.resolved_fn_value_set[idx] {
1532 return tc.resolved_fn_value_names[idx]
1533 }
1534 return none
1535}
1536
1537// resolve_fn_value_name_for_expected resolves and records a function value in an expected FnType context.
1538fn (mut tc TypeChecker) resolve_fn_value_name_for_expected(id flat.NodeId, expected Type) ?string {
1539 if name := tc.resolved_fn_value_name(id) {
1540 return name
1541 }
1542 if int(id) < 0 || int(id) >= tc.a.nodes.len {
1543 return none
1544 }
1545 node := tc.a.nodes[int(id)]
1546 if tc.fn_value_shadowed_by_value(node) {
1547 return none
1548 }
1549 key := tc.fn_value_match_key(node, expected) or { return none }
1550 tc.remember_resolved_fn_value_chain(id, key)
1551 return key
1552}
1553
1554// remember_resolved_call supports remember resolved call handling for TypeChecker.
1555fn (mut tc TypeChecker) remember_resolved_call(id flat.NodeId, name string) {
1556 idx := int(id)
1557 if idx < 0 {
1558 return
1559 }
1560 if idx >= tc.resolved_call_names.len {
1561 tc.extend_node_caches(tc.a.nodes.len)
1562 }
1563 if idx < tc.resolved_call_names.len {
1564 tc.resolved_call_names[idx] = name
1565 tc.resolved_call_set[idx] = true
1566 }
1567}
1568
1569// remember_resolved_fn_value records the exact function declaration used by a function value.
1570fn (mut tc TypeChecker) remember_resolved_fn_value(id flat.NodeId, name string) {
1571 idx := int(id)
1572 if idx < 0 {
1573 return
1574 }
1575 if idx >= tc.resolved_fn_value_names.len {
1576 tc.extend_node_caches(tc.a.nodes.len)
1577 }
1578 if idx < tc.resolved_fn_value_names.len {
1579 tc.resolved_fn_value_names[idx] = name
1580 tc.resolved_fn_value_set[idx] = true
1581 }
1582}
1583
1584fn (mut tc TypeChecker) remember_resolved_fn_value_chain(id flat.NodeId, name string) {
1585 tc.remember_resolved_fn_value(id, name)
1586 if int(id) < 0 || int(id) >= tc.a.nodes.len {
1587 return
1588 }
1589 node := tc.a.nodes[int(id)]
1590 if node.kind in [.cast_expr, .paren, .expr_stmt] && node.children_count > 0 {
1591 tc.remember_resolved_fn_value_chain(tc.a.child(&node, 0), name)
1592 }
1593}
1594
1595// register_synth_type records the type of a generated or transformed node.
1596pub fn (mut tc TypeChecker) register_synth_type(id flat.NodeId, typ Type) {
1597 tc.remember_expr_type(id, typ)
1598}
1599
1600// remember_expr_type supports remember expr type handling for TypeChecker.
1601fn (mut tc TypeChecker) remember_expr_type(id flat.NodeId, typ Type) {
1602 if int(id) < 0 {
1603 return
1604 }
1605 kind := if int(id) < tc.a.nodes.len { tc.a.nodes[int(id)].kind } else { flat.NodeKind.empty }
1606 if should_cache_expr_type(kind, typ) {
1607 idx := int(id)
1608 if idx >= tc.expr_type_values.len {
1609 tc.extend_node_caches(tc.a.nodes.len)
1610 }
1611 if idx < tc.expr_type_values.len {
1612 tc.expr_type_values[idx] = typ
1613 tc.expr_type_set[idx] = true
1614 }
1615 }
1616}
1617
1618// should_cache_expr_type reports whether should cache expr type applies in types.
1619fn should_cache_expr_type(kind flat.NodeKind, typ Type) bool {
1620 if typ is Void || typ is Unknown {
1621 return false
1622 }
1623 if typ is Array || typ is ArrayFixed || typ is Map || typ is Pointer || typ is FnType
1624 || typ is OptionType || typ is ResultType || typ is Struct || typ is Interface
1625 || typ is Enum || typ is SumType || typ is Alias || typ is MultiReturn {
1626 return true
1627 }
1628 kind_id := int(kind)
1629 return kind_id != 1 && kind_id != 2 && kind_id != 3 && kind_id != 4 && kind_id != 5
1630 && kind_id != 28
1631}
1632
1633// check_semantics validates check semantics state for types.
1634pub fn (mut tc TypeChecker) check_semantics() {
1635 tc.check_export_attrs()
1636 tc.cur_module = ''
1637 tc.cur_file = ''
1638 for i, node in tc.a.nodes {
1639 match node.kind {
1640 .file {
1641 tc.enter_file(node.value)
1642 }
1643 .module_decl {
1644 tc.enter_module(node.value)
1645 }
1646 .struct_decl {
1647 tc.check_decl_type_strings(flat.NodeId(i), node)
1648 tc.check_struct_field_defaults(node)
1649 }
1650 .type_decl, .interface_decl {
1651 tc.check_decl_type_strings(flat.NodeId(i), node)
1652 }
1653 .enum_decl {
1654 tc.check_enum_field_values(node)
1655 }
1656 .const_decl {
1657 tc.check_const_field_values(node)
1658 }
1659 .fn_decl {
1660 tc.check_decl_type_strings(flat.NodeId(i), node)
1661 tc.cur_fn_ret_type = tc.parse_type(node.typ)
1662 tc.cur_fn_node_id = i
1663 tc.method_value_locals = map[string]bool{}
1664 tc.method_value_local_depth = map[string]int{}
1665 tc.push_scope()
1666 for pi in 0 .. node.children_count {
1667 p := tc.a.child_node(&node, pi)
1668 if p.kind == .param && p.value.len > 0 {
1669 tc.cur_scope.insert(p.value, tc.parse_type(p.typ))
1670 }
1671 }
1672 tc.insert_implicit_veb_ctx(node)
1673 tc.check_fn_body(node)
1674 tc.cur_fn_node_id = -1
1675 is_disabled_stub := node.value in tc.a.disabled_fns
1676 if !type_allows_implicit_return(tc.cur_fn_ret_type)
1677 && !tc.fn_body_definitely_returns(node) && !is_disabled_stub
1678 && tc.should_diagnose(flat.NodeId(i)) {
1679 tc.record_error(.return_mismatch,
1680 'missing return at end of function `${node.value}`; expected `${tc.cur_fn_ret_type.name()}`',
1681 flat.NodeId(i))
1682 }
1683 tc.pop_scope()
1684 tc.cur_fn_ret_type = Type(void_)
1685 }
1686 .c_fn_decl {
1687 if tc.reject_unsupported_generics {
1688 tc.check_decl_type_strings(flat.NodeId(i), node)
1689 }
1690 }
1691 else {}
1692 }
1693
1694 _ = i
1695 }
1696}
1697
1698fn (mut tc TypeChecker) check_export_attrs() {
1699 mut natural_symbols := map[string]string{}
1700 synthetic_main_reserved := tc.has_synthetic_c_entry_main()
1701 mut cur_module := ''
1702 for node in tc.a.nodes {
1703 match node.kind {
1704 .file {
1705 tc.enter_file(node.value)
1706 cur_module = tc.cur_module
1707 }
1708 .module_decl {
1709 cur_module = node.value
1710 tc.enter_module(node.value)
1711 }
1712 .fn_decl {
1713 qname := export_qualified_fn_name(cur_module, node.value)
1714 natural_symbol := export_natural_c_symbol(cur_module, node.value)
1715 natural_symbols[natural_symbol] = qname
1716 }
1717 else {}
1718 }
1719 }
1720 mut export_symbols := map[string]string{}
1721 cur_module = ''
1722 for i, node in tc.a.nodes {
1723 match node.kind {
1724 .file {
1725 tc.enter_file(node.value)
1726 cur_module = tc.cur_module
1727 }
1728 .module_decl {
1729 cur_module = node.value
1730 tc.enter_module(node.value)
1731 }
1732 .fn_decl {
1733 qname := export_qualified_fn_name(cur_module, node.value)
1734 export_name := tc.a.export_fn_names[qname] or { continue }
1735 if export_name.len == 0 {
1736 tc.record_error_unfiltered(.unsupported_generic,
1737 'empty export name for `${qname}`', flat.NodeId(i))
1738 continue
1739 }
1740 if !is_valid_export_c_name(export_name) {
1741 tc.record_error_unfiltered(.unsupported_generic,
1742 'invalid export name `${export_name}` for `${qname}`', flat.NodeId(i))
1743 }
1744 if synthetic_main_reserved && export_name == 'main' {
1745 tc.record_error_unfiltered(.unsupported_generic,
1746 'export name `main` for `${qname}` collides with synthetic entry point `main`',
1747 flat.NodeId(i))
1748 }
1749 if node.generic_params.len > 0 {
1750 tc.record_error_unfiltered(.unsupported_generic,
1751 'generic function `${qname}` cannot be exported', flat.NodeId(i))
1752 }
1753 for pi in 0 .. node.children_count {
1754 p := tc.a.child_node(&node, pi)
1755 if p.kind == .param && (p.value.len == 0 || p.typ.len == 0) {
1756 tc.record_error_unfiltered(.unsupported_generic,
1757 'exported function `${qname}` must name all parameters', flat.NodeId(i))
1758 }
1759 }
1760 if existing := export_symbols[export_name] {
1761 if existing != qname {
1762 tc.record_error_unfiltered(.unsupported_generic,
1763 'duplicate export name `${export_name}` for `${qname}` and `${existing}`',
1764 flat.NodeId(i))
1765 }
1766 } else {
1767 export_symbols[export_name] = qname
1768 }
1769 if existing := natural_symbols[export_name] {
1770 tc.record_error_unfiltered(.unsupported_generic,
1771 'export name `${export_name}` for `${qname}` collides with `${existing}`',
1772 flat.NodeId(i))
1773 }
1774 }
1775 else {}
1776 }
1777 }
1778}
1779
1780fn (tc &TypeChecker) has_synthetic_c_entry_main() bool {
1781 if tc.has_c_test_harness_main() {
1782 return true
1783 }
1784 if tc.has_main_module_fn_main() {
1785 return false
1786 }
1787 return tc.has_c_top_level_main()
1788}
1789
1790fn (tc &TypeChecker) has_main_module_fn_main() bool {
1791 mut cur_module := ''
1792 for node in tc.a.nodes {
1793 match node.kind {
1794 .file {
1795 cur_module = ''
1796 }
1797 .module_decl {
1798 cur_module = node.value
1799 }
1800 .fn_decl {
1801 if node.value == 'main' && (cur_module.len == 0 || cur_module == 'main') {
1802 return true
1803 }
1804 }
1805 else {}
1806 }
1807 }
1808 return false
1809}
1810
1811fn (tc &TypeChecker) has_c_test_harness_main() bool {
1812 for file_idx, file_node in tc.a.nodes {
1813 if file_idx < tc.a.user_code_start || file_node.kind != .file || file_node.value.len == 0 {
1814 continue
1815 }
1816 if !tc.is_selected_input_file(file_node.value) {
1817 continue
1818 }
1819 module_name := tc.top_level_file_module_name(file_node)
1820 if is_c_backend_test_file(file_node.value)
1821 && (module_name.len == 0 || module_name == 'main') {
1822 return true
1823 }
1824 }
1825 return false
1826}
1827
1828fn (tc &TypeChecker) has_c_top_level_main() bool {
1829 for file_idx, file_node in tc.a.nodes {
1830 if !tc.should_emit_c_top_level_file(file_idx, file_node) {
1831 continue
1832 }
1833 for i in 0 .. file_node.children_count {
1834 child_id := tc.a.child(&file_node, i)
1835 if int(child_id) < tc.a.user_code_start {
1836 continue
1837 }
1838 if tc.is_c_top_level_stmt(child_id) {
1839 return true
1840 }
1841 }
1842 }
1843 return false
1844}
1845
1846fn (tc &TypeChecker) should_emit_c_top_level_file(file_idx int, file_node flat.Node) bool {
1847 if file_idx < tc.a.user_code_start || file_node.kind != .file || file_node.children_count == 0 {
1848 return false
1849 }
1850 module_name := tc.top_level_file_module_name(file_node)
1851 return module_name.len == 0 || module_name == 'main'
1852}
1853
1854fn (tc &TypeChecker) top_level_file_module_name(file_node flat.Node) string {
1855 if module_name := tc.file_modules[file_node.value] {
1856 return module_name
1857 }
1858 for i in 0 .. file_node.children_count {
1859 child := tc.a.child_node(&file_node, i)
1860 if child.kind == .module_decl {
1861 return child.value
1862 }
1863 }
1864 return ''
1865}
1866
1867fn (tc &TypeChecker) is_c_top_level_stmt(id flat.NodeId) bool {
1868 if int(id) < 0 {
1869 return false
1870 }
1871 node := tc.a.nodes[int(id)]
1872 return match node.kind {
1873 .expr_stmt, .assign, .decl_assign, .selector_assign, .index_assign, .for_stmt,
1874 .for_in_stmt, .if_expr, .match_stmt, .assert_stmt, .defer_stmt {
1875 true
1876 }
1877 .block, .comptime_if {
1878 for i in 0 .. node.children_count {
1879 if tc.is_c_top_level_stmt(tc.a.child(&node, i)) {
1880 return true
1881 }
1882 }
1883 false
1884 }
1885 else {
1886 false
1887 }
1888 }
1889}
1890
1891fn (tc &TypeChecker) is_selected_input_file(file string) bool {
1892 return tc.diagnostic_files.len == 0 || tc.diagnostic_files[file]
1893}
1894
1895fn is_c_backend_test_file(path string) bool {
1896 file := path.all_after_last('/').all_after_last('\\')
1897 if file.ends_with('_test.v') || file.ends_with('_test.c.v') {
1898 return true
1899 }
1900 if !file.ends_with('.v') {
1901 return false
1902 }
1903 base := file[..file.len - 2]
1904 if !base.contains('.') {
1905 return false
1906 }
1907 return base.all_after_last('.') == 'c' && base.all_before_last('.').ends_with('_test')
1908}
1909
1910fn export_qualified_fn_name(module_name string, name string) string {
1911 if module_name.len == 0 || module_name == 'main' || module_name == 'builtin' {
1912 return name
1913 }
1914 return '${module_name}.${name}'
1915}
1916
1917fn export_natural_c_symbol(module_name string, name string) string {
1918 if module_name == 'builtin' && name == 'free' {
1919 return 'v_free'
1920 }
1921 if module_name.len > 0 && module_name != 'main' && module_name != 'builtin' {
1922 return c_name('${module_name}.${name}')
1923 }
1924 if name == 'free' {
1925 return 'v_free'
1926 }
1927 if name == 'exit' {
1928 return 'v_exit'
1929 }
1930 if name in export_c_libc_collision_symbols {
1931 return 'v_${name}'
1932 }
1933 return c_name(name)
1934}
1935
1936fn is_valid_export_c_name(name string) bool {
1937 if name.len == 0 {
1938 return false
1939 }
1940 if name in export_c_reserved_words {
1941 return false
1942 }
1943 if name in export_v3_reserved_c_symbols {
1944 return false
1945 }
1946 first := name[0]
1947 if !((first >= `a` && first <= `z`) || (first >= `A` && first <= `Z`) || first == `_`) {
1948 return false
1949 }
1950 for i in 1 .. name.len {
1951 c := name[i]
1952 if (c >= `a` && c <= `z`) || (c >= `A` && c <= `Z`) || (c >= `0` && c <= `9`) || c == `_` {
1953 continue
1954 }
1955 return false
1956 }
1957 return true
1958}
1959
1960fn (mut tc TypeChecker) insert_implicit_veb_ctx(node flat.Node) {
1961 if !tc.fn_needs_implicit_veb_ctx(node) {
1962 return
1963 }
1964 tc.cur_scope.insert('ctx', tc.implicit_veb_ctx_type())
1965}
1966
1967fn (tc &TypeChecker) fn_param_types_with_implicit_veb_ctx(node flat.Node, params []Type) []Type {
1968 if !tc.fn_needs_implicit_veb_ctx(node) {
1969 return params
1970 }
1971 insert_idx := tc.fn_implicit_veb_ctx_insert_index(node)
1972 mut result := []Type{cap: params.len + 1}
1973 for i, param in params {
1974 if i == insert_idx {
1975 result << tc.implicit_veb_ctx_type()
1976 }
1977 result << param
1978 }
1979 if insert_idx >= params.len {
1980 result << tc.implicit_veb_ctx_type()
1981 }
1982 return result
1983}
1984
1985fn (tc &TypeChecker) implicit_veb_ctx_type() Type {
1986 return tc.parse_type('mut Context')
1987}
1988
1989fn (tc &TypeChecker) fn_needs_implicit_veb_ctx(node flat.Node) bool {
1990 return tc.fn_returns_veb_result(node) && tc.fn_has_receiver_param(node)
1991 && !tc.fn_receiver_type_is_context(node) && !tc.fn_has_param(node, 'ctx')
1992 && tc.type_name_known_in_current_module('Context')
1993}
1994
1995fn (tc &TypeChecker) fn_implicit_veb_ctx_insert_index(node flat.Node) int {
1996 if tc.fn_has_receiver_param(node) {
1997 return 1
1998 }
1999 return 0
2000}
2001
2002fn (tc &TypeChecker) fn_has_receiver_param(node flat.Node) bool {
2003 if !node.value.contains('.') || node.children_count == 0 {
2004 return false
2005 }
2006 first := tc.a.child_node(&node, 0)
2007 if first.kind != .param || first.typ.len == 0 {
2008 return false
2009 }
2010 receiver := node.value.all_before_last('.').all_after_last('.')
2011 param_type := first.typ.trim_left('&').all_after_last('.')
2012 return receiver == param_type
2013}
2014
2015fn (tc &TypeChecker) fn_receiver_type_is_context(node flat.Node) bool {
2016 if !tc.fn_has_receiver_param(node) {
2017 return false
2018 }
2019 first := tc.a.child_node(&node, 0)
2020 return first.typ.trim_left('&').all_after_last('.') == 'Context'
2021}
2022
2023fn (tc &TypeChecker) fn_has_param(node flat.Node, name string) bool {
2024 for i in 0 .. node.children_count {
2025 p := tc.a.child_node(&node, i)
2026 if p.kind == .param && p.value == name {
2027 return true
2028 }
2029 }
2030 return false
2031}
2032
2033fn (tc &TypeChecker) fn_returns_veb_result(node flat.Node) bool {
2034 if node.typ == 'veb.Result' {
2035 return true
2036 }
2037 ret := tc.parse_type(node.typ)
2038 return ret.name() == 'veb.Result'
2039}
2040
2041// check_fn_body validates check fn body state for types.
2042fn (mut tc TypeChecker) check_fn_body(node flat.Node) {
2043 for i in 0 .. node.children_count {
2044 child_id := tc.a.child(&node, i)
2045 child := tc.a.child_node(&node, i)
2046 if child.kind == .param {
2047 continue
2048 }
2049 tc.check_node(child_id)
2050 }
2051}
2052
2053// check_decl_type_strings validates check decl type strings state for types.
2054fn (mut tc TypeChecker) check_decl_type_strings(node_id flat.NodeId, node flat.Node) {
2055 generic_params := tc.infer_decl_generic_params(node)
2056 if node.kind == .struct_decl {
2057 if node.typ.contains('generic') && tc.reject_unsupported_generics {
2058 tc.record_unsupported_generic('unsupported generic struct `${node.value}`', node_id)
2059 }
2060 } else {
2061 if node.generic_params.len > 0 && tc.reject_unsupported_generics {
2062 tc.record_unsupported_generic('unsupported generic declaration `${node.value}`',
2063 node_id)
2064 }
2065 tc.check_type_string_for_unsupported_generics(node.typ, node_id, generic_params)
2066 }
2067 for i in 0 .. node.children_count {
2068 child_id := tc.a.child(&node, i)
2069 if int(child_id) < 0 {
2070 continue
2071 }
2072 child := tc.a.nodes[int(child_id)]
2073 tc.check_type_string_for_unsupported_generics(child.typ, child_id, generic_params)
2074 if node.kind == .type_decl && child.value.len > 0 {
2075 tc.check_type_string_for_unsupported_generics(child.value, child_id, generic_params)
2076 }
2077 for j in 0 .. child.children_count {
2078 grandchild_id := tc.a.child(&child, j)
2079 if int(grandchild_id) < 0 {
2080 continue
2081 }
2082 grandchild := tc.a.nodes[int(grandchild_id)]
2083 tc.check_type_string_for_unsupported_generics(grandchild.typ, grandchild_id,
2084 generic_params)
2085 }
2086 }
2087}
2088
2089fn (tc &TypeChecker) infer_decl_generic_params(node flat.Node) map[string]bool {
2090 mut params := map[string]bool{}
2091 for name in node.generic_params {
2092 params[name] = true
2093 }
2094 tc.collect_generic_receiver_params(node, mut params)
2095 return params
2096}
2097
2098fn (tc &TypeChecker) collect_generic_receiver_params(node flat.Node, mut params map[string]bool) {
2099 if node.kind != .fn_decl && node.kind != .c_fn_decl {
2100 return
2101 }
2102 if !node.value.contains('.') {
2103 return
2104 }
2105 if node.children_count == 0 {
2106 return
2107 }
2108 receiver_id := tc.a.child(&node, 0)
2109 if int(receiver_id) < 0 {
2110 return
2111 }
2112 receiver := tc.a.nodes[int(receiver_id)]
2113 if receiver.kind != .param {
2114 return
2115 }
2116 receiver_type := receiver.typ.trim_left('&')
2117 if receiver_type != node.value.all_before_last('.') {
2118 return
2119 }
2120 mut counts := map[string]int{}
2121 if !tc.collect_generic_param_candidates(receiver.typ, mut counts) {
2122 return
2123 }
2124 for name, _ in counts {
2125 params[name] = true
2126 }
2127}
2128
2129fn (tc &TypeChecker) collect_generic_param_candidates(typ string, mut counts map[string]int) bool {
2130 clean := typ.trim_space()
2131 if clean.len == 0 {
2132 return false
2133 }
2134 if clean.starts_with('&') || clean.starts_with('?') || clean.starts_with('!') {
2135 return tc.collect_generic_param_candidates(clean[1..], mut counts)
2136 }
2137 if clean.starts_with('shared ') {
2138 return tc.collect_generic_param_candidates(clean[7..], mut counts)
2139 }
2140 if clean.starts_with('...') {
2141 return tc.collect_generic_param_candidates(clean[3..], mut counts)
2142 }
2143 if clean.starts_with('[]') {
2144 return tc.collect_generic_param_candidates(clean[2..], mut counts)
2145 }
2146 if clean.starts_with('map[') {
2147 mut found_context := false
2148 bracket_end := find_matching_bracket(clean, 3)
2149 if bracket_end < clean.len {
2150 if tc.collect_generic_param_candidates(clean[4..bracket_end], mut counts) {
2151 found_context = true
2152 }
2153 if tc.collect_generic_param_candidates(clean[bracket_end + 1..], mut counts) {
2154 found_context = true
2155 }
2156 }
2157 return found_context
2158 }
2159 if clean.starts_with('[') {
2160 idx := clean.index_u8(`]`)
2161 if idx > 0 {
2162 return tc.collect_generic_param_candidates(clean[idx + 1..], mut counts)
2163 }
2164 return false
2165 }
2166 if clean.starts_with('(') && clean.ends_with(')') {
2167 mut found_context := false
2168 for part in split_params(clean[1..clean.len - 1]) {
2169 if tc.collect_generic_param_candidates(part, mut counts) {
2170 found_context = true
2171 }
2172 }
2173 return found_context
2174 }
2175 if clean.starts_with('fn(') || clean.starts_with('fn (') {
2176 mut found_context := false
2177 params_start := clean.index_u8(`(`) + 1
2178 mut depth := 1
2179 mut params_end := params_start
2180 for params_end < clean.len {
2181 if clean[params_end] == `(` {
2182 depth++
2183 } else if clean[params_end] == `)` {
2184 depth--
2185 if depth == 0 {
2186 break
2187 }
2188 }
2189 params_end++
2190 }
2191 if params_end < clean.len {
2192 for part in split_params(clean[params_start..params_end]) {
2193 trimmed := part.trim_space()
2194 parts := trimmed.split(' ')
2195 param_type := if parts.len >= 2 { parts[parts.len - 1] } else { trimmed }
2196 if tc.collect_generic_param_candidates(param_type, mut counts) {
2197 found_context = true
2198 }
2199 }
2200 if tc.collect_generic_param_candidates(clean[params_end + 1..], mut counts) {
2201 found_context = true
2202 }
2203 }
2204 return found_context
2205 }
2206 if generic_type_application(clean) {
2207 bracket := clean.index_u8(`[`)
2208 bracket_end := find_matching_bracket(clean, bracket)
2209 if bracket_end < clean.len {
2210 for part in split_params(clean[bracket + 1..bracket_end]) {
2211 tc.collect_generic_param_candidates(part, mut counts)
2212 }
2213 }
2214 return true
2215 }
2216 if is_bare_generic_param(clean) && !tc.type_name_known(clean) {
2217 counts[clean] = (counts[clean] or { 0 }) + 1
2218 }
2219 return false
2220}
2221
2222// check_type_string_for_unsupported_generics
2223// validates helper state for types.
2224fn (mut tc TypeChecker) check_type_string_for_unsupported_generics(typ string, node_id flat.NodeId, generic_params map[string]bool) {
2225 clean := typ.trim_space()
2226 if clean.len == 0 {
2227 return
2228 }
2229 if clean in ['generic', 'params', 'union'] {
2230 return
2231 }
2232 if clean.starts_with('&') || clean.starts_with('?') || clean.starts_with('!') {
2233 tc.check_type_string_for_unsupported_generics(clean[1..], node_id, generic_params)
2234 return
2235 }
2236 if clean.starts_with('shared ') {
2237 tc.check_type_string_for_unsupported_generics(clean[7..], node_id, generic_params)
2238 return
2239 }
2240 if clean == 'thread' || clean == 'chan' {
2241 return
2242 }
2243 if clean.starts_with('thread ') {
2244 // `thread T` is a thread handle; only its element type T needs checking.
2245 tc.check_type_string_for_unsupported_generics(clean[7..], node_id, generic_params)
2246 return
2247 }
2248 if clean.starts_with('chan ') {
2249 tc.check_type_string_for_unsupported_generics(clean[5..], node_id, generic_params)
2250 return
2251 }
2252 if clean.starts_with('...') {
2253 tc.check_type_string_for_unsupported_generics(clean[3..], node_id, generic_params)
2254 return
2255 }
2256 if clean.starts_with('[]') {
2257 tc.check_type_string_for_unsupported_generics(clean[2..], node_id, generic_params)
2258 return
2259 }
2260 if clean.starts_with('map[') {
2261 bracket_end := find_matching_bracket(clean, 3)
2262 if bracket_end < clean.len {
2263 tc.check_type_string_for_unsupported_generics(clean[4..bracket_end], node_id,
2264 generic_params)
2265 tc.check_type_string_for_unsupported_generics(clean[bracket_end + 1..], node_id,
2266 generic_params)
2267 }
2268 return
2269 }
2270 if clean.starts_with('[') {
2271 idx := clean.index_u8(`]`)
2272 if idx > 0 {
2273 tc.check_type_string_for_unsupported_generics(clean[idx + 1..], node_id, generic_params)
2274 }
2275 return
2276 }
2277 if clean.starts_with('(') && clean.ends_with(')') {
2278 for part in split_params(clean[1..clean.len - 1]) {
2279 tc.check_type_string_for_unsupported_generics(part, node_id, generic_params)
2280 }
2281 return
2282 }
2283 if clean.starts_with('fn(') || clean.starts_with('fn (') {
2284 tc.check_fn_type_string_for_unsupported_generics(clean, node_id, generic_params)
2285 return
2286 }
2287 if generic_type_application(clean) {
2288 if tc.reject_unsupported_generics {
2289 tc.record_unsupported_generic('unsupported generic type application `${clean}`',
2290 node_id)
2291 return
2292 }
2293 bracket := clean.index_u8(`[`)
2294 bracket_end := find_matching_bracket(clean, bracket)
2295 base := clean[..bracket].trim_space()
2296 if should_check_named_type(base) && !tc.type_name_known(base) {
2297 tc.record_error(.unknown_type, 'unknown type `${base}`', node_id)
2298 }
2299 if bracket_end < clean.len {
2300 for part in split_params(clean[bracket + 1..bracket_end]) {
2301 tc.check_type_string_for_unsupported_generics(part, node_id, generic_params)
2302 }
2303 }
2304 return
2305 }
2306 if is_bare_generic_param(clean) && !tc.type_name_known(clean) {
2307 if tc.reject_unsupported_generics {
2308 tc.record_unsupported_generic('unsupported generic type parameter `${clean}`', node_id)
2309 return
2310 }
2311 if clean in generic_params {
2312 return
2313 }
2314 }
2315 if should_check_named_type(clean) && !tc.type_name_known(clean) {
2316 tc.record_error(.unknown_type, 'unknown type `${clean}`', node_id)
2317 }
2318}
2319
2320// check_fn_type_string_for_unsupported_generics
2321// validates helper state for types.
2322fn (mut tc TypeChecker) check_fn_type_string_for_unsupported_generics(typ string, node_id flat.NodeId, generic_params map[string]bool) {
2323 params_start := typ.index_u8(`(`) + 1
2324 mut depth := 1
2325 mut params_end := params_start
2326 for params_end < typ.len {
2327 if typ[params_end] == `(` {
2328 depth++
2329 } else if typ[params_end] == `)` {
2330 depth--
2331 if depth == 0 {
2332 break
2333 }
2334 }
2335 params_end++
2336 }
2337 if params_end >= typ.len {
2338 return
2339 }
2340 for part in split_params(typ[params_start..params_end]) {
2341 trimmed := part.trim_space()
2342 parts := trimmed.split(' ')
2343 param_type := if parts.len >= 2 { parts[parts.len - 1] } else { trimmed }
2344 tc.check_type_string_for_unsupported_generics(param_type, node_id, generic_params)
2345 }
2346 ret := typ[params_end + 1..].trim_space()
2347 tc.check_type_string_for_unsupported_generics(ret, node_id, generic_params)
2348}
2349
2350// generic_type_application supports generic type application handling for types.
2351fn generic_type_application(typ string) bool {
2352 _, _, ok := generic_type_application_parts(typ)
2353 return ok
2354}
2355
2356fn (tc &TypeChecker) generic_args_are_concrete(args []string) bool {
2357 for arg in args {
2358 if tc.type_text_has_generic_placeholder(arg) {
2359 return false
2360 }
2361 }
2362 return true
2363}
2364
2365fn (tc &TypeChecker) type_text_has_generic_placeholder(typ string) bool {
2366 clean := typ.trim_space()
2367 if is_bare_generic_param(clean) {
2368 return !tc.is_known_type_text(clean)
2369 }
2370 if clean.starts_with('&') {
2371 return tc.type_text_has_generic_placeholder(clean[1..])
2372 }
2373 if clean.starts_with('mut ') {
2374 return tc.type_text_has_generic_placeholder(clean[4..])
2375 }
2376 if clean.starts_with('?') || clean.starts_with('!') {
2377 return tc.type_text_has_generic_placeholder(clean[1..])
2378 }
2379 if clean.starts_with('...') {
2380 return tc.type_text_has_generic_placeholder(clean[3..])
2381 }
2382 if clean.starts_with('[]') {
2383 return tc.type_text_has_generic_placeholder(clean[2..])
2384 }
2385 if clean.starts_with('map[') {
2386 bracket_end := find_matching_bracket(clean, 3)
2387 if bracket_end < clean.len {
2388 return tc.type_text_has_generic_placeholder(clean[4..bracket_end])
2389 || tc.type_text_has_generic_placeholder(clean[bracket_end + 1..])
2390 }
2391 }
2392 if clean.starts_with('[') {
2393 bracket_end := find_matching_bracket(clean, 0)
2394 if bracket_end < clean.len {
2395 return tc.type_text_has_generic_placeholder(clean[bracket_end + 1..])
2396 }
2397 }
2398 _, args, ok := generic_type_application_parts(clean)
2399 if ok {
2400 for arg in args {
2401 if tc.type_text_has_generic_placeholder(arg) {
2402 return true
2403 }
2404 }
2405 }
2406 return false
2407}
2408
2409fn generic_type_application_parts(typ string) (string, []string, bool) {
2410 if typ.starts_with('[') || !typ.contains('[') {
2411 return '', []string{}, false
2412 }
2413 bracket := typ.index_u8(`[`)
2414 bracket_end := find_matching_bracket(typ, bracket)
2415 if bracket <= 0 || bracket_end <= bracket {
2416 return '', []string{}, false
2417 }
2418 inner := typ[bracket + 1..bracket_end].trim_space()
2419 if is_fixed_array_len_text(inner) {
2420 return '', []string{}, false
2421 }
2422 return typ[..bracket], split_params(inner), true
2423}
2424
2425// is_fixed_array_len_text reports whether a postfix `Base[inner]` bracket holds a fixed-array
2426// length rather than a generic type argument. `ArrayFixed.name()` renders the length as a decimal
2427// (`u8[16]`), a non-decimal literal (`u8[0x10]`), or the source length expression (`u8[segs + 1]`);
2428// a generic argument is always a type, never a number or arithmetic expression. Recognising all
2429// three keeps such a postfix name parsing as a fixed array (e.g. when `[]thread T.wait()` recovers
2430// the spawned return type) instead of a bogus generic application.
2431fn is_fixed_array_len_text(inner string) bool {
2432 s := inner.trim_space()
2433 if s.len == 0 {
2434 return false
2435 }
2436 // A fixed-array length is a single integer expression; a comma means the brackets hold a
2437 // generic argument LIST (`Pair[int, &Node]`), not a length. Without this an `&` (or `-`)
2438 // that merely leads a later pointer type argument would be read as a length operator.
2439 if s.contains(',') {
2440 return false
2441 }
2442 if v_int_literal_value(s) != none {
2443 return true
2444 }
2445 for i in 0 .. s.len {
2446 c := s[i]
2447 if c in [`+`, `*`, `/`, `%`, `|`, `^`, `<`, `>`] {
2448 return true
2449 }
2450 // A leading `-`/`&` is a negative literal / pointer-type argument; elsewhere they are the
2451 // subtraction / bitwise-and operators of a length expression.
2452 if (c == `-` || c == `&`) && i > 0 {
2453 return true
2454 }
2455 }
2456 return false
2457}
2458
2459// is_decimal_int_literal reports whether is decimal int literal applies in types.
2460fn is_decimal_int_literal(s string) bool {
2461 if s.len == 0 {
2462 return false
2463 }
2464 for i in 0 .. s.len {
2465 if s[i] < `0` || s[i] > `9` {
2466 return false
2467 }
2468 }
2469 return true
2470}
2471
2472// v_int_literal_value parses a complete V integer literal — decimal, hex (`0x`), octal
2473// (`0o`), or binary (`0b`), with optional `_` digit separators — to its value. Returns
2474// none when `s` is not a whole integer literal (a const name, an expression, etc.), so
2475// const-length folding accepts `0xF & 6` / `[0b1100 >> 1]int`, not just decimal text.
2476fn v_int_literal_value(s string) ?int {
2477 if s.len == 0 {
2478 return none
2479 }
2480 t := s.replace('_', '')
2481 if t.len == 0 {
2482 return none
2483 }
2484 mut base := 10
2485 mut digits := t
2486 if t.len >= 2 && t[0] == `0` {
2487 c := t[1]
2488 if c == `x` || c == `X` {
2489 base = 16
2490 digits = t[2..]
2491 } else if c == `o` || c == `O` {
2492 base = 8
2493 digits = t[2..]
2494 } else if c == `b` || c == `B` {
2495 base = 2
2496 digits = t[2..]
2497 }
2498 }
2499 if digits.len == 0 {
2500 return none
2501 }
2502 mut value := 0
2503 for ch in digits {
2504 mut d := 0
2505 if ch >= `0` && ch <= `9` {
2506 d = int(ch - `0`)
2507 } else if ch >= `a` && ch <= `f` {
2508 d = int(ch - `a`) + 10
2509 } else if ch >= `A` && ch <= `F` {
2510 d = int(ch - `A`) + 10
2511 } else {
2512 return none
2513 }
2514 if d >= base {
2515 return none
2516 }
2517 value = value * base + d
2518 }
2519 return value
2520}
2521
2522// is_bare_generic_param reports whether is bare generic param applies in types.
2523fn is_bare_generic_param(typ string) bool {
2524 return typ.len == 1 && typ[0] >= `A` && typ[0] <= `Z`
2525}
2526
2527fn generic_param_index(name string) int {
2528 return match name {
2529 'T', 'A', 'K', 'X' { 0 }
2530 'U', 'B', 'V', 'Y' { 1 }
2531 'C', 'W', 'Z' { 2 }
2532 else { 0 }
2533 }
2534}
2535
2536fn generic_placeholder_from_unknown(typ Unknown) ?string {
2537 start := typ.reason.index_u8(`\``)
2538 if start < 0 {
2539 return none
2540 }
2541 end := typ.reason[start + 1..].index_u8(`\``)
2542 if end < 0 {
2543 return none
2544 }
2545 name := typ.reason[start + 1..start + 1 + end]
2546 if !is_bare_generic_param(name) {
2547 return none
2548 }
2549 return name
2550}
2551
2552fn (tc &TypeChecker) resolve_known_field_type(type_name string, fallback Type) Type {
2553 qname := tc.qualify_name(type_name)
2554 if qname in tc.structs {
2555 return Type(Struct{
2556 name: qname
2557 })
2558 }
2559 if type_name in tc.structs {
2560 return Type(Struct{
2561 name: type_name
2562 })
2563 }
2564 if qname in tc.interface_names {
2565 return Type(Interface{
2566 name: qname
2567 })
2568 }
2569 if type_name in tc.interface_names {
2570 return Type(Interface{
2571 name: type_name
2572 })
2573 }
2574 if qname in tc.type_aliases {
2575 return Type(Alias{
2576 name: qname
2577 base_type: tc.parse_type(tc.type_aliases[qname])
2578 })
2579 }
2580 if type_name in tc.type_aliases {
2581 return Type(Alias{
2582 name: type_name
2583 base_type: tc.parse_type(tc.type_aliases[type_name])
2584 })
2585 }
2586 return fallback
2587}
2588
2589// type_name_known returns type name known data for TypeChecker.
2590fn (tc &TypeChecker) type_name_known(typ string) bool {
2591 if is_builtin_type_name(typ) || typ == 'unknown' || typ.starts_with('C.') {
2592 return true
2593 }
2594 qtyp := tc.qualify_name(typ)
2595 if !typ.contains('.') {
2596 if resolved := tc.resolve_selective_import_type_symbol(typ) {
2597 return tc.type_symbol_known(resolved)
2598 }
2599 }
2600 return typ in tc.type_aliases || qtyp in tc.type_aliases || typ in tc.structs
2601 || qtyp in tc.structs || typ in tc.interface_names || qtyp in tc.interface_names
2602 || typ in tc.enum_names || qtyp in tc.enum_names || typ in tc.sum_types
2603 || qtyp in tc.sum_types
2604}
2605
2606fn (tc &TypeChecker) type_name_known_in_current_module(typ string) bool {
2607 qtyp := tc.qualify_name(typ)
2608 return qtyp in tc.type_aliases || qtyp in tc.structs || qtyp in tc.interface_names
2609 || qtyp in tc.enum_names || qtyp in tc.sum_types
2610}
2611
2612// should_check_named_type reports whether should check named type applies in types.
2613fn should_check_named_type(typ string) bool {
2614 if typ.len == 0 {
2615 return false
2616 }
2617 for i in 0 .. typ.len {
2618 c := typ[i]
2619 if !((c >= `a` && c <= `z`) || (c >= `A` && c <= `Z`)
2620 || (c >= `0` && c <= `9`) || c == `_` || c == `.`) {
2621 return false
2622 }
2623 }
2624 return true
2625}
2626
2627// check_struct_field_defaults validates check struct field defaults state for types.
2628fn (mut tc TypeChecker) check_struct_field_defaults(node flat.Node) {
2629 for i in 0 .. node.children_count {
2630 field := tc.a.child_node(&node, i)
2631 if field.kind != .field_decl || field.children_count == 0 {
2632 continue
2633 }
2634 default_id := tc.a.child(field, 0)
2635 expected := tc.parse_type(field.typ)
2636 tc.check_node(default_id)
2637 actual := tc.resolve_expr(default_id, expected)
2638 if !tc.type_compatible(actual, expected) {
2639 tc.type_mismatch(.assignment_mismatch,
2640 'cannot initialize field `${field.value}` with `${actual.name()}`; expected `${expected.name()}`',
2641 default_id)
2642 }
2643 }
2644}
2645
2646// check_enum_field_values validates check enum field values state for types.
2647fn (mut tc TypeChecker) check_enum_field_values(node flat.Node) {
2648 for i in 0 .. node.children_count {
2649 field := tc.a.child_node(&node, i)
2650 if field.kind != .enum_field || field.children_count == 0 {
2651 continue
2652 }
2653 value_id := tc.a.child(field, 0)
2654 tc.check_node(value_id)
2655 value_type := tc.resolve_type(value_id)
2656 if value_type is Unknown {
2657 continue
2658 }
2659 if !value_type.is_integer() {
2660 tc.type_mismatch(.assignment_mismatch,
2661 'enum field `${field.value}` value must be integer, not `${value_type.name()}`',
2662 value_id)
2663 }
2664 }
2665}
2666
2667// check_const_field_values validates check const field values state for types.
2668fn (mut tc TypeChecker) check_const_field_values(node flat.Node) {
2669 for i in 0 .. node.children_count {
2670 field := tc.a.child_node(&node, i)
2671 if field.kind != .const_field || field.children_count == 0 {
2672 continue
2673 }
2674 tc.check_node(tc.a.child(field, 0))
2675 }
2676}
2677
2678// fn_body_definitely_returns supports fn body definitely returns handling for TypeChecker.
2679fn (tc &TypeChecker) fn_body_definitely_returns(node flat.Node) bool {
2680 for i in 0 .. node.children_count {
2681 child_id := tc.a.child(&node, i)
2682 child := tc.a.child_node(&node, i)
2683 if child.kind == .param {
2684 continue
2685 }
2686 if tc.stmt_definitely_returns(child_id) {
2687 return true
2688 }
2689 }
2690 return false
2691}
2692
2693fn type_allows_implicit_return(typ Type) bool {
2694 if typ is Void {
2695 return true
2696 }
2697 if typ is OptionType {
2698 return typ.base_type is Void
2699 }
2700 if typ is ResultType {
2701 return typ.base_type is Void
2702 }
2703 return false
2704}
2705
2706// valid_node_id supports valid node id handling for TypeChecker.
2707fn (tc &TypeChecker) valid_node_id(id flat.NodeId) bool {
2708 return int(id) >= 0 && tc.a != unsafe { nil } && int(id) < tc.a.nodes.len
2709}
2710
2711// stmt_definitely_returns supports stmt definitely returns handling for TypeChecker.
2712fn (tc &TypeChecker) stmt_definitely_returns(id flat.NodeId) bool {
2713 if !tc.valid_node_id(id) {
2714 return false
2715 }
2716 node := tc.a.nodes[int(id)]
2717 match node.kind {
2718 .return_stmt {
2719 return true
2720 }
2721 .block {
2722 for i in 0 .. node.children_count {
2723 if tc.stmt_definitely_returns(tc.a.child(&node, i)) {
2724 return true
2725 }
2726 }
2727 return false
2728 }
2729 .if_expr {
2730 if node.children_count < 3 {
2731 return false
2732 }
2733 return tc.stmt_definitely_returns(tc.a.child(&node, 1))
2734 && tc.stmt_definitely_returns(tc.a.child(&node, 2))
2735 }
2736 .match_stmt {
2737 if node.children_count < 2 {
2738 return false
2739 }
2740 mut has_else := false
2741 for i in 1 .. node.children_count {
2742 branch := tc.a.child_node(&node, i)
2743 if branch.kind != .match_branch {
2744 return false
2745 }
2746 if branch.value == 'else' {
2747 has_else = true
2748 }
2749 if !tc.match_branch_definitely_returns(branch) {
2750 return false
2751 }
2752 }
2753 return has_else || tc.match_without_else_exhaustive_enum_returns(node)
2754 }
2755 else {
2756 return false
2757 }
2758 }
2759}
2760
2761// match_covers_all_enum_variants reports whether a `match` over an enum subject
2762// lists every variant of that enum (so it is exhaustive without an `else`).
2763fn (tc &TypeChecker) match_covers_all_enum_variants(node flat.Node) bool {
2764 if node.children_count < 2 {
2765 return false
2766 }
2767 subject_type := unwrap_pointer(tc.resolve_type(tc.a.child(&node, 0)))
2768 mut enum_name := ''
2769 if subject_type is Enum {
2770 enum_name = subject_type.name
2771 } else {
2772 return false
2773 }
2774 // A `[flag]` enum value can hold combined or zero bits (`.read | .write`, `0`) that
2775 // no single-field branch covers, so listing every field is NOT exhaustive — such a
2776 // match needs an explicit `else`.
2777 if enum_name in tc.flag_enums {
2778 return false
2779 }
2780 all_fields := tc.enum_fields[enum_name] or { return false }
2781 if all_fields.len == 0 {
2782 return false
2783 }
2784 mut covered := map[string]bool{}
2785 for i in 1 .. node.children_count {
2786 branch := tc.a.child_node(&node, i)
2787 if branch.kind != .match_branch {
2788 return false
2789 }
2790 if branch.value == 'else' {
2791 return true
2792 }
2793 n_conds := branch.value.int()
2794 for j in 0 .. n_conds {
2795 cond := tc.a.child_node(branch, j)
2796 if cond.kind == .enum_val {
2797 covered[cond.value.all_after_last('.')] = true
2798 }
2799 }
2800 }
2801 for f in all_fields {
2802 if f !in covered {
2803 return false
2804 }
2805 }
2806 return true
2807}
2808
2809// match_branch_definitely_returns
2810// supports helper handling in types.
2811fn (tc &TypeChecker) match_branch_definitely_returns(branch &flat.Node) bool {
2812 body_start := if branch.value == 'else' { 0 } else { branch.value.int() }
2813 for i in body_start .. branch.children_count {
2814 if tc.stmt_definitely_returns(tc.a.child(branch, i)) {
2815 return true
2816 }
2817 }
2818 return false
2819}
2820
2821fn (tc &TypeChecker) match_without_else_exhaustive_enum_returns(node flat.Node) bool {
2822 subject_type := unwrap_pointer(tc.resolve_type(tc.a.child(&node, 0)))
2823 if subject_type is Enum {
2824 enum_name := tc.resolve_enum_name(subject_type.name) or { subject_type.name }
2825 if subject_type.is_flag || enum_name in tc.flag_enums {
2826 return false
2827 }
2828 fields := tc.enum_fields[enum_name] or { return false }
2829 if fields.len == 0 {
2830 return false
2831 }
2832 mut covered := map[string]bool{}
2833 for i in 1 .. node.children_count {
2834 branch := tc.a.child_node(&node, i)
2835 if branch.kind != .match_branch || branch.value == 'else' {
2836 return false
2837 }
2838 n_conds := branch.value.int()
2839 if n_conds <= 0 || n_conds > branch.children_count {
2840 return false
2841 }
2842 for j in 0 .. n_conds {
2843 cond := tc.a.child_node(branch, j)
2844 field := tc.match_enum_condition_field(cond, enum_name) or { return false }
2845 covered[field] = true
2846 }
2847 }
2848 for field in fields {
2849 if field !in covered {
2850 return false
2851 }
2852 }
2853 return true
2854 }
2855 return false
2856}
2857
2858fn (tc &TypeChecker) match_enum_condition_field(cond &flat.Node, enum_name string) ?string {
2859 match cond.kind {
2860 .enum_val {
2861 field := cond.value.all_after_last('.')
2862 if tc.enum_value_matches(cond.value, enum_name) {
2863 return field
2864 }
2865 }
2866 .selector {
2867 if typ := tc.enum_selector_type(cond) {
2868 if typ is Enum {
2869 cond_enum_name := tc.resolve_enum_name(typ.name) or { typ.name }
2870 if cond_enum_name == enum_name && tc.enum_has_field(enum_name, cond.value) {
2871 return cond.value
2872 }
2873 }
2874 }
2875 }
2876 else {}
2877 }
2878
2879 return none
2880}
2881
2882// node_kind_id supports node kind id handling for types.
2883fn node_kind_id(node flat.Node) int {
2884 mut kind_id := node.kind_id
2885 if kind_id == 0 && int(node.kind) != 0 {
2886 kind_id = int(node.kind)
2887 }
2888 return kind_id
2889}
2890
2891// check_node validates check node state for types.
2892fn (mut tc TypeChecker) check_node(id flat.NodeId) {
2893 idx := int(id)
2894 if idx < 0 {
2895 return
2896 }
2897 if idx >= tc.checking_nodes.len {
2898 tc.extend_node_caches(tc.a.nodes.len)
2899 }
2900 if idx < tc.checking_nodes.len {
2901 if tc.checking_nodes[idx] {
2902 return
2903 }
2904 tc.checking_nodes[idx] = true
2905 defer {
2906 tc.checking_nodes[idx] = false
2907 }
2908 }
2909 node := tc.a.nodes[idx]
2910 kind_id := node_kind_id(node)
2911 if kind_id == 1 || kind_id == 2 || kind_id == 3 || kind_id == 4 || kind_id == 5 || kind_id == 28
2912 || kind_id == 29 {
2913 return
2914 }
2915 if kind_id == 45 {
2916 tc.check_block(node)
2917 return
2918 }
2919 if kind_id == 46 {
2920 tc.check_for_stmt(node)
2921 return
2922 }
2923 if kind_id == 47 {
2924 tc.check_for_in_stmt(node)
2925 return
2926 }
2927 if kind_id == 41 {
2928 tc.check_decl_assign(id, node)
2929 return
2930 }
2931 if kind_id == 40 || kind_id == 42 || kind_id == 43 {
2932 tc.check_assign(id, node)
2933 return
2934 }
2935 if kind_id == 44 {
2936 tc.check_return(id, node)
2937 return
2938 }
2939 if kind_id == 12 {
2940 tc.check_call(id, node)
2941 return
2942 }
2943 if kind_id == 21 {
2944 tc.check_fn_literal(node)
2945 return
2946 }
2947 if kind_id == 32 {
2948 tc.check_lambda_expr(node)
2949 return
2950 }
2951 if kind_id == 15 {
2952 tc.check_if_expr(id, node)
2953 return
2954 }
2955 if kind_id == 22 {
2956 tc.check_or_expr(node)
2957 return
2958 }
2959 if kind_id == 50 {
2960 tc.check_match_stmt(id, node)
2961 return
2962 }
2963 if kind_id == 37 {
2964 tc.check_is_expr(id, node)
2965 return
2966 }
2967 if kind_id == 10 {
2968 tc.check_postfix(id, node)
2969 return
2970 }
2971 if kind_id == 16 || kind_id == 26 {
2972 tc.check_struct_init(id, node)
2973 return
2974 }
2975 if kind_id == 13 {
2976 tc.check_selector(id, node)
2977 return
2978 }
2979 if kind_id == 14 {
2980 tc.check_index(id, node)
2981 return
2982 }
2983 if kind_id == 7 {
2984 tc.check_ident(id, node)
2985 return
2986 }
2987 if node.kind == .array_init {
2988 tc.check_array_init(node)
2989 return
2990 }
2991 if node.kind == .select_stmt {
2992 tc.check_select_stmt(node)
2993 return
2994 }
2995 // A method value stored in a container escapes the single-use guarantee of its per-site
2996 // static receiver, so reject `[obj.method]` / `arr << obj.method` / `{'k': obj.method}`.
2997 if node.kind == .array_literal {
2998 for i in 0 .. node.children_count {
2999 tc.reject_stored_method_value(tc.a.child(&node, i))
3000 }
3001 } else if node.kind == .map_init {
3002 // children alternate key, value, key, value, ...; check the value positions.
3003 for j := 1; j < node.children_count; j += 2 {
3004 tc.reject_stored_method_value(tc.a.child(&node, j))
3005 }
3006 } else if node.kind == .infix && node.op == .left_shift && node.children_count >= 2 {
3007 if unwrap_pointer(tc.resolve_type(tc.a.child(&node, 0))) is Array {
3008 tc.reject_stored_method_value(tc.a.child(&node, 1))
3009 }
3010 }
3011
3012 for i in 0 .. node.children_count {
3013 tc.check_node(tc.a.child(&node, i))
3014 }
3015}
3016
3017// check_select_stmt validates a `select { ... }` statement. A receive branch
3018// `val := <-ch` binds `val` (the channel's element type) in the branch body's
3019// scope; other branches (sends, bare conditions, `else`) are checked as-is.
3020fn (mut tc TypeChecker) check_select_stmt(node flat.Node) {
3021 for i in 0 .. node.children_count {
3022 branch_id := tc.a.child(&node, i)
3023 if !tc.valid_node_id(branch_id) {
3024 continue
3025 }
3026 branch := tc.a.nodes[int(branch_id)]
3027 if branch.kind != .select_branch {
3028 tc.check_node(branch_id)
3029 continue
3030 }
3031 tc.push_scope()
3032 mut body_start := 0
3033 if branch.value == 'recv' && branch.children_count >= 2 {
3034 // children[0] = bound var ident, children[1] = `<-ch` receive expr.
3035 var_id := tc.a.child(&branch, 0)
3036 recv_id := tc.a.child(&branch, 1)
3037 tc.check_node(recv_id)
3038 elem_type := tc.resolve_type(recv_id)
3039 if tc.valid_node_id(var_id) {
3040 var_node := tc.a.nodes[int(var_id)]
3041 if var_node.kind == .ident && var_node.value.len > 0 {
3042 tc.cur_scope.insert(var_node.value, elem_type)
3043 }
3044 }
3045 body_start = 2
3046 }
3047 for j in body_start .. branch.children_count {
3048 tc.check_node(tc.a.child(&branch, j))
3049 }
3050 tc.pop_scope()
3051 }
3052}
3053
3054// check_array_init validates an `[]T{len: ..., init: ...}` initializer. The `init:`
3055// expression may reference the magic `index` variable (the current element index),
3056// so it is checked in a scope where `index` is bound to an int.
3057fn (mut tc TypeChecker) check_array_init(node flat.Node) {
3058 for i in 0 .. node.children_count {
3059 child_id := tc.a.child(&node, i)
3060 child := tc.a.nodes[int(child_id)]
3061 if child.kind == .field_init && child.value == 'init' {
3062 tc.push_scope()
3063 tc.cur_scope.insert('index', Type(int_))
3064 tc.check_node(child_id)
3065 tc.pop_scope()
3066 } else {
3067 tc.check_node(child_id)
3068 }
3069 }
3070}
3071
3072// check_or_expr validates check or expr state for types.
3073fn (mut tc TypeChecker) check_or_expr(node flat.Node) {
3074 if node.children_count == 0 {
3075 return
3076 }
3077 inner_id := tc.a.child(&node, 0)
3078 tc.check_node(inner_id)
3079 if node.children_count < 2 || node.value in ['!', '?'] {
3080 return
3081 }
3082 tc.push_scope()
3083 tc.cur_scope.insert('err', tc.parse_type('IError'))
3084 tc.check_node(tc.a.child(&node, 1))
3085 tc.pop_scope()
3086}
3087
3088// check_fn_literal validates check fn literal state for types.
3089fn (mut tc TypeChecker) check_fn_literal(node flat.Node) {
3090 saved_ret := tc.cur_fn_ret_type
3091 tc.cur_fn_ret_type = tc.parse_type(node.typ)
3092 tc.push_scope()
3093 for i in 0 .. node.children_count {
3094 child := tc.a.child_node(&node, i)
3095 if child.kind == .param && child.value.len > 0 {
3096 tc.cur_scope.insert(child.value, tc.parse_type(child.typ))
3097 }
3098 }
3099 for i in 0 .. node.children_count {
3100 child_id := tc.a.child(&node, i)
3101 child := tc.a.nodes[int(child_id)]
3102 if child.kind == .param || child.kind == .ident {
3103 continue
3104 }
3105 tc.check_node(child_id)
3106 }
3107 tc.pop_scope()
3108 tc.cur_fn_ret_type = saved_ret
3109}
3110
3111// check_lambda_expr validates check lambda expr state for types.
3112fn (mut tc TypeChecker) check_lambda_expr(node flat.Node) {
3113 if node.children_count == 0 {
3114 return
3115 }
3116 tc.push_scope()
3117 for i in 0 .. node.children_count - 1 {
3118 child := tc.a.child_node(&node, i)
3119 if child.kind == .ident && child.value.len > 0 {
3120 tc.cur_scope.insert(child.value, unknown_type('lambda parameter `${child.value}`'))
3121 }
3122 }
3123 tc.check_node(tc.a.child(&node, node.children_count - 1))
3124 tc.pop_scope()
3125}
3126
3127// check_block validates check block state for types.
3128fn (mut tc TypeChecker) check_block(node flat.Node) {
3129 tc.push_scope()
3130 for i in 0 .. node.children_count {
3131 tc.check_node(tc.a.child(&node, i))
3132 }
3133 tc.pop_scope()
3134}
3135
3136// check_for_stmt validates check for stmt state for types.
3137fn (mut tc TypeChecker) check_for_stmt(node flat.Node) {
3138 tc.push_scope()
3139 if node.children_count > 0 {
3140 init_id := tc.a.child(&node, 0)
3141 if int(init_id) >= 0 {
3142 tc.check_node(init_id)
3143 }
3144 }
3145 if node.children_count > 1 {
3146 cond_id := tc.a.child(&node, 1)
3147 if int(cond_id) >= 0 {
3148 tc.check_bool_condition(cond_id)
3149 }
3150 }
3151 if node.children_count > 2 {
3152 post_id := tc.a.child(&node, 2)
3153 if int(post_id) >= 0 {
3154 tc.check_node(post_id)
3155 }
3156 }
3157 for i in 3 .. node.children_count {
3158 tc.check_node(tc.a.child(&node, i))
3159 }
3160 tc.pop_scope()
3161}
3162
3163// check_for_in_stmt validates check for in stmt state for types.
3164fn (mut tc TypeChecker) check_for_in_stmt(node flat.Node) {
3165 header := node.value.int()
3166 if header < 3 || node.children_count < 3 {
3167 return
3168 }
3169 tc.push_scope()
3170 key_id := tc.a.child(&node, 0)
3171 val_id := tc.a.child(&node, 1)
3172 container_id := tc.a.child(&node, 2)
3173 tc.check_node(container_id)
3174 has_val := int(val_id) >= 0
3175 if header == 4 {
3176 tc.insert_loop_var(key_id, Type(int_))
3177 tc.check_node(tc.a.child(&node, 3))
3178 } else {
3179 clean := unwrap_pointer(tc.resolve_type(container_id))
3180 if clean is Array {
3181 if has_val {
3182 tc.insert_loop_var(key_id, Type(int_))
3183 tc.insert_loop_var(val_id, clean.elem_type)
3184 } else {
3185 tc.insert_loop_var(key_id, clean.elem_type)
3186 }
3187 } else if clean is ArrayFixed {
3188 if has_val {
3189 tc.insert_loop_var(key_id, Type(int_))
3190 tc.insert_loop_var(val_id, clean.elem_type)
3191 } else {
3192 tc.insert_loop_var(key_id, clean.elem_type)
3193 }
3194 } else if clean is Map {
3195 if has_val {
3196 tc.insert_loop_var(key_id, clean.key_type)
3197 tc.insert_loop_var(val_id, clean.value_type)
3198 } else {
3199 tc.insert_loop_var(key_id, clean.value_type)
3200 }
3201 } else if clean is String {
3202 if has_val {
3203 tc.insert_loop_var(key_id, Type(int_))
3204 tc.insert_loop_var(val_id, Type(u8_))
3205 } else {
3206 tc.insert_loop_var(key_id, Type(u8_))
3207 }
3208 } else {
3209 container := tc.a.nodes[int(container_id)]
3210 if container.kind == .range {
3211 tc.insert_loop_var(key_id, Type(int_))
3212 } else if tc.should_diagnose(container_id) {
3213 tc.record_error(.cannot_index, 'cannot iterate over `${clean.name()}`',
3214 container_id)
3215 }
3216 }
3217 }
3218 for i in header .. node.children_count {
3219 tc.check_node(tc.a.child(&node, i))
3220 }
3221 tc.pop_scope()
3222}
3223
3224// check_decl_assign validates check decl assign state for types.
3225fn (mut tc TypeChecker) check_decl_assign(id flat.NodeId, node flat.Node) {
3226 if node.children_count == 0 {
3227 return
3228 }
3229 if tc.check_multi_return_decl_assign(id, node) {
3230 return
3231 }
3232 mut i := 0
3233 for i + 1 < node.children_count {
3234 lhs_id := tc.a.child(&node, i)
3235 rhs_id := tc.a.child(&node, i + 1)
3236 tc.check_node(rhs_id)
3237 mut rhs_type := tc.decl_assign_inferred_type(rhs_id)
3238 mut expected := rhs_type
3239 if node.children_count == 2 && node.typ.len > 0 {
3240 expected = tc.parse_type(node.typ)
3241 rhs_type = tc.resolve_expr(rhs_id, expected)
3242 if !tc.type_compatible(rhs_type, expected) {
3243 tc.type_mismatch(.assignment_mismatch,
3244 'cannot assign `${rhs_type.name()}` to `${expected.name()}`', id)
3245 }
3246 }
3247 tc.insert_decl_lhs(lhs_id, expected)
3248 tc.track_method_value_local(lhs_id, rhs_id)
3249 i += 2
3250 }
3251}
3252
3253// cur_scope_depth returns the number of enclosing scopes (the current scope's parent-chain
3254// length), used to tell a dominating top-level reassignment from one nested in a branch/loop.
3255fn (tc &TypeChecker) cur_scope_depth() int {
3256 mut d := 0
3257 mut s := tc.cur_scope
3258 for s != unsafe { nil } {
3259 d++
3260 s = s.parent
3261 }
3262 return d
3263}
3264
3265// track_method_value_local records (or clears) a local variable bound to a method value, so a
3266// later `return cb` / `arr << cb` aliasing the same per-site static receiver is rejected as an
3267// escape just like the bare `return c.report`.
3268fn (mut tc TypeChecker) track_method_value_local(lhs_id flat.NodeId, rhs_id flat.NodeId) {
3269 if int(lhs_id) < 0 {
3270 return
3271 }
3272 lhs := tc.a.nodes[int(lhs_id)]
3273 if lhs.kind != .ident || lhs.value.len == 0 || lhs.value == '_' {
3274 return
3275 }
3276 if tc.expr_is_method_value(rhs_id) {
3277 tc.method_value_locals[lhs.value] = true
3278 tc.method_value_local_depth[lhs.value] = tc.cur_scope_depth()
3279 } else if lhs.value in tc.method_value_locals {
3280 // Reassigned to a non-method-value. Only clear the marker when this reassignment
3281 // dominates later uses — at the same or a shallower scope than where the local was
3282 // marked. A reassignment in a deeper conditional/loop scope does not run on every path
3283 // (`mut cb := c.report; if x { cb = plain }; return cb`), so the local may still hold the
3284 // method value; keep the maybe-method marker and let the later escape be rejected.
3285 marked_depth := tc.method_value_local_depth[lhs.value] or { 0 }
3286 if tc.cur_scope_depth() <= marked_depth {
3287 tc.method_value_locals.delete(lhs.value)
3288 tc.method_value_local_depth.delete(lhs.value)
3289 }
3290 }
3291}
3292
3293fn (mut tc TypeChecker) decl_assign_inferred_type(rhs_id flat.NodeId) Type {
3294 if int(rhs_id) < 0 || int(rhs_id) >= tc.a.nodes.len {
3295 return unknown_type('missing declaration initializer')
3296 }
3297 rhs := tc.a.nodes[int(rhs_id)]
3298 if rhs.kind == .cast_expr && rhs.value.len > 0 {
3299 typ := tc.parse_type(rhs.value)
3300 if typ is Alias {
3301 return typ
3302 }
3303 }
3304 if typ := tc.infer_fn_value_decl_type(rhs_id) {
3305 return typ
3306 }
3307 return tc.resolve_type(rhs_id)
3308}
3309
3310fn (mut tc TypeChecker) infer_fn_value_decl_type(rhs_id flat.NodeId) ?Type {
3311 if int(rhs_id) < 0 || int(rhs_id) >= tc.a.nodes.len {
3312 return none
3313 }
3314 rhs := tc.a.nodes[int(rhs_id)]
3315 if tc.fn_value_shadowed_by_value(rhs) {
3316 return none
3317 }
3318 key := tc.fn_value_key(rhs) or { return none }
3319 typ := tc.fn_type_from_key(key) or { return none }
3320 tc.remember_resolved_fn_value_chain(rhs_id, key)
3321 tc.register_synth_type(rhs_id, typ)
3322 return typ
3323}
3324
3325fn (tc &TypeChecker) fn_value_shadowed_by_value(node flat.Node) bool {
3326 match node.kind {
3327 .ident {
3328 return tc.name_bound_as_value(node.value)
3329 }
3330 .selector {
3331 return tc.selector_base_bound_as_value(node)
3332 }
3333 .cast_expr, .paren, .expr_stmt {
3334 if node.children_count == 0 {
3335 return false
3336 }
3337 return tc.fn_value_shadowed_by_value(tc.a.child_node(&node, 0))
3338 }
3339 else {
3340 return false
3341 }
3342 }
3343}
3344
3345// lvalue_is_local_var reports whether an assignment target is safe to receive a method value:
3346// the blank discard `_` (stores nothing) or a plain function-local variable bound under its bare
3347// name in the current scope. Non-local storage (a struct field `h.cb`, an array/map element
3348// `cbs[i]`, or a module-level global, which lives in file_scope under its qualified name and so
3349// misses a bare lookup) is not. A method value may alias a local (tracked for a later escape) but
3350// must not be stored into anything that outlives the call site.
3351fn (tc &TypeChecker) lvalue_is_local_var(lhs_id flat.NodeId) bool {
3352 if int(lhs_id) < 0 {
3353 return false
3354 }
3355 lhs := tc.a.nodes[int(lhs_id)]
3356 if lhs.kind != .ident || lhs.value.len == 0 {
3357 return false
3358 }
3359 if lhs.value == '_' {
3360 return true
3361 }
3362 return tc.cur_scope.lookup(lhs.value) != none
3363}
3364
3365fn (tc &TypeChecker) selector_base_bound_as_value(node flat.Node) bool {
3366 if node.children_count == 0 {
3367 return false
3368 }
3369 base := tc.a.child_node(&node, 0)
3370 match base.kind {
3371 .ident {
3372 return tc.name_bound_as_value(base.value)
3373 }
3374 .selector {
3375 return tc.selector_base_bound_as_value(base)
3376 }
3377 .cast_expr, .paren, .expr_stmt {
3378 if base.children_count == 0 {
3379 return false
3380 }
3381 return tc.fn_value_shadowed_by_value(tc.a.child_node(base, 0))
3382 }
3383 else {
3384 return false
3385 }
3386 }
3387}
3388
3389fn (tc &TypeChecker) name_bound_as_value(name string) bool {
3390 if name.len == 0 {
3391 return false
3392 }
3393 if typ := tc.cur_scope.lookup(name) {
3394 return typ !is Void
3395 }
3396 if typ := tc.file_scope.lookup(name) {
3397 return typ !is Void
3398 }
3399 return false
3400}
3401
3402// check_multi_return_decl_assign validates check multi return decl assign state for types.
3403fn (mut tc TypeChecker) check_multi_return_decl_assign(id flat.NodeId, node flat.Node) bool {
3404 if node.children_count < 3 {
3405 return false
3406 }
3407 rhs_id := tc.a.child(&node, 1)
3408 rhs_type := tc.resolve_type(rhs_id)
3409 rhs_type_name := rhs_type.name()
3410 if rhs_type is MultiReturn {
3411 tc.check_node(rhs_id)
3412 lhs_ids := tc.multi_assign_lhs_ids(node)
3413 if lhs_ids.len != rhs_type.types.len {
3414 if tc.should_diagnose(id) {
3415 tc.record_error(.assignment_mismatch,
3416 'multi-return assignment mismatch: ${lhs_ids.len} variables but `${rhs_type_name}` has ${rhs_type.types.len} values',
3417 id)
3418 }
3419 return true
3420 }
3421 for i, lhs_id in lhs_ids {
3422 tc.insert_decl_lhs(lhs_id, rhs_type.types[i])
3423 }
3424 return true
3425 }
3426 return false
3427}
3428
3429// multi_assign_lhs_ids supports multi assign lhs ids handling for TypeChecker.
3430fn (tc &TypeChecker) multi_assign_lhs_ids(node flat.Node) []flat.NodeId {
3431 mut lhs_ids := []flat.NodeId{}
3432 if node.children_count > 0 {
3433 lhs_ids << tc.a.child(&node, 0)
3434 }
3435 for i in 2 .. node.children_count {
3436 lhs_ids << tc.a.child(&node, i)
3437 }
3438 return lhs_ids
3439}
3440
3441// insert_decl_lhs updates insert decl lhs state for types.
3442fn (mut tc TypeChecker) insert_decl_lhs(lhs_id flat.NodeId, typ Type) {
3443 if int(lhs_id) < 0 || typ is Void {
3444 return
3445 }
3446 lhs := tc.a.nodes[int(lhs_id)]
3447 if lhs.kind == .ident && lhs.value.len > 0 {
3448 tc.cur_scope.insert(lhs.value, typ)
3449 tc.register_synth_type(lhs_id, typ)
3450 }
3451}
3452
3453// check_assign validates check assign state for types.
3454fn (mut tc TypeChecker) check_assign(id flat.NodeId, node flat.Node) {
3455 if node.children_count < 2 {
3456 return
3457 }
3458 if node.kind == .index_assign && tc.reject_unlowered_map_mutation
3459 && tc.index_assign_lhs_is_map(node) {
3460 if tc.should_diagnose(id) {
3461 tc.record_error(.assignment_mismatch,
3462 'internal compiler error: unlowered map index assignment reached post-transform checker',
3463 id)
3464 }
3465 for i := 1; i < node.children_count; i += 2 {
3466 tc.check_node(tc.a.child(&node, i))
3467 }
3468 return
3469 }
3470 if tc.check_multi_return_assign(id, node) {
3471 return
3472 }
3473 mut i := 0
3474 for i + 1 < node.children_count {
3475 lhs_id := tc.a.child(&node, i)
3476 rhs_id := tc.a.child(&node, i + 1)
3477 lhs_type := tc.resolve_lvalue_type(lhs_id)
3478 tc.check_node(rhs_id)
3479 rhs_type := tc.resolve_expr(rhs_id, lhs_type)
3480 if !tc.type_compatible(rhs_type, lhs_type) {
3481 tc.type_mismatch(.assignment_mismatch,
3482 'cannot assign `${rhs_type.name()}` to `${lhs_type.name()}`', id)
3483 }
3484 if node.kind in [.assign, .selector_assign, .index_assign] {
3485 if tc.expr_is_method_value(rhs_id) && !tc.lvalue_is_local_var(lhs_id) {
3486 // Storing a method value into a struct field (`h.cb = ..`), an array/map element
3487 // (`cbs[i] = ..`), or a global lets it outlive the per-site static `_mvctx_N`
3488 // receiver slot, which the next evaluation of the same site overwrites — so every
3489 // stored callback would use the last receiver. Reject it like the other escapes.
3490 tc.reject_stored_method_value(rhs_id)
3491 } else {
3492 tc.track_method_value_local(lhs_id, rhs_id)
3493 }
3494 }
3495 i += 2
3496 }
3497}
3498
3499// index_assign_lhs_is_map supports index assign lhs is map handling for TypeChecker.
3500fn (tc &TypeChecker) index_assign_lhs_is_map(node flat.Node) bool {
3501 if node.children_count == 0 {
3502 return false
3503 }
3504 lhs_id := tc.a.child(&node, 0)
3505 if int(lhs_id) < 0 {
3506 return false
3507 }
3508 lhs := tc.a.nodes[int(lhs_id)]
3509 if lhs.kind != .index || lhs.children_count < 2 {
3510 return false
3511 }
3512 base_type := unwrap_pointer(tc.resolve_type(tc.a.child(&lhs, 0)))
3513 return base_type is Map
3514}
3515
3516// check_multi_return_assign validates check multi return assign state for types.
3517fn (mut tc TypeChecker) check_multi_return_assign(id flat.NodeId, node flat.Node) bool {
3518 if node.children_count < 3 {
3519 return false
3520 }
3521 rhs_id := tc.a.child(&node, 1)
3522 rhs_type := tc.resolve_type(rhs_id)
3523 rhs_type_name := rhs_type.name()
3524 if rhs_type is MultiReturn {
3525 tc.check_node(rhs_id)
3526 lhs_ids := tc.multi_assign_lhs_ids(node)
3527 if lhs_ids.len != rhs_type.types.len {
3528 if tc.should_diagnose(id) {
3529 tc.record_error(.assignment_mismatch,
3530 'multi-return assignment mismatch: ${lhs_ids.len} variables but `${rhs_type_name}` has ${rhs_type.types.len} values',
3531 id)
3532 }
3533 return true
3534 }
3535 for i, lhs_id in lhs_ids {
3536 lhs_type := tc.resolve_lvalue_type(lhs_id)
3537 if !tc.type_compatible(rhs_type.types[i], lhs_type) {
3538 tc.type_mismatch(.assignment_mismatch,
3539 'cannot assign `${rhs_type.types[i].name()}` to `${lhs_type.name()}`', id)
3540 }
3541 }
3542 return true
3543 }
3544 return false
3545}
3546
3547// check_postfix validates check postfix state for types.
3548fn (mut tc TypeChecker) check_postfix(id flat.NodeId, node flat.Node) {
3549 if node.children_count == 0 {
3550 return
3551 }
3552 child_id := tc.a.child(&node, 0)
3553 tc.check_node(child_id)
3554 child := tc.a.nodes[int(child_id)]
3555 if child.kind == .index && child.children_count >= 2 {
3556 base_type := unwrap_pointer(tc.resolve_type(tc.a.child(&child, 0)))
3557 if base_type is Map && node.op in [.inc, .dec] && tc.reject_unlowered_map_mutation
3558 && tc.should_diagnose(id) {
3559 tc.record_error(.assignment_mismatch,
3560 'internal compiler error: unlowered map index postfix mutation reached post-transform checker',
3561 id)
3562 }
3563 }
3564}
3565
3566// resolve_lvalue_type resolves resolve lvalue type information for types.
3567fn (mut tc TypeChecker) resolve_lvalue_type(lhs_id flat.NodeId) Type {
3568 if int(lhs_id) < 0 {
3569 return Type(void_)
3570 }
3571 lhs := tc.a.nodes[int(lhs_id)]
3572 if lhs.kind == .ident {
3573 if typ := tc.cur_scope.lookup(lhs.value) {
3574 return typ
3575 }
3576 if typ := tc.file_scope.lookup(lhs.value) {
3577 return typ
3578 }
3579 if tc.should_diagnose(lhs_id) && lhs.value != '_' {
3580 tc.record_error(.unknown_ident, 'unknown identifier `${lhs.value}`', lhs_id)
3581 }
3582 return unknown_type('unknown identifier `${lhs.value}`')
3583 }
3584 if lhs.kind == .selector {
3585 tc.check_selector(lhs_id, lhs)
3586 return tc.resolve_type(lhs_id)
3587 }
3588 if lhs.kind == .index {
3589 tc.check_index(lhs_id, lhs)
3590 return tc.resolve_type(lhs_id)
3591 }
3592 return tc.resolve_type(lhs_id)
3593}
3594
3595// check_return validates check return state for types.
3596fn (mut tc TypeChecker) check_return(id flat.NodeId, node flat.Node) {
3597 // A returned method value escapes the function, where its per-site static receiver
3598 // can't keep multiple returned callbacks distinct (a factory `fn bind(c) fn () int {
3599 // return c.report }`); reject it rather than emitting invalid C.
3600 for i in 0 .. node.children_count {
3601 tc.reject_stored_method_value(tc.a.child(&node, i))
3602 }
3603 expected := tc.cur_fn_ret_type
3604 if expected is Void {
3605 if node.children_count > 0 && tc.should_diagnose(id) {
3606 tc.record_error(.return_mismatch, 'void function should not return a value', id)
3607 }
3608 for i in 0 .. node.children_count {
3609 tc.check_node(tc.a.child(&node, i))
3610 }
3611 return
3612 }
3613 if node.children_count == 0 {
3614 if type_allows_implicit_return(expected) {
3615 return
3616 }
3617 if tc.should_diagnose(id) {
3618 tc.record_error(.return_mismatch, 'missing return value of type `${expected.name()}`',
3619 id)
3620 }
3621 return
3622 }
3623 if multi := multi_return_payload_type(expected) {
3624 if node.children_count == 1 {
3625 child_id := tc.a.child(&node, 0)
3626 tc.check_node(child_id)
3627 actual := tc.resolve_expr(child_id, expected)
3628 if tc.type_compatible(actual, expected) {
3629 return
3630 }
3631 }
3632 if node.children_count != multi.types.len {
3633 if tc.should_diagnose(id) {
3634 tc.record_error(.return_mismatch,
3635 'return value count mismatch: expected ${multi.types.len}, got ${node.children_count}',
3636 id)
3637 }
3638 return
3639 }
3640 for i in 0 .. node.children_count {
3641 child_id := tc.a.child(&node, i)
3642 tc.check_node(child_id)
3643 actual := tc.resolve_expr(child_id, multi.types[i])
3644 if !tc.type_compatible(actual, multi.types[i]) {
3645 tc.type_mismatch(.return_mismatch,
3646 'cannot return `${actual.name()}` as `${multi.types[i].name()}`', id)
3647 }
3648 }
3649 return
3650 }
3651 if node.children_count != 1 {
3652 if tc.should_diagnose(id) {
3653 tc.record_error(.return_mismatch,
3654 'return value count mismatch: expected 1, got ${node.children_count}', id)
3655 }
3656 return
3657 }
3658 child_id := tc.a.child(&node, 0)
3659 tc.check_node(child_id)
3660 actual := tc.resolve_expr(child_id, expected)
3661 if !tc.type_compatible(actual, expected) {
3662 tc.type_mismatch(.return_mismatch,
3663 'cannot return `${actual.name()}` as `${expected.name()}`', id)
3664 }
3665}
3666
3667fn multi_return_payload_type(typ Type) ?MultiReturn {
3668 if typ is MultiReturn {
3669 return typ
3670 }
3671 if typ is OptionType {
3672 base := typ.base_type
3673 if base is MultiReturn {
3674 return base
3675 }
3676 }
3677 if typ is ResultType {
3678 base := typ.base_type
3679 if base is MultiReturn {
3680 return base
3681 }
3682 }
3683 return none
3684}
3685
3686// check_call validates check call state for types.
3687fn (mut tc TypeChecker) check_call(id flat.NodeId, node flat.Node) {
3688 if info := tc.resolve_call_info(id, node) {
3689 if info.name.len > 0 && !is_array_dsl_call_name(info.name) {
3690 tc.remember_resolved_call(id, info.name)
3691 }
3692 if info.return_type !is Void && info.return_type !is Unknown {
3693 tc.remember_expr_type(id, info.return_type)
3694 }
3695 tc.check_call_arg_types(id, node, info)
3696 return
3697 }
3698 if tc.call_has_ambiguous_selective_import(node) {
3699 tc.record_error(.unknown_fn, 'ambiguous selective import `${tc.call_display_name(node)}`',
3700 id)
3701 return
3702 }
3703 if tc.should_diagnose(id) && !tc.is_known_call(node) {
3704 tc.record_error(.unknown_fn, 'unknown function `${tc.call_display_name(node)}`', id)
3705 }
3706 for i in 1 .. node.children_count {
3707 tc.check_node(tc.call_arg_value(tc.a.child(&node, i)))
3708 }
3709}
3710
3711// should_diagnose reports whether should diagnose applies in types.
3712fn (tc &TypeChecker) should_diagnose(id flat.NodeId) bool {
3713 if int(id) < 0 || int(id) < tc.a.user_code_start {
3714 return false
3715 }
3716 if int(id) < tc.a.nodes.len && !tc.a.nodes[int(id)].pos.is_valid() && !tc.diagnose_unknown_calls {
3717 return false
3718 }
3719 if tc.diagnostic_files.len == 0 {
3720 return true
3721 }
3722 return tc.cur_file in tc.diagnostic_files
3723}
3724
3725fn (tc &TypeChecker) should_diagnose_unsupported_generic(id flat.NodeId) bool {
3726 if tc.should_diagnose(id) {
3727 return true
3728 }
3729 if int(id) < 0 || int(id) < tc.a.user_code_start {
3730 return false
3731 }
3732 if tc.diagnostic_files.len == 0 {
3733 return false
3734 }
3735 return tc.diagnostic_files['generic:' + tc.cur_file]
3736}
3737
3738// should_diagnose_unknown_call reports whether should diagnose unknown call applies in types.
3739fn (tc &TypeChecker) should_diagnose_unknown_call(id flat.NodeId) bool {
3740 return tc.diagnose_unknown_calls && tc.should_diagnose(id)
3741}
3742
3743// resolve_call_info resolves resolve call info information for types.
3744fn (mut tc TypeChecker) resolve_call_info(_id flat.NodeId, node flat.Node) ?CallInfo {
3745 if node.children_count == 0 {
3746 return none
3747 }
3748 fn_node := tc.a.child_node(&node, 0)
3749 if info := tc.resolve_generic_call_info(fn_node) {
3750 return info
3751 }
3752 if fn_node.kind == .selector {
3753 base_id := tc.a.child(fn_node, 0)
3754 base_node := tc.a.nodes[int(base_id)]
3755 if base_node.kind == .ident && base_node.value == 'C' {
3756 return none
3757 }
3758 if base_node.kind == .ident {
3759 if resolved_mod := tc.resolve_import_alias(base_node.value) {
3760 mod_name := '${resolved_mod}.${fn_node.value}'
3761 if mod_name in tc.fn_ret_types {
3762 return tc.call_info(mod_name, false)
3763 }
3764 }
3765 qbase := tc.qualify_name(base_node.value)
3766 static_name := '${qbase}.${fn_node.value}'
3767 if static_name in tc.fn_ret_types && (qbase in tc.structs
3768 || qbase in tc.enum_names || qbase in tc.sum_types
3769 || qbase in tc.interface_names || qbase in tc.type_aliases) {
3770 // `qbase in tc.type_aliases` covers static methods on a type alias,
3771 // e.g. `fn SimdFloat4.new()` for `type SimdFloat4 = vec.Vec4[f32]`.
3772 return tc.call_info(static_name, false)
3773 }
3774 if fn_node.value == 'zero' && qbase in tc.flag_enums {
3775 return CallInfo{
3776 name: ''
3777 params: []Type{}
3778 return_type: Type(Enum{
3779 name: qbase
3780 is_flag: true
3781 })
3782 params_known: true
3783 }
3784 }
3785 } else if base_node.kind == .selector {
3786 if method_name := tc.module_const_receiver_method_name(base_node, fn_node.value) {
3787 return tc.call_info(method_name, true)
3788 }
3789 inner := tc.a.child_node(base_node, 0)
3790 if inner.kind == .ident {
3791 mod_name := tc.resolve_import_alias(inner.value) or { inner.value }
3792 full_name := '${mod_name}.${base_node.value}.${fn_node.value}'
3793 if full_name in tc.fn_ret_types {
3794 return tc.call_info(full_name, false)
3795 }
3796 }
3797 }
3798 if fn_typ := tc.selector_fn_type(fn_node) {
3799 return CallInfo{
3800 name: ''
3801 params: fn_typ.params.clone()
3802 return_type: fn_typ.return_type