desc_resolve.go 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  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. "google.golang.org/protobuf/internal/encoding/defval"
  7. "google.golang.org/protobuf/internal/errors"
  8. "google.golang.org/protobuf/internal/filedesc"
  9. "google.golang.org/protobuf/reflect/protoreflect"
  10. "google.golang.org/protobuf/reflect/protoregistry"
  11. "google.golang.org/protobuf/types/descriptorpb"
  12. )
  13. // resolver is a wrapper around a local registry of declarations within the file
  14. // and the remote resolver. The remote resolver is restricted to only return
  15. // descriptors that have been imported.
  16. type resolver struct {
  17. local descsByName
  18. remote Resolver
  19. imports importSet
  20. allowUnresolvable bool
  21. }
  22. func (r *resolver) resolveMessageDependencies(ms []filedesc.Message, mds []*descriptorpb.DescriptorProto) (err error) {
  23. for i, md := range mds {
  24. m := &ms[i]
  25. for j, fd := range md.GetField() {
  26. f := &m.L2.Fields.List[j]
  27. if f.L1.Cardinality == protoreflect.Required {
  28. m.L2.RequiredNumbers.List = append(m.L2.RequiredNumbers.List, f.L1.Number)
  29. }
  30. if fd.OneofIndex != nil {
  31. k := int(fd.GetOneofIndex())
  32. if !(0 <= k && k < len(md.GetOneofDecl())) {
  33. return errors.New("message field %q has an invalid oneof index: %d", f.FullName(), k)
  34. }
  35. o := &m.L2.Oneofs.List[k]
  36. f.L1.ContainingOneof = o
  37. o.L1.Fields.List = append(o.L1.Fields.List, f)
  38. }
  39. if f.L1.Kind, f.L1.Enum, f.L1.Message, err = r.findTarget(f.Kind(), f.Parent().FullName(), partialName(fd.GetTypeName()), f.IsWeak()); err != nil {
  40. return errors.New("message field %q cannot resolve type: %v", f.FullName(), err)
  41. }
  42. if fd.DefaultValue != nil {
  43. v, ev, err := unmarshalDefault(fd.GetDefaultValue(), f, r.allowUnresolvable)
  44. if err != nil {
  45. return errors.New("message field %q has invalid default: %v", f.FullName(), err)
  46. }
  47. f.L1.Default = filedesc.DefaultValue(v, ev)
  48. }
  49. }
  50. if err := r.resolveMessageDependencies(m.L1.Messages.List, md.GetNestedType()); err != nil {
  51. return err
  52. }
  53. if err := r.resolveExtensionDependencies(m.L1.Extensions.List, md.GetExtension()); err != nil {
  54. return err
  55. }
  56. }
  57. return nil
  58. }
  59. func (r *resolver) resolveExtensionDependencies(xs []filedesc.Extension, xds []*descriptorpb.FieldDescriptorProto) (err error) {
  60. for i, xd := range xds {
  61. x := &xs[i]
  62. if x.L1.Extendee, err = r.findMessageDescriptor(x.Parent().FullName(), partialName(xd.GetExtendee()), false); err != nil {
  63. return errors.New("extension field %q cannot resolve extendee: %v", x.FullName(), err)
  64. }
  65. if x.L1.Kind, x.L2.Enum, x.L2.Message, err = r.findTarget(x.Kind(), x.Parent().FullName(), partialName(xd.GetTypeName()), false); err != nil {
  66. return errors.New("extension field %q cannot resolve type: %v", x.FullName(), err)
  67. }
  68. if xd.DefaultValue != nil {
  69. v, ev, err := unmarshalDefault(xd.GetDefaultValue(), x, r.allowUnresolvable)
  70. if err != nil {
  71. return errors.New("extension field %q has invalid default: %v", x.FullName(), err)
  72. }
  73. x.L2.Default = filedesc.DefaultValue(v, ev)
  74. }
  75. }
  76. return nil
  77. }
  78. func (r *resolver) resolveServiceDependencies(ss []filedesc.Service, sds []*descriptorpb.ServiceDescriptorProto) (err error) {
  79. for i, sd := range sds {
  80. s := &ss[i]
  81. for j, md := range sd.GetMethod() {
  82. m := &s.L2.Methods.List[j]
  83. m.L1.Input, err = r.findMessageDescriptor(m.Parent().FullName(), partialName(md.GetInputType()), false)
  84. if err != nil {
  85. return errors.New("service method %q cannot resolve input: %v", m.FullName(), err)
  86. }
  87. m.L1.Output, err = r.findMessageDescriptor(s.FullName(), partialName(md.GetOutputType()), false)
  88. if err != nil {
  89. return errors.New("service method %q cannot resolve output: %v", m.FullName(), err)
  90. }
  91. }
  92. }
  93. return nil
  94. }
  95. // findTarget finds an enum or message descriptor if k is an enum, message,
  96. // group, or unknown. If unknown, and the name could be resolved, the kind
  97. // returned kind is set based on the type of the resolved descriptor.
  98. func (r *resolver) findTarget(k protoreflect.Kind, scope protoreflect.FullName, ref partialName, isWeak bool) (protoreflect.Kind, protoreflect.EnumDescriptor, protoreflect.MessageDescriptor, error) {
  99. switch k {
  100. case protoreflect.EnumKind:
  101. ed, err := r.findEnumDescriptor(scope, ref, isWeak)
  102. if err != nil {
  103. return 0, nil, nil, err
  104. }
  105. return k, ed, nil, nil
  106. case protoreflect.MessageKind, protoreflect.GroupKind:
  107. md, err := r.findMessageDescriptor(scope, ref, isWeak)
  108. if err != nil {
  109. return 0, nil, nil, err
  110. }
  111. return k, nil, md, nil
  112. case 0:
  113. // Handle unspecified kinds (possible with parsers that operate
  114. // on a per-file basis without knowledge of dependencies).
  115. d, err := r.findDescriptor(scope, ref)
  116. if err == protoregistry.NotFound && (r.allowUnresolvable || isWeak) {
  117. return k, filedesc.PlaceholderEnum(ref.FullName()), filedesc.PlaceholderMessage(ref.FullName()), nil
  118. } else if err == protoregistry.NotFound {
  119. return 0, nil, nil, errors.New("%q not found", ref.FullName())
  120. } else if err != nil {
  121. return 0, nil, nil, err
  122. }
  123. switch d := d.(type) {
  124. case protoreflect.EnumDescriptor:
  125. return protoreflect.EnumKind, d, nil, nil
  126. case protoreflect.MessageDescriptor:
  127. return protoreflect.MessageKind, nil, d, nil
  128. default:
  129. return 0, nil, nil, errors.New("unknown kind")
  130. }
  131. default:
  132. if ref != "" {
  133. return 0, nil, nil, errors.New("target name cannot be specified for %v", k)
  134. }
  135. if !k.IsValid() {
  136. return 0, nil, nil, errors.New("invalid kind: %d", k)
  137. }
  138. return k, nil, nil, nil
  139. }
  140. }
  141. // findDescriptor finds the descriptor by name,
  142. // which may be a relative name within some scope.
  143. //
  144. // Suppose the scope was "fizz.buzz" and the reference was "Foo.Bar",
  145. // then the following full names are searched:
  146. // - fizz.buzz.Foo.Bar
  147. // - fizz.Foo.Bar
  148. // - Foo.Bar
  149. func (r *resolver) findDescriptor(scope protoreflect.FullName, ref partialName) (protoreflect.Descriptor, error) {
  150. if !ref.IsValid() {
  151. return nil, errors.New("invalid name reference: %q", ref)
  152. }
  153. if ref.IsFull() {
  154. scope, ref = "", ref[1:]
  155. }
  156. var foundButNotImported protoreflect.Descriptor
  157. for {
  158. // Derive the full name to search.
  159. s := protoreflect.FullName(ref)
  160. if scope != "" {
  161. s = scope + "." + s
  162. }
  163. // Check the current file for the descriptor.
  164. if d, ok := r.local[s]; ok {
  165. return d, nil
  166. }
  167. // Check the remote registry for the descriptor.
  168. d, err := r.remote.FindDescriptorByName(s)
  169. if err == nil {
  170. // Only allow descriptors covered by one of the imports.
  171. if r.imports[d.ParentFile().Path()] {
  172. return d, nil
  173. }
  174. foundButNotImported = d
  175. } else if err != protoregistry.NotFound {
  176. return nil, errors.Wrap(err, "%q", s)
  177. }
  178. // Continue on at a higher level of scoping.
  179. if scope == "" {
  180. if d := foundButNotImported; d != nil {
  181. return nil, errors.New("resolved %q, but %q is not imported", d.FullName(), d.ParentFile().Path())
  182. }
  183. return nil, protoregistry.NotFound
  184. }
  185. scope = scope.Parent()
  186. }
  187. }
  188. func (r *resolver) findEnumDescriptor(scope protoreflect.FullName, ref partialName, isWeak bool) (protoreflect.EnumDescriptor, error) {
  189. d, err := r.findDescriptor(scope, ref)
  190. if err == protoregistry.NotFound && (r.allowUnresolvable || isWeak) {
  191. return filedesc.PlaceholderEnum(ref.FullName()), nil
  192. } else if err == protoregistry.NotFound {
  193. return nil, errors.New("%q not found", ref.FullName())
  194. } else if err != nil {
  195. return nil, err
  196. }
  197. ed, ok := d.(protoreflect.EnumDescriptor)
  198. if !ok {
  199. return nil, errors.New("resolved %q, but it is not an enum", d.FullName())
  200. }
  201. return ed, nil
  202. }
  203. func (r *resolver) findMessageDescriptor(scope protoreflect.FullName, ref partialName, isWeak bool) (protoreflect.MessageDescriptor, error) {
  204. d, err := r.findDescriptor(scope, ref)
  205. if err == protoregistry.NotFound && (r.allowUnresolvable || isWeak) {
  206. return filedesc.PlaceholderMessage(ref.FullName()), nil
  207. } else if err == protoregistry.NotFound {
  208. return nil, errors.New("%q not found", ref.FullName())
  209. } else if err != nil {
  210. return nil, err
  211. }
  212. md, ok := d.(protoreflect.MessageDescriptor)
  213. if !ok {
  214. return nil, errors.New("resolved %q, but it is not an message", d.FullName())
  215. }
  216. return md, nil
  217. }
  218. // partialName is the partial name. A leading dot means that the name is full,
  219. // otherwise the name is relative to some current scope.
  220. // See google.protobuf.FieldDescriptorProto.type_name.
  221. type partialName string
  222. func (s partialName) IsFull() bool {
  223. return len(s) > 0 && s[0] == '.'
  224. }
  225. func (s partialName) IsValid() bool {
  226. if s.IsFull() {
  227. return protoreflect.FullName(s[1:]).IsValid()
  228. }
  229. return protoreflect.FullName(s).IsValid()
  230. }
  231. const unknownPrefix = "*."
  232. // FullName converts the partial name to a full name on a best-effort basis.
  233. // If relative, it creates an invalid full name, using a "*." prefix
  234. // to indicate that the start of the full name is unknown.
  235. func (s partialName) FullName() protoreflect.FullName {
  236. if s.IsFull() {
  237. return protoreflect.FullName(s[1:])
  238. }
  239. return protoreflect.FullName(unknownPrefix + s)
  240. }
  241. func unmarshalDefault(s string, fd protoreflect.FieldDescriptor, allowUnresolvable bool) (protoreflect.Value, protoreflect.EnumValueDescriptor, error) {
  242. var evs protoreflect.EnumValueDescriptors
  243. if fd.Enum() != nil {
  244. evs = fd.Enum().Values()
  245. }
  246. v, ev, err := defval.Unmarshal(s, fd.Kind(), evs, defval.Descriptor)
  247. if err != nil && allowUnresolvable && evs != nil && protoreflect.Name(s).IsValid() {
  248. v = protoreflect.ValueOfEnum(0)
  249. if evs.Len() > 0 {
  250. v = protoreflect.ValueOfEnum(evs.Get(0).Number())
  251. }
  252. ev = filedesc.PlaceholderEnumValue(fd.Enum().FullName().Parent().Append(protoreflect.Name(s)))
  253. } else if err != nil {
  254. return v, ev, err
  255. }
  256. if fd.Syntax() == protoreflect.Proto3 {
  257. return v, ev, errors.New("cannot be specified under proto3 semantics")
  258. }
  259. if fd.Kind() == protoreflect.MessageKind || fd.Kind() == protoreflect.GroupKind || fd.Cardinality() == protoreflect.Repeated {
  260. return v, ev, errors.New("cannot be specified on composite types")
  261. }
  262. return v, ev, nil
  263. }