Debian Codegraph @

types/types.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 types
18
19 import "strings"
20
21 // Ref makes a reference to the given type. It can only be used for e.g.
22 // passing to namers.
23 func Ref(packageName, typeName string) *Type {
24 return &Type{Name: Name{
25 Name: typeName,
26 Package: packageName,
27 }}
28 }
29
30 // A type name may have a package qualifier.
31 type Name struct {
32 // Empty if embedded or builtin. This is the package path unless Path is specified.
33 Package string
34 // The type name.
35 Name string
36 // An optional location of the type definition for languages that can have disjoint
37 // packages and paths.
38 Path string
39 }
40
41 // String returns the name formatted as a string.
42 func (n Name) String() string {
43 if n.Package == "" {
44 return n.Name
45 }
46 return n.Package + "." + n.Name
47 }
48
49 // ParseFullyQualifiedName parses a name like k8s.io/kubernetes/pkg/api.Pod into a Name.
50 func ParseFullyQualifiedName(fqn string) Name {
51 cs := strings.Split(fqn, ".")
52 pkg := ""
53 if len(cs) > 1 {
54 pkg = strings.Join(cs[0:len(cs)-1], ".")
55 }
56 return Name{
57 Name: cs[len(cs)-1],
58 Package: pkg,
59 }
60 }
61
62 // The possible classes of types.
63 type Kind string
64
65 const (
66 // Builtin is a primitive, like bool, string, int.
67 Builtin Kind = "Builtin"
68 Struct Kind = "Struct"
69 Map Kind = "Map"
70 Slice Kind = "Slice"
71 Pointer Kind = "Pointer"
72
73 // Alias is an alias of another type, e.g. in:
74 // type Foo string
75 // type Bar Foo
76 // Bar is an alias of Foo.
77 //
78 // In the real go type system, Foo is a "Named" string; but to simplify
79 // generation, this type system will just say that Foo *is* a builtin.
80 // We then need "Alias" as a way for us to say that Bar *is* a Foo.
81 Alias Kind = "Alias"
82
83 // Interface is any type that could have differing types at run time.
84 Interface Kind = "Interface"
85
86 // Array is just like slice, but has a fixed length.
87 Array Kind = "Array"
88
89 // The remaining types are included for completeness, but are not well
90 // supported.
91 Chan Kind = "Chan"
92 Func Kind = "Func"
93
94 // DeclarationOf is different from other Kinds; it indicates that instead of
95 // representing an actual Type, the type is a declaration of an instance of
96 // a type. E.g., a top-level function, variable, or constant. See the
97 // comment for Type.Name for more detail.
98 DeclarationOf Kind = "DeclarationOf"
99 Unknown Kind = ""
100 Unsupported Kind = "Unsupported"
101
102 // Protobuf is protobuf type.
103 Protobuf Kind = "Protobuf"
104 )
105
106 // Package holds package-level information.
107 // Fields are public, as everything in this package, to enable consumption by
108 // templates (for example). But it is strongly encouraged for code to build by
109 // using the provided functions.
110 type Package struct {
111 // Canonical name of this package-- its path.
112 Path string
113
114 // The location this package was loaded from
115 SourcePath string
116
117 // Short name of this package; the name that appears in the
118 // 'package x' line.
119 Name string
120
121 // The comment right above the package declaration in doc.go, if any.
122 DocComments []string
123
124 // All comments from doc.go, if any.
125 // TODO: remove Comments and use DocComments everywhere.
126 Comments []string
127
128 // Types within this package, indexed by their name (*not* including
129 // package name).
130 Types map[string]*Type
131
132 // Functions within this package, indexed by their name (*not* including
133 // package name).
134 Functions map[string]*Type
135
136 // Global variables within this package, indexed by their name (*not* including
137 // package name).
138 Variables map[string]*Type
139
140 // Global constants within this package, indexed by their name (*not* including
141 // package name).
142 Constants map[string]*Type
143
144 // Packages imported by this package, indexed by (canonicalized)
145 // package path.
146 Imports map[string]*Package
147 }
148
149 // Has returns true if the given name references a type known to this package.
150 func (p *Package) Has(name string) bool {
151 _, has := p.Types[name]
152 return has
153 }
154
155 // Type gets the given Type in this Package. If the Type is not already
156 // defined, this will add it and return the new Type value. The caller is
157 // expected to finish initialization.
158 func (p *Package) Type(typeName string) *Type {
159 if t, ok := p.Types[typeName]; ok {
160 return t
161 }
162 if p.Path == "" {
163 // Import the standard builtin types!
164 if t, ok := builtins.Types[typeName]; ok {
165 p.Types[typeName] = t
166 return t
167 }
168 }
169 t := &Type{Name: Name{Package: p.Path, Name: typeName}}
170 p.Types[typeName] = t
171 return t
172 }
173
174 // Function gets the given function Type in this Package. If the function is
175 // not already defined, this will add it. If a function is added, it's the
176 // caller's responsibility to finish construction of the function by setting
177 // Underlying to the correct type.
178 func (p *Package) Function(funcName string) *Type {
179 if t, ok := p.Functions[funcName]; ok {
180 return t
181 }
182 t := &Type{Name: Name{Package: p.Path, Name: funcName}}
183 t.Kind = DeclarationOf
184 p.Functions[funcName] = t
185 return t
186 }
187
188 // Variable gets the given variable Type in this Package. If the variable is
189 // not already defined, this will add it. If a variable is added, it's the caller's
190 // responsibility to finish construction of the variable by setting Underlying
191 // to the correct type.
192 func (p *Package) Variable(varName string) *Type {
193 if t, ok := p.Variables[varName]; ok {
194 return t
195 }
196 t := &Type{Name: Name{Package: p.Path, Name: varName}}
197 t.Kind = DeclarationOf
198 p.Variables[varName] = t
199 return t
200 }
201
202 // Constant gets the given constant Type in this Package. If the constant is
203 // not already defined, this will add it. If a constant is added, it's the caller's
204 // responsibility to finish construction of the constant by setting Underlying
205 // to the correct type.
206 func (p *Package) Constant(constName string) *Type {
207 if t, ok := p.Constants[constName]; ok {
208 return t
209 }
210 t := &Type{Name: Name{Package: p.Path, Name: constName}}
211 t.Kind = DeclarationOf
212 p.Constants[constName] = t
213 return t
214 }
215
216 // HasImport returns true if p imports packageName. Package names include the
217 // package directory.
218 func (p *Package) HasImport(packageName string) bool {
219 _, has := p.Imports[packageName]
220 return has
221 }
222
223 // Universe is a map of all packages. The key is the package name, but you
224 // should use Package(), Type(), Function(), or Variable() instead of direct
225 // access.
226 type Universe map[string]*Package
227
228 // Type returns the canonical type for the given fully-qualified name. Builtin
229 // types will always be found, even if they haven't been explicitly added to
230 // the map. If a non-existing type is requested, this will create (a marker for)
231 // it.
232 func (u Universe) Type(n Name) *Type {
233 return u.Package(n.Package).Type(n.Name)
234 }
235
236 // Function returns the canonical function for the given fully-qualified name.
237 // If a non-existing function is requested, this will create (a marker for) it.
238 // If a marker is created, it's the caller's responsibility to finish
239 // construction of the function by setting Underlying to the correct type.
240 func (u Universe) Function(n Name) *Type {
241 return u.Package(n.Package).Function(n.Name)
242 }
243
244 // Variable returns the canonical variable for the given fully-qualified name.
245 // If a non-existing variable is requested, this will create (a marker for) it.
246 // If a marker is created, it's the caller's responsibility to finish
247 // construction of the variable by setting Underlying to the correct type.
248 func (u Universe) Variable(n Name) *Type {
249 return u.Package(n.Package).Variable(n.Name)
250 }
251
252 // Constant returns the canonical constant for the given fully-qualified name.
253 // If a non-existing constant is requested, this will create (a marker for) it.
254 // If a marker is created, it's the caller's responsibility to finish
255 // construction of the constant by setting Underlying to the correct type.
256 func (u Universe) Constant(n Name) *Type {
257 return u.Package(n.Package).Constant(n.Name)
258 }
259
260 // AddImports registers import lines for packageName. May be called multiple times.
261 // You are responsible for canonicalizing all package paths.
262 func (u Universe) AddImports(packagePath string, importPaths ...string) {
263 p := u.Package(packagePath)
264 for _, i := range importPaths {
265 p.Imports[i] = u.Package(i)
266 }
267 }
268
269 // Package returns the Package for the given path.
270 // If a non-existing package is requested, this will create (a marker for) it.
271 // If a marker is created, it's the caller's responsibility to finish
272 // construction of the package.
273 func (u Universe) Package(packagePath string) *Package {
274 if p, ok := u[packagePath]; ok {
275 return p
276 }
277 p := &Package{
278 Path: packagePath,
279 Types: map[string]*Type{},
280 Functions: map[string]*Type{},
281 Variables: map[string]*Type{},
282 Constants: map[string]*Type{},
283 Imports: map[string]*Package{},
284 }
285 u[packagePath] = p
286 return p
287 }
288
289 // Type represents a subset of possible go types.
290 type Type struct {
291 // There are two general categories of types, those explicitly named
292 // and those anonymous. Named ones will have a non-empty package in the
293 // name field.
294 //
295 // An exception: If Kind == DeclarationOf, then this name is the name of a
296 // top-level function, variable, or const, and the type can be found in Underlying.
297 // We do this to allow the naming system to work against these objects, even
298 // though they aren't strictly speaking types.
299 Name Name
300
301 // The general kind of this type.
302 Kind Kind
303
304 // If there are comment lines immediately before the type definition,
305 // they will be recorded here.
306 CommentLines []string
307
308 // If there are comment lines preceding the `CommentLines`, they will be
309 // recorded here. There are two cases:
310 // ---
311 // SecondClosestCommentLines
312 // a blank line
313 // CommentLines
314 // type definition
315 // ---
316 //
317 // or
318 // ---
319 // SecondClosestCommentLines
320 // a blank line
321 // type definition
322 // ---
323 SecondClosestCommentLines []string
324
325 // If Kind == Struct
326 Members []Member
327
328 // If Kind == Map, Slice, Pointer, or Chan
329 Elem *Type
330
331 // If Kind == Map, this is the map's key type.
332 Key *Type
333
334 // If Kind == Alias, this is the underlying type.
335 // If Kind == DeclarationOf, this is the type of the declaration.
336 Underlying *Type
337
338 // If Kind == Interface, this is the set of all required functions.
339 // Otherwise, if this is a named type, this is the list of methods that
340 // type has. (All elements will have Kind=="Func")
341 Methods map[string]*Type
342
343 // If Kind == func, this is the signature of the function.
344 Signature *Signature
345
346 // ConstValue contains a stringified constant value if
347 // Kind == DeclarationOf and this is a constant value
348 // declaration. For string constants, this field contains
349 // the entire, un-quoted value. For other types, it contains
350 // a human-readable literal.
351 ConstValue *string
352
353 // TODO: Add:
354 // * channel direction
355
356 // If Kind == Array
357 Len int64
358 }
359
360 // String returns the name of the type.
361 func (t *Type) String() string {
362 return t.Name.String()
363 }
364
365 // IsPrimitive returns whether the type is a built-in type or is an alias to a
366 // built-in type. For example: strings and aliases of strings are primitives,
367 // structs are not.
368 func (t *Type) IsPrimitive() bool {
369 if t.Kind == Builtin || (t.Kind == Alias && t.Underlying.Kind == Builtin) {
370 return true
371 }
372 return false
373 }
374
375 // IsAssignable returns whether the type is deep-assignable. For example,
376 // slices and maps and pointers are shallow copies, but ints and strings are
377 // complete.
378 func (t *Type) IsAssignable() bool {
379 if t.IsPrimitive() {
380 return true
381 }
382 if t.Kind == Struct {
383 for _, m := range t.Members {
384 if !m.Type.IsAssignable() {
385 return false
386 }
387 }
388 return true
389 }
390 return false
391 }
392
393 // IsAnonymousStruct returns true if the type is an anonymous struct or an alias
394 // to an anonymous struct.
395 func (t *Type) IsAnonymousStruct() bool {
396 return (t.Kind == Struct && t.Name.Name == "struct{}") || (t.Kind == Alias && t.Underlying.IsAnonymousStruct())
397 }
398
399 // A single struct member
400 type Member struct {
401 // The name of the member.
402 Name string
403
404 // If the member is embedded (anonymous) this will be true, and the
405 // Name will be the type name.
406 Embedded bool
407
408 // If there are comment lines immediately before the member in the type
409 // definition, they will be recorded here.
410 CommentLines []string
411
412 // If there are tags along with this member, they will be saved here.
413 Tags string
414
415 // The type of this member.
416 Type *Type
417 }
418
419 // String returns the name and type of the member.
420 func (m Member) String() string {
421 return m.Name + " " + m.Type.String()
422 }
423
424 // Signature is a function's signature.
425 type Signature struct {
426 // If a method of some type, this is the type it's a member of.
427 Receiver *Type
428 Parameters []*Type
429 ParameterNames []string
430 Results []*Type
431 ResultNames []string
432
433 // True if the last in parameter is of the form ...T.
434 Variadic bool
435
436 // If there are comment lines immediately before this
437 // signature/method/function declaration, they will be recorded here.
438 CommentLines []string
439 }
440
441 // Built in types.
442 var (
443 String = &Type{
444 Name: Name{Name: "string"},
445 Kind: Builtin,
446 }
447 Int64 = &Type{
448 Name: Name{Name: "int64"},
449 Kind: Builtin,
450 }
451 Int32 = &Type{
452 Name: Name{Name: "int32"},
453 Kind: Builtin,
454 }
455 Int16 = &Type{
456 Name: Name{Name: "int16"},
457 Kind: Builtin,
458 }
459 Int = &Type{
460 Name: Name{Name: "int"},
461 Kind: Builtin,
462 }
463 Uint64 = &Type{
464 Name: Name{Name: "uint64"},
465 Kind: Builtin,
466 }
467 Uint32 = &Type{
468 Name: Name{Name: "uint32"},
469 Kind: Builtin,
470 }
471 Uint16 = &Type{
472 Name: Name{Name: "uint16"},
473 Kind: Builtin,
474 }
475 Uint = &Type{
476 Name: Name{Name: "uint"},
477 Kind: Builtin,
478 }
479 Uintptr = &Type{
480 Name: Name{Name: "uintptr"},
481 Kind: Builtin,
482 }
483 Float64 = &Type{
484 Name: Name{Name: "float64"},
485 Kind: Builtin,
486 }
487 Float32 = &Type{
488 Name: Name{Name: "float32"},
489 Kind: Builtin,
490 }
491 Float = &Type{
492 Name: Name{Name: "float"},
493 Kind: Builtin,
494 }
495 Bool = &Type{
496 Name: Name{Name: "bool"},
497 Kind: Builtin,
498 }
499 Byte = &Type{
500 Name: Name{Name: "byte"},
501 Kind: Builtin,
502 }
503
504 builtins = &Package{
505 Types: map[string]*Type{
506 "bool": Bool,
507 "string": String,
508 "int": Int,
509 "int64": Int64,
510 "int32": Int32,
511 "int16": Int16,
512 "int8": Byte,
513 "uint": Uint,
514 "uint64": Uint64,
515 "uint32": Uint32,
516 "uint16": Uint16,
517 "uint8": Byte,
518 "uintptr": Uintptr,
519 "byte": Byte,
520 "float": Float,
521 "float64": Float64,
522 "float32": Float32,
523 },
524 Imports: map[string]*Package{},
525 Path: "",
526 Name: "",
527 }
528 )
529
530 func IsInteger(t *Type) bool {
531 switch t {
532 case Int, Int64, Int32, Int16, Uint, Uint64, Uint32, Uint16, Byte:
533 return true
534 default:
535 return false
536 }
537 }