internal/lsp: improve completion after accidental keywords

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

variance := 123

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

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

We also fix accidental keywords in selectors, such as:


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

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
Run-TryBot: Muir Manders <>
TryBot-Result: Gobot Gobot <>
Reviewed-by: Rebecca Stambler <>
4 files changed
tree: 83500044813d278ed80e8a94dcddd69216892750
  1. .gitattributes
  2. .gitignore
  9. benchmark/
  10. blog/
  11. cmd/
  12. codereview.cfg
  13. container/
  14. cover/
  15. go.mod
  16. go.sum
  17. go/
  18. godoc/
  19. gopls/
  20. imports/
  21. internal/
  22. playground/
  23. present/
  24. refactor/
  25. txtar/

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.


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

Report Issues / Send Patches

This repository uses Gerrit for code changes. To learn how to submit changes to this repository, see

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