internal/lsp: improve completion after accidental keywords

Sometimes the prefix of the thing you want to complete is a keyword.
For example:

variance := 123
fmt.Println(var<>)

In this case the parser produces an *ast.BadExpr which breaks
completion. We now repair this BadExpr by replacing it with
an *ast.Ident named "var".

We also repair empty decls using a similar approach. This fixes cases
like:

var typeName string
type<> // want to complete to "typeName"

We also fix accidental keywords in selectors, such as:

foo.var<>

The parser produces a phantom "_" in place of the keyword, so we swap
it back for an *ast.Ident named "var".

In general, though, accidental keywords wreak havoc on the AST so we
can only do so much. There are still many cases where a keyword prefix
breaks completion. Perhaps in the future the parser can be
cursor/in-progress-edit aware and turn accidental keywords into
identifiers.

Fixes golang/go#34332.

PS I tweaked nodeContains() to include n.End() to fix a test failure
against tip related to a change to go/parser. When a syntax error is
present, an *ast.BlockStmt's End() is now set to the block's final
statement's End() (earlier than what it used to be). In order for the
cursor pos to test "inside" the block in this case I had to relax the
End() comparison.

Change-Id: Ib45952cf086cc974f1578298df3dd12829344faa
Reviewed-on: https://go-review.googlesource.com/c/tools/+/209438
Run-TryBot: Muir Manders <muir@mnd.rs>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Reviewed-by: Rebecca Stambler <rstambler@golang.org>
4 files changed
tree: 83500044813d278ed80e8a94dcddd69216892750
  1. benchmark/
  2. blog/
  3. cmd/
  4. container/
  5. cover/
  6. go/
  7. godoc/
  8. gopls/
  9. imports/
  10. internal/
  11. playground/
  12. present/
  13. refactor/
  14. txtar/
  15. .gitattributes
  16. .gitignore
  17. AUTHORS
  18. codereview.cfg
  19. CONTRIBUTING.md
  20. CONTRIBUTORS
  21. go.mod
  22. go.sum
  23. LICENSE
  24. PATENTS
  25. README.md
README.md

Go Tools

This subrepository holds the source for various packages and tools that support the Go programming language.

Some of the tools, godoc and vet for example, are included in binary Go distributions.

Others, including the Go guru and the test coverage tool, can be fetched with go get.

Packages include a type-checker for Go and an implementation of the Static Single Assignment form (SSA) representation for Go programs.

Download/Install

The easiest way to install is to run go get -u golang.org/x/tools/.... You can also manually git clone the repository to $GOPATH/src/golang.org/x/tools.

Report Issues / Send Patches

This repository uses Gerrit for code changes. To learn how to submit changes to this repository, see https://golang.org/doc/contribute.html.

The main issue tracker for the tools repository is located at https://github.com/golang/go/issues. Prefix your issue with “x/tools/(your subdir):” in the subject line, so it is easy to find.