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.
18 // Some constants in the form of bytes, to avoid string overhead.
19 // Needlessly fastidious, I suppose.
21 commaSpaceBytes = []byte(", ")
22 nilAngleBytes = []byte("<nil>")
23 nilParenBytes = []byte("(nil)")
24 nilBytes = []byte("nil")
25 mapBytes = []byte("map[")
26 missingBytes = []byte("(MISSING)")
27 panicBytes = []byte("(PANIC=")
28 extraBytes = []byte("%!(EXTRA ")
29 irparenBytes = []byte("i)")
30 bytesBytes = []byte("[]byte{")
31 widthBytes = []byte("%!(BADWIDTH)")
32 precBytes = []byte("%!(BADPREC)")
33 noVerbBytes = []byte("%!(NOVERB)")
36 // State represents the printer state passed to custom formatters.
37 // It provides access to the io.Writer interface plus information about
38 // the flags and options for the operand's format specifier.
39 type State interface {
40 // Write is the function to call to emit formatted output to be printed.
41 Write(b []byte) (ret int, err error)
42 // Width returns the value of the width option and whether it has been set.
43 Width() (wid int, ok bool)
44 // Precision returns the value of the precision option and whether it has been set.
45 Precision() (prec int, ok bool)
47 // Flag returns whether the flag c, a character, has been set.
51 // Formatter is the interface implemented by values with a custom formatter.
52 // The implementation of Format may call Sprintf or Fprintf(f) etc.
53 // to generate its output.
54 type Formatter interface {
55 Format(f State, c rune)
58 // Stringer is implemented by any value that has a String method,
59 // which defines the ``native'' format for that value.
60 // The String method is used to print values passed as an operand
61 // to a %s or %v format or to an unformatted printer such as Print.
62 type Stringer interface {
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
70 type GoStringer interface {
77 erroring bool // printing an error condition
79 // field holds the current item, as an interface{}.
81 // value holds the current item, as a reflect.Value, and will be
82 // the zero Value if the item has not been reflected.
84 runeBuf [utf8.UTFMax]byte
88 // A cache holds a set of reusable objects.
89 // The slice is a stack (LIFO).
90 // If more are needed, the cache creates them by calling new.
94 new func() interface{}
97 func (c *cache) put(x interface{}) {
99 if len(c.saved) < cap(c.saved) {
100 c.saved = append(c.saved, x)
105 func (c *cache) get() interface{} {
113 c.saved = c.saved[0 : n-1]
118 func newCache(f func() interface{}) *cache {
119 return &cache{saved: make([]interface{}, 0, 100), new: f}
122 var ppFree = newCache(func() interface{} { return new(pp) })
124 // Allocate a new pp struct or grab a cached one.
125 func newPrinter() *pp {
126 p := ppFree.get().(*pp)
133 // Save used pp structs in ppFree; avoids an allocation per invocation.
134 func (p *pp) free() {
135 // Don't hold on to pp structs with large buffers.
136 if cap(p.buf.Bytes()) > 1024 {
141 p.value = reflect.Value{}
145 func (p *pp) Width() (wid int, ok bool) { return p.fmt.wid, p.fmt.widPresent }
147 func (p *pp) Precision() (prec int, ok bool) { return p.fmt.prec, p.fmt.precPresent }
149 func (p *pp) Flag(b int) bool {
165 func (p *pp) add(c rune) {
169 // Implement Write so we can call Fprintf on a pp (through State), for
170 // recursive use in custom verbs.
171 func (p *pp) Write(b []byte) (ret int, err error) {
172 return p.buf.Write(b)
175 // These routines end in 'f' and take a format string.
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) {
181 p.doPrintf(format, a)
182 n64, err := p.buf.WriteTo(w)
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...)
193 // Sprintf formats according to a format specifier and returns the resulting string.
194 func Sprintf(format string, a ...interface{}) string {
196 p.doPrintf(format, a)
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...))
208 // These routines do not take a format string
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) {
215 p.doPrint(a, false, false)
216 n64, err := p.buf.WriteTo(w)
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...)
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 {
232 p.doPrint(a, false, false)
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.
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) {
247 p.doPrint(a, true, true)
248 n64, err := p.buf.WriteTo(w)
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...)
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 {
264 p.doPrint(a, true, true)
270 // Get the i'th arg of the struct value.
271 // If the arg 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 {
275 if val.Kind() == reflect.Interface && !val.IsNil() {
281 // Convert ASCII to integer. n is 0 (and got is false) if no number present.
282 func parsenum(s string, start, end int) (num int, isnum bool, newi int) {
286 for newi = start; newi < end && '0' <= s[newi] && s[newi] <= '9'; newi++ {
287 num = num*10 + int(s[newi]-'0')
293 func (p *pp) unknownType(v interface{}) {
295 p.buf.Write(nilAngleBytes)
299 p.buf.WriteString(reflect.TypeOf(v).String())
303 func (p *pp) badVerb(verb rune) {
311 p.buf.WriteString(reflect.TypeOf(p.field).String())
313 p.printField(p.field, 'v', false, false, 0)
314 case p.value.IsValid():
315 p.buf.WriteString(p.value.Type().String())
317 p.printValue(p.value, 'v', false, false, 0)
319 p.buf.Write(nilAngleBytes)
325 func (p *pp) fmtBool(v bool, verb rune) {
334 // fmtC formats a rune for the 'c' format.
335 func (p *pp) fmtC(c int64) {
336 r := rune(c) // Check for overflow.
340 w := utf8.EncodeRune(p.runeBuf[0:utf8.UTFMax], r)
341 p.fmt.pad(p.runeBuf[0:w])
344 func (p *pp) fmtInt64(v int64, verb rune) {
347 p.fmt.integer(v, 2, signed, ldigits)
351 p.fmt.integer(v, 10, signed, ldigits)
353 p.fmt.integer(v, 8, signed, ldigits)
355 if 0 <= v && v <= unicode.MaxRune {
361 p.fmt.integer(v, 16, signed, ldigits)
365 p.fmt.integer(v, 16, signed, udigits)
371 // fmt0x64 formats a uint64 in hexadecimal and prefixes it with 0x or
372 // not, as requested, by temporarily setting the sharp flag.
373 func (p *pp) fmt0x64(v uint64, leading0x bool) {
375 p.fmt.sharp = leading0x
376 p.fmt.integer(int64(v), 16, unsigned, ldigits)
380 // fmtUnicode formats a uint64 in U+1234 form by
381 // temporarily turning on the unicode flag and tweaking the precision.
382 func (p *pp) fmtUnicode(v int64) {
383 precPresent := p.fmt.precPresent
388 // If prec is already set, leave it alone; otherwise 4 is minimum.
390 p.fmt.precPresent = true
392 p.fmt.unicode = true // turn on U+
393 p.fmt.uniQuote = sharp
394 p.fmt.integer(int64(v), 16, unsigned, udigits)
395 p.fmt.unicode = false
396 p.fmt.uniQuote = false
398 p.fmt.precPresent = precPresent
402 func (p *pp) fmtUint64(v uint64, verb rune, goSyntax bool) {
405 p.fmt.integer(int64(v), 2, unsigned, ldigits)
409 p.fmt.integer(int64(v), 10, unsigned, ldigits)
414 p.fmt.integer(int64(v), 10, unsigned, ldigits)
417 p.fmt.integer(int64(v), 8, unsigned, ldigits)
419 if 0 <= v && v <= unicode.MaxRune {
420 p.fmt.fmt_qc(int64(v))
425 p.fmt.integer(int64(v), 16, unsigned, ldigits)
427 p.fmt.integer(int64(v), 16, unsigned, udigits)
429 p.fmtUnicode(int64(v))
435 func (p *pp) fmtFloat32(v float32, verb rune) {
454 func (p *pp) fmtFloat64(v float64, verb rune) {
473 func (p *pp) fmtComplex64(v complex64, verb rune) {
475 case 'e', 'E', 'f', 'F', 'g', 'G':
476 p.fmt.fmt_c64(v, verb)
478 p.fmt.fmt_c64(v, 'g')
484 func (p *pp) fmtComplex128(v complex128, verb rune) {
486 case 'e', 'E', 'f', 'F', 'g', 'G':
487 p.fmt.fmt_c128(v, verb)
489 p.fmt.fmt_c128(v, 'g')
495 func (p *pp) fmtString(v string, verb rune, goSyntax bool) {
516 func (p *pp) fmtBytes(v []byte, verb rune, goSyntax bool, depth int) {
517 if verb == 'v' || verb == 'd' {
519 p.buf.Write(bytesBytes)
523 for i, c := range v {
526 p.buf.Write(commaSpaceBytes)
531 p.printField(c, 'v', p.fmt.plus, goSyntax, depth+1)
555 func (p *pp) fmtPointer(value reflect.Value, verb rune, goSyntax bool) {
557 switch value.Kind() {
558 case reflect.Chan, reflect.Func, reflect.Map, reflect.Ptr, reflect.Slice, reflect.UnsafePointer:
566 p.buf.WriteString(value.Type().String())
570 p.buf.Write(nilBytes)
572 p.fmt0x64(uint64(u), true)
576 p.fmt0x64(uint64(u), !p.fmt.sharp)
581 intBits = reflect.TypeOf(0).Bits()
582 floatBits = reflect.TypeOf(0.0).Bits()
583 complexBits = reflect.TypeOf(1i).Bits()
584 uintptrBits = reflect.TypeOf(uintptr(0)).Bits()
587 func (p *pp) catchPanic(field interface{}, verb rune) {
588 if err := recover(); err != nil {
589 // If it's a nil pointer, just say "<nil>". The likeliest causes are a
590 // Stringer that fails to guard against nil or a nil pointer for a
591 // value receiver, and in either case, "<nil>" is a nice result.
592 if v := reflect.ValueOf(field); v.Kind() == reflect.Ptr && v.IsNil() {
593 p.buf.Write(nilAngleBytes)
596 // Otherwise print a concise panic message. Most of the time the panic
597 // value will print itself nicely.
599 // Nested panics; the recursion in printField cannot succeed.
604 p.buf.Write(panicBytes)
606 p.printField(err, 'v', false, false, 0)
612 func (p *pp) handleMethods(verb rune, plus, goSyntax bool, depth int) (wasString, handled bool) {
616 // Is it a Formatter?
617 if formatter, ok := p.field.(Formatter); ok {
620 defer p.catchPanic(p.field, verb)
621 formatter.Format(p, verb)
624 // Must not touch flags before Formatter looks at them.
629 // If we're doing Go syntax and the field knows how to supply it, take care of it now.
632 if stringer, ok := p.field.(GoStringer); ok {
635 defer p.catchPanic(p.field, verb)
636 // Print the result of GoString unadorned.
637 p.fmtString(stringer.GoString(), 's', false)
641 // If a string is acceptable according to the format, see if
642 // the value satisfies one of the string-valued interfaces.
643 // Println etc. set verb to %v, which is "stringable".
645 case 'v', 's', 'x', 'X', 'q':
646 // Is it an error or Stringer?
647 // The duplication in the bodies is necessary:
648 // setting wasString and handled, and deferring catchPanic,
649 // must happen before calling the method.
650 switch v := p.field.(type) {
654 defer p.catchPanic(p.field, verb)
655 p.printField(v.Error(), verb, plus, false, depth)
661 defer p.catchPanic(p.field, verb)
662 p.printField(v.String(), verb, plus, false, depth)
671 func (p *pp) printField(field interface{}, verb rune, plus, goSyntax bool, depth int) (wasString bool) {
673 if verb == 'T' || verb == 'v' {
674 p.buf.Write(nilAngleBytes)
682 p.value = reflect.Value{}
683 // Special processing considerations.
684 // %T (the value's type) and %p (its address) are special; we always do them first.
687 p.printField(reflect.TypeOf(field).String(), 's', false, false, 0)
690 p.fmtPointer(reflect.ValueOf(field), verb, goSyntax)
694 if wasString, handled := p.handleMethods(verb, plus, goSyntax, depth); handled {
698 // Some types can be done without reflection.
699 switch f := field.(type) {
703 p.fmtFloat32(f, verb)
705 p.fmtFloat64(f, verb)
707 p.fmtComplex64(complex64(f), verb)
709 p.fmtComplex128(f, verb)
711 p.fmtInt64(int64(f), verb)
713 p.fmtInt64(int64(f), verb)
715 p.fmtInt64(int64(f), verb)
717 p.fmtInt64(int64(f), verb)
721 p.fmtUint64(uint64(f), verb, goSyntax)
723 p.fmtUint64(uint64(f), verb, goSyntax)
725 p.fmtUint64(uint64(f), verb, goSyntax)
727 p.fmtUint64(uint64(f), verb, goSyntax)
729 p.fmtUint64(f, verb, goSyntax)
731 p.fmtUint64(uint64(f), verb, goSyntax)
733 p.fmtString(f, verb, goSyntax)
734 wasString = verb == 's' || verb == 'v'
736 p.fmtBytes(f, verb, goSyntax, depth)
737 wasString = verb == 's'
739 // Need to use reflection
740 return p.printReflectValue(reflect.ValueOf(field), verb, plus, goSyntax, depth)
746 // printValue is like printField but starts with a reflect value, not an interface{} value.
747 func (p *pp) printValue(value reflect.Value, verb rune, plus, goSyntax bool, depth int) (wasString bool) {
748 if !value.IsValid() {
749 if verb == 'T' || verb == 'v' {
750 p.buf.Write(nilAngleBytes)
757 // Special processing considerations.
758 // %T (the value's type) and %p (its address) are special; we always do them first.
761 p.printField(value.Type().String(), 's', false, false, 0)
764 p.fmtPointer(value, verb, goSyntax)
768 // Handle values with special methods.
769 // Call always, even when field == nil, because handleMethods clears p.fmt.plus for us.
770 p.field = nil // Make sure it's cleared, for safety.
771 if value.CanInterface() {
772 p.field = value.Interface()
774 if wasString, handled := p.handleMethods(verb, plus, goSyntax, depth); handled {
778 return p.printReflectValue(value, verb, plus, goSyntax, depth)
781 // printReflectValue is the fallback for both printField and printValue.
782 // It uses reflect to print the value.
783 func (p *pp) printReflectValue(value reflect.Value, verb rune, plus, goSyntax bool, depth int) (wasString bool) {
787 switch f := value; f.Kind() {
789 p.fmtBool(f.Bool(), verb)
790 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
791 p.fmtInt64(f.Int(), verb)
792 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
793 p.fmtUint64(uint64(f.Uint()), verb, goSyntax)
794 case reflect.Float32, reflect.Float64:
795 if f.Type().Size() == 4 {
796 p.fmtFloat32(float32(f.Float()), verb)
798 p.fmtFloat64(float64(f.Float()), verb)
800 case reflect.Complex64, reflect.Complex128:
801 if f.Type().Size() == 8 {
802 p.fmtComplex64(complex64(f.Complex()), verb)
804 p.fmtComplex128(complex128(f.Complex()), verb)
807 p.fmtString(f.String(), verb, goSyntax)
810 p.buf.WriteString(f.Type().String())
812 p.buf.WriteString("(nil)")
817 p.buf.Write(mapBytes)
820 for i, key := range keys {
823 p.buf.Write(commaSpaceBytes)
828 p.printValue(key, verb, plus, goSyntax, depth+1)
830 p.printValue(f.MapIndex(key), verb, plus, goSyntax, depth+1)
839 p.buf.WriteString(value.Type().String())
844 for i := 0; i < v.NumField(); i++ {
847 p.buf.Write(commaSpaceBytes)
852 if plus || goSyntax {
853 if f := t.Field(i); f.Name != "" {
854 p.buf.WriteString(f.Name)
858 p.printValue(getField(v, i), verb, plus, goSyntax, depth+1)
861 case reflect.Interface:
863 if !value.IsValid() {
865 p.buf.WriteString(f.Type().String())
866 p.buf.Write(nilParenBytes)
868 p.buf.Write(nilAngleBytes)
871 wasString = p.printValue(value, verb, plus, goSyntax, depth+1)
873 case reflect.Array, reflect.Slice:
874 // Byte slices are special.
875 if f.Type().Elem().Kind() == reflect.Uint8 {
876 // We know it's a slice of bytes, but we also know it does not have static type
877 // []byte, or it would have been caught above. Therefore we cannot convert
878 // it directly in the (slightly) obvious way: f.Interface().([]byte); it doesn't have
879 // that type, and we can't write an expression of the right type and do a
880 // conversion because we don't have a static way to write the right type.
881 // So we build a slice by hand. This is a rare case but it would be nice
882 // if reflection could help a little more.
883 bytes := make([]byte, f.Len())
884 for i := range bytes {
885 bytes[i] = byte(f.Index(i).Uint())
887 p.fmtBytes(bytes, verb, goSyntax, depth)
888 wasString = verb == 's'
892 p.buf.WriteString(value.Type().String())
893 if f.Kind() == reflect.Slice && f.IsNil() {
894 p.buf.WriteString("(nil)")
901 for i := 0; i < f.Len(); i++ {
904 p.buf.Write(commaSpaceBytes)
909 p.printValue(f.Index(i), verb, plus, goSyntax, depth+1)
918 // pointer to array or slice or struct? ok at top level
919 // but not embedded (avoid loops)
920 if v != 0 && depth == 0 {
921 switch a := f.Elem(); a.Kind() {
922 case reflect.Array, reflect.Slice:
924 p.printValue(a, verb, plus, goSyntax, depth+1)
928 p.printValue(a, verb, plus, goSyntax, depth+1)
934 p.buf.WriteString(value.Type().String())
938 p.buf.Write(nilBytes)
940 p.fmt0x64(uint64(v), true)
946 p.buf.Write(nilAngleBytes)
949 p.fmt0x64(uint64(v), true)
950 case reflect.Chan, reflect.Func, reflect.UnsafePointer:
951 p.fmtPointer(value, verb, goSyntax)
959 // intFromArg gets the fieldnumth element of a. On return, isInt reports whether the argument has type int.
960 func intFromArg(a []interface{}, end, i, fieldnum int) (num int, isInt bool, newi, newfieldnum int) {
961 newi, newfieldnum = end, fieldnum
962 if i < end && fieldnum < len(a) {
963 num, isInt = a[fieldnum].(int)
964 newi, newfieldnum = i+1, fieldnum+1
969 func (p *pp) doPrintf(format string, a []interface{}) {
971 fieldnum := 0 // we process one field per non-trivial format
972 for i := 0; i < end; {
974 for i < end && format[i] != '%' {
978 p.buf.WriteString(format[lasti:i])
981 // done processing format string
1006 // do we have width?
1007 if i < end && format[i] == '*' {
1008 p.fmt.wid, p.fmt.widPresent, i, fieldnum = intFromArg(a, end, i, fieldnum)
1009 if !p.fmt.widPresent {
1010 p.buf.Write(widthBytes)
1013 p.fmt.wid, p.fmt.widPresent, i = parsenum(format, i, end)
1015 // do we have precision?
1016 if i < end && format[i] == '.' {
1017 if format[i+1] == '*' {
1018 p.fmt.prec, p.fmt.precPresent, i, fieldnum = intFromArg(a, end, i+1, fieldnum)
1019 if !p.fmt.precPresent {
1020 p.buf.Write(precBytes)
1023 p.fmt.prec, p.fmt.precPresent, i = parsenum(format, i+1, end)
1024 if !p.fmt.precPresent {
1026 p.fmt.precPresent = true
1031 p.buf.Write(noVerbBytes)
1034 c, w := utf8.DecodeRuneInString(format[i:])
1036 // percent is special - absorbs no operand
1038 p.buf.WriteByte('%') // We ignore width and prec.
1041 if fieldnum >= len(a) { // out of operands
1042 p.buf.WriteByte('%')
1044 p.buf.Write(missingBytes)
1047 field := a[fieldnum]
1050 goSyntax := c == 'v' && p.fmt.sharp
1051 plus := c == 'v' && p.fmt.plus
1052 p.printField(field, c, plus, goSyntax, 0)
1055 if fieldnum < len(a) {
1056 p.buf.Write(extraBytes)
1057 for ; fieldnum < len(a); fieldnum++ {
1058 field := a[fieldnum]
1060 p.buf.WriteString(reflect.TypeOf(field).String())
1061 p.buf.WriteByte('=')
1063 p.printField(field, 'v', false, false, 0)
1064 if fieldnum+1 < len(a) {
1065 p.buf.Write(commaSpaceBytes)
1068 p.buf.WriteByte(')')
1072 func (p *pp) doPrint(a []interface{}, addspace, addnewline bool) {
1074 for fieldnum := 0; fieldnum < len(a); fieldnum++ {
1076 // always add spaces if we're doing println
1077 field := a[fieldnum]
1079 isString := field != nil && reflect.TypeOf(field).Kind() == reflect.String
1080 if addspace || !isString && !prevString {
1081 p.buf.WriteByte(' ')
1084 prevString = p.printField(field, 'v', false, false, 0)
1087 p.buf.WriteByte('\n')