text_parser.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891
  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. sv.Field(oop.Field).Set(nv)
  556. }
  557. if !dst.IsValid() {
  558. return p.errorf("unknown field name %q in %v", name, st)
  559. }
  560. if dst.Kind() == reflect.Map {
  561. // Consume any colon.
  562. if err := p.checkForColon(props, dst.Type()); err != nil {
  563. return err
  564. }
  565. // Construct the map if it doesn't already exist.
  566. if dst.IsNil() {
  567. dst.Set(reflect.MakeMap(dst.Type()))
  568. }
  569. key := reflect.New(dst.Type().Key()).Elem()
  570. val := reflect.New(dst.Type().Elem()).Elem()
  571. // The map entry should be this sequence of tokens:
  572. // < key : KEY value : VALUE >
  573. // However, implementations may omit key or value, and technically
  574. // we should support them in any order. See b/28924776 for a time
  575. // this went wrong.
  576. tok := p.next()
  577. var terminator string
  578. switch tok.value {
  579. case "<":
  580. terminator = ">"
  581. case "{":
  582. terminator = "}"
  583. default:
  584. return p.errorf("expected '{' or '<', found %q", tok.value)
  585. }
  586. for {
  587. tok := p.next()
  588. if tok.err != nil {
  589. return tok.err
  590. }
  591. if tok.value == terminator {
  592. break
  593. }
  594. switch tok.value {
  595. case "key":
  596. if err := p.consumeToken(":"); err != nil {
  597. return err
  598. }
  599. if err := p.readAny(key, props.mkeyprop); err != nil {
  600. return err
  601. }
  602. if err := p.consumeOptionalSeparator(); err != nil {
  603. return err
  604. }
  605. case "value":
  606. if err := p.checkForColon(props.mvalprop, dst.Type().Elem()); err != nil {
  607. return err
  608. }
  609. if err := p.readAny(val, props.mvalprop); err != nil {
  610. return err
  611. }
  612. if err := p.consumeOptionalSeparator(); err != nil {
  613. return err
  614. }
  615. default:
  616. p.back()
  617. return p.errorf(`expected "key", "value", or %q, found %q`, terminator, tok.value)
  618. }
  619. }
  620. dst.SetMapIndex(key, val)
  621. continue
  622. }
  623. // Check that it's not already set if it's not a repeated field.
  624. if !props.Repeated && fieldSet[name] {
  625. return p.errorf("non-repeated field %q was repeated", name)
  626. }
  627. if err := p.checkForColon(props, dst.Type()); err != nil {
  628. return err
  629. }
  630. // Parse into the field.
  631. fieldSet[name] = true
  632. if err := p.readAny(dst, props); err != nil {
  633. if _, ok := err.(*RequiredNotSetError); !ok {
  634. return err
  635. }
  636. reqFieldErr = err
  637. }
  638. if props.Required {
  639. reqCount--
  640. }
  641. if err := p.consumeOptionalSeparator(); err != nil {
  642. return err
  643. }
  644. }
  645. if reqCount > 0 {
  646. return p.missingRequiredFieldError(sv)
  647. }
  648. return reqFieldErr
  649. }
  650. // consumeExtName consumes extension name or expanded Any type URL and the
  651. // following ']'. It returns the name or URL consumed.
  652. func (p *textParser) consumeExtName() (string, error) {
  653. tok := p.next()
  654. if tok.err != nil {
  655. return "", tok.err
  656. }
  657. // If extension name or type url is quoted, it's a single token.
  658. if len(tok.value) > 2 && isQuote(tok.value[0]) && tok.value[len(tok.value)-1] == tok.value[0] {
  659. name, err := unquoteC(tok.value[1:len(tok.value)-1], rune(tok.value[0]))
  660. if err != nil {
  661. return "", err
  662. }
  663. return name, p.consumeToken("]")
  664. }
  665. // Consume everything up to "]"
  666. var parts []string
  667. for tok.value != "]" {
  668. parts = append(parts, tok.value)
  669. tok = p.next()
  670. if tok.err != nil {
  671. return "", p.errorf("unrecognized type_url or extension name: %s", tok.err)
  672. }
  673. }
  674. return strings.Join(parts, ""), nil
  675. }
  676. // consumeOptionalSeparator consumes an optional semicolon or comma.
  677. // It is used in readStruct to provide backward compatibility.
  678. func (p *textParser) consumeOptionalSeparator() error {
  679. tok := p.next()
  680. if tok.err != nil {
  681. return tok.err
  682. }
  683. if tok.value != ";" && tok.value != "," {
  684. p.back()
  685. }
  686. return nil
  687. }
  688. func (p *textParser) readAny(v reflect.Value, props *Properties) error {
  689. tok := p.next()
  690. if tok.err != nil {
  691. return tok.err
  692. }
  693. if tok.value == "" {
  694. return p.errorf("unexpected EOF")
  695. }
  696. switch fv := v; fv.Kind() {
  697. case reflect.Slice:
  698. at := v.Type()
  699. if at.Elem().Kind() == reflect.Uint8 {
  700. // Special case for []byte
  701. if tok.value[0] != '"' && tok.value[0] != '\'' {
  702. // Deliberately written out here, as the error after
  703. // this switch statement would write "invalid []byte: ...",
  704. // which is not as user-friendly.
  705. return p.errorf("invalid string: %v", tok.value)
  706. }
  707. bytes := []byte(tok.unquoted)
  708. fv.Set(reflect.ValueOf(bytes))
  709. return nil
  710. }
  711. // Repeated field.
  712. if tok.value == "[" {
  713. // Repeated field with list notation, like [1,2,3].
  714. for {
  715. fv.Set(reflect.Append(fv, reflect.New(at.Elem()).Elem()))
  716. err := p.readAny(fv.Index(fv.Len()-1), props)
  717. if err != nil {
  718. return err
  719. }
  720. tok := p.next()
  721. if tok.err != nil {
  722. return tok.err
  723. }
  724. if tok.value == "]" {
  725. break
  726. }
  727. if tok.value != "," {
  728. return p.errorf("Expected ']' or ',' found %q", tok.value)
  729. }
  730. }
  731. return nil
  732. }
  733. // One value of the repeated field.
  734. p.back()
  735. fv.Set(reflect.Append(fv, reflect.New(at.Elem()).Elem()))
  736. return p.readAny(fv.Index(fv.Len()-1), props)
  737. case reflect.Bool:
  738. // true/1/t/True or false/f/0/False.
  739. switch tok.value {
  740. case "true", "1", "t", "True":
  741. fv.SetBool(true)
  742. return nil
  743. case "false", "0", "f", "False":
  744. fv.SetBool(false)
  745. return nil
  746. }
  747. case reflect.Float32, reflect.Float64:
  748. v := tok.value
  749. // Ignore 'f' for compatibility with output generated by C++, but don't
  750. // remove 'f' when the value is "-inf" or "inf".
  751. if strings.HasSuffix(v, "f") && tok.value != "-inf" && tok.value != "inf" {
  752. v = v[:len(v)-1]
  753. }
  754. if f, err := strconv.ParseFloat(v, fv.Type().Bits()); err == nil {
  755. fv.SetFloat(f)
  756. return nil
  757. }
  758. case reflect.Int32:
  759. if x, err := strconv.ParseInt(tok.value, 0, 32); err == nil {
  760. fv.SetInt(x)
  761. return nil
  762. }
  763. if len(props.Enum) == 0 {
  764. break
  765. }
  766. m, ok := enumValueMaps[props.Enum]
  767. if !ok {
  768. break
  769. }
  770. x, ok := m[tok.value]
  771. if !ok {
  772. break
  773. }
  774. fv.SetInt(int64(x))
  775. return nil
  776. case reflect.Int64:
  777. if x, err := strconv.ParseInt(tok.value, 0, 64); err == nil {
  778. fv.SetInt(x)
  779. return nil
  780. }
  781. case reflect.Ptr:
  782. // A basic field (indirected through pointer), or a repeated message/group
  783. p.back()
  784. fv.Set(reflect.New(fv.Type().Elem()))
  785. return p.readAny(fv.Elem(), props)
  786. case reflect.String:
  787. if tok.value[0] == '"' || tok.value[0] == '\'' {
  788. fv.SetString(tok.unquoted)
  789. return nil
  790. }
  791. case reflect.Struct:
  792. var terminator string
  793. switch tok.value {
  794. case "{":
  795. terminator = "}"
  796. case "<":
  797. terminator = ">"
  798. default:
  799. return p.errorf("expected '{' or '<', found %q", tok.value)
  800. }
  801. // TODO: Handle nested messages which implement encoding.TextUnmarshaler.
  802. return p.readStruct(fv, terminator)
  803. case reflect.Uint32:
  804. if x, err := strconv.ParseUint(tok.value, 0, 32); err == nil {
  805. fv.SetUint(uint64(x))
  806. return nil
  807. }
  808. case reflect.Uint64:
  809. if x, err := strconv.ParseUint(tok.value, 0, 64); err == nil {
  810. fv.SetUint(x)
  811. return nil
  812. }
  813. }
  814. return p.errorf("invalid %v: %v", v.Type(), tok.value)
  815. }
  816. // UnmarshalText reads a protocol buffer in Text format. UnmarshalText resets pb
  817. // before starting to unmarshal, so any existing data in pb is always removed.
  818. // If a required field is not set and no other error occurs,
  819. // UnmarshalText returns *RequiredNotSetError.
  820. func UnmarshalText(s string, pb Message) error {
  821. if um, ok := pb.(encoding.TextUnmarshaler); ok {
  822. err := um.UnmarshalText([]byte(s))
  823. return err
  824. }
  825. pb.Reset()
  826. v := reflect.ValueOf(pb)
  827. if pe := newTextParser(s).readStruct(v.Elem(), ""); pe != nil {
  828. return pe
  829. }
  830. return nil
  831. }