github.com/cosmos/cosmos-proto@v1.0.0-beta.3/features/fastreflection/descriptors.go (about)

     1  package fastreflection
     2  
     3  import (
     4  	"fmt"
     5  	"github.com/cosmos/cosmos-proto/generator"
     6  	"google.golang.org/protobuf/reflect/protoreflect"
     7  
     8  	"github.com/cosmos/cosmos-proto/features/fastreflection/copied"
     9  	"google.golang.org/protobuf/compiler/protogen"
    10  )
    11  
    12  type descGen struct {
    13  	*generator.GeneratedFile
    14  	file    *protogen.File
    15  	message *protogen.Message
    16  }
    17  
    18  func (g *descGen) generate() {
    19  	// init is going to initialize descriptor information
    20  	g.P("var (")
    21  	g.P(messageDescriptorName(g.message), " ", protoreflectPkg.Ident("MessageDescriptor"))
    22  	for _, field := range g.message.Fields {
    23  		g.P(fieldDescriptorName(field), " ", protoreflectPkg.Ident("FieldDescriptor"))
    24  	}
    25  	g.P(")")
    26  	g.P("func init() {")
    27  	g.P(copied.InitFunctionName(g.file), "()")
    28  	// we need to consider nested messages. so we try to recreate the hierarchy
    29  	// ex messageA contains messageB contains messageC
    30  	args := []interface{}{messageDescriptorName(g.message), " = ", g.file.GoDescriptorIdent.GoName}
    31  	for _, md := range findParents(g.message.Desc) {
    32  		args = append(args, ".Messages().ByName(\"", md.Name(), "\")")
    33  	}
    34  	g.P(args...)
    35  	for _, field := range g.message.Fields {
    36  		g.P(fieldDescriptorName(field), " = ", messageDescriptorName(g.message), ".Fields().ByName(\"", field.Desc.Name(), "\")")
    37  	}
    38  	g.P("}")
    39  }
    40  
    41  func fieldDescriptorName(field *protogen.Field) string {
    42  	return fmt.Sprintf("fd_%s_%s", field.Parent.GoIdent.GoName, field.Desc.Name())
    43  }
    44  
    45  func findParents(message protoreflect.MessageDescriptor) []protoreflect.MessageDescriptor {
    46  	parent, ok := message.Parent().(protoreflect.MessageDescriptor)
    47  	if !ok {
    48  		return []protoreflect.MessageDescriptor{message}
    49  	}
    50  
    51  	return append(findParents(parent), message)
    52  }