text_parser.go 21 KB

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