decode.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767
  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. "unicode/utf8"
  8. "google.golang.org/protobuf/internal/encoding/messageset"
  9. "google.golang.org/protobuf/internal/encoding/text"
  10. "google.golang.org/protobuf/internal/errors"
  11. "google.golang.org/protobuf/internal/flags"
  12. "google.golang.org/protobuf/internal/genid"
  13. "google.golang.org/protobuf/internal/pragma"
  14. "google.golang.org/protobuf/internal/set"
  15. "google.golang.org/protobuf/internal/strs"
  16. "google.golang.org/protobuf/proto"
  17. "google.golang.org/protobuf/reflect/protoreflect"
  18. "google.golang.org/protobuf/reflect/protoregistry"
  19. )
  20. // Unmarshal reads the given []byte into the given [proto.Message].
  21. // The provided message must be mutable (e.g., a non-nil pointer to a message).
  22. func Unmarshal(b []byte, m proto.Message) error {
  23. return UnmarshalOptions{}.Unmarshal(b, m)
  24. }
  25. // UnmarshalOptions is a configurable textproto format unmarshaler.
  26. type UnmarshalOptions struct {
  27. pragma.NoUnkeyedLiterals
  28. // AllowPartial accepts input for messages that will result in missing
  29. // required fields. If AllowPartial is false (the default), Unmarshal will
  30. // return error if there are any missing required fields.
  31. AllowPartial bool
  32. // DiscardUnknown specifies whether to ignore unknown fields when parsing.
  33. // An unknown field is any field whose field name or field number does not
  34. // resolve to any known or extension field in the message.
  35. // By default, unmarshal rejects unknown fields as an error.
  36. DiscardUnknown bool
  37. // Resolver is used for looking up types when unmarshaling
  38. // google.protobuf.Any messages or extension fields.
  39. // If nil, this defaults to using protoregistry.GlobalTypes.
  40. Resolver interface {
  41. protoregistry.MessageTypeResolver
  42. protoregistry.ExtensionTypeResolver
  43. }
  44. }
  45. // Unmarshal reads the given []byte and populates the given [proto.Message]
  46. // using options in the UnmarshalOptions object.
  47. // The provided message must be mutable (e.g., a non-nil pointer to a message).
  48. func (o UnmarshalOptions) Unmarshal(b []byte, m proto.Message) error {
  49. return o.unmarshal(b, m)
  50. }
  51. // unmarshal is a centralized function that all unmarshal operations go through.
  52. // For profiling purposes, avoid changing the name of this function or
  53. // introducing other code paths for unmarshal that do not go through this.
  54. func (o UnmarshalOptions) unmarshal(b []byte, m proto.Message) error {
  55. proto.Reset(m)
  56. if o.Resolver == nil {
  57. o.Resolver = protoregistry.GlobalTypes
  58. }
  59. dec := decoder{text.NewDecoder(b), o}
  60. if err := dec.unmarshalMessage(m.ProtoReflect(), false); err != nil {
  61. return err
  62. }
  63. if o.AllowPartial {
  64. return nil
  65. }
  66. return proto.CheckInitialized(m)
  67. }
  68. type decoder struct {
  69. *text.Decoder
  70. opts UnmarshalOptions
  71. }
  72. // newError returns an error object with position info.
  73. func (d decoder) newError(pos int, f string, x ...any) error {
  74. line, column := d.Position(pos)
  75. head := fmt.Sprintf("(line %d:%d): ", line, column)
  76. return errors.New(head+f, x...)
  77. }
  78. // unexpectedTokenError returns a syntax error for the given unexpected token.
  79. func (d decoder) unexpectedTokenError(tok text.Token) error {
  80. return d.syntaxError(tok.Pos(), "unexpected token: %s", tok.RawString())
  81. }
  82. // syntaxError returns a syntax error for given position.
  83. func (d decoder) syntaxError(pos int, f string, x ...any) error {
  84. line, column := d.Position(pos)
  85. head := fmt.Sprintf("syntax error (line %d:%d): ", line, column)
  86. return errors.New(head+f, x...)
  87. }
  88. // unmarshalMessage unmarshals into the given protoreflect.Message.
  89. func (d decoder) unmarshalMessage(m protoreflect.Message, checkDelims bool) error {
  90. messageDesc := m.Descriptor()
  91. if !flags.ProtoLegacy && messageset.IsMessageSet(messageDesc) {
  92. return errors.New("no support for proto1 MessageSets")
  93. }
  94. if messageDesc.FullName() == genid.Any_message_fullname {
  95. return d.unmarshalAny(m, checkDelims)
  96. }
  97. if checkDelims {
  98. tok, err := d.Read()
  99. if err != nil {
  100. return err
  101. }
  102. if tok.Kind() != text.MessageOpen {
  103. return d.unexpectedTokenError(tok)
  104. }
  105. }
  106. var seenNums set.Ints
  107. var seenOneofs set.Ints
  108. fieldDescs := messageDesc.Fields()
  109. for {
  110. // Read field name.
  111. tok, err := d.Read()
  112. if err != nil {
  113. return err
  114. }
  115. switch typ := tok.Kind(); typ {
  116. case text.Name:
  117. // Continue below.
  118. case text.EOF:
  119. if checkDelims {
  120. return text.ErrUnexpectedEOF
  121. }
  122. return nil
  123. default:
  124. if checkDelims && typ == text.MessageClose {
  125. return nil
  126. }
  127. return d.unexpectedTokenError(tok)
  128. }
  129. // Resolve the field descriptor.
  130. var name protoreflect.Name
  131. var fd protoreflect.FieldDescriptor
  132. var xt protoreflect.ExtensionType
  133. var xtErr error
  134. var isFieldNumberName bool
  135. switch tok.NameKind() {
  136. case text.IdentName:
  137. name = protoreflect.Name(tok.IdentName())
  138. fd = fieldDescs.ByTextName(string(name))
  139. case text.TypeName:
  140. // Handle extensions only. This code path is not for Any.
  141. xt, xtErr = d.opts.Resolver.FindExtensionByName(protoreflect.FullName(tok.TypeName()))
  142. case text.FieldNumber:
  143. isFieldNumberName = true
  144. num := protoreflect.FieldNumber(tok.FieldNumber())
  145. if !num.IsValid() {
  146. return d.newError(tok.Pos(), "invalid field number: %d", num)
  147. }
  148. fd = fieldDescs.ByNumber(num)
  149. if fd == nil {
  150. xt, xtErr = d.opts.Resolver.FindExtensionByNumber(messageDesc.FullName(), num)
  151. }
  152. }
  153. if xt != nil {
  154. fd = xt.TypeDescriptor()
  155. if !messageDesc.ExtensionRanges().Has(fd.Number()) || fd.ContainingMessage().FullName() != messageDesc.FullName() {
  156. return d.newError(tok.Pos(), "message %v cannot be extended by %v", messageDesc.FullName(), fd.FullName())
  157. }
  158. } else if xtErr != nil && xtErr != protoregistry.NotFound {
  159. return d.newError(tok.Pos(), "unable to resolve [%s]: %v", tok.RawString(), xtErr)
  160. }
  161. // Handle unknown fields.
  162. if fd == nil {
  163. if d.opts.DiscardUnknown || messageDesc.ReservedNames().Has(name) {
  164. d.skipValue()
  165. continue
  166. }
  167. return d.newError(tok.Pos(), "unknown field: %v", tok.RawString())
  168. }
  169. // Handle fields identified by field number.
  170. if isFieldNumberName {
  171. // TODO: Add an option to permit parsing field numbers.
  172. //
  173. // This requires careful thought as the MarshalOptions.EmitUnknown
  174. // option allows formatting unknown fields as the field number and the
  175. // best-effort textual representation of the field value. In that case,
  176. // it may not be possible to unmarshal the value from a parser that does
  177. // have information about the unknown field.
  178. return d.newError(tok.Pos(), "cannot specify field by number: %v", tok.RawString())
  179. }
  180. switch {
  181. case fd.IsList():
  182. kind := fd.Kind()
  183. if kind != protoreflect.MessageKind && kind != protoreflect.GroupKind && !tok.HasSeparator() {
  184. return d.syntaxError(tok.Pos(), "missing field separator :")
  185. }
  186. list := m.Mutable(fd).List()
  187. if err := d.unmarshalList(fd, list); err != nil {
  188. return err
  189. }
  190. case fd.IsMap():
  191. mmap := m.Mutable(fd).Map()
  192. if err := d.unmarshalMap(fd, mmap); err != nil {
  193. return err
  194. }
  195. default:
  196. kind := fd.Kind()
  197. if kind != protoreflect.MessageKind && kind != protoreflect.GroupKind && !tok.HasSeparator() {
  198. return d.syntaxError(tok.Pos(), "missing field separator :")
  199. }
  200. // If field is a oneof, check if it has already been set.
  201. if od := fd.ContainingOneof(); od != nil {
  202. idx := uint64(od.Index())
  203. if seenOneofs.Has(idx) {
  204. return d.newError(tok.Pos(), "error parsing %q, oneof %v is already set", tok.RawString(), od.FullName())
  205. }
  206. seenOneofs.Set(idx)
  207. }
  208. num := uint64(fd.Number())
  209. if seenNums.Has(num) {
  210. return d.newError(tok.Pos(), "non-repeated field %q is repeated", tok.RawString())
  211. }
  212. if err := d.unmarshalSingular(fd, m); err != nil {
  213. return err
  214. }
  215. seenNums.Set(num)
  216. }
  217. }
  218. return nil
  219. }
  220. // unmarshalSingular unmarshals a non-repeated field value specified by the
  221. // given FieldDescriptor.
  222. func (d decoder) unmarshalSingular(fd protoreflect.FieldDescriptor, m protoreflect.Message) error {
  223. var val protoreflect.Value
  224. var err error
  225. switch fd.Kind() {
  226. case protoreflect.MessageKind, protoreflect.GroupKind:
  227. val = m.NewField(fd)
  228. err = d.unmarshalMessage(val.Message(), true)
  229. default:
  230. val, err = d.unmarshalScalar(fd)
  231. }
  232. if err == nil {
  233. m.Set(fd, val)
  234. }
  235. return err
  236. }
  237. // unmarshalScalar unmarshals a scalar/enum protoreflect.Value specified by the
  238. // given FieldDescriptor.
  239. func (d decoder) unmarshalScalar(fd protoreflect.FieldDescriptor) (protoreflect.Value, error) {
  240. tok, err := d.Read()
  241. if err != nil {
  242. return protoreflect.Value{}, err
  243. }
  244. if tok.Kind() != text.Scalar {
  245. return protoreflect.Value{}, d.unexpectedTokenError(tok)
  246. }
  247. kind := fd.Kind()
  248. switch kind {
  249. case protoreflect.BoolKind:
  250. if b, ok := tok.Bool(); ok {
  251. return protoreflect.ValueOfBool(b), nil
  252. }
  253. case protoreflect.Int32Kind, protoreflect.Sint32Kind, protoreflect.Sfixed32Kind:
  254. if n, ok := tok.Int32(); ok {
  255. return protoreflect.ValueOfInt32(n), nil
  256. }
  257. case protoreflect.Int64Kind, protoreflect.Sint64Kind, protoreflect.Sfixed64Kind:
  258. if n, ok := tok.Int64(); ok {
  259. return protoreflect.ValueOfInt64(n), nil
  260. }
  261. case protoreflect.Uint32Kind, protoreflect.Fixed32Kind:
  262. if n, ok := tok.Uint32(); ok {
  263. return protoreflect.ValueOfUint32(n), nil
  264. }
  265. case protoreflect.Uint64Kind, protoreflect.Fixed64Kind:
  266. if n, ok := tok.Uint64(); ok {
  267. return protoreflect.ValueOfUint64(n), nil
  268. }
  269. case protoreflect.FloatKind:
  270. if n, ok := tok.Float32(); ok {
  271. return protoreflect.ValueOfFloat32(n), nil
  272. }
  273. case protoreflect.DoubleKind:
  274. if n, ok := tok.Float64(); ok {
  275. return protoreflect.ValueOfFloat64(n), nil
  276. }
  277. case protoreflect.StringKind:
  278. if s, ok := tok.String(); ok {
  279. if strs.EnforceUTF8(fd) && !utf8.ValidString(s) {
  280. return protoreflect.Value{}, d.newError(tok.Pos(), "contains invalid UTF-8")
  281. }
  282. return protoreflect.ValueOfString(s), nil
  283. }
  284. case protoreflect.BytesKind:
  285. if b, ok := tok.String(); ok {
  286. return protoreflect.ValueOfBytes([]byte(b)), nil
  287. }
  288. case protoreflect.EnumKind:
  289. if lit, ok := tok.Enum(); ok {
  290. // Lookup EnumNumber based on name.
  291. if enumVal := fd.Enum().Values().ByName(protoreflect.Name(lit)); enumVal != nil {
  292. return protoreflect.ValueOfEnum(enumVal.Number()), nil
  293. }
  294. }
  295. if num, ok := tok.Int32(); ok {
  296. return protoreflect.ValueOfEnum(protoreflect.EnumNumber(num)), nil
  297. }
  298. default:
  299. panic(fmt.Sprintf("invalid scalar kind %v", kind))
  300. }
  301. return protoreflect.Value{}, d.newError(tok.Pos(), "invalid value for %v type: %v", kind, tok.RawString())
  302. }
  303. // unmarshalList unmarshals into given protoreflect.List. A list value can
  304. // either be in [] syntax or simply just a single scalar/message value.
  305. func (d decoder) unmarshalList(fd protoreflect.FieldDescriptor, list protoreflect.List) error {
  306. tok, err := d.Peek()
  307. if err != nil {
  308. return err
  309. }
  310. switch fd.Kind() {
  311. case protoreflect.MessageKind, protoreflect.GroupKind:
  312. switch tok.Kind() {
  313. case text.ListOpen:
  314. d.Read()
  315. for {
  316. tok, err := d.Peek()
  317. if err != nil {
  318. return err
  319. }
  320. switch tok.Kind() {
  321. case text.ListClose:
  322. d.Read()
  323. return nil
  324. case text.MessageOpen:
  325. pval := list.NewElement()
  326. if err := d.unmarshalMessage(pval.Message(), true); err != nil {
  327. return err
  328. }
  329. list.Append(pval)
  330. default:
  331. return d.unexpectedTokenError(tok)
  332. }
  333. }
  334. case text.MessageOpen:
  335. pval := list.NewElement()
  336. if err := d.unmarshalMessage(pval.Message(), true); err != nil {
  337. return err
  338. }
  339. list.Append(pval)
  340. return nil
  341. }
  342. default:
  343. switch tok.Kind() {
  344. case text.ListOpen:
  345. d.Read()
  346. for {
  347. tok, err := d.Peek()
  348. if err != nil {
  349. return err
  350. }
  351. switch tok.Kind() {
  352. case text.ListClose:
  353. d.Read()
  354. return nil
  355. case text.Scalar:
  356. pval, err := d.unmarshalScalar(fd)
  357. if err != nil {
  358. return err
  359. }
  360. list.Append(pval)
  361. default:
  362. return d.unexpectedTokenError(tok)
  363. }
  364. }
  365. case text.Scalar:
  366. pval, err := d.unmarshalScalar(fd)
  367. if err != nil {
  368. return err
  369. }
  370. list.Append(pval)
  371. return nil
  372. }
  373. }
  374. return d.unexpectedTokenError(tok)
  375. }
  376. // unmarshalMap unmarshals into given protoreflect.Map. A map value is a
  377. // textproto message containing {key: <kvalue>, value: <mvalue>}.
  378. func (d decoder) unmarshalMap(fd protoreflect.FieldDescriptor, mmap protoreflect.Map) error {
  379. // Determine ahead whether map entry is a scalar type or a message type in
  380. // order to call the appropriate unmarshalMapValue func inside
  381. // unmarshalMapEntry.
  382. var unmarshalMapValue func() (protoreflect.Value, error)
  383. switch fd.MapValue().Kind() {
  384. case protoreflect.MessageKind, protoreflect.GroupKind:
  385. unmarshalMapValue = func() (protoreflect.Value, error) {
  386. pval := mmap.NewValue()
  387. if err := d.unmarshalMessage(pval.Message(), true); err != nil {
  388. return protoreflect.Value{}, err
  389. }
  390. return pval, nil
  391. }
  392. default:
  393. unmarshalMapValue = func() (protoreflect.Value, error) {
  394. return d.unmarshalScalar(fd.MapValue())
  395. }
  396. }
  397. tok, err := d.Read()
  398. if err != nil {
  399. return err
  400. }
  401. switch tok.Kind() {
  402. case text.MessageOpen:
  403. return d.unmarshalMapEntry(fd, mmap, unmarshalMapValue)
  404. case text.ListOpen:
  405. for {
  406. tok, err := d.Read()
  407. if err != nil {
  408. return err
  409. }
  410. switch tok.Kind() {
  411. case text.ListClose:
  412. return nil
  413. case text.MessageOpen:
  414. if err := d.unmarshalMapEntry(fd, mmap, unmarshalMapValue); err != nil {
  415. return err
  416. }
  417. default:
  418. return d.unexpectedTokenError(tok)
  419. }
  420. }
  421. default:
  422. return d.unexpectedTokenError(tok)
  423. }
  424. }
  425. // unmarshalMap unmarshals into given protoreflect.Map. A map value is a
  426. // textproto message containing {key: <kvalue>, value: <mvalue>}.
  427. func (d decoder) unmarshalMapEntry(fd protoreflect.FieldDescriptor, mmap protoreflect.Map, unmarshalMapValue func() (protoreflect.Value, error)) error {
  428. var key protoreflect.MapKey
  429. var pval protoreflect.Value
  430. Loop:
  431. for {
  432. // Read field name.
  433. tok, err := d.Read()
  434. if err != nil {
  435. return err
  436. }
  437. switch tok.Kind() {
  438. case text.Name:
  439. if tok.NameKind() != text.IdentName {
  440. if !d.opts.DiscardUnknown {
  441. return d.newError(tok.Pos(), "unknown map entry field %q", tok.RawString())
  442. }
  443. d.skipValue()
  444. continue Loop
  445. }
  446. // Continue below.
  447. case text.MessageClose:
  448. break Loop
  449. default:
  450. return d.unexpectedTokenError(tok)
  451. }
  452. switch name := protoreflect.Name(tok.IdentName()); name {
  453. case genid.MapEntry_Key_field_name:
  454. if !tok.HasSeparator() {
  455. return d.syntaxError(tok.Pos(), "missing field separator :")
  456. }
  457. if key.IsValid() {
  458. return d.newError(tok.Pos(), "map entry %q cannot be repeated", name)
  459. }
  460. val, err := d.unmarshalScalar(fd.MapKey())
  461. if err != nil {
  462. return err
  463. }
  464. key = val.MapKey()
  465. case genid.MapEntry_Value_field_name:
  466. if kind := fd.MapValue().Kind(); (kind != protoreflect.MessageKind) && (kind != protoreflect.GroupKind) {
  467. if !tok.HasSeparator() {
  468. return d.syntaxError(tok.Pos(), "missing field separator :")
  469. }
  470. }
  471. if pval.IsValid() {
  472. return d.newError(tok.Pos(), "map entry %q cannot be repeated", name)
  473. }
  474. pval, err = unmarshalMapValue()
  475. if err != nil {
  476. return err
  477. }
  478. default:
  479. if !d.opts.DiscardUnknown {
  480. return d.newError(tok.Pos(), "unknown map entry field %q", name)
  481. }
  482. d.skipValue()
  483. }
  484. }
  485. if !key.IsValid() {
  486. key = fd.MapKey().Default().MapKey()
  487. }
  488. if !pval.IsValid() {
  489. switch fd.MapValue().Kind() {
  490. case protoreflect.MessageKind, protoreflect.GroupKind:
  491. // If value field is not set for message/group types, construct an
  492. // empty one as default.
  493. pval = mmap.NewValue()
  494. default:
  495. pval = fd.MapValue().Default()
  496. }
  497. }
  498. mmap.Set(key, pval)
  499. return nil
  500. }
  501. // unmarshalAny unmarshals an Any textproto. It can either be in expanded form
  502. // or non-expanded form.
  503. func (d decoder) unmarshalAny(m protoreflect.Message, checkDelims bool) error {
  504. var typeURL string
  505. var bValue []byte
  506. var seenTypeUrl bool
  507. var seenValue bool
  508. var isExpanded bool
  509. if checkDelims {
  510. tok, err := d.Read()
  511. if err != nil {
  512. return err
  513. }
  514. if tok.Kind() != text.MessageOpen {
  515. return d.unexpectedTokenError(tok)
  516. }
  517. }
  518. Loop:
  519. for {
  520. // Read field name. Can only have 3 possible field names, i.e. type_url,
  521. // value and type URL name inside [].
  522. tok, err := d.Read()
  523. if err != nil {
  524. return err
  525. }
  526. if typ := tok.Kind(); typ != text.Name {
  527. if checkDelims {
  528. if typ == text.MessageClose {
  529. break Loop
  530. }
  531. } else if typ == text.EOF {
  532. break Loop
  533. }
  534. return d.unexpectedTokenError(tok)
  535. }
  536. switch tok.NameKind() {
  537. case text.IdentName:
  538. // Both type_url and value fields require field separator :.
  539. if !tok.HasSeparator() {
  540. return d.syntaxError(tok.Pos(), "missing field separator :")
  541. }
  542. switch name := protoreflect.Name(tok.IdentName()); name {
  543. case genid.Any_TypeUrl_field_name:
  544. if seenTypeUrl {
  545. return d.newError(tok.Pos(), "duplicate %v field", genid.Any_TypeUrl_field_fullname)
  546. }
  547. if isExpanded {
  548. return d.newError(tok.Pos(), "conflict with [%s] field", typeURL)
  549. }
  550. tok, err := d.Read()
  551. if err != nil {
  552. return err
  553. }
  554. var ok bool
  555. typeURL, ok = tok.String()
  556. if !ok {
  557. return d.newError(tok.Pos(), "invalid %v field value: %v", genid.Any_TypeUrl_field_fullname, tok.RawString())
  558. }
  559. seenTypeUrl = true
  560. case genid.Any_Value_field_name:
  561. if seenValue {
  562. return d.newError(tok.Pos(), "duplicate %v field", genid.Any_Value_field_fullname)
  563. }
  564. if isExpanded {
  565. return d.newError(tok.Pos(), "conflict with [%s] field", typeURL)
  566. }
  567. tok, err := d.Read()
  568. if err != nil {
  569. return err
  570. }
  571. s, ok := tok.String()
  572. if !ok {
  573. return d.newError(tok.Pos(), "invalid %v field value: %v", genid.Any_Value_field_fullname, tok.RawString())
  574. }
  575. bValue = []byte(s)
  576. seenValue = true
  577. default:
  578. if !d.opts.DiscardUnknown {
  579. return d.newError(tok.Pos(), "invalid field name %q in %v message", tok.RawString(), genid.Any_message_fullname)
  580. }
  581. }
  582. case text.TypeName:
  583. if isExpanded {
  584. return d.newError(tok.Pos(), "cannot have more than one type")
  585. }
  586. if seenTypeUrl {
  587. return d.newError(tok.Pos(), "conflict with type_url field")
  588. }
  589. typeURL = tok.TypeName()
  590. var err error
  591. bValue, err = d.unmarshalExpandedAny(typeURL, tok.Pos())
  592. if err != nil {
  593. return err
  594. }
  595. isExpanded = true
  596. default:
  597. if !d.opts.DiscardUnknown {
  598. return d.newError(tok.Pos(), "invalid field name %q in %v message", tok.RawString(), genid.Any_message_fullname)
  599. }
  600. }
  601. }
  602. fds := m.Descriptor().Fields()
  603. if len(typeURL) > 0 {
  604. m.Set(fds.ByNumber(genid.Any_TypeUrl_field_number), protoreflect.ValueOfString(typeURL))
  605. }
  606. if len(bValue) > 0 {
  607. m.Set(fds.ByNumber(genid.Any_Value_field_number), protoreflect.ValueOfBytes(bValue))
  608. }
  609. return nil
  610. }
  611. func (d decoder) unmarshalExpandedAny(typeURL string, pos int) ([]byte, error) {
  612. mt, err := d.opts.Resolver.FindMessageByURL(typeURL)
  613. if err != nil {
  614. return nil, d.newError(pos, "unable to resolve message [%v]: %v", typeURL, err)
  615. }
  616. // Create new message for the embedded message type and unmarshal the value
  617. // field into it.
  618. m := mt.New()
  619. if err := d.unmarshalMessage(m, true); err != nil {
  620. return nil, err
  621. }
  622. // Serialize the embedded message and return the resulting bytes.
  623. b, err := proto.MarshalOptions{
  624. AllowPartial: true, // Never check required fields inside an Any.
  625. Deterministic: true,
  626. }.Marshal(m.Interface())
  627. if err != nil {
  628. return nil, d.newError(pos, "error in marshaling message into Any.value: %v", err)
  629. }
  630. return b, nil
  631. }
  632. // skipValue makes the decoder parse a field value in order to advance the read
  633. // to the next field. It relies on Read returning an error if the types are not
  634. // in valid sequence.
  635. func (d decoder) skipValue() error {
  636. tok, err := d.Read()
  637. if err != nil {
  638. return err
  639. }
  640. // Only need to continue reading for messages and lists.
  641. switch tok.Kind() {
  642. case text.MessageOpen:
  643. return d.skipMessageValue()
  644. case text.ListOpen:
  645. for {
  646. tok, err := d.Read()
  647. if err != nil {
  648. return err
  649. }
  650. switch tok.Kind() {
  651. case text.ListClose:
  652. return nil
  653. case text.MessageOpen:
  654. if err := d.skipMessageValue(); err != nil {
  655. return err
  656. }
  657. default:
  658. // Skip items. This will not validate whether skipped values are
  659. // of the same type or not, same behavior as C++
  660. // TextFormat::Parser::AllowUnknownField(true) version 3.8.0.
  661. }
  662. }
  663. }
  664. return nil
  665. }
  666. // skipMessageValue makes the decoder parse and skip over all fields in a
  667. // message. It assumes that the previous read type is MessageOpen.
  668. func (d decoder) skipMessageValue() error {
  669. for {
  670. tok, err := d.Read()
  671. if err != nil {
  672. return err
  673. }
  674. switch tok.Kind() {
  675. case text.MessageClose:
  676. return nil
  677. case text.Name:
  678. if err := d.skipValue(); err != nil {
  679. return err
  680. }
  681. }
  682. }
  683. }