From 650114540157bcfda9be915c2c7cd451bd4c12de Mon Sep 17 00:00:00 2001 From: Felipe Pena Date: Fri, 3 Jan 2025 20:10:43 -0300 Subject: [PATCH] fix --- vlib/v/checker/checker.v | 15 +++++++++++---- vlib/v/tests/options/option_concatexpr_test.v | 6 +++--- vlib/v/tests/options/option_unwrap_as_cast_test.v | 8 ++++---- 3 files changed, 18 insertions(+), 11 deletions(-) diff --git a/vlib/v/checker/checker.v b/vlib/v/checker/checker.v index 1b0df5a3020c3d..d590855a95cfa8 100644 --- a/vlib/v/checker/checker.v +++ b/vlib/v/checker/checker.v @@ -2959,10 +2959,17 @@ pub fn (mut c Checker) expr(mut node ast.Expr) ast.Type { c.table.used_features.as_cast = true } if mut node.expr is ast.Ident { - if !node.typ.has_flag(.option) && node.expr.obj.typ.has_flag(.option) - && node.expr.or_expr.kind == .absent { - c.error('variable `${node.expr.name}` is an Option, it must be unwrapped first', - node.expr.pos) + if mut node.expr.obj is ast.Var { + ident_typ := if node.expr.obj.smartcasts.len > 0 { + node.expr.obj.smartcasts.last() + } else { + node.expr.obj.typ + } + if !node.typ.has_flag(.option) && ident_typ.has_flag(.option) + && node.expr.or_expr.kind == .absent { + c.error('variable `${node.expr.name}` is an Option, it must be unwrapped first', + node.expr.pos) + } } } if expr_type_sym.kind == .sum_type { diff --git a/vlib/v/tests/options/option_concatexpr_test.v b/vlib/v/tests/options/option_concatexpr_test.v index f8b181e073c72b..a19b1488e5b5a1 100644 --- a/vlib/v/tests/options/option_concatexpr_test.v +++ b/vlib/v/tests/options/option_concatexpr_test.v @@ -12,17 +12,17 @@ fn foo(f int) !(int, ?int) { fn test_main() { a, b := foo(-1) or { 2, 2 } - c := b as int + c := b? as int assert a == 2 assert c == 2 a2, b2 := foo(0) or { 2, 2 } - c2 := b2 as int + c2 := b2? as int assert a2 == 0 assert c2 == 0 a3, b3 := foo(1) or { 2, 2 } - c3 := b3 as int + c3 := b3? as int assert a3 == 1 assert c3 == 1 } diff --git a/vlib/v/tests/options/option_unwrap_as_cast_test.v b/vlib/v/tests/options/option_unwrap_as_cast_test.v index 6bf6879a9f74d4..a6353525655b6a 100644 --- a/vlib/v/tests/options/option_unwrap_as_cast_test.v +++ b/vlib/v/tests/options/option_unwrap_as_cast_test.v @@ -15,9 +15,9 @@ fn get_opt_int(a int) ?int { fn test_option_unwrap_as_cast() { x := get_opt(1) d := get_opt_int(12) - dump(d as int == 12) - dump('${x as string}' == 'success') + dump(d? as int == 12) + dump('${x? as string}' == 'success') - assert d as int == 12 - assert x as string == 'success' + assert d? as int == 12 + assert x? as string == 'success' }