From c229649527913a05dace78a8e1074260b2e785f4 Mon Sep 17 00:00:00 2001 From: Muir Manders Date: Fri, 14 Feb 2020 09:02:32 -0800 Subject: [PATCH] internal/lsp/cache: fix crash fixing curlies near EOF We were crashing in cases like: 1: func foo() { 2: if b<> We were trying to get the line start position for line 3, but there is no line 3. Fix by bailing out early if we are the last line in the file because there is nothing to fix in that case. Fixes golang/go#37226. Change-Id: I4ad5746d7b55bdcc2de57c04e972c15a61084faa Reviewed-on: https://go-review.googlesource.com/c/tools/+/219498 Run-TryBot: Muir Manders Reviewed-by: Rebecca Stambler TryBot-Result: Gobot Gobot --- internal/lsp/cache/parse.go | 9 ++++++++- .../lsp/primarymod/danglingstmt/dangling_if_eof.go | 8 ++++++++ internal/lsp/testdata/lsp/summary.txt.golden | 2 +- 3 files changed, 17 insertions(+), 2 deletions(-) create mode 100644 internal/lsp/testdata/lsp/primarymod/danglingstmt/dangling_if_eof.go diff --git a/internal/lsp/cache/parse.go b/internal/lsp/cache/parse.go index 816b89abed..6d26674f76 100644 --- a/internal/lsp/cache/parse.go +++ b/internal/lsp/cache/parse.go @@ -328,12 +328,19 @@ func fixMissingCurlies(f *ast.File, b *ast.BlockStmt, parent ast.Node, tok *toke } } + parentLine := tok.Line(parent.Pos()) + + if parentLine >= tok.LineCount() { + // If we are the last line in the file, no need to fix anything. + return nil + } + // Insert curlies at the end of parent's starting line. The parent // is the statement that contains the block, e.g. *ast.IfStmt. The // block's Pos()/End() can't be relied upon because they are based // on the (missing) curly braces. We assume the statement is a // single line for now and try sticking the curly braces at the end. - insertPos := tok.LineStart(tok.Line(parent.Pos())+1) - 1 + insertPos := tok.LineStart(parentLine+1) - 1 // Scootch position backwards until it's not in a comment. For example: // diff --git a/internal/lsp/testdata/lsp/primarymod/danglingstmt/dangling_if_eof.go b/internal/lsp/testdata/lsp/primarymod/danglingstmt/dangling_if_eof.go new file mode 100644 index 0000000000..3454c9fa63 --- /dev/null +++ b/internal/lsp/testdata/lsp/primarymod/danglingstmt/dangling_if_eof.go @@ -0,0 +1,8 @@ +package danglingstmt + +func bar5() bool { //@item(danglingBar5, "bar5", "func() bool", "func") + return true +} + +func _() { + if b //@rank(" //", danglingBar5) diff --git a/internal/lsp/testdata/lsp/summary.txt.golden b/internal/lsp/testdata/lsp/summary.txt.golden index 8681655380..d9120ea7ac 100644 --- a/internal/lsp/testdata/lsp/summary.txt.golden +++ b/internal/lsp/testdata/lsp/summary.txt.golden @@ -5,7 +5,7 @@ CompletionSnippetCount = 67 UnimportedCompletionsCount = 11 DeepCompletionsCount = 5 FuzzyCompletionsCount = 8 -RankedCompletionsCount = 98 +RankedCompletionsCount = 99 CaseSensitiveCompletionsCount = 4 DiagnosticsCount = 38 FoldingRangesCount = 2