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

parser: smartcast mutable selector (#6881)

This commit is contained in:
Daniel Däschle 2020-11-19 21:05:10 +01:00 committed by GitHub
parent 2e57a1e1a6
commit 41ba942369
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
6 changed files with 59 additions and 1 deletions

View File

@ -87,8 +87,10 @@ fn (mut p Parser) if_expr(is_comptime bool) ast.IfExpr {
comments << p.eat_comments()
// `if mut name is T`
mut is_mut_name := false
if p.tok.kind == .key_mut && p.peek_tok2.kind == .key_is {
mut mut_pos := token.Position{}
if p.tok.kind == .key_mut {
is_mut_name = true
mut_pos = p.tok.position()
p.next()
comments << p.eat_comments()
}
@ -135,6 +137,11 @@ fn (mut p Parser) if_expr(is_comptime bool) ast.IfExpr {
} else {
''
}
if !is_is_cast && is_mut_name {
p.error_with_pos('remove unnecessary `mut`', mut_pos)
}
} else if is_mut_name {
p.error_with_pos('remove unnecessary `mut`', mut_pos)
}
end_pos := p.prev_tok.position()
body_pos := p.tok.position()

View File

@ -0,0 +1,7 @@
vlib/v/parser/tests/unnecessary_mut.vv:3:5: error: remove unnecessary `mut`
1 | fn main() {
2 | mut x := 0
3 | if mut x == 0 {
| ~~~
4 | println(true)
5 | }

View File

@ -0,0 +1,6 @@
fn main() {
mut x := 0
if mut x == 0 {
println(true)
}
}

View File

@ -0,0 +1,6 @@
vlib/v/parser/tests/unnecessary_mut_2.vv:2:5: error: remove unnecessary `mut`
1 | fn main() {
2 | if mut true {
| ~~~
3 | println(true)
4 | }

View File

@ -0,0 +1,5 @@
fn main() {
if mut true {
println(true)
}
}

View File

@ -357,6 +357,11 @@ mut:
__type Food = Milk | Eggs
struct FoodWrapper {
mut:
food Food
}
fn test_match_aggregate() {
f := Food(Milk{'test'})
match union f {
@ -410,6 +415,28 @@ fn test_if_not_mut() {
}
}
fn test_match_mut_selector() {
mut f := FoodWrapper{Food(Milk{'test'})}
match union mut f.food {
Eggs {
f.food.name = 'eggs'
assert f.food.name == 'eggs'
}
Milk {
f.food.name = 'milk'
assert f.food.name == 'milk'
}
}
}
fn test_if_mut_selector() {
mut f := FoodWrapper{Food(Milk{'test'})}
if mut f.food is Milk {
f.food.name = 'milk'
assert f.food.name == 'milk'
}
}
fn test_sum_type_match() {
// TODO: Remove these casts
assert is_gt_simple('3', int(2))