chore: vendor

This commit is contained in:
2024-08-04 11:06:58 +02:00
parent 2a5985e44e
commit 04aec8232f
3557 changed files with 981078 additions and 1 deletions

View File

@ -0,0 +1,78 @@
// Copyright 2020 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 protoreflect
import (
"google.golang.org/protobuf/internal/pragma"
)
// The following types are used by the fast-path Message.ProtoMethods method.
//
// To avoid polluting the public protoreflect API with types used only by
// low-level implementations, the canonical definitions of these types are
// in the runtime/protoiface package. The definitions here and in protoiface
// must be kept in sync.
type (
methods = struct {
pragma.NoUnkeyedLiterals
Flags supportFlags
Size func(sizeInput) sizeOutput
Marshal func(marshalInput) (marshalOutput, error)
Unmarshal func(unmarshalInput) (unmarshalOutput, error)
Merge func(mergeInput) mergeOutput
CheckInitialized func(checkInitializedInput) (checkInitializedOutput, error)
}
supportFlags = uint64
sizeInput = struct {
pragma.NoUnkeyedLiterals
Message Message
Flags uint8
}
sizeOutput = struct {
pragma.NoUnkeyedLiterals
Size int
}
marshalInput = struct {
pragma.NoUnkeyedLiterals
Message Message
Buf []byte
Flags uint8
}
marshalOutput = struct {
pragma.NoUnkeyedLiterals
Buf []byte
}
unmarshalInput = struct {
pragma.NoUnkeyedLiterals
Message Message
Buf []byte
Flags uint8
Resolver interface {
FindExtensionByName(field FullName) (ExtensionType, error)
FindExtensionByNumber(message FullName, field FieldNumber) (ExtensionType, error)
}
Depth int
}
unmarshalOutput = struct {
pragma.NoUnkeyedLiterals
Flags uint8
}
mergeInput = struct {
pragma.NoUnkeyedLiterals
Source Message
Destination Message
}
mergeOutput = struct {
pragma.NoUnkeyedLiterals
Flags uint8
}
checkInitializedInput = struct {
pragma.NoUnkeyedLiterals
Message Message
}
checkInitializedOutput = struct {
pragma.NoUnkeyedLiterals
}
)

View File

@ -0,0 +1,513 @@
// 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 protoreflect provides interfaces to dynamically manipulate messages.
//
// This package includes type descriptors which describe the structure of types
// defined in proto source files and value interfaces which provide the
// ability to examine and manipulate the contents of messages.
//
// # Protocol Buffer Descriptors
//
// Protobuf descriptors (e.g., [EnumDescriptor] or [MessageDescriptor])
// are immutable objects that represent protobuf type information.
// They are wrappers around the messages declared in descriptor.proto.
// Protobuf descriptors alone lack any information regarding Go types.
//
// Enums and messages generated by this module implement [Enum] and [ProtoMessage],
// where the Descriptor and ProtoReflect.Descriptor accessors respectively
// return the protobuf descriptor for the values.
//
// The protobuf descriptor interfaces are not meant to be implemented by
// user code since they might need to be extended in the future to support
// additions to the protobuf language.
// The [google.golang.org/protobuf/reflect/protodesc] package converts between
// google.protobuf.DescriptorProto messages and protobuf descriptors.
//
// # Go Type Descriptors
//
// A type descriptor (e.g., [EnumType] or [MessageType]) is a constructor for
// a concrete Go type that represents the associated protobuf descriptor.
// There is commonly a one-to-one relationship between protobuf descriptors and
// Go type descriptors, but it can potentially be a one-to-many relationship.
//
// Enums and messages generated by this module implement [Enum] and [ProtoMessage],
// where the Type and ProtoReflect.Type accessors respectively
// return the protobuf descriptor for the values.
//
// The [google.golang.org/protobuf/types/dynamicpb] package can be used to
// create Go type descriptors from protobuf descriptors.
//
// # Value Interfaces
//
// The [Enum] and [Message] interfaces provide a reflective view over an
// enum or message instance. For enums, it provides the ability to retrieve
// the enum value number for any concrete enum type. For messages, it provides
// the ability to access or manipulate fields of the message.
//
// To convert a [google.golang.org/protobuf/proto.Message] to a [protoreflect.Message], use the
// former's ProtoReflect method. Since the ProtoReflect method is new to the
// v2 message interface, it may not be present on older message implementations.
// The [github.com/golang/protobuf/proto.MessageReflect] function can be used
// to obtain a reflective view on older messages.
//
// # Relationships
//
// The following diagrams demonstrate the relationships between
// various types declared in this package.
//
// ┌───────────────────────────────────┐
// V │
// ┌────────────── New(n) ─────────────┐ │
// │ │ │
// │ ┌──── Descriptor() ──┐ │ ┌── Number() ──┐ │
// │ │ V V │ V │
// ╔════════════╗ ╔════════════════╗ ╔════════╗ ╔════════════╗
// ║ EnumType ║ ║ EnumDescriptor ║ ║ Enum ║ ║ EnumNumber ║
// ╚════════════╝ ╚════════════════╝ ╚════════╝ ╚════════════╝
// Λ Λ │ │
// │ └─── Descriptor() ──┘ │
// │ │
// └────────────────── Type() ───────┘
//
// • An [EnumType] describes a concrete Go enum type.
// It has an EnumDescriptor and can construct an Enum instance.
//
// • An [EnumDescriptor] describes an abstract protobuf enum type.
//
// • An [Enum] is a concrete enum instance. Generated enums implement Enum.
//
// ┌──────────────── New() ─────────────────┐
// │ │
// │ ┌─── Descriptor() ─────┐ │ ┌── Interface() ───┐
// │ │ V V │ V
// ╔═════════════╗ ╔═══════════════════╗ ╔═════════╗ ╔══════════════╗
// ║ MessageType ║ ║ MessageDescriptor ║ ║ Message ║ ║ ProtoMessage ║
// ╚═════════════╝ ╚═══════════════════╝ ╚═════════╝ ╚══════════════╝
// Λ Λ │ │ Λ │
// │ └──── Descriptor() ────┘ │ └─ ProtoReflect() ─┘
// │ │
// └─────────────────── Type() ─────────┘
//
// • A [MessageType] describes a concrete Go message type.
// It has a [MessageDescriptor] and can construct a [Message] instance.
// Just as how Go's [reflect.Type] is a reflective description of a Go type,
// a [MessageType] is a reflective description of a Go type for a protobuf message.
//
// • A [MessageDescriptor] describes an abstract protobuf message type.
// It has no understanding of Go types. In order to construct a [MessageType]
// from just a [MessageDescriptor], you can consider looking up the message type
// in the global registry using the FindMessageByName method on
// [google.golang.org/protobuf/reflect/protoregistry.GlobalTypes]
// or constructing a dynamic [MessageType] using
// [google.golang.org/protobuf/types/dynamicpb.NewMessageType].
//
// • A [Message] is a reflective view over a concrete message instance.
// Generated messages implement [ProtoMessage], which can convert to a [Message].
// Just as how Go's [reflect.Value] is a reflective view over a Go value,
// a [Message] is a reflective view over a concrete protobuf message instance.
// Using Go reflection as an analogy, the [ProtoMessage.ProtoReflect] method is similar to
// calling [reflect.ValueOf], and the [Message.Interface] method is similar to
// calling [reflect.Value.Interface].
//
// ┌── TypeDescriptor() ──┐ ┌───── Descriptor() ─────┐
// │ V │ V
// ╔═══════════════╗ ╔═════════════════════════╗ ╔═════════════════════╗
// ║ ExtensionType ║ ║ ExtensionTypeDescriptor ║ ║ ExtensionDescriptor ║
// ╚═══════════════╝ ╚═════════════════════════╝ ╚═════════════════════╝
// Λ │ │ Λ │ Λ
// └─────── Type() ───────┘ │ └─── may implement ────┘ │
// │ │
// └────── implements ────────┘
//
// • An [ExtensionType] describes a concrete Go implementation of an extension.
// It has an [ExtensionTypeDescriptor] and can convert to/from
// an abstract [Value] and a Go value.
//
// • An [ExtensionTypeDescriptor] is an [ExtensionDescriptor]
// which also has an [ExtensionType].
//
// • An [ExtensionDescriptor] describes an abstract protobuf extension field and
// may not always be an [ExtensionTypeDescriptor].
package protoreflect
import (
"fmt"
"strings"
"google.golang.org/protobuf/encoding/protowire"
"google.golang.org/protobuf/internal/pragma"
)
type doNotImplement pragma.DoNotImplement
// ProtoMessage is the top-level interface that all proto messages implement.
// This is declared in the protoreflect package to avoid a cyclic dependency;
// use the [google.golang.org/protobuf/proto.Message] type instead, which aliases this type.
type ProtoMessage interface{ ProtoReflect() Message }
// Syntax is the language version of the proto file.
type Syntax syntax
type syntax int8 // keep exact type opaque as the int type may change
const (
Proto2 Syntax = 2
Proto3 Syntax = 3
Editions Syntax = 4
)
// IsValid reports whether the syntax is valid.
func (s Syntax) IsValid() bool {
switch s {
case Proto2, Proto3, Editions:
return true
default:
return false
}
}
// String returns s as a proto source identifier (e.g., "proto2").
func (s Syntax) String() string {
switch s {
case Proto2:
return "proto2"
case Proto3:
return "proto3"
case Editions:
return "editions"
default:
return fmt.Sprintf("<unknown:%d>", s)
}
}
// GoString returns s as a Go source identifier (e.g., "Proto2").
func (s Syntax) GoString() string {
switch s {
case Proto2:
return "Proto2"
case Proto3:
return "Proto3"
default:
return fmt.Sprintf("Syntax(%d)", s)
}
}
// Cardinality determines whether a field is optional, required, or repeated.
type Cardinality cardinality
type cardinality int8 // keep exact type opaque as the int type may change
// Constants as defined by the google.protobuf.Cardinality enumeration.
const (
Optional Cardinality = 1 // appears zero or one times
Required Cardinality = 2 // appears exactly one time; invalid with Proto3
Repeated Cardinality = 3 // appears zero or more times
)
// IsValid reports whether the cardinality is valid.
func (c Cardinality) IsValid() bool {
switch c {
case Optional, Required, Repeated:
return true
default:
return false
}
}
// String returns c as a proto source identifier (e.g., "optional").
func (c Cardinality) String() string {
switch c {
case Optional:
return "optional"
case Required:
return "required"
case Repeated:
return "repeated"
default:
return fmt.Sprintf("<unknown:%d>", c)
}
}
// GoString returns c as a Go source identifier (e.g., "Optional").
func (c Cardinality) GoString() string {
switch c {
case Optional:
return "Optional"
case Required:
return "Required"
case Repeated:
return "Repeated"
default:
return fmt.Sprintf("Cardinality(%d)", c)
}
}
// Kind indicates the basic proto kind of a field.
type Kind kind
type kind int8 // keep exact type opaque as the int type may change
// Constants as defined by the google.protobuf.Field.Kind enumeration.
const (
BoolKind Kind = 8
EnumKind Kind = 14
Int32Kind Kind = 5
Sint32Kind Kind = 17
Uint32Kind Kind = 13
Int64Kind Kind = 3
Sint64Kind Kind = 18
Uint64Kind Kind = 4
Sfixed32Kind Kind = 15
Fixed32Kind Kind = 7
FloatKind Kind = 2
Sfixed64Kind Kind = 16
Fixed64Kind Kind = 6
DoubleKind Kind = 1
StringKind Kind = 9
BytesKind Kind = 12
MessageKind Kind = 11
GroupKind Kind = 10
)
// IsValid reports whether the kind is valid.
func (k Kind) IsValid() bool {
switch k {
case BoolKind, EnumKind,
Int32Kind, Sint32Kind, Uint32Kind,
Int64Kind, Sint64Kind, Uint64Kind,
Sfixed32Kind, Fixed32Kind, FloatKind,
Sfixed64Kind, Fixed64Kind, DoubleKind,
StringKind, BytesKind, MessageKind, GroupKind:
return true
default:
return false
}
}
// String returns k as a proto source identifier (e.g., "bool").
func (k Kind) String() string {
switch k {
case BoolKind:
return "bool"
case EnumKind:
return "enum"
case Int32Kind:
return "int32"
case Sint32Kind:
return "sint32"
case Uint32Kind:
return "uint32"
case Int64Kind:
return "int64"
case Sint64Kind:
return "sint64"
case Uint64Kind:
return "uint64"
case Sfixed32Kind:
return "sfixed32"
case Fixed32Kind:
return "fixed32"
case FloatKind:
return "float"
case Sfixed64Kind:
return "sfixed64"
case Fixed64Kind:
return "fixed64"
case DoubleKind:
return "double"
case StringKind:
return "string"
case BytesKind:
return "bytes"
case MessageKind:
return "message"
case GroupKind:
return "group"
default:
return fmt.Sprintf("<unknown:%d>", k)
}
}
// GoString returns k as a Go source identifier (e.g., "BoolKind").
func (k Kind) GoString() string {
switch k {
case BoolKind:
return "BoolKind"
case EnumKind:
return "EnumKind"
case Int32Kind:
return "Int32Kind"
case Sint32Kind:
return "Sint32Kind"
case Uint32Kind:
return "Uint32Kind"
case Int64Kind:
return "Int64Kind"
case Sint64Kind:
return "Sint64Kind"
case Uint64Kind:
return "Uint64Kind"
case Sfixed32Kind:
return "Sfixed32Kind"
case Fixed32Kind:
return "Fixed32Kind"
case FloatKind:
return "FloatKind"
case Sfixed64Kind:
return "Sfixed64Kind"
case Fixed64Kind:
return "Fixed64Kind"
case DoubleKind:
return "DoubleKind"
case StringKind:
return "StringKind"
case BytesKind:
return "BytesKind"
case MessageKind:
return "MessageKind"
case GroupKind:
return "GroupKind"
default:
return fmt.Sprintf("Kind(%d)", k)
}
}
// FieldNumber is the field number in a message.
type FieldNumber = protowire.Number
// FieldNumbers represent a list of field numbers.
type FieldNumbers interface {
// Len reports the number of fields in the list.
Len() int
// Get returns the ith field number. It panics if out of bounds.
Get(i int) FieldNumber
// Has reports whether n is within the list of fields.
Has(n FieldNumber) bool
doNotImplement
}
// FieldRanges represent a list of field number ranges.
type FieldRanges interface {
// Len reports the number of ranges in the list.
Len() int
// Get returns the ith range. It panics if out of bounds.
Get(i int) [2]FieldNumber // start inclusive; end exclusive
// Has reports whether n is within any of the ranges.
Has(n FieldNumber) bool
doNotImplement
}
// EnumNumber is the numeric value for an enum.
type EnumNumber int32
// EnumRanges represent a list of enum number ranges.
type EnumRanges interface {
// Len reports the number of ranges in the list.
Len() int
// Get returns the ith range. It panics if out of bounds.
Get(i int) [2]EnumNumber // start inclusive; end inclusive
// Has reports whether n is within any of the ranges.
Has(n EnumNumber) bool
doNotImplement
}
// Name is the short name for a proto declaration. This is not the name
// as used in Go source code, which might not be identical to the proto name.
type Name string // e.g., "Kind"
// IsValid reports whether s is a syntactically valid name.
// An empty name is invalid.
func (s Name) IsValid() bool {
return consumeIdent(string(s)) == len(s)
}
// Names represent a list of names.
type Names interface {
// Len reports the number of names in the list.
Len() int
// Get returns the ith name. It panics if out of bounds.
Get(i int) Name
// Has reports whether s matches any names in the list.
Has(s Name) bool
doNotImplement
}
// FullName is a qualified name that uniquely identifies a proto declaration.
// A qualified name is the concatenation of the proto package along with the
// fully-declared name (i.e., name of parent preceding the name of the child),
// with a '.' delimiter placed between each [Name].
//
// This should not have any leading or trailing dots.
type FullName string // e.g., "google.protobuf.Field.Kind"
// IsValid reports whether s is a syntactically valid full name.
// An empty full name is invalid.
func (s FullName) IsValid() bool {
i := consumeIdent(string(s))
if i < 0 {
return false
}
for len(s) > i {
if s[i] != '.' {
return false
}
i++
n := consumeIdent(string(s[i:]))
if n < 0 {
return false
}
i += n
}
return true
}
func consumeIdent(s string) (i int) {
if len(s) == 0 || !isLetter(s[i]) {
return -1
}
i++
for len(s) > i && isLetterDigit(s[i]) {
i++
}
return i
}
func isLetter(c byte) bool {
return c == '_' || ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z')
}
func isLetterDigit(c byte) bool {
return isLetter(c) || ('0' <= c && c <= '9')
}
// Name returns the short name, which is the last identifier segment.
// A single segment FullName is the [Name] itself.
func (n FullName) Name() Name {
if i := strings.LastIndexByte(string(n), '.'); i >= 0 {
return Name(n[i+1:])
}
return Name(n)
}
// Parent returns the full name with the trailing identifier removed.
// A single segment FullName has no parent.
func (n FullName) Parent() FullName {
if i := strings.LastIndexByte(string(n), '.'); i >= 0 {
return n[:i]
}
return ""
}
// Append returns the qualified name appended with the provided short name.
//
// Invariant: n == n.Parent().Append(n.Name()) // assuming n is valid
func (n FullName) Append(s Name) FullName {
if n == "" {
return FullName(s)
}
return n + "." + FullName(s)
}

