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 // If gcCompatibilityMode is set, printing of types is modified
43 // to match the representation of some types in the gc compiler:
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)
50 // This makes it easier to compare packages computed with the type-
51 // checker vs packages imported from gc export data.
53 // Caution: This flag affects all uses of WriteType, globally.
54 // It is only provided for testing in conjunction with
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
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 {
68 WriteType(&buf, typ, qf)
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))
79 // instanceMarker is the prefix for an instantiated type
80 // in "non-evaluated" instance form.
81 const instanceMarker = '#'
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
88 for _, t := range visited {
90 fmt.Fprintf(buf, "○%T", goTypeName(typ)) // cycle to typ
94 visited = append(visited, typ)
96 switch t := typ.(type) {
98 buf.WriteString("<nil>")
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)
110 if gcCompatibilityMode {
111 // forget the alias names
119 buf.WriteString(t.name)
122 fmt.Fprintf(buf, "[%d]", t.len)
123 writeType(buf, t.elem, qf, visited)
126 buf.WriteString("[]")
127 writeType(buf, t.elem, qf, visited)
130 buf.WriteString("struct{")
131 for i, f := range t.fields {
133 buf.WriteString("; ")
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).
139 buf.WriteString(f.name)
142 writeType(buf, f.typ, qf, visited)
143 if tag := t.Tag(i); tag != "" {
144 fmt.Fprintf(buf, " %q", tag)
151 writeType(buf, t.base, qf, visited)
154 writeTuple(buf, t, false, qf, visited)
157 buf.WriteString("func")
158 writeSignature(buf, t, qf, visited)
161 for i, t := range t.types {
163 buf.WriteString(", ")
165 writeType(buf, t, qf, visited)
169 // We write the source-level methods and embedded types rather
170 // than the actual method set since resolved method signatures
171 // may have non-printable cycles if parameters have embedded
172 // interface types that (directly or indirectly) embed the
173 // current interface. For instance, consider the result type
177 // m() interface{ T }
180 buf.WriteString("interface{")
182 if gcCompatibilityMode {
183 // print flattened interface
184 // (useful to compare against gc-generated interfaces)
185 for i, m := range t.allMethods {
187 buf.WriteString("; ")
189 buf.WriteString(m.name)
190 writeSignature(buf, m.typ.(*Signature), qf, visited)
193 if !empty && t.allTypes != nil {
194 buf.WriteString("; ")
196 if t.allTypes != nil {
197 buf.WriteString("type ")
198 writeType(buf, t.allTypes, qf, visited)
201 // print explicit interface methods and embedded types
202 for i, m := range t.methods {
204 buf.WriteString("; ")
206 buf.WriteString(m.name)
207 writeSignature(buf, m.typ.(*Signature), qf, visited)
210 if !empty && t.types != nil {
211 buf.WriteString("; ")
214 buf.WriteString("type ")
215 writeType(buf, t.types, qf, visited)
218 if !empty && len(t.embeddeds) > 0 {
219 buf.WriteString("; ")
221 for i, typ := range t.embeddeds {
223 buf.WriteString("; ")
225 writeType(buf, typ, qf, visited)
229 if t.allMethods == nil || len(t.methods) > len(t.allMethods) {
233 buf.WriteString("/* incomplete */")
238 buf.WriteString("map[")
239 writeType(buf, t.key, qf, visited)
241 writeType(buf, t.elem, qf, visited)
249 // chan (<-chan T) requires parentheses
250 if c, _ := t.elem.(*Chan); c != nil && c.dir == RecvOnly {
264 writeType(buf, t.elem, qf, visited)
270 writeTypeName(buf, t.obj, qf)
274 writeTypeList(buf, t.targs, qf, visited)
276 } else if t.tparams != nil {
277 // parameterized type
278 writeTParamList(buf, t.tparams, qf, visited)
286 buf.WriteString(s + subscript(t.id))
289 buf.WriteByte(instanceMarker) // indicate "non-evaluated" syntactic instance
290 writeTypeName(buf, t.base.obj, qf)
292 writeTypeList(buf, t.targs, qf, visited)
302 // For externally defined implementations of Type.
303 buf.WriteString(t.String())
307 func writeTypeList(buf *bytes.Buffer, list []Type, qf Qualifier, visited []Type) {
308 for i, typ := range list {
310 buf.WriteString(", ")
312 writeType(buf, typ, qf, visited)
316 func writeTParamList(buf *bytes.Buffer, list []*TypeName, qf Qualifier, visited []Type) {
319 for i, p := range list {
320 // TODO(gri) support 'any' sugar here.
321 var b Type = &emptyInterface
322 if t, _ := p.typ.(*TypeParam); t != nil && t.bound != nil {
327 // type bound changed - write previous one before advancing
329 writeType(buf, prev, qf, visited)
331 buf.WriteString(", ")
335 if t, _ := p.typ.(*TypeParam); t != nil {
336 writeType(buf, t, qf, visited)
338 buf.WriteString(p.name)
343 writeType(buf, prev, qf, visited)
348 func writeTypeName(buf *bytes.Buffer, obj *TypeName, qf Qualifier) {
349 s := "<Named w/o object>"
352 writePackage(buf, obj.pkg, qf)
354 // TODO(gri): function-local named types should be displayed
355 // differently from named types at package level to avoid
362 func writeTuple(buf *bytes.Buffer, tup *Tuple, variadic bool, qf Qualifier, visited []Type) {
365 for i, v := range tup.vars {
367 buf.WriteString(", ")
370 buf.WriteString(v.name)
374 if variadic && i == len(tup.vars)-1 {
375 if s, ok := typ.(*Slice); ok {
376 buf.WriteString("...")
380 // append(s, "foo"...) leads to signature func([]byte, string...)
381 if t := asBasic(typ); t == nil || t.kind != String {
382 panic("internal error: string type expected")
384 writeType(buf, typ, qf, visited)
385 buf.WriteString("...")
389 writeType(buf, typ, qf, visited)
395 // WriteSignature writes the representation of the signature sig to buf,
396 // without a leading "func" keyword.
397 // The Qualifier controls the printing of
398 // package-level objects, and may be nil.
399 func WriteSignature(buf *bytes.Buffer, sig *Signature, qf Qualifier) {
400 writeSignature(buf, sig, qf, make([]Type, 0, 8))
403 func writeSignature(buf *bytes.Buffer, sig *Signature, qf Qualifier, visited []Type) {
404 if sig.tparams != nil {
405 writeTParamList(buf, sig.tparams, qf, visited)
408 writeTuple(buf, sig.params, sig.variadic, qf, visited)
410 n := sig.results.Len()
417 if n == 1 && sig.results.vars[0].name == "" {
418 // single unnamed result
419 writeType(buf, sig.results.vars[0].typ, qf, visited)
423 // multiple or named result(s)
424 writeTuple(buf, sig.results, false, qf, visited)
427 // subscript returns the decimal (utf8) representation of x using subscript digits.
428 func subscript(x uint64) string {
429 const w = len("₀") // all digits 0...9 have the same utf8 width
434 utf8.EncodeRune(buf[i:], '₀'+rune(x%10)) // '₀' == U+2080
440 return string(buf[i:])