OSDN Git Service

libgo: Update to weekly.2011-11-18.
[pf3gnuchains/gcc-fork.git] / libgo / go / fmt / print.go
1 // Copyright 2009 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package fmt
6
7 import (
8         "bytes"
9         "errors"
10         "io"
11         "os"
12         "reflect"
13         "sync"
14         "unicode"
15         "unicode/utf8"
16 )
17
18 // Some constants in the form of bytes, to avoid string overhead.
19 // Needlessly fastidious, I suppose.
20 var (
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)")
34 )
35
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)
46
47         // Flag returns whether the flag c, a character, has been set.
48         Flag(c int) bool
49 }
50
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)
56 }
57
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 {
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 type pp struct {
75         n         int
76         panicking bool
77         buf       bytes.Buffer
78         // field holds the current item, as an interface{}.
79         field 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.
82         value   reflect.Value
83         runeBuf [utf8.UTFMax]byte
84         fmt     fmt
85 }
86
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.
90 type cache struct {
91         mu    sync.Mutex
92         saved []interface{}
93         new   func() interface{}
94 }
95
96 func (c *cache) put(x interface{}) {
97         c.mu.Lock()
98         if len(c.saved) < cap(c.saved) {
99                 c.saved = append(c.saved, x)
100         }
101         c.mu.Unlock()
102 }
103
104 func (c *cache) get() interface{} {
105         c.mu.Lock()
106         n := len(c.saved)
107         if n == 0 {
108                 c.mu.Unlock()
109                 return c.new()
110         }
111         x := c.saved[n-1]
112         c.saved = c.saved[0 : n-1]
113         c.mu.Unlock()
114         return x
115 }
116
117 func newCache(f func() interface{}) *cache {
118         return &cache{saved: make([]interface{}, 0, 100), new: f}
119 }
120
121 var ppFree = newCache(func() interface{} { return new(pp) })
122
123 // Allocate a new pp struct or grab a cached one.
124 func newPrinter() *pp {
125         p := ppFree.get().(*pp)
126         p.panicking = false
127         p.fmt.init(&p.buf)
128         return p
129 }
130
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 {
135                 return
136         }
137         p.buf.Reset()
138         p.field = nil
139         p.value = reflect.Value{}
140         ppFree.put(p)
141 }
142
143 func (p *pp) Width() (wid int, ok bool) { return p.fmt.wid, p.fmt.widPresent }
144
145 func (p *pp) Precision() (prec int, ok bool) { return p.fmt.prec, p.fmt.precPresent }
146
147 func (p *pp) Flag(b int) bool {
148         switch b {
149         case '-':
150                 return p.fmt.minus
151         case '+':
152                 return p.fmt.plus
153         case '#':
154                 return p.fmt.sharp
155         case ' ':
156                 return p.fmt.space
157         case '0':
158                 return p.fmt.zero
159         }
160         return false
161 }
162
163 func (p *pp) add(c rune) {
164         p.buf.WriteRune(c)
165 }
166
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)
171 }
172
173 // These routines end in 'f' and take a format string.
174
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) {
178         p := newPrinter()
179         p.doPrintf(format, a)
180         n64, err := p.buf.WriteTo(w)
181         p.free()
182         return int(n64), err
183 }
184
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...)
189 }
190
191 // Sprintf formats according to a format specifier and returns the resulting string.
192 func Sprintf(format string, a ...interface{}) string {
193         p := newPrinter()
194         p.doPrintf(format, a)
195         s := p.buf.String()
196         p.free()
197         return s
198 }
199
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...))
204 }
205
206 // These routines do not take a format string
207
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) {
212         p := newPrinter()
213         p.doPrint(a, false, false)
214         n64, err := p.buf.WriteTo(w)
215         p.free()
216         return int(n64), err
217 }
218
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...)
224 }
225
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 {
229         p := newPrinter()
230         p.doPrint(a, false, false)
231         s := p.buf.String()
232         p.free()
233         return s
234 }
235
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.
239
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) {
244         p := newPrinter()
245         p.doPrint(a, true, true)
246         n64, err := p.buf.WriteTo(w)
247         p.free()
248         return int(n64), err
249 }
250
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...)
256 }
257
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 {
261         p := newPrinter()
262         p.doPrint(a, true, true)
263         s := p.buf.String()
264         p.free()
265         return s
266 }
267
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 {
272         val := v.Field(i)
273         if val.Kind() == reflect.Interface && !val.IsNil() {
274                 val = val.Elem()
275         }
276         return val
277 }
278
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) {
281         if start >= end {
282                 return 0, false, end
283         }
284         for newi = start; newi < end && '0' <= s[newi] && s[newi] <= '9'; newi++ {
285                 num = num*10 + int(s[newi]-'0')
286                 isnum = true
287         }
288         return
289 }
290
291 func (p *pp) unknownType(v interface{}) {
292         if v == nil {
293                 p.buf.Write(nilAngleBytes)
294                 return
295         }
296         p.buf.WriteByte('?')
297         p.buf.WriteString(reflect.TypeOf(v).String())
298         p.buf.WriteByte('?')
299 }
300
301 func (p *pp) badVerb(verb rune) {
302         p.add('%')
303         p.add('!')
304         p.add(verb)
305         p.add('(')
306         switch {
307         case p.field != nil:
308                 p.buf.WriteString(reflect.TypeOf(p.field).String())
309                 p.add('=')
310                 p.printField(p.field, 'v', false, false, 0)
311         case p.value.IsValid():
312                 p.buf.WriteString(p.value.Type().String())
313                 p.add('=')
314                 p.printValue(p.value, 'v', false, false, 0)
315         default:
316                 p.buf.Write(nilAngleBytes)
317         }
318         p.add(')')
319 }
320
321 func (p *pp) fmtBool(v bool, verb rune) {
322         switch verb {
323         case 't', 'v':
324                 p.fmt.fmt_boolean(v)
325         default:
326                 p.badVerb(verb)
327         }
328 }
329
330 // fmtC formats a rune for the 'c' format.
331 func (p *pp) fmtC(c int64) {
332         r := rune(c) // Check for overflow.
333         if int64(r) != c {
334                 r = utf8.RuneError
335         }
336         w := utf8.EncodeRune(p.runeBuf[0:utf8.UTFMax], r)
337         p.fmt.pad(p.runeBuf[0:w])
338 }
339
340 func (p *pp) fmtInt64(v int64, verb rune) {
341         switch verb {
342         case 'b':
343                 p.fmt.integer(v, 2, signed, ldigits)
344         case 'c':
345                 p.fmtC(v)
346         case 'd', 'v':
347                 p.fmt.integer(v, 10, signed, ldigits)
348         case 'o':
349                 p.fmt.integer(v, 8, signed, ldigits)
350         case 'q':
351                 if 0 <= v && v <= unicode.MaxRune {
352                         p.fmt.fmt_qc(v)
353                 } else {
354                         p.badVerb(verb)
355                 }
356         case 'x':
357                 p.fmt.integer(v, 16, signed, ldigits)
358         case 'U':
359                 p.fmtUnicode(v)
360         case 'X':
361                 p.fmt.integer(v, 16, signed, udigits)
362         default:
363                 p.badVerb(verb)
364         }
365 }
366
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) {
370         sharp := p.fmt.sharp
371         p.fmt.sharp = leading0x
372         p.fmt.integer(int64(v), 16, unsigned, ldigits)
373         p.fmt.sharp = sharp
374 }
375
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
380         sharp := p.fmt.sharp
381         p.fmt.sharp = false
382         prec := p.fmt.prec
383         if !precPresent {
384                 // If prec is already set, leave it alone; otherwise 4 is minimum.
385                 p.fmt.prec = 4
386                 p.fmt.precPresent = true
387         }
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
393         p.fmt.prec = prec
394         p.fmt.precPresent = precPresent
395         p.fmt.sharp = sharp
396 }
397
398 func (p *pp) fmtUint64(v uint64, verb rune, goSyntax bool) {
399         switch verb {
400         case 'b':
401                 p.fmt.integer(int64(v), 2, unsigned, ldigits)
402         case 'c':
403                 p.fmtC(int64(v))
404         case 'd':
405                 p.fmt.integer(int64(v), 10, unsigned, ldigits)
406         case 'v':
407                 if goSyntax {
408                         p.fmt0x64(v, true)
409                 } else {
410                         p.fmt.integer(int64(v), 10, unsigned, ldigits)
411                 }
412         case 'o':
413                 p.fmt.integer(int64(v), 8, unsigned, ldigits)
414         case 'q':
415                 if 0 <= v && v <= unicode.MaxRune {
416                         p.fmt.fmt_qc(int64(v))
417                 } else {
418                         p.badVerb(verb)
419                 }
420         case 'x':
421                 p.fmt.integer(int64(v), 16, unsigned, ldigits)
422         case 'X':
423                 p.fmt.integer(int64(v), 16, unsigned, udigits)
424         case 'U':
425                 p.fmtUnicode(int64(v))
426         default:
427                 p.badVerb(verb)
428         }
429 }
430
431 func (p *pp) fmtFloat32(v float32, verb rune) {
432         switch verb {
433         case 'b':
434                 p.fmt.fmt_fb32(v)
435         case 'e':
436                 p.fmt.fmt_e32(v)
437         case 'E':
438                 p.fmt.fmt_E32(v)
439         case 'f':
440                 p.fmt.fmt_f32(v)
441         case 'g', 'v':
442                 p.fmt.fmt_g32(v)
443         case 'G':
444                 p.fmt.fmt_G32(v)
445         default:
446                 p.badVerb(verb)
447         }
448 }
449
450 func (p *pp) fmtFloat64(v float64, verb rune) {
451         switch verb {
452         case 'b':
453                 p.fmt.fmt_fb64(v)
454         case 'e':
455                 p.fmt.fmt_e64(v)
456         case 'E':
457                 p.fmt.fmt_E64(v)
458         case 'f':
459                 p.fmt.fmt_f64(v)
460         case 'g', 'v':
461                 p.fmt.fmt_g64(v)
462         case 'G':
463                 p.fmt.fmt_G64(v)
464         default:
465                 p.badVerb(verb)
466         }
467 }
468
469 func (p *pp) fmtComplex64(v complex64, verb rune) {
470         switch verb {
471         case 'e', 'E', 'f', 'F', 'g', 'G':
472                 p.fmt.fmt_c64(v, verb)
473         case 'v':
474                 p.fmt.fmt_c64(v, 'g')
475         default:
476                 p.badVerb(verb)
477         }
478 }
479
480 func (p *pp) fmtComplex128(v complex128, verb rune) {
481         switch verb {
482         case 'e', 'E', 'f', 'F', 'g', 'G':
483                 p.fmt.fmt_c128(v, verb)
484         case 'v':
485                 p.fmt.fmt_c128(v, 'g')
486         default:
487                 p.badVerb(verb)
488         }
489 }
490
491 func (p *pp) fmtString(v string, verb rune, goSyntax bool) {
492         switch verb {
493         case 'v':
494                 if goSyntax {
495                         p.fmt.fmt_q(v)
496                 } else {
497                         p.fmt.fmt_s(v)
498                 }
499         case 's':
500                 p.fmt.fmt_s(v)
501         case 'x':
502                 p.fmt.fmt_sx(v)
503         case 'X':
504                 p.fmt.fmt_sX(v)
505         case 'q':
506                 p.fmt.fmt_q(v)
507         default:
508                 p.badVerb(verb)
509         }
510 }
511
512 func (p *pp) fmtBytes(v []byte, verb rune, goSyntax bool, depth int) {
513         if verb == 'v' || verb == 'd' {
514                 if goSyntax {
515                         p.buf.Write(bytesBytes)
516                 } else {
517                         p.buf.WriteByte('[')
518                 }
519                 for i, c := range v {
520                         if i > 0 {
521                                 if goSyntax {
522                                         p.buf.Write(commaSpaceBytes)
523                                 } else {
524                                         p.buf.WriteByte(' ')
525                                 }
526                         }
527                         p.printField(c, 'v', p.fmt.plus, goSyntax, depth+1)
528                 }
529                 if goSyntax {
530                         p.buf.WriteByte('}')
531                 } else {
532                         p.buf.WriteByte(']')
533                 }
534                 return
535         }
536         s := string(v)
537         switch verb {
538         case 's':
539                 p.fmt.fmt_s(s)
540         case 'x':
541                 p.fmt.fmt_sx(s)
542         case 'X':
543                 p.fmt.fmt_sX(s)
544         case 'q':
545                 p.fmt.fmt_q(s)
546         default:
547                 p.badVerb(verb)
548         }
549 }
550
551 func (p *pp) fmtPointer(value reflect.Value, verb rune, goSyntax bool) {
552         var u uintptr
553         switch value.Kind() {
554         case reflect.Chan, reflect.Func, reflect.Map, reflect.Ptr, reflect.Slice, reflect.UnsafePointer:
555                 u = value.Pointer()
556         default:
557                 p.badVerb(verb)
558                 return
559         }
560         if goSyntax {
561                 p.add('(')
562                 p.buf.WriteString(value.Type().String())
563                 p.add(')')
564                 p.add('(')
565                 if u == 0 {
566                         p.buf.Write(nilBytes)
567                 } else {
568                         p.fmt0x64(uint64(u), true)
569                 }
570                 p.add(')')
571         } else {
572                 p.fmt0x64(uint64(u), !p.fmt.sharp)
573         }
574 }
575
576 var (
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()
581 )
582
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)
590                         return
591                 }
592                 // Otherwise print a concise panic message. Most of the time the panic
593                 // value will print itself nicely.
594                 if p.panicking {
595                         // Nested panics; the recursion in printField cannot succeed.
596                         panic(err)
597                 }
598                 p.buf.WriteByte('%')
599                 p.add(verb)
600                 p.buf.Write(panicBytes)
601                 p.panicking = true
602                 p.printField(err, 'v', false, false, 0)
603                 p.panicking = false
604                 p.buf.WriteByte(')')
605         }
606 }
607
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 {
611                 handled = true
612                 wasString = false
613                 defer p.catchPanic(p.field, verb)
614                 formatter.Format(p, verb)
615                 return
616         }
617         // Must not touch flags before Formatter looks at them.
618         if plus {
619                 p.fmt.plus = false
620         }
621
622         // If we're doing Go syntax and the field knows how to supply it, take care of it now.
623         if goSyntax {
624                 p.fmt.sharp = false
625                 if stringer, ok := p.field.(GoStringer); ok {
626                         wasString = false
627                         handled = true
628                         defer p.catchPanic(p.field, verb)
629                         // Print the result of GoString unadorned.
630                         p.fmtString(stringer.GoString(), 's', false)
631                         return
632                 }
633         } else {
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) {
639                 case error:
640                         wasString = false
641                         handled = true
642                         defer p.catchPanic(p.field, verb)
643                         p.printField(v.Error(), verb, plus, false, depth)
644                         return
645
646                 case Stringer:
647                         wasString = false
648                         handled = true
649                         defer p.catchPanic(p.field, verb)
650                         p.printField(v.String(), verb, plus, false, depth)
651                         return
652                 }
653         }
654         handled = false
655         return
656 }
657
658 func (p *pp) printField(field interface{}, verb rune, plus, goSyntax bool, depth int) (wasString bool) {
659         if field == nil {
660                 if verb == 'T' || verb == 'v' {
661                         p.buf.Write(nilAngleBytes)
662                 } else {
663                         p.badVerb(verb)
664                 }
665                 return false
666         }
667
668         p.field = field
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.
672         switch verb {
673         case 'T':
674                 p.printField(reflect.TypeOf(field).String(), 's', false, false, 0)
675                 return false
676         case 'p':
677                 p.fmtPointer(reflect.ValueOf(field), verb, goSyntax)
678                 return false
679         }
680
681         if wasString, handled := p.handleMethods(verb, plus, goSyntax, depth); handled {
682                 return wasString
683         }
684
685         // Some types can be done without reflection.
686         switch f := field.(type) {
687         case bool:
688                 p.fmtBool(f, verb)
689         case float32:
690                 p.fmtFloat32(f, verb)
691         case float64:
692                 p.fmtFloat64(f, verb)
693         case complex64:
694                 p.fmtComplex64(complex64(f), verb)
695         case complex128:
696                 p.fmtComplex128(f, verb)
697         case int:
698                 p.fmtInt64(int64(f), verb)
699         case int8:
700                 p.fmtInt64(int64(f), verb)
701         case int16:
702                 p.fmtInt64(int64(f), verb)
703         case int32:
704                 p.fmtInt64(int64(f), verb)
705         case int64:
706                 p.fmtInt64(f, verb)
707         case uint:
708                 p.fmtUint64(uint64(f), verb, goSyntax)
709         case uint8:
710                 p.fmtUint64(uint64(f), verb, goSyntax)
711         case uint16:
712                 p.fmtUint64(uint64(f), verb, goSyntax)
713         case uint32:
714                 p.fmtUint64(uint64(f), verb, goSyntax)
715         case uint64:
716                 p.fmtUint64(f, verb, goSyntax)
717         case uintptr:
718                 p.fmtUint64(uint64(f), verb, goSyntax)
719         case string:
720                 p.fmtString(f, verb, goSyntax)
721                 wasString = verb == 's' || verb == 'v'
722         case []byte:
723                 p.fmtBytes(f, verb, goSyntax, depth)
724                 wasString = verb == 's'
725         default:
726                 // Need to use reflection
727                 return p.printReflectValue(reflect.ValueOf(field), verb, plus, goSyntax, depth)
728         }
729         p.field = nil
730         return
731 }
732
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)
738                 } else {
739                         p.badVerb(verb)
740                 }
741                 return false
742         }
743
744         // Special processing considerations.
745         // %T (the value's type) and %p (its address) are special; we always do them first.
746         switch verb {
747         case 'T':
748                 p.printField(value.Type().String(), 's', false, false, 0)
749                 return false
750         case 'p':
751                 p.fmtPointer(value, verb, goSyntax)
752                 return false
753         }
754
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()
760         }
761         if wasString, handled := p.handleMethods(verb, plus, goSyntax, depth); handled {
762                 return wasString
763         }
764
765         return p.printReflectValue(value, verb, plus, goSyntax, depth)
766 }
767
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) {
771         oldValue := p.value
772         p.value = value
773 BigSwitch:
774         switch f := value; f.Kind() {
775         case reflect.Bool:
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)
784                 } else {
785                         p.fmtFloat64(float64(f.Float()), verb)
786                 }
787         case reflect.Complex64, reflect.Complex128:
788                 if f.Type().Size() == 8 {
789                         p.fmtComplex64(complex64(f.Complex()), verb)
790                 } else {
791                         p.fmtComplex128(complex128(f.Complex()), verb)
792                 }
793         case reflect.String:
794                 p.fmtString(f.String(), verb, goSyntax)
795         case reflect.Map:
796                 if goSyntax {
797                         p.buf.WriteString(f.Type().String())
798                         if f.IsNil() {
799                                 p.buf.WriteString("(nil)")
800                                 break
801                         }
802                         p.buf.WriteByte('{')
803                 } else {
804                         p.buf.Write(mapBytes)
805                 }
806                 keys := f.MapKeys()
807                 for i, key := range keys {
808                         if i > 0 {
809                                 if goSyntax {
810                                         p.buf.Write(commaSpaceBytes)
811                                 } else {
812                                         p.buf.WriteByte(' ')
813                                 }
814                         }
815                         p.printValue(key, verb, plus, goSyntax, depth+1)
816                         p.buf.WriteByte(':')
817                         p.printValue(f.MapIndex(key), verb, plus, goSyntax, depth+1)
818                 }
819                 if goSyntax {
820                         p.buf.WriteByte('}')
821                 } else {
822                         p.buf.WriteByte(']')
823                 }
824         case reflect.Struct:
825                 if goSyntax {
826                         p.buf.WriteString(value.Type().String())
827                 }
828                 p.add('{')
829                 v := f
830                 t := v.Type()
831                 for i := 0; i < v.NumField(); i++ {
832                         if i > 0 {
833                                 if goSyntax {
834                                         p.buf.Write(commaSpaceBytes)
835                                 } else {
836                                         p.buf.WriteByte(' ')
837                                 }
838                         }
839                         if plus || goSyntax {
840                                 if f := t.Field(i); f.Name != "" {
841                                         p.buf.WriteString(f.Name)
842                                         p.buf.WriteByte(':')
843                                 }
844                         }
845                         p.printValue(getField(v, i), verb, plus, goSyntax, depth+1)
846                 }
847                 p.buf.WriteByte('}')
848         case reflect.Interface:
849                 value := f.Elem()
850                 if !value.IsValid() {
851                         if goSyntax {
852                                 p.buf.WriteString(f.Type().String())
853                                 p.buf.Write(nilParenBytes)
854                         } else {
855                                 p.buf.Write(nilAngleBytes)
856                         }
857                 } else {
858                         wasString = p.printValue(value, verb, plus, goSyntax, depth+1)
859                 }
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())
873                         }
874                         p.fmtBytes(bytes, verb, goSyntax, depth)
875                         wasString = verb == 's'
876                         break
877                 }
878                 if goSyntax {
879                         p.buf.WriteString(value.Type().String())
880                         if f.IsNil() {
881                                 p.buf.WriteString("(nil)")
882                                 break
883                         }
884                         p.buf.WriteByte('{')
885                 } else {
886                         p.buf.WriteByte('[')
887                 }
888                 for i := 0; i < f.Len(); i++ {
889                         if i > 0 {
890                                 if goSyntax {
891                                         p.buf.Write(commaSpaceBytes)
892                                 } else {
893                                         p.buf.WriteByte(' ')
894                                 }
895                         }
896                         p.printValue(f.Index(i), verb, plus, goSyntax, depth+1)
897                 }
898                 if goSyntax {
899                         p.buf.WriteByte('}')
900                 } else {
901                         p.buf.WriteByte(']')
902                 }
903         case reflect.Ptr:
904                 v := f.Pointer()
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:
910                                 p.buf.WriteByte('&')
911                                 p.printValue(a, verb, plus, goSyntax, depth+1)
912                                 break BigSwitch
913                         case reflect.Struct:
914                                 p.buf.WriteByte('&')
915                                 p.printValue(a, verb, plus, goSyntax, depth+1)
916                                 break BigSwitch
917                         }
918                 }
919                 if goSyntax {
920                         p.buf.WriteByte('(')
921                         p.buf.WriteString(value.Type().String())
922                         p.buf.WriteByte(')')
923                         p.buf.WriteByte('(')
924                         if v == 0 {
925                                 p.buf.Write(nilBytes)
926                         } else {
927                                 p.fmt0x64(uint64(v), true)
928                         }
929                         p.buf.WriteByte(')')
930                         break
931                 }
932                 if v == 0 {
933                         p.buf.Write(nilAngleBytes)
934                         break
935                 }
936                 p.fmt0x64(uint64(v), true)
937         case reflect.Chan, reflect.Func, reflect.UnsafePointer:
938                 p.fmtPointer(value, verb, goSyntax)
939         default:
940                 p.unknownType(f)
941         }
942         p.value = oldValue
943         return wasString
944 }
945
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
952         }
953         return
954 }
955
956 func (p *pp) doPrintf(format string, a []interface{}) {
957         end := len(format)
958         fieldnum := 0 // we process one field per non-trivial format
959         for i := 0; i < end; {
960                 lasti := i
961                 for i < end && format[i] != '%' {
962                         i++
963                 }
964                 if i > lasti {
965                         p.buf.WriteString(format[lasti:i])
966                 }
967                 if i >= end {
968                         // done processing format string
969                         break
970                 }
971
972                 // Process one verb
973                 i++
974                 // flags and widths
975                 p.fmt.clearflags()
976         F:
977                 for ; i < end; i++ {
978                         switch format[i] {
979                         case '#':
980                                 p.fmt.sharp = true
981                         case '0':
982                                 p.fmt.zero = true
983                         case '+':
984                                 p.fmt.plus = true
985                         case '-':
986                                 p.fmt.minus = true
987                         case ' ':
988                                 p.fmt.space = true
989                         default:
990                                 break F
991                         }
992                 }
993                 // do we have width?
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)
998                         }
999                 } else {
1000                         p.fmt.wid, p.fmt.widPresent, i = parsenum(format, i, end)
1001                 }
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)
1008                                 }
1009                         } else {
1010                                 p.fmt.prec, p.fmt.precPresent, i = parsenum(format, i+1, end)
1011                                 if !p.fmt.precPresent {
1012                                         p.fmt.prec = 0
1013                                         p.fmt.precPresent = true
1014                                 }
1015                         }
1016                 }
1017                 if i >= end {
1018                         p.buf.Write(noVerbBytes)
1019                         continue
1020                 }
1021                 c, w := utf8.DecodeRuneInString(format[i:])
1022                 i += w
1023                 // percent is special - absorbs no operand
1024                 if c == '%' {
1025                         p.buf.WriteByte('%') // We ignore width and prec.
1026                         continue
1027                 }
1028                 if fieldnum >= len(a) { // out of operands
1029                         p.buf.WriteByte('%')
1030                         p.add(c)
1031                         p.buf.Write(missingBytes)
1032                         continue
1033                 }
1034                 field := a[fieldnum]
1035                 fieldnum++
1036
1037                 goSyntax := c == 'v' && p.fmt.sharp
1038                 plus := c == 'v' && p.fmt.plus
1039                 p.printField(field, c, plus, goSyntax, 0)
1040         }
1041
1042         if fieldnum < len(a) {
1043                 p.buf.Write(extraBytes)
1044                 for ; fieldnum < len(a); fieldnum++ {
1045                         field := a[fieldnum]
1046                         if field != nil {
1047                                 p.buf.WriteString(reflect.TypeOf(field).String())
1048                                 p.buf.WriteByte('=')
1049                         }
1050                         p.printField(field, 'v', false, false, 0)
1051                         if fieldnum+1 < len(a) {
1052                                 p.buf.Write(commaSpaceBytes)
1053                         }
1054                 }
1055                 p.buf.WriteByte(')')
1056         }
1057 }
1058
1059 func (p *pp) doPrint(a []interface{}, addspace, addnewline bool) {
1060         prevString := false
1061         for fieldnum := 0; fieldnum < len(a); fieldnum++ {
1062                 p.fmt.clearflags()
1063                 // always add spaces if we're doing println
1064                 field := a[fieldnum]
1065                 if fieldnum > 0 {
1066                         isString := field != nil && reflect.TypeOf(field).Kind() == reflect.String
1067                         if addspace || !isString && !prevString {
1068                                 p.buf.WriteByte(' ')
1069                         }
1070                 }
1071                 prevString = p.printField(field, 'v', false, false, 0)
1072         }
1073         if addnewline {
1074                 p.buf.WriteByte('\n')
1075         }
1076 }