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

View as plain text