github.com/ader1990/go@v0.0.0-20140630135419-8c24447fa791/src/pkg/go/printer/nodes.go (about)

     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  	"bytes"
    13  	"go/ast"
    14  	"go/token"
    15  	"unicode/utf8"
    16  )
    17  
    18  // Formatting issues:
    19  // - better comment formatting for /*-style comments at the end of a line (e.g. a declaration)
    20  //   when the comment spans multiple lines; if such a comment is just two lines, formatting is
    21  //   not idempotent
    22  // - formatting of expression lists
    23  // - should use blank instead of tab to separate one-line function bodies from
    24  //   the function header unless there is a group of consecutive one-liners
    25  
    26  // ----------------------------------------------------------------------------
    27  // Common AST nodes.
    28  
    29  // Print as many newlines as necessary (but at least min newlines) to get to
    30  // the current line. ws is printed before the first line break. If newSection
    31  // is set, the first line break is printed as formfeed. Returns true if any
    32  // line break was printed; returns false otherwise.
    33  //
    34  // TODO(gri): linebreak may add too many lines if the next statement at "line"
    35  //            is preceded by comments because the computation of n assumes
    36  //            the current position before the comment and the target position
    37  //            after the comment. Thus, after interspersing such comments, the
    38  //            space taken up by them is not considered to reduce the number of
    39  //            linebreaks. At the moment there is no easy way to know about
    40  //            future (not yet interspersed) comments in this function.
    41  //
    42  func (p *printer) linebreak(line, min int, ws whiteSpace, newSection bool) (printedBreak bool) {
    43  	n := nlimit(line - p.pos.Line)
    44  	if n < min {
    45  		n = min
    46  	}
    47  	if n > 0 {
    48  		p.print(ws)
    49  		if newSection {
    50  			p.print(formfeed)
    51  			n--
    52  		}
    53  		for ; n > 0; n-- {
    54  			p.print(newline)
    55  		}
    56  		printedBreak = true
    57  	}
    58  	return
    59  }
    60  
    61  // setComment sets g as the next comment if g != nil and if node comments
    62  // are enabled - this mode is used when printing source code fragments such
    63  // as exports only. It assumes that there is no pending comment in p.comments
    64  // and at most one pending comment in the p.comment cache.
    65  func (p *printer) setComment(g *ast.CommentGroup) {
    66  	if g == nil || !p.useNodeComments {
    67  		return
    68  	}
    69  	if p.comments == nil {
    70  		// initialize p.comments lazily
    71  		p.comments = make([]*ast.CommentGroup, 1)
    72  	} else if p.cindex < len(p.comments) {
    73  		// for some reason there are pending comments; this
    74  		// should never happen - handle gracefully and flush
    75  		// all comments up to g, ignore anything after that
    76  		p.flush(p.posFor(g.List[0].Pos()), token.ILLEGAL)
    77  		p.comments = p.comments[0:1]
    78  		// in debug mode, report error
    79  		p.internalError("setComment found pending comments")
    80  	}
    81  	p.comments[0] = g
    82  	p.cindex = 0
    83  	// don't overwrite any pending comment in the p.comment cache
    84  	// (there may be a pending comment when a line comment is
    85  	// immediately followed by a lead comment with no other
    86  	// tokens between)
    87  	if p.commentOffset == infinity {
    88  		p.nextComment() // get comment ready for use
    89  	}
    90  }
    91  
    92  type exprListMode uint
    93  
    94  const (
    95  	commaTerm exprListMode = 1 << iota // list is optionally terminated by a comma
    96  	noIndent                           // no extra indentation in multi-line lists
    97  )
    98  
    99  // If indent is set, a multi-line identifier list is indented after the
   100  // first linebreak encountered.
   101  func (p *printer) identList(list []*ast.Ident, indent bool) {
   102  	// convert into an expression list so we can re-use exprList formatting
   103  	xlist := make([]ast.Expr, len(list))
   104  	for i, x := range list {
   105  		xlist[i] = x
   106  	}
   107  	var mode exprListMode
   108  	if !indent {
   109  		mode = noIndent
   110  	}
   111  	p.exprList(token.NoPos, xlist, 1, mode, token.NoPos)
   112  }
   113  
   114  // Print a list of expressions. If the list spans multiple
   115  // source lines, the original line breaks are respected between
   116  // expressions.
   117  //
   118  // TODO(gri) Consider rewriting this to be independent of []ast.Expr
   119  //           so that we can use the algorithm for any kind of list
   120  //           (e.g., pass list via a channel over which to range).
   121  func (p *printer) exprList(prev0 token.Pos, list []ast.Expr, depth int, mode exprListMode, next0 token.Pos) {
   122  	if len(list) == 0 {
   123  		return
   124  	}
   125  
   126  	prev := p.posFor(prev0)
   127  	next := p.posFor(next0)
   128  	line := p.lineFor(list[0].Pos())
   129  	endLine := p.lineFor(list[len(list)-1].End())
   130  
   131  	if prev.IsValid() && prev.Line == line && line == endLine {
   132  		// all list entries on a single line
   133  		for i, x := range list {
   134  			if i > 0 {
   135  				// use position of expression following the comma as
   136  				// comma position for correct comment placement
   137  				p.print(x.Pos(), token.COMMA, blank)
   138  			}
   139  			p.expr0(x, depth)
   140  		}
   141  		return
   142  	}
   143  
   144  	// list entries span multiple lines;
   145  	// use source code positions to guide line breaks
   146  
   147  	// don't add extra indentation if noIndent is set;
   148  	// i.e., pretend that the first line is already indented
   149  	ws := ignore
   150  	if mode&noIndent == 0 {
   151  		ws = indent
   152  	}
   153  
   154  	// the first linebreak is always a formfeed since this section must not
   155  	// depend on any previous formatting
   156  	prevBreak := -1 // index of last expression that was followed by a linebreak
   157  	if prev.IsValid() && prev.Line < line && p.linebreak(line, 0, ws, true) {
   158  		ws = ignore
   159  		prevBreak = 0
   160  	}
   161  
   162  	// initialize expression/key size: a zero value indicates expr/key doesn't fit on a single line
   163  	size := 0
   164  
   165  	// print all list elements
   166  	for i, x := range list {
   167  		prevLine := line
   168  		line = p.lineFor(x.Pos())
   169  
   170  		// determine if the next linebreak, if any, needs to use formfeed:
   171  		// in general, use the entire node size to make the decision; for
   172  		// key:value expressions, use the key size
   173  		// TODO(gri) for a better result, should probably incorporate both
   174  		//           the key and the node size into the decision process
   175  		useFF := true
   176  
   177  		// determine element size: all bets are off if we don't have
   178  		// position information for the previous and next token (likely
   179  		// generated code - simply ignore the size in this case by setting
   180  		// it to 0)
   181  		prevSize := size
   182  		const infinity = 1e6 // larger than any source line
   183  		size = p.nodeSize(x, infinity)
   184  		pair, isPair := x.(*ast.KeyValueExpr)
   185  		if size <= infinity && prev.IsValid() && next.IsValid() {
   186  			// x fits on a single line
   187  			if isPair {
   188  				size = p.nodeSize(pair.Key, infinity) // size <= infinity
   189  			}
   190  		} else {
   191  			// size too large or we don't have good layout information
   192  			size = 0
   193  		}
   194  
   195  		// if the previous line and the current line had single-
   196  		// line-expressions and the key sizes are small or the
   197  		// the ratio between the key sizes does not exceed a
   198  		// threshold, align columns and do not use formfeed
   199  		if prevSize > 0 && size > 0 {
   200  			const smallSize = 20
   201  			if prevSize <= smallSize && size <= smallSize {
   202  				useFF = false
   203  			} else {
   204  				const r = 4 // threshold
   205  				ratio := float64(size) / float64(prevSize)
   206  				useFF = ratio <= 1.0/r || r <= ratio
   207  			}
   208  		}
   209  
   210  		if i > 0 {
   211  			needsLinebreak := prevLine < line && prevLine > 0 && line > 0
   212  			// use position of expression following the comma as
   213  			// comma position for correct comment placement, but
   214  			// only if the expression is on the same line
   215  			if !needsLinebreak {
   216  				p.print(x.Pos())
   217  			}
   218  			p.print(token.COMMA)
   219  			needsBlank := true
   220  			if needsLinebreak {
   221  				// lines are broken using newlines so comments remain aligned
   222  				// unless forceFF is set or there are multiple expressions on
   223  				// the same line in which case formfeed is used
   224  				if p.linebreak(line, 0, ws, useFF || prevBreak+1 < i) {
   225  					ws = ignore
   226  					prevBreak = i
   227  					needsBlank = false // we got a line break instead
   228  				}
   229  			}
   230  			if needsBlank {
   231  				p.print(blank)
   232  			}
   233  		}
   234  
   235  		if isPair && size > 0 && len(list) > 1 {
   236  			// we have a key:value expression that fits onto one line and
   237  			// is in a list with more then one entry: use a column for the
   238  			// key such that consecutive entries can align if possible
   239  			p.expr(pair.Key)
   240  			p.print(pair.Colon, token.COLON, vtab)
   241  			p.expr(pair.Value)
   242  		} else {
   243  			p.expr0(x, depth)
   244  		}
   245  	}
   246  
   247  	if mode&commaTerm != 0 && next.IsValid() && p.pos.Line < next.Line {
   248  		// print a terminating comma if the next token is on a new line
   249  		p.print(token.COMMA)
   250  		if ws == ignore && mode&noIndent == 0 {
   251  			// unindent if we indented
   252  			p.print(unindent)
   253  		}
   254  		p.print(formfeed) // terminating comma needs a line break to look good
   255  		return
   256  	}
   257  
   258  	if ws == ignore && mode&noIndent == 0 {
   259  		// unindent if we indented
   260  		p.print(unindent)
   261  	}
   262  }
   263  
   264  func (p *printer) parameters(fields *ast.FieldList) {
   265  	p.print(fields.Opening, token.LPAREN)
   266  	if len(fields.List) > 0 {
   267  		prevLine := p.lineFor(fields.Opening)
   268  		ws := indent
   269  		for i, par := range fields.List {
   270  			// determine par begin and end line (may be different
   271  			// if there are multiple parameter names for this par
   272  			// or the type is on a separate line)
   273  			var parLineBeg int
   274  			if len(par.Names) > 0 {
   275  				parLineBeg = p.lineFor(par.Names[0].Pos())
   276  			} else {
   277  				parLineBeg = p.lineFor(par.Type.Pos())
   278  			}
   279  			var parLineEnd = p.lineFor(par.Type.End())
   280  			// separating "," if needed
   281  			needsLinebreak := 0 < prevLine && prevLine < parLineBeg
   282  			if i > 0 {
   283  				// use position of parameter following the comma as
   284  				// comma position for correct comma placement, but
   285  				// only if the next parameter is on the same line
   286  				if !needsLinebreak {
   287  					p.print(par.Pos())
   288  				}
   289  				p.print(token.COMMA)
   290  			}
   291  			// separator if needed (linebreak or blank)
   292  			if needsLinebreak && p.linebreak(parLineBeg, 0, ws, true) {
   293  				// break line if the opening "(" or previous parameter ended on a different line
   294  				ws = ignore
   295  			} else if i > 0 {
   296  				p.print(blank)
   297  			}
   298  			// parameter names
   299  			if len(par.Names) > 0 {
   300  				// Very subtle: If we indented before (ws == ignore), identList
   301  				// won't indent again. If we didn't (ws == indent), identList will
   302  				// indent if the identList spans multiple lines, and it will outdent
   303  				// again at the end (and still ws == indent). Thus, a subsequent indent
   304  				// by a linebreak call after a type, or in the next multi-line identList
   305  				// will do the right thing.
   306  				p.identList(par.Names, ws == indent)
   307  				p.print(blank)
   308  			}
   309  			// parameter type
   310  			p.expr(stripParensAlways(par.Type))
   311  			prevLine = parLineEnd
   312  		}
   313  		// if the closing ")" is on a separate line from the last parameter,
   314  		// print an additional "," and line break
   315  		if closing := p.lineFor(fields.Closing); 0 < prevLine && prevLine < closing {
   316  			p.print(token.COMMA)
   317  			p.linebreak(closing, 0, ignore, true)
   318  		}
   319  		// unindent if we indented
   320  		if ws == ignore {
   321  			p.print(unindent)
   322  		}
   323  	}
   324  	p.print(fields.Closing, token.RPAREN)
   325  }
   326  
   327  func (p *printer) signature(params, result *ast.FieldList) {
   328  	if params != nil {
   329  		p.parameters(params)
   330  	} else {
   331  		p.print(token.LPAREN, token.RPAREN)
   332  	}
   333  	n := result.NumFields()
   334  	if n > 0 {
   335  		// result != nil
   336  		p.print(blank)
   337  		if n == 1 && result.List[0].Names == nil {
   338  			// single anonymous result; no ()'s
   339  			p.expr(stripParensAlways(result.List[0].Type))
   340  			return
   341  		}
   342  		p.parameters(result)
   343  	}
   344  }
   345  
   346  func identListSize(list []*ast.Ident, maxSize int) (size int) {
   347  	for i, x := range list {
   348  		if i > 0 {
   349  			size += len(", ")
   350  		}
   351  		size += utf8.RuneCountInString(x.Name)
   352  		if size >= maxSize {
   353  			break
   354  		}
   355  	}
   356  	return
   357  }
   358  
   359  func (p *printer) isOneLineFieldList(list []*ast.Field) bool {
   360  	if len(list) != 1 {
   361  		return false // allow only one field
   362  	}
   363  	f := list[0]
   364  	if f.Tag != nil || f.Comment != nil {
   365  		return false // don't allow tags or comments
   366  	}
   367  	// only name(s) and type
   368  	const maxSize = 30 // adjust as appropriate, this is an approximate value
   369  	namesSize := identListSize(f.Names, maxSize)
   370  	if namesSize > 0 {
   371  		namesSize = 1 // blank between names and types
   372  	}
   373  	typeSize := p.nodeSize(f.Type, maxSize)
   374  	return namesSize+typeSize <= maxSize
   375  }
   376  
   377  func (p *printer) setLineComment(text string) {
   378  	p.setComment(&ast.CommentGroup{List: []*ast.Comment{{Slash: token.NoPos, Text: text}}})
   379  }
   380  
   381  func (p *printer) fieldList(fields *ast.FieldList, isStruct, isIncomplete bool) {
   382  	lbrace := fields.Opening
   383  	list := fields.List
   384  	rbrace := fields.Closing
   385  	hasComments := isIncomplete || p.commentBefore(p.posFor(rbrace))
   386  	srcIsOneLine := lbrace.IsValid() && rbrace.IsValid() && p.lineFor(lbrace) == p.lineFor(rbrace)
   387  
   388  	if !hasComments && srcIsOneLine {
   389  		// possibly a one-line struct/interface
   390  		if len(list) == 0 {
   391  			// no blank between keyword and {} in this case
   392  			p.print(lbrace, token.LBRACE, rbrace, token.RBRACE)
   393  			return
   394  		} else if isStruct && p.isOneLineFieldList(list) { // for now ignore interfaces
   395  			// small enough - print on one line
   396  			// (don't use identList and ignore source line breaks)
   397  			p.print(lbrace, token.LBRACE, blank)
   398  			f := list[0]
   399  			for i, x := range f.Names {
   400  				if i > 0 {
   401  					// no comments so no need for comma position
   402  					p.print(token.COMMA, blank)
   403  				}
   404  				p.expr(x)
   405  			}
   406  			if len(f.Names) > 0 {
   407  				p.print(blank)
   408  			}
   409  			p.expr(f.Type)
   410  			p.print(blank, rbrace, token.RBRACE)
   411  			return
   412  		}
   413  	}
   414  	// hasComments || !srcIsOneLine
   415  
   416  	p.print(blank, lbrace, token.LBRACE, indent)
   417  	if hasComments || len(list) > 0 {
   418  		p.print(formfeed)
   419  	}
   420  
   421  	if isStruct {
   422  
   423  		sep := vtab
   424  		if len(list) == 1 {
   425  			sep = blank
   426  		}
   427  		var line int
   428  		for i, f := range list {
   429  			if i > 0 {
   430  				p.linebreak(p.lineFor(f.Pos()), 1, ignore, p.linesFrom(line) > 0)
   431  			}
   432  			extraTabs := 0
   433  			p.setComment(f.Doc)
   434  			p.recordLine(&line)
   435  			if len(f.Names) > 0 {
   436  				// named fields
   437  				p.identList(f.Names, false)
   438  				p.print(sep)
   439  				p.expr(f.Type)
   440  				extraTabs = 1
   441  			} else {
   442  				// anonymous field
   443  				p.expr(f.Type)
   444  				extraTabs = 2
   445  			}
   446  			if f.Tag != nil {
   447  				if len(f.Names) > 0 && sep == vtab {
   448  					p.print(sep)
   449  				}
   450  				p.print(sep)
   451  				p.expr(f.Tag)
   452  				extraTabs = 0
   453  			}
   454  			if f.Comment != nil {
   455  				for ; extraTabs > 0; extraTabs-- {
   456  					p.print(sep)
   457  				}
   458  				p.setComment(f.Comment)
   459  			}
   460  		}
   461  		if isIncomplete {
   462  			if len(list) > 0 {
   463  				p.print(formfeed)
   464  			}
   465  			p.flush(p.posFor(rbrace), token.RBRACE) // make sure we don't lose the last line comment
   466  			p.setLineComment("// contains filtered or unexported fields")
   467  		}
   468  
   469  	} else { // interface
   470  
   471  		var line int
   472  		for i, f := range list {
   473  			if i > 0 {
   474  				p.linebreak(p.lineFor(f.Pos()), 1, ignore, p.linesFrom(line) > 0)
   475  			}
   476  			p.setComment(f.Doc)
   477  			p.recordLine(&line)
   478  			if ftyp, isFtyp := f.Type.(*ast.FuncType); isFtyp {
   479  				// method
   480  				p.expr(f.Names[0])
   481  				p.signature(ftyp.Params, ftyp.Results)
   482  			} else {
   483  				// embedded interface
   484  				p.expr(f.Type)
   485  			}
   486  			p.setComment(f.Comment)
   487  		}
   488  		if isIncomplete {
   489  			if len(list) > 0 {
   490  				p.print(formfeed)
   491  			}
   492  			p.flush(p.posFor(rbrace), token.RBRACE) // make sure we don't lose the last line comment
   493  			p.setLineComment("// contains filtered or unexported methods")
   494  		}
   495  
   496  	}
   497  	p.print(unindent, formfeed, rbrace, token.RBRACE)
   498  }
   499  
   500  // ----------------------------------------------------------------------------
   501  // Expressions
   502  
   503  func walkBinary(e *ast.BinaryExpr) (has4, has5 bool, maxProblem int) {
   504  	switch e.Op.Precedence() {
   505  	case 4:
   506  		has4 = true
   507  	case 5:
   508  		has5 = true
   509  	}
   510  
   511  	switch l := e.X.(type) {
   512  	case *ast.BinaryExpr:
   513  		if l.Op.Precedence() < e.Op.Precedence() {
   514  			// parens will be inserted.
   515  			// pretend this is an *ast.ParenExpr and do nothing.
   516  			break
   517  		}
   518  		h4, h5, mp := walkBinary(l)
   519  		has4 = has4 || h4
   520  		has5 = has5 || h5
   521  		if maxProblem < mp {
   522  			maxProblem = mp
   523  		}
   524  	}
   525  
   526  	switch r := e.Y.(type) {
   527  	case *ast.BinaryExpr:
   528  		if r.Op.Precedence() <= e.Op.Precedence() {
   529  			// parens will be inserted.
   530  			// pretend this is an *ast.ParenExpr and do nothing.
   531  			break
   532  		}
   533  		h4, h5, mp := walkBinary(r)
   534  		has4 = has4 || h4
   535  		has5 = has5 || h5
   536  		if maxProblem < mp {
   537  			maxProblem = mp
   538  		}
   539  
   540  	case *ast.StarExpr:
   541  		if e.Op == token.QUO { // `*/`
   542  			maxProblem = 5
   543  		}
   544  
   545  	case *ast.UnaryExpr:
   546  		switch e.Op.String() + r.Op.String() {
   547  		case "/*", "&&", "&^":
   548  			maxProblem = 5
   549  		case "++", "--":
   550  			if maxProblem < 4 {
   551  				maxProblem = 4
   552  			}
   553  		}
   554  	}
   555  	return
   556  }
   557  
   558  func cutoff(e *ast.BinaryExpr, depth int) int {
   559  	has4, has5, maxProblem := walkBinary(e)
   560  	if maxProblem > 0 {
   561  		return maxProblem + 1
   562  	}
   563  	if has4 && has5 {
   564  		if depth == 1 {
   565  			return 5
   566  		}
   567  		return 4
   568  	}
   569  	if depth == 1 {
   570  		return 6
   571  	}
   572  	return 4
   573  }
   574  
   575  func diffPrec(expr ast.Expr, prec int) int {
   576  	x, ok := expr.(*ast.BinaryExpr)
   577  	if !ok || prec != x.Op.Precedence() {
   578  		return 1
   579  	}
   580  	return 0
   581  }
   582  
   583  func reduceDepth(depth int) int {
   584  	depth--
   585  	if depth < 1 {
   586  		depth = 1
   587  	}
   588  	return depth
   589  }
   590  
   591  // Format the binary expression: decide the cutoff and then format.
   592  // Let's call depth == 1 Normal mode, and depth > 1 Compact mode.
   593  // (Algorithm suggestion by Russ Cox.)
   594  //
   595  // The precedences are:
   596  //	5             *  /  %  <<  >>  &  &^
   597  //	4             +  -  |  ^
   598  //	3             ==  !=  <  <=  >  >=
   599  //	2             &&
   600  //	1             ||
   601  //
   602  // The only decision is whether there will be spaces around levels 4 and 5.
   603  // There are never spaces at level 6 (unary), and always spaces at levels 3 and below.
   604  //
   605  // To choose the cutoff, look at the whole expression but excluding primary
   606  // expressions (function calls, parenthesized exprs), and apply these rules:
   607  //
   608  //	1) If there is a binary operator with a right side unary operand
   609  //	   that would clash without a space, the cutoff must be (in order):
   610  //
   611  //		/*	6
   612  //		&&	6
   613  //		&^	6
   614  //		++	5
   615  //		--	5
   616  //
   617  //         (Comparison operators always have spaces around them.)
   618  //
   619  //	2) If there is a mix of level 5 and level 4 operators, then the cutoff
   620  //	   is 5 (use spaces to distinguish precedence) in Normal mode
   621  //	   and 4 (never use spaces) in Compact mode.
   622  //
   623  //	3) If there are no level 4 operators or no level 5 operators, then the
   624  //	   cutoff is 6 (always use spaces) in Normal mode
   625  //	   and 4 (never use spaces) in Compact mode.
   626  //
   627  func (p *printer) binaryExpr(x *ast.BinaryExpr, prec1, cutoff, depth int) {
   628  	prec := x.Op.Precedence()
   629  	if prec < prec1 {
   630  		// parenthesis needed
   631  		// Note: The parser inserts an ast.ParenExpr node; thus this case
   632  		//       can only occur if the AST is created in a different way.
   633  		p.print(token.LPAREN)
   634  		p.expr0(x, reduceDepth(depth)) // parentheses undo one level of depth
   635  		p.print(token.RPAREN)
   636  		return
   637  	}
   638  
   639  	printBlank := prec < cutoff
   640  
   641  	ws := indent
   642  	p.expr1(x.X, prec, depth+diffPrec(x.X, prec))
   643  	if printBlank {
   644  		p.print(blank)
   645  	}
   646  	xline := p.pos.Line // before the operator (it may be on the next line!)
   647  	yline := p.lineFor(x.Y.Pos())
   648  	p.print(x.OpPos, x.Op)
   649  	if xline != yline && xline > 0 && yline > 0 {
   650  		// at least one line break, but respect an extra empty line
   651  		// in the source
   652  		if p.linebreak(yline, 1, ws, true) {
   653  			ws = ignore
   654  			printBlank = false // no blank after line break
   655  		}
   656  	}
   657  	if printBlank {
   658  		p.print(blank)
   659  	}
   660  	p.expr1(x.Y, prec+1, depth+1)
   661  	if ws == ignore {
   662  		p.print(unindent)
   663  	}
   664  }
   665  
   666  func isBinary(expr ast.Expr) bool {
   667  	_, ok := expr.(*ast.BinaryExpr)
   668  	return ok
   669  }
   670  
   671  func (p *printer) expr1(expr ast.Expr, prec1, depth int) {
   672  	p.print(expr.Pos())
   673  
   674  	switch x := expr.(type) {
   675  	case *ast.BadExpr:
   676  		p.print("BadExpr")
   677  
   678  	case *ast.Ident:
   679  		p.print(x)
   680  
   681  	case *ast.BinaryExpr:
   682  		if depth < 1 {
   683  			p.internalError("depth < 1:", depth)
   684  			depth = 1
   685  		}
   686  		p.binaryExpr(x, prec1, cutoff(x, depth), depth)
   687  
   688  	case *ast.KeyValueExpr:
   689  		p.expr(x.Key)
   690  		p.print(x.Colon, token.COLON, blank)
   691  		p.expr(x.Value)
   692  
   693  	case *ast.StarExpr:
   694  		const prec = token.UnaryPrec
   695  		if prec < prec1 {
   696  			// parenthesis needed
   697  			p.print(token.LPAREN)
   698  			p.print(token.MUL)
   699  			p.expr(x.X)
   700  			p.print(token.RPAREN)
   701  		} else {
   702  			// no parenthesis needed
   703  			p.print(token.MUL)
   704  			p.expr(x.X)
   705  		}
   706  
   707  	case *ast.UnaryExpr:
   708  		const prec = token.UnaryPrec
   709  		if prec < prec1 {
   710  			// parenthesis needed
   711  			p.print(token.LPAREN)
   712  			p.expr(x)
   713  			p.print(token.RPAREN)
   714  		} else {
   715  			// no parenthesis needed
   716  			p.print(x.Op)
   717  			if x.Op == token.RANGE {
   718  				// TODO(gri) Remove this code if it cannot be reached.
   719  				p.print(blank)
   720  			}
   721  			p.expr1(x.X, prec, depth)
   722  		}
   723  
   724  	case *ast.BasicLit:
   725  		p.print(x)
   726  
   727  	case *ast.FuncLit:
   728  		p.expr(x.Type)
   729  		p.adjBlock(p.distanceFrom(x.Type.Pos()), blank, x.Body)
   730  
   731  	case *ast.ParenExpr:
   732  		if _, hasParens := x.X.(*ast.ParenExpr); hasParens {
   733  			// don't print parentheses around an already parenthesized expression
   734  			// TODO(gri) consider making this more general and incorporate precedence levels
   735  			p.expr0(x.X, reduceDepth(depth)) // parentheses undo one level of depth
   736  		} else {
   737  			p.print(token.LPAREN)
   738  			p.expr0(x.X, reduceDepth(depth)) // parentheses undo one level of depth
   739  			p.print(x.Rparen, token.RPAREN)
   740  		}
   741  
   742  	case *ast.SelectorExpr:
   743  		p.expr1(x.X, token.HighestPrec, depth)
   744  		p.print(token.PERIOD)
   745  		if line := p.lineFor(x.Sel.Pos()); p.pos.IsValid() && p.pos.Line < line {
   746  			p.print(indent, newline, x.Sel.Pos(), x.Sel, unindent)
   747  		} else {
   748  			p.print(x.Sel.Pos(), x.Sel)
   749  		}
   750  
   751  	case *ast.TypeAssertExpr:
   752  		p.expr1(x.X, token.HighestPrec, depth)
   753  		p.print(token.PERIOD, x.Lparen, token.LPAREN)
   754  		if x.Type != nil {
   755  			p.expr(x.Type)
   756  		} else {
   757  			p.print(token.TYPE)
   758  		}
   759  		p.print(x.Rparen, token.RPAREN)
   760  
   761  	case *ast.IndexExpr:
   762  		// TODO(gri): should treat[] like parentheses and undo one level of depth
   763  		p.expr1(x.X, token.HighestPrec, 1)
   764  		p.print(x.Lbrack, token.LBRACK)
   765  		p.expr0(x.Index, depth+1)
   766  		p.print(x.Rbrack, token.RBRACK)
   767  
   768  	case *ast.SliceExpr:
   769  		// TODO(gri): should treat[] like parentheses and undo one level of depth
   770  		p.expr1(x.X, token.HighestPrec, 1)
   771  		p.print(x.Lbrack, token.LBRACK)
   772  		indices := []ast.Expr{x.Low, x.High}
   773  		if x.Max != nil {
   774  			indices = append(indices, x.Max)
   775  		}
   776  		for i, y := range indices {
   777  			if i > 0 {
   778  				// blanks around ":" if both sides exist and either side is a binary expression
   779  				// TODO(gri) once we have committed a variant of a[i:j:k] we may want to fine-
   780  				//           tune the formatting here
   781  				x := indices[i-1]
   782  				if depth <= 1 && x != nil && y != nil && (isBinary(x) || isBinary(y)) {
   783  					p.print(blank, token.COLON, blank)
   784  				} else {
   785  					p.print(token.COLON)
   786  				}
   787  			}
   788  			if y != nil {
   789  				p.expr0(y, depth+1)
   790  			}
   791  		}
   792  		p.print(x.Rbrack, token.RBRACK)
   793  
   794  	case *ast.CallExpr:
   795  		if len(x.Args) > 1 {
   796  			depth++
   797  		}
   798  		if _, ok := x.Fun.(*ast.FuncType); ok {
   799  			// conversions to literal function types require parentheses around the type
   800  			p.print(token.LPAREN)
   801  			p.expr1(x.Fun, token.HighestPrec, depth)
   802  			p.print(token.RPAREN)
   803  		} else {
   804  			p.expr1(x.Fun, token.HighestPrec, depth)
   805  		}
   806  		p.print(x.Lparen, token.LPAREN)
   807  		if x.Ellipsis.IsValid() {
   808  			p.exprList(x.Lparen, x.Args, depth, 0, x.Ellipsis)
   809  			p.print(x.Ellipsis, token.ELLIPSIS)
   810  			if x.Rparen.IsValid() && p.lineFor(x.Ellipsis) < p.lineFor(x.Rparen) {
   811  				p.print(token.COMMA, formfeed)
   812  			}
   813  		} else {
   814  			p.exprList(x.Lparen, x.Args, depth, commaTerm, x.Rparen)
   815  		}
   816  		p.print(x.Rparen, token.RPAREN)
   817  
   818  	case *ast.CompositeLit:
   819  		// composite literal elements that are composite literals themselves may have the type omitted
   820  		if x.Type != nil {
   821  			p.expr1(x.Type, token.HighestPrec, depth)
   822  		}
   823  		p.print(x.Lbrace, token.LBRACE)
   824  		p.exprList(x.Lbrace, x.Elts, 1, commaTerm, x.Rbrace)
   825  		// do not insert extra line break following a /*-style comment
   826  		// before the closing '}' as it might break the code if there
   827  		// is no trailing ','
   828  		mode := noExtraLinebreak
   829  		// do not insert extra blank following a /*-style comment
   830  		// before the closing '}' unless the literal is empty
   831  		if len(x.Elts) > 0 {
   832  			mode |= noExtraBlank
   833  		}
   834  		p.print(mode, x.Rbrace, token.RBRACE, mode)
   835  
   836  	case *ast.Ellipsis:
   837  		p.print(token.ELLIPSIS)
   838  		if x.Elt != nil {
   839  			p.expr(x.Elt)
   840  		}
   841  
   842  	case *ast.ArrayType:
   843  		p.print(token.LBRACK)
   844  		if x.Len != nil {
   845  			p.expr(x.Len)
   846  		}
   847  		p.print(token.RBRACK)
   848  		p.expr(x.Elt)
   849  
   850  	case *ast.StructType:
   851  		p.print(token.STRUCT)
   852  		p.fieldList(x.Fields, true, x.Incomplete)
   853  
   854  	case *ast.FuncType:
   855  		p.print(token.FUNC)
   856  		p.signature(x.Params, x.Results)
   857  
   858  	case *ast.InterfaceType:
   859  		p.print(token.INTERFACE)
   860  		p.fieldList(x.Methods, false, x.Incomplete)
   861  
   862  	case *ast.MapType:
   863  		p.print(token.MAP, token.LBRACK)
   864  		p.expr(x.Key)
   865  		p.print(token.RBRACK)
   866  		p.expr(x.Value)
   867  
   868  	case *ast.ChanType:
   869  		switch x.Dir {
   870  		case ast.SEND | ast.RECV:
   871  			p.print(token.CHAN)
   872  		case ast.RECV:
   873  			p.print(token.ARROW, token.CHAN) // x.Arrow and x.Pos() are the same
   874  		case ast.SEND:
   875  			p.print(token.CHAN, x.Arrow, token.ARROW)
   876  		}
   877  		p.print(blank)
   878  		p.expr(x.Value)
   879  
   880  	default:
   881  		panic("unreachable")
   882  	}
   883  
   884  	return
   885  }
   886  
   887  func (p *printer) expr0(x ast.Expr, depth int) {
   888  	p.expr1(x, token.LowestPrec, depth)
   889  }
   890  
   891  func (p *printer) expr(x ast.Expr) {
   892  	const depth = 1
   893  	p.expr1(x, token.LowestPrec, depth)
   894  }
   895  
   896  // ----------------------------------------------------------------------------
   897  // Statements
   898  
   899  // Print the statement list indented, but without a newline after the last statement.
   900  // Extra line breaks between statements in the source are respected but at most one
   901  // empty line is printed between statements.
   902  func (p *printer) stmtList(list []ast.Stmt, nindent int, nextIsRBrace bool) {
   903  	if nindent > 0 {
   904  		p.print(indent)
   905  	}
   906  	var line int
   907  	i := 0
   908  	for _, s := range list {
   909  		// ignore empty statements (was issue 3466)
   910  		if _, isEmpty := s.(*ast.EmptyStmt); !isEmpty {
   911  			// nindent == 0 only for lists of switch/select case clauses;
   912  			// in those cases each clause is a new section
   913  			if len(p.output) > 0 {
   914  				// only print line break if we are not at the beginning of the output
   915  				// (i.e., we are not printing only a partial program)
   916  				p.linebreak(p.lineFor(s.Pos()), 1, ignore, i == 0 || nindent == 0 || p.linesFrom(line) > 0)
   917  			}
   918  			p.recordLine(&line)
   919  			p.stmt(s, nextIsRBrace && i == len(list)-1)
   920  			// labeled statements put labels on a separate line, but here
   921  			// we only care about the start line of the actual statement
   922  			// without label - correct line for each label
   923  			for t := s; ; {
   924  				lt, _ := t.(*ast.LabeledStmt)
   925  				if lt == nil {
   926  					break
   927  				}
   928  				line++
   929  				t = lt.Stmt
   930  			}
   931  			i++
   932  		}
   933  	}
   934  	if nindent > 0 {
   935  		p.print(unindent)
   936  	}
   937  }
   938  
   939  // block prints an *ast.BlockStmt; it always spans at least two lines.
   940  func (p *printer) block(b *ast.BlockStmt, nindent int) {
   941  	p.print(b.Lbrace, token.LBRACE)
   942  	p.stmtList(b.List, nindent, true)
   943  	p.linebreak(p.lineFor(b.Rbrace), 1, ignore, true)
   944  	p.print(b.Rbrace, token.RBRACE)
   945  }
   946  
   947  func isTypeName(x ast.Expr) bool {
   948  	switch t := x.(type) {
   949  	case *ast.Ident:
   950  		return true
   951  	case *ast.SelectorExpr:
   952  		return isTypeName(t.X)
   953  	}
   954  	return false
   955  }
   956  
   957  func stripParens(x ast.Expr) ast.Expr {
   958  	if px, strip := x.(*ast.ParenExpr); strip {
   959  		// parentheses must not be stripped if there are any
   960  		// unparenthesized composite literals starting with
   961  		// a type name
   962  		ast.Inspect(px.X, func(node ast.Node) bool {
   963  			switch x := node.(type) {
   964  			case *ast.ParenExpr:
   965  				// parentheses protect enclosed composite literals
   966  				return false
   967  			case *ast.CompositeLit:
   968  				if isTypeName(x.Type) {
   969  					strip = false // do not strip parentheses
   970  				}
   971  				return false
   972  			}
   973  			// in all other cases, keep inspecting
   974  			return true
   975  		})
   976  		if strip {
   977  			return stripParens(px.X)
   978  		}
   979  	}
   980  	return x
   981  }
   982  
   983  func stripParensAlways(x ast.Expr) ast.Expr {
   984  	if x, ok := x.(*ast.ParenExpr); ok {
   985  		return stripParensAlways(x.X)
   986  	}
   987  	return x
   988  }
   989  
   990  func (p *printer) controlClause(isForStmt bool, init ast.Stmt, expr ast.Expr, post ast.Stmt) {
   991  	p.print(blank)
   992  	needsBlank := false
   993  	if init == nil && post == nil {
   994  		// no semicolons required
   995  		if expr != nil {
   996  			p.expr(stripParens(expr))
   997  			needsBlank = true
   998  		}
   999  	} else {
  1000  		// all semicolons required
  1001  		// (they are not separators, print them explicitly)
  1002  		if init != nil {
  1003  			p.stmt(init, false)
  1004  		}
  1005  		p.print(token.SEMICOLON, blank)
  1006  		if expr != nil {
  1007  			p.expr(stripParens(expr))
  1008  			needsBlank = true
  1009  		}
  1010  		if isForStmt {
  1011  			p.print(token.SEMICOLON, blank)
  1012  			needsBlank = false
  1013  			if post != nil {
  1014  				p.stmt(post, false)
  1015  				needsBlank = true
  1016  			}
  1017  		}
  1018  	}
  1019  	if needsBlank {
  1020  		p.print(blank)
  1021  	}
  1022  }
  1023  
  1024  // indentList reports whether an expression list would look better if it
  1025  // were indented wholesale (starting with the very first element, rather
  1026  // than starting at the first line break).
  1027  //
  1028  func (p *printer) indentList(list []ast.Expr) bool {
  1029  	// Heuristic: indentList returns true if there are more than one multi-
  1030  	// line element in the list, or if there is any element that is not
  1031  	// starting on the same line as the previous one ends.
  1032  	if len(list) >= 2 {
  1033  		var b = p.lineFor(list[0].Pos())
  1034  		var e = p.lineFor(list[len(list)-1].End())
  1035  		if 0 < b && b < e {
  1036  			// list spans multiple lines
  1037  			n := 0 // multi-line element count
  1038  			line := b
  1039  			for _, x := range list {
  1040  				xb := p.lineFor(x.Pos())
  1041  				xe := p.lineFor(x.End())
  1042  				if line < xb {
  1043  					// x is not starting on the same
  1044  					// line as the previous one ended
  1045  					return true
  1046  				}
  1047  				if xb < xe {
  1048  					// x is a multi-line element
  1049  					n++
  1050  				}
  1051  				line = xe
  1052  			}
  1053  			return n > 1
  1054  		}
  1055  	}
  1056  	return false
  1057  }
  1058  
  1059  func (p *printer) stmt(stmt ast.Stmt, nextIsRBrace bool) {
  1060  	p.print(stmt.Pos())
  1061  
  1062  	switch s := stmt.(type) {
  1063  	case *ast.BadStmt:
  1064  		p.print("BadStmt")
  1065  
  1066  	case *ast.DeclStmt:
  1067  		p.decl(s.Decl)
  1068  
  1069  	case *ast.EmptyStmt:
  1070  		// nothing to do
  1071  
  1072  	case *ast.LabeledStmt:
  1073  		// a "correcting" unindent immediately following a line break
  1074  		// is applied before the line break if there is no comment
  1075  		// between (see writeWhitespace)
  1076  		p.print(unindent)
  1077  		p.expr(s.Label)
  1078  		p.print(s.Colon, token.COLON, indent)
  1079  		if e, isEmpty := s.Stmt.(*ast.EmptyStmt); isEmpty {
  1080  			if !nextIsRBrace {
  1081  				p.print(newline, e.Pos(), token.SEMICOLON)
  1082  				break
  1083  			}
  1084  		} else {
  1085  			p.linebreak(p.lineFor(s.Stmt.Pos()), 1, ignore, true)
  1086  		}
  1087  		p.stmt(s.Stmt, nextIsRBrace)
  1088  
  1089  	case *ast.ExprStmt:
  1090  		const depth = 1
  1091  		p.expr0(s.X, depth)
  1092  
  1093  	case *ast.SendStmt:
  1094  		const depth = 1
  1095  		p.expr0(s.Chan, depth)
  1096  		p.print(blank, s.Arrow, token.ARROW, blank)
  1097  		p.expr0(s.Value, depth)
  1098  
  1099  	case *ast.IncDecStmt:
  1100  		const depth = 1
  1101  		p.expr0(s.X, depth+1)
  1102  		p.print(s.TokPos, s.Tok)
  1103  
  1104  	case *ast.AssignStmt:
  1105  		var depth = 1
  1106  		if len(s.Lhs) > 1 && len(s.Rhs) > 1 {
  1107  			depth++
  1108  		}
  1109  		p.exprList(s.Pos(), s.Lhs, depth, 0, s.TokPos)
  1110  		p.print(blank, s.TokPos, s.Tok, blank)
  1111  		p.exprList(s.TokPos, s.Rhs, depth, 0, token.NoPos)
  1112  
  1113  	case *ast.GoStmt:
  1114  		p.print(token.GO, blank)
  1115  		p.expr(s.Call)
  1116  
  1117  	case *ast.DeferStmt:
  1118  		p.print(token.DEFER, blank)
  1119  		p.expr(s.Call)
  1120  
  1121  	case *ast.ReturnStmt:
  1122  		p.print(token.RETURN)
  1123  		if s.Results != nil {
  1124  			p.print(blank)
  1125  			// Use indentList heuristic to make corner cases look
  1126  			// better (issue 1207). A more systematic approach would
  1127  			// always indent, but this would cause significant
  1128  			// reformatting of the code base and not necessarily
  1129  			// lead to more nicely formatted code in general.
  1130  			if p.indentList(s.Results) {
  1131  				p.print(indent)
  1132  				p.exprList(s.Pos(), s.Results, 1, noIndent, token.NoPos)
  1133  				p.print(unindent)
  1134  			} else {
  1135  				p.exprList(s.Pos(), s.Results, 1, 0, token.NoPos)
  1136  			}
  1137  		}
  1138  
  1139  	case *ast.BranchStmt:
  1140  		p.print(s.Tok)
  1141  		if s.Label != nil {
  1142  			p.print(blank)
  1143  			p.expr(s.Label)
  1144  		}
  1145  
  1146  	case *ast.BlockStmt:
  1147  		p.block(s, 1)
  1148  
  1149  	case *ast.IfStmt:
  1150  		p.print(token.IF)
  1151  		p.controlClause(false, s.Init, s.Cond, nil)
  1152  		p.block(s.Body, 1)
  1153  		if s.Else != nil {
  1154  			p.print(blank, token.ELSE, blank)
  1155  			switch s.Else.(type) {
  1156  			case *ast.BlockStmt, *ast.IfStmt:
  1157  				p.stmt(s.Else, nextIsRBrace)
  1158  			default:
  1159  				p.print(token.LBRACE, indent, formfeed)
  1160  				p.stmt(s.Else, true)
  1161  				p.print(unindent, formfeed, token.RBRACE)
  1162  			}
  1163  		}
  1164  
  1165  	case *ast.CaseClause:
  1166  		if s.List != nil {
  1167  			p.print(token.CASE, blank)
  1168  			p.exprList(s.Pos(), s.List, 1, 0, s.Colon)
  1169  		} else {
  1170  			p.print(token.DEFAULT)
  1171  		}
  1172  		p.print(s.Colon, token.COLON)
  1173  		p.stmtList(s.Body, 1, nextIsRBrace)
  1174  
  1175  	case *ast.SwitchStmt:
  1176  		p.print(token.SWITCH)
  1177  		p.controlClause(false, s.Init, s.Tag, nil)
  1178  		p.block(s.Body, 0)
  1179  
  1180  	case *ast.TypeSwitchStmt:
  1181  		p.print(token.SWITCH)
  1182  		if s.Init != nil {
  1183  			p.print(blank)
  1184  			p.stmt(s.Init, false)
  1185  			p.print(token.SEMICOLON)
  1186  		}
  1187  		p.print(blank)
  1188  		p.stmt(s.Assign, false)
  1189  		p.print(blank)
  1190  		p.block(s.Body, 0)
  1191  
  1192  	case *ast.CommClause:
  1193  		if s.Comm != nil {
  1194  			p.print(token.CASE, blank)
  1195  			p.stmt(s.Comm, false)
  1196  		} else {
  1197  			p.print(token.DEFAULT)
  1198  		}
  1199  		p.print(s.Colon, token.COLON)
  1200  		p.stmtList(s.Body, 1, nextIsRBrace)
  1201  
  1202  	case *ast.SelectStmt:
  1203  		p.print(token.SELECT, blank)
  1204  		body := s.Body
  1205  		if len(body.List) == 0 && !p.commentBefore(p.posFor(body.Rbrace)) {
  1206  			// print empty select statement w/o comments on one line
  1207  			p.print(body.Lbrace, token.LBRACE, body.Rbrace, token.RBRACE)
  1208  		} else {
  1209  			p.block(body, 0)
  1210  		}
  1211  
  1212  	case *ast.ForStmt:
  1213  		p.print(token.FOR)
  1214  		p.controlClause(true, s.Init, s.Cond, s.Post)
  1215  		p.block(s.Body, 1)
  1216  
  1217  	case *ast.RangeStmt:
  1218  		p.print(token.FOR, blank)
  1219  		p.expr(s.Key)
  1220  		if s.Value != nil {
  1221  			// use position of value following the comma as
  1222  			// comma position for correct comment placement
  1223  			p.print(s.Value.Pos(), token.COMMA, blank)
  1224  			p.expr(s.Value)
  1225  		}
  1226  		p.print(blank, s.TokPos, s.Tok, blank, token.RANGE, blank)
  1227  		p.expr(stripParens(s.X))
  1228  		p.print(blank)
  1229  		p.block(s.Body, 1)
  1230  
  1231  	default:
  1232  		panic("unreachable")
  1233  	}
  1234  
  1235  	return
  1236  }
  1237  
  1238  // ----------------------------------------------------------------------------
  1239  // Declarations
  1240  
  1241  // The keepTypeColumn function determines if the type column of a series of
  1242  // consecutive const or var declarations must be kept, or if initialization
  1243  // values (V) can be placed in the type column (T) instead. The i'th entry
  1244  // in the result slice is true if the type column in spec[i] must be kept.
  1245  //
  1246  // For example, the declaration:
  1247  //
  1248  //	const (
  1249  //		foobar int = 42 // comment
  1250  //		x          = 7  // comment
  1251  //		foo
  1252  //              bar = 991
  1253  //	)
  1254  //
  1255  // leads to the type/values matrix below. A run of value columns (V) can
  1256  // be moved into the type column if there is no type for any of the values
  1257  // in that column (we only move entire columns so that they align properly).
  1258  //
  1259  //	matrix        formatted     result
  1260  //                    matrix
  1261  //	T  V    ->    T  V     ->   true      there is a T and so the type
  1262  //	-  V          -  V          true      column must be kept
  1263  //	-  -          -  -          false
  1264  //	-  V          V  -          false     V is moved into T column
  1265  //
  1266  func keepTypeColumn(specs []ast.Spec) []bool {
  1267  	m := make([]bool, len(specs))
  1268  
  1269  	populate := func(i, j int, keepType bool) {
  1270  		if keepType {
  1271  			for ; i < j; i++ {
  1272  				m[i] = true
  1273  			}
  1274  		}
  1275  	}
  1276  
  1277  	i0 := -1 // if i0 >= 0 we are in a run and i0 is the start of the run
  1278  	var keepType bool
  1279  	for i, s := range specs {
  1280  		t := s.(*ast.ValueSpec)
  1281  		if t.Values != nil {
  1282  			if i0 < 0 {
  1283  				// start of a run of ValueSpecs with non-nil Values
  1284  				i0 = i
  1285  				keepType = false
  1286  			}
  1287  		} else {
  1288  			if i0 >= 0 {
  1289  				// end of a run
  1290  				populate(i0, i, keepType)
  1291  				i0 = -1
  1292  			}
  1293  		}
  1294  		if t.Type != nil {
  1295  			keepType = true
  1296  		}
  1297  	}
  1298  	if i0 >= 0 {
  1299  		// end of a run
  1300  		populate(i0, len(specs), keepType)
  1301  	}
  1302  
  1303  	return m
  1304  }
  1305  
  1306  func (p *printer) valueSpec(s *ast.ValueSpec, keepType bool) {
  1307  	p.setComment(s.Doc)
  1308  	p.identList(s.Names, false) // always present
  1309  	extraTabs := 3
  1310  	if s.Type != nil || keepType {
  1311  		p.print(vtab)
  1312  		extraTabs--
  1313  	}
  1314  	if s.Type != nil {
  1315  		p.expr(s.Type)
  1316  	}
  1317  	if s.Values != nil {
  1318  		p.print(vtab, token.ASSIGN, blank)
  1319  		p.exprList(token.NoPos, s.Values, 1, 0, token.NoPos)
  1320  		extraTabs--
  1321  	}
  1322  	if s.Comment != nil {
  1323  		for ; extraTabs > 0; extraTabs-- {
  1324  			p.print(vtab)
  1325  		}
  1326  		p.setComment(s.Comment)
  1327  	}
  1328  }
  1329  
  1330  // The parameter n is the number of specs in the group. If doIndent is set,
  1331  // multi-line identifier lists in the spec are indented when the first
  1332  // linebreak is encountered.
  1333  //
  1334  func (p *printer) spec(spec ast.Spec, n int, doIndent bool) {
  1335  	switch s := spec.(type) {
  1336  	case *ast.ImportSpec:
  1337  		p.setComment(s.Doc)
  1338  		if s.Name != nil {
  1339  			p.expr(s.Name)
  1340  			p.print(blank)
  1341  		}
  1342  		p.expr(s.Path)
  1343  		p.setComment(s.Comment)
  1344  		p.print(s.EndPos)
  1345  
  1346  	case *ast.ValueSpec:
  1347  		if n != 1 {
  1348  			p.internalError("expected n = 1; got", n)
  1349  		}
  1350  		p.setComment(s.Doc)
  1351  		p.identList(s.Names, doIndent) // always present
  1352  		if s.Type != nil {
  1353  			p.print(blank)
  1354  			p.expr(s.Type)
  1355  		}
  1356  		if s.Values != nil {
  1357  			p.print(blank, token.ASSIGN, blank)
  1358  			p.exprList(token.NoPos, s.Values, 1, 0, token.NoPos)
  1359  		}
  1360  		p.setComment(s.Comment)
  1361  
  1362  	case *ast.TypeSpec:
  1363  		p.setComment(s.Doc)
  1364  		p.expr(s.Name)
  1365  		if n == 1 {
  1366  			p.print(blank)
  1367  		} else {
  1368  			p.print(vtab)
  1369  		}
  1370  		p.expr(s.Type)
  1371  		p.setComment(s.Comment)
  1372  
  1373  	default:
  1374  		panic("unreachable")
  1375  	}
  1376  }
  1377  
  1378  func (p *printer) genDecl(d *ast.GenDecl) {
  1379  	p.setComment(d.Doc)
  1380  	p.print(d.Pos(), d.Tok, blank)
  1381  
  1382  	if d.Lparen.IsValid() {
  1383  		// group of parenthesized declarations
  1384  		p.print(d.Lparen, token.LPAREN)
  1385  		if n := len(d.Specs); n > 0 {
  1386  			p.print(indent, formfeed)
  1387  			if n > 1 && (d.Tok == token.CONST || d.Tok == token.VAR) {
  1388  				// two or more grouped const/var declarations:
  1389  				// determine if the type column must be kept
  1390  				keepType := keepTypeColumn(d.Specs)
  1391  				var line int
  1392  				for i, s := range d.Specs {
  1393  					if i > 0 {
  1394  						p.linebreak(p.lineFor(s.Pos()), 1, ignore, p.linesFrom(line) > 0)
  1395  					}
  1396  					p.recordLine(&line)
  1397  					p.valueSpec(s.(*ast.ValueSpec), keepType[i])
  1398  				}
  1399  			} else {
  1400  				var line int
  1401  				for i, s := range d.Specs {
  1402  					if i > 0 {
  1403  						p.linebreak(p.lineFor(s.Pos()), 1, ignore, p.linesFrom(line) > 0)
  1404  					}
  1405  					p.recordLine(&line)
  1406  					p.spec(s, n, false)
  1407  				}
  1408  			}
  1409  			p.print(unindent, formfeed)
  1410  		}
  1411  		p.print(d.Rparen, token.RPAREN)
  1412  
  1413  	} else {
  1414  		// single declaration
  1415  		p.spec(d.Specs[0], 1, true)
  1416  	}
  1417  }
  1418  
  1419  // nodeSize determines the size of n in chars after formatting.
  1420  // The result is <= maxSize if the node fits on one line with at
  1421  // most maxSize chars and the formatted output doesn't contain
  1422  // any control chars. Otherwise, the result is > maxSize.
  1423  //
  1424  func (p *printer) nodeSize(n ast.Node, maxSize int) (size int) {
  1425  	// nodeSize invokes the printer, which may invoke nodeSize
  1426  	// recursively. For deep composite literal nests, this can
  1427  	// lead to an exponential algorithm. Remember previous
  1428  	// results to prune the recursion (was issue 1628).
  1429  	if size, found := p.nodeSizes[n]; found {
  1430  		return size
  1431  	}
  1432  
  1433  	size = maxSize + 1 // assume n doesn't fit
  1434  	p.nodeSizes[n] = size
  1435  
  1436  	// nodeSize computation must be independent of particular
  1437  	// style so that we always get the same decision; print
  1438  	// in RawFormat
  1439  	cfg := Config{Mode: RawFormat}
  1440  	var buf bytes.Buffer
  1441  	if err := cfg.fprint(&buf, p.fset, n, p.nodeSizes); err != nil {
  1442  		return
  1443  	}
  1444  	if buf.Len() <= maxSize {
  1445  		for _, ch := range buf.Bytes() {
  1446  			if ch < ' ' {
  1447  				return
  1448  			}
  1449  		}
  1450  		size = buf.Len() // n fits
  1451  		p.nodeSizes[n] = size
  1452  	}
  1453  	return
  1454  }
  1455  
  1456  // bodySize is like nodeSize but it is specialized for *ast.BlockStmt's.
  1457  func (p *printer) bodySize(b *ast.BlockStmt, maxSize int) int {
  1458  	pos1 := b.Pos()
  1459  	pos2 := b.Rbrace
  1460  	if pos1.IsValid() && pos2.IsValid() && p.lineFor(pos1) != p.lineFor(pos2) {
  1461  		// opening and closing brace are on different lines - don't make it a one-liner
  1462  		return maxSize + 1
  1463  	}
  1464  	if len(b.List) > 5 {
  1465  		// too many statements - don't make it a one-liner
  1466  		return maxSize + 1
  1467  	}
  1468  	// otherwise, estimate body size
  1469  	bodySize := p.commentSizeBefore(p.posFor(pos2))
  1470  	for i, s := range b.List {
  1471  		if bodySize > maxSize {
  1472  			break // no need to continue
  1473  		}
  1474  		if i > 0 {
  1475  			bodySize += 2 // space for a semicolon and blank
  1476  		}
  1477  		bodySize += p.nodeSize(s, maxSize)
  1478  	}
  1479  	return bodySize
  1480  }
  1481  
  1482  // adjBlock prints an "adjacent" block (e.g., a for-loop or function body) following
  1483  // a header (e.g., a for-loop control clause or function signature) of given headerSize.
  1484  // If the header's and block's size are "small enough" and the block is "simple enough",
  1485  // the block is printed on the current line, without line breaks, spaced from the header
  1486  // by sep. Otherwise the block's opening "{" is printed on the current line, followed by
  1487  // lines for the block's statements and its closing "}".
  1488  //
  1489  func (p *printer) adjBlock(headerSize int, sep whiteSpace, b *ast.BlockStmt) {
  1490  	if b == nil {
  1491  		return
  1492  	}
  1493  
  1494  	const maxSize = 100
  1495  	if headerSize+p.bodySize(b, maxSize) <= maxSize {
  1496  		p.print(sep, b.Lbrace, token.LBRACE)
  1497  		if len(b.List) > 0 {
  1498  			p.print(blank)
  1499  			for i, s := range b.List {
  1500  				if i > 0 {
  1501  					p.print(token.SEMICOLON, blank)
  1502  				}
  1503  				p.stmt(s, i == len(b.List)-1)
  1504  			}
  1505  			p.print(blank)
  1506  		}
  1507  		p.print(noExtraLinebreak, b.Rbrace, token.RBRACE, noExtraLinebreak)
  1508  		return
  1509  	}
  1510  
  1511  	if sep != ignore {
  1512  		p.print(blank) // always use blank
  1513  	}
  1514  	p.block(b, 1)
  1515  }
  1516  
  1517  // distanceFrom returns the column difference between from and p.pos (the current
  1518  // estimated position) if both are on the same line; if they are on different lines
  1519  // (or unknown) the result is infinity.
  1520  func (p *printer) distanceFrom(from token.Pos) int {
  1521  	if from.IsValid() && p.pos.IsValid() {
  1522  		if f := p.posFor(from); f.Line == p.pos.Line {
  1523  			return p.pos.Column - f.Column
  1524  		}
  1525  	}
  1526  	return infinity
  1527  }
  1528  
  1529  func (p *printer) funcDecl(d *ast.FuncDecl) {
  1530  	p.setComment(d.Doc)
  1531  	p.print(d.Pos(), token.FUNC, blank)
  1532  	if d.Recv != nil {
  1533  		p.parameters(d.Recv) // method: print receiver
  1534  		p.print(blank)
  1535  	}
  1536  	p.expr(d.Name)
  1537  	p.signature(d.Type.Params, d.Type.Results)
  1538  	p.adjBlock(p.distanceFrom(d.Pos()), vtab, d.Body)
  1539  }
  1540  
  1541  func (p *printer) decl(decl ast.Decl) {
  1542  	switch d := decl.(type) {
  1543  	case *ast.BadDecl:
  1544  		p.print(d.Pos(), "BadDecl")
  1545  	case *ast.GenDecl:
  1546  		p.genDecl(d)
  1547  	case *ast.FuncDecl:
  1548  		p.funcDecl(d)
  1549  	default:
  1550  		panic("unreachable")
  1551  	}
  1552  }
  1553  
  1554  // ----------------------------------------------------------------------------
  1555  // Files
  1556  
  1557  func declToken(decl ast.Decl) (tok token.Token) {
  1558  	tok = token.ILLEGAL
  1559  	switch d := decl.(type) {
  1560  	case *ast.GenDecl:
  1561  		tok = d.Tok
  1562  	case *ast.FuncDecl:
  1563  		tok = token.FUNC
  1564  	}
  1565  	return
  1566  }
  1567  
  1568  func (p *printer) declList(list []ast.Decl) {
  1569  	tok := token.ILLEGAL
  1570  	for _, d := range list {
  1571  		prev := tok
  1572  		tok = declToken(d)
  1573  		// If the declaration token changed (e.g., from CONST to TYPE)
  1574  		// or the next declaration has documentation associated with it,
  1575  		// print an empty line between top-level declarations.
  1576  		// (because p.linebreak is called with the position of d, which
  1577  		// is past any documentation, the minimum requirement is satisfied
  1578  		// even w/o the extra getDoc(d) nil-check - leave it in case the
  1579  		// linebreak logic improves - there's already a TODO).
  1580  		if len(p.output) > 0 {
  1581  			// only print line break if we are not at the beginning of the output
  1582  			// (i.e., we are not printing only a partial program)
  1583  			min := 1
  1584  			if prev != tok || getDoc(d) != nil {
  1585  				min = 2
  1586  			}
  1587  			p.linebreak(p.lineFor(d.Pos()), min, ignore, false)
  1588  		}
  1589  		p.decl(d)
  1590  	}
  1591  }
  1592  
  1593  func (p *printer) file(src *ast.File) {
  1594  	p.setComment(src.Doc)
  1595  	p.print(src.Pos(), token.PACKAGE, blank)
  1596  	p.expr(src.Name)
  1597  	p.declList(src.Decls)
  1598  	p.print(newline)
  1599  }