decode.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  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. package textpb
  5. import (
  6. "fmt"
  7. "github.com/golang/protobuf/v2/internal/encoding/text"
  8. "github.com/golang/protobuf/v2/internal/errors"
  9. "github.com/golang/protobuf/v2/internal/pragma"
  10. "github.com/golang/protobuf/v2/internal/set"
  11. "github.com/golang/protobuf/v2/proto"
  12. pref "github.com/golang/protobuf/v2/reflect/protoreflect"
  13. )
  14. // Unmarshal reads the given []byte into the given proto.Message.
  15. // TODO: may want to describe when Unmarshal returns error.
  16. func Unmarshal(m proto.Message, b []byte) error {
  17. return UnmarshalOptions{}.Unmarshal(m, b)
  18. }
  19. // UnmarshalOptions is a configurable textproto format parser.
  20. type UnmarshalOptions struct {
  21. pragma.NoUnkeyedLiterals
  22. }
  23. // Unmarshal reads the given []byte and populates the given proto.Message using options in
  24. // UnmarshalOptions object.
  25. func (o UnmarshalOptions) Unmarshal(m proto.Message, b []byte) error {
  26. var nerr errors.NonFatal
  27. mr := m.ProtoReflect()
  28. // Clear all fields before populating it.
  29. // TODO: Determine if this needs to be consistent with jsonpb and binary unmarshal where
  30. // behavior is to merge values into existing message. If decision is to not clear the fields
  31. // ahead, code will need to be updated properly when merging nested messages.
  32. resetMessage(mr)
  33. // Parse into text.Value of message type.
  34. val, err := text.Unmarshal(b)
  35. if !nerr.Merge(err) {
  36. return err
  37. }
  38. err = o.unmarshalMessage(val.Message(), mr)
  39. if !nerr.Merge(err) {
  40. return err
  41. }
  42. return nerr.E
  43. }
  44. // resetMessage clears all fields of given protoreflect.Message.
  45. // TODO: This should go into the proto package.
  46. func resetMessage(m pref.Message) {
  47. knownFields := m.KnownFields()
  48. knownFields.Range(func(num pref.FieldNumber, _ pref.Value) bool {
  49. knownFields.Clear(num)
  50. return true
  51. })
  52. unknownFields := m.UnknownFields()
  53. unknownFields.Range(func(num pref.FieldNumber, _ pref.RawFields) bool {
  54. unknownFields.Set(num, nil)
  55. return true
  56. })
  57. extTypes := knownFields.ExtensionTypes()
  58. extTypes.Range(func(xt pref.ExtensionType) bool {
  59. extTypes.Remove(xt)
  60. return true
  61. })
  62. }
  63. // unmarshalMessage unmarshals a [][2]text.Value message into the given protoreflect.Message.
  64. func (o UnmarshalOptions) unmarshalMessage(tmsg [][2]text.Value, m pref.Message) error {
  65. var nerr errors.NonFatal
  66. msgType := m.Type()
  67. fieldDescs := msgType.Fields()
  68. reservedNames := msgType.ReservedNames()
  69. knownFields := m.KnownFields()
  70. var reqNums set.Ints
  71. var seenNums set.Ints
  72. for _, tfield := range tmsg {
  73. tkey := tfield[0]
  74. tval := tfield[1]
  75. var fd pref.FieldDescriptor
  76. name, ok := tkey.Name()
  77. if ok {
  78. fd = fieldDescs.ByName(name)
  79. }
  80. if fd == nil {
  81. // Ignore reserved names.
  82. if reservedNames.Has(name) {
  83. continue
  84. }
  85. // TODO: Can provide option to ignore unknown message fields.
  86. return errors.New("%v contains unknown field: %v", msgType.FullName(), tkey)
  87. }
  88. if cardinality := fd.Cardinality(); cardinality == pref.Repeated {
  89. // Map or list fields have cardinality of repeated.
  90. if err := o.unmarshalRepeated(tval, fd, knownFields); !nerr.Merge(err) {
  91. return err
  92. }
  93. } else {
  94. // Required or optional fields.
  95. num := uint64(fd.Number())
  96. if seenNums.Has(num) {
  97. return errors.New("non-repeated field %v is repeated", fd.FullName())
  98. }
  99. if err := o.unmarshalSingular(tval, fd, knownFields); !nerr.Merge(err) {
  100. return err
  101. }
  102. if cardinality == pref.Required {
  103. reqNums.Set(num)
  104. }
  105. seenNums.Set(num)
  106. }
  107. }
  108. // Check for any missing required fields.
  109. allReqNums := msgType.RequiredNumbers()
  110. if reqNums.Len() != allReqNums.Len() {
  111. for i := 0; i < allReqNums.Len(); i++ {
  112. if num := allReqNums.Get(i); !reqNums.Has(uint64(num)) {
  113. nerr.AppendRequiredNotSet(string(fieldDescs.ByNumber(num).FullName()))
  114. }
  115. }
  116. }
  117. return nerr.E
  118. }
  119. // unmarshalSingular unmarshals given text.Value into the non-repeated field.
  120. func (o UnmarshalOptions) unmarshalSingular(input text.Value, fd pref.FieldDescriptor, knownFields pref.KnownFields) error {
  121. num := fd.Number()
  122. var nerr errors.NonFatal
  123. var val pref.Value
  124. switch fd.Kind() {
  125. case pref.MessageKind, pref.GroupKind:
  126. if input.Type() != text.Message {
  127. return errors.New("%v contains invalid message/group value: %v", fd.FullName(), input)
  128. }
  129. m := knownFields.NewMessage(num).ProtoReflect()
  130. if err := o.unmarshalMessage(input.Message(), m); !nerr.Merge(err) {
  131. return err
  132. }
  133. val = pref.ValueOf(m)
  134. default:
  135. var err error
  136. val, err = unmarshalScalar(input, fd)
  137. if !nerr.Merge(err) {
  138. return err
  139. }
  140. }
  141. knownFields.Set(num, val)
  142. return nerr.E
  143. }
  144. // unmarshalRepeated unmarshals given text.Value into a repeated field. Caller should only
  145. // call this for cardinality=repeated.
  146. func (o UnmarshalOptions) unmarshalRepeated(input text.Value, fd pref.FieldDescriptor, knownFields pref.KnownFields) error {
  147. var items []text.Value
  148. // If input is not a list, turn it into a list.
  149. if input.Type() != text.List {
  150. items = []text.Value{input}
  151. } else {
  152. items = input.List()
  153. }
  154. var nerr errors.NonFatal
  155. num := fd.Number()
  156. val := knownFields.Get(num)
  157. if !fd.IsMap() {
  158. if err := o.unmarshalList(items, fd, val.List()); !nerr.Merge(err) {
  159. return err
  160. }
  161. } else {
  162. if err := o.unmarshalMap(items, fd, val.Map()); !nerr.Merge(err) {
  163. return err
  164. }
  165. }
  166. return nerr.E
  167. }
  168. // unmarshalScalar converts the given text.Value to a scalar/enum protoreflect.Value specified in
  169. // the given FieldDescriptor. Caller should not pass in a FieldDescriptor for a message/group kind.
  170. func unmarshalScalar(input text.Value, fd pref.FieldDescriptor) (pref.Value, error) {
  171. const b32 = false
  172. const b64 = true
  173. switch kind := fd.Kind(); kind {
  174. case pref.BoolKind:
  175. if b, ok := input.Bool(); ok {
  176. return pref.ValueOf(bool(b)), nil
  177. }
  178. case pref.Int32Kind, pref.Sint32Kind, pref.Sfixed32Kind:
  179. if n, ok := input.Int(b32); ok {
  180. return pref.ValueOf(int32(n)), nil
  181. }
  182. case pref.Int64Kind, pref.Sint64Kind, pref.Sfixed64Kind:
  183. if n, ok := input.Int(b64); ok {
  184. return pref.ValueOf(int64(n)), nil
  185. }
  186. case pref.Uint32Kind, pref.Fixed32Kind:
  187. if n, ok := input.Uint(b32); ok {
  188. return pref.ValueOf(uint32(n)), nil
  189. }
  190. case pref.Uint64Kind, pref.Fixed64Kind:
  191. if n, ok := input.Uint(b64); ok {
  192. return pref.ValueOf(uint64(n)), nil
  193. }
  194. case pref.FloatKind:
  195. if n, ok := input.Float(b32); ok {
  196. return pref.ValueOf(float32(n)), nil
  197. }
  198. case pref.DoubleKind:
  199. if n, ok := input.Float(b64); ok {
  200. return pref.ValueOf(float64(n)), nil
  201. }
  202. case pref.StringKind:
  203. if input.Type() == text.String {
  204. return pref.ValueOf(string(input.String())), nil
  205. }
  206. case pref.BytesKind:
  207. if input.Type() == text.String {
  208. return pref.ValueOf([]byte(input.String())), nil
  209. }
  210. case pref.EnumKind:
  211. // If input is int32, use directly.
  212. if n, ok := input.Int(b32); ok {
  213. return pref.ValueOf(pref.EnumNumber(n)), nil
  214. } else {
  215. if name, ok := input.Name(); ok {
  216. // Lookup EnumNumber based on name.
  217. if enumVal := fd.EnumType().Values().ByName(name); enumVal != nil {
  218. return pref.ValueOf(enumVal.Number()), nil
  219. }
  220. }
  221. }
  222. default:
  223. panic(fmt.Sprintf("invalid scalar kind %v", kind))
  224. }
  225. return pref.Value{}, errors.New("%v contains invalid scalar value: %v", fd.FullName(), input)
  226. }
  227. // unmarshalList unmarshals given []text.Value into given protoreflect.List.
  228. func (o UnmarshalOptions) unmarshalList(inputList []text.Value, fd pref.FieldDescriptor, list pref.List) error {
  229. var nerr errors.NonFatal
  230. switch fd.Kind() {
  231. case pref.MessageKind, pref.GroupKind:
  232. for _, input := range inputList {
  233. if input.Type() != text.Message {
  234. return errors.New("%v contains invalid message/group value: %v", fd.FullName(), input)
  235. }
  236. m := list.NewMessage().ProtoReflect()
  237. if err := o.unmarshalMessage(input.Message(), m); !nerr.Merge(err) {
  238. return err
  239. }
  240. list.Append(pref.ValueOf(m))
  241. }
  242. default:
  243. for _, input := range inputList {
  244. val, err := unmarshalScalar(input, fd)
  245. if !nerr.Merge(err) {
  246. return err
  247. }
  248. list.Append(val)
  249. }
  250. }
  251. return nerr.E
  252. }
  253. // unmarshalMap unmarshals given []text.Value into given protoreflect.Map.
  254. func (o UnmarshalOptions) unmarshalMap(input []text.Value, fd pref.FieldDescriptor, mmap pref.Map) error {
  255. var nerr errors.NonFatal
  256. fields := fd.MessageType().Fields()
  257. keyDesc := fields.ByNumber(1)
  258. valDesc := fields.ByNumber(2)
  259. // Determine ahead whether map entry is a scalar type or a message type in order to call the
  260. // appropriate unmarshalMapValue func inside the for loop below.
  261. unmarshalMapValue := o.unmarshalMapScalarValue
  262. switch valDesc.Kind() {
  263. case pref.MessageKind, pref.GroupKind:
  264. unmarshalMapValue = o.unmarshalMapMessageValue
  265. }
  266. for _, entry := range input {
  267. if entry.Type() != text.Message {
  268. return errors.New("%v contains invalid map entry: %v", fd.FullName(), entry)
  269. }
  270. tkey, tval, err := parseMapEntry(entry.Message(), fd.FullName())
  271. if !nerr.Merge(err) {
  272. return err
  273. }
  274. pkey, err := unmarshalMapKey(tkey, keyDesc)
  275. if !nerr.Merge(err) {
  276. return err
  277. }
  278. err = unmarshalMapValue(tval, pkey, valDesc, mmap)
  279. if !nerr.Merge(err) {
  280. return err
  281. }
  282. }
  283. return nerr.E
  284. }
  285. // parseMapEntry parses [][2]text.Value for field names key and value, and return corresponding
  286. // field values. If there are duplicate field names, the value for the last field is returned. If
  287. // the field name does not exist, it will return the zero value of text.Value. It will return an
  288. // error if there are unknown field names.
  289. func parseMapEntry(mapEntry [][2]text.Value, name pref.FullName) (key text.Value, value text.Value, err error) {
  290. for _, field := range mapEntry {
  291. keyStr, ok := field[0].Name()
  292. if ok {
  293. switch keyStr {
  294. case "key":
  295. if key.Type() != 0 {
  296. return key, value, errors.New("%v contains duplicate key field", name)
  297. }
  298. key = field[1]
  299. case "value":
  300. if value.Type() != 0 {
  301. return key, value, errors.New("%v contains duplicate value field", name)
  302. }
  303. value = field[1]
  304. default:
  305. ok = false
  306. }
  307. }
  308. if !ok {
  309. // TODO: Do not return error if ignore unknown option is added and enabled.
  310. return key, value, errors.New("%v contains unknown map entry name: %v", name, field[0])
  311. }
  312. }
  313. return key, value, nil
  314. }
  315. // unmarshalMapKey converts given text.Value into a protoreflect.MapKey. A map key type is any
  316. // integral or string type.
  317. func unmarshalMapKey(input text.Value, fd pref.FieldDescriptor) (pref.MapKey, error) {
  318. // If input is not set, use the zero value.
  319. if input.Type() == 0 {
  320. return fd.Default().MapKey(), nil
  321. }
  322. val, err := unmarshalScalar(input, fd)
  323. if err != nil {
  324. return pref.MapKey{}, errors.New("%v contains invalid key: %v", fd.FullName(), input)
  325. }
  326. return val.MapKey(), nil
  327. }
  328. // unmarshalMapMessageValue unmarshals given message-type text.Value into a protoreflect.Map for
  329. // the given MapKey.
  330. func (o UnmarshalOptions) unmarshalMapMessageValue(input text.Value, pkey pref.MapKey, _ pref.FieldDescriptor, mmap pref.Map) error {
  331. var nerr errors.NonFatal
  332. var value [][2]text.Value
  333. if input.Type() != 0 {
  334. value = input.Message()
  335. }
  336. m := mmap.NewMessage().ProtoReflect()
  337. if err := o.unmarshalMessage(value, m); !nerr.Merge(err) {
  338. return err
  339. }
  340. mmap.Set(pkey, pref.ValueOf(m))
  341. return nerr.E
  342. }
  343. // unmarshalMapScalarValue unmarshals given scalar-type text.Value into a protoreflect.Map
  344. // for the given MapKey.
  345. func (o UnmarshalOptions) unmarshalMapScalarValue(input text.Value, pkey pref.MapKey, fd pref.FieldDescriptor, mmap pref.Map) error {
  346. var val pref.Value
  347. if input.Type() == 0 {
  348. val = fd.Default()
  349. } else {
  350. var err error
  351. val, err = unmarshalScalar(input, fd)
  352. if err != nil {
  353. return err
  354. }
  355. }
  356. mmap.Set(pkey, val)
  357. return nil
  358. }