1 // Copyright 2011 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
7 // A Type represents a type of Go.
8 // All types implement the Type interface.
10 // Underlying returns the underlying type of a type.
13 // String returns a string representation of a type.
17 // BasicKind describes the kind of basic type.
21 Invalid BasicKind = iota // type is invalid
43 // types for untyped values
57 // BasicInfo is a set of flags describing properties of a basic type.
60 // Properties of basic types.
62 IsBoolean BasicInfo = 1 << iota
70 IsOrdered = IsInteger | IsFloat | IsString
71 IsNumeric = IsInteger | IsFloat | IsComplex
72 IsConstType = IsBoolean | IsNumeric | IsString
75 // A Basic represents a basic type.
82 // Kind returns the kind of basic type b.
83 func (b *Basic) Kind() BasicKind { return b.kind }
85 // Info returns information about properties of basic type b.
86 func (b *Basic) Info() BasicInfo { return b.info }
88 // Name returns the name of basic type b.
89 func (b *Basic) Name() string { return b.name }
91 // An Array represents an array type.
97 // NewArray returns a new array type for the given element type and length.
98 // A negative length indicates an unknown length.
99 func NewArray(elem Type, len int64) *Array { return &Array{len, elem} }
101 // Len returns the length of array a.
102 // A negative result indicates an unknown length.
103 func (a *Array) Len() int64 { return a.len }
105 // Elem returns element type of array a.
106 func (a *Array) Elem() Type { return a.elem }
108 // A Slice represents a slice type.
113 // NewSlice returns a new slice type for the given element type.
114 func NewSlice(elem Type) *Slice { return &Slice{elem} }
116 // Elem returns the element type of slice s.
117 func (s *Slice) Elem() Type { return s.elem }
119 // A Struct represents a struct type.
122 tags []string // field tags; nil if there are no tags
125 // NewStruct returns a new struct with the given fields and corresponding field tags.
126 // If a field with index i has a tag, tags[i] must be that tag, but len(tags) may be
127 // only as long as required to hold the tag with the largest index i. Consequently,
128 // if no field has a tag, tags may be nil.
129 func NewStruct(fields []*Var, tags []string) *Struct {
131 for _, f := range fields {
132 if f.name != "_" && fset.insert(f) != nil {
133 panic("multiple fields with the same name")
136 if len(tags) > len(fields) {
137 panic("more tags than fields")
139 return &Struct{fields: fields, tags: tags}
142 // NumFields returns the number of fields in the struct (including blank and embedded fields).
143 func (s *Struct) NumFields() int { return len(s.fields) }
145 // Field returns the i'th field for 0 <= i < NumFields().
146 func (s *Struct) Field(i int) *Var { return s.fields[i] }
148 // Tag returns the i'th field tag for 0 <= i < NumFields().
149 func (s *Struct) Tag(i int) string {
156 // A Pointer represents a pointer type.
157 type Pointer struct {
158 base Type // element type
161 // NewPointer returns a new pointer type for the given element (base) type.
162 func NewPointer(elem Type) *Pointer { return &Pointer{base: elem} }
164 // Elem returns the element type for the given pointer p.
165 func (p *Pointer) Elem() Type { return p.base }
167 // A Tuple represents an ordered list of variables; a nil *Tuple is a valid (empty) tuple.
168 // Tuples are used as components of signatures and to represent the type of multiple
169 // assignments; they are not first class types of Go.
174 // NewTuple returns a new tuple for the given variables.
175 func NewTuple(x ...*Var) *Tuple {
182 // Len returns the number variables of tuple t.
183 func (t *Tuple) Len() int {
190 // At returns the i'th variable of tuple t.
191 func (t *Tuple) At(i int) *Var { return t.vars[i] }
193 // A Signature represents a (non-builtin) function or method type.
194 // The receiver is ignored when comparing signatures for identity.
195 type Signature struct {
196 // We need to keep the scope in Signature (rather than passing it around
197 // and store it in the Func Object) because when type-checking a function
198 // literal we call the general type checker which returns a general Type.
199 // We then unpack the *Signature and use the scope for the literal body.
200 scope *Scope // function scope, present for package-local signatures
201 recv *Var // nil if not a method
202 params *Tuple // (incoming) parameters from left to right; or nil
203 results *Tuple // (outgoing) results from left to right; or nil
204 variadic bool // true if the last parameter's type is of the form ...T (or string, for append built-in only)
207 // NewSignature returns a new function type for the given receiver, parameters,
208 // and results, either of which may be nil. If variadic is set, the function
209 // is variadic, it must have at least one parameter, and the last parameter
210 // must be of unnamed slice type.
211 func NewSignature(recv *Var, params, results *Tuple, variadic bool) *Signature {
215 panic("types.NewSignature: variadic function must have at least one parameter")
217 if _, ok := params.At(n - 1).typ.(*Slice); !ok {
218 panic("types.NewSignature: variadic parameter must be of unnamed slice type")
221 return &Signature{nil, recv, params, results, variadic}
224 // Recv returns the receiver of signature s (if a method), or nil if a
225 // function. It is ignored when comparing signatures for identity.
227 // For an abstract method, Recv returns the enclosing interface either
228 // as a *Named or an *Interface. Due to embedding, an interface may
229 // contain methods whose receiver type is a different interface.
230 func (s *Signature) Recv() *Var { return s.recv }
232 // Params returns the parameters of signature s, or nil.
233 func (s *Signature) Params() *Tuple { return s.params }
235 // Results returns the results of signature s, or nil.
236 func (s *Signature) Results() *Tuple { return s.results }
238 // Variadic reports whether the signature s is variadic.
239 func (s *Signature) Variadic() bool { return s.variadic }
241 // An Interface represents an interface type.
242 type Interface struct {
243 methods []*Func // ordered list of explicitly declared methods
244 embeddeds []Type // ordered list of explicitly embedded types
246 allMethods []*Func // ordered list of methods declared with or embedded in this interface (TODO(gri): replace with mset)
249 // emptyInterface represents the empty (completed) interface
250 var emptyInterface = Interface{allMethods: markComplete}
252 // markComplete is used to mark an empty interface as completely
253 // set up by setting the allMethods field to a non-nil empty slice.
254 var markComplete = make([]*Func, 0)
256 // NewInterface returns a new (incomplete) interface for the given methods and embedded types.
257 // Each embedded type must have an underlying type of interface type.
258 // NewInterface takes ownership of the provided methods and may modify their types by setting
259 // missing receivers. To compute the method set of the interface, Complete must be called.
261 // Deprecated: Use NewInterfaceType instead which allows any (even non-defined) interface types
262 // to be embedded. This is necessary for interfaces that embed alias type names referring to
263 // non-defined (literal) interface types.
264 func NewInterface(methods []*Func, embeddeds []*Named) *Interface {
265 tnames := make([]Type, len(embeddeds))
266 for i, t := range embeddeds {
269 return NewInterfaceType(methods, tnames)
272 // NewInterfaceType returns a new (incomplete) interface for the given methods and embedded types.
273 // Each embedded type must have an underlying type of interface type (this property is not
274 // verified for defined types, which may be in the process of being set up and which don't
275 // have a valid underlying type yet).
276 // NewInterfaceType takes ownership of the provided methods and may modify their types by setting
277 // missing receivers. To compute the method set of the interface, Complete must be called.
278 func NewInterfaceType(methods []*Func, embeddeds []Type) *Interface {
279 if len(methods) == 0 && len(embeddeds) == 0 {
280 return &emptyInterface
283 // set method receivers if necessary
284 typ := new(Interface)
285 for _, m := range methods {
286 if sig := m.typ.(*Signature); sig.recv == nil {
287 sig.recv = NewVar(m.pos, m.pkg, "", typ)
291 // All embedded types should be interfaces; however, defined types
292 // may not yet be fully resolved. Only verify that non-defined types
293 // are interfaces. This matches the behavior of the code before the
294 // fix for #25301 (issue #25596).
295 for _, t := range embeddeds {
296 if _, ok := t.(*Named); !ok && !IsInterface(t) {
297 panic("embedded type is not an interface")
301 // sort for API stability
305 typ.methods = methods
306 typ.embeddeds = embeddeds
310 // NumExplicitMethods returns the number of explicitly declared methods of interface t.
311 func (t *Interface) NumExplicitMethods() int { return len(t.methods) }
313 // ExplicitMethod returns the i'th explicitly declared method of interface t for 0 <= i < t.NumExplicitMethods().
314 // The methods are ordered by their unique Id.
315 func (t *Interface) ExplicitMethod(i int) *Func { return t.methods[i] }
317 // NumEmbeddeds returns the number of embedded types in interface t.
318 func (t *Interface) NumEmbeddeds() int { return len(t.embeddeds) }
320 // Embedded returns the i'th embedded defined (*Named) type of interface t for 0 <= i < t.NumEmbeddeds().
321 // The result is nil if the i'th embedded type is not a defined type.
323 // Deprecated: Use EmbeddedType which is not restricted to defined (*Named) types.
324 func (t *Interface) Embedded(i int) *Named { tname, _ := t.embeddeds[i].(*Named); return tname }
326 // EmbeddedType returns the i'th embedded type of interface t for 0 <= i < t.NumEmbeddeds().
327 func (t *Interface) EmbeddedType(i int) Type { return t.embeddeds[i] }
329 // NumMethods returns the total number of methods of interface t.
330 // The interface must have been completed.
331 func (t *Interface) NumMethods() int { t.assertCompleteness(); return len(t.allMethods) }
333 func (t *Interface) assertCompleteness() {
334 if t.allMethods == nil {
335 panic("interface is incomplete")
339 // Method returns the i'th method of interface t for 0 <= i < t.NumMethods().
340 // The methods are ordered by their unique Id.
341 // The interface must have been completed.
342 func (t *Interface) Method(i int) *Func { t.assertCompleteness(); return t.allMethods[i] }
344 // Empty reports whether t is the empty interface.
345 // The interface must have been completed.
346 func (t *Interface) Empty() bool { t.assertCompleteness(); return len(t.allMethods) == 0 }
348 // Complete computes the interface's method set. It must be called by users of
349 // NewInterfaceType and NewInterface after the interface's embedded types are
350 // fully defined and before using the interface type in any way other than to
351 // form other types. The interface must not contain duplicate methods or a
352 // panic occurs. Complete returns the receiver.
353 func (t *Interface) Complete() *Interface {
354 // TODO(gri) consolidate this method with Checker.completeInterface
355 if t.allMethods != nil {
359 t.allMethods = markComplete // avoid infinite recursion
364 addMethod := func(m *Func, explicit bool) {
365 switch other := seen.insert(m); {
367 methods = append(methods, m)
369 panic("duplicate method " + m.name)
371 // check method signatures after all locally embedded interfaces are computed
372 todo = append(todo, m, other.(*Func))
376 for _, m := range t.methods {
380 for _, typ := range t.embeddeds {
381 typ := typ.Underlying().(*Interface)
383 for _, m := range typ.allMethods {
388 for i := 0; i < len(todo); i += 2 {
391 if !Identical(m.typ, other.typ) {
392 panic("duplicate method " + m.name)
398 t.allMethods = methods
404 // A Map represents a map type.
409 // NewMap returns a new map for the given key and element types.
410 func NewMap(key, elem Type) *Map {
411 return &Map{key, elem}
414 // Key returns the key type of map m.
415 func (m *Map) Key() Type { return m.key }
417 // Elem returns the element type of map m.
418 func (m *Map) Elem() Type { return m.elem }
420 // A Chan represents a channel type.
426 // A ChanDir value indicates a channel direction.
429 // The direction of a channel is indicated by one of these constants.
431 SendRecv ChanDir = iota
436 // NewChan returns a new channel type for the given direction and element type.
437 func NewChan(dir ChanDir, elem Type) *Chan {
438 return &Chan{dir, elem}
441 // Dir returns the direction of channel c.
442 func (c *Chan) Dir() ChanDir { return c.dir }
444 // Elem returns the element type of channel c.
445 func (c *Chan) Elem() Type { return c.elem }
447 // A Named represents a named type.
449 info typeInfo // for cycle detection
450 obj *TypeName // corresponding declared object
451 orig Type // type (on RHS of declaration) this *Named type is derived of (for cycle reporting)
452 underlying Type // possibly a *Named during setup; never a *Named once set up completely
453 methods []*Func // methods declared for this type (not the method set of this type); signatures are type-checked lazily
456 // NewNamed returns a new named type for the given type name, underlying type, and associated methods.
457 // If the given type name obj doesn't have a type yet, its type is set to the returned named type.
458 // The underlying type must not be a *Named.
459 func NewNamed(obj *TypeName, underlying Type, methods []*Func) *Named {
460 if _, ok := underlying.(*Named); ok {
461 panic("types.NewNamed: underlying type must not be *Named")
463 typ := &Named{obj: obj, orig: underlying, underlying: underlying, methods: methods}
470 // Obj returns the type name for the named type t.
471 func (t *Named) Obj() *TypeName { return t.obj }
473 // NumMethods returns the number of explicit methods whose receiver is named type t.
474 func (t *Named) NumMethods() int { return len(t.methods) }
476 // Method returns the i'th method of named type t for 0 <= i < t.NumMethods().
477 func (t *Named) Method(i int) *Func { return t.methods[i] }
479 // SetUnderlying sets the underlying type and marks t as complete.
480 func (t *Named) SetUnderlying(underlying Type) {
481 if underlying == nil {
482 panic("types.Named.SetUnderlying: underlying type must not be nil")
484 if _, ok := underlying.(*Named); ok {
485 panic("types.Named.SetUnderlying: underlying type must not be *Named")
487 t.underlying = underlying
490 // AddMethod adds method m unless it is already in the method list.
491 func (t *Named) AddMethod(m *Func) {
492 if i, _ := lookupMethod(t.methods, m.pkg, m.name); i < 0 {
493 t.methods = append(t.methods, m)
497 // Implementations for Type methods.
499 func (b *Basic) Underlying() Type { return b }
500 func (a *Array) Underlying() Type { return a }
501 func (s *Slice) Underlying() Type { return s }
502 func (s *Struct) Underlying() Type { return s }
503 func (p *Pointer) Underlying() Type { return p }
504 func (t *Tuple) Underlying() Type { return t }
505 func (s *Signature) Underlying() Type { return s }
506 func (t *Interface) Underlying() Type { return t }
507 func (m *Map) Underlying() Type { return m }
508 func (c *Chan) Underlying() Type { return c }
509 func (t *Named) Underlying() Type { return t.underlying }
511 func (b *Basic) String() string { return TypeString(b, nil) }
512 func (a *Array) String() string { return TypeString(a, nil) }
513 func (s *Slice) String() string { return TypeString(s, nil) }
514 func (s *Struct) String() string { return TypeString(s, nil) }
515 func (p *Pointer) String() string { return TypeString(p, nil) }
516 func (t *Tuple) String() string { return TypeString(t, nil) }
517 func (s *Signature) String() string { return TypeString(s, nil) }
518 func (t *Interface) String() string { return TypeString(t, nil) }
519 func (m *Map) String() string { return TypeString(m, nil) }
520 func (c *Chan) String() string { return TypeString(c, nil) }
521 func (t *Named) String() string { return TypeString(t, nil) }