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.
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 const 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
234 // Unnamed type with unexported fields. Derive PkgPath from field.
236 for i := 0; i < t.NumField() && pkgPath == ""; i++ {
237 pkgPath = t.Field(i).PkgPath
239 name = fmt.Sprintf("%q.(%v)", pkgPath, t.String()) // e.g., "path/to/package".(struct { a int })
241 panic(fmt.Sprintf("cannot handle unexported field at %#v:\n\t%v\n%s", s.curPath, name, help))
244 panic("not reachable")
247 // identRx represents a valid identifier according to the Go specification.
248 const identRx = `[_\p{L}][_\p{L}\p{N}]*`
250 var identsRx = regexp.MustCompile(`^` + identRx + `(\.` + identRx + `)*$`)
252 // Transformer returns an Option that applies a transformation function that
253 // converts values of a certain type into that of another.
255 // The transformer f must be a function "func(T) R" that converts values of
256 // type T to those of type R and is implicitly filtered to input values
257 // assignable to T. The transformer must not mutate T in any way.
259 // To help prevent some cases of infinite recursive cycles applying the
260 // same transform to the output of itself (e.g., in the case where the
261 // input and output types are the same), an implicit filter is added such that
262 // a transformer is applicable only if that exact transformer is not already
263 // in the tail of the Path since the last non-Transform step.
264 // For situations where the implicit filter is still insufficient,
265 // consider using cmpopts.AcyclicTransformer, which adds a filter
266 // to prevent the transformer from being recursively applied upon itself.
268 // The name is a user provided label that is used as the Transform.Name in the
269 // transformation PathStep (and eventually shown in the Diff output).
270 // The name must be a valid identifier or qualified identifier in Go syntax.
271 // If empty, an arbitrary name is used.
272 func Transformer(name string, f interface{}) Option {
273 v := reflect.ValueOf(f)
274 if !function.IsType(v.Type(), function.Transformer) || v.IsNil() {
275 panic(fmt.Sprintf("invalid transformer function: %T", f))
278 name = function.NameOf(v)
279 if !identsRx.MatchString(name) {
280 name = "λ" // Lambda-symbol as placeholder name
282 } else if !identsRx.MatchString(name) {
283 panic(fmt.Sprintf("invalid name: %q", name))
285 tr := &transformer{name: name, fnc: reflect.ValueOf(f)}
286 if ti := v.Type().In(0); ti.Kind() != reflect.Interface || ti.NumMethod() > 0 {
292 type transformer struct {
295 typ reflect.Type // T
296 fnc reflect.Value // func(T) R
299 func (tr *transformer) isFiltered() bool { return tr.typ != nil }
301 func (tr *transformer) filter(s *state, t reflect.Type, _, _ reflect.Value) applicableOption {
302 for i := len(s.curPath) - 1; i >= 0; i-- {
303 if t, ok := s.curPath[i].(Transform); !ok {
304 break // Hit most recent non-Transform step
305 } else if tr == t.trans {
306 return nil // Cannot directly use same Transform
309 if tr.typ == nil || t.AssignableTo(tr.typ) {
315 func (tr *transformer) apply(s *state, vx, vy reflect.Value) {
316 step := Transform{&transform{pathStep{typ: tr.fnc.Type().Out(0)}, tr}}
317 vvx := s.callTRFunc(tr.fnc, vx, step)
318 vvy := s.callTRFunc(tr.fnc, vy, step)
319 step.vx, step.vy = vvx, vvy
323 func (tr transformer) String() string {
324 return fmt.Sprintf("Transformer(%s, %s)", tr.name, function.NameOf(tr.fnc))
327 // Comparer returns an Option that determines whether two values are equal
330 // The comparer f must be a function "func(T, T) bool" and is implicitly
331 // filtered to input values assignable to T. If T is an interface, it is
332 // possible that f is called with two values of different concrete types that
335 // The equality function must be:
336 // • Symmetric: equal(x, y) == equal(y, x)
337 // • Deterministic: equal(x, y) == equal(x, y)
338 // • Pure: equal(x, y) does not modify x or y
339 func Comparer(f interface{}) Option {
340 v := reflect.ValueOf(f)
341 if !function.IsType(v.Type(), function.Equal) || v.IsNil() {
342 panic(fmt.Sprintf("invalid comparer function: %T", f))
344 cm := &comparer{fnc: v}
345 if ti := v.Type().In(0); ti.Kind() != reflect.Interface || ti.NumMethod() > 0 {
351 type comparer struct {
353 typ reflect.Type // T
354 fnc reflect.Value // func(T, T) bool
357 func (cm *comparer) isFiltered() bool { return cm.typ != nil }
359 func (cm *comparer) filter(_ *state, t reflect.Type, _, _ reflect.Value) applicableOption {
360 if cm.typ == nil || t.AssignableTo(cm.typ) {
366 func (cm *comparer) apply(s *state, vx, vy reflect.Value) {
367 eq := s.callTTBFunc(cm.fnc, vx, vy)
368 s.report(eq, reportByFunc)
371 func (cm comparer) String() string {
372 return fmt.Sprintf("Comparer(%s)", function.NameOf(cm.fnc))
375 // Exporter returns an Option that specifies whether Equal is allowed to
376 // introspect into the unexported fields of certain struct types.
378 // Users of this option must understand that comparing on unexported fields
379 // from external packages is not safe since changes in the internal
380 // implementation of some external package may cause the result of Equal
381 // to unexpectedly change. However, it may be valid to use this option on types
382 // defined in an internal package where the semantic meaning of an unexported
383 // field is in the control of the user.
385 // In many cases, a custom Comparer should be used instead that defines
386 // equality as a function of the public API of a type rather than the underlying
387 // unexported implementation.
389 // For example, the reflect.Type documentation defines equality to be determined
390 // by the == operator on the interface (essentially performing a shallow pointer
391 // comparison) and most attempts to compare *regexp.Regexp types are interested
392 // in only checking that the regular expression strings are equal.
393 // Both of these are accomplished using Comparers:
395 // Comparer(func(x, y reflect.Type) bool { return x == y })
396 // Comparer(func(x, y *regexp.Regexp) bool { return x.String() == y.String() })
398 // In other cases, the cmpopts.IgnoreUnexported option can be used to ignore
399 // all unexported fields on specified struct types.
400 func Exporter(f func(reflect.Type) bool) Option {
401 if !supportExporters {
402 panic("Exporter is not supported on purego builds")
407 type exporter func(reflect.Type) bool
409 func (exporter) filter(_ *state, _ reflect.Type, _, _ reflect.Value) applicableOption {
410 panic("not implemented")
413 // AllowUnexported returns an Options that allows Equal to forcibly introspect
414 // unexported fields of the specified struct types.
416 // See Exporter for the proper use of this option.
417 func AllowUnexported(types ...interface{}) Option {
418 m := make(map[reflect.Type]bool)
419 for _, typ := range types {
420 t := reflect.TypeOf(typ)
421 if t.Kind() != reflect.Struct {
422 panic(fmt.Sprintf("invalid struct type: %T", typ))
426 return exporter(func(t reflect.Type) bool { return m[t] })
429 // Result represents the comparison result for a single node and
430 // is provided by cmp when calling Result (see Reporter).
432 _ [0]func() // Make Result incomparable
436 // Equal reports whether the node was determined to be equal or not.
437 // As a special case, ignored nodes are considered equal.
438 func (r Result) Equal() bool {
439 return r.flags&(reportEqual|reportByIgnore) != 0
442 // ByIgnore reports whether the node is equal because it was ignored.
443 // This never reports true if Equal reports false.
444 func (r Result) ByIgnore() bool {
445 return r.flags&reportByIgnore != 0
448 // ByMethod reports whether the Equal method determined equality.
449 func (r Result) ByMethod() bool {
450 return r.flags&reportByMethod != 0
453 // ByFunc reports whether a Comparer function determined equality.
454 func (r Result) ByFunc() bool {
455 return r.flags&reportByFunc != 0
458 // ByCycle reports whether a reference cycle was detected.
459 func (r Result) ByCycle() bool {
460 return r.flags&reportByCycle != 0
463 type resultFlags uint
466 _ resultFlags = (1 << iota) / 2
476 // Reporter is an Option that can be passed to Equal. When Equal traverses
477 // the value trees, it calls PushStep as it descends into each node in the
478 // tree and PopStep as it ascend out of the node. The leaves of the tree are
479 // either compared (determined to be equal or not equal) or ignored and reported
480 // as such by calling the Report method.
481 func Reporter(r interface {
482 // PushStep is called when a tree-traversal operation is performed.
483 // The PathStep itself is only valid until the step is popped.
484 // The PathStep.Values are valid for the duration of the entire traversal
485 // and must not be mutated.
487 // Equal always calls PushStep at the start to provide an operation-less
488 // PathStep used to report the root values.
490 // Within a slice, the exact set of inserted, removed, or modified elements
491 // is unspecified and may change in future implementations.
492 // The entries of a map are iterated through in an unspecified order.
495 // Report is called exactly once on leaf nodes to report whether the
496 // comparison identified the node as equal, unequal, or ignored.
497 // A leaf node is one that is immediately preceded by and followed by
498 // a pair of PushStep and PopStep calls.
501 // PopStep ascends back up the value tree.
502 // There is always a matching pop call for every push call.
508 type reporter struct{ reporterIface }
509 type reporterIface interface {
515 func (reporter) filter(_ *state, _ reflect.Type, _, _ reflect.Value) applicableOption {
516 panic("not implemented")
519 // normalizeOption normalizes the input options such that all Options groups
520 // are flattened and groups with a single element are reduced to that element.
521 // Only coreOptions and Options containing coreOptions are allowed.
522 func normalizeOption(src Option) Option {
523 switch opts := flattenOptions(nil, Options{src}); len(opts) {
533 // flattenOptions copies all options in src to dst as a flat list.
534 // Only coreOptions and Options containing coreOptions are allowed.
535 func flattenOptions(dst, src Options) Options {
536 for _, opt := range src {
537 switch opt := opt.(type) {
541 dst = flattenOptions(dst, opt)
543 dst = append(dst, opt)
545 panic(fmt.Sprintf("invalid option type: %T", opt))