View File

@ -0,0 +1,129 @@
// Copyright 2019 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 protoreflect
import (
"strconv"
)
// SourceLocations is a list of source locations.
type SourceLocations interface {
// Len reports the number of source locations in the proto file.
Len() int
// Get returns the ith SourceLocation. It panics if out of bounds.
Get(int) SourceLocation
// ByPath returns the SourceLocation for the given path,
// returning the first location if multiple exist for the same path.
// If multiple locations exist for the same path,
// then SourceLocation.Next index can be used to identify the
// index of the next SourceLocation.
// If no location exists for this path, it returns the zero value.
ByPath(path SourcePath) SourceLocation
// ByDescriptor returns the SourceLocation for the given descriptor,
// returning the first location if multiple exist for the same path.
// If no location exists for this descriptor, it returns the zero value.
ByDescriptor(desc Descriptor) SourceLocation
doNotImplement
}
// SourceLocation describes a source location and
// corresponds with the google.protobuf.SourceCodeInfo.Location message.
type SourceLocation struct {
// Path is the path to the declaration from the root file descriptor.
// The contents of this slice must not be mutated.
Path SourcePath
// StartLine and StartColumn are the zero-indexed starting location
// in the source file for the declaration.
StartLine, StartColumn int
// EndLine and EndColumn are the zero-indexed ending location
// in the source file for the declaration.
// In the descriptor.proto, the end line may be omitted if it is identical
// to the start line. Here, it is always populated.
EndLine, EndColumn int
// LeadingDetachedComments are the leading detached comments
// for the declaration. The contents of this slice must not be mutated.
LeadingDetachedComments []string
// LeadingComments is the leading attached comment for the declaration.
LeadingComments string
// TrailingComments is the trailing attached comment for the declaration.
TrailingComments string
// Next is an index into SourceLocations for the next source location that
// has the same Path. It is zero if there is no next location.
Next int
}
// SourcePath identifies part of a file descriptor for a source location.
// The SourcePath is a sequence of either field numbers or indexes into
// a repeated field that form a path starting from the root file descriptor.
//
// See google.protobuf.SourceCodeInfo.Location.path.
type SourcePath []int32
// Equal reports whether p1 equals p2.
func (p1 SourcePath) Equal(p2 SourcePath) bool {
if len(p1) != len(p2) {
return false
}
for i := range p1 {
if p1[i] != p2[i] {
return false
}
}
return true
}
// String formats the path in a humanly readable manner.
// The output is guaranteed to be deterministic,
// making it suitable for use as a key into a Go map.
// It is not guaranteed to be stable as the exact output could change
// in a future version of this module.
//
// Example output:
//
// .message_type[6].nested_type[15].field[3]
func (p SourcePath) String() string {
b := p.appendFileDescriptorProto(nil)
for _, i := range p {
b = append(b, '.')
b = strconv.AppendInt(b, int64(i), 10)
}
return string(b)
}
type appendFunc func(*SourcePath, []byte) []byte
func (p *SourcePath) appendSingularField(b []byte, name string, f appendFunc) []byte {
if len(*p) == 0 {
return b
}
b = append(b, '.')
b = append(b, name...)
*p = (*p)[1:]
if f != nil {
b = f(p, b)
}
return b
}
func (p *SourcePath) appendRepeatedField(b []byte, name string, f appendFunc) []byte {
b = p.appendSingularField(b, name, nil)
if len(*p) == 0 || (*p)[0] < 0 {
return b
}
b = append(b, '[')
b = strconv.AppendUint(b, uint64((*p)[0]), 10)
b = append(b, ']')
*p = (*p)[1:]
if f != nil {
b = f(p, b)
}
return b
}

View File

