blob: 2e2a67fffa1af10875afe7420461f32027dcb801 [file] [log] [blame]
Rob Pikeaaa3a622010-03-20 22:32:34 -07001// Go support for Protocol Buffers - Google's data interchange format
2//
David Symondsee6e9c52012-11-29 08:51:07 +11003// Copyright 2010 The Go Authors. All rights reserved.
David Symonds558f13f2014-11-24 10:28:53 +11004// https://github.com/golang/protobuf
Rob Pikeaaa3a622010-03-20 22:32:34 -07005//
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 Symonds54531052011-12-08 12:00:31 +110035// TODO: message sets.
Rob Pikeaaa3a622010-03-20 22:32:34 -070036
37import (
David Symonds81177532014-11-20 14:33:40 +110038 "encoding"
David Symondsfa94a1e2012-09-24 13:21:49 +100039 "errors"
Rob Pikeaaa3a622010-03-20 22:32:34 -070040 "fmt"
Rob Pikeaaa3a622010-03-20 22:32:34 -070041 "reflect"
42 "strconv"
David Symonds183124e2012-03-23 13:20:23 +110043 "strings"
David Symondsfa94a1e2012-09-24 13:21:49 +100044 "unicode/utf8"
Rob Pikeaaa3a622010-03-20 22:32:34 -070045)
46
Rob Pikeaaa3a622010-03-20 22:32:34 -070047type ParseError struct {
48 Message string
49 Line int // 1-based line number
50 Offset int // 0-based byte offset from start of input
51}
52
Rob Pikea17fdd92011-11-02 12:43:05 -070053func (p *ParseError) Error() string {
Rob Pikeaaa3a622010-03-20 22:32:34 -070054 if p.Line == 1 {
55 // show offset only for first line
56 return fmt.Sprintf("line 1.%d: %v", p.Offset, p.Message)
57 }
58 return fmt.Sprintf("line %d: %v", p.Line, p.Message)
59}
60
61type token struct {
62 value string
63 err *ParseError
64 line int // line number
65 offset int // byte number from start of input, not start of line
66 unquoted string // the unquoted version of value, if it was a quoted string
67}
68
69func (t *token) String() string {
70 if t.err == nil {
71 return fmt.Sprintf("%q (line=%d, offset=%d)", t.value, t.line, t.offset)
72 }
73 return fmt.Sprintf("parse error: %v", t.err)
74}
75
76type textParser struct {
77 s string // remaining input
78 done bool // whether the parsing is finished (success or error)
79 backed bool // whether back() was called
80 offset, line int
81 cur token
82}
83
84func newTextParser(s string) *textParser {
85 p := new(textParser)
86 p.s = s
87 p.line = 1
88 p.cur.line = 1
89 return p
90}
91
Rob Piked6420b82011-04-13 16:37:04 -070092func (p *textParser) errorf(format string, a ...interface{}) *ParseError {
Rob Pikead7cac72010-09-29 12:29:26 -070093 pe := &ParseError{fmt.Sprintf(format, a...), p.cur.line, p.cur.offset}
Rob Pikeaaa3a622010-03-20 22:32:34 -070094 p.cur.err = pe
95 p.done = true
96 return pe
97}
98
99// Numbers and identifiers are matched by [-+._A-Za-z0-9]
100func isIdentOrNumberChar(c byte) bool {
101 switch {
102 case 'A' <= c && c <= 'Z', 'a' <= c && c <= 'z':
103 return true
104 case '0' <= c && c <= '9':
105 return true
106 }
107 switch c {
108 case '-', '+', '.', '_':
109 return true
110 }
111 return false
112}
113
114func isWhitespace(c byte) bool {
115 switch c {
116 case ' ', '\t', '\n', '\r':
117 return true
118 }
119 return false
120}
121
122func (p *textParser) skipWhitespace() {
123 i := 0
124 for i < len(p.s) && (isWhitespace(p.s[i]) || p.s[i] == '#') {
125 if p.s[i] == '#' {
126 // comment; skip to end of line or input
127 for i < len(p.s) && p.s[i] != '\n' {
128 i++
129 }
130 if i == len(p.s) {
131 break
132 }
133 }
134 if p.s[i] == '\n' {
135 p.line++
136 }
137 i++
138 }
139 p.offset += i
140 p.s = p.s[i:len(p.s)]
141 if len(p.s) == 0 {
142 p.done = true
143 }
144}
145
146func (p *textParser) advance() {
147 // Skip whitespace
148 p.skipWhitespace()
149 if p.done {
150 return
151 }
152
153 // Start of non-whitespace
154 p.cur.err = nil
155 p.cur.offset, p.cur.line = p.offset, p.line
156 p.cur.unquoted = ""
157 switch p.s[0] {
David Symondsbe02a4a2012-12-06 15:20:41 +1100158 case '<', '>', '{', '}', ':', '[', ']', ';', ',':
Rob Pikeaaa3a622010-03-20 22:32:34 -0700159 // Single symbol
160 p.cur.value, p.s = p.s[0:1], p.s[1:len(p.s)]
David Symonds162d0032012-06-28 09:44:46 -0700161 case '"', '\'':
Rob Pikeaaa3a622010-03-20 22:32:34 -0700162 // Quoted string
163 i := 1
David Symonds162d0032012-06-28 09:44:46 -0700164 for i < len(p.s) && p.s[i] != p.s[0] && p.s[i] != '\n' {
Rob Pikeaaa3a622010-03-20 22:32:34 -0700165 if p.s[i] == '\\' && i+1 < len(p.s) {
166 // skip escaped char
167 i++
168 }
169 i++
170 }
David Symonds162d0032012-06-28 09:44:46 -0700171 if i >= len(p.s) || p.s[i] != p.s[0] {
Rob Piked6420b82011-04-13 16:37:04 -0700172 p.errorf("unmatched quote")
Rob Pikeaaa3a622010-03-20 22:32:34 -0700173 return
174 }
David Symondsfa94a1e2012-09-24 13:21:49 +1000175 unq, err := unquoteC(p.s[1:i], rune(p.s[0]))
Rob Pikeaaa3a622010-03-20 22:32:34 -0700176 if err != nil {
David Symondsbafa7bc2015-07-01 07:59:00 +1000177 p.errorf("invalid quoted string %s: %v", p.s[0:i+1], err)
Rob Pikeaaa3a622010-03-20 22:32:34 -0700178 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 {
Rob Piked6420b82011-04-13 16:37:04 -0700188 p.errorf("unexpected byte %#x", p.s[0])
Rob Pikeaaa3a622010-03-20 22:32:34 -0700189 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
David Symondsfa94a1e2012-09-24 13:21:49 +1000196var (
David Symondsa7f3a0f2013-09-09 13:32:33 +1000197 errBadUTF8 = errors.New("proto: bad UTF-8")
198 errBadHex = errors.New("proto: bad hexadecimal")
David Symondsfa94a1e2012-09-24 13:21:49 +1000199)
200
201func unquoteC(s string, quote rune) (string, error) {
202 // This is based on C++'s tokenizer.cc.
203 // Despite its name, this is *not* parsing C syntax.
204 // For instance, "\0" is an invalid quoted string.
205
206 // Avoid allocation in trivial cases.
207 simple := true
208 for _, r := range s {
209 if r == '\\' || r == quote {
210 simple = false
211 break
212 }
David Symonds162d0032012-06-28 09:44:46 -0700213 }
David Symondsfa94a1e2012-09-24 13:21:49 +1000214 if simple {
215 return s, nil
216 }
217
218 buf := make([]byte, 0, 3*len(s)/2)
219 for len(s) > 0 {
220 r, n := utf8.DecodeRuneInString(s)
221 if r == utf8.RuneError && n == 1 {
222 return "", errBadUTF8
223 }
224 s = s[n:]
225 if r != '\\' {
226 if r < utf8.RuneSelf {
227 buf = append(buf, byte(r))
228 } else {
229 buf = append(buf, string(r)...)
230 }
231 continue
232 }
233
234 ch, tail, err := unescape(s)
235 if err != nil {
236 return "", err
237 }
238 buf = append(buf, ch...)
239 s = tail
240 }
241 return string(buf), nil
David Symonds162d0032012-06-28 09:44:46 -0700242}
243
David Symondsfa94a1e2012-09-24 13:21:49 +1000244func unescape(s string) (ch string, tail string, err error) {
245 r, n := utf8.DecodeRuneInString(s)
246 if r == utf8.RuneError && n == 1 {
247 return "", "", errBadUTF8
David Symonds162d0032012-06-28 09:44:46 -0700248 }
David Symondsfa94a1e2012-09-24 13:21:49 +1000249 s = s[n:]
250 switch r {
251 case 'a':
252 return "\a", s, nil
253 case 'b':
254 return "\b", s, nil
255 case 'f':
256 return "\f", s, nil
257 case 'n':
258 return "\n", s, nil
259 case 'r':
260 return "\r", s, nil
261 case 't':
262 return "\t", s, nil
263 case 'v':
264 return "\v", s, nil
265 case '?':
266 return "?", s, nil // trigraph workaround
267 case '\'', '"', '\\':
268 return string(r), s, nil
269 case '0', '1', '2', '3', '4', '5', '6', '7', 'x', 'X':
270 if len(s) < 2 {
271 return "", "", fmt.Errorf(`\%c requires 2 following digits`, r)
272 }
273 base := 8
274 ss := s[:2]
275 s = s[2:]
276 if r == 'x' || r == 'X' {
277 base = 16
278 } else {
279 ss = string(r) + ss
280 }
281 i, err := strconv.ParseUint(ss, base, 8)
282 if err != nil {
283 return "", "", err
284 }
285 return string([]byte{byte(i)}), s, nil
286 case 'u', 'U':
287 n := 4
288 if r == 'U' {
289 n = 8
290 }
291 if len(s) < n {
292 return "", "", fmt.Errorf(`\%c requires %d digits`, r, n)
293 }
David Symonds162d0032012-06-28 09:44:46 -0700294
David Symondsfa94a1e2012-09-24 13:21:49 +1000295 bs := make([]byte, n/2)
296 for i := 0; i < n; i += 2 {
297 a, ok1 := unhex(s[i])
298 b, ok2 := unhex(s[i+1])
299 if !ok1 || !ok2 {
300 return "", "", errBadHex
301 }
302 bs[i/2] = a<<4 | b
303 }
304 s = s[n:]
305 return string(bs), s, nil
306 }
307 return "", "", fmt.Errorf(`unknown escape \%c`, r)
308}
309
310// Adapted from src/pkg/strconv/quote.go.
311func unhex(b byte) (v byte, ok bool) {
312 switch {
313 case '0' <= b && b <= '9':
314 return b - '0', true
315 case 'a' <= b && b <= 'f':
316 return b - 'a' + 10, true
317 case 'A' <= b && b <= 'F':
318 return b - 'A' + 10, true
319 }
320 return 0, false
David Symonds183124e2012-03-23 13:20:23 +1100321}
322
Rob Pikeaaa3a622010-03-20 22:32:34 -0700323// Back off the parser by one token. Can only be done between calls to next().
324// It makes the next advance() a no-op.
325func (p *textParser) back() { p.backed = true }
326
327// Advances the parser and returns the new current token.
328func (p *textParser) next() *token {
329 if p.backed || p.done {
330 p.backed = false
331 return &p.cur
332 }
333 p.advance()
334 if p.done {
335 p.cur.value = ""
336 } else if len(p.cur.value) > 0 && p.cur.value[0] == '"' {
337 // Look for multiple quoted strings separated by whitespace,
338 // and concatenate them.
339 cat := p.cur
340 for {
341 p.skipWhitespace()
342 if p.done || p.s[0] != '"' {
343 break
344 }
345 p.advance()
346 if p.cur.err != nil {
347 return &p.cur
348 }
349 cat.value += " " + p.cur.value
350 cat.unquoted += p.cur.unquoted
351 }
352 p.done = false // parser may have seen EOF, but we want to return cat
353 p.cur = cat
354 }
355 return &p.cur
356}
357
David Symonds3ea3e052014-12-22 16:15:28 +1100358func (p *textParser) consumeToken(s string) error {
359 tok := p.next()
360 if tok.err != nil {
361 return tok.err
362 }
363 if tok.value != s {
364 p.back()
365 return p.errorf("expected %q, found %q", s, tok.value)
366 }
367 return nil
368}
369
David Symonds2a1c6b92014-10-12 16:42:41 +1100370// Return a RequiredNotSetError indicating which required field was not set.
371func (p *textParser) missingRequiredFieldError(sv reflect.Value) *RequiredNotSetError {
Rob Pike97e934d2011-04-11 12:52:49 -0700372 st := sv.Type()
Rob Pikeaaa3a622010-03-20 22:32:34 -0700373 sprops := GetProperties(st)
374 for i := 0; i < st.NumField(); i++ {
Rob Pike97e934d2011-04-11 12:52:49 -0700375 if !isNil(sv.Field(i)) {
Rob Pikeaaa3a622010-03-20 22:32:34 -0700376 continue
377 }
378
379 props := sprops.Prop[i]
380 if props.Required {
David Symonds2a1c6b92014-10-12 16:42:41 +1100381 return &RequiredNotSetError{fmt.Sprintf("%v.%v", st, props.OrigName)}
Rob Pikeaaa3a622010-03-20 22:32:34 -0700382 }
383 }
David Symonds2a1c6b92014-10-12 16:42:41 +1100384 return &RequiredNotSetError{fmt.Sprintf("%v.<unknown field name>", st)} // should not happen
Rob Pikeaaa3a622010-03-20 22:32:34 -0700385}
386
387// Returns the index in the struct for the named field, as well as the parsed tag properties.
David Symonds59b73b32015-08-24 13:22:02 +1000388func structFieldByName(sprops *StructProperties, name string) (int, *Properties, bool) {
David Symonds2bba1b22012-09-26 14:53:08 +1000389 i, ok := sprops.decoderOrigNames[name]
David Symonds79eae332010-10-16 11:33:20 +1100390 if ok {
391 return i, sprops.Prop[i], true
Rob Pikeaaa3a622010-03-20 22:32:34 -0700392 }
393 return -1, nil, false
394}
395
David Symonds54531052011-12-08 12:00:31 +1100396// Consume a ':' from the input stream (if the next token is a colon),
397// returning an error if a colon is needed but not present.
398func (p *textParser) checkForColon(props *Properties, typ reflect.Type) *ParseError {
399 tok := p.next()
400 if tok.err != nil {
401 return tok.err
402 }
403 if tok.value != ":" {
404 // Colon is optional when the field is a group or message.
405 needColon := true
406 switch props.Wire {
407 case "group":
408 needColon = false
409 case "bytes":
410 // A "bytes" field is either a message, a string, or a repeated field;
411 // those three become *T, *string and []T respectively, so we can check for
412 // this field being a pointer to a non-string.
413 if typ.Kind() == reflect.Ptr {
414 // *T or *string
415 if typ.Elem().Kind() == reflect.String {
416 break
417 }
418 } else if typ.Kind() == reflect.Slice {
419 // []T or []*T
420 if typ.Elem().Kind() != reflect.Ptr {
421 break
422 }
David Symondsabd3b412014-11-28 11:43:44 +1100423 } else if typ.Kind() == reflect.String {
424 // The proto3 exception is for a string field,
425 // which requires a colon.
426 break
David Symonds54531052011-12-08 12:00:31 +1100427 }
428 needColon = false
429 }
430 if needColon {
431 return p.errorf("expected ':', found %q", tok.value)
432 }
433 p.back()
434 }
435 return nil
436}
437
David Symonds2a1c6b92014-10-12 16:42:41 +1100438func (p *textParser) readStruct(sv reflect.Value, terminator string) error {
Rob Pike97e934d2011-04-11 12:52:49 -0700439 st := sv.Type()
David Symonds59b73b32015-08-24 13:22:02 +1000440 sprops := GetProperties(st)
441 reqCount := sprops.reqCount
David Symonds2a1c6b92014-10-12 16:42:41 +1100442 var reqFieldErr error
David Symonds8a099d02014-10-30 12:40:51 +1100443 fieldSet := make(map[string]bool)
Rob Pikeaaa3a622010-03-20 22:32:34 -0700444 // A struct is a sequence of "name: value", terminated by one of
David Symonds54531052011-12-08 12:00:31 +1100445 // '>' or '}', or the end of the input. A name may also be
446 // "[extension]".
Rob Pikeaaa3a622010-03-20 22:32:34 -0700447 for {
448 tok := p.next()
449 if tok.err != nil {
450 return tok.err
451 }
452 if tok.value == terminator {
453 break
454 }
David Symonds54531052011-12-08 12:00:31 +1100455 if tok.value == "[" {
456 // Looks like an extension.
457 //
458 // TODO: Check whether we need to handle
459 // namespace rooted names (e.g. ".something.Foo").
460 tok = p.next()
461 if tok.err != nil {
462 return tok.err
463 }
464 var desc *ExtensionDesc
465 // This could be faster, but it's functional.
466 // TODO: Do something smarter than a linear scan.
David Symonds9f60f432012-06-14 09:45:25 +1000467 for _, d := range RegisteredExtensions(reflect.New(st).Interface().(Message)) {
David Symonds54531052011-12-08 12:00:31 +1100468 if d.Name == tok.value {
469 desc = d
470 break
Rob Pikeaaa3a622010-03-20 22:32:34 -0700471 }
Rob Pikeaaa3a622010-03-20 22:32:34 -0700472 }
David Symonds54531052011-12-08 12:00:31 +1100473 if desc == nil {
474 return p.errorf("unrecognized extension %q", tok.value)
Rob Pikeaaa3a622010-03-20 22:32:34 -0700475 }
David Symonds54531052011-12-08 12:00:31 +1100476 // Check the extension terminator.
477 tok = p.next()
478 if tok.err != nil {
479 return tok.err
480 }
481 if tok.value != "]" {
482 return p.errorf("unrecognized extension terminator %q", tok.value)
483 }
Rob Pikeaaa3a622010-03-20 22:32:34 -0700484
David Symonds54531052011-12-08 12:00:31 +1100485 props := &Properties{}
486 props.Parse(desc.Tag)
Rob Pikeaaa3a622010-03-20 22:32:34 -0700487
David Symonds54531052011-12-08 12:00:31 +1100488 typ := reflect.TypeOf(desc.ExtensionType)
489 if err := p.checkForColon(props, typ); err != nil {
490 return err
491 }
492
David Symonds61826da2012-05-05 09:31:28 +1000493 rep := desc.repeated()
494
David Symonds54531052011-12-08 12:00:31 +1100495 // Read the extension structure, and set it in
496 // the value we're constructing.
David Symonds61826da2012-05-05 09:31:28 +1000497 var ext reflect.Value
498 if !rep {
499 ext = reflect.New(typ).Elem()
500 } else {
501 ext = reflect.New(typ.Elem()).Elem()
502 }
David Symonds54531052011-12-08 12:00:31 +1100503 if err := p.readAny(ext, props); err != nil {
David Symonds2a1c6b92014-10-12 16:42:41 +1100504 if _, ok := err.(*RequiredNotSetError); !ok {
505 return err
506 }
507 reqFieldErr = err
David Symonds54531052011-12-08 12:00:31 +1100508 }
David Symonds61826da2012-05-05 09:31:28 +1000509 ep := sv.Addr().Interface().(extendableProto)
510 if !rep {
511 SetExtension(ep, desc, ext.Interface())
512 } else {
513 old, err := GetExtension(ep, desc)
514 var sl reflect.Value
515 if err == nil {
516 sl = reflect.ValueOf(old) // existing slice
517 } else {
518 sl = reflect.MakeSlice(typ, 0, 1)
519 }
520 sl = reflect.Append(sl, ext)
521 SetExtension(ep, desc, sl.Interface())
522 }
David Symonds59b73b32015-08-24 13:22:02 +1000523 if err := p.consumeOptionalSeparator(); err != nil {
524 return err
525 }
526 continue
527 }
528
529 // This is a normal, non-extension field.
530 name := tok.value
531 var dst reflect.Value
532 fi, props, ok := structFieldByName(sprops, name)
533 if ok {
534 dst = sv.Field(fi)
David Symonds54531052011-12-08 12:00:31 +1100535 } else {
David Symonds59b73b32015-08-24 13:22:02 +1000536 // Maybe it is a oneof.
537 // TODO: If this shows in profiles, cache the mapping.
538 for _, oot := range sprops.oneofTypes {
539 sp := reflect.ValueOf(oot).Type() // *T
540 var p Properties
541 p.Parse(sp.Elem().Field(0).Tag.Get("protobuf"))
542 if p.OrigName != name {
543 continue
544 }
545 nv := reflect.New(sp.Elem())
546 dst = nv.Elem().Field(0)
547 props = &p
548 // There will be exactly one interface field that
549 // this new value is assignable to.
550 for i := 0; i < st.NumField(); i++ {
551 f := st.Field(i)
552 if f.Type.Kind() != reflect.Interface {
553 continue
554 }
555 if !nv.Type().AssignableTo(f.Type) {
556 continue
557 }
558 sv.Field(i).Set(nv)
559 break
560 }
561 break
David Symonds54531052011-12-08 12:00:31 +1100562 }
David Symonds59b73b32015-08-24 13:22:02 +1000563 }
564 if !dst.IsValid() {
565 return p.errorf("unknown field name %q in %v", name, st)
566 }
David Symonds54531052011-12-08 12:00:31 +1100567
David Symonds59b73b32015-08-24 13:22:02 +1000568 if dst.Kind() == reflect.Map {
569 // Consume any colon.
570 if err := p.checkForColon(props, dst.Type()); err != nil {
David Symonds54531052011-12-08 12:00:31 +1100571 return err
572 }
573
David Symonds59b73b32015-08-24 13:22:02 +1000574 // Construct the map if it doesn't already exist.
575 if dst.IsNil() {
576 dst.Set(reflect.MakeMap(dst.Type()))
David Symonds54531052011-12-08 12:00:31 +1100577 }
David Symonds59b73b32015-08-24 13:22:02 +1000578 key := reflect.New(dst.Type().Key()).Elem()
579 val := reflect.New(dst.Type().Elem()).Elem()
580
581 // The map entry should be this sequence of tokens:
582 // < key : KEY value : VALUE >
583 // Technically the "key" and "value" could come in any order,
584 // but in practice they won't.
585
586 tok := p.next()
587 var terminator string
588 switch tok.value {
589 case "<":
590 terminator = ">"
591 case "{":
592 terminator = "}"
593 default:
594 return p.errorf("expected '{' or '<', found %q", tok.value)
595 }
596 if err := p.consumeToken("key"); err != nil {
597 return err
598 }
599 if err := p.consumeToken(":"); err != nil {
600 return err
601 }
602 if err := p.readAny(key, props.mkeyprop); err != nil {
603 return err
604 }
605 if err := p.consumeOptionalSeparator(); err != nil {
606 return err
607 }
608 if err := p.consumeToken("value"); err != nil {
609 return err
610 }
611 if err := p.checkForColon(props.mvalprop, dst.Type().Elem()); err != nil {
612 return err
613 }
614 if err := p.readAny(val, props.mvalprop); err != nil {
615 return err
616 }
617 if err := p.consumeOptionalSeparator(); err != nil {
618 return err
619 }
620 if err := p.consumeToken(terminator); err != nil {
621 return err
622 }
623
624 dst.SetMapIndex(key, val)
625 continue
626 }
627
628 // Check that it's not already set if it's not a repeated field.
629 if !props.Repeated && fieldSet[name] {
630 return p.errorf("non-repeated field %q was repeated", name)
631 }
632
633 if err := p.checkForColon(props, dst.Type()); err != nil {
634 return err
635 }
636
637 // Parse into the field.
638 fieldSet[name] = true
639 if err := p.readAny(dst, props); err != nil {
640 if _, ok := err.(*RequiredNotSetError); !ok {
641 return err
642 }
643 reqFieldErr = err
644 } else if props.Required {
645 reqCount--
Rob Pikeaaa3a622010-03-20 22:32:34 -0700646 }
David Symondsbe02a4a2012-12-06 15:20:41 +1100647
David Symonds056d5ce2015-05-12 19:27:00 +1000648 if err := p.consumeOptionalSeparator(); err != nil {
649 return err
David Symondsbe02a4a2012-12-06 15:20:41 +1100650 }
David Symonds056d5ce2015-05-12 19:27:00 +1000651
Rob Pikeaaa3a622010-03-20 22:32:34 -0700652 }
653
654 if reqCount > 0 {
655 return p.missingRequiredFieldError(sv)
656 }
David Symonds2a1c6b92014-10-12 16:42:41 +1100657 return reqFieldErr
Rob Pikeaaa3a622010-03-20 22:32:34 -0700658}
659
David Symonds056d5ce2015-05-12 19:27:00 +1000660// consumeOptionalSeparator consumes an optional semicolon or comma.
661// It is used in readStruct to provide backward compatibility.
662func (p *textParser) consumeOptionalSeparator() error {
663 tok := p.next()
664 if tok.err != nil {
665 return tok.err
666 }
667 if tok.value != ";" && tok.value != "," {
668 p.back()
669 }
670 return nil
671}
672
David Symonds2a1c6b92014-10-12 16:42:41 +1100673func (p *textParser) readAny(v reflect.Value, props *Properties) error {
Rob Pikeaaa3a622010-03-20 22:32:34 -0700674 tok := p.next()
675 if tok.err != nil {
676 return tok.err
677 }
678 if tok.value == "" {
Rob Piked6420b82011-04-13 16:37:04 -0700679 return p.errorf("unexpected EOF")
Rob Pikeaaa3a622010-03-20 22:32:34 -0700680 }
681
Rob Pike97e934d2011-04-11 12:52:49 -0700682 switch fv := v; fv.Kind() {
683 case reflect.Slice:
684 at := v.Type()
Rob Pikeab5b8022010-06-21 17:47:58 -0700685 if at.Elem().Kind() == reflect.Uint8 {
Rob Pikeaaa3a622010-03-20 22:32:34 -0700686 // Special case for []byte
David Symonds162d0032012-06-28 09:44:46 -0700687 if tok.value[0] != '"' && tok.value[0] != '\'' {
Rob Pikeaaa3a622010-03-20 22:32:34 -0700688 // Deliberately written out here, as the error after
689 // this switch statement would write "invalid []byte: ...",
690 // which is not as user-friendly.
Rob Piked6420b82011-04-13 16:37:04 -0700691 return p.errorf("invalid string: %v", tok.value)
Rob Pikeaaa3a622010-03-20 22:32:34 -0700692 }
693 bytes := []byte(tok.unquoted)
Nigel Tao4ede8452011-04-28 11:27:25 +1000694 fv.Set(reflect.ValueOf(bytes))
Rob Pikeaaa3a622010-03-20 22:32:34 -0700695 return nil
696 }
697 // Repeated field. May already exist.
David Symonds79eae332010-10-16 11:33:20 +1100698 flen := fv.Len()
699 if flen == fv.Cap() {
700 nav := reflect.MakeSlice(at, flen, 2*flen+1)
Rob Pike48fd4a42010-12-14 23:40:41 -0800701 reflect.Copy(nav, fv)
David Symonds79eae332010-10-16 11:33:20 +1100702 fv.Set(nav)
703 }
704 fv.SetLen(flen + 1)
Rob Pikeaaa3a622010-03-20 22:32:34 -0700705
706 // Read one.
707 p.back()
David Symondsef8f0e82011-10-13 12:57:34 +1100708 return p.readAny(fv.Index(flen), props)
Rob Pike97e934d2011-04-11 12:52:49 -0700709 case reflect.Bool:
Rob Pikeaaa3a622010-03-20 22:32:34 -0700710 // Either "true", "false", 1 or 0.
711 switch tok.value {
712 case "true", "1":
Rob Pike97e934d2011-04-11 12:52:49 -0700713 fv.SetBool(true)
Rob Pikeaaa3a622010-03-20 22:32:34 -0700714 return nil
715 case "false", "0":
Rob Pike97e934d2011-04-11 12:52:49 -0700716 fv.SetBool(false)
Rob Pikeaaa3a622010-03-20 22:32:34 -0700717 return nil
718 }
Rob Pike97e934d2011-04-11 12:52:49 -0700719 case reflect.Float32, reflect.Float64:
David Symonds6bd081e2012-06-28 10:46:25 -0700720 v := tok.value
David Symondsbe02a4a2012-12-06 15:20:41 +1100721 // Ignore 'f' for compatibility with output generated by C++, but don't
722 // remove 'f' when the value is "-inf" or "inf".
723 if strings.HasSuffix(v, "f") && tok.value != "-inf" && tok.value != "inf" {
David Symonds6bd081e2012-06-28 10:46:25 -0700724 v = v[:len(v)-1]
725 }
726 if f, err := strconv.ParseFloat(v, fv.Type().Bits()); err == nil {
Rob Pike97e934d2011-04-11 12:52:49 -0700727 fv.SetFloat(f)
Rob Pikeaaa3a622010-03-20 22:32:34 -0700728 return nil
729 }
Rob Pike19b2dbb2011-04-11 16:49:15 -0700730 case reflect.Int32:
David Symonds32612dd2012-06-15 07:59:05 -0700731 if x, err := strconv.ParseInt(tok.value, 0, 32); err == nil {
Rob Pike19b2dbb2011-04-11 16:49:15 -0700732 fv.SetInt(x)
Rob Pikeaaa3a622010-03-20 22:32:34 -0700733 return nil
Rob Pike19b2dbb2011-04-11 16:49:15 -0700734 }
David Symonds8bb628d2014-07-22 13:49:35 +1000735
Rob Pike19b2dbb2011-04-11 16:49:15 -0700736 if len(props.Enum) == 0 {
737 break
738 }
739 m, ok := enumValueMaps[props.Enum]
740 if !ok {
741 break
742 }
743 x, ok := m[tok.value]
744 if !ok {
745 break
746 }
747 fv.SetInt(int64(x))
748 return nil
749 case reflect.Int64:
David Symonds32612dd2012-06-15 07:59:05 -0700750 if x, err := strconv.ParseInt(tok.value, 0, 64); err == nil {
Rob Pike19b2dbb2011-04-11 16:49:15 -0700751 fv.SetInt(x)
752 return nil
Rob Pikeaaa3a622010-03-20 22:32:34 -0700753 }
David Symonds8bb628d2014-07-22 13:49:35 +1000754
Rob Pike97e934d2011-04-11 12:52:49 -0700755 case reflect.Ptr:
Rob Pikeaaa3a622010-03-20 22:32:34 -0700756 // A basic field (indirected through pointer), or a repeated message/group
757 p.back()
Rob Pikeccd260c2011-04-18 13:13:04 -0700758 fv.Set(reflect.New(fv.Type().Elem()))
Rob Pikeaaa3a622010-03-20 22:32:34 -0700759 return p.readAny(fv.Elem(), props)
Rob Pike97e934d2011-04-11 12:52:49 -0700760 case reflect.String:
David Symonds162d0032012-06-28 09:44:46 -0700761 if tok.value[0] == '"' || tok.value[0] == '\'' {
Rob Pike97e934d2011-04-11 12:52:49 -0700762 fv.SetString(tok.unquoted)
Rob Pikeaaa3a622010-03-20 22:32:34 -0700763 return nil
764 }
Rob Pike97e934d2011-04-11 12:52:49 -0700765 case reflect.Struct:
Rob Pikeaaa3a622010-03-20 22:32:34 -0700766 var terminator string
767 switch tok.value {
768 case "{":
769 terminator = "}"
770 case "<":
771 terminator = ">"
772 default:
Rob Piked6420b82011-04-13 16:37:04 -0700773 return p.errorf("expected '{' or '<', found %q", tok.value)
Rob Pikeaaa3a622010-03-20 22:32:34 -0700774 }
David Symonds81177532014-11-20 14:33:40 +1100775 // TODO: Handle nested messages which implement encoding.TextUnmarshaler.
Rob Pikeaaa3a622010-03-20 22:32:34 -0700776 return p.readStruct(fv, terminator)
Rob Pike19b2dbb2011-04-11 16:49:15 -0700777 case reflect.Uint32:
David Symonds32612dd2012-06-15 07:59:05 -0700778 if x, err := strconv.ParseUint(tok.value, 0, 32); err == nil {
Rob Pike19b2dbb2011-04-11 16:49:15 -0700779 fv.SetUint(uint64(x))
780 return nil
781 }
782 case reflect.Uint64:
David Symonds32612dd2012-06-15 07:59:05 -0700783 if x, err := strconv.ParseUint(tok.value, 0, 64); err == nil {
Rob Pike19b2dbb2011-04-11 16:49:15 -0700784 fv.SetUint(x)
785 return nil
Rob Pikeaaa3a622010-03-20 22:32:34 -0700786 }
787 }
Rob Piked6420b82011-04-13 16:37:04 -0700788 return p.errorf("invalid %v: %v", v.Type(), tok.value)
Rob Pikeaaa3a622010-03-20 22:32:34 -0700789}
790
David Symonds501f7db2013-08-05 13:53:28 +1000791// UnmarshalText reads a protocol buffer in Text format. UnmarshalText resets pb
792// before starting to unmarshal, so any existing data in pb is always removed.
David Symonds2a1c6b92014-10-12 16:42:41 +1100793// If a required field is not set and no other error occurs,
794// UnmarshalText returns *RequiredNotSetError.
David Symonds9f60f432012-06-14 09:45:25 +1000795func UnmarshalText(s string, pb Message) error {
David Symonds81177532014-11-20 14:33:40 +1100796 if um, ok := pb.(encoding.TextUnmarshaler); ok {
David Symonds267e8052014-02-19 14:50:51 +1100797 err := um.UnmarshalText([]byte(s))
798 return err
799 }
David Symonds501f7db2013-08-05 13:53:28 +1000800 pb.Reset()
Nigel Tao4ede8452011-04-28 11:27:25 +1000801 v := reflect.ValueOf(pb)
David Symondsa9cda212011-04-15 01:23:17 -0700802 if pe := newTextParser(s).readStruct(v.Elem(), ""); pe != nil {
Rob Pikeaaa3a622010-03-20 22:32:34 -0700803 return pe
804 }
805 return nil
806}