Debian Codegraph @

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