github.com/hikaru7719/go@v0.0.0-20181025140707-c8b2ac68906a/src/fmt/print.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 package fmt 6 7 import ( 8 "errors" 9 "internal/fmtsort" 10 "io" 11 "os" 12 "reflect" 13 "sync" 14 "unicode/utf8" 15 ) 16 17 // Strings for use with buffer.WriteString. 18 // This is less overhead than using buffer.Write with byte arrays. 19 const ( 20 commaSpaceString = ", " 21 nilAngleString = "<nil>" 22 nilParenString = "(nil)" 23 nilString = "nil" 24 mapString = "map[" 25 percentBangString = "%!" 26 missingString = "(MISSING)" 27 badIndexString = "(BADINDEX)" 28 panicString = "(PANIC=" 29 extraString = "%!(EXTRA " 30 badWidthString = "%!(BADWIDTH)" 31 badPrecString = "%!(BADPREC)" 32 noVerbString = "%!(NOVERB)" 33 invReflectString = "<invalid reflect.Value>" 34 ) 35 36 // State represents the printer state passed to custom formatters. 37 // It provides access to the io.Writer interface plus information about 38 // the flags and options for the operand's format specifier. 39 type State interface { 40 // Write is the function to call to emit formatted output to be printed. 41 Write(b []byte) (n int, err error) 42 // Width returns the value of the width option and whether it has been set. 43 Width() (wid int, ok bool) 44 // Precision returns the value of the precision option and whether it has been set. 45 Precision() (prec int, ok bool) 46 47 // Flag reports whether the flag c, a character, has been set. 48 Flag(c int) bool 49 } 50 51 // Formatter is the interface implemented by values with a custom formatter. 52 // The implementation of Format may call Sprint(f) or Fprint(f) etc. 53 // to generate its output. 54 type Formatter interface { 55 Format(f State, c rune) 56 } 57 58 // Stringer is implemented by any value that has a String method, 59 // which defines the ``native'' format for that value. 60 // The String method is used to print values passed as an operand 61 // to any format that accepts a string or to an unformatted printer 62 // such as Print. 63 type Stringer interface { 64 String() string 65 } 66 67 // GoStringer is implemented by any value that has a GoString method, 68 // which defines the Go syntax for that value. 69 // The GoString method is used to print values passed as an operand 70 // to a %#v format. 71 type GoStringer interface { 72 GoString() string 73 } 74 75 // Use simple []byte instead of bytes.Buffer to avoid large dependency. 76 type buffer []byte 77 78 func (b *buffer) Write(p []byte) { 79 *b = append(*b, p...) 80 } 81 82 func (b *buffer) WriteString(s string) { 83 *b = append(*b, s...) 84 } 85 86 func (b *buffer) WriteByte(c byte) { 87 *b = append(*b, c) 88 } 89 90 func (bp *buffer) WriteRune(r rune) { 91 if r < utf8.RuneSelf { 92 *bp = append(*bp, byte(r)) 93 return 94 } 95 96 b := *bp 97 n := len(b) 98 for n+utf8.UTFMax > cap(b) { 99 b = append(b, 0) 100 } 101 w := utf8.EncodeRune(b[n:n+utf8.UTFMax], r) 102 *bp = b[:n+w] 103 } 104 105 // pp is used to store a printer's state and is reused with sync.Pool to avoid allocations. 106 type pp struct { 107 buf buffer 108 109 // arg holds the current item, as an interface{}. 110 arg interface{} 111 112 // value is used instead of arg for reflect values. 113 value reflect.Value 114 115 // fmt is used to format basic items such as integers or strings. 116 fmt fmt 117 118 // reordered records whether the format string used argument reordering. 119 reordered bool 120 // goodArgNum records whether the most recent reordering directive was valid. 121 goodArgNum bool 122 // panicking is set by catchPanic to avoid infinite panic, recover, panic, ... recursion. 123 panicking bool 124 // erroring is set when printing an error string to guard against calling handleMethods. 125 erroring bool 126 } 127 128 var ppFree = sync.Pool{ 129 New: func() interface{} { return new(pp) }, 130 } 131 132 // newPrinter allocates a new pp struct or grabs a cached one. 133 func newPrinter() *pp { 134 p := ppFree.Get().(*pp) 135 p.panicking = false 136 p.erroring = false 137 p.fmt.init(&p.buf) 138 return p 139 } 140 141 // free saves used pp structs in ppFree; avoids an allocation per invocation. 142 func (p *pp) free() { 143 // Proper usage of a sync.Pool requires each entry to have approximately 144 // the same memory cost. To obtain this property when the stored type 145 // contains a variably-sized buffer, we add a hard limit on the maximum buffer 146 // to place back in the pool. 147 // 148 // See https://golang.org/issue/23199 149 if cap(p.buf) > 64<<10 { 150 return 151 } 152 153 p.buf = p.buf[:0] 154 p.arg = nil 155 p.value = reflect.Value{} 156 ppFree.Put(p) 157 } 158 159 func (p *pp) Width() (wid int, ok bool) { return p.fmt.wid, p.fmt.widPresent } 160 161 func (p *pp) Precision() (prec int, ok bool) { return p.fmt.prec, p.fmt.precPresent } 162 163 func (p *pp) Flag(b int) bool { 164 switch b { 165 case '-': 166 return p.fmt.minus 167 case '+': 168 return p.fmt.plus || p.fmt.plusV 169 case '#': 170 return p.fmt.sharp || p.fmt.sharpV 171 case ' ': 172 return p.fmt.space 173 case '0': 174 return p.fmt.zero 175 } 176 return false 177 } 178 179 // Implement Write so we can call Fprintf on a pp (through State), for 180 // recursive use in custom verbs. 181 func (p *pp) Write(b []byte) (ret int, err error) { 182 p.buf.Write(b) 183 return len(b), nil 184 } 185 186 // Implement WriteString so that we can call io.WriteString 187 // on a pp (through state), for efficiency. 188 func (p *pp) WriteString(s string) (ret int, err error) { 189 p.buf.WriteString(s) 190 return len(s), nil 191 } 192 193 // These routines end in 'f' and take a format string. 194 195 // Fprintf formats according to a format specifier and writes to w. 196 // It returns the number of bytes written and any write error encountered. 197 func Fprintf(w io.Writer, format string, a ...interface{}) (n int, err error) { 198 p := newPrinter() 199 p.doPrintf(format, a) 200 n, err = w.Write(p.buf) 201 p.free() 202 return 203 } 204 205 // Printf formats according to a format specifier and writes to standard output. 206 // It returns the number of bytes written and any write error encountered. 207 func Printf(format string, a ...interface{}) (n int, err error) { 208 return Fprintf(os.Stdout, format, a...) 209 } 210 211 // Sprintf formats according to a format specifier and returns the resulting string. 212 func Sprintf(format string, a ...interface{}) string { 213 p := newPrinter() 214 p.doPrintf(format, a) 215 s := string(p.buf) 216 p.free() 217 return s 218 } 219 220 // Errorf formats according to a format specifier and returns the string 221 // as a value that satisfies error. 222 func Errorf(format string, a ...interface{}) error { 223 return errors.New(Sprintf(format, a...)) 224 } 225 226 // These routines do not take a format string 227 228 // Fprint formats using the default formats for its operands and writes to w. 229 // Spaces are added between operands when neither is a string. 230 // It returns the number of bytes written and any write error encountered. 231 func Fprint(w io.Writer, a ...interface{}) (n int, err error) { 232 p := newPrinter() 233 p.doPrint(a) 234 n, err = w.Write(p.buf) 235 p.free() 236 return 237 } 238 239 // Print formats using the default formats for its operands and writes to standard output. 240 // Spaces are added between operands when neither is a string. 241 // It returns the number of bytes written and any write error encountered. 242 func Print(a ...interface{}) (n int, err error) { 243 return Fprint(os.Stdout, a...) 244 } 245 246 // Sprint formats using the default formats for its operands and returns the resulting string. 247 // Spaces are added between operands when neither is a string. 248 func Sprint(a ...interface{}) string { 249 p := newPrinter() 250 p.doPrint(a) 251 s := string(p.buf) 252 p.free() 253 return s 254 } 255 256 // These routines end in 'ln', do not take a format string, 257 // always add spaces between operands, and add a newline 258 // after the last operand. 259 260 // Fprintln formats using the default formats for its operands and writes to w. 261 // Spaces are always added between operands and a newline is appended. 262 // It returns the number of bytes written and any write error encountered. 263 func Fprintln(w io.Writer, a ...interface{}) (n int, err error) { 264 p := newPrinter() 265 p.doPrintln(a) 266 n, err = w.Write(p.buf) 267 p.free() 268 return 269 } 270 271 // Println formats using the default formats for its operands and writes to standard output. 272 // Spaces are always added between operands and a newline is appended. 273 // It returns the number of bytes written and any write error encountered. 274 func Println(a ...interface{}) (n int, err error) { 275 return Fprintln(os.Stdout, a...) 276 } 277 278 // Sprintln formats using the default formats for its operands and returns the resulting string. 279 // Spaces are always added between operands and a newline is appended. 280 func Sprintln(a ...interface{}) string { 281 p := newPrinter() 282 p.doPrintln(a) 283 s := string(p.buf) 284 p.free() 285 return s 286 } 287 288 // getField gets the i'th field of the struct value. 289 // If the field is itself is an interface, return a value for 290 // the thing inside the interface, not the interface itself. 291 func getField(v reflect.Value, i int) reflect.Value { 292 val := v.Field(i) 293 if val.Kind() == reflect.Interface && !val.IsNil() { 294 val = val.Elem() 295 } 296 return val 297 } 298 299 // tooLarge reports whether the magnitude of the integer is 300 // too large to be used as a formatting width or precision. 301 func tooLarge(x int) bool { 302 const max int = 1e6 303 return x > max || x < -max 304 } 305 306 // parsenum converts ASCII to integer. num is 0 (and isnum is false) if no number present. 307 func parsenum(s string, start, end int) (num int, isnum bool, newi int) { 308 if start >= end { 309 return 0, false, end 310 } 311 for newi = start; newi < end && '0' <= s[newi] && s[newi] <= '9'; newi++ { 312 if tooLarge(num) { 313 return 0, false, end // Overflow; crazy long number most likely. 314 } 315 num = num*10 + int(s[newi]-'0') 316 isnum = true 317 } 318 return 319 } 320 321 func (p *pp) unknownType(v reflect.Value) { 322 if !v.IsValid() { 323 p.buf.WriteString(nilAngleString) 324 return 325 } 326 p.buf.WriteByte('?') 327 p.buf.WriteString(v.Type().String()) 328 p.buf.WriteByte('?') 329 } 330 331 func (p *pp) badVerb(verb rune) { 332 p.erroring = true 333 p.buf.WriteString(percentBangString) 334 p.buf.WriteRune(verb) 335 p.buf.WriteByte('(') 336 switch { 337 case p.arg != nil: 338 p.buf.WriteString(reflect.TypeOf(p.arg).String()) 339 p.buf.WriteByte('=') 340 p.printArg(p.arg, 'v') 341 case p.value.IsValid(): 342 p.buf.WriteString(p.value.Type().String()) 343 p.buf.WriteByte('=') 344 p.printValue(p.value, 'v', 0) 345 default: 346 p.buf.WriteString(nilAngleString) 347 } 348 p.buf.WriteByte(')') 349 p.erroring = false 350 } 351 352 func (p *pp) fmtBool(v bool, verb rune) { 353 switch verb { 354 case 't', 'v': 355 p.fmt.fmtBoolean(v) 356 default: 357 p.badVerb(verb) 358 } 359 } 360 361 // fmt0x64 formats a uint64 in hexadecimal and prefixes it with 0x or 362 // not, as requested, by temporarily setting the sharp flag. 363 func (p *pp) fmt0x64(v uint64, leading0x bool) { 364 sharp := p.fmt.sharp 365 p.fmt.sharp = leading0x 366 p.fmt.fmtInteger(v, 16, unsigned, ldigits) 367 p.fmt.sharp = sharp 368 } 369 370 // fmtInteger formats a signed or unsigned integer. 371 func (p *pp) fmtInteger(v uint64, isSigned bool, verb rune) { 372 switch verb { 373 case 'v': 374 if p.fmt.sharpV && !isSigned { 375 p.fmt0x64(v, true) 376 } else { 377 p.fmt.fmtInteger(v, 10, isSigned, ldigits) 378 } 379 case 'd': 380 p.fmt.fmtInteger(v, 10, isSigned, ldigits) 381 case 'b': 382 p.fmt.fmtInteger(v, 2, isSigned, ldigits) 383 case 'o': 384 p.fmt.fmtInteger(v, 8, isSigned, ldigits) 385 case 'x': 386 p.fmt.fmtInteger(v, 16, isSigned, ldigits) 387 case 'X': 388 p.fmt.fmtInteger(v, 16, isSigned, udigits) 389 case 'c': 390 p.fmt.fmtC(v) 391 case 'q': 392 if v <= utf8.MaxRune { 393 p.fmt.fmtQc(v) 394 } else { 395 p.badVerb(verb) 396 } 397 case 'U': 398 p.fmt.fmtUnicode(v) 399 default: 400 p.badVerb(verb) 401 } 402 } 403 404 // fmtFloat formats a float. The default precision for each verb 405 // is specified as last argument in the call to fmt_float. 406 func (p *pp) fmtFloat(v float64, size int, verb rune) { 407 switch verb { 408 case 'v': 409 p.fmt.fmtFloat(v, size, 'g', -1) 410 case 'b', 'g', 'G': 411 p.fmt.fmtFloat(v, size, verb, -1) 412 case 'f', 'e', 'E': 413 p.fmt.fmtFloat(v, size, verb, 6) 414 case 'F': 415 p.fmt.fmtFloat(v, size, 'f', 6) 416 default: 417 p.badVerb(verb) 418 } 419 } 420 421 // fmtComplex formats a complex number v with 422 // r = real(v) and j = imag(v) as (r+ji) using 423 // fmtFloat for r and j formatting. 424 func (p *pp) fmtComplex(v complex128, size int, verb rune) { 425 // Make sure any unsupported verbs are found before the 426 // calls to fmtFloat to not generate an incorrect error string. 427 switch verb { 428 case 'v', 'b', 'g', 'G', 'f', 'F', 'e', 'E': 429 oldPlus := p.fmt.plus 430 p.buf.WriteByte('(') 431 p.fmtFloat(real(v), size/2, verb) 432 // Imaginary part always has a sign. 433 p.fmt.plus = true 434 p.fmtFloat(imag(v), size/2, verb) 435 p.buf.WriteString("i)") 436 p.fmt.plus = oldPlus 437 default: 438 p.badVerb(verb) 439 } 440 } 441 442 func (p *pp) fmtString(v string, verb rune) { 443 switch verb { 444 case 'v': 445 if p.fmt.sharpV { 446 p.fmt.fmtQ(v) 447 } else { 448 p.fmt.fmtS(v) 449 } 450 case 's': 451 p.fmt.fmtS(v) 452 case 'x': 453 p.fmt.fmtSx(v, ldigits) 454 case 'X': 455 p.fmt.fmtSx(v, udigits) 456 case 'q': 457 p.fmt.fmtQ(v) 458 default: 459 p.badVerb(verb) 460 } 461 } 462 463 func (p *pp) fmtBytes(v []byte, verb rune, typeString string) { 464 switch verb { 465 case 'v', 'd': 466 if p.fmt.sharpV { 467 p.buf.WriteString(typeString) 468 if v == nil { 469 p.buf.WriteString(nilParenString) 470 return 471 } 472 p.buf.WriteByte('{') 473 for i, c := range v { 474 if i > 0 { 475 p.buf.WriteString(commaSpaceString) 476 } 477 p.fmt0x64(uint64(c), true) 478 } 479 p.buf.WriteByte('}') 480 } else { 481 p.buf.WriteByte('[') 482 for i, c := range v { 483 if i > 0 { 484 p.buf.WriteByte(' ') 485 } 486 p.fmt.fmtInteger(uint64(c), 10, unsigned, ldigits) 487 } 488 p.buf.WriteByte(']') 489 } 490 case 's': 491 p.fmt.fmtS(string(v)) 492 case 'x': 493 p.fmt.fmtBx(v, ldigits) 494 case 'X': 495 p.fmt.fmtBx(v, udigits) 496 case 'q': 497 p.fmt.fmtQ(string(v)) 498 default: 499 p.printValue(reflect.ValueOf(v), verb, 0) 500 } 501 } 502 503 func (p *pp) fmtPointer(value reflect.Value, verb rune) { 504 var u uintptr 505 switch value.Kind() { 506 case reflect.Chan, reflect.Func, reflect.Map, reflect.Ptr, reflect.Slice, reflect.UnsafePointer: 507 u = value.Pointer() 508 default: 509 p.badVerb(verb) 510 return 511 } 512 513 switch verb { 514 case 'v': 515 if p.fmt.sharpV { 516 p.buf.WriteByte('(') 517 p.buf.WriteString(value.Type().String()) 518 p.buf.WriteString(")(") 519 if u == 0 { 520 p.buf.WriteString(nilString) 521 } else { 522 p.fmt0x64(uint64(u), true) 523 } 524 p.buf.WriteByte(')') 525 } else { 526 if u == 0 { 527 p.fmt.padString(nilAngleString) 528 } else { 529 p.fmt0x64(uint64(u), !p.fmt.sharp) 530 } 531 } 532 case 'p': 533 p.fmt0x64(uint64(u), !p.fmt.sharp) 534 case 'b', 'o', 'd', 'x', 'X': 535 p.fmtInteger(uint64(u), unsigned, verb) 536 default: 537 p.badVerb(verb) 538 } 539 } 540 541 func (p *pp) catchPanic(arg interface{}, verb rune) { 542 if err := recover(); err != nil { 543 // If it's a nil pointer, just say "<nil>". The likeliest causes are a 544 // Stringer that fails to guard against nil or a nil pointer for a 545 // value receiver, and in either case, "<nil>" is a nice result. 546 if v := reflect.ValueOf(arg); v.Kind() == reflect.Ptr && v.IsNil() { 547 p.buf.WriteString(nilAngleString) 548 return 549 } 550 // Otherwise print a concise panic message. Most of the time the panic 551 // value will print itself nicely. 552 if p.panicking { 553 // Nested panics; the recursion in printArg cannot succeed. 554 panic(err) 555 } 556 557 oldFlags := p.fmt.fmtFlags 558 // For this output we want default behavior. 559 p.fmt.clearflags() 560 561 p.buf.WriteString(percentBangString) 562 p.buf.WriteRune(verb) 563 p.buf.WriteString(panicString) 564 p.panicking = true 565 p.printArg(err, 'v') 566 p.panicking = false 567 p.buf.WriteByte(')') 568 569 p.fmt.fmtFlags = oldFlags 570 } 571 } 572 573 func (p *pp) handleMethods(verb rune) (handled bool) { 574 if p.erroring { 575 return 576 } 577 // Is it a Formatter? 578 if formatter, ok := p.arg.(Formatter); ok { 579 handled = true 580 defer p.catchPanic(p.arg, verb) 581 formatter.Format(p, verb) 582 return 583 } 584 585 // If we're doing Go syntax and the argument knows how to supply it, take care of it now. 586 if p.fmt.sharpV { 587 if stringer, ok := p.arg.(GoStringer); ok { 588 handled = true 589 defer p.catchPanic(p.arg, verb) 590 // Print the result of GoString unadorned. 591 p.fmt.fmtS(stringer.GoString()) 592 return 593 } 594 } else { 595 // If a string is acceptable according to the format, see if 596 // the value satisfies one of the string-valued interfaces. 597 // Println etc. set verb to %v, which is "stringable". 598 switch verb { 599 case 'v', 's', 'x', 'X', 'q': 600 // Is it an error or Stringer? 601 // The duplication in the bodies is necessary: 602 // setting handled and deferring catchPanic 603 // must happen before calling the method. 604 switch v := p.arg.(type) { 605 case error: 606 handled = true 607 defer p.catchPanic(p.arg, verb) 608 p.fmtString(v.Error(), verb) 609 return 610 611 case Stringer: 612 handled = true 613 defer p.catchPanic(p.arg, verb) 614 p.fmtString(v.String(), verb) 615 return 616 } 617 } 618 } 619 return false 620 } 621 622 func (p *pp) printArg(arg interface{}, verb rune) { 623 p.arg = arg 624 p.value = reflect.Value{} 625 626 if arg == nil { 627 switch verb { 628 case 'T', 'v': 629 p.fmt.padString(nilAngleString) 630 default: 631 p.badVerb(verb) 632 } 633 return 634 } 635 636 // Special processing considerations. 637 // %T (the value's type) and %p (its address) are special; we always do them first. 638 switch verb { 639 case 'T': 640 p.fmt.fmtS(reflect.TypeOf(arg).String()) 641 return 642 case 'p': 643 p.fmtPointer(reflect.ValueOf(arg), 'p') 644 return 645 } 646 647 // Some types can be done without reflection. 648 switch f := arg.(type) { 649 case bool: 650 p.fmtBool(f, verb) 651 case float32: 652 p.fmtFloat(float64(f), 32, verb) 653 case float64: 654 p.fmtFloat(f, 64, verb) 655 case complex64: 656 p.fmtComplex(complex128(f), 64, verb) 657 case complex128: 658 p.fmtComplex(f, 128, verb) 659 case int: 660 p.fmtInteger(uint64(f), signed, verb) 661 case int8: 662 p.fmtInteger(uint64(f), signed, verb) 663 case int16: 664 p.fmtInteger(uint64(f), signed, verb) 665 case int32: 666 p.fmtInteger(uint64(f), signed, verb) 667 case int64: 668 p.fmtInteger(uint64(f), signed, verb) 669 case uint: 670 p.fmtInteger(uint64(f), unsigned, verb) 671 case uint8: 672 p.fmtInteger(uint64(f), unsigned, verb) 673 case uint16: 674 p.fmtInteger(uint64(f), unsigned, verb) 675 case uint32: 676 p.fmtInteger(uint64(f), unsigned, verb) 677 case uint64: 678 p.fmtInteger(f, unsigned, verb) 679 case uintptr: 680 p.fmtInteger(uint64(f), unsigned, verb) 681 case string: 682 p.fmtString(f, verb) 683 case []byte: 684 p.fmtBytes(f, verb, "[]byte") 685 case reflect.Value: 686 // Handle extractable values with special methods 687 // since printValue does not handle them at depth 0. 688 if f.IsValid() && f.CanInterface() { 689 p.arg = f.Interface() 690 if p.handleMethods(verb) { 691 return 692 } 693 } 694 p.printValue(f, verb, 0) 695 default: 696 // If the type is not simple, it might have methods. 697 if !p.handleMethods(verb) { 698 // Need to use reflection, since the type had no 699 // interface methods that could be used for formatting. 700 p.printValue(reflect.ValueOf(f), verb, 0) 701 } 702 } 703 } 704 705 // printValue is similar to printArg but starts with a reflect value, not an interface{} value. 706 // It does not handle 'p' and 'T' verbs because these should have been already handled by printArg. 707 func (p *pp) printValue(value reflect.Value, verb rune, depth int) { 708 // Handle values with special methods if not already handled by printArg (depth == 0). 709 if depth > 0 && value.IsValid() && value.CanInterface() { 710 p.arg = value.Interface() 711 if p.handleMethods(verb) { 712 return 713 } 714 } 715 p.arg = nil 716 p.value = value 717 718 switch f := value; value.Kind() { 719 case reflect.Invalid: 720 if depth == 0 { 721 p.buf.WriteString(invReflectString) 722 } else { 723 switch verb { 724 case 'v': 725 p.buf.WriteString(nilAngleString) 726 default: 727 p.badVerb(verb) 728 } 729 } 730 case reflect.Bool: 731 p.fmtBool(f.Bool(), verb) 732 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: 733 p.fmtInteger(uint64(f.Int()), signed, verb) 734 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: 735 p.fmtInteger(f.Uint(), unsigned, verb) 736 case reflect.Float32: 737 p.fmtFloat(f.Float(), 32, verb) 738 case reflect.Float64: 739 p.fmtFloat(f.Float(), 64, verb) 740 case reflect.Complex64: 741 p.fmtComplex(f.Complex(), 64, verb) 742 case reflect.Complex128: 743 p.fmtComplex(f.Complex(), 128, verb) 744 case reflect.String: 745 p.fmtString(f.String(), verb) 746 case reflect.Map: 747 if p.fmt.sharpV { 748 p.buf.WriteString(f.Type().String()) 749 if f.IsNil() { 750 p.buf.WriteString(nilParenString) 751 return 752 } 753 p.buf.WriteByte('{') 754 } else { 755 p.buf.WriteString(mapString) 756 } 757 sorted := fmtsort.Sort(f) 758 for i, key := range sorted.Key { 759 if i > 0 { 760 if p.fmt.sharpV { 761 p.buf.WriteString(commaSpaceString) 762 } else { 763 p.buf.WriteByte(' ') 764 } 765 } 766 p.printValue(key, verb, depth+1) 767 p.buf.WriteByte(':') 768 p.printValue(sorted.Value[i], verb, depth+1) 769 } 770 if p.fmt.sharpV { 771 p.buf.WriteByte('}') 772 } else { 773 p.buf.WriteByte(']') 774 } 775 case reflect.Struct: 776 if p.fmt.sharpV { 777 p.buf.WriteString(f.Type().String()) 778 } 779 p.buf.WriteByte('{') 780 for i := 0; i < f.NumField(); i++ { 781 if i > 0 { 782 if p.fmt.sharpV { 783 p.buf.WriteString(commaSpaceString) 784 } else { 785 p.buf.WriteByte(' ') 786 } 787 } 788 if p.fmt.plusV || p.fmt.sharpV { 789 if name := f.Type().Field(i).Name; name != "" { 790 p.buf.WriteString(name) 791 p.buf.WriteByte(':') 792 } 793 } 794 p.printValue(getField(f, i), verb, depth+1) 795 } 796 p.buf.WriteByte('}') 797 case reflect.Interface: 798 value := f.Elem() 799 if !value.IsValid() { 800 if p.fmt.sharpV { 801 p.buf.WriteString(f.Type().String()) 802 p.buf.WriteString(nilParenString) 803 } else { 804 p.buf.WriteString(nilAngleString) 805 } 806 } else { 807 p.printValue(value, verb, depth+1) 808 } 809 case reflect.Array, reflect.Slice: 810 switch verb { 811 case 's', 'q', 'x', 'X': 812 // Handle byte and uint8 slices and arrays special for the above verbs. 813 t := f.Type() 814 if t.Elem().Kind() == reflect.Uint8 { 815 var bytes []byte 816 if f.Kind() == reflect.Slice { 817 bytes = f.Bytes() 818 } else if f.CanAddr() { 819 bytes = f.Slice(0, f.Len()).Bytes() 820 } else { 821 // We have an array, but we cannot Slice() a non-addressable array, 822 // so we build a slice by hand. This is a rare case but it would be nice 823 // if reflection could help a little more. 824 bytes = make([]byte, f.Len()) 825 for i := range bytes { 826 bytes[i] = byte(f.Index(i).Uint()) 827 } 828 } 829 p.fmtBytes(bytes, verb, t.String()) 830 return 831 } 832 } 833 if p.fmt.sharpV { 834 p.buf.WriteString(f.Type().String()) 835 if f.Kind() == reflect.Slice && f.IsNil() { 836 p.buf.WriteString(nilParenString) 837 return 838 } 839 p.buf.WriteByte('{') 840 for i := 0; i < f.Len(); i++ { 841 if i > 0 { 842 p.buf.WriteString(commaSpaceString) 843 } 844 p.printValue(f.Index(i), verb, depth+1) 845 } 846 p.buf.WriteByte('}') 847 } else { 848 p.buf.WriteByte('[') 849 for i := 0; i < f.Len(); i++ { 850 if i > 0 { 851 p.buf.WriteByte(' ') 852 } 853 p.printValue(f.Index(i), verb, depth+1) 854 } 855 p.buf.WriteByte(']') 856 } 857 case reflect.Ptr: 858 // pointer to array or slice or struct? ok at top level 859 // but not embedded (avoid loops) 860 if depth == 0 && f.Pointer() != 0 { 861 switch a := f.Elem(); a.Kind() { 862 case reflect.Array, reflect.Slice, reflect.Struct, reflect.Map: 863 p.buf.WriteByte('&') 864 p.printValue(a, verb, depth+1) 865 return 866 } 867 } 868 fallthrough 869 case reflect.Chan, reflect.Func, reflect.UnsafePointer: 870 p.fmtPointer(f, verb) 871 default: 872 p.unknownType(f) 873 } 874 } 875 876 // intFromArg gets the argNumth element of a. On return, isInt reports whether the argument has integer type. 877 func intFromArg(a []interface{}, argNum int) (num int, isInt bool, newArgNum int) { 878 newArgNum = argNum 879 if argNum < len(a) { 880 num, isInt = a[argNum].(int) // Almost always OK. 881 if !isInt { 882 // Work harder. 883 switch v := reflect.ValueOf(a[argNum]); v.Kind() { 884 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: 885 n := v.Int() 886 if int64(int(n)) == n { 887 num = int(n) 888 isInt = true 889 } 890 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: 891 n := v.Uint() 892 if int64(n) >= 0 && uint64(int(n)) == n { 893 num = int(n) 894 isInt = true 895 } 896 default: 897 // Already 0, false. 898 } 899 } 900 newArgNum = argNum + 1 901 if tooLarge(num) { 902 num = 0 903 isInt = false 904 } 905 } 906 return 907 } 908 909 // parseArgNumber returns the value of the bracketed number, minus 1 910 // (explicit argument numbers are one-indexed but we want zero-indexed). 911 // The opening bracket is known to be present at format[0]. 912 // The returned values are the index, the number of bytes to consume 913 // up to the closing paren, if present, and whether the number parsed 914 // ok. The bytes to consume will be 1 if no closing paren is present. 915 func parseArgNumber(format string) (index int, wid int, ok bool) { 916 // There must be at least 3 bytes: [n]. 917 if len(format) < 3 { 918 return 0, 1, false 919 } 920 921 // Find closing bracket. 922 for i := 1; i < len(format); i++ { 923 if format[i] == ']' { 924 width, ok, newi := parsenum(format, 1, i) 925 if !ok || newi != i { 926 return 0, i + 1, false 927 } 928 return width - 1, i + 1, true // arg numbers are one-indexed and skip paren. 929 } 930 } 931 return 0, 1, false 932 } 933 934 // argNumber returns the next argument to evaluate, which is either the value of the passed-in 935 // argNum or the value of the bracketed integer that begins format[i:]. It also returns 936 // the new value of i, that is, the index of the next byte of the format to process. 937 func (p *pp) argNumber(argNum int, format string, i int, numArgs int) (newArgNum, newi int, found bool) { 938 if len(format) <= i || format[i] != '[' { 939 return argNum, i, false 940 } 941 p.reordered = true 942 index, wid, ok := parseArgNumber(format[i:]) 943 if ok && 0 <= index && index < numArgs { 944 return index, i + wid, true 945 } 946 p.goodArgNum = false 947 return argNum, i + wid, ok 948 } 949 950 func (p *pp) badArgNum(verb rune) { 951 p.buf.WriteString(percentBangString) 952 p.buf.WriteRune(verb) 953 p.buf.WriteString(badIndexString) 954 } 955 956 func (p *pp) missingArg(verb rune) { 957 p.buf.WriteString(percentBangString) 958 p.buf.WriteRune(verb) 959 p.buf.WriteString(missingString) 960 } 961 962 func (p *pp) doPrintf(format string, a []interface{}) { 963 end := len(format) 964 argNum := 0 // we process one argument per non-trivial format 965 afterIndex := false // previous item in format was an index like [3]. 966 p.reordered = false 967 formatLoop: 968 for i := 0; i < end; { 969 p.goodArgNum = true 970 lasti := i 971 for i < end && format[i] != '%' { 972 i++ 973 } 974 if i > lasti { 975 p.buf.WriteString(format[lasti:i]) 976 } 977 if i >= end { 978 // done processing format string 979 break 980 } 981 982 // Process one verb 983 i++ 984 985 // Do we have flags? 986 p.fmt.clearflags() 987 simpleFormat: 988 for ; i < end; i++ { 989 c := format[i] 990 switch c { 991 case '#': 992 p.fmt.sharp = true 993 case '0': 994 p.fmt.zero = !p.fmt.minus // Only allow zero padding to the left. 995 case '+': 996 p.fmt.plus = true 997 case '-': 998 p.fmt.minus = true 999 p.fmt.zero = false // Do not pad with zeros to the right. 1000 case ' ': 1001 p.fmt.space = true 1002 default: 1003 // Fast path for common case of ascii lower case simple verbs 1004 // without precision or width or argument indices. 1005 if 'a' <= c && c <= 'z' && argNum < len(a) { 1006 if c == 'v' { 1007 // Go syntax 1008 p.fmt.sharpV = p.fmt.sharp 1009 p.fmt.sharp = false 1010 // Struct-field syntax 1011 p.fmt.plusV = p.fmt.plus 1012 p.fmt.plus = false 1013 } 1014 p.printArg(a[argNum], rune(c)) 1015 argNum++ 1016 i++ 1017 continue formatLoop 1018 } 1019 // Format is more complex than simple flags and a verb or is malformed. 1020 break simpleFormat 1021 } 1022 } 1023 1024 // Do we have an explicit argument index? 1025 argNum, i, afterIndex = p.argNumber(argNum, format, i, len(a)) 1026 1027 // Do we have width? 1028 if i < end && format[i] == '*' { 1029 i++ 1030 p.fmt.wid, p.fmt.widPresent, argNum = intFromArg(a, argNum) 1031 1032 if !p.fmt.widPresent { 1033 p.buf.WriteString(badWidthString) 1034 } 1035 1036 // We have a negative width, so take its value and ensure 1037 // that the minus flag is set 1038 if p.fmt.wid < 0 { 1039 p.fmt.wid = -p.fmt.wid 1040 p.fmt.minus = true 1041 p.fmt.zero = false // Do not pad with zeros to the right. 1042 } 1043 afterIndex = false 1044 } else { 1045 p.fmt.wid, p.fmt.widPresent, i = parsenum(format, i, end) 1046 if afterIndex && p.fmt.widPresent { // "%[3]2d" 1047 p.goodArgNum = false 1048 } 1049 } 1050 1051 // Do we have precision? 1052 if i+1 < end && format[i] == '.' { 1053 i++ 1054 if afterIndex { // "%[3].2d" 1055 p.goodArgNum = false 1056 } 1057 argNum, i, afterIndex = p.argNumber(argNum, format, i, len(a)) 1058 if i < end && format[i] == '*' { 1059 i++ 1060 p.fmt.prec, p.fmt.precPresent, argNum = intFromArg(a, argNum) 1061 // Negative precision arguments don't make sense 1062 if p.fmt.prec < 0 { 1063 p.fmt.prec = 0 1064 p.fmt.precPresent = false 1065 } 1066 if !p.fmt.precPresent { 1067 p.buf.WriteString(badPrecString) 1068 } 1069 afterIndex = false 1070 } else { 1071 p.fmt.prec, p.fmt.precPresent, i = parsenum(format, i, end) 1072 if !p.fmt.precPresent { 1073 p.fmt.prec = 0 1074 p.fmt.precPresent = true 1075 } 1076 } 1077 } 1078 1079 if !afterIndex { 1080 argNum, i, afterIndex = p.argNumber(argNum, format, i, len(a)) 1081 } 1082 1083 if i >= end { 1084 p.buf.WriteString(noVerbString) 1085 break 1086 } 1087 1088 verb, size := rune(format[i]), 1 1089 if verb >= utf8.RuneSelf { 1090 verb, size = utf8.DecodeRuneInString(format[i:]) 1091 } 1092 i += size 1093 1094 switch { 1095 case verb == '%': // Percent does not absorb operands and ignores f.wid and f.prec. 1096 p.buf.WriteByte('%') 1097 case !p.goodArgNum: 1098 p.badArgNum(verb) 1099 case argNum >= len(a): // No argument left over to print for the current verb. 1100 p.missingArg(verb) 1101 case verb == 'v': 1102 // Go syntax 1103 p.fmt.sharpV = p.fmt.sharp 1104 p.fmt.sharp = false 1105 // Struct-field syntax 1106 p.fmt.plusV = p.fmt.plus 1107 p.fmt.plus = false 1108 fallthrough 1109 default: 1110 p.printArg(a[argNum], verb) 1111 argNum++ 1112 } 1113 } 1114 1115 // Check for extra arguments unless the call accessed the arguments 1116 // out of order, in which case it's too expensive to detect if they've all 1117 // been used and arguably OK if they're not. 1118 if !p.reordered && argNum < len(a) { 1119 p.fmt.clearflags() 1120 p.buf.WriteString(extraString) 1121 for i, arg := range a[argNum:] { 1122 if i > 0 { 1123 p.buf.WriteString(commaSpaceString) 1124 } 1125 if arg == nil { 1126 p.buf.WriteString(nilAngleString) 1127 } else { 1128 p.buf.WriteString(reflect.TypeOf(arg).String()) 1129 p.buf.WriteByte('=') 1130 p.printArg(arg, 'v') 1131 } 1132 } 1133 p.buf.WriteByte(')') 1134 } 1135 } 1136 1137 func (p *pp) doPrint(a []interface{}) { 1138 prevString := false 1139 for argNum, arg := range a { 1140 isString := arg != nil && reflect.TypeOf(arg).Kind() == reflect.String 1141 // Add a space between two non-string arguments. 1142 if argNum > 0 && !isString && !prevString { 1143 p.buf.WriteByte(' ') 1144 } 1145 p.printArg(arg, 'v') 1146 prevString = isString 1147 } 1148 } 1149 1150 // doPrintln is like doPrint but always adds a space between arguments 1151 // and a newline after the last argument. 1152 func (p *pp) doPrintln(a []interface{}) { 1153 for argNum, arg := range a { 1154 if argNum > 0 { 1155 p.buf.WriteByte(' ') 1156 } 1157 p.printArg(arg, 'v') 1158 } 1159 p.buf.WriteByte('\n') 1160 }