Skip to content

Commit 9048b46

Browse files
committed
internal/lsp: avoid panic caused by assuming file ends with newline
importPrefix in format.go computes the end of the package statement including a trailing newline. This causes a panic if the user has not typed the newline. The code now checks for that case. Fixes golang/go#40208 Change-Id: I4c5118a5de78027e6c5e6ed91dfddca81e38f7e9 Reviewed-on: https://go-review.googlesource.com/c/tools/+/242638 Reviewed-by: Heschi Kreinick <[email protected]>
1 parent 6acd2ab commit 9048b46

File tree

2 files changed

+5
-1
lines changed

2 files changed

+5
-1
lines changed

internal/lsp/source/format.go

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -214,6 +214,9 @@ func importPrefix(src []byte) string {
214214
}
215215
if importEnd == 0 {
216216
importEnd = pkgEnd
217+
if importEnd > len(src) {
218+
importEnd-- // pkgEnd is off by 1 because Pos is 1-based
219+
}
217220
}
218221
for _, c := range f.Comments {
219222
if int(c.End()) > importEnd {

internal/lsp/source/format_test.go

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ type data struct {
1010

1111
func TestImportPrefix(t *testing.T) {
1212
var tdata = []data{
13+
{"package foo", "package foo"},
1314
{"package foo\n", "package foo\n"},
1415
{"package foo\n\nfunc f(){}\n", "package foo\n"},
1516
{"package foo\n\nimport \"fmt\"\n", "package foo\n\nimport \"fmt\""},
@@ -24,7 +25,7 @@ func TestImportPrefix(t *testing.T) {
2425
for i, x := range tdata {
2526
got := importPrefix([]byte(x.input))
2627
if got != x.want {
27-
t.Errorf("%d: got\n%q, wanted\n%q", i, got, x.want)
28+
t.Errorf("%d: got\n%q, wanted\n%q for %q", i, got, x.want, x.input)
2829
}
2930
}
3031
}

0 commit comments

Comments
 (0)