blob: 29bf11421e25009a207b96c4a1a70a105cb80748 [file] [log] [blame]
Herbie Ongc96a79d2019-03-08 10:49:17 -08001// Copyright 2019 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
Damien Neil5c5b5312019-05-14 12:44:37 -07005package protojson
Herbie Ongc96a79d2019-03-08 10:49:17 -08006
7import (
8 "encoding/base64"
9 "fmt"
10 "math"
11 "strconv"
12 "strings"
13
Damien Neile89e6242019-05-13 23:55:40 -070014 "google.golang.org/protobuf/internal/encoding/json"
15 "google.golang.org/protobuf/internal/errors"
16 "google.golang.org/protobuf/internal/pragma"
17 "google.golang.org/protobuf/internal/set"
18 "google.golang.org/protobuf/proto"
19 pref "google.golang.org/protobuf/reflect/protoreflect"
20 "google.golang.org/protobuf/reflect/protoregistry"
Herbie Ongc96a79d2019-03-08 10:49:17 -080021)
22
23// Unmarshal reads the given []byte into the given proto.Message.
Joe Tsaicdb77732019-05-14 16:05:06 -070024func Unmarshal(b []byte, m proto.Message) error {
25 return UnmarshalOptions{}.Unmarshal(b, m)
Herbie Ongc96a79d2019-03-08 10:49:17 -080026}
27
28// UnmarshalOptions is a configurable JSON format parser.
Herbie Onge52379a2019-03-15 18:00:19 -070029type UnmarshalOptions struct {
30 pragma.NoUnkeyedLiterals
31
Herbie Ong4f0be712019-04-25 17:57:12 -070032 // If AllowPartial is set, input for messages that will result in missing
33 // required fields will not return an error.
Herbie Ong329be5b2019-03-27 14:47:59 -070034 AllowPartial bool
35
Herbie Ong4f0be712019-04-25 17:57:12 -070036 // If DiscardUnknown is set, unknown fields are ignored.
37 DiscardUnknown bool
38
Joe Tsai1c283042019-05-14 14:28:19 -070039 // Resolver is used for looking up types when unmarshaling
40 // google.protobuf.Any messages or extension fields.
41 // If nil, this defaults to using protoregistry.GlobalTypes.
42 Resolver interface {
43 protoregistry.MessageTypeResolver
44 protoregistry.ExtensionTypeResolver
45 }
Herbie Ong822de2d2019-03-27 13:16:23 -070046
47 decoder *json.Decoder
Herbie Onge52379a2019-03-15 18:00:19 -070048}
Herbie Ongc96a79d2019-03-08 10:49:17 -080049
50// Unmarshal reads the given []byte and populates the given proto.Message using
51// options in UnmarshalOptions object. It will clear the message first before
52// setting the fields. If it returns an error, the given message may be
53// partially set.
Joe Tsaicdb77732019-05-14 16:05:06 -070054func (o UnmarshalOptions) Unmarshal(b []byte, m proto.Message) error {
Herbie Ongc96a79d2019-03-08 10:49:17 -080055 // TODO: Determine if we would like to have an option for merging or only
Joe Tsai378c1322019-04-25 23:48:08 -070056 // have merging behavior. We should at least be consistent with textproto
Herbie Ongc96a79d2019-03-08 10:49:17 -080057 // marshaling.
Joe Tsai378c1322019-04-25 23:48:08 -070058 proto.Reset(m)
Herbie Ongc96a79d2019-03-08 10:49:17 -080059
Herbie Ong822de2d2019-03-27 13:16:23 -070060 if o.Resolver == nil {
61 o.Resolver = protoregistry.GlobalTypes
Herbie Onge52379a2019-03-15 18:00:19 -070062 }
Herbie Ong822de2d2019-03-27 13:16:23 -070063 o.decoder = json.NewDecoder(b)
Herbie Onge52379a2019-03-15 18:00:19 -070064
Herbie Ongc96a79d2019-03-08 10:49:17 -080065 var nerr errors.NonFatal
Joe Tsai378c1322019-04-25 23:48:08 -070066 if err := o.unmarshalMessage(m.ProtoReflect(), false); !nerr.Merge(err) {
Herbie Ongc96a79d2019-03-08 10:49:17 -080067 return err
68 }
69
70 // Check for EOF.
Herbie Ong822de2d2019-03-27 13:16:23 -070071 val, err := o.decoder.Read()
Herbie Ongc96a79d2019-03-08 10:49:17 -080072 if err != nil {
73 return err
74 }
75 if val.Type() != json.EOF {
76 return unexpectedJSONError{val}
77 }
Damien Neil4686e232019-04-05 13:31:40 -070078
79 if !o.AllowPartial {
80 nerr.Merge(proto.IsInitialized(m))
81 }
Herbie Ongc96a79d2019-03-08 10:49:17 -080082 return nerr.E
83}
84
Herbie Ongc96a79d2019-03-08 10:49:17 -080085// unexpectedJSONError is an error that contains the unexpected json.Value. This
Herbie Ong822de2d2019-03-27 13:16:23 -070086// is returned by methods to provide callers the read json.Value that it did not
87// expect.
Herbie Ongc96a79d2019-03-08 10:49:17 -080088// TODO: Consider moving this to internal/encoding/json for consistency with
89// errors that package returns.
90type unexpectedJSONError struct {
91 value json.Value
92}
93
94func (e unexpectedJSONError) Error() string {
95 return newError("unexpected value %s", e.value).Error()
96}
97
98// newError returns an error object. If one of the values passed in is of
99// json.Value type, it produces an error with position info.
100func newError(f string, x ...interface{}) error {
101 var hasValue bool
102 var line, column int
103 for i := 0; i < len(x); i++ {
104 if val, ok := x[i].(json.Value); ok {
105 line, column = val.Position()
106 hasValue = true
107 break
108 }
109 }
110 e := errors.New(f, x...)
111 if hasValue {
112 return errors.New("(line %d:%d): %v", line, column, e)
113 }
114 return e
115}
116
Herbie Ongc96a79d2019-03-08 10:49:17 -0800117// unmarshalMessage unmarshals a message into the given protoreflect.Message.
Herbie Ong8ac9dd22019-03-27 12:20:50 -0700118func (o UnmarshalOptions) unmarshalMessage(m pref.Message, skipTypeURL bool) error {
Herbie Ongc96a79d2019-03-08 10:49:17 -0800119 var nerr errors.NonFatal
Herbie Ongc96a79d2019-03-08 10:49:17 -0800120
Joe Tsai0fc49f82019-05-01 12:29:25 -0700121 if isCustomType(m.Descriptor().FullName()) {
Herbie Ong822de2d2019-03-27 13:16:23 -0700122 return o.unmarshalCustomType(m)
Herbie Onge63c4c42019-03-22 22:20:22 -0700123 }
Herbie Ongc96a79d2019-03-08 10:49:17 -0800124
Herbie Ong822de2d2019-03-27 13:16:23 -0700125 jval, err := o.decoder.Read()
Herbie Ongc96a79d2019-03-08 10:49:17 -0800126 if !nerr.Merge(err) {
127 return err
128 }
129 if jval.Type() != json.StartObject {
130 return unexpectedJSONError{jval}
131 }
132
Herbie Ong8ac9dd22019-03-27 12:20:50 -0700133 if err := o.unmarshalFields(m, skipTypeURL); !nerr.Merge(err) {
Herbie Onge63c4c42019-03-22 22:20:22 -0700134 return err
135 }
136
137 return nerr.E
138}
139
140// unmarshalFields unmarshals the fields into the given protoreflect.Message.
Herbie Ong8ac9dd22019-03-27 12:20:50 -0700141func (o UnmarshalOptions) unmarshalFields(m pref.Message, skipTypeURL bool) error {
Herbie Onge63c4c42019-03-22 22:20:22 -0700142 var nerr errors.NonFatal
Herbie Onge63c4c42019-03-22 22:20:22 -0700143 var seenNums set.Ints
Herbie Ong8a1d4602019-04-02 20:19:36 -0700144 var seenOneofs set.Ints
Herbie Onge63c4c42019-03-22 22:20:22 -0700145
Joe Tsai0fc49f82019-05-01 12:29:25 -0700146 messageDesc := m.Descriptor()
Joe Tsai0fc49f82019-05-01 12:29:25 -0700147 fieldDescs := messageDesc.Fields()
Herbie Onge63c4c42019-03-22 22:20:22 -0700148
Herbie Ongc96a79d2019-03-08 10:49:17 -0800149Loop:
150 for {
151 // Read field name.
Herbie Ong822de2d2019-03-27 13:16:23 -0700152 jval, err := o.decoder.Read()
Herbie Ongc96a79d2019-03-08 10:49:17 -0800153 if !nerr.Merge(err) {
154 return err
155 }
156 switch jval.Type() {
157 default:
158 return unexpectedJSONError{jval}
159 case json.EndObject:
160 break Loop
161 case json.Name:
162 // Continue below.
163 }
164
165 name, err := jval.Name()
166 if !nerr.Merge(err) {
167 return err
168 }
Herbie Ong8ac9dd22019-03-27 12:20:50 -0700169 // Unmarshaling a non-custom embedded message in Any will contain the
170 // JSON field "@type" which should be skipped because it is not a field
171 // of the embedded message, but simply an artifact of the Any format.
172 if skipTypeURL && name == "@type" {
173 o.decoder.Read()
174 continue
175 }
Herbie Ongc96a79d2019-03-08 10:49:17 -0800176
Herbie Onge52379a2019-03-15 18:00:19 -0700177 // Get the FieldDescriptor.
178 var fd pref.FieldDescriptor
179 if strings.HasPrefix(name, "[") && strings.HasSuffix(name, "]") {
180 // Only extension names are in [name] format.
Joe Tsai378c1322019-04-25 23:48:08 -0700181 extName := pref.FullName(name[1 : len(name)-1])
182 extType, err := o.findExtension(extName)
183 if err != nil && err != protoregistry.NotFound {
184 return errors.New("unable to resolve [%v]: %v", extName, err)
Herbie Onge52379a2019-03-15 18:00:19 -0700185 }
Joe Tsai378c1322019-04-25 23:48:08 -0700186 fd = extType
Herbie Onge52379a2019-03-15 18:00:19 -0700187 } else {
188 // The name can either be the JSON name or the proto field name.
189 fd = fieldDescs.ByJSONName(name)
190 if fd == nil {
191 fd = fieldDescs.ByName(pref.Name(name))
192 }
Herbie Ongc96a79d2019-03-08 10:49:17 -0800193 }
194
195 if fd == nil {
196 // Field is unknown.
Herbie Ong4f0be712019-04-25 17:57:12 -0700197 if o.DiscardUnknown {
198 if err := skipJSONValue(o.decoder); !nerr.Merge(err) {
199 return err
200 }
201 continue
202 }
Joe Tsai0fc49f82019-05-01 12:29:25 -0700203 return newError("%v contains unknown field %s", messageDesc.FullName(), jval)
Herbie Ongc96a79d2019-03-08 10:49:17 -0800204 }
205
206 // Do not allow duplicate fields.
207 num := uint64(fd.Number())
208 if seenNums.Has(num) {
Joe Tsai0fc49f82019-05-01 12:29:25 -0700209 return newError("%v contains repeated field %s", messageDesc.FullName(), jval)
Herbie Ongc96a79d2019-03-08 10:49:17 -0800210 }
211 seenNums.Set(num)
212
Herbie Onge63c4c42019-03-22 22:20:22 -0700213 // No need to set values for JSON null unless the field type is
Herbie Ong300b9fe2019-03-29 15:42:20 -0700214 // google.protobuf.Value or google.protobuf.NullValue.
215 if o.decoder.Peek() == json.Null && !isKnownValue(fd) && !isNullValue(fd) {
Herbie Ong822de2d2019-03-27 13:16:23 -0700216 o.decoder.Read()
Herbie Ongc96a79d2019-03-08 10:49:17 -0800217 continue
218 }
219
Joe Tsaiac31a352019-05-13 14:32:56 -0700220 switch {
221 case fd.IsList():
Joe Tsai378c1322019-04-25 23:48:08 -0700222 list := m.Mutable(fd).List()
Joe Tsaiac31a352019-05-13 14:32:56 -0700223 if err := o.unmarshalList(list, fd); !nerr.Merge(err) {
Herbie Ongc96a79d2019-03-08 10:49:17 -0800224 return errors.New("%v|%q: %v", fd.FullName(), name, err)
225 }
Joe Tsaiac31a352019-05-13 14:32:56 -0700226 case fd.IsMap():
Joe Tsai378c1322019-04-25 23:48:08 -0700227 mmap := m.Mutable(fd).Map()
Joe Tsaiac31a352019-05-13 14:32:56 -0700228 if err := o.unmarshalMap(mmap, fd); !nerr.Merge(err) {
229 return errors.New("%v|%q: %v", fd.FullName(), name, err)
230 }
231 default:
Herbie Ong8a1d4602019-04-02 20:19:36 -0700232 // If field is a oneof, check if it has already been set.
Joe Tsaiac31a352019-05-13 14:32:56 -0700233 if od := fd.ContainingOneof(); od != nil {
Herbie Ong8a1d4602019-04-02 20:19:36 -0700234 idx := uint64(od.Index())
235 if seenOneofs.Has(idx) {
236 return errors.New("%v: oneof is already set", od.FullName())
237 }
238 seenOneofs.Set(idx)
239 }
240
Herbie Ongc96a79d2019-03-08 10:49:17 -0800241 // Required or optional fields.
Joe Tsai378c1322019-04-25 23:48:08 -0700242 if err := o.unmarshalSingular(m, fd); !nerr.Merge(err) {
Herbie Ongc96a79d2019-03-08 10:49:17 -0800243 return errors.New("%v|%q: %v", fd.FullName(), name, err)
244 }
Herbie Ongc96a79d2019-03-08 10:49:17 -0800245 }
246 }
247
248 return nerr.E
249}
250
Herbie Onge52379a2019-03-15 18:00:19 -0700251// findExtension returns protoreflect.ExtensionType from the resolver if found.
Herbie Ong822de2d2019-03-27 13:16:23 -0700252func (o UnmarshalOptions) findExtension(xtName pref.FullName) (pref.ExtensionType, error) {
253 xt, err := o.Resolver.FindExtensionByName(xtName)
Herbie Onge52379a2019-03-15 18:00:19 -0700254 if err == nil {
255 return xt, nil
256 }
257
258 // Check if this is a MessageSet extension field.
Herbie Ong822de2d2019-03-27 13:16:23 -0700259 xt, err = o.Resolver.FindExtensionByName(xtName + ".message_set_extension")
Herbie Onge52379a2019-03-15 18:00:19 -0700260 if err == nil && isMessageSetExtension(xt) {
261 return xt, nil
262 }
263 return nil, protoregistry.NotFound
264}
265
Herbie Ong300b9fe2019-03-29 15:42:20 -0700266func isKnownValue(fd pref.FieldDescriptor) bool {
Joe Tsaid24bc722019-04-15 23:39:09 -0700267 md := fd.Message()
Herbie Ong300b9fe2019-03-29 15:42:20 -0700268 return md != nil && md.FullName() == "google.protobuf.Value"
269}
270
271func isNullValue(fd pref.FieldDescriptor) bool {
Joe Tsaid24bc722019-04-15 23:39:09 -0700272 ed := fd.Enum()
Herbie Ong300b9fe2019-03-29 15:42:20 -0700273 return ed != nil && ed.FullName() == "google.protobuf.NullValue"
274}
275
Herbie Ongc96a79d2019-03-08 10:49:17 -0800276// unmarshalSingular unmarshals to the non-repeated field specified by the given
277// FieldDescriptor.
Joe Tsai378c1322019-04-25 23:48:08 -0700278func (o UnmarshalOptions) unmarshalSingular(m pref.Message, fd pref.FieldDescriptor) error {
Herbie Ongc96a79d2019-03-08 10:49:17 -0800279 var val pref.Value
280 var err error
Herbie Ongc96a79d2019-03-08 10:49:17 -0800281 switch fd.Kind() {
282 case pref.MessageKind, pref.GroupKind:
Joe Tsai378c1322019-04-25 23:48:08 -0700283 m2 := m.NewMessage(fd)
284 err = o.unmarshalMessage(m2, false)
285 val = pref.ValueOf(m2)
Herbie Ongc96a79d2019-03-08 10:49:17 -0800286 default:
Herbie Ong822de2d2019-03-27 13:16:23 -0700287 val, err = o.unmarshalScalar(fd)
Herbie Ongc96a79d2019-03-08 10:49:17 -0800288 }
289
290 var nerr errors.NonFatal
291 if !nerr.Merge(err) {
292 return err
293 }
Joe Tsai378c1322019-04-25 23:48:08 -0700294 m.Set(fd, val)
Herbie Ongc96a79d2019-03-08 10:49:17 -0800295 return nerr.E
296}
297
298// unmarshalScalar unmarshals to a scalar/enum protoreflect.Value specified by
299// the given FieldDescriptor.
Herbie Ong822de2d2019-03-27 13:16:23 -0700300func (o UnmarshalOptions) unmarshalScalar(fd pref.FieldDescriptor) (pref.Value, error) {
Herbie Ongc96a79d2019-03-08 10:49:17 -0800301 const b32 int = 32
302 const b64 int = 64
303
304 var nerr errors.NonFatal
Herbie Ong822de2d2019-03-27 13:16:23 -0700305 jval, err := o.decoder.Read()
Herbie Ongc96a79d2019-03-08 10:49:17 -0800306 if !nerr.Merge(err) {
307 return pref.Value{}, err
308 }
309
310 kind := fd.Kind()
311 switch kind {
312 case pref.BoolKind:
313 return unmarshalBool(jval)
314
315 case pref.Int32Kind, pref.Sint32Kind, pref.Sfixed32Kind:
316 return unmarshalInt(jval, b32)
317
318 case pref.Int64Kind, pref.Sint64Kind, pref.Sfixed64Kind:
319 return unmarshalInt(jval, b64)
320
321 case pref.Uint32Kind, pref.Fixed32Kind:
322 return unmarshalUint(jval, b32)
323
324 case pref.Uint64Kind, pref.Fixed64Kind:
325 return unmarshalUint(jval, b64)
326
327 case pref.FloatKind:
328 return unmarshalFloat(jval, b32)
329
330 case pref.DoubleKind:
331 return unmarshalFloat(jval, b64)
332
333 case pref.StringKind:
334 pval, err := unmarshalString(jval)
335 if !nerr.Merge(err) {
336 return pval, err
337 }
338 return pval, nerr.E
339
340 case pref.BytesKind:
341 return unmarshalBytes(jval)
342
343 case pref.EnumKind:
344 return unmarshalEnum(jval, fd)
345 }
346
347 panic(fmt.Sprintf("invalid scalar kind %v", kind))
348}
349
350func unmarshalBool(jval json.Value) (pref.Value, error) {
351 if jval.Type() != json.Bool {
352 return pref.Value{}, unexpectedJSONError{jval}
353 }
354 b, err := jval.Bool()
355 return pref.ValueOf(b), err
356}
357
358func unmarshalInt(jval json.Value, bitSize int) (pref.Value, error) {
359 switch jval.Type() {
360 case json.Number:
361 return getInt(jval, bitSize)
362
363 case json.String:
Herbie Onge52379a2019-03-15 18:00:19 -0700364 // Decode number from string.
Herbie Ong06a6b0b2019-04-24 21:15:45 -0700365 s := strings.TrimSpace(jval.String())
366 if len(s) != len(jval.String()) {
367 return pref.Value{}, errors.New("invalid number %v", jval.Raw())
368 }
369 dec := json.NewDecoder([]byte(s))
Herbie Ongc96a79d2019-03-08 10:49:17 -0800370 var nerr errors.NonFatal
371 jval, err := dec.Read()
372 if !nerr.Merge(err) {
373 return pref.Value{}, err
374 }
375 return getInt(jval, bitSize)
376 }
377 return pref.Value{}, unexpectedJSONError{jval}
378}
379
380func getInt(jval json.Value, bitSize int) (pref.Value, error) {
381 n, err := jval.Int(bitSize)
382 if err != nil {
383 return pref.Value{}, err
384 }
385 if bitSize == 32 {
386 return pref.ValueOf(int32(n)), nil
387 }
388 return pref.ValueOf(n), nil
389}
390
391func unmarshalUint(jval json.Value, bitSize int) (pref.Value, error) {
392 switch jval.Type() {
393 case json.Number:
394 return getUint(jval, bitSize)
395
396 case json.String:
Herbie Onge52379a2019-03-15 18:00:19 -0700397 // Decode number from string.
Herbie Ong06a6b0b2019-04-24 21:15:45 -0700398 s := strings.TrimSpace(jval.String())
399 if len(s) != len(jval.String()) {
400 return pref.Value{}, errors.New("invalid number %v", jval.Raw())
401 }
402 dec := json.NewDecoder([]byte(s))
Herbie Ongc96a79d2019-03-08 10:49:17 -0800403 var nerr errors.NonFatal
404 jval, err := dec.Read()
405 if !nerr.Merge(err) {
406 return pref.Value{}, err
407 }
408 return getUint(jval, bitSize)
409 }
410 return pref.Value{}, unexpectedJSONError{jval}
411}
412
413func getUint(jval json.Value, bitSize int) (pref.Value, error) {
414 n, err := jval.Uint(bitSize)
415 if err != nil {
416 return pref.Value{}, err
417 }
418 if bitSize == 32 {
419 return pref.ValueOf(uint32(n)), nil
420 }
421 return pref.ValueOf(n), nil
422}
423
424func unmarshalFloat(jval json.Value, bitSize int) (pref.Value, error) {
425 switch jval.Type() {
426 case json.Number:
427 return getFloat(jval, bitSize)
428
429 case json.String:
430 s := jval.String()
431 switch s {
432 case "NaN":
433 if bitSize == 32 {
434 return pref.ValueOf(float32(math.NaN())), nil
435 }
436 return pref.ValueOf(math.NaN()), nil
437 case "Infinity":
438 if bitSize == 32 {
439 return pref.ValueOf(float32(math.Inf(+1))), nil
440 }
441 return pref.ValueOf(math.Inf(+1)), nil
442 case "-Infinity":
443 if bitSize == 32 {
444 return pref.ValueOf(float32(math.Inf(-1))), nil
445 }
446 return pref.ValueOf(math.Inf(-1)), nil
447 }
Herbie Onge52379a2019-03-15 18:00:19 -0700448 // Decode number from string.
Herbie Ong06a6b0b2019-04-24 21:15:45 -0700449 if len(s) != len(strings.TrimSpace(s)) {
450 return pref.Value{}, errors.New("invalid number %v", jval.Raw())
451 }
Herbie Onge52379a2019-03-15 18:00:19 -0700452 dec := json.NewDecoder([]byte(s))
Herbie Ongc96a79d2019-03-08 10:49:17 -0800453 var nerr errors.NonFatal
454 jval, err := dec.Read()
455 if !nerr.Merge(err) {
456 return pref.Value{}, err
457 }
458 return getFloat(jval, bitSize)
459 }
460 return pref.Value{}, unexpectedJSONError{jval}
461}
462
463func getFloat(jval json.Value, bitSize int) (pref.Value, error) {
464 n, err := jval.Float(bitSize)
465 if err != nil {
466 return pref.Value{}, err
467 }
468 if bitSize == 32 {
469 return pref.ValueOf(float32(n)), nil
470 }
471 return pref.ValueOf(n), nil
472}
473
474func unmarshalString(jval json.Value) (pref.Value, error) {
475 if jval.Type() != json.String {
476 return pref.Value{}, unexpectedJSONError{jval}
477 }
478 return pref.ValueOf(jval.String()), nil
479}
480
481func unmarshalBytes(jval json.Value) (pref.Value, error) {
482 if jval.Type() != json.String {
483 return pref.Value{}, unexpectedJSONError{jval}
484 }
485
486 s := jval.String()
487 enc := base64.StdEncoding
488 if strings.ContainsAny(s, "-_") {
489 enc = base64.URLEncoding
490 }
491 if len(s)%4 != 0 {
492 enc = enc.WithPadding(base64.NoPadding)
493 }
494 b, err := enc.DecodeString(s)
495 if err != nil {
496 return pref.Value{}, err
497 }
498 return pref.ValueOf(b), nil
499}
500
501func unmarshalEnum(jval json.Value, fd pref.FieldDescriptor) (pref.Value, error) {
502 switch jval.Type() {
503 case json.String:
504 // Lookup EnumNumber based on name.
505 s := jval.String()
Joe Tsaid24bc722019-04-15 23:39:09 -0700506 if enumVal := fd.Enum().Values().ByName(pref.Name(s)); enumVal != nil {
Herbie Ongc96a79d2019-03-08 10:49:17 -0800507 return pref.ValueOf(enumVal.Number()), nil
508 }
509 return pref.Value{}, newError("invalid enum value %q", jval)
510
511 case json.Number:
512 n, err := jval.Int(32)
513 if err != nil {
514 return pref.Value{}, err
515 }
516 return pref.ValueOf(pref.EnumNumber(n)), nil
Herbie Ong300b9fe2019-03-29 15:42:20 -0700517
518 case json.Null:
519 // This is only valid for google.protobuf.NullValue.
520 if isNullValue(fd) {
521 return pref.ValueOf(pref.EnumNumber(0)), nil
522 }
Herbie Ongc96a79d2019-03-08 10:49:17 -0800523 }
524
525 return pref.Value{}, unexpectedJSONError{jval}
526}
527
Herbie Ong822de2d2019-03-27 13:16:23 -0700528func (o UnmarshalOptions) unmarshalList(list pref.List, fd pref.FieldDescriptor) error {
Herbie Ongc96a79d2019-03-08 10:49:17 -0800529 var nerr errors.NonFatal
Herbie Ong822de2d2019-03-27 13:16:23 -0700530 jval, err := o.decoder.Read()
Herbie Ongc96a79d2019-03-08 10:49:17 -0800531 if !nerr.Merge(err) {
532 return err
533 }
534 if jval.Type() != json.StartArray {
535 return unexpectedJSONError{jval}
536 }
537
538 switch fd.Kind() {
539 case pref.MessageKind, pref.GroupKind:
540 for {
541 m := list.NewMessage()
Herbie Ong8ac9dd22019-03-27 12:20:50 -0700542 err := o.unmarshalMessage(m, false)
Herbie Ongc96a79d2019-03-08 10:49:17 -0800543 if !nerr.Merge(err) {
544 if e, ok := err.(unexpectedJSONError); ok {
545 if e.value.Type() == json.EndArray {
546 // Done with list.
547 return nerr.E
548 }
549 }
550 return err
551 }
552 list.Append(pref.ValueOf(m))
553 }
554 default:
555 for {
Herbie Ong822de2d2019-03-27 13:16:23 -0700556 val, err := o.unmarshalScalar(fd)
Herbie Ongc96a79d2019-03-08 10:49:17 -0800557 if !nerr.Merge(err) {
558 if e, ok := err.(unexpectedJSONError); ok {
559 if e.value.Type() == json.EndArray {
560 // Done with list.
561 return nerr.E
562 }
563 }
564 return err
565 }
566 list.Append(val)
567 }
568 }
569 return nerr.E
570}
571
Herbie Ong822de2d2019-03-27 13:16:23 -0700572func (o UnmarshalOptions) unmarshalMap(mmap pref.Map, fd pref.FieldDescriptor) error {
Herbie Ongc96a79d2019-03-08 10:49:17 -0800573 var nerr errors.NonFatal
Herbie Ong822de2d2019-03-27 13:16:23 -0700574 jval, err := o.decoder.Read()
Herbie Ongc96a79d2019-03-08 10:49:17 -0800575 if !nerr.Merge(err) {
576 return err
577 }
578 if jval.Type() != json.StartObject {
579 return unexpectedJSONError{jval}
580 }
581
Herbie Ongc96a79d2019-03-08 10:49:17 -0800582 // Determine ahead whether map entry is a scalar type or a message type in
583 // order to call the appropriate unmarshalMapValue func inside the for loop
584 // below.
Joe Tsaiac31a352019-05-13 14:32:56 -0700585 var unmarshalMapValue func() (pref.Value, error)
586 switch fd.MapValue().Kind() {
Herbie Ongc96a79d2019-03-08 10:49:17 -0800587 case pref.MessageKind, pref.GroupKind:
588 unmarshalMapValue = func() (pref.Value, error) {
Herbie Onge63c4c42019-03-22 22:20:22 -0700589 var nerr errors.NonFatal
Herbie Ongc96a79d2019-03-08 10:49:17 -0800590 m := mmap.NewMessage()
Herbie Ong8ac9dd22019-03-27 12:20:50 -0700591 if err := o.unmarshalMessage(m, false); !nerr.Merge(err) {
Herbie Ongc96a79d2019-03-08 10:49:17 -0800592 return pref.Value{}, err
593 }
Herbie Onge63c4c42019-03-22 22:20:22 -0700594 return pref.ValueOf(m), nerr.E
Herbie Ongc96a79d2019-03-08 10:49:17 -0800595 }
Joe Tsaiac31a352019-05-13 14:32:56 -0700596 default:
597 unmarshalMapValue = func() (pref.Value, error) {
598 return o.unmarshalScalar(fd.MapValue())
599 }
Herbie Ongc96a79d2019-03-08 10:49:17 -0800600 }
601
602Loop:
603 for {
604 // Read field name.
Herbie Ong822de2d2019-03-27 13:16:23 -0700605 jval, err := o.decoder.Read()
Herbie Ongc96a79d2019-03-08 10:49:17 -0800606 if !nerr.Merge(err) {
607 return err
608 }
609 switch jval.Type() {
610 default:
611 return unexpectedJSONError{jval}
612 case json.EndObject:
613 break Loop
614 case json.Name:
615 // Continue.
616 }
617
618 name, err := jval.Name()
619 if !nerr.Merge(err) {
620 return err
621 }
622
623 // Unmarshal field name.
Joe Tsaiac31a352019-05-13 14:32:56 -0700624 pkey, err := unmarshalMapKey(name, fd.MapKey())
Herbie Ongc96a79d2019-03-08 10:49:17 -0800625 if !nerr.Merge(err) {
626 return err
627 }
628
629 // Check for duplicate field name.
630 if mmap.Has(pkey) {
631 return newError("duplicate map key %q", jval)
632 }
633
634 // Read and unmarshal field value.
635 pval, err := unmarshalMapValue()
636 if !nerr.Merge(err) {
637 return err
638 }
639
640 mmap.Set(pkey, pval)
641 }
642
643 return nerr.E
644}
645
646// unmarshalMapKey converts given string into a protoreflect.MapKey. A map key type is any
647// integral or string type.
648func unmarshalMapKey(name string, fd pref.FieldDescriptor) (pref.MapKey, error) {
649 const b32 = 32
650 const b64 = 64
651 const base10 = 10
652
653 kind := fd.Kind()
654 switch kind {
655 case pref.StringKind:
656 return pref.ValueOf(name).MapKey(), nil
657
658 case pref.BoolKind:
659 switch name {
660 case "true":
661 return pref.ValueOf(true).MapKey(), nil
662 case "false":
663 return pref.ValueOf(false).MapKey(), nil
664 }
665 return pref.MapKey{}, errors.New("invalid value for boolean key %q", name)
666
667 case pref.Int32Kind, pref.Sint32Kind, pref.Sfixed32Kind:
668 n, err := strconv.ParseInt(name, base10, b32)
669 if err != nil {
670 return pref.MapKey{}, err
671 }
672 return pref.ValueOf(int32(n)).MapKey(), nil
673
674 case pref.Int64Kind, pref.Sint64Kind, pref.Sfixed64Kind:
675 n, err := strconv.ParseInt(name, base10, b64)
676 if err != nil {
677 return pref.MapKey{}, err
678 }
679 return pref.ValueOf(int64(n)).MapKey(), nil
680
681 case pref.Uint32Kind, pref.Fixed32Kind:
682 n, err := strconv.ParseUint(name, base10, b32)
683 if err != nil {
684 return pref.MapKey{}, err
685 }
686 return pref.ValueOf(uint32(n)).MapKey(), nil
687
688 case pref.Uint64Kind, pref.Fixed64Kind:
689 n, err := strconv.ParseUint(name, base10, b64)
690 if err != nil {
691 return pref.MapKey{}, err
692 }
693 return pref.ValueOf(uint64(n)).MapKey(), nil
694 }
695
696 panic(fmt.Sprintf("%s: invalid kind %s for map key", fd.FullName(), kind))
697}