Debian Codegraph @

gopls/internal/golang/symbols.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 golang
6
7 import (
8 "context"
9 "fmt"
10 "go/ast"
11 "go/token"
12 "go/types"
13
14 "golang.org/x/tools/gopls/internal/cache"
15 "golang.org/x/tools/gopls/internal/cache/parsego"
16 "golang.org/x/tools/gopls/internal/file"
17 "golang.org/x/tools/gopls/internal/protocol"
18 "golang.org/x/tools/gopls/internal/protocol/command"
19 "golang.org/x/tools/internal/astutil"
20 "golang.org/x/tools/internal/event"
21 )
22
23 func DocumentSymbols(ctx context.Context, snapshot *cache.Snapshot, fh file.Handle) ([]protocol.DocumentSymbol, error) {
24 ctx, done := event.Start(ctx, "golang.DocumentSymbols")
25 defer done()
26
27 pgf, err := snapshot.ParseGo(ctx, fh, parsego.Full)
28 if err != nil {
29 return nil, fmt.Errorf("getting file for DocumentSymbols: %w", err)
30 }
31
32 // Build symbols for file declarations. When encountering a declaration with
33 // errors (typically because positions are invalid), we skip the declaration
34 // entirely. VS Code fails to show any symbols if one of the top-level
35 // symbols is missing position information.
36 var symbols []protocol.DocumentSymbol
37 for _, decl := range pgf.File.Decls {
38 switch decl := decl.(type) {
39 case *ast.FuncDecl:
40 if decl.Name.Name == "_" {
41 continue
42 }
43 fs, err := funcSymbol(pgf.Mapper, pgf.Tok, decl)
44 if err == nil {
45 // If function is a method, prepend the type of the method.
46 if decl.Recv != nil && len(decl.Recv.List) > 0 {
47 fs.Name = fmt.Sprintf("(%s).%s", types.ExprString(decl.Recv.List[0].Type), fs.Name)
48 }
49 symbols = append(symbols, fs)
50 }
51 case *ast.GenDecl:
52 for _, spec := range decl.Specs {
53 switch spec := spec.(type) {
54 case *ast.TypeSpec:
55 if spec.Name.Name == "_" {
56 continue
57 }
58 ts, err := typeSymbol(pgf.Mapper, pgf.Tok, spec)
59 if err == nil {
60 symbols = append(symbols, ts)
61 }
62 case *ast.ValueSpec:
63 for _, name := range spec.Names {
64 if name.Name == "_" {
65 continue
66 }
67 vs, err := varSymbol(pgf.Mapper, pgf.Tok, spec, name, decl.Tok == token.CONST)
68 if err == nil {
69 symbols = append(symbols, vs)
70 }
71 }
72 }
73 }
74 }
75 }
76 return symbols, nil
77 }
78
79 // PackageSymbols returns a list of symbols in the narrowest package for the given file (specified
80 // by its URI).
81 // Methods with receivers are stored as children under the symbol for their receiver type.
82 // The PackageSymbol data type contains the same fields as protocol.DocumentSymbol, with
83 // an additional int field "File" that stores the index of that symbol's file in the
84 // PackageSymbolsResult.Files.
85 // Symbols are gathered using syntax rather than type information because type checking is
86 // significantly slower. Syntax information provides enough value to the user without
87 // causing a lag when loading symbol information across different files.
88 func PackageSymbols(ctx context.Context, snapshot *cache.Snapshot, uri protocol.DocumentURI) (command.PackageSymbolsResult, error) {
89 ctx, done := event.Start(ctx, "source.PackageSymbols")
90 defer done()
91
92 pkgFiles := []protocol.DocumentURI{uri}
93
94 // golang/vscode-go#3681: do our best if the file is not in a package.
95 // TODO(rfindley): revisit this in the future once there is more graceful
96 // handling in VS Code.
97 if mp, err := snapshot.NarrowestMetadataForFile(ctx, uri); err == nil {
98 pkgFiles = mp.CompiledGoFiles
99 }
100
101 var (
102 pkgName string
103 symbols []command.PackageSymbol
104 receiverToMethods = make(map[string][]command.PackageSymbol) // receiver name -> methods
105 typeSymbolToIdx = make(map[string]int) // type name -> index in symbols
106 )
107 for fidx, f := range pkgFiles {
108 fh, err := snapshot.ReadFile(ctx, f)
109 if err != nil {
110 return command.PackageSymbolsResult{}, err
111 }
112 pgf, err := snapshot.ParseGo(ctx, fh, parsego.Full)
113 if err != nil {
114 return command.PackageSymbolsResult{}, err
115 }
116 if pkgName == "" && pgf.File != nil && pgf.File.Name != nil {
117 pkgName = pgf.File.Name.Name
118 }
119 for _, decl := range pgf.File.Decls {
120 switch decl := decl.(type) {
121 case *ast.FuncDecl:
122 if decl.Name.Name == "_" {
123 continue
124 }
125 if fs, err := funcSymbol(pgf.Mapper, pgf.Tok, decl); err == nil {
126 // If function is a method, prepend the type of the method.
127 // Don't add the method as its own symbol; store it so we can
128 // add it as a child of the receiver type later
129 if decl.Recv != nil && len(decl.Recv.List) > 0 {
130 _, rname, _ := astutil.UnpackRecv(decl.Recv.List[0].Type)
131 receiverToMethods[rname.String()] = append(receiverToMethods[rname.String()], toPackageSymbol(fidx, fs))
132 } else {
133 symbols = append(symbols, toPackageSymbol(fidx, fs))
134 }
135 }
136 case *ast.GenDecl:
137 for _, spec := range decl.Specs {
138 switch spec := spec.(type) {
139 case *ast.TypeSpec:
140 if spec.Name.Name == "_" {
141 continue
142 }
143 if ts, err := typeSymbol(pgf.Mapper, pgf.Tok, spec); err == nil {
144 typeSymbolToIdx[ts.Name] = len(symbols)
145 symbols = append(symbols, toPackageSymbol(fidx, ts))
146 }
147 case *ast.ValueSpec:
148 for _, name := range spec.Names {
149 if name.Name == "_" {
150 continue
151 }
152 if vs, err := varSymbol(pgf.Mapper, pgf.Tok, spec, name, decl.Tok == token.CONST); err == nil {
153 symbols = append(symbols, toPackageSymbol(fidx, vs))
154 }
155 }
156 }
157 }
158 }
159 }
160 }
161 // Add methods as the child of their receiver type symbol
162 for recv, methods := range receiverToMethods {
163 if i, ok := typeSymbolToIdx[recv]; ok {
164 symbols[i].Children = append(symbols[i].Children, methods...)
165 }
166 }
167 return command.PackageSymbolsResult{
168 PackageName: pkgName,
169 Files: pkgFiles,
170 Symbols: symbols,
171 }, nil
172 }
173
174 func toPackageSymbol(fileIndex int, s protocol.DocumentSymbol) command.PackageSymbol {
175 var res command.PackageSymbol
176 res.Name = s.Name
177 res.Detail = s.Detail
178 res.Kind = s.Kind
179 res.Tags = s.Tags
180 res.Range = s.Range
181 res.SelectionRange = s.SelectionRange
182
183 children := make([]command.PackageSymbol, len(s.Children))
184 for i, c := range s.Children {
185 children[i] = toPackageSymbol(fileIndex, c)
186 }
187 res.Children = children
188
189 res.File = fileIndex
190 return res
191 }
192
193 func funcSymbol(m *protocol.Mapper, tf *token.File, decl *ast.FuncDecl) (protocol.DocumentSymbol, error) {
194 s := protocol.DocumentSymbol{
195 Name: decl.Name.Name,
196 Kind: protocol.Function,
197 }
198 if decl.Recv != nil {
199 s.Kind = protocol.Method
200 }
201 var err error
202 s.Range, err = m.NodeRange(tf, decl)
203 if err != nil {
204 return protocol.DocumentSymbol{}, err
205 }
206 s.SelectionRange, err = m.NodeRange(tf, decl.Name)
207 if err != nil {
208 return protocol.DocumentSymbol{}, err
209 }
210 s.Detail = types.ExprString(decl.Type)
211 return s, nil
212 }
213
214 func typeSymbol(m *protocol.Mapper, tf *token.File, spec *ast.TypeSpec) (protocol.DocumentSymbol, error) {
215 s := protocol.DocumentSymbol{
216 Name: spec.Name.Name,
217 }
218 var err error
219 s.Range, err = m.NodeRange(tf, spec)
220 if err != nil {
221 return protocol.DocumentSymbol{}, err
222 }
223 s.SelectionRange, err = m.NodeRange(tf, spec.Name)
224 if err != nil {
225 return protocol.DocumentSymbol{}, err
226 }
227 s.Kind, s.Detail, s.Children = typeDetails(m, tf, spec.Type)
228 return s, nil
229 }
230
231 func typeDetails(m *protocol.Mapper, tf *token.File, typExpr ast.Expr) (kind protocol.SymbolKind, detail string, children []protocol.DocumentSymbol) {
232 switch typExpr := typExpr.(type) {
233 case *ast.StructType:
234 kind = protocol.Struct
235 children = fieldListSymbols(m, tf, typExpr.Fields, protocol.Field)
236 if len(children) > 0 {
237 detail = "struct{...}"
238 } else {
239 detail = "struct{}"
240 }
241
242 // Find interface methods and embedded types.
243 case *ast.InterfaceType:
244 kind = protocol.Interface
245 children = fieldListSymbols(m, tf, typExpr.Methods, protocol.Method)
246 if len(children) > 0 {
247 detail = "interface{...}"
248 } else {
249 detail = "interface{}"
250 }
251
252 case *ast.FuncType:
253 kind = protocol.Function
254 detail = types.ExprString(typExpr)
255
256 default:
257 kind = protocol.Class // catch-all, for cases where we don't know the kind syntactically
258 detail = types.ExprString(typExpr)
259 }
260 return
261 }
262
263 func fieldListSymbols(m *protocol.Mapper, tf *token.File, fields *ast.FieldList, fieldKind protocol.SymbolKind) []protocol.DocumentSymbol {
264 if fields == nil {
265 return nil
266 }
267
268 var symbols []protocol.DocumentSymbol
269 for _, field := range fields.List {
270 detail, children := "", []protocol.DocumentSymbol(nil)
271 if field.Type != nil {
272 _, detail, children = typeDetails(m, tf, field.Type)
273 }
274 if len(field.Names) == 0 { // embedded interface or struct field
275 // By default, use the formatted type details as the name of this field.
276 // This handles potentially invalid syntax, as well as type embeddings in
277 // interfaces.
278 child := protocol.DocumentSymbol{
279 Name: detail,
280 Kind: protocol.Field, // consider all embeddings to be fields
281 Children: children,
282 }
283
284 // If the field is a valid embedding, promote the type name to field
285 // name.
286 selection := field.Type
287 if id := embeddedIdent(field.Type); id != nil {
288 child.Name = id.Name
289 child.Detail = detail
290 selection = id
291 }
292
293 if rng, err := m.NodeRange(tf, field.Type); err == nil {
294 child.Range = rng
295 }
296 if rng, err := m.NodeRange(tf, selection); err == nil {
297 child.SelectionRange = rng
298 }
299
300 symbols = append(symbols, child)
301 } else {
302 for _, name := range field.Names {
303 child := protocol.DocumentSymbol{
304 Name: name.Name,
305 Kind: fieldKind,
306 Detail: detail,
307 Children: children,
308 }
309
310 if rng, err := m.NodeRange(tf, field); err == nil {
311 child.Range = rng
312 }
313 if rng, err := m.NodeRange(tf, name); err == nil {
314 child.SelectionRange = rng
315 }
316
317 symbols = append(symbols, child)
318 }
319 }
320
321 }
322 return symbols
323 }
324
325 func varSymbol(m *protocol.Mapper, tf *token.File, spec *ast.ValueSpec, name *ast.Ident, isConst bool) (protocol.DocumentSymbol, error) {
326 s := protocol.DocumentSymbol{
327 Name: name.Name,
328 Kind: protocol.Variable,
329 }
330 if isConst {
331 s.Kind = protocol.Constant
332 }
333 var err error
334 s.Range, err = m.NodeRange(tf, spec)
335 if err != nil {
336 return protocol.DocumentSymbol{}, err
337 }
338 s.SelectionRange, err = m.NodeRange(tf, name)
339 if err != nil {
340 return protocol.DocumentSymbol{}, err
341 }
342 if spec.Type != nil { // type may be missing from the syntax
343 _, s.Detail, s.Children = typeDetails(m, tf, spec.Type)
344 }
345 return s, nil
346 }