checker: check if unwrapped m[key] if m is Option (fix #23446) (#23459)

This commit is contained in:
Swastik Baranwal 2025-01-15 03:12:00 +05:30 committed by GitHub
parent 6ab25623e3
commit 9ea3ea38e1
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
4 changed files with 24 additions and 0 deletions

View File

@ -4914,6 +4914,9 @@ fn (mut c Checker) index_expr(mut node ast.IndexExpr) ast.Type {
} else if node.left is ast.CallExpr { } else if node.left is ast.CallExpr {
c.error('type `?${typ_sym.name}` is an Option, it must be unwrapped with `func()?`, or use `func() or {default}`', c.error('type `?${typ_sym.name}` is an Option, it must be unwrapped with `func()?`, or use `func() or {default}`',
node.left.pos()) node.left.pos())
} else if node.left is ast.SelectorExpr && node.left.or_block.kind == .absent {
c.error('type `?${typ_sym.name}` is an Option, it must be unwrapped first; use `${node.left}?` to do it',
node.left.pos())
} }
} else if typ.has_flag(.result) { } else if typ.has_flag(.result) {
c.error('type `!${typ_sym.name}` is a Result, it does not support indexing', node.left.pos()) c.error('type `!${typ_sym.name}` is a Result, it does not support indexing', node.left.pos())

View File

@ -1,3 +1,9 @@
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
20 | }
21 | }
22 | assert op2.opmap['1'] == 1.0
| ~~~~~
23 | }
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 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
20 | } 20 | }
21 | } 21 | }

View File

@ -0,0 +1,6 @@
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
6 | fn main() {
7 | x := Abc{}
8 | _ := x.m['test'] or { 'test' }
| ^
9 | }

View File

@ -0,0 +1,9 @@
struct Abc {
mut:
m ?map[string]string
}
fn main() {
x := Abc{}
_ := x.m['test'] or { 'test' }
}