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 (
8	"sort"
9	"sync"
10)
11
12// A Type represents a type of Go.
13// All types implement the Type interface.
14type 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.
23type BasicKind int
24
25const (
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.
63type BasicInfo int
64
65// Properties of basic types.
66const (
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.
81type Basic struct {
82	kind BasicKind
83	info BasicInfo
84	name string
85}
86
87// Kind returns the kind of basic type b.
88func (b *Basic) Kind() BasicKind { return b.kind }
89
90// Info returns information about properties of basic type b.
91func (b *Basic) Info() BasicInfo { return b.info }
92
93// Name returns the name of basic type b.
94func (b *Basic) Name() string { return b.name }
95
96// An Array represents an array type.
97type Array struct {
98	len  int64
99	elem Type
100}
101
102// NewArray returns a new array type for the given element type and length.
103func NewArray(elem Type, len int64) *Array { return &Array{len, elem} }
104
105// Len returns the length of array a.
106func (a *Array) Len() int64 { return a.len }
107
108// Elem returns element type of array a.
109func (a *Array) Elem() Type { return a.elem }
110
111// A Slice represents a slice type.
112type Slice struct {
113	elem Type
114}
115
116// NewSlice returns a new slice type for the given element type.
117func NewSlice(elem Type) *Slice { return &Slice{elem} }
118
119// Elem returns the element type of slice s.
120func (s *Slice) Elem() Type { return s.elem }
121
122// A Struct represents a struct type.
123type 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.
134func 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).
148func (s *Struct) NumFields() int { return len(s.fields) }
149
150// Field returns the i'th field for 0 <= i < NumFields().
151func (s *Struct) Field(i int) *Var { return s.fields[i] }
152
153// Tag returns the i'th field tag for 0 <= i < NumFields().
154func (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.
162type Pointer struct {
163	base Type // element type
164}
165
166// NewPointer returns a new pointer type for the given element (base) type.
167func NewPointer(elem Type) *Pointer { return &Pointer{base: elem} }
168
169// Elem returns the element type for the given pointer p.
170func (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.
175type Tuple struct {
176	vars []*Var
177}
178
179// NewTuple returns a new tuple for the given variables.
180func 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.
188func (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.
196func (t *Tuple) At(i int) *Var { return t.vars[i] }
197
198// A Signature represents a (non-builtin) function or method type.
199type 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.
215func 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.
234func (s *Signature) Recv() *Var { return s.recv }
235
236// Params returns the parameters of signature s, or nil.
237func (s *Signature) Params() *Tuple { return s.params }
238
239// Results returns the results of signature s, or nil.
240func (s *Signature) Results() *Tuple { return s.results }
241
242// Variadic reports whether the signature s is variadic.
243func (s *Signature) Variadic() bool { return s.variadic }
244
245// An Interface represents an interface type.
246type 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.
254func 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.
279func (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.
283func (t *Interface) ExplicitMethod(i int) *Func { return t.methods[i] }
284
285// NumEmbeddeds returns the number of embedded types in interface t.
286func (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.
290func (t *Interface) Embedded(i int) *Named { return t.embeddeds[i] }
291
292// NumMethods returns the total number of methods of interface t.
293func (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.
297func (t *Interface) Method(i int) *Func { return t.allMethods[i] }
298
299// Empty returns true if t is the empty interface.
300func (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.
306func (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.
340type Map struct {
341	key, elem Type
342}
343
344// NewMap returns a new map for the given key and element types.
345func NewMap(key, elem Type) *Map {
346	return &Map{key, elem}
347}
348
349// Key returns the key type of map m.
350func (m *Map) Key() Type { return m.key }
351
352// Elem returns the element type of map m.
353func (m *Map) Elem() Type { return m.elem }
354
355// A Chan represents a channel type.
356type Chan struct {
357	dir  ChanDir
358	elem Type
359}
360
361// A ChanDir value indicates a channel direction.
362type ChanDir int
363
364// The direction of a channel is indicated by one of these constants.
365const (
366	SendRecv ChanDir = iota
367	SendOnly
368	RecvOnly
369)
370
371// NewChan returns a new channel type for the given direction and element type.
372func NewChan(dir ChanDir, elem Type) *Chan {
373	return &Chan{dir, elem}
374}
375
376// Dir returns the direction of channel c.
377func (c *Chan) Dir() ChanDir { return c.dir }
378
379// Elem returns the element type of channel c.
380func (c *Chan) Elem() Type { return c.elem }
381
382// A Named represents a named type.
383type 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.
391func 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.
403func (t *Named) Obj() *TypeName { return t.obj }
404
405// NumMethods returns the number of explicit methods whose receiver is named type t.
406func (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().
409func (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
413func (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
425func (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
433func (t *Basic) Underlying() Type     { return t }
434func (t *Array) Underlying() Type     { return t }
435func (t *Slice) Underlying() Type     { return t }
436func (t *Struct) Underlying() Type    { return t }
437func (t *Pointer) Underlying() Type   { return t }
438func (t *Tuple) Underlying() Type     { return t }
439func (t *Signature) Underlying() Type { return t }
440func (t *Interface) Underlying() Type { return t }
441func (t *Map) Underlying() Type       { return t }
442func (t *Chan) Underlying() Type      { return t }
443func (t *Named) Underlying() Type     { return t.underlying }
444
445func (t *Basic) String() string     { return TypeString(t, nil) }
446func (t *Array) String() string     { return TypeString(t, nil) }
447func (t *Slice) String() string     { return TypeString(t, nil) }
448func (t *Struct) String() string    { return TypeString(t, nil) }
449func (t *Pointer) String() string   { return TypeString(t, nil) }
450func (t *Tuple) String() string     { return TypeString(t, nil) }
451func (t *Signature) String() string { return TypeString(t, nil) }
452func (t *Interface) String() string { return TypeString(t, nil) }
453func (t *Map) String() string       { return TypeString(t, nil) }
454func (t *Chan) String() string      { return TypeString(t, nil) }
455func (t *Named) String() string     { return TypeString(t, nil) }
456