compare.go 22 KB

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