Skip to content

Commit

Permalink
cgen: fix smartcasting a reference to a sumtype value (#21730)
Browse files Browse the repository at this point in the history
  • Loading branch information
yuyi98 authored Jun 25, 2024
1 parent 5b93582 commit 98a1ee2
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 1 deletion.
9 changes: 8 additions & 1 deletion vlib/v/gen/c/cgen.v
Original file line number Diff line number Diff line change
Expand Up @@ -4931,7 +4931,14 @@ fn (mut g Gen) ident(node ast.Ident) {
if node.obj.is_inherited {
g.write(closure_ctx + '->')
}
g.write(name)
if node.obj.typ.nr_muls() > 1 {
g.write('(')
g.write('*'.repeat(node.obj.typ.nr_muls() - 1))
g.write(name)
g.write(')')
} else {
g.write(name)
}
if node.obj.orig_type.is_ptr() {
is_ptr = true
}
Expand Down
3 changes: 3 additions & 0 deletions vlib/v/gen/c/infix.v
Original file line number Diff line number Diff line change
Expand Up @@ -695,6 +695,9 @@ fn (mut g Gen) infix_expr_is_op(node ast.InfixExpr) {

cmp_op := if node.op == .key_is { '==' } else { '!=' }
g.write('(')
if node.left_type.nr_muls() > 1 {
g.write('*'.repeat(node.left_type.nr_muls() - 1))
}
if is_aggregate {
g.write('${node.left}')
} else {
Expand Down
29 changes: 29 additions & 0 deletions vlib/v/tests/sumtype_with_reference_test.v
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
struct Parse {
mut:
stack []&Element
}

struct Balise {}

struct RawText {
s string
}

type Element = Balise | RawText

fn (mut p Parse) process_open_tag() string {
mut last := &p.stack[0]
if mut last is RawText {
println(last)
return last.s
} else {
return ''
}
}

fn test_sumtype_with_reference() {
mut parse := Parse{
stack: [&RawText{'raw'}]
}
assert parse.process_open_tag() == 'raw'
}

0 comments on commit 98a1ee2

Please sign in to comment.