Skip to content

Commit 7aa8294

Browse files
committed
internal/lsp: handle panic in fix AST
I'm not sure how this can happen, but it seems possible that a bad expression might somehow have an invalid position. Fixes golang/go#47231 Change-Id: I0794bdfb66f668fc375e9fe561c9f239c8b92492 Reviewed-on: https://go-review.googlesource.com/c/tools/+/334892 Trust: Rebecca Stambler <[email protected]> Run-TryBot: Rebecca Stambler <[email protected]> gopls-CI: kokoro <[email protected]> TryBot-Result: Go Bot <[email protected]> Reviewed-by: Robert Findley <[email protected]>
1 parent 6e9046b commit 7aa8294

File tree

1 file changed

+17
-1
lines changed

1 file changed

+17
-1
lines changed

internal/lsp/cache/parse.go

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1070,7 +1070,17 @@ func fixArrayType(bad *ast.BadExpr, parent ast.Node, tok *token.File, src []byte
10701070

10711071
exprBytes := make([]byte, 0, int(to-from)+3)
10721072
// Avoid doing tok.Offset(to) since that panics if badExpr ends at EOF.
1073-
exprBytes = append(exprBytes, src[tok.Offset(from):tok.Offset(to-1)+1]...)
1073+
// It also panics if the position is not in the range of the file, and
1074+
// badExprs may not necessarily have good positions, so check first.
1075+
if !inRange(tok, from) {
1076+
return false
1077+
}
1078+
if !inRange(tok, to-1) {
1079+
return false
1080+
}
1081+
fromOffset := tok.Offset(from)
1082+
toOffset := tok.Offset(to-1) + 1
1083+
exprBytes = append(exprBytes, src[fromOffset:toOffset]...)
10741084
exprBytes = bytes.TrimSpace(exprBytes)
10751085

10761086
// If our expression ends in "]" (e.g. "[]"), add a phantom selector
@@ -1102,6 +1112,12 @@ func fixArrayType(bad *ast.BadExpr, parent ast.Node, tok *token.File, src []byte
11021112
return replaceNode(parent, bad, at)
11031113
}
11041114

1115+
// inRange reports whether the given position is in the given token.File.
1116+
func inRange(tok *token.File, pos token.Pos) bool {
1117+
size := tok.Pos(tok.Size())
1118+
return int(pos) >= tok.Base() && pos <= size
1119+
}
1120+
11051121
// precedingToken scans src to find the token preceding pos.
11061122
func precedingToken(pos token.Pos, tok *token.File, src []byte) token.Token {
11071123
s := &scanner.Scanner{}

0 commit comments

Comments
 (0)