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

checker: add checks for optional selector_expr (#8330)

This commit is contained in:
Swastik Baranwal 2021-01-27 18:23:20 +05:30 committed by GitHub
parent 58a76344cb
commit 17921f4171
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 16 additions and 0 deletions

View File

@ -2077,6 +2077,11 @@ pub fn (mut c Checker) selector_expr(mut selector_expr ast.SelectorExpr) table.T
return table.void_type return table.void_type
} }
selector_expr.expr_type = typ selector_expr.expr_type = typ
if selector_expr.expr_type.has_flag(.optional) && !((selector_expr.expr is ast.Ident
&& (selector_expr.expr as ast.Ident).kind == .constant)) {
c.error('cannot access fields of an optional, handle the error with `or {...}` or propagate it with `?`',
selector_expr.pos)
}
field_name := selector_expr.field_name field_name := selector_expr.field_name
utyp := c.unwrap_generic(typ) utyp := c.unwrap_generic(typ)
sym := c.table.get_type_symbol(utyp) sym := c.table.get_type_symbol(utyp)

View File

@ -0,0 +1,6 @@
vlib/v/checker/tests/selector_expr_optional_err.vv:4:46: error: cannot access fields of an optional, handle the error with `or {...}` or propagate it with `?`
2 |
3 | fn main() {
4 | println(http.get('https://httpbin.org/').status_code)
| ~~~~~~~~~~~
5 | }

View File

@ -0,0 +1,5 @@
import net.http
fn main() {
println(http.get('https://httpbin.org/').status_code)
}