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.
18 // A Qualifier controls how named package-level objects are printed in
19 // calls to TypeString, ObjectString, and SelectionString.
21 // These three formatting routines call the Qualifier for each
22 // package-level object O, and if the Qualifier returns a non-empty
23 // string p, the object is printed in the form p.O.
24 // If it returns an empty string, only the object name O is printed.
26 // Using a nil Qualifier is equivalent to using (*Package).Path: the
27 // object is qualified by the import path, e.g., "encoding/json.Marshal".
28 type Qualifier func(*Package) string
30 // RelativeTo returns a Qualifier that fully qualifies members of
31 // all packages other than pkg.
32 func RelativeTo(pkg *Package) Qualifier {
36 return func(other *Package) string {
38 return "" // same package; unqualified
44 // TypeString returns the string representation of typ.
45 // The Qualifier controls the printing of
46 // package-level objects, and may be nil.
47 func TypeString(typ Type, qf Qualifier) string {
49 WriteType(&buf, typ, qf)
53 // WriteType writes the string representation of typ to buf.
54 // The Qualifier controls the printing of
55 // package-level objects, and may be nil.
56 func WriteType(buf *bytes.Buffer, typ Type, qf Qualifier) {
57 newTypeWriter(buf, qf).typ(typ)
60 // WriteSignature writes the representation of the signature sig to buf,
61 // without a leading "func" keyword.
62 // The Qualifier controls the printing of
63 // package-level objects, and may be nil.
64 func WriteSignature(buf *bytes.Buffer, sig *Signature, qf Qualifier) {
65 newTypeWriter(buf, qf).signature(sig)
68 type typeWriter struct {
72 ctxt *Context // if non-nil, we are type hashing
73 tparams *TypeParamList // local type parameters
74 paramNames bool // if set, write function parameter names, otherwise, write types only
75 tpSubscripts bool // if set, write type parameter indices as subscripts
78 func newTypeWriter(buf *bytes.Buffer, qf Qualifier) *typeWriter {
79 return &typeWriter{buf, make(map[Type]bool), qf, nil, nil, true, false}
82 func newTypeHasher(buf *bytes.Buffer, ctxt *Context) *typeWriter {
84 return &typeWriter{buf, make(map[Type]bool), nil, ctxt, nil, false, false}
87 func (w *typeWriter) byte(b byte) {
96 if b == ',' || b == ';' {
101 func (w *typeWriter) string(s string) {
105 func (w *typeWriter) error(msg string) {
109 w.buf.WriteString("<" + msg + ">")
112 func (w *typeWriter) typ(typ Type) {
114 w.error("cycle to " + goTypeName(typ))
118 defer delete(w.seen, typ)
120 switch t := typ.(type) {
125 // exported basic types go into package unsafe
126 // (currently this is just unsafe.Pointer)
127 if isExported(t.name) {
128 if obj, _ := Unsafe.scope.Lookup(t.name).(*TypeName); obj != nil {
137 w.string(strconv.FormatInt(t.len, 10))
147 for i, f := range t.fields {
151 // This doesn't do the right thing for embedded type
152 // aliases where we should print the alias name, not
153 // the aliased type (see issue #44410).
159 if tag := t.Tag(i); tag != "" {
161 // TODO(gri) If tag contains blanks, replacing them with '#'
162 // in Context.TypeHash may produce another tag
164 w.string(strconv.Quote(tag))
181 // Unions only appear as (syntactic) embedded elements
182 // in interfaces and syntactically cannot be empty.
184 w.error("empty union")
187 for i, t := range t.terms {
199 if t == universeAny.Type() {
200 // When not hashing, we can try to improve type strings by writing "any"
201 // for a type that is pointer-identical to universeAny. This logic should
202 // be deprecated by more robust handling for aliases.
206 if t == universeComparable.Type().(*Named).underlying {
207 w.string("interface{comparable}")
212 if len(t.methods) == 0 && len(t.embeddeds) == 1 {
213 w.typ(t.embeddeds[0])
216 // Something's wrong with the implicit interface.
217 // Print it as such and continue.
218 w.string("/* implicit */ ")
220 w.string("interface{")
223 w.typeSet(t.typeSet())
225 for _, m := range t.methods {
231 w.signature(m.typ.(*Signature))
233 for _, typ := range t.embeddeds {
255 // chan (<-chan T) requires parentheses
256 if c, _ := t.elem.(*Chan); c != nil && c.dir == RecvOnly {
264 w.error("unknown channel direction")
276 // If hashing, write a unique prefix for t to represent its identity, since
277 // named type identity is pointer identity.
279 w.string(strconv.Itoa(w.ctxt.getID(t)))
281 w.typeName(t.obj) // when hashing written for readability of the hash only
284 w.typeList(t.inst.targs.list())
285 } else if w.ctxt == nil && t.TypeParams().Len() != 0 { // For type hashing, don't need to format the TypeParams
286 // parameterized type
287 w.tParamList(t.TypeParams().list())
292 w.error("unnamed type parameter")
295 if i := tparamIndex(w.tparams.list(), t); i >= 0 {
296 // The names of type parameters that are declared by the type being
297 // hashed are not part of the type identity. Replace them with a
298 // placeholder indicating their index.
299 w.string(fmt.Sprintf("$%d", i))
302 if w.tpSubscripts || w.ctxt != nil {
303 w.string(subscript(t.id))
308 // For externally defined implementations of Type.
309 // Note: In this case cycles won't be caught.
314 // typeSet writes a canonical hash for an interface type set.
315 func (w *typeWriter) typeSet(s *_TypeSet) {
316 assert(w.ctxt != nil)
318 for _, m := range s.methods {
324 w.signature(m.typ.(*Signature))
327 case s.terms.isAll():
329 case s.terms.isEmpty():
330 w.string(s.terms.String())
332 var termHashes []string
333 for _, term := range s.terms {
334 // terms are not canonically sorted, so we sort their hashes instead.
339 newTypeHasher(&buf, w.ctxt).typ(term.typ)
340 termHashes = append(termHashes, buf.String())
342 sort.Strings(termHashes)
346 w.string(strings.Join(termHashes, "|"))
350 func (w *typeWriter) typeList(list []Type) {
352 for i, typ := range list {
361 func (w *typeWriter) tParamList(list []*TypeParam) {
364 for i, tpar := range list {
365 // Determine the type parameter and its constraint.
366 // list is expected to hold type parameter names,
367 // but don't crash if that's not the case.
369 w.error("nil type parameter")
373 if tpar.bound != prev {
374 // bound changed - write previous one before advancing
390 func (w *typeWriter) typeName(obj *TypeName) {
392 writePackage(w.buf, obj.pkg, w.qf)
397 func (w *typeWriter) tuple(tup *Tuple, variadic bool) {
400 for i, v := range tup.vars {
404 // parameter names are ignored for type identity and thus type hashes
405 if w.ctxt == nil && v.name != "" && w.paramNames {
410 if variadic && i == len(tup.vars)-1 {
411 if s, ok := typ.(*Slice); ok {
416 // append(s, "foo"...) leads to signature func([]byte, string...)
417 if t, _ := under(typ).(*Basic); t == nil || t.kind != String {
418 w.error("expected string type")
432 func (w *typeWriter) signature(sig *Signature) {
433 if sig.TypeParams().Len() != 0 {
435 assert(w.tparams == nil)
436 w.tparams = sig.TypeParams()
441 w.tParamList(sig.TypeParams().list())
444 w.tuple(sig.params, sig.variadic)
446 n := sig.results.Len()
453 if n == 1 && (w.ctxt != nil || sig.results.vars[0].name == "") {
454 // single unnamed result (if type hashing, name must be ignored)
455 w.typ(sig.results.vars[0].typ)
459 // multiple or named result(s)
460 w.tuple(sig.results, false)
463 // subscript returns the decimal (utf8) representation of x using subscript digits.
464 func subscript(x uint64) string {
465 const w = len("₀") // all digits 0...9 have the same utf8 width
470 utf8.EncodeRune(buf[i:], '₀'+rune(x%10)) // '₀' == U+2080
476 return string(buf[i:])