v2 / vlib / v / tests / comptime / comptime_variant_test.v
47 lines · 41 sloc · 843 bytes · 439eceb5ce67003141d2d2be84adb01659380f59
Raw
1type TestSum = int | string
2
3fn gen[T](val T) {
4 $if val is $sumtype {
5 $for f in T.variants {
6 dump(f)
7 dump(f.typ)
8 $if f.typ is $int {
9 dump('is int')
10 assert f.typ == typeof[int]().idx
11 } $else $if f.typ is string {
12 dump('is string')
13 assert f.typ == typeof[string]().idx
14 }
15 }
16 }
17}
18
19fn test_main() {
20 a := TestSum(123)
21 gen(a)
22}
23
24type FieldVariantsMixed = []bool | []int | []string | string
25
26struct FieldVariantsHolder {
27mut:
28 t FieldVariantsMixed
29}
30
31fn enumerate_sumtype_field_variants[T]() int {
32 mut count := 0
33 $for field in T.fields {
34 $if field.typ is $sumtype {
35 $for variant in field.typ.variants {
36 if typeof(variant.typ).name != '' {
37 count++
38 }
39 }
40 }
41 }
42 return count
43}
44
45fn test_comptime_for_field_typ_variants() {
46 assert enumerate_sumtype_field_variants[FieldVariantsHolder]() == 4
47}
48