Debian Codegraph @

v2/namer/namer.go

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