Copyright 2018 The Go Authors. All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.

package prototext

import (
	
	
	

	
	
	
	
	
	
	
	
	
	pref 
	
)
Unmarshal reads the given []byte into the given proto.Message.
func ( []byte,  proto.Message) error {
	return UnmarshalOptions{}.Unmarshal(, )
}
UnmarshalOptions is a configurable textproto format unmarshaler.
AllowPartial accepts input for messages that will result in missing required fields. If AllowPartial is false (the default), Unmarshal will return error if there are any missing required fields.
DiscardUnknown specifies whether to ignore unknown fields when parsing. An unknown field is any field whose field name or field number does not resolve to any known or extension field in the message. By default, unmarshal rejects unknown fields as an error.
Resolver is used for looking up types when unmarshaling google.protobuf.Any messages or extension fields. If nil, this defaults to using protoregistry.GlobalTypes.
Unmarshal reads the given []byte and populates the given proto.Message using options in UnmarshalOptions object.
func ( UnmarshalOptions) ( []byte,  proto.Message) error {
	return .unmarshal(, )
}
unmarshal is a centralized function that all unmarshal operations go through. For profiling purposes, avoid changing the name of this function or introducing other code paths for unmarshal that do not go through this.
func ( UnmarshalOptions) ( []byte,  proto.Message) error {
	proto.Reset()

	if .Resolver == nil {
		.Resolver = protoregistry.GlobalTypes
	}

	 := decoder{text.NewDecoder(), }
	if  := .unmarshalMessage(.ProtoReflect(), false);  != nil {
		return 
	}
	if .AllowPartial {
		return nil
	}
	return proto.CheckInitialized()
}

type decoder struct {
	*text.Decoder
	opts UnmarshalOptions
}
newError returns an error object with position info.
func ( decoder) ( int,  string,  ...interface{}) error {
	,  := .Position()
	 := fmt.Sprintf("(line %d:%d): ", , )
	return errors.New(+, ...)
}
unexpectedTokenError returns a syntax error for the given unexpected token.
func ( decoder) ( text.Token) error {
	return .syntaxError(.Pos(), "unexpected token: %s", .RawString())
}
syntaxError returns a syntax error for given position.
func ( decoder) ( int,  string,  ...interface{}) error {
	,  := .Position()
	 := fmt.Sprintf("syntax error (line %d:%d): ", , )
	return errors.New(+, ...)
}
unmarshalMessage unmarshals into the given protoreflect.Message.
func ( decoder) ( pref.Message,  bool) error {
	 := .Descriptor()
	if !flags.ProtoLegacy && messageset.IsMessageSet() {
		return errors.New("no support for proto1 MessageSets")
	}

	if .FullName() == genid.Any_message_fullname {
		return .unmarshalAny(, )
	}

	if  {
		,  := .Read()
		if  != nil {
			return 
		}

		if .Kind() != text.MessageOpen {
			return .unexpectedTokenError()
		}
	}

	var  set.Ints
	var  set.Ints
	 := .Fields()

Read field name.
		,  := .Read()
		if  != nil {
			return 
		}
		switch  := .Kind();  {
Continue below.
		case text.EOF:
			if  {
				return text.ErrUnexpectedEOF
			}
			return nil
		default:
			if  &&  == text.MessageClose {
				return nil
			}
			return .unexpectedTokenError()
		}
Resolve the field descriptor.
		var  pref.Name
		var  pref.FieldDescriptor
		var  pref.ExtensionType
		var  error
		var  bool

		switch .NameKind() {
		case text.IdentName:
			 = pref.Name(.IdentName())
			 = .ByName()
The proto name of a group field is in all lowercase, while the textproto field name is the group message name.
				 := .ByName(pref.Name(strings.ToLower(string())))
				if  != nil && .Kind() == pref.GroupKind && .Message().Name() ==  {
					 = 
				}
			} else if .Kind() == pref.GroupKind && .Message().Name() !=  {
				 = nil // reset since field name is actually the message name
			}

Handle extensions only. This code path is not for Any.
			,  = .findExtension(pref.FullName(.TypeName()))

		case text.FieldNumber:
			 = true
			 := pref.FieldNumber(.FieldNumber())
			if !.IsValid() {
				return .newError(.Pos(), "invalid field number: %d", )
			}
			 = .ByNumber()
			if  == nil {
				,  = .opts.Resolver.FindExtensionByNumber(.FullName(), )
			}
		}

		if  != nil {
			 = .TypeDescriptor()
			if !.ExtensionRanges().Has(.Number()) || .ContainingMessage().FullName() != .FullName() {
				return .newError(.Pos(), "message %v cannot be extended by %v", .FullName(), .FullName())
			}
		} else if  != nil &&  != protoregistry.NotFound {
			return .newError(.Pos(), "unable to resolve [%s]: %v", .RawString(), )
		}
		if flags.ProtoLegacy {
			if  != nil && .IsWeak() && .Message().IsPlaceholder() {
				 = nil // reset since the weak reference is not linked in
			}
		}
