From c9ecc5b0ddd6258f9aa35b23f07b98c4112df49b Mon Sep 17 00:00:00 2001 From: Felipe Pena Date: Sun, 10 Nov 2024 15:15:01 -0300 Subject: [PATCH] v: add `typeof(expr).unaliased_typ` (#22806) --- vlib/v/checker/checker.v | 2 +- vlib/v/gen/c/cgen.v | 8 ++++++++ vlib/v/tests/typeof_unaliased_typ_test.v | 20 ++++++++++++++++++++ 3 files changed, 29 insertions(+), 1 deletion(-) create mode 100644 vlib/v/tests/typeof_unaliased_typ_test.v diff --git a/vlib/v/checker/checker.v b/vlib/v/checker/checker.v index 573628446a..4d935fca58 100644 --- a/vlib/v/checker/checker.v +++ b/vlib/v/checker/checker.v @@ -1537,7 +1537,7 @@ fn (mut c Checker) selector_expr(mut node ast.SelectorExpr) ast.Type { else { if node.field_name == 'name' { return ast.string_type - } else if node.field_name == 'idx' { + } else if node.field_name in ['idx', 'unaliased_typ'] { return ast.int_type } else if node.field_name == 'indirections' { return ast.int_type diff --git a/vlib/v/gen/c/cgen.v b/vlib/v/gen/c/cgen.v index 05d7b0c8b7..59a50eb67c 100644 --- a/vlib/v/gen/c/cgen.v +++ b/vlib/v/gen/c/cgen.v @@ -3897,6 +3897,14 @@ fn (mut g Gen) selector_expr(node ast.SelectorExpr) { // `typeof(expr).idx` g.write(int(g.unwrap_generic(name_type)).str()) return + } else if node.field_name == 'unaliased_typ' { + mut name_type := node.name_type + if node.expr is ast.TypeOf { + name_type = g.resolve_comptime_type(node.expr.expr, name_type) + } + // `typeof(expr).unaliased_typ` + g.write(int(g.table.unaliased_type(g.unwrap_generic(name_type))).str()) + return } else if node.field_name == 'indirections' { mut name_type := node.name_type if node.expr is ast.TypeOf { diff --git a/vlib/v/tests/typeof_unaliased_typ_test.v b/vlib/v/tests/typeof_unaliased_typ_test.v new file mode 100644 index 0000000000..b964dd30b8 --- /dev/null +++ b/vlib/v/tests/typeof_unaliased_typ_test.v @@ -0,0 +1,20 @@ +struct Foo { + a int +} + +type Bar = Foo + +type ArrBar = []Bar + +fn test_main() { + assert typeof[Bar]().unaliased_typ == typeof[Foo]().unaliased_typ + assert typeof[int]().unaliased_typ != typeof[Foo]().unaliased_typ + assert typeof[int]().unaliased_typ == typeof[int]().unaliased_typ + assert typeof[ArrBar]().unaliased_typ == typeof[[]Bar]().idx + + a := Bar{} + assert typeof(a).unaliased_typ == typeof[Foo]().idx + + b := ArrBar{} + assert typeof(b).unaliased_typ == typeof[[]Bar]().idx +}