From 8a1e90fff1b33b8f9fffe54b1e0db8f2da6997bc Mon Sep 17 00:00:00 2001 From: Felipe Pena Date: Sun, 19 Feb 2023 13:56:14 -0300 Subject: [PATCH] checker: allow `none` to be casted to all option types, including aliases (#17348) --- vlib/v/checker/checker.v | 4 ++- vlib/v/tests/cast_none_to_option_test.v | 38 +++++++++++++++++++++++++ 2 files changed, 41 insertions(+), 1 deletion(-) create mode 100644 vlib/v/tests/cast_none_to_option_test.v diff --git a/vlib/v/checker/checker.v b/vlib/v/checker/checker.v index d5ff9b21cb..c3674b2c44 100644 --- a/vlib/v/checker/checker.v +++ b/vlib/v/checker/checker.v @@ -2755,7 +2755,9 @@ fn (mut c Checker) cast_expr(mut node ast.CastExpr) ast.Type { if from_type == ast.void_type { c.error('expression does not return a value so it cannot be cast', node.expr.pos()) } - if to_sym.kind == .sum_type { + if to_type.has_flag(.option) && from_type == ast.none_type { + // allow conversion from none to every option type + } else if to_sym.kind == .sum_type { if from_type in [ast.int_literal_type, ast.float_literal_type] { xx := if from_type == ast.int_literal_type { ast.int_type } else { ast.f64_type } node.expr_type = c.promote_num(node.expr_type, xx) diff --git a/vlib/v/tests/cast_none_to_option_test.v b/vlib/v/tests/cast_none_to_option_test.v new file mode 100644 index 0000000000..a6768315f4 --- /dev/null +++ b/vlib/v/tests/cast_none_to_option_test.v @@ -0,0 +1,38 @@ +struct Test {} + +type AliasType = Test + +type I20 = int + +type Byt = u8 + +fn test_cast_none() { + a := ?I20(none) + assert a == none + b := ?int(none) + assert b == none + c := ?i16(none) + assert c == none + d := ?u32(none) + assert d == none + e := ?u16(none) + assert e == none + f := ?u8(none) + assert f == none + g := ?Test(none) + assert g == none + h := ?AliasType(none) + assert h == none + i := ?Byt(none) + assert i == none + j := ?rune(none) + assert j == none + k := ?string(none) + assert k == none + l := ?[]Byt(none) + assert l == none + m := ?[]Test(none) + assert m == none + n := ?[]AliasType(none) + assert n == none +}