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