Skip to content

Commit

Permalink
checker: check if unwrapped m[key] if m is Option
Browse files Browse the repository at this point in the history
  • Loading branch information
Delta456 committed Jan 14, 2025
1 parent a5f3b4a commit 29ce5b8
Show file tree
Hide file tree
Showing 4 changed files with 24 additions and 0 deletions.
3 changes: 3 additions & 0 deletions vlib/v/checker/checker.v
Original file line number Diff line number Diff line change
Expand Up @@ -4914,6 +4914,9 @@ fn (mut c Checker) index_expr(mut node ast.IndexExpr) ast.Type {
} 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}`',
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 `struct.var?[]` to do it',
node.left.pos())
}
} else if typ.has_flag(.result) {
c.error('type `!${typ_sym.name}` is a Result, it does not support indexing', node.left.pos())
Expand Down
6 changes: 6 additions & 0 deletions vlib/v/checker/tests/option_map_err.out
Original file line number Diff line number Diff line change
@@ -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 `struct.var?[]` 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
20 | }
21 | }
Expand Down
6 changes: 6 additions & 0 deletions vlib/v/checker/tests/selector_expr_opt_map_get_err.out
Original file line number Diff line number Diff line change
@@ -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 `struct.var?[]` to do it
6 | fn main() {
7 | x := Abc{}
8 | _ := x.m['test'] or { 'test' }
| ^
9 | }
9 changes: 9 additions & 0 deletions vlib/v/checker/tests/selector_expr_opt_map_get_err.vv
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
struct Abc {
mut:
m ?map[string]string
}

fn main() {
x := Abc{}
_ := x.m['test'] or { 'test' }
}

0 comments on commit 29ce5b8

Please sign in to comment.