-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
completion.go
2967 lines (2601 loc) · 86.1 KB
/
completion.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 2018 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 completion provides core functionality for code completion in Go
// editors and tools.
package completion
import (
"context"
"fmt"
"go/ast"
"go/constant"
"go/scanner"
"go/token"
"go/types"
"math"
"sort"
"strconv"
"strings"
"sync"
"time"
"unicode"
"golang.org/x/tools/go/ast/astutil"
"golang.org/x/tools/internal/event"
"golang.org/x/tools/internal/imports"
"golang.org/x/tools/internal/lsp/fuzzy"
"golang.org/x/tools/internal/lsp/protocol"
"golang.org/x/tools/internal/lsp/snippet"
"golang.org/x/tools/internal/lsp/source"
"golang.org/x/tools/internal/typeparams"
errors "golang.org/x/xerrors"
)
type CompletionItem struct {
// Label is the primary text the user sees for this completion item.
Label string
// Detail is supplemental information to present to the user.
// This often contains the type or return type of the completion item.
Detail string
// InsertText is the text to insert if this item is selected.
// Any of the prefix that has already been typed is not trimmed.
// The insert text does not contain snippets.
InsertText string
Kind protocol.CompletionItemKind
Tags []protocol.CompletionItemTag
Deprecated bool // Deprecated, prefer Tags if available
// An optional array of additional TextEdits that are applied when
// selecting this completion.
//
// Additional text edits should be used to change text unrelated to the current cursor position
// (for example adding an import statement at the top of the file if the completion item will
// insert an unqualified type).
AdditionalTextEdits []protocol.TextEdit
// Depth is how many levels were searched to find this completion.
// For example when completing "foo<>", "fooBar" is depth 0, and
// "fooBar.Baz" is depth 1.
Depth int
// Score is the internal relevance score.
// A higher score indicates that this completion item is more relevant.
Score float64
// snippet is the LSP snippet for the completion item. The LSP
// specification contains details about LSP snippets. For example, a
// snippet for a function with the following signature:
//
// func foo(a, b, c int)
//
// would be:
//
// foo(${1:a int}, ${2: b int}, ${3: c int})
//
// If Placeholders is false in the CompletionOptions, the above
// snippet would instead be:
//
// foo(${1:})
snippet *snippet.Builder
// Documentation is the documentation for the completion item.
Documentation string
// obj is the object from which this candidate was derived, if any.
// obj is for internal use only.
obj types.Object
}
// completionOptions holds completion specific configuration.
type completionOptions struct {
unimported bool
documentation bool
fullDocumentation bool
placeholders bool
literal bool
snippets bool
postfix bool
matcher source.Matcher
budget time.Duration
}
// Snippet is a convenience returns the snippet if available, otherwise
// the InsertText.
// used for an item, depending on if the callee wants placeholders or not.
func (i *CompletionItem) Snippet() string {
if i.snippet != nil {
return i.snippet.String()
}
return i.InsertText
}
// Scoring constants are used for weighting the relevance of different candidates.
const (
// stdScore is the base score for all completion items.
stdScore float64 = 1.0
// highScore indicates a very relevant completion item.
highScore float64 = 10.0
// lowScore indicates an irrelevant or not useful completion item.
lowScore float64 = 0.01
)
// matcher matches a candidate's label against the user input. The
// returned score reflects the quality of the match. A score of zero
// indicates no match, and a score of one means a perfect match.
type matcher interface {
Score(candidateLabel string) (score float32)
}
// prefixMatcher implements case sensitive prefix matching.
type prefixMatcher string
func (pm prefixMatcher) Score(candidateLabel string) float32 {
if strings.HasPrefix(candidateLabel, string(pm)) {
return 1
}
return -1
}
// insensitivePrefixMatcher implements case insensitive prefix matching.
type insensitivePrefixMatcher string
func (ipm insensitivePrefixMatcher) Score(candidateLabel string) float32 {
if strings.HasPrefix(strings.ToLower(candidateLabel), string(ipm)) {
return 1
}
return -1
}
// completer contains the necessary information for a single completion request.
type completer struct {
snapshot source.Snapshot
pkg source.Package
qf types.Qualifier
opts *completionOptions
// completionContext contains information about the trigger for this
// completion request.
completionContext completionContext
// fh is a handle to the file associated with this completion request.
fh source.FileHandle
// filename is the name of the file associated with this completion request.
filename string
// file is the AST of the file associated with this completion request.
file *ast.File
// pos is the position at which the request was triggered.
pos token.Pos
// path is the path of AST nodes enclosing the position.
path []ast.Node
// seen is the map that ensures we do not return duplicate results.
seen map[types.Object]bool
// items is the list of completion items returned.
items []CompletionItem
// completionCallbacks is a list of callbacks to collect completions that
// require expensive operations. This includes operations where we search
// through the entire module cache.
completionCallbacks []func(opts *imports.Options) error
// surrounding describes the identifier surrounding the position.
surrounding *Selection
// inference contains information we've inferred about ideal
// candidates such as the candidate's type.
inference candidateInference
// enclosingFunc contains information about the function enclosing
// the position.
enclosingFunc *funcInfo
// enclosingCompositeLiteral contains information about the composite literal
// enclosing the position.
enclosingCompositeLiteral *compLitInfo
// deepState contains the current state of our deep completion search.
deepState deepCompletionState
// matcher matches the candidates against the surrounding prefix.
matcher matcher
// methodSetCache caches the types.NewMethodSet call, which is relatively
// expensive and can be called many times for the same type while searching
// for deep completions.
methodSetCache map[methodSetKey]*types.MethodSet
// mapper converts the positions in the file from which the completion originated.
mapper *protocol.ColumnMapper
// startTime is when we started processing this completion request. It does
// not include any time the request spent in the queue.
startTime time.Time
}
// funcInfo holds info about a function object.
type funcInfo struct {
// sig is the function declaration enclosing the position.
sig *types.Signature
// body is the function's body.
body *ast.BlockStmt
}
type compLitInfo struct {
// cl is the *ast.CompositeLit enclosing the position.
cl *ast.CompositeLit
// clType is the type of cl.
clType types.Type
// kv is the *ast.KeyValueExpr enclosing the position, if any.
kv *ast.KeyValueExpr
// inKey is true if we are certain the position is in the key side
// of a key-value pair.
inKey bool
// maybeInFieldName is true if inKey is false and it is possible
// we are completing a struct field name. For example,
// "SomeStruct{<>}" will be inKey=false, but maybeInFieldName=true
// because we _could_ be completing a field name.
maybeInFieldName bool
}
type importInfo struct {
importPath string
name string
pkg source.Package
}
type methodSetKey struct {
typ types.Type
addressable bool
}
type completionContext struct {
// triggerCharacter is the character used to trigger completion at current
// position, if any.
triggerCharacter string
// triggerKind is information about how a completion was triggered.
triggerKind protocol.CompletionTriggerKind
// commentCompletion is true if we are completing a comment.
commentCompletion bool
// packageCompletion is true if we are completing a package name.
packageCompletion bool
}
// A Selection represents the cursor position and surrounding identifier.
type Selection struct {
content string
cursor token.Pos
source.MappedRange
}
func (p Selection) Content() string {
return p.content
}
func (p Selection) Start() token.Pos {
return p.MappedRange.SpanRange().Start
}
func (p Selection) End() token.Pos {
return p.MappedRange.SpanRange().End
}
func (p Selection) Prefix() string {
return p.content[:p.cursor-p.SpanRange().Start]
}
func (p Selection) Suffix() string {
return p.content[p.cursor-p.SpanRange().Start:]
}
func (c *completer) setSurrounding(ident *ast.Ident) {
if c.surrounding != nil {
return
}
if !(ident.Pos() <= c.pos && c.pos <= ident.End()) {
return
}
c.surrounding = &Selection{
content: ident.Name,
cursor: c.pos,
// Overwrite the prefix only.
MappedRange: source.NewMappedRange(c.snapshot.FileSet(), c.mapper, ident.Pos(), ident.End()),
}
c.setMatcherFromPrefix(c.surrounding.Prefix())
}
func (c *completer) setMatcherFromPrefix(prefix string) {
switch c.opts.matcher {
case source.Fuzzy:
c.matcher = fuzzy.NewMatcher(prefix)
case source.CaseSensitive:
c.matcher = prefixMatcher(prefix)
default:
c.matcher = insensitivePrefixMatcher(strings.ToLower(prefix))
}
}
func (c *completer) getSurrounding() *Selection {
if c.surrounding == nil {
c.surrounding = &Selection{
content: "",
cursor: c.pos,
MappedRange: source.NewMappedRange(c.snapshot.FileSet(), c.mapper, c.pos, c.pos),
}
}
return c.surrounding
}
// candidate represents a completion candidate.
type candidate struct {
// obj is the types.Object to complete to.
obj types.Object
// score is used to rank candidates.
score float64
// name is the deep object name path, e.g. "foo.bar"
name string
// detail is additional information about this item. If not specified,
// defaults to type string for the object.
detail string
// path holds the path from the search root (excluding the candidate
// itself) for a deep candidate.
path []types.Object
// pathInvokeMask is a bit mask tracking whether each entry in path
// should be formatted with "()" (i.e. whether it is a function
// invocation).
pathInvokeMask uint16
// mods contains modifications that should be applied to the
// candidate when inserted. For example, "foo" may be inserted as
// "*foo" or "foo()".
mods []typeModKind
// addressable is true if a pointer can be taken to the candidate.
addressable bool
// convertTo is a type that this candidate should be cast to. For
// example, if convertTo is float64, "foo" should be formatted as
// "float64(foo)".
convertTo types.Type
// imp is the import that needs to be added to this package in order
// for this candidate to be valid. nil if no import needed.
imp *importInfo
}
func (c candidate) hasMod(mod typeModKind) bool {
for _, m := range c.mods {
if m == mod {
return true
}
}
return false
}
// ErrIsDefinition is an error that informs the user they got no
// completions because they tried to complete the name of a new object
// being defined.
type ErrIsDefinition struct {
objStr string
}
func (e ErrIsDefinition) Error() string {
msg := "this is a definition"
if e.objStr != "" {
msg += " of " + e.objStr
}
return msg
}
// Completion returns a list of possible candidates for completion, given a
// a file and a position.
//
// The selection is computed based on the preceding identifier and can be used by
// the client to score the quality of the completion. For instance, some clients
// may tolerate imperfect matches as valid completion results, since users may make typos.
func Completion(ctx context.Context, snapshot source.Snapshot, fh source.FileHandle, protoPos protocol.Position, protoContext protocol.CompletionContext) ([]CompletionItem, *Selection, error) {
ctx, done := event.Start(ctx, "completion.Completion")
defer done()
startTime := time.Now()
pkg, pgf, err := source.GetParsedFile(ctx, snapshot, fh, source.NarrowestPackage)
if err != nil || pgf.File.Package == token.NoPos {
// If we can't parse this file or find position for the package
// keyword, it may be missing a package declaration. Try offering
// suggestions for the package declaration.
// Note that this would be the case even if the keyword 'package' is
// present but no package name exists.
items, surrounding, innerErr := packageClauseCompletions(ctx, snapshot, fh, protoPos)
if innerErr != nil {
// return the error for GetParsedFile since it's more relevant in this situation.
return nil, nil, errors.Errorf("getting file for Completion: %w (package completions: %v)", err, innerErr)
}
return items, surrounding, nil
}
spn, err := pgf.Mapper.PointSpan(protoPos)
if err != nil {
return nil, nil, err
}
rng, err := spn.Range(pgf.Mapper.Converter)
if err != nil {
return nil, nil, err
}
// Completion is based on what precedes the cursor.
// Find the path to the position before pos.
path, _ := astutil.PathEnclosingInterval(pgf.File, rng.Start-1, rng.Start-1)
if path == nil {
return nil, nil, errors.Errorf("cannot find node enclosing position")
}
pos := rng.Start
// Check if completion at this position is valid. If not, return early.
switch n := path[0].(type) {
case *ast.BasicLit:
// Skip completion inside literals except for ImportSpec
if len(path) > 1 {
if _, ok := path[1].(*ast.ImportSpec); ok {
break
}
}
return nil, nil, nil
case *ast.CallExpr:
if n.Ellipsis.IsValid() && pos > n.Ellipsis && pos <= n.Ellipsis+token.Pos(len("...")) {
// Don't offer completions inside or directly after "...". For
// example, don't offer completions at "<>" in "foo(bar...<>").
return nil, nil, nil
}
case *ast.Ident:
// reject defining identifiers
if obj, ok := pkg.GetTypesInfo().Defs[n]; ok {
if v, ok := obj.(*types.Var); ok && v.IsField() && v.Embedded() {
// An anonymous field is also a reference to a type.
} else if pgf.File.Name == n {
// Don't skip completions if Ident is for package name.
break
} else {
objStr := ""
if obj != nil {
qual := types.RelativeTo(pkg.GetTypes())
objStr = types.ObjectString(obj, qual)
}
ans, sel := definition(path, obj, snapshot.FileSet(), pgf.Mapper, fh)
if ans != nil {
sort.Slice(ans, func(i, j int) bool {
return ans[i].Score > ans[j].Score
})
return ans, sel, nil
}
return nil, nil, ErrIsDefinition{objStr: objStr}
}
}
}
opts := snapshot.View().Options()
c := &completer{
pkg: pkg,
snapshot: snapshot,
qf: source.Qualifier(pgf.File, pkg.GetTypes(), pkg.GetTypesInfo()),
completionContext: completionContext{
triggerCharacter: protoContext.TriggerCharacter,
triggerKind: protoContext.TriggerKind,
},
fh: fh,
filename: fh.URI().Filename(),
file: pgf.File,
path: path,
pos: pos,
seen: make(map[types.Object]bool),
enclosingFunc: enclosingFunction(path, pkg.GetTypesInfo()),
enclosingCompositeLiteral: enclosingCompositeLiteral(path, rng.Start, pkg.GetTypesInfo()),
deepState: deepCompletionState{
enabled: opts.DeepCompletion,
},
opts: &completionOptions{
matcher: opts.Matcher,
unimported: opts.CompleteUnimported,
documentation: opts.CompletionDocumentation && opts.HoverKind != source.NoDocumentation,
fullDocumentation: opts.HoverKind == source.FullDocumentation,
placeholders: opts.UsePlaceholders,
literal: opts.LiteralCompletions && opts.InsertTextFormat == protocol.SnippetTextFormat,
budget: opts.CompletionBudget,
snippets: opts.InsertTextFormat == protocol.SnippetTextFormat,
postfix: opts.ExperimentalPostfixCompletions,
},
// default to a matcher that always matches
matcher: prefixMatcher(""),
methodSetCache: make(map[methodSetKey]*types.MethodSet),
mapper: pgf.Mapper,
startTime: startTime,
}
var cancel context.CancelFunc
if c.opts.budget == 0 {
ctx, cancel = context.WithCancel(ctx)
} else {
// timeoutDuration is the completion budget remaining. If less than
// 10ms, set to 10ms
timeoutDuration := time.Until(c.startTime.Add(c.opts.budget))
if timeoutDuration < 10*time.Millisecond {
timeoutDuration = 10 * time.Millisecond
}
ctx, cancel = context.WithTimeout(ctx, timeoutDuration)
}
defer cancel()
if surrounding := c.containingIdent(pgf.Src); surrounding != nil {
c.setSurrounding(surrounding)
}
c.inference = expectedCandidate(ctx, c)
err = c.collectCompletions(ctx)
if err != nil {
return nil, nil, err
}
// Deep search collected candidates and their members for more candidates.
c.deepSearch(ctx)
for _, callback := range c.completionCallbacks {
if err := c.snapshot.RunProcessEnvFunc(ctx, callback); err != nil {
return nil, nil, err
}
}
// Search candidates populated by expensive operations like
// unimportedMembers etc. for more completion items.
c.deepSearch(ctx)
// Statement candidates offer an entire statement in certain contexts, as
// opposed to a single object. Add statement candidates last because they
// depend on other candidates having already been collected.
c.addStatementCandidates()
c.sortItems()
return c.items, c.getSurrounding(), nil
}
// collectCompletions adds possible completion candidates to either the deep
// search queue or completion items directly for different completion contexts.
func (c *completer) collectCompletions(ctx context.Context) error {
// Inside import blocks, return completions for unimported packages.
for _, importSpec := range c.file.Imports {
if !(importSpec.Path.Pos() <= c.pos && c.pos <= importSpec.Path.End()) {
continue
}
return c.populateImportCompletions(ctx, importSpec)
}
// Inside comments, offer completions for the name of the relevant symbol.
for _, comment := range c.file.Comments {
if comment.Pos() < c.pos && c.pos <= comment.End() {
c.populateCommentCompletions(ctx, comment)
return nil
}
}
// Struct literals are handled entirely separately.
if c.wantStructFieldCompletions() {
// If we are definitely completing a struct field name, deep completions
// don't make sense.
if c.enclosingCompositeLiteral.inKey {
c.deepState.enabled = false
}
return c.structLiteralFieldName(ctx)
}
if lt := c.wantLabelCompletion(); lt != labelNone {
c.labels(lt)
return nil
}
if c.emptySwitchStmt() {
// Empty switch statements only admit "default" and "case" keywords.
c.addKeywordItems(map[string]bool{}, highScore, CASE, DEFAULT)
return nil
}
switch n := c.path[0].(type) {
case *ast.Ident:
if c.file.Name == n {
return c.packageNameCompletions(ctx, c.fh.URI(), n)
} else if sel, ok := c.path[1].(*ast.SelectorExpr); ok && sel.Sel == n {
// Is this the Sel part of a selector?
return c.selector(ctx, sel)
}
return c.lexical(ctx)
// The function name hasn't been typed yet, but the parens are there:
// recv.‸(arg)
case *ast.TypeAssertExpr:
// Create a fake selector expression.
return c.selector(ctx, &ast.SelectorExpr{X: n.X})
case *ast.SelectorExpr:
return c.selector(ctx, n)
// At the file scope, only keywords are allowed.
case *ast.BadDecl, *ast.File:
c.addKeywordCompletions()
default:
// fallback to lexical completions
return c.lexical(ctx)
}
return nil
}
// containingIdent returns the *ast.Ident containing pos, if any. It
// synthesizes an *ast.Ident to allow completion in the face of
// certain syntax errors.
func (c *completer) containingIdent(src []byte) *ast.Ident {
// In the normal case, our leaf AST node is the identifier being completed.
if ident, ok := c.path[0].(*ast.Ident); ok {
return ident
}
pos, tkn, lit := c.scanToken(src)
if !pos.IsValid() {
return nil
}
fakeIdent := &ast.Ident{Name: lit, NamePos: pos}
if _, isBadDecl := c.path[0].(*ast.BadDecl); isBadDecl {
// You don't get *ast.Idents at the file level, so look for bad
// decls and use the manually extracted token.
return fakeIdent
} else if c.emptySwitchStmt() {
// Only keywords are allowed in empty switch statements.
// *ast.Idents are not parsed, so we must use the manually
// extracted token.
return fakeIdent
} else if tkn.IsKeyword() {
// Otherwise, manually extract the prefix if our containing token
// is a keyword. This improves completion after an "accidental
// keyword", e.g. completing to "variance" in "someFunc(var<>)".
return fakeIdent
}
return nil
}
// scanToken scans pgh's contents for the token containing pos.
func (c *completer) scanToken(contents []byte) (token.Pos, token.Token, string) {
tok := c.snapshot.FileSet().File(c.pos)
var s scanner.Scanner
s.Init(tok, contents, nil, 0)
for {
tknPos, tkn, lit := s.Scan()
if tkn == token.EOF || tknPos >= c.pos {
return token.NoPos, token.ILLEGAL, ""
}
if len(lit) > 0 && tknPos <= c.pos && c.pos <= tknPos+token.Pos(len(lit)) {
return tknPos, tkn, lit
}
}
}
func (c *completer) sortItems() {
sort.SliceStable(c.items, func(i, j int) bool {
// Sort by score first.
if c.items[i].Score != c.items[j].Score {
return c.items[i].Score > c.items[j].Score
}
// Then sort by label so order stays consistent. This also has the
// effect of preferring shorter candidates.
return c.items[i].Label < c.items[j].Label
})
}
// emptySwitchStmt reports whether pos is in an empty switch or select
// statement.
func (c *completer) emptySwitchStmt() bool {
block, ok := c.path[0].(*ast.BlockStmt)
if !ok || len(block.List) > 0 || len(c.path) == 1 {
return false
}
switch c.path[1].(type) {
case *ast.SwitchStmt, *ast.TypeSwitchStmt, *ast.SelectStmt:
return true
default:
return false
}
}
// populateImportCompletions yields completions for an import path around the cursor.
//
// Completions are suggested at the directory depth of the given import path so
// that we don't overwhelm the user with a large list of possibilities. As an
// example, a completion for the prefix "golang" results in "golang.org/".
// Completions for "golang.org/" yield its subdirectories
// (i.e. "golang.org/x/"). The user is meant to accept completion suggestions
// until they reach a complete import path.
func (c *completer) populateImportCompletions(ctx context.Context, searchImport *ast.ImportSpec) error {
if !strings.HasPrefix(searchImport.Path.Value, `"`) {
return nil
}
// deepSearch is not valuable for import completions.
c.deepState.enabled = false
importPath := searchImport.Path.Value
// Extract the text between the quotes (if any) in an import spec.
// prefix is the part of import path before the cursor.
prefixEnd := c.pos - searchImport.Path.Pos()
prefix := strings.Trim(importPath[:prefixEnd], `"`)
// The number of directories in the import path gives us the depth at
// which to search.
depth := len(strings.Split(prefix, "/")) - 1
content := importPath
start, end := searchImport.Path.Pos(), searchImport.Path.End()
namePrefix, nameSuffix := `"`, `"`
// If a starting quote is present, adjust surrounding to either after the
// cursor or after the first slash (/), except if cursor is at the starting
// quote. Otherwise we provide a completion including the starting quote.
if strings.HasPrefix(importPath, `"`) && c.pos > searchImport.Path.Pos() {
content = content[1:]
start++
if depth > 0 {
// Adjust textEdit start to replacement range. For ex: if current
// path was "golang.or/x/to<>ols/internal/", where <> is the cursor
// position, start of the replacement range would be after
// "golang.org/x/".
path := strings.SplitAfter(prefix, "/")
numChars := len(strings.Join(path[:len(path)-1], ""))
content = content[numChars:]
start += token.Pos(numChars)
}
namePrefix = ""
}
// We won't provide an ending quote if one is already present, except if
// cursor is after the ending quote but still in import spec. This is
// because cursor has to be in our textEdit range.
if strings.HasSuffix(importPath, `"`) && c.pos < searchImport.Path.End() {
end--
content = content[:len(content)-1]
nameSuffix = ""
}
c.surrounding = &Selection{
content: content,
cursor: c.pos,
MappedRange: source.NewMappedRange(c.snapshot.FileSet(), c.mapper, start, end),
}
seenImports := make(map[string]struct{})
for _, importSpec := range c.file.Imports {
if importSpec.Path.Value == importPath {
continue
}
seenImportPath, err := strconv.Unquote(importSpec.Path.Value)
if err != nil {
return err
}
seenImports[seenImportPath] = struct{}{}
}
var mu sync.Mutex // guard c.items locally, since searchImports is called in parallel
seen := make(map[string]struct{})
searchImports := func(pkg imports.ImportFix) {
path := pkg.StmtInfo.ImportPath
if _, ok := seenImports[path]; ok {
return
}
// Any package path containing fewer directories than the search
// prefix is not a match.
pkgDirList := strings.Split(path, "/")
if len(pkgDirList) < depth+1 {
return
}
pkgToConsider := strings.Join(pkgDirList[:depth+1], "/")
name := pkgDirList[depth]
// if we're adding an opening quote to completion too, set name to full
// package path since we'll need to overwrite that range.
if namePrefix == `"` {
name = pkgToConsider
}
score := pkg.Relevance
if len(pkgDirList)-1 == depth {
score *= highScore
} else {
// For incomplete package paths, add a terminal slash to indicate that the
// user should keep triggering completions.
name += "/"
pkgToConsider += "/"
}
if _, ok := seen[pkgToConsider]; ok {
return
}
seen[pkgToConsider] = struct{}{}
mu.Lock()
defer mu.Unlock()
name = namePrefix + name + nameSuffix
obj := types.NewPkgName(0, nil, name, types.NewPackage(pkgToConsider, name))
c.deepState.enqueue(candidate{
obj: obj,
detail: fmt.Sprintf("%q", pkgToConsider),
score: score,
})
}
c.completionCallbacks = append(c.completionCallbacks, func(opts *imports.Options) error {
return imports.GetImportPaths(ctx, searchImports, prefix, c.filename, c.pkg.GetTypes().Name(), opts.Env)
})
return nil
}
// populateCommentCompletions yields completions for comments preceding or in declarations.
func (c *completer) populateCommentCompletions(ctx context.Context, comment *ast.CommentGroup) {
// If the completion was triggered by a period, ignore it. These types of
// completions will not be useful in comments.
if c.completionContext.triggerCharacter == "." {
return
}
// Using the comment position find the line after
file := c.snapshot.FileSet().File(comment.End())
if file == nil {
return
}
// Deep completion doesn't work properly in comments since we don't
// have a type object to complete further.
c.deepState.enabled = false
c.completionContext.commentCompletion = true
// Documentation isn't useful in comments, since it might end up being the
// comment itself.
c.opts.documentation = false
commentLine := file.Line(comment.End())
// comment is valid, set surrounding as word boundaries around cursor
c.setSurroundingForComment(comment)
// Using the next line pos, grab and parse the exported symbol on that line
for _, n := range c.file.Decls {
declLine := file.Line(n.Pos())
// if the comment is not in, directly above or on the same line as a declaration
if declLine != commentLine && declLine != commentLine+1 &&
!(n.Pos() <= comment.Pos() && comment.End() <= n.End()) {
continue
}
switch node := n.(type) {
// handle const, vars, and types
case *ast.GenDecl:
for _, spec := range node.Specs {
switch spec := spec.(type) {
case *ast.ValueSpec:
for _, name := range spec.Names {
if name.String() == "_" {
continue
}
obj := c.pkg.GetTypesInfo().ObjectOf(name)
c.deepState.enqueue(candidate{obj: obj, score: stdScore})
}
case *ast.TypeSpec:
// add TypeSpec fields to completion
switch typeNode := spec.Type.(type) {
case *ast.StructType:
c.addFieldItems(ctx, typeNode.Fields)
case *ast.FuncType:
c.addFieldItems(ctx, typeNode.Params)
c.addFieldItems(ctx, typeNode.Results)
case *ast.InterfaceType:
c.addFieldItems(ctx, typeNode.Methods)
}
if spec.Name.String() == "_" {
continue
}
obj := c.pkg.GetTypesInfo().ObjectOf(spec.Name)
// Type name should get a higher score than fields but not highScore by default
// since field near a comment cursor gets a highScore
score := stdScore * 1.1
// If type declaration is on the line after comment, give it a highScore.
if declLine == commentLine+1 {
score = highScore
}
c.deepState.enqueue(candidate{obj: obj, score: score})
}
}
// handle functions
case *ast.FuncDecl:
c.addFieldItems(ctx, node.Recv)
c.addFieldItems(ctx, node.Type.Params)
c.addFieldItems(ctx, node.Type.Results)
// collect receiver struct fields
if node.Recv != nil {
for _, fields := range node.Recv.List {
for _, name := range fields.Names {
obj := c.pkg.GetTypesInfo().ObjectOf(name)
if obj == nil {
continue
}
recvType := obj.Type().Underlying()
if ptr, ok := recvType.(*types.Pointer); ok {
recvType = ptr.Elem()
}
recvStruct, ok := recvType.Underlying().(*types.Struct)
if !ok {
continue
}
for i := 0; i < recvStruct.NumFields(); i++ {
field := recvStruct.Field(i)
c.deepState.enqueue(candidate{obj: field, score: lowScore})
}
}
}
}
if node.Name.String() == "_" {
continue
}
obj := c.pkg.GetTypesInfo().ObjectOf(node.Name)
if obj == nil || obj.Pkg() != nil && obj.Pkg() != c.pkg.GetTypes() {
continue
}
c.deepState.enqueue(candidate{obj: obj, score: highScore})
}
}
}
// sets word boundaries surrounding a cursor for a comment
func (c *completer) setSurroundingForComment(comments *ast.CommentGroup) {
var cursorComment *ast.Comment
for _, comment := range comments.List {
if c.pos >= comment.Pos() && c.pos <= comment.End() {
cursorComment = comment
break
}
}
// if cursor isn't in the comment
if cursorComment == nil {
return