v2 / vlib / v / tests / fns / method_call_resolve_test.v
74 lines · 65 sloc · 1.31 KB · 6488041a749df9762348d019c4223908c476f2e2
Raw
1struct Human {
2 name string
3}
4
5enum Animal {
6 dog
7 cat
8}
9
10struct Encoder {}
11
12type Entity = Animal | Human
13
14@[sumtype_to: Animal]
15fn (ent Entity) json_cast_to_animal() Animal {
16 return ent as Animal
17}
18
19@[sumtype_to: Human]
20fn (ent Entity) json_cast_to_human() Human {
21 return ent as Human
22}
23
24fn encode[T](val T) {
25 $if T is $sumtype {
26 $for method in T.methods {
27 if method.attrs.len >= 1 {
28 if method.attrs[0].contains('sumtype_to') {
29 if val.type_name() == method.attrs[0].all_after('sumtype_to:').trim_space() {
30 encode(val.$method())
31 }
32 }
33 }
34 }
35 } $else $if T is $struct {
36 assert val == Human{
37 name: 'Monke'
38 }
39 } $else $if T is $enum {
40 assert val == Animal.cat
41 }
42}
43
44fn test_func() {
45 encode(Entity(Human{'Monke'}))
46 encode(Entity(Animal.cat))
47}
48
49fn (e &Encoder) encode[T](val T) {
50 $if T is $sumtype {
51 $for method in T.methods {
52 if method.attrs.len >= 1 {
53 if method.attrs[0].contains('sumtype_to') {
54 if val.type_name() == method.attrs[0].all_after('sumtype_to:').trim_space() {
55 println(val.$method())
56 e.encode(val.$method())
57 }
58 }
59 }
60 }
61 } $else $if T is $struct {
62 assert val == Human{
63 name: 'Monke'
64 }
65 } $else $if T is $enum {
66 assert val == Animal.cat
67 }
68}
69
70fn test_method() {
71 e := Encoder{}
72 e.encode(Entity(Human{'Monke'}))
73 e.encode(Entity(Animal.cat))
74}
75