Debian Codegraph @

gopls/internal/golang/definition.go

raw symbols SCIP
1 // Copyright 2023 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 "errors"
10 "fmt"
11 "go/ast"
12 "go/parser"
13 "go/token"
14 "go/types"
15 "regexp"
16 "strings"
17
18 "golang.org/x/tools/gopls/internal/cache"
19 "golang.org/x/tools/gopls/internal/cache/metadata"
20 "golang.org/x/tools/gopls/internal/cache/parsego"
21 "golang.org/x/tools/gopls/internal/file"
22 "golang.org/x/tools/gopls/internal/protocol"
23 "golang.org/x/tools/gopls/internal/util/bug"
24 "golang.org/x/tools/internal/astutil"
25 "golang.org/x/tools/internal/event"
26 )
27
28 // Definition handles the textDocument/definition request for Go files.
29 func Definition(ctx context.Context, snapshot *cache.Snapshot, fh file.Handle, rng protocol.Range) ([]protocol.Location, error) {
30 ctx, done := event.Start(ctx, "golang.Definition")
31 defer done()
32
33 pkg, pgf, err := NarrowestPackageForFile(ctx, snapshot, fh.URI())
34 if err != nil {
35 return nil, err
36 }
37 start, end, err := pgf.RangePos(rng)
38 if err != nil {
39 return nil, err
40 }
41 cur, _ := pgf.Cursor().FindByPos(start, end) // can't fail
42
43 // Handle the case where the range is in an import.
44 importLocations, err := importDefinition(ctx, snapshot, pkg, pgf, start, end)
45 if err != nil {
46 return nil, err
47 }
48 if len(importLocations) > 0 {
49 return importLocations, nil
50 }
51
52 // Handle the case where the cursor is in the package name.
53 // We use "<= End" to accept a query immediately after the package name.
54 if pgf.File != nil && astutil.NodeContains(pgf.File.Name, astutil.RangeOf(start, end)) {
55 // If there's no package documentation, just use current file.
56 declFile := pgf
57 for _, pgf := range pkg.CompiledGoFiles() {
58 if pgf.File.Name != nil && pgf.File.Doc != nil {
59 declFile = pgf
60 break
61 }
62 }
63 loc, err := declFile.NodeLocation(declFile.File.Name)
64 if err != nil {
65 return nil, err
66 }
67 return []protocol.Location{loc}, nil
68 }
69
70 // Handle the case where the cursor is in a linkname directive.
71 locations, err := linknameDefinition(ctx, snapshot, pgf.Mapper, rng)
72 if !errors.Is(err, ErrNoLinkname) {
73 return locations, err // may be success or failure
74 }
75
76 // Handle the case where the cursor is in an embed directive.
77 locations, err = embedDefinition(pgf.Mapper, rng)
78 if !errors.Is(err, ErrNoEmbed) {
79 return locations, err // may be success or failure
80 }
81
82 // Handle the case where the cursor is in a doc link.
83 locations, err = docLinkDefinition(ctx, snapshot, pkg, pgf, start, end)
84 if !errors.Is(err, errNoCommentReference) {
85 return locations, err // may be success or failure
86 }
87
88 // Handle definition requests for various special kinds of syntax node.
89 switch node := cur.Node().(type) {
90 // Handle the case where the cursor is on a return statement by jumping to the result variables.
91 case *ast.ReturnStmt:
92 var funcType *ast.FuncType
93 for c := range cur.Enclosing() {
94 switch n := c.Node().(type) {
95 case *ast.FuncLit:
96 funcType = n.Type
97 case *ast.FuncDecl:
98 funcType = n.Type
99 }
100 if funcType != nil {
101 break
102 }
103 }
104 // Inv: funcType != nil, as a return stmt cannot appear outside a function.
105 if funcType.Results == nil {
106 return nil, nil // no result variables
107 }
108 loc, err := pgf.NodeLocation(funcType.Results)
109 if err != nil {
110 return nil, err
111 }
112 return []protocol.Location{loc}, nil
113
114 case *ast.BranchStmt:
115 // Handle the case where the cursor is on a goto, break or continue statement by returning the
116 // location of the label, the closing brace of the relevant block statement, or the
117 // start of the relevant loop, respectively.
118 label, isLabeled := pkg.TypesInfo().Uses[node.Label].(*types.Label)
119 switch node.Tok {
120 case token.GOTO:
121 if !isLabeled {
122 return nil, fmt.Errorf("undefined label")
123 }
124 loc, err := pgf.PosLocation(label.Pos(), label.Pos()+token.Pos(len(label.Name())))
125 if err != nil {
126 return nil, err
127 }
128 return []protocol.Location{loc}, nil
129
130 case token.BREAK, token.CONTINUE:
131 // Find innermost relevant ancestor for break/continue.
132 for c := range cur.Enclosing() {
133 if isLabeled {
134 l, ok := c.Parent().Node().(*ast.LabeledStmt)
135 if !(ok && l.Label.Name == label.Name()) {
136 continue
137 }
138 }
139 switch n := c.Node().(type) {
140 case *ast.ForStmt, *ast.RangeStmt:
141 var start, end token.Pos
142 if node.Tok == token.BREAK {
143 start, end = n.End()-token.Pos(len("}")), n.End()
144 } else { // CONTINUE
145 start, end = n.Pos(), n.Pos()+token.Pos(len("for"))
146 }
147 loc, err := pgf.PosLocation(start, end)
148 if err != nil {
149 return nil, err
150 }
151 return []protocol.Location{loc}, nil
152 case *ast.SwitchStmt, *ast.TypeSwitchStmt, *ast.SelectStmt:
153 if node.Tok == token.BREAK {
154 loc, err := pgf.PosLocation(n.End()-1, n.End())
155 if err != nil {
156 return nil, err
157 }
158 return []protocol.Location{loc}, nil
159 }
160 case *ast.FuncDecl, *ast.FuncLit:
161 // bad syntax; avoid jumping outside the current function
162 return nil, nil
163 }
164 }
165 }
166 }
167
168 // The general case: the cursor is on (or near) an identifier.
169 objects, err := objectsAt(pkg.TypesInfo(), cur)
170 if err != nil {
171 return nil, nil
172 }
173 obj := objects[0].obj
174 cur = objects[0].cur // nearby
175 id, ok := cur.Node().(*ast.Ident)
176 if !ok {
177 // objectsAt can return a non-Ident (e.g. ImportSpec),
178 // but we dealt with them earlier. Can't happen?
179 return nil, nil
180 }
181
182 // If the query position was an embedded field, we want to jump
183 // to the field's type definition, not the field's definition (#42254).
184 if v, ok := obj.(*types.Var); ok && v.Embedded() {
185 // types.Info.Uses contains the embedded field's *types.TypeName.
186 if typeName := pkg.TypesInfo().Uses[id]; typeName != nil {
187 obj = typeName
188 }
189 }
190
191 // Non-go (e.g. assembly) symbols
192 //
193 // When already at the definition of a Go function without
194 // a body, we jump to its non-Go (C or assembly) definition.
195 for _, decl := range pgf.File.Decls {
196 if decl, ok := decl.(*ast.FuncDecl); ok &&
197 decl.Body == nil &&
198 astutil.NodeContains(decl.Name, astutil.RangeOf(start, end)) {
199 return nonGoDefinition(ctx, snapshot, pkg, decl.Name.Name)
200 }
201 }
202
203 // Finally, map the object position.
204 loc, err := ObjectLocation(ctx, pkg.FileSet(), snapshot, obj)
205 if err != nil {
206 return nil, err
207 }
208 return []protocol.Location{loc}, nil
209 }
210
211 // builtinDecl returns the parsed Go file and node corresponding to a builtin
212 // object, which may be a universe object or part of types.Unsafe, as well as
213 // its declaring identifier.
214 func builtinDecl(ctx context.Context, snapshot *cache.Snapshot, obj types.Object) (*parsego.File, *ast.Ident, error) {
215 // declaringIdent returns the file-level declaration node (as reported by
216 // ast.Object) and declaring identifier of name using legacy (go/ast) object
217 // resolution.
218 declaringIdent := func(file *ast.File, name string) (ast.Node, *ast.Ident, error) {
219 astObj := file.Scope.Lookup(name)
220 if astObj == nil {
221 // Every built-in should have documentation syntax.
222 // However, it is possible to reach this statement by
223 // commenting out declarations in {builtin,unsafe}.go.
224 return nil, nil, fmt.Errorf("internal error: no object for %s", name)
225 }
226 decl, ok := astObj.Decl.(ast.Node)
227 if !ok {
228 return nil, nil, bug.Errorf("internal error: no declaration for %s", obj.Name())
229 }
230 var ident *ast.Ident
231 switch node := decl.(type) {
232 case *ast.Field:
233 for _, id := range node.Names {
234 if id.Name == name {
235 ident = id
236 }
237 }
238 case *ast.ValueSpec:
239 for _, id := range node.Names {
240 if id.Name == name {
241 ident = id
242 }
243 }
244 case *ast.TypeSpec:
245 ident = node.Name
246 case *ast.Ident:
247 ident = node
248 case *ast.FuncDecl:
249 ident = node.Name
250 case *ast.ImportSpec, *ast.LabeledStmt, *ast.AssignStmt:
251 // Not reachable for imported objects.
252 default:
253 return nil, nil, bug.Errorf("internal error: unexpected decl type %T", decl)
254 }
255 if ident == nil {
256 return nil, nil, bug.Errorf("internal error: no declaring identifier for %s", obj.Name())
257 }
258 return decl, ident, nil
259 }
260
261 var (
262 pgf *parsego.File
263 ident *ast.Ident
264 err error
265 )
266 if obj.Pkg() == types.Unsafe {
267 // package "unsafe":
268 // parse $GOROOT/src/unsafe/unsafe.go
269 //
270 // (Strictly, we shouldn't assume that the ID of a std
271 // package is its PkgPath, but no Bazel+gopackagesdriver
272 // users have complained about this yet.)
273 unsafe := snapshot.Metadata("unsafe")
274 if unsafe == nil {
275 // If the type checker somehow resolved 'unsafe', we must have metadata
276 // for it.
277 return nil, nil, bug.Errorf("no metadata for package 'unsafe'")
278 }
279 uri := unsafe.GoFiles[0]
280 fh, err := snapshot.ReadFile(ctx, uri)
281 if err != nil {
282 return nil, nil, err
283 }
284 // TODO(rfindley): treat unsafe symmetrically with the builtin file. Either
285 // pre-parse them both, or look up metadata for both.
286 pgf, err = snapshot.ParseGo(ctx, fh, parsego.Full&^parser.SkipObjectResolution)
287 if err != nil {
288 return nil, nil, err
289 }
290 _, ident, err = declaringIdent(pgf.File, obj.Name())
291 if err != nil {
292 return nil, nil, err
293 }
294 } else {
295 // pseudo-package "builtin":
296 // use parsed $GOROOT/src/builtin/builtin.go
297 pgf, err = snapshot.BuiltinFile(ctx)
298 if err != nil {
299 return nil, nil, err
300 }
301
302 if obj.Parent() == types.Universe {
303 // built-in function or type
304 _, ident, err = declaringIdent(pgf.File, obj.Name())
305 if err != nil {
306 return nil, nil, err
307 }
308 } else if obj.Name() == "Error" {
309 // error.Error method
310 decl, _, err := declaringIdent(pgf.File, "error")
311 if err != nil {
312 return nil, nil, err
313 }
314 field := decl.(*ast.TypeSpec).Type.(*ast.InterfaceType).Methods.List[0]
315 ident = field.Names[0]
316 } else {
317 return nil, nil, bug.Errorf("unknown built-in %v", obj)
318 }
319 }
320 _ = ident.Name // ident != nil
321
322 return pgf, ident, nil
323 }
324
325 // importDefinition returns locations defining a package referenced by the
326 // import spec containing pos.
327 //
328 // If pos is not inside an import spec, it returns nil, nil.
329 func importDefinition(ctx context.Context, s *cache.Snapshot, pkg *cache.Package, pgf *parsego.File, start, end token.Pos) ([]protocol.Location, error) {
330 var imp *ast.ImportSpec
331 for _, spec := range pgf.File.Imports {
332 // We use "<= End" to accept a query immediately after an ImportSpec.
333 if astutil.NodeContains(spec.Path, astutil.RangeOf(start, end)) {
334 imp = spec
335 }
336 }
337 if imp == nil {
338 return nil, nil
339 }
340
341 importPath := metadata.UnquoteImportPath(imp)
342 impID := pkg.Metadata().DepsByImpPath[importPath]
343 if impID == "" {
344 return nil, fmt.Errorf("failed to resolve import %q", importPath)
345 }
346 impMetadata := s.Metadata(impID)
347 if impMetadata == nil {
348 return nil, fmt.Errorf("missing information for package %q", impID)
349 }
350
351 var locs []protocol.Location
352 for _, f := range impMetadata.CompiledGoFiles {
353 fh, err := s.ReadFile(ctx, f)
354 if err != nil {
355 if ctx.Err() != nil {
356 return nil, ctx.Err()
357 }
358 continue
359 }
360 pgf, err := s.ParseGo(ctx, fh, parsego.Header)
361 if err != nil {
362 if ctx.Err() != nil {
363 return nil, ctx.Err()
364 }
365 continue
366 }
367 loc, err := pgf.NodeLocation(pgf.File)
368 if err != nil {
369 return nil, err
370 }
371 locs = append(locs, loc)
372 }
373
374 if len(locs) == 0 {
375 return nil, fmt.Errorf("package %q has no readable files", impID) // incl. unsafe
376 }
377
378 return locs, nil
379 }
380
381 // ObjectLocation returns the location of the declaring identifier of obj.
382 // If valid, obj.Pos() must be mapped by fset.
383 // It may need to read the declaring file content, hence (ctx, s).
384 // It supports the builtin and unsafe pseudo-packages.
385 func ObjectLocation(ctx context.Context, fset *token.FileSet, snapshot *cache.Snapshot, obj types.Object) (protocol.Location, error) {
386 if isBuiltin(obj) {
387 // Returns fake source declaration in {builtin,unsafe}.go.
388 pgf, ident, err := builtinDecl(ctx, snapshot, obj)
389 if err != nil {
390 return protocol.Location{}, err
391 }
392 return pgf.NodeLocation(ident)
393 }
394
395 // An imported Go package has a package-local, unqualified name.
396 // When the name matches the imported package name, there is usually
397 // no identifier in the import spec with the local package name.
398 //
399 // For example:
400 // import "go/‸ast" // name "ast" matches package name
401 // import ‸a "go/ast" // name "a" does not match package name
402 //
403 // When the identifier does not appear in the source, have the range
404 // of the object be the import path, including quotes.
405 //
406 // But this is just a heuristic, and it's wrong in this case:
407 // import ‸ast "go/ast" // name matches (spurious result is `ast "go/`)
408 nameLen := len(obj.Name())
409 if pkgName, ok := obj.(*types.PkgName); ok && pkgName.Imported().Name() == pkgName.Name() {
410 nameLen = len(pkgName.Imported().Path()) + len(`""`)
411 }
412
413 var (
414 start = obj.Pos()
415 end = start + token.Pos(nameLen)
416 )
417 file := fset.File(start)
418 if file == nil {
419 return protocol.Location{}, bug.Errorf("FileSet does not map Pos %d", start)
420 }
421 uri := protocol.URIFromPath(file.Name())
422 fh, err := snapshot.ReadFile(ctx, uri)
423 if err != nil {
424 return protocol.Location{}, err
425 }
426 content, err := fh.Content()
427 if err != nil {
428 return protocol.Location{}, err
429 }
430 // TODO(rfindley): avoid the duplicate column mapping here, by associating a
431 // column mapper with each file handle.
432 m := protocol.NewMapper(fh.URI(), content)
433 return m.PosLocation(file, start, end)
434 }
435
436 // nonGoDefinition returns the location of the definition of a non-Go symbol.
437 // Only assembly is supported for now.
438 func nonGoDefinition(ctx context.Context, snapshot *cache.Snapshot, pkg *cache.Package, symbol string) ([]protocol.Location, error) {
439 // Examples:
440 // TEXT runtime·foo(SB)
441 // TEXT ·foo<ABIInternal>(SB)
442 // TODO(adonovan): why does ^TEXT cause it not to match?
443 pattern := regexp.MustCompile("TEXT\\b.*·(" + regexp.QuoteMeta(symbol) + ")[\\(<]")
444
445 for _, uri := range pkg.Metadata().OtherFiles {
446 if strings.HasSuffix(uri.Path(), ".s") {
447 fh, err := snapshot.ReadFile(ctx, uri)
448 if err != nil {
449 return nil, err // context cancelled
450 }
451 content, err := fh.Content()
452 if err != nil {
453 continue // can't read file
454 }
455 if match := pattern.FindSubmatchIndex(content); match != nil {
456 mapper := protocol.NewMapper(uri, content)
457 loc, err := mapper.OffsetLocation(match[2], match[3])
458 if err != nil {
459 return nil, err
460 }
461 return []protocol.Location{loc}, nil
462 }
463 }
464 }
465
466 // TODO(adonovan): try C files
467
468 // This may be reached for functions that aren't implemented
469 // in assembly (e.g. compiler intrinsics like getg).
470 return nil, fmt.Errorf("can't find non-Go definition of %s", symbol)
471 }