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