@ -0,0 +1,573 @@
// Copyright 2019 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-protos. DO NOT EDIT.
package protoreflect
func (p *SourcePath) appendFileDescriptorProto(b []byte) []byte {
if len(*p) == 0 {
return b
}
switch (*p)[0] {
case 1:
b = p.appendSingularField(b, "name", nil)
case 2:
b = p.appendSingularField(b, "package", nil)
case 3:
b = p.appendRepeatedField(b, "dependency", nil)
case 10:
b = p.appendRepeatedField(b, "public_dependency", nil)
case 11:
b = p.appendRepeatedField(b, "weak_dependency", nil)
case 4:
b = p.appendRepeatedField(b, "message_type", (*SourcePath).appendDescriptorProto)
case 5:
b = p.appendRepeatedField(b, "enum_type", (*SourcePath).appendEnumDescriptorProto)
case 6:
b = p.appendRepeatedField(b, "service", (*SourcePath).appendServiceDescriptorProto)
case 7:
b = p.appendRepeatedField(b, "extension", (*SourcePath).appendFieldDescriptorProto)
case 8:
b = p.appendSingularField(b, "options", (*SourcePath).appendFileOptions)
case 9:
b = p.appendSingularField(b, "source_code_info", (*SourcePath).appendSourceCodeInfo)
case 12:
b = p.appendSingularField(b, "syntax", nil)
case 14:
b = p.appendSingularField(b, "edition", nil)
}
return b
}
func (p *SourcePath) appendDescriptorProto(b []byte) []byte {
if len(*p) == 0 {
return b
}
switch (*p)[0] {
case 1:
b = p.appendSingularField(b, "name", nil)
case 2:
b = p.appendRepeatedField(b, "field", (*SourcePath).appendFieldDescriptorProto)
case 6:
b = p.appendRepeatedField(b, "extension", (*SourcePath).appendFieldDescriptorProto)
case 3:
b = p.appendRepeatedField(b, "nested_type", (*SourcePath).appendDescriptorProto)
case 4:
b = p.appendRepeatedField(b, "enum_type", (*SourcePath).appendEnumDescriptorProto)
case 5:
b = p.appendRepeatedField(b, "extension_range", (*SourcePath).appendDescriptorProto_ExtensionRange)
case 8:
b = p.appendRepeatedField(b, "oneof_decl", (*SourcePath).appendOneofDescriptorProto)
case 7:
b = p.appendSingularField(b, "options", (*SourcePath).appendMessageOptions)
case 9:
b = p.appendRepeatedField(b, "reserved_range", (*SourcePath).appendDescriptorProto_ReservedRange)
case 10:
b = p.appendRepeatedField(b, "reserved_name", nil)
}
return b
}
func (p *SourcePath) appendEnumDescriptorProto(b []byte) []byte {
if len(*p) == 0 {
return b
}
switch (*p)[0] {
case 1:
b = p.appendSingularField(b, "name", nil)
case 2:
b = p.appendRepeatedField(b, "value", (*SourcePath).appendEnumValueDescriptorProto)
case 3:
b = p.appendSingularField(b, "options", (*SourcePath).appendEnumOptions)
case 4:
b = p.appendRepeatedField(b, "reserved_range", (*SourcePath).appendEnumDescriptorProto_EnumReservedRange)
case 5:
b = p.appendRepeatedField(b, "reserved_name", nil)
}
return b
}
func (p *SourcePath) appendServiceDescriptorProto(b []byte) []byte {
if len(*p) == 0 {
return b
}
switch (*p)[0] {
case 1:
b = p.appendSingularField(b, "name", nil)
case 2:
b = p.appendRepeatedField(b, "method", (*SourcePath).appendMethodDescriptorProto)
case 3:
b = p.appendSingularField(b, "options", (*SourcePath).appendServiceOptions)
}
return b
}
func (p *SourcePath) appendFieldDescriptorProto(b []byte) []byte {
if len(*p) == 0 {
return b
}
switch (*p)[0] {
case 1:
b = p.appendSingularField(b, "name", nil)
case 3:
b = p.appendSingularField(b, "number", nil)
case 4:
b = p.appendSingularField(b, "label", nil)
case 5:
b = p.appendSingularField(b, "type", nil)
case 6:
b = p.appendSingularField(b, "type_name", nil)
case 2:
b = p.appendSingularField(b, "extendee", nil)
case 7:
b = p.appendSingularField(b, "default_value", nil)
case 9:
b = p.appendSingularField(b, "oneof_index", nil)
case 10:
b = p.appendSingularField(b, "json_name", nil)
case 8:
b = p.appendSingularField(b, "options", (*SourcePath).appendFieldOptions)
case 17:
b = p.appendSingularField(b, "proto3_optional", nil)
}
return b
}
func (p *SourcePath) appendFileOptions(b []byte) []byte {
if len(*p) == 0 {
return b
}
switch (*p)[0] {
case 1:
b = p.appendSingularField(b, "java_package", nil)
case 8:
b = p.appendSingularField(b, "java_outer_classname", nil)
case 10:
b = p.appendSingularField(b, "java_multiple_files", nil)
case 20:
b = p.appendSingularField(b, "java_generate_equals_and_hash", nil)
case 27:
b = p.appendSingularField(b, "java_string_check_utf8", nil)
case 9:
b = p.appendSingularField(b, "optimize_for", nil)
case 11:
b = p.appendSingularField(b, "go_package", nil)
case 16:
b = p.appendSingularField(b, "cc_generic_services", nil)
case 17:
b = p.appendSingularField(b, "java_generic_services", nil)
case 18:
b = p.appendSingularField(b, "py_generic_services", nil)
case 23:
b = p.appendSingularField(b, "deprecated", nil)
case 31:
b = p.appendSingularField(b, "cc_enable_arenas", nil)
case 36:
b = p.appendSingularField(b, "objc_class_prefix", nil)
case 37:
b = p.appendSingularField(b, "csharp_namespace", nil)
case 39:
b = p.appendSingularField(b, "swift_prefix", nil)
case 40:
b = p.appendSingularField(b, "php_class_prefix", nil)
case 41:
b = p.appendSingularField(b, "php_namespace", nil)
case 44:
b = p.appendSingularField(b, "php_metadata_namespace", nil)
case 45:
b = p.appendSingularField(b, "ruby_package", nil)
case 50:
b = p.appendSingularField(b, "features", (*SourcePath).appendFeatureSet)
case 999:
b = p.appendRepeatedField(b, "uninterpreted_option", (*SourcePath).appendUninterpretedOption)
}
return b
}
func (p *SourcePath) appendSourceCodeInfo(b []byte) []byte {
if len(*p) == 0 {
return b
}
switch (*p)[0] {
case 1:
b = p.appendRepeatedField(b, "location", (*SourcePath).appendSourceCodeInfo_Location)
}
return b
}
func (p *SourcePath) appendDescriptorProto_ExtensionRange(b []byte) []byte {
if len(*p) == 0 {
return b
}
switch (*p)[0] {
case 1:
b = p.appendSingularField(b, "start", nil)
case 2:
b = p.appendSingularField(b, "end", nil)
case 3:
b = p.appendSingularField(b, "options", (*SourcePath).appendExtensionRangeOptions)
}
return b
}
func (p *SourcePath) appendOneofDescriptorProto(b []byte) []byte {
if len(*p) == 0 {
return b
}
switch (*p)[0] {
case 1:
b = p.appendSingularField(b, "name", nil)
case 2:
b = p.appendSingularField(b, "options", (*SourcePath).appendOneofOptions)
}
return b
}
func (p *SourcePath) appendMessageOptions(b []byte) []byte {
if len(*p) == 0 {
return b
}
switch (*p)[0] {
case 1:
b = p.appendSingularField(b, "message_set_wire_format", nil)
case 2:
b = p.appendSingularField(b, "no_standard_descriptor_accessor", nil)
case 3:
b = p.appendSingularField(b, "deprecated", nil)
case 7:
b = p.appendSingularField(b, "map_entry", nil)
case 11:
b = p.appendSingularField(b, "deprecated_legacy_json_field_conflicts", nil)
case 12:
b = p.appendSingularField(b, "features", (*SourcePath).appendFeatureSet)
case 999:
b = p.appendRepeatedField(b, "uninterpreted_option", (*SourcePath).appendUninterpretedOption)
}
return b
}
func (p *SourcePath) appendDescriptorProto_ReservedRange(b []byte) []byte {
if len(*p) == 0 {
return b
}
switch (*p)[0] {
case 1:
b = p.appendSingularField(b, "start", nil)
case 2:
b = p.appendSingularField(b, "end", nil)
}
return b
}
func (p *SourcePath) appendEnumValueDescriptorProto(b []byte) []byte {
if len(*p) == 0 {
return b
}
switch (*p)[0] {
case 1:
b = p.appendSingularField(b, "name", nil)
case 2:
b = p.appendSingularField(b, "number", nil)
case 3:
b = p.appendSingularField(b, "options", (*SourcePath).appendEnumValueOptions)
}
return b
}
func (p *SourcePath) appendEnumOptions(b []byte) []byte {
if len(*p) == 0 {
return b
}
switch (*p)[0] {
case 2:
b = p.appendSingularField(b, "allow_alias", nil)
case 3:
b = p.appendSingularField(b, "deprecated", nil)
case 6:
b = p.appendSingularField(b, "deprecated_legacy_json_field_conflicts", nil)
case 7:
b = p.appendSingularField(b, "features", (*SourcePath).appendFeatureSet)
case 999:
b = p.appendRepeatedField(b, "uninterpreted_option", (*SourcePath).appendUninterpretedOption)
}
return b
}
func (p *SourcePath) appendEnumDescriptorProto_EnumReservedRange(b []byte) []byte {
if len(*p) == 0 {
return b
}
switch (*p)[0] {
case 1:
b = p.appendSingularField(b, "start", nil)
case 2:
b = p.appendSingularField(b, "end", nil)
}
return b
}
func (p *SourcePath) appendMethodDescriptorProto(b []byte) []byte {
if len(*p) == 0 {
return b
}
switch (*p)[0] {
case 1:
b = p.appendSingularField(b, "name", nil)
case 2:
b = p.appendSingularField(b, "input_type", nil)
case 3:
b = p.appendSingularField(b, "output_type", nil)
case 4:
b = p.appendSingularField(b, "options", (*SourcePath).appendMethodOptions)
case 5:
b = p.appendSingularField(b, "client_streaming", nil)
case 6:
b = p.appendSingularField(b, "server_streaming", nil)
}
return b
}
func (p *SourcePath) appendServiceOptions(b []byte) []byte {
if len(*p) == 0 {
return b
}
switch (*p)[0] {
case 34:
b = p.appendSingularField(b, "features", (*SourcePath).appendFeatureSet)
case 33:
b = p.appendSingularField(b, "deprecated", nil)
case 999:
b = p.appendRepeatedField(b, "uninterpreted_option", (*SourcePath).appendUninterpretedOption)
}
return b
}
func (p *SourcePath) appendFieldOptions(b []byte) []byte {
if len(*p) == 0 {
return b
}
switch (*p)[0] {
case 1:
b = p.appendSingularField(b, "ctype", nil)
case 2:
b = p.appendSingularField(b, "packed", nil)
case 6:
b = p.appendSingularField(b, "jstype", nil)
case 5:
b = p.appendSingularField(b, "lazy", nil)
case 15:
b = p.appendSingularField(b, "unverified_lazy", nil)
case 3:
b = p.appendSingularField(b, "deprecated", nil)
case 10:
b = p.appendSingularField(b, "weak", nil)
case 16:
b = p.appendSingularField(b, "debug_redact", nil)
case 17:
b = p.appendSingularField(b, "retention", nil)
case 19:
b = p.appendRepeatedField(b, "targets", nil)
case 20:
b = p.appendRepeatedField(b, "edition_defaults", (*SourcePath).appendFieldOptions_EditionDefault)
case 21:
b = p.appendSingularField(b, "features", (*SourcePath).appendFeatureSet)
case 22:
b = p.appendSingularField(b, "feature_support", (*SourcePath).appendFieldOptions_FeatureSupport)
case 999:
b = p.appendRepeatedField(b, "uninterpreted_option", (*SourcePath).appendUninterpretedOption)
}
return b
}
func (p *SourcePath) appendFeatureSet(b []byte) []byte {
if len(*p) == 0 {
return b
}
switch (*p)[0] {
case 1:
b = p.appendSingularField(b, "field_presence", nil)
case 2:
b = p.appendSingularField(b, "enum_type", nil)
case 3:
b = p.appendSingularField(b, "repeated_field_encoding", nil)
case 4:
b = p.appendSingularField(b, "utf8_validation", nil)
case 5:
b = p.appendSingularField(b, "message_encoding", nil)
case 6:
b = p.appendSingularField(b, "json_format", nil)
}
return b
}
func (p *SourcePath) appendUninterpretedOption(b []byte) []byte {
if len(*p) == 0 {
return b
}
switch (*p)[0] {
case 2:
b = p.appendRepeatedField(b, "name", (*SourcePath).appendUninterpretedOption_NamePart)
case 3:
b = p.appendSingularField(b, "identifier_value", nil)
case 4:
b = p.appendSingularField(b, "positive_int_value", nil)
case 5:
b = p.appendSingularField(b, "negative_int_value", nil)
case 6:
b = p.appendSingularField(b, "double_value", nil)
case 7:
b = p.appendSingularField(b, "string_value", nil)
case 8:
b = p.appendSingularField(b, "aggregate_value", nil)
}
return b
}
func (p *SourcePath) appendSourceCodeInfo_Location(b []byte) []byte {
if len(*p) == 0 {
return b
}
switch (*p)[0] {
case 1:
b = p.appendRepeatedField(b, "path", nil)
case 2:
b = p.appendRepeatedField(b, "span", nil)
case 3:
b = p.appendSingularField(b, "leading_comments", nil)
case 4:
b = p.appendSingularField(b, "trailing_comments", nil)
case 6:
b = p.appendRepeatedField(b, "leading_detached_comments", nil)
}
return b
}
func (p *SourcePath) appendExtensionRangeOptions(b []byte) []byte {
if len(*p) == 0 {
return b
}
switch (*p)[0] {
case 999:
b = p.appendRepeatedField(b, "uninterpreted_option", (*SourcePath).appendUninterpretedOption)
case 2:
b = p.appendRepeatedField(b, "declaration", (*SourcePath).appendExtensionRangeOptions_Declaration)
case 50:
b = p.appendSingularField(b, "features", (*SourcePath).appendFeatureSet)
case 3:
b = p.appendSingularField(b, "verification", nil)
}
return b
}
func (p *SourcePath) appendOneofOptions(b []byte) []byte {
if len(*p) == 0 {
return b
}
switch (*p)[0] {
case 1:
b = p.appendSingularField(b, "features", (*SourcePath).appendFeatureSet)
case 999:
b = p.appendRepeatedField(b, "uninterpreted_option", (*SourcePath).appendUninterpretedOption)
}
return b
}
func (p *SourcePath) appendEnumValueOptions(b []byte) []byte {
if len(*p) == 0 {
return b
}
switch (*p)[0] {
case 1:
b = p.appendSingularField(b, "deprecated", nil)
case 2:
b = p.appendSingularField(b, "features", (*SourcePath).appendFeatureSet)
case 3:
b = p.appendSingularField(b, "debug_redact", nil)
case 4:
b = p.appendSingularField(b, "feature_support", (*SourcePath).appendFieldOptions_FeatureSupport)
case 999:
b = p.appendRepeatedField(b, "uninterpreted_option", (*SourcePath).appendUninterpretedOption)
}
return b
}
func (p *SourcePath) appendMethodOptions(b []byte) []byte {
if len(*p) == 0 {
return b
}
switch (*p)[0] {
case 33:
b = p.appendSingularField(b, "deprecated", nil)
case 34:
b = p.appendSingularField(b, "idempotency_level", nil)
case 35:
b = p.appendSingularField(b, "features", (*SourcePath).appendFeatureSet)
case 999:
b = p.appendRepeatedField(b, "uninterpreted_option", (*SourcePath).appendUninterpretedOption)
}
return b
}
func (p *SourcePath) appendFieldOptions_EditionDefault(b []byte) []byte {
if len(*p) == 0 {
return b
}
switch (*p)[0] {
case 3:
b = p.appendSingularField(b, "edition", nil)
case 2:
b = p.appendSingularField(b, "value", nil)
}
return b
}
func (p *SourcePath) appendFieldOptions_FeatureSupport(b []byte) []byte {
if len(*p) == 0 {
return b
}
switch (*p)[0] {
case 1:
b = p.appendSingularField(b, "edition_introduced", nil)
case 2:
b = p.appendSingularField(b, "edition_deprecated", nil)
case 3:
b = p.appendSingularField(b, "deprecation_warning", nil)
case 4:
b = p.appendSingularField(b, "edition_removed", nil)
}
return b
}
func (p *SourcePath) appendUninterpretedOption_NamePart(b []byte) []byte {
if len(*p) == 0 {
return b
}
switch (*p)[0] {
case 1:
b = p.appendSingularField(b, "name_part", nil)
case 2:
b = p.appendSingularField(b, "is_extension", nil)
}
return b
}
func (p *SourcePath) appendExtensionRangeOptions_Declaration(b []byte) []byte {
if len(*p) == 0 {
return b
}
switch (*p)[0] {
case 1:
b = p.appendSingularField(b, "number", nil)
case 2:
b = p.appendSingularField(b, "full_name", nil)
case 3:
b = p.appendSingularField(b, "type", nil)
case 5:
b = p.appendSingularField(b, "reserved", nil)
case 6:
b = p.appendSingularField(b, "repeated", nil)
}
return b
}

View File

