Skip to content

Commit

Permalink
checker, cgen: fix sumtype smartcasted var as inherited var (fix #23716
Browse files Browse the repository at this point in the history
…) (#23731)
  • Loading branch information
felipensp authored Feb 15, 2025
1 parent f4aa139 commit 00a08c4
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 4 deletions.
9 changes: 7 additions & 2 deletions vlib/v/checker/fn.v
Original file line number Diff line number Diff line change
Expand Up @@ -634,8 +634,13 @@ fn (mut c Checker) anon_fn(mut node ast.AnonFn) ast.Type {
c.error('original `${parent_var.name}` is immutable, declare it with `mut` to make it mutable',
var.pos)
}
ptyp := if parent_var.smartcasts.len > 0 {
parent_var.smartcasts.last()
} else {
parent_var.typ
}
if parent_var.typ != ast.no_type {
parent_var_sym := c.table.final_sym(parent_var.typ)
parent_var_sym := c.table.final_sym(ptyp)
if parent_var_sym.info is ast.FnType {
ret_typ := c.unwrap_generic(parent_var_sym.info.func.return_type)
if ret_typ.has_flag(.generic) {
Expand Down Expand Up @@ -663,7 +668,7 @@ fn (mut c Checker) anon_fn(mut node ast.AnonFn) ast.Type {
var.typ = parent_var.expr.expr_type.clear_option_and_result()
}
} else {
var.typ = parent_var.typ
var.typ = ptyp
}
if var.typ.has_flag(.generic) {
has_generic = true
Expand Down
11 changes: 9 additions & 2 deletions vlib/v/gen/c/fn.v
Original file line number Diff line number Diff line change
Expand Up @@ -662,13 +662,20 @@ fn (mut g Gen) gen_anon_fn(mut node ast.AnonFn) {
g.writeln('.${var_name} = string_clone(${var_name}),')
} else {
mut is_auto_heap := false
mut field_name := ''
if obj := node.decl.scope.parent.find(var.name) {
if obj is ast.Var {
is_auto_heap = !obj.is_stack_obj && obj.is_auto_heap
if obj.smartcasts.len > 0 {
if g.table.type_kind(obj.typ) == .sum_type {
cast_sym := g.table.sym(obj.smartcasts.last())
field_name += '._${cast_sym.cname}'
}
}
}
}
if is_auto_heap && !is_ptr {
g.writeln('.${var_name} = *${var_name},')
if (is_auto_heap && !is_ptr) || field_name != '' {
g.writeln('.${var_name} = *${var_name}${field_name},')
} else {
g.writeln('.${var_name} = ${var_name},')
}
Expand Down
26 changes: 26 additions & 0 deletions vlib/v/tests/sumtypes/sumtype_inherited_var_test.v
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
struct Aa {
a int
}

struct Bb {
b int
}

type Type = Aa | Bb

fn test_main() {
t := Type(Aa{
a: 2
})
match t {
Aa {
assert t.a == 2
func := fn [t] () {
assert typeof(t).name == 'Aa'
assert t.a == 2
}
func()
}
Bb {}
}
}

0 comments on commit 00a08c4

Please sign in to comment.