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