Debian Codegraph @

internal/govendor/go/printer/nodes.go

raw symbols SCIP
1 // Copyright 2009 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 // This file implements printing of AST nodes; specifically
6 // expressions, statements, declarations, and files. It uses
7 // the print functionality implemented in printer.go.
8
9 package printer
10
11 import (
12 "go/ast"
13 "go/token"
14 "math"
15 "strconv"
16 "strings"
17 "unicode"
18 "unicode/utf8"
19 )
20
21 // Formatting issues:
22 // - better comment formatting for /*-style comments at the end of a line (e.g. a declaration)
23 // when the comment spans multiple lines; if such a comment is just two lines, formatting is
24 // not idempotent
25 // - formatting of expression lists
26 // - should use blank instead of tab to separate one-line function bodies from
27 // the function header unless there is a group of consecutive one-liners
28
29 // ----------------------------------------------------------------------------
30 // Common AST nodes.
31
32 // Print as many newlines as necessary (but at least min newlines) to get to
33 // the current line. ws is printed before the first line break. If newSection
34 // is set, the first line break is printed as formfeed. Returns 0 if no line
35 // breaks were printed, returns 1 if there was exactly one newline printed,
36 // and returns a value > 1 if there was a formfeed or more than one newline
37 // printed.
38 //
39 // TODO(gri): linebreak may add too many lines if the next statement at "line"
40 // is preceded by comments because the computation of n assumes
41 // the current position before the comment and the target position
42 // after the comment. Thus, after interspersing such comments, the
43 // space taken up by them is not considered to reduce the number of
44 // linebreaks. At the moment there is no easy way to know about
45 // future (not yet interspersed) comments in this function.
46 func (p *printer) linebreak(line, min int, ws whiteSpace, newSection bool) (nbreaks int) {
47 n := nlimit(line - p.pos.Line)
48 if n < min {
49 n = min
50 }
51 if n > 0 {
52 p.print(ws)
53 if newSection {
54 p.print(formfeed)
55 n--
56 nbreaks = 2
57 }
58 nbreaks += n
59 for ; n > 0; n-- {
60 p.print(newline)
61 }
62 }
63 return
64 }
65
66 // setComment sets g as the next comment if g != nil and if node comments
67 // are enabled - this mode is used when printing source code fragments such
68 // as exports only. It assumes that there is no pending comment in p.comments
69 // and at most one pending comment in the p.comment cache.
70 func (p *printer) setComment(g *ast.CommentGroup) {
71 if g == nil || !p.useNodeComments {
72 return
73 }
74 if p.comments == nil {
75 // initialize p.comments lazily
76 p.comments = make([]*ast.CommentGroup, 1)
77 } else if p.cindex < len(p.comments) {
78 // for some reason there are pending comments; this
79 // should never happen - handle gracefully and flush
80 // all comments up to g, ignore anything after that
81 p.flush(p.posFor(g.List[0].Pos()), token.ILLEGAL)
82 p.comments = p.comments[0:1]
83 // in debug mode, report error
84 p.internalError("setComment found pending comments")
85 }
86 p.comments[0] = g
87 p.cindex = 0
88 // don't overwrite any pending comment in the p.comment cache
89 // (there may be a pending comment when a line comment is
90 // immediately followed by a lead comment with no other
91 // tokens between)
92 if p.commentOffset == infinity {
93 p.nextComment() // get comment ready for use
94 }
95 }
96
97 type exprListMode uint
98
99 const (
100 commaTerm exprListMode = 1 << iota // list is optionally terminated by a comma
101 noIndent // no extra indentation in multi-line lists
102 )
103
104 // If indent is set, a multi-line identifier list is indented after the
105 // first linebreak encountered.
106 func (p *printer) identList(list []*ast.Ident, indent bool) {
107 // convert into an expression list so we can re-use exprList formatting
108 xlist := make([]ast.Expr, len(list))
109 for i, x := range list {
110 xlist[i] = x
111 }
112 var mode exprListMode
113 if !indent {
114 mode = noIndent
115 }
116 p.exprList(token.NoPos, xlist, 1, mode, token.NoPos, false)
117 }
118
119 const filteredMsg = "contains filtered or unexported fields"
120
121 // Print a list of expressions. If the list spans multiple
122 // source lines, the original line breaks are respected between
123 // expressions.
124 //
125 // TODO(gri) Consider rewriting this to be independent of []ast.Expr
126 // so that we can use the algorithm for any kind of list
127 //
128 // (e.g., pass list via a channel over which to range).
129 func (p *printer) exprList(prev0 token.Pos, list []ast.Expr, depth int, mode exprListMode, next0 token.Pos, isIncomplete bool) {
130 if len(list) == 0 {
131 if isIncomplete {
132 prev := p.posFor(prev0)
133 next := p.posFor(next0)
134 if prev.IsValid() && prev.Line == next.Line {
135 p.print("/* " + filteredMsg + " */")
136 } else {
137 p.print(newline)
138 p.print(indent, "// "+filteredMsg, unindent, newline)
139 }
140 }
141 return
142 }
143
144 prev := p.posFor(prev0)
145 next := p.posFor(next0)
146 line := p.lineFor(list[0].Pos())
147 endLine := p.lineFor(list[len(list)-1].End())
148
149 if prev.IsValid() && prev.Line == line && line == endLine {
150 // all list entries on a single line
151 for i, x := range list {
152 if i > 0 {
153 // use position of expression following the comma as
154 // comma position for correct comment placement
155 p.setPos(x.Pos())
156 p.print(token.COMMA, blank)
157 }
158 p.expr0(x, depth)
159 }
160 if isIncomplete {
161 p.print(token.COMMA, blank, "/* "+filteredMsg+" */")
162 }
163 return
164 }
165
166 // list entries span multiple lines;
167 // use source code positions to guide line breaks
168
169 // Don't add extra indentation if noIndent is set;
170 // i.e., pretend that the first line is already indented.
171 ws := ignore
172 if mode&noIndent == 0 {
173 ws = indent
174 }
175
176 // The first linebreak is always a formfeed since this section must not
177 // depend on any previous formatting.
178 prevBreak := -1 // index of last expression that was followed by a linebreak
179 if prev.IsValid() && prev.Line < line && p.linebreak(line, 0, ws, true) > 0 {
180 ws = ignore
181 prevBreak = 0
182 }
183
184 // initialize expression/key size: a zero value indicates expr/key doesn't fit on a single line
185 size := 0
186
187 // We use the ratio between the geometric mean of the previous key sizes and
188 // the current size to determine if there should be a break in the alignment.
189 // To compute the geometric mean we accumulate the ln(size) values (lnsum)
190 // and the number of sizes included (count).
191 lnsum := 0.0
192 count := 0
193
194 // print all list elements
195 prevLine := prev.Line
196 for i, x := range list {
197 line = p.lineFor(x.Pos())
198
199 // Determine if the next linebreak, if any, needs to use formfeed:
200 // in general, use the entire node size to make the decision; for
201 // key:value expressions, use the key size.
202 // TODO(gri) for a better result, should probably incorporate both
203 // the key and the node size into the decision process
204 useFF := true
205
206 // Determine element size: All bets are off if we don't have
207 // position information for the previous and next token (likely
208 // generated code - simply ignore the size in this case by setting
209 // it to 0).
210 prevSize := size
211 const infinity = 1e6 // larger than any source line
212 size = p.nodeSize(x, infinity)
213 pair, isPair := x.(*ast.KeyValueExpr)
214 if size <= infinity && prev.IsValid() && next.IsValid() {
215 // x fits on a single line
216 if isPair {
217 size = p.nodeSize(pair.Key, infinity) // size <= infinity
218 }
219 } else {
220 // size too large or we don't have good layout information
221 size = 0
222 }
223
224 // If the previous line and the current line had single-
225 // line-expressions and the key sizes are small or the
226 // ratio between the current key and the geometric mean
227 // if the previous key sizes does not exceed a threshold,
228 // align columns and do not use formfeed.
229 if prevSize > 0 && size > 0 {
230 const smallSize = 40
231 if count == 0 || prevSize <= smallSize && size <= smallSize {
232 useFF = false
233 } else {
234 const r = 2.5 // threshold
235 geomean := math.Exp(lnsum / float64(count)) // count > 0
236 ratio := float64(size) / geomean
237 useFF = r*ratio <= 1 || r <= ratio
238 }
239 }
240
241 needsLinebreak := 0 < prevLine && prevLine < line
242 if i > 0 {
243 // Use position of expression following the comma as
244 // comma position for correct comment placement, but
245 // only if the expression is on the same line.
246 if !needsLinebreak {
247 p.setPos(x.Pos())
248 }
249 p.print(token.COMMA)
250 needsBlank := true
251 if needsLinebreak {
252 // Lines are broken using newlines so comments remain aligned
253 // unless useFF is set or there are multiple expressions on
254 // the same line in which case formfeed is used.
255 nbreaks := p.linebreak(line, 0, ws, useFF || prevBreak+1 < i)
256 if nbreaks > 0 {
257 ws = ignore
258 prevBreak = i
259 needsBlank = false // we got a line break instead
260 }
261 // If there was a new section or more than one new line
262 // (which means that the tabwriter will implicitly break
263 // the section), reset the geomean variables since we are
264 // starting a new group of elements with the next element.
265 if nbreaks > 1 {
266 lnsum = 0
267 count = 0
268 }
269 }
270 if needsBlank {
271 p.print(blank)
272 }
273 }
274
275 if len(list) > 1 && isPair && size > 0 && needsLinebreak {
276 // We have a key:value expression that fits onto one line
277 // and it's not on the same line as the prior expression:
278 // Use a column for the key such that consecutive entries
279 // can align if possible.
280 // (needsLinebreak is set if we started a new line before)
281 p.expr(pair.Key)
282 p.setPos(pair.Colon)
283 p.print(token.COLON, vtab)
284 p.expr(pair.Value)
285 } else {
286 p.expr0(x, depth)
287 }
288
289 if size > 0 {
290 lnsum += math.Log(float64(size))
291 count++
292 }
293
294 prevLine = line
295 }
296
297 if mode&commaTerm != 0 && next.IsValid() && p.pos.Line < next.Line {
298 // Print a terminating comma if the next token is on a new line.
299 p.print(token.COMMA)
300 if isIncomplete {
301 p.print(newline)
302 p.print("// " + filteredMsg)
303 }
304 if ws == ignore && mode&noIndent == 0 {
305 // unindent if we indented
306 p.print(unindent)
307 }
308 p.print(formfeed) // terminating comma needs a line break to look good
309 return
310 }
311
312 if isIncomplete {
313 p.print(token.COMMA, newline)
314 p.print("// "+filteredMsg, newline)
315 }
316
317 if ws == ignore && mode&noIndent == 0 {
318 // unindent if we indented
319 p.print(unindent)
320 }
321 }
322
323 type paramMode int
324
325 const (
326 funcParam paramMode = iota
327 funcTParam
328 typeTParam
329 )
330
331 func (p *printer) parameters(fields *ast.FieldList, mode paramMode) {
332 openTok, closeTok := token.LPAREN, token.RPAREN
333 if mode != funcParam {
334 openTok, closeTok = token.LBRACK, token.RBRACK
335 }
336 p.setPos(fields.Opening)
337 p.print(openTok)
338 if len(fields.List) > 0 {
339 prevLine := p.lineFor(fields.Opening)
340 ws := indent
341 for i, par := range fields.List {
342 // determine par begin and end line (may be different
343 // if there are multiple parameter names for this par
344 // or the type is on a separate line)
345 parLineBeg := p.lineFor(par.Pos())
346 parLineEnd := p.lineFor(par.End())
347 // separating "," if needed
348 needsLinebreak := 0 < prevLine && prevLine < parLineBeg
349 if i > 0 {
350 // use position of parameter following the comma as
351 // comma position for correct comma placement, but
352 // only if the next parameter is on the same line
353 if !needsLinebreak {
354 p.setPos(par.Pos())
355 }
356 p.print(token.COMMA)
357 }
358 // separator if needed (linebreak or blank)
359 if needsLinebreak && p.linebreak(parLineBeg, 0, ws, true) > 0 {
360 // break line if the opening "(" or previous parameter ended on a different line
361 ws = ignore
362 } else if i > 0 {
363 p.print(blank)
364 }
365 // parameter names
366 if len(par.Names) > 0 {
367 // Very subtle: If we indented before (ws == ignore), identList
368 // won't indent again. If we didn't (ws == indent), identList will
369 // indent if the identList spans multiple lines, and it will outdent
370 // again at the end (and still ws == indent). Thus, a subsequent indent
371 // by a linebreak call after a type, or in the next multi-line identList
372 // will do the right thing.
373 p.identList(par.Names, ws == indent)
374 p.print(blank)
375 }
376 // parameter type
377 p.expr(stripParensAlways(par.Type))
378 prevLine = parLineEnd
379 }
380
381 // if the closing ")" is on a separate line from the last parameter,
382 // print an additional "," and line break
383 if closing := p.lineFor(fields.Closing); 0 < prevLine && prevLine < closing {
384 p.print(token.COMMA)
385 p.linebreak(closing, 0, ignore, true)
386 } else if mode == typeTParam && fields.NumFields() == 1 && combinesWithName(fields.List[0].Type) {
387 // A type parameter list [P T] where the name P and the type expression T syntactically
388 // combine to another valid (value) expression requires a trailing comma, as in [P *T,]
389 // (or an enclosing interface as in [P interface(*T)]), so that the type parameter list
390 // is not parsed as an array length [P*T].
391 p.print(token.COMMA)
392 }
393
394 // unindent if we indented
395 if ws == ignore {
396 p.print(unindent)
397 }
398 }
399
400 p.setPos(fields.Closing)
401 p.print(closeTok)
402 }
403
404 // combinesWithName reports whether a name followed by the expression x
405 // syntactically combines to another valid (value) expression. For instance
406 // using *T for x, "name *T" syntactically appears as the expression x*T.
407 // On the other hand, using P|Q or *P|~Q for x, "name P|Q" or name *P|~Q"
408 // cannot be combined into a valid (value) expression.
409 func combinesWithName(x ast.Expr) bool {
410 switch x := x.(type) {
411 case *ast.StarExpr:
412 // name *x.X combines to name*x.X if x.X is not a type element
413 return !isTypeElem(x.X)
414 case *ast.BinaryExpr:
415 return combinesWithName(x.X) && !isTypeElem(x.Y)
416 case *ast.ParenExpr:
417 // name(x) combines but we are making sure at
418 // the call site that x is never parenthesized.
419 panic("unexpected parenthesized expression")
420 }
421 return false
422 }
423
424 // isTypeElem reports whether x is a (possibly parenthesized) type element expression.
425 // The result is false if x could be a type element OR an ordinary (value) expression.
426 func isTypeElem(x ast.Expr) bool {
427 switch x := x.(type) {
428 case *ast.ArrayType, *ast.StructType, *ast.FuncType, *ast.InterfaceType, *ast.MapType, *ast.ChanType:
429 return true
430 case *ast.UnaryExpr:
431 return x.Op == token.TILDE
432 case *ast.BinaryExpr:
433 return isTypeElem(x.X) || isTypeElem(x.Y)
434 case *ast.ParenExpr:
435 return isTypeElem(x.X)
436 }
437 return false
438 }
439
440 func (p *printer) signature(sig *ast.FuncType) {
441 if sig.TypeParams != nil {
442 p.parameters(sig.TypeParams, funcTParam)
443 }
444 if sig.Params != nil {
445 p.parameters(sig.Params, funcParam)
446 } else {
447 p.print(token.LPAREN, token.RPAREN)
448 }
449 res := sig.Results
450 n := res.NumFields()
451 if n > 0 {
452 // res != nil
453 p.print(blank)
454 if n == 1 && res.List[0].Names == nil {
455 // single anonymous res; no ()'s
456 p.expr(stripParensAlways(res.List[0].Type))
457 return
458 }
459 p.parameters(res, funcParam)
460 }
461 }
462
463 func identListSize(list []*ast.Ident, maxSize int) (size int) {
464 for i, x := range list {
465 if i > 0 {
466 size += len(", ")
467 }
468 size += utf8.RuneCountInString(x.Name)
469 if size >= maxSize {
470 break
471 }
472 }
473 return
474 }
475
476 func (p *printer) isOneLineFieldList(list []*ast.Field) bool {
477 if len(list) != 1 {
478 return false // allow only one field
479 }
480 f := list[0]
481 if f.Tag != nil || f.Comment != nil {
482 return false // don't allow tags or comments
483 }
484 // only name(s) and type
485 const maxSize = 30 // adjust as appropriate, this is an approximate value
486 namesSize := identListSize(f.Names, maxSize)
487 if namesSize > 0 {
488 namesSize = 1 // blank between names and types
489 }
490 typeSize := p.nodeSize(f.Type, maxSize)
491 return namesSize+typeSize <= maxSize
492 }
493
494 func (p *printer) setLineComment(text string) {
495 p.setComment(&ast.CommentGroup{List: []*ast.Comment{{Slash: token.NoPos, Text: text}}})
496 }
497
498 func (p *printer) fieldList(fields *ast.FieldList, isStruct, isIncomplete bool) {
499 lbrace := fields.Opening
500 list := fields.List
501 rbrace := fields.Closing
502 hasComments := isIncomplete || p.commentBefore(p.posFor(rbrace))
503 srcIsOneLine := lbrace.IsValid() && rbrace.IsValid() && p.lineFor(lbrace) == p.lineFor(rbrace)
504
505 if !hasComments && srcIsOneLine {
506 // possibly a one-line struct/interface
507 if len(list) == 0 {
508 // no blank between keyword and {} in this case
509 p.setPos(lbrace)
510 p.print(token.LBRACE)
511 p.setPos(rbrace)
512 p.print(token.RBRACE)
513 return
514 } else if p.isOneLineFieldList(list) {
515 // small enough - print on one line
516 // (don't use identList and ignore source line breaks)
517 p.setPos(lbrace)
518 p.print(token.LBRACE, blank)
519 f := list[0]
520 if isStruct {
521 for i, x := range f.Names {
522 if i > 0 {
523 // no comments so no need for comma position
524 p.print(token.COMMA, blank)
525 }
526 p.expr(x)
527 }
528 if len(f.Names) > 0 {
529 p.print(blank)
530 }
531 p.expr(f.Type)
532 } else { // interface
533 if len(f.Names) > 0 {
534 name := f.Names[0] // method name
535 p.expr(name)
536 p.signature(f.Type.(*ast.FuncType)) // don't print "func"
537 } else {
538 // embedded interface
539 p.expr(f.Type)
540 }
541 }
542 p.print(blank)
543 p.setPos(rbrace)
544 p.print(token.RBRACE)
545 return
546 }
547 }
548 // hasComments || !srcIsOneLine
549
550 p.print(blank)
551 p.setPos(lbrace)
552 p.print(token.LBRACE, indent)
553 if hasComments || len(list) > 0 {
554 p.print(formfeed)
555 }
556
557 if isStruct {
558
559 sep := vtab
560 if len(list) == 1 {
561 sep = blank
562 }
563 var line int
564 for i, f := range list {
565 if i > 0 {
566 p.linebreak(p.lineFor(f.Pos()), 1, ignore, p.linesFrom(line) > 0)
567 }
568 extraTabs := 0
569 p.setComment(f.Doc)
570 p.recordLine(&line)
571 if len(f.Names) > 0 {
572 // named fields
573 p.identList(f.Names, false)
574 p.print(sep)
575 p.expr(f.Type)
576 extraTabs = 1
577 } else {
578 // anonymous field
579 p.expr(f.Type)
580 extraTabs = 2
581 }
582 if f.Tag != nil {
583 if len(f.Names) > 0 && sep == vtab {
584 p.print(sep)
585 }
586 p.print(sep)
587 p.expr(f.Tag)
588 extraTabs = 0
589 }
590 if f.Comment != nil {
591 for ; extraTabs > 0; extraTabs-- {
592 p.print(sep)
593 }
594 p.setComment(f.Comment)
595 }
596 }
597 if isIncomplete {
598 if len(list) > 0 {
599 p.print(formfeed)
600 }
601 p.flush(p.posFor(rbrace), token.RBRACE) // make sure we don't lose the last line comment
602 p.setLineComment("// " + filteredMsg)
603 }
604
605 } else { // interface
606
607 var line int
608 var prev *ast.Ident // previous "type" identifier
609 for i, f := range list {
610 var name *ast.Ident // first name, or nil
611 if len(f.Names) > 0 {
612 name = f.Names[0]
613 }
614 if i > 0 {
615 // don't do a line break (min == 0) if we are printing a list of types
616 // TODO(gri) this doesn't work quite right if the list of types is
617 // spread across multiple lines
618 min := 1
619 if prev != nil && name == prev {
620 min = 0
621 }
622 p.linebreak(p.lineFor(f.Pos()), min, ignore, p.linesFrom(line) > 0)
623 }
624 p.setComment(f.Doc)
625 p.recordLine(&line)
626 if name != nil {
627 // method
628 p.expr(name)
629 p.signature(f.Type.(*ast.FuncType)) // don't print "func"
630 prev = nil
631 } else {
632 // embedded interface
633 p.expr(f.Type)
634 prev = nil
635 }
636 p.setComment(f.Comment)
637 }
638 if isIncomplete {
639 if len(list) > 0 {
640 p.print(formfeed)
641 }
642 p.flush(p.posFor(rbrace), token.RBRACE) // make sure we don't lose the last line comment
643 p.setLineComment("// contains filtered or unexported methods")
644 }
645
646 }
647 p.print(unindent, formfeed)
648 p.setPos(rbrace)
649 p.print(token.RBRACE)
650 }
651
652 // ----------------------------------------------------------------------------
653 // Expressions
654
655 func walkBinary(e *ast.BinaryExpr) (has4, has5 bool, maxProblem int) {
656 switch e.Op.Precedence() {
657 case 4:
658 has4 = true
659 case 5:
660 has5 = true
661 }
662
663 switch l := e.X.(type) {
664 case *ast.BinaryExpr:
665 if l.Op.Precedence() < e.Op.Precedence() {
666 // parens will be inserted.
667 // pretend this is an *ast.ParenExpr and do nothing.
668 break
669 }
670 h4, h5, mp := walkBinary(l)
671 has4 = has4 || h4
672 has5 = has5 || h5
673 if maxProblem < mp {
674 maxProblem = mp
675 }
676 }
677
678 switch r := e.Y.(type) {
679 case *ast.BinaryExpr:
680 if r.Op.Precedence() <= e.Op.Precedence() {
681 // parens will be inserted.
682 // pretend this is an *ast.ParenExpr and do nothing.
683 break
684 }
685 h4, h5, mp := walkBinary(r)
686 has4 = has4 || h4
687 has5 = has5 || h5
688 if maxProblem < mp {
689 maxProblem = mp
690 }
691
692 case *ast.StarExpr:
693 if e.Op == token.QUO { // `*/`
694 maxProblem = 5
695 }
696
697 case *ast.UnaryExpr:
698 switch e.Op.String() + r.Op.String() {
699 case "/*", "&&", "&^":
700 maxProblem = 5
701 case "++", "--":
702 if maxProblem < 4 {
703 maxProblem = 4
704 }
705 }
706 }
707 return
708 }
709
710 func cutoff(e *ast.BinaryExpr, depth int) int {
711 has4, has5, maxProblem := walkBinary(e)
712 if maxProblem > 0 {
713 return maxProblem + 1
714 }
715 if has4 && has5 {
716 if depth == 1 {
717 return 5
718 }
719 return 4
720 }
721 if depth == 1 {
722 return 6
723 }
724 return 4
725 }
726
727 func diffPrec(expr ast.Expr, prec int) int {
728 x, ok := expr.(*ast.BinaryExpr)
729 if !ok || prec != x.Op.Precedence() {
730 return 1
731 }
732 return 0
733 }
734
735 func reduceDepth(depth int) int {
736 depth--
737 if depth < 1 {
738 depth = 1
739 }
740 return depth
741 }
742
743 // Format the binary expression: decide the cutoff and then format.
744 // Let's call depth == 1 Normal mode, and depth > 1 Compact mode.
745 // (Algorithm suggestion by Russ Cox.)
746 //
747 // The precedences are:
748 //
749 // 5 * / % << >> & &^
750 // 4 + - | ^
751 // 3 == != < <= > >=
752 // 2 &&
753 // 1 ||
754 //
755 // The only decision is whether there will be spaces around levels 4 and 5.
756 // There are never spaces at level 6 (unary), and always spaces at levels 3 and below.
757 //
758 // To choose the cutoff, look at the whole expression but excluding primary
759 // expressions (function calls, parenthesized exprs), and apply these rules:
760 //
761 // 1. If there is a binary operator with a right side unary operand
762 // that would clash without a space, the cutoff must be (in order):
763 //
764 // /* 6
765 // && 6
766 // &^ 6
767 // ++ 5
768 // -- 5
769 //
770 // (Comparison operators always have spaces around them.)
771 //
772 // 2. If there is a mix of level 5 and level 4 operators, then the cutoff
773 // is 5 (use spaces to distinguish precedence) in Normal mode
774 // and 4 (never use spaces) in Compact mode.
775 //
776 // 3. If there are no level 4 operators or no level 5 operators, then the
777 // cutoff is 6 (always use spaces) in Normal mode
778 // and 4 (never use spaces) in Compact mode.
779 func (p *printer) binaryExpr(x *ast.BinaryExpr, prec1, cutoff, depth int) {
780 prec := x.Op.Precedence()
781 if prec < prec1 {
782 // parenthesis needed
783 // Note: The parser inserts an ast.ParenExpr node; thus this case
784 // can only occur if the AST is created in a different way.
785 p.print(token.LPAREN)
786 p.expr0(x, reduceDepth(depth)) // parentheses undo one level of depth
787 p.print(token.RPAREN)
788 return
789 }
790
791 printBlank := prec < cutoff
792
793 ws := indent
794 p.expr1(x.X, prec, depth+diffPrec(x.X, prec))
795 if printBlank {
796 p.print(blank)
797 }
798 xline := p.pos.Line // before the operator (it may be on the next line!)
799 yline := p.lineFor(x.Y.Pos())
800 p.setPos(x.OpPos)
801 p.print(x.Op)
802 if xline != yline && xline > 0 && yline > 0 {
803 // at least one line break, but respect an extra empty line
804 // in the source
805 if p.linebreak(yline, 1, ws, true) > 0 {
806 ws = ignore
807 printBlank = false // no blank after line break
808 }
809 }
810 if printBlank {
811 p.print(blank)
812 }
813 p.expr1(x.Y, prec+1, depth+1)
814 if ws == ignore {
815 p.print(unindent)
816 }
817 }
818
819 func isBinary(expr ast.Expr) bool {
820 _, ok := expr.(*ast.BinaryExpr)
821 return ok
822 }
823
824 func (p *printer) expr1(expr ast.Expr, prec1, depth int) {
825 p.setPos(expr.Pos())
826
827 switch x := expr.(type) {
828 case *ast.BadExpr:
829 p.print("BadExpr")
830
831 case *ast.Ident:
832 p.print(x)
833
834 case *ast.BinaryExpr:
835 if depth < 1 {
836 p.internalError("depth < 1:", depth)
837 depth = 1
838 }
839 p.binaryExpr(x, prec1, cutoff(x, depth), depth)
840
841 case *ast.KeyValueExpr:
842 p.expr(x.Key)
843 p.setPos(x.Colon)
844 p.print(token.COLON, blank)
845 p.expr(x.Value)
846
847 case *ast.StarExpr:
848 const prec = token.UnaryPrec
849 if prec < prec1 {
850 // parenthesis needed
851 p.print(token.LPAREN)
852 p.print(token.MUL)
853 p.expr(x.X)
854 p.print(token.RPAREN)
855 } else {
856 // no parenthesis needed
857 p.print(token.MUL)
858 p.expr(x.X)
859 }
860
861 case *ast.UnaryExpr:
862 const prec = token.UnaryPrec
863 if prec < prec1 {
864 // parenthesis needed
865 p.print(token.LPAREN)
866 p.expr(x)
867 p.print(token.RPAREN)
868 } else {
869 // no parenthesis needed
870 p.print(x.Op)
871 if x.Op == token.RANGE {
872 // TODO(gri) Remove this code if it cannot be reached.
873 p.print(blank)
874 }
875 p.expr1(x.X, prec, depth)
876 }
877
878 case *ast.BasicLit:
879 if p.Config.Mode&normalizeNumbers != 0 {
880 x = normalizedNumber(x)
881 }
882 p.print(x)
883
884 case *ast.FuncLit:
885 p.setPos(x.Type.Pos())
886 p.print(token.FUNC)
887 // See the comment in funcDecl about how the header size is computed.
888 startCol := p.out.Column - len("func")
889 p.signature(x.Type)
890 p.funcBody(p.distanceFrom(x.Type.Pos(), startCol), blank, x.Body)
891
892 case *ast.ParenExpr:
893 if _, hasParens := x.X.(*ast.ParenExpr); hasParens {
894 // don't print parentheses around an already parenthesized expression
895 // TODO(gri) consider making this more general and incorporate precedence levels
896 p.expr0(x.X, depth)
897 } else {
898 p.print(token.LPAREN)
899 p.expr0(x.X, reduceDepth(depth)) // parentheses undo one level of depth
900 p.setPos(x.Rparen)
901 p.print(token.RPAREN)
902 }
903
904 case *ast.SelectorExpr:
905 p.selectorExpr(x, depth, false)
906
907 case *ast.TypeAssertExpr:
908 p.expr1(x.X, token.HighestPrec, depth)
909 p.print(token.PERIOD)
910 p.setPos(x.Lparen)
911 p.print(token.LPAREN)
912 if x.Type != nil {
913 p.expr(x.Type)
914 } else {
915 p.print(token.TYPE)
916 }
917 p.setPos(x.Rparen)
918 p.print(token.RPAREN)
919
920 case *ast.IndexExpr:
921 // TODO(gri): should treat[] like parentheses and undo one level of depth
922 p.expr1(x.X, token.HighestPrec, 1)
923 p.setPos(x.Lbrack)
924 p.print(token.LBRACK)
925 p.expr0(x.Index, depth+1)
926 p.setPos(x.Rbrack)
927 p.print(token.RBRACK)
928
929 case *ast.IndexListExpr:
930 // TODO(gri): as for IndexExpr, should treat [] like parentheses and undo
931 // one level of depth
932 p.expr1(x.X, token.HighestPrec, 1)
933 p.setPos(x.Lbrack)
934 p.print(token.LBRACK)
935 p.exprList(x.Lbrack, x.Indices, depth+1, commaTerm, x.Rbrack, false)
936 p.setPos(x.Rbrack)
937 p.print(token.RBRACK)
938
939 case *ast.SliceExpr:
940 // TODO(gri): should treat[] like parentheses and undo one level of depth
941 p.expr1(x.X, token.HighestPrec, 1)
942 p.setPos(x.Lbrack)
943 p.print(token.LBRACK)
944 indices := []ast.Expr{x.Low, x.High}
945 if x.Max != nil {
946 indices = append(indices, x.Max)
947 }
948 // determine if we need extra blanks around ':'
949 var needsBlanks bool
950 if depth <= 1 {
951 var indexCount int
952 var hasBinaries bool
953 for _, x := range indices {
954 if x != nil {
955 indexCount++
956 if isBinary(x) {
957 hasBinaries = true
958 }
959 }
960 }
961 if indexCount > 1 && hasBinaries {
962 needsBlanks = true
963 }
964 }
965 for i, x := range indices {
966 if i > 0 {
967 if indices[i-1] != nil && needsBlanks {
968 p.print(blank)
969 }
970 p.print(token.COLON)
971 if x != nil && needsBlanks {
972 p.print(blank)
973 }
974 }
975 if x != nil {
976 p.expr0(x, depth+1)
977 }
978 }
979 p.setPos(x.Rbrack)
980 p.print(token.RBRACK)
981
982 case *ast.CallExpr:
983 if len(x.Args) > 1 {
984 depth++
985 }
986 var wasIndented bool
987 if _, ok := x.Fun.(*ast.FuncType); ok {
988 // conversions to literal function types require parentheses around the type
989 p.print(token.LPAREN)
990 wasIndented = p.possibleSelectorExpr(x.Fun, token.HighestPrec, depth)
991 p.print(token.RPAREN)
992 } else {
993 wasIndented = p.possibleSelectorExpr(x.Fun, token.HighestPrec, depth)
994 }
995 p.setPos(x.Lparen)
996 p.print(token.LPAREN)
997 if x.Ellipsis.IsValid() {
998 p.exprList(x.Lparen, x.Args, depth, 0, x.Ellipsis, false)
999 p.setPos(x.Ellipsis)
1000 p.print(token.ELLIPSIS)
1001 if x.Rparen.IsValid() && p.lineFor(x.Ellipsis) < p.lineFor(x.Rparen) {
1002 p.print(token.COMMA, formfeed)
1003 }
1004 } else {
1005 p.exprList(x.Lparen, x.Args, depth, commaTerm, x.Rparen, false)
1006 }
1007 p.setPos(x.Rparen)
1008 p.print(token.RPAREN)
1009 if wasIndented {
1010 p.print(unindent)
1011 }
1012
1013 case *ast.CompositeLit:
1014 // composite literal elements that are composite literals themselves may have the type omitted
1015 if x.Type != nil {
1016 p.expr1(x.Type, token.HighestPrec, depth)
1017 }
1018 p.level++
1019 p.setPos(x.Lbrace)
1020 p.print(token.LBRACE)
1021 p.exprList(x.Lbrace, x.Elts, 1, commaTerm, x.Rbrace, x.Incomplete)
1022 // do not insert extra line break following a /*-style comment
1023 // before the closing '}' as it might break the code if there
1024 // is no trailing ','
1025 mode := noExtraLinebreak
1026 // do not insert extra blank following a /*-style comment
1027 // before the closing '}' unless the literal is empty
1028 if len(x.Elts) > 0 {
1029 mode |= noExtraBlank
1030 }
1031 // need the initial indent to print lone comments with
1032 // the proper level of indentation
1033 p.print(indent, unindent, mode)
1034 p.setPos(x.Rbrace)
1035 p.print(token.RBRACE, mode)
1036 p.level--
1037
1038 case *ast.Ellipsis:
1039 p.print(token.ELLIPSIS)
1040 if x.Elt != nil {
1041 p.expr(x.Elt)
1042 }
1043
1044 case *ast.ArrayType:
1045 p.print(token.LBRACK)
1046 if x.Len != nil {
1047 p.expr(x.Len)
1048 }
1049 p.print(token.RBRACK)
1050 p.expr(x.Elt)
1051
1052 case *ast.StructType:
1053 p.print(token.STRUCT)
1054 p.fieldList(x.Fields, true, x.Incomplete)
1055
1056 case *ast.FuncType:
1057 p.print(token.FUNC)
1058 p.signature(x)
1059
1060 case *ast.InterfaceType:
1061 p.print(token.INTERFACE)
1062 p.fieldList(x.Methods, false, x.Incomplete)
1063
1064 case *ast.MapType:
1065 p.print(token.MAP, token.LBRACK)
1066 p.expr(x.Key)
1067 p.print(token.RBRACK)
1068 p.expr(x.Value)
1069
1070 case *ast.ChanType:
1071 switch x.Dir {
1072 case ast.SEND | ast.RECV:
1073 p.print(token.CHAN)
1074 case ast.RECV:
1075 p.print(token.ARROW, token.CHAN) // x.Arrow and x.Pos() are the same
1076 case ast.SEND:
1077 p.print(token.CHAN)
1078 p.setPos(x.Arrow)
1079 p.print(token.ARROW)
1080 }
1081 p.print(blank)
1082 p.expr(x.Value)
1083
1084 default:
1085 panic("unreachable")
1086 }
1087 }
1088
1089 // normalizedNumber rewrites base prefixes and exponents
1090 // of numbers to use lower-case letters (0X123 to 0x123 and 1.2E3 to 1.2e3),
1091 // and removes leading 0's from integer imaginary literals (0765i to 765i).
1092 // It leaves hexadecimal digits alone.
1093 //
1094 // normalizedNumber doesn't modify the ast.BasicLit value lit points to.
1095 // If lit is not a number or a number in canonical format already,
1096 // lit is returned as is. Otherwise a new ast.BasicLit is created.
1097 func normalizedNumber(lit *ast.BasicLit) *ast.BasicLit {
1098 if lit.Kind != token.INT && lit.Kind != token.FLOAT && lit.Kind != token.IMAG {
1099 return lit // not a number - nothing to do
1100 }
1101 if len(lit.Value) < 2 {
1102 return lit // only one digit (common case) - nothing to do
1103 }
1104 // len(lit.Value) >= 2
1105
1106 // We ignore lit.Kind because for lit.Kind == token.IMAG the literal may be an integer
1107 // or floating-point value, decimal or not. Instead, just consider the literal pattern.
1108 x := lit.Value
1109 switch x[:2] {
1110 default:
1111 // 0-prefix octal, decimal int, or float (possibly with 'i' suffix)
1112 if i := strings.LastIndexByte(x, 'E'); i >= 0 {
1113 x = x[:i] + "e" + x[i+1:]
1114 break
1115 }
1116 // remove leading 0's from integer (but not floating-point) imaginary literals
1117 if x[len(x)-1] == 'i' && !strings.ContainsAny(x, ".e") {
1118 x = strings.TrimLeft(x, "0_")
1119 if x == "i" {
1120 x = "0i"
1121 }
1122 }
1123 case "0X":
1124 x = "0x" + x[2:]
1125 // possibly a hexadecimal float
1126 if i := strings.LastIndexByte(x, 'P'); i >= 0 {
1127 x = x[:i] + "p" + x[i+1:]
1128 }
1129 case "0x":
1130 // possibly a hexadecimal float
1131 i := strings.LastIndexByte(x, 'P')
1132 if i == -1 {
1133 return lit // nothing to do
1134 }
1135 x = x[:i] + "p" + x[i+1:]
1136 case "0O":
1137 x = "0o" + x[2:]
1138 case "0o":
1139 return lit // nothing to do
1140 case "0B":
1141 x = "0b" + x[2:]
1142 case "0b":
1143 return lit // nothing to do
1144 }
1145
1146 return &ast.BasicLit{ValuePos: lit.ValuePos, Kind: lit.Kind, Value: x}
1147 }
1148
1149 func (p *printer) possibleSelectorExpr(expr ast.Expr, prec1, depth int) bool {
1150 if x, ok := expr.(*ast.SelectorExpr); ok {
1151 return p.selectorExpr(x, depth, true)
1152 }
1153 p.expr1(expr, prec1, depth)
1154 return false
1155 }
1156
1157 // selectorExpr handles an *ast.SelectorExpr node and reports whether x spans
1158 // multiple lines.
1159 func (p *printer) selectorExpr(x *ast.SelectorExpr, depth int, isMethod bool) bool {
1160 p.expr1(x.X, token.HighestPrec, depth)
1161 p.print(token.PERIOD)
1162 if line := p.lineFor(x.Sel.Pos()); p.pos.IsValid() && p.pos.Line < line {
1163 p.print(indent, newline)
1164 p.setPos(x.Sel.Pos())
1165 p.print(x.Sel)
1166 if !isMethod {
1167 p.print(unindent)
1168 }
1169 return true
1170 }
1171 p.setPos(x.Sel.Pos())
1172 p.print(x.Sel)
1173 return false
1174 }
1175
1176 func (p *printer) expr0(x ast.Expr, depth int) {
1177 p.expr1(x, token.LowestPrec, depth)
1178 }
1179
1180 func (p *printer) expr(x ast.Expr) {
1181 const depth = 1
1182 p.expr1(x, token.LowestPrec, depth)
1183 }
1184
1185 // ----------------------------------------------------------------------------
1186 // Statements
1187
1188 // Print the statement list indented, but without a newline after the last statement.
1189 // Extra line breaks between statements in the source are respected but at most one
1190 // empty line is printed between statements.
1191 func (p *printer) stmtList(list []ast.Stmt, nindent int, nextIsRBrace bool) {
1192 if nindent > 0 {
1193 p.print(indent)
1194 }
1195 var line int
1196 i := 0
1197 for _, s := range list {
1198 // ignore empty statements (was issue 3466)
1199 if _, isEmpty := s.(*ast.EmptyStmt); !isEmpty {
1200 // nindent == 0 only for lists of switch/select case clauses;
1201 // in those cases each clause is a new section
1202 if len(p.output) > 0 {
1203 // only print line break if we are not at the beginning of the output
1204 // (i.e., we are not printing only a partial program)
1205 p.linebreak(p.lineFor(s.Pos()), 1, ignore, i == 0 || nindent == 0 || p.linesFrom(line) > 0)
1206 }
1207 p.recordLine(&line)
1208 p.stmt(s, nextIsRBrace && i == len(list)-1)
1209 // labeled statements put labels on a separate line, but here
1210 // we only care about the start line of the actual statement
1211 // without label - correct line for each label
1212 for t := s; ; {
1213 lt, _ := t.(*ast.LabeledStmt)
1214 if lt == nil {
1215 break
1216 }
1217 line++
1218 t = lt.Stmt
1219 }
1220 i++
1221 }
1222 }
1223 if nindent > 0 {
1224 p.print(unindent)
1225 }
1226 }
1227
1228 // block prints an *ast.BlockStmt; it always spans at least two lines.
1229 func (p *printer) block(b *ast.BlockStmt, nindent int) {
1230 p.setPos(b.Lbrace)
1231 p.print(token.LBRACE)
1232 p.stmtList(b.List, nindent, true)
1233 p.linebreak(p.lineFor(b.Rbrace), 1, ignore, true)
1234 p.setPos(b.Rbrace)
1235 p.print(token.RBRACE)
1236 }
1237
1238 func isTypeName(x ast.Expr) bool {
1239 switch t := x.(type) {
1240 case *ast.Ident:
1241 return true
1242 case *ast.SelectorExpr:
1243 return isTypeName(t.X)
1244 }
1245 return false
1246 }
1247
1248 func stripParens(x ast.Expr) ast.Expr {
1249 if px, strip := x.(*ast.ParenExpr); strip {
1250 // parentheses must not be stripped if there are any
1251 // unparenthesized composite literals starting with
1252 // a type name
1253 ast.Inspect(px.X, func(node ast.Node) bool {
1254 switch x := node.(type) {
1255 case *ast.ParenExpr:
1256 // parentheses protect enclosed composite literals
1257 return false
1258 case *ast.CompositeLit:
1259 if isTypeName(x.Type) {
1260 strip = false // do not strip parentheses
1261 }
1262 return false
1263 }
1264 // in all other cases, keep inspecting
1265 return true
1266 })
1267 if strip {
1268 return stripParens(px.X)
1269 }
1270 }
1271 return x
1272 }
1273
1274 func stripParensAlways(x ast.Expr) ast.Expr {
1275 if x, ok := x.(*ast.ParenExpr); ok {
1276 return stripParensAlways(x.X)
1277 }
1278 return x
1279 }
1280
1281 func (p *printer) controlClause(isForStmt bool, init ast.Stmt, expr ast.Expr, post ast.Stmt) {
1282 p.print(blank)
1283 needsBlank := false
1284 if init == nil && post == nil {
1285 // no semicolons required
1286 if expr != nil {
1287 p.expr(stripParens(expr))
1288 needsBlank = true
1289 }
1290 } else {
1291 // all semicolons required
1292 // (they are not separators, print them explicitly)
1293 if init != nil {
1294 p.stmt(init, false)
1295 }
1296 p.print(token.SEMICOLON, blank)
1297 if expr != nil {
1298 p.expr(stripParens(expr))
1299 needsBlank = true
1300 }
1301 if isForStmt {
1302 p.print(token.SEMICOLON, blank)
1303 needsBlank = false
1304 if post != nil {
1305 p.stmt(post, false)
1306 needsBlank = true
1307 }
1308 }
1309 }
1310 if needsBlank {
1311 p.print(blank)
1312 }
1313 }
1314
1315 // indentList reports whether an expression list would look better if it
1316 // were indented wholesale (starting with the very first element, rather
1317 // than starting at the first line break).
1318 func (p *printer) indentList(list []ast.Expr) bool {
1319 // Heuristic: indentList reports whether there are more than one multi-
1320 // line element in the list, or if there is any element that is not
1321 // starting on the same line as the previous one ends.
1322 if len(list) >= 2 {
1323 b := p.lineFor(list[0].Pos())
1324 e := p.lineFor(list[len(list)-1].End())
1325 if 0 < b && b < e {
1326 // list spans multiple lines
1327 n := 0 // multi-line element count
1328 line := b
1329 for _, x := range list {
1330 xb := p.lineFor(x.Pos())
1331 xe := p.lineFor(x.End())
1332 if line < xb {
1333 // x is not starting on the same
1334 // line as the previous one ended
1335 return true
1336 }
1337 if xb < xe {
1338 // x is a multi-line element
1339 n++
1340 }
1341 line = xe
1342 }
1343 return n > 1
1344 }
1345 }
1346 return false
1347 }
1348
1349 func (p *printer) stmt(stmt ast.Stmt, nextIsRBrace bool) {
1350 p.setPos(stmt.Pos())
1351
1352 switch s := stmt.(type) {
1353 case *ast.BadStmt:
1354 p.print("BadStmt")
1355
1356 case *ast.DeclStmt:
1357 p.decl(s.Decl)
1358
1359 case *ast.EmptyStmt:
1360 // nothing to do
1361
1362 case *ast.LabeledStmt:
1363 // a "correcting" unindent immediately following a line break
1364 // is applied before the line break if there is no comment
1365 // between (see writeWhitespace)
1366 p.print(unindent)
1367 p.expr(s.Label)
1368 p.setPos(s.Colon)
1369 p.print(token.COLON, indent)
1370 if e, isEmpty := s.Stmt.(*ast.EmptyStmt); isEmpty {
1371 if !nextIsRBrace {
1372 p.print(newline)
1373 p.setPos(e.Pos())
1374 p.print(token.SEMICOLON)
1375 break
1376 }
1377 } else {
1378 p.linebreak(p.lineFor(s.Stmt.Pos()), 1, ignore, true)
1379 }
1380 p.stmt(s.Stmt, nextIsRBrace)
1381
1382 case *ast.ExprStmt:
1383 const depth = 1
1384 p.expr0(s.X, depth)
1385
1386 case *ast.SendStmt:
1387 const depth = 1
1388 p.expr0(s.Chan, depth)
1389 p.print(blank)
1390 p.setPos(s.Arrow)
1391 p.print(token.ARROW, blank)
1392 p.expr0(s.Value, depth)
1393
1394 case *ast.IncDecStmt:
1395 const depth = 1
1396 p.expr0(s.X, depth+1)
1397 p.setPos(s.TokPos)
1398 p.print(s.Tok)
1399
1400 case *ast.AssignStmt:
1401 depth := 1
1402 if len(s.Lhs) > 1 && len(s.Rhs) > 1 {
1403 depth++
1404 }
1405 p.exprList(s.Pos(), s.Lhs, depth, 0, s.TokPos, false)
1406 p.print(blank)
1407 p.setPos(s.TokPos)
1408 p.print(s.Tok, blank)
1409 p.exprList(s.TokPos, s.Rhs, depth, 0, token.NoPos, false)
1410
1411 case *ast.GoStmt:
1412 p.print(token.GO, blank)
1413 p.expr(s.Call)
1414
1415 case *ast.DeferStmt:
1416 p.print(token.DEFER, blank)
1417 p.expr(s.Call)
1418
1419 case *ast.ReturnStmt:
1420 p.print(token.RETURN)
1421 if s.Results != nil {
1422 p.print(blank)
1423 // Use indentList heuristic to make corner cases look
1424 // better (issue 1207). A more systematic approach would
1425 // always indent, but this would cause significant
1426 // reformatting of the code base and not necessarily
1427 // lead to more nicely formatted code in general.
1428 if p.indentList(s.Results) {
1429 p.print(indent)
1430 // Use NoPos so that a newline never goes before
1431 // the results (see issue #32854).
1432 p.exprList(token.NoPos, s.Results, 1, noIndent, token.NoPos, false)
1433 p.print(unindent)
1434 } else {
1435 p.exprList(token.NoPos, s.Results, 1, 0, token.NoPos, false)
1436 }
1437 }
1438
1439 case *ast.BranchStmt:
1440 p.print(s.Tok)
1441 if s.Label != nil {
1442 p.print(blank)
1443 p.expr(s.Label)
1444 }
1445
1446 case *ast.BlockStmt:
1447 p.block(s, 1)
1448
1449 case *ast.IfStmt:
1450 p.print(token.IF)
1451 p.controlClause(false, s.Init, s.Cond, nil)
1452 p.block(s.Body, 1)
1453 if s.Else != nil {
1454 p.print(blank, token.ELSE, blank)
1455 switch s.Else.(type) {
1456 case *ast.BlockStmt, *ast.IfStmt:
1457 p.stmt(s.Else, nextIsRBrace)
1458 default:
1459 // This can only happen with an incorrectly
1460 // constructed AST. Permit it but print so
1461 // that it can be parsed without errors.
1462 p.print(token.LBRACE, indent, formfeed)
1463 p.stmt(s.Else, true)
1464 p.print(unindent, formfeed, token.RBRACE)
1465 }
1466 }
1467
1468 case *ast.CaseClause:
1469 if s.List != nil {
1470 p.print(token.CASE, blank)
1471 p.exprList(s.Pos(), s.List, 1, 0, s.Colon, false)
1472 } else {
1473 p.print(token.DEFAULT)
1474 }
1475 p.setPos(s.Colon)
1476 p.print(token.COLON)
1477 p.stmtList(s.Body, 1, nextIsRBrace)
1478
1479 case *ast.SwitchStmt:
1480 p.print(token.SWITCH)
1481 p.controlClause(false, s.Init, s.Tag, nil)
1482 p.block(s.Body, 0)
1483
1484 case *ast.TypeSwitchStmt:
1485 p.print(token.SWITCH)
1486 if s.Init != nil {
1487 p.print(blank)
1488 p.stmt(s.Init, false)
1489 p.print(token.SEMICOLON)
1490 }
1491 p.print(blank)
1492 p.stmt(s.Assign, false)
1493 p.print(blank)
1494 p.block(s.Body, 0)
1495
1496 case *ast.CommClause:
1497 if s.Comm != nil {
1498 p.print(token.CASE, blank)
1499 p.stmt(s.Comm, false)
1500 } else {
1501 p.print(token.DEFAULT)
1502 }
1503 p.setPos(s.Colon)
1504 p.print(token.COLON)
1505 p.stmtList(s.Body, 1, nextIsRBrace)
1506
1507 case *ast.SelectStmt:
1508 p.print(token.SELECT, blank)
1509 body := s.Body
1510 if len(body.List) == 0 && !p.commentBefore(p.posFor(body.Rbrace)) {
1511 // print empty select statement w/o comments on one line
1512 p.setPos(body.Lbrace)
1513 p.print(token.LBRACE)
1514 p.setPos(body.Rbrace)
1515 p.print(token.RBRACE)
1516 } else {
1517 p.block(body, 0)
1518 }
1519
1520 case *ast.ForStmt:
1521 p.print(token.FOR)
1522 p.controlClause(true, s.Init, s.Cond, s.Post)
1523 p.block(s.Body, 1)
1524
1525 case *ast.RangeStmt:
1526 p.print(token.FOR, blank)
1527 if s.Key != nil {
1528 p.expr(s.Key)
1529 if s.Value != nil {
1530 // use position of value following the comma as
1531 // comma position for correct comment placement
1532 p.setPos(s.Value.Pos())
1533 p.print(token.COMMA, blank)
1534 p.expr(s.Value)
1535 }
1536 p.print(blank)
1537 p.setPos(s.TokPos)
1538 p.print(s.Tok, blank)
1539 }
1540 p.print(token.RANGE, blank)
1541 p.expr(stripParens(s.X))
1542 p.print(blank)
1543 p.block(s.Body, 1)
1544
1545 default:
1546 panic("unreachable")
1547 }
1548 }
1549
1550 // ----------------------------------------------------------------------------
1551 // Declarations
1552
1553 // The keepTypeColumn function determines if the type column of a series of
1554 // consecutive const or var declarations must be kept, or if initialization
1555 // values (V) can be placed in the type column (T) instead. The i'th entry
1556 // in the result slice is true if the type column in spec[i] must be kept.
1557 //
1558 // For example, the declaration:
1559 //
1560 // const (
1561 // foobar int = 42 // comment
1562 // x = 7 // comment
1563 // foo
1564 // bar = 991
1565 // )
1566 //
1567 // leads to the type/values matrix below. A run of value columns (V) can
1568 // be moved into the type column if there is no type for any of the values
1569 // in that column (we only move entire columns so that they align properly).
1570 //
1571 // matrix formatted result
1572 // matrix
1573 // T V -> T V -> true there is a T and so the type
1574 // - V - V true column must be kept
1575 // - - - - false
1576 // - V V - false V is moved into T column
1577 func keepTypeColumn(specs []ast.Spec) []bool {
1578 m := make([]bool, len(specs))
1579
1580 populate := func(i, j int, keepType bool) {
1581 if keepType {
1582 for ; i < j; i++ {
1583 m[i] = true
1584 }
1585 }
1586 }
1587
1588 i0 := -1 // if i0 >= 0 we are in a run and i0 is the start of the run
1589 var keepType bool
1590 for i, s := range specs {
1591 t := s.(*ast.ValueSpec)
1592 if t.Values != nil {
1593 if i0 < 0 {
1594 // start of a run of ValueSpecs with non-nil Values
1595 i0 = i
1596 keepType = false
1597 }
1598 } else {
1599 if i0 >= 0 {
1600 // end of a run
1601 populate(i0, i, keepType)
1602 i0 = -1
1603 }
1604 }
1605 if t.Type != nil {
1606 keepType = true
1607 }
1608 }
1609 if i0 >= 0 {
1610 // end of a run
1611 populate(i0, len(specs), keepType)
1612 }
1613
1614 return m
1615 }
1616
1617 func (p *printer) valueSpec(s *ast.ValueSpec, keepType bool) {
1618 p.setComment(s.Doc)
1619 p.identList(s.Names, false) // always present
1620 extraTabs := 3
1621 if s.Type != nil || keepType {
1622 p.print(vtab)
1623 extraTabs--
1624 }
1625 if s.Type != nil {
1626 p.expr(s.Type)
1627 }
1628 if s.Values != nil {
1629 p.print(vtab, token.ASSIGN, blank)
1630 p.exprList(token.NoPos, s.Values, 1, 0, token.NoPos, false)
1631 extraTabs--
1632 }
1633 if s.Comment != nil {
1634 for ; extraTabs > 0; extraTabs-- {
1635 p.print(vtab)
1636 }
1637 p.setComment(s.Comment)
1638 }
1639 }
1640
1641 func sanitizeImportPath(lit *ast.BasicLit) *ast.BasicLit {
1642 // Note: An unmodified AST generated by go/parser will already
1643 // contain a backward- or double-quoted path string that does
1644 // not contain any invalid characters, and most of the work
1645 // here is not needed. However, a modified or generated AST
1646 // may possibly contain non-canonical paths. Do the work in
1647 // all cases since it's not too hard and not speed-critical.
1648
1649 // if we don't have a proper string, be conservative and return whatever we have
1650 if lit.Kind != token.STRING {
1651 return lit
1652 }
1653 s, err := strconv.Unquote(lit.Value)
1654 if err != nil {
1655 return lit
1656 }
1657
1658 // if the string is an invalid path, return whatever we have
1659 //
1660 // spec: "Implementation restriction: A compiler may restrict
1661 // ImportPaths to non-empty strings using only characters belonging
1662 // to Unicode's L, M, N, P, and S general categories (the Graphic
1663 // characters without spaces) and may also exclude the characters
1664 // !"#$%&'()*,:;<=>?[\]^`{|} and the Unicode replacement character
1665 // U+FFFD."
1666 if s == "" {
1667 return lit
1668 }
1669 const illegalChars = `!"#$%&'()*,:;<=>?[\]^{|}` + "`\uFFFD"
1670 for _, r := range s {
1671 if !unicode.IsGraphic(r) || unicode.IsSpace(r) || strings.ContainsRune(illegalChars, r) {
1672 return lit
1673 }
1674 }
1675
1676 // otherwise, return the double-quoted path
1677 s = strconv.Quote(s)
1678 if s == lit.Value {
1679 return lit // nothing wrong with lit
1680 }
1681 return &ast.BasicLit{ValuePos: lit.ValuePos, Kind: token.STRING, Value: s}
1682 }
1683
1684 // The parameter n is the number of specs in the group. If doIndent is set,
1685 // multi-line identifier lists in the spec are indented when the first
1686 // linebreak is encountered.
1687 func (p *printer) spec(spec ast.Spec, n int, doIndent bool) {
1688 switch s := spec.(type) {
1689 case *ast.ImportSpec:
1690 p.setComment(s.Doc)
1691 if s.Name != nil {
1692 p.expr(s.Name)
1693 p.print(blank)
1694 }
1695 p.expr(sanitizeImportPath(s.Path))
1696 p.setComment(s.Comment)
1697 p.setPos(s.EndPos)
1698
1699 case *ast.ValueSpec:
1700 if n != 1 {
1701 p.internalError("expected n = 1; got", n)
1702 }
1703 p.setComment(s.Doc)
1704 p.identList(s.Names, doIndent) // always present
1705 if s.Type != nil {
1706 p.print(blank)
1707 p.expr(s.Type)
1708 }
1709 if s.Values != nil {
1710 p.print(blank, token.ASSIGN, blank)
1711 p.exprList(token.NoPos, s.Values, 1, 0, token.NoPos, false)
1712 }
1713 p.setComment(s.Comment)
1714
1715 case *ast.TypeSpec:
1716 p.setComment(s.Doc)
1717 p.expr(s.Name)
1718 if s.TypeParams != nil {
1719 p.parameters(s.TypeParams, typeTParam)
1720 }
1721 if n == 1 {
1722 p.print(blank)
1723 } else {
1724 p.print(vtab)
1725 }
1726 if s.Assign.IsValid() {
1727 p.print(token.ASSIGN, blank)
1728 }
1729 p.expr(s.Type)
1730 p.setComment(s.Comment)
1731
1732 default:
1733 panic("unreachable")
1734 }
1735 }
1736
1737 func (p *printer) genDecl(d *ast.GenDecl) {
1738 p.setComment(d.Doc)
1739 p.setPos(d.Pos())
1740 p.print(d.Tok, blank)
1741
1742 if d.Lparen.IsValid() || len(d.Specs) > 1 {
1743 // group of parenthesized declarations
1744 p.setPos(d.Lparen)
1745 p.print(token.LPAREN)
1746 if n := len(d.Specs); n > 0 {
1747 p.print(indent, formfeed)
1748 if n > 1 && (d.Tok == token.CONST || d.Tok == token.VAR) {
1749 // two or more grouped const/var declarations:
1750 // determine if the type column must be kept
1751 keepType := keepTypeColumn(d.Specs)
1752 var line int
1753 for i, s := range d.Specs {
1754 if i > 0 {
1755 p.linebreak(p.lineFor(s.Pos()), 1, ignore, p.linesFrom(line) > 0)
1756 }
1757 p.recordLine(&line)
1758 p.valueSpec(s.(*ast.ValueSpec), keepType[i])
1759 }
1760 } else {
1761 var line int
1762 for i, s := range d.Specs {
1763 if i > 0 {
1764 p.linebreak(p.lineFor(s.Pos()), 1, ignore, p.linesFrom(line) > 0)
1765 }
1766 p.recordLine(&line)
1767 p.spec(s, n, false)
1768 }
1769 }
1770 p.print(unindent, formfeed)
1771 }
1772 p.setPos(d.Rparen)
1773 p.print(token.RPAREN)
1774
1775 } else if len(d.Specs) > 0 {
1776 // single declaration
1777 p.spec(d.Specs[0], 1, true)
1778 }
1779 }
1780
1781 // sizeCounter is an io.Writer which counts the number of bytes written,
1782 // as well as whether a newline character was seen.
1783 type sizeCounter struct {
1784 hasNewline bool
1785 size int
1786 }
1787
1788 func (c *sizeCounter) Write(p []byte) (int, error) {
1789 if !c.hasNewline {
1790 for _, b := range p {
1791 if b == '\n' || b == '\f' {
1792 c.hasNewline = true
1793 break
1794 }
1795 }
1796 }
1797 c.size += len(p)
1798 return len(p), nil
1799 }
1800
1801 // nodeSize determines the size of n in chars after formatting.
1802 // The result is <= maxSize if the node fits on one line with at
1803 // most maxSize chars and the formatted output doesn't contain
1804 // any control chars. Otherwise, the result is > maxSize.
1805 func (p *printer) nodeSize(n ast.Node, maxSize int) (size int) {
1806 // nodeSize invokes the printer, which may invoke nodeSize
1807 // recursively. For deep composite literal nests, this can
1808 // lead to an exponential algorithm. Remember previous
1809 // results to prune the recursion (was issue 1628).
1810 if size, found := p.nodeSizes[n]; found {
1811 return size
1812 }
1813
1814 size = maxSize + 1 // assume n doesn't fit
1815 p.nodeSizes[n] = size
1816
1817 // nodeSize computation must be independent of particular
1818 // style so that we always get the same decision; print
1819 // in RawFormat
1820 cfg := Config{Mode: RawFormat}
1821 var counter sizeCounter
1822 if err := cfg.fprint(&counter, p.fset, n, p.nodeSizes); err != nil {
1823 return
1824 }
1825 if counter.size <= maxSize && !counter.hasNewline {
1826 // n fits in a single line
1827 size = counter.size
1828 p.nodeSizes[n] = size
1829 }
1830 return
1831 }
1832
1833 // numLines returns the number of lines spanned by node n in the original source.
1834 func (p *printer) numLines(n ast.Node) int {
1835 if from := n.Pos(); from.IsValid() {
1836 if to := n.End(); to.IsValid() {
1837 return p.lineFor(to) - p.lineFor(from) + 1
1838 }
1839 }
1840 return infinity
1841 }
1842
1843 // bodySize is like nodeSize but it is specialized for *ast.BlockStmt's.
1844 func (p *printer) bodySize(b *ast.BlockStmt, maxSize int) int {
1845 pos1 := b.Pos()
1846 pos2 := b.Rbrace
1847 if pos1.IsValid() && pos2.IsValid() && p.lineFor(pos1) != p.lineFor(pos2) {
1848 // opening and closing brace are on different lines - don't make it a one-liner
1849 return maxSize + 1
1850 }
1851 if len(b.List) > 5 {
1852 // too many statements - don't make it a one-liner
1853 return maxSize + 1
1854 }
1855 // otherwise, estimate body size
1856 bodySize := p.commentSizeBefore(p.posFor(pos2))
1857 for i, s := range b.List {
1858 if bodySize > maxSize {
1859 break // no need to continue
1860 }
1861 if i > 0 {
1862 bodySize += 2 // space for a semicolon and blank
1863 }
1864 bodySize += p.nodeSize(s, maxSize)
1865 }
1866 return bodySize
1867 }
1868
1869 // funcBody prints a function body following a function header of given headerSize.
1870 // If the header's and block's size are "small enough" and the block is "simple enough",
1871 // the block is printed on the current line, without line breaks, spaced from the header
1872 // by sep. Otherwise the block's opening "{" is printed on the current line, followed by
1873 // lines for the block's statements and its closing "}".
1874 func (p *printer) funcBody(headerSize int, sep whiteSpace, b *ast.BlockStmt) {
1875 if b == nil {
1876 return
1877 }
1878
1879 // save/restore composite literal nesting level
1880 defer func(level int) {
1881 p.level = level
1882 }(p.level)
1883 p.level = 0
1884
1885 const maxSize = 100
1886 if headerSize+p.bodySize(b, maxSize) <= maxSize {
1887 p.print(sep)
1888 p.setPos(b.Lbrace)
1889 p.print(token.LBRACE)
1890 if len(b.List) > 0 {
1891 p.print(blank)
1892 for i, s := range b.List {
1893 if i > 0 {
1894 p.print(token.SEMICOLON, blank)
1895 }
1896 p.stmt(s, i == len(b.List)-1)
1897 }
1898 p.print(blank)
1899 }
1900 p.print(noExtraLinebreak)
1901 p.setPos(b.Rbrace)
1902 p.print(token.RBRACE, noExtraLinebreak)
1903 return
1904 }
1905
1906 if sep != ignore {
1907 p.print(blank) // always use blank
1908 }
1909 p.block(b, 1)
1910 }
1911
1912 // distanceFrom returns the column difference between p.out (the current output
1913 // position) and startOutCol. If the start position is on a different line from
1914 // the current position (or either is unknown), the result is infinity.
1915 func (p *printer) distanceFrom(startPos token.Pos, startOutCol int) int {
1916 if startPos.IsValid() && p.pos.IsValid() && p.posFor(startPos).Line == p.pos.Line {
1917 return p.out.Column - startOutCol
1918 }
1919 return infinity
1920 }
1921
1922 func (p *printer) funcDecl(d *ast.FuncDecl) {
1923 p.setComment(d.Doc)
1924 p.setPos(d.Pos())
1925 p.print(token.FUNC, blank)
1926 // We have to save startCol only after emitting FUNC; otherwise it can be on a
1927 // different line (all whitespace preceding the FUNC is emitted only when the
1928 // FUNC is emitted).
1929 startCol := p.out.Column - len("func ")
1930 if d.Recv != nil {
1931 p.parameters(d.Recv, funcParam) // method: print receiver
1932 p.print(blank)
1933 }
1934 p.expr(d.Name)
1935 p.signature(d.Type)
1936 p.funcBody(p.distanceFrom(d.Pos(), startCol), vtab, d.Body)
1937 }
1938
1939 func (p *printer) decl(decl ast.Decl) {
1940 switch d := decl.(type) {
1941 case *ast.BadDecl:
1942 p.setPos(d.Pos())
1943 p.print("BadDecl")
1944 case *ast.GenDecl:
1945 p.genDecl(d)
1946 case *ast.FuncDecl:
1947 p.funcDecl(d)
1948 default:
1949 panic("unreachable")
1950 }
1951 }
1952
1953 // ----------------------------------------------------------------------------
1954 // Files
1955
1956 func declToken(decl ast.Decl) (tok token.Token) {
1957 tok = token.ILLEGAL
1958 switch d := decl.(type) {
1959 case *ast.GenDecl:
1960 tok = d.Tok
1961 case *ast.FuncDecl:
1962 tok = token.FUNC
1963 }
1964 return
1965 }
1966
1967 func (p *printer) declList(list []ast.Decl) {
1968 tok := token.ILLEGAL
1969 for _, d := range list {
1970 prev := tok
1971 tok = declToken(d)
1972 // If the declaration token changed (e.g., from CONST to TYPE)
1973 // or the next declaration has documentation associated with it,
1974 // print an empty line between top-level declarations.
1975 // (because p.linebreak is called with the position of d, which
1976 // is past any documentation, the minimum requirement is satisfied
1977 // even w/o the extra getDoc(d) nil-check - leave it in case the
1978 // linebreak logic improves - there's already a TODO).
1979 if len(p.output) > 0 {
1980 // only print line break if we are not at the beginning of the output
1981 // (i.e., we are not printing only a partial program)
1982 min := 1
1983 if prev != tok || getDoc(d) != nil {
1984 min = 2
1985 }
1986 // start a new section if the next declaration is a function
1987 // that spans multiple lines (see also issue #19544)
1988 p.linebreak(p.lineFor(d.Pos()), min, ignore, tok == token.FUNC && p.numLines(d) > 1)
1989 }
1990 p.decl(d)
1991 }
1992 }
1993
1994 func (p *printer) file(src *ast.File) {
1995 p.setComment(src.Doc)
1996 p.setPos(src.Pos())
1997 p.print(token.PACKAGE, blank)
1998 p.expr(src.Name)
1999 p.declList(src.Decls)
2000 p.print(newline)
2001 }