v2 / vlib / v / tests / comptime / comptime_call_method_closure_test.v
73 lines · 61 sloc · 1.23 KB · 617adaf0d6d80cc250cce9b509880da481d70884
Raw
1struct Foo {}
2
3fn (f Foo) foo() string {
4 return 'foo'
5}
6
7fn (f Foo) bar() string {
8 return 'bar'
9}
10
11struct NamedFoo {
12 name string
13}
14
15fn (f NamedFoo) foo() string {
16 return 'foo ${f.name}'
17}
18
19fn (f NamedFoo) bar() string {
20 return 'bar ${f.name}'
21}
22
23fn test_main() {
24 f := Foo{}
25 mut results := []string{}
26 $for method in Foo.methods {
27 x := fn [method, f] () string {
28 return f.$method()
29 }
30 results << x()
31 }
32 assert results[0] == 'foo'
33 assert results[1] == 'bar'
34}
35
36fn test_comptime_method_value() {
37 f := NamedFoo{'rabbit'}
38 mut results := []string{}
39 $for method in NamedFoo.methods {
40 x := f.$(method)
41 results << x()
42 }
43 assert results[0] == 'foo rabbit'
44 assert results[1] == 'bar rabbit'
45}
46
47@[heap]
48struct MethodMapApp {
49 prefix string
50}
51
52fn (app &MethodMapApp) alpha() string {
53 return '${app.prefix}:alpha'
54}
55
56fn (app &MethodMapApp) beta() string {
57 return '${app.prefix}:beta'
58}
59
60fn build_method_map[T](app &T) map[string]fn () string {
61 mut syms := map[string]fn () string{}
62 $for method in T.methods {
63 syms[method.name] = app.$(method.name)
64 }
65 return syms
66}
67
68fn test_comptime_method_value_map() {
69 app := MethodMapApp{'ctx'}
70 syms := build_method_map(app)
71 assert syms['alpha']() == 'ctx:alpha'
72 assert syms['beta']() == 'ctx:beta'
73}
74