Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

cgen, checker: allow none as arg to ?&type #21231

Merged
merged 1 commit into from
Apr 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions vlib/v/checker/check_types.v
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,7 @@ fn (mut c Checker) check_expected_call_arg(got ast.Type, expected_ ast.Type, lan
if expected.has_flag(.option) {
got_is_ptr := got.is_ptr()
|| (arg.expr is ast.Ident && (arg.expr as ast.Ident).is_mut())
|| arg.expr is ast.None
if (expected.is_ptr() && !got_is_ptr) || (!expected.is_ptr() && got.is_ptr()) {
got_typ_str, expected_typ_str := c.get_string_names_of(got, expected)
return error('cannot use `${got_typ_str}` as `${expected_typ_str}`')
Expand Down
3 changes: 3 additions & 0 deletions vlib/v/gen/c/fn.v
Original file line number Diff line number Diff line change
Expand Up @@ -2552,6 +2552,9 @@ fn (mut g Gen) ref_or_deref_arg(arg ast.CallArg, expected_type ast.Type, lang as
}
if atype.has_flag(.generic) || arg.expr is ast.StructInit {
g.write('(voidptr)&/*qq*/')
} else if arg.expr is ast.None {
g.expr_with_opt(arg.expr, arg_typ, expected_type)
return
} else {
needs_closing = true
if arg_typ_sym.kind in [.sum_type, .interface_] {
Expand Down
12 changes: 12 additions & 0 deletions vlib/v/tests/option_ptr_arg_none_test.v
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
fn takes_optional_pointer(maybe_ptr ?&int) int {
if ptr := maybe_ptr {
return *ptr
} else {
return 0
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please return (and assert) a different value. 0 is a default value for many things, and thus the test with it, is a bit less sensitive than what it could be.

}
}

fn test_main() {
val := takes_optional_pointer(none)
assert val == 0
}