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