Skip to content

Commit

Permalink
cgen: fix none passed to a generic option cast expression (fix #21215
Browse files Browse the repository at this point in the history
…) (#21276)
  • Loading branch information
felipensp committed Apr 14, 2024
1 parent ae5421e commit 149cbba
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 2 deletions.
8 changes: 6 additions & 2 deletions vlib/v/gen/c/assign.v
Expand Up @@ -71,8 +71,12 @@ fn (mut g Gen) expr_opt_with_cast(expr ast.Expr, expr_typ ast.Type, ret_typ ast.
styp := g.base_type(ret_typ)
decl_styp := g.typ(ret_typ).replace('*', '_ptr')
g.writeln('${decl_styp} ${past.tmp_var};')
g.write('_option_ok(&(${styp}[]) {')

is_none := expr is ast.CastExpr && expr.expr is ast.None
if is_none {
g.write('_option_none(&(${styp}[]) {')
} else {
g.write('_option_ok(&(${styp}[]) {')
}
if expr is ast.CastExpr && expr_typ.has_flag(.option) {
g.write('*((${g.base_type(expr_typ)}*)')
g.expr(expr)
Expand Down
27 changes: 27 additions & 0 deletions vlib/v/tests/option_generic_cast_none_test.v
@@ -0,0 +1,27 @@
pub type MyFn[T] = fn (mut my_state T)

fn higher_order_fn[T](initial_state T, maybe_callback ?MyFn[T]) State {
mut my_state := initial_state
if callback := maybe_callback {
callback[T](mut my_state)
callback[T](mut my_state)
}
return my_state
}

pub struct State {
mut:
x int
}

fn handler(mut my_state State) {
my_state.x += 1
}

fn test_main() {
mut state := State{}
state = higher_order_fn[State](state, ?MyFn[State](handler))
state = higher_order_fn[State](state, ?MyFn[State](none))
state = higher_order_fn[State](state, handler)
assert state.x == 4
}

0 comments on commit 149cbba

Please sign in to comment.