Debian Codegraph @

gopls/internal/golang/completion/package.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 "bytes"
9 "context"
10 "errors"
11 "fmt"
12 "go/ast"
13 "go/parser"
14 "go/scanner"
15 "go/token"
16 "go/types"
17 "path/filepath"
18 "sort"
19 "strings"
20 "unicode"
21
22 "golang.org/x/tools/gopls/internal/cache"
23 "golang.org/x/tools/gopls/internal/cache/parsego"
24 "golang.org/x/tools/gopls/internal/file"
25 "golang.org/x/tools/gopls/internal/fuzzy"
26 "golang.org/x/tools/gopls/internal/golang"
27 "golang.org/x/tools/gopls/internal/protocol"
28 "golang.org/x/tools/gopls/internal/util/safetoken"
29 )
30
31 // bestPackage offers the best package name for a package declaration when
32 // one is not present in the given file.
33 func bestPackage(ctx context.Context, snapshot *cache.Snapshot, uri protocol.DocumentURI) (string, error) {
34 suggestions, err := packageSuggestions(ctx, snapshot, uri, "")
35 if err != nil {
36 return "", err
37 }
38 // sort with the same way of sortItems.
39 sort.SliceStable(suggestions, func(i, j int) bool {
40 if suggestions[i].score != suggestions[j].score {
41 return suggestions[i].score > suggestions[j].score
42 }
43 return suggestions[i].name < suggestions[j].name
44 })
45
46 return suggestions[0].name, nil
47 }
48
49 // packageClauseCompletions offers completions for a package declaration when
50 // one is not present in the given file.
51 func packageClauseCompletions(ctx context.Context, snapshot *cache.Snapshot, fh file.Handle, position protocol.Position) ([]CompletionItem, *Selection, error) {
52 // We know that the AST for this file will be empty due to the missing
53 // package declaration, but parse it anyway to get a mapper.
54 // TODO(adonovan): opt: there's no need to parse just to get a mapper.
55 pgf, err := snapshot.ParseGo(ctx, fh, parsego.Full)
56 if err != nil {
57 return nil, nil, err
58 }
59
60 offset, err := pgf.Mapper.PositionOffset(position)
61 if err != nil {
62 return nil, nil, err
63 }
64 surrounding, err := packageCompletionSurrounding(pgf, offset)
65 if err != nil {
66 return nil, nil, fmt.Errorf("invalid position for package completion: %w", err)
67 }
68
69 packageSuggestions, err := packageSuggestions(ctx, snapshot, fh.URI(), "")
70 if err != nil {
71 return nil, nil, err
72 }
73
74 var items []CompletionItem
75 for _, pkg := range packageSuggestions {
76 insertText := fmt.Sprintf("package %s", pkg.name)
77 items = append(items, CompletionItem{
78 Label: insertText,
79 Kind: protocol.ModuleCompletion,
80 InsertText: insertText,
81 Score: pkg.score,
82 })
83 }
84 sortItems(items)
85 return items, surrounding, nil
86 }
87
88 // packageCompletionSurrounding returns surrounding for package completion if a
89 // package completions can be suggested at a given cursor offset. A valid location
90 // for package completion is above any declarations or import statements.
91 func packageCompletionSurrounding(pgf *parsego.File, offset int) (*Selection, error) {
92 m := pgf.Mapper
93 // If the file lacks a package declaration, the parser will return an empty
94 // AST. As a work-around, try to parse an expression from the file contents.
95 fset := token.NewFileSet()
96 expr, _ := parser.ParseExprFrom(fset, m.URI.Path(), pgf.Src, parser.Mode(0))
97 if expr == nil {
98 return nil, fmt.Errorf("unparsable file (%s)", m.URI)
99 }
100 tok := fset.File(expr.Pos())
101 cursor := tok.Pos(offset)
102
103 // If we were able to parse out an identifier as the first expression from
104 // the file, it may be the beginning of a package declaration ("pack ").
105 // We can offer package completions if the cursor is in the identifier.
106 if name, ok := expr.(*ast.Ident); ok {
107 if cursor >= name.Pos() && cursor <= name.End() {
108 if !strings.HasPrefix(PACKAGE, name.Name) {
109 return nil, fmt.Errorf("cursor in non-matching ident")
110 }
111 sel := &Selection{
112 content: name.Name,
113 cursor: cursor,
114 tokFile: tok,
115 start: name.Pos(),
116 end: name.End(),
117 mapper: m,
118 }
119 sel.check()
120 return sel, nil
121 }
122 }
123
124 // The file is invalid, but it contains an expression that we were able to
125 // parse. We will use this expression to construct the cursor's
126 // "surrounding".
127
128 // First, consider the possibility that we have a valid "package" keyword
129 // with an empty package name ("package "). "package" is parsed as an
130 // *ast.BadDecl since it is a keyword.
131 start, err := safetoken.Offset(tok, expr.Pos())
132 if err != nil {
133 return nil, err
134 }
135 if offset > start && string(bytes.TrimRight(pgf.Src[start:offset], " ")) == PACKAGE {
136 sel := &Selection{
137 content: string(pgf.Src[start:offset]),
138 cursor: cursor,
139 tokFile: tok,
140 start: expr.Pos(),
141 end: cursor,
142 mapper: m,
143 }
144 sel.check()
145 return sel, nil
146 }
147
148 // If the cursor is after the start of the expression, no package
149 // declaration will be valid.
150 if cursor > expr.Pos() {
151 return nil, fmt.Errorf("cursor after expression")
152 }
153
154 // If the cursor is in a comment, don't offer any completions.
155 if cursorInComment(tok, cursor, m.Content) {
156 return nil, fmt.Errorf("cursor in comment")
157 }
158
159 // The surrounding range in this case is the cursor.
160 sel := &Selection{
161 content: "",
162 tokFile: tok,
163 start: cursor,
164 end: cursor,
165 cursor: cursor,
166 mapper: m,
167 }
168 sel.check()
169 return sel, nil
170 }
171
172 func cursorInComment(file *token.File, cursor token.Pos, src []byte) bool {
173 var s scanner.Scanner
174 s.Init(file, src, func(_ token.Position, _ string) {}, scanner.ScanComments)
175 for {
176 pos, tok, lit := s.Scan()
177 if pos <= cursor && cursor <= token.Pos(int(pos)+len(lit)) {
178 return tok == token.COMMENT
179 }
180 if tok == token.EOF {
181 break
182 }
183 }
184 return false
185 }
186
187 // packageNameCompletions returns name completions for a package clause using
188 // the current name as prefix.
189 func (c *completer) packageNameCompletions(ctx context.Context, fileURI protocol.DocumentURI, name *ast.Ident) error {
190 cursor := int(c.pos - name.NamePos)
191 if cursor < 0 || cursor > len(name.Name) {
192 return errors.New("cursor is not in package name identifier")
193 }
194
195 c.completionContext.packageCompletion = true
196
197 prefix := name.Name[:cursor]
198 packageSuggestions, err := packageSuggestions(ctx, c.snapshot, fileURI, prefix)
199 if err != nil {
200 return err
201 }
202
203 for _, pkg := range packageSuggestions {
204 c.deepState.enqueue(pkg)
205 }
206 return nil
207 }
208
209 // packageSuggestions returns a list of packages from workspace packages that
210 // have the given prefix and are used in the same directory as the given
211 // file. This also includes test packages for these packages (<pkg>_test) and
212 // the directory name itself.
213 func packageSuggestions(ctx context.Context, snapshot *cache.Snapshot, fileURI protocol.DocumentURI, prefix string) (packages []candidate, err error) {
214 active, err := snapshot.WorkspaceMetadata(ctx)
215 if err != nil {
216 return nil, err
217 }
218
219 toCandidate := func(name string, score float64) candidate {
220 obj := types.NewPkgName(0, nil, name, types.NewPackage("", name))
221 return candidate{obj: obj, name: name, detail: name, score: score}
222 }
223
224 var currentPackageName string
225 // TODO: consider propagating error.
226 if md, err := snapshot.NarrowestMetadataForFile(ctx, fileURI); err == nil {
227 currentPackageName = string(md.Name)
228 }
229
230 matcher := fuzzy.NewMatcher(prefix)
231
232 // Always try to suggest a main package
233 defer func() {
234 mainScore := lowScore
235 if currentPackageName == "main" {
236 mainScore = highScore
237 }
238 if score := float64(matcher.Score("main")); score > 0 {
239 packages = append(packages, toCandidate("main", score*mainScore))
240 }
241 }()
242
243 dirPath := fileURI.DirPath()
244 dirName := filepath.Base(dirPath)
245 if !isValidDirName(dirName) {
246 return packages, nil
247 }
248 pkgName := convertDirNameToPkgName(dirName)
249
250 seenPkgs := make(map[golang.PackageName]struct{})
251
252 // The `go` command by default only allows one package per directory but we
253 // support multiple package suggestions since gopls is build system agnostic.
254 for _, mp := range active {
255 if mp.Name == "main" || mp.Name == "" {
256 continue
257 }
258 if _, ok := seenPkgs[mp.Name]; ok {
259 continue
260 }
261
262 // Only add packages that are previously used in the current directory.
263 var relevantPkg bool
264 for _, uri := range mp.CompiledGoFiles {
265 if uri.DirPath() == dirPath {
266 relevantPkg = true
267 break
268 }
269 }
270 if !relevantPkg {
271 continue
272 }
273
274 // Add a found package used in current directory as a high relevance
275 // suggestion and the test package for it as a medium relevance
276 // suggestion.
277 if score := float64(matcher.Score(string(mp.Name))); score > 0 {
278 packages = append(packages, toCandidate(string(mp.Name), score*highScore))
279 }
280 seenPkgs[mp.Name] = struct{}{}
281
282 testPkgName := mp.Name + "_test"
283 if _, ok := seenPkgs[testPkgName]; ok || strings.HasSuffix(string(mp.Name), "_test") {
284 continue
285 }
286 if score := float64(matcher.Score(string(testPkgName))); score > 0 {
287 packages = append(packages, toCandidate(string(testPkgName), score*stdScore))
288 }
289 seenPkgs[testPkgName] = struct{}{}
290 }
291
292 if _, ok := seenPkgs[pkgName]; !ok {
293 // Add current directory name as a low relevance suggestion.
294 dirNameScore := lowScore
295 // if current package name is empty, the dir name is the best choice.
296 if currentPackageName == "" {
297 dirNameScore = highScore
298 }
299 if score := float64(matcher.Score(string(pkgName))); score > 0 {
300 packages = append(packages, toCandidate(string(pkgName), score*dirNameScore))
301 }
302
303 testPkgName := pkgName + "_test"
304 if score := float64(matcher.Score(string(testPkgName))); score > 0 {
305 packages = append(packages, toCandidate(string(testPkgName), score*dirNameScore))
306 }
307 }
308
309 return packages, nil
310 }
311
312 // isValidDirName checks whether the passed directory name can be used in
313 // a package path. Requirements for a package path can be found here:
314 // https://golang.org/ref/mod#go-mod-file-ident.
315 func isValidDirName(dirName string) bool {
316 if dirName == "" {
317 return false
318 }
319
320 for i, ch := range dirName {
321 if isLetter(ch) || isDigit(ch) {
322 continue
323 }
324 if i == 0 {
325 // Directory name can start only with '_'. '.' is not allowed in module paths.
326 // '-' and '~' are not allowed because elements of package paths must be
327 // safe command-line arguments.
328 if ch == '_' {
329 continue
330 }
331 } else {
332 // Modules path elements can't end with '.'
333 if isAllowedPunctuation(ch) && (i != len(dirName)-1 || ch != '.') {
334 continue
335 }
336 }
337
338 return false
339 }
340 return true
341 }
342
343 // convertDirNameToPkgName converts a valid directory name to a valid package name.
344 // It leaves only letters and digits. All letters are mapped to lower case.
345 func convertDirNameToPkgName(dirName string) golang.PackageName {
346 var buf bytes.Buffer
347 for _, ch := range dirName {
348 switch {
349 case isLetter(ch):
350 buf.WriteRune(unicode.ToLower(ch))
351
352 case buf.Len() != 0 && isDigit(ch):
353 buf.WriteRune(ch)
354 }
355 }
356 return golang.PackageName(buf.String())
357 }
358
359 // isLetter and isDigit allow only ASCII characters because
360 // "Each path element is a non-empty string made of up ASCII letters,
361 // ASCII digits, and limited ASCII punctuation"
362 // (see https://golang.org/ref/mod#go-mod-file-ident).
363
364 func isLetter(ch rune) bool {
365 return 'a' <= ch && ch <= 'z' || 'A' <= ch && ch <= 'Z'
366 }
367
368 func isDigit(ch rune) bool {
369 return '0' <= ch && ch <= '9'
370 }
371
372 func isAllowedPunctuation(ch rune) bool {
373 return ch == '_' || ch == '-' || ch == '~' || ch == '.'
374 }