text_parser.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  1. // Go support for Protocol Buffers - Google's data interchange format
  2. //
  3. // Copyright 2010 Google Inc. 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, extensions.
  34. import (
  35. "fmt"
  36. "reflect"
  37. "strconv"
  38. )
  39. // ParseError satisfies the error interface.
  40. type ParseError struct {
  41. Message string
  42. Line int // 1-based line number
  43. Offset int // 0-based byte offset from start of input
  44. }
  45. func (p *ParseError) Error() string {
  46. if p.Line == 1 {
  47. // show offset only for first line
  48. return fmt.Sprintf("line 1.%d: %v", p.Offset, p.Message)
  49. }
  50. return fmt.Sprintf("line %d: %v", p.Line, p.Message)
  51. }
  52. type token struct {
  53. value string
  54. err *ParseError
  55. line int // line number
  56. offset int // byte number from start of input, not start of line
  57. unquoted string // the unquoted version of value, if it was a quoted string
  58. }
  59. func (t *token) String() string {
  60. if t.err == nil {
  61. return fmt.Sprintf("%q (line=%d, offset=%d)", t.value, t.line, t.offset)
  62. }
  63. return fmt.Sprintf("parse error: %v", t.err)
  64. }
  65. type textParser struct {
  66. s string // remaining input
  67. done bool // whether the parsing is finished (success or error)
  68. backed bool // whether back() was called
  69. offset, line int
  70. cur token
  71. }
  72. func newTextParser(s string) *textParser {
  73. p := new(textParser)
  74. p.s = s
  75. p.line = 1
  76. p.cur.line = 1
  77. return p
  78. }
  79. func (p *textParser) errorf(format string, a ...interface{}) *ParseError {
  80. pe := &ParseError{fmt.Sprintf(format, a...), p.cur.line, p.cur.offset}
  81. p.cur.err = pe
  82. p.done = true
  83. return pe
  84. }
  85. // Numbers and identifiers are matched by [-+._A-Za-z0-9]
  86. func isIdentOrNumberChar(c byte) bool {
  87. switch {
  88. case 'A' <= c && c <= 'Z', 'a' <= c && c <= 'z':
  89. return true
  90. case '0' <= c && c <= '9':
  91. return true
  92. }
  93. switch c {
  94. case '-', '+', '.', '_':
  95. return true
  96. }
  97. return false
  98. }
  99. func isWhitespace(c byte) bool {
  100. switch c {
  101. case ' ', '\t', '\n', '\r':
  102. return true
  103. }
  104. return false
  105. }
  106. func (p *textParser) skipWhitespace() {
  107. i := 0
  108. for i < len(p.s) && (isWhitespace(p.s[i]) || p.s[i] == '#') {
  109. if p.s[i] == '#' {
  110. // comment; skip to end of line or input
  111. for i < len(p.s) && p.s[i] != '\n' {
  112. i++
  113. }
  114. if i == len(p.s) {
  115. break
  116. }
  117. }
  118. if p.s[i] == '\n' {
  119. p.line++
  120. }
  121. i++
  122. }
  123. p.offset += i
  124. p.s = p.s[i:len(p.s)]
  125. if len(p.s) == 0 {
  126. p.done = true
  127. }
  128. }
  129. func (p *textParser) advance() {
  130. // Skip whitespace
  131. p.skipWhitespace()
  132. if p.done {
  133. return
  134. }
  135. // Start of non-whitespace
  136. p.cur.err = nil
  137. p.cur.offset, p.cur.line = p.offset, p.line
  138. p.cur.unquoted = ""
  139. switch p.s[0] {
  140. case '<', '>', '{', '}', ':':
  141. // Single symbol
  142. p.cur.value, p.s = p.s[0:1], p.s[1:len(p.s)]
  143. case '"':
  144. // Quoted string
  145. i := 1
  146. for i < len(p.s) && p.s[i] != '"' && p.s[i] != '\n' {
  147. if p.s[i] == '\\' && i+1 < len(p.s) {
  148. // skip escaped char
  149. i++
  150. }
  151. i++
  152. }
  153. if i >= len(p.s) || p.s[i] != '"' {
  154. p.errorf("unmatched quote")
  155. return
  156. }
  157. // TODO: Should be UnquoteC.
  158. unq, err := strconv.Unquote(p.s[0 : i+1])
  159. if err != nil {
  160. p.errorf("invalid quoted string %v", p.s[0:i+1])
  161. return
  162. }
  163. p.cur.value, p.s = p.s[0:i+1], p.s[i+1:len(p.s)]
  164. p.cur.unquoted = unq
  165. default:
  166. i := 0
  167. for i < len(p.s) && isIdentOrNumberChar(p.s[i]) {
  168. i++
  169. }
  170. if i == 0 {
  171. p.errorf("unexpected byte %#x", p.s[0])
  172. return
  173. }
  174. p.cur.value, p.s = p.s[0:i], p.s[i:len(p.s)]
  175. }
  176. p.offset += len(p.cur.value)
  177. }
  178. // Back off the parser by one token. Can only be done between calls to next().
  179. // It makes the next advance() a no-op.
  180. func (p *textParser) back() { p.backed = true }
  181. // Advances the parser and returns the new current token.
  182. func (p *textParser) next() *token {
  183. if p.backed || p.done {
  184. p.backed = false
  185. return &p.cur
  186. }
  187. p.advance()
  188. if p.done {
  189. p.cur.value = ""
  190. } else if len(p.cur.value) > 0 && p.cur.value[0] == '"' {
  191. // Look for multiple quoted strings separated by whitespace,
  192. // and concatenate them.
  193. cat := p.cur
  194. for {
  195. p.skipWhitespace()
  196. if p.done || p.s[0] != '"' {
  197. break
  198. }
  199. p.advance()
  200. if p.cur.err != nil {
  201. return &p.cur
  202. }
  203. cat.value += " " + p.cur.value
  204. cat.unquoted += p.cur.unquoted
  205. }
  206. p.done = false // parser may have seen EOF, but we want to return cat
  207. p.cur = cat
  208. }
  209. return &p.cur
  210. }
  211. // Return an error indicating which required field was not set.
  212. func (p *textParser) missingRequiredFieldError(sv reflect.Value) *ParseError {
  213. st := sv.Type()
  214. sprops := GetProperties(st)
  215. for i := 0; i < st.NumField(); i++ {
  216. if !isNil(sv.Field(i)) {
  217. continue
  218. }
  219. props := sprops.Prop[i]
  220. if props.Required {
  221. return p.errorf("message %v missing required field %q", st, props.OrigName)
  222. }
  223. }
  224. return p.errorf("message %v missing required field", st) // should not happen
  225. }
  226. // Returns the index in the struct for the named field, as well as the parsed tag properties.
  227. func structFieldByName(st reflect.Type, name string) (int, *Properties, bool) {
  228. sprops := GetProperties(st)
  229. i, ok := sprops.origNames[name]
  230. if ok {
  231. return i, sprops.Prop[i], true
  232. }
  233. return -1, nil, false
  234. }
  235. func (p *textParser) readStruct(sv reflect.Value, terminator string) *ParseError {
  236. st := sv.Type()
  237. reqCount := GetProperties(st).reqCount
  238. // A struct is a sequence of "name: value", terminated by one of
  239. // '>' or '}', or the end of the input.
  240. for {
  241. tok := p.next()
  242. if tok.err != nil {
  243. return tok.err
  244. }
  245. if tok.value == terminator {
  246. break
  247. }
  248. fi, props, ok := structFieldByName(st, tok.value)
  249. if !ok {
  250. return p.errorf("unknown field name %q in %v", tok.value, st)
  251. }
  252. // Check that it's not already set if it's not a repeated field.
  253. if !props.Repeated && !isNil(sv.Field(fi)) {
  254. return p.errorf("non-repeated field %q was repeated", tok.value)
  255. }
  256. tok = p.next()
  257. if tok.err != nil {
  258. return tok.err
  259. }
  260. if tok.value != ":" {
  261. // Colon is optional when the field is a group or message.
  262. needColon := true
  263. switch props.Wire {
  264. case "group":
  265. needColon = false
  266. case "bytes":
  267. // A "bytes" field is either a message, a string, or a repeated field;
  268. // those three become *T, *string and []T respectively, so we can check for
  269. // this field being a pointer to a non-string.
  270. typ := st.Field(fi).Type
  271. if typ.Kind() == reflect.Ptr {
  272. // *T or *string
  273. if typ.Elem().Kind() == reflect.String {
  274. break
  275. }
  276. } else if typ.Kind() == reflect.Slice {
  277. // []T or []*T
  278. if typ.Elem().Kind() != reflect.Ptr {
  279. break
  280. }
  281. }
  282. needColon = false
  283. }
  284. if needColon {
  285. return p.errorf("expected ':', found %q", tok.value)
  286. }
  287. p.back()
  288. }
  289. // Parse into the field.
  290. if err := p.readAny(sv.Field(fi), props); err != nil {
  291. return err
  292. }
  293. if props.Required {
  294. reqCount--
  295. }
  296. }
  297. if reqCount > 0 {
  298. return p.missingRequiredFieldError(sv)
  299. }
  300. return nil
  301. }
  302. const (
  303. minInt32 = -1 << 31
  304. maxInt32 = 1<<31 - 1
  305. maxUint32 = 1<<32 - 1
  306. )
  307. func (p *textParser) readAny(v reflect.Value, props *Properties) *ParseError {
  308. tok := p.next()
  309. if tok.err != nil {
  310. return tok.err
  311. }
  312. if tok.value == "" {
  313. return p.errorf("unexpected EOF")
  314. }
  315. switch fv := v; fv.Kind() {
  316. case reflect.Slice:
  317. at := v.Type()
  318. if at.Elem().Kind() == reflect.Uint8 {
  319. // Special case for []byte
  320. if tok.value[0] != '"' {
  321. // Deliberately written out here, as the error after
  322. // this switch statement would write "invalid []byte: ...",
  323. // which is not as user-friendly.
  324. return p.errorf("invalid string: %v", tok.value)
  325. }
  326. bytes := []byte(tok.unquoted)
  327. fv.Set(reflect.ValueOf(bytes))
  328. return nil
  329. }
  330. // Repeated field. May already exist.
  331. flen := fv.Len()
  332. if flen == fv.Cap() {
  333. nav := reflect.MakeSlice(at, flen, 2*flen+1)
  334. reflect.Copy(nav, fv)
  335. fv.Set(nav)
  336. }
  337. fv.SetLen(flen + 1)
  338. // Read one.
  339. p.back()
  340. return p.readAny(fv.Index(flen), props)
  341. case reflect.Bool:
  342. // Either "true", "false", 1 or 0.
  343. switch tok.value {
  344. case "true", "1":
  345. fv.SetBool(true)
  346. return nil
  347. case "false", "0":
  348. fv.SetBool(false)
  349. return nil
  350. }
  351. case reflect.Float32, reflect.Float64:
  352. if f, err := strconv.AtofN(tok.value, fv.Type().Bits()); err == nil {
  353. fv.SetFloat(f)
  354. return nil
  355. }
  356. case reflect.Int32:
  357. if x, err := strconv.Atoi64(tok.value); err == nil && minInt32 <= x && x <= maxInt32 {
  358. fv.SetInt(x)
  359. return nil
  360. }
  361. if len(props.Enum) == 0 {
  362. break
  363. }
  364. m, ok := enumValueMaps[props.Enum]
  365. if !ok {
  366. break
  367. }
  368. x, ok := m[tok.value]
  369. if !ok {
  370. break
  371. }
  372. fv.SetInt(int64(x))
  373. return nil
  374. case reflect.Int64:
  375. if x, err := strconv.Atoi64(tok.value); err == nil {
  376. fv.SetInt(x)
  377. return nil
  378. }
  379. case reflect.Ptr:
  380. // A basic field (indirected through pointer), or a repeated message/group
  381. p.back()
  382. fv.Set(reflect.New(fv.Type().Elem()))
  383. return p.readAny(fv.Elem(), props)
  384. case reflect.String:
  385. if tok.value[0] == '"' {
  386. fv.SetString(tok.unquoted)
  387. return nil
  388. }
  389. case reflect.Struct:
  390. var terminator string
  391. switch tok.value {
  392. case "{":
  393. terminator = "}"
  394. case "<":
  395. terminator = ">"
  396. default:
  397. return p.errorf("expected '{' or '<', found %q", tok.value)
  398. }
  399. return p.readStruct(fv, terminator)
  400. case reflect.Uint32:
  401. if x, err := strconv.Atoui64(tok.value); err == nil && x <= maxUint32 {
  402. fv.SetUint(uint64(x))
  403. return nil
  404. }
  405. case reflect.Uint64:
  406. if x, err := strconv.Atoui64(tok.value); err == nil {
  407. fv.SetUint(x)
  408. return nil
  409. }
  410. }
  411. return p.errorf("invalid %v: %v", v.Type(), tok.value)
  412. }
  413. var notPtrStruct error = &ParseError{"destination is not a pointer to a struct", 0, 0}
  414. // UnmarshalText reads a protobuffer in Text format.
  415. func UnmarshalText(s string, pb interface{}) error {
  416. v := reflect.ValueOf(pb)
  417. if v.Kind() != reflect.Ptr || v.Elem().Kind() != reflect.Struct {
  418. return notPtrStruct
  419. }
  420. if pe := newTextParser(s).readStruct(v.Elem(), ""); pe != nil {
  421. return pe
  422. }
  423. return nil
  424. }