...

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

View as plain text