reflect/protoreflect: add helper methods to FieldDescriptor
Added API:
FieldDescriptor.IsExtension
FieldDescriptor.IsList
FieldDescriptor.MapKey
FieldDescriptor.MapValue
FieldDescriptor.ContainingOneof
FieldDescriptor.ContainingMessage
Deprecated API (to be removed in subsequent CL):
FieldDescriptor.Oneof
FieldDescriptor.Extendee
These methods help cleanup several common usage patterns.
Change-Id: I9a3ffabc2edb2173c536509b22f330f98bba7cf3
Reviewed-on: https://go-review.googlesource.com/c/protobuf/+/176977
Reviewed-by: Damien Neil <dneil@google.com>
diff --git a/cmd/protoc-gen-go/internal_gengo/main.go b/cmd/protoc-gen-go/internal_gengo/main.go
index 9e11fb0..cedda8b 100644
--- a/cmd/protoc-gen-go/internal_gengo/main.go
+++ b/cmd/protoc-gen-go/internal_gengo/main.go
@@ -559,20 +559,21 @@
goType = "[]byte"
pointer = false
case protoreflect.MessageKind, protoreflect.GroupKind:
- if field.Desc.IsMap() {
- keyType, _ := fieldGoType(g, field.Message.Fields[0])
- valType, _ := fieldGoType(g, field.Message.Fields[1])
- return fmt.Sprintf("map[%v]%v", keyType, valType), false
- }
goType = "*" + g.QualifiedGoIdent(field.Message.GoIdent)
pointer = false
}
- if field.Desc.Cardinality() == protoreflect.Repeated {
+ switch {
+ case field.Desc.IsList():
goType = "[]" + goType
pointer = false
+ case field.Desc.IsMap():
+ keyType, _ := fieldGoType(g, field.Message.Fields[0])
+ valType, _ := fieldGoType(g, field.Message.Fields[1])
+ return fmt.Sprintf("map[%v]%v", keyType, valType), false
}
+
// Extension fields always have pointer type, even when defined in a proto3 file.
- if field.Desc.Syntax() == protoreflect.Proto3 && field.Desc.Extendee() == nil {
+ if field.Desc.Syntax() == protoreflect.Proto3 && !field.Desc.IsExtension() {
pointer = false
}
return goType, pointer
@@ -587,7 +588,7 @@
}
func fieldDefaultValue(g *protogen.GeneratedFile, message *protogen.Message, field *protogen.Field) string {
- if field.Desc.Cardinality() == protoreflect.Repeated {
+ if field.Desc.IsList() {
return "nil"
}
if field.Desc.HasDefault() {
@@ -653,7 +654,7 @@
g.P("var (")
for i, extension := range f.allExtensions {
ed := extension.Desc
- targetName := string(ed.Extendee().FullName())
+ targetName := string(ed.ContainingMessage().FullName())
typeName := ed.Kind().String()
switch ed.Kind() {
case protoreflect.EnumKind: