From 7cff7fb8282f34fa8d8469175d360f24372992bd Mon Sep 17 00:00:00 2001 From: shove Date: Tue, 13 Sep 2022 15:19:58 +0800 Subject: [PATCH] cgen: fix `f as Fun`, where f is `type Expr = Fun | int`, and `struct Fun { f fn (int) int }`. (fix #15730) (#15744) --- vlib/v/gen/c/fn.v | 11 ++++++++++- .../tests/sumtype_with_struct_fn_field_call_test.v | 13 +++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) create mode 100644 vlib/v/tests/sumtype_with_struct_fn_field_call_test.v diff --git a/vlib/v/gen/c/fn.v b/vlib/v/gen/c/fn.v index e59009ec01..55e2f8776e 100644 --- a/vlib/v/gen/c/fn.v +++ b/vlib/v/gen/c/fn.v @@ -1342,7 +1342,16 @@ fn (mut g Gen) fn_call(node ast.CallExpr) { if obj := node.scope.find(node.name) { match obj { ast.Var { - if obj.smartcasts.len > 0 { + // Temp fix generate call fn error when the struct type of sumtype + // has the fn field and is same to the struct name. + mut is_need_cast := true + if node.left_type != 0 { + left_sym := g.table.sym(node.left_type) + if left_sym.kind == .struct_ && node.name == obj.name { + is_need_cast = false + } + } + if obj.smartcasts.len > 0 && is_need_cast { for _ in obj.smartcasts { g.write('(*') } diff --git a/vlib/v/tests/sumtype_with_struct_fn_field_call_test.v b/vlib/v/tests/sumtype_with_struct_fn_field_call_test.v new file mode 100644 index 0000000000..4d8b39ff40 --- /dev/null +++ b/vlib/v/tests/sumtype_with_struct_fn_field_call_test.v @@ -0,0 +1,13 @@ +type Expr = Fun | int + +struct Fun { + f fn (int) int +} + +fn test_sumtype_with_struct_fn_field_call() { + f := Expr(0) + if f is Fun { + println((f as Fun).f(0)) + } + assert true +}