Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.
 
 
 

469 rader
15 KiB

  1. // Copyright 2016 Google LLC
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. // Package fields provides a view of the fields of a struct that follows the Go
  15. // rules, amended to consider tags and case insensitivity.
  16. //
  17. // Usage
  18. //
  19. // First define a function that interprets tags:
  20. //
  21. // func parseTag(st reflect.StructTag) (name string, keep bool, other interface{}, err error) { ... }
  22. //
  23. // The function's return values describe whether to ignore the field
  24. // completely or provide an alternate name, as well as other data from the
  25. // parse that is stored to avoid re-parsing.
  26. //
  27. // Then define a function to validate the type:
  28. //
  29. // func validate(t reflect.Type) error { ... }
  30. //
  31. // Then, if necessary, define a function to specify leaf types - types
  32. // which should be considered one field and not be recursed into:
  33. //
  34. // func isLeafType(t reflect.Type) bool { ... }
  35. //
  36. // eg:
  37. //
  38. // func isLeafType(t reflect.Type) bool {
  39. // return t == reflect.TypeOf(time.Time{})
  40. // }
  41. //
  42. // Next, construct a Cache, passing your functions. As its name suggests, a
  43. // Cache remembers validation and field information for a type, so subsequent
  44. // calls with the same type are very fast.
  45. //
  46. // cache := fields.NewCache(parseTag, validate, isLeafType)
  47. //
  48. // To get the fields of a struct type as determined by the above rules, call
  49. // the Fields method:
  50. //
  51. // fields, err := cache.Fields(reflect.TypeOf(MyStruct{}))
  52. //
  53. // The return value can be treated as a slice of Fields.
  54. //
  55. // Given a string, such as a key or column name obtained during unmarshalling,
  56. // call Match on the list of fields to find a field whose name is the best
  57. // match:
  58. //
  59. // field := fields.Match(name)
  60. //
  61. // Match looks for an exact match first, then falls back to a case-insensitive
  62. // comparison.
  63. package fields
  64. import (
  65. "bytes"
  66. "errors"
  67. "reflect"
  68. "sort"
  69. "strings"
  70. "cloud.google.com/go/internal/atomiccache"
  71. )
  72. // A Field records information about a struct field.
  73. type Field struct {
  74. Name string // effective field name
  75. NameFromTag bool // did Name come from a tag?
  76. Type reflect.Type // field type
  77. Index []int // index sequence, for reflect.Value.FieldByIndex
  78. ParsedTag interface{} // third return value of the parseTag function
  79. nameBytes []byte
  80. equalFold func(s, t []byte) bool
  81. }
  82. type ParseTagFunc func(reflect.StructTag) (name string, keep bool, other interface{}, err error)
  83. type ValidateFunc func(reflect.Type) error
  84. type LeafTypesFunc func(reflect.Type) bool
  85. // A Cache records information about the fields of struct types.
  86. //
  87. // A Cache is safe for use by multiple goroutines.
  88. type Cache struct {
  89. parseTag ParseTagFunc
  90. validate ValidateFunc
  91. leafTypes LeafTypesFunc
  92. cache atomiccache.Cache // from reflect.Type to cacheValue
  93. }
  94. // NewCache constructs a Cache.
  95. //
  96. // Its first argument should be a function that accepts
  97. // a struct tag and returns four values: an alternative name for the field
  98. // extracted from the tag, a boolean saying whether to keep the field or ignore
  99. // it, additional data that is stored with the field information to avoid
  100. // having to parse the tag again, and an error.
  101. //
  102. // Its second argument should be a function that accepts a reflect.Type and
  103. // returns an error if the struct type is invalid in any way. For example, it
  104. // may check that all of the struct field tags are valid, or that all fields
  105. // are of an appropriate type.
  106. func NewCache(parseTag ParseTagFunc, validate ValidateFunc, leafTypes LeafTypesFunc) *Cache {
  107. if parseTag == nil {
  108. parseTag = func(reflect.StructTag) (string, bool, interface{}, error) {
  109. return "", true, nil, nil
  110. }
  111. }
  112. if validate == nil {
  113. validate = func(reflect.Type) error {
  114. return nil
  115. }
  116. }
  117. if leafTypes == nil {
  118. leafTypes = func(reflect.Type) bool {
  119. return false
  120. }
  121. }
  122. return &Cache{
  123. parseTag: parseTag,
  124. validate: validate,
  125. leafTypes: leafTypes,
  126. }
  127. }
  128. // A fieldScan represents an item on the fieldByNameFunc scan work list.
  129. type fieldScan struct {
  130. typ reflect.Type
  131. index []int
  132. }
  133. // Fields returns all the exported fields of t, which must be a struct type. It
  134. // follows the standard Go rules for embedded fields, modified by the presence
  135. // of tags. The result is sorted lexicographically by index.
  136. //
  137. // These rules apply in the absence of tags:
  138. // Anonymous struct fields are treated as if their inner exported fields were
  139. // fields in the outer struct (embedding). The result includes all fields that
  140. // aren't shadowed by fields at higher level of embedding. If more than one
  141. // field with the same name exists at the same level of embedding, it is
  142. // excluded. An anonymous field that is not of struct type is treated as having
  143. // its type as its name.
  144. //
  145. // Tags modify these rules as follows:
  146. // A field's tag is used as its name.
  147. // An anonymous struct field with a name given in its tag is treated as
  148. // a field having that name, rather than an embedded struct (the struct's
  149. // fields will not be returned).
  150. // If more than one field with the same name exists at the same level of embedding,
  151. // but exactly one of them is tagged, then the tagged field is reported and the others
  152. // are ignored.
  153. func (c *Cache) Fields(t reflect.Type) (List, error) {
  154. if t.Kind() != reflect.Struct {
  155. panic("fields: Fields of non-struct type")
  156. }
  157. return c.cachedTypeFields(t)
  158. }
  159. // A List is a list of Fields.
  160. type List []Field
  161. // Match returns the field in the list whose name best matches the supplied
  162. // name, nor nil if no field does. If there is a field with the exact name, it
  163. // is returned. Otherwise the first field (sorted by index) whose name matches
  164. // case-insensitively is returned.
  165. func (l List) Match(name string) *Field {
  166. return l.MatchBytes([]byte(name))
  167. }
  168. // MatchBytes is identical to Match, except that the argument is a byte slice.
  169. func (l List) MatchBytes(name []byte) *Field {
  170. var f *Field
  171. for i := range l {
  172. ff := &l[i]
  173. if bytes.Equal(ff.nameBytes, name) {
  174. return ff
  175. }
  176. if f == nil && ff.equalFold(ff.nameBytes, name) {
  177. f = ff
  178. }
  179. }
  180. return f
  181. }
  182. type cacheValue struct {
  183. fields List
  184. err error
  185. }
  186. // cachedTypeFields is like typeFields but uses a cache to avoid repeated work.
  187. // This code has been copied and modified from
  188. // https://go.googlesource.com/go/+/go1.7.3/src/encoding/json/encode.go.
  189. func (c *Cache) cachedTypeFields(t reflect.Type) (List, error) {
  190. cv := c.cache.Get(t, func() interface{} {
  191. if err := c.validate(t); err != nil {
  192. return cacheValue{nil, err}
  193. }
  194. f, err := c.typeFields(t)
  195. return cacheValue{List(f), err}
  196. }).(cacheValue)
  197. return cv.fields, cv.err
  198. }
  199. func (c *Cache) typeFields(t reflect.Type) ([]Field, error) {
  200. fields, err := c.listFields(t)
  201. if err != nil {
  202. return nil, err
  203. }
  204. sort.Sort(byName(fields))
  205. // Delete all fields that are hidden by the Go rules for embedded fields.
  206. // The fields are sorted in primary order of name, secondary order of field
  207. // index length. So the first field with a given name is the dominant one.
  208. var out []Field
  209. for advance, i := 0, 0; i < len(fields); i += advance {
  210. // One iteration per name.
  211. // Find the sequence of fields with the name of this first field.
  212. fi := fields[i]
  213. name := fi.Name
  214. for advance = 1; i+advance < len(fields); advance++ {
  215. fj := fields[i+advance]
  216. if fj.Name != name {
  217. break
  218. }
  219. }
  220. // Find the dominant field, if any, out of all fields that have the same name.
  221. dominant, ok := dominantField(fields[i : i+advance])
  222. if ok {
  223. out = append(out, dominant)
  224. }
  225. }
  226. sort.Sort(byIndex(out))
  227. return out, nil
  228. }
  229. func (c *Cache) listFields(t reflect.Type) ([]Field, error) {
  230. // This uses the same condition that the Go language does: there must be a unique instance
  231. // of the match at a given depth level. If there are multiple instances of a match at the
  232. // same depth, they annihilate each other and inhibit any possible match at a lower level.
  233. // The algorithm is breadth first search, one depth level at a time.
  234. // The current and next slices are work queues:
  235. // current lists the fields to visit on this depth level,
  236. // and next lists the fields on the next lower level.
  237. current := []fieldScan{}
  238. next := []fieldScan{{typ: t}}
  239. // nextCount records the number of times an embedded type has been
  240. // encountered and considered for queueing in the 'next' slice.
  241. // We only queue the first one, but we increment the count on each.
  242. // If a struct type T can be reached more than once at a given depth level,
  243. // then it annihilates itself and need not be considered at all when we
  244. // process that next depth level.
  245. var nextCount map[reflect.Type]int
  246. // visited records the structs that have been considered already.
  247. // Embedded pointer fields can create cycles in the graph of
  248. // reachable embedded types; visited avoids following those cycles.
  249. // It also avoids duplicated effort: if we didn't find the field in an
  250. // embedded type T at level 2, we won't find it in one at level 4 either.
  251. visited := map[reflect.Type]bool{}
  252. var fields []Field // Fields found.
  253. for len(next) > 0 {
  254. current, next = next, current[:0]
  255. count := nextCount
  256. nextCount = nil
  257. // Process all the fields at this depth, now listed in 'current'.
  258. // The loop queues embedded fields found in 'next', for processing during the next
  259. // iteration. The multiplicity of the 'current' field counts is recorded
  260. // in 'count'; the multiplicity of the 'next' field counts is recorded in 'nextCount'.
  261. for _, scan := range current {
  262. t := scan.typ
  263. if visited[t] {
  264. // We've looked through this type before, at a higher level.
  265. // That higher level would shadow the lower level we're now at,
  266. // so this one can't be useful to us. Ignore it.
  267. continue
  268. }
  269. visited[t] = true
  270. for i := 0; i < t.NumField(); i++ {
  271. f := t.Field(i)
  272. exported := (f.PkgPath == "")
  273. // If a named field is unexported, ignore it. An anonymous
  274. // unexported field is processed, because it may contain
  275. // exported fields, which are visible.
  276. if !exported && !f.Anonymous {
  277. continue
  278. }
  279. // Examine the tag.
  280. tagName, keep, other, err := c.parseTag(f.Tag)
  281. if err != nil {
  282. return nil, err
  283. }
  284. if !keep {
  285. continue
  286. }
  287. if c.leafTypes(f.Type) {
  288. fields = append(fields, newField(f, tagName, other, scan.index, i))
  289. continue
  290. }
  291. var ntyp reflect.Type
  292. if f.Anonymous {
  293. // Anonymous field of type T or *T.
  294. ntyp = f.Type
  295. if ntyp.Kind() == reflect.Ptr {
  296. ntyp = ntyp.Elem()
  297. }
  298. }
  299. // Record fields with a tag name, non-anonymous fields, or
  300. // anonymous non-struct fields.
  301. if tagName != "" || ntyp == nil || ntyp.Kind() != reflect.Struct {
  302. if !exported {
  303. continue
  304. }
  305. fields = append(fields, newField(f, tagName, other, scan.index, i))
  306. if count[t] > 1 {
  307. // If there were multiple instances, add a second,
  308. // so that the annihilation code will see a duplicate.
  309. fields = append(fields, fields[len(fields)-1])
  310. }
  311. continue
  312. }
  313. // Queue embedded struct fields for processing with next level,
  314. // but only if the embedded types haven't already been queued.
  315. if nextCount[ntyp] > 0 {
  316. nextCount[ntyp] = 2 // exact multiple doesn't matter
  317. continue
  318. }
  319. if nextCount == nil {
  320. nextCount = map[reflect.Type]int{}
  321. }
  322. nextCount[ntyp] = 1
  323. if count[t] > 1 {
  324. nextCount[ntyp] = 2 // exact multiple doesn't matter
  325. }
  326. var index []int
  327. index = append(index, scan.index...)
  328. index = append(index, i)
  329. next = append(next, fieldScan{ntyp, index})
  330. }
  331. }
  332. }
  333. return fields, nil
  334. }
  335. func newField(f reflect.StructField, tagName string, other interface{}, index []int, i int) Field {
  336. name := tagName
  337. if name == "" {
  338. name = f.Name
  339. }
  340. sf := Field{
  341. Name: name,
  342. NameFromTag: tagName != "",
  343. Type: f.Type,
  344. ParsedTag: other,
  345. nameBytes: []byte(name),
  346. }
  347. sf.equalFold = foldFunc(sf.nameBytes)
  348. sf.Index = append(sf.Index, index...)
  349. sf.Index = append(sf.Index, i)
  350. return sf
  351. }
  352. // byName sorts fields using the following criteria, in order:
  353. // 1. name
  354. // 2. embedding depth
  355. // 3. tag presence (preferring a tagged field)
  356. // 4. index sequence.
  357. type byName []Field
  358. func (x byName) Len() int { return len(x) }
  359. func (x byName) Swap(i, j int) { x[i], x[j] = x[j], x[i] }
  360. func (x byName) Less(i, j int) bool {
  361. if x[i].Name != x[j].Name {
  362. return x[i].Name < x[j].Name
  363. }
  364. if len(x[i].Index) != len(x[j].Index) {
  365. return len(x[i].Index) < len(x[j].Index)
  366. }
  367. if x[i].NameFromTag != x[j].NameFromTag {
  368. return x[i].NameFromTag
  369. }
  370. return byIndex(x).Less(i, j)
  371. }
  372. // byIndex sorts field by index sequence.
  373. type byIndex []Field
  374. func (x byIndex) Len() int { return len(x) }
  375. func (x byIndex) Swap(i, j int) { x[i], x[j] = x[j], x[i] }
  376. func (x byIndex) Less(i, j int) bool {
  377. xi := x[i].Index
  378. xj := x[j].Index
  379. ln := len(xi)
  380. if l := len(xj); l < ln {
  381. ln = l
  382. }
  383. for k := 0; k < ln; k++ {
  384. if xi[k] != xj[k] {
  385. return xi[k] < xj[k]
  386. }
  387. }
  388. return len(xi) < len(xj)
  389. }
  390. // dominantField looks through the fields, all of which are known to have the
  391. // same name, to find the single field that dominates the others using Go's
  392. // embedding rules, modified by the presence of tags. If there are multiple
  393. // top-level fields, the boolean will be false: This condition is an error in
  394. // Go and we skip all the fields.
  395. func dominantField(fs []Field) (Field, bool) {
  396. // The fields are sorted in increasing index-length order, then by presence of tag.
  397. // That means that the first field is the dominant one. We need only check
  398. // for error cases: two fields at top level, either both tagged or neither tagged.
  399. if len(fs) > 1 && len(fs[0].Index) == len(fs[1].Index) && fs[0].NameFromTag == fs[1].NameFromTag {
  400. return Field{}, false
  401. }
  402. return fs[0], true
  403. }
  404. // ParseStandardTag extracts the sub-tag named by key, then parses it using the
  405. // de facto standard format introduced in encoding/json:
  406. // "-" means "ignore this tag". It must occur by itself. (parseStandardTag returns an error
  407. // in this case, whereas encoding/json accepts the "-" even if it is not alone.)
  408. // "<name>" provides an alternative name for the field
  409. // "<name>,opt1,opt2,..." specifies options after the name.
  410. // The options are returned as a []string.
  411. func ParseStandardTag(key string, t reflect.StructTag) (name string, keep bool, options []string, err error) {
  412. s := t.Get(key)
  413. parts := strings.Split(s, ",")
  414. if parts[0] == "-" {
  415. if len(parts) > 1 {
  416. return "", false, nil, errors.New(`"-" field tag with options`)
  417. }
  418. return "", false, nil, nil
  419. }
  420. if len(parts) > 1 {
  421. options = parts[1:]
  422. }
  423. return parts[0], true, options, nil
  424. }