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 {
78 // field holds the current item, as an interface{}.
80 // value holds the current item, as a reflect.Value, and will be
81 // the zero Value if the item has not been reflected.
83 runeBuf [utf8.UTFMax]byte
87 // A cache holds a set of reusable objects.
88 // The slice is a stack (LIFO).
89 // If more are needed, the cache creates them by calling new.
93 new func() interface{}
96 func (c *cache) put(x interface{}) {
98 if len(c.saved) < cap(c.saved) {
99 c.saved = append(c.saved, x)
104 func (c *cache) get() interface{} {
112 c.saved = c.saved[0 : n-1]
117 func newCache(f func() interface{}) *cache {
118 return &cache{saved: make([]interface{}, 0, 100), new: f}
121 var ppFree = newCache(func() interface{} { return new(pp) })
123 // Allocate a new pp struct or grab a cached one.
124 func newPrinter() *pp {
125 p := ppFree.get().(*pp)
131 // Save used pp structs in ppFree; avoids an allocation per invocation.
132 func (p *pp) free() {
133 // Don't hold on to pp structs with large buffers.
134 if cap(p.buf.Bytes()) > 1024 {
139 p.value = reflect.Value{}
143 func (p *pp) Width() (wid int, ok bool) { return p.fmt.wid, p.fmt.widPresent }
145 func (p *pp) Precision() (prec int, ok bool) { return p.fmt.prec, p.fmt.precPresent }
147 func (p *pp) Flag(b int) bool {
163 func (p *pp) add(c rune) {
167 // Implement Write so we can call Fprintf on a pp (through State), for
168 // recursive use in custom verbs.
169 func (p *pp) Write(b []byte) (ret int, err error) {
170 return p.buf.Write(b)
173 // These routines end in 'f' and take a format string.
175 // Fprintf formats according to a format specifier and writes to w.
176 // It returns the number of bytes written and any write error encountered.
177 func Fprintf(w io.Writer, format string, a ...interface{}) (n int, err error) {
179 p.doPrintf(format, a)
180 n64, err := p.buf.WriteTo(w)
185 // Printf formats according to a format specifier and writes to standard output.
186 // It returns the number of bytes written and any write error encountered.
187 func Printf(format string, a ...interface{}) (n int, err error) {
188 return Fprintf(os.Stdout, format, a...)
191 // Sprintf formats according to a format specifier and returns the resulting string.
192 func Sprintf(format string, a ...interface{}) string {
194 p.doPrintf(format, a)
200 // Errorf formats according to a format specifier and returns the string
201 // as a value that satisfies error.
202 func Errorf(format string, a ...interface{}) error {
203 return errors.New(Sprintf(format, a...))
206 // These routines do not take a format string
208 // Fprint formats using the default formats for its operands and writes to w.
209 // Spaces are added between operands when neither is a string.
210 // It returns the number of bytes written and any write error encountered.
211 func Fprint(w io.Writer, a ...interface{}) (n int, err error) {
213 p.doPrint(a, false, false)
214 n64, err := p.buf.WriteTo(w)
219 // Print formats using the default formats for its operands and writes to standard output.
220 // Spaces are added between operands when neither is a string.
221 // It returns the number of bytes written and any write error encountered.
222 func Print(a ...interface{}) (n int, err error) {
223 return Fprint(os.Stdout, a...)
226 // Sprint formats using the default formats for its operands and returns the resulting string.
227 // Spaces are added between operands when neither is a string.
228 func Sprint(a ...interface{}) string {
230 p.doPrint(a, false, false)
236 // These routines end in 'ln', do not take a format string,
237 // always add spaces between operands, and add a newline
238 // after the last operand.
240 // Fprintln formats using the default formats for its operands and writes to w.
241 // Spaces are always added between operands and a newline is appended.
242 // It returns the number of bytes written and any write error encountered.
243 func Fprintln(w io.Writer, a ...interface{}) (n int, err error) {
245 p.doPrint(a, true, true)
246 n64, err := p.buf.WriteTo(w)
251 // Println formats using the default formats for its operands and writes to standard output.
252 // Spaces are always added between operands and a newline is appended.
253 // It returns the number of bytes written and any write error encountered.
254 func Println(a ...interface{}) (n int, err error) {
255 return Fprintln(os.Stdout, a...)
258 // Sprintln formats using the default formats for its operands and returns the resulting string.
259 // Spaces are always added between operands and a newline is appended.
260 func Sprintln(a ...interface{}) string {
262 p.doPrint(a, true, true)
268 // Get the i'th arg of the struct value.
269 // If the arg itself is an interface, return a value for
270 // the thing inside the interface, not the interface itself.
271 func getField(v reflect.Value, i int) reflect.Value {
273 if val.Kind() == reflect.Interface && !val.IsNil() {
279 // Convert ASCII to integer. n is 0 (and got is false) if no number present.
280 func parsenum(s string, start, end int) (num int, isnum bool, newi int) {
284 for newi = start; newi < end && '0' <= s[newi] && s[newi] <= '9'; newi++ {
285 num = num*10 + int(s[newi]-'0')
291 func (p *pp) unknownType(v interface{}) {
293 p.buf.Write(nilAngleBytes)
297 p.buf.WriteString(reflect.TypeOf(v).String())
301 func (p *pp) badVerb(verb rune) {
308 p.buf.WriteString(reflect.TypeOf(p.field).String())
310 p.printField(p.field, 'v', false, false, 0)
311 case p.value.IsValid():
312 p.buf.WriteString(p.value.Type().String())
314 p.printValue(p.value, 'v', false, false, 0)
316 p.buf.Write(nilAngleBytes)
321 func (p *pp) fmtBool(v bool, verb rune) {
330 // fmtC formats a rune for the 'c' format.
331 func (p *pp) fmtC(c int64) {
332 r := rune(c) // Check for overflow.
336 w := utf8.EncodeRune(p.runeBuf[0:utf8.UTFMax], r)
337 p.fmt.pad(p.runeBuf[0:w])
340 func (p *pp) fmtInt64(v int64, verb rune) {
343 p.fmt.integer(v, 2, signed, ldigits)
347 p.fmt.integer(v, 10, signed, ldigits)
349 p.fmt.integer(v, 8, signed, ldigits)
351 if 0 <= v && v <= unicode.MaxRune {
357 p.fmt.integer(v, 16, signed, ldigits)
361 p.fmt.integer(v, 16, signed, udigits)
367 // fmt0x64 formats a uint64 in hexadecimal and prefixes it with 0x or
368 // not, as requested, by temporarily setting the sharp flag.
369 func (p *pp) fmt0x64(v uint64, leading0x bool) {
371 p.fmt.sharp = leading0x
372 p.fmt.integer(int64(v), 16, unsigned, ldigits)
376 // fmtUnicode formats a uint64 in U+1234 form by
377 // temporarily turning on the unicode flag and tweaking the precision.
378 func (p *pp) fmtUnicode(v int64) {
379 precPresent := p.fmt.precPresent
384 // If prec is already set, leave it alone; otherwise 4 is minimum.
386 p.fmt.precPresent = true
388 p.fmt.unicode = true // turn on U+
389 p.fmt.uniQuote = sharp
390 p.fmt.integer(int64(v), 16, unsigned, udigits)
391 p.fmt.unicode = false
392 p.fmt.uniQuote = false
394 p.fmt.precPresent = precPresent
398 func (p *pp) fmtUint64(v uint64, verb rune, goSyntax bool) {
401 p.fmt.integer(int64(v), 2, unsigned, ldigits)
405 p.fmt.integer(int64(v), 10, unsigned, ldigits)
410 p.fmt.integer(int64(v), 10, unsigned, ldigits)
413 p.fmt.integer(int64(v), 8, unsigned, ldigits)
415 if 0 <= v && v <= unicode.MaxRune {
416 p.fmt.fmt_qc(int64(v))
421 p.fmt.integer(int64(v), 16, unsigned, ldigits)
423 p.fmt.integer(int64(v), 16, unsigned, udigits)
425 p.fmtUnicode(int64(v))
431 func (p *pp) fmtFloat32(v float32, verb rune) {
450 func (p *pp) fmtFloat64(v float64, verb rune) {
469 func (p *pp) fmtComplex64(v complex64, verb rune) {
471 case 'e', 'E', 'f', 'F', 'g', 'G':
472 p.fmt.fmt_c64(v, verb)
474 p.fmt.fmt_c64(v, 'g')
480 func (p *pp) fmtComplex128(v complex128, verb rune) {
482 case 'e', 'E', 'f', 'F', 'g', 'G':
483 p.fmt.fmt_c128(v, verb)
485 p.fmt.fmt_c128(v, 'g')
491 func (p *pp) fmtString(v string, verb rune, goSyntax bool) {
512 func (p *pp) fmtBytes(v []byte, verb rune, goSyntax bool, depth int) {
513 if verb == 'v' || verb == 'd' {
515 p.buf.Write(bytesBytes)
519 for i, c := range v {
522 p.buf.Write(commaSpaceBytes)
527 p.printField(c, 'v', p.fmt.plus, goSyntax, depth+1)
551 func (p *pp) fmtPointer(value reflect.Value, verb rune, goSyntax bool) {
553 switch value.Kind() {
554 case reflect.Chan, reflect.Func, reflect.Map, reflect.Ptr, reflect.Slice, reflect.UnsafePointer:
562 p.buf.WriteString(value.Type().String())
566 p.buf.Write(nilBytes)
568 p.fmt0x64(uint64(u), true)
572 p.fmt0x64(uint64(u), !p.fmt.sharp)
577 intBits = reflect.TypeOf(0).Bits()
578 floatBits = reflect.TypeOf(0.0).Bits()
579 complexBits = reflect.TypeOf(1i).Bits()
580 uintptrBits = reflect.TypeOf(uintptr(0)).Bits()
583 func (p *pp) catchPanic(field interface{}, verb rune) {
584 if err := recover(); err != nil {
585 // If it's a nil pointer, just say "<nil>". The likeliest causes are a
586 // Stringer that fails to guard against nil or a nil pointer for a
587 // value receiver, and in either case, "<nil>" is a nice result.
588 if v := reflect.ValueOf(field); v.Kind() == reflect.Ptr && v.IsNil() {
589 p.buf.Write(nilAngleBytes)
592 // Otherwise print a concise panic message. Most of the time the panic
593 // value will print itself nicely.
595 // Nested panics; the recursion in printField cannot succeed.
600 p.buf.Write(panicBytes)
602 p.printField(err, 'v', false, false, 0)
608 func (p *pp) handleMethods(verb rune, plus, goSyntax bool, depth int) (wasString, handled bool) {
609 // Is it a Formatter?
610 if formatter, ok := p.field.(Formatter); ok {
613 defer p.catchPanic(p.field, verb)
614 formatter.Format(p, verb)
617 // Must not touch flags before Formatter looks at them.
622 // If we're doing Go syntax and the field knows how to supply it, take care of it now.
625 if stringer, ok := p.field.(GoStringer); ok {
628 defer p.catchPanic(p.field, verb)
629 // Print the result of GoString unadorned.
630 p.fmtString(stringer.GoString(), 's', false)
634 // Is it an error or Stringer?
635 // The duplication in the bodies is necessary:
636 // setting wasString and handled and deferring catchPanic
637 // must happen before calling the method.
638 switch v := p.field.(type) {
642 defer p.catchPanic(p.field, verb)
643 p.printField(v.Error(), verb, plus, false, depth)
649 defer p.catchPanic(p.field, verb)
650 p.printField(v.String(), verb, plus, false, depth)
658 func (p *pp) printField(field interface{}, verb rune, plus, goSyntax bool, depth int) (wasString bool) {
660 if verb == 'T' || verb == 'v' {
661 p.buf.Write(nilAngleBytes)
669 p.value = reflect.Value{}
670 // Special processing considerations.
671 // %T (the value's type) and %p (its address) are special; we always do them first.
674 p.printField(reflect.TypeOf(field).String(), 's', false, false, 0)
677 p.fmtPointer(reflect.ValueOf(field), verb, goSyntax)
681 if wasString, handled := p.handleMethods(verb, plus, goSyntax, depth); handled {
685 // Some types can be done without reflection.
686 switch f := field.(type) {
690 p.fmtFloat32(f, verb)
692 p.fmtFloat64(f, verb)
694 p.fmtComplex64(complex64(f), verb)
696 p.fmtComplex128(f, verb)
698 p.fmtInt64(int64(f), verb)
700 p.fmtInt64(int64(f), verb)
702 p.fmtInt64(int64(f), verb)
704 p.fmtInt64(int64(f), verb)
708 p.fmtUint64(uint64(f), verb, goSyntax)
710 p.fmtUint64(uint64(f), verb, goSyntax)
712 p.fmtUint64(uint64(f), verb, goSyntax)
714 p.fmtUint64(uint64(f), verb, goSyntax)
716 p.fmtUint64(f, verb, goSyntax)
718 p.fmtUint64(uint64(f), verb, goSyntax)
720 p.fmtString(f, verb, goSyntax)
721 wasString = verb == 's' || verb == 'v'
723 p.fmtBytes(f, verb, goSyntax, depth)
724 wasString = verb == 's'
726 // Need to use reflection
727 return p.printReflectValue(reflect.ValueOf(field), verb, plus, goSyntax, depth)
733 // printValue is like printField but starts with a reflect value, not an interface{} value.
734 func (p *pp) printValue(value reflect.Value, verb rune, plus, goSyntax bool, depth int) (wasString bool) {
735 if !value.IsValid() {
736 if verb == 'T' || verb == 'v' {
737 p.buf.Write(nilAngleBytes)
744 // Special processing considerations.
745 // %T (the value's type) and %p (its address) are special; we always do them first.
748 p.printField(value.Type().String(), 's', false, false, 0)
751 p.fmtPointer(value, verb, goSyntax)
755 // Handle values with special methods.
756 // Call always, even when field == nil, because handleMethods clears p.fmt.plus for us.
757 p.field = nil // Make sure it's cleared, for safety.
758 if value.CanInterface() {
759 p.field = value.Interface()
761 if wasString, handled := p.handleMethods(verb, plus, goSyntax, depth); handled {
765 return p.printReflectValue(value, verb, plus, goSyntax, depth)
768 // printReflectValue is the fallback for both printField and printValue.
769 // It uses reflect to print the value.
770 func (p *pp) printReflectValue(value reflect.Value, verb rune, plus, goSyntax bool, depth int) (wasString bool) {
774 switch f := value; f.Kind() {
776 p.fmtBool(f.Bool(), verb)
777 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
778 p.fmtInt64(f.Int(), verb)
779 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
780 p.fmtUint64(uint64(f.Uint()), verb, goSyntax)
781 case reflect.Float32, reflect.Float64:
782 if f.Type().Size() == 4 {
783 p.fmtFloat32(float32(f.Float()), verb)
785 p.fmtFloat64(float64(f.Float()), verb)
787 case reflect.Complex64, reflect.Complex128:
788 if f.Type().Size() == 8 {
789 p.fmtComplex64(complex64(f.Complex()), verb)
791 p.fmtComplex128(complex128(f.Complex()), verb)
794 p.fmtString(f.String(), verb, goSyntax)
797 p.buf.WriteString(f.Type().String())
799 p.buf.WriteString("(nil)")
804 p.buf.Write(mapBytes)
807 for i, key := range keys {
810 p.buf.Write(commaSpaceBytes)
815 p.printValue(key, verb, plus, goSyntax, depth+1)
817 p.printValue(f.MapIndex(key), verb, plus, goSyntax, depth+1)
826 p.buf.WriteString(value.Type().String())
831 for i := 0; i < v.NumField(); i++ {
834 p.buf.Write(commaSpaceBytes)
839 if plus || goSyntax {
840 if f := t.Field(i); f.Name != "" {
841 p.buf.WriteString(f.Name)
845 p.printValue(getField(v, i), verb, plus, goSyntax, depth+1)
848 case reflect.Interface:
850 if !value.IsValid() {
852 p.buf.WriteString(f.Type().String())
853 p.buf.Write(nilParenBytes)
855 p.buf.Write(nilAngleBytes)
858 wasString = p.printValue(value, verb, plus, goSyntax, depth+1)
860 case reflect.Array, reflect.Slice:
861 // Byte slices are special.
862 if f.Type().Elem().Kind() == reflect.Uint8 {
863 // We know it's a slice of bytes, but we also know it does not have static type
864 // []byte, or it would have been caught above. Therefore we cannot convert
865 // it directly in the (slightly) obvious way: f.Interface().([]byte); it doesn't have
866 // that type, and we can't write an expression of the right type and do a
867 // conversion because we don't have a static way to write the right type.
868 // So we build a slice by hand. This is a rare case but it would be nice
869 // if reflection could help a little more.
870 bytes := make([]byte, f.Len())
871 for i := range bytes {
872 bytes[i] = byte(f.Index(i).Uint())
874 p.fmtBytes(bytes, verb, goSyntax, depth)
875 wasString = verb == 's'
879 p.buf.WriteString(value.Type().String())
881 p.buf.WriteString("(nil)")
888 for i := 0; i < f.Len(); i++ {
891 p.buf.Write(commaSpaceBytes)
896 p.printValue(f.Index(i), verb, plus, goSyntax, depth+1)
905 // pointer to array or slice or struct? ok at top level
906 // but not embedded (avoid loops)
907 if v != 0 && depth == 0 {
908 switch a := f.Elem(); a.Kind() {
909 case reflect.Array, reflect.Slice:
911 p.printValue(a, verb, plus, goSyntax, depth+1)
915 p.printValue(a, verb, plus, goSyntax, depth+1)
921 p.buf.WriteString(value.Type().String())
925 p.buf.Write(nilBytes)
927 p.fmt0x64(uint64(v), true)
933 p.buf.Write(nilAngleBytes)
936 p.fmt0x64(uint64(v), true)
937 case reflect.Chan, reflect.Func, reflect.UnsafePointer:
938 p.fmtPointer(value, verb, goSyntax)
946 // intFromArg gets the fieldnumth element of a. On return, isInt reports whether the argument has type int.
947 func intFromArg(a []interface{}, end, i, fieldnum int) (num int, isInt bool, newi, newfieldnum int) {
948 newi, newfieldnum = end, fieldnum
949 if i < end && fieldnum < len(a) {
950 num, isInt = a[fieldnum].(int)
951 newi, newfieldnum = i+1, fieldnum+1
956 func (p *pp) doPrintf(format string, a []interface{}) {
958 fieldnum := 0 // we process one field per non-trivial format
959 for i := 0; i < end; {
961 for i < end && format[i] != '%' {
965 p.buf.WriteString(format[lasti:i])
968 // done processing format string
994 if i < end && format[i] == '*' {
995 p.fmt.wid, p.fmt.widPresent, i, fieldnum = intFromArg(a, end, i, fieldnum)
996 if !p.fmt.widPresent {
997 p.buf.Write(widthBytes)
1000 p.fmt.wid, p.fmt.widPresent, i = parsenum(format, i, end)
1002 // do we have precision?
1003 if i < end && format[i] == '.' {
1004 if format[i+1] == '*' {
1005 p.fmt.prec, p.fmt.precPresent, i, fieldnum = intFromArg(a, end, i+1, fieldnum)
1006 if !p.fmt.precPresent {
1007 p.buf.Write(precBytes)
1010 p.fmt.prec, p.fmt.precPresent, i = parsenum(format, i+1, end)
1011 if !p.fmt.precPresent {
1013 p.fmt.precPresent = true
1018 p.buf.Write(noVerbBytes)
1021 c, w := utf8.DecodeRuneInString(format[i:])
1023 // percent is special - absorbs no operand
1025 p.buf.WriteByte('%') // We ignore width and prec.
1028 if fieldnum >= len(a) { // out of operands
1029 p.buf.WriteByte('%')
1031 p.buf.Write(missingBytes)
1034 field := a[fieldnum]
1037 goSyntax := c == 'v' && p.fmt.sharp
1038 plus := c == 'v' && p.fmt.plus
1039 p.printField(field, c, plus, goSyntax, 0)
1042 if fieldnum < len(a) {
1043 p.buf.Write(extraBytes)
1044 for ; fieldnum < len(a); fieldnum++ {
1045 field := a[fieldnum]
1047 p.buf.WriteString(reflect.TypeOf(field).String())
1048 p.buf.WriteByte('=')
1050 p.printField(field, 'v', false, false, 0)
1051 if fieldnum+1 < len(a) {
1052 p.buf.Write(commaSpaceBytes)
1055 p.buf.WriteByte(')')
1059 func (p *pp) doPrint(a []interface{}, addspace, addnewline bool) {
1061 for fieldnum := 0; fieldnum < len(a); fieldnum++ {
1063 // always add spaces if we're doing println
1064 field := a[fieldnum]
1066 isString := field != nil && reflect.TypeOf(field).Kind() == reflect.String
1067 if addspace || !isString && !prevString {
1068 p.buf.WriteByte(' ')
1071 prevString = p.printField(field, 'v', false, false, 0)
1074 p.buf.WriteByte('\n')