blob: 31efc0516a34f077370f8827011eda6623761c5b [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 Pikeaaa3a622010-03-20 22:32:34 -070043type ParseError struct {
44 Message string
45 Line int // 1-based line number
46 Offset int // 0-based byte offset from start of input
47}
48
Rob Pikea17fdd92011-11-02 12:43:05 -070049func (p *ParseError) Error() string {
Rob Pikeaaa3a622010-03-20 22:32:34 -070050 if p.Line == 1 {
51 // show offset only for first line
52 return fmt.Sprintf("line 1.%d: %v", p.Offset, p.Message)
53 }
54 return fmt.Sprintf("line %d: %v", p.Line, p.Message)
55}
56
57type token struct {
58 value string
59 err *ParseError
60 line int // line number
61 offset int // byte number from start of input, not start of line
62 unquoted string // the unquoted version of value, if it was a quoted string
63}
64
65func (t *token) String() string {
66 if t.err == nil {
67 return fmt.Sprintf("%q (line=%d, offset=%d)", t.value, t.line, t.offset)
68 }
69 return fmt.Sprintf("parse error: %v", t.err)
70}
71
72type textParser struct {
73 s string // remaining input
74 done bool // whether the parsing is finished (success or error)
75 backed bool // whether back() was called
76 offset, line int
77 cur token
78}
79
80func 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
Rob Piked6420b82011-04-13 16:37:04 -070088func (p *textParser) errorf(format string, a ...interface{}) *ParseError {
Rob Pikead7cac72010-09-29 12:29:26 -070089 pe := &ParseError{fmt.Sprintf(format, a...), p.cur.line, p.cur.offset}
Rob Pikeaaa3a622010-03-20 22:32:34 -070090 p.cur.err = pe
91 p.done = true
92 return pe
93}
94
95// Numbers and identifiers are matched by [-+._A-Za-z0-9]
96func isIdentOrNumberChar(c byte) bool {
97 switch {
98 case 'A' <= c && c <= 'Z', 'a' <= c && c <= 'z':
99 return true
100 case '0' <= c && c <= '9':
101 return true
102 }
103 switch c {
104 case '-', '+', '.', '_':
105 return true
106 }
107 return false
108}
109
110func isWhitespace(c byte) bool {
111 switch c {
112 case ' ', '\t', '\n', '\r':
113 return true
114 }
115 return false
116}
117
118func (p *textParser) skipWhitespace() {
119 i := 0
120 for i < len(p.s) && (isWhitespace(p.s[i]) || p.s[i] == '#') {
121 if p.s[i] == '#' {
122 // comment; skip to end of line or input
123 for i < len(p.s) && p.s[i] != '\n' {
124 i++
125 }
126 if i == len(p.s) {
127 break
128 }
129 }
130 if p.s[i] == '\n' {
131 p.line++
132 }
133 i++
134 }
135 p.offset += i
136 p.s = p.s[i:len(p.s)]
137 if len(p.s) == 0 {
138 p.done = true
139 }
140}
141
142func (p *textParser) advance() {
143 // Skip whitespace
144 p.skipWhitespace()
145 if p.done {
146 return
147 }
148
149 // Start of non-whitespace
150 p.cur.err = nil
151 p.cur.offset, p.cur.line = p.offset, p.line
152 p.cur.unquoted = ""
153 switch p.s[0] {
154 case '<', '>', '{', '}', ':':
155 // Single symbol
156 p.cur.value, p.s = p.s[0:1], p.s[1:len(p.s)]
157 case '"':
158 // Quoted string
159 i := 1
160 for i < len(p.s) && p.s[i] != '"' && p.s[i] != '\n' {
161 if p.s[i] == '\\' && i+1 < len(p.s) {
162 // skip escaped char
163 i++
164 }
165 i++
166 }
167 if i >= len(p.s) || p.s[i] != '"' {
Rob Piked6420b82011-04-13 16:37:04 -0700168 p.errorf("unmatched quote")
Rob Pikeaaa3a622010-03-20 22:32:34 -0700169 return
170 }
171 // TODO: Should be UnquoteC.
172 unq, err := strconv.Unquote(p.s[0 : i+1])
173 if err != nil {
Rob Piked6420b82011-04-13 16:37:04 -0700174 p.errorf("invalid quoted string %v", p.s[0:i+1])
Rob Pikeaaa3a622010-03-20 22:32:34 -0700175 return
176 }
177 p.cur.value, p.s = p.s[0:i+1], p.s[i+1:len(p.s)]
178 p.cur.unquoted = unq
179 default:
180 i := 0
181 for i < len(p.s) && isIdentOrNumberChar(p.s[i]) {
182 i++
183 }
184 if i == 0 {
Rob Piked6420b82011-04-13 16:37:04 -0700185 p.errorf("unexpected byte %#x", p.s[0])
Rob Pikeaaa3a622010-03-20 22:32:34 -0700186 return
187 }
188 p.cur.value, p.s = p.s[0:i], p.s[i:len(p.s)]
189 }
190 p.offset += len(p.cur.value)
191}
192
193// Back off the parser by one token. Can only be done between calls to next().
194// It makes the next advance() a no-op.
195func (p *textParser) back() { p.backed = true }
196
197// Advances the parser and returns the new current token.
198func (p *textParser) next() *token {
199 if p.backed || p.done {
200 p.backed = false
201 return &p.cur
202 }
203 p.advance()
204 if p.done {
205 p.cur.value = ""
206 } else if len(p.cur.value) > 0 && p.cur.value[0] == '"' {
207 // Look for multiple quoted strings separated by whitespace,
208 // and concatenate them.
209 cat := p.cur
210 for {
211 p.skipWhitespace()
212 if p.done || p.s[0] != '"' {
213 break
214 }
215 p.advance()
216 if p.cur.err != nil {
217 return &p.cur
218 }
219 cat.value += " " + p.cur.value
220 cat.unquoted += p.cur.unquoted
221 }
222 p.done = false // parser may have seen EOF, but we want to return cat
223 p.cur = cat
224 }
225 return &p.cur
226}
227
Rob Pikeaaa3a622010-03-20 22:32:34 -0700228// Return an error indicating which required field was not set.
Rob Pike97e934d2011-04-11 12:52:49 -0700229func (p *textParser) missingRequiredFieldError(sv reflect.Value) *ParseError {
230 st := sv.Type()
Rob Pikeaaa3a622010-03-20 22:32:34 -0700231 sprops := GetProperties(st)
232 for i := 0; i < st.NumField(); i++ {
Rob Pike97e934d2011-04-11 12:52:49 -0700233 if !isNil(sv.Field(i)) {
Rob Pikeaaa3a622010-03-20 22:32:34 -0700234 continue
235 }
236
237 props := sprops.Prop[i]
238 if props.Required {
Rob Piked6420b82011-04-13 16:37:04 -0700239 return p.errorf("message %v missing required field %q", st, props.OrigName)
Rob Pikeaaa3a622010-03-20 22:32:34 -0700240 }
241 }
Rob Piked6420b82011-04-13 16:37:04 -0700242 return p.errorf("message %v missing required field", st) // should not happen
Rob Pikeaaa3a622010-03-20 22:32:34 -0700243}
244
245// Returns the index in the struct for the named field, as well as the parsed tag properties.
Rob Pike97e934d2011-04-11 12:52:49 -0700246func structFieldByName(st reflect.Type, name string) (int, *Properties, bool) {
Rob Pikeaaa3a622010-03-20 22:32:34 -0700247 sprops := GetProperties(st)
David Symonds79eae332010-10-16 11:33:20 +1100248 i, ok := sprops.origNames[name]
249 if ok {
250 return i, sprops.Prop[i], true
Rob Pikeaaa3a622010-03-20 22:32:34 -0700251 }
252 return -1, nil, false
253}
254
Rob Pike97e934d2011-04-11 12:52:49 -0700255func (p *textParser) readStruct(sv reflect.Value, terminator string) *ParseError {
256 st := sv.Type()
Rob Pikeaaa3a622010-03-20 22:32:34 -0700257 reqCount := GetProperties(st).reqCount
258 // A struct is a sequence of "name: value", terminated by one of
259 // '>' or '}', or the end of the input.
260 for {
261 tok := p.next()
262 if tok.err != nil {
263 return tok.err
264 }
265 if tok.value == terminator {
266 break
267 }
268
269 fi, props, ok := structFieldByName(st, tok.value)
270 if !ok {
Rob Piked6420b82011-04-13 16:37:04 -0700271 return p.errorf("unknown field name %q in %v", tok.value, st)
Rob Pikeaaa3a622010-03-20 22:32:34 -0700272 }
273
274 // Check that it's not already set if it's not a repeated field.
Rob Pike97e934d2011-04-11 12:52:49 -0700275 if !props.Repeated && !isNil(sv.Field(fi)) {
Rob Piked6420b82011-04-13 16:37:04 -0700276 return p.errorf("non-repeated field %q was repeated", tok.value)
Rob Pikeaaa3a622010-03-20 22:32:34 -0700277 }
278
279 tok = p.next()
280 if tok.err != nil {
281 return tok.err
282 }
283 if tok.value != ":" {
284 // Colon is optional when the field is a group or message.
285 needColon := true
286 switch props.Wire {
287 case "group":
288 needColon = false
289 case "bytes":
290 // A "bytes" field is either a message, a string, or a repeated field;
291 // those three become *T, *string and []T respectively, so we can check for
292 // this field being a pointer to a non-string.
293 typ := st.Field(fi).Type
David Symondsa9cda212011-04-15 01:23:17 -0700294 if typ.Kind() == reflect.Ptr {
Rob Pikeaaf695a2010-06-22 15:51:21 -0700295 // *T or *string
David Symondsa9cda212011-04-15 01:23:17 -0700296 if typ.Elem().Kind() == reflect.String {
Rob Pikeaaf695a2010-06-22 15:51:21 -0700297 break
298 }
David Symondsa9cda212011-04-15 01:23:17 -0700299 } else if typ.Kind() == reflect.Slice {
Rob Pikeaaf695a2010-06-22 15:51:21 -0700300 // []T or []*T
David Symondsa9cda212011-04-15 01:23:17 -0700301 if typ.Elem().Kind() != reflect.Ptr {
Rob Pikeaaf695a2010-06-22 15:51:21 -0700302 break
303 }
Rob Pikeaaa3a622010-03-20 22:32:34 -0700304 }
305 needColon = false
306 }
307 if needColon {
Rob Piked6420b82011-04-13 16:37:04 -0700308 return p.errorf("expected ':', found %q", tok.value)
Rob Pikeaaa3a622010-03-20 22:32:34 -0700309 }
310 p.back()
311 }
312
313 // Parse into the field.
314 if err := p.readAny(sv.Field(fi), props); err != nil {
315 return err
316 }
317
318 if props.Required {
319 reqCount--
320 }
321 }
322
323 if reqCount > 0 {
324 return p.missingRequiredFieldError(sv)
325 }
326 return nil
327}
328
329const (
330 minInt32 = -1 << 31
331 maxInt32 = 1<<31 - 1
332 maxUint32 = 1<<32 - 1
333)
334
335func (p *textParser) readAny(v reflect.Value, props *Properties) *ParseError {
336 tok := p.next()
337 if tok.err != nil {
338 return tok.err
339 }
340 if tok.value == "" {
Rob Piked6420b82011-04-13 16:37:04 -0700341 return p.errorf("unexpected EOF")
Rob Pikeaaa3a622010-03-20 22:32:34 -0700342 }
343
Rob Pike97e934d2011-04-11 12:52:49 -0700344 switch fv := v; fv.Kind() {
345 case reflect.Slice:
346 at := v.Type()
Rob Pikeab5b8022010-06-21 17:47:58 -0700347 if at.Elem().Kind() == reflect.Uint8 {
Rob Pikeaaa3a622010-03-20 22:32:34 -0700348 // Special case for []byte
349 if tok.value[0] != '"' {
350 // Deliberately written out here, as the error after
351 // this switch statement would write "invalid []byte: ...",
352 // which is not as user-friendly.
Rob Piked6420b82011-04-13 16:37:04 -0700353 return p.errorf("invalid string: %v", tok.value)
Rob Pikeaaa3a622010-03-20 22:32:34 -0700354 }
355 bytes := []byte(tok.unquoted)
Nigel Tao4ede8452011-04-28 11:27:25 +1000356 fv.Set(reflect.ValueOf(bytes))
Rob Pikeaaa3a622010-03-20 22:32:34 -0700357 return nil
358 }
359 // Repeated field. May already exist.
David Symonds79eae332010-10-16 11:33:20 +1100360 flen := fv.Len()
361 if flen == fv.Cap() {
362 nav := reflect.MakeSlice(at, flen, 2*flen+1)
Rob Pike48fd4a42010-12-14 23:40:41 -0800363 reflect.Copy(nav, fv)
David Symonds79eae332010-10-16 11:33:20 +1100364 fv.Set(nav)
365 }
366 fv.SetLen(flen + 1)
Rob Pikeaaa3a622010-03-20 22:32:34 -0700367
368 // Read one.
369 p.back()
David Symondsef8f0e82011-10-13 12:57:34 +1100370 return p.readAny(fv.Index(flen), props)
Rob Pike97e934d2011-04-11 12:52:49 -0700371 case reflect.Bool:
Rob Pikeaaa3a622010-03-20 22:32:34 -0700372 // Either "true", "false", 1 or 0.
373 switch tok.value {
374 case "true", "1":
Rob Pike97e934d2011-04-11 12:52:49 -0700375 fv.SetBool(true)
Rob Pikeaaa3a622010-03-20 22:32:34 -0700376 return nil
377 case "false", "0":
Rob Pike97e934d2011-04-11 12:52:49 -0700378 fv.SetBool(false)
Rob Pikeaaa3a622010-03-20 22:32:34 -0700379 return nil
380 }
Rob Pike97e934d2011-04-11 12:52:49 -0700381 case reflect.Float32, reflect.Float64:
Rob Pikeab5b8022010-06-21 17:47:58 -0700382 if f, err := strconv.AtofN(tok.value, fv.Type().Bits()); err == nil {
Rob Pike97e934d2011-04-11 12:52:49 -0700383 fv.SetFloat(f)
Rob Pikeaaa3a622010-03-20 22:32:34 -0700384 return nil
385 }
Rob Pike19b2dbb2011-04-11 16:49:15 -0700386 case reflect.Int32:
387 if x, err := strconv.Atoi64(tok.value); err == nil && minInt32 <= x && x <= maxInt32 {
388 fv.SetInt(x)
Rob Pikeaaa3a622010-03-20 22:32:34 -0700389 return nil
Rob Pike19b2dbb2011-04-11 16:49:15 -0700390 }
391 if len(props.Enum) == 0 {
392 break
393 }
394 m, ok := enumValueMaps[props.Enum]
395 if !ok {
396 break
397 }
398 x, ok := m[tok.value]
399 if !ok {
400 break
401 }
402 fv.SetInt(int64(x))
403 return nil
404 case reflect.Int64:
405 if x, err := strconv.Atoi64(tok.value); err == nil {
406 fv.SetInt(x)
407 return nil
Rob Pikeaaa3a622010-03-20 22:32:34 -0700408 }
Rob Pike97e934d2011-04-11 12:52:49 -0700409 case reflect.Ptr:
Rob Pikeaaa3a622010-03-20 22:32:34 -0700410 // A basic field (indirected through pointer), or a repeated message/group
411 p.back()
Rob Pikeccd260c2011-04-18 13:13:04 -0700412 fv.Set(reflect.New(fv.Type().Elem()))
Rob Pikeaaa3a622010-03-20 22:32:34 -0700413 return p.readAny(fv.Elem(), props)
Rob Pike97e934d2011-04-11 12:52:49 -0700414 case reflect.String:
Rob Pikeaaa3a622010-03-20 22:32:34 -0700415 if tok.value[0] == '"' {
Rob Pike97e934d2011-04-11 12:52:49 -0700416 fv.SetString(tok.unquoted)
Rob Pikeaaa3a622010-03-20 22:32:34 -0700417 return nil
418 }
Rob Pike97e934d2011-04-11 12:52:49 -0700419 case reflect.Struct:
Rob Pikeaaa3a622010-03-20 22:32:34 -0700420 var terminator string
421 switch tok.value {
422 case "{":
423 terminator = "}"
424 case "<":
425 terminator = ">"
426 default:
Rob Piked6420b82011-04-13 16:37:04 -0700427 return p.errorf("expected '{' or '<', found %q", tok.value)
Rob Pikeaaa3a622010-03-20 22:32:34 -0700428 }
429 return p.readStruct(fv, terminator)
Rob Pike19b2dbb2011-04-11 16:49:15 -0700430 case reflect.Uint32:
431 if x, err := strconv.Atoui64(tok.value); err == nil && x <= maxUint32 {
432 fv.SetUint(uint64(x))
433 return nil
434 }
435 case reflect.Uint64:
436 if x, err := strconv.Atoui64(tok.value); err == nil {
437 fv.SetUint(x)
438 return nil
Rob Pikeaaa3a622010-03-20 22:32:34 -0700439 }
440 }
Rob Piked6420b82011-04-13 16:37:04 -0700441 return p.errorf("invalid %v: %v", v.Type(), tok.value)
Rob Pikeaaa3a622010-03-20 22:32:34 -0700442}
443
Rob Pikea17fdd92011-11-02 12:43:05 -0700444var notPtrStruct error = &ParseError{"destination is not a pointer to a struct", 0, 0}
Rob Pikeaaa3a622010-03-20 22:32:34 -0700445
446// UnmarshalText reads a protobuffer in Text format.
Rob Pikea17fdd92011-11-02 12:43:05 -0700447func UnmarshalText(s string, pb interface{}) error {
Nigel Tao4ede8452011-04-28 11:27:25 +1000448 v := reflect.ValueOf(pb)
David Symondsa9cda212011-04-15 01:23:17 -0700449 if v.Kind() != reflect.Ptr || v.Elem().Kind() != reflect.Struct {
Rob Pikeaaa3a622010-03-20 22:32:34 -0700450 return notPtrStruct
451 }
David Symondsa9cda212011-04-15 01:23:17 -0700452 if pe := newTextParser(s).readStruct(v.Elem(), ""); pe != nil {
Rob Pikeaaa3a622010-03-20 22:32:34 -0700453 return pe
454 }
455 return nil
456}