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