Skip to content

Commit

Permalink
internal/lsp: handle panic in fix AST
Browse files Browse the repository at this point in the history
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]>
  • Loading branch information
stamblerre committed Jul 21, 2021
1 parent 6e9046b commit 7aa8294
Showing 1 changed file with 17 additions and 1 deletion.
18 changes: 17 additions & 1 deletion internal/lsp/cache/parse.go
Original file line number Diff line number Diff line change
Expand Up @@ -1070,7 +1070,17 @@ func fixArrayType(bad *ast.BadExpr, parent ast.Node, tok *token.File, src []byte

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

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

// inRange reports whether the given position is in the given token.File.
func inRange(tok *token.File, pos token.Pos) bool {
size := tok.Pos(tok.Size())
return int(pos) >= tok.Base() && pos <= size
}

// precedingToken scans src to find the token preceding pos.
func precedingToken(pos token.Pos, tok *token.File, src []byte) token.Token {
s := &scanner.Scanner{}
Expand Down

0 comments on commit 7aa8294

Please sign in to comment.