diff options
Diffstat (limited to 'libgo/go/fmt/print.go')
-rw-r--r-- | libgo/go/fmt/print.go | 282 |
1 files changed, 178 insertions, 104 deletions
diff --git a/libgo/go/fmt/print.go b/libgo/go/fmt/print.go index 5f37fd12085..1ea816d6d5f 100644 --- a/libgo/go/fmt/print.go +++ b/libgo/go/fmt/print.go @@ -16,19 +16,21 @@ import ( // Some constants in the form of bytes, to avoid string overhead. // Needlessly fastidious, I suppose. var ( - commaSpaceBytes = []byte(", ") - nilAngleBytes = []byte("<nil>") - nilParenBytes = []byte("(nil)") - nilBytes = []byte("nil") - mapBytes = []byte("map[") - missingBytes = []byte("(MISSING)") - panicBytes = []byte("(PANIC=") - extraBytes = []byte("%!(EXTRA ") - irparenBytes = []byte("i)") - bytesBytes = []byte("[]byte{") - badWidthBytes = []byte("%!(BADWIDTH)") - badPrecBytes = []byte("%!(BADPREC)") - noVerbBytes = []byte("%!(NOVERB)") + commaSpaceBytes = []byte(", ") + nilAngleBytes = []byte("<nil>") + nilParenBytes = []byte("(nil)") + nilBytes = []byte("nil") + mapBytes = []byte("map[") + percentBangBytes = []byte("%!") + missingBytes = []byte("(MISSING)") + badIndexBytes = []byte("(BADINDEX)") + panicBytes = []byte("(PANIC=") + extraBytes = []byte("%!(EXTRA ") + irparenBytes = []byte("i)") + bytesBytes = []byte("[]byte{") + badWidthBytes = []byte("%!(BADWIDTH)") + badPrecBytes = []byte("%!(BADPREC)") + noVerbBytes = []byte("%!(NOVERB)") ) // State represents the printer state passed to custom formatters. @@ -42,7 +44,7 @@ type State interface { // Precision returns the value of the precision option and whether it has been set. Precision() (prec int, ok bool) - // Flag returns whether the flag c, a character, has been set. + // Flag reports whether the flag c, a character, has been set. Flag(c int) bool } @@ -109,13 +111,17 @@ type pp struct { 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 most recent reordering directive was valid. + goodArgNum bool + runeBuf [utf8.UTFMax]byte + fmt fmt } // A cache holds a set of reusable objects. @@ -170,7 +176,7 @@ func (p *pp) free() { return } p.buf = p.buf[:0] - p.field = nil + p.arg = nil p.value = reflect.Value{} ppFree.put(p) } @@ -212,9 +218,9 @@ func (p *pp) Write(b []byte) (ret int, err error) { 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. @@ -246,9 +252,9 @@ func Errorf(format string, a ...interface{}) error { 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. @@ -278,9 +284,9 @@ func Sprint(a ...interface{}) string { 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. @@ -300,8 +306,8 @@ func Sprintln(a ...interface{}) string { 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) @@ -340,10 +346,10 @@ func (p *pp) badVerb(verb rune) { 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('=') @@ -505,7 +511,7 @@ func (p *pp) fmtFloat64(v float64, verb rune) { func (p *pp) fmtComplex64(v complex64, verb rune) { switch verb { - case 'e', 'E', 'f', 'F', 'g', 'G': + case 'b', 'e', 'E', 'f', 'F', 'g', 'G': p.fmt.fmt_c64(v, verb) case 'v': p.fmt.fmt_c64(v, 'g') @@ -516,7 +522,7 @@ func (p *pp) fmtComplex64(v complex64, verb rune) { func (p *pp) fmtComplex128(v complex128, verb rune) { switch verb { - case 'e', 'E', 'f', 'F', 'g', 'G': + case 'b', 'e', 'E', 'f', 'F', 'g', 'G': p.fmt.fmt_c128(v, verb) case 'v': p.fmt.fmt_c128(v, 'g') @@ -566,7 +572,7 @@ func (p *pp) fmtBytes(v []byte, verb rune, goSyntax bool, typ reflect.Type, dept 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('}') @@ -635,31 +641,29 @@ func (p *pp) fmtPointer(value reflect.Value, verb rune, goSyntax bool) { var ( intBits = reflect.TypeOf(0).Bits() - floatBits = reflect.TypeOf(0.0).Bits() - complexBits = reflect.TypeOf(1i).Bits() 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.buf.Write(percentBangBytes) 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(')') } @@ -670,10 +674,10 @@ func (p *pp) handleMethods(verb rune, plus, goSyntax bool, depth int) (wasString 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 } @@ -682,13 +686,13 @@ func (p *pp) handleMethods(verb rune, plus, goSyntax bool, depth int) (wasString 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 @@ -703,19 +707,19 @@ func (p *pp) handleMethods(verb rune, plus, goSyntax bool, depth int) (wasString // 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 } } @@ -724,11 +728,11 @@ func (p *pp) handleMethods(verb rune, plus, goSyntax bool, depth int) (wasString 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 { @@ -741,10 +745,10 @@ func (p *pp) printField(field interface{}, verb rune, plus, goSyntax bool, depth // %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 } @@ -762,7 +766,7 @@ func (p *pp) printField(field interface{}, verb rune, plus, goSyntax bool, depth } // Some types can be done without reflection. - switch f := field.(type) { + switch f := arg.(type) { case bool: p.fmtBool(f, verb) case float32: @@ -770,7 +774,7 @@ func (p *pp) printField(field interface{}, verb rune, plus, goSyntax bool, depth case float64: p.fmtFloat64(f, verb) case complex64: - p.fmtComplex64(complex64(f), verb) + p.fmtComplex64(f, verb) case complex128: p.fmtComplex128(f, verb) case int: @@ -806,17 +810,17 @@ func (p *pp) printField(field interface{}, verb rune, plus, goSyntax bool, depth p.fmt.plus = oldPlus p.fmt.sharp = oldSharp // If the type is not simple, it might have methods. - if wasString, handled := p.handleMethods(verb, plus, goSyntax, depth); handled { - return wasString + if isString, handled := p.handleMethods(verb, plus, goSyntax, depth); handled { + return isString } // 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' { @@ -831,7 +835,7 @@ func (p *pp) printValue(value reflect.Value, verb rune, plus, goSyntax bool, dep // %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) @@ -839,19 +843,19 @@ func (p *pp) printValue(value reflect.Value, verb rune, plus, goSyntax bool, dep } // 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 + if isString, handled := p.handleMethods(verb, plus, goSyntax, depth); handled { + return isString } 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 @@ -863,18 +867,18 @@ BigSwitch: case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: p.fmtInt64(f.Int(), verb) case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - p.fmtUint64(uint64(f.Uint()), verb, goSyntax) + p.fmtUint64(f.Uint(), verb, goSyntax) case reflect.Float32, reflect.Float64: if f.Type().Size() == 4 { p.fmtFloat32(float32(f.Float()), verb) } else { - p.fmtFloat64(float64(f.Float()), verb) + p.fmtFloat64(f.Float(), verb) } case reflect.Complex64, reflect.Complex128: if f.Type().Size() == 8 { p.fmtComplex64(complex64(f.Complex()), verb) } else { - p.fmtComplex128(complex128(f.Complex()), verb) + p.fmtComplex128(f.Complex(), verb) } case reflect.String: p.fmtString(f.String(), verb, goSyntax) @@ -1015,20 +1019,59 @@ BigSwitch: 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{}, argNum int) (num int, isInt bool, newArgNum int) { + newArgNum = argNum + if argNum < len(a) { + num, isInt = a[argNum].(int) + newArgNum = 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 bracket. + 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, found bool) { + if len(format) <= i || format[i] != '[' { + return argNum, i, false + } + p.reordered = true + index, wid, ok := parseArgNumber(format[i:]) + if ok && 0 <= index && index < numArgs { + return index, i + wid, true + } + p.goodArgNum = false + return argNum, i + wid, true +} + 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 + afterIndex := false // previous item in format was an index like [3]. + p.reordered = false for i := 0; i < end; { + p.goodArgNum = true lasti := i for i < end && format[i] != '%' { i++ @@ -1043,7 +1086,8 @@ func (p *pp) doPrintf(format string, a []interface{}) { // Process one verb i++ - // flags and widths + + // Do we have flags? p.fmt.clearflags() F: for ; i < end; i++ { @@ -1062,30 +1106,52 @@ func (p *pp) doPrintf(format string, a []interface{}) { break F } } - // do we have width? + + // Do we have an explicit argument index? + argNum, i, afterIndex = 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) + i++ + p.fmt.wid, p.fmt.widPresent, argNum = intFromArg(a, argNum) if !p.fmt.widPresent { p.buf.Write(badWidthBytes) } + afterIndex = false } else { p.fmt.wid, p.fmt.widPresent, i = parsenum(format, i, end) + if afterIndex && p.fmt.widPresent { // "%[3]2d" + p.goodArgNum = false + } } - // 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) + i++ + if afterIndex { // "%[3].2d" + p.goodArgNum = false + } + argNum, i, afterIndex = p.argNumber(argNum, format, i, len(a)) + if format[i] == '*' { + i++ + p.fmt.prec, p.fmt.precPresent, argNum = intFromArg(a, argNum) if !p.fmt.precPresent { p.buf.Write(badPrecBytes) } + afterIndex = false } else { - p.fmt.prec, p.fmt.precPresent, i = parsenum(format, i+1, end) + p.fmt.prec, p.fmt.precPresent, i = parsenum(format, i, end) if !p.fmt.precPresent { p.fmt.prec = 0 p.fmt.precPresent = true } } } + + if !afterIndex { + argNum, i, afterIndex = p.argNumber(argNum, format, i, len(a)) + } + if i >= end { p.buf.Write(noVerbBytes) continue @@ -1097,30 +1163,38 @@ func (p *pp) doPrintf(format string, a []interface{}) { p.buf.WriteByte('%') // We ignore width and prec. continue } - if fieldnum >= len(a) { // out of operands - p.buf.WriteByte('%') + if !p.goodArgNum { + p.buf.Write(percentBangBytes) + p.add(c) + p.buf.Write(badIndexBytes) + continue + } else if argNum >= len(a) { // out of operands + p.buf.Write(percentBangBytes) 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) } } @@ -1130,17 +1204,17 @@ func (p *pp) doPrintf(format string, a []interface{}) { 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') |