Repository navigation
Expand file tree
/
Copy pathcheck.go
More file actions
executable file
·1951 lines (1760 loc) · 63.6 KB
/
Copy pathcheck.go
File metadata and controls
executable file
·1951 lines (1760 loc) · 63.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2019 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package cache
import (
"context"
"crypto/sha256"
"fmt"
"go/ast"
"go/build"
"go/parser"
"go/token"
"go/types"
"regexp"
"runtime"
"sort"
"strings"
"sync"
"sync/atomic"
"golang.org/x/mod/module"
"golang.org/x/sync/errgroup"
"golang.org/x/tools/go/ast/astutil"
"golang.org/x/tools/gopls/internal/cache/metadata"
"golang.org/x/tools/gopls/internal/cache/typerefs"
"golang.org/x/tools/gopls/internal/file"
"golang.org/x/tools/gopls/internal/filecache"
"golang.org/x/tools/gopls/internal/protocol"
"golang.org/x/tools/gopls/internal/util/bug"
"golang.org/x/tools/gopls/internal/util/safetoken"
"golang.org/x/tools/gopls/internal/util/slices"
"golang.org/x/tools/internal/analysisinternal"
"golang.org/x/tools/internal/event"
"golang.org/x/tools/internal/event/tag"
"golang.org/x/tools/internal/gcimporter"
"golang.org/x/tools/internal/packagesinternal"
"golang.org/x/tools/internal/tokeninternal"
"golang.org/x/tools/internal/typesinternal"
"golang.org/x/tools/internal/versions"
)
// Various optimizations that should not affect correctness.
const (
preserveImportGraph = true // hold on to the import graph for open packages
)
type unit = struct{}
// A typeCheckBatch holds data for a logical type-checking operation, which may
// type-check many unrelated packages.
//
// It shares state such as parsed files and imports, to optimize type-checking
// for packages with overlapping dependency graphs.
type typeCheckBatch struct {
activePackageCache interface {
getActivePackage(id PackageID) *Package
setActivePackage(id PackageID, pkg *Package)
}
syntaxIndex map[PackageID]int // requested ID -> index in ids
pre preTypeCheck
post postTypeCheck
handles map[PackageID]*packageHandle
parseCache *parseCache
fset *token.FileSet // describes all parsed or imported files
cpulimit chan unit // concurrency limiter for CPU-bound operations
mu sync.Mutex
syntaxPackages map[PackageID]*futurePackage // results of processing a requested package; may hold (nil, nil)
importPackages map[PackageID]*futurePackage // package results to use for importing
}
// A futurePackage is a future result of type checking or importing a package,
// to be cached in a map.
//
// The goroutine that creates the futurePackage is responsible for evaluating
// its value, and closing the done channel.
type futurePackage struct {
done chan unit
v pkgOrErr
}
type pkgOrErr struct {
pkg *types.Package
err error
}
// TypeCheck parses and type-checks the specified packages,
// and returns them in the same order as the ids.
// The resulting packages' types may belong to different importers,
// so types from different packages are incommensurable.
//
// The resulting packages slice always contains len(ids) entries, though some
// of them may be nil if (and only if) the resulting error is non-nil.
//
// An error is returned if any of the requested packages fail to type-check.
// This is different from having type-checking errors: a failure to type-check
// indicates context cancellation or otherwise significant failure to perform
// the type-checking operation.
//
// In general, clients should never need to type-checked syntax for an
// intermediate test variant (ITV) package. Callers should apply
// RemoveIntermediateTestVariants (or equivalent) before this method, or any
// of the potentially type-checking methods below.
func (s *Snapshot) TypeCheck(ctx context.Context, ids ...PackageID) ([]*Package, error) {
pkgs := make([]*Package, len(ids))
var (
needIDs []PackageID // ids to type-check
indexes []int // original index of requested ids
)
// Check for existing active packages, as any package will do.
//
// This is also done inside forEachPackage, but doing it here avoids
// unnecessary set up for type checking (e.g. assembling the package handle
// graph).
for i, id := range ids {
if pkg := s.getActivePackage(id); pkg != nil {
pkgs[i] = pkg
} else {
needIDs = append(needIDs, id)
indexes = append(indexes, i)
}
}
post := func(i int, pkg *Package) {
pkgs[indexes[i]] = pkg
}
return pkgs, s.forEachPackage(ctx, needIDs, nil, post)
}
// getImportGraph returns a shared import graph use for this snapshot, or nil.
//
// This is purely an optimization: holding on to more imports allows trading
// memory for CPU and latency. Currently, getImportGraph returns an import
// graph containing all packages imported by open packages, since these are
// highly likely to be needed when packages change.
//
// Furthermore, since we memoize active packages, including their imports in
// the shared import graph means we don't run the risk of pinning duplicate
// copies of common imports, if active packages are computed in separate type
// checking batches.
func (s *Snapshot) getImportGraph(ctx context.Context) *importGraph {
if !preserveImportGraph {
return nil
}
s.mu.Lock()
// Evaluate the shared import graph for the snapshot. There are three major
// codepaths here:
//
// 1. importGraphDone == nil, importGraph == nil: it is this goroutine's
// responsibility to type-check the shared import graph.
// 2. importGraphDone == nil, importGraph != nil: it is this goroutine's
// responsibility to resolve the import graph, which may result in
// type-checking only if the existing importGraph (carried over from the
// preceding snapshot) is invalid.
// 3. importGraphDone != nil: some other goroutine is doing (1) or (2), wait
// for the work to be done.
done := s.importGraphDone
if done == nil {
done = make(chan unit)
s.importGraphDone = done
release := s.Acquire() // must acquire to use the snapshot asynchronously
go func() {
defer release()
importGraph, err := s.resolveImportGraph() // may be nil
if err != nil {
if ctx.Err() == nil {
event.Error(ctx, "computing the shared import graph", err)
}
importGraph = nil
}
s.mu.Lock()
s.importGraph = importGraph
s.mu.Unlock()
close(done)
}()
}
s.mu.Unlock()
select {
case <-done:
return s.importGraph
case <-ctx.Done():
return nil
}
}
// resolveImportGraph evaluates the shared import graph to use for
// type-checking in this snapshot. This may involve re-using the import graph
// of the previous snapshot (stored in s.importGraph), or computing a fresh
// import graph.
//
// resolveImportGraph should only be called from getImportGraph.
func (s *Snapshot) resolveImportGraph() (*importGraph, error) {
ctx := s.backgroundCtx
ctx, done := event.Start(event.Detach(ctx), "cache.resolveImportGraph")
defer done()
s.mu.Lock()
lastImportGraph := s.importGraph
s.mu.Unlock()
openPackages := make(map[PackageID]bool)
for _, fh := range s.Overlays() {
// golang/go#66145: don't call MetadataForFile here. This function, which
// builds a shared import graph, is an optimization. We don't want it to
// have the side effect of triggering a load.
//
// In the past, a call to MetadataForFile here caused a bunch of
// unnecessary loads in multi-root workspaces (and as a result, spurious
// diagnostics).
g := s.MetadataGraph()
var mps []*metadata.Package
for _, id := range g.IDs[fh.URI()] {
mps = append(mps, g.Packages[id])
}
metadata.RemoveIntermediateTestVariants(&mps)
for _, mp := range mps {
openPackages[mp.ID] = true
}
}
var openPackageIDs []PackageID
for id := range openPackages {
openPackageIDs = append(openPackageIDs, id)
}
handles, err := s.getPackageHandles(ctx, openPackageIDs)
if err != nil {
return nil, err
}
// Subtlety: we erase the upward cone of open packages from the shared import
// graph, to increase reusability.
//
// This is easiest to understand via an example: suppose A imports B, and B
// imports C. Now suppose A and B are open. If we preserve the entire set of
// shared deps by open packages, deps will be {B, C}. But this means that any
// change to the open package B will invalidate the shared import graph,
// meaning we will experience no benefit from sharing when B is edited.
// Consider that this will be a common scenario, when A is foo_test and B is
// foo. Better to just preserve the shared import C.
//
// With precise pruning, we may want to truncate this search based on
// reachability.
//
// TODO(rfindley): this logic could use a unit test.
volatileDeps := make(map[PackageID]bool)
var isVolatile func(*packageHandle) bool
isVolatile = func(ph *packageHandle) (volatile bool) {
if v, ok := volatileDeps[ph.mp.ID]; ok {
return v
}
defer func() {
volatileDeps[ph.mp.ID] = volatile
}()
if openPackages[ph.mp.ID] {
return true
}
for _, dep := range ph.mp.DepsByPkgPath {
if isVolatile(handles[dep]) {
return true
}
}
return false
}
for _, dep := range handles {
isVolatile(dep)
}
for id, volatile := range volatileDeps {
if volatile {
delete(handles, id)
}
}
// We reuse the last import graph if and only if none of the dependencies
// have changed. Doing better would involve analyzing dependencies to find
// subgraphs that are still valid. Not worth it, especially when in the
// common case nothing has changed.
unchanged := lastImportGraph != nil && len(handles) == len(lastImportGraph.depKeys)
var ids []PackageID
depKeys := make(map[PackageID]file.Hash)
for id, ph := range handles {
ids = append(ids, id)
depKeys[id] = ph.key
if unchanged {
prevKey, ok := lastImportGraph.depKeys[id]
unchanged = ok && prevKey == ph.key
}
}
if unchanged {
return lastImportGraph, nil
}
b, err := s.forEachPackageInternal(ctx, nil, ids, nil, nil, nil, handles)
if err != nil {
return nil, err
}
next := &importGraph{
fset: b.fset,
depKeys: depKeys,
imports: make(map[PackageID]pkgOrErr),
}
for id, fut := range b.importPackages {
if fut.v.pkg == nil && fut.v.err == nil {
panic(fmt.Sprintf("internal error: import node %s is not evaluated", id))
}
next.imports[id] = fut.v
}
return next, nil
}
// An importGraph holds selected results of a type-checking pass, to be re-used
// by subsequent snapshots.
type importGraph struct {
fset *token.FileSet // fileset used for type checking imports
depKeys map[PackageID]file.Hash // hash of direct dependencies for this graph
imports map[PackageID]pkgOrErr // results of type checking
}
// Package visiting functions used by forEachPackage; see the documentation of
// forEachPackage for details.
type (
preTypeCheck = func(int, *packageHandle) bool // false => don't type check
postTypeCheck = func(int, *Package)
)
// forEachPackage does a pre- and post- order traversal of the packages
// specified by ids using the provided pre and post functions.
//
// The pre func is optional. If set, pre is evaluated after the package
// handle has been constructed, but before type-checking. If pre returns false,
// type-checking is skipped for this package handle.
//
// post is called with a syntax package after type-checking completes
// successfully. It is only called if pre returned true.
//
// Both pre and post may be called concurrently.
func (s *Snapshot) forEachPackage(ctx context.Context, ids []PackageID, pre preTypeCheck, post postTypeCheck) error {
ctx, done := event.Start(ctx, "cache.forEachPackage", tag.PackageCount.Of(len(ids)))
defer done()
if len(ids) == 0 {
return nil // short cut: many call sites do not handle empty ids
}
handles, err := s.getPackageHandles(ctx, ids)
if err != nil {
return err
}
impGraph := s.getImportGraph(ctx)
_, err = s.forEachPackageInternal(ctx, impGraph, nil, ids, pre, post, handles)
return err
}
// forEachPackageInternal is used by both forEachPackage and loadImportGraph to
// type-check a graph of packages.
//
// If a non-nil importGraph is provided, imports in this graph will be reused.
func (s *Snapshot) forEachPackageInternal(ctx context.Context, importGraph *importGraph, importIDs, syntaxIDs []PackageID, pre preTypeCheck, post postTypeCheck, handles map[PackageID]*packageHandle) (*typeCheckBatch, error) {
b := &typeCheckBatch{
activePackageCache: s,
pre: pre,
post: post,
handles: handles,
parseCache: s.view.parseCache,
fset: fileSetWithBase(reservedForParsing),
syntaxIndex: make(map[PackageID]int),
cpulimit: make(chan unit, runtime.GOMAXPROCS(0)),
syntaxPackages: make(map[PackageID]*futurePackage),
importPackages: make(map[PackageID]*futurePackage),
}
if importGraph != nil {
// Clone the file set every time, to ensure we do not leak files.
b.fset = tokeninternal.CloneFileSet(importGraph.fset)
// Pre-populate future cache with 'done' futures.
done := make(chan unit)
close(done)
for id, res := range importGraph.imports {
b.importPackages[id] = &futurePackage{done, res}
}
} else {
b.fset = fileSetWithBase(reservedForParsing)
}
for i, id := range syntaxIDs {
b.syntaxIndex[id] = i
}
// Start a single goroutine for each requested package.
//
// Other packages are reached recursively, and will not be evaluated if they
// are not needed.
var g errgroup.Group
for _, id := range importIDs {
id := id
g.Go(func() error {
_, err := b.getImportPackage(ctx, id)
return err
})
}
for i, id := range syntaxIDs {
i := i
id := id
g.Go(func() error {
_, err := b.handleSyntaxPackage(ctx, i, id)
return err
})
}
return b, g.Wait()
}
// TODO(rfindley): re-order the declarations below to read better from top-to-bottom.
// getImportPackage returns the *types.Package to use for importing the
// package referenced by id.
//
// This may be the package produced by type-checking syntax (as in the case
// where id is in the set of requested IDs), a package loaded from export data,
// or a package type-checked for import only.
func (b *typeCheckBatch) getImportPackage(ctx context.Context, id PackageID) (pkg *types.Package, err error) {
b.mu.Lock()
f, ok := b.importPackages[id]
if ok {
b.mu.Unlock()
select {
case <-ctx.Done():
return nil, ctx.Err()
case <-f.done:
return f.v.pkg, f.v.err
}
}
f = &futurePackage{done: make(chan unit)}
b.importPackages[id] = f
b.mu.Unlock()
defer func() {
f.v = pkgOrErr{pkg, err}
close(f.done)
}()
if index, ok := b.syntaxIndex[id]; ok {
pkg, err := b.handleSyntaxPackage(ctx, index, id)
if err != nil {
return nil, err
}
if pkg != nil {
return pkg, nil
}
// type-checking was short-circuited by the pre- func.
}
// unsafe cannot be imported or type-checked.
if id == "unsafe" {
return types.Unsafe, nil
}
ph := b.handles[id]
// Do a second check for "unsafe" defensively, due to golang/go#60890.
if ph.mp.PkgPath == "unsafe" {
bug.Reportf("encountered \"unsafe\" as %s (golang/go#60890)", id)
return types.Unsafe, nil
}
data, err := filecache.Get(exportDataKind, ph.key)
if err == filecache.ErrNotFound {
// No cached export data: type-check as fast as possible.
return b.checkPackageForImport(ctx, ph)
}
if err != nil {
return nil, fmt.Errorf("failed to read cache data for %s: %v", ph.mp.ID, err)
}
return b.importPackage(ctx, ph.mp, data)
}
// handleSyntaxPackage handles one package from the ids slice.
//
// If type checking occurred while handling the package, it returns the
// resulting types.Package so that it may be used for importing.
//
// handleSyntaxPackage returns (nil, nil) if pre returned false.
func (b *typeCheckBatch) handleSyntaxPackage(ctx context.Context, i int, id PackageID) (pkg *types.Package, err error) {
b.mu.Lock()
f, ok := b.syntaxPackages[id]
if ok {
b.mu.Unlock()
<-f.done
return f.v.pkg, f.v.err
}
f = &futurePackage{done: make(chan unit)}
b.syntaxPackages[id] = f
b.mu.Unlock()
defer func() {
f.v = pkgOrErr{pkg, err}
close(f.done)
}()
ph := b.handles[id]
if b.pre != nil && !b.pre(i, ph) {
return nil, nil // skip: export data only
}
// Check for existing active packages.
//
// Since gopls can't depend on package identity, any instance of the
// requested package must be ok to return.
//
// This is an optimization to avoid redundant type-checking: following
// changes to an open package many LSP clients send several successive
// requests for package information for the modified package (semantic
// tokens, code lens, inlay hints, etc.)
if pkg := b.activePackageCache.getActivePackage(id); pkg != nil {
b.post(i, pkg)
return nil, nil // skip: not checked in this batch
}
// Wait for predecessors.
{
var g errgroup.Group
for _, depID := range ph.mp.DepsByPkgPath {
depID := depID
g.Go(func() error {
_, err := b.getImportPackage(ctx, depID)
return err
})
}
if err := g.Wait(); err != nil {
// Failure to import a package should not abort the whole operation.
// Stop only if the context was cancelled, a likely cause.
// Import errors will be reported as type diagnostics.
if ctx.Err() != nil {
return nil, ctx.Err()
}
}
}
// Wait to acquire a CPU token.
//
// Note: it is important to acquire this token only after awaiting
// predecessors, to avoid starvation.
select {
case <-ctx.Done():
return nil, ctx.Err()
case b.cpulimit <- unit{}:
defer func() {
<-b.cpulimit // release CPU token
}()
}
// Compute the syntax package.
p, err := b.checkPackage(ctx, ph)
if err != nil {
return nil, err
}
// Update caches.
b.activePackageCache.setActivePackage(id, p) // store active packages in memory
go storePackageResults(ctx, ph, p) // ...and write all packages to disk
b.post(i, p)
return p.pkg.types, nil
}
// storePackageResults serializes and writes information derived from p to the
// file cache.
// The context is used only for logging; cancellation does not affect the operation.
func storePackageResults(ctx context.Context, ph *packageHandle, p *Package) {
toCache := map[string][]byte{
xrefsKind: p.pkg.xrefs(),
methodSetsKind: p.pkg.methodsets().Encode(),
diagnosticsKind: encodeDiagnostics(p.pkg.diagnostics),
}
if p.metadata.PkgPath != "unsafe" { // unsafe cannot be exported
exportData, err := gcimporter.IExportShallow(p.pkg.fset, p.pkg.types, bug.Reportf)
if err != nil {
bug.Reportf("exporting package %v: %v", p.metadata.ID, err)
} else {
toCache[exportDataKind] = exportData
}
} else if p.metadata.ID != "unsafe" {
// golang/go#60890: we should only ever see one variant of the "unsafe"
// package.
bug.Reportf("encountered \"unsafe\" as %s (golang/go#60890)", p.metadata.ID)
}
for kind, data := range toCache {
if err := filecache.Set(kind, ph.key, data); err != nil {
event.Error(ctx, fmt.Sprintf("storing %s data for %s", kind, ph.mp.ID), err)
}
}
}
// importPackage loads the given package from its export data in p.exportData
// (which must already be populated).
func (b *typeCheckBatch) importPackage(ctx context.Context, mp *metadata.Package, data []byte) (*types.Package, error) {
ctx, done := event.Start(ctx, "cache.typeCheckBatch.importPackage", tag.Package.Of(string(mp.ID)))
defer done()
impMap := b.importMap(mp.ID)
thisPackage := types.NewPackage(string(mp.PkgPath), string(mp.Name))
getPackages := func(items []gcimporter.GetPackagesItem) error {
for i, item := range items {
var id PackageID
var pkg *types.Package
if item.Path == string(mp.PkgPath) {
id = mp.ID
pkg = thisPackage
// debugging issues #60904, #64235
if pkg.Name() != item.Name {
// This would mean that mp.Name != item.Name, so the
// manifest in the export data of mp.PkgPath is
// inconsistent with mp.Name. Or perhaps there
// are duplicate PkgPath items in the manifest?
return bug.Errorf("internal error: package name is %q, want %q (id=%q, path=%q) (see issue #60904)",
pkg.Name(), item.Name, id, item.Path)
}
} else {
id = impMap[item.Path]
var err error
pkg, err = b.getImportPackage(ctx, id)
if err != nil {
return err
}
// We intentionally duplicate the bug.Errorf calls because
// telemetry tells us only the program counter, not the message.
// debugging issues #60904, #64235
if pkg.Name() != item.Name {
// This means that, while reading the manifest of the
// export data of mp.PkgPath, one of its indirect
// dependencies had a name that differs from the
// Metadata.Name
return bug.Errorf("internal error: package name is %q, want %q (id=%q, path=%q) (see issue #60904)",
pkg.Name(), item.Name, id, item.Path)
}
}
items[i].Pkg = pkg
}
return nil
}
// Importing is potentially expensive, and might not encounter cancellations
// via dependencies (e.g. if they have already been evaluated).
if ctx.Err() != nil {
return nil, ctx.Err()
}
imported, err := gcimporter.IImportShallow(b.fset, getPackages, data, string(mp.PkgPath), bug.Reportf)
if err != nil {
return nil, fmt.Errorf("import failed for %q: %v", mp.ID, err)
}
return imported, nil
}
// checkPackageForImport type checks, but skips function bodies and does not
// record syntax information.
func (b *typeCheckBatch) checkPackageForImport(ctx context.Context, ph *packageHandle) (*types.Package, error) {
ctx, done := event.Start(ctx, "cache.typeCheckBatch.checkPackageForImport", tag.Package.Of(string(ph.mp.ID)))
defer done()
onError := func(e error) {
// Ignore errors for exporting.
}
cfg := b.typesConfig(ctx, ph.localInputs, onError)
cfg.IgnoreFuncBodies = true
// Parse the compiled go files, bypassing the parse cache as packages checked
// for import are unlikely to get cache hits. Additionally, we can optimize
// parsing slightly by not passing parser.ParseComments.
pgfs := make([]*ParsedGoFile, len(ph.localInputs.compiledGoFiles))
{
var group errgroup.Group
// Set an arbitrary concurrency limit; we want some parallelism but don't
// need GOMAXPROCS, as there is already a lot of concurrency among calls to
// checkPackageForImport.
//
// TODO(rfindley): is there a better way to limit parallelism here? We could
// have a global limit on the type-check batch, but would have to be very
// careful to avoid starvation.
group.SetLimit(4)
for i, fh := range ph.localInputs.compiledGoFiles {
i, fh := i, fh
group.Go(func() error {
pgf, err := parseGoImpl(ctx, b.fset, fh, parser.SkipObjectResolution, false)
pgfs[i] = pgf
return err
})
}
if err := group.Wait(); err != nil {
return nil, err // cancelled, or catastrophic error (e.g. missing file)
}
}
pkg := types.NewPackage(string(ph.localInputs.pkgPath), string(ph.localInputs.name))
check := types.NewChecker(cfg, b.fset, pkg, nil)
files := make([]*ast.File, len(pgfs))
for i, pgf := range pgfs {
files[i] = pgf.File
}
// Type checking is expensive, and we may not have encountered cancellations
// via parsing (e.g. if we got nothing but cache hits for parsed files).
if ctx.Err() != nil {
return nil, ctx.Err()
}
_ = check.Files(files) // ignore errors
// If the context was cancelled, we may have returned a ton of transient
// errors to the type checker. Swallow them.
if ctx.Err() != nil {
return nil, ctx.Err()
}
// Asynchronously record export data.
go func() {
exportData, err := gcimporter.IExportShallow(b.fset, pkg, bug.Reportf)
if err != nil {
bug.Reportf("exporting package %v: %v", ph.mp.ID, err)
return
}
if err := filecache.Set(exportDataKind, ph.key, exportData); err != nil {
event.Error(ctx, fmt.Sprintf("storing export data for %s", ph.mp.ID), err)
}
}()
return pkg, nil
}
// importMap returns the map of package path -> package ID relative to the
// specified ID.
func (b *typeCheckBatch) importMap(id PackageID) map[string]PackageID {
impMap := make(map[string]PackageID)
var populateDeps func(*metadata.Package)
populateDeps = func(parent *metadata.Package) {
for _, id := range parent.DepsByPkgPath {
mp := b.handles[id].mp
if prevID, ok := impMap[string(mp.PkgPath)]; ok {
// debugging #63822
if prevID != mp.ID {
bug.Reportf("inconsistent view of dependencies")
}
continue
}
impMap[string(mp.PkgPath)] = mp.ID
populateDeps(mp)
}
}
mp := b.handles[id].mp
populateDeps(mp)
return impMap
}
// A packageHandle holds inputs required to compute a Package, including
// metadata, derived diagnostics, files, and settings. Additionally,
// packageHandles manage a key for these inputs, to use in looking up
// precomputed results.
//
// packageHandles may be invalid following an invalidation via snapshot.clone,
// but the handles returned by getPackageHandles will always be valid.
//
// packageHandles are critical for implementing "precise pruning" in gopls:
// packageHandle.key is a hash of a precise set of inputs, such as package
// files and "reachable" syntax, that may affect type checking.
//
// packageHandles also keep track of state that allows gopls to compute, and
// then quickly recompute, these keys. This state is split into two categories:
// - local state, which depends only on the package's local files and metadata
// - other state, which includes data derived from dependencies.
//
// Dividing the data in this way allows gopls to minimize invalidation when a
// package is modified. For example, any change to a package file fully
// invalidates the package handle. On the other hand, if that change was not
// metadata-affecting it may be the case that packages indirectly depending on
// the modified package are unaffected by the change. For that reason, we have
// two types of invalidation, corresponding to the two types of data above:
// - deletion of the handle, which occurs when the package itself changes
// - clearing of the validated field, which marks the package as possibly
// invalid.
//
// With the second type of invalidation, packageHandles are re-evaluated from the
// bottom up. If this process encounters a packageHandle whose deps have not
// changed (as detected by the depkeys field), then the packageHandle in
// question must also not have changed, and we need not re-evaluate its key.
type packageHandle struct {
mp *metadata.Package
// loadDiagnostics memoizes the result of processing error messages from
// go/packages (i.e. `go list`).
//
// These are derived from metadata using a snapshot. Since they depend on
// file contents (for translating positions), they should theoretically be
// invalidated by file changes, but historically haven't been. In practice
// they are rare and indicate a fundamental error that needs to be corrected
// before development can continue, so it may not be worth significant
// engineering effort to implement accurate invalidation here.
//
// TODO(rfindley): loadDiagnostics are out of place here, as they don't
// directly relate to type checking. We should perhaps move the caching of
// load diagnostics to an entirely separate component, so that Packages need
// only be concerned with parsing and type checking.
// (Nevertheless, since the lifetime of load diagnostics matches that of the
// Metadata, it is convenient to memoize them here.)
loadDiagnostics []*Diagnostic
// Local data:
// localInputs holds all local type-checking localInputs, excluding
// dependencies.
localInputs typeCheckInputs
// localKey is a hash of localInputs.
localKey file.Hash
// refs is the result of syntactic dependency analysis produced by the
// typerefs package.
refs map[string][]typerefs.Symbol
// Data derived from dependencies:
// validated indicates whether the current packageHandle is known to have a
// valid key. Invalidated package handles are stored for packages whose
// type information may have changed.
validated bool
// depKeys records the key of each dependency that was used to calculate the
// key above. If the handle becomes invalid, we must re-check that each still
// matches.
depKeys map[PackageID]file.Hash
// key is the hashed key for the package.
//
// It includes the all bits of the transitive closure of
// dependencies's sources.
key file.Hash
}
// clone returns a copy of the receiver with the validated bit set to the
// provided value.
func (ph *packageHandle) clone(validated bool) *packageHandle {
copy := *ph
copy.validated = validated
return ©
}
// getPackageHandles gets package handles for all given ids and their
// dependencies, recursively.
func (s *Snapshot) getPackageHandles(ctx context.Context, ids []PackageID) (map[PackageID]*packageHandle, error) {
// perform a two-pass traversal.
//
// On the first pass, build up a bidirectional graph of handle nodes, and collect leaves.
// Then build package handles from bottom up.
s.mu.Lock() // guard s.meta and s.packages below
b := &packageHandleBuilder{
s: s,
transitiveRefs: make(map[typerefs.IndexID]*partialRefs),
nodes: make(map[typerefs.IndexID]*handleNode),
}
var leaves []*handleNode
var makeNode func(*handleNode, PackageID) *handleNode
makeNode = func(from *handleNode, id PackageID) *handleNode {
idxID := b.s.pkgIndex.IndexID(id)
n, ok := b.nodes[idxID]
if !ok {
mp := s.meta.Packages[id]
if mp == nil {
panic(fmt.Sprintf("nil metadata for %q", id))
}
n = &handleNode{
mp: mp,
idxID: idxID,
unfinishedSuccs: int32(len(mp.DepsByPkgPath)),
}
if entry, hit := b.s.packages.Get(mp.ID); hit {
n.ph = entry
}
if n.unfinishedSuccs == 0 {
leaves = append(leaves, n)
} else {
n.succs = make(map[PackageID]*handleNode, n.unfinishedSuccs)
}
b.nodes[idxID] = n
for _, depID := range mp.DepsByPkgPath {
n.succs[depID] = makeNode(n, depID)
}
}
// Add edge from predecessor.
if from != nil {
n.preds = append(n.preds, from)
}
return n
}
for _, id := range ids {
makeNode(nil, id)
}
s.mu.Unlock()
g, ctx := errgroup.WithContext(ctx)
// files are preloaded, so building package handles is CPU-bound.
//
// Note that we can't use g.SetLimit, as that could result in starvation:
// g.Go blocks until a slot is available, and so all existing goroutines
// could be blocked trying to enqueue a predecessor.
limiter := make(chan unit, runtime.GOMAXPROCS(0))
var enqueue func(*handleNode)
enqueue = func(n *handleNode) {
g.Go(func() error {
limiter <- unit{}
defer func() { <-limiter }()
if ctx.Err() != nil {
return ctx.Err()
}
b.buildPackageHandle(ctx, n)
for _, pred := range n.preds {
if atomic.AddInt32(&pred.unfinishedSuccs, -1) == 0 {
enqueue(pred)
}
}
return n.err
})
}
for _, leaf := range leaves {
enqueue(leaf)
}
if err := g.Wait(); err != nil {
return nil, err
}
// Copy handles into the result map.
handles := make(map[PackageID]*packageHandle, len(b.nodes))
for _, v := range b.nodes {
assert(v.ph != nil, "nil handle")
handles[v.mp.ID] = v.ph
}
return handles, nil
}
// A packageHandleBuilder computes a batch of packageHandles concurrently,
// sharing computed transitive reachability sets used to compute package keys.
type packageHandleBuilder struct {
s *Snapshot
// nodes are assembled synchronously.
nodes map[typerefs.IndexID]*handleNode
// transitiveRefs is incrementally evaluated as package handles are built.
transitiveRefsMu sync.Mutex
transitiveRefs map[typerefs.IndexID]*partialRefs // see getTransitiveRefs
}
// A handleNode represents a to-be-computed packageHandle within a graph of
// predecessors and successors.
//
// It is used to implement a bottom-up construction of packageHandles.
type handleNode struct {
mp *metadata.Package
idxID typerefs.IndexID
ph *packageHandle
err error
preds []*handleNode
succs map[PackageID]*handleNode
unfinishedSuccs int32
}
// partialRefs maps names declared by a given package to their set of
// transitive references.
//
// If complete is set, refs is known to be complete for the package in
// question. Otherwise, it may only map a subset of all names declared by the
// package.
type partialRefs struct {
refs map[string]*typerefs.PackageSet
complete bool
}
// getTransitiveRefs gets or computes the set of transitively reachable
// packages for each exported name in the package specified by id.