1 // Copyright 2018 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
5 // Package source provides core features for use by Go editors and tools.
18 "golang.org/x/tools/internal/event"
19 "golang.org/x/tools/internal/imports"
20 "golang.org/x/tools/internal/lsp/diff"
21 "golang.org/x/tools/internal/lsp/protocol"
24 // Format formats a file with a given range.
25 func Format(ctx context.Context, snapshot Snapshot, fh FileHandle) ([]protocol.TextEdit, error) {
26 ctx, done := event.Start(ctx, "source.Format")
29 pgf, err := snapshot.ParseGo(ctx, fh, ParseFull)
33 // Even if this file has parse errors, it might still be possible to format it.
34 // Using format.Node on an AST with errors may result in code being modified.
35 // Attempt to format the source of this file instead.
36 if pgf.ParseErr != nil {
37 formatted, err := formatSource(ctx, fh)
41 return computeTextEdits(ctx, snapshot, pgf, string(formatted))
44 fset := snapshot.FileSet()
46 // format.Node changes slightly from one release to another, so the version
47 // of Go used to build the LSP server will determine how it formats code.
48 // This should be acceptable for all users, who likely be prompted to rebuild
49 // the LSP server on each Go release.
50 buf := &bytes.Buffer{}
51 if err := format.Node(buf, fset, pgf.File); err != nil {
54 formatted := buf.String()
56 // Apply additional formatting, if any is supported. Currently, the only
57 // supported additional formatter is gofumpt.
58 if format := snapshot.View().Options().Hooks.GofumptFormat; snapshot.View().Options().Gofumpt && format != nil {
59 b, err := format(ctx, buf.Bytes())
65 return computeTextEdits(ctx, snapshot, pgf, formatted)
68 func formatSource(ctx context.Context, fh FileHandle) ([]byte, error) {
69 _, done := event.Start(ctx, "source.formatSource")
72 data, err := fh.Read()
76 return format.Source(data)
79 type ImportFix struct {
80 Fix *imports.ImportFix
81 Edits []protocol.TextEdit
84 // AllImportsFixes formats f for each possible fix to the imports.
85 // In addition to returning the result of applying all edits,
86 // it returns a list of fixes that could be applied to the file, with the
87 // corresponding TextEdits that would be needed to apply that fix.
88 func AllImportsFixes(ctx context.Context, snapshot Snapshot, fh FileHandle) (allFixEdits []protocol.TextEdit, editsPerFix []*ImportFix, err error) {
89 ctx, done := event.Start(ctx, "source.AllImportsFixes")
92 pgf, err := snapshot.ParseGo(ctx, fh, ParseFull)
96 if err := snapshot.RunProcessEnvFunc(ctx, func(opts *imports.Options) error {
97 allFixEdits, editsPerFix, err = computeImportEdits(snapshot, pgf, opts)
100 return nil, nil, fmt.Errorf("AllImportsFixes: %v", err)
102 return allFixEdits, editsPerFix, nil
105 // computeImportEdits computes a set of edits that perform one or all of the
106 // necessary import fixes.
107 func computeImportEdits(snapshot Snapshot, pgf *ParsedGoFile, options *imports.Options) (allFixEdits []protocol.TextEdit, editsPerFix []*ImportFix, err error) {
108 filename := pgf.URI.Filename()
110 // Build up basic information about the original file.
111 allFixes, err := imports.FixImports(filename, pgf.Src, options)
116 allFixEdits, err = computeFixEdits(snapshot, pgf, options, allFixes)
121 // Apply all of the import fixes to the file.
122 // Add the edits for each fix to the result.
123 for _, fix := range allFixes {
124 edits, err := computeFixEdits(snapshot, pgf, options, []*imports.ImportFix{fix})
128 editsPerFix = append(editsPerFix, &ImportFix{
133 return allFixEdits, editsPerFix, nil
136 // ComputeOneImportFixEdits returns text edits for a single import fix.
137 func ComputeOneImportFixEdits(snapshot Snapshot, pgf *ParsedGoFile, fix *imports.ImportFix) ([]protocol.TextEdit, error) {
138 options := &imports.Options{
139 LocalPrefix: snapshot.View().Options().Local,
148 return computeFixEdits(snapshot, pgf, options, []*imports.ImportFix{fix})
151 func computeFixEdits(snapshot Snapshot, pgf *ParsedGoFile, options *imports.Options, fixes []*imports.ImportFix) ([]protocol.TextEdit, error) {
152 // trim the original data to match fixedData
153 left := importPrefix(pgf.Src)
154 extra := !strings.Contains(left, "\n") // one line may have more than imports
156 left = string(pgf.Src)
158 if len(left) > 0 && left[len(left)-1] != '\n' {
161 // Apply the fixes and re-parse the file so that we can locate the
163 flags := parser.ImportsOnly
165 // used all of origData above, use all of it here too
168 fixedData, err := imports.ApplyFixes(fixes, "", pgf.Src, options, flags)
172 if fixedData == nil || fixedData[len(fixedData)-1] != '\n' {
173 fixedData = append(fixedData, '\n') // ApplyFixes may miss the newline, go figure.
175 edits := snapshot.View().Options().ComputeEdits(pgf.URI, left, string(fixedData))
176 return ToProtocolEdits(pgf.Mapper, edits)
179 // importPrefix returns the prefix of the given file content through the final
180 // import statement. If there are no imports, the prefix is the package
181 // statement and any comment groups below it.
182 func importPrefix(src []byte) string {
183 fset := token.NewFileSet()
184 // do as little parsing as possible
185 f, err := parser.ParseFile(fset, "", src, parser.ImportsOnly|parser.ParseComments)
186 if err != nil { // This can happen if 'package' is misspelled
189 tok := fset.File(f.Pos())
191 for _, d := range f.Decls {
192 if x, ok := d.(*ast.GenDecl); ok && x.Tok == token.IMPORT {
193 if e := tok.Offset(d.End()); e > importEnd {
199 maybeAdjustToLineEnd := func(pos token.Pos, isCommentNode bool) int {
200 offset := tok.Offset(pos)
202 // Don't go past the end of the file.
203 if offset > len(src) {
206 // The go/ast package does not account for different line endings, and
207 // specifically, in the text of a comment, it will strip out \r\n line
208 // endings in favor of \n. To account for these differences, we try to
209 // return a position on the next line whenever possible.
210 switch line := tok.Line(tok.Pos(offset)); {
211 case line < tok.LineCount():
212 nextLineOffset := tok.Offset(tok.LineStart(line + 1))
213 // If we found a position that is at the end of a line, move the
214 // offset to the start of the next line.
215 if offset+1 == nextLineOffset {
216 offset = nextLineOffset
218 case isCommentNode, offset+1 == tok.Size():
219 // If the last line of the file is a comment, or we are at the end
220 // of the file, the prefix is the entire file.
226 pkgEnd := f.Name.End()
227 importEnd = maybeAdjustToLineEnd(pkgEnd, false)
229 for _, c := range f.Comments {
230 if end := tok.Offset(c.End()); end > importEnd {
231 // Work-around golang/go#41197: For multi-line comments add +2 to
232 // the offset. The end position does not account for the */ at the
234 endLine := tok.Position(c.End()).Line
235 if end+2 <= tok.Size() && tok.Position(tok.Pos(end+2)).Line == endLine {
238 importEnd = maybeAdjustToLineEnd(tok.Pos(end), true)
241 if importEnd > len(src) {
244 return string(src[:importEnd])
247 func computeTextEdits(ctx context.Context, snapshot Snapshot, pgf *ParsedGoFile, formatted string) ([]protocol.TextEdit, error) {
248 _, done := event.Start(ctx, "source.computeTextEdits")
251 edits := snapshot.View().Options().ComputeEdits(pgf.URI, string(pgf.Src), formatted)
252 return ToProtocolEdits(pgf.Mapper, edits)
255 func ToProtocolEdits(m *protocol.ColumnMapper, edits []diff.TextEdit) ([]protocol.TextEdit, error) {
259 result := make([]protocol.TextEdit, len(edits))
260 for i, edit := range edits {
261 rng, err := m.Range(edit.Span)
265 result[i] = protocol.TextEdit{
267 NewText: edit.NewText,
273 func FromProtocolEdits(m *protocol.ColumnMapper, edits []protocol.TextEdit) ([]diff.TextEdit, error) {
277 result := make([]diff.TextEdit, len(edits))
278 for i, edit := range edits {
279 spn, err := m.RangeSpan(edit.Range)
283 result[i] = diff.TextEdit{
285 NewText: edit.NewText,