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. The Qualifier controls the printing
62 // of package-level objects, and may be nil.
63 func WriteSignature(buf *bytes.Buffer, sig *Signature, qf Qualifier) {
64 newTypeWriter(buf, qf).signature(sig)
67 type typeWriter struct {
71 ctxt *Context // if non-nil, we are type hashing
72 tparams *TypeParamList // local type parameters
73 paramNames bool // if set, write function parameter names, otherwise, write types only
74 tpSubscripts bool // if set, write type parameter indices as subscripts
75 pkgInfo bool // package-annotate first unexported-type field to avoid confusing type description
78 func newTypeWriter(buf *bytes.Buffer, qf Qualifier) *typeWriter {
79 return &typeWriter{buf, make(map[Type]bool), qf, nil, nil, true, false, false}
82 func newTypeHasher(buf *bytes.Buffer, ctxt *Context) *typeWriter {
84 return &typeWriter{buf, make(map[Type]bool), nil, ctxt, nil, false, 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 {
152 // If disambiguating one struct for another, look for the first unexported field.
153 // Do this first in case of nested structs; tag the first-outermost field.
155 if w.qf == nil && w.pkgInfo && !isExported(f.name) {
156 // note for embedded types, type name is field name, and "string" etc are lower case hence unexported.
158 w.pkgInfo = false // only tag once
161 // This doesn't do the right thing for embedded type
162 // aliases where we should print the alias name, not
163 // the aliased type (see go.dev/issue/44410).
170 w.string(" /* package ")
171 w.string(f.pkg.Path())
174 if tag := t.Tag(i); tag != "" {
176 // TODO(gri) If tag contains blanks, replacing them with '#'
177 // in Context.TypeHash may produce another tag
179 w.string(strconv.Quote(tag))
196 // Unions only appear as (syntactic) embedded elements
197 // in interfaces and syntactically cannot be empty.
199 w.error("empty union")
202 for i, t := range t.terms {
214 if t == universeAny.Type() {
215 // When not hashing, we can try to improve type strings by writing "any"
216 // for a type that is pointer-identical to universeAny. This logic should
217 // be deprecated by more robust handling for aliases.
221 if t == asNamed(universeComparable.Type()).underlying {
222 w.string("interface{comparable}")
227 if len(t.methods) == 0 && len(t.embeddeds) == 1 {
228 w.typ(t.embeddeds[0])
231 // Something's wrong with the implicit interface.
232 // Print it as such and continue.
233 w.string("/* implicit */ ")
235 w.string("interface{")
238 w.typeSet(t.typeSet())
240 for _, m := range t.methods {
246 w.signature(m.typ.(*Signature))
248 for _, typ := range t.embeddeds {
270 // chan (<-chan T) requires parentheses
271 if c, _ := t.elem.(*Chan); c != nil && c.dir == RecvOnly {
279 w.error("unknown channel direction")
291 // If hashing, write a unique prefix for t to represent its identity, since
292 // named type identity is pointer identity.
294 w.string(strconv.Itoa(w.ctxt.getID(t)))
296 w.typeName(t.obj) // when hashing written for readability of the hash only
299 w.typeList(t.inst.targs.list())
300 } else if w.ctxt == nil && t.TypeParams().Len() != 0 { // For type hashing, don't need to format the TypeParams
301 // parameterized type
302 w.tParamList(t.TypeParams().list())
307 w.error("unnamed type parameter")
310 if i := tparamIndex(w.tparams.list(), t); i >= 0 {
311 // The names of type parameters that are declared by the type being
312 // hashed are not part of the type identity. Replace them with a
313 // placeholder indicating their index.
314 w.string(fmt.Sprintf("$%d", i))
317 if w.tpSubscripts || w.ctxt != nil {
318 w.string(subscript(t.id))
320 // If the type parameter name is the same as a predeclared object
321 // (say int), point out where it is declared to avoid confusing
322 // error messages. This doesn't need to be super-elegant; we just
323 // need a clear indication that this is not a predeclared name.
324 if w.ctxt == nil && Universe.Lookup(t.obj.name) != nil {
325 w.string(sprintf(nil, false, " /* with %s declared at %s */", t.obj.name, t.obj.Pos()))
330 // For externally defined implementations of Type.
331 // Note: In this case cycles won't be caught.
336 // typeSet writes a canonical hash for an interface type set.
337 func (w *typeWriter) typeSet(s *_TypeSet) {
338 assert(w.ctxt != nil)
340 for _, m := range s.methods {
346 w.signature(m.typ.(*Signature))
349 case s.terms.isAll():
351 case s.terms.isEmpty():
352 w.string(s.terms.String())
354 var termHashes []string
355 for _, term := range s.terms {
356 // terms are not canonically sorted, so we sort their hashes instead.
361 newTypeHasher(&buf, w.ctxt).typ(term.typ)
362 termHashes = append(termHashes, buf.String())
364 sort.Strings(termHashes)
368 w.string(strings.Join(termHashes, "|"))
372 func (w *typeWriter) typeList(list []Type) {
374 for i, typ := range list {
383 func (w *typeWriter) tParamList(list []*TypeParam) {
386 for i, tpar := range list {
387 // Determine the type parameter and its constraint.
388 // list is expected to hold type parameter names,
389 // but don't crash if that's not the case.
391 w.error("nil type parameter")
395 if tpar.bound != prev {
396 // bound changed - write previous one before advancing
412 func (w *typeWriter) typeName(obj *TypeName) {
413 w.string(packagePrefix(obj.pkg, w.qf))
417 func (w *typeWriter) tuple(tup *Tuple, variadic bool) {
420 for i, v := range tup.vars {
424 // parameter names are ignored for type identity and thus type hashes
425 if w.ctxt == nil && v.name != "" && w.paramNames {
430 if variadic && i == len(tup.vars)-1 {
431 if s, ok := typ.(*Slice); ok {
436 // append(s, "foo"...) leads to signature func([]byte, string...)
437 if t, _ := under(typ).(*Basic); t == nil || t.kind != String {
438 w.error("expected string type")
452 func (w *typeWriter) signature(sig *Signature) {
453 if sig.TypeParams().Len() != 0 {
455 assert(w.tparams == nil)
456 w.tparams = sig.TypeParams()
461 w.tParamList(sig.TypeParams().list())
464 w.tuple(sig.params, sig.variadic)
466 n := sig.results.Len()
473 if n == 1 && (w.ctxt != nil || sig.results.vars[0].name == "") {
474 // single unnamed result (if type hashing, name must be ignored)
475 w.typ(sig.results.vars[0].typ)
479 // multiple or named result(s)
480 w.tuple(sig.results, false)
483 // subscript returns the decimal (utf8) representation of x using subscript digits.
484 func subscript(x uint64) string {
485 const w = len("₀") // all digits 0...9 have the same utf8 width
490 utf8.EncodeRune(buf[i:], '₀'+rune(x%10)) // '₀' == U+2080
496 return string(buf[i:])