From e01d973c27a27a1cf5daf62e0e05fe5928a7b33c Mon Sep 17 00:00:00 2001 From: phoebe Date: Mon, 3 Jul 2023 07:01:34 +0200 Subject: [PATCH] checker: fix comptime "ident is type" (#18747) --- vlib/v/checker/if.v | 7 ++++++ .../tests/run/comptime_ident_is_type.run.out | 6 +++++ .../tests/run/comptime_ident_is_type.vv | 22 +++++++++++++++++++ 3 files changed, 35 insertions(+) create mode 100644 vlib/v/checker/tests/run/comptime_ident_is_type.run.out create mode 100644 vlib/v/checker/tests/run/comptime_ident_is_type.vv diff --git a/vlib/v/checker/if.v b/vlib/v/checker/if.v index ea40f4139da4f5..b5faad869934e1 100644 --- a/vlib/v/checker/if.v +++ b/vlib/v/checker/if.v @@ -161,6 +161,13 @@ fn (mut c Checker) if_expr(mut node ast.IfExpr) ast.Type { is_comptime_type_is_expr = true left_type := c.unwrap_generic(left.typ) skip_state = c.check_compatible_types(left_type, right as ast.TypeNode) + } else if left is ast.Ident { + is_comptime_type_is_expr = true + mut checked_type := ast.void_type + if var := left.scope.find_var(left.name) { + checked_type = c.unwrap_generic(var.typ) + } + skip_state = c.check_compatible_types(checked_type, right as ast.TypeNode) } } } else if branch.cond.op in [.eq, .ne] { diff --git a/vlib/v/checker/tests/run/comptime_ident_is_type.run.out b/vlib/v/checker/tests/run/comptime_ident_is_type.run.out new file mode 100644 index 00000000000000..37667b9a0d1e17 --- /dev/null +++ b/vlib/v/checker/tests/run/comptime_ident_is_type.run.out @@ -0,0 +1,6 @@ +u64: true +u64 array: 0 +other array: 1 +other array: 0 +other int: false +unknown type diff --git a/vlib/v/checker/tests/run/comptime_ident_is_type.vv b/vlib/v/checker/tests/run/comptime_ident_is_type.vv new file mode 100644 index 00000000000000..bde92665dd01f4 --- /dev/null +++ b/vlib/v/checker/tests/run/comptime_ident_is_type.vv @@ -0,0 +1,22 @@ +fn test[T](val T) { + $if val is u64 { + println('u64: ${val == u64(0)}') + } $else $if val is []u64 { + println('u64 array: ${val.len}') + } $else $if val is $int { + println('other int: ${val == 0}') + } $else $if val is $array { + println('other array: ${val.len}') + } $else { + println('unknown type') + } +} + +fn main() { + test(u64(0)) + test([]u64{}) + test(['string']) + test([]u32{}) + test(int(12)) + test('string') +}