dump.go 8.3 KB

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