Giant blob of minor changes
[dotfiles/.git] / .config / coc / extensions / coc-go-data / tools / pkg / mod / golang.org / x / tools@v0.0.0-20201028153306-37f0764111ff / internal / lsp / source / format.go
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.
4
5 // Package source provides core features for use by Go editors and tools.
6 package source
7
8 import (
9         "bytes"
10         "context"
11         "fmt"
12         "go/ast"
13         "go/format"
14         "go/parser"
15         "go/token"
16         "strings"
17
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"
22 )
23
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")
27         defer done()
28
29         pgf, err := snapshot.ParseGo(ctx, fh, ParseFull)
30         if err != nil {
31                 return nil, err
32         }
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)
38                 if err != nil {
39                         return nil, err
40                 }
41                 return computeTextEdits(ctx, snapshot, pgf, string(formatted))
42         }
43
44         fset := snapshot.FileSet()
45
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 {
52                 return nil, err
53         }
54         formatted := buf.String()
55
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())
60                 if err != nil {
61                         return nil, err
62                 }
63                 formatted = string(b)
64         }
65         return computeTextEdits(ctx, snapshot, pgf, formatted)
66 }
67
68 func formatSource(ctx context.Context, fh FileHandle) ([]byte, error) {
69         _, done := event.Start(ctx, "source.formatSource")
70         defer done()
71
72         data, err := fh.Read()
73         if err != nil {
74                 return nil, err
75         }
76         return format.Source(data)
77 }
78
79 type ImportFix struct {
80         Fix   *imports.ImportFix
81         Edits []protocol.TextEdit
82 }
83
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")
90         defer done()
91
92         pgf, err := snapshot.ParseGo(ctx, fh, ParseFull)
93         if err != nil {
94                 return nil, nil, err
95         }
96         if err := snapshot.RunProcessEnvFunc(ctx, func(opts *imports.Options) error {
97                 allFixEdits, editsPerFix, err = computeImportEdits(snapshot, pgf, opts)
98                 return err
99         }); err != nil {
100                 return nil, nil, fmt.Errorf("AllImportsFixes: %v", err)
101         }
102         return allFixEdits, editsPerFix, nil
103 }
104
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()
109
110         // Build up basic information about the original file.
111         allFixes, err := imports.FixImports(filename, pgf.Src, options)
112         if err != nil {
113                 return nil, nil, err
114         }
115
116         allFixEdits, err = computeFixEdits(snapshot, pgf, options, allFixes)
117         if err != nil {
118                 return nil, nil, err
119         }
120
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})
125                 if err != nil {
126                         return nil, nil, err
127                 }
128                 editsPerFix = append(editsPerFix, &ImportFix{
129                         Fix:   fix,
130                         Edits: edits,
131                 })
132         }
133         return allFixEdits, editsPerFix, nil
134 }
135
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,
140                 // Defaults.
141                 AllErrors:  true,
142                 Comments:   true,
143                 Fragment:   true,
144                 FormatOnly: false,
145                 TabIndent:  true,
146                 TabWidth:   8,
147         }
148         return computeFixEdits(snapshot, pgf, options, []*imports.ImportFix{fix})
149 }
150
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
155         if extra {
156                 left = string(pgf.Src)
157         }
158         if len(left) > 0 && left[len(left)-1] != '\n' {
159                 left += "\n"
160         }
161         // Apply the fixes and re-parse the file so that we can locate the
162         // new imports.
163         flags := parser.ImportsOnly
164         if extra {
165                 // used all of origData above, use all of it here too
166                 flags = 0
167         }
168         fixedData, err := imports.ApplyFixes(fixes, "", pgf.Src, options, flags)
169         if err != nil {
170                 return nil, err
171         }
172         if fixedData == nil || fixedData[len(fixedData)-1] != '\n' {
173                 fixedData = append(fixedData, '\n') // ApplyFixes may miss the newline, go figure.
174         }
175         edits := snapshot.View().Options().ComputeEdits(pgf.URI, left, string(fixedData))
176         return ToProtocolEdits(pgf.Mapper, edits)
177 }
178
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
187                 return ""
188         }
189         tok := fset.File(f.Pos())
190         var importEnd int
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 {
194                                 importEnd = e
195                         }
196                 }
197         }
198
199         maybeAdjustToLineEnd := func(pos token.Pos, isCommentNode bool) int {
200                 offset := tok.Offset(pos)
201
202                 // Don't go past the end of the file.
203                 if offset > len(src) {
204                         offset = len(src)
205                 }
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
217                         }
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.
221                         offset = len(src)
222                 }
223                 return offset
224         }
225         if importEnd == 0 {
226                 pkgEnd := f.Name.End()
227                 importEnd = maybeAdjustToLineEnd(pkgEnd, false)
228         }
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
233                         // end.
234                         endLine := tok.Position(c.End()).Line
235                         if end+2 <= tok.Size() && tok.Position(tok.Pos(end+2)).Line == endLine {
236                                 end += 2
237                         }
238                         importEnd = maybeAdjustToLineEnd(tok.Pos(end), true)
239                 }
240         }
241         if importEnd > len(src) {
242                 importEnd = len(src)
243         }
244         return string(src[:importEnd])
245 }
246
247 func computeTextEdits(ctx context.Context, snapshot Snapshot, pgf *ParsedGoFile, formatted string) ([]protocol.TextEdit, error) {
248         _, done := event.Start(ctx, "source.computeTextEdits")
249         defer done()
250
251         edits := snapshot.View().Options().ComputeEdits(pgf.URI, string(pgf.Src), formatted)
252         return ToProtocolEdits(pgf.Mapper, edits)
253 }
254
255 func ToProtocolEdits(m *protocol.ColumnMapper, edits []diff.TextEdit) ([]protocol.TextEdit, error) {
256         if edits == nil {
257                 return nil, nil
258         }
259         result := make([]protocol.TextEdit, len(edits))
260         for i, edit := range edits {
261                 rng, err := m.Range(edit.Span)
262                 if err != nil {
263                         return nil, err
264                 }
265                 result[i] = protocol.TextEdit{
266                         Range:   rng,
267                         NewText: edit.NewText,
268                 }
269         }
270         return result, nil
271 }
272
273 func FromProtocolEdits(m *protocol.ColumnMapper, edits []protocol.TextEdit) ([]diff.TextEdit, error) {
274         if edits == nil {
275                 return nil, nil
276         }
277         result := make([]diff.TextEdit, len(edits))
278         for i, edit := range edits {
279                 spn, err := m.RangeSpan(edit.Range)
280                 if err != nil {
281                         return nil, err
282                 }
283                 result[i] = diff.TextEdit{
284                         Span:    spn,
285                         NewText: edit.NewText,
286                 }
287         }
288         return result, nil
289 }