| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
package completion |
| 8 |
|
| 9 |
import ( |
| 10 |
"context" |
| 11 |
"fmt" |
| 12 |
"go/ast" |
| 13 |
"go/constant" |
| 14 |
"go/scanner" |
| 15 |
"go/token" |
| 16 |
"go/types" |
| 17 |
"iter" |
| 18 |
"math" |
| 19 |
"slices" |
| 20 |
"sort" |
| 21 |
"strconv" |
| 22 |
"strings" |
| 23 |
"sync" |
| 24 |
"time" |
| 25 |
"unicode" |
| 26 |
"unicode/utf8" |
| 27 |
|
| 28 |
goastutil "golang.org/x/tools/go/ast/astutil" |
| 29 |
"golang.org/x/tools/gopls/internal/cache" |
| 30 |
"golang.org/x/tools/gopls/internal/cache/metadata" |
| 31 |
"golang.org/x/tools/gopls/internal/cache/parsego" |
| 32 |
"golang.org/x/tools/gopls/internal/file" |
| 33 |
"golang.org/x/tools/gopls/internal/fuzzy" |
| 34 |
"golang.org/x/tools/gopls/internal/golang" |
| 35 |
"golang.org/x/tools/gopls/internal/golang/completion/snippet" |
| 36 |
"golang.org/x/tools/gopls/internal/protocol" |
| 37 |
"golang.org/x/tools/gopls/internal/settings" |
| 38 |
"golang.org/x/tools/gopls/internal/util/bug" |
| 39 |
"golang.org/x/tools/gopls/internal/util/safetoken" |
| 40 |
"golang.org/x/tools/internal/astutil" |
| 41 |
"golang.org/x/tools/internal/event" |
| 42 |
"golang.org/x/tools/internal/imports" |
| 43 |
"golang.org/x/tools/internal/typeparams" |
| 44 |
"golang.org/x/tools/internal/typesinternal" |
| 45 |
"golang.org/x/tools/internal/versions" |
| 46 |
) |
| 47 |
|
| 48 |
|
| 49 |
type CompletionItem struct { |
| 50 |
|
| 51 |
|
| 52 |
|
| 53 |
|
| 54 |
Label string |
| 55 |
|
| 56 |
|
| 57 |
|
| 58 |
Detail string |
| 59 |
|
| 60 |
|
| 61 |
|
| 62 |
|
| 63 |
InsertText string |
| 64 |
|
| 65 |
Kind protocol.CompletionItemKind |
| 66 |
Tags []protocol.CompletionItemTag |
| 67 |
Deprecated bool |
| 68 |
|
| 69 |
|
| 70 |
|
| 71 |
|
| 72 |
|
| 73 |
|
| 74 |
|
| 75 |
AdditionalTextEdits []protocol.TextEdit |
| 76 |
|
| 77 |
|
| 78 |
|
| 79 |
|
| 80 |
Depth int |
| 81 |
|
| 82 |
|
| 83 |
|
| 84 |
Score float64 |
| 85 |
|
| 86 |
|
| 87 |
|
| 88 |
|
| 89 |
|
| 90 |
|
| 91 |
|
| 92 |
|
| 93 |
|
| 94 |
|
| 95 |
|
| 96 |
|
| 97 |
|
| 98 |
|
| 99 |
|
| 100 |
snippet *snippet.Builder |
| 101 |
|
| 102 |
|
| 103 |
Documentation string |
| 104 |
|
| 105 |
|
| 106 |
|
| 107 |
|
| 108 |
isSlice bool |
| 109 |
} |
| 110 |
|
| 111 |
|
| 112 |
type completionOptions struct { |
| 113 |
unimported bool |
| 114 |
documentation bool |
| 115 |
fullDocumentation bool |
| 116 |
placeholders bool |
| 117 |
snippets bool |
| 118 |
postfix bool |
| 119 |
matcher settings.Matcher |
| 120 |
budget time.Duration |
| 121 |
completeFunctionCalls bool |
| 122 |
} |
| 123 |
|
| 124 |
|
| 125 |
|
| 126 |
|
| 127 |
func (i *CompletionItem) Snippet() string { |
| 128 |
if i.snippet != nil { |
| 129 |
return i.snippet.String() |
| 130 |
} |
| 131 |
return i.InsertText |
| 132 |
} |
| 133 |
|
| 134 |
|
| 135 |
|
| 136 |
|
| 137 |
func (i *CompletionItem) addConversion(c *completer, conv conversionEdits) { |
| 138 |
if conv.prefix != "" { |
| 139 |
|
| 140 |
if sel := enclosingSelector(c.path, c.pos); sel != nil { |
| 141 |
edits, err := c.editText(sel.Pos(), sel.Pos(), conv.prefix) |
| 142 |
if err != nil { |
| 143 |
|
| 144 |
return |
| 145 |
} |
| 146 |
i.AdditionalTextEdits = append(i.AdditionalTextEdits, edits...) |
| 147 |
} else { |
| 148 |
|
| 149 |
i.InsertText = conv.prefix + i.InsertText |
| 150 |
i.snippet.PrependText(conv.prefix) |
| 151 |
} |
| 152 |
} |
| 153 |
|
| 154 |
if conv.suffix != "" { |
| 155 |
i.InsertText += conv.suffix |
| 156 |
i.snippet.WriteText(conv.suffix) |
| 157 |
} |
| 158 |
} |
| 159 |
|
| 160 |
|
| 161 |
const ( |
| 162 |
|
| 163 |
lowScore float64 = 0.01 |
| 164 |
|
| 165 |
|
| 166 |
stdScore float64 = 1.0 |
| 167 |
|
| 168 |
|
| 169 |
highScore float64 = 10.0 |
| 170 |
) |
| 171 |
|
| 172 |
|
| 173 |
|
| 174 |
|
| 175 |
type matcher interface { |
| 176 |
Score(candidateLabel string) (score float32) |
| 177 |
} |
| 178 |
|
| 179 |
|
| 180 |
type prefixMatcher string |
| 181 |
|
| 182 |
func (pm prefixMatcher) Score(candidateLabel string) float32 { |
| 183 |
if strings.HasPrefix(candidateLabel, string(pm)) { |
| 184 |
return 1 |
| 185 |
} |
| 186 |
return -1 |
| 187 |
} |
| 188 |
|
| 189 |
|
| 190 |
type insensitivePrefixMatcher string |
| 191 |
|
| 192 |
func (ipm insensitivePrefixMatcher) Score(candidateLabel string) float32 { |
| 193 |
if strings.HasPrefix(strings.ToLower(candidateLabel), string(ipm)) { |
| 194 |
return 1 |
| 195 |
} |
| 196 |
return -1 |
| 197 |
} |
| 198 |
|
| 199 |
|
| 200 |
type completer struct { |
| 201 |
snapshot *cache.Snapshot |
| 202 |
pkg *cache.Package |
| 203 |
qual types.Qualifier |
| 204 |
mq golang.MetadataQualifier |
| 205 |
opts *completionOptions |
| 206 |
|
| 207 |
|
| 208 |
|
| 209 |
completionContext completionContext |
| 210 |
|
| 211 |
|
| 212 |
fh file.Handle |
| 213 |
|
| 214 |
|
| 215 |
filename string |
| 216 |
|
| 217 |
|
| 218 |
pgf *parsego.File |
| 219 |
|
| 220 |
|
| 221 |
|
| 222 |
|
| 223 |
goversion string |
| 224 |
|
| 225 |
|
| 226 |
pos token.Pos |
| 227 |
|
| 228 |
|
| 229 |
path []ast.Node |
| 230 |
|
| 231 |
|
| 232 |
seen map[types.Object]bool |
| 233 |
|
| 234 |
|
| 235 |
items []CompletionItem |
| 236 |
|
| 237 |
|
| 238 |
|
| 239 |
|
| 240 |
completionCallbacks []func(context.Context, *imports.Options) error |
| 241 |
|
| 242 |
|
| 243 |
surrounding *Selection |
| 244 |
|
| 245 |
|
| 246 |
|
| 247 |
inferredSelectorLHS string |
| 248 |
|
| 249 |
|
| 250 |
|
| 251 |
inference candidateInference |
| 252 |
|
| 253 |
|
| 254 |
|
| 255 |
enclosingFunc *funcInfo |
| 256 |
|
| 257 |
|
| 258 |
|
| 259 |
enclosingCompositeLiteral *compLitInfo |
| 260 |
|
| 261 |
|
| 262 |
deepState deepCompletionState |
| 263 |
|
| 264 |
|
| 265 |
matcher matcher |
| 266 |
|
| 267 |
|
| 268 |
|
| 269 |
|
| 270 |
|
| 271 |
methodSetCache map[methodSetKey]*types.MethodSet |
| 272 |
|
| 273 |
|
| 274 |
|
| 275 |
|
| 276 |
|
| 277 |
|
| 278 |
tooNewSymbolsCache map[*types.Package]map[types.Object]string |
| 279 |
|
| 280 |
|
| 281 |
mapper *protocol.Mapper |
| 282 |
|
| 283 |
|
| 284 |
|
| 285 |
|
| 286 |
|
| 287 |
|
| 288 |
|
| 289 |
|
| 290 |
startTime time.Time |
| 291 |
|
| 292 |
|
| 293 |
|
| 294 |
|
| 295 |
|
| 296 |
|
| 297 |
|
| 298 |
|
| 299 |
|
| 300 |
|
| 301 |
scopes []*types.Scope |
| 302 |
} |
| 303 |
|
| 304 |
|
| 305 |
|
| 306 |
func (c *completer) tooNew(obj types.Object) bool { |
| 307 |
pkg := obj.Pkg() |
| 308 |
if pkg == nil { |
| 309 |
return false |
| 310 |
} |
| 311 |
disallowed, ok := c.tooNewSymbolsCache[pkg] |
| 312 |
if !ok { |
| 313 |
disallowed = typesinternal.TooNewStdSymbols(pkg, c.goversion) |
| 314 |
c.tooNewSymbolsCache[pkg] = disallowed |
| 315 |
} |
| 316 |
return disallowed[obj] != "" |
| 317 |
} |
| 318 |
|
| 319 |
|
| 320 |
type funcInfo struct { |
| 321 |
|
| 322 |
sig *types.Signature |
| 323 |
|
| 324 |
|
| 325 |
body *ast.BlockStmt |
| 326 |
} |
| 327 |
|
| 328 |
type compLitInfo struct { |
| 329 |
|
| 330 |
cl *ast.CompositeLit |
| 331 |
|
| 332 |
|
| 333 |
clType types.Type |
| 334 |
|
| 335 |
|
| 336 |
kv *ast.KeyValueExpr |
| 337 |
|
| 338 |
|
| 339 |
|
| 340 |
inKey bool |
| 341 |
|
| 342 |
|
| 343 |
|
| 344 |
|
| 345 |
|
| 346 |
maybeInFieldName bool |
| 347 |
} |
| 348 |
|
| 349 |
type importInfo struct { |
| 350 |
importPath string |
| 351 |
name string |
| 352 |
} |
| 353 |
|
| 354 |
type methodSetKey struct { |
| 355 |
typ types.Type |
| 356 |
addressable bool |
| 357 |
} |
| 358 |
|
| 359 |
type completionContext struct { |
| 360 |
|
| 361 |
|
| 362 |
triggerCharacter string |
| 363 |
|
| 364 |
|
| 365 |
triggerKind protocol.CompletionTriggerKind |
| 366 |
|
| 367 |
|
| 368 |
commentCompletion bool |
| 369 |
|
| 370 |
|
| 371 |
|
| 372 |
|
| 373 |
|
| 374 |
|
| 375 |
commentNeedsLeadingSpace bool |
| 376 |
|
| 377 |
|
| 378 |
packageCompletion bool |
| 379 |
} |
| 380 |
|
| 381 |
|
| 382 |
type Selection struct { |
| 383 |
content string |
| 384 |
tokFile *token.File |
| 385 |
start, end, cursor token.Pos |
| 386 |
mapper *protocol.Mapper |
| 387 |
} |
| 388 |
|
| 389 |
|
| 390 |
func (p Selection) Range() (protocol.Range, error) { |
| 391 |
return p.mapper.PosRange(p.tokFile, p.start, p.end) |
| 392 |
} |
| 393 |
|
| 394 |
|
| 395 |
func (p Selection) PrefixRange() (protocol.Range, error) { |
| 396 |
return p.mapper.PosRange(p.tokFile, p.start, p.cursor) |
| 397 |
} |
| 398 |
|
| 399 |
func (p Selection) Prefix() string { |
| 400 |
return p.content[:p.cursor-p.start] |
| 401 |
} |
| 402 |
|
| 403 |
func (p Selection) Suffix() string { |
| 404 |
return p.content[p.cursor-p.start:] |
| 405 |
} |
| 406 |
|
| 407 |
|
| 408 |
|
| 409 |
func (p Selection) check() { |
| 410 |
offset := int(p.cursor - p.start) |
| 411 |
|
| 412 |
if offset < 0 { |
| 413 |
bug.Reportf("Selection invariant, len(content)=%d cursor=%d start=%d", len(p.content), p.cursor, p.start) |
| 414 |
} |
| 415 |
if offset > len(p.content) { |
| 416 |
bug.Reportf("Selection invariant, len(content)=%d cursor=%d start=%d", len(p.content), p.cursor, p.start) |
| 417 |
} |
| 418 |
} |
| 419 |
|
| 420 |
func (c *completer) setSurrounding(ident *ast.Ident) { |
| 421 |
if c.surrounding != nil { |
| 422 |
return |
| 423 |
} |
| 424 |
if !(ident.Pos() <= c.pos && c.pos <= ident.End()) { |
| 425 |
return |
| 426 |
} |
| 427 |
|
| 428 |
c.surrounding = &Selection{ |
| 429 |
content: ident.Name, |
| 430 |
cursor: c.pos, |
| 431 |
|
| 432 |
tokFile: c.pgf.Tok, |
| 433 |
start: ident.Pos(), |
| 434 |
end: ident.End(), |
| 435 |
mapper: c.mapper, |
| 436 |
} |
| 437 |
c.surrounding.check() |
| 438 |
|
| 439 |
c.setMatcherFromPrefix(c.surrounding.Prefix()) |
| 440 |
} |
| 441 |
|
| 442 |
func (c *completer) setMatcherFromPrefix(prefix string) { |
| 443 |
switch c.opts.matcher { |
| 444 |
case settings.Fuzzy: |
| 445 |
c.matcher = fuzzy.NewMatcher(prefix) |
| 446 |
case settings.CaseSensitive: |
| 447 |
c.matcher = prefixMatcher(prefix) |
| 448 |
default: |
| 449 |
c.matcher = insensitivePrefixMatcher(strings.ToLower(prefix)) |
| 450 |
} |
| 451 |
} |
| 452 |
|
| 453 |
func (c *completer) getSurrounding() *Selection { |
| 454 |
if c.surrounding == nil { |
| 455 |
c.surrounding = &Selection{ |
| 456 |
content: "", |
| 457 |
cursor: c.pos, |
| 458 |
tokFile: c.pgf.Tok, |
| 459 |
start: c.pos, |
| 460 |
end: c.pos, |
| 461 |
mapper: c.mapper, |
| 462 |
} |
| 463 |
c.surrounding.check() |
| 464 |
} |
| 465 |
return c.surrounding |
| 466 |
} |
| 467 |
|
| 468 |
|
| 469 |
type candidate struct { |
| 470 |
|
| 471 |
|
| 472 |
|
| 473 |
obj types.Object |
| 474 |
|
| 475 |
|
| 476 |
score float64 |
| 477 |
|
| 478 |
|
| 479 |
name string |
| 480 |
|
| 481 |
|
| 482 |
|
| 483 |
detail string |
| 484 |
|
| 485 |
|
| 486 |
|
| 487 |
path []types.Object |
| 488 |
|
| 489 |
|
| 490 |
|
| 491 |
|
| 492 |
pathInvokeMask uint16 |
| 493 |
|
| 494 |
|
| 495 |
|
| 496 |
|
| 497 |
mods []typeModKind |
| 498 |
|
| 499 |
|
| 500 |
addressable bool |
| 501 |
|
| 502 |
|
| 503 |
|
| 504 |
|
| 505 |
convertTo types.Type |
| 506 |
|
| 507 |
|
| 508 |
|
| 509 |
imp *importInfo |
| 510 |
} |
| 511 |
|
| 512 |
func (c candidate) hasMod(mod typeModKind) bool { |
| 513 |
return slices.Contains(c.mods, mod) |
| 514 |
} |
| 515 |
|
| 516 |
|
| 517 |
|
| 518 |
|
| 519 |
|
| 520 |
|
| 521 |
|
| 522 |
func Completion(ctx context.Context, snapshot *cache.Snapshot, fh file.Handle, protoPos protocol.Position, protoContext protocol.CompletionContext) ([]CompletionItem, *Selection, error) { |
| 523 |
ctx, done := event.Start(ctx, "completion.Completion") |
| 524 |
defer done() |
| 525 |
|
| 526 |
startTime := time.Now() |
| 527 |
|
| 528 |
pkg, pgf, err := golang.NarrowestPackageForFile(ctx, snapshot, fh.URI()) |
| 529 |
if err != nil || !pgf.File.Package.IsValid() { |
| 530 |
|
| 531 |
|
| 532 |
|
| 533 |
|
| 534 |
|
| 535 |
|
| 536 |
|
| 537 |
items, surrounding, innerErr := packageClauseCompletions(ctx, snapshot, fh, protoPos) |
| 538 |
if innerErr != nil { |
| 539 |
|
| 540 |
return nil, nil, fmt.Errorf("getting file %s for Completion: %v (package completions: %v)", fh.URI(), err, innerErr) |
| 541 |
} |
| 542 |
return items, surrounding, nil |
| 543 |
} |
| 544 |
|
| 545 |
pos, err := pgf.PositionPos(protoPos) |
| 546 |
if err != nil { |
| 547 |
return nil, nil, err |
| 548 |
} |
| 549 |
|
| 550 |
|
| 551 |
path, _ := goastutil.PathEnclosingInterval(pgf.File, pos-1, pos-1) |
| 552 |
if path == nil { |
| 553 |
return nil, nil, fmt.Errorf("cannot find node enclosing position") |
| 554 |
} |
| 555 |
|
| 556 |
info := pkg.TypesInfo() |
| 557 |
|
| 558 |
|
| 559 |
switch n := path[0].(type) { |
| 560 |
case *ast.BasicLit: |
| 561 |
|
| 562 |
if len(path) > 1 { |
| 563 |
if _, ok := path[1].(*ast.ImportSpec); ok { |
| 564 |
break |
| 565 |
} |
| 566 |
} |
| 567 |
return nil, nil, nil |
| 568 |
case *ast.CallExpr: |
| 569 |
if n.Ellipsis.IsValid() && pos > n.Ellipsis && pos <= n.Ellipsis+token.Pos(len("...")) { |
| 570 |
|
| 571 |
|
| 572 |
return nil, nil, nil |
| 573 |
} |
| 574 |
case *ast.Ident: |
| 575 |
|
| 576 |
if obj, ok := info.Defs[n]; ok { |
| 577 |
if v, ok := obj.(*types.Var); ok && v.IsField() && v.Embedded() { |
| 578 |
|
| 579 |
|
| 580 |
} else if pgf.File.Name == n { |
| 581 |
|
| 582 |
} else { |
| 583 |
|
| 584 |
|
| 585 |
ans, sel := definition(path, obj, pgf) |
| 586 |
if ans != nil { |
| 587 |
sort.Slice(ans, func(i, j int) bool { |
| 588 |
return ans[i].Score > ans[j].Score |
| 589 |
}) |
| 590 |
return ans, sel, nil |
| 591 |
} |
| 592 |
|
| 593 |
return nil, nil, nil |
| 594 |
} |
| 595 |
} |
| 596 |
} |
| 597 |
|
| 598 |
|
| 599 |
|
| 600 |
var scopes []*types.Scope |
| 601 |
for _, n := range path { |
| 602 |
switch node := n.(type) { |
| 603 |
case *ast.FuncDecl: |
| 604 |
n = node.Type |
| 605 |
case *ast.FuncLit: |
| 606 |
n = node.Type |
| 607 |
} |
| 608 |
scopes = append(scopes, info.Scopes[n]) |
| 609 |
} |
| 610 |
scopes = append(scopes, pkg.Types().Scope(), types.Universe) |
| 611 |
|
| 612 |
opts := snapshot.Options() |
| 613 |
c := &completer{ |
| 614 |
pkg: pkg, |
| 615 |
snapshot: snapshot, |
| 616 |
qual: typesinternal.FileQualifier(pgf.File, pkg.Types()), |
| 617 |
mq: golang.MetadataQualifierForFile(snapshot, pgf.File, pkg.Metadata()), |
| 618 |
completionContext: completionContext{ |
| 619 |
triggerCharacter: protoContext.TriggerCharacter, |
| 620 |
triggerKind: protoContext.TriggerKind, |
| 621 |
}, |
| 622 |
fh: fh, |
| 623 |
filename: fh.URI().Path(), |
| 624 |
pgf: pgf, |
| 625 |
goversion: versions.FileVersion(info, pgf.File), |
| 626 |
path: path, |
| 627 |
pos: pos, |
| 628 |
seen: make(map[types.Object]bool), |
| 629 |
enclosingFunc: enclosingFunction(path, info), |
| 630 |
enclosingCompositeLiteral: enclosingCompositeLiteral(path, pos, info), |
| 631 |
deepState: deepCompletionState{ |
| 632 |
enabled: opts.DeepCompletion, |
| 633 |
}, |
| 634 |
opts: &completionOptions{ |
| 635 |
matcher: opts.Matcher, |
| 636 |
unimported: opts.CompleteUnimported, |
| 637 |
documentation: opts.CompletionDocumentation && opts.HoverKind != settings.NoDocumentation, |
| 638 |
fullDocumentation: opts.HoverKind == settings.FullDocumentation, |
| 639 |
placeholders: opts.UsePlaceholders, |
| 640 |
budget: opts.CompletionBudget, |
| 641 |
snippets: opts.InsertTextFormat == protocol.SnippetTextFormat, |
| 642 |
postfix: opts.ExperimentalPostfixCompletions, |
| 643 |
completeFunctionCalls: opts.CompleteFunctionCalls, |
| 644 |
}, |
| 645 |
|
| 646 |
matcher: prefixMatcher(""), |
| 647 |
methodSetCache: make(map[methodSetKey]*types.MethodSet), |
| 648 |
tooNewSymbolsCache: make(map[*types.Package]map[types.Object]string), |
| 649 |
mapper: pgf.Mapper, |
| 650 |
startTime: startTime, |
| 651 |
scopes: scopes, |
| 652 |
} |
| 653 |
|
| 654 |
ctx, cancel := context.WithCancel(ctx) |
| 655 |
defer cancel() |
| 656 |
|
| 657 |
|
| 658 |
|
| 659 |
|
| 660 |
|
| 661 |
|
| 662 |
|
| 663 |
|
| 664 |
|
| 665 |
|
| 666 |
|
| 667 |
|
| 668 |
|
| 669 |
var deadline *time.Time |
| 670 |
if c.opts.budget > 0 { |
| 671 |
d := startTime.Add(c.opts.budget) |
| 672 |
deadline = &d |
| 673 |
} |
| 674 |
|
| 675 |
if surrounding := c.containingIdent(pgf.Src); surrounding != nil { |
| 676 |
c.setSurrounding(surrounding) |
| 677 |
} |
| 678 |
|
| 679 |
c.inference = expectedCandidate(ctx, c) |
| 680 |
|
| 681 |
err = c.collectCompletions(ctx) |
| 682 |
if err != nil { |
| 683 |
return nil, nil, fmt.Errorf("failed to collect completions: %v", err) |
| 684 |
} |
| 685 |
|
| 686 |
|
| 687 |
c.deepSearch(ctx, 1, deadline) |
| 688 |
|
| 689 |
|
| 690 |
|
| 691 |
|
| 692 |
|
| 693 |
|
| 694 |
if c.opts.budget > 0 { |
| 695 |
timeoutDuration := time.Until(c.startTime.Add(c.opts.budget)) |
| 696 |
ctx, cancel = context.WithTimeout(ctx, timeoutDuration) |
| 697 |
defer cancel() |
| 698 |
} |
| 699 |
|
| 700 |
for _, callback := range c.completionCallbacks { |
| 701 |
if deadline == nil || time.Now().Before(*deadline) { |
| 702 |
if err := c.snapshot.RunProcessEnvFunc(ctx, callback); err != nil { |
| 703 |
return nil, nil, fmt.Errorf("failed to run goimports callback: %v", err) |
| 704 |
} |
| 705 |
} |
| 706 |
} |
| 707 |
|
| 708 |
|
| 709 |
|
| 710 |
c.deepSearch(ctx, 0, deadline) |
| 711 |
|
| 712 |
|
| 713 |
|
| 714 |
|
| 715 |
c.addStatementCandidates() |
| 716 |
|
| 717 |
sortItems(c.items) |
| 718 |
return c.items, c.getSurrounding(), nil |
| 719 |
} |
| 720 |
|
| 721 |
|
| 722 |
|
| 723 |
func (c *completer) collectCompletions(ctx context.Context) error { |
| 724 |
|
| 725 |
for _, importSpec := range c.pgf.File.Imports { |
| 726 |
if !(importSpec.Path.Pos() <= c.pos && c.pos <= importSpec.Path.End()) { |
| 727 |
continue |
| 728 |
} |
| 729 |
return c.populateImportCompletions(importSpec) |
| 730 |
} |
| 731 |
|
| 732 |
|
| 733 |
for _, comment := range c.pgf.File.Comments { |
| 734 |
if comment.Pos() < c.pos && c.pos <= comment.End() { |
| 735 |
c.populateCommentCompletions(comment) |
| 736 |
return nil |
| 737 |
} |
| 738 |
} |
| 739 |
|
| 740 |
|
| 741 |
if wantStructFieldCompletions(c.enclosingCompositeLiteral) { |
| 742 |
|
| 743 |
|
| 744 |
if c.enclosingCompositeLiteral.inKey { |
| 745 |
c.deepState.enabled = false |
| 746 |
} |
| 747 |
return c.structLiteralFieldName(ctx) |
| 748 |
} |
| 749 |
|
| 750 |
if lt := c.wantLabelCompletion(); lt != labelNone { |
| 751 |
c.labels(lt) |
| 752 |
return nil |
| 753 |
} |
| 754 |
|
| 755 |
if c.emptySwitchStmt() { |
| 756 |
|
| 757 |
c.addKeywordItems(map[string]bool{}, highScore, CASE, DEFAULT) |
| 758 |
return nil |
| 759 |
} |
| 760 |
|
| 761 |
switch n := c.path[0].(type) { |
| 762 |
case *ast.Ident: |
| 763 |
if c.pgf.File.Name == n { |
| 764 |
return c.packageNameCompletions(ctx, c.fh.URI(), n) |
| 765 |
} else if sel, ok := c.path[1].(*ast.SelectorExpr); ok && sel.Sel == n { |
| 766 |
‸). |
| 767 |
return c.selector(ctx, sel) |
| 768 |
} |
| 769 |
return c.lexical(ctx) |
| 770 |
|
| 771 |
case *ast.TypeAssertExpr: |
| 772 |
|
| 773 |
g) |
| 774 |
|
| 775 |
|
| 776 |
|
| 777 |
|
| 778 |
sel := &ast.Ident{NamePos: n.X.End() + token.Pos(len(".")), Name: "_"} |
| 779 |
return c.selector(ctx, &ast.SelectorExpr{X: n.X, Sel: sel}) |
| 780 |
|
| 781 |
case *ast.SelectorExpr: |
| 782 |
), |
| 783 |
). |
| 784 |
return c.selector(ctx, n) |
| 785 |
|
| 786 |
case *ast.BadDecl, *ast.File: |
| 787 |
|
| 788 |
c.addKeywordCompletions() |
| 789 |
|
| 790 |
default: |
| 791 |
if c.tryInferredSelector() { |
| 792 |
return nil |
| 793 |
} |
| 794 |
|
| 795 |
return c.lexical(ctx) |
| 796 |
} |
| 797 |
|
| 798 |
return nil |
| 799 |
} |
| 800 |
|
| 801 |
|
| 802 |
|
| 803 |
func (c *completer) tryInferredSelector() bool { |
| 804 |
if c.inferredSelectorLHS == "" { |
| 805 |
return false |
| 806 |
} |
| 807 |
for _, scope := range c.scopes { |
| 808 |
if scope == nil { |
| 809 |
continue |
| 810 |
} |
| 811 |
obj := scope.Lookup(c.inferredSelectorLHS) |
| 812 |
if obj == nil { |
| 813 |
continue |
| 814 |
} |
| 815 |
if pkgName, ok := obj.(*types.PkgName); ok { |
| 816 |
c.packageMembers(pkgName.Imported(), stdScore, nil, c.deepState.enqueue) |
| 817 |
return true |
| 818 |
} |
| 819 |
if typeIsValid(obj.Type()) { |
| 820 |
c.methodsAndFields(obj.Type(), isVar(obj), nil, c.deepState.enqueue) |
| 821 |
return true |
| 822 |
} |
| 823 |
} |
| 824 |
return false |
| 825 |
} |
| 826 |
|
| 827 |
|
| 828 |
|
| 829 |
|
| 830 |
func (c *completer) containingIdent(src []byte) *ast.Ident { |
| 831 |
|
| 832 |
if ident, ok := c.path[0].(*ast.Ident); ok { |
| 833 |
return ident |
| 834 |
} |
| 835 |
|
| 836 |
pos, tkn, lit := c.scanToken(src) |
| 837 |
if ok, lhs := c.inferSelector(src); ok { |
| 838 |
c.inferredSelectorLHS = lhs |
| 839 |
} |
| 840 |
if !pos.IsValid() { |
| 841 |
return nil |
| 842 |
} |
| 843 |
|
| 844 |
fakeIdent := &ast.Ident{Name: lit, NamePos: pos} |
| 845 |
if _, isBadDecl := c.path[0].(*ast.BadDecl); isBadDecl { |
| 846 |
|
| 847 |
|
| 848 |
return fakeIdent |
| 849 |
} else if c.emptySwitchStmt() { |
| 850 |
|
| 851 |
|
| 852 |
|
| 853 |
return fakeIdent |
| 854 |
} else if tkn.IsKeyword() { |
| 855 |
|
| 856 |
|
| 857 |
|
| 858 |
return fakeIdent |
| 859 |
} else if tkn == token.IDENT { |
| 860 |
|
| 861 |
|
| 862 |
return fakeIdent |
| 863 |
} else if block, ok := c.path[0].(*ast.BlockStmt); ok && len(block.List) != 0 { |
| 864 |
last := block.List[len(block.List)-1] |
| 865 |
|
| 866 |
|
| 867 |
t" |
| 868 |
if expr, ok := last.(*ast.ExprStmt); ok && |
| 869 |
(is[*ast.Ident](expr.X) || |
| 870 |
is[*ast.SelectorExpr](expr.X) || |
| 871 |
is[*ast.IndexExpr](expr.X) || |
| 872 |
is[*ast.StarExpr](expr.X)) { |
| 873 |
return fakeIdent |
| 874 |
} |
| 875 |
} |
| 876 |
|
| 877 |
return nil |
| 878 |
} |
| 879 |
|
| 880 |
|
| 881 |
func (c *completer) scanToken(contents []byte) (token.Pos, token.Token, string) { |
| 882 |
tok := c.pkg.FileSet().File(c.pos) |
| 883 |
|
| 884 |
var s scanner.Scanner |
| 885 |
|
| 886 |
|
| 887 |
s.Init(tok, contents, nil, 0) |
| 888 |
for { |
| 889 |
tknPos, tkn, lit := s.Scan() |
| 890 |
if tkn == token.EOF || tknPos >= c.pos { |
| 891 |
return token.NoPos, token.ILLEGAL, "" |
| 892 |
} |
| 893 |
|
| 894 |
if len(lit) > 0 && tknPos <= c.pos && c.pos <= tknPos+token.Pos(len(lit)) { |
| 895 |
return tknPos, tkn, lit |
| 896 |
} |
| 897 |
} |
| 898 |
} |
| 899 |
|
| 900 |
|
| 901 |
|
| 902 |
|
| 903 |
func (c *completer) inferSelector(src []byte) (bool, string) { |
| 904 |
offset, err := safetoken.Offset(c.pgf.Tok, c.pos) |
| 905 |
if err != nil { |
| 906 |
return false, "" |
| 907 |
} |
| 908 |
|
| 909 |
|
| 910 |
|
| 911 |
scanBackIdent := func(end int) int { |
| 912 |
i := end |
| 913 |
for i > 0 { |
| 914 |
r, size := utf8.DecodeLastRune(src[:i]) |
| 915 |
if !unicode.IsLetter(r) && !unicode.IsDigit(r) && r != '_' { |
| 916 |
break |
| 917 |
} |
| 918 |
i -= size |
| 919 |
} |
| 920 |
return i |
| 921 |
} |
| 922 |
|
| 923 |
|
| 924 |
beforeIdent := scanBackIdent(offset) |
| 925 |
|
| 926 |
|
| 927 |
if beforeIdent <= 0 || src[beforeIdent-1] != '.' { |
| 928 |
return false, "" |
| 929 |
} |
| 930 |
|
| 931 |
|
| 932 |
startOfLHS := scanBackIdent(beforeIdent - 1) |
| 933 |
if startOfLHS == beforeIdent-1 { |
| 934 |
return false, "" |
| 935 |
} |
| 936 |
|
| 937 |
lhs := string(src[startOfLHS : beforeIdent-1]) |
| 938 |
if !token.IsIdentifier(lhs) { |
| 939 |
return false, "" |
| 940 |
} |
| 941 |
return true, lhs |
| 942 |
} |
| 943 |
|
| 944 |
func sortItems(items []CompletionItem) { |
| 945 |
sort.SliceStable(items, func(i, j int) bool { |
| 946 |
|
| 947 |
if items[i].Score != items[j].Score { |
| 948 |
return items[i].Score > items[j].Score |
| 949 |
} |
| 950 |
|
| 951 |
|
| 952 |
|
| 953 |
return items[i].Label < items[j].Label |
| 954 |
}) |
| 955 |
} |
| 956 |
|
| 957 |
|
| 958 |
|
| 959 |
func (c *completer) emptySwitchStmt() bool { |
| 960 |
block, ok := c.path[0].(*ast.BlockStmt) |
| 961 |
if !ok || len(block.List) > 0 || len(c.path) == 1 { |
| 962 |
return false |
| 963 |
} |
| 964 |
|
| 965 |
switch c.path[1].(type) { |
| 966 |
case *ast.SwitchStmt, *ast.TypeSwitchStmt, *ast.SelectStmt: |
| 967 |
return true |
| 968 |
default: |
| 969 |
return false |
| 970 |
} |
| 971 |
} |
| 972 |
|
| 973 |
|
| 974 |
|
| 975 |
|
| 976 |
|
| 977 |
|
| 978 |
|
| 979 |
|
| 980 |
|
| 981 |
func (c *completer) populateImportCompletions(searchImport *ast.ImportSpec) error { |
| 982 |
if !strings.HasPrefix(searchImport.Path.Value, `"`) { |
| 983 |
return nil |
| 984 |
} |
| 985 |
|
| 986 |
|
| 987 |
c.deepState.enabled = false |
| 988 |
|
| 989 |
importPath := searchImport.Path.Value |
| 990 |
|
| 991 |
|
| 992 |
|
| 993 |
prefixEnd := c.pos - searchImport.Path.Pos() |
| 994 |
prefix := strings.Trim(importPath[:prefixEnd], `"`) |
| 995 |
|
| 996 |
|
| 997 |
|
| 998 |
depth := len(strings.Split(prefix, "/")) - 1 |
| 999 |
|
| 1000 |
content := importPath |
| 1001 |
start, end := searchImport.Path.Pos(), searchImport.Path.End() |
| 1002 |
namePrefix, nameSuffix := `"`, `"` |
| 1003 |
|
| 1004 |
|
| 1005 |
|
| 1006 |
if strings.HasPrefix(importPath, `"`) && c.pos > searchImport.Path.Pos() { |
| 1007 |
content = content[1:] |
| 1008 |
start++ |
| 1009 |
if depth > 0 { |
| 1010 |
|
| 1011 |
|
| 1012 |
|
| 1013 |
|
| 1014 |
path := strings.SplitAfter(prefix, "/") |
| 1015 |
numChars := len(strings.Join(path[:len(path)-1], "")) |
| 1016 |
content = content[numChars:] |
| 1017 |
start += token.Pos(numChars) |
| 1018 |
} |
| 1019 |
namePrefix = "" |
| 1020 |
} |
| 1021 |
|
| 1022 |
|
| 1023 |
|
| 1024 |
|
| 1025 |
if strings.HasSuffix(importPath, `"`) && c.pos < searchImport.Path.End() { |
| 1026 |
end-- |
| 1027 |
content = content[:len(content)-1] |
| 1028 |
nameSuffix = "" |
| 1029 |
} |
| 1030 |
|
| 1031 |
c.surrounding = &Selection{ |
| 1032 |
content: content, |
| 1033 |
cursor: c.pos, |
| 1034 |
tokFile: c.pgf.Tok, |
| 1035 |
start: start, |
| 1036 |
end: end, |
| 1037 |
mapper: c.mapper, |
| 1038 |
} |
| 1039 |
c.surrounding.check() |
| 1040 |
|
| 1041 |
seenImports := make(map[string]struct{}) |
| 1042 |
for _, importSpec := range c.pgf.File.Imports { |
| 1043 |
if importSpec.Path.Value == importPath { |
| 1044 |
continue |
| 1045 |
} |
| 1046 |
seenImportPath, err := strconv.Unquote(importSpec.Path.Value) |
| 1047 |
if err != nil { |
| 1048 |
return err |
| 1049 |
} |
| 1050 |
seenImports[seenImportPath] = struct{}{} |
| 1051 |
} |
| 1052 |
|
| 1053 |
var mu sync.Mutex |
| 1054 |
seen := make(map[string]struct{}) |
| 1055 |
searchImports := func(pkg imports.ImportFix) { |
| 1056 |
path := pkg.StmtInfo.ImportPath |
| 1057 |
if _, ok := seenImports[path]; ok { |
| 1058 |
return |
| 1059 |
} |
| 1060 |
|
| 1061 |
|
| 1062 |
|
| 1063 |
pkgDirList := strings.Split(path, "/") |
| 1064 |
if len(pkgDirList) < depth+1 { |
| 1065 |
return |
| 1066 |
} |
| 1067 |
pkgToConsider := strings.Join(pkgDirList[:depth+1], "/") |
| 1068 |
|
| 1069 |
name := pkgDirList[depth] |
| 1070 |
|
| 1071 |
|
| 1072 |
if namePrefix == `"` { |
| 1073 |
name = pkgToConsider |
| 1074 |
} |
| 1075 |
|
| 1076 |
score := pkg.Relevance |
| 1077 |
if len(pkgDirList)-1 == depth { |
| 1078 |
score *= highScore |
| 1079 |
} else { |
| 1080 |
|
| 1081 |
|
| 1082 |
name += "/" |
| 1083 |
pkgToConsider += "/" |
| 1084 |
} |
| 1085 |
|
| 1086 |
if _, ok := seen[pkgToConsider]; ok { |
| 1087 |
return |
| 1088 |
} |
| 1089 |
seen[pkgToConsider] = struct{}{} |
| 1090 |
|
| 1091 |
mu.Lock() |
| 1092 |
defer mu.Unlock() |
| 1093 |
|
| 1094 |
name = namePrefix + name + nameSuffix |
| 1095 |
obj := types.NewPkgName(0, nil, name, types.NewPackage(pkgToConsider, name)) |
| 1096 |
c.deepState.enqueue(candidate{ |
| 1097 |
obj: obj, |
| 1098 |
detail: strconv.Quote(pkgToConsider), |
| 1099 |
score: score, |
| 1100 |
}) |
| 1101 |
} |
| 1102 |
|
| 1103 |
c.completionCallbacks = append(c.completionCallbacks, func(ctx context.Context, opts *imports.Options) error { |
| 1104 |
if err := imports.GetImportPaths(ctx, searchImports, prefix, c.filename, c.pkg.Types().Name(), opts.Env); err != nil { |
| 1105 |
return fmt.Errorf("getting import paths: %v", err) |
| 1106 |
} |
| 1107 |
return nil |
| 1108 |
}) |
| 1109 |
return nil |
| 1110 |
} |
| 1111 |
|
| 1112 |
|
| 1113 |
func (c *completer) populateCommentCompletions(comment *ast.CommentGroup) { |
| 1114 |
|
| 1115 |
|
| 1116 |
if c.completionContext.triggerCharacter == "." { |
| 1117 |
return |
| 1118 |
} |
| 1119 |
|
| 1120 |
|
| 1121 |
file := c.pkg.FileSet().File(comment.End()) |
| 1122 |
if file == nil { |
| 1123 |
return |
| 1124 |
} |
| 1125 |
|
| 1126 |
|
| 1127 |
|
| 1128 |
c.deepState.enabled = false |
| 1129 |
c.completionContext.commentCompletion = true |
| 1130 |
|
| 1131 |
|
| 1132 |
|
| 1133 |
c.opts.documentation = false |
| 1134 |
|
| 1135 |
commentLine := safetoken.Line(file, comment.End()) |
| 1136 |
|
| 1137 |
|
| 1138 |
c.setSurroundingForComment(comment) |
| 1139 |
|
| 1140 |
|
| 1141 |
|
| 1142 |
|
| 1143 |
|
| 1144 |
|
| 1145 |
if c.surrounding != nil { |
| 1146 |
for _, cmt := range comment.List { |
| 1147 |
if c.surrounding.start == cmt.Slash+2 { |
| 1148 |
c.completionContext.commentNeedsLeadingSpace = true |
| 1149 |
break |
| 1150 |
} |
| 1151 |
} |
| 1152 |
} |
| 1153 |
|
| 1154 |
|
| 1155 |
for _, n := range c.pgf.File.Decls { |
| 1156 |
declLine := safetoken.Line(file, n.Pos()) |
| 1157 |
|
| 1158 |
if declLine != commentLine && declLine != commentLine+1 && |
| 1159 |
!(n.Pos() <= comment.Pos() && comment.End() <= n.End()) { |
| 1160 |
continue |
| 1161 |
} |
| 1162 |
switch node := n.(type) { |
| 1163 |
|
| 1164 |
case *ast.GenDecl: |
| 1165 |
for _, spec := range node.Specs { |
| 1166 |
switch spec := spec.(type) { |
| 1167 |
case *ast.ValueSpec: |
| 1168 |
for _, name := range spec.Names { |
| 1169 |
if name.String() == "_" { |
| 1170 |
continue |
| 1171 |
} |
| 1172 |
obj := c.pkg.TypesInfo().ObjectOf(name) |
| 1173 |
c.deepState.enqueue(candidate{obj: obj, score: stdScore}) |
| 1174 |
} |
| 1175 |
case *ast.TypeSpec: |
| 1176 |
|
| 1177 |
switch typeNode := spec.Type.(type) { |
| 1178 |
case *ast.StructType: |
| 1179 |
c.addFieldItems(typeNode.Fields) |
| 1180 |
case *ast.FuncType: |
| 1181 |
c.addFieldItems(typeNode.Params) |
| 1182 |
c.addFieldItems(typeNode.Results) |
| 1183 |
case *ast.InterfaceType: |
| 1184 |
c.addFieldItems(typeNode.Methods) |
| 1185 |
} |
| 1186 |
|
| 1187 |
if spec.Name.String() == "_" { |
| 1188 |
continue |
| 1189 |
} |
| 1190 |
|
| 1191 |
obj := c.pkg.TypesInfo().ObjectOf(spec.Name) |
| 1192 |
|
| 1193 |
|
| 1194 |
score := stdScore * 1.1 |
| 1195 |
|
| 1196 |
if declLine == commentLine+1 { |
| 1197 |
score = highScore |
| 1198 |
} |
| 1199 |
|
| 1200 |
c.deepState.enqueue(candidate{obj: obj, score: score}) |
| 1201 |
} |
| 1202 |
} |
| 1203 |
|
| 1204 |
case *ast.FuncDecl: |
| 1205 |
c.addFieldItems(node.Recv) |
| 1206 |
c.addFieldItems(node.Type.Params) |
| 1207 |
c.addFieldItems(node.Type.Results) |
| 1208 |
|
| 1209 |
|
| 1210 |
if node.Recv != nil { |
| 1211 |
fn, ok := c.pkg.TypesInfo().Defs[node.Name].(*types.Func) |
| 1212 |
if !ok { |
| 1213 |
|
| 1214 |
|
| 1215 |
continue |
| 1216 |
} |
| 1217 |
sig := fn.Signature() |
| 1218 |
recv := sig.Recv() |
| 1219 |
if recv == nil { |
| 1220 |
continue |
| 1221 |
} |
| 1222 |
_, named := typesinternal.ReceiverNamed(recv) |
| 1223 |
if named != nil { |
| 1224 |
if recvStruct, ok := named.Underlying().(*types.Struct); ok { |
| 1225 |
for field := range recvStruct.Fields() { |
| 1226 |
c.deepState.enqueue(candidate{obj: field, score: lowScore}) |
| 1227 |
} |
| 1228 |
} |
| 1229 |
} |
| 1230 |
} |
| 1231 |
|
| 1232 |
if node.Name.String() == "_" { |
| 1233 |
continue |
| 1234 |
} |
| 1235 |
|
| 1236 |
obj := c.pkg.TypesInfo().ObjectOf(node.Name) |
| 1237 |
if obj == nil || obj.Pkg() != nil && obj.Pkg() != c.pkg.Types() { |
| 1238 |
continue |
| 1239 |
} |
| 1240 |
|
| 1241 |
c.deepState.enqueue(candidate{obj: obj, score: highScore}) |
| 1242 |
} |
| 1243 |
} |
| 1244 |
} |
| 1245 |
|
| 1246 |
|
| 1247 |
func (c *completer) setSurroundingForComment(comments *ast.CommentGroup) { |
| 1248 |
var cursorComment *ast.Comment |
| 1249 |
for _, comment := range comments.List { |
| 1250 |
if c.pos >= comment.Pos() && c.pos <= comment.End() { |
| 1251 |
cursorComment = comment |
| 1252 |
break |
| 1253 |
} |
| 1254 |
} |
| 1255 |
|
| 1256 |
if cursorComment == nil { |
| 1257 |
return |
| 1258 |
} |
| 1259 |
|
| 1260 |
|
| 1261 |
cursorOffset := int(c.pos - cursorComment.Pos()) |
| 1262 |
start, end := cursorOffset, cursorOffset |
| 1263 |
for start > 0 && isValidIdentifierChar(cursorComment.Text[start-1]) { |
| 1264 |
start-- |
| 1265 |
} |
| 1266 |
for end < len(cursorComment.Text) && isValidIdentifierChar(cursorComment.Text[end]) { |
| 1267 |
end++ |
| 1268 |
} |
| 1269 |
|
| 1270 |
c.surrounding = &Selection{ |
| 1271 |
content: cursorComment.Text[start:end], |
| 1272 |
cursor: c.pos, |
| 1273 |
tokFile: c.pgf.Tok, |
| 1274 |
start: token.Pos(int(cursorComment.Slash) + start), |
| 1275 |
end: token.Pos(int(cursorComment.Slash) + end), |
| 1276 |
mapper: c.mapper, |
| 1277 |
} |
| 1278 |
c.surrounding.check() |
| 1279 |
c.setMatcherFromPrefix(c.surrounding.Prefix()) |
| 1280 |
} |
| 1281 |
|
| 1282 |
|
| 1283 |
|
| 1284 |
func isValidIdentifierChar(char byte) bool { |
| 1285 |
charRune := rune(char) |
| 1286 |
return unicode.In(charRune, unicode.Letter, unicode.Digit) || char == '_' |
| 1287 |
} |
| 1288 |
|
| 1289 |
|
| 1290 |
func (c *completer) addFieldItems(fields *ast.FieldList) { |
| 1291 |
|
| 1292 |
|
| 1293 |
|
| 1294 |
if fields == nil || c.surrounding == nil { |
| 1295 |
return |
| 1296 |
} |
| 1297 |
|
| 1298 |
cursor := c.surrounding.cursor |
| 1299 |
for _, field := range fields.List { |
| 1300 |
for _, name := range field.Names { |
| 1301 |
if name.String() == "_" { |
| 1302 |
continue |
| 1303 |
} |
| 1304 |
obj := c.pkg.TypesInfo().ObjectOf(name) |
| 1305 |
if obj == nil { |
| 1306 |
continue |
| 1307 |
} |
| 1308 |
|
| 1309 |
|
| 1310 |
score := stdScore |
| 1311 |
if field.Comment != nil && field.Comment.Pos() <= cursor && cursor <= field.Comment.End() { |
| 1312 |
score = highScore |
| 1313 |
} else if field.Doc != nil && field.Doc.Pos() <= cursor && cursor <= field.Doc.End() { |
| 1314 |
score = highScore |
| 1315 |
} |
| 1316 |
|
| 1317 |
c.deepState.enqueue(candidate{obj: obj, score: score}) |
| 1318 |
} |
| 1319 |
} |
| 1320 |
} |
| 1321 |
|
| 1322 |
func wantStructFieldCompletions(enclosingCl *compLitInfo) bool { |
| 1323 |
if enclosingCl == nil { |
| 1324 |
return false |
| 1325 |
} |
| 1326 |
return is[*types.Struct](enclosingCl.clType) && (enclosingCl.inKey || enclosingCl.maybeInFieldName) |
| 1327 |
} |
| 1328 |
|
| 1329 |
func (c *completer) wantTypeName() bool { |
| 1330 |
return !c.completionContext.commentCompletion && c.inference.typeName.wantTypeName |
| 1331 |
} |
| 1332 |
|
| 1333 |
|
| 1334 |
const ( |
| 1335 |
maxUnimportedPackageNames = 5 |
| 1336 |
) |
| 1337 |
|
| 1338 |
|
| 1339 |
|
| 1340 |
|
| 1341 |
|
| 1342 |
func (c *completer) selector(ctx context.Context, sel *ast.SelectorExpr) error { |
| 1343 |
c.inference.objChain = objChain(c.pkg.TypesInfo(), sel.X) |
| 1344 |
|
| 1345 |
|
| 1346 |
if tv, ok := c.pkg.TypesInfo().Types[sel.X]; ok { |
| 1347 |
c.methodsAndFields(tv.Type, tv.Addressable(), nil, c.deepState.enqueue) |
| 1348 |
c.addPostfixSnippetCandidates(ctx, sel) |
| 1349 |
return nil |
| 1350 |
} |
| 1351 |
|
| 1352 |
id, ok := sel.X.(*ast.Ident) |
| 1353 |
if !ok { |
| 1354 |
return nil |
| 1355 |
} |
| 1356 |
|
| 1357 |
|
| 1358 |
if pkgName, ok := c.pkg.TypesInfo().Uses[id].(*types.PkgName); ok { |
| 1359 |
|
| 1360 |
imp := pkgName.Imported() |
| 1361 |
|
| 1362 |
|
| 1363 |
if _, ok := c.pkg.Metadata().DepsByPkgPath[golang.PackagePath(imp.Path())]; ok { |
| 1364 |
c.packageMembers(imp, stdScore, nil, c.deepState.enqueue) |
| 1365 |
return nil |
| 1366 |
} |
| 1367 |
|
| 1368 |
} |
| 1369 |
|
| 1370 |
|
| 1371 |
if !c.opts.unimported { |
| 1372 |
return nil |
| 1373 |
} |
| 1374 |
|
| 1375 |
|
| 1376 |
|
| 1377 |
|
| 1378 |
|
| 1379 |
prefix := sel.Sel.Name |
| 1380 |
if c.surrounding != nil { |
| 1381 |
if c.surrounding.content != sel.Sel.Name { |
| 1382 |
|
| 1383 |
if len(c.surrounding.content) == 0 { |
| 1384 |
bug.Reportf("surrounding is empty, should be %q", sel.Sel.Name) |
| 1385 |
} else if len(sel.Sel.Name) == 0 { |
| 1386 |
bug.Reportf("sel.Sel.Name is empty, should be %q", c.surrounding.content) |
| 1387 |
} else { |
| 1388 |
bug.Reportf("unexpected surrounding: %q != %q", c.surrounding.content, sel.Sel.Name) |
| 1389 |
} |
| 1390 |
} else { |
| 1391 |
prefix = sel.Sel.Name[:c.surrounding.cursor-c.surrounding.start] |
| 1392 |
} |
| 1393 |
} |
| 1394 |
c.unimported(ctx, metadata.PackageName(id.Name), prefix) |
| 1395 |
return nil |
| 1396 |
|
| 1397 |
} |
| 1398 |
|
| 1399 |
|
| 1400 |
|
| 1401 |
func unimportedScore(relevance float64) float64 { |
| 1402 |
return (stdScore + .1*relevance) / 2 |
| 1403 |
} |
| 1404 |
|
| 1405 |
func (c *completer) packageMembers(pkg *types.Package, score float64, imp *importInfo, cb func(candidate)) { |
| 1406 |
scope := pkg.Scope() |
| 1407 |
for _, name := range scope.Names() { |
| 1408 |
obj := scope.Lookup(name) |
| 1409 |
if c.tooNew(obj) { |
| 1410 |
continue |
| 1411 |
} |
| 1412 |
cb(candidate{ |
| 1413 |
obj: obj, |
| 1414 |
score: score, |
| 1415 |
imp: imp, |
| 1416 |
addressable: isVar(obj), |
| 1417 |
}) |
| 1418 |
} |
| 1419 |
} |
| 1420 |
|
| 1421 |
|
| 1422 |
|
| 1423 |
func ignoreUnimportedCompletion(fix *imports.ImportFix) bool { |
| 1424 |
|
| 1425 |
return fix != nil && strings.HasPrefix(fix.StmtInfo.ImportPath, "golang.org/toolchain") |
| 1426 |
} |
| 1427 |
|
| 1428 |
func (c *completer) methodsAndFields(typ types.Type, addressable bool, imp *importInfo, cb func(candidate)) { |
| 1429 |
if isStarTestingDotF(typ) { |
| 1430 |
|
| 1431 |
if c.fuzz(typ, imp, cb) { |
| 1432 |
return |
| 1433 |
} |
| 1434 |
} |
| 1435 |
|
| 1436 |
mset := c.methodSetCache[methodSetKey{typ, addressable}] |
| 1437 |
if mset == nil { |
| 1438 |
if addressable && !types.IsInterface(typ) && !isPointer(typ) { |
| 1439 |
|
| 1440 |
mset = types.NewMethodSet(types.NewPointer(typ)) |
| 1441 |
} else { |
| 1442 |
|
| 1443 |
mset = types.NewMethodSet(typ) |
| 1444 |
} |
| 1445 |
c.methodSetCache[methodSetKey{typ, addressable}] = mset |
| 1446 |
} |
| 1447 |
|
| 1448 |
for method := range mset.Methods() { |
| 1449 |
obj := method.Obj() |
| 1450 |
|
| 1451 |
if c.tooNew(obj) { |
| 1452 |
continue |
| 1453 |
} |
| 1454 |
cb(candidate{ |
| 1455 |
obj: method.Obj(), |
| 1456 |
score: stdScore, |
| 1457 |
imp: imp, |
| 1458 |
addressable: addressable || isPointer(typ), |
| 1459 |
}) |
| 1460 |
} |
| 1461 |
|
| 1462 |
|
| 1463 |
eachField(typ, func(v *types.Var) { |
| 1464 |
if c.tooNew(v) { |
| 1465 |
return |
| 1466 |
} |
| 1467 |
cb(candidate{ |
| 1468 |
obj: v, |
| 1469 |
score: stdScore - 0.01, |
| 1470 |
imp: imp, |
| 1471 |
addressable: addressable || isPointer(typ), |
| 1472 |
}) |
| 1473 |
}) |
| 1474 |
} |
| 1475 |
|
| 1476 |
|
| 1477 |
func isStarTestingDotF(typ types.Type) bool { |
| 1478 |
|
| 1479 |
|
| 1480 |
ptr, _ := typ.(*types.Pointer) |
| 1481 |
if ptr == nil { |
| 1482 |
return false |
| 1483 |
} |
| 1484 |
named, _ := ptr.Elem().(*types.Named) |
| 1485 |
if named == nil { |
| 1486 |
return false |
| 1487 |
} |
| 1488 |
obj := named.Obj() |
| 1489 |
|
| 1490 |
return obj != nil && obj.Pkg() != nil && obj.Pkg().Path() == "testing" && obj.Name() == "F" |
| 1491 |
} |
| 1492 |
|
| 1493 |
|
| 1494 |
func (c *completer) lexical(ctx context.Context) error { |
| 1495 |
var ( |
| 1496 |
builtinIota = types.Universe.Lookup("iota") |
| 1497 |
builtinNil = types.Universe.Lookup("nil") |
| 1498 |
|
| 1499 |
|
| 1500 |
|
| 1501 |
|
| 1502 |
) |
| 1503 |
|
| 1504 |
|
| 1505 |
|
| 1506 |
seen := make(map[string]struct{}) |
| 1507 |
|
| 1508 |
|
| 1509 |
for i, scope := range c.scopes { |
| 1510 |
if scope == nil { |
| 1511 |
continue |
| 1512 |
} |
| 1513 |
|
| 1514 |
Names: |
| 1515 |
for _, name := range scope.Names() { |
| 1516 |
declScope, obj := scope.LookupParent(name, c.pos) |
| 1517 |
if declScope != scope { |
| 1518 |
continue |
| 1519 |
} |
| 1520 |
|
| 1521 |
|
| 1522 |
|
| 1523 |
if !isPkgName(obj) && !typeIsValid(obj.Type()) { |
| 1524 |
|
| 1525 |
|
| 1526 |
var node ast.Node |
| 1527 |
if i < len(c.path) { |
| 1528 |
node = c.path[i] |
| 1529 |
} else if i == len(c.path) { |
| 1530 |
node = c.path[i-1] |
| 1531 |
} |
| 1532 |
if node != nil { |
| 1533 |
if resolved := resolveInvalid(c.pkg.FileSet(), obj, node, c.pkg.TypesInfo()); resolved != nil { |
| 1534 |
obj = resolved |
| 1535 |
} |
| 1536 |
} |
| 1537 |
} |
| 1538 |
|
| 1539 |
|
| 1540 |
for _, ident := range enclosingDeclLHS(c.path) { |
| 1541 |
if obj.Pos() == ident.Pos() { |
| 1542 |
continue Names |
| 1543 |
} |
| 1544 |
} |
| 1545 |
|
| 1546 |
|
| 1547 |
if obj == builtinIota && !c.inConstDecl() { |
| 1548 |
continue |
| 1549 |
} |
| 1550 |
|
| 1551 |
|
| 1552 |
score := stdScore * math.Pow(.99, float64(i)) |
| 1553 |
|
| 1554 |
|
| 1555 |
if obj == builtinNil { |
| 1556 |
score /= 2 |
| 1557 |
} |
| 1558 |
|
| 1559 |
|
| 1560 |
if _, ok := seen[obj.Name()]; !ok { |
| 1561 |
seen[obj.Name()] = struct{}{} |
| 1562 |
c.deepState.enqueue(candidate{ |
| 1563 |
obj: obj, |
| 1564 |
score: score, |
| 1565 |
addressable: isVar(obj), |
| 1566 |
}) |
| 1567 |
} |
| 1568 |
} |
| 1569 |
} |
| 1570 |
|
| 1571 |
if c.inference.objType != nil { |
| 1572 |
if named, ok := types.Unalias(typesinternal.Unpointer(c.inference.objType)).(*types.Named); ok { |
| 1573 |
|
| 1574 |
|
| 1575 |
|
| 1576 |
|
| 1577 |
if named.Obj() != nil && named.Obj().Pkg() != nil { |
| 1578 |
pkg := named.Obj().Pkg() |
| 1579 |
|
| 1580 |
|
| 1581 |
|
| 1582 |
|
| 1583 |
if _, ok := seen[pkg.Name()]; !ok && pkg != c.pkg.Types() && !alreadyImports(c.pgf.File, golang.ImportPath(pkg.Path())) { |
| 1584 |
seen[pkg.Name()] = struct{}{} |
| 1585 |
obj := types.NewPkgName(0, nil, pkg.Name(), pkg) |
| 1586 |
imp := &importInfo{ |
| 1587 |
importPath: pkg.Path(), |
| 1588 |
} |
| 1589 |
if imports.ImportPathToAssumedName(pkg.Path()) != pkg.Name() { |
| 1590 |
imp.name = pkg.Name() |
| 1591 |
} |
| 1592 |
c.deepState.enqueue(candidate{ |
| 1593 |
obj: obj, |
| 1594 |
score: stdScore, |
| 1595 |
imp: imp, |
| 1596 |
}) |
| 1597 |
} |
| 1598 |
} |
| 1599 |
} |
| 1600 |
} |
| 1601 |
|
| 1602 |
if c.opts.unimported { |
| 1603 |
if err := c.unimportedPackages(ctx, seen); err != nil { |
| 1604 |
return err |
| 1605 |
} |
| 1606 |
} |
| 1607 |
|
| 1608 |
if c.inference.typeName.isTypeParam { |
| 1609 |
|
| 1610 |
|
| 1611 |
|
| 1612 |
if t, ok := c.inference.objType.(*types.Interface); ok { |
| 1613 |
if terms, err := typeparams.InterfaceTermSet(t); err == nil { |
| 1614 |
for _, term := range terms { |
| 1615 |
c.injectType(ctx, term.Type()) |
| 1616 |
} |
| 1617 |
} |
| 1618 |
} |
| 1619 |
} else { |
| 1620 |
c.injectType(ctx, c.inference.objType) |
| 1621 |
} |
| 1622 |
|
| 1623 |
|
| 1624 |
c.addKeywordCompletions() |
| 1625 |
|
| 1626 |
return nil |
| 1627 |
} |
| 1628 |
|
| 1629 |
|
| 1630 |
|
| 1631 |
|
| 1632 |
|
| 1633 |
|
| 1634 |
func (c *completer) injectType(ctx context.Context, t types.Type) { |
| 1635 |
if t == nil { |
| 1636 |
return |
| 1637 |
} |
| 1638 |
|
| 1639 |
t = typesinternal.Unpointer(t) |
| 1640 |
|
| 1641 |
|
| 1642 |
|
| 1643 |
|
| 1644 |
|
| 1645 |
|
| 1646 |
if pnt, ok := t.(typesinternal.NamedOrAlias); !ok || pnt.TypeParams().Len() > 0 { |
| 1647 |
|
| 1648 |
|
| 1649 |
c.literal(ctx, t, nil) |
| 1650 |
|
| 1651 |
if _, isBasic := t.(*types.Basic); !isBasic { |
| 1652 |
|
| 1653 |
|
| 1654 |
|
| 1655 |
fakeNamedType := candidate{ |
| 1656 |
obj: types.NewTypeName(token.NoPos, nil, types.TypeString(t, c.qual), t), |
| 1657 |
score: stdScore, |
| 1658 |
} |
| 1659 |
|
| 1660 |
|
| 1661 |
if c.matchingTypeName(&fakeNamedType) { |
| 1662 |
c.deepState.enqueue(fakeNamedType) |
| 1663 |
} |
| 1664 |
} |
| 1665 |
} |
| 1666 |
} |
| 1667 |
|
| 1668 |
func (c *completer) unimportedPackages(ctx context.Context, seen map[string]struct{}) error { |
| 1669 |
var prefix string |
| 1670 |
if c.surrounding != nil { |
| 1671 |
prefix = c.surrounding.Prefix() |
| 1672 |
} |
| 1673 |
|
| 1674 |
|
| 1675 |
|
| 1676 |
if prefix == "" { |
| 1677 |
return nil |
| 1678 |
} |
| 1679 |
|
| 1680 |
count := 0 |
| 1681 |
|
| 1682 |
|
| 1683 |
all, err := c.snapshot.AllMetadata(ctx) |
| 1684 |
if err != nil { |
| 1685 |
return err |
| 1686 |
} |
| 1687 |
pkgNameByPath := make(map[golang.PackagePath]string) |
| 1688 |
var paths []string |
| 1689 |
for _, mp := range all { |
| 1690 |
if mp.ForTest != "" { |
| 1691 |
continue |
| 1692 |
} |
| 1693 |
if mp.Name == "main" { |
| 1694 |
continue |
| 1695 |
} |
| 1696 |
if !strings.HasPrefix(string(mp.Name), prefix) { |
| 1697 |
continue |
| 1698 |
} |
| 1699 |
paths = append(paths, string(mp.PkgPath)) |
| 1700 |
pkgNameByPath[mp.PkgPath] = string(mp.Name) |
| 1701 |
} |
| 1702 |
|
| 1703 |
|
| 1704 |
var relevances map[string]float64 |
| 1705 |
if len(paths) != 0 { |
| 1706 |
if err := c.snapshot.RunProcessEnvFunc(ctx, func(ctx context.Context, opts *imports.Options) error { |
| 1707 |
var err error |
| 1708 |
relevances, err = imports.ScoreImportPaths(ctx, opts.Env, paths) |
| 1709 |
return err |
| 1710 |
}); err != nil { |
| 1711 |
return err |
| 1712 |
} |
| 1713 |
} |
| 1714 |
sort.Slice(paths, func(i, j int) bool { |
| 1715 |
if relevances[paths[i]] != relevances[paths[j]] { |
| 1716 |
return relevances[paths[i]] > relevances[paths[j]] |
| 1717 |
} |
| 1718 |
|
| 1719 |
|
| 1720 |
|
| 1721 |
return paths[i] < paths[j] |
| 1722 |
}) |
| 1723 |
|
| 1724 |
for _, path := range paths { |
| 1725 |
name := pkgNameByPath[golang.PackagePath(path)] |
| 1726 |
if _, ok := seen[name]; ok { |
| 1727 |
continue |
| 1728 |
} |
| 1729 |
imp := &importInfo{ |
| 1730 |
importPath: path, |
| 1731 |
} |
| 1732 |
if imports.ImportPathToAssumedName(path) != name { |
| 1733 |
imp.name = name |
| 1734 |
} |
| 1735 |
if count >= maxUnimportedPackageNames { |
| 1736 |
return nil |
| 1737 |
} |
| 1738 |
c.deepState.enqueue(candidate{ |
| 1739 |
|
| 1740 |
obj: types.NewPkgName(0, nil, name, types.NewPackage(path, name)), |
| 1741 |
score: unimportedScore(relevances[path]), |
| 1742 |
imp: imp, |
| 1743 |
}) |
| 1744 |
count++ |
| 1745 |
} |
| 1746 |
|
| 1747 |
var mu sync.Mutex |
| 1748 |
add := func(pkg imports.ImportFix) { |
| 1749 |
if ignoreUnimportedCompletion(&pkg) { |
| 1750 |
return |
| 1751 |
} |
| 1752 |
mu.Lock() |
| 1753 |
defer mu.Unlock() |
| 1754 |
if _, ok := seen[pkg.IdentName]; ok { |
| 1755 |
return |
| 1756 |
} |
| 1757 |
if _, ok := relevances[pkg.StmtInfo.ImportPath]; ok { |
| 1758 |
return |
| 1759 |
} |
| 1760 |
|
| 1761 |
if count >= maxUnimportedPackageNames { |
| 1762 |
return |
| 1763 |
} |
| 1764 |
|
| 1765 |
|
| 1766 |
|
| 1767 |
|
| 1768 |
obj := types.NewPkgName(0, nil, pkg.IdentName, types.NewPackage(pkg.StmtInfo.ImportPath, pkg.IdentName)) |
| 1769 |
c.deepState.enqueue(candidate{ |
| 1770 |
obj: obj, |
| 1771 |
score: unimportedScore(pkg.Relevance), |
| 1772 |
imp: &importInfo{ |
| 1773 |
importPath: pkg.StmtInfo.ImportPath, |
| 1774 |
name: pkg.StmtInfo.Name, |
| 1775 |
}, |
| 1776 |
}) |
| 1777 |
count++ |
| 1778 |
} |
| 1779 |
|
| 1780 |
c.completionCallbacks = append(c.completionCallbacks, func(ctx context.Context, opts *imports.Options) error { |
| 1781 |
if err := imports.GetAllCandidates(ctx, add, prefix, c.filename, c.pkg.Types().Name(), opts.Env); err != nil { |
| 1782 |
return fmt.Errorf("getting completion candidates: %v", err) |
| 1783 |
} |
| 1784 |
return nil |
| 1785 |
}) |
| 1786 |
|
| 1787 |
return nil |
| 1788 |
} |
| 1789 |
|
| 1790 |
|
| 1791 |
func alreadyImports(f *ast.File, path golang.ImportPath) bool { |
| 1792 |
for _, s := range f.Imports { |
| 1793 |
if metadata.UnquoteImportPath(s) == path { |
| 1794 |
return true |
| 1795 |
} |
| 1796 |
} |
| 1797 |
return false |
| 1798 |
} |
| 1799 |
|
| 1800 |
func (c *completer) inConstDecl() bool { |
| 1801 |
for _, n := range c.path { |
| 1802 |
if decl, ok := n.(*ast.GenDecl); ok && decl.Tok == token.CONST { |
| 1803 |
return true |
| 1804 |
} |
| 1805 |
} |
| 1806 |
return false |
| 1807 |
} |
| 1808 |
|
| 1809 |
|
| 1810 |
func (c *completer) structLiteralFieldName(ctx context.Context) error { |
| 1811 |
clInfo := c.enclosingCompositeLiteral |
| 1812 |
|
| 1813 |
if t, ok := clInfo.clType.Underlying().(*types.Struct); ok { |
| 1814 |
|
| 1815 |
|
| 1816 |
|
| 1817 |
existing := make(map[types.Object][]int) |
| 1818 |
for _, elt := range clInfo.cl.Elts { |
| 1819 |
if kv, ok := elt.(*ast.KeyValueExpr); ok { |
| 1820 |
if key, ok := kv.Key.(*ast.Ident); ok && clInfo.kv != kv { |
| 1821 |
seln, ok := types.LookupSelection(clInfo.clType, true, c.pkg.Types(), key.Name) |
| 1822 |
if ok { |
| 1823 |
existing[seln.Obj()] = seln.Index() |
| 1824 |
} |
| 1825 |
} |
| 1826 |
} |
| 1827 |
} |
| 1828 |
|
| 1829 |
|
| 1830 |
fields := func(t *types.Struct) iter.Seq[*types.Var] { |
| 1831 |
|
| 1832 |
deep := versions.AtLeast(c.goversion, versions.Go1_27) |
| 1833 |
|
| 1834 |
return func(yield func(*types.Var) bool) { |
| 1835 |
var collect func(t *types.Struct) bool |
| 1836 |
collect = func(t *types.Struct) bool { |
| 1837 |
for f := range t.Fields() { |
| 1838 |
if !yield(f) { |
| 1839 |
return false |
| 1840 |
} |
| 1841 |
if deep && f.Anonymous() { |
| 1842 |
if inner, ok := f.Type().Underlying().(*types.Struct); ok && !collect(inner) { |
| 1843 |
return false |
| 1844 |
} |
| 1845 |
} |
| 1846 |
} |
| 1847 |
return true |
| 1848 |
} |
| 1849 |
collect(t) |
| 1850 |
} |
| 1851 |
} |
| 1852 |
|
| 1853 |
|
| 1854 |
|
| 1855 |
conflict := func(a, b []int) bool { |
| 1856 |
for i := range min(len(a), len(b)) { |
| 1857 |
if a[i] != b[i] { |
| 1858 |
return false |
| 1859 |
} |
| 1860 |
} |
| 1861 |
return true |
| 1862 |
} |
| 1863 |
|
| 1864 |
fieldloop: |
| 1865 |
for f := range fields(t) { |
| 1866 |
seln, ok := types.LookupSelection(clInfo.clType, true, c.pkg.Types(), f.Name()) |
| 1867 |
if !ok || seln.Obj() != f { |
| 1868 |
continue |
| 1869 |
} |
| 1870 |
|
| 1871 |
|
| 1872 |
for _, indices := range existing { |
| 1873 |
if conflict(seln.Index(), indices) { |
| 1874 |
continue fieldloop |
| 1875 |
} |
| 1876 |
} |
| 1877 |
|
| 1878 |
const deltaScore = 0.0001 |
| 1879 |
const depthPenalty = 0.01 |
| 1880 |
depth := len(seln.Index()) |
| 1881 |
fieldIdx := seln.Index()[depth-1] |
| 1882 |
c.deepState.enqueue(candidate{ |
| 1883 |
obj: seln.Obj(), |
| 1884 |
score: highScore - float64(depth-1)*depthPenalty - float64(fieldIdx)*deltaScore, |
| 1885 |
}) |
| 1886 |
} |
| 1887 |
|
| 1888 |
|
| 1889 |
|
| 1890 |
if !clInfo.maybeInFieldName { |
| 1891 |
return nil |
| 1892 |
} |
| 1893 |
} |
| 1894 |
|
| 1895 |
return c.lexical(ctx) |
| 1896 |
} |
| 1897 |
|
| 1898 |
|
| 1899 |
|
| 1900 |
|
| 1901 |
|
| 1902 |
func enclosingCompositeLiteral(path []ast.Node, pos token.Pos, info *types.Info) *compLitInfo { |
| 1903 |
for _, n := range path { |
| 1904 |
switch n := n.(type) { |
| 1905 |
case *ast.CompositeLit: |
| 1906 |
|
| 1907 |
|
| 1908 |
|
| 1909 |
|
| 1910 |
|
| 1911 |
|
| 1912 |
if !(n.Lbrace < pos && pos <= n.Rbrace) { |
| 1913 |
|
| 1914 |
|
| 1915 |
break |
| 1916 |
} |
| 1917 |
|
| 1918 |
tv, ok := info.Types[n] |
| 1919 |
if !ok { |
| 1920 |
return nil |
| 1921 |
} |
| 1922 |
|
| 1923 |
clInfo := compLitInfo{ |
| 1924 |
cl: n, |
| 1925 |
clType: typesinternal.Unpointer(tv.Type).Underlying(), |
| 1926 |
} |
| 1927 |
|
| 1928 |
var ( |
| 1929 |
expr ast.Expr |
| 1930 |
hasKeys bool |
| 1931 |
) |
| 1932 |
for _, el := range n.Elts { |
| 1933 |
|
| 1934 |
if el.Pos() <= pos && pos <= el.End() { |
| 1935 |
expr = el |
| 1936 |
} |
| 1937 |
|
| 1938 |
if kv, ok := el.(*ast.KeyValueExpr); ok { |
| 1939 |
hasKeys = true |
| 1940 |
|
| 1941 |
|
| 1942 |
if expr == el { |
| 1943 |
clInfo.kv = kv |
| 1944 |
break |
| 1945 |
} |
| 1946 |
} |
| 1947 |
} |
| 1948 |
|
| 1949 |
if clInfo.kv != nil { |
| 1950 |
|
| 1951 |
|
| 1952 |
clInfo.inKey = pos <= clInfo.kv.Colon |
| 1953 |
} else if hasKeys { |
| 1954 |
|
| 1955 |
|
| 1956 |
|
| 1957 |
clInfo.inKey = true |
| 1958 |
} else { |
| 1959 |
switch clInfo.clType.(type) { |
| 1960 |
case *types.Struct: |
| 1961 |
if len(n.Elts) == 0 { |
| 1962 |
|
| 1963 |
|
| 1964 |
|
| 1965 |
clInfo.maybeInFieldName = true |
| 1966 |
} else if len(n.Elts) == 1 { |
| 1967 |
|
| 1968 |
|
| 1969 |
|
| 1970 |
_, clInfo.maybeInFieldName = expr.(*ast.Ident) |
| 1971 |
} |
| 1972 |
case *types.Map: |
| 1973 |
|
| 1974 |
|
| 1975 |
clInfo.inKey = true |
| 1976 |
} |
| 1977 |
} |
| 1978 |
|
| 1979 |
return &clInfo |
| 1980 |
default: |
| 1981 |
if breaksExpectedTypeInference(n, pos) { |
| 1982 |
return nil |
| 1983 |
} |
| 1984 |
} |
| 1985 |
} |
| 1986 |
|
| 1987 |
return nil |
| 1988 |
} |
| 1989 |
|
| 1990 |
|
| 1991 |
|
| 1992 |
func enclosingFunction(path []ast.Node, info *types.Info) *funcInfo { |
| 1993 |
for _, node := range path { |
| 1994 |
switch t := node.(type) { |
| 1995 |
case *ast.FuncDecl: |
| 1996 |
if obj, ok := info.Defs[t.Name]; ok { |
| 1997 |
return &funcInfo{ |
| 1998 |
sig: obj.Type().(*types.Signature), |
| 1999 |
body: t.Body, |
| 2000 |
} |
| 2001 |
} |
| 2002 |
case *ast.FuncLit: |
| 2003 |
if typ, ok := info.Types[t]; ok { |
| 2004 |
if sig, _ := typ.Type.(*types.Signature); sig == nil { |
| 2005 |
|
| 2006 |
|
| 2007 |
|
| 2008 |
return nil |
| 2009 |
} |
| 2010 |
return &funcInfo{ |
| 2011 |
sig: typ.Type.(*types.Signature), |
| 2012 |
body: t.Body, |
| 2013 |
} |
| 2014 |
} |
| 2015 |
} |
| 2016 |
} |
| 2017 |
return nil |
| 2018 |
} |
| 2019 |
|
| 2020 |
func expectedCompositeLiteralType(clInfo *compLitInfo, pos token.Pos) types.Type { |
| 2021 |
switch t := clInfo.clType.(type) { |
| 2022 |
case *types.Slice: |
| 2023 |
if clInfo.inKey { |
| 2024 |
return types.Typ[types.UntypedInt] |
| 2025 |
} |
| 2026 |
return t.Elem() |
| 2027 |
case *types.Array: |
| 2028 |
if clInfo.inKey { |
| 2029 |
return types.Typ[types.UntypedInt] |
| 2030 |
} |
| 2031 |
return t.Elem() |
| 2032 |
case *types.Map: |
| 2033 |
if clInfo.inKey { |
| 2034 |
return t.Key() |
| 2035 |
} |
| 2036 |
return t.Elem() |
| 2037 |
case *types.Struct: |
| 2038 |
|
| 2039 |
if clInfo.inKey { |
| 2040 |
return nil |
| 2041 |
} |
| 2042 |
|
| 2043 |
|
| 2044 |
|
| 2045 |
if clInfo.kv != nil { |
| 2046 |
if key, ok := clInfo.kv.Key.(*ast.Ident); ok { |
| 2047 |
for field := range t.Fields() { |
| 2048 |
if field.Name() == key.Name { |
| 2049 |
return field.Type() |
| 2050 |
} |
| 2051 |
} |
| 2052 |
} |
| 2053 |
} else { |
| 2054 |
|
| 2055 |
|
| 2056 |
|
| 2057 |
|
| 2058 |
|
| 2059 |
if i := exprAtPos(pos, clInfo.cl.Elts); i < t.NumFields() { |
| 2060 |
return t.Field(i).Type() |
| 2061 |
} |
| 2062 |
} |
| 2063 |
} |
| 2064 |
return nil |
| 2065 |
} |
| 2066 |
|
| 2067 |
|
| 2068 |
type typeMod struct { |
| 2069 |
mod typeModKind |
| 2070 |
arrayLen int64 |
| 2071 |
} |
| 2072 |
|
| 2073 |
type typeModKind int |
| 2074 |
|
| 2075 |
const ( |
| 2076 |
dereference typeModKind = iota |
| 2077 |
reference |
| 2078 |
chanRead |
| 2079 |
sliceType |
| 2080 |
arrayType |
| 2081 |
invoke |
| 2082 |
takeSlice |
| 2083 |
takeDotDotDot |
| 2084 |
index |
| 2085 |
) |
| 2086 |
|
| 2087 |
type objKind int |
| 2088 |
|
| 2089 |
const ( |
| 2090 |
kindAny objKind = 0 |
| 2091 |
kindArray objKind = 1 << iota |
| 2092 |
kindSlice |
| 2093 |
kindChan |
| 2094 |
kindMap |
| 2095 |
kindStruct |
| 2096 |
kindString |
| 2097 |
kindInt |
| 2098 |
kindBool |
| 2099 |
kindBytes |
| 2100 |
kindPtr |
| 2101 |
kindInterface |
| 2102 |
kindFloat |
| 2103 |
kindComplex |
| 2104 |
kindError |
| 2105 |
kindStringer |
| 2106 |
kindFunc |
| 2107 |
kindRange0Func |
| 2108 |
kindRange1Func |
| 2109 |
kindRange2Func |
| 2110 |
) |
| 2111 |
|
| 2112 |
|
| 2113 |
|
| 2114 |
type penalizedObj struct { |
| 2115 |
|
| 2116 |
|
| 2117 |
objChain []types.Object |
| 2118 |
|
| 2119 |
penalty float64 |
| 2120 |
} |
| 2121 |
|
| 2122 |
|
| 2123 |
|
| 2124 |
type candidateInference struct { |
| 2125 |
|
| 2126 |
objType types.Type |
| 2127 |
|
| 2128 |
|
| 2129 |
objKind objKind |
| 2130 |
|
| 2131 |
|
| 2132 |
|
| 2133 |
|
| 2134 |
|
| 2135 |
variadic bool |
| 2136 |
|
| 2137 |
|
| 2138 |
|
| 2139 |
modifiers []typeMod |
| 2140 |
|
| 2141 |
|
| 2142 |
convertibleTo types.Type |
| 2143 |
|
| 2144 |
|
| 2145 |
|
| 2146 |
|
| 2147 |
|
| 2148 |
|
| 2149 |
|
| 2150 |
|
| 2151 |
|
| 2152 |
|
| 2153 |
|
| 2154 |
|
| 2155 |
|
| 2156 |
|
| 2157 |
|
| 2158 |
|
| 2159 |
|
| 2160 |
|
| 2161 |
needsExactType bool |
| 2162 |
|
| 2163 |
|
| 2164 |
|
| 2165 |
typeName typeNameInference |
| 2166 |
|
| 2167 |
|
| 2168 |
|
| 2169 |
|
| 2170 |
|
| 2171 |
|
| 2172 |
|
| 2173 |
|
| 2174 |
assignees []types.Type |
| 2175 |
|
| 2176 |
|
| 2177 |
|
| 2178 |
|
| 2179 |
|
| 2180 |
|
| 2181 |
|
| 2182 |
|
| 2183 |
|
| 2184 |
|
| 2185 |
variadicAssignees bool |
| 2186 |
|
| 2187 |
|
| 2188 |
|
| 2189 |
|
| 2190 |
|
| 2191 |
|
| 2192 |
penalized []penalizedObj |
| 2193 |
|
| 2194 |
|
| 2195 |
|
| 2196 |
|
| 2197 |
objChain []types.Object |
| 2198 |
} |
| 2199 |
|
| 2200 |
|
| 2201 |
|
| 2202 |
type typeNameInference struct { |
| 2203 |
|
| 2204 |
wantTypeName bool |
| 2205 |
|
| 2206 |
|
| 2207 |
|
| 2208 |
modifiers []typeMod |
| 2209 |
|
| 2210 |
|
| 2211 |
assertableFrom types.Type |
| 2212 |
|
| 2213 |
|
| 2214 |
wantComparable bool |
| 2215 |
|
| 2216 |
|
| 2217 |
|
| 2218 |
seenTypeSwitchCases []types.Type |
| 2219 |
|
| 2220 |
|
| 2221 |
|
| 2222 |
compLitType bool |
| 2223 |
|
| 2224 |
|
| 2225 |
isTypeParam bool |
| 2226 |
} |
| 2227 |
|
| 2228 |
|
| 2229 |
|
| 2230 |
func expectedCandidate(ctx context.Context, c *completer) (inf candidateInference) { |
| 2231 |
inf.typeName = expectTypeName(c) |
| 2232 |
|
| 2233 |
if c.enclosingCompositeLiteral != nil { |
| 2234 |
inf.objType = expectedCompositeLiteralType(c.enclosingCompositeLiteral, c.pos) |
| 2235 |
} |
| 2236 |
|
| 2237 |
Nodes: |
| 2238 |
for i, node := range c.path { |
| 2239 |
switch node := node.(type) { |
| 2240 |
case *ast.BinaryExpr: |
| 2241 |
|
| 2242 |
e := node.X |
| 2243 |
if c.pos < node.OpPos { |
| 2244 |
e = node.Y |
| 2245 |
} |
| 2246 |
if tv, ok := c.pkg.TypesInfo().Types[e]; ok { |
| 2247 |
switch node.Op { |
| 2248 |
case token.LAND, token.LOR: |
| 2249 |
|
| 2250 |
|
| 2251 |
|
| 2252 |
default: |
| 2253 |
inf.objType = tv.Type |
| 2254 |
} |
| 2255 |
break Nodes |
| 2256 |
} |
| 2257 |
case *ast.AssignStmt: |
| 2258 |
objType, assignees := expectedAssignStmtTypes(c.pkg, node, c.pos) |
| 2259 |
inf.objType = objType |
| 2260 |
inf.assignees = assignees |
| 2261 |
return inf |
| 2262 |
case *ast.ValueSpec: |
| 2263 |
inf.objType = expectedValueSpecType(c.pkg, node, c.pos) |
| 2264 |
return |
| 2265 |
case *ast.ReturnStmt: |
| 2266 |
if c.enclosingFunc != nil { |
| 2267 |
inf.objType = expectedReturnStmtType(c.enclosingFunc.sig, node, c.pos) |
| 2268 |
} |
| 2269 |
return inf |
| 2270 |
case *ast.SendStmt: |
| 2271 |
if typ := expectedSendStmtType(c.pkg, node, c.pos); typ != nil { |
| 2272 |
inf.objType = typ |
| 2273 |
} |
| 2274 |
return inf |
| 2275 |
case *ast.CallExpr: |
| 2276 |
|
| 2277 |
if node.Lparen < c.pos && c.pos <= node.Rparen { |
| 2278 |
|
| 2279 |
|
| 2280 |
if typ := typeConversion(node, c.pkg.TypesInfo()); typ != nil { |
| 2281 |
inf.convertibleTo = typ |
| 2282 |
break Nodes |
| 2283 |
} |
| 2284 |
|
| 2285 |
if sig, ok := c.pkg.TypesInfo().Types[node.Fun].Type.(*types.Signature); ok { |
| 2286 |
|
| 2287 |
if !sig.Variadic() && exprAtPos(c.pos, node.Args) >= sig.Params().Len() { |
| 2288 |
return inf |
| 2289 |
} |
| 2290 |
|
| 2291 |
|
| 2292 |
var free typeparams.Free |
| 2293 |
if free.Has(sig.Results()) { |
| 2294 |
targs := c.getTypeArgs(node) |
| 2295 |
res := inferExpectedResultTypes(c, i) |
| 2296 |
substs := reverseInferTypeArgs(sig, targs, res) |
| 2297 |
inst := instantiate(sig, substs) |
| 2298 |
if inst != nil { |
| 2299 |
|
| 2300 |
|
| 2301 |
|
| 2302 |
|
| 2303 |
inf.needsExactType = true |
| 2304 |
sig = inst |
| 2305 |
} |
| 2306 |
} |
| 2307 |
|
| 2308 |
inf = c.expectedCallParamType(inf, node, sig) |
| 2309 |
} |
| 2310 |
|
| 2311 |
if funIdent, ok := node.Fun.(*ast.Ident); ok { |
| 2312 |
obj := c.pkg.TypesInfo().ObjectOf(funIdent) |
| 2313 |
|
| 2314 |
if obj != nil && obj.Parent() == types.Universe { |
| 2315 |
|
| 2316 |
|
| 2317 |
defer func() { |
| 2318 |
inf = c.builtinArgType(obj, node, inf) |
| 2319 |
inf.objKind = c.builtinArgKind(ctx, obj, node) |
| 2320 |
}() |
| 2321 |
|
| 2322 |
|
| 2323 |
|
| 2324 |
|
| 2325 |
|
| 2326 |
|
| 2327 |
|
| 2328 |
|
| 2329 |
|
| 2330 |
|
| 2331 |
continue Nodes |
| 2332 |
} |
| 2333 |
} |
| 2334 |
|
| 2335 |
return inf |
| 2336 |
} |
| 2337 |
case *ast.CaseClause: |
| 2338 |
if swtch, ok := findSwitchStmt(c.path[i+1:], c.pos, node).(*ast.SwitchStmt); ok { |
| 2339 |
if tv, ok := c.pkg.TypesInfo().Types[swtch.Tag]; ok { |
| 2340 |
inf.objType = tv.Type |
| 2341 |
|
| 2342 |
|
| 2343 |
|
| 2344 |
for _, cc := range swtch.Body.List { |
| 2345 |
for _, caseExpr := range cc.(*ast.CaseClause).List { |
| 2346 |
|
| 2347 |
if caseExpr.Pos() < c.pos && c.pos <= caseExpr.End() { |
| 2348 |
continue |
| 2349 |
} |
| 2350 |
|
| 2351 |
if objs := objChain(c.pkg.TypesInfo(), caseExpr); len(objs) > 0 { |
| 2352 |
inf.penalized = append(inf.penalized, penalizedObj{objChain: objs, penalty: 0.1}) |
| 2353 |
} |
| 2354 |
} |
| 2355 |
} |
| 2356 |
} |
| 2357 |
} |
| 2358 |
return inf |
| 2359 |
case *ast.SliceExpr: |
| 2360 |
|
| 2361 |
if node.Lbrack < c.pos && c.pos <= node.Rbrack { |
| 2362 |
inf.objType = types.Typ[types.UntypedInt] |
| 2363 |
} |
| 2364 |
return inf |
| 2365 |
case *ast.IndexExpr: |
| 2366 |
|
| 2367 |
if node.Lbrack < c.pos && c.pos <= node.Rbrack { |
| 2368 |
if tv, ok := c.pkg.TypesInfo().Types[node.X]; ok { |
| 2369 |
switch t := tv.Type.Underlying().(type) { |
| 2370 |
case *types.Map: |
| 2371 |
inf.objType = t.Key() |
| 2372 |
case *types.Slice, *types.Array: |
| 2373 |
inf.objType = types.Typ[types.UntypedInt] |
| 2374 |
} |
| 2375 |
|
| 2376 |
if ct := expectedConstraint(tv.Type, 0); ct != nil { |
| 2377 |
inf.objType = ct |
| 2378 |
inf.typeName.wantTypeName = true |
| 2379 |
inf.typeName.isTypeParam = true |
| 2380 |
if typ := c.inferExpectedTypeArg(i+1, 0); typ != nil { |
| 2381 |
inf.objType = typ |
| 2382 |
} |
| 2383 |
} |
| 2384 |
} |
| 2385 |
} |
| 2386 |
return inf |
| 2387 |
case *ast.IndexListExpr: |
| 2388 |
if node.Lbrack < c.pos && c.pos <= node.Rbrack { |
| 2389 |
if tv, ok := c.pkg.TypesInfo().Types[node.X]; ok { |
| 2390 |
typeParamIdx := exprAtPos(c.pos, node.Indices) |
| 2391 |
if ct := expectedConstraint(tv.Type, typeParamIdx); ct != nil { |
| 2392 |
inf.objType = ct |
| 2393 |
inf.typeName.wantTypeName = true |
| 2394 |
inf.typeName.isTypeParam = true |
| 2395 |
if typ := c.inferExpectedTypeArg(i+1, typeParamIdx); typ != nil { |
| 2396 |
inf.objType = typ |
| 2397 |
} |
| 2398 |
} |
| 2399 |
} |
| 2400 |
} |
| 2401 |
return inf |
| 2402 |
case *ast.RangeStmt: |
| 2403 |
if astutil.NodeContainsPos(node.X, c.pos) { |
| 2404 |
inf.objKind |= kindSlice | kindArray | kindMap | kindString |
| 2405 |
if node.Key == nil && node.Value == nil { |
| 2406 |
inf.objKind |= kindRange0Func | kindRange1Func | kindRange2Func |
| 2407 |
} else if node.Value == nil { |
| 2408 |
inf.objKind |= kindChan | kindRange1Func | kindRange2Func |
| 2409 |
} else { |
| 2410 |
inf.objKind |= kindRange2Func |
| 2411 |
} |
| 2412 |
} |
| 2413 |
return inf |
| 2414 |
case *ast.StarExpr: |
| 2415 |
inf.modifiers = append(inf.modifiers, typeMod{mod: dereference}) |
| 2416 |
case *ast.UnaryExpr: |
| 2417 |
switch node.Op { |
| 2418 |
case token.AND: |
| 2419 |
inf.modifiers = append(inf.modifiers, typeMod{mod: reference}) |
| 2420 |
case token.ARROW: |
| 2421 |
inf.modifiers = append(inf.modifiers, typeMod{mod: chanRead}) |
| 2422 |
} |
| 2423 |
case *ast.DeferStmt, *ast.GoStmt: |
| 2424 |
inf.objKind |= kindFunc |
| 2425 |
return inf |
| 2426 |
default: |
| 2427 |
if breaksExpectedTypeInference(node, c.pos) { |
| 2428 |
return inf |
| 2429 |
} |
| 2430 |
} |
| 2431 |
} |
| 2432 |
|
| 2433 |
return inf |
| 2434 |
} |
| 2435 |
|
| 2436 |
|
| 2437 |
|
| 2438 |
|
| 2439 |
|
| 2440 |
|
| 2441 |
|
| 2442 |
|
| 2443 |
|
| 2444 |
|
| 2445 |
|
| 2446 |
|
| 2447 |
|
| 2448 |
|
| 2449 |
func inferExpectedResultTypes(c *completer, callNodeIdx int) []types.Type { |
| 2450 |
callNode, ok := c.path[callNodeIdx].(*ast.CallExpr) |
| 2451 |
if !ok { |
| 2452 |
bug.Reportf("inferExpectedResultTypes given callNodeIndex: %v which is not a ast.CallExpr\n", callNodeIdx) |
| 2453 |
return nil |
| 2454 |
} |
| 2455 |
|
| 2456 |
if len(c.path) <= callNodeIdx+1 { |
| 2457 |
return nil |
| 2458 |
} |
| 2459 |
|
| 2460 |
var expectedResults []types.Type |
| 2461 |
|
| 2462 |
|
| 2463 |
|
| 2464 |
|
| 2465 |
switch node := c.path[callNodeIdx+1].(type) { |
| 2466 |
case *ast.KeyValueExpr: |
| 2467 |
enclosingCompositeLiteral := enclosingCompositeLiteral(c.path[callNodeIdx:], callNode.Pos(), c.pkg.TypesInfo()) |
| 2468 |
if enclosingCompositeLiteral != nil && !wantStructFieldCompletions(enclosingCompositeLiteral) { |
| 2469 |
expectedResults = append(expectedResults, expectedCompositeLiteralType(enclosingCompositeLiteral, callNode.Pos())) |
| 2470 |
} |
| 2471 |
case *ast.AssignStmt: |
| 2472 |
objType, assignees := expectedAssignStmtTypes(c.pkg, node, c.pos) |
| 2473 |
if len(assignees) > 0 { |
| 2474 |
return assignees |
| 2475 |
} else if objType != nil { |
| 2476 |
expectedResults = append(expectedResults, objType) |
| 2477 |
} |
| 2478 |
case *ast.ValueSpec: |
| 2479 |
if resultType := expectedValueSpecType(c.pkg, node, c.pos); resultType != nil { |
| 2480 |
expectedResults = append(expectedResults, resultType) |
| 2481 |
} |
| 2482 |
case *ast.SendStmt: |
| 2483 |
if resultType := expectedSendStmtType(c.pkg, node, c.pos); resultType != nil { |
| 2484 |
expectedResults = append(expectedResults, resultType) |
| 2485 |
} |
| 2486 |
case *ast.ReturnStmt: |
| 2487 |
if c.enclosingFunc == nil { |
| 2488 |
return nil |
| 2489 |
} |
| 2490 |
|
| 2491 |
|
| 2492 |
|
| 2493 |
|
| 2494 |
|
| 2495 |
|
| 2496 |
if exprAtPos(c.pos, node.Results) == 0 { |
| 2497 |
if callSig := c.pkg.TypesInfo().Types[callNode.Fun].Type.(*types.Signature); callSig != nil { |
| 2498 |
enclosingResults := c.enclosingFunc.sig.Results() |
| 2499 |
if callSig.Results().Len() == enclosingResults.Len() { |
| 2500 |
expectedResults = make([]types.Type, enclosingResults.Len()) |
| 2501 |
for i := range enclosingResults.Len() { |
| 2502 |
expectedResults[i] = enclosingResults.At(i).Type() |
| 2503 |
} |
| 2504 |
return expectedResults |
| 2505 |
} |
| 2506 |
} |
| 2507 |
} |
| 2508 |
|
| 2509 |
if resultType := expectedReturnStmtType(c.enclosingFunc.sig, node, c.pos); resultType != nil { |
| 2510 |
expectedResults = append(expectedResults, resultType) |
| 2511 |
} |
| 2512 |
case *ast.CallExpr: |
| 2513 |
|
| 2514 |
|
| 2515 |
|
| 2516 |
|
| 2517 |
} |
| 2518 |
return expectedResults |
| 2519 |
} |
| 2520 |
|
| 2521 |
|
| 2522 |
|
| 2523 |
func expectedSendStmtType(pkg *cache.Package, node *ast.SendStmt, pos token.Pos) types.Type { |
| 2524 |
|
| 2525 |
if pos > node.Arrow+1 { |
| 2526 |
if tv, ok := pkg.TypesInfo().Types[node.Chan]; ok { |
| 2527 |
if ch, ok := tv.Type.Underlying().(*types.Chan); ok { |
| 2528 |
return ch.Elem() |
| 2529 |
} |
| 2530 |
} |
| 2531 |
} |
| 2532 |
return nil |
| 2533 |
} |
| 2534 |
|
| 2535 |
|
| 2536 |
|
| 2537 |
func expectedValueSpecType(pkg *cache.Package, node *ast.ValueSpec, pos token.Pos) types.Type { |
| 2538 |
if node.Type != nil && pos > node.Type.End() { |
| 2539 |
return pkg.TypesInfo().TypeOf(node.Type) |
| 2540 |
} |
| 2541 |
return nil |
| 2542 |
} |
| 2543 |
|
| 2544 |
|
| 2545 |
|
| 2546 |
|
| 2547 |
|
| 2548 |
func expectedAssignStmtTypes(pkg *cache.Package, node *ast.AssignStmt, pos token.Pos) (objType types.Type, assignees []types.Type) { |
| 2549 |
|
| 2550 |
if pos > node.TokPos { |
| 2551 |
i := exprAtPos(pos, node.Rhs) |
| 2552 |
if i >= len(node.Lhs) { |
| 2553 |
i = len(node.Lhs) - 1 |
| 2554 |
} |
| 2555 |
if tv, ok := pkg.TypesInfo().Types[node.Lhs[i]]; ok { |
| 2556 |
objType = tv.Type |
| 2557 |
} |
| 2558 |
|
| 2559 |
|
| 2560 |
|
| 2561 |
|
| 2562 |
if len(node.Rhs) <= 1 { |
| 2563 |
for _, lhs := range node.Lhs { |
| 2564 |
assignees = append(assignees, pkg.TypesInfo().TypeOf(lhs)) |
| 2565 |
} |
| 2566 |
} else { |
| 2567 |
|
| 2568 |
|
| 2569 |
|
| 2570 |
assignees = append(assignees, pkg.TypesInfo().TypeOf(node.Lhs[i])) |
| 2571 |
} |
| 2572 |
} |
| 2573 |
return objType, assignees |
| 2574 |
} |
| 2575 |
|
| 2576 |
|
| 2577 |
|
| 2578 |
func expectedReturnStmtType(enclosingSig *types.Signature, node *ast.ReturnStmt, pos token.Pos) types.Type { |
| 2579 |
if enclosingSig != nil { |
| 2580 |
if resultIdx := exprAtPos(pos, node.Results); resultIdx < enclosingSig.Results().Len() { |
| 2581 |
return enclosingSig.Results().At(resultIdx).Type() |
| 2582 |
} |
| 2583 |
} |
| 2584 |
return nil |
| 2585 |
} |
| 2586 |
|
| 2587 |
|
| 2588 |
func (c *completer) getTypeArgs(callExpr *ast.CallExpr) []types.Type { |
| 2589 |
var targs []types.Type |
| 2590 |
switch fun := callExpr.Fun.(type) { |
| 2591 |
case *ast.IndexListExpr: |
| 2592 |
for i := range fun.Indices { |
| 2593 |
if typ, ok := c.pkg.TypesInfo().Types[fun.Indices[i]]; ok && typeIsValid(typ.Type) { |
| 2594 |
targs = append(targs, typ.Type) |
| 2595 |
} |
| 2596 |
} |
| 2597 |
case *ast.IndexExpr: |
| 2598 |
if typ, ok := c.pkg.TypesInfo().Types[fun.Index]; ok && typeIsValid(typ.Type) { |
| 2599 |
targs = []types.Type{typ.Type} |
| 2600 |
} |
| 2601 |
} |
| 2602 |
return targs |
| 2603 |
} |
| 2604 |
|
| 2605 |
|
| 2606 |
|
| 2607 |
|
| 2608 |
|
| 2609 |
|
| 2610 |
func reverseInferTypeArgs(sig *types.Signature, typeArgs []types.Type, expectedResults []types.Type) []types.Type { |
| 2611 |
if len(expectedResults) == 0 || sig == nil || sig.TypeParams().Len() == 0 || sig.Results().Len() != len(expectedResults) { |
| 2612 |
return nil |
| 2613 |
} |
| 2614 |
|
| 2615 |
tparams := make([]*types.TypeParam, sig.TypeParams().Len()) |
| 2616 |
for i := range sig.TypeParams().Len() { |
| 2617 |
tparams[i] = sig.TypeParams().At(i) |
| 2618 |
} |
| 2619 |
|
| 2620 |
for i := len(typeArgs); i < sig.TypeParams().Len(); i++ { |
| 2621 |
typeArgs = append(typeArgs, nil) |
| 2622 |
} |
| 2623 |
|
| 2624 |
u := newUnifier(tparams, typeArgs) |
| 2625 |
for i, assignee := range expectedResults { |
| 2626 |
|
| 2627 |
|
| 2628 |
if !u.unify(sig.Results().At(i).Type(), assignee, unifyModeExact) { |
| 2629 |
return nil |
| 2630 |
} |
| 2631 |
} |
| 2632 |
|
| 2633 |
substs := make([]types.Type, sig.TypeParams().Len()) |
| 2634 |
for i := range sig.TypeParams().Len() { |
| 2635 |
if sub := u.handles[sig.TypeParams().At(i)]; sub != nil && *sub != nil { |
| 2636 |
|
| 2637 |
if !assignableTo(*sub, sig.TypeParams().At(i).Constraint()) { |
| 2638 |
return nil |
| 2639 |
} |
| 2640 |
substs[i] = *sub |
| 2641 |
} |
| 2642 |
} |
| 2643 |
return substs |
| 2644 |
} |
| 2645 |
|
| 2646 |
|
| 2647 |
|
| 2648 |
|
| 2649 |
|
| 2650 |
|
| 2651 |
func (c *completer) inferExpectedTypeArg(callNodeIdx int, typeParamIdx int) types.Type { |
| 2652 |
if len(c.path) <= callNodeIdx { |
| 2653 |
return nil |
| 2654 |
} |
| 2655 |
|
| 2656 |
callNode, ok := c.path[callNodeIdx].(*ast.CallExpr) |
| 2657 |
if !ok { |
| 2658 |
return nil |
| 2659 |
} |
| 2660 |
sig, ok := c.pkg.TypesInfo().Types[callNode.Fun].Type.(*types.Signature) |
| 2661 |
if !ok { |
| 2662 |
return nil |
| 2663 |
} |
| 2664 |
|
| 2665 |
|
| 2666 |
expectedResults := inferExpectedResultTypes(c, callNodeIdx) |
| 2667 |
if typeParamIdx < 0 || typeParamIdx >= sig.TypeParams().Len() { |
| 2668 |
return nil |
| 2669 |
} |
| 2670 |
substs := reverseInferTypeArgs(sig, nil, expectedResults) |
| 2671 |
if substs == nil || substs[typeParamIdx] == nil { |
| 2672 |
return nil |
| 2673 |
} |
| 2674 |
|
| 2675 |
return substs[typeParamIdx] |
| 2676 |
} |
| 2677 |
|
| 2678 |
|
| 2679 |
|
| 2680 |
func instantiate(sig *types.Signature, substs []types.Type) *types.Signature { |
| 2681 |
if substs == nil || sig == nil || len(substs) != sig.TypeParams().Len() { |
| 2682 |
return nil |
| 2683 |
} |
| 2684 |
|
| 2685 |
for i := range substs { |
| 2686 |
if substs[i] == nil { |
| 2687 |
substs[i] = sig.TypeParams().At(i) |
| 2688 |
} |
| 2689 |
} |
| 2690 |
|
| 2691 |
if inst, err := types.Instantiate(nil, sig, substs, true); err == nil { |
| 2692 |
if inst, ok := inst.(*types.Signature); ok { |
| 2693 |
return inst |
| 2694 |
} |
| 2695 |
} |
| 2696 |
|
| 2697 |
return nil |
| 2698 |
} |
| 2699 |
|
| 2700 |
func (c *completer) expectedCallParamType(inf candidateInference, node *ast.CallExpr, sig *types.Signature) candidateInference { |
| 2701 |
numParams := sig.Params().Len() |
| 2702 |
if numParams == 0 { |
| 2703 |
return inf |
| 2704 |
} |
| 2705 |
|
| 2706 |
exprIdx := exprAtPos(c.pos, node.Args) |
| 2707 |
|
| 2708 |
|
| 2709 |
|
| 2710 |
|
| 2711 |
|
| 2712 |
|
| 2713 |
if len(node.Args) <= 1 && exprIdx == 0 { |
| 2714 |
for v := range sig.Params().Variables() { |
| 2715 |
inf.assignees = append(inf.assignees, v.Type()) |
| 2716 |
} |
| 2717 |
|
| 2718 |
|
| 2719 |
inf.variadicAssignees = sig.Variadic() |
| 2720 |
} |
| 2721 |
|
| 2722 |
|
| 2723 |
if exprIdx >= numParams { |
| 2724 |
inf.objType = sig.Params().At(numParams - 1).Type() |
| 2725 |
} else { |
| 2726 |
inf.objType = sig.Params().At(exprIdx).Type() |
| 2727 |
} |
| 2728 |
|
| 2729 |
if sig.Variadic() && exprIdx >= (numParams-1) { |
| 2730 |
|
| 2731 |
inf.objType = deslice(inf.objType) |
| 2732 |
|
| 2733 |
inf.variadic = exprIdx == numParams-1 && len(node.Args) <= numParams |
| 2734 |
|
| 2735 |
|
| 2736 |
inf.objKind |= printfArgKind(c.pkg.TypesInfo(), node, exprIdx) |
| 2737 |
} |
| 2738 |
|
| 2739 |
|
| 2740 |
|
| 2741 |
|
| 2742 |
if tp, _ := inf.objType.(*types.TypeParam); tp != nil { |
| 2743 |
inf.objType = tp.Constraint() |
| 2744 |
} |
| 2745 |
|
| 2746 |
return inf |
| 2747 |
} |
| 2748 |
|
| 2749 |
func expectedConstraint(t types.Type, idx int) types.Type { |
| 2750 |
var tp *types.TypeParamList |
| 2751 |
if pnt, ok := t.(typesinternal.NamedOrAlias); ok { |
| 2752 |
tp = pnt.TypeParams() |
| 2753 |
} else if sig, _ := t.Underlying().(*types.Signature); sig != nil { |
| 2754 |
tp = sig.TypeParams() |
| 2755 |
} |
| 2756 |
if tp == nil || idx >= tp.Len() { |
| 2757 |
return nil |
| 2758 |
} |
| 2759 |
return tp.At(idx).Constraint() |
| 2760 |
} |
| 2761 |
|
| 2762 |
|
| 2763 |
|
| 2764 |
|
| 2765 |
func objChain(info *types.Info, e ast.Expr) []types.Object { |
| 2766 |
var objs []types.Object |
| 2767 |
|
| 2768 |
for e != nil { |
| 2769 |
switch n := e.(type) { |
| 2770 |
case *ast.Ident: |
| 2771 |
obj := info.ObjectOf(n) |
| 2772 |
if obj == nil { |
| 2773 |
return nil |
| 2774 |
} |
| 2775 |
objs = append(objs, obj) |
| 2776 |
e = nil |
| 2777 |
case *ast.SelectorExpr: |
| 2778 |
obj := info.ObjectOf(n.Sel) |
| 2779 |
if obj == nil { |
| 2780 |
return nil |
| 2781 |
} |
| 2782 |
objs = append(objs, obj) |
| 2783 |
e = n.X |
| 2784 |
case *ast.CallExpr: |
| 2785 |
if len(n.Args) > 0 { |
| 2786 |
return nil |
| 2787 |
} |
| 2788 |
e = n.Fun |
| 2789 |
default: |
| 2790 |
return nil |
| 2791 |
} |
| 2792 |
} |
| 2793 |
|
| 2794 |
|
| 2795 |
slices.Reverse(objs) |
| 2796 |
|
| 2797 |
return objs |
| 2798 |
} |
| 2799 |
|
| 2800 |
|
| 2801 |
|
| 2802 |
func (ci candidateInference) applyTypeModifiers(typ types.Type, addressable bool) types.Type { |
| 2803 |
for _, mod := range ci.modifiers { |
| 2804 |
switch mod.mod { |
| 2805 |
case dereference: |
| 2806 |
|
| 2807 |
|
| 2808 |
if ptr, ok := typ.Underlying().(*types.Pointer); ok { |
| 2809 |
typ = ptr.Elem() |
| 2810 |
} else { |
| 2811 |
return nil |
| 2812 |
} |
| 2813 |
case reference: |
| 2814 |
|
| 2815 |
|
| 2816 |
if addressable { |
| 2817 |
typ = types.NewPointer(typ) |
| 2818 |
} else { |
| 2819 |
return nil |
| 2820 |
} |
| 2821 |
case chanRead: |
| 2822 |
|
| 2823 |
if ch, ok := typ.(*types.Chan); ok { |
| 2824 |
typ = ch.Elem() |
| 2825 |
} else { |
| 2826 |
return nil |
| 2827 |
} |
| 2828 |
} |
| 2829 |
} |
| 2830 |
|
| 2831 |
return typ |
| 2832 |
} |
| 2833 |
|
| 2834 |
|
| 2835 |
func (ci candidateInference) applyTypeNameModifiers(typ types.Type) types.Type { |
| 2836 |
for _, mod := range ci.typeName.modifiers { |
| 2837 |
switch mod.mod { |
| 2838 |
case reference: |
| 2839 |
typ = types.NewPointer(typ) |
| 2840 |
case arrayType: |
| 2841 |
typ = types.NewArray(typ, mod.arrayLen) |
| 2842 |
case sliceType: |
| 2843 |
typ = types.NewSlice(typ) |
| 2844 |
} |
| 2845 |
} |
| 2846 |
return typ |
| 2847 |
} |
| 2848 |
|
| 2849 |
|
| 2850 |
|
| 2851 |
func (ci candidateInference) matchesVariadic(candType types.Type) bool { |
| 2852 |
return ci.variadic && ci.objType != nil && assignableTo(candType, types.NewSlice(ci.objType)) |
| 2853 |
} |
| 2854 |
|
| 2855 |
|
| 2856 |
|
| 2857 |
func findSwitchStmt(path []ast.Node, pos token.Pos, c *ast.CaseClause) ast.Stmt { |
| 2858 |
|
| 2859 |
if exprAtPos(pos, c.List) >= len(c.List) { |
| 2860 |
return nil |
| 2861 |
} |
| 2862 |
|
| 2863 |
if len(path) < 2 { |
| 2864 |
return nil |
| 2865 |
} |
| 2866 |
if _, ok := path[0].(*ast.BlockStmt); !ok { |
| 2867 |
return nil |
| 2868 |
} |
| 2869 |
switch s := path[1].(type) { |
| 2870 |
case *ast.SwitchStmt: |
| 2871 |
return s |
| 2872 |
case *ast.TypeSwitchStmt: |
| 2873 |
return s |
| 2874 |
default: |
| 2875 |
return nil |
| 2876 |
} |
| 2877 |
} |
| 2878 |
|
| 2879 |
|
| 2880 |
|
| 2881 |
|
| 2882 |
func breaksExpectedTypeInference(n ast.Node, pos token.Pos) bool { |
| 2883 |
switch n := n.(type) { |
| 2884 |
case *ast.CompositeLit: |
| 2885 |
|
| 2886 |
|
| 2887 |
return n.Type == nil || !astutil.NodeContainsPos(n.Type, pos) |
| 2888 |
case *ast.CallExpr: |
| 2889 |
|
| 2890 |
|
| 2891 |
return !astutil.NodeContainsPos(n.Fun, pos) |
| 2892 |
case *ast.FuncLit, *ast.IndexExpr, *ast.SliceExpr: |
| 2893 |
return true |
| 2894 |
default: |
| 2895 |
return false |
| 2896 |
} |
| 2897 |
} |
| 2898 |
|
| 2899 |
|
| 2900 |
func expectTypeName(c *completer) typeNameInference { |
| 2901 |
var inf typeNameInference |
| 2902 |
|
| 2903 |
Nodes: |
| 2904 |
for i, p := range c.path { |
| 2905 |
switch n := p.(type) { |
| 2906 |
case *ast.FieldList: |
| 2907 |
|
| 2908 |
|
| 2909 |
|
| 2910 |
|
| 2911 |
|
| 2912 |
inf.wantTypeName = true |
| 2913 |
break Nodes |
| 2914 |
case *ast.CaseClause: |
| 2915 |
|
| 2916 |
if swtch, ok := findSwitchStmt(c.path[i+1:], c.pos, n).(*ast.TypeSwitchStmt); ok { |
| 2917 |
|
| 2918 |
ast.Inspect(swtch.Assign, func(n ast.Node) bool { |
| 2919 |
if ta, ok := n.(*ast.TypeAssertExpr); ok { |
| 2920 |
inf.assertableFrom = c.pkg.TypesInfo().TypeOf(ta.X) |
| 2921 |
return false |
| 2922 |
} |
| 2923 |
return true |
| 2924 |
}) |
| 2925 |
inf.wantTypeName = true |
| 2926 |
|
| 2927 |
|
| 2928 |
|
| 2929 |
for _, e := range swtch.Body.List { |
| 2930 |
for _, typeExpr := range e.(*ast.CaseClause).List { |
| 2931 |
|
| 2932 |
|
| 2933 |
if typeExpr.Pos() < c.pos && c.pos <= typeExpr.End() { |
| 2934 |
continue |
| 2935 |
} |
| 2936 |
|
| 2937 |
if t := c.pkg.TypesInfo().TypeOf(typeExpr); t != nil { |
| 2938 |
inf.seenTypeSwitchCases = append(inf.seenTypeSwitchCases, t) |
| 2939 |
} |
| 2940 |
} |
| 2941 |
} |
| 2942 |
|
| 2943 |
break Nodes |
| 2944 |
} |
| 2945 |
return typeNameInference{} |
| 2946 |
case *ast.TypeAssertExpr: |
| 2947 |
|
| 2948 |
if n.Lparen < c.pos && c.pos <= n.Rparen { |
| 2949 |
|
| 2950 |
inf.assertableFrom = c.pkg.TypesInfo().TypeOf(n.X) |
| 2951 |
inf.wantTypeName = true |
| 2952 |
break Nodes |
| 2953 |
} |
| 2954 |
return typeNameInference{} |
| 2955 |
case *ast.StarExpr: |
| 2956 |
inf.modifiers = append(inf.modifiers, typeMod{mod: reference}) |
| 2957 |
case *ast.CompositeLit: |
| 2958 |
|
| 2959 |
|
| 2960 |
if n.Type != nil && n.Type.Pos() <= c.pos && c.pos <= n.Type.End() { |
| 2961 |
inf.wantTypeName = true |
| 2962 |
inf.compLitType = true |
| 2963 |
|
| 2964 |
if i < len(c.path)-1 { |
| 2965 |
|
| 2966 |
|
| 2967 |
|
| 2968 |
if u, ok := c.path[i+1].(*ast.UnaryExpr); ok && u.Op == token.AND { |
| 2969 |
inf.modifiers = append(inf.modifiers, typeMod{mod: reference}) |
| 2970 |
} |
| 2971 |
} |
| 2972 |
} |
| 2973 |
break Nodes |
| 2974 |
case *ast.ArrayType: |
| 2975 |
|
| 2976 |
if n.Elt.Pos() <= c.pos && c.pos <= n.Elt.End() { |
| 2977 |
inf.wantTypeName = true |
| 2978 |
if n.Len == nil { |
| 2979 |
|
| 2980 |
inf.modifiers = append(inf.modifiers, typeMod{mod: sliceType}) |
| 2981 |
} else { |
| 2982 |
|
| 2983 |
tv, ok := c.pkg.TypesInfo().Types[n.Len] |
| 2984 |
if ok && tv.Value != nil && tv.Value.Kind() == constant.Int { |
| 2985 |
if arrayLen, ok := constant.Int64Val(tv.Value); ok { |
| 2986 |
inf.modifiers = append(inf.modifiers, typeMod{mod: arrayType, arrayLen: arrayLen}) |
| 2987 |
} |
| 2988 |
} |
| 2989 |
} |
| 2990 |
|
| 2991 |
|
| 2992 |
|
| 2993 |
if i < len(c.path)-1 { |
| 2994 |
if _, ok := c.path[i+1].(*ast.ArrayType); ok { |
| 2995 |
continue Nodes |
| 2996 |
} |
| 2997 |
} |
| 2998 |
|
| 2999 |
break Nodes |
| 3000 |
} |
| 3001 |
case *ast.MapType: |
| 3002 |
inf.wantTypeName = true |
| 3003 |
if n.Key != nil { |
| 3004 |
inf.wantComparable = astutil.NodeContainsPos(n.Key, c.pos) |
| 3005 |
} else { |
| 3006 |
|
| 3007 |
|
| 3008 |
inf.wantComparable = c.pos == n.Pos()+token.Pos(len("map[")) |
| 3009 |
} |
| 3010 |
break Nodes |
| 3011 |
case *ast.ValueSpec: |
| 3012 |
inf.wantTypeName = n.Type != nil && astutil.NodeContainsPos(n.Type, c.pos) |
| 3013 |
break Nodes |
| 3014 |
case *ast.TypeSpec: |
| 3015 |
inf.wantTypeName = astutil.NodeContainsPos(n.Type, c.pos) |
| 3016 |
default: |
| 3017 |
if breaksExpectedTypeInference(p, c.pos) { |
| 3018 |
return typeNameInference{} |
| 3019 |
} |
| 3020 |
} |
| 3021 |
} |
| 3022 |
|
| 3023 |
return inf |
| 3024 |
} |
| 3025 |
|
| 3026 |
func (c *completer) fakeObj(T types.Type) *types.Var { |
| 3027 |
return types.NewVar(token.NoPos, c.pkg.Types(), "", T) |
| 3028 |
} |
| 3029 |
|
| 3030 |
|
| 3031 |
|
| 3032 |
func derivableTypes(t types.Type, addressable bool, f func(t types.Type, addressable bool, mod typeModKind) bool) bool { |
| 3033 |
switch t := t.Underlying().(type) { |
| 3034 |
case *types.Signature: |
| 3035 |
|
| 3036 |
if t.Results().Len() == 1 && f(t.Results().At(0).Type(), false, invoke) { |
| 3037 |
return true |
| 3038 |
} |
| 3039 |
case *types.Array: |
| 3040 |
if f(t.Elem(), true, index) { |
| 3041 |
return true |
| 3042 |
} |
| 3043 |
|
| 3044 |
if f(types.NewSlice(t.Elem()), false, takeSlice) { |
| 3045 |
return true |
| 3046 |
} |
| 3047 |
case *types.Pointer: |
| 3048 |
if f(t.Elem(), false, dereference) { |
| 3049 |
return true |
| 3050 |
} |
| 3051 |
case *types.Slice: |
| 3052 |
if f(t.Elem(), true, index) { |
| 3053 |
return true |
| 3054 |
} |
| 3055 |
case *types.Map: |
| 3056 |
if f(t.Elem(), false, index) { |
| 3057 |
return true |
| 3058 |
} |
| 3059 |
case *types.Chan: |
| 3060 |
if f(t.Elem(), false, chanRead) { |
| 3061 |
return true |
| 3062 |
} |
| 3063 |
} |
| 3064 |
|
| 3065 |
|
| 3066 |
if addressable && f(types.NewPointer(t), false, reference) { |
| 3067 |
return true |
| 3068 |
} |
| 3069 |
|
| 3070 |
return false |
| 3071 |
} |
| 3072 |
|
| 3073 |
|
| 3074 |
|
| 3075 |
|
| 3076 |
|
| 3077 |
func (c *candidate) anyCandType(f func(t types.Type, addressable bool) bool) bool { |
| 3078 |
if c.obj == nil || c.obj.Type() == nil { |
| 3079 |
return false |
| 3080 |
} |
| 3081 |
|
| 3082 |
const maxDepth = 3 |
| 3083 |
|
| 3084 |
var searchTypes func(t types.Type, addressable bool, mods []typeModKind) bool |
| 3085 |
searchTypes = func(t types.Type, addressable bool, mods []typeModKind) bool { |
| 3086 |
if f(t, addressable) { |
| 3087 |
if len(mods) > 0 { |
| 3088 |
newMods := make([]typeModKind, len(mods)+len(c.mods)) |
| 3089 |
copy(newMods, mods) |
| 3090 |
copy(newMods[len(mods):], c.mods) |
| 3091 |
c.mods = newMods |
| 3092 |
} |
| 3093 |
return true |
| 3094 |
} |
| 3095 |
|
| 3096 |
if len(mods) == maxDepth { |
| 3097 |
return false |
| 3098 |
} |
| 3099 |
|
| 3100 |
return derivableTypes(t, addressable, func(t types.Type, addressable bool, mod typeModKind) bool { |
| 3101 |
return searchTypes(t, addressable, append(mods, mod)) |
| 3102 |
}) |
| 3103 |
} |
| 3104 |
|
| 3105 |
return searchTypes(c.obj.Type(), c.addressable, make([]typeModKind, 0, maxDepth)) |
| 3106 |
} |
| 3107 |
|
| 3108 |
|
| 3109 |
|
| 3110 |
func (c *completer) matchingCandidate(cand *candidate) bool { |
| 3111 |
if c.completionContext.commentCompletion { |
| 3112 |
return false |
| 3113 |
} |
| 3114 |
|
| 3115 |
|
| 3116 |
if v, ok := cand.obj.(*types.Var); ok && v.IsField() && wantStructFieldCompletions(c.enclosingCompositeLiteral) { |
| 3117 |
return true |
| 3118 |
} |
| 3119 |
|
| 3120 |
if isTypeName(cand.obj) { |
| 3121 |
return c.matchingTypeName(cand) |
| 3122 |
} else if c.wantTypeName() { |
| 3123 |
|
| 3124 |
return false |
| 3125 |
} |
| 3126 |
|
| 3127 |
if c.inference.candTypeMatches(cand) { |
| 3128 |
return true |
| 3129 |
} |
| 3130 |
|
| 3131 |
candType := cand.obj.Type() |
| 3132 |
if candType == nil { |
| 3133 |
return false |
| 3134 |
} |
| 3135 |
|
| 3136 |
if sig, ok := candType.Underlying().(*types.Signature); ok { |
| 3137 |
if c.inference.assigneesMatch(cand, sig) { |
| 3138 |
|
| 3139 |
cand.mods = append(cand.mods, invoke) |
| 3140 |
return true |
| 3141 |
} |
| 3142 |
} |
| 3143 |
|
| 3144 |
|
| 3145 |
|
| 3146 |
|
| 3147 |
if isFunc(cand.obj) { |
| 3148 |
cand.mods = append(cand.mods, invoke) |
| 3149 |
} |
| 3150 |
|
| 3151 |
return false |
| 3152 |
} |
| 3153 |
|
| 3154 |
|
| 3155 |
|
| 3156 |
|
| 3157 |
func (ci *candidateInference) candTypeMatches(cand *candidate) bool { |
| 3158 |
var ( |
| 3159 |
expTypes = make([]types.Type, 0, 2) |
| 3160 |
variadicType types.Type |
| 3161 |
) |
| 3162 |
if ci.objType != nil { |
| 3163 |
expTypes = append(expTypes, ci.objType) |
| 3164 |
|
| 3165 |
if ci.variadic { |
| 3166 |
variadicType = types.NewSlice(ci.objType) |
| 3167 |
expTypes = append(expTypes, variadicType) |
| 3168 |
} |
| 3169 |
} |
| 3170 |
|
| 3171 |
return cand.anyCandType(func(candType types.Type, addressable bool) bool { |
| 3172 |
|
| 3173 |
candType = ci.applyTypeModifiers(candType, addressable) |
| 3174 |
if candType == nil { |
| 3175 |
return false |
| 3176 |
} |
| 3177 |
|
| 3178 |
if ci.convertibleTo != nil && convertibleTo(candType, ci.convertibleTo) { |
| 3179 |
return true |
| 3180 |
} |
| 3181 |
|
| 3182 |
for _, expType := range expTypes { |
| 3183 |
if isEmptyInterface(expType) { |
| 3184 |
|
| 3185 |
|
| 3186 |
|
| 3187 |
|
| 3188 |
|
| 3189 |
|
| 3190 |
|
| 3191 |
continue |
| 3192 |
} |
| 3193 |
|
| 3194 |
matches := ci.typeMatches(expType, candType) |
| 3195 |
if !matches { |
| 3196 |
|
| 3197 |
|
| 3198 |
if considerTypeConversion(candType, expType, cand.path) { |
| 3199 |
cand.convertTo = expType |
| 3200 |
|
| 3201 |
|
| 3202 |
cand.score *= 0.5 |
| 3203 |
return true |
| 3204 |
} |
| 3205 |
|
| 3206 |
continue |
| 3207 |
} |
| 3208 |
|
| 3209 |
if expType == variadicType { |
| 3210 |
cand.mods = append(cand.mods, takeDotDotDot) |
| 3211 |
} |
| 3212 |
|
| 3213 |
|
| 3214 |
|
| 3215 |
if ci.needsExactType && !types.Identical(candType, expType) { |
| 3216 |
cand.convertTo = expType |
| 3217 |
|
| 3218 |
cand.score *= 0.95 |
| 3219 |
} |
| 3220 |
|
| 3221 |
|
| 3222 |
|
| 3223 |
|
| 3224 |
if isUntyped(candType) && !types.Identical(candType, expType) && cand.obj.Parent() != types.Universe { |
| 3225 |
|
| 3226 |
|
| 3227 |
|
| 3228 |
if len(cand.path) > 0 && isPkgName(cand.path[0]) { |
| 3229 |
cand.score *= 0.5 |
| 3230 |
} else { |
| 3231 |
cand.score *= 0.75 |
| 3232 |
} |
| 3233 |
} |
| 3234 |
|
| 3235 |
return true |
| 3236 |
} |
| 3237 |
|
| 3238 |
|
| 3239 |
|
| 3240 |
if ci.objType == nil || isEmptyInterface(ci.objType) { |
| 3241 |
|
| 3242 |
|
| 3243 |
|
| 3244 |
|
| 3245 |
|
| 3246 |
|
| 3247 |
|
| 3248 |
|
| 3249 |
if len(ci.modifiers) > 0 { |
| 3250 |
return true |
| 3251 |
} |
| 3252 |
|
| 3253 |
|
| 3254 |
|
| 3255 |
if ci.kindMatches(candType) { |
| 3256 |
if ci.objKind == kindFunc { |
| 3257 |
cand.mods = append(cand.mods, invoke) |
| 3258 |
} |
| 3259 |
return true |
| 3260 |
} |
| 3261 |
} |
| 3262 |
|
| 3263 |
return false |
| 3264 |
}) |
| 3265 |
} |
| 3266 |
|
| 3267 |
|
| 3268 |
|
| 3269 |
func considerTypeConversion(from, to types.Type, path []types.Object) bool { |
| 3270 |
|
| 3271 |
|
| 3272 |
|
| 3273 |
if len(path) > 0 && isPkgName(path[0]) { |
| 3274 |
return false |
| 3275 |
} |
| 3276 |
|
| 3277 |
if _, ok := from.(*types.TypeParam); ok { |
| 3278 |
return false |
| 3279 |
} |
| 3280 |
|
| 3281 |
if !convertibleTo(from, to) { |
| 3282 |
return false |
| 3283 |
} |
| 3284 |
|
| 3285 |
|
| 3286 |
|
| 3287 |
if isBasicKind(from, types.IsInteger) && isBasicKind(to, types.IsString) { |
| 3288 |
return false |
| 3289 |
} |
| 3290 |
|
| 3291 |
return true |
| 3292 |
} |
| 3293 |
|
| 3294 |
|
| 3295 |
|
| 3296 |
func (ci *candidateInference) typeMatches(expType, candType types.Type) bool { |
| 3297 |
|
| 3298 |
|
| 3299 |
if candBasic, ok := candType.Underlying().(*types.Basic); ok { |
| 3300 |
if expBasic, ok := expType.Underlying().(*types.Basic); ok { |
| 3301 |
|
| 3302 |
|
| 3303 |
|
| 3304 |
|
| 3305 |
|
| 3306 |
a, b := candBasic.Info(), expBasic.Info() |
| 3307 |
if a&types.IsUntyped == 0 || (b&types.IsInteger > 0 && b&types.IsUntyped > 0) { |
| 3308 |
a, b = b, a |
| 3309 |
} |
| 3310 |
|
| 3311 |
|
| 3312 |
if a&types.IsUntyped > 0 { |
| 3313 |
switch { |
| 3314 |
|
| 3315 |
case a&types.IsInteger > 0 && b&types.IsFloat > 0: |
| 3316 |
return true |
| 3317 |
|
| 3318 |
|
| 3319 |
|
| 3320 |
|
| 3321 |
case a&types.IsConstType == b&types.IsConstType: |
| 3322 |
return true |
| 3323 |
} |
| 3324 |
} |
| 3325 |
} |
| 3326 |
} |
| 3327 |
|
| 3328 |
|
| 3329 |
|
| 3330 |
return assignableTo(candType, expType) |
| 3331 |
} |
| 3332 |
|
| 3333 |
|
| 3334 |
|
| 3335 |
func (ci *candidateInference) kindMatches(candType types.Type) bool { |
| 3336 |
return ci.objKind > 0 && ci.objKind&candKind(candType) > 0 |
| 3337 |
} |
| 3338 |
|
| 3339 |
|
| 3340 |
|
| 3341 |
func (ci *candidateInference) assigneesMatch(cand *candidate, sig *types.Signature) bool { |
| 3342 |
if len(ci.assignees) == 0 { |
| 3343 |
return false |
| 3344 |
} |
| 3345 |
|
| 3346 |
|
| 3347 |
|
| 3348 |
if sig.Results().Len() == 1 { |
| 3349 |
return false |
| 3350 |
} |
| 3351 |
|
| 3352 |
|
| 3353 |
|
| 3354 |
if ci.variadicAssignees && len(ci.assignees) == 1 && isEmptyInterface(deslice(ci.assignees[0])) { |
| 3355 |
return false |
| 3356 |
} |
| 3357 |
|
| 3358 |
var numberOfResultsCouldMatch bool |
| 3359 |
if ci.variadicAssignees { |
| 3360 |
numberOfResultsCouldMatch = sig.Results().Len() >= len(ci.assignees)-1 |
| 3361 |
} else { |
| 3362 |
numberOfResultsCouldMatch = sig.Results().Len() == len(ci.assignees) |
| 3363 |
} |
| 3364 |
|
| 3365 |
|
| 3366 |
|
| 3367 |
|
| 3368 |
|
| 3369 |
|
| 3370 |
if !numberOfResultsCouldMatch { |
| 3371 |
cand.score /= 2 |
| 3372 |
return false |
| 3373 |
} |
| 3374 |
|
| 3375 |
|
| 3376 |
|
| 3377 |
|
| 3378 |
allMatch := false |
| 3379 |
for i := range sig.Results().Len() { |
| 3380 |
var assignee types.Type |
| 3381 |
|
| 3382 |
|
| 3383 |
|
| 3384 |
if ci.variadicAssignees && i >= len(ci.assignees)-1 { |
| 3385 |
assignee = ci.assignees[len(ci.assignees)-1] |
| 3386 |
if elem := deslice(assignee); elem != nil { |
| 3387 |
assignee = elem |
| 3388 |
} |
| 3389 |
} else { |
| 3390 |
assignee = ci.assignees[i] |
| 3391 |
} |
| 3392 |
|
| 3393 |
if assignee == nil || assignee == types.Typ[types.Invalid] { |
| 3394 |
continue |
| 3395 |
} |
| 3396 |
|
| 3397 |
allMatch = ci.typeMatches(assignee, sig.Results().At(i).Type()) |
| 3398 |
if !allMatch { |
| 3399 |
break |
| 3400 |
} |
| 3401 |
} |
| 3402 |
return allMatch |
| 3403 |
} |
| 3404 |
|
| 3405 |
func (c *completer) matchingTypeName(cand *candidate) bool { |
| 3406 |
if !c.wantTypeName() { |
| 3407 |
return false |
| 3408 |
} |
| 3409 |
|
| 3410 |
wantExactTypeParam := c.inference.typeName.isTypeParam && |
| 3411 |
c.inference.typeName.wantTypeName && c.inference.needsExactType |
| 3412 |
|
| 3413 |
typeMatches := func(candType types.Type) bool { |
| 3414 |
|
| 3415 |
candType = c.inference.applyTypeNameModifiers(candType) |
| 3416 |
|
| 3417 |
if from := c.inference.typeName.assertableFrom; from != nil { |
| 3418 |
|
| 3419 |
|
| 3420 |
if types.Identical(from, candType) { |
| 3421 |
return false |
| 3422 |
} |
| 3423 |
|
| 3424 |
if intf, ok := from.Underlying().(*types.Interface); ok { |
| 3425 |
if !types.AssertableTo(intf, candType) { |
| 3426 |
return false |
| 3427 |
} |
| 3428 |
} |
| 3429 |
} |
| 3430 |
|
| 3431 |
|
| 3432 |
|
| 3433 |
|
| 3434 |
if wantExactTypeParam && types.Identical(candType, c.inference.objType) { |
| 3435 |
return true |
| 3436 |
} |
| 3437 |
|
| 3438 |
if c.inference.typeName.wantComparable && !types.Comparable(candType) { |
| 3439 |
return false |
| 3440 |
} |
| 3441 |
|
| 3442 |
|
| 3443 |
|
| 3444 |
for _, seen := range c.inference.typeName.seenTypeSwitchCases { |
| 3445 |
if types.Identical(candType, seen) { |
| 3446 |
return false |
| 3447 |
} |
| 3448 |
} |
| 3449 |
|
| 3450 |
|
| 3451 |
|
| 3452 |
|
| 3453 |
|
| 3454 |
|
| 3455 |
|
| 3456 |
if c.inference.objType != nil { |
| 3457 |
return assignableTo(candType, c.inference.objType) |
| 3458 |
} |
| 3459 |
|
| 3460 |
|
| 3461 |
return true |
| 3462 |
} |
| 3463 |
|
| 3464 |
t := cand.obj.Type() |
| 3465 |
|
| 3466 |
if typeMatches(t) { |
| 3467 |
return true |
| 3468 |
} |
| 3469 |
|
| 3470 |
if !types.IsInterface(t) && typeMatches(types.NewPointer(t)) { |
| 3471 |
if c.inference.typeName.compLitType { |
| 3472 |
|
| 3473 |
|
| 3474 |
cand.mods = append(cand.mods, reference) |
| 3475 |
} else { |
| 3476 |
|
| 3477 |
|
| 3478 |
cand.mods = append(cand.mods, dereference) |
| 3479 |
} |
| 3480 |
return true |
| 3481 |
} |
| 3482 |
|
| 3483 |
return false |
| 3484 |
} |
| 3485 |
|
| 3486 |
var ( |
| 3487 |
|
| 3488 |
errorIntf = types.Universe.Lookup("error").Type().Underlying().(*types.Interface) |
| 3489 |
|
| 3490 |
|
| 3491 |
stringerIntf = types.NewInterfaceType([]*types.Func{ |
| 3492 |
types.NewFunc(token.NoPos, nil, "String", types.NewSignatureType( |
| 3493 |
nil, nil, |
| 3494 |
nil, nil, |
| 3495 |
types.NewTuple(types.NewParam(token.NoPos, nil, "", types.Typ[types.String])), |
| 3496 |
false, |
| 3497 |
)), |
| 3498 |
}, nil).Complete() |
| 3499 |
|
| 3500 |
byteType = types.Universe.Lookup("byte").Type() |
| 3501 |
|
| 3502 |
boolType = types.Universe.Lookup("bool").Type() |
| 3503 |
) |
| 3504 |
|
| 3505 |
|
| 3506 |
func candKind(candType types.Type) objKind { |
| 3507 |
var kind objKind |
| 3508 |
|
| 3509 |
switch t := candType.Underlying().(type) { |
| 3510 |
case *types.Array: |
| 3511 |
kind |= kindArray |
| 3512 |
if t.Elem() == byteType { |
| 3513 |
kind |= kindBytes |
| 3514 |
} |
| 3515 |
case *types.Slice: |
| 3516 |
kind |= kindSlice |
| 3517 |
if t.Elem() == byteType { |
| 3518 |
kind |= kindBytes |
| 3519 |
} |
| 3520 |
case *types.Chan: |
| 3521 |
kind |= kindChan |
| 3522 |
case *types.Map: |
| 3523 |
kind |= kindMap |
| 3524 |
case *types.Pointer: |
| 3525 |
kind |= kindPtr |
| 3526 |
|
| 3527 |
|
| 3528 |
|
| 3529 |
if _, isArray := t.Elem().Underlying().(*types.Array); isArray { |
| 3530 |
kind |= kindArray |
| 3531 |
} |
| 3532 |
case *types.Interface: |
| 3533 |
kind |= kindInterface |
| 3534 |
case *types.Basic: |
| 3535 |
switch info := t.Info(); { |
| 3536 |
case info&types.IsString > 0: |
| 3537 |
kind |= kindString |
| 3538 |
case info&types.IsInteger > 0: |
| 3539 |
kind |= kindInt |
| 3540 |
case info&types.IsFloat > 0: |
| 3541 |
kind |= kindFloat |
| 3542 |
case info&types.IsComplex > 0: |
| 3543 |
kind |= kindComplex |
| 3544 |
case info&types.IsBoolean > 0: |
| 3545 |
kind |= kindBool |
| 3546 |
} |
| 3547 |
case *types.Signature: |
| 3548 |
kind |= kindFunc |
| 3549 |
|
| 3550 |
switch rangeFuncParamCount(t) { |
| 3551 |
case 0: |
| 3552 |
kind |= kindRange0Func |
| 3553 |
case 1: |
| 3554 |
kind |= kindRange1Func |
| 3555 |
case 2: |
| 3556 |
kind |= kindRange2Func |
| 3557 |
} |
| 3558 |
} |
| 3559 |
|
| 3560 |
if types.Implements(candType, errorIntf) { |
| 3561 |
kind |= kindError |
| 3562 |
} |
| 3563 |
|
| 3564 |
if types.Implements(candType, stringerIntf) { |
| 3565 |
kind |= kindStringer |
| 3566 |
} |
| 3567 |
|
| 3568 |
return kind |
| 3569 |
} |
| 3570 |
|
| 3571 |
|
| 3572 |
func rangeFuncParamCount(sig *types.Signature) int { |
| 3573 |
if sig.Results().Len() != 0 || sig.Params().Len() != 1 { |
| 3574 |
return -1 |
| 3575 |
} |
| 3576 |
|
| 3577 |
yieldSig, _ := sig.Params().At(0).Type().Underlying().(*types.Signature) |
| 3578 |
if yieldSig == nil { |
| 3579 |
return -1 |
| 3580 |
} |
| 3581 |
|
| 3582 |
if yieldSig.Results().Len() != 1 || yieldSig.Results().At(0).Type() != boolType { |
| 3583 |
return -1 |
| 3584 |
} |
| 3585 |
|
| 3586 |
return yieldSig.Params().Len() |
| 3587 |
} |
| 3588 |
|
| 3589 |
|
| 3590 |
func (c *completer) innermostScope() *types.Scope { |
| 3591 |
for _, s := range c.scopes { |
| 3592 |
if s != nil { |
| 3593 |
return s |
| 3594 |
} |
| 3595 |
} |
| 3596 |
return nil |
| 3597 |
} |
| 3598 |
|
| 3599 |
|
| 3600 |
func isSlice(obj types.Object) bool { |
| 3601 |
if obj != nil && obj.Type() != nil { |
| 3602 |
if _, ok := obj.Type().Underlying().(*types.Slice); ok { |
| 3603 |
return true |
| 3604 |
} |
| 3605 |
} |
| 3606 |
return false |
| 3607 |
} |
| 3608 |
|
| 3609 |
func is[T any](x any) bool { |
| 3610 |
_, ok := x.(T) |
| 3611 |
return ok |
| 3612 |
} |