checker: show available sumtype variants in match branches on typos

pull/13766/head
Delyan Angelov 2022-03-18 11:29:36 +02:00
parent 00563a130d
commit 817bedec5d
No known key found for this signature in database
GPG Key ID: 66886C0F12D595ED
5 changed files with 37 additions and 2 deletions

View File

@ -236,7 +236,11 @@ fn (mut c Checker) match_exprs(mut node ast.MatchExpr, cond_type_sym ast.TypeSym
if expr_type !in cond_type_sym.info.variants { if expr_type !in cond_type_sym.info.variants {
expr_str := c.table.type_to_str(expr_type) expr_str := c.table.type_to_str(expr_type)
expect_str := c.table.type_to_str(node.cond_type) expect_str := c.table.type_to_str(node.cond_type)
c.error('`$expect_str` has no variant `$expr_str`', expr.pos()) sumtype_variant_names := cond_type_sym.info.variants.map(c.table.type_to_str_using_aliases(it,
{}))
suggestion := util.new_suggestion(expr_str, sumtype_variant_names)
c.error(suggestion.say('`$expect_str` has no variant `$expr_str`'),
expr.pos())
} }
} else if cond_type_sym.info is ast.Alias && expr_type_sym.info is ast.Struct { } else if cond_type_sym.info is ast.Alias && expr_type_sym.info is ast.Struct {
expr_str := c.table.type_to_str(expr_type) expr_str := c.table.type_to_str(expr_type)

View File

@ -0,0 +1,5 @@
module amod
pub struct Xyz {}
pub struct Bcg {}

View File

@ -1,4 +1,5 @@
vlib/v/checker/tests/match_invalid_type.vv:5:3: error: `IoS` has no variant `byte` vlib/v/checker/tests/match_invalid_type.vv:5:3: error: `IoS` has no variant `byte`.
2 possibilities: `int`, `string`.
3 | fn sum() { 3 | fn sum() {
4 | match IoS(1) { 4 | match IoS(1) {
5 | byte { 5 | byte {

View File

@ -0,0 +1,8 @@
vlib/v/checker/tests/sumtype_has_no_variant_suggestion.vv:14:5: error: `Abc` has no variant `amod.NonExisting`.
5 possibilities: `amod.Bcg`, `amod.Xyz`, `AnotherStruct`, `Struct1`, `ThirdStruct`.
12 | a := Abc(Struct1{})
13 | match a {
14 | x.NonExisting { println('----') }
| ~~~~~~~~~~~
15 | else {}
16 | }

View File

@ -0,0 +1,17 @@
import v.checker.tests.amod as x
struct Struct1 {}
struct AnotherStruct {}
struct ThirdStruct {}
type Abc = AnotherStruct | Struct1 | ThirdStruct | x.Bcg | x.Xyz
fn main() {
a := Abc(Struct1{})
match a {
x.NonExisting { println('----') }
else {}
}
}