1 // Copyright 2017, The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
13 "github.com/google/go-cmp/cmp/internal/function"
16 // Option configures for specific behavior of Equal and Diff. In particular,
17 // the fundamental Option functions (Ignore, Transformer, and Comparer),
18 // configure how equality is determined.
20 // The fundamental options may be composed with filters (FilterPath and
21 // FilterValues) to control the scope over which they are applied.
23 // The cmp/cmpopts package provides helper functions for creating options that
24 // may be used with Equal and Diff.
25 type Option interface {
26 // filter applies all filters and returns the option that remains.
27 // Each option may only read s.curPath and call s.callTTBFunc.
29 // An Options is returned only if multiple comparers or transformers
30 // can apply simultaneously and will only contain values of those types
31 // or sub-Options containing values of those types.
32 filter(s *state, t reflect.Type, vx, vy reflect.Value) applicableOption
35 // applicableOption represents the following types:
36 // Fundamental: ignore | validator | *comparer | *transformer
38 type applicableOption interface {
41 // apply executes the option, which may mutate s or panic.
42 apply(s *state, vx, vy reflect.Value)
45 // coreOption represents the following types:
46 // Fundamental: ignore | validator | *comparer | *transformer
47 // Filters: *pathFilter | *valuesFilter
48 type coreOption interface {
55 func (core) isCore() {}
57 // Options is a list of Option values that also satisfies the Option interface.
58 // Helper comparison packages may return an Options value when packing multiple
59 // Option values into a single Option. When this package processes an Options,
60 // it will be implicitly expanded into a flat list.
62 // Applying a filter on an Options is equivalent to applying that same filter
63 // on all individual options held within.
66 func (opts Options) filter(s *state, t reflect.Type, vx, vy reflect.Value) (out applicableOption) {
67 for _, opt := range opts {
68 switch opt := opt.filter(s, t, vx, vy); opt.(type) {
70 return ignore{} // Only ignore can short-circuit evaluation
72 out = validator{} // Takes precedence over comparer or transformer
73 case *comparer, *transformer, Options:
79 case *comparer, *transformer, Options:
80 out = Options{out, opt} // Conflicting comparers or transformers
87 func (opts Options) apply(s *state, _, _ reflect.Value) {
88 const warning = "ambiguous set of applicable options"
89 const help = "consider using filters to ensure at most one Comparer or Transformer may apply"
91 for _, opt := range flattenOptions(nil, opts) {
92 ss = append(ss, fmt.Sprint(opt))
94 set := strings.Join(ss, "\n\t")
95 panic(fmt.Sprintf("%s at %#v:\n\t%s\n%s", warning, s.curPath, set, help))
98 func (opts Options) String() string {
100 for _, opt := range opts {
101 ss = append(ss, fmt.Sprint(opt))
103 return fmt.Sprintf("Options{%s}", strings.Join(ss, ", "))
106 // FilterPath returns a new Option where opt is only evaluated if filter f
107 // returns true for the current Path in the value tree.
109 // This filter is called even if a slice element or map entry is missing and
110 // provides an opportunity to ignore such cases. The filter function must be
111 // symmetric such that the filter result is identical regardless of whether the
112 // missing value is from x or y.
114 // The option passed in may be an Ignore, Transformer, Comparer, Options, or
115 // a previously filtered Option.
116 func FilterPath(f func(Path) bool, opt Option) Option {
118 panic("invalid path filter function")
120 if opt := normalizeOption(opt); opt != nil {
121 return &pathFilter{fnc: f, opt: opt}
126 type pathFilter struct {
132 func (f pathFilter) filter(s *state, t reflect.Type, vx, vy reflect.Value) applicableOption {
133 if f.fnc(s.curPath) {
134 return f.opt.filter(s, t, vx, vy)
139 func (f pathFilter) String() string {
140 return fmt.Sprintf("FilterPath(%s, %v)", function.NameOf(reflect.ValueOf(f.fnc)), f.opt)
143 // FilterValues returns a new Option where opt is only evaluated if filter f,
144 // which is a function of the form "func(T, T) bool", returns true for the
145 // current pair of values being compared. If either value is invalid or
146 // the type of the values is not assignable to T, then this filter implicitly
149 // The filter function must be
150 // symmetric (i.e., agnostic to the order of the inputs) and
151 // deterministic (i.e., produces the same result when given the same inputs).
152 // If T is an interface, it is possible that f is called with two values with
153 // different concrete types that both implement T.
155 // The option passed in may be an Ignore, Transformer, Comparer, Options, or
156 // a previously filtered Option.
157 func FilterValues(f interface{}, opt Option) Option {
158 v := reflect.ValueOf(f)
159 if !function.IsType(v.Type(), function.ValueFilter) || v.IsNil() {
160 panic(fmt.Sprintf("invalid values filter function: %T", f))
162 if opt := normalizeOption(opt); opt != nil {
163 vf := &valuesFilter{fnc: v, opt: opt}
164 if ti := v.Type().In(0); ti.Kind() != reflect.Interface || ti.NumMethod() > 0 {
172 type valuesFilter struct {
174 typ reflect.Type // T
175 fnc reflect.Value // func(T, T) bool
179 func (f valuesFilter) filter(s *state, t reflect.Type, vx, vy reflect.Value) applicableOption {
180 if !vx.IsValid() || !vx.CanInterface() || !vy.IsValid() || !vy.CanInterface() {
183 if (f.typ == nil || t.AssignableTo(f.typ)) && s.callTTBFunc(f.fnc, vx, vy) {
184 return f.opt.filter(s, t, vx, vy)
189 func (f valuesFilter) String() string {
190 return fmt.Sprintf("FilterValues(%s, %v)", function.NameOf(f.fnc), f.opt)
193 // Ignore is an Option that causes all comparisons to be ignored.
194 // This value is intended to be combined with FilterPath or FilterValues.
195 // It is an error to pass an unfiltered Ignore option to Equal.
196 func Ignore() Option { return ignore{} }
198 type ignore struct{ core }
200 func (ignore) isFiltered() bool { return false }
201 func (ignore) filter(_ *state, _ reflect.Type, _, _ reflect.Value) applicableOption { return ignore{} }
202 func (ignore) apply(s *state, _, _ reflect.Value) { s.report(true, reportByIgnore) }
203 func (ignore) String() string { return "Ignore()" }
205 // validator is a sentinel Option type to indicate that some options could not
206 // be evaluated due to unexported fields, missing slice elements, or
207 // missing map entries. Both values are validator only for unexported fields.
208 type validator struct{ core }
210 func (validator) filter(_ *state, _ reflect.Type, vx, vy reflect.Value) applicableOption {
211 if !vx.IsValid() || !vy.IsValid() {
214 if !vx.CanInterface() || !vy.CanInterface() {
219 func (validator) apply(s *state, vx, vy reflect.Value) {
220 // Implies missing slice element or map entry.
221 if !vx.IsValid() || !vy.IsValid() {
222 s.report(vx.IsValid() == vy.IsValid(), 0)
226 // Unable to Interface implies unexported field without visibility access.
227 if !vx.CanInterface() || !vy.CanInterface() {
228 help := "consider using a custom Comparer; if you control the implementation of type, you can also consider using an Exporter, AllowUnexported, or cmpopts.IgnoreUnexported"
230 if t := s.curPath.Index(-2).Type(); t.Name() != "" {
231 // Named type with unexported fields.
232 name = fmt.Sprintf("%q.%v", t.PkgPath(), t.Name()) // e.g., "path/to/package".MyType
233 if _, ok := reflect.New(t).Interface().(error); ok {
234 help = "consider using cmpopts.EquateErrors to compare error values"
237 // Unnamed type with unexported fields. Derive PkgPath from field.
239 for i := 0; i < t.NumField() && pkgPath == ""; i++ {
240 pkgPath = t.Field(i).PkgPath
242 name = fmt.Sprintf("%q.(%v)", pkgPath, t.String()) // e.g., "path/to/package".(struct { a int })
244 panic(fmt.Sprintf("cannot handle unexported field at %#v:\n\t%v\n%s", s.curPath, name, help))
247 panic("not reachable")
250 // identRx represents a valid identifier according to the Go specification.
251 const identRx = `[_\p{L}][_\p{L}\p{N}]*`
253 var identsRx = regexp.MustCompile(`^` + identRx + `(\.` + identRx + `)*$`)
255 // Transformer returns an Option that applies a transformation function that
256 // converts values of a certain type into that of another.
258 // The transformer f must be a function "func(T) R" that converts values of
259 // type T to those of type R and is implicitly filtered to input values
260 // assignable to T. The transformer must not mutate T in any way.
262 // To help prevent some cases of infinite recursive cycles applying the
263 // same transform to the output of itself (e.g., in the case where the
264 // input and output types are the same), an implicit filter is added such that
265 // a transformer is applicable only if that exact transformer is not already
266 // in the tail of the Path since the last non-Transform step.
267 // For situations where the implicit filter is still insufficient,
268 // consider using cmpopts.AcyclicTransformer, which adds a filter
269 // to prevent the transformer from being recursively applied upon itself.
271 // The name is a user provided label that is used as the Transform.Name in the
272 // transformation PathStep (and eventually shown in the Diff output).
273 // The name must be a valid identifier or qualified identifier in Go syntax.
274 // If empty, an arbitrary name is used.
275 func Transformer(name string, f interface{}) Option {
276 v := reflect.ValueOf(f)
277 if !function.IsType(v.Type(), function.Transformer) || v.IsNil() {
278 panic(fmt.Sprintf("invalid transformer function: %T", f))
281 name = function.NameOf(v)
282 if !identsRx.MatchString(name) {
283 name = "λ" // Lambda-symbol as placeholder name
285 } else if !identsRx.MatchString(name) {
286 panic(fmt.Sprintf("invalid name: %q", name))
288 tr := &transformer{name: name, fnc: reflect.ValueOf(f)}
289 if ti := v.Type().In(0); ti.Kind() != reflect.Interface || ti.NumMethod() > 0 {
295 type transformer struct {
298 typ reflect.Type // T
299 fnc reflect.Value // func(T) R
302 func (tr *transformer) isFiltered() bool { return tr.typ != nil }
304 func (tr *transformer) filter(s *state, t reflect.Type, _, _ reflect.Value) applicableOption {
305 for i := len(s.curPath) - 1; i >= 0; i-- {
306 if t, ok := s.curPath[i].(Transform); !ok {
307 break // Hit most recent non-Transform step
308 } else if tr == t.trans {
309 return nil // Cannot directly use same Transform
312 if tr.typ == nil || t.AssignableTo(tr.typ) {
318 func (tr *transformer) apply(s *state, vx, vy reflect.Value) {
319 step := Transform{&transform{pathStep{typ: tr.fnc.Type().Out(0)}, tr}}
320 vvx := s.callTRFunc(tr.fnc, vx, step)
321 vvy := s.callTRFunc(tr.fnc, vy, step)
322 step.vx, step.vy = vvx, vvy
326 func (tr transformer) String() string {
327 return fmt.Sprintf("Transformer(%s, %s)", tr.name, function.NameOf(tr.fnc))
330 // Comparer returns an Option that determines whether two values are equal
333 // The comparer f must be a function "func(T, T) bool" and is implicitly
334 // filtered to input values assignable to T. If T is an interface, it is
335 // possible that f is called with two values of different concrete types that
338 // The equality function must be:
339 // • Symmetric: equal(x, y) == equal(y, x)
340 // • Deterministic: equal(x, y) == equal(x, y)
341 // • Pure: equal(x, y) does not modify x or y
342 func Comparer(f interface{}) Option {
343 v := reflect.ValueOf(f)
344 if !function.IsType(v.Type(), function.Equal) || v.IsNil() {
345 panic(fmt.Sprintf("invalid comparer function: %T", f))
347 cm := &comparer{fnc: v}
348 if ti := v.Type().In(0); ti.Kind() != reflect.Interface || ti.NumMethod() > 0 {
354 type comparer struct {
356 typ reflect.Type // T
357 fnc reflect.Value // func(T, T) bool
360 func (cm *comparer) isFiltered() bool { return cm.typ != nil }
362 func (cm *comparer) filter(_ *state, t reflect.Type, _, _ reflect.Value) applicableOption {
363 if cm.typ == nil || t.AssignableTo(cm.typ) {
369 func (cm *comparer) apply(s *state, vx, vy reflect.Value) {
370 eq := s.callTTBFunc(cm.fnc, vx, vy)
371 s.report(eq, reportByFunc)
374 func (cm comparer) String() string {
375 return fmt.Sprintf("Comparer(%s)", function.NameOf(cm.fnc))
378 // Exporter returns an Option that specifies whether Equal is allowed to
379 // introspect into the unexported fields of certain struct types.
381 // Users of this option must understand that comparing on unexported fields
382 // from external packages is not safe since changes in the internal
383 // implementation of some external package may cause the result of Equal
384 // to unexpectedly change. However, it may be valid to use this option on types
385 // defined in an internal package where the semantic meaning of an unexported
386 // field is in the control of the user.
388 // In many cases, a custom Comparer should be used instead that defines
389 // equality as a function of the public API of a type rather than the underlying
390 // unexported implementation.
392 // For example, the reflect.Type documentation defines equality to be determined
393 // by the == operator on the interface (essentially performing a shallow pointer
394 // comparison) and most attempts to compare *regexp.Regexp types are interested
395 // in only checking that the regular expression strings are equal.
396 // Both of these are accomplished using Comparers:
398 // Comparer(func(x, y reflect.Type) bool { return x == y })
399 // Comparer(func(x, y *regexp.Regexp) bool { return x.String() == y.String() })
401 // In other cases, the cmpopts.IgnoreUnexported option can be used to ignore
402 // all unexported fields on specified struct types.
403 func Exporter(f func(reflect.Type) bool) Option {
404 if !supportExporters {
405 panic("Exporter is not supported on purego builds")
410 type exporter func(reflect.Type) bool
412 func (exporter) filter(_ *state, _ reflect.Type, _, _ reflect.Value) applicableOption {
413 panic("not implemented")
416 // AllowUnexported returns an Options that allows Equal to forcibly introspect
417 // unexported fields of the specified struct types.
419 // See Exporter for the proper use of this option.
420 func AllowUnexported(types ...interface{}) Option {
421 m := make(map[reflect.Type]bool)
422 for _, typ := range types {
423 t := reflect.TypeOf(typ)
424 if t.Kind() != reflect.Struct {
425 panic(fmt.Sprintf("invalid struct type: %T", typ))
429 return exporter(func(t reflect.Type) bool { return m[t] })
432 // Result represents the comparison result for a single node and
433 // is provided by cmp when calling Result (see Reporter).
435 _ [0]func() // Make Result incomparable
439 // Equal reports whether the node was determined to be equal or not.
440 // As a special case, ignored nodes are considered equal.
441 func (r Result) Equal() bool {
442 return r.flags&(reportEqual|reportByIgnore) != 0
445 // ByIgnore reports whether the node is equal because it was ignored.
446 // This never reports true if Equal reports false.
447 func (r Result) ByIgnore() bool {
448 return r.flags&reportByIgnore != 0
451 // ByMethod reports whether the Equal method determined equality.
452 func (r Result) ByMethod() bool {
453 return r.flags&reportByMethod != 0
456 // ByFunc reports whether a Comparer function determined equality.
457 func (r Result) ByFunc() bool {
458 return r.flags&reportByFunc != 0
461 // ByCycle reports whether a reference cycle was detected.
462 func (r Result) ByCycle() bool {
463 return r.flags&reportByCycle != 0
466 type resultFlags uint
469 _ resultFlags = (1 << iota) / 2
479 // Reporter is an Option that can be passed to Equal. When Equal traverses
480 // the value trees, it calls PushStep as it descends into each node in the
481 // tree and PopStep as it ascend out of the node. The leaves of the tree are
482 // either compared (determined to be equal or not equal) or ignored and reported
483 // as such by calling the Report method.
484 func Reporter(r interface {
485 // PushStep is called when a tree-traversal operation is performed.
486 // The PathStep itself is only valid until the step is popped.
487 // The PathStep.Values are valid for the duration of the entire traversal
488 // and must not be mutated.
490 // Equal always calls PushStep at the start to provide an operation-less
491 // PathStep used to report the root values.
493 // Within a slice, the exact set of inserted, removed, or modified elements
494 // is unspecified and may change in future implementations.
495 // The entries of a map are iterated through in an unspecified order.
498 // Report is called exactly once on leaf nodes to report whether the
499 // comparison identified the node as equal, unequal, or ignored.
500 // A leaf node is one that is immediately preceded by and followed by
501 // a pair of PushStep and PopStep calls.
504 // PopStep ascends back up the value tree.
505 // There is always a matching pop call for every push call.
511 type reporter struct{ reporterIface }
512 type reporterIface interface {
518 func (reporter) filter(_ *state, _ reflect.Type, _, _ reflect.Value) applicableOption {
519 panic("not implemented")
522 // normalizeOption normalizes the input options such that all Options groups
523 // are flattened and groups with a single element are reduced to that element.
524 // Only coreOptions and Options containing coreOptions are allowed.
525 func normalizeOption(src Option) Option {
526 switch opts := flattenOptions(nil, Options{src}); len(opts) {
536 // flattenOptions copies all options in src to dst as a flat list.
537 // Only coreOptions and Options containing coreOptions are allowed.
538 func flattenOptions(dst, src Options) Options {
539 for _, opt := range src {
540 switch opt := opt.(type) {
544 dst = flattenOptions(dst, opt)
546 dst = append(dst, opt)
548 panic(fmt.Sprintf("invalid option type: %T", opt))