1 /*
2 A method expression is a value, run rather than described.
3 4 `(*T).M` names the method as a plain function whose first parameter is the
5 receiver, and storing it in a field is how compress/flate keeps its fill and
6 step functions (d.fill = (*compressor).fillDeflate, d.step = (*compressor).deflate).
7 stage4 built the operand `(*T)` as an expression, got nothing, and left a NIL
8 function value in the field - so `d.step(d)` called through a nil pointer and
9 flate/flate->zlib->png died with SIGSEGV the first time any of it ran. legacy
10 built it correctly, which is why the shape was in the tree at all.
11 12 The fixture pins the value, the call through a struct field, a method with a
13 result, and a method with no result: the nil was silent, so the only test that
14 catches it is one that calls the value.
15 */
16 package main
17 18 type Counter struct {
19 step func(*Counter)
20 fill func(*Counter, int32)
21 n int32
22 }
23 24 func (c *Counter) bump() {
25 c.n++
26 }
27 28 func (c *Counter) add(k int32) {
29 c.n += k
30 }
31 32 func (c *Counter) twice(x int32) (out int32) {
33 return x * 2
34 }
35 36 type Box struct {
37 mul func(*Counter, int32) int32
38 }
39 40 func main() {
41 // Termination: a batch program must still be stoppable, so the entry
42 // handles the channel the runtime closes on SIGINT/SIGTERM.
43 select {
44 case <-shutdown:
45 return
46 default:
47 }
48 49 c := &Counter{}
50 c.step = (*Counter).bump
51 c.fill = (*Counter).add
52 if c.step == nil || c.fill == nil {
53 panic("method expression evaluated to a nil function value")
54 }
55 c.step(c)
56 c.step(c)
57 if c.n != 2 {
58 panic("call through a method expression did not reach the method")
59 }
60 c.fill(c, 40)
61 if c.n != 42 {
62 panic("method expression with a parameter did not pass it")
63 }
64 b := &Box{mul: (*Counter).twice}
65 if b.mul(c, 21) != 42 {
66 panic("method expression with a result is wrong")
67 }
68 println("method expressions ok")
69 }
70