Skip to content

Commit

Permalink
parser: give a friendly error when misusing if over $if (#19810)
Browse files Browse the repository at this point in the history
  • Loading branch information
Delta456 authored Nov 9, 2023
1 parent 97f7c3f commit 2b21dea
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 0 deletions.
12 changes: 12 additions & 0 deletions vlib/v/parser/if_match.v
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ fn (mut p Parser) if_expr(is_comptime bool) ast.IfExpr {
p.check(.dollar)
}
}
if_pos := p.tok.pos()
// `if` or `else if`
p.check(.key_if)
if p.tok.kind == .key_match {
Expand Down Expand Up @@ -139,6 +140,17 @@ fn (mut p Parser) if_expr(is_comptime bool) ast.IfExpr {
p.comptime_if_cond = true
p.inside_if_cond = true
cond = p.expr(0)
if mut cond is ast.InfixExpr && !is_comptime {
if cond.op in [.key_is, .not_is] {
if mut cond.left is ast.Ident {
if cond.left.name.len == 1 && cond.left.name.is_capital()
&& cond.right is ast.TypeNode {
p.error_with_pos('use `\$if` instead of `if`', if_pos)
return ast.IfExpr{}
}
}
}
}
p.inside_if_cond = false
if p.if_cond_comments.len > 0 {
comments << p.if_cond_comments
Expand Down
7 changes: 7 additions & 0 deletions vlib/v/parser/tests/not_using_if_comptime_in_comptime_err.out
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
vlib/v/parser/tests/not_using_if_comptime_in_comptime_err.vv:10:2: error: use `$if` instead of `if`
8 |
9 | fn check[T]() bool {
10 | if T is Checkable {
| ~~
11 | return true
12 | } else {
17 changes: 17 additions & 0 deletions vlib/v/parser/tests/not_using_if_comptime_in_comptime_err.vv
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
interface Checkable {
test int
}

struct Test {
test int
}

fn check[T]() bool {
if T is Checkable {
return true
} else {
return false
}
}

println(check[Test]())

0 comments on commit 2b21dea

Please sign in to comment.