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