github.com/rsc/go@v0.0.0-20150416155037-e040fd465409/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  // TODO(gri) Revisit factory functions - make sure they have all relevant parameters.
    10  
    11  // A Type represents a type of Go.
    12  // All types implement the Type interface.
    13  type Type interface {
    14  	// Underlying returns the underlying type of a type.
    15  	Underlying() Type
    16  
    17  	// String returns a string representation of a type.
    18  	String() string
    19  }
    20  
    21  // BasicKind describes the kind of basic type.
    22  type BasicKind int
    23  
    24  const (
    25  	Invalid BasicKind = iota // type is invalid
    26  
    27  	// predeclared types
    28  	Bool
    29  	Int
    30  	Int8
    31  	Int16
    32  	Int32
    33  	Int64
    34  	Uint
    35  	Uint8
    36  	Uint16
    37  	Uint32
    38  	Uint64
    39  	Uintptr
    40  	Float32
    41  	Float64
    42  	Complex64
    43  	Complex128
    44  	String
    45  	UnsafePointer
    46  
    47  	// types for untyped values
    48  	UntypedBool
    49  	UntypedInt
    50  	UntypedRune
    51  	UntypedFloat
    52  	UntypedComplex
    53  	UntypedString
    54  	UntypedNil
    55  
    56  	// aliases
    57  	Byte = Uint8
    58  	Rune = Int32
    59  )
    60  
    61  // BasicInfo is a set of flags describing properties of a basic type.
    62  type BasicInfo int
    63  
    64  // Properties of basic types.
    65  const (
    66  	IsBoolean BasicInfo = 1 << iota
    67  	IsInteger
    68  	IsUnsigned
    69  	IsFloat
    70  	IsComplex
    71  	IsString
    72  	IsUntyped
    73  
    74  	IsOrdered   = IsInteger | IsFloat | IsString
    75  	IsNumeric   = IsInteger | IsFloat | IsComplex
    76  	IsConstType = IsBoolean | IsNumeric | IsString
    77  )
    78  
    79  // A Basic represents a basic type.
    80  type Basic struct {
    81  	kind BasicKind
    82  	info BasicInfo
    83  	name string
    84  }
    85  
    86  // Kind returns the kind of basic type b.
    87  func (b *Basic) Kind() BasicKind { return b.kind }
    88  
    89  // Info returns information about properties of basic type b.
    90  func (b *Basic) Info() BasicInfo { return b.info }
    91  
    92  // Name returns the name of basic type b.
    93  func (b *Basic) Name() string { return b.name }
    94  
    95  // An Array represents an array type.
    96  type Array struct {
    97  	len  int64
    98  	elem Type
    99  }
   100  
   101  // NewArray returns a new array type for the given element type and length.
   102  func NewArray(elem Type, len int64) *Array { return &Array{len, elem} }
   103  
   104  // Len returns the length of array a.
   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  	// TODO(gri) access to offsets is not threadsafe - fix this
   126  	offsets []int64 // field offsets in bytes, lazily initialized
   127  }
   128  
   129  // NewStruct returns a new struct with the given fields and corresponding field tags.
   130  // If a field with index i has a tag, tags[i] must be that tag, but len(tags) may be
   131  // only as long as required to hold the tag with the largest index i. Consequently,
   132  // if no field has a tag, tags may be nil.
   133  func NewStruct(fields []*Var, tags []string) *Struct {
   134  	var fset objset
   135  	for _, f := range fields {
   136  		if f.name != "_" && fset.insert(f) != nil {
   137  			panic("multiple fields with the same name")
   138  		}
   139  	}
   140  	if len(tags) > len(fields) {
   141  		panic("more tags than fields")
   142  	}
   143  	return &Struct{fields: fields, tags: tags}
   144  }
   145  
   146  // NumFields returns the number of fields in the struct (including blank and anonymous fields).
   147  func (s *Struct) NumFields() int { return len(s.fields) }
   148  
   149  // Field returns the i'th field for 0 <= i < NumFields().
   150  func (s *Struct) Field(i int) *Var { return s.fields[i] }
   151  
   152  // Tag returns the i'th field tag for 0 <= i < NumFields().
   153  func (s *Struct) Tag(i int) string {
   154  	if i < len(s.tags) {
   155  		return s.tags[i]
   156  	}
   157  	return ""
   158  }
   159  
   160  // A Pointer represents a pointer type.
   161  type Pointer struct {
   162  	base Type // element type
   163  }
   164  
   165  // NewPointer returns a new pointer type for the given element (base) type.
   166  func NewPointer(elem Type) *Pointer { return &Pointer{base: elem} }
   167  
   168  // Elem returns the element type for the given pointer p.
   169  func (p *Pointer) Elem() Type { return p.base }
   170  
   171  // A Tuple represents an ordered list of variables; a nil *Tuple is a valid (empty) tuple.
   172  // Tuples are used as components of signatures and to represent the type of multiple
   173  // assignments; they are not first class types of Go.
   174  type Tuple struct {
   175  	vars []*Var
   176  }
   177  
   178  // NewTuple returns a new tuple for the given variables.
   179  func NewTuple(x ...*Var) *Tuple {
   180  	if len(x) > 0 {
   181  		return &Tuple{x}
   182  	}
   183  	return nil
   184  }
   185  
   186  // Len returns the number variables of tuple t.
   187  func (t *Tuple) Len() int {
   188  	if t != nil {
   189  		return len(t.vars)
   190  	}
   191  	return 0
   192  }
   193  
   194  // At returns the i'th variable of tuple t.
   195  func (t *Tuple) At(i int) *Var { return t.vars[i] }
   196  
   197  // A Signature represents a (non-builtin) function or method type.
   198  type Signature struct {
   199  	scope    *Scope // function scope, always present
   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(scope *Scope, recv *Var, params, results *Tuple, variadic bool) *Signature {
   211  	// TODO(gri) Should we rely on the correct (non-nil) incoming scope
   212  	//           or should this function allocate and populate a scope?
   213  	if variadic {
   214  		n := params.Len()
   215  		if n == 0 {
   216  			panic("types.NewSignature: variadic function must have at least one parameter")
   217  		}
   218  		if _, ok := params.At(n - 1).typ.(*Slice); !ok {
   219  			panic("types.NewSignature: variadic parameter must be of unnamed slice type")
   220  		}
   221  	}
   222  	return &Signature{scope, recv, params, results, variadic}
   223  }
   224  
   225  // Recv returns the receiver of signature s (if a method), or nil if a
   226  // function.
   227  //
   228  // For an abstract method, Recv returns the enclosing interface either
   229  // as a *Named or an *Interface.  Due to embedding, an interface may
   230  // contain methods whose receiver type is a different interface.
   231  func (s *Signature) Recv() *Var { return s.recv }
   232  
   233  // Params returns the parameters of signature s, or nil.
   234  func (s *Signature) Params() *Tuple { return s.params }
   235  
   236  // Results returns the results of signature s, or nil.
   237  func (s *Signature) Results() *Tuple { return s.results }
   238  
   239  // Variadic reports whether the signature s is variadic.
   240  func (s *Signature) Variadic() bool { return s.variadic }
   241  
   242  // An Interface represents an interface type.
   243  type Interface struct {
   244  	methods   []*Func  // ordered list of explicitly declared methods
   245  	embeddeds []*Named // ordered list of explicitly embedded types
   246  
   247  	allMethods []*Func // ordered list of methods declared with or embedded in this interface (TODO(gri): replace with mset)
   248  }
   249  
   250  // NewInterface returns a new interface for the given methods and embedded types.
   251  func NewInterface(methods []*Func, embeddeds []*Named) *Interface {
   252  	typ := new(Interface)
   253  
   254  	var mset objset
   255  	for _, m := range methods {
   256  		if mset.insert(m) != nil {
   257  			panic("multiple methods with the same name")
   258  		}
   259  		// set receiver
   260  		// TODO(gri) Ideally, we should use a named type here instead of
   261  		// typ, for less verbose printing of interface method signatures.
   262  		m.typ.(*Signature).recv = NewVar(m.pos, m.pkg, "", typ)
   263  	}
   264  	sort.Sort(byUniqueMethodName(methods))
   265  
   266  	if embeddeds == nil {
   267  		sort.Sort(byUniqueTypeName(embeddeds))
   268  	}
   269  
   270  	typ.methods = methods
   271  	typ.embeddeds = embeddeds
   272  	return typ
   273  }
   274  
   275  // NumExplicitMethods returns the number of explicitly declared methods of interface t.
   276  func (t *Interface) NumExplicitMethods() int { return len(t.methods) }
   277  
   278  // ExplicitMethod returns the i'th explicitly declared method of interface t for 0 <= i < t.NumExplicitMethods().
   279  // The methods are ordered by their unique Id.
   280  func (t *Interface) ExplicitMethod(i int) *Func { return t.methods[i] }
   281  
   282  // NumEmbeddeds returns the number of embedded types in interface t.
   283  func (t *Interface) NumEmbeddeds() int { return len(t.embeddeds) }
   284  
   285  // Embedded returns the i'th embedded type of interface t for 0 <= i < t.NumEmbeddeds().
   286  // The types are ordered by the corresponding TypeName's unique Id.
   287  func (t *Interface) Embedded(i int) *Named { return t.embeddeds[i] }
   288  
   289  // NumMethods returns the total number of methods of interface t.
   290  func (t *Interface) NumMethods() int { return len(t.allMethods) }
   291  
   292  // Method returns the i'th method of interface t for 0 <= i < t.NumMethods().
   293  // The methods are ordered by their unique Id.
   294  func (t *Interface) Method(i int) *Func { return t.allMethods[i] }
   295  
   296  // Empty returns true if t is the empty interface.
   297  func (t *Interface) Empty() bool { return len(t.allMethods) == 0 }
   298  
   299  // Complete computes the interface's method set. It must be called by users of
   300  // NewInterface after the interface's embedded types are fully defined and
   301  // before using the interface type in any way other than to form other types.
   302  // Complete returns the receiver.
   303  func (t *Interface) Complete() *Interface {
   304  	if t.allMethods != nil {
   305  		return t
   306  	}
   307  
   308  	var allMethods []*Func
   309  	if t.embeddeds == nil {
   310  		if t.methods == nil {
   311  			allMethods = make([]*Func, 0, 1)
   312  		} else {
   313  			allMethods = t.methods
   314  		}
   315  	} else {
   316  		allMethods = append(allMethods, t.methods...)
   317  		for _, et := range t.embeddeds {
   318  			it := et.Underlying().(*Interface)
   319  			it.Complete()
   320  			for _, tm := range it.allMethods {
   321  				// Make a copy of the method and adjust its receiver type.
   322  				newm := *tm
   323  				newmtyp := *tm.typ.(*Signature)
   324  				newm.typ = &newmtyp
   325  				newmtyp.recv = NewVar(newm.pos, newm.pkg, "", t)
   326  				allMethods = append(allMethods, &newm)
   327  			}
   328  		}
   329  		sort.Sort(byUniqueMethodName(allMethods))
   330  	}
   331  	t.allMethods = allMethods
   332  
   333  	return t
   334  }
   335  
   336  // A Map represents a map type.
   337  type Map struct {
   338  	key, elem Type
   339  }
   340  
   341  // NewMap returns a new map for the given key and element types.
   342  func NewMap(key, elem Type) *Map {
   343  	return &Map{key, elem}
   344  }
   345  
   346  // Key returns the key type of map m.
   347  func (m *Map) Key() Type { return m.key }
   348  
   349  // Elem returns the element type of map m.
   350  func (m *Map) Elem() Type { return m.elem }
   351  
   352  // A Chan represents a channel type.
   353  type Chan struct {
   354  	dir  ChanDir
   355  	elem Type
   356  }
   357  
   358  // A ChanDir value indicates a channel direction.
   359  type ChanDir int
   360  
   361  // The direction of a channel is indicated by one of the following constants.
   362  const (
   363  	SendRecv ChanDir = iota
   364  	SendOnly
   365  	RecvOnly
   366  )
   367  
   368  // NewChan returns a new channel type for the given direction and element type.
   369  func NewChan(dir ChanDir, elem Type) *Chan {
   370  	return &Chan{dir, elem}
   371  }
   372  
   373  // Dir returns the direction of channel c.
   374  func (c *Chan) Dir() ChanDir { return c.dir }
   375  
   376  // Elem returns the element type of channel c.
   377  func (c *Chan) Elem() Type { return c.elem }
   378  
   379  // A Named represents a named type.
   380  type Named struct {
   381  	obj        *TypeName // corresponding declared object
   382  	underlying Type      // possibly a *Named during setup; never a *Named once set up completely
   383  	methods    []*Func   // methods declared for this type (not the method set of this type)
   384  }
   385  
   386  // NewNamed returns a new named type for the given type name, underlying type, and associated methods.
   387  // The underlying type must not be a *Named.
   388  func NewNamed(obj *TypeName, underlying Type, methods []*Func) *Named {
   389  	if _, ok := underlying.(*Named); ok {
   390  		panic("types.NewNamed: underlying type must not be *Named")
   391  	}
   392  	typ := &Named{obj: obj, underlying: underlying, methods: methods}
   393  	if obj.typ == nil {
   394  		obj.typ = typ
   395  	}
   396  	return typ
   397  }
   398  
   399  // TypeName returns the type name for the named type t.
   400  func (t *Named) Obj() *TypeName { return t.obj }
   401  
   402  // NumMethods returns the number of explicit methods whose receiver is named type t.
   403  func (t *Named) NumMethods() int { return len(t.methods) }
   404  
   405  // Method returns the i'th method of named type t for 0 <= i < t.NumMethods().
   406  func (t *Named) Method(i int) *Func { return t.methods[i] }
   407  
   408  // SetUnderlying sets the underlying type and marks t as complete.
   409  // TODO(gri) determine if there's a better solution rather than providing this function
   410  func (t *Named) SetUnderlying(underlying Type) {
   411  	if underlying == nil {
   412  		panic("types.Named.SetUnderlying: underlying type must not be nil")
   413  	}
   414  	if _, ok := underlying.(*Named); ok {
   415  		panic("types.Named.SetUnderlying: underlying type must not be *Named")
   416  	}
   417  	t.underlying = underlying
   418  }
   419  
   420  // AddMethod adds method m unless it is already in the method list.
   421  // TODO(gri) find a better solution instead of providing this function
   422  func (t *Named) AddMethod(m *Func) {
   423  	if i, _ := lookupMethod(t.methods, m.pkg, m.name); i < 0 {
   424  		t.methods = append(t.methods, m)
   425  	}
   426  }
   427  
   428  // Implementations for Type methods.
   429  
   430  func (t *Basic) Underlying() Type     { return t }
   431  func (t *Array) Underlying() Type     { return t }
   432  func (t *Slice) Underlying() Type     { return t }
   433  func (t *Struct) Underlying() Type    { return t }
   434  func (t *Pointer) Underlying() Type   { return t }
   435  func (t *Tuple) Underlying() Type     { return t }
   436  func (t *Signature) Underlying() Type { return t }
   437  func (t *Interface) Underlying() Type { return t }
   438  func (t *Map) Underlying() Type       { return t }
   439  func (t *Chan) Underlying() Type      { return t }
   440  func (t *Named) Underlying() Type     { return t.underlying }
   441  
   442  func (t *Basic) String() string     { return TypeString(nil, t) }
   443  func (t *Array) String() string     { return TypeString(nil, t) }
   444  func (t *Slice) String() string     { return TypeString(nil, t) }
   445  func (t *Struct) String() string    { return TypeString(nil, t) }
   446  func (t *Pointer) String() string   { return TypeString(nil, t) }
   447  func (t *Tuple) String() string     { return TypeString(nil, t) }
   448  func (t *Signature) String() string { return TypeString(nil, t) }
   449  func (t *Interface) String() string { return TypeString(nil, t) }
   450  func (t *Map) String() string       { return TypeString(nil, t) }
   451  func (t *Chan) String() string      { return TypeString(nil, t) }
   452  func (t *Named) String() string     { return TypeString(nil, t) }