Skip to content

Commit

Permalink
fix
Browse files Browse the repository at this point in the history
  • Loading branch information
felipensp committed Jan 3, 2025
1 parent 5eecd04 commit fe26aad
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 0 deletions.
8 changes: 8 additions & 0 deletions vlib/v/checker/checker.v
Original file line number Diff line number Diff line change
Expand Up @@ -1386,6 +1386,13 @@ fn (mut c Checker) check_expr_option_or_result_call(expr ast.Expr, ret_type ast.
c.check_expr_option_or_result_call(expr.expr, ret_type)
}
ast.AsCast {
if expr.expr is ast.Ident {
if !ret_type.has_flag(.option) && expr.expr.obj.typ.has_flag(.option)
&& expr.expr.or_expr.kind == .absent {
c.error('variable `${expr.expr.name}` is an Option, it must be unwrapped first',
expr.expr.pos)
}
}
c.check_expr_option_or_result_call(expr.expr, ret_type)
}
ast.ParExpr {
Expand Down Expand Up @@ -2958,6 +2965,7 @@ pub fn (mut c Checker) expr(mut node ast.Expr) ast.Type {
if !c.is_builtin_mod {
c.table.used_features.as_cast = true
}
c.check_expr_option_or_result_call(node.expr, node.typ)
if expr_type_sym.kind == .sum_type {
c.ensure_type_exists(node.typ, node.pos)
if !c.table.sumtype_has_variant(c.unwrap_generic(node.expr_type), c.unwrap_generic(node.typ),
Expand Down
5 changes: 5 additions & 0 deletions vlib/v/checker/tests/option_as_cast_err.out
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
vlib/v/checker/tests/option_as_cast_err.vv:12:9: error: variable `b` is an Option, it must be unwrapped first
10 | println(b)
11 | println(b? as int)
12 | println(b as int)
| ^
12 changes: 12 additions & 0 deletions vlib/v/checker/tests/option_as_cast_err.vv
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
type Sum = int | string

fn sum() ?Sum {
return Sum(5)
}

a := sum()?
println(a as int)
b := sum()
println(b)
println(b? as int)
println(b as int)

0 comments on commit fe26aad

Please sign in to comment.