Skip to content

Commit 97d01a9

Browse files
authored
checker: refactor string to enum error check, handle EnumName(string_variable) too (#20210)
1 parent a8e0ced commit 97d01a9

File tree

3 files changed

+14
-3
lines changed

3 files changed

+14
-3
lines changed

vlib/v/checker/checker.v

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3318,8 +3318,8 @@ fn (mut c Checker) cast_expr(mut node ast.CastExpr) ast.Type {
33183318
}
33193319
}
33203320
}
3321-
if mut node.expr is ast.StringLiteral {
3322-
c.add_error_detail('use ${c.table.type_to_str(node.typ)}.from_string(\'${node.expr.val}\') instead')
3321+
if node.expr_type == ast.string_type_idx {
3322+
c.add_error_detail('use ${c.table.type_to_str(node.typ)}.from_string(${node.expr}) instead')
33233323
c.error('cannot cast `string` to `enum`', node.pos)
33243324
}
33253325
}

vlib/v/checker/tests/string_to_enum_cast_err.out

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,5 +3,13 @@ vlib/v/checker/tests/string_to_enum_cast_err.vv:8:7: error: cannot cast `string`
33
7 | fn main() {
44
8 | _ := Test('one')
55
| ~~~~~~~~~~~
6-
9 | }
6+
9 |
7+
10 | my_str := 'one'
78
Details: use main.Test.from_string('one') instead
9+
vlib/v/checker/tests/string_to_enum_cast_err.vv:11:7: error: cannot cast `string` to `enum`
10+
9 |
11+
10 | my_str := 'one'
12+
11 | _ := Test(my_str)
13+
| ~~~~~~~~~~~~
14+
12 | }
15+
Details: use main.Test.from_string(my_str) instead

vlib/v/checker/tests/string_to_enum_cast_err.vv

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,4 +6,7 @@ enum Test {
66

77
fn main() {
88
_ := Test('one')
9+
10+
my_str := 'one'
11+
_ := Test(my_str)
912
}

0 commit comments

Comments
 (0)