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
5package fmt
6
7import (
8	"errors"
9	"internal/fmtsort"
10	"io"
11	"os"
12	"reflect"
13	"sync"
14	"unicode/utf8"
15)
16
17// Strings for use with buffer.WriteString.
18// This is less overhead than using buffer.Write with byte arrays.
19const (
20	commaSpaceString  = ", "
21	nilAngleString    = "<nil>"
22	nilParenString    = "(nil)"
23	nilString         = "nil"
24	mapString         = "map["
25	percentBangString = "%!"
26	missingString     = "(MISSING)"
27	badIndexString    = "(BADINDEX)"
28	panicString       = "(PANIC="
29	extraString       = "%!(EXTRA "
30	badWidthString    = "%!(BADWIDTH)"
31	badPrecString     = "%!(BADPREC)"
32	noVerbString      = "%!(NOVERB)"
33	invReflectString  = "<invalid reflect.Value>"
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.
39type State interface {
40	// Write is the function to call to emit formatted output to be printed.
41	Write(b []byte) (n 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 reports 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 Sprint(f) or Fprint(f) etc.
53// to generate its output.
54type 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 any format that accepts a string or to an unformatted printer
62// such as Print.
63type Stringer interface {
64	String() string
65}
66
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.
71type GoStringer interface {
72	GoString() string
73}
74
75// Use simple []byte instead of bytes.Buffer to avoid large dependency.
76type buffer []byte
77
78func (b *buffer) Write(p []byte) {
79	*b = append(*b, p...)
80}
81
82func (b *buffer) WriteString(s string) {
83	*b = append(*b, s...)
84}
85
86func (b *buffer) WriteByte(c byte) {
87	*b = append(*b, c)
88}
89
90func (bp *buffer) WriteRune(r rune) {
91	if r < utf8.RuneSelf {
92		*bp = append(*bp, byte(r))
93		return
94	}
95
96	b := *bp
97	n := len(b)
98	for n+utf8.UTFMax > cap(b) {
99		b = append(b, 0)
100	}
101	w := utf8.EncodeRune(b[n:n+utf8.UTFMax], r)
102	*bp = b[:n+w]
103}
104
105// pp is used to store a printer's state and is reused with sync.Pool to avoid allocations.
106type pp struct {
107	buf buffer
108
109	// arg holds the current item, as an interface{}.
110	arg interface{}
111
112	// value is used instead of arg for reflect values.
113	value reflect.Value
114
115	// fmt is used to format basic items such as integers or strings.
116	fmt fmt
117
118	// reordered records whether the format string used argument reordering.
119	reordered bool
120	// goodArgNum records whether the most recent reordering directive was valid.
121	goodArgNum bool
122	// panicking is set by catchPanic to avoid infinite panic, recover, panic, ... recursion.
123	panicking bool
124	// erroring is set when printing an error string to guard against calling handleMethods.
125	erroring bool
126}
127
128var ppFree = sync.Pool{
129	New: func() interface{} { return new(pp) },
130}
131
132// newPrinter allocates a new pp struct or grabs a cached one.
133func newPrinter() *pp {
134	p := ppFree.Get().(*pp)
135	p.panicking = false
136	p.erroring = false
137	p.fmt.init(&p.buf)
138	return p
139}
140
141// free saves used pp structs in ppFree; avoids an allocation per invocation.
142func (p *pp) free() {
143	// Proper usage of a sync.Pool requires each entry to have approximately
144	// the same memory cost. To obtain this property when the stored type
145	// contains a variably-sized buffer, we add a hard limit on the maximum buffer
146	// to place back in the pool.
147	//
148	// See https://golang.org/issue/23199
149	if cap(p.buf) > 64<<10 {
150		return
151	}
152
153	p.buf = p.buf[:0]
154	p.arg = nil
155	p.value = reflect.Value{}
156	ppFree.Put(p)
157}
158
159func (p *pp) Width() (wid int, ok bool) { return p.fmt.wid, p.fmt.widPresent }
160
161func (p *pp) Precision() (prec int, ok bool) { return p.fmt.prec, p.fmt.precPresent }
162
163func (p *pp) Flag(b int) bool {
164	switch b {
165	case '-':
166		return p.fmt.minus
167	case '+':
168		return p.fmt.plus || p.fmt.plusV
169	case '#':
170		return p.fmt.sharp || p.fmt.sharpV
171	case ' ':
172		return p.fmt.space
173	case '0':
174		return p.fmt.zero
175	}
176	return false
177}
178
179// Implement Write so we can call Fprintf on a pp (through State), for
180// recursive use in custom verbs.
181func (p *pp) Write(b []byte) (ret int, err error) {
182	p.buf.Write(b)
183	return len(b), nil
184}
185
186// Implement WriteString so that we can call io.WriteString
187// on a pp (through state), for efficiency.
188func (p *pp) WriteString(s string) (ret int, err error) {
189	p.buf.WriteString(s)
190	return len(s), nil
191}
192
193// These routines end in 'f' and take a format string.
194
195// Fprintf formats according to a format specifier and writes to w.
196// It returns the number of bytes written and any write error encountered.
197func Fprintf(w io.Writer, format string, a ...interface{}) (n int, err error) {
198	p := newPrinter()
199	p.doPrintf(format, a)
200	n, err = w.Write(p.buf)
201	p.free()
202	return
203}
204
205// Printf formats according to a format specifier and writes to standard output.
206// It returns the number of bytes written and any write error encountered.
207func Printf(format string, a ...interface{}) (n int, err error) {
208	return Fprintf(os.Stdout, format, a...)
209}
210
211// Sprintf formats according to a format specifier and returns the resulting string.
212func Sprintf(format string, a ...interface{}) string {
213	p := newPrinter()
214	p.doPrintf(format, a)
215	s := string(p.buf)
216	p.free()
217	return s
218}
219
220// Errorf formats according to a format specifier and returns the string
221// as a value that satisfies error.
222func Errorf(format string, a ...interface{}) error {
223	return errors.New(Sprintf(format, a...))
224}
225
226// These routines do not take a format string
227
228// Fprint formats using the default formats for its operands and writes to w.
229// Spaces are added between operands when neither is a string.
230// It returns the number of bytes written and any write error encountered.
231func Fprint(w io.Writer, a ...interface{}) (n int, err error) {
232	p := newPrinter()
233	p.doPrint(a)
234	n, err = w.Write(p.buf)
235	p.free()
236	return
237}
238
239// Print formats using the default formats for its operands and writes to standard output.
240// Spaces are added between operands when neither is a string.
241// It returns the number of bytes written and any write error encountered.
242func Print(a ...interface{}) (n int, err error) {
243	return Fprint(os.Stdout, a...)
244}
245
246// Sprint formats using the default formats for its operands and returns the resulting string.
247// Spaces are added between operands when neither is a string.
248func Sprint(a ...interface{}) string {
249	p := newPrinter()
250	p.doPrint(a)
251	s := string(p.buf)
252	p.free()
253	return s
254}
255
256// These routines end in 'ln', do not take a format string,
257// always add spaces between operands, and add a newline
258// after the last operand.
259
260// Fprintln formats using the default formats for its operands and writes to w.
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.
263func Fprintln(w io.Writer, a ...interface{}) (n int, err error) {
264	p := newPrinter()
265	p.doPrintln(a)
266	n, err = w.Write(p.buf)
267	p.free()
268	return
269}
270
271// Println formats using the default formats for its operands and writes to standard output.
272// Spaces are always added between operands and a newline is appended.
273// It returns the number of bytes written and any write error encountered.
274func Println(a ...interface{}) (n int, err error) {
275	return Fprintln(os.Stdout, a...)
276}
277
278// Sprintln formats using the default formats for its operands and returns the resulting string.
279// Spaces are always added between operands and a newline is appended.
280func Sprintln(a ...interface{}) string {
281	p := newPrinter()
282	p.doPrintln(a)
283	s := string(p.buf)
284	p.free()
285	return s
286}
287
288// getField gets the i'th field of the struct value.
289// If the field is itself is an interface, return a value for
290// the thing inside the interface, not the interface itself.
291func getField(v reflect.Value, i int) reflect.Value {
292	val := v.Field(i)
293	if val.Kind() == reflect.Interface && !val.IsNil() {
294		val = val.Elem()
295	}
296	return val
297}
298
299// tooLarge reports whether the magnitude of the integer is
300// too large to be used as a formatting width or precision.
301func tooLarge(x int) bool {
302	const max int = 1e6
303	return x > max || x < -max
304}
305
306// parsenum converts ASCII to integer.  num is 0 (and isnum is false) if no number present.
307func parsenum(s string, start, end int) (num int, isnum bool, newi int) {
308	if start >= end {
309		return 0, false, end
310	}
311	for newi = start; newi < end && '0' <= s[newi] && s[newi] <= '9'; newi++ {
312		if tooLarge(num) {
313			return 0, false, end // Overflow; crazy long number most likely.
314		}
315		num = num*10 + int(s[newi]-'0')
316		isnum = true
317	}
318	return
319}
320
321func (p *pp) unknownType(v reflect.Value) {
322	if !v.IsValid() {
323		p.buf.WriteString(nilAngleString)
324		return
325	}
326	p.buf.WriteByte('?')
327	p.buf.WriteString(v.Type().String())
328	p.buf.WriteByte('?')
329}
330
331func (p *pp) badVerb(verb rune) {
332	p.erroring = true
333	p.buf.WriteString(percentBangString)
334	p.buf.WriteRune(verb)
335	p.buf.WriteByte('(')
336	switch {
337	case p.arg != nil:
338		p.buf.WriteString(reflect.TypeOf(p.arg).String())
339		p.buf.WriteByte('=')
340		p.printArg(p.arg, 'v')
341	case p.value.IsValid():
342		p.buf.WriteString(p.value.Type().String())
343		p.buf.WriteByte('=')
344		p.printValue(p.value, 'v', 0)
345	default:
346		p.buf.WriteString(nilAngleString)
347	}
348	p.buf.WriteByte(')')
349	p.erroring = false
350}
351
352func (p *pp) fmtBool(v bool, verb rune) {
353	switch verb {
354	case 't', 'v':
355		p.fmt.fmtBoolean(v)
356	default:
357		p.badVerb(verb)
358	}
359}
360
361// fmt0x64 formats a uint64 in hexadecimal and prefixes it with 0x or
362// not, as requested, by temporarily setting the sharp flag.
363func (p *pp) fmt0x64(v uint64, leading0x bool) {
364	sharp := p.fmt.sharp
365	p.fmt.sharp = leading0x
366	p.fmt.fmtInteger(v, 16, unsigned, ldigits)
367	p.fmt.sharp = sharp
368}
369
370// fmtInteger formats a signed or unsigned integer.
371func (p *pp) fmtInteger(v uint64, isSigned bool, verb rune) {
372	switch verb {
373	case 'v':
374		if p.fmt.sharpV && !isSigned {
375			p.fmt0x64(v, true)
376		} else {
377			p.fmt.fmtInteger(v, 10, isSigned, ldigits)
378		}
379	case 'd':
380		p.fmt.fmtInteger(v, 10, isSigned, ldigits)
381	case 'b':
382		p.fmt.fmtInteger(v, 2, isSigned, ldigits)
383	case 'o':
384		p.fmt.fmtInteger(v, 8, isSigned, ldigits)
385	case 'x':
386		p.fmt.fmtInteger(v, 16, isSigned, ldigits)
387	case 'X':
388		p.fmt.fmtInteger(v, 16, isSigned, udigits)
389	case 'c':
390		p.fmt.fmtC(v)
391	case 'q':
392		if v <= utf8.MaxRune {
393			p.fmt.fmtQc(v)
394		} else {
395			p.badVerb(verb)
396		}
397	case 'U':
398		p.fmt.fmtUnicode(v)
399	default:
400		p.badVerb(verb)
401	}
402}
403
404// fmtFloat formats a float. The default precision for each verb
405// is specified as last argument in the call to fmt_float.
406func (p *pp) fmtFloat(v float64, size int, verb rune) {
407	switch verb {
408	case 'v':
409		p.fmt.fmtFloat(v, size, 'g', -1)
410	case 'b', 'g', 'G':
411		p.fmt.fmtFloat(v, size, verb, -1)
412	case 'f', 'e', 'E':
413		p.fmt.fmtFloat(v, size, verb, 6)
414	case 'F':
415		p.fmt.fmtFloat(v, size, 'f', 6)
416	default:
417		p.badVerb(verb)
418	}
419}
420
421// fmtComplex formats a complex number v with
422// r = real(v) and j = imag(v) as (r+ji) using
423// fmtFloat for r and j formatting.
424func (p *pp) fmtComplex(v complex128, size int, verb rune) {
425	// Make sure any unsupported verbs are found before the
426	// calls to fmtFloat to not generate an incorrect error string.
427	switch verb {
428	case 'v', 'b', 'g', 'G', 'f', 'F', 'e', 'E':
429		oldPlus := p.fmt.plus
430		p.buf.WriteByte('(')
431		p.fmtFloat(real(v), size/2, verb)
432		// Imaginary part always has a sign.
433		p.fmt.plus = true
434		p.fmtFloat(imag(v), size/2, verb)
435		p.buf.WriteString("i)")
436		p.fmt.plus = oldPlus
437	default:
438		p.badVerb(verb)
439	}
440}
441
442func (p *pp) fmtString(v string, verb rune) {
443	switch verb {
444	case 'v':
445		if p.fmt.sharpV {
446			p.fmt.fmtQ(v)
447		} else {
448			p.fmt.fmtS(v)
449		}
450	case 's':
451		p.fmt.fmtS(v)
452	case 'x':
453		p.fmt.fmtSx(v, ldigits)
454	case 'X':
455		p.fmt.fmtSx(v, udigits)
456	case 'q':
457		p.fmt.fmtQ(v)
458	default:
459		p.badVerb(verb)
460	}
461}
462
463func (p *pp) fmtBytes(v []byte, verb rune, typeString string) {
464	switch verb {
465	case 'v', 'd':
466		if p.fmt.sharpV {
467			p.buf.WriteString(typeString)
468			if v == nil {
469				p.buf.WriteString(nilParenString)
470				return
471			}
472			p.buf.WriteByte('{')
473			for i, c := range v {
474				if i > 0 {
475					p.buf.WriteString(commaSpaceString)
476				}
477				p.fmt0x64(uint64(c), true)
478			}
479			p.buf.WriteByte('}')
480		} else {
481			p.buf.WriteByte('[')
482			for i, c := range v {
483				if i > 0 {
484					p.buf.WriteByte(' ')
485				}
486				p.fmt.fmtInteger(uint64(c), 10, unsigned, ldigits)
487			}
488			p.buf.WriteByte(']')
489		}
490	case 's':
491		p.fmt.fmtBs(v)
492	case 'x':
493		p.fmt.fmtBx(v, ldigits)
494	case 'X':
495		p.fmt.fmtBx(v, udigits)
496	case 'q':
497		p.fmt.fmtQ(string(v))
498	default:
499		p.printValue(reflect.ValueOf(v), verb, 0)
500	}
501}
502
503func (p *pp) fmtPointer(value reflect.Value, verb rune) {
504	var u uintptr
505	switch value.Kind() {
506	case reflect.Chan, reflect.Func, reflect.Map, reflect.Ptr, reflect.Slice, reflect.UnsafePointer:
507		u = value.Pointer()
508	default:
509		p.badVerb(verb)
510		return
511	}
512
513	switch verb {
514	case 'v':
515		if p.fmt.sharpV {
516			p.buf.WriteByte('(')
517			p.buf.WriteString(value.Type().String())
518			p.buf.WriteString(")(")
519			if u == 0 {
520				p.buf.WriteString(nilString)
521			} else {
522				p.fmt0x64(uint64(u), true)
523			}
524			p.buf.WriteByte(')')
525		} else {
526			if u == 0 {
527				p.fmt.padString(nilAngleString)
528			} else {
529				p.fmt0x64(uint64(u), !p.fmt.sharp)
530			}
531		}
532	case 'p':
533		p.fmt0x64(uint64(u), !p.fmt.sharp)
534	case 'b', 'o', 'd', 'x', 'X':
535		p.fmtInteger(uint64(u), unsigned, verb)
536	default:
537		p.badVerb(verb)
538	}
539}
540
541func (p *pp) catchPanic(arg interface{}, verb rune, method string) {
542	if err := recover(); err != nil {
543		// If it's a nil pointer, just say "<nil>". The likeliest causes are a
544		// Stringer that fails to guard against nil or a nil pointer for a
545		// value receiver, and in either case, "<nil>" is a nice result.
546		if v := reflect.ValueOf(arg); v.Kind() == reflect.Ptr && v.IsNil() {
547			p.buf.WriteString(nilAngleString)
548			return
549		}
550		// Otherwise print a concise panic message. Most of the time the panic
551		// value will print itself nicely.
552		if p.panicking {
553			// Nested panics; the recursion in printArg cannot succeed.
554			panic(err)
555		}
556
557		oldFlags := p.fmt.fmtFlags
558		// For this output we want default behavior.
559		p.fmt.clearflags()
560
561		p.buf.WriteString(percentBangString)
562		p.buf.WriteRune(verb)
563		p.buf.WriteString(panicString)
564		p.buf.WriteString(method)
565		p.buf.WriteString(" method: ")
566		p.panicking = true
567		p.printArg(err, 'v')
568		p.panicking = false
569		p.buf.WriteByte(')')
570
571		p.fmt.fmtFlags = oldFlags
572	}
573}
574
575func (p *pp) handleMethods(verb rune) (handled bool) {
576	if p.erroring {
577		return
578	}
579	// Is it a Formatter?
580	if formatter, ok := p.arg.(Formatter); ok {
581		handled = true
582		defer p.catchPanic(p.arg, verb, "Format")
583		formatter.Format(p, verb)
584		return
585	}
586
587	// If we're doing Go syntax and the argument knows how to supply it, take care of it now.
588	if p.fmt.sharpV {
589		if stringer, ok := p.arg.(GoStringer); ok {
590			handled = true
591			defer p.catchPanic(p.arg, verb, "GoString")
592			// Print the result of GoString unadorned.
593			p.fmt.fmtS(stringer.GoString())
594			return
595		}
596	} else {
597		// If a string is acceptable according to the format, see if
598		// the value satisfies one of the string-valued interfaces.
599		// Println etc. set verb to %v, which is "stringable".
600		switch verb {
601		case 'v', 's', 'x', 'X', 'q':
602			// Is it an error or Stringer?
603			// The duplication in the bodies is necessary:
604			// setting handled and deferring catchPanic
605			// must happen before calling the method.
606			switch v := p.arg.(type) {
607			case error:
608				handled = true
609				defer p.catchPanic(p.arg, verb, "Error")
610				p.fmtString(v.Error(), verb)
611				return
612
613			case Stringer:
614				handled = true
615				defer p.catchPanic(p.arg, verb, "String")
616				p.fmtString(v.String(), verb)
617				return
618			}
619		}
620	}
621	return false
622}
623
624func (p *pp) printArg(arg interface{}, verb rune) {
625	p.arg = arg
626	p.value = reflect.Value{}
627
628	if arg == nil {
629		switch verb {
630		case 'T', 'v':
631			p.fmt.padString(nilAngleString)
632		default:
633			p.badVerb(verb)
634		}
635		return
636	}
637
638	// Special processing considerations.
639	// %T (the value's type) and %p (its address) are special; we always do them first.
640	switch verb {
641	case 'T':
642		p.fmt.fmtS(reflect.TypeOf(arg).String())
643		return
644	case 'p':
645		p.fmtPointer(reflect.ValueOf(arg), 'p')
646		return
647	}
648
649	// Some types can be done without reflection.
650	switch f := arg.(type) {
651	case bool:
652		p.fmtBool(f, verb)
653	case float32:
654		p.fmtFloat(float64(f), 32, verb)
655	case float64:
656		p.fmtFloat(f, 64, verb)
657	case complex64:
658		p.fmtComplex(complex128(f), 64, verb)
659	case complex128:
660		p.fmtComplex(f, 128, verb)
661	case int:
662		p.fmtInteger(uint64(f), signed, verb)
663	case int8:
664		p.fmtInteger(uint64(f), signed, verb)
665	case int16:
666		p.fmtInteger(uint64(f), signed, verb)
667	case int32:
668		p.fmtInteger(uint64(f), signed, verb)
669	case int64:
670		p.fmtInteger(uint64(f), signed, verb)
671	case uint:
672		p.fmtInteger(uint64(f), unsigned, verb)
673	case uint8:
674		p.fmtInteger(uint64(f), unsigned, verb)
675	case uint16:
676		p.fmtInteger(uint64(f), unsigned, verb)
677	case uint32:
678		p.fmtInteger(uint64(f), unsigned, verb)
679	case uint64:
680		p.fmtInteger(f, unsigned, verb)
681	case uintptr:
682		p.fmtInteger(uint64(f), unsigned, verb)
683	case string:
684		p.fmtString(f, verb)
685	case []byte:
686		p.fmtBytes(f, verb, "[]byte")
687	case reflect.Value:
688		// Handle extractable values with special methods
689		// since printValue does not handle them at depth 0.
690		if f.IsValid() && f.CanInterface() {
691			p.arg = f.Interface()
692			if p.handleMethods(verb) {
693				return
694			}
695		}
696		p.printValue(f, verb, 0)
697	default:
698		// If the type is not simple, it might have methods.
699		if !p.handleMethods(verb) {
700			// Need to use reflection, since the type had no
701			// interface methods that could be used for formatting.
702			p.printValue(reflect.ValueOf(f), verb, 0)
703		}
704	}
705}
706
707// printValue is similar to printArg but starts with a reflect value, not an interface{} value.
708// It does not handle 'p' and 'T' verbs because these should have been already handled by printArg.
709func (p *pp) printValue(value reflect.Value, verb rune, depth int) {
710	// Handle values with special methods if not already handled by printArg (depth == 0).
711	if depth > 0 && value.IsValid() && value.CanInterface() {
712		p.arg = value.Interface()
713		if p.handleMethods(verb) {
714			return
715		}
716	}
717	p.arg = nil
718	p.value = value
719
720	switch f := value; value.Kind() {
721	case reflect.Invalid:
722		if depth == 0 {
723			p.buf.WriteString(invReflectString)
724		} else {
725			switch verb {
726			case 'v':
727				p.buf.WriteString(nilAngleString)
728			default:
729				p.badVerb(verb)
730			}
731		}
732	case reflect.Bool:
733		p.fmtBool(f.Bool(), verb)
734	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
735		p.fmtInteger(uint64(f.Int()), signed, verb)
736	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
737		p.fmtInteger(f.Uint(), unsigned, verb)
738	case reflect.Float32:
739		p.fmtFloat(f.Float(), 32, verb)
740	case reflect.Float64:
741		p.fmtFloat(f.Float(), 64, verb)
742	case reflect.Complex64:
743		p.fmtComplex(f.Complex(), 64, verb)
744	case reflect.Complex128:
745		p.fmtComplex(f.Complex(), 128, verb)
746	case reflect.String:
747		p.fmtString(f.String(), verb)
748	case reflect.Map:
749		if p.fmt.sharpV {
750			p.buf.WriteString(f.Type().String())
751			if f.IsNil() {
752				p.buf.WriteString(nilParenString)
753				return
754			}
755			p.buf.WriteByte('{')
756		} else {
757			p.buf.WriteString(mapString)
758		}
759		sorted := fmtsort.Sort(f)
760		for i, key := range sorted.Key {
761			if i > 0 {
762				if p.fmt.sharpV {
763					p.buf.WriteString(commaSpaceString)
764				} else {
765					p.buf.WriteByte(' ')
766				}
767			}
768			p.printValue(key, verb, depth+1)
769			p.buf.WriteByte(':')
770			p.printValue(sorted.Value[i], verb, depth+1)
771		}
772		if p.fmt.sharpV {
773			p.buf.WriteByte('}')
774		} else {
775			p.buf.WriteByte(']')
776		}
777	case reflect.Struct:
778		if p.fmt.sharpV {
779			p.buf.WriteString(f.Type().String())
780		}
781		p.buf.WriteByte('{')
782		for i := 0; i < f.NumField(); i++ {
783			if i > 0 {
784				if p.fmt.sharpV {
785					p.buf.WriteString(commaSpaceString)
786				} else {
787					p.buf.WriteByte(' ')
788				}
789			}
790			if p.fmt.plusV || p.fmt.sharpV {
791				if name := f.Type().Field(i).Name; name != "" {
792					p.buf.WriteString(name)
793					p.buf.WriteByte(':')
794				}
795			}
796			p.printValue(getField(f, i), verb, depth+1)
797		}
798		p.buf.WriteByte('}')
799	case reflect.Interface:
800		value := f.Elem()
801		if !value.IsValid() {
802			if p.fmt.sharpV {
803				p.buf.WriteString(f.Type().String())
804				p.buf.WriteString(nilParenString)
805			} else {
806				p.buf.WriteString(nilAngleString)
807			}
808		} else {
809			p.printValue(value, verb, depth+1)
810		}
811	case reflect.Array, reflect.Slice:
812		switch verb {
813		case 's', 'q', 'x', 'X':
814			// Handle byte and uint8 slices and arrays special for the above verbs.
815			t := f.Type()
816			if t.Elem().Kind() == reflect.Uint8 {
817				var bytes []byte
818				if f.Kind() == reflect.Slice {
819					bytes = f.Bytes()
820				} else if f.CanAddr() {
821					bytes = f.Slice(0, f.Len()).Bytes()
822				} else {
823					// We have an array, but we cannot Slice() a non-addressable array,
824					// so we build a slice by hand. This is a rare case but it would be nice
825					// if reflection could help a little more.
826					bytes = make([]byte, f.Len())
827					for i := range bytes {
828						bytes[i] = byte(f.Index(i).Uint())
829					}
830				}
831				p.fmtBytes(bytes, verb, t.String())
832				return
833			}
834		}
835		if p.fmt.sharpV {
836			p.buf.WriteString(f.Type().String())
837			if f.Kind() == reflect.Slice && f.IsNil() {
838				p.buf.WriteString(nilParenString)
839				return
840			}
841			p.buf.WriteByte('{')
842			for i := 0; i < f.Len(); i++ {
843				if i > 0 {
844					p.buf.WriteString(commaSpaceString)
845				}
846				p.printValue(f.Index(i), verb, depth+1)
847			}
848			p.buf.WriteByte('}')
849		} else {
850			p.buf.WriteByte('[')
851			for i := 0; i < f.Len(); i++ {
852				if i > 0 {
853					p.buf.WriteByte(' ')
854				}
855				p.printValue(f.Index(i), verb, depth+1)
856			}
857			p.buf.WriteByte(']')
858		}
859	case reflect.Ptr:
860		// pointer to array or slice or struct? ok at top level
861		// but not embedded (avoid loops)
862		if depth == 0 && f.Pointer() != 0 {
863			switch a := f.Elem(); a.Kind() {
864			case reflect.Array, reflect.Slice, reflect.Struct, reflect.Map:
865				p.buf.WriteByte('&')
866				p.printValue(a, verb, depth+1)
867				return
868			}
869		}
870		fallthrough
871	case reflect.Chan, reflect.Func, reflect.UnsafePointer:
872		p.fmtPointer(f, verb)
873	default:
874		p.unknownType(f)
875	}
876}
877
878// intFromArg gets the argNumth element of a. On return, isInt reports whether the argument has integer type.
879func intFromArg(a []interface{}, argNum int) (num int, isInt bool, newArgNum int) {
880	newArgNum = argNum
881	if argNum < len(a) {
882		num, isInt = a[argNum].(int) // Almost always OK.
883		if !isInt {
884			// Work harder.
885			switch v := reflect.ValueOf(a[argNum]); v.Kind() {
886			case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
887				n := v.Int()
888				if int64(int(n)) == n {
889					num = int(n)
890					isInt = true
891				}
892			case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
893				n := v.Uint()
894				if int64(n) >= 0 && uint64(int(n)) == n {
895					num = int(n)
896					isInt = true
897				}
898			default:
899				// Already 0, false.
900			}
901		}
902		newArgNum = argNum + 1
903		if tooLarge(num) {
904			num = 0
905			isInt = false
906		}
907	}
908	return
909}
910
911// parseArgNumber returns the value of the bracketed number, minus 1
912// (explicit argument numbers are one-indexed but we want zero-indexed).
913// The opening bracket is known to be present at format[0].
914// The returned values are the index, the number of bytes to consume
915// up to the closing paren, if present, and whether the number parsed
916// ok. The bytes to consume will be 1 if no closing paren is present.
917func parseArgNumber(format string) (index int, wid int, ok bool) {
918	// There must be at least 3 bytes: [n].
919	if len(format) < 3 {
920		return 0, 1, false
921	}
922
923	// Find closing bracket.
924	for i := 1; i < len(format); i++ {
925		if format[i] == ']' {
926			width, ok, newi := parsenum(format, 1, i)
927			if !ok || newi != i {
928				return 0, i + 1, false
929			}
930			return width - 1, i + 1, true // arg numbers are one-indexed and skip paren.
931		}
932	}
933	return 0, 1, false
934}
935
936// argNumber returns the next argument to evaluate, which is either the value of the passed-in
937// argNum or the value of the bracketed integer that begins format[i:]. It also returns
938// the new value of i, that is, the index of the next byte of the format to process.
939func (p *pp) argNumber(argNum int, format string, i int, numArgs int) (newArgNum, newi int, found bool) {
940	if len(format) <= i || format[i] != '[' {
941		return argNum, i, false
942	}
943	p.reordered = true
944	index, wid, ok := parseArgNumber(format[i:])
945	if ok && 0 <= index && index < numArgs {
946		return index, i + wid, true
947	}
948	p.goodArgNum = false
949	return argNum, i + wid, ok
950}
951
952func (p *pp) badArgNum(verb rune) {
953	p.buf.WriteString(percentBangString)
954	p.buf.WriteRune(verb)
955	p.buf.WriteString(badIndexString)
956}
957
958func (p *pp) missingArg(verb rune) {
959	p.buf.WriteString(percentBangString)
960	p.buf.WriteRune(verb)
961	p.buf.WriteString(missingString)
962}
963
964func (p *pp) doPrintf(format string, a []interface{}) {
965	end := len(format)
966	argNum := 0         // we process one argument per non-trivial format
967	afterIndex := false // previous item in format was an index like [3].
968	p.reordered = false
969formatLoop:
970	for i := 0; i < end; {
971		p.goodArgNum = true
972		lasti := i
973		for i < end && format[i] != '%' {
974			i++
975		}
976		if i > lasti {
977			p.buf.WriteString(format[lasti:i])
978		}
979		if i >= end {
980			// done processing format string
981			break
982		}
983
984		// Process one verb
985		i++
986
987		// Do we have flags?
988		p.fmt.clearflags()
989	simpleFormat:
990		for ; i < end; i++ {
991			c := format[i]
992			switch c {
993			case '#':
994				p.fmt.sharp = true
995			case '0':
996				p.fmt.zero = !p.fmt.minus // Only allow zero padding to the left.
997			case '+':
998				p.fmt.plus = true
999			case '-':
1000				p.fmt.minus = true
1001				p.fmt.zero = false // Do not pad with zeros to the right.
1002			case ' ':
1003				p.fmt.space = true
1004			default:
1005				// Fast path for common case of ascii lower case simple verbs
1006				// without precision or width or argument indices.
1007				if 'a' <= c && c <= 'z' && argNum < len(a) {
1008					if c == 'v' {
1009						// Go syntax
1010						p.fmt.sharpV = p.fmt.sharp
1011						p.fmt.sharp = false
1012						// Struct-field syntax
1013						p.fmt.plusV = p.fmt.plus
1014						p.fmt.plus = false
1015					}
1016					p.printArg(a[argNum], rune(c))
1017					argNum++
1018					i++
1019					continue formatLoop
1020				}
1021				// Format is more complex than simple flags and a verb or is malformed.
1022				break simpleFormat
1023			}
1024		}
1025
1026		// Do we have an explicit argument index?
1027		argNum, i, afterIndex = p.argNumber(argNum, format, i, len(a))
1028
1029		// Do we have width?
1030		if i < end && format[i] == '*' {
1031			i++
1032			p.fmt.wid, p.fmt.widPresent, argNum = intFromArg(a, argNum)
1033
1034			if !p.fmt.widPresent {
1035				p.buf.WriteString(badWidthString)
1036			}
1037
1038			// We have a negative width, so take its value and ensure
1039			// that the minus flag is set
1040			if p.fmt.wid < 0 {
1041				p.fmt.wid = -p.fmt.wid
1042				p.fmt.minus = true
1043				p.fmt.zero = false // Do not pad with zeros to the right.
1044			}
1045			afterIndex = false
1046		} else {
1047			p.fmt.wid, p.fmt.widPresent, i = parsenum(format, i, end)
1048			if afterIndex && p.fmt.widPresent { // "%[3]2d"
1049				p.goodArgNum = false
1050			}
1051		}
1052
1053		// Do we have precision?
1054		if i+1 < end && format[i] == '.' {
1055			i++
1056			if afterIndex { // "%[3].2d"
1057				p.goodArgNum = false
1058			}
1059			argNum, i, afterIndex = p.argNumber(argNum, format, i, len(a))
1060			if i < end && format[i] == '*' {
1061				i++
1062				p.fmt.prec, p.fmt.precPresent, argNum = intFromArg(a, argNum)
1063				// Negative precision arguments don't make sense
1064				if p.fmt.prec < 0 {
1065					p.fmt.prec = 0
1066					p.fmt.precPresent = false
1067				}
1068				if !p.fmt.precPresent {
1069					p.buf.WriteString(badPrecString)
1070				}
1071				afterIndex = false
1072			} else {
1073				p.fmt.prec, p.fmt.precPresent, i = parsenum(format, i, end)
1074				if !p.fmt.precPresent {
1075					p.fmt.prec = 0
1076					p.fmt.precPresent = true
1077				}
1078			}
1079		}
1080
1081		if !afterIndex {
1082			argNum, i, afterIndex = p.argNumber(argNum, format, i, len(a))
1083		}
1084
1085		if i >= end {
1086			p.buf.WriteString(noVerbString)
1087			break
1088		}
1089
1090		verb, size := rune(format[i]), 1
1091		if verb >= utf8.RuneSelf {
1092			verb, size = utf8.DecodeRuneInString(format[i:])
1093		}
1094		i += size
1095
1096		switch {
1097		case verb == '%': // Percent does not absorb operands and ignores f.wid and f.prec.
1098			p.buf.WriteByte('%')
1099		case !p.goodArgNum:
1100			p.badArgNum(verb)
1101		case argNum >= len(a): // No argument left over to print for the current verb.
1102			p.missingArg(verb)
1103		case verb == 'v':
1104			// Go syntax
1105			p.fmt.sharpV = p.fmt.sharp
1106			p.fmt.sharp = false
1107			// Struct-field syntax
1108			p.fmt.plusV = p.fmt.plus
1109			p.fmt.plus = false
1110			fallthrough
1111		default:
1112			p.printArg(a[argNum], verb)
1113			argNum++
1114		}
1115	}
1116
1117	// Check for extra arguments unless the call accessed the arguments
1118	// out of order, in which case it's too expensive to detect if they've all
1119	// been used and arguably OK if they're not.
1120	if !p.reordered && argNum < len(a) {
1121		p.fmt.clearflags()
1122		p.buf.WriteString(extraString)
1123		for i, arg := range a[argNum:] {
1124			if i > 0 {
1125				p.buf.WriteString(commaSpaceString)
1126			}
1127			if arg == nil {
1128				p.buf.WriteString(nilAngleString)
1129			} else {
1130				p.buf.WriteString(reflect.TypeOf(arg).String())
1131				p.buf.WriteByte('=')
1132				p.printArg(arg, 'v')
1133			}
1134		}
1135		p.buf.WriteByte(')')
1136	}
1137}
1138
1139func (p *pp) doPrint(a []interface{}) {
1140	prevString := false
1141	for argNum, arg := range a {
1142		isString := arg != nil && reflect.TypeOf(arg).Kind() == reflect.String
1143		// Add a space between two non-string arguments.
1144		if argNum > 0 && !isString && !prevString {
1145			p.buf.WriteByte(' ')
1146		}
1147		p.printArg(arg, 'v')
1148		prevString = isString
1149	}
1150}
1151
1152// doPrintln is like doPrint but always adds a space between arguments
1153// and a newline after the last argument.
1154func (p *pp) doPrintln(a []interface{}) {
1155	for argNum, arg := range a {
1156		if argNum > 0 {
1157			p.buf.WriteByte(' ')
1158		}
1159		p.printArg(arg, 'v')
1160	}
1161	p.buf.WriteByte('\n')
1162}
1163