Não pode escolher mais do que 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 

525 linhas
17 KiB

  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 AllowUnexported or cmpopts.IgnoreUnexported"
  202. panic(fmt.Sprintf("cannot handle unexported field: %#v\n%s", s.curPath, help))
  203. }
  204. panic("not reachable")
  205. }
  206. // identRx represents a valid identifier according to the Go specification.
  207. const identRx = `[_\p{L}][_\p{L}\p{N}]*`
  208. var identsRx = regexp.MustCompile(`^` + identRx + `(\.` + identRx + `)*$`)
  209. // Transformer returns an Option that applies a transformation function that
  210. // converts values of a certain type into that of another.
  211. //
  212. // The transformer f must be a function "func(T) R" that converts values of
  213. // type T to those of type R and is implicitly filtered to input values
  214. // assignable to T. The transformer must not mutate T in any way.
  215. //
  216. // To help prevent some cases of infinite recursive cycles applying the
  217. // same transform to the output of itself (e.g., in the case where the
  218. // input and output types are the same), an implicit filter is added such that
  219. // a transformer is applicable only if that exact transformer is not already
  220. // in the tail of the Path since the last non-Transform step.
  221. // For situations where the implicit filter is still insufficient,
  222. // consider using cmpopts.AcyclicTransformer, which adds a filter
  223. // to prevent the transformer from being recursively applied upon itself.
  224. //
  225. // The name is a user provided label that is used as the Transform.Name in the
  226. // transformation PathStep (and eventually shown in the Diff output).
  227. // The name must be a valid identifier or qualified identifier in Go syntax.
  228. // If empty, an arbitrary name is used.
  229. func Transformer(name string, f interface{}) Option {
  230. v := reflect.ValueOf(f)
  231. if !function.IsType(v.Type(), function.Transformer) || v.IsNil() {
  232. panic(fmt.Sprintf("invalid transformer function: %T", f))
  233. }
  234. if name == "" {
  235. name = function.NameOf(v)
  236. if !identsRx.MatchString(name) {
  237. name = "λ" // Lambda-symbol as placeholder name
  238. }
  239. } else if !identsRx.MatchString(name) {
  240. panic(fmt.Sprintf("invalid name: %q", name))
  241. }
  242. tr := &transformer{name: name, fnc: reflect.ValueOf(f)}
  243. if ti := v.Type().In(0); ti.Kind() != reflect.Interface || ti.NumMethod() > 0 {
  244. tr.typ = ti
  245. }
  246. return tr
  247. }
  248. type transformer struct {
  249. core
  250. name string
  251. typ reflect.Type // T
  252. fnc reflect.Value // func(T) R
  253. }
  254. func (tr *transformer) isFiltered() bool { return tr.typ != nil }
  255. func (tr *transformer) filter(s *state, t reflect.Type, _, _ reflect.Value) applicableOption {
  256. for i := len(s.curPath) - 1; i >= 0; i-- {
  257. if t, ok := s.curPath[i].(Transform); !ok {
  258. break // Hit most recent non-Transform step
  259. } else if tr == t.trans {
  260. return nil // Cannot directly use same Transform
  261. }
  262. }
  263. if tr.typ == nil || t.AssignableTo(tr.typ) {
  264. return tr
  265. }
  266. return nil
  267. }
  268. func (tr *transformer) apply(s *state, vx, vy reflect.Value) {
  269. step := Transform{&transform{pathStep{typ: tr.fnc.Type().Out(0)}, tr}}
  270. vvx := s.callTRFunc(tr.fnc, vx, step)
  271. vvy := s.callTRFunc(tr.fnc, vy, step)
  272. step.vx, step.vy = vvx, vvy
  273. s.compareAny(step)
  274. }
  275. func (tr transformer) String() string {
  276. return fmt.Sprintf("Transformer(%s, %s)", tr.name, function.NameOf(tr.fnc))
  277. }
  278. // Comparer returns an Option that determines whether two values are equal
  279. // to each other.
  280. //
  281. // The comparer f must be a function "func(T, T) bool" and is implicitly
  282. // filtered to input values assignable to T. If T is an interface, it is
  283. // possible that f is called with two values of different concrete types that
  284. // both implement T.
  285. //
  286. // The equality function must be:
  287. // • Symmetric: equal(x, y) == equal(y, x)
  288. // • Deterministic: equal(x, y) == equal(x, y)
  289. // • Pure: equal(x, y) does not modify x or y
  290. func Comparer(f interface{}) Option {
  291. v := reflect.ValueOf(f)
  292. if !function.IsType(v.Type(), function.Equal) || v.IsNil() {
  293. panic(fmt.Sprintf("invalid comparer function: %T", f))
  294. }
  295. cm := &comparer{fnc: v}
  296. if ti := v.Type().In(0); ti.Kind() != reflect.Interface || ti.NumMethod() > 0 {
  297. cm.typ = ti
  298. }
  299. return cm
  300. }
  301. type comparer struct {
  302. core
  303. typ reflect.Type // T
  304. fnc reflect.Value // func(T, T) bool
  305. }
  306. func (cm *comparer) isFiltered() bool { return cm.typ != nil }
  307. func (cm *comparer) filter(_ *state, t reflect.Type, _, _ reflect.Value) applicableOption {
  308. if cm.typ == nil || t.AssignableTo(cm.typ) {
  309. return cm
  310. }
  311. return nil
  312. }
  313. func (cm *comparer) apply(s *state, vx, vy reflect.Value) {
  314. eq := s.callTTBFunc(cm.fnc, vx, vy)
  315. s.report(eq, reportByFunc)
  316. }
  317. func (cm comparer) String() string {
  318. return fmt.Sprintf("Comparer(%s)", function.NameOf(cm.fnc))
  319. }
  320. // AllowUnexported returns an Option that forcibly allows operations on
  321. // unexported fields in certain structs, which are specified by passing in a
  322. // value of each struct type.
  323. //
  324. // Users of this option must understand that comparing on unexported fields
  325. // from external packages is not safe since changes in the internal
  326. // implementation of some external package may cause the result of Equal
  327. // to unexpectedly change. However, it may be valid to use this option on types
  328. // defined in an internal package where the semantic meaning of an unexported
  329. // field is in the control of the user.
  330. //
  331. // In many cases, a custom Comparer should be used instead that defines
  332. // equality as a function of the public API of a type rather than the underlying
  333. // unexported implementation.
  334. //
  335. // For example, the reflect.Type documentation defines equality to be determined
  336. // by the == operator on the interface (essentially performing a shallow pointer
  337. // comparison) and most attempts to compare *regexp.Regexp types are interested
  338. // in only checking that the regular expression strings are equal.
  339. // Both of these are accomplished using Comparers:
  340. //
  341. // Comparer(func(x, y reflect.Type) bool { return x == y })
  342. // Comparer(func(x, y *regexp.Regexp) bool { return x.String() == y.String() })
  343. //
  344. // In other cases, the cmpopts.IgnoreUnexported option can be used to ignore
  345. // all unexported fields on specified struct types.
  346. func AllowUnexported(types ...interface{}) Option {
  347. if !supportAllowUnexported {
  348. panic("AllowUnexported is not supported on purego builds, Google App Engine Standard, or GopherJS")
  349. }
  350. m := make(map[reflect.Type]bool)
  351. for _, typ := range types {
  352. t := reflect.TypeOf(typ)
  353. if t.Kind() != reflect.Struct {
  354. panic(fmt.Sprintf("invalid struct type: %T", typ))
  355. }
  356. m[t] = true
  357. }
  358. return visibleStructs(m)
  359. }
  360. type visibleStructs map[reflect.Type]bool
  361. func (visibleStructs) filter(_ *state, _ reflect.Type, _, _ reflect.Value) applicableOption {
  362. panic("not implemented")
  363. }
  364. // Result represents the comparison result for a single node and
  365. // is provided by cmp when calling Result (see Reporter).
  366. type Result struct {
  367. _ [0]func() // Make Result incomparable
  368. flags resultFlags
  369. }
  370. // Equal reports whether the node was determined to be equal or not.
  371. // As a special case, ignored nodes are considered equal.
  372. func (r Result) Equal() bool {
  373. return r.flags&(reportEqual|reportByIgnore) != 0
  374. }
  375. // ByIgnore reports whether the node is equal because it was ignored.
  376. // This never reports true if Equal reports false.
  377. func (r Result) ByIgnore() bool {
  378. return r.flags&reportByIgnore != 0
  379. }
  380. // ByMethod reports whether the Equal method determined equality.
  381. func (r Result) ByMethod() bool {
  382. return r.flags&reportByMethod != 0
  383. }
  384. // ByFunc reports whether a Comparer function determined equality.
  385. func (r Result) ByFunc() bool {
  386. return r.flags&reportByFunc != 0
  387. }
  388. type resultFlags uint
  389. const (
  390. _ resultFlags = (1 << iota) / 2
  391. reportEqual
  392. reportUnequal
  393. reportByIgnore
  394. reportByMethod
  395. reportByFunc
  396. )
  397. // Reporter is an Option that can be passed to Equal. When Equal traverses
  398. // the value trees, it calls PushStep as it descends into each node in the
  399. // tree and PopStep as it ascend out of the node. The leaves of the tree are
  400. // either compared (determined to be equal or not equal) or ignored and reported
  401. // as such by calling the Report method.
  402. func Reporter(r interface {
  403. // PushStep is called when a tree-traversal operation is performed.
  404. // The PathStep itself is only valid until the step is popped.
  405. // The PathStep.Values are valid for the duration of the entire traversal
  406. // and must not be mutated.
  407. //
  408. // Equal always calls PushStep at the start to provide an operation-less
  409. // PathStep used to report the root values.
  410. //
  411. // Within a slice, the exact set of inserted, removed, or modified elements
  412. // is unspecified and may change in future implementations.
  413. // The entries of a map are iterated through in an unspecified order.
  414. PushStep(PathStep)
  415. // Report is called exactly once on leaf nodes to report whether the
  416. // comparison identified the node as equal, unequal, or ignored.
  417. // A leaf node is one that is immediately preceded by and followed by
  418. // a pair of PushStep and PopStep calls.
  419. Report(Result)
  420. // PopStep ascends back up the value tree.
  421. // There is always a matching pop call for every push call.
  422. PopStep()
  423. }) Option {
  424. return reporter{r}
  425. }
  426. type reporter struct{ reporterIface }
  427. type reporterIface interface {
  428. PushStep(PathStep)
  429. Report(Result)
  430. PopStep()
  431. }
  432. func (reporter) filter(_ *state, _ reflect.Type, _, _ reflect.Value) applicableOption {
  433. panic("not implemented")
  434. }
  435. // normalizeOption normalizes the input options such that all Options groups
  436. // are flattened and groups with a single element are reduced to that element.
  437. // Only coreOptions and Options containing coreOptions are allowed.
  438. func normalizeOption(src Option) Option {
  439. switch opts := flattenOptions(nil, Options{src}); len(opts) {
  440. case 0:
  441. return nil
  442. case 1:
  443. return opts[0]
  444. default:
  445. return opts
  446. }
  447. }
  448. // flattenOptions copies all options in src to dst as a flat list.
  449. // Only coreOptions and Options containing coreOptions are allowed.
  450. func flattenOptions(dst, src Options) Options {
  451. for _, opt := range src {
  452. switch opt := opt.(type) {
  453. case nil:
  454. continue
  455. case Options:
  456. dst = flattenOptions(dst, opt)
  457. case coreOption:
  458. dst = append(dst, opt)
  459. default:
  460. panic(fmt.Sprintf("invalid option type: %T", opt))
  461. }
  462. }
  463. return dst
  464. }