Skip to content

Commit c6d331d

Browse files
adonovangopherbot
authored andcommitted
internal/refactor/inline: don't add same import PkgName twice
The logic to choose a fresh names checked for conflicts in the caller and callee but not against the newly added imports. This change adds a fix and a test. Also, don't use "init" as a PkgName: it's reserved. Fixes golang/go#63298 Change-Id: I7670fb841d6a4f521d567d39fef86c88f06e5c98 Reviewed-on: https://go-review.googlesource.com/c/tools/+/531698 Reviewed-by: Robert Findley <[email protected]> Auto-Submit: Alan Donovan <[email protected]> LUCI-TryBot-Result: Go LUCI <[email protected]>
1 parent 1058109 commit c6d331d

File tree

2 files changed

+64
-1
lines changed

2 files changed

+64
-1
lines changed

internal/refactor/inline/inline.go

+12-1
Original file line numberDiff line numberDiff line change
@@ -331,18 +331,29 @@ func inline(logf func(string, ...any), caller *Caller, callee *gobCallee) (*resu
331331
}
332332
}
333333

334+
newlyAdded := func(name string) bool {
335+
for _, new := range newImports {
336+
if new.Name.Name == name {
337+
return true
338+
}
339+
}
340+
return false
341+
}
342+
334343
// import added by callee
335344
//
336345
// Choose local PkgName based on last segment of
337346
// package path plus, if needed, a numeric suffix to
338347
// ensure uniqueness.
339348
//
349+
// "init" is not a legal PkgName.
350+
//
340351
// TODO(adonovan): preserve the PkgName used
341352
// in the original source, or, for a dot import,
342353
// use the package's declared name.
343354
base := pathpkg.Base(path)
344355
name := base
345-
for n := 0; shadows[name] || caller.lookup(name) != nil; n++ {
356+
for n := 0; shadows[name] || caller.lookup(name) != nil || newlyAdded(name) || name == "init"; n++ {
346357
name = fmt.Sprintf("%s%d", base, n)
347358
}
348359

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
Regression test for #63298: inlining a function that
2+
depends on two packages with the same name leads
3+
to duplicate PkgNames.
4+
5+
-- go.mod --
6+
module testdata
7+
go 1.12
8+
9+
-- a/a.go --
10+
package a
11+
12+
func _() {
13+
a2() //@ inline(re"a2", result)
14+
}
15+
16+
-- a/a2.go --
17+
package a
18+
19+
import "testdata/b"
20+
import anotherb "testdata/another/b"
21+
22+
func a2() {
23+
b.B()
24+
anotherb.B()
25+
}
26+
27+
-- b/b.go --
28+
package b
29+
30+
func B() {}
31+
32+
-- b/another/b.go --
33+
package b
34+
35+
func B() {}
36+
37+
-- result --
38+
package a
39+
40+
import (
41+
b "testdata/b"
42+
b0 "testdata/another/b"
43+
44+
//@ inline(re"a2", result)
45+
)
46+
47+
func _() {
48+
{
49+
b.B()
50+
b0.B()
51+
}
52+
}

0 commit comments

Comments
 (0)