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.
17 "golang.org/x/tools/internal/event"
18 "golang.org/x/tools/internal/lsp/protocol"
19 errors "golang.org/x/xerrors"
22 type HoverInformation struct {
23 // Signature is the symbol's signature.
24 Signature string `json:"signature"`
26 // SingleLine is a single line describing the symbol.
27 // This is recommended only for use in clients that show a single line for hover.
28 SingleLine string `json:"singleLine"`
30 // Synopsis is a single sentence synopsis of the symbol's documentation.
31 Synopsis string `json:"synopsis"`
33 // FullDocumentation is the symbol's full documentation.
34 FullDocumentation string `json:"fullDocumentation"`
36 // LinkPath is the pkg.go.dev link for the given symbol.
37 // For example, the "go/ast" part of "pkg.go.dev/go/ast#Node".
38 LinkPath string `json:"linkPath"`
40 // LinkAnchor is the pkg.go.dev link anchor for the given symbol.
41 // For example, the "Node" part of "pkg.go.dev/go/ast#Node".
42 LinkAnchor string `json:"linkAnchor"`
44 // importPath is the import path for the package containing the given
48 // symbolName is the types.Object.Name for the given symbol.
52 comment *ast.CommentGroup
54 // isTypeName reports whether the identifier is a type name. In such cases,
55 // the hover has the prefix "type ".
59 func Hover(ctx context.Context, snapshot Snapshot, fh FileHandle, position protocol.Position) (*protocol.Hover, error) {
60 ident, err := Identifier(ctx, snapshot, fh, position)
64 h, err := HoverIdentifier(ctx, ident)
68 rng, err := ident.Range()
72 // See golang/go#36998: don't link to modules matching GOPRIVATE.
73 if snapshot.View().IsGoPrivatePath(h.importPath) {
76 hover, err := FormatHover(h, snapshot.View().Options())
80 return &protocol.Hover{
81 Contents: protocol.MarkupContent{
82 Kind: snapshot.View().Options().PreferredContentFormat,
89 func HoverIdentifier(ctx context.Context, i *IdentifierInfo) (*HoverInformation, error) {
90 ctx, done := event.Start(ctx, "source.Hover")
93 fset := i.Snapshot.FileSet()
94 h, err := HoverInfo(ctx, i.pkg, i.Declaration.obj, i.Declaration.node)
98 // Determine the symbol's signature.
99 switch x := h.source.(type) {
101 var b strings.Builder
102 if err := format.Node(&b, fset, x); err != nil {
105 h.Signature = b.String()
107 h.Signature = "type " + h.Signature
110 // If the variable is implicitly declared in a type switch, we need to
111 // manually generate its object string.
112 if typ := i.Declaration.typeSwitchImplicit; typ != nil {
113 if v, ok := x.(*types.Var); ok {
114 h.Signature = fmt.Sprintf("var %s %s", v.Name(), types.TypeString(typ, i.qf))
118 h.Signature = objectString(x, i.qf)
120 if obj := i.Declaration.obj; obj != nil {
121 h.SingleLine = objectString(obj, i.qf)
123 obj := i.Declaration.obj
127 switch obj := obj.(type) {
129 h.importPath = obj.Imported().Path()
130 h.LinkPath = h.importPath
131 h.symbolName = obj.Name()
132 if mod, version, ok := moduleAtVersion(h.LinkPath, i); ok {
133 h.LinkPath = strings.Replace(h.LinkPath, mod, mod+"@"+version, 1)
137 h.importPath = "builtin"
138 h.LinkPath = h.importPath
139 h.LinkAnchor = obj.Name()
140 h.symbolName = h.LinkAnchor
143 // Check if the identifier is test-only (and is therefore not part of a
144 // package's API). This is true if the request originated in a test package,
145 // and if the declaration is also found in the same test package.
146 if i.pkg != nil && obj.Pkg() != nil && i.pkg.ForTest() != "" {
147 if _, err := i.pkg.File(i.Declaration.MappedRange[0].URI()); err == nil {
151 // Don't return links for other unexported types.
156 switch obj := obj.(type) {
158 // If the object is a field, and we have an associated selector
159 // composite literal, or struct, we can determine the link.
161 if named, ok := i.enclosing.(*types.Named); ok {
162 rTypeName = named.Obj().Name()
166 typ, ok := obj.Type().(*types.Signature)
170 if r := typ.Recv(); r != nil {
171 switch rtyp := Deref(r.Type()).(type) {
175 // If we have an unexported type, see if the enclosing type is
176 // exported (we may have an interface or struct we can link
177 // to). If not, don't show any link.
178 if !rtyp.Obj().Exported() {
179 if named, ok := i.enclosing.(*types.Named); ok && named.Obj().Exported() {
180 rTypeName = named.Obj().Name()
185 rTypeName = rtyp.Obj().Name()
190 h.importPath = obj.Pkg().Path()
191 h.LinkPath = h.importPath
192 if mod, version, ok := moduleAtVersion(h.LinkPath, i); ok {
193 h.LinkPath = strings.Replace(h.LinkPath, mod, mod+"@"+version, 1)
196 h.LinkAnchor = fmt.Sprintf("%s.%s", rTypeName, obj.Name())
197 h.symbolName = fmt.Sprintf("(%s.%s).%s", obj.Pkg().Name(), rTypeName, obj.Name())
200 // For most cases, the link is "package/path#symbol".
201 h.LinkAnchor = obj.Name()
202 h.symbolName = fmt.Sprintf("%s.%s", obj.Pkg().Name(), obj.Name())
206 func moduleAtVersion(path string, i *IdentifierInfo) (string, string, bool) {
207 if strings.ToLower(i.Snapshot.View().Options().LinkTarget) != "pkg.go.dev" {
210 impPkg, err := i.pkg.GetImport(path)
214 if impPkg.Version() == nil {
217 version, modpath := impPkg.Version().Version, impPkg.Version().Path
218 if modpath == "" || version == "" {
221 return modpath, version, true
224 // objectString is a wrapper around the types.ObjectString function.
225 // It handles adding more information to the object string.
226 func objectString(obj types.Object, qf types.Qualifier) string {
227 str := types.ObjectString(obj, qf)
228 switch obj := obj.(type) {
230 str = fmt.Sprintf("%s = %s", str, obj.Val())
235 // HoverInfo returns a HoverInformation struct for an ast node and its type
237 func HoverInfo(ctx context.Context, pkg Package, obj types.Object, node ast.Node) (*HoverInformation, error) {
238 var info *HoverInformation
240 switch node := node.(type) {
242 // The package declaration.
243 for _, f := range pkg.GetSyntax() {
245 info = &HoverInformation{comment: f.Doc}
248 case *ast.ImportSpec:
249 // Try to find the package documentation for an imported package.
250 if pkgName, ok := obj.(*types.PkgName); ok {
251 imp, err := pkg.GetImport(pkgName.Imported().Path())
255 // Assume that only one file will contain package documentation,
256 // so pick the first file that has a doc comment.
257 for _, file := range imp.GetSyntax() {
259 info = &HoverInformation{source: obj, comment: file.Doc}
264 info = &HoverInformation{source: node}
266 switch obj := obj.(type) {
267 case *types.TypeName, *types.Var, *types.Const, *types.Func:
269 info, err = formatGenDecl(node, obj, obj.Type())
273 _, info.isType = obj.(*types.TypeName)
276 if obj.Parent() == types.Universe {
277 if obj.Name() == "error" {
278 info = &HoverInformation{source: node}
280 info = &HoverInformation{source: node.Name} // comments not needed for builtins
286 info = &HoverInformation{source: obj, comment: node.Doc}
288 info = &HoverInformation{source: node.Type, comment: node.Doc}
293 info = &HoverInformation{source: obj}
296 if info.comment != nil {
297 info.FullDocumentation = info.comment.Text()
298 info.Synopsis = doc.Synopsis(info.FullDocumentation)
304 func formatGenDecl(node *ast.GenDecl, obj types.Object, typ types.Type) (*HoverInformation, error) {
305 if _, ok := typ.(*types.Named); ok {
306 switch typ.Underlying().(type) {
307 case *types.Interface, *types.Struct:
308 return formatGenDecl(node, obj, typ.Underlying())
312 for _, s := range node.Specs {
313 if s.Pos() <= obj.Pos() && obj.Pos() <= s.End() {
319 return nil, errors.Errorf("no spec for node %v at position %v", node, obj.Pos())
322 // If we have a field or method.
324 case *types.Var, *types.Const, *types.Func:
325 return formatVar(spec, obj, node), nil
328 switch spec := spec.(type) {
330 if len(node.Specs) > 1 {
331 // If multiple types are declared in the same block.
332 return &HoverInformation{source: spec.Type, comment: spec.Doc}, nil
334 return &HoverInformation{source: spec, comment: node.Doc}, nil
337 return &HoverInformation{source: spec, comment: spec.Doc}, nil
338 case *ast.ImportSpec:
339 return &HoverInformation{source: spec, comment: spec.Doc}, nil
341 return nil, errors.Errorf("unable to format spec %v (%T)", spec, spec)
344 func formatVar(node ast.Spec, obj types.Object, decl *ast.GenDecl) *HoverInformation {
345 var fieldList *ast.FieldList
346 switch spec := node.(type) {
348 switch t := spec.Type.(type) {
349 case *ast.StructType:
351 case *ast.InterfaceType:
352 fieldList = t.Methods
360 comment = spec.Comment
362 return &HoverInformation{source: obj, comment: comment}
364 // If we have a struct or interface declaration,
365 // we need to match the object to the corresponding field or method.
366 if fieldList != nil {
367 for i := 0; i < len(fieldList.List); i++ {
368 field := fieldList.List[i]
369 if field.Pos() <= obj.Pos() && obj.Pos() <= field.End() {
370 if field.Doc.Text() != "" {
371 return &HoverInformation{source: obj, comment: field.Doc}
373 return &HoverInformation{source: obj, comment: field.Comment}
377 return &HoverInformation{source: obj, comment: decl.Doc}
380 func FormatHover(h *HoverInformation, options *Options) (string, error) {
381 signature := h.Signature
382 if signature != "" && options.PreferredContentFormat == protocol.Markdown {
383 signature = fmt.Sprintf("```go\n%s\n```", signature)
386 switch options.HoverKind {
388 return h.SingleLine, nil
389 case NoDocumentation:
390 return signature, nil
392 b, err := json.Marshal(h)
396 return string(b), nil
398 link := formatLink(h, options)
399 switch options.HoverKind {
400 case SynopsisDocumentation:
401 doc := formatDoc(h.Synopsis, options)
402 return formatHover(options, signature, link, doc), nil
403 case FullDocumentation:
404 doc := formatDoc(h.FullDocumentation, options)
405 return formatHover(options, signature, link, doc), nil
407 return "", errors.Errorf("no hover for %v", h.source)
410 func formatLink(h *HoverInformation, options *Options) string {
411 if !options.LinksInHover || options.LinkTarget == "" || h.LinkPath == "" {
414 plainLink := BuildLink(options.LinkTarget, h.LinkPath, h.LinkAnchor)
415 switch options.PreferredContentFormat {
416 case protocol.Markdown:
417 return fmt.Sprintf("[`%s` on %s](%s)", h.symbolName, options.LinkTarget, plainLink)
418 case protocol.PlainText:
425 // BuildLink constructs a link with the given target, path, and anchor.
426 func BuildLink(target, path, anchor string) string {
427 link := fmt.Sprintf("https://%s/%s", target, path)
428 if target == "pkg.go.dev" {
429 link += "?utm_source=gopls"
434 return link + "#" + anchor
437 func formatDoc(doc string, options *Options) string {
438 if options.PreferredContentFormat == protocol.Markdown {
439 return CommentToMarkdown(doc)
444 func formatHover(options *Options, x ...string) string {
445 var b strings.Builder
446 for i, el := range x {
450 // Don't write out final newline.
454 // If any elements of the remainder of the list are non-empty,
456 if anyNonEmpty(x[i+1:]) {
457 if options.PreferredContentFormat == protocol.Markdown {
458 b.WriteString("\n\n")
468 func anyNonEmpty(x []string) bool {
469 for _, el := range x {