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".
29 type Qualifier func(*Package) string
31 // RelativeTo returns a Qualifier that fully qualifies members of
32 // all packages other than pkg.
33 func RelativeTo(pkg *Package) Qualifier {
37 return func(other *Package) string {
39 return "" // same package; unqualified
45 // TypeString returns the string representation of typ.
46 // The Qualifier controls the printing of
47 // package-level objects, and may be nil.
48 func TypeString(typ Type, qf Qualifier) string {
49 return typeString(typ, qf, false)
52 func typeString(typ Type, qf Qualifier, debug bool) string {
54 w := newTypeWriter(&buf, qf)
60 // WriteType writes the string representation of typ to buf.
61 // The Qualifier controls the printing of
62 // package-level objects, and may be nil.
63 func WriteType(buf *bytes.Buffer, typ Type, qf Qualifier) {
64 newTypeWriter(buf, qf).typ(typ)
67 // WriteSignature writes the representation of the signature sig to buf,
68 // without a leading "func" keyword.
69 // The Qualifier controls the printing of
70 // package-level objects, and may be nil.
71 func WriteSignature(buf *bytes.Buffer, sig *Signature, qf Qualifier) {
72 newTypeWriter(buf, qf).signature(sig)
75 type typeWriter struct {
79 ctxt *Context // if non-nil, we are type hashing
80 tparams *TypeParamList // local type parameters
81 debug bool // if true, write debug annotations
84 func newTypeWriter(buf *bytes.Buffer, qf Qualifier) *typeWriter {
85 return &typeWriter{buf, make(map[Type]bool), qf, nil, nil, false}
88 func newTypeHasher(buf *bytes.Buffer, ctxt *Context) *typeWriter {
90 return &typeWriter{buf, make(map[Type]bool), nil, ctxt, nil, false}
93 func (w *typeWriter) byte(b byte) {
102 if b == ',' || b == ';' {
107 func (w *typeWriter) string(s string) {
111 func (w *typeWriter) error(msg string) {
115 w.buf.WriteString("<" + msg + ">")
118 func (w *typeWriter) typ(typ Type) {
120 w.error("cycle to " + goTypeName(typ))
124 defer delete(w.seen, typ)
126 switch t := typ.(type) {
131 // exported basic types go into package unsafe
132 // (currently this is just unsafe.Pointer)
133 if isExported(t.name) {
134 if obj, _ := Unsafe.scope.Lookup(t.name).(*TypeName); obj != nil {
143 w.string(strconv.FormatInt(t.len, 10))
153 for i, f := range t.fields {
157 // This doesn't do the right thing for embedded type
158 // aliases where we should print the alias name, not
159 // the aliased type (see issue #44410).
165 if tag := t.Tag(i); tag != "" {
167 // TODO(gri) If tag contains blanks, replacing them with '#'
168 // in Context.TypeHash may produce another tag
170 w.string(strconv.Quote(tag))
187 // Unions only appear as (syntactic) embedded elements
188 // in interfaces and syntactically cannot be empty.
190 w.error("empty union")
193 for i, t := range t.terms {
205 if t == universeAny.Type() {
206 // When not hashing, we can try to improve type strings by writing "any"
207 // for a type that is pointer-identical to universeAny. This logic should
208 // be deprecated by more robust handling for aliases.
212 if t == universeComparable.Type().(*Named).underlying {
213 w.string("interface{comparable}")
218 if len(t.methods) == 0 && len(t.embeddeds) == 1 {
219 w.typ(t.embeddeds[0])
222 // Something's wrong with the implicit interface.
223 // Print it as such and continue.
224 w.string("/* implicit */ ")
226 w.string("interface{")
229 w.typeSet(t.typeSet())
231 for _, m := range t.methods {
237 w.signature(m.typ.(*Signature))
239 for _, typ := range t.embeddeds {
261 // chan (<-chan T) requires parentheses
262 if c, _ := t.elem.(*Chan); c != nil && c.dir == RecvOnly {
270 w.error("unknown channel direction")
282 // If hashing, write a unique prefix for t to represent its identity, since
283 // named type identity is pointer identity.
285 w.string(strconv.Itoa(w.ctxt.getID(t)))
287 w.typeName(t.obj) // when hashing written for readability of the hash only
290 w.typeList(t.targs.list())
291 } else if w.ctxt == nil && t.TypeParams().Len() != 0 { // For type hashing, don't need to format the TypeParams
292 // parameterized type
293 w.tParamList(t.TypeParams().list())
298 w.error("unnamed type parameter")
301 if i := tparamIndex(w.tparams.list(), t); i >= 0 {
302 // The names of type parameters that are declared by the type being
303 // hashed are not part of the type identity. Replace them with a
304 // placeholder indicating their index.
305 w.string(fmt.Sprintf("$%d", i))
308 if w.debug || w.ctxt != nil {
309 w.string(subscript(t.id))
314 // For externally defined implementations of Type.
315 // Note: In this case cycles won't be caught.
320 // typeSet writes a canonical hash for an interface type set.
321 func (w *typeWriter) typeSet(s *_TypeSet) {
322 assert(w.ctxt != nil)
324 for _, m := range s.methods {
330 w.signature(m.typ.(*Signature))
333 case s.terms.isAll():
335 case s.terms.isEmpty():
336 w.string(s.terms.String())
338 var termHashes []string
339 for _, term := range s.terms {
340 // terms are not canonically sorted, so we sort their hashes instead.
345 newTypeHasher(&buf, w.ctxt).typ(term.typ)
346 termHashes = append(termHashes, buf.String())
348 sort.Strings(termHashes)
352 w.string(strings.Join(termHashes, "|"))
356 func (w *typeWriter) typeList(list []Type) {
358 for i, typ := range list {
367 func (w *typeWriter) tParamList(list []*TypeParam) {
370 for i, tpar := range list {
371 // Determine the type parameter and its constraint.
372 // list is expected to hold type parameter names,
373 // but don't crash if that's not the case.
375 w.error("nil type parameter")
379 if tpar.bound != prev {
380 // bound changed - write previous one before advancing
396 func (w *typeWriter) typeName(obj *TypeName) {
398 writePackage(w.buf, obj.pkg, w.qf)
403 func (w *typeWriter) tuple(tup *Tuple, variadic bool) {
406 for i, v := range tup.vars {
410 // parameter names are ignored for type identity and thus type hashes
411 if w.ctxt == nil && v.name != "" {
416 if variadic && i == len(tup.vars)-1 {
417 if s, ok := typ.(*Slice); ok {
422 // append(s, "foo"...) leads to signature func([]byte, string...)
423 if t, _ := under(typ).(*Basic); t == nil || t.kind != String {
424 w.error("expected string type")
438 func (w *typeWriter) signature(sig *Signature) {
439 if sig.TypeParams().Len() != 0 {
441 assert(w.tparams == nil)
442 w.tparams = sig.TypeParams()
447 w.tParamList(sig.TypeParams().list())
450 w.tuple(sig.params, sig.variadic)
452 n := sig.results.Len()
459 if n == 1 && (w.ctxt != nil || sig.results.vars[0].name == "") {
460 // single unnamed result (if type hashing, name must be ignored)
461 w.typ(sig.results.vars[0].typ)
465 // multiple or named result(s)
466 w.tuple(sig.results, false)
469 // subscript returns the decimal (utf8) representation of x using subscript digits.
470 func subscript(x uint64) string {
471 const w = len("₀") // all digits 0...9 have the same utf8 width
476 utf8.EncodeRune(buf[i:], '₀'+rune(x%10)) // '₀' == U+2080
482 return string(buf[i:])