Skip to content

Commit

Permalink
don't hoist local closure variables to parent function
Browse files Browse the repository at this point in the history
Signed-off-by: Achille Roussel <[email protected]>
  • Loading branch information
achille-roussel committed Sep 20, 2023
1 parent f42f9be commit ba04082
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 25 deletions.
2 changes: 1 addition & 1 deletion compiler/compile.go
Original file line number Diff line number Diff line change
Expand Up @@ -337,7 +337,7 @@ func (c *compiler) compileFunction(p *packages.Package, fn *ast.FuncDecl, color
// declarations to the function prologue. We downgrade inline var decls and
// assignments that use := to assignments that use =. Constant decls are
// hoisted and also have their value assigned in the function prologue.
decls := extractDecls(fn, p.TypesInfo)
decls := extractDecls(fn.Body, p.TypesInfo)
renameObjects(fn, p.TypesInfo, decls)
for _, decl := range decls {
gen.Body.List = append(gen.Body.List, &ast.DeclStmt{Decl: decl})
Expand Down
10 changes: 8 additions & 2 deletions compiler/decls.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,13 @@ import (
// Note that declarations are extracted from all nested scopes within the
// function body, so there may be duplicate identifiers. Identifiers can be
// disambiguated using (*types.Info).ObjectOf(ident).
func extractDecls(fn *ast.FuncDecl, info *types.Info) (decls []*ast.GenDecl) {
ast.Inspect(fn.Body, func(node ast.Node) bool {
func extractDecls(tree ast.Node, info *types.Info) (decls []*ast.GenDecl) {
ast.Inspect(tree, func(node ast.Node) bool {
switch n := node.(type) {
case *ast.FuncLit:
// Stop when we encounter a function listeral so we don't hoist its
// local variables into the scope of its parent function.
return false
case *ast.GenDecl: // const, var, type
if n.Tok == token.TYPE || n.Tok == token.CONST {
decls = append(decls, n)
Expand Down Expand Up @@ -135,6 +139,8 @@ func renameObjects(tree ast.Node, info *types.Info, decls []*ast.GenDecl) {
func removeDecls(tree ast.Node) {
astutil.Apply(tree, func(cursor *astutil.Cursor) bool {
switch n := cursor.Node().(type) {
case *ast.FuncLit:
return false
case *ast.AssignStmt:
if n.Tok == token.DEFINE {
if _, ok := cursor.Parent().(*ast.TypeSwitchStmt); ok {
Expand Down
38 changes: 16 additions & 22 deletions compiler/testdata/coroutine_durable.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit ba04082

Please sign in to comment.