internal/prototype: move from reflect/prototype
The prototype package was initially used by generated reflection support,
but has now been replaced by internal/fileinit.
Eventually, this functionality should be deleted and re-written in terms
of other components in the repo.
Usages that prototype currently provides (but should be moved) are:
* Constructing standalone messages and enums, which is behavior we should
provide in reflect/protodesc. The google.protobuf.{Enum,Type} are well-known
proto messages designed for this purpose.
* Constructing placeholder files, enums, and messages.
* Consructing protoreflect.{Message,Enum,Extension}Types, which are protobuf
descriptors with associated Go type information.
Change-Id: Id7dbefff952682781b439aa555508c59b2629f9e
Reviewed-on: https://go-review.googlesource.com/c/protobuf/+/167383
Reviewed-by: Damien Neil <dneil@google.com>
diff --git a/reflect/protodesc/protodesc.go b/reflect/protodesc/protodesc.go
index e2b402b..41b4055 100644
--- a/reflect/protodesc/protodesc.go
+++ b/reflect/protodesc/protodesc.go
@@ -12,9 +12,9 @@
"github.com/golang/protobuf/v2/internal/encoding/defval"
"github.com/golang/protobuf/v2/internal/errors"
+ "github.com/golang/protobuf/v2/internal/prototype"
"github.com/golang/protobuf/v2/reflect/protoreflect"
"github.com/golang/protobuf/v2/reflect/protoregistry"
- "github.com/golang/protobuf/v2/reflect/prototype"
descriptorpb "github.com/golang/protobuf/v2/types/descriptor"
)
diff --git a/reflect/protoregistry/registry_test.go b/reflect/protoregistry/registry_test.go
index c7ddae4..ee9d742 100644
--- a/reflect/protoregistry/registry_test.go
+++ b/reflect/protoregistry/registry_test.go
@@ -14,9 +14,9 @@
"github.com/golang/protobuf/protoapi"
"github.com/golang/protobuf/v2/internal/legacy"
+ ptype "github.com/golang/protobuf/v2/internal/prototype"
pref "github.com/golang/protobuf/v2/reflect/protoreflect"
preg "github.com/golang/protobuf/v2/reflect/protoregistry"
- ptype "github.com/golang/protobuf/v2/reflect/prototype"
testpb "github.com/golang/protobuf/v2/reflect/protoregistry/testprotos"
)
diff --git a/reflect/prototype/desc_test.go b/reflect/prototype/desc_test.go
deleted file mode 100644
index a071a10..0000000
--- a/reflect/prototype/desc_test.go
+++ /dev/null
@@ -1,61 +0,0 @@
-// 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 prototype
-
-import (
- "reflect"
- "testing"
-
- pref "github.com/golang/protobuf/v2/reflect/protoreflect"
-)
-
-// TestDescriptors tests that the implementations do not declare additional
-// methods that do not exist on the interface types.
-func TestDescriptors(t *testing.T) {
- tests := []interface{}{
- []pref.FileDescriptor{placeholderFile{}, fileDesc{}},
- []pref.MessageDescriptor{placeholderMessage{}, standaloneMessage{}, messageDesc{}},
- []pref.FieldDescriptor{standaloneExtension{}, fieldDesc{}, extensionDesc{}},
- []pref.OneofDescriptor{oneofDesc{}},
- []pref.EnumDescriptor{placeholderEnum{}, standaloneEnum{}, enumDesc{}},
- []pref.EnumValueDescriptor{enumValueDesc{}},
- []pref.ServiceDescriptor{serviceDesc{}},
- []pref.MethodDescriptor{methodDesc{}},
-
- []pref.FileImports{(*fileImports)(nil)},
- []pref.MessageDescriptors{(*messages)(nil)},
- []pref.Names{(*names)(nil)},
- []pref.FieldNumbers{(*numbers)(nil)},
- []pref.FieldRanges{(*fieldRanges)(nil)},
- []pref.FieldDescriptors{(*fields)(nil), (*oneofFields)(nil)},
- []pref.OneofDescriptors{(*oneofs)(nil)},
- []pref.ExtensionDescriptors{(*extensions)(nil)},
- []pref.EnumRanges{(*enumRanges)(nil)},
- []pref.EnumDescriptors{(*enums)(nil)},
- []pref.EnumValueDescriptors{(*enumValues)(nil)},
- []pref.ServiceDescriptors{(*services)(nil)},
- []pref.MethodDescriptors{(*methods)(nil)},
- }
-
- for _, tt := range tests {
- v := reflect.ValueOf(tt) // []T where T is an interface
- ifaceType := v.Type().Elem()
- for i := 0; i < v.Len(); i++ {
- implType := v.Index(i).Elem().Type()
-
- var hasName bool
- for j := 0; j < implType.NumMethod(); j++ {
- if name := implType.Method(j).Name; name == "Format" {
- hasName = true
- } else if _, ok := ifaceType.MethodByName(name); !ok {
- t.Errorf("spurious method: %v.%v", implType, name)
- }
- }
- if !hasName {
- t.Errorf("missing method: %v.Format", implType)
- }
- }
- }
-}
diff --git a/reflect/prototype/go_type.go b/reflect/prototype/go_type.go
deleted file mode 100644
index a9fcc39..0000000
--- a/reflect/prototype/go_type.go
+++ /dev/null
@@ -1,287 +0,0 @@
-// 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 prototype
-
-import (
- "fmt"
- "reflect"
- "sync"
-
- "github.com/golang/protobuf/v2/internal/typefmt"
- "github.com/golang/protobuf/v2/internal/value"
- "github.com/golang/protobuf/v2/reflect/protoreflect"
-)
-
-// GoEnum creates a new protoreflect.EnumType by combining the provided
-// protoreflect.EnumDescriptor with the provided constructor function.
-func GoEnum(ed protoreflect.EnumDescriptor, fn func(protoreflect.EnumType, protoreflect.EnumNumber) protoreflect.Enum) protoreflect.EnumType {
- if ed.IsPlaceholder() {
- panic("enum descriptor must not be a placeholder")
- }
- return &goEnum{EnumDescriptor: ed, new: fn}
-}
-
-type goEnum struct {
- protoreflect.EnumDescriptor
- new func(protoreflect.EnumType, protoreflect.EnumNumber) protoreflect.Enum
-
- once sync.Once
- typ reflect.Type
-}
-
-func (t *goEnum) GoType() reflect.Type {
- t.New(0) // initialize t.typ
- return t.typ
-}
-func (t *goEnum) New(n protoreflect.EnumNumber) protoreflect.Enum {
- e := t.new(t, n)
- t.once.Do(func() { t.typ = reflect.TypeOf(e) })
- if t.typ != reflect.TypeOf(e) {
- panic(fmt.Sprintf("mismatching types for enum: got %T, want %v", e, t.typ))
- }
- return e
-}
-func (t *goEnum) Format(s fmt.State, r rune) {
- typefmt.FormatDesc(s, r, t)
-}
-
-// GoMessage creates a new protoreflect.MessageType by combining the provided
-// protoreflect.MessageDescriptor with the provided constructor function.
-func GoMessage(md protoreflect.MessageDescriptor, fn func(protoreflect.MessageType) protoreflect.Message) protoreflect.MessageType {
- if md.IsPlaceholder() {
- panic("message descriptor must not be a placeholder")
- }
- // NOTE: Avoid calling fn in the constructor since fn itself may depend on
- // this function returning (for cyclic message dependencies).
- return &goMessage{MessageDescriptor: md, new: fn}
-}
-
-type goMessage struct {
- protoreflect.MessageDescriptor
- new func(protoreflect.MessageType) protoreflect.Message
-
- once sync.Once
- typ reflect.Type
-}
-
-func (t *goMessage) GoType() reflect.Type {
- t.New() // initialize t.typ
- return t.typ
-}
-func (t *goMessage) New() protoreflect.Message {
- m := t.new(t)
- mi := m.Interface()
- t.once.Do(func() { t.typ = reflect.TypeOf(mi) })
- if t.typ != reflect.TypeOf(mi) {
- panic(fmt.Sprintf("mismatching types for message: got %T, want %v", mi, t.typ))
- }
- return m
-}
-func (t *goMessage) Format(s fmt.State, r rune) {
- typefmt.FormatDesc(s, r, t)
-}
-
-// GoExtension creates a new protoreflect.ExtensionType.
-//
-// An enum type must be provided for enum extension fields if
-// ExtensionDescriptor.EnumType does not implement protoreflect.EnumType,
-// in which case it replaces the original enum in ExtensionDescriptor.
-//
-// Similarly, a message type must be provided for message extension fields if
-// ExtensionDescriptor.MessageType does not implement protoreflect.MessageType,
-// in which case it replaces the original message in ExtensionDescriptor.
-//
-// The Go type is currently determined automatically.
-// The type is T for scalars and *[]T for lists (maps are not allowed).
-// The type T is determined as follows:
-//
-// +------------+-------------------------------------+
-// | Go type | Protobuf kind |
-// +------------+-------------------------------------+
-// | bool | BoolKind |
-// | int32 | Int32Kind, Sint32Kind, Sfixed32Kind |
-// | int64 | Int64Kind, Sint64Kind, Sfixed64Kind |
-// | uint32 | Uint32Kind, Fixed32Kind |
-// | uint64 | Uint64Kind, Fixed64Kind |
-// | float32 | FloatKind |
-// | float64 | DoubleKind |
-// | string | StringKind |
-// | []byte | BytesKind |
-// | E | EnumKind |
-// | M | MessageKind, GroupKind |
-// +------------+-------------------------------------+
-//
-// The type E is the concrete enum type returned by NewEnum,
-// which is often, but not required to be, a named int32 type.
-// The type M is the concrete message type returned by NewMessage,
-// which is often, but not required to be, a pointer to a named struct type.
-func GoExtension(xd protoreflect.ExtensionDescriptor, et protoreflect.EnumType, mt protoreflect.MessageType) protoreflect.ExtensionType {
- if xd.ExtendedType() == nil {
- panic("field descriptor does not extend a message")
- }
- switch xd.Kind() {
- case protoreflect.EnumKind:
- if et2, ok := xd.EnumType().(protoreflect.EnumType); ok && et == nil {
- et = et2
- }
- if et == nil {
- panic("enum type not provided for enum kind")
- }
- if mt != nil {
- panic("message type provided for enum kind")
- }
- case protoreflect.MessageKind, protoreflect.GroupKind:
- if mt2, ok := xd.MessageType().(protoreflect.MessageType); ok && mt == nil {
- mt = mt2
- }
- if et != nil {
- panic("enum type provided for message kind")
- }
- if mt == nil {
- panic("message type not provided for message kind")
- }
- default:
- if et != nil || mt != nil {
- panic(fmt.Sprintf("enum or message type provided for %v kind", xd.Kind()))
- }
- }
- return &goExtension{ExtensionDescriptor: xd, enumType: et, messageType: mt}
-}
-
-type goExtension struct {
- protoreflect.ExtensionDescriptor
- enumType protoreflect.EnumType
- messageType protoreflect.MessageType
-
- once sync.Once
- typ reflect.Type
- new func() protoreflect.Value
- valueOf func(v interface{}) protoreflect.Value
- interfaceOf func(v protoreflect.Value) interface{}
-}
-
-func (t *goExtension) EnumType() protoreflect.EnumDescriptor {
- return t.enumType
-}
-func (t *goExtension) MessageType() protoreflect.MessageDescriptor {
- return t.messageType
-}
-func (t *goExtension) GoType() reflect.Type {
- t.lazyInit()
- return t.typ
-}
-func (t *goExtension) New() protoreflect.Value {
- t.lazyInit()
- pv := t.new()
- v := t.interfaceOf(pv)
- if reflect.TypeOf(v) != t.typ {
- panic(fmt.Sprintf("invalid type: got %T, want %v", v, t.typ))
- }
- return pv
-}
-func (t *goExtension) ValueOf(v interface{}) protoreflect.Value {
- t.lazyInit()
- if reflect.TypeOf(v) != t.typ {
- panic(fmt.Sprintf("invalid type: got %T, want %v", v, t.typ))
- }
- return t.valueOf(v)
-}
-func (t *goExtension) InterfaceOf(pv protoreflect.Value) interface{} {
- t.lazyInit()
- v := t.interfaceOf(pv)
- if reflect.TypeOf(v) != t.typ {
- panic(fmt.Sprintf("invalid type: got %T, want %v", v, t.typ))
- }
- return v
-}
-func (t *goExtension) Format(s fmt.State, r rune) {
- typefmt.FormatDesc(s, r, t)
-}
-func (t *goExtension) lazyInit() {
- t.once.Do(func() {
- switch t.Cardinality() {
- case protoreflect.Optional:
- switch t.Kind() {
- case protoreflect.EnumKind:
- t.typ = t.enumType.GoType()
- t.new = func() protoreflect.Value {
- return t.Default()
- }
- t.valueOf = func(v interface{}) protoreflect.Value {
- ev := v.(protoreflect.Enum)
- return protoreflect.ValueOf(ev.Number())
- }
- t.interfaceOf = func(pv protoreflect.Value) interface{} {
- return t.enumType.New(pv.Enum())
- }
- case protoreflect.MessageKind, protoreflect.GroupKind:
- t.typ = t.messageType.GoType()
- t.new = func() protoreflect.Value {
- return protoreflect.ValueOf(t.messageType.New())
- }
- t.valueOf = func(v interface{}) protoreflect.Value {
- mv := v.(protoreflect.ProtoMessage).ProtoReflect()
- return protoreflect.ValueOf(mv)
- }
- t.interfaceOf = func(pv protoreflect.Value) interface{} {
- return pv.Message().Interface()
- }
- default:
- t.typ = goTypeForPBKind[t.Kind()]
- t.new = func() protoreflect.Value {
- return t.Default()
- }
- t.valueOf = func(v interface{}) protoreflect.Value {
- return protoreflect.ValueOf(v)
- }
- t.interfaceOf = func(pv protoreflect.Value) interface{} {
- return pv.Interface()
- }
- }
- case protoreflect.Repeated:
- var typ reflect.Type
- switch t.Kind() {
- case protoreflect.EnumKind:
- typ = t.enumType.GoType()
- case protoreflect.MessageKind, protoreflect.GroupKind:
- typ = t.messageType.GoType()
- default:
- typ = goTypeForPBKind[t.Kind()]
- }
- c := value.NewConverter(typ, t.Kind())
- t.typ = reflect.PtrTo(reflect.SliceOf(typ))
- t.new = func() protoreflect.Value {
- v := reflect.New(t.typ.Elem()).Interface()
- return protoreflect.ValueOf(value.ListOf(v, c))
- }
- t.valueOf = func(v interface{}) protoreflect.Value {
- return protoreflect.ValueOf(value.ListOf(v, c))
- }
- t.interfaceOf = func(pv protoreflect.Value) interface{} {
- return pv.List().(value.Unwrapper).ProtoUnwrap()
- }
- default:
- panic(fmt.Sprintf("invalid cardinality: %v", t.Cardinality()))
- }
- })
-}
-
-var goTypeForPBKind = map[protoreflect.Kind]reflect.Type{
- protoreflect.BoolKind: reflect.TypeOf(bool(false)),
- protoreflect.Int32Kind: reflect.TypeOf(int32(0)),
- protoreflect.Sint32Kind: reflect.TypeOf(int32(0)),
- protoreflect.Sfixed32Kind: reflect.TypeOf(int32(0)),
- protoreflect.Int64Kind: reflect.TypeOf(int64(0)),
- protoreflect.Sint64Kind: reflect.TypeOf(int64(0)),
- protoreflect.Sfixed64Kind: reflect.TypeOf(int64(0)),
- protoreflect.Uint32Kind: reflect.TypeOf(uint32(0)),
- protoreflect.Fixed32Kind: reflect.TypeOf(uint32(0)),
- protoreflect.Uint64Kind: reflect.TypeOf(uint64(0)),
- protoreflect.Fixed64Kind: reflect.TypeOf(uint64(0)),
- protoreflect.FloatKind: reflect.TypeOf(float32(0)),
- protoreflect.DoubleKind: reflect.TypeOf(float64(0)),
- protoreflect.StringKind: reflect.TypeOf(string("")),
- protoreflect.BytesKind: reflect.TypeOf([]byte(nil)),
-}
diff --git a/reflect/prototype/name_pure.go b/reflect/prototype/name_pure.go
deleted file mode 100644
index 3720729..0000000
--- a/reflect/prototype/name_pure.go
+++ /dev/null
@@ -1,19 +0,0 @@
-// 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.
-
-// +build purego appengine
-
-package prototype
-
-import pref "github.com/golang/protobuf/v2/reflect/protoreflect"
-
-func getNameBuilder() *nameBuilder { return nil }
-func putNameBuilder(*nameBuilder) {}
-
-type nameBuilder struct{}
-
-// Append is equivalent to protoreflect.FullName.Append.
-func (*nameBuilder) Append(prefix pref.FullName, name pref.Name) pref.FullName {
- return prefix.Append(name)
-}
diff --git a/reflect/prototype/name_unsafe.go b/reflect/prototype/name_unsafe.go
deleted file mode 100644
index 27b22ad..0000000
--- a/reflect/prototype/name_unsafe.go
+++ /dev/null
@@ -1,99 +0,0 @@
-// 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.
-
-// +build !purego,!appengine
-
-package prototype
-
-import (
- "strings"
- "sync"
- "unsafe"
-
- pref "github.com/golang/protobuf/v2/reflect/protoreflect"
-)
-
-var nameBuilderPool = sync.Pool{
- New: func() interface{} { return new(nameBuilder) },
-}
-
-func getNameBuilder() *nameBuilder {
- return nameBuilderPool.Get().(*nameBuilder)
-}
-func putNameBuilder(b *nameBuilder) {
- nameBuilderPool.Put(b)
-}
-
-type nameBuilder struct {
- sb stringBuilder
-}
-
-// Append is equivalent to protoreflect.FullName.Append, but is optimized for
-// large batches of operations where each name has a shared lifetime.
-func (b *nameBuilder) Append(prefix pref.FullName, name pref.Name) pref.FullName {
- const batchSize = 1 << 12
- n := len(prefix) + len(".") + len(name)
- if b.sb.Cap()-b.sb.Len() < n {
- b.sb.Reset()
- b.sb.Grow(batchSize)
- }
- if !strings.HasSuffix(b.sb.String(), string(prefix)) {
- b.sb.WriteString(string(prefix))
- }
- b.sb.WriteByte('.')
- b.sb.WriteString(string(name))
- s := b.sb.String()
- return pref.FullName(strings.TrimPrefix(s[len(s)-n:], "."))
-}
-
-// stringsBuilder is a simplified copy of the strings.Builder from Go1.12:
-// * removed the shallow copy check
-// * removed methods that we do not use (e.g. WriteRune)
-//
-// A forked version is used:
-// * to enable Go1.9 support, but strings.Builder was added in Go1.10
-// * for the Cap method, which was missing until Go1.12
-//
-// TODO: Remove this when Go1.12 is the minimally supported toolchain version.
-type stringBuilder struct {
- buf []byte
-}
-
-func (b *stringBuilder) String() string {
- return *(*string)(unsafe.Pointer(&b.buf))
-}
-func (b *stringBuilder) Len() int {
- return len(b.buf)
-}
-func (b *stringBuilder) Cap() int {
- return cap(b.buf)
-}
-func (b *stringBuilder) Reset() {
- b.buf = nil
-}
-func (b *stringBuilder) grow(n int) {
- buf := make([]byte, len(b.buf), 2*cap(b.buf)+n)
- copy(buf, b.buf)
- b.buf = buf
-}
-func (b *stringBuilder) Grow(n int) {
- if n < 0 {
- panic("stringBuilder.Grow: negative count")
- }
- if cap(b.buf)-len(b.buf) < n {
- b.grow(n)
- }
-}
-func (b *stringBuilder) Write(p []byte) (int, error) {
- b.buf = append(b.buf, p...)
- return len(p), nil
-}
-func (b *stringBuilder) WriteByte(c byte) error {
- b.buf = append(b.buf, c)
- return nil
-}
-func (b *stringBuilder) WriteString(s string) (int, error) {
- b.buf = append(b.buf, s...)
- return len(s), nil
-}
diff --git a/reflect/prototype/options.go b/reflect/prototype/options.go
deleted file mode 100644
index ec5c857..0000000
--- a/reflect/prototype/options.go
+++ /dev/null
@@ -1,52 +0,0 @@
-// 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 prototype
-
-import (
- pref "github.com/golang/protobuf/v2/reflect/protoreflect"
-)
-
-// X provides functionality internal to the protobuf module.
-//
-// WARNING: The compatibility agreement covers nothing except for functionality
-// needed to keep existing generated messages operational. The Go authors
-// are not responsible for breakages that occur due to unauthorized usages.
-var X internal
-
-type internal struct{}
-
-// optionTypes contains typed nil-pointers to each of the options types.
-// These are populated at init time by the descriptor package.
-var optionTypes struct {
- File pref.OptionsMessage
- Enum pref.OptionsMessage
- EnumValue pref.OptionsMessage
- Message pref.OptionsMessage
- Field pref.OptionsMessage
- Oneof pref.OptionsMessage
- ExtensionRange pref.OptionsMessage
- Service pref.OptionsMessage
- Method pref.OptionsMessage
-}
-
-func (internal) FileOptions() pref.OptionsMessage { return optionTypes.File }
-func (internal) EnumOptions() pref.OptionsMessage { return optionTypes.Enum }
-func (internal) EnumValueOptions() pref.OptionsMessage { return optionTypes.EnumValue }
-func (internal) MessageOptions() pref.OptionsMessage { return optionTypes.Message }
-func (internal) FieldOptions() pref.OptionsMessage { return optionTypes.Field }
-func (internal) OneofOptions() pref.OptionsMessage { return optionTypes.Oneof }
-func (internal) ExtensionRangeOptions() pref.OptionsMessage { return optionTypes.ExtensionRange }
-func (internal) ServiceOptions() pref.OptionsMessage { return optionTypes.Service }
-func (internal) MethodOptions() pref.OptionsMessage { return optionTypes.Method }
-
-func (internal) RegisterFileOptions(m pref.OptionsMessage) { optionTypes.File = m }
-func (internal) RegisterEnumOptions(m pref.OptionsMessage) { optionTypes.Enum = m }
-func (internal) RegisterEnumValueOptions(m pref.OptionsMessage) { optionTypes.EnumValue = m }
-func (internal) RegisterMessageOptions(m pref.OptionsMessage) { optionTypes.Message = m }
-func (internal) RegisterFieldOptions(m pref.OptionsMessage) { optionTypes.Field = m }
-func (internal) RegisterOneofOptions(m pref.OptionsMessage) { optionTypes.Oneof = m }
-func (internal) RegisterExtensionRangeOptions(m pref.OptionsMessage) { optionTypes.ExtensionRange = m }
-func (internal) RegisterServiceOptions(m pref.OptionsMessage) { optionTypes.Service = m }
-func (internal) RegisterMethodOptions(m pref.OptionsMessage) { optionTypes.Method = m }
diff --git a/reflect/prototype/placeholder.go b/reflect/prototype/placeholder.go
deleted file mode 100644
index 3a5ffdc..0000000
--- a/reflect/prototype/placeholder.go
+++ /dev/null
@@ -1,32 +0,0 @@
-// 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 prototype
-
-import "github.com/golang/protobuf/v2/reflect/protoreflect"
-
-// PlaceholderFile returns a placeholder protoreflect.FileType where
-// only the Path and Package accessors are valid.
-func PlaceholderFile(path string, pkg protoreflect.FullName) protoreflect.FileDescriptor {
- // TODO: Is Package needed for placeholders?
- return placeholderFile{path, placeholderName(pkg)}
-}
-
-// PlaceholderMessage returns a placeholder protoreflect.MessageType
-// where only the Name and FullName accessors are valid.
-//
-// A placeholder can be used within File literals when referencing a message
-// that is declared within that file.
-func PlaceholderMessage(name protoreflect.FullName) protoreflect.MessageDescriptor {
- return placeholderMessage{placeholderName(name)}
-}
-
-// PlaceholderEnum returns a placeholder protoreflect.EnumType
-// where only the Name and FullName accessors are valid.
-//
-// A placeholder can be used within File literals when referencing an enum
-// that is declared within that file.
-func PlaceholderEnum(name protoreflect.FullName) protoreflect.EnumDescriptor {
- return placeholderEnum{placeholderName(name)}
-}
diff --git a/reflect/prototype/placeholder_type.go b/reflect/prototype/placeholder_type.go
deleted file mode 100644
index 8930aab..0000000
--- a/reflect/prototype/placeholder_type.go
+++ /dev/null
@@ -1,85 +0,0 @@
-// 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 prototype
-
-import (
- "fmt"
-
- pragma "github.com/golang/protobuf/v2/internal/pragma"
- pfmt "github.com/golang/protobuf/v2/internal/typefmt"
- pref "github.com/golang/protobuf/v2/reflect/protoreflect"
-)
-
-var (
- emptyFiles fileImports
- emptyMessages messages
- emptyFields fields
- emptyOneofs oneofs
- emptyNames names
- emptyNumbers numbers
- emptyFieldRanges fieldRanges
- emptyEnums enums
- emptyEnumValues enumValues
- emptyEnumRanges enumRanges
- emptyExtensions extensions
- emptyServices services
-)
-
-type placeholderName pref.FullName
-
-func (t placeholderName) Parent() (pref.Descriptor, bool) { return nil, false }
-func (t placeholderName) Index() int { return 0 }
-func (t placeholderName) Syntax() pref.Syntax { return 0 }
-func (t placeholderName) Name() pref.Name { return pref.FullName(t).Name() }
-func (t placeholderName) FullName() pref.FullName { return pref.FullName(t) }
-func (t placeholderName) IsPlaceholder() bool { return true }
-func (t placeholderName) ProtoInternal(pragma.DoNotImplement) {}
-
-type placeholderFile struct {
- path string
- placeholderName
-}
-
-func (t placeholderFile) Options() pref.OptionsMessage { return optionTypes.File }
-func (t placeholderFile) Path() string { return t.path }
-func (t placeholderFile) Package() pref.FullName { return t.FullName() }
-func (t placeholderFile) Imports() pref.FileImports { return &emptyFiles }
-func (t placeholderFile) Enums() pref.EnumDescriptors { return &emptyEnums }
-func (t placeholderFile) Messages() pref.MessageDescriptors { return &emptyMessages }
-func (t placeholderFile) Extensions() pref.ExtensionDescriptors { return &emptyExtensions }
-func (t placeholderFile) Services() pref.ServiceDescriptors { return &emptyServices }
-func (t placeholderFile) DescriptorByName(pref.FullName) pref.Descriptor { return nil }
-func (t placeholderFile) Format(s fmt.State, r rune) { pfmt.FormatDesc(s, r, t) }
-func (t placeholderFile) ProtoType(pref.FileDescriptor) {}
-
-type placeholderMessage struct {
- placeholderName
-}
-
-func (t placeholderMessage) Options() pref.OptionsMessage { return optionTypes.Message }
-func (t placeholderMessage) IsMapEntry() bool { return false }
-func (t placeholderMessage) Fields() pref.FieldDescriptors { return &emptyFields }
-func (t placeholderMessage) Oneofs() pref.OneofDescriptors { return &emptyOneofs }
-func (t placeholderMessage) ReservedNames() pref.Names { return &emptyNames }
-func (t placeholderMessage) ReservedRanges() pref.FieldRanges { return &emptyFieldRanges }
-func (t placeholderMessage) RequiredNumbers() pref.FieldNumbers { return &emptyNumbers }
-func (t placeholderMessage) ExtensionRanges() pref.FieldRanges { return &emptyFieldRanges }
-func (t placeholderMessage) ExtensionRangeOptions(int) pref.OptionsMessage { panic("out of bounds") }
-func (t placeholderMessage) Enums() pref.EnumDescriptors { return &emptyEnums }
-func (t placeholderMessage) Messages() pref.MessageDescriptors { return &emptyMessages }
-func (t placeholderMessage) Extensions() pref.ExtensionDescriptors { return &emptyExtensions }
-func (t placeholderMessage) Format(s fmt.State, r rune) { pfmt.FormatDesc(s, r, t) }
-func (t placeholderMessage) ProtoType(pref.MessageDescriptor) {}
-
-type placeholderEnum struct {
- placeholderName
-}
-
-func (t placeholderEnum) Options() pref.OptionsMessage { return optionTypes.Enum }
-func (t placeholderEnum) Values() pref.EnumValueDescriptors { return &emptyEnumValues }
-func (t placeholderEnum) ReservedNames() pref.Names { return &emptyNames }
-func (t placeholderEnum) ReservedRanges() pref.EnumRanges { return &emptyEnumRanges }
-func (t placeholderEnum) Format(s fmt.State, r rune) { pfmt.FormatDesc(s, r, t) }
-func (t placeholderEnum) ProtoType(pref.EnumDescriptor) {}
diff --git a/reflect/prototype/protofile.go b/reflect/prototype/protofile.go
deleted file mode 100644
index 9b141cd..0000000
--- a/reflect/prototype/protofile.go
+++ /dev/null
@@ -1,229 +0,0 @@
-// 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 prototype provides builders to construct protobuf types that
-// implement the interfaces defined in the protoreflect package.
-//
-// Protobuf types can either be constructed as standalone types
-// (e.g., StandaloneMessage), or together as a batch of types in a single
-// proto file (e.g., File). When creating standalone types, additional
-// information must be provided such as the full type name and the proto syntax.
-// When creating an entire file, the syntax and full name is derived from
-// the parent type.
-//
-// Most types contain options, defined as messages in descriptor.proto.
-// To avoid cyclic dependencies, the prototype package treats these options
-// as opaque protoreflect.ProtoMessage values. In some cases where the option
-// contains semantically important information (e.g.,
-// google.protobuf.MessageOptions.map_entry), this information must be provided
-// as a field of the corresponding type (e.g., prototype.Message.MapEntry).
-package prototype
-
-import "github.com/golang/protobuf/v2/reflect/protoreflect"
-
-// Every struct has a "meta" struct embedded within it as a pointer.
-// The meta type provides additional data structures for efficient lookup on
-// certain methods (e.g., ByName) or derived information that can be
-// derived from the parent (e.g., FullName). The meta type is lazily allocated
-// and initialized. This architectural approach keeps the literal representation
-// smaller, which then keeps the generated code size smaller.
-
-// TODO: Instead of a top-down construction approach where internal references
-// to message types use placeholder types, we could add a Reference method
-// on Message and Enum that creates a MessageDescriptor or EnumDescriptor
-// reference that only becomes valid after NewFile.
-// However, that API approach is more error prone, as it causes more memory
-// aliasing and provides more opportunity for misuse.
-// Also, it requires that NewFile at least eagerly initialize all
-// messages and enums list types. We can always add that API in the future.
-
-// File is a constructor for protoreflect.FileDescriptor.
-type File struct {
- Syntax protoreflect.Syntax
- Path string
- Package protoreflect.FullName
- Imports []protoreflect.FileImport
- Options protoreflect.OptionsMessage
-
- Enums []Enum
- Messages []Message
- Extensions []Extension
- Services []Service
-
- *fileMeta
-}
-
-// NewFile creates a new protoreflect.FileDescriptor from the provided value.
-// The file must represent a valid proto file according to protobuf semantics.
-//
-// Fields that reference an enum or message that is being declared within the
-// same File can be represented using a placeholder descriptor. NewFile will
-// automatically resolve the placeholder to point to a concrete descriptor.
-// Alternatively, a reference descriptor obtained via Enum.Reference or
-// Message.Reference can be used instead. The placeholder approach makes it
-// possible to declare the file descriptor as a single File literal and
-// is generally easier to use. The reference approach is more performant,
-// but also more error prone.
-//
-// The caller must relinquish full ownership of the input t and must not
-// access or mutate any fields. The input must not contain slices that are
-// sub-slices of each other.
-func NewFile(t *File) (protoreflect.FileDescriptor, error) {
- // TODO: Provide an unverified make that avoids validating the file.
- // This is useful for generated code since we know that protoc-gen-go
- // already validated the protobuf types.
- ft := newFile(t)
- if err := validateFile(ft); err != nil {
- return nil, err
- }
-
- // TODO: When using reference descriptors, it is vital that all enums and
- // messages are touched so that they are initialized before returning.
- // Otherwise, reference descriptors may still be invalid.
- //
- // We can remove this once validateFile is implemented, since it will
- // inherently touch all the necessary messages and enums.
- visitMessages(ft)
-
- return ft, nil
-}
-
-func visitMessages(d interface {
- Enums() protoreflect.EnumDescriptors
- Messages() protoreflect.MessageDescriptors
-}) {
- d.Enums()
- ms := d.Messages()
- for i := 0; i < ms.Len(); i++ {
- visitMessages(ms.Get(i))
- }
-}
-
-// Message is a constructor for protoreflect.MessageDescriptor.
-type Message struct {
- Name protoreflect.Name
- Fields []Field
- Oneofs []Oneof
- ReservedNames []protoreflect.Name
- ReservedRanges [][2]protoreflect.FieldNumber
- ExtensionRanges [][2]protoreflect.FieldNumber
- ExtensionRangeOptions []protoreflect.OptionsMessage
- Options protoreflect.OptionsMessage
- IsMapEntry bool
-
- Enums []Enum
- Messages []Message
- Extensions []Extension
-
- *messageMeta
-}
-
-// Reference returns m as a reference protoreflect.MessageDescriptor,
-// which can be used to satisfy internal dependencies within a proto file.
-// Methods on the returned descriptor are not valid until the file that this
-// message belongs to has been constructed via NewFile.
-func (m *Message) Reference() protoreflect.MessageDescriptor {
- return messageDesc{m}
-}
-
-// Field is a constructor for protoreflect.FieldDescriptor.
-type Field struct {
- Name protoreflect.Name
- Number protoreflect.FieldNumber
- Cardinality protoreflect.Cardinality
- Kind protoreflect.Kind
- JSONName string
- Default protoreflect.Value
- OneofName protoreflect.Name
- MessageType protoreflect.MessageDescriptor
- EnumType protoreflect.EnumDescriptor
- Options protoreflect.OptionsMessage
- IsPacked OptionalBool
- IsWeak bool
-
- *fieldMeta
-}
-
-// Oneof is a constructor for protoreflect.OneofDescriptor.
-type Oneof struct {
- Name protoreflect.Name
- Options protoreflect.OptionsMessage
-
- *oneofMeta
-}
-
-// Extension is a constructor for protoreflect.ExtensionDescriptor.
-type Extension struct {
- Name protoreflect.Name
- Number protoreflect.FieldNumber
- Cardinality protoreflect.Cardinality
- Kind protoreflect.Kind
- Default protoreflect.Value
- MessageType protoreflect.MessageDescriptor
- EnumType protoreflect.EnumDescriptor
- ExtendedType protoreflect.MessageDescriptor
- Options protoreflect.OptionsMessage
- IsPacked OptionalBool
-
- *extensionMeta
-}
-
-// Enum is a constructor for protoreflect.EnumDescriptor.
-type Enum struct {
- Name protoreflect.Name
- Values []EnumValue
- ReservedNames []protoreflect.Name
- ReservedRanges [][2]protoreflect.EnumNumber
- Options protoreflect.OptionsMessage
-
- *enumMeta
-}
-
-// Reference returns e as a reference protoreflect.EnumDescriptor,
-// which can be used to satisfy internal dependencies within a proto file.
-// Methods on the returned descriptor are not valid until the file that this
-// enum belongs to has been constructed via NewFile.
-func (e *Enum) Reference() protoreflect.EnumDescriptor {
- return enumDesc{e}
-}
-
-// EnumValue is a constructor for protoreflect.EnumValueDescriptor.
-type EnumValue struct {
- Name protoreflect.Name
- Number protoreflect.EnumNumber
- Options protoreflect.OptionsMessage
-
- *enumValueMeta
-}
-
-// Service is a constructor for protoreflect.ServiceDescriptor.
-type Service struct {
- Name protoreflect.Name
- Methods []Method
- Options protoreflect.OptionsMessage
-
- *serviceMeta
-}
-
-// Method is a constructor for protoreflect.MethodDescriptor.
-type Method struct {
- Name protoreflect.Name
- InputType protoreflect.MessageDescriptor
- OutputType protoreflect.MessageDescriptor
- IsStreamingClient bool
- IsStreamingServer bool
- Options protoreflect.OptionsMessage
-
- *methodMeta
-}
-
-// OptionalBool is a tristate boolean.
-type OptionalBool uint8
-
-// Tristate boolean values.
-const (
- DefaultBool OptionalBool = iota
- True
- False
-)
diff --git a/reflect/prototype/protofile_list.go b/reflect/prototype/protofile_list.go
deleted file mode 100644
index 188be49..0000000
--- a/reflect/prototype/protofile_list.go
+++ /dev/null
@@ -1,131 +0,0 @@
-// 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 prototype
-
-import (
- "fmt"
- "sync"
-
- pragma "github.com/golang/protobuf/v2/internal/pragma"
- pset "github.com/golang/protobuf/v2/internal/set"
- pfmt "github.com/golang/protobuf/v2/internal/typefmt"
- pref "github.com/golang/protobuf/v2/reflect/protoreflect"
-)
-
-type names []pref.Name
-
-func (p *names) Len() int { return len(*p) }
-func (p *names) Get(i int) pref.Name { return (*p)[i] }
-func (p *names) Has(s pref.Name) bool {
- for _, n := range *p {
- if s == n {
- return true
- }
- }
- return false
-}
-func (p *names) Format(s fmt.State, r rune) { pfmt.FormatList(s, r, p) }
-func (p *names) ProtoInternal(pragma.DoNotImplement) {}
-
-type numbersMeta struct {
- once sync.Once
- ns []pref.FieldNumber
- nss pset.Ints
-}
-type numbers numbersMeta
-
-func (p *numbersMeta) lazyInit(fs []Field) *numbers {
- p.once.Do(func() {
- for i := range fs {
- if f := &fs[i]; f.Cardinality == pref.Required {
- p.ns = append(p.ns, f.Number)
- p.nss.Set(uint64(f.Number))
- }
- }
- })
- return (*numbers)(p)
-}
-func (p *numbers) Len() int { return len(p.ns) }
-func (p *numbers) Get(i int) pref.FieldNumber { return p.ns[i] }
-func (p *numbers) Has(n pref.FieldNumber) bool { return p.nss.Has(uint64(n)) }
-func (p *numbers) Format(s fmt.State, r rune) { pfmt.FormatList(s, r, p) }
-func (p *numbers) ProtoInternal(pragma.DoNotImplement) {}
-
-type fieldRanges [][2]pref.FieldNumber
-
-func (p *fieldRanges) Len() int { return len(*p) }
-func (p *fieldRanges) Get(i int) [2]pref.FieldNumber { return (*p)[i] }
-func (p *fieldRanges) Has(n pref.FieldNumber) bool {
- for _, r := range *p {
- if r[0] <= n && n < r[1] {
- return true
- }
- }
- return false
-}
-func (p *fieldRanges) Format(s fmt.State, r rune) { pfmt.FormatList(s, r, p) }
-func (p *fieldRanges) ProtoInternal(pragma.DoNotImplement) {}
-
-type enumRanges [][2]pref.EnumNumber
-
-func (p *enumRanges) Len() int { return len(*p) }
-func (p *enumRanges) Get(i int) [2]pref.EnumNumber { return (*p)[i] }
-func (p *enumRanges) Has(n pref.EnumNumber) bool {
- for _, r := range *p {
- if r[0] <= n && n <= r[1] {
- return true
- }
- }
- return false
-}
-func (p *enumRanges) Format(s fmt.State, r rune) { pfmt.FormatList(s, r, p) }
-func (p *enumRanges) ProtoInternal(pragma.DoNotImplement) {}
-
-type fileImports []pref.FileImport
-
-func (p *fileImports) Len() int { return len(*p) }
-func (p *fileImports) Get(i int) pref.FileImport { return (*p)[i] }
-func (p *fileImports) Format(s fmt.State, r rune) { pfmt.FormatList(s, r, p) }
-func (p *fileImports) ProtoInternal(pragma.DoNotImplement) {}
-
-type oneofFieldsMeta struct {
- once sync.Once
- typs []pref.FieldDescriptor
- byName map[pref.Name]pref.FieldDescriptor
- byJSON map[string]pref.FieldDescriptor
- byNum map[pref.FieldNumber]pref.FieldDescriptor
-}
-type oneofFields oneofFieldsMeta
-
-func (p *oneofFieldsMeta) lazyInit(parent pref.Descriptor) *oneofFields {
- p.once.Do(func() {
- otyp := parent.(pref.OneofDescriptor)
- mtyp, _ := parent.Parent()
- fs := mtyp.(pref.MessageDescriptor).Fields()
- for i := 0; i < fs.Len(); i++ {
- if f := fs.Get(i); otyp == f.OneofType() {
- p.typs = append(p.typs, f)
- }
- }
- if len(p.typs) > 0 {
- p.byName = make(map[pref.Name]pref.FieldDescriptor, len(p.typs))
- p.byJSON = make(map[string]pref.FieldDescriptor, len(p.typs))
- p.byNum = make(map[pref.FieldNumber]pref.FieldDescriptor, len(p.typs))
- for _, f := range p.typs {
- p.byName[f.Name()] = f
- p.byJSON[f.JSONName()] = f
- p.byNum[f.Number()] = f
- }
- }
- })
- return (*oneofFields)(p)
-}
-func (p *oneofFields) Len() int { return len(p.typs) }
-func (p *oneofFields) Get(i int) pref.FieldDescriptor { return p.typs[i] }
-func (p *oneofFields) ByName(s pref.Name) pref.FieldDescriptor { return p.byName[s] }
-func (p *oneofFields) ByJSONName(s string) pref.FieldDescriptor { return p.byJSON[s] }
-func (p *oneofFields) ByNumber(n pref.FieldNumber) pref.FieldDescriptor { return p.byNum[n] }
-func (p *oneofFields) Format(s fmt.State, r rune) { pfmt.FormatList(s, r, p) }
-func (p *oneofFields) ProtoInternal(pragma.DoNotImplement) {}
diff --git a/reflect/prototype/protofile_list_gen.go b/reflect/prototype/protofile_list_gen.go
deleted file mode 100644
index fb3d741..0000000
--- a/reflect/prototype/protofile_list_gen.go
+++ /dev/null
@@ -1,445 +0,0 @@
-// 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.
-
-// Code generated by generate-types. DO NOT EDIT.
-
-package prototype
-
-import (
- "fmt"
- "sync"
-
- "github.com/golang/protobuf/v2/internal/pragma"
- "github.com/golang/protobuf/v2/internal/typefmt"
- "github.com/golang/protobuf/v2/reflect/protoreflect"
-)
-
-type messagesMeta struct {
- once sync.Once
- typs []Message
- nameOnce sync.Once
- byName map[protoreflect.Name]*Message
-}
-type messages messagesMeta
-
-func (p *messagesMeta) lazyInit(parent protoreflect.Descriptor, ts []Message) *messages {
- p.once.Do(func() {
- nb := getNameBuilder()
- defer putNameBuilder(nb)
- metas := make([]messageMeta, len(ts))
- for i := range ts {
- t := &ts[i]
- if t.messageMeta != nil {
- panic("already initialized")
- }
- t.messageMeta = &metas[i]
- t.inheritedMeta.init(nb, parent, i, t.Name, false)
- }
- p.typs = ts
- })
- return (*messages)(p)
-}
-func (p *messages) Len() int { return len(p.typs) }
-func (p *messages) Get(i int) protoreflect.MessageDescriptor { return messageDesc{&p.typs[i]} }
-func (p *messages) ByName(s protoreflect.Name) protoreflect.MessageDescriptor {
- p.nameOnce.Do(func() {
- if len(p.typs) > 0 {
- p.byName = make(map[protoreflect.Name]*Message, len(p.typs))
- for i := range p.typs {
- t := &p.typs[i]
- p.byName[t.Name] = t
- }
- }
- })
- t := p.byName[s]
- if t == nil {
- return nil
- }
- return messageDesc{t}
-}
-func (p *messages) Format(s fmt.State, r rune) { typefmt.FormatList(s, r, p) }
-func (p *messages) ProtoInternal(pragma.DoNotImplement) {}
-
-type fieldsMeta struct {
- once sync.Once
- typs []Field
- nameOnce sync.Once
- byName map[protoreflect.Name]*Field
- jsonOnce sync.Once
- byJSON map[string]*Field
- numOnce sync.Once
- byNum map[protoreflect.FieldNumber]*Field
-}
-type fields fieldsMeta
-
-func (p *fieldsMeta) lazyInit(parent protoreflect.Descriptor, ts []Field) *fields {
- p.once.Do(func() {
- nb := getNameBuilder()
- defer putNameBuilder(nb)
- metas := make([]fieldMeta, len(ts))
- for i := range ts {
- t := &ts[i]
- if t.fieldMeta != nil {
- panic("already initialized")
- }
- t.fieldMeta = &metas[i]
- t.inheritedMeta.init(nb, parent, i, t.Name, false)
- }
- p.typs = ts
- })
- return (*fields)(p)
-}
-func (p *fields) Len() int { return len(p.typs) }
-func (p *fields) Get(i int) protoreflect.FieldDescriptor { return fieldDesc{&p.typs[i]} }
-func (p *fields) ByName(s protoreflect.Name) protoreflect.FieldDescriptor {
- p.nameOnce.Do(func() {
- if len(p.typs) > 0 {
- p.byName = make(map[protoreflect.Name]*Field, len(p.typs))
- for i := range p.typs {
- t := &p.typs[i]
- p.byName[t.Name] = t
- }
- }
- })
- t := p.byName[s]
- if t == nil {
- return nil
- }
- return fieldDesc{t}
-}
-func (p *fields) ByJSONName(s string) protoreflect.FieldDescriptor {
- p.jsonOnce.Do(func() {
- if len(p.typs) > 0 {
- p.byJSON = make(map[string]*Field, len(p.typs))
- for i := range p.typs {
- t := &p.typs[i]
- s := fieldDesc{t}.JSONName()
- if _, ok := p.byJSON[s]; !ok {
- p.byJSON[s] = t
- }
- }
- }
- })
- t := p.byJSON[s]
- if t == nil {
- return nil
- }
- return fieldDesc{t}
-}
-func (p *fields) ByNumber(n protoreflect.FieldNumber) protoreflect.FieldDescriptor {
- p.numOnce.Do(func() {
- if len(p.typs) > 0 {
- p.byNum = make(map[protoreflect.FieldNumber]*Field, len(p.typs))
- for i := range p.typs {
- t := &p.typs[i]
- if _, ok := p.byNum[t.Number]; !ok {
- p.byNum[t.Number] = t
- }
- }
- }
- })
- t := p.byNum[n]
- if t == nil {
- return nil
- }
- return fieldDesc{t}
-}
-func (p *fields) Format(s fmt.State, r rune) { typefmt.FormatList(s, r, p) }
-func (p *fields) ProtoInternal(pragma.DoNotImplement) {}
-
-type oneofsMeta struct {
- once sync.Once
- typs []Oneof
- nameOnce sync.Once
- byName map[protoreflect.Name]*Oneof
-}
-type oneofs oneofsMeta
-
-func (p *oneofsMeta) lazyInit(parent protoreflect.Descriptor, ts []Oneof) *oneofs {
- p.once.Do(func() {
- nb := getNameBuilder()
- defer putNameBuilder(nb)
- metas := make([]oneofMeta, len(ts))
- for i := range ts {
- t := &ts[i]
- if t.oneofMeta != nil {
- panic("already initialized")
- }
- t.oneofMeta = &metas[i]
- t.inheritedMeta.init(nb, parent, i, t.Name, false)
- }
- p.typs = ts
- })
- return (*oneofs)(p)
-}
-func (p *oneofs) Len() int { return len(p.typs) }
-func (p *oneofs) Get(i int) protoreflect.OneofDescriptor { return oneofDesc{&p.typs[i]} }
-func (p *oneofs) ByName(s protoreflect.Name) protoreflect.OneofDescriptor {
- p.nameOnce.Do(func() {
- if len(p.typs) > 0 {
- p.byName = make(map[protoreflect.Name]*Oneof, len(p.typs))
- for i := range p.typs {
- t := &p.typs[i]
- p.byName[t.Name] = t
- }
- }
- })
- t := p.byName[s]
- if t == nil {
- return nil
- }
- return oneofDesc{t}
-}
-func (p *oneofs) Format(s fmt.State, r rune) { typefmt.FormatList(s, r, p) }
-func (p *oneofs) ProtoInternal(pragma.DoNotImplement) {}
-
-type extensionsMeta struct {
- once sync.Once
- typs []Extension
- nameOnce sync.Once
- byName map[protoreflect.Name]*Extension
-}
-type extensions extensionsMeta
-
-func (p *extensionsMeta) lazyInit(parent protoreflect.Descriptor, ts []Extension) *extensions {
- p.once.Do(func() {
- nb := getNameBuilder()
- defer putNameBuilder(nb)
- metas := make([]extensionMeta, len(ts))
- for i := range ts {
- t := &ts[i]
- if t.extensionMeta != nil {
- panic("already initialized")
- }
- t.extensionMeta = &metas[i]
- t.inheritedMeta.init(nb, parent, i, t.Name, false)
- }
- p.typs = ts
- })
- return (*extensions)(p)
-}
-func (p *extensions) Len() int { return len(p.typs) }
-func (p *extensions) Get(i int) protoreflect.ExtensionDescriptor { return extensionDesc{&p.typs[i]} }
-func (p *extensions) ByName(s protoreflect.Name) protoreflect.ExtensionDescriptor {
- p.nameOnce.Do(func() {
- if len(p.typs) > 0 {
- p.byName = make(map[protoreflect.Name]*Extension, len(p.typs))
- for i := range p.typs {
- t := &p.typs[i]
- p.byName[t.Name] = t
- }
- }
- })
- t := p.byName[s]
- if t == nil {
- return nil
- }
- return extensionDesc{t}
-}
-func (p *extensions) Format(s fmt.State, r rune) { typefmt.FormatList(s, r, p) }
-func (p *extensions) ProtoInternal(pragma.DoNotImplement) {}
-
-type enumsMeta struct {
- once sync.Once
- typs []Enum
- nameOnce sync.Once
- byName map[protoreflect.Name]*Enum
-}
-type enums enumsMeta
-
-func (p *enumsMeta) lazyInit(parent protoreflect.Descriptor, ts []Enum) *enums {
- p.once.Do(func() {
- nb := getNameBuilder()
- defer putNameBuilder(nb)
- metas := make([]enumMeta, len(ts))
- for i := range ts {
- t := &ts[i]
- if t.enumMeta != nil {
- panic("already initialized")
- }
- t.enumMeta = &metas[i]
- t.inheritedMeta.init(nb, parent, i, t.Name, false)
- }
- p.typs = ts
- })
- return (*enums)(p)
-}
-func (p *enums) Len() int { return len(p.typs) }
-func (p *enums) Get(i int) protoreflect.EnumDescriptor { return enumDesc{&p.typs[i]} }
-func (p *enums) ByName(s protoreflect.Name) protoreflect.EnumDescriptor {
- p.nameOnce.Do(func() {
- if len(p.typs) > 0 {
- p.byName = make(map[protoreflect.Name]*Enum, len(p.typs))
- for i := range p.typs {
- t := &p.typs[i]
- p.byName[t.Name] = t
- }
- }
- })
- t := p.byName[s]
- if t == nil {
- return nil
- }
- return enumDesc{t}
-}
-func (p *enums) Format(s fmt.State, r rune) { typefmt.FormatList(s, r, p) }
-func (p *enums) ProtoInternal(pragma.DoNotImplement) {}
-
-type enumValuesMeta struct {
- once sync.Once
- typs []EnumValue
- nameOnce sync.Once
- byName map[protoreflect.Name]*EnumValue
- numOnce sync.Once
- byNum map[protoreflect.EnumNumber]*EnumValue
-}
-type enumValues enumValuesMeta
-
-func (p *enumValuesMeta) lazyInit(parent protoreflect.Descriptor, ts []EnumValue) *enumValues {
- p.once.Do(func() {
- nb := getNameBuilder()
- defer putNameBuilder(nb)
- metas := make([]enumValueMeta, len(ts))
- for i := range ts {
- t := &ts[i]
- if t.enumValueMeta != nil {
- panic("already initialized")
- }
- t.enumValueMeta = &metas[i]
- t.inheritedMeta.init(nb, parent, i, t.Name, true)
- }
- p.typs = ts
- })
- return (*enumValues)(p)
-}
-func (p *enumValues) Len() int { return len(p.typs) }
-func (p *enumValues) Get(i int) protoreflect.EnumValueDescriptor { return enumValueDesc{&p.typs[i]} }
-func (p *enumValues) ByName(s protoreflect.Name) protoreflect.EnumValueDescriptor {
- p.nameOnce.Do(func() {
- if len(p.typs) > 0 {
- p.byName = make(map[protoreflect.Name]*EnumValue, len(p.typs))
- for i := range p.typs {
- t := &p.typs[i]
- p.byName[t.Name] = t
- }
- }
- })
- t := p.byName[s]
- if t == nil {
- return nil
- }
- return enumValueDesc{t}
-}
-func (p *enumValues) ByNumber(n protoreflect.EnumNumber) protoreflect.EnumValueDescriptor {
- p.numOnce.Do(func() {
- if len(p.typs) > 0 {
- p.byNum = make(map[protoreflect.EnumNumber]*EnumValue, len(p.typs))
- for i := range p.typs {
- t := &p.typs[i]
- if _, ok := p.byNum[t.Number]; !ok {
- p.byNum[t.Number] = t
- }
- }
- }
- })
- t := p.byNum[n]
- if t == nil {
- return nil
- }
- return enumValueDesc{t}
-}
-func (p *enumValues) Format(s fmt.State, r rune) { typefmt.FormatList(s, r, p) }
-func (p *enumValues) ProtoInternal(pragma.DoNotImplement) {}
-
-type servicesMeta struct {
- once sync.Once
- typs []Service
- nameOnce sync.Once
- byName map[protoreflect.Name]*Service
-}
-type services servicesMeta
-
-func (p *servicesMeta) lazyInit(parent protoreflect.Descriptor, ts []Service) *services {
- p.once.Do(func() {
- nb := getNameBuilder()
- defer putNameBuilder(nb)
- metas := make([]serviceMeta, len(ts))
- for i := range ts {
- t := &ts[i]
- if t.serviceMeta != nil {
- panic("already initialized")
- }
- t.serviceMeta = &metas[i]
- t.inheritedMeta.init(nb, parent, i, t.Name, false)
- }
- p.typs = ts
- })
- return (*services)(p)
-}
-func (p *services) Len() int { return len(p.typs) }
-func (p *services) Get(i int) protoreflect.ServiceDescriptor { return serviceDesc{&p.typs[i]} }
-func (p *services) ByName(s protoreflect.Name) protoreflect.ServiceDescriptor {
- p.nameOnce.Do(func() {
- if len(p.typs) > 0 {
- p.byName = make(map[protoreflect.Name]*Service, len(p.typs))
- for i := range p.typs {
- t := &p.typs[i]
- p.byName[t.Name] = t
- }
- }
- })
- t := p.byName[s]
- if t == nil {
- return nil
- }
- return serviceDesc{t}
-}
-func (p *services) Format(s fmt.State, r rune) { typefmt.FormatList(s, r, p) }
-func (p *services) ProtoInternal(pragma.DoNotImplement) {}
-
-type methodsMeta struct {
- once sync.Once
- typs []Method
- nameOnce sync.Once
- byName map[protoreflect.Name]*Method
-}
-type methods methodsMeta
-
-func (p *methodsMeta) lazyInit(parent protoreflect.Descriptor, ts []Method) *methods {
- p.once.Do(func() {
- nb := getNameBuilder()
- defer putNameBuilder(nb)
- metas := make([]methodMeta, len(ts))
- for i := range ts {
- t := &ts[i]
- if t.methodMeta != nil {
- panic("already initialized")
- }
- t.methodMeta = &metas[i]
- t.inheritedMeta.init(nb, parent, i, t.Name, false)
- }
- p.typs = ts
- })
- return (*methods)(p)
-}
-func (p *methods) Len() int { return len(p.typs) }
-func (p *methods) Get(i int) protoreflect.MethodDescriptor { return methodDesc{&p.typs[i]} }
-func (p *methods) ByName(s protoreflect.Name) protoreflect.MethodDescriptor {
- p.nameOnce.Do(func() {
- if len(p.typs) > 0 {
- p.byName = make(map[protoreflect.Name]*Method, len(p.typs))
- for i := range p.typs {
- t := &p.typs[i]
- p.byName[t.Name] = t
- }
- }
- })
- t := p.byName[s]
- if t == nil {
- return nil
- }
- return methodDesc{t}
-}
-func (p *methods) Format(s fmt.State, r rune) { typefmt.FormatList(s, r, p) }
-func (p *methods) ProtoInternal(pragma.DoNotImplement) {}
diff --git a/reflect/prototype/protofile_type.go b/reflect/prototype/protofile_type.go
deleted file mode 100644
index 421fe9e..0000000
--- a/reflect/prototype/protofile_type.go
+++ /dev/null
@@ -1,639 +0,0 @@
-// 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 prototype
-
-import (
- "bytes"
- "fmt"
- "strings"
- "sync"
-
- pragma "github.com/golang/protobuf/v2/internal/pragma"
- pfmt "github.com/golang/protobuf/v2/internal/typefmt"
- pref "github.com/golang/protobuf/v2/reflect/protoreflect"
-)
-
-// inheritedMeta is information inherited from the parent.
-type inheritedMeta struct {
- parent pref.Descriptor
- index int
- syntax pref.Syntax
- fullName pref.FullName
-}
-
-func (m *inheritedMeta) init(nb *nameBuilder, parent pref.Descriptor, index int, name pref.Name, child bool) {
- // Most descriptors are namespaced as a child of their parent.
- // However, EnumValues are the exception in that they are namespaced
- // as a sibling of the parent Enum type.
- prefix := parent.FullName()
- if child {
- prefix = prefix.Parent()
- }
-
- m.parent = parent
- m.index = index
- m.syntax = parent.Syntax()
- m.fullName = nb.Append(prefix, name)
-}
-
-type fileMeta struct {
- ms messagesMeta
- es enumsMeta
- xs extensionsMeta
- ss servicesMeta
- ds descriptorsMeta
-}
-type fileDesc struct{ f *File }
-
-// altOptions returns m as is if it is non-nil. Otherwise, it returns alt.
-func altOptions(m, alt pref.OptionsMessage) pref.OptionsMessage {
- if m != nil {
- return m
- }
- return alt
-}
-
-func newFile(f *File) fileDesc {
- if f.fileMeta != nil {
- panic("already initialized")
- }
- f.fileMeta = new(fileMeta)
- return fileDesc{f}
-}
-func (t fileDesc) Parent() (pref.Descriptor, bool) { return nil, false }
-func (t fileDesc) Index() int { return 0 }
-func (t fileDesc) Syntax() pref.Syntax { return t.f.Syntax }
-func (t fileDesc) Name() pref.Name { return t.f.Package.Name() }
-func (t fileDesc) FullName() pref.FullName { return t.f.Package }
-func (t fileDesc) IsPlaceholder() bool { return false }
-func (t fileDesc) Options() pref.OptionsMessage { return altOptions(t.f.Options, optionTypes.File) }
-func (t fileDesc) Path() string { return t.f.Path }
-func (t fileDesc) Package() pref.FullName { return t.f.Package }
-func (t fileDesc) Imports() pref.FileImports { return (*fileImports)(&t.f.Imports) }
-func (t fileDesc) Enums() pref.EnumDescriptors { return t.f.es.lazyInit(t, t.f.Enums) }
-func (t fileDesc) Messages() pref.MessageDescriptors { return t.f.ms.lazyInit(t, t.f.Messages) }
-func (t fileDesc) Extensions() pref.ExtensionDescriptors { return t.f.xs.lazyInit(t, t.f.Extensions) }
-func (t fileDesc) Services() pref.ServiceDescriptors { return t.f.ss.lazyInit(t, t.f.Services) }
-func (t fileDesc) DescriptorByName(s pref.FullName) pref.Descriptor { return t.f.ds.lookup(t, s) }
-func (t fileDesc) Format(s fmt.State, r rune) { pfmt.FormatDesc(s, r, t) }
-func (t fileDesc) ProtoType(pref.FileDescriptor) {}
-func (t fileDesc) ProtoInternal(pragma.DoNotImplement) {}
-
-// descriptorsMeta is a lazily initialized map of all descriptors declared in
-// the file by full name.
-type descriptorsMeta struct {
- once sync.Once
- m map[pref.FullName]pref.Descriptor
-}
-
-func (m *descriptorsMeta) lookup(fd pref.FileDescriptor, s pref.FullName) pref.Descriptor {
- m.once.Do(func() {
- m.m = make(map[pref.FullName]pref.Descriptor)
- m.initMap(fd)
- delete(m.m, fd.Package()) // avoid registering the file descriptor itself
- })
- return m.m[s]
-}
-func (m *descriptorsMeta) initMap(d pref.Descriptor) {
- m.m[d.FullName()] = d
- if ds, ok := d.(interface {
- Enums() pref.EnumDescriptors
- }); ok {
- for i := 0; i < ds.Enums().Len(); i++ {
- m.initMap(ds.Enums().Get(i))
- }
- }
- if ds, ok := d.(interface {
- Values() pref.EnumValueDescriptors
- }); ok {
- for i := 0; i < ds.Values().Len(); i++ {
- m.initMap(ds.Values().Get(i))
- }
- }
- if ds, ok := d.(interface {
- Messages() pref.MessageDescriptors
- }); ok {
- for i := 0; i < ds.Messages().Len(); i++ {
- m.initMap(ds.Messages().Get(i))
- }
- }
- if ds, ok := d.(interface {
- Fields() pref.FieldDescriptors
- }); ok {
- for i := 0; i < ds.Fields().Len(); i++ {
- m.initMap(ds.Fields().Get(i))
- }
- }
- if ds, ok := d.(interface {
- Oneofs() pref.OneofDescriptors
- }); ok {
- for i := 0; i < ds.Oneofs().Len(); i++ {
- m.initMap(ds.Oneofs().Get(i))
- }
- }
- if ds, ok := d.(interface {
- Extensions() pref.ExtensionDescriptors
- }); ok {
- for i := 0; i < ds.Extensions().Len(); i++ {
- m.initMap(ds.Extensions().Get(i))
- }
- }
- if ds, ok := d.(interface {
- Services() pref.ServiceDescriptors
- }); ok {
- for i := 0; i < ds.Services().Len(); i++ {
- m.initMap(ds.Services().Get(i))
- }
- }
- if ds, ok := d.(interface {
- Methods() pref.MethodDescriptors
- }); ok {
- for i := 0; i < ds.Methods().Len(); i++ {
- m.initMap(ds.Methods().Get(i))
- }
- }
-}
-
-type messageMeta struct {
- inheritedMeta
-
- fs fieldsMeta
- os oneofsMeta
- ns numbersMeta
- ms messagesMeta
- es enumsMeta
- xs extensionsMeta
-}
-type messageDesc struct{ m *Message }
-
-func (t messageDesc) Parent() (pref.Descriptor, bool) { return t.m.parent, true }
-func (t messageDesc) Index() int { return t.m.index }
-func (t messageDesc) Syntax() pref.Syntax { return t.m.syntax }
-func (t messageDesc) Name() pref.Name { return t.m.Name }
-func (t messageDesc) FullName() pref.FullName { return t.m.fullName }
-func (t messageDesc) IsPlaceholder() bool { return false }
-func (t messageDesc) Options() pref.OptionsMessage {
- return altOptions(t.m.Options, optionTypes.Message)
-}
-func (t messageDesc) IsMapEntry() bool { return t.m.IsMapEntry }
-func (t messageDesc) Fields() pref.FieldDescriptors { return t.m.fs.lazyInit(t, t.m.Fields) }
-func (t messageDesc) Oneofs() pref.OneofDescriptors { return t.m.os.lazyInit(t, t.m.Oneofs) }
-func (t messageDesc) ReservedNames() pref.Names { return (*names)(&t.m.ReservedNames) }
-func (t messageDesc) ReservedRanges() pref.FieldRanges { return (*fieldRanges)(&t.m.ReservedRanges) }
-func (t messageDesc) RequiredNumbers() pref.FieldNumbers { return t.m.ns.lazyInit(t.m.Fields) }
-func (t messageDesc) ExtensionRanges() pref.FieldRanges { return (*fieldRanges)(&t.m.ExtensionRanges) }
-func (t messageDesc) ExtensionRangeOptions(i int) pref.OptionsMessage {
- return extensionRangeOptions(i, len(t.m.ExtensionRanges), t.m.ExtensionRangeOptions)
-}
-func (t messageDesc) Enums() pref.EnumDescriptors { return t.m.es.lazyInit(t, t.m.Enums) }
-func (t messageDesc) Messages() pref.MessageDescriptors { return t.m.ms.lazyInit(t, t.m.Messages) }
-func (t messageDesc) Extensions() pref.ExtensionDescriptors { return t.m.xs.lazyInit(t, t.m.Extensions) }
-func (t messageDesc) Format(s fmt.State, r rune) { pfmt.FormatDesc(s, r, t) }
-func (t messageDesc) ProtoType(pref.MessageDescriptor) {}
-func (t messageDesc) ProtoInternal(pragma.DoNotImplement) {}
-
-func extensionRangeOptions(i, n int, ms []pref.OptionsMessage) pref.OptionsMessage {
- if i < 0 || i >= n {
- panic("out of bounds")
- }
- var m pref.OptionsMessage
- if i < len(ms) {
- m = ms[i]
- }
- if m == nil {
- m = optionTypes.ExtensionRange
- }
- return m
-}
-
-type fieldMeta struct {
- inheritedMeta
-
- js jsonName
- dv defaultValue
- ot oneofReference
- mt messageReference
- et enumReference
-}
-type fieldDesc struct{ f *Field }
-
-func (t fieldDesc) Parent() (pref.Descriptor, bool) { return t.f.parent, true }
-func (t fieldDesc) Index() int { return t.f.index }
-func (t fieldDesc) Syntax() pref.Syntax { return t.f.syntax }
-func (t fieldDesc) Name() pref.Name { return t.f.Name }
-func (t fieldDesc) FullName() pref.FullName { return t.f.fullName }
-func (t fieldDesc) IsPlaceholder() bool { return false }
-func (t fieldDesc) Options() pref.OptionsMessage { return altOptions(t.f.Options, optionTypes.Field) }
-func (t fieldDesc) Number() pref.FieldNumber { return t.f.Number }
-func (t fieldDesc) Cardinality() pref.Cardinality { return t.f.Cardinality }
-func (t fieldDesc) Kind() pref.Kind { return t.f.Kind }
-func (t fieldDesc) HasJSONName() bool { return t.f.JSONName != "" }
-func (t fieldDesc) JSONName() string { return t.f.js.lazyInit(t.f) }
-func (t fieldDesc) IsPacked() bool {
- return isPacked(t.f.IsPacked, t.f.syntax, t.f.Cardinality, t.f.Kind)
-}
-func (t fieldDesc) IsWeak() bool { return t.f.IsWeak }
-func (t fieldDesc) IsMap() bool {
- mt := t.MessageType()
- return mt != nil && mt.IsMapEntry()
-}
-func (t fieldDesc) HasDefault() bool { return t.f.Default.IsValid() }
-func (t fieldDesc) Default() pref.Value { return t.f.dv.value(t, t.f.Default) }
-func (t fieldDesc) DefaultEnumValue() pref.EnumValueDescriptor { return t.f.dv.enum(t, t.f.Default) }
-func (t fieldDesc) OneofType() pref.OneofDescriptor { return t.f.ot.lazyInit(t, t.f.OneofName) }
-func (t fieldDesc) ExtendedType() pref.MessageDescriptor { return nil }
-func (t fieldDesc) MessageType() pref.MessageDescriptor { return t.f.mt.lazyInit(t, &t.f.MessageType) }
-func (t fieldDesc) EnumType() pref.EnumDescriptor { return t.f.et.lazyInit(t, &t.f.EnumType) }
-func (t fieldDesc) Format(s fmt.State, r rune) { pfmt.FormatDesc(s, r, t) }
-func (t fieldDesc) ProtoType(pref.FieldDescriptor) {}
-func (t fieldDesc) ProtoInternal(pragma.DoNotImplement) {}
-
-func isPacked(packed OptionalBool, s pref.Syntax, c pref.Cardinality, k pref.Kind) bool {
- if packed == False || (packed == DefaultBool && s == pref.Proto2) {
- return false
- }
- if c != pref.Repeated {
- return false
- }
- switch k {
- case pref.StringKind, pref.BytesKind, pref.MessageKind, pref.GroupKind:
- return false
- }
- return true
-}
-
-type jsonName struct {
- once sync.Once
- name string
-}
-
-func (p *jsonName) lazyInit(f *Field) string {
- p.once.Do(func() {
- // TODO: We may need to share this logic with jsonpb for implementation
- // of the FieldMask well-known type.
- if f.JSONName != "" {
- p.name = f.JSONName
- return
- }
- var b []byte
- var wasUnderscore bool
- for i := 0; i < len(f.Name); i++ { // proto identifiers are always ASCII
- c := f.Name[i]
- if c != '_' {
- isLower := 'a' <= c && c <= 'z'
- if wasUnderscore && isLower {
- c -= 'a' - 'A'
- }
- b = append(b, c)
- }
- wasUnderscore = c == '_'
- }
- p.name = string(b)
- })
- return p.name
-}
-
-// oneofReference resolves the name of a oneof by searching the parent
-// message for the matching OneofDescriptor declaration.
-type oneofReference struct {
- once sync.Once
- otyp pref.OneofDescriptor
-}
-
-func (p *oneofReference) lazyInit(parent pref.Descriptor, name pref.Name) pref.OneofDescriptor {
- p.once.Do(func() {
- if name != "" {
- mtyp, _ := parent.Parent()
- p.otyp = mtyp.(pref.MessageDescriptor).Oneofs().ByName(name)
- // TODO: We need validate to detect this mismatch.
- }
- })
- return p.otyp
-}
-
-type oneofMeta struct {
- inheritedMeta
-
- fs oneofFieldsMeta
-}
-type oneofDesc struct{ o *Oneof }
-
-func (t oneofDesc) Parent() (pref.Descriptor, bool) { return t.o.parent, true }
-func (t oneofDesc) Index() int { return t.o.index }
-func (t oneofDesc) Syntax() pref.Syntax { return t.o.syntax }
-func (t oneofDesc) Name() pref.Name { return t.o.Name }
-func (t oneofDesc) FullName() pref.FullName { return t.o.fullName }
-func (t oneofDesc) IsPlaceholder() bool { return false }
-func (t oneofDesc) Options() pref.OptionsMessage { return altOptions(t.o.Options, optionTypes.Oneof) }
-func (t oneofDesc) Fields() pref.FieldDescriptors { return t.o.fs.lazyInit(t) }
-func (t oneofDesc) Format(s fmt.State, r rune) { pfmt.FormatDesc(s, r, t) }
-func (t oneofDesc) ProtoType(pref.OneofDescriptor) {}
-func (t oneofDesc) ProtoInternal(pragma.DoNotImplement) {}
-
-type extensionMeta struct {
- inheritedMeta
-
- dv defaultValue
- xt messageReference
- mt messageReference
- et enumReference
-}
-type extensionDesc struct{ x *Extension }
-
-func (t extensionDesc) Parent() (pref.Descriptor, bool) { return t.x.parent, true }
-func (t extensionDesc) Syntax() pref.Syntax { return t.x.syntax }
-func (t extensionDesc) Index() int { return t.x.index }
-func (t extensionDesc) Name() pref.Name { return t.x.Name }
-func (t extensionDesc) FullName() pref.FullName { return t.x.fullName }
-func (t extensionDesc) IsPlaceholder() bool { return false }
-func (t extensionDesc) Options() pref.OptionsMessage {
- return altOptions(t.x.Options, optionTypes.Field)
-}
-func (t extensionDesc) Number() pref.FieldNumber { return t.x.Number }
-func (t extensionDesc) Cardinality() pref.Cardinality { return t.x.Cardinality }
-func (t extensionDesc) Kind() pref.Kind { return t.x.Kind }
-func (t extensionDesc) HasJSONName() bool { return false }
-func (t extensionDesc) JSONName() string { return "" }
-func (t extensionDesc) IsPacked() bool {
- // Extensions always use proto2 defaults for packing.
- return isPacked(t.x.IsPacked, pref.Proto2, t.x.Cardinality, t.x.Kind)
-}
-func (t extensionDesc) IsWeak() bool { return false }
-func (t extensionDesc) IsMap() bool { return false }
-func (t extensionDesc) HasDefault() bool { return t.x.Default.IsValid() }
-func (t extensionDesc) Default() pref.Value { return t.x.dv.value(t, t.x.Default) }
-func (t extensionDesc) DefaultEnumValue() pref.EnumValueDescriptor { return t.x.dv.enum(t, t.x.Default) }
-func (t extensionDesc) OneofType() pref.OneofDescriptor { return nil }
-func (t extensionDesc) ExtendedType() pref.MessageDescriptor {
- return t.x.xt.lazyInit(t, &t.x.ExtendedType)
-}
-func (t extensionDesc) MessageType() pref.MessageDescriptor {
- return t.x.mt.lazyInit(t, &t.x.MessageType)
-}
-func (t extensionDesc) EnumType() pref.EnumDescriptor { return t.x.et.lazyInit(t, &t.x.EnumType) }
-func (t extensionDesc) Format(s fmt.State, r rune) { pfmt.FormatDesc(s, r, t) }
-func (t extensionDesc) ProtoType(pref.FieldDescriptor) {}
-func (t extensionDesc) ProtoInternal(pragma.DoNotImplement) {}
-
-type enumMeta struct {
- inheritedMeta
-
- vs enumValuesMeta
-}
-type enumDesc struct{ e *Enum }
-
-func (t enumDesc) Parent() (pref.Descriptor, bool) { return t.e.parent, true }
-func (t enumDesc) Index() int { return t.e.index }
-func (t enumDesc) Syntax() pref.Syntax { return t.e.syntax }
-func (t enumDesc) Name() pref.Name { return t.e.Name }
-func (t enumDesc) FullName() pref.FullName { return t.e.fullName }
-func (t enumDesc) IsPlaceholder() bool { return false }
-func (t enumDesc) Options() pref.OptionsMessage { return altOptions(t.e.Options, optionTypes.Enum) }
-func (t enumDesc) Values() pref.EnumValueDescriptors { return t.e.vs.lazyInit(t, t.e.Values) }
-func (t enumDesc) ReservedNames() pref.Names { return (*names)(&t.e.ReservedNames) }
-func (t enumDesc) ReservedRanges() pref.EnumRanges { return (*enumRanges)(&t.e.ReservedRanges) }
-func (t enumDesc) Format(s fmt.State, r rune) { pfmt.FormatDesc(s, r, t) }
-func (t enumDesc) ProtoType(pref.EnumDescriptor) {}
-func (t enumDesc) ProtoInternal(pragma.DoNotImplement) {}
-
-type enumValueMeta struct {
- inheritedMeta
-}
-type enumValueDesc struct{ v *EnumValue }
-
-func (t enumValueDesc) Parent() (pref.Descriptor, bool) { return t.v.parent, true }
-func (t enumValueDesc) Index() int { return t.v.index }
-func (t enumValueDesc) Syntax() pref.Syntax { return t.v.syntax }
-func (t enumValueDesc) Name() pref.Name { return t.v.Name }
-func (t enumValueDesc) FullName() pref.FullName { return t.v.fullName }
-func (t enumValueDesc) IsPlaceholder() bool { return false }
-func (t enumValueDesc) Options() pref.OptionsMessage {
- return altOptions(t.v.Options, optionTypes.EnumValue)
-}
-func (t enumValueDesc) Number() pref.EnumNumber { return t.v.Number }
-func (t enumValueDesc) Format(s fmt.State, r rune) { pfmt.FormatDesc(s, r, t) }
-func (t enumValueDesc) ProtoType(pref.EnumValueDescriptor) {}
-func (t enumValueDesc) ProtoInternal(pragma.DoNotImplement) {}
-
-type serviceMeta struct {
- inheritedMeta
-
- ms methodsMeta
-}
-type serviceDesc struct{ s *Service }
-
-func (t serviceDesc) Parent() (pref.Descriptor, bool) { return t.s.parent, true }
-func (t serviceDesc) Index() int { return t.s.index }
-func (t serviceDesc) Syntax() pref.Syntax { return t.s.syntax }
-func (t serviceDesc) Name() pref.Name { return t.s.Name }
-func (t serviceDesc) FullName() pref.FullName { return t.s.fullName }
-func (t serviceDesc) IsPlaceholder() bool { return false }
-func (t serviceDesc) Options() pref.OptionsMessage {
- return altOptions(t.s.Options, optionTypes.Service)
-}
-func (t serviceDesc) Methods() pref.MethodDescriptors { return t.s.ms.lazyInit(t, t.s.Methods) }
-func (t serviceDesc) Format(s fmt.State, r rune) { pfmt.FormatDesc(s, r, t) }
-func (t serviceDesc) ProtoType(pref.ServiceDescriptor) {}
-func (t serviceDesc) ProtoInternal(pragma.DoNotImplement) {}
-
-type methodMeta struct {
- inheritedMeta
-
- mit messageReference
- mot messageReference
-}
-type methodDesc struct{ m *Method }
-
-func (t methodDesc) Parent() (pref.Descriptor, bool) { return t.m.parent, true }
-func (t methodDesc) Index() int { return t.m.index }
-func (t methodDesc) Syntax() pref.Syntax { return t.m.syntax }
-func (t methodDesc) Name() pref.Name { return t.m.Name }
-func (t methodDesc) FullName() pref.FullName { return t.m.fullName }
-func (t methodDesc) IsPlaceholder() bool { return false }
-func (t methodDesc) Options() pref.OptionsMessage { return altOptions(t.m.Options, optionTypes.Method) }
-func (t methodDesc) InputType() pref.MessageDescriptor { return t.m.mit.lazyInit(t, &t.m.InputType) }
-func (t methodDesc) OutputType() pref.MessageDescriptor { return t.m.mot.lazyInit(t, &t.m.OutputType) }
-func (t methodDesc) IsStreamingClient() bool { return t.m.IsStreamingClient }
-func (t methodDesc) IsStreamingServer() bool { return t.m.IsStreamingServer }
-func (t methodDesc) Format(s fmt.State, r rune) { pfmt.FormatDesc(s, r, t) }
-func (t methodDesc) ProtoType(pref.MethodDescriptor) {}
-func (t methodDesc) ProtoInternal(pragma.DoNotImplement) {}
-
-type defaultValue struct {
- once sync.Once
- val pref.Value
- eval pref.EnumValueDescriptor
- buf []byte
-}
-
-var (
- zeroBool = pref.ValueOf(false)
- zeroInt32 = pref.ValueOf(int32(0))
- zeroInt64 = pref.ValueOf(int64(0))
- zeroUint32 = pref.ValueOf(uint32(0))
- zeroUint64 = pref.ValueOf(uint64(0))
- zeroFloat32 = pref.ValueOf(float32(0))
- zeroFloat64 = pref.ValueOf(float64(0))
- zeroString = pref.ValueOf(string(""))
- zeroBytes = pref.ValueOf([]byte(nil))
- zeroEnum = pref.ValueOf(pref.EnumNumber(0))
-)
-
-func (p *defaultValue) lazyInit(t pref.FieldDescriptor, v pref.Value) {
- p.once.Do(func() {
- p.val = v
- if v.IsValid() {
- switch t.Kind() {
- case pref.EnumKind:
- // Treat a string value as an identifier referencing some enum
- // value by name and extract the enum number.
- // If this fails, validateMessage will later detect that the
- // default value for an enum value is the wrong type.
- switch v := v.Interface().(type) {
- case string:
- if ev := t.EnumType().Values().ByName(pref.Name(v)); ev != nil {
- p.eval = ev
- p.val = pref.ValueOf(p.eval.Number())
- }
- case pref.EnumNumber:
- p.eval = t.EnumType().Values().ByNumber(v)
- }
- case pref.BytesKind:
- // Store a copy of the default bytes, so that we can detect
- // accidental mutations of the original value.
- if b, ok := v.Interface().([]byte); ok && len(b) > 0 {
- p.buf = append([]byte(nil), b...)
- }
- }
- return
- }
- switch t.Kind() {
- case pref.BoolKind:
- p.val = zeroBool
- case pref.Int32Kind, pref.Sint32Kind, pref.Sfixed32Kind:
- p.val = zeroInt32
- case pref.Int64Kind, pref.Sint64Kind, pref.Sfixed64Kind:
- p.val = zeroInt64
- case pref.Uint32Kind, pref.Fixed32Kind:
- p.val = zeroUint32
- case pref.Uint64Kind, pref.Fixed64Kind:
- p.val = zeroUint64
- case pref.FloatKind:
- p.val = zeroFloat32
- case pref.DoubleKind:
- p.val = zeroFloat64
- case pref.StringKind:
- p.val = zeroString
- case pref.BytesKind:
- p.val = zeroBytes
- case pref.EnumKind:
- p.val = zeroEnum
- if t.Syntax() == pref.Proto2 {
- if et := t.EnumType(); et != nil {
- if vs := et.Values(); vs.Len() > 0 {
- p.val = pref.ValueOf(vs.Get(0).Number())
- }
- }
- }
- }
- })
- if len(p.buf) > 0 && !bytes.Equal(p.buf, p.val.Bytes()) {
- // TODO: Avoid panic if we're running with the race detector and instead
- // spawn a goroutine that periodically resets this value back to the
- // original to induce a race that can be detected by the detector.
- panic(fmt.Sprintf("proto: detected mutation on the default bytes for %v", t.FullName()))
- }
-}
-
-func (p *defaultValue) value(t pref.FieldDescriptor, v pref.Value) pref.Value {
- p.lazyInit(t, v)
- return p.val
-}
-
-func (p *defaultValue) enum(t pref.FieldDescriptor, v pref.Value) pref.EnumValueDescriptor {
- p.lazyInit(t, v)
- return p.eval
-}
-
-// messageReference resolves PlaceholderMessages that reference declarations
-// within the FileDescriptor tree that parent is a member of.
-type messageReference struct{ once sync.Once }
-
-func (p *messageReference) lazyInit(parent pref.Descriptor, pt *pref.MessageDescriptor) pref.MessageDescriptor {
- p.once.Do(func() {
- if t := *pt; t != nil && t.IsPlaceholder() {
- if d, ok := resolveReference(parent, t.FullName()).(pref.MessageDescriptor); ok {
- *pt = d
- }
- }
- })
- return *pt
-}
-
-// enumReference resolves PlaceholderEnums that reference declarations
-// within the FileDescriptor tree that parent is a member of.
-type enumReference struct{ once sync.Once }
-
-func (p *enumReference) lazyInit(parent pref.Descriptor, pt *pref.EnumDescriptor) pref.EnumDescriptor {
- p.once.Do(func() {
- if t := *pt; t != nil && t.IsPlaceholder() {
- if d, ok := resolveReference(parent, t.FullName()).(pref.EnumDescriptor); ok {
- *pt = d
- }
- }
- })
- return *pt
-}
-
-// resolveReference searches parent for the MessageDescriptor or EnumDescriptor
-// declaration identified by refName. This returns nil if not found.
-func resolveReference(parent pref.Descriptor, refName pref.FullName) pref.Descriptor {
- // Ascend upwards until a prefix match is found.
- cur := parent
- for cur != nil {
- curName := cur.FullName()
- if strings.HasPrefix(string(refName), string(curName)) {
- if len(refName) == len(curName) {
- refName = refName[len(curName):]
- break // e.g., refName: foo.firetruck, curName: foo.firetruck
- } else if refName[len(curName)] == '.' {
- refName = refName[len(curName)+len("."):]
- break // e.g., refName: foo.firetruck.driver, curName: foo.firetruck
- } else if len(curName) == 0 {
- break // FileDescriptor has no package name
- }
- // No match. (e.g., refName: foo.firetruck, curName: foo.fire)
- }
- cur, _ = cur.Parent() // nil after ascending above FileDescriptor
- }
-
- // Descend downwards to resolve all relative names.
- for cur != nil && len(refName) > 0 {
- var head pref.Name
- head, refName = pref.Name(refName), ""
- if i := strings.IndexByte(string(head), '.'); i >= 0 {
- head, refName = head[:i], pref.FullName(head[i+len("."):])
- }
-
- // Search the current descriptor for the nested declaration.
- var next pref.Descriptor
- if t, ok := cur.(interface {
- Messages() pref.MessageDescriptors
- }); ok && next == nil {
- if d := t.Messages().ByName(head); d != nil {
- next = d
- }
- }
- if t, ok := cur.(interface {
- Enums() pref.EnumDescriptors
- }); ok && next == nil {
- if d := t.Enums().ByName(head); d != nil {
- next = d
- }
- }
- cur = next // nil if not found
- }
- return cur
-}
diff --git a/reflect/prototype/resolve_test.go b/reflect/prototype/resolve_test.go
deleted file mode 100644
index de0b758..0000000
--- a/reflect/prototype/resolve_test.go
+++ /dev/null
@@ -1,146 +0,0 @@
-// 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 prototype
-
-import (
- "testing"
-
- pref "github.com/golang/protobuf/v2/reflect/protoreflect"
-)
-
-func TestResolve(t *testing.T) {
- f := &File{
- Syntax: pref.Proto2,
- Package: "test",
- Messages: []Message{{
- Name: "FooMessage",
- Fields: []Field{{Name: "F", Number: 1, Cardinality: pref.Optional, Kind: pref.BytesKind}},
- Messages: []Message{{
- Name: "FooMessage",
- Fields: []Field{{Name: "F", Number: 1, Cardinality: pref.Optional, Kind: pref.BytesKind}},
- }, {
- Name: "BarMessage",
- Fields: []Field{{Name: "F", Number: 1, Cardinality: pref.Optional, Kind: pref.BytesKind}},
- }},
- Enums: []Enum{{
- Name: "FooEnum",
- Values: []EnumValue{{Name: "E", Number: 0}},
- }, {
- Name: "BarEnum",
- Values: []EnumValue{{Name: "E", Number: 0}},
- }},
- }, {
- Name: "BarMessage",
- Fields: []Field{{Name: "F", Number: 1, Cardinality: pref.Optional, Kind: pref.BytesKind}},
- }},
- Enums: []Enum{{
- Name: "FooEnum",
- Values: []EnumValue{{Name: "E", Number: 0}},
- }, {
- Name: "BarEnum",
- Values: []EnumValue{{Name: "E", Number: 0}},
- }},
- }
-
- fd, err := NewFile(f)
- if err != nil {
- t.Fatalf("NewFile() error: %v", err)
- }
-
- tests := []struct {
- parent pref.Descriptor
- name pref.FullName
- want pref.Descriptor
- }{{
- parent: fd.Enums().Get(0),
- name: "test.Foo",
- want: nil,
- }, {
- parent: fd.Enums().Get(0),
- name: "test.FooEnum",
- want: fd.Enums().Get(0),
- }, {
- parent: fd.Enums().Get(0),
- name: "test.BarEnum",
- want: fd.Enums().Get(1),
- }, {
- parent: fd.Enums().Get(0),
- name: "test.BarMessage",
- want: fd.Messages().Get(1),
- }, {
- parent: fd.Enums().Get(0),
- name: "test.FooMessage.BarMessage",
- want: fd.Messages().Get(0).Messages().Get(1),
- }, {
- parent: fd.Enums().Get(0),
- name: "test.FooMessage.Bar",
- want: nil,
- }, {
- parent: fd.Messages().Get(1),
- name: "test.FooMessage.BarEnum",
- want: fd.Messages().Get(0).Enums().Get(1),
- }, {
- parent: fd.Messages().Get(1),
- name: "test.FooEnum",
- want: fd.Enums().Get(0),
- }, {
- parent: fd.Messages().Get(0),
- name: "test.FooEnum",
- want: fd.Enums().Get(0),
- }, {
- parent: fd.Messages().Get(0),
- name: "test.FooEnum.NonExistent",
- want: nil,
- }, {
- parent: fd.Messages().Get(0),
- name: "test.FooMessage.FooEnum",
- want: fd.Messages().Get(0).Enums().Get(0),
- }, {
- parent: fd.Messages().Get(0),
- name: "test.FooMessage",
- want: fd.Messages().Get(0),
- }, {
- parent: fd.Messages().Get(0),
- name: "test.FooMessage.Fizz",
- want: nil,
- }, {
- parent: fd.Messages().Get(0).Messages().Get(0),
- name: "test.FooMessage.FooMessage",
- want: fd.Messages().Get(0).Messages().Get(0),
- }, {
- parent: fd.Messages().Get(0).Messages().Get(0),
- name: "test.FooMessage.BarMessage",
- want: fd.Messages().Get(0).Messages().Get(1),
- }, {
- parent: fd.Messages().Get(0).Messages().Get(0),
- name: "test.BarMessage.FooMessage",
- want: nil,
- }, {
- parent: fd.Messages().Get(0).Messages().Get(0),
- name: "test.BarMessage",
- want: fd.Messages().Get(1),
- }, {
- parent: fd.Messages().Get(0).Messages().Get(0),
- name: "test.BarMessageExtra",
- want: nil,
- }, {
- parent: fd.Messages().Get(0).Messages().Get(0),
- name: "taste.BarMessage",
- want: nil,
- }}
-
- for _, tt := range tests {
- got := resolveReference(tt.parent, tt.name)
- if got != tt.want {
- fullName := func(d pref.Descriptor) string {
- if d == nil {
- return "<nil>"
- }
- return string(d.FullName())
- }
- t.Errorf("resolveReference(%v, %v) = %v, want %v", fullName(tt.parent), tt.name, fullName(got), fullName(tt.want))
- }
- }
-}
diff --git a/reflect/prototype/standalone.go b/reflect/prototype/standalone.go
deleted file mode 100644
index 5dcf3a9..0000000
--- a/reflect/prototype/standalone.go
+++ /dev/null
@@ -1,135 +0,0 @@
-// 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 prototype
-
-import (
- "github.com/golang/protobuf/v2/internal/errors"
- "github.com/golang/protobuf/v2/reflect/protoreflect"
-)
-
-// TODO: Should the constructors take in a value rather than a pointer?
-// TODO: Support initializing StandaloneMessage from a google.protobuf.Type?
-
-// StandaloneMessage is a constructor for a protoreflect.MessageDescriptor
-// that does not have a parent and has no child declarations.
-type StandaloneMessage struct {
- Syntax protoreflect.Syntax
- FullName protoreflect.FullName
- Fields []Field
- Oneofs []Oneof
- ReservedNames []protoreflect.Name
- ReservedRanges [][2]protoreflect.FieldNumber
- ExtensionRanges [][2]protoreflect.FieldNumber
- ExtensionRangeOptions []protoreflect.OptionsMessage
- Options protoreflect.OptionsMessage
- IsMapEntry bool
-
- fields fieldsMeta
- oneofs oneofsMeta
- nums numbersMeta
-}
-
-// NewMessage creates a new protoreflect.MessageDescriptor.
-// The caller must relinquish full ownership of the input t and must not
-// access or mutate any fields.
-func NewMessage(t *StandaloneMessage) (protoreflect.MessageDescriptor, error) {
- mt := standaloneMessage{t}
- if err := validateMessage(mt); err != nil {
- return nil, err
- }
- return mt, nil
-}
-
-// NewMessages creates a set of new protoreflect.MessageDescriptors.
-//
-// This constructor permits the creation of cyclic message types that depend
-// on each other. For example, message A may have a field of type message B,
-// where message B may have a field of type message A. In such a case,
-// a placeholder message is used for these cyclic references.
-//
-// The caller must relinquish full ownership of the input ts and must not
-// access or mutate any fields.
-func NewMessages(ts []*StandaloneMessage) ([]protoreflect.MessageDescriptor, error) {
- // TODO: Should this be []*T or []T?
- // TODO: NewMessages is a superset of NewMessage. Do we need NewMessage?
- ms := map[protoreflect.FullName]protoreflect.MessageDescriptor{}
- for _, t := range ts {
- if _, ok := ms[t.FullName]; ok {
- return nil, errors.New("duplicate message %v", t.FullName)
- }
- ms[t.FullName] = standaloneMessage{t}
- }
-
- var mts []protoreflect.MessageDescriptor
- for _, t := range ts {
- for i, f := range t.Fields {
- // Resolve placeholder messages with a concrete standalone message.
- // If this fails, validateMessage will complain about it later.
- if f.MessageType != nil && f.MessageType.IsPlaceholder() && !f.IsWeak {
- if m, ok := ms[f.MessageType.FullName()]; ok {
- t.Fields[i].MessageType = m
- }
- }
- }
- mt := standaloneMessage{t}
- if err := validateMessage(mt); err != nil {
- return nil, err
- }
- mts = append(mts, mt)
- }
- return mts, nil
-}
-
-// StandaloneEnum is a constructor for a protoreflect.EnumDescriptor
-// that does not have a parent.
-type StandaloneEnum struct {
- Syntax protoreflect.Syntax
- FullName protoreflect.FullName
- Values []EnumValue
- ReservedNames []protoreflect.Name
- ReservedRanges [][2]protoreflect.EnumNumber
- Options protoreflect.OptionsMessage
-
- vals enumValuesMeta
-}
-
-// NewEnum creates a new protoreflect.EnumDescriptor.
-// The caller must relinquish full ownership of the input t and must not
-// access or mutate any fields.
-func NewEnum(t *StandaloneEnum) (protoreflect.EnumDescriptor, error) {
- et := standaloneEnum{t}
- if err := validateEnum(et); err != nil {
- return nil, err
- }
- return et, nil
-}
-
-// StandaloneExtension is a constructor for a protoreflect.ExtensionDescriptor
-// that does not have a parent.
-type StandaloneExtension struct {
- FullName protoreflect.FullName
- Number protoreflect.FieldNumber
- Cardinality protoreflect.Cardinality
- Kind protoreflect.Kind
- Default protoreflect.Value
- MessageType protoreflect.MessageDescriptor
- EnumType protoreflect.EnumDescriptor
- ExtendedType protoreflect.MessageDescriptor
- Options protoreflect.OptionsMessage
- IsPacked OptionalBool
-
- dv defaultValue
-}
-
-// NewExtension creates a new protoreflect.ExtensionDescriptor.
-// The caller must relinquish full ownership of the input t and must not
-// access or mutate any fields.
-func NewExtension(t *StandaloneExtension) (protoreflect.ExtensionDescriptor, error) {
- xt := standaloneExtension{t}
- if err := validateExtension(xt); err != nil {
- return nil, err
- }
- return xt, nil
-}
diff --git a/reflect/prototype/standalone_type.go b/reflect/prototype/standalone_type.go
deleted file mode 100644
index 1eeb6f6..0000000
--- a/reflect/prototype/standalone_type.go
+++ /dev/null
@@ -1,97 +0,0 @@
-// 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 prototype
-
-import (
- "fmt"
-
- pragma "github.com/golang/protobuf/v2/internal/pragma"
- pfmt "github.com/golang/protobuf/v2/internal/typefmt"
- pref "github.com/golang/protobuf/v2/reflect/protoreflect"
-)
-
-type standaloneMessage struct{ m *StandaloneMessage }
-
-func (t standaloneMessage) Parent() (pref.Descriptor, bool) { return nil, false }
-func (t standaloneMessage) Index() int { return 0 }
-func (t standaloneMessage) Syntax() pref.Syntax { return t.m.Syntax }
-func (t standaloneMessage) Name() pref.Name { return t.m.FullName.Name() }
-func (t standaloneMessage) FullName() pref.FullName { return t.m.FullName }
-func (t standaloneMessage) IsPlaceholder() bool { return false }
-func (t standaloneMessage) Options() pref.OptionsMessage {
- return altOptions(t.m.Options, optionTypes.Message)
-}
-func (t standaloneMessage) IsMapEntry() bool { return t.m.IsMapEntry }
-func (t standaloneMessage) Fields() pref.FieldDescriptors { return t.m.fields.lazyInit(t, t.m.Fields) }
-func (t standaloneMessage) Oneofs() pref.OneofDescriptors { return t.m.oneofs.lazyInit(t, t.m.Oneofs) }
-func (t standaloneMessage) ReservedNames() pref.Names { return (*names)(&t.m.ReservedNames) }
-func (t standaloneMessage) ReservedRanges() pref.FieldRanges {
- return (*fieldRanges)(&t.m.ReservedRanges)
-}
-func (t standaloneMessage) RequiredNumbers() pref.FieldNumbers { return t.m.nums.lazyInit(t.m.Fields) }
-func (t standaloneMessage) ExtensionRanges() pref.FieldRanges {
- return (*fieldRanges)(&t.m.ExtensionRanges)
-}
-func (t standaloneMessage) ExtensionRangeOptions(i int) pref.OptionsMessage {
- return extensionRangeOptions(i, len(t.m.ExtensionRanges), t.m.ExtensionRangeOptions)
-}
-func (t standaloneMessage) Enums() pref.EnumDescriptors { return &emptyEnums }
-func (t standaloneMessage) Messages() pref.MessageDescriptors { return &emptyMessages }
-func (t standaloneMessage) Extensions() pref.ExtensionDescriptors { return &emptyExtensions }
-func (t standaloneMessage) Format(s fmt.State, r rune) { pfmt.FormatDesc(s, r, t) }
-func (t standaloneMessage) ProtoType(pref.MessageDescriptor) {}
-func (t standaloneMessage) ProtoInternal(pragma.DoNotImplement) {}
-
-type standaloneEnum struct{ e *StandaloneEnum }
-
-func (t standaloneEnum) Parent() (pref.Descriptor, bool) { return nil, false }
-func (t standaloneEnum) Index() int { return 0 }
-func (t standaloneEnum) Syntax() pref.Syntax { return t.e.Syntax }
-func (t standaloneEnum) Name() pref.Name { return t.e.FullName.Name() }
-func (t standaloneEnum) FullName() pref.FullName { return t.e.FullName }
-func (t standaloneEnum) IsPlaceholder() bool { return false }
-func (t standaloneEnum) Options() pref.OptionsMessage {
- return altOptions(t.e.Options, optionTypes.Enum)
-}
-func (t standaloneEnum) Values() pref.EnumValueDescriptors { return t.e.vals.lazyInit(t, t.e.Values) }
-func (t standaloneEnum) ReservedNames() pref.Names { return (*names)(&t.e.ReservedNames) }
-func (t standaloneEnum) ReservedRanges() pref.EnumRanges { return (*enumRanges)(&t.e.ReservedRanges) }
-func (t standaloneEnum) Format(s fmt.State, r rune) { pfmt.FormatDesc(s, r, t) }
-func (t standaloneEnum) ProtoType(pref.EnumDescriptor) {}
-func (t standaloneEnum) ProtoInternal(pragma.DoNotImplement) {}
-
-type standaloneExtension struct{ x *StandaloneExtension }
-
-func (t standaloneExtension) Parent() (pref.Descriptor, bool) { return nil, false }
-func (t standaloneExtension) Index() int { return 0 }
-func (t standaloneExtension) Syntax() pref.Syntax { return pref.Proto2 }
-func (t standaloneExtension) Name() pref.Name { return t.x.FullName.Name() }
-func (t standaloneExtension) FullName() pref.FullName { return t.x.FullName }
-func (t standaloneExtension) IsPlaceholder() bool { return false }
-func (t standaloneExtension) Options() pref.OptionsMessage {
- return altOptions(t.x.Options, optionTypes.Field)
-}
-func (t standaloneExtension) Number() pref.FieldNumber { return t.x.Number }
-func (t standaloneExtension) Cardinality() pref.Cardinality { return t.x.Cardinality }
-func (t standaloneExtension) Kind() pref.Kind { return t.x.Kind }
-func (t standaloneExtension) HasJSONName() bool { return false }
-func (t standaloneExtension) JSONName() string { return "" }
-func (t standaloneExtension) IsPacked() bool {
- return isPacked(t.x.IsPacked, pref.Proto2, t.x.Cardinality, t.x.Kind)
-}
-func (t standaloneExtension) IsWeak() bool { return false }
-func (t standaloneExtension) IsMap() bool { return false }
-func (t standaloneExtension) HasDefault() bool { return t.x.Default.IsValid() }
-func (t standaloneExtension) Default() pref.Value { return t.x.dv.value(t, t.x.Default) }
-func (t standaloneExtension) DefaultEnumValue() pref.EnumValueDescriptor {
- return t.x.dv.enum(t, t.x.Default)
-}
-func (t standaloneExtension) OneofType() pref.OneofDescriptor { return nil }
-func (t standaloneExtension) MessageType() pref.MessageDescriptor { return t.x.MessageType }
-func (t standaloneExtension) EnumType() pref.EnumDescriptor { return t.x.EnumType }
-func (t standaloneExtension) ExtendedType() pref.MessageDescriptor { return t.x.ExtendedType }
-func (t standaloneExtension) Format(s fmt.State, r rune) { pfmt.FormatDesc(s, r, t) }
-func (t standaloneExtension) ProtoType(pref.FieldDescriptor) {}
-func (t standaloneExtension) ProtoInternal(pragma.DoNotImplement) {}
diff --git a/reflect/prototype/type_test.go b/reflect/prototype/type_test.go
deleted file mode 100644
index 5064af4..0000000
--- a/reflect/prototype/type_test.go
+++ /dev/null
@@ -1,906 +0,0 @@
-// 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 prototype_test
-
-import (
- "fmt"
- "reflect"
- "regexp"
- "strconv"
- "strings"
- "testing"
-
- protoV1 "github.com/golang/protobuf/proto"
- detrand "github.com/golang/protobuf/v2/internal/detrand"
- scalar "github.com/golang/protobuf/v2/internal/scalar"
- pdesc "github.com/golang/protobuf/v2/reflect/protodesc"
- pref "github.com/golang/protobuf/v2/reflect/protoreflect"
- ptype "github.com/golang/protobuf/v2/reflect/prototype"
-
- descriptorpb "github.com/golang/protobuf/v2/types/descriptor"
-)
-
-func init() {
- // Disable detrand to enable direct comparisons on outputs.
- detrand.Disable()
-}
-
-// TODO: Test protodesc.NewFile with imported files.
-
-func TestFile(t *testing.T) {
- f1 := &ptype.File{
- Syntax: pref.Proto2,
- Path: "path/to/file.proto",
- Package: "test",
- Options: &descriptorpb.FileOptions{Deprecated: scalar.Bool(true)},
- Messages: []ptype.Message{{
- Name: "A", // "test.A"
- Options: &descriptorpb.MessageOptions{
- MapEntry: scalar.Bool(true),
- Deprecated: scalar.Bool(true),
- },
- IsMapEntry: true,
- Fields: []ptype.Field{{
- Name: "key", // "test.A.key"
- Number: 1,
- Options: &descriptorpb.FieldOptions{Deprecated: scalar.Bool(true)},
- Cardinality: pref.Optional,
- Kind: pref.StringKind,
- }, {
- Name: "value", // "test.A.value"
- Number: 2,
- Cardinality: pref.Optional,
- Kind: pref.MessageKind,
- MessageType: ptype.PlaceholderMessage("test.B"),
- }},
- }, {
- Name: "B", // "test.B"
- Fields: []ptype.Field{{
- Name: "field_one", // "test.B.field_one"
- Number: 1,
- Cardinality: pref.Optional,
- Kind: pref.StringKind,
- Default: pref.ValueOf("hello, \"world!\"\n"),
- OneofName: "O1",
- }, {
- Name: "field_two", // "test.B.field_two"
- JSONName: "Field2",
- Number: 2,
- Cardinality: pref.Optional,
- Kind: pref.EnumKind,
- Default: pref.ValueOf(pref.EnumNumber(1)),
- EnumType: ptype.PlaceholderEnum("test.E1"),
- OneofName: "O2",
- }, {
- Name: "field_three", // "test.B.field_three"
- Number: 3,
- Cardinality: pref.Optional,
- Kind: pref.MessageKind,
- MessageType: ptype.PlaceholderMessage("test.C"),
- OneofName: "O2",
- }, {
- Name: "field_four", // "test.B.field_four"
- JSONName: "Field4",
- Number: 4,
- Cardinality: pref.Repeated,
- Kind: pref.MessageKind,
- MessageType: ptype.PlaceholderMessage("test.A"),
- }, {
- Name: "field_five", // "test.B.field_five"
- Number: 5,
- Cardinality: pref.Repeated,
- Kind: pref.Int32Kind,
- Options: &descriptorpb.FieldOptions{Packed: scalar.Bool(true)},
- IsPacked: ptype.True,
- }, {
- Name: "field_six", // "test.B.field_six"
- Number: 6,
- Cardinality: pref.Required,
- Kind: pref.BytesKind,
- }},
- Oneofs: []ptype.Oneof{
- {
- Name: "O1", // "test.B.O1"
- Options: &descriptorpb.OneofOptions{
- UninterpretedOption: []*descriptorpb.UninterpretedOption{
- {StringValue: []byte("option")},
- },
- },
- },
- {Name: "O2"}, // "test.B.O2"
- },
- ReservedNames: []pref.Name{"fizz", "buzz"},
- ReservedRanges: [][2]pref.FieldNumber{{100, 200}, {300, 301}},
- ExtensionRanges: [][2]pref.FieldNumber{{1000, 2000}, {3000, 3001}},
- ExtensionRangeOptions: []pref.OptionsMessage{
- 0: (*descriptorpb.ExtensionRangeOptions)(nil),
- 1: new(descriptorpb.ExtensionRangeOptions),
- },
- }, {
- Name: "C", // "test.C"
- Messages: []ptype.Message{{
- Name: "A", // "test.C.A"
- Fields: []ptype.Field{{Name: "F", Number: 1, Cardinality: pref.Required, Kind: pref.BytesKind, Default: pref.ValueOf([]byte("dead\xbe\xef"))}},
- }},
- Enums: []ptype.Enum{{
- Name: "E1", // "test.C.E1"
- Values: []ptype.EnumValue{{Name: "FOO", Number: 0}, {Name: "BAR", Number: 1}},
- }},
- Extensions: []ptype.Extension{{
- Name: "X", // "test.C.X"
- Number: 1000,
- Cardinality: pref.Repeated,
- Kind: pref.MessageKind,
- Options: &descriptorpb.FieldOptions{Packed: scalar.Bool(false)},
- IsPacked: ptype.False,
- MessageType: ptype.PlaceholderMessage("test.C"),
- ExtendedType: ptype.PlaceholderMessage("test.B"),
- }},
- }},
- Enums: []ptype.Enum{{
- Name: "E1", // "test.E1"
- Options: &descriptorpb.EnumOptions{Deprecated: scalar.Bool(true)},
- Values: []ptype.EnumValue{
- {
- Name: "FOO",
- Number: 0,
- Options: &descriptorpb.EnumValueOptions{Deprecated: scalar.Bool(true)},
- },
- {Name: "BAR", Number: 1},
- },
- ReservedNames: []pref.Name{"FIZZ", "BUZZ"},
- ReservedRanges: [][2]pref.EnumNumber{{10, 19}, {30, 30}},
- }},
- Extensions: []ptype.Extension{{
- Name: "X", // "test.X"
- Number: 1000,
- Cardinality: pref.Repeated,
- Kind: pref.MessageKind,
- Options: &descriptorpb.FieldOptions{Packed: scalar.Bool(true)},
- IsPacked: ptype.True,
- MessageType: ptype.PlaceholderMessage("test.C"),
- ExtendedType: ptype.PlaceholderMessage("test.B"),
- }},
- Services: []ptype.Service{{
- Name: "S", // "test.S"
- Options: &descriptorpb.ServiceOptions{Deprecated: scalar.Bool(true)},
- Methods: []ptype.Method{{
- Name: "M", // "test.S.M"
- InputType: ptype.PlaceholderMessage("test.A"),
- OutputType: ptype.PlaceholderMessage("test.C.A"),
- IsStreamingClient: true,
- IsStreamingServer: true,
- Options: &descriptorpb.MethodOptions{Deprecated: scalar.Bool(true)},
- }},
- }},
- }
- fd1, err := ptype.NewFile(f1)
- if err != nil {
- t.Fatalf("prototype.NewFile() error: %v", err)
- }
-
- f2 := &descriptorpb.FileDescriptorProto{
- Syntax: scalar.String("proto2"),
- Name: scalar.String("path/to/file.proto"),
- Package: scalar.String("test"),
- Options: &descriptorpb.FileOptions{Deprecated: scalar.Bool(true)},
- MessageType: []*descriptorpb.DescriptorProto{{
- Name: scalar.String("A"),
- Options: &descriptorpb.MessageOptions{
- MapEntry: scalar.Bool(true),
- Deprecated: scalar.Bool(true),
- },
- Field: []*descriptorpb.FieldDescriptorProto{{
- Name: scalar.String("key"),
- Number: scalar.Int32(1),
- Options: &descriptorpb.FieldOptions{Deprecated: scalar.Bool(true)},
- Label: descriptorpb.FieldDescriptorProto_Label(pref.Optional).Enum(),
- Type: descriptorpb.FieldDescriptorProto_Type(pref.StringKind).Enum(),
- }, {
- Name: scalar.String("value"),
- Number: scalar.Int32(2),
- Label: descriptorpb.FieldDescriptorProto_Label(pref.Optional).Enum(),
- Type: descriptorpb.FieldDescriptorProto_Type(pref.MessageKind).Enum(),
- TypeName: scalar.String(".test.B"),
- }},
- }, {
- Name: scalar.String("B"),
- Field: []*descriptorpb.FieldDescriptorProto{{
- Name: scalar.String("field_one"),
- Number: scalar.Int32(1),
- Label: descriptorpb.FieldDescriptorProto_Label(pref.Optional).Enum(),
- Type: descriptorpb.FieldDescriptorProto_Type(pref.StringKind).Enum(),
- DefaultValue: scalar.String("hello, \"world!\"\n"),
- OneofIndex: scalar.Int32(0),
- }, {
- Name: scalar.String("field_two"),
- JsonName: scalar.String("Field2"),
- Number: scalar.Int32(2),
- Label: descriptorpb.FieldDescriptorProto_Label(pref.Optional).Enum(),
- Type: descriptorpb.FieldDescriptorProto_Type(pref.EnumKind).Enum(),
- DefaultValue: scalar.String("BAR"),
- TypeName: scalar.String(".test.E1"),
- OneofIndex: scalar.Int32(1),
- }, {
- Name: scalar.String("field_three"),
- Number: scalar.Int32(3),
- Label: descriptorpb.FieldDescriptorProto_Label(pref.Optional).Enum(),
- Type: descriptorpb.FieldDescriptorProto_Type(pref.MessageKind).Enum(),
- TypeName: scalar.String(".test.C"),
- OneofIndex: scalar.Int32(1),
- }, {
- Name: scalar.String("field_four"),
- JsonName: scalar.String("Field4"),
- Number: scalar.Int32(4),
- Label: descriptorpb.FieldDescriptorProto_Label(pref.Repeated).Enum(),
- Type: descriptorpb.FieldDescriptorProto_Type(pref.MessageKind).Enum(),
- TypeName: scalar.String(".test.A"),
- }, {
- Name: scalar.String("field_five"),
- Number: scalar.Int32(5),
- Label: descriptorpb.FieldDescriptorProto_Label(pref.Repeated).Enum(),
- Type: descriptorpb.FieldDescriptorProto_Type(pref.Int32Kind).Enum(),
- Options: &descriptorpb.FieldOptions{Packed: scalar.Bool(true)},
- }, {
- Name: scalar.String("field_six"),
- Number: scalar.Int32(6),
- Label: descriptorpb.FieldDescriptorProto_Label(pref.Required).Enum(),
- Type: descriptorpb.FieldDescriptorProto_Type(pref.BytesKind).Enum(),
- }},
- OneofDecl: []*descriptorpb.OneofDescriptorProto{
- {
- Name: scalar.String("O1"),
- Options: &descriptorpb.OneofOptions{
- UninterpretedOption: []*descriptorpb.UninterpretedOption{
- {StringValue: []byte("option")},
- },
- },
- },
- {Name: scalar.String("O2")},
- },
- ReservedName: []string{"fizz", "buzz"},
- ReservedRange: []*descriptorpb.DescriptorProto_ReservedRange{
- {Start: scalar.Int32(100), End: scalar.Int32(200)},
- {Start: scalar.Int32(300), End: scalar.Int32(301)},
- },
- ExtensionRange: []*descriptorpb.DescriptorProto_ExtensionRange{
- {Start: scalar.Int32(1000), End: scalar.Int32(2000)},
- {Start: scalar.Int32(3000), End: scalar.Int32(3001), Options: new(descriptorpb.ExtensionRangeOptions)},
- },
- }, {
- Name: scalar.String("C"),
- NestedType: []*descriptorpb.DescriptorProto{{
- Name: scalar.String("A"),
- Field: []*descriptorpb.FieldDescriptorProto{{
- Name: scalar.String("F"),
- Number: scalar.Int32(1),
- Label: descriptorpb.FieldDescriptorProto_Label(pref.Required).Enum(),
- Type: descriptorpb.FieldDescriptorProto_Type(pref.BytesKind).Enum(),
- DefaultValue: scalar.String(`dead\276\357`),
- }},
- }},
- EnumType: []*descriptorpb.EnumDescriptorProto{{
- Name: scalar.String("E1"),
- Value: []*descriptorpb.EnumValueDescriptorProto{
- {Name: scalar.String("FOO"), Number: scalar.Int32(0)},
- {Name: scalar.String("BAR"), Number: scalar.Int32(1)},
- },
- }},
- Extension: []*descriptorpb.FieldDescriptorProto{{
- Name: scalar.String("X"),
- Number: scalar.Int32(1000),
- Label: descriptorpb.FieldDescriptorProto_Label(pref.Repeated).Enum(),
- Type: descriptorpb.FieldDescriptorProto_Type(pref.MessageKind).Enum(),
- TypeName: scalar.String(".test.C"),
- Extendee: scalar.String(".test.B"),
- }},
- }},
- EnumType: []*descriptorpb.EnumDescriptorProto{{
- Name: scalar.String("E1"),
- Options: &descriptorpb.EnumOptions{Deprecated: scalar.Bool(true)},
- Value: []*descriptorpb.EnumValueDescriptorProto{
- {
- Name: scalar.String("FOO"),
- Number: scalar.Int32(0),
- Options: &descriptorpb.EnumValueOptions{Deprecated: scalar.Bool(true)},
- },
- {Name: scalar.String("BAR"), Number: scalar.Int32(1)},
- },
- ReservedName: []string{"FIZZ", "BUZZ"},
- ReservedRange: []*descriptorpb.EnumDescriptorProto_EnumReservedRange{
- {Start: scalar.Int32(10), End: scalar.Int32(19)},
- {Start: scalar.Int32(30), End: scalar.Int32(30)},
- },
- }},
- Extension: []*descriptorpb.FieldDescriptorProto{{
- Name: scalar.String("X"),
- Number: scalar.Int32(1000),
- Label: descriptorpb.FieldDescriptorProto_Label(pref.Repeated).Enum(),
- Type: descriptorpb.FieldDescriptorProto_Type(pref.MessageKind).Enum(),
- Options: &descriptorpb.FieldOptions{Packed: scalar.Bool(true)},
- TypeName: scalar.String(".test.C"),
- Extendee: scalar.String(".test.B"),
- }},
- Service: []*descriptorpb.ServiceDescriptorProto{{
- Name: scalar.String("S"),
- Options: &descriptorpb.ServiceOptions{Deprecated: scalar.Bool(true)},
- Method: []*descriptorpb.MethodDescriptorProto{{
- Name: scalar.String("M"),
- InputType: scalar.String(".test.A"),
- OutputType: scalar.String(".test.C.A"),
- ClientStreaming: scalar.Bool(true),
- ServerStreaming: scalar.Bool(true),
- Options: &descriptorpb.MethodOptions{Deprecated: scalar.Bool(true)},
- }},
- }},
- }
- fd2, err := pdesc.NewFile(f2, nil)
- if err != nil {
- t.Fatalf("protodesc.NewFile() error: %v", err)
- }
-
- tests := []struct {
- name string
- desc pref.FileDescriptor
- }{
- {"prototype.NewFile", fd1},
- {"protodesc.NewFile", fd2},
- }
- for _, tt := range tests {
- tt := tt
- t.Run(tt.name, func(t *testing.T) {
- // Run sub-tests in parallel to induce potential races.
- for i := 0; i < 2; i++ {
- t.Run("Accessors", func(t *testing.T) { t.Parallel(); testFileAccessors(t, tt.desc) })
- t.Run("Format", func(t *testing.T) { t.Parallel(); testFileFormat(t, tt.desc) })
- }
- })
- }
-}
-
-func testFileAccessors(t *testing.T, fd pref.FileDescriptor) {
- // Represent the descriptor as a map where each key is an accessor method
- // and the value is either the wanted tail value or another accessor map.
- type M = map[string]interface{}
- want := M{
- "Parent": nil,
- "Index": 0,
- "Syntax": pref.Proto2,
- "Name": pref.Name("test"),
- "FullName": pref.FullName("test"),
- "Path": "path/to/file.proto",
- "Package": pref.FullName("test"),
- "IsPlaceholder": false,
- "Options": &descriptorpb.FileOptions{Deprecated: scalar.Bool(true)},
- "Messages": M{
- "Len": 3,
- "Get:0": M{
- "Parent": M{"FullName": pref.FullName("test")},
- "Index": 0,
- "Syntax": pref.Proto2,
- "Name": pref.Name("A"),
- "FullName": pref.FullName("test.A"),
- "IsPlaceholder": false,
- "IsMapEntry": true,
- "Options": &descriptorpb.MessageOptions{
- MapEntry: scalar.Bool(true),
- Deprecated: scalar.Bool(true),
- },
- "Fields": M{
- "Len": 2,
- "ByNumber:1": M{
- "Parent": M{"FullName": pref.FullName("test.A")},
- "Index": 0,
- "Name": pref.Name("key"),
- "FullName": pref.FullName("test.A.key"),
- "Number": pref.FieldNumber(1),
- "Cardinality": pref.Optional,
- "Kind": pref.StringKind,
- "Options": &descriptorpb.FieldOptions{Deprecated: scalar.Bool(true)},
- "HasJSONName": false,
- "JSONName": "key",
- "IsPacked": false,
- "IsMap": false,
- "IsWeak": false,
- "Default": "",
- "OneofType": nil,
- "ExtendedType": nil,
- "MessageType": nil,
- "EnumType": nil,
- },
- "ByNumber:2": M{
- "Parent": M{"FullName": pref.FullName("test.A")},
- "Index": 1,
- "Name": pref.Name("value"),
- "FullName": pref.FullName("test.A.value"),
- "Number": pref.FieldNumber(2),
- "Cardinality": pref.Optional,
- "Kind": pref.MessageKind,
- "JSONName": "value",
- "IsPacked": false,
- "IsMap": false,
- "IsWeak": false,
- "Default": nil,
- "OneofType": nil,
- "ExtendedType": nil,
- "MessageType": M{"FullName": pref.FullName("test.B"), "IsPlaceholder": false},
- "EnumType": nil,
- },
- "ByNumber:3": nil,
- },
- "Oneofs": M{"Len": 0},
- "RequiredNumbers": M{"Len": 0},
- "ExtensionRanges": M{"Len": 0},
- "Messages": M{"Len": 0},
- "Enums": M{"Len": 0},
- "Extensions": M{"Len": 0},
- },
- "ByName:B": M{
- "Name": pref.Name("B"),
- "Index": 1,
- "Fields": M{
- "Len": 6,
- "ByJSONName:field_one": nil,
- "ByJSONName:fieldOne": M{
- "Name": pref.Name("field_one"),
- "Index": 0,
- "JSONName": "fieldOne",
- "Default": "hello, \"world!\"\n",
- "OneofType": M{"Name": pref.Name("O1"), "IsPlaceholder": false},
- },
- "ByJSONName:fieldTwo": nil,
- "ByJSONName:Field2": M{
- "Name": pref.Name("field_two"),
- "Index": 1,
- "HasJSONName": true,
- "JSONName": "Field2",
- "Default": pref.EnumNumber(1),
- "OneofType": M{"Name": pref.Name("O2"), "IsPlaceholder": false},
- },
- "ByName:fieldThree": nil,
- "ByName:field_three": M{
- "IsMap": false,
- "MessageType": M{"FullName": pref.FullName("test.C"), "IsPlaceholder": false},
- "OneofType": M{"Name": pref.Name("O2"), "IsPlaceholder": false},
- },
- "ByNumber:12": nil,
- "ByNumber:4": M{
- "Cardinality": pref.Repeated,
- "IsMap": true,
- "Default": nil,
- "MessageType": M{"FullName": pref.FullName("test.A"), "IsPlaceholder": false},
- },
- "ByNumber:5": M{
- "Cardinality": pref.Repeated,
- "Kind": pref.Int32Kind,
- "IsPacked": true,
- "Default": int32(0),
- },
- "ByNumber:6": M{
- "Cardinality": pref.Required,
- "Default": []byte(nil),
- "OneofType": nil,
- },
- },
- "Oneofs": M{
- "Len": 2,
- "ByName:O0": nil,
- "ByName:O1": M{
- "FullName": pref.FullName("test.B.O1"),
- "Index": 0,
- "Options": &descriptorpb.OneofOptions{
- UninterpretedOption: []*descriptorpb.UninterpretedOption{
- {StringValue: []byte("option")},
- },
- },
- "Fields": M{
- "Len": 1,
- "Get:0": M{"FullName": pref.FullName("test.B.field_one")},
- },
- },
- "Get:1": M{
- "FullName": pref.FullName("test.B.O2"),
- "Index": 1,
- "Fields": M{
- "Len": 2,
- "ByName:field_two": M{"Name": pref.Name("field_two")},
- "Get:1": M{"Name": pref.Name("field_three")},
- },
- },
- },
- "ReservedNames": M{
- "Len": 2,
- "Get:0": pref.Name("fizz"),
- "Has:buzz": true,
- "Has:noexist": false,
- },
- "ReservedRanges": M{
- "Len": 2,
- "Get:0": [2]pref.FieldNumber{100, 200},
- "Has:99": false,
- "Has:100": true,
- "Has:150": true,
- "Has:199": true,
- "Has:200": false,
- "Has:300": true,
- "Has:301": false,
- },
- "RequiredNumbers": M{
- "Len": 1,
- "Get:0": pref.FieldNumber(6),
- "Has:1": false,
- "Has:6": true,
- },
- "ExtensionRanges": M{
- "Len": 2,
- "Get:0": [2]pref.FieldNumber{1000, 2000},
- "Has:999": false,
- "Has:1000": true,
- "Has:1500": true,
- "Has:1999": true,
- "Has:2000": false,
- "Has:3000": true,
- "Has:3001": false,
- },
- "ExtensionRangeOptions:0": (*descriptorpb.ExtensionRangeOptions)(nil),
- "ExtensionRangeOptions:1": new(descriptorpb.ExtensionRangeOptions),
- },
- "Get:2": M{
- "Name": pref.Name("C"),
- "Index": 2,
- "Messages": M{
- "Len": 1,
- "Get:0": M{"FullName": pref.FullName("test.C.A")},
- },
- "Enums": M{
- "Len": 1,
- "Get:0": M{"FullName": pref.FullName("test.C.E1")},
- },
- "Extensions": M{
- "Len": 1,
- "Get:0": M{"FullName": pref.FullName("test.C.X")},
- },
- },
- },
- "Enums": M{
- "Len": 1,
- "Get:0": M{
- "Name": pref.Name("E1"),
- "Options": &descriptorpb.EnumOptions{Deprecated: scalar.Bool(true)},
- "Values": M{
- "Len": 2,
- "ByName:Foo": nil,
- "ByName:FOO": M{
- "FullName": pref.FullName("test.FOO"),
- "Options": &descriptorpb.EnumValueOptions{Deprecated: scalar.Bool(true)},
- },
- "ByNumber:2": nil,
- "ByNumber:1": M{"FullName": pref.FullName("test.BAR")},
- },
- "ReservedNames": M{
- "Len": 2,
- "Get:0": pref.Name("FIZZ"),
- "Has:BUZZ": true,
- "Has:NOEXIST": false,
- },
- "ReservedRanges": M{
- "Len": 2,
- "Get:0": [2]pref.EnumNumber{10, 19},
- "Has:9": false,
- "Has:10": true,
- "Has:15": true,
- "Has:19": true,
- "Has:20": false,
- "Has:30": true,
- "Has:31": false,
- },
- },
- },
- "Extensions": M{
- "Len": 1,
- "ByName:X": M{
- "Name": pref.Name("X"),
- "Number": pref.FieldNumber(1000),
- "Cardinality": pref.Repeated,
- "Kind": pref.MessageKind,
- "IsPacked": false,
- "MessageType": M{"FullName": pref.FullName("test.C"), "IsPlaceholder": false},
- "ExtendedType": M{"FullName": pref.FullName("test.B"), "IsPlaceholder": false},
- "Options": &descriptorpb.FieldOptions{Packed: scalar.Bool(true)},
- },
- },
- "Services": M{
- "Len": 1,
- "ByName:s": nil,
- "ByName:S": M{
- "Parent": M{"FullName": pref.FullName("test")},
- "Name": pref.Name("S"),
- "FullName": pref.FullName("test.S"),
- "Options": &descriptorpb.ServiceOptions{Deprecated: scalar.Bool(true)},
- "Methods": M{
- "Len": 1,
- "Get:0": M{
- "Parent": M{"FullName": pref.FullName("test.S")},
- "Name": pref.Name("M"),
- "FullName": pref.FullName("test.S.M"),
- "InputType": M{"FullName": pref.FullName("test.A"), "IsPlaceholder": false},
- "OutputType": M{"FullName": pref.FullName("test.C.A"), "IsPlaceholder": false},
- "IsStreamingClient": true,
- "IsStreamingServer": true,
- "Options": &descriptorpb.MethodOptions{Deprecated: scalar.Bool(true)},
- },
- },
- },
- },
- "DescriptorByName:": nil,
- "DescriptorByName:A": nil,
- "DescriptorByName:test": nil,
- "DescriptorByName:test.": nil,
- "DescriptorByName:test.A": M{"FullName": pref.FullName("test.A")},
- "DescriptorByName:test.A.key": M{"FullName": pref.FullName("test.A.key")},
- "DescriptorByName:test.A.A": nil,
- "DescriptorByName:test.A.field_one": nil,
- "DescriptorByName:test.B.field_one": M{"FullName": pref.FullName("test.B.field_one")},
- "DescriptorByName:test.B.O1": M{"FullName": pref.FullName("test.B.O1")},
- "DescriptorByName:test.B.O3": nil,
- "DescriptorByName:test.C.E1": M{"FullName": pref.FullName("test.C.E1")},
- "DescriptorByName:test.C.E1.FOO": nil,
- "DescriptorByName:test.C.FOO": M{"FullName": pref.FullName("test.C.FOO")},
- "DescriptorByName:test.C.Foo": nil,
- "DescriptorByName:test.C.BAZ": nil,
- "DescriptorByName:test.E1": M{"FullName": pref.FullName("test.E1")},
- "DescriptorByName:test.E1.FOO": nil,
- "DescriptorByName:test.FOO": M{"FullName": pref.FullName("test.FOO")},
- "DescriptorByName:test.Foo": nil,
- "DescriptorByName:test.BAZ": nil,
- "DescriptorByName:test.C.X": M{"FullName": pref.FullName("test.C.X")},
- "DescriptorByName:test.X": M{"FullName": pref.FullName("test.X")},
- "DescriptorByName:test.X.": nil,
- "DescriptorByName:test.S": M{"FullName": pref.FullName("test.S")},
- "DescriptorByName:test.S.M": M{"FullName": pref.FullName("test.S.M")},
- "DescriptorByName:test.M": nil,
- }
- checkAccessors(t, "", reflect.ValueOf(fd), want)
-}
-func checkAccessors(t *testing.T, p string, rv reflect.Value, want map[string]interface{}) {
- p0 := p
- defer func() {
- if ex := recover(); ex != nil {
- t.Errorf("panic at %v: %v", p, ex)
- }
- }()
-
- if rv.Interface() == nil {
- t.Errorf("%v is nil, want non-nil", p)
- return
- }
- for s, v := range want {
- // Call the accessor method.
- p = p0 + "." + s
- var rets []reflect.Value
- if i := strings.IndexByte(s, ':'); i >= 0 {
- // Accessor method takes in a single argument, which is encoded
- // after the accessor name, separated by a ':' delimiter.
- fnc := rv.MethodByName(s[:i])
- arg := reflect.New(fnc.Type().In(0)).Elem()
- s = s[i+len(":"):]
- switch arg.Kind() {
- case reflect.String:
- arg.SetString(s)
- case reflect.Int32, reflect.Int:
- n, _ := strconv.ParseInt(s, 0, 64)
- arg.SetInt(n)
- }
- rets = fnc.Call([]reflect.Value{arg})
- } else {
- rets = rv.MethodByName(s).Call(nil)
- }
-
- // Check that (val, ok) pattern is internally consistent.
- if len(rets) == 2 {
- if rets[0].IsNil() && rets[1].Bool() {
- t.Errorf("%v = (nil, true), want (nil, false)", p)
- }
- if !rets[0].IsNil() && !rets[1].Bool() {
- t.Errorf("%v = (non-nil, false), want (non-nil, true)", p)
- }
- }
-
- // Check that the accessor output matches.
- if want, ok := v.(map[string]interface{}); ok {
- checkAccessors(t, p, rets[0], want)
- continue
- }
-
- got := rets[0].Interface()
- if pv, ok := got.(pref.Value); ok {
- got = pv.Interface()
- }
-
- // Compare with proto.Equal if possible.
- gotMsg, gotMsgOK := got.(protoV1.Message)
- wantMsg, wantMsgOK := v.(protoV1.Message)
- if gotMsgOK && wantMsgOK {
- if !protoV1.Equal(gotMsg, wantMsg) {
- t.Errorf("%v = %v, want %v", p, got, want)
- }
- continue
- }
-
- if want := v; !reflect.DeepEqual(got, want) {
- t.Errorf("%v = %T(%v), want %T(%v)", p, got, got, want, want)
- }
- }
-}
-
-func testFileFormat(t *testing.T, fd pref.FileDescriptor) {
- const want = `FileDescriptor{
- Syntax: proto2
- Path: "path/to/file.proto"
- Package: test
- Messages: [{
- Name: A
- IsMapEntry: true
- Fields: [{
- Name: key
- Number: 1
- Cardinality: optional
- Kind: string
- JSONName: "key"
- }, {
- Name: value
- Number: 2
- Cardinality: optional
- Kind: message
- JSONName: "value"
- MessageType: test.B
- }]
- }, {
- Name: B
- Fields: [{
- Name: field_one
- Number: 1
- Cardinality: optional
- Kind: string
- JSONName: "fieldOne"
- HasDefault: true
- Default: "hello, \"world!\"\n"
- OneofType: O1
- }, {
- Name: field_two
- Number: 2
- Cardinality: optional
- Kind: enum
- HasJSONName: true
- JSONName: "Field2"
- HasDefault: true
- Default: 1
- OneofType: O2
- EnumType: test.E1
- }, {
- Name: field_three
- Number: 3
- Cardinality: optional
- Kind: message
- JSONName: "fieldThree"
- OneofType: O2
- MessageType: test.C
- }, {
- Name: field_four
- Number: 4
- Cardinality: repeated
- Kind: message
- HasJSONName: true
- JSONName: "Field4"
- IsMap: true
- MessageType: test.A
- }, {
- Name: field_five
- Number: 5
- Cardinality: repeated
- Kind: int32
- JSONName: "fieldFive"
- IsPacked: true
- }, {
- Name: field_six
- Number: 6
- Cardinality: required
- Kind: bytes
- JSONName: "fieldSix"
- }]
- Oneofs: [{
- Name: O1
- Fields: [field_one]
- }, {
- Name: O2
- Fields: [field_two, field_three]
- }]
- ReservedNames: [fizz, buzz]
- ReservedRanges: [100:200, 300]
- RequiredNumbers: [6]
- ExtensionRanges: [1000:2000, 3000]
- }, {
- Name: C
- Messages: [{
- Name: A
- Fields: [{
- Name: F
- Number: 1
- Cardinality: required
- Kind: bytes
- JSONName: "F"
- HasDefault: true
- Default: "dead\xbe\xef"
- }]
- RequiredNumbers: [1]
- }]
- Enums: [{
- Name: E1
- Values: [
- {Name: FOO}
- {Name: BAR, Number: 1}
- ]
- }]
- Extensions: [{
- Name: X
- Number: 1000
- Cardinality: repeated
- Kind: message
- ExtendedType: test.B
- MessageType: test.C
- }]
- }]
- Enums: [{
- Name: E1
- Values: [
- {Name: FOO}
- {Name: BAR, Number: 1}
- ]
- ReservedNames: [FIZZ, BUZZ]
- ReservedRanges: [10:20, 30]
- }]
- Extensions: [{
- Name: X
- Number: 1000
- Cardinality: repeated
- Kind: message
- ExtendedType: test.B
- MessageType: test.C
- }]
- Services: [{
- Name: S
- Methods: [{
- Name: M
- InputType: test.A
- OutputType: test.C.A
- IsStreamingClient: true
- IsStreamingServer: true
- }]
- }]
-}`
- tests := []struct{ fmt, want string }{{"%v", compactMultiFormat(want)}, {"%+v", want}}
- for _, tt := range tests {
- got := fmt.Sprintf(tt.fmt, fd)
- if got != tt.want {
- t.Errorf("fmt.Sprintf(%q, fd):\ngot: %s\nwant: %s", tt.fmt, got, tt.want)
- }
- }
-}
-
-// compactMultiFormat returns the single line form of a multi line output.
-func compactMultiFormat(s string) string {
- var b []byte
- for _, s := range strings.Split(s, "\n") {
- s = strings.TrimSpace(s)
- s = regexp.MustCompile(": +").ReplaceAllString(s, ": ")
- prevWord := len(b) > 0 && b[len(b)-1] != '[' && b[len(b)-1] != '{'
- nextWord := len(s) > 0 && s[0] != ']' && s[0] != '}'
- if prevWord && nextWord {
- b = append(b, ", "...)
- }
- b = append(b, s...)
- }
- return string(b)
-}
diff --git a/reflect/prototype/validate.go b/reflect/prototype/validate.go
deleted file mode 100644
index b4f2ad3..0000000
--- a/reflect/prototype/validate.go
+++ /dev/null
@@ -1,46 +0,0 @@
-// 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 prototype
-
-import (
- pref "github.com/golang/protobuf/v2/reflect/protoreflect"
-)
-
-// TODO: This is important to prevent users from creating invalid types,
-// but is not functionality needed now.
-//
-// Things to verify:
-// * Weak fields are only used if flags.Proto1Legacy is set
-// * Weak fields can only reference singular messages
-// (check if this the case for oneof fields)
-// * FieldDescriptor.MessageType cannot reference a remote type when the
-// remote name is a type within the local file.
-// * Default enum identifiers resolve to a declared number.
-// * Default values are only allowed in proto2.
-// * Default strings are valid UTF-8? Note that protoc does not check this.
-// * Field extensions are only valid in proto2, except when extending the
-// descriptor options.
-// * Remote enum and message types are actually found in imported files.
-// * Placeholder messages and types may only be for weak fields.
-// * Placeholder full names must be valid.
-// * The name of each descriptor must be valid.
-// * Options are of the correct Go type (e.g. *descriptorpb.MessageOptions).
-// * len(ExtensionRangeOptions) <= len(ExtensionRanges)
-
-func validateFile(t pref.FileDescriptor) error {
- return nil
-}
-
-func validateMessage(t pref.MessageDescriptor) error {
- return nil
-}
-
-func validateExtension(t pref.ExtensionDescriptor) error {
- return nil
-}
-
-func validateEnum(t pref.EnumDescriptor) error {
- return nil
-}