Debian Codegraph @

format/format.go

raw symbols SCIP
1 // Copyright (c) 2019, Daniel Martí <[email protected]>
2 // See LICENSE for licensing information
3
4 // Package format exposes gofumpt's formatting in an API similar to go/format.
5 // In general, the APIs are only guaranteed to work well when the input source
6 // is in canonical gofmt format.
7 package format
8
9 import (
10 "bytes"
11 "fmt"
12 "go/ast"
13 "go/parser"
14 "go/token"
15 "os"
16 "reflect"
17 "regexp"
18 "sort"
19 "strconv"
20 "strings"
21 "unicode"
22 "unicode/utf8"
23
24 "github.com/google/go-cmp/cmp"
25 "golang.org/x/mod/semver"
26 "golang.org/x/tools/go/ast/astutil"
27
28 "mvdan.cc/gofumpt/internal/govendor/go/format"
29 "mvdan.cc/gofumpt/internal/version"
30 )
31
32 // Options is the set of formatting options which affect gofumpt.
33 type Options struct {
34 // TODO: link to the go/version docs once Go 1.22 is out.
35 // The old semver docs said:
36 //
37 // LangVersion is treated as a semantic version, which may start with a "v"
38 // prefix. Like Go versions, it may also be incomplete; "1.14" is equivalent
39 // to "1.14.0". When empty, it is equivalent to "v1", to not use language
40 // features which could break programs.
41
42 // LangVersion is the Go version a piece of code is written in.
43 // The version is used to decide whether to apply formatting
44 // rules which require new language features.
45 // When inside a Go module, LangVersion should typically be:
46 //
47 // go mod edit -json | jq -r '.Go'
48 LangVersion string
49
50 // ModulePath corresponds to the Go module path which contains the source
51 // code being formatted. When inside a Go module, ModulePath should be:
52 //
53 // go mod edit -json | jq -r '.Module.Path'
54 //
55 // ModulePath is used for formatting decisions like what import paths are
56 // considered to be not part of the standard library. When empty, the source
57 // is formatted as if it weren't inside a module.
58 ModulePath string
59
60 // ExtraRules enables extra formatting rules, such as grouping function
61 // parameters with repeated types together.
62 ExtraRules bool
63 }
64
65 // Source formats src in gofumpt's format, assuming that src holds a valid Go
66 // source file.
67 func Source(src []byte, opts Options) ([]byte, error) {
68 fset := token.NewFileSet()
69
70 // Ensure our parsed files never start with base 1,
71 // to ensure that using token.NoPos+1 will panic.
72 fset.AddFile("gofumpt_base.go", 1, 10)
73
74 file, err := parser.ParseFile(fset, "", src, parser.SkipObjectResolution|parser.ParseComments)
75 if err != nil {
76 return nil, err
77 }
78
79 File(fset, file, opts)
80
81 var buf bytes.Buffer
82 if err := format.Node(&buf, fset, file); err != nil {
83 return nil, err
84 }
85 return buf.Bytes(), nil
86 }
87
88 var rxGoVersionMajorMinor = regexp.MustCompile(`^(v|go)?([1-9]+)\.([0-9]+)`)
89
90 // File modifies a file and fset in place to follow gofumpt's format. The
91 // changes might include manipulating adding or removing newlines in fset,
92 // modifying the position of nodes, or modifying literal values.
93 func File(fset *token.FileSet, file *ast.File, opts Options) {
94 simplify(file)
95
96 // TODO: replace this hacky mess with go/version once we can rely on Go 1.22,
97 // as well as replacing our uses of the semver package.
98 // In particular, we likely want to allow any of 1.21, 1.21.2, or go1.21rc3,
99 // but we can rely on go/version.Lang to validate and normalize.
100 if opts.LangVersion == "" {
101 opts.LangVersion = "v1.0"
102 }
103 m := rxGoVersionMajorMinor.FindStringSubmatch(opts.LangVersion)
104 if m == nil {
105 panic(fmt.Sprintf("invalid Go version: %q", opts.LangVersion))
106 }
107 opts.LangVersion = "v" + m[2] + "." + m[3]
108 f := &fumpter{
109 file: fset.File(file.Pos()),
110 fset: fset,
111 astFile: file,
112 Options: opts,
113
114 minSplitFactor: 0.4,
115 }
116 var topFuncType *ast.FuncType
117 pre := func(c *astutil.Cursor) bool {
118 f.applyPre(c)
119 switch node := c.Node().(type) {
120 case *ast.FuncDecl:
121 topFuncType = node.Type
122 case *ast.FieldList:
123 ft, _ := c.Parent().(*ast.FuncType)
124 if ft == nil || ft != topFuncType {
125 break
126 }
127
128 // For top-level function declaration parameters,
129 // require the line split to be longer.
130 // This avoids func lines which are a bit too short,
131 // and allows func lines which are a bit longer.
132 //
133 // We don't just increase longLineLimit,
134 // as we still want splits at around the same place.
135 if ft.Params == node {
136 f.minSplitFactor = 0.6
137 }
138
139 // Don't split result parameters into multiple lines,
140 // as that can be easily confused for input parameters.
141 // TODO: consider the same for single-line func calls in
142 // if statements.
143 // TODO: perhaps just use a higher factor, like 0.8.
144 if ft.Results == node {
145 f.minSplitFactor = 1000
146 }
147 case *ast.BlockStmt:
148 f.blockLevel++
149 }
150 return true
151 }
152 post := func(c *astutil.Cursor) bool {
153 f.applyPost(c)
154
155 // Reset minSplitFactor and blockLevel.
156 switch node := c.Node().(type) {
157 case *ast.FuncType:
158 if node == topFuncType {
159 f.minSplitFactor = 0.4
160 }
161 case *ast.BlockStmt:
162 f.blockLevel--
163 }
164 return true
165 }
166 astutil.Apply(file, pre, post)
167 }
168
169 // Multiline nodes which could easily fit on a single line under this many bytes
170 // may be collapsed onto a single line.
171 const shortLineLimit = 60
172
173 // Single-line nodes which take over this many bytes, and could easily be split
174 // into two lines of at least its minSplitFactor factor, may be split.
175 const longLineLimit = 100
176
177 var rxOctalInteger = regexp.MustCompile(`\A0[0-7_]+\z`)
178
179 type fumpter struct {
180 Options
181
182 file *token.File
183 fset *token.FileSet
184
185 astFile *ast.File
186
187 // blockLevel is the number of indentation blocks we're currently under.
188 // It is used to approximate the levels of indentation a line will end
189 // up with.
190 blockLevel int
191
192 minSplitFactor float64
193 }
194
195 func (f *fumpter) commentsBetween(p1, p2 token.Pos) []*ast.CommentGroup {
196 comments := f.astFile.Comments
197 i1 := sort.Search(len(comments), func(i int) bool {
198 return comments[i].Pos() >= p1
199 })
200 comments = comments[i1:]
201 i2 := sort.Search(len(comments), func(i int) bool {
202 return comments[i].Pos() >= p2
203 })
204 comments = comments[:i2]
205 return comments
206 }
207
208 func (f *fumpter) inlineComment(pos token.Pos) *ast.Comment {
209 comments := f.astFile.Comments
210 i := sort.Search(len(comments), func(i int) bool {
211 return comments[i].Pos() >= pos
212 })
213 if i >= len(comments) {
214 return nil
215 }
216 line := f.Line(pos)
217 for _, comment := range comments[i].List {
218 if f.Line(comment.Pos()) == line {
219 return comment
220 }
221 }
222 return nil
223 }
224
225 // addNewline is a hack to let us force a newline at a certain position.
226 func (f *fumpter) addNewline(at token.Pos) {
227 offset := f.Offset(at)
228
229 // TODO: replace with the new Lines method once we require Go 1.21 or later
230 field := reflect.ValueOf(f.file).Elem().FieldByName("lines")
231 n := field.Len()
232 lines := make([]int, 0, n+1)
233 for i := 0; i < n; i++ {
234 cur := int(field.Index(i).Int())
235 if offset == cur {
236 // This newline already exists; do nothing. Duplicate
237 // newlines can't exist.
238 return
239 }
240 if offset >= 0 && offset < cur {
241 lines = append(lines, offset)
242 offset = -1
243 }
244 lines = append(lines, cur)
245 }
246 if offset >= 0 {
247 lines = append(lines, offset)
248 }
249 if !f.file.SetLines(lines) {
250 panic(fmt.Sprintf("could not set lines to %v", lines))
251 }
252 }
253
254 // removeLines removes all newlines between two positions, so that they end
255 // up on the same line.
256 func (f *fumpter) removeLines(fromLine, toLine int) {
257 for fromLine < toLine {
258 f.file.MergeLine(fromLine)
259 toLine--
260 }
261 }
262
263 // removeLinesBetween is like removeLines, but it leaves one newline between the
264 // two positions.
265 func (f *fumpter) removeLinesBetween(from, to token.Pos) {
266 f.removeLines(f.Line(from)+1, f.Line(to))
267 }
268
269 func (f *fumpter) Position(p token.Pos) token.Position {
270 return f.file.PositionFor(p, false)
271 }
272
273 func (f *fumpter) Line(p token.Pos) int {
274 return f.Position(p).Line
275 }
276
277 func (f *fumpter) Offset(p token.Pos) int {
278 return f.file.Offset(p)
279 }
280
281 type byteCounter int
282
283 func (b *byteCounter) Write(p []byte) (n int, err error) {
284 *b += byteCounter(len(p))
285 return len(p), nil
286 }
287
288 func (f *fumpter) printLength(node ast.Node) int {
289 var count byteCounter
290 if err := format.Node(&count, f.fset, node); err != nil {
291 panic(fmt.Sprintf("unexpected print error: %v", err))
292 }
293
294 // Add the space taken by an inline comment.
295 if c := f.inlineComment(node.End()); c != nil {
296 fmt.Fprintf(&count, " %s", c.Text)
297 }
298
299 // Add an approximation of the indentation level. We can't know the
300 // number of tabs go/printer will add ahead of time. Trying to print the
301 // entire top-level declaration would tell us that, but then it's near
302 // impossible to reliably find our node again.
303 return int(count) + (f.blockLevel * 8)
304 }
305
306 func (f *fumpter) lineEnd(line int) token.Pos {
307 if line < 1 {
308 panic("illegal line number")
309 }
310 total := f.file.LineCount()
311 if line > total {
312 panic("illegal line number")
313 }
314 if line == total {
315 return f.astFile.End()
316 }
317 return f.file.LineStart(line+1) - 1
318 }
319
320 // rxCommentDirective covers all common Go comment directives:
321 //
322 // //go: | standard Go directives, like go:noinline
323 // //some-words: | similar to the syntax above, like lint:ignore or go-sumtype:decl
324 // //line | inserted line information for cmd/compile
325 // //export | to mark cgo funcs for exporting
326 // //extern | C function declarations for gccgo
327 // //sys(nb)? | syscall function wrapper prototypes
328 // //nolint | nolint directive for golangci
329 // //noinspection | noinspection directive for GoLand and friends
330 // //NOSONAR | NOSONAR directive for SonarQube
331 //
332 // Note that the "some-words:" matching expects a letter afterward, such as
333 // "go:generate", to prevent matching false positives like "https://site".
334 var rxCommentDirective = regexp.MustCompile(`^([a-z-]+:[a-z]+|line\b|export\b|extern\b|sys(nb)?\b|no(lint|inspection)\b)|NOSONAR\b`)
335
336 func (f *fumpter) applyPre(c *astutil.Cursor) {
337 f.splitLongLine(c)
338
339 switch node := c.Node().(type) {
340 case *ast.File:
341 // Join contiguous lone var/const/import lines.
342 // Abort if there are empty lines in between,
343 // including a leading comment if it's a directive.
344 newDecls := make([]ast.Decl, 0, len(node.Decls))
345 for i := 0; i < len(node.Decls); {
346 newDecls = append(newDecls, node.Decls[i])
347 start, ok := node.Decls[i].(*ast.GenDecl)
348 if !ok || isCgoImport(start) || containsAnyDirective(start.Doc) {
349 i++
350 continue
351 }
352 lastPos := start.Pos()
353 contLoop:
354 for i++; i < len(node.Decls); {
355 cont, ok := node.Decls[i].(*ast.GenDecl)
356 if !ok || cont.Tok != start.Tok || cont.Lparen != token.NoPos || isCgoImport(cont) {
357 break
358 }
359 // Are there things between these two declarations? e.g. empty lines, comments, directives
360 // If so, break the chain on empty lines and directives, continue below for comments.
361 if f.Line(lastPos) < f.Line(cont.Pos())-1 {
362 // break on empty line
363 if cont.Doc == nil {
364 break
365 }
366 // break on directive
367 for i, comment := range cont.Doc.List {
368 if f.Line(comment.Slash) != f.Line(lastPos)+1+i || rxCommentDirective.MatchString(strings.TrimPrefix(comment.Text, "//")) {
369 break contLoop
370 }
371 }
372 // continue below for comments
373 }
374
375 start.Specs = append(start.Specs, cont.Specs...)
376 if c := f.inlineComment(cont.End()); c != nil {
377 // don't move an inline comment outside
378 start.Rparen = c.End()
379 } else {
380 // so the code below treats the joined
381 // decl group as multi-line
382 start.Rparen = cont.End()
383 }
384 lastPos = cont.Pos()
385 i++
386 }
387 }
388 node.Decls = newDecls
389
390 // Multiline top-level declarations should be separated by an
391 // empty line.
392 // Do this after the joining of lone declarations above,
393 // as joining single-line declarations makes then multi-line.
394 var lastMulti bool
395 var lastEnd token.Pos
396 for _, decl := range node.Decls {
397 pos := decl.Pos()
398 comments := f.commentsBetween(lastEnd, pos)
399 if len(comments) > 0 {
400 pos = comments[0].Pos()
401 }
402
403 // Note that we want End-1, as End is the character after the node.
404 multi := f.Line(pos) < f.Line(decl.End()-1)
405 if multi && lastMulti && f.Line(lastEnd)+1 == f.Line(pos) {
406 f.addNewline(lastEnd)
407 }
408
409 lastMulti = multi
410 lastEnd = decl.End()
411 }
412
413 // Comments aren't nodes, so they're not walked by default.
414 groupLoop:
415 for _, group := range node.Comments {
416 for _, comment := range group.List {
417 if comment.Text == "//gofumpt:diagnose" || strings.HasPrefix(comment.Text, "//gofumpt:diagnose ") {
418 slc := []string{
419 "//gofumpt:diagnose",
420 "version:",
421 version.String(""),
422 "flags:",
423 "-lang=" + f.LangVersion,
424 "-modpath=" + f.ModulePath,
425 }
426 if f.ExtraRules {
427 slc = append(slc, "-extra")
428 }
429 comment.Text = strings.Join(slc, " ")
430 }
431 body := strings.TrimPrefix(comment.Text, "//")
432 if body == comment.Text {
433 // /*-style comment
434 continue groupLoop
435 }
436 if rxCommentDirective.MatchString(body) {
437 // this line is a directive
438 continue groupLoop
439 }
440 r, _ := utf8.DecodeRuneInString(body)
441 if !unicode.IsLetter(r) && !unicode.IsNumber(r) && !unicode.IsSpace(r) {
442 // this line could be code like "//{"
443 continue groupLoop
444 }
445 }
446 // If none of the comment group's lines look like a
447 // directive or code, add spaces, if needed.
448 for _, comment := range group.List {
449 body := strings.TrimPrefix(comment.Text, "//")
450 r, _ := utf8.DecodeRuneInString(body)
451 if !unicode.IsSpace(r) {
452 comment.Text = "// " + body
453 }
454 }
455 }
456
457 case *ast.DeclStmt:
458 decl, ok := node.Decl.(*ast.GenDecl)
459 if !ok || decl.Tok != token.VAR || len(decl.Specs) != 1 {
460 break // e.g. const name = "value"
461 }
462 spec := decl.Specs[0].(*ast.ValueSpec)
463 if spec.Type != nil {
464 break // e.g. var name Type
465 }
466 tok := token.ASSIGN
467 names := make([]ast.Expr, len(spec.Names))
468 for i, name := range spec.Names {
469 names[i] = name
470 if name.Name != "_" {
471 tok = token.DEFINE
472 }
473 }
474 c.Replace(&ast.AssignStmt{
475 Lhs: names,
476 Tok: tok,
477 Rhs: spec.Values,
478 })
479
480 case *ast.GenDecl:
481 if node.Tok == token.IMPORT && node.Lparen.IsValid() {
482 f.joinStdImports(node)
483 }
484
485 // Single var declarations shouldn't use parentheses, unless
486 // there's a comment on the grouped declaration.
487 if node.Tok == token.VAR && len(node.Specs) == 1 &&
488 node.Lparen.IsValid() && node.Doc == nil {
489 specPos := node.Specs[0].Pos()
490 specEnd := node.Specs[0].End()
491
492 if len(f.commentsBetween(node.TokPos, specPos)) > 0 {
493 // If the single spec has a comment on the line above,
494 // the comment must go before the entire declaration now.
495 node.TokPos = specPos
496 } else {
497 f.removeLines(f.Line(node.TokPos), f.Line(specPos))
498 }
499 if len(f.commentsBetween(specEnd, node.Rparen)) > 0 {
500 // Leave one newline to not force a comment on the next line to
501 // become an inline comment.
502 f.removeLines(f.Line(specEnd)+1, f.Line(node.Rparen))
503 } else {
504 f.removeLines(f.Line(specEnd), f.Line(node.Rparen))
505 }
506
507 // Remove the parentheses. go/printer will automatically
508 // get rid of the newlines.
509 node.Lparen = token.NoPos
510 node.Rparen = token.NoPos
511 }
512
513 case *ast.InterfaceType:
514 if len(node.Methods.List) > 0 {
515 method := node.Methods.List[0]
516 removeToPos := method.Pos()
517 if comments := f.commentsBetween(node.Interface, method.Pos()); len(comments) > 0 {
518 // only remove leading line upto the first comment
519 removeToPos = comments[0].Pos()
520 }
521 // remove leading lines if they exist
522 f.removeLines(f.Line(node.Interface)+1, f.Line(removeToPos))
523 }
524
525 case *ast.BlockStmt:
526 f.stmts(node.List)
527 comments := f.commentsBetween(node.Lbrace, node.Rbrace)
528 if len(node.List) == 0 && len(comments) == 0 {
529 f.removeLinesBetween(node.Lbrace, node.Rbrace)
530 break
531 }
532
533 var sign *ast.FuncType
534 var cond ast.Expr
535 switch parent := c.Parent().(type) {
536 case *ast.FuncDecl:
537 sign = parent.Type
538 case *ast.FuncLit:
539 sign = parent.Type
540 case *ast.IfStmt:
541 cond = parent.Cond
542 case *ast.ForStmt:
543 cond = parent.Cond
544 }
545
546 if len(node.List) > 1 && sign == nil {
547 // only if we have a single statement, or if
548 // it's a func body.
549 break
550 }
551 var bodyPos, bodyEnd token.Pos
552
553 if len(node.List) > 0 {
554 bodyPos = node.List[0].Pos()
555 bodyEnd = node.List[len(node.List)-1].End()
556 }
557 if len(comments) > 0 {
558 if pos := comments[0].Pos(); !bodyPos.IsValid() || pos < bodyPos {
559 bodyPos = pos
560 }
561 if pos := comments[len(comments)-1].End(); !bodyPos.IsValid() || pos > bodyEnd {
562 bodyEnd = pos
563 }
564 }
565
566 f.removeLinesBetween(bodyEnd, node.Rbrace)
567
568 if cond != nil && f.Line(cond.Pos()) != f.Line(cond.End()) {
569 // The body is preceded by a multi-line condition, so an
570 // empty line can help readability.
571 return
572 }
573 if sign != nil {
574 endLine := f.Line(sign.End())
575
576 if f.Line(sign.Pos()) != endLine {
577 handleMultiLine := func(fl *ast.FieldList) {
578 // Refuse to insert a newline before the closing token
579 // if the list is empty or all in one line.
580 if fl == nil || len(fl.List) == 0 {
581 return
582 }
583 fieldOpeningLine := f.Line(fl.Opening)
584 fieldClosingLine := f.Line(fl.Closing)
585 if fieldOpeningLine == fieldClosingLine {
586 return
587 }
588
589 lastFieldEnd := fl.List[len(fl.List)-1].End()
590 lastFieldLine := f.Line(lastFieldEnd)
591 isLastFieldOnFieldClosingLine := lastFieldLine == fieldClosingLine
592 isLastFieldOnSigClosingLine := lastFieldLine == endLine
593
594 var isLastCommentGrpOnFieldClosingLine, isLastCommentGrpOnSigClosingLine bool
595 if comments := f.commentsBetween(lastFieldEnd, fl.Closing); len(comments) > 0 {
596 lastCommentGrp := comments[len(comments)-1]
597 lastCommentGrpLine := f.Line(lastCommentGrp.End())
598
599 isLastCommentGrpOnFieldClosingLine = lastCommentGrpLine == fieldClosingLine
600 isLastCommentGrpOnSigClosingLine = lastCommentGrpLine == endLine
601 }
602
603 // is there a comment grp/last field, field closing and sig closing on the same line?
604 if (isLastFieldOnFieldClosingLine && isLastFieldOnSigClosingLine) ||
605 (isLastCommentGrpOnFieldClosingLine && isLastCommentGrpOnSigClosingLine) {
606 fl.Closing += 1
607 f.addNewline(fl.Closing)
608 }
609 }
610 handleMultiLine(sign.Params)
611 if sign.Results != nil && len(sign.Results.List) > 0 {
612 lastResultLine := f.Line(sign.Results.List[len(sign.Results.List)-1].End())
613 isLastResultOnParamClosingLine := sign.Params != nil && lastResultLine == f.Line(sign.Params.Closing)
614 if !isLastResultOnParamClosingLine {
615 handleMultiLine(sign.Results)
616 }
617 }
618 }
619 }
620
621 f.removeLinesBetween(node.Lbrace, bodyPos)
622
623 case *ast.CaseClause:
624 f.stmts(node.Body)
625 openLine := f.Line(node.Case)
626 closeLine := f.Line(node.Colon)
627 if openLine == closeLine {
628 // nothing to do
629 break
630 }
631 if len(f.commentsBetween(node.Case, node.Colon)) > 0 {
632 // don't move comments
633 break
634 }
635 // check the length excluding the body
636 nodeWithoutBody := &ast.CaseClause{
637 Case: node.Case,
638 List: node.List,
639 Colon: node.Colon,
640 }
641 if f.printLength(nodeWithoutBody) > shortLineLimit {
642 // too long to collapse
643 break
644 }
645 f.removeLines(openLine, closeLine)
646
647 case *ast.CommClause:
648 f.stmts(node.Body)
649
650 case *ast.FieldList:
651 numFields := node.NumFields()
652 comments := f.commentsBetween(node.Pos(), node.End())
653
654 if numFields == 0 && len(comments) == 0 {
655 // Empty field lists should not contain a newline.
656 // Do not join the two lines if the first has an inline
657 // comment, as that can result in broken formatting.
658 openLine := f.Line(node.Pos())
659 closeLine := f.Line(node.End())
660 f.removeLines(openLine, closeLine)
661 } else {
662 // Remove lines before first comment/field and lines after last
663 // comment/field
664 var bodyPos, bodyEnd token.Pos
665 if numFields > 0 {
666 bodyPos = node.List[0].Pos()
667 bodyEnd = node.List[len(node.List)-1].End()
668 }
669 if len(comments) > 0 {
670 if pos := comments[0].Pos(); !bodyPos.IsValid() || pos < bodyPos {
671 bodyPos = pos
672 }
673 if pos := comments[len(comments)-1].End(); !bodyPos.IsValid() || pos > bodyEnd {
674 bodyEnd = pos
675 }
676 }
677 f.removeLinesBetween(node.Pos(), bodyPos)
678 f.removeLinesBetween(bodyEnd, node.End())
679 }
680
681 // Merging adjacent fields (e.g. parameters) is disabled by default.
682 if !f.ExtraRules {
683 break
684 }
685 switch c.Parent().(type) {
686 case *ast.FuncDecl, *ast.FuncType, *ast.InterfaceType:
687 node.List = f.mergeAdjacentFields(node.List)
688 c.Replace(node)
689 case *ast.StructType:
690 // Do not merge adjacent fields in structs.
691 }
692
693 case *ast.BasicLit:
694 // Octal number literals were introduced in 1.13.
695 if semver.Compare(f.LangVersion, "v1.13") >= 0 {
696 if node.Kind == token.INT && rxOctalInteger.MatchString(node.Value) {
697 node.Value = "0o" + node.Value[1:]
698 c.Replace(node)
699 }
700 }
701
702 case *ast.AssignStmt:
703 // Only remove lines between the assignment token and the first right-hand side expression
704 f.removeLines(f.Line(node.TokPos), f.Line(node.Rhs[0].Pos()))
705 }
706 }
707
708 func (f *fumpter) applyPost(c *astutil.Cursor) {
709 switch node := c.Node().(type) {
710 // Adding newlines to composite literals happens as a "post" step, so
711 // that we can take into account whether "pre" steps added any newlines
712 // that would affect us here.
713 case *ast.CompositeLit:
714 if len(node.Elts) == 0 {
715 // doesn't have elements
716 break
717 }
718 openLine := f.Line(node.Lbrace)
719 closeLine := f.Line(node.Rbrace)
720 if openLine == closeLine {
721 // all in a single line
722 break
723 }
724
725 newlineAroundElems := false
726 newlineBetweenElems := false
727 lastEnd := node.Lbrace
728 lastLine := openLine
729 for i, elem := range node.Elts {
730 pos := elem.Pos()
731 comments := f.commentsBetween(lastEnd, pos)
732 if len(comments) > 0 {
733 pos = comments[0].Pos()
734 }
735 if curLine := f.Line(pos); curLine > lastLine {
736 if i == 0 {
737 newlineAroundElems = true
738
739 // remove leading lines if they exist
740 f.removeLines(openLine+1, curLine)
741 } else {
742 newlineBetweenElems = true
743 }
744 }
745 lastEnd = elem.End()
746 lastLine = f.Line(lastEnd)
747 }
748 if closeLine > lastLine {
749 newlineAroundElems = true
750 }
751
752 if newlineBetweenElems || newlineAroundElems {
753 first := node.Elts[0]
754 if openLine == f.Line(first.Pos()) {
755 // We want the newline right after the brace.
756 f.addNewline(node.Lbrace + 1)
757 closeLine = f.Line(node.Rbrace)
758 }
759 last := node.Elts[len(node.Elts)-1]
760 if closeLine == f.Line(last.End()) {
761 // We want the newline right before the brace.
762 f.addNewline(node.Rbrace)
763 }
764 }
765
766 // If there's a newline between any consecutive elements, there
767 // must be a newline between all composite literal elements.
768 if !newlineBetweenElems {
769 break
770 }
771 for i1, elem1 := range node.Elts {
772 i2 := i1 + 1
773 if i2 >= len(node.Elts) {
774 break
775 }
776 elem2 := node.Elts[i2]
777 // TODO: do we care about &{}?
778 _, ok1 := elem1.(*ast.CompositeLit)
779 _, ok2 := elem2.(*ast.CompositeLit)
780 if !ok1 && !ok2 {
781 continue
782 }
783 if f.Line(elem1.End()) == f.Line(elem2.Pos()) {
784 f.addNewline(elem1.End())
785 }
786 }
787 }
788 }
789
790 func (f *fumpter) splitLongLine(c *astutil.Cursor) {
791 if os.Getenv("GOFUMPT_SPLIT_LONG_LINES") != "on" {
792 // By default, this feature is turned off.
793 // Turn it on by setting GOFUMPT_SPLIT_LONG_LINES=on.
794 return
795 }
796 node := c.Node()
797 if node == nil {
798 return
799 }
800
801 newlinePos := node.Pos()
802 start := f.Position(node.Pos())
803 end := f.Position(node.End())
804
805 // If the node is already split in multiple lines, there's nothing to do.
806 if start.Line != end.Line {
807 return
808 }
809
810 // Only split at the start of the current node if it's part of a list.
811 if _, ok := c.Parent().(*ast.BinaryExpr); ok {
812 // Chains of binary expressions are considered lists, too.
813 } else if c.Index() >= 0 {
814 // For the rest of the nodes, we're in a list if c.Index() >= 0.
815 } else {
816 return
817 }
818
819 // Like in printLength, add an approximation of the indentation level.
820 // Since any existing tabs were already counted as one column, multiply
821 // the level by 7.
822 startCol := start.Column + f.blockLevel*7
823 endCol := end.Column + f.blockLevel*7
824
825 // If this is a composite literal,
826 // and we were going to insert a newline before the entire literal,
827 // insert the newline before the first element instead.
828 // Since we'll add a newline after the last element too,
829 // this format is generally going to be nicer.
830 if comp := isComposite(node); comp != nil && len(comp.Elts) > 0 {
831 newlinePos = comp.Elts[0].Pos()
832 }
833
834 // If this is a function call,
835 // and we were to add a newline before the first argument,
836 // prefer adding the newline before the entire call.
837 // End-of-line parentheses aren't very nice, as we don't put their
838 // counterparts at the start of a line too.
839 // We do this by using the average of the two starting positions.
840 if call, _ := node.(*ast.CallExpr); call != nil && len(call.Args) > 0 {
841 first := f.Position(call.Args[0].Pos())
842 startCol += (first.Column - start.Column) / 2
843 }
844
845 // If the start position is too short, we definitely won't split the line.
846 if startCol <= shortLineLimit {
847 return
848 }
849
850 lineEnd := f.Position(f.lineEnd(start.Line))
851
852 // firstLength and secondLength are the split line lengths, excluding
853 // indentation.
854 firstLength := start.Column - f.blockLevel
855 if firstLength < 0 {
856 panic("negative length")
857 }
858 secondLength := lineEnd.Column - start.Column
859 if secondLength < 0 {
860 panic("negative length")
861 }
862
863 // If the line ends past the long line limit,
864 // and both splits are estimated to take at least minSplitFactor of the limit,
865 // then split the line.
866 minSplitLength := int(f.minSplitFactor * longLineLimit)
867 if endCol > longLineLimit &&
868 firstLength >= minSplitLength && secondLength >= minSplitLength {
869 f.addNewline(newlinePos)
870 }
871 }
872
873 func isComposite(node ast.Node) *ast.CompositeLit {
874 switch node := node.(type) {
875 case *ast.CompositeLit:
876 return node
877 case *ast.UnaryExpr:
878 return isComposite(node.X) // e.g. &T{}
879 default:
880 return nil
881 }
882 }
883
884 func (f *fumpter) stmts(list []ast.Stmt) {
885 for i, stmt := range list {
886 ifs, ok := stmt.(*ast.IfStmt)
887 if !ok || i < 1 {
888 continue // not an if following another statement
889 }
890 as, ok := list[i-1].(*ast.AssignStmt)
891 if !ok || (as.Tok != token.DEFINE && as.Tok != token.ASSIGN) ||
892 !identEqual(as.Lhs[len(as.Lhs)-1], "err") {
893 continue // not ", err :=" nor ", err ="
894 }
895 be, ok := ifs.Cond.(*ast.BinaryExpr)
896 if !ok || ifs.Init != nil || ifs.Else != nil {
897 continue // complex if
898 }
899 if be.Op != token.NEQ || !identEqual(be.X, "err") ||
900 !identEqual(be.Y, "nil") {
901 continue // not "err != nil"
902 }
903 f.removeLinesBetween(as.End(), ifs.Pos())
904 }
905 }
906
907 func identEqual(expr ast.Expr, name string) bool {
908 id, ok := expr.(*ast.Ident)
909 return ok && id.Name == name
910 }
911
912 // isCgoImport returns true if the declaration is simply:
913 //
914 // import "C"
915 //
916 // or the equivalent:
917 //
918 // import `C`
919 //
920 // Note that parentheses do not affect the result.
921 func isCgoImport(decl *ast.GenDecl) bool {
922 if decl.Tok != token.IMPORT || len(decl.Specs) != 1 {
923 return false
924 }
925 spec := decl.Specs[0].(*ast.ImportSpec)
926 v, err := strconv.Unquote(spec.Path.Value)
927 if err != nil {
928 panic(err) // should never error
929 }
930 return v == "C"
931 }
932
933 // joinStdImports ensures that all standard library imports are together and at
934 // the top of the imports list.
935 func (f *fumpter) joinStdImports(d *ast.GenDecl) {
936 var std, other []ast.Spec
937 firstGroup := true
938 lastEnd := d.Pos()
939 needsSort := false
940
941 // If ModulePath is "foo/bar", we assume "foo/..." is not part of std.
942 // Users shouldn't declare modules that may collide with std this way,
943 // but historically some private codebases have done so.
944 // This is a relatively harmless way to make gofumpt compatible with them,
945 // as it changes nothing for the common external module paths.
946 var modulePrefix string
947 if f.ModulePath == "" {
948 // Nothing to do.
949 } else if i := strings.IndexByte(f.ModulePath, '/'); i != -1 {
950 // ModulePath is "foo/bar", so we use "foo" as the prefix.
951 modulePrefix = f.ModulePath[:i]
952 } else {
953 // ModulePath is "foo", so we use "foo" as the prefix.
954 modulePrefix = f.ModulePath
955 }
956
957 for i, spec := range d.Specs {
958 spec := spec.(*ast.ImportSpec)
959 if coms := f.commentsBetween(lastEnd, spec.Pos()); len(coms) > 0 {
960 lastEnd = coms[len(coms)-1].End()
961 }
962 if i > 0 && firstGroup && f.Line(spec.Pos()) > f.Line(lastEnd)+1 {
963 firstGroup = false
964 } else {
965 // We're still in the first group, update lastEnd.
966 lastEnd = spec.End()
967 }
968
969 path, err := strconv.Unquote(spec.Path.Value)
970 if err != nil {
971 panic(err) // should never error
972 }
973 periodIndex := strings.IndexByte(path, '.')
974 slashIndex := strings.IndexByte(path, '/')
975 switch {
976 // Imports with a period in the first path element are third party.
977 // Note that this includes "foo.com" and excludes "foo/bar.com/baz".
978 case periodIndex > 0 && (slashIndex == -1 || periodIndex < slashIndex),
979
980 // "test" and "example" are reserved as per golang.org/issue/37641.
981 // "internal" is unreachable.
982 strings.HasPrefix(path, "test/"),
983 strings.HasPrefix(path, "example/"),
984 strings.HasPrefix(path, "internal/"),
985
986 // See if we match modulePrefix; see its documentation above.
987 // We match either exactly or with a slash suffix,
988 // so that the prefix "foo" for "foo/..." does not match "foobar".
989 path == modulePrefix || strings.HasPrefix(path, modulePrefix+"/"),
990
991 // To be conservative, if an import has a name or an inline
992 // comment, and isn't part of the top group, treat it as non-std.
993 !firstGroup && (spec.Name != nil || spec.Comment != nil):
994 other = append(other, spec)
995 continue
996 }
997
998 // If we're moving this std import further up, reset its
999 // position, to avoid breaking comments.
1000 if !firstGroup || len(other) > 0 {
1001 setPos(reflect.ValueOf(spec), d.Pos())
1002 needsSort = true
1003 }
1004 std = append(std, spec)
1005 }
1006 // Ensure there is an empty line between std imports and other imports.
1007 if len(std) > 0 && len(other) > 0 && f.Line(std[len(std)-1].End())+1 >= f.Line(other[0].Pos()) {
1008 // We add two newlines, as that's necessary in some edge cases.
1009 // For example, if the std and non-std imports were together and
1010 // without indentation, adding one newline isn't enough. Two
1011 // empty lines will be printed as one by go/printer, anyway.
1012 f.addNewline(other[0].Pos() - 1)
1013 f.addNewline(other[0].Pos())
1014 }
1015 // Finally, join the imports, keeping std at the top.
1016 d.Specs = append(std, other...)
1017
1018 // If we moved any std imports to the first group, we need to sort them
1019 // again.
1020 if needsSort {
1021 ast.SortImports(f.fset, f.astFile)
1022 }
1023 }
1024
1025 // mergeAdjacentFields returns fields with adjacent fields merged if possible.
1026 func (f *fumpter) mergeAdjacentFields(fields []*ast.Field) []*ast.Field {
1027 // If there are less than two fields then there is nothing to merge.
1028 if len(fields) < 2 {
1029 return fields
1030 }
1031
1032 // Otherwise, iterate over adjacent pairs of fields, merging if possible,
1033 // and mutating fields. Elements of fields may be mutated (if merged with
1034 // following fields), discarded (if merged with a preceding field), or left
1035 // unchanged.
1036 i := 0
1037 for j := 1; j < len(fields); j++ {
1038 if f.shouldMergeAdjacentFields(fields[i], fields[j]) {
1039 fields[i].Names = append(fields[i].Names, fields[j].Names...)
1040 } else {
1041 i++
1042 fields[i] = fields[j]
1043 }
1044 }
1045 return fields[:i+1]
1046 }
1047
1048 func (f *fumpter) shouldMergeAdjacentFields(f1, f2 *ast.Field) bool {
1049 if len(f1.Names) == 0 || len(f2.Names) == 0 {
1050 // Both must have names for the merge to work.
1051 return false
1052 }
1053 if f.Line(f1.Pos()) != f.Line(f2.Pos()) {
1054 // Trust the user if they used separate lines.
1055 return false
1056 }
1057
1058 // Only merge if the types are equal.
1059 opt := cmp.Comparer(func(x, y token.Pos) bool { return true })
1060 return cmp.Equal(f1.Type, f2.Type, opt)
1061 }
1062
1063 var posType = reflect.TypeOf(token.NoPos)
1064
1065 // setPos recursively sets all position fields in the node v to pos.
1066 func setPos(v reflect.Value, pos token.Pos) {
1067 if v.Kind() == reflect.Ptr {
1068 v = v.Elem()
1069 }
1070 if !v.IsValid() {
1071 return
1072 }
1073 if v.Type() == posType {
1074 v.Set(reflect.ValueOf(pos))
1075 }
1076 if v.Kind() == reflect.Struct {
1077 for i := 0; i < v.NumField(); i++ {
1078 setPos(v.Field(i), pos)
1079 }
1080 }
1081 }
1082
1083 func containsAnyDirective(group *ast.CommentGroup) bool {
1084 if group == nil {
1085 return false
1086 }
1087 for _, comment := range group.List {
1088 body := strings.TrimPrefix(comment.Text, "//")
1089 if rxCommentDirective.MatchString(body) {
1090 return true
1091 }
1092 }
1093 return false
1094 }