@ -0,0 +1,672 @@
// 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 protoreflect
// Descriptor provides a set of accessors that are common to every descriptor.
// Each descriptor type wraps the equivalent google.protobuf.XXXDescriptorProto,
// but provides efficient lookup and immutability.
//
// Each descriptor is comparable. Equality implies that the two types are
// exactly identical. However, it is possible for the same semantically
// identical proto type to be represented by multiple type descriptors.
//
// For example, suppose we have t1 and t2 which are both an [MessageDescriptor].
// If t1 == t2, then the types are definitely equal and all accessors return
// the same information. However, if t1 != t2, then it is still possible that
// they still represent the same proto type (e.g., t1.FullName == t2.FullName).
// This can occur if a descriptor type is created dynamically, or multiple
// versions of the same proto type are accidentally linked into the Go binary.
type Descriptor interface {
// ParentFile returns the parent file descriptor that this descriptor
// is declared within. The parent file for the file descriptor is itself.
//
// Support for this functionality is optional and may return nil.
ParentFile() FileDescriptor
// Parent returns the parent containing this descriptor declaration.
// The following shows the mapping from child type to possible parent types:
//
// ╔═════════════════════╤═══════════════════════════════════╗
// ║ Child type │ Possible parent types ║
// ╠═════════════════════╪═══════════════════════════════════╣
// ║ FileDescriptor │ nil ║
// ║ MessageDescriptor │ FileDescriptor, MessageDescriptor ║
// ║ FieldDescriptor │ FileDescriptor, MessageDescriptor ║
// ║ OneofDescriptor │ MessageDescriptor ║
// ║ EnumDescriptor │ FileDescriptor, MessageDescriptor ║
// ║ EnumValueDescriptor │ EnumDescriptor ║
// ║ ServiceDescriptor │ FileDescriptor ║
// ║ MethodDescriptor │ ServiceDescriptor ║
// ╚═════════════════════╧═══════════════════════════════════╝
//
// Support for this functionality is optional and may return nil.
Parent() Descriptor
// Index returns the index of this descriptor within its parent.
// It returns 0 if the descriptor does not have a parent or if the parent
// is unknown.
Index() int
// Syntax is the protobuf syntax.
Syntax() Syntax // e.g., Proto2 or Proto3
// Name is the short name of the declaration (i.e., FullName.Name).
Name() Name // e.g., "Any"
// FullName is the fully-qualified name of the declaration.
//
// The FullName is a concatenation of the full name of the type that this
// type is declared within and the declaration name. For example,
// field "foo_field" in message "proto.package.MyMessage" is
// uniquely identified as "proto.package.MyMessage.foo_field".
// Enum values are an exception to the rule (see EnumValueDescriptor).
FullName() FullName // e.g., "google.protobuf.Any"
// IsPlaceholder reports whether type information is missing since a
// dependency is not resolved, in which case only name information is known.
//
// Placeholder types may only be returned by the following accessors
// as a result of unresolved dependencies or weak imports:
//
// ╔═══════════════════════════════════╤═════════════════════╗
// ║ Accessor │ Descriptor ║
// ╠═══════════════════════════════════╪═════════════════════╣
// ║ FileImports.FileDescriptor │ FileDescriptor ║
// ║ FieldDescriptor.Enum │ EnumDescriptor ║
// ║ FieldDescriptor.Message │ MessageDescriptor ║
// ║ FieldDescriptor.DefaultEnumValue │ EnumValueDescriptor ║
// ║ FieldDescriptor.ContainingMessage │ MessageDescriptor ║
// ║ MethodDescriptor.Input │ MessageDescriptor ║
// ║ MethodDescriptor.Output │ MessageDescriptor ║
// ╚═══════════════════════════════════╧═════════════════════╝
//
// If true, only Name and FullName are valid.
// For FileDescriptor, the Path is also valid.
IsPlaceholder() bool
// Options returns the descriptor options. The caller must not modify
// the returned value.
//
// To avoid a dependency cycle, this function returns a proto.Message value.
// The proto message type returned for each descriptor type is as follows:
// ╔═════════════════════╤══════════════════════════════════════════╗
// ║ Go type │ Protobuf message type ║
// ╠═════════════════════╪══════════════════════════════════════════╣
// ║ FileDescriptor │ google.protobuf.FileOptions ║
// ║ EnumDescriptor │ google.protobuf.EnumOptions ║
// ║ EnumValueDescriptor │ google.protobuf.EnumValueOptions ║
// ║ MessageDescriptor │ google.protobuf.MessageOptions ║
// ║ FieldDescriptor │ google.protobuf.FieldOptions ║
// ║ OneofDescriptor │ google.protobuf.OneofOptions ║
// ║ ServiceDescriptor │ google.protobuf.ServiceOptions ║
// ║ MethodDescriptor │ google.protobuf.MethodOptions ║
// ╚═════════════════════╧══════════════════════════════════════════╝
//
// This method returns a typed nil-pointer if no options are present.
// The caller must import the descriptorpb package to use this.
Options() ProtoMessage
doNotImplement
}
// FileDescriptor describes the types in a complete proto file and
// corresponds with the google.protobuf.FileDescriptorProto message.
//
// Top-level declarations:
// [EnumDescriptor], [MessageDescriptor], [FieldDescriptor], and/or [ServiceDescriptor].
type FileDescriptor interface {
Descriptor // Descriptor.FullName is identical to Package
// Path returns the file name, relative to the source tree root.
Path() string // e.g., "path/to/file.proto"
// Package returns the protobuf package namespace.
Package() FullName // e.g., "google.protobuf"
// Imports is a list of imported proto files.
Imports() FileImports
// Enums is a list of the top-level enum declarations.
Enums() EnumDescriptors
// Messages is a list of the top-level message declarations.
Messages() MessageDescriptors
// Extensions is a list of the top-level extension declarations.
Extensions() ExtensionDescriptors
// Services is a list of the top-level service declarations.
Services() ServiceDescriptors
// SourceLocations is a list of source locations.
SourceLocations() SourceLocations
isFileDescriptor
}
type isFileDescriptor interface{ ProtoType(FileDescriptor) }
// FileImports is a list of file imports.
type FileImports interface {
// Len reports the number of files imported by this proto file.
Len() int
// Get returns the ith FileImport. It panics if out of bounds.
Get(i int) FileImport
doNotImplement
}
// FileImport is the declaration for a proto file import.
type FileImport struct {
// FileDescriptor is the file type for the given import.
// It is a placeholder descriptor if IsWeak is set or if a dependency has
// not been regenerated to implement the new reflection APIs.
FileDescriptor
// IsPublic reports whether this is a public import, which causes this file
// to alias declarations within the imported file. The intended use cases
// for this feature is the ability to move proto files without breaking
// existing dependencies.
//
// The current file and the imported file must be within proto package.
IsPublic bool
// IsWeak reports whether this is a weak import, which does not impose
// a direct dependency on the target file.
//
// Weak imports are a legacy proto1 feature. Equivalent behavior is
// achieved using proto2 extension fields or proto3 Any messages.
IsWeak bool
}
// MessageDescriptor describes a message and
// corresponds with the google.protobuf.DescriptorProto message.
//
// Nested declarations:
// [FieldDescriptor], [OneofDescriptor], [FieldDescriptor], [EnumDescriptor],
// and/or [MessageDescriptor].
type MessageDescriptor interface {
Descriptor
// IsMapEntry indicates that this is an auto-generated message type to
// represent the entry type for a map field.
//
// Map entry messages have only two fields:
// • a "key" field with a field number of 1
// • a "value" field with a field number of 2
// The key and value types are determined by these two fields.
//
// If IsMapEntry is true, it implies that FieldDescriptor.IsMap is true
// for some field with this message type.
IsMapEntry() bool
// Fields is a list of nested field declarations.
Fields() FieldDescriptors
// Oneofs is a list of nested oneof declarations.
Oneofs() OneofDescriptors
// ReservedNames is a list of reserved field names.
ReservedNames() Names
// ReservedRanges is a list of reserved ranges of field numbers.
ReservedRanges() FieldRanges
// RequiredNumbers is a list of required field numbers.
// In Proto3, it is always an empty list.
RequiredNumbers() FieldNumbers
// ExtensionRanges is the field ranges used for extension fields.
// In Proto3, it is always an empty ranges.
ExtensionRanges() FieldRanges
// ExtensionRangeOptions returns the ith extension range options.
//
// To avoid a dependency cycle, this method returns a proto.Message] value,
// which always contains a google.protobuf.ExtensionRangeOptions message.
// This method returns a typed nil-pointer if no options are present.
// The caller must import the descriptorpb package to use this.
ExtensionRangeOptions(i int) ProtoMessage
// Enums is a list of nested enum declarations.
Enums() EnumDescriptors
// Messages is a list of nested message declarations.
Messages() MessageDescriptors
// Extensions is a list of nested extension declarations.
Extensions() ExtensionDescriptors
isMessageDescriptor
}
type isMessageDescriptor interface{ ProtoType(MessageDescriptor) }
// MessageType encapsulates a [MessageDescriptor] with a concrete Go implementation.
// It is recommended that implementations of this interface also implement the
// [MessageFieldTypes] interface.
type MessageType interface {
// New returns a newly allocated empty message.
// It may return nil for synthetic messages representing a map entry.
New() Message
// Zero returns an empty, read-only message.
// It may return nil for synthetic messages representing a map entry.
Zero() Message
// Descriptor returns the message descriptor.
//
// Invariant: t.Descriptor() == t.New().Descriptor()
Descriptor() MessageDescriptor
}
// MessageFieldTypes extends a [MessageType] by providing type information
// regarding enums and messages referenced by the message fields.
type MessageFieldTypes interface {
MessageType
// Enum returns the EnumType for the ith field in MessageDescriptor.Fields.
// It returns nil if the ith field is not an enum kind.
// It panics if out of bounds.
//
// Invariant: mt.Enum(i).Descriptor() == mt.Descriptor().Fields(i).Enum()
Enum(i int) EnumType
// Message returns the MessageType for the ith field in MessageDescriptor.Fields.
// It returns nil if the ith field is not a message or group kind.
// It panics if out of bounds.
//
// Invariant: mt.Message(i).Descriptor() == mt.Descriptor().Fields(i).Message()
Message(i int) MessageType
}
// MessageDescriptors is a list of message declarations.
type MessageDescriptors interface {
// Len reports the number of messages.
Len() int
// Get returns the ith MessageDescriptor. It panics if out of bounds.
Get(i int) MessageDescriptor
// ByName returns the MessageDescriptor for a message named s.
// It returns nil if not found.
ByName(s Name) MessageDescriptor
doNotImplement
}
// FieldDescriptor describes a field within a message and
// corresponds with the google.protobuf.FieldDescriptorProto message.
//
// It is used for both normal fields defined within the parent message
// (e.g., [MessageDescriptor.Fields]) and fields that extend some remote message
// (e.g., [FileDescriptor.Extensions] or [MessageDescriptor.Extensions]).
type FieldDescriptor interface {
Descriptor
// Number reports the unique number for this field.
Number() FieldNumber
// Cardinality reports the cardinality for this field.
Cardinality() Cardinality
// Kind reports the basic kind for this field.
Kind() Kind
// HasJSONName reports whether this field has an explicitly set JSON name.
HasJSONName() bool
// JSONName reports the name used for JSON serialization.
// It is usually the camel-cased form of the field name.
// Extension fields are represented by the full name surrounded by brackets.
JSONName() string
// TextName reports the name used for text serialization.
// It is usually the name of the field, except that groups use the name
// of the inlined message, and extension fields are represented by the
// full name surrounded by brackets.
TextName() string
// HasPresence reports whether the field distinguishes between unpopulated
// and default values.
HasPresence() bool
// IsExtension reports whether this is an extension field. If false,
// then Parent and ContainingMessage refer to the same message.
// Otherwise, ContainingMessage and Parent likely differ.
IsExtension() bool
// HasOptionalKeyword reports whether the "optional" keyword was explicitly
// specified in the source .proto file.
HasOptionalKeyword() bool
// IsWeak reports whether this is a weak field, which does not impose a
// direct dependency on the target type.
// If true, then Message returns a placeholder type.
IsWeak() bool
// IsPacked reports whether repeated primitive numeric kinds should be
// serialized using a packed encoding.
// If true, then it implies Cardinality is Repeated.
IsPacked() bool
// IsList reports whether this field represents a list,
// where the value type for the associated field is a List.
// It is equivalent to checking whether Cardinality is Repeated and
// that IsMap reports false.
IsList() bool
// IsMap reports whether this field represents a map,
// where the value type for the associated field is a Map.
// It is equivalent to checking whether Cardinality is Repeated,
// that the Kind is MessageKind, and that MessageDescriptor.IsMapEntry reports true.
IsMap() bool
// MapKey returns the field descriptor for the key in the map entry.
// It returns nil if IsMap reports false.
MapKey() FieldDescriptor
// MapValue returns the field descriptor for the value in the map entry.
// It returns nil if IsMap reports false.
MapValue() FieldDescriptor
// HasDefault reports whether this field has a default value.
HasDefault() bool
// Default returns the default value for scalar fields.
// For proto2, it is the default value as specified in the proto file,
// or the zero value if unspecified.
// For proto3, it is always the zero value of the scalar.
// The Value type is determined by the Kind.
Default() Value
// DefaultEnumValue returns the enum value descriptor for the default value
// of an enum field, and is nil for any other kind of field.
DefaultEnumValue() EnumValueDescriptor
// ContainingOneof is the containing oneof that this field belongs to,
// and is nil if this field is not part of a oneof.
ContainingOneof() OneofDescriptor
// ContainingMessage is the containing message that this field belongs to.
// For extension fields, this may not necessarily be the parent message
// that the field is declared within.
ContainingMessage() MessageDescriptor
// Enum is the enum descriptor if Kind is EnumKind.
// It returns nil for any other Kind.
Enum() EnumDescriptor
// Message is the message descriptor if Kind is
// MessageKind or GroupKind. It returns nil for any other Kind.
Message() MessageDescriptor
isFieldDescriptor
}
type isFieldDescriptor interface{ ProtoType(FieldDescriptor) }
// FieldDescriptors is a list of field declarations.
type FieldDescriptors interface {
// Len reports the number of fields.
Len() int
// Get returns the ith FieldDescriptor. It panics if out of bounds.
Get(i int) FieldDescriptor
// ByName returns the FieldDescriptor for a field named s.
// It returns nil if not found.
ByName(s Name) FieldDescriptor
// ByJSONName returns the FieldDescriptor for a field with s as the JSON name.
// It returns nil if not found.
ByJSONName(s string) FieldDescriptor
// ByTextName returns the FieldDescriptor for a field with s as the text name.
// It returns nil if not found.
ByTextName(s string) FieldDescriptor
// ByNumber returns the FieldDescriptor for a field numbered n.
// It returns nil if not found.
ByNumber(n FieldNumber) FieldDescriptor
doNotImplement
}
// OneofDescriptor describes a oneof field set within a given message and
// corresponds with the google.protobuf.OneofDescriptorProto message.
type OneofDescriptor interface {
Descriptor
// IsSynthetic reports whether this is a synthetic oneof created to support
// proto3 optional semantics. If true, Fields contains exactly one field
// with FieldDescriptor.HasOptionalKeyword specified.
IsSynthetic() bool
// Fields is a list of fields belonging to this oneof.
Fields() FieldDescriptors
isOneofDescriptor
}
type isOneofDescriptor interface{ ProtoType(OneofDescriptor) }
// OneofDescriptors is a list of oneof declarations.
type OneofDescriptors interface {
// Len reports the number of oneof fields.
Len() int
// Get returns the ith OneofDescriptor. It panics if out of bounds.
Get(i int) OneofDescriptor
// ByName returns the OneofDescriptor for a oneof named s.
// It returns nil if not found.
ByName(s Name) OneofDescriptor
doNotImplement
}
// ExtensionDescriptor is an alias of [FieldDescriptor] for documentation.
type ExtensionDescriptor = FieldDescriptor
// ExtensionTypeDescriptor is an [ExtensionDescriptor] with an associated [ExtensionType].
type ExtensionTypeDescriptor interface {
ExtensionDescriptor
// Type returns the associated ExtensionType.
Type() ExtensionType
// Descriptor returns the plain ExtensionDescriptor without the
// associated ExtensionType.
Descriptor() ExtensionDescriptor
}
// ExtensionDescriptors is a list of field declarations.
type ExtensionDescriptors interface {
// Len reports the number of fields.
Len() int
// Get returns the ith ExtensionDescriptor. It panics if out of bounds.
Get(i int) ExtensionDescriptor
// ByName returns the ExtensionDescriptor for a field named s.
// It returns nil if not found.
ByName(s Name) ExtensionDescriptor
doNotImplement
}
// ExtensionType encapsulates an [ExtensionDescriptor] with a concrete
// Go implementation. The nested field descriptor must be for a extension field.
//
// While a normal field is a member of the parent message that it is declared
// within (see [Descriptor.Parent]), an extension field is a member of some other
// target message (see [FieldDescriptor.ContainingMessage]) and may have no
// relationship with the parent. However, the full name of an extension field is
// relative to the parent that it is declared within.
//
// For example:
//
// syntax = "proto2";
// package example;
// message FooMessage {
// extensions 100 to max;
// }
// message BarMessage {
// extends FooMessage { optional BarMessage bar_field = 100; }
// }
//
// Field "bar_field" is an extension of FooMessage, but its full name is
// "example.BarMessage.bar_field" instead of "example.FooMessage.bar_field".
type ExtensionType interface {
// New returns a new value for the field.
// For scalars, this returns the default value in native Go form.
New() Value
// Zero returns a new value for the field.
// For scalars, this returns the default value in native Go form.
// For composite types, this returns an empty, read-only message, list, or map.
Zero() Value
// TypeDescriptor returns the extension type descriptor.
TypeDescriptor() ExtensionTypeDescriptor
// ValueOf wraps the input and returns it as a Value.
// ValueOf panics if the input value is invalid or not the appropriate type.
//
// ValueOf is more extensive than protoreflect.ValueOf for a given field's
// value as it has more type information available.
ValueOf(any) Value
// InterfaceOf completely unwraps the Value to the underlying Go type.
// InterfaceOf panics if the input is nil or does not represent the
// appropriate underlying Go type. For composite types, it panics if the
// value is not mutable.
//
// InterfaceOf is able to unwrap the Value further than Value.Interface
// as it has more type information available.
InterfaceOf(Value) any
// IsValidValue reports whether the Value is valid to assign to the field.
IsValidValue(Value) bool
// IsValidInterface reports whether the input is valid to assign to the field.
IsValidInterface(any) bool
}
// EnumDescriptor describes an enum and
// corresponds with the google.protobuf.EnumDescriptorProto message.
//
// Nested declarations:
// [EnumValueDescriptor].
type EnumDescriptor interface {
Descriptor
// Values is a list of nested enum value declarations.
Values() EnumValueDescriptors
// ReservedNames is a list of reserved enum names.
ReservedNames() Names
// ReservedRanges is a list of reserved ranges of enum numbers.
ReservedRanges() EnumRanges
// IsClosed reports whether this enum uses closed semantics.
// See https://protobuf.dev/programming-guides/enum/#definitions.
// Note: the Go protobuf implementation is not spec compliant and treats
// all enums as open enums.
IsClosed() bool
isEnumDescriptor
}
type isEnumDescriptor interface{ ProtoType(EnumDescriptor) }
// EnumType encapsulates an [EnumDescriptor] with a concrete Go implementation.
type EnumType interface {
// New returns an instance of this enum type with its value set to n.
New(n EnumNumber) Enum
// Descriptor returns the enum descriptor.
//
// Invariant: t.Descriptor() == t.New(0).Descriptor()
Descriptor() EnumDescriptor
}
// EnumDescriptors is a list of enum declarations.
type EnumDescriptors interface {
// Len reports the number of enum types.
Len() int
// Get returns the ith EnumDescriptor. It panics if out of bounds.
Get(i int) EnumDescriptor
// ByName returns the EnumDescriptor for an enum named s.
// It returns nil if not found.
ByName(s Name) EnumDescriptor
doNotImplement
}
// EnumValueDescriptor describes an enum value and
// corresponds with the google.protobuf.EnumValueDescriptorProto message.
//
// All other proto declarations are in the namespace of the parent.
// However, enum values do not follow this rule and are within the namespace
// of the parent's parent (i.e., they are a sibling of the containing enum).
// Thus, a value named "FOO_VALUE" declared within an enum uniquely identified
// as "proto.package.MyEnum" has a full name of "proto.package.FOO_VALUE".
type EnumValueDescriptor interface {
Descriptor
// Number returns the enum value as an integer.
Number() EnumNumber
isEnumValueDescriptor
}
type isEnumValueDescriptor interface{ ProtoType(EnumValueDescriptor) }
// EnumValueDescriptors is a list of enum value declarations.
type EnumValueDescriptors interface {
// Len reports the number of enum values.
Len() int
// Get returns the ith EnumValueDescriptor. It panics if out of bounds.
Get(i int) EnumValueDescriptor
// ByName returns the EnumValueDescriptor for the enum value named s.
// It returns nil if not found.
ByName(s Name) EnumValueDescriptor
// ByNumber returns the EnumValueDescriptor for the enum value numbered n.
// If multiple have the same number, the first one defined is returned
// It returns nil if not found.
ByNumber(n EnumNumber) EnumValueDescriptor
doNotImplement
}
// ServiceDescriptor describes a service and
// corresponds with the google.protobuf.ServiceDescriptorProto message.
//
// Nested declarations: [MethodDescriptor].
type ServiceDescriptor interface {
Descriptor
// Methods is a list of nested message declarations.
Methods() MethodDescriptors
isServiceDescriptor
}
type isServiceDescriptor interface{ ProtoType(ServiceDescriptor) }
// ServiceDescriptors is a list of service declarations.
type ServiceDescriptors interface {
// Len reports the number of services.
Len() int
// Get returns the ith ServiceDescriptor. It panics if out of bounds.
Get(i int) ServiceDescriptor
// ByName returns the ServiceDescriptor for a service named s.
// It returns nil if not found.
ByName(s Name) ServiceDescriptor
doNotImplement
}
// MethodDescriptor describes a method and
// corresponds with the google.protobuf.MethodDescriptorProto message.
type MethodDescriptor interface {
Descriptor
// Input is the input message descriptor.
Input() MessageDescriptor
// Output is the output message descriptor.
Output() MessageDescriptor
// IsStreamingClient reports whether the client streams multiple messages.
IsStreamingClient() bool
// IsStreamingServer reports whether the server streams multiple messages.
IsStreamingServer() bool
isMethodDescriptor
}
type isMethodDescriptor interface{ ProtoType(MethodDescriptor) }
// MethodDescriptors is a list of method declarations.
type MethodDescriptors interface {
// Len reports the number of methods.
Len() int
// Get returns the ith MethodDescriptor. It panics if out of bounds.
Get(i int) MethodDescriptor
// ByName returns the MethodDescriptor for a service method named s.
// It returns nil if not found.
ByName(s Name) MethodDescriptor
doNotImplement
}

