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

View as plain text