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