|
| 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 source |
| 6 | + |
| 7 | +import ( |
| 8 | + "context" |
| 9 | + "fmt" |
| 10 | + "go/ast" |
| 11 | + "go/types" |
| 12 | + "path/filepath" |
| 13 | + "strings" |
| 14 | + |
| 15 | + "golang.org/x/tools/internal/lsp/fuzzy" |
| 16 | + "golang.org/x/tools/internal/lsp/protocol" |
| 17 | + "golang.org/x/tools/internal/span" |
| 18 | + errors "golang.org/x/xerrors" |
| 19 | +) |
| 20 | + |
| 21 | +// packageClauseCompletions offers completions for a package declaration when |
| 22 | +// one is not present in the given file. |
| 23 | +func packageClauseCompletions(ctx context.Context, snapshot Snapshot, fh FileHandle, pos protocol.Position) ([]CompletionItem, *Selection, error) { |
| 24 | + // We know that the AST for this file will be empty due to the missing |
| 25 | + // package declaration, but parse it anyway to get a mapper. |
| 26 | + pgf, err := snapshot.ParseGo(ctx, fh, ParseHeader) |
| 27 | + if err != nil { |
| 28 | + return nil, nil, err |
| 29 | + } |
| 30 | + |
| 31 | + // Check that the file is completely empty, to avoid offering incorrect package |
| 32 | + // clause completions. |
| 33 | + // TODO: Support package clause completions in all files. |
| 34 | + if pgf.Tok.Size() != 0 { |
| 35 | + return nil, nil, errors.New("package clause completion is only offered for empty file") |
| 36 | + } |
| 37 | + |
| 38 | + cursorSpan, err := pgf.Mapper.PointSpan(pos) |
| 39 | + if err != nil { |
| 40 | + return nil, nil, err |
| 41 | + } |
| 42 | + rng, err := cursorSpan.Range(pgf.Mapper.Converter) |
| 43 | + if err != nil { |
| 44 | + return nil, nil, err |
| 45 | + } |
| 46 | + |
| 47 | + surrounding := &Selection{ |
| 48 | + content: "", |
| 49 | + cursor: rng.Start, |
| 50 | + mappedRange: newMappedRange(snapshot.FileSet(), pgf.Mapper, rng.Start, rng.Start), |
| 51 | + } |
| 52 | + |
| 53 | + packageSuggestions, err := packageSuggestions(ctx, snapshot, fh.URI(), "") |
| 54 | + if err != nil { |
| 55 | + return nil, nil, err |
| 56 | + } |
| 57 | + |
| 58 | + var items []CompletionItem |
| 59 | + for _, pkg := range packageSuggestions { |
| 60 | + insertText := fmt.Sprintf("package %s", pkg.name) |
| 61 | + items = append(items, CompletionItem{ |
| 62 | + Label: insertText, |
| 63 | + Kind: protocol.ModuleCompletion, |
| 64 | + InsertText: insertText, |
| 65 | + Score: pkg.score, |
| 66 | + }) |
| 67 | + } |
| 68 | + |
| 69 | + return items, surrounding, nil |
| 70 | +} |
| 71 | + |
| 72 | +// packageNameCompletions returns name completions for a package clause using |
| 73 | +// the current name as prefix. |
| 74 | +func (c *completer) packageNameCompletions(ctx context.Context, fileURI span.URI, name *ast.Ident) error { |
| 75 | + cursor := int(c.pos - name.NamePos) |
| 76 | + if cursor < 0 || cursor > len(name.Name) { |
| 77 | + return errors.New("cursor is not in package name identifier") |
| 78 | + } |
| 79 | + |
| 80 | + prefix := name.Name[:cursor] |
| 81 | + packageSuggestions, err := packageSuggestions(ctx, c.snapshot, fileURI, prefix) |
| 82 | + if err != nil { |
| 83 | + return err |
| 84 | + } |
| 85 | + |
| 86 | + for _, pkg := range packageSuggestions { |
| 87 | + if item, err := c.item(ctx, pkg); err == nil { |
| 88 | + c.items = append(c.items, item) |
| 89 | + } |
| 90 | + } |
| 91 | + return nil |
| 92 | +} |
| 93 | + |
| 94 | +// packageSuggestions returns a list of packages from workspace packages that |
| 95 | +// have the given prefix and are used in the the same directory as the given |
| 96 | +// file. This also includes test packages for these packages (<pkg>_test) and |
| 97 | +// the directory name itself. |
| 98 | +func packageSuggestions(ctx context.Context, snapshot Snapshot, fileURI span.URI, prefix string) ([]candidate, error) { |
| 99 | + workspacePackages, err := snapshot.WorkspacePackages(ctx) |
| 100 | + if err != nil { |
| 101 | + return nil, err |
| 102 | + } |
| 103 | + |
| 104 | + dirPath := filepath.Dir(string(fileURI)) |
| 105 | + dirName := filepath.Base(dirPath) |
| 106 | + |
| 107 | + seenPkgs := make(map[string]struct{}) |
| 108 | + |
| 109 | + toCandidate := func(name string, score float64) candidate { |
| 110 | + obj := types.NewPkgName(0, nil, name, types.NewPackage("", name)) |
| 111 | + return candidate{obj: obj, name: name, score: score} |
| 112 | + } |
| 113 | + |
| 114 | + matcher := fuzzy.NewMatcher(prefix) |
| 115 | + |
| 116 | + // The `go` command by default only allows one package per directory but we |
| 117 | + // support multiple package suggestions since gopls is build system agnostic. |
| 118 | + var packages []candidate |
| 119 | + for _, pkg := range workspacePackages { |
| 120 | + if pkg.Name() == "main" { |
| 121 | + continue |
| 122 | + } |
| 123 | + if _, ok := seenPkgs[pkg.Name()]; ok { |
| 124 | + continue |
| 125 | + } |
| 126 | + |
| 127 | + // Only add packages that are previously used in the current directory. |
| 128 | + var relevantPkg bool |
| 129 | + for _, pgf := range pkg.CompiledGoFiles() { |
| 130 | + if filepath.Dir(string(pgf.URI)) == dirPath { |
| 131 | + relevantPkg = true |
| 132 | + break |
| 133 | + } |
| 134 | + } |
| 135 | + if !relevantPkg { |
| 136 | + continue |
| 137 | + } |
| 138 | + |
| 139 | + // Add a found package used in current directory as a high relevance |
| 140 | + // suggestion and the test package for it as a medium relevance |
| 141 | + // suggestion. |
| 142 | + if score := float64(matcher.Score(pkg.Name())); score > 0 { |
| 143 | + packages = append(packages, toCandidate(pkg.Name(), score*highScore)) |
| 144 | + } |
| 145 | + seenPkgs[pkg.Name()] = struct{}{} |
| 146 | + |
| 147 | + testPkgName := pkg.Name() + "_test" |
| 148 | + if _, ok := seenPkgs[testPkgName]; ok || strings.HasSuffix(pkg.Name(), "_test") { |
| 149 | + continue |
| 150 | + } |
| 151 | + if score := float64(matcher.Score(testPkgName)); score > 0 { |
| 152 | + packages = append(packages, toCandidate(testPkgName, score*stdScore)) |
| 153 | + } |
| 154 | + seenPkgs[testPkgName] = struct{}{} |
| 155 | + } |
| 156 | + |
| 157 | + // Add current directory name as a low relevance suggestion. |
| 158 | + if _, ok := seenPkgs[dirName]; !ok { |
| 159 | + if score := float64(matcher.Score(dirName)); score > 0 { |
| 160 | + packages = append(packages, toCandidate(dirName, score*lowScore)) |
| 161 | + } |
| 162 | + |
| 163 | + testDirName := dirName + "_test" |
| 164 | + if score := float64(matcher.Score(testDirName)); score > 0 { |
| 165 | + packages = append(packages, toCandidate(testDirName, score*lowScore)) |
| 166 | + } |
| 167 | + } |
| 168 | + |
| 169 | + if score := float64(matcher.Score("main")); score > 0 { |
| 170 | + packages = append(packages, toCandidate("main", score*lowScore)) |
| 171 | + } |
| 172 | + |
| 173 | + return packages, nil |
| 174 | +} |
0 commit comments