View File

@ -0,0 +1,285 @@
// 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 protoreflect
import "google.golang.org/protobuf/encoding/protowire"
// Enum is a reflection interface for a concrete enum value,
// which provides type information and a getter for the enum number.
// Enum does not provide a mutable API since enums are commonly backed by
// Go constants, which are not addressable.
type Enum interface {
// Descriptor returns enum descriptor, which contains only the protobuf
// type information for the enum.
Descriptor() EnumDescriptor
// Type returns the enum type, which encapsulates both Go and protobuf
// type information. If the Go type information is not needed,
// it is recommended that the enum descriptor be used instead.
Type() EnumType
// Number returns the enum value as an integer.
Number() EnumNumber
}
// Message is a reflective interface for a concrete message value,
// encapsulating both type and value information for the message.
//
// Accessor/mutators for individual fields are keyed by [FieldDescriptor].
// For non-extension fields, the descriptor must exactly match the
// field known by the parent message.
// For extension fields, the descriptor must implement [ExtensionTypeDescriptor],
// extend the parent message (i.e., have the same message [FullName]), and
// be within the parent's extension range.
//
// Each field [Value] can be a scalar or a composite type ([Message], [List], or [Map]).
// See [Value] for the Go types associated with a [FieldDescriptor].
// Providing a [Value] that is invalid or of an incorrect type panics.
type Message interface {
// Descriptor returns message descriptor, which contains only the protobuf
// type information for the message.
Descriptor() MessageDescriptor
// Type returns the message type, which encapsulates both Go and protobuf
// type information. If the Go type information is not needed,
// it is recommended that the message descriptor be used instead.
Type() MessageType
// New returns a newly allocated and mutable empty message.
New() Message
// Interface unwraps the message reflection interface and
// returns the underlying ProtoMessage interface.
Interface() ProtoMessage
// Range iterates over every populated field in an undefined order,
// calling f for each field descriptor and value encountered.
// Range returns immediately if f returns false.
// While iterating, mutating operations may only be performed
// on the current field descriptor.
Range(f func(FieldDescriptor, Value) bool)
// Has reports whether a field is populated.
//
// Some fields have the property of nullability where it is possible to
// distinguish between the default value of a field and whether the field
// was explicitly populated with the default value. Singular message fields,
// member fields of a oneof, and proto2 scalar fields are nullable. Such
// fields are populated only if explicitly set.
//
// In other cases (aside from the nullable cases above),
// a proto3 scalar field is populated if it contains a non-zero value, and
// a repeated field is populated if it is non-empty.
Has(FieldDescriptor) bool
// Clear clears the field such that a subsequent Has call reports false.
//
// Clearing an extension field clears both the extension type and value
// associated with the given field number.
//
// Clear is a mutating operation and unsafe for concurrent use.
Clear(FieldDescriptor)
// Get retrieves the value for a field.
//
// For unpopulated scalars, it returns the default value, where
// the default value of a bytes scalar is guaranteed to be a copy.
// For unpopulated composite types, it returns an empty, read-only view
// of the value; to obtain a mutable reference, use Mutable.
Get(FieldDescriptor) Value
// Set stores the value for a field.
//
// For a field belonging to a oneof, it implicitly clears any other field
// that may be currently set within the same oneof.
// For extension fields, it implicitly stores the provided ExtensionType.
// When setting a composite type, it is unspecified whether the stored value
// aliases the source's memory in any way. If the composite value is an
// empty, read-only value, then it panics.
//
// Set is a mutating operation and unsafe for concurrent use.
Set(FieldDescriptor, Value)
// Mutable returns a mutable reference to a composite type.
//
// If the field is unpopulated, it may allocate a composite value.
// For a field belonging to a oneof, it implicitly clears any other field
// that may be currently set within the same oneof.
// For extension fields, it implicitly stores the provided ExtensionType
// if not already stored.
// It panics if the field does not contain a composite type.
//
// Mutable is a mutating operation and unsafe for concurrent use.
Mutable(FieldDescriptor) Value
// NewField returns a new value that is assignable to the field
// for the given descriptor. For scalars, this returns the default value.
// For lists, maps, and messages, this returns a new, empty, mutable value.
NewField(FieldDescriptor) Value
// WhichOneof reports which field within the oneof is populated,
// returning nil if none are populated.
// It panics if the oneof descriptor does not belong to this message.
WhichOneof(OneofDescriptor) FieldDescriptor
// GetUnknown retrieves the entire list of unknown fields.
// The caller may only mutate the contents of the RawFields
// if the mutated bytes are stored back into the message with SetUnknown.
GetUnknown() RawFields
// SetUnknown stores an entire list of unknown fields.
// The raw fields must be syntactically valid according to the wire format.
// An implementation may panic if this is not the case.
// Once stored, the caller must not mutate the content of the RawFields.
// An empty RawFields may be passed to clear the fields.
//
// SetUnknown is a mutating operation and unsafe for concurrent use.
SetUnknown(RawFields)
// IsValid reports whether the message is valid.
//
// An invalid message is an empty, read-only value.
//
// An invalid message often corresponds to a nil pointer of the concrete
// message type, but the details are implementation dependent.
// Validity is not part of the protobuf data model, and may not
// be preserved in marshaling or other operations.
IsValid() bool
// ProtoMethods returns optional fast-path implementations of various operations.
// This method may return nil.
//
// The returned methods type is identical to
// google.golang.org/protobuf/runtime/protoiface.Methods.
// Consult the protoiface package documentation for details.
ProtoMethods() *methods
}
// RawFields is the raw bytes for an ordered sequence of fields.
// Each field contains both the tag (representing field number and wire type),
// and also the wire data itself.
type RawFields []byte
// IsValid reports whether b is syntactically correct wire format.
func (b RawFields) IsValid() bool {
for len(b) > 0 {
_, _, n := protowire.ConsumeField(b)
if n < 0 {
return false
}
b = b[n:]
}
return true
}
// List is a zero-indexed, ordered list.
// The element [Value] type is determined by [FieldDescriptor.Kind].
// Providing a [Value] that is invalid or of an incorrect type panics.
type List interface {
// Len reports the number of entries in the List.
// Get, Set, and Truncate panic with out of bound indexes.
Len() int
// Get retrieves the value at the given index.
// It never returns an invalid value.
Get(int) Value
// Set stores a value for the given index.
// When setting a composite type, it is unspecified whether the set
// value aliases the source's memory in any way.
//
// Set is a mutating operation and unsafe for concurrent use.
Set(int, Value)
// Append appends the provided value to the end of the list.
// When appending a composite type, it is unspecified whether the appended
// value aliases the source's memory in any way.
//
// Append is a mutating operation and unsafe for concurrent use.
Append(Value)
// AppendMutable appends a new, empty, mutable message value to the end
// of the list and returns it.
// It panics if the list does not contain a message type.
AppendMutable() Value
// Truncate truncates the list to a smaller length.
//
// Truncate is a mutating operation and unsafe for concurrent use.
Truncate(int)
// NewElement returns a new value for a list element.
// For enums, this returns the first enum value.
// For other scalars, this returns the zero value.
// For messages, this returns a new, empty, mutable value.
NewElement() Value
// IsValid reports whether the list is valid.
//
// An invalid list is an empty, read-only value.
//
// Validity is not part of the protobuf data model, and may not
// be preserved in marshaling or other operations.
IsValid() bool
}
// Map is an unordered, associative map.
// The entry [MapKey] type is determined by [FieldDescriptor.MapKey].Kind.
// The entry [Value] type is determined by [FieldDescriptor.MapValue].Kind.
// Providing a [MapKey] or [Value] that is invalid or of an incorrect type panics.
type Map interface {
// Len reports the number of elements in the map.
Len() int
// Range iterates over every map entry in an undefined order,
// calling f for each key and value encountered.
// Range calls f Len times unless f returns false, which stops iteration.
// While iterating, mutating operations may only be performed
// on the current map key.
Range(f func(MapKey, Value) bool)
// Has reports whether an entry with the given key is in the map.
Has(MapKey) bool
// Clear clears the entry associated with they given key.
// The operation does nothing if there is no entry associated with the key.
//
// Clear is a mutating operation and unsafe for concurrent use.
Clear(MapKey)
// Get retrieves the value for an entry with the given key.
// It returns an invalid value for non-existent entries.
Get(MapKey) Value
// Set stores the value for an entry with the given key.
// It panics when given a key or value that is invalid or the wrong type.
// When setting a composite type, it is unspecified whether the set
// value aliases the source's memory in any way.
//
// Set is a mutating operation and unsafe for concurrent use.
Set(MapKey, Value)
// Mutable retrieves a mutable reference to the entry for the given key.
// If no entry exists for the key, it creates a new, empty, mutable value
// and stores it as the entry for the key.
// It panics if the map value is not a message.
Mutable(MapKey) Value
// NewValue returns a new value assignable as a map value.
// For enums, this returns the first enum value.
// For other scalars, this returns the zero value.
// For messages, this returns a new, empty, mutable value.
NewValue() Value
// IsValid reports whether the map is valid.
//
// An invalid map is an empty, read-only value.
//
// An invalid message often corresponds to a nil Go map value,
// but the details are implementation dependent.
// Validity is not part of the protobuf data model, and may not
// be preserved in marshaling or other operations.
IsValid() bool
}

View File

@ -0,0 +1,168 @@
// Copyright 2022 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 protoreflect
import (
"bytes"
"fmt"
"math"
"reflect"
"google.golang.org/protobuf/encoding/protowire"
)
// Equal reports whether v1 and v2 are recursively equal.
//
// - Values of different types are always unequal.
//
// - Bytes values are equal if they contain identical bytes.
// Empty bytes (regardless of nil-ness) are considered equal.
//
// - Floating point values are equal if they contain the same value.
// Unlike the == operator, a NaN is equal to another NaN.
//
// - Enums are equal if they contain the same number.
// Since [Value] does not contain an enum descriptor,
// enum values do not consider the type of the enum.
//
// - Other scalar values are equal if they contain the same value.
//
// - [Message] values are equal if they belong to the same message descriptor,
// have the same set of populated known and extension field values,
// and the same set of unknown fields values.
//
// - [List] values are equal if they are the same length and
// each corresponding element is equal.
//
// - [Map] values are equal if they have the same set of keys and
// the corresponding value for each key is equal.
func (v1 Value) Equal(v2 Value) bool {
return equalValue(v1, v2)
}
func equalValue(x, y Value) bool {
eqType := x.typ == y.typ
switch x.typ {
case nilType:
return eqType
case boolType:
return eqType && x.Bool() == y.Bool()
case int32Type, int64Type:
return eqType && x.Int() == y.Int()
case uint32Type, uint64Type:
return eqType && x.Uint() == y.Uint()
case float32Type, float64Type:
return eqType && equalFloat(x.Float(), y.Float())
case stringType:
return eqType && x.String() == y.String()
case bytesType:
return eqType && bytes.Equal(x.Bytes(), y.Bytes())
case enumType:
return eqType && x.Enum() == y.Enum()
default:
switch x := x.Interface().(type) {
case Message:
y, ok := y.Interface().(Message)
return ok && equalMessage(x, y)
case List:
y, ok := y.Interface().(List)
return ok && equalList(x, y)
case Map:
y, ok := y.Interface().(Map)
return ok && equalMap(x, y)
default:
panic(fmt.Sprintf("unknown type: %T", x))
}
}
}
// equalFloat compares two floats, where NaNs are treated as equal.
func equalFloat(x, y float64) bool {
if math.IsNaN(x) || math.IsNaN(y) {
return math.IsNaN(x) && math.IsNaN(y)
}
return x == y
}
// equalMessage compares two messages.
func equalMessage(mx, my Message) bool {
if mx.Descriptor() != my.Descriptor() {
return false
}
nx := 0
equal := true
mx.Range(func(fd FieldDescriptor, vx Value) bool {
nx++
vy := my.Get(fd)
equal = my.Has(fd) && equalValue(vx, vy)
return equal
})
if !equal {
return false
}
ny := 0
my.Range(func(fd FieldDescriptor, vx Value) bool {
ny++
return true
})
if nx != ny {
return false
}
return equalUnknown(mx.GetUnknown(), my.GetUnknown())
}
// equalList compares two lists.
func equalList(x, y List) bool {
if x.Len() != y.Len() {
return false
}
for i := x.Len() - 1; i >= 0; i-- {
if !equalValue(x.Get(i), y.Get(i)) {
return false
}
}
return true
}
// equalMap compares two maps.
func equalMap(x, y Map) bool {
if x.Len() != y.Len() {
return false
}
equal := true
x.Range(func(k MapKey, vx Value) bool {
vy := y.Get(k)
equal = y.Has(k) && equalValue(vx, vy)
return equal
})
return equal
}
// equalUnknown compares unknown fields by direct comparison on the raw bytes
// of each individual field number.
func equalUnknown(x, y RawFields) bool {
if len(x) != len(y) {
return false
}
if bytes.Equal([]byte(x), []byte(y)) {
return true
}
mx := make(map[FieldNumber]RawFields)
my := make(map[FieldNumber]RawFields)
for len(x) > 0 {
fnum, _, n := protowire.ConsumeField(x)
mx[fnum] = append(mx[fnum], x[:n]...)
x = x[n:]
}
for len(y) > 0 {
fnum, _, n := protowire.ConsumeField(y)
my[fnum] = append(my[fnum], y[:n]...)
y = y[n:]
}
return reflect.DeepEqual(mx, my)
}

