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

View as plain text