Handle unknown fields.
		if  == nil {
			if .opts.DiscardUnknown || .ReservedNames().Has() {
				.skipValue()
				continue
			}
			return .newError(.Pos(), "unknown field: %v", .RawString())
		}
Handle fields identified by field number.
TODO: Add an option to permit parsing field numbers. This requires careful thought as the MarshalOptions.EmitUnknown option allows formatting unknown fields as the field number and the best-effort textual representation of the field value. In that case, it may not be possible to unmarshal the value from a parser that does have information about the unknown field.
			return .newError(.Pos(), "cannot specify field by number: %v", .RawString())
		}

		switch {
		case .IsList():
			 := .Kind()
			if  != pref.MessageKind &&  != pref.GroupKind && !.HasSeparator() {
				return .syntaxError(.Pos(), "missing field separator :")
			}

			 := .Mutable().List()
			if  := .unmarshalList(, );  != nil {
				return 
			}

		case .IsMap():
			 := .Mutable().Map()
			if  := .unmarshalMap(, );  != nil {
				return 
			}

		default:
			 := .Kind()
			if  != pref.MessageKind &&  != pref.GroupKind && !.HasSeparator() {
				return .syntaxError(.Pos(), "missing field separator :")
			}
If field is a oneof, check if it has already been set.
			if  := .ContainingOneof();  != nil {
				 := uint64(.Index())
				if .Has() {
					return .newError(.Pos(), "error parsing %q, oneof %v is already set", .RawString(), .FullName())
				}
				.Set()
			}

			 := uint64(.Number())
			if .Has() {
				return .newError(.Pos(), "non-repeated field %q is repeated", .RawString())
			}

			if  := .unmarshalSingular(, );  != nil {
				return 
			}
			.Set()
		}
	}

	return nil
}
findExtension returns protoreflect.ExtensionType from the Resolver if found.
func ( decoder) ( pref.FullName) (pref.ExtensionType, error) {
	,  := .opts.Resolver.FindExtensionByName()
	if  == nil {
		return , nil
	}
	return messageset.FindMessageSetExtension(.opts.Resolver, )
}
unmarshalSingular unmarshals a non-repeated field value specified by the given FieldDescriptor.
func ( decoder) ( pref.FieldDescriptor,  pref.Message) error {
	var  pref.Value
	var  error
	switch .Kind() {
	case pref.MessageKind, pref.GroupKind:
		 = .NewField()
		 = .unmarshalMessage(.Message(), true)
	default:
		,  = .unmarshalScalar()
	}
	if  == nil {
		.Set(, )
	}
	return 
}
unmarshalScalar unmarshals a scalar/enum protoreflect.Value specified by the given FieldDescriptor.
func ( decoder) ( pref.FieldDescriptor) (pref.Value, error) {
	,  := .Read()
	if  != nil {
		return pref.Value{}, 
	}

	if .Kind() != text.Scalar {
		return pref.Value{}, .unexpectedTokenError()
	}

	 := .Kind()
	switch  {
	case pref.BoolKind:
		if ,  := .Bool();  {
			return pref.ValueOfBool(), nil
		}

	case pref.Int32Kind, pref.Sint32Kind, pref.Sfixed32Kind:
		if ,  := .Int32();  {
			return pref.ValueOfInt32(), nil
		}

	case pref.Int64Kind, pref.Sint64Kind, pref.Sfixed64Kind:
		if ,  := .Int64();  {
			return pref.ValueOfInt64(), nil
		}

	case pref.Uint32Kind, pref.Fixed32Kind:
		if ,  := .Uint32();  {
			return pref.ValueOfUint32(), nil
		}

	case pref.Uint64Kind, pref.Fixed64Kind:
		if ,  := .Uint64();  {
			return pref.ValueOfUint64(), nil
		}

	case pref.FloatKind:
		if ,  := .Float32();  {
			return pref.ValueOfFloat32(), nil
		}

	case pref.DoubleKind:
		if ,  := .Float64();  {
			return pref.ValueOfFloat64(), nil
		}

	case pref.StringKind:
		if ,  := .String();  {
			if strs.EnforceUTF8() && !utf8.ValidString() {
				return pref.Value{}, .newError(.Pos(), "contains invalid UTF-8")
			}
			return pref.ValueOfString(), nil
		}

	case pref.BytesKind:
		if ,  := .String();  {
			return pref.ValueOfBytes([]byte()), nil
		}

	case pref.EnumKind:
Lookup EnumNumber based on name.
			if  := .Enum().Values().ByName(pref.Name());  != nil {
				return pref.ValueOfEnum(.Number()), nil
			}
		}
		if ,  := .Int32();  {
			return pref.ValueOfEnum(pref.EnumNumber()), nil
		}

	default:
		panic(fmt.Sprintf("invalid scalar kind %v", ))
	}

	return pref.Value{}, .newError(.Pos(), "invalid value for %v type: %v", , .RawString())
}
unmarshalList unmarshals into given protoreflect.List. A list value can either be in [] syntax or simply just a single scalar/message value.
func ( decoder) ( pref.FieldDescriptor,  pref.List) error {
	,  := .Peek()
	if  != nil {
		return 
	}

	switch .Kind() {
	case pref.MessageKind, pref.GroupKind:
		switch .Kind() {
		case text.ListOpen:
			.Read()
			for {
				,  := .Peek()
				if  != nil {
					return 
				}

				switch .Kind() {
				case text.ListClose:
					.Read()
					return nil
				case text.MessageOpen:
					 := .NewElement()
					if  := .unmarshalMessage(.Message(), true);  != nil {
						return 
					}
					.Append()
				default:
					return .unexpectedTokenError()
				}
			}

		case text.MessageOpen:
			 := .NewElement()
			if  := .unmarshalMessage(.Message(), true);  != nil {
				return 
			}
			.Append()
			return nil
		}

	default:
		switch .Kind() {
		case text.ListOpen:
			.Read()
			for {
				,  := .Peek()
				if  != nil {
					return 
				}

				switch .Kind() {
				case text.ListClose:
					.Read()
					return nil
				case text.Scalar:
					,  := .unmarshalScalar()
					if  != nil {
						return 
					}
					.Append()
				default:
					return .unexpectedTokenError()
				}
			}

		case text.Scalar:
			,  := .unmarshalScalar()
			if  != nil {
				return 
			}
			.Append()
			return nil
		}
	}

	return .unexpectedTokenError()
}
unmarshalMap unmarshals into given protoreflect.Map. A map value is a textproto message containing {key: <kvalue>, value: <mvalue>}.
Determine ahead whether map entry is a scalar type or a message type in order to call the appropriate unmarshalMapValue func inside unmarshalMapEntry.
	var  func() (pref.Value, error)
	switch .MapValue().Kind() {
	case pref.MessageKind, pref.GroupKind:
		 = func() (pref.Value, error) {
			 := .NewValue()
			if  := .unmarshalMessage(.Message(), true);  != nil {
				return pref.Value{}, 
			}
			return , nil
		}
	default:
		 = func() (pref.Value, error) {
			return .unmarshalScalar(.MapValue())
		}
	}

	,  := .Read()
	if  != nil {
		return 
	}
	switch .Kind() {
	case text.MessageOpen:
		return .unmarshalMapEntry(, , )

	case text.ListOpen:
		for {
			,  := .Read()
			if  != nil {
				return 
			}
			switch .Kind() {
			case text.ListClose:
				return nil
			case text.MessageOpen:
				if  := .unmarshalMapEntry(, , );  != nil {
					return 
				}
			default:
				return .unexpectedTokenError()
			}
		}

	default:
		return .unexpectedTokenError()
	}
}
unmarshalMap unmarshals into given protoreflect.Map. A map value is a textproto message containing {key: <kvalue>, value: <mvalue>}.
func ( decoder) ( pref.FieldDescriptor,  pref.Map,  func() (pref.Value, error)) error {
	var  pref.MapKey
	var  pref.Value
:
Read field name.
		,  := .Read()
		if  != nil {
			return 
		}
		switch .Kind() {
		case text.Name:
			if .NameKind() != text.IdentName {
				if !.opts.DiscardUnknown {
					return .newError(.Pos(), "unknown map entry field %q", .RawString())
				}
				.skipValue()
				continue 
Continue below.
		case text.MessageClose:
			break 
		default:
			return .unexpectedTokenError()
		}

		switch  := pref.Name(.IdentName());  {
		case genid.MapEntry_Key_field_name:
			if !.HasSeparator() {
				return .syntaxError(.Pos(), "missing field separator :")
			}
			if .IsValid() {
				return .newError(.Pos(), "map entry %q cannot be repeated", )
			}
			,  := .unmarshalScalar(.MapKey())
			if  != nil {
				return 
			}
			 = .MapKey()

		case genid.MapEntry_Value_field_name:
			if  := .MapValue().Kind(); ( != pref.MessageKind) && ( != pref.GroupKind) {
				if !.HasSeparator() {
					return .syntaxError(.Pos(), "missing field separator :")
				}
			}
			if .IsValid() {
				return .newError(.Pos(), "map entry %q cannot be repeated", )
			}
			,  = ()
			if  != nil {
				return 
			}

		default:
			if !.opts.DiscardUnknown {
				return .newError(.Pos(), "unknown map entry field %q", )
			}
			.skipValue()
		}
	}

	if !.IsValid() {
		 = .MapKey().Default().MapKey()
	}
	if !.IsValid() {
		switch .MapValue().Kind() {
If value field is not set for message/group types, construct an empty one as default.
			 = .NewValue()
		default:
			 = .MapValue().Default()
		}
	}
	.Set(, )
	return nil
}
unmarshalAny unmarshals an Any textproto. It can either be in expanded form or non-expanded form.
func ( decoder) ( pref.Message,  bool) error {
	var  string
	var  []byte
	var  bool
	var  bool
	var  bool

	if  {
		,  := .Read()
		if  != nil {
			return 
		}

		if .Kind() != text.MessageOpen {
			return .unexpectedTokenError()
		}
	}

:
Read field name. Can only have 3 possible field names, i.e. type_url, value and type URL name inside [].
		,  := .Read()
		if  != nil {
			return 
		}
		if  := .Kind();  != text.Name {
			if  {
				if  == text.MessageClose {
					break 
				}
			} else if  == text.EOF {
				break 
			}
			return .unexpectedTokenError()
		}

		switch .NameKind() {
Both type_url and value fields require field separator :.
			if !.HasSeparator() {
				return .syntaxError(.Pos(), "missing field separator :")
			}

			switch  := pref.Name(.IdentName());  {
			case genid.Any_TypeUrl_field_name:
				if  {
					return .newError(.Pos(), "duplicate %v field", genid.Any_TypeUrl_field_fullname)
				}
				if  {
					return .newError(.Pos(), "conflict with [%s] field", )
				}
				,  := .Read()
				if  != nil {
					return 
				}
				var  bool
				,  = .String()
				if ! {
					return .newError(.Pos(), "invalid %v field value: %v", genid.Any_TypeUrl_field_fullname, .RawString())
				}
				 = true

			case genid.Any_Value_field_name:
				if  {
					return .newError(.Pos(), "duplicate %v field", genid.Any_Value_field_fullname)
				}
				if  {
					return .newError(.Pos(), "conflict with [%s] field", )
				}
				,  := .Read()
				if  != nil {
					return 
				}
				,  := .String()
				if ! {
					return .newError(.Pos(), "invalid %v field value: %v", genid.Any_Value_field_fullname, .RawString())
				}
				 = []byte()
				 = true

			default:
				if !.opts.DiscardUnknown {
					return .newError(.Pos(), "invalid field name %q in %v message", .RawString(), genid.Any_message_fullname)
				}
			}

		case text.TypeName:
			if  {
				return .newError(.Pos(), "cannot have more than one type")
			}
			if  {
				return .newError(.Pos(), "conflict with type_url field")
			}
			 = .TypeName()
			var  error
			,  = .unmarshalExpandedAny(, .Pos())
			if  != nil {
				return 
			}
			 = true

		default:
			if !.opts.DiscardUnknown {
				return .newError(.Pos(), "invalid field name %q in %v message", .RawString(), genid.Any_message_fullname)
			}
		}
	}

	 := .Descriptor().Fields()
	if len() > 0 {
		.Set(.ByNumber(genid.Any_TypeUrl_field_number), pref.ValueOfString())
	}
	if len() > 0 {
		.Set(.ByNumber(genid.Any_Value_field_number), pref.ValueOfBytes())
	}
	return nil
}

