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

checker: disallow unwrapped option/result with in operator (#17875)

This commit is contained in:
Swastik Baranwal 2023-04-05 13:50:42 +05:30 committed by GitHub
parent fc4c431d83
commit d30e1a52e2
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 55 additions and 0 deletions

View File

@ -195,6 +195,18 @@ fn (mut c Checker) infix_expr(mut node ast.InfixExpr) ast.Type {
node.pos)
}
}
if mut node.left is ast.CallExpr {
if node.left.return_type.has_flag(.option)
|| node.left.return_type.has_flag(.result) {
option_or_result := if node.left.return_type.has_flag(.option) {
'option'
} else {
'result'
}
c.error('unwrapped ${option_or_result} cannot be used with `${node.op.str()}`',
left_pos)
}
}
node.promoted_type = ast.bool_type
return ast.bool_type
}

View File

@ -0,0 +1,28 @@
vlib/v/checker/tests/unwrapped_option_result_in_operation_err.vv:3:6: error: unwrapped result cannot be used with `!in`
1 | fn main() {
2 | list := ['string']
3 | _ = return_string_or_error() !in list
| ~~~~~~~~~~~~~~~~~~~~~~~~
4 | _ = return_string_or_error() in list
5 | _ = return_string_or_none() in list
vlib/v/checker/tests/unwrapped_option_result_in_operation_err.vv:4:6: error: unwrapped result cannot be used with `in`
2 | list := ['string']
3 | _ = return_string_or_error() !in list
4 | _ = return_string_or_error() in list
| ~~~~~~~~~~~~~~~~~~~~~~~~
5 | _ = return_string_or_none() in list
6 | _ = return_string_or_error() !in list
vlib/v/checker/tests/unwrapped_option_result_in_operation_err.vv:5:6: error: unwrapped option cannot be used with `in`
3 | _ = return_string_or_error() !in list
4 | _ = return_string_or_error() in list
5 | _ = return_string_or_none() in list
| ~~~~~~~~~~~~~~~~~~~~~~~
6 | _ = return_string_or_error() !in list
7 | }
vlib/v/checker/tests/unwrapped_option_result_in_operation_err.vv:6:6: error: unwrapped result cannot be used with `!in`
4 | _ = return_string_or_error() in list
5 | _ = return_string_or_none() in list
6 | _ = return_string_or_error() !in list
| ~~~~~~~~~~~~~~~~~~~~~~~~
7 | }
8 |

View File

@ -0,0 +1,15 @@
fn main() {
list := ['string']
_ = return_string_or_error() !in list
_ = return_string_or_error() in list
_ = return_string_or_none() in list
_ = return_string_or_error() !in list
}
fn return_string_or_error() !string {
return ''
}
fn return_string_or_none() ?string {
return ''
}