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 | 21ade49 | 2019-05-22 13:42:54 -0400 | [diff] [blame] | 5 | package impl |
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 | 851185d | 2019-07-01 13:45:52 -0700 | [diff] [blame^] | 10 | "strings" |
Joe Tsai | 90fe996 | 2018-10-18 11:06:29 -0700 | [diff] [blame] | 11 | "sync" |
Joe Tsai | 851185d | 2019-07-01 13:45:52 -0700 | [diff] [blame^] | 12 | "unicode" |
Joe Tsai | 90fe996 | 2018-10-18 11:06:29 -0700 | [diff] [blame] | 13 | |
Joe Tsai | 851185d | 2019-07-01 13:45:52 -0700 | [diff] [blame^] | 14 | "google.golang.org/protobuf/internal/descopts" |
| 15 | ptag "google.golang.org/protobuf/internal/encoding/tag" |
| 16 | "google.golang.org/protobuf/internal/filedesc" |
Joe Tsai | d888139 | 2019-06-06 13:01:53 -0700 | [diff] [blame] | 17 | "google.golang.org/protobuf/reflect/protoreflect" |
Damien Neil | e89e624 | 2019-05-13 23:55:40 -0700 | [diff] [blame] | 18 | pref "google.golang.org/protobuf/reflect/protoreflect" |
Joe Tsai | b2f66be | 2019-05-22 00:42:45 -0400 | [diff] [blame] | 19 | "google.golang.org/protobuf/reflect/prototype" |
Joe Tsai | 90fe996 | 2018-10-18 11:06:29 -0700 | [diff] [blame] | 20 | ) |
| 21 | |
Joe Tsai | 21ade49 | 2019-05-22 13:42:54 -0400 | [diff] [blame] | 22 | // legacyWrapMessage wraps v as a protoreflect.ProtoMessage, |
Joe Tsai | f0c01e4 | 2018-11-06 13:05:20 -0800 | [diff] [blame] | 23 | // where v must be a *struct kind and not implement the v2 API already. |
Joe Tsai | 21ade49 | 2019-05-22 13:42:54 -0400 | [diff] [blame] | 24 | func legacyWrapMessage(v reflect.Value) pref.ProtoMessage { |
| 25 | mt := legacyLoadMessageInfo(v.Type()) |
Joe Tsai | 08e0030 | 2018-11-26 22:32:06 -0800 | [diff] [blame] | 26 | return mt.MessageOf(v.Interface()).Interface() |
Joe Tsai | f0c01e4 | 2018-11-06 13:05:20 -0800 | [diff] [blame] | 27 | } |
| 28 | |
Joe Tsai | 21ade49 | 2019-05-22 13:42:54 -0400 | [diff] [blame] | 29 | var legacyMessageTypeCache sync.Map // map[reflect.Type]*MessageInfo |
Joe Tsai | ce6edd3 | 2018-10-19 16:27:46 -0700 | [diff] [blame] | 30 | |
Joe Tsai | 21ade49 | 2019-05-22 13:42:54 -0400 | [diff] [blame] | 31 | // legacyLoadMessageInfo dynamically loads a *MessageInfo for t, |
Joe Tsai | f0c01e4 | 2018-11-06 13:05:20 -0800 | [diff] [blame] | 32 | // where t must be a *struct kind and not implement the v2 API already. |
Joe Tsai | 21ade49 | 2019-05-22 13:42:54 -0400 | [diff] [blame] | 33 | func legacyLoadMessageInfo(t reflect.Type) *MessageInfo { |
Joe Tsai | 4fe9663 | 2019-05-22 05:12:36 -0400 | [diff] [blame] | 34 | // Fast-path: check if a MessageInfo is cached for this concrete type. |
Joe Tsai | 21ade49 | 2019-05-22 13:42:54 -0400 | [diff] [blame] | 35 | if mt, ok := legacyMessageTypeCache.Load(t); ok { |
| 36 | return mt.(*MessageInfo) |
Joe Tsai | ce6edd3 | 2018-10-19 16:27:46 -0700 | [diff] [blame] | 37 | } |
| 38 | |
Joe Tsai | 4fe9663 | 2019-05-22 05:12:36 -0400 | [diff] [blame] | 39 | // Slow-path: derive message descriptor and initialize MessageInfo. |
Joe Tsai | 21ade49 | 2019-05-22 13:42:54 -0400 | [diff] [blame] | 40 | md := LegacyLoadMessageDesc(t) |
| 41 | mt := new(MessageInfo) |
Damien Neil | 8012b44 | 2019-01-18 09:32:24 -0800 | [diff] [blame] | 42 | mt.GoType = t |
Joe Tsai | b2f66be | 2019-05-22 00:42:45 -0400 | [diff] [blame] | 43 | mt.PBType = &prototype.Message{ |
| 44 | MessageDescriptor: md, |
| 45 | NewMessage: func() pref.Message { |
| 46 | return mt.MessageOf(reflect.New(t.Elem()).Interface()) |
| 47 | }, |
| 48 | } |
Joe Tsai | 21ade49 | 2019-05-22 13:42:54 -0400 | [diff] [blame] | 49 | if mt, ok := legacyMessageTypeCache.LoadOrStore(t, mt); ok { |
| 50 | return mt.(*MessageInfo) |
Joe Tsai | b936504 | 2019-03-19 14:14:29 -0700 | [diff] [blame] | 51 | } |
Joe Tsai | f0c01e4 | 2018-11-06 13:05:20 -0800 | [diff] [blame] | 52 | return mt |
Joe Tsai | ce6edd3 | 2018-10-19 16:27:46 -0700 | [diff] [blame] | 53 | } |
| 54 | |
Joe Tsai | d888139 | 2019-06-06 13:01:53 -0700 | [diff] [blame] | 55 | var legacyMessageDescCache sync.Map // map[reflect.Type]protoreflect.MessageDescriptor |
Joe Tsai | 90fe996 | 2018-10-18 11:06:29 -0700 | [diff] [blame] | 56 | |
Joe Tsai | 21ade49 | 2019-05-22 13:42:54 -0400 | [diff] [blame] | 57 | // LegacyLoadMessageDesc 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. |
Joe Tsai | 21ade49 | 2019-05-22 13:42:54 -0400 | [diff] [blame] | 61 | func LegacyLoadMessageDesc(t reflect.Type) pref.MessageDescriptor { |
Joe Tsai | 851185d | 2019-07-01 13:45:52 -0700 | [diff] [blame^] | 62 | return legacyLoadMessageDesc(t, true) |
| 63 | } |
| 64 | func legacyLoadMessageDesc(t reflect.Type, finalized bool) pref.MessageDescriptor { |
Joe Tsai | 90fe996 | 2018-10-18 11:06:29 -0700 | [diff] [blame] | 65 | // Fast-path: check if a MessageDescriptor is cached for this concrete type. |
Joe Tsai | 21ade49 | 2019-05-22 13:42:54 -0400 | [diff] [blame] | 66 | if mi, ok := legacyMessageDescCache.Load(t); ok { |
Joe Tsai | 90fe996 | 2018-10-18 11:06:29 -0700 | [diff] [blame] | 67 | return mi.(pref.MessageDescriptor) |
| 68 | } |
| 69 | |
Joe Tsai | d888139 | 2019-06-06 13:01:53 -0700 | [diff] [blame] | 70 | // Slow-path: initialize MessageDescriptor from the raw descriptor. |
Joe Tsai | 90fe996 | 2018-10-18 11:06:29 -0700 | [diff] [blame] | 71 | mv := reflect.New(t.Elem()).Interface() |
| 72 | if _, ok := mv.(pref.ProtoMessage); ok { |
| 73 | panic(fmt.Sprintf("%v already implements proto.Message", t)) |
| 74 | } |
Joe Tsai | d888139 | 2019-06-06 13:01:53 -0700 | [diff] [blame] | 75 | mdV1, ok := mv.(messageV1) |
| 76 | if !ok { |
Joe Tsai | 851185d | 2019-07-01 13:45:52 -0700 | [diff] [blame^] | 77 | return aberrantLoadMessageDesc(t, finalized) |
Joe Tsai | d888139 | 2019-06-06 13:01:53 -0700 | [diff] [blame] | 78 | } |
| 79 | b, idxs := mdV1.Descriptor() |
Joe Tsai | 90fe996 | 2018-10-18 11:06:29 -0700 | [diff] [blame] | 80 | |
Joe Tsai | d888139 | 2019-06-06 13:01:53 -0700 | [diff] [blame] | 81 | md := legacyLoadFileDesc(b).Messages().Get(idxs[0]) |
| 82 | for _, i := range idxs[1:] { |
| 83 | md = md.Messages().Get(i) |
Joe Tsai | 90fe996 | 2018-10-18 11:06:29 -0700 | [diff] [blame] | 84 | } |
Joe Tsai | d888139 | 2019-06-06 13:01:53 -0700 | [diff] [blame] | 85 | if md, ok := legacyMessageDescCache.LoadOrStore(t, md); ok { |
| 86 | return md.(protoreflect.MessageDescriptor) |
Joe Tsai | 90fe996 | 2018-10-18 11:06:29 -0700 | [diff] [blame] | 87 | } |
Joe Tsai | d888139 | 2019-06-06 13:01:53 -0700 | [diff] [blame] | 88 | return md |
Joe Tsai | 90fe996 | 2018-10-18 11:06:29 -0700 | [diff] [blame] | 89 | } |
Joe Tsai | 851185d | 2019-07-01 13:45:52 -0700 | [diff] [blame^] | 90 | |
| 91 | var aberrantMessageDescCache sync.Map // map[reflect.Type]aberrantMessageDesc |
| 92 | |
| 93 | // aberrantMessageDesc is a tuple containing a MessageDescriptor and a channel |
| 94 | // to signal whether the descriptor is initialized. For external lookups, |
| 95 | // we must ensure that the descriptor is fully initialized. For internal lookups |
| 96 | // to resolve cycles, we only need to obtain the descriptor reference. |
| 97 | type aberrantMessageDesc struct { |
| 98 | desc protoreflect.MessageDescriptor |
| 99 | done chan struct{} // closed when desc is fully initialized |
| 100 | } |
| 101 | |
| 102 | // aberrantLoadEnumDesc returns an EnumDescriptor derived from the Go type, |
| 103 | // which must not implement protoreflect.ProtoMessage or messageV1. |
| 104 | // |
| 105 | // This is a best-effort derivation of the message descriptor using the protobuf |
| 106 | // tags on the struct fields. |
| 107 | // |
| 108 | // The finalized flag determines whether the returned message descriptor must |
| 109 | // be fully initialized. |
| 110 | func aberrantLoadMessageDesc(t reflect.Type, finalized bool) pref.MessageDescriptor { |
| 111 | // Fast-path: check if an MessageDescriptor is cached for this concrete type. |
| 112 | if mdi, ok := aberrantMessageDescCache.Load(t); ok { |
| 113 | if finalized { |
| 114 | <-mdi.(aberrantMessageDesc).done |
| 115 | } |
| 116 | return mdi.(aberrantMessageDesc).desc |
| 117 | } |
| 118 | |
| 119 | // Medium-path: create an initial descriptor and cache it immediately, |
| 120 | // so that cyclic references can be resolved. Each descriptor is paired |
| 121 | // with a channel to signal when the descriptor is fully initialized. |
| 122 | md := &filedesc.Message{L2: new(filedesc.MessageL2)} |
| 123 | mdi := aberrantMessageDesc{desc: md, done: make(chan struct{})} |
| 124 | if mdi, ok := aberrantMessageDescCache.LoadOrStore(t, mdi); ok { |
| 125 | if finalized { |
| 126 | <-mdi.(aberrantMessageDesc).done |
| 127 | } |
| 128 | return mdi.(aberrantMessageDesc).desc |
| 129 | } |
| 130 | defer func() { close(mdi.done) }() |
| 131 | |
| 132 | // Slow-path: construct a descriptor from the Go struct type (best-effort). |
| 133 | md.L0.FullName = aberrantDeriveFullName(t.Elem()) |
| 134 | md.L0.ParentFile = filedesc.SurrogateProto2 |
| 135 | |
| 136 | // If possible, use the custom protobuf name specified on the type. |
| 137 | fn, ok := t.MethodByName("XXX_MessageName") |
| 138 | if !ok { |
| 139 | fn, ok = t.Elem().MethodByName("XXX_MessageName") |
| 140 | } |
| 141 | if ok { |
| 142 | v := fn.Func.Call([]reflect.Value{reflect.Zero(fn.Type.In(0))})[0] |
| 143 | if s := pref.FullName(v.String()); s.IsValid() { |
| 144 | md.L0.FullName = s |
| 145 | } |
| 146 | } |
| 147 | |
| 148 | // Try to determine if the message is using proto3 by checking scalars. |
| 149 | for i := 0; i < t.Elem().NumField(); i++ { |
| 150 | f := t.Elem().Field(i) |
| 151 | if tag := f.Tag.Get("protobuf"); tag != "" { |
| 152 | switch f.Type.Kind() { |
| 153 | case reflect.Bool, reflect.Int32, reflect.Int64, reflect.Uint32, reflect.Uint64, reflect.Float32, reflect.Float64, reflect.String: |
| 154 | md.L0.ParentFile = filedesc.SurrogateProto3 |
| 155 | } |
| 156 | for _, s := range strings.Split(tag, ",") { |
| 157 | if s == "proto3" { |
| 158 | md.L0.ParentFile = filedesc.SurrogateProto3 |
| 159 | } |
| 160 | } |
| 161 | } |
| 162 | } |
| 163 | |
| 164 | // Obtain a list of oneof wrapper types. |
| 165 | var oneofWrappers []reflect.Type |
| 166 | if fn, ok := t.MethodByName("XXX_OneofFuncs"); ok { |
| 167 | vs := fn.Func.Call([]reflect.Value{reflect.Zero(fn.Type.In(0))})[3] |
| 168 | for _, v := range vs.Interface().([]interface{}) { |
| 169 | oneofWrappers = append(oneofWrappers, reflect.TypeOf(v)) |
| 170 | } |
| 171 | } |
| 172 | if fn, ok := t.MethodByName("XXX_OneofWrappers"); ok { |
| 173 | vs := fn.Func.Call([]reflect.Value{reflect.Zero(fn.Type.In(0))})[0] |
| 174 | for _, v := range vs.Interface().([]interface{}) { |
| 175 | oneofWrappers = append(oneofWrappers, reflect.TypeOf(v)) |
| 176 | } |
| 177 | } |
| 178 | |
| 179 | // Obtain a list of the extension ranges. |
| 180 | if fn, ok := t.MethodByName("ExtensionRangeArray"); ok { |
| 181 | vs := fn.Func.Call([]reflect.Value{reflect.Zero(fn.Type.In(0))})[0] |
| 182 | for i := 0; i < vs.Len(); i++ { |
| 183 | v := vs.Index(i) |
| 184 | md.L2.ExtensionRanges.List = append(md.L2.ExtensionRanges.List, [2]pref.FieldNumber{ |
| 185 | pref.FieldNumber(v.FieldByName("Start").Int()), |
| 186 | pref.FieldNumber(v.FieldByName("End").Int() + 1), |
| 187 | }) |
| 188 | md.L2.ExtensionRangeOptions = append(md.L2.ExtensionRangeOptions, nil) |
| 189 | } |
| 190 | } |
| 191 | |
| 192 | // Derive the message fields by inspecting the struct fields. |
| 193 | for i := 0; i < t.Elem().NumField(); i++ { |
| 194 | f := t.Elem().Field(i) |
| 195 | if tag := f.Tag.Get("protobuf"); tag != "" { |
| 196 | tagKey := f.Tag.Get("protobuf_key") |
| 197 | tagVal := f.Tag.Get("protobuf_val") |
| 198 | aberrantAppendField(md, f.Type, tag, tagKey, tagVal) |
| 199 | } |
| 200 | if tag := f.Tag.Get("protobuf_oneof"); tag != "" { |
| 201 | n := len(md.L2.Oneofs.List) |
| 202 | md.L2.Oneofs.List = append(md.L2.Oneofs.List, filedesc.Oneof{}) |
| 203 | od := &md.L2.Oneofs.List[n] |
| 204 | od.L0.FullName = md.FullName().Append(pref.Name(tag)) |
| 205 | od.L0.ParentFile = md.L0.ParentFile |
| 206 | od.L0.Parent = md |
| 207 | od.L0.Index = n |
| 208 | |
| 209 | for _, t := range oneofWrappers { |
| 210 | if t.Implements(f.Type) { |
| 211 | f := t.Elem().Field(0) |
| 212 | if tag := f.Tag.Get("protobuf"); tag != "" { |
| 213 | aberrantAppendField(md, f.Type, tag, "", "") |
| 214 | fd := &md.L2.Fields.List[len(md.L2.Fields.List)-1] |
| 215 | fd.L1.ContainingOneof = od |
| 216 | od.L1.Fields.List = append(od.L1.Fields.List, fd) |
| 217 | } |
| 218 | } |
| 219 | } |
| 220 | } |
| 221 | } |
| 222 | |
| 223 | // TODO: Use custom Marshal/Unmarshal methods for the fast-path? |
| 224 | |
| 225 | return md |
| 226 | } |
| 227 | |
| 228 | func aberrantAppendField(md *filedesc.Message, goType reflect.Type, tag, tagKey, tagVal string) { |
| 229 | t := goType |
| 230 | isOptional := t.Kind() == reflect.Ptr && t.Elem().Kind() != reflect.Struct |
| 231 | isRepeated := t.Kind() == reflect.Slice && t.Elem().Kind() != reflect.Uint8 |
| 232 | if isOptional || isRepeated { |
| 233 | t = t.Elem() |
| 234 | } |
| 235 | fd := ptag.Unmarshal(tag, t, placeholderEnumValues{}).(*filedesc.Field) |
| 236 | |
| 237 | // Append field descriptor to the message. |
| 238 | n := len(md.L2.Fields.List) |
| 239 | md.L2.Fields.List = append(md.L2.Fields.List, *fd) |
| 240 | fd = &md.L2.Fields.List[n] |
| 241 | fd.L0.FullName = md.FullName().Append(fd.Name()) |
| 242 | fd.L0.ParentFile = md.L0.ParentFile |
| 243 | fd.L0.Parent = md |
| 244 | fd.L0.Index = n |
| 245 | |
| 246 | if fd.L1.IsWeak || fd.L1.HasPacked { |
| 247 | fd.L1.Options = func() pref.ProtoMessage { |
| 248 | opts := descopts.Field.ProtoReflect().New() |
| 249 | if fd.L1.IsWeak { |
| 250 | opts.Set(opts.Descriptor().Fields().ByName("weak"), protoreflect.ValueOf(true)) |
| 251 | } |
| 252 | if fd.L1.HasPacked { |
| 253 | opts.Set(opts.Descriptor().Fields().ByName("packed"), protoreflect.ValueOf(fd.L1.IsPacked)) |
| 254 | } |
| 255 | return opts.Interface() |
| 256 | } |
| 257 | } |
| 258 | |
| 259 | // Populate Enum and Message. |
| 260 | if fd.Enum() == nil && fd.Kind() == pref.EnumKind { |
| 261 | switch v := reflect.Zero(t).Interface().(type) { |
| 262 | case pref.Enum: |
| 263 | fd.L1.Enum = v.Descriptor() |
| 264 | default: |
| 265 | fd.L1.Enum = LegacyLoadEnumDesc(t) |
| 266 | } |
| 267 | } |
| 268 | if fd.Message() == nil && (fd.Kind() == pref.MessageKind || fd.Kind() == pref.GroupKind) { |
| 269 | switch v := reflect.Zero(t).Interface().(type) { |
| 270 | case pref.ProtoMessage: |
| 271 | fd.L1.Message = v.ProtoReflect().Descriptor() |
| 272 | default: |
| 273 | if t.Kind() == reflect.Map { |
| 274 | n := len(md.L1.Messages.List) |
| 275 | md.L1.Messages.List = append(md.L1.Messages.List, filedesc.Message{L2: new(filedesc.MessageL2)}) |
| 276 | md2 := &md.L1.Messages.List[n] |
| 277 | md2.L0.FullName = md.FullName().Append(aberrantMapEntryName(fd.Name())) |
| 278 | md2.L0.ParentFile = md.L0.ParentFile |
| 279 | md2.L0.Parent = md |
| 280 | md2.L0.Index = n |
| 281 | |
| 282 | md2.L2.IsMapEntry = true |
| 283 | md2.L2.Options = func() pref.ProtoMessage { |
| 284 | opts := descopts.Message.ProtoReflect().New() |
| 285 | opts.Set(opts.Descriptor().Fields().ByName("map_entry"), protoreflect.ValueOf(true)) |
| 286 | return opts.Interface() |
| 287 | } |
| 288 | |
| 289 | aberrantAppendField(md2, t.Key(), tagKey, "", "") |
| 290 | aberrantAppendField(md2, t.Elem(), tagVal, "", "") |
| 291 | |
| 292 | fd.L1.Message = md2 |
| 293 | break |
| 294 | } |
| 295 | fd.L1.Message = aberrantLoadMessageDesc(t, false) |
| 296 | } |
| 297 | } |
| 298 | } |
| 299 | |
| 300 | type placeholderEnumValues struct { |
| 301 | protoreflect.EnumValueDescriptors |
| 302 | } |
| 303 | |
| 304 | func (placeholderEnumValues) ByNumber(n pref.EnumNumber) pref.EnumValueDescriptor { |
| 305 | return filedesc.PlaceholderEnumValue(pref.FullName(fmt.Sprintf("UNKNOWN_%d", n))) |
| 306 | } |
| 307 | |
| 308 | // aberrantMapEntryName derives the name for a map entry message. |
| 309 | // See protoc v3.8.0: src/google/protobuf/descriptor.cc:254-276,6057 |
| 310 | func aberrantMapEntryName(s pref.Name) pref.Name { |
| 311 | var b []byte |
| 312 | upperNext := true |
| 313 | for _, c := range s { |
| 314 | switch { |
| 315 | case c == '_': |
| 316 | upperNext = true |
| 317 | case upperNext: |
| 318 | b = append(b, byte(unicode.ToUpper(c))) |
| 319 | upperNext = false |
| 320 | default: |
| 321 | b = append(b, byte(c)) |
| 322 | } |
| 323 | } |
| 324 | b = append(b, "Entry"...) |
| 325 | return pref.Name(b) |
| 326 | } |