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 type typeWriter struct {
70 ctxt *Context // if non-nil, we are type hashing
73 func newTypeWriter(buf *bytes.Buffer, qf Qualifier) *typeWriter {
74 return &typeWriter{buf, make(map[Type]bool), qf, nil}
77 func newTypeHasher(buf *bytes.Buffer, ctxt *Context) *typeWriter {
79 return &typeWriter{buf, make(map[Type]bool), nil, ctxt}
82 func (w *typeWriter) byte(b byte) {
91 if b == ',' || b == ';' {
96 func (w *typeWriter) string(s string) {
100 func (w *typeWriter) error(msg string) {
104 w.buf.WriteString("<" + msg + ">")
107 func (w *typeWriter) typ(typ Type) {
109 w.error("cycle to " + goTypeName(typ))
113 defer delete(w.seen, typ)
115 switch t := typ.(type) {
120 // exported basic types go into package unsafe
121 // (currently this is just unsafe.Pointer)
122 if isExported(t.name) {
123 if obj, _ := Unsafe.scope.Lookup(t.name).(*TypeName); obj != nil {
132 w.string(strconv.FormatInt(t.len, 10))
142 for i, f := range t.fields {
146 // This doesn't do the right thing for embedded type
147 // aliases where we should print the alias name, not
148 // the aliased type (see issue #44410).
154 if tag := t.Tag(i); tag != "" {
156 // TODO(gri) If tag contains blanks, replacing them with '#'
157 // in Context.TypeHash may produce another tag
159 w.string(strconv.Quote(tag))
176 // Unions only appear as (syntactic) embedded elements
177 // in interfaces and syntactically cannot be empty.
179 w.error("empty union")
182 for i, t := range t.terms {
194 if len(t.methods) == 0 && len(t.embeddeds) == 1 {
195 w.typ(t.embeddeds[0])
198 // Something's wrong with the implicit interface.
199 // Print it as such and continue.
200 w.string("/* implicit */ ")
202 w.string("interface{")
204 for _, m := range t.methods {
210 w.signature(m.typ.(*Signature))
212 for _, typ := range t.embeddeds {
233 // chan (<-chan T) requires parentheses
234 if c, _ := t.elem.(*Chan); c != nil && c.dir == RecvOnly {
242 w.error("unknown channel direction")
258 w.typeList(t.targs.list())
259 } else if w.ctxt == nil && t.TypeParams().Len() != 0 { // For type hashing, don't need to format the TParams
260 // parameterized type
261 w.tParamList(t.TypeParams().list())
266 w.error("unnamed type parameter")
269 // Optionally write out package for typeparams (like Named).
270 if t.obj.pkg != nil {
271 writePackage(w.buf, t.obj.pkg, w.qf)
273 w.string(t.obj.name + subscript(t.id))
276 // For externally defined implementations of Type.
277 // Note: In this case cycles won't be caught.
282 // If w.ctxt is non-nil, typePrefix writes a unique prefix for the named type t
283 // based on the types already observed by w.ctxt. If w.ctxt is nil, it does
285 func (w *typeWriter) typePrefix(t *Named) {
287 w.string(strconv.Itoa(w.ctxt.idForType(t)))
291 func (w *typeWriter) typeList(list []Type) {
293 for i, typ := range list {
302 func (w *typeWriter) tParamList(list []*TypeParam) {
305 for i, tpar := range list {
306 // Determine the type parameter and its constraint.
307 // list is expected to hold type parameter names,
308 // but don't crash if that's not the case.
310 w.error("nil type parameter")
314 if tpar.bound != prev {
315 // bound changed - write previous one before advancing
331 func (w *typeWriter) typeName(obj *TypeName) {
333 writePackage(w.buf, obj.pkg, w.qf)
338 func (w *typeWriter) tuple(tup *Tuple, variadic bool) {
341 for i, v := range tup.vars {
345 // parameter names are ignored for type identity and thus type hashes
346 if w.ctxt == nil && v.name != "" {
351 if variadic && i == len(tup.vars)-1 {
352 if s, ok := typ.(*Slice); ok {
357 // append(s, "foo"...) leads to signature func([]byte, string...)
358 if t := toBasic(typ); t == nil || t.kind != String {
359 w.error("expected string type")
373 func (w *typeWriter) signature(sig *Signature) {
374 if sig.TypeParams().Len() != 0 {
375 w.tParamList(sig.TypeParams().list())
378 w.tuple(sig.params, sig.variadic)
380 n := sig.results.Len()
387 if n == 1 && (w.ctxt != nil || sig.results.vars[0].name == "") {
388 // single unnamed result (if type hashing, name must be ignored)
389 w.typ(sig.results.vars[0].typ)
393 // multiple or named result(s)
394 w.tuple(sig.results, false)
397 // subscript returns the decimal (utf8) representation of x using subscript digits.
398 func subscript(x uint64) string {
399 const w = len("₀") // all digits 0...9 have the same utf8 width
404 utf8.EncodeRune(buf[i:], '₀'+rune(x%10)) // '₀' == U+2080
410 return string(buf[i:])