Source file src/pkg/fmt/print.go
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 "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. 18 var ( 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 widthBytes = []byte("%!(BADWIDTH)") 30 precBytes = []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. 37 type 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. 52 type 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. 60 type 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. 68 type GoStringer interface { 69 GoString() string 70 } 71 72 // Use simple []byte instead of bytes.Buffer to avoid large dependency. 73 type buffer []byte 74 75 func (b *buffer) Write(p []byte) (n int, err error) { 76 *b = append(*b, p...) 77 return len(p), nil 78 } 79 80 func (b *buffer) WriteString(s string) (n int, err error) { 81 *b = append(*b, s...) 82 return len(s), nil 83 } 84 85 func (b *buffer) WriteByte(c byte) error { 86 *b = append(*b, c) 87 return nil 88 } 89 90 func (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 106 type 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. 123 type cache struct { 124 mu sync.Mutex 125 saved []interface{} 126 new func() interface{} 127 } 128 129 func (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 137 func (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 150 func newCache(f func() interface{}) *cache { 151 return &cache{saved: make([]interface{}, 0, 100), new: f} 152 } 153 154 var ppFree = newCache(func() interface{} { return new(pp) }) 155 156 // Allocate a new pp struct or grab a cached one. 157 func 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 // Save used pp structs in ppFree; avoids an allocation per invocation. 166 func (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 177 func (p *pp) Width() (wid int, ok bool) { return p.fmt.wid, p.fmt.widPresent } 178 179 func (p *pp) Precision() (prec int, ok bool) { return p.fmt.prec, p.fmt.precPresent } 180 181 func (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 197 func (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. 203 func (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. 211 func 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. 221 func 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. 226 func 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. 236 func 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. 245 func 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. 256 func 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. 262 func 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. 277 func 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. 288 func 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. 294 func 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 // Get 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. 305 func 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 // Convert ASCII to integer. n is 0 (and got is false) if no number present. 314 func 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 325 func (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 335 func (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 357 func (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. 367 func (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 376 func (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. 405 func (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. 414 func (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 434 func (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 467 func (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 486 func (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 505 func (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 516 func (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 527 func (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 548 func (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 s := string(v) 573 switch verb { 574 case 's': 575 p.fmt.fmt_s(s) 576 case 'x': 577 p.fmt.fmt_sx(s, ldigits) 578 case 'X': 579 p.fmt.fmt_sx(s, udigits) 580 case 'q': 581 p.fmt.fmt_q(s) 582 default: 583 p.badVerb(verb) 584 } 585 } 586 587 func (p *pp) fmtPointer(value reflect.Value, verb rune, goSyntax bool) { 588 switch verb { 589 case 'p', 'v', 'b', 'd', 'o', 'x', 'X': 590 // ok 591 default: 592 p.badVerb(verb) 593 return 594 } 595 596 var u uintptr 597 switch value.Kind() { 598 case reflect.Chan, reflect.Func, reflect.Map, reflect.Ptr, reflect.Slice, reflect.UnsafePointer: 599 u = value.Pointer() 600 default: 601 p.badVerb(verb) 602 return 603 } 604 605 if goSyntax { 606 p.add('(') 607 p.buf.WriteString(value.Type().String()) 608 p.add(')') 609 p.add('(') 610 if u == 0 { 611 p.buf.Write(nilBytes) 612 } else { 613 p.fmt0x64(uint64(u), true) 614 } 615 p.add(')') 616 } else if verb == 'v' && u == 0 { 617 p.buf.Write(nilAngleBytes) 618 } else { 619 p.fmt0x64(uint64(u), !p.fmt.sharp) 620 } 621 } 622 623 var ( 624 intBits = reflect.TypeOf(0).Bits() 625 floatBits = reflect.TypeOf(0.0).Bits() 626 complexBits = reflect.TypeOf(1i).Bits() 627 uintptrBits = reflect.TypeOf(uintptr(0)).Bits() 628 ) 629 630 func (p *pp) catchPanic(field interface{}, verb rune) { 631 if err := recover(); err != nil { 632 // If it's a nil pointer, just say "<nil>". The likeliest causes are a 633 // Stringer that fails to guard against nil or a nil pointer for a 634 // value receiver, and in either case, "<nil>" is a nice result. 635 if v := reflect.ValueOf(field); v.Kind() == reflect.Ptr && v.IsNil() { 636 p.buf.Write(nilAngleBytes) 637 return 638 } 639 // Otherwise print a concise panic message. Most of the time the panic 640 // value will print itself nicely. 641 if p.panicking { 642 // Nested panics; the recursion in printField cannot succeed. 643 panic(err) 644 } 645 p.buf.WriteByte('%') 646 p.add(verb) 647 p.buf.Write(panicBytes) 648 p.panicking = true 649 p.printField(err, 'v', false, false, 0) 650 p.panicking = false 651 p.buf.WriteByte(')') 652 } 653 } 654 655 func (p *pp) handleMethods(verb rune, plus, goSyntax bool, depth int) (wasString, handled bool) { 656 if p.erroring { 657 return 658 } 659 // Is it a Formatter? 660 if formatter, ok := p.field.(Formatter); ok { 661 handled = true 662 wasString = false 663 defer p.catchPanic(p.field, verb) 664 formatter.Format(p, verb) 665 return 666 } 667 // Must not touch flags before Formatter looks at them. 668 if plus { 669 p.fmt.plus = false 670 } 671 672 // If we're doing Go syntax and the field knows how to supply it, take care of it now. 673 if goSyntax { 674 p.fmt.sharp = false 675 if stringer, ok := p.field.(GoStringer); ok { 676 wasString = false 677 handled = true 678 defer p.catchPanic(p.field, verb) 679 // Print the result of GoString unadorned. 680 p.fmtString(stringer.GoString(), 's', false) 681 return 682 } 683 } else { 684 // If a string is acceptable according to the format, see if 685 // the value satisfies one of the string-valued interfaces. 686 // Println etc. set verb to %v, which is "stringable". 687 switch verb { 688 case 'v', 's', 'x', 'X', 'q': 689 // Is it an error or Stringer? 690 // The duplication in the bodies is necessary: 691 // setting wasString and handled, and deferring catchPanic, 692 // must happen before calling the method. 693 switch v := p.field.(type) { 694 case error: 695 wasString = false 696 handled = true 697 defer p.catchPanic(p.field, verb) 698 p.printField(v.Error(), verb, plus, false, depth) 699 return 700 701 case Stringer: 702 wasString = false 703 handled = true 704 defer p.catchPanic(p.field, verb) 705 p.printField(v.String(), verb, plus, false, depth) 706 return 707 } 708 } 709 } 710 handled = false 711 return 712 } 713 714 func (p *pp) printField(field interface{}, verb rune, plus, goSyntax bool, depth int) (wasString bool) { 715 if field == nil { 716 if verb == 'T' || verb == 'v' { 717 p.buf.Write(nilAngleBytes) 718 } else { 719 p.badVerb(verb) 720 } 721 return false 722 } 723 724 p.field = field 725 p.value = reflect.Value{} 726 // Special processing considerations. 727 // %T (the value's type) and %p (its address) are special; we always do them first. 728 switch verb { 729 case 'T': 730 p.printField(reflect.TypeOf(field).String(), 's', false, false, 0) 731 return false 732 case 'p': 733 p.fmtPointer(reflect.ValueOf(field), verb, goSyntax) 734 return false 735 } 736 737 if wasString, handled := p.handleMethods(verb, plus, goSyntax, depth); handled { 738 return wasString 739 } 740 741 // Some types can be done without reflection. 742 switch f := field.(type) { 743 case bool: 744 p.fmtBool(f, verb) 745 case float32: 746 p.fmtFloat32(f, verb) 747 case float64: 748 p.fmtFloat64(f, verb) 749 case complex64: 750 p.fmtComplex64(complex64(f), verb) 751 case complex128: 752 p.fmtComplex128(f, verb) 753 case int: 754 p.fmtInt64(int64(f), verb) 755 case int8: 756 p.fmtInt64(int64(f), verb) 757 case int16: 758 p.fmtInt64(int64(f), verb) 759 case int32: 760 p.fmtInt64(int64(f), verb) 761 case int64: 762 p.fmtInt64(f, verb) 763 case uint: 764 p.fmtUint64(uint64(f), verb, goSyntax) 765 case uint8: 766 p.fmtUint64(uint64(f), verb, goSyntax) 767 case uint16: 768 p.fmtUint64(uint64(f), verb, goSyntax) 769 case uint32: 770 p.fmtUint64(uint64(f), verb, goSyntax) 771 case uint64: 772 p.fmtUint64(f, verb, goSyntax) 773 case uintptr: 774 p.fmtUint64(uint64(f), verb, goSyntax) 775 case string: 776 p.fmtString(f, verb, goSyntax) 777 wasString = verb == 's' || verb == 'v' 778 case []byte: 779 p.fmtBytes(f, verb, goSyntax, depth) 780 wasString = verb == 's' 781 default: 782 // Need to use reflection 783 return p.printReflectValue(reflect.ValueOf(field), verb, plus, goSyntax, depth) 784 } 785 p.field = nil 786 return 787 } 788 789 // printValue is like printField but starts with a reflect value, not an interface{} value. 790 func (p *pp) printValue(value reflect.Value, verb rune, plus, goSyntax bool, depth int) (wasString bool) { 791 if !value.IsValid() { 792 if verb == 'T' || verb == 'v' { 793 p.buf.Write(nilAngleBytes) 794 } else { 795 p.badVerb(verb) 796 } 797 return false 798 } 799 800 // Special processing considerations. 801 // %T (the value's type) and %p (its address) are special; we always do them first. 802 switch verb { 803 case 'T': 804 p.printField(value.Type().String(), 's', false, false, 0) 805 return false 806 case 'p': 807 p.fmtPointer(value, verb, goSyntax) 808 return false 809 } 810 811 // Handle values with special methods. 812 // Call always, even when field == nil, because handleMethods clears p.fmt.plus for us. 813 p.field = nil // Make sure it's cleared, for safety. 814 if value.CanInterface() { 815 p.field = value.Interface() 816 } 817 if wasString, handled := p.handleMethods(verb, plus, goSyntax, depth); handled { 818 return wasString 819 } 820 821 return p.printReflectValue(value, verb, plus, goSyntax, depth) 822 } 823 824 // printReflectValue is the fallback for both printField and printValue. 825 // It uses reflect to print the value. 826 func (p *pp) printReflectValue(value reflect.Value, verb rune, plus, goSyntax bool, depth int) (wasString bool) { 827 oldValue := p.value 828 p.value = value 829 BigSwitch: 830 switch f := value; f.Kind() { 831 case reflect.Bool: 832 p.fmtBool(f.Bool(), verb) 833 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: 834 p.fmtInt64(f.Int(), verb) 835 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: 836 p.fmtUint64(uint64(f.Uint()), verb, goSyntax) 837 case reflect.Float32, reflect.Float64: 838 if f.Type().Size() == 4 { 839 p.fmtFloat32(float32(f.Float()), verb) 840 } else { 841 p.fmtFloat64(float64(f.Float()), verb) 842 } 843 case reflect.Complex64, reflect.Complex128: 844 if f.Type().Size() == 8 { 845 p.fmtComplex64(complex64(f.Complex()), verb) 846 } else { 847 p.fmtComplex128(complex128(f.Complex()), verb) 848 } 849 case reflect.String: 850 p.fmtString(f.String(), verb, goSyntax) 851 case reflect.Map: 852 if goSyntax { 853 p.buf.WriteString(f.Type().String()) 854 if f.IsNil() { 855 p.buf.WriteString("(nil)") 856 break 857 } 858 p.buf.WriteByte('{') 859 } else { 860 p.buf.Write(mapBytes) 861 } 862 keys := f.MapKeys() 863 for i, key := range keys { 864 if i > 0 { 865 if goSyntax { 866 p.buf.Write(commaSpaceBytes) 867 } else { 868 p.buf.WriteByte(' ') 869 } 870 } 871 p.printValue(key, verb, plus, goSyntax, depth+1) 872 p.buf.WriteByte(':') 873 p.printValue(f.MapIndex(key), verb, plus, goSyntax, depth+1) 874 } 875 if goSyntax { 876 p.buf.WriteByte('}') 877 } else { 878 p.buf.WriteByte(']') 879 } 880 case reflect.Struct: 881 if goSyntax { 882 p.buf.WriteString(value.Type().String()) 883 } 884 p.add('{') 885 v := f 886 t := v.Type() 887 for i := 0; i < v.NumField(); i++ { 888 if i > 0 { 889 if goSyntax { 890 p.buf.Write(commaSpaceBytes) 891 } else { 892 p.buf.WriteByte(' ') 893 } 894 } 895 if plus || goSyntax { 896 if f := t.Field(i); f.Name != "" { 897 p.buf.WriteString(f.Name) 898 p.buf.WriteByte(':') 899 } 900 } 901 p.printValue(getField(v, i), verb, plus, goSyntax, depth+1) 902 } 903 p.buf.WriteByte('}') 904 case reflect.Interface: 905 value := f.Elem() 906 if !value.IsValid() { 907 if goSyntax { 908 p.buf.WriteString(f.Type().String()) 909 p.buf.Write(nilParenBytes) 910 } else { 911 p.buf.Write(nilAngleBytes) 912 } 913 } else { 914 wasString = p.printValue(value, verb, plus, goSyntax, depth+1) 915 } 916 case reflect.Array, reflect.Slice: 917 // Byte slices are special. 918 if f.Type().Elem().Kind() == reflect.Uint8 { 919 // We know it's a slice of bytes, but we also know it does not have static type 920 // []byte, or it would have been caught above. Therefore we cannot convert 921 // it directly in the (slightly) obvious way: f.Interface().([]byte); it doesn't have 922 // that type, and we can't write an expression of the right type and do a 923 // conversion because we don't have a static way to write the right type. 924 // So we build a slice by hand. This is a rare case but it would be nice 925 // if reflection could help a little more. 926 bytes := make([]byte, f.Len()) 927 for i := range bytes { 928 bytes[i] = byte(f.Index(i).Uint()) 929 } 930 p.fmtBytes(bytes, verb, goSyntax, depth) 931 wasString = verb == 's' 932 break 933 } 934 if goSyntax { 935 p.buf.WriteString(value.Type().String()) 936 if f.Kind() == reflect.Slice && f.IsNil() { 937 p.buf.WriteString("(nil)") 938 break 939 } 940 p.buf.WriteByte('{') 941 } else { 942 p.buf.WriteByte('[') 943 } 944 for i := 0; i < f.Len(); i++ { 945 if i > 0 { 946 if goSyntax { 947 p.buf.Write(commaSpaceBytes) 948 } else { 949 p.buf.WriteByte(' ') 950 } 951 } 952 p.printValue(f.Index(i), verb, plus, goSyntax, depth+1) 953 } 954 if goSyntax { 955 p.buf.WriteByte('}') 956 } else { 957 p.buf.WriteByte(']') 958 } 959 case reflect.Ptr: 960 v := f.Pointer() 961 // pointer to array or slice or struct? ok at top level 962 // but not embedded (avoid loops) 963 if v != 0 && depth == 0 { 964 switch a := f.Elem(); a.Kind() { 965 case reflect.Array, reflect.Slice: 966 p.buf.WriteByte('&') 967 p.printValue(a, verb, plus, goSyntax, depth+1) 968 break BigSwitch 969 case reflect.Struct: 970 p.buf.WriteByte('&') 971 p.printValue(a, verb, plus, goSyntax, depth+1) 972 break BigSwitch 973 } 974 } 975 fallthrough 976 case reflect.Chan, reflect.Func, reflect.UnsafePointer: 977 p.fmtPointer(value, verb, goSyntax) 978 default: 979 p.unknownType(f) 980 } 981 p.value = oldValue 982 return wasString 983 } 984 985 // intFromArg gets the fieldnumth element of a. On return, isInt reports whether the argument has type int. 986 func intFromArg(a []interface{}, end, i, fieldnum int) (num int, isInt bool, newi, newfieldnum int) { 987 newi, newfieldnum = end, fieldnum 988 if i < end && fieldnum < len(a) { 989 num, isInt = a[fieldnum].(int) 990 newi, newfieldnum = i+1, fieldnum+1 991 } 992 return 993 } 994 995 func (p *pp) doPrintf(format string, a []interface{}) { 996 end := len(format) 997 fieldnum := 0 // we process one field per non-trivial format 998 for i := 0; i < end; { 999 lasti := i 1000 for i < end && format[i] != '%' { 1001 i++ 1002 } 1003 if i > lasti { 1004 p.buf.WriteString(format[lasti:i]) 1005 } 1006 if i >= end { 1007 // done processing format string 1008 break 1009 } 1010 1011 // Process one verb 1012 i++ 1013 // flags and widths 1014 p.fmt.clearflags() 1015 F: 1016 for ; i < end; i++ { 1017 switch format[i] { 1018 case '#': 1019 p.fmt.sharp = true 1020 case '0': 1021 p.fmt.zero = true 1022 case '+': 1023 p.fmt.plus = true 1024 case '-': 1025 p.fmt.minus = true 1026 case ' ': 1027 p.fmt.space = true 1028 default: 1029 break F 1030 } 1031 } 1032 // do we have width? 1033 if i < end && format[i] == '*' { 1034 p.fmt.wid, p.fmt.widPresent, i, fieldnum = intFromArg(a, end, i, fieldnum) 1035 if !p.fmt.widPresent { 1036 p.buf.Write(widthBytes) 1037 } 1038 } else { 1039 p.fmt.wid, p.fmt.widPresent, i = parsenum(format, i, end) 1040 } 1041 // do we have precision? 1042 if i < end && format[i] == '.' { 1043 if format[i+1] == '*' { 1044 p.fmt.prec, p.fmt.precPresent, i, fieldnum = intFromArg(a, end, i+1, fieldnum) 1045 if !p.fmt.precPresent { 1046 p.buf.Write(precBytes) 1047 } 1048 } else { 1049 p.fmt.prec, p.fmt.precPresent, i = parsenum(format, i+1, end) 1050 if !p.fmt.precPresent { 1051 p.fmt.prec = 0 1052 p.fmt.precPresent = true 1053 } 1054 } 1055 } 1056 if i >= end { 1057 p.buf.Write(noVerbBytes) 1058 continue 1059 } 1060 c, w := utf8.DecodeRuneInString(format[i:]) 1061 i += w 1062 // percent is special - absorbs no operand 1063 if c == '%' { 1064 p.buf.WriteByte('%') // We ignore width and prec. 1065 continue 1066 } 1067 if fieldnum >= len(a) { // out of operands 1068 p.buf.WriteByte('%') 1069 p.add(c) 1070 p.buf.Write(missingBytes) 1071 continue 1072 } 1073 field := a[fieldnum] 1074 fieldnum++ 1075 1076 goSyntax := c == 'v' && p.fmt.sharp 1077 plus := c == 'v' && p.fmt.plus 1078 p.printField(field, c, plus, goSyntax, 0) 1079 } 1080 1081 if fieldnum < len(a) { 1082 p.buf.Write(extraBytes) 1083 for ; fieldnum < len(a); fieldnum++ { 1084 field := a[fieldnum] 1085 if field != nil { 1086 p.buf.WriteString(reflect.TypeOf(field).String()) 1087 p.buf.WriteByte('=') 1088 } 1089 p.printField(field, 'v', false, false, 0) 1090 if fieldnum+1 < len(a) { 1091 p.buf.Write(commaSpaceBytes) 1092 } 1093 } 1094 p.buf.WriteByte(')') 1095 } 1096 } 1097 1098 func (p *pp) doPrint(a []interface{}, addspace, addnewline bool) { 1099 prevString := false 1100 for fieldnum := 0; fieldnum < len(a); fieldnum++ { 1101 p.fmt.clearflags() 1102 // always add spaces if we're doing println 1103 field := a[fieldnum] 1104 if fieldnum > 0 { 1105 isString := field != nil && reflect.TypeOf(field).Kind() == reflect.String 1106 if addspace || !isString && !prevString { 1107 p.buf.WriteByte(' ') 1108 } 1109 } 1110 prevString = p.printField(field, 'v', false, false, 0) 1111 } 1112 if addnewline { 1113 p.buf.WriteByte('\n') 1114 } 1115 }