Debian Codegraph @

gopls/internal/golang/format.go

raw symbols SCIP
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 golang defines the LSP features for navigation, analysis,
6 // and refactoring of Go source code.
7 package golang
8
9 import (
10 "bytes"
11 "context"
12 "fmt"
13 "go/ast"
14 "go/format"
15 "go/parser"
16 "go/token"
17 "strings"
18 "text/scanner"
19
20 "golang.org/x/tools/gopls/internal/cache"
21 "golang.org/x/tools/gopls/internal/cache/parsego"
22 "golang.org/x/tools/gopls/internal/file"
23 "golang.org/x/tools/gopls/internal/protocol"
24 "golang.org/x/tools/gopls/internal/util/safetoken"
25 "golang.org/x/tools/gopls/internal/util/tokeninternal"
26 "golang.org/x/tools/internal/diff"
27 "golang.org/x/tools/internal/event"
28 "golang.org/x/tools/internal/imports"
29 gofumptFormat "mvdan.cc/gofumpt/format"
30 )
31
32 // Format formats a file with a given range.
33 func Format(ctx context.Context, snapshot *cache.Snapshot, fh file.Handle) ([]protocol.TextEdit, error) {
34 ctx, done := event.Start(ctx, "golang.Format")
35 defer done()
36
37 pgf, err := snapshot.ParseGo(ctx, fh, parsego.Full)
38 if err != nil {
39 return nil, err
40 }
41
42 // Even if this file has parse errors, it might still be possible to format it.
43 // Using format.Node on an AST with errors may result in code being modified.
44 // Attempt to format the source of this file instead.
45 if pgf.ParseErr != nil {
46 formatted, err := formatSource(ctx, fh)
47 if err != nil {
48 return nil, err
49 }
50 return computeTextEdits(ctx, pgf, string(formatted))
51 }
52
53 // format.Node changes slightly from one release to another, so the version
54 // of Go used to build the LSP server will determine how it formats code.
55 // This should be acceptable for all users, who likely be prompted to rebuild
56 // the LSP server on each Go release.
57 buf := &bytes.Buffer{}
58 fset := tokeninternal.FileSetFor(pgf.Tok)
59 if err := format.Node(buf, fset, pgf.File); err != nil {
60 return nil, err
61 }
62 formatted := buf.String()
63
64 // Apply additional formatting, if any is supported. Currently, the only
65 // supported additional formatter is gofumpt.
66 if snapshot.Options().Gofumpt {
67 // gofumpt can customize formatting based on language version and module
68 // path, if available.
69 //
70 // Try to derive this information, but fall-back on the default behavior.
71 //
72 // TODO: under which circumstances can we fail to find module information?
73 // Can this, for example, result in inconsistent formatting across saves,
74 // due to pending calls to packages.Load?
75 var opts gofumptFormat.Options
76 meta, err := snapshot.NarrowestMetadataForFile(ctx, fh.URI())
77 if err == nil {
78 if mi := meta.Module; mi != nil {
79 if v := mi.GoVersion; v != "" {
80 opts.LangVersion = "go" + v
81 }
82 opts.ModulePath = mi.Path
83 }
84 }
85 b, err := gofumptFormat.Source(buf.Bytes(), opts)
86 if err != nil {
87 return nil, err
88 }
89 formatted = string(b)
90 }
91 return computeTextEdits(ctx, pgf, formatted)
92 }
93
94 func formatSource(ctx context.Context, fh file.Handle) ([]byte, error) {
95 _, done := event.Start(ctx, "golang.formatSource")
96 defer done()
97
98 data, err := fh.Content()
99 if err != nil {
100 return nil, err
101 }
102 return format.Source(data)
103 }
104
105 type importFix struct {
106 fix *imports.ImportFix
107 edits []protocol.TextEdit
108 }
109
110 // allImportsFixes formats f for each possible fix to the imports.
111 // In addition to returning the result of applying all edits,
112 // it returns a list of fixes that could be applied to the file, with the
113 // corresponding TextEdits that would be needed to apply that fix.
114 func allImportsFixes(ctx context.Context, snapshot *cache.Snapshot, pgf *parsego.File) (allFixEdits []protocol.TextEdit, editsPerFix []*importFix, err error) {
115 ctx, done := event.Start(ctx, "golang.allImportsFixes")
116 defer done()
117
118 if err := snapshot.RunProcessEnvFunc(ctx, func(ctx context.Context, opts *imports.Options) error {
119 allFixEdits, editsPerFix, err = computeImportEdits(ctx, pgf, snapshot, opts)
120 return err
121 }); err != nil {
122 return nil, nil, fmt.Errorf("allImportsFixes: %v", err)
123 }
124 return allFixEdits, editsPerFix, nil
125 }
126
127 // computeImportEdits computes a set of edits that perform one or all of the
128 // necessary import fixes.
129 func computeImportEdits(ctx context.Context, pgf *parsego.File, snapshot *cache.Snapshot, options *imports.Options) (allFixEdits []protocol.TextEdit, editsPerFix []*importFix, err error) {
130 goroot := snapshot.View().Folder().Env.GOROOT
131 filename := pgf.URI.Path()
132
133 source := snapshot.NewGoplsSource()
134 // imports require a current metadata graph
135 // TODO(rfindley): improve the API
136 snapshot.WorkspaceMetadata(ctx) // ignore error
137 allFixes, err := imports.FixImports(ctx, filename, pgf.Src, goroot, options.Env.Logf, source)
138 if err != nil {
139 return nil, nil, err
140 }
141
142 allFixEdits, err = computeFixEdits(pgf.Src, options, allFixes)
143 if err != nil {
144 return nil, nil, err
145 }
146
147 // Apply all of the import fixes to the file.
148 // Add the edits for each fix to the result.
149 for _, fix := range allFixes {
150 edits, err := computeFixEdits(pgf.Src, options, []*imports.ImportFix{fix})
151 if err != nil {
152 return nil, nil, err
153 }
154 editsPerFix = append(editsPerFix, &importFix{
155 fix: fix,
156 edits: edits,
157 })
158 }
159 return allFixEdits, editsPerFix, nil
160 }
161
162 // ComputeImportFixEdits returns text edits for a single import fix.
163 func ComputeImportFixEdits(localPrefix string, src []byte, fixes ...*imports.ImportFix) ([]protocol.TextEdit, error) {
164 options := &imports.Options{
165 LocalPrefix: localPrefix,
166 // Defaults.
167 AllErrors: true,
168 Comments: true,
169 Fragment: true,
170 FormatOnly: false,
171 TabIndent: true,
172 TabWidth: 8,
173 }
174 return computeFixEdits(src, options, fixes)
175 }
176
177 func computeFixEdits(src []byte, options *imports.Options, fixes []*imports.ImportFix) ([]protocol.TextEdit, error) {
178 // trim the original data to match fixedData
179 left, err := importPrefix(src)
180 if err != nil {
181 return nil, err
182 }
183 extra := !strings.Contains(left, "\n") // one line may have more than imports
184 if extra {
185 left = string(src)
186 }
187 if len(left) > 0 && left[len(left)-1] != '\n' {
188 left += "\n"
189 }
190 // Apply the fixes and re-parse the file so that we can locate the
191 // new imports.
192 flags := parser.ImportsOnly
193 if extra {
194 // used all of origData above, use all of it here too
195 flags = 0
196 }
197 fixedData, err := imports.ApplyFixes(fixes, "", src, options, flags)
198 if err != nil {
199 return nil, err
200 }
201 if fixedData == nil || fixedData[len(fixedData)-1] != '\n' {
202 fixedData = append(fixedData, '\n') // ApplyFixes may miss the newline, go figure.
203 }
204 edits := diff.Strings(left, string(fixedData))
205 return protocolEditsFromSource([]byte(left), edits)
206 }
207
208 // importPrefix returns the prefix of the given file content through the final
209 // import statement. If there are no imports, the prefix is the package
210 // statement and any comment groups below it.
211 func importPrefix(src []byte) (string, error) {
212 fset := token.NewFileSet()
213 // do as little parsing as possible
214 f, err := parser.ParseFile(fset, "", src, parser.ImportsOnly|parser.ParseComments)
215 if err != nil { // This can happen if 'package' is misspelled
216 return "", fmt.Errorf("importPrefix: failed to parse: %s", err)
217 }
218 tok := fset.File(f.FileStart)
219 var importEnd int
220 for _, d := range f.Decls {
221 if x, ok := d.(*ast.GenDecl); ok && x.Tok == token.IMPORT {
222 if e, err := safetoken.Offset(tok, d.End()); err != nil {
223 return "", fmt.Errorf("importPrefix: %s", err)
224 } else if e > importEnd {
225 importEnd = e
226 }
227 }
228 }
229
230 maybeAdjustToLineEnd := func(pos token.Pos, isCommentNode bool) int {
231 offset, err := safetoken.Offset(tok, pos)
232 if err != nil {
233 return -1
234 }
235
236 // Don't go past the end of the file.
237 if offset > len(src) {
238 offset = len(src)
239 }
240 // The go/ast package does not account for different line endings, and
241 // specifically, in the text of a comment, it will strip out \r\n line
242 // endings in favor of \n. To account for these differences, we try to
243 // return a position on the next line whenever possible.
244 switch line := safetoken.Line(tok, tok.Pos(offset)); {
245 case line < tok.LineCount():
246 nextLineOffset, err := safetoken.Offset(tok, tok.LineStart(line+1))
247 if err != nil {
248 return -1
249 }
250 // If we found a position that is at the end of a line, move the
251 // offset to the start of the next line.
252 if offset+1 == nextLineOffset {
253 offset = nextLineOffset
254 }
255 case isCommentNode, offset+1 == tok.Size():
256 // If the last line of the file is a comment, or we are at the end
257 // of the file, the prefix is the entire file.
258 offset = len(src)
259 }
260 return offset
261 }
262 if importEnd == 0 {
263 pkgEnd := f.Name.End()
264 importEnd = maybeAdjustToLineEnd(pkgEnd, false)
265 }
266 for _, cgroup := range f.Comments {
267 for _, c := range cgroup.List {
268 if end, err := safetoken.Offset(tok, c.End()); err != nil {
269 return "", err
270 } else if end > importEnd {
271 startLine := safetoken.Position(tok, c.Pos()).Line
272 endLine := safetoken.Position(tok, c.End()).Line
273
274 // Work around golang/go#41197 by checking if the comment might
275 // contain "\r", and if so, find the actual end position of the
276 // comment by scanning the content of the file.
277 startOffset, err := safetoken.Offset(tok, c.Pos())
278 if err != nil {
279 return "", err
280 }
281 if startLine != endLine && bytes.Contains(src[startOffset:], []byte("\r")) {
282 if commentEnd := scanForCommentEnd(src[startOffset:]); commentEnd > 0 {
283 end = startOffset + commentEnd
284 }
285 }
286 importEnd = maybeAdjustToLineEnd(tok.Pos(end), true)
287 }
288 }
289 }
290 if importEnd > len(src) {
291 importEnd = len(src)
292 }
293 return string(src[:importEnd]), nil
294 }
295
296 // scanForCommentEnd returns the offset of the end of the multi-line comment
297 // at the start of the given byte slice.
298 func scanForCommentEnd(src []byte) int {
299 var s scanner.Scanner
300 s.Init(bytes.NewReader(src))
301 s.Mode ^= scanner.SkipComments
302
303 t := s.Scan()
304 if t == scanner.Comment {
305 return s.Pos().Offset
306 }
307 return 0
308 }
309
310 func computeTextEdits(ctx context.Context, pgf *parsego.File, formatted string) ([]protocol.TextEdit, error) {
311 _, done := event.Start(ctx, "golang.computeTextEdits")
312 defer done()
313
314 edits := diff.Strings(string(pgf.Src), formatted)
315 return protocol.EditsFromDiffEdits(pgf.Mapper, edits)
316 }
317
318 // protocolEditsFromSource converts text edits to LSP edits using the original
319 // source.
320 func protocolEditsFromSource(src []byte, edits []diff.Edit) ([]protocol.TextEdit, error) {
321 m := protocol.NewMapper("", src)
322 var result []protocol.TextEdit
323 for _, edit := range edits {
324 rng, err := m.OffsetRange(edit.Start, edit.End)
325 if err != nil {
326 return nil, err
327 }
328
329 if rng.Start == rng.End && edit.New == "" {
330 // Degenerate case, which may result from a diff tool wanting to delete
331 // '\r' in line endings. Filter it out.
332 continue
333 }
334 result = append(result, protocol.TextEdit{
335 Range: rng,
336 NewText: edit.New,
337 })
338 }
339 return result, nil
340 }