checker: forbid optional variable (#14460)
parent
1c0e0ec6a1
commit
9ad7307e31
|
@ -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')
|
||||||
|
|
|
@ -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 | }
|
|
@ -0,0 +1,3 @@
|
||||||
|
fn main() {
|
||||||
|
_ := ?bool(false)
|
||||||
|
}
|
|
@ -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)
|
||||||
|
|
|
@ -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
|
|
||||||
}
|
|
||||||
*/
|
|
Loading…
Reference in New Issue