...
Run Format

Source file src/fmt/print.go

Documentation: fmt

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

View as plain text