text_parser.go 11 KB

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