| 1 |
|
| 2 |
|
| 3 |
|
| 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 |
|
| 32 |
|
| 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 |
|
| 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 |
|
| 50 |
|
| 51 |
func packageClauseCompletions(ctx context.Context, snapshot *cache.Snapshot, fh file.Handle, position protocol.Position) ([]CompletionItem, *Selection, error) { |
| 52 |
|
| 53 |
|
| 54 |
|
| 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 |
|
| 89 |
|
| 90 |
|
| 91 |
func packageCompletionSurrounding(pgf *parsego.File, offset int) (*Selection, error) { |
| 92 |
m := pgf.Mapper |
| 93 |
|
| 94 |
|
| 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 |
|
| 104 |
|
| 105 |
|
| 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 |
|
| 125 |
|
| 126 |
|
| 127 |
|
| 128 |
|
| 129 |
|
| 130 |
|
| 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 |
|
| 149 |
|
| 150 |
if cursor > expr.Pos() { |
| 151 |
return nil, fmt.Errorf("cursor after expression") |
| 152 |
} |
| 153 |
|
| 154 |
|
| 155 |
if cursorInComment(tok, cursor, m.Content) { |
| 156 |
return nil, fmt.Errorf("cursor in comment") |
| 157 |
} |
| 158 |
|
| 159 |
|
| 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 |
|
| 188 |
|
| 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 |
|
| 210 |
|
| 211 |
|
| 212 |
|
| 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 |
|
| 226 |
if md, err := snapshot.NarrowestMetadataForFile(ctx, fileURI); err == nil { |
| 227 |
currentPackageName = string(md.Name) |
| 228 |
} |
| 229 |
|
| 230 |
matcher := fuzzy.NewMatcher(prefix) |
| 231 |
|
| 232 |
|
| 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 |
|
| 253 |
|
| 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 |
|
| 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 |
|
| 275 |
|
| 276 |
|
| 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 |
|
| 294 |
dirNameScore := lowScore |
| 295 |
|
| 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 |
|
| 313 |
|
| 314 |
|
| 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 |
|
| 326 |
|
| 327 |
|
| 328 |
if ch == '_' { |
| 329 |
continue |
| 330 |
} |
| 331 |
} else { |
| 332 |
|
| 333 |
if isAllowedPunctuation(ch) && (i != len(dirName)-1 || ch != '.') { |
| 334 |
continue |
| 335 |
} |
| 336 |
} |
| 337 |
|
| 338 |
return false |
| 339 |
} |
| 340 |
return true |
| 341 |
} |
| 342 |
|
| 343 |
|
| 344 |
|
| 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 |
|
| 360 |
|
| 361 |
|
| 362 |
|
| 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 |
} |