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 newTypeWriter(buf, qf).typ(typ)
58 // WriteSignature writes the representation of the signature sig to buf,
59 // without a leading "func" keyword.
60 // The Qualifier controls the printing of
61 // package-level objects, and may be nil.
62 func WriteSignature(buf *bytes.Buffer, sig *Signature, qf Qualifier) {
63 newTypeWriter(buf, qf).signature(sig)
66 // instanceMarker is the prefix for an instantiated type in unexpanded form.
67 const instanceMarker = '#'
69 type typeWriter struct {
76 func newTypeWriter(buf *bytes.Buffer, qf Qualifier) *typeWriter {
77 return &typeWriter{buf, make(map[Type]bool), qf, false}
80 func newTypeHasher(buf *bytes.Buffer) *typeWriter {
81 return &typeWriter{buf, make(map[Type]bool), nil, true}
84 func (w *typeWriter) byte(b byte) { w.buf.WriteByte(b) }
85 func (w *typeWriter) string(s string) { w.buf.WriteString(s) }
86 func (w *typeWriter) writef(format string, args ...interface{}) { fmt.Fprintf(w.buf, format, args...) }
87 func (w *typeWriter) error(msg string) {
91 w.string("<" + msg + ">")
94 func (w *typeWriter) typ(typ Type) {
96 w.error("cycle to " + goTypeName(typ))
100 defer delete(w.seen, typ)
102 switch t := typ.(type) {
107 // exported basic types go into package unsafe
108 // (currently this is just unsafe.Pointer)
109 if isExported(t.name) {
110 if obj, _ := Unsafe.scope.Lookup(t.name).(*TypeName); obj != nil {
118 w.writef("[%d]", t.len)
127 for i, f := range t.fields {
131 // This doesn't do the right thing for embedded type
132 // aliases where we should print the alias name, not
133 // the aliased type (see issue #44410).
139 if tag := t.Tag(i); tag != "" {
157 // Unions only appear as (syntactic) embedded elements
158 // in interfaces and syntactically cannot be empty.
160 w.error("empty union")
163 for i, t := range t.terms {
174 w.string("interface{")
176 for _, m := range t.methods {
182 w.signature(m.typ.(*Signature))
184 for _, typ := range t.embeddeds {
205 // chan (<-chan T) requires parentheses
206 if c, _ := t.elem.(*Chan); c != nil && c.dir == RecvOnly {
214 w.error("unknown channel direction")
227 // Instance markers indicate unexpanded instantiated
228 // types. Write them to aid debugging, but don't write
229 // them when we need an instance hash: whether a type
230 // is fully expanded or not doesn't matter for identity.
231 if !w.hash && t.instPos != nil {
232 w.byte(instanceMarker)
237 w.typeList(t.targs.list())
238 } else if t.TParams().Len() != 0 {
239 // parameterized type
240 w.tParamList(t.TParams().list())
245 w.error("unnamed type parameter")
248 // Optionally write out package for typeparams (like Named).
249 // TODO(danscales): this is required for import/export, so
250 // we maybe need a separate function that won't be changed
251 // for debugging purposes.
252 if t.obj.pkg != nil {
253 writePackage(w.buf, t.obj.pkg, w.qf)
255 w.string(t.obj.name + subscript(t.id))
261 // For externally defined implementations of Type.
262 // Note: In this case cycles won't be caught.
267 func (w *typeWriter) typeList(list []Type) {
269 for i, typ := range list {
278 func (w *typeWriter) tParamList(list []*TypeParam) {
281 for i, tpar := range list {
282 // Determine the type parameter and its constraint.
283 // list is expected to hold type parameter names,
284 // but don't crash if that's not the case.
286 w.error("nil type parameter")
290 if tpar.bound != prev {
291 // bound changed - write previous one before advancing
307 func (w *typeWriter) typeName(obj *TypeName) {
309 writePackage(w.buf, obj.pkg, w.qf)
314 // For local defined types, use the (original!) TypeName's scope
315 // numbers to disambiguate.
316 if typ, _ := obj.typ.(*Named); typ != nil {
317 // TODO(gri) Figure out why typ.orig != typ.orig.orig sometimes
318 // and whether the loop can iterate more than twice.
319 // (It seems somehow connected to instance types.)
320 for typ.orig != typ {
323 w.writeScopeNumbers(typ.obj.parent)
328 // writeScopeNumbers writes the number sequence for this scope to buf
329 // in the form ".i.j.k" where i, j, k, etc. stand for scope numbers.
330 // If a scope is nil or has no parent (such as a package scope), nothing
332 func (w *typeWriter) writeScopeNumbers(s *Scope) {
333 if s != nil && s.number > 0 {
334 w.writeScopeNumbers(s.parent)
335 w.writef(".%d", s.number)
339 func (w *typeWriter) tuple(tup *Tuple, variadic bool) {
342 for i, v := range tup.vars {
346 // parameter names are ignored for type identity and thus type hashes
347 if !w.hash && v.name != "" {
352 if variadic && i == len(tup.vars)-1 {
353 if s, ok := typ.(*Slice); ok {
358 // append(s, "foo"...) leads to signature func([]byte, string...)
359 if t := asBasic(typ); t == nil || t.kind != String {
360 w.error("expected string type")
374 func (w *typeWriter) signature(sig *Signature) {
375 if sig.TParams().Len() != 0 {
376 w.tParamList(sig.TParams().list())
379 w.tuple(sig.params, sig.variadic)
381 n := sig.results.Len()
388 if n == 1 && (w.hash || sig.results.vars[0].name == "") {
389 // single unnamed result (if type hashing, name must be ignored)
390 w.typ(sig.results.vars[0].typ)
394 // multiple or named result(s)
395 w.tuple(sig.results, false)
398 // subscript returns the decimal (utf8) representation of x using subscript digits.
399 func subscript(x uint64) string {
400 const w = len("₀") // all digits 0...9 have the same utf8 width
405 utf8.EncodeRune(buf[i:], '₀'+rune(x%10)) // '₀' == U+2080
411 return string(buf[i:])