dump.go 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  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. ignoreNextIndent bool
  32. cs *ConfigState
  33. }
  34. // indent performs indentation according to the depth level and cs.Indent
  35. // option.
  36. func (d *dumpState) indent() {
  37. if d.ignoreNextIndent {
  38. d.ignoreNextIndent = 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 invalid reflect values immediately.
  128. kind := v.Kind()
  129. if kind == reflect.Invalid {
  130. d.w.Write(invalidAngleBytes)
  131. return
  132. }
  133. // Handle pointers specially.
  134. if kind == reflect.Ptr {
  135. d.indent()
  136. d.dumpPtr(v)
  137. return
  138. }
  139. // Print type information unless already handled elsewhere.
  140. if !d.ignoreNextType {
  141. d.indent()
  142. d.w.Write(openParenBytes)
  143. d.w.Write([]byte(v.Type().String()))
  144. d.w.Write(closeParenBytes)
  145. d.w.Write(spaceBytes)
  146. }
  147. d.ignoreNextType = false
  148. // Call Stringer/error interfaces if they exist and the handle methods flag
  149. // is enabled
  150. if !d.cs.DisableMethods {
  151. if (kind != reflect.Invalid) && (kind != reflect.Interface) {
  152. if handled := handleMethods(d.cs, d.w, v); handled {
  153. return
  154. }
  155. }
  156. }
  157. switch kind {
  158. case reflect.Invalid:
  159. // Do nothing. We should never get here since invalid has already
  160. // been handled above.
  161. case reflect.Bool:
  162. printBool(d.w, v.Bool())
  163. case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int:
  164. printInt(d.w, v.Int())
  165. case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint:
  166. printUint(d.w, v.Uint())
  167. case reflect.Float32:
  168. printFloat(d.w, v.Float(), 32)
  169. case reflect.Float64:
  170. printFloat(d.w, v.Float(), 64)
  171. case reflect.Complex64:
  172. printComplex(d.w, v.Complex(), 32)
  173. case reflect.Complex128:
  174. printComplex(d.w, v.Complex(), 64)
  175. case reflect.Array, reflect.Slice:
  176. d.w.Write(openBraceNewlineBytes)
  177. d.depth++
  178. if (d.cs.MaxDepth != 0) && (d.depth > d.cs.MaxDepth) {
  179. d.indent()
  180. d.w.Write(maxNewlineBytes)
  181. } else {
  182. numEntries := v.Len()
  183. for i := 0; i < numEntries; i++ {
  184. d.dump(d.unpackValue(v.Index(i)))
  185. if i < (numEntries - 1) {
  186. d.w.Write(commaNewlineBytes)
  187. } else {
  188. d.w.Write(newlineBytes)
  189. }
  190. }
  191. }
  192. d.depth--
  193. d.indent()
  194. d.w.Write(closeBraceBytes)
  195. case reflect.String:
  196. d.w.Write([]byte(strconv.Quote(v.String())))
  197. case reflect.Interface:
  198. // Do nothing. We should never get here due to unpackValue calls.
  199. case reflect.Ptr:
  200. // Do nothing. We should never get here since pointers have already
  201. // been handled above.
  202. case reflect.Map:
  203. d.w.Write(openBraceNewlineBytes)
  204. d.depth++
  205. if (d.cs.MaxDepth != 0) && (d.depth > d.cs.MaxDepth) {
  206. d.indent()
  207. d.w.Write(maxNewlineBytes)
  208. } else {
  209. numEntries := v.Len()
  210. keys := v.MapKeys()
  211. for i, key := range keys {
  212. d.dump(d.unpackValue(key))
  213. d.w.Write(colonSpaceBytes)
  214. d.ignoreNextIndent = true
  215. d.dump(d.unpackValue(v.MapIndex(key)))
  216. if i < (numEntries - 1) {
  217. d.w.Write(commaNewlineBytes)
  218. } else {
  219. d.w.Write(newlineBytes)
  220. }
  221. }
  222. }
  223. d.depth--
  224. d.indent()
  225. d.w.Write(closeBraceBytes)
  226. case reflect.Struct:
  227. d.w.Write(openBraceNewlineBytes)
  228. d.depth++
  229. if (d.cs.MaxDepth != 0) && (d.depth > d.cs.MaxDepth) {
  230. d.indent()
  231. d.w.Write(maxNewlineBytes)
  232. } else {
  233. vt := v.Type()
  234. numFields := v.NumField()
  235. for i := 0; i < numFields; i++ {
  236. d.indent()
  237. vtf := vt.Field(i)
  238. d.w.Write([]byte(vtf.Name))
  239. d.w.Write(colonSpaceBytes)
  240. d.ignoreNextIndent = true
  241. d.dump(d.unpackValue(v.Field(i)))
  242. if i < (numFields - 1) {
  243. d.w.Write(commaNewlineBytes)
  244. } else {
  245. d.w.Write(newlineBytes)
  246. }
  247. }
  248. }
  249. d.depth--
  250. d.indent()
  251. d.w.Write(closeBraceBytes)
  252. case reflect.Uintptr:
  253. printHexPtr(d.w, uintptr(v.Uint()))
  254. case reflect.UnsafePointer, reflect.Chan, reflect.Func:
  255. printHexPtr(d.w, v.Pointer())
  256. // There were not any other types at the time this code was written, but
  257. // fall back to letting the default fmt package handle it in case any new
  258. // types are added.
  259. default:
  260. if v.CanInterface() {
  261. fmt.Fprintf(d.w, "%v", v.Interface())
  262. } else {
  263. fmt.Fprintf(d.w, "%v", v.String())
  264. }
  265. }
  266. }
  267. // fdump is a helper function to consolidate the logic from the various public
  268. // methods which take varying writers and config states.
  269. func fdump(cs *ConfigState, w io.Writer, a ...interface{}) {
  270. for _, arg := range a {
  271. if arg == nil {
  272. w.Write(interfaceBytes)
  273. w.Write(spaceBytes)
  274. w.Write(nilAngleBytes)
  275. w.Write(newlineBytes)
  276. continue
  277. }
  278. d := dumpState{w: w, cs: cs}
  279. d.pointers = make(map[uintptr]int)
  280. d.dump(reflect.ValueOf(arg))
  281. d.w.Write(newlineBytes)
  282. }
  283. }
  284. // Fdump formats and displays the passed arguments to io.Writer w. It formats
  285. // exactly the same as Dump.
  286. func Fdump(w io.Writer, a ...interface{}) {
  287. fdump(&Config, w, a...)
  288. }
  289. /*
  290. Dump displays the passed parameters to standard out with newlines, customizable
  291. indentation, and additional debug information such as complete types and all
  292. pointer addresses used to indirect to the final value. It provides the
  293. following features over the built-in printing facilities provided by the fmt
  294. package:
  295. * Pointers are dereferenced and followed
  296. * Circular data structures are detected and handled properly
  297. * Custom Stringer/error interfaces are optionally invoked, including
  298. on unexported types
  299. * Custom types which only implement the Stringer/error interfaces via
  300. a pointer receiver are optionally invoked when passing non-pointer
  301. variables
  302. The configuration options are controlled by an exported package global,
  303. spew.Config. See ConfigState for options documentation.
  304. See Fdump if you would prefer dumping to an arbitrary io.Writer.
  305. */
  306. func Dump(a ...interface{}) {
  307. fdump(&Config, os.Stdout, a...)
  308. }