blob: 2467a92f88a0de26828b23b93f01e705aef900a9 [file] [log] [blame]
Joe Tsai23ddbd12018-08-26 22:48:17 -07001// 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
Joe Tsaie1f8d502018-11-26 18:55:29 -08005// Package protodesc provides for converting descriptorpb.FileDescriptorProto
6// to/from the reflective protoreflect.FileDescriptor.
7package protodesc
Joe Tsai23ddbd12018-08-26 22:48:17 -07008
9import (
10 "fmt"
11 "math"
12 "strconv"
13 "strings"
14
Joe Tsai01ab2962018-09-21 17:44:00 -070015 "github.com/golang/protobuf/v2/internal/encoding/text"
16 "github.com/golang/protobuf/v2/internal/errors"
17 "github.com/golang/protobuf/v2/reflect/protoreflect"
18 "github.com/golang/protobuf/v2/reflect/protoregistry"
Joe Tsaie1f8d502018-11-26 18:55:29 -080019 "github.com/golang/protobuf/v2/reflect/prototype"
20
21 descriptorpb "github.com/golang/protobuf/v2/types/descriptor"
Joe Tsai23ddbd12018-08-26 22:48:17 -070022)
23
24// TODO: Should we be responsible for validating other parts of the descriptor
25// that we don't directly use?
26//
27// For example:
28// * That field numbers don't overlap with reserved numbers.
29// * That field names don't overlap with reserved names.
30// * That enum numbers don't overlap with reserved numbers.
31// * That enum names don't overlap with reserved names.
32// * That "extendee" is not set for a message field.
33// * That "oneof_index" is not set for an extension field.
34// * That "json_name" is not set for an extension field. Maybe, maybe not.
35// * That "type_name" is not set on a field for non-enums and non-messages.
36// * That "weak" is not set for an extension field (double check this).
37
38// TODO: Store the input file descriptor to implement:
39// * protoreflect.Descriptor.DescriptorProto
40// * protoreflect.Descriptor.DescriptorOptions
41
42// TODO: Should we return a File instead of protoreflect.FileDescriptor?
43// This would allow users to mutate the File before converting it.
44// However, this will complicate future work for validation since File may now
45// diverge from the stored descriptor proto (see above TODO).
46
Joe Tsaie1f8d502018-11-26 18:55:29 -080047// NewFile creates a new protoreflect.FileDescriptor from the provided
48// file descriptor message. The file must represent a valid proto file according
49// to protobuf semantics.
Joe Tsai23ddbd12018-08-26 22:48:17 -070050//
51// Any import files, enum types, or message types referenced in the file are
52// resolved using the provided registry. When looking up an import file path,
53// the path must be unique. The newly created file descriptor is not registered
54// back into the provided file registry.
55//
56// The caller must relinquish full ownership of the input fd and must not
57// access or mutate any fields.
Joe Tsaie1f8d502018-11-26 18:55:29 -080058func NewFile(fd *descriptorpb.FileDescriptorProto, r *protoregistry.Files) (protoreflect.FileDescriptor, error) {
59 var f prototype.File
Joe Tsai23ddbd12018-08-26 22:48:17 -070060 switch fd.GetSyntax() {
Joe Tsaibce82b82018-12-06 09:39:03 -080061 case "proto2", "":
Joe Tsai23ddbd12018-08-26 22:48:17 -070062 f.Syntax = protoreflect.Proto2
63 case "proto3":
64 f.Syntax = protoreflect.Proto3
65 default:
66 return nil, errors.New("invalid syntax: %v", fd.GetSyntax())
67 }
68 f.Path = fd.GetName()
69 f.Package = protoreflect.FullName(fd.GetPackage())
Damien Neil204f1c02018-10-23 15:03:38 -070070 f.Options = fd.GetOptions()
Joe Tsai23ddbd12018-08-26 22:48:17 -070071
72 f.Imports = make([]protoreflect.FileImport, len(fd.GetDependency()))
73 for _, i := range fd.GetPublicDependency() {
74 if int(i) >= len(f.Imports) || f.Imports[i].IsPublic {
75 return nil, errors.New("invalid or duplicate public import index: %d", i)
76 }
77 f.Imports[i].IsPublic = true
78 }
79 for _, i := range fd.GetWeakDependency() {
80 if int(i) >= len(f.Imports) || f.Imports[i].IsWeak {
81 return nil, errors.New("invalid or duplicate weak import index: %d", i)
82 }
83 f.Imports[i].IsWeak = true
84 }
85 for i, path := range fd.GetDependency() {
86 var n int
87 imp := &f.Imports[i]
88 r.RangeFilesByPath(path, func(fd protoreflect.FileDescriptor) bool {
89 imp.FileDescriptor = fd
90 n++
91 return true
92 })
93 if n > 1 {
94 return nil, errors.New("duplicate files for import %q", path)
95 }
96 if imp.IsWeak || imp.FileDescriptor == nil {
Joe Tsaie1f8d502018-11-26 18:55:29 -080097 imp.FileDescriptor = prototype.PlaceholderFile(path, "")
Joe Tsai23ddbd12018-08-26 22:48:17 -070098 }
99 }
100
101 var err error
Damien Neild4803f52018-09-19 11:43:35 -0700102 f.Messages, err = messagesFromDescriptorProto(fd.GetMessageType(), f.Syntax, r)
Joe Tsai23ddbd12018-08-26 22:48:17 -0700103 if err != nil {
104 return nil, err
105 }
106 f.Enums, err = enumsFromDescriptorProto(fd.GetEnumType(), r)
107 if err != nil {
108 return nil, err
109 }
110 f.Extensions, err = extensionsFromDescriptorProto(fd.GetExtension(), r)
111 if err != nil {
112 return nil, err
113 }
114 f.Services, err = servicesFromDescriptorProto(fd.GetService(), r)
115 if err != nil {
116 return nil, err
117 }
118
Joe Tsaie1f8d502018-11-26 18:55:29 -0800119 return prototype.NewFile(&f)
Joe Tsai23ddbd12018-08-26 22:48:17 -0700120}
121
Joe Tsaie1f8d502018-11-26 18:55:29 -0800122func messagesFromDescriptorProto(mds []*descriptorpb.DescriptorProto, syntax protoreflect.Syntax, r *protoregistry.Files) (ms []prototype.Message, err error) {
Joe Tsai23ddbd12018-08-26 22:48:17 -0700123 for _, md := range mds {
Joe Tsaie1f8d502018-11-26 18:55:29 -0800124 var m prototype.Message
Joe Tsai23ddbd12018-08-26 22:48:17 -0700125 m.Name = protoreflect.Name(md.GetName())
Damien Neil204f1c02018-10-23 15:03:38 -0700126 m.Options = md.GetOptions()
Joe Tsai23ddbd12018-08-26 22:48:17 -0700127 for _, fd := range md.GetField() {
Joe Tsaie1f8d502018-11-26 18:55:29 -0800128 var f prototype.Field
Joe Tsai23ddbd12018-08-26 22:48:17 -0700129 f.Name = protoreflect.Name(fd.GetName())
130 f.Number = protoreflect.FieldNumber(fd.GetNumber())
131 f.Cardinality = protoreflect.Cardinality(fd.GetLabel())
132 f.Kind = protoreflect.Kind(fd.GetType())
Damien Neil204f1c02018-10-23 15:03:38 -0700133 f.Options = fd.GetOptions()
Joe Tsai23ddbd12018-08-26 22:48:17 -0700134 f.JSONName = fd.GetJsonName()
Joe Tsai23ddbd12018-08-26 22:48:17 -0700135 if fd.DefaultValue != nil {
136 f.Default, err = parseDefault(fd.GetDefaultValue(), f.Kind)
137 if err != nil {
138 return nil, err
139 }
140 }
141 if fd.OneofIndex != nil {
142 i := int(fd.GetOneofIndex())
143 if i >= len(md.GetOneofDecl()) {
144 return nil, errors.New("invalid oneof index: %d", i)
145 }
146 f.OneofName = protoreflect.Name(md.GetOneofDecl()[i].GetName())
147 }
Joe Tsaie1f8d502018-11-26 18:55:29 -0800148 opts, _ := f.Options.(*descriptorpb.FieldOptions)
Joe Tsai23ddbd12018-08-26 22:48:17 -0700149 switch f.Kind {
150 case protoreflect.EnumKind:
151 f.EnumType, err = findEnumDescriptor(fd.GetTypeName(), r)
152 if err != nil {
153 return nil, err
154 }
Joe Tsaie1f8d502018-11-26 18:55:29 -0800155 if opts.GetWeak() && !f.EnumType.IsPlaceholder() {
156 f.EnumType = prototype.PlaceholderEnum(f.EnumType.FullName())
Joe Tsai23ddbd12018-08-26 22:48:17 -0700157 }
158 case protoreflect.MessageKind, protoreflect.GroupKind:
159 f.MessageType, err = findMessageDescriptor(fd.GetTypeName(), r)
160 if err != nil {
161 return nil, err
162 }
Joe Tsaie1f8d502018-11-26 18:55:29 -0800163 if opts.GetWeak() && !f.MessageType.IsPlaceholder() {
164 f.MessageType = prototype.PlaceholderMessage(f.MessageType.FullName())
Joe Tsai23ddbd12018-08-26 22:48:17 -0700165 }
166 }
167 m.Fields = append(m.Fields, f)
168 }
169 for _, od := range md.GetOneofDecl() {
Joe Tsaie1f8d502018-11-26 18:55:29 -0800170 m.Oneofs = append(m.Oneofs, prototype.Oneof{
Damien Neil204f1c02018-10-23 15:03:38 -0700171 Name: protoreflect.Name(od.GetName()),
172 Options: od.Options,
173 })
Joe Tsai23ddbd12018-08-26 22:48:17 -0700174 }
Joe Tsaibce82b82018-12-06 09:39:03 -0800175 for _, s := range md.GetReservedName() {
176 m.ReservedNames = append(m.ReservedNames, protoreflect.Name(s))
177 }
178 for _, rr := range md.GetReservedRange() {
179 m.ReservedRanges = append(m.ReservedRanges, [2]protoreflect.FieldNumber{
180 protoreflect.FieldNumber(rr.GetStart()),
181 protoreflect.FieldNumber(rr.GetEnd()),
182 })
183 }
Joe Tsai23ddbd12018-08-26 22:48:17 -0700184 for _, xr := range md.GetExtensionRange() {
185 m.ExtensionRanges = append(m.ExtensionRanges, [2]protoreflect.FieldNumber{
186 protoreflect.FieldNumber(xr.GetStart()),
187 protoreflect.FieldNumber(xr.GetEnd()),
188 })
Joe Tsai381f04c2018-12-06 12:10:41 -0800189 m.ExtensionRangeOptions = append(m.ExtensionRangeOptions, xr.GetOptions())
Joe Tsai23ddbd12018-08-26 22:48:17 -0700190 }
191
Damien Neild4803f52018-09-19 11:43:35 -0700192 m.Messages, err = messagesFromDescriptorProto(md.GetNestedType(), syntax, r)
Joe Tsai23ddbd12018-08-26 22:48:17 -0700193 if err != nil {
194 return nil, err
195 }
196 m.Enums, err = enumsFromDescriptorProto(md.GetEnumType(), r)
197 if err != nil {
198 return nil, err
199 }
200 m.Extensions, err = extensionsFromDescriptorProto(md.GetExtension(), r)
201 if err != nil {
202 return nil, err
203 }
204
205 ms = append(ms, m)
206 }
207 return ms, nil
208}
209
Joe Tsaie1f8d502018-11-26 18:55:29 -0800210func enumsFromDescriptorProto(eds []*descriptorpb.EnumDescriptorProto, r *protoregistry.Files) (es []prototype.Enum, err error) {
Joe Tsai23ddbd12018-08-26 22:48:17 -0700211 for _, ed := range eds {
Joe Tsaie1f8d502018-11-26 18:55:29 -0800212 var e prototype.Enum
Joe Tsai23ddbd12018-08-26 22:48:17 -0700213 e.Name = protoreflect.Name(ed.GetName())
Damien Neil204f1c02018-10-23 15:03:38 -0700214 e.Options = ed.GetOptions()
Joe Tsai23ddbd12018-08-26 22:48:17 -0700215 for _, vd := range ed.GetValue() {
Joe Tsaie1f8d502018-11-26 18:55:29 -0800216 e.Values = append(e.Values, prototype.EnumValue{
Damien Neil204f1c02018-10-23 15:03:38 -0700217 Name: protoreflect.Name(vd.GetName()),
218 Number: protoreflect.EnumNumber(vd.GetNumber()),
219 Options: vd.Options,
Joe Tsai23ddbd12018-08-26 22:48:17 -0700220 })
221 }
Joe Tsaibce82b82018-12-06 09:39:03 -0800222 for _, s := range ed.GetReservedName() {
223 e.ReservedNames = append(e.ReservedNames, protoreflect.Name(s))
224 }
225 for _, rr := range ed.GetReservedRange() {
226 e.ReservedRanges = append(e.ReservedRanges, [2]protoreflect.EnumNumber{
227 protoreflect.EnumNumber(rr.GetStart()),
228 protoreflect.EnumNumber(rr.GetEnd()),
229 })
230 }
Joe Tsai23ddbd12018-08-26 22:48:17 -0700231 es = append(es, e)
232 }
233 return es, nil
234}
235
Joe Tsaie1f8d502018-11-26 18:55:29 -0800236func extensionsFromDescriptorProto(xds []*descriptorpb.FieldDescriptorProto, r *protoregistry.Files) (xs []prototype.Extension, err error) {
Joe Tsai23ddbd12018-08-26 22:48:17 -0700237 for _, xd := range xds {
Joe Tsaie1f8d502018-11-26 18:55:29 -0800238 var x prototype.Extension
Joe Tsai23ddbd12018-08-26 22:48:17 -0700239 x.Name = protoreflect.Name(xd.GetName())
240 x.Number = protoreflect.FieldNumber(xd.GetNumber())
241 x.Cardinality = protoreflect.Cardinality(xd.GetLabel())
242 x.Kind = protoreflect.Kind(xd.GetType())
Damien Neil204f1c02018-10-23 15:03:38 -0700243 x.Options = xd.GetOptions()
Joe Tsai23ddbd12018-08-26 22:48:17 -0700244 if xd.DefaultValue != nil {
245 x.Default, err = parseDefault(xd.GetDefaultValue(), x.Kind)
246 if err != nil {
247 return nil, err
248 }
249 }
250 switch x.Kind {
251 case protoreflect.EnumKind:
252 x.EnumType, err = findEnumDescriptor(xd.GetTypeName(), r)
253 if err != nil {
254 return nil, err
255 }
256 case protoreflect.MessageKind, protoreflect.GroupKind:
257 x.MessageType, err = findMessageDescriptor(xd.GetTypeName(), r)
258 if err != nil {
259 return nil, err
260 }
261 }
262 x.ExtendedType, err = findMessageDescriptor(xd.GetExtendee(), r)
263 if err != nil {
264 return nil, err
265 }
266 xs = append(xs, x)
267 }
268 return xs, nil
269}
270
Joe Tsaie1f8d502018-11-26 18:55:29 -0800271func servicesFromDescriptorProto(sds []*descriptorpb.ServiceDescriptorProto, r *protoregistry.Files) (ss []prototype.Service, err error) {
Joe Tsai23ddbd12018-08-26 22:48:17 -0700272 for _, sd := range sds {
Joe Tsaie1f8d502018-11-26 18:55:29 -0800273 var s prototype.Service
Joe Tsai23ddbd12018-08-26 22:48:17 -0700274 s.Name = protoreflect.Name(sd.GetName())
Damien Neil204f1c02018-10-23 15:03:38 -0700275 s.Options = sd.GetOptions()
Joe Tsai23ddbd12018-08-26 22:48:17 -0700276 for _, md := range sd.GetMethod() {
Joe Tsaie1f8d502018-11-26 18:55:29 -0800277 var m prototype.Method
Joe Tsai23ddbd12018-08-26 22:48:17 -0700278 m.Name = protoreflect.Name(md.GetName())
Damien Neil204f1c02018-10-23 15:03:38 -0700279 m.Options = md.GetOptions()
Joe Tsai23ddbd12018-08-26 22:48:17 -0700280 m.InputType, err = findMessageDescriptor(md.GetInputType(), r)
281 if err != nil {
282 return nil, err
283 }
284 m.OutputType, err = findMessageDescriptor(md.GetOutputType(), r)
285 if err != nil {
286 return nil, err
287 }
288 m.IsStreamingClient = md.GetClientStreaming()
289 m.IsStreamingServer = md.GetServerStreaming()
290 s.Methods = append(s.Methods, m)
291 }
292 ss = append(ss, s)
293 }
294 return ss, nil
295}
296
297// TODO: Should we allow relative names? The protoc compiler has emitted
298// absolute names for some time now. Requiring absolute names as an input
299// simplifies our implementation as we won't need to implement C++'s namespace
300// scoping rules.
301
302func findMessageDescriptor(s string, r *protoregistry.Files) (protoreflect.MessageDescriptor, error) {
303 if !strings.HasPrefix(s, ".") {
304 return nil, errors.New("identifier name must be fully qualified with a leading dot: %v", s)
305 }
306 name := protoreflect.FullName(strings.TrimPrefix(s, "."))
307 switch m, err := r.FindDescriptorByName(name); {
308 case err == nil:
309 m, ok := m.(protoreflect.MessageDescriptor)
310 if !ok {
311 return nil, errors.New("resolved wrong type: got %v, want message", typeName(m))
312 }
313 return m, nil
314 case err == protoregistry.NotFound:
Joe Tsaie1f8d502018-11-26 18:55:29 -0800315 return prototype.PlaceholderMessage(name), nil
Joe Tsai23ddbd12018-08-26 22:48:17 -0700316 default:
317 return nil, err
318 }
319}
320
321func findEnumDescriptor(s string, r *protoregistry.Files) (protoreflect.EnumDescriptor, error) {
322 if !strings.HasPrefix(s, ".") {
323 return nil, errors.New("identifier name must be fully qualified with a leading dot: %v", s)
324 }
325 name := protoreflect.FullName(strings.TrimPrefix(s, "."))
326 switch e, err := r.FindDescriptorByName(name); {
327 case err == nil:
328 e, ok := e.(protoreflect.EnumDescriptor)
329 if !ok {
330 return nil, errors.New("resolved wrong type: got %T, want enum", typeName(e))
331 }
332 return e, nil
333 case err == protoregistry.NotFound:
Joe Tsaie1f8d502018-11-26 18:55:29 -0800334 return prototype.PlaceholderEnum(name), nil
Joe Tsai23ddbd12018-08-26 22:48:17 -0700335 default:
336 return nil, err
337 }
338}
339
340func typeName(t protoreflect.Descriptor) string {
341 switch t.(type) {
342 case protoreflect.EnumType:
343 return "enum"
344 case protoreflect.MessageType:
345 return "message"
346 default:
347 return fmt.Sprintf("%T", t)
348 }
349}
350
351func parseDefault(s string, k protoreflect.Kind) (protoreflect.Value, error) {
352 switch k {
353 case protoreflect.BoolKind:
354 switch s {
355 case "true":
356 return protoreflect.ValueOf(true), nil
357 case "false":
358 return protoreflect.ValueOf(false), nil
359 }
360 case protoreflect.EnumKind:
361 // For enums, we are supposed to return a protoreflect.EnumNumber type.
362 // However, default values record the name instead of the number.
363 // We are unable to resolve the name into a number without additional
364 // type information. Thus, we temporarily return the name identifier
365 // for now and rely on logic in defaultValue.lazyInit to resolve it.
366 return protoreflect.ValueOf(s), nil
367 case protoreflect.Int32Kind, protoreflect.Sint32Kind, protoreflect.Sfixed32Kind:
368 v, err := strconv.ParseInt(s, 0, 32)
369 if err == nil {
370 return protoreflect.ValueOf(int32(v)), nil
371 }
372 case protoreflect.Int64Kind, protoreflect.Sint64Kind, protoreflect.Sfixed64Kind:
373 v, err := strconv.ParseInt(s, 0, 64)
374 if err == nil {
375 return protoreflect.ValueOf(int64(v)), nil
376 }
377 case protoreflect.Uint32Kind, protoreflect.Fixed32Kind:
378 v, err := strconv.ParseUint(s, 0, 32)
379 if err == nil {
Joe Tsai90fe9962018-10-18 11:06:29 -0700380 return protoreflect.ValueOf(uint32(v)), nil
Joe Tsai23ddbd12018-08-26 22:48:17 -0700381 }
382 case protoreflect.Uint64Kind, protoreflect.Fixed64Kind:
383 v, err := strconv.ParseUint(s, 0, 64)
384 if err == nil {
385 return protoreflect.ValueOf(uint64(v)), nil
386 }
387 case protoreflect.FloatKind, protoreflect.DoubleKind:
388 var v float64
389 var err error
390 switch s {
391 case "nan":
392 v = math.NaN()
393 case "inf":
394 v = math.Inf(+1)
395 case "-inf":
396 v = math.Inf(-1)
397 default:
398 v, err = strconv.ParseFloat(s, 64)
399 }
400 if err == nil {
401 if k == protoreflect.FloatKind {
402 return protoreflect.ValueOf(float32(v)), nil
403 }
404 return protoreflect.ValueOf(float64(v)), nil
405 }
Joe Tsai1dab2cb2018-09-28 13:39:07 -0700406 case protoreflect.StringKind:
407 // String values are already unescaped and can be used as is.
408 return protoreflect.ValueOf(s), nil
409 case protoreflect.BytesKind:
410 // Bytes values use the same escaping as the text format,
Joe Tsai23ddbd12018-08-26 22:48:17 -0700411 // however they lack the surrounding double quotes.
412 // TODO: Export unmarshalString in the text package to avoid this hack.
413 v, err := text.Unmarshal([]byte(`["` + s + `"]:0`))
414 if err == nil && len(v.Message()) == 1 {
415 s := v.Message()[0][0].String()
Joe Tsai23ddbd12018-08-26 22:48:17 -0700416 return protoreflect.ValueOf([]byte(s)), nil
417 }
418 }
Joe Tsai812d9132018-09-12 11:26:15 -0700419 return protoreflect.Value{}, errors.New("invalid default value for %v: %q", k, s)
Joe Tsai23ddbd12018-08-26 22:48:17 -0700420}