v2 / vlib / v / tests / conditions / matches / match_smartcast_test.v
163 lines · 141 sloc · 2.23 KB · 6d3fc3d1461ce249c90765d44e6baab80af6d1f9
Raw
1type Node = Expr | string
2type Expr = IfExpr | IntegerLiteral
3
4struct IntegerLiteral {}
5
6struct IfExpr {
7 pos int
8}
9
10struct NodeWrapper {
11 node Node
12}
13
14fn test_nested_sumtype_match_selector() {
15 c := NodeWrapper{Node(Expr(IfExpr{
16 pos: 1
17 }))}
18 match c.node {
19 Expr {
20 match c.node {
21 IfExpr {
22 assert c.node.pos == 1
23 }
24 else {
25 assert false
26 }
27 }
28 }
29 else {
30 assert false
31 }
32 }
33}
34
35fn test_nested_sumtype_match() {
36 c := Node(Expr(IfExpr{
37 pos: 1
38 }))
39 match c {
40 Expr {
41 match c {
42 IfExpr {
43 assert c.pos == 1
44 }
45 else {
46 assert false
47 }
48 }
49 }
50 else {
51 assert false
52 }
53 }
54}
55
56struct Milk {
57mut:
58 name string
59}
60
61struct Eggs {
62mut:
63 name string
64}
65
66type Food = Eggs | Milk
67
68struct FoodWrapper {
69mut:
70 food Food
71}
72
73fn test_match_mut() {
74 mut f := Food(Milk{'test'})
75 match mut f {
76 Eggs {
77 f.name = 'eggs'
78 assert f.name == 'eggs'
79 }
80 Milk {
81 f.name = 'milk'
82 assert f.name == 'milk'
83 }
84 }
85}
86
87fn test_match_mut_selector() {
88 mut f := FoodWrapper{Food(Milk{'test'})}
89 match mut f.food {
90 Eggs {
91 f.food.name = 'eggs'
92 assert f.food.name == 'eggs'
93 }
94 Milk {
95 f.food.name = 'milk'
96 assert f.food.name == 'milk'
97 }
98 }
99}
100
101// for issue 20167
102type Any_1 = f64 | int | string
103type Any_2 = int | string
104
105struct Struct {
106 field Any_2
107}
108
109fn test_branches_return_struct_field() {
110 any_2 := Struct{Any_2(42)}
111 m := {
112 'item1': Any_1('')
113 'item2': match any_2.field {
114 string { any_2.field }
115 int { any_2.field }
116 }
117 }
118 assert m['item2']! == Any_1(42)
119}
120
121struct NestedMatchA {
122 a int
123}
124
125struct NestedMatchB {
126 b int
127}
128
129struct NestedMatchC {
130 c int
131}
132
133type NestedMatchD = NestedMatchA | NestedMatchB
134type NestedMatchE = NestedMatchC | NestedMatchD
135
136fn describe_nested_match(e NestedMatchE) string {
137 return match e {
138 NestedMatchA { 'A:${e.a}' }
139 NestedMatchB { 'B:${e.b}' }
140 NestedMatchC { 'C:${e.c}' }
141 }
142}
143
144fn pass_nested_match(e NestedMatchE) NestedMatchE {
145 return e
146}
147
148fn test_nested_sumtype_leaf_match_and_argument() {
149 a := NestedMatchA{
150 a: 1
151 }
152 b := NestedMatchB{
153 b: 2
154 }
155 c := NestedMatchC{
156 c: 3
157 }
158
159 assert describe_nested_match(a) == 'A:1'
160 assert describe_nested_match(b) == 'B:2'
161 assert describe_nested_match(c) == 'C:3'
162 assert describe_nested_match(pass_nested_match(a)) == 'A:1'
163}
164