github.com/mattn/go@v0.0.0-20171011075504-07f7db3ea99f/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  // 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)
   205  }
   206  
   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 {
   212  	if variadic {
   213  		n := params.Len()
   214  		if n == 0 {
   215  			panic("types.NewSignature: variadic function must have at least one parameter")
   216  		}
   217  		if _, ok := params.At(n - 1).typ.(*Slice); !ok {
   218  			panic("types.NewSignature: variadic parameter must be of unnamed slice type")
   219  		}
   220  	}
   221  	return &Signature{nil, recv, params, results, variadic}
   222  }
   223  
   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.
   226  //
   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 }
   231  
   232  // Params returns the parameters of signature s, or nil.
   233  func (s *Signature) Params() *Tuple { return s.params }
   234  
   235  // Results returns the results of signature s, or nil.
   236  func (s *Signature) Results() *Tuple { return s.results }
   237  
   238  // Variadic reports whether the signature s is variadic.
   239  func (s *Signature) Variadic() bool { return s.variadic }
   240  
   241  // An Interface represents an interface type.
   242  type Interface struct {
   243  	methods   []*Func  // ordered list of explicitly declared methods
   244  	embeddeds []*Named // ordered list of explicitly embedded types
   245  
   246  	allMethods []*Func // ordered list of methods declared with or embedded in this interface (TODO(gri): replace with mset)
   247  }
   248  
   249  // NewInterface returns a new interface for the given methods and embedded types.
   250  func NewInterface(methods []*Func, embeddeds []*Named) *Interface {
   251  	typ := new(Interface)
   252  
   253  	var mset objset
   254  	for _, m := range methods {
   255  		if mset.insert(m) != nil {
   256  			panic("multiple methods with the same name")
   257  		}
   258  		// set receiver
   259  		// TODO(gri) Ideally, we should use a named type here instead of
   260  		// typ, for less verbose printing of interface method signatures.
   261  		m.typ.(*Signature).recv = NewVar(m.pos, m.pkg, "", typ)
   262  	}
   263  	sort.Sort(byUniqueMethodName(methods))
   264  
   265  	if embeddeds == nil {
   266  		sort.Sort(byUniqueTypeName(embeddeds))
   267  	}
   268  
   269  	typ.methods = methods
   270  	typ.embeddeds = embeddeds
   271  	return typ
   272  }
   273  
   274  // NumExplicitMethods returns the number of explicitly declared methods of interface t.
   275  func (t *Interface) NumExplicitMethods() int { return len(t.methods) }
   276  
   277  // ExplicitMethod returns the i'th explicitly declared method of interface t for 0 <= i < t.NumExplicitMethods().
   278  // The methods are ordered by their unique Id.
   279  func (t *Interface) ExplicitMethod(i int) *Func { return t.methods[i] }
   280  
   281  // NumEmbeddeds returns the number of embedded types in interface t.
   282  func (t *Interface) NumEmbeddeds() int { return len(t.embeddeds) }
   283  
   284  // Embedded returns the i'th embedded type of interface t for 0 <= i < t.NumEmbeddeds().
   285  // The types are ordered by the corresponding TypeName's unique Id.
   286  func (t *Interface) Embedded(i int) *Named { return t.embeddeds[i] }
   287  
   288  // NumMethods returns the total number of methods of interface t.
   289  func (t *Interface) NumMethods() int { return len(t.allMethods) }
   290  
   291  // Method returns the i'th method of interface t for 0 <= i < t.NumMethods().
   292  // The methods are ordered by their unique Id.
   293  func (t *Interface) Method(i int) *Func { return t.allMethods[i] }
   294  
   295  // Empty returns true if t is the empty interface.
   296  func (t *Interface) Empty() bool { return len(t.allMethods) == 0 }
   297  
   298  // Complete computes the interface's method set. It must be called by users of
   299  // NewInterface after the interface's embedded types are fully defined and
   300  // before using the interface type in any way other than to form other types.
   301  // Complete returns the receiver.
   302  func (t *Interface) Complete() *Interface {
   303  	if t.allMethods != nil {
   304  		return t
   305  	}
   306  
   307  	var allMethods []*Func
   308  	if t.embeddeds == nil {
   309  		if t.methods == nil {
   310  			allMethods = make([]*Func, 0, 1)
   311  		} else {
   312  			allMethods = t.methods
   313  		}
   314  	} else {
   315  		allMethods = append(allMethods, t.methods...)
   316  		for _, et := range t.embeddeds {
   317  			it := et.Underlying().(*Interface)
   318  			it.Complete()
   319  			for _, tm := range it.allMethods {
   320  				// Make a copy of the method and adjust its receiver type.
   321  				newm := *tm
   322  				newmtyp := *tm.typ.(*Signature)
   323  				newm.typ = &newmtyp
   324  				newmtyp.recv = NewVar(newm.pos, newm.pkg, "", t)
   325  				allMethods = append(allMethods, &newm)
   326  			}
   327  		}
   328  		sort.Sort(byUniqueMethodName(allMethods))
   329  	}
   330  	t.allMethods = allMethods
   331  
   332  	return t
   333  }
   334  
   335  // A Map represents a map type.
   336  type Map struct {
   337  	key, elem Type
   338  }
   339  
   340  // NewMap returns a new map for the given key and element types.
   341  func NewMap(key, elem Type) *Map {
   342  	return &Map{key, elem}
   343  }
   344  
   345  // Key returns the key type of map m.
   346  func (m *Map) Key() Type { return m.key }
   347  
   348  // Elem returns the element type of map m.
   349  func (m *Map) Elem() Type { return m.elem }
   350  
   351  // A Chan represents a channel type.
   352  type Chan struct {
   353  	dir  ChanDir
   354  	elem Type
   355  }
   356  
   357  // A ChanDir value indicates a channel direction.
   358  type ChanDir int
   359  
   360  // The direction of a channel is indicated by one of these constants.
   361  const (
   362  	SendRecv ChanDir = iota
   363  	SendOnly
   364  	RecvOnly
   365  )
   366  
   367  // NewChan returns a new channel type for the given direction and element type.
   368  func NewChan(dir ChanDir, elem Type) *Chan {
   369  	return &Chan{dir, elem}
   370  }
   371  
   372  // Dir returns the direction of channel c.
   373  func (c *Chan) Dir() ChanDir { return c.dir }
   374  
   375  // Elem returns the element type of channel c.
   376  func (c *Chan) Elem() Type { return c.elem }
   377  
   378  // A Named represents a named type.
   379  type Named struct {
   380  	obj        *TypeName // corresponding declared object
   381  	underlying Type      // possibly a *Named during setup; never a *Named once set up completely
   382  	methods    []*Func   // methods declared for this type (not the method set of this type)
   383  }
   384  
   385  // NewNamed returns a new named type for the given type name, underlying type, and associated methods.
   386  // The underlying type must not be a *Named.
   387  func NewNamed(obj *TypeName, underlying Type, methods []*Func) *Named {
   388  	if _, ok := underlying.(*Named); ok {
   389  		panic("types.NewNamed: underlying type must not be *Named")
   390  	}
   391  	typ := &Named{obj: obj, underlying: underlying, methods: methods}
   392  	if obj.typ == nil {
   393  		obj.typ = typ
   394  	}
   395  	return typ
   396  }
   397  
   398  // Obj returns the type name for the named type t.
   399  func (t *Named) Obj() *TypeName { return t.obj }
   400  
   401  // NumMethods returns the number of explicit methods whose receiver is named type t.
   402  func (t *Named) NumMethods() int { return len(t.methods) }
   403  
   404  // Method returns the i'th method of named type t for 0 <= i < t.NumMethods().
   405  func (t *Named) Method(i int) *Func { return t.methods[i] }
   406  
   407  // SetUnderlying sets the underlying type and marks t as complete.
   408  // TODO(gri) determine if there's a better solution rather than providing this function
   409  func (t *Named) SetUnderlying(underlying Type) {
   410  	if underlying == nil {
   411  		panic("types.Named.SetUnderlying: underlying type must not be nil")
   412  	}
   413  	if _, ok := underlying.(*Named); ok {
   414  		panic("types.Named.SetUnderlying: underlying type must not be *Named")
   415  	}
   416  	t.underlying = underlying
   417  }
   418  
   419  // AddMethod adds method m unless it is already in the method list.
   420  // TODO(gri) find a better solution instead of providing this function
   421  func (t *Named) AddMethod(m *Func) {
   422  	if i, _ := lookupMethod(t.methods, m.pkg, m.name); i < 0 {
   423  		t.methods = append(t.methods, m)
   424  	}
   425  }
   426  
   427  // Implementations for Type methods.
   428  
   429  func (t *Basic) Underlying() Type     { return t }
   430  func (t *Array) Underlying() Type     { return t }
   431  func (t *Slice) Underlying() Type     { return t }
   432  func (t *Struct) Underlying() Type    { return t }
   433  func (t *Pointer) Underlying() Type   { return t }
   434  func (t *Tuple) Underlying() Type     { return t }
   435  func (t *Signature) Underlying() Type { return t }
   436  func (t *Interface) Underlying() Type { return t }
   437  func (t *Map) Underlying() Type       { return t }
   438  func (t *Chan) Underlying() Type      { return t }
   439  func (t *Named) Underlying() Type     { return t.underlying }
   440  
   441  func (t *Basic) String() string     { return TypeString(t, nil) }
   442  func (t *Array) String() string     { return TypeString(t, nil) }
   443  func (t *Slice) String() string     { return TypeString(t, nil) }
   444  func (t *Struct) String() string    { return TypeString(t, nil) }
   445  func (t *Pointer) String() string   { return TypeString(t, nil) }
   446  func (t *Tuple) String() string     { return TypeString(t, nil) }
   447  func (t *Signature) String() string { return TypeString(t, nil) }
   448  func (t *Interface) String() string { return TypeString(t, nil) }
   449  func (t *Map) String() string       { return TypeString(t, nil) }
   450  func (t *Chan) String() string      { return TypeString(t, nil) }
   451  func (t *Named) String() string     { return TypeString(t, nil) }