Skip to content

Commit 9ea3ea3

Browse files
authored
checker: check if unwrapped m[key] if m is Option (fix #23446) (#23459)
1 parent 6ab2562 commit 9ea3ea3

4 files changed

Lines changed: 24 additions & 0 deletions

File tree

‎vlib/v/checker/checker.v‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4914,6 +4914,9 @@ fn (mut c Checker) index_expr(mut node ast.IndexExpr) ast.Type {
49144914
} else if node.left is ast.CallExpr {
49154915
c.error('type `?${typ_sym.name}` is an Option, it must be unwrapped with `func()?`, or use `func() or {default}`',
49164916
node.left.pos())
4917+
} else if node.left is ast.SelectorExpr && node.left.or_block.kind == .absent {
4918+
c.error('type `?${typ_sym.name}` is an Option, it must be unwrapped first; use `${node.left}?` to do it',
4919+
node.left.pos())
49174920
}
49184921
} else if typ.has_flag(.result) {
49194922
c.error('type `!${typ_sym.name}` is a Result, it does not support indexing', node.left.pos())

‎vlib/v/checker/tests/option_map_err.out‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,9 @@
1+
vlib/v/checker/tests/option_map_err.vv:22:13: error: type `?map[string]f64` is an Option, it must be unwrapped first; use `op2.opmap?` to do it
2+
20 | }
3+
21 | }
4+
22 | assert op2.opmap['1'] == 1.0
5+
| ~~~~~
6+
23 | }
17
vlib/v/checker/tests/option_map_err.vv:22:13: error: field `opmap` is an Option, so it should have either an `or {}` block, or `?` at the end
28
20 | }
39
21 | }
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
vlib/v/checker/tests/selector_expr_opt_map_get_err.vv:8:9: error: type `?map[string]string` is an Option, it must be unwrapped first; use `x.m?` to do it
2+
6 | fn main() {
3+
7 | x := Abc{}
4+
8 | _ := x.m['test'] or { 'test' }
5+
| ^
6+
9 | }
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
struct Abc {
2+
mut:
3+
m ?map[string]string
4+
}
5+
6+
fn main() {
7+
x := Abc{}
8+
_ := x.m['test'] or { 'test' }
9+
}

0 commit comments

Comments
 (0)