-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
Copy pathhover.go
1759 lines (1596 loc) · 50.7 KB
/
hover.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2019 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package golang
import (
"bytes"
"context"
"fmt"
"go/ast"
"go/constant"
"go/doc"
"go/format"
"go/printer"
"go/token"
"go/types"
"go/version"
"io/fs"
"path/filepath"
"slices"
"sort"
"strconv"
"strings"
"text/tabwriter"
"time"
"unicode/utf8"
"golang.org/x/text/unicode/runenames"
"golang.org/x/tools/go/ast/astutil"
"golang.org/x/tools/go/types/typeutil"
"golang.org/x/tools/gopls/internal/cache"
"golang.org/x/tools/gopls/internal/cache/metadata"
"golang.org/x/tools/gopls/internal/cache/parsego"
"golang.org/x/tools/gopls/internal/file"
"golang.org/x/tools/gopls/internal/protocol"
"golang.org/x/tools/gopls/internal/settings"
gastutil "golang.org/x/tools/gopls/internal/util/astutil"
"golang.org/x/tools/gopls/internal/util/bug"
"golang.org/x/tools/gopls/internal/util/safetoken"
"golang.org/x/tools/internal/event"
"golang.org/x/tools/internal/stdlib"
"golang.org/x/tools/internal/tokeninternal"
"golang.org/x/tools/internal/typeparams"
"golang.org/x/tools/internal/typesinternal"
)
// hoverResult contains the (internal) result of a hover query.
// It is formatted in one of several formats as determined by the
// HoverKind setting.
type hoverResult struct {
// synopsis is a single sentence synopsis of the symbol's documentation.
//
// TODO(adonovan): in what syntax? It (usually) comes from doc.synopsis,
// which produces "Text" form, but it may be fed to
// DocCommentToMarkdown, which expects doc comment syntax.
synopsis string
// fullDocumentation is the symbol's full documentation.
fullDocumentation string
// signature is the symbol's signature.
signature string
// singleLine is a single line describing the symbol.
// This is recommended only for use in clients that show a single line for hover.
singleLine string
// symbolName is the human-readable name to use for the symbol in links.
symbolName string
// linkPath is the path of the package enclosing the given symbol,
// with the module portion (if any) replaced by "module@version".
//
// For example: "github.com/google/go-github/[email protected]/github".
//
// Use LinkTarget + "/" + linkPath + "#" + LinkAnchor to form a pkgsite URL.
linkPath string
// linkAnchor is the pkg.go.dev link anchor for the given symbol.
// For example, the "Node" part of "pkg.go.dev/go/ast#Node".
linkAnchor string
// typeDecl is the declaration syntax for a type,
// or "" for a non-type.
typeDecl string
// methods is the list of descriptions of methods of a type,
// omitting any that are obvious from typeDecl.
// It is "" for a non-type.
methods string
// promotedFields is the list of descriptions of accessible
// fields of a (struct) type that were promoted through an
// embedded field.
promotedFields string
// footer is additional content to insert at the bottom of the hover
// documentation, before the pkgdoc link.
footer string
}
// Hover implements the "textDocument/hover" RPC for Go files.
// It may return nil even on success.
//
// If pkgURL is non-nil, it should be used to generate doc links.
func Hover(ctx context.Context, snapshot *cache.Snapshot, fh file.Handle, position protocol.Position, pkgURL func(path PackagePath, fragment string) protocol.URI) (*protocol.Hover, error) {
ctx, done := event.Start(ctx, "golang.Hover")
defer done()
rng, h, err := hover(ctx, snapshot, fh, position)
if err != nil {
return nil, err
}
if h == nil {
return nil, nil
}
hover, err := formatHover(h, snapshot.Options(), pkgURL)
if err != nil {
return nil, err
}
return &protocol.Hover{
Contents: protocol.MarkupContent{
Kind: snapshot.Options().PreferredContentFormat,
Value: hover,
},
Range: rng,
}, nil
}
// hover computes hover information at the given position. If we do not support
// hovering at the position, it returns _, nil, nil: an error is only returned
// if the position is valid but we fail to compute hover information.
//
// TODO(adonovan): strength-reduce file.Handle to protocol.DocumentURI.
func hover(ctx context.Context, snapshot *cache.Snapshot, fh file.Handle, pp protocol.Position) (protocol.Range, *hoverResult, error) {
// Check for hover inside the builtin file before attempting type checking
// below. NarrowestPackageForFile may or may not succeed, depending on
// whether this is a GOROOT view, but even if it does succeed the resulting
// package will be command-line-arguments package. The user should get a
// hover for the builtin object, not the object type checked from the
// builtin.go.
if snapshot.IsBuiltin(fh.URI()) {
pgf, err := snapshot.BuiltinFile(ctx)
if err != nil {
return protocol.Range{}, nil, err
}
pos, err := pgf.PositionPos(pp)
if err != nil {
return protocol.Range{}, nil, err
}
path, _ := astutil.PathEnclosingInterval(pgf.File, pos, pos)
if id, ok := path[0].(*ast.Ident); ok {
rng, err := pgf.NodeRange(id)
if err != nil {
return protocol.Range{}, nil, err
}
var obj types.Object
if id.Name == "Error" {
obj = types.Universe.Lookup("error").Type().Underlying().(*types.Interface).Method(0)
} else {
obj = types.Universe.Lookup(id.Name)
}
if obj != nil {
h, err := hoverBuiltin(ctx, snapshot, obj)
return rng, h, err
}
}
return protocol.Range{}, nil, nil // no object to hover
}
pkg, pgf, err := NarrowestPackageForFile(ctx, snapshot, fh.URI())
if err != nil {
return protocol.Range{}, nil, err
}
pos, err := pgf.PositionPos(pp)
if err != nil {
return protocol.Range{}, nil, err
}
// Handle hovering over the package name, which does not have an associated
// object.
// As with import paths, we allow hovering just after the package name.
if pgf.File.Name != nil && gastutil.NodeContains(pgf.File.Name, pos) {
return hoverPackageName(pkg, pgf)
}
// Handle hovering over embed directive argument.
pattern, embedRng := parseEmbedDirective(pgf.Mapper, pp)
if pattern != "" {
return hoverEmbed(fh, embedRng, pattern)
}
// hoverRange is the range reported to the client (e.g. for highlighting).
// It may be an expansion around the selected identifier,
// for instance when hovering over a linkname directive or doc link.
var hoverRange *protocol.Range
// Handle linkname directive by overriding what to look for.
if pkgPath, name, offset := parseLinkname(pgf.Mapper, pp); pkgPath != "" && name != "" {
// rng covering 2nd linkname argument: pkgPath.name.
rng, err := pgf.PosRange(pgf.Tok.Pos(offset), pgf.Tok.Pos(offset+len(pkgPath)+len(".")+len(name)))
if err != nil {
return protocol.Range{}, nil, fmt.Errorf("range over linkname arg: %w", err)
}
hoverRange = &rng
pkg, pgf, pos, err = findLinkname(ctx, snapshot, PackagePath(pkgPath), name)
if err != nil {
return protocol.Range{}, nil, fmt.Errorf("find linkname: %w", err)
}
}
// Handle hovering over a doc link
if obj, rng, _ := parseDocLink(pkg, pgf, pos); obj != nil {
// Built-ins have no position.
if isBuiltin(obj) {
h, err := hoverBuiltin(ctx, snapshot, obj)
return rng, h, err
}
// Find position in declaring file.
hoverRange = &rng
objURI := safetoken.StartPosition(pkg.FileSet(), obj.Pos())
pkg, pgf, err = NarrowestPackageForFile(ctx, snapshot, protocol.URIFromPath(objURI.Filename))
if err != nil {
return protocol.Range{}, nil, err
}
pos = pgf.Tok.Pos(objURI.Offset)
}
// Handle hovering over import paths, which do not have an associated
// identifier.
for _, spec := range pgf.File.Imports {
if gastutil.NodeContains(spec, pos) {
rng, hoverRes, err := hoverImport(ctx, snapshot, pkg, pgf, spec)
if err != nil {
return protocol.Range{}, nil, err
}
if hoverRange == nil {
hoverRange = &rng
}
return *hoverRange, hoverRes, nil // (hoverRes may be nil)
}
}
// Handle hovering over various special kinds of syntax node.
if path, _ := astutil.PathEnclosingInterval(pgf.File, pos, pos); len(path) > 0 {
switch node := path[0].(type) {
// Handle hovering over (non-import-path) literals.
case *ast.BasicLit:
return hoverLit(pgf, node, pos)
case *ast.ReturnStmt:
return hoverReturnStatement(pgf, path, node)
}
}
// Handle hover over identifier.
// The general case: compute hover information for the object referenced by
// the identifier at pos.
ident, obj, selectedType := referencedObject(pkg, pgf, pos)
if obj == nil || ident == nil {
return protocol.Range{}, nil, nil // no object to hover
}
// Unless otherwise specified, rng covers the ident being hovered.
if hoverRange == nil {
rng, err := pgf.NodeRange(ident)
if err != nil {
return protocol.Range{}, nil, err
}
hoverRange = &rng
}
// By convention, we qualify hover information relative to the package
// from which the request originated.
qual := typesinternal.FileQualifier(pgf.File, pkg.Types())
// Handle type switch identifiers as a special case, since they don't have an
// object.
//
// There's not much useful information to provide.
if selectedType != nil {
v := types.NewVar(obj.Pos(), obj.Pkg(), obj.Name(), selectedType)
typesinternal.SetVarKind(v, typesinternal.LocalVar)
signature := types.ObjectString(v, qual)
return *hoverRange, &hoverResult{
signature: signature,
singleLine: signature,
symbolName: v.Name(),
}, nil
}
if isBuiltin(obj) {
// Built-ins have no position.
h, err := hoverBuiltin(ctx, snapshot, obj)
return *hoverRange, h, err
}
// For all other objects, consider the full syntax of their declaration in
// order to correctly compute their documentation, signature, and link.
//
// Beware: decl{PGF,Pos} are not necessarily associated with pkg.FileSet().
declPGF, declPos, err := parseFull(ctx, snapshot, pkg.FileSet(), obj.Pos())
if err != nil {
return protocol.Range{}, nil, fmt.Errorf("re-parsing declaration of %s: %v", obj.Name(), err)
}
decl, spec, field := findDeclInfo([]*ast.File{declPGF.File}, declPos) // may be nil^3
comment := chooseDocComment(pkg.FileSet(), decl, spec, field)
docText := comment.Text()
// By default, types.ObjectString provides a reasonable signature.
signature := objectString(obj, qual, declPos, declPGF.Tok, spec)
singleLineSignature := signature
// Display struct tag for struct fields at the end of the signature.
if field != nil && field.Tag != nil {
signature += " " + field.Tag.Value
}
// TODO(rfindley): we could do much better for inferred signatures.
// TODO(adonovan): fuse the two calls below.
if inferred := inferredSignature(pkg.TypesInfo(), ident); inferred != nil {
if s := inferredSignatureString(obj, qual, inferred); s != "" {
signature = s
}
}
// Compute size information for types,
// and (size, offset) for struct fields.
//
// Also, if a struct type's field ordering is significantly
// wasteful of space, report its optimal size.
//
// This information is useful when debugging crashes or
// optimizing layout. To reduce distraction, we show it only
// when hovering over the declaring identifier,
// but not referring identifiers.
//
// Size and alignment vary across OS/ARCH.
// Gopls will select the appropriate build configuration when
// viewing a type declaration in a build-tagged file, but will
// use the default build config for all other types, even
// if they embed platform-variant types.
//
var sizeOffset string // optional size/offset description
// debugging #69362: unexpected nil Defs[ident] value (?)
_ = ident.Pos() // (can't be nil due to check after referencedObject)
_ = pkg.TypesInfo() // (can't be nil due to check in call to inferredSignature)
_ = pkg.TypesInfo().Defs // (can't be nil due to nature of cache.Package)
if def, ok := pkg.TypesInfo().Defs[ident]; ok {
_ = def.Pos() // can't be nil due to reasoning in #69362.
}
if def, ok := pkg.TypesInfo().Defs[ident]; ok && ident.Pos() == def.Pos() {
// This is the declaring identifier.
// (We can't simply use ident.Pos() == obj.Pos() because
// referencedObject prefers the TypeName for an embedded field).
// format returns the decimal and hex representation of x.
format := func(x int64) string {
if x < 10 {
return fmt.Sprintf("%d", x)
}
return fmt.Sprintf("%[1]d (%#[1]x)", x)
}
path := pathEnclosingObjNode(pgf.File, pos)
// Build string of form "size=... (X% wasted), offset=...".
size, wasted, offset := computeSizeOffsetInfo(pkg, path, obj)
var buf strings.Builder
if size >= 0 {
fmt.Fprintf(&buf, "size=%s", format(size))
if wasted >= 20 { // >=20% wasted
fmt.Fprintf(&buf, " (%d%% wasted)", wasted)
}
}
if offset >= 0 {
if buf.Len() > 0 {
buf.WriteString(", ")
}
fmt.Fprintf(&buf, "offset=%s", format(offset))
}
sizeOffset = buf.String()
}
var typeDecl, methods, fields string
// For "objects defined by a type spec", the signature produced by
// objectString is insufficient:
// (1) large structs are formatted poorly, with no newlines
// (2) we lose inline comments
// Furthermore, we include a summary of their method set.
_, isTypeName := obj.(*types.TypeName)
_, isTypeParam := types.Unalias(obj.Type()).(*types.TypeParam)
if isTypeName && !isTypeParam {
spec, ok := spec.(*ast.TypeSpec)
if !ok {
// We cannot find a TypeSpec for this type or alias declaration
// (that is not a type parameter or a built-in).
// This should be impossible even for ill-formed trees;
// we suspect that AST repair may be creating inconsistent
// positions. Don't report a bug in that case. (#64241)
errorf := fmt.Errorf
if !declPGF.Fixed() {
errorf = bug.Errorf
}
return protocol.Range{}, nil, errorf("type name %q without type spec", obj.Name())
}
// Format the type's declaration syntax.
{
// Don't duplicate comments.
spec2 := *spec
spec2.Doc = nil
spec2.Comment = nil
var b strings.Builder
b.WriteString("type ")
fset := tokeninternal.FileSetFor(declPGF.Tok)
// TODO(adonovan): use a smarter formatter that omits
// inaccessible fields (non-exported ones from other packages).
if err := format.Node(&b, fset, &spec2); err != nil {
return protocol.Range{}, nil, err
}
typeDecl = b.String()
// Splice in size/offset at end of first line.
// "type T struct { // size=..."
if sizeOffset != "" {
nl := strings.IndexByte(typeDecl, '\n')
if nl < 0 {
nl = len(typeDecl)
}
typeDecl = typeDecl[:nl] + " // " + sizeOffset + typeDecl[nl:]
}
}
// Promoted fields
//
// Show a table of accessible fields of the (struct)
// type that may not be visible in the syntax (above)
// due to promotion through embedded fields.
//
// Example:
//
// // Embedded fields:
// foo int // through x.y
// z string // through x.y
if prom := promotedFields(obj.Type(), pkg.Types()); len(prom) > 0 {
var b strings.Builder
b.WriteString("// Embedded fields:\n")
w := tabwriter.NewWriter(&b, 0, 8, 1, ' ', 0)
for _, f := range prom {
fmt.Fprintf(w, "%s\t%s\t// through %s\t\n",
f.field.Name(),
types.TypeString(f.field.Type(), qual),
f.path)
}
w.Flush()
b.WriteByte('\n')
fields = b.String()
}
// -- methods --
// For an interface type, explicit methods will have
// already been displayed when the node was formatted
// above. Don't list these again.
var skip map[string]bool
if iface, ok := spec.Type.(*ast.InterfaceType); ok {
if iface.Methods.List != nil {
for _, m := range iface.Methods.List {
if len(m.Names) == 1 {
if skip == nil {
skip = make(map[string]bool)
}
skip[m.Names[0].Name] = true
}
}
}
}
// Display all the type's accessible methods,
// including those that require a pointer receiver,
// and those promoted from embedded struct fields or
// embedded interfaces.
var b strings.Builder
for _, m := range typeutil.IntuitiveMethodSet(obj.Type(), nil) {
if !accessibleTo(m.Obj(), pkg.Types()) {
continue // inaccessible
}
if skip[m.Obj().Name()] {
continue // redundant with format.Node above
}
if b.Len() > 0 {
b.WriteByte('\n')
}
// Use objectString for its prettier rendering of method receivers.
b.WriteString(objectString(m.Obj(), qual, token.NoPos, nil, nil))
}
methods = b.String()
signature = typeDecl + "\n" + methods
} else {
// Non-types
if sizeOffset != "" {
signature += " // " + sizeOffset
}
}
// Compute link data (on pkg.go.dev or other documentation host).
//
// If linkPath is empty, the symbol is not linkable.
var (
linkName string // => link title, always non-empty
linkPath string // => link path
anchor string // link anchor
linkMeta *metadata.Package // metadata for the linked package
)
{
linkMeta = findFileInDeps(snapshot, pkg.Metadata(), declPGF.URI)
if linkMeta == nil {
return protocol.Range{}, nil, bug.Errorf("no package data for %s", declPGF.URI)
}
// For package names, we simply link to their imported package.
if pkgName, ok := obj.(*types.PkgName); ok {
linkName = pkgName.Name()
linkPath = pkgName.Imported().Path()
impID := linkMeta.DepsByPkgPath[PackagePath(pkgName.Imported().Path())]
linkMeta = snapshot.Metadata(impID)
if linkMeta == nil {
// Broken imports have fake package paths, so it is not a bug if we
// don't have metadata. As of writing, there is no way to distinguish
// broken imports from a true bug where expected metadata is missing.
return protocol.Range{}, nil, fmt.Errorf("no package data for %s", declPGF.URI)
}
} else {
// For all others, check whether the object is in the package scope, or
// an exported field or method of an object in the package scope.
//
// We try to match pkgsite's heuristics for what is linkable, and what is
// not.
var recv types.Object
switch obj := obj.(type) {
case *types.Func:
sig := obj.Signature()
if sig.Recv() != nil {
tname := typeToObject(sig.Recv().Type())
if tname != nil { // beware typed nil
recv = tname
}
}
case *types.Var:
if obj.IsField() {
if spec, ok := spec.(*ast.TypeSpec); ok {
typeName := spec.Name
scopeObj, _ := obj.Pkg().Scope().Lookup(typeName.Name).(*types.TypeName)
if scopeObj != nil {
if st, _ := scopeObj.Type().Underlying().(*types.Struct); st != nil {
for i := 0; i < st.NumFields(); i++ {
if obj == st.Field(i) {
recv = scopeObj
}
}
}
}
}
}
}
// Even if the object is not available in package documentation, it may
// be embedded in a documented receiver. Detect this by searching
// enclosing selector expressions.
//
// TODO(rfindley): pkgsite doesn't document fields from embedding, just
// methods.
if recv == nil || !recv.Exported() {
path := pathEnclosingObjNode(pgf.File, pos)
if enclosing := searchForEnclosing(pkg.TypesInfo(), path); enclosing != nil {
recv = enclosing
} else {
recv = nil // note: just recv = ... could result in a typed nil.
}
}
pkg := obj.Pkg()
if recv != nil {
linkName = fmt.Sprintf("(%s.%s).%s", pkg.Name(), recv.Name(), obj.Name())
if obj.Exported() && recv.Exported() && typesinternal.IsPackageLevel(recv) {
linkPath = pkg.Path()
anchor = fmt.Sprintf("%s.%s", recv.Name(), obj.Name())
}
} else {
linkName = fmt.Sprintf("%s.%s", pkg.Name(), obj.Name())
if obj.Exported() && typesinternal.IsPackageLevel(obj) {
linkPath = pkg.Path()
anchor = obj.Name()
}
}
}
}
if snapshot.IsGoPrivatePath(linkPath) || linkMeta.ForTest != "" {
linkPath = ""
} else if linkMeta.Module != nil && linkMeta.Module.Version != "" {
mod := linkMeta.Module
linkPath = strings.Replace(linkPath, mod.Path, mod.Path+"@"+mod.Version, 1)
}
var footer string
if sym := StdSymbolOf(obj); sym != nil && sym.Version > 0 {
footer = fmt.Sprintf("Added in %v", sym.Version)
}
return *hoverRange, &hoverResult{
synopsis: doc.Synopsis(docText),
fullDocumentation: docText,
singleLine: singleLineSignature,
symbolName: linkName,
signature: signature,
linkPath: linkPath,
linkAnchor: anchor,
typeDecl: typeDecl,
methods: methods,
promotedFields: fields,
footer: footer,
}, nil
}
// hoverBuiltin computes hover information when hovering over a builtin
// identifier.
func hoverBuiltin(ctx context.Context, snapshot *cache.Snapshot, obj types.Object) (*hoverResult, error) {
// Special handling for error.Error, which is the only builtin method.
//
// TODO(rfindley): can this be unified with the handling below?
if obj.Name() == "Error" {
signature := obj.String()
return &hoverResult{
signature: signature,
singleLine: signature,
// TODO(rfindley): these are better than the current behavior.
// SymbolName: "(error).Error",
// LinkPath: "builtin",
// LinkAnchor: "error.Error",
}, nil
}
pgf, ident, err := builtinDecl(ctx, snapshot, obj)
if err != nil {
return nil, err
}
var (
comment *ast.CommentGroup
decl ast.Decl
)
path, _ := astutil.PathEnclosingInterval(pgf.File, ident.Pos(), ident.Pos())
for _, n := range path {
switch n := n.(type) {
case *ast.GenDecl:
// Separate documentation and signature.
comment = n.Doc
node2 := *n
node2.Doc = nil
decl = &node2
case *ast.FuncDecl:
// Ditto.
comment = n.Doc
node2 := *n
node2.Doc = nil
decl = &node2
}
}
signature := formatNodeFile(pgf.Tok, decl)
// Replace fake types with their common equivalent.
// TODO(rfindley): we should instead use obj.Type(), which would have the
// *actual* types of the builtin call.
signature = replacer.Replace(signature)
docText := comment.Text()
return &hoverResult{
synopsis: doc.Synopsis(docText),
fullDocumentation: docText,
signature: signature,
singleLine: obj.String(),
symbolName: obj.Name(),
linkPath: "builtin",
linkAnchor: obj.Name(),
}, nil
}
// hoverImport computes hover information when hovering over the import path of
// imp in the file pgf of pkg.
//
// If we do not have metadata for the hovered import, it returns _
func hoverImport(ctx context.Context, snapshot *cache.Snapshot, pkg *cache.Package, pgf *parsego.File, imp *ast.ImportSpec) (protocol.Range, *hoverResult, error) {
rng, err := pgf.NodeRange(imp.Path)
if err != nil {
return protocol.Range{}, nil, err
}
importPath := metadata.UnquoteImportPath(imp)
if importPath == "" {
return protocol.Range{}, nil, fmt.Errorf("invalid import path")
}
impID := pkg.Metadata().DepsByImpPath[importPath]
if impID == "" {
return protocol.Range{}, nil, fmt.Errorf("no package data for import %q", importPath)
}
impMetadata := snapshot.Metadata(impID)
if impMetadata == nil {
return protocol.Range{}, nil, bug.Errorf("failed to resolve import ID %q", impID)
}
// Find the first file with a package doc comment.
var comment *ast.CommentGroup
for _, f := range impMetadata.CompiledGoFiles {
fh, err := snapshot.ReadFile(ctx, f)
if err != nil {
if ctx.Err() != nil {
return protocol.Range{}, nil, ctx.Err()
}
continue
}
pgf, err := snapshot.ParseGo(ctx, fh, parsego.Header)
if err != nil {
if ctx.Err() != nil {
return protocol.Range{}, nil, ctx.Err()
}
continue
}
if pgf.File.Doc != nil {
comment = pgf.File.Doc
break
}
}
docText := comment.Text()
return rng, &hoverResult{
signature: "package " + string(impMetadata.Name),
synopsis: doc.Synopsis(docText),
fullDocumentation: docText,
}, nil
}
// hoverPackageName computes hover information for the package name of the file
// pgf in pkg.
func hoverPackageName(pkg *cache.Package, pgf *parsego.File) (protocol.Range, *hoverResult, error) {
var comment *ast.CommentGroup
for _, pgf := range pkg.CompiledGoFiles() {
if pgf.File.Doc != nil {
comment = pgf.File.Doc
break
}
}
rng, err := pgf.NodeRange(pgf.File.Name)
if err != nil {
return protocol.Range{}, nil, err
}
docText := comment.Text()
// List some package attributes at the bottom of the documentation, if
// applicable.
type attr struct{ title, value string }
var attrs []attr
if !metadata.IsCommandLineArguments(pkg.Metadata().ID) {
attrs = append(attrs, attr{"Package path", string(pkg.Metadata().PkgPath)})
}
if pkg.Metadata().Module != nil {
attrs = append(attrs, attr{"Module", pkg.Metadata().Module.Path})
}
// Show the effective language version for this package.
if v := pkg.TypesInfo().FileVersions[pgf.File]; v != "" {
attr := attr{value: version.Lang(v)}
if v == pkg.Types().GoVersion() {
attr.title = "Language version"
} else {
attr.title = "Language version (current file)"
}
attrs = append(attrs, attr)
}
// TODO(rfindley): consider exec'ing go here to compute DefaultGODEBUG, or
// propose adding GODEBUG info to go/packages.
var footer string
for i, attr := range attrs {
if i > 0 {
footer += "\n"
}
footer += fmt.Sprintf(" - %s: %s", attr.title, attr.value)
}
return rng, &hoverResult{
signature: "package " + string(pkg.Metadata().Name),
synopsis: doc.Synopsis(docText),
fullDocumentation: docText,
footer: footer,
}, nil
}
// hoverLit computes hover information when hovering over the basic literal lit
// in the file pgf. The provided pos must be the exact position of the cursor,
// as it is used to extract the hovered rune in strings.
//
// For example, hovering over "\u2211" in "foo \u2211 bar" yields:
//
// '∑', U+2211, N-ARY SUMMATION
func hoverLit(pgf *parsego.File, lit *ast.BasicLit, pos token.Pos) (protocol.Range, *hoverResult, error) {
var (
value string // if non-empty, a constant value to format in hover
r rune // if non-zero, format a description of this rune in hover
start, end token.Pos // hover span
)
// Extract a rune from the current position.
// 'Ω', "...Ω...", or 0x03A9 => 'Ω', U+03A9, GREEK CAPITAL LETTER OMEGA
switch lit.Kind {
case token.CHAR:
s, err := strconv.Unquote(lit.Value)
if err != nil {
// If the conversion fails, it's because of an invalid syntax, therefore
// there is no rune to be found.
return protocol.Range{}, nil, nil
}
r, _ = utf8.DecodeRuneInString(s)
if r == utf8.RuneError {
return protocol.Range{}, nil, fmt.Errorf("rune error")
}
start, end = lit.Pos(), lit.End()
case token.INT:
// Short literals (e.g. 99 decimal, 07 octal) are uninteresting.
if len(lit.Value) < 3 {
return protocol.Range{}, nil, nil
}
v := constant.MakeFromLiteral(lit.Value, lit.Kind, 0)
if v.Kind() != constant.Int {
return protocol.Range{}, nil, nil
}
switch lit.Value[:2] {
case "0x", "0X":
// As a special case, try to recognize hexadecimal literals as runes if
// they are within the range of valid unicode values.
if v, ok := constant.Int64Val(v); ok && v > 0 && v <= utf8.MaxRune && utf8.ValidRune(rune(v)) {
r = rune(v)
}
fallthrough
case "0o", "0O", "0b", "0B":
// Format the decimal value of non-decimal literals.
value = v.ExactString()
start, end = lit.Pos(), lit.End()
default:
return protocol.Range{}, nil, nil
}
case token.STRING:
// It's a string, scan only if it contains a unicode escape sequence under or before the
// current cursor position.
litOffset, err := safetoken.Offset(pgf.Tok, lit.Pos())
if err != nil {
return protocol.Range{}, nil, err
}
offset, err := safetoken.Offset(pgf.Tok, pos)
if err != nil {
return protocol.Range{}, nil, err
}
for i := offset - litOffset; i > 0; i-- {
// Start at the cursor position and search backward for the beginning of a rune escape sequence.
rr, _ := utf8.DecodeRuneInString(lit.Value[i:])
if rr == utf8.RuneError {
return protocol.Range{}, nil, fmt.Errorf("rune error")
}
if rr == '\\' {
// Got the beginning, decode it.
var tail string
r, _, tail, err = strconv.UnquoteChar(lit.Value[i:], '"')
if err != nil {
// If the conversion fails, it's because of an invalid syntax,
// therefore is no rune to be found.
return protocol.Range{}, nil, nil
}
// Only the rune escape sequence part of the string has to be highlighted, recompute the range.
runeLen := len(lit.Value) - (i + len(tail))
start = token.Pos(int(lit.Pos()) + i)
end = token.Pos(int(start) + runeLen)
break
}
}
}
if value == "" && r == 0 { // nothing to format
return protocol.Range{}, nil, nil
}
rng, err := pgf.PosRange(start, end)
if err != nil {
return protocol.Range{}, nil, err
}
var b strings.Builder
if value != "" {
b.WriteString(value)
}
if r != 0 {
runeName := runenames.Name(r)
if len(runeName) > 0 && runeName[0] == '<' {
// Check if the rune looks like an HTML tag. If so, trim the surrounding <>
// characters to work around https://github.com/microsoft/vscode/issues/124042.
runeName = strings.TrimRight(runeName[1:], ">")
}
if b.Len() > 0 {
b.WriteString(", ")
}
if strconv.IsPrint(r) {
fmt.Fprintf(&b, "'%c', ", r)
}
fmt.Fprintf(&b, "U+%04X, %s", r, runeName)
}
hover := b.String()
return rng, &hoverResult{
synopsis: hover,
fullDocumentation: hover,
}, nil
}
func hoverReturnStatement(pgf *parsego.File, path []ast.Node, ret *ast.ReturnStmt) (protocol.Range, *hoverResult, error) {
var funcType *ast.FuncType
// Find innermost enclosing function.
for _, n := range path {
switch n := n.(type) {
case *ast.FuncLit:
funcType = n.Type
case *ast.FuncDecl:
funcType = n.Type
}
if funcType != nil {
break
}
}
// Inv: funcType != nil because a ReturnStmt is always enclosed by a function.
if funcType.Results == nil {
return protocol.Range{}, nil, nil // no result variables
}
rng, err := pgf.PosRange(ret.Pos(), ret.End())
if err != nil {
return protocol.Range{}, nil, err
}
// Format the function's result type.
var buf strings.Builder
var cfg printer.Config
fset := token.NewFileSet()
buf.WriteString("returns (")
for i, field := range funcType.Results.List {
if i > 0 {
buf.WriteString(", ")
}
cfg.Fprint(&buf, fset, field.Type)
}
buf.WriteByte(')')
return rng, &hoverResult{
signature: buf.String(),
}, nil
}
// hoverEmbed computes hover information for a filepath.Match pattern.
// Assumes that the pattern is relative to the location of fh.
func hoverEmbed(fh file.Handle, rng protocol.Range, pattern string) (protocol.Range, *hoverResult, error) {
s := &strings.Builder{}
dir := fh.URI().DirPath()
var matches []string
err := filepath.WalkDir(dir, func(abs string, d fs.DirEntry, e error) error {
if e != nil {
return e
}
rel, err := filepath.Rel(dir, abs)
if err != nil {
return err
}
ok, err := filepath.Match(pattern, rel)
if err != nil {
return err
}
if ok && !d.IsDir() {
matches = append(matches, rel)
}
return nil
})
if err != nil {
return protocol.Range{}, nil, err
}