github.com/muesli/go@v0.0.0-20170208044820-e410d2a81ef2/src/fmt/print.go (about)

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