]> Cypherpunks.ru repositories - gostls13.git/blob - src/cmd/compile/internal/types2/typestring.go
cmd/compile/internal/types2: use []*TypeParam rather than []*TypeName for type param...
[gostls13.git] / src / cmd / compile / internal / types2 / typestring.go
1 // Copyright 2013 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 // This file implements printing of types.
6
7 package types2
8
9 import (
10         "bytes"
11         "fmt"
12         "unicode/utf8"
13 )
14
15 // A Qualifier controls how named package-level objects are printed in
16 // calls to TypeString, ObjectString, and SelectionString.
17 //
18 // These three formatting routines call the Qualifier for each
19 // package-level object O, and if the Qualifier returns a non-empty
20 // string p, the object is printed in the form p.O.
21 // If it returns an empty string, only the object name O is printed.
22 //
23 // Using a nil Qualifier is equivalent to using (*Package).Path: the
24 // object is qualified by the import path, e.g., "encoding/json.Marshal".
25 //
26 type Qualifier func(*Package) string
27
28 // RelativeTo returns a Qualifier that fully qualifies members of
29 // all packages other than pkg.
30 func RelativeTo(pkg *Package) Qualifier {
31         if pkg == nil {
32                 return nil
33         }
34         return func(other *Package) string {
35                 if pkg == other {
36                         return "" // same package; unqualified
37                 }
38                 return other.Path()
39         }
40 }
41
42 // TypeString returns the string representation of typ.
43 // The Qualifier controls the printing of
44 // package-level objects, and may be nil.
45 func TypeString(typ Type, qf Qualifier) string {
46         var buf bytes.Buffer
47         WriteType(&buf, typ, qf)
48         return buf.String()
49 }
50
51 // WriteType writes the string representation of typ to buf.
52 // The Qualifier controls the printing of
53 // package-level objects, and may be nil.
54 func WriteType(buf *bytes.Buffer, typ Type, qf Qualifier) {
55         writeType(buf, typ, qf, make([]Type, 0, 8))
56 }
57
58 // instanceMarker is the prefix for an instantiated type
59 // in "non-evaluated" instance form.
60 const instanceMarker = '#'
61
62 func writeType(buf *bytes.Buffer, typ Type, qf Qualifier, visited []Type) {
63         // Theoretically, this is a quadratic lookup algorithm, but in
64         // practice deeply nested composite types with unnamed component
65         // types are uncommon. This code is likely more efficient than
66         // using a map.
67         for _, t := range visited {
68                 if t == typ {
69                         fmt.Fprintf(buf, "○%T", goTypeName(typ)) // cycle to typ
70                         return
71                 }
72         }
73         visited = append(visited, typ)
74
75         switch t := typ.(type) {
76         case nil:
77                 buf.WriteString("<nil>")
78
79         case *Basic:
80                 // exported basic types go into package unsafe
81                 // (currently this is just unsafe.Pointer)
82                 if isExported(t.name) {
83                         if obj, _ := Unsafe.scope.Lookup(t.name).(*TypeName); obj != nil {
84                                 writeTypeName(buf, obj, qf)
85                                 break
86                         }
87                 }
88                 buf.WriteString(t.name)
89
90         case *Array:
91                 fmt.Fprintf(buf, "[%d]", t.len)
92                 writeType(buf, t.elem, qf, visited)
93
94         case *Slice:
95                 buf.WriteString("[]")
96                 writeType(buf, t.elem, qf, visited)
97
98         case *Struct:
99                 buf.WriteString("struct{")
100                 for i, f := range t.fields {
101                         if i > 0 {
102                                 buf.WriteString("; ")
103                         }
104                         // This doesn't do the right thing for embedded type
105                         // aliases where we should print the alias name, not
106                         // the aliased type (see issue #44410).
107                         if !f.embedded {
108                                 buf.WriteString(f.name)
109                                 buf.WriteByte(' ')
110                         }
111                         writeType(buf, f.typ, qf, visited)
112                         if tag := t.Tag(i); tag != "" {
113                                 fmt.Fprintf(buf, " %q", tag)
114                         }
115                 }
116                 buf.WriteByte('}')
117
118         case *Pointer:
119                 buf.WriteByte('*')
120                 writeType(buf, t.base, qf, visited)
121
122         case *Tuple:
123                 writeTuple(buf, t, false, qf, visited)
124
125         case *Signature:
126                 buf.WriteString("func")
127                 writeSignature(buf, t, qf, visited)
128
129         case *Union:
130                 // Unions only appear as (syntactic) embedded elements
131                 // in interfaces and syntactically cannot be empty.
132                 if t.Len() == 0 {
133                         panic("empty union")
134                 }
135                 for i, t := range t.terms {
136                         if i > 0 {
137                                 buf.WriteByte('|')
138                         }
139                         if t.tilde {
140                                 buf.WriteByte('~')
141                         }
142                         writeType(buf, t.typ, qf, visited)
143                 }
144
145         case *Interface:
146                 buf.WriteString("interface{")
147                 first := true
148                 for _, m := range t.methods {
149                         if !first {
150                                 buf.WriteString("; ")
151                         }
152                         first = false
153                         buf.WriteString(m.name)
154                         writeSignature(buf, m.typ.(*Signature), qf, visited)
155                 }
156                 for _, typ := range t.embeddeds {
157                         if !first {
158                                 buf.WriteString("; ")
159                         }
160                         first = false
161                         writeType(buf, typ, qf, visited)
162                 }
163                 buf.WriteByte('}')
164
165         case *Map:
166                 buf.WriteString("map[")
167                 writeType(buf, t.key, qf, visited)
168                 buf.WriteByte(']')
169                 writeType(buf, t.elem, qf, visited)
170
171         case *Chan:
172                 var s string
173                 var parens bool
174                 switch t.dir {
175                 case SendRecv:
176                         s = "chan "
177                         // chan (<-chan T) requires parentheses
178                         if c, _ := t.elem.(*Chan); c != nil && c.dir == RecvOnly {
179                                 parens = true
180                         }
181                 case SendOnly:
182                         s = "chan<- "
183                 case RecvOnly:
184                         s = "<-chan "
185                 default:
186                         unreachable()
187                 }
188                 buf.WriteString(s)
189                 if parens {
190                         buf.WriteByte('(')
191                 }
192                 writeType(buf, t.elem, qf, visited)
193                 if parens {
194                         buf.WriteByte(')')
195                 }
196
197         case *Named:
198                 if t.instance != nil {
199                         buf.WriteByte(instanceMarker)
200                 }
201                 writeTypeName(buf, t.obj, qf)
202                 if t.targs != nil {
203                         // instantiated type
204                         buf.WriteByte('[')
205                         writeTypeList(buf, t.targs, qf, visited)
206                         buf.WriteByte(']')
207                 } else if t.TParams().Len() != 0 {
208                         // parameterized type
209                         writeTParamList(buf, t.TParams().list(), qf, visited)
210                 }
211
212         case *TypeParam:
213                 s := "?"
214                 if t.obj != nil {
215                         // Optionally write out package for typeparams (like Named).
216                         // TODO(danscales): this is required for import/export, so
217                         // we maybe need a separate function that won't be changed
218                         // for debugging purposes.
219                         if t.obj.pkg != nil {
220                                 writePackage(buf, t.obj.pkg, qf)
221                         }
222                         s = t.obj.name
223                 }
224                 buf.WriteString(s + subscript(t.id))
225
226         case *top:
227                 buf.WriteString("⊤")
228
229         default:
230                 // For externally defined implementations of Type.
231                 // Note: In this case cycles won't be caught.
232                 buf.WriteString(t.String())
233         }
234 }
235
236 func writeTypeList(buf *bytes.Buffer, list []Type, qf Qualifier, visited []Type) {
237         for i, typ := range list {
238                 if i > 0 {
239                         buf.WriteString(", ")
240                 }
241                 writeType(buf, typ, qf, visited)
242         }
243 }
244
245 func writeTParamList(buf *bytes.Buffer, list []*TypeParam, qf Qualifier, visited []Type) {
246         buf.WriteString("[")
247         var prev Type
248         for i, tpar := range list {
249                 // Determine the type parameter and its constraint.
250                 // list is expected to hold type parameter names,
251                 // but don't crash if that's not the case.
252                 var bound Type
253                 if tpar != nil {
254                         bound = tpar.bound // should not be nil but we want to see it if it is
255                 }
256
257                 if i > 0 {
258                         if bound != prev {
259                                 // bound changed - write previous one before advancing
260                                 buf.WriteByte(' ')
261                                 writeType(buf, prev, qf, visited)
262                         }
263                         buf.WriteString(", ")
264                 }
265                 prev = bound
266
267                 if tpar != nil {
268                         writeType(buf, tpar, qf, visited)
269                 } else {
270                         buf.WriteString(tpar.obj.name)
271                 }
272         }
273         if prev != nil {
274                 buf.WriteByte(' ')
275                 writeType(buf, prev, qf, visited)
276         }
277         buf.WriteByte(']')
278 }
279
280 func writeTypeName(buf *bytes.Buffer, obj *TypeName, qf Qualifier) {
281         if obj == nil {
282                 buf.WriteString("<Named w/o object>")
283                 return
284         }
285         if obj.pkg != nil {
286                 writePackage(buf, obj.pkg, qf)
287         }
288         buf.WriteString(obj.name)
289
290         if instanceHashing != 0 {
291                 // For local defined types, use the (original!) TypeName's scope
292                 // numbers to disambiguate.
293                 typ := obj.typ.(*Named)
294                 // TODO(gri) Figure out why typ.orig != typ.orig.orig sometimes
295                 //           and whether the loop can iterate more than twice.
296                 //           (It seems somehow connected to instance types.)
297                 for typ.orig != typ {
298                         typ = typ.orig
299                 }
300                 writeScopeNumbers(buf, typ.obj.parent)
301         }
302 }
303
304 // writeScopeNumbers writes the number sequence for this scope to buf
305 // in the form ".i.j.k" where i, j, k, etc. stand for scope numbers.
306 // If a scope is nil or has no parent (such as a package scope), nothing
307 // is written.
308 func writeScopeNumbers(buf *bytes.Buffer, s *Scope) {
309         if s != nil && s.number > 0 {
310                 writeScopeNumbers(buf, s.parent)
311                 fmt.Fprintf(buf, ".%d", s.number)
312         }
313 }
314
315 func writeTuple(buf *bytes.Buffer, tup *Tuple, variadic bool, qf Qualifier, visited []Type) {
316         buf.WriteByte('(')
317         if tup != nil {
318                 for i, v := range tup.vars {
319                         if i > 0 {
320                                 buf.WriteString(", ")
321                         }
322                         if v.name != "" {
323                                 buf.WriteString(v.name)
324                                 buf.WriteByte(' ')
325                         }
326                         typ := v.typ
327                         if variadic && i == len(tup.vars)-1 {
328                                 if s, ok := typ.(*Slice); ok {
329                                         buf.WriteString("...")
330                                         typ = s.elem
331                                 } else {
332                                         // special case:
333                                         // append(s, "foo"...) leads to signature func([]byte, string...)
334                                         if t := asBasic(typ); t == nil || t.kind != String {
335                                                 panic("expected string type")
336                                         }
337                                         writeType(buf, typ, qf, visited)
338                                         buf.WriteString("...")
339                                         continue
340                                 }
341                         }
342                         writeType(buf, typ, qf, visited)
343                 }
344         }
345         buf.WriteByte(')')
346 }
347
348 // WriteSignature writes the representation of the signature sig to buf,
349 // without a leading "func" keyword.
350 // The Qualifier controls the printing of
351 // package-level objects, and may be nil.
352 func WriteSignature(buf *bytes.Buffer, sig *Signature, qf Qualifier) {
353         writeSignature(buf, sig, qf, make([]Type, 0, 8))
354 }
355
356 func writeSignature(buf *bytes.Buffer, sig *Signature, qf Qualifier, visited []Type) {
357         if sig.TParams().Len() != 0 {
358                 writeTParamList(buf, sig.TParams().list(), qf, visited)
359         }
360
361         writeTuple(buf, sig.params, sig.variadic, qf, visited)
362
363         n := sig.results.Len()
364         if n == 0 {
365                 // no result
366                 return
367         }
368
369         buf.WriteByte(' ')
370         if n == 1 && sig.results.vars[0].name == "" {
371                 // single unnamed result
372                 writeType(buf, sig.results.vars[0].typ, qf, visited)
373                 return
374         }
375
376         // multiple or named result(s)
377         writeTuple(buf, sig.results, false, qf, visited)
378 }
379
380 // subscript returns the decimal (utf8) representation of x using subscript digits.
381 func subscript(x uint64) string {
382         const w = len("₀") // all digits 0...9 have the same utf8 width
383         var buf [32 * w]byte
384         i := len(buf)
385         for {
386                 i -= w
387                 utf8.EncodeRune(buf[i:], '₀'+rune(x%10)) // '₀' == U+2080
388                 x /= 10
389                 if x == 0 {
390                         break
391                 }
392         }
393         return string(buf[i:])
394 }