fmt.go 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  1. // Copyright 2018 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. package xerrors
  5. import (
  6. "fmt"
  7. "strings"
  8. "unicode"
  9. "unicode/utf8"
  10. "golang.org/x/xerrors/internal"
  11. )
  12. const percentBangString = "%!"
  13. // Errorf formats according to a format specifier and returns the string as a
  14. // value that satisfies error.
  15. //
  16. // The returned error includes the file and line number of the caller when
  17. // formatted with additional detail enabled. If the last argument is an error
  18. // the returned error's Format method will return it if the format string ends
  19. // with ": %s", ": %v", or ": %w". If the last argument is an error and the
  20. // format string ends with ": %w", the returned error implements an Unwrap
  21. // method returning it.
  22. //
  23. // If the format specifier includes a %w verb with an error operand in a
  24. // position other than at the end, the returned error will still implement an
  25. // Unwrap method returning the operand, but the error's Format method will not
  26. // return the wrapped error.
  27. //
  28. // It is invalid to include more than one %w verb or to supply it with an
  29. // operand that does not implement the error interface. The %w verb is otherwise
  30. // a synonym for %v.
  31. //
  32. // Deprecated: As of Go 1.13, use fmt.Errorf instead.
  33. func Errorf(format string, a ...interface{}) error {
  34. format = formatPlusW(format)
  35. // Support a ": %[wsv]" suffix, which works well with xerrors.Formatter.
  36. wrap := strings.HasSuffix(format, ": %w")
  37. idx, format2, ok := parsePercentW(format)
  38. percentWElsewhere := !wrap && idx >= 0
  39. if !percentWElsewhere && (wrap || strings.HasSuffix(format, ": %s") || strings.HasSuffix(format, ": %v")) {
  40. err := errorAt(a, len(a)-1)
  41. if err == nil {
  42. return &noWrapError{fmt.Sprintf(format, a...), nil, Caller(1)}
  43. }
  44. // TODO: this is not entirely correct. The error value could be
  45. // printed elsewhere in format if it mixes numbered with unnumbered
  46. // substitutions. With relatively small changes to doPrintf we can
  47. // have it optionally ignore extra arguments and pass the argument
  48. // list in its entirety.
  49. msg := fmt.Sprintf(format[:len(format)-len(": %s")], a[:len(a)-1]...)
  50. frame := Frame{}
  51. if internal.EnableTrace {
  52. frame = Caller(1)
  53. }
  54. if wrap {
  55. return &wrapError{msg, err, frame}
  56. }
  57. return &noWrapError{msg, err, frame}
  58. }
  59. // Support %w anywhere.
  60. // TODO: don't repeat the wrapped error's message when %w occurs in the middle.
  61. msg := fmt.Sprintf(format2, a...)
  62. if idx < 0 {
  63. return &noWrapError{msg, nil, Caller(1)}
  64. }
  65. err := errorAt(a, idx)
  66. if !ok || err == nil {
  67. // Too many %ws or argument of %w is not an error. Approximate the Go
  68. // 1.13 fmt.Errorf message.
  69. return &noWrapError{fmt.Sprintf("%sw(%s)", percentBangString, msg), nil, Caller(1)}
  70. }
  71. frame := Frame{}
  72. if internal.EnableTrace {
  73. frame = Caller(1)
  74. }
  75. return &wrapError{msg, err, frame}
  76. }
  77. func errorAt(args []interface{}, i int) error {
  78. if i < 0 || i >= len(args) {
  79. return nil
  80. }
  81. err, ok := args[i].(error)
  82. if !ok {
  83. return nil
  84. }
  85. return err
  86. }
  87. // formatPlusW is used to avoid the vet check that will barf at %w.
  88. func formatPlusW(s string) string {
  89. return s
  90. }
  91. // Return the index of the only %w in format, or -1 if none.
  92. // Also return a rewritten format string with %w replaced by %v, and
  93. // false if there is more than one %w.
  94. // TODO: handle "%[N]w".
  95. func parsePercentW(format string) (idx int, newFormat string, ok bool) {
  96. // Loosely copied from golang.org/x/tools/go/analysis/passes/printf/printf.go.
  97. idx = -1
  98. ok = true
  99. n := 0
  100. sz := 0
  101. var isW bool
  102. for i := 0; i < len(format); i += sz {
  103. if format[i] != '%' {
  104. sz = 1
  105. continue
  106. }
  107. // "%%" is not a format directive.
  108. if i+1 < len(format) && format[i+1] == '%' {
  109. sz = 2
  110. continue
  111. }
  112. sz, isW = parsePrintfVerb(format[i:])
  113. if isW {
  114. if idx >= 0 {
  115. ok = false
  116. } else {
  117. idx = n
  118. }
  119. // "Replace" the last character, the 'w', with a 'v'.
  120. p := i + sz - 1
  121. format = format[:p] + "v" + format[p+1:]
  122. }
  123. n++
  124. }
  125. return idx, format, ok
  126. }
  127. // Parse the printf verb starting with a % at s[0].
  128. // Return how many bytes it occupies and whether the verb is 'w'.
  129. func parsePrintfVerb(s string) (int, bool) {
  130. // Assume only that the directive is a sequence of non-letters followed by a single letter.
  131. sz := 0
  132. var r rune
  133. for i := 1; i < len(s); i += sz {
  134. r, sz = utf8.DecodeRuneInString(s[i:])
  135. if unicode.IsLetter(r) {
  136. return i + sz, r == 'w'
  137. }
  138. }
  139. return len(s), false
  140. }
  141. type noWrapError struct {
  142. msg string
  143. err error
  144. frame Frame
  145. }
  146. func (e *noWrapError) Error() string {
  147. return fmt.Sprint(e)
  148. }
  149. func (e *noWrapError) Format(s fmt.State, v rune) { FormatError(e, s, v) }
  150. func (e *noWrapError) FormatError(p Printer) (next error) {
  151. p.Print(e.msg)
  152. e.frame.Format(p)
  153. return e.err
  154. }
  155. type wrapError struct {
  156. msg string
  157. err error
  158. frame Frame
  159. }
  160. func (e *wrapError) Error() string {
  161. return fmt.Sprint(e)
  162. }
  163. func (e *wrapError) Format(s fmt.State, v rune) { FormatError(e, s, v) }
  164. func (e *wrapError) FormatError(p Printer) (next error) {
  165. p.Print(e.msg)
  166. e.frame.Format(p)
  167. return e.err
  168. }
  169. func (e *wrapError) Unwrap() error {
  170. return e.err
  171. }