1 // Copyright 2020, 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.md file.
12 // TypeString is nearly identical to reflect.Type.String,
13 // but has an additional option to specify that full type names be used.
14 func TypeString(t reflect.Type, qualified bool) string {
15 return string(appendTypeName(nil, t, qualified, false))
18 func appendTypeName(b []byte, t reflect.Type, qualified, elideFunc bool) []byte {
19 // BUG: Go reflection provides no way to disambiguate two named types
20 // of the same name and within the same package,
21 // but declared within the namespace of different functions.
25 if qualified && t.PkgPath() != "" {
27 b = append(b, t.PkgPath()...)
30 b = append(b, t.Name()...)
32 b = append(b, t.String()...)
38 switch k := t.Kind(); k {
39 case reflect.Bool, reflect.String, reflect.UnsafePointer,
40 reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
41 reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr,
42 reflect.Float32, reflect.Float64, reflect.Complex64, reflect.Complex128:
43 b = append(b, k.String()...)
45 if t.ChanDir() == reflect.RecvDir {
46 b = append(b, "<-"...)
48 b = append(b, "chan"...)
49 if t.ChanDir() == reflect.SendDir {
50 b = append(b, "<-"...)
53 b = appendTypeName(b, t.Elem(), qualified, false)
56 b = append(b, "func"...)
59 for i := 0; i < t.NumIn(); i++ {
61 b = append(b, ", "...)
63 if i == t.NumIn()-1 && t.IsVariadic() {
64 b = append(b, "..."...)
65 b = appendTypeName(b, t.In(i).Elem(), qualified, false)
67 b = appendTypeName(b, t.In(i), qualified, false)
76 b = appendTypeName(b, t.Out(0), qualified, false)
78 b = append(b, " ("...)
79 for i := 0; i < t.NumOut(); i++ {
81 b = append(b, ", "...)
83 b = appendTypeName(b, t.Out(i), qualified, false)
88 b = append(b, "struct{ "...)
89 for i := 0; i < t.NumField(); i++ {
91 b = append(b, "; "...)
95 if qualified && sf.PkgPath != "" {
97 b = append(b, sf.PkgPath...)
101 b = append(b, sf.Name...)
104 b = appendTypeName(b, sf.Type, qualified, false)
107 b = strconv.AppendQuote(b, string(sf.Tag))
110 if b[len(b)-1] == ' ' {
116 case reflect.Slice, reflect.Array:
118 if k == reflect.Array {
119 b = strconv.AppendUint(b, uint64(t.Len()), 10)
122 b = appendTypeName(b, t.Elem(), qualified, false)
124 b = append(b, "map["...)
125 b = appendTypeName(b, t.Key(), qualified, false)
127 b = appendTypeName(b, t.Elem(), qualified, false)
130 b = appendTypeName(b, t.Elem(), qualified, false)
131 case reflect.Interface:
132 b = append(b, "interface{ "...)
133 for i := 0; i < t.NumMethod(); i++ {
135 b = append(b, "; "...)
138 if qualified && m.PkgPath != "" {
140 b = append(b, m.PkgPath...)
144 b = append(b, m.Name...)
145 b = appendTypeName(b, m.Type, qualified, true)
147 if b[len(b)-1] == ' ' {
154 panic("invalid kind: " + k.String())