options.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549
  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. package cmp
  5. import (
  6. "fmt"
  7. "reflect"
  8. "regexp"
  9. "strings"
  10. "github.com/google/go-cmp/cmp/internal/function"
  11. )
  12. // Option configures for specific behavior of Equal and Diff. In particular,
  13. // the fundamental Option functions (Ignore, Transformer, and Comparer),
  14. // configure how equality is determined.
  15. //
  16. // The fundamental options may be composed with filters (FilterPath and
  17. // FilterValues) to control the scope over which they are applied.
  18. //
  19. // The cmp/cmpopts package provides helper functions for creating options that
  20. // may be used with Equal and Diff.
  21. type Option interface {
  22. // filter applies all filters and returns the option that remains.
  23. // Each option may only read s.curPath and call s.callTTBFunc.
  24. //
  25. // An Options is returned only if multiple comparers or transformers
  26. // can apply simultaneously and will only contain values of those types
  27. // or sub-Options containing values of those types.
  28. filter(s *state, t reflect.Type, vx, vy reflect.Value) applicableOption
  29. }
  30. // applicableOption represents the following types:
  31. // Fundamental: ignore | validator | *comparer | *transformer
  32. // Grouping: Options
  33. type applicableOption interface {
  34. Option
  35. // apply executes the option, which may mutate s or panic.
  36. apply(s *state, vx, vy reflect.Value)
  37. }
  38. // coreOption represents the following types:
  39. // Fundamental: ignore | validator | *comparer | *transformer
  40. // Filters: *pathFilter | *valuesFilter
  41. type coreOption interface {
  42. Option
  43. isCore()
  44. }
  45. type core struct{}
  46. func (core) isCore() {}
  47. // Options is a list of Option values that also satisfies the Option interface.
  48. // Helper comparison packages may return an Options value when packing multiple
  49. // Option values into a single Option. When this package processes an Options,
  50. // it will be implicitly expanded into a flat list.
  51. //
  52. // Applying a filter on an Options is equivalent to applying that same filter
  53. // on all individual options held within.
  54. type Options []Option
  55. func (opts Options) filter(s *state, t reflect.Type, vx, vy reflect.Value) (out applicableOption) {
  56. for _, opt := range opts {
  57. switch opt := opt.filter(s, t, vx, vy); opt.(type) {
  58. case ignore:
  59. return ignore{} // Only ignore can short-circuit evaluation
  60. case validator:
  61. out = validator{} // Takes precedence over comparer or transformer
  62. case *comparer, *transformer, Options:
  63. switch out.(type) {
  64. case nil:
  65. out = opt
  66. case validator:
  67. // Keep validator
  68. case *comparer, *transformer, Options:
  69. out = Options{out, opt} // Conflicting comparers or transformers
  70. }
  71. }
  72. }
  73. return out
  74. }
  75. func (opts Options) apply(s *state, _, _ reflect.Value) {
  76. const warning = "ambiguous set of applicable options"
  77. const help = "consider using filters to ensure at most one Comparer or Transformer may apply"
  78. var ss []string
  79. for _, opt := range flattenOptions(nil, opts) {
  80. ss = append(ss, fmt.Sprint(opt))
  81. }
  82. set := strings.Join(ss, "\n\t")
  83. panic(fmt.Sprintf("%s at %#v:\n\t%s\n%s", warning, s.curPath, set, help))
  84. }
  85. func (opts Options) String() string {
  86. var ss []string
  87. for _, opt := range opts {
  88. ss = append(ss, fmt.Sprint(opt))
  89. }
  90. return fmt.Sprintf("Options{%s}", strings.Join(ss, ", "))
  91. }
  92. // FilterPath returns a new Option where opt is only evaluated if filter f
  93. // returns true for the current Path in the value tree.
  94. //
  95. // This filter is called even if a slice element or map entry is missing and
  96. // provides an opportunity to ignore such cases. The filter function must be
  97. // symmetric such that the filter result is identical regardless of whether the
  98. // missing value is from x or y.
  99. //
  100. // The option passed in may be an Ignore, Transformer, Comparer, Options, or
  101. // a previously filtered Option.
  102. func FilterPath(f func(Path) bool, opt Option) Option {
  103. if f == nil {
  104. panic("invalid path filter function")
  105. }
  106. if opt := normalizeOption(opt); opt != nil {
  107. return &pathFilter{fnc: f, opt: opt}
  108. }
  109. return nil
  110. }
  111. type pathFilter struct {
  112. core
  113. fnc func(Path) bool
  114. opt Option
  115. }
  116. func (f pathFilter) filter(s *state, t reflect.Type, vx, vy reflect.Value) applicableOption {
  117. if f.fnc(s.curPath) {
  118. return f.opt.filter(s, t, vx, vy)
  119. }
  120. return nil
  121. }
  122. func (f pathFilter) String() string {
  123. return fmt.Sprintf("FilterPath(%s, %v)", function.NameOf(reflect.ValueOf(f.fnc)), f.opt)
  124. }
  125. // FilterValues returns a new Option where opt is only evaluated if filter f,
  126. // which is a function of the form "func(T, T) bool", returns true for the
  127. // current pair of values being compared. If either value is invalid or
  128. // the type of the values is not assignable to T, then this filter implicitly
  129. // returns false.
  130. //
  131. // The filter function must be
  132. // symmetric (i.e., agnostic to the order of the inputs) and
  133. // deterministic (i.e., produces the same result when given the same inputs).
  134. // If T is an interface, it is possible that f is called with two values with
  135. // different concrete types that both implement T.
  136. //
  137. // The option passed in may be an Ignore, Transformer, Comparer, Options, or
  138. // a previously filtered Option.
  139. func FilterValues(f interface{}, opt Option) Option {
  140. v := reflect.ValueOf(f)
  141. if !function.IsType(v.Type(), function.ValueFilter) || v.IsNil() {
  142. panic(fmt.Sprintf("invalid values filter function: %T", f))
  143. }
  144. if opt := normalizeOption(opt); opt != nil {
  145. vf := &valuesFilter{fnc: v, opt: opt}
  146. if ti := v.Type().In(0); ti.Kind() != reflect.Interface || ti.NumMethod() > 0 {
  147. vf.typ = ti
  148. }
  149. return vf
  150. }
  151. return nil
  152. }
  153. type valuesFilter struct {
  154. core
  155. typ reflect.Type // T
  156. fnc reflect.Value // func(T, T) bool
  157. opt Option
  158. }
  159. func (f valuesFilter) filter(s *state, t reflect.Type, vx, vy reflect.Value) applicableOption {
  160. if !vx.IsValid() || !vx.CanInterface() || !vy.IsValid() || !vy.CanInterface() {
  161. return nil
  162. }
  163. if (f.typ == nil || t.AssignableTo(f.typ)) && s.callTTBFunc(f.fnc, vx, vy) {
  164. return f.opt.filter(s, t, vx, vy)
  165. }
  166. return nil
  167. }
  168. func (f valuesFilter) String() string {
  169. return fmt.Sprintf("FilterValues(%s, %v)", function.NameOf(f.fnc), f.opt)
  170. }
  171. // Ignore is an Option that causes all comparisons to be ignored.
  172. // This value is intended to be combined with FilterPath or FilterValues.
  173. // It is an error to pass an unfiltered Ignore option to Equal.
  174. func Ignore() Option { return ignore{} }
  175. type ignore struct{ core }
  176. func (ignore) isFiltered() bool { return false }
  177. func (ignore) filter(_ *state, _ reflect.Type, _, _ reflect.Value) applicableOption { return ignore{} }
  178. func (ignore) apply(s *state, _, _ reflect.Value) { s.report(true, reportByIgnore) }
  179. func (ignore) String() string { return "Ignore()" }
  180. // validator is a sentinel Option type to indicate that some options could not
  181. // be evaluated due to unexported fields, missing slice elements, or
  182. // missing map entries. Both values are validator only for unexported fields.
  183. type validator struct{ core }
  184. func (validator) filter(_ *state, _ reflect.Type, vx, vy reflect.Value) applicableOption {
  185. if !vx.IsValid() || !vy.IsValid() {
  186. return validator{}
  187. }
  188. if !vx.CanInterface() || !vy.CanInterface() {
  189. return validator{}
  190. }
  191. return nil
  192. }
  193. func (validator) apply(s *state, vx, vy reflect.Value) {
  194. // Implies missing slice element or map entry.
  195. if !vx.IsValid() || !vy.IsValid() {
  196. s.report(vx.IsValid() == vy.IsValid(), 0)
  197. return
  198. }
  199. // Unable to Interface implies unexported field without visibility access.
  200. if !vx.CanInterface() || !vy.CanInterface() {
  201. 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"
  202. var name string
  203. if t := s.curPath.Index(-2).Type(); t.Name() != "" {
  204. // Named type with unexported fields.
  205. name = fmt.Sprintf("%q.%v", t.PkgPath(), t.Name()) // e.g., "path/to/package".MyType
  206. } else {
  207. // Unnamed type with unexported fields. Derive PkgPath from field.
  208. var pkgPath string
  209. for i := 0; i < t.NumField() && pkgPath == ""; i++ {
  210. pkgPath = t.Field(i).PkgPath
  211. }
  212. name = fmt.Sprintf("%q.(%v)", pkgPath, t.String()) // e.g., "path/to/package".(struct { a int })
  213. }
  214. panic(fmt.Sprintf("cannot handle unexported field at %#v:\n\t%v\n%s", s.curPath, name, help))
  215. }
  216. panic("not reachable")
  217. }
  218. // identRx represents a valid identifier according to the Go specification.
  219. const identRx = `[_\p{L}][_\p{L}\p{N}]*`
  220. var identsRx = regexp.MustCompile(`^` + identRx + `(\.` + identRx + `)*$`)
  221. // Transformer returns an Option that applies a transformation function that
  222. // converts values of a certain type into that of another.
  223. //
  224. // The transformer f must be a function "func(T) R" that converts values of
  225. // type T to those of type R and is implicitly filtered to input values
  226. // assignable to T. The transformer must not mutate T in any way.
  227. //
  228. // To help prevent some cases of infinite recursive cycles applying the
  229. // same transform to the output of itself (e.g., in the case where the
  230. // input and output types are the same), an implicit filter is added such that
  231. // a transformer is applicable only if that exact transformer is not already
  232. // in the tail of the Path since the last non-Transform step.
  233. // For situations where the implicit filter is still insufficient,
  234. // consider using cmpopts.AcyclicTransformer, which adds a filter
  235. // to prevent the transformer from being recursively applied upon itself.
  236. //
  237. // The name is a user provided label that is used as the Transform.Name in the
  238. // transformation PathStep (and eventually shown in the Diff output).
  239. // The name must be a valid identifier or qualified identifier in Go syntax.
  240. // If empty, an arbitrary name is used.
  241. func Transformer(name string, f interface{}) Option {
  242. v := reflect.ValueOf(f)
  243. if !function.IsType(v.Type(), function.Transformer) || v.IsNil() {
  244. panic(fmt.Sprintf("invalid transformer function: %T", f))
  245. }
  246. if name == "" {
  247. name = function.NameOf(v)
  248. if !identsRx.MatchString(name) {
  249. name = "λ" // Lambda-symbol as placeholder name
  250. }
  251. } else if !identsRx.MatchString(name) {
  252. panic(fmt.Sprintf("invalid name: %q", name))
  253. }
  254. tr := &transformer{name: name, fnc: reflect.ValueOf(f)}
  255. if ti := v.Type().In(0); ti.Kind() != reflect.Interface || ti.NumMethod() > 0 {
  256. tr.typ = ti
  257. }
  258. return tr
  259. }
  260. type transformer struct {
  261. core
  262. name string
  263. typ reflect.Type // T
  264. fnc reflect.Value // func(T) R
  265. }
  266. func (tr *transformer) isFiltered() bool { return tr.typ != nil }
  267. func (tr *transformer) filter(s *state, t reflect.Type, _, _ reflect.Value) applicableOption {
  268. for i := len(s.curPath) - 1; i >= 0; i-- {
  269. if t, ok := s.curPath[i].(Transform); !ok {
  270. break // Hit most recent non-Transform step
  271. } else if tr == t.trans {
  272. return nil // Cannot directly use same Transform
  273. }
  274. }
  275. if tr.typ == nil || t.AssignableTo(tr.typ) {
  276. return tr
  277. }
  278. return nil
  279. }
  280. func (tr *transformer) apply(s *state, vx, vy reflect.Value) {
  281. step := Transform{&transform{pathStep{typ: tr.fnc.Type().Out(0)}, tr}}
  282. vvx := s.callTRFunc(tr.fnc, vx, step)
  283. vvy := s.callTRFunc(tr.fnc, vy, step)
  284. step.vx, step.vy = vvx, vvy
  285. s.compareAny(step)
  286. }
  287. func (tr transformer) String() string {
  288. return fmt.Sprintf("Transformer(%s, %s)", tr.name, function.NameOf(tr.fnc))
  289. }
  290. // Comparer returns an Option that determines whether two values are equal
  291. // to each other.
  292. //
  293. // The comparer f must be a function "func(T, T) bool" and is implicitly
  294. // filtered to input values assignable to T. If T is an interface, it is
  295. // possible that f is called with two values of different concrete types that
  296. // both implement T.
  297. //
  298. // The equality function must be:
  299. // • Symmetric: equal(x, y) == equal(y, x)
  300. // • Deterministic: equal(x, y) == equal(x, y)
  301. // • Pure: equal(x, y) does not modify x or y
  302. func Comparer(f interface{}) Option {
  303. v := reflect.ValueOf(f)
  304. if !function.IsType(v.Type(), function.Equal) || v.IsNil() {
  305. panic(fmt.Sprintf("invalid comparer function: %T", f))
  306. }
  307. cm := &comparer{fnc: v}
  308. if ti := v.Type().In(0); ti.Kind() != reflect.Interface || ti.NumMethod() > 0 {
  309. cm.typ = ti
  310. }
  311. return cm
  312. }
  313. type comparer struct {
  314. core
  315. typ reflect.Type // T
  316. fnc reflect.Value // func(T, T) bool
  317. }
  318. func (cm *comparer) isFiltered() bool { return cm.typ != nil }
  319. func (cm *comparer) filter(_ *state, t reflect.Type, _, _ reflect.Value) applicableOption {
  320. if cm.typ == nil || t.AssignableTo(cm.typ) {
  321. return cm
  322. }
  323. return nil
  324. }
  325. func (cm *comparer) apply(s *state, vx, vy reflect.Value) {
  326. eq := s.callTTBFunc(cm.fnc, vx, vy)
  327. s.report(eq, reportByFunc)
  328. }
  329. func (cm comparer) String() string {
  330. return fmt.Sprintf("Comparer(%s)", function.NameOf(cm.fnc))
  331. }
  332. // Exporter returns an Option that specifies whether Equal is allowed to
  333. // introspect into the unexported fields of certain struct types.
  334. //
  335. // Users of this option must understand that comparing on unexported fields
  336. // from external packages is not safe since changes in the internal
  337. // implementation of some external package may cause the result of Equal
  338. // to unexpectedly change. However, it may be valid to use this option on types
  339. // defined in an internal package where the semantic meaning of an unexported
  340. // field is in the control of the user.
  341. //
  342. // In many cases, a custom Comparer should be used instead that defines
  343. // equality as a function of the public API of a type rather than the underlying
  344. // unexported implementation.
  345. //
  346. // For example, the reflect.Type documentation defines equality to be determined
  347. // by the == operator on the interface (essentially performing a shallow pointer
  348. // comparison) and most attempts to compare *regexp.Regexp types are interested
  349. // in only checking that the regular expression strings are equal.
  350. // Both of these are accomplished using Comparers:
  351. //
  352. // Comparer(func(x, y reflect.Type) bool { return x == y })
  353. // Comparer(func(x, y *regexp.Regexp) bool { return x.String() == y.String() })
  354. //
  355. // In other cases, the cmpopts.IgnoreUnexported option can be used to ignore
  356. // all unexported fields on specified struct types.
  357. func Exporter(f func(reflect.Type) bool) Option {
  358. if !supportExporters {
  359. panic("Exporter is not supported on purego builds")
  360. }
  361. return exporter(f)
  362. }
  363. type exporter func(reflect.Type) bool
  364. func (exporter) filter(_ *state, _ reflect.Type, _, _ reflect.Value) applicableOption {
  365. panic("not implemented")
  366. }
  367. // AllowUnexported returns an Options that allows Equal to forcibly introspect
  368. // unexported fields of the specified struct types.
  369. //
  370. // See Exporter for the proper use of this option.
  371. func AllowUnexported(types ...interface{}) Option {
  372. m := make(map[reflect.Type]bool)
  373. for _, typ := range types {
  374. t := reflect.TypeOf(typ)
  375. if t.Kind() != reflect.Struct {
  376. panic(fmt.Sprintf("invalid struct type: %T", typ))
  377. }
  378. m[t] = true
  379. }
  380. return exporter(func(t reflect.Type) bool { return m[t] })
  381. }
  382. // Result represents the comparison result for a single node and
  383. // is provided by cmp when calling Result (see Reporter).
  384. type Result struct {
  385. _ [0]func() // Make Result incomparable
  386. flags resultFlags
  387. }
  388. // Equal reports whether the node was determined to be equal or not.
  389. // As a special case, ignored nodes are considered equal.
  390. func (r Result) Equal() bool {
  391. return r.flags&(reportEqual|reportByIgnore) != 0
  392. }
  393. // ByIgnore reports whether the node is equal because it was ignored.
  394. // This never reports true if Equal reports false.
  395. func (r Result) ByIgnore() bool {
  396. return r.flags&reportByIgnore != 0
  397. }
  398. // ByMethod reports whether the Equal method determined equality.
  399. func (r Result) ByMethod() bool {
  400. return r.flags&reportByMethod != 0
  401. }
  402. // ByFunc reports whether a Comparer function determined equality.
  403. func (r Result) ByFunc() bool {
  404. return r.flags&reportByFunc != 0
  405. }
  406. // ByCycle reports whether a reference cycle was detected.
  407. func (r Result) ByCycle() bool {
  408. return r.flags&reportByCycle != 0
  409. }
  410. type resultFlags uint
  411. const (
  412. _ resultFlags = (1 << iota) / 2
  413. reportEqual
  414. reportUnequal
  415. reportByIgnore
  416. reportByMethod
  417. reportByFunc
  418. reportByCycle
  419. )
  420. // Reporter is an Option that can be passed to Equal. When Equal traverses
  421. // the value trees, it calls PushStep as it descends into each node in the
  422. // tree and PopStep as it ascend out of the node. The leaves of the tree are
  423. // either compared (determined to be equal or not equal) or ignored and reported
  424. // as such by calling the Report method.
  425. func Reporter(r interface {
  426. // PushStep is called when a tree-traversal operation is performed.
  427. // The PathStep itself is only valid until the step is popped.
  428. // The PathStep.Values are valid for the duration of the entire traversal
  429. // and must not be mutated.
  430. //
  431. // Equal always calls PushStep at the start to provide an operation-less
  432. // PathStep used to report the root values.
  433. //
  434. // Within a slice, the exact set of inserted, removed, or modified elements
  435. // is unspecified and may change in future implementations.
  436. // The entries of a map are iterated through in an unspecified order.
  437. PushStep(PathStep)
  438. // Report is called exactly once on leaf nodes to report whether the
  439. // comparison identified the node as equal, unequal, or ignored.
  440. // A leaf node is one that is immediately preceded by and followed by
  441. // a pair of PushStep and PopStep calls.
  442. Report(Result)
  443. // PopStep ascends back up the value tree.
  444. // There is always a matching pop call for every push call.
  445. PopStep()
  446. }) Option {
  447. return reporter{r}
  448. }
  449. type reporter struct{ reporterIface }
  450. type reporterIface interface {
  451. PushStep(PathStep)
  452. Report(Result)
  453. PopStep()
  454. }
  455. func (reporter) filter(_ *state, _ reflect.Type, _, _ reflect.Value) applicableOption {
  456. panic("not implemented")
  457. }
  458. // normalizeOption normalizes the input options such that all Options groups
  459. // are flattened and groups with a single element are reduced to that element.
  460. // Only coreOptions and Options containing coreOptions are allowed.
  461. func normalizeOption(src Option) Option {
  462. switch opts := flattenOptions(nil, Options{src}); len(opts) {
  463. case 0:
  464. return nil
  465. case 1:
  466. return opts[0]
  467. default:
  468. return opts
  469. }
  470. }
  471. // flattenOptions copies all options in src to dst as a flat list.
  472. // Only coreOptions and Options containing coreOptions are allowed.
  473. func flattenOptions(dst, src Options) Options {
  474. for _, opt := range src {
  475. switch opt := opt.(type) {
  476. case nil:
  477. continue
  478. case Options:
  479. dst = flattenOptions(dst, opt)
  480. case coreOption:
  481. dst = append(dst, opt)
  482. default:
  483. panic(fmt.Sprintf("invalid option type: %T", opt))
  484. }
  485. }
  486. return dst
  487. }