View File

@ -0,0 +1,60 @@
// 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.
//go:build purego || appengine
// +build purego appengine
package protoreflect
import "google.golang.org/protobuf/internal/pragma"
type valueType int
const (
nilType valueType = iota
boolType
int32Type
int64Type
uint32Type
uint64Type
float32Type
float64Type
stringType
bytesType
enumType
ifaceType
)
// value is a union where only one type can be represented at a time.
// This uses a distinct field for each type. This is type safe in Go, but
// occupies more memory than necessary (72B).
type value struct {
pragma.DoNotCompare // 0B
typ valueType // 8B
num uint64 // 8B
str string // 16B
bin []byte // 24B
iface any // 16B
}
func valueOfString(v string) Value {
return Value{typ: stringType, str: v}
}
func valueOfBytes(v []byte) Value {
return Value{typ: bytesType, bin: v}
}
func valueOfIface(v any) Value {
return Value{typ: ifaceType, iface: v}
}
func (v Value) getString() string {
return v.str
}
func (v Value) getBytes() []byte {
return v.bin
}
func (v Value) getIface() any {
return v.iface
}

View File

@ -0,0 +1,438 @@
// 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 protoreflect
import (
"fmt"
"math"
)
// Value is a union where only one Go type may be set at a time.
// The Value is used to represent all possible values a field may take.
// The following shows which Go type is used to represent each proto [Kind]:
//
// ╔════════════╤═════════════════════════════════════╗
// ║ 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 ║
// ║ EnumNumber │ EnumKind ║
// ║ Message │ MessageKind, GroupKind ║
// ╚════════════╧═════════════════════════════════════╝
//
// Multiple protobuf Kinds may be represented by a single Go type if the type
// can losslessly represent the information for the proto kind. For example,
// [Int64Kind], [Sint64Kind], and [Sfixed64Kind] are all represented by int64,
// but use different integer encoding methods.
//
// The [List] or [Map] types are used if the field cardinality is repeated.
// A field is a [List] if [FieldDescriptor.IsList] reports true.
// A field is a [Map] if [FieldDescriptor.IsMap] reports true.
//
// Converting to/from a Value and a concrete Go value panics on type mismatch.
// For example, [ValueOf]("hello").Int() panics because this attempts to
// retrieve an int64 from a string.
//
// [List], [Map], and [Message] Values are called "composite" values.
//
// A composite Value may alias (reference) memory at some location,
// such that changes to the Value updates the that location.
// A composite value acquired with a Mutable method, such as [Message.Mutable],
// always references the source object.
//
// For example:
//
// // Append a 0 to a "repeated int32" field.
// // Since the Value returned by Mutable is guaranteed to alias
// // the source message, modifying the Value modifies the message.
// message.Mutable(fieldDesc).List().Append(protoreflect.ValueOfInt32(0))
//
// // Assign [0] to a "repeated int32" field by creating a new Value,
// // modifying it, and assigning it.
// list := message.NewField(fieldDesc).List()
// list.Append(protoreflect.ValueOfInt32(0))
// message.Set(fieldDesc, list)
// // ERROR: Since it is not defined whether Set aliases the source,
// // appending to the List here may or may not modify the message.
// list.Append(protoreflect.ValueOfInt32(0))
//
// Some operations, such as [Message.Get], may return an "empty, read-only"
// composite Value. Modifying an empty, read-only value panics.
type Value value
// The protoreflect API uses a custom Value union type instead of any
// to keep the future open for performance optimizations. Using an any
// always incurs an allocation for primitives (e.g., int64) since it needs to
// be boxed on the heap (as interfaces can only contain pointers natively).
// Instead, we represent the Value union as a flat struct that internally keeps
// track of which type is set. Using unsafe, the Value union can be reduced
// down to 24B, which is identical in size to a slice.
//
// The latest compiler (Go1.11) currently suffers from some limitations:
// • With inlining, the compiler should be able to statically prove that
// only one of these switch cases are taken and inline one specific case.
// See https://golang.org/issue/22310.
// ValueOf returns a Value initialized with the concrete value stored in v.
// This panics if the type does not match one of the allowed types in the
// Value union.
func ValueOf(v any) Value {
switch v := v.(type) {
case nil:
return Value{}
case bool:
return ValueOfBool(v)
case int32:
return ValueOfInt32(v)
case int64:
return ValueOfInt64(v)
case uint32:
return ValueOfUint32(v)
case uint64:
return ValueOfUint64(v)
case float32:
return ValueOfFloat32(v)
case float64:
return ValueOfFloat64(v)
case string:
return ValueOfString(v)
case []byte:
return ValueOfBytes(v)
case EnumNumber:
return ValueOfEnum(v)
case Message, List, Map:
return valueOfIface(v)
case ProtoMessage:
panic(fmt.Sprintf("invalid proto.Message(%T) type, expected a protoreflect.Message type", v))
default:
panic(fmt.Sprintf("invalid type: %T", v))
}
}
// ValueOfBool returns a new boolean value.
func ValueOfBool(v bool) Value {
if v {
return Value{typ: boolType, num: 1}
} else {
return Value{typ: boolType, num: 0}
}
}
// ValueOfInt32 returns a new int32 value.
func ValueOfInt32(v int32) Value {
return Value{typ: int32Type, num: uint64(v)}
}
// ValueOfInt64 returns a new int64 value.
func ValueOfInt64(v int64) Value {
return Value{typ: int64Type, num: uint64(v)}
}
// ValueOfUint32 returns a new uint32 value.
func ValueOfUint32(v uint32) Value {
return Value{typ: uint32Type, num: uint64(v)}
}
// ValueOfUint64 returns a new uint64 value.
func ValueOfUint64(v uint64) Value {
return Value{typ: uint64Type, num: v}
}
// ValueOfFloat32 returns a new float32 value.
func ValueOfFloat32(v float32) Value {
return Value{typ: float32Type, num: uint64(math.Float64bits(float64(v)))}
}
// ValueOfFloat64 returns a new float64 value.
func ValueOfFloat64(v float64) Value {
return Value{typ: float64Type, num: uint64(math.Float64bits(float64(v)))}
}
// ValueOfString returns a new string value.
func ValueOfString(v string) Value {
return valueOfString(v)
}
// ValueOfBytes returns a new bytes value.
func ValueOfBytes(v []byte) Value {
return valueOfBytes(v[:len(v):len(v)])
}
// ValueOfEnum returns a new enum value.
func ValueOfEnum(v EnumNumber) Value {
return Value{typ: enumType, num: uint64(v)}
}
// ValueOfMessage returns a new Message value.
func ValueOfMessage(v Message) Value {
return valueOfIface(v)
}
// ValueOfList returns a new List value.
func ValueOfList(v List) Value {
return valueOfIface(v)
}
// ValueOfMap returns a new Map value.
func ValueOfMap(v Map) Value {
return valueOfIface(v)
}
// IsValid reports whether v is populated with a value.
func (v Value) IsValid() bool {
return v.typ != nilType
}
// Interface returns v as an any.
//
// Invariant: v == ValueOf(v).Interface()
func (v Value) Interface() any {
switch v.typ {
case nilType:
return nil
case boolType:
return v.Bool()
case int32Type:
return int32(v.Int())
case int64Type:
return int64(v.Int())
case uint32Type:
return uint32(v.Uint())
case uint64Type:
return uint64(v.Uint())
case float32Type:
return float32(v.Float())
case float64Type:
return float64(v.Float())
case stringType:
return v.String()
case bytesType:
return v.Bytes()
case enumType:
return v.Enum()
default:
return v.getIface()
}
}
func (v Value) typeName() string {
switch v.typ {
case nilType:
return "nil"
case boolType:
return "bool"
case int32Type:
return "int32"
case int64Type:
return "int64"
case uint32Type:
return "uint32"
case uint64Type:
return "uint64"
case float32Type:
return "float32"
case float64Type:
return "float64"
case stringType:
return "string"
case bytesType:
return "bytes"
case enumType:
return "enum"
default:
switch v := v.getIface().(type) {
case Message:
return "message"
case List:
return "list"
case Map:
return "map"
default:
return fmt.Sprintf("<unknown: %T>", v)
}
}
}
func (v Value) panicMessage(what string) string {
return fmt.Sprintf("type mismatch: cannot convert %v to %s", v.typeName(), what)
}
// Bool returns v as a bool and panics if the type is not a bool.
func (v Value) Bool() bool {
switch v.typ {
case boolType:
return v.num > 0
default:
panic(v.panicMessage("bool"))
}
}
// Int returns v as a int64 and panics if the type is not a int32 or int64.
func (v Value) Int() int64 {
switch v.typ {
case int32Type, int64Type:
return int64(v.num)
default:
panic(v.panicMessage("int"))
}
}
// Uint returns v as a uint64 and panics if the type is not a uint32 or uint64.
func (v Value) Uint() uint64 {
switch v.typ {
case uint32Type, uint64Type:
return uint64(v.num)
default:
panic(v.panicMessage("uint"))
}
}
// Float returns v as a float64 and panics if the type is not a float32 or float64.
func (v Value) Float() float64 {
switch v.typ {
case float32Type, float64Type:
return math.Float64frombits(uint64(v.num))
default:
panic(v.panicMessage("float"))
}
}
// String returns v as a string. Since this method implements [fmt.Stringer],
// this returns the formatted string value for any non-string type.
func (v Value) String() string {
switch v.typ {
case stringType:
return v.getString()
default:
return fmt.Sprint(v.Interface())
}
}
// Bytes returns v as a []byte and panics if the type is not a []byte.
func (v Value) Bytes() []byte {
switch v.typ {
case bytesType:
return v.getBytes()
default:
panic(v.panicMessage("bytes"))
}
}
// Enum returns v as a [EnumNumber] and panics if the type is not a [EnumNumber].
func (v Value) Enum() EnumNumber {
switch v.typ {
case enumType:
return EnumNumber(v.num)
default:
panic(v.panicMessage("enum"))
}
}
// Message returns v as a [Message] and panics if the type is not a [Message].
func (v Value) Message() Message {
switch vi := v.getIface().(type) {
case Message:
return vi
default:
panic(v.panicMessage("message"))
}
}
// List returns v as a [List] and panics if the type is not a [List].
func (v Value) List() List {
switch vi := v.getIface().(type) {
case List:
return vi
default:
panic(v.panicMessage("list"))
}
}
// Map returns v as a [Map] and panics if the type is not a [Map].
func (v Value) Map() Map {
switch vi := v.getIface().(type) {
case Map:
return vi
default:
panic(v.panicMessage("map"))
}
}
// MapKey returns v as a [MapKey] and panics for invalid [MapKey] types.
func (v Value) MapKey() MapKey {
switch v.typ {
case boolType, int32Type, int64Type, uint32Type, uint64Type, stringType:
return MapKey(v)
default:
panic(v.panicMessage("map key"))
}
}
// MapKey is used to index maps, where the Go type of the MapKey must match
// the specified key [Kind] (see [MessageDescriptor.IsMapEntry]).
// The following shows what Go type is used to represent each proto [Kind]:
//
// ╔═════════╤═════════════════════════════════════╗
// ║ Go type │ Protobuf kind ║
// ╠═════════╪═════════════════════════════════════╣
// ║ bool │ BoolKind ║
// ║ int32 │ Int32Kind, Sint32Kind, Sfixed32Kind ║
// ║ int64 │ Int64Kind, Sint64Kind, Sfixed64Kind ║
// ║ uint32 │ Uint32Kind, Fixed32Kind ║
// ║ uint64 │ Uint64Kind, Fixed64Kind ║
// ║ string │ StringKind ║
// ╚═════════╧═════════════════════════════════════╝
//
// A MapKey is constructed and accessed through a [Value]:
//
// k := ValueOf("hash").MapKey() // convert string to MapKey
// s := k.String() // convert MapKey to string
//
// The MapKey is a strict subset of valid types used in [Value];
// converting a [Value] to a MapKey with an invalid type panics.
type MapKey value
// IsValid reports whether k is populated with a value.
func (k MapKey) IsValid() bool {
return Value(k).IsValid()
}
// Interface returns k as an any.
func (k MapKey) Interface() any {
return Value(k).Interface()
}
// Bool returns k as a bool and panics if the type is not a bool.
func (k MapKey) Bool() bool {
return Value(k).Bool()
}
// Int returns k as a int64 and panics if the type is not a int32 or int64.
func (k MapKey) Int() int64 {
return Value(k).Int()
}
// Uint returns k as a uint64 and panics if the type is not a uint32 or uint64.
func (k MapKey) Uint() uint64 {
return Value(k).Uint()
}
// String returns k as a string. Since this method implements [fmt.Stringer],
// this returns the formatted string value for any non-string type.
func (k MapKey) String() string {
return Value(k).String()
}
// Value returns k as a [Value].
func (k MapKey) Value() Value {
return Value(k)
}

View File

