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

v: allow none for not first values on map initialization (#18821)

This commit is contained in:
Felipe Pena 2023-07-09 09:41:24 -03:00 committed by GitHub
parent 8f3a1751e3
commit 59eb76c81d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
5 changed files with 75 additions and 1 deletions

View File

@ -409,6 +409,11 @@ fn (mut c Checker) map_init(mut node ast.MapInit) ast.Type {
expecting_interface_map := map_value_sym.kind == .interface_
//
mut same_key_type := true
if node.keys.len == 1 && val0_type == ast.none_type {
c.error('map value cannot be only `none`', node.vals[0].pos())
}
for i, mut key in node.keys {
if i == 0 && !use_expected_type {
continue
@ -445,6 +450,9 @@ fn (mut c Checker) map_init(mut node ast.MapInit) ast.Type {
c.error('invalid map value: ${msg}', val.pos())
}
}
if val_type == ast.none_type && val0_type.has_flag(.option) {
continue
}
if !c.check_types(val_type, val0_type)
|| val0_type.has_flag(.option) != val_type.has_flag(.option)
|| (i == 0 && val_type.is_number() && val0_type.is_number()

View File

@ -0,0 +1,34 @@
vlib/v/checker/tests/map_with_none_err.vv:2:6: warning: unused variable: `a`
1 | fn main() {
2 | mut a := {
| ^
3 | 'bar': none
4 | }
vlib/v/checker/tests/map_with_none_err.vv:6:6: warning: unused variable: `b`
4 | }
5 |
6 | mut b := {
| ^
7 | 'foo': 1,
8 | 'bar': none
vlib/v/checker/tests/map_with_none_err.vv:11:6: warning: unused variable: `c`
9 | }
10 |
11 | mut c := {
| ^
12 | 'foo': ?int(none),
13 | 'bar': none
vlib/v/checker/tests/map_with_none_err.vv:3:10: error: map value cannot be only `none`
1 | fn main() {
2 | mut a := {
3 | 'bar': none
| ~~~~
4 | }
5 |
vlib/v/checker/tests/map_with_none_err.vv:8:10: error: invalid map value: expected `int`, not `none`
6 | mut b := {
7 | 'foo': 1,
8 | 'bar': none
| ~~~~
9 | }
10 |

View File

@ -0,0 +1,15 @@
fn main() {
mut a := {
'bar': none
}
mut b := {
'foo': 1,
'bar': none
}
mut c := {
'foo': ?int(none),
'bar': none
}
}

View File

@ -4018,7 +4018,7 @@ fn (mut g Gen) map_init(node ast.MapInit) {
}
if value_sym.kind == .sum_type {
g.expr_with_cast(expr, node.val_types[i], unwrap_val_typ)
} else if node.val_types[i].has_flag(.option) {
} else if node.val_types[i].has_flag(.option) || node.val_types[i] == ast.none_type {
g.expr_with_opt(expr, node.val_types[i], unwrap_val_typ)
} else {
g.expr(expr)

View File

@ -0,0 +1,17 @@
fn test_main() {
mut a := {
'foo': ?int(1)
'bar': none
}
a['foo'] = 1
assert dump(a) == a
}
fn test_none() {
mut a := {
'foo': ?int(1)
'bar': none
}
a['foo'] = none
assert dump(a) == a
}