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
5package types
6
7import "sort"
8
9// A Type represents a type of Go.
10// All types implement the Type interface.
11type 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.
20type BasicKind int
21
22const (
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.
60type BasicInfo int
61
62// Properties of basic types.
63const (
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.
78type Basic struct {
79	kind BasicKind
80	info BasicInfo
81	name string
82}
83
84// Kind returns the kind of basic type b.
85func (b *Basic) Kind() BasicKind { return b.kind }
86
87// Info returns information about properties of basic type b.
88func (b *Basic) Info() BasicInfo { return b.info }
89
90// Name returns the name of basic type b.
91func (b *Basic) Name() string { return b.name }
92
93// An Array represents an array type.
94type Array struct {
95	len  int64
96	elem Type
97}
98
99// NewArray returns a new array type for the given element type and length.
100func NewArray(elem Type, len int64) *Array { return &Array{len, elem} }
101
102// Len returns the length of array a.
103func (a *Array) Len() int64 { return a.len }
104
105// Elem returns element type of array a.
106func (a *Array) Elem() Type { return a.elem }
107
108// A Slice represents a slice type.
109type Slice struct {
110	elem Type
111}
112
113// NewSlice returns a new slice type for the given element type.
114func NewSlice(elem Type) *Slice { return &Slice{elem} }
115
116// Elem returns the element type of slice s.
117func (s *Slice) Elem() Type { return s.elem }
118
119// A Struct represents a struct type.
120type 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.
129func 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).
143func (s *Struct) NumFields() int { return len(s.fields) }
144
145// Field returns the i'th field for 0 <= i < NumFields().
146func (s *Struct) Field(i int) *Var { return s.fields[i] }
147
148// Tag returns the i'th field tag for 0 <= i < NumFields().
149func (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.
157type Pointer struct {
158	base Type // element type
159}
160
161// NewPointer returns a new pointer type for the given element (base) type.
162func NewPointer(elem Type) *Pointer { return &Pointer{base: elem} }
163
164// Elem returns the element type for the given pointer p.
165func (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.
170type Tuple struct {
171	vars []*Var
172}
173
174// NewTuple returns a new tuple for the given variables.
175func 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.
183func (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.
191func (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.
195type 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.
211func 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.
230func (s *Signature) Recv() *Var { return s.recv }
231
232// Params returns the parameters of signature s, or nil.
233func (s *Signature) Params() *Tuple { return s.params }
234
235// Results returns the results of signature s, or nil.
236func (s *Signature) Results() *Tuple { return s.results }
237
238// Variadic reports whether the signature s is variadic.
239func (s *Signature) Variadic() bool { return s.variadic }
240
241// An Interface represents an interface type.
242type 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// emptyInterface represents the empty (completed) interface
250var 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.
254var markComplete = make([]*Func, 0)
255
256// NewInterface returns a new (incomplete) interface for the given methods and embedded types.
257// To compute the method set of the interface, Complete must be called.
258func NewInterface(methods []*Func, embeddeds []*Named) *Interface {
259	typ := new(Interface)
260
261	if len(methods) == 0 && len(embeddeds) == 0 {
262		return typ
263	}
264
265	var mset objset
266	for _, m := range methods {
267		if mset.insert(m) != nil {
268			panic("multiple methods with the same name")
269		}
270		// set receiver
271		// TODO(gri) Ideally, we should use a named type here instead of
272		// typ, for less verbose printing of interface method signatures.
273		m.typ.(*Signature).recv = NewVar(m.pos, m.pkg, "", typ)
274	}
275	sort.Sort(byUniqueMethodName(methods))
276
277	if embeddeds != nil {
278		sort.Sort(byUniqueTypeName(embeddeds))
279	}
280
281	typ.methods = methods
282	typ.embeddeds = embeddeds
283	return typ
284}
285
286// NumExplicitMethods returns the number of explicitly declared methods of interface t.
287func (t *Interface) NumExplicitMethods() int { return len(t.methods) }
288
289// ExplicitMethod returns the i'th explicitly declared method of interface t for 0 <= i < t.NumExplicitMethods().
290// The methods are ordered by their unique Id.
291func (t *Interface) ExplicitMethod(i int) *Func { return t.methods[i] }
292
293// NumEmbeddeds returns the number of embedded types in interface t.
294func (t *Interface) NumEmbeddeds() int { return len(t.embeddeds) }
295
296// Embedded returns the i'th embedded type of interface t for 0 <= i < t.NumEmbeddeds().
297// The types are ordered by the corresponding TypeName's unique Id.
298func (t *Interface) Embedded(i int) *Named { return t.embeddeds[i] }
299
300// NumMethods returns the total number of methods of interface t.
301func (t *Interface) NumMethods() int { return len(t.allMethods) }
302
303// Method returns the i'th method of interface t for 0 <= i < t.NumMethods().
304// The methods are ordered by their unique Id.
305func (t *Interface) Method(i int) *Func { return t.allMethods[i] }
306
307// Empty returns true if t is the empty interface.
308func (t *Interface) Empty() bool { return len(t.allMethods) == 0 }
309
310// Complete computes the interface's method set. It must be called by users of
311// NewInterface after the interface's embedded types are fully defined and
312// before using the interface type in any way other than to form other types.
313// Complete returns the receiver.
314func (t *Interface) Complete() *Interface {
315	if t.allMethods != nil {
316		return t
317	}
318
319	var allMethods []*Func
320	if t.embeddeds == nil {
321		if t.methods == nil {
322			allMethods = make([]*Func, 0, 1)
323		} else {
324			allMethods = t.methods
325		}
326	} else {
327		allMethods = append(allMethods, t.methods...)
328		for _, et := range t.embeddeds {
329			it := et.Underlying().(*Interface)
330			it.Complete()
331			for _, tm := range it.allMethods {
332				// Make a copy of the method and adjust its receiver type.
333				newm := *tm
334				newmtyp := *tm.typ.(*Signature)
335				newm.typ = &newmtyp
336				newmtyp.recv = NewVar(newm.pos, newm.pkg, "", t)
337				allMethods = append(allMethods, &newm)
338			}
339		}
340		sort.Sort(byUniqueMethodName(allMethods))
341	}
342	t.allMethods = allMethods
343
344	return t
345}
346
347// A Map represents a map type.
348type Map struct {
349	key, elem Type
350}
351
352// NewMap returns a new map for the given key and element types.
353func NewMap(key, elem Type) *Map {
354	return &Map{key, elem}
355}
356
357// Key returns the key type of map m.
358func (m *Map) Key() Type { return m.key }
359
360// Elem returns the element type of map m.
361func (m *Map) Elem() Type { return m.elem }
362
363// A Chan represents a channel type.
364type Chan struct {
365	dir  ChanDir
366	elem Type
367}
368
369// A ChanDir value indicates a channel direction.
370type ChanDir int
371
372// The direction of a channel is indicated by one of these constants.
373const (
374	SendRecv ChanDir = iota
375	SendOnly
376	RecvOnly
377)
378
379// NewChan returns a new channel type for the given direction and element type.
380func NewChan(dir ChanDir, elem Type) *Chan {
381	return &Chan{dir, elem}
382}
383
384// Dir returns the direction of channel c.
385func (c *Chan) Dir() ChanDir { return c.dir }
386
387// Elem returns the element type of channel c.
388func (c *Chan) Elem() Type { return c.elem }
389
390// A Named represents a named type.
391type Named struct {
392	obj        *TypeName // corresponding declared object
393	underlying Type      // possibly a *Named during setup; never a *Named once set up completely
394	methods    []*Func   // methods declared for this type (not the method set of this type)
395}
396
397// NewNamed returns a new named type for the given type name, underlying type, and associated methods.
398// If the given type name obj doesn't have a type yet, its type is set to the returned named type.
399// The underlying type must not be a *Named.
400func NewNamed(obj *TypeName, underlying Type, methods []*Func) *Named {
401	if _, ok := underlying.(*Named); ok {
402		panic("types.NewNamed: underlying type must not be *Named")
403	}
404	typ := &Named{obj: obj, underlying: underlying, methods: methods}
405	if obj.typ == nil {
406		obj.typ = typ
407	}
408	return typ
409}
410
411// Obj returns the type name for the named type t.
412func (t *Named) Obj() *TypeName { return t.obj }
413
414// NumMethods returns the number of explicit methods whose receiver is named type t.
415func (t *Named) NumMethods() int { return len(t.methods) }
416
417// Method returns the i'th method of named type t for 0 <= i < t.NumMethods().
418func (t *Named) Method(i int) *Func { return t.methods[i] }
419
420// SetUnderlying sets the underlying type and marks t as complete.
421func (t *Named) SetUnderlying(underlying Type) {
422	if underlying == nil {
423		panic("types.Named.SetUnderlying: underlying type must not be nil")
424	}
425	if _, ok := underlying.(*Named); ok {
426		panic("types.Named.SetUnderlying: underlying type must not be *Named")
427	}
428	t.underlying = underlying
429}
430
431// AddMethod adds method m unless it is already in the method list.
432func (t *Named) AddMethod(m *Func) {
433	if i, _ := lookupMethod(t.methods, m.pkg, m.name); i < 0 {
434		t.methods = append(t.methods, m)
435	}
436}
437
438// Implementations for Type methods.
439
440func (t *Basic) Underlying() Type     { return t }
441func (t *Array) Underlying() Type     { return t }
442func (t *Slice) Underlying() Type     { return t }
443func (t *Struct) Underlying() Type    { return t }
444func (t *Pointer) Underlying() Type   { return t }
445func (t *Tuple) Underlying() Type     { return t }
446func (t *Signature) Underlying() Type { return t }
447func (t *Interface) Underlying() Type { return t }
448func (t *Map) Underlying() Type       { return t }
449func (t *Chan) Underlying() Type      { return t }
450func (t *Named) Underlying() Type     { return t.underlying }
451
452func (t *Basic) String() string     { return TypeString(t, nil) }
453func (t *Array) String() string     { return TypeString(t, nil) }
454func (t *Slice) String() string     { return TypeString(t, nil) }
455func (t *Struct) String() string    { return TypeString(t, nil) }
456func (t *Pointer) String() string   { return TypeString(t, nil) }
457func (t *Tuple) String() string     { return TypeString(t, nil) }
458func (t *Signature) String() string { return TypeString(t, nil) }
459func (t *Interface) String() string { return TypeString(t, nil) }
460func (t *Map) String() string       { return TypeString(t, nil) }
461func (t *Chan) String() string      { return TypeString(t, nil) }
462func (t *Named) String() string     { return TypeString(t, nil) }
463