Skip to content

Commit 95ece92

Browse files
committed
internal/lsp/source: trim file very carefully
Apparently the AST will sometimes give us offsets past the end of the file. Don't crash when it does. Fixes golang/go#36610. Change-Id: I3cfbf8645bfcea94a5d87bca5bef4236d657b2c0 Reviewed-on: https://go-review.googlesource.com/c/tools/+/215119 Run-TryBot: Heschi Kreinick <[email protected]> TryBot-Result: Gobot Gobot <[email protected]> Reviewed-by: Rebecca Stambler <[email protected]>
1 parent a209551 commit 95ece92

File tree

2 files changed

+32
-2
lines changed

2 files changed

+32
-2
lines changed

internal/lsp/source/format.go

+7-2
Original file line numberDiff line numberDiff line change
@@ -245,8 +245,13 @@ func trimToImports(fset *token.FileSet, f *ast.File, src []byte) ([]byte, int) {
245245
tok := fset.File(f.Pos())
246246
start := firstImport.Pos()
247247
end := lastImport.End()
248-
if tok.LineCount() > fset.Position(end).Line {
249-
end = fset.File(f.Pos()).LineStart(fset.Position(lastImport.End()).Line + 1)
248+
// The parser will happily feed us nonsense. See golang/go#36610.
249+
tokStart, tokEnd := token.Pos(tok.Base()), token.Pos(tok.Base()+tok.Size())
250+
if start < tokStart || start > tokEnd || end < tokStart || end > tokEnd {
251+
return nil, 0
252+
}
253+
if nextLine := fset.Position(end).Line + 1; tok.LineCount() >= nextLine {
254+
end = fset.File(f.Pos()).LineStart(nextLine)
250255
}
251256

252257
startLineOffset := fset.Position(start).Line - 1 // lines are 1-indexed.

internal/lsp/source/format_test.go

+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
package source
2+
3+
import (
4+
"go/parser"
5+
"go/token"
6+
"testing"
7+
)
8+
9+
func TestTrimToImports(t *testing.T) {
10+
const input = `package source
11+
12+
import (
13+
m
14+
"fmt"
15+
)
16+
17+
func foo() {
18+
fmt.Println("hi")
19+
}
20+
`
21+
22+
fs := token.NewFileSet()
23+
f, _ := parser.ParseFile(fs, "foo.go", input, parser.ImportsOnly)
24+
trimToImports(fs, f, []byte(input))
25+
}

0 commit comments

Comments
 (0)