Skip to content

Commit

Permalink
checker: fix .variant smartcast on non-comptime variables (#20575)
Browse files Browse the repository at this point in the history
  • Loading branch information
felipensp committed Jan 20, 2024
1 parent 6107e0d commit 9092d7f
Show file tree
Hide file tree
Showing 5 changed files with 44 additions and 12 deletions.
2 changes: 1 addition & 1 deletion vlib/v/checker/checker.v
Expand Up @@ -3884,7 +3884,7 @@ fn (mut c Checker) smartcast(mut expr ast.Expr, cur_type ast.Type, to_type_ ast.
orig_type = expr.obj.typ
}
is_inherited = expr.obj.is_inherited
ct_type_var = if is_comptime && expr.obj.ct_type_var != .no_comptime {
ct_type_var = if is_comptime {
.smartcast
} else {
.no_comptime
Expand Down
12 changes: 8 additions & 4 deletions vlib/v/debug/tests/comptime_variant.expect
@@ -1,9 +1,13 @@
#!/usr/bin/env expect
source "common.tcl"

expect "Break on * comptime_variant_int in ${test_file}:7"
expect "${test_file}:7 vdbg> "
send "p a\n"
expect "a = 0 (int)"
expect "Break on * comptime_variant in ${test_file}:6"
expect "${test_file}:6 vdbg> "
send "p arg\n"
expect "arg = 0 (int)"
send "c\n"
expect "${test_file}:6 vdbg> "
send "p arg\n"
expect "arg = foo (string)"
send "q\n"
expect eof
12 changes: 6 additions & 6 deletions vlib/v/debug/tests/comptime_variant.vv
@@ -1,15 +1,15 @@
type MySum = int | string

fn comptime_variant_int() {
a := MySum(int(0))
$for v in MySum.variants {
if a is v {
fn comptime_variant(arg MySum) {
$for v in arg.variants {
if arg is v {
$dbg;
dump(a)
dump(arg)
}
}
}

fn main() {
comptime_variant_int()
comptime_variant(MySum(int(0)))
comptime_variant(MySum('foo'))
}
8 changes: 7 additions & 1 deletion vlib/v/gen/c/cgen.v
Expand Up @@ -3937,7 +3937,13 @@ fn (mut g Gen) debugger_stmt(node ast.DebuggerStmt) {
if obj.name !in vars {
if obj is ast.Var && obj.pos.pos < node.pos.pos {
keys.write_string('_SLIT("${obj.name}")')
var_typ := if obj.smartcasts.len > 0 { obj.smartcasts.last() } else { obj.typ }
var_typ := if obj.ct_type_var != .no_comptime {
g.comptime.get_comptime_var_type(ast.Ident{ obj: obj })
} else if obj.smartcasts.len > 0 {
obj.smartcasts.last()
} else {
obj.typ
}
values.write_string('{.typ=_SLIT("${g.table.type_to_str(g.unwrap_generic(var_typ))}"),.value=')
obj_sym := g.table.sym(obj.typ)
cast_sym := g.table.sym(var_typ)
Expand Down
22 changes: 22 additions & 0 deletions vlib/v/tests/comptime_smartcast_var_test.v
@@ -0,0 +1,22 @@
type TestSum = bool | f64 | int | string

fn test_main() {
a := TestSum(true)
$for v in TestSum.variants {
if a is v {
$if a is bool {
assert a == true
}
$if a is string {
assert a == ''
}
$if a is f64 {
assert a == 0
}
$if a is int {
assert a == 0
}
}
}
assert true
}

0 comments on commit 9092d7f

Please sign in to comment.