func ( decoder) ( string,  int) ([]byte, error) {
	,  := .opts.Resolver.FindMessageByURL()
	if  != nil {
		return nil, .newError(, "unable to resolve message [%v]: %v", , )
Create new message for the embedded message type and unmarshal the value field into it.
	 := .New()
	if  := .unmarshalMessage(, true);  != nil {
		return nil, 
Serialize the embedded message and return the resulting bytes.
	,  := proto.MarshalOptions{
		AllowPartial:  true, // Never check required fields inside an Any.
		Deterministic: true,
	}.Marshal(.Interface())
	if  != nil {
		return nil, .newError(, "error in marshaling message into Any.value: %v", )
	}
	return , nil
}
skipValue makes the decoder parse a field value in order to advance the read to the next field. It relies on Read returning an error if the types are not in valid sequence.
func ( decoder) () error {
	,  := .Read()
	if  != nil {
		return 
Only need to continue reading for messages and lists.
	switch .Kind() {
	case text.MessageOpen:
		return .skipMessageValue()

	case text.ListOpen:
		for {
			,  := .Read()
			if  != nil {
				return 
			}
			switch .Kind() {
			case text.ListClose:
				return nil
			case text.MessageOpen:
				return .skipMessageValue()
Skip items. This will not validate whether skipped values are of the same type or not, same behavior as C++ TextFormat::Parser::AllowUnknownField(true) version 3.8.0.
				if  := .();  != nil {
					return 
				}
			}
		}
	}
	return nil
}
skipMessageValue makes the decoder parse and skip over all fields in a message. It assumes that the previous read type is MessageOpen.
func ( decoder) () error {
	for {
		,  := .Read()
		if  != nil {
			return 
		}
		switch .Kind() {
		case text.MessageClose:
			return nil
		case text.Name:
			if  := .skipValue();  != nil {
				return 
			}
		}
	}