Joe Tsai | 90fe996 | 2018-10-18 11:06:29 -0700 | [diff] [blame] | 1 | // Copyright 2018 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. |
| 4 | |
Joe Tsai | 08e0030 | 2018-11-26 22:32:06 -0800 | [diff] [blame] | 5 | package legacy |
Joe Tsai | 90fe996 | 2018-10-18 11:06:29 -0700 | [diff] [blame] | 6 | |
| 7 | import ( |
| 8 | "fmt" |
Joe Tsai | 90fe996 | 2018-10-18 11:06:29 -0700 | [diff] [blame] | 9 | "reflect" |
Joe Tsai | 90fe996 | 2018-10-18 11:06:29 -0700 | [diff] [blame] | 10 | "strings" |
| 11 | "sync" |
| 12 | "unicode" |
| 13 | |
Damien Neil | e89e624 | 2019-05-13 23:55:40 -0700 | [diff] [blame] | 14 | ptag "google.golang.org/protobuf/internal/encoding/tag" |
| 15 | pimpl "google.golang.org/protobuf/internal/impl" |
| 16 | ptype "google.golang.org/protobuf/internal/prototype" |
| 17 | pref "google.golang.org/protobuf/reflect/protoreflect" |
Joe Tsai | b2f66be | 2019-05-22 00:42:45 -0400 | [diff] [blame^] | 18 | "google.golang.org/protobuf/reflect/prototype" |
Joe Tsai | 90fe996 | 2018-10-18 11:06:29 -0700 | [diff] [blame] | 19 | ) |
| 20 | |
Joe Tsai | 6dbffb7 | 2018-12-04 14:06:19 -0800 | [diff] [blame] | 21 | // wrapMessage wraps v as a protoreflect.ProtoMessage, |
Joe Tsai | f0c01e4 | 2018-11-06 13:05:20 -0800 | [diff] [blame] | 22 | // where v must be a *struct kind and not implement the v2 API already. |
Joe Tsai | 6dbffb7 | 2018-12-04 14:06:19 -0800 | [diff] [blame] | 23 | func wrapMessage(v reflect.Value) pref.ProtoMessage { |
Joe Tsai | 4fe9663 | 2019-05-22 05:12:36 -0400 | [diff] [blame] | 24 | mt := loadMessageInfo(v.Type()) |
Joe Tsai | 08e0030 | 2018-11-26 22:32:06 -0800 | [diff] [blame] | 25 | return mt.MessageOf(v.Interface()).Interface() |
Joe Tsai | f0c01e4 | 2018-11-06 13:05:20 -0800 | [diff] [blame] | 26 | } |
| 27 | |
Joe Tsai | 4fe9663 | 2019-05-22 05:12:36 -0400 | [diff] [blame] | 28 | var messageTypeCache sync.Map // map[reflect.Type]*MessageInfo |
Joe Tsai | ce6edd3 | 2018-10-19 16:27:46 -0700 | [diff] [blame] | 29 | |
Joe Tsai | 4fe9663 | 2019-05-22 05:12:36 -0400 | [diff] [blame] | 30 | // loadMessageInfo dynamically loads a *MessageInfo for t, |
Joe Tsai | f0c01e4 | 2018-11-06 13:05:20 -0800 | [diff] [blame] | 31 | // where t must be a *struct kind and not implement the v2 API already. |
Joe Tsai | 4fe9663 | 2019-05-22 05:12:36 -0400 | [diff] [blame] | 32 | func loadMessageInfo(t reflect.Type) *pimpl.MessageInfo { |
| 33 | // Fast-path: check if a MessageInfo is cached for this concrete type. |
Joe Tsai | f0c01e4 | 2018-11-06 13:05:20 -0800 | [diff] [blame] | 34 | if mt, ok := messageTypeCache.Load(t); ok { |
Joe Tsai | 4fe9663 | 2019-05-22 05:12:36 -0400 | [diff] [blame] | 35 | return mt.(*pimpl.MessageInfo) |
Joe Tsai | ce6edd3 | 2018-10-19 16:27:46 -0700 | [diff] [blame] | 36 | } |
| 37 | |
Joe Tsai | 4fe9663 | 2019-05-22 05:12:36 -0400 | [diff] [blame] | 38 | // Slow-path: derive message descriptor and initialize MessageInfo. |
Joe Tsai | 35ec98f | 2019-03-25 14:41:32 -0700 | [diff] [blame] | 39 | md := LoadMessageDesc(t) |
Joe Tsai | 4fe9663 | 2019-05-22 05:12:36 -0400 | [diff] [blame] | 40 | mt := new(pimpl.MessageInfo) |
Damien Neil | 8012b44 | 2019-01-18 09:32:24 -0800 | [diff] [blame] | 41 | mt.GoType = t |
Joe Tsai | b2f66be | 2019-05-22 00:42:45 -0400 | [diff] [blame^] | 42 | mt.PBType = &prototype.Message{ |
| 43 | MessageDescriptor: md, |
| 44 | NewMessage: func() pref.Message { |
| 45 | return mt.MessageOf(reflect.New(t.Elem()).Interface()) |
| 46 | }, |
| 47 | } |
Joe Tsai | b936504 | 2019-03-19 14:14:29 -0700 | [diff] [blame] | 48 | if mt, ok := messageTypeCache.LoadOrStore(t, mt); ok { |
Joe Tsai | 4fe9663 | 2019-05-22 05:12:36 -0400 | [diff] [blame] | 49 | return mt.(*pimpl.MessageInfo) |
Joe Tsai | b936504 | 2019-03-19 14:14:29 -0700 | [diff] [blame] | 50 | } |
Joe Tsai | f0c01e4 | 2018-11-06 13:05:20 -0800 | [diff] [blame] | 51 | return mt |
Joe Tsai | ce6edd3 | 2018-10-19 16:27:46 -0700 | [diff] [blame] | 52 | } |
| 53 | |
Joe Tsai | b936504 | 2019-03-19 14:14:29 -0700 | [diff] [blame] | 54 | var messageDescLock sync.Mutex |
Joe Tsai | 90fe996 | 2018-10-18 11:06:29 -0700 | [diff] [blame] | 55 | var messageDescCache sync.Map // map[reflect.Type]protoreflect.MessageDescriptor |
| 56 | |
Joe Tsai | 35ec98f | 2019-03-25 14:41:32 -0700 | [diff] [blame] | 57 | // LoadMessageDesc returns an MessageDescriptor derived from the Go type, |
Joe Tsai | ce6edd3 | 2018-10-19 16:27:46 -0700 | [diff] [blame] | 58 | // which must be a *struct kind and not implement the v2 API already. |
Joe Tsai | 35ec98f | 2019-03-25 14:41:32 -0700 | [diff] [blame] | 59 | // |
| 60 | // This is exported for testing purposes. |
| 61 | func LoadMessageDesc(t reflect.Type) pref.MessageDescriptor { |
Joe Tsai | 90fe996 | 2018-10-18 11:06:29 -0700 | [diff] [blame] | 62 | return messageDescSet{}.Load(t) |
| 63 | } |
| 64 | |
| 65 | type messageDescSet struct { |
| 66 | visited map[reflect.Type]*ptype.StandaloneMessage |
| 67 | descs []*ptype.StandaloneMessage |
| 68 | types []reflect.Type |
| 69 | } |
| 70 | |
| 71 | func (ms messageDescSet) Load(t reflect.Type) pref.MessageDescriptor { |
| 72 | // Fast-path: check if a MessageDescriptor is cached for this concrete type. |
| 73 | if mi, ok := messageDescCache.Load(t); ok { |
| 74 | return mi.(pref.MessageDescriptor) |
| 75 | } |
| 76 | |
| 77 | // Slow-path: initialize MessageDescriptor from the Go type. |
Joe Tsai | b936504 | 2019-03-19 14:14:29 -0700 | [diff] [blame] | 78 | // |
| 79 | // Hold a global lock during message creation to ensure that each Go type |
| 80 | // maps to exactly one MessageDescriptor. After obtaining the lock, we must |
| 81 | // check again whether the message has already been handled. |
| 82 | messageDescLock.Lock() |
| 83 | defer messageDescLock.Unlock() |
| 84 | if mi, ok := messageDescCache.Load(t); ok { |
| 85 | return mi.(pref.MessageDescriptor) |
| 86 | } |
Joe Tsai | 90fe996 | 2018-10-18 11:06:29 -0700 | [diff] [blame] | 87 | |
| 88 | // Processing t recursively populates descs and types with all sub-messages. |
| 89 | // The descriptor for the first type is guaranteed to be at the front. |
| 90 | ms.processMessage(t) |
| 91 | |
| 92 | // Within a proto file it is possible for cyclic dependencies to exist |
| 93 | // between multiple message types. When these cases arise, the set of |
| 94 | // message descriptors must be created together. |
| 95 | mds, err := ptype.NewMessages(ms.descs) |
| 96 | if err != nil { |
| 97 | panic(err) |
| 98 | } |
| 99 | for i, md := range mds { |
| 100 | // Protobuf semantics represents map entries under-the-hood as |
| 101 | // pseudo-messages (has a descriptor, but no generated Go type). |
| 102 | // Avoid caching these fake messages. |
| 103 | if t := ms.types[i]; t.Kind() != reflect.Map { |
| 104 | messageDescCache.Store(t, md) |
| 105 | } |
| 106 | } |
| 107 | return mds[0] |
| 108 | } |
| 109 | |
| 110 | func (ms *messageDescSet) processMessage(t reflect.Type) pref.MessageDescriptor { |
| 111 | // Fast-path: Obtain a placeholder if the message is already processed. |
| 112 | if m, ok := ms.visited[t]; ok { |
| 113 | return ptype.PlaceholderMessage(m.FullName) |
| 114 | } |
| 115 | |
| 116 | // Slow-path: Walk over the struct fields to derive the message descriptor. |
Joe Tsai | 6f9095c | 2018-11-10 14:12:21 -0800 | [diff] [blame] | 117 | if t.Kind() != reflect.Ptr || t.Elem().Kind() != reflect.Struct || t.Elem().PkgPath() == "" { |
| 118 | panic(fmt.Sprintf("got %v, want named *struct kind", t)) |
Joe Tsai | 90fe996 | 2018-10-18 11:06:29 -0700 | [diff] [blame] | 119 | } |
| 120 | |
| 121 | // Derive name and syntax from the raw descriptor. |
| 122 | m := new(ptype.StandaloneMessage) |
| 123 | mv := reflect.New(t.Elem()).Interface() |
| 124 | if _, ok := mv.(pref.ProtoMessage); ok { |
| 125 | panic(fmt.Sprintf("%v already implements proto.Message", t)) |
| 126 | } |
Joe Tsai | 6dbffb7 | 2018-12-04 14:06:19 -0800 | [diff] [blame] | 127 | if md, ok := mv.(messageV1); ok { |
Joe Tsai | 90fe996 | 2018-10-18 11:06:29 -0700 | [diff] [blame] | 128 | b, idxs := md.Descriptor() |
Damien Neil | 987d570 | 2019-04-10 11:06:53 -0700 | [diff] [blame] | 129 | fd := loadFileDesc(b) |
Joe Tsai | 90fe996 | 2018-10-18 11:06:29 -0700 | [diff] [blame] | 130 | |
| 131 | // Derive syntax. |
| 132 | switch fd.GetSyntax() { |
| 133 | case "proto2", "": |
| 134 | m.Syntax = pref.Proto2 |
| 135 | case "proto3": |
| 136 | m.Syntax = pref.Proto3 |
| 137 | } |
| 138 | |
| 139 | // Derive full name. |
| 140 | md := fd.MessageType[idxs[0]] |
| 141 | m.FullName = pref.FullName(fd.GetPackage()).Append(pref.Name(md.GetName())) |
| 142 | for _, i := range idxs[1:] { |
| 143 | md = md.NestedType[i] |
| 144 | m.FullName = m.FullName.Append(pref.Name(md.GetName())) |
| 145 | } |
| 146 | } else { |
Joe Tsai | 6dbffb7 | 2018-12-04 14:06:19 -0800 | [diff] [blame] | 147 | // If the type does not implement messageV1, then the only way to |
Joe Tsai | 90fe996 | 2018-10-18 11:06:29 -0700 | [diff] [blame] | 148 | // obtain the full name is through the registry. However, this is |
| 149 | // unreliable as some generated messages register with a fork of |
| 150 | // golang/protobuf, so the registry may not have this information. |
| 151 | m.FullName = deriveFullName(t.Elem()) |
| 152 | m.Syntax = pref.Proto2 |
| 153 | |
| 154 | // Try to determine if the message is using proto3 by checking scalars. |
| 155 | for i := 0; i < t.Elem().NumField(); i++ { |
| 156 | f := t.Elem().Field(i) |
| 157 | if tag := f.Tag.Get("protobuf"); tag != "" { |
| 158 | switch f.Type.Kind() { |
| 159 | case reflect.Bool, reflect.Int32, reflect.Int64, reflect.Uint32, reflect.Uint64, reflect.Float32, reflect.Float64, reflect.String: |
| 160 | m.Syntax = pref.Proto3 |
| 161 | } |
| 162 | for _, s := range strings.Split(tag, ",") { |
| 163 | if s == "proto3" { |
| 164 | m.Syntax = pref.Proto3 |
| 165 | } |
| 166 | } |
| 167 | } |
| 168 | } |
| 169 | } |
| 170 | ms.visit(m, t) |
| 171 | |
| 172 | // Obtain a list of oneof wrapper types. |
| 173 | var oneofWrappers []reflect.Type |
| 174 | if fn, ok := t.MethodByName("XXX_OneofFuncs"); ok { |
| 175 | vs := fn.Func.Call([]reflect.Value{reflect.Zero(fn.Type.In(0))})[3] |
| 176 | for _, v := range vs.Interface().([]interface{}) { |
| 177 | oneofWrappers = append(oneofWrappers, reflect.TypeOf(v)) |
| 178 | } |
| 179 | } |
Joe Tsai | 25cc69d | 2018-11-28 23:43:49 -0800 | [diff] [blame] | 180 | if fn, ok := t.MethodByName("XXX_OneofWrappers"); ok { |
| 181 | vs := fn.Func.Call([]reflect.Value{reflect.Zero(fn.Type.In(0))})[0] |
| 182 | for _, v := range vs.Interface().([]interface{}) { |
| 183 | oneofWrappers = append(oneofWrappers, reflect.TypeOf(v)) |
| 184 | } |
| 185 | } |
Joe Tsai | 90fe996 | 2018-10-18 11:06:29 -0700 | [diff] [blame] | 186 | |
| 187 | // Obtain a list of the extension ranges. |
| 188 | if fn, ok := t.MethodByName("ExtensionRangeArray"); ok { |
| 189 | vs := fn.Func.Call([]reflect.Value{reflect.Zero(fn.Type.In(0))})[0] |
| 190 | for i := 0; i < vs.Len(); i++ { |
| 191 | v := vs.Index(i) |
| 192 | m.ExtensionRanges = append(m.ExtensionRanges, [2]pref.FieldNumber{ |
| 193 | pref.FieldNumber(v.FieldByName("Start").Int()), |
| 194 | pref.FieldNumber(v.FieldByName("End").Int() + 1), |
| 195 | }) |
| 196 | } |
| 197 | } |
| 198 | |
| 199 | // Derive the message fields by inspecting the struct fields. |
| 200 | for i := 0; i < t.Elem().NumField(); i++ { |
| 201 | f := t.Elem().Field(i) |
| 202 | if tag := f.Tag.Get("protobuf"); tag != "" { |
| 203 | tagKey := f.Tag.Get("protobuf_key") |
| 204 | tagVal := f.Tag.Get("protobuf_val") |
| 205 | m.Fields = append(m.Fields, ms.parseField(tag, tagKey, tagVal, f.Type, m)) |
| 206 | } |
| 207 | if tag := f.Tag.Get("protobuf_oneof"); tag != "" { |
| 208 | name := pref.Name(tag) |
| 209 | m.Oneofs = append(m.Oneofs, ptype.Oneof{Name: name}) |
| 210 | for _, t := range oneofWrappers { |
| 211 | if t.Implements(f.Type) { |
| 212 | f := t.Elem().Field(0) |
| 213 | if tag := f.Tag.Get("protobuf"); tag != "" { |
| 214 | ft := ms.parseField(tag, "", "", f.Type, m) |
| 215 | ft.OneofName = name |
| 216 | m.Fields = append(m.Fields, ft) |
| 217 | } |
| 218 | } |
| 219 | } |
| 220 | } |
| 221 | } |
| 222 | |
| 223 | return ptype.PlaceholderMessage(m.FullName) |
| 224 | } |
| 225 | |
Joe Tsai | 05828db | 2018-11-01 13:52:16 -0700 | [diff] [blame] | 226 | func (ms *messageDescSet) parseField(tag, tagKey, tagVal string, goType reflect.Type, parent *ptype.StandaloneMessage) ptype.Field { |
| 227 | t := goType |
Joe Tsai | 90fe996 | 2018-10-18 11:06:29 -0700 | [diff] [blame] | 228 | isOptional := t.Kind() == reflect.Ptr && t.Elem().Kind() != reflect.Struct |
| 229 | isRepeated := t.Kind() == reflect.Slice && t.Elem().Kind() != reflect.Uint8 |
| 230 | if isOptional || isRepeated { |
| 231 | t = t.Elem() |
| 232 | } |
Joe Tsai | 05828db | 2018-11-01 13:52:16 -0700 | [diff] [blame] | 233 | f := ptag.Unmarshal(tag, t) |
Joe Tsai | 90fe996 | 2018-10-18 11:06:29 -0700 | [diff] [blame] | 234 | |
| 235 | // Populate EnumType and MessageType. |
| 236 | if f.EnumType == nil && f.Kind == pref.EnumKind { |
Damien Neil | a8593ba | 2019-01-08 16:18:07 -0800 | [diff] [blame] | 237 | if ev, ok := reflect.Zero(t).Interface().(pref.Enum); ok { |
Joe Tsai | 0fc49f8 | 2019-05-01 12:29:25 -0700 | [diff] [blame] | 238 | f.EnumType = ev.Descriptor() |
Joe Tsai | 90fe996 | 2018-10-18 11:06:29 -0700 | [diff] [blame] | 239 | } else { |
Joe Tsai | 35ec98f | 2019-03-25 14:41:32 -0700 | [diff] [blame] | 240 | f.EnumType = LoadEnumDesc(t) |
Joe Tsai | 90fe996 | 2018-10-18 11:06:29 -0700 | [diff] [blame] | 241 | } |
| 242 | } |
| 243 | if f.MessageType == nil && (f.Kind == pref.MessageKind || f.Kind == pref.GroupKind) { |
| 244 | if mv, ok := reflect.Zero(t).Interface().(pref.ProtoMessage); ok { |
Joe Tsai | 0fc49f8 | 2019-05-01 12:29:25 -0700 | [diff] [blame] | 245 | f.MessageType = mv.ProtoReflect().Descriptor() |
Joe Tsai | 90fe996 | 2018-10-18 11:06:29 -0700 | [diff] [blame] | 246 | } else if t.Kind() == reflect.Map { |
| 247 | m := &ptype.StandaloneMessage{ |
Damien Neil | 232ea15 | 2018-12-10 15:14:36 -0800 | [diff] [blame] | 248 | Syntax: parent.Syntax, |
| 249 | FullName: parent.FullName.Append(mapEntryName(f.Name)), |
Damien Neil | 232ea15 | 2018-12-10 15:14:36 -0800 | [diff] [blame] | 250 | IsMapEntry: true, |
Joe Tsai | 90fe996 | 2018-10-18 11:06:29 -0700 | [diff] [blame] | 251 | Fields: []ptype.Field{ |
| 252 | ms.parseField(tagKey, "", "", t.Key(), nil), |
| 253 | ms.parseField(tagVal, "", "", t.Elem(), nil), |
| 254 | }, |
| 255 | } |
| 256 | ms.visit(m, t) |
| 257 | f.MessageType = ptype.PlaceholderMessage(m.FullName) |
| 258 | } else if mv, ok := messageDescCache.Load(t); ok { |
| 259 | f.MessageType = mv.(pref.MessageDescriptor) |
| 260 | } else { |
| 261 | f.MessageType = ms.processMessage(t) |
| 262 | } |
| 263 | } |
| 264 | return f |
| 265 | } |
| 266 | |
| 267 | func (ms *messageDescSet) visit(m *ptype.StandaloneMessage, t reflect.Type) { |
| 268 | if ms.visited == nil { |
| 269 | ms.visited = make(map[reflect.Type]*ptype.StandaloneMessage) |
| 270 | } |
| 271 | if t.Kind() != reflect.Map { |
| 272 | ms.visited[t] = m |
| 273 | } |
| 274 | ms.descs = append(ms.descs, m) |
| 275 | ms.types = append(ms.types, t) |
| 276 | } |
| 277 | |
| 278 | // deriveFullName derives a fully qualified protobuf name for the given Go type |
| 279 | // The provided name is not guaranteed to be stable nor universally unique. |
| 280 | // It should be sufficiently unique within a program. |
| 281 | func deriveFullName(t reflect.Type) pref.FullName { |
| 282 | sanitize := func(r rune) rune { |
| 283 | switch { |
| 284 | case r == '/': |
| 285 | return '.' |
| 286 | case 'a' <= r && r <= 'z', 'A' <= r && r <= 'Z', '0' <= r && r <= '9': |
| 287 | return r |
| 288 | default: |
| 289 | return '_' |
| 290 | } |
| 291 | } |
| 292 | prefix := strings.Map(sanitize, t.PkgPath()) |
| 293 | suffix := strings.Map(sanitize, t.Name()) |
| 294 | if suffix == "" { |
| 295 | suffix = fmt.Sprintf("UnknownX%X", reflect.ValueOf(t).Pointer()) |
| 296 | } |
| 297 | |
| 298 | ss := append(strings.Split(prefix, "."), suffix) |
| 299 | for i, s := range ss { |
| 300 | if s == "" || ('0' <= s[0] && s[0] <= '9') { |
| 301 | ss[i] = "x" + s |
| 302 | } |
| 303 | } |
| 304 | return pref.FullName(strings.Join(ss, ".")) |
| 305 | } |
| 306 | |
| 307 | // mapEntryName derives the message name for a map field of a given name. |
| 308 | // This is identical to MapEntryName from parser.cc in the protoc source. |
| 309 | func mapEntryName(s pref.Name) pref.Name { |
| 310 | var b []byte |
| 311 | nextUpper := true |
| 312 | for i := 0; i < len(s); i++ { |
| 313 | if c := s[i]; c == '_' { |
| 314 | nextUpper = true |
| 315 | } else { |
| 316 | if nextUpper { |
| 317 | c = byte(unicode.ToUpper(rune(c))) |
| 318 | nextUpper = false |
| 319 | } |
| 320 | b = append(b, c) |
| 321 | } |
| 322 | } |
| 323 | return pref.Name(append(b, "Entry"...)) |
| 324 | } |