...
Run Format

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

View as plain text