]> Cypherpunks.ru repositories - gostls13.git/blob - src/cmd/compile/internal/types2/typestring.go
[dev.typeparams] all: merge master (fdab5be) into dev.typeparams
[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 // If gcCompatibilityMode is set, printing of types is modified
43 // to match the representation of some types in the gc compiler:
44 //
45 //      - byte and rune lose their alias name and simply stand for
46 //        uint8 and int32 respectively
47 //      - embedded interfaces get flattened (the embedding info is lost,
48 //        and certain recursive interface types cannot be printed anymore)
49 //
50 // This makes it easier to compare packages computed with the type-
51 // checker vs packages imported from gc export data.
52 //
53 // Caution: This flag affects all uses of WriteType, globally.
54 // It is only provided for testing in conjunction with
55 // gc-generated data.
56 //
57 // This flag is exported in the x/tools/go/types package. We don't
58 // need it at the moment in the std repo and so we don't export it
59 // anymore. We should eventually try to remove it altogether.
60 // TODO(gri) remove this
61 var gcCompatibilityMode bool
62
63 // TypeString returns the string representation of typ.
64 // The Qualifier controls the printing of
65 // package-level objects, and may be nil.
66 func TypeString(typ Type, qf Qualifier) string {
67         var buf bytes.Buffer
68         WriteType(&buf, typ, qf)
69         return buf.String()
70 }
71
72 // WriteType writes the string representation of typ to buf.
73 // The Qualifier controls the printing of
74 // package-level objects, and may be nil.
75 func WriteType(buf *bytes.Buffer, typ Type, qf Qualifier) {
76         writeType(buf, typ, qf, make([]Type, 0, 8))
77 }
78
79 // instanceMarker is the prefix for an instantiated type
80 // in "non-evaluated" instance form.
81 const instanceMarker = '#'
82
83 func writeType(buf *bytes.Buffer, typ Type, qf Qualifier, visited []Type) {
84         // Theoretically, this is a quadratic lookup algorithm, but in
85         // practice deeply nested composite types with unnamed component
86         // types are uncommon. This code is likely more efficient than
87         // using a map.
88         for _, t := range visited {
89                 if t == typ {
90                         fmt.Fprintf(buf, "○%T", goTypeName(typ)) // cycle to typ
91                         return
92                 }
93         }
94         visited = append(visited, typ)
95
96         switch t := typ.(type) {
97         case nil:
98                 buf.WriteString("<nil>")
99
100         case *Basic:
101                 // exported basic types go into package unsafe
102                 // (currently this is just unsafe.Pointer)
103                 if isExported(t.name) {
104                         if obj, _ := Unsafe.scope.Lookup(t.name).(*TypeName); obj != nil {
105                                 writeTypeName(buf, obj, qf)
106                                 break
107                         }
108                 }
109
110                 if gcCompatibilityMode {
111                         // forget the alias names
112                         switch t.kind {
113                         case Byte:
114                                 t = Typ[Uint8]
115                         case Rune:
116                                 t = Typ[Int32]
117                         }
118                 }
119                 buf.WriteString(t.name)
120
121         case *Array:
122                 fmt.Fprintf(buf, "[%d]", t.len)
123                 writeType(buf, t.elem, qf, visited)
124
125         case *Slice:
126                 buf.WriteString("[]")
127                 writeType(buf, t.elem, qf, visited)
128
129         case *Struct:
130                 buf.WriteString("struct{")
131                 for i, f := range t.fields {
132                         if i > 0 {
133                                 buf.WriteString("; ")
134                         }
135                         // This doesn't do the right thing for embedded type
136                         // aliases where we should print the alias name, not
137                         // the aliased type (see issue #44410).
138                         if !f.embedded {
139                                 buf.WriteString(f.name)
140                                 buf.WriteByte(' ')
141                         }
142                         writeType(buf, f.typ, qf, visited)
143                         if tag := t.Tag(i); tag != "" {
144                                 fmt.Fprintf(buf, " %q", tag)
145                         }
146                 }
147                 buf.WriteByte('}')
148
149         case *Pointer:
150                 buf.WriteByte('*')
151                 writeType(buf, t.base, qf, visited)
152
153         case *Tuple:
154                 writeTuple(buf, t, false, qf, visited)
155
156         case *Signature:
157                 buf.WriteString("func")
158                 writeSignature(buf, t, qf, visited)
159
160         case *Union:
161                 if t.IsEmpty() {
162                         buf.WriteString("⊥")
163                         break
164                 }
165                 for i, e := range t.types {
166                         if i > 0 {
167                                 buf.WriteString("|")
168                         }
169                         if t.tilde[i] {
170                                 buf.WriteByte('~')
171                         }
172                         writeType(buf, e, qf, visited)
173                 }
174
175         case *Interface:
176                 // We write the source-level methods and embedded types rather
177                 // than the actual method set since resolved method signatures
178                 // may have non-printable cycles if parameters have embedded
179                 // interface types that (directly or indirectly) embed the
180                 // current interface. For instance, consider the result type
181                 // of m:
182                 //
183                 //     type T interface{
184                 //         m() interface{ T }
185                 //     }
186                 //
187                 buf.WriteString("interface{")
188                 empty := true
189                 if gcCompatibilityMode {
190                         // print flattened interface
191                         // (useful to compare against gc-generated interfaces)
192                         for i, m := range t.allMethods {
193                                 if i > 0 {
194                                         buf.WriteString("; ")
195                                 }
196                                 buf.WriteString(m.name)
197                                 writeSignature(buf, m.typ.(*Signature), qf, visited)
198                                 empty = false
199                         }
200                         if !empty && t.allTypes != nil {
201                                 buf.WriteString("; ")
202                         }
203                         if t.allTypes != nil {
204                                 buf.WriteString("type ")
205                                 writeType(buf, t.allTypes, qf, visited)
206                         }
207                 } else {
208                         // print explicit interface methods and embedded types
209                         for i, m := range t.methods {
210                                 if i > 0 {
211                                         buf.WriteString("; ")
212                                 }
213                                 buf.WriteString(m.name)
214                                 writeSignature(buf, m.typ.(*Signature), qf, visited)
215                                 empty = false
216                         }
217                         if !empty && len(t.embeddeds) > 0 {
218                                 buf.WriteString("; ")
219                         }
220                         for i, typ := range t.embeddeds {
221                                 if i > 0 {
222                                         buf.WriteString("; ")
223                                 }
224                                 writeType(buf, typ, qf, visited)
225                                 empty = false
226                         }
227                 }
228                 if debug && (t.allMethods == nil || len(t.methods) > len(t.allMethods)) {
229                         if !empty {
230                                 buf.WriteByte(' ')
231                         }
232                         buf.WriteString("/* incomplete */")
233                 }
234                 buf.WriteByte('}')
235
236         case *Map:
237                 buf.WriteString("map[")
238                 writeType(buf, t.key, qf, visited)
239                 buf.WriteByte(']')
240                 writeType(buf, t.elem, qf, visited)
241
242         case *Chan:
243                 var s string
244                 var parens bool
245                 switch t.dir {
246                 case SendRecv:
247                         s = "chan "
248                         // chan (<-chan T) requires parentheses
249                         if c, _ := t.elem.(*Chan); c != nil && c.dir == RecvOnly {
250                                 parens = true
251                         }
252                 case SendOnly:
253                         s = "chan<- "
254                 case RecvOnly:
255                         s = "<-chan "
256                 default:
257                         panic("unreachable")
258                 }
259                 buf.WriteString(s)
260                 if parens {
261                         buf.WriteByte('(')
262                 }
263                 writeType(buf, t.elem, qf, visited)
264                 if parens {
265                         buf.WriteByte(')')
266                 }
267
268         case *Named:
269                 writeTypeName(buf, t.obj, qf)
270                 if t.targs != nil {
271                         // instantiated type
272                         buf.WriteByte('[')
273                         writeTypeList(buf, t.targs, qf, visited)
274                         buf.WriteByte(']')
275                 } else if t.TParams() != nil {
276                         // parameterized type
277                         writeTParamList(buf, t.TParams(), qf, visited)
278                 }
279
280         case *TypeParam:
281                 s := "?"
282                 if t.obj != nil {
283                         // Optionally write out package for typeparams (like Named).
284                         // TODO(danscales): this is required for import/export, so
285                         // we maybe need a separate function that won't be changed
286                         // for debugging purposes.
287                         if t.obj.pkg != nil {
288                                 writePackage(buf, t.obj.pkg, qf)
289                         }
290                         s = t.obj.name
291                 }
292                 buf.WriteString(s + subscript(t.id))
293
294         case *instance:
295                 buf.WriteByte(instanceMarker) // indicate "non-evaluated" syntactic instance
296                 writeTypeName(buf, t.base.obj, qf)
297                 buf.WriteByte('[')
298                 writeTypeList(buf, t.targs, qf, visited)
299                 buf.WriteByte(']')
300
301         case *top:
302                 buf.WriteString("⊤")
303
304         default:
305                 // For externally defined implementations of Type.
306                 // Note: In this case cycles won't be caught.
307                 buf.WriteString(t.String())
308         }
309 }
310
311 func writeTypeList(buf *bytes.Buffer, list []Type, qf Qualifier, visited []Type) {
312         for i, typ := range list {
313                 if i > 0 {
314                         buf.WriteString(", ")
315                 }
316                 writeType(buf, typ, qf, visited)
317         }
318 }
319
320 func writeTParamList(buf *bytes.Buffer, list []*TypeName, qf Qualifier, visited []Type) {
321         buf.WriteString("[")
322         var prev Type
323         for i, p := range list {
324                 // TODO(gri) support 'any' sugar here.
325                 var b Type = &emptyInterface
326                 if t, _ := p.typ.(*TypeParam); t != nil && t.bound != nil {
327                         b = t.bound
328                 }
329                 if i > 0 {
330                         if b != prev {
331                                 // type bound changed - write previous one before advancing
332                                 buf.WriteByte(' ')
333                                 writeType(buf, prev, qf, visited)
334                         }
335                         buf.WriteString(", ")
336                 }
337                 prev = b
338
339                 if t, _ := p.typ.(*TypeParam); t != nil {
340                         writeType(buf, t, qf, visited)
341                 } else {
342                         buf.WriteString(p.name)
343                 }
344         }
345         if prev != nil {
346                 buf.WriteByte(' ')
347                 writeType(buf, prev, qf, visited)
348         }
349         buf.WriteByte(']')
350 }
351
352 func writeTypeName(buf *bytes.Buffer, obj *TypeName, qf Qualifier) {
353         s := "<Named w/o object>"
354         if obj != nil {
355                 if obj.pkg != nil {
356                         writePackage(buf, obj.pkg, qf)
357                 }
358                 // TODO(gri): function-local named types should be displayed
359                 // differently from named types at package level to avoid
360                 // ambiguity.
361                 s = obj.name
362         }
363         buf.WriteString(s)
364 }
365
366 func writeTuple(buf *bytes.Buffer, tup *Tuple, variadic bool, qf Qualifier, visited []Type) {
367         buf.WriteByte('(')
368         if tup != nil {
369                 for i, v := range tup.vars {
370                         if i > 0 {
371                                 buf.WriteString(", ")
372                         }
373                         if v.name != "" {
374                                 buf.WriteString(v.name)
375                                 buf.WriteByte(' ')
376                         }
377                         typ := v.typ
378                         if variadic && i == len(tup.vars)-1 {
379                                 if s, ok := typ.(*Slice); ok {
380                                         buf.WriteString("...")
381                                         typ = s.elem
382                                 } else {
383                                         // special case:
384                                         // append(s, "foo"...) leads to signature func([]byte, string...)
385                                         if t := asBasic(typ); t == nil || t.kind != String {
386                                                 panic("internal error: string type expected")
387                                         }
388                                         writeType(buf, typ, qf, visited)
389                                         buf.WriteString("...")
390                                         continue
391                                 }
392                         }
393                         writeType(buf, typ, qf, visited)
394                 }
395         }
396         buf.WriteByte(')')
397 }
398
399 // WriteSignature writes the representation of the signature sig to buf,
400 // without a leading "func" keyword.
401 // The Qualifier controls the printing of
402 // package-level objects, and may be nil.
403 func WriteSignature(buf *bytes.Buffer, sig *Signature, qf Qualifier) {
404         writeSignature(buf, sig, qf, make([]Type, 0, 8))
405 }
406
407 func writeSignature(buf *bytes.Buffer, sig *Signature, qf Qualifier, visited []Type) {
408         if sig.tparams != nil {
409                 writeTParamList(buf, sig.tparams, qf, visited)
410         }
411
412         writeTuple(buf, sig.params, sig.variadic, qf, visited)
413
414         n := sig.results.Len()
415         if n == 0 {
416                 // no result
417                 return
418         }
419
420         buf.WriteByte(' ')
421         if n == 1 && sig.results.vars[0].name == "" {
422                 // single unnamed result
423                 writeType(buf, sig.results.vars[0].typ, qf, visited)
424                 return
425         }
426
427         // multiple or named result(s)
428         writeTuple(buf, sig.results, false, qf, visited)
429 }
430
431 // subscript returns the decimal (utf8) representation of x using subscript digits.
432 func subscript(x uint64) string {
433         const w = len("₀") // all digits 0...9 have the same utf8 width
434         var buf [32 * w]byte
435         i := len(buf)
436         for {
437                 i -= w
438                 utf8.EncodeRune(buf[i:], '₀'+rune(x%10)) // '₀' == U+2080
439                 x /= 10
440                 if x == 0 {
441                         break
442                 }
443         }
444         return string(buf[i:])
445 }