github.com/zebozhuang/go@v0.0.0-20200207033046-f8a98f6f5c5d/src/go/types/type.go (about)

     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  func NewArray(elem Type, len int64) *Array { return &Array{len, elem} }
   101  
   102  // Len returns the length of array a.
   103  func (a *Array) Len() int64 { return a.len }
   104  
   105  // Elem returns element type of array a.
   106  func (a *Array) Elem() Type { return a.elem }
   107  
   108  // A Slice represents a slice type.
   109  type Slice struct {
   110  	elem Type
   111  }
   112  
   113  // NewSlice returns a new slice type for the given element type.
   114  func NewSlice(elem Type) *Slice { return &Slice{elem} }
   115  
   116  // Elem returns the element type of slice s.
   117  func (s *Slice) Elem() Type { return s.elem }
   118  
   119  // A Struct represents a struct type.
   120  type Struct struct {
   121  	fields []*Var
   122  	tags   []string // field tags; nil if there are no tags
   123  }
   124  
   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 {
   130  	var fset objset
   131  	for _, f := range fields {
   132  		if f.name != "_" && fset.insert(f) != nil {
   133  			panic("multiple fields with the same name")
   134  		}
   135  	}
   136  	if len(tags) > len(fields) {
   137  		panic("more tags than fields")
   138  	}
   139  	return &Struct{fields: fields, tags: tags}
   140  }
   141  
   142  // NumFields returns the number of fields in the struct (including blank and anonymous fields).
   143  func (s *Struct) NumFields() int { return len(s.fields) }
   144  
   145  // Field returns the i'th field for 0 <= i < NumFields().
   146  func (s *Struct) Field(i int) *Var { return s.fields[i] }
   147  
   148  // Tag returns the i'th field tag for 0 <= i < NumFields().
   149  func (s *Struct) Tag(i int) string {
   150  	if i < len(s.tags) {
   151  		return s.tags[i]
   152  	}
   153  	return ""
   154  }
   155  
   156  // A Pointer represents a pointer type.
   157  type Pointer struct {
   158  	base Type // element type
   159  }
   160  
   161  // NewPointer returns a new pointer type for the given element (base) type.
   162  func NewPointer(elem Type) *Pointer { return &Pointer{base: elem} }
   163  
   164  // Elem returns the element type for the given pointer p.
   165  func (p *Pointer) Elem() Type { return p.base }
   166  
   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.
   170  type Tuple struct {
   171  	vars []*Var
   172  }
   173  
   174  // NewTuple returns a new tuple for the given variables.
   175  func NewTuple(x ...*Var) *Tuple {
   176  	if len(x) > 0 {
   177  		return &Tuple{x}
   178  	}
   179  	return nil
   180  }
   181  
   182  // Len returns the number variables of tuple t.
   183  func (t *Tuple) Len() int {
   184  	if t != nil {
   185  		return len(t.vars)
   186  	}
   187  	return 0
   188  }
   189  
   190  // At returns the i'th variable of tuple t.
   191  func (t *Tuple) At(i int) *Var { return t.vars[i] }
   192  
   193  // A Signature represents a (non-builtin) function or method type.
   194  type Signature struct {
   195  	// We need to keep the scope in Signature (rather than passing it around
   196  	// and store it in the Func Object) because when type-checking a function
   197  	// literal we call the general type checker which returns a general Type.
   198  	// We then unpack the *Signature and use the scope for the literal body.
   199  	scope    *Scope // function scope, present for package-local signatures
   200  	recv     *Var   // nil if not a method
   201  	params   *Tuple // (incoming) parameters from left to right; or nil
   202  	results  *Tuple // (outgoing) results from left to right; or nil
   203  	variadic bool   // true if the last parameter's type is of the form ...T (or string, for append built-in only)
   204  }
   205  
   206  // NewSignature returns a new function type for the given receiver, parameters,
   207  // and results, either of which may be nil. If variadic is set, the function
   208  // is variadic, it must have at least one parameter, and the last parameter
   209  // must be of unnamed slice type.
   210  func NewSignature(recv *Var, params, results *Tuple, variadic bool) *Signature {
   211  	if variadic {
   212  		n := params.Len()
   213  		if n == 0 {
   214  			panic("types.NewSignature: variadic function must have at least one parameter")
   215  		}
   216  		if _, ok := params.At(n - 1).typ.(*Slice); !ok {
   217  			panic("types.NewSignature: variadic parameter must be of unnamed slice type")
   218  		}
   219  	}
   220  	return &Signature{nil, recv, params, results, variadic}
   221  }
   222  
   223  // Recv returns the receiver of signature s (if a method), or nil if a
   224  // function.
   225  //
   226  // For an abstract method, Recv returns the enclosing interface either
   227  // as a *Named or an *Interface. Due to embedding, an interface may
   228  // contain methods whose receiver type is a different interface.
   229  func (s *Signature) Recv() *Var { return s.recv }
   230  
   231  // Params returns the parameters of signature s, or nil.
   232  func (s *Signature) Params() *Tuple { return s.params }
   233  
   234  // Results returns the results of signature s, or nil.
   235  func (s *Signature) Results() *Tuple { return s.results }
   236  
   237  // Variadic reports whether the signature s is variadic.
   238  func (s *Signature) Variadic() bool { return s.variadic }
   239  
   240  // An Interface represents an interface type.
   241  type Interface struct {
   242  	methods   []*Func  // ordered list of explicitly declared methods
   243  	embeddeds []*Named // ordered list of explicitly embedded types
   244  
   245  	allMethods []*Func // ordered list of methods declared with or embedded in this interface (TODO(gri): replace with mset)
   246  }
   247  
   248  // NewInterface returns a new interface for the given methods and embedded types.
   249  func NewInterface(methods []*Func, embeddeds []*Named) *Interface {
   250  	typ := new(Interface)
   251  
   252  	var mset objset
   253  	for _, m := range methods {
   254  		if mset.insert(m) != nil {
   255  			panic("multiple methods with the same name")
   256  		}
   257  		// set receiver
   258  		// TODO(gri) Ideally, we should use a named type here instead of
   259  		// typ, for less verbose printing of interface method signatures.
   260  		m.typ.(*Signature).recv = NewVar(m.pos, m.pkg, "", typ)
   261  	}
   262  	sort.Sort(byUniqueMethodName(methods))
   263  
   264  	if embeddeds == nil {
   265  		sort.Sort(byUniqueTypeName(embeddeds))
   266  	}
   267  
   268  	typ.methods = methods
   269  	typ.embeddeds = embeddeds
   270  	return typ
   271  }
   272  
   273  // NumExplicitMethods returns the number of explicitly declared methods of interface t.
   274  func (t *Interface) NumExplicitMethods() int { return len(t.methods) }
   275  
   276  // ExplicitMethod returns the i'th explicitly declared method of interface t for 0 <= i < t.NumExplicitMethods().
   277  // The methods are ordered by their unique Id.
   278  func (t *Interface) ExplicitMethod(i int) *Func { return t.methods[i] }
   279  
   280  // NumEmbeddeds returns the number of embedded types in interface t.
   281  func (t *Interface) NumEmbeddeds() int { return len(t.embeddeds) }
   282  
   283  // Embedded returns the i'th embedded type of interface t for 0 <= i < t.NumEmbeddeds().
   284  // The types are ordered by the corresponding TypeName's unique Id.
   285  func (t *Interface) Embedded(i int) *Named { return t.embeddeds[i] }
   286  
   287  // NumMethods returns the total number of methods of interface t.
   288  func (t *Interface) NumMethods() int { return len(t.allMethods) }
   289  
   290  // Method returns the i'th method of interface t for 0 <= i < t.NumMethods().
   291  // The methods are ordered by their unique Id.
   292  func (t *Interface) Method(i int) *Func { return t.allMethods[i] }
   293  
   294  // Empty returns true if t is the empty interface.
   295  func (t *Interface) Empty() bool { return len(t.allMethods) == 0 }
   296  
   297  // Complete computes the interface's method set. It must be called by users of
   298  // NewInterface after the interface's embedded types are fully defined and
   299  // before using the interface type in any way other than to form other types.
   300  // Complete returns the receiver.
   301  func (t *Interface) Complete() *Interface {
   302  	if t.allMethods != nil {
   303  		return t
   304  	}
   305  
   306  	var allMethods []*Func
   307  	if t.embeddeds == nil {
   308  		if t.methods == nil {
   309  			allMethods = make([]*Func, 0, 1)
   310  		} else {
   311  			allMethods = t.methods
   312  		}
   313  	} else {
   314  		allMethods = append(allMethods, t.methods...)
   315  		for _, et := range t.embeddeds {
   316  			it := et.Underlying().(*Interface)
   317  			it.Complete()
   318  			for _, tm := range it.allMethods {
   319  				// Make a copy of the method and adjust its receiver type.
   320  				newm := *tm
   321  				newmtyp := *tm.typ.(*Signature)
   322  				newm.typ = &newmtyp
   323  				newmtyp.recv = NewVar(newm.pos, newm.pkg, "", t)
   324  				allMethods = append(allMethods, &newm)
   325  			}
   326  		}
   327  		sort.Sort(byUniqueMethodName(allMethods))
   328  	}
   329  	t.allMethods = allMethods
   330  
   331  	return t
   332  }
   333  
   334  // A Map represents a map type.
   335  type Map struct {
   336  	key, elem Type
   337  }
   338  
   339  // NewMap returns a new map for the given key and element types.
   340  func NewMap(key, elem Type) *Map {
   341  	return &Map{key, elem}
   342  }
   343  
   344  // Key returns the key type of map m.
   345  func (m *Map) Key() Type { return m.key }
   346  
   347  // Elem returns the element type of map m.
   348  func (m *Map) Elem() Type { return m.elem }
   349  
   350  // A Chan represents a channel type.
   351  type Chan struct {
   352  	dir  ChanDir
   353  	elem Type
   354  }
   355  
   356  // A ChanDir value indicates a channel direction.
   357  type ChanDir int
   358  
   359  // The direction of a channel is indicated by one of these constants.
   360  const (
   361  	SendRecv ChanDir = iota
   362  	SendOnly
   363  	RecvOnly
   364  )
   365  
   366  // NewChan returns a new channel type for the given direction and element type.
   367  func NewChan(dir ChanDir, elem Type) *Chan {
   368  	return &Chan{dir, elem}
   369  }
   370  
   371  // Dir returns the direction of channel c.
   372  func (c *Chan) Dir() ChanDir { return c.dir }
   373  
   374  // Elem returns the element type of channel c.
   375  func (c *Chan) Elem() Type { return c.elem }
   376  
   377  // A Named represents a named type.
   378  type Named struct {
   379  	obj        *TypeName // corresponding declared object
   380  	underlying Type      // possibly a *Named during setup; never a *Named once set up completely
   381  	methods    []*Func   // methods declared for this type (not the method set of this type)
   382  }
   383  
   384  // NewNamed returns a new named type for the given type name, underlying type, and associated methods.
   385  // The underlying type must not be a *Named.
   386  func NewNamed(obj *TypeName, underlying Type, methods []*Func) *Named {
   387  	if _, ok := underlying.(*Named); ok {
   388  		panic("types.NewNamed: underlying type must not be *Named")
   389  	}
   390  	typ := &Named{obj: obj, underlying: underlying, methods: methods}
   391  	if obj.typ == nil {
   392  		obj.typ = typ
   393  	}
   394  	return typ
   395  }
   396  
   397  // Obj returns the type name for the named type t.
   398  func (t *Named) Obj() *TypeName { return t.obj }
   399  
   400  // NumMethods returns the number of explicit methods whose receiver is named type t.
   401  func (t *Named) NumMethods() int { return len(t.methods) }
   402  
   403  // Method returns the i'th method of named type t for 0 <= i < t.NumMethods().
   404  func (t *Named) Method(i int) *Func { return t.methods[i] }
   405  
   406  // SetUnderlying sets the underlying type and marks t as complete.
   407  // TODO(gri) determine if there's a better solution rather than providing this function
   408  func (t *Named) SetUnderlying(underlying Type) {
   409  	if underlying == nil {
   410  		panic("types.Named.SetUnderlying: underlying type must not be nil")
   411  	}
   412  	if _, ok := underlying.(*Named); ok {
   413  		panic("types.Named.SetUnderlying: underlying type must not be *Named")
   414  	}
   415  	t.underlying = underlying
   416  }
   417  
   418  // AddMethod adds method m unless it is already in the method list.
   419  // TODO(gri) find a better solution instead of providing this function
   420  func (t *Named) AddMethod(m *Func) {
   421  	if i, _ := lookupMethod(t.methods, m.pkg, m.name); i < 0 {
   422  		t.methods = append(t.methods, m)
   423  	}
   424  }
   425  
   426  // Implementations for Type methods.
   427  
   428  func (t *Basic) Underlying() Type     { return t }
   429  func (t *Array) Underlying() Type     { return t }
   430  func (t *Slice) Underlying() Type     { return t }
   431  func (t *Struct) Underlying() Type    { return t }
   432  func (t *Pointer) Underlying() Type   { return t }
   433  func (t *Tuple) Underlying() Type     { return t }
   434  func (t *Signature) Underlying() Type { return t }
   435  func (t *Interface) Underlying() Type { return t }
   436  func (t *Map) Underlying() Type       { return t }
   437  func (t *Chan) Underlying() Type      { return t }
   438  func (t *Named) Underlying() Type     { return t.underlying }
   439  
   440  func (t *Basic) String() string     { return TypeString(t, nil) }
   441  func (t *Array) String() string     { return TypeString(t, nil) }
   442  func (t *Slice) String() string     { return TypeString(t, nil) }
   443  func (t *Struct) String() string    { return TypeString(t, nil) }
   444  func (t *Pointer) String() string   { return TypeString(t, nil) }
   445  func (t *Tuple) String() string     { return TypeString(t, nil) }
   446  func (t *Signature) String() string { return TypeString(t, nil) }
   447  func (t *Interface) String() string { return TypeString(t, nil) }
   448  func (t *Map) String() string       { return TypeString(t, nil) }
   449  func (t *Chan) String() string      { return TypeString(t, nil) }
   450  func (t *Named) String() string     { return TypeString(t, nil) }