desc.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. // Copyright 2018 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 provides functionality for converting
  5. // FileDescriptorProto messages to/from [protoreflect.FileDescriptor] values.
  6. //
  7. // The google.protobuf.FileDescriptorProto is a protobuf message that describes
  8. // the type information for a .proto file in a form that is easily serializable.
  9. // The [protoreflect.FileDescriptor] is a more structured representation of
  10. // the FileDescriptorProto message where references and remote dependencies
  11. // can be directly followed.
  12. package protodesc
  13. import (
  14. "google.golang.org/protobuf/internal/errors"
  15. "google.golang.org/protobuf/internal/filedesc"
  16. "google.golang.org/protobuf/internal/pragma"
  17. "google.golang.org/protobuf/internal/strs"
  18. "google.golang.org/protobuf/proto"
  19. "google.golang.org/protobuf/reflect/protoreflect"
  20. "google.golang.org/protobuf/reflect/protoregistry"
  21. "google.golang.org/protobuf/types/descriptorpb"
  22. )
  23. // Resolver is the resolver used by [NewFile] to resolve dependencies.
  24. // The enums and messages provided must belong to some parent file,
  25. // which is also registered.
  26. //
  27. // It is implemented by [protoregistry.Files].
  28. type Resolver interface {
  29. FindFileByPath(string) (protoreflect.FileDescriptor, error)
  30. FindDescriptorByName(protoreflect.FullName) (protoreflect.Descriptor, error)
  31. }
  32. // FileOptions configures the construction of file descriptors.
  33. type FileOptions struct {
  34. pragma.NoUnkeyedLiterals
  35. // AllowUnresolvable configures New to permissively allow unresolvable
  36. // file, enum, or message dependencies. Unresolved dependencies are replaced
  37. // by placeholder equivalents.
  38. //
  39. // The following dependencies may be left unresolved:
  40. // • Resolving an imported file.
  41. // • Resolving the type for a message field or extension field.
  42. // If the kind of the field is unknown, then a placeholder is used for both
  43. // the Enum and Message accessors on the protoreflect.FieldDescriptor.
  44. // • Resolving an enum value set as the default for an optional enum field.
  45. // If unresolvable, the protoreflect.FieldDescriptor.Default is set to the
  46. // first value in the associated enum (or zero if the also enum dependency
  47. // is also unresolvable). The protoreflect.FieldDescriptor.DefaultEnumValue
  48. // is populated with a placeholder.
  49. // • Resolving the extended message type for an extension field.
  50. // • Resolving the input or output message type for a service method.
  51. //
  52. // If the unresolved dependency uses a relative name,
  53. // then the placeholder will contain an invalid FullName with a "*." prefix,
  54. // indicating that the starting prefix of the full name is unknown.
  55. AllowUnresolvable bool
  56. }
  57. // NewFile creates a new [protoreflect.FileDescriptor] from the provided
  58. // file descriptor message. See [FileOptions.New] for more information.
  59. func NewFile(fd *descriptorpb.FileDescriptorProto, r Resolver) (protoreflect.FileDescriptor, error) {
  60. return FileOptions{}.New(fd, r)
  61. }
  62. // NewFiles creates a new [protoregistry.Files] from the provided
  63. // FileDescriptorSet message. See [FileOptions.NewFiles] for more information.
  64. func NewFiles(fd *descriptorpb.FileDescriptorSet) (*protoregistry.Files, error) {
  65. return FileOptions{}.NewFiles(fd)
  66. }
  67. // New creates a new [protoreflect.FileDescriptor] from the provided
  68. // file descriptor message. The file must represent a valid proto file according
  69. // to protobuf semantics. The returned descriptor is a deep copy of the input.
  70. //
  71. // Any imported files, enum types, or message types referenced in the file are
  72. // resolved using the provided registry. When looking up an import file path,
  73. // the path must be unique. The newly created file descriptor is not registered
  74. // back into the provided file registry.
  75. func (o FileOptions) New(fd *descriptorpb.FileDescriptorProto, r Resolver) (protoreflect.FileDescriptor, error) {
  76. if r == nil {
  77. r = (*protoregistry.Files)(nil) // empty resolver
  78. }
  79. // Handle the file descriptor content.
  80. f := &filedesc.File{L2: &filedesc.FileL2{}}
  81. switch fd.GetSyntax() {
  82. case "proto2", "":
  83. f.L1.Syntax = protoreflect.Proto2
  84. case "proto3":
  85. f.L1.Syntax = protoreflect.Proto3
  86. case "editions":
  87. f.L1.Syntax = protoreflect.Editions
  88. f.L1.Edition = fromEditionProto(fd.GetEdition())
  89. default:
  90. return nil, errors.New("invalid syntax: %q", fd.GetSyntax())
  91. }
  92. if f.L1.Syntax == protoreflect.Editions && (fd.GetEdition() < SupportedEditionsMinimum || fd.GetEdition() > SupportedEditionsMaximum) {
  93. return nil, errors.New("use of edition %v not yet supported by the Go Protobuf runtime", fd.GetEdition())
  94. }
  95. f.L1.Path = fd.GetName()
  96. if f.L1.Path == "" {
  97. return nil, errors.New("file path must be populated")
  98. }
  99. f.L1.Package = protoreflect.FullName(fd.GetPackage())
  100. if !f.L1.Package.IsValid() && f.L1.Package != "" {
  101. return nil, errors.New("invalid package: %q", f.L1.Package)
  102. }
  103. if opts := fd.GetOptions(); opts != nil {
  104. opts = proto.Clone(opts).(*descriptorpb.FileOptions)
  105. f.L2.Options = func() protoreflect.ProtoMessage { return opts }
  106. }
  107. if f.L1.Syntax == protoreflect.Editions {
  108. initFileDescFromFeatureSet(f, fd.GetOptions().GetFeatures())
  109. }
  110. f.L2.Imports = make(filedesc.FileImports, len(fd.GetDependency()))
  111. for _, i := range fd.GetPublicDependency() {
  112. if !(0 <= i && int(i) < len(f.L2.Imports)) || f.L2.Imports[i].IsPublic {
  113. return nil, errors.New("invalid or duplicate public import index: %d", i)
  114. }
  115. f.L2.Imports[i].IsPublic = true
  116. }
  117. for _, i := range fd.GetWeakDependency() {
  118. if !(0 <= i && int(i) < len(f.L2.Imports)) || f.L2.Imports[i].IsWeak {
  119. return nil, errors.New("invalid or duplicate weak import index: %d", i)
  120. }
  121. f.L2.Imports[i].IsWeak = true
  122. }
  123. imps := importSet{f.Path(): true}
  124. for i, path := range fd.GetDependency() {
  125. imp := &f.L2.Imports[i]
  126. f, err := r.FindFileByPath(path)
  127. if err == protoregistry.NotFound && (o.AllowUnresolvable || imp.IsWeak) {
  128. f = filedesc.PlaceholderFile(path)
  129. } else if err != nil {
  130. return nil, errors.New("could not resolve import %q: %v", path, err)
  131. }
  132. imp.FileDescriptor = f
  133. if imps[imp.Path()] {
  134. return nil, errors.New("already imported %q", path)
  135. }
  136. imps[imp.Path()] = true
  137. }
  138. for i := range fd.GetDependency() {
  139. imp := &f.L2.Imports[i]
  140. imps.importPublic(imp.Imports())
  141. }
  142. // Handle source locations.
  143. f.L2.Locations.File = f
  144. for _, loc := range fd.GetSourceCodeInfo().GetLocation() {
  145. var l protoreflect.SourceLocation
  146. // TODO: Validate that the path points to an actual declaration?
  147. l.Path = protoreflect.SourcePath(loc.GetPath())
  148. s := loc.GetSpan()
  149. switch len(s) {
  150. case 3:
  151. l.StartLine, l.StartColumn, l.EndLine, l.EndColumn = int(s[0]), int(s[1]), int(s[0]), int(s[2])
  152. case 4:
  153. l.StartLine, l.StartColumn, l.EndLine, l.EndColumn = int(s[0]), int(s[1]), int(s[2]), int(s[3])
  154. default:
  155. return nil, errors.New("invalid span: %v", s)
  156. }
  157. // TODO: Validate that the span information is sensible?
  158. // See https://github.com/protocolbuffers/protobuf/issues/6378.
  159. if false && (l.EndLine < l.StartLine || l.StartLine < 0 || l.StartColumn < 0 || l.EndColumn < 0 ||
  160. (l.StartLine == l.EndLine && l.EndColumn <= l.StartColumn)) {
  161. return nil, errors.New("invalid span: %v", s)
  162. }
  163. l.LeadingDetachedComments = loc.GetLeadingDetachedComments()
  164. l.LeadingComments = loc.GetLeadingComments()
  165. l.TrailingComments = loc.GetTrailingComments()
  166. f.L2.Locations.List = append(f.L2.Locations.List, l)
  167. }
  168. // Step 1: Allocate and derive the names for all declarations.
  169. // This copies all fields from the descriptor proto except:
  170. // google.protobuf.FieldDescriptorProto.type_name
  171. // google.protobuf.FieldDescriptorProto.default_value
  172. // google.protobuf.FieldDescriptorProto.oneof_index
  173. // google.protobuf.FieldDescriptorProto.extendee
  174. // google.protobuf.MethodDescriptorProto.input
  175. // google.protobuf.MethodDescriptorProto.output
  176. var err error
  177. sb := new(strs.Builder)
  178. r1 := make(descsByName)
  179. if f.L1.Enums.List, err = r1.initEnumDeclarations(fd.GetEnumType(), f, sb); err != nil {
  180. return nil, err
  181. }
  182. if f.L1.Messages.List, err = r1.initMessagesDeclarations(fd.GetMessageType(), f, sb); err != nil {
  183. return nil, err
  184. }
  185. if f.L1.Extensions.List, err = r1.initExtensionDeclarations(fd.GetExtension(), f, sb); err != nil {
  186. return nil, err
  187. }
  188. if f.L1.Services.List, err = r1.initServiceDeclarations(fd.GetService(), f, sb); err != nil {
  189. return nil, err
  190. }
  191. // Step 2: Resolve every dependency reference not handled by step 1.
  192. r2 := &resolver{local: r1, remote: r, imports: imps, allowUnresolvable: o.AllowUnresolvable}
  193. if err := r2.resolveMessageDependencies(f.L1.Messages.List, fd.GetMessageType()); err != nil {
  194. return nil, err
  195. }
  196. if err := r2.resolveExtensionDependencies(f.L1.Extensions.List, fd.GetExtension()); err != nil {
  197. return nil, err
  198. }
  199. if err := r2.resolveServiceDependencies(f.L1.Services.List, fd.GetService()); err != nil {
  200. return nil, err
  201. }
  202. // Step 3: Validate every enum, message, and extension declaration.
  203. if err := validateEnumDeclarations(f.L1.Enums.List, fd.GetEnumType()); err != nil {
  204. return nil, err
  205. }
  206. if err := validateMessageDeclarations(f.L1.Messages.List, fd.GetMessageType()); err != nil {
  207. return nil, err
  208. }
  209. if err := validateExtensionDeclarations(f.L1.Extensions.List, fd.GetExtension()); err != nil {
  210. return nil, err
  211. }
  212. return f, nil
  213. }
  214. type importSet map[string]bool
  215. func (is importSet) importPublic(imps protoreflect.FileImports) {
  216. for i := 0; i < imps.Len(); i++ {
  217. if imp := imps.Get(i); imp.IsPublic {
  218. is[imp.Path()] = true
  219. is.importPublic(imp.Imports())
  220. }
  221. }
  222. }
  223. // NewFiles creates a new [protoregistry.Files] from the provided
  224. // FileDescriptorSet message. The descriptor set must include only
  225. // valid files according to protobuf semantics. The returned descriptors
  226. // are a deep copy of the input.
  227. func (o FileOptions) NewFiles(fds *descriptorpb.FileDescriptorSet) (*protoregistry.Files, error) {
  228. files := make(map[string]*descriptorpb.FileDescriptorProto)
  229. for _, fd := range fds.File {
  230. if _, ok := files[fd.GetName()]; ok {
  231. return nil, errors.New("file appears multiple times: %q", fd.GetName())
  232. }
  233. files[fd.GetName()] = fd
  234. }
  235. r := &protoregistry.Files{}
  236. for _, fd := range files {
  237. if err := o.addFileDeps(r, fd, files); err != nil {
  238. return nil, err
  239. }
  240. }
  241. return r, nil
  242. }
  243. func (o FileOptions) addFileDeps(r *protoregistry.Files, fd *descriptorpb.FileDescriptorProto, files map[string]*descriptorpb.FileDescriptorProto) error {
  244. // Set the entry to nil while descending into a file's dependencies to detect cycles.
  245. files[fd.GetName()] = nil
  246. for _, dep := range fd.Dependency {
  247. depfd, ok := files[dep]
  248. if depfd == nil {
  249. if ok {
  250. return errors.New("import cycle in file: %q", dep)
  251. }
  252. continue
  253. }
  254. if err := o.addFileDeps(r, depfd, files); err != nil {
  255. return err
  256. }
  257. }
  258. // Delete the entry once dependencies are processed.
  259. delete(files, fd.GetName())
  260. f, err := o.New(fd, r)
  261. if err != nil {
  262. return err
  263. }
  264. return r.RegisterFile(f)
  265. }