Source file src/go/printer/nodes.go

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

View as plain text