Debian Codegraph @

gopls/internal/cache/analysis.go

raw symbols SCIP
1 // Copyright 2019 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package cache
6
7 // This file defines gopls' driver for modular static analysis (go/analysis).
8
9 import (
10 "bytes"
11 "context"
12 "crypto/sha256"
13 "encoding/gob"
14 "encoding/json"
15 "errors"
16 "fmt"
17 "go/ast"
18 "go/token"
19 "go/types"
20 "log"
21 urlpkg "net/url"
22 "path/filepath"
23 "reflect"
24 "runtime"
25 "runtime/debug"
26 "slices"
27 "sort"
28 "strings"
29 "sync"
30 "sync/atomic"
31 "time"
32
33 "golang.org/x/sync/errgroup"
34 "golang.org/x/tools/go/analysis"
35 "golang.org/x/tools/go/packages"
36 "golang.org/x/tools/gopls/internal/cache/metadata"
37 "golang.org/x/tools/gopls/internal/file"
38 "golang.org/x/tools/gopls/internal/filecache"
39 "golang.org/x/tools/gopls/internal/label"
40 "golang.org/x/tools/gopls/internal/progress"
41 "golang.org/x/tools/gopls/internal/protocol"
42 "golang.org/x/tools/gopls/internal/settings"
43 "golang.org/x/tools/gopls/internal/util/bug"
44 "golang.org/x/tools/gopls/internal/util/frob"
45 "golang.org/x/tools/gopls/internal/util/moremaps"
46 "golang.org/x/tools/gopls/internal/util/persistent"
47 "golang.org/x/tools/gopls/internal/util/safetoken"
48 "golang.org/x/tools/internal/analysis/driverutil"
49 "golang.org/x/tools/internal/astutil"
50 "golang.org/x/tools/internal/event"
51 "golang.org/x/tools/internal/facts"
52 )
53
54 /*
55
56 DESIGN
57
58 An analysis request ([Snapshot.Analyze]) computes diagnostics for the
59 requested packages using the set of analyzers enabled in this view. Each
60 request constructs a transitively closed DAG of nodes, each representing a
61 package, then works bottom up in parallel postorder calling
62 [analysisNode.runCached] to ensure that each node's analysis summary is up
63 to date. The summary contains the analysis diagnostics and serialized facts.
64
65 The entire DAG is ephemeral. Each node in the DAG records the set of
66 analyzers to run: the complete set for the root packages, and the "facty"
67 subset for dependencies. Each package is thus analyzed at most once.
68
69 Each node has a cryptographic key, which is either memoized in the Snapshot
70 or computed by [analysisNode.cacheKey]. This key is a hash of the "recipe"
71 for the analysis step, including the inputs into the type checked package
72 (and its reachable dependencies), the set of analyzers, and importable
73 facts.
74
75 The key is sought in a machine-global persistent file-system based cache. If
76 this gopls process, or another gopls process on the same machine, has
77 already performed this analysis step, runCached will make a cache hit and
78 load the serialized summary of the results. If not, it will have to proceed
79 to run() to parse and type-check the package and then apply a set of
80 analyzers to it. (The set of analyzers applied to a single package itself
81 forms a graph of "actions", and it too is evaluated in parallel postorder;
82 these dependency edges within the same package are called "horizontal".)
83 Finally it writes a new cache entry containing serialized diagnostics and
84 analysis facts.
85
86 The summary must record whether a package is transitively error-free
87 (whether it would compile) because many analyzers are not safe to run on
88 packages with inconsistent types.
89
90 For fact encoding, we use the same fact set as the unitchecker (vet) to
91 record and serialize analysis facts. The fact serialization mechanism is
92 analogous to "deep" export data.
93
94 */
95
96 // TODO(adonovan):
97 // - Add a (white-box) test of pruning when a change doesn't affect export data.
98 // - Optimise pruning based on subset of packages mentioned in exportdata.
99 // - Better logging so that it is possible to deduce why an analyzer is not
100 // being run--often due to very indirect failures. Even if the ultimate
101 // consumer decides to ignore errors, tests and other situations want to be
102 // assured of freedom from errors, not just missing results. This should be
103 // recorded.
104
105 // AnalysisProgressTitle is the title of the progress report for ongoing
106 // analysis. It is sought by regression tests for the progress reporting
107 // feature.
108 const AnalysisProgressTitle = "Analyzing Dependencies"
109
110 // Analyze applies the set of enabled analyzers to the packages in the pkgs
111 // map, and returns their diagnostics.
112 //
113 // Notifications of progress may be sent to the optional reporter.
114 func (s *Snapshot) Analyze(ctx context.Context, pkgs map[PackageID]*metadata.Package, reporter *progress.Tracker) ([]*Diagnostic, error) {
115 start := time.Now() // for progress reporting
116
117 var tagStr string // sorted comma-separated list of PackageIDs
118 {
119 keys := make([]string, 0, len(pkgs))
120 for id := range pkgs {
121 keys = append(keys, string(id))
122 }
123 sort.Strings(keys)
124 tagStr = strings.Join(keys, ",")
125 }
126 ctx, done := event.Start(ctx, "snapshot.Analyze", label.Package.Of(tagStr))
127 defer done()
128
129 // Filter and sort enabled root analyzers.
130 // A disabled analyzer may still be run if required by another.
131 var (
132 toSrc = make(map[*analysis.Analyzer]*settings.Analyzer)
133 enabledAnalyzers []*analysis.Analyzer // enabled subset + transitive requirements
134 )
135 for _, a := range settings.AllAnalyzers {
136 if a.Enabled(s.Options()) {
137 toSrc[a.Analyzer()] = a
138 enabledAnalyzers = append(enabledAnalyzers, a.Analyzer())
139 }
140 }
141 sort.Slice(enabledAnalyzers, func(i, j int) bool {
142 return enabledAnalyzers[i].Name < enabledAnalyzers[j].Name
143 })
144
145 enabledAnalyzers = requiredAnalyzers(enabledAnalyzers)
146
147 // Perform basic sanity checks.
148 // (Ideally we would do this only once.)
149 if err := analysis.Validate(enabledAnalyzers); err != nil {
150 return nil, fmt.Errorf("invalid analyzer configuration: %v", err)
151 }
152
153 stableNames := make(map[*analysis.Analyzer]string)
154
155 var facty []*analysis.Analyzer // facty subset of enabled + transitive requirements
156 for _, a := range enabledAnalyzers {
157 // TODO(adonovan): reject duplicate stable names (very unlikely).
158 stableNames[a] = stableName(a)
159
160 // Register fact types of all required analyzers.
161 if len(a.FactTypes) > 0 {
162 facty = append(facty, a)
163 for _, f := range a.FactTypes {
164 gob.Register(f) // <2us
165 }
166 }
167 }
168 facty = requiredAnalyzers(facty)
169
170 batch, release := s.acquireTypeChecking()
171 defer release()
172
173 ids := moremaps.KeySlice(pkgs)
174 handles, err := s.getPackageHandles(ctx, ids)
175 if err != nil {
176 return nil, err
177 }
178 batch.addHandles(handles)
179
180 // Starting from the root packages and following DepsByPkgPath,
181 // build the DAG of packages we're going to analyze.
182 //
183 // Root nodes will run the enabled set of analyzers,
184 // whereas dependencies will run only the facty set.
185 // Because (by construction) enabled is a superset of facty,
186 // we can analyze each node with exactly one set of analyzers.
187 nodes := make(map[PackageID]*analysisNode)
188 var leaves []*analysisNode // nodes with no unfinished successors
189 var makeNode func(from *analysisNode, id PackageID) (*analysisNode, error)
190 makeNode = func(from *analysisNode, id PackageID) (*analysisNode, error) {
191 an, ok := nodes[id]
192 if !ok {
193 ph := handles[id]
194 if ph == nil {
195 return nil, bug.Errorf("no metadata for %s", id)
196 }
197
198 // -- preorder --
199
200 an = &analysisNode{
201 parseCache: s.view.parseCache,
202 fsource: s, // expose only ReadFile
203 batch: batch,
204 ph: ph,
205 analyzers: facty, // all nodes run at least the facty analyzers
206 stableNames: stableNames,
207 }
208 nodes[id] = an
209
210 // -- recursion --
211
212 // Build subgraphs for dependencies.
213 an.succs = make(map[PackageID]*analysisNode, len(ph.mp.DepsByPkgPath))
214 for _, depID := range ph.mp.DepsByPkgPath {
215 dep, err := makeNode(an, depID)
216 if err != nil {
217 return nil, err
218 }
219 an.succs[depID] = dep
220 }
221
222 // -- postorder --
223
224 // Add leaf nodes (no successors) directly to queue.
225 if len(an.succs) == 0 {
226 leaves = append(leaves, an)
227 }
228 }
229 // Add edge from predecessor.
230 if from != nil {
231 from.unfinishedSuccs.Add(+1) // incref
232 an.preds = append(an.preds, from)
233 }
234 // Increment unfinishedPreds even for root nodes (from==nil), so that their
235 // Action summaries are never cleared.
236 an.unfinishedPreds.Add(+1)
237 return an, nil
238 }
239
240 // For root packages, we run the enabled set of analyzers.
241 var roots []*analysisNode
242 for id := range pkgs {
243 root, err := makeNode(nil, id)
244 if err != nil {
245 return nil, err
246 }
247 root.analyzers = enabledAnalyzers
248 roots = append(roots, root)
249 }
250
251 // Progress reporting. If supported, gopls reports progress on analysis
252 // passes that are taking a long time.
253 maybeReport := func(completed int64) {}
254
255 // Enable progress reporting if enabled by the user
256 // and we have a capable reporter.
257 if reporter != nil && reporter.SupportsWorkDoneProgress() && s.Options().AnalysisProgressReporting {
258 var reportAfter = s.Options().ReportAnalysisProgressAfter // tests may set this to 0
259 const reportEvery = 1 * time.Second
260
261 ctx, cancel := context.WithCancel(ctx)
262 defer cancel()
263
264 var (
265 reportMu sync.Mutex
266 lastReport time.Time
267 wd *progress.WorkDone
268 )
269 defer func() {
270 reportMu.Lock()
271 defer reportMu.Unlock()
272
273 if wd != nil {
274 wd.End(ctx, "Done.") // ensure that the progress report exits
275 }
276 }()
277 maybeReport = func(completed int64) {
278 now := time.Now()
279 if now.Sub(start) < reportAfter {
280 return
281 }
282
283 reportMu.Lock()
284 defer reportMu.Unlock()
285
286 if wd == nil {
287 wd = reporter.Start(ctx, AnalysisProgressTitle, "", nil, cancel)
288 }
289
290 if now.Sub(lastReport) > reportEvery {
291 lastReport = now
292 // Trailing space is intentional: some LSP clients strip newlines.
293 msg := fmt.Sprintf(`Indexed %d/%d packages. (Set "analysisProgressReporting" to false to disable notifications.)`,
294 completed, len(nodes))
295 wd.Report(ctx, msg, float64(completed)/float64(len(nodes)))
296 }
297 }
298 }
299
300 // Execute phase: run leaves first, adding
301 // new nodes to the queue as they become leaves.
302 var g errgroup.Group
303
304 // Analysis is CPU-bound.
305 //
306 // Note: avoid g.SetLimit here: it makes g.Go stop accepting work, which
307 // prevents workers from enqeuing, and thus finishing, and thus allowing the
308 // group to make progress: deadlock.
309 limiter := make(chan unit, runtime.GOMAXPROCS(0))
310 var completed atomic.Int64
311
312 var enqueue func(*analysisNode)
313 enqueue = func(an *analysisNode) {
314 g.Go(func() error {
315 limiter <- unit{}
316 defer func() { <-limiter }()
317
318 // Check to see if we already have a valid cache key. If not, compute it.
319 //
320 // The snapshot field that memoizes keys depends on whether this key is
321 // for the analysis result including all enabled analyzer, or just facty analyzers.
322 var keys *persistent.Map[PackageID, file.Hash]
323 if _, root := pkgs[an.ph.mp.ID]; root {
324 keys = s.fullAnalysisKeys
325 } else {
326 keys = s.factyAnalysisKeys
327 }
328
329 // As keys is referenced by a snapshot field, it's guarded by s.mu.
330 s.mu.Lock()
331 key, keyFound := keys.Get(an.ph.mp.ID)
332 s.mu.Unlock()
333
334 if !keyFound {
335 key = an.cacheKey()
336 s.mu.Lock()
337 keys.Set(an.ph.mp.ID, key, nil)
338 s.mu.Unlock()
339 }
340
341 summary, err := an.runCached(ctx, key)
342 if err != nil {
343 return err // cancelled, or failed to produce a package
344 }
345
346 maybeReport(completed.Add(1))
347 // Copy fields onto the node. The summary itself (which may
348 // be shared via filecache or inFlightAnalyses) is not
349 // retained, so it is never mutated.
350 an.compiles = summary.Compiles
351 an.actions = summary.Actions
352
353 // Notify each waiting predecessor,
354 // and enqueue it when it becomes a leaf.
355 for _, pred := range an.preds {
356 if pred.unfinishedSuccs.Add(-1) == 0 { // decref
357 enqueue(pred)
358 }
359 }
360
361 // Notify each successor that we no longer need
362 // its action summaries, which hold Result values.
363 // After the last one, delete it, so that we
364 // free up large results such as SSA.
365 for _, succ := range an.succs {
366 succ.decrefPreds()
367 }
368 return nil
369 })
370 }
371 for _, leaf := range leaves {
372 enqueue(leaf)
373 }
374 if err := g.Wait(); err != nil {
375 return nil, err // cancelled, or failed to produce a package
376 }
377
378 // Inv: all root nodes now have a summary.
379 for _, root := range roots {
380 if root.actions == nil {
381 panic("root analysisNode has nil actions")
382 }
383 }
384
385 // Report diagnostics only from enabled actions that succeeded.
386 // Errors from creating or analyzing packages are ignored.
387 // Diagnostics are reported in the order of the analyzers argument.
388 //
389 // TODO(adonovan): ignoring action errors gives the caller no way
390 // to distinguish "there are no problems in this code" from
391 // "the code (or analyzers!) are so broken that we couldn't even
392 // begin the analysis you asked for".
393 // Even if current callers choose to discard the
394 // results, we should propagate the per-action errors.
395 var results []*Diagnostic
396 for _, root := range roots {
397 for _, a := range enabledAnalyzers {
398 // Skip analyzers that were added only to
399 // fulfil requirements of the original set.
400 srcAnalyzer, ok := toSrc[a]
401 if !ok {
402 // Although this 'skip' operation is logically sound,
403 // it is nonetheless surprising that its absence should
404 // cause #60909 since none of the analyzers currently added for
405 // requirements (e.g. ctrlflow, inspect, buildssa)
406 // is capable of reporting diagnostics.
407 if summary := root.actions[stableNames[a]]; summary != nil {
408 if n := len(summary.Diagnostics); n > 0 {
409 bug.Reportf("Internal error: got %d unexpected diagnostics from analyzer %s. This analyzer was added only to fulfil the requirements of the requested set of analyzers, and it is not expected that such analyzers report diagnostics. Please report this in issue #60909.", n, a)
410 }
411 }
412 continue
413 }
414
415 // Inv: root.actions is the successful result of run (via runCached).
416 summary, ok := root.actions[stableNames[a]]
417 if summary == nil {
418 panic(fmt.Sprintf("analyzeSummary.Actions[%q] = (nil, %t); got %v (#60551)",
419 stableNames[a], ok, root.actions))
420 }
421 if summary.Err != "" {
422 continue // action failed
423 }
424 for _, gobDiag := range summary.Diagnostics {
425 results = append(results, toSourceDiagnostic(srcAnalyzer, &gobDiag))
426 }
427 }
428 }
429 return results, nil
430 }
431
432 func (an *analysisNode) decrefPreds() {
433 if an.unfinishedPreds.Add(-1) == 0 {
434 an.actions = nil
435 }
436 }
437
438 // An analysisNode is a node in a doubly-linked DAG isomorphic to the
439 // import graph. Each node represents a single package, and the DAG
440 // represents a batch of analysis work done at once using a single
441 // realm of token.Pos or types.Object values.
442 //
443 // A complete DAG is created anew for each batch of analysis;
444 // subgraphs are not reused over time.
445 // TODO(rfindley): with cached keys we can typically avoid building the full
446 // DAG, so as an optimization we should rewrite this using a top-down
447 // traversal, rather than bottom-up.
448 //
449 // Each node's run method is called in parallel postorder. On success,
450 // its summary field is populated, either from the cache (hit), or by
451 // type-checking and analyzing syntax (miss).
452 type analysisNode struct {
453 parseCache *parseCache // shared parse cache
454 fsource file.Source // Snapshot.ReadFile, for use by Pass.ReadFile
455 batch *typeCheckBatch // type checking batch, for shared type checking
456 ph *packageHandle // package handle, for key and reachability analysis
457 analyzers []*analysis.Analyzer // set of analyzers to run
458 preds []*analysisNode // graph edges:
459 succs map[PackageID]*analysisNode // (preds -> self -> succs)
460 unfinishedSuccs atomic.Int32
461 unfinishedPreds atomic.Int32 // effectively an actions refcount
462 compiles bool // copied from analyzeSummary
463 actions actionMap // copied from analyzeSummary; nilled by decrefPreds
464 stableNames map[*analysis.Analyzer]string // cross-process stable names for Analyzers
465
466 summaryHashOnce sync.Once
467 _summaryHash file.Hash // memoized hash of data affecting dependents
468 }
469
470 func (an *analysisNode) String() string { return string(an.ph.mp.ID) }
471
472 // summaryHash computes the hash of the node summary, which may affect other
473 // nodes depending on this node.
474 //
475 // The result is memoized to avoid redundant work when analyzing multiple
476 // dependents.
477 func (an *analysisNode) summaryHash() file.Hash {
478 an.summaryHashOnce.Do(func() {
479 hasher := sha256.New()
480 fmt.Fprintf(hasher, "dep: %s\n", an.ph.mp.PkgPath)
481 fmt.Fprintf(hasher, "compiles: %t\n", an.compiles)
482
483 // action results: errors and facts
484 for name, summary := range moremaps.Sorted(an.actions) {
485 fmt.Fprintf(hasher, "action %s\n", name)
486 if summary.Err != "" {
487 fmt.Fprintf(hasher, "error %s\n", summary.Err)
488 } else {
489 fmt.Fprintf(hasher, "facts %s\n", summary.FactsHash)
490 // We can safely omit summary.diagnostics
491 // from the key since they have no downstream effect.
492 }
493 }
494 hasher.Sum(an._summaryHash[:0])
495 })
496 return an._summaryHash
497 }
498
499 // analyzeSummary is a gob-serializable summary of successfully
500 // applying a list of analyzers to a package.
501 type analyzeSummary struct {
502 Compiles bool // transitively free of list/parse/type errors
503 Actions actionMap // maps analyzer stablename to analysis results (*actionSummary)
504 }
505
506 // actionMap defines a stable Gob encoding for a map.
507 // TODO(adonovan): generalize and move to a library when we can use generics.
508 type actionMap map[string]*actionSummary
509
510 var (
511 _ gob.GobEncoder = (actionMap)(nil)
512 _ gob.GobDecoder = (*actionMap)(nil)
513 )
514
515 type actionsMapEntry struct {
516 K string
517 V *actionSummary
518 }
519
520 func (m actionMap) GobEncode() ([]byte, error) {
521 entries := make([]actionsMapEntry, 0, len(m))
522 for k, v := range m {
523 entries = append(entries, actionsMapEntry{k, v})
524 }
525 sort.Slice(entries, func(i, j int) bool {
526 return entries[i].K < entries[j].K
527 })
528 var buf bytes.Buffer
529 err := gob.NewEncoder(&buf).Encode(entries)
530 return buf.Bytes(), err
531 }
532
533 func (m *actionMap) GobDecode(data []byte) error {
534 var entries []actionsMapEntry
535 if err := gob.NewDecoder(bytes.NewReader(data)).Decode(&entries); err != nil {
536 return err
537 }
538 *m = make(actionMap, len(entries))
539 for _, e := range entries {
540 (*m)[e.K] = e.V
541 }
542 return nil
543 }
544
545 // actionSummary is a gob-serializable summary of one possibly failed analysis action.
546 // If Err is non-empty, the other fields are undefined.
547 type actionSummary struct {
548 Facts []byte // the encoded facts.Set
549 FactsHash file.Hash // hash(Facts)
550 Diagnostics []gobDiagnostic
551 Err string // "" => success
552 }
553
554 var (
555 // inFlightAnalyses records active analysis operations so that later requests
556 // can be satisfied by joining onto earlier requests that are still active.
557 //
558 // Note that persistent=false, so results are cleared once they are delivered
559 // to awaiting goroutines.
560 inFlightAnalyses = newFutureCache[file.Hash, *analyzeSummary](false)
561
562 // cacheLimit reduces parallelism of filecache updates.
563 // We allow more than typical GOMAXPROCS as it's a mix of CPU and I/O.
564 cacheLimit = make(chan unit, 32)
565 )
566
567 // runCached applies a list of analyzers (plus any others
568 // transitively required by them) to a package. It succeeds as long
569 // as it could produce a types.Package, even if there were direct or
570 // indirect list/parse/type errors, and even if all the analysis
571 // actions failed. It usually fails only if the package was unknown,
572 // a file was missing, or the operation was cancelled.
573 //
574 // The provided key is the cache key for this package.
575 func (an *analysisNode) runCached(ctx context.Context, key file.Hash) (*analyzeSummary, error) {
576 // At this point we have the action results (serialized packages and facts)
577 // of our immediate dependencies, and the metadata and content of this
578 // package.
579 //
580 // We now consult a global cache of promised results. If nothing material has
581 // changed, we'll make a hit in the shared cache.
582
583 // Access the cache. The returned summary is shared (via memCache or
584 // inFlightAnalyses) and must be treated as immutable; the caller
585 // copies its fields onto the analysisNode rather than retaining it.
586 const cacheKind = "analysis"
587 if summary, ok := filecache.GetOrFatal(cacheKind, key, analyzeSummaryCodec.Decode); ok {
588 return summary, nil // cache hit
589 }
590
591 // Cache miss: do the work.
592 return inFlightAnalyses.get(ctx, key, func(ctx context.Context) (*analyzeSummary, error) {
593 summary, err := an.run(ctx)
594 if err != nil {
595 return nil, err
596 }
597 go func() {
598 cacheLimit <- unit{} // acquire token
599 defer func() { <-cacheLimit }() // release token
600
601 data := analyzeSummaryCodec.Encode(summary)
602 if false {
603 log.Printf("Set key=%d value=%d id=%s\n", len(key), len(data), an.ph.mp.ID)
604 }
605 if err := filecache.Set(cacheKind, key, data); err != nil {
606 event.Error(ctx, "internal error updating analysis shared cache", err)
607 }
608 }()
609 return summary, nil
610 })
611 }
612
613 // cacheKey returns a cache key that is a cryptographic digest
614 // of the all the values that might affect type checking and analysis:
615 // the analyzer names, package metadata, names and contents of
616 // compiled Go files, and vdeps (successor) information
617 // (export data and facts).
618 func (an *analysisNode) cacheKey() file.Hash {
619 hasher := sha256.New()
620
621 // In principle, a key must be the hash of an
622 // unambiguous encoding of all the relevant data.
623 // If it's ambiguous, we risk collisions.
624
625 // analyzers
626 fmt.Fprintf(hasher, "analyzers: %d\n", len(an.analyzers))
627 for _, a := range an.analyzers {
628 fmt.Fprintln(hasher, a.Name)
629 }
630
631 // type checked package
632 fmt.Fprintf(hasher, "package: %s\n", an.ph.key)
633
634 // metadata errors: used for 'compiles' field
635 fmt.Fprintf(hasher, "errors: %d", len(an.ph.mp.Errors))
636
637 // vdeps, in PackageID order
638 for _, vdep := range moremaps.Sorted(an.succs) {
639 hash := vdep.summaryHash()
640 hasher.Write(hash[:])
641 }
642
643 var hash file.Hash
644 hasher.Sum(hash[:0])
645 return hash
646 }
647
648 // run implements the cache-miss case.
649 // This function does not access the snapshot.
650 //
651 // Postcondition: on success, the analyzeSummary.Actions
652 // key set is {a.Name for a in analyzers}.
653 func (an *analysisNode) run(ctx context.Context) (*analyzeSummary, error) {
654 // Type-check the package syntax.
655 pkg, err := an.typeCheck(ctx)
656 if err != nil {
657 return nil, err
658 }
659
660 // Poll cancellation state.
661 if err := ctx.Err(); err != nil {
662 return nil, err
663 }
664
665 // -- analysis --
666
667 // Build action graph for this package.
668 // Each graph node (action) is one unit of analysis.
669 actions := make(map[*analysis.Analyzer]*action)
670 var mkAction func(a *analysis.Analyzer) *action
671 mkAction = func(a *analysis.Analyzer) *action {
672 act, ok := actions[a]
673 if !ok {
674 var hdeps []*action
675 for _, req := range a.Requires {
676 hdeps = append(hdeps, mkAction(req))
677 }
678 act = &action{
679 a: a,
680 fsource: an.fsource,
681 stableName: an.stableNames[a],
682 pkg: pkg,
683 vdeps: an.succs,
684 hdeps: hdeps,
685 }
686 actions[a] = act
687 }
688 return act
689 }
690
691 // Build actions for initial package.
692 var roots []*action
693 for _, a := range an.analyzers {
694 roots = append(roots, mkAction(a))
695 }
696
697 // Execute the graph in parallel.
698 execActions(ctx, roots)
699 // Inv: each root's summary is set (whether success or error).
700
701 // Don't return (or cache) the result in case of cancellation.
702 if err := ctx.Err(); err != nil {
703 return nil, err // cancelled
704 }
705
706 // Return summaries only for the requested actions.
707 summaries := make(map[string]*actionSummary)
708 for _, root := range roots {
709 if root.summary == nil {
710 panic("root has nil action.summary (#60551)")
711 }
712 summaries[root.stableName] = root.summary
713 }
714
715 return &analyzeSummary{
716 Compiles: pkg.compiles,
717 Actions: summaries,
718 }, nil
719 }
720
721 func (an *analysisNode) typeCheck(ctx context.Context) (*analysisPackage, error) {
722 ppkg, err := an.batch.getPackage(ctx, an.ph)
723 if err != nil {
724 return nil, err
725 }
726
727 compiles := len(an.ph.mp.Errors) == 0 && len(ppkg.TypeErrors()) == 0
728
729 // The go/analysis framework implicitly promises to deliver
730 // trees with legacy ast.Object resolution. Do that now.
731 files := make([]*ast.File, len(ppkg.CompiledGoFiles()))
732 for i, p := range ppkg.CompiledGoFiles() {
733 p.Resolve()
734 files[i] = p.File
735 if p.ParseErr != nil {
736 compiles = false // parse error
737 }
738 }
739
740 // The fact decoder needs a means to look up a Package by path.
741 pkgLookup := typesLookup(ppkg.Types())
742 factsDecoder := facts.NewDecoderFunc(ppkg.Types(), func(path string) *types.Package {
743 // Note: Decode is called concurrently, and thus so is this function.
744
745 // Does the fact relate to a package reachable through imports?
746 if !an.ph.reachable.MayContain(path) {
747 return nil
748 }
749
750 return pkgLookup(path)
751 })
752
753 var typeErrors []types.Error
754 filterErrors:
755 for _, typeError := range ppkg.TypeErrors() {
756 // Suppress type errors in files with parse errors
757 // as parser recovery can be quite lossy (#59888).
758 for _, p := range ppkg.CompiledGoFiles() {
759 if p.ParseErr != nil && astutil.NodeContainsPos(p.File, typeError.Pos) {
760 continue filterErrors
761 }
762 }
763 typeErrors = append(typeErrors, typeError)
764 }
765
766 for _, vdep := range an.succs {
767 if !vdep.compiles {
768 compiles = false // transitive error
769 }
770 }
771
772 return &analysisPackage{
773 pkg: ppkg,
774 files: files,
775 typeErrors: typeErrors,
776 compiles: compiles,
777 factsDecoder: factsDecoder,
778 }, nil
779 }
780
781 // typesLookup implements a concurrency safe depth-first traversal searching
782 // imports of pkg for a given package path.
783 func typesLookup(pkg *types.Package) func(string) *types.Package {
784 var (
785 mu sync.Mutex // guards impMap and pending
786
787 // impMap memoizes the lookup of package paths.
788 impMap = map[string]*types.Package{
789 pkg.Path(): pkg,
790 }
791 // pending is a FIFO queue of packages that have yet to have their
792 // dependencies fully scanned.
793 // Invariant: all entries in pending are already mapped in impMap.
794 pending = []*types.Package{pkg}
795 )
796
797 // search scans children the next package in pending, looking for pkgPath.
798 search := func(pkgPath string) (sought *types.Package, numPending int) {
799 mu.Lock()
800 defer mu.Unlock()
801
802 if p, ok := impMap[pkgPath]; ok {
803 return p, len(pending)
804 }
805
806 if len(pending) == 0 {
807 return nil, 0
808 }
809
810 pkg := pending[0]
811 pending = pending[1:]
812 for _, dep := range pkg.Imports() {
813 depPath := dep.Path()
814 if _, ok := impMap[depPath]; ok {
815 continue
816 }
817 impMap[depPath] = dep
818
819 pending = append(pending, dep)
820 if depPath == pkgPath {
821 // Don't return early; finish processing pkg's deps.
822 sought = dep
823 }
824 }
825 return sought, len(pending)
826 }
827
828 return func(pkgPath string) *types.Package {
829 p, np := (*types.Package)(nil), 1
830 for p == nil && np > 0 {
831 p, np = search(pkgPath)
832 }
833 return p
834 }
835 }
836
837 // analysisPackage contains information about a package, including
838 // syntax trees, used transiently during its type-checking and analysis.
839 type analysisPackage struct {
840 pkg *Package
841 files []*ast.File // same as parsed[i].File
842 typeErrors []types.Error // filtered type checker errors
843 compiles bool // package is transitively free of list/parse/type errors
844 factsDecoder *facts.Decoder
845 }
846
847 // An action represents one unit of analysis work: the application of
848 // one analysis to one package. Actions form a DAG, both within a
849 // package (as different analyzers are applied, either in sequence or
850 // parallel), and across packages (as dependencies are analyzed).
851 type action struct {
852 once sync.Once
853 a *analysis.Analyzer
854 fsource file.Source // Snapshot.ReadFile, for Pass.ReadFile
855 stableName string // cross-process stable name of analyzer
856 pkg *analysisPackage
857 hdeps []*action // horizontal dependencies
858 vdeps map[PackageID]*analysisNode // vertical dependencies
859
860 // results of action.exec():
861 result any // result of Run function, of type a.ResultType
862 summary *actionSummary
863 err error
864 }
865
866 func (act *action) String() string {
867 return fmt.Sprintf("%s@%s", act.a.Name, act.pkg.pkg.metadata.ID)
868 }
869
870 // execActions executes a set of action graph nodes in parallel.
871 // Postcondition: each action.summary is set, even in case of error.
872 func execActions(ctx context.Context, actions []*action) {
873 var wg sync.WaitGroup
874 for _, act := range actions {
875 wg.Go(func() {
876 act.once.Do(func() {
877 execActions(ctx, act.hdeps) // analyze "horizontal" dependencies
878 act.result, act.summary, act.err = act.exec(ctx)
879 if act.err != nil {
880 act.summary = &actionSummary{Err: act.err.Error()}
881 // TODO(adonovan): suppress logging. But
882 // shouldn't the root error's causal chain
883 // include this information?
884 if false { // debugging
885 log.Printf("act.exec(%v) failed: %v", act, act.err)
886 }
887 }
888 })
889 if act.summary == nil {
890 panic("nil action.summary (#60551)")
891 }
892 })
893 }
894 wg.Wait()
895 }
896
897 // exec defines the execution of a single action.
898 // It returns the (ephemeral) result of the analyzer's Run function,
899 // along with its (serializable) facts and diagnostics.
900 // Or it returns an error if the analyzer did not run to
901 // completion and deliver a valid result.
902 func (act *action) exec(ctx context.Context) (any, *actionSummary, error) {
903 analyzer := act.a
904 apkg := act.pkg
905
906 hasFacts := len(analyzer.FactTypes) > 0
907
908 // Report an error if any action dependency (vertical or horizontal) failed.
909 // To avoid long error messages describing chains of failure,
910 // we return the dependencies' error' unadorned.
911 if hasFacts {
912 // TODO(adonovan): use deterministic order.
913 for _, vdep := range act.vdeps {
914 if summ := vdep.actions[act.stableName]; summ.Err != "" {
915 return nil, nil, errors.New(summ.Err)
916 }
917 }
918 }
919 for _, dep := range act.hdeps {
920 if dep.err != nil {
921 return nil, nil, dep.err
922 }
923 }
924 // Inv: all action dependencies succeeded.
925
926 // Were there list/parse/type errors that might prevent analysis?
927 if !apkg.compiles && !analyzer.RunDespiteErrors {
928 return nil, nil, fmt.Errorf("skipping analysis %q because package %q does not compile", analyzer.Name, apkg.pkg.metadata.ID)
929 }
930 // Inv: package is well-formed enough to proceed with analysis.
931
932 if false { // debugging
933 log.Println("action.exec", act)
934 }
935
936 // Gather analysis Result values from horizontal dependencies.
937 inputs := make(map[*analysis.Analyzer]any)
938 for _, dep := range act.hdeps {
939 inputs[dep.a] = dep.result
940 }
941
942 // TODO(adonovan): opt: facts.Set works but it may be more
943 // efficient to fork and tailor it to our precise needs.
944 //
945 // We've already sharded the fact encoding by action
946 // so that it can be done in parallel.
947 // We could eliminate locking.
948 // We could also dovetail more closely with the export data
949 // decoder to obtain a more compact representation of
950 // packages and objects (e.g. its internal IDs, instead
951 // of PkgPaths and objectpaths.)
952 // More importantly, we should avoid re-export of
953 // facts that related to objects that are discarded
954 // by "deep" export data. Better still, use a "shallow" approach.
955
956 // Read and decode analysis facts for each direct import.
957 factset, err := apkg.factsDecoder.Decode(func(pkgPath string) ([]byte, error) {
958 if !hasFacts {
959 return nil, nil // analyzer doesn't use facts, so no vdeps
960 }
961
962 // Package.Imports() may contain a fake "C" package. Ignore it.
963 if pkgPath == "C" {
964 return nil, nil
965 }
966
967 id, ok := apkg.pkg.metadata.DepsByPkgPath[PackagePath(pkgPath)]
968 if !ok {
969 // This may mean imp was synthesized by the type
970 // checker because it failed to import it for any reason
971 // (e.g. bug processing export data; metadata ignoring
972 // a cycle-forming import).
973 // In that case, the fake package's imp.Path
974 // is set to the failed importPath (and thus
975 // it may lack a "vendor/" prefix).
976 //
977 // For now, silently ignore it on the assumption
978 // that the error is already reported elsewhere.
979 // return nil, fmt.Errorf("missing metadata")
980 return nil, nil
981 }
982
983 vdep := act.vdeps[id]
984 if vdep == nil {
985 return nil, bug.Errorf("internal error in %s: missing vdep for id=%s", apkg.pkg.Types().Path(), id)
986 }
987
988 return vdep.actions[act.stableName].Facts, nil
989 })
990 if err != nil {
991 return nil, nil, fmt.Errorf("internal error decoding analysis facts: %w", err)
992 }
993
994 // TODO(adonovan): make Export*Fact panic rather than discarding
995 // undeclared fact types, so that we discover bugs in analyzers.
996 factFilter := make(map[reflect.Type]bool)
997 for _, f := range analyzer.FactTypes {
998 factFilter[reflect.TypeOf(f)] = true
999 }
1000
1001 // Now run the (pkg, analyzer) action.
1002 var diagnostics []gobDiagnostic
1003
1004 pass := &analysis.Pass{
1005 Analyzer: analyzer,
1006 Fset: apkg.pkg.FileSet(),
1007 Files: apkg.files,
1008 OtherFiles: nil, // since gopls doesn't handle non-Go (e.g. asm) files
1009 IgnoredFiles: nil, // zero-config gopls should analyze these files in another view
1010 Pkg: apkg.pkg.Types(),
1011 TypesInfo: apkg.pkg.TypesInfo(),
1012 TypesSizes: apkg.pkg.TypesSizes(),
1013 TypeErrors: apkg.typeErrors,
1014 Module: analysisModuleFromPackagesModule(apkg.pkg.metadata.Module),
1015 ResultOf: inputs,
1016 Report: func(d analysis.Diagnostic) {
1017 // Assert that SuggestedFixes are well formed.
1018 //
1019 // ValidateFixes allows a fix.End to be slightly beyond
1020 // EOF to avoid spurious assertions when reporting
1021 // fixes as the end of truncated files; see #71659.
1022 if err := driverutil.ValidateFixes(apkg.pkg.FileSet(), analyzer, d.SuggestedFixes); err != nil {
1023 bug.Reportf("invalid SuggestedFixes: %v", err)
1024 d.SuggestedFixes = nil
1025 }
1026 diagnostic, err := toGobDiagnostic(apkg.pkg, analyzer, d)
1027 if err != nil {
1028 // Don't bug.Report here: these errors all originate in
1029 // posToLocation, and we can more accurately discriminate
1030 // severe errors from benign ones in that function.
1031 event.Error(ctx, fmt.Sprintf("internal error converting diagnostic from analyzer %q", analyzer.Name), err)
1032 return
1033 }
1034 diagnostics = append(diagnostics, diagnostic)
1035 },
1036 ImportObjectFact: factset.ImportObjectFact,
1037 ExportObjectFact: factset.ExportObjectFact,
1038 ImportPackageFact: factset.ImportPackageFact,
1039 ExportPackageFact: factset.ExportPackageFact,
1040 AllObjectFacts: func() []analysis.ObjectFact { return factset.AllObjectFacts(factFilter) },
1041 AllPackageFacts: func() []analysis.PackageFact { return factset.AllPackageFacts(factFilter) },
1042 }
1043
1044 pass.ReadFile = func(filename string) ([]byte, error) {
1045 // Read file from snapshot, to ensure reads are consistent.
1046 //
1047 // TODO(adonovan): make the dependency analysis sound by
1048 // incorporating these additional files into the analysis
1049 // hash. This requires either (a) preemptively reading and
1050 // hashing a potentially large number of mostly irrelevant
1051 // files; or (b) some kind of dynamic dependency discovery
1052 // system like used in Bazel for C++ headers. Neither entices.
1053 if err := driverutil.CheckReadable(pass, filename); err != nil {
1054 return nil, err
1055 }
1056 h, err := act.fsource.ReadFile(ctx, protocol.URIFromPath(filename))
1057 if err != nil {
1058 return nil, err
1059 }
1060 content, err := h.Content()
1061 if err != nil {
1062 return nil, err // file doesn't exist
1063 }
1064 return slices.Clone(content), nil // follow ownership of os.ReadFile
1065 }
1066
1067 // Recover from panics (only) within the analyzer logic.
1068 // (Use an anonymous function to limit the recover scope.)
1069 var result any
1070 func() {
1071 start := time.Now()
1072 defer func() {
1073 if r := recover(); r != nil {
1074 // An Analyzer panicked, likely due to a bug.
1075 //
1076 // In general we want to discover and fix such panics quickly,
1077 // so we don't suppress them, but some bugs in third-party
1078 // analyzers cannot be quickly fixed, so we use an allowlist
1079 // to suppress panics.
1080 const strict = true
1081 if strict && bug.PanicOnBugs &&
1082 analyzer.Name != "buildir" { // see https://github.com/dominikh/go-tools/issues/1343
1083 // Uncomment this when debugging suspected failures
1084 // in the driver, not the analyzer.
1085 if false {
1086 debug.SetTraceback("all") // show all goroutines
1087 }
1088 panic(r)
1089 } else {
1090 // In production, suppress the panic and press on.
1091 err = fmt.Errorf("analysis %s for package %s panicked: %v", analyzer.Name, pass.Pkg.Path(), r)
1092 }
1093 }
1094
1095 // Accumulate running time for each checker.
1096 analyzerRunTimesMu.Lock()
1097 analyzerRunTimes[analyzer] += time.Since(start)
1098 analyzerRunTimesMu.Unlock()
1099 }()
1100
1101 result, err = pass.Analyzer.Run(pass)
1102 }()
1103 if err != nil {
1104 return nil, nil, err
1105 }
1106
1107 if got, want := reflect.TypeOf(result), pass.Analyzer.ResultType; got != want {
1108 return nil, nil, bug.Errorf(
1109 "internal error: on package %s, analyzer %s returned a result of type %v, but declared ResultType %v",
1110 pass.Pkg.Path(), pass.Analyzer, got, want)
1111 }
1112
1113 // Disallow Export*Fact calls after Run.
1114 // (A panic means the Analyzer is abusing concurrency.)
1115 pass.ExportObjectFact = func(obj types.Object, fact analysis.Fact) {
1116 panic(fmt.Sprintf("%v: Pass.ExportObjectFact(%s, %T) called after Run", act, obj, fact))
1117 }
1118 pass.ExportPackageFact = func(fact analysis.Fact) {
1119 panic(fmt.Sprintf("%v: Pass.ExportPackageFact(%T) called after Run", act, fact))
1120 }
1121
1122 factsdata := factset.Encode()
1123 return result, &actionSummary{
1124 Diagnostics: diagnostics,
1125 Facts: factsdata,
1126 FactsHash: file.HashOf(factsdata),
1127 }, nil
1128 }
1129
1130 var (
1131 analyzerRunTimesMu sync.Mutex
1132 analyzerRunTimes = make(map[*analysis.Analyzer]time.Duration)
1133 )
1134
1135 type LabelDuration struct {
1136 Label string
1137 Duration time.Duration
1138 }
1139
1140 // AnalyzerRunTimes returns the accumulated time spent in each Analyzer's
1141 // Run function since process start, in descending order.
1142 func AnalyzerRunTimes() []LabelDuration {
1143 analyzerRunTimesMu.Lock()
1144 defer analyzerRunTimesMu.Unlock()
1145
1146 slice := make([]LabelDuration, 0, len(analyzerRunTimes))
1147 for a, t := range analyzerRunTimes {
1148 slice = append(slice, LabelDuration{Label: a.Name, Duration: t})
1149 }
1150 sort.Slice(slice, func(i, j int) bool {
1151 return slice[i].Duration > slice[j].Duration
1152 })
1153 return slice
1154 }
1155
1156 // requiredAnalyzers returns the transitive closure of required analyzers in preorder.
1157 func requiredAnalyzers(analyzers []*analysis.Analyzer) []*analysis.Analyzer {
1158 var result []*analysis.Analyzer
1159 seen := make(map[*analysis.Analyzer]bool)
1160 var visitAll func([]*analysis.Analyzer)
1161 visitAll = func(analyzers []*analysis.Analyzer) {
1162 for _, a := range analyzers {
1163 if !seen[a] {
1164 seen[a] = true
1165 result = append(result, a)
1166 visitAll(a.Requires)
1167 }
1168 }
1169 }
1170 visitAll(analyzers)
1171 return result
1172 }
1173
1174 var analyzeSummaryCodec = frob.CodecFor[*analyzeSummary]()
1175
1176 // -- data types for serialization of analysis.Diagnostic and golang.Diagnostic --
1177
1178 // (The name says gob but we use frob.)
1179 var diagnosticsCodec = frob.CodecFor[[]gobDiagnostic]()
1180
1181 type gobDiagnostic struct {
1182 Location protocol.Location
1183 Severity protocol.DiagnosticSeverity
1184 Code string
1185 CodeHref string
1186 Source string
1187 Message string
1188 SuggestedFixes []gobSuggestedFix
1189 Related []gobRelatedInformation
1190 Tags []protocol.DiagnosticTag
1191 }
1192
1193 type gobRelatedInformation struct {
1194 Location protocol.Location
1195 Message string
1196 }
1197
1198 type gobSuggestedFix struct {
1199 Message string
1200 TextEdits []gobTextEdit
1201 Command *gobCommand
1202 ActionKind protocol.CodeActionKind
1203 }
1204
1205 type gobCommand struct {
1206 Title string
1207 Command string
1208 Arguments []json.RawMessage
1209 }
1210
1211 type gobTextEdit struct {
1212 Location protocol.Location
1213 NewText []byte
1214 }
1215
1216 // toGobDiagnostic converts an analysis.Diagnosic to a serializable gobDiagnostic,
1217 // which requires expanding token.Pos positions into protocol.Location form.
1218 func toGobDiagnostic(pkg *Package, a *analysis.Analyzer, diag analysis.Diagnostic) (gobDiagnostic, error) {
1219 var fixes []gobSuggestedFix
1220 for _, fix := range diag.SuggestedFixes {
1221 var gobEdits []gobTextEdit
1222 for _, textEdit := range fix.TextEdits {
1223 loc, err := diagnosticPosToLocation(pkg, false, textEdit.Pos, textEdit.End)
1224 if err != nil {
1225 return gobDiagnostic{}, fmt.Errorf("in SuggestedFixes: %w", err)
1226 }
1227 gobEdits = append(gobEdits, gobTextEdit{
1228 Location: loc,
1229 NewText: textEdit.NewText,
1230 })
1231 }
1232 fixes = append(fixes, gobSuggestedFix{
1233 Message: fix.Message,
1234 TextEdits: gobEdits,
1235 })
1236 }
1237
1238 var related []gobRelatedInformation
1239 for _, r := range diag.Related {
1240 // The position of RelatedInformation may be
1241 // within another (dependency) package.
1242 const allowDeps = true
1243 loc, err := diagnosticPosToLocation(pkg, allowDeps, r.Pos, r.End)
1244 if err != nil {
1245 return gobDiagnostic{}, fmt.Errorf("in Related: %w", err)
1246 }
1247 related = append(related, gobRelatedInformation{
1248 Location: loc,
1249 Message: r.Message,
1250 })
1251 }
1252
1253 loc, err := diagnosticPosToLocation(pkg, false, diag.Pos, diag.End)
1254 if err != nil {
1255 return gobDiagnostic{}, err
1256 }
1257
1258 // The Code column of VSCode's Problems table renders this
1259 // information as "Source(Code)" where code is a link to CodeHref.
1260 // (The code field must be nonempty for anything to appear.)
1261 diagURL := effectiveURL(a, diag)
1262 code := "default"
1263 if diag.Category != "" {
1264 code = diag.Category
1265 }
1266
1267 return gobDiagnostic{
1268 Location: loc,
1269 // Severity for analysis diagnostics is dynamic,
1270 // based on user configuration per analyzer.
1271 Code: code,
1272 CodeHref: diagURL,
1273 Source: a.Name,
1274 Message: diag.Message,
1275 SuggestedFixes: fixes,
1276 Related: related,
1277 // Analysis diagnostics do not contain tags.
1278 }, nil
1279 }
1280
1281 // diagnosticPosToLocation converts from token.Pos to protocol form, in the
1282 // context of the specified package and, optionally, its dependencies.
1283 func diagnosticPosToLocation(pkg *Package, allowDeps bool, start, end token.Pos) (protocol.Location, error) {
1284 if end == token.NoPos {
1285 end = start
1286 }
1287
1288 fset := pkg.FileSet()
1289 tokFile := fset.File(start)
1290
1291 // Find existing mapper by file name.
1292 // (Don't require an exact token.File match
1293 // as the analyzer may have re-parsed the file.)
1294 var (
1295 mapper *protocol.Mapper
1296 fixed bool
1297 )
1298 for _, p := range pkg.CompiledGoFiles() {
1299 if p.Tok.Name() == tokFile.Name() {
1300 mapper = p.Mapper
1301 fixed = p.Fixed() // suppress some assertions after parser recovery
1302 break
1303 }
1304 }
1305 // TODO(adonovan): search pkg.AsmFiles too; see #71754.
1306 if mapper != nil {
1307 // debugging #64547
1308 fileStart := token.Pos(tokFile.Base())
1309 fileEnd := fileStart + token.Pos(tokFile.Size())
1310 if start < fileStart {
1311 if !fixed {
1312 bug.Reportf("start < start of file")
1313 }
1314 start = fileStart
1315 }
1316 if end < start {
1317 // This can happen if End is zero (#66683)
1318 // or a small positive displacement from zero
1319 // due to recursive Node.End() computation.
1320 // This usually arises from poor parser recovery
1321 // of an incomplete term at EOF.
1322 if !fixed {
1323 bug.Reportf("end < start of file")
1324 }
1325 end = fileEnd
1326 }
1327 if end > fileEnd+1 {
1328 if !fixed {
1329 bug.Reportf("end > end of file + 1")
1330 }
1331 end = fileEnd
1332 }
1333
1334 return mapper.PosLocation(tokFile, start, end)
1335 }
1336
1337 // Inv: the positions are not within this package.
1338
1339 if allowDeps {
1340 // Positions in Diagnostic.RelatedInformation may belong to a
1341 // dependency package. We cannot accurately map them to
1342 // protocol.Location coordinates without a Mapper for the
1343 // relevant file, but none exists if the file was loaded from
1344 // export data, and we have no means (Snapshot) of loading it.
1345 //
1346 // So, fall back to approximate conversion to UTF-16:
1347 // for non-ASCII text, the column numbers may be wrong.
1348 var (
1349 startPosn = safetoken.StartPosition(fset, start)
1350 endPosn = safetoken.EndPosition(fset, end)
1351 )
1352 return protocol.Location{
1353 URI: protocol.URIFromPath(startPosn.Filename),
1354 Range: protocol.Range{
1355 Start: protocol.Position{
1356 Line: uint32(startPosn.Line - 1),
1357 Character: uint32(startPosn.Column - 1),
1358 },
1359 End: protocol.Position{
1360 Line: uint32(endPosn.Line - 1),
1361 Character: uint32(endPosn.Column - 1),
1362 },
1363 },
1364 }, nil
1365 }
1366
1367 // The start position was not among the package's parsed
1368 // Go files, indicating that the analyzer added new files
1369 // to the FileSet.
1370 //
1371 // For example, the cgocall analyzer re-parses and
1372 // type-checks some of the files in a special environment;
1373 // and asmdecl and other low-level runtime analyzers call
1374 // ReadFile to parse non-Go files.
1375 // (This is a supported feature, documented at go/analysis.)
1376 //
1377 // In principle these files could be:
1378 //
1379 // - OtherFiles (non-Go files such as asm).
1380 // However, we set Pass.OtherFiles=[] because
1381 // gopls won't service "diagnose" requests
1382 // for non-Go files, so there's no point
1383 // reporting diagnostics in them.
1384 //
1385 // - IgnoredFiles (files tagged for other configs).
1386 // However, we set Pass.IgnoredFiles=[] because,
1387 // in most cases, zero-config gopls should create
1388 // another view that covers these files.
1389 //
1390 // - Referents of //line directives, as in cgo packages.
1391 // The file names in this case are not known a priori.
1392 // gopls generally tries to avoid honoring line directives,
1393 // but analyzers such as cgocall may honor them.
1394 //
1395 // In short, it's unclear how this can be reached
1396 // other than due to an analyzer bug.
1397
1398 return protocol.Location{}, bug.Errorf("diagnostic location is not among files of package: %s", tokFile.Name())
1399 }
1400
1401 // effectiveURL computes the effective URL of diag,
1402 // using the algorithm specified at Diagnostic.URL.
1403 func effectiveURL(a *analysis.Analyzer, diag analysis.Diagnostic) string {
1404 u := diag.URL
1405 if u == "" && diag.Category != "" {
1406 u = "#" + diag.Category
1407 }
1408 if base, err := urlpkg.Parse(a.URL); err == nil {
1409 if rel, err := urlpkg.Parse(u); err == nil {
1410 u = base.ResolveReference(rel).String()
1411 }
1412 }
1413 return u
1414 }
1415
1416 // stableName returns a name for the analyzer that is unique and
1417 // stable across address spaces.
1418 //
1419 // Analyzer names are not unique. For example, gopls includes
1420 // both x/tools/passes/nilness and staticcheck/nilness.
1421 // For serialization, we must assign each analyzer a unique identifier
1422 // that two gopls processes accessing the cache can agree on.
1423 func stableName(a *analysis.Analyzer) string {
1424 // Incorporate the file and line of the analyzer's Run function.
1425 addr := reflect.ValueOf(a.Run).Pointer()
1426 fn := runtime.FuncForPC(addr)
1427 file, line := fn.FileLine(addr)
1428
1429 // It is tempting to use just a.Name as the stable name when
1430 // it is unique, but making them always differ helps avoid
1431 // name/stablename confusion.
1432 return fmt.Sprintf("%s(%s:%d)", a.Name, filepath.Base(file), line)
1433 }
1434
1435 // analysisModuleFromPackagesModule converts a packages.Module to an analysis.Module.
1436 func analysisModuleFromPackagesModule(mod *packages.Module) *analysis.Module {
1437 if mod == nil {
1438 return nil
1439 }
1440
1441 var modErr *analysis.ModuleError
1442 if mod.Error != nil {
1443 modErr = &analysis.ModuleError{
1444 Err: mod.Error.Err,
1445 }
1446 }
1447
1448 return &analysis.Module{
1449 Path: mod.Path,
1450 Version: mod.Version,
1451 Replace: analysisModuleFromPackagesModule(mod.Replace),
1452 Time: mod.Time,
1453 Main: mod.Main,
1454 Indirect: mod.Indirect,
1455 Dir: mod.Dir,
1456 GoMod: mod.GoMod,
1457 GoVersion: mod.GoVersion,
1458 Error: modErr,
1459 }
1460 }