Black Lives Matter. Support the Equal Justice Initiative.

Source file src/go/types/type.go

Documentation: go/types

     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.
     4  
     5  package types
     6  
     7  import "sort"
     8  
     9  // A Type represents a type of Go.
    10  // All types implement the Type interface.
    11  type Type interface {
    12  	// Underlying returns the underlying type of a type.
    13  	Underlying() Type
    14  
    15  	// String returns a string representation of a type.
    16  	String() string
    17  }
    18  
    19  // BasicKind describes the kind of basic type.
    20  type BasicKind int
    21  
    22  const (
    23  	Invalid BasicKind = iota // type is invalid
    24  
    25  	// predeclared types
    26  	Bool
    27  	Int
    28  	Int8
    29  	Int16
    30  	Int32
    31  	Int64
    32  	Uint
    33  	Uint8
    34  	Uint16
    35  	Uint32
    36  	Uint64
    37  	Uintptr
    38  	Float32
    39  	Float64
    40  	Complex64
    41  	Complex128
    42  	String
    43  	UnsafePointer
    44  
    45  	// types for untyped values
    46  	UntypedBool
    47  	UntypedInt
    48  	UntypedRune
    49  	UntypedFloat
    50  	UntypedComplex
    51  	UntypedString
    52  	UntypedNil
    53  
    54  	// aliases
    55  	Byte = Uint8
    56  	Rune = Int32
    57  )
    58  
    59  // BasicInfo is a set of flags describing properties of a basic type.
    60  type BasicInfo int
    61  
    62  // Properties of basic types.
    63  const (
    64  	IsBoolean BasicInfo = 1 << iota
    65  	IsInteger
    66  	IsUnsigned
    67  	IsFloat
    68  	IsComplex
    69  	IsString
    70  	IsUntyped
    71  
    72  	IsOrdered   = IsInteger | IsFloat | IsString
    73  	IsNumeric   = IsInteger | IsFloat | IsComplex
    74  	IsConstType = IsBoolean | IsNumeric | IsString
    75  )
    76  
    77  // A Basic represents a basic type.
    78  type Basic struct {
    79  	kind BasicKind
    80  	info BasicInfo
    81  	name string
    82  }
    83  
    84  // Kind returns the kind of basic type b.
    85  func (b *Basic) Kind() BasicKind { return b.kind }
    86  
    87  // Info returns information about properties of basic type b.
    88  func (b *Basic) Info() BasicInfo { return b.info }
    89  
    90  // Name returns the name of basic type b.
    91  func (b *Basic) Name() string { return b.name }
    92  
    93  // An Array represents an array type.
    94  type Array struct {
    95  	len  int64
    96  	elem Type
    97  }
    98  
    99  // NewArray returns a new array type for the given element type and length.
   100  // A negative length indicates an unknown length.
   101  func NewArray(elem Type, len int64) *Array { return &Array{len, elem} }
   102  
   103  // Len returns the length of array a.
   104  // A negative result indicates an unknown length.
   105  func (a *Array) Len() int64 { return a.len }
   106  
   107  // Elem returns element type of array a.
   108  func (a *Array) Elem() Type { return a.elem }
   109  
   110  // A Slice represents a slice type.
   111  type Slice struct {
   112  	elem Type
   113  }
   114  
   115  // NewSlice returns a new slice type for the given element type.
   116  func NewSlice(elem Type) *Slice { return &Slice{elem} }
   117  
   118  // Elem returns the element type of slice s.
   119  func (s *Slice) Elem() Type { return s.elem }
   120  
   121  // A Struct represents a struct type.
   122  type Struct struct {
   123  	fields []*Var
   124  	tags   []string // field tags; nil if there are no tags
   125  }
   126  
   127  // NewStruct returns a new struct with the given fields and corresponding field tags.
   128  // If a field with index i has a tag, tags[i] must be that tag, but len(tags) may be
   129  // only as long as required to hold the tag with the largest index i. Consequently,
   130  // if no field has a tag, tags may be nil.
   131  func NewStruct(fields []*Var, tags []string) *Struct {
   132  	var fset objset
   133  	for _, f := range fields {
   134  		if f.name != "_" && fset.insert(f) != nil {
   135  			panic("multiple fields with the same name")
   136  		}
   137  	}
   138  	if len(tags) > len(fields) {
   139  		panic("more tags than fields")
   140  	}
   141  	return &Struct{fields: fields, tags: tags}
   142  }
   143  
   144  // NumFields returns the number of fields in the struct (including blank and embedded fields).
   145  func (s *Struct) NumFields() int { return len(s.fields) }
   146  
   147  // Field returns the i'th field for 0 <= i < NumFields().
   148  func (s *Struct) Field(i int) *Var { return s.fields[i] }
   149  
   150  // Tag returns the i'th field tag for 0 <= i < NumFields().
   151  func (s *Struct) Tag(i int) string {
   152  	if i < len(s.tags) {
   153  		return s.tags[i]
   154  	}
   155  	return ""
   156  }
   157  
   158  // A Pointer represents a pointer type.
   159  type Pointer struct {
   160  	base Type // element type
   161  }
   162  
   163  // NewPointer returns a new pointer type for the given element (base) type.
   164  func NewPointer(elem Type) *Pointer { return &Pointer{base: elem} }
   165  
   166  // Elem returns the element type for the given pointer p.
   167  func (p *Pointer) Elem() Type { return p.base }
   168  
   169  // A Tuple represents an ordered list of variables; a nil *Tuple is a valid (empty) tuple.
   170  // Tuples are used as components of signatures and to represent the type of multiple
   171  // assignments; they are not first class types of Go.
   172  type Tuple struct {
   173  	vars []*Var
   174  }
   175  
   176  // NewTuple returns a new tuple for the given variables.
   177  func NewTuple(x ...*Var) *Tuple {
   178  	if len(x) > 0 {
   179  		return &Tuple{x}
   180  	}
   181  	return nil
   182  }
   183  
   184  // Len returns the number variables of tuple t.
   185  func (t *Tuple) Len() int {
   186  	if t != nil {
   187  		return len(t.vars)
   188  	}
   189  	return 0
   190  }
   191  
   192  // At returns the i'th variable of tuple t.
   193  func (t *Tuple) At(i int) *Var { return t.vars[i] }
   194  
   195  // A Signature represents a (non-builtin) function or method type.
   196  // The receiver is ignored when comparing signatures for identity.
   197  type Signature struct {
   198  	// We need to keep the scope in Signature (rather than passing it around
   199  	// and store it in the Func Object) because when type-checking a function
   200  	// literal we call the general type checker which returns a general Type.
   201  	// We then unpack the *Signature and use the scope for the literal body.
   202  	scope    *Scope // function scope, present for package-local signatures
   203  	recv     *Var   // nil if not a method
   204  	params   *Tuple // (incoming) parameters from left to right; or nil
   205  	results  *Tuple // (outgoing) results from left to right; or nil
   206  	variadic bool   // true if the last parameter's type is of the form ...T (or string, for append built-in only)
   207  }
   208  
   209  // NewSignature returns a new function type for the given receiver, parameters,
   210  // and results, either of which may be nil. If variadic is set, the function
   211  // is variadic, it must have at least one parameter, and the last parameter
   212  // must be of unnamed slice type.
   213  func NewSignature(recv *Var, params, results *Tuple, variadic bool) *Signature {
   214  	if variadic {
   215  		n := params.Len()
   216  		if n == 0 {
   217  			panic("types.NewSignature: variadic function must have at least one parameter")
   218  		}
   219  		if _, ok := params.At(n - 1).typ.(*Slice); !ok {
   220  			panic("types.NewSignature: variadic parameter must be of unnamed slice type")
   221  		}
   222  	}
   223  	return &Signature{nil, recv, params, results, variadic}
   224  }
   225  
   226  // Recv returns the receiver of signature s (if a method), or nil if a
   227  // function. It is ignored when comparing signatures for identity.
   228  //
   229  // For an abstract method, Recv returns the enclosing interface either
   230  // as a *Named or an *Interface. Due to embedding, an interface may
   231  // contain methods whose receiver type is a different interface.
   232  func (s *Signature) Recv() *Var { return s.recv }
   233  
   234  // Params returns the parameters of signature s, or nil.
   235  func (s *Signature) Params() *Tuple { return s.params }
   236  
   237  // Results returns the results of signature s, or nil.
   238  func (s *Signature) Results() *Tuple { return s.results }
   239  
   240  // Variadic reports whether the signature s is variadic.
   241  func (s *Signature) Variadic() bool { return s.variadic }
   242  
   243  // An Interface represents an interface type.
   244  type Interface struct {
   245  	methods   []*Func // ordered list of explicitly declared methods
   246  	embeddeds []Type  // ordered list of explicitly embedded types
   247  
   248  	allMethods []*Func // ordered list of methods declared with or embedded in this interface (TODO(gri): replace with mset)
   249  }
   250  
   251  // emptyInterface represents the empty (completed) interface
   252  var emptyInterface = Interface{allMethods: markComplete}
   253  
   254  // markComplete is used to mark an empty interface as completely
   255  // set up by setting the allMethods field to a non-nil empty slice.
   256  var markComplete = make([]*Func, 0)
   257  
   258  // NewInterface returns a new (incomplete) interface for the given methods and embedded types.
   259  // Each embedded type must have an underlying type of interface type.
   260  // NewInterface takes ownership of the provided methods and may modify their types by setting
   261  // missing receivers. To compute the method set of the interface, Complete must be called.
   262  //
   263  // Deprecated: Use NewInterfaceType instead which allows any (even non-defined) interface types
   264  // to be embedded. This is necessary for interfaces that embed alias type names referring to
   265  // non-defined (literal) interface types.
   266  func NewInterface(methods []*Func, embeddeds []*Named) *Interface {
   267  	tnames := make([]Type, len(embeddeds))
   268  	for i, t := range embeddeds {
   269  		tnames[i] = t
   270  	}
   271  	return NewInterfaceType(methods, tnames)
   272  }
   273  
   274  // NewInterfaceType returns a new (incomplete) interface for the given methods and embedded types.
   275  // Each embedded type must have an underlying type of interface type (this property is not
   276  // verified for defined types, which may be in the process of being set up and which don't
   277  // have a valid underlying type yet).
   278  // NewInterfaceType takes ownership of the provided methods and may modify their types by setting
   279  // missing receivers. To compute the method set of the interface, Complete must be called.
   280  func NewInterfaceType(methods []*Func, embeddeds []Type) *Interface {
   281  	if len(methods) == 0 && len(embeddeds) == 0 {
   282  		return &emptyInterface
   283  	}
   284  
   285  	// set method receivers if necessary
   286  	typ := new(Interface)
   287  	for _, m := range methods {
   288  		if sig := m.typ.(*Signature); sig.recv == nil {
   289  			sig.recv = NewVar(m.pos, m.pkg, "", typ)
   290  		}
   291  	}
   292  
   293  	// All embedded types should be interfaces; however, defined types
   294  	// may not yet be fully resolved. Only verify that non-defined types
   295  	// are interfaces. This matches the behavior of the code before the
   296  	// fix for #25301 (issue #25596).
   297  	for _, t := range embeddeds {
   298  		if _, ok := t.(*Named); !ok && !IsInterface(t) {
   299  			panic("embedded type is not an interface")
   300  		}
   301  	}
   302  
   303  	// sort for API stability
   304  	sort.Sort(byUniqueMethodName(methods))
   305  	sort.Stable(byUniqueTypeName(embeddeds))
   306  
   307  	typ.methods = methods
   308  	typ.embeddeds = embeddeds
   309  	return typ
   310  }
   311  
   312  // NumExplicitMethods returns the number of explicitly declared methods of interface t.
   313  func (t *Interface) NumExplicitMethods() int { return len(t.methods) }
   314  
   315  // ExplicitMethod returns the i'th explicitly declared method of interface t for 0 <= i < t.NumExplicitMethods().
   316  // The methods are ordered by their unique Id.
   317  func (t *Interface) ExplicitMethod(i int) *Func { return t.methods[i] }
   318  
   319  // NumEmbeddeds returns the number of embedded types in interface t.
   320  func (t *Interface) NumEmbeddeds() int { return len(t.embeddeds) }
   321  
   322  // Embedded returns the i'th embedded defined (*Named) type of interface t for 0 <= i < t.NumEmbeddeds().
   323  // The result is nil if the i'th embedded type is not a defined type.
   324  //
   325  // Deprecated: Use EmbeddedType which is not restricted to defined (*Named) types.
   326  func (t *Interface) Embedded(i int) *Named { tname, _ := t.embeddeds[i].(*Named); return tname }
   327  
   328  // EmbeddedType returns the i'th embedded type of interface t for 0 <= i < t.NumEmbeddeds().
   329  func (t *Interface) EmbeddedType(i int) Type { return t.embeddeds[i] }
   330  
   331  // NumMethods returns the total number of methods of interface t.
   332  // The interface must have been completed.
   333  func (t *Interface) NumMethods() int { t.assertCompleteness(); return len(t.allMethods) }
   334  
   335  func (t *Interface) assertCompleteness() {
   336  	if t.allMethods == nil {
   337  		panic("interface is incomplete")
   338  	}
   339  }
   340  
   341  // Method returns the i'th method of interface t for 0 <= i < t.NumMethods().
   342  // The methods are ordered by their unique Id.
   343  // The interface must have been completed.
   344  func (t *Interface) Method(i int) *Func { t.assertCompleteness(); return t.allMethods[i] }
   345  
   346  // Empty reports whether t is the empty interface.
   347  // The interface must have been completed.
   348  func (t *Interface) Empty() bool { t.assertCompleteness(); return len(t.allMethods) == 0 }
   349  
   350  // Complete computes the interface's method set. It must be called by users of
   351  // NewInterfaceType and NewInterface after the interface's embedded types are
   352  // fully defined and before using the interface type in any way other than to
   353  // form other types. The interface must not contain duplicate methods or a
   354  // panic occurs. Complete returns the receiver.
   355  func (t *Interface) Complete() *Interface {
   356  	// TODO(gri) consolidate this method with Checker.completeInterface
   357  	if t.allMethods != nil {
   358  		return t
   359  	}
   360  
   361  	t.allMethods = markComplete // avoid infinite recursion
   362  
   363  	var todo []*Func
   364  	var methods []*Func
   365  	var seen objset
   366  	addMethod := func(m *Func, explicit bool) {
   367  		switch other := seen.insert(m); {
   368  		case other == nil:
   369  			methods = append(methods, m)
   370  		case explicit:
   371  			panic("duplicate method " + m.name)
   372  		default:
   373  			// check method signatures after all locally embedded interfaces are computed
   374  			todo = append(todo, m, other.(*Func))
   375  		}
   376  	}
   377  
   378  	for _, m := range t.methods {
   379  		addMethod(m, true)
   380  	}
   381  
   382  	for _, typ := range t.embeddeds {
   383  		typ := typ.Underlying().(*Interface)
   384  		typ.Complete()
   385  		for _, m := range typ.allMethods {
   386  			addMethod(m, false)
   387  		}
   388  	}
   389  
   390  	for i := 0; i < len(todo); i += 2 {
   391  		m := todo[i]
   392  		other := todo[i+1]
   393  		if !Identical(m.typ, other.typ) {
   394  			panic("duplicate method " + m.name)
   395  		}
   396  	}
   397  
   398  	if methods != nil {
   399  		sort.Sort(byUniqueMethodName(methods))
   400  		t.allMethods = methods
   401  	}
   402  
   403  	return t
   404  }
   405  
   406  // A Map represents a map type.
   407  type Map struct {
   408  	key, elem Type
   409  }
   410  
   411  // NewMap returns a new map for the given key and element types.
   412  func NewMap(key, elem Type) *Map {
   413  	return &Map{key, elem}
   414  }
   415  
   416  // Key returns the key type of map m.
   417  func (m *Map) Key() Type { return m.key }
   418  
   419  // Elem returns the element type of map m.
   420  func (m *Map) Elem() Type { return m.elem }
   421  
   422  // A Chan represents a channel type.
   423  type Chan struct {
   424  	dir  ChanDir
   425  	elem Type
   426  }
   427  
   428  // A ChanDir value indicates a channel direction.
   429  type ChanDir int
   430  
   431  // The direction of a channel is indicated by one of these constants.
   432  const (
   433  	SendRecv ChanDir = iota
   434  	SendOnly
   435  	RecvOnly
   436  )
   437  
   438  // NewChan returns a new channel type for the given direction and element type.
   439  func NewChan(dir ChanDir, elem Type) *Chan {
   440  	return &Chan{dir, elem}
   441  }
   442  
   443  // Dir returns the direction of channel c.
   444  func (c *Chan) Dir() ChanDir { return c.dir }
   445  
   446  // Elem returns the element type of channel c.
   447  func (c *Chan) Elem() Type { return c.elem }
   448  
   449  // A Named represents a named type.
   450  type Named struct {
   451  	info       typeInfo  // for cycle detection
   452  	obj        *TypeName // corresponding declared object
   453  	orig       Type      // type (on RHS of declaration) this *Named type is derived of (for cycle reporting)
   454  	underlying Type      // possibly a *Named during setup; never a *Named once set up completely
   455  	methods    []*Func   // methods declared for this type (not the method set of this type); signatures are type-checked lazily
   456  }
   457  
   458  // NewNamed returns a new named type for the given type name, underlying type, and associated methods.
   459  // If the given type name obj doesn't have a type yet, its type is set to the returned named type.
   460  // The underlying type must not be a *Named.
   461  func NewNamed(obj *TypeName, underlying Type, methods []*Func) *Named {
   462  	if _, ok := underlying.(*Named); ok {
   463  		panic("types.NewNamed: underlying type must not be *Named")
   464  	}
   465  	typ := &Named{obj: obj, orig: underlying, underlying: underlying, methods: methods}
   466  	if obj.typ == nil {
   467  		obj.typ = typ
   468  	}
   469  	return typ
   470  }
   471  
   472  // Obj returns the type name for the named type t.
   473  func (t *Named) Obj() *TypeName { return t.obj }
   474  
   475  // NumMethods returns the number of explicit methods whose receiver is named type t.
   476  func (t *Named) NumMethods() int { return len(t.methods) }
   477  
   478  // Method returns the i'th method of named type t for 0 <= i < t.NumMethods().
   479  func (t *Named) Method(i int) *Func { return t.methods[i] }
   480  
   481  // SetUnderlying sets the underlying type and marks t as complete.
   482  func (t *Named) SetUnderlying(underlying Type) {
   483  	if underlying == nil {
   484  		panic("types.Named.SetUnderlying: underlying type must not be nil")
   485  	}
   486  	if _, ok := underlying.(*Named); ok {
   487  		panic("types.Named.SetUnderlying: underlying type must not be *Named")
   488  	}
   489  	t.underlying = underlying
   490  }
   491  
   492  // AddMethod adds method m unless it is already in the method list.
   493  func (t *Named) AddMethod(m *Func) {
   494  	if i, _ := lookupMethod(t.methods, m.pkg, m.name); i < 0 {
   495  		t.methods = append(t.methods, m)
   496  	}
   497  }
   498  
   499  // Implementations for Type methods.
   500  
   501  func (b *Basic) Underlying() Type     { return b }
   502  func (a *Array) Underlying() Type     { return a }
   503  func (s *Slice) Underlying() Type     { return s }
   504  func (s *Struct) Underlying() Type    { return s }
   505  func (p *Pointer) Underlying() Type   { return p }
   506  func (t *Tuple) Underlying() Type     { return t }
   507  func (s *Signature) Underlying() Type { return s }
   508  func (t *Interface) Underlying() Type { return t }
   509  func (m *Map) Underlying() Type       { return m }
   510  func (c *Chan) Underlying() Type      { return c }
   511  func (t *Named) Underlying() Type     { return t.underlying }
   512  
   513  func (b *Basic) String() string     { return TypeString(b, nil) }
   514  func (a *Array) String() string     { return TypeString(a, nil) }
   515  func (s *Slice) String() string     { return TypeString(s, nil) }
   516  func (s *Struct) String() string    { return TypeString(s, nil) }
   517  func (p *Pointer) String() string   { return TypeString(p, nil) }
   518  func (t *Tuple) String() string     { return TypeString(t, nil) }
   519  func (s *Signature) String() string { return TypeString(s, nil) }
   520  func (t *Interface) String() string { return TypeString(t, nil) }
   521  func (m *Map) String() string       { return TypeString(m, nil) }
   522  func (c *Chan) String() string      { return TypeString(c, nil) }
   523  func (t *Named) String() string     { return TypeString(t, nil) }
   524  

View as plain text