Skip to content

Commit acd9977

Browse files
authored
Merge pull request #503 from xushiwei/q
cb.ConvertToClosure
2 parents 910138a + 9e47cb0 commit acd9977

2 files changed

Lines changed: 27 additions & 0 deletions

File tree

codebuild.go

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -620,6 +620,18 @@ func (p *CodeBuilder) NewClosureWith(sig *types.Signature) *Func {
620620
return p.pkg.newClosure(sig)
621621
}
622622

623+
// ConvertToClosure converts an expression into a closure.
624+
func (p *CodeBuilder) ConvertToClosure() *CodeBuilder {
625+
pkg := p.pkg
626+
e := p.stk.Pop()
627+
ret := pkg.NewParam(token.NoPos, "", types.Default(e.Type))
628+
p.NewClosure(nil, types.NewTuple(ret), false).BodyStart(pkg)
629+
p.emitStmt(&ast.ReturnStmt{
630+
Results: []ast.Expr{e.Val},
631+
})
632+
return p.End()
633+
}
634+
623635
// NewType func
624636
func (p *CodeBuilder) NewType(name string, src ...ast.Node) *TypeDecl {
625637
return p.NewTypeDefs().NewType(name, src...)

gop_test.go

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,21 @@ func newGopMainPackage() *gogen.Package {
5757

5858
// ----------------------------------------------------------------------------
5959

60+
func TestConvertToClosure(t *testing.T) {
61+
pkg := newMainPackage()
62+
pkg.NewFunc(nil, "main", nil, nil, false).BodyStart(pkg).
63+
DefineVarStart(0, "x").Val(1).ConvertToClosure().EndInit(1).
64+
End()
65+
domTest(t, pkg, `package main
66+
67+
func main() {
68+
x := func() int {
69+
return 1
70+
}
71+
}
72+
`)
73+
}
74+
6075
func TestGopoConst(t *testing.T) {
6176
pkg := newPackage("foo", false)
6277
pkg.CB().NewConstStart(nil, "Gopo_x").

0 commit comments

Comments
 (0)