dump.go 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. /*
  2. * Copyright (c) 2013 Dave Collins <dave@davec.name>
  3. *
  4. * Permission to use, copy, modify, and distribute this software for any
  5. * purpose with or without fee is hereby granted, provided that the above
  6. * copyright notice and this permission notice appear in all copies.
  7. *
  8. * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  9. * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  10. * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  11. * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  12. * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  13. * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  14. * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  15. */
  16. package spew
  17. import (
  18. "bytes"
  19. "fmt"
  20. "io"
  21. "os"
  22. "reflect"
  23. "strconv"
  24. )
  25. // dumpState contains information about the state of a dump operation.
  26. type dumpState struct {
  27. w io.Writer
  28. depth int
  29. pointers map[uintptr]int
  30. ignoreNextType bool
  31. ignoreNextPad bool
  32. }
  33. // pad performs indentation according to the depth level and Config.Indent
  34. // option.
  35. func (d *dumpState) pad() {
  36. if d.ignoreNextPad {
  37. d.ignoreNextPad = false
  38. return
  39. }
  40. d.w.Write(bytes.Repeat([]byte(Config.Indent), d.depth))
  41. }
  42. // dumpPtr handles formatting of pointers by indirecting them as necessary.
  43. func (d *dumpState) dumpPtr(v reflect.Value) {
  44. // Remove pointers at or below the current depth from map used to detect
  45. // circular refs.
  46. for k, depth := range d.pointers {
  47. if depth >= d.depth {
  48. delete(d.pointers, k)
  49. }
  50. }
  51. // Keep list of all dereferenced pointers to show later.
  52. pointerChain := make([]uintptr, 0)
  53. // Figure out how many levels of indirection there are by derferencing
  54. // pointers and unpacking interfaces down the chain while detecting circular
  55. // references.
  56. nilFound := false
  57. cycleFound := false
  58. indirects := 0
  59. ve := v
  60. for ve.Kind() == reflect.Ptr {
  61. indirects++
  62. if ve.IsNil() {
  63. nilFound = true
  64. break
  65. }
  66. addr := ve.Pointer()
  67. pointerChain = append(pointerChain, addr)
  68. if pd, ok := d.pointers[addr]; ok && pd < d.depth {
  69. cycleFound = true
  70. indirects--
  71. break
  72. }
  73. d.pointers[addr] = d.depth
  74. ve = ve.Elem()
  75. if ve.Kind() == reflect.Interface {
  76. if ve.IsNil() {
  77. nilFound = true
  78. break
  79. }
  80. ve = ve.Elem()
  81. }
  82. }
  83. // Display type information.
  84. d.w.Write(openParenBytes)
  85. d.w.Write(bytes.Repeat(asteriskBytes, indirects))
  86. d.w.Write([]byte(ve.Type().String()))
  87. d.w.Write(closeParenBytes)
  88. // Display pointer information.
  89. d.w.Write(openParenBytes)
  90. for i, addr := range pointerChain {
  91. if i > 0 {
  92. d.w.Write(pointerChainBytes)
  93. }
  94. printHexPtr(d.w, addr)
  95. }
  96. d.w.Write(closeParenBytes)
  97. // Display dereferenced value.
  98. d.w.Write(openParenBytes)
  99. switch {
  100. case nilFound == true:
  101. d.w.Write(nilAngleBytes)
  102. case cycleFound == true:
  103. d.w.Write(circularBytes)
  104. default:
  105. d.ignoreNextType = true
  106. d.dump(ve)
  107. }
  108. d.w.Write(closeParenBytes)
  109. }
  110. // dump is the main workhorse for dumping a value. It uses the passed reflect
  111. // value to figure out what kind of object we are dealing with and formats it
  112. // appropriately. It is a recursive function, however circular data structures
  113. // are detected and handled properly.
  114. func (d *dumpState) dump(v reflect.Value) {
  115. // Handle pointers specially.
  116. kind := v.Kind()
  117. if kind == reflect.Ptr {
  118. d.pad()
  119. d.dumpPtr(v)
  120. return
  121. }
  122. // Print type information unless already handled elsewhere.
  123. if !d.ignoreNextType {
  124. d.pad()
  125. d.w.Write(openParenBytes)
  126. d.w.Write([]byte(v.Type().String()))
  127. d.w.Write(closeParenBytes)
  128. d.w.Write(spaceBytes)
  129. }
  130. d.ignoreNextType = false
  131. // Call error/Stringer interfaces if they exist and the handle methods flag
  132. // is enabled
  133. if !Config.DisableMethods {
  134. if (kind != reflect.Invalid) && (kind != reflect.Interface) {
  135. if handled := handleMethods(d.w, v); handled {
  136. return
  137. }
  138. }
  139. }
  140. switch kind {
  141. case reflect.Invalid:
  142. d.w.Write(invalidAngleBytes)
  143. case reflect.Bool:
  144. printBool(d.w, v.Bool())
  145. case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int:
  146. printInt(d.w, v.Int())
  147. case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint:
  148. printUint(d.w, v.Uint())
  149. case reflect.Float32:
  150. printFloat(d.w, v.Float(), 32)
  151. case reflect.Float64:
  152. printFloat(d.w, v.Float(), 64)
  153. case reflect.Complex64:
  154. printComplex(d.w, v.Complex(), 32)
  155. case reflect.Complex128:
  156. printComplex(d.w, v.Complex(), 64)
  157. case reflect.Array, reflect.Slice:
  158. d.w.Write(openBraceNewlineBytes)
  159. d.depth++
  160. if (Config.MaxDepth != 0) && (d.depth > Config.MaxDepth) {
  161. d.pad()
  162. d.w.Write(maxNewlineBytes)
  163. } else {
  164. numEntries := v.Len()
  165. for i := 0; i < numEntries; i++ {
  166. d.dump(unpackValue(v.Index(i)))
  167. if i < (numEntries - 1) {
  168. d.w.Write(commaNewlineBytes)
  169. } else {
  170. d.w.Write(newlineBytes)
  171. }
  172. }
  173. }
  174. d.depth--
  175. d.pad()
  176. d.w.Write(closeBraceBytes)
  177. case reflect.String:
  178. d.w.Write([]byte(strconv.Quote(v.String())))
  179. case reflect.Interface:
  180. // Do nothing. We should never get here due to unpackValue calls.
  181. case reflect.Ptr:
  182. // Do nothing. We should never get here since pointer have already
  183. // been handled above.
  184. case reflect.Map:
  185. d.w.Write(openBraceNewlineBytes)
  186. d.depth++
  187. if (Config.MaxDepth != 0) && (d.depth > Config.MaxDepth) {
  188. d.pad()
  189. d.w.Write(maxNewlineBytes)
  190. } else {
  191. numEntries := v.Len()
  192. keys := v.MapKeys()
  193. for i, key := range keys {
  194. d.dump(unpackValue(key))
  195. d.w.Write(colonSpaceBytes)
  196. d.ignoreNextPad = true
  197. d.dump(unpackValue(v.MapIndex(key)))
  198. if i < (numEntries - 1) {
  199. d.w.Write(commaNewlineBytes)
  200. } else {
  201. d.w.Write(newlineBytes)
  202. }
  203. }
  204. }
  205. d.depth--
  206. d.pad()
  207. d.w.Write(closeBraceBytes)
  208. case reflect.Struct:
  209. d.w.Write(openBraceNewlineBytes)
  210. d.depth++
  211. if (Config.MaxDepth != 0) && (d.depth > Config.MaxDepth) {
  212. d.pad()
  213. d.w.Write(maxNewlineBytes)
  214. } else {
  215. vt := v.Type()
  216. numFields := v.NumField()
  217. for i := 0; i < numFields; i++ {
  218. d.pad()
  219. vtf := vt.Field(i)
  220. d.w.Write([]byte(vtf.Name))
  221. d.w.Write(colonSpaceBytes)
  222. d.ignoreNextPad = true
  223. d.dump(unpackValue(v.Field(i)))
  224. if i < (numFields - 1) {
  225. d.w.Write(commaNewlineBytes)
  226. } else {
  227. d.w.Write(newlineBytes)
  228. }
  229. }
  230. }
  231. d.depth--
  232. d.pad()
  233. d.w.Write(closeBraceBytes)
  234. case reflect.Uintptr:
  235. printHexPtr(d.w, uintptr(v.Uint()))
  236. case reflect.UnsafePointer, reflect.Chan, reflect.Func:
  237. printHexPtr(d.w, v.Pointer())
  238. // There were not any other types at the time this code was written, but
  239. // fall back to letting the default fmt package handle it in case any new
  240. // types are added.
  241. default:
  242. if v.CanInterface() {
  243. fmt.Fprintf(d.w, "%v", v.Interface())
  244. } else {
  245. fmt.Fprintf(d.w, "%v", v.String())
  246. }
  247. }
  248. }
  249. // Fdump formats and displays the passed arguments to io.Writer w. It formats
  250. // exactly the same as Dump.
  251. func Fdump(w io.Writer, a ...interface{}) {
  252. for _, arg := range a {
  253. if arg == nil {
  254. w.Write(interfaceBytes)
  255. w.Write(nilAngleBytes)
  256. w.Write(newlineBytes)
  257. continue
  258. }
  259. d := dumpState{w: w}
  260. d.pointers = make(map[uintptr]int)
  261. d.dump(reflect.ValueOf(arg))
  262. d.w.Write(newlineBytes)
  263. }
  264. }
  265. /*
  266. Dump displays the passed parameters to standard out with newlines, customizable
  267. indentation, and additional debug information such as complete types and all
  268. pointer addresses used to indirect to the final value. It provides the
  269. following features over the built-in printing facilities provided by the fmt
  270. package:
  271. * Pointers are dereferenced and followed
  272. * Circular data structures are detected and handled properly
  273. * Custom error/Stringer interfaces are optionally invoked, including
  274. on unexported types
  275. * Custom types which only implement the error/Stringer interfaces via
  276. a pointer receiver are optionally invoked when passing non-pointer
  277. variables
  278. The configuration options are controlled by an exported package global,
  279. spew.Config. See ConfigState for options documentation.
  280. See Fdump if you would prefer dump to an arbitrary io.Writer.
  281. */
  282. func Dump(a ...interface{}) {
  283. Fdump(os.Stdout, a...)
  284. }