namer.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  1. /*
  2. Copyright 2015 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 namer
  14. import (
  15. "path/filepath"
  16. "strings"
  17. "k8s.io/kubernetes/cmd/libs/go2idl/types"
  18. )
  19. // Returns whether a name is a private Go name.
  20. func IsPrivateGoName(name string) bool {
  21. return len(name) == 0 || strings.ToLower(name[:1]) == name[:1]
  22. }
  23. // NewPublicNamer is a helper function that returns a namer that makes
  24. // CamelCase names. See the NameStrategy struct for an explanation of the
  25. // arguments to this constructor.
  26. func NewPublicNamer(prependPackageNames int, ignoreWords ...string) *NameStrategy {
  27. n := &NameStrategy{
  28. Join: Joiner(IC, IC),
  29. IgnoreWords: map[string]bool{},
  30. PrependPackageNames: prependPackageNames,
  31. }
  32. for _, w := range ignoreWords {
  33. n.IgnoreWords[w] = true
  34. }
  35. return n
  36. }
  37. // NewPrivateNamer is a helper function that returns a namer that makes
  38. // camelCase names. See the NameStrategy struct for an explanation of the
  39. // arguments to this constructor.
  40. func NewPrivateNamer(prependPackageNames int, ignoreWords ...string) *NameStrategy {
  41. n := &NameStrategy{
  42. Join: Joiner(IL, IC),
  43. IgnoreWords: map[string]bool{},
  44. PrependPackageNames: prependPackageNames,
  45. }
  46. for _, w := range ignoreWords {
  47. n.IgnoreWords[w] = true
  48. }
  49. return n
  50. }
  51. // NewRawNamer will return a Namer that makes a name by which you would
  52. // directly refer to a type, optionally keeping track of the import paths
  53. // necessary to reference the names it provides. Tracker may be nil.
  54. // The 'pkg' is the full package name, in which the Namer is used - all
  55. // types from that package will be referenced by just type name without
  56. // referencing the package.
  57. //
  58. // For example, if the type is map[string]int, a raw namer will literally
  59. // return "map[string]int".
  60. //
  61. // Or if the type, in package foo, is "type Bar struct { ... }", then the raw
  62. // namer will return "foo.Bar" as the name of the type, and if 'tracker' was
  63. // not nil, will record that package foo needs to be imported.
  64. func NewRawNamer(pkg string, tracker ImportTracker) *rawNamer {
  65. return &rawNamer{pkg: pkg, tracker: tracker}
  66. }
  67. // Names is a map from Type to name, as defined by some Namer.
  68. type Names map[*types.Type]string
  69. // Namer takes a type, and assigns a name.
  70. //
  71. // The purpose of this complexity is so that you can assign coherent
  72. // side-by-side systems of names for the types. For example, you might want a
  73. // public interface, a private implementation struct, and also to reference
  74. // literally the type name.
  75. //
  76. // Note that it is safe to call your own Name() function recursively to find
  77. // the names of keys, elements, etc. This is because anonymous types can't have
  78. // cycles in their names, and named types don't require the sort of recursion
  79. // that would be problematic.
  80. type Namer interface {
  81. Name(*types.Type) string
  82. }
  83. // NameSystems is a map of a system name to a namer for that system.
  84. type NameSystems map[string]Namer
  85. // NameStrategy is a general Namer. The easiest way to use it is to copy the
  86. // Public/PrivateNamer variables, and modify the members you wish to change.
  87. //
  88. // The Name method produces a name for the given type, of the forms:
  89. // Anonymous types: <Prefix><Type description><Suffix>
  90. // Named types: <Prefix><Optional Prepended Package name(s)><Original name><Suffix>
  91. //
  92. // In all cases, every part of the name is run through the capitalization
  93. // functions.
  94. //
  95. // The IgnoreWords map can be set if you have directory names that are
  96. // semantically meaningless for naming purposes, e.g. "proto".
  97. //
  98. // Prefix and Suffix can be used to disambiguate parallel systems of type
  99. // names. For example, if you want to generate an interface and an
  100. // implementation, you might want to suffix one with "Interface" and the other
  101. // with "Implementation". Another common use-- if you want to generate private
  102. // types, and one of your source types could be "string", you can't use the
  103. // default lowercase private namer. You'll have to add a suffix or prefix.
  104. type NameStrategy struct {
  105. Prefix, Suffix string
  106. Join func(pre string, parts []string, post string) string
  107. // Add non-meaningful package directory names here (e.g. "proto") and
  108. // they will be ignored.
  109. IgnoreWords map[string]bool
  110. // If > 0, prepend exactly that many package directory names (or as
  111. // many as there are). Package names listed in "IgnoreWords" will be
  112. // ignored.
  113. //
  114. // For example, if Ignore words lists "proto" and type Foo is in
  115. // pkg/server/frobbing/proto, then a value of 1 will give a type name
  116. // of FrobbingFoo, 2 gives ServerFrobbingFoo, etc.
  117. PrependPackageNames int
  118. // A cache of names thus far assigned by this namer.
  119. Names
  120. }
  121. // IC ensures the first character is uppercase.
  122. func IC(in string) string {
  123. if in == "" {
  124. return in
  125. }
  126. return strings.ToUpper(in[:1]) + in[1:]
  127. }
  128. // IL ensures the first character is lowercase.
  129. func IL(in string) string {
  130. if in == "" {
  131. return in
  132. }
  133. return strings.ToLower(in[:1]) + in[1:]
  134. }
  135. // Joiner lets you specify functions that preprocess the various components of
  136. // a name before joining them. You can construct e.g. camelCase or CamelCase or
  137. // any other way of joining words. (See the IC and IL convenience functions.)
  138. func Joiner(first, others func(string) string) func(pre string, in []string, post string) string {
  139. return func(pre string, in []string, post string) string {
  140. tmp := []string{others(pre)}
  141. for i := range in {
  142. tmp = append(tmp, others(in[i]))
  143. }
  144. tmp = append(tmp, others(post))
  145. return first(strings.Join(tmp, ""))
  146. }
  147. }
  148. func (ns *NameStrategy) removePrefixAndSuffix(s string) string {
  149. // The join function may have changed capitalization.
  150. lowerIn := strings.ToLower(s)
  151. lowerP := strings.ToLower(ns.Prefix)
  152. lowerS := strings.ToLower(ns.Suffix)
  153. b, e := 0, len(s)
  154. if strings.HasPrefix(lowerIn, lowerP) {
  155. b = len(ns.Prefix)
  156. }
  157. if strings.HasSuffix(lowerIn, lowerS) {
  158. e -= len(ns.Suffix)
  159. }
  160. return s[b:e]
  161. }
  162. var (
  163. importPathNameSanitizer = strings.NewReplacer("-", "_", ".", "")
  164. )
  165. // filters out unwanted directory names and sanitizes remaining names.
  166. func (ns *NameStrategy) filterDirs(path string) []string {
  167. allDirs := strings.Split(path, string(filepath.Separator))
  168. dirs := make([]string, 0, len(allDirs))
  169. for _, p := range allDirs {
  170. if ns.IgnoreWords == nil || !ns.IgnoreWords[p] {
  171. dirs = append(dirs, importPathNameSanitizer.Replace(p))
  172. }
  173. }
  174. return dirs
  175. }
  176. // See the comment on NameStrategy.
  177. func (ns *NameStrategy) Name(t *types.Type) string {
  178. if ns.Names == nil {
  179. ns.Names = Names{}
  180. }
  181. if s, ok := ns.Names[t]; ok {
  182. return s
  183. }
  184. if t.Name.Package != "" {
  185. dirs := append(ns.filterDirs(t.Name.Package), t.Name.Name)
  186. i := ns.PrependPackageNames + 1
  187. dn := len(dirs)
  188. if i > dn {
  189. i = dn
  190. }
  191. name := ns.Join(ns.Prefix, dirs[dn-i:], ns.Suffix)
  192. ns.Names[t] = name
  193. return name
  194. }
  195. // Only anonymous types remain.
  196. var name string
  197. switch t.Kind {
  198. case types.Builtin:
  199. name = ns.Join(ns.Prefix, []string{t.Name.Name}, ns.Suffix)
  200. case types.Map:
  201. name = ns.Join(ns.Prefix, []string{
  202. "Map",
  203. ns.removePrefixAndSuffix(ns.Name(t.Key)),
  204. "To",
  205. ns.removePrefixAndSuffix(ns.Name(t.Elem)),
  206. }, ns.Suffix)
  207. case types.Slice:
  208. name = ns.Join(ns.Prefix, []string{
  209. "Slice",
  210. ns.removePrefixAndSuffix(ns.Name(t.Elem)),
  211. }, ns.Suffix)
  212. case types.Pointer:
  213. name = ns.Join(ns.Prefix, []string{
  214. "Pointer",
  215. ns.removePrefixAndSuffix(ns.Name(t.Elem)),
  216. }, ns.Suffix)
  217. case types.Struct:
  218. names := []string{"Struct"}
  219. for _, m := range t.Members {
  220. names = append(names, ns.removePrefixAndSuffix(ns.Name(m.Type)))
  221. }
  222. name = ns.Join(ns.Prefix, names, ns.Suffix)
  223. // TODO: add types.Chan
  224. case types.Interface:
  225. // TODO: add to name test
  226. names := []string{"Interface"}
  227. for _, m := range t.Methods {
  228. // TODO: include function signature
  229. names = append(names, m.Name.Name)
  230. }
  231. name = ns.Join(ns.Prefix, names, ns.Suffix)
  232. case types.Func:
  233. // TODO: add to name test
  234. parts := []string{"Func"}
  235. for _, pt := range t.Signature.Parameters {
  236. parts = append(parts, ns.removePrefixAndSuffix(ns.Name(pt)))
  237. }
  238. parts = append(parts, "Returns")
  239. for _, rt := range t.Signature.Results {
  240. parts = append(parts, ns.removePrefixAndSuffix(ns.Name(rt)))
  241. }
  242. name = ns.Join(ns.Prefix, parts, ns.Suffix)
  243. default:
  244. name = "unnameable_" + string(t.Kind)
  245. }
  246. ns.Names[t] = name
  247. return name
  248. }
  249. // ImportTracker allows a raw namer to keep track of the packages needed for
  250. // import. You can implement yourself or use the one in the generation package.
  251. type ImportTracker interface {
  252. AddType(*types.Type)
  253. LocalNameOf(packagePath string) string
  254. PathOf(localName string) (string, bool)
  255. ImportLines() []string
  256. }
  257. type rawNamer struct {
  258. pkg string
  259. tracker ImportTracker
  260. Names
  261. }
  262. // Name makes a name the way you'd write it to literally refer to type t,
  263. // making ordinary assumptions about how you've imported t's package (or using
  264. // r.tracker to specifically track the package imports).
  265. func (r *rawNamer) Name(t *types.Type) string {
  266. if r.Names == nil {
  267. r.Names = Names{}
  268. }
  269. if name, ok := r.Names[t]; ok {
  270. return name
  271. }
  272. if t.Name.Package != "" {
  273. var name string
  274. if r.tracker != nil {
  275. r.tracker.AddType(t)
  276. if t.Name.Package == r.pkg {
  277. name = t.Name.Name
  278. } else {
  279. name = r.tracker.LocalNameOf(t.Name.Package) + "." + t.Name.Name
  280. }
  281. } else {
  282. if t.Name.Package == r.pkg {
  283. name = t.Name.Name
  284. } else {
  285. name = filepath.Base(t.Name.Package) + "." + t.Name.Name
  286. }
  287. }
  288. r.Names[t] = name
  289. return name
  290. }
  291. var name string
  292. switch t.Kind {
  293. case types.Builtin:
  294. name = t.Name.Name
  295. case types.Map:
  296. name = "map[" + r.Name(t.Key) + "]" + r.Name(t.Elem)
  297. case types.Slice:
  298. name = "[]" + r.Name(t.Elem)
  299. case types.Pointer:
  300. name = "*" + r.Name(t.Elem)
  301. case types.Struct:
  302. elems := []string{}
  303. for _, m := range t.Members {
  304. elems = append(elems, m.Name+" "+r.Name(m.Type))
  305. }
  306. name = "struct{" + strings.Join(elems, "; ") + "}"
  307. // TODO: add types.Chan
  308. case types.Interface:
  309. // TODO: add to name test
  310. elems := []string{}
  311. for _, m := range t.Methods {
  312. // TODO: include function signature
  313. elems = append(elems, m.Name.Name)
  314. }
  315. name = "interface{" + strings.Join(elems, "; ") + "}"
  316. case types.Func:
  317. // TODO: add to name test
  318. params := []string{}
  319. for _, pt := range t.Signature.Parameters {
  320. params = append(params, r.Name(pt))
  321. }
  322. results := []string{}
  323. for _, rt := range t.Signature.Results {
  324. results = append(results, r.Name(rt))
  325. }
  326. name = "func(" + strings.Join(params, ",") + ")"
  327. if len(results) == 1 {
  328. name += " " + results[0]
  329. } else if len(results) > 1 {
  330. name += " (" + strings.Join(results, ",") + ")"
  331. }
  332. default:
  333. name = "unnameable_" + string(t.Kind)
  334. }
  335. r.Names[t] = name
  336. return name
  337. }