text_parser.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684
  1. // Go support for Protocol Buffers - Google's data interchange format
  2. //
  3. // Copyright 2010 The Go Authors. All rights reserved.
  4. // http://code.google.com/p/goprotobuf/
  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. "errors"
  36. "fmt"
  37. "reflect"
  38. "strconv"
  39. "strings"
  40. "unicode/utf8"
  41. )
  42. // textUnmarshaler is implemented by Messages that can unmarshal themsleves.
  43. // It is identical to encoding.TextUnmarshaler, introduced in go 1.2,
  44. // which will eventually replace it.
  45. type textUnmarshaler interface {
  46. UnmarshalText(text []byte) error
  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 %v", p.s[0:i+1])
  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. // Return an error indicating which required field was not set.
  338. func (p *textParser) missingRequiredFieldError(sv reflect.Value) *ParseError {
  339. st := sv.Type()
  340. sprops := GetProperties(st)
  341. for i := 0; i < st.NumField(); i++ {
  342. if !isNil(sv.Field(i)) {
  343. continue
  344. }
  345. props := sprops.Prop[i]
  346. if props.Required {
  347. return p.errorf("message %v missing required field %q", st, props.OrigName)
  348. }
  349. }
  350. return p.errorf("message %v missing required field", st) // should not happen
  351. }
  352. // Returns the index in the struct for the named field, as well as the parsed tag properties.
  353. func structFieldByName(st reflect.Type, name string) (int, *Properties, bool) {
  354. sprops := GetProperties(st)
  355. i, ok := sprops.decoderOrigNames[name]
  356. if ok {
  357. return i, sprops.Prop[i], true
  358. }
  359. return -1, nil, false
  360. }
  361. // Consume a ':' from the input stream (if the next token is a colon),
  362. // returning an error if a colon is needed but not present.
  363. func (p *textParser) checkForColon(props *Properties, typ reflect.Type) *ParseError {
  364. tok := p.next()
  365. if tok.err != nil {
  366. return tok.err
  367. }
  368. if tok.value != ":" {
  369. // Colon is optional when the field is a group or message.
  370. needColon := true
  371. switch props.Wire {
  372. case "group":
  373. needColon = false
  374. case "bytes":
  375. // A "bytes" field is either a message, a string, or a repeated field;
  376. // those three become *T, *string and []T respectively, so we can check for
  377. // this field being a pointer to a non-string.
  378. if typ.Kind() == reflect.Ptr {
  379. // *T or *string
  380. if typ.Elem().Kind() == reflect.String {
  381. break
  382. }
  383. } else if typ.Kind() == reflect.Slice {
  384. // []T or []*T
  385. if typ.Elem().Kind() != reflect.Ptr {
  386. break
  387. }
  388. }
  389. needColon = false
  390. }
  391. if needColon {
  392. return p.errorf("expected ':', found %q", tok.value)
  393. }
  394. p.back()
  395. }
  396. return nil
  397. }
  398. func (p *textParser) readStruct(sv reflect.Value, terminator string) *ParseError {
  399. st := sv.Type()
  400. reqCount := GetProperties(st).reqCount
  401. // A struct is a sequence of "name: value", terminated by one of
  402. // '>' or '}', or the end of the input. A name may also be
  403. // "[extension]".
  404. for {
  405. tok := p.next()
  406. if tok.err != nil {
  407. return tok.err
  408. }
  409. if tok.value == terminator {
  410. break
  411. }
  412. if tok.value == "[" {
  413. // Looks like an extension.
  414. //
  415. // TODO: Check whether we need to handle
  416. // namespace rooted names (e.g. ".something.Foo").
  417. tok = p.next()
  418. if tok.err != nil {
  419. return tok.err
  420. }
  421. var desc *ExtensionDesc
  422. // This could be faster, but it's functional.
  423. // TODO: Do something smarter than a linear scan.
  424. for _, d := range RegisteredExtensions(reflect.New(st).Interface().(Message)) {
  425. if d.Name == tok.value {
  426. desc = d
  427. break
  428. }
  429. }
  430. if desc == nil {
  431. return p.errorf("unrecognized extension %q", tok.value)
  432. }
  433. // Check the extension terminator.
  434. tok = p.next()
  435. if tok.err != nil {
  436. return tok.err
  437. }
  438. if tok.value != "]" {
  439. return p.errorf("unrecognized extension terminator %q", tok.value)
  440. }
  441. props := &Properties{}
  442. props.Parse(desc.Tag)
  443. typ := reflect.TypeOf(desc.ExtensionType)
  444. if err := p.checkForColon(props, typ); err != nil {
  445. return err
  446. }
  447. rep := desc.repeated()
  448. // Read the extension structure, and set it in
  449. // the value we're constructing.
  450. var ext reflect.Value
  451. if !rep {
  452. ext = reflect.New(typ).Elem()
  453. } else {
  454. ext = reflect.New(typ.Elem()).Elem()
  455. }
  456. if err := p.readAny(ext, props); err != nil {
  457. return err
  458. }
  459. ep := sv.Addr().Interface().(extendableProto)
  460. if !rep {
  461. SetExtension(ep, desc, ext.Interface())
  462. } else {
  463. old, err := GetExtension(ep, desc)
  464. var sl reflect.Value
  465. if err == nil {
  466. sl = reflect.ValueOf(old) // existing slice
  467. } else {
  468. sl = reflect.MakeSlice(typ, 0, 1)
  469. }
  470. sl = reflect.Append(sl, ext)
  471. SetExtension(ep, desc, sl.Interface())
  472. }
  473. } else {
  474. // This is a normal, non-extension field.
  475. fi, props, ok := structFieldByName(st, tok.value)
  476. if !ok {
  477. return p.errorf("unknown field name %q in %v", tok.value, st)
  478. }
  479. dst := sv.Field(fi)
  480. isDstNil := isNil(dst)
  481. // Check that it's not already set if it's not a repeated field.
  482. if !props.Repeated && !isDstNil {
  483. return p.errorf("non-repeated field %q was repeated", tok.value)
  484. }
  485. if err := p.checkForColon(props, st.Field(fi).Type); err != nil {
  486. return err
  487. }
  488. // Parse into the field.
  489. if err := p.readAny(dst, props); err != nil {
  490. return err
  491. }
  492. if props.Required {
  493. reqCount--
  494. }
  495. }
  496. // For backward compatibility, permit a semicolon or comma after a field.
  497. tok = p.next()
  498. if tok.err != nil {
  499. return tok.err
  500. }
  501. if tok.value != ";" && tok.value != "," {
  502. p.back()
  503. }
  504. }
  505. if reqCount > 0 {
  506. return p.missingRequiredFieldError(sv)
  507. }
  508. return nil
  509. }
  510. func (p *textParser) readAny(v reflect.Value, props *Properties) *ParseError {
  511. tok := p.next()
  512. if tok.err != nil {
  513. return tok.err
  514. }
  515. if tok.value == "" {
  516. return p.errorf("unexpected EOF")
  517. }
  518. switch fv := v; fv.Kind() {
  519. case reflect.Slice:
  520. at := v.Type()
  521. if at.Elem().Kind() == reflect.Uint8 {
  522. // Special case for []byte
  523. if tok.value[0] != '"' && tok.value[0] != '\'' {
  524. // Deliberately written out here, as the error after
  525. // this switch statement would write "invalid []byte: ...",
  526. // which is not as user-friendly.
  527. return p.errorf("invalid string: %v", tok.value)
  528. }
  529. bytes := []byte(tok.unquoted)
  530. fv.Set(reflect.ValueOf(bytes))
  531. return nil
  532. }
  533. // Repeated field. May already exist.
  534. flen := fv.Len()
  535. if flen == fv.Cap() {
  536. nav := reflect.MakeSlice(at, flen, 2*flen+1)
  537. reflect.Copy(nav, fv)
  538. fv.Set(nav)
  539. }
  540. fv.SetLen(flen + 1)
  541. // Read one.
  542. p.back()
  543. return p.readAny(fv.Index(flen), props)
  544. case reflect.Bool:
  545. // Either "true", "false", 1 or 0.
  546. switch tok.value {
  547. case "true", "1":
  548. fv.SetBool(true)
  549. return nil
  550. case "false", "0":
  551. fv.SetBool(false)
  552. return nil
  553. }
  554. case reflect.Float32, reflect.Float64:
  555. v := tok.value
  556. // Ignore 'f' for compatibility with output generated by C++, but don't
  557. // remove 'f' when the value is "-inf" or "inf".
  558. if strings.HasSuffix(v, "f") && tok.value != "-inf" && tok.value != "inf" {
  559. v = v[:len(v)-1]
  560. }
  561. if f, err := strconv.ParseFloat(v, fv.Type().Bits()); err == nil {
  562. fv.SetFloat(f)
  563. return nil
  564. }
  565. case reflect.Int32:
  566. if x, err := strconv.ParseInt(tok.value, 0, 32); err == nil {
  567. fv.SetInt(x)
  568. return nil
  569. }
  570. if len(props.Enum) == 0 {
  571. break
  572. }
  573. m, ok := enumValueMaps[props.Enum]
  574. if !ok {
  575. break
  576. }
  577. x, ok := m[tok.value]
  578. if !ok {
  579. break
  580. }
  581. fv.SetInt(int64(x))
  582. return nil
  583. case reflect.Int64:
  584. if x, err := strconv.ParseInt(tok.value, 0, 64); err == nil {
  585. fv.SetInt(x)
  586. return nil
  587. }
  588. case reflect.Ptr:
  589. // A basic field (indirected through pointer), or a repeated message/group
  590. p.back()
  591. fv.Set(reflect.New(fv.Type().Elem()))
  592. return p.readAny(fv.Elem(), props)
  593. case reflect.String:
  594. if tok.value[0] == '"' || tok.value[0] == '\'' {
  595. fv.SetString(tok.unquoted)
  596. return nil
  597. }
  598. case reflect.Struct:
  599. var terminator string
  600. switch tok.value {
  601. case "{":
  602. terminator = "}"
  603. case "<":
  604. terminator = ">"
  605. default:
  606. return p.errorf("expected '{' or '<', found %q", tok.value)
  607. }
  608. // TODO: Handle nested messages which implement textUnmarshaler.
  609. return p.readStruct(fv, terminator)
  610. case reflect.Uint32:
  611. if x, err := strconv.ParseUint(tok.value, 0, 32); err == nil {
  612. fv.SetUint(uint64(x))
  613. return nil
  614. }
  615. case reflect.Uint64:
  616. if x, err := strconv.ParseUint(tok.value, 0, 64); err == nil {
  617. fv.SetUint(x)
  618. return nil
  619. }
  620. }
  621. return p.errorf("invalid %v: %v", v.Type(), tok.value)
  622. }
  623. // UnmarshalText reads a protocol buffer in Text format. UnmarshalText resets pb
  624. // before starting to unmarshal, so any existing data in pb is always removed.
  625. func UnmarshalText(s string, pb Message) error {
  626. if um, ok := pb.(textUnmarshaler); ok {
  627. err := um.UnmarshalText([]byte(s))
  628. return err
  629. }
  630. pb.Reset()
  631. v := reflect.ValueOf(pb)
  632. if pe := newTextParser(s).readStruct(v.Elem(), ""); pe != nil {
  633. return pe
  634. }
  635. return nil
  636. }