blob: 9b880aa8c961d6a7dc1ae31624507d6191b4fa6e [file] [log] [blame]
khenaidoo7d3c5582021-08-11 18:09:44 -04001// Copyright 2019 The Go Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style
3// license that can be found in the LICENSE file.
4
5package protodesc
6
7import (
8 "fmt"
9 "strings"
10
11 "google.golang.org/protobuf/internal/encoding/defval"
12 "google.golang.org/protobuf/internal/strs"
13 "google.golang.org/protobuf/proto"
14 "google.golang.org/protobuf/reflect/protoreflect"
15
16 "google.golang.org/protobuf/types/descriptorpb"
17)
18
Akash Reddy Kankanala92dfdf82025-03-23 22:07:09 +053019// ToFileDescriptorProto copies a [protoreflect.FileDescriptor] into a
khenaidoo7d3c5582021-08-11 18:09:44 -040020// google.protobuf.FileDescriptorProto message.
21func ToFileDescriptorProto(file protoreflect.FileDescriptor) *descriptorpb.FileDescriptorProto {
22 p := &descriptorpb.FileDescriptorProto{
23 Name: proto.String(file.Path()),
24 Options: proto.Clone(file.Options()).(*descriptorpb.FileOptions),
25 }
26 if file.Package() != "" {
27 p.Package = proto.String(string(file.Package()))
28 }
29 for i, imports := 0, file.Imports(); i < imports.Len(); i++ {
30 imp := imports.Get(i)
31 p.Dependency = append(p.Dependency, imp.Path())
32 if imp.IsPublic {
33 p.PublicDependency = append(p.PublicDependency, int32(i))
34 }
khenaidoo7d3c5582021-08-11 18:09:44 -040035 }
36 for i, locs := 0, file.SourceLocations(); i < locs.Len(); i++ {
37 loc := locs.Get(i)
38 l := &descriptorpb.SourceCodeInfo_Location{}
39 l.Path = append(l.Path, loc.Path...)
40 if loc.StartLine == loc.EndLine {
41 l.Span = []int32{int32(loc.StartLine), int32(loc.StartColumn), int32(loc.EndColumn)}
42 } else {
43 l.Span = []int32{int32(loc.StartLine), int32(loc.StartColumn), int32(loc.EndLine), int32(loc.EndColumn)}
44 }
45 l.LeadingDetachedComments = append([]string(nil), loc.LeadingDetachedComments...)
46 if loc.LeadingComments != "" {
47 l.LeadingComments = proto.String(loc.LeadingComments)
48 }
49 if loc.TrailingComments != "" {
50 l.TrailingComments = proto.String(loc.TrailingComments)
51 }
52 if p.SourceCodeInfo == nil {
53 p.SourceCodeInfo = &descriptorpb.SourceCodeInfo{}
54 }
55 p.SourceCodeInfo.Location = append(p.SourceCodeInfo.Location, l)
56
57 }
58 for i, messages := 0, file.Messages(); i < messages.Len(); i++ {
59 p.MessageType = append(p.MessageType, ToDescriptorProto(messages.Get(i)))
60 }
61 for i, enums := 0, file.Enums(); i < enums.Len(); i++ {
62 p.EnumType = append(p.EnumType, ToEnumDescriptorProto(enums.Get(i)))
63 }
64 for i, services := 0, file.Services(); i < services.Len(); i++ {
65 p.Service = append(p.Service, ToServiceDescriptorProto(services.Get(i)))
66 }
67 for i, exts := 0, file.Extensions(); i < exts.Len(); i++ {
68 p.Extension = append(p.Extension, ToFieldDescriptorProto(exts.Get(i)))
69 }
Akash Reddy Kankanala92dfdf82025-03-23 22:07:09 +053070 if syntax := file.Syntax(); syntax != protoreflect.Proto2 && syntax.IsValid() {
khenaidoo7d3c5582021-08-11 18:09:44 -040071 p.Syntax = proto.String(file.Syntax().String())
72 }
Akash Reddy Kankanala92dfdf82025-03-23 22:07:09 +053073 if file.Syntax() == protoreflect.Editions {
74 desc := file
75 if fileImportDesc, ok := file.(protoreflect.FileImport); ok {
76 desc = fileImportDesc.FileDescriptor
77 }
78
79 if editionsInterface, ok := desc.(interface{ Edition() int32 }); ok {
80 p.Edition = descriptorpb.Edition(editionsInterface.Edition()).Enum()
81 }
82 }
khenaidoo7d3c5582021-08-11 18:09:44 -040083 return p
84}
85
Akash Reddy Kankanala92dfdf82025-03-23 22:07:09 +053086// ToDescriptorProto copies a [protoreflect.MessageDescriptor] into a
khenaidoo7d3c5582021-08-11 18:09:44 -040087// google.protobuf.DescriptorProto message.
88func ToDescriptorProto(message protoreflect.MessageDescriptor) *descriptorpb.DescriptorProto {
89 p := &descriptorpb.DescriptorProto{
90 Name: proto.String(string(message.Name())),
91 Options: proto.Clone(message.Options()).(*descriptorpb.MessageOptions),
92 }
93 for i, fields := 0, message.Fields(); i < fields.Len(); i++ {
94 p.Field = append(p.Field, ToFieldDescriptorProto(fields.Get(i)))
95 }
96 for i, exts := 0, message.Extensions(); i < exts.Len(); i++ {
97 p.Extension = append(p.Extension, ToFieldDescriptorProto(exts.Get(i)))
98 }
99 for i, messages := 0, message.Messages(); i < messages.Len(); i++ {
100 p.NestedType = append(p.NestedType, ToDescriptorProto(messages.Get(i)))
101 }
102 for i, enums := 0, message.Enums(); i < enums.Len(); i++ {
103 p.EnumType = append(p.EnumType, ToEnumDescriptorProto(enums.Get(i)))
104 }
105 for i, xranges := 0, message.ExtensionRanges(); i < xranges.Len(); i++ {
106 xrange := xranges.Get(i)
107 p.ExtensionRange = append(p.ExtensionRange, &descriptorpb.DescriptorProto_ExtensionRange{
108 Start: proto.Int32(int32(xrange[0])),
109 End: proto.Int32(int32(xrange[1])),
110 Options: proto.Clone(message.ExtensionRangeOptions(i)).(*descriptorpb.ExtensionRangeOptions),
111 })
112 }
113 for i, oneofs := 0, message.Oneofs(); i < oneofs.Len(); i++ {
114 p.OneofDecl = append(p.OneofDecl, ToOneofDescriptorProto(oneofs.Get(i)))
115 }
116 for i, ranges := 0, message.ReservedRanges(); i < ranges.Len(); i++ {
117 rrange := ranges.Get(i)
118 p.ReservedRange = append(p.ReservedRange, &descriptorpb.DescriptorProto_ReservedRange{
119 Start: proto.Int32(int32(rrange[0])),
120 End: proto.Int32(int32(rrange[1])),
121 })
122 }
123 for i, names := 0, message.ReservedNames(); i < names.Len(); i++ {
124 p.ReservedName = append(p.ReservedName, string(names.Get(i)))
125 }
126 return p
127}
128
Akash Reddy Kankanala92dfdf82025-03-23 22:07:09 +0530129// ToFieldDescriptorProto copies a [protoreflect.FieldDescriptor] into a
khenaidoo7d3c5582021-08-11 18:09:44 -0400130// google.protobuf.FieldDescriptorProto message.
131func ToFieldDescriptorProto(field protoreflect.FieldDescriptor) *descriptorpb.FieldDescriptorProto {
132 p := &descriptorpb.FieldDescriptorProto{
133 Name: proto.String(string(field.Name())),
134 Number: proto.Int32(int32(field.Number())),
135 Label: descriptorpb.FieldDescriptorProto_Label(field.Cardinality()).Enum(),
136 Options: proto.Clone(field.Options()).(*descriptorpb.FieldOptions),
137 }
138 if field.IsExtension() {
139 p.Extendee = fullNameOf(field.ContainingMessage())
140 }
141 if field.Kind().IsValid() {
142 p.Type = descriptorpb.FieldDescriptorProto_Type(field.Kind()).Enum()
143 }
144 if field.Enum() != nil {
145 p.TypeName = fullNameOf(field.Enum())
146 }
147 if field.Message() != nil {
148 p.TypeName = fullNameOf(field.Message())
149 }
150 if field.HasJSONName() {
151 // A bug in older versions of protoc would always populate the
152 // "json_name" option for extensions when it is meaningless.
153 // When it did so, it would always use the camel-cased field name.
154 if field.IsExtension() {
155 p.JsonName = proto.String(strs.JSONCamelCase(string(field.Name())))
156 } else {
157 p.JsonName = proto.String(field.JSONName())
158 }
159 }
160 if field.Syntax() == protoreflect.Proto3 && field.HasOptionalKeyword() {
161 p.Proto3Optional = proto.Bool(true)
162 }
Akash Reddy Kankanala92dfdf82025-03-23 22:07:09 +0530163 if field.Syntax() == protoreflect.Editions {
164 // Editions have no group keyword, this type is only set so that downstream users continue
165 // treating this as delimited encoding.
166 if p.GetType() == descriptorpb.FieldDescriptorProto_TYPE_GROUP {
167 p.Type = descriptorpb.FieldDescriptorProto_TYPE_MESSAGE.Enum()
168 }
169 // Editions have no required keyword, this label is only set so that downstream users continue
170 // treating it as required.
171 if p.GetLabel() == descriptorpb.FieldDescriptorProto_LABEL_REQUIRED {
172 p.Label = descriptorpb.FieldDescriptorProto_LABEL_OPTIONAL.Enum()
173 }
174 }
khenaidoo7d3c5582021-08-11 18:09:44 -0400175 if field.HasDefault() {
176 def, err := defval.Marshal(field.Default(), field.DefaultEnumValue(), field.Kind(), defval.Descriptor)
177 if err != nil && field.DefaultEnumValue() != nil {
178 def = string(field.DefaultEnumValue().Name()) // occurs for unresolved enum values
179 } else if err != nil {
180 panic(fmt.Sprintf("%v: %v", field.FullName(), err))
181 }
182 p.DefaultValue = proto.String(def)
183 }
184 if oneof := field.ContainingOneof(); oneof != nil {
185 p.OneofIndex = proto.Int32(int32(oneof.Index()))
186 }
187 return p
188}
189
Akash Reddy Kankanala92dfdf82025-03-23 22:07:09 +0530190// ToOneofDescriptorProto copies a [protoreflect.OneofDescriptor] into a
khenaidoo7d3c5582021-08-11 18:09:44 -0400191// google.protobuf.OneofDescriptorProto message.
192func ToOneofDescriptorProto(oneof protoreflect.OneofDescriptor) *descriptorpb.OneofDescriptorProto {
193 return &descriptorpb.OneofDescriptorProto{
194 Name: proto.String(string(oneof.Name())),
195 Options: proto.Clone(oneof.Options()).(*descriptorpb.OneofOptions),
196 }
197}
198
Akash Reddy Kankanala92dfdf82025-03-23 22:07:09 +0530199// ToEnumDescriptorProto copies a [protoreflect.EnumDescriptor] into a
khenaidoo7d3c5582021-08-11 18:09:44 -0400200// google.protobuf.EnumDescriptorProto message.
201func ToEnumDescriptorProto(enum protoreflect.EnumDescriptor) *descriptorpb.EnumDescriptorProto {
202 p := &descriptorpb.EnumDescriptorProto{
203 Name: proto.String(string(enum.Name())),
204 Options: proto.Clone(enum.Options()).(*descriptorpb.EnumOptions),
205 }
206 for i, values := 0, enum.Values(); i < values.Len(); i++ {
207 p.Value = append(p.Value, ToEnumValueDescriptorProto(values.Get(i)))
208 }
209 for i, ranges := 0, enum.ReservedRanges(); i < ranges.Len(); i++ {
210 rrange := ranges.Get(i)
211 p.ReservedRange = append(p.ReservedRange, &descriptorpb.EnumDescriptorProto_EnumReservedRange{
212 Start: proto.Int32(int32(rrange[0])),
213 End: proto.Int32(int32(rrange[1])),
214 })
215 }
216 for i, names := 0, enum.ReservedNames(); i < names.Len(); i++ {
217 p.ReservedName = append(p.ReservedName, string(names.Get(i)))
218 }
219 return p
220}
221
Akash Reddy Kankanala92dfdf82025-03-23 22:07:09 +0530222// ToEnumValueDescriptorProto copies a [protoreflect.EnumValueDescriptor] into a
khenaidoo7d3c5582021-08-11 18:09:44 -0400223// google.protobuf.EnumValueDescriptorProto message.
224func ToEnumValueDescriptorProto(value protoreflect.EnumValueDescriptor) *descriptorpb.EnumValueDescriptorProto {
225 return &descriptorpb.EnumValueDescriptorProto{
226 Name: proto.String(string(value.Name())),
227 Number: proto.Int32(int32(value.Number())),
228 Options: proto.Clone(value.Options()).(*descriptorpb.EnumValueOptions),
229 }
230}
231
Akash Reddy Kankanala92dfdf82025-03-23 22:07:09 +0530232// ToServiceDescriptorProto copies a [protoreflect.ServiceDescriptor] into a
khenaidoo7d3c5582021-08-11 18:09:44 -0400233// google.protobuf.ServiceDescriptorProto message.
234func ToServiceDescriptorProto(service protoreflect.ServiceDescriptor) *descriptorpb.ServiceDescriptorProto {
235 p := &descriptorpb.ServiceDescriptorProto{
236 Name: proto.String(string(service.Name())),
237 Options: proto.Clone(service.Options()).(*descriptorpb.ServiceOptions),
238 }
239 for i, methods := 0, service.Methods(); i < methods.Len(); i++ {
240 p.Method = append(p.Method, ToMethodDescriptorProto(methods.Get(i)))
241 }
242 return p
243}
244
Akash Reddy Kankanala92dfdf82025-03-23 22:07:09 +0530245// ToMethodDescriptorProto copies a [protoreflect.MethodDescriptor] into a
khenaidoo7d3c5582021-08-11 18:09:44 -0400246// google.protobuf.MethodDescriptorProto message.
247func ToMethodDescriptorProto(method protoreflect.MethodDescriptor) *descriptorpb.MethodDescriptorProto {
248 p := &descriptorpb.MethodDescriptorProto{
249 Name: proto.String(string(method.Name())),
250 InputType: fullNameOf(method.Input()),
251 OutputType: fullNameOf(method.Output()),
252 Options: proto.Clone(method.Options()).(*descriptorpb.MethodOptions),
253 }
254 if method.IsStreamingClient() {
255 p.ClientStreaming = proto.Bool(true)
256 }
257 if method.IsStreamingServer() {
258 p.ServerStreaming = proto.Bool(true)
259 }
260 return p
261}
262
263func fullNameOf(d protoreflect.Descriptor) *string {
264 if d == nil {
265 return nil
266 }
267 if strings.HasPrefix(string(d.FullName()), unknownPrefix) {
268 return proto.String(string(d.FullName()[len(unknownPrefix):]))
269 }
270 return proto.String("." + string(d.FullName()))
271}