compare.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669
  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 may use that method to determine equality.
  21. // This allows package authors to determine the equality operation
  22. // 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 (see cmpopts.IgnoreUnexported)
  29. // or explicitly 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/function"
  37. "github.com/google/go-cmp/cmp/internal/value"
  38. )
  39. // TODO(≥go1.18): Use any instead of interface{}.
  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 non-zero,
  47. // then Equal panics because it is ambiguous which option to use.
  48. // If S contains a single Transformer, then use that to transform
  49. // the current 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,
  60. // and 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 = anyType
  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. if !s.dynChecker.Next() {
  296. return f.Call([]reflect.Value{v})[0]
  297. }
  298. // Run the function twice and ensure that we get the same results back.
  299. // We run in goroutines so that the race detector (if enabled) can detect
  300. // unsafe mutations to the input.
  301. c := make(chan reflect.Value)
  302. go detectRaces(c, f, v)
  303. got := <-c
  304. want := f.Call([]reflect.Value{v})[0]
  305. if step.vx, step.vy = got, want; !s.statelessCompare(step).Equal() {
  306. // To avoid false-positives with non-reflexive equality operations,
  307. // we sanity check whether a value is equal to itself.
  308. if step.vx, step.vy = want, want; !s.statelessCompare(step).Equal() {
  309. return want
  310. }
  311. panic(fmt.Sprintf("non-deterministic function detected: %s", function.NameOf(f)))
  312. }
  313. return want
  314. }
  315. func (s *state) callTTBFunc(f, x, y reflect.Value) bool {
  316. if !s.dynChecker.Next() {
  317. return f.Call([]reflect.Value{x, y})[0].Bool()
  318. }
  319. // Swapping the input arguments is sufficient to check that
  320. // f is symmetric and deterministic.
  321. // We run in goroutines so that the race detector (if enabled) can detect
  322. // unsafe mutations to the input.
  323. c := make(chan reflect.Value)
  324. go detectRaces(c, f, y, x)
  325. got := <-c
  326. want := f.Call([]reflect.Value{x, y})[0].Bool()
  327. if !got.IsValid() || got.Bool() != want {
  328. panic(fmt.Sprintf("non-deterministic or non-symmetric function detected: %s", function.NameOf(f)))
  329. }
  330. return want
  331. }
  332. func detectRaces(c chan<- reflect.Value, f reflect.Value, vs ...reflect.Value) {
  333. var ret reflect.Value
  334. defer func() {
  335. recover() // Ignore panics, let the other call to f panic instead
  336. c <- ret
  337. }()
  338. ret = f.Call(vs)[0]
  339. }
  340. func (s *state) compareStruct(t reflect.Type, vx, vy reflect.Value) {
  341. var addr bool
  342. var vax, vay reflect.Value // Addressable versions of vx and vy
  343. var mayForce, mayForceInit bool
  344. step := StructField{&structField{}}
  345. for i := 0; i < t.NumField(); i++ {
  346. step.typ = t.Field(i).Type
  347. step.vx = vx.Field(i)
  348. step.vy = vy.Field(i)
  349. step.name = t.Field(i).Name
  350. step.idx = i
  351. step.unexported = !isExported(step.name)
  352. if step.unexported {
  353. if step.name == "_" {
  354. continue
  355. }
  356. // Defer checking of unexported fields until later to give an
  357. // Ignore a chance to ignore the field.
  358. if !vax.IsValid() || !vay.IsValid() {
  359. // For retrieveUnexportedField to work, the parent struct must
  360. // be addressable. Create a new copy of the values if
  361. // necessary to make them addressable.
  362. addr = vx.CanAddr() || vy.CanAddr()
  363. vax = makeAddressable(vx)
  364. vay = makeAddressable(vy)
  365. }
  366. if !mayForceInit {
  367. for _, xf := range s.exporters {
  368. mayForce = mayForce || xf(t)
  369. }
  370. mayForceInit = true
  371. }
  372. step.mayForce = mayForce
  373. step.paddr = addr
  374. step.pvx = vax
  375. step.pvy = vay
  376. step.field = t.Field(i)
  377. }
  378. s.compareAny(step)
  379. }
  380. }
  381. func (s *state) compareSlice(t reflect.Type, vx, vy reflect.Value) {
  382. isSlice := t.Kind() == reflect.Slice
  383. if isSlice && (vx.IsNil() || vy.IsNil()) {
  384. s.report(vx.IsNil() && vy.IsNil(), 0)
  385. return
  386. }
  387. // NOTE: It is incorrect to call curPtrs.Push on the slice header pointer
  388. // since slices represents a list of pointers, rather than a single pointer.
  389. // The pointer checking logic must be handled on a per-element basis
  390. // in compareAny.
  391. //
  392. // A slice header (see reflect.SliceHeader) in Go is a tuple of a starting
  393. // pointer P, a length N, and a capacity C. Supposing each slice element has
  394. // a memory size of M, then the slice is equivalent to the list of pointers:
  395. // [P+i*M for i in range(N)]
  396. //
  397. // For example, v[:0] and v[:1] are slices with the same starting pointer,
  398. // but they are clearly different values. Using the slice pointer alone
  399. // violates the assumption that equal pointers implies equal values.
  400. step := SliceIndex{&sliceIndex{pathStep: pathStep{typ: t.Elem()}, isSlice: isSlice}}
  401. withIndexes := func(ix, iy int) SliceIndex {
  402. if ix >= 0 {
  403. step.vx, step.xkey = vx.Index(ix), ix
  404. } else {
  405. step.vx, step.xkey = reflect.Value{}, -1
  406. }
  407. if iy >= 0 {
  408. step.vy, step.ykey = vy.Index(iy), iy
  409. } else {
  410. step.vy, step.ykey = reflect.Value{}, -1
  411. }
  412. return step
  413. }
  414. // Ignore options are able to ignore missing elements in a slice.
  415. // However, detecting these reliably requires an optimal differencing
  416. // algorithm, for which diff.Difference is not.
  417. //
  418. // Instead, we first iterate through both slices to detect which elements
  419. // would be ignored if standing alone. The index of non-discarded elements
  420. // are stored in a separate slice, which diffing is then performed on.
  421. var indexesX, indexesY []int
  422. var ignoredX, ignoredY []bool
  423. for ix := 0; ix < vx.Len(); ix++ {
  424. ignored := s.statelessCompare(withIndexes(ix, -1)).NumDiff == 0
  425. if !ignored {
  426. indexesX = append(indexesX, ix)
  427. }
  428. ignoredX = append(ignoredX, ignored)
  429. }
  430. for iy := 0; iy < vy.Len(); iy++ {
  431. ignored := s.statelessCompare(withIndexes(-1, iy)).NumDiff == 0
  432. if !ignored {
  433. indexesY = append(indexesY, iy)
  434. }
  435. ignoredY = append(ignoredY, ignored)
  436. }
  437. // Compute an edit-script for slices vx and vy (excluding ignored elements).
  438. edits := diff.Difference(len(indexesX), len(indexesY), func(ix, iy int) diff.Result {
  439. return s.statelessCompare(withIndexes(indexesX[ix], indexesY[iy]))
  440. })
  441. // Replay the ignore-scripts and the edit-script.
  442. var ix, iy int
  443. for ix < vx.Len() || iy < vy.Len() {
  444. var e diff.EditType
  445. switch {
  446. case ix < len(ignoredX) && ignoredX[ix]:
  447. e = diff.UniqueX
  448. case iy < len(ignoredY) && ignoredY[iy]:
  449. e = diff.UniqueY
  450. default:
  451. e, edits = edits[0], edits[1:]
  452. }
  453. switch e {
  454. case diff.UniqueX:
  455. s.compareAny(withIndexes(ix, -1))
  456. ix++
  457. case diff.UniqueY:
  458. s.compareAny(withIndexes(-1, iy))
  459. iy++
  460. default:
  461. s.compareAny(withIndexes(ix, iy))
  462. ix++
  463. iy++
  464. }
  465. }
  466. }
  467. func (s *state) compareMap(t reflect.Type, vx, vy reflect.Value) {
  468. if vx.IsNil() || vy.IsNil() {
  469. s.report(vx.IsNil() && vy.IsNil(), 0)
  470. return
  471. }
  472. // Cycle-detection for maps.
  473. if eq, visited := s.curPtrs.Push(vx, vy); visited {
  474. s.report(eq, reportByCycle)
  475. return
  476. }
  477. defer s.curPtrs.Pop(vx, vy)
  478. // We combine and sort the two map keys so that we can perform the
  479. // comparisons in a deterministic order.
  480. step := MapIndex{&mapIndex{pathStep: pathStep{typ: t.Elem()}}}
  481. for _, k := range value.SortKeys(append(vx.MapKeys(), vy.MapKeys()...)) {
  482. step.vx = vx.MapIndex(k)
  483. step.vy = vy.MapIndex(k)
  484. step.key = k
  485. if !step.vx.IsValid() && !step.vy.IsValid() {
  486. // It is possible for both vx and vy to be invalid if the
  487. // key contained a NaN value in it.
  488. //
  489. // Even with the ability to retrieve NaN keys in Go 1.12,
  490. // there still isn't a sensible way to compare the values since
  491. // a NaN key may map to multiple unordered values.
  492. // The most reasonable way to compare NaNs would be to compare the
  493. // set of values. However, this is impossible to do efficiently
  494. // since set equality is provably an O(n^2) operation given only
  495. // an Equal function. If we had a Less function or Hash function,
  496. // this could be done in O(n*log(n)) or O(n), respectively.
  497. //
  498. // Rather than adding complex logic to deal with NaNs, make it
  499. // the user's responsibility to compare such obscure maps.
  500. const help = "consider providing a Comparer to compare the map"
  501. panic(fmt.Sprintf("%#v has map key with NaNs\n%s", s.curPath, help))
  502. }
  503. s.compareAny(step)
  504. }
  505. }
  506. func (s *state) comparePtr(t reflect.Type, vx, vy reflect.Value) {
  507. if vx.IsNil() || vy.IsNil() {
  508. s.report(vx.IsNil() && vy.IsNil(), 0)
  509. return
  510. }
  511. // Cycle-detection for pointers.
  512. if eq, visited := s.curPtrs.Push(vx, vy); visited {
  513. s.report(eq, reportByCycle)
  514. return
  515. }
  516. defer s.curPtrs.Pop(vx, vy)
  517. vx, vy = vx.Elem(), vy.Elem()
  518. s.compareAny(Indirect{&indirect{pathStep{t.Elem(), vx, vy}}})
  519. }
  520. func (s *state) compareInterface(t reflect.Type, vx, vy reflect.Value) {
  521. if vx.IsNil() || vy.IsNil() {
  522. s.report(vx.IsNil() && vy.IsNil(), 0)
  523. return
  524. }
  525. vx, vy = vx.Elem(), vy.Elem()
  526. if vx.Type() != vy.Type() {
  527. s.report(false, 0)
  528. return
  529. }
  530. s.compareAny(TypeAssertion{&typeAssertion{pathStep{vx.Type(), vx, vy}}})
  531. }
  532. func (s *state) report(eq bool, rf resultFlags) {
  533. if rf&reportByIgnore == 0 {
  534. if eq {
  535. s.result.NumSame++
  536. rf |= reportEqual
  537. } else {
  538. s.result.NumDiff++
  539. rf |= reportUnequal
  540. }
  541. }
  542. for _, r := range s.reporters {
  543. r.Report(Result{flags: rf})
  544. }
  545. }
  546. // recChecker tracks the state needed to periodically perform checks that
  547. // user provided transformers are not stuck in an infinitely recursive cycle.
  548. type recChecker struct{ next int }
  549. // Check scans the Path for any recursive transformers and panics when any
  550. // recursive transformers are detected. Note that the presence of a
  551. // recursive Transformer does not necessarily imply an infinite cycle.
  552. // As such, this check only activates after some minimal number of path steps.
  553. func (rc *recChecker) Check(p Path) {
  554. const minLen = 1 << 16
  555. if rc.next == 0 {
  556. rc.next = minLen
  557. }
  558. if len(p) < rc.next {
  559. return
  560. }
  561. rc.next <<= 1
  562. // Check whether the same transformer has appeared at least twice.
  563. var ss []string
  564. m := map[Option]int{}
  565. for _, ps := range p {
  566. if t, ok := ps.(Transform); ok {
  567. t := t.Option()
  568. if m[t] == 1 { // Transformer was used exactly once before
  569. tf := t.(*transformer).fnc.Type()
  570. ss = append(ss, fmt.Sprintf("%v: %v => %v", t, tf.In(0), tf.Out(0)))
  571. }
  572. m[t]++
  573. }
  574. }
  575. if len(ss) > 0 {
  576. const warning = "recursive set of Transformers detected"
  577. const help = "consider using cmpopts.AcyclicTransformer"
  578. set := strings.Join(ss, "\n\t")
  579. panic(fmt.Sprintf("%s:\n\t%s\n%s", warning, set, help))
  580. }
  581. }
  582. // dynChecker tracks the state needed to periodically perform checks that
  583. // user provided functions are symmetric and deterministic.
  584. // The zero value is safe for immediate use.
  585. type dynChecker struct{ curr, next int }
  586. // Next increments the state and reports whether a check should be performed.
  587. //
  588. // Checks occur every Nth function call, where N is a triangular number:
  589. //
  590. // 0 1 3 6 10 15 21 28 36 45 55 66 78 91 105 120 136 153 171 190 ...
  591. //
  592. // See https://en.wikipedia.org/wiki/Triangular_number
  593. //
  594. // This sequence ensures that the cost of checks drops significantly as
  595. // the number of functions calls grows larger.
  596. func (dc *dynChecker) Next() bool {
  597. ok := dc.curr == dc.next
  598. if ok {
  599. dc.curr = 0
  600. dc.next++
  601. }
  602. dc.curr++
  603. return ok
  604. }
  605. // makeAddressable returns a value that is always addressable.
  606. // It returns the input verbatim if it is already addressable,
  607. // otherwise it creates a new value and returns an addressable copy.
  608. func makeAddressable(v reflect.Value) reflect.Value {
  609. if v.CanAddr() {
  610. return v
  611. }
  612. vc := reflect.New(v.Type()).Elem()
  613. vc.Set(v)
  614. return vc
  615. }