Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

checker: check if unwrapped m[key] if m is Option #23459

Merged
merged 4 commits into from
Jan 14, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 `${node.left}?` 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 `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
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 `x.m?` 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' }
}
Loading