proto.go 10 KB

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