Skip to content

Commit e27768f

Browse files
committed
internal/refactor/inline: freeishNames initial scope
Start the freeishNames walk with a non-nil scope. We may need it if the argument node establishes a binding without first opening a scope. (Example in the code.) For golang/go#73321. Change-Id: I72d45e26d27a726d869c9b8eb7d47bc187059832 Reviewed-on: https://go-review.googlesource.com/c/tools/+/665776 LUCI-TryBot-Result: Go LUCI <[email protected]> Reviewed-by: Alan Donovan <[email protected]>
1 parent 264b0a5 commit e27768f

File tree

3 files changed

+39
-0
lines changed

3 files changed

+39
-0
lines changed

internal/refactor/inline/free.go

+6
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,13 @@ import (
3535
// panics if it sees one.
3636
func freeishNames(free map[string]bool, n ast.Node, includeComplitIdents bool) {
3737
v := &freeVisitor{free: free, includeComplitIdents: includeComplitIdents}
38+
// Begin with a scope, even though n might not be a form that establishes a scope.
39+
// For example, n might be:
40+
// x := ...
41+
// Then we need to add the first x to some scope.
42+
v.openScope()
3843
ast.Walk(v, n)
44+
v.closeScope()
3945
assert(v.scope == nil, "unbalanced scopes")
4046
}
4147

internal/refactor/inline/free_test.go

+8
Original file line numberDiff line numberDiff line change
@@ -229,6 +229,14 @@ func TestFreeishNames(t *testing.T) {
229229
}
230230
}
231231

232+
func TestFreeishNamesScope(t *testing.T) {
233+
// Verify that inputs that don't start a scope don't crash.
234+
_, f := mustParse(t, "free.go", `package p; func _() { x := 1; _ = x }`)
235+
// Select the short var decl, not the entire function body.
236+
n := f.Decls[0].(*ast.FuncDecl).Body.List[0]
237+
freeishNames(map[string]bool{}, n, false)
238+
}
239+
232240
func mustParse(t *testing.T, filename string, content any) (*token.FileSet, *ast.File) {
233241
fset := token.NewFileSet()
234242
f, err := parser.ParseFile(fset, filename, content, parser.ParseComments|parser.SkipObjectResolution)

internal/refactor/inline/testdata/n-ary.txtar

+25
Original file line numberDiff line numberDiff line change
@@ -77,3 +77,28 @@ func _() {
7777
}
7878

7979
func f4() int { return 2 + 2 }
80+
-- e/e.go --
81+
package e
82+
83+
func _() {
84+
switch {
85+
case true:
86+
a, b := f5() //@ inline(re"f5", f5)
87+
_, _ = a, b
88+
}
89+
}
90+
91+
func f5() (int, int) { return 2, 2}
92+
93+
-- f5 --
94+
package e
95+
96+
func _() {
97+
switch {
98+
case true:
99+
a, b := 2, 2 //@ inline(re"f5", f5)
100+
_, _ = a, b
101+
}
102+
}
103+
104+
func f5() (int, int) { return 2, 2 }

0 commit comments

Comments
 (0)