compare.go 22 KB

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