blob: ae2015a80b369a215685c0bad64c04b3f772d6b0 [file] [log] [blame]
Herbie Ong800c9902018-12-06 15:28:53 -08001// 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
5package textpb
6
7import (
8 "fmt"
Herbie Ong0dcfb9a2019-01-14 15:32:26 -08009 "strings"
Herbie Ong800c9902018-12-06 15:28:53 -080010
11 "github.com/golang/protobuf/v2/internal/encoding/text"
12 "github.com/golang/protobuf/v2/internal/errors"
Herbie Onge1e34932019-03-29 01:05:57 -070013 "github.com/golang/protobuf/v2/internal/fieldnum"
Herbie Ong800c9902018-12-06 15:28:53 -080014 "github.com/golang/protobuf/v2/internal/pragma"
15 "github.com/golang/protobuf/v2/internal/set"
16 "github.com/golang/protobuf/v2/proto"
17 pref "github.com/golang/protobuf/v2/reflect/protoreflect"
Herbie Ongc525c972018-12-18 18:04:31 -080018 "github.com/golang/protobuf/v2/reflect/protoregistry"
Herbie Ong800c9902018-12-06 15:28:53 -080019)
20
21// Unmarshal reads the given []byte into the given proto.Message.
Herbie Ong800c9902018-12-06 15:28:53 -080022func Unmarshal(m proto.Message, b []byte) error {
23 return UnmarshalOptions{}.Unmarshal(m, b)
24}
25
Herbie Ong42577ea2019-03-26 16:26:22 -070026// UnmarshalOptions is a configurable textproto format unmarshaler.
Herbie Ong800c9902018-12-06 15:28:53 -080027type UnmarshalOptions struct {
28 pragma.NoUnkeyedLiterals
Herbie Ongc525c972018-12-18 18:04:31 -080029
Herbie Ong42577ea2019-03-26 16:26:22 -070030 // AllowPartial accepts input for messages that will result in missing
31 // required fields. If AllowPartial is false (the default), Unmarshal will
32 // return error if there are any missing required fields.
33 AllowPartial bool
34
Herbie Ongc525c972018-12-18 18:04:31 -080035 // Resolver is the registry used for type lookups when unmarshaling extensions
36 // and processing Any. If Resolver is not set, unmarshaling will default to
37 // using protoregistry.GlobalTypes.
38 Resolver *protoregistry.Types
Herbie Ong800c9902018-12-06 15:28:53 -080039}
40
41// Unmarshal reads the given []byte and populates the given proto.Message using options in
42// UnmarshalOptions object.
43func (o UnmarshalOptions) Unmarshal(m proto.Message, b []byte) error {
44 var nerr errors.NonFatal
45
46 mr := m.ProtoReflect()
47 // Clear all fields before populating it.
48 // TODO: Determine if this needs to be consistent with jsonpb and binary unmarshal where
49 // behavior is to merge values into existing message. If decision is to not clear the fields
50 // ahead, code will need to be updated properly when merging nested messages.
51 resetMessage(mr)
52
53 // Parse into text.Value of message type.
54 val, err := text.Unmarshal(b)
55 if !nerr.Merge(err) {
56 return err
57 }
58
Herbie Ongc525c972018-12-18 18:04:31 -080059 if o.Resolver == nil {
60 o.Resolver = protoregistry.GlobalTypes
61 }
Herbie Ong800c9902018-12-06 15:28:53 -080062 err = o.unmarshalMessage(val.Message(), mr)
63 if !nerr.Merge(err) {
64 return err
65 }
66
67 return nerr.E
68}
69
70// resetMessage clears all fields of given protoreflect.Message.
71// TODO: This should go into the proto package.
72func resetMessage(m pref.Message) {
73 knownFields := m.KnownFields()
74 knownFields.Range(func(num pref.FieldNumber, _ pref.Value) bool {
75 knownFields.Clear(num)
76 return true
77 })
78 unknownFields := m.UnknownFields()
79 unknownFields.Range(func(num pref.FieldNumber, _ pref.RawFields) bool {
80 unknownFields.Set(num, nil)
81 return true
82 })
Herbie Ong800c9902018-12-06 15:28:53 -080083 extTypes := knownFields.ExtensionTypes()
84 extTypes.Range(func(xt pref.ExtensionType) bool {
85 extTypes.Remove(xt)
86 return true
87 })
88}
89
90// unmarshalMessage unmarshals a [][2]text.Value message into the given protoreflect.Message.
91func (o UnmarshalOptions) unmarshalMessage(tmsg [][2]text.Value, m pref.Message) error {
92 var nerr errors.NonFatal
93
94 msgType := m.Type()
Herbie Ong66c365c2019-01-04 14:08:41 -080095 knownFields := m.KnownFields()
96
97 // Handle expanded Any message.
98 if msgType.FullName() == "google.protobuf.Any" && isExpandedAny(tmsg) {
99 return o.unmarshalAny(tmsg[0], knownFields)
100 }
101
Herbie Ong800c9902018-12-06 15:28:53 -0800102 fieldDescs := msgType.Fields()
Herbie Ong7c624e22018-12-13 14:41:22 -0800103 reservedNames := msgType.ReservedNames()
Herbie Ongc525c972018-12-18 18:04:31 -0800104 xtTypes := knownFields.ExtensionTypes()
Herbie Ong800c9902018-12-06 15:28:53 -0800105 var reqNums set.Ints
106 var seenNums set.Ints
107
108 for _, tfield := range tmsg {
109 tkey := tfield[0]
110 tval := tfield[1]
111
112 var fd pref.FieldDescriptor
Herbie Ongc525c972018-12-18 18:04:31 -0800113 var name pref.Name
114 switch tkey.Type() {
115 case text.Name:
116 name, _ = tkey.Name()
Herbie Ong800c9902018-12-06 15:28:53 -0800117 fd = fieldDescs.ByName(name)
Herbie Ong0dcfb9a2019-01-14 15:32:26 -0800118 if fd == nil {
119 // Check if this is a group field.
120 fd = fieldDescs.ByName(pref.Name(strings.ToLower(string(name))))
121 }
Herbie Ongc525c972018-12-18 18:04:31 -0800122 case text.String:
Herbie Ong66c365c2019-01-04 14:08:41 -0800123 // Handle extensions only. This code path is not for Any.
124 if msgType.FullName() == "google.protobuf.Any" {
125 break
126 }
127 // Extensions have to be registered first in the message's
Herbie Ongc525c972018-12-18 18:04:31 -0800128 // ExtensionTypes before setting a value to it.
129 xtName := pref.FullName(tkey.String())
Herbie Ong66c365c2019-01-04 14:08:41 -0800130 // Check first if it is already registered. This is the case for
131 // repeated fields.
Herbie Ongc525c972018-12-18 18:04:31 -0800132 xt := xtTypes.ByName(xtName)
133 if xt == nil {
134 var err error
Herbie Ong6470ea62019-01-07 18:56:57 -0800135 xt, err = o.findExtension(xtName)
Herbie Ongc525c972018-12-18 18:04:31 -0800136 if err != nil && err != protoregistry.NotFound {
Herbie Ong66c365c2019-01-04 14:08:41 -0800137 return errors.New("unable to resolve [%v]: %v", xtName, err)
Herbie Ongc525c972018-12-18 18:04:31 -0800138 }
139 if xt != nil {
140 xtTypes.Register(xt)
141 }
142 }
143 fd = xt
Herbie Ong800c9902018-12-06 15:28:53 -0800144 }
Herbie Ongc525c972018-12-18 18:04:31 -0800145
Herbie Ong800c9902018-12-06 15:28:53 -0800146 if fd == nil {
Herbie Ong7c624e22018-12-13 14:41:22 -0800147 // Ignore reserved names.
148 if reservedNames.Has(name) {
149 continue
150 }
Herbie Ong800c9902018-12-06 15:28:53 -0800151 // TODO: Can provide option to ignore unknown message fields.
Herbie Ong800c9902018-12-06 15:28:53 -0800152 return errors.New("%v contains unknown field: %v", msgType.FullName(), tkey)
153 }
154
155 if cardinality := fd.Cardinality(); cardinality == pref.Repeated {
156 // Map or list fields have cardinality of repeated.
157 if err := o.unmarshalRepeated(tval, fd, knownFields); !nerr.Merge(err) {
158 return err
159 }
160 } else {
161 // Required or optional fields.
162 num := uint64(fd.Number())
163 if seenNums.Has(num) {
164 return errors.New("non-repeated field %v is repeated", fd.FullName())
165 }
166 if err := o.unmarshalSingular(tval, fd, knownFields); !nerr.Merge(err) {
167 return err
168 }
Herbie Ong42577ea2019-03-26 16:26:22 -0700169 if !o.AllowPartial && cardinality == pref.Required {
Herbie Ong800c9902018-12-06 15:28:53 -0800170 reqNums.Set(num)
171 }
172 seenNums.Set(num)
173 }
174 }
175
Herbie Ong42577ea2019-03-26 16:26:22 -0700176 if !o.AllowPartial {
177 // Check for any missing required fields.
178 allReqNums := msgType.RequiredNumbers()
179 if reqNums.Len() != allReqNums.Len() {
180 for i := 0; i < allReqNums.Len(); i++ {
181 if num := allReqNums.Get(i); !reqNums.Has(uint64(num)) {
182 nerr.AppendRequiredNotSet(string(fieldDescs.ByNumber(num).FullName()))
183 }
Herbie Ong800c9902018-12-06 15:28:53 -0800184 }
185 }
186 }
187
188 return nerr.E
189}
190
Herbie Ong6470ea62019-01-07 18:56:57 -0800191// findExtension returns protoreflect.ExtensionType from the Resolver if found.
192func (o UnmarshalOptions) findExtension(xtName pref.FullName) (pref.ExtensionType, error) {
193 xt, err := o.Resolver.FindExtensionByName(xtName)
194 if err == nil {
195 return xt, nil
196 }
197
198 // Check if this is a MessageSet extension field.
199 xt, err = o.Resolver.FindExtensionByName(xtName + ".message_set_extension")
200 if err == nil && isMessageSetExtension(xt) {
201 return xt, nil
202 }
203 return nil, protoregistry.NotFound
204}
205
Herbie Ong800c9902018-12-06 15:28:53 -0800206// unmarshalSingular unmarshals given text.Value into the non-repeated field.
207func (o UnmarshalOptions) unmarshalSingular(input text.Value, fd pref.FieldDescriptor, knownFields pref.KnownFields) error {
208 num := fd.Number()
209
210 var nerr errors.NonFatal
211 var val pref.Value
212 switch fd.Kind() {
213 case pref.MessageKind, pref.GroupKind:
214 if input.Type() != text.Message {
215 return errors.New("%v contains invalid message/group value: %v", fd.FullName(), input)
216 }
Joe Tsai3bc7d6f2019-01-09 02:57:13 -0800217 m := knownFields.NewMessage(num)
Herbie Ong800c9902018-12-06 15:28:53 -0800218 if err := o.unmarshalMessage(input.Message(), m); !nerr.Merge(err) {
219 return err
220 }
221 val = pref.ValueOf(m)
222 default:
223 var err error
224 val, err = unmarshalScalar(input, fd)
225 if !nerr.Merge(err) {
226 return err
227 }
228 }
229 knownFields.Set(num, val)
230
231 return nerr.E
232}
233
234// unmarshalRepeated unmarshals given text.Value into a repeated field. Caller should only
235// call this for cardinality=repeated.
236func (o UnmarshalOptions) unmarshalRepeated(input text.Value, fd pref.FieldDescriptor, knownFields pref.KnownFields) error {
237 var items []text.Value
238 // If input is not a list, turn it into a list.
239 if input.Type() != text.List {
240 items = []text.Value{input}
241 } else {
242 items = input.List()
243 }
244
245 var nerr errors.NonFatal
246 num := fd.Number()
247 val := knownFields.Get(num)
248 if !fd.IsMap() {
249 if err := o.unmarshalList(items, fd, val.List()); !nerr.Merge(err) {
250 return err
251 }
252 } else {
253 if err := o.unmarshalMap(items, fd, val.Map()); !nerr.Merge(err) {
254 return err
255 }
256 }
257
258 return nerr.E
259}
260
261// unmarshalScalar converts the given text.Value to a scalar/enum protoreflect.Value specified in
262// the given FieldDescriptor. Caller should not pass in a FieldDescriptor for a message/group kind.
263func unmarshalScalar(input text.Value, fd pref.FieldDescriptor) (pref.Value, error) {
264 const b32 = false
265 const b64 = true
266
267 switch kind := fd.Kind(); kind {
268 case pref.BoolKind:
269 if b, ok := input.Bool(); ok {
270 return pref.ValueOf(bool(b)), nil
271 }
272 case pref.Int32Kind, pref.Sint32Kind, pref.Sfixed32Kind:
273 if n, ok := input.Int(b32); ok {
274 return pref.ValueOf(int32(n)), nil
275 }
276 case pref.Int64Kind, pref.Sint64Kind, pref.Sfixed64Kind:
277 if n, ok := input.Int(b64); ok {
278 return pref.ValueOf(int64(n)), nil
279 }
280 case pref.Uint32Kind, pref.Fixed32Kind:
281 if n, ok := input.Uint(b32); ok {
282 return pref.ValueOf(uint32(n)), nil
283 }
284 case pref.Uint64Kind, pref.Fixed64Kind:
285 if n, ok := input.Uint(b64); ok {
286 return pref.ValueOf(uint64(n)), nil
287 }
288 case pref.FloatKind:
Herbie Ong250c6ea2019-03-12 20:55:10 -0700289 if n, ok := input.Float(b32); ok {
Herbie Ong800c9902018-12-06 15:28:53 -0800290 return pref.ValueOf(float32(n)), nil
291 }
292 case pref.DoubleKind:
Herbie Ong250c6ea2019-03-12 20:55:10 -0700293 if n, ok := input.Float(b64); ok {
Herbie Ong800c9902018-12-06 15:28:53 -0800294 return pref.ValueOf(float64(n)), nil
295 }
296 case pref.StringKind:
297 if input.Type() == text.String {
298 return pref.ValueOf(string(input.String())), nil
299 }
300 case pref.BytesKind:
301 if input.Type() == text.String {
302 return pref.ValueOf([]byte(input.String())), nil
303 }
304 case pref.EnumKind:
305 // If input is int32, use directly.
306 if n, ok := input.Int(b32); ok {
307 return pref.ValueOf(pref.EnumNumber(n)), nil
Herbie Ong66c365c2019-01-04 14:08:41 -0800308 }
309 if name, ok := input.Name(); ok {
310 // Lookup EnumNumber based on name.
311 if enumVal := fd.EnumType().Values().ByName(name); enumVal != nil {
312 return pref.ValueOf(enumVal.Number()), nil
Herbie Ong800c9902018-12-06 15:28:53 -0800313 }
314 }
315 default:
316 panic(fmt.Sprintf("invalid scalar kind %v", kind))
317 }
318
319 return pref.Value{}, errors.New("%v contains invalid scalar value: %v", fd.FullName(), input)
320}
321
322// unmarshalList unmarshals given []text.Value into given protoreflect.List.
323func (o UnmarshalOptions) unmarshalList(inputList []text.Value, fd pref.FieldDescriptor, list pref.List) error {
324 var nerr errors.NonFatal
325
326 switch fd.Kind() {
327 case pref.MessageKind, pref.GroupKind:
328 for _, input := range inputList {
329 if input.Type() != text.Message {
330 return errors.New("%v contains invalid message/group value: %v", fd.FullName(), input)
331 }
Joe Tsai3bc7d6f2019-01-09 02:57:13 -0800332 m := list.NewMessage()
Herbie Ong800c9902018-12-06 15:28:53 -0800333 if err := o.unmarshalMessage(input.Message(), m); !nerr.Merge(err) {
334 return err
335 }
336 list.Append(pref.ValueOf(m))
337 }
338 default:
339 for _, input := range inputList {
340 val, err := unmarshalScalar(input, fd)
341 if !nerr.Merge(err) {
342 return err
343 }
344 list.Append(val)
345 }
346 }
347
348 return nerr.E
349}
350
351// unmarshalMap unmarshals given []text.Value into given protoreflect.Map.
352func (o UnmarshalOptions) unmarshalMap(input []text.Value, fd pref.FieldDescriptor, mmap pref.Map) error {
353 var nerr errors.NonFatal
354 fields := fd.MessageType().Fields()
355 keyDesc := fields.ByNumber(1)
356 valDesc := fields.ByNumber(2)
357
358 // Determine ahead whether map entry is a scalar type or a message type in order to call the
359 // appropriate unmarshalMapValue func inside the for loop below.
Herbie Ong66c365c2019-01-04 14:08:41 -0800360 unmarshalMapValue := unmarshalMapScalarValue
Herbie Ong800c9902018-12-06 15:28:53 -0800361 switch valDesc.Kind() {
362 case pref.MessageKind, pref.GroupKind:
363 unmarshalMapValue = o.unmarshalMapMessageValue
364 }
365
366 for _, entry := range input {
367 if entry.Type() != text.Message {
368 return errors.New("%v contains invalid map entry: %v", fd.FullName(), entry)
369 }
370 tkey, tval, err := parseMapEntry(entry.Message(), fd.FullName())
371 if !nerr.Merge(err) {
372 return err
373 }
374 pkey, err := unmarshalMapKey(tkey, keyDesc)
375 if !nerr.Merge(err) {
376 return err
377 }
378 err = unmarshalMapValue(tval, pkey, valDesc, mmap)
379 if !nerr.Merge(err) {
380 return err
381 }
382 }
383
384 return nerr.E
385}
386
387// parseMapEntry parses [][2]text.Value for field names key and value, and return corresponding
388// field values. If there are duplicate field names, the value for the last field is returned. If
389// the field name does not exist, it will return the zero value of text.Value. It will return an
390// error if there are unknown field names.
391func parseMapEntry(mapEntry [][2]text.Value, name pref.FullName) (key text.Value, value text.Value, err error) {
392 for _, field := range mapEntry {
393 keyStr, ok := field[0].Name()
394 if ok {
395 switch keyStr {
396 case "key":
397 if key.Type() != 0 {
398 return key, value, errors.New("%v contains duplicate key field", name)
399 }
400 key = field[1]
401 case "value":
402 if value.Type() != 0 {
403 return key, value, errors.New("%v contains duplicate value field", name)
404 }
405 value = field[1]
406 default:
407 ok = false
408 }
409 }
410 if !ok {
411 // TODO: Do not return error if ignore unknown option is added and enabled.
412 return key, value, errors.New("%v contains unknown map entry name: %v", name, field[0])
413 }
414 }
415 return key, value, nil
416}
417
418// unmarshalMapKey converts given text.Value into a protoreflect.MapKey. A map key type is any
419// integral or string type.
420func unmarshalMapKey(input text.Value, fd pref.FieldDescriptor) (pref.MapKey, error) {
421 // If input is not set, use the zero value.
422 if input.Type() == 0 {
423 return fd.Default().MapKey(), nil
424 }
425
426 val, err := unmarshalScalar(input, fd)
427 if err != nil {
428 return pref.MapKey{}, errors.New("%v contains invalid key: %v", fd.FullName(), input)
429 }
430 return val.MapKey(), nil
431}
432
433// unmarshalMapMessageValue unmarshals given message-type text.Value into a protoreflect.Map for
434// the given MapKey.
435func (o UnmarshalOptions) unmarshalMapMessageValue(input text.Value, pkey pref.MapKey, _ pref.FieldDescriptor, mmap pref.Map) error {
436 var nerr errors.NonFatal
437 var value [][2]text.Value
438 if input.Type() != 0 {
439 value = input.Message()
440 }
Joe Tsai3bc7d6f2019-01-09 02:57:13 -0800441 m := mmap.NewMessage()
Herbie Ong800c9902018-12-06 15:28:53 -0800442 if err := o.unmarshalMessage(value, m); !nerr.Merge(err) {
443 return err
444 }
445 mmap.Set(pkey, pref.ValueOf(m))
446 return nerr.E
447}
448
449// unmarshalMapScalarValue unmarshals given scalar-type text.Value into a protoreflect.Map
450// for the given MapKey.
Herbie Ong66c365c2019-01-04 14:08:41 -0800451func unmarshalMapScalarValue(input text.Value, pkey pref.MapKey, fd pref.FieldDescriptor, mmap pref.Map) error {
Herbie Ong800c9902018-12-06 15:28:53 -0800452 var val pref.Value
453 if input.Type() == 0 {
454 val = fd.Default()
455 } else {
456 var err error
457 val, err = unmarshalScalar(input, fd)
458 if err != nil {
459 return err
460 }
461 }
462 mmap.Set(pkey, val)
463 return nil
464}
Herbie Ong66c365c2019-01-04 14:08:41 -0800465
466// isExpandedAny returns true if given [][2]text.Value may be an expanded Any that contains only one
467// field with key type of text.String type and value type of text.Message.
468func isExpandedAny(tmsg [][2]text.Value) bool {
469 if len(tmsg) != 1 {
470 return false
471 }
472
473 field := tmsg[0]
474 return field[0].Type() == text.String && field[1].Type() == text.Message
475}
476
477// unmarshalAny unmarshals an expanded Any textproto. This method assumes that the given
478// tfield has key type of text.String and value type of text.Message.
479func (o UnmarshalOptions) unmarshalAny(tfield [2]text.Value, knownFields pref.KnownFields) error {
480 var nerr errors.NonFatal
481
482 typeURL := tfield[0].String()
483 value := tfield[1].Message()
484
485 mt, err := o.Resolver.FindMessageByURL(typeURL)
486 if !nerr.Merge(err) {
487 return errors.New("unable to resolve message [%v]: %v", typeURL, err)
488 }
489 // Create new message for the embedded message type and unmarshal the
490 // value into it.
491 m := mt.New()
492 if err := o.unmarshalMessage(value, m); !nerr.Merge(err) {
493 return err
494 }
495 // Serialize the embedded message and assign the resulting bytes to the value field.
Herbie Onge0cf15b2019-03-15 19:32:38 -0700496 b, err := proto.MarshalOptions{Deterministic: true}.Marshal(m.Interface())
Herbie Ong66c365c2019-01-04 14:08:41 -0800497 if !nerr.Merge(err) {
498 return err
499 }
500
Herbie Onge1e34932019-03-29 01:05:57 -0700501 knownFields.Set(fieldnum.Any_TypeUrl, pref.ValueOf(typeURL))
502 knownFields.Set(fieldnum.Any_Value, pref.ValueOf(b))
Herbie Ong66c365c2019-01-04 14:08:41 -0800503
504 return nerr.E
505}