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