Debian Codegraph @

gopls/internal/test/integration/completion/completion_test.go

raw symbols SCIP
1 // Copyright 2020 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 "fmt"
9 "os"
10 "path/filepath"
11 "slices"
12 "sort"
13 "strings"
14 "testing"
15 "time"
16
17 "github.com/google/go-cmp/cmp"
18 "golang.org/x/telemetry/counter"
19 "golang.org/x/telemetry/counter/countertest"
20 "golang.org/x/tools/gopls/internal/protocol"
21 "golang.org/x/tools/gopls/internal/server"
22 . "golang.org/x/tools/gopls/internal/test/integration"
23 "golang.org/x/tools/gopls/internal/test/integration/fake"
24 "golang.org/x/tools/gopls/internal/util/bug"
25 "golang.org/x/tools/internal/modindex"
26 "golang.org/x/tools/internal/testenv"
27 )
28
29 func TestMain(m *testing.M) {
30 bug.PanicOnBugs = true
31 os.Exit(Main(m))
32 }
33
34 const proxy = `
35 -- [email protected]/go.mod --
36 module example.com
37
38 go 1.12
39 -- [email protected]/blah/blah.go --
40 package blah
41
42 const Name = "Blah"
43 -- [email protected]/go.mod --
44 module random.org
45
46 go 1.12
47 -- [email protected]/blah/blah.go --
48 package hello
49
50 const Name = "Hello"
51 `
52
53 func TestPackageCompletion(t *testing.T) {
54 const files = `
55 -- go.mod --
56 module mod.com
57
58 go 1.12
59 -- cmd/main.go --
60 package main
61 -- cmd/testfile.go --
62 package
63 -- fruits/apple.go --
64 package apple
65
66 fun apple() int {
67 return 0
68 }
69
70 -- fruits/testfile.go --
71 // this is a comment
72
73 /*
74 this is a multiline comment
75 */
76
77 import "fmt"
78
79 func test() {}
80
81 -- fruits/testfile2.go --
82 package
83
84 -- fruits/testfile3.go --
85 pac
86 -- 123f_r.u~its-123/testfile.go --
87 package
88
89 -- .invalid-dir@-name/testfile.go --
90 package
91 `
92 var (
93 testfile4 = ""
94 testfile5 = "/*a comment*/ "
95 testfile6 = "/*a comment*/\n"
96 )
97 for _, tc := range []struct {
98 name string
99 filename string
100 content *string
101 triggerRegexp string
102 want []string
103 editRegexp string
104 }{
105 {
106 name: "main package completion after package keyword",
107 filename: "cmd/testfile.go",
108 triggerRegexp: "package()",
109 want: []string{"package main", "package cmd", "package cmd_test"},
110 editRegexp: "package",
111 },
112 {
113 name: "package completion at valid position",
114 filename: "fruits/testfile.go",
115 triggerRegexp: "\n()",
116 want: []string{"package apple", "package apple_test", "package fruits", "package fruits_test", "package main"},
117 editRegexp: "\n()",
118 },
119 {
120 name: "package completion in a comment",
121 filename: "fruits/testfile.go",
122 triggerRegexp: "th()is",
123 want: nil,
124 },
125 {
126 name: "package completion in a multiline comment",
127 filename: "fruits/testfile.go",
128 triggerRegexp: `\/\*\n()`,
129 want: nil,
130 },
131 {
132 name: "package completion at invalid position",
133 filename: "fruits/testfile.go",
134 triggerRegexp: "import \"fmt\"\n()",
135 want: nil,
136 },
137 {
138 name: "package completion after package keyword",
139 filename: "fruits/testfile2.go",
140 triggerRegexp: "package()",
141 want: []string{"package apple", "package apple_test", "package fruits", "package fruits_test", "package main"},
142 editRegexp: "package",
143 },
144 {
145 name: "package completion with 'pac' prefix",
146 filename: "fruits/testfile3.go",
147 triggerRegexp: "pac()",
148 want: []string{"package apple", "package apple_test", "package fruits", "package fruits_test", "package main"},
149 editRegexp: "pac",
150 },
151 {
152 name: "package completion for empty file",
153 filename: "fruits/testfile4.go",
154 triggerRegexp: "^$",
155 content: &testfile4,
156 want: []string{"package apple", "package apple_test", "package fruits", "package fruits_test", "package main"},
157 editRegexp: "^$",
158 },
159 {
160 name: "package completion without terminal newline",
161 filename: "fruits/testfile5.go",
162 triggerRegexp: `\*\/ ()`,
163 content: &testfile5,
164 want: []string{"package apple", "package apple_test", "package fruits", "package fruits_test", "package main"},
165 editRegexp: `\*\/ ()`,
166 },
167 {
168 name: "package completion on terminal newline",
169 filename: "fruits/testfile6.go",
170 triggerRegexp: `\*\/\n()`,
171 content: &testfile6,
172 want: []string{"package apple", "package apple_test", "package fruits", "package fruits_test", "package main"},
173 editRegexp: `\*\/\n()`,
174 },
175 // Issue golang/go#44680
176 {
177 name: "package completion for dir name with punctuation",
178 filename: "123f_r.u~its-123/testfile.go",
179 triggerRegexp: "package()",
180 want: []string{"package fruits123", "package fruits123_test", "package main"},
181 editRegexp: "package",
182 },
183 {
184 name: "package completion for invalid dir name",
185 filename: ".invalid-dir@-name/testfile.go",
186 triggerRegexp: "package()",
187 want: []string{"package main"},
188 editRegexp: "package",
189 },
190 } {
191 t.Run(tc.name, func(t *testing.T) {
192 Run(t, files, func(t *testing.T, env *Env) {
193 if tc.content != nil {
194 env.WriteWorkspaceFile(tc.filename, *tc.content)
195 env.Await(env.DoneWithChangeWatchedFiles())
196 }
197 env.OpenFile(tc.filename)
198 completions := env.Completion(env.RegexpSearch(tc.filename, tc.triggerRegexp))
199
200 // Check that the completion item suggestions are in the range
201 // of the file. {Start,End}.Line are zero-based.
202 lineCount := len(strings.Split(env.BufferText(tc.filename), "\n"))
203 for _, item := range completions.Items {
204 for _, mode := range []string{"replace", "insert"} {
205 edit, err := protocol.SelectCompletionTextEdit(item, mode == "replace")
206 if err != nil {
207 t.Fatalf("unexpected text edit in completion item (%v): %v", mode, err)
208 }
209 if start := int(edit.Range.Start.Line); start > lineCount {
210 t.Fatalf("unexpected text edit range (%v) start line number: got %d, want <= %d", mode, start, lineCount)
211 }
212 if end := int(edit.Range.End.Line); end > lineCount {
213 t.Fatalf("unexpected text edit range (%v) end line number: got %d, want <= %d", mode, end, lineCount)
214 }
215 }
216 }
217
218 if tc.want != nil {
219 expectedLoc := env.RegexpSearch(tc.filename, tc.editRegexp)
220 for _, item := range completions.Items {
221 for _, mode := range []string{"replace", "insert"} {
222 edit, _ := protocol.SelectCompletionTextEdit(item, mode == "replace")
223 gotRng := edit.Range
224 if expectedLoc.Range != gotRng {
225 t.Errorf("unexpected completion range (%v) for completion item %s: got %v, want %v",
226 mode, item.Label, gotRng, expectedLoc.Range)
227 }
228 }
229 }
230 }
231
232 diff := compareCompletionLabels(tc.want, completions.Items)
233 if diff != "" {
234 t.Error(diff)
235 }
236 })
237 })
238 }
239 }
240
241 func TestPackageNameCompletion(t *testing.T) {
242 const files = `
243 -- go.mod --
244 module mod.com
245
246 go 1.12
247 -- math/add.go --
248 package ma
249 `
250
251 want := []string{"ma", "ma_test", "main", "math", "math_test"}
252 Run(t, files, func(t *testing.T, env *Env) {
253 env.OpenFile("math/add.go")
254 completions := env.Completion(env.RegexpSearch("math/add.go", "package ma()"))
255
256 diff := compareCompletionLabels(want, completions.Items)
257 if diff != "" {
258 t.Fatal(diff)
259 }
260 })
261 }
262
263 // compareCompletionLabels returns a non-empty string reporting the
264 // difference (if any) between the labels of the actual completion
265 // items (gotItems) and the expected list (want).
266 //
267 // A want item with a "?" suffix is optional.
268 //
269 // TODO(rfindley): audit/clean up call sites for this helper, to ensure
270 // consistent test errors.
271 func compareCompletionLabels(want []string, gotItems []protocol.CompletionItem) string {
272 var got []string
273 for _, item := range gotItems {
274 got = append(got, item.Label)
275 if item.Label != item.InsertText && item.TextEdit == nil {
276 // Label should be the same as InsertText, if InsertText is to be used
277 return fmt.Sprintf("label not the same as InsertText %#v", item)
278 }
279 }
280
281 if len(got) == 0 && len(want) == 0 {
282 return "" // treat nil and the empty slice as equivalent
283 }
284
285 // A 'want' item with a '?' suffix is optional, to ease
286 // migration across versions. Remove any that are not present
287 // in the 'got' set.
288 var out []string
289 for _, item := range want {
290 item, optional := strings.CutSuffix(item, "?")
291 if optional && !slices.Contains(got, item) {
292 continue // optional item is missing
293 }
294 out = append(out, item)
295 }
296 want = out
297
298 if diff := cmp.Diff(want, got); diff != "" {
299 return fmt.Sprintf("completion item mismatch (-want +got):\n%s", diff)
300 }
301 return ""
302 }
303
304 func TestIssue74611(t *testing.T) {
305 // Completions should not offer symbols from unimported packages
306 // that cannot be imported because they are "internal".
307 //
308 // Ideally, we should test std case as well but because mocking
309 // a fake stdlib is hard, we just test the 3rd user case.
310 // std test is done interactively.
311 const files = `-- go.mod --
312 module mod.com/cmd
313
314 go 1.21
315
316 -- a.go --
317 package pkg
318 import "fmt"
319
320 func main() {
321 fmt.Println("call Println to use fmt")
322 _ = maps
323 } // (completion requested at start of line)
324 `
325
326 WithOptions().Run(t, files, func(t *testing.T, env *Env) {
327 filename := "a.go"
328 // Trigger unimported completions for the maps package.
329 env.OpenFile(filename)
330 env.Await(env.DoneWithOpen())
331 loc := env.RegexpSearch(filename, `()\n\}`)
332 completions := env.Completion(loc)
333 if len(completions.Items) == 0 {
334 t.Fatalf("no completion items")
335 }
336 runtimeMaps := `"internal/runtime/maps"`
337 found := slices.ContainsFunc(completions.Items, func(item protocol.CompletionItem) bool {
338 return item.Detail == runtimeMaps
339 })
340
341 if found {
342 t.Fatalf("unwanted completion: %s", runtimeMaps)
343 }
344 })
345 }
346
347 func TestUnimportedCompletion(t *testing.T) {
348 const mod = `
349 -- go.mod --
350 module mod.com
351
352 go 1.14
353
354 require example.com v1.2.3
355 -- main.go --
356 package main
357
358 func main() {
359 _ = blah
360 }
361 -- main2.go --
362 package main
363
364 import "example.com/blah"
365
366 func _() {
367 _ = blah.Hello
368 }
369 `
370 WithOptions(
371 WriteGoSum("."),
372 ProxyFiles(proxy),
373 ).Run(t, mod, func(t *testing.T, env *Env) {
374 // Make sure the dependency is in the module cache and accessible for
375 // unimported completions, and then remove it before proceeding.
376 env.RemoveWorkspaceFile("main2.go")
377 env.RunGoCommand("mod", "tidy")
378 env.Await(env.DoneWithChangeWatchedFiles())
379
380 // Trigger unimported completions for the example.com/blah package.
381 env.OpenFile("main.go")
382 env.Await(env.DoneWithOpen())
383 loc := env.RegexpSearch("main.go", "()ah")
384 completions := env.Completion(loc)
385 if len(completions.Items) == 0 {
386 t.Fatalf("no completion items")
387 }
388 env.AcceptCompletion(loc, completions.Items[0]) // adds blah import to main.go
389 env.Await(env.DoneWithChange())
390
391 // Trigger completions once again for the blah.<> selector.
392 env.RegexpReplace("main.go", "_ = blah", "_ = blah.")
393 env.Await(env.DoneWithChange())
394 loc = env.RegexpSearch("main.go", `()\n\}`)
395 completions = env.Completion(loc)
396 if len(completions.Items) != 1 {
397 t.Fatalf("expected 1 completion item, got %v", len(completions.Items))
398 }
399 item := completions.Items[0]
400 if item.Label != "Name" {
401 t.Fatalf("expected completion item blah.Name, got %v", item.Label)
402 }
403 env.AcceptCompletion(loc, item)
404
405 // Await the diagnostics to add example.com/blah to the go.mod file.
406 env.AfterChange(
407 Diagnostics(env.AtRegexp("main.go", `"example.com/blah"`)),
408 )
409 })
410 }
411
412 // Test that completions still work with an undownloaded module, golang/go#43333.
413 func TestUndownloadedModule(t *testing.T) {
414 // mod.com depends on example.com, but only in a file that's hidden by a
415 // build tag, so the IWL won't download example.com. That will cause errors
416 // in the go list -m call performed by the imports package.
417 const files = `
418 -- go.mod --
419 module mod.com
420
421 go 1.14
422
423 require example.com v1.2.3
424 -- useblah.go --
425 // +build hidden
426
427 package pkg
428 import "example.com/blah"
429 var _ = blah.Name
430 -- mainmod/mainmod.go --
431 package mainmod
432
433 const Name = "mainmod"
434 `
435 WithOptions(
436 WriteGoSum("."),
437 ProxyFiles(proxy)).Run(t, files, func(t *testing.T, env *Env) {
438 env.CreateBuffer("import.go", "package pkg\nvar _ = mainmod.Name\n")
439 env.SaveBuffer("import.go")
440 content := env.ReadWorkspaceFile("import.go")
441 if !strings.Contains(content, `import "mod.com/mainmod`) {
442 t.Errorf("expected import of mod.com/mainmod in %q", content)
443 }
444 })
445 }
446
447 // Test that we can doctor the source code enough so the file is
448 // parseable and completion works as expected.
449 func TestSourceFixup(t *testing.T) {
450 // This example relies on the fixer to turn "s." into "s._" so
451 // that it parses as a SelectorExpr with only local problems,
452 // instead of snarfing up the following declaration of S
453 // looking for an identifier; thus completion offers s.i.
454 const files = `
455 -- go.mod --
456 module mod.com
457
458 go 1.12
459 -- foo.go --
460 package foo
461
462 func _() {
463 var s S
464 if s.
465 }
466
467 type S struct {
468 i int
469 }
470 `
471
472 Run(t, files, func(t *testing.T, env *Env) {
473 env.OpenFile("foo.go")
474 completions := env.Completion(env.RegexpSearch("foo.go", `if s\.()`))
475 diff := compareCompletionLabels([]string{"i"}, completions.Items)
476 if diff != "" {
477 t.Fatal(diff)
478 }
479 })
480 }
481
482 func TestCompletion_Issue45510(t *testing.T) {
483 const files = `
484 -- go.mod --
485 module mod.com
486
487 go 1.12
488 -- main.go --
489 package main
490
491 func _() {
492 type a *a
493 var aaaa1, aaaa2 a
494 var _ a = aaaa
495
496 type b a
497 var bbbb1, bbbb2 b
498 var _ b = bbbb
499 }
500
501 type (
502 c *d
503 d *e
504 e **c
505 )
506
507 func _() {
508 var (
509 xxxxc c
510 xxxxd d
511 xxxxe e
512 )
513
514 var _ c = xxxx
515 var _ d = xxxx
516 var _ e = xxxx
517 }
518 `
519
520 Run(t, files, func(t *testing.T, env *Env) {
521 env.OpenFile("main.go")
522
523 tests := []struct {
524 re string
525 want []string
526 }{
527 {`var _ a = aaaa()`, []string{"aaaa1", "aaaa2"}},
528 {`var _ b = bbbb()`, []string{"bbbb1", "bbbb2"}},
529 {`var _ c = xxxx()`, []string{"xxxxc", "xxxxd", "xxxxe"}},
530 {`var _ d = xxxx()`, []string{"xxxxc", "xxxxd", "xxxxe"}},
531 {`var _ e = xxxx()`, []string{"xxxxc", "xxxxd", "xxxxe"}},
532 }
533 for _, tt := range tests {
534 completions := env.Completion(env.RegexpSearch("main.go", tt.re))
535 diff := compareCompletionLabels(tt.want, completions.Items)
536 if diff != "" {
537 t.Errorf("%s: %s", tt.re, diff)
538 }
539 }
540 })
541 }
542
543 func TestCompletionDeprecation(t *testing.T) {
544 const files = `
545 -- go.mod --
546 module test.com
547
548 go 1.16
549 -- prog.go --
550 package waste
551 // Deprecated: use newFoof.
552 func fooFunc() bool {
553 return false
554 }
555
556 // Deprecated: bad.
557 const badPi = 3.14
558
559 func doit() {
560 if fooF
561 panic()
562 x := badP
563 }
564 `
565 Run(t, files, func(t *testing.T, env *Env) {
566 env.OpenFile("prog.go")
567 loc := env.RegexpSearch("prog.go", "if fooF")
568 loc.Range.Start.Character += uint32(protocol.UTF16Len([]byte("if fooF")))
569 completions := env.Completion(loc)
570 diff := compareCompletionLabels([]string{"fooFunc"}, completions.Items)
571 if diff != "" {
572 t.Error(diff)
573 }
574 if completions.Items[0].Tags == nil {
575 t.Errorf("expected Tags to show deprecation %#v", completions.Items[0].Tags)
576 }
577 loc = env.RegexpSearch("prog.go", "= badP")
578 loc.Range.Start.Character += uint32(protocol.UTF16Len([]byte("= badP")))
579 completions = env.Completion(loc)
580 diff = compareCompletionLabels([]string{"badPi"}, completions.Items)
581 if diff != "" {
582 t.Error(diff)
583 }
584 if completions.Items[0].Tags == nil {
585 t.Errorf("expected Tags to show deprecation %#v", completions.Items[0].Tags)
586 }
587 })
588 }
589
590 func TestUnimportedCompletion_VSCodeIssue1489(t *testing.T) {
591 const src = `
592 -- go.mod --
593 module mod.com
594
595 go 1.14
596
597 -- main.go --
598 package main
599
600 import "fmt"
601
602 func main() {
603 fmt.Println("a")
604 math.Sqr
605 }
606 `
607 WithOptions(
608 WindowsLineEndings(),
609 Settings{"ui.completion.usePlaceholders": true},
610 ).Run(t, src, func(t *testing.T, env *Env) {
611 // Trigger unimported completions for the mod.com package.
612 env.OpenFile("main.go")
613 env.Await(env.DoneWithOpen())
614 loc := env.RegexpSearch("main.go", "Sqr()")
615 completions := env.Completion(loc)
616 if len(completions.Items) == 0 {
617 t.Fatalf("no completion items")
618 }
619 env.AcceptCompletion(loc, completions.Items[0])
620 env.Await(env.DoneWithChange())
621 got := env.BufferText("main.go")
622 want := "package main\r\n\r\nimport (\r\n\t\"fmt\"\r\n\t\"math\"\r\n)\r\n\r\nfunc main() {\r\n\tfmt.Println(\"a\")\r\n\tmath.Sqrt(${1:x float64})\r\n}\r\n"
623 if diff := cmp.Diff(want, got); diff != "" {
624 t.Errorf("unimported completion (-want +got):\n%s", diff)
625 }
626 })
627 }
628
629 func TestUnimportedCompletion_VSCodeIssue3365(t *testing.T) {
630 const src = `
631 -- go.mod --
632 module mod.com
633
634 go 1.19
635
636 -- main.go --
637 package main
638
639 func main() {
640 println(strings.TLower)
641 }
642
643 var Lower = ""
644 `
645 find := func(t *testing.T, completions *protocol.CompletionList, name string) protocol.CompletionItem {
646 t.Helper()
647 if completions == nil || len(completions.Items) == 0 {
648 t.Fatalf("no completion items")
649 }
650 for _, i := range completions.Items {
651 if i.Label == name {
652 return i
653 }
654 }
655 t.Fatalf("no item with label %q", name)
656 return protocol.CompletionItem{}
657 }
658
659 for _, supportInsertReplace := range []bool{true, false} {
660 t.Run(fmt.Sprintf("insertReplaceSupport=%v", supportInsertReplace), func(t *testing.T) {
661 capabilities := fmt.Sprintf(`{ "textDocument": { "completion": { "completionItem": {"insertReplaceSupport":%t, "snippetSupport": false } } } }`, supportInsertReplace)
662 runner := WithOptions(
663 CapabilitiesJSON([]byte(capabilities)),
664 )
665 runner.Run(t, src, func(t *testing.T, env *Env) {
666 env.OpenFile("main.go")
667 env.Await(env.DoneWithOpen())
668 orig := env.BufferText("main.go")
669
670 // We try to trigger completion at "println(strings.T<>Lower)"
671 // and accept the completion candidate that matches the 'accept' label.
672 insertModeWant := "println(strings.ToUpperLower)"
673 if !supportInsertReplace {
674 insertModeWant = "println(strings.ToUpper)"
675 }
676 testcases := []struct {
677 mode string
678 accept string
679 want string
680 }{
681 {
682 mode: "insert",
683 accept: "ToUpper",
684 want: insertModeWant,
685 },
686 {
687 mode: "insert",
688 accept: "ToLower",
689 want: "println(strings.ToLower)", // The suffix 'Lower' is included in the text edit.
690 },
691 {
692 mode: "replace",
693 accept: "ToUpper",
694 want: "println(strings.ToUpper)",
695 },
696 {
697 mode: "replace",
698 accept: "ToLower",
699 want: "println(strings.ToLower)",
700 },
701 }
702
703 for _, tc := range testcases {
704 t.Logf("mode=%q accept=%q", tc.mode, tc.accept)
705 env.SetSuggestionInsertReplaceMode(tc.mode == "replace")
706 env.SetBufferContent("main.go", orig)
707 loc := env.RegexpSearch("main.go", `()Lower\)`)
708 completions := env.Completion(loc)
709 item := find(t, completions, tc.accept)
710 env.AcceptCompletion(loc, item)
711 got := env.BufferText("main.go")
712 if !strings.Contains(got, tc.want) {
713 t.Errorf("unexpected state after completion:\n%v\nwanted %v", got, tc.want)
714 }
715 }
716 })
717 })
718 }
719 }
720 func TestUnimportedCompletionHasPlaceholders60269(t *testing.T) {
721 // We can't express this as a marker test because it doesn't support AcceptCompletion.
722 const src = `
723 -- go.mod --
724 module example.com
725 go 1.12
726
727 -- a/a.go --
728 package a
729
730 var _ = b.F
731
732 -- b/b.go --
733 package b
734
735 func F0(a, b int, c float64) {}
736 func F1(int, chan *string) {}
737 func F2[K, V any](map[K]V, chan V) {} // missing type parameters was issue #60959
738 func F3[K comparable, V any](map[K]V, chan V) {}
739 `
740 WithOptions(
741 WindowsLineEndings(),
742 Settings{"ui.completion.usePlaceholders": true},
743 ).Run(t, src, func(t *testing.T, env *Env) {
744 env.OpenFile("a/a.go")
745 env.Await(env.DoneWithOpen())
746
747 // The table lists the expected completions of b.F as they appear in Items.
748 const common = "package a\r\n\r\nimport \"example.com/b\"\r\n\r\nvar _ = "
749 for i, want := range []string{
750 common + "b.F0(${1:a int}, ${2:b int}, ${3:c float64})\r\n",
751 common + "b.F1(${1:_ int}, ${2:_ chan *string})\r\n",
752 common + "b.F2(${1:_ map[K]V}, ${2:_ chan V})\r\n",
753 common + "b.F3(${1:_ map[K]V}, ${2:_ chan V})\r\n",
754 } {
755 loc := env.RegexpSearch("a/a.go", "b.F()")
756 completions := env.Completion(loc)
757 if len(completions.Items) == 0 {
758 t.Fatalf("no completion items")
759 }
760 saved := env.BufferText("a/a.go")
761 env.AcceptCompletion(loc, completions.Items[i])
762 env.Await(env.DoneWithChange())
763 got := env.BufferText("a/a.go")
764 if diff := cmp.Diff(want, got); diff != "" {
765 t.Errorf("%d: unimported completion (-want +got):\n%s", i, diff)
766 }
767 env.SetBufferContent("a/a.go", saved) // restore
768 }
769 })
770 }
771
772 func TestCompleteAllFields(t *testing.T) {
773 // This test verifies that completion results always include all struct fields.
774 // See golang/go#53992.
775
776 const src = `
777 -- go.mod --
778 module mod.com
779
780 go 1.18
781
782 -- p/p.go --
783 package p
784
785 import (
786 "fmt"
787
788 . "net/http"
789 . "runtime"
790 . "go/types"
791 . "go/parser"
792 . "go/ast"
793 )
794
795 type S struct {
796 a, b, c, d, e, f, g, h, i, j, k, l, m int
797 n, o, p, q, r, s, t, u, v, w, x, y, z int
798 }
799
800 func _() {
801 var s S
802 fmt.Println(s.)
803 }
804 `
805
806 WithOptions(Settings{
807 "completionBudget": "1ns", // must be non-zero as 0 => infinity
808 }).Run(t, src, func(t *testing.T, env *Env) {
809 wantFields := make(map[string]bool)
810 for c := 'a'; c <= 'z'; c++ {
811 wantFields[string(c)] = true
812 }
813
814 env.OpenFile("p/p.go")
815 // Make an arbitrary edit to ensure we're not hitting the cache.
816 env.EditBuffer("p/p.go", fake.NewEdit(0, 0, 0, 0, fmt.Sprintf("// current time: %v\n", time.Now())))
817 loc := env.RegexpSearch("p/p.go", `s\.()`)
818 completions := env.Completion(loc)
819 gotFields := make(map[string]bool)
820 for _, item := range completions.Items {
821 if item.Kind == protocol.FieldCompletion {
822 gotFields[item.Label] = true
823 }
824 }
825
826 if diff := cmp.Diff(wantFields, gotFields); diff != "" {
827 t.Errorf("Completion(...) returned mismatching fields (-want +got):\n%s", diff)
828 }
829 })
830 }
831
832 func TestDefinition(t *testing.T) {
833 files := `
834 -- go.mod --
835 module mod.com
836
837 go 1.18
838 -- a_test.go --
839 package foo
840 `
841 tests := []struct {
842 line string // the sole line in the buffer after the package statement
843 pat string // the pattern to search for
844 want []string // expected completions
845 }{
846 {"func T", "T", []string{"TestXxx(t *testing.T)", "TestMain(m *testing.M)"}},
847 {"func T()", "T", []string{"TestMain", "Test"}},
848 {"func TestM", "TestM", []string{"TestMain(m *testing.M)", "TestM(t *testing.T)"}},
849 {"func TestM()", "TestM", []string{"TestMain"}},
850 {"func TestMi", "TestMi", []string{"TestMi(t *testing.T)"}},
851 {"func TestMi()", "TestMi", nil},
852 {"func TestG", "TestG", []string{"TestG(t *testing.T)"}},
853 {"func TestG(", "TestG", nil},
854 {"func Ben", "B", []string{"BenchmarkXxx(b *testing.B)"}},
855 {"func Ben(", "Ben", []string{"Benchmark"}},
856 {"func BenchmarkFoo", "BenchmarkFoo", []string{"BenchmarkFoo(b *testing.B)"}},
857 {"func BenchmarkFoo(", "BenchmarkFoo", nil},
858 {"func Fuz", "F", []string{"FuzzXxx(f *testing.F)"}},
859 {"func Fuz(", "Fuz", []string{"Fuzz"}},
860 {"func Testx", "Testx", nil},
861 {"func TestMe(t *testing.T)", "TestMe", nil},
862 {"func Te(t *testing.T)", "Te", []string{"TestMain", "Test"}},
863 }
864 fname := "a_test.go"
865 Run(t, files, func(t *testing.T, env *Env) {
866 env.OpenFile(fname)
867 env.Await(env.DoneWithOpen())
868 for _, test := range tests {
869 env.SetBufferContent(fname, "package foo\n"+test.line)
870 loc := env.RegexpSearch(fname, test.pat)
871 loc.Range.Start.Character += uint32(protocol.UTF16Len([]byte(test.pat)))
872 completions := env.Completion(loc)
873 if diff := compareCompletionLabels(test.want, completions.Items); diff != "" {
874 t.Error(diff)
875 }
876 }
877 })
878 }
879
880 // Test that completing a definition replaces source text when applied, golang/go#56852.
881 func TestDefinitionReplaceRange(t *testing.T) {
882 const mod = `
883 -- go.mod --
884 module mod.com
885
886 go 1.17
887 `
888
889 tests := []struct {
890 name string
891 before, after string
892 }{
893 {
894 name: "func TestMa",
895 before: `
896 package foo_test
897
898 func TestMa
899 `,
900 after: `
901 package foo_test
902
903 func TestMain(m *testing.M)
904 `,
905 },
906 {
907 name: "func TestSome",
908 before: `
909 package foo_test
910
911 func TestSome
912 `,
913 after: `
914 package foo_test
915
916 func TestSome(t *testing.T)
917 `,
918 },
919 {
920 name: "func Bench",
921 before: `
922 package foo_test
923
924 func Bench
925 `,
926 // Note: Snippet with escaped }.
927 after: `
928 package foo_test
929
930 func Benchmark${1:Xxx}(b *testing.B) {
931 $0
932 \}
933 `,
934 },
935 }
936
937 Run(t, mod, func(t *testing.T, env *Env) {
938 env.CreateBuffer("foo_test.go", "")
939
940 for _, tst := range tests {
941 tst.before = strings.Trim(tst.before, "\n")
942 tst.after = strings.Trim(tst.after, "\n")
943 env.SetBufferContent("foo_test.go", tst.before)
944
945 loc := env.RegexpSearch("foo_test.go", tst.name)
946 loc.Range.Start.Character = uint32(protocol.UTF16Len([]byte(tst.name)))
947 completions := env.Completion(loc)
948 if len(completions.Items) == 0 {
949 t.Fatalf("no completion items")
950 }
951
952 env.AcceptCompletion(loc, completions.Items[0])
953 env.Await(env.DoneWithChange())
954 if buf := env.BufferText("foo_test.go"); buf != tst.after {
955 t.Errorf("%s:incorrect completion: got %q, want %q", tst.name, buf, tst.after)
956 }
957 }
958 })
959 }
960
961 func TestGoWorkCompletion(t *testing.T) {
962 const files = `
963 -- go.work --
964 go 1.18
965
966 use ./a
967 use ./a/ba
968 use ./a/b/
969 use ./dir/foo
970 use ./dir/foobar/
971 use ./missing/
972 -- a/go.mod --
973 -- go.mod --
974 -- a/bar/go.mod --
975 -- a/b/c/d/e/f/go.mod --
976 -- dir/bar --
977 -- dir/foobar/go.mod --
978 `
979
980 Run(t, files, func(t *testing.T, env *Env) {
981 env.OpenFile("go.work")
982
983 tests := []struct {
984 re string
985 want []string
986 }{
987 {`use ()\.`, []string{".", "./a", "./a/bar", "./dir/foobar"}},
988 {`use \.()`, []string{"", "/a", "/a/bar", "/dir/foobar"}},
989 {`use \./()`, []string{"a", "a/bar", "dir/foobar"}},
990 {`use ./a()`, []string{"", "/b/c/d/e/f", "/bar"}},
991 {`use ./a/b()`, []string{"/c/d/e/f", "ar"}},
992 {`use ./a/b/()`, []string{`c/d/e/f`}},
993 {`use ./a/ba()`, []string{"r"}},
994 {`use ./dir/foo()`, []string{"bar"}},
995 {`use ./dir/foobar/()`, []string{}},
996 {`use ./missing/()`, []string{}},
997 }
998 for _, tt := range tests {
999 completions := env.Completion(env.RegexpSearch("go.work", tt.re))
1000 diff := compareCompletionLabels(tt.want, completions.Items)
1001 if diff != "" {
1002 t.Errorf("%s: %s", tt.re, diff)
1003 }
1004 }
1005 })
1006 }
1007
1008 const reverseInferenceSrcPrelude = `
1009 -- go.mod --
1010 module mod.com
1011
1012 go 1.18
1013 -- a.go --
1014 package a
1015
1016 type InterfaceA interface {
1017 implA()
1018 }
1019
1020 type InterfaceB interface {
1021 implB()
1022 }
1023
1024
1025 type TypeA struct{}
1026
1027 func (TypeA) implA() {}
1028
1029 type TypeX string
1030
1031 func (TypeX) implB() {}
1032
1033 type TypeB struct{}
1034
1035 func (TypeB) implB() {}
1036
1037 type TypeC struct{} // should have no impact
1038
1039 type Wrap[T any] struct {
1040 inner *T
1041 }
1042
1043 func NewWrap[T any](x T) Wrap[T] {
1044 return Wrap[T]{inner: &x}
1045 }
1046
1047 func DoubleWrap[T any, U any](t T, u U) (Wrap[T], Wrap[U]) {
1048 return Wrap[T]{inner: &t}, Wrap[U]{inner: &u}
1049 }
1050
1051 func IntWrap[T int32 | int64](x T) Wrap[T] {
1052 return Wrap[T]{inner: &x}
1053 }
1054
1055 var ia InterfaceA
1056 var ib InterfaceB
1057
1058 var avar TypeA
1059 var bvar TypeB
1060
1061 var i int
1062 var i32 int32
1063 var i64 int64
1064 `
1065
1066 func TestReverseInferCompletion(t *testing.T) {
1067 src := reverseInferenceSrcPrelude + `
1068 func main() {
1069 var _ Wrap[int64] = IntWrap()
1070 }
1071 `
1072 Run(t, src, func(t *testing.T, env *Env) {
1073 compl := env.RegexpSearch("a.go", `IntWrap\(()\)`)
1074
1075 env.OpenFile("a.go")
1076 result := env.Completion(compl)
1077
1078 wantLabel := []string{"i64", "i", "i32", "int64()"}
1079
1080 // only check the prefix due to formatting differences with escaped characters
1081 wantText := []string{"i64", "int64(i", "int64(i32", "int64("}
1082
1083 for i, item := range result.Items[:len(wantLabel)] {
1084 if diff := cmp.Diff(wantLabel[i], item.Label); diff != "" {
1085 t.Errorf("Completion: unexpected label mismatch (-want +got):\n%s", diff)
1086 }
1087
1088 if insertText, ok := item.TextEdit.Value.(protocol.InsertReplaceEdit); ok {
1089 if diff := cmp.Diff(wantText[i], insertText.NewText[:len(wantText[i])]); diff != "" {
1090 t.Errorf("Completion: unexpected insertText mismatch (checks prefix only) (-want +got):\n%s", diff)
1091 }
1092 }
1093 }
1094 })
1095 }
1096
1097 func TestInterfaceReverseInferCompletion(t *testing.T) {
1098 src := reverseInferenceSrcPrelude + `
1099 func main() {
1100 var wa Wrap[InterfaceA]
1101 var wb Wrap[InterfaceB]
1102 wb = NewWrap() // wb is of type Wrap[InterfaceB]
1103 }
1104 `
1105
1106 Run(t, src, func(t *testing.T, env *Env) {
1107 compl := env.RegexpSearch("a.go", `NewWrap\(()\)`)
1108
1109 env.OpenFile("a.go")
1110 result := env.Completion(compl)
1111
1112 wantLabel := []string{"ib", "bvar", "wb.inner", "TypeB{}", "TypeX()", "nil"}
1113
1114 // only check the prefix due to formatting differences with escaped characters
1115 wantText := []string{"ib", "InterfaceB(", "*wb.inner", "InterfaceB(", "InterfaceB(", "nil"}
1116
1117 for i, item := range result.Items[:len(wantLabel)] {
1118 if diff := cmp.Diff(wantLabel[i], item.Label); diff != "" {
1119 t.Errorf("Completion: unexpected label mismatch (-want +got):\n%s", diff)
1120 }
1121
1122 if insertText, ok := item.TextEdit.Value.(protocol.InsertReplaceEdit); ok {
1123 if diff := cmp.Diff(wantText[i], insertText.NewText[:len(wantText[i])]); diff != "" {
1124 t.Errorf("Completion: unexpected insertText mismatch (checks prefix only) (-want +got):\n%s", diff)
1125 }
1126 }
1127 }
1128 })
1129 }
1130
1131 func TestInvalidReverseInferenceDefaultsToConstraintCompletion(t *testing.T) {
1132 src := reverseInferenceSrcPrelude + `
1133 func main() {
1134 var wa Wrap[InterfaceA]
1135 // This is ambiguous, so default to the constraint rather the inference.
1136 wa = IntWrap()
1137 }
1138 `
1139 Run(t, src, func(t *testing.T, env *Env) {
1140 compl := env.RegexpSearch("a.go", `IntWrap\(()\)`)
1141
1142 env.OpenFile("a.go")
1143 result := env.Completion(compl)
1144
1145 wantLabel := []string{"i32", "i64", "nil"}
1146
1147 for i, item := range result.Items[:len(wantLabel)] {
1148 if diff := cmp.Diff(wantLabel[i], item.Label); diff != "" {
1149 t.Errorf("Completion: unexpected label mismatch (-want +got):\n%s", diff)
1150 }
1151 }
1152 })
1153 }
1154
1155 func TestInterfaceReverseInferTypeParamCompletion(t *testing.T) {
1156 src := reverseInferenceSrcPrelude + `
1157 func main() {
1158 var wa Wrap[InterfaceA]
1159 var wb Wrap[InterfaceB]
1160 wb = NewWrap[]()
1161 }
1162 `
1163
1164 Run(t, src, func(t *testing.T, env *Env) {
1165 compl := env.RegexpSearch("a.go", `NewWrap\[()\]\(\)`)
1166
1167 env.OpenFile("a.go")
1168 result := env.Completion(compl)
1169 want := []string{"InterfaceB", "TypeB", "TypeX", "InterfaceA", "TypeA"}
1170 for i, item := range result.Items[:len(want)] {
1171 if diff := cmp.Diff(want[i], item.Label); diff != "" {
1172 t.Errorf("Completion: unexpected mismatch (-want +got):\n%s", diff)
1173 }
1174 }
1175 })
1176 }
1177
1178 func TestInvalidReverseInferenceTypeParamDefaultsToConstraintCompletion(t *testing.T) {
1179 src := reverseInferenceSrcPrelude + `
1180 func main() {
1181 var wa Wrap[InterfaceA]
1182 // This is ambiguous, so default to the constraint rather the inference.
1183 wb = IntWrap[]()
1184 }
1185 `
1186
1187 Run(t, src, func(t *testing.T, env *Env) {
1188 compl := env.RegexpSearch("a.go", `IntWrap\[()\]\(\)`)
1189
1190 env.OpenFile("a.go")
1191 result := env.Completion(compl)
1192 want := []string{"int32", "int64"}
1193 for i, item := range result.Items[:len(want)] {
1194 if diff := cmp.Diff(want[i], item.Label); diff != "" {
1195 t.Errorf("Completion: unexpected mismatch (-want +got):\n%s", diff)
1196 }
1197 }
1198 })
1199 }
1200
1201 func TestReverseInferDoubleTypeParamCompletion(t *testing.T) {
1202 src := reverseInferenceSrcPrelude + `
1203 func main() {
1204 var wa Wrap[InterfaceA]
1205 var wb Wrap[InterfaceB]
1206
1207 wa, wb = DoubleWrap[]()
1208 // _ is necessary to trick the parser into an index list expression
1209 wa, wb = DoubleWrap[InterfaceA, _]()
1210 }
1211 `
1212 Run(t, src, func(t *testing.T, env *Env) {
1213 env.OpenFile("a.go")
1214
1215 compl := env.RegexpSearch("a.go", `DoubleWrap\[()\]\(\)`)
1216 result := env.Completion(compl)
1217
1218 wantLabel := []string{"InterfaceA", "TypeA", "InterfaceB", "TypeB", "TypeC"}
1219
1220 for i, item := range result.Items[:len(wantLabel)] {
1221 if diff := cmp.Diff(wantLabel[i], item.Label); diff != "" {
1222 t.Errorf("Completion: unexpected label mismatch (-want +got):\n%s", diff)
1223 }
1224 }
1225
1226 compl = env.RegexpSearch("a.go", `DoubleWrap\[InterfaceA, ()_\]\(\)`)
1227 result = env.Completion(compl)
1228
1229 wantLabel = []string{"InterfaceB", "TypeB", "TypeX", "InterfaceA", "TypeA"}
1230
1231 for i, item := range result.Items[:len(wantLabel)] {
1232 if diff := cmp.Diff(wantLabel[i], item.Label); diff != "" {
1233 t.Errorf("Completion: unexpected label mismatch (-want +got):\n%s", diff)
1234 }
1235 }
1236 })
1237 }
1238
1239 func TestDoubleParamReturnCompletion(t *testing.T) {
1240 src := reverseInferenceSrcPrelude + `
1241 func concrete() (Wrap[InterfaceA], Wrap[InterfaceB]) {
1242 return DoubleWrap[]()
1243 }
1244
1245 func concrete2() (Wrap[InterfaceA], Wrap[InterfaceB]) {
1246 return DoubleWrap[InterfaceA, _]()
1247 }
1248 `
1249
1250 Run(t, src, func(t *testing.T, env *Env) {
1251 env.OpenFile("a.go")
1252
1253 tests := map[string][]string{
1254 `DoubleWrap\[()\]\(\)`: {"InterfaceA", "TypeA", "InterfaceB", "TypeB", "TypeC"},
1255 `DoubleWrap\[InterfaceA, ()\_\]\(\)`: {"InterfaceB", "TypeB", "TypeX", "InterfaceA", "TypeA"},
1256 }
1257
1258 for re, wantLabels := range tests {
1259 compl := env.RegexpSearch("a.go", re)
1260 result := env.Completion(compl)
1261 if len(result.Items) < len(wantLabels) {
1262 t.Fatalf("Completion(%q) returned mismatching labels: got %v, want at least labels %v", re, result.Items, wantLabels)
1263 }
1264 for i, item := range result.Items[:len(wantLabels)] {
1265 if diff := cmp.Diff(wantLabels[i], item.Label); diff != "" {
1266 t.Errorf("Completion(%q): unexpected label mismatch (-want +got):\n%s", re, diff)
1267 }
1268 }
1269 }
1270 })
1271 }
1272
1273 func TestBuiltinCompletion(t *testing.T) {
1274 const files = `
1275 -- go.mod --
1276 module mod.com
1277
1278 go 1.18
1279 -- a.go --
1280 package a
1281
1282 func _() {
1283 // here
1284 }
1285 `
1286
1287 Run(t, files, func(t *testing.T, env *Env) {
1288 env.OpenFile("a.go")
1289 result := env.Completion(env.RegexpSearch("a.go", `()\/\/ here`))
1290 builtins := []string{
1291 "any", "append", "bool", "byte", "cap", "close",
1292 "comparable", "complex", "complex128", "complex64", "copy", "delete",
1293 "error", "false", "float32", "float64", "imag", "int", "int16", "int32",
1294 "int64", "int8", "len", "make", "new", "panic", "print", "println", "real",
1295 "recover", "rune", "string", "true", "uint", "uint16", "uint32", "uint64",
1296 "uint8", "uintptr", "nil",
1297 }
1298 if testenv.Go1Point() >= 21 {
1299 builtins = append(builtins, "clear", "max", "min")
1300 }
1301 sort.Strings(builtins)
1302 var got []string
1303
1304 for _, item := range result.Items {
1305 // TODO(rfindley): for flexibility, ignore zero while it is being
1306 // implemented. Remove this if/when zero lands.
1307 if item.Label != "zero" {
1308 got = append(got, item.Label)
1309 }
1310 }
1311 sort.Strings(got)
1312
1313 if diff := cmp.Diff(builtins, got); diff != "" {
1314 t.Errorf("Completion: unexpected mismatch (-want +got):\n%s", diff)
1315 }
1316 })
1317 }
1318
1319 func TestOverlayCompletion(t *testing.T) {
1320 const files = `
1321 -- go.mod --
1322 module foo.test
1323
1324 go 1.18
1325
1326 -- foo/foo.go --
1327 package foo
1328
1329 type Foo struct{}
1330 `
1331
1332 Run(t, files, func(t *testing.T, env *Env) {
1333 env.CreateBuffer("nodisk/nodisk.go", `
1334 package nodisk
1335
1336 import (
1337 "foo.test/foo"
1338 )
1339
1340 func _() {
1341 foo.Foo()
1342 }
1343 `)
1344 list := env.Completion(env.RegexpSearch("nodisk/nodisk.go", "foo.()Foo"))
1345 want := []string{"Foo"}
1346 var got []string
1347 for _, item := range list.Items {
1348 got = append(got, item.Label)
1349 }
1350 if diff := cmp.Diff(want, got); diff != "" {
1351 t.Errorf("Completion: unexpected mismatch (-want +got):\n%s", diff)
1352 }
1353 })
1354 }
1355
1356 // Fix for golang/go#60062: unimported completion included "golang.org/toolchain" results.
1357 // and check that functions (from the standard library) have snippets
1358 func TestToolchainCompletions(t *testing.T) {
1359 const files = `
1360 -- go.mod --
1361 module foo.test/foo
1362
1363 go 1.21
1364
1365 -- foo.go --
1366 package foo
1367
1368 func _() {
1369 os.Open
1370 }
1371
1372 func _() {
1373 strings
1374 }
1375 `
1376
1377 const proxy = `
1378 -- golang.org/[email protected]/go.mod --
1379 module golang.org/toolchain
1380 -- golang.org/[email protected]/src/os/os.go --
1381 package os
1382
1383 func Open() {}
1384 -- golang.org/[email protected]/src/strings/strings.go --
1385 package strings
1386
1387 func Join() {}
1388 `
1389
1390 WithOptions(
1391 ProxyFiles(proxy),
1392 ).Run(t, files, func(t *testing.T, env *Env) {
1393 env.RunGoCommand("mod", "download", "golang.org/[email protected]")
1394 env.OpenFile("foo.go")
1395
1396 for _, pattern := range []string{"os.Open()", "string()"} {
1397 loc := env.RegexpSearch("foo.go", pattern)
1398 res := env.Completion(loc)
1399 for _, item := range res.Items {
1400 if strings.Contains(item.Detail, "golang.org/toolchain") {
1401 t.Errorf("Completion(...) returned toolchain item %#v", item)
1402 }
1403 if strings.HasPrefix(item.Detail, "func") {
1404 // check that there are snippets
1405 x, ok := item.TextEdit.Value.(protocol.InsertReplaceEdit)
1406 if !ok {
1407 t.Errorf("item.TextEdit.Value unexpected type %T", item.TextEdit.Value)
1408 }
1409 if !strings.Contains(x.NewText, "${1") {
1410 t.Errorf("expected snippet in %q", x.NewText)
1411 }
1412 }
1413 }
1414 }
1415 })
1416 }
1417
1418 // when completing using the module cache, prefer things mentioned
1419 // in the go.mod file.
1420 func TestIssue61208(t *testing.T) {
1421
1422 const cache = `
1423 -- [email protected]/go.mod --
1424 module example.com
1425
1426 go 1.22
1427 -- [email protected]/blah/blah.go --
1428 package blah
1429
1430 const Name = "Blah"
1431 -- [email protected]/go.mod --
1432 module random.org
1433
1434 go 1.22
1435 -- [email protected]/blah/blah.go --
1436 package blah
1437
1438 const Name = "Hello"
1439 `
1440 const files = `
1441 -- go.mod --
1442 module mod.com
1443 go 1.22
1444 require random.org v1.2.3
1445 -- main.go --
1446 package main
1447 var _ = blah.
1448 `
1449 modcache := t.TempDir()
1450 defer CleanModCache(t, modcache)
1451 mx := fake.UnpackTxt(cache)
1452 for k, v := range mx {
1453 fname := filepath.Join(modcache, k)
1454 dir := filepath.Dir(fname)
1455 os.MkdirAll(dir, 0777) // ignore error
1456 if err := os.WriteFile(fname, v, 0644); err != nil {
1457 t.Fatal(err)
1458 }
1459 }
1460
1461 WithOptions(
1462 EnvVars{"GOMODCACHE": modcache},
1463 WriteGoSum("."),
1464 NoLogsOnError(),
1465 ).Run(t, files, func(t *testing.T, env *Env) {
1466 env.OpenFile("main.go")
1467 env.Await(env.DoneWithOpen())
1468 loc := env.RegexpSearch("main.go", "blah.()")
1469 completions := env.Completion(loc)
1470 if len(completions.Items) != 1 {
1471 t.Errorf("got %d, expected 1", len(completions.Items))
1472 for _, x := range completions.Items {
1473 t.Logf("%#v", x.AdditionalTextEdits[0].NewText)
1474 }
1475 }
1476 if got := completions.Items[0].AdditionalTextEdits[0].NewText; !strings.Contains(got, `"random.org`) {
1477 t.Errorf("got %q, expected a `random.org`", got)
1478 }
1479 })
1480 }
1481
1482 // show that the efficacy counters get exercised. Fortunately a small program
1483 // exercises them all
1484 func TestCounters(t *testing.T) {
1485 const files = `
1486 -- go.mod --
1487 module foo
1488 go 1.21
1489 -- x.go --
1490 package foo
1491
1492 func main() {
1493 }
1494
1495 `
1496 WithOptions(
1497 Modes(Default),
1498 ).Run(t, files, func(t *testing.T, env *Env) {
1499 cts := func() map[*counter.Counter]uint64 {
1500 ans := make(map[*counter.Counter]uint64)
1501 for _, c := range server.CompletionCounters {
1502 ans[c], _ = countertest.ReadCounter(c)
1503 }
1504 return ans
1505 }
1506 before := cts()
1507 env.OpenFile("x.go")
1508 env.Await(env.DoneWithOpen())
1509 saved := env.BufferText("x.go")
1510 lines := strings.Split(saved, "\n")
1511 // make sure the unused counter is exercised
1512 loc := env.RegexpSearch("x.go", "main")
1513 loc.Range.End = loc.Range.Start
1514 env.Completion(loc) // ignore the proposed completions
1515 env.RegexpReplace("x.go", "main", "Main") // completions are unused
1516 env.SetBufferContent("x.go", saved) // restore x.go
1517 // used:no
1518
1519 // all the action is after 4 characters on line 2 (counting from 0)
1520 for i := 2; i < len(lines); i++ {
1521 l := lines[i]
1522 loc.Range.Start.Line = uint32(i)
1523 for j := 4; j < len(l); j++ {
1524 loc.Range.Start.Character = uint32(j)
1525 loc.Range.End = loc.Range.Start
1526 res := env.Completion(loc)
1527 if len(res.Items) > 0 {
1528 r := res.Items[0]
1529 env.AcceptCompletion(loc, r)
1530 env.SetBufferContent("x.go", saved)
1531 }
1532 }
1533 }
1534 after := cts()
1535 for c := range after {
1536 if after[c] <= before[c] {
1537 t.Errorf("%s did not increase", c.Name())
1538 }
1539 }
1540 })
1541 }
1542
1543 // find import foo "bar" for foo.xxx
1544 func TestImportAlias(t *testing.T) {
1545 testenv.NeedsGoCommand1Point(t, 24) // we will find math/rand/v2
1546 const files = `
1547 -- a.go --
1548 package x
1549 var _ = xrand.
1550 -- b.go --
1551 package x
1552
1553 import xrand "math/rand"
1554
1555 var _ = xrand.Int()
1556
1557 -- go.mod --
1558 module foo.com
1559
1560 go 1.24.2
1561 `
1562 Run(t, files, func(t *testing.T, env *Env) {
1563 env.OpenFile("a.go")
1564 env.Await(env.DoneWithOpen())
1565 loc := env.RegexpSearch("a.go", "xrand.()")
1566 compls := env.Completion(loc)
1567 if len(compls.Items) == 0 {
1568 t.Fatal("no completions")
1569 }
1570 one := compls.Items[0].AdditionalTextEdits[0].NewText
1571 if one != "\nimport xrand \"math/rand\"\n" {
1572 t.Errorf("wrong import %q", one)
1573 }
1574 })
1575 }
1576
1577 func TestModIndexDirEmpty(t *testing.T) {
1578 // Test for issue #75505. Do not run this test in parallel.
1579 // Test that if modindex.IndexDir is empty, we still get stdlib completions
1580 // but not unimported completions from modules.
1581
1582 // Save/restore IndexDir, and set it to empty string.
1583 // This simulates having no module cache.
1584 old := modindex.IndexDir
1585 modindex.IndexDir = ""
1586 defer func() { modindex.IndexDir = old }()
1587 // for the paranoid, with modindex.IndexDir = old here, the test fails
1588
1589 const mod = `
1590 -- go.mod --
1591 module mod.com
1592 go 1.22
1593 require example.com v1.2.3
1594 -- main.go --
1595 package main
1596 func main() {
1597 _ = fmt.P
1598 _ = blah.N
1599 }
1600 -- main2.go --
1601 package main
1602 import "example.com/blah"
1603 func _() {
1604 _ = blah.Hello
1605 }
1606 `
1607 WithOptions(
1608 WriteGoSum("."),
1609 ProxyFiles(proxy), // providing example.com through GOPROXY to the go command
1610 ).Run(t, mod, func(t *testing.T, env *Env) {
1611 // We need example.com in the module cache, but not
1612 // otherwise available to the completion logic.
1613 env.RemoveWorkspaceFile("main2.go")
1614 env.RunGoCommand("mod", "tidy")
1615 env.Await(env.DoneWithChangeWatchedFiles())
1616
1617 env.OpenFile("main.go")
1618 env.Await(env.DoneWithOpen())
1619
1620 // 1. Check stdlib completion (should work)
1621 loc := env.RegexpSearch("main.go", "fmt.P()")
1622 completions := env.Completion(loc)
1623 if len(completions.Items) == 0 {
1624 t.Errorf("stdlib completion failed to find fmt.Print...")
1625 }
1626
1627 // 2. Check unimported completion (should fail)
1628 // We look for "blah.H" which is from example.com
1629 loc = env.RegexpSearch("main.go", "blah.N()")
1630 completions = env.Completion(loc)
1631
1632 // We expect NO unimported completions for blah.Name because modindex is disabled.
1633 for _, item := range completions.Items {
1634 // We shouldn't get candidate from example.com/blah.
1635 if strings.Contains(item.Detail, "example.com/blah") {
1636 t.Errorf("unexpected unimported completion for blah with empty IndexDir: %v", item)
1637 }
1638 }
1639 })
1640 }