1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00

checker: disallow matching type with primitive vars (#18084)

This commit is contained in:
Swastik Baranwal 2023-05-02 14:10:38 +05:30 committed by GitHub
parent ca2820da5f
commit c4cce3bc00
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 20 additions and 0 deletions

View File

@ -198,6 +198,10 @@ fn (mut c Checker) match_exprs(mut node ast.MatchExpr, cond_type_sym ast.TypeSym
c.error('struct instances cannot be matched by type name, they can only be matched to other instances of the same struct type', c.error('struct instances cannot be matched by type name, they can only be matched to other instances of the same struct type',
branch.pos) branch.pos)
} }
if mut expr is ast.TypeNode && cond_sym.is_primitive() {
c.error('matching by type can only be done for sum types, generics, interfaces, `${node.cond}` is none of those',
branch.pos)
}
if mut expr is ast.RangeExpr { if mut expr is ast.RangeExpr {
// Allow for `match enum_value { 4..5 { } }`, even though usually int and enum values, // Allow for `match enum_value { 4..5 { } }`, even though usually int and enum values,
// are considered incompatible outside unsafe{}, and are not allowed to be compared directly // are considered incompatible outside unsafe{}, and are not allowed to be compared directly

View File

@ -0,0 +1,7 @@
vlib/v/checker/tests/match_type_node_with_non_sum_type_err.vv:5:3: error: matching by type can only be done for sum types, generics, interfaces, `b` is none of those
3 |
4 | match b {
5 | i64 { println('i64') }
| ~~~
6 | 100 { println(100) }
7 | else {}

View File

@ -0,0 +1,9 @@
fn main() {
b := i64(100)
match b {
i64 { println('i64') }
100 { println(100) }
else {}
}
}