nilBytes = []byte("nil")
mapBytes = []byte("map[")
missingBytes = []byte("(MISSING)")
+ badArgNum = []byte("(BADARGNUM)")
panicBytes = []byte("(PANIC=")
extraBytes = []byte("%!(EXTRA ")
irparenBytes = []byte("i)")
panicking bool
erroring bool // printing an error condition
buf buffer
- // field holds the current item, as an interface{}.
- field interface{}
+ // arg holds the current item, as an interface{}.
+ arg interface{}
// value holds the current item, as a reflect.Value, and will be
// the zero Value if the item has not been reflected.
- value reflect.Value
- runeBuf [utf8.UTFMax]byte
- fmt fmt
+ value reflect.Value
+ // reordered records whether the format string used argument reordering.
+ reordered bool
+ // goodArgNum records whether the last reordering directive was valid.
+ goodArgNum bool
+ runeBuf [utf8.UTFMax]byte
+ fmt fmt
}
// A cache holds a set of reusable objects.
return
}
p.buf = p.buf[:0]
- p.field = nil
+ p.arg = nil
p.value = reflect.Value{}
ppFree.put(p)
}
func Fprintf(w io.Writer, format string, a ...interface{}) (n int, err error) {
p := newPrinter()
p.doPrintf(format, a)
- n64, err := w.Write(p.buf)
+ n, err = w.Write(p.buf)
p.free()
- return int(n64), err
+ return
}
// Printf formats according to a format specifier and writes to standard output.
func Fprint(w io.Writer, a ...interface{}) (n int, err error) {
p := newPrinter()
p.doPrint(a, false, false)
- n64, err := w.Write(p.buf)
+ n, err = w.Write(p.buf)
p.free()
- return int(n64), err
+ return
}
// Print formats using the default formats for its operands and writes to standard output.
func Fprintln(w io.Writer, a ...interface{}) (n int, err error) {
p := newPrinter()
p.doPrint(a, true, true)
- n64, err := w.Write(p.buf)
+ n, err = w.Write(p.buf)
p.free()
- return int(n64), err
+ return
}
// Println formats using the default formats for its operands and writes to standard output.
return s
}
-// getField gets the i'th arg of the struct value.
-// If the arg itself is an interface, return a value for
+// getField gets the i'th field of the struct value.
+// If the field is itself is an interface, return a value for
// the thing inside the interface, not the interface itself.
func getField(v reflect.Value, i int) reflect.Value {
val := v.Field(i)
p.add(verb)
p.add('(')
switch {
- case p.field != nil:
- p.buf.WriteString(reflect.TypeOf(p.field).String())
+ case p.arg != nil:
+ p.buf.WriteString(reflect.TypeOf(p.arg).String())
p.add('=')
- p.printField(p.field, 'v', false, false, 0)
+ p.printArg(p.arg, 'v', false, false, 0)
case p.value.IsValid():
p.buf.WriteString(p.value.Type().String())
p.add('=')
p.buf.WriteByte(' ')
}
}
- p.printField(c, 'v', p.fmt.plus, goSyntax, depth+1)
+ p.printArg(c, 'v', p.fmt.plus, goSyntax, depth+1)
}
if goSyntax {
p.buf.WriteByte('}')
uintptrBits = reflect.TypeOf(uintptr(0)).Bits()
)
-func (p *pp) catchPanic(field interface{}, verb rune) {
+func (p *pp) catchPanic(arg interface{}, verb rune) {
if err := recover(); err != nil {
// If it's a nil pointer, just say "<nil>". The likeliest causes are a
// Stringer that fails to guard against nil or a nil pointer for a
// value receiver, and in either case, "<nil>" is a nice result.
- if v := reflect.ValueOf(field); v.Kind() == reflect.Ptr && v.IsNil() {
+ if v := reflect.ValueOf(arg); v.Kind() == reflect.Ptr && v.IsNil() {
p.buf.Write(nilAngleBytes)
return
}
// Otherwise print a concise panic message. Most of the time the panic
// value will print itself nicely.
if p.panicking {
- // Nested panics; the recursion in printField cannot succeed.
+ // Nested panics; the recursion in printArg cannot succeed.
panic(err)
}
p.buf.WriteByte('%')
p.add(verb)
p.buf.Write(panicBytes)
p.panicking = true
- p.printField(err, 'v', false, false, 0)
+ p.printArg(err, 'v', false, false, 0)
p.panicking = false
p.buf.WriteByte(')')
}
return
}
// Is it a Formatter?
- if formatter, ok := p.field.(Formatter); ok {
+ if formatter, ok := p.arg.(Formatter); ok {
handled = true
wasString = false
- defer p.catchPanic(p.field, verb)
+ defer p.catchPanic(p.arg, verb)
formatter.Format(p, verb)
return
}
p.fmt.plus = false
}
- // If we're doing Go syntax and the field knows how to supply it, take care of it now.
+ // If we're doing Go syntax and the argument knows how to supply it, take care of it now.
if goSyntax {
p.fmt.sharp = false
- if stringer, ok := p.field.(GoStringer); ok {
+ if stringer, ok := p.arg.(GoStringer); ok {
wasString = false
handled = true
- defer p.catchPanic(p.field, verb)
+ defer p.catchPanic(p.arg, verb)
// Print the result of GoString unadorned.
p.fmtString(stringer.GoString(), 's', false)
return
// The duplication in the bodies is necessary:
// setting wasString and handled, and deferring catchPanic,
// must happen before calling the method.
- switch v := p.field.(type) {
+ switch v := p.arg.(type) {
case error:
wasString = false
handled = true
- defer p.catchPanic(p.field, verb)
- p.printField(v.Error(), verb, plus, false, depth)
+ defer p.catchPanic(p.arg, verb)
+ p.printArg(v.Error(), verb, plus, false, depth)
return
case Stringer:
wasString = false
handled = true
- defer p.catchPanic(p.field, verb)
- p.printField(v.String(), verb, plus, false, depth)
+ defer p.catchPanic(p.arg, verb)
+ p.printArg(v.String(), verb, plus, false, depth)
return
}
}
return
}
-func (p *pp) printField(field interface{}, verb rune, plus, goSyntax bool, depth int) (wasString bool) {
- p.field = field
+func (p *pp) printArg(arg interface{}, verb rune, plus, goSyntax bool, depth int) (wasString bool) {
+ p.arg = arg
p.value = reflect.Value{}
- if field == nil {
+ if arg == nil {
if verb == 'T' || verb == 'v' {
p.fmt.pad(nilAngleBytes)
} else {
// %T (the value's type) and %p (its address) are special; we always do them first.
switch verb {
case 'T':
- p.printField(reflect.TypeOf(field).String(), 's', false, false, 0)
+ p.printArg(reflect.TypeOf(arg).String(), 's', false, false, 0)
return false
case 'p':
- p.fmtPointer(reflect.ValueOf(field), verb, goSyntax)
+ p.fmtPointer(reflect.ValueOf(arg), verb, goSyntax)
return false
}
}
// Some types can be done without reflection.
- switch f := field.(type) {
+ switch f := arg.(type) {
case bool:
p.fmtBool(f, verb)
case float32:
return wasString
}
// Need to use reflection
- return p.printReflectValue(reflect.ValueOf(field), verb, plus, goSyntax, depth)
+ return p.printReflectValue(reflect.ValueOf(arg), verb, plus, goSyntax, depth)
}
- p.field = nil
+ p.arg = nil
return
}
-// printValue is like printField but starts with a reflect value, not an interface{} value.
+// printValue is like printArg but starts with a reflect value, not an interface{} value.
func (p *pp) printValue(value reflect.Value, verb rune, plus, goSyntax bool, depth int) (wasString bool) {
if !value.IsValid() {
if verb == 'T' || verb == 'v' {
// %T (the value's type) and %p (its address) are special; we always do them first.
switch verb {
case 'T':
- p.printField(value.Type().String(), 's', false, false, 0)
+ p.printArg(value.Type().String(), 's', false, false, 0)
return false
case 'p':
p.fmtPointer(value, verb, goSyntax)
}
// Handle values with special methods.
- // Call always, even when field == nil, because handleMethods clears p.fmt.plus for us.
- p.field = nil // Make sure it's cleared, for safety.
+ // Call always, even when arg == nil, because handleMethods clears p.fmt.plus for us.
+ p.arg = nil // Make sure it's cleared, for safety.
if value.CanInterface() {
- p.field = value.Interface()
+ p.arg = value.Interface()
}
if wasString, handled := p.handleMethods(verb, plus, goSyntax, depth); handled {
return wasString
return p.printReflectValue(value, verb, plus, goSyntax, depth)
}
-// printReflectValue is the fallback for both printField and printValue.
+// printReflectValue is the fallback for both printArg and printValue.
// It uses reflect to print the value.
func (p *pp) printReflectValue(value reflect.Value, verb rune, plus, goSyntax bool, depth int) (wasString bool) {
oldValue := p.value
return wasString
}
-// intFromArg gets the fieldnumth element of a. On return, isInt reports whether the argument has type int.
-func intFromArg(a []interface{}, end, i, fieldnum int) (num int, isInt bool, newi, newfieldnum int) {
- newi, newfieldnum = end, fieldnum
- if i < end && fieldnum < len(a) {
- num, isInt = a[fieldnum].(int)
- newi, newfieldnum = i+1, fieldnum+1
+// intFromArg gets the argNumth element of a. On return, isInt reports whether the argument has type int.
+func intFromArg(a []interface{}, end, i, argNum int) (num int, isInt bool, newi, newArgNum int) {
+ newi, newArgNum = end, argNum
+ if i < end && argNum < len(a) {
+ num, isInt = a[argNum].(int)
+ newi, newArgNum = i+1, argNum+1
}
return
}
+// parseArgNumber returns the value of the bracketed number, minus 1
+// (explicit argument numbers are one-indexed but we want zero-indexed).
+// The opening bracket is known to be present at format[0].
+// The returned values are the index, the number of bytes to consume
+// up to the closing paren, if present, and whether the number parsed
+// ok. The bytes to consume will be 1 if no closing paren is present.
+func parseArgNumber(format string) (index int, wid int, ok bool) {
+ // Find closing parenthesis
+ for i := 1; i < len(format); i++ {
+ if format[i] == ']' {
+ width, ok, newi := parsenum(format, 1, i)
+ if !ok || newi != i {
+ return 0, i + 1, false
+ }
+ return width - 1, i + 1, true // arg numbers are one-indexed and skip paren.
+ }
+ }
+ return 0, 1, false
+}
+
+// argNumber returns the next argument to evaluate, which is either the value of the passed-in
+// argNum or the value of the bracketed integer that begins format[i:]. It also returns
+// the new value of i, that is, the index of the next byte of the format to process.
+func (p *pp) argNumber(argNum int, format string, i int, numArgs int) (newArgNum, newi int) {
+ p.goodArgNum = true
+ if len(format) <= i || format[i] != '[' {
+ return argNum, i
+ }
+ p.reordered = true
+ index, wid, ok := parseArgNumber(format[i:])
+ if ok && 0 <= index && index < numArgs {
+ return index, i + wid
+ }
+ p.goodArgNum = false
+ return argNum, i + wid
+}
+
func (p *pp) doPrintf(format string, a []interface{}) {
end := len(format)
- fieldnum := 0 // we process one field per non-trivial format
+ argNum := 0 // we process one argument per non-trivial format
+ p.reordered = false
for i := 0; i < end; {
lasti := i
for i < end && format[i] != '%' {
// Process one verb
i++
- // flags and widths
+
+ // Do we have flags?
p.fmt.clearflags()
F:
for ; i < end; i++ {
break F
}
}
- // do we have width?
+
+ // Do we have an explicit argument index?
+ argNum, i = p.argNumber(argNum, format, i, len(a))
+
+ // Do we have width?
if i < end && format[i] == '*' {
- p.fmt.wid, p.fmt.widPresent, i, fieldnum = intFromArg(a, end, i, fieldnum)
+ p.fmt.wid, p.fmt.widPresent, i, argNum = intFromArg(a, end, i, argNum)
if !p.fmt.widPresent {
p.buf.Write(badWidthBytes)
}
+ argNum, i = p.argNumber(argNum, format, i, len(a)) // We consumed []; another can follow here.
} else {
p.fmt.wid, p.fmt.widPresent, i = parsenum(format, i, end)
}
- // do we have precision?
+
+ // Do we have precision?
if i+1 < end && format[i] == '.' {
if format[i+1] == '*' {
- p.fmt.prec, p.fmt.precPresent, i, fieldnum = intFromArg(a, end, i+1, fieldnum)
+ p.fmt.prec, p.fmt.precPresent, i, argNum = intFromArg(a, end, i+1, argNum)
if !p.fmt.precPresent {
p.buf.Write(badPrecBytes)
}
+ argNum, i = p.argNumber(argNum, format, i, len(a)) // We consumed []; another can follow here.
} else {
p.fmt.prec, p.fmt.precPresent, i = parsenum(format, i+1, end)
if !p.fmt.precPresent {
p.buf.WriteByte('%') // We ignore width and prec.
continue
}
- if fieldnum >= len(a) { // out of operands
+ if !p.goodArgNum {
+ p.buf.WriteByte('%')
+ p.add(c)
+ p.buf.Write(badArgNum)
+ continue
+ } else if argNum >= len(a) { // out of operands
p.buf.WriteByte('%')
p.add(c)
p.buf.Write(missingBytes)
continue
}
- field := a[fieldnum]
- fieldnum++
+ arg := a[argNum]
+ argNum++
goSyntax := c == 'v' && p.fmt.sharp
plus := c == 'v' && p.fmt.plus
- p.printField(field, c, plus, goSyntax, 0)
+ p.printArg(arg, c, plus, goSyntax, 0)
}
- if fieldnum < len(a) {
+ // Check for extra arguments unless the call accessed the arguments
+ // out of order, in which case it's too expensive to detect if they've all
+ // been used and arguably OK if they're not.
+ if !p.reordered && argNum < len(a) {
p.buf.Write(extraBytes)
- for ; fieldnum < len(a); fieldnum++ {
- field := a[fieldnum]
- if field != nil {
- p.buf.WriteString(reflect.TypeOf(field).String())
+ for ; argNum < len(a); argNum++ {
+ arg := a[argNum]
+ if arg != nil {
+ p.buf.WriteString(reflect.TypeOf(arg).String())
p.buf.WriteByte('=')
}
- p.printField(field, 'v', false, false, 0)
- if fieldnum+1 < len(a) {
+ p.printArg(arg, 'v', false, false, 0)
+ if argNum+1 < len(a) {
p.buf.Write(commaSpaceBytes)
}
}
func (p *pp) doPrint(a []interface{}, addspace, addnewline bool) {
prevString := false
- for fieldnum := 0; fieldnum < len(a); fieldnum++ {
+ for argNum := 0; argNum < len(a); argNum++ {
p.fmt.clearflags()
// always add spaces if we're doing Println
- field := a[fieldnum]
- if fieldnum > 0 {
- isString := field != nil && reflect.TypeOf(field).Kind() == reflect.String
+ arg := a[argNum]
+ if argNum > 0 {
+ isString := arg != nil && reflect.TypeOf(arg).Kind() == reflect.String
if addspace || !isString && !prevString {
p.buf.WriteByte(' ')
}
}
- prevString = p.printField(field, 'v', false, false, 0)
+ prevString = p.printArg(arg, 'v', false, false, 0)
}
if addnewline {
p.buf.WriteByte('\n')