decode.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  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. knownFields := m.KnownFields()
  69. var reqNums set.Ints
  70. var seenNums set.Ints
  71. for _, tfield := range tmsg {
  72. tkey := tfield[0]
  73. tval := tfield[1]
  74. var fd pref.FieldDescriptor
  75. if name, ok := tkey.Name(); ok {
  76. fd = fieldDescs.ByName(name)
  77. }
  78. if fd == nil {
  79. // TODO: Can provide option to ignore unknown message fields.
  80. // TODO: Simply ignore and skip reserved field names.
  81. return errors.New("%v contains unknown field: %v", msgType.FullName(), tkey)
  82. }
  83. if cardinality := fd.Cardinality(); cardinality == pref.Repeated {
  84. // Map or list fields have cardinality of repeated.
  85. if err := o.unmarshalRepeated(tval, fd, knownFields); !nerr.Merge(err) {
  86. return err
  87. }
  88. } else {
  89. // Required or optional fields.
  90. num := uint64(fd.Number())
  91. if seenNums.Has(num) {
  92. return errors.New("non-repeated field %v is repeated", fd.FullName())
  93. }
  94. if err := o.unmarshalSingular(tval, fd, knownFields); !nerr.Merge(err) {
  95. return err
  96. }
  97. if cardinality == pref.Required {
  98. reqNums.Set(num)
  99. }
  100. seenNums.Set(num)
  101. }
  102. }
  103. // Check for any missing required fields.
  104. allReqNums := msgType.RequiredNumbers()
  105. if reqNums.Len() != allReqNums.Len() {
  106. for i := 0; i < allReqNums.Len(); i++ {
  107. if num := allReqNums.Get(i); !reqNums.Has(uint64(num)) {
  108. nerr.AppendRequiredNotSet(string(fieldDescs.ByNumber(num).FullName()))
  109. }
  110. }
  111. }
  112. return nerr.E
  113. }
  114. // unmarshalSingular unmarshals given text.Value into the non-repeated field.
  115. func (o UnmarshalOptions) unmarshalSingular(input text.Value, fd pref.FieldDescriptor, knownFields pref.KnownFields) error {
  116. num := fd.Number()
  117. var nerr errors.NonFatal
  118. var val pref.Value
  119. switch fd.Kind() {
  120. case pref.MessageKind, pref.GroupKind:
  121. if input.Type() != text.Message {
  122. return errors.New("%v contains invalid message/group value: %v", fd.FullName(), input)
  123. }
  124. m := knownFields.NewMessage(num).ProtoReflect()
  125. if err := o.unmarshalMessage(input.Message(), m); !nerr.Merge(err) {
  126. return err
  127. }
  128. val = pref.ValueOf(m)
  129. default:
  130. var err error
  131. val, err = unmarshalScalar(input, fd)
  132. if !nerr.Merge(err) {
  133. return err
  134. }
  135. }
  136. knownFields.Set(num, val)
  137. return nerr.E
  138. }
  139. // unmarshalRepeated unmarshals given text.Value into a repeated field. Caller should only
  140. // call this for cardinality=repeated.
  141. func (o UnmarshalOptions) unmarshalRepeated(input text.Value, fd pref.FieldDescriptor, knownFields pref.KnownFields) error {
  142. var items []text.Value
  143. // If input is not a list, turn it into a list.
  144. if input.Type() != text.List {
  145. items = []text.Value{input}
  146. } else {
  147. items = input.List()
  148. }
  149. var nerr errors.NonFatal
  150. num := fd.Number()
  151. val := knownFields.Get(num)
  152. if !fd.IsMap() {
  153. if err := o.unmarshalList(items, fd, val.List()); !nerr.Merge(err) {
  154. return err
  155. }
  156. } else {
  157. if err := o.unmarshalMap(items, fd, val.Map()); !nerr.Merge(err) {
  158. return err
  159. }
  160. }
  161. return nerr.E
  162. }
  163. // unmarshalScalar converts the given text.Value to a scalar/enum protoreflect.Value specified in
  164. // the given FieldDescriptor. Caller should not pass in a FieldDescriptor for a message/group kind.
  165. func unmarshalScalar(input text.Value, fd pref.FieldDescriptor) (pref.Value, error) {
  166. const b32 = false
  167. const b64 = true
  168. switch kind := fd.Kind(); kind {
  169. case pref.BoolKind:
  170. if b, ok := input.Bool(); ok {
  171. return pref.ValueOf(bool(b)), nil
  172. }
  173. case pref.Int32Kind, pref.Sint32Kind, pref.Sfixed32Kind:
  174. if n, ok := input.Int(b32); ok {
  175. return pref.ValueOf(int32(n)), nil
  176. }
  177. case pref.Int64Kind, pref.Sint64Kind, pref.Sfixed64Kind:
  178. if n, ok := input.Int(b64); ok {
  179. return pref.ValueOf(int64(n)), nil
  180. }
  181. case pref.Uint32Kind, pref.Fixed32Kind:
  182. if n, ok := input.Uint(b32); ok {
  183. return pref.ValueOf(uint32(n)), nil
  184. }
  185. case pref.Uint64Kind, pref.Fixed64Kind:
  186. if n, ok := input.Uint(b64); ok {
  187. return pref.ValueOf(uint64(n)), nil
  188. }
  189. case pref.FloatKind:
  190. if n, ok := input.Float(b32); ok {
  191. return pref.ValueOf(float32(n)), nil
  192. }
  193. case pref.DoubleKind:
  194. if n, ok := input.Float(b64); ok {
  195. return pref.ValueOf(float64(n)), nil
  196. }
  197. case pref.StringKind:
  198. if input.Type() == text.String {
  199. return pref.ValueOf(string(input.String())), nil
  200. }
  201. case pref.BytesKind:
  202. if input.Type() == text.String {
  203. return pref.ValueOf([]byte(input.String())), nil
  204. }
  205. case pref.EnumKind:
  206. // If input is int32, use directly.
  207. if n, ok := input.Int(b32); ok {
  208. return pref.ValueOf(pref.EnumNumber(n)), nil
  209. } else {
  210. if name, ok := input.Name(); ok {
  211. // Lookup EnumNumber based on name.
  212. if enumVal := fd.EnumType().Values().ByName(name); enumVal != nil {
  213. return pref.ValueOf(enumVal.Number()), nil
  214. }
  215. }
  216. }
  217. default:
  218. panic(fmt.Sprintf("invalid scalar kind %v", kind))
  219. }
  220. return pref.Value{}, errors.New("%v contains invalid scalar value: %v", fd.FullName(), input)
  221. }
  222. // unmarshalList unmarshals given []text.Value into given protoreflect.List.
  223. func (o UnmarshalOptions) unmarshalList(inputList []text.Value, fd pref.FieldDescriptor, list pref.List) error {
  224. var nerr errors.NonFatal
  225. switch fd.Kind() {
  226. case pref.MessageKind, pref.GroupKind:
  227. for _, input := range inputList {
  228. if input.Type() != text.Message {
  229. return errors.New("%v contains invalid message/group value: %v", fd.FullName(), input)
  230. }
  231. m := list.NewMessage().ProtoReflect()
  232. if err := o.unmarshalMessage(input.Message(), m); !nerr.Merge(err) {
  233. return err
  234. }
  235. list.Append(pref.ValueOf(m))
  236. }
  237. default:
  238. for _, input := range inputList {
  239. val, err := unmarshalScalar(input, fd)
  240. if !nerr.Merge(err) {
  241. return err
  242. }
  243. list.Append(val)
  244. }
  245. }
  246. return nerr.E
  247. }
  248. // unmarshalMap unmarshals given []text.Value into given protoreflect.Map.
  249. func (o UnmarshalOptions) unmarshalMap(input []text.Value, fd pref.FieldDescriptor, mmap pref.Map) error {
  250. var nerr errors.NonFatal
  251. fields := fd.MessageType().Fields()
  252. keyDesc := fields.ByNumber(1)
  253. valDesc := fields.ByNumber(2)
  254. // Determine ahead whether map entry is a scalar type or a message type in order to call the
  255. // appropriate unmarshalMapValue func inside the for loop below.
  256. unmarshalMapValue := o.unmarshalMapScalarValue
  257. switch valDesc.Kind() {
  258. case pref.MessageKind, pref.GroupKind:
  259. unmarshalMapValue = o.unmarshalMapMessageValue
  260. }
  261. for _, entry := range input {
  262. if entry.Type() != text.Message {
  263. return errors.New("%v contains invalid map entry: %v", fd.FullName(), entry)
  264. }
  265. tkey, tval, err := parseMapEntry(entry.Message(), fd.FullName())
  266. if !nerr.Merge(err) {
  267. return err
  268. }
  269. pkey, err := unmarshalMapKey(tkey, keyDesc)
  270. if !nerr.Merge(err) {
  271. return err
  272. }
  273. err = unmarshalMapValue(tval, pkey, valDesc, mmap)
  274. if !nerr.Merge(err) {
  275. return err
  276. }
  277. }
  278. return nerr.E
  279. }
  280. // parseMapEntry parses [][2]text.Value for field names key and value, and return corresponding
  281. // field values. If there are duplicate field names, the value for the last field is returned. If
  282. // the field name does not exist, it will return the zero value of text.Value. It will return an
  283. // error if there are unknown field names.
  284. func parseMapEntry(mapEntry [][2]text.Value, name pref.FullName) (key text.Value, value text.Value, err error) {
  285. for _, field := range mapEntry {
  286. keyStr, ok := field[0].Name()
  287. if ok {
  288. switch keyStr {
  289. case "key":
  290. if key.Type() != 0 {
  291. return key, value, errors.New("%v contains duplicate key field", name)
  292. }
  293. key = field[1]
  294. case "value":
  295. if value.Type() != 0 {
  296. return key, value, errors.New("%v contains duplicate value field", name)
  297. }
  298. value = field[1]
  299. default:
  300. ok = false
  301. }
  302. }
  303. if !ok {
  304. // TODO: Do not return error if ignore unknown option is added and enabled.
  305. return key, value, errors.New("%v contains unknown map entry name: %v", name, field[0])
  306. }
  307. }
  308. return key, value, nil
  309. }
  310. // unmarshalMapKey converts given text.Value into a protoreflect.MapKey. A map key type is any
  311. // integral or string type.
  312. func unmarshalMapKey(input text.Value, fd pref.FieldDescriptor) (pref.MapKey, error) {
  313. // If input is not set, use the zero value.
  314. if input.Type() == 0 {
  315. return fd.Default().MapKey(), nil
  316. }
  317. val, err := unmarshalScalar(input, fd)
  318. if err != nil {
  319. return pref.MapKey{}, errors.New("%v contains invalid key: %v", fd.FullName(), input)
  320. }
  321. return val.MapKey(), nil
  322. }
  323. // unmarshalMapMessageValue unmarshals given message-type text.Value into a protoreflect.Map for
  324. // the given MapKey.
  325. func (o UnmarshalOptions) unmarshalMapMessageValue(input text.Value, pkey pref.MapKey, _ pref.FieldDescriptor, mmap pref.Map) error {
  326. var nerr errors.NonFatal
  327. var value [][2]text.Value
  328. if input.Type() != 0 {
  329. value = input.Message()
  330. }
  331. m := mmap.NewMessage().ProtoReflect()
  332. if err := o.unmarshalMessage(value, m); !nerr.Merge(err) {
  333. return err
  334. }
  335. mmap.Set(pkey, pref.ValueOf(m))
  336. return nerr.E
  337. }
  338. // unmarshalMapScalarValue unmarshals given scalar-type text.Value into a protoreflect.Map
  339. // for the given MapKey.
  340. func (o UnmarshalOptions) unmarshalMapScalarValue(input text.Value, pkey pref.MapKey, fd pref.FieldDescriptor, mmap pref.Map) error {
  341. var val pref.Value
  342. if input.Type() == 0 {
  343. val = fd.Default()
  344. } else {
  345. var err error
  346. val, err = unmarshalScalar(input, fd)
  347. if err != nil {
  348. return err
  349. }
  350. }
  351. mmap.Set(pkey, val)
  352. return nil
  353. }