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