path.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  1. // Copyright 2017, 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 cmp
  5. import (
  6. "fmt"
  7. "reflect"
  8. "strings"
  9. "unicode"
  10. "unicode/utf8"
  11. "github.com/google/go-cmp/cmp/internal/value"
  12. )
  13. // Path is a list of PathSteps describing the sequence of operations to get
  14. // from some root type to the current position in the value tree.
  15. // The first Path element is always an operation-less PathStep that exists
  16. // simply to identify the initial type.
  17. //
  18. // When traversing structs with embedded structs, the embedded struct will
  19. // always be accessed as a field before traversing the fields of the
  20. // embedded struct themselves. That is, an exported field from the
  21. // embedded struct will never be accessed directly from the parent struct.
  22. type Path []PathStep
  23. // PathStep is a union-type for specific operations to traverse
  24. // a value's tree structure. Users of this package never need to implement
  25. // these types as values of this type will be returned by this package.
  26. //
  27. // Implementations of this interface are
  28. // StructField, SliceIndex, MapIndex, Indirect, TypeAssertion, and Transform.
  29. type PathStep interface {
  30. String() string
  31. // Type is the resulting type after performing the path step.
  32. Type() reflect.Type
  33. // Values is the resulting values after performing the path step.
  34. // The type of each valid value is guaranteed to be identical to Type.
  35. //
  36. // In some cases, one or both may be invalid or have restrictions:
  37. // - For StructField, both are not interface-able if the current field
  38. // is unexported and the struct type is not explicitly permitted by
  39. // an Exporter to traverse unexported fields.
  40. // - For SliceIndex, one may be invalid if an element is missing from
  41. // either the x or y slice.
  42. // - For MapIndex, one may be invalid if an entry is missing from
  43. // either the x or y map.
  44. //
  45. // The provided values must not be mutated.
  46. Values() (vx, vy reflect.Value)
  47. }
  48. var (
  49. _ PathStep = StructField{}
  50. _ PathStep = SliceIndex{}
  51. _ PathStep = MapIndex{}
  52. _ PathStep = Indirect{}
  53. _ PathStep = TypeAssertion{}
  54. _ PathStep = Transform{}
  55. )
  56. func (pa *Path) push(s PathStep) {
  57. *pa = append(*pa, s)
  58. }
  59. func (pa *Path) pop() {
  60. *pa = (*pa)[:len(*pa)-1]
  61. }
  62. // Last returns the last PathStep in the Path.
  63. // If the path is empty, this returns a non-nil PathStep that reports a nil Type.
  64. func (pa Path) Last() PathStep {
  65. return pa.Index(-1)
  66. }
  67. // Index returns the ith step in the Path and supports negative indexing.
  68. // A negative index starts counting from the tail of the Path such that -1
  69. // refers to the last step, -2 refers to the second-to-last step, and so on.
  70. // If index is invalid, this returns a non-nil PathStep that reports a nil Type.
  71. func (pa Path) Index(i int) PathStep {
  72. if i < 0 {
  73. i = len(pa) + i
  74. }
  75. if i < 0 || i >= len(pa) {
  76. return pathStep{}
  77. }
  78. return pa[i]
  79. }
  80. // String returns the simplified path to a node.
  81. // The simplified path only contains struct field accesses.
  82. //
  83. // For example:
  84. //
  85. // MyMap.MySlices.MyField
  86. func (pa Path) String() string {
  87. var ss []string
  88. for _, s := range pa {
  89. if _, ok := s.(StructField); ok {
  90. ss = append(ss, s.String())
  91. }
  92. }
  93. return strings.TrimPrefix(strings.Join(ss, ""), ".")
  94. }
  95. // GoString returns the path to a specific node using Go syntax.
  96. //
  97. // For example:
  98. //
  99. // (*root.MyMap["key"].(*mypkg.MyStruct).MySlices)[2][3].MyField
  100. func (pa Path) GoString() string {
  101. var ssPre, ssPost []string
  102. var numIndirect int
  103. for i, s := range pa {
  104. var nextStep PathStep
  105. if i+1 < len(pa) {
  106. nextStep = pa[i+1]
  107. }
  108. switch s := s.(type) {
  109. case Indirect:
  110. numIndirect++
  111. pPre, pPost := "(", ")"
  112. switch nextStep.(type) {
  113. case Indirect:
  114. continue // Next step is indirection, so let them batch up
  115. case StructField:
  116. numIndirect-- // Automatic indirection on struct fields
  117. case nil:
  118. pPre, pPost = "", "" // Last step; no need for parenthesis
  119. }
  120. if numIndirect > 0 {
  121. ssPre = append(ssPre, pPre+strings.Repeat("*", numIndirect))
  122. ssPost = append(ssPost, pPost)
  123. }
  124. numIndirect = 0
  125. continue
  126. case Transform:
  127. ssPre = append(ssPre, s.trans.name+"(")
  128. ssPost = append(ssPost, ")")
  129. continue
  130. }
  131. ssPost = append(ssPost, s.String())
  132. }
  133. for i, j := 0, len(ssPre)-1; i < j; i, j = i+1, j-1 {
  134. ssPre[i], ssPre[j] = ssPre[j], ssPre[i]
  135. }
  136. return strings.Join(ssPre, "") + strings.Join(ssPost, "")
  137. }
  138. type pathStep struct {
  139. typ reflect.Type
  140. vx, vy reflect.Value
  141. }
  142. func (ps pathStep) Type() reflect.Type { return ps.typ }
  143. func (ps pathStep) Values() (vx, vy reflect.Value) { return ps.vx, ps.vy }
  144. func (ps pathStep) String() string {
  145. if ps.typ == nil {
  146. return "<nil>"
  147. }
  148. s := value.TypeString(ps.typ, false)
  149. if s == "" || strings.ContainsAny(s, "{}\n") {
  150. return "root" // Type too simple or complex to print
  151. }
  152. return fmt.Sprintf("{%s}", s)
  153. }
  154. // StructField represents a struct field access on a field called Name.
  155. type StructField struct{ *structField }
  156. type structField struct {
  157. pathStep
  158. name string
  159. idx int
  160. // These fields are used for forcibly accessing an unexported field.
  161. // pvx, pvy, and field are only valid if unexported is true.
  162. unexported bool
  163. mayForce bool // Forcibly allow visibility
  164. paddr bool // Was parent addressable?
  165. pvx, pvy reflect.Value // Parent values (always addressable)
  166. field reflect.StructField // Field information
  167. }
  168. func (sf StructField) Type() reflect.Type { return sf.typ }
  169. func (sf StructField) Values() (vx, vy reflect.Value) {
  170. if !sf.unexported {
  171. return sf.vx, sf.vy // CanInterface reports true
  172. }
  173. // Forcibly obtain read-write access to an unexported struct field.
  174. if sf.mayForce {
  175. vx = retrieveUnexportedField(sf.pvx, sf.field, sf.paddr)
  176. vy = retrieveUnexportedField(sf.pvy, sf.field, sf.paddr)
  177. return vx, vy // CanInterface reports true
  178. }
  179. return sf.vx, sf.vy // CanInterface reports false
  180. }
  181. func (sf StructField) String() string { return fmt.Sprintf(".%s", sf.name) }
  182. // Name is the field name.
  183. func (sf StructField) Name() string { return sf.name }
  184. // Index is the index of the field in the parent struct type.
  185. // See reflect.Type.Field.
  186. func (sf StructField) Index() int { return sf.idx }
  187. // SliceIndex is an index operation on a slice or array at some index Key.
  188. type SliceIndex struct{ *sliceIndex }
  189. type sliceIndex struct {
  190. pathStep
  191. xkey, ykey int
  192. isSlice bool // False for reflect.Array
  193. }
  194. func (si SliceIndex) Type() reflect.Type { return si.typ }
  195. func (si SliceIndex) Values() (vx, vy reflect.Value) { return si.vx, si.vy }
  196. func (si SliceIndex) String() string {
  197. switch {
  198. case si.xkey == si.ykey:
  199. return fmt.Sprintf("[%d]", si.xkey)
  200. case si.ykey == -1:
  201. // [5->?] means "I don't know where X[5] went"
  202. return fmt.Sprintf("[%d->?]", si.xkey)
  203. case si.xkey == -1:
  204. // [?->3] means "I don't know where Y[3] came from"
  205. return fmt.Sprintf("[?->%d]", si.ykey)
  206. default:
  207. // [5->3] means "X[5] moved to Y[3]"
  208. return fmt.Sprintf("[%d->%d]", si.xkey, si.ykey)
  209. }
  210. }
  211. // Key is the index key; it may return -1 if in a split state
  212. func (si SliceIndex) Key() int {
  213. if si.xkey != si.ykey {
  214. return -1
  215. }
  216. return si.xkey
  217. }
  218. // SplitKeys are the indexes for indexing into slices in the
  219. // x and y values, respectively. These indexes may differ due to the
  220. // insertion or removal of an element in one of the slices, causing
  221. // all of the indexes to be shifted. If an index is -1, then that
  222. // indicates that the element does not exist in the associated slice.
  223. //
  224. // Key is guaranteed to return -1 if and only if the indexes returned
  225. // by SplitKeys are not the same. SplitKeys will never return -1 for
  226. // both indexes.
  227. func (si SliceIndex) SplitKeys() (ix, iy int) { return si.xkey, si.ykey }
  228. // MapIndex is an index operation on a map at some index Key.
  229. type MapIndex struct{ *mapIndex }
  230. type mapIndex struct {
  231. pathStep
  232. key reflect.Value
  233. }
  234. func (mi MapIndex) Type() reflect.Type { return mi.typ }
  235. func (mi MapIndex) Values() (vx, vy reflect.Value) { return mi.vx, mi.vy }
  236. func (mi MapIndex) String() string { return fmt.Sprintf("[%#v]", mi.key) }
  237. // Key is the value of the map key.
  238. func (mi MapIndex) Key() reflect.Value { return mi.key }
  239. // Indirect represents pointer indirection on the parent type.
  240. type Indirect struct{ *indirect }
  241. type indirect struct {
  242. pathStep
  243. }
  244. func (in Indirect) Type() reflect.Type { return in.typ }
  245. func (in Indirect) Values() (vx, vy reflect.Value) { return in.vx, in.vy }
  246. func (in Indirect) String() string { return "*" }
  247. // TypeAssertion represents a type assertion on an interface.
  248. type TypeAssertion struct{ *typeAssertion }
  249. type typeAssertion struct {
  250. pathStep
  251. }
  252. func (ta TypeAssertion) Type() reflect.Type { return ta.typ }
  253. func (ta TypeAssertion) Values() (vx, vy reflect.Value) { return ta.vx, ta.vy }
  254. func (ta TypeAssertion) String() string { return fmt.Sprintf(".(%v)", value.TypeString(ta.typ, false)) }
  255. // Transform is a transformation from the parent type to the current type.
  256. type Transform struct{ *transform }
  257. type transform struct {
  258. pathStep
  259. trans *transformer
  260. }
  261. func (tf Transform) Type() reflect.Type { return tf.typ }
  262. func (tf Transform) Values() (vx, vy reflect.Value) { return tf.vx, tf.vy }
  263. func (tf Transform) String() string { return fmt.Sprintf("%s()", tf.trans.name) }
  264. // Name is the name of the Transformer.
  265. func (tf Transform) Name() string { return tf.trans.name }
  266. // Func is the function pointer to the transformer function.
  267. func (tf Transform) Func() reflect.Value { return tf.trans.fnc }
  268. // Option returns the originally constructed Transformer option.
  269. // The == operator can be used to detect the exact option used.
  270. func (tf Transform) Option() Option { return tf.trans }
  271. // pointerPath represents a dual-stack of pointers encountered when
  272. // recursively traversing the x and y values. This data structure supports
  273. // detection of cycles and determining whether the cycles are equal.
  274. // In Go, cycles can occur via pointers, slices, and maps.
  275. //
  276. // The pointerPath uses a map to represent a stack; where descension into a
  277. // pointer pushes the address onto the stack, and ascension from a pointer
  278. // pops the address from the stack. Thus, when traversing into a pointer from
  279. // reflect.Ptr, reflect.Slice element, or reflect.Map, we can detect cycles
  280. // by checking whether the pointer has already been visited. The cycle detection
  281. // uses a separate stack for the x and y values.
  282. //
  283. // If a cycle is detected we need to determine whether the two pointers
  284. // should be considered equal. The definition of equality chosen by Equal
  285. // requires two graphs to have the same structure. To determine this, both the
  286. // x and y values must have a cycle where the previous pointers were also
  287. // encountered together as a pair.
  288. //
  289. // Semantically, this is equivalent to augmenting Indirect, SliceIndex, and
  290. // MapIndex with pointer information for the x and y values.
  291. // Suppose px and py are two pointers to compare, we then search the
  292. // Path for whether px was ever encountered in the Path history of x, and
  293. // similarly so with py. If either side has a cycle, the comparison is only
  294. // equal if both px and py have a cycle resulting from the same PathStep.
  295. //
  296. // Using a map as a stack is more performant as we can perform cycle detection
  297. // in O(1) instead of O(N) where N is len(Path).
  298. type pointerPath struct {
  299. // mx is keyed by x pointers, where the value is the associated y pointer.
  300. mx map[value.Pointer]value.Pointer
  301. // my is keyed by y pointers, where the value is the associated x pointer.
  302. my map[value.Pointer]value.Pointer
  303. }
  304. func (p *pointerPath) Init() {
  305. p.mx = make(map[value.Pointer]value.Pointer)
  306. p.my = make(map[value.Pointer]value.Pointer)
  307. }
  308. // Push indicates intent to descend into pointers vx and vy where
  309. // visited reports whether either has been seen before. If visited before,
  310. // equal reports whether both pointers were encountered together.
  311. // Pop must be called if and only if the pointers were never visited.
  312. //
  313. // The pointers vx and vy must be a reflect.Ptr, reflect.Slice, or reflect.Map
  314. // and be non-nil.
  315. func (p pointerPath) Push(vx, vy reflect.Value) (equal, visited bool) {
  316. px := value.PointerOf(vx)
  317. py := value.PointerOf(vy)
  318. _, ok1 := p.mx[px]
  319. _, ok2 := p.my[py]
  320. if ok1 || ok2 {
  321. equal = p.mx[px] == py && p.my[py] == px // Pointers paired together
  322. return equal, true
  323. }
  324. p.mx[px] = py
  325. p.my[py] = px
  326. return false, false
  327. }
  328. // Pop ascends from pointers vx and vy.
  329. func (p pointerPath) Pop(vx, vy reflect.Value) {
  330. delete(p.mx, value.PointerOf(vx))
  331. delete(p.my, value.PointerOf(vy))
  332. }
  333. // isExported reports whether the identifier is exported.
  334. func isExported(id string) bool {
  335. r, _ := utf8.DecodeRuneInString(id)
  336. return unicode.IsUpper(r)
  337. }