path.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  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.md 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. // MyMap.MySlices.MyField
  85. func (pa Path) String() string {
  86. var ss []string
  87. for _, s := range pa {
  88. if _, ok := s.(StructField); ok {
  89. ss = append(ss, s.String())
  90. }
  91. }
  92. return strings.TrimPrefix(strings.Join(ss, ""), ".")
  93. }
  94. // GoString returns the path to a specific node using Go syntax.
  95. //
  96. // For example:
  97. // (*root.MyMap["key"].(*mypkg.MyStruct).MySlices)[2][3].MyField
  98. func (pa Path) GoString() string {
  99. var ssPre, ssPost []string
  100. var numIndirect int
  101. for i, s := range pa {
  102. var nextStep PathStep
  103. if i+1 < len(pa) {
  104. nextStep = pa[i+1]
  105. }
  106. switch s := s.(type) {
  107. case Indirect:
  108. numIndirect++
  109. pPre, pPost := "(", ")"
  110. switch nextStep.(type) {
  111. case Indirect:
  112. continue // Next step is indirection, so let them batch up
  113. case StructField:
  114. numIndirect-- // Automatic indirection on struct fields
  115. case nil:
  116. pPre, pPost = "", "" // Last step; no need for parenthesis
  117. }
  118. if numIndirect > 0 {
  119. ssPre = append(ssPre, pPre+strings.Repeat("*", numIndirect))
  120. ssPost = append(ssPost, pPost)
  121. }
  122. numIndirect = 0
  123. continue
  124. case Transform:
  125. ssPre = append(ssPre, s.trans.name+"(")
  126. ssPost = append(ssPost, ")")
  127. continue
  128. }
  129. ssPost = append(ssPost, s.String())
  130. }
  131. for i, j := 0, len(ssPre)-1; i < j; i, j = i+1, j-1 {
  132. ssPre[i], ssPre[j] = ssPre[j], ssPre[i]
  133. }
  134. return strings.Join(ssPre, "") + strings.Join(ssPost, "")
  135. }
  136. type pathStep struct {
  137. typ reflect.Type
  138. vx, vy reflect.Value
  139. }
  140. func (ps pathStep) Type() reflect.Type { return ps.typ }
  141. func (ps pathStep) Values() (vx, vy reflect.Value) { return ps.vx, ps.vy }
  142. func (ps pathStep) String() string {
  143. if ps.typ == nil {
  144. return "<nil>"
  145. }
  146. s := ps.typ.String()
  147. if s == "" || strings.ContainsAny(s, "{}\n") {
  148. return "root" // Type too simple or complex to print
  149. }
  150. return fmt.Sprintf("{%s}", s)
  151. }
  152. // StructField represents a struct field access on a field called Name.
  153. type StructField struct{ *structField }
  154. type structField struct {
  155. pathStep
  156. name string
  157. idx int
  158. // These fields are used for forcibly accessing an unexported field.
  159. // pvx, pvy, and field are only valid if unexported is true.
  160. unexported bool
  161. mayForce bool // Forcibly allow visibility
  162. pvx, pvy reflect.Value // Parent values
  163. field reflect.StructField // Field information
  164. }
  165. func (sf StructField) Type() reflect.Type { return sf.typ }
  166. func (sf StructField) Values() (vx, vy reflect.Value) {
  167. if !sf.unexported {
  168. return sf.vx, sf.vy // CanInterface reports true
  169. }
  170. // Forcibly obtain read-write access to an unexported struct field.
  171. if sf.mayForce {
  172. vx = retrieveUnexportedField(sf.pvx, sf.field)
  173. vy = retrieveUnexportedField(sf.pvy, sf.field)
  174. return vx, vy // CanInterface reports true
  175. }
  176. return sf.vx, sf.vy // CanInterface reports false
  177. }
  178. func (sf StructField) String() string { return fmt.Sprintf(".%s", sf.name) }
  179. // Name is the field name.
  180. func (sf StructField) Name() string { return sf.name }
  181. // Index is the index of the field in the parent struct type.
  182. // See reflect.Type.Field.
  183. func (sf StructField) Index() int { return sf.idx }
  184. // SliceIndex is an index operation on a slice or array at some index Key.
  185. type SliceIndex struct{ *sliceIndex }
  186. type sliceIndex struct {
  187. pathStep
  188. xkey, ykey int
  189. isSlice bool // False for reflect.Array
  190. }
  191. func (si SliceIndex) Type() reflect.Type { return si.typ }
  192. func (si SliceIndex) Values() (vx, vy reflect.Value) { return si.vx, si.vy }
  193. func (si SliceIndex) String() string {
  194. switch {
  195. case si.xkey == si.ykey:
  196. return fmt.Sprintf("[%d]", si.xkey)
  197. case si.ykey == -1:
  198. // [5->?] means "I don't know where X[5] went"
  199. return fmt.Sprintf("[%d->?]", si.xkey)
  200. case si.xkey == -1:
  201. // [?->3] means "I don't know where Y[3] came from"
  202. return fmt.Sprintf("[?->%d]", si.ykey)
  203. default:
  204. // [5->3] means "X[5] moved to Y[3]"
  205. return fmt.Sprintf("[%d->%d]", si.xkey, si.ykey)
  206. }
  207. }
  208. // Key is the index key; it may return -1 if in a split state
  209. func (si SliceIndex) Key() int {
  210. if si.xkey != si.ykey {
  211. return -1
  212. }
  213. return si.xkey
  214. }
  215. // SplitKeys are the indexes for indexing into slices in the
  216. // x and y values, respectively. These indexes may differ due to the
  217. // insertion or removal of an element in one of the slices, causing
  218. // all of the indexes to be shifted. If an index is -1, then that
  219. // indicates that the element does not exist in the associated slice.
  220. //
  221. // Key is guaranteed to return -1 if and only if the indexes returned
  222. // by SplitKeys are not the same. SplitKeys will never return -1 for
  223. // both indexes.
  224. func (si SliceIndex) SplitKeys() (ix, iy int) { return si.xkey, si.ykey }
  225. // MapIndex is an index operation on a map at some index Key.
  226. type MapIndex struct{ *mapIndex }
  227. type mapIndex struct {
  228. pathStep
  229. key reflect.Value
  230. }
  231. func (mi MapIndex) Type() reflect.Type { return mi.typ }
  232. func (mi MapIndex) Values() (vx, vy reflect.Value) { return mi.vx, mi.vy }
  233. func (mi MapIndex) String() string { return fmt.Sprintf("[%#v]", mi.key) }
  234. // Key is the value of the map key.
  235. func (mi MapIndex) Key() reflect.Value { return mi.key }
  236. // Indirect represents pointer indirection on the parent type.
  237. type Indirect struct{ *indirect }
  238. type indirect struct {
  239. pathStep
  240. }
  241. func (in Indirect) Type() reflect.Type { return in.typ }
  242. func (in Indirect) Values() (vx, vy reflect.Value) { return in.vx, in.vy }
  243. func (in Indirect) String() string { return "*" }
  244. // TypeAssertion represents a type assertion on an interface.
  245. type TypeAssertion struct{ *typeAssertion }
  246. type typeAssertion struct {
  247. pathStep
  248. }
  249. func (ta TypeAssertion) Type() reflect.Type { return ta.typ }
  250. func (ta TypeAssertion) Values() (vx, vy reflect.Value) { return ta.vx, ta.vy }
  251. func (ta TypeAssertion) String() string { return fmt.Sprintf(".(%v)", ta.typ) }
  252. // Transform is a transformation from the parent type to the current type.
  253. type Transform struct{ *transform }
  254. type transform struct {
  255. pathStep
  256. trans *transformer
  257. }
  258. func (tf Transform) Type() reflect.Type { return tf.typ }
  259. func (tf Transform) Values() (vx, vy reflect.Value) { return tf.vx, tf.vy }
  260. func (tf Transform) String() string { return fmt.Sprintf("%s()", tf.trans.name) }
  261. // Name is the name of the Transformer.
  262. func (tf Transform) Name() string { return tf.trans.name }
  263. // Func is the function pointer to the transformer function.
  264. func (tf Transform) Func() reflect.Value { return tf.trans.fnc }
  265. // Option returns the originally constructed Transformer option.
  266. // The == operator can be used to detect the exact option used.
  267. func (tf Transform) Option() Option { return tf.trans }
  268. // pointerPath represents a dual-stack of pointers encountered when
  269. // recursively traversing the x and y values. This data structure supports
  270. // detection of cycles and determining whether the cycles are equal.
  271. // In Go, cycles can occur via pointers, slices, and maps.
  272. //
  273. // The pointerPath uses a map to represent a stack; where descension into a
  274. // pointer pushes the address onto the stack, and ascension from a pointer
  275. // pops the address from the stack. Thus, when traversing into a pointer from
  276. // reflect.Ptr, reflect.Slice element, or reflect.Map, we can detect cycles
  277. // by checking whether the pointer has already been visited. The cycle detection
  278. // uses a seperate stack for the x and y values.
  279. //
  280. // If a cycle is detected we need to determine whether the two pointers
  281. // should be considered equal. The definition of equality chosen by Equal
  282. // requires two graphs to have the same structure. To determine this, both the
  283. // x and y values must have a cycle where the previous pointers were also
  284. // encountered together as a pair.
  285. //
  286. // Semantically, this is equivalent to augmenting Indirect, SliceIndex, and
  287. // MapIndex with pointer information for the x and y values.
  288. // Suppose px and py are two pointers to compare, we then search the
  289. // Path for whether px was ever encountered in the Path history of x, and
  290. // similarly so with py. If either side has a cycle, the comparison is only
  291. // equal if both px and py have a cycle resulting from the same PathStep.
  292. //
  293. // Using a map as a stack is more performant as we can perform cycle detection
  294. // in O(1) instead of O(N) where N is len(Path).
  295. type pointerPath struct {
  296. // mx is keyed by x pointers, where the value is the associated y pointer.
  297. mx map[value.Pointer]value.Pointer
  298. // my is keyed by y pointers, where the value is the associated x pointer.
  299. my map[value.Pointer]value.Pointer
  300. }
  301. func (p *pointerPath) Init() {
  302. p.mx = make(map[value.Pointer]value.Pointer)
  303. p.my = make(map[value.Pointer]value.Pointer)
  304. }
  305. // Push indicates intent to descend into pointers vx and vy where
  306. // visited reports whether either has been seen before. If visited before,
  307. // equal reports whether both pointers were encountered together.
  308. // Pop must be called if and only if the pointers were never visited.
  309. //
  310. // The pointers vx and vy must be a reflect.Ptr, reflect.Slice, or reflect.Map
  311. // and be non-nil.
  312. func (p pointerPath) Push(vx, vy reflect.Value) (equal, visited bool) {
  313. px := value.PointerOf(vx)
  314. py := value.PointerOf(vy)
  315. _, ok1 := p.mx[px]
  316. _, ok2 := p.my[py]
  317. if ok1 || ok2 {
  318. equal = p.mx[px] == py && p.my[py] == px // Pointers paired together
  319. return equal, true
  320. }
  321. p.mx[px] = py
  322. p.my[py] = px
  323. return false, false
  324. }
  325. // Pop ascends from pointers vx and vy.
  326. func (p pointerPath) Pop(vx, vy reflect.Value) {
  327. delete(p.mx, value.PointerOf(vx))
  328. delete(p.my, value.PointerOf(vy))
  329. }
  330. // isExported reports whether the identifier is exported.
  331. func isExported(id string) bool {
  332. r, _ := utf8.DecodeRuneInString(id)
  333. return unicode.IsUpper(r)
  334. }