1 // Go support for Protocol Buffers - Google's data interchange format
3 // Copyright 2010 The Go Authors. All rights reserved.
4 // https://github.com/golang/protobuf
6 // Redistribution and use in source and binary forms, with or without
7 // modification, are permitted provided that the following conditions are
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
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.
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.
34 // Functions for parsing the Text protocol buffer format.
35 // TODO: message sets.
47 // Error string emitted when deserializing Any and fields are already set
48 const anyRepeatedlyUnpacked = "Any message unpacked multiple times, or %q already set"
50 type ParseError struct {
52 Line int // 1-based line number
53 Offset int // 0-based byte offset from start of input
56 func (p *ParseError) Error() string {
58 // show offset only for first line
59 return fmt.Sprintf("line 1.%d: %v", p.Offset, p.Message)
61 return fmt.Sprintf("line %d: %v", p.Line, p.Message)
67 line int // line number
68 offset int // byte number from start of input, not start of line
69 unquoted string // the unquoted version of value, if it was a quoted string
72 func (t *token) String() string {
74 return fmt.Sprintf("%q (line=%d, offset=%d)", t.value, t.line, t.offset)
76 return fmt.Sprintf("parse error: %v", t.err)
79 type textParser struct {
80 s string // remaining input
81 done bool // whether the parsing is finished (success or error)
82 backed bool // whether back() was called
87 func newTextParser(s string) *textParser {
95 func (p *textParser) errorf(format string, a ...interface{}) *ParseError {
96 pe := &ParseError{fmt.Sprintf(format, a...), p.cur.line, p.cur.offset}
102 // Numbers and identifiers are matched by [-+._A-Za-z0-9]
103 func isIdentOrNumberChar(c byte) bool {
105 case 'A' <= c && c <= 'Z', 'a' <= c && c <= 'z':
107 case '0' <= c && c <= '9':
111 case '-', '+', '.', '_':
117 func isWhitespace(c byte) bool {
119 case ' ', '\t', '\n', '\r':
125 func isQuote(c byte) bool {
133 func (p *textParser) skipWhitespace() {
135 for i < len(p.s) && (isWhitespace(p.s[i]) || p.s[i] == '#') {
137 // comment; skip to end of line or input
138 for i < len(p.s) && p.s[i] != '\n' {
151 p.s = p.s[i:len(p.s)]
157 func (p *textParser) advance() {
164 // Start of non-whitespace
166 p.cur.offset, p.cur.line = p.offset, p.line
169 case '<', '>', '{', '}', ':', '[', ']', ';', ',', '/':
171 p.cur.value, p.s = p.s[0:1], p.s[1:len(p.s)]
175 for i < len(p.s) && p.s[i] != p.s[0] && p.s[i] != '\n' {
176 if p.s[i] == '\\' && i+1 < len(p.s) {
182 if i >= len(p.s) || p.s[i] != p.s[0] {
183 p.errorf("unmatched quote")
186 unq, err := unquoteC(p.s[1:i], rune(p.s[0]))
188 p.errorf("invalid quoted string %s: %v", p.s[0:i+1], err)
191 p.cur.value, p.s = p.s[0:i+1], p.s[i+1:len(p.s)]
195 for i < len(p.s) && isIdentOrNumberChar(p.s[i]) {
199 p.errorf("unexpected byte %#x", p.s[0])
202 p.cur.value, p.s = p.s[0:i], p.s[i:len(p.s)]
204 p.offset += len(p.cur.value)
208 errBadUTF8 = errors.New("proto: bad UTF-8")
211 func unquoteC(s string, quote rune) (string, error) {
212 // This is based on C++'s tokenizer.cc.
213 // Despite its name, this is *not* parsing C syntax.
214 // For instance, "\0" is an invalid quoted string.
216 // Avoid allocation in trivial cases.
218 for _, r := range s {
219 if r == '\\' || r == quote {
228 buf := make([]byte, 0, 3*len(s)/2)
230 r, n := utf8.DecodeRuneInString(s)
231 if r == utf8.RuneError && n == 1 {
232 return "", errBadUTF8
236 if r < utf8.RuneSelf {
237 buf = append(buf, byte(r))
239 buf = append(buf, string(r)...)
244 ch, tail, err := unescape(s)
248 buf = append(buf, ch...)
251 return string(buf), nil
254 func unescape(s string) (ch string, tail string, err error) {
255 r, n := utf8.DecodeRuneInString(s)
256 if r == utf8.RuneError && n == 1 {
257 return "", "", errBadUTF8
276 return "?", s, nil // trigraph workaround
277 case '\'', '"', '\\':
278 return string(r), s, nil
279 case '0', '1', '2', '3', '4', '5', '6', '7':
281 return "", "", fmt.Errorf(`\%c requires 2 following digits`, r)
283 ss := string(r) + s[:2]
285 i, err := strconv.ParseUint(ss, 8, 8)
287 return "", "", fmt.Errorf(`\%s contains non-octal digits`, ss)
289 return string([]byte{byte(i)}), s, nil
290 case 'x', 'X', 'u', 'U':
301 return "", "", fmt.Errorf(`\%c requires %d following digits`, r, n)
305 i, err := strconv.ParseUint(ss, 16, 64)
307 return "", "", fmt.Errorf(`\%c%s contains non-hexadecimal digits`, r, ss)
309 if r == 'x' || r == 'X' {
310 return string([]byte{byte(i)}), s, nil
312 if i > utf8.MaxRune {
313 return "", "", fmt.Errorf(`\%c%s is not a valid Unicode code point`, r, ss)
315 return string(i), s, nil
317 return "", "", fmt.Errorf(`unknown escape \%c`, r)
320 // Back off the parser by one token. Can only be done between calls to next().
321 // It makes the next advance() a no-op.
322 func (p *textParser) back() { p.backed = true }
324 // Advances the parser and returns the new current token.
325 func (p *textParser) next() *token {
326 if p.backed || p.done {
333 } else if len(p.cur.value) > 0 && isQuote(p.cur.value[0]) {
334 // Look for multiple quoted strings separated by whitespace,
335 // and concatenate them.
339 if p.done || !isQuote(p.s[0]) {
343 if p.cur.err != nil {
346 cat.value += " " + p.cur.value
347 cat.unquoted += p.cur.unquoted
349 p.done = false // parser may have seen EOF, but we want to return cat
355 func (p *textParser) consumeToken(s string) error {
362 return p.errorf("expected %q, found %q", s, tok.value)
367 // Return a RequiredNotSetError indicating which required field was not set.
368 func (p *textParser) missingRequiredFieldError(sv reflect.Value) *RequiredNotSetError {
370 sprops := GetProperties(st)
371 for i := 0; i < st.NumField(); i++ {
372 if !isNil(sv.Field(i)) {
376 props := sprops.Prop[i]
378 return &RequiredNotSetError{fmt.Sprintf("%v.%v", st, props.OrigName)}
381 return &RequiredNotSetError{fmt.Sprintf("%v.<unknown field name>", st)} // should not happen
384 // Returns the index in the struct for the named field, as well as the parsed tag properties.
385 func structFieldByName(sprops *StructProperties, name string) (int, *Properties, bool) {
386 i, ok := sprops.decoderOrigNames[name]
388 return i, sprops.Prop[i], true
390 return -1, nil, false
393 // Consume a ':' from the input stream (if the next token is a colon),
394 // returning an error if a colon is needed but not present.
395 func (p *textParser) checkForColon(props *Properties, typ reflect.Type) *ParseError {
400 if tok.value != ":" {
401 // Colon is optional when the field is a group or message.
407 // A "bytes" field is either a message, a string, or a repeated field;
408 // those three become *T, *string and []T respectively, so we can check for
409 // this field being a pointer to a non-string.
410 if typ.Kind() == reflect.Ptr {
412 if typ.Elem().Kind() == reflect.String {
415 } else if typ.Kind() == reflect.Slice {
417 if typ.Elem().Kind() != reflect.Ptr {
420 } else if typ.Kind() == reflect.String {
421 // The proto3 exception is for a string field,
422 // which requires a colon.
428 return p.errorf("expected ':', found %q", tok.value)
435 func (p *textParser) readStruct(sv reflect.Value, terminator string) error {
437 sprops := GetProperties(st)
438 reqCount := sprops.reqCount
439 var reqFieldErr error
440 fieldSet := make(map[string]bool)
441 // A struct is a sequence of "name: value", terminated by one of
442 // '>' or '}', or the end of the input. A name may also be
443 // "[extension]" or "[type/url]".
445 // The whole struct can also be an expanded Any message, like:
446 // [type/url] < ... struct contents ... >
452 if tok.value == terminator {
455 if tok.value == "[" {
456 // Looks like an extension or an Any.
458 // TODO: Check whether we need to handle
459 // namespace rooted names (e.g. ".something.Foo").
460 extName, err := p.consumeExtName()
465 if s := strings.LastIndex(extName, "/"); s >= 0 {
466 // If it contains a slash, it's an Any type URL.
467 messageName := extName[s+1:]
468 mt := MessageType(messageName)
470 return p.errorf("unrecognized message %q in google.protobuf.Any", messageName)
476 // consume an optional colon
477 if tok.value == ":" {
483 var terminator string
490 return p.errorf("expected '{' or '<', found %q", tok.value)
492 v := reflect.New(mt.Elem())
493 if pe := p.readStruct(v.Elem(), terminator); pe != nil {
496 b, err := Marshal(v.Interface().(Message))
498 return p.errorf("failed to marshal message of type %q: %v", messageName, err)
500 if fieldSet["type_url"] {
501 return p.errorf(anyRepeatedlyUnpacked, "type_url")
503 if fieldSet["value"] {
504 return p.errorf(anyRepeatedlyUnpacked, "value")
506 sv.FieldByName("TypeUrl").SetString(extName)
507 sv.FieldByName("Value").SetBytes(b)
508 fieldSet["type_url"] = true
509 fieldSet["value"] = true
513 var desc *ExtensionDesc
514 // This could be faster, but it's functional.
515 // TODO: Do something smarter than a linear scan.
516 for _, d := range RegisteredExtensions(reflect.New(st).Interface().(Message)) {
517 if d.Name == extName {
523 return p.errorf("unrecognized extension %q", extName)
526 props := &Properties{}
527 props.Parse(desc.Tag)
529 typ := reflect.TypeOf(desc.ExtensionType)
530 if err := p.checkForColon(props, typ); err != nil {
534 rep := desc.repeated()
536 // Read the extension structure, and set it in
537 // the value we're constructing.
538 var ext reflect.Value
540 ext = reflect.New(typ).Elem()
542 ext = reflect.New(typ.Elem()).Elem()
544 if err := p.readAny(ext, props); err != nil {
545 if _, ok := err.(*RequiredNotSetError); !ok {
550 ep := sv.Addr().Interface().(Message)
552 SetExtension(ep, desc, ext.Interface())
554 old, err := GetExtension(ep, desc)
557 sl = reflect.ValueOf(old) // existing slice
559 sl = reflect.MakeSlice(typ, 0, 1)
561 sl = reflect.Append(sl, ext)
562 SetExtension(ep, desc, sl.Interface())
564 if err := p.consumeOptionalSeparator(); err != nil {
570 // This is a normal, non-extension field.
572 var dst reflect.Value
573 fi, props, ok := structFieldByName(sprops, name)
576 } else if oop, ok := sprops.OneofTypes[name]; ok {
579 nv := reflect.New(oop.Type.Elem())
580 dst = nv.Elem().Field(0)
581 field := sv.Field(oop.Field)
583 return p.errorf("field '%s' would overwrite already parsed oneof '%s'", name, sv.Type().Field(oop.Field).Name)
588 return p.errorf("unknown field name %q in %v", name, st)
591 if dst.Kind() == reflect.Map {
592 // Consume any colon.
593 if err := p.checkForColon(props, dst.Type()); err != nil {
597 // Construct the map if it doesn't already exist.
599 dst.Set(reflect.MakeMap(dst.Type()))
601 key := reflect.New(dst.Type().Key()).Elem()
602 val := reflect.New(dst.Type().Elem()).Elem()
604 // The map entry should be this sequence of tokens:
605 // < key : KEY value : VALUE >
606 // However, implementations may omit key or value, and technically
607 // we should support them in any order. See b/28924776 for a time
611 var terminator string
618 return p.errorf("expected '{' or '<', found %q", tok.value)
625 if tok.value == terminator {
630 if err := p.consumeToken(":"); err != nil {
633 if err := p.readAny(key, props.MapKeyProp); err != nil {
636 if err := p.consumeOptionalSeparator(); err != nil {
640 if err := p.checkForColon(props.MapValProp, dst.Type().Elem()); err != nil {
643 if err := p.readAny(val, props.MapValProp); err != nil {
646 if err := p.consumeOptionalSeparator(); err != nil {
651 return p.errorf(`expected "key", "value", or %q, found %q`, terminator, tok.value)
655 dst.SetMapIndex(key, val)
659 // Check that it's not already set if it's not a repeated field.
660 if !props.Repeated && fieldSet[name] {
661 return p.errorf("non-repeated field %q was repeated", name)
664 if err := p.checkForColon(props, dst.Type()); err != nil {
668 // Parse into the field.
669 fieldSet[name] = true
670 if err := p.readAny(dst, props); err != nil {
671 if _, ok := err.(*RequiredNotSetError); !ok {
680 if err := p.consumeOptionalSeparator(); err != nil {
687 return p.missingRequiredFieldError(sv)
692 // consumeExtName consumes extension name or expanded Any type URL and the
693 // following ']'. It returns the name or URL consumed.
694 func (p *textParser) consumeExtName() (string, error) {
700 // If extension name or type url is quoted, it's a single token.
701 if len(tok.value) > 2 && isQuote(tok.value[0]) && tok.value[len(tok.value)-1] == tok.value[0] {
702 name, err := unquoteC(tok.value[1:len(tok.value)-1], rune(tok.value[0]))
706 return name, p.consumeToken("]")
709 // Consume everything up to "]"
711 for tok.value != "]" {
712 parts = append(parts, tok.value)
715 return "", p.errorf("unrecognized type_url or extension name: %s", tok.err)
717 if p.done && tok.value != "]" {
718 return "", p.errorf("unclosed type_url or extension name")
721 return strings.Join(parts, ""), nil
724 // consumeOptionalSeparator consumes an optional semicolon or comma.
725 // It is used in readStruct to provide backward compatibility.
726 func (p *textParser) consumeOptionalSeparator() error {
731 if tok.value != ";" && tok.value != "," {
737 func (p *textParser) readAny(v reflect.Value, props *Properties) error {
743 return p.errorf("unexpected EOF")
746 switch fv := v; fv.Kind() {
749 if at.Elem().Kind() == reflect.Uint8 {
750 // Special case for []byte
751 if tok.value[0] != '"' && tok.value[0] != '\'' {
752 // Deliberately written out here, as the error after
753 // this switch statement would write "invalid []byte: ...",
754 // which is not as user-friendly.
755 return p.errorf("invalid string: %v", tok.value)
757 bytes := []byte(tok.unquoted)
758 fv.Set(reflect.ValueOf(bytes))
762 if tok.value == "[" {
763 // Repeated field with list notation, like [1,2,3].
765 fv.Set(reflect.Append(fv, reflect.New(at.Elem()).Elem()))
766 err := p.readAny(fv.Index(fv.Len()-1), props)
774 if tok.value == "]" {
777 if tok.value != "," {
778 return p.errorf("Expected ']' or ',' found %q", tok.value)
783 // One value of the repeated field.
785 fv.Set(reflect.Append(fv, reflect.New(at.Elem()).Elem()))
786 return p.readAny(fv.Index(fv.Len()-1), props)
788 // true/1/t/True or false/f/0/False.
790 case "true", "1", "t", "True":
793 case "false", "0", "f", "False":
797 case reflect.Float32, reflect.Float64:
799 // Ignore 'f' for compatibility with output generated by C++, but don't
800 // remove 'f' when the value is "-inf" or "inf".
801 if strings.HasSuffix(v, "f") && tok.value != "-inf" && tok.value != "inf" {
804 if f, err := strconv.ParseFloat(v, fv.Type().Bits()); err == nil {
809 if x, err := strconv.ParseInt(tok.value, 0, 32); err == nil {
814 if len(props.Enum) == 0 {
817 m, ok := enumValueMaps[props.Enum]
821 x, ok := m[tok.value]
828 if x, err := strconv.ParseInt(tok.value, 0, 64); err == nil {
834 // A basic field (indirected through pointer), or a repeated message/group
836 fv.Set(reflect.New(fv.Type().Elem()))
837 return p.readAny(fv.Elem(), props)
839 if tok.value[0] == '"' || tok.value[0] == '\'' {
840 fv.SetString(tok.unquoted)
844 var terminator string
851 return p.errorf("expected '{' or '<', found %q", tok.value)
853 // TODO: Handle nested messages which implement encoding.TextUnmarshaler.
854 return p.readStruct(fv, terminator)
856 if x, err := strconv.ParseUint(tok.value, 0, 32); err == nil {
857 fv.SetUint(uint64(x))
861 if x, err := strconv.ParseUint(tok.value, 0, 64); err == nil {
866 return p.errorf("invalid %v: %v", v.Type(), tok.value)
869 // UnmarshalText reads a protocol buffer in Text format. UnmarshalText resets pb
870 // before starting to unmarshal, so any existing data in pb is always removed.
871 // If a required field is not set and no other error occurs,
872 // UnmarshalText returns *RequiredNotSetError.
873 func UnmarshalText(s string, pb Message) error {
874 if um, ok := pb.(encoding.TextUnmarshaler); ok {
875 return um.UnmarshalText([]byte(s))
878 v := reflect.ValueOf(pb)
879 return newTextParser(s).readStruct(v.Elem(), "")