Debian Codegraph @

errors/fmt/print.go

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