Debian Codegraph @

gopls/internal/cache/symbols.go

raw symbols SCIP
1 // Copyright 2021 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 import (
8 "context"
9 "crypto/sha256"
10 "fmt"
11 "go/parser"
12 "go/token"
13 "runtime"
14
15 "golang.org/x/sync/errgroup"
16 "golang.org/x/tools/gopls/internal/cache/metadata"
17 "golang.org/x/tools/gopls/internal/cache/parsego"
18 "golang.org/x/tools/gopls/internal/cache/symbols"
19 "golang.org/x/tools/gopls/internal/file"
20 "golang.org/x/tools/gopls/internal/filecache"
21 "golang.org/x/tools/gopls/internal/protocol"
22 "golang.org/x/tools/gopls/internal/util/bug"
23 "golang.org/x/tools/internal/event"
24 )
25
26 // Symbols extracts and returns symbol information for every file contained in
27 // a loaded package. It awaits snapshot loading.
28 //
29 // If workspaceOnly is set, this only includes symbols from files in a
30 // workspace package. Otherwise, it returns symbols from all loaded packages.
31 func (s *Snapshot) Symbols(ctx context.Context, ids ...PackageID) ([]*symbols.Package, error) {
32 meta := s.MetadataGraph()
33
34 res := make([]*symbols.Package, len(ids))
35 var g errgroup.Group
36 g.SetLimit(runtime.GOMAXPROCS(-1)) // symbolizing is cpu bound
37 for i, id := range ids {
38 g.Go(func() error {
39 mp := meta.Packages[id]
40 if mp == nil {
41 return bug.Errorf("missing metadata for %q", id)
42 }
43
44 key, fhs, err := symbolKey(ctx, mp, s)
45 if err != nil {
46 return err
47 }
48
49 if pkg, ok := filecache.GetOrFatal(symbolsKind, key, symbols.Decode); ok {
50 res[i] = pkg
51 return nil
52 }
53
54 pgfs, err := s.view.parseCache.parseFiles(ctx, token.NewFileSet(), parsego.Full&^parser.ParseComments, false, fhs...)
55 if err != nil {
56 return err
57 }
58 pkg := symbols.New(pgfs)
59
60 // Store the resulting data in the cache.
61 go func() {
62 data := pkg.Encode()
63 if err := filecache.Set(symbolsKind, key, data); err != nil {
64 event.Error(ctx, fmt.Sprintf("storing symbol data for %s", id), err)
65 }
66 }()
67
68 res[i] = pkg
69 return nil
70 })
71 }
72
73 return res, g.Wait()
74 }
75
76 func symbolKey(ctx context.Context, mp *metadata.Package, fs file.Source) (file.Hash, []file.Handle, error) {
77 seen := make(map[protocol.DocumentURI]bool)
78 var fhs []file.Handle
79 for _, list := range [][]protocol.DocumentURI{mp.GoFiles, mp.CompiledGoFiles} {
80 for _, uri := range list {
81 if !seen[uri] {
82 seen[uri] = true
83 fh, err := fs.ReadFile(ctx, uri)
84 if err != nil {
85 return file.Hash{}, nil, err // context cancelled
86 }
87 fhs = append(fhs, fh)
88 }
89 }
90 }
91
92 hasher := sha256.New()
93 fmt.Fprintf(hasher, "symbols: %s\n", mp.PkgPath)
94 fmt.Fprintf(hasher, "files: %d\n", len(fhs))
95 for _, fh := range fhs {
96 fmt.Fprintln(hasher, fh.Identity())
97 }
98 var hash file.Hash
99 hasher.Sum(hash[:0])
100 return hash, fhs, nil
101 }