encode.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  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. "sort"
  8. "github.com/golang/protobuf/v2/internal/encoding/text"
  9. "github.com/golang/protobuf/v2/internal/encoding/wire"
  10. "github.com/golang/protobuf/v2/internal/errors"
  11. "github.com/golang/protobuf/v2/internal/pragma"
  12. "github.com/golang/protobuf/v2/proto"
  13. pref "github.com/golang/protobuf/v2/reflect/protoreflect"
  14. "github.com/golang/protobuf/v2/reflect/protoregistry"
  15. descpb "github.com/golang/protobuf/v2/types/descriptor"
  16. )
  17. // Marshal writes the given proto.Message in textproto format using default options.
  18. // TODO: may want to describe when Marshal returns error.
  19. func Marshal(m proto.Message) ([]byte, error) {
  20. return MarshalOptions{}.Marshal(m)
  21. }
  22. // MarshalOptions is a configurable text format marshaler.
  23. type MarshalOptions struct {
  24. pragma.NoUnkeyedLiterals
  25. // Set Compact to true to have output in a single line with no line breaks.
  26. Compact bool
  27. // Resolver is the registry used for type lookups when marshaling out
  28. // google.protobuf.Any messages in expanded form. If Resolver is not set,
  29. // marshaling will default to using protoregistry.GlobalTypes. If a type is
  30. // not found, an Any message will be marshaled as a regular message.
  31. Resolver *protoregistry.Types
  32. }
  33. // Marshal writes the given proto.Message in textproto format using options in MarshalOptions object.
  34. func (o MarshalOptions) Marshal(m proto.Message) ([]byte, error) {
  35. if o.Resolver == nil {
  36. o.Resolver = protoregistry.GlobalTypes
  37. }
  38. var nerr errors.NonFatal
  39. var v text.Value
  40. var err error
  41. v, err = o.marshalMessage(m.ProtoReflect())
  42. if !nerr.Merge(err) {
  43. return nil, err
  44. }
  45. indent := " "
  46. if o.Compact {
  47. indent = ""
  48. }
  49. delims := [2]byte{'{', '}'}
  50. const outputASCII = false
  51. b, err := text.Marshal(v, indent, delims, outputASCII)
  52. if !nerr.Merge(err) {
  53. return nil, err
  54. }
  55. return b, nerr.E
  56. }
  57. // marshalMessage converts a protoreflect.Message to a text.Value.
  58. func (o MarshalOptions) marshalMessage(m pref.Message) (text.Value, error) {
  59. var nerr errors.NonFatal
  60. var msgFields [][2]text.Value
  61. msgType := m.Type()
  62. // Handle Any expansion.
  63. if msgType.FullName() == "google.protobuf.Any" {
  64. msg, err := o.marshalAny(m)
  65. if err == nil || nerr.Merge(err) {
  66. // Return as is for nil or non-fatal error.
  67. return msg, nerr.E
  68. }
  69. // For other errors, continue on to marshal Any as a regular message.
  70. }
  71. // Handle known fields.
  72. fieldDescs := msgType.Fields()
  73. knownFields := m.KnownFields()
  74. size := fieldDescs.Len()
  75. for i := 0; i < size; i++ {
  76. fd := fieldDescs.Get(i)
  77. num := fd.Number()
  78. if !knownFields.Has(num) {
  79. if fd.Cardinality() == pref.Required {
  80. // Treat unset required fields as a non-fatal error.
  81. nerr.AppendRequiredNotSet(string(fd.FullName()))
  82. }
  83. continue
  84. }
  85. tname := text.ValueOf(fd.Name())
  86. pval := knownFields.Get(num)
  87. var err error
  88. msgFields, err = o.appendField(msgFields, tname, pval, fd)
  89. if !nerr.Merge(err) {
  90. return text.Value{}, err
  91. }
  92. }
  93. // Handle extensions.
  94. var err error
  95. msgFields, err = o.appendExtensions(msgFields, knownFields)
  96. if !nerr.Merge(err) {
  97. return text.Value{}, err
  98. }
  99. // Handle unknown fields.
  100. // TODO: Provide option to exclude or include unknown fields.
  101. m.UnknownFields().Range(func(_ pref.FieldNumber, raw pref.RawFields) bool {
  102. msgFields = appendUnknown(msgFields, raw)
  103. return true
  104. })
  105. return text.ValueOf(msgFields), nerr.E
  106. }
  107. // appendField marshals a protoreflect.Value and appends it to the given [][2]text.Value.
  108. func (o MarshalOptions) appendField(msgFields [][2]text.Value, tname text.Value, pval pref.Value, fd pref.FieldDescriptor) ([][2]text.Value, error) {
  109. var nerr errors.NonFatal
  110. // Use type name for group field name.
  111. if fd.Kind() == pref.GroupKind {
  112. tname = text.ValueOf(fd.MessageType().Name())
  113. }
  114. if fd.Cardinality() == pref.Repeated {
  115. // Map or repeated fields.
  116. var items []text.Value
  117. var err error
  118. if fd.IsMap() {
  119. items, err = o.marshalMap(pval.Map(), fd)
  120. if !nerr.Merge(err) {
  121. return msgFields, err
  122. }
  123. } else {
  124. items, err = o.marshalList(pval.List(), fd)
  125. if !nerr.Merge(err) {
  126. return msgFields, err
  127. }
  128. }
  129. // Add each item as key: value field.
  130. for _, item := range items {
  131. msgFields = append(msgFields, [2]text.Value{tname, item})
  132. }
  133. } else {
  134. // Required or optional fields.
  135. tval, err := o.marshalSingular(pval, fd)
  136. if !nerr.Merge(err) {
  137. return msgFields, err
  138. }
  139. msgFields = append(msgFields, [2]text.Value{tname, tval})
  140. }
  141. return msgFields, nerr.E
  142. }
  143. // marshalSingular converts a non-repeated field value to text.Value.
  144. // This includes all scalar types, enums, messages, and groups.
  145. func (o MarshalOptions) marshalSingular(val pref.Value, fd pref.FieldDescriptor) (text.Value, error) {
  146. kind := fd.Kind()
  147. switch kind {
  148. case pref.BoolKind,
  149. pref.Int32Kind, pref.Sint32Kind, pref.Uint32Kind,
  150. pref.Int64Kind, pref.Sint64Kind, pref.Uint64Kind,
  151. pref.Sfixed32Kind, pref.Fixed32Kind,
  152. pref.Sfixed64Kind, pref.Fixed64Kind,
  153. pref.FloatKind, pref.DoubleKind,
  154. pref.StringKind, pref.BytesKind:
  155. return text.ValueOf(val.Interface()), nil
  156. case pref.EnumKind:
  157. num := val.Enum()
  158. if desc := fd.EnumType().Values().ByNumber(num); desc != nil {
  159. return text.ValueOf(desc.Name()), nil
  160. }
  161. // Use numeric value if there is no enum description.
  162. return text.ValueOf(int32(num)), nil
  163. case pref.MessageKind, pref.GroupKind:
  164. return o.marshalMessage(val.Message())
  165. }
  166. return text.Value{}, errors.New("%v has unknown kind: %v", fd.FullName(), kind)
  167. }
  168. // marshalList converts a protoreflect.List to []text.Value.
  169. func (o MarshalOptions) marshalList(list pref.List, fd pref.FieldDescriptor) ([]text.Value, error) {
  170. var nerr errors.NonFatal
  171. size := list.Len()
  172. values := make([]text.Value, 0, size)
  173. for i := 0; i < size; i++ {
  174. item := list.Get(i)
  175. val, err := o.marshalSingular(item, fd)
  176. if !nerr.Merge(err) {
  177. // Return already marshaled values.
  178. return values, err
  179. }
  180. values = append(values, val)
  181. }
  182. return values, nerr.E
  183. }
  184. var (
  185. mapKeyName = text.ValueOf(pref.Name("key"))
  186. mapValueName = text.ValueOf(pref.Name("value"))
  187. )
  188. // marshalMap converts a protoreflect.Map to []text.Value.
  189. func (o MarshalOptions) marshalMap(mmap pref.Map, fd pref.FieldDescriptor) ([]text.Value, error) {
  190. var nerr errors.NonFatal
  191. // values is a list of messages.
  192. values := make([]text.Value, 0, mmap.Len())
  193. msgFields := fd.MessageType().Fields()
  194. keyType := msgFields.ByNumber(1)
  195. valType := msgFields.ByNumber(2)
  196. mmap.Range(func(key pref.MapKey, val pref.Value) bool {
  197. keyTxtVal, err := o.marshalSingular(key.Value(), keyType)
  198. if !nerr.Merge(err) {
  199. return false
  200. }
  201. valTxtVal, err := o.marshalSingular(val, valType)
  202. if !nerr.Merge(err) {
  203. return false
  204. }
  205. // Map entry (message) contains 2 fields, first field for key and second field for value.
  206. msg := text.ValueOf([][2]text.Value{
  207. {mapKeyName, keyTxtVal},
  208. {mapValueName, valTxtVal},
  209. })
  210. values = append(values, msg)
  211. return true
  212. })
  213. sortMap(keyType.Kind(), values)
  214. return values, nerr.E
  215. }
  216. // sortMap orders list based on value of key field for deterministic output.
  217. // TODO: Improve sort comparison of text.Value for map keys.
  218. func sortMap(keyKind pref.Kind, values []text.Value) {
  219. less := func(i, j int) bool {
  220. mi := values[i].Message()
  221. mj := values[j].Message()
  222. return mi[0][1].String() < mj[0][1].String()
  223. }
  224. switch keyKind {
  225. case pref.Int32Kind, pref.Sint32Kind, pref.Sfixed32Kind:
  226. less = func(i, j int) bool {
  227. mi := values[i].Message()
  228. mj := values[j].Message()
  229. ni, _ := mi[0][1].Int(false)
  230. nj, _ := mj[0][1].Int(false)
  231. return ni < nj
  232. }
  233. case pref.Int64Kind, pref.Sint64Kind, pref.Sfixed64Kind:
  234. less = func(i, j int) bool {
  235. mi := values[i].Message()
  236. mj := values[j].Message()
  237. ni, _ := mi[0][1].Int(true)
  238. nj, _ := mj[0][1].Int(true)
  239. return ni < nj
  240. }
  241. case pref.Uint32Kind, pref.Fixed32Kind:
  242. less = func(i, j int) bool {
  243. mi := values[i].Message()
  244. mj := values[j].Message()
  245. ni, _ := mi[0][1].Uint(false)
  246. nj, _ := mj[0][1].Uint(false)
  247. return ni < nj
  248. }
  249. case pref.Uint64Kind, pref.Fixed64Kind:
  250. less = func(i, j int) bool {
  251. mi := values[i].Message()
  252. mj := values[j].Message()
  253. ni, _ := mi[0][1].Uint(true)
  254. nj, _ := mj[0][1].Uint(true)
  255. return ni < nj
  256. }
  257. }
  258. sort.Slice(values, less)
  259. }
  260. // appendExtensions marshals extension fields and appends them to the given [][2]text.Value.
  261. func (o MarshalOptions) appendExtensions(msgFields [][2]text.Value, knownFields pref.KnownFields) ([][2]text.Value, error) {
  262. var nerr errors.NonFatal
  263. xtTypes := knownFields.ExtensionTypes()
  264. xtFields := make([][2]text.Value, 0, xtTypes.Len())
  265. var err error
  266. xtTypes.Range(func(xt pref.ExtensionType) bool {
  267. name := xt.FullName()
  268. // If extended type is a MessageSet, set field name to be the message type name.
  269. if isMessageSetExtension(xt) {
  270. name = xt.MessageType().FullName()
  271. }
  272. num := xt.Number()
  273. if knownFields.Has(num) {
  274. // Use string type to produce [name] format.
  275. tname := text.ValueOf(string(name))
  276. pval := knownFields.Get(num)
  277. xtFields, err = o.appendField(xtFields, tname, pval, xt)
  278. if err != nil {
  279. return false
  280. }
  281. }
  282. return true
  283. })
  284. if !nerr.Merge(err) {
  285. return msgFields, err
  286. }
  287. // Sort extensions lexicographically and append to output.
  288. sort.SliceStable(xtFields, func(i, j int) bool {
  289. return xtFields[i][0].String() < xtFields[j][0].String()
  290. })
  291. return append(msgFields, xtFields...), nerr.E
  292. }
  293. // isMessageSetExtension reports whether extension extends a message set.
  294. func isMessageSetExtension(xt pref.ExtensionType) bool {
  295. if xt.Name() != "message_set_extension" {
  296. return false
  297. }
  298. mt := xt.MessageType()
  299. if mt == nil {
  300. return false
  301. }
  302. if xt.FullName().Parent() != mt.FullName() {
  303. return false
  304. }
  305. xmt := xt.ExtendedType()
  306. if xmt.Fields().Len() != 0 {
  307. return false
  308. }
  309. opt := xmt.Options().(*descpb.MessageOptions)
  310. if opt == nil {
  311. return false
  312. }
  313. return opt.GetMessageSetWireFormat()
  314. }
  315. // appendUnknown parses the given []byte and appends field(s) into the given fields slice.
  316. // This function assumes proper encoding in the given []byte.
  317. func appendUnknown(fields [][2]text.Value, b []byte) [][2]text.Value {
  318. for len(b) > 0 {
  319. var value interface{}
  320. num, wtype, n := wire.ConsumeTag(b)
  321. b = b[n:]
  322. switch wtype {
  323. case wire.VarintType:
  324. value, n = wire.ConsumeVarint(b)
  325. case wire.Fixed32Type:
  326. value, n = wire.ConsumeFixed32(b)
  327. case wire.Fixed64Type:
  328. value, n = wire.ConsumeFixed64(b)
  329. case wire.BytesType:
  330. value, n = wire.ConsumeBytes(b)
  331. case wire.StartGroupType:
  332. var v []byte
  333. v, n = wire.ConsumeGroup(num, b)
  334. var msg [][2]text.Value
  335. value = appendUnknown(msg, v)
  336. default:
  337. panic(fmt.Sprintf("error parsing unknown field wire type: %v", wtype))
  338. }
  339. fields = append(fields, [2]text.Value{text.ValueOf(uint32(num)), text.ValueOf(value)})
  340. b = b[n:]
  341. }
  342. return fields
  343. }
  344. // marshalAny converts a google.protobuf.Any protoreflect.Message to a text.Value.
  345. func (o MarshalOptions) marshalAny(m pref.Message) (text.Value, error) {
  346. var nerr errors.NonFatal
  347. fds := m.Type().Fields()
  348. tfd := fds.ByName("type_url")
  349. if tfd == nil || tfd.Kind() != pref.StringKind {
  350. return text.Value{}, errors.New("invalid google.protobuf.Any message")
  351. }
  352. vfd := fds.ByName("value")
  353. if vfd == nil || vfd.Kind() != pref.BytesKind {
  354. return text.Value{}, errors.New("invalid google.protobuf.Any message")
  355. }
  356. knownFields := m.KnownFields()
  357. typeURL := knownFields.Get(tfd.Number()).String()
  358. value := knownFields.Get(vfd.Number())
  359. emt, err := o.Resolver.FindMessageByURL(typeURL)
  360. if !nerr.Merge(err) {
  361. return text.Value{}, err
  362. }
  363. em := emt.New().Interface()
  364. // TODO: Need to set types registry in binary unmarshaling.
  365. err = proto.Unmarshal(value.Bytes(), em)
  366. if !nerr.Merge(err) {
  367. return text.Value{}, err
  368. }
  369. msg, err := o.marshalMessage(em.ProtoReflect())
  370. if !nerr.Merge(err) {
  371. return text.Value{}, err
  372. }
  373. // Expanded Any field value contains only a single field with the type_url field value as the
  374. // field name in [] and a text marshaled field value of the embedded message.
  375. msgFields := [][2]text.Value{
  376. {
  377. text.ValueOf(typeURL),
  378. msg,
  379. },
  380. }
  381. return text.ValueOf(msgFields), nerr.E
  382. }