encode.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  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 prototext
  5. import (
  6. "fmt"
  7. "sort"
  8. "unicode/utf8"
  9. "google.golang.org/protobuf/internal/encoding/messageset"
  10. "google.golang.org/protobuf/internal/encoding/text"
  11. "google.golang.org/protobuf/internal/encoding/wire"
  12. "google.golang.org/protobuf/internal/errors"
  13. "google.golang.org/protobuf/internal/fieldnum"
  14. "google.golang.org/protobuf/internal/flags"
  15. "google.golang.org/protobuf/internal/mapsort"
  16. "google.golang.org/protobuf/internal/pragma"
  17. "google.golang.org/protobuf/proto"
  18. pref "google.golang.org/protobuf/reflect/protoreflect"
  19. "google.golang.org/protobuf/reflect/protoregistry"
  20. )
  21. // Marshal writes the given proto.Message in textproto format using default
  22. // options. Do not depend on the output being stable. It may change over time
  23. // across different versions of the program.
  24. func Marshal(m proto.Message) ([]byte, error) {
  25. return MarshalOptions{}.Marshal(m)
  26. }
  27. // MarshalOptions is a configurable text format marshaler.
  28. type MarshalOptions struct {
  29. pragma.NoUnkeyedLiterals
  30. // AllowPartial allows messages that have missing required fields to marshal
  31. // without returning an error. If AllowPartial is false (the default),
  32. // Marshal will return error if there are any missing required fields.
  33. AllowPartial bool
  34. // EmitUnknown specifies whether to emit unknown fields in the output.
  35. // If specified, the unmarshaler may be unable to parse the output.
  36. // The default is to exclude unknown fields.
  37. EmitUnknown bool
  38. // If Indent is a non-empty string, it causes entries for a Message to be
  39. // preceded by the indent and trailed by a newline. Indent can only be
  40. // composed of space or tab characters.
  41. Indent string
  42. // Resolver is used for looking up types when expanding google.protobuf.Any
  43. // messages. If nil, this defaults to using protoregistry.GlobalTypes.
  44. Resolver interface {
  45. protoregistry.ExtensionTypeResolver
  46. protoregistry.MessageTypeResolver
  47. }
  48. }
  49. // Marshal writes the given proto.Message in textproto format using options in
  50. // MarshalOptions object. Do not depend on the output being stable. It may
  51. // change over time across different versions of the program.
  52. func (o MarshalOptions) Marshal(m proto.Message) ([]byte, error) {
  53. if o.Resolver == nil {
  54. o.Resolver = protoregistry.GlobalTypes
  55. }
  56. v, err := o.marshalMessage(m.ProtoReflect())
  57. if err != nil {
  58. return nil, err
  59. }
  60. delims := [2]byte{'{', '}'}
  61. const outputASCII = false
  62. b, err := text.Marshal(v, o.Indent, delims, outputASCII)
  63. if err != nil {
  64. return nil, err
  65. }
  66. if o.AllowPartial {
  67. return b, nil
  68. }
  69. return b, proto.IsInitialized(m)
  70. }
  71. // marshalMessage converts a protoreflect.Message to a text.Value.
  72. func (o MarshalOptions) marshalMessage(m pref.Message) (text.Value, error) {
  73. messageDesc := m.Descriptor()
  74. if !flags.ProtoLegacy && messageset.IsMessageSet(messageDesc) {
  75. return text.Value{}, errors.New("no support for proto1 MessageSets")
  76. }
  77. // Handle Any expansion.
  78. if messageDesc.FullName() == "google.protobuf.Any" {
  79. if msg, err := o.marshalAny(m); err == nil {
  80. // Return as is if no error.
  81. return msg, nil
  82. }
  83. // Otherwise continue on to marshal Any as a regular message.
  84. }
  85. // Handle known fields.
  86. var msgFields [][2]text.Value
  87. fieldDescs := messageDesc.Fields()
  88. size := fieldDescs.Len()
  89. for i := 0; i < size; {
  90. fd := fieldDescs.Get(i)
  91. if od := fd.ContainingOneof(); od != nil {
  92. fd = m.WhichOneof(od)
  93. i += od.Fields().Len()
  94. } else {
  95. i++
  96. }
  97. if fd == nil || !m.Has(fd) {
  98. continue
  99. }
  100. name := text.ValueOf(fd.Name())
  101. // Use type name for group field name.
  102. if fd.Kind() == pref.GroupKind {
  103. name = text.ValueOf(fd.Message().Name())
  104. }
  105. pval := m.Get(fd)
  106. var err error
  107. msgFields, err = o.appendField(msgFields, name, pval, fd)
  108. if err != nil {
  109. return text.Value{}, err
  110. }
  111. }
  112. // Handle extensions.
  113. var err error
  114. msgFields, err = o.appendExtensions(msgFields, m)
  115. if err != nil {
  116. return text.Value{}, err
  117. }
  118. // Handle unknown fields.
  119. if o.EmitUnknown {
  120. msgFields = appendUnknown(msgFields, m.GetUnknown())
  121. }
  122. return text.ValueOf(msgFields), nil
  123. }
  124. // appendField marshals a protoreflect.Value and appends it to the given [][2]text.Value.
  125. func (o MarshalOptions) appendField(msgFields [][2]text.Value, name text.Value, pval pref.Value, fd pref.FieldDescriptor) ([][2]text.Value, error) {
  126. switch {
  127. case fd.IsList():
  128. items, err := o.marshalList(pval.List(), fd)
  129. if err != nil {
  130. return msgFields, err
  131. }
  132. for _, item := range items {
  133. msgFields = append(msgFields, [2]text.Value{name, item})
  134. }
  135. case fd.IsMap():
  136. items, err := o.marshalMap(pval.Map(), fd)
  137. if err != nil {
  138. return msgFields, err
  139. }
  140. for _, item := range items {
  141. msgFields = append(msgFields, [2]text.Value{name, item})
  142. }
  143. default:
  144. tval, err := o.marshalSingular(pval, fd)
  145. if err != nil {
  146. return msgFields, err
  147. }
  148. msgFields = append(msgFields, [2]text.Value{name, tval})
  149. }
  150. return msgFields, nil
  151. }
  152. // marshalSingular converts a non-repeated field value to text.Value.
  153. // This includes all scalar types, enums, messages, and groups.
  154. func (o MarshalOptions) marshalSingular(val pref.Value, fd pref.FieldDescriptor) (text.Value, error) {
  155. kind := fd.Kind()
  156. switch kind {
  157. case pref.BoolKind,
  158. pref.Int32Kind, pref.Sint32Kind, pref.Uint32Kind,
  159. pref.Int64Kind, pref.Sint64Kind, pref.Uint64Kind,
  160. pref.Sfixed32Kind, pref.Fixed32Kind,
  161. pref.Sfixed64Kind, pref.Fixed64Kind,
  162. pref.FloatKind, pref.DoubleKind,
  163. pref.BytesKind:
  164. return text.ValueOf(val.Interface()), nil
  165. case pref.StringKind:
  166. s := val.String()
  167. if !utf8.ValidString(s) {
  168. return text.Value{}, errors.InvalidUTF8(string(fd.FullName()))
  169. }
  170. return text.ValueOf(s), nil
  171. case pref.EnumKind:
  172. num := val.Enum()
  173. if desc := fd.Enum().Values().ByNumber(num); desc != nil {
  174. return text.ValueOf(desc.Name()), nil
  175. }
  176. // Use numeric value if there is no enum description.
  177. return text.ValueOf(int32(num)), nil
  178. case pref.MessageKind, pref.GroupKind:
  179. return o.marshalMessage(val.Message())
  180. }
  181. panic(fmt.Sprintf("%v has unknown kind: %v", fd.FullName(), kind))
  182. }
  183. // marshalList converts a protoreflect.List to []text.Value.
  184. func (o MarshalOptions) marshalList(list pref.List, fd pref.FieldDescriptor) ([]text.Value, error) {
  185. size := list.Len()
  186. values := make([]text.Value, 0, size)
  187. for i := 0; i < size; i++ {
  188. item := list.Get(i)
  189. val, err := o.marshalSingular(item, fd)
  190. if err != nil {
  191. // Return already marshaled values.
  192. return values, err
  193. }
  194. values = append(values, val)
  195. }
  196. return values, nil
  197. }
  198. var (
  199. mapKeyName = text.ValueOf(pref.Name("key"))
  200. mapValueName = text.ValueOf(pref.Name("value"))
  201. )
  202. // marshalMap converts a protoreflect.Map to []text.Value.
  203. func (o MarshalOptions) marshalMap(mmap pref.Map, fd pref.FieldDescriptor) ([]text.Value, error) {
  204. // values is a list of messages.
  205. values := make([]text.Value, 0, mmap.Len())
  206. var err error
  207. mapsort.Range(mmap, fd.MapKey().Kind(), func(key pref.MapKey, val pref.Value) bool {
  208. var keyTxtVal text.Value
  209. keyTxtVal, err = o.marshalSingular(key.Value(), fd.MapKey())
  210. if err != nil {
  211. return false
  212. }
  213. var valTxtVal text.Value
  214. valTxtVal, err = o.marshalSingular(val, fd.MapValue())
  215. if err != nil {
  216. return false
  217. }
  218. // Map entry (message) contains 2 fields, first field for key and second field for value.
  219. msg := text.ValueOf([][2]text.Value{
  220. {mapKeyName, keyTxtVal},
  221. {mapValueName, valTxtVal},
  222. })
  223. values = append(values, msg)
  224. err = nil
  225. return true
  226. })
  227. if err != nil {
  228. return nil, err
  229. }
  230. return values, nil
  231. }
  232. // appendExtensions marshals extension fields and appends them to the given [][2]text.Value.
  233. func (o MarshalOptions) appendExtensions(msgFields [][2]text.Value, m pref.Message) ([][2]text.Value, error) {
  234. var err error
  235. var entries [][2]text.Value
  236. m.Range(func(fd pref.FieldDescriptor, v pref.Value) bool {
  237. if !fd.IsExtension() {
  238. return true
  239. }
  240. // For MessageSet extensions, the name used is the parent message.
  241. name := fd.FullName()
  242. if messageset.IsMessageSetExtension(fd) {
  243. name = name.Parent()
  244. }
  245. // Use string type to produce [name] format.
  246. tname := text.ValueOf(string(name))
  247. entries, err = o.appendField(entries, tname, v, fd)
  248. if err != nil {
  249. return false
  250. }
  251. err = nil
  252. return true
  253. })
  254. if err != nil {
  255. return msgFields, err
  256. }
  257. // Sort extensions lexicographically and append to output.
  258. sort.SliceStable(entries, func(i, j int) bool {
  259. return entries[i][0].String() < entries[j][0].String()
  260. })
  261. return append(msgFields, entries...), nil
  262. }
  263. // appendUnknown parses the given []byte and appends field(s) into the given fields slice.
  264. // This function assumes proper encoding in the given []byte.
  265. func appendUnknown(fields [][2]text.Value, b []byte) [][2]text.Value {
  266. for len(b) > 0 {
  267. var value interface{}
  268. num, wtype, n := wire.ConsumeTag(b)
  269. b = b[n:]
  270. switch wtype {
  271. case wire.VarintType:
  272. value, n = wire.ConsumeVarint(b)
  273. case wire.Fixed32Type:
  274. value, n = wire.ConsumeFixed32(b)
  275. case wire.Fixed64Type:
  276. value, n = wire.ConsumeFixed64(b)
  277. case wire.BytesType:
  278. value, n = wire.ConsumeBytes(b)
  279. case wire.StartGroupType:
  280. var v []byte
  281. v, n = wire.ConsumeGroup(num, b)
  282. var msg [][2]text.Value
  283. value = appendUnknown(msg, v)
  284. default:
  285. panic(fmt.Sprintf("error parsing unknown field wire type: %v", wtype))
  286. }
  287. fields = append(fields, [2]text.Value{text.ValueOf(uint32(num)), text.ValueOf(value)})
  288. b = b[n:]
  289. }
  290. return fields
  291. }
  292. // marshalAny converts a google.protobuf.Any protoreflect.Message to a text.Value.
  293. func (o MarshalOptions) marshalAny(m pref.Message) (text.Value, error) {
  294. fds := m.Descriptor().Fields()
  295. fdType := fds.ByNumber(fieldnum.Any_TypeUrl)
  296. fdValue := fds.ByNumber(fieldnum.Any_Value)
  297. typeURL := m.Get(fdType).String()
  298. value := m.Get(fdValue)
  299. emt, err := o.Resolver.FindMessageByURL(typeURL)
  300. if err != nil {
  301. return text.Value{}, err
  302. }
  303. em := emt.New().Interface()
  304. err = proto.UnmarshalOptions{
  305. AllowPartial: true,
  306. Resolver: o.Resolver,
  307. }.Unmarshal(value.Bytes(), em)
  308. if err != nil {
  309. return text.Value{}, err
  310. }
  311. msg, err := o.marshalMessage(em.ProtoReflect())
  312. if err != nil {
  313. return text.Value{}, err
  314. }
  315. // Expanded Any field value contains only a single field with the type_url field value as the
  316. // field name in [] and a text marshaled field value of the embedded message.
  317. msgFields := [][2]text.Value{
  318. {
  319. text.ValueOf(typeURL),
  320. msg,
  321. },
  322. }
  323. return text.ValueOf(msgFields), nil
  324. }