compare.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682
  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 determines equality of values.
  5. //
  6. // This package is intended to be a more powerful and safer alternative to
  7. // reflect.DeepEqual for comparing whether two values are semantically equal.
  8. // It is intended to only be used in tests, as performance is not a goal and
  9. // it may panic if it cannot compare the values. Its propensity towards
  10. // panicking means that its unsuitable for production environments where a
  11. // spurious panic may be fatal.
  12. //
  13. // The primary features of cmp are:
  14. //
  15. // • When the default behavior of equality does not suit the needs of the test,
  16. // custom equality functions can override the equality operation.
  17. // For example, an equality function may report floats as equal so long as they
  18. // are within some tolerance of each other.
  19. //
  20. // • Types that have an Equal method may use that method to determine equality.
  21. // This allows package authors to determine the equality operation for the types
  22. // that they define.
  23. //
  24. // • If no custom equality functions are used and no Equal method is defined,
  25. // equality is determined by recursively comparing the primitive kinds on both
  26. // values, much like reflect.DeepEqual. Unlike reflect.DeepEqual, unexported
  27. // fields are not compared by default; they result in panics unless suppressed
  28. // by using an Ignore option (see cmpopts.IgnoreUnexported) or explicitly
  29. // compared using the Exporter option.
  30. package cmp
  31. import (
  32. "fmt"
  33. "reflect"
  34. "strings"
  35. "github.com/google/go-cmp/cmp/internal/diff"
  36. "github.com/google/go-cmp/cmp/internal/flags"
  37. "github.com/google/go-cmp/cmp/internal/function"
  38. "github.com/google/go-cmp/cmp/internal/value"
  39. )
  40. // Equal reports whether x and y are equal by recursively applying the
  41. // following rules in the given order to x and y and all of their sub-values:
  42. //
  43. // • Let S be the set of all Ignore, Transformer, and Comparer options that
  44. // remain after applying all path filters, value filters, and type filters.
  45. // If at least one Ignore exists in S, then the comparison is ignored.
  46. // If the number of Transformer and Comparer options in S is greater than one,
  47. // then Equal panics because it is ambiguous which option to use.
  48. // If S contains a single Transformer, then use that to transform the current
  49. // values and recursively call Equal on the output values.
  50. // If S contains a single Comparer, then use that to compare the current values.
  51. // Otherwise, evaluation proceeds to the next rule.
  52. //
  53. // • If the values have an Equal method of the form "(T) Equal(T) bool" or
  54. // "(T) Equal(I) bool" where T is assignable to I, then use the result of
  55. // x.Equal(y) even if x or y is nil. Otherwise, no such method exists and
  56. // evaluation proceeds to the next rule.
  57. //
  58. // • Lastly, try to compare x and y based on their basic kinds.
  59. // Simple kinds like booleans, integers, floats, complex numbers, strings, and
  60. // channels are compared using the equivalent of the == operator in Go.
  61. // Functions are only equal if they are both nil, otherwise they are unequal.
  62. //
  63. // Structs are equal if recursively calling Equal on all fields report equal.
  64. // If a struct contains unexported fields, Equal panics unless an Ignore option
  65. // (e.g., cmpopts.IgnoreUnexported) ignores that field or the Exporter option
  66. // explicitly permits comparing the unexported field.
  67. //
  68. // Slices are equal if they are both nil or both non-nil, where recursively
  69. // calling Equal on all non-ignored slice or array elements report equal.
  70. // Empty non-nil slices and nil slices are not equal; to equate empty slices,
  71. // consider using cmpopts.EquateEmpty.
  72. //
  73. // Maps are equal if they are both nil or both non-nil, where recursively
  74. // calling Equal on all non-ignored map entries report equal.
  75. // Map keys are equal according to the == operator.
  76. // To use custom comparisons for map keys, consider using cmpopts.SortMaps.
  77. // Empty non-nil maps and nil maps are not equal; to equate empty maps,
  78. // consider using cmpopts.EquateEmpty.
  79. //
  80. // Pointers and interfaces are equal if they are both nil or both non-nil,
  81. // where they have the same underlying concrete type and recursively
  82. // calling Equal on the underlying values reports equal.
  83. //
  84. // Before recursing into a pointer, slice element, or map, the current path
  85. // is checked to detect whether the address has already been visited.
  86. // If there is a cycle, then the pointed at values are considered equal
  87. // only if both addresses were previously visited in the same path step.
  88. func Equal(x, y interface{}, opts ...Option) bool {
  89. s := newState(opts)
  90. s.compareAny(rootStep(x, y))
  91. return s.result.Equal()
  92. }
  93. // Diff returns a human-readable report of the differences between two values:
  94. // y - x. It returns an empty string if and only if Equal returns true for the
  95. // same input values and options.
  96. //
  97. // The output is displayed as a literal in pseudo-Go syntax.
  98. // At the start of each line, a "-" prefix indicates an element removed from x,
  99. // a "+" prefix to indicates an element added from y, and the lack of a prefix
  100. // indicates an element common to both x and y. If possible, the output
  101. // uses fmt.Stringer.String or error.Error methods to produce more humanly
  102. // readable outputs. In such cases, the string is prefixed with either an
  103. // 's' or 'e' character, respectively, to indicate that the method was called.
  104. //
  105. // Do not depend on this output being stable. If you need the ability to
  106. // programmatically interpret the difference, consider using a custom Reporter.
  107. func Diff(x, y interface{}, opts ...Option) string {
  108. s := newState(opts)
  109. // Optimization: If there are no other reporters, we can optimize for the
  110. // common case where the result is equal (and thus no reported difference).
  111. // This avoids the expensive construction of a difference tree.
  112. if len(s.reporters) == 0 {
  113. s.compareAny(rootStep(x, y))
  114. if s.result.Equal() {
  115. return ""
  116. }
  117. s.result = diff.Result{} // Reset results
  118. }
  119. r := new(defaultReporter)
  120. s.reporters = append(s.reporters, reporter{r})
  121. s.compareAny(rootStep(x, y))
  122. d := r.String()
  123. if (d == "") != s.result.Equal() {
  124. panic("inconsistent difference and equality results")
  125. }
  126. return d
  127. }
  128. // rootStep constructs the first path step. If x and y have differing types,
  129. // then they are stored within an empty interface type.
  130. func rootStep(x, y interface{}) PathStep {
  131. vx := reflect.ValueOf(x)
  132. vy := reflect.ValueOf(y)
  133. // If the inputs are different types, auto-wrap them in an empty interface
  134. // so that they have the same parent type.
  135. var t reflect.Type
  136. if !vx.IsValid() || !vy.IsValid() || vx.Type() != vy.Type() {
  137. t = reflect.TypeOf((*interface{})(nil)).Elem()
  138. if vx.IsValid() {
  139. vvx := reflect.New(t).Elem()
  140. vvx.Set(vx)
  141. vx = vvx
  142. }
  143. if vy.IsValid() {
  144. vvy := reflect.New(t).Elem()
  145. vvy.Set(vy)
  146. vy = vvy
  147. }
  148. } else {
  149. t = vx.Type()
  150. }
  151. return &pathStep{t, vx, vy}
  152. }
  153. type state struct {
  154. // These fields represent the "comparison state".
  155. // Calling statelessCompare must not result in observable changes to these.
  156. result diff.Result // The current result of comparison
  157. curPath Path // The current path in the value tree
  158. curPtrs pointerPath // The current set of visited pointers
  159. reporters []reporter // Optional reporters
  160. // recChecker checks for infinite cycles applying the same set of
  161. // transformers upon the output of itself.
  162. recChecker recChecker
  163. // dynChecker triggers pseudo-random checks for option correctness.
  164. // It is safe for statelessCompare to mutate this value.
  165. dynChecker dynChecker
  166. // These fields, once set by processOption, will not change.
  167. exporters []exporter // List of exporters for structs with unexported fields
  168. opts Options // List of all fundamental and filter options
  169. }
  170. func newState(opts []Option) *state {
  171. // Always ensure a validator option exists to validate the inputs.
  172. s := &state{opts: Options{validator{}}}
  173. s.curPtrs.Init()
  174. s.processOption(Options(opts))
  175. return s
  176. }
  177. func (s *state) processOption(opt Option) {
  178. switch opt := opt.(type) {
  179. case nil:
  180. case Options:
  181. for _, o := range opt {
  182. s.processOption(o)
  183. }
  184. case coreOption:
  185. type filtered interface {
  186. isFiltered() bool
  187. }
  188. if fopt, ok := opt.(filtered); ok && !fopt.isFiltered() {
  189. panic(fmt.Sprintf("cannot use an unfiltered option: %v", opt))
  190. }
  191. s.opts = append(s.opts, opt)
  192. case exporter:
  193. s.exporters = append(s.exporters, opt)
  194. case reporter:
  195. s.reporters = append(s.reporters, opt)
  196. default:
  197. panic(fmt.Sprintf("unknown option %T", opt))
  198. }
  199. }
  200. // statelessCompare compares two values and returns the result.
  201. // This function is stateless in that it does not alter the current result,
  202. // or output to any registered reporters.
  203. func (s *state) statelessCompare(step PathStep) diff.Result {
  204. // We do not save and restore curPath and curPtrs because all of the
  205. // compareX methods should properly push and pop from them.
  206. // It is an implementation bug if the contents of the paths differ from
  207. // when calling this function to when returning from it.
  208. oldResult, oldReporters := s.result, s.reporters
  209. s.result = diff.Result{} // Reset result
  210. s.reporters = nil // Remove reporters to avoid spurious printouts
  211. s.compareAny(step)
  212. res := s.result
  213. s.result, s.reporters = oldResult, oldReporters
  214. return res
  215. }
  216. func (s *state) compareAny(step PathStep) {
  217. // Update the path stack.
  218. s.curPath.push(step)
  219. defer s.curPath.pop()
  220. for _, r := range s.reporters {
  221. r.PushStep(step)
  222. defer r.PopStep()
  223. }
  224. s.recChecker.Check(s.curPath)
  225. // Cycle-detection for slice elements (see NOTE in compareSlice).
  226. t := step.Type()
  227. vx, vy := step.Values()
  228. if si, ok := step.(SliceIndex); ok && si.isSlice && vx.IsValid() && vy.IsValid() {
  229. px, py := vx.Addr(), vy.Addr()
  230. if eq, visited := s.curPtrs.Push(px, py); visited {
  231. s.report(eq, reportByCycle)
  232. return
  233. }
  234. defer s.curPtrs.Pop(px, py)
  235. }
  236. // Rule 1: Check whether an option applies on this node in the value tree.
  237. if s.tryOptions(t, vx, vy) {
  238. return
  239. }
  240. // Rule 2: Check whether the type has a valid Equal method.
  241. if s.tryMethod(t, vx, vy) {
  242. return
  243. }
  244. // Rule 3: Compare based on the underlying kind.
  245. switch t.Kind() {
  246. case reflect.Bool:
  247. s.report(vx.Bool() == vy.Bool(), 0)
  248. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  249. s.report(vx.Int() == vy.Int(), 0)
  250. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
  251. s.report(vx.Uint() == vy.Uint(), 0)
  252. case reflect.Float32, reflect.Float64:
  253. s.report(vx.Float() == vy.Float(), 0)
  254. case reflect.Complex64, reflect.Complex128:
  255. s.report(vx.Complex() == vy.Complex(), 0)
  256. case reflect.String:
  257. s.report(vx.String() == vy.String(), 0)
  258. case reflect.Chan, reflect.UnsafePointer:
  259. s.report(vx.Pointer() == vy.Pointer(), 0)
  260. case reflect.Func:
  261. s.report(vx.IsNil() && vy.IsNil(), 0)
  262. case reflect.Struct:
  263. s.compareStruct(t, vx, vy)
  264. case reflect.Slice, reflect.Array:
  265. s.compareSlice(t, vx, vy)
  266. case reflect.Map:
  267. s.compareMap(t, vx, vy)
  268. case reflect.Ptr:
  269. s.comparePtr(t, vx, vy)
  270. case reflect.Interface:
  271. s.compareInterface(t, vx, vy)
  272. default:
  273. panic(fmt.Sprintf("%v kind not handled", t.Kind()))
  274. }
  275. }
  276. func (s *state) tryOptions(t reflect.Type, vx, vy reflect.Value) bool {
  277. // Evaluate all filters and apply the remaining options.
  278. if opt := s.opts.filter(s, t, vx, vy); opt != nil {
  279. opt.apply(s, vx, vy)
  280. return true
  281. }
  282. return false
  283. }
  284. func (s *state) tryMethod(t reflect.Type, vx, vy reflect.Value) bool {
  285. // Check if this type even has an Equal method.
  286. m, ok := t.MethodByName("Equal")
  287. if !ok || !function.IsType(m.Type, function.EqualAssignable) {
  288. return false
  289. }
  290. eq := s.callTTBFunc(m.Func, vx, vy)
  291. s.report(eq, reportByMethod)
  292. return true
  293. }
  294. func (s *state) callTRFunc(f, v reflect.Value, step Transform) reflect.Value {
  295. v = sanitizeValue(v, f.Type().In(0))
  296. if !s.dynChecker.Next() {
  297. return f.Call([]reflect.Value{v})[0]
  298. }
  299. // Run the function twice and ensure that we get the same results back.
  300. // We run in goroutines so that the race detector (if enabled) can detect
  301. // unsafe mutations to the input.
  302. c := make(chan reflect.Value)
  303. go detectRaces(c, f, v)
  304. got := <-c
  305. want := f.Call([]reflect.Value{v})[0]
  306. if step.vx, step.vy = got, want; !s.statelessCompare(step).Equal() {
  307. // To avoid false-positives with non-reflexive equality operations,
  308. // we sanity check whether a value is equal to itself.
  309. if step.vx, step.vy = want, want; !s.statelessCompare(step).Equal() {
  310. return want
  311. }
  312. panic(fmt.Sprintf("non-deterministic function detected: %s", function.NameOf(f)))
  313. }
  314. return want
  315. }
  316. func (s *state) callTTBFunc(f, x, y reflect.Value) bool {
  317. x = sanitizeValue(x, f.Type().In(0))
  318. y = sanitizeValue(y, f.Type().In(1))
  319. if !s.dynChecker.Next() {
  320. return f.Call([]reflect.Value{x, y})[0].Bool()
  321. }
  322. // Swapping the input arguments is sufficient to check that
  323. // f is symmetric and deterministic.
  324. // We run in goroutines so that the race detector (if enabled) can detect
  325. // unsafe mutations to the input.
  326. c := make(chan reflect.Value)
  327. go detectRaces(c, f, y, x)
  328. got := <-c
  329. want := f.Call([]reflect.Value{x, y})[0].Bool()
  330. if !got.IsValid() || got.Bool() != want {
  331. panic(fmt.Sprintf("non-deterministic or non-symmetric function detected: %s", function.NameOf(f)))
  332. }
  333. return want
  334. }
  335. func detectRaces(c chan<- reflect.Value, f reflect.Value, vs ...reflect.Value) {
  336. var ret reflect.Value
  337. defer func() {
  338. recover() // Ignore panics, let the other call to f panic instead
  339. c <- ret
  340. }()
  341. ret = f.Call(vs)[0]
  342. }
  343. // sanitizeValue converts nil interfaces of type T to those of type R,
  344. // assuming that T is assignable to R.
  345. // Otherwise, it returns the input value as is.
  346. func sanitizeValue(v reflect.Value, t reflect.Type) reflect.Value {
  347. // TODO(≥go1.10): Workaround for reflect bug (https://golang.org/issue/22143).
  348. if !flags.AtLeastGo110 {
  349. if v.Kind() == reflect.Interface && v.IsNil() && v.Type() != t {
  350. return reflect.New(t).Elem()
  351. }
  352. }
  353. return v
  354. }
  355. func (s *state) compareStruct(t reflect.Type, vx, vy reflect.Value) {
  356. var addr bool
  357. var vax, vay reflect.Value // Addressable versions of vx and vy
  358. var mayForce, mayForceInit bool
  359. step := StructField{&structField{}}
  360. for i := 0; i < t.NumField(); i++ {
  361. step.typ = t.Field(i).Type
  362. step.vx = vx.Field(i)
  363. step.vy = vy.Field(i)
  364. step.name = t.Field(i).Name
  365. step.idx = i
  366. step.unexported = !isExported(step.name)
  367. if step.unexported {
  368. if step.name == "_" {
  369. continue
  370. }
  371. // Defer checking of unexported fields until later to give an
  372. // Ignore a chance to ignore the field.
  373. if !vax.IsValid() || !vay.IsValid() {
  374. // For retrieveUnexportedField to work, the parent struct must
  375. // be addressable. Create a new copy of the values if
  376. // necessary to make them addressable.
  377. addr = vx.CanAddr() || vy.CanAddr()
  378. vax = makeAddressable(vx)
  379. vay = makeAddressable(vy)
  380. }
  381. if !mayForceInit {
  382. for _, xf := range s.exporters {
  383. mayForce = mayForce || xf(t)
  384. }
  385. mayForceInit = true
  386. }
  387. step.mayForce = mayForce
  388. step.paddr = addr
  389. step.pvx = vax
  390. step.pvy = vay
  391. step.field = t.Field(i)
  392. }
  393. s.compareAny(step)
  394. }
  395. }
  396. func (s *state) compareSlice(t reflect.Type, vx, vy reflect.Value) {
  397. isSlice := t.Kind() == reflect.Slice
  398. if isSlice && (vx.IsNil() || vy.IsNil()) {
  399. s.report(vx.IsNil() && vy.IsNil(), 0)
  400. return
  401. }
  402. // NOTE: It is incorrect to call curPtrs.Push on the slice header pointer
  403. // since slices represents a list of pointers, rather than a single pointer.
  404. // The pointer checking logic must be handled on a per-element basis
  405. // in compareAny.
  406. //
  407. // A slice header (see reflect.SliceHeader) in Go is a tuple of a starting
  408. // pointer P, a length N, and a capacity C. Supposing each slice element has
  409. // a memory size of M, then the slice is equivalent to the list of pointers:
  410. // [P+i*M for i in range(N)]
  411. //
  412. // For example, v[:0] and v[:1] are slices with the same starting pointer,
  413. // but they are clearly different values. Using the slice pointer alone
  414. // violates the assumption that equal pointers implies equal values.
  415. step := SliceIndex{&sliceIndex{pathStep: pathStep{typ: t.Elem()}, isSlice: isSlice}}
  416. withIndexes := func(ix, iy int) SliceIndex {
  417. if ix >= 0 {
  418. step.vx, step.xkey = vx.Index(ix), ix
  419. } else {
  420. step.vx, step.xkey = reflect.Value{}, -1
  421. }
  422. if iy >= 0 {
  423. step.vy, step.ykey = vy.Index(iy), iy
  424. } else {
  425. step.vy, step.ykey = reflect.Value{}, -1
  426. }
  427. return step
  428. }
  429. // Ignore options are able to ignore missing elements in a slice.
  430. // However, detecting these reliably requires an optimal differencing
  431. // algorithm, for which diff.Difference is not.
  432. //
  433. // Instead, we first iterate through both slices to detect which elements
  434. // would be ignored if standing alone. The index of non-discarded elements
  435. // are stored in a separate slice, which diffing is then performed on.
  436. var indexesX, indexesY []int
  437. var ignoredX, ignoredY []bool
  438. for ix := 0; ix < vx.Len(); ix++ {
  439. ignored := s.statelessCompare(withIndexes(ix, -1)).NumDiff == 0
  440. if !ignored {
  441. indexesX = append(indexesX, ix)
  442. }
  443. ignoredX = append(ignoredX, ignored)
  444. }
  445. for iy := 0; iy < vy.Len(); iy++ {
  446. ignored := s.statelessCompare(withIndexes(-1, iy)).NumDiff == 0
  447. if !ignored {
  448. indexesY = append(indexesY, iy)
  449. }
  450. ignoredY = append(ignoredY, ignored)
  451. }
  452. // Compute an edit-script for slices vx and vy (excluding ignored elements).
  453. edits := diff.Difference(len(indexesX), len(indexesY), func(ix, iy int) diff.Result {
  454. return s.statelessCompare(withIndexes(indexesX[ix], indexesY[iy]))
  455. })
  456. // Replay the ignore-scripts and the edit-script.
  457. var ix, iy int
  458. for ix < vx.Len() || iy < vy.Len() {
  459. var e diff.EditType
  460. switch {
  461. case ix < len(ignoredX) && ignoredX[ix]:
  462. e = diff.UniqueX
  463. case iy < len(ignoredY) && ignoredY[iy]:
  464. e = diff.UniqueY
  465. default:
  466. e, edits = edits[0], edits[1:]
  467. }
  468. switch e {
  469. case diff.UniqueX:
  470. s.compareAny(withIndexes(ix, -1))
  471. ix++
  472. case diff.UniqueY:
  473. s.compareAny(withIndexes(-1, iy))
  474. iy++
  475. default:
  476. s.compareAny(withIndexes(ix, iy))
  477. ix++
  478. iy++
  479. }
  480. }
  481. }
  482. func (s *state) compareMap(t reflect.Type, vx, vy reflect.Value) {
  483. if vx.IsNil() || vy.IsNil() {
  484. s.report(vx.IsNil() && vy.IsNil(), 0)
  485. return
  486. }
  487. // Cycle-detection for maps.
  488. if eq, visited := s.curPtrs.Push(vx, vy); visited {
  489. s.report(eq, reportByCycle)
  490. return
  491. }
  492. defer s.curPtrs.Pop(vx, vy)
  493. // We combine and sort the two map keys so that we can perform the
  494. // comparisons in a deterministic order.
  495. step := MapIndex{&mapIndex{pathStep: pathStep{typ: t.Elem()}}}
  496. for _, k := range value.SortKeys(append(vx.MapKeys(), vy.MapKeys()...)) {
  497. step.vx = vx.MapIndex(k)
  498. step.vy = vy.MapIndex(k)
  499. step.key = k
  500. if !step.vx.IsValid() && !step.vy.IsValid() {
  501. // It is possible for both vx and vy to be invalid if the
  502. // key contained a NaN value in it.
  503. //
  504. // Even with the ability to retrieve NaN keys in Go 1.12,
  505. // there still isn't a sensible way to compare the values since
  506. // a NaN key may map to multiple unordered values.
  507. // The most reasonable way to compare NaNs would be to compare the
  508. // set of values. However, this is impossible to do efficiently
  509. // since set equality is provably an O(n^2) operation given only
  510. // an Equal function. If we had a Less function or Hash function,
  511. // this could be done in O(n*log(n)) or O(n), respectively.
  512. //
  513. // Rather than adding complex logic to deal with NaNs, make it
  514. // the user's responsibility to compare such obscure maps.
  515. const help = "consider providing a Comparer to compare the map"
  516. panic(fmt.Sprintf("%#v has map key with NaNs\n%s", s.curPath, help))
  517. }
  518. s.compareAny(step)
  519. }
  520. }
  521. func (s *state) comparePtr(t reflect.Type, vx, vy reflect.Value) {
  522. if vx.IsNil() || vy.IsNil() {
  523. s.report(vx.IsNil() && vy.IsNil(), 0)
  524. return
  525. }
  526. // Cycle-detection for pointers.
  527. if eq, visited := s.curPtrs.Push(vx, vy); visited {
  528. s.report(eq, reportByCycle)
  529. return
  530. }
  531. defer s.curPtrs.Pop(vx, vy)
  532. vx, vy = vx.Elem(), vy.Elem()
  533. s.compareAny(Indirect{&indirect{pathStep{t.Elem(), vx, vy}}})
  534. }
  535. func (s *state) compareInterface(t reflect.Type, vx, vy reflect.Value) {
  536. if vx.IsNil() || vy.IsNil() {
  537. s.report(vx.IsNil() && vy.IsNil(), 0)
  538. return
  539. }
  540. vx, vy = vx.Elem(), vy.Elem()
  541. if vx.Type() != vy.Type() {
  542. s.report(false, 0)
  543. return
  544. }
  545. s.compareAny(TypeAssertion{&typeAssertion{pathStep{vx.Type(), vx, vy}}})
  546. }
  547. func (s *state) report(eq bool, rf resultFlags) {
  548. if rf&reportByIgnore == 0 {
  549. if eq {
  550. s.result.NumSame++
  551. rf |= reportEqual
  552. } else {
  553. s.result.NumDiff++
  554. rf |= reportUnequal
  555. }
  556. }
  557. for _, r := range s.reporters {
  558. r.Report(Result{flags: rf})
  559. }
  560. }
  561. // recChecker tracks the state needed to periodically perform checks that
  562. // user provided transformers are not stuck in an infinitely recursive cycle.
  563. type recChecker struct{ next int }
  564. // Check scans the Path for any recursive transformers and panics when any
  565. // recursive transformers are detected. Note that the presence of a
  566. // recursive Transformer does not necessarily imply an infinite cycle.
  567. // As such, this check only activates after some minimal number of path steps.
  568. func (rc *recChecker) Check(p Path) {
  569. const minLen = 1 << 16
  570. if rc.next == 0 {
  571. rc.next = minLen
  572. }
  573. if len(p) < rc.next {
  574. return
  575. }
  576. rc.next <<= 1
  577. // Check whether the same transformer has appeared at least twice.
  578. var ss []string
  579. m := map[Option]int{}
  580. for _, ps := range p {
  581. if t, ok := ps.(Transform); ok {
  582. t := t.Option()
  583. if m[t] == 1 { // Transformer was used exactly once before
  584. tf := t.(*transformer).fnc.Type()
  585. ss = append(ss, fmt.Sprintf("%v: %v => %v", t, tf.In(0), tf.Out(0)))
  586. }
  587. m[t]++
  588. }
  589. }
  590. if len(ss) > 0 {
  591. const warning = "recursive set of Transformers detected"
  592. const help = "consider using cmpopts.AcyclicTransformer"
  593. set := strings.Join(ss, "\n\t")
  594. panic(fmt.Sprintf("%s:\n\t%s\n%s", warning, set, help))
  595. }
  596. }
  597. // dynChecker tracks the state needed to periodically perform checks that
  598. // user provided functions are symmetric and deterministic.
  599. // The zero value is safe for immediate use.
  600. type dynChecker struct{ curr, next int }
  601. // Next increments the state and reports whether a check should be performed.
  602. //
  603. // Checks occur every Nth function call, where N is a triangular number:
  604. // 0 1 3 6 10 15 21 28 36 45 55 66 78 91 105 120 136 153 171 190 ...
  605. // See https://en.wikipedia.org/wiki/Triangular_number
  606. //
  607. // This sequence ensures that the cost of checks drops significantly as
  608. // the number of functions calls grows larger.
  609. func (dc *dynChecker) Next() bool {
  610. ok := dc.curr == dc.next
  611. if ok {
  612. dc.curr = 0
  613. dc.next++
  614. }
  615. dc.curr++
  616. return ok
  617. }
  618. // makeAddressable returns a value that is always addressable.
  619. // It returns the input verbatim if it is already addressable,
  620. // otherwise it creates a new value and returns an addressable copy.
  621. func makeAddressable(v reflect.Value) reflect.Value {
  622. if v.CanAddr() {
  623. return v
  624. }
  625. vc := reflect.New(v.Type()).Elem()
  626. vc.Set(v)
  627. return vc
  628. }