1
0
mirror of https://github.com/golang/go synced 2024-11-19 00:44:40 -07:00
go/ssa/interp/testdata/boundmeth.go
Alan Donovan 8cdf1f1cb1 go.tools/ssa: add support for bound-method closures.
Extracted Builder.findMethod function to handle
methodset/receiver logic common to
function calls (Builder.setCall) and
bound method closure creation (Builder.selector).

Capture: added explicit Name, Type fields to Capture instead
of relying on Outer field, which is now un-exported since its
only purpose is to let Builder.expr(case *ast.FuncLit) know
which values to put in the closure; it is nilled immediately
after.

Simplified Function.lookup() logic: there's no need to walk
the Outer chain each time to set Alloc.Heap=true, as it's
already set during creation of the outermost
Capture{outer:*Alloc}.

Added interp/testdata/boundmeth.go test.

Cosmetic changes:
- add support for bound method thunks to Function.FullName().
- Simplified {Literal,Global,Builtin,Function}.String()
- doc: Captures are no longer necessarily addresses.
- added yet another missing pair of "()" (go/types accessors).
- print "Synthetic" not "Declared at -" for synthetic functions.
- use '$' not center-dot in synthetic identifiers (easier to type).

R=gri
CC=golang-dev
https://golang.org/cl/9654043
2013-05-22 17:56:18 -04:00

89 lines
1.1 KiB
Go

// Tests of bound method closures.
package main
func assert(b bool) {
if !b {
panic("oops")
}
}
type I int
func (i I) add(x int) int {
return int(i) + x
}
func valueReceiver() {
var three I = 3
assert(three.add(5) == 8)
var add3 func(int) int = three.add
assert(add3(5) == 8)
}
type S struct{ x int }
func (s *S) incr() {
s.x++
}
func (s *S) get() int {
return s.x
}
func pointerReceiver() {
ps := new(S)
incr := ps.incr
get := ps.get
assert(get() == 0)
incr()
incr()
incr()
assert(get() == 3)
}
func addressibleValuePointerReceiver() {
var s S
incr := s.incr
get := s.get
assert(get() == 0)
incr()
incr()
incr()
assert(get() == 3)
}
type S2 struct {
S
}
func promotedReceiver() {
var s2 S2
incr := s2.incr
get := s2.get
assert(get() == 0)
incr()
incr()
incr()
assert(get() == 3)
}
func anonStruct() {
var s struct{ S }
incr := s.incr
get := s.get
assert(get() == 0)
incr()
incr()
incr()
assert(get() == 3)
}
func main() {
valueReceiver()
pointerReceiver()
addressibleValuePointerReceiver()
promotedReceiver()
anonStruct()
}