Debian Codegraph @

gopls/internal/golang/hover.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 "bytes"
9 "cmp"
10 "context"
11 "encoding/json"
12 "fmt"
13 "go/ast"
14 "go/constant"
15 "go/doc"
16 "go/format"
17 "go/printer"
18 "go/token"
19 "go/types"
20 "go/version"
21 "io/fs"
22 "path/filepath"
23 "slices"
24 "sort"
25 "strconv"
26 "strings"
27 "text/tabwriter"
28 "time"
29 "unicode/utf8"
30
31 "golang.org/x/text/unicode/runenames"
32 goastutil "golang.org/x/tools/go/ast/astutil"
33 "golang.org/x/tools/go/ast/inspector"
34 "golang.org/x/tools/go/types/typeutil"
35 "golang.org/x/tools/gopls/internal/cache"
36 "golang.org/x/tools/gopls/internal/cache/metadata"
37 "golang.org/x/tools/gopls/internal/cache/parsego"
38 "golang.org/x/tools/gopls/internal/file"
39 "golang.org/x/tools/gopls/internal/protocol"
40 "golang.org/x/tools/gopls/internal/settings"
41 "golang.org/x/tools/gopls/internal/util/bug"
42 "golang.org/x/tools/gopls/internal/util/cursorutil"
43 "golang.org/x/tools/gopls/internal/util/safetoken"
44 "golang.org/x/tools/gopls/internal/util/tokeninternal"
45 "golang.org/x/tools/internal/astutil"
46 "golang.org/x/tools/internal/event"
47 "golang.org/x/tools/internal/stdlib"
48 "golang.org/x/tools/internal/typeparams"
49 "golang.org/x/tools/internal/typesinternal"
50 )
51
52 // hoverResult contains the (internal) result of a hover query.
53 // It is formatted in one of several formats as determined by the
54 // HoverKind setting.
55 type hoverResult struct {
56 // The fields below are exported to define the JSON hover format.
57 // TODO(golang/go#70233): (re)remove support for JSON hover.
58
59 // Synopsis is a single sentence Synopsis of the symbol's documentation.
60 //
61 // TODO(adonovan): in what syntax? It (usually) comes from doc.Synopsis,
62 // which produces "Text" form, but it may be fed to
63 // DocCommentToMarkdown, which expects doc comment syntax.
64 Synopsis string `json:"synopsis"`
65
66 // FullDocumentation is the symbol's full documentation.
67 FullDocumentation string `json:"fullDocumentation"`
68
69 // Signature is the symbol's Signature.
70 Signature string `json:"signature"`
71
72 // SingleLine is a single line describing the symbol.
73 // This is recommended only for use in clients that show a single line for hover.
74 SingleLine string `json:"singleLine"`
75
76 // SymbolName is the human-readable name to use for the symbol in links.
77 SymbolName string `json:"symbolName"`
78
79 // LinkPath is the path of the package enclosing the given symbol,
80 // with the module portion (if any) replaced by "module@version".
81 //
82 // For example: "github.com/google/go-github/[email protected]/github".
83 //
84 // Use LinkTarget + "/" + LinkPath + "#" + LinkAnchor to form a pkgsite URL.
85 LinkPath string `json:"linkPath"`
86
87 // LinkAnchor is the pkg.go.dev link anchor for the given symbol.
88 // For example, the "Node" part of "pkg.go.dev/go/ast#Node".
89 LinkAnchor string `json:"linkAnchor"`
90
91 // New fields go below, and are unexported. The existing
92 // exported fields are underspecified and have already
93 // constrained our movements too much. A detailed JSON
94 // interface might be nice, but it needs a design and a
95 // precise specification.
96 // TODO(golang/go#70233): (re)deprecate the JSON hover output.
97
98 // typeDecl is the declaration syntax for a type,
99 // or "" for a non-type.
100 typeDecl string
101
102 // methods is the list of descriptions of methods of a type,
103 // omitting any that are obvious from typeDecl.
104 // It is "" for a non-type.
105 methods string
106
107 // promotedFields is the list of descriptions of accessible
108 // fields of a (struct) type that were promoted through an
109 // embedded field.
110 promotedFields string
111
112 // footer is additional content to insert at the bottom of the hover
113 // documentation, before the pkgdoc link.
114 footer string
115 }
116
117 // Hover implements the "textDocument/hover" RPC for Go files.
118 // It may return nil even on success.
119 //
120 // If pkgURL is non-nil, it should be used to generate doc links.
121 func Hover(ctx context.Context, snapshot *cache.Snapshot, fh file.Handle, rng protocol.Range, pkgURL func(path PackagePath, fragment string) protocol.URI) (*protocol.Hover, error) {
122 ctx, done := event.Start(ctx, "golang.Hover")
123 defer done()
124
125 rng, h, err := hover(ctx, snapshot, fh, rng)
126 if err != nil {
127 return nil, err
128 }
129 if h == nil {
130 return nil, nil
131 }
132 hover, err := formatHover(h, snapshot.Options(), pkgURL)
133 if err != nil {
134 return nil, err
135 }
136 return &protocol.Hover{
137 Contents: protocol.MarkupContent{
138 Kind: snapshot.Options().PreferredContentFormat,
139 Value: hover,
140 },
141 Range: rng,
142 }, nil
143 }
144
145 // findRhsTypeDecl finds an alias's rhs type and returns its declaration.
146 // The rhs of an alias might be an alias as well, but we feel this is a rare case.
147 // It returns an empty string if the given obj is not an alias.
148 func findRhsTypeDecl(ctx context.Context, snapshot *cache.Snapshot, pkg *cache.Package, obj types.Object) (string, error) {
149 if alias, ok := obj.Type().(*types.Alias); ok {
150 // we choose Rhs instead of types.Unalias to make the connection between original alias
151 // and the corresponding aliased type clearer.
152 // types.Unalias brings confusion because it breaks the connection from A to C given
153 // the alias chain like 'type ( A = B; B = C; )' except we show all transitive alias
154 // from start to the end. As it's rare, we don't do so.
155 if named, ok := alias.Rhs().(*types.Named); ok {
156 obj = named.Obj()
157 declPGF1, declPos1, err := parseFull(ctx, snapshot, pkg.FileSet(), obj)
158 if err != nil {
159 return "", err
160 }
161 realTypeDecl, _, err := typeDeclContent(declPGF1, declPos1, obj.Name())
162 return realTypeDecl, err
163 }
164 }
165
166 return "", nil
167 }
168
169 // hover computes hover information at the given range. When hover over a single
170 // point, the input range's start and end are the same.
171 //
172 // If we do not support hovering at the position, it returns _, nil, nil:
173 // an error is only returned if the position is valid but we fail to compute
174 // hover information.
175 //
176 // TODO(adonovan): strength-reduce file.Handle to protocol.DocumentURI.
177 func hover(ctx context.Context, snapshot *cache.Snapshot, fh file.Handle, rng protocol.Range) (protocol.Range, *hoverResult, error) {
178 // Check for hover inside the builtin file before attempting type checking
179 // below. NarrowestPackageForFile may or may not succeed, depending on
180 // whether this is a GOROOT view, but even if it does succeed the resulting
181 // package will be command-line-arguments package. The user should get a
182 // hover for the builtin object, not the object type checked from the
183 // builtin.go.
184 if snapshot.IsBuiltin(fh.URI()) {
185 pgf, err := snapshot.BuiltinFile(ctx)
186 if err != nil {
187 return protocol.Range{}, nil, err
188 }
189 start, end, err := pgf.RangePos(rng)
190 if err != nil {
191 return protocol.Range{}, nil, err
192 }
193 cur, _ := pgf.Cursor().FindByPos(start, end) // can't fail
194 if id, ok := cur.Node().(*ast.Ident); ok {
195 rng, err := pgf.NodeRange(id)
196 if err != nil {
197 return protocol.Range{}, nil, err
198 }
199 var obj types.Object
200 if id.Name == "Error" {
201 obj = types.Universe.Lookup("error").Type().Underlying().(*types.Interface).Method(0)
202 } else {
203 obj = types.Universe.Lookup(id.Name)
204 }
205 if obj != nil {
206 h, err := hoverBuiltin(ctx, snapshot, obj)
207 return rng, h, err
208 }
209 }
210 return protocol.Range{}, nil, nil // no object to hover
211 }
212
213 pkg, pgf, err := NarrowestPackageForFile(ctx, snapshot, fh.URI())
214 if err != nil {
215 return protocol.Range{}, nil, err
216 }
217 var posRange astutil.Range
218 {
219 start, end, err := pgf.RangePos(rng)
220 if err != nil {
221 return protocol.Range{}, nil, err
222 }
223 posRange = astutil.RangeOf(start, end)
224 }
225
226 // Handle hovering over the package name, which does not have an associated
227 // object.
228 // As with import paths, we allow hovering just after the package name.
229 if pgf.File.Name != nil && astutil.NodeContains(pgf.File.Name, posRange) {
230 return hoverPackageName(pkg, pgf)
231 }
232
233 // Handle hovering over embed directive argument.
234 pattern, embedRng := parseEmbedDirective(pgf.Mapper, rng)
235 if pattern != "" {
236 return hoverEmbed(fh, embedRng, pattern)
237 }
238
239 // hoverRange is the range reported to the client (e.g. for highlighting).
240 // It may be an expansion around the selected identifier,
241 // for instance when hovering over a linkname directive or doc link.
242 var hoverRange *protocol.Range
243 // Handle linkname directive by overriding what to look for.
244 if pkgPath, name, offset := parseLinkname(pgf.Mapper, rng); pkgPath != "" && name != "" {
245 // rng covering 2nd linkname argument: pkgPath.name.
246 rng, err := pgf.PosRange(pgf.Tok.Pos(offset), pgf.Tok.Pos(offset+len(pkgPath)+len(".")+len(name)))
247 if err != nil {
248 return protocol.Range{}, nil, fmt.Errorf("range over linkname arg: %w", err)
249 }
250 hoverRange = &rng
251
252 var pos token.Pos
253 // Subtle: updates pkg, which defines the FileSet used to resolve (start, end),
254 // which were obtained from pkg.
255 pkg, pgf, pos, err = findLinkname(ctx, snapshot, PackagePath(pkgPath), name)
256 if err != nil {
257 return protocol.Range{}, nil, fmt.Errorf("find linkname: %w", err)
258 }
259 posRange = astutil.RangeOf(pos, pos) // move the range
260 }
261
262 // TODO(hxjiang): Hovering over a doc link like "[foo.Foo]" and a direct
263 // call to "foo.Foo" can produce different signatures. The doc link hover is
264 // qualified relative to the function's definition file, whereas the direct
265 // call hover is qualified relative to the current file where the call occurs.
266
267 // Handle hovering over a doc link
268 if obj, rng, err := resolveDocLink(pkg, pgf, posRange); obj != nil {
269 // Built-ins have no position.
270 if isBuiltin(obj) {
271 h, err := hoverBuiltin(ctx, snapshot, obj)
272 return rng, h, err
273 }
274
275 // Find position in declaring file.
276 hoverRange = &rng
277
278 var pos token.Pos
279 // Subtle: updates pkg, which defines the FileSet used to resolve (start, end),
280 // which were obtained from pkg.
281 pkg, pgf, pos, err = NarrowestDeclaringPackage(ctx, snapshot, pkg, obj)
282 if err != nil {
283 return protocol.Range{}, nil, err
284 }
285 posRange = astutil.RangeOf(pos, pos)
286 }
287
288 // Find cursor for selection.
289 cur, ok := pgf.Cursor().FindByPos(posRange.Pos(), posRange.End())
290 if !ok {
291 return protocol.Range{}, nil, fmt.Errorf("hover position not within file")
292 }
293
294 // Handle hovering over import specs,
295 // which may not have an associated identifier.
296 for _, spec := range pgf.File.Imports {
297 if astutil.NodeContains(spec, posRange) {
298 path := metadata.UnquoteImportPath(spec)
299 hoverRes, err := hoverPackageRef(ctx, snapshot, pkg, path)
300 if err != nil {
301 return protocol.Range{}, nil, err
302 }
303 rng, err := pgf.NodeRange(spec.Path)
304 if err != nil {
305 return protocol.Range{}, nil, err
306 }
307 if hoverRange == nil { // (may have already been set by a doc link)
308 hoverRange = &rng
309 }
310 return *hoverRange, hoverRes, nil // (hoverRes may be nil)
311 }
312 }
313
314 // By convention, we qualify hover information relative to the package
315 // from which the request originated.
316 qual := typesinternal.FileQualifier(pgf.File, pkg.Types())
317
318 // Handle hovering over various special kinds of syntax node.
319 switch node := cur.Node().(type) {
320 // (import paths were handled above)
321 case *ast.ReturnStmt:
322 return hoverReturnStatement(pgf, cur)
323 case *ast.Ident:
324 // fall through to rest of function
325 case ast.Expr:
326 tv, ok := pkg.TypesInfo().Types[node]
327 if !ok {
328 return protocol.Range{}, nil, nil
329 }
330 if tv.Value != nil {
331 // non-identifier constant expression
332 return hoverConstantExpr(pgf, node, tv, posRange)
333 }
334 // non-constant, non-identifier expression
335 // TODO(hxjiang): what info should we provide other than type of
336 // the selected expression.
337 // TODO(hxjiang): show method set of the given expression' type.
338 r := &hoverResult{
339 Synopsis: goastutil.NodeDescription(node),
340 FullDocumentation: types.TypeString(pkg.TypesInfo().TypeOf(node), qual),
341 }
342
343 highlight, err := pgf.NodeRange(node)
344 if err != nil {
345 return protocol.Range{}, nil, err
346 }
347 return highlight, r, nil
348 }
349
350 // Handle hover over identifier.
351
352 // The general case: compute hover information for the object referenced by
353 // the identifier at (or near) pos.
354 objects, err := objectsAt(pkg.TypesInfo(), cur)
355 if err != nil {
356 return protocol.Range{}, nil, nil // no object to hover
357 }
358 // Pick first object arbitrarily.
359 // Update cursor to its identifier (perhaps nearby).
360 obj, cur := objects[0].obj, objects[0].cur
361 ident, ok := cur.Node().(*ast.Ident)
362 if !ok {
363 return protocol.Range{}, nil, nil // e.g. ImportSpec?
364 }
365
366 // Unless otherwise specified, rng covers the ident being hovered.
367 if hoverRange == nil {
368 rng, err := pgf.NodeRange(ident)
369 if err != nil {
370 return protocol.Range{}, nil, err
371 }
372 hoverRange = &rng
373 }
374
375 // Handle type switch identifiers as a special case,
376 // since they don't have a regular object.
377 // There's not much useful information to provide.
378 if _, selectedType := typeSwitchVars(pkg.TypesInfo(), cur); selectedType != nil {
379 v := types.NewVar(obj.Pos(), obj.Pkg(), obj.Name(), selectedType)
380 typesinternal.SetVarKind(v, typesinternal.LocalVar)
381 signature := types.ObjectString(v, qual)
382 return *hoverRange, &hoverResult{
383 Signature: signature,
384 SingleLine: signature,
385 SymbolName: v.Name(),
386 }, nil
387 }
388
389 if isBuiltin(obj) {
390 // Built-ins have no position.
391 h, err := hoverBuiltin(ctx, snapshot, obj)
392 return *hoverRange, h, err
393 }
394
395 // For all other objects, load type information for their declaring package
396 // in order to correctly compute their documentation, signature, and link.
397 //
398 // Beware: positions derived from decl{Obj,Pkg,PGF,Pos} should be resolve
399 // using declPkg.FileSet; other positions should use pkg.FileSet().
400 declPkg, declPGF, declPos, err := NarrowestDeclaringPackage(ctx, snapshot, pkg, obj)
401 if err != nil {
402 return protocol.Range{}, nil, err
403 }
404
405 decl, spec, field, assign := findDeclInfo([]*ast.File{declPGF.File}, declPos) // may be nil^4
406
407 var docText string
408 if docComment := chooseDocComment(declPGF, decl, spec, field, assign); docComment != nil {
409 docBuf := new(strings.Builder)
410 docBuf.WriteString(docComment.Text())
411
412 // docLinks maps the literal text of a doc link to its definition URI.
413 // Since the link parser yields progressively for each part of a symbol
414 // path (e.g., "fmt", then "fmt.Scanner"), we intentionally overwrite the
415 // map entry to ensure the final value is the URI for the complete symbol.
416 docLinks := make(map[string]string)
417 for docLink := range commentDocLinks(docComment) {
418 obj := lookupDocLinkSymbol(declPkg, declPGF, docLink.nameText)
419 if obj == nil {
420 continue
421 }
422
423 // The URI is set to the location of the right-most element in a doc link
424 // (e.g., 'Scan' in [fmt.Scanner.Scan]). The sequential yielding of path
425 // segments intentionally overwrites the location for previous segments,
426 // ensuring only the most specific definition's location is retained.
427 loc, err := ObjectLocation(ctx, declPkg.FileSet(), snapshot, obj)
428 if err != nil {
429 return protocol.Range{}, nil, err
430 }
431
432 // The #line,col URL fragment is a non-standard format for file
433 // URIs that is supported by VS Code for navigating from hover
434 // text. The line and column are 1-based, and the column is a
435 // UTF-16 code unit offset, matching the LSP's definition of
436 // character position.
437 docLinks[docLink.bracketText] = fmt.Sprintf("%s#%d,%d", loc.URI, loc.Range.Start.Line+1, loc.Range.Start.Character+1)
438 }
439
440 // Attaching doc links to the bottom of the comment. The non-deterministic
441 // order is acceptable as these will be removed later by the [formatHover].
442 if len(docLinks) > 0 {
443 docBuf.WriteString("\n")
444 for doc, link := range docLinks {
445 fmt.Fprintf(docBuf, "%s: %s\n", doc, link)
446 }
447 }
448
449 docText = docBuf.String()
450 }
451
452 // By default, types.ObjectString provides a reasonable signature.
453 signature := objectString(obj, qual, declPos, declPGF.Tok, spec)
454
455 // When hovering over a reference to a promoted struct field or method,
456 // show the implicitly selected intervening fields.
457 isFieldOrMethod := false
458 switch obj := obj.(type) {
459 case *types.Var:
460 isFieldOrMethod = obj.IsField()
461 case *types.Func:
462 isFieldOrMethod = true
463 }
464
465 if isFieldOrMethod {
466 if selExpr, ok := cur.Parent().Node().(*ast.SelectorExpr); ok {
467 if sel, ok := pkg.TypesInfo().Selections[selExpr]; ok && len(sel.Index()) > 1 {
468 var s strings.Builder
469 s.WriteString(" // through ")
470 t := typesinternal.Unpointer(sel.Recv())
471 for i, index := range sel.Index()[:len(sel.Index())-1] {
472 if _, ok := t.Underlying().(*types.Struct); !ok {
473 break
474 }
475 if i > 0 {
476 s.WriteString(", ")
477 }
478 field := typesinternal.Unpointer(t.Underlying()).(*types.Struct).Field(index)
479 t = field.Type()
480 // Inv: fieldType is N or *N for some NamedOrAlias type N.
481 if ptr, ok := t.(*types.Pointer); ok {
482 s.WriteString("*")
483 t = ptr.Elem()
484 }
485 s.WriteString(types.TypeString(t, qual))
486 }
487 // Update signature to include embedded struct info.
488 signature += s.String()
489 }
490 }
491 }
492
493 singleLineSignature := signature
494
495 // Display struct tag for struct fields at the end of the signature.
496 if field != nil && field.Tag != nil {
497 signature += " " + field.Tag.Value
498 }
499
500 // For references to generic functions or methods,
501 // show the inferred signature type in a comment:
502 //
503 // func Method(C[string]) // func[U any]()
504 //
505 // For all others, do nothing; signature will be computed below.
506 //
507 // TODO(adonovan): show TypeParam/TypeArg correspondence, e.g. [T=string, U=int].
508 if inferred, ok := types.Unalias(pkg.TypesInfo().Instances[ident].Type).(*types.Signature); ok {
509 if sig, ok := obj.Type().Underlying().(*types.Signature); ok && sig.TypeParams().Len() > 0 { // (can't fail?)
510 obj2 := types.NewFunc(obj.Pos(), obj.Pkg(), obj.Name(), inferred)
511 str := types.ObjectString(obj2, qual)
512 // Try to avoid overly long lines.
513 space := " "
514 if len(str) > 60 {
515 space = "\n"
516 }
517 signature = str + space + "// " + types.TypeString(sig, qual)
518 }
519 }
520
521 // Compute size information for types,
522 // including allocator size class,
523 // and (size, offset) for struct fields.
524 //
525 // Also, if a struct type's field ordering is significantly
526 // wasteful of space, report its optimal size.
527 //
528 // This information is useful when debugging crashes or
529 // optimizing layout. To reduce distraction, we show it only
530 // when hovering over the declaring identifier,
531 // but not referring identifiers.
532 //
533 // Size and alignment vary across OS/ARCH.
534 // Gopls will select the appropriate build configuration when
535 // viewing a type declaration in a build-tagged file, but will
536 // use the default build config for all other types, even
537 // if they embed platform-variant types.
538 //
539 var sizeOffset string
540
541 if ident.Pos() == obj.Pos() {
542 // This is the declaring identifier.
543
544 // format returns the decimal and hex representation of x.
545 format := func(x int64) string {
546 if x < 10 {
547 return fmt.Sprintf("%d", x)
548 }
549 return fmt.Sprintf("%[1]d (%#[1]x)", x)
550 }
551
552 // Build string of form "size=... (X% wasted), class=..., offset=...".
553 size, wasted, offset := computeSizeOffsetInfo(pkg, cur, obj)
554 var buf strings.Builder
555 if size >= 0 {
556 fmt.Fprintf(&buf, "size=%s", format(size))
557 if wasted >= 20 { // >=20% wasted
558 fmt.Fprintf(&buf, " (%d%% wasted)", wasted)
559 }
560
561 // Include allocator size class, if larger.
562 if class := sizeClass(size); class > size {
563 fmt.Fprintf(&buf, ", class=%s", format(class))
564 }
565 }
566 if offset >= 0 {
567 if buf.Len() > 0 {
568 buf.WriteString(", ")
569 }
570 fmt.Fprintf(&buf, "offset=%s", format(offset))
571 }
572 sizeOffset = buf.String()
573 }
574
575 var typeDecl, methods, fields string
576
577 // For "objects defined by a type spec", the signature produced by
578 // objectString is insufficient:
579 // (1) large structs are formatted poorly, with no newlines
580 // (2) we lose inline comments
581 // Furthermore, we include a summary of their method set.
582 _, isTypeName := obj.(*types.TypeName)
583 _, isTypeParam := types.Unalias(obj.Type()).(*types.TypeParam)
584 if isTypeName && !isTypeParam {
585 var spec1 *ast.TypeSpec
586 typeDecl, spec1, err = typeDeclContent(declPGF, declPos, obj.Name())
587 if err != nil {
588 return protocol.Range{}, nil, err
589 }
590
591 // Splice in size/offset at end of first line.
592 // "type T struct { // size=..."
593 if sizeOffset != "" {
594 nl := strings.IndexByte(typeDecl, '\n')
595 if nl < 0 {
596 nl = len(typeDecl)
597 }
598 typeDecl = typeDecl[:nl] + " // " + sizeOffset + typeDecl[nl:]
599 }
600
601 // Promoted fields
602 //
603 // Show a table of accessible fields of the (struct)
604 // type that may not be visible in the syntax (above)
605 // due to promotion through embedded fields.
606 //
607 // Example:
608 //
609 // // Embedded fields:
610 // foo int // through x.y
611 // z string // through x.y
612 if prom := promotedFields(obj.Type(), pkg.Types()); len(prom) > 0 {
613 var b strings.Builder
614 b.WriteString("// Embedded fields:\n")
615 w := tabwriter.NewWriter(&b, 0, 8, 1, ' ', 0)
616 for _, f := range prom {
617 fmt.Fprintf(w, "%s\t%s\t// through %s\t\n",
618 f.field.Name(),
619 types.TypeString(f.field.Type(), qual),
620 f.path)
621 }
622 w.Flush() // ignore error
623 b.WriteByte('\n')
624 fields = b.String()
625 }
626
627 // -- methods --
628
629 // For an interface type, explicit methods will have
630 // already been displayed when the node was formatted
631 // above. Don't list these again.
632 var skip map[string]bool
633 if iface, ok := spec1.Type.(*ast.InterfaceType); ok {
634 if iface.Methods.List != nil {
635 for _, m := range iface.Methods.List {
636 if len(m.Names) == 1 {
637 if skip == nil {
638 skip = make(map[string]bool)
639 }
640 skip[m.Names[0].Name] = true
641 }
642 }
643 }
644 }
645
646 // Display all the type's accessible methods,
647 // including those that require a pointer receiver,
648 // and those promoted from embedded struct fields or
649 // embedded interfaces.
650 var b strings.Builder
651 for _, m := range typeutil.IntuitiveMethodSet(obj.Type(), nil) {
652 if !accessibleTo(m.Obj(), pkg.Types()) {
653 continue // inaccessible
654 }
655 if skip[m.Obj().Name()] {
656 continue // redundant with format.Node above
657 }
658 if b.Len() > 0 {
659 b.WriteByte('\n')
660 }
661
662 // Use objectString for its prettier rendering of method receivers.
663 b.WriteString(objectString(m.Obj(), qual, token.NoPos, nil, nil))
664 }
665 methods = b.String()
666
667 signature = typeDecl + "\n" + methods
668 } else {
669 // Non-types
670 if sizeOffset != "" {
671 signature += " // " + sizeOffset
672 }
673 }
674
675 if isTypeName {
676 // get the real type decl only if current object is a type,
677 // for non-types, we'd better hide the real type decl to avoid possible confusion.
678 //
679 // realTypeDecl is defined to store the underlying definition of an alias.
680 realTypeDecl, _ := findRhsTypeDecl(ctx, snapshot, pkg, obj) // tolerate the error
681 if realTypeDecl != "" {
682 typeDecl += fmt.Sprintf("\n\n%s", realTypeDecl)
683 }
684 }
685
686 // Compute link data (on pkg.go.dev or other documentation host).
687 //
688 // If linkPath is empty, the symbol is not linkable.
689 var (
690 linkName string // => link title, always non-empty
691 linkPath string // => link path
692 anchor string // link anchor
693 linkMeta *metadata.Package // metadata for the linked package
694 )
695 {
696 linkMeta = findFileInDeps(snapshot, pkg.Metadata(), declPGF.URI)
697 if linkMeta == nil {
698 return protocol.Range{}, nil, bug.Errorf("no package data for %s", declPGF.URI)
699 }
700
701 // For package names, we simply link to their imported package.
702 if pkgName, ok := obj.(*types.PkgName); ok {
703 linkName = pkgName.Name()
704 linkPath = pkgName.Imported().Path()
705 impID := linkMeta.DepsByPkgPath[PackagePath(pkgName.Imported().Path())]
706 linkMeta = snapshot.Metadata(impID)
707 if linkMeta == nil {
708 // Broken imports have fake package paths, so it is not a bug if we
709 // don't have metadata. As of writing, there is no way to distinguish
710 // broken imports from a true bug where expected metadata is missing.
711 return protocol.Range{}, nil, fmt.Errorf("no package data for %s", declPGF.URI)
712 }
713 } else {
714 // For all others, check whether the object is in the package scope, or
715 // an exported field or method of an object in the package scope.
716 //
717 // We try to match pkgsite's heuristics for what is linkable, and what is
718 // not.
719 var recv types.Object
720 switch obj := obj.(type) {
721 case *types.Func:
722 sig := obj.Signature()
723 if sig.Recv() != nil {
724 tnames := typeToObjects(sig.Recv().Type())
725 if len(tnames) == 1 { // beware empty slice
726 recv = tnames[0]
727 }
728 }
729 case *types.Var:
730 if obj.IsField() {
731 if spec, ok := spec.(*ast.TypeSpec); ok {
732 typeName := spec.Name
733 scopeObj, _ := obj.Pkg().Scope().Lookup(typeName.Name).(*types.TypeName)
734 if scopeObj != nil {
735 if st, _ := scopeObj.Type().Underlying().(*types.Struct); st != nil {
736 for field := range st.Fields() {
737 if obj == field {
738 recv = scopeObj
739 }
740 }
741 }
742 }
743 }
744 }
745 }
746
747 // Even if the object is not available in package documentation, it may
748 // be embedded in a documented receiver. Detect this by searching
749 // enclosing selector expressions.
750 //
751 // TODO(rfindley): pkgsite doesn't document fields from embedding, just
752 // methods.
753 if recv == nil || !recv.Exported() {
754 if enclosing := searchForEnclosing(pkg.TypesInfo(), cur); enclosing != nil {
755 recv = enclosing
756 } else {
757 recv = nil // note: just recv = ... could result in a typed nil.
758 }
759 }
760
761 pkg := obj.Pkg()
762 if recv != nil {
763 linkName = fmt.Sprintf("(%s.%s).%s", pkg.Name(), recv.Name(), obj.Name())
764 if obj.Exported() && recv.Exported() && typesinternal.IsPackageLevel(recv) {
765 linkPath = pkg.Path()
766 anchor = fmt.Sprintf("%s.%s", recv.Name(), obj.Name())
767 }
768 } else {
769 linkName = fmt.Sprintf("%s.%s", pkg.Name(), obj.Name())
770 if obj.Exported() && typesinternal.IsPackageLevel(obj) {
771 linkPath = pkg.Path()
772 anchor = obj.Name()
773 }
774 }
775 }
776 }
777
778 if snapshot.IsGoPrivatePath(linkPath) || linkMeta.ForTest != "" {
779 linkPath = ""
780 } else if linkMeta.Module != nil && linkMeta.Module.Version != "" {
781 mod := linkMeta.Module
782 linkPath = strings.Replace(linkPath, mod.Path, cache.ResolvedString(mod), 1)
783 }
784
785 // Handle hover over an imported package name identifier.
786 if pkgName, ok := obj.(*types.PkgName); ok {
787 hoverRes, err := hoverPackageRef(ctx, snapshot, pkg, metadata.ImportPath(pkgName.Imported().Path()))
788 if err != nil {
789 return protocol.Range{}, nil, err
790 }
791 hoverRes.LinkAnchor = anchor
792 hoverRes.LinkPath = linkPath
793 hoverRes.SymbolName = linkName
794 return *hoverRange, hoverRes, nil // (hoverRes may be nil)
795 }
796
797 var footer string
798 if sym := StdSymbolOf(obj); sym != nil && sym.Version > 0 {
799 footer = fmt.Sprintf("Added in %v", sym.Version)
800 }
801
802 return *hoverRange, &hoverResult{
803 Synopsis: doc.Synopsis(docText),
804 FullDocumentation: docText,
805 SingleLine: singleLineSignature,
806 SymbolName: linkName,
807 Signature: signature,
808 LinkPath: linkPath,
809 LinkAnchor: anchor,
810 typeDecl: typeDecl,
811 methods: methods,
812 promotedFields: fields,
813 footer: footer,
814 }, nil
815 }
816
817 // typeDeclContent returns a well formatted type definition.
818 func typeDeclContent(declPGF *parsego.File, declPos token.Pos, name string) (string, *ast.TypeSpec, error) {
819 _, spec, _, _ := findDeclInfo([]*ast.File{declPGF.File}, declPos) // may be nil^4
820 // Don't duplicate comments.
821 spec1, ok := spec.(*ast.TypeSpec)
822 if !ok {
823 // We cannot find a TypeSpec for this type or alias declaration
824 // (that is not a type parameter or a built-in).
825 // This should be impossible even for ill-formed trees;
826 // we suspect that AST repair may be creating inconsistent
827 // positions. Don't report a bug in that case. (#64241)
828 errorf := fmt.Errorf
829 if !declPGF.Fixed() {
830 errorf = bug.Errorf
831 }
832 return "", nil, errorf("type name %q without type spec", name)
833 }
834 spec2 := *spec1
835 spec2.Doc = nil
836 spec2.Comment = nil
837
838 var b strings.Builder
839 b.WriteString("type ")
840 fset := tokeninternal.FileSetFor(declPGF.Tok)
841 // TODO(adonovan): use a smarter formatter that omits
842 // inaccessible fields (non-exported ones from other packages).
843 if err := format.Node(&b, fset, &spec2); err != nil {
844 return "", nil, err
845 }
846 typeDecl := b.String()
847 return typeDecl, spec1, nil
848 }
849
850 // hoverBuiltin computes hover information when hovering over a builtin
851 // identifier.
852 func hoverBuiltin(ctx context.Context, snapshot *cache.Snapshot, obj types.Object) (*hoverResult, error) {
853 // Special handling for error.Error, which is the only builtin method.
854 //
855 // TODO(rfindley): can this be unified with the handling below?
856 if obj.Name() == "Error" {
857 signature := obj.String()
858 return &hoverResult{
859 Signature: signature,
860 SingleLine: signature,
861 // TODO(rfindley): these are better than the current behavior.
862 // SymbolName: "(error).Error",
863 // LinkPath: "builtin",
864 // LinkAnchor: "error.Error",
865 }, nil
866 }
867
868 pgf, ident, err := builtinDecl(ctx, snapshot, obj)
869 if err != nil {
870 return nil, err
871 }
872
873 var (
874 comment *ast.CommentGroup
875 decl ast.Decl
876 )
877 curIdent, _ := pgf.Cursor().FindNode(ident) // can't fail
878 for cur := range curIdent.Enclosing() {
879 switch n := cur.Node().(type) {
880 case *ast.GenDecl:
881 // Separate documentation and signature.
882 comment = n.Doc
883 node2 := *n
884 node2.Doc = nil
885 decl = &node2
886 case *ast.FuncDecl:
887 // Ditto.
888 comment = n.Doc
889 node2 := *n
890 node2.Doc = nil
891 decl = &node2
892 }
893 }
894
895 signature := formatNodeFile(pgf.Tok, decl)
896 // Replace fake types with their common equivalent.
897 // TODO(rfindley): we should instead use obj.Type(), which would have the
898 // *actual* types of the builtin call.
899 signature = replacer.Replace(signature)
900
901 docText := comment.Text()
902 return &hoverResult{
903 Synopsis: doc.Synopsis(docText),
904 FullDocumentation: docText,
905 Signature: signature,
906 SingleLine: obj.String(),
907 SymbolName: obj.Name(),
908 LinkPath: "builtin",
909 LinkAnchor: obj.Name(),
910 }, nil
911 }
912
913 // hoverPackageRef computes hover information for the package of the specified
914 // path imported by pkg. If we do not have metadata for the hovered import, it
915 // returns _
916 func hoverPackageRef(ctx context.Context, snapshot *cache.Snapshot, pkg *cache.Package, importPath metadata.ImportPath) (*hoverResult, error) {
917 impID := pkg.Metadata().DepsByImpPath[importPath]
918 if impID == "" {
919 return nil, fmt.Errorf("no package data for import %q", importPath)
920 }
921 impMetadata := snapshot.Metadata(impID)
922 if impMetadata == nil {
923 return nil, bug.Errorf("failed to resolve import ID %q", impID)
924 }
925
926 // Find the first file with a package doc comment.
927 var comment *ast.CommentGroup
928 for _, f := range impMetadata.CompiledGoFiles {
929 fh, err := snapshot.ReadFile(ctx, f)
930 if err != nil {
931 if ctx.Err() != nil {
932 return nil, ctx.Err()
933 }
934 continue
935 }
936 pgf, err := snapshot.ParseGo(ctx, fh, parsego.Header)
937 if err != nil {
938 if ctx.Err() != nil {
939 return nil, ctx.Err()
940 }
941 continue
942 }
943 if pgf.File.Doc != nil {
944 comment = pgf.File.Doc
945 break
946 }
947 }
948
949 docText := comment.Text()
950 return &hoverResult{
951 Signature: "package " + string(impMetadata.Name),
952 Synopsis: doc.Synopsis(docText),
953 FullDocumentation: docText,
954 }, nil
955 }
956
957 // hoverPackageName computes hover information for the package name of the file
958 // pgf in pkg.
959 func hoverPackageName(pkg *cache.Package, pgf *parsego.File) (protocol.Range, *hoverResult, error) {
960 var comment *ast.CommentGroup
961 for _, pgf := range pkg.CompiledGoFiles() {
962 if pgf.File.Doc != nil {
963 comment = pgf.File.Doc
964 break
965 }
966 }
967 rng, err := pgf.NodeRange(pgf.File.Name)
968 if err != nil {
969 return protocol.Range{}, nil, err
970 }
971 docText := comment.Text()
972
973 // List some package attributes at the bottom of the documentation, if
974 // applicable.
975 type attr struct{ title, value string }
976 var attrs []attr
977
978 if !metadata.IsCommandLineArguments(pkg.Metadata().ID) {
979 attrs = append(attrs, attr{"Package path", string(pkg.Metadata().PkgPath)})
980 }
981
982 if pkg.Metadata().Module != nil {
983 attrs = append(attrs, attr{"Module", pkg.Metadata().Module.Path})
984 }
985
986 // Show the effective language version for this package.
987 if v := pkg.TypesInfo().FileVersions[pgf.File]; v != "" {
988 attr := attr{value: version.Lang(v)}
989 if v == pkg.Types().GoVersion() {
990 attr.title = "Language version"
991 } else {
992 attr.title = "Language version (current file)"
993 }
994 attrs = append(attrs, attr)
995 }
996
997 // TODO(rfindley): consider exec'ing go here to compute DefaultGODEBUG, or
998 // propose adding GODEBUG info to go/packages.
999
1000 var footer strings.Builder
1001 for i, attr := range attrs {
1002 if i > 0 {
1003 footer.WriteString("\n")
1004 }
1005 fmt.Fprintf(&footer, " - %s: %s", attr.title, attr.value)
1006 }
1007
1008 return rng, &hoverResult{
1009 Signature: "package " + string(pkg.Metadata().Name),
1010 Synopsis: doc.Synopsis(docText),
1011 FullDocumentation: docText,
1012 footer: footer.String(),
1013 }, nil
1014 }
1015
1016 // hoverConstantExpr computes information about the value of a constant expression.
1017 //
1018 // The provided start and end positions must be precise. For example, when hovering
1019 // over a string literal, the exact cursor position is used to identify and display
1020 // the value of the rune under the cursor.
1021 func hoverConstantExpr(pgf *parsego.File, expr ast.Expr, tv types.TypeAndValue, posRange astutil.Range) (protocol.Range, *hoverResult, error) {
1022 var (
1023 value string // if non-empty, a constant value to format in hover
1024 r rune // if non-zero, format a description of this rune in hover
1025 start, end token.Pos // hover span
1026 )
1027 if lit, ok := expr.(*ast.BasicLit); ok {
1028 switch tv.Value.Kind() {
1029 case constant.Bool:
1030 fallthrough
1031 case constant.Float:
1032 fallthrough
1033 case constant.Complex:
1034 fallthrough
1035 case constant.Unknown:
1036 // In most cases, basic literals are uninteresting.
1037 break
1038 case constant.Int:
1039 switch lit.Kind {
1040 case token.CHAR:
1041 s, err := strconv.Unquote(lit.Value)
1042 if err != nil {
1043 // If the conversion fails, it's because of an invalid syntax, therefore
1044 // there is no rune to be found.
1045 return protocol.Range{}, nil, nil
1046 }
1047 r, _ = utf8.DecodeRuneInString(s)
1048 if r == utf8.RuneError {
1049 return protocol.Range{}, nil, fmt.Errorf("rune error")
1050 }
1051 start, end = lit.Pos(), lit.End()
1052 case token.INT:
1053 // Short literals (e.g. 99 decimal, 07 octal) are uninteresting.
1054 if len(lit.Value) < 3 {
1055 return protocol.Range{}, nil, nil
1056 }
1057
1058 v := constant.MakeFromLiteral(lit.Value, lit.Kind, 0)
1059 if v.Kind() != constant.Int {
1060 return protocol.Range{}, nil, nil
1061 }
1062
1063 switch lit.Value[:2] {
1064 case "0x", "0X":
1065 // As a special case, try to recognize hexadecimal literals as runes if
1066 // they are within the range of valid unicode values.
1067 if v, ok := constant.Int64Val(v); ok && v > 0 && v <= utf8.MaxRune && utf8.ValidRune(rune(v)) {
1068 r = rune(v)
1069 }
1070 fallthrough
1071 case "0o", "0O", "0b", "0B":
1072 // Format the decimal value of non-decimal literals.
1073 value = v.ExactString()
1074 start, end = lit.Pos(), lit.End()
1075 default:
1076 return protocol.Range{}, nil, nil
1077 }
1078 }
1079 case constant.String:
1080 index, err := astutil.OffsetInStringLiteral(lit, posRange.Pos())
1081 if err != nil {
1082 return protocol.Range{}, nil, err
1083 }
1084 // pos is the point in the literal where the current rune starts.
1085 pos, err := astutil.PosInStringLiteral(lit, index)
1086 if err != nil {
1087 return protocol.Range{}, nil, err
1088 }
1089
1090 rest, err := pgf.PosText(pos, lit.End())
1091 if err != nil {
1092 return protocol.Range{}, nil, err
1093 }
1094
1095 // Is the selected character denoted by an escape sequence?
1096 if bytes.HasPrefix(rest, []byte(`\`)) {
1097 rr, _, tail, err := strconv.UnquoteChar(string(rest), lit.Value[0])
1098 if err != nil {
1099 return protocol.Range{}, nil, err
1100 }
1101
1102 rawSize := len(rest) - len(tail)
1103
1104 start, end = pos, pos+token.Pos(rawSize)
1105 r = rr
1106 }
1107 default:
1108 panic("unexpected constant.Kind")
1109 }
1110 } else {
1111 // By default, provide value information and the expression's range.
1112 // It is possible evaluated value will give us the wrong number because
1113 // type checker will perform error recovery.
1114 // E.g. expression like '\u22111' + 1 is invalid but type checker
1115 // will yield the value of `\u2211` + 1.
1116
1117 // We could be more smart about whether we want to evaluate an
1118 // [ast.Expr] as a number or as a rune by evaluating the syntax of
1119 // the expression. e.g. rune + int => rune, rune - int => rune.
1120 value = tv.Value.String()
1121 start, end = expr.Pos(), expr.End()
1122 }
1123
1124 if value == "" && r == 0 { // nothing to format
1125 return protocol.Range{}, nil, nil
1126 }
1127
1128 rng, err := pgf.PosRange(start, end)
1129 if err != nil {
1130 return protocol.Range{}, nil, err
1131 }
1132
1133 var b strings.Builder
1134 if value != "" {
1135 b.WriteString(value)
1136 }
1137 if r != 0 {
1138 runeName := runenames.Name(r)
1139 if len(runeName) > 0 && runeName[0] == '<' {
1140 // Check if the rune looks like an HTML tag. If so, trim the surrounding <>
1141 // characters to work around https://github.com/microsoft/vscode/issues/124042.
1142 runeName = strings.TrimRight(runeName[1:], ">")
1143 }
1144 if b.Len() > 0 {
1145 b.WriteString(", ")
1146 }
1147 if strconv.IsPrint(r) {
1148 fmt.Fprintf(&b, "'%c', ", r)
1149 }
1150 fmt.Fprintf(&b, "U+%04X, %s", r, runeName)
1151 }
1152 hover := b.String()
1153 return rng, &hoverResult{
1154 Synopsis: hover,
1155 FullDocumentation: hover,
1156 }, nil
1157 }
1158
1159 func hoverReturnStatement(pgf *parsego.File, curReturn inspector.Cursor) (protocol.Range, *hoverResult, error) {
1160 var funcType *ast.FuncType
1161 // Find innermost enclosing function.
1162 for c := range curReturn.Enclosing((*ast.FuncDecl)(nil), (*ast.FuncLit)(nil)) {
1163 switch n := c.Node().(type) {
1164 case *ast.FuncLit:
1165 funcType = n.Type
1166 case *ast.FuncDecl:
1167 funcType = n.Type
1168 }
1169 if funcType != nil {
1170 break
1171 }
1172 }
1173 // Inv: funcType != nil because a ReturnStmt is always enclosed by a function.
1174 if funcType.Results == nil {
1175 return protocol.Range{}, nil, nil // no result variables
1176 }
1177 rng, err := pgf.NodeRange(curReturn.Node())
1178 if err != nil {
1179 return protocol.Range{}, nil, err
1180 }
1181 // Format the function's result type.
1182 var buf strings.Builder
1183 var cfg printer.Config
1184 fset := token.NewFileSet()
1185 buf.WriteString("returns (")
1186 for i, field := range funcType.Results.List {
1187 if i > 0 {
1188 buf.WriteString(", ")
1189 }
1190 cfg.Fprint(&buf, fset, field.Type) // ignore error
1191 }
1192 buf.WriteByte(')')
1193 return rng, &hoverResult{
1194 Signature: buf.String(),
1195 }, nil
1196 }
1197
1198 // hoverEmbed computes hover information for a filepath.Match pattern.
1199 // Assumes that the pattern is relative to the location of fh.
1200 func hoverEmbed(fh file.Handle, rng protocol.Range, pattern string) (protocol.Range, *hoverResult, error) {
1201 s := &strings.Builder{}
1202
1203 dir := fh.URI().DirPath()
1204 var matches []string
1205 err := filepath.WalkDir(dir, func(abs string, d fs.DirEntry, e error) error {
1206 if e != nil {
1207 return e
1208 }
1209 rel, err := filepath.Rel(dir, abs)
1210 if err != nil {
1211 return err
1212 }
1213 ok, err := filepath.Match(pattern, rel)
1214 if err != nil {
1215 return err
1216 }
1217 if ok && !d.IsDir() {
1218 matches = append(matches, rel)
1219 }
1220 return nil
1221 })
1222 if err != nil {
1223 return protocol.Range{}, nil, err
1224 }
1225
1226 for _, m := range matches {
1227 // TODO: Renders each file as separate markdown paragraphs.
1228 // If forcing (a single) newline is possible it might be more clear.
1229 fmt.Fprintf(s, "%s\n\n", m)
1230 }
1231
1232 res := &hoverResult{
1233 Signature: fmt.Sprintf("Embedding %q", pattern),
1234 Synopsis: s.String(),
1235 FullDocumentation: s.String(),
1236 }
1237 return rng, res, nil
1238 }
1239
1240 // objectString is a wrapper around the types.ObjectString function.
1241 // It handles adding more information to the object string.
1242 // If spec is non-nil, it may be used to format additional declaration
1243 // syntax, and file must be the token.File describing its positions.
1244 //
1245 // Precondition: obj is not a built-in function or method.
1246 func objectString(obj types.Object, qual types.Qualifier, declPos token.Pos, file *token.File, spec ast.Spec) string {
1247 str := types.ObjectString(obj, qual)
1248
1249 switch obj := obj.(type) {
1250 case *types.Func:
1251 // We fork ObjectString to improve its rendering of methods:
1252 // specifically, we show the receiver name,
1253 // and replace the period in (T).f by a space (#62190).
1254
1255 sig := obj.Signature()
1256
1257 var buf bytes.Buffer
1258 buf.WriteString("func ")
1259 if recv := sig.Recv(); recv != nil {
1260 buf.WriteByte('(')
1261 if _, ok := recv.Type().(*types.Interface); ok {
1262 // gcimporter creates abstract methods of
1263 // named interfaces using the interface type
1264 // (not the named type) as the receiver.
1265 // Don't print it in full.
1266 buf.WriteString("interface")
1267 } else {
1268 // Show receiver name (go/types does not).
1269 name := recv.Name()
1270 if name != "" && name != "_" {
1271 buf.WriteString(name)
1272 buf.WriteString(" ")
1273 }
1274 types.WriteType(&buf, recv.Type(), qual)
1275 }
1276 buf.WriteByte(')')
1277 buf.WriteByte(' ') // space (go/types uses a period)
1278 } else if s := qual(obj.Pkg()); s != "" {
1279 buf.WriteString(s)
1280 buf.WriteString(".")
1281 }
1282 buf.WriteString(obj.Name())
1283 types.WriteSignature(&buf, sig, qual)
1284 str = buf.String()
1285
1286 case *types.Const:
1287 // Show value of a constant.
1288 var (
1289 declaration = obj.Val().String() // default formatted declaration
1290 comment = "" // if non-empty, a clarifying comment
1291 )
1292
1293 // Try to use the original declaration.
1294 switch obj.Val().Kind() {
1295 case constant.String:
1296 // Usually the original declaration of a string doesn't carry much information.
1297 // Also strings can be very long. So, just use the constant's value.
1298
1299 default:
1300 if spec, _ := spec.(*ast.ValueSpec); spec != nil {
1301 for i, name := range spec.Names {
1302 if declPos == name.Pos() {
1303 if i < len(spec.Values) {
1304 originalDeclaration := formatNodeFile(file, spec.Values[i])
1305 if originalDeclaration != declaration {
1306 comment = declaration
1307 declaration = originalDeclaration
1308 }
1309 }
1310 break
1311 }
1312 }
1313 }
1314 }
1315
1316 // Special formatting cases.
1317 switch typ := types.Unalias(obj.Type()).(type) {
1318 case *types.Named:
1319 // Try to add a formatted duration as an inline comment.
1320 pkg := typ.Obj().Pkg()
1321 if pkg.Path() == "time" && typ.Obj().Name() == "Duration" && obj.Val().Kind() == constant.Int {
1322 if d, ok := constant.Int64Val(obj.Val()); ok {
1323 comment = time.Duration(d).String()
1324 }
1325 }
1326 }
1327 if comment == declaration {
1328 comment = ""
1329 }
1330
1331 str += " = " + declaration
1332 if comment != "" {
1333 str += " // " + comment
1334 }
1335 }
1336 return str
1337 }
1338
1339 // HoverDocForObject returns the best doc comment for obj (for which
1340 // fset provides file/line information).
1341 //
1342 // TODO(rfindley): there appears to be zero(!) tests for this functionality.
1343 func HoverDocForObject(ctx context.Context, snapshot *cache.Snapshot, fset *token.FileSet, obj types.Object) (*ast.CommentGroup, error) {
1344 if is[*types.TypeName](obj) && is[*types.TypeParam](obj.Type()) {
1345 return nil, nil
1346 }
1347
1348 pgf, pos, err := parseFull(ctx, snapshot, fset, obj)
1349 if err != nil {
1350 return nil, fmt.Errorf("re-parsing: %v", err)
1351 }
1352
1353 decl, spec, field, assign := findDeclInfo([]*ast.File{pgf.File}, pos)
1354 return chooseDocComment(pgf, decl, spec, field, assign), nil
1355 }
1356
1357 // chooseDocComment returns the best doc comment for the given declaration
1358 // information.
1359 func chooseDocComment(pgf *parsego.File, decl ast.Decl, spec ast.Spec, field *ast.Field, assign *ast.AssignStmt) *ast.CommentGroup {
1360 if assign != nil {
1361 // AssignStmt lacks a Doc field; locate the comment on the line above.
1362 tokFile := pgf.Tok
1363 compare := func(cg *ast.CommentGroup, line int) int {
1364 return cmp.Compare(safetoken.Line(tokFile, cg.End()), line-1)
1365 }
1366 assignLine := safetoken.Line(tokFile, assign.Pos())
1367 i, found := slices.BinarySearchFunc(pgf.File.Comments, assignLine, compare)
1368 if found {
1369 // The comment must start at the beginning of the line, otherwise it may
1370 // be a comment on a previous assignment.
1371 comment := pgf.File.Comments[i]
1372 lineStart := pgf.Tok.LineStart(safetoken.Position(tokFile, comment.Pos()).Line)
1373 if comment.Pos()-lineStart <= 1 {
1374 return comment
1375 }
1376 }
1377 }
1378 if field != nil {
1379 if field.Doc != nil {
1380 return field.Doc
1381 }
1382 if field.Comment != nil {
1383 return field.Comment
1384 }
1385 return nil
1386 }
1387 switch decl := decl.(type) {
1388 case *ast.FuncDecl:
1389 return decl.Doc
1390 case *ast.GenDecl:
1391 switch spec := spec.(type) {
1392 case *ast.ValueSpec:
1393 if spec.Doc != nil {
1394 return spec.Doc
1395 }
1396 if decl.Doc != nil {
1397 return decl.Doc
1398 }
1399 return spec.Comment
1400 case *ast.TypeSpec:
1401 if spec.Doc != nil {
1402 return spec.Doc
1403 }
1404 if decl.Doc != nil {
1405 return decl.Doc
1406 }
1407 return spec.Comment
1408 }
1409 }
1410 return nil
1411 }
1412
1413 // parseFull fully parses the file containing the declaration of obj
1414 // (for which fset provides file/line information). It returns the
1415 // parsego.File and the position of the declaration within it.
1416 //
1417 // BEWARE: the provided FileSet is used only to interpret the provided
1418 // pos; the resulting File and Pos may belong to the same or a
1419 // different FileSet, such as one synthesized by the parser cache, if
1420 // parse-caching is enabled.
1421 func parseFull(ctx context.Context, snapshot *cache.Snapshot, fset *token.FileSet, obj types.Object) (*parsego.File, token.Pos, error) {
1422 if isBuiltin(obj) {
1423 pgf, id, err := builtinDecl(ctx, snapshot, obj)
1424 if err != nil {
1425 return nil, 0, err
1426 }
1427 return pgf, id.Pos(), err
1428 }
1429 pos := obj.Pos()
1430 f := fset.File(pos)
1431 if f == nil {
1432 return nil, 0, bug.Errorf("internal error: no file for position %d", pos)
1433 }
1434
1435 uri := protocol.URIFromPath(f.Name())
1436 fh, err := snapshot.ReadFile(ctx, uri)
1437 if err != nil {
1438 return nil, 0, err
1439 }
1440
1441 pgf, err := snapshot.ParseGo(ctx, fh, parsego.Full)
1442 if err != nil {
1443 return nil, 0, err
1444 }
1445
1446 // Translate pos from original file to new file.
1447 offset, err := safetoken.Offset(f, pos)
1448 if err != nil {
1449 return nil, 0, bug.Errorf("offset out of bounds in %q", uri)
1450 }
1451 fullPos, err := safetoken.Pos(pgf.Tok, offset)
1452 if err != nil {
1453 return nil, 0, err
1454 }
1455
1456 return pgf, fullPos, nil
1457 }
1458
1459 // If pkgURL is non-nil, it should be used to generate doc links.
1460 func formatHover(h *hoverResult, options *settings.Options, pkgURL func(path PackagePath, fragment string) protocol.URI) (string, error) {
1461 markdown := options.PreferredContentFormat == protocol.Markdown
1462 maybeFenced := func(s string) string {
1463 if s != "" && markdown {
1464 s = fmt.Sprintf("```go\n%s\n```", strings.Trim(s, "\n"))
1465 }
1466 return s
1467 }
1468
1469 switch options.HoverKind {
1470 case settings.SingleLine:
1471 return h.SingleLine, nil
1472
1473 case settings.NoDocumentation:
1474 return maybeFenced(h.Signature), nil
1475
1476 case settings.Structured:
1477 b, err := json.Marshal(h)
1478 if err != nil {
1479 return "", err
1480 }
1481 return string(b), nil
1482
1483 case settings.SynopsisDocumentation, settings.FullDocumentation:
1484 var sections [][]string // assembled below
1485
1486 // Signature section.
1487 //
1488 // For types, we display TypeDecl and Methods,
1489 // but not Signature, which is redundant (= TypeDecl + "\n" + Methods).
1490 // For all other symbols, we display Signature;
1491 // TypeDecl and Methods are empty.
1492 // TODO(golang/go#70233): When JSON is no more, we could rationalize this.
1493 if h.typeDecl != "" {
1494 sections = append(sections, []string{maybeFenced(h.typeDecl)})
1495 } else {
1496 sections = append(sections, []string{maybeFenced(h.Signature)})
1497 }
1498
1499 // Doc section.
1500 var doc string
1501 switch options.HoverKind {
1502 case settings.SynopsisDocumentation:
1503 doc = h.Synopsis
1504 case settings.FullDocumentation:
1505 doc = h.FullDocumentation
1506 }
1507 if options.PreferredContentFormat == protocol.Markdown {
1508 doc = DocCommentToMarkdown(doc, options)
1509 }
1510 sections = append(sections, []string{
1511 doc,
1512 maybeFenced(h.promotedFields),
1513 maybeFenced(h.methods),
1514 })
1515
1516 // Footer section.
1517 sections = append(sections, []string{
1518 h.footer,
1519 formatLink(h, options, pkgURL),
1520 })
1521
1522 var b strings.Builder
1523 newline := func() {
1524 if options.PreferredContentFormat == protocol.Markdown {
1525 b.WriteString("\n\n")
1526 } else {
1527 b.WriteByte('\n')
1528 }
1529 }
1530 for _, section := range sections {
1531 start := b.Len()
1532 for _, part := range section {
1533 if part == "" {
1534 continue
1535 }
1536 // When markdown is available, insert an hline before the start of
1537 // the section, if there is content above.
1538 if markdown && b.Len() == start && start > 0 {
1539 newline()
1540 b.WriteString("---")
1541 }
1542 if b.Len() > 0 {
1543 newline()
1544 }
1545 b.WriteString(part)
1546 }
1547 }
1548 return b.String(), nil
1549
1550 default:
1551 return "", fmt.Errorf("invalid HoverKind: %v", options.HoverKind)
1552 }
1553 }
1554
1555 // StdSymbolOf returns the std lib symbol information of the given obj.
1556 // It returns nil if the input obj is not an exported standard library symbol.
1557 func StdSymbolOf(obj types.Object) *stdlib.Symbol {
1558 if !obj.Exported() || obj.Pkg() == nil {
1559 return nil
1560 }
1561
1562 // Symbols that not defined in standard library should return early.
1563 // TODO(hxjiang): The returned slices is binary searchable.
1564 symbols := stdlib.PackageSymbols[obj.Pkg().Path()]
1565 if symbols == nil {
1566 return nil
1567 }
1568
1569 // Handle Function, Type, Const & Var.
1570 if obj != nil && typesinternal.IsPackageLevel(obj) {
1571 for _, s := range symbols {
1572 if s.Kind == stdlib.Method || s.Kind == stdlib.Field {
1573 continue
1574 }
1575 if s.Name == obj.Name() {
1576 return &s
1577 }
1578 }
1579 return nil
1580 }
1581
1582 // Handle Method.
1583 if fn, _ := obj.(*types.Func); fn != nil {
1584 isPtr, named := typesinternal.ReceiverNamed(fn.Signature().Recv())
1585 if named != nil && typesinternal.IsPackageLevel(named.Obj()) {
1586 for _, s := range symbols {
1587 if s.Kind != stdlib.Method {
1588 continue
1589 }
1590 ptr, recv, name := s.SplitMethod()
1591 if ptr == isPtr && recv == named.Obj().Name() && name == fn.Name() {
1592 return &s
1593 }
1594 }
1595 return nil
1596 }
1597 }
1598
1599 // Handle Field.
1600 if v, _ := obj.(*types.Var); v != nil && v.IsField() {
1601 for _, s := range symbols {
1602 if s.Kind != stdlib.Field {
1603 continue
1604 }
1605
1606 typeName, fieldName := s.SplitField()
1607 if fieldName != v.Name() {
1608 continue
1609 }
1610
1611 typeObj := obj.Pkg().Scope().Lookup(typeName)
1612 if typeObj == nil {
1613 continue
1614 }
1615
1616 if fieldObj, _, _ := types.LookupFieldOrMethod(typeObj.Type(), true, obj.Pkg(), fieldName); obj == fieldObj {
1617 return &s
1618 }
1619 }
1620 return nil
1621 }
1622
1623 return nil
1624 }
1625
1626 // If pkgURL is non-nil, it should be used to generate doc links.
1627 func formatLink(h *hoverResult, options *settings.Options, pkgURL func(path PackagePath, fragment string) protocol.URI) string {
1628 if options.LinksInHover == settings.LinksInHover_None || h.LinkPath == "" {
1629 return ""
1630 }
1631 var url protocol.URI
1632 var caption string
1633 if pkgURL != nil { // LinksInHover == "gopls"
1634 // Discard optional module version portion.
1635 // (Ideally the hoverResult would retain the structure...)
1636 path := h.LinkPath
1637 if module, versionDir, ok := strings.Cut(h.LinkPath, "@"); ok {
1638 // "module@version/dir"
1639 path = module
1640 if _, dir, ok := strings.Cut(versionDir, "/"); ok {
1641 path += "/" + dir
1642 }
1643 }
1644 url = pkgURL(PackagePath(path), h.LinkAnchor)
1645 caption = "in gopls doc viewer"
1646 } else {
1647 if options.LinkTarget == "" {
1648 return ""
1649 }
1650 url = cache.BuildLink(options.LinkTarget, h.LinkPath, h.LinkAnchor)
1651 caption = "on " + options.LinkTarget
1652 }
1653 switch options.PreferredContentFormat {
1654 case protocol.Markdown:
1655 return fmt.Sprintf("[`%s` %s](%s)", h.SymbolName, caption, url)
1656 case protocol.PlainText:
1657 return ""
1658 default:
1659 return url
1660 }
1661 }
1662
1663 // findDeclInfo returns the syntax nodes involved in the declaration of the
1664 // types.Object with position pos, searching the given list of file syntax
1665 // trees.
1666 //
1667 // Pos may be the position of the name-defining identifier in an AssignStmt,
1668 // FuncDecl, ValueSpec, TypeSpec, Field, or as a special case the position of
1669 // Ellipsis.Elt in an ellipsis field.
1670 //
1671 // If found, the resulting decl, spec, field and assign will be the inner-most
1672 // instance of each node type surrounding pos.
1673 //
1674 // If field is non-nil, pos is the position of a field Var. If field is nil and
1675 // spec is non-nil, pos is the position of a Var, Const, or TypeName object. If
1676 // both field and spec are nil and decl is non-nil, pos is the position of a
1677 // Func object. If assign is non-nil, pos is the position of the assignment of a
1678 // function literal.
1679 //
1680 // It returns a nil decl if no object-defining node is found at pos.
1681 //
1682 // TODO(rfindley): this function has tricky semantics, and may be worth unit
1683 // testing and/or refactoring.
1684 func findDeclInfo(files []*ast.File, pos token.Pos) (decl ast.Decl, spec ast.Spec, field *ast.Field, assign *ast.AssignStmt) {
1685 found := false
1686
1687 // Visit the files in search of the node at pos.
1688 stack := make([]ast.Node, 0, 20)
1689
1690 // Allocate the closure once, outside the loop.
1691 f := func(n ast.Node, stack []ast.Node) bool {
1692 if found {
1693 return false
1694 }
1695
1696 // Skip subtrees (incl. files) that don't contain the search point.
1697 if !(n.Pos() <= pos && pos < n.End()) {
1698 return false
1699 }
1700
1701 switch n := n.(type) {
1702 case *ast.AssignStmt:
1703 if len(n.Lhs) != 1 {
1704 return false
1705 }
1706 lhs := n.Lhs[0]
1707 if lhs.Pos() == pos {
1708 assign = n
1709 found = true
1710 return false
1711 }
1712
1713 case *ast.Field:
1714 findEnclosingDeclAndSpec := func() {
1715 for _, n := range slices.Backward(stack) {
1716 switch n := n.(type) {
1717 case ast.Spec:
1718 spec = n
1719 case ast.Decl:
1720 decl = n
1721 return
1722 }
1723 }
1724 }
1725
1726 // Check each field name since you can have
1727 // multiple names for the same type expression.
1728 for _, id := range n.Names {
1729 if id.Pos() == pos {
1730 field = n
1731 findEnclosingDeclAndSpec()
1732 found = true
1733 return false
1734 }
1735 }
1736
1737 // Check *ast.Field itself. This handles embedded
1738 // fields which have no associated *ast.Ident name.
1739 if n.Pos() == pos {
1740 field = n
1741 findEnclosingDeclAndSpec()
1742 found = true
1743 return false
1744 }
1745
1746 // Also check "X" in "...X". This makes it easy to format variadic
1747 // signature params properly.
1748 //
1749 // TODO(rfindley): I don't understand this comment. How does finding the
1750 // field in this case make it easier to format variadic signature params?
1751 if ell, ok := n.Type.(*ast.Ellipsis); ok && ell.Elt != nil && ell.Elt.Pos() == pos {
1752 field = n
1753 findEnclosingDeclAndSpec()
1754 found = true
1755 return false
1756 }
1757
1758 case *ast.FuncDecl:
1759 if n.Name.Pos() == pos {
1760 decl = n
1761 found = true
1762 return false
1763 }
1764
1765 case *ast.GenDecl:
1766 for _, s := range n.Specs {
1767 switch s := s.(type) {
1768 case *ast.TypeSpec:
1769 if s.Name.Pos() == pos {
1770 decl = n
1771 spec = s
1772 found = true
1773 return false
1774 }
1775 case *ast.ValueSpec:
1776 for _, id := range s.Names {
1777 if id.Pos() == pos {
1778 decl = n
1779 spec = s
1780 found = true
1781 return false
1782 }
1783 }
1784 }
1785 }
1786 }
1787 return true
1788 }
1789 for _, file := range files {
1790 ast.PreorderStack(file, stack, f)
1791 if found {
1792 return decl, spec, field, assign
1793 }
1794 }
1795
1796 return nil, nil, nil, nil
1797 }
1798
1799 type promotedField struct {
1800 path string // path (e.g. "x.y" through embedded fields)
1801 field *types.Var
1802 }
1803
1804 // promotedFields returns the list of accessible promoted fields of a struct type t.
1805 // (Logic plundered from x/tools/cmd/guru/describe.go.)
1806 func promotedFields(t types.Type, from *types.Package) []promotedField {
1807 wantField := func(f *types.Var) bool {
1808 if !accessibleTo(f, from) {
1809 return false
1810 }
1811 // Check that the field is not shadowed.
1812 obj, _, _ := types.LookupFieldOrMethod(t, true, f.Pkg(), f.Name())
1813 return obj == f
1814 }
1815
1816 var fields []promotedField
1817 var visit func(t types.Type, stack []*types.Named)
1818 visit = func(t types.Type, stack []*types.Named) {
1819 tStruct, ok := typesinternal.Unpointer(t).Underlying().(*types.Struct)
1820 if !ok {
1821 return
1822 }
1823 fieldloop:
1824 for f := range tStruct.Fields() {
1825
1826 // Handle recursion through anonymous fields.
1827 if f.Anonymous() {
1828 if _, named := typesinternal.ReceiverNamed(f); named != nil {
1829 // If we've already visited this named type
1830 // on this path, break the cycle.
1831 for _, x := range stack {
1832 if x.Origin() == named.Origin() {
1833 continue fieldloop
1834 }
1835 }
1836 visit(f.Type(), append(stack, named))
1837 }
1838 }
1839
1840 // Save accessible promoted fields.
1841 if len(stack) > 0 && wantField(f) {
1842 var path strings.Builder
1843 for i, t := range stack {
1844 if i > 0 {
1845 path.WriteByte('.')
1846 }
1847 path.WriteString(t.Obj().Name())
1848 }
1849 fields = append(fields, promotedField{
1850 path: path.String(),
1851 field: f,
1852 })
1853 }
1854 }
1855 }
1856 visit(t, nil)
1857
1858 return fields
1859 }
1860
1861 func accessibleTo(obj types.Object, pkg *types.Package) bool {
1862 return obj.Exported() || obj.Pkg() == pkg
1863 }
1864
1865 // computeSizeOffsetInfo reports the size of obj (if a type or struct
1866 // field), its wasted space percentage (if a struct type), and its
1867 // offset (if a struct field). curIdent is obj's declaring identifier.
1868 // It returns -1 for undefined components.
1869 func computeSizeOffsetInfo(pkg *cache.Package, curIdent inspector.Cursor, obj types.Object) (size, wasted, offset int64) {
1870 size, wasted, offset = -1, -1, -1
1871
1872 var free typeparams.Free
1873 sizes := pkg.TypesSizes()
1874
1875 // size (types and fields)
1876 if v, ok := obj.(*types.Var); ok && v.IsField() || is[*types.TypeName](obj) {
1877 // If the field's type has free type parameters,
1878 // its size cannot be computed.
1879 if !free.Has(obj.Type()) {
1880 size = sizes.Sizeof(obj.Type())
1881 }
1882
1883 // wasted space (struct types)
1884 if tStruct, ok := obj.Type().Underlying().(*types.Struct); ok && is[*types.TypeName](obj) && size > 0 {
1885 fields := slices.Collect(tStruct.Fields())
1886 if len(fields) > 0 {
1887 // Sort into descending (most compact) order
1888 // and recompute size of entire struct.
1889 sort.Slice(fields, func(i, j int) bool {
1890 return sizes.Sizeof(fields[i].Type()) >
1891 sizes.Sizeof(fields[j].Type())
1892 })
1893 offsets := sizes.Offsetsof(fields)
1894 compactSize := offsets[len(offsets)-1] + sizes.Sizeof(fields[len(fields)-1].Type())
1895 wasted = 100 * (size - compactSize) / size
1896 }
1897 }
1898 }
1899
1900 // offset (fields)
1901 if v, ok := obj.(*types.Var); ok && v.IsField() {
1902 // Find enclosing struct type.
1903 var tStruct *types.Struct
1904 if n, _ := cursorutil.FirstEnclosing[*ast.StructType](curIdent); n != nil {
1905 t, ok := pkg.TypesInfo().TypeOf(n).(*types.Struct)
1906 if ok {
1907 // golang/go#69150: TypeOf(n) was observed not to be a Struct (likely
1908 // nil) in some cases.
1909 tStruct = t
1910 }
1911 }
1912 if tStruct != nil {
1913 var fields []*types.Var
1914 for f := range tStruct.Fields() {
1915 // If any preceding field's type has free type parameters,
1916 // its offset cannot be computed.
1917 if free.Has(f.Type()) {
1918 break
1919 }
1920 fields = append(fields, f)
1921 if f == v {
1922 offsets := sizes.Offsetsof(fields)
1923 offset = offsets[len(offsets)-1]
1924 break
1925 }
1926 }
1927 }
1928 }
1929
1930 return
1931 }
1932
1933 // sizeClass reports the size class for a struct of the specified size, or -1 if unknown.f
1934 // See GOROOT/src/runtime/msize.go for details.
1935 func sizeClass(size int64) int64 {
1936 if size > 1<<16 {
1937 return -1 // avoid allocation
1938 }
1939 // We assume that bytes.Clone doesn't trim,
1940 // and reports the underlying size class; see TestSizeClass.
1941 return int64(cap(bytes.Clone(make([]byte, size))))
1942 }