blob: 358764b7713dd7cda1f6e1861f0d363f76e70d62 [file] [log] [blame]
Rob Pikeaaa3a622010-03-20 22:32:34 -07001// 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
32package proto
33
34// Functions for parsing the Text protocol buffer format.
David Symonds9f402812011-04-28 18:08:44 +100035// TODO: message sets, extensions.
Rob Pikeaaa3a622010-03-20 22:32:34 -070036
37import (
38 "fmt"
Rob Pikeaaa3a622010-03-20 22:32:34 -070039 "reflect"
40 "strconv"
41)
42
Rob Pikea17fdd92011-11-02 12:43:05 -070043// ParseError satisfies the error interface.
Rob Pikeaaa3a622010-03-20 22:32:34 -070044type ParseError struct {
45 Message string
46 Line int // 1-based line number
47 Offset int // 0-based byte offset from start of input
48}
49
Rob Pikea17fdd92011-11-02 12:43:05 -070050func (p *ParseError) Error() string {
Rob Pikeaaa3a622010-03-20 22:32:34 -070051 if p.Line == 1 {
52 // show offset only for first line
53 return fmt.Sprintf("line 1.%d: %v", p.Offset, p.Message)
54 }
55 return fmt.Sprintf("line %d: %v", p.Line, p.Message)
56}
57
58type token struct {
59 value string
60 err *ParseError
61 line int // line number
62 offset int // byte number from start of input, not start of line
63 unquoted string // the unquoted version of value, if it was a quoted string
64}
65
66func (t *token) String() string {
67 if t.err == nil {
68 return fmt.Sprintf("%q (line=%d, offset=%d)", t.value, t.line, t.offset)
69 }
70 return fmt.Sprintf("parse error: %v", t.err)
71}
72
73type 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
81func newTextParser(s string) *textParser {
82 p := new(textParser)
83 p.s = s
84 p.line = 1
85 p.cur.line = 1
86 return p
87}
88
Rob Piked6420b82011-04-13 16:37:04 -070089func (p *textParser) errorf(format string, a ...interface{}) *ParseError {
Rob Pikead7cac72010-09-29 12:29:26 -070090 pe := &ParseError{fmt.Sprintf(format, a...), p.cur.line, p.cur.offset}
Rob Pikeaaa3a622010-03-20 22:32:34 -070091 p.cur.err = pe
92 p.done = true
93 return pe
94}
95
96// Numbers and identifiers are matched by [-+._A-Za-z0-9]
97func isIdentOrNumberChar(c byte) bool {
98 switch {
99 case 'A' <= c && c <= 'Z', 'a' <= c && c <= 'z':
100 return true
101 case '0' <= c && c <= '9':
102 return true
103 }
104 switch c {
105 case '-', '+', '.', '_':
106 return true
107 }
108 return false
109}
110
111func isWhitespace(c byte) bool {
112 switch c {
113 case ' ', '\t', '\n', '\r':
114 return true
115 }
116 return false
117}
118
119func (p *textParser) skipWhitespace() {
120 i := 0
121 for i < len(p.s) && (isWhitespace(p.s[i]) || p.s[i] == '#') {
122 if p.s[i] == '#' {
123 // comment; skip to end of line or input
124 for i < len(p.s) && p.s[i] != '\n' {
125 i++
126 }
127 if i == len(p.s) {
128 break
129 }
130 }
131 if p.s[i] == '\n' {
132 p.line++
133 }
134 i++
135 }
136 p.offset += i
137 p.s = p.s[i:len(p.s)]
138 if len(p.s) == 0 {
139 p.done = true
140 }
141}
142
143func (p *textParser) advance() {
144 // Skip whitespace
145 p.skipWhitespace()
146 if p.done {
147 return
148 }
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[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] != '"' {
Rob Piked6420b82011-04-13 16:37:04 -0700169 p.errorf("unmatched quote")
Rob Pikeaaa3a622010-03-20 22:32:34 -0700170 return
171 }
172 // TODO: Should be UnquoteC.
173 unq, err := strconv.Unquote(p.s[0 : i+1])
174 if err != nil {
Rob Piked6420b82011-04-13 16:37:04 -0700175 p.errorf("invalid quoted string %v", p.s[0:i+1])
Rob Pikeaaa3a622010-03-20 22:32:34 -0700176 return
177 }
178 p.cur.value, p.s = p.s[0:i+1], p.s[i+1:len(p.s)]
179 p.cur.unquoted = unq
180 default:
181 i := 0
182 for i < len(p.s) && isIdentOrNumberChar(p.s[i]) {
183 i++
184 }
185 if i == 0 {
Rob Piked6420b82011-04-13 16:37:04 -0700186 p.errorf("unexpected byte %#x", p.s[0])
Rob Pikeaaa3a622010-03-20 22:32:34 -0700187 return
188 }
189 p.cur.value, p.s = p.s[0:i], p.s[i:len(p.s)]
190 }
191 p.offset += len(p.cur.value)
192}
193
194// Back off the parser by one token. Can only be done between calls to next().
195// It makes the next advance() a no-op.
196func (p *textParser) back() { p.backed = true }
197
198// Advances the parser and returns the new current token.
199func (p *textParser) next() *token {
200 if p.backed || p.done {
201 p.backed = false
202 return &p.cur
203 }
204 p.advance()
205 if p.done {
206 p.cur.value = ""
207 } else if len(p.cur.value) > 0 && p.cur.value[0] == '"' {
208 // Look for multiple quoted strings separated by whitespace,
209 // and concatenate them.
210 cat := p.cur
211 for {
212 p.skipWhitespace()
213 if p.done || p.s[0] != '"' {
214 break
215 }
216 p.advance()
217 if p.cur.err != nil {
218 return &p.cur
219 }
220 cat.value += " " + p.cur.value
221 cat.unquoted += p.cur.unquoted
222 }
223 p.done = false // parser may have seen EOF, but we want to return cat
224 p.cur = cat
225 }
226 return &p.cur
227}
228
Rob Pikeaaa3a622010-03-20 22:32:34 -0700229// Return an error indicating which required field was not set.
Rob Pike97e934d2011-04-11 12:52:49 -0700230func (p *textParser) missingRequiredFieldError(sv reflect.Value) *ParseError {
231 st := sv.Type()
Rob Pikeaaa3a622010-03-20 22:32:34 -0700232 sprops := GetProperties(st)
233 for i := 0; i < st.NumField(); i++ {
Rob Pike97e934d2011-04-11 12:52:49 -0700234 if !isNil(sv.Field(i)) {
Rob Pikeaaa3a622010-03-20 22:32:34 -0700235 continue
236 }
237
238 props := sprops.Prop[i]
239 if props.Required {
Rob Piked6420b82011-04-13 16:37:04 -0700240 return p.errorf("message %v missing required field %q", st, props.OrigName)
Rob Pikeaaa3a622010-03-20 22:32:34 -0700241 }
242 }
Rob Piked6420b82011-04-13 16:37:04 -0700243 return p.errorf("message %v missing required field", st) // should not happen
Rob Pikeaaa3a622010-03-20 22:32:34 -0700244}
245
246// Returns the index in the struct for the named field, as well as the parsed tag properties.
Rob Pike97e934d2011-04-11 12:52:49 -0700247func structFieldByName(st reflect.Type, name string) (int, *Properties, bool) {
Rob Pikeaaa3a622010-03-20 22:32:34 -0700248 sprops := GetProperties(st)
David Symonds79eae332010-10-16 11:33:20 +1100249 i, ok := sprops.origNames[name]
250 if ok {
251 return i, sprops.Prop[i], true
Rob Pikeaaa3a622010-03-20 22:32:34 -0700252 }
253 return -1, nil, false
254}
255
Rob Pike97e934d2011-04-11 12:52:49 -0700256func (p *textParser) readStruct(sv reflect.Value, terminator string) *ParseError {
257 st := sv.Type()
Rob Pikeaaa3a622010-03-20 22:32:34 -0700258 reqCount := GetProperties(st).reqCount
259 // A struct is a sequence of "name: value", terminated by one of
260 // '>' or '}', or the end of the input.
261 for {
262 tok := p.next()
263 if tok.err != nil {
264 return tok.err
265 }
266 if tok.value == terminator {
267 break
268 }
269
270 fi, props, ok := structFieldByName(st, tok.value)
271 if !ok {
Rob Piked6420b82011-04-13 16:37:04 -0700272 return p.errorf("unknown field name %q in %v", tok.value, st)
Rob Pikeaaa3a622010-03-20 22:32:34 -0700273 }
274
275 // Check that it's not already set if it's not a repeated field.
Rob Pike97e934d2011-04-11 12:52:49 -0700276 if !props.Repeated && !isNil(sv.Field(fi)) {
Rob Piked6420b82011-04-13 16:37:04 -0700277 return p.errorf("non-repeated field %q was repeated", tok.value)
Rob Pikeaaa3a622010-03-20 22:32:34 -0700278 }
279
280 tok = p.next()
281 if tok.err != nil {
282 return tok.err
283 }
284 if tok.value != ":" {
285 // Colon is optional when the field is a group or message.
286 needColon := true
287 switch props.Wire {
288 case "group":
289 needColon = false
290 case "bytes":
291 // A "bytes" field is either a message, a string, or a repeated field;
292 // those three become *T, *string and []T respectively, so we can check for
293 // this field being a pointer to a non-string.
294 typ := st.Field(fi).Type
David Symondsa9cda212011-04-15 01:23:17 -0700295 if typ.Kind() == reflect.Ptr {
Rob Pikeaaf695a2010-06-22 15:51:21 -0700296 // *T or *string
David Symondsa9cda212011-04-15 01:23:17 -0700297 if typ.Elem().Kind() == reflect.String {
Rob Pikeaaf695a2010-06-22 15:51:21 -0700298 break
299 }
David Symondsa9cda212011-04-15 01:23:17 -0700300 } else if typ.Kind() == reflect.Slice {
Rob Pikeaaf695a2010-06-22 15:51:21 -0700301 // []T or []*T
David Symondsa9cda212011-04-15 01:23:17 -0700302 if typ.Elem().Kind() != reflect.Ptr {
Rob Pikeaaf695a2010-06-22 15:51:21 -0700303 break
304 }
Rob Pikeaaa3a622010-03-20 22:32:34 -0700305 }
306 needColon = false
307 }
308 if needColon {
Rob Piked6420b82011-04-13 16:37:04 -0700309 return p.errorf("expected ':', found %q", tok.value)
Rob Pikeaaa3a622010-03-20 22:32:34 -0700310 }
311 p.back()
312 }
313
314 // Parse into the field.
315 if err := p.readAny(sv.Field(fi), props); err != nil {
316 return err
317 }
318
319 if props.Required {
320 reqCount--
321 }
322 }
323
324 if reqCount > 0 {
325 return p.missingRequiredFieldError(sv)
326 }
327 return nil
328}
329
330const (
331 minInt32 = -1 << 31
332 maxInt32 = 1<<31 - 1
333 maxUint32 = 1<<32 - 1
334)
335
336func (p *textParser) readAny(v reflect.Value, props *Properties) *ParseError {
337 tok := p.next()
338 if tok.err != nil {
339 return tok.err
340 }
341 if tok.value == "" {
Rob Piked6420b82011-04-13 16:37:04 -0700342 return p.errorf("unexpected EOF")
Rob Pikeaaa3a622010-03-20 22:32:34 -0700343 }
344
Rob Pike97e934d2011-04-11 12:52:49 -0700345 switch fv := v; fv.Kind() {
346 case reflect.Slice:
347 at := v.Type()
Rob Pikeab5b8022010-06-21 17:47:58 -0700348 if at.Elem().Kind() == reflect.Uint8 {
Rob Pikeaaa3a622010-03-20 22:32:34 -0700349 // Special case for []byte
350 if tok.value[0] != '"' {
351 // Deliberately written out here, as the error after
352 // this switch statement would write "invalid []byte: ...",
353 // which is not as user-friendly.
Rob Piked6420b82011-04-13 16:37:04 -0700354 return p.errorf("invalid string: %v", tok.value)
Rob Pikeaaa3a622010-03-20 22:32:34 -0700355 }
356 bytes := []byte(tok.unquoted)
Nigel Tao4ede8452011-04-28 11:27:25 +1000357 fv.Set(reflect.ValueOf(bytes))
Rob Pikeaaa3a622010-03-20 22:32:34 -0700358 return nil
359 }
360 // Repeated field. May already exist.
David Symonds79eae332010-10-16 11:33:20 +1100361 flen := fv.Len()
362 if flen == fv.Cap() {
363 nav := reflect.MakeSlice(at, flen, 2*flen+1)
Rob Pike48fd4a42010-12-14 23:40:41 -0800364 reflect.Copy(nav, fv)
David Symonds79eae332010-10-16 11:33:20 +1100365 fv.Set(nav)
366 }
367 fv.SetLen(flen + 1)
Rob Pikeaaa3a622010-03-20 22:32:34 -0700368
369 // Read one.
370 p.back()
David Symondsef8f0e82011-10-13 12:57:34 +1100371 return p.readAny(fv.Index(flen), props)
Rob Pike97e934d2011-04-11 12:52:49 -0700372 case reflect.Bool:
Rob Pikeaaa3a622010-03-20 22:32:34 -0700373 // Either "true", "false", 1 or 0.
374 switch tok.value {
375 case "true", "1":
Rob Pike97e934d2011-04-11 12:52:49 -0700376 fv.SetBool(true)
Rob Pikeaaa3a622010-03-20 22:32:34 -0700377 return nil
378 case "false", "0":
Rob Pike97e934d2011-04-11 12:52:49 -0700379 fv.SetBool(false)
Rob Pikeaaa3a622010-03-20 22:32:34 -0700380 return nil
381 }
Rob Pike97e934d2011-04-11 12:52:49 -0700382 case reflect.Float32, reflect.Float64:
Rob Pikeab5b8022010-06-21 17:47:58 -0700383 if f, err := strconv.AtofN(tok.value, fv.Type().Bits()); err == nil {
Rob Pike97e934d2011-04-11 12:52:49 -0700384 fv.SetFloat(f)
Rob Pikeaaa3a622010-03-20 22:32:34 -0700385 return nil
386 }
Rob Pike19b2dbb2011-04-11 16:49:15 -0700387 case reflect.Int32:
388 if x, err := strconv.Atoi64(tok.value); err == nil && minInt32 <= x && x <= maxInt32 {
389 fv.SetInt(x)
Rob Pikeaaa3a622010-03-20 22:32:34 -0700390 return nil
Rob Pike19b2dbb2011-04-11 16:49:15 -0700391 }
392 if len(props.Enum) == 0 {
393 break
394 }
395 m, ok := enumValueMaps[props.Enum]
396 if !ok {
397 break
398 }
399 x, ok := m[tok.value]
400 if !ok {
401 break
402 }
403 fv.SetInt(int64(x))
404 return nil
405 case reflect.Int64:
406 if x, err := strconv.Atoi64(tok.value); err == nil {
407 fv.SetInt(x)
408 return nil
Rob Pikeaaa3a622010-03-20 22:32:34 -0700409 }
Rob Pike97e934d2011-04-11 12:52:49 -0700410 case reflect.Ptr:
Rob Pikeaaa3a622010-03-20 22:32:34 -0700411 // A basic field (indirected through pointer), or a repeated message/group
412 p.back()
Rob Pikeccd260c2011-04-18 13:13:04 -0700413 fv.Set(reflect.New(fv.Type().Elem()))
Rob Pikeaaa3a622010-03-20 22:32:34 -0700414 return p.readAny(fv.Elem(), props)
Rob Pike97e934d2011-04-11 12:52:49 -0700415 case reflect.String:
Rob Pikeaaa3a622010-03-20 22:32:34 -0700416 if tok.value[0] == '"' {
Rob Pike97e934d2011-04-11 12:52:49 -0700417 fv.SetString(tok.unquoted)
Rob Pikeaaa3a622010-03-20 22:32:34 -0700418 return nil
419 }
Rob Pike97e934d2011-04-11 12:52:49 -0700420 case reflect.Struct:
Rob Pikeaaa3a622010-03-20 22:32:34 -0700421 var terminator string
422 switch tok.value {
423 case "{":
424 terminator = "}"
425 case "<":
426 terminator = ">"
427 default:
Rob Piked6420b82011-04-13 16:37:04 -0700428 return p.errorf("expected '{' or '<', found %q", tok.value)
Rob Pikeaaa3a622010-03-20 22:32:34 -0700429 }
430 return p.readStruct(fv, terminator)
Rob Pike19b2dbb2011-04-11 16:49:15 -0700431 case reflect.Uint32:
432 if x, err := strconv.Atoui64(tok.value); err == nil && x <= maxUint32 {
433 fv.SetUint(uint64(x))
434 return nil
435 }
436 case reflect.Uint64:
437 if x, err := strconv.Atoui64(tok.value); err == nil {
438 fv.SetUint(x)
439 return nil
Rob Pikeaaa3a622010-03-20 22:32:34 -0700440 }
441 }
Rob Piked6420b82011-04-13 16:37:04 -0700442 return p.errorf("invalid %v: %v", v.Type(), tok.value)
Rob Pikeaaa3a622010-03-20 22:32:34 -0700443}
444
Rob Pikea17fdd92011-11-02 12:43:05 -0700445var notPtrStruct error = &ParseError{"destination is not a pointer to a struct", 0, 0}
Rob Pikeaaa3a622010-03-20 22:32:34 -0700446
447// UnmarshalText reads a protobuffer in Text format.
Rob Pikea17fdd92011-11-02 12:43:05 -0700448func UnmarshalText(s string, pb interface{}) error {
Nigel Tao4ede8452011-04-28 11:27:25 +1000449 v := reflect.ValueOf(pb)
David Symondsa9cda212011-04-15 01:23:17 -0700450 if v.Kind() != reflect.Ptr || v.Elem().Kind() != reflect.Struct {
Rob Pikeaaa3a622010-03-20 22:32:34 -0700451 return notPtrStruct
452 }
David Symondsa9cda212011-04-15 01:23:17 -0700453 if pe := newTextParser(s).readStruct(v.Elem(), ""); pe != nil {
Rob Pikeaaa3a622010-03-20 22:32:34 -0700454 return pe
455 }
456 return nil
457}