github.com/integration-system/go-cmp@v0.0.0-20190131081942-ac5582987a2f/cmp/compare.go (about) 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 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 25 // by using an Ignore option (see cmpopts.IgnoreUnexported) or explicitly compared 26 // using the AllowUnexported option. 27 package cmp 28 29 import ( 30 "fmt" 31 "reflect" 32 "strings" 33 34 "github.com/integration-system/go-cmp/cmp/internal/diff" 35 "github.com/integration-system/go-cmp/cmp/internal/function" 36 "github.com/integration-system/go-cmp/cmp/internal/value" 37 ) 38 39 // BUG(dsnet): Maps with keys containing NaN values cannot be properly compared due to 40 // the reflection package's inability to retrieve such entries. Equal will panic 41 // anytime it comes across a NaN key, but this behavior may change. 42 // 43 // See https://golang.org/issue/11104 for more details. 44 45 var nothing = reflect.Value{} 46 47 // Equal reports whether x and y are equal by recursively applying the 48 // following rules in the given order to x and y and all of their sub-values: 49 // 50 // • If two values are not of the same type, then they are never equal 51 // and the overall result is false. 52 // 53 // • Let S be the set of all Ignore, Transformer, and Comparer options that 54 // remain after applying all path filters, value filters, and type filters. 55 // If at least one Ignore exists in S, then the comparison is ignored. 56 // If the number of Transformer and Comparer options in S is greater than one, 57 // then Equal panics because it is ambiguous which option to use. 58 // If S contains a single Transformer, then use that to transform the current 59 // values and recursively call Equal on the output values. 60 // If S contains a single Comparer, then use that to compare the current values. 61 // Otherwise, evaluation proceeds to the next rule. 62 // 63 // • If the values have an Equal method of the form "(T) Equal(T) bool" or 64 // "(T) Equal(I) bool" where T is assignable to I, then use the result of 65 // x.Equal(y) even if x or y is nil. 66 // Otherwise, no such method exists and evaluation proceeds to the next rule. 67 // 68 // • Lastly, try to compare x and y based on their basic kinds. 69 // Simple kinds like booleans, integers, floats, complex numbers, strings, and 70 // channels are compared using the equivalent of the == operator in Go. 71 // Functions are only equal if they are both nil, otherwise they are unequal. 72 // Pointers are equal if the underlying values they point to are also equal. 73 // Interfaces are equal if their underlying concrete values are also equal. 74 // 75 // Structs are equal if all of their fields are equal. If a struct contains 76 // unexported fields, Equal panics unless the AllowUnexported option is used or 77 // an Ignore option (e.g., cmpopts.IgnoreUnexported) ignores that field. 78 // 79 // Arrays, slices, and maps are equal if they are both nil or both non-nil 80 // with the same length and the elements at each index or key are equal. 81 // Note that a non-nil empty slice and a nil slice are not equal. 82 // To equate empty slices and maps, consider using cmpopts.EquateEmpty. 83 // Map keys are equal according to the == operator. 84 // To use custom comparisons for map keys, consider using cmpopts.SortMaps. 85 func Equal(x, y interface{}, opts ...Option) bool { 86 s := newState(opts) 87 s.compareAny(reflect.ValueOf(x), reflect.ValueOf(y), nothing, nothing) 88 return s.result.Equal() 89 } 90 91 // Diff returns a human-readable report of the differences between two values. 92 // It returns an empty string if and only if Equal returns true for the same 93 // input values and options. The output string will use the "-" symbol to 94 // indicate elements removed from x, and the "+" symbol to indicate elements 95 // added to y. 96 // 97 // Do not depend on this output being stable. 98 func Diff(x, y interface{}, opts ...Option) string { 99 r := new(defaultReporter) 100 opts = Options{Options(opts), r} 101 eq := Equal(x, y, opts...) 102 d := r.String() 103 if (d == "") != eq { 104 panic("inconsistent difference and equality results") 105 } 106 return d 107 } 108 109 type state struct { 110 // These fields represent the "comparison state". 111 // Calling statelessCompare must not result in observable changes to these. 112 result diff.Result // The current result of comparison 113 curPath Path // The current path in the value tree 114 reporters []Reporter // Optional reporters used for difference formatting 115 116 // recChecker checks for infinite cycles applying the same set of 117 // transformers upon the output of itself. 118 recChecker recChecker 119 120 // dynChecker triggers pseudo-random checks for option correctness. 121 // It is safe for statelessCompare to mutate this value. 122 dynChecker dynChecker 123 124 // These fields, once set by processOption, will not change. 125 exporters map[reflect.Type]bool // Set of structs with unexported field visibility 126 opts Options // List of all fundamental and filter options 127 } 128 129 func newState(opts []Option) *state { 130 s := new(state) 131 for _, opt := range opts { 132 s.processOption(opt) 133 } 134 return s 135 } 136 137 func (s *state) processOption(opt Option) { 138 switch opt := opt.(type) { 139 case nil: 140 case Options: 141 for _, o := range opt { 142 s.processOption(o) 143 } 144 case coreOption: 145 type filtered interface { 146 isFiltered() bool 147 } 148 if fopt, ok := opt.(filtered); ok && !fopt.isFiltered() { 149 panic(fmt.Sprintf("cannot use an unfiltered option: %v", opt)) 150 } 151 s.opts = append(s.opts, opt) 152 case visibleStructs: 153 if s.exporters == nil { 154 s.exporters = make(map[reflect.Type]bool) 155 } 156 for t := range opt { 157 s.exporters[t] = true 158 } 159 case Reporter: 160 s.reporters = append(s.reporters, opt) 161 default: 162 panic(fmt.Sprintf("unknown option %T", opt)) 163 } 164 } 165 166 // statelessCompare compares two values and returns the result. 167 // This function is stateless in that it does not alter the current result, 168 // or output to any registered reporters. 169 func (s *state) statelessCompare(vx, vy, parentX, parentY reflect.Value) diff.Result { 170 // We do not save and restore the curPath because all of the compareX 171 // methods should properly push and pop from the path. 172 // It is an implementation bug if the contents of curPath differs from 173 // when calling this function to when returning from it. 174 175 oldResult, oldReporter := s.result, s.reporters 176 s.result = diff.Result{} // Reset result 177 s.reporters = nil // Remove reporter to avoid spurious printouts 178 s.compareAny(vx, vy, parentX, parentY) 179 res := s.result 180 s.result, s.reporters = oldResult, oldReporter 181 return res 182 } 183 184 func (s *state) compareAny(vx, vy, parentX, parentY reflect.Value) { 185 // TODO: Support cyclic data structures. 186 s.recChecker.Check(s.curPath) 187 188 // Rule 0: Differing types are never equal. 189 if !vx.IsValid() || !vy.IsValid() { 190 s.report(vx.IsValid() == vy.IsValid(), vx, vy) 191 return 192 } 193 if vx.Type() != vy.Type() { 194 s.report(false, vx, vy) // Possible for path to be empty 195 return 196 } 197 t := vx.Type() 198 if len(s.curPath) == 0 { 199 s.curPath.push(&pathStep{typ: t, parentX: parentX, parentY: parentY}) 200 defer s.curPath.pop() 201 } 202 vx, vy = s.tryExporting(vx, vy) 203 204 // Rule 1: Check whether an option applies on this node in the value tree. 205 if s.tryOptions(vx, vy, parentX, parentY, t) { 206 return 207 } 208 209 // Rule 2: Check whether the type has a valid Equal method. 210 if s.tryMethod(vx, vy, t) { 211 return 212 } 213 214 // Rule 3: Recursively descend into each value's underlying kind. 215 switch t.Kind() { 216 case reflect.Bool: 217 s.report(vx.Bool() == vy.Bool(), vx, vy) 218 return 219 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: 220 s.report(vx.Int() == vy.Int(), vx, vy) 221 return 222 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: 223 s.report(vx.Uint() == vy.Uint(), vx, vy) 224 return 225 case reflect.Float32, reflect.Float64: 226 s.report(vx.Float() == vy.Float(), vx, vy) 227 return 228 case reflect.Complex64, reflect.Complex128: 229 s.report(vx.Complex() == vy.Complex(), vx, vy) 230 return 231 case reflect.String: 232 s.report(vx.String() == vy.String(), vx, vy) 233 return 234 case reflect.Chan, reflect.UnsafePointer: 235 s.report(vx.Pointer() == vy.Pointer(), vx, vy) 236 return 237 case reflect.Func: 238 s.report(vx.IsNil() && vy.IsNil(), vx, vy) 239 return 240 case reflect.Ptr: 241 if vx.IsNil() || vy.IsNil() { 242 s.report(vx.IsNil() && vy.IsNil(), vx, vy) 243 return 244 } 245 s.curPath.push(&indirect{pathStep{t.Elem(), parentX, parentY}}) 246 defer s.curPath.pop() 247 s.compareAny(vx.Elem(), vy.Elem(), parentX, parentY) 248 return 249 case reflect.Interface: 250 if vx.IsNil() || vy.IsNil() { 251 s.report(vx.IsNil() && vy.IsNil(), vx, vy) 252 return 253 } 254 if vx.Elem().Type() != vy.Elem().Type() { 255 s.report(false, vx.Elem(), vy.Elem()) 256 return 257 } 258 s.curPath.push(&typeAssertion{pathStep{vx.Elem().Type(), parentX, parentY}}) 259 defer s.curPath.pop() 260 s.compareAny(vx.Elem(), vy.Elem(), parentX, parentY) 261 return 262 case reflect.Slice: 263 if vx.IsNil() || vy.IsNil() { 264 s.report(vx.IsNil() && vy.IsNil(), vx, vy) 265 return 266 } 267 fallthrough 268 case reflect.Array: 269 s.compareArray(vx, vy, vx, vy, t) 270 return 271 case reflect.Map: 272 s.compareMap(vx, vy, vx, vy, t) 273 return 274 case reflect.Struct: 275 s.compareStruct(vx, vy, vx, vy, t) 276 return 277 default: 278 panic(fmt.Sprintf("%v kind not handled", t.Kind())) 279 } 280 } 281 282 func (s *state) tryExporting(vx, vy reflect.Value) (reflect.Value, reflect.Value) { 283 if sf, ok := s.curPath[len(s.curPath)-1].(*structField); ok && sf.unexported { 284 if sf.force { 285 // Use unsafe pointer arithmetic to get read-write access to an 286 // unexported field in the struct. 287 vx = unsafeRetrieveField(sf.pvx, sf.field) 288 vy = unsafeRetrieveField(sf.pvy, sf.field) 289 } else { 290 // We are not allowed to export the value, so invalidate them 291 // so that tryOptions can panic later if not explicitly ignored. 292 vx = nothing 293 vy = nothing 294 } 295 } 296 return vx, vy 297 } 298 299 func (s *state) tryOptions(vx, vy, parentX, parentY reflect.Value, t reflect.Type) bool { 300 // If there were no FilterValues, we will not detect invalid inputs, 301 // so manually check for them and append invalid if necessary. 302 // We still evaluate the options since an ignore can override invalid. 303 opts := s.opts 304 if !vx.IsValid() || !vy.IsValid() { 305 opts = Options{opts, invalid{}} 306 } 307 308 // Evaluate all filters and apply the remaining options. 309 if opt := opts.filter(s, vx, vy, t); opt != nil { 310 opt.apply(s, vx, vy, parentX, parentY) 311 return true 312 } 313 return false 314 } 315 316 func (s *state) tryMethod(vx, vy reflect.Value, t reflect.Type) bool { 317 // Check if this type even has an Equal method. 318 m, ok := t.MethodByName("Equal") 319 if !ok || !function.IsType(m.Type, function.EqualAssignable) { 320 return false 321 } 322 323 eq := s.callTTBFunc(m.Func, vx, vy) 324 s.report(eq, vx, vy) 325 return true 326 } 327 328 func (s *state) callTRFunc(f, v reflect.Value) reflect.Value { 329 v = sanitizeValue(v, f.Type().In(0)) 330 if !s.dynChecker.Next() { 331 return f.Call([]reflect.Value{v})[0] 332 } 333 334 // Run the function twice and ensure that we get the same results back. 335 // We run in goroutines so that the race detector (if enabled) can detect 336 // unsafe mutations to the input. 337 c := make(chan reflect.Value) 338 go detectRaces(c, f, v) 339 want := f.Call([]reflect.Value{v})[0] 340 if got := <-c; !s.statelessCompare(got, want, nothing, nothing).Equal() { 341 // To avoid false-positives with non-reflexive equality operations, 342 // we sanity check whether a value is equal to itself. 343 if !s.statelessCompare(want, want, nothing, nothing).Equal() { 344 return want 345 } 346 fn := getFuncName(f.Pointer()) 347 panic(fmt.Sprintf("non-deterministic function detected: %s", fn)) 348 } 349 return want 350 } 351 352 func (s *state) callTTBFunc(f, x, y reflect.Value) bool { 353 x = sanitizeValue(x, f.Type().In(0)) 354 y = sanitizeValue(y, f.Type().In(1)) 355 if !s.dynChecker.Next() { 356 return f.Call([]reflect.Value{x, y})[0].Bool() 357 } 358 359 // Swapping the input arguments is sufficient to check that 360 // f is symmetric and deterministic. 361 // We run in goroutines so that the race detector (if enabled) can detect 362 // unsafe mutations to the input. 363 c := make(chan reflect.Value) 364 go detectRaces(c, f, y, x) 365 want := f.Call([]reflect.Value{x, y})[0].Bool() 366 if got := <-c; !got.IsValid() || got.Bool() != want { 367 fn := getFuncName(f.Pointer()) 368 panic(fmt.Sprintf("non-deterministic or non-symmetric function detected: %s", fn)) 369 } 370 return want 371 } 372 373 func detectRaces(c chan<- reflect.Value, f reflect.Value, vs ...reflect.Value) { 374 var ret reflect.Value 375 defer func() { 376 recover() // Ignore panics, let the other call to f panic instead 377 c <- ret 378 }() 379 ret = f.Call(vs)[0] 380 } 381 382 // sanitizeValue converts nil interfaces of type T to those of type R, 383 // assuming that T is assignable to R. 384 // Otherwise, it returns the input value as is. 385 func sanitizeValue(v reflect.Value, t reflect.Type) reflect.Value { 386 // TODO(dsnet): Workaround for reflect bug (https://golang.org/issue/22143). 387 // The upstream fix landed in Go1.10, so we can remove this when drop support 388 // for Go1.9 and below. 389 if v.Kind() == reflect.Interface && v.IsNil() && v.Type() != t { 390 return reflect.New(t).Elem() 391 } 392 return v 393 } 394 395 func (s *state) compareArray(vx, vy, parentX, parentY reflect.Value, t reflect.Type) { 396 step := &sliceIndex{pathStep{t.Elem(), parentX, parentY}, 0, 0} 397 s.curPath.push(step) 398 399 // Compute an edit-script for slices vx and vy. 400 es := diff.Difference(vx.Len(), vy.Len(), func(ix, iy int) diff.Result { 401 step.xkey, step.ykey = ix, iy 402 return s.statelessCompare(vx.Index(ix), vy.Index(iy), vx, vy) 403 }) 404 405 // Report the entire slice as is if the arrays are of primitive kind, 406 // and the arrays are different enough. 407 isPrimitive := false 408 switch t.Elem().Kind() { 409 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, 410 reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr, 411 reflect.Bool, reflect.Float32, reflect.Float64, reflect.Complex64, reflect.Complex128: 412 isPrimitive = true 413 } 414 if isPrimitive && es.Dist() > (vx.Len()+vy.Len())/4 { 415 s.curPath.pop() // Pop first since we are reporting the whole slice 416 s.report(false, vx, vy) 417 return 418 } 419 420 // Replay the edit-script. 421 var ix, iy int 422 for _, e := range es { 423 switch e { 424 case diff.UniqueX: 425 step.xkey, step.ykey = ix, -1 426 s.report(false, vx.Index(ix), nothing) 427 ix++ 428 case diff.UniqueY: 429 step.xkey, step.ykey = -1, iy 430 s.report(false, nothing, vy.Index(iy)) 431 iy++ 432 default: 433 step.xkey, step.ykey = ix, iy 434 if e == diff.Identity { 435 s.report(true, vx.Index(ix), vy.Index(iy)) 436 } else { 437 s.compareAny(vx.Index(ix), vy.Index(iy), vx, vy) 438 } 439 ix++ 440 iy++ 441 } 442 } 443 s.curPath.pop() 444 return 445 } 446 447 func (s *state) compareMap(vx, vy, parentX, parentY reflect.Value, t reflect.Type) { 448 if vx.IsNil() || vy.IsNil() { 449 s.report(vx.IsNil() && vy.IsNil(), vx, vy) 450 return 451 } 452 453 // We combine and sort the two map keys so that we can perform the 454 // comparisons in a deterministic order. 455 step := &mapIndex{pathStep: pathStep{t.Elem(), parentX, parentY}} 456 s.curPath.push(step) 457 defer s.curPath.pop() 458 for _, k := range value.SortKeys(append(vx.MapKeys(), vy.MapKeys()...)) { 459 step.key = k 460 vvx := vx.MapIndex(k) 461 vvy := vy.MapIndex(k) 462 switch { 463 case vvx.IsValid() && vvy.IsValid(): 464 s.compareAny(vvx, vvy, vx, vy) 465 case vvx.IsValid() && !vvy.IsValid(): 466 s.report(false, vvx, nothing) 467 case !vvx.IsValid() && vvy.IsValid(): 468 s.report(false, nothing, vvy) 469 default: 470 // It is possible for both vvx and vvy to be invalid if the 471 // key contained a NaN value in it. There is no way in 472 // reflection to be able to retrieve these values. 473 // See https://golang.org/issue/11104 474 panic(fmt.Sprintf("%#v has map key with NaNs", s.curPath)) 475 } 476 } 477 } 478 479 func (s *state) compareStruct(vx, vy, parentX, parentY reflect.Value, t reflect.Type) { 480 var vax, vay reflect.Value // Addressable versions of vx and vy 481 482 step := &structField{} 483 s.curPath.push(step) 484 defer s.curPath.pop() 485 for i := 0; i < t.NumField(); i++ { 486 vvx := vx.Field(i) 487 vvy := vy.Field(i) 488 step.typ = t.Field(i).Type 489 step.name = t.Field(i).Name 490 step.parentX = parentX 491 step.parentY = parentY 492 step.idx = i 493 step.unexported = !isExported(step.name) 494 if step.unexported { 495 // Defer checking of unexported fields until later to give an 496 // Ignore a chance to ignore the field. 497 if !vax.IsValid() || !vay.IsValid() { 498 // For unsafeRetrieveField to work, the parent struct must 499 // be addressable. Create a new copy of the values if 500 // necessary to make them addressable. 501 vax = makeAddressable(vx) 502 vay = makeAddressable(vy) 503 } 504 step.force = s.exporters[t] 505 step.pvx = vax 506 step.pvy = vay 507 step.field = t.Field(i) 508 } 509 s.compareAny(vvx, vvy, vx, vy) 510 } 511 } 512 513 // report records the result of a single comparison. 514 // It also calls Report if any reporter is registered. 515 func (s *state) report(eq bool, vx, vy reflect.Value) { 516 if eq { 517 s.result.NSame++ 518 } else { 519 s.result.NDiff++ 520 } 521 for _, r := range s.reporters { 522 r.Report(vx, vy, eq, s.curPath) 523 } 524 } 525 526 // recChecker tracks the state needed to periodically perform checks that 527 // user provided transformers are not stuck in an infinitely recursive cycle. 528 type recChecker struct{ next int } 529 530 // Check scans the Path for any recursive transformers and panics when any 531 // recursive transformers are detected. Note that the presence of a 532 // recursive Transformer does not necessarily imply an infinite cycle. 533 // As such, this check only activates after some minimal number of path steps. 534 func (rc *recChecker) Check(p Path) { 535 const minLen = 1 << 16 536 if rc.next == 0 { 537 rc.next = minLen 538 } 539 if len(p) < rc.next { 540 return 541 } 542 rc.next <<= 1 543 544 // Check whether the same transformer has appeared at least twice. 545 var ss []string 546 m := map[Option]int{} 547 for _, ps := range p { 548 if t, ok := ps.(Transform); ok { 549 t := t.Option() 550 if m[t] == 1 { // Transformer was used exactly once before 551 tf := t.(*transformer).fnc.Type() 552 ss = append(ss, fmt.Sprintf("%v: %v => %v", t, tf.In(0), tf.Out(0))) 553 } 554 m[t]++ 555 } 556 } 557 if len(ss) > 0 { 558 const warning = "recursive set of Transformers detected" 559 const help = "consider using cmpopts.AcyclicTransformer" 560 set := strings.Join(ss, "\n\t") 561 panic(fmt.Sprintf("%s:\n\t%s\n%s", warning, set, help)) 562 } 563 } 564 565 // dynChecker tracks the state needed to periodically perform checks that 566 // user provided functions are symmetric and deterministic. 567 // The zero value is safe for immediate use. 568 type dynChecker struct{ curr, next int } 569 570 // Next increments the state and reports whether a check should be performed. 571 // 572 // Checks occur every Nth function call, where N is a triangular number: 573 // 0 1 3 6 10 15 21 28 36 45 55 66 78 91 105 120 136 153 171 190 ... 574 // See https://en.wikipedia.org/wiki/Triangular_number 575 // 576 // This sequence ensures that the cost of checks drops significantly as 577 // the number of functions calls grows larger. 578 func (dc *dynChecker) Next() bool { 579 ok := dc.curr == dc.next 580 if ok { 581 dc.curr = 0 582 dc.next++ 583 } 584 dc.curr++ 585 return ok 586 } 587 588 // makeAddressable returns a value that is always addressable. 589 // It returns the input verbatim if it is already addressable, 590 // otherwise it creates a new value and returns an addressable copy. 591 func makeAddressable(v reflect.Value) reflect.Value { 592 if v.CanAddr() { 593 return v 594 } 595 vc := reflect.New(v.Type()).Elem() 596 vc.Set(v) 597 return vc 598 }