dump.go 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  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. cs *ConfigState
  33. }
  34. // pad performs indentation according to the depth level and cs.Indent
  35. // option.
  36. func (d *dumpState) pad() {
  37. if d.ignoreNextPad {
  38. d.ignoreNextPad = false
  39. return
  40. }
  41. d.w.Write(bytes.Repeat([]byte(d.cs.Indent), d.depth))
  42. }
  43. // unpackValue returns values inside of non-nil interfaces when possible.
  44. // This is useful for data types like structs, arrays, slices, and maps which
  45. // can contain varying types packed inside an interface.
  46. func (d *dumpState) unpackValue(v reflect.Value) reflect.Value {
  47. if v.Kind() == reflect.Interface && !v.IsNil() {
  48. v = v.Elem()
  49. }
  50. return v
  51. }
  52. // dumpPtr handles formatting of pointers by indirecting them as necessary.
  53. func (d *dumpState) dumpPtr(v reflect.Value) {
  54. // Remove pointers at or below the current depth from map used to detect
  55. // circular refs.
  56. for k, depth := range d.pointers {
  57. if depth >= d.depth {
  58. delete(d.pointers, k)
  59. }
  60. }
  61. // Keep list of all dereferenced pointers to show later.
  62. pointerChain := make([]uintptr, 0)
  63. // Figure out how many levels of indirection there are by dereferencing
  64. // pointers and unpacking interfaces down the chain while detecting circular
  65. // references.
  66. nilFound := false
  67. cycleFound := false
  68. indirects := 0
  69. ve := v
  70. for ve.Kind() == reflect.Ptr {
  71. if ve.IsNil() {
  72. nilFound = true
  73. break
  74. }
  75. indirects++
  76. addr := ve.Pointer()
  77. pointerChain = append(pointerChain, addr)
  78. if pd, ok := d.pointers[addr]; ok && pd < d.depth {
  79. cycleFound = true
  80. indirects--
  81. break
  82. }
  83. d.pointers[addr] = d.depth
  84. ve = ve.Elem()
  85. if ve.Kind() == reflect.Interface {
  86. if ve.IsNil() {
  87. nilFound = true
  88. break
  89. }
  90. ve = ve.Elem()
  91. }
  92. }
  93. // Display type information.
  94. d.w.Write(openParenBytes)
  95. d.w.Write(bytes.Repeat(asteriskBytes, indirects))
  96. d.w.Write([]byte(ve.Type().String()))
  97. d.w.Write(closeParenBytes)
  98. // Display pointer information.
  99. if len(pointerChain) > 0 {
  100. d.w.Write(openParenBytes)
  101. for i, addr := range pointerChain {
  102. if i > 0 {
  103. d.w.Write(pointerChainBytes)
  104. }
  105. printHexPtr(d.w, addr)
  106. }
  107. d.w.Write(closeParenBytes)
  108. }
  109. // Display dereferenced value.
  110. d.w.Write(openParenBytes)
  111. switch {
  112. case nilFound == true:
  113. d.w.Write(nilAngleBytes)
  114. case cycleFound == true:
  115. d.w.Write(circularBytes)
  116. default:
  117. d.ignoreNextType = true
  118. d.dump(ve)
  119. }
  120. d.w.Write(closeParenBytes)
  121. }
  122. // dump is the main workhorse for dumping a value. It uses the passed reflect
  123. // value to figure out what kind of object we are dealing with and formats it
  124. // appropriately. It is a recursive function, however circular data structures
  125. // are detected and handled properly.
  126. func (d *dumpState) dump(v reflect.Value) {
  127. // Handle pointers specially.
  128. kind := v.Kind()
  129. if kind == reflect.Ptr {
  130. d.pad()
  131. d.dumpPtr(v)
  132. return
  133. }
  134. // Print type information unless already handled elsewhere.
  135. if !d.ignoreNextType {
  136. d.pad()
  137. d.w.Write(openParenBytes)
  138. d.w.Write([]byte(v.Type().String()))
  139. d.w.Write(closeParenBytes)
  140. d.w.Write(spaceBytes)
  141. }
  142. d.ignoreNextType = false
  143. // Call Stringer/error interfaces if they exist and the handle methods flag
  144. // is enabled
  145. if !d.cs.DisableMethods {
  146. if (kind != reflect.Invalid) && (kind != reflect.Interface) {
  147. if handled := handleMethods(d.cs, d.w, v); handled {
  148. return
  149. }
  150. }
  151. }
  152. switch kind {
  153. case reflect.Invalid:
  154. d.w.Write(invalidAngleBytes)
  155. case reflect.Bool:
  156. printBool(d.w, v.Bool())
  157. case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int:
  158. printInt(d.w, v.Int())
  159. case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint:
  160. printUint(d.w, v.Uint())
  161. case reflect.Float32:
  162. printFloat(d.w, v.Float(), 32)
  163. case reflect.Float64:
  164. printFloat(d.w, v.Float(), 64)
  165. case reflect.Complex64:
  166. printComplex(d.w, v.Complex(), 32)
  167. case reflect.Complex128:
  168. printComplex(d.w, v.Complex(), 64)
  169. case reflect.Array, reflect.Slice:
  170. d.w.Write(openBraceNewlineBytes)
  171. d.depth++
  172. if (d.cs.MaxDepth != 0) && (d.depth > d.cs.MaxDepth) {
  173. d.pad()
  174. d.w.Write(maxNewlineBytes)
  175. } else {
  176. numEntries := v.Len()
  177. for i := 0; i < numEntries; i++ {
  178. d.dump(d.unpackValue(v.Index(i)))
  179. if i < (numEntries - 1) {
  180. d.w.Write(commaNewlineBytes)
  181. } else {
  182. d.w.Write(newlineBytes)
  183. }
  184. }
  185. }
  186. d.depth--
  187. d.pad()
  188. d.w.Write(closeBraceBytes)
  189. case reflect.String:
  190. d.w.Write([]byte(strconv.Quote(v.String())))
  191. case reflect.Interface:
  192. // Do nothing. We should never get here due to unpackValue calls.
  193. case reflect.Ptr:
  194. // Do nothing. We should never get here since pointers have already
  195. // been handled above.
  196. case reflect.Map:
  197. d.w.Write(openBraceNewlineBytes)
  198. d.depth++
  199. if (d.cs.MaxDepth != 0) && (d.depth > d.cs.MaxDepth) {
  200. d.pad()
  201. d.w.Write(maxNewlineBytes)
  202. } else {
  203. numEntries := v.Len()
  204. keys := v.MapKeys()
  205. for i, key := range keys {
  206. d.dump(d.unpackValue(key))
  207. d.w.Write(colonSpaceBytes)
  208. d.ignoreNextPad = true
  209. d.dump(d.unpackValue(v.MapIndex(key)))
  210. if i < (numEntries - 1) {
  211. d.w.Write(commaNewlineBytes)
  212. } else {
  213. d.w.Write(newlineBytes)
  214. }
  215. }
  216. }
  217. d.depth--
  218. d.pad()
  219. d.w.Write(closeBraceBytes)
  220. case reflect.Struct:
  221. d.w.Write(openBraceNewlineBytes)
  222. d.depth++
  223. if (d.cs.MaxDepth != 0) && (d.depth > d.cs.MaxDepth) {
  224. d.pad()
  225. d.w.Write(maxNewlineBytes)
  226. } else {
  227. vt := v.Type()
  228. numFields := v.NumField()
  229. for i := 0; i < numFields; i++ {
  230. d.pad()
  231. vtf := vt.Field(i)
  232. d.w.Write([]byte(vtf.Name))
  233. d.w.Write(colonSpaceBytes)
  234. d.ignoreNextPad = true
  235. d.dump(d.unpackValue(v.Field(i)))
  236. if i < (numFields - 1) {
  237. d.w.Write(commaNewlineBytes)
  238. } else {
  239. d.w.Write(newlineBytes)
  240. }
  241. }
  242. }
  243. d.depth--
  244. d.pad()
  245. d.w.Write(closeBraceBytes)
  246. case reflect.Uintptr:
  247. printHexPtr(d.w, uintptr(v.Uint()))
  248. case reflect.UnsafePointer, reflect.Chan, reflect.Func:
  249. printHexPtr(d.w, v.Pointer())
  250. // There were not any other types at the time this code was written, but
  251. // fall back to letting the default fmt package handle it in case any new
  252. // types are added.
  253. default:
  254. if v.CanInterface() {
  255. fmt.Fprintf(d.w, "%v", v.Interface())
  256. } else {
  257. fmt.Fprintf(d.w, "%v", v.String())
  258. }
  259. }
  260. }
  261. // fdump is a helper function to consolidate the logic from the various public
  262. // methods which take varying writers and config states.
  263. func fdump(cs *ConfigState, w io.Writer, a ...interface{}) {
  264. for _, arg := range a {
  265. if arg == nil {
  266. w.Write(interfaceBytes)
  267. w.Write(spaceBytes)
  268. w.Write(nilAngleBytes)
  269. w.Write(newlineBytes)
  270. continue
  271. }
  272. d := dumpState{w: w, cs: cs}
  273. d.pointers = make(map[uintptr]int)
  274. d.dump(reflect.ValueOf(arg))
  275. d.w.Write(newlineBytes)
  276. }
  277. }
  278. // Fdump formats and displays the passed arguments to io.Writer w. It formats
  279. // exactly the same as Dump.
  280. func Fdump(w io.Writer, a ...interface{}) {
  281. fdump(&Config, w, a...)
  282. }
  283. /*
  284. Dump displays the passed parameters to standard out with newlines, customizable
  285. indentation, and additional debug information such as complete types and all
  286. pointer addresses used to indirect to the final value. It provides the
  287. following features over the built-in printing facilities provided by the fmt
  288. package:
  289. * Pointers are dereferenced and followed
  290. * Circular data structures are detected and handled properly
  291. * Custom Stringer/error interfaces are optionally invoked, including
  292. on unexported types
  293. * Custom types which only implement the Stringer/error interfaces via
  294. a pointer receiver are optionally invoked when passing non-pointer
  295. variables
  296. The configuration options are controlled by an exported package global,
  297. spew.Config. See ConfigState for options documentation.
  298. See Fdump if you would prefer dumping to an arbitrary io.Writer.
  299. */
  300. func Dump(a ...interface{}) {
  301. fdump(&Config, os.Stdout, a...)
  302. }