You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

fmt.go 5.0KB

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