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