]> Cypherpunks.ru repositories - gostls13.git/blob - src/cmd/compile/internal/types2/typestring.go
[dev.typeparams] cmd/compile/internal/types2: replace Sum type with Union type
[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                 for i, e := range t.types {
162                         if i > 0 {
163                                 buf.WriteString("|")
164                         }
165                         if t.tilde[i] {
166                                 buf.WriteByte('~')
167                         }
168                         writeType(buf, e, qf, visited)
169                 }
170
171         case *Interface:
172                 // We write the source-level methods and embedded types rather
173                 // than the actual method set since resolved method signatures
174                 // may have non-printable cycles if parameters have embedded
175                 // interface types that (directly or indirectly) embed the
176                 // current interface. For instance, consider the result type
177                 // of m:
178                 //
179                 //     type T interface{
180                 //         m() interface{ T }
181                 //     }
182                 //
183                 buf.WriteString("interface{")
184                 empty := true
185                 if gcCompatibilityMode {
186                         // print flattened interface
187                         // (useful to compare against gc-generated interfaces)
188                         for i, m := range t.allMethods {
189                                 if i > 0 {
190                                         buf.WriteString("; ")
191                                 }
192                                 buf.WriteString(m.name)
193                                 writeSignature(buf, m.typ.(*Signature), qf, visited)
194                                 empty = false
195                         }
196                         if !empty && t.allTypes != nil {
197                                 buf.WriteString("; ")
198                         }
199                         if t.allTypes != nil {
200                                 buf.WriteString("type ")
201                                 writeType(buf, t.allTypes, qf, visited)
202                         }
203                 } else {
204                         // print explicit interface methods and embedded types
205                         for i, m := range t.methods {
206                                 if i > 0 {
207                                         buf.WriteString("; ")
208                                 }
209                                 buf.WriteString(m.name)
210                                 writeSignature(buf, m.typ.(*Signature), qf, visited)
211                                 empty = false
212                         }
213                         if !empty && len(t.embeddeds) > 0 {
214                                 buf.WriteString("; ")
215                         }
216                         for i, typ := range t.embeddeds {
217                                 if i > 0 {
218                                         buf.WriteString("; ")
219                                 }
220                                 writeType(buf, typ, qf, visited)
221                                 empty = false
222                         }
223                 }
224                 if debug && (t.allMethods == nil || len(t.methods) > len(t.allMethods)) {
225                         if !empty {
226                                 buf.WriteByte(' ')
227                         }
228                         buf.WriteString("/* incomplete */")
229                 }
230                 buf.WriteByte('}')
231
232         case *Map:
233                 buf.WriteString("map[")
234                 writeType(buf, t.key, qf, visited)
235                 buf.WriteByte(']')
236                 writeType(buf, t.elem, qf, visited)
237
238         case *Chan:
239                 var s string
240                 var parens bool
241                 switch t.dir {
242                 case SendRecv:
243                         s = "chan "
244                         // chan (<-chan T) requires parentheses
245                         if c, _ := t.elem.(*Chan); c != nil && c.dir == RecvOnly {
246                                 parens = true
247                         }
248                 case SendOnly:
249                         s = "chan<- "
250                 case RecvOnly:
251                         s = "<-chan "
252                 default:
253                         panic("unreachable")
254                 }
255                 buf.WriteString(s)
256                 if parens {
257                         buf.WriteByte('(')
258                 }
259                 writeType(buf, t.elem, qf, visited)
260                 if parens {
261                         buf.WriteByte(')')
262                 }
263
264         case *Named:
265                 writeTypeName(buf, t.obj, qf)
266                 if t.targs != nil {
267                         // instantiated type
268                         buf.WriteByte('[')
269                         writeTypeList(buf, t.targs, qf, visited)
270                         buf.WriteByte(']')
271                 } else if t.tparams != nil {
272                         // parameterized type
273                         writeTParamList(buf, t.tparams, qf, visited)
274                 }
275
276         case *TypeParam:
277                 s := "?"
278                 if t.obj != nil {
279                         // Optionally write out package for typeparams (like Named).
280                         // TODO(danscales): this is required for import/export, so
281                         // we maybe need a separate function that won't be changed
282                         // for debugging purposes.
283                         if t.obj.pkg != nil {
284                                 writePackage(buf, t.obj.pkg, qf)
285                         }
286                         s = t.obj.name
287                 }
288                 buf.WriteString(s + subscript(t.id))
289
290         case *instance:
291                 buf.WriteByte(instanceMarker) // indicate "non-evaluated" syntactic instance
292                 writeTypeName(buf, t.base.obj, qf)
293                 buf.WriteByte('[')
294                 writeTypeList(buf, t.targs, qf, visited)
295                 buf.WriteByte(']')
296
297         case *bottom:
298                 buf.WriteString("⊥")
299
300         case *top:
301                 buf.WriteString("⊤")
302
303         default:
304                 // For externally defined implementations of Type.
305                 // Note: In this case cycles won't be caught.
306                 buf.WriteString(t.String())
307         }
308 }
309
310 func writeTypeList(buf *bytes.Buffer, list []Type, qf Qualifier, visited []Type) {
311         for i, typ := range list {
312                 if i > 0 {
313                         buf.WriteString(", ")
314                 }
315                 writeType(buf, typ, qf, visited)
316         }
317 }
318
319 func writeTParamList(buf *bytes.Buffer, list []*TypeName, qf Qualifier, visited []Type) {
320         buf.WriteString("[")
321         var prev Type
322         for i, p := range list {
323                 // TODO(gri) support 'any' sugar here.
324                 var b Type = &emptyInterface
325                 if t, _ := p.typ.(*TypeParam); t != nil && t.bound != nil {
326                         b = t.bound
327                 }
328                 if i > 0 {
329                         if b != prev {
330                                 // type bound changed - write previous one before advancing
331                                 buf.WriteByte(' ')
332                                 writeType(buf, prev, qf, visited)
333                         }
334                         buf.WriteString(", ")
335                 }
336                 prev = b
337
338                 if t, _ := p.typ.(*TypeParam); t != nil {
339                         writeType(buf, t, qf, visited)
340                 } else {
341                         buf.WriteString(p.name)
342                 }
343         }
344         if prev != nil {
345                 buf.WriteByte(' ')
346                 writeType(buf, prev, qf, visited)
347         }
348         buf.WriteByte(']')
349 }
350
351 func writeTypeName(buf *bytes.Buffer, obj *TypeName, qf Qualifier) {
352         s := "<Named w/o object>"
353         if obj != nil {
354                 if obj.pkg != nil {
355                         writePackage(buf, obj.pkg, qf)
356                 }
357                 // TODO(gri): function-local named types should be displayed
358                 // differently from named types at package level to avoid
359                 // ambiguity.
360                 s = obj.name
361         }
362         buf.WriteString(s)
363 }
364
365 func writeTuple(buf *bytes.Buffer, tup *Tuple, variadic bool, qf Qualifier, visited []Type) {
366         buf.WriteByte('(')
367         if tup != nil {
368                 for i, v := range tup.vars {
369                         if i > 0 {
370                                 buf.WriteString(", ")
371                         }
372                         if v.name != "" {
373                                 buf.WriteString(v.name)
374                                 buf.WriteByte(' ')
375                         }
376                         typ := v.typ
377                         if variadic && i == len(tup.vars)-1 {
378                                 if s, ok := typ.(*Slice); ok {
379                                         buf.WriteString("...")
380                                         typ = s.elem
381                                 } else {
382                                         // special case:
383                                         // append(s, "foo"...) leads to signature func([]byte, string...)
384                                         if t := asBasic(typ); t == nil || t.kind != String {
385                                                 panic("internal error: string type expected")
386                                         }
387                                         writeType(buf, typ, qf, visited)
388                                         buf.WriteString("...")
389                                         continue
390                                 }
391                         }
392                         writeType(buf, typ, qf, visited)
393                 }
394         }
395         buf.WriteByte(')')
396 }
397
398 // WriteSignature writes the representation of the signature sig to buf,
399 // without a leading "func" keyword.
400 // The Qualifier controls the printing of
401 // package-level objects, and may be nil.
402 func WriteSignature(buf *bytes.Buffer, sig *Signature, qf Qualifier) {
403         writeSignature(buf, sig, qf, make([]Type, 0, 8))
404 }
405
406 func writeSignature(buf *bytes.Buffer, sig *Signature, qf Qualifier, visited []Type) {
407         if sig.tparams != nil {
408                 writeTParamList(buf, sig.tparams, qf, visited)
409         }
410
411         writeTuple(buf, sig.params, sig.variadic, qf, visited)
412
413         n := sig.results.Len()
414         if n == 0 {
415                 // no result
416                 return
417         }
418
419         buf.WriteByte(' ')
420         if n == 1 && sig.results.vars[0].name == "" {
421                 // single unnamed result
422                 writeType(buf, sig.results.vars[0].typ, qf, visited)
423                 return
424         }
425
426         // multiple or named result(s)
427         writeTuple(buf, sig.results, false, qf, visited)
428 }
429
430 // subscript returns the decimal (utf8) representation of x using subscript digits.
431 func subscript(x uint64) string {
432         const w = len("₀") // all digits 0...9 have the same utf8 width
433         var buf [32 * w]byte
434         i := len(buf)
435         for {
436                 i -= w
437                 utf8.EncodeRune(buf[i:], '₀'+rune(x%10)) // '₀' == U+2080
438                 x /= 10
439                 if x == 0 {
440                         break
441                 }
442         }
443         return string(buf[i:])
444 }