checker: forbid optional variable (#14460)

master
Daniel Däschle 2022-05-19 15:04:44 +02:00 committed by GitHub
parent 3291c59ebf
commit a52fbc5e51
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
5 changed files with 12 additions and 29 deletions

View File

@ -2312,6 +2312,10 @@ pub fn (mut c Checker) cast_expr(mut node ast.CastExpr) ast.Type {
mut to_sym := c.table.sym(to_type) // type to be used as cast mut to_sym := c.table.sym(to_type) // type to be used as cast
mut final_to_sym := c.table.final_sym(to_type) mut final_to_sym := c.table.final_sym(to_type)
if to_type.has_flag(.optional) {
c.error('casting to optional type is forbidden', node.pos)
}
if (to_sym.is_number() && from_sym.name == 'JS.Number') if (to_sym.is_number() && from_sym.name == 'JS.Number')
|| (to_sym.is_number() && from_sym.name == 'JS.BigInt') || (to_sym.is_number() && from_sym.name == 'JS.BigInt')
|| (to_sym.is_string() && from_sym.name == 'JS.String') || (to_sym.is_string() && from_sym.name == 'JS.String')

View File

@ -0,0 +1,5 @@
vlib/v/checker/tests/optional_variable_err.vv:2:7: error: casting to optional type is forbidden
1 | fn main() {
2 | _ := ?bool(false)
| ~~~~~~~~~~~~
3 | }

View File

@ -0,0 +1,3 @@
fn main() {
_ := ?bool(false)
}

View File

@ -2243,10 +2243,6 @@ fn (mut g Gen) expr_with_cast(expr ast.Expr, got_type_raw ast.Type, expected_typ
g.write('*') g.write('*')
} }
} }
if expected_type.has_flag(.optional) && expr is ast.None {
g.gen_optional_error(expected_type, expr)
return
}
if expr is ast.IntegerLiteral { if expr is ast.IntegerLiteral {
if expected_type in [ast.u64_type, ast.u32_type, ast.u16_type] && expr.val[0] != `-` { if expected_type in [ast.u64_type, ast.u32_type, ast.u16_type] && expr.val[0] != `-` {
g.expr(expr) g.expr(expr)

View File

@ -1,25 +0,0 @@
type Foo = int | string
fn test_optional_none_assign() {
x := ?Foo(none)
// assert x.err == none
// assert !x.has_value
}
fn test_optional_none_assign_nonsumtype() {
x := ?int(none)
// assert x.err == none
// assert !x.has_value
}
// TODO: make this working next
/*
fn test_optional_value_assign() {
x := ?Foo('test')
}
fn test_optional_none_reassign() {
mut x := ?Foo('test')
x = none
}
*/