1
0
mirror of https://github.com/golang/go synced 2024-10-01 03:28:32 -06:00
go/internal/lsp/format.go
Ian Cottrell 2f43c6d1a2 internal/span: change to private fields
Change span to hide its fields and have validating accessors
This catches the cases where either the offset or the position is being used
when it was not set.
It also normalizes the forms as the API now controls them, and allows us to
simplify some of the logic.
The converters are now allowed to return an error, which lets us cleanly
propagate bad cases.
The lsp was then converted to the new format, and also had some error checking
of its own added on the top.
All this allowed me to find and fix a few issues, most notably a case where the
wrong column mapper was being used during the conversion of definition results.

Change-Id: Iebdf8901e8269b28aaef60caf76574baa25c46d4
Reviewed-on: https://go-review.googlesource.com/c/tools/+/167858
Run-TryBot: Ian Cottrell <iancottrell@google.com>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Reviewed-by: Rebecca Stambler <rstambler@golang.org>
2019-03-15 18:05:47 +00:00

67 lines
1.6 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, err := s.Range(m.Converter)
if err != nil {
return nil, err
}
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)
}
func toProtocolEdits(m *protocol.ColumnMapper, edits []source.TextEdit) ([]protocol.TextEdit, error) {
if edits == nil {
return nil, nil
}
result := make([]protocol.TextEdit, len(edits))
for i, edit := range edits {
rng, err := m.Range(edit.Span)
if err != nil {
return nil, err
}
result[i] = protocol.TextEdit{
Range: rng,
NewText: edit.NewText,
}
}
return result, nil
}
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
}