Debian Codegraph @

gopls/internal/golang/signature_help.go

raw symbols SCIP
1 // Copyright 2018 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package golang
6
7 import (
8 "context"
9 "fmt"
10 "go/ast"
11 "go/token"
12 "go/types"
13 "strings"
14
15 "golang.org/x/tools/go/ast/astutil"
16 "golang.org/x/tools/gopls/internal/cache"
17 "golang.org/x/tools/gopls/internal/file"
18 "golang.org/x/tools/gopls/internal/protocol"
19 "golang.org/x/tools/gopls/internal/settings"
20 "golang.org/x/tools/internal/event"
21 "golang.org/x/tools/internal/typesinternal"
22 )
23
24 // SignatureHelp returns information about the signature of the innermost
25 // function call enclosing the position, or nil if there is none.
26 func SignatureHelp(ctx context.Context, snapshot *cache.Snapshot, fh file.Handle, rng protocol.Range, context *protocol.SignatureHelpContext) (*protocol.SignatureInformation, error) {
27 ctx, done := event.Start(ctx, "golang.SignatureHelp")
28 defer done()
29
30 // We need full type-checking here, as we must type-check function bodies in
31 // order to provide signature help at the requested position.
32 pkg, pgf, err := NarrowestPackageForFile(ctx, snapshot, fh.URI())
33 if err != nil {
34 return nil, fmt.Errorf("getting file for SignatureHelp: %w", err)
35 }
36 start, end, err := pgf.RangePos(rng)
37 if err != nil {
38 return nil, err
39 }
40 // Find a call expression surrounding the query position.
41 var callExpr *ast.CallExpr
42 path, _ := astutil.PathEnclosingInterval(pgf.File, start, end)
43 if path == nil {
44 return nil, fmt.Errorf("cannot find node enclosing position")
45 }
46 info := pkg.TypesInfo()
47 var fnval ast.Expr
48 loop:
49 for i, node := range path {
50 switch node := node.(type) {
51 case *ast.Ident:
52 // If the selected text is a function/method Ident or SelectorExpr,
53 // even one not in function call position,
54 // show help for its signature. Example:
55 // once.Do(initialize⁁)
56 // should show help for initialize, not once.Do.
57 if t := info.TypeOf(node); t != nil &&
58 info.Defs[node] == nil &&
59 is[*types.Signature](t.Underlying()) {
60 if sel, ok := path[i+1].(*ast.SelectorExpr); ok && sel.Sel == node {
61 fnval = sel // e.g. fmt.Println⁁
62 } else {
63 fnval = node
64 }
65 break loop
66 }
67 case *ast.CallExpr:
68 // Beware: the ')' may be missing.
69 if node.Lparen <= start && end <= node.Rparen {
70 callExpr = node
71 fnval = callExpr.Fun
72 break loop
73 }
74 case *ast.FuncLit, *ast.FuncType, *ast.CompositeLit:
75 // The user is within an anonymous function or
76 // a composite literal, which may be the argument
77 // to the *ast.CallExpr.
78 // Don't show signature help in this case.
79 return nil, nil
80 case *ast.BasicLit:
81 // golang/go#43397: don't offer signature help when the user is typing
82 // in a string literal unless it was manually invoked or help is already active.
83 if node.Kind == token.STRING &&
84 (context == nil || (context.TriggerKind != protocol.SigInvoked && !context.IsRetrigger)) {
85 return nil, nil
86 }
87 }
88 }
89
90 if fnval == nil {
91 return nil, nil
92 }
93
94 // Get the type information for the function being called.
95 var sig *types.Signature
96 if tv, ok := info.Types[fnval]; !ok {
97 return nil, fmt.Errorf("cannot get type for Fun %[1]T (%[1]v)", fnval)
98 } else if tv.IsType() {
99 return nil, nil // a conversion, not a call
100 } else if sig, ok = tv.Type.Underlying().(*types.Signature); !ok {
101 return nil, fmt.Errorf("call operand is not a func or type: %[1]T (%[1]v)", fnval)
102 }
103 // Inv: sig != nil
104
105 // Get the object representing the function, if available.
106 // There is no object in certain cases such as calling a function returned by
107 // a function (e.g. "foo()()").
108 var obj types.Object
109 switch t := fnval.(type) {
110 case *ast.Ident:
111 obj = info.ObjectOf(t)
112 case *ast.SelectorExpr:
113 obj = info.ObjectOf(t.Sel)
114 }
115
116 if obj != nil && isBuiltin(obj) {
117 // Special handling for error.Error, which is the only builtin method.
118 if obj.Name() == "Error" {
119 return &protocol.SignatureInformation{
120 Label: "Error() string",
121 // TODO(skewb1k): move the docstring for error.Error to builtin.go and reuse it across all relevant LSP methods.
122 Documentation: stringToSigInfoDocumentation("Error returns the error message.", snapshot.Options()),
123 Parameters: nil,
124 ActiveParameter: nil,
125 }, nil
126 }
127 s, err := NewBuiltinSignature(ctx, snapshot, obj.Name())
128 if err != nil {
129 return nil, err
130 }
131 return signatureInformation(s, snapshot.Options(), start, end, callExpr)
132 }
133
134 mq := MetadataQualifierForFile(snapshot, pgf.File, pkg.Metadata())
135 qual := typesinternal.FileQualifier(pgf.File, pkg.Types())
136 var (
137 comment *ast.CommentGroup
138 name string
139 )
140
141 if obj != nil {
142 comment, err = HoverDocForObject(ctx, snapshot, pkg.FileSet(), obj)
143 if err != nil {
144 return nil, err
145 }
146 name = obj.Name()
147 } else {
148 name = "func"
149 }
150
151 s, err := NewSignature(ctx, snapshot, pkg, sig, comment, qual, mq)
152 if err != nil {
153 return nil, err
154 }
155 s.name = name
156 return signatureInformation(s, snapshot.Options(), start, end, callExpr)
157 }
158
159 func signatureInformation(sig *signature, options *settings.Options, start, end token.Pos, call *ast.CallExpr) (*protocol.SignatureInformation, error) {
160 paramInfo := make([]protocol.ParameterInformation, 0, len(sig.params))
161 for _, p := range sig.params {
162 paramInfo = append(paramInfo, protocol.ParameterInformation{Label: p})
163 }
164 return &protocol.SignatureInformation{
165 Label: sig.name + sig.Format(),
166 Documentation: stringToSigInfoDocumentation(sig.doc, options),
167 Parameters: paramInfo,
168 ActiveParameter: activeParameter(sig, start, end, call),
169 }, nil
170 }
171
172 // activeParameter returns a pointer to a variable containing
173 // the index of the active parameter (if known), or nil otherwise.
174 func activeParameter(sig *signature, start, end token.Pos, call *ast.CallExpr) *uint32 {
175 if call == nil {
176 return nil
177 }
178 numParams := uint32(len(sig.params))
179 if numParams == 0 {
180 return nil
181 }
182 // Check if the position is even in the range of the arguments.
183 if !(call.Lparen < start && end <= call.Rparen) {
184 return nil
185 }
186
187 var activeParam uint32
188 for _, arg := range call.Args {
189 if end <= arg.End() {
190 break
191 }
192 // Don't advance the active parameter for the last parameter of a variadic function.
193 if !sig.variadic || activeParam < numParams-1 {
194 activeParam++
195 }
196 }
197 return &activeParam
198 }
199
200 func stringToSigInfoDocumentation(s string, options *settings.Options) *protocol.Or_SignatureInformation_documentation {
201 v := s
202 k := protocol.PlainText
203 if options.PreferredContentFormat == protocol.Markdown {
204 v = DocCommentToMarkdown(s, options)
205 // whether or not content is newline terminated may not matter for LSP clients,
206 // but our tests expect trailing newlines to be stripped.
207 v = strings.TrimSuffix(v, "\n") // TODO(pjw): change the golden files
208 k = protocol.Markdown
209 }
210 return &protocol.Or_SignatureInformation_documentation{
211 Value: protocol.MarkupContent{
212 Kind: k,
213 Value: v,
214 },
215 }
216 }