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
9package printer
10
11import (
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.
46func (p *printer) linebreak(line, min int, ws whiteSpace, newSection bool) (nbreaks int) {
47	n := max(nlimit(line-p.pos.Line), min)
48	if n > 0 {
49		p.print(ws)
50		if newSection {
51			p.print(formfeed)
52			n--
53			nbreaks = 2
54		}
55		nbreaks += n
56		for ; n > 0; n-- {
57			p.print(newline)
58		}
59	}
60	return
61}
62
63// setComment sets g as the next comment if g != nil and if node comments
64// are enabled - this mode is used when printing source code fragments such
65// as exports only. It assumes that there is no pending comment in p.comments
66// and at most one pending comment in the p.comment cache.
67func (p *printer) setComment(g *ast.CommentGroup) {
68	if g == nil || !p.useNodeComments {
69		return
70	}
71	if p.comments == nil {
72		// initialize p.comments lazily
73		p.comments = make([]*ast.CommentGroup, 1)
74	} else if p.cindex < len(p.comments) {
75		// for some reason there are pending comments; this
76		// should never happen - handle gracefully and flush
77		// all comments up to g, ignore anything after that
78		p.flush(p.posFor(g.List[0].Pos()), token.ILLEGAL)
79		p.comments = p.comments[0:1]
80		// in debug mode, report error
81		p.internalError("setComment found pending comments")
82	}
83	p.comments[0] = g
84	p.cindex = 0
85	// don't overwrite any pending comment in the p.comment cache
86	// (there may be a pending comment when a line comment is
87	// immediately followed by a lead comment with no other
88	// tokens between)
89	if p.commentOffset == infinity {
90		p.nextComment() // get comment ready for use
91	}
92}
93
94type exprListMode uint
95
96const (
97	commaTerm exprListMode = 1 << iota // list is optionally terminated by a comma
98	noIndent                           // no extra indentation in multi-line lists
99)
100
101// If indent is set, a multi-line identifier list is indented after the
102// first linebreak encountered.
103func (p *printer) identList(list []*ast.Ident, indent bool) {
104	// convert into an expression list so we can re-use exprList formatting
105	xlist := make([]ast.Expr, len(list))
106	for i, x := range list {
107		xlist[i] = x
108	}
109	var mode exprListMode
110	if !indent {
111		mode = noIndent
112	}
113	p.exprList(token.NoPos, xlist, 1, mode, token.NoPos, false)
114}
115
116const filteredMsg = "contains filtered or unexported fields"
117
118// Print a list of expressions. If the list spans multiple
119// source lines, the original line breaks are respected between
120// expressions.
121//
122// TODO(gri) Consider rewriting this to be independent of []ast.Expr
123// so that we can use the algorithm for any kind of list
124//
125//	(e.g., pass list via a channel over which to range).
126func (p *printer) exprList(prev0 token.Pos, list []ast.Expr, depth int, mode exprListMode, next0 token.Pos, isIncomplete bool) {
127	if len(list) == 0 {
128		if isIncomplete {
129			prev := p.posFor(prev0)
130			next := p.posFor(next0)
131			if prev.IsValid() && prev.Line == next.Line {
132				p.print("/* " + filteredMsg + " */")
133			} else {
134				p.print(newline)
135				p.print(indent, "// "+filteredMsg, unindent, newline)
136			}
137		}
138		return
139	}
140
141	prev := p.posFor(prev0)
142	next := p.posFor(next0)
143	line := p.lineFor(list[0].Pos())
144	endLine := p.lineFor(list[len(list)-1].End())
145
146	if prev.IsValid() && prev.Line == line && line == endLine {
147		// all list entries on a single line
148		for i, x := range list {
149			if i > 0 {
150				// use position of expression following the comma as
151				// comma position for correct comment placement
152				p.setPos(x.Pos())
153				p.print(token.COMMA, blank)
154			}
155			p.expr0(x, depth)
156		}
157		if isIncomplete {
158			p.print(token.COMMA, blank, "/* "+filteredMsg+" */")
159		}
160		return
161	}
162
163	// list entries span multiple lines;
164	// use source code positions to guide line breaks
165
166	// Don't add extra indentation if noIndent is set;
167	// i.e., pretend that the first line is already indented.
168	ws := ignore
169	if mode&noIndent == 0 {
170		ws = indent
171	}
172
173	// The first linebreak is always a formfeed since this section must not
174	// depend on any previous formatting.
175	prevBreak := -1 // index of last expression that was followed by a linebreak
176	if prev.IsValid() && prev.Line < line && p.linebreak(line, 0, ws, true) > 0 {
177		ws = ignore
178		prevBreak = 0
179	}
180
181	// initialize expression/key size: a zero value indicates expr/key doesn't fit on a single line
182	size := 0
183
184	// We use the ratio between the geometric mean of the previous key sizes and
185	// the current size to determine if there should be a break in the alignment.
186	// To compute the geometric mean we accumulate the ln(size) values (lnsum)
187	// and the number of sizes included (count).
188	lnsum := 0.0
189	count := 0
190
191	// print all list elements
192	prevLine := prev.Line
193	for i, x := range list {
194		line = p.lineFor(x.Pos())
195
196		// Determine if the next linebreak, if any, needs to use formfeed:
197		// in general, use the entire node size to make the decision; for
198		// key:value expressions, use the key size.
199		// TODO(gri) for a better result, should probably incorporate both
200		//           the key and the node size into the decision process
201		useFF := true
202
203		// Determine element size: All bets are off if we don't have
204		// position information for the previous and next token (likely
205		// generated code - simply ignore the size in this case by setting
206		// it to 0).
207		prevSize := size
208		const infinity = 1e6 // larger than any source line
209		size = p.nodeSize(x, infinity)
210		pair, isPair := x.(*ast.KeyValueExpr)
211		if size <= infinity && prev.IsValid() && next.IsValid() {
212			// x fits on a single line
213			if isPair {
214				size = p.nodeSize(pair.Key, infinity) // size <= infinity
215			}
216		} else {
217			// size too large or we don't have good layout information
218			size = 0
219		}
220
221		// If the previous line and the current line had single-
222		// line-expressions and the key sizes are small or the
223		// ratio between the current key and the geometric mean
224		// if the previous key sizes does not exceed a threshold,
225		// align columns and do not use formfeed.
226		if prevSize > 0 && size > 0 {
227			const smallSize = 40
228			if count == 0 || prevSize <= smallSize && size <= smallSize {
229				useFF = false
230			} else {
231				const r = 2.5                               // threshold
232				geomean := math.Exp(lnsum / float64(count)) // count > 0
233				ratio := float64(size) / geomean
234				useFF = r*ratio <= 1 || r <= ratio
235			}
236		}
237
238		needsLinebreak := 0 < prevLine && prevLine < line
239		if i > 0 {
240			// Use position of expression following the comma as
241			// comma position for correct comment placement, but
242			// only if the expression is on the same line.
243			if !needsLinebreak {
244				p.setPos(x.Pos())
245			}
246			p.print(token.COMMA)
247			needsBlank := true
248			if needsLinebreak {
249				// Lines are broken using newlines so comments remain aligned
250				// unless useFF is set or there are multiple expressions on
251				// the same line in which case formfeed is used.
252				nbreaks := p.linebreak(line, 0, ws, useFF || prevBreak+1 < i)
253				if nbreaks > 0 {
254					ws = ignore
255					prevBreak = i
256					needsBlank = false // we got a line break instead
257				}
258				// If there was a new section or more than one new line
259				// (which means that the tabwriter will implicitly break
260				// the section), reset the geomean variables since we are
261				// starting a new group of elements with the next element.
262				if nbreaks > 1 {
263					lnsum = 0
264					count = 0
265				}
266			}
267			if needsBlank {
268				p.print(blank)
269			}
270		}
271
272		if len(list) > 1 && isPair && size > 0 && needsLinebreak {
273			// We have a key:value expression that fits onto one line
274			// and it's not on the same line as the prior expression:
275			// Use a column for the key such that consecutive entries
276			// can align if possible.
277			// (needsLinebreak is set if we started a new line before)
278			p.expr(pair.Key)
279			p.setPos(pair.Colon)
280			p.print(token.COLON, vtab)
281			p.expr(pair.Value)
282		} else {
283			p.expr0(x, depth)
284		}
285
286		if size > 0 {
287			lnsum += math.Log(float64(size))
288			count++
289		}
290
291		prevLine = line
292	}
293
294	if mode&commaTerm != 0 && next.IsValid() && p.pos.Line < next.Line {
295		// Print a terminating comma if the next token is on a new line.
296		p.print(token.COMMA)
297		if isIncomplete {
298			p.print(newline)
299			p.print("// " + filteredMsg)
300		}
301		if ws == ignore && mode&noIndent == 0 {
302			// unindent if we indented
303			p.print(unindent)
304		}
305		p.print(formfeed) // terminating comma needs a line break to look good
306		return
307	}
308
309	if isIncomplete {
310		p.print(token.COMMA, newline)
311		p.print("// "+filteredMsg, newline)
312	}
313
314	if ws == ignore && mode&noIndent == 0 {
315		// unindent if we indented
316		p.print(unindent)
317	}
318}
319
320type paramMode int
321
322const (
323	funcParam paramMode = iota
324	funcTParam
325	typeTParam
326)
327
328func (p *printer) parameters(fields *ast.FieldList, mode paramMode) {
329	openTok, closeTok := token.LPAREN, token.RPAREN
330	if mode != funcParam {
331		openTok, closeTok = token.LBRACK, token.RBRACK
332	}
333	p.setPos(fields.Opening)
334	p.print(openTok)
335	if len(fields.List) > 0 {
336		prevLine := p.lineFor(fields.Opening)
337		ws := indent
338		for i, par := range fields.List {
339			// determine par begin and end line (may be different
340			// if there are multiple parameter names for this par
341			// or the type is on a separate line)
342			parLineBeg := p.lineFor(par.Pos())
343			parLineEnd := p.lineFor(par.End())
344			// separating "," if needed
345			needsLinebreak := 0 < prevLine && prevLine < parLineBeg
346			if i > 0 {
347				// use position of parameter following the comma as
348				// comma position for correct comma placement, but
349				// only if the next parameter is on the same line
350				if !needsLinebreak {
351					p.setPos(par.Pos())
352				}
353				p.print(token.COMMA)
354			}
355			// separator if needed (linebreak or blank)
356			if needsLinebreak && p.linebreak(parLineBeg, 0, ws, true) > 0 {
357				// break line if the opening "(" or previous parameter ended on a different line
358				ws = ignore
359			} else if i > 0 {
360				p.print(blank)
361			}
362			// parameter names
363			if len(par.Names) > 0 {
364				// Very subtle: If we indented before (ws == ignore), identList
365				// won't indent again. If we didn't (ws == indent), identList will
366				// indent if the identList spans multiple lines, and it will outdent
367				// again at the end (and still ws == indent). Thus, a subsequent indent
368				// by a linebreak call after a type, or in the next multi-line identList
369				// will do the right thing.
370				p.identList(par.Names, ws == indent)
371				p.print(blank)
372			}
373			// parameter type
374			p.expr(stripParensAlways(par.Type))
375			prevLine = parLineEnd
376		}
377
378		// if the closing ")" is on a separate line from the last parameter,
379		// print an additional "," and line break
380		if closing := p.lineFor(fields.Closing); 0 < prevLine && prevLine < closing {
381			p.print(token.COMMA)
382			p.linebreak(closing, 0, ignore, true)
383		} else if mode == typeTParam && fields.NumFields() == 1 && combinesWithName(fields.List[0].Type) {
384			// A type parameter list [P T] where the name P and the type expression T syntactically
385			// combine to another valid (value) expression requires a trailing comma, as in [P *T,]
386			// (or an enclosing interface as in [P interface(*T)]), so that the type parameter list
387			// is not parsed as an array length [P*T].
388			p.print(token.COMMA)
389		}
390
391		// unindent if we indented
392		if ws == ignore {
393			p.print(unindent)
394		}
395	}
396
397	p.setPos(fields.Closing)
398	p.print(closeTok)
399}
400
401// combinesWithName reports whether a name followed by the expression x
402// syntactically combines to another valid (value) expression. For instance
403// using *T for x, "name *T" syntactically appears as the expression x*T.
404// On the other hand, using  P|Q or *P|~Q for x, "name P|Q" or name *P|~Q"
405// cannot be combined into a valid (value) expression.
406func combinesWithName(x ast.Expr) bool {
407	switch x := x.(type) {
408	case *ast.StarExpr:
409		// name *x.X combines to name*x.X if x.X is not a type element
410		return !isTypeElem(x.X)
411	case *ast.BinaryExpr:
412		return combinesWithName(x.X) && !isTypeElem(x.Y)
413	case *ast.ParenExpr:
414		// name(x) combines but we are making sure at
415		// the call site that x is never parenthesized.
416		panic("unexpected parenthesized expression")
417	}
418	return false
419}
420
421// isTypeElem reports whether x is a (possibly parenthesized) type element expression.
422// The result is false if x could be a type element OR an ordinary (value) expression.
423func isTypeElem(x ast.Expr) bool {
424	switch x := x.(type) {
425	case *ast.ArrayType, *ast.StructType, *ast.FuncType, *ast.InterfaceType, *ast.MapType, *ast.ChanType:
426		return true
427	case *ast.UnaryExpr:
428		return x.Op == token.TILDE
429	case *ast.BinaryExpr:
430		return isTypeElem(x.X) || isTypeElem(x.Y)
431	case *ast.ParenExpr:
432		return isTypeElem(x.X)
433	}
434	return false
435}
436
437func (p *printer) signature(sig *ast.FuncType) {
438	if sig.TypeParams != nil {
439		p.parameters(sig.TypeParams, funcTParam)
440	}
441	if sig.Params != nil {
442		p.parameters(sig.Params, funcParam)
443	} else {
444		p.print(token.LPAREN, token.RPAREN)
445	}
446	res := sig.Results
447	n := res.NumFields()
448	if n > 0 {
449		// res != nil
450		p.print(blank)
451		if n == 1 && res.List[0].Names == nil {
452			// single anonymous res; no ()'s
453			p.expr(stripParensAlways(res.List[0].Type))
454			return
455		}
456		p.parameters(res, funcParam)
457	}
458}
459
460func identListSize(list []*ast.Ident, maxSize int) (size int) {
461	for i, x := range list {
462		if i > 0 {
463			size += len(", ")
464		}
465		size += utf8.RuneCountInString(x.Name)
466		if size >= maxSize {
467			break
468		}
469	}
470	return
471}
472
473func (p *printer) isOneLineFieldList(list []*ast.Field) bool {
474	if len(list) != 1 {
475		return false // allow only one field
476	}
477	f := list[0]
478	if f.Tag != nil || f.Comment != nil {
479		return false // don't allow tags or comments
480	}
481	// only name(s) and type
482	const maxSize = 30 // adjust as appropriate, this is an approximate value
483	namesSize := identListSize(f.Names, maxSize)
484	if namesSize > 0 {
485		namesSize = 1 // blank between names and types
486	}
487	typeSize := p.nodeSize(f.Type, maxSize)
488	return namesSize+typeSize <= maxSize
489}
490
491func (p *printer) setLineComment(text string) {
492	p.setComment(&ast.CommentGroup{List: []*ast.Comment{{Slash: token.NoPos, Text: text}}})
493}
494
495func (p *printer) fieldList(fields *ast.FieldList, isStruct, isIncomplete bool) {
496	lbrace := fields.Opening
497	list := fields.List
498	rbrace := fields.Closing
499	hasComments := isIncomplete || p.commentBefore(p.posFor(rbrace))
500	srcIsOneLine := lbrace.IsValid() && rbrace.IsValid() && p.lineFor(lbrace) == p.lineFor(rbrace)
501
502	if !hasComments && srcIsOneLine {
503		// possibly a one-line struct/interface
504		if len(list) == 0 {
505			// no blank between keyword and {} in this case
506			p.setPos(lbrace)
507			p.print(token.LBRACE)
508			p.setPos(rbrace)
509			p.print(token.RBRACE)
510			return
511		} else if p.isOneLineFieldList(list) {
512			// small enough - print on one line
513			// (don't use identList and ignore source line breaks)
514			p.setPos(lbrace)
515			p.print(token.LBRACE, blank)
516			f := list[0]
517			if isStruct {
518				for i, x := range f.Names {
519					if i > 0 {
520						// no comments so no need for comma position
521						p.print(token.COMMA, blank)
522					}
523					p.expr(x)
524				}
525				if len(f.Names) > 0 {
526					p.print(blank)
527				}
528				p.expr(f.Type)
529			} else { // interface
530				if len(f.Names) > 0 {
531					name := f.Names[0] // method name
532					p.expr(name)
533					p.signature(f.Type.(*ast.FuncType)) // don't print "func"
534				} else {
535					// embedded interface
536					p.expr(f.Type)
537				}
538			}
539			p.print(blank)
540			p.setPos(rbrace)
541			p.print(token.RBRACE)
542			return
543		}
544	}
545	// hasComments || !srcIsOneLine
546
547	p.print(blank)
548	p.setPos(lbrace)
549	p.print(token.LBRACE, indent)
550	if hasComments || len(list) > 0 {
551		p.print(formfeed)
552	}
553
554	if isStruct {
555
556		sep := vtab
557		if len(list) == 1 {
558			sep = blank
559		}
560		var line int
561		for i, f := range list {
562			if i > 0 {
563				p.linebreak(p.lineFor(f.Pos()), 1, ignore, p.linesFrom(line) > 0)
564			}
565			extraTabs := 0
566			p.setComment(f.Doc)
567			p.recordLine(&line)
568			if len(f.Names) > 0 {
569				// named fields
570				p.identList(f.Names, false)
571				p.print(sep)
572				p.expr(f.Type)
573				extraTabs = 1
574			} else {
575				// anonymous field
576				p.expr(f.Type)
577				extraTabs = 2
578			}
579			if f.Tag != nil {
580				if len(f.Names) > 0 && sep == vtab {
581					p.print(sep)
582				}
583				p.print(sep)
584				p.expr(f.Tag)
585				extraTabs = 0
586			}
587			if f.Comment != nil {
588				for ; extraTabs > 0; extraTabs-- {
589					p.print(sep)
590				}
591				p.setComment(f.Comment)
592			}
593		}
594		if isIncomplete {
595			if len(list) > 0 {
596				p.print(formfeed)
597			}
598			p.flush(p.posFor(rbrace), token.RBRACE) // make sure we don't lose the last line comment
599			p.setLineComment("// " + filteredMsg)
600		}
601
602	} else { // interface
603
604		var line int
605		var prev *ast.Ident // previous "type" identifier
606		for i, f := range list {
607			var name *ast.Ident // first name, or nil
608			if len(f.Names) > 0 {
609				name = f.Names[0]
610			}
611			if i > 0 {
612				// don't do a line break (min == 0) if we are printing a list of types
613				// TODO(gri) this doesn't work quite right if the list of types is
614				//           spread across multiple lines
615				min := 1
616				if prev != nil && name == prev {
617					min = 0
618				}
619				p.linebreak(p.lineFor(f.Pos()), min, ignore, p.linesFrom(line) > 0)
620			}
621			p.setComment(f.Doc)
622			p.recordLine(&line)
623			if name != nil {
624				// method
625				p.expr(name)
626				p.signature(f.Type.(*ast.FuncType)) // don't print "func"
627				prev = nil
628			} else {
629				// embedded interface
630				p.expr(f.Type)
631				prev = nil
632			}
633			p.setComment(f.Comment)
634		}
635		if isIncomplete {
636			if len(list) > 0 {
637				p.print(formfeed)
638			}
639			p.flush(p.posFor(rbrace), token.RBRACE) // make sure we don't lose the last line comment
640			p.setLineComment("// contains filtered or unexported methods")
641		}
642
643	}
644	p.print(unindent, formfeed)
645	p.setPos(rbrace)
646	p.print(token.RBRACE)
647}
648
649// ----------------------------------------------------------------------------
650// Expressions
651
652func walkBinary(e *ast.BinaryExpr) (has4, has5 bool, maxProblem int) {
653	switch e.Op.Precedence() {
654	case 4:
655		has4 = true
656	case 5:
657		has5 = true
658	}
659
660	switch l := e.X.(type) {
661	case *ast.BinaryExpr:
662		if l.Op.Precedence() < e.Op.Precedence() {
663			// parens will be inserted.
664			// pretend this is an *ast.ParenExpr and do nothing.
665			break
666		}
667		h4, h5, mp := walkBinary(l)
668		has4 = has4 || h4
669		has5 = has5 || h5
670		maxProblem = max(maxProblem, mp)
671	}
672
673	switch r := e.Y.(type) {
674	case *ast.BinaryExpr:
675		if r.Op.Precedence() <= e.Op.Precedence() {
676			// parens will be inserted.
677			// pretend this is an *ast.ParenExpr and do nothing.
678			break
679		}
680		h4, h5, mp := walkBinary(r)
681		has4 = has4 || h4
682		has5 = has5 || h5
683		maxProblem = max(maxProblem, mp)
684
685	case *ast.StarExpr:
686		if e.Op == token.QUO { // `*/`
687			maxProblem = 5
688		}
689
690	case *ast.UnaryExpr:
691		switch e.Op.String() + r.Op.String() {
692		case "/*", "&&", "&^":
693			maxProblem = 5
694		case "++", "--":
695			maxProblem = max(maxProblem, 4)
696		}
697	}
698	return
699}
700
701func cutoff(e *ast.BinaryExpr, depth int) int {
702	has4, has5, maxProblem := walkBinary(e)
703	if maxProblem > 0 {
704		return maxProblem + 1
705	}
706	if has4 && has5 {
707		if depth == 1 {
708			return 5
709		}
710		return 4
711	}
712	if depth == 1 {
713		return 6
714	}
715	return 4
716}
717
718func diffPrec(expr ast.Expr, prec int) int {
719	x, ok := expr.(*ast.BinaryExpr)
720	if !ok || prec != x.Op.Precedence() {
721		return 1
722	}
723	return 0
724}
725
726func reduceDepth(depth int) int {
727	depth--
728	if depth < 1 {
729		depth = 1
730	}
731	return depth
732}
733
734// Format the binary expression: decide the cutoff and then format.
735// Let's call depth == 1 Normal mode, and depth > 1 Compact mode.
736// (Algorithm suggestion by Russ Cox.)
737//
738// The precedences are:
739//
740//	5             *  /  %  <<  >>  &  &^
741//	4             +  -  |  ^
742//	3             ==  !=  <  <=  >  >=
743//	2             &&
744//	1             ||
745//
746// The only decision is whether there will be spaces around levels 4 and 5.
747// There are never spaces at level 6 (unary), and always spaces at levels 3 and below.
748//
749// To choose the cutoff, look at the whole expression but excluding primary
750// expressions (function calls, parenthesized exprs), and apply these rules:
751//
752//  1. If there is a binary operator with a right side unary operand
753//     that would clash without a space, the cutoff must be (in order):
754//
755//     /*	6
756//     &&	6
757//     &^	6
758//     ++	5
759//     --	5
760//
761//     (Comparison operators always have spaces around them.)
762//
763//  2. If there is a mix of level 5 and level 4 operators, then the cutoff
764//     is 5 (use spaces to distinguish precedence) in Normal mode
765//     and 4 (never use spaces) in Compact mode.
766//
767//  3. If there are no level 4 operators or no level 5 operators, then the
768//     cutoff is 6 (always use spaces) in Normal mode
769//     and 4 (never use spaces) in Compact mode.
770func (p *printer) binaryExpr(x *ast.BinaryExpr, prec1, cutoff, depth int) {
771	prec := x.Op.Precedence()
772	if prec < prec1 {
773		// parenthesis needed
774		// Note: The parser inserts an ast.ParenExpr node; thus this case
775		//       can only occur if the AST is created in a different way.
776		p.print(token.LPAREN)
777		p.expr0(x, reduceDepth(depth)) // parentheses undo one level of depth
778		p.print(token.RPAREN)
779		return
780	}
781
782	printBlank := prec < cutoff
783
784	ws := indent
785	p.expr1(x.X, prec, depth+diffPrec(x.X, prec))
786	if printBlank {
787		p.print(blank)
788	}
789	xline := p.pos.Line // before the operator (it may be on the next line!)
790	yline := p.lineFor(x.Y.Pos())
791	p.setPos(x.OpPos)
792	p.print(x.Op)
793	if xline != yline && xline > 0 && yline > 0 {
794		// at least one line break, but respect an extra empty line
795		// in the source
796		if p.linebreak(yline, 1, ws, true) > 0 {
797			ws = ignore
798			printBlank = false // no blank after line break
799		}
800	}
801	if printBlank {
802		p.print(blank)
803	}
804	p.expr1(x.Y, prec+1, depth+1)
805	if ws == ignore {
806		p.print(unindent)
807	}
808}
809
810func isBinary(expr ast.Expr) bool {
811	_, ok := expr.(*ast.BinaryExpr)
812	return ok
813}
814
815func (p *printer) expr1(expr ast.Expr, prec1, depth int) {
816	p.setPos(expr.Pos())
817
818	switch x := expr.(type) {
819	case *ast.BadExpr:
820		p.print("BadExpr")
821
822	case *ast.Ident:
823		p.print(x)
824
825	case *ast.BinaryExpr:
826		if depth < 1 {
827			p.internalError("depth < 1:", depth)
828			depth = 1
829		}
830		p.binaryExpr(x, prec1, cutoff(x, depth), depth)
831
832	case *ast.KeyValueExpr:
833		p.expr(x.Key)
834		p.setPos(x.Colon)
835		p.print(token.COLON, blank)
836		p.expr(x.Value)
837
838	case *ast.StarExpr:
839		const prec = token.UnaryPrec
840		if prec < prec1 {
841			// parenthesis needed
842			p.print(token.LPAREN)
843			p.print(token.MUL)
844			p.expr(x.X)
845			p.print(token.RPAREN)
846		} else {
847			// no parenthesis needed
848			p.print(token.MUL)
849			p.expr(x.X)
850		}
851
852	case *ast.UnaryExpr:
853		const prec = token.UnaryPrec
854		if prec < prec1 {
855			// parenthesis needed
856			p.print(token.LPAREN)
857			p.expr(x)
858			p.print(token.RPAREN)
859		} else {
860			// no parenthesis needed
861			p.print(x.Op)
862			if x.Op == token.RANGE {
863				// TODO(gri) Remove this code if it cannot be reached.
864				p.print(blank)
865			}
866			p.expr1(x.X, prec, depth)
867		}
868
869	case *ast.BasicLit:
870		if p.Config.Mode&normalizeNumbers != 0 {
871			x = normalizedNumber(x)
872		}
873		p.print(x)
874
875	case *ast.FuncLit:
876		p.setPos(x.Type.Pos())
877		p.print(token.FUNC)
878		// See the comment in funcDecl about how the header size is computed.
879		startCol := p.out.Column - len("func")
880		p.signature(x.Type)
881		p.funcBody(p.distanceFrom(x.Type.Pos(), startCol), blank, x.Body)
882
883	case *ast.ParenExpr:
884		if _, hasParens := x.X.(*ast.ParenExpr); hasParens {
885			// don't print parentheses around an already parenthesized expression
886			// TODO(gri) consider making this more general and incorporate precedence levels
887			p.expr0(x.X, depth)
888		} else {
889			p.print(token.LPAREN)
890			p.expr0(x.X, reduceDepth(depth)) // parentheses undo one level of depth
891			p.setPos(x.Rparen)
892			p.print(token.RPAREN)
893		}
894
895	case *ast.SelectorExpr:
896		p.selectorExpr(x, depth, false)
897
898	case *ast.TypeAssertExpr:
899		p.expr1(x.X, token.HighestPrec, depth)
900		p.print(token.PERIOD)
901		p.setPos(x.Lparen)
902		p.print(token.LPAREN)
903		if x.Type != nil {
904			p.expr(x.Type)
905		} else {
906			p.print(token.TYPE)
907		}
908		p.setPos(x.Rparen)
909		p.print(token.RPAREN)
910
911	case *ast.IndexExpr:
912		// TODO(gri): should treat[] like parentheses and undo one level of depth
913		p.expr1(x.X, token.HighestPrec, 1)
914		p.setPos(x.Lbrack)
915		p.print(token.LBRACK)
916		p.expr0(x.Index, depth+1)
917		p.setPos(x.Rbrack)
918		p.print(token.RBRACK)
919
920	case *ast.IndexListExpr:
921		// TODO(gri): as for IndexExpr, should treat [] like parentheses and undo
922		// one level of depth
923		p.expr1(x.X, token.HighestPrec, 1)
924		p.setPos(x.Lbrack)
925		p.print(token.LBRACK)
926		p.exprList(x.Lbrack, x.Indices, depth+1, commaTerm, x.Rbrack, false)
927		p.setPos(x.Rbrack)
928		p.print(token.RBRACK)
929
930	case *ast.SliceExpr:
931		// TODO(gri): should treat[] like parentheses and undo one level of depth
932		p.expr1(x.X, token.HighestPrec, 1)
933		p.setPos(x.Lbrack)
934		p.print(token.LBRACK)
935		indices := []ast.Expr{x.Low, x.High}
936		if x.Max != nil {
937			indices = append(indices, x.Max)
938		}
939		// determine if we need extra blanks around ':'
940		var needsBlanks bool
941		if depth <= 1 {
942			var indexCount int
943			var hasBinaries bool
944			for _, x := range indices {
945				if x != nil {
946					indexCount++
947					if isBinary(x) {
948						hasBinaries = true
949					}
950				}
951			}
952			if indexCount > 1 && hasBinaries {
953				needsBlanks = true
954			}
955		}
956		for i, x := range indices {
957			if i > 0 {
958				if indices[i-1] != nil && needsBlanks {
959					p.print(blank)
960				}
961				p.print(token.COLON)
962				if x != nil && needsBlanks {
963					p.print(blank)
964				}
965			}
966			if x != nil {
967				p.expr0(x, depth+1)
968			}
969		}
970		p.setPos(x.Rbrack)
971		p.print(token.RBRACK)
972
973	case *ast.CallExpr:
974		if len(x.Args) > 1 {
975			depth++
976		}
977
978		// Conversions to literal function types or <-chan
979		// types require parentheses around the type.
980		paren := false
981		switch t := x.Fun.(type) {
982		case *ast.FuncType:
983			paren = true
984		case *ast.ChanType:
985			paren = t.Dir == ast.RECV
986		}
987		if paren {
988			p.print(token.LPAREN)
989		}
990		wasIndented := p.possibleSelectorExpr(x.Fun, token.HighestPrec, depth)
991		if paren {
992			p.print(token.RPAREN)
993		}
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.
1097func 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
1149func (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.
1159func (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
1176func (p *printer) expr0(x ast.Expr, depth int) {
1177	p.expr1(x, token.LowestPrec, depth)
1178}
1179
1180func (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.
1191func (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.
1229func (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
1238func 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
1248func 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
1274func 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
1281func (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).
1318func (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		var b = p.lineFor(list[0].Pos())
1324		var 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
1349func (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		var 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
1577func 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
1617func (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
1641func 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.
1687func (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
1737func (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.
1783type sizeCounter struct {
1784	hasNewline bool
1785	size       int
1786}
1787
1788func (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.
1805func (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.
1834func (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.
1844func (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 "}".
1874func (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.
1915func (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
1922func (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
1939func (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
1956func 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
1967func (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
1994func (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}
2002