text_parser.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896
  1. // Go support for Protocol Buffers - Google's data interchange format
  2. //
  3. // Copyright 2010 The Go Authors. All rights reserved.
  4. // https://github.com/golang/protobuf
  5. //
  6. // Redistribution and use in source and binary forms, with or without
  7. // modification, are permitted provided that the following conditions are
  8. // met:
  9. //
  10. // * Redistributions of source code must retain the above copyright
  11. // notice, this list of conditions and the following disclaimer.
  12. // * Redistributions in binary form must reproduce the above
  13. // copyright notice, this list of conditions and the following disclaimer
  14. // in the documentation and/or other materials provided with the
  15. // distribution.
  16. // * Neither the name of Google Inc. nor the names of its
  17. // contributors may be used to endorse or promote products derived from
  18. // this software without specific prior written permission.
  19. //
  20. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  22. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  23. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  24. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  25. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  26. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  27. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  28. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  29. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  30. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. package proto
  32. // Functions for parsing the Text protocol buffer format.
  33. // TODO: message sets.
  34. import (
  35. "encoding"
  36. "errors"
  37. "fmt"
  38. "reflect"
  39. "strconv"
  40. "strings"
  41. "unicode/utf8"
  42. )
  43. // Error string emitted when deserializing Any and fields are already set
  44. const anyRepeatedlyUnpacked = "Any message unpacked multiple times, or %q already set"
  45. type ParseError struct {
  46. Message string
  47. Line int // 1-based line number
  48. Offset int // 0-based byte offset from start of input
  49. }
  50. func (p *ParseError) Error() string {
  51. if p.Line == 1 {
  52. // show offset only for first line
  53. return fmt.Sprintf("line 1.%d: %v", p.Offset, p.Message)
  54. }
  55. return fmt.Sprintf("line %d: %v", p.Line, p.Message)
  56. }
  57. type token struct {
  58. value string
  59. err *ParseError
  60. line int // line number
  61. offset int // byte number from start of input, not start of line
  62. unquoted string // the unquoted version of value, if it was a quoted string
  63. }
  64. func (t *token) String() string {
  65. if t.err == nil {
  66. return fmt.Sprintf("%q (line=%d, offset=%d)", t.value, t.line, t.offset)
  67. }
  68. return fmt.Sprintf("parse error: %v", t.err)
  69. }
  70. type textParser struct {
  71. s string // remaining input
  72. done bool // whether the parsing is finished (success or error)
  73. backed bool // whether back() was called
  74. offset, line int
  75. cur token
  76. }
  77. func newTextParser(s string) *textParser {
  78. p := new(textParser)
  79. p.s = s
  80. p.line = 1
  81. p.cur.line = 1
  82. return p
  83. }
  84. func (p *textParser) errorf(format string, a ...interface{}) *ParseError {
  85. pe := &ParseError{fmt.Sprintf(format, a...), p.cur.line, p.cur.offset}
  86. p.cur.err = pe
  87. p.done = true
  88. return pe
  89. }
  90. // Numbers and identifiers are matched by [-+._A-Za-z0-9]
  91. func isIdentOrNumberChar(c byte) bool {
  92. switch {
  93. case 'A' <= c && c <= 'Z', 'a' <= c && c <= 'z':
  94. return true
  95. case '0' <= c && c <= '9':
  96. return true
  97. }
  98. switch c {
  99. case '-', '+', '.', '_':
  100. return true
  101. }
  102. return false
  103. }
  104. func isWhitespace(c byte) bool {
  105. switch c {
  106. case ' ', '\t', '\n', '\r':
  107. return true
  108. }
  109. return false
  110. }
  111. func isQuote(c byte) bool {
  112. switch c {
  113. case '"', '\'':
  114. return true
  115. }
  116. return false
  117. }
  118. func (p *textParser) skipWhitespace() {
  119. i := 0
  120. for i < len(p.s) && (isWhitespace(p.s[i]) || p.s[i] == '#') {
  121. if p.s[i] == '#' {
  122. // comment; skip to end of line or input
  123. for i < len(p.s) && p.s[i] != '\n' {
  124. i++
  125. }
  126. if i == len(p.s) {
  127. break
  128. }
  129. }
  130. if p.s[i] == '\n' {
  131. p.line++
  132. }
  133. i++
  134. }
  135. p.offset += i
  136. p.s = p.s[i:len(p.s)]
  137. if len(p.s) == 0 {
  138. p.done = true
  139. }
  140. }
  141. func (p *textParser) advance() {
  142. // Skip whitespace
  143. p.skipWhitespace()
  144. if p.done {
  145. return
  146. }
  147. // Start of non-whitespace
  148. p.cur.err = nil
  149. p.cur.offset, p.cur.line = p.offset, p.line
  150. p.cur.unquoted = ""
  151. switch p.s[0] {
  152. case '<', '>', '{', '}', ':', '[', ']', ';', ',', '/':
  153. // Single symbol
  154. p.cur.value, p.s = p.s[0:1], p.s[1:len(p.s)]
  155. case '"', '\'':
  156. // Quoted string
  157. i := 1
  158. for i < len(p.s) && p.s[i] != p.s[0] && p.s[i] != '\n' {
  159. if p.s[i] == '\\' && i+1 < len(p.s) {
  160. // skip escaped char
  161. i++
  162. }
  163. i++
  164. }
  165. if i >= len(p.s) || p.s[i] != p.s[0] {
  166. p.errorf("unmatched quote")
  167. return
  168. }
  169. unq, err := unquoteC(p.s[1:i], rune(p.s[0]))
  170. if err != nil {
  171. p.errorf("invalid quoted string %s: %v", p.s[0:i+1], err)
  172. return
  173. }
  174. p.cur.value, p.s = p.s[0:i+1], p.s[i+1:len(p.s)]
  175. p.cur.unquoted = unq
  176. default:
  177. i := 0
  178. for i < len(p.s) && isIdentOrNumberChar(p.s[i]) {
  179. i++
  180. }
  181. if i == 0 {
  182. p.errorf("unexpected byte %#x", p.s[0])
  183. return
  184. }
  185. p.cur.value, p.s = p.s[0:i], p.s[i:len(p.s)]
  186. }
  187. p.offset += len(p.cur.value)
  188. }
  189. var (
  190. errBadUTF8 = errors.New("proto: bad UTF-8")
  191. errBadHex = errors.New("proto: bad hexadecimal")
  192. )
  193. func unquoteC(s string, quote rune) (string, error) {
  194. // This is based on C++'s tokenizer.cc.
  195. // Despite its name, this is *not* parsing C syntax.
  196. // For instance, "\0" is an invalid quoted string.
  197. // Avoid allocation in trivial cases.
  198. simple := true
  199. for _, r := range s {
  200. if r == '\\' || r == quote {
  201. simple = false
  202. break
  203. }
  204. }
  205. if simple {
  206. return s, nil
  207. }
  208. buf := make([]byte, 0, 3*len(s)/2)
  209. for len(s) > 0 {
  210. r, n := utf8.DecodeRuneInString(s)
  211. if r == utf8.RuneError && n == 1 {
  212. return "", errBadUTF8
  213. }
  214. s = s[n:]
  215. if r != '\\' {
  216. if r < utf8.RuneSelf {
  217. buf = append(buf, byte(r))
  218. } else {
  219. buf = append(buf, string(r)...)
  220. }
  221. continue
  222. }
  223. ch, tail, err := unescape(s)
  224. if err != nil {
  225. return "", err
  226. }
  227. buf = append(buf, ch...)
  228. s = tail
  229. }
  230. return string(buf), nil
  231. }
  232. func unescape(s string) (ch string, tail string, err error) {
  233. r, n := utf8.DecodeRuneInString(s)
  234. if r == utf8.RuneError && n == 1 {
  235. return "", "", errBadUTF8
  236. }
  237. s = s[n:]
  238. switch r {
  239. case 'a':
  240. return "\a", s, nil
  241. case 'b':
  242. return "\b", s, nil
  243. case 'f':
  244. return "\f", s, nil
  245. case 'n':
  246. return "\n", s, nil
  247. case 'r':
  248. return "\r", s, nil
  249. case 't':
  250. return "\t", s, nil
  251. case 'v':
  252. return "\v", s, nil
  253. case '?':
  254. return "?", s, nil // trigraph workaround
  255. case '\'', '"', '\\':
  256. return string(r), s, nil
  257. case '0', '1', '2', '3', '4', '5', '6', '7', 'x', 'X':
  258. if len(s) < 2 {
  259. return "", "", fmt.Errorf(`\%c requires 2 following digits`, r)
  260. }
  261. base := 8
  262. ss := s[:2]
  263. s = s[2:]
  264. if r == 'x' || r == 'X' {
  265. base = 16
  266. } else {
  267. ss = string(r) + ss
  268. }
  269. i, err := strconv.ParseUint(ss, base, 8)
  270. if err != nil {
  271. return "", "", err
  272. }
  273. return string([]byte{byte(i)}), s, nil
  274. case 'u', 'U':
  275. n := 4
  276. if r == 'U' {
  277. n = 8
  278. }
  279. if len(s) < n {
  280. return "", "", fmt.Errorf(`\%c requires %d digits`, r, n)
  281. }
  282. bs := make([]byte, n/2)
  283. for i := 0; i < n; i += 2 {
  284. a, ok1 := unhex(s[i])
  285. b, ok2 := unhex(s[i+1])
  286. if !ok1 || !ok2 {
  287. return "", "", errBadHex
  288. }
  289. bs[i/2] = a<<4 | b
  290. }
  291. s = s[n:]
  292. return string(bs), s, nil
  293. }
  294. return "", "", fmt.Errorf(`unknown escape \%c`, r)
  295. }
  296. // Adapted from src/pkg/strconv/quote.go.
  297. func unhex(b byte) (v byte, ok bool) {
  298. switch {
  299. case '0' <= b && b <= '9':
  300. return b - '0', true
  301. case 'a' <= b && b <= 'f':
  302. return b - 'a' + 10, true
  303. case 'A' <= b && b <= 'F':
  304. return b - 'A' + 10, true
  305. }
  306. return 0, false
  307. }
  308. // Back off the parser by one token. Can only be done between calls to next().
  309. // It makes the next advance() a no-op.
  310. func (p *textParser) back() { p.backed = true }
  311. // Advances the parser and returns the new current token.
  312. func (p *textParser) next() *token {
  313. if p.backed || p.done {
  314. p.backed = false
  315. return &p.cur
  316. }
  317. p.advance()
  318. if p.done {
  319. p.cur.value = ""
  320. } else if len(p.cur.value) > 0 && isQuote(p.cur.value[0]) {
  321. // Look for multiple quoted strings separated by whitespace,
  322. // and concatenate them.
  323. cat := p.cur
  324. for {
  325. p.skipWhitespace()
  326. if p.done || !isQuote(p.s[0]) {
  327. break
  328. }
  329. p.advance()
  330. if p.cur.err != nil {
  331. return &p.cur
  332. }
  333. cat.value += " " + p.cur.value
  334. cat.unquoted += p.cur.unquoted
  335. }
  336. p.done = false // parser may have seen EOF, but we want to return cat
  337. p.cur = cat
  338. }
  339. return &p.cur
  340. }
  341. func (p *textParser) consumeToken(s string) error {
  342. tok := p.next()
  343. if tok.err != nil {
  344. return tok.err
  345. }
  346. if tok.value != s {
  347. p.back()
  348. return p.errorf("expected %q, found %q", s, tok.value)
  349. }
  350. return nil
  351. }
  352. // Return a RequiredNotSetError indicating which required field was not set.
  353. func (p *textParser) missingRequiredFieldError(sv reflect.Value) *RequiredNotSetError {
  354. st := sv.Type()
  355. sprops := GetProperties(st)
  356. for i := 0; i < st.NumField(); i++ {
  357. if !isNil(sv.Field(i)) {
  358. continue
  359. }
  360. props := sprops.Prop[i]
  361. if props.Required {
  362. return &RequiredNotSetError{fmt.Sprintf("%v.%v", st, props.OrigName)}
  363. }
  364. }
  365. return &RequiredNotSetError{fmt.Sprintf("%v.<unknown field name>", st)} // should not happen
  366. }
  367. // Returns the index in the struct for the named field, as well as the parsed tag properties.
  368. func structFieldByName(sprops *StructProperties, name string) (int, *Properties, bool) {
  369. i, ok := sprops.decoderOrigNames[name]
  370. if ok {
  371. return i, sprops.Prop[i], true
  372. }
  373. return -1, nil, false
  374. }
  375. // Consume a ':' from the input stream (if the next token is a colon),
  376. // returning an error if a colon is needed but not present.
  377. func (p *textParser) checkForColon(props *Properties, typ reflect.Type) *ParseError {
  378. tok := p.next()
  379. if tok.err != nil {
  380. return tok.err
  381. }
  382. if tok.value != ":" {
  383. // Colon is optional when the field is a group or message.
  384. needColon := true
  385. switch props.Wire {
  386. case "group":
  387. needColon = false
  388. case "bytes":
  389. // A "bytes" field is either a message, a string, or a repeated field;
  390. // those three become *T, *string and []T respectively, so we can check for
  391. // this field being a pointer to a non-string.
  392. if typ.Kind() == reflect.Ptr {
  393. // *T or *string
  394. if typ.Elem().Kind() == reflect.String {
  395. break
  396. }
  397. } else if typ.Kind() == reflect.Slice {
  398. // []T or []*T
  399. if typ.Elem().Kind() != reflect.Ptr {
  400. break
  401. }
  402. } else if typ.Kind() == reflect.String {
  403. // The proto3 exception is for a string field,
  404. // which requires a colon.
  405. break
  406. }
  407. needColon = false
  408. }
  409. if needColon {
  410. return p.errorf("expected ':', found %q", tok.value)
  411. }
  412. p.back()
  413. }
  414. return nil
  415. }
  416. func (p *textParser) readStruct(sv reflect.Value, terminator string) error {
  417. st := sv.Type()
  418. sprops := GetProperties(st)
  419. reqCount := sprops.reqCount
  420. var reqFieldErr error
  421. fieldSet := make(map[string]bool)
  422. // A struct is a sequence of "name: value", terminated by one of
  423. // '>' or '}', or the end of the input. A name may also be
  424. // "[extension]" or "[type/url]".
  425. //
  426. // The whole struct can also be an expanded Any message, like:
  427. // [type/url] < ... struct contents ... >
  428. for {
  429. tok := p.next()
  430. if tok.err != nil {
  431. return tok.err
  432. }
  433. if tok.value == terminator {
  434. break
  435. }
  436. if tok.value == "[" {
  437. // Looks like an extension or an Any.
  438. //
  439. // TODO: Check whether we need to handle
  440. // namespace rooted names (e.g. ".something.Foo").
  441. extName, err := p.consumeExtName()
  442. if err != nil {
  443. return err
  444. }
  445. if s := strings.LastIndex(extName, "/"); s >= 0 {
  446. // If it contains a slash, it's an Any type URL.
  447. messageName := extName[s+1:]
  448. mt := MessageType(messageName)
  449. if mt == nil {
  450. return p.errorf("unrecognized message %q in google.protobuf.Any", messageName)
  451. }
  452. tok = p.next()
  453. if tok.err != nil {
  454. return tok.err
  455. }
  456. // consume an optional colon
  457. if tok.value == ":" {
  458. tok = p.next()
  459. if tok.err != nil {
  460. return tok.err
  461. }
  462. }
  463. var terminator string
  464. switch tok.value {
  465. case "<":
  466. terminator = ">"
  467. case "{":
  468. terminator = "}"
  469. default:
  470. return p.errorf("expected '{' or '<', found %q", tok.value)
  471. }
  472. v := reflect.New(mt.Elem())
  473. if pe := p.readStruct(v.Elem(), terminator); pe != nil {
  474. return pe
  475. }
  476. b, err := Marshal(v.Interface().(Message))
  477. if err != nil {
  478. return p.errorf("failed to marshal message of type %q: %v", messageName, err)
  479. }
  480. if fieldSet["type_url"] {
  481. return p.errorf(anyRepeatedlyUnpacked, "type_url")
  482. }
  483. if fieldSet["value"] {
  484. return p.errorf(anyRepeatedlyUnpacked, "value")
  485. }
  486. sv.FieldByName("TypeUrl").SetString(extName)
  487. sv.FieldByName("Value").SetBytes(b)
  488. fieldSet["type_url"] = true
  489. fieldSet["value"] = true
  490. continue
  491. }
  492. var desc *ExtensionDesc
  493. // This could be faster, but it's functional.
  494. // TODO: Do something smarter than a linear scan.
  495. for _, d := range RegisteredExtensions(reflect.New(st).Interface().(Message)) {
  496. if d.Name == extName {
  497. desc = d
  498. break
  499. }
  500. }
  501. if desc == nil {
  502. return p.errorf("unrecognized extension %q", extName)
  503. }
  504. props := &Properties{}
  505. props.Parse(desc.Tag)
  506. typ := reflect.TypeOf(desc.ExtensionType)
  507. if err := p.checkForColon(props, typ); err != nil {
  508. return err
  509. }
  510. rep := desc.repeated()
  511. // Read the extension structure, and set it in
  512. // the value we're constructing.
  513. var ext reflect.Value
  514. if !rep {
  515. ext = reflect.New(typ).Elem()
  516. } else {
  517. ext = reflect.New(typ.Elem()).Elem()
  518. }
  519. if err := p.readAny(ext, props); err != nil {
  520. if _, ok := err.(*RequiredNotSetError); !ok {
  521. return err
  522. }
  523. reqFieldErr = err
  524. }
  525. ep := sv.Addr().Interface().(Message)
  526. if !rep {
  527. SetExtension(ep, desc, ext.Interface())
  528. } else {
  529. old, err := GetExtension(ep, desc)
  530. var sl reflect.Value
  531. if err == nil {
  532. sl = reflect.ValueOf(old) // existing slice
  533. } else {
  534. sl = reflect.MakeSlice(typ, 0, 1)
  535. }
  536. sl = reflect.Append(sl, ext)
  537. SetExtension(ep, desc, sl.Interface())
  538. }
  539. if err := p.consumeOptionalSeparator(); err != nil {
  540. return err
  541. }
  542. continue
  543. }
  544. // This is a normal, non-extension field.
  545. name := tok.value
  546. var dst reflect.Value
  547. fi, props, ok := structFieldByName(sprops, name)
  548. if ok {
  549. dst = sv.Field(fi)
  550. } else if oop, ok := sprops.OneofTypes[name]; ok {
  551. // It is a oneof.
  552. props = oop.Prop
  553. nv := reflect.New(oop.Type.Elem())
  554. dst = nv.Elem().Field(0)
  555. field := sv.Field(oop.Field)
  556. if !field.IsNil() {
  557. return p.errorf("field '%s' would overwrite already parsed oneof '%s'", name, sv.Type().Field(oop.Field).Name)
  558. }
  559. field.Set(nv)
  560. }
  561. if !dst.IsValid() {
  562. return p.errorf("unknown field name %q in %v", name, st)
  563. }
  564. if dst.Kind() == reflect.Map {
  565. // Consume any colon.
  566. if err := p.checkForColon(props, dst.Type()); err != nil {
  567. return err
  568. }
  569. // Construct the map if it doesn't already exist.
  570. if dst.IsNil() {
  571. dst.Set(reflect.MakeMap(dst.Type()))
  572. }
  573. key := reflect.New(dst.Type().Key()).Elem()
  574. val := reflect.New(dst.Type().Elem()).Elem()
  575. // The map entry should be this sequence of tokens:
  576. // < key : KEY value : VALUE >
  577. // However, implementations may omit key or value, and technically
  578. // we should support them in any order. See b/28924776 for a time
  579. // this went wrong.
  580. tok := p.next()
  581. var terminator string
  582. switch tok.value {
  583. case "<":
  584. terminator = ">"
  585. case "{":
  586. terminator = "}"
  587. default:
  588. return p.errorf("expected '{' or '<', found %q", tok.value)
  589. }
  590. for {
  591. tok := p.next()
  592. if tok.err != nil {
  593. return tok.err
  594. }
  595. if tok.value == terminator {
  596. break
  597. }
  598. switch tok.value {
  599. case "key":
  600. if err := p.consumeToken(":"); err != nil {
  601. return err
  602. }
  603. if err := p.readAny(key, props.mkeyprop); err != nil {
  604. return err
  605. }
  606. if err := p.consumeOptionalSeparator(); err != nil {
  607. return err
  608. }
  609. case "value":
  610. if err := p.checkForColon(props.mvalprop, dst.Type().Elem()); err != nil {
  611. return err
  612. }
  613. if err := p.readAny(val, props.mvalprop); err != nil {
  614. return err
  615. }
  616. if err := p.consumeOptionalSeparator(); err != nil {
  617. return err
  618. }
  619. default:
  620. p.back()
  621. return p.errorf(`expected "key", "value", or %q, found %q`, terminator, tok.value)
  622. }
  623. }
  624. dst.SetMapIndex(key, val)
  625. continue
  626. }
  627. // Check that it's not already set if it's not a repeated field.
  628. if !props.Repeated && fieldSet[name] {
  629. return p.errorf("non-repeated field %q was repeated", name)
  630. }
  631. if err := p.checkForColon(props, dst.Type()); err != nil {
  632. return err
  633. }
  634. // Parse into the field.
  635. fieldSet[name] = true
  636. if err := p.readAny(dst, props); err != nil {
  637. if _, ok := err.(*RequiredNotSetError); !ok {
  638. return err
  639. }
  640. reqFieldErr = err
  641. }
  642. if props.Required {
  643. reqCount--
  644. }
  645. if err := p.consumeOptionalSeparator(); err != nil {
  646. return err
  647. }
  648. }
  649. if reqCount > 0 {
  650. return p.missingRequiredFieldError(sv)
  651. }
  652. return reqFieldErr
  653. }
  654. // consumeExtName consumes extension name or expanded Any type URL and the
  655. // following ']'. It returns the name or URL consumed.
  656. func (p *textParser) consumeExtName() (string, error) {
  657. tok := p.next()
  658. if tok.err != nil {
  659. return "", tok.err
  660. }
  661. // If extension name or type url is quoted, it's a single token.
  662. if len(tok.value) > 2 && isQuote(tok.value[0]) && tok.value[len(tok.value)-1] == tok.value[0] {
  663. name, err := unquoteC(tok.value[1:len(tok.value)-1], rune(tok.value[0]))
  664. if err != nil {
  665. return "", err
  666. }
  667. return name, p.consumeToken("]")
  668. }
  669. // Consume everything up to "]"
  670. var parts []string
  671. for tok.value != "]" {
  672. parts = append(parts, tok.value)
  673. tok = p.next()
  674. if tok.err != nil {
  675. return "", p.errorf("unrecognized type_url or extension name: %s", tok.err)
  676. }
  677. }
  678. return strings.Join(parts, ""), nil
  679. }
  680. // consumeOptionalSeparator consumes an optional semicolon or comma.
  681. // It is used in readStruct to provide backward compatibility.
  682. func (p *textParser) consumeOptionalSeparator() error {
  683. tok := p.next()
  684. if tok.err != nil {
  685. return tok.err
  686. }
  687. if tok.value != ";" && tok.value != "," {
  688. p.back()
  689. }
  690. return nil
  691. }
  692. func (p *textParser) readAny(v reflect.Value, props *Properties) error {
  693. tok := p.next()
  694. if tok.err != nil {
  695. return tok.err
  696. }
  697. if tok.value == "" {
  698. return p.errorf("unexpected EOF")
  699. }
  700. switch fv := v; fv.Kind() {
  701. case reflect.Slice:
  702. at := v.Type()
  703. if at.Elem().Kind() == reflect.Uint8 {
  704. // Special case for []byte
  705. if tok.value[0] != '"' && tok.value[0] != '\'' {
  706. // Deliberately written out here, as the error after
  707. // this switch statement would write "invalid []byte: ...",
  708. // which is not as user-friendly.
  709. return p.errorf("invalid string: %v", tok.value)
  710. }
  711. bytes := []byte(tok.unquoted)
  712. fv.Set(reflect.ValueOf(bytes))
  713. return nil
  714. }
  715. // Repeated field.
  716. if tok.value == "[" {
  717. // Repeated field with list notation, like [1,2,3].
  718. for {
  719. fv.Set(reflect.Append(fv, reflect.New(at.Elem()).Elem()))
  720. err := p.readAny(fv.Index(fv.Len()-1), props)
  721. if err != nil {
  722. return err
  723. }
  724. tok := p.next()
  725. if tok.err != nil {
  726. return tok.err
  727. }
  728. if tok.value == "]" {
  729. break
  730. }
  731. if tok.value != "," {
  732. return p.errorf("Expected ']' or ',' found %q", tok.value)
  733. }
  734. }
  735. return nil
  736. }
  737. // One value of the repeated field.
  738. p.back()
  739. fv.Set(reflect.Append(fv, reflect.New(at.Elem()).Elem()))
  740. return p.readAny(fv.Index(fv.Len()-1), props)
  741. case reflect.Bool:
  742. // true/1/t/True or false/f/0/False.
  743. switch tok.value {
  744. case "true", "1", "t", "True":
  745. fv.SetBool(true)
  746. return nil
  747. case "false", "0", "f", "False":
  748. fv.SetBool(false)
  749. return nil
  750. }
  751. case reflect.Float32, reflect.Float64:
  752. v := tok.value
  753. // Ignore 'f' for compatibility with output generated by C++, but don't
  754. // remove 'f' when the value is "-inf" or "inf".
  755. if strings.HasSuffix(v, "f") && tok.value != "-inf" && tok.value != "inf" {
  756. v = v[:len(v)-1]
  757. }
  758. if f, err := strconv.ParseFloat(v, fv.Type().Bits()); err == nil {
  759. fv.SetFloat(f)
  760. return nil
  761. }
  762. case reflect.Int32:
  763. if x, err := strconv.ParseInt(tok.value, 0, 32); err == nil {
  764. fv.SetInt(x)
  765. return nil
  766. }
  767. if len(props.Enum) == 0 {
  768. break
  769. }
  770. m, ok := enumValueMaps[props.Enum]
  771. if !ok {
  772. break
  773. }
  774. x, ok := m[tok.value]
  775. if !ok {
  776. break
  777. }
  778. fv.SetInt(int64(x))
  779. return nil
  780. case reflect.Int64:
  781. if x, err := strconv.ParseInt(tok.value, 0, 64); err == nil {
  782. fv.SetInt(x)
  783. return nil
  784. }
  785. case reflect.Ptr:
  786. // A basic field (indirected through pointer), or a repeated message/group
  787. p.back()
  788. fv.Set(reflect.New(fv.Type().Elem()))
  789. return p.readAny(fv.Elem(), props)
  790. case reflect.String:
  791. if tok.value[0] == '"' || tok.value[0] == '\'' {
  792. fv.SetString(tok.unquoted)
  793. return nil
  794. }
  795. case reflect.Struct:
  796. var terminator string
  797. switch tok.value {
  798. case "{":
  799. terminator = "}"
  800. case "<":
  801. terminator = ">"
  802. default:
  803. return p.errorf("expected '{' or '<', found %q", tok.value)
  804. }
  805. // TODO: Handle nested messages which implement encoding.TextUnmarshaler.
  806. return p.readStruct(fv, terminator)
  807. case reflect.Uint32:
  808. if x, err := strconv.ParseUint(tok.value, 0, 32); err == nil {
  809. fv.SetUint(x)
  810. return nil
  811. }
  812. case reflect.Uint64:
  813. if x, err := strconv.ParseUint(tok.value, 0, 64); err == nil {
  814. fv.SetUint(x)
  815. return nil
  816. }
  817. }
  818. return p.errorf("invalid %v: %v", v.Type(), tok.value)
  819. }
  820. // UnmarshalText reads a protocol buffer in Text format. UnmarshalText resets pb
  821. // before starting to unmarshal, so any existing data in pb is always removed.
  822. // If a required field is not set and no other error occurs,
  823. // UnmarshalText returns *RequiredNotSetError.
  824. func UnmarshalText(s string, pb Message) error {
  825. if um, ok := pb.(encoding.TextUnmarshaler); ok {
  826. err := um.UnmarshalText([]byte(s))
  827. return err
  828. }
  829. pb.Reset()
  830. v := reflect.ValueOf(pb)
  831. if pe := newTextParser(s).readStruct(v.Elem(), ""); pe != nil {
  832. return pe
  833. }
  834. return nil
  835. }