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 (
     8  	"fmt"
     9  	"go/token"
    10  	"sync/atomic"
    11  )
    12  
    13  // A Type represents a type of Go.
    14  // All types implement the Type interface.
    15  type Type interface {
    16  	// Underlying returns the underlying type of a type
    17  	// w/o following forwarding chains. Only used by
    18  	// client packages (here for backward-compatibility).
    19  	Underlying() Type
    20  
    21  	// String returns a string representation of a type.
    22  	String() string
    23  }
    24  
    25  // BasicKind describes the kind of basic type.
    26  type BasicKind int
    27  
    28  const (
    29  	Invalid BasicKind = iota // type is invalid
    30  
    31  	// predeclared types
    32  	Bool
    33  	Int
    34  	Int8
    35  	Int16
    36  	Int32
    37  	Int64
    38  	Uint
    39  	Uint8
    40  	Uint16
    41  	Uint32
    42  	Uint64
    43  	Uintptr
    44  	Float32
    45  	Float64
    46  	Complex64
    47  	Complex128
    48  	String
    49  	UnsafePointer
    50  
    51  	// types for untyped values
    52  	UntypedBool
    53  	UntypedInt
    54  	UntypedRune
    55  	UntypedFloat
    56  	UntypedComplex
    57  	UntypedString
    58  	UntypedNil
    59  
    60  	// aliases
    61  	Byte = Uint8
    62  	Rune = Int32
    63  )
    64  
    65  // BasicInfo is a set of flags describing properties of a basic type.
    66  type BasicInfo int
    67  
    68  // Properties of basic types.
    69  const (
    70  	IsBoolean BasicInfo = 1 << iota
    71  	IsInteger
    72  	IsUnsigned
    73  	IsFloat
    74  	IsComplex
    75  	IsString
    76  	IsUntyped
    77  
    78  	IsOrdered   = IsInteger | IsFloat | IsString
    79  	IsNumeric   = IsInteger | IsFloat | IsComplex
    80  	IsConstType = IsBoolean | IsNumeric | IsString
    81  )
    82  
    83  // A Basic represents a basic type.
    84  type Basic struct {
    85  	kind BasicKind
    86  	info BasicInfo
    87  	name string
    88  }
    89  
    90  // Kind returns the kind of basic type b.
    91  func (b *Basic) Kind() BasicKind { return b.kind }
    92  
    93  // Info returns information about properties of basic type b.
    94  func (b *Basic) Info() BasicInfo { return b.info }
    95  
    96  // Name returns the name of basic type b.
    97  func (b *Basic) Name() string { return b.name }
    98  
    99  // An Array represents an array type.
   100  type Array struct {
   101  	len  int64
   102  	elem Type
   103  }
   104  
   105  // NewArray returns a new array type for the given element type and length.
   106  // A negative length indicates an unknown length.
   107  func NewArray(elem Type, len int64) *Array { return &Array{len: len, elem: elem} }
   108  
   109  // Len returns the length of array a.
   110  // A negative result indicates an unknown length.
   111  func (a *Array) Len() int64 { return a.len }
   112  
   113  // Elem returns element type of array a.
   114  func (a *Array) Elem() Type { return a.elem }
   115  
   116  // A Slice represents a slice type.
   117  type Slice struct {
   118  	elem Type
   119  }
   120  
   121  // NewSlice returns a new slice type for the given element type.
   122  func NewSlice(elem Type) *Slice { return &Slice{elem: elem} }
   123  
   124  // Elem returns the element type of slice s.
   125  func (s *Slice) Elem() Type { return s.elem }
   126  
   127  // A Struct represents a struct type.
   128  type Struct struct {
   129  	fields []*Var
   130  	tags   []string // field tags; nil if there are no tags
   131  }
   132  
   133  // NewStruct returns a new struct with the given fields and corresponding field tags.
   134  // If a field with index i has a tag, tags[i] must be that tag, but len(tags) may be
   135  // only as long as required to hold the tag with the largest index i. Consequently,
   136  // if no field has a tag, tags may be nil.
   137  func NewStruct(fields []*Var, tags []string) *Struct {
   138  	var fset objset
   139  	for _, f := range fields {
   140  		if f.name != "_" && fset.insert(f) != nil {
   141  			panic("multiple fields with the same name")
   142  		}
   143  	}
   144  	if len(tags) > len(fields) {
   145  		panic("more tags than fields")
   146  	}
   147  	return &Struct{fields: fields, tags: tags}
   148  }
   149  
   150  // NumFields returns the number of fields in the struct (including blank and embedded fields).
   151  func (s *Struct) NumFields() int { return len(s.fields) }
   152  
   153  // Field returns the i'th field for 0 <= i < NumFields().
   154  func (s *Struct) Field(i int) *Var { return s.fields[i] }
   155  
   156  // Tag returns the i'th field tag for 0 <= i < NumFields().
   157  func (s *Struct) Tag(i int) string {
   158  	if i < len(s.tags) {
   159  		return s.tags[i]
   160  	}
   161  	return ""
   162  }
   163  
   164  // A Pointer represents a pointer type.
   165  type Pointer struct {
   166  	base Type // element type
   167  }
   168  
   169  // NewPointer returns a new pointer type for the given element (base) type.
   170  func NewPointer(elem Type) *Pointer { return &Pointer{base: elem} }
   171  
   172  // Elem returns the element type for the given pointer p.
   173  func (p *Pointer) Elem() Type { return p.base }
   174  
   175  // A Tuple represents an ordered list of variables; a nil *Tuple is a valid (empty) tuple.
   176  // Tuples are used as components of signatures and to represent the type of multiple
   177  // assignments; they are not first class types of Go.
   178  type Tuple struct {
   179  	vars []*Var
   180  }
   181  
   182  // NewTuple returns a new tuple for the given variables.
   183  func NewTuple(x ...*Var) *Tuple {
   184  	if len(x) > 0 {
   185  		return &Tuple{vars: x}
   186  	}
   187  	// TODO(gri) Don't represent empty tuples with a (*Tuple)(nil) pointer;
   188  	//           it's too subtle and causes problems.
   189  	return nil
   190  }
   191  
   192  // Len returns the number variables of tuple t.
   193  func (t *Tuple) Len() int {
   194  	if t != nil {
   195  		return len(t.vars)
   196  	}
   197  	return 0
   198  }
   199  
   200  // At returns the i'th variable of tuple t.
   201  func (t *Tuple) At(i int) *Var { return t.vars[i] }
   202  
   203  // A Signature represents a (non-builtin) function or method type.
   204  // The receiver is ignored when comparing signatures for identity.
   205  type Signature struct {
   206  	// We need to keep the scope in Signature (rather than passing it around
   207  	// and store it in the Func Object) because when type-checking a function
   208  	// literal we call the general type checker which returns a general Type.
   209  	// We then unpack the *Signature and use the scope for the literal body.
   210  	rparams  []*TypeName // receiver type parameters from left to right, or nil
   211  	tparams  []*TypeName // type parameters from left to right, or nil
   212  	scope    *Scope      // function scope, present for package-local signatures
   213  	recv     *Var        // nil if not a method
   214  	params   *Tuple      // (incoming) parameters from left to right; or nil
   215  	results  *Tuple      // (outgoing) results from left to right; or nil
   216  	variadic bool        // true if the last parameter's type is of the form ...T (or string, for append built-in only)
   217  }
   218  
   219  // NewSignature returns a new function type for the given receiver, parameters,
   220  // and results, either of which may be nil. If variadic is set, the function
   221  // is variadic, it must have at least one parameter, and the last parameter
   222  // must be of unnamed slice type.
   223  func NewSignature(recv *Var, params, results *Tuple, variadic bool) *Signature {
   224  	if variadic {
   225  		n := params.Len()
   226  		if n == 0 {
   227  			panic("types.NewSignature: variadic function must have at least one parameter")
   228  		}
   229  		if _, ok := params.At(n - 1).typ.(*Slice); !ok {
   230  			panic("types.NewSignature: variadic parameter must be of unnamed slice type")
   231  		}
   232  	}
   233  	return &Signature{recv: recv, params: params, results: results, variadic: variadic}
   234  }
   235  
   236  // Recv returns the receiver of signature s (if a method), or nil if a
   237  // function. It is ignored when comparing signatures for identity.
   238  //
   239  // For an abstract method, Recv returns the enclosing interface either
   240  // as a *Named or an *Interface. Due to embedding, an interface may
   241  // contain methods whose receiver type is a different interface.
   242  func (s *Signature) Recv() *Var { return s.recv }
   243  
   244  // _TParams returns the type parameters of signature s, or nil.
   245  func (s *Signature) _TParams() []*TypeName { return s.tparams }
   246  
   247  // _SetTParams sets the type parameters of signature s.
   248  func (s *Signature) _SetTParams(tparams []*TypeName) { s.tparams = tparams }
   249  
   250  // Params returns the parameters of signature s, or nil.
   251  func (s *Signature) Params() *Tuple { return s.params }
   252  
   253  // Results returns the results of signature s, or nil.
   254  func (s *Signature) Results() *Tuple { return s.results }
   255  
   256  // Variadic reports whether the signature s is variadic.
   257  func (s *Signature) Variadic() bool { return s.variadic }
   258  
   259  // A _Sum represents a set of possible types.
   260  // Sums are currently used to represent type lists of interfaces
   261  // and thus the underlying types of type parameters; they are not
   262  // first class types of Go.
   263  type _Sum struct {
   264  	types []Type // types are unique
   265  }
   266  
   267  // _NewSum returns a new Sum type consisting of the provided
   268  // types if there are more than one. If there is exactly one
   269  // type, it returns that type. If the list of types is empty
   270  // the result is nil.
   271  func _NewSum(types []Type) Type {
   272  	if len(types) == 0 {
   273  		return nil
   274  	}
   275  
   276  	// What should happen if types contains a sum type?
   277  	// Do we flatten the types list? For now we check
   278  	// and panic. This should not be possible for the
   279  	// current use case of type lists.
   280  	// TODO(gri) Come up with the rules for sum types.
   281  	for _, t := range types {
   282  		if _, ok := t.(*_Sum); ok {
   283  			panic("sum type contains sum type - unimplemented")
   284  		}
   285  	}
   286  
   287  	if len(types) == 1 {
   288  		return types[0]
   289  	}
   290  	return &_Sum{types: types}
   291  }
   292  
   293  // is reports whether all types in t satisfy pred.
   294  func (s *_Sum) is(pred func(Type) bool) bool {
   295  	if s == nil {
   296  		return false
   297  	}
   298  	for _, t := range s.types {
   299  		if !pred(t) {
   300  			return false
   301  		}
   302  	}
   303  	return true
   304  }
   305  
   306  // An Interface represents an interface type.
   307  type Interface struct {
   308  	methods   []*Func // ordered list of explicitly declared methods
   309  	types     Type    // (possibly a Sum) type declared with a type list (TODO(gri) need better field name)
   310  	embeddeds []Type  // ordered list of explicitly embedded types
   311  
   312  	allMethods []*Func // ordered list of methods declared with or embedded in this interface (TODO(gri): replace with mset)
   313  	allTypes   Type    // intersection of all embedded and locally declared types  (TODO(gri) need better field name)
   314  
   315  	obj Object // type declaration defining this interface; or nil (for better error messages)
   316  }
   317  
   318  // unpack unpacks a type into a list of types.
   319  // TODO(gri) Try to eliminate the need for this function.
   320  func unpackType(typ Type) []Type {
   321  	if typ == nil {
   322  		return nil
   323  	}
   324  	if sum := asSum(typ); sum != nil {
   325  		return sum.types
   326  	}
   327  	return []Type{typ}
   328  }
   329  
   330  // is reports whether interface t represents types that all satisfy pred.
   331  func (t *Interface) is(pred func(Type) bool) bool {
   332  	if t.allTypes == nil {
   333  		return false // we must have at least one type! (was bug)
   334  	}
   335  	for _, t := range unpackType(t.allTypes) {
   336  		if !pred(t) {
   337  			return false
   338  		}
   339  	}
   340  	return true
   341  }
   342  
   343  // emptyInterface represents the empty (completed) interface
   344  var emptyInterface = Interface{allMethods: markComplete}
   345  
   346  // markComplete is used to mark an empty interface as completely
   347  // set up by setting the allMethods field to a non-nil empty slice.
   348  var markComplete = make([]*Func, 0)
   349  
   350  // NewInterface returns a new (incomplete) interface for the given methods and embedded types.
   351  // Each embedded type must have an underlying type of interface type.
   352  // NewInterface takes ownership of the provided methods and may modify their types by setting
   353  // missing receivers. To compute the method set of the interface, Complete must be called.
   354  //
   355  // Deprecated: Use NewInterfaceType instead which allows any (even non-defined) interface types
   356  // to be embedded. This is necessary for interfaces that embed alias type names referring to
   357  // non-defined (literal) interface types.
   358  func NewInterface(methods []*Func, embeddeds []*Named) *Interface {
   359  	tnames := make([]Type, len(embeddeds))
   360  	for i, t := range embeddeds {
   361  		tnames[i] = t
   362  	}
   363  	return NewInterfaceType(methods, tnames)
   364  }
   365  
   366  // NewInterfaceType returns a new (incomplete) interface for the given methods and embedded types.
   367  // Each embedded type must have an underlying type of interface type (this property is not
   368  // verified for defined types, which may be in the process of being set up and which don't
   369  // have a valid underlying type yet).
   370  // NewInterfaceType takes ownership of the provided methods and may modify their types by setting
   371  // missing receivers. To compute the method set of the interface, Complete must be called.
   372  func NewInterfaceType(methods []*Func, embeddeds []Type) *Interface {
   373  	if len(methods) == 0 && len(embeddeds) == 0 {
   374  		return &emptyInterface
   375  	}
   376  
   377  	// set method receivers if necessary
   378  	typ := new(Interface)
   379  	for _, m := range methods {
   380  		if sig := m.typ.(*Signature); sig.recv == nil {
   381  			sig.recv = NewVar(m.pos, m.pkg, "", typ)
   382  		}
   383  	}
   384  
   385  	// All embedded types should be interfaces; however, defined types
   386  	// may not yet be fully resolved. Only verify that non-defined types
   387  	// are interfaces. This matches the behavior of the code before the
   388  	// fix for #25301 (issue #25596).
   389  	for _, t := range embeddeds {
   390  		if _, ok := t.(*Named); !ok && !IsInterface(t) {
   391  			panic("embedded type is not an interface")
   392  		}
   393  	}
   394  
   395  	// sort for API stability
   396  	sortMethods(methods)
   397  	sortTypes(embeddeds)
   398  
   399  	typ.methods = methods
   400  	typ.embeddeds = embeddeds
   401  	return typ
   402  }
   403  
   404  // NumExplicitMethods returns the number of explicitly declared methods of interface t.
   405  func (t *Interface) NumExplicitMethods() int { return len(t.methods) }
   406  
   407  // ExplicitMethod returns the i'th explicitly declared method of interface t for 0 <= i < t.NumExplicitMethods().
   408  // The methods are ordered by their unique Id.
   409  func (t *Interface) ExplicitMethod(i int) *Func { return t.methods[i] }
   410  
   411  // NumEmbeddeds returns the number of embedded types in interface t.
   412  func (t *Interface) NumEmbeddeds() int { return len(t.embeddeds) }
   413  
   414  // Embedded returns the i'th embedded defined (*Named) type of interface t for 0 <= i < t.NumEmbeddeds().
   415  // The result is nil if the i'th embedded type is not a defined type.
   416  //
   417  // Deprecated: Use EmbeddedType which is not restricted to defined (*Named) types.
   418  func (t *Interface) Embedded(i int) *Named { tname, _ := t.embeddeds[i].(*Named); return tname }
   419  
   420  // EmbeddedType returns the i'th embedded type of interface t for 0 <= i < t.NumEmbeddeds().
   421  func (t *Interface) EmbeddedType(i int) Type { return t.embeddeds[i] }
   422  
   423  // NumMethods returns the total number of methods of interface t.
   424  // The interface must have been completed.
   425  func (t *Interface) NumMethods() int { t.assertCompleteness(); return len(t.allMethods) }
   426  
   427  func (t *Interface) assertCompleteness() {
   428  	if t.allMethods == nil {
   429  		panic("interface is incomplete")
   430  	}
   431  }
   432  
   433  // Method returns the i'th method of interface t for 0 <= i < t.NumMethods().
   434  // The methods are ordered by their unique Id.
   435  // The interface must have been completed.
   436  func (t *Interface) Method(i int) *Func { t.assertCompleteness(); return t.allMethods[i] }
   437  
   438  // Empty reports whether t is the empty interface.
   439  func (t *Interface) Empty() bool {
   440  	if t.allMethods != nil {
   441  		// interface is complete - quick test
   442  		// A non-nil allTypes may still be empty and represents the bottom type.
   443  		return len(t.allMethods) == 0 && t.allTypes == nil
   444  	}
   445  	return !t.iterate(func(t *Interface) bool {
   446  		return len(t.methods) > 0 || t.types != nil
   447  	}, nil)
   448  }
   449  
   450  // _HasTypeList reports whether interface t has a type list, possibly from an embedded type.
   451  func (t *Interface) _HasTypeList() bool {
   452  	if t.allMethods != nil {
   453  		// interface is complete - quick test
   454  		return t.allTypes != nil
   455  	}
   456  
   457  	return t.iterate(func(t *Interface) bool {
   458  		return t.types != nil
   459  	}, nil)
   460  }
   461  
   462  // _IsComparable reports whether interface t is or embeds the predeclared interface "comparable".
   463  func (t *Interface) _IsComparable() bool {
   464  	if t.allMethods != nil {
   465  		// interface is complete - quick test
   466  		_, m := lookupMethod(t.allMethods, nil, "==")
   467  		return m != nil
   468  	}
   469  
   470  	return t.iterate(func(t *Interface) bool {
   471  		_, m := lookupMethod(t.methods, nil, "==")
   472  		return m != nil
   473  	}, nil)
   474  }
   475  
   476  // _IsConstraint reports t.HasTypeList() || t.IsComparable().
   477  func (t *Interface) _IsConstraint() bool {
   478  	if t.allMethods != nil {
   479  		// interface is complete - quick test
   480  		if t.allTypes != nil {
   481  			return true
   482  		}
   483  		_, m := lookupMethod(t.allMethods, nil, "==")
   484  		return m != nil
   485  	}
   486  
   487  	return t.iterate(func(t *Interface) bool {
   488  		if t.types != nil {
   489  			return true
   490  		}
   491  		_, m := lookupMethod(t.methods, nil, "==")
   492  		return m != nil
   493  	}, nil)
   494  }
   495  
   496  // iterate calls f with t and then with any embedded interface of t, recursively, until f returns true.
   497  // iterate reports whether any call to f returned true.
   498  func (t *Interface) iterate(f func(*Interface) bool, seen map[*Interface]bool) bool {
   499  	if f(t) {
   500  		return true
   501  	}
   502  	for _, e := range t.embeddeds {
   503  		// e should be an interface but be careful (it may be invalid)
   504  		if e := asInterface(e); e != nil {
   505  			// Cyclic interfaces such as "type E interface { E }" are not permitted
   506  			// but they are still constructed and we need to detect such cycles.
   507  			if seen[e] {
   508  				continue
   509  			}
   510  			if seen == nil {
   511  				seen = make(map[*Interface]bool)
   512  			}
   513  			seen[e] = true
   514  			if e.iterate(f, seen) {
   515  				return true
   516  			}
   517  		}
   518  	}
   519  	return false
   520  }
   521  
   522  // isSatisfiedBy reports whether interface t's type list is satisfied by the type typ.
   523  // If the type list is empty (absent), typ trivially satisfies the interface.
   524  // TODO(gri) This is not a great name. Eventually, we should have a more comprehensive
   525  //           "implements" predicate.
   526  func (t *Interface) isSatisfiedBy(typ Type) bool {
   527  	t.Complete()
   528  	if t.allTypes == nil {
   529  		return true
   530  	}
   531  	types := unpackType(t.allTypes)
   532  	return includes(types, typ) || includes(types, under(typ))
   533  }
   534  
   535  // Complete computes the interface's method set. It must be called by users of
   536  // NewInterfaceType and NewInterface after the interface's embedded types are
   537  // fully defined and before using the interface type in any way other than to
   538  // form other types. The interface must not contain duplicate methods or a
   539  // panic occurs. Complete returns the receiver.
   540  func (t *Interface) Complete() *Interface {
   541  	// TODO(gri) consolidate this method with Checker.completeInterface
   542  	if t.allMethods != nil {
   543  		return t
   544  	}
   545  
   546  	t.allMethods = markComplete // avoid infinite recursion
   547  
   548  	var todo []*Func
   549  	var methods []*Func
   550  	var seen objset
   551  	addMethod := func(m *Func, explicit bool) {
   552  		switch other := seen.insert(m); {
   553  		case other == nil:
   554  			methods = append(methods, m)
   555  		case explicit:
   556  			panic("duplicate method " + m.name)
   557  		default:
   558  			// check method signatures after all locally embedded interfaces are computed
   559  			todo = append(todo, m, other.(*Func))
   560  		}
   561  	}
   562  
   563  	for _, m := range t.methods {
   564  		addMethod(m, true)
   565  	}
   566  
   567  	allTypes := t.types
   568  
   569  	for _, typ := range t.embeddeds {
   570  		utyp := under(typ)
   571  		etyp := asInterface(utyp)
   572  		if etyp == nil {
   573  			if utyp != Typ[Invalid] {
   574  				panic(fmt.Sprintf("%s is not an interface", typ))
   575  			}
   576  			continue
   577  		}
   578  		etyp.Complete()
   579  		for _, m := range etyp.allMethods {
   580  			addMethod(m, false)
   581  		}
   582  		allTypes = intersect(allTypes, etyp.allTypes)
   583  	}
   584  
   585  	for i := 0; i < len(todo); i += 2 {
   586  		m := todo[i]
   587  		other := todo[i+1]
   588  		if !Identical(m.typ, other.typ) {
   589  			panic("duplicate method " + m.name)
   590  		}
   591  	}
   592  
   593  	if methods != nil {
   594  		sortMethods(methods)
   595  		t.allMethods = methods
   596  	}
   597  	t.allTypes = allTypes
   598  
   599  	return t
   600  }
   601  
   602  // A Map represents a map type.
   603  type Map struct {
   604  	key, elem Type
   605  }
   606  
   607  // NewMap returns a new map for the given key and element types.
   608  func NewMap(key, elem Type) *Map {
   609  	return &Map{key: key, elem: elem}
   610  }
   611  
   612  // Key returns the key type of map m.
   613  func (m *Map) Key() Type { return m.key }
   614  
   615  // Elem returns the element type of map m.
   616  func (m *Map) Elem() Type { return m.elem }
   617  
   618  // A Chan represents a channel type.
   619  type Chan struct {
   620  	dir  ChanDir
   621  	elem Type
   622  }
   623  
   624  // A ChanDir value indicates a channel direction.
   625  type ChanDir int
   626  
   627  // The direction of a channel is indicated by one of these constants.
   628  const (
   629  	SendRecv ChanDir = iota
   630  	SendOnly
   631  	RecvOnly
   632  )
   633  
   634  // NewChan returns a new channel type for the given direction and element type.
   635  func NewChan(dir ChanDir, elem Type) *Chan {
   636  	return &Chan{dir: dir, elem: elem}
   637  }
   638  
   639  // Dir returns the direction of channel c.
   640  func (c *Chan) Dir() ChanDir { return c.dir }
   641  
   642  // Elem returns the element type of channel c.
   643  func (c *Chan) Elem() Type { return c.elem }
   644  
   645  // A Named represents a named (defined) type.
   646  type Named struct {
   647  	check      *Checker    // for Named.under implementation; nilled once under has been called
   648  	info       typeInfo    // for cycle detection
   649  	obj        *TypeName   // corresponding declared object
   650  	orig       Type        // type (on RHS of declaration) this *Named type is derived of (for cycle reporting)
   651  	underlying Type        // possibly a *Named during setup; never a *Named once set up completely
   652  	tparams    []*TypeName // type parameters, or nil
   653  	targs      []Type      // type arguments (after instantiation), or nil
   654  	methods    []*Func     // methods declared for this type (not the method set of this type); signatures are type-checked lazily
   655  }
   656  
   657  // NewNamed returns a new named type for the given type name, underlying type, and associated methods.
   658  // If the given type name obj doesn't have a type yet, its type is set to the returned named type.
   659  // The underlying type must not be a *Named.
   660  func NewNamed(obj *TypeName, underlying Type, methods []*Func) *Named {
   661  	if _, ok := underlying.(*Named); ok {
   662  		panic("types.NewNamed: underlying type must not be *Named")
   663  	}
   664  	return (*Checker)(nil).newNamed(obj, underlying, methods)
   665  }
   666  
   667  func (check *Checker) newNamed(obj *TypeName, underlying Type, methods []*Func) *Named {
   668  	typ := &Named{check: check, obj: obj, orig: underlying, underlying: underlying, methods: methods}
   669  	if obj.typ == nil {
   670  		obj.typ = typ
   671  	}
   672  	// Ensure that typ is always expanded, at which point the check field can be
   673  	// nilled out.
   674  	//
   675  	// Note that currently we cannot nil out check inside typ.under(), because
   676  	// it's possible that typ is expanded multiple times.
   677  	//
   678  	// TODO(rFindley): clean this up so that under is the only function mutating
   679  	//                 named types.
   680  	if check != nil {
   681  		check.later(func() {
   682  			switch typ.under().(type) {
   683  			case *Named, *instance:
   684  				panic("internal error: unexpanded underlying type")
   685  			}
   686  			typ.check = nil
   687  		})
   688  	}
   689  	return typ
   690  }
   691  
   692  // Obj returns the type name for the named type t.
   693  func (t *Named) Obj() *TypeName { return t.obj }
   694  
   695  // TODO(gri) Come up with a better representation and API to distinguish
   696  //           between parameterized instantiated and non-instantiated types.
   697  
   698  // _TParams returns the type parameters of the named type t, or nil.
   699  // The result is non-nil for an (originally) parameterized type even if it is instantiated.
   700  func (t *Named) _TParams() []*TypeName { return t.tparams }
   701  
   702  // _TArgs returns the type arguments after instantiation of the named type t, or nil if not instantiated.
   703  func (t *Named) _TArgs() []Type { return t.targs }
   704  
   705  // _SetTArgs sets the type arguments of Named.
   706  func (t *Named) _SetTArgs(args []Type) { t.targs = args }
   707  
   708  // NumMethods returns the number of explicit methods whose receiver is named type t.
   709  func (t *Named) NumMethods() int { return len(t.methods) }
   710  
   711  // Method returns the i'th method of named type t for 0 <= i < t.NumMethods().
   712  func (t *Named) Method(i int) *Func { return t.methods[i] }
   713  
   714  // SetUnderlying sets the underlying type and marks t as complete.
   715  func (t *Named) SetUnderlying(underlying Type) {
   716  	if underlying == nil {
   717  		panic("types.Named.SetUnderlying: underlying type must not be nil")
   718  	}
   719  	if _, ok := underlying.(*Named); ok {
   720  		panic("types.Named.SetUnderlying: underlying type must not be *Named")
   721  	}
   722  	t.underlying = underlying
   723  }
   724  
   725  // AddMethod adds method m unless it is already in the method list.
   726  func (t *Named) AddMethod(m *Func) {
   727  	if i, _ := lookupMethod(t.methods, m.pkg, m.name); i < 0 {
   728  		t.methods = append(t.methods, m)
   729  	}
   730  }
   731  
   732  // Note: This is a uint32 rather than a uint64 because the
   733  // respective 64 bit atomic instructions are not available
   734  // on all platforms.
   735  var lastId uint32
   736  
   737  // nextId returns a value increasing monotonically by 1 with
   738  // each call, starting with 1. It may be called concurrently.
   739  func nextId() uint64 { return uint64(atomic.AddUint32(&lastId, 1)) }
   740  
   741  // A _TypeParam represents a type parameter type.
   742  type _TypeParam struct {
   743  	check *Checker  // for lazy type bound completion
   744  	id    uint64    // unique id
   745  	obj   *TypeName // corresponding type name
   746  	index int       // parameter index
   747  	bound Type      // *Named or *Interface; underlying type is always *Interface
   748  }
   749  
   750  // newTypeParam returns a new TypeParam.
   751  func (check *Checker) newTypeParam(obj *TypeName, index int, bound Type) *_TypeParam {
   752  	assert(bound != nil)
   753  	typ := &_TypeParam{check: check, id: nextId(), obj: obj, index: index, bound: bound}
   754  	if obj.typ == nil {
   755  		obj.typ = typ
   756  	}
   757  	return typ
   758  }
   759  
   760  func (t *_TypeParam) Bound() *Interface {
   761  	iface := asInterface(t.bound)
   762  	// use the type bound position if we have one
   763  	pos := token.NoPos
   764  	if n, _ := t.bound.(*Named); n != nil {
   765  		pos = n.obj.pos
   766  	}
   767  	// TODO(rFindley) switch this to an unexported method on Checker.
   768  	t.check.completeInterface(pos, iface)
   769  	return iface
   770  }
   771  
   772  // optype returns a type's operational type. Except for
   773  // type parameters, the operational type is the same
   774  // as the underlying type (as returned by under). For
   775  // Type parameters, the operational type is determined
   776  // by the corresponding type bound's type list. The
   777  // result may be the bottom or top type, but it is never
   778  // the incoming type parameter.
   779  func optype(typ Type) Type {
   780  	if t := asTypeParam(typ); t != nil {
   781  		// If the optype is typ, return the top type as we have
   782  		// no information. It also prevents infinite recursion
   783  		// via the asTypeParam converter function. This can happen
   784  		// for a type parameter list of the form:
   785  		// (type T interface { type T }).
   786  		// See also issue #39680.
   787  		if u := t.Bound().allTypes; u != nil && u != typ {
   788  			// u != typ and u is a type parameter => under(u) != typ, so this is ok
   789  			return under(u)
   790  		}
   791  		return theTop
   792  	}
   793  	return under(typ)
   794  }
   795  
   796  // An instance represents an instantiated generic type syntactically
   797  // (without expanding the instantiation). Type instances appear only
   798  // during type-checking and are replaced by their fully instantiated
   799  // (expanded) types before the end of type-checking.
   800  type instance struct {
   801  	check   *Checker    // for lazy instantiation
   802  	pos     token.Pos   // position of type instantiation; for error reporting only
   803  	base    *Named      // parameterized type to be instantiated
   804  	targs   []Type      // type arguments
   805  	poslist []token.Pos // position of each targ; for error reporting only
   806  	value   Type        // base(targs...) after instantiation or Typ[Invalid]; nil if not yet set
   807  }
   808  
   809  // expand returns the instantiated (= expanded) type of t.
   810  // The result is either an instantiated *Named type, or
   811  // Typ[Invalid] if there was an error.
   812  func (t *instance) expand() Type {
   813  	v := t.value
   814  	if v == nil {
   815  		v = t.check.instantiate(t.pos, t.base, t.targs, t.poslist)
   816  		if v == nil {
   817  			v = Typ[Invalid]
   818  		}
   819  		t.value = v
   820  	}
   821  	// After instantiation we must have an invalid or a *Named type.
   822  	if debug && v != Typ[Invalid] {
   823  		_ = v.(*Named)
   824  	}
   825  	return v
   826  }
   827  
   828  // expand expands a type instance into its instantiated
   829  // type and leaves all other types alone. expand does
   830  // not recurse.
   831  func expand(typ Type) Type {
   832  	if t, _ := typ.(*instance); t != nil {
   833  		return t.expand()
   834  	}
   835  	return typ
   836  }
   837  
   838  // expandf is set to expand.
   839  // Call expandf when calling expand causes compile-time cycle error.
   840  var expandf func(Type) Type
   841  
   842  func init() { expandf = expand }
   843  
   844  // bottom represents the bottom of the type lattice.
   845  // It is the underlying type of a type parameter that
   846  // cannot be satisfied by any type, usually because
   847  // the intersection of type constraints left nothing).
   848  type bottom struct{}
   849  
   850  // theBottom is the singleton bottom type.
   851  var theBottom = &bottom{}
   852  
   853  // top represents the top of the type lattice.
   854  // It is the underlying type of a type parameter that
   855  // can be satisfied by any type (ignoring methods),
   856  // usually because the type constraint has no type
   857  // list.
   858  type top struct{}
   859  
   860  // theTop is the singleton top type.
   861  var theTop = &top{}
   862  
   863  // Type-specific implementations of Underlying.
   864  func (t *Basic) Underlying() Type      { return t }
   865  func (t *Array) Underlying() Type      { return t }
   866  func (t *Slice) Underlying() Type      { return t }
   867  func (t *Struct) Underlying() Type     { return t }
   868  func (t *Pointer) Underlying() Type    { return t }
   869  func (t *Tuple) Underlying() Type      { return t }
   870  func (t *Signature) Underlying() Type  { return t }
   871  func (t *_Sum) Underlying() Type       { return t }
   872  func (t *Interface) Underlying() Type  { return t }
   873  func (t *Map) Underlying() Type        { return t }
   874  func (t *Chan) Underlying() Type       { return t }
   875  func (t *Named) Underlying() Type      { return t.underlying }
   876  func (t *_TypeParam) Underlying() Type { return t }
   877  func (t *instance) Underlying() Type   { return t }
   878  func (t *bottom) Underlying() Type     { return t }
   879  func (t *top) Underlying() Type        { return t }
   880  
   881  // Type-specific implementations of String.
   882  func (t *Basic) String() string      { return TypeString(t, nil) }
   883  func (t *Array) String() string      { return TypeString(t, nil) }
   884  func (t *Slice) String() string      { return TypeString(t, nil) }
   885  func (t *Struct) String() string     { return TypeString(t, nil) }
   886  func (t *Pointer) String() string    { return TypeString(t, nil) }
   887  func (t *Tuple) String() string      { return TypeString(t, nil) }
   888  func (t *Signature) String() string  { return TypeString(t, nil) }
   889  func (t *_Sum) String() string       { return TypeString(t, nil) }
   890  func (t *Interface) String() string  { return TypeString(t, nil) }
   891  func (t *Map) String() string        { return TypeString(t, nil) }
   892  func (t *Chan) String() string       { return TypeString(t, nil) }
   893  func (t *Named) String() string      { return TypeString(t, nil) }
   894  func (t *_TypeParam) String() string { return TypeString(t, nil) }
   895  func (t *instance) String() string   { return TypeString(t, nil) }
   896  func (t *bottom) String() string     { return TypeString(t, nil) }
   897  func (t *top) String() string        { return TypeString(t, nil) }
   898  
   899  // under returns the true expanded underlying type.
   900  // If it doesn't exist, the result is Typ[Invalid].
   901  // under must only be called when a type is known
   902  // to be fully set up.
   903  func under(t Type) Type {
   904  	// TODO(gri) is this correct for *Sum?
   905  	if n := asNamed(t); n != nil {
   906  		return n.under()
   907  	}
   908  	return t
   909  }
   910  
   911  // Converters
   912  //
   913  // A converter must only be called when a type is
   914  // known to be fully set up. A converter returns
   915  // a type's operational type (see comment for optype)
   916  // or nil if the type argument is not of the
   917  // respective type.
   918  
   919  func asBasic(t Type) *Basic {
   920  	op, _ := optype(t).(*Basic)
   921  	return op
   922  }
   923  
   924  func asArray(t Type) *Array {
   925  	op, _ := optype(t).(*Array)
   926  	return op
   927  }
   928  
   929  func asSlice(t Type) *Slice {
   930  	op, _ := optype(t).(*Slice)
   931  	return op
   932  }
   933  
   934  func asStruct(t Type) *Struct {
   935  	op, _ := optype(t).(*Struct)
   936  	return op
   937  }
   938  
   939  func asPointer(t Type) *Pointer {
   940  	op, _ := optype(t).(*Pointer)
   941  	return op
   942  }
   943  
   944  func asTuple(t Type) *Tuple {
   945  	op, _ := optype(t).(*Tuple)
   946  	return op
   947  }
   948  
   949  func asSignature(t Type) *Signature {
   950  	op, _ := optype(t).(*Signature)
   951  	return op
   952  }
   953  
   954  func asSum(t Type) *_Sum {
   955  	op, _ := optype(t).(*_Sum)
   956  	return op
   957  }
   958  
   959  func asInterface(t Type) *Interface {
   960  	op, _ := optype(t).(*Interface)
   961  	return op
   962  }
   963  
   964  func asMap(t Type) *Map {
   965  	op, _ := optype(t).(*Map)
   966  	return op
   967  }
   968  
   969  func asChan(t Type) *Chan {
   970  	op, _ := optype(t).(*Chan)
   971  	return op
   972  }
   973  
   974  // If the argument to asNamed and asTypeParam is of the respective types
   975  // (possibly after expanding an instance type), these methods return that type.
   976  // Otherwise the result is nil.
   977  
   978  func asNamed(t Type) *Named {
   979  	e, _ := expand(t).(*Named)
   980  	return e
   981  }
   982  
   983  func asTypeParam(t Type) *_TypeParam {
   984  	u, _ := under(t).(*_TypeParam)
   985  	return u
   986  }
   987  

View as plain text