| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
package typerefs_test |
| 6 |
|
| 7 |
import ( |
| 8 |
"bytes" |
| 9 |
"context" |
| 10 |
"flag" |
| 11 |
"fmt" |
| 12 |
"go/token" |
| 13 |
"go/types" |
| 14 |
"os" |
| 15 |
"slices" |
| 16 |
"strings" |
| 17 |
"sync" |
| 18 |
"testing" |
| 19 |
"time" |
| 20 |
|
| 21 |
"golang.org/x/tools/go/gcexportdata" |
| 22 |
"golang.org/x/tools/go/packages" |
| 23 |
"golang.org/x/tools/gopls/internal/cache/metadata" |
| 24 |
"golang.org/x/tools/gopls/internal/cache/parsego" |
| 25 |
"golang.org/x/tools/gopls/internal/cache/typerefs" |
| 26 |
"golang.org/x/tools/gopls/internal/protocol" |
| 27 |
"golang.org/x/tools/internal/astutil" |
| 28 |
"golang.org/x/tools/internal/packagesinternal" |
| 29 |
"golang.org/x/tools/internal/testenv" |
| 30 |
) |
| 31 |
|
| 32 |
var ( |
| 33 |
dir = flag.String("dir", "", "dir to run go/packages from") |
| 34 |
query = flag.String("query", "std", "go/packages load query to use for walkdecl tests") |
| 35 |
verify = flag.Bool("verify", true, "whether to verify reachable packages using export data (may be slow on large graphs)") |
| 36 |
) |
| 37 |
|
| 38 |
type ( |
| 39 |
packageName = metadata.PackageName |
| 40 |
PackageID = metadata.PackageID |
| 41 |
ImportPath = metadata.ImportPath |
| 42 |
PackagePath = metadata.PackagePath |
| 43 |
Metadata = metadata.Package |
| 44 |
MetadataSource = metadata.Source |
| 45 |
) |
| 46 |
|
| 47 |
|
| 48 |
|
| 49 |
|
| 50 |
|
| 51 |
|
| 52 |
|
| 53 |
|
| 54 |
|
| 55 |
|
| 56 |
|
| 57 |
|
| 58 |
|
| 59 |
|
| 60 |
|
| 61 |
|
| 62 |
|
| 63 |
|
| 64 |
|
| 65 |
|
| 66 |
func TestBuildPackageGraph(t *testing.T) { |
| 67 |
if testing.Short() { |
| 68 |
t.Skip("skipping with -short: loading the packages can take a long time with a cold cache") |
| 69 |
} |
| 70 |
testenv.NeedsGoBuild(t) |
| 71 |
|
| 72 |
t0 := time.Now() |
| 73 |
exports, meta, err := loadPackages(*query, *verify) |
| 74 |
if err != nil { |
| 75 |
t.Fatalf("loading failed: %v", err) |
| 76 |
} |
| 77 |
t.Logf("loaded %d packages in %v", len(exports), time.Since(t0)) |
| 78 |
|
| 79 |
ctx := context.Background() |
| 80 |
var ids []PackageID |
| 81 |
for id := range exports { |
| 82 |
ids = append(ids, id) |
| 83 |
} |
| 84 |
slices.Sort(ids) |
| 85 |
|
| 86 |
t0 = time.Now() |
| 87 |
g, err := BuildPackageGraph(ctx, meta, ids, newParser().parse) |
| 88 |
if err != nil { |
| 89 |
t.Fatal(err) |
| 90 |
} |
| 91 |
t.Logf("building package graph took %v", time.Since(t0)) |
| 92 |
|
| 93 |
|
| 94 |
|
| 95 |
|
| 96 |
|
| 97 |
|
| 98 |
|
| 99 |
|
| 100 |
|
| 101 |
|
| 102 |
|
| 103 |
type edgeSet map[PackageID]map[PackageID]bool |
| 104 |
var ( |
| 105 |
imports = make(edgeSet) |
| 106 |
importedBy = make(edgeSet) |
| 107 |
reaches = make(edgeSet) |
| 108 |
reachedBy = make(edgeSet) |
| 109 |
loads = make(edgeSet) |
| 110 |
loadedBy = make(edgeSet) |
| 111 |
) |
| 112 |
recordEdge := func(from, to PackageID, fwd, rev edgeSet) { |
| 113 |
if fwd[from] == nil { |
| 114 |
fwd[from] = make(map[PackageID]bool) |
| 115 |
} |
| 116 |
fwd[from][to] = true |
| 117 |
if rev[to] == nil { |
| 118 |
rev[to] = make(map[PackageID]bool) |
| 119 |
} |
| 120 |
rev[to][from] = true |
| 121 |
} |
| 122 |
|
| 123 |
exportedPackages := make(map[PackageID]*types.Package) |
| 124 |
importPackage := func(id PackageID) *types.Package { |
| 125 |
exportFile := exports[id] |
| 126 |
if exportFile == "" { |
| 127 |
return nil |
| 128 |
} |
| 129 |
mp := meta.Metadata(id) |
| 130 |
tpkg, ok := exportedPackages[id] |
| 131 |
if !ok { |
| 132 |
pkgPath := string(mp.PkgPath) |
| 133 |
tpkg, err = importFromExportData(pkgPath, exportFile) |
| 134 |
if err != nil { |
| 135 |
t.Fatalf("importFromExportData(%s, %s) failed: %v", pkgPath, exportFile, err) |
| 136 |
} |
| 137 |
exportedPackages[id] = tpkg |
| 138 |
} |
| 139 |
return tpkg |
| 140 |
} |
| 141 |
|
| 142 |
for _, id := range ids { |
| 143 |
pkg, err := g.Package(ctx, id) |
| 144 |
if err != nil { |
| 145 |
t.Fatal(err) |
| 146 |
} |
| 147 |
pkg.ReachesByDeps.Elems(func(id2 typerefs.IndexID) { |
| 148 |
recordEdge(id, g.pkgIndex.PackageID(id2), reaches, reachedBy) |
| 149 |
}) |
| 150 |
|
| 151 |
importMap := importMap(id, meta) |
| 152 |
for _, id2 := range importMap { |
| 153 |
recordEdge(id, id2, imports, importedBy) |
| 154 |
} |
| 155 |
|
| 156 |
if *verify { |
| 157 |
for _, depID := range meta.Metadata(id).DepsByPkgPath { |
| 158 |
tpkg := importPackage(depID) |
| 159 |
if tpkg == nil { |
| 160 |
continue |
| 161 |
} |
| 162 |
for _, imp := range tpkg.Imports() { |
| 163 |
depID, ok := importMap[PackagePath(imp.Path())] |
| 164 |
if !ok { |
| 165 |
t.Errorf("import map (len: %d) for %s missing imported types.Package %s", len(importMap), id, imp.Path()) |
| 166 |
continue |
| 167 |
} |
| 168 |
recordEdge(id, depID, loads, loadedBy) |
| 169 |
} |
| 170 |
} |
| 171 |
|
| 172 |
for depID := range loads[id] { |
| 173 |
if !pkg.ReachesByDeps.Contains(depID) { |
| 174 |
t.Errorf("package %s was imported by %s, but not detected as reachable", depID, id) |
| 175 |
} |
| 176 |
} |
| 177 |
} |
| 178 |
} |
| 179 |
|
| 180 |
if testing.Verbose() { |
| 181 |
fmt.Printf("%-52s%8s%8s%8s%8s%8s%8s\n", "package ID", "imp", "impBy", "reach", "reachBy", "load", "loadBy") |
| 182 |
for _, id := range ids { |
| 183 |
fmt.Printf("%-52s%8d%8d%8d%8d%8d%8d\n", id, len(imports[id]), len(importedBy[id]), len(reaches[id]), len(reachedBy[id]), len(loads[id]), len(loadedBy[id])) |
| 184 |
} |
| 185 |
fmt.Println(strings.Repeat("-", 100)) |
| 186 |
fmt.Printf("%-52s%8s%8s%8s%8s%8s%8s\n", "package ID", "imp", "impBy", "reach", "reachBy", "load", "loadBy") |
| 187 |
|
| 188 |
avg := func(m edgeSet) float64 { |
| 189 |
var avg float64 |
| 190 |
for _, id := range ids { |
| 191 |
s := m[id] |
| 192 |
avg += float64(len(s)) / float64(len(ids)) |
| 193 |
} |
| 194 |
return avg |
| 195 |
} |
| 196 |
fmt.Printf("%52s%8.1f%8.1f%8.1f%8.1f%8.1f%8.1f\n", "averages:", avg(imports), avg(importedBy), avg(reaches), avg(reachedBy), avg(loads), avg(loadedBy)) |
| 197 |
} |
| 198 |
} |
| 199 |
|
| 200 |
func importMap(id PackageID, meta MetadataSource) map[PackagePath]PackageID { |
| 201 |
imports := make(map[PackagePath]PackageID) |
| 202 |
var recordIDs func(PackageID) |
| 203 |
recordIDs = func(id PackageID) { |
| 204 |
mp := meta.Metadata(id) |
| 205 |
if _, ok := imports[mp.PkgPath]; ok { |
| 206 |
return |
| 207 |
} |
| 208 |
imports[mp.PkgPath] = id |
| 209 |
for _, id := range mp.DepsByPkgPath { |
| 210 |
recordIDs(id) |
| 211 |
} |
| 212 |
} |
| 213 |
for _, id := range meta.Metadata(id).DepsByPkgPath { |
| 214 |
recordIDs(id) |
| 215 |
} |
| 216 |
return imports |
| 217 |
} |
| 218 |
|
| 219 |
func importFromExportData(pkgPath, exportFile string) (*types.Package, error) { |
| 220 |
file, err := os.Open(exportFile) |
| 221 |
if err != nil { |
| 222 |
return nil, err |
| 223 |
} |
| 224 |
r, err := gcexportdata.NewReader(file) |
| 225 |
if err != nil { |
| 226 |
file.Close() |
| 227 |
return nil, err |
| 228 |
} |
| 229 |
fset := token.NewFileSet() |
| 230 |
tpkg, err := gcexportdata.Read(r, fset, make(map[string]*types.Package), pkgPath) |
| 231 |
file.Close() |
| 232 |
if err != nil { |
| 233 |
return nil, err |
| 234 |
} |
| 235 |
|
| 236 |
|
| 237 |
|
| 238 |
|
| 239 |
|
| 240 |
var out bytes.Buffer |
| 241 |
err = gcexportdata.Write(&out, fset, tpkg) |
| 242 |
if err != nil { |
| 243 |
return nil, err |
| 244 |
} |
| 245 |
return gcexportdata.Read(&out, token.NewFileSet(), make(map[string]*types.Package), pkgPath) |
| 246 |
} |
| 247 |
|
| 248 |
func BenchmarkBuildPackageGraph(b *testing.B) { |
| 249 |
t0 := time.Now() |
| 250 |
exports, meta, err := loadPackages(*query, *verify) |
| 251 |
if err != nil { |
| 252 |
b.Fatalf("loading failed: %v", err) |
| 253 |
} |
| 254 |
b.Logf("loaded %d packages in %v", len(exports), time.Since(t0)) |
| 255 |
ctx := context.Background() |
| 256 |
var ids []PackageID |
| 257 |
for id := range exports { |
| 258 |
ids = append(ids, id) |
| 259 |
} |
| 260 |
|
| 261 |
for b.Loop() { |
| 262 |
_, err := BuildPackageGraph(ctx, meta, ids, newParser().parse) |
| 263 |
if err != nil { |
| 264 |
b.Fatal(err) |
| 265 |
} |
| 266 |
} |
| 267 |
} |
| 268 |
|
| 269 |
type memoizedParser struct { |
| 270 |
mu sync.Mutex |
| 271 |
files map[protocol.DocumentURI]*futureParse |
| 272 |
} |
| 273 |
|
| 274 |
type futureParse struct { |
| 275 |
done chan struct{} |
| 276 |
pgf *parsego.File |
| 277 |
err error |
| 278 |
} |
| 279 |
|
| 280 |
func newParser() *memoizedParser { |
| 281 |
return &memoizedParser{ |
| 282 |
files: make(map[protocol.DocumentURI]*futureParse), |
| 283 |
} |
| 284 |
} |
| 285 |
|
| 286 |
func (p *memoizedParser) parse(ctx context.Context, uri protocol.DocumentURI) (*parsego.File, error) { |
| 287 |
doParse := func(ctx context.Context, uri protocol.DocumentURI) (*parsego.File, error) { |
| 288 |
|
| 289 |
content, err := os.ReadFile(uri.Path()) |
| 290 |
if err != nil { |
| 291 |
return nil, err |
| 292 |
} |
| 293 |
content = astutil.PurgeFuncBodies(content) |
| 294 |
pgf, _ := parsego.Parse(ctx, token.NewFileSet(), uri, content, parsego.Full, false) |
| 295 |
return pgf, nil |
| 296 |
} |
| 297 |
|
| 298 |
p.mu.Lock() |
| 299 |
fut, ok := p.files[uri] |
| 300 |
if ok { |
| 301 |
p.mu.Unlock() |
| 302 |
select { |
| 303 |
case <-fut.done: |
| 304 |
case <-ctx.Done(): |
| 305 |
return nil, ctx.Err() |
| 306 |
} |
| 307 |
} else { |
| 308 |
fut = &futureParse{done: make(chan struct{})} |
| 309 |
p.files[uri] = fut |
| 310 |
p.mu.Unlock() |
| 311 |
fut.pgf, fut.err = doParse(ctx, uri) |
| 312 |
close(fut.done) |
| 313 |
} |
| 314 |
return fut.pgf, fut.err |
| 315 |
} |
| 316 |
|
| 317 |
type mapMetadataSource struct { |
| 318 |
m map[PackageID]*Metadata |
| 319 |
} |
| 320 |
|
| 321 |
func (s mapMetadataSource) Metadata(id PackageID) *Metadata { |
| 322 |
return s.m[id] |
| 323 |
} |
| 324 |
|
| 325 |
|
| 326 |
|
| 327 |
|
| 328 |
|
| 329 |
|
| 330 |
func loadPackages(query string, needExport bool) (map[PackageID]string, MetadataSource, error) { |
| 331 |
cfg := &packages.Config{ |
| 332 |
Dir: *dir, |
| 333 |
Mode: packages.NeedName | |
| 334 |
packages.NeedFiles | |
| 335 |
packages.NeedCompiledGoFiles | |
| 336 |
packages.NeedImports | |
| 337 |
packages.NeedDeps | |
| 338 |
packages.NeedTypesSizes | |
| 339 |
packages.NeedModule | |
| 340 |
packages.NeedEmbedFiles | |
| 341 |
packages.LoadMode(packagesinternal.DepsErrors) | |
| 342 |
packages.NeedForTest, |
| 343 |
Tests: true, |
| 344 |
} |
| 345 |
if needExport { |
| 346 |
cfg.Mode |= packages.NeedExportFile |
| 347 |
} |
| 348 |
pkgs, err := packages.Load(cfg, query) |
| 349 |
if err != nil { |
| 350 |
return nil, nil, err |
| 351 |
} |
| 352 |
|
| 353 |
meta := make(map[PackageID]*Metadata) |
| 354 |
var buildMetadata func(pkg *packages.Package) |
| 355 |
buildMetadata = func(pkg *packages.Package) { |
| 356 |
id := PackageID(pkg.ID) |
| 357 |
if meta[id] != nil { |
| 358 |
return |
| 359 |
} |
| 360 |
mp := &Metadata{ |
| 361 |
ID: id, |
| 362 |
PkgPath: PackagePath(pkg.PkgPath), |
| 363 |
Name: packageName(pkg.Name), |
| 364 |
ForTest: PackagePath(pkg.ForTest), |
| 365 |
TypesSizes: pkg.TypesSizes, |
| 366 |
LoadDir: cfg.Dir, |
| 367 |
Module: pkg.Module, |
| 368 |
Errors: pkg.Errors, |
| 369 |
DepsErrors: packagesinternal.GetDepsErrors(pkg), |
| 370 |
} |
| 371 |
meta[id] = mp |
| 372 |
|
| 373 |
for _, filename := range pkg.CompiledGoFiles { |
| 374 |
mp.CompiledGoFiles = append(mp.CompiledGoFiles, protocol.URIFromPath(filename)) |
| 375 |
} |
| 376 |
for _, filename := range pkg.GoFiles { |
| 377 |
mp.GoFiles = append(mp.GoFiles, protocol.URIFromPath(filename)) |
| 378 |
} |
| 379 |
|
| 380 |
mp.DepsByImpPath = make(map[ImportPath]PackageID) |
| 381 |
mp.DepsByPkgPath = make(map[PackagePath]PackageID) |
| 382 |
for importPath, imported := range pkg.Imports { |
| 383 |
importPath := ImportPath(importPath) |
| 384 |
|
| 385 |
|
| 386 |
if importPath != "unsafe" && len(imported.CompiledGoFiles) == 0 { |
| 387 |
mp.DepsByImpPath[importPath] = "" |
| 388 |
continue |
| 389 |
} |
| 390 |
|
| 391 |
mp.DepsByImpPath[importPath] = PackageID(imported.ID) |
| 392 |
mp.DepsByPkgPath[PackagePath(imported.PkgPath)] = PackageID(imported.ID) |
| 393 |
buildMetadata(imported) |
| 394 |
} |
| 395 |
} |
| 396 |
|
| 397 |
exportFiles := make(map[PackageID]string) |
| 398 |
for _, pkg := range pkgs { |
| 399 |
exportFiles[PackageID(pkg.ID)] = pkg.ExportFile |
| 400 |
buildMetadata(pkg) |
| 401 |
} |
| 402 |
return exportFiles, &mapMetadataSource{meta}, nil |
| 403 |
} |