...
Run Format

Source file src/fmt/print.go

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

View as plain text