OSDN Git Service

Update Go library to last weekly.
[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         "io"
10         "os"
11         "reflect"
12         "sync"
13         "unicode"
14         "utf8"
15 )
16
17 // Some constants in the form of bytes, to avoid string overhead.
18 // Needlessly fastidious, I suppose.
19 var (
20         commaSpaceBytes = []byte(", ")
21         nilAngleBytes   = []byte("<nil>")
22         nilParenBytes   = []byte("(nil)")
23         nilBytes        = []byte("nil")
24         mapBytes        = []byte("map[")
25         missingBytes    = []byte("(MISSING)")
26         panicBytes      = []byte("(PANIC=")
27         extraBytes      = []byte("%!(EXTRA ")
28         irparenBytes    = []byte("i)")
29         bytesBytes      = []byte("[]byte{")
30         widthBytes      = []byte("%!(BADWIDTH)")
31         precBytes       = []byte("%!(BADPREC)")
32         noVerbBytes     = []byte("%!(NOVERB)")
33 )
34
35 // State represents the printer state passed to custom formatters.
36 // It provides access to the io.Writer interface plus information about
37 // the flags and options for the operand's format specifier.
38 type State interface {
39         // Write is the function to call to emit formatted output to be printed.
40         Write(b []byte) (ret int, err os.Error)
41         // Width returns the value of the width option and whether it has been set.
42         Width() (wid int, ok bool)
43         // Precision returns the value of the precision option and whether it has been set.
44         Precision() (prec int, ok bool)
45
46         // Flag returns whether the flag c, a character, has been set.
47         Flag(c int) bool
48 }
49
50 // Formatter is the interface implemented by values with a custom formatter.
51 // The implementation of Format may call Sprintf or Fprintf(f) etc.
52 // to generate its output.
53 type Formatter interface {
54         Format(f State, c int)
55 }
56
57 // Stringer is implemented by any value that has a String method,
58 // which defines the ``native'' format for that value.
59 // The String method is used to print values passed as an operand
60 // to a %s or %v format or to an unformatted printer such as Print.
61 type Stringer interface {
62         String() string
63 }
64
65 // GoStringer is implemented by any value that has a GoString method,
66 // which defines the Go syntax for that value.
67 // The GoString method is used to print values passed as an operand
68 // to a %#v format.
69 type GoStringer interface {
70         GoString() string
71 }
72
73 type pp struct {
74         n         int
75         panicking bool
76         buf       bytes.Buffer
77         // value holds the current item, as a reflect.Value, and will be
78         // the zero Value if the item has not been reflected.
79         value   reflect.Value
80         runeBuf [utf8.UTFMax]byte
81         fmt     fmt
82 }
83
84 // A cache holds a set of reusable objects.
85 // The slice is a stack (LIFO).
86 // If more are needed, the cache creates them by calling new.
87 type cache struct {
88         mu    sync.Mutex
89         saved []interface{}
90         new   func() interface{}
91 }
92
93 func (c *cache) put(x interface{}) {
94         c.mu.Lock()
95         if len(c.saved) < cap(c.saved) {
96                 c.saved = append(c.saved, x)
97         }
98         c.mu.Unlock()
99 }
100
101 func (c *cache) get() interface{} {
102         c.mu.Lock()
103         n := len(c.saved)
104         if n == 0 {
105                 c.mu.Unlock()
106                 return c.new()
107         }
108         x := c.saved[n-1]
109         c.saved = c.saved[0 : n-1]
110         c.mu.Unlock()
111         return x
112 }
113
114 func newCache(f func() interface{}) *cache {
115         return &cache{saved: make([]interface{}, 0, 100), new: f}
116 }
117
118 var ppFree = newCache(func() interface{} { return new(pp) })
119
120 // Allocate a new pp struct or grab a cached one.
121 func newPrinter() *pp {
122         p := ppFree.get().(*pp)
123         p.panicking = false
124         p.fmt.init(&p.buf)
125         return p
126 }
127
128 // Save used pp structs in ppFree; avoids an allocation per invocation.
129 func (p *pp) free() {
130         // Don't hold on to pp structs with large buffers.
131         if cap(p.buf.Bytes()) > 1024 {
132                 return
133         }
134         p.buf.Reset()
135         p.value = reflect.Value{}
136         ppFree.put(p)
137 }
138
139 func (p *pp) Width() (wid int, ok bool) { return p.fmt.wid, p.fmt.widPresent }
140
141 func (p *pp) Precision() (prec int, ok bool) { return p.fmt.prec, p.fmt.precPresent }
142
143 func (p *pp) Flag(b int) bool {
144         switch b {
145         case '-':
146                 return p.fmt.minus
147         case '+':
148                 return p.fmt.plus
149         case '#':
150                 return p.fmt.sharp
151         case ' ':
152                 return p.fmt.space
153         case '0':
154                 return p.fmt.zero
155         }
156         return false
157 }
158
159 func (p *pp) add(c int) {
160         p.buf.WriteRune(c)
161 }
162
163 // Implement Write so we can call Fprintf on a pp (through State), for
164 // recursive use in custom verbs.
165 func (p *pp) Write(b []byte) (ret int, err os.Error) {
166         return p.buf.Write(b)
167 }
168
169 // These routines end in 'f' and take a format string.
170
171 // Fprintf formats according to a format specifier and writes to w.
172 // It returns the number of bytes written and any write error encountered.
173 func Fprintf(w io.Writer, format string, a ...interface{}) (n int, err os.Error) {
174         p := newPrinter()
175         p.doPrintf(format, a)
176         n64, err := p.buf.WriteTo(w)
177         p.free()
178         return int(n64), err
179 }
180
181 // Printf formats according to a format specifier and writes to standard output.
182 // It returns the number of bytes written and any write error encountered.
183 func Printf(format string, a ...interface{}) (n int, err os.Error) {
184         return Fprintf(os.Stdout, format, a...)
185 }
186
187 // Sprintf formats according to a format specifier and returns the resulting string.
188 func Sprintf(format string, a ...interface{}) string {
189         p := newPrinter()
190         p.doPrintf(format, a)
191         s := p.buf.String()
192         p.free()
193         return s
194 }
195
196 // Errorf formats according to a format specifier and returns the string 
197 // as a value that satisfies os.Error.
198 func Errorf(format string, a ...interface{}) os.Error {
199         return os.NewError(Sprintf(format, a...))
200 }
201
202 // These routines do not take a format string
203
204 // Fprint formats using the default formats for its operands and writes to w.
205 // Spaces are added between operands when neither is a string.
206 // It returns the number of bytes written and any write error encountered.
207 func Fprint(w io.Writer, a ...interface{}) (n int, err os.Error) {
208         p := newPrinter()
209         p.doPrint(a, false, false)
210         n64, err := p.buf.WriteTo(w)
211         p.free()
212         return int(n64), err
213 }
214
215 // Print formats using the default formats for its operands and writes to standard output.
216 // Spaces are added between operands when neither is a string.
217 // It returns the number of bytes written and any write error encountered.
218 func Print(a ...interface{}) (n int, err os.Error) {
219         return Fprint(os.Stdout, a...)
220 }
221
222 // Sprint formats using the default formats for its operands and returns the resulting string.
223 // Spaces are added between operands when neither is a string.
224 func Sprint(a ...interface{}) string {
225         p := newPrinter()
226         p.doPrint(a, false, false)
227         s := p.buf.String()
228         p.free()
229         return s
230 }
231
232 // These routines end in 'ln', do not take a format string,
233 // always add spaces between operands, and add a newline
234 // after the last operand.
235
236 // Fprintln formats using the default formats for its operands and writes to w.
237 // Spaces are always added between operands and a newline is appended.
238 // It returns the number of bytes written and any write error encountered.
239 func Fprintln(w io.Writer, a ...interface{}) (n int, err os.Error) {
240         p := newPrinter()
241         p.doPrint(a, true, true)
242         n64, err := p.buf.WriteTo(w)
243         p.free()
244         return int(n64), err
245 }
246
247 // Println formats using the default formats for its operands and writes to standard output.
248 // Spaces are always added between operands and a newline is appended.
249 // It returns the number of bytes written and any write error encountered.
250 func Println(a ...interface{}) (n int, err os.Error) {
251         return Fprintln(os.Stdout, a...)
252 }
253
254 // Sprintln formats using the default formats for its operands and returns the resulting string.
255 // Spaces are always added between operands and a newline is appended.
256 func Sprintln(a ...interface{}) string {
257         p := newPrinter()
258         p.doPrint(a, true, true)
259         s := p.buf.String()
260         p.free()
261         return s
262 }
263
264 // Get the i'th arg of the struct value.
265 // If the arg itself is an interface, return a value for
266 // the thing inside the interface, not the interface itself.
267 func getField(v reflect.Value, i int) reflect.Value {
268         val := v.Field(i)
269         if val.Kind() == reflect.Interface && !val.IsNil() {
270                 val = val.Elem()
271         }
272         return val
273 }
274
275 // Convert ASCII to integer.  n is 0 (and got is false) if no number present.
276 func parsenum(s string, start, end int) (num int, isnum bool, newi int) {
277         if start >= end {
278                 return 0, false, end
279         }
280         for newi = start; newi < end && '0' <= s[newi] && s[newi] <= '9'; newi++ {
281                 num = num*10 + int(s[newi]-'0')
282                 isnum = true
283         }
284         return
285 }
286
287 func (p *pp) unknownType(v interface{}) {
288         if v == nil {
289                 p.buf.Write(nilAngleBytes)
290                 return
291         }
292         p.buf.WriteByte('?')
293         p.buf.WriteString(reflect.TypeOf(v).String())
294         p.buf.WriteByte('?')
295 }
296
297 func (p *pp) badVerb(verb int, val interface{}) {
298         p.add('%')
299         p.add('!')
300         p.add(verb)
301         p.add('(')
302         switch {
303         case val != nil:
304                 p.buf.WriteString(reflect.TypeOf(val).String())
305                 p.add('=')
306                 p.printField(val, 'v', false, false, 0)
307         case p.value.IsValid():
308                 p.buf.WriteString(p.value.Type().String())
309                 p.add('=')
310                 p.printValue(p.value, 'v', false, false, 0)
311         default:
312                 p.buf.Write(nilAngleBytes)
313         }
314         p.add(')')
315 }
316
317 func (p *pp) fmtBool(v bool, verb int, value interface{}) {
318         switch verb {
319         case 't', 'v':
320                 p.fmt.fmt_boolean(v)
321         default:
322                 p.badVerb(verb, value)
323         }
324 }
325
326 // fmtC formats a rune for the 'c' format.
327 func (p *pp) fmtC(c int64) {
328         rune := int(c) // Check for overflow.
329         if int64(rune) != c {
330                 rune = utf8.RuneError
331         }
332         w := utf8.EncodeRune(p.runeBuf[0:utf8.UTFMax], rune)
333         p.fmt.pad(p.runeBuf[0:w])
334 }
335
336 func (p *pp) fmtInt64(v int64, verb int, value interface{}) {
337         switch verb {
338         case 'b':
339                 p.fmt.integer(v, 2, signed, ldigits)
340         case 'c':
341                 p.fmtC(v)
342         case 'd', 'v':
343                 p.fmt.integer(v, 10, signed, ldigits)
344         case 'o':
345                 p.fmt.integer(v, 8, signed, ldigits)
346         case 'q':
347                 if 0 <= v && v <= unicode.MaxRune {
348                         p.fmt.fmt_qc(v)
349                 } else {
350                         p.badVerb(verb, value)
351                 }
352         case 'x':
353                 p.fmt.integer(v, 16, signed, ldigits)
354         case 'U':
355                 p.fmtUnicode(v)
356         case 'X':
357                 p.fmt.integer(v, 16, signed, udigits)
358         default:
359                 p.badVerb(verb, value)
360         }
361 }
362
363 // fmt0x64 formats a uint64 in hexadecimal and prefixes it with 0x or
364 // not, as requested, by temporarily setting the sharp flag.
365 func (p *pp) fmt0x64(v uint64, leading0x bool) {
366         sharp := p.fmt.sharp
367         p.fmt.sharp = leading0x
368         p.fmt.integer(int64(v), 16, unsigned, ldigits)
369         p.fmt.sharp = sharp
370 }
371
372 // fmtUnicode formats a uint64 in U+1234 form by
373 // temporarily turning on the unicode flag and tweaking the precision.
374 func (p *pp) fmtUnicode(v int64) {
375         precPresent := p.fmt.precPresent
376         sharp := p.fmt.sharp
377         p.fmt.sharp = false
378         prec := p.fmt.prec
379         if !precPresent {
380                 // If prec is already set, leave it alone; otherwise 4 is minimum.
381                 p.fmt.prec = 4
382                 p.fmt.precPresent = true
383         }
384         p.fmt.unicode = true // turn on U+
385         p.fmt.uniQuote = sharp
386         p.fmt.integer(int64(v), 16, unsigned, udigits)
387         p.fmt.unicode = false
388         p.fmt.uniQuote = false
389         p.fmt.prec = prec
390         p.fmt.precPresent = precPresent
391         p.fmt.sharp = sharp
392 }
393
394 func (p *pp) fmtUint64(v uint64, verb int, goSyntax bool, value interface{}) {
395         switch verb {
396         case 'b':
397                 p.fmt.integer(int64(v), 2, unsigned, ldigits)
398         case 'c':
399                 p.fmtC(int64(v))
400         case 'd':
401                 p.fmt.integer(int64(v), 10, unsigned, ldigits)
402         case 'v':
403                 if goSyntax {
404                         p.fmt0x64(v, true)
405                 } else {
406                         p.fmt.integer(int64(v), 10, unsigned, ldigits)
407                 }
408         case 'o':
409                 p.fmt.integer(int64(v), 8, unsigned, ldigits)
410         case 'q':
411                 if 0 <= v && v <= unicode.MaxRune {
412                         p.fmt.fmt_qc(int64(v))
413                 } else {
414                         p.badVerb(verb, value)
415                 }
416         case 'x':
417                 p.fmt.integer(int64(v), 16, unsigned, ldigits)
418         case 'X':
419                 p.fmt.integer(int64(v), 16, unsigned, udigits)
420         case 'U':
421                 p.fmtUnicode(int64(v))
422         default:
423                 p.badVerb(verb, value)
424         }
425 }
426
427 func (p *pp) fmtFloat32(v float32, verb int, value interface{}) {
428         switch verb {
429         case 'b':
430                 p.fmt.fmt_fb32(v)
431         case 'e':
432                 p.fmt.fmt_e32(v)
433         case 'E':
434                 p.fmt.fmt_E32(v)
435         case 'f':
436                 p.fmt.fmt_f32(v)
437         case 'g', 'v':
438                 p.fmt.fmt_g32(v)
439         case 'G':
440                 p.fmt.fmt_G32(v)
441         default:
442                 p.badVerb(verb, value)
443         }
444 }
445
446 func (p *pp) fmtFloat64(v float64, verb int, value interface{}) {
447         switch verb {
448         case 'b':
449                 p.fmt.fmt_fb64(v)
450         case 'e':
451                 p.fmt.fmt_e64(v)
452         case 'E':
453                 p.fmt.fmt_E64(v)
454         case 'f':
455                 p.fmt.fmt_f64(v)
456         case 'g', 'v':
457                 p.fmt.fmt_g64(v)
458         case 'G':
459                 p.fmt.fmt_G64(v)
460         default:
461                 p.badVerb(verb, value)
462         }
463 }
464
465 func (p *pp) fmtComplex64(v complex64, verb int, value interface{}) {
466         switch verb {
467         case 'e', 'E', 'f', 'F', 'g', 'G':
468                 p.fmt.fmt_c64(v, verb)
469         case 'v':
470                 p.fmt.fmt_c64(v, 'g')
471         default:
472                 p.badVerb(verb, value)
473         }
474 }
475
476 func (p *pp) fmtComplex128(v complex128, verb int, value interface{}) {
477         switch verb {
478         case 'e', 'E', 'f', 'F', 'g', 'G':
479                 p.fmt.fmt_c128(v, verb)
480         case 'v':
481                 p.fmt.fmt_c128(v, 'g')
482         default:
483                 p.badVerb(verb, value)
484         }
485 }
486
487 func (p *pp) fmtString(v string, verb int, goSyntax bool, value interface{}) {
488         switch verb {
489         case 'v':
490                 if goSyntax {
491                         p.fmt.fmt_q(v)
492                 } else {
493                         p.fmt.fmt_s(v)
494                 }
495         case 's':
496                 p.fmt.fmt_s(v)
497         case 'x':
498                 p.fmt.fmt_sx(v)
499         case 'X':
500                 p.fmt.fmt_sX(v)
501         case 'q':
502                 p.fmt.fmt_q(v)
503         default:
504                 p.badVerb(verb, value)
505         }
506 }
507
508 func (p *pp) fmtBytes(v []byte, verb int, goSyntax bool, depth int, value interface{}) {
509         if verb == 'v' || verb == 'd' {
510                 if goSyntax {
511                         p.buf.Write(bytesBytes)
512                 } else {
513                         p.buf.WriteByte('[')
514                 }
515                 for i, c := range v {
516                         if i > 0 {
517                                 if goSyntax {
518                                         p.buf.Write(commaSpaceBytes)
519                                 } else {
520                                         p.buf.WriteByte(' ')
521                                 }
522                         }
523                         p.printField(c, 'v', p.fmt.plus, goSyntax, depth+1)
524                 }
525                 if goSyntax {
526                         p.buf.WriteByte('}')
527                 } else {
528                         p.buf.WriteByte(']')
529                 }
530                 return
531         }
532         s := string(v)
533         switch verb {
534         case 's':
535                 p.fmt.fmt_s(s)
536         case 'x':
537                 p.fmt.fmt_sx(s)
538         case 'X':
539                 p.fmt.fmt_sX(s)
540         case 'q':
541                 p.fmt.fmt_q(s)
542         default:
543                 p.badVerb(verb, value)
544         }
545 }
546
547 func (p *pp) fmtPointer(field interface{}, value reflect.Value, verb int, goSyntax bool) {
548         var u uintptr
549         switch value.Kind() {
550         case reflect.Chan, reflect.Func, reflect.Map, reflect.Ptr, reflect.Slice, reflect.UnsafePointer:
551                 u = value.Pointer()
552         default:
553                 p.badVerb(verb, field)
554                 return
555         }
556         if goSyntax {
557                 p.add('(')
558                 p.buf.WriteString(value.Type().String())
559                 p.add(')')
560                 p.add('(')
561                 if u == 0 {
562                         p.buf.Write(nilBytes)
563                 } else {
564                         p.fmt0x64(uint64(u), true)
565                 }
566                 p.add(')')
567         } else {
568                 p.fmt0x64(uint64(u), !p.fmt.sharp)
569         }
570 }
571
572 var (
573         intBits     = reflect.TypeOf(0).Bits()
574         floatBits   = reflect.TypeOf(0.0).Bits()
575         complexBits = reflect.TypeOf(1i).Bits()
576         uintptrBits = reflect.TypeOf(uintptr(0)).Bits()
577 )
578
579 func (p *pp) catchPanic(val interface{}, verb int) {
580         if err := recover(); err != nil {
581                 // If it's a nil pointer, just say "<nil>". The likeliest causes are a
582                 // Stringer that fails to guard against nil or a nil pointer for a
583                 // value receiver, and in either case, "<nil>" is a nice result.
584                 if v := reflect.ValueOf(val); v.Kind() == reflect.Ptr && v.IsNil() {
585                         p.buf.Write(nilAngleBytes)
586                         return
587                 }
588                 // Otherwise print a concise panic message. Most of the time the panic
589                 // value will print itself nicely.
590                 if p.panicking {
591                         // Nested panics; the recursion in printField cannot succeed.
592                         panic(err)
593                 }
594                 p.buf.WriteByte('%')
595                 p.add(verb)
596                 p.buf.Write(panicBytes)
597                 p.panicking = true
598                 p.printField(err, 'v', false, false, 0)
599                 p.panicking = false
600                 p.buf.WriteByte(')')
601         }
602 }
603
604 func (p *pp) handleMethods(field interface{}, verb int, plus, goSyntax bool, depth int) (wasString, handled bool) {
605         // Is it a Formatter?
606         if formatter, ok := field.(Formatter); ok {
607                 handled = true
608                 wasString = false
609                 defer p.catchPanic(field, verb)
610                 formatter.Format(p, verb)
611                 return
612         }
613         // Must not touch flags before Formatter looks at them.
614         if plus {
615                 p.fmt.plus = false
616         }
617
618         // If we're doing Go syntax and the field knows how to supply it, take care of it now.
619         if goSyntax {
620                 p.fmt.sharp = false
621                 if stringer, ok := field.(GoStringer); ok {
622                         wasString = false
623                         handled = true
624                         defer p.catchPanic(field, verb)
625                         // Print the result of GoString unadorned.
626                         p.fmtString(stringer.GoString(), 's', false, field)
627                         return
628                 }
629         } else {
630                 // Is it a Stringer?
631                 if stringer, ok := field.(Stringer); ok {
632                         wasString = false
633                         handled = true
634                         defer p.catchPanic(field, verb)
635                         p.printField(stringer.String(), verb, plus, false, depth)
636                         return
637                 }
638         }
639         handled = false
640         return
641 }
642
643 func (p *pp) printField(field interface{}, verb int, plus, goSyntax bool, depth int) (wasString bool) {
644         if field == nil {
645                 if verb == 'T' || verb == 'v' {
646                         p.buf.Write(nilAngleBytes)
647                 } else {
648                         p.badVerb(verb, field)
649                 }
650                 return false
651         }
652
653         // Special processing considerations.
654         // %T (the value's type) and %p (its address) are special; we always do them first.
655         switch verb {
656         case 'T':
657                 p.printField(reflect.TypeOf(field).String(), 's', false, false, 0)
658                 return false
659         case 'p':
660                 p.fmtPointer(field, reflect.ValueOf(field), verb, goSyntax)
661                 return false
662         }
663
664         if wasString, handled := p.handleMethods(field, verb, plus, goSyntax, depth); handled {
665                 return wasString
666         }
667
668         // Some types can be done without reflection.
669         switch f := field.(type) {
670         case bool:
671                 p.fmtBool(f, verb, field)
672                 return false
673         case float32:
674                 p.fmtFloat32(f, verb, field)
675                 return false
676         case float64:
677                 p.fmtFloat64(f, verb, field)
678                 return false
679         case complex64:
680                 p.fmtComplex64(complex64(f), verb, field)
681                 return false
682         case complex128:
683                 p.fmtComplex128(f, verb, field)
684                 return false
685         case int:
686                 p.fmtInt64(int64(f), verb, field)
687                 return false
688         case int8:
689                 p.fmtInt64(int64(f), verb, field)
690                 return false
691         case int16:
692                 p.fmtInt64(int64(f), verb, field)
693                 return false
694         case int32:
695                 p.fmtInt64(int64(f), verb, field)
696                 return false
697         case int64:
698                 p.fmtInt64(f, verb, field)
699                 return false
700         case uint:
701                 p.fmtUint64(uint64(f), verb, goSyntax, field)
702                 return false
703         case uint8:
704                 p.fmtUint64(uint64(f), verb, goSyntax, field)
705                 return false
706         case uint16:
707                 p.fmtUint64(uint64(f), verb, goSyntax, field)
708                 return false
709         case uint32:
710                 p.fmtUint64(uint64(f), verb, goSyntax, field)
711                 return false
712         case uint64:
713                 p.fmtUint64(f, verb, goSyntax, field)
714                 return false
715         case uintptr:
716                 p.fmtUint64(uint64(f), verb, goSyntax, field)
717                 return false
718         case string:
719                 p.fmtString(f, verb, goSyntax, field)
720                 return verb == 's' || verb == 'v'
721         case []byte:
722                 p.fmtBytes(f, verb, goSyntax, depth, field)
723                 return verb == 's'
724         }
725
726         // Need to use reflection
727         return p.printReflectValue(reflect.ValueOf(field), verb, plus, goSyntax, depth)
728 }
729
730 // printValue is like printField but starts with a reflect value, not an interface{} value.
731 func (p *pp) printValue(value reflect.Value, verb int, plus, goSyntax bool, depth int) (wasString bool) {
732         if !value.IsValid() {
733                 if verb == 'T' || verb == 'v' {
734                         p.buf.Write(nilAngleBytes)
735                 } else {
736                         p.badVerb(verb, nil)
737                 }
738                 return false
739         }
740
741         // Special processing considerations.
742         // %T (the value's type) and %p (its address) are special; we always do them first.
743         switch verb {
744         case 'T':
745                 p.printField(value.Type().String(), 's', false, false, 0)
746                 return false
747         case 'p':
748                 p.fmtPointer(nil, value, verb, goSyntax)
749                 return false
750         }
751
752         // Handle values with special methods.
753         // Call always, even when field == nil, because handleMethods clears p.fmt.plus for us.
754         var field interface{}
755         if value.CanInterface() {
756                 field = value.Interface()
757         }
758         if wasString, handled := p.handleMethods(field, verb, plus, goSyntax, depth); handled {
759                 return wasString
760         }
761
762         return p.printReflectValue(value, verb, plus, goSyntax, depth)
763 }
764
765 // printReflectValue is the fallback for both printField and printValue.
766 // It uses reflect to print the value.
767 func (p *pp) printReflectValue(value reflect.Value, verb int, plus, goSyntax bool, depth int) (wasString bool) {
768         oldValue := p.value
769         p.value = value
770 BigSwitch:
771         switch f := value; f.Kind() {
772         case reflect.Bool:
773                 p.fmtBool(f.Bool(), verb, nil)
774         case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
775                 p.fmtInt64(f.Int(), verb, nil)
776         case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
777                 p.fmtUint64(uint64(f.Uint()), verb, goSyntax, nil)
778         case reflect.Float32, reflect.Float64:
779                 if f.Type().Size() == 4 {
780                         p.fmtFloat32(float32(f.Float()), verb, nil)
781                 } else {
782                         p.fmtFloat64(float64(f.Float()), verb, nil)
783                 }
784         case reflect.Complex64, reflect.Complex128:
785                 if f.Type().Size() == 8 {
786                         p.fmtComplex64(complex64(f.Complex()), verb, nil)
787                 } else {
788                         p.fmtComplex128(complex128(f.Complex()), verb, nil)
789                 }
790         case reflect.String:
791                 p.fmtString(f.String(), verb, goSyntax, nil)
792         case reflect.Map:
793                 if goSyntax {
794                         p.buf.WriteString(f.Type().String())
795                         p.buf.WriteByte('{')
796                 } else {
797                         p.buf.Write(mapBytes)
798                 }
799                 keys := f.MapKeys()
800                 for i, key := range keys {
801                         if i > 0 {
802                                 if goSyntax {
803                                         p.buf.Write(commaSpaceBytes)
804                                 } else {
805                                         p.buf.WriteByte(' ')
806                                 }
807                         }
808                         p.printValue(key, verb, plus, goSyntax, depth+1)
809                         p.buf.WriteByte(':')
810                         p.printValue(f.MapIndex(key), verb, plus, goSyntax, depth+1)
811                 }
812                 if goSyntax {
813                         p.buf.WriteByte('}')
814                 } else {
815                         p.buf.WriteByte(']')
816                 }
817         case reflect.Struct:
818                 if goSyntax {
819                         p.buf.WriteString(value.Type().String())
820                 }
821                 p.add('{')
822                 v := f
823                 t := v.Type()
824                 for i := 0; i < v.NumField(); i++ {
825                         if i > 0 {
826                                 if goSyntax {
827                                         p.buf.Write(commaSpaceBytes)
828                                 } else {
829                                         p.buf.WriteByte(' ')
830                                 }
831                         }
832                         if plus || goSyntax {
833                                 if f := t.Field(i); f.Name != "" {
834                                         p.buf.WriteString(f.Name)
835                                         p.buf.WriteByte(':')
836                                 }
837                         }
838                         p.printValue(getField(v, i), verb, plus, goSyntax, depth+1)
839                 }
840                 p.buf.WriteByte('}')
841         case reflect.Interface:
842                 value := f.Elem()
843                 if !value.IsValid() {
844                         if goSyntax {
845                                 p.buf.WriteString(value.Type().String())
846                                 p.buf.Write(nilParenBytes)
847                         } else {
848                                 p.buf.Write(nilAngleBytes)
849                         }
850                 } else {
851                         wasString = p.printValue(value, verb, plus, goSyntax, depth+1)
852                 }
853         case reflect.Array, reflect.Slice:
854                 // Byte slices are special.
855                 if f.Type().Elem().Kind() == reflect.Uint8 {
856                         // We know it's a slice of bytes, but we also know it does not have static type
857                         // []byte, or it would have been caught above.  Therefore we cannot convert
858                         // it directly in the (slightly) obvious way: f.Interface().([]byte); it doesn't have
859                         // that type, and we can't write an expression of the right type and do a
860                         // conversion because we don't have a static way to write the right type.
861                         // So we build a slice by hand.  This is a rare case but it would be nice
862                         // if reflection could help a little more.
863                         bytes := make([]byte, f.Len())
864                         for i := range bytes {
865                                 bytes[i] = byte(f.Index(i).Uint())
866                         }
867                         p.fmtBytes(bytes, verb, goSyntax, depth, nil)
868                         wasString = verb == 's'
869                         break
870                 }
871                 if goSyntax {
872                         p.buf.WriteString(value.Type().String())
873                         p.buf.WriteByte('{')
874                 } else {
875                         p.buf.WriteByte('[')
876                 }
877                 for i := 0; i < f.Len(); i++ {
878                         if i > 0 {
879                                 if goSyntax {
880                                         p.buf.Write(commaSpaceBytes)
881                                 } else {
882                                         p.buf.WriteByte(' ')
883                                 }
884                         }
885                         p.printValue(f.Index(i), verb, plus, goSyntax, depth+1)
886                 }
887                 if goSyntax {
888                         p.buf.WriteByte('}')
889                 } else {
890                         p.buf.WriteByte(']')
891                 }
892         case reflect.Ptr:
893                 v := f.Pointer()
894                 // pointer to array or slice or struct?  ok at top level
895                 // but not embedded (avoid loops)
896                 if v != 0 && depth == 0 {
897                         switch a := f.Elem(); a.Kind() {
898                         case reflect.Array, reflect.Slice:
899                                 p.buf.WriteByte('&')
900                                 p.printValue(a, verb, plus, goSyntax, depth+1)
901                                 break BigSwitch
902                         case reflect.Struct:
903                                 p.buf.WriteByte('&')
904                                 p.printValue(a, verb, plus, goSyntax, depth+1)
905                                 break BigSwitch
906                         }
907                 }
908                 if goSyntax {
909                         p.buf.WriteByte('(')
910                         p.buf.WriteString(value.Type().String())
911                         p.buf.WriteByte(')')
912                         p.buf.WriteByte('(')
913                         if v == 0 {
914                                 p.buf.Write(nilBytes)
915                         } else {
916                                 p.fmt0x64(uint64(v), true)
917                         }
918                         p.buf.WriteByte(')')
919                         break
920                 }
921                 if v == 0 {
922                         p.buf.Write(nilAngleBytes)
923                         break
924                 }
925                 p.fmt0x64(uint64(v), true)
926         case reflect.Chan, reflect.Func, reflect.UnsafePointer:
927                 p.fmtPointer(nil, value, verb, goSyntax)
928         default:
929                 p.unknownType(f)
930         }
931         p.value = oldValue
932         return wasString
933 }
934
935 // intFromArg gets the fieldnumth element of a. On return, isInt reports whether the argument has type int.
936 func intFromArg(a []interface{}, end, i, fieldnum int) (num int, isInt bool, newi, newfieldnum int) {
937         newi, newfieldnum = end, fieldnum
938         if i < end && fieldnum < len(a) {
939                 num, isInt = a[fieldnum].(int)
940                 newi, newfieldnum = i+1, fieldnum+1
941         }
942         return
943 }
944
945 func (p *pp) doPrintf(format string, a []interface{}) {
946         end := len(format)
947         fieldnum := 0 // we process one field per non-trivial format
948         for i := 0; i < end; {
949                 lasti := i
950                 for i < end && format[i] != '%' {
951                         i++
952                 }
953                 if i > lasti {
954                         p.buf.WriteString(format[lasti:i])
955                 }
956                 if i >= end {
957                         // done processing format string
958                         break
959                 }
960
961                 // Process one verb
962                 i++
963                 // flags and widths
964                 p.fmt.clearflags()
965         F:
966                 for ; i < end; i++ {
967                         switch format[i] {
968                         case '#':
969                                 p.fmt.sharp = true
970                         case '0':
971                                 p.fmt.zero = true
972                         case '+':
973                                 p.fmt.plus = true
974                         case '-':
975                                 p.fmt.minus = true
976                         case ' ':
977                                 p.fmt.space = true
978                         default:
979                                 break F
980                         }
981                 }
982                 // do we have width?
983                 if i < end && format[i] == '*' {
984                         p.fmt.wid, p.fmt.widPresent, i, fieldnum = intFromArg(a, end, i, fieldnum)
985                         if !p.fmt.widPresent {
986                                 p.buf.Write(widthBytes)
987                         }
988                 } else {
989                         p.fmt.wid, p.fmt.widPresent, i = parsenum(format, i, end)
990                 }
991                 // do we have precision?
992                 if i < end && format[i] == '.' {
993                         if format[i+1] == '*' {
994                                 p.fmt.prec, p.fmt.precPresent, i, fieldnum = intFromArg(a, end, i+1, fieldnum)
995                                 if !p.fmt.precPresent {
996                                         p.buf.Write(precBytes)
997                                 }
998                         } else {
999                                 p.fmt.prec, p.fmt.precPresent, i = parsenum(format, i+1, end)
1000                                 if !p.fmt.precPresent {
1001                                         p.fmt.prec = 0
1002                                         p.fmt.precPresent = true
1003                                 }
1004                         }
1005                 }
1006                 if i >= end {
1007                         p.buf.Write(noVerbBytes)
1008                         continue
1009                 }
1010                 c, w := utf8.DecodeRuneInString(format[i:])
1011                 i += w
1012                 // percent is special - absorbs no operand
1013                 if c == '%' {
1014                         p.buf.WriteByte('%') // We ignore width and prec.
1015                         continue
1016                 }
1017                 if fieldnum >= len(a) { // out of operands
1018                         p.buf.WriteByte('%')
1019                         p.add(c)
1020                         p.buf.Write(missingBytes)
1021                         continue
1022                 }
1023                 field := a[fieldnum]
1024                 fieldnum++
1025
1026                 goSyntax := c == 'v' && p.fmt.sharp
1027                 plus := c == 'v' && p.fmt.plus
1028                 p.printField(field, c, plus, goSyntax, 0)
1029         }
1030
1031         if fieldnum < len(a) {
1032                 p.buf.Write(extraBytes)
1033                 for ; fieldnum < len(a); fieldnum++ {
1034                         field := a[fieldnum]
1035                         if field != nil {
1036                                 p.buf.WriteString(reflect.TypeOf(field).String())
1037                                 p.buf.WriteByte('=')
1038                         }
1039                         p.printField(field, 'v', false, false, 0)
1040                         if fieldnum+1 < len(a) {
1041                                 p.buf.Write(commaSpaceBytes)
1042                         }
1043                 }
1044                 p.buf.WriteByte(')')
1045         }
1046 }
1047
1048 func (p *pp) doPrint(a []interface{}, addspace, addnewline bool) {
1049         prevString := false
1050         for fieldnum := 0; fieldnum < len(a); fieldnum++ {
1051                 p.fmt.clearflags()
1052                 // always add spaces if we're doing println
1053                 field := a[fieldnum]
1054                 if fieldnum > 0 {
1055                         isString := field != nil && reflect.TypeOf(field).Kind() == reflect.String
1056                         if addspace || !isString && !prevString {
1057                                 p.buf.WriteByte(' ')
1058                         }
1059                 }
1060                 prevString = p.printField(field, 'v', false, false, 0)
1061         }
1062         if addnewline {
1063                 p.buf.WriteByte('\n')
1064         }
1065 }