@ -0,0 +1,99 @@
// 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.
//go:build !purego && !appengine && !go1.21
// +build !purego,!appengine,!go1.21
package protoreflect
import (
"unsafe"
"google.golang.org/protobuf/internal/pragma"
)
type (
stringHeader struct {
Data unsafe.Pointer
Len int
}
sliceHeader struct {
Data unsafe.Pointer
Len int
Cap int
}
ifaceHeader struct {
Type unsafe.Pointer
Data unsafe.Pointer
}
)
var (
nilType = typeOf(nil)
boolType = typeOf(*new(bool))
int32Type = typeOf(*new(int32))
int64Type = typeOf(*new(int64))
uint32Type = typeOf(*new(uint32))
uint64Type = typeOf(*new(uint64))
float32Type = typeOf(*new(float32))
float64Type = typeOf(*new(float64))
stringType = typeOf(*new(string))
bytesType = typeOf(*new([]byte))
enumType = typeOf(*new(EnumNumber))
)
// typeOf returns a pointer to the Go type information.
// The pointer is comparable and equal if and only if the types are identical.
func typeOf(t any) unsafe.Pointer {
return (*ifaceHeader)(unsafe.Pointer(&t)).Type
}
// value is a union where only one type can be represented at a time.
// The struct is 24B large on 64-bit systems and requires the minimum storage
// necessary to represent each possible type.
//
// The Go GC needs to be able to scan variables containing pointers.
// As such, pointers and non-pointers cannot be intermixed.
type value struct {
pragma.DoNotCompare // 0B
// typ stores the type of the value as a pointer to the Go type.
typ unsafe.Pointer // 8B
// ptr stores the data pointer for a String, Bytes, or interface value.
ptr unsafe.Pointer // 8B
// num stores a Bool, Int32, Int64, Uint32, Uint64, Float32, Float64, or
// Enum value as a raw uint64.
//
// It is also used to store the length of a String or Bytes value;
// the capacity is ignored.
num uint64 // 8B
}
func valueOfString(v string) Value {
p := (*stringHeader)(unsafe.Pointer(&v))
return Value{typ: stringType, ptr: p.Data, num: uint64(len(v))}
}
func valueOfBytes(v []byte) Value {
p := (*sliceHeader)(unsafe.Pointer(&v))
return Value{typ: bytesType, ptr: p.Data, num: uint64(len(v))}
}
func valueOfIface(v any) Value {
p := (*ifaceHeader)(unsafe.Pointer(&v))
return Value{typ: p.Type, ptr: p.Data}
}
func (v Value) getString() (x string) {
*(*stringHeader)(unsafe.Pointer(&x)) = stringHeader{Data: v.ptr, Len: int(v.num)}
return x
}
func (v Value) getBytes() (x []byte) {
*(*sliceHeader)(unsafe.Pointer(&x)) = sliceHeader{Data: v.ptr, Len: int(v.num), Cap: int(v.num)}
return x
}
func (v Value) getIface() (x any) {
*(*ifaceHeader)(unsafe.Pointer(&x)) = ifaceHeader{Type: v.typ, Data: v.ptr}
return x
}

View File

@ -0,0 +1,87 @@
// 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.
//go:build !purego && !appengine && go1.21
// +build !purego,!appengine,go1.21
package protoreflect
import (
"unsafe"
"google.golang.org/protobuf/internal/pragma"
)
type (
ifaceHeader struct {
_ [0]any // if interfaces have greater alignment than unsafe.Pointer, this will enforce it.
Type unsafe.Pointer
Data unsafe.Pointer
}
)
var (
nilType = typeOf(nil)
boolType = typeOf(*new(bool))
int32Type = typeOf(*new(int32))
int64Type = typeOf(*new(int64))
uint32Type = typeOf(*new(uint32))
uint64Type = typeOf(*new(uint64))
float32Type = typeOf(*new(float32))
float64Type = typeOf(*new(float64))
stringType = typeOf(*new(string))
bytesType = typeOf(*new([]byte))
enumType = typeOf(*new(EnumNumber))
)
// typeOf returns a pointer to the Go type information.
// The pointer is comparable and equal if and only if the types are identical.
func typeOf(t any) unsafe.Pointer {
return (*ifaceHeader)(unsafe.Pointer(&t)).Type
}
// value is a union where only one type can be represented at a time.
// The struct is 24B large on 64-bit systems and requires the minimum storage
// necessary to represent each possible type.
//
// The Go GC needs to be able to scan variables containing pointers.
// As such, pointers and non-pointers cannot be intermixed.
type value struct {
pragma.DoNotCompare // 0B
// typ stores the type of the value as a pointer to the Go type.
typ unsafe.Pointer // 8B
// ptr stores the data pointer for a String, Bytes, or interface value.
ptr unsafe.Pointer // 8B
// num stores a Bool, Int32, Int64, Uint32, Uint64, Float32, Float64, or
// Enum value as a raw uint64.
//
// It is also used to store the length of a String or Bytes value;
// the capacity is ignored.
num uint64 // 8B
}
func valueOfString(v string) Value {
return Value{typ: stringType, ptr: unsafe.Pointer(unsafe.StringData(v)), num: uint64(len(v))}
}
func valueOfBytes(v []byte) Value {
return Value{typ: bytesType, ptr: unsafe.Pointer(unsafe.SliceData(v)), num: uint64(len(v))}
}
func valueOfIface(v any) Value {
p := (*ifaceHeader)(unsafe.Pointer(&v))
return Value{typ: p.Type, ptr: p.Data}
}
func (v Value) getString() string {
return unsafe.String((*byte)(v.ptr), v.num)
}
func (v Value) getBytes() []byte {
return unsafe.Slice((*byte)(v.ptr), v.num)
}
func (v Value) getIface() (x any) {
*(*ifaceHeader)(unsafe.Pointer(&x)) = ifaceHeader{Type: v.typ, Data: v.ptr}
return x
}

View File

