Path: blob/main/vendor/github.com/google/go-cmp/cmp/compare.go
2880 views
// Copyright 2017, The Go Authors. All rights reserved.1// Use of this source code is governed by a BSD-style2// license that can be found in the LICENSE file.34// Package cmp determines equality of values.5//6// This package is intended to be a more powerful and safer alternative to7// [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 and9// it may panic if it cannot compare the values. Its propensity towards10// panicking means that its unsuitable for production environments where a11// 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 as18// they are within some tolerance of each other.19//20// - Types with an Equal method (e.g., [time.Time.Equal]) may use that method21// to determine equality. This allows package authors to determine22// the equality operation for the types that they define.23//24// - If no custom equality functions are used and no Equal method is defined,25// equality is determined by recursively comparing the primitive kinds on26// both values, much like [reflect.DeepEqual]. Unlike [reflect.DeepEqual],27// unexported fields are not compared by default; they result in panics28// unless suppressed by using an [Ignore] option29// (see [github.com/google/go-cmp/cmp/cmpopts.IgnoreUnexported])30// or explicitly compared using the [Exporter] option.31package cmp3233import (34"fmt"35"reflect"36"strings"3738"github.com/google/go-cmp/cmp/internal/diff"39"github.com/google/go-cmp/cmp/internal/function"40"github.com/google/go-cmp/cmp/internal/value"41)4243// TODO(≥go1.18): Use any instead of interface{}.4445// Equal reports whether x and y are equal by recursively applying the46// following rules in the given order to x and y and all of their sub-values:47//48// - Let S be the set of all [Ignore], [Transformer], and [Comparer] options that49// remain after applying all path filters, value filters, and type filters.50// If at least one [Ignore] exists in S, then the comparison is ignored.51// If the number of [Transformer] and [Comparer] options in S is non-zero,52// then Equal panics because it is ambiguous which option to use.53// If S contains a single [Transformer], then use that to transform54// the current values and recursively call Equal on the output values.55// If S contains a single [Comparer], then use that to compare the current values.56// Otherwise, evaluation proceeds to the next rule.57//58// - If the values have an Equal method of the form "(T) Equal(T) bool" or59// "(T) Equal(I) bool" where T is assignable to I, then use the result of60// x.Equal(y) even if x or y is nil. Otherwise, no such method exists and61// evaluation proceeds to the next rule.62//63// - Lastly, try to compare x and y based on their basic kinds.64// Simple kinds like booleans, integers, floats, complex numbers, strings,65// and channels are compared using the equivalent of the == operator in Go.66// Functions are only equal if they are both nil, otherwise they are unequal.67//68// Structs are equal if recursively calling Equal on all fields report equal.69// If a struct contains unexported fields, Equal panics unless an [Ignore] option70// (e.g., [github.com/google/go-cmp/cmp/cmpopts.IgnoreUnexported]) ignores that field71// or the [Exporter] option explicitly permits comparing the unexported field.72//73// Slices are equal if they are both nil or both non-nil, where recursively74// calling Equal on all non-ignored slice or array elements report equal.75// Empty non-nil slices and nil slices are not equal; to equate empty slices,76// consider using [github.com/google/go-cmp/cmp/cmpopts.EquateEmpty].77//78// Maps are equal if they are both nil or both non-nil, where recursively79// calling Equal on all non-ignored map entries report equal.80// Map keys are equal according to the == operator.81// To use custom comparisons for map keys, consider using82// [github.com/google/go-cmp/cmp/cmpopts.SortMaps].83// Empty non-nil maps and nil maps are not equal; to equate empty maps,84// consider using [github.com/google/go-cmp/cmp/cmpopts.EquateEmpty].85//86// Pointers and interfaces are equal if they are both nil or both non-nil,87// where they have the same underlying concrete type and recursively88// calling Equal on the underlying values reports equal.89//90// Before recursing into a pointer, slice element, or map, the current path91// is checked to detect whether the address has already been visited.92// If there is a cycle, then the pointed at values are considered equal93// only if both addresses were previously visited in the same path step.94func Equal(x, y interface{}, opts ...Option) bool {95s := newState(opts)96s.compareAny(rootStep(x, y))97return s.result.Equal()98}99100// Diff returns a human-readable report of the differences between two values:101// y - x. It returns an empty string if and only if Equal returns true for the102// same input values and options.103//104// The output is displayed as a literal in pseudo-Go syntax.105// At the start of each line, a "-" prefix indicates an element removed from x,106// a "+" prefix to indicates an element added from y, and the lack of a prefix107// indicates an element common to both x and y. If possible, the output108// uses fmt.Stringer.String or error.Error methods to produce more humanly109// readable outputs. In such cases, the string is prefixed with either an110// 's' or 'e' character, respectively, to indicate that the method was called.111//112// Do not depend on this output being stable. If you need the ability to113// programmatically interpret the difference, consider using a custom Reporter.114func Diff(x, y interface{}, opts ...Option) string {115s := newState(opts)116117// Optimization: If there are no other reporters, we can optimize for the118// common case where the result is equal (and thus no reported difference).119// This avoids the expensive construction of a difference tree.120if len(s.reporters) == 0 {121s.compareAny(rootStep(x, y))122if s.result.Equal() {123return ""124}125s.result = diff.Result{} // Reset results126}127128r := new(defaultReporter)129s.reporters = append(s.reporters, reporter{r})130s.compareAny(rootStep(x, y))131d := r.String()132if (d == "") != s.result.Equal() {133panic("inconsistent difference and equality results")134}135return d136}137138// rootStep constructs the first path step. If x and y have differing types,139// then they are stored within an empty interface type.140func rootStep(x, y interface{}) PathStep {141vx := reflect.ValueOf(x)142vy := reflect.ValueOf(y)143144// If the inputs are different types, auto-wrap them in an empty interface145// so that they have the same parent type.146var t reflect.Type147if !vx.IsValid() || !vy.IsValid() || vx.Type() != vy.Type() {148t = anyType149if vx.IsValid() {150vvx := reflect.New(t).Elem()151vvx.Set(vx)152vx = vvx153}154if vy.IsValid() {155vvy := reflect.New(t).Elem()156vvy.Set(vy)157vy = vvy158}159} else {160t = vx.Type()161}162163return &pathStep{t, vx, vy}164}165166type state struct {167// These fields represent the "comparison state".168// Calling statelessCompare must not result in observable changes to these.169result diff.Result // The current result of comparison170curPath Path // The current path in the value tree171curPtrs pointerPath // The current set of visited pointers172reporters []reporter // Optional reporters173174// recChecker checks for infinite cycles applying the same set of175// transformers upon the output of itself.176recChecker recChecker177178// dynChecker triggers pseudo-random checks for option correctness.179// It is safe for statelessCompare to mutate this value.180dynChecker dynChecker181182// These fields, once set by processOption, will not change.183exporters []exporter // List of exporters for structs with unexported fields184opts Options // List of all fundamental and filter options185}186187func newState(opts []Option) *state {188// Always ensure a validator option exists to validate the inputs.189s := &state{opts: Options{validator{}}}190s.curPtrs.Init()191s.processOption(Options(opts))192return s193}194195func (s *state) processOption(opt Option) {196switch opt := opt.(type) {197case nil:198case Options:199for _, o := range opt {200s.processOption(o)201}202case coreOption:203type filtered interface {204isFiltered() bool205}206if fopt, ok := opt.(filtered); ok && !fopt.isFiltered() {207panic(fmt.Sprintf("cannot use an unfiltered option: %v", opt))208}209s.opts = append(s.opts, opt)210case exporter:211s.exporters = append(s.exporters, opt)212case reporter:213s.reporters = append(s.reporters, opt)214default:215panic(fmt.Sprintf("unknown option %T", opt))216}217}218219// statelessCompare compares two values and returns the result.220// This function is stateless in that it does not alter the current result,221// or output to any registered reporters.222func (s *state) statelessCompare(step PathStep) diff.Result {223// We do not save and restore curPath and curPtrs because all of the224// compareX methods should properly push and pop from them.225// It is an implementation bug if the contents of the paths differ from226// when calling this function to when returning from it.227228oldResult, oldReporters := s.result, s.reporters229s.result = diff.Result{} // Reset result230s.reporters = nil // Remove reporters to avoid spurious printouts231s.compareAny(step)232res := s.result233s.result, s.reporters = oldResult, oldReporters234return res235}236237func (s *state) compareAny(step PathStep) {238// Update the path stack.239s.curPath.push(step)240defer s.curPath.pop()241for _, r := range s.reporters {242r.PushStep(step)243defer r.PopStep()244}245s.recChecker.Check(s.curPath)246247// Cycle-detection for slice elements (see NOTE in compareSlice).248t := step.Type()249vx, vy := step.Values()250if si, ok := step.(SliceIndex); ok && si.isSlice && vx.IsValid() && vy.IsValid() {251px, py := vx.Addr(), vy.Addr()252if eq, visited := s.curPtrs.Push(px, py); visited {253s.report(eq, reportByCycle)254return255}256defer s.curPtrs.Pop(px, py)257}258259// Rule 1: Check whether an option applies on this node in the value tree.260if s.tryOptions(t, vx, vy) {261return262}263264// Rule 2: Check whether the type has a valid Equal method.265if s.tryMethod(t, vx, vy) {266return267}268269// Rule 3: Compare based on the underlying kind.270switch t.Kind() {271case reflect.Bool:272s.report(vx.Bool() == vy.Bool(), 0)273case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:274s.report(vx.Int() == vy.Int(), 0)275case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:276s.report(vx.Uint() == vy.Uint(), 0)277case reflect.Float32, reflect.Float64:278s.report(vx.Float() == vy.Float(), 0)279case reflect.Complex64, reflect.Complex128:280s.report(vx.Complex() == vy.Complex(), 0)281case reflect.String:282s.report(vx.String() == vy.String(), 0)283case reflect.Chan, reflect.UnsafePointer:284s.report(vx.Pointer() == vy.Pointer(), 0)285case reflect.Func:286s.report(vx.IsNil() && vy.IsNil(), 0)287case reflect.Struct:288s.compareStruct(t, vx, vy)289case reflect.Slice, reflect.Array:290s.compareSlice(t, vx, vy)291case reflect.Map:292s.compareMap(t, vx, vy)293case reflect.Ptr:294s.comparePtr(t, vx, vy)295case reflect.Interface:296s.compareInterface(t, vx, vy)297default:298panic(fmt.Sprintf("%v kind not handled", t.Kind()))299}300}301302func (s *state) tryOptions(t reflect.Type, vx, vy reflect.Value) bool {303// Evaluate all filters and apply the remaining options.304if opt := s.opts.filter(s, t, vx, vy); opt != nil {305opt.apply(s, vx, vy)306return true307}308return false309}310311func (s *state) tryMethod(t reflect.Type, vx, vy reflect.Value) bool {312// Check if this type even has an Equal method.313m, ok := t.MethodByName("Equal")314if !ok || !function.IsType(m.Type, function.EqualAssignable) {315return false316}317318eq := s.callTTBFunc(m.Func, vx, vy)319s.report(eq, reportByMethod)320return true321}322323func (s *state) callTRFunc(f, v reflect.Value, step Transform) reflect.Value {324if !s.dynChecker.Next() {325return f.Call([]reflect.Value{v})[0]326}327328// Run the function twice and ensure that we get the same results back.329// We run in goroutines so that the race detector (if enabled) can detect330// unsafe mutations to the input.331c := make(chan reflect.Value)332go detectRaces(c, f, v)333got := <-c334want := f.Call([]reflect.Value{v})[0]335if step.vx, step.vy = got, want; !s.statelessCompare(step).Equal() {336// To avoid false-positives with non-reflexive equality operations,337// we sanity check whether a value is equal to itself.338if step.vx, step.vy = want, want; !s.statelessCompare(step).Equal() {339return want340}341panic(fmt.Sprintf("non-deterministic function detected: %s", function.NameOf(f)))342}343return want344}345346func (s *state) callTTBFunc(f, x, y reflect.Value) bool {347if !s.dynChecker.Next() {348return f.Call([]reflect.Value{x, y})[0].Bool()349}350351// Swapping the input arguments is sufficient to check that352// f is symmetric and deterministic.353// We run in goroutines so that the race detector (if enabled) can detect354// unsafe mutations to the input.355c := make(chan reflect.Value)356go detectRaces(c, f, y, x)357got := <-c358want := f.Call([]reflect.Value{x, y})[0].Bool()359if !got.IsValid() || got.Bool() != want {360panic(fmt.Sprintf("non-deterministic or non-symmetric function detected: %s", function.NameOf(f)))361}362return want363}364365func detectRaces(c chan<- reflect.Value, f reflect.Value, vs ...reflect.Value) {366var ret reflect.Value367defer func() {368recover() // Ignore panics, let the other call to f panic instead369c <- ret370}()371ret = f.Call(vs)[0]372}373374func (s *state) compareStruct(t reflect.Type, vx, vy reflect.Value) {375var addr bool376var vax, vay reflect.Value // Addressable versions of vx and vy377378var mayForce, mayForceInit bool379step := StructField{&structField{}}380for i := 0; i < t.NumField(); i++ {381step.typ = t.Field(i).Type382step.vx = vx.Field(i)383step.vy = vy.Field(i)384step.name = t.Field(i).Name385step.idx = i386step.unexported = !isExported(step.name)387if step.unexported {388if step.name == "_" {389continue390}391// Defer checking of unexported fields until later to give an392// Ignore a chance to ignore the field.393if !vax.IsValid() || !vay.IsValid() {394// For retrieveUnexportedField to work, the parent struct must395// be addressable. Create a new copy of the values if396// necessary to make them addressable.397addr = vx.CanAddr() || vy.CanAddr()398vax = makeAddressable(vx)399vay = makeAddressable(vy)400}401if !mayForceInit {402for _, xf := range s.exporters {403mayForce = mayForce || xf(t)404}405mayForceInit = true406}407step.mayForce = mayForce408step.paddr = addr409step.pvx = vax410step.pvy = vay411step.field = t.Field(i)412}413s.compareAny(step)414}415}416417func (s *state) compareSlice(t reflect.Type, vx, vy reflect.Value) {418isSlice := t.Kind() == reflect.Slice419if isSlice && (vx.IsNil() || vy.IsNil()) {420s.report(vx.IsNil() && vy.IsNil(), 0)421return422}423424// NOTE: It is incorrect to call curPtrs.Push on the slice header pointer425// since slices represents a list of pointers, rather than a single pointer.426// The pointer checking logic must be handled on a per-element basis427// in compareAny.428//429// A slice header (see reflect.SliceHeader) in Go is a tuple of a starting430// pointer P, a length N, and a capacity C. Supposing each slice element has431// a memory size of M, then the slice is equivalent to the list of pointers:432// [P+i*M for i in range(N)]433//434// For example, v[:0] and v[:1] are slices with the same starting pointer,435// but they are clearly different values. Using the slice pointer alone436// violates the assumption that equal pointers implies equal values.437438step := SliceIndex{&sliceIndex{pathStep: pathStep{typ: t.Elem()}, isSlice: isSlice}}439withIndexes := func(ix, iy int) SliceIndex {440if ix >= 0 {441step.vx, step.xkey = vx.Index(ix), ix442} else {443step.vx, step.xkey = reflect.Value{}, -1444}445if iy >= 0 {446step.vy, step.ykey = vy.Index(iy), iy447} else {448step.vy, step.ykey = reflect.Value{}, -1449}450return step451}452453// Ignore options are able to ignore missing elements in a slice.454// However, detecting these reliably requires an optimal differencing455// algorithm, for which diff.Difference is not.456//457// Instead, we first iterate through both slices to detect which elements458// would be ignored if standing alone. The index of non-discarded elements459// are stored in a separate slice, which diffing is then performed on.460var indexesX, indexesY []int461var ignoredX, ignoredY []bool462for ix := 0; ix < vx.Len(); ix++ {463ignored := s.statelessCompare(withIndexes(ix, -1)).NumDiff == 0464if !ignored {465indexesX = append(indexesX, ix)466}467ignoredX = append(ignoredX, ignored)468}469for iy := 0; iy < vy.Len(); iy++ {470ignored := s.statelessCompare(withIndexes(-1, iy)).NumDiff == 0471if !ignored {472indexesY = append(indexesY, iy)473}474ignoredY = append(ignoredY, ignored)475}476477// Compute an edit-script for slices vx and vy (excluding ignored elements).478edits := diff.Difference(len(indexesX), len(indexesY), func(ix, iy int) diff.Result {479return s.statelessCompare(withIndexes(indexesX[ix], indexesY[iy]))480})481482// Replay the ignore-scripts and the edit-script.483var ix, iy int484for ix < vx.Len() || iy < vy.Len() {485var e diff.EditType486switch {487case ix < len(ignoredX) && ignoredX[ix]:488e = diff.UniqueX489case iy < len(ignoredY) && ignoredY[iy]:490e = diff.UniqueY491default:492e, edits = edits[0], edits[1:]493}494switch e {495case diff.UniqueX:496s.compareAny(withIndexes(ix, -1))497ix++498case diff.UniqueY:499s.compareAny(withIndexes(-1, iy))500iy++501default:502s.compareAny(withIndexes(ix, iy))503ix++504iy++505}506}507}508509func (s *state) compareMap(t reflect.Type, vx, vy reflect.Value) {510if vx.IsNil() || vy.IsNil() {511s.report(vx.IsNil() && vy.IsNil(), 0)512return513}514515// Cycle-detection for maps.516if eq, visited := s.curPtrs.Push(vx, vy); visited {517s.report(eq, reportByCycle)518return519}520defer s.curPtrs.Pop(vx, vy)521522// We combine and sort the two map keys so that we can perform the523// comparisons in a deterministic order.524step := MapIndex{&mapIndex{pathStep: pathStep{typ: t.Elem()}}}525for _, k := range value.SortKeys(append(vx.MapKeys(), vy.MapKeys()...)) {526step.vx = vx.MapIndex(k)527step.vy = vy.MapIndex(k)528step.key = k529if !step.vx.IsValid() && !step.vy.IsValid() {530// It is possible for both vx and vy to be invalid if the531// key contained a NaN value in it.532//533// Even with the ability to retrieve NaN keys in Go 1.12,534// there still isn't a sensible way to compare the values since535// a NaN key may map to multiple unordered values.536// The most reasonable way to compare NaNs would be to compare the537// set of values. However, this is impossible to do efficiently538// since set equality is provably an O(n^2) operation given only539// an Equal function. If we had a Less function or Hash function,540// this could be done in O(n*log(n)) or O(n), respectively.541//542// Rather than adding complex logic to deal with NaNs, make it543// the user's responsibility to compare such obscure maps.544const help = "consider providing a Comparer to compare the map"545panic(fmt.Sprintf("%#v has map key with NaNs\n%s", s.curPath, help))546}547s.compareAny(step)548}549}550551func (s *state) comparePtr(t reflect.Type, vx, vy reflect.Value) {552if vx.IsNil() || vy.IsNil() {553s.report(vx.IsNil() && vy.IsNil(), 0)554return555}556557// Cycle-detection for pointers.558if eq, visited := s.curPtrs.Push(vx, vy); visited {559s.report(eq, reportByCycle)560return561}562defer s.curPtrs.Pop(vx, vy)563564vx, vy = vx.Elem(), vy.Elem()565s.compareAny(Indirect{&indirect{pathStep{t.Elem(), vx, vy}}})566}567568func (s *state) compareInterface(t reflect.Type, vx, vy reflect.Value) {569if vx.IsNil() || vy.IsNil() {570s.report(vx.IsNil() && vy.IsNil(), 0)571return572}573vx, vy = vx.Elem(), vy.Elem()574if vx.Type() != vy.Type() {575s.report(false, 0)576return577}578s.compareAny(TypeAssertion{&typeAssertion{pathStep{vx.Type(), vx, vy}}})579}580581func (s *state) report(eq bool, rf resultFlags) {582if rf&reportByIgnore == 0 {583if eq {584s.result.NumSame++585rf |= reportEqual586} else {587s.result.NumDiff++588rf |= reportUnequal589}590}591for _, r := range s.reporters {592r.Report(Result{flags: rf})593}594}595596// recChecker tracks the state needed to periodically perform checks that597// user provided transformers are not stuck in an infinitely recursive cycle.598type recChecker struct{ next int }599600// Check scans the Path for any recursive transformers and panics when any601// recursive transformers are detected. Note that the presence of a602// recursive Transformer does not necessarily imply an infinite cycle.603// As such, this check only activates after some minimal number of path steps.604func (rc *recChecker) Check(p Path) {605const minLen = 1 << 16606if rc.next == 0 {607rc.next = minLen608}609if len(p) < rc.next {610return611}612rc.next <<= 1613614// Check whether the same transformer has appeared at least twice.615var ss []string616m := map[Option]int{}617for _, ps := range p {618if t, ok := ps.(Transform); ok {619t := t.Option()620if m[t] == 1 { // Transformer was used exactly once before621tf := t.(*transformer).fnc.Type()622ss = append(ss, fmt.Sprintf("%v: %v => %v", t, tf.In(0), tf.Out(0)))623}624m[t]++625}626}627if len(ss) > 0 {628const warning = "recursive set of Transformers detected"629const help = "consider using cmpopts.AcyclicTransformer"630set := strings.Join(ss, "\n\t")631panic(fmt.Sprintf("%s:\n\t%s\n%s", warning, set, help))632}633}634635// dynChecker tracks the state needed to periodically perform checks that636// user provided functions are symmetric and deterministic.637// The zero value is safe for immediate use.638type dynChecker struct{ curr, next int }639640// Next increments the state and reports whether a check should be performed.641//642// Checks occur every Nth function call, where N is a triangular number:643//644// 0 1 3 6 10 15 21 28 36 45 55 66 78 91 105 120 136 153 171 190 ...645//646// See https://en.wikipedia.org/wiki/Triangular_number647//648// This sequence ensures that the cost of checks drops significantly as649// the number of functions calls grows larger.650func (dc *dynChecker) Next() bool {651ok := dc.curr == dc.next652if ok {653dc.curr = 0654dc.next++655}656dc.curr++657return ok658}659660// makeAddressable returns a value that is always addressable.661// It returns the input verbatim if it is already addressable,662// otherwise it creates a new value and returns an addressable copy.663func makeAddressable(v reflect.Value) reflect.Value {664if v.CanAddr() {665return v666}667vc := reflect.New(v.Type()).Elem()668vc.Set(v)669return vc670}671672673