Skip to content

Commit 919c68e

Browse files
authored
comptime: fix $match with fn type (#25271)
1 parent 4ea0563 commit 919c68e

2 files changed

Lines changed: 43 additions & 4 deletions

File tree

‎vlib/v/checker/match.v‎

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -145,10 +145,18 @@ fn (mut c Checker) match_expr(mut node ast.MatchExpr) ast.Type {
145145
node.cond)
146146
c_str = '${expr} == ${c.table.type_to_str(branch_type)}'
147147
} else {
148-
// $match a { $int {}
149-
comptime_match_branch_result = c.check_compatible_types(node.cond_type,
150-
'${node.cond}', expr)
151-
c_str = '${c.table.type_to_str(node.cond_type)} == ${expr}'
148+
is_function := c.table.final_sym(node.cond_type).kind == .function
149+
if !is_function {
150+
// $match a { $int {}
151+
comptime_match_branch_result = c.check_compatible_types(node.cond_type,
152+
'${node.cond}', expr)
153+
c_str = '${c.table.type_to_str(node.cond_type)} == ${expr}'
154+
} else {
155+
// $match T { FnType {} }
156+
branch_type := c.get_expr_type(expr)
157+
comptime_match_branch_result = c.table.type_to_str(node.cond_type) == c.table.type_to_str(branch_type)
158+
c_str = '${comptime_match_branch_result} == true'
159+
}
152160
}
153161
if comptime_match_branch_result {
154162
break
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
type FN1 = fn (a int) int
2+
3+
type FN2 = fn (a int, b int) int
4+
5+
type FN3 = FN1 | FN2
6+
7+
fn invoke[T](cb T) int {
8+
$match T {
9+
FN1 {
10+
return cb(1)
11+
}
12+
FN2 {
13+
return cb(1, 2)
14+
}
15+
$else {
16+
return 0
17+
}
18+
}
19+
}
20+
21+
fn test_main() {
22+
ret1 := invoke(fn (a int) int {
23+
return a
24+
})
25+
assert ret1 == 1
26+
27+
ret2 := invoke(fn (a int, b int) int {
28+
return a + b
29+
})
30+
assert ret2 == 3
31+
}

0 commit comments

Comments
 (0)