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.
16 // Some constants in the form of bytes, to avoid string overhead.
17 // Needlessly fastidious, I suppose.
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)")
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 os.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)
45 // Flag returns whether the flag c, a character, has been set.
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 int)
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 {
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
68 type GoStringer interface {
76 runeBuf [utf8.UTFMax]byte
80 // A cache holds a set of reusable objects.
81 // The buffered channel holds the currently available objects.
82 // If more are needed, the cache creates them by calling new.
84 saved chan interface{}
85 new func() interface{}
88 func (c *cache) put(x interface{}) {
97 func (c *cache) get() interface{} {
100 return x // reused from cache
107 func newCache(f func() interface{}) *cache {
108 return &cache{make(chan interface{}, 100), f}
111 var ppFree = newCache(func() interface{} { return new(pp) })
113 // Allocate a new pp struct or grab a cached one.
114 func newPrinter() *pp {
115 p := ppFree.get().(*pp)
121 // Save used pp structs in ppFree; avoids an allocation per invocation.
122 func (p *pp) free() {
123 // Don't hold on to pp structs with large buffers.
124 if cap(p.buf.Bytes()) > 1024 {
131 func (p *pp) Width() (wid int, ok bool) { return p.fmt.wid, p.fmt.widPresent }
133 func (p *pp) Precision() (prec int, ok bool) { return p.fmt.prec, p.fmt.precPresent }
135 func (p *pp) Flag(b int) bool {
151 func (p *pp) add(c int) {
155 // Implement Write so we can call Fprintf on a pp (through State), for
156 // recursive use in custom verbs.
157 func (p *pp) Write(b []byte) (ret int, err os.Error) {
158 return p.buf.Write(b)
161 // These routines end in 'f' and take a format string.
163 // Fprintf formats according to a format specifier and writes to w.
164 // It returns the number of bytes written and any write error encountered.
165 func Fprintf(w io.Writer, format string, a ...interface{}) (n int, err os.Error) {
167 p.doPrintf(format, a)
168 n64, err := p.buf.WriteTo(w)
173 // Printf formats according to a format specifier and writes to standard output.
174 // It returns the number of bytes written and any write error encountered.
175 func Printf(format string, a ...interface{}) (n int, err os.Error) {
176 return Fprintf(os.Stdout, format, a...)
179 // Sprintf formats according to a format specifier and returns the resulting string.
180 func Sprintf(format string, a ...interface{}) string {
182 p.doPrintf(format, a)
188 // Errorf formats according to a format specifier and returns the string
189 // converted to an os.ErrorString, which satisfies the os.Error interface.
190 func Errorf(format string, a ...interface{}) os.Error {
191 return os.NewError(Sprintf(format, a...))
194 // These routines do not take a format string
196 // Fprint formats using the default formats for its operands and writes to w.
197 // Spaces are added between operands when neither is a string.
198 // It returns the number of bytes written and any write error encountered.
199 func Fprint(w io.Writer, a ...interface{}) (n int, err os.Error) {
201 p.doPrint(a, false, false)
202 n64, err := p.buf.WriteTo(w)
207 // Print formats using the default formats for its operands and writes to standard output.
208 // Spaces are added between operands when neither is a string.
209 // It returns the number of bytes written and any write error encountered.
210 func Print(a ...interface{}) (n int, err os.Error) {
211 return Fprint(os.Stdout, a...)
214 // Sprint formats using the default formats for its operands and returns the resulting string.
215 // Spaces are added between operands when neither is a string.
216 func Sprint(a ...interface{}) string {
218 p.doPrint(a, false, false)
224 // These routines end in 'ln', do not take a format string,
225 // always add spaces between operands, and add a newline
226 // after the last operand.
228 // Fprintln formats using the default formats for its operands and writes to w.
229 // Spaces are always added between operands and a newline is appended.
230 // It returns the number of bytes written and any write error encountered.
231 func Fprintln(w io.Writer, a ...interface{}) (n int, err os.Error) {
233 p.doPrint(a, true, true)
234 n64, err := p.buf.WriteTo(w)
239 // Println formats using the default formats for its operands and writes to standard output.
240 // Spaces are always added between operands and a newline is appended.
241 // It returns the number of bytes written and any write error encountered.
242 func Println(a ...interface{}) (n int, err os.Error) {
243 return Fprintln(os.Stdout, a...)
246 // Sprintln formats using the default formats for its operands and returns the resulting string.
247 // Spaces are always added between operands and a newline is appended.
248 func Sprintln(a ...interface{}) string {
250 p.doPrint(a, true, true)
256 // Get the i'th arg of the struct value.
257 // If the arg itself is an interface, return a value for
258 // the thing inside the interface, not the interface itself.
259 func getField(v reflect.Value, i int) reflect.Value {
261 if i := val; i.Kind() == reflect.Interface {
262 if inter := i.Interface(); inter != nil {
263 return reflect.ValueOf(inter)
269 // Convert ASCII to integer. n is 0 (and got is false) if no number present.
270 func parsenum(s string, start, end int) (num int, isnum bool, newi int) {
274 for newi = start; newi < end && '0' <= s[newi] && s[newi] <= '9'; newi++ {
275 num = num*10 + int(s[newi]-'0')
281 func (p *pp) unknownType(v interface{}) {
283 p.buf.Write(nilAngleBytes)
287 p.buf.WriteString(reflect.TypeOf(v).String())
291 func (p *pp) badVerb(verb int, val interface{}) {
297 p.buf.Write(nilAngleBytes)
299 p.buf.WriteString(reflect.TypeOf(val).String())
301 p.printField(val, 'v', false, false, 0)
306 func (p *pp) fmtBool(v bool, verb int, value interface{}) {
311 p.badVerb(verb, value)
315 // fmtC formats a rune for the 'c' format.
316 func (p *pp) fmtC(c int64) {
317 rune := int(c) // Check for overflow.
318 if int64(rune) != c {
319 rune = utf8.RuneError
321 w := utf8.EncodeRune(p.runeBuf[0:utf8.UTFMax], rune)
322 p.fmt.pad(p.runeBuf[0:w])
325 func (p *pp) fmtInt64(v int64, verb int, value interface{}) {
328 p.fmt.integer(v, 2, signed, ldigits)
332 p.fmt.integer(v, 10, signed, ldigits)
334 p.fmt.integer(v, 8, signed, ldigits)
336 if 0 <= v && v <= unicode.MaxRune {
339 p.badVerb(verb, value)
342 p.fmt.integer(v, 16, signed, ldigits)
346 p.fmt.integer(v, 16, signed, udigits)
348 p.badVerb(verb, value)
352 // fmt0x64 formats a uint64 in hexadecimal and prefixes it with 0x or
353 // not, as requested, by temporarily setting the sharp flag.
354 func (p *pp) fmt0x64(v uint64, leading0x bool) {
356 p.fmt.sharp = leading0x
357 p.fmt.integer(int64(v), 16, unsigned, ldigits)
361 // fmtUnicode formats a uint64 in U+1234 form by
362 // temporarily turning on the unicode flag and tweaking the precision.
363 func (p *pp) fmtUnicode(v int64) {
364 precPresent := p.fmt.precPresent
369 // If prec is already set, leave it alone; otherwise 4 is minimum.
371 p.fmt.precPresent = true
373 p.fmt.unicode = true // turn on U+
374 p.fmt.uniQuote = sharp
375 p.fmt.integer(int64(v), 16, unsigned, udigits)
376 p.fmt.unicode = false
377 p.fmt.uniQuote = false
379 p.fmt.precPresent = precPresent
383 func (p *pp) fmtUint64(v uint64, verb int, goSyntax bool, value interface{}) {
386 p.fmt.integer(int64(v), 2, unsigned, ldigits)
390 p.fmt.integer(int64(v), 10, unsigned, ldigits)
395 p.fmt.integer(int64(v), 10, unsigned, ldigits)
398 p.fmt.integer(int64(v), 8, unsigned, ldigits)
400 if 0 <= v && v <= unicode.MaxRune {
401 p.fmt.fmt_qc(int64(v))
403 p.badVerb(verb, value)
406 p.fmt.integer(int64(v), 16, unsigned, ldigits)
408 p.fmt.integer(int64(v), 16, unsigned, udigits)
410 p.fmtUnicode(int64(v))
412 p.badVerb(verb, value)
416 func (p *pp) fmtFloat32(v float32, verb int, value interface{}) {
431 p.badVerb(verb, value)
435 func (p *pp) fmtFloat64(v float64, verb int, value interface{}) {
450 p.badVerb(verb, value)
454 func (p *pp) fmtComplex64(v complex64, verb int, value interface{}) {
456 case 'e', 'E', 'f', 'F', 'g', 'G':
457 p.fmt.fmt_c64(v, verb)
459 p.fmt.fmt_c64(v, 'g')
461 p.badVerb(verb, value)
465 func (p *pp) fmtComplex128(v complex128, verb int, value interface{}) {
467 case 'e', 'E', 'f', 'F', 'g', 'G':
468 p.fmt.fmt_c128(v, verb)
470 p.fmt.fmt_c128(v, 'g')
472 p.badVerb(verb, value)
476 func (p *pp) fmtString(v string, verb int, goSyntax bool, value interface{}) {
493 p.badVerb(verb, value)
497 func (p *pp) fmtBytes(v []byte, verb int, goSyntax bool, depth int, value interface{}) {
498 if verb == 'v' || verb == 'd' {
500 p.buf.Write(bytesBytes)
504 for i, c := range v {
507 p.buf.Write(commaSpaceBytes)
512 p.printField(c, 'v', p.fmt.plus, goSyntax, depth+1)
532 p.badVerb(verb, value)
536 func (p *pp) fmtPointer(field interface{}, value reflect.Value, verb int, goSyntax bool) {
538 switch value.Kind() {
539 case reflect.Chan, reflect.Func, reflect.Map, reflect.Ptr, reflect.Slice, reflect.UnsafePointer:
542 p.badVerb(verb, field)
547 p.buf.WriteString(reflect.TypeOf(field).String())
551 p.buf.Write(nilBytes)
553 p.fmt0x64(uint64(u), true)
557 p.fmt0x64(uint64(u), !p.fmt.sharp)
562 intBits = reflect.TypeOf(0).Bits()
563 floatBits = reflect.TypeOf(0.0).Bits()
564 complexBits = reflect.TypeOf(1i).Bits()
565 uintptrBits = reflect.TypeOf(uintptr(0)).Bits()
568 func (p *pp) catchPanic(val interface{}, verb int) {
569 if err := recover(); err != nil {
570 // If it's a nil pointer, just say "<nil>". The likeliest causes are a
571 // Stringer that fails to guard against nil or a nil pointer for a
572 // value receiver, and in either case, "<nil>" is a nice result.
573 if v := reflect.ValueOf(val); v.Kind() == reflect.Ptr && v.IsNil() {
574 p.buf.Write(nilAngleBytes)
577 // Otherwise print a concise panic message. Most of the time the panic
578 // value will print itself nicely.
580 // Nested panics; the recursion in printField cannot succeed.
585 p.buf.Write(panicBytes)
587 p.printField(err, 'v', false, false, 0)
593 func (p *pp) printField(field interface{}, verb int, plus, goSyntax bool, depth int) (wasString bool) {
595 if verb == 'T' || verb == 'v' {
596 p.buf.Write(nilAngleBytes)
598 p.badVerb(verb, field)
603 // Special processing considerations.
604 // %T (the value's type) and %p (its address) are special; we always do them first.
607 p.printField(reflect.TypeOf(field).String(), 's', false, false, 0)
610 p.fmtPointer(field, reflect.ValueOf(field), verb, goSyntax)
613 // Is it a Formatter?
614 if formatter, ok := field.(Formatter); ok {
615 defer p.catchPanic(field, verb)
616 formatter.Format(p, verb)
617 return false // this value is not a string
620 // Must not touch flags before Formatter looks at them.
624 // If we're doing Go syntax and the field knows how to supply it, take care of it now.
627 if stringer, ok := field.(GoStringer); ok {
628 defer p.catchPanic(field, verb)
629 // Print the result of GoString unadorned.
630 p.fmtString(stringer.GoString(), 's', false, field)
631 return false // this value is not a string
635 if stringer, ok := field.(Stringer); ok {
636 defer p.catchPanic(field, verb)
637 p.printField(stringer.String(), verb, plus, false, depth)
638 return false // this value is not a string
642 // Some types can be done without reflection.
643 switch f := field.(type) {
645 p.fmtBool(f, verb, field)
648 p.fmtFloat32(f, verb, field)
651 p.fmtFloat64(f, verb, field)
654 p.fmtComplex64(complex64(f), verb, field)
657 p.fmtComplex128(f, verb, field)
660 p.fmtInt64(int64(f), verb, field)
663 p.fmtInt64(int64(f), verb, field)
666 p.fmtInt64(int64(f), verb, field)
669 p.fmtInt64(int64(f), verb, field)
672 p.fmtInt64(f, verb, field)
675 p.fmtUint64(uint64(f), verb, goSyntax, field)
678 p.fmtUint64(uint64(f), verb, goSyntax, field)
681 p.fmtUint64(uint64(f), verb, goSyntax, field)
684 p.fmtUint64(uint64(f), verb, goSyntax, field)
687 p.fmtUint64(f, verb, goSyntax, field)
690 p.fmtUint64(uint64(f), verb, goSyntax, field)
693 p.fmtString(f, verb, goSyntax, field)
694 return verb == 's' || verb == 'v'
696 p.fmtBytes(f, verb, goSyntax, depth, field)
700 // Need to use reflection
701 value := reflect.ValueOf(field)
704 switch f := value; f.Kind() {
706 p.fmtBool(f.Bool(), verb, field)
707 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
708 p.fmtInt64(f.Int(), verb, field)
709 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
710 p.fmtUint64(uint64(f.Uint()), verb, goSyntax, field)
711 case reflect.Float32, reflect.Float64:
712 if f.Type().Size() == 4 {
713 p.fmtFloat32(float32(f.Float()), verb, field)
715 p.fmtFloat64(float64(f.Float()), verb, field)
717 case reflect.Complex64, reflect.Complex128:
718 if f.Type().Size() == 8 {
719 p.fmtComplex64(complex64(f.Complex()), verb, field)
721 p.fmtComplex128(complex128(f.Complex()), verb, field)
724 p.fmtString(f.String(), verb, goSyntax, field)
727 p.buf.WriteString(f.Type().String())
730 p.buf.Write(mapBytes)
733 for i, key := range keys {
736 p.buf.Write(commaSpaceBytes)
741 p.printField(key.Interface(), verb, plus, goSyntax, depth+1)
743 p.printField(f.MapIndex(key).Interface(), verb, plus, goSyntax, depth+1)
752 p.buf.WriteString(reflect.TypeOf(field).String())
757 for i := 0; i < v.NumField(); i++ {
760 p.buf.Write(commaSpaceBytes)
765 if plus || goSyntax {
766 if f := t.Field(i); f.Name != "" {
767 p.buf.WriteString(f.Name)
771 p.printField(getField(v, i).Interface(), verb, plus, goSyntax, depth+1)
774 case reflect.Interface:
776 if !value.IsValid() {
778 p.buf.WriteString(reflect.TypeOf(field).String())
779 p.buf.Write(nilParenBytes)
781 p.buf.Write(nilAngleBytes)
784 return p.printField(value.Interface(), verb, plus, goSyntax, depth+1)
786 case reflect.Array, reflect.Slice:
787 // Byte slices are special.
788 if f.Type().Elem().Kind() == reflect.Uint8 {
789 // We know it's a slice of bytes, but we also know it does not have static type
790 // []byte, or it would have been caught above. Therefore we cannot convert
791 // it directly in the (slightly) obvious way: f.Interface().([]byte); it doesn't have
792 // that type, and we can't write an expression of the right type and do a
793 // conversion because we don't have a static way to write the right type.
794 // So we build a slice by hand. This is a rare case but it would be nice
795 // if reflection could help a little more.
796 bytes := make([]byte, f.Len())
797 for i := range bytes {
798 bytes[i] = byte(f.Index(i).Uint())
800 p.fmtBytes(bytes, verb, goSyntax, depth, field)
804 p.buf.WriteString(reflect.TypeOf(field).String())
809 for i := 0; i < f.Len(); i++ {
812 p.buf.Write(commaSpaceBytes)
817 p.printField(f.Index(i).Interface(), verb, plus, goSyntax, depth+1)
826 // pointer to array or slice or struct? ok at top level
827 // but not embedded (avoid loops)
828 if v != 0 && depth == 0 {
829 switch a := f.Elem(); a.Kind() {
830 case reflect.Array, reflect.Slice:
832 p.printField(a.Interface(), verb, plus, goSyntax, depth+1)
836 p.printField(a.Interface(), verb, plus, goSyntax, depth+1)
842 p.buf.WriteString(reflect.TypeOf(field).String())
846 p.buf.Write(nilBytes)
848 p.fmt0x64(uint64(v), true)
854 p.buf.Write(nilAngleBytes)
857 p.fmt0x64(uint64(v), true)
858 case reflect.Chan, reflect.Func, reflect.UnsafePointer:
859 p.fmtPointer(field, value, verb, goSyntax)
866 // intFromArg gets the fieldnumth element of a. On return, isInt reports whether the argument has type int.
867 func intFromArg(a []interface{}, end, i, fieldnum int) (num int, isInt bool, newi, newfieldnum int) {
868 newi, newfieldnum = end, fieldnum
869 if i < end && fieldnum < len(a) {
870 num, isInt = a[fieldnum].(int)
871 newi, newfieldnum = i+1, fieldnum+1
876 func (p *pp) doPrintf(format string, a []interface{}) {
878 fieldnum := 0 // we process one field per non-trivial format
879 for i := 0; i < end; {
881 for i < end && format[i] != '%' {
885 p.buf.WriteString(format[lasti:i])
888 // done processing format string
914 if i < end && format[i] == '*' {
915 p.fmt.wid, p.fmt.widPresent, i, fieldnum = intFromArg(a, end, i, fieldnum)
916 if !p.fmt.widPresent {
917 p.buf.Write(widthBytes)
920 p.fmt.wid, p.fmt.widPresent, i = parsenum(format, i, end)
922 // do we have precision?
923 if i < end && format[i] == '.' {
924 if format[i+1] == '*' {
925 p.fmt.prec, p.fmt.precPresent, i, fieldnum = intFromArg(a, end, i+1, fieldnum)
926 if !p.fmt.precPresent {
927 p.buf.Write(precBytes)
930 p.fmt.prec, p.fmt.precPresent, i = parsenum(format, i+1, end)
931 if !p.fmt.precPresent {
933 p.fmt.precPresent = true
938 p.buf.Write(noVerbBytes)
941 c, w := utf8.DecodeRuneInString(format[i:])
943 // percent is special - absorbs no operand
945 p.buf.WriteByte('%') // We ignore width and prec.
948 if fieldnum >= len(a) { // out of operands
951 p.buf.Write(missingBytes)
957 goSyntax := c == 'v' && p.fmt.sharp
958 plus := c == 'v' && p.fmt.plus
959 p.printField(field, c, plus, goSyntax, 0)
962 if fieldnum < len(a) {
963 p.buf.Write(extraBytes)
964 for ; fieldnum < len(a); fieldnum++ {
967 p.buf.WriteString(reflect.TypeOf(field).String())
970 p.printField(field, 'v', false, false, 0)
971 if fieldnum+1 < len(a) {
972 p.buf.Write(commaSpaceBytes)
979 func (p *pp) doPrint(a []interface{}, addspace, addnewline bool) {
981 for fieldnum := 0; fieldnum < len(a); fieldnum++ {
983 // always add spaces if we're doing println
986 isString := field != nil && reflect.TypeOf(field).Kind() == reflect.String
987 if addspace || !isString && !prevString {
991 prevString = p.printField(field, 'v', false, false, 0)
994 p.buf.WriteByte('\n')