blob: c9a63ceda5e6a73e58d7e79f67b7ea8a017f18c8 [file] [log] [blame]
Matteo Scandoloa6a3aee2019-11-26 13:30:14 -07001// 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
5// Package cmp determines equality of values.
6//
7// This package is intended to be a more powerful and safer alternative to
8// reflect.DeepEqual for comparing whether two values are semantically equal.
9//
10// The primary features of cmp are:
11//
12// • When the default behavior of equality does not suit the needs of the test,
13// custom equality functions can override the equality operation.
14// For example, an equality function may report floats as equal so long as they
15// are within some tolerance of each other.
16//
17// • Types that have an Equal method may use that method to determine equality.
18// This allows package authors to determine the equality operation for the types
19// that they define.
20//
21// • If no custom equality functions are used and no Equal method is defined,
22// equality is determined by recursively comparing the primitive kinds on both
23// values, much like reflect.DeepEqual. Unlike reflect.DeepEqual, unexported
24// fields are not compared by default; they result in panics unless suppressed
Pragya Arya324337e2020-02-20 14:35:08 +053025// by using an Ignore option (see cmpopts.IgnoreUnexported) or explicitly
26// compared using the Exporter option.
Matteo Scandoloa6a3aee2019-11-26 13:30:14 -070027package cmp
28
29import (
30 "fmt"
31 "reflect"
Pragya Arya324337e2020-02-20 14:35:08 +053032 "strings"
Matteo Scandoloa6a3aee2019-11-26 13:30:14 -070033
34 "github.com/google/go-cmp/cmp/internal/diff"
Pragya Arya324337e2020-02-20 14:35:08 +053035 "github.com/google/go-cmp/cmp/internal/flags"
Matteo Scandoloa6a3aee2019-11-26 13:30:14 -070036 "github.com/google/go-cmp/cmp/internal/function"
37 "github.com/google/go-cmp/cmp/internal/value"
38)
39
Matteo Scandoloa6a3aee2019-11-26 13:30:14 -070040// 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//
Matteo Scandoloa6a3aee2019-11-26 13:30:14 -070043// • 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
Pragya Arya324337e2020-02-20 14:35:08 +053055// x.Equal(y) even if x or y is nil. Otherwise, no such method exists and
56// evaluation proceeds to the next rule.
Matteo Scandoloa6a3aee2019-11-26 13:30:14 -070057//
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.
Matteo Scandoloa6a3aee2019-11-26 13:30:14 -070062//
Pragya Arya324337e2020-02-20 14:35:08 +053063// 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.
Matteo Scandoloa6a3aee2019-11-26 13:30:14 -070067//
Pragya Arya324337e2020-02-20 14:35:08 +053068// 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.
Matteo Scandoloa6a3aee2019-11-26 13:30:14 -070075// Map keys are equal according to the == operator.
76// To use custom comparisons for map keys, consider using cmpopts.SortMaps.
Pragya Arya324337e2020-02-20 14:35:08 +053077// 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.
Matteo Scandoloa6a3aee2019-11-26 13:30:14 -070088func Equal(x, y interface{}, opts ...Option) bool {
Pragya Arya324337e2020-02-20 14:35:08 +053089 vx := reflect.ValueOf(x)
90 vy := reflect.ValueOf(y)
91
92 // If the inputs are different types, auto-wrap them in an empty interface
93 // so that they have the same parent type.
94 var t reflect.Type
95 if !vx.IsValid() || !vy.IsValid() || vx.Type() != vy.Type() {
96 t = reflect.TypeOf((*interface{})(nil)).Elem()
97 if vx.IsValid() {
98 vvx := reflect.New(t).Elem()
99 vvx.Set(vx)
100 vx = vvx
101 }
102 if vy.IsValid() {
103 vvy := reflect.New(t).Elem()
104 vvy.Set(vy)
105 vy = vvy
106 }
107 } else {
108 t = vx.Type()
109 }
110
Matteo Scandoloa6a3aee2019-11-26 13:30:14 -0700111 s := newState(opts)
Pragya Arya324337e2020-02-20 14:35:08 +0530112 s.compareAny(&pathStep{t, vx, vy})
Matteo Scandoloa6a3aee2019-11-26 13:30:14 -0700113 return s.result.Equal()
114}
115
116// Diff returns a human-readable report of the differences between two values.
117// It returns an empty string if and only if Equal returns true for the same
Pragya Arya324337e2020-02-20 14:35:08 +0530118// input values and options.
Matteo Scandoloa6a3aee2019-11-26 13:30:14 -0700119//
Pragya Arya324337e2020-02-20 14:35:08 +0530120// The output is displayed as a literal in pseudo-Go syntax.
121// At the start of each line, a "-" prefix indicates an element removed from x,
122// a "+" prefix to indicates an element added to y, and the lack of a prefix
123// indicates an element common to both x and y. If possible, the output
124// uses fmt.Stringer.String or error.Error methods to produce more humanly
125// readable outputs. In such cases, the string is prefixed with either an
126// 's' or 'e' character, respectively, to indicate that the method was called.
127//
128// Do not depend on this output being stable. If you need the ability to
129// programmatically interpret the difference, consider using a custom Reporter.
Matteo Scandoloa6a3aee2019-11-26 13:30:14 -0700130func Diff(x, y interface{}, opts ...Option) string {
131 r := new(defaultReporter)
Pragya Arya324337e2020-02-20 14:35:08 +0530132 eq := Equal(x, y, Options(opts), Reporter(r))
Matteo Scandoloa6a3aee2019-11-26 13:30:14 -0700133 d := r.String()
134 if (d == "") != eq {
135 panic("inconsistent difference and equality results")
136 }
137 return d
138}
139
140type state struct {
141 // These fields represent the "comparison state".
142 // Calling statelessCompare must not result in observable changes to these.
Pragya Arya324337e2020-02-20 14:35:08 +0530143 result diff.Result // The current result of comparison
144 curPath Path // The current path in the value tree
145 curPtrs pointerPath // The current set of visited pointers
146 reporters []reporter // Optional reporters
147
148 // recChecker checks for infinite cycles applying the same set of
149 // transformers upon the output of itself.
150 recChecker recChecker
Matteo Scandoloa6a3aee2019-11-26 13:30:14 -0700151
152 // dynChecker triggers pseudo-random checks for option correctness.
153 // It is safe for statelessCompare to mutate this value.
154 dynChecker dynChecker
155
156 // These fields, once set by processOption, will not change.
Pragya Arya324337e2020-02-20 14:35:08 +0530157 exporters []exporter // List of exporters for structs with unexported fields
158 opts Options // List of all fundamental and filter options
Matteo Scandoloa6a3aee2019-11-26 13:30:14 -0700159}
160
161func newState(opts []Option) *state {
Pragya Arya324337e2020-02-20 14:35:08 +0530162 // Always ensure a validator option exists to validate the inputs.
163 s := &state{opts: Options{validator{}}}
164 s.curPtrs.Init()
165 s.processOption(Options(opts))
Matteo Scandoloa6a3aee2019-11-26 13:30:14 -0700166 return s
167}
168
169func (s *state) processOption(opt Option) {
170 switch opt := opt.(type) {
171 case nil:
172 case Options:
173 for _, o := range opt {
174 s.processOption(o)
175 }
176 case coreOption:
177 type filtered interface {
178 isFiltered() bool
179 }
180 if fopt, ok := opt.(filtered); ok && !fopt.isFiltered() {
181 panic(fmt.Sprintf("cannot use an unfiltered option: %v", opt))
182 }
183 s.opts = append(s.opts, opt)
Pragya Arya324337e2020-02-20 14:35:08 +0530184 case exporter:
185 s.exporters = append(s.exporters, opt)
Matteo Scandoloa6a3aee2019-11-26 13:30:14 -0700186 case reporter:
Pragya Arya324337e2020-02-20 14:35:08 +0530187 s.reporters = append(s.reporters, opt)
Matteo Scandoloa6a3aee2019-11-26 13:30:14 -0700188 default:
189 panic(fmt.Sprintf("unknown option %T", opt))
190 }
191}
192
193// statelessCompare compares two values and returns the result.
194// This function is stateless in that it does not alter the current result,
195// or output to any registered reporters.
Pragya Arya324337e2020-02-20 14:35:08 +0530196func (s *state) statelessCompare(step PathStep) diff.Result {
197 // We do not save and restore curPath and curPtrs because all of the
198 // compareX methods should properly push and pop from them.
199 // It is an implementation bug if the contents of the paths differ from
Matteo Scandoloa6a3aee2019-11-26 13:30:14 -0700200 // when calling this function to when returning from it.
201
Pragya Arya324337e2020-02-20 14:35:08 +0530202 oldResult, oldReporters := s.result, s.reporters
Matteo Scandoloa6a3aee2019-11-26 13:30:14 -0700203 s.result = diff.Result{} // Reset result
Pragya Arya324337e2020-02-20 14:35:08 +0530204 s.reporters = nil // Remove reporters to avoid spurious printouts
205 s.compareAny(step)
Matteo Scandoloa6a3aee2019-11-26 13:30:14 -0700206 res := s.result
Pragya Arya324337e2020-02-20 14:35:08 +0530207 s.result, s.reporters = oldResult, oldReporters
Matteo Scandoloa6a3aee2019-11-26 13:30:14 -0700208 return res
209}
210
Pragya Arya324337e2020-02-20 14:35:08 +0530211func (s *state) compareAny(step PathStep) {
212 // Update the path stack.
213 s.curPath.push(step)
214 defer s.curPath.pop()
215 for _, r := range s.reporters {
216 r.PushStep(step)
217 defer r.PopStep()
218 }
219 s.recChecker.Check(s.curPath)
Matteo Scandoloa6a3aee2019-11-26 13:30:14 -0700220
Pragya Arya324337e2020-02-20 14:35:08 +0530221 // Cycle-detection for slice elements (see NOTE in compareSlice).
222 t := step.Type()
223 vx, vy := step.Values()
224 if si, ok := step.(SliceIndex); ok && si.isSlice && vx.IsValid() && vy.IsValid() {
225 px, py := vx.Addr(), vy.Addr()
226 if eq, visited := s.curPtrs.Push(px, py); visited {
227 s.report(eq, reportByCycle)
228 return
229 }
230 defer s.curPtrs.Pop(px, py)
Matteo Scandoloa6a3aee2019-11-26 13:30:14 -0700231 }
Matteo Scandoloa6a3aee2019-11-26 13:30:14 -0700232
233 // Rule 1: Check whether an option applies on this node in the value tree.
Pragya Arya324337e2020-02-20 14:35:08 +0530234 if s.tryOptions(t, vx, vy) {
Matteo Scandoloa6a3aee2019-11-26 13:30:14 -0700235 return
236 }
237
238 // Rule 2: Check whether the type has a valid Equal method.
Pragya Arya324337e2020-02-20 14:35:08 +0530239 if s.tryMethod(t, vx, vy) {
Matteo Scandoloa6a3aee2019-11-26 13:30:14 -0700240 return
241 }
242
Pragya Arya324337e2020-02-20 14:35:08 +0530243 // Rule 3: Compare based on the underlying kind.
Matteo Scandoloa6a3aee2019-11-26 13:30:14 -0700244 switch t.Kind() {
245 case reflect.Bool:
Pragya Arya324337e2020-02-20 14:35:08 +0530246 s.report(vx.Bool() == vy.Bool(), 0)
Matteo Scandoloa6a3aee2019-11-26 13:30:14 -0700247 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
Pragya Arya324337e2020-02-20 14:35:08 +0530248 s.report(vx.Int() == vy.Int(), 0)
Matteo Scandoloa6a3aee2019-11-26 13:30:14 -0700249 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
Pragya Arya324337e2020-02-20 14:35:08 +0530250 s.report(vx.Uint() == vy.Uint(), 0)
Matteo Scandoloa6a3aee2019-11-26 13:30:14 -0700251 case reflect.Float32, reflect.Float64:
Pragya Arya324337e2020-02-20 14:35:08 +0530252 s.report(vx.Float() == vy.Float(), 0)
Matteo Scandoloa6a3aee2019-11-26 13:30:14 -0700253 case reflect.Complex64, reflect.Complex128:
Pragya Arya324337e2020-02-20 14:35:08 +0530254 s.report(vx.Complex() == vy.Complex(), 0)
Matteo Scandoloa6a3aee2019-11-26 13:30:14 -0700255 case reflect.String:
Pragya Arya324337e2020-02-20 14:35:08 +0530256 s.report(vx.String() == vy.String(), 0)
Matteo Scandoloa6a3aee2019-11-26 13:30:14 -0700257 case reflect.Chan, reflect.UnsafePointer:
Pragya Arya324337e2020-02-20 14:35:08 +0530258 s.report(vx.Pointer() == vy.Pointer(), 0)
Matteo Scandoloa6a3aee2019-11-26 13:30:14 -0700259 case reflect.Func:
Pragya Arya324337e2020-02-20 14:35:08 +0530260 s.report(vx.IsNil() && vy.IsNil(), 0)
Matteo Scandoloa6a3aee2019-11-26 13:30:14 -0700261 case reflect.Struct:
Pragya Arya324337e2020-02-20 14:35:08 +0530262 s.compareStruct(t, vx, vy)
263 case reflect.Slice, reflect.Array:
264 s.compareSlice(t, vx, vy)
265 case reflect.Map:
266 s.compareMap(t, vx, vy)
267 case reflect.Ptr:
268 s.comparePtr(t, vx, vy)
269 case reflect.Interface:
270 s.compareInterface(t, vx, vy)
Matteo Scandoloa6a3aee2019-11-26 13:30:14 -0700271 default:
272 panic(fmt.Sprintf("%v kind not handled", t.Kind()))
273 }
274}
275
Pragya Arya324337e2020-02-20 14:35:08 +0530276func (s *state) tryOptions(t reflect.Type, vx, vy reflect.Value) bool {
Matteo Scandoloa6a3aee2019-11-26 13:30:14 -0700277 // Evaluate all filters and apply the remaining options.
Pragya Arya324337e2020-02-20 14:35:08 +0530278 if opt := s.opts.filter(s, t, vx, vy); opt != nil {
Matteo Scandoloa6a3aee2019-11-26 13:30:14 -0700279 opt.apply(s, vx, vy)
280 return true
281 }
282 return false
283}
284
Pragya Arya324337e2020-02-20 14:35:08 +0530285func (s *state) tryMethod(t reflect.Type, vx, vy reflect.Value) bool {
Matteo Scandoloa6a3aee2019-11-26 13:30:14 -0700286 // Check if this type even has an Equal method.
287 m, ok := t.MethodByName("Equal")
288 if !ok || !function.IsType(m.Type, function.EqualAssignable) {
289 return false
290 }
291
292 eq := s.callTTBFunc(m.Func, vx, vy)
Pragya Arya324337e2020-02-20 14:35:08 +0530293 s.report(eq, reportByMethod)
Matteo Scandoloa6a3aee2019-11-26 13:30:14 -0700294 return true
295}
296
Pragya Arya324337e2020-02-20 14:35:08 +0530297func (s *state) callTRFunc(f, v reflect.Value, step Transform) reflect.Value {
Matteo Scandoloa6a3aee2019-11-26 13:30:14 -0700298 v = sanitizeValue(v, f.Type().In(0))
299 if !s.dynChecker.Next() {
300 return f.Call([]reflect.Value{v})[0]
301 }
302
303 // Run the function twice and ensure that we get the same results back.
304 // We run in goroutines so that the race detector (if enabled) can detect
305 // unsafe mutations to the input.
306 c := make(chan reflect.Value)
307 go detectRaces(c, f, v)
Pragya Arya324337e2020-02-20 14:35:08 +0530308 got := <-c
Matteo Scandoloa6a3aee2019-11-26 13:30:14 -0700309 want := f.Call([]reflect.Value{v})[0]
Pragya Arya324337e2020-02-20 14:35:08 +0530310 if step.vx, step.vy = got, want; !s.statelessCompare(step).Equal() {
Matteo Scandoloa6a3aee2019-11-26 13:30:14 -0700311 // To avoid false-positives with non-reflexive equality operations,
312 // we sanity check whether a value is equal to itself.
Pragya Arya324337e2020-02-20 14:35:08 +0530313 if step.vx, step.vy = want, want; !s.statelessCompare(step).Equal() {
Matteo Scandoloa6a3aee2019-11-26 13:30:14 -0700314 return want
315 }
Pragya Arya324337e2020-02-20 14:35:08 +0530316 panic(fmt.Sprintf("non-deterministic function detected: %s", function.NameOf(f)))
Matteo Scandoloa6a3aee2019-11-26 13:30:14 -0700317 }
318 return want
319}
320
321func (s *state) callTTBFunc(f, x, y reflect.Value) bool {
322 x = sanitizeValue(x, f.Type().In(0))
323 y = sanitizeValue(y, f.Type().In(1))
324 if !s.dynChecker.Next() {
325 return f.Call([]reflect.Value{x, y})[0].Bool()
326 }
327
328 // Swapping the input arguments is sufficient to check that
329 // f is symmetric and deterministic.
330 // We run in goroutines so that the race detector (if enabled) can detect
331 // unsafe mutations to the input.
332 c := make(chan reflect.Value)
333 go detectRaces(c, f, y, x)
Pragya Arya324337e2020-02-20 14:35:08 +0530334 got := <-c
Matteo Scandoloa6a3aee2019-11-26 13:30:14 -0700335 want := f.Call([]reflect.Value{x, y})[0].Bool()
Pragya Arya324337e2020-02-20 14:35:08 +0530336 if !got.IsValid() || got.Bool() != want {
337 panic(fmt.Sprintf("non-deterministic or non-symmetric function detected: %s", function.NameOf(f)))
Matteo Scandoloa6a3aee2019-11-26 13:30:14 -0700338 }
339 return want
340}
341
342func detectRaces(c chan<- reflect.Value, f reflect.Value, vs ...reflect.Value) {
343 var ret reflect.Value
344 defer func() {
345 recover() // Ignore panics, let the other call to f panic instead
346 c <- ret
347 }()
348 ret = f.Call(vs)[0]
349}
350
351// sanitizeValue converts nil interfaces of type T to those of type R,
352// assuming that T is assignable to R.
353// Otherwise, it returns the input value as is.
354func sanitizeValue(v reflect.Value, t reflect.Type) reflect.Value {
Pragya Arya324337e2020-02-20 14:35:08 +0530355 // TODO(dsnet): Workaround for reflect bug (https://golang.org/issue/22143).
356 if !flags.AtLeastGo110 {
357 if v.Kind() == reflect.Interface && v.IsNil() && v.Type() != t {
358 return reflect.New(t).Elem()
359 }
Matteo Scandoloa6a3aee2019-11-26 13:30:14 -0700360 }
361 return v
362}
363
Pragya Arya324337e2020-02-20 14:35:08 +0530364func (s *state) compareStruct(t reflect.Type, vx, vy reflect.Value) {
Matteo Scandoloa6a3aee2019-11-26 13:30:14 -0700365 var vax, vay reflect.Value // Addressable versions of vx and vy
366
Pragya Arya324337e2020-02-20 14:35:08 +0530367 var mayForce, mayForceInit bool
368 step := StructField{&structField{}}
Matteo Scandoloa6a3aee2019-11-26 13:30:14 -0700369 for i := 0; i < t.NumField(); i++ {
Matteo Scandoloa6a3aee2019-11-26 13:30:14 -0700370 step.typ = t.Field(i).Type
Pragya Arya324337e2020-02-20 14:35:08 +0530371 step.vx = vx.Field(i)
372 step.vy = vy.Field(i)
Matteo Scandoloa6a3aee2019-11-26 13:30:14 -0700373 step.name = t.Field(i).Name
374 step.idx = i
375 step.unexported = !isExported(step.name)
376 if step.unexported {
Pragya Arya324337e2020-02-20 14:35:08 +0530377 if step.name == "_" {
378 continue
379 }
Matteo Scandoloa6a3aee2019-11-26 13:30:14 -0700380 // Defer checking of unexported fields until later to give an
381 // Ignore a chance to ignore the field.
382 if !vax.IsValid() || !vay.IsValid() {
Pragya Arya324337e2020-02-20 14:35:08 +0530383 // For retrieveUnexportedField to work, the parent struct must
Matteo Scandoloa6a3aee2019-11-26 13:30:14 -0700384 // be addressable. Create a new copy of the values if
385 // necessary to make them addressable.
386 vax = makeAddressable(vx)
387 vay = makeAddressable(vy)
388 }
Pragya Arya324337e2020-02-20 14:35:08 +0530389 if !mayForceInit {
390 for _, xf := range s.exporters {
391 mayForce = mayForce || xf(t)
392 }
393 mayForceInit = true
394 }
395 step.mayForce = mayForce
Matteo Scandoloa6a3aee2019-11-26 13:30:14 -0700396 step.pvx = vax
397 step.pvy = vay
398 step.field = t.Field(i)
399 }
Pragya Arya324337e2020-02-20 14:35:08 +0530400 s.compareAny(step)
Matteo Scandoloa6a3aee2019-11-26 13:30:14 -0700401 }
402}
403
Pragya Arya324337e2020-02-20 14:35:08 +0530404func (s *state) compareSlice(t reflect.Type, vx, vy reflect.Value) {
405 isSlice := t.Kind() == reflect.Slice
406 if isSlice && (vx.IsNil() || vy.IsNil()) {
407 s.report(vx.IsNil() && vy.IsNil(), 0)
408 return
Matteo Scandoloa6a3aee2019-11-26 13:30:14 -0700409 }
Pragya Arya324337e2020-02-20 14:35:08 +0530410
411 // NOTE: It is incorrect to call curPtrs.Push on the slice header pointer
412 // since slices represents a list of pointers, rather than a single pointer.
413 // The pointer checking logic must be handled on a per-element basis
414 // in compareAny.
415 //
416 // A slice header (see reflect.SliceHeader) in Go is a tuple of a starting
417 // pointer P, a length N, and a capacity C. Supposing each slice element has
418 // a memory size of M, then the slice is equivalent to the list of pointers:
419 // [P+i*M for i in range(N)]
420 //
421 // For example, v[:0] and v[:1] are slices with the same starting pointer,
422 // but they are clearly different values. Using the slice pointer alone
423 // violates the assumption that equal pointers implies equal values.
424
425 step := SliceIndex{&sliceIndex{pathStep: pathStep{typ: t.Elem()}, isSlice: isSlice}}
426 withIndexes := func(ix, iy int) SliceIndex {
427 if ix >= 0 {
428 step.vx, step.xkey = vx.Index(ix), ix
429 } else {
430 step.vx, step.xkey = reflect.Value{}, -1
431 }
432 if iy >= 0 {
433 step.vy, step.ykey = vy.Index(iy), iy
434 } else {
435 step.vy, step.ykey = reflect.Value{}, -1
436 }
437 return step
438 }
439
440 // Ignore options are able to ignore missing elements in a slice.
441 // However, detecting these reliably requires an optimal differencing
442 // algorithm, for which diff.Difference is not.
443 //
444 // Instead, we first iterate through both slices to detect which elements
445 // would be ignored if standing alone. The index of non-discarded elements
446 // are stored in a separate slice, which diffing is then performed on.
447 var indexesX, indexesY []int
448 var ignoredX, ignoredY []bool
449 for ix := 0; ix < vx.Len(); ix++ {
450 ignored := s.statelessCompare(withIndexes(ix, -1)).NumDiff == 0
451 if !ignored {
452 indexesX = append(indexesX, ix)
453 }
454 ignoredX = append(ignoredX, ignored)
455 }
456 for iy := 0; iy < vy.Len(); iy++ {
457 ignored := s.statelessCompare(withIndexes(-1, iy)).NumDiff == 0
458 if !ignored {
459 indexesY = append(indexesY, iy)
460 }
461 ignoredY = append(ignoredY, ignored)
462 }
463
464 // Compute an edit-script for slices vx and vy (excluding ignored elements).
465 edits := diff.Difference(len(indexesX), len(indexesY), func(ix, iy int) diff.Result {
466 return s.statelessCompare(withIndexes(indexesX[ix], indexesY[iy]))
467 })
468
469 // Replay the ignore-scripts and the edit-script.
470 var ix, iy int
471 for ix < vx.Len() || iy < vy.Len() {
472 var e diff.EditType
473 switch {
474 case ix < len(ignoredX) && ignoredX[ix]:
475 e = diff.UniqueX
476 case iy < len(ignoredY) && ignoredY[iy]:
477 e = diff.UniqueY
478 default:
479 e, edits = edits[0], edits[1:]
480 }
481 switch e {
482 case diff.UniqueX:
483 s.compareAny(withIndexes(ix, -1))
484 ix++
485 case diff.UniqueY:
486 s.compareAny(withIndexes(-1, iy))
487 iy++
488 default:
489 s.compareAny(withIndexes(ix, iy))
490 ix++
491 iy++
492 }
493 }
494}
495
496func (s *state) compareMap(t reflect.Type, vx, vy reflect.Value) {
497 if vx.IsNil() || vy.IsNil() {
498 s.report(vx.IsNil() && vy.IsNil(), 0)
499 return
500 }
501
502 // Cycle-detection for maps.
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
509 // We combine and sort the two map keys so that we can perform the
510 // comparisons in a deterministic order.
511 step := MapIndex{&mapIndex{pathStep: pathStep{typ: t.Elem()}}}
512 for _, k := range value.SortKeys(append(vx.MapKeys(), vy.MapKeys()...)) {
513 step.vx = vx.MapIndex(k)
514 step.vy = vy.MapIndex(k)
515 step.key = k
516 if !step.vx.IsValid() && !step.vy.IsValid() {
517 // It is possible for both vx and vy to be invalid if the
518 // key contained a NaN value in it.
519 //
520 // Even with the ability to retrieve NaN keys in Go 1.12,
521 // there still isn't a sensible way to compare the values since
522 // a NaN key may map to multiple unordered values.
523 // The most reasonable way to compare NaNs would be to compare the
524 // set of values. However, this is impossible to do efficiently
525 // since set equality is provably an O(n^2) operation given only
526 // an Equal function. If we had a Less function or Hash function,
527 // this could be done in O(n*log(n)) or O(n), respectively.
528 //
529 // Rather than adding complex logic to deal with NaNs, make it
530 // the user's responsibility to compare such obscure maps.
531 const help = "consider providing a Comparer to compare the map"
532 panic(fmt.Sprintf("%#v has map key with NaNs\n%s", s.curPath, help))
533 }
534 s.compareAny(step)
535 }
536}
537
538func (s *state) comparePtr(t reflect.Type, vx, vy reflect.Value) {
539 if vx.IsNil() || vy.IsNil() {
540 s.report(vx.IsNil() && vy.IsNil(), 0)
541 return
542 }
543
544 // Cycle-detection for pointers.
545 if eq, visited := s.curPtrs.Push(vx, vy); visited {
546 s.report(eq, reportByCycle)
547 return
548 }
549 defer s.curPtrs.Pop(vx, vy)
550
551 vx, vy = vx.Elem(), vy.Elem()
552 s.compareAny(Indirect{&indirect{pathStep{t.Elem(), vx, vy}}})
553}
554
555func (s *state) compareInterface(t reflect.Type, vx, vy reflect.Value) {
556 if vx.IsNil() || vy.IsNil() {
557 s.report(vx.IsNil() && vy.IsNil(), 0)
558 return
559 }
560 vx, vy = vx.Elem(), vy.Elem()
561 if vx.Type() != vy.Type() {
562 s.report(false, 0)
563 return
564 }
565 s.compareAny(TypeAssertion{&typeAssertion{pathStep{vx.Type(), vx, vy}}})
566}
567
568func (s *state) report(eq bool, rf resultFlags) {
569 if rf&reportByIgnore == 0 {
570 if eq {
571 s.result.NumSame++
572 rf |= reportEqual
573 } else {
574 s.result.NumDiff++
575 rf |= reportUnequal
576 }
577 }
578 for _, r := range s.reporters {
579 r.Report(Result{flags: rf})
580 }
581}
582
583// recChecker tracks the state needed to periodically perform checks that
584// user provided transformers are not stuck in an infinitely recursive cycle.
585type recChecker struct{ next int }
586
587// Check scans the Path for any recursive transformers and panics when any
588// recursive transformers are detected. Note that the presence of a
589// recursive Transformer does not necessarily imply an infinite cycle.
590// As such, this check only activates after some minimal number of path steps.
591func (rc *recChecker) Check(p Path) {
592 const minLen = 1 << 16
593 if rc.next == 0 {
594 rc.next = minLen
595 }
596 if len(p) < rc.next {
597 return
598 }
599 rc.next <<= 1
600
601 // Check whether the same transformer has appeared at least twice.
602 var ss []string
603 m := map[Option]int{}
604 for _, ps := range p {
605 if t, ok := ps.(Transform); ok {
606 t := t.Option()
607 if m[t] == 1 { // Transformer was used exactly once before
608 tf := t.(*transformer).fnc.Type()
609 ss = append(ss, fmt.Sprintf("%v: %v => %v", t, tf.In(0), tf.Out(0)))
610 }
611 m[t]++
612 }
613 }
614 if len(ss) > 0 {
615 const warning = "recursive set of Transformers detected"
616 const help = "consider using cmpopts.AcyclicTransformer"
617 set := strings.Join(ss, "\n\t")
618 panic(fmt.Sprintf("%s:\n\t%s\n%s", warning, set, help))
Matteo Scandoloa6a3aee2019-11-26 13:30:14 -0700619 }
620}
621
622// dynChecker tracks the state needed to periodically perform checks that
623// user provided functions are symmetric and deterministic.
624// The zero value is safe for immediate use.
625type dynChecker struct{ curr, next int }
626
627// Next increments the state and reports whether a check should be performed.
628//
629// Checks occur every Nth function call, where N is a triangular number:
630// 0 1 3 6 10 15 21 28 36 45 55 66 78 91 105 120 136 153 171 190 ...
631// See https://en.wikipedia.org/wiki/Triangular_number
632//
633// This sequence ensures that the cost of checks drops significantly as
634// the number of functions calls grows larger.
635func (dc *dynChecker) Next() bool {
636 ok := dc.curr == dc.next
637 if ok {
638 dc.curr = 0
639 dc.next++
640 }
641 dc.curr++
642 return ok
643}
644
645// makeAddressable returns a value that is always addressable.
646// It returns the input verbatim if it is already addressable,
647// otherwise it creates a new value and returns an addressable copy.
648func makeAddressable(v reflect.Value) reflect.Value {
649 if v.CanAddr() {
650 return v
651 }
652 vc := reflect.New(v.Type()).Elem()
653 vc.Set(v)
654 return vc
655}