]> Cypherpunks.ru repositories - gostls13.git/blob - src/go/types/type.go
go/types: revert "no 'declared but not used' errors for invalid var decls"
[gostls13.git] / src / go / types / type.go
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 // A Type represents a type of Go.
8 // All types implement the Type interface.
9 type Type interface {
10         // Underlying returns the underlying type of a type.
11         Underlying() Type
12
13         // String returns a string representation of a type.
14         String() string
15 }
16
17 // BasicKind describes the kind of basic type.
18 type BasicKind int
19
20 const (
21         Invalid BasicKind = iota // type is invalid
22
23         // predeclared types
24         Bool
25         Int
26         Int8
27         Int16
28         Int32
29         Int64
30         Uint
31         Uint8
32         Uint16
33         Uint32
34         Uint64
35         Uintptr
36         Float32
37         Float64
38         Complex64
39         Complex128
40         String
41         UnsafePointer
42
43         // types for untyped values
44         UntypedBool
45         UntypedInt
46         UntypedRune
47         UntypedFloat
48         UntypedComplex
49         UntypedString
50         UntypedNil
51
52         // aliases
53         Byte = Uint8
54         Rune = Int32
55 )
56
57 // BasicInfo is a set of flags describing properties of a basic type.
58 type BasicInfo int
59
60 // Properties of basic types.
61 const (
62         IsBoolean BasicInfo = 1 << iota
63         IsInteger
64         IsUnsigned
65         IsFloat
66         IsComplex
67         IsString
68         IsUntyped
69
70         IsOrdered   = IsInteger | IsFloat | IsString
71         IsNumeric   = IsInteger | IsFloat | IsComplex
72         IsConstType = IsBoolean | IsNumeric | IsString
73 )
74
75 // A Basic represents a basic type.
76 type Basic struct {
77         kind BasicKind
78         info BasicInfo
79         name string
80 }
81
82 // Kind returns the kind of basic type b.
83 func (b *Basic) Kind() BasicKind { return b.kind }
84
85 // Info returns information about properties of basic type b.
86 func (b *Basic) Info() BasicInfo { return b.info }
87
88 // Name returns the name of basic type b.
89 func (b *Basic) Name() string { return b.name }
90
91 // An Array represents an array type.
92 type Array struct {
93         len  int64
94         elem Type
95 }
96
97 // NewArray returns a new array type for the given element type and length.
98 // A negative length indicates an unknown length.
99 func NewArray(elem Type, len int64) *Array { return &Array{len, elem} }
100
101 // Len returns the length of array a.
102 // A negative result indicates an unknown length.
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 embedded 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 []Type  // 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 // emptyInterface represents the empty (completed) interface
250 var emptyInterface = Interface{allMethods: markComplete}
251
252 // markComplete is used to mark an empty interface as completely
253 // set up by setting the allMethods field to a non-nil empty slice.
254 var markComplete = make([]*Func, 0)
255
256 // NewInterface returns a new (incomplete) interface for the given methods and embedded types.
257 // Each embedded type must have an underlying type of interface type.
258 // NewInterface takes ownership of the provided methods and may modify their types by setting
259 // missing receivers. To compute the method set of the interface, Complete must be called.
260 //
261 // Deprecated: Use NewInterfaceType instead which allows any (even non-defined) interface types
262 // to be embedded. This is necessary for interfaces that embed alias type names referring to
263 // non-defined (literal) interface types.
264 func NewInterface(methods []*Func, embeddeds []*Named) *Interface {
265         tnames := make([]Type, len(embeddeds))
266         for i, t := range embeddeds {
267                 tnames[i] = t
268         }
269         return NewInterfaceType(methods, tnames)
270 }
271
272 // NewInterfaceType returns a new (incomplete) interface for the given methods and embedded types.
273 // Each embedded type must have an underlying type of interface type (this property is not
274 // verified for defined types, which may be in the process of being set up and which don't
275 // have a valid underlying type yet).
276 // NewInterfaceType takes ownership of the provided methods and may modify their types by setting
277 // missing receivers. To compute the method set of the interface, Complete must be called.
278 func NewInterfaceType(methods []*Func, embeddeds []Type) *Interface {
279         if len(methods) == 0 && len(embeddeds) == 0 {
280                 return &emptyInterface
281         }
282
283         // set method receivers if necessary
284         typ := new(Interface)
285         for _, m := range methods {
286                 if sig := m.typ.(*Signature); sig.recv == nil {
287                         sig.recv = NewVar(m.pos, m.pkg, "", typ)
288                 }
289         }
290
291         // All embedded types should be interfaces; however, defined types
292         // may not yet be fully resolved. Only verify that non-defined types
293         // are interfaces. This matches the behavior of the code before the
294         // fix for #25301 (issue #25596).
295         for _, t := range embeddeds {
296                 if _, ok := t.(*Named); !ok && !IsInterface(t) {
297                         panic("embedded type is not an interface")
298                 }
299         }
300
301         // sort for API stability
302         sortMethods(methods)
303         sortTypes(embeddeds)
304
305         typ.methods = methods
306         typ.embeddeds = embeddeds
307         return typ
308 }
309
310 // NumExplicitMethods returns the number of explicitly declared methods of interface t.
311 func (t *Interface) NumExplicitMethods() int { return len(t.methods) }
312
313 // ExplicitMethod returns the i'th explicitly declared method of interface t for 0 <= i < t.NumExplicitMethods().
314 // The methods are ordered by their unique Id.
315 func (t *Interface) ExplicitMethod(i int) *Func { return t.methods[i] }
316
317 // NumEmbeddeds returns the number of embedded types in interface t.
318 func (t *Interface) NumEmbeddeds() int { return len(t.embeddeds) }
319
320 // Embedded returns the i'th embedded defined (*Named) type of interface t for 0 <= i < t.NumEmbeddeds().
321 // The result is nil if the i'th embedded type is not a defined type.
322 //
323 // Deprecated: Use EmbeddedType which is not restricted to defined (*Named) types.
324 func (t *Interface) Embedded(i int) *Named { tname, _ := t.embeddeds[i].(*Named); return tname }
325
326 // EmbeddedType returns the i'th embedded type of interface t for 0 <= i < t.NumEmbeddeds().
327 func (t *Interface) EmbeddedType(i int) Type { return t.embeddeds[i] }
328
329 // NumMethods returns the total number of methods of interface t.
330 // The interface must have been completed.
331 func (t *Interface) NumMethods() int { t.assertCompleteness(); return len(t.allMethods) }
332
333 func (t *Interface) assertCompleteness() {
334         if t.allMethods == nil {
335                 panic("interface is incomplete")
336         }
337 }
338
339 // Method returns the i'th method of interface t for 0 <= i < t.NumMethods().
340 // The methods are ordered by their unique Id.
341 // The interface must have been completed.
342 func (t *Interface) Method(i int) *Func { t.assertCompleteness(); return t.allMethods[i] }
343
344 // Empty reports whether t is the empty interface.
345 // The interface must have been completed.
346 func (t *Interface) Empty() bool { t.assertCompleteness(); return len(t.allMethods) == 0 }
347
348 // Complete computes the interface's method set. It must be called by users of
349 // NewInterfaceType and NewInterface after the interface's embedded types are
350 // fully defined and before using the interface type in any way other than to
351 // form other types. The interface must not contain duplicate methods or a
352 // panic occurs. Complete returns the receiver.
353 func (t *Interface) Complete() *Interface {
354         // TODO(gri) consolidate this method with Checker.completeInterface
355         if t.allMethods != nil {
356                 return t
357         }
358
359         t.allMethods = markComplete // avoid infinite recursion
360
361         var todo []*Func
362         var methods []*Func
363         var seen objset
364         addMethod := func(m *Func, explicit bool) {
365                 switch other := seen.insert(m); {
366                 case other == nil:
367                         methods = append(methods, m)
368                 case explicit:
369                         panic("duplicate method " + m.name)
370                 default:
371                         // check method signatures after all locally embedded interfaces are computed
372                         todo = append(todo, m, other.(*Func))
373                 }
374         }
375
376         for _, m := range t.methods {
377                 addMethod(m, true)
378         }
379
380         for _, typ := range t.embeddeds {
381                 typ := typ.Underlying().(*Interface)
382                 typ.Complete()
383                 for _, m := range typ.allMethods {
384                         addMethod(m, false)
385                 }
386         }
387
388         for i := 0; i < len(todo); i += 2 {
389                 m := todo[i]
390                 other := todo[i+1]
391                 if !Identical(m.typ, other.typ) {
392                         panic("duplicate method " + m.name)
393                 }
394         }
395
396         if methods != nil {
397                 sortMethods(methods)
398                 t.allMethods = methods
399         }
400
401         return t
402 }
403
404 // A Map represents a map type.
405 type Map struct {
406         key, elem Type
407 }
408
409 // NewMap returns a new map for the given key and element types.
410 func NewMap(key, elem Type) *Map {
411         return &Map{key, elem}
412 }
413
414 // Key returns the key type of map m.
415 func (m *Map) Key() Type { return m.key }
416
417 // Elem returns the element type of map m.
418 func (m *Map) Elem() Type { return m.elem }
419
420 // A Chan represents a channel type.
421 type Chan struct {
422         dir  ChanDir
423         elem Type
424 }
425
426 // A ChanDir value indicates a channel direction.
427 type ChanDir int
428
429 // The direction of a channel is indicated by one of these constants.
430 const (
431         SendRecv ChanDir = iota
432         SendOnly
433         RecvOnly
434 )
435
436 // NewChan returns a new channel type for the given direction and element type.
437 func NewChan(dir ChanDir, elem Type) *Chan {
438         return &Chan{dir, elem}
439 }
440
441 // Dir returns the direction of channel c.
442 func (c *Chan) Dir() ChanDir { return c.dir }
443
444 // Elem returns the element type of channel c.
445 func (c *Chan) Elem() Type { return c.elem }
446
447 // A Named represents a named type.
448 type Named struct {
449         info       typeInfo  // for cycle detection
450         obj        *TypeName // corresponding declared object
451         orig       Type      // type (on RHS of declaration) this *Named type is derived of (for cycle reporting)
452         underlying Type      // possibly a *Named during setup; never a *Named once set up completely
453         methods    []*Func   // methods declared for this type (not the method set of this type); signatures are type-checked lazily
454 }
455
456 // NewNamed returns a new named type for the given type name, underlying type, and associated methods.
457 // If the given type name obj doesn't have a type yet, its type is set to the returned named type.
458 // The underlying type must not be a *Named.
459 func NewNamed(obj *TypeName, underlying Type, methods []*Func) *Named {
460         if _, ok := underlying.(*Named); ok {
461                 panic("types.NewNamed: underlying type must not be *Named")
462         }
463         typ := &Named{obj: obj, orig: underlying, underlying: underlying, methods: methods}
464         if obj.typ == nil {
465                 obj.typ = typ
466         }
467         return typ
468 }
469
470 // Obj returns the type name for the named type t.
471 func (t *Named) Obj() *TypeName { return t.obj }
472
473 // NumMethods returns the number of explicit methods whose receiver is named type t.
474 func (t *Named) NumMethods() int { return len(t.methods) }
475
476 // Method returns the i'th method of named type t for 0 <= i < t.NumMethods().
477 func (t *Named) Method(i int) *Func { return t.methods[i] }
478
479 // SetUnderlying sets the underlying type and marks t as complete.
480 func (t *Named) SetUnderlying(underlying Type) {
481         if underlying == nil {
482                 panic("types.Named.SetUnderlying: underlying type must not be nil")
483         }
484         if _, ok := underlying.(*Named); ok {
485                 panic("types.Named.SetUnderlying: underlying type must not be *Named")
486         }
487         t.underlying = underlying
488 }
489
490 // AddMethod adds method m unless it is already in the method list.
491 func (t *Named) AddMethod(m *Func) {
492         if i, _ := lookupMethod(t.methods, m.pkg, m.name); i < 0 {
493                 t.methods = append(t.methods, m)
494         }
495 }
496
497 // Implementations for Type methods.
498
499 func (b *Basic) Underlying() Type     { return b }
500 func (a *Array) Underlying() Type     { return a }
501 func (s *Slice) Underlying() Type     { return s }
502 func (s *Struct) Underlying() Type    { return s }
503 func (p *Pointer) Underlying() Type   { return p }
504 func (t *Tuple) Underlying() Type     { return t }
505 func (s *Signature) Underlying() Type { return s }
506 func (t *Interface) Underlying() Type { return t }
507 func (m *Map) Underlying() Type       { return m }
508 func (c *Chan) Underlying() Type      { return c }
509 func (t *Named) Underlying() Type     { return t.underlying }
510
511 func (b *Basic) String() string     { return TypeString(b, nil) }
512 func (a *Array) String() string     { return TypeString(a, nil) }
513 func (s *Slice) String() string     { return TypeString(s, nil) }
514 func (s *Struct) String() string    { return TypeString(s, nil) }
515 func (p *Pointer) String() string   { return TypeString(p, nil) }
516 func (t *Tuple) String() string     { return TypeString(t, nil) }
517 func (s *Signature) String() string { return TypeString(s, nil) }
518 func (t *Interface) String() string { return TypeString(t, nil) }
519 func (m *Map) String() string       { return TypeString(m, nil) }
520 func (c *Chan) String() string      { return TypeString(c, nil) }
521 func (t *Named) String() string     { return TypeString(t, nil) }