mirror of
https://github.com/golang/go.git
synced 2025-05-07 08:32:59 +00:00
We may encounter these nil pointer if go/packages cannot find the package of the given file, for example, when the user creates a new file or a new package. Change-Id: I16993017243a56332dd9f7e0aaf3c1d57f20fc3a Reviewed-on: https://go-review.googlesource.com/c/tools/+/167462 Run-TryBot: Rebecca Stambler <rstambler@golang.org> Reviewed-by: Ian Cottrell <iancottrell@google.com> TryBot-Result: Gobot Gobot <gobot@golang.org>
60 lines
1.5 KiB
Go
60 lines
1.5 KiB
Go
package lsp
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
|
|
"golang.org/x/tools/internal/lsp/protocol"
|
|
"golang.org/x/tools/internal/lsp/source"
|
|
"golang.org/x/tools/internal/span"
|
|
)
|
|
|
|
// formatRange formats a document with a given range.
|
|
func formatRange(ctx context.Context, v source.View, s span.Span) ([]protocol.TextEdit, error) {
|
|
f, m, err := newColumnMap(ctx, v, s.URI)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
rng := s.Range(m.Converter)
|
|
if rng.Start == rng.End {
|
|
// If we have a single point, assume we want the whole file.
|
|
tok := f.GetToken(ctx)
|
|
if tok == nil {
|
|
return nil, fmt.Errorf("no file information for %s", f.URI())
|
|
}
|
|
rng.End = tok.Pos(tok.Size())
|
|
}
|
|
edits, err := source.Format(ctx, f, rng)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return toProtocolEdits(m, edits), nil
|
|
}
|
|
|
|
func toProtocolEdits(m *protocol.ColumnMapper, edits []source.TextEdit) []protocol.TextEdit {
|
|
if edits == nil {
|
|
return nil
|
|
}
|
|
result := make([]protocol.TextEdit, len(edits))
|
|
for i, edit := range edits {
|
|
result[i] = protocol.TextEdit{
|
|
Range: m.Range(edit.Span),
|
|
NewText: edit.NewText,
|
|
}
|
|
}
|
|
return result
|
|
}
|
|
|
|
func newColumnMap(ctx context.Context, v source.View, uri span.URI) (source.File, *protocol.ColumnMapper, error) {
|
|
f, err := v.GetFile(ctx, uri)
|
|
if err != nil {
|
|
return nil, nil, err
|
|
}
|
|
tok := f.GetToken(ctx)
|
|
if tok == nil {
|
|
return nil, nil, fmt.Errorf("no file information for %v", f.URI())
|
|
}
|
|
m := protocol.NewColumnMapper(f.URI(), f.GetFileSet(ctx), tok, f.GetContent(ctx))
|
|
return f, m, nil
|
|
}
|