Debian Codegraph @

gopls/internal/golang/completion/deep_completion.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 completion
6
7 import (
8 "context"
9 "go/types"
10 "strings"
11 "time"
12
13 "golang.org/x/tools/gopls/internal/util/typesutil"
14 "golang.org/x/tools/internal/packagepath"
15 )
16
17 // MaxDeepCompletions limits deep completion results because in most cases
18 // there are too many to be useful.
19 const MaxDeepCompletions = 3
20
21 // deepCompletionState stores our state as we search for deep completions.
22 // "deep completion" refers to searching into objects' fields and methods to
23 // find more completion candidates.
24 type deepCompletionState struct {
25 // enabled indicates whether deep completion is permitted.
26 enabled bool
27
28 // queueClosed is used to disable adding new sub-fields to search queue
29 // once we're running out of our time budget.
30 queueClosed bool
31
32 // thisQueue holds the current breadth first search queue.
33 thisQueue []candidate
34
35 // nextQueue holds the next breadth first search iteration's queue.
36 nextQueue []candidate
37
38 // highScores tracks the highest deep candidate scores we have found
39 // so far. This is used to avoid work for low scoring deep candidates.
40 highScores [MaxDeepCompletions]float64
41
42 // candidateCount is the count of unique deep candidates encountered
43 // so far.
44 candidateCount int
45 }
46
47 // enqueue adds a candidate to the search queue.
48 func (s *deepCompletionState) enqueue(cand candidate) {
49 s.nextQueue = append(s.nextQueue, cand)
50 }
51
52 // scorePenalty computes a deep candidate score penalty. A candidate is
53 // penalized based on depth to favor shallower candidates. We also give a
54 // slight bonus to unexported objects and a slight additional penalty to
55 // function objects.
56 func (s *deepCompletionState) scorePenalty(cand *candidate) float64 {
57 var deepPenalty float64
58 for _, dc := range cand.path {
59 deepPenalty++
60
61 if !dc.Exported() {
62 deepPenalty -= 0.1
63 }
64
65 if _, isSig := dc.Type().Underlying().(*types.Signature); isSig {
66 deepPenalty += 0.1
67 }
68 }
69
70 // Normalize penalty to a max depth of 10.
71 return deepPenalty / 10
72 }
73
74 // isHighScore returns whether score is among the top MaxDeepCompletions deep
75 // candidate scores encountered so far. If so, it adds score to highScores,
76 // possibly displacing an existing high score.
77 func (s *deepCompletionState) isHighScore(score float64) bool {
78 // Invariant: s.highScores is sorted with highest score first. Unclaimed
79 // positions are trailing zeros.
80
81 // If we beat an existing score then take its spot.
82 for i, deepScore := range s.highScores {
83 if score <= deepScore {
84 continue
85 }
86
87 if deepScore != 0 && i != len(s.highScores)-1 {
88 // If this wasn't an empty slot then we need to scooch everyone
89 // down one spot.
90 copy(s.highScores[i+1:], s.highScores[i:])
91 }
92 s.highScores[i] = score
93 return true
94 }
95
96 return false
97 }
98
99 // newPath returns path from search root for an object following a given
100 // candidate.
101 func (s *deepCompletionState) newPath(cand candidate, obj types.Object) []types.Object {
102 path := make([]types.Object, len(cand.path)+1)
103 copy(path, cand.path)
104 path[len(path)-1] = obj
105
106 return path
107 }
108
109 // deepSearch searches a candidate and its subordinate objects for completion
110 // items if deep completion is enabled and adds the valid candidates to
111 // completion items.
112 func (c *completer) deepSearch(ctx context.Context, minDepth int, deadline *time.Time) {
113 defer func() {
114 // We can return early before completing the search, so be sure to
115 // clear out our queues to not impact any further invocations.
116 c.deepState.thisQueue = c.deepState.thisQueue[:0]
117 c.deepState.nextQueue = c.deepState.nextQueue[:0]
118 }()
119
120 depth := 0 // current depth being processed
121 // Stop reports whether we should stop the search immediately.
122 stop := func() bool {
123 // Context cancellation indicates that the actual completion operation was
124 // cancelled, so ignore minDepth and deadline.
125 select {
126 case <-ctx.Done():
127 return true
128 default:
129 }
130 // Otherwise, only stop if we've searched at least minDepth and reached the deadline.
131 return depth > minDepth && deadline != nil && time.Now().After(*deadline)
132 }
133
134 for len(c.deepState.nextQueue) > 0 {
135 depth++
136 if stop() {
137 return
138 }
139 c.deepState.thisQueue, c.deepState.nextQueue = c.deepState.nextQueue, c.deepState.thisQueue[:0]
140
141 outer:
142 for _, cand := range c.deepState.thisQueue {
143 obj := cand.obj
144
145 if obj == nil {
146 continue
147 }
148
149 // At the top level, dedupe by object.
150 if len(cand.path) == 0 {
151 if c.seen[obj] {
152 continue
153 }
154 c.seen[obj] = true
155 }
156
157 // If obj is not accessible because it lives in another package and is
158 // not exported, don't treat it as a completion candidate unless it's
159 // a package completion candidate.
160 if !c.completionContext.packageCompletion &&
161 obj.Pkg() != nil && obj.Pkg() != c.pkg.Types() && !obj.Exported() {
162 continue
163 }
164
165 if cand.imp != nil && !packagepath.CanImport(string(c.pkg.Metadata().PkgPath), cand.imp.importPath) {
166 continue // inaccessible internal package
167 }
168
169 // If we want a type name, don't offer non-type name candidates.
170 // However, do offer package names since they can contain type names,
171 // and do offer any candidate without a type since we aren't sure if it
172 // is a type name or not (i.e. unimported candidate).
173 if c.wantTypeName() && obj.Type() != nil && !isTypeName(obj) && !isPkgName(obj) {
174 continue
175 }
176
177 // When searching deep, make sure we don't have a cycle in our chain.
178 // We don't dedupe by object because we want to allow both "foo.Baz"
179 // and "bar.Baz" even though "Baz" is represented the same types.Object
180 // in both.
181 for _, seenObj := range cand.path {
182 if seenObj == obj {
183 continue outer
184 }
185 }
186
187 c.addCandidate(ctx, &cand)
188
189 c.deepState.candidateCount++
190 if c.opts.budget > 0 && c.deepState.candidateCount%100 == 0 {
191 if stop() {
192 return
193 }
194 spent := float64(time.Since(c.startTime)) / float64(c.opts.budget)
195 // If we are almost out of budgeted time, no further elements
196 // should be added to the queue. This ensures remaining time is
197 // used for processing current queue.
198 if !c.deepState.queueClosed && spent >= 0.85 {
199 c.deepState.queueClosed = true
200 }
201 }
202
203 // if deep search is disabled, don't add any more candidates.
204 if !c.deepState.enabled || c.deepState.queueClosed {
205 continue
206 }
207
208 // Searching members for a type name doesn't make sense.
209 if isTypeName(obj) {
210 continue
211 }
212 if obj.Type() == nil {
213 continue
214 }
215
216 // Don't search embedded fields because they were already included in their
217 // parent's fields.
218 if v, ok := obj.(*types.Var); ok && v.Embedded() {
219 continue
220 }
221
222 if sig, ok := obj.Type().Underlying().(*types.Signature); ok {
223 // If obj is a function that takes no arguments and returns one
224 // value, keep searching across the function call.
225 if sig.Params().Len() == 0 && sig.Results().Len() == 1 {
226 path := c.deepState.newPath(cand, obj)
227 // The result of a function call is not addressable.
228 c.methodsAndFields(sig.Results().At(0).Type(), false, cand.imp, func(newCand candidate) {
229 newCand.pathInvokeMask = cand.pathInvokeMask | (1 << uint64(len(cand.path)))
230 newCand.path = path
231 c.deepState.enqueue(newCand)
232 })
233 }
234 }
235
236 path := c.deepState.newPath(cand, obj)
237 switch obj := obj.(type) {
238 case *types.PkgName:
239 c.packageMembers(obj.Imported(), stdScore, cand.imp, func(newCand candidate) {
240 newCand.pathInvokeMask = cand.pathInvokeMask
241 newCand.path = path
242 c.deepState.enqueue(newCand)
243 })
244 default:
245 c.methodsAndFields(obj.Type(), cand.addressable, cand.imp, func(newCand candidate) {
246 newCand.pathInvokeMask = cand.pathInvokeMask
247 newCand.path = path
248 c.deepState.enqueue(newCand)
249 })
250 }
251 }
252 }
253 }
254
255 // addCandidate adds a completion candidate to suggestions, without searching
256 // its members for more candidates.
257 func (c *completer) addCandidate(ctx context.Context, cand *candidate) {
258 obj := cand.obj
259 if obj != nil && obj.Name() == "_" {
260 return
261 }
262 if c.matchingCandidate(cand) {
263 cand.score *= highScore
264
265 if p := c.penalty(cand); p > 0 {
266 cand.score *= (1 - p)
267 }
268 } else if isTypeName(obj) {
269 // If obj is a *types.TypeName that didn't otherwise match, check
270 // if a literal object of this type makes a good candidate.
271
272 // We only care about named types (i.e. don't want builtin types).
273 if _, isNamed := obj.Type().(*types.Named); isNamed {
274 c.literal(ctx, obj.Type(), cand.imp)
275 }
276 }
277
278 // Lower score of method calls so we prefer fields and vars over calls.
279 if cand.hasMod(invoke) {
280 if sig, ok := obj.Type().Underlying().(*types.Signature); ok && sig.Recv() != nil {
281 cand.score *= 0.9
282 }
283 }
284
285 // Prefer private objects over public ones.
286 if !obj.Exported() && obj.Parent() != types.Universe {
287 cand.score *= 1.1
288 }
289
290 // Slight penalty for index modifier (e.g. changing "foo" to
291 // "foo[]") to curb false positives.
292 if cand.hasMod(index) {
293 cand.score *= 0.9
294 }
295
296 // Favor shallow matches by lowering score according to depth.
297 cand.score -= cand.score * c.deepState.scorePenalty(cand)
298
299 if cand.score < 0 {
300 cand.score = 0
301 }
302
303 cand.name = deepCandName(cand)
304 if item, err := c.item(ctx, *cand); err == nil {
305 c.items = append(c.items, item)
306 }
307 }
308
309 // deepCandName produces the full candidate name including any
310 // ancestor objects. For example, "foo.bar().baz" for candidate "baz".
311 func deepCandName(cand *candidate) string {
312 totalLen := len(cand.obj.Name())
313 for i, obj := range cand.path {
314 totalLen += len(obj.Name()) + 1
315 if cand.pathInvokeMask&(1<<uint16(i)) > 0 {
316 totalLen += 2
317 }
318 }
319
320 var buf strings.Builder
321 buf.Grow(totalLen)
322
323 for i, obj := range cand.path {
324 buf.WriteString(obj.Name())
325 if fn, ok := obj.(*types.Func); ok {
326 buf.WriteString(typesutil.FormatTypeParams(fn.Signature().TypeParams()))
327 }
328 if cand.pathInvokeMask&(1<<uint16(i)) > 0 {
329 buf.WriteByte('(')
330 buf.WriteByte(')')
331 }
332 buf.WriteByte('.')
333 }
334
335 buf.WriteString(cand.obj.Name())
336
337 return buf.String()
338 }
339
340 // penalty reports a score penalty for cand in the range (0, 1).
341 // For example, a candidate is penalized if it has already been used
342 // in another switch case statement.
343 func (c *completer) penalty(cand *candidate) float64 {
344 for _, p := range c.inference.penalized {
345 if c.objChainMatches(cand, p.objChain) {
346 return p.penalty
347 }
348 }
349
350 return 0
351 }
352
353 // objChainMatches reports whether cand combined with the surrounding
354 // object prefix matches chain.
355 func (c *completer) objChainMatches(cand *candidate, chain []types.Object) bool {
356 // For example, when completing:
357 //
358 // foo.ba<>
359 //
360 // If we are considering the deep candidate "bar.baz", cand is baz,
361 // objChain is [foo] and deepChain is [bar]. We would match the
362 // chain [foo, bar, baz].
363 if len(chain) != len(c.inference.objChain)+len(cand.path)+1 {
364 return false
365 }
366
367 if chain[len(chain)-1] != cand.obj {
368 return false
369 }
370
371 for i, o := range c.inference.objChain {
372 if chain[i] != o {
373 return false
374 }
375 }
376
377 for i, o := range cand.path {
378 if chain[i+len(c.inference.objChain)] != o {
379 return false
380 }
381 }
382
383 return true
384 }