visit.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. /*
  2. Copyright 2019 The Kubernetes Authors.
  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. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package loader
  14. import (
  15. "go/ast"
  16. "reflect"
  17. "strconv"
  18. )
  19. // TypeCallback is a callback called for each raw AST (gendecl, typespec) combo.
  20. type TypeCallback func(file *ast.File, decl *ast.GenDecl, spec *ast.TypeSpec)
  21. // EachType calls the given callback for each (gendecl, typespec) combo in the
  22. // given package. Generally, using markers.EachType is better when working
  23. // with marker data, and has a more convinient representation.
  24. func EachType(pkg *Package, cb TypeCallback) {
  25. visitor := &typeVisitor{
  26. callback: cb,
  27. }
  28. pkg.NeedSyntax()
  29. for _, file := range pkg.Syntax {
  30. visitor.file = file
  31. ast.Walk(visitor, file)
  32. }
  33. }
  34. // typeVisitor visits all TypeSpecs, calling the given callback for each.
  35. type typeVisitor struct {
  36. callback TypeCallback
  37. decl *ast.GenDecl
  38. file *ast.File
  39. }
  40. // Visit visits all TypeSpecs.
  41. func (v *typeVisitor) Visit(node ast.Node) ast.Visitor {
  42. if node == nil {
  43. v.decl = nil
  44. return v
  45. }
  46. switch typedNode := node.(type) {
  47. case *ast.File:
  48. v.file = typedNode
  49. return v
  50. case *ast.GenDecl:
  51. v.decl = typedNode
  52. return v
  53. case *ast.TypeSpec:
  54. v.callback(v.file, v.decl, typedNode)
  55. return nil // don't recurse
  56. default:
  57. return nil
  58. }
  59. }
  60. // ParseAstTag parses the given raw tag literal into a reflect.StructTag.
  61. func ParseAstTag(tag *ast.BasicLit) reflect.StructTag {
  62. if tag == nil {
  63. return reflect.StructTag("")
  64. }
  65. tagStr, err := strconv.Unquote(tag.Value)
  66. if err != nil {
  67. return reflect.StructTag("")
  68. }
  69. return reflect.StructTag(tagStr)
  70. }