You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

309 lines
9.6 KiB

  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. )
  12. // Path is a list of PathSteps describing the sequence of operations to get
  13. // from some root type to the current position in the value tree.
  14. // The first Path element is always an operation-less PathStep that exists
  15. // simply to identify the initial type.
  16. //
  17. // When traversing structs with embedded structs, the embedded struct will
  18. // always be accessed as a field before traversing the fields of the
  19. // embedded struct themselves. That is, an exported field from the
  20. // embedded struct will never be accessed directly from the parent struct.
  21. type Path []PathStep
  22. // PathStep is a union-type for specific operations to traverse
  23. // a value's tree structure. Users of this package never need to implement
  24. // these types as values of this type will be returned by this package.
  25. //
  26. // Implementations of this interface are
  27. // StructField, SliceIndex, MapIndex, Indirect, TypeAssertion, and Transform.
  28. type PathStep interface {
  29. String() string
  30. // Type is the resulting type after performing the path step.
  31. Type() reflect.Type
  32. // Values is the resulting values after performing the path step.
  33. // The type of each valid value is guaranteed to be identical to Type.
  34. //
  35. // In some cases, one or both may be invalid or have restrictions:
  36. // • For StructField, both are not interface-able if the current field
  37. // is unexported and the struct type is not explicitly permitted by
  38. // AllowUnexported to traverse unexported fields.
  39. // • For SliceIndex, one may be invalid if an element is missing from
  40. // either the x or y slice.
  41. // • For MapIndex, one may be invalid if an entry is missing from
  42. // either the x or y map.
  43. //
  44. // The provided values must not be mutated.
  45. Values() (vx, vy reflect.Value)
  46. }
  47. var (
  48. _ PathStep = StructField{}
  49. _ PathStep = SliceIndex{}
  50. _ PathStep = MapIndex{}
  51. _ PathStep = Indirect{}
  52. _ PathStep = TypeAssertion{}
  53. _ PathStep = Transform{}
  54. )
  55. func (pa *Path) push(s PathStep) {
  56. *pa = append(*pa, s)
  57. }
  58. func (pa *Path) pop() {
  59. *pa = (*pa)[:len(*pa)-1]
  60. }
  61. // Last returns the last PathStep in the Path.
  62. // If the path is empty, this returns a non-nil PathStep that reports a nil Type.
  63. func (pa Path) Last() PathStep {
  64. return pa.Index(-1)
  65. }
  66. // Index returns the ith step in the Path and supports negative indexing.
  67. // A negative index starts counting from the tail of the Path such that -1
  68. // refers to the last step, -2 refers to the second-to-last step, and so on.
  69. // If index is invalid, this returns a non-nil PathStep that reports a nil Type.
  70. func (pa Path) Index(i int) PathStep {
  71. if i < 0 {
  72. i = len(pa) + i
  73. }
  74. if i < 0 || i >= len(pa) {
  75. return pathStep{}
  76. }
  77. return pa[i]
  78. }
  79. // String returns the simplified path to a node.
  80. // The simplified path only contains struct field accesses.
  81. //
  82. // For example:
  83. // MyMap.MySlices.MyField
  84. func (pa Path) String() string {
  85. var ss []string
  86. for _, s := range pa {
  87. if _, ok := s.(StructField); ok {
  88. ss = append(ss, s.String())
  89. }
  90. }
  91. return strings.TrimPrefix(strings.Join(ss, ""), ".")
  92. }
  93. // GoString returns the path to a specific node using Go syntax.
  94. //
  95. // For example:
  96. // (*root.MyMap["key"].(*mypkg.MyStruct).MySlices)[2][3].MyField
  97. func (pa Path) GoString() string {
  98. var ssPre, ssPost []string
  99. var numIndirect int
  100. for i, s := range pa {
  101. var nextStep PathStep
  102. if i+1 < len(pa) {
  103. nextStep = pa[i+1]
  104. }
  105. switch s := s.(type) {
  106. case Indirect:
  107. numIndirect++
  108. pPre, pPost := "(", ")"
  109. switch nextStep.(type) {
  110. case Indirect:
  111. continue // Next step is indirection, so let them batch up
  112. case StructField:
  113. numIndirect-- // Automatic indirection on struct fields
  114. case nil:
  115. pPre, pPost = "", "" // Last step; no need for parenthesis
  116. }
  117. if numIndirect > 0 {
  118. ssPre = append(ssPre, pPre+strings.Repeat("*", numIndirect))
  119. ssPost = append(ssPost, pPost)
  120. }
  121. numIndirect = 0
  122. continue
  123. case Transform:
  124. ssPre = append(ssPre, s.trans.name+"(")
  125. ssPost = append(ssPost, ")")
  126. continue
  127. }
  128. ssPost = append(ssPost, s.String())
  129. }
  130. for i, j := 0, len(ssPre)-1; i < j; i, j = i+1, j-1 {
  131. ssPre[i], ssPre[j] = ssPre[j], ssPre[i]
  132. }
  133. return strings.Join(ssPre, "") + strings.Join(ssPost, "")
  134. }
  135. type pathStep struct {
  136. typ reflect.Type
  137. vx, vy reflect.Value
  138. }
  139. func (ps pathStep) Type() reflect.Type { return ps.typ }
  140. func (ps pathStep) Values() (vx, vy reflect.Value) { return ps.vx, ps.vy }
  141. func (ps pathStep) String() string {
  142. if ps.typ == nil {
  143. return "<nil>"
  144. }
  145. s := ps.typ.String()
  146. if s == "" || strings.ContainsAny(s, "{}\n") {
  147. return "root" // Type too simple or complex to print
  148. }
  149. return fmt.Sprintf("{%s}", s)
  150. }
  151. // StructField represents a struct field access on a field called Name.
  152. type StructField struct{ *structField }
  153. type structField struct {
  154. pathStep
  155. name string
  156. idx int
  157. // These fields are used for forcibly accessing an unexported field.
  158. // pvx, pvy, and field are only valid if unexported is true.
  159. unexported bool
  160. mayForce bool // Forcibly allow visibility
  161. pvx, pvy reflect.Value // Parent values
  162. field reflect.StructField // Field information
  163. }
  164. func (sf StructField) Type() reflect.Type { return sf.typ }
  165. func (sf StructField) Values() (vx, vy reflect.Value) {
  166. if !sf.unexported {
  167. return sf.vx, sf.vy // CanInterface reports true
  168. }
  169. // Forcibly obtain read-write access to an unexported struct field.
  170. if sf.mayForce {
  171. vx = retrieveUnexportedField(sf.pvx, sf.field)
  172. vy = retrieveUnexportedField(sf.pvy, sf.field)
  173. return vx, vy // CanInterface reports true
  174. }
  175. return sf.vx, sf.vy // CanInterface reports false
  176. }
  177. func (sf StructField) String() string { return fmt.Sprintf(".%s", sf.name) }
  178. // Name is the field name.
  179. func (sf StructField) Name() string { return sf.name }
  180. // Index is the index of the field in the parent struct type.
  181. // See reflect.Type.Field.
  182. func (sf StructField) Index() int { return sf.idx }
  183. // SliceIndex is an index operation on a slice or array at some index Key.
  184. type SliceIndex struct{ *sliceIndex }
  185. type sliceIndex struct {
  186. pathStep
  187. xkey, ykey int
  188. }
  189. func (si SliceIndex) Type() reflect.Type { return si.typ }
  190. func (si SliceIndex) Values() (vx, vy reflect.Value) { return si.vx, si.vy }
  191. func (si SliceIndex) String() string {
  192. switch {
  193. case si.xkey == si.ykey:
  194. return fmt.Sprintf("[%d]", si.xkey)
  195. case si.ykey == -1:
  196. // [5->?] means "I don't know where X[5] went"
  197. return fmt.Sprintf("[%d->?]", si.xkey)
  198. case si.xkey == -1:
  199. // [?->3] means "I don't know where Y[3] came from"
  200. return fmt.Sprintf("[?->%d]", si.ykey)
  201. default:
  202. // [5->3] means "X[5] moved to Y[3]"
  203. return fmt.Sprintf("[%d->%d]", si.xkey, si.ykey)
  204. }
  205. }
  206. // Key is the index key; it may return -1 if in a split state
  207. func (si SliceIndex) Key() int {
  208. if si.xkey != si.ykey {
  209. return -1
  210. }
  211. return si.xkey
  212. }
  213. // SplitKeys are the indexes for indexing into slices in the
  214. // x and y values, respectively. These indexes may differ due to the
  215. // insertion or removal of an element in one of the slices, causing
  216. // all of the indexes to be shifted. If an index is -1, then that
  217. // indicates that the element does not exist in the associated slice.
  218. //
  219. // Key is guaranteed to return -1 if and only if the indexes returned
  220. // by SplitKeys are not the same. SplitKeys will never return -1 for
  221. // both indexes.
  222. func (si SliceIndex) SplitKeys() (ix, iy int) { return si.xkey, si.ykey }
  223. // MapIndex is an index operation on a map at some index Key.
  224. type MapIndex struct{ *mapIndex }
  225. type mapIndex struct {
  226. pathStep
  227. key reflect.Value
  228. }
  229. func (mi MapIndex) Type() reflect.Type { return mi.typ }
  230. func (mi MapIndex) Values() (vx, vy reflect.Value) { return mi.vx, mi.vy }
  231. func (mi MapIndex) String() string { return fmt.Sprintf("[%#v]", mi.key) }
  232. // Key is the value of the map key.
  233. func (mi MapIndex) Key() reflect.Value { return mi.key }
  234. // Indirect represents pointer indirection on the parent type.
  235. type Indirect struct{ *indirect }
  236. type indirect struct {
  237. pathStep
  238. }
  239. func (in Indirect) Type() reflect.Type { return in.typ }
  240. func (in Indirect) Values() (vx, vy reflect.Value) { return in.vx, in.vy }
  241. func (in Indirect) String() string { return "*" }
  242. // TypeAssertion represents a type assertion on an interface.
  243. type TypeAssertion struct{ *typeAssertion }
  244. type typeAssertion struct {
  245. pathStep
  246. }
  247. func (ta TypeAssertion) Type() reflect.Type { return ta.typ }
  248. func (ta TypeAssertion) Values() (vx, vy reflect.Value) { return ta.vx, ta.vy }
  249. func (ta TypeAssertion) String() string { return fmt.Sprintf(".(%v)", ta.typ) }
  250. // Transform is a transformation from the parent type to the current type.
  251. type Transform struct{ *transform }
  252. type transform struct {
  253. pathStep
  254. trans *transformer
  255. }
  256. func (tf Transform) Type() reflect.Type { return tf.typ }
  257. func (tf Transform) Values() (vx, vy reflect.Value) { return tf.vx, tf.vy }
  258. func (tf Transform) String() string { return fmt.Sprintf("%s()", tf.trans.name) }
  259. // Name is the name of the Transformer.
  260. func (tf Transform) Name() string { return tf.trans.name }
  261. // Func is the function pointer to the transformer function.
  262. func (tf Transform) Func() reflect.Value { return tf.trans.fnc }
  263. // Option returns the originally constructed Transformer option.
  264. // The == operator can be used to detect the exact option used.
  265. func (tf Transform) Option() Option { return tf.trans }
  266. // isExported reports whether the identifier is exported.
  267. func isExported(id string) bool {
  268. r, _ := utf8.DecodeRuneInString(id)
  269. return unicode.IsUpper(r)
  270. }