/
descriptor.go
2134 lines (1900 loc) · 68.2 KB
/
descriptor.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package desc
import (
"bytes"
"errors"
"fmt"
"reflect"
"sort"
"strconv"
"strings"
"sync"
"unicode/utf8"
"github.com/golang/protobuf/proto"
dpb "github.com/golang/protobuf/protoc-gen-go/descriptor"
descinternal "github.com/jhump/protoreflect/desc/internal"
"github.com/jhump/protoreflect/internal"
)
// Descriptor is the common interface implemented by all descriptor objects.
type Descriptor interface {
// GetName returns the name of the object described by the descriptor. This will
// be a base name that does not include enclosing message names or the package name.
// For file descriptors, this indicates the path and name to the described file.
GetName() string
// GetFullyQualifiedName returns the fully-qualified name of the object described by
// the descriptor. This will include the package name and any enclosing message names.
// For file descriptors, this returns the path and name to the described file (same as
// GetName).
GetFullyQualifiedName() string
// GetParent returns the enclosing element in a proto source file. If the described
// object is a top-level object, this returns the file descriptor. Otherwise, it returns
// the element in which the described object was declared. File descriptors have no
// parent and return nil.
GetParent() Descriptor
// GetFile returns the file descriptor in which this element was declared. File
// descriptors return themselves.
GetFile() *FileDescriptor
// GetOptions returns the options proto containing options for the described element.
GetOptions() proto.Message
// GetSourceInfo returns any source code information that was present in the file
// descriptor. Source code info is optional. If no source code info is available for
// the element (including if there is none at all in the file descriptor) then this
// returns nil
GetSourceInfo() *dpb.SourceCodeInfo_Location
// AsProto returns the underlying descriptor proto for this descriptor.
AsProto() proto.Message
}
// FileDescriptor describes a proto source file.
type FileDescriptor struct {
proto *dpb.FileDescriptorProto
symbols map[string]Descriptor
deps []*FileDescriptor
publicDeps []*FileDescriptor
weakDeps []*FileDescriptor
messages []*MessageDescriptor
enums []*EnumDescriptor
extensions []*FieldDescriptor
services []*ServiceDescriptor
fieldIndex map[string]map[int32]*FieldDescriptor
isProto3 bool
}
// CreateFileDescriptor instantiates a new file descriptor for the given descriptor proto.
// The file's direct dependencies must be provided. If the given dependencies do not include
// all of the file's dependencies or if the contents of the descriptors are internally
// inconsistent (e.g. contain unresolvable symbols) then an error is returned.
func CreateFileDescriptor(fd *dpb.FileDescriptorProto, deps ...*FileDescriptor) (*FileDescriptor, error) {
ret := &FileDescriptor{proto: fd, symbols: map[string]Descriptor{}, fieldIndex: map[string]map[int32]*FieldDescriptor{}}
pkg := fd.GetPackage()
// populate references to file descriptor dependencies
files := map[string]*FileDescriptor{}
for _, f := range deps {
files[f.proto.GetName()] = f
}
ret.deps = make([]*FileDescriptor, len(fd.GetDependency()))
for i, d := range fd.GetDependency() {
ret.deps[i] = files[d]
if ret.deps[i] == nil {
return nil, fmt.Errorf("Given dependencies did not include %q", d)
}
}
ret.publicDeps = make([]*FileDescriptor, len(fd.GetPublicDependency()))
for i, pd := range fd.GetPublicDependency() {
ret.publicDeps[i] = ret.deps[pd]
}
ret.weakDeps = make([]*FileDescriptor, len(fd.GetWeakDependency()))
for i, wd := range fd.GetWeakDependency() {
ret.weakDeps[i] = ret.deps[wd]
}
ret.isProto3 = fd.GetSyntax() == "proto3"
// populate all tables of child descriptors
for _, m := range fd.GetMessageType() {
md, n := createMessageDescriptor(ret, ret, pkg, m, ret.symbols)
ret.symbols[n] = md
ret.messages = append(ret.messages, md)
}
for _, e := range fd.GetEnumType() {
ed, n := createEnumDescriptor(ret, ret, pkg, e, ret.symbols)
ret.symbols[n] = ed
ret.enums = append(ret.enums, ed)
}
for _, ex := range fd.GetExtension() {
exd, n := createFieldDescriptor(ret, ret, pkg, ex)
ret.symbols[n] = exd
ret.extensions = append(ret.extensions, exd)
}
for _, s := range fd.GetService() {
sd, n := createServiceDescriptor(ret, pkg, s, ret.symbols)
ret.symbols[n] = sd
ret.services = append(ret.services, sd)
}
sourceCodeInfo := descinternal.CreateSourceInfoMap(fd)
// now we can resolve all type references and source code info
scopes := []scope{fileScope(ret)}
path := make([]int32, 1, 8)
path[0] = descinternal.File_messagesTag
for i, md := range ret.messages {
if err := md.resolve(append(path, int32(i)), sourceCodeInfo, scopes); err != nil {
return nil, err
}
}
path[0] = descinternal.File_enumsTag
for i, ed := range ret.enums {
ed.resolve(append(path, int32(i)), sourceCodeInfo)
}
path[0] = descinternal.File_extensionsTag
for i, exd := range ret.extensions {
if err := exd.resolve(append(path, int32(i)), sourceCodeInfo, scopes); err != nil {
return nil, err
}
}
path[0] = descinternal.File_servicesTag
for i, sd := range ret.services {
if err := sd.resolve(append(path, int32(i)), sourceCodeInfo, scopes); err != nil {
return nil, err
}
}
return ret, nil
}
// CreateFileDescriptors constructs a set of descriptors, one for each of the
// given descriptor protos. The given set of descriptor protos must include all
// transitive dependencies for every file.
func CreateFileDescriptors(fds []*dpb.FileDescriptorProto) (map[string]*FileDescriptor, error) {
if len(fds) == 0 {
return nil, nil
}
files := map[string]*dpb.FileDescriptorProto{}
resolved := map[string]*FileDescriptor{}
var name string
for _, fd := range fds {
name = fd.GetName()
files[name] = fd
}
for _, fd := range fds {
_, err := createFromSet(fd.GetName(), nil, files, resolved)
if err != nil {
return nil, err
}
}
return resolved, nil
}
// ToFileDescriptorSet creates a FileDescriptorSet proto that contains all of the given
// file descriptors and their transitive dependencies. The files are topologically sorted
// so that a file will always appear after its dependencies.
func ToFileDescriptorSet(fds ...*FileDescriptor) *dpb.FileDescriptorSet {
var fdps []*dpb.FileDescriptorProto
addAllFiles(fds, &fdps, map[string]struct{}{})
return &dpb.FileDescriptorSet{File: fdps}
}
func addAllFiles(src []*FileDescriptor, results *[]*dpb.FileDescriptorProto, seen map[string]struct{}) {
for _, fd := range src {
if _, ok := seen[fd.GetName()]; ok {
continue
}
seen[fd.GetName()] = struct{}{}
addAllFiles(fd.GetDependencies(), results, seen)
*results = append(*results, fd.AsFileDescriptorProto())
}
}
// CreateFileDescriptorFromSet creates a descriptor from the given file descriptor set. The
// set's *last* file will be the returned descriptor. The set's remaining files must comprise
// the full set of transitive dependencies of that last file. This is the same format and
// order used by protoc when emitting a FileDescriptorSet file with an invocation like so:
// protoc --descriptor_set_out=./test.protoset --include_imports -I. test.proto
func CreateFileDescriptorFromSet(fds *dpb.FileDescriptorSet) (*FileDescriptor, error) {
files := fds.GetFile()
if len(files) == 0 {
return nil, errors.New("file descriptor set is empty")
}
resolved, err := CreateFileDescriptors(files)
if err != nil {
return nil, err
}
lastFilename := files[len(files)-1].GetName()
return resolved[lastFilename], nil
}
// createFromSet creates a descriptor for the given filename. It recursively
// creates descriptors for the given file's dependencies.
func createFromSet(filename string, seen []string, files map[string]*dpb.FileDescriptorProto, resolved map[string]*FileDescriptor) (*FileDescriptor, error) {
for _, s := range seen {
if filename == s {
return nil, fmt.Errorf("cycle in imports: %s", strings.Join(append(seen, filename), " -> "))
}
}
seen = append(seen, filename)
if d, ok := resolved[filename]; ok {
return d, nil
}
fdp := files[filename]
if fdp == nil {
return nil, fmt.Errorf("file descriptor set missing a dependency: %s", filename)
}
deps := make([]*FileDescriptor, len(fdp.GetDependency()))
for i, depName := range fdp.GetDependency() {
if dep, err := createFromSet(depName, seen, files, resolved); err != nil {
return nil, err
} else {
deps[i] = dep
}
}
d, err := CreateFileDescriptor(fdp, deps...)
if err != nil {
return nil, err
}
resolved[filename] = d
return d, nil
}
func (fd *FileDescriptor) registerField(field *FieldDescriptor) {
fields := fd.fieldIndex[field.owner.GetFullyQualifiedName()]
if fields == nil {
fields = map[int32]*FieldDescriptor{}
fd.fieldIndex[field.owner.GetFullyQualifiedName()] = fields
}
fields[field.GetNumber()] = field
}
// GetName returns the name of the file, as it was given to the protoc invocation
// to compile it, possibly including path (relative to a directory in the proto
// import path).
func (fd *FileDescriptor) GetName() string {
return fd.proto.GetName()
}
// GetFullyQualifiedName returns the name of the file, same as GetName. It is
// present to satisfy the Descriptor interface.
func (fd *FileDescriptor) GetFullyQualifiedName() string {
return fd.proto.GetName()
}
// GetPackage returns the name of the package declared in the file.
func (fd *FileDescriptor) GetPackage() string {
return fd.proto.GetPackage()
}
// GetParent always returns nil: files are the root of descriptor hierarchies.
// Is it present to satisfy the Descriptor interface.
func (fd *FileDescriptor) GetParent() Descriptor {
return nil
}
// GetFile returns the receiver, which is a file descriptor. This is present
// to satisfy the Descriptor interface.
func (fd *FileDescriptor) GetFile() *FileDescriptor {
return fd
}
// GetOptions returns the file's options. Most usages will be more interested
// in GetFileOptions, which has a concrete return type. This generic version
// is present to satisfy the Descriptor interface.
func (fd *FileDescriptor) GetOptions() proto.Message {
return fd.proto.GetOptions()
}
// GetFileOptions returns the file's options.
func (fd *FileDescriptor) GetFileOptions() *dpb.FileOptions {
return fd.proto.GetOptions()
}
// GetSourceInfo returns nil for files. It is present to satisfy the Descriptor
// interface.
func (fd *FileDescriptor) GetSourceInfo() *dpb.SourceCodeInfo_Location {
return nil
}
// AsProto returns the underlying descriptor proto. Most usages will be more
// interested in AsFileDescriptorProto, which has a concrete return type. This
// generic version is present to satisfy the Descriptor interface.
func (fd *FileDescriptor) AsProto() proto.Message {
return fd.proto
}
// AsFileDescriptorProto returns the underlying descriptor proto.
func (fd *FileDescriptor) AsFileDescriptorProto() *dpb.FileDescriptorProto {
return fd.proto
}
// String returns the underlying descriptor proto, in compact text format.
func (fd *FileDescriptor) String() string {
return fd.proto.String()
}
// IsProto3 returns true if the file declares a syntax of "proto3".
func (fd *FileDescriptor) IsProto3() bool {
return fd.isProto3
}
// GetDependencies returns all of this file's dependencies. These correspond to
// import statements in the file.
func (fd *FileDescriptor) GetDependencies() []*FileDescriptor {
return fd.deps
}
// GetPublicDependencies returns all of this file's public dependencies. These
// correspond to public import statements in the file.
func (fd *FileDescriptor) GetPublicDependencies() []*FileDescriptor {
return fd.publicDeps
}
// GetWeakDependencies returns all of this file's weak dependencies. These
// correspond to weak import statements in the file.
func (fd *FileDescriptor) GetWeakDependencies() []*FileDescriptor {
return fd.weakDeps
}
// GetMessageTypes returns all top-level messages declared in this file.
func (fd *FileDescriptor) GetMessageTypes() []*MessageDescriptor {
return fd.messages
}
// GetEnumTypes returns all top-level enums declared in this file.
func (fd *FileDescriptor) GetEnumTypes() []*EnumDescriptor {
return fd.enums
}
// GetExtensions returns all top-level extensions declared in this file.
func (fd *FileDescriptor) GetExtensions() []*FieldDescriptor {
return fd.extensions
}
// GetServices returns all services declared in this file.
func (fd *FileDescriptor) GetServices() []*ServiceDescriptor {
return fd.services
}
// FindSymbol returns the descriptor contained within this file for the
// element with the given fully-qualified symbol name. If no such element
// exists then this method returns nil.
func (fd *FileDescriptor) FindSymbol(symbol string) Descriptor {
if symbol[0] == '.' {
symbol = symbol[1:]
}
return fd.symbols[symbol]
}
// FindMessage finds the message with the given fully-qualified name. If no
// such element exists in this file then nil is returned.
func (fd *FileDescriptor) FindMessage(msgName string) *MessageDescriptor {
if md, ok := fd.symbols[msgName].(*MessageDescriptor); ok {
return md
} else {
return nil
}
}
// FindEnum finds the enum with the given fully-qualified name. If no such
// element exists in this file then nil is returned.
func (fd *FileDescriptor) FindEnum(enumName string) *EnumDescriptor {
if ed, ok := fd.symbols[enumName].(*EnumDescriptor); ok {
return ed
} else {
return nil
}
}
// FindService finds the service with the given fully-qualified name. If no
// such element exists in this file then nil is returned.
func (fd *FileDescriptor) FindService(serviceName string) *ServiceDescriptor {
if sd, ok := fd.symbols[serviceName].(*ServiceDescriptor); ok {
return sd
} else {
return nil
}
}
// FindExtension finds the extension field for the given extended type name and
// tag number. If no such element exists in this file then nil is returned.
func (fd *FileDescriptor) FindExtension(extendeeName string, tagNumber int32) *FieldDescriptor {
if exd, ok := fd.fieldIndex[extendeeName][tagNumber]; ok && exd.IsExtension() {
return exd
} else {
return nil
}
}
// FindExtensionByName finds the extension field with the given fully-qualified
// name. If no such element exists in this file then nil is returned.
func (fd *FileDescriptor) FindExtensionByName(extName string) *FieldDescriptor {
if exd, ok := fd.symbols[extName].(*FieldDescriptor); ok && exd.IsExtension() {
return exd
} else {
return nil
}
}
// MessageDescriptor describes a protocol buffer message.
type MessageDescriptor struct {
proto *dpb.DescriptorProto
parent Descriptor
file *FileDescriptor
fields []*FieldDescriptor
nested []*MessageDescriptor
enums []*EnumDescriptor
extensions []*FieldDescriptor
oneOfs []*OneOfDescriptor
extRanges extRanges
fqn string
sourceInfo *dpb.SourceCodeInfo_Location
jsonNames jsonNameMap
isProto3 bool
isMapEntry bool
}
func createMessageDescriptor(fd *FileDescriptor, parent Descriptor, enclosing string, md *dpb.DescriptorProto, symbols map[string]Descriptor) (*MessageDescriptor, string) {
msgName := merge(enclosing, md.GetName())
ret := &MessageDescriptor{proto: md, parent: parent, file: fd, fqn: msgName}
for _, f := range md.GetField() {
fld, n := createFieldDescriptor(fd, ret, msgName, f)
symbols[n] = fld
ret.fields = append(ret.fields, fld)
}
for _, nm := range md.NestedType {
nmd, n := createMessageDescriptor(fd, ret, msgName, nm, symbols)
symbols[n] = nmd
ret.nested = append(ret.nested, nmd)
}
for _, e := range md.EnumType {
ed, n := createEnumDescriptor(fd, ret, msgName, e, symbols)
symbols[n] = ed
ret.enums = append(ret.enums, ed)
}
for _, ex := range md.GetExtension() {
exd, n := createFieldDescriptor(fd, ret, msgName, ex)
symbols[n] = exd
ret.extensions = append(ret.extensions, exd)
}
for i, o := range md.GetOneofDecl() {
od, n := createOneOfDescriptor(fd, ret, i, msgName, o)
symbols[n] = od
ret.oneOfs = append(ret.oneOfs, od)
}
for _, r := range md.GetExtensionRange() {
// proto.ExtensionRange is inclusive (and that's how extension ranges are defined in code).
// but protoc converts range to exclusive end in descriptor, so we must convert back
end := r.GetEnd() - 1
ret.extRanges = append(ret.extRanges, proto.ExtensionRange{
Start: r.GetStart(),
End: end})
}
sort.Sort(ret.extRanges)
ret.isProto3 = fd.isProto3
ret.isMapEntry = md.GetOptions().GetMapEntry() &&
len(ret.fields) == 2 &&
ret.fields[0].GetNumber() == 1 &&
ret.fields[1].GetNumber() == 2
return ret, msgName
}
func (md *MessageDescriptor) resolve(path []int32, sourceCodeInfo descinternal.SourceInfoMap, scopes []scope) error {
md.sourceInfo = sourceCodeInfo.Get(path)
path = append(path, descinternal.Message_nestedMessagesTag)
scopes = append(scopes, messageScope(md))
for i, nmd := range md.nested {
if err := nmd.resolve(append(path, int32(i)), sourceCodeInfo, scopes); err != nil {
return err
}
}
path[len(path)-1] = descinternal.Message_enumsTag
for i, ed := range md.enums {
ed.resolve(append(path, int32(i)), sourceCodeInfo)
}
path[len(path)-1] = descinternal.Message_fieldsTag
for i, fld := range md.fields {
if err := fld.resolve(append(path, int32(i)), sourceCodeInfo, scopes); err != nil {
return err
}
}
path[len(path)-1] = descinternal.Message_extensionsTag
for i, exd := range md.extensions {
if err := exd.resolve(append(path, int32(i)), sourceCodeInfo, scopes); err != nil {
return err
}
}
path[len(path)-1] = descinternal.Message_oneOfsTag
for i, od := range md.oneOfs {
od.resolve(append(path, int32(i)), sourceCodeInfo)
}
return nil
}
// GetName returns the simple (unqualified) name of the message.
func (md *MessageDescriptor) GetName() string {
return md.proto.GetName()
}
// GetFullyQualifiedName returns the fully qualified name of the message. This
// includes the package name (if there is one) as well as the names of any
// enclosing messages.
func (md *MessageDescriptor) GetFullyQualifiedName() string {
return md.fqn
}
// GetParent returns the message's enclosing descriptor. For top-level messages,
// this will be a file descriptor. Otherwise it will be the descriptor for the
// enclosing message.
func (md *MessageDescriptor) GetParent() Descriptor {
return md.parent
}
// GetFile returns the descriptor for the file in which this message is defined.
func (md *MessageDescriptor) GetFile() *FileDescriptor {
return md.file
}
// GetOptions returns the message's options. Most usages will be more interested
// in GetMessageOptions, which has a concrete return type. This generic version
// is present to satisfy the Descriptor interface.
func (md *MessageDescriptor) GetOptions() proto.Message {
return md.proto.GetOptions()
}
// GetMessageOptions returns the message's options.
func (md *MessageDescriptor) GetMessageOptions() *dpb.MessageOptions {
return md.proto.GetOptions()
}
// GetSourceInfo returns source info for the message, if present in the
// descriptor. Not all descriptors will contain source info. If non-nil, the
// returned info contains information about the location in the file where the
// message was defined and also contains comments associated with the message
// definition.
func (md *MessageDescriptor) GetSourceInfo() *dpb.SourceCodeInfo_Location {
return md.sourceInfo
}
// AsProto returns the underlying descriptor proto. Most usages will be more
// interested in AsDescriptorProto, which has a concrete return type. This
// generic version is present to satisfy the Descriptor interface.
func (md *MessageDescriptor) AsProto() proto.Message {
return md.proto
}
// AsDescriptorProto returns the underlying descriptor proto.
func (md *MessageDescriptor) AsDescriptorProto() *dpb.DescriptorProto {
return md.proto
}
// String returns the underlying descriptor proto, in compact text format.
func (md *MessageDescriptor) String() string {
return md.proto.String()
}
// IsMapEntry returns true if this is a synthetic message type that represents an entry
// in a map field.
func (md *MessageDescriptor) IsMapEntry() bool {
return md.isMapEntry
}
// GetFields returns all of the fields for this message.
func (md *MessageDescriptor) GetFields() []*FieldDescriptor {
return md.fields
}
// GetNestedMessageTypes returns all of the message types declared inside this message.
func (md *MessageDescriptor) GetNestedMessageTypes() []*MessageDescriptor {
return md.nested
}
// GetNestedEnumTypes returns all of the enums declared inside this message.
func (md *MessageDescriptor) GetNestedEnumTypes() []*EnumDescriptor {
return md.enums
}
// GetNestedExtensions returns all of the extensions declared inside this message.
func (md *MessageDescriptor) GetNestedExtensions() []*FieldDescriptor {
return md.extensions
}
// GetOneOfs returns all of the one-of field sets declared inside this message.
func (md *MessageDescriptor) GetOneOfs() []*OneOfDescriptor {
return md.oneOfs
}
// IsProto3 returns true if the file in which this message is defined declares a syntax of "proto3".
func (md *MessageDescriptor) IsProto3() bool {
return md.isProto3
}
// GetExtensionRanges returns the ranges of extension field numbers for this message.
func (md *MessageDescriptor) GetExtensionRanges() []proto.ExtensionRange {
return md.extRanges
}
// IsExtendable returns true if this message has any extension ranges.
func (md *MessageDescriptor) IsExtendable() bool {
return len(md.extRanges) > 0
}
// IsExtension returns true if the given tag number is within any of this message's
// extension ranges.
func (md *MessageDescriptor) IsExtension(tagNumber int32) bool {
return md.extRanges.IsExtension(tagNumber)
}
type extRanges []proto.ExtensionRange
func (er extRanges) String() string {
var buf bytes.Buffer
first := true
for _, r := range er {
if first {
first = false
} else {
buf.WriteString(",")
}
fmt.Fprintf(&buf, "%d..%d", r.Start, r.End)
}
return buf.String()
}
func (er extRanges) IsExtension(tagNumber int32) bool {
i := sort.Search(len(er), func(i int) bool { return er[i].End >= tagNumber })
return i < len(er) && tagNumber >= er[i].Start
}
func (er extRanges) Len() int {
return len(er)
}
func (er extRanges) Less(i, j int) bool {
return er[i].Start < er[j].Start
}
func (er extRanges) Swap(i, j int) {
er[i], er[j] = er[j], er[i]
}
// FindFieldByName finds the field with the given name. If no such field exists
// then nil is returned. Only regular fields are returned, not extensions.
func (md *MessageDescriptor) FindFieldByName(fieldName string) *FieldDescriptor {
fqn := fmt.Sprintf("%s.%s", md.fqn, fieldName)
if fd, ok := md.file.symbols[fqn].(*FieldDescriptor); ok && !fd.IsExtension() {
return fd
} else {
return nil
}
}
// FindFieldByNumber finds the field with the given tag number. If no such field
// exists then nil is returned. Only regular fields are returned, not extensions.
func (md *MessageDescriptor) FindFieldByNumber(tagNumber int32) *FieldDescriptor {
if fd, ok := md.file.fieldIndex[md.fqn][tagNumber]; ok && !fd.IsExtension() {
return fd
} else {
return nil
}
}
// FieldDescriptor describes a field of a protocol buffer message.
type FieldDescriptor struct {
proto *dpb.FieldDescriptorProto
parent Descriptor
owner *MessageDescriptor
file *FileDescriptor
oneOf *OneOfDescriptor
msgType *MessageDescriptor
enumType *EnumDescriptor
fqn string
sourceInfo *dpb.SourceCodeInfo_Location
def memoizedDefault
isMap bool
}
func createFieldDescriptor(fd *FileDescriptor, parent Descriptor, enclosing string, fld *dpb.FieldDescriptorProto) (*FieldDescriptor, string) {
fldName := merge(enclosing, fld.GetName())
ret := &FieldDescriptor{proto: fld, parent: parent, file: fd, fqn: fldName}
if fld.GetExtendee() == "" {
ret.owner = parent.(*MessageDescriptor)
}
// owner for extensions, field type (be it message or enum), and one-ofs get resolved later
return ret, fldName
}
func (fd *FieldDescriptor) resolve(path []int32, sourceCodeInfo descinternal.SourceInfoMap, scopes []scope) error {
if fd.proto.OneofIndex != nil && fd.oneOf == nil {
return fmt.Errorf("Could not link field %s to one-of index %d", fd.fqn, *fd.proto.OneofIndex)
}
fd.sourceInfo = sourceCodeInfo.Get(path)
if fd.proto.GetType() == dpb.FieldDescriptorProto_TYPE_ENUM {
if desc, err := resolve(fd.file, fd.proto.GetTypeName(), scopes); err != nil {
return err
} else {
fd.enumType = desc.(*EnumDescriptor)
}
}
if fd.proto.GetType() == dpb.FieldDescriptorProto_TYPE_MESSAGE || fd.proto.GetType() == dpb.FieldDescriptorProto_TYPE_GROUP {
if desc, err := resolve(fd.file, fd.proto.GetTypeName(), scopes); err != nil {
return err
} else {
fd.msgType = desc.(*MessageDescriptor)
}
}
if fd.proto.GetExtendee() != "" {
if desc, err := resolve(fd.file, fd.proto.GetExtendee(), scopes); err != nil {
return err
} else {
fd.owner = desc.(*MessageDescriptor)
}
}
fd.file.registerField(fd)
fd.isMap = fd.proto.GetLabel() == dpb.FieldDescriptorProto_LABEL_REPEATED &&
fd.proto.GetType() == dpb.FieldDescriptorProto_TYPE_MESSAGE &&
fd.GetMessageType().IsMapEntry()
return nil
}
func (fd *FieldDescriptor) determineDefault() interface{} {
if fd.IsMap() {
return map[interface{}]interface{}(nil)
} else if fd.IsRepeated() {
return []interface{}(nil)
} else if fd.msgType != nil {
return nil
}
proto3 := fd.file.isProto3
if !proto3 {
def := fd.AsFieldDescriptorProto().GetDefaultValue()
if def != "" {
ret := parseDefaultValue(fd, def)
if ret != nil {
return ret
}
// if we can't parse default value, fall-through to return normal default...
}
}
switch fd.GetType() {
case dpb.FieldDescriptorProto_TYPE_FIXED32,
dpb.FieldDescriptorProto_TYPE_UINT32:
return uint32(0)
case dpb.FieldDescriptorProto_TYPE_SFIXED32,
dpb.FieldDescriptorProto_TYPE_INT32,
dpb.FieldDescriptorProto_TYPE_SINT32:
return int32(0)
case dpb.FieldDescriptorProto_TYPE_FIXED64,
dpb.FieldDescriptorProto_TYPE_UINT64:
return uint64(0)
case dpb.FieldDescriptorProto_TYPE_SFIXED64,
dpb.FieldDescriptorProto_TYPE_INT64,
dpb.FieldDescriptorProto_TYPE_SINT64:
return int64(0)
case dpb.FieldDescriptorProto_TYPE_FLOAT:
return float32(0.0)
case dpb.FieldDescriptorProto_TYPE_DOUBLE:
return float64(0.0)
case dpb.FieldDescriptorProto_TYPE_BOOL:
return false
case dpb.FieldDescriptorProto_TYPE_BYTES:
return []byte(nil)
case dpb.FieldDescriptorProto_TYPE_STRING:
return ""
case dpb.FieldDescriptorProto_TYPE_ENUM:
if proto3 {
return int32(0)
}
enumVals := fd.GetEnumType().GetValues()
if len(enumVals) > 0 {
return enumVals[0].GetNumber()
} else {
return int32(0) // WTF?
}
default:
panic(fmt.Sprintf("Unknown field type: %v", fd.GetType()))
}
}
func parseDefaultValue(fd *FieldDescriptor, val string) interface{} {
switch fd.GetType() {
case dpb.FieldDescriptorProto_TYPE_ENUM:
vd := fd.GetEnumType().FindValueByName(val)
if vd != nil {
return vd.GetNumber()
}
return nil
case dpb.FieldDescriptorProto_TYPE_BOOL:
if val == "true" {
return true
} else if val == "false" {
return false
}
return nil
case dpb.FieldDescriptorProto_TYPE_BYTES:
return []byte(unescape(val))
case dpb.FieldDescriptorProto_TYPE_STRING:
return val
case dpb.FieldDescriptorProto_TYPE_FLOAT:
if f, err := strconv.ParseFloat(val, 32); err == nil {
return float32(f)
} else {
return float32(0)
}
case dpb.FieldDescriptorProto_TYPE_DOUBLE:
if f, err := strconv.ParseFloat(val, 64); err == nil {
return f
} else {
return float64(0)
}
case dpb.FieldDescriptorProto_TYPE_INT32,
dpb.FieldDescriptorProto_TYPE_SINT32,
dpb.FieldDescriptorProto_TYPE_SFIXED32:
if i, err := strconv.ParseInt(val, 10, 32); err == nil {
return int32(i)
} else {
return int32(0)
}
case dpb.FieldDescriptorProto_TYPE_UINT32,
dpb.FieldDescriptorProto_TYPE_FIXED32:
if i, err := strconv.ParseUint(val, 10, 32); err == nil {
return uint32(i)
} else {
return uint32(0)
}
case dpb.FieldDescriptorProto_TYPE_INT64,
dpb.FieldDescriptorProto_TYPE_SINT64,
dpb.FieldDescriptorProto_TYPE_SFIXED64:
if i, err := strconv.ParseInt(val, 10, 64); err == nil {
return i
} else {
return int64(0)
}
case dpb.FieldDescriptorProto_TYPE_UINT64,
dpb.FieldDescriptorProto_TYPE_FIXED64:
if i, err := strconv.ParseUint(val, 10, 64); err == nil {
return i
} else {
return uint64(0)
}
default:
return nil
}
}
func unescape(s string) string {
// protoc encodes default values for 'bytes' fields using C escaping,
// so this function reverses that escaping
out := make([]byte, 0, len(s))
var buf [4]byte
for len(s) > 0 {
if s[0] != '\\' || len(s) < 2 {
// not escape sequence, or too short to be well-formed escape
out = append(out, s[0])
s = s[1:]
} else if s[1] == 'x' || s[1] == 'X' {
n := matchPrefix(s[2:], 2, isHex)
if n == 0 {
// bad escape
out = append(out, s[:2]...)
s = s[2:]
} else {
c, err := strconv.ParseUint(s[2:2+n], 16, 8)
if err != nil {
// shouldn't really happen...
out = append(out, s[:2+n]...)
} else {
out = append(out, byte(c))
}
s = s[2+n:]
}
} else if s[1] >= '0' && s[1] <= '7' {
n := 1 + matchPrefix(s[2:], 2, isOctal)
c, err := strconv.ParseUint(s[1:1+n], 8, 8)
if err != nil || c > 0xff {
out = append(out, s[:1+n]...)
} else {
out = append(out, byte(c))
}
s = s[1+n:]
} else if s[1] == 'u' {
if len(s) < 6 {
// bad escape
out = append(out, s...)
s = s[len(s):]
} else {
c, err := strconv.ParseUint(s[2:6], 16, 16)
if err != nil {
// bad escape
out = append(out, s[:6]...)
} else {
w := utf8.EncodeRune(buf[:], rune(c))
out = append(out, buf[:w]...)
}
s = s[6:]
}
} else if s[1] == 'U' {
if len(s) < 10 {
// bad escape
out = append(out, s...)
s = s[len(s):]
} else {
c, err := strconv.ParseUint(s[2:10], 16, 32)
if err != nil || c > 0x10ffff {
// bad escape
out = append(out, s[:10]...)
} else {
w := utf8.EncodeRune(buf[:], rune(c))
out = append(out, buf[:w]...)
}
s = s[10:]
}
} else {
switch s[1] {
case 'a':
out = append(out, '\a')
case 'b':
out = append(out, '\b')
case 'f':
out = append(out, '\f')
case 'n':
out = append(out, '\n')
case 'r':
out = append(out, '\r')
case 't':
out = append(out, '\t')
case 'v':
out = append(out, '\v')
case '\\':
out = append(out, '\\')
case '\'':
out = append(out, '\'')
case '"':
out = append(out, '"')
case '?':
out = append(out, '?')
default:
// invalid escape, just copy it as-is
out = append(out, s[:2]...)
}
s = s[2:]
}
}
return string(out)
}
func isOctal(b byte) bool { return b >= '0' && b <= '7' }
func isHex(b byte) bool {
return (b >= '0' && b <= '9') || (b >= 'a' && b <= 'f') || (b >= 'A' && b <= 'F')
}
func matchPrefix(s string, limit int, fn func(byte) bool) int {
l := len(s)
if l > limit {
l = limit
}
i := 0
for ; i < l; i++ {
if !fn(s[i]) {
return i
}
}
return i
}
// GetName returns the name of the field.
func (fd *FieldDescriptor) GetName() string {
return fd.proto.GetName()
}
// GetNumber returns the tag number of this field.
func (fd *FieldDescriptor) GetNumber() int32 {
return fd.proto.GetNumber()
}
// GetFullyQualifiedName returns the fully qualified name of the field. Unlike
// GetName, this includes fully qualified name of the enclosing message for
// regular fields.
//