Skip to content

Commit

Permalink
gopls/internal/lsp/safetoken: fix error message
Browse files Browse the repository at this point in the history
This change uses [x:y] notation in the error message to indicate
an inclusive interval, which is what the logic actually implements.
We also include the file name.

Also, put the inequalities in lo <= x <= hi form for clarity,
and inline/simplify the token.File.Pos/Offset calls to avoid
the redundant double-check.

Updates golang/go#57484

Change-Id: I63e10d0e6659aae2613b5b7d51e87a8a4bfb225d
Reviewed-on: https://go-review.googlesource.com/c/tools/+/459637
Run-TryBot: Alan Donovan <adonovan@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
Reviewed-by: Robert Findley <rfindley@google.com>
  • Loading branch information
adonovan committed Dec 28, 2022
1 parent 44395ff commit ef1ec5d
Showing 1 changed file with 14 additions and 14 deletions.
28 changes: 14 additions & 14 deletions gopls/internal/lsp/safetoken/safetoken.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,26 +11,26 @@ import (
"go/token"
)

// Offset returns tok.Offset(pos), but first checks that the pos is in range
// Offset returns f.Offset(pos), but first checks that the pos is in range
// for the given file.
func Offset(tf *token.File, pos token.Pos) (int, error) {
if !InRange(tf, pos) {
return -1, fmt.Errorf("pos %v is not in range for file [%v:%v)", pos, tf.Base(), tf.Base()+tf.Size())
func Offset(f *token.File, pos token.Pos) (int, error) {
if !InRange(f, pos) {
return -1, fmt.Errorf("pos %d is not in range [%d:%d] of file %s",
pos, f.Base(), f.Base()+f.Size(), f.Name())
}
return tf.Offset(pos), nil
return int(pos) - f.Base(), nil
}

// Pos returns tok.Pos(offset), but first checks that the offset is valid for
// Pos returns f.Pos(offset), but first checks that the offset is valid for
// the given file.
func Pos(tf *token.File, offset int) (token.Pos, error) {
if offset < 0 || offset > tf.Size() {
return token.NoPos, fmt.Errorf("offset %v is not in range for file of size %v", offset, tf.Size())
func Pos(f *token.File, offset int) (token.Pos, error) {
if !(0 <= offset && offset <= f.Size()) {
return token.NoPos, fmt.Errorf("offset %d is not in range for file %s of size %d", offset, f.Name(), f.Size())
}
return tf.Pos(offset), nil
return token.Pos(f.Base() + offset), nil
}

// InRange reports whether the given position is in the given token.File.
func InRange(tf *token.File, pos token.Pos) bool {
size := tf.Pos(tf.Size())
return int(pos) >= tf.Base() && pos <= size
// InRange reports whether file f contains position pos.
func InRange(f *token.File, pos token.Pos) bool {
return token.Pos(f.Base()) <= pos && pos <= token.Pos(f.Base()+f.Size())
}

0 comments on commit ef1ec5d

Please sign in to comment.