Black Lives Matter. Support the Equal Justice Initiative.

Source file src/go/printer/nodes.go

Documentation: go/printer

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

View as plain text