libgo: Merge from revision 18783:00cce3a34d7e of master library.
[official-gcc.git] / libgo / go / fmt / print.go
blob2f13bcd95e971415401e75a10b0f7d36d209d930
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.
5 package fmt
7 import (
8 "errors"
9 "io"
10 "os"
11 "reflect"
12 "sync"
13 "unicode/utf8"
16 // Some constants in the form of bytes, to avoid string overhead.
17 // Needlessly fastidious, I suppose.
18 var (
19 commaSpaceBytes = []byte(", ")
20 nilAngleBytes = []byte("<nil>")
21 nilParenBytes = []byte("(nil)")
22 nilBytes = []byte("nil")
23 mapBytes = []byte("map[")
24 percentBangBytes = []byte("%!")
25 missingBytes = []byte("(MISSING)")
26 badIndexBytes = []byte("(BADINDEX)")
27 panicBytes = []byte("(PANIC=")
28 extraBytes = []byte("%!(EXTRA ")
29 irparenBytes = []byte("i)")
30 bytesBytes = []byte("[]byte{")
31 badWidthBytes = []byte("%!(BADWIDTH)")
32 badPrecBytes = []byte("%!(BADPREC)")
33 noVerbBytes = []byte("%!(NOVERB)")
36 // State represents the printer state passed to custom formatters.
37 // It provides access to the io.Writer interface plus information about
38 // the flags and options for the operand's format specifier.
39 type State interface {
40 // Write is the function to call to emit formatted output to be printed.
41 Write(b []byte) (ret int, err error)
42 // Width returns the value of the width option and whether it has been set.
43 Width() (wid int, ok bool)
44 // Precision returns the value of the precision option and whether it has been set.
45 Precision() (prec int, ok bool)
47 // Flag reports whether the flag c, a character, has been set.
48 Flag(c int) bool
51 // Formatter is the interface implemented by values with a custom formatter.
52 // The implementation of Format may call Sprint(f) or Fprint(f) etc.
53 // to generate its output.
54 type Formatter interface {
55 Format(f State, c rune)
58 // Stringer is implemented by any value that has a String method,
59 // which defines the ``native'' format for that value.
60 // The String method is used to print values passed as an operand
61 // to any format that accepts a string or to an unformatted printer
62 // such as Print.
63 type Stringer interface {
64 String() string
67 // GoStringer is implemented by any value that has a GoString method,
68 // which defines the Go syntax for that value.
69 // The GoString method is used to print values passed as an operand
70 // to a %#v format.
71 type GoStringer interface {
72 GoString() string
75 // Use simple []byte instead of bytes.Buffer to avoid large dependency.
76 type buffer []byte
78 func (b *buffer) Write(p []byte) (n int, err error) {
79 *b = append(*b, p...)
80 return len(p), nil
83 func (b *buffer) WriteString(s string) (n int, err error) {
84 *b = append(*b, s...)
85 return len(s), nil
88 func (b *buffer) WriteByte(c byte) error {
89 *b = append(*b, c)
90 return nil
93 func (bp *buffer) WriteRune(r rune) error {
94 if r < utf8.RuneSelf {
95 *bp = append(*bp, byte(r))
96 return nil
99 b := *bp
100 n := len(b)
101 for n+utf8.UTFMax > cap(b) {
102 b = append(b, 0)
104 w := utf8.EncodeRune(b[n:n+utf8.UTFMax], r)
105 *bp = b[:n+w]
106 return nil
109 type pp struct {
110 n int
111 panicking bool
112 erroring bool // printing an error condition
113 buf buffer
114 // arg holds the current item, as an interface{}.
115 arg interface{}
116 // value holds the current item, as a reflect.Value, and will be
117 // the zero Value if the item has not been reflected.
118 value reflect.Value
119 // reordered records whether the format string used argument reordering.
120 reordered bool
121 // goodArgNum records whether the most recent reordering directive was valid.
122 goodArgNum bool
123 runeBuf [utf8.UTFMax]byte
124 fmt fmt
127 var ppFree = sync.Pool{
128 New: func() interface{} { return new(pp) },
131 // newPrinter allocates a new pp struct or grab a cached one.
132 func newPrinter() *pp {
133 p := ppFree.Get().(*pp)
134 p.panicking = false
135 p.erroring = false
136 p.fmt.init(&p.buf)
137 return p
140 // free saves used pp structs in ppFree; avoids an allocation per invocation.
141 func (p *pp) free() {
142 // Don't hold on to pp structs with large buffers.
143 if cap(p.buf) > 1024 {
144 return
146 p.buf = p.buf[:0]
147 p.arg = nil
148 p.value = reflect.Value{}
149 ppFree.Put(p)
152 func (p *pp) Width() (wid int, ok bool) { return p.fmt.wid, p.fmt.widPresent }
154 func (p *pp) Precision() (prec int, ok bool) { return p.fmt.prec, p.fmt.precPresent }
156 func (p *pp) Flag(b int) bool {
157 switch b {
158 case '-':
159 return p.fmt.minus
160 case '+':
161 return p.fmt.plus
162 case '#':
163 return p.fmt.sharp
164 case ' ':
165 return p.fmt.space
166 case '0':
167 return p.fmt.zero
169 return false
172 func (p *pp) add(c rune) {
173 p.buf.WriteRune(c)
176 // Implement Write so we can call Fprintf on a pp (through State), for
177 // recursive use in custom verbs.
178 func (p *pp) Write(b []byte) (ret int, err error) {
179 return p.buf.Write(b)
182 // These routines end in 'f' and take a format string.
184 // Fprintf formats according to a format specifier and writes to w.
185 // It returns the number of bytes written and any write error encountered.
186 func Fprintf(w io.Writer, format string, a ...interface{}) (n int, err error) {
187 p := newPrinter()
188 p.doPrintf(format, a)
189 n, err = w.Write(p.buf)
190 p.free()
191 return
194 // Printf formats according to a format specifier and writes to standard output.
195 // It returns the number of bytes written and any write error encountered.
196 func Printf(format string, a ...interface{}) (n int, err error) {
197 return Fprintf(os.Stdout, format, a...)
200 // Sprintf formats according to a format specifier and returns the resulting string.
201 func Sprintf(format string, a ...interface{}) string {
202 p := newPrinter()
203 p.doPrintf(format, a)
204 s := string(p.buf)
205 p.free()
206 return s
209 // Errorf formats according to a format specifier and returns the string
210 // as a value that satisfies error.
211 func Errorf(format string, a ...interface{}) error {
212 return errors.New(Sprintf(format, a...))
215 // These routines do not take a format string
217 // Fprint formats using the default formats for its operands and writes to w.
218 // Spaces are added between operands when neither is a string.
219 // It returns the number of bytes written and any write error encountered.
220 func Fprint(w io.Writer, a ...interface{}) (n int, err error) {
221 p := newPrinter()
222 p.doPrint(a, false, false)
223 n, err = w.Write(p.buf)
224 p.free()
225 return
228 // Print formats using the default formats for its operands and writes to standard output.
229 // Spaces are added between operands when neither is a string.
230 // It returns the number of bytes written and any write error encountered.
231 func Print(a ...interface{}) (n int, err error) {
232 return Fprint(os.Stdout, a...)
235 // Sprint formats using the default formats for its operands and returns the resulting string.
236 // Spaces are added between operands when neither is a string.
237 func Sprint(a ...interface{}) string {
238 p := newPrinter()
239 p.doPrint(a, false, false)
240 s := string(p.buf)
241 p.free()
242 return s
245 // These routines end in 'ln', do not take a format string,
246 // always add spaces between operands, and add a newline
247 // after the last operand.
249 // Fprintln formats using the default formats for its operands and writes to w.
250 // Spaces are always added between operands and a newline is appended.
251 // It returns the number of bytes written and any write error encountered.
252 func Fprintln(w io.Writer, a ...interface{}) (n int, err error) {
253 p := newPrinter()
254 p.doPrint(a, true, true)
255 n, err = w.Write(p.buf)
256 p.free()
257 return
260 // Println formats using the default formats for its operands and writes to standard output.
261 // Spaces are always added between operands and a newline is appended.
262 // It returns the number of bytes written and any write error encountered.
263 func Println(a ...interface{}) (n int, err error) {
264 return Fprintln(os.Stdout, a...)
267 // Sprintln formats using the default formats for its operands and returns the resulting string.
268 // Spaces are always added between operands and a newline is appended.
269 func Sprintln(a ...interface{}) string {
270 p := newPrinter()
271 p.doPrint(a, true, true)
272 s := string(p.buf)
273 p.free()
274 return s
277 // getField gets the i'th field of the struct value.
278 // If the field is itself is an interface, return a value for
279 // the thing inside the interface, not the interface itself.
280 func getField(v reflect.Value, i int) reflect.Value {
281 val := v.Field(i)
282 if val.Kind() == reflect.Interface && !val.IsNil() {
283 val = val.Elem()
285 return val
288 // parsenum converts ASCII to integer. num is 0 (and isnum is false) if no number present.
289 func parsenum(s string, start, end int) (num int, isnum bool, newi int) {
290 if start >= end {
291 return 0, false, end
293 for newi = start; newi < end && '0' <= s[newi] && s[newi] <= '9'; newi++ {
294 num = num*10 + int(s[newi]-'0')
295 isnum = true
297 return
300 func (p *pp) unknownType(v interface{}) {
301 if v == nil {
302 p.buf.Write(nilAngleBytes)
303 return
305 p.buf.WriteByte('?')
306 p.buf.WriteString(reflect.TypeOf(v).String())
307 p.buf.WriteByte('?')
310 func (p *pp) badVerb(verb rune) {
311 p.erroring = true
312 p.add('%')
313 p.add('!')
314 p.add(verb)
315 p.add('(')
316 switch {
317 case p.arg != nil:
318 p.buf.WriteString(reflect.TypeOf(p.arg).String())
319 p.add('=')
320 p.printArg(p.arg, 'v', false, false, 0)
321 case p.value.IsValid():
322 p.buf.WriteString(p.value.Type().String())
323 p.add('=')
324 p.printValue(p.value, 'v', false, false, 0)
325 default:
326 p.buf.Write(nilAngleBytes)
328 p.add(')')
329 p.erroring = false
332 func (p *pp) fmtBool(v bool, verb rune) {
333 switch verb {
334 case 't', 'v':
335 p.fmt.fmt_boolean(v)
336 default:
337 p.badVerb(verb)
341 // fmtC formats a rune for the 'c' format.
342 func (p *pp) fmtC(c int64) {
343 r := rune(c) // Check for overflow.
344 if int64(r) != c {
345 r = utf8.RuneError
347 w := utf8.EncodeRune(p.runeBuf[0:utf8.UTFMax], r)
348 p.fmt.pad(p.runeBuf[0:w])
351 func (p *pp) fmtInt64(v int64, verb rune) {
352 switch verb {
353 case 'b':
354 p.fmt.integer(v, 2, signed, ldigits)
355 case 'c':
356 p.fmtC(v)
357 case 'd', 'v':
358 p.fmt.integer(v, 10, signed, ldigits)
359 case 'o':
360 p.fmt.integer(v, 8, signed, ldigits)
361 case 'q':
362 if 0 <= v && v <= utf8.MaxRune {
363 p.fmt.fmt_qc(v)
364 } else {
365 p.badVerb(verb)
367 case 'x':
368 p.fmt.integer(v, 16, signed, ldigits)
369 case 'U':
370 p.fmtUnicode(v)
371 case 'X':
372 p.fmt.integer(v, 16, signed, udigits)
373 default:
374 p.badVerb(verb)
378 // fmt0x64 formats a uint64 in hexadecimal and prefixes it with 0x or
379 // not, as requested, by temporarily setting the sharp flag.
380 func (p *pp) fmt0x64(v uint64, leading0x bool) {
381 sharp := p.fmt.sharp
382 p.fmt.sharp = leading0x
383 p.fmt.integer(int64(v), 16, unsigned, ldigits)
384 p.fmt.sharp = sharp
387 // fmtUnicode formats a uint64 in U+1234 form by
388 // temporarily turning on the unicode flag and tweaking the precision.
389 func (p *pp) fmtUnicode(v int64) {
390 precPresent := p.fmt.precPresent
391 sharp := p.fmt.sharp
392 p.fmt.sharp = false
393 prec := p.fmt.prec
394 if !precPresent {
395 // If prec is already set, leave it alone; otherwise 4 is minimum.
396 p.fmt.prec = 4
397 p.fmt.precPresent = true
399 p.fmt.unicode = true // turn on U+
400 p.fmt.uniQuote = sharp
401 p.fmt.integer(int64(v), 16, unsigned, udigits)
402 p.fmt.unicode = false
403 p.fmt.uniQuote = false
404 p.fmt.prec = prec
405 p.fmt.precPresent = precPresent
406 p.fmt.sharp = sharp
409 func (p *pp) fmtUint64(v uint64, verb rune, goSyntax bool) {
410 switch verb {
411 case 'b':
412 p.fmt.integer(int64(v), 2, unsigned, ldigits)
413 case 'c':
414 p.fmtC(int64(v))
415 case 'd':
416 p.fmt.integer(int64(v), 10, unsigned, ldigits)
417 case 'v':
418 if goSyntax {
419 p.fmt0x64(v, true)
420 } else {
421 p.fmt.integer(int64(v), 10, unsigned, ldigits)
423 case 'o':
424 p.fmt.integer(int64(v), 8, unsigned, ldigits)
425 case 'q':
426 if 0 <= v && v <= utf8.MaxRune {
427 p.fmt.fmt_qc(int64(v))
428 } else {
429 p.badVerb(verb)
431 case 'x':
432 p.fmt.integer(int64(v), 16, unsigned, ldigits)
433 case 'X':
434 p.fmt.integer(int64(v), 16, unsigned, udigits)
435 case 'U':
436 p.fmtUnicode(int64(v))
437 default:
438 p.badVerb(verb)
442 func (p *pp) fmtFloat32(v float32, verb rune) {
443 switch verb {
444 case 'b':
445 p.fmt.fmt_fb32(v)
446 case 'e':
447 p.fmt.fmt_e32(v)
448 case 'E':
449 p.fmt.fmt_E32(v)
450 case 'f':
451 p.fmt.fmt_f32(v)
452 case 'g', 'v':
453 p.fmt.fmt_g32(v)
454 case 'G':
455 p.fmt.fmt_G32(v)
456 default:
457 p.badVerb(verb)
461 func (p *pp) fmtFloat64(v float64, verb rune) {
462 switch verb {
463 case 'b':
464 p.fmt.fmt_fb64(v)
465 case 'e':
466 p.fmt.fmt_e64(v)
467 case 'E':
468 p.fmt.fmt_E64(v)
469 case 'f':
470 p.fmt.fmt_f64(v)
471 case 'g', 'v':
472 p.fmt.fmt_g64(v)
473 case 'G':
474 p.fmt.fmt_G64(v)
475 default:
476 p.badVerb(verb)
480 func (p *pp) fmtComplex64(v complex64, verb rune) {
481 switch verb {
482 case 'b', 'e', 'E', 'f', 'F', 'g', 'G':
483 p.fmt.fmt_c64(v, verb)
484 case 'v':
485 p.fmt.fmt_c64(v, 'g')
486 default:
487 p.badVerb(verb)
491 func (p *pp) fmtComplex128(v complex128, verb rune) {
492 switch verb {
493 case 'b', 'e', 'E', 'f', 'F', 'g', 'G':
494 p.fmt.fmt_c128(v, verb)
495 case 'v':
496 p.fmt.fmt_c128(v, 'g')
497 default:
498 p.badVerb(verb)
502 func (p *pp) fmtString(v string, verb rune, goSyntax bool) {
503 switch verb {
504 case 'v':
505 if goSyntax {
506 p.fmt.fmt_q(v)
507 } else {
508 p.fmt.fmt_s(v)
510 case 's':
511 p.fmt.fmt_s(v)
512 case 'x':
513 p.fmt.fmt_sx(v, ldigits)
514 case 'X':
515 p.fmt.fmt_sx(v, udigits)
516 case 'q':
517 p.fmt.fmt_q(v)
518 default:
519 p.badVerb(verb)
523 func (p *pp) fmtBytes(v []byte, verb rune, goSyntax bool, typ reflect.Type, depth int) {
524 if verb == 'v' || verb == 'd' {
525 if goSyntax {
526 if typ == nil {
527 p.buf.Write(bytesBytes)
528 } else {
529 p.buf.WriteString(typ.String())
530 p.buf.WriteByte('{')
532 } else {
533 p.buf.WriteByte('[')
535 for i, c := range v {
536 if i > 0 {
537 if goSyntax {
538 p.buf.Write(commaSpaceBytes)
539 } else {
540 p.buf.WriteByte(' ')
543 p.printArg(c, 'v', p.fmt.plus, goSyntax, depth+1)
545 if goSyntax {
546 p.buf.WriteByte('}')
547 } else {
548 p.buf.WriteByte(']')
550 return
552 switch verb {
553 case 's':
554 p.fmt.fmt_s(string(v))
555 case 'x':
556 p.fmt.fmt_bx(v, ldigits)
557 case 'X':
558 p.fmt.fmt_bx(v, udigits)
559 case 'q':
560 p.fmt.fmt_q(string(v))
561 default:
562 p.badVerb(verb)
566 func (p *pp) fmtPointer(value reflect.Value, verb rune, goSyntax bool) {
567 use0x64 := true
568 switch verb {
569 case 'p', 'v':
570 // ok
571 case 'b', 'd', 'o', 'x', 'X':
572 use0x64 = false
573 // ok
574 default:
575 p.badVerb(verb)
576 return
579 var u uintptr
580 switch value.Kind() {
581 case reflect.Chan, reflect.Func, reflect.Map, reflect.Ptr, reflect.Slice, reflect.UnsafePointer:
582 u = value.Pointer()
583 default:
584 p.badVerb(verb)
585 return
588 if goSyntax {
589 p.add('(')
590 p.buf.WriteString(value.Type().String())
591 p.add(')')
592 p.add('(')
593 if u == 0 {
594 p.buf.Write(nilBytes)
595 } else {
596 p.fmt0x64(uint64(u), true)
598 p.add(')')
599 } else if verb == 'v' && u == 0 {
600 p.buf.Write(nilAngleBytes)
601 } else {
602 if use0x64 {
603 p.fmt0x64(uint64(u), !p.fmt.sharp)
604 } else {
605 p.fmtUint64(uint64(u), verb, false)
610 var (
611 intBits = reflect.TypeOf(0).Bits()
612 uintptrBits = reflect.TypeOf(uintptr(0)).Bits()
615 func (p *pp) catchPanic(arg interface{}, verb rune) {
616 if err := recover(); err != nil {
617 // If it's a nil pointer, just say "<nil>". The likeliest causes are a
618 // Stringer that fails to guard against nil or a nil pointer for a
619 // value receiver, and in either case, "<nil>" is a nice result.
620 if v := reflect.ValueOf(arg); v.Kind() == reflect.Ptr && v.IsNil() {
621 p.buf.Write(nilAngleBytes)
622 return
624 // Otherwise print a concise panic message. Most of the time the panic
625 // value will print itself nicely.
626 if p.panicking {
627 // Nested panics; the recursion in printArg cannot succeed.
628 panic(err)
630 p.buf.Write(percentBangBytes)
631 p.add(verb)
632 p.buf.Write(panicBytes)
633 p.panicking = true
634 p.printArg(err, 'v', false, false, 0)
635 p.panicking = false
636 p.buf.WriteByte(')')
640 func (p *pp) handleMethods(verb rune, plus, goSyntax bool, depth int) (wasString, handled bool) {
641 if p.erroring {
642 return
644 // Is it a Formatter?
645 if formatter, ok := p.arg.(Formatter); ok {
646 handled = true
647 wasString = false
648 defer p.catchPanic(p.arg, verb)
649 formatter.Format(p, verb)
650 return
652 // Must not touch flags before Formatter looks at them.
653 if plus {
654 p.fmt.plus = false
657 // If we're doing Go syntax and the argument knows how to supply it, take care of it now.
658 if goSyntax {
659 p.fmt.sharp = false
660 if stringer, ok := p.arg.(GoStringer); ok {
661 wasString = false
662 handled = true
663 defer p.catchPanic(p.arg, verb)
664 // Print the result of GoString unadorned.
665 p.fmtString(stringer.GoString(), 's', false)
666 return
668 } else {
669 // If a string is acceptable according to the format, see if
670 // the value satisfies one of the string-valued interfaces.
671 // Println etc. set verb to %v, which is "stringable".
672 switch verb {
673 case 'v', 's', 'x', 'X', 'q':
674 // Is it an error or Stringer?
675 // The duplication in the bodies is necessary:
676 // setting wasString and handled, and deferring catchPanic,
677 // must happen before calling the method.
678 switch v := p.arg.(type) {
679 case error:
680 wasString = false
681 handled = true
682 defer p.catchPanic(p.arg, verb)
683 p.printArg(v.Error(), verb, plus, false, depth)
684 return
686 case Stringer:
687 wasString = false
688 handled = true
689 defer p.catchPanic(p.arg, verb)
690 p.printArg(v.String(), verb, plus, false, depth)
691 return
695 handled = false
696 return
699 func (p *pp) printArg(arg interface{}, verb rune, plus, goSyntax bool, depth int) (wasString bool) {
700 p.arg = arg
701 p.value = reflect.Value{}
703 if arg == nil {
704 if verb == 'T' || verb == 'v' {
705 p.fmt.pad(nilAngleBytes)
706 } else {
707 p.badVerb(verb)
709 return false
712 // Special processing considerations.
713 // %T (the value's type) and %p (its address) are special; we always do them first.
714 switch verb {
715 case 'T':
716 p.printArg(reflect.TypeOf(arg).String(), 's', false, false, 0)
717 return false
718 case 'p':
719 p.fmtPointer(reflect.ValueOf(arg), verb, goSyntax)
720 return false
723 // Clear flags for base formatters.
724 // handleMethods needs them, so we must restore them later.
725 // We could call handleMethods here and avoid this work, but
726 // handleMethods is expensive enough to be worth delaying.
727 oldPlus := p.fmt.plus
728 oldSharp := p.fmt.sharp
729 if plus {
730 p.fmt.plus = false
732 if goSyntax {
733 p.fmt.sharp = false
736 // Some types can be done without reflection.
737 switch f := arg.(type) {
738 case bool:
739 p.fmtBool(f, verb)
740 case float32:
741 p.fmtFloat32(f, verb)
742 case float64:
743 p.fmtFloat64(f, verb)
744 case complex64:
745 p.fmtComplex64(f, verb)
746 case complex128:
747 p.fmtComplex128(f, verb)
748 case int:
749 p.fmtInt64(int64(f), verb)
750 case int8:
751 p.fmtInt64(int64(f), verb)
752 case int16:
753 p.fmtInt64(int64(f), verb)
754 case int32:
755 p.fmtInt64(int64(f), verb)
756 case int64:
757 p.fmtInt64(f, verb)
758 case uint:
759 p.fmtUint64(uint64(f), verb, goSyntax)
760 case uint8:
761 p.fmtUint64(uint64(f), verb, goSyntax)
762 case uint16:
763 p.fmtUint64(uint64(f), verb, goSyntax)
764 case uint32:
765 p.fmtUint64(uint64(f), verb, goSyntax)
766 case uint64:
767 p.fmtUint64(f, verb, goSyntax)
768 case uintptr:
769 p.fmtUint64(uint64(f), verb, goSyntax)
770 case string:
771 p.fmtString(f, verb, goSyntax)
772 wasString = verb == 's' || verb == 'v'
773 case []byte:
774 p.fmtBytes(f, verb, goSyntax, nil, depth)
775 wasString = verb == 's'
776 default:
777 // Restore flags in case handleMethods finds a Formatter.
778 p.fmt.plus = oldPlus
779 p.fmt.sharp = oldSharp
780 // If the type is not simple, it might have methods.
781 if isString, handled := p.handleMethods(verb, plus, goSyntax, depth); handled {
782 return isString
784 // Need to use reflection
785 return p.printReflectValue(reflect.ValueOf(arg), verb, plus, goSyntax, depth)
787 p.arg = nil
788 return
791 // printValue is like printArg but starts with a reflect value, not an interface{} value.
792 func (p *pp) printValue(value reflect.Value, verb rune, plus, goSyntax bool, depth int) (wasString bool) {
793 if !value.IsValid() {
794 if verb == 'T' || verb == 'v' {
795 p.buf.Write(nilAngleBytes)
796 } else {
797 p.badVerb(verb)
799 return false
802 // Special processing considerations.
803 // %T (the value's type) and %p (its address) are special; we always do them first.
804 switch verb {
805 case 'T':
806 p.printArg(value.Type().String(), 's', false, false, 0)
807 return false
808 case 'p':
809 p.fmtPointer(value, verb, goSyntax)
810 return false
813 // Handle values with special methods.
814 // Call always, even when arg == nil, because handleMethods clears p.fmt.plus for us.
815 p.arg = nil // Make sure it's cleared, for safety.
816 if value.CanInterface() {
817 p.arg = value.Interface()
819 if isString, handled := p.handleMethods(verb, plus, goSyntax, depth); handled {
820 return isString
823 return p.printReflectValue(value, verb, plus, goSyntax, depth)
826 // printReflectValue is the fallback for both printArg and printValue.
827 // It uses reflect to print the value.
828 func (p *pp) printReflectValue(value reflect.Value, verb rune, plus, goSyntax bool, depth int) (wasString bool) {
829 oldValue := p.value
830 p.value = value
831 BigSwitch:
832 switch f := value; f.Kind() {
833 case reflect.Bool:
834 p.fmtBool(f.Bool(), verb)
835 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
836 p.fmtInt64(f.Int(), verb)
837 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
838 p.fmtUint64(f.Uint(), verb, goSyntax)
839 case reflect.Float32, reflect.Float64:
840 if f.Type().Size() == 4 {
841 p.fmtFloat32(float32(f.Float()), verb)
842 } else {
843 p.fmtFloat64(f.Float(), verb)
845 case reflect.Complex64, reflect.Complex128:
846 if f.Type().Size() == 8 {
847 p.fmtComplex64(complex64(f.Complex()), verb)
848 } else {
849 p.fmtComplex128(f.Complex(), verb)
851 case reflect.String:
852 p.fmtString(f.String(), verb, goSyntax)
853 case reflect.Map:
854 if goSyntax {
855 p.buf.WriteString(f.Type().String())
856 if f.IsNil() {
857 p.buf.WriteString("(nil)")
858 break
860 p.buf.WriteByte('{')
861 } else {
862 p.buf.Write(mapBytes)
864 keys := f.MapKeys()
865 for i, key := range keys {
866 if i > 0 {
867 if goSyntax {
868 p.buf.Write(commaSpaceBytes)
869 } else {
870 p.buf.WriteByte(' ')
873 p.printValue(key, verb, plus, goSyntax, depth+1)
874 p.buf.WriteByte(':')
875 p.printValue(f.MapIndex(key), verb, plus, goSyntax, depth+1)
877 if goSyntax {
878 p.buf.WriteByte('}')
879 } else {
880 p.buf.WriteByte(']')
882 case reflect.Struct:
883 if goSyntax {
884 p.buf.WriteString(value.Type().String())
886 p.add('{')
887 v := f
888 t := v.Type()
889 for i := 0; i < v.NumField(); i++ {
890 if i > 0 {
891 if goSyntax {
892 p.buf.Write(commaSpaceBytes)
893 } else {
894 p.buf.WriteByte(' ')
897 if plus || goSyntax {
898 if f := t.Field(i); f.Name != "" {
899 p.buf.WriteString(f.Name)
900 p.buf.WriteByte(':')
903 p.printValue(getField(v, i), verb, plus, goSyntax, depth+1)
905 p.buf.WriteByte('}')
906 case reflect.Interface:
907 value := f.Elem()
908 if !value.IsValid() {
909 if goSyntax {
910 p.buf.WriteString(f.Type().String())
911 p.buf.Write(nilParenBytes)
912 } else {
913 p.buf.Write(nilAngleBytes)
915 } else {
916 wasString = p.printValue(value, verb, plus, goSyntax, depth+1)
918 case reflect.Array, reflect.Slice:
919 // Byte slices are special.
920 if typ := f.Type(); typ.Elem().Kind() == reflect.Uint8 {
921 var bytes []byte
922 if f.Kind() == reflect.Slice {
923 bytes = f.Bytes()
924 } else if f.CanAddr() {
925 bytes = f.Slice(0, f.Len()).Bytes()
926 } else {
927 // We have an array, but we cannot Slice() a non-addressable array,
928 // so we build a slice by hand. This is a rare case but it would be nice
929 // if reflection could help a little more.
930 bytes = make([]byte, f.Len())
931 for i := range bytes {
932 bytes[i] = byte(f.Index(i).Uint())
935 p.fmtBytes(bytes, verb, goSyntax, typ, depth)
936 wasString = verb == 's'
937 break
939 if goSyntax {
940 p.buf.WriteString(value.Type().String())
941 if f.Kind() == reflect.Slice && f.IsNil() {
942 p.buf.WriteString("(nil)")
943 break
945 p.buf.WriteByte('{')
946 } else {
947 p.buf.WriteByte('[')
949 for i := 0; i < f.Len(); i++ {
950 if i > 0 {
951 if goSyntax {
952 p.buf.Write(commaSpaceBytes)
953 } else {
954 p.buf.WriteByte(' ')
957 p.printValue(f.Index(i), verb, plus, goSyntax, depth+1)
959 if goSyntax {
960 p.buf.WriteByte('}')
961 } else {
962 p.buf.WriteByte(']')
964 case reflect.Ptr:
965 v := f.Pointer()
966 // pointer to array or slice or struct? ok at top level
967 // but not embedded (avoid loops)
968 if v != 0 && depth == 0 {
969 switch a := f.Elem(); a.Kind() {
970 case reflect.Array, reflect.Slice:
971 p.buf.WriteByte('&')
972 p.printValue(a, verb, plus, goSyntax, depth+1)
973 break BigSwitch
974 case reflect.Struct:
975 p.buf.WriteByte('&')
976 p.printValue(a, verb, plus, goSyntax, depth+1)
977 break BigSwitch
980 fallthrough
981 case reflect.Chan, reflect.Func, reflect.UnsafePointer:
982 p.fmtPointer(value, verb, goSyntax)
983 default:
984 p.unknownType(f)
986 p.value = oldValue
987 return wasString
990 // intFromArg gets the argNumth element of a. On return, isInt reports whether the argument has type int.
991 func intFromArg(a []interface{}, argNum int) (num int, isInt bool, newArgNum int) {
992 newArgNum = argNum
993 if argNum < len(a) {
994 num, isInt = a[argNum].(int)
995 newArgNum = argNum + 1
997 return
1000 // parseArgNumber returns the value of the bracketed number, minus 1
1001 // (explicit argument numbers are one-indexed but we want zero-indexed).
1002 // The opening bracket is known to be present at format[0].
1003 // The returned values are the index, the number of bytes to consume
1004 // up to the closing paren, if present, and whether the number parsed
1005 // ok. The bytes to consume will be 1 if no closing paren is present.
1006 func parseArgNumber(format string) (index int, wid int, ok bool) {
1007 // Find closing bracket.
1008 for i := 1; i < len(format); i++ {
1009 if format[i] == ']' {
1010 width, ok, newi := parsenum(format, 1, i)
1011 if !ok || newi != i {
1012 return 0, i + 1, false
1014 return width - 1, i + 1, true // arg numbers are one-indexed and skip paren.
1017 return 0, 1, false
1020 // argNumber returns the next argument to evaluate, which is either the value of the passed-in
1021 // argNum or the value of the bracketed integer that begins format[i:]. It also returns
1022 // the new value of i, that is, the index of the next byte of the format to process.
1023 func (p *pp) argNumber(argNum int, format string, i int, numArgs int) (newArgNum, newi int, found bool) {
1024 if len(format) <= i || format[i] != '[' {
1025 return argNum, i, false
1027 p.reordered = true
1028 index, wid, ok := parseArgNumber(format[i:])
1029 if ok && 0 <= index && index < numArgs {
1030 return index, i + wid, true
1032 p.goodArgNum = false
1033 return argNum, i + wid, true
1036 func (p *pp) doPrintf(format string, a []interface{}) {
1037 end := len(format)
1038 argNum := 0 // we process one argument per non-trivial format
1039 afterIndex := false // previous item in format was an index like [3].
1040 p.reordered = false
1041 for i := 0; i < end; {
1042 p.goodArgNum = true
1043 lasti := i
1044 for i < end && format[i] != '%' {
1047 if i > lasti {
1048 p.buf.WriteString(format[lasti:i])
1050 if i >= end {
1051 // done processing format string
1052 break
1055 // Process one verb
1058 // Do we have flags?
1059 p.fmt.clearflags()
1061 for ; i < end; i++ {
1062 switch format[i] {
1063 case '#':
1064 p.fmt.sharp = true
1065 case '0':
1066 p.fmt.zero = true
1067 case '+':
1068 p.fmt.plus = true
1069 case '-':
1070 p.fmt.minus = true
1071 case ' ':
1072 p.fmt.space = true
1073 default:
1074 break F
1078 // Do we have an explicit argument index?
1079 argNum, i, afterIndex = p.argNumber(argNum, format, i, len(a))
1081 // Do we have width?
1082 if i < end && format[i] == '*' {
1084 p.fmt.wid, p.fmt.widPresent, argNum = intFromArg(a, argNum)
1085 if !p.fmt.widPresent {
1086 p.buf.Write(badWidthBytes)
1088 afterIndex = false
1089 } else {
1090 p.fmt.wid, p.fmt.widPresent, i = parsenum(format, i, end)
1091 if afterIndex && p.fmt.widPresent { // "%[3]2d"
1092 p.goodArgNum = false
1096 // Do we have precision?
1097 if i+1 < end && format[i] == '.' {
1099 if afterIndex { // "%[3].2d"
1100 p.goodArgNum = false
1102 argNum, i, afterIndex = p.argNumber(argNum, format, i, len(a))
1103 if format[i] == '*' {
1105 p.fmt.prec, p.fmt.precPresent, argNum = intFromArg(a, argNum)
1106 if !p.fmt.precPresent {
1107 p.buf.Write(badPrecBytes)
1109 afterIndex = false
1110 } else {
1111 p.fmt.prec, p.fmt.precPresent, i = parsenum(format, i, end)
1112 if !p.fmt.precPresent {
1113 p.fmt.prec = 0
1114 p.fmt.precPresent = true
1119 if !afterIndex {
1120 argNum, i, afterIndex = p.argNumber(argNum, format, i, len(a))
1123 if i >= end {
1124 p.buf.Write(noVerbBytes)
1125 continue
1127 c, w := utf8.DecodeRuneInString(format[i:])
1128 i += w
1129 // percent is special - absorbs no operand
1130 if c == '%' {
1131 p.buf.WriteByte('%') // We ignore width and prec.
1132 continue
1134 if !p.goodArgNum {
1135 p.buf.Write(percentBangBytes)
1136 p.add(c)
1137 p.buf.Write(badIndexBytes)
1138 continue
1139 } else if argNum >= len(a) { // out of operands
1140 p.buf.Write(percentBangBytes)
1141 p.add(c)
1142 p.buf.Write(missingBytes)
1143 continue
1145 arg := a[argNum]
1146 argNum++
1148 goSyntax := c == 'v' && p.fmt.sharp
1149 plus := c == 'v' && p.fmt.plus
1150 p.printArg(arg, c, plus, goSyntax, 0)
1153 // Check for extra arguments unless the call accessed the arguments
1154 // out of order, in which case it's too expensive to detect if they've all
1155 // been used and arguably OK if they're not.
1156 if !p.reordered && argNum < len(a) {
1157 p.buf.Write(extraBytes)
1158 for ; argNum < len(a); argNum++ {
1159 arg := a[argNum]
1160 if arg != nil {
1161 p.buf.WriteString(reflect.TypeOf(arg).String())
1162 p.buf.WriteByte('=')
1164 p.printArg(arg, 'v', false, false, 0)
1165 if argNum+1 < len(a) {
1166 p.buf.Write(commaSpaceBytes)
1169 p.buf.WriteByte(')')
1173 func (p *pp) doPrint(a []interface{}, addspace, addnewline bool) {
1174 prevString := false
1175 for argNum := 0; argNum < len(a); argNum++ {
1176 p.fmt.clearflags()
1177 // always add spaces if we're doing Println
1178 arg := a[argNum]
1179 if argNum > 0 {
1180 isString := arg != nil && reflect.TypeOf(arg).Kind() == reflect.String
1181 if addspace || !isString && !prevString {
1182 p.buf.WriteByte(' ')
1185 prevString = p.printArg(arg, 'v', false, false, 0)
1187 if addnewline {
1188 p.buf.WriteByte('\n')