github.com/jd-ly/tools@v0.5.7/internal/lsp/source/format.go (about) 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 "text/scanner" 18 19 "github.com/jd-ly/tools/internal/event" 20 "github.com/jd-ly/tools/internal/imports" 21 "github.com/jd-ly/tools/internal/lsp/diff" 22 "github.com/jd-ly/tools/internal/lsp/protocol" 23 ) 24 25 // Format formats a file with a given range. 26 func Format(ctx context.Context, snapshot Snapshot, fh FileHandle) ([]protocol.TextEdit, error) { 27 ctx, done := event.Start(ctx, "source.Format") 28 defer done() 29 30 pgf, err := snapshot.ParseGo(ctx, fh, ParseFull) 31 if err != nil { 32 return nil, err 33 } 34 // Even if this file has parse errors, it might still be possible to format it. 35 // Using format.Node on an AST with errors may result in code being modified. 36 // Attempt to format the source of this file instead. 37 if pgf.ParseErr != nil { 38 formatted, err := formatSource(ctx, fh) 39 if err != nil { 40 return nil, err 41 } 42 return computeTextEdits(ctx, snapshot, pgf, string(formatted)) 43 } 44 45 fset := snapshot.FileSet() 46 47 // format.Node changes slightly from one release to another, so the version 48 // of Go used to build the LSP server will determine how it formats code. 49 // This should be acceptable for all users, who likely be prompted to rebuild 50 // the LSP server on each Go release. 51 buf := &bytes.Buffer{} 52 if err := format.Node(buf, fset, pgf.File); err != nil { 53 return nil, err 54 } 55 formatted := buf.String() 56 57 // Apply additional formatting, if any is supported. Currently, the only 58 // supported additional formatter is gofumpt. 59 if format := snapshot.View().Options().Hooks.GofumptFormat; snapshot.View().Options().Gofumpt && format != nil { 60 b, err := format(ctx, buf.Bytes()) 61 if err != nil { 62 return nil, err 63 } 64 formatted = string(b) 65 } 66 return computeTextEdits(ctx, snapshot, pgf, formatted) 67 } 68 69 func formatSource(ctx context.Context, fh FileHandle) ([]byte, error) { 70 _, done := event.Start(ctx, "source.formatSource") 71 defer done() 72 73 data, err := fh.Read() 74 if err != nil { 75 return nil, err 76 } 77 return format.Source(data) 78 } 79 80 type ImportFix struct { 81 Fix *imports.ImportFix 82 Edits []protocol.TextEdit 83 } 84 85 // AllImportsFixes formats f for each possible fix to the imports. 86 // In addition to returning the result of applying all edits, 87 // it returns a list of fixes that could be applied to the file, with the 88 // corresponding TextEdits that would be needed to apply that fix. 89 func AllImportsFixes(ctx context.Context, snapshot Snapshot, fh FileHandle) (allFixEdits []protocol.TextEdit, editsPerFix []*ImportFix, err error) { 90 ctx, done := event.Start(ctx, "source.AllImportsFixes") 91 defer done() 92 93 pgf, err := snapshot.ParseGo(ctx, fh, ParseFull) 94 if err != nil { 95 return nil, nil, err 96 } 97 if err := snapshot.RunProcessEnvFunc(ctx, func(opts *imports.Options) error { 98 allFixEdits, editsPerFix, err = computeImportEdits(snapshot, pgf, opts) 99 return err 100 }); err != nil { 101 return nil, nil, fmt.Errorf("AllImportsFixes: %v", err) 102 } 103 return allFixEdits, editsPerFix, nil 104 } 105 106 // computeImportEdits computes a set of edits that perform one or all of the 107 // necessary import fixes. 108 func computeImportEdits(snapshot Snapshot, pgf *ParsedGoFile, options *imports.Options) (allFixEdits []protocol.TextEdit, editsPerFix []*ImportFix, err error) { 109 filename := pgf.URI.Filename() 110 111 // Build up basic information about the original file. 112 allFixes, err := imports.FixImports(filename, pgf.Src, options) 113 if err != nil { 114 return nil, nil, err 115 } 116 117 allFixEdits, err = computeFixEdits(snapshot, pgf, options, allFixes) 118 if err != nil { 119 return nil, nil, err 120 } 121 122 // Apply all of the import fixes to the file. 123 // Add the edits for each fix to the result. 124 for _, fix := range allFixes { 125 edits, err := computeFixEdits(snapshot, pgf, options, []*imports.ImportFix{fix}) 126 if err != nil { 127 return nil, nil, err 128 } 129 editsPerFix = append(editsPerFix, &ImportFix{ 130 Fix: fix, 131 Edits: edits, 132 }) 133 } 134 return allFixEdits, editsPerFix, nil 135 } 136 137 // ComputeOneImportFixEdits returns text edits for a single import fix. 138 func ComputeOneImportFixEdits(snapshot Snapshot, pgf *ParsedGoFile, fix *imports.ImportFix) ([]protocol.TextEdit, error) { 139 options := &imports.Options{ 140 LocalPrefix: snapshot.View().Options().Local, 141 // Defaults. 142 AllErrors: true, 143 Comments: true, 144 Fragment: true, 145 FormatOnly: false, 146 TabIndent: true, 147 TabWidth: 8, 148 } 149 return computeFixEdits(snapshot, pgf, options, []*imports.ImportFix{fix}) 150 } 151 152 func computeFixEdits(snapshot Snapshot, pgf *ParsedGoFile, options *imports.Options, fixes []*imports.ImportFix) ([]protocol.TextEdit, error) { 153 // trim the original data to match fixedData 154 left := importPrefix(pgf.Src) 155 extra := !strings.Contains(left, "\n") // one line may have more than imports 156 if extra { 157 left = string(pgf.Src) 158 } 159 if len(left) > 0 && left[len(left)-1] != '\n' { 160 left += "\n" 161 } 162 // Apply the fixes and re-parse the file so that we can locate the 163 // new imports. 164 flags := parser.ImportsOnly 165 if extra { 166 // used all of origData above, use all of it here too 167 flags = 0 168 } 169 fixedData, err := imports.ApplyFixes(fixes, "", pgf.Src, options, flags) 170 if err != nil { 171 return nil, err 172 } 173 if fixedData == nil || fixedData[len(fixedData)-1] != '\n' { 174 fixedData = append(fixedData, '\n') // ApplyFixes may miss the newline, go figure. 175 } 176 edits := snapshot.View().Options().ComputeEdits(pgf.URI, left, string(fixedData)) 177 return ToProtocolEdits(pgf.Mapper, edits) 178 } 179 180 // importPrefix returns the prefix of the given file content through the final 181 // import statement. If there are no imports, the prefix is the package 182 // statement and any comment groups below it. 183 func importPrefix(src []byte) string { 184 fset := token.NewFileSet() 185 // do as little parsing as possible 186 f, err := parser.ParseFile(fset, "", src, parser.ImportsOnly|parser.ParseComments) 187 if err != nil { // This can happen if 'package' is misspelled 188 return "" 189 } 190 tok := fset.File(f.Pos()) 191 var importEnd int 192 for _, d := range f.Decls { 193 if x, ok := d.(*ast.GenDecl); ok && x.Tok == token.IMPORT { 194 if e := tok.Offset(d.End()); e > importEnd { 195 importEnd = e 196 } 197 } 198 } 199 200 maybeAdjustToLineEnd := func(pos token.Pos, isCommentNode bool) int { 201 offset := tok.Offset(pos) 202 203 // Don't go past the end of the file. 204 if offset > len(src) { 205 offset = len(src) 206 } 207 // The go/ast package does not account for different line endings, and 208 // specifically, in the text of a comment, it will strip out \r\n line 209 // endings in favor of \n. To account for these differences, we try to 210 // return a position on the next line whenever possible. 211 switch line := tok.Line(tok.Pos(offset)); { 212 case line < tok.LineCount(): 213 nextLineOffset := tok.Offset(tok.LineStart(line + 1)) 214 // If we found a position that is at the end of a line, move the 215 // offset to the start of the next line. 216 if offset+1 == nextLineOffset { 217 offset = nextLineOffset 218 } 219 case isCommentNode, offset+1 == tok.Size(): 220 // If the last line of the file is a comment, or we are at the end 221 // of the file, the prefix is the entire file. 222 offset = len(src) 223 } 224 return offset 225 } 226 if importEnd == 0 { 227 pkgEnd := f.Name.End() 228 importEnd = maybeAdjustToLineEnd(pkgEnd, false) 229 } 230 for _, cgroup := range f.Comments { 231 for _, c := range cgroup.List { 232 if end := tok.Offset(c.End()); end > importEnd { 233 startLine := tok.Position(c.Pos()).Line 234 endLine := tok.Position(c.End()).Line 235 236 // Work around golang/go#41197 by checking if the comment might 237 // contain "\r", and if so, find the actual end position of the 238 // comment by scanning the content of the file. 239 startOffset := tok.Offset(c.Pos()) 240 if startLine != endLine && bytes.Contains(src[startOffset:], []byte("\r")) { 241 if commentEnd := scanForCommentEnd(tok, src[startOffset:]); commentEnd > 0 { 242 end = startOffset + commentEnd 243 } 244 } 245 importEnd = maybeAdjustToLineEnd(tok.Pos(end), true) 246 } 247 } 248 } 249 if importEnd > len(src) { 250 importEnd = len(src) 251 } 252 return string(src[:importEnd]) 253 } 254 255 // scanForCommentEnd returns the offset of the end of the multi-line comment 256 // at the start of the given byte slice. 257 func scanForCommentEnd(tok *token.File, src []byte) int { 258 var s scanner.Scanner 259 s.Init(bytes.NewReader(src)) 260 s.Mode ^= scanner.SkipComments 261 262 t := s.Scan() 263 if t == scanner.Comment { 264 return s.Pos().Offset 265 } 266 return 0 267 } 268 269 func computeTextEdits(ctx context.Context, snapshot Snapshot, pgf *ParsedGoFile, formatted string) ([]protocol.TextEdit, error) { 270 _, done := event.Start(ctx, "source.computeTextEdits") 271 defer done() 272 273 edits := snapshot.View().Options().ComputeEdits(pgf.URI, string(pgf.Src), formatted) 274 return ToProtocolEdits(pgf.Mapper, edits) 275 } 276 277 func ToProtocolEdits(m *protocol.ColumnMapper, edits []diff.TextEdit) ([]protocol.TextEdit, error) { 278 if edits == nil { 279 return nil, nil 280 } 281 result := make([]protocol.TextEdit, len(edits)) 282 for i, edit := range edits { 283 rng, err := m.Range(edit.Span) 284 if err != nil { 285 return nil, err 286 } 287 result[i] = protocol.TextEdit{ 288 Range: rng, 289 NewText: edit.NewText, 290 } 291 } 292 return result, nil 293 } 294 295 func FromProtocolEdits(m *protocol.ColumnMapper, edits []protocol.TextEdit) ([]diff.TextEdit, error) { 296 if edits == nil { 297 return nil, nil 298 } 299 result := make([]diff.TextEdit, len(edits)) 300 for i, edit := range edits { 301 spn, err := m.RangeSpan(edit.Range) 302 if err != nil { 303 return nil, err 304 } 305 result[i] = diff.TextEdit{ 306 Span: spn, 307 NewText: edit.NewText, 308 } 309 } 310 return result, nil 311 }