From edd07bff01c4241e1ec6c2dd40c2f5591622f108 Mon Sep 17 00:00:00 2001 From: Felipe Pena Date: Wed, 10 Jan 2024 12:40:28 -0300 Subject: [PATCH] checker: fix comptime if with comptime smartcast (#20466) --- vlib/v/checker/if.v | 3 ++ .../inout/comptime_smartcast_variant.out | 5 +++ .../inout/comptime_smartcast_variant.vv | 34 +++++++++++++++++++ 3 files changed, 42 insertions(+) create mode 100644 vlib/v/slow_tests/inout/comptime_smartcast_variant.out create mode 100644 vlib/v/slow_tests/inout/comptime_smartcast_variant.vv diff --git a/vlib/v/checker/if.v b/vlib/v/checker/if.v index 50c14dee1..af48f98f1 100644 --- a/vlib/v/checker/if.v +++ b/vlib/v/checker/if.v @@ -122,6 +122,9 @@ fn (mut c Checker) if_expr(mut node ast.IfExpr) ast.Type { is_comptime_type_is_expr = true if var := left.scope.find_var(left.name) { checked_type = c.unwrap_generic(var.typ) + if var.smartcasts.len > 0 { + checked_type = c.unwrap_generic(var.smartcasts.last()) + } } skip_state = if c.comptime.is_comptime_type(checked_type, right as ast.ComptimeType) diff --git a/vlib/v/slow_tests/inout/comptime_smartcast_variant.out b/vlib/v/slow_tests/inout/comptime_smartcast_variant.out new file mode 100644 index 000000000..81d296481 --- /dev/null +++ b/vlib/v/slow_tests/inout/comptime_smartcast_variant.out @@ -0,0 +1,5 @@ +[vlib/v/slow_tests/inout/comptime_smartcast_variant.vv:14] field_value: foo +[vlib/v/slow_tests/inout/comptime_smartcast_variant.vv:18] '$field_value is a string': foo is a string +[vlib/v/slow_tests/inout/comptime_smartcast_variant.vv:14] field_value: 1 +[vlib/v/slow_tests/inout/comptime_smartcast_variant.vv:16] '$field_value is an int': 1 is an int +[vlib/v/slow_tests/inout/comptime_smartcast_variant.vv:33] v: done diff --git a/vlib/v/slow_tests/inout/comptime_smartcast_variant.vv b/vlib/v/slow_tests/inout/comptime_smartcast_variant.vv new file mode 100644 index 000000000..a865d21a4 --- /dev/null +++ b/vlib/v/slow_tests/inout/comptime_smartcast_variant.vv @@ -0,0 +1,34 @@ +type TestSum = int | string + +struct Abc { + s TestSum + t TestSum +} + +fn get_value[T](obj T) string { + $for field in T.fields { + field_value := obj.$(field.name) + $if field_value is $sumtype { + $for field_variant in field_value.variants { + if field_value is field_variant { + dump(field_value) + $if field_value is $int { + dump('${field_value} is an int') + } $else $if field_value is $string { + dump('${field_value} is a string') + } + } + } + } + } + return 'done' +} + +fn main() { + a := Abc{ + s: TestSum('foo') + t: TestSum(1) + } + v := get_value(a) + dump(v) +} -- 2.39.5