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.
5 // This file implements printing of types.
15 // A Qualifier controls how named package-level objects are printed in
16 // calls to TypeString, ObjectString, and SelectionString.
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.
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".
26 type Qualifier func(*Package) string
28 // RelativeTo returns a Qualifier that fully qualifies members of
29 // all packages other than pkg.
30 func RelativeTo(pkg *Package) Qualifier {
34 return func(other *Package) string {
36 return "" // same package; unqualified
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 {
47 WriteType(&buf, typ, qf)
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))
58 // instanceMarker is the prefix for an instantiated type
59 // in "non-evaluated" instance form.
60 const instanceMarker = '#'
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
67 for _, t := range visited {
69 fmt.Fprintf(buf, "○%T", goTypeName(typ)) // cycle to typ
73 visited = append(visited, typ)
75 switch t := typ.(type) {
77 buf.WriteString("<nil>")
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)
88 buf.WriteString(t.name)
91 fmt.Fprintf(buf, "[%d]", t.len)
92 writeType(buf, t.elem, qf, visited)
96 writeType(buf, t.elem, qf, visited)
99 buf.WriteString("struct{")
100 for i, f := range t.fields {
102 buf.WriteString("; ")
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).
108 buf.WriteString(f.name)
111 writeType(buf, f.typ, qf, visited)
112 if tag := t.Tag(i); tag != "" {
113 fmt.Fprintf(buf, " %q", tag)
120 writeType(buf, t.base, qf, visited)
123 writeTuple(buf, t, false, qf, visited)
126 buf.WriteString("func")
127 writeSignature(buf, t, qf, visited)
130 // Unions only appear as (syntactic) embedded elements
131 // in interfaces and syntactically cannot be empty.
135 for i, t := range t.terms {
142 writeType(buf, t.typ, qf, visited)
146 buf.WriteString("interface{")
148 for _, m := range t.methods {
150 buf.WriteString("; ")
153 buf.WriteString(m.name)
154 writeSignature(buf, m.typ.(*Signature), qf, visited)
156 for _, typ := range t.embeddeds {
158 buf.WriteString("; ")
161 writeType(buf, typ, qf, visited)
166 buf.WriteString("map[")
167 writeType(buf, t.key, qf, visited)
169 writeType(buf, t.elem, qf, visited)
177 // chan (<-chan T) requires parentheses
178 if c, _ := t.elem.(*Chan); c != nil && c.dir == RecvOnly {
192 writeType(buf, t.elem, qf, visited)
198 if t.instance != nil {
199 buf.WriteByte(instanceMarker)
201 writeTypeName(buf, t.obj, qf)
205 writeTypeList(buf, t.targs, qf, visited)
207 } else if t.TParams().Len() != 0 {
208 // parameterized type
209 writeTParamList(buf, t.TParams().list(), qf, visited)
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)
224 buf.WriteString(s + subscript(t.id))
230 // For externally defined implementations of Type.
231 // Note: In this case cycles won't be caught.
232 buf.WriteString(t.String())
236 func writeTypeList(buf *bytes.Buffer, list []Type, qf Qualifier, visited []Type) {
237 for i, typ := range list {
239 buf.WriteString(", ")
241 writeType(buf, typ, qf, visited)
245 func writeTParamList(buf *bytes.Buffer, list []*TypeName, qf Qualifier, visited []Type) {
248 for i, p := 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 tpar, _ := p.typ.(*TypeParam)
255 bound = tpar.bound // should not be nil but we want to see it if it is
260 // bound changed - write previous one before advancing
262 writeType(buf, prev, qf, visited)
264 buf.WriteString(", ")
269 writeType(buf, tpar, qf, visited)
271 buf.WriteString(p.name)
276 writeType(buf, prev, qf, visited)
281 func writeTypeName(buf *bytes.Buffer, obj *TypeName, qf Qualifier) {
283 buf.WriteString("<Named w/o object>")
287 writePackage(buf, obj.pkg, qf)
289 buf.WriteString(obj.name)
291 if instanceHashing != 0 {
292 // For local defined types, use the (original!) TypeName's scope
293 // numbers to disambiguate.
294 typ := obj.typ.(*Named)
295 // TODO(gri) Figure out why typ.orig != typ.orig.orig sometimes
296 // and whether the loop can iterate more than twice.
297 // (It seems somehow connected to instance types.)
298 for typ.orig != typ {
301 writeScopeNumbers(buf, typ.obj.parent)
305 // writeScopeNumbers writes the number sequence for this scope to buf
306 // in the form ".i.j.k" where i, j, k, etc. stand for scope numbers.
307 // If a scope is nil or has no parent (such as a package scope), nothing
309 func writeScopeNumbers(buf *bytes.Buffer, s *Scope) {
310 if s != nil && s.number > 0 {
311 writeScopeNumbers(buf, s.parent)
312 fmt.Fprintf(buf, ".%d", s.number)
316 func writeTuple(buf *bytes.Buffer, tup *Tuple, variadic bool, qf Qualifier, visited []Type) {
319 for i, v := range tup.vars {
321 buf.WriteString(", ")
324 buf.WriteString(v.name)
328 if variadic && i == len(tup.vars)-1 {
329 if s, ok := typ.(*Slice); ok {
330 buf.WriteString("...")
334 // append(s, "foo"...) leads to signature func([]byte, string...)
335 if t := asBasic(typ); t == nil || t.kind != String {
336 panic("expected string type")
338 writeType(buf, typ, qf, visited)
339 buf.WriteString("...")
343 writeType(buf, typ, qf, visited)
349 // WriteSignature writes the representation of the signature sig to buf,
350 // without a leading "func" keyword.
351 // The Qualifier controls the printing of
352 // package-level objects, and may be nil.
353 func WriteSignature(buf *bytes.Buffer, sig *Signature, qf Qualifier) {
354 writeSignature(buf, sig, qf, make([]Type, 0, 8))
357 func writeSignature(buf *bytes.Buffer, sig *Signature, qf Qualifier, visited []Type) {
358 if sig.TParams().Len() != 0 {
359 writeTParamList(buf, sig.TParams().list(), qf, visited)
362 writeTuple(buf, sig.params, sig.variadic, qf, visited)
364 n := sig.results.Len()
371 if n == 1 && sig.results.vars[0].name == "" {
372 // single unnamed result
373 writeType(buf, sig.results.vars[0].typ, qf, visited)
377 // multiple or named result(s)
378 writeTuple(buf, sig.results, false, qf, visited)
381 // subscript returns the decimal (utf8) representation of x using subscript digits.
382 func subscript(x uint64) string {
383 const w = len("₀") // all digits 0...9 have the same utf8 width
388 utf8.EncodeRune(buf[i:], '₀'+rune(x%10)) // '₀' == U+2080
394 return string(buf[i:])