Joe Tsai | fa02f4e | 2018-09-12 16:20:37 -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 | |
| 5 | package impl |
| 6 | |
| 7 | import ( |
Joe Tsai | c6b7561 | 2018-09-13 14:24:37 -0700 | [diff] [blame^] | 8 | "fmt" |
Joe Tsai | fa02f4e | 2018-09-12 16:20:37 -0700 | [diff] [blame] | 9 | "reflect" |
| 10 | "strconv" |
| 11 | "strings" |
Joe Tsai | c6b7561 | 2018-09-13 14:24:37 -0700 | [diff] [blame^] | 12 | "sync" |
Joe Tsai | fa02f4e | 2018-09-12 16:20:37 -0700 | [diff] [blame] | 13 | |
Joe Tsai | 01ab296 | 2018-09-21 17:44:00 -0700 | [diff] [blame] | 14 | pref "github.com/golang/protobuf/v2/reflect/protoreflect" |
Joe Tsai | c6b7561 | 2018-09-13 14:24:37 -0700 | [diff] [blame^] | 15 | ptype "github.com/golang/protobuf/v2/reflect/prototype" |
Joe Tsai | fa02f4e | 2018-09-12 16:20:37 -0700 | [diff] [blame] | 16 | ) |
| 17 | |
Joe Tsai | c6b7561 | 2018-09-13 14:24:37 -0700 | [diff] [blame^] | 18 | // MessageType provides protobuf related functionality for a given Go type |
| 19 | // that represents a message. A given instance of MessageType is tied to |
| 20 | // exactly one Go type, which must be a pointer to a struct type. |
| 21 | type MessageType struct { |
| 22 | // Desc is an optionally provided message descriptor. If nil, the descriptor |
| 23 | // is lazily derived from the Go type information of generated messages |
| 24 | // for the v1 API. |
| 25 | // |
| 26 | // Once set, this field must never be mutated. |
| 27 | Desc pref.MessageDescriptor |
| 28 | |
| 29 | once sync.Once // protects all unexported fields |
| 30 | |
| 31 | goType reflect.Type // pointer to struct |
| 32 | pbType pref.MessageType // only valid if goType does not implement proto.Message |
| 33 | |
Joe Tsai | fa02f4e | 2018-09-12 16:20:37 -0700 | [diff] [blame] | 34 | // TODO: Split fields into dense and sparse maps similar to the current |
| 35 | // table-driven implementation in v1? |
| 36 | fields map[pref.FieldNumber]*fieldInfo |
| 37 | } |
| 38 | |
Joe Tsai | c6b7561 | 2018-09-13 14:24:37 -0700 | [diff] [blame^] | 39 | // init lazily initializes the MessageType upon first use and |
| 40 | // also checks that the provided pointer p is of the correct Go type. |
| 41 | // |
| 42 | // It must be called at the start of every exported method. |
| 43 | func (mi *MessageType) init(p interface{}) { |
| 44 | mi.once.Do(func() { |
| 45 | v := reflect.ValueOf(p) |
| 46 | t := v.Type() |
| 47 | if t.Kind() != reflect.Ptr && t.Elem().Kind() != reflect.Struct { |
| 48 | panic(fmt.Sprintf("got %v, want *struct kind", t)) |
| 49 | } |
| 50 | mi.goType = t |
| 51 | |
| 52 | // Derive the message descriptor if unspecified. |
| 53 | md := mi.Desc |
| 54 | if md == nil { |
| 55 | // TODO: derive the message type from the Go struct type |
| 56 | } |
| 57 | |
| 58 | // Initialize the Go message type wrapper if the Go type does not |
| 59 | // implement the proto.Message interface. |
| 60 | // |
| 61 | // Otherwise, we assume that the Go type manually implements the |
| 62 | // interface and is internally consistent such that: |
| 63 | // goType == reflect.New(goType.Elem()).Interface().(proto.Message).ProtoReflect().Type().GoType() |
| 64 | // |
| 65 | // Generated code ensures that this property holds. |
| 66 | if _, ok := p.(pref.ProtoMessage); !ok { |
| 67 | mi.pbType = ptype.NewGoMessage(&ptype.GoMessage{ |
| 68 | MessageDescriptor: md, |
| 69 | New: func(pref.MessageType) pref.ProtoMessage { |
| 70 | p := reflect.New(t.Elem()).Interface() |
| 71 | return (*message)(mi.dataTypeOf(p)) |
| 72 | }, |
| 73 | }) |
| 74 | } |
| 75 | |
| 76 | mi.generateFieldFuncs(t.Elem(), md) |
| 77 | }) |
| 78 | |
| 79 | // TODO: Remove this check? This API is primarily used by generated code, |
| 80 | // and should not violate this assumption. Leave this check in for now to |
| 81 | // provide some sanity checks during development. This can be removed if |
| 82 | // it proves to be detrimental to performance. |
| 83 | if reflect.TypeOf(p) != mi.goType { |
| 84 | panic(fmt.Sprintf("type mismatch: got %T, want %v", p, mi.goType)) |
| 85 | } |
| 86 | } |
| 87 | |
Joe Tsai | fa02f4e | 2018-09-12 16:20:37 -0700 | [diff] [blame] | 88 | // generateFieldFuncs generates per-field functions for all common operations |
| 89 | // to be performed on each field. It takes in a reflect.Type representing the |
| 90 | // Go struct, and a protoreflect.MessageDescriptor to match with the fields |
| 91 | // in the struct. |
| 92 | // |
| 93 | // This code assumes that the struct is well-formed and panics if there are |
| 94 | // any discrepancies. |
Joe Tsai | c6b7561 | 2018-09-13 14:24:37 -0700 | [diff] [blame^] | 95 | func (mi *MessageType) generateFieldFuncs(t reflect.Type, md pref.MessageDescriptor) { |
Joe Tsai | fa02f4e | 2018-09-12 16:20:37 -0700 | [diff] [blame] | 96 | // Generate a mapping of field numbers and names to Go struct field or type. |
| 97 | fields := map[pref.FieldNumber]reflect.StructField{} |
| 98 | oneofs := map[pref.Name]reflect.StructField{} |
| 99 | oneofFields := map[pref.FieldNumber]reflect.Type{} |
| 100 | special := map[string]reflect.StructField{} |
| 101 | fieldLoop: |
| 102 | for i := 0; i < t.NumField(); i++ { |
| 103 | f := t.Field(i) |
| 104 | for _, s := range strings.Split(f.Tag.Get("protobuf"), ",") { |
| 105 | if len(s) > 0 && strings.Trim(s, "0123456789") == "" { |
| 106 | n, _ := strconv.ParseUint(s, 10, 64) |
| 107 | fields[pref.FieldNumber(n)] = f |
| 108 | continue fieldLoop |
| 109 | } |
| 110 | } |
| 111 | if s := f.Tag.Get("protobuf_oneof"); len(s) > 0 { |
| 112 | oneofs[pref.Name(s)] = f |
| 113 | continue fieldLoop |
| 114 | } |
| 115 | switch f.Name { |
| 116 | case "XXX_weak", "XXX_unrecognized", "XXX_sizecache", "XXX_extensions", "XXX_InternalExtensions": |
| 117 | special[f.Name] = f |
| 118 | continue fieldLoop |
| 119 | } |
| 120 | } |
| 121 | if fn, ok := t.MethodByName("XXX_OneofFuncs"); ok { |
| 122 | vs := fn.Func.Call([]reflect.Value{reflect.New(fn.Type.In(0)).Elem()})[3] |
| 123 | oneofLoop: |
| 124 | for _, v := range vs.Interface().([]interface{}) { |
| 125 | tf := reflect.TypeOf(v).Elem() |
| 126 | f := tf.Field(0) |
| 127 | for _, s := range strings.Split(f.Tag.Get("protobuf"), ",") { |
| 128 | if len(s) > 0 && strings.Trim(s, "0123456789") == "" { |
| 129 | n, _ := strconv.ParseUint(s, 10, 64) |
| 130 | oneofFields[pref.FieldNumber(n)] = tf |
| 131 | continue oneofLoop |
| 132 | } |
| 133 | } |
| 134 | } |
| 135 | } |
| 136 | |
| 137 | mi.fields = map[pref.FieldNumber]*fieldInfo{} |
| 138 | for i := 0; i < md.Fields().Len(); i++ { |
| 139 | fd := md.Fields().Get(i) |
| 140 | fs := fields[fd.Number()] |
| 141 | var fi fieldInfo |
| 142 | switch { |
| 143 | case fd.IsWeak(): |
| 144 | fi = fieldInfoForWeak(fd, special["XXX_weak"]) |
| 145 | case fd.OneofType() != nil: |
| 146 | fi = fieldInfoForOneof(fd, oneofs[fd.OneofType().Name()], oneofFields[fd.Number()]) |
| 147 | case fd.IsMap(): |
| 148 | fi = fieldInfoForMap(fd, fs) |
| 149 | case fd.Cardinality() == pref.Repeated: |
| 150 | fi = fieldInfoForVector(fd, fs) |
Joe Tsai | c6b7561 | 2018-09-13 14:24:37 -0700 | [diff] [blame^] | 151 | case fd.Kind() == pref.MessageKind || fd.Kind() == pref.GroupKind: |
Joe Tsai | fa02f4e | 2018-09-12 16:20:37 -0700 | [diff] [blame] | 152 | fi = fieldInfoForMessage(fd, fs) |
Joe Tsai | c6b7561 | 2018-09-13 14:24:37 -0700 | [diff] [blame^] | 153 | default: |
| 154 | fi = fieldInfoForScalar(fd, fs) |
Joe Tsai | fa02f4e | 2018-09-12 16:20:37 -0700 | [diff] [blame] | 155 | } |
| 156 | mi.fields[fd.Number()] = &fi |
| 157 | } |
| 158 | } |
Joe Tsai | c6b7561 | 2018-09-13 14:24:37 -0700 | [diff] [blame^] | 159 | |
| 160 | func (mi *MessageType) MessageOf(p interface{}) pref.Message { |
| 161 | mi.init(p) |
| 162 | if m, ok := p.(pref.ProtoMessage); ok { |
| 163 | // We assume p properly implements protoreflect.Message. |
| 164 | // See the comment in MessageType.init regarding pbType. |
| 165 | return m.ProtoReflect() |
| 166 | } |
| 167 | return (*message)(mi.dataTypeOf(p)) |
| 168 | } |
| 169 | |
| 170 | func (mi *MessageType) KnownFieldsOf(p interface{}) pref.KnownFields { |
| 171 | mi.init(p) |
| 172 | return (*knownFields)(mi.dataTypeOf(p)) |
| 173 | } |
| 174 | |
| 175 | func (mi *MessageType) UnknownFieldsOf(p interface{}) pref.UnknownFields { |
| 176 | mi.init(p) |
| 177 | return (*unknownFields)(mi.dataTypeOf(p)) |
| 178 | } |
| 179 | |
| 180 | func (mi *MessageType) dataTypeOf(p interface{}) *messageDataType { |
| 181 | return &messageDataType{pointerOfIface(&p), mi} |
| 182 | } |
| 183 | |
| 184 | // messageDataType is a tuple of a pointer to the message data and |
| 185 | // a pointer to the message type. |
| 186 | // |
| 187 | // TODO: Unfortunately, we need to close over a pointer and MessageType, |
| 188 | // which incurs an an allocation. This pair is similar to a Go interface, |
| 189 | // which is essentially a tuple of the same thing. We can make this efficient |
| 190 | // with reflect.NamedOf (see https://golang.org/issues/16522). |
| 191 | // |
| 192 | // With that hypothetical API, we could dynamically create a new named type |
| 193 | // that has the same underlying type as MessageType.goType, and |
| 194 | // dynamically create methods that close over MessageType. |
| 195 | // Since the new type would have the same underlying type, we could directly |
| 196 | // convert between pointers of those types, giving us an efficient way to swap |
| 197 | // out the method set. |
| 198 | // |
| 199 | // Barring the ability to dynamically create named types, the workaround is |
| 200 | // 1. either to accept the cost of an allocation for this wrapper struct or |
| 201 | // 2. generate more types and methods, at the expense of binary size increase. |
| 202 | type messageDataType struct { |
| 203 | p pointer |
| 204 | mi *MessageType |
| 205 | } |
| 206 | |
| 207 | type message messageDataType |
| 208 | |
| 209 | func (m *message) Type() pref.MessageType { |
| 210 | return m.mi.pbType |
| 211 | } |
| 212 | func (m *message) KnownFields() pref.KnownFields { |
| 213 | return (*knownFields)(m) |
| 214 | } |
| 215 | func (m *message) UnknownFields() pref.UnknownFields { |
| 216 | return (*unknownFields)(m) |
| 217 | } |
| 218 | func (m *message) Unwrap() interface{} { |
| 219 | return m.p.asType(m.mi.goType.Elem()).Interface() |
| 220 | } |
| 221 | func (m *message) Interface() pref.ProtoMessage { |
| 222 | return m |
| 223 | } |
| 224 | func (m *message) ProtoReflect() pref.Message { |
| 225 | return m |
| 226 | } |
| 227 | func (m *message) ProtoMutable() {} |
| 228 | |
| 229 | type knownFields messageDataType |
| 230 | |
| 231 | func (fs *knownFields) List() (nums []pref.FieldNumber) { |
| 232 | for n, fi := range fs.mi.fields { |
| 233 | if fi.has(fs.p) { |
| 234 | nums = append(nums, n) |
| 235 | } |
| 236 | } |
| 237 | // TODO: Handle extension fields. |
| 238 | return nums |
| 239 | } |
| 240 | func (fs *knownFields) Len() (cnt int) { |
| 241 | for _, fi := range fs.mi.fields { |
| 242 | if fi.has(fs.p) { |
| 243 | cnt++ |
| 244 | } |
| 245 | } |
| 246 | // TODO: Handle extension fields. |
| 247 | return cnt |
| 248 | } |
| 249 | func (fs *knownFields) Has(n pref.FieldNumber) bool { |
| 250 | if fi := fs.mi.fields[n]; fi != nil { |
| 251 | return fi.has(fs.p) |
| 252 | } |
| 253 | // TODO: Handle extension fields. |
| 254 | return false |
| 255 | } |
| 256 | func (fs *knownFields) Get(n pref.FieldNumber) pref.Value { |
| 257 | if fi := fs.mi.fields[n]; fi != nil { |
| 258 | return fi.get(fs.p) |
| 259 | } |
| 260 | // TODO: Handle extension fields. |
| 261 | return pref.Value{} |
| 262 | } |
| 263 | func (fs *knownFields) Set(n pref.FieldNumber, v pref.Value) { |
| 264 | if fi := fs.mi.fields[n]; fi != nil { |
| 265 | fi.set(fs.p, v) |
| 266 | return |
| 267 | } |
| 268 | // TODO: Handle extension fields. |
| 269 | panic("invalid field") |
| 270 | } |
| 271 | func (fs *knownFields) Clear(n pref.FieldNumber) { |
| 272 | if fi := fs.mi.fields[n]; fi != nil { |
| 273 | fi.clear(fs.p) |
| 274 | return |
| 275 | } |
| 276 | // TODO: Handle extension fields. |
| 277 | panic("invalid field") |
| 278 | } |
| 279 | func (fs *knownFields) Mutable(n pref.FieldNumber) pref.Mutable { |
| 280 | if fi := fs.mi.fields[n]; fi != nil { |
| 281 | return fi.mutable(fs.p) |
| 282 | } |
| 283 | // TODO: Handle extension fields. |
| 284 | panic("invalid field") |
| 285 | } |
| 286 | func (fs *knownFields) Range(f func(pref.FieldNumber, pref.Value) bool) { |
| 287 | for n, fi := range fs.mi.fields { |
| 288 | if fi.has(fs.p) { |
| 289 | if !f(n, fi.get(fs.p)) { |
| 290 | return |
| 291 | } |
| 292 | } |
| 293 | } |
| 294 | // TODO: Handle extension fields. |
| 295 | } |
| 296 | func (fs *knownFields) ExtensionTypes() pref.ExtensionFieldTypes { |
| 297 | return (*extensionFieldTypes)(fs) |
| 298 | } |
| 299 | |
| 300 | type extensionFieldTypes messageDataType // TODO |
| 301 | |
| 302 | func (fs *extensionFieldTypes) List() []pref.ExtensionType { return nil } |
| 303 | func (fs *extensionFieldTypes) Len() int { return 0 } |
| 304 | func (fs *extensionFieldTypes) Register(pref.ExtensionType) { return } |
| 305 | func (fs *extensionFieldTypes) Remove(pref.ExtensionType) { return } |
| 306 | func (fs *extensionFieldTypes) ByNumber(pref.FieldNumber) pref.ExtensionType { return nil } |
| 307 | func (fs *extensionFieldTypes) ByName(pref.FullName) pref.ExtensionType { return nil } |
| 308 | func (fs *extensionFieldTypes) Range(f func(pref.ExtensionType) bool) { return } |
| 309 | |
| 310 | type unknownFields messageDataType // TODO |
| 311 | |
| 312 | func (fs *unknownFields) List() []pref.FieldNumber { return nil } |
| 313 | func (fs *unknownFields) Len() int { return 0 } |
| 314 | func (fs *unknownFields) Get(n pref.FieldNumber) pref.RawFields { return nil } |
| 315 | func (fs *unknownFields) Set(n pref.FieldNumber, b pref.RawFields) { return } |
| 316 | func (fs *unknownFields) Range(f func(pref.FieldNumber, pref.RawFields) bool) { return } |
| 317 | func (fs *unknownFields) IsSupported() bool { return false } |