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.
16 // A Qualifier controls how named package-level objects are printed in
17 // calls to TypeString, ObjectString, and SelectionString.
19 // These three formatting routines call the Qualifier for each
20 // package-level object O, and if the Qualifier returns a non-empty
21 // string p, the object is printed in the form p.O.
22 // If it returns an empty string, only the object name O is printed.
24 // Using a nil Qualifier is equivalent to using (*Package).Path: the
25 // object is qualified by the import path, e.g., "encoding/json.Marshal".
27 type Qualifier func(*Package) string
29 // RelativeTo returns a Qualifier that fully qualifies members of
30 // all packages other than pkg.
31 func RelativeTo(pkg *Package) Qualifier {
35 return func(other *Package) string {
37 return "" // same package; unqualified
43 // TypeString returns the string representation of typ.
44 // The Qualifier controls the printing of
45 // package-level objects, and may be nil.
46 func TypeString(typ Type, qf Qualifier) string {
47 return typeString(typ, qf, false)
50 func typeString(typ Type, qf Qualifier, debug bool) string {
52 w := newTypeWriter(&buf, qf)
58 // WriteType writes the string representation of typ to buf.
59 // The Qualifier controls the printing of
60 // package-level objects, and may be nil.
61 func WriteType(buf *bytes.Buffer, typ Type, qf Qualifier) {
62 newTypeWriter(buf, qf).typ(typ)
65 // WriteSignature writes the representation of the signature sig to buf,
66 // without a leading "func" keyword.
67 // The Qualifier controls the printing of
68 // package-level objects, and may be nil.
69 func WriteSignature(buf *bytes.Buffer, sig *Signature, qf Qualifier) {
70 newTypeWriter(buf, qf).signature(sig)
73 type typeWriter struct {
77 ctxt *Context // if non-nil, we are type hashing
78 tparams *TypeParamList // local type parameters
79 debug bool // if true, write debug annotations
82 func newTypeWriter(buf *bytes.Buffer, qf Qualifier) *typeWriter {
83 return &typeWriter{buf, make(map[Type]bool), qf, nil, nil, false}
86 func newTypeHasher(buf *bytes.Buffer, ctxt *Context) *typeWriter {
88 return &typeWriter{buf, make(map[Type]bool), nil, ctxt, nil, false}
91 func (w *typeWriter) byte(b byte) {
100 if b == ',' || b == ';' {
105 func (w *typeWriter) string(s string) {
109 func (w *typeWriter) error(msg string) {
113 w.buf.WriteString("<" + msg + ">")
116 func (w *typeWriter) typ(typ Type) {
118 w.error("cycle to " + goTypeName(typ))
122 defer delete(w.seen, typ)
124 switch t := typ.(type) {
129 // exported basic types go into package unsafe
130 // (currently this is just unsafe.Pointer)
131 if isExported(t.name) {
132 if obj, _ := Unsafe.scope.Lookup(t.name).(*TypeName); obj != nil {
141 w.string(strconv.FormatInt(t.len, 10))
151 for i, f := range t.fields {
155 // This doesn't do the right thing for embedded type
156 // aliases where we should print the alias name, not
157 // the aliased type (see issue #44410).
163 if tag := t.Tag(i); tag != "" {
165 // TODO(gri) If tag contains blanks, replacing them with '#'
166 // in Context.TypeHash may produce another tag
168 w.string(strconv.Quote(tag))
185 // Unions only appear as (syntactic) embedded elements
186 // in interfaces and syntactically cannot be empty.
188 w.error("empty union")
191 for i, t := range t.terms {
202 if t == universeAny.Type() && w.ctxt == nil {
203 // When not hashing, we can try to improve type strings by writing "any"
204 // for a type that is pointer-identical to universeAny. This logic should
205 // be deprecated by more robust handling for aliases.
210 if len(t.methods) == 0 && len(t.embeddeds) == 1 {
211 w.typ(t.embeddeds[0])
214 // Something's wrong with the implicit interface.
215 // Print it as such and continue.
216 w.string("/* implicit */ ")
218 w.string("interface{")
220 for _, m := range t.methods {
226 w.signature(m.typ.(*Signature))
228 for _, typ := range t.embeddeds {
249 // chan (<-chan T) requires parentheses
250 if c, _ := t.elem.(*Chan); c != nil && c.dir == RecvOnly {
258 w.error("unknown channel direction")
270 // If hashing, write a unique prefix for t to represent its identity, since
271 // named type identity is pointer identity.
273 w.string(strconv.Itoa(w.ctxt.getID(t)))
275 w.typeName(t.obj) // when hashing written for readability of the hash only
278 w.typeList(t.targs.list())
279 } else if w.ctxt == nil && t.TypeParams().Len() != 0 { // For type hashing, don't need to format the TypeParams
280 // parameterized type
281 w.tParamList(t.TypeParams().list())
286 w.error("unnamed type parameter")
289 if i := tparamIndex(w.tparams.list(), t); i >= 0 {
290 // The names of type parameters that are declared by the type being
291 // hashed are not part of the type identity. Replace them with a
292 // placeholder indicating their index.
293 w.string(fmt.Sprintf("$%d", i))
296 if w.debug || w.ctxt != nil {
297 w.string(subscript(t.id))
302 // For externally defined implementations of Type.
303 // Note: In this case cycles won't be caught.
308 func (w *typeWriter) typeList(list []Type) {
310 for i, typ := range list {
319 func (w *typeWriter) tParamList(list []*TypeParam) {
322 for i, tpar := range list {
323 // Determine the type parameter and its constraint.
324 // list is expected to hold type parameter names,
325 // but don't crash if that's not the case.
327 w.error("nil type parameter")
331 if tpar.bound != prev {
332 // bound changed - write previous one before advancing
348 func (w *typeWriter) typeName(obj *TypeName) {
350 writePackage(w.buf, obj.pkg, w.qf)
355 func (w *typeWriter) tuple(tup *Tuple, variadic bool) {
358 for i, v := range tup.vars {
362 // parameter names are ignored for type identity and thus type hashes
363 if w.ctxt == nil && v.name != "" {
368 if variadic && i == len(tup.vars)-1 {
369 if s, ok := typ.(*Slice); ok {
374 // append(s, "foo"...) leads to signature func([]byte, string...)
375 if t, _ := under(typ).(*Basic); t == nil || t.kind != String {
376 w.error("expected string type")
390 func (w *typeWriter) signature(sig *Signature) {
391 if sig.TypeParams().Len() != 0 {
393 assert(w.tparams == nil)
394 w.tparams = sig.TypeParams()
399 w.tParamList(sig.TypeParams().list())
402 w.tuple(sig.params, sig.variadic)
404 n := sig.results.Len()
411 if n == 1 && (w.ctxt != nil || sig.results.vars[0].name == "") {
412 // single unnamed result (if type hashing, name must be ignored)
413 w.typ(sig.results.vars[0].typ)
417 // multiple or named result(s)
418 w.tuple(sig.results, false)
421 // subscript returns the decimal (utf8) representation of x using subscript digits.
422 func subscript(x uint64) string {
423 const w = len("₀") // all digits 0...9 have the same utf8 width
428 utf8.EncodeRune(buf[i:], '₀'+rune(x%10)) // '₀' == U+2080
434 return string(buf[i:])