From d632e840907dfe3155ec95c2a846319efd6a50fb Mon Sep 17 00:00:00 2001 From: shove Date: Thu, 24 Nov 2022 00:08:49 +0800 Subject: [PATCH] cgen: fix comptime optional methods call and optional field (fix #16499 #16465) (#16503) --- vlib/v/gen/c/assign.v | 5 ++-- vlib/v/gen/c/comptime.v | 7 +++++ .../gen/c/testdata/comptime_optional_call.out | 10 +++++++ .../gen/c/testdata/comptime_optional_call.vv | 28 +++++++++++++++++++ 4 files changed, 48 insertions(+), 2 deletions(-) create mode 100644 vlib/v/gen/c/testdata/comptime_optional_call.out create mode 100644 vlib/v/gen/c/testdata/comptime_optional_call.vv diff --git a/vlib/v/gen/c/assign.v b/vlib/v/gen/c/assign.v index 579a44922a..6240296d89 100644 --- a/vlib/v/gen/c/assign.v +++ b/vlib/v/gen/c/assign.v @@ -434,8 +434,9 @@ fn (mut g Gen) assign_stmt(node_ ast.AssignStmt) { */ } if !cloned { - if (var_type.has_flag(.optional) && !val_type.has_flag(.optional)) - || (var_type.has_flag(.result) && !val_type.has_flag(.result)) { + if !g.inside_comptime_for_field + && ((var_type.has_flag(.optional) && !val_type.has_flag(.optional)) + || (var_type.has_flag(.result) && !val_type.has_flag(.result))) { tmp_var := g.new_tmp_var() g.expr_with_tmp_var(val, val_type, var_type, tmp_var) } else if is_fixed_array_var { diff --git a/vlib/v/gen/c/comptime.v b/vlib/v/gen/c/comptime.v index 9e4eeff684..71ba57d60d 100644 --- a/vlib/v/gen/c/comptime.v +++ b/vlib/v/gen/c/comptime.v @@ -121,6 +121,10 @@ fn (mut g Gen) comptime_call(mut node ast.ComptimeCall) { } return } + + if !g.inside_call && (m.return_type.has_flag(.optional) || m.return_type.has_flag(.result)) { + g.write('(*(${g.base_type(m.return_type)}*)') + } // TODO: check argument types g.write('${util.no_dots(sym.name)}_${g.comptime_for_method}(') @@ -165,6 +169,9 @@ fn (mut g Gen) comptime_call(mut node ast.ComptimeCall) { } } g.write(')') + if !g.inside_call && (m.return_type.has_flag(.optional) || m.return_type.has_flag(.result)) { + g.write('.data)') + } return } mut j := 0 diff --git a/vlib/v/gen/c/testdata/comptime_optional_call.out b/vlib/v/gen/c/testdata/comptime_optional_call.out new file mode 100644 index 0000000000..10bbd90bc9 --- /dev/null +++ b/vlib/v/gen/c/testdata/comptime_optional_call.out @@ -0,0 +1,10 @@ +0 +0 +Option(0) +Option(0) +Option(error: none) +Option(error: none) +1 +1 +println(NIL) +Option(error: none) diff --git a/vlib/v/gen/c/testdata/comptime_optional_call.vv b/vlib/v/gen/c/testdata/comptime_optional_call.vv new file mode 100644 index 0000000000..4476afa5c5 --- /dev/null +++ b/vlib/v/gen/c/testdata/comptime_optional_call.vv @@ -0,0 +1,28 @@ +struct Foo { + foobar int + bar ?int + baz ?int = none +} + +fn (f Foo) bar() int { + return 1 +} + +fn (f Foo) baz() ?string { + return none +} + +fn main() { + foo := Foo{} + + $for field in Foo.fields { + var := foo.$(field.name) + println(var) + println(foo.$(field.name)) + } + $for method in Foo.methods { + var := foo.$method() + println(var) + println(foo.$method()) + } +}