Skip to content

Commit c8d5ccf

Browse files
committed
[dev.unified] go/internal/gcimporter: flatten imports
The current documentation for go/types.(*Packages).Imports requires that the import graph be flattened when read from export data. I think this is a documentation bug (incorrectly codifying the existing behavior, rather than documenting it as a known bug), but until that's decided, we can at least flatten imports ourselves. Updates #54096. Change-Id: Idc054a2efc908b3e6651e6567d0ea0e89bb0c54d Reviewed-on: https://go-review.googlesource.com/c/go/+/419596 Run-TryBot: Matthew Dempsky <[email protected]> Reviewed-by: David Chase <[email protected]> TryBot-Result: Gopher Robot <[email protected]>
1 parent ac0844e commit c8d5ccf

File tree

1 file changed

+31
-1
lines changed

1 file changed

+31
-1
lines changed

src/go/internal/gcimporter/ureader.go

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -206,11 +206,41 @@ func (r *reader) doPkg() *types.Package {
206206
for i := range imports {
207207
imports[i] = r.pkg()
208208
}
209-
pkg.SetImports(imports)
209+
210+
// The documentation for (*types.Package).Imports requires
211+
// flattening the import graph when reading from export data, as
212+
// obviously incorrect as that is.
213+
//
214+
// TODO(mdempsky): Remove this if go.dev/issue/54096 is accepted.
215+
pkg.SetImports(flattenImports(imports))
210216

211217
return pkg
212218
}
213219

220+
// flattenImports returns the transitive closure of all imported
221+
// packages rooted from pkgs.
222+
func flattenImports(pkgs []*types.Package) []*types.Package {
223+
var res []*types.Package
224+
225+
seen := make(map[*types.Package]bool)
226+
var add func(pkg *types.Package)
227+
add = func(pkg *types.Package) {
228+
if seen[pkg] {
229+
return
230+
}
231+
seen[pkg] = true
232+
res = append(res, pkg)
233+
for _, imp := range pkg.Imports() {
234+
add(imp)
235+
}
236+
}
237+
238+
for _, pkg := range pkgs {
239+
add(pkg)
240+
}
241+
return res
242+
}
243+
214244
// @@@ Types
215245

216246
func (r *reader) typ() types.Type {

0 commit comments

Comments
 (0)