text_parser.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841
  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 (p *textParser) skipWhitespace() {
  115. i := 0
  116. for i < len(p.s) && (isWhitespace(p.s[i]) || p.s[i] == '#') {
  117. if p.s[i] == '#' {
  118. // comment; skip to end of line or input
  119. for i < len(p.s) && p.s[i] != '\n' {
  120. i++
  121. }
  122. if i == len(p.s) {
  123. break
  124. }
  125. }
  126. if p.s[i] == '\n' {
  127. p.line++
  128. }
  129. i++
  130. }
  131. p.offset += i
  132. p.s = p.s[i:len(p.s)]
  133. if len(p.s) == 0 {
  134. p.done = true
  135. }
  136. }
  137. func (p *textParser) advance() {
  138. // Skip whitespace
  139. p.skipWhitespace()
  140. if p.done {
  141. return
  142. }
  143. // Start of non-whitespace
  144. p.cur.err = nil
  145. p.cur.offset, p.cur.line = p.offset, p.line
  146. p.cur.unquoted = ""
  147. switch p.s[0] {
  148. case '<', '>', '{', '}', ':', '[', ']', ';', ',':
  149. // Single symbol
  150. p.cur.value, p.s = p.s[0:1], p.s[1:len(p.s)]
  151. case '"', '\'':
  152. // Quoted string
  153. i := 1
  154. for i < len(p.s) && p.s[i] != p.s[0] && p.s[i] != '\n' {
  155. if p.s[i] == '\\' && i+1 < len(p.s) {
  156. // skip escaped char
  157. i++
  158. }
  159. i++
  160. }
  161. if i >= len(p.s) || p.s[i] != p.s[0] {
  162. p.errorf("unmatched quote")
  163. return
  164. }
  165. unq, err := unquoteC(p.s[1:i], rune(p.s[0]))
  166. if err != nil {
  167. p.errorf("invalid quoted string %s: %v", p.s[0:i+1], err)
  168. return
  169. }
  170. p.cur.value, p.s = p.s[0:i+1], p.s[i+1:len(p.s)]
  171. p.cur.unquoted = unq
  172. default:
  173. i := 0
  174. for i < len(p.s) && isIdentOrNumberChar(p.s[i]) {
  175. i++
  176. }
  177. if i == 0 {
  178. p.errorf("unexpected byte %#x", p.s[0])
  179. return
  180. }
  181. p.cur.value, p.s = p.s[0:i], p.s[i:len(p.s)]
  182. }
  183. p.offset += len(p.cur.value)
  184. }
  185. var (
  186. errBadUTF8 = errors.New("proto: bad UTF-8")
  187. errBadHex = errors.New("proto: bad hexadecimal")
  188. )
  189. func unquoteC(s string, quote rune) (string, error) {
  190. // This is based on C++'s tokenizer.cc.
  191. // Despite its name, this is *not* parsing C syntax.
  192. // For instance, "\0" is an invalid quoted string.
  193. // Avoid allocation in trivial cases.
  194. simple := true
  195. for _, r := range s {
  196. if r == '\\' || r == quote {
  197. simple = false
  198. break
  199. }
  200. }
  201. if simple {
  202. return s, nil
  203. }
  204. buf := make([]byte, 0, 3*len(s)/2)
  205. for len(s) > 0 {
  206. r, n := utf8.DecodeRuneInString(s)
  207. if r == utf8.RuneError && n == 1 {
  208. return "", errBadUTF8
  209. }
  210. s = s[n:]
  211. if r != '\\' {
  212. if r < utf8.RuneSelf {
  213. buf = append(buf, byte(r))
  214. } else {
  215. buf = append(buf, string(r)...)
  216. }
  217. continue
  218. }
  219. ch, tail, err := unescape(s)
  220. if err != nil {
  221. return "", err
  222. }
  223. buf = append(buf, ch...)
  224. s = tail
  225. }
  226. return string(buf), nil
  227. }
  228. func unescape(s string) (ch string, tail string, err error) {
  229. r, n := utf8.DecodeRuneInString(s)
  230. if r == utf8.RuneError && n == 1 {
  231. return "", "", errBadUTF8
  232. }
  233. s = s[n:]
  234. switch r {
  235. case 'a':
  236. return "\a", s, nil
  237. case 'b':
  238. return "\b", s, nil
  239. case 'f':
  240. return "\f", s, nil
  241. case 'n':
  242. return "\n", s, nil
  243. case 'r':
  244. return "\r", s, nil
  245. case 't':
  246. return "\t", s, nil
  247. case 'v':
  248. return "\v", s, nil
  249. case '?':
  250. return "?", s, nil // trigraph workaround
  251. case '\'', '"', '\\':
  252. return string(r), s, nil
  253. case '0', '1', '2', '3', '4', '5', '6', '7', 'x', 'X':
  254. if len(s) < 2 {
  255. return "", "", fmt.Errorf(`\%c requires 2 following digits`, r)
  256. }
  257. base := 8
  258. ss := s[:2]
  259. s = s[2:]
  260. if r == 'x' || r == 'X' {
  261. base = 16
  262. } else {
  263. ss = string(r) + ss
  264. }
  265. i, err := strconv.ParseUint(ss, base, 8)
  266. if err != nil {
  267. return "", "", err
  268. }
  269. return string([]byte{byte(i)}), s, nil
  270. case 'u', 'U':
  271. n := 4
  272. if r == 'U' {
  273. n = 8
  274. }
  275. if len(s) < n {
  276. return "", "", fmt.Errorf(`\%c requires %d digits`, r, n)
  277. }
  278. bs := make([]byte, n/2)
  279. for i := 0; i < n; i += 2 {
  280. a, ok1 := unhex(s[i])
  281. b, ok2 := unhex(s[i+1])
  282. if !ok1 || !ok2 {
  283. return "", "", errBadHex
  284. }
  285. bs[i/2] = a<<4 | b
  286. }
  287. s = s[n:]
  288. return string(bs), s, nil
  289. }
  290. return "", "", fmt.Errorf(`unknown escape \%c`, r)
  291. }
  292. // Adapted from src/pkg/strconv/quote.go.
  293. func unhex(b byte) (v byte, ok bool) {
  294. switch {
  295. case '0' <= b && b <= '9':
  296. return b - '0', true
  297. case 'a' <= b && b <= 'f':
  298. return b - 'a' + 10, true
  299. case 'A' <= b && b <= 'F':
  300. return b - 'A' + 10, true
  301. }
  302. return 0, false
  303. }
  304. // Back off the parser by one token. Can only be done between calls to next().
  305. // It makes the next advance() a no-op.
  306. func (p *textParser) back() { p.backed = true }
  307. // Advances the parser and returns the new current token.
  308. func (p *textParser) next() *token {
  309. if p.backed || p.done {
  310. p.backed = false
  311. return &p.cur
  312. }
  313. p.advance()
  314. if p.done {
  315. p.cur.value = ""
  316. } else if len(p.cur.value) > 0 && p.cur.value[0] == '"' {
  317. // Look for multiple quoted strings separated by whitespace,
  318. // and concatenate them.
  319. cat := p.cur
  320. for {
  321. p.skipWhitespace()
  322. if p.done || p.s[0] != '"' {
  323. break
  324. }
  325. p.advance()
  326. if p.cur.err != nil {
  327. return &p.cur
  328. }
  329. cat.value += " " + p.cur.value
  330. cat.unquoted += p.cur.unquoted
  331. }
  332. p.done = false // parser may have seen EOF, but we want to return cat
  333. p.cur = cat
  334. }
  335. return &p.cur
  336. }
  337. func (p *textParser) consumeToken(s string) error {
  338. tok := p.next()
  339. if tok.err != nil {
  340. return tok.err
  341. }
  342. if tok.value != s {
  343. p.back()
  344. return p.errorf("expected %q, found %q", s, tok.value)
  345. }
  346. return nil
  347. }
  348. // Return a RequiredNotSetError indicating which required field was not set.
  349. func (p *textParser) missingRequiredFieldError(sv reflect.Value) *RequiredNotSetError {
  350. st := sv.Type()
  351. sprops := GetProperties(st)
  352. for i := 0; i < st.NumField(); i++ {
  353. if !isNil(sv.Field(i)) {
  354. continue
  355. }
  356. props := sprops.Prop[i]
  357. if props.Required {
  358. return &RequiredNotSetError{fmt.Sprintf("%v.%v", st, props.OrigName)}
  359. }
  360. }
  361. return &RequiredNotSetError{fmt.Sprintf("%v.<unknown field name>", st)} // should not happen
  362. }
  363. // Returns the index in the struct for the named field, as well as the parsed tag properties.
  364. func structFieldByName(sprops *StructProperties, name string) (int, *Properties, bool) {
  365. i, ok := sprops.decoderOrigNames[name]
  366. if ok {
  367. return i, sprops.Prop[i], true
  368. }
  369. return -1, nil, false
  370. }
  371. // Consume a ':' from the input stream (if the next token is a colon),
  372. // returning an error if a colon is needed but not present.
  373. func (p *textParser) checkForColon(props *Properties, typ reflect.Type) *ParseError {
  374. tok := p.next()
  375. if tok.err != nil {
  376. return tok.err
  377. }
  378. if tok.value != ":" {
  379. // Colon is optional when the field is a group or message.
  380. needColon := true
  381. switch props.Wire {
  382. case "group":
  383. needColon = false
  384. case "bytes":
  385. // A "bytes" field is either a message, a string, or a repeated field;
  386. // those three become *T, *string and []T respectively, so we can check for
  387. // this field being a pointer to a non-string.
  388. if typ.Kind() == reflect.Ptr {
  389. // *T or *string
  390. if typ.Elem().Kind() == reflect.String {
  391. break
  392. }
  393. } else if typ.Kind() == reflect.Slice {
  394. // []T or []*T
  395. if typ.Elem().Kind() != reflect.Ptr {
  396. break
  397. }
  398. } else if typ.Kind() == reflect.String {
  399. // The proto3 exception is for a string field,
  400. // which requires a colon.
  401. break
  402. }
  403. needColon = false
  404. }
  405. if needColon {
  406. return p.errorf("expected ':', found %q", tok.value)
  407. }
  408. p.back()
  409. }
  410. return nil
  411. }
  412. func (p *textParser) readStruct(sv reflect.Value, terminator string) error {
  413. st := sv.Type()
  414. sprops := GetProperties(st)
  415. reqCount := sprops.reqCount
  416. var reqFieldErr error
  417. fieldSet := make(map[string]bool)
  418. // A struct is a sequence of "name: value", terminated by one of
  419. // '>' or '}', or the end of the input. A name may also be
  420. // "[extension]".
  421. for {
  422. tok := p.next()
  423. if tok.err != nil {
  424. return tok.err
  425. }
  426. if tok.value == terminator {
  427. break
  428. }
  429. if tok.value == "[" {
  430. // Looks like an extension.
  431. //
  432. // TODO: Check whether we need to handle
  433. // namespace rooted names (e.g. ".something.Foo").
  434. tok = p.next()
  435. if tok.err != nil {
  436. return tok.err
  437. }
  438. var desc *ExtensionDesc
  439. // This could be faster, but it's functional.
  440. // TODO: Do something smarter than a linear scan.
  441. for _, d := range RegisteredExtensions(reflect.New(st).Interface().(Message)) {
  442. if d.Name == tok.value {
  443. desc = d
  444. break
  445. }
  446. }
  447. if desc == nil {
  448. return p.errorf("unrecognized extension %q", tok.value)
  449. }
  450. // Check the extension terminator.
  451. tok = p.next()
  452. if tok.err != nil {
  453. return tok.err
  454. }
  455. if tok.value != "]" {
  456. return p.errorf("unrecognized extension terminator %q", tok.value)
  457. }
  458. props := &Properties{}
  459. props.Parse(desc.Tag)
  460. typ := reflect.TypeOf(desc.ExtensionType)
  461. if err := p.checkForColon(props, typ); err != nil {
  462. return err
  463. }
  464. rep := desc.repeated()
  465. // Read the extension structure, and set it in
  466. // the value we're constructing.
  467. var ext reflect.Value
  468. if !rep {
  469. ext = reflect.New(typ).Elem()
  470. } else {
  471. ext = reflect.New(typ.Elem()).Elem()
  472. }
  473. if err := p.readAny(ext, props); err != nil {
  474. if _, ok := err.(*RequiredNotSetError); !ok {
  475. return err
  476. }
  477. reqFieldErr = err
  478. }
  479. ep := sv.Addr().Interface().(extendableProto)
  480. if !rep {
  481. SetExtension(ep, desc, ext.Interface())
  482. } else {
  483. old, err := GetExtension(ep, desc)
  484. var sl reflect.Value
  485. if err == nil {
  486. sl = reflect.ValueOf(old) // existing slice
  487. } else {
  488. sl = reflect.MakeSlice(typ, 0, 1)
  489. }
  490. sl = reflect.Append(sl, ext)
  491. SetExtension(ep, desc, sl.Interface())
  492. }
  493. if err := p.consumeOptionalSeparator(); err != nil {
  494. return err
  495. }
  496. continue
  497. }
  498. // This is a normal, non-extension field.
  499. name := tok.value
  500. var dst reflect.Value
  501. fi, props, ok := structFieldByName(sprops, name)
  502. if ok {
  503. dst = sv.Field(fi)
  504. } else if oop, ok := sprops.OneofTypes[name]; ok {
  505. // It is a oneof.
  506. props = oop.Prop
  507. nv := reflect.New(oop.Type.Elem())
  508. dst = nv.Elem().Field(0)
  509. sv.Field(oop.Field).Set(nv)
  510. }
  511. if !dst.IsValid() {
  512. return p.errorf("unknown field name %q in %v", name, st)
  513. }
  514. if dst.Kind() == reflect.Map {
  515. // Consume any colon.
  516. if err := p.checkForColon(props, dst.Type()); err != nil {
  517. return err
  518. }
  519. // Construct the map if it doesn't already exist.
  520. if dst.IsNil() {
  521. dst.Set(reflect.MakeMap(dst.Type()))
  522. }
  523. key := reflect.New(dst.Type().Key()).Elem()
  524. val := reflect.New(dst.Type().Elem()).Elem()
  525. // The map entry should be this sequence of tokens:
  526. // < key : KEY value : VALUE >
  527. // Technically the "key" and "value" could come in any order,
  528. // but in practice they won't.
  529. tok := p.next()
  530. var terminator string
  531. switch tok.value {
  532. case "<":
  533. terminator = ">"
  534. case "{":
  535. terminator = "}"
  536. default:
  537. return p.errorf("expected '{' or '<', found %q", tok.value)
  538. }
  539. if err := p.consumeToken("key"); err != nil {
  540. return err
  541. }
  542. if err := p.consumeToken(":"); err != nil {
  543. return err
  544. }
  545. if err := p.readAny(key, props.mkeyprop); err != nil {
  546. return err
  547. }
  548. if err := p.consumeOptionalSeparator(); err != nil {
  549. return err
  550. }
  551. if err := p.consumeToken("value"); err != nil {
  552. return err
  553. }
  554. if err := p.checkForColon(props.mvalprop, dst.Type().Elem()); err != nil {
  555. return err
  556. }
  557. if err := p.readAny(val, props.mvalprop); err != nil {
  558. return err
  559. }
  560. if err := p.consumeOptionalSeparator(); err != nil {
  561. return err
  562. }
  563. if err := p.consumeToken(terminator); err != nil {
  564. return err
  565. }
  566. dst.SetMapIndex(key, val)
  567. continue
  568. }
  569. // Check that it's not already set if it's not a repeated field.
  570. if !props.Repeated && fieldSet[name] {
  571. return p.errorf("non-repeated field %q was repeated", name)
  572. }
  573. if err := p.checkForColon(props, dst.Type()); err != nil {
  574. return err
  575. }
  576. // Parse into the field.
  577. fieldSet[name] = true
  578. if err := p.readAny(dst, props); err != nil {
  579. if _, ok := err.(*RequiredNotSetError); !ok {
  580. return err
  581. }
  582. reqFieldErr = err
  583. } else if props.Required {
  584. reqCount--
  585. }
  586. if err := p.consumeOptionalSeparator(); err != nil {
  587. return err
  588. }
  589. }
  590. if reqCount > 0 {
  591. return p.missingRequiredFieldError(sv)
  592. }
  593. return reqFieldErr
  594. }
  595. // consumeOptionalSeparator consumes an optional semicolon or comma.
  596. // It is used in readStruct to provide backward compatibility.
  597. func (p *textParser) consumeOptionalSeparator() error {
  598. tok := p.next()
  599. if tok.err != nil {
  600. return tok.err
  601. }
  602. if tok.value != ";" && tok.value != "," {
  603. p.back()
  604. }
  605. return nil
  606. }
  607. func (p *textParser) readAny(v reflect.Value, props *Properties) error {
  608. tok := p.next()
  609. if tok.err != nil {
  610. return tok.err
  611. }
  612. if tok.value == "" {
  613. return p.errorf("unexpected EOF")
  614. }
  615. if len(props.CustomType) > 0 {
  616. if props.Repeated {
  617. t := reflect.TypeOf(v.Interface())
  618. if t.Kind() == reflect.Slice {
  619. tc := reflect.TypeOf(new(Marshaler))
  620. ok := t.Elem().Implements(tc.Elem())
  621. if ok {
  622. fv := v
  623. flen := fv.Len()
  624. if flen == fv.Cap() {
  625. nav := reflect.MakeSlice(v.Type(), flen, 2*flen+1)
  626. reflect.Copy(nav, fv)
  627. fv.Set(nav)
  628. }
  629. fv.SetLen(flen + 1)
  630. // Read one.
  631. p.back()
  632. return p.readAny(fv.Index(flen), props)
  633. }
  634. }
  635. }
  636. if reflect.TypeOf(v.Interface()).Kind() == reflect.Ptr {
  637. custom := reflect.New(props.ctype.Elem()).Interface().(Unmarshaler)
  638. err := custom.Unmarshal([]byte(tok.unquoted))
  639. if err != nil {
  640. return p.errorf("%v %v: %v", err, v.Type(), tok.value)
  641. }
  642. v.Set(reflect.ValueOf(custom))
  643. } else {
  644. custom := reflect.New(reflect.TypeOf(v.Interface())).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.Indirect(reflect.ValueOf(custom)))
  650. }
  651. return nil
  652. }
  653. switch fv := v; fv.Kind() {
  654. case reflect.Slice:
  655. at := v.Type()
  656. if at.Elem().Kind() == reflect.Uint8 {
  657. // Special case for []byte
  658. if tok.value[0] != '"' && tok.value[0] != '\'' {
  659. // Deliberately written out here, as the error after
  660. // this switch statement would write "invalid []byte: ...",
  661. // which is not as user-friendly.
  662. return p.errorf("invalid string: %v", tok.value)
  663. }
  664. bytes := []byte(tok.unquoted)
  665. fv.Set(reflect.ValueOf(bytes))
  666. return nil
  667. }
  668. // Repeated field.
  669. if tok.value == "[" {
  670. // Repeated field with list notation, like [1,2,3].
  671. for {
  672. fv.Set(reflect.Append(fv, reflect.New(at.Elem()).Elem()))
  673. err := p.readAny(fv.Index(fv.Len()-1), props)
  674. if err != nil {
  675. return err
  676. }
  677. tok := p.next()
  678. if tok.err != nil {
  679. return tok.err
  680. }
  681. if tok.value == "]" {
  682. break
  683. }
  684. if tok.value != "," {
  685. return p.errorf("Expected ']' or ',' found %q", tok.value)
  686. }
  687. }
  688. return nil
  689. }
  690. // One value of the repeated field.
  691. p.back()
  692. fv.Set(reflect.Append(fv, reflect.New(at.Elem()).Elem()))
  693. return p.readAny(fv.Index(fv.Len()-1), props)
  694. case reflect.Bool:
  695. // Either "true", "false", 1 or 0.
  696. switch tok.value {
  697. case "true", "1":
  698. fv.SetBool(true)
  699. return nil
  700. case "false", "0":
  701. fv.SetBool(false)
  702. return nil
  703. }
  704. case reflect.Float32, reflect.Float64:
  705. v := tok.value
  706. // Ignore 'f' for compatibility with output generated by C++, but don't
  707. // remove 'f' when the value is "-inf" or "inf".
  708. if strings.HasSuffix(v, "f") && tok.value != "-inf" && tok.value != "inf" {
  709. v = v[:len(v)-1]
  710. }
  711. if f, err := strconv.ParseFloat(v, fv.Type().Bits()); err == nil {
  712. fv.SetFloat(f)
  713. return nil
  714. }
  715. case reflect.Int32:
  716. if x, err := strconv.ParseInt(tok.value, 0, 32); err == nil {
  717. fv.SetInt(x)
  718. return nil
  719. }
  720. if len(props.Enum) == 0 {
  721. break
  722. }
  723. m, ok := enumValueMaps[props.Enum]
  724. if !ok {
  725. break
  726. }
  727. x, ok := m[tok.value]
  728. if !ok {
  729. break
  730. }
  731. fv.SetInt(int64(x))
  732. return nil
  733. case reflect.Int64:
  734. if x, err := strconv.ParseInt(tok.value, 0, 64); err == nil {
  735. fv.SetInt(x)
  736. return nil
  737. }
  738. case reflect.Ptr:
  739. // A basic field (indirected through pointer), or a repeated message/group
  740. p.back()
  741. fv.Set(reflect.New(fv.Type().Elem()))
  742. return p.readAny(fv.Elem(), props)
  743. case reflect.String:
  744. if tok.value[0] == '"' || tok.value[0] == '\'' {
  745. fv.SetString(tok.unquoted)
  746. return nil
  747. }
  748. case reflect.Struct:
  749. var terminator string
  750. switch tok.value {
  751. case "{":
  752. terminator = "}"
  753. case "<":
  754. terminator = ">"
  755. default:
  756. return p.errorf("expected '{' or '<', found %q", tok.value)
  757. }
  758. // TODO: Handle nested messages which implement encoding.TextUnmarshaler.
  759. return p.readStruct(fv, terminator)
  760. case reflect.Uint32:
  761. if x, err := strconv.ParseUint(tok.value, 0, 32); err == nil {
  762. fv.SetUint(uint64(x))
  763. return nil
  764. }
  765. case reflect.Uint64:
  766. if x, err := strconv.ParseUint(tok.value, 0, 64); err == nil {
  767. fv.SetUint(x)
  768. return nil
  769. }
  770. }
  771. return p.errorf("invalid %v: %v", v.Type(), tok.value)
  772. }
  773. // UnmarshalText reads a protocol buffer in Text format. UnmarshalText resets pb
  774. // before starting to unmarshal, so any existing data in pb is always removed.
  775. // If a required field is not set and no other error occurs,
  776. // UnmarshalText returns *RequiredNotSetError.
  777. func UnmarshalText(s string, pb Message) error {
  778. if um, ok := pb.(encoding.TextUnmarshaler); ok {
  779. err := um.UnmarshalText([]byte(s))
  780. return err
  781. }
  782. pb.Reset()
  783. v := reflect.ValueOf(pb)
  784. if pe := newTextParser(s).readStruct(v.Elem(), ""); pe != nil {
  785. return pe
  786. }
  787. return nil
  788. }