@ -0,0 +1,882 @@
// 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 protoregistry provides data structures to register and lookup
// protobuf descriptor types.
//
// The [Files] registry contains file descriptors and provides the ability
// to iterate over the files or lookup a specific descriptor within the files.
// [Files] only contains protobuf descriptors and has no understanding of Go
// type information that may be associated with each descriptor.
//
// The [Types] registry contains descriptor types for which there is a known
// Go type associated with that descriptor. It provides the ability to iterate
// over the registered types or lookup a type by name.
package protoregistry
import (
"fmt"
"os"
"strings"
"sync"
"google.golang.org/protobuf/internal/encoding/messageset"
"google.golang.org/protobuf/internal/errors"
"google.golang.org/protobuf/internal/flags"
"google.golang.org/protobuf/reflect/protoreflect"
)
// conflictPolicy configures the policy for handling registration conflicts.
//
// It can be over-written at compile time with a linker-initialized variable:
//
// go build -ldflags "-X google.golang.org/protobuf/reflect/protoregistry.conflictPolicy=warn"
//
// It can be over-written at program execution with an environment variable:
//
// GOLANG_PROTOBUF_REGISTRATION_CONFLICT=warn ./main
//
// Neither of the above are covered by the compatibility promise and
// may be removed in a future release of this module.
var conflictPolicy = "panic" // "panic" | "warn" | "ignore"
// ignoreConflict reports whether to ignore a registration conflict
// given the descriptor being registered and the error.
// It is a variable so that the behavior is easily overridden in another file.
var ignoreConflict = func(d protoreflect.Descriptor, err error) bool {
const env = "GOLANG_PROTOBUF_REGISTRATION_CONFLICT"
const faq = "https://protobuf.dev/reference/go/faq#namespace-conflict"
policy := conflictPolicy
if v := os.Getenv(env); v != "" {
policy = v
}
switch policy {
case "panic":
panic(fmt.Sprintf("%v\nSee %v\n", err, faq))
case "warn":
fmt.Fprintf(os.Stderr, "WARNING: %v\nSee %v\n\n", err, faq)
return true
case "ignore":
return true
default:
panic("invalid " + env + " value: " + os.Getenv(env))
}
}
var globalMutex sync.RWMutex
// GlobalFiles is a global registry of file descriptors.
var GlobalFiles *Files = new(Files)
// GlobalTypes is the registry used by default for type lookups
// unless a local registry is provided by the user.
var GlobalTypes *Types = new(Types)
// NotFound is a sentinel error value to indicate that the type was not found.
//
// Since registry lookup can happen in the critical performance path, resolvers
// must return this exact error value, not an error wrapping it.
var NotFound = errors.New("not found")
// Files is a registry for looking up or iterating over files and the
// descriptors contained within them.
// The Find and Range methods are safe for concurrent use.
type Files struct {
// The map of descsByName contains:
// EnumDescriptor
// EnumValueDescriptor
// MessageDescriptor
// ExtensionDescriptor
// ServiceDescriptor
// *packageDescriptor
//
// Note that files are stored as a slice, since a package may contain
// multiple files. Only top-level declarations are registered.
// Note that enum values are in the top-level since that are in the same
// scope as the parent enum.
descsByName map[protoreflect.FullName]any
filesByPath map[string][]protoreflect.FileDescriptor
numFiles int
}
type packageDescriptor struct {
files []protoreflect.FileDescriptor
}
// RegisterFile registers the provided file descriptor.
//
// If any descriptor within the file conflicts with the descriptor of any
// previously registered file (e.g., two enums with the same full name),
// then the file is not registered and an error is returned.
//
// It is permitted for multiple files to have the same file path.
func (r *Files) RegisterFile(file protoreflect.FileDescriptor) error {
if r == GlobalFiles {
globalMutex.Lock()
defer globalMutex.Unlock()
}
if r.descsByName == nil {
r.descsByName = map[protoreflect.FullName]any{
"": &packageDescriptor{},
}
r.filesByPath = make(map[string][]protoreflect.FileDescriptor)
}
path := file.Path()
if prev := r.filesByPath[path]; len(prev) > 0 {
r.checkGenProtoConflict(path)
err := errors.New("file %q is already registered", file.Path())
err = amendErrorWithCaller(err, prev[0], file)
if !(r == GlobalFiles && ignoreConflict(file, err)) {
return err
}
}
for name := file.Package(); name != ""; name = name.Parent() {
switch prev := r.descsByName[name]; prev.(type) {
case nil, *packageDescriptor:
default:
err := errors.New("file %q has a package name conflict over %v", file.Path(), name)
err = amendErrorWithCaller(err, prev, file)
if r == GlobalFiles && ignoreConflict(file, err) {
err = nil
}
return err
}
}
var err error
var hasConflict bool
rangeTopLevelDescriptors(file, func(d protoreflect.Descriptor) {
if prev := r.descsByName[d.FullName()]; prev != nil {
hasConflict = true
err = errors.New("file %q has a name conflict over %v", file.Path(), d.FullName())
err = amendErrorWithCaller(err, prev, file)
if r == GlobalFiles && ignoreConflict(d, err) {
err = nil
}
}
})
if hasConflict {
return err
}
for name := file.Package(); name != ""; name = name.Parent() {
if r.descsByName[name] == nil {
r.descsByName[name] = &packageDescriptor{}
}
}
p := r.descsByName[file.Package()].(*packageDescriptor)
p.files = append(p.files, file)
rangeTopLevelDescriptors(file, func(d protoreflect.Descriptor) {
r.descsByName[d.FullName()] = d
})
r.filesByPath[path] = append(r.filesByPath[path], file)
r.numFiles++
return nil
}
// Several well-known types were hosted in the google.golang.org/genproto module
// but were later moved to this module. To avoid a weak dependency on the
// genproto module (and its relatively large set of transitive dependencies),
// we rely on a registration conflict to determine whether the genproto version
// is too old (i.e., does not contain aliases to the new type declarations).
func (r *Files) checkGenProtoConflict(path string) {
if r != GlobalFiles {
return
}
var prevPath string
const prevModule = "google.golang.org/genproto"
const prevVersion = "cb27e3aa (May 26th, 2020)"
switch path {
case "google/protobuf/field_mask.proto":
prevPath = prevModule + "/protobuf/field_mask"
case "google/protobuf/api.proto":
prevPath = prevModule + "/protobuf/api"
case "google/protobuf/type.proto":
prevPath = prevModule + "/protobuf/ptype"
case "google/protobuf/source_context.proto":
prevPath = prevModule + "/protobuf/source_context"
default:
return
}
pkgName := strings.TrimSuffix(strings.TrimPrefix(path, "google/protobuf/"), ".proto")
pkgName = strings.Replace(pkgName, "_", "", -1) + "pb" // e.g., "field_mask" => "fieldmaskpb"
currPath := "google.golang.org/protobuf/types/known/" + pkgName
panic(fmt.Sprintf(""+
"duplicate registration of %q\n"+
"\n"+
"The generated definition for this file has moved:\n"+
"\tfrom: %q\n"+
"\tto: %q\n"+
"A dependency on the %q module must\n"+
"be at version %v or higher.\n"+
"\n"+
"Upgrade the dependency by running:\n"+
"\tgo get -u %v\n",
path, prevPath, currPath, prevModule, prevVersion, prevPath))
}
// FindDescriptorByName looks up a descriptor by the full name.
//
// This returns (nil, [NotFound]) if not found.
func (r *Files) FindDescriptorByName(name protoreflect.FullName) (protoreflect.Descriptor, error) {
if r == nil {
return nil, NotFound
}
if r == GlobalFiles {
globalMutex.RLock()
defer globalMutex.RUnlock()
}
prefix := name
suffix := nameSuffix("")
for prefix != "" {
if d, ok := r.descsByName[prefix]; ok {
switch d := d.(type) {
case protoreflect.EnumDescriptor:
if d.FullName() == name {
return d, nil
}
case protoreflect.EnumValueDescriptor:
if d.FullName() == name {
return d, nil
}
case protoreflect.MessageDescriptor:
if d.FullName() == name {
return d, nil
}
if d := findDescriptorInMessage(d, suffix); d != nil && d.FullName() == name {
return d, nil
}
case protoreflect.ExtensionDescriptor:
if d.FullName() == name {
return d, nil
}
case protoreflect.ServiceDescriptor:
if d.FullName() == name {
return d, nil
}
if d := d.Methods().ByName(suffix.Pop()); d != nil && d.FullName() == name {
return d, nil
}
}
return nil, NotFound
}
prefix = prefix.Parent()
suffix = nameSuffix(name[len(prefix)+len("."):])
}
return nil, NotFound
}
func findDescriptorInMessage(md protoreflect.MessageDescriptor, suffix nameSuffix) protoreflect.Descriptor {
name := suffix.Pop()
if suffix == "" {
if ed := md.Enums().ByName(name); ed != nil {
return ed
}
for i := md.Enums().Len() - 1; i >= 0; i-- {
if vd := md.Enums().Get(i).Values().ByName(name); vd != nil {
return vd
}
}
if xd := md.Extensions().ByName(name); xd != nil {
return xd
}
if fd := md.Fields().ByName(name); fd != nil {
return fd
}
if od := md.Oneofs().ByName(name); od != nil {
return od
}
}
if md := md.Messages().ByName(name); md != nil {
if suffix == "" {
return md
}
return findDescriptorInMessage(md, suffix)
}
return nil
}
type nameSuffix string
func (s *nameSuffix) Pop() (name protoreflect.Name) {
if i := strings.IndexByte(string(*s), '.'); i >= 0 {
name, *s = protoreflect.Name((*s)[:i]), (*s)[i+1:]
} else {
name, *s = protoreflect.Name((*s)), ""
}
return name
}
// FindFileByPath looks up a file by the path.
//
// This returns (nil, [NotFound]) if not found.
// This returns an error if multiple files have the same path.
func (r *Files) FindFileByPath(path string) (protoreflect.FileDescriptor, error) {
if r == nil {
return nil, NotFound
}
if r == GlobalFiles {
globalMutex.RLock()
defer globalMutex.RUnlock()
}
fds := r.filesByPath[path]
switch len(fds) {
case 0:
return nil, NotFound
case 1:
return fds[0], nil
default:
return nil, errors.New("multiple files named %q", path)
}
}
// NumFiles reports the number of registered files,
// including duplicate files with the same name.
func (r *Files) NumFiles() int {
if r == nil {
return 0
}
if r == GlobalFiles {
globalMutex.RLock()
defer globalMutex.RUnlock()
}
return r.numFiles
}
// RangeFiles iterates over all registered files while f returns true.
// If multiple files have the same name, RangeFiles iterates over all of them.
// The iteration order is undefined.
func (r *Files) RangeFiles(f func(protoreflect.FileDescriptor) bool) {
if r == nil {
return
}
if r == GlobalFiles {
globalMutex.RLock()
defer globalMutex.RUnlock()
}
for _, files := range r.filesByPath {
for _, file := range files {
if !f(file) {
return
}
}
}
}
// NumFilesByPackage reports the number of registered files in a proto package.
func (r *Files) NumFilesByPackage(name protoreflect.FullName) int {
if r == nil {
return 0
}
if r == GlobalFiles {
globalMutex.RLock()
defer globalMutex.RUnlock()
}
p, ok := r.descsByName[name].(*packageDescriptor)
if !ok {
return 0
}
return len(p.files)
}
// RangeFilesByPackage iterates over all registered files in a given proto package
// while f returns true. The iteration order is undefined.
func (r *Files) RangeFilesByPackage(name protoreflect.FullName, f func(protoreflect.FileDescriptor) bool) {
if r == nil {
return
}
if r == GlobalFiles {
globalMutex.RLock()
defer globalMutex.RUnlock()
}
p, ok := r.descsByName[name].(*packageDescriptor)
if !ok {
return
}
for _, file := range p.files {
if !f(file) {
return
}
}
}
// rangeTopLevelDescriptors iterates over all top-level descriptors in a file
// which will be directly entered into the registry.
func rangeTopLevelDescriptors(fd protoreflect.FileDescriptor, f func(protoreflect.Descriptor)) {
eds := fd.Enums()
for i := eds.Len() - 1; i >= 0; i-- {
f(eds.Get(i))
vds := eds.Get(i).Values()
for i := vds.Len() - 1; i >= 0; i-- {
f(vds.Get(i))
}
}
mds := fd.Messages()
for i := mds.Len() - 1; i >= 0; i-- {
f(mds.Get(i))
}
xds := fd.Extensions()
for i := xds.Len() - 1; i >= 0; i-- {
f(xds.Get(i))
}
sds := fd.Services()
for i := sds.Len() - 1; i >= 0; i-- {
f(sds.Get(i))
}
}
// MessageTypeResolver is an interface for looking up messages.
//
// A compliant implementation must deterministically return the same type
// if no error is encountered.
//
// The [Types] type implements this interface.
type MessageTypeResolver interface {
// FindMessageByName looks up a message by its full name.
// E.g., "google.protobuf.Any"
//
// This return (nil, NotFound) if not found.
FindMessageByName(message protoreflect.FullName) (protoreflect.MessageType, error)
// FindMessageByURL looks up a message by a URL identifier.
// See documentation on google.protobuf.Any.type_url for the URL format.
//
// This returns (nil, NotFound) if not found.
FindMessageByURL(url string) (protoreflect.MessageType, error)
}
// ExtensionTypeResolver is an interface for looking up extensions.
//
// A compliant implementation must deterministically return the same type
// if no error is encountered.
//
// The [Types] type implements this interface.
type ExtensionTypeResolver interface {
// FindExtensionByName looks up a extension field by the field's full name.
// Note that this is the full name of the field as determined by
// where the extension is declared and is unrelated to the full name of the
// message being extended.
//
// This returns (nil, NotFound) if not found.
FindExtensionByName(field protoreflect.FullName) (protoreflect.ExtensionType, error)
// FindExtensionByNumber looks up a extension field by the field number
// within some parent message, identified by full name.
//
// This returns (nil, NotFound) if not found.
FindExtensionByNumber(message protoreflect.FullName, field protoreflect.FieldNumber) (protoreflect.ExtensionType, error)
}
var (
_ MessageTypeResolver = (*Types)(nil)
_ ExtensionTypeResolver = (*Types)(nil)
)
// Types is a registry for looking up or iterating over descriptor types.
// The Find and Range methods are safe for concurrent use.
type Types struct {
typesByName typesByName
extensionsByMessage extensionsByMessage
numEnums int
numMessages int
numExtensions int
}
type (
typesByName map[protoreflect.FullName]any
extensionsByMessage map[protoreflect.FullName]extensionsByNumber
extensionsByNumber map[protoreflect.FieldNumber]protoreflect.ExtensionType
)
// RegisterMessage registers the provided message type.
//
// If a naming conflict occurs, the type is not registered and an error is returned.
func (r *Types) RegisterMessage(mt protoreflect.MessageType) error {
// Under rare circumstances getting the descriptor might recursively
// examine the registry, so fetch it before locking.
md := mt.Descriptor()
if r == GlobalTypes {
globalMutex.Lock()
defer globalMutex.Unlock()
}
if err := r.register("message", md, mt); err != nil {
return err
}
r.numMessages++
return nil
}
// RegisterEnum registers the provided enum type.
//
// If a naming conflict occurs, the type is not registered and an error is returned.
func (r *Types) RegisterEnum(et protoreflect.EnumType) error {
// Under rare circumstances getting the descriptor might recursively
// examine the registry, so fetch it before locking.
ed := et.Descriptor()
if r == GlobalTypes {
globalMutex.Lock()
defer globalMutex.Unlock()
}
if err := r.register("enum", ed, et); err != nil {
return err
}
r.numEnums++
return nil
}
// RegisterExtension registers the provided extension type.
//
// If a naming conflict occurs, the type is not registered and an error is returned.
func (r *Types) RegisterExtension(xt protoreflect.ExtensionType) error {
// Under rare circumstances getting the descriptor might recursively
// examine the registry, so fetch it before locking.
//
// A known case where this can happen: Fetching the TypeDescriptor for a
// legacy ExtensionDesc can consult the global registry.
xd := xt.TypeDescriptor()
if r == GlobalTypes {
globalMutex.Lock()
defer globalMutex.Unlock()
}
field := xd.Number()
message := xd.ContainingMessage().FullName()
if prev := r.extensionsByMessage[message][field]; prev != nil {
err := errors.New("extension number %d is already registered on message %v", field, message)
err = amendErrorWithCaller(err, prev, xt)
if !(r == GlobalTypes && ignoreConflict(xd, err)) {
return err
}
}
if err := r.register("extension", xd, xt); err != nil {
return err
}
if r.extensionsByMessage == nil {
r.extensionsByMessage = make(extensionsByMessage)
}
if r.extensionsByMessage[message] == nil {
r.extensionsByMessage[message] = make(extensionsByNumber)
}
r.extensionsByMessage[message][field] = xt
r.numExtensions++
return nil
}
func (r *Types) register(kind string, desc protoreflect.Descriptor, typ any) error {
name := desc.FullName()
prev := r.typesByName[name]
if prev != nil {
err := errors.New("%v %v is already registered", kind, name)
err = amendErrorWithCaller(err, prev, typ)
if !(r == GlobalTypes && ignoreConflict(desc, err)) {
return err
}
}
if r.typesByName == nil {
r.typesByName = make(typesByName)
}
r.typesByName[name] = typ
return nil
}
// FindEnumByName looks up an enum by its full name.
// E.g., "google.protobuf.Field.Kind".
//
// This returns (nil, [NotFound]) if not found.
func (r *Types) FindEnumByName(enum protoreflect.FullName) (protoreflect.EnumType, error) {
if r == nil {
return nil, NotFound
}
if r == GlobalTypes {
globalMutex.RLock()
defer globalMutex.RUnlock()
}
if v := r.typesByName[enum]; v != nil {
if et, _ := v.(protoreflect.EnumType); et != nil {
return et, nil
}
return nil, errors.New("found wrong type: got %v, want enum", typeName(v))
}
return nil, NotFound
}
// FindMessageByName looks up a message by its full name,
// e.g. "google.protobuf.Any".
//
// This returns (nil, [NotFound]) if not found.
func (r *Types) FindMessageByName(message protoreflect.FullName) (protoreflect.MessageType, error) {
if r == nil {
return nil, NotFound
}
if r == GlobalTypes {
globalMutex.RLock()
defer globalMutex.RUnlock()
}
if v := r.typesByName[message]; v != nil {
if mt, _ := v.(protoreflect.MessageType); mt != nil {
return mt, nil
}
return nil, errors.New("found wrong type: got %v, want message", typeName(v))
}
return nil, NotFound
}
// FindMessageByURL looks up a message by a URL identifier.
// See documentation on google.protobuf.Any.type_url for the URL format.
//
// This returns (nil, [NotFound]) if not found.
func (r *Types) FindMessageByURL(url string) (protoreflect.MessageType, error) {
// This function is similar to FindMessageByName but
// truncates anything before and including '/' in the URL.
if r == nil {
return nil, NotFound
}
if r == GlobalTypes {
globalMutex.RLock()
defer globalMutex.RUnlock()
}
message := protoreflect.FullName(url)
if i := strings.LastIndexByte(url, '/'); i >= 0 {
message = message[i+len("/"):]
}
if v := r.typesByName[message]; v != nil {
if mt, _ := v.(protoreflect.MessageType); mt != nil {
return mt, nil
}
return nil, errors.New("found wrong type: got %v, want message", typeName(v))
}
return nil, NotFound
}
// FindExtensionByName looks up a extension field by the field's full name.
// Note that this is the full name of the field as determined by
// where the extension is declared and is unrelated to the full name of the
// message being extended.
//
// This returns (nil, [NotFound]) if not found.
func (r *Types) FindExtensionByName(field protoreflect.FullName) (protoreflect.ExtensionType, error) {
if r == nil {
return nil, NotFound
}
if r == GlobalTypes {
globalMutex.RLock()
defer globalMutex.RUnlock()
}
if v := r.typesByName[field]; v != nil {
if xt, _ := v.(protoreflect.ExtensionType); xt != nil {
return xt, nil
}
// MessageSet extensions are special in that the name of the extension
// is the name of the message type used to extend the MessageSet.
// This naming scheme is used by text and JSON serialization.
//
// This feature is protected by the ProtoLegacy flag since MessageSets
// are a proto1 feature that is long deprecated.
if flags.ProtoLegacy {
if _, ok := v.(protoreflect.MessageType); ok {
field := field.Append(messageset.ExtensionName)
if v := r.typesByName[field]; v != nil {
if xt, _ := v.(protoreflect.ExtensionType); xt != nil {
if messageset.IsMessageSetExtension(xt.TypeDescriptor()) {
return xt, nil
}
}
}
}
}
return nil, errors.New("found wrong type: got %v, want extension", typeName(v))
}
return nil, NotFound
}
// FindExtensionByNumber looks up a extension field by the field number
// within some parent message, identified by full name.
//
// This returns (nil, [NotFound]) if not found.
func (r *Types) FindExtensionByNumber(message protoreflect.FullName, field protoreflect.FieldNumber) (protoreflect.ExtensionType, error) {
if r == nil {
return nil, NotFound
}
if r == GlobalTypes {
globalMutex.RLock()
defer globalMutex.RUnlock()
}
if xt, ok := r.extensionsByMessage[message][field]; ok {
return xt, nil
}
return nil, NotFound
}
// NumEnums reports the number of registered enums.
func (r *Types) NumEnums() int {
if r == nil {
return 0
}
if r == GlobalTypes {
globalMutex.RLock()
defer globalMutex.RUnlock()
}
return r.numEnums
}
// RangeEnums iterates over all registered enums while f returns true.
// Iteration order is undefined.
func (r *Types) RangeEnums(f func(protoreflect.EnumType) bool) {
if r == nil {
return
}
if r == GlobalTypes {
globalMutex.RLock()
defer globalMutex.RUnlock()
}
for _, typ := range r.typesByName {
if et, ok := typ.(protoreflect.EnumType); ok {
if !f(et) {
return
}
}
}
}
// NumMessages reports the number of registered messages.
func (r *Types) NumMessages() int {
if r == nil {
return 0
}
if r == GlobalTypes {
globalMutex.RLock()
defer globalMutex.RUnlock()
}
return r.numMessages
}
// RangeMessages iterates over all registered messages while f returns true.
// Iteration order is undefined.
func (r *Types) RangeMessages(f func(protoreflect.MessageType) bool) {
if r == nil {
return
}
if r == GlobalTypes {
globalMutex.RLock()
defer globalMutex.RUnlock()
}
for _, typ := range r.typesByName {
if mt, ok := typ.(protoreflect.MessageType); ok {
if !f(mt) {
return
}
}
}
}
// NumExtensions reports the number of registered extensions.
func (r *Types) NumExtensions() int {
if r == nil {
return 0
}
if r == GlobalTypes {
globalMutex.RLock()
defer globalMutex.RUnlock()
}
return r.numExtensions
}
// RangeExtensions iterates over all registered extensions while f returns true.
// Iteration order is undefined.
func (r *Types) RangeExtensions(f func(protoreflect.ExtensionType) bool) {
if r == nil {
return
}
if r == GlobalTypes {
globalMutex.RLock()
defer globalMutex.RUnlock()
}
for _, typ := range r.typesByName {
if xt, ok := typ.(protoreflect.ExtensionType); ok {
if !f(xt) {
return
}
}
}
}
// NumExtensionsByMessage reports the number of registered extensions for
// a given message type.
func (r *Types) NumExtensionsByMessage(message protoreflect.FullName) int {
if r == nil {
return 0
}
if r == GlobalTypes {
globalMutex.RLock()
defer globalMutex.RUnlock()
}
return len(r.extensionsByMessage[message])
}
// RangeExtensionsByMessage iterates over all registered extensions filtered
// by a given message type while f returns true. Iteration order is undefined.
func (r *Types) RangeExtensionsByMessage(message protoreflect.FullName, f func(protoreflect.ExtensionType) bool) {
if r == nil {
return
}
if r == GlobalTypes {
globalMutex.RLock()
defer globalMutex.RUnlock()
}
for _, xt := range r.extensionsByMessage[message] {
if !f(xt) {
return
}
}
}
func typeName(t any) string {
switch t.(type) {
case protoreflect.EnumType:
return "enum"
case protoreflect.MessageType:
return "message"
case protoreflect.ExtensionType:
return "extension"
default:
return fmt.Sprintf("%T", t)
}
}
func amendErrorWithCaller(err error, prev, curr any) error {
prevPkg := goPackage(prev)
currPkg := goPackage(curr)
if prevPkg == "" || currPkg == "" || prevPkg == currPkg {
return err
}
return errors.New("%s\n\tpreviously from: %q\n\tcurrently from: %q", err, prevPkg, currPkg)
}
func goPackage(v any) string {
switch d := v.(type) {
case protoreflect.EnumType:
v = d.Descriptor()
case protoreflect.MessageType:
v = d.Descriptor()
case protoreflect.ExtensionType:
v = d.TypeDescriptor()
}
if d, ok := v.(protoreflect.Descriptor); ok {
v = d.ParentFile()
}
if d, ok := v.(interface{ GoPackagePath() string }); ok {
return d.GoPackagePath()
}
return ""
}