-
Notifications
You must be signed in to change notification settings - Fork 167
/
print.go
2744 lines (2471 loc) · 84.2 KB
/
print.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 protoprint
import (
"bytes"
"fmt"
"io"
"math"
"os"
"path/filepath"
"reflect"
"sort"
"strings"
"unicode"
"unicode/utf8"
protov1 "github.com/golang/protobuf/proto"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/reflect/protoreflect"
"google.golang.org/protobuf/reflect/protoregistry"
"google.golang.org/protobuf/types/descriptorpb"
"google.golang.org/protobuf/types/dynamicpb"
"github.com/jhump/protoreflect/desc"
"github.com/jhump/protoreflect/desc/internal"
)
// Printer knows how to format file descriptors as proto source code. Its fields
// provide some control over how the resulting source file is constructed and
// formatted.
type Printer struct {
// If true, comments are rendered using "/*" style comments. Otherwise, they
// are printed using "//" style line comments.
PreferMultiLineStyleComments bool
// If true, elements are sorted into a canonical order.
//
// The canonical order for elements in a file follows:
// 1. Syntax
// 2. Package
// 3. Imports (sorted lexically)
// 4. Options (sorted by name, standard options before custom options)
// 5. Messages (sorted by name)
// 6. Enums (sorted by name)
// 7. Services (sorted by name)
// 8. Extensions (grouped by extendee, sorted by extendee+tag)
//
// The canonical order of elements in a message follows:
// 1. Options (sorted by name, standard options before custom options)
// 2. Fields and One-Ofs (sorted by tag; one-ofs interleaved based on the
// minimum tag therein)
// 3. Nested Messages (sorted by name)
// 4. Nested Enums (sorted by name)
// 5. Extension ranges (sorted by starting tag number)
// 6. Nested Extensions (grouped by extendee, sorted by extendee+tag)
// 7. Reserved ranges (sorted by starting tag number)
// 8. Reserved names (sorted lexically)
//
// Methods are sorted within a service by name and appear after any service
// options (which are sorted by name, standard options before custom ones).
// Enum values are sorted within an enum, first by numeric value then by
// name, and also appear after any enum options.
//
// Options for fields, enum values, and extension ranges are sorted by name,
// standard options before custom ones.
SortElements bool
// The "less" function used to sort elements when printing. It is given two
// elements, a and b, and should return true if a is "less than" b. In this
// case, "less than" means that element a should appear earlier in the file
// than element b.
//
// If this field is nil, no custom sorting is done and the SortElements
// field is consulted to decide how to order the output. If this field is
// non-nil, the SortElements field is ignored and this function is called to
// order elements.
CustomSortFunction func(a, b Element) bool
// The indentation used. Any characters other than spaces or tabs will be
// replaced with spaces. If unset/empty, two spaces will be used.
Indent string
// If true, detached comments (between elements) will be ignored.
//
// Deprecated: Use OmitComments bitmask instead.
OmitDetachedComments bool
// A bitmask of comment types to omit. If unset, all comments will be
// included. Use CommentsAll to not print any comments.
OmitComments CommentType
// If true, trailing comments that typically appear on the same line as an
// element (option, field, enum value, method) will be printed on a separate
// line instead.
//
// So, with this set, you'll get output like so:
//
// // leading comment for field
// repeated string names = 1;
// // trailing comment
//
// If left false, the printer will try to emit trailing comments on the same
// line instead:
//
// // leading comment for field
// repeated string names = 1; // trailing comment
//
// If the trailing comment has more than one line, it will automatically be
// forced to the next line.
TrailingCommentsOnSeparateLine bool
// If true, the printed output will eschew any blank lines, which otherwise
// appear between descriptor elements and comment blocks. Note that if
// detached comments are being printed, this will cause them to be merged
// into the subsequent leading comments. Similarly, any element trailing
// comments will be merged into the subsequent leading comments.
Compact bool
// If true, all references to messages, extensions, and enums (such as in
// options, field types, and method request and response types) will be
// fully-qualified. When left unset, the referenced elements will contain
// only as much qualifier as is required.
//
// For example, if a message is in the same package as the reference, the
// simple name can be used. If a message shares some context with the
// reference, only the unshared context needs to be included. For example:
//
// message Foo {
// message Bar {
// enum Baz {
// ZERO = 0;
// ONE = 1;
// }
// }
//
// // This field shares some context as the enum it references: they are
// // both inside of the namespace Foo:
// // field is "Foo.my_baz"
// // enum is "Foo.Bar.Baz"
// // So we only need to qualify the reference with the context that they
// // do NOT have in common:
// Bar.Baz my_baz = 1;
// }
//
// When printing fully-qualified names, they will be preceded by a dot, to
// avoid any ambiguity that they might be relative vs. fully-qualified.
ForceFullyQualifiedNames bool
// The number of options that trigger short options expressions to be
// rendered using multiple lines. Short options expressions are those
// found on fields and enum values, that use brackets ("[" and "]") and
// comma-separated options. If more options than this are present, they
// will be expanded to multiple lines (one option per line).
//
// If unset (e.g. if zero), a default threshold of 3 is used.
ShortOptionsExpansionThresholdCount int
// The length of printed options that trigger short options expressions to
// be rendered using multiple lines. If the short options contain more than
// one option and their printed length is longer than this threshold, they
// will be expanded to multiple lines (one option per line).
//
// If unset (e.g. if zero), a default threshold of 50 is used.
ShortOptionsExpansionThresholdLength int
// The length of a printed option value message literal that triggers the
// message literal to be rendered using multiple lines instead of using a
// compact single-line form. The message must include at least two fields
// or contain a field that is a nested message to be expanded.
//
// This value is further used to decide when to expand individual field
// values that are nested message literals or array literals (for repeated
// fields).
//
// If unset (e.g. if zero), a default threshold of 50 is used.
MessageLiteralExpansionThresholdLength int
}
// CommentType is a kind of comments in a proto source file. This can be used
// as a bitmask.
type CommentType int
const (
// CommentsDetached refers to comments that are not "attached" to any
// source element. They are attributed to the subsequent element in the
// file as "detached" comments.
CommentsDetached CommentType = 1 << iota
// CommentsTrailing refers to a comment block immediately following an
// element in the source file. If another element immediately follows
// the trailing comment, it is instead considered a leading comment for
// that subsequent element.
CommentsTrailing
// CommentsLeading refers to a comment block immediately preceding an
// element in the source file. For high-level elements (those that have
// their own descriptor), these are used as doc comments for that element.
CommentsLeading
// CommentsTokens refers to any comments (leading, trailing, or detached)
// on low-level elements in the file. "High-level" elements have their own
// descriptors, e.g. messages, enums, fields, services, and methods. But
// comments can appear anywhere (such as around identifiers and keywords,
// sprinkled inside the declarations of a high-level element). This class
// of comments are for those extra comments sprinkled into the file.
CommentsTokens
// CommentsNonDoc refers to comments that are *not* doc comments. This is a
// bitwise union of everything other than CommentsLeading. If you configure
// a printer to omit this, only doc comments on descriptor elements will be
// included in the printed output.
CommentsNonDoc = CommentsDetached | CommentsTrailing | CommentsTokens
// CommentsAll indicates all kinds of comments. If you configure a printer
// to omit this, no comments will appear in the printed output, even if the
// input descriptors had source info and comments.
CommentsAll = -1
)
// PrintProtoFiles prints all of the given file descriptors. The given open
// function is given a file name and is responsible for creating the outputs and
// returning the corresponding writer.
func (p *Printer) PrintProtoFiles(fds []*desc.FileDescriptor, open func(name string) (io.WriteCloser, error)) error {
for _, fd := range fds {
w, err := open(fd.GetName())
if err != nil {
return fmt.Errorf("failed to open %s: %v", fd.GetName(), err)
}
err = func() error {
defer w.Close()
return p.PrintProtoFile(fd, w)
}()
if err != nil {
return fmt.Errorf("failed to write %s: %v", fd.GetName(), err)
}
}
return nil
}
// PrintProtosToFileSystem prints all of the given file descriptors to files in
// the given directory. If file names in the given descriptors include path
// information, they will be relative to the given root.
func (p *Printer) PrintProtosToFileSystem(fds []*desc.FileDescriptor, rootDir string) error {
return p.PrintProtoFiles(fds, func(name string) (io.WriteCloser, error) {
fullPath := filepath.Join(rootDir, name)
dir := filepath.Dir(fullPath)
if err := os.MkdirAll(dir, os.ModePerm); err != nil {
return nil, err
}
return os.OpenFile(fullPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)
})
}
// pkg represents a package name
type pkg string
// imp represents an imported file name
type imp string
// ident represents an identifier
type ident string
// messageVal represents a message value for an option
type messageVal struct {
// the package and scope in which the option value is defined
pkg, scope string
// the option value
msg proto.Message
}
// option represents a resolved descriptor option
type option struct {
name string
val interface{}
}
// reservedRange represents a reserved range from a message or enum
type reservedRange struct {
start, end int32
}
// PrintProtoFile prints the given single file descriptor to the given writer.
func (p *Printer) PrintProtoFile(fd *desc.FileDescriptor, out io.Writer) error {
return p.printProto(fd, out)
}
// PrintProtoToString prints the given descriptor and returns the resulting
// string. This can be used to print proto files, but it can also be used to get
// the proto "source form" for any kind of descriptor, which can be a more
// user-friendly way to present descriptors that are intended for human
// consumption.
func (p *Printer) PrintProtoToString(dsc desc.Descriptor) (string, error) {
var buf bytes.Buffer
if err := p.printProto(dsc, &buf); err != nil {
return "", err
}
return buf.String(), nil
}
func (p *Printer) printProto(dsc desc.Descriptor, out io.Writer) error {
w := newWriter(out)
if p.Indent == "" {
// default indent to two spaces
p.Indent = " "
} else {
// indent must be all spaces or tabs, so convert other chars to spaces
ind := make([]rune, 0, len(p.Indent))
for _, r := range p.Indent {
if r == '\t' {
ind = append(ind, r)
} else {
ind = append(ind, ' ')
}
}
p.Indent = string(ind)
}
if p.OmitDetachedComments {
p.OmitComments |= CommentsDetached
}
fdp := dsc.GetFile().AsFileDescriptorProto()
sourceInfo := internal.CreateSourceInfoMap(fdp)
extendOptionLocations(sourceInfo, fdp.GetSourceCodeInfo().GetLocation())
var reg protoregistry.Types
internal.RegisterTypesVisibleToFile(®, dsc.GetFile().UnwrapFile())
reparseUnknown(®, fdp.ProtoReflect())
path := findElement(dsc)
switch d := dsc.(type) {
case *desc.FileDescriptor:
p.printFile(d, ®, w, sourceInfo)
case *desc.MessageDescriptor:
p.printMessage(d, ®, w, sourceInfo, path, 0)
case *desc.FieldDescriptor:
var scope string
if md, ok := d.GetParent().(*desc.MessageDescriptor); ok {
scope = md.GetFullyQualifiedName()
} else {
scope = d.GetFile().GetPackage()
}
if d.IsExtension() {
_, _ = fmt.Fprint(w, "extend ")
extNameSi := sourceInfo.Get(append(path, internal.Field_extendeeTag))
p.printElementString(extNameSi, w, 0, p.qualifyName(d.GetFile().GetPackage(), scope, d.GetOwner().GetFullyQualifiedName()))
_, _ = fmt.Fprintln(w, "{")
p.printField(d, ®, w, sourceInfo, path, scope, 1)
_, _ = fmt.Fprintln(w, "}")
} else {
p.printField(d, ®, w, sourceInfo, path, scope, 0)
}
case *desc.OneOfDescriptor:
md := d.GetOwner()
elements := elementAddrs{dsc: md}
for i := range md.GetFields() {
elements.addrs = append(elements.addrs, elementAddr{elementType: internal.Message_fieldsTag, elementIndex: i})
}
p.printOneOf(d, elements, 0, ®, w, sourceInfo, path[:len(path)-1], 0, path[len(path)-1])
case *desc.EnumDescriptor:
p.printEnum(d, ®, w, sourceInfo, path, 0)
case *desc.EnumValueDescriptor:
p.printEnumValue(d, ®, w, sourceInfo, path, 0)
case *desc.ServiceDescriptor:
p.printService(d, ®, w, sourceInfo, path, 0)
case *desc.MethodDescriptor:
p.printMethod(d, ®, w, sourceInfo, path, 0)
}
return w.err
}
func findElement(dsc desc.Descriptor) []int32 {
if dsc.GetParent() == nil {
return nil
}
path := findElement(dsc.GetParent())
switch d := dsc.(type) {
case *desc.MessageDescriptor:
if pm, ok := d.GetParent().(*desc.MessageDescriptor); ok {
return append(path, internal.Message_nestedMessagesTag, getMessageIndex(d, pm.GetNestedMessageTypes()))
}
return append(path, internal.File_messagesTag, getMessageIndex(d, d.GetFile().GetMessageTypes()))
case *desc.FieldDescriptor:
if d.IsExtension() {
if pm, ok := d.GetParent().(*desc.MessageDescriptor); ok {
return append(path, internal.Message_extensionsTag, getFieldIndex(d, pm.GetNestedExtensions()))
}
return append(path, internal.File_extensionsTag, getFieldIndex(d, d.GetFile().GetExtensions()))
}
return append(path, internal.Message_fieldsTag, getFieldIndex(d, d.GetOwner().GetFields()))
case *desc.OneOfDescriptor:
return append(path, internal.Message_oneOfsTag, getOneOfIndex(d, d.GetOwner().GetOneOfs()))
case *desc.EnumDescriptor:
if pm, ok := d.GetParent().(*desc.MessageDescriptor); ok {
return append(path, internal.Message_enumsTag, getEnumIndex(d, pm.GetNestedEnumTypes()))
}
return append(path, internal.File_enumsTag, getEnumIndex(d, d.GetFile().GetEnumTypes()))
case *desc.EnumValueDescriptor:
return append(path, internal.Enum_valuesTag, getEnumValueIndex(d, d.GetEnum().GetValues()))
case *desc.ServiceDescriptor:
return append(path, internal.File_servicesTag, getServiceIndex(d, d.GetFile().GetServices()))
case *desc.MethodDescriptor:
return append(path, internal.Service_methodsTag, getMethodIndex(d, d.GetService().GetMethods()))
default:
panic(fmt.Sprintf("unexpected descriptor type: %T", dsc))
}
}
func getMessageIndex(md *desc.MessageDescriptor, list []*desc.MessageDescriptor) int32 {
for i := range list {
if md == list[i] {
return int32(i)
}
}
panic(fmt.Sprintf("unable to determine index of message %s", md.GetFullyQualifiedName()))
}
func getFieldIndex(fd *desc.FieldDescriptor, list []*desc.FieldDescriptor) int32 {
for i := range list {
if fd == list[i] {
return int32(i)
}
}
panic(fmt.Sprintf("unable to determine index of field %s", fd.GetFullyQualifiedName()))
}
func getOneOfIndex(ood *desc.OneOfDescriptor, list []*desc.OneOfDescriptor) int32 {
for i := range list {
if ood == list[i] {
return int32(i)
}
}
panic(fmt.Sprintf("unable to determine index of oneof %s", ood.GetFullyQualifiedName()))
}
func getEnumIndex(ed *desc.EnumDescriptor, list []*desc.EnumDescriptor) int32 {
for i := range list {
if ed == list[i] {
return int32(i)
}
}
panic(fmt.Sprintf("unable to determine index of enum %s", ed.GetFullyQualifiedName()))
}
func getEnumValueIndex(evd *desc.EnumValueDescriptor, list []*desc.EnumValueDescriptor) int32 {
for i := range list {
if evd == list[i] {
return int32(i)
}
}
panic(fmt.Sprintf("unable to determine index of enum value %s", evd.GetFullyQualifiedName()))
}
func getServiceIndex(sd *desc.ServiceDescriptor, list []*desc.ServiceDescriptor) int32 {
for i := range list {
if sd == list[i] {
return int32(i)
}
}
panic(fmt.Sprintf("unable to determine index of service %s", sd.GetFullyQualifiedName()))
}
func getMethodIndex(mtd *desc.MethodDescriptor, list []*desc.MethodDescriptor) int32 {
for i := range list {
if mtd == list[i] {
return int32(i)
}
}
panic(fmt.Sprintf("unable to determine index of method %s", mtd.GetFullyQualifiedName()))
}
func (p *Printer) newLine(w io.Writer) {
if !p.Compact {
_, _ = fmt.Fprintln(w)
}
}
func reparseUnknown(reg *protoregistry.Types, msg protoreflect.Message) {
msg.Range(func(fld protoreflect.FieldDescriptor, val protoreflect.Value) bool {
if fld.Kind() != protoreflect.MessageKind && fld.Kind() != protoreflect.GroupKind {
return true
}
if fld.IsList() {
l := val.List()
for i := 0; i < l.Len(); i++ {
reparseUnknown(reg, l.Get(i).Message())
}
} else if fld.IsMap() {
mapVal := fld.MapValue()
if mapVal.Kind() != protoreflect.MessageKind && mapVal.Kind() != protoreflect.GroupKind {
return true
}
m := val.Map()
m.Range(func(k protoreflect.MapKey, v protoreflect.Value) bool {
reparseUnknown(reg, v.Message())
return true
})
} else {
reparseUnknown(reg, val.Message())
}
return true
})
unk := msg.GetUnknown()
if len(unk) > 0 {
other := msg.New().Interface()
if err := (proto.UnmarshalOptions{Resolver: reg}).Unmarshal(unk, other); err == nil {
msg.SetUnknown(nil)
proto.Merge(msg.Interface(), other)
}
}
}
func (p *Printer) printFile(fd *desc.FileDescriptor, reg *protoregistry.Types, w *writer, sourceInfo internal.SourceInfoMap) {
opts, err := p.extractOptions(fd, protov1.MessageV2(fd.GetOptions()))
if err != nil {
return
}
fdp := fd.AsFileDescriptorProto()
path := make([]int32, 1)
path[0] = internal.File_packageTag
sourceInfo.PutIfAbsent(append(path, 0), sourceInfo.Get(path))
path[0] = internal.File_syntaxTag
si := sourceInfo.Get(path)
p.printElement(false, si, w, 0, func(w *writer) {
syn := fdp.GetSyntax()
if syn == "editions" {
_, _ = fmt.Fprintf(w, "edition = %q;", strings.TrimPrefix(fdp.GetEdition().String(), "EDITION_"))
return
}
if syn == "" {
syn = "proto2"
}
_, _ = fmt.Fprintf(w, "syntax = %q;", syn)
})
p.newLine(w)
skip := map[interface{}]bool{}
elements := elementAddrs{dsc: fd, opts: opts}
if fdp.Package != nil {
elements.addrs = append(elements.addrs, elementAddr{elementType: internal.File_packageTag, elementIndex: 0, order: -3})
}
for i := range fdp.GetDependency() {
elements.addrs = append(elements.addrs, elementAddr{elementType: internal.File_dependencyTag, elementIndex: i, order: -2})
}
elements.addrs = append(elements.addrs, optionsAsElementAddrs(internal.File_optionsTag, -1, opts)...)
for i := range fd.GetMessageTypes() {
elements.addrs = append(elements.addrs, elementAddr{elementType: internal.File_messagesTag, elementIndex: i})
}
for i := range fd.GetEnumTypes() {
elements.addrs = append(elements.addrs, elementAddr{elementType: internal.File_enumsTag, elementIndex: i})
}
for i := range fd.GetServices() {
elements.addrs = append(elements.addrs, elementAddr{elementType: internal.File_servicesTag, elementIndex: i})
}
exts := p.computeExtensions(sourceInfo, fd.GetExtensions(), []int32{internal.File_extensionsTag})
for i, extd := range fd.GetExtensions() {
if extd.GetType() == descriptorpb.FieldDescriptorProto_TYPE_GROUP {
// we don't emit nested messages for groups since
// they get special treatment
skip[extd.GetMessageType()] = true
}
elements.addrs = append(elements.addrs, elementAddr{elementType: internal.File_extensionsTag, elementIndex: i})
}
p.sort(elements, sourceInfo, nil)
pkgName := fd.GetPackage()
for i, el := range elements.addrs {
d := elements.at(el)
// skip[d] will panic if d is a slice (which it could be for []option),
// so just ignore it since we don't try to skip options
if reflect.TypeOf(d).Kind() != reflect.Slice && skip[d] {
// skip this element
continue
}
if i > 0 {
p.newLine(w)
}
path = []int32{el.elementType, int32(el.elementIndex)}
switch d := d.(type) {
case pkg:
si := sourceInfo.Get(path)
p.printElement(false, si, w, 0, func(w *writer) {
_, _ = fmt.Fprintf(w, "package %s;", d)
})
case imp:
si := sourceInfo.Get(path)
var modifier string
for _, idx := range fdp.PublicDependency {
if fdp.Dependency[idx] == string(d) {
modifier = "public "
break
}
}
if modifier == "" {
for _, idx := range fdp.WeakDependency {
if fdp.Dependency[idx] == string(d) {
modifier = "weak "
break
}
}
}
p.printElement(false, si, w, 0, func(w *writer) {
_, _ = fmt.Fprintf(w, "import %s%q;", modifier, d)
})
case []option:
p.printOptionsLong(d, reg, w, sourceInfo, path, 0)
case *desc.MessageDescriptor:
p.printMessage(d, reg, w, sourceInfo, path, 0)
case *desc.EnumDescriptor:
p.printEnum(d, reg, w, sourceInfo, path, 0)
case *desc.ServiceDescriptor:
p.printService(d, reg, w, sourceInfo, path, 0)
case *desc.FieldDescriptor:
extDecl := exts[d]
p.printExtensions(extDecl, exts, elements, i, reg, w, sourceInfo, nil, internal.File_extensionsTag, pkgName, pkgName, 0)
// we printed all extensions in the group, so we can skip the others
for _, fld := range extDecl.fields {
skip[fld] = true
}
}
}
}
func findExtSi(fieldSi *descriptorpb.SourceCodeInfo_Location, extSis []*descriptorpb.SourceCodeInfo_Location) *descriptorpb.SourceCodeInfo_Location {
if len(fieldSi.GetSpan()) == 0 {
return nil
}
for _, extSi := range extSis {
if isSpanWithin(fieldSi.Span, extSi.Span) {
return extSi
}
}
return nil
}
func isSpanWithin(span, enclosing []int32) bool {
start := enclosing[0]
var end int32
if len(enclosing) == 3 {
end = enclosing[0]
} else {
end = enclosing[2]
}
if span[0] < start || span[0] > end {
return false
}
if span[0] == start {
return span[1] >= enclosing[1]
} else if span[0] == end {
return span[1] <= enclosing[len(enclosing)-1]
}
return true
}
type extensionDecl struct {
extendee string
sourceInfo *descriptorpb.SourceCodeInfo_Location
fields []*desc.FieldDescriptor
}
type extensions map[*desc.FieldDescriptor]*extensionDecl
func (p *Printer) computeExtensions(sourceInfo internal.SourceInfoMap, exts []*desc.FieldDescriptor, path []int32) extensions {
extsMap := map[string]map[*descriptorpb.SourceCodeInfo_Location]*extensionDecl{}
extSis := sourceInfo.GetAll(path)
for _, extd := range exts {
name := extd.GetOwner().GetFullyQualifiedName()
extSi := findExtSi(extd.GetSourceInfo(), extSis)
extsBySi := extsMap[name]
if extsBySi == nil {
extsBySi = map[*descriptorpb.SourceCodeInfo_Location]*extensionDecl{}
extsMap[name] = extsBySi
}
extDecl := extsBySi[extSi]
if extDecl == nil {
extDecl = &extensionDecl{
sourceInfo: extSi,
extendee: name,
}
extsBySi[extSi] = extDecl
}
extDecl.fields = append(extDecl.fields, extd)
}
ret := extensions{}
for _, extsBySi := range extsMap {
for _, extDecl := range extsBySi {
for _, extd := range extDecl.fields {
ret[extd] = extDecl
}
}
}
return ret
}
func (p *Printer) sort(elements elementAddrs, sourceInfo internal.SourceInfoMap, path []int32) {
if p.CustomSortFunction != nil {
sort.Stable(customSortOrder{elementAddrs: elements, less: p.CustomSortFunction})
} else if p.SortElements {
// canonical sorted order
sort.Stable(elements)
} else {
// use source order (per location information in SourceCodeInfo); or
// if that isn't present use declaration order, but grouped by type
sort.Stable(elementSrcOrder{
elementAddrs: elements,
sourceInfo: sourceInfo,
prefix: path,
})
}
}
func (p *Printer) qualifyMessageOptionName(pkg, scope string, fqn string) string {
// Message options must at least include the message scope, even if the option
// is inside that message. We do that by requiring we have at least one
// enclosing skip in the qualified name.
return p.qualifyElementName(pkg, scope, fqn, 1)
}
func (p *Printer) qualifyExtensionLiteralName(pkg, scope string, fqn string) string {
// In message literals, extensions can have package name omitted but may not
// have any other scopes omitted. We signal that via negative arg.
return p.qualifyElementName(pkg, scope, fqn, -1)
}
func (p *Printer) qualifyName(pkg, scope string, fqn string) string {
return p.qualifyElementName(pkg, scope, fqn, 0)
}
func (p *Printer) qualifyElementName(pkg, scope string, fqn string, required int) string {
if p.ForceFullyQualifiedNames {
// forcing fully-qualified names; make sure to include preceding dot
if fqn[0] == '.' {
return fqn
}
return fmt.Sprintf(".%s", fqn)
}
// compute relative name (so no leading dot)
if fqn[0] == '.' {
fqn = fqn[1:]
}
if required < 0 {
scope = pkg + "."
} else if len(scope) > 0 && scope[len(scope)-1] != '.' {
scope = scope + "."
}
count := 0
for scope != "" {
if strings.HasPrefix(fqn, scope) && count >= required {
return fqn[len(scope):]
}
if scope == pkg+"." {
break
}
pos := strings.LastIndex(scope[:len(scope)-1], ".")
scope = scope[:pos+1]
count++
}
return fqn
}
func (p *Printer) typeString(fld *desc.FieldDescriptor, scope string) string {
if fld.IsMap() {
return fmt.Sprintf("map<%s, %s>", p.typeString(fld.GetMapKeyType(), scope), p.typeString(fld.GetMapValueType(), scope))
}
fldProto := fld.AsFieldDescriptorProto()
if fldProto.Type == nil && fldProto.TypeName != nil {
// In an unlinked proto, the type may be absent because it is not known
// whether the symbol is a message or an enum. In that case, just return
// the type name.
return fldProto.GetTypeName()
}
switch fld.GetType() {
case descriptorpb.FieldDescriptorProto_TYPE_INT32:
return "int32"
case descriptorpb.FieldDescriptorProto_TYPE_INT64:
return "int64"
case descriptorpb.FieldDescriptorProto_TYPE_UINT32:
return "uint32"
case descriptorpb.FieldDescriptorProto_TYPE_UINT64:
return "uint64"
case descriptorpb.FieldDescriptorProto_TYPE_SINT32:
return "sint32"
case descriptorpb.FieldDescriptorProto_TYPE_SINT64:
return "sint64"
case descriptorpb.FieldDescriptorProto_TYPE_FIXED32:
return "fixed32"
case descriptorpb.FieldDescriptorProto_TYPE_FIXED64:
return "fixed64"
case descriptorpb.FieldDescriptorProto_TYPE_SFIXED32:
return "sfixed32"
case descriptorpb.FieldDescriptorProto_TYPE_SFIXED64:
return "sfixed64"
case descriptorpb.FieldDescriptorProto_TYPE_FLOAT:
return "float"
case descriptorpb.FieldDescriptorProto_TYPE_DOUBLE:
return "double"
case descriptorpb.FieldDescriptorProto_TYPE_BOOL:
return "bool"
case descriptorpb.FieldDescriptorProto_TYPE_STRING:
return "string"
case descriptorpb.FieldDescriptorProto_TYPE_BYTES:
return "bytes"
case descriptorpb.FieldDescriptorProto_TYPE_ENUM:
return p.qualifyName(fld.GetFile().GetPackage(), scope, fld.GetEnumType().GetFullyQualifiedName())
case descriptorpb.FieldDescriptorProto_TYPE_MESSAGE:
return p.qualifyName(fld.GetFile().GetPackage(), scope, fld.GetMessageType().GetFullyQualifiedName())
case descriptorpb.FieldDescriptorProto_TYPE_GROUP:
return fld.GetMessageType().GetName()
}
panic(fmt.Sprintf("invalid type: %v", fld.GetType()))
}
func (p *Printer) printMessage(md *desc.MessageDescriptor, reg *protoregistry.Types, w *writer, sourceInfo internal.SourceInfoMap, path []int32, indent int) {
si := sourceInfo.Get(path)
p.printBlockElement(true, si, w, indent, func(w *writer, trailer func(int, bool)) {
p.indent(w, indent)
_, _ = fmt.Fprint(w, "message ")
nameSi := sourceInfo.Get(append(path, internal.Message_nameTag))
p.printElementString(nameSi, w, indent, md.GetName())
_, _ = fmt.Fprintln(w, "{")
trailer(indent+1, true)
p.printMessageBody(md, reg, w, sourceInfo, path, indent+1)
p.indent(w, indent)
_, _ = fmt.Fprintln(w, "}")
})
}
func (p *Printer) printMessageBody(md *desc.MessageDescriptor, reg *protoregistry.Types, w *writer, sourceInfo internal.SourceInfoMap, path []int32, indent int) {
opts, err := p.extractOptions(md, protov1.MessageV2(md.GetOptions()))
if err != nil {
if w.err == nil {
w.err = err
}
return
}
skip := map[interface{}]bool{}
maxTag := internal.GetMaxTag(md.GetMessageOptions().GetMessageSetWireFormat())
elements := elementAddrs{dsc: md, opts: opts}
elements.addrs = append(elements.addrs, optionsAsElementAddrs(internal.Message_optionsTag, -1, opts)...)
for i := range md.AsDescriptorProto().GetReservedRange() {
elements.addrs = append(elements.addrs, elementAddr{elementType: internal.Message_reservedRangeTag, elementIndex: i})
}
for i := range md.AsDescriptorProto().GetReservedName() {
elements.addrs = append(elements.addrs, elementAddr{elementType: internal.Message_reservedNameTag, elementIndex: i})
}
for i := range md.AsDescriptorProto().GetExtensionRange() {
elements.addrs = append(elements.addrs, elementAddr{elementType: internal.Message_extensionRangeTag, elementIndex: i})
}
for i, fld := range md.GetFields() {
if fld.IsMap() || fld.GetType() == descriptorpb.FieldDescriptorProto_TYPE_GROUP {
// we don't emit nested messages for map types or groups since
// they get special treatment
skip[fld.GetMessageType()] = true
}
elements.addrs = append(elements.addrs, elementAddr{elementType: internal.Message_fieldsTag, elementIndex: i})
}
for i := range md.GetNestedMessageTypes() {
elements.addrs = append(elements.addrs, elementAddr{elementType: internal.Message_nestedMessagesTag, elementIndex: i})
}
for i := range md.GetNestedEnumTypes() {
elements.addrs = append(elements.addrs, elementAddr{elementType: internal.Message_enumsTag, elementIndex: i})
}
exts := p.computeExtensions(sourceInfo, md.GetNestedExtensions(), append(path, internal.Message_extensionsTag))
for i, extd := range md.GetNestedExtensions() {
if extd.GetType() == descriptorpb.FieldDescriptorProto_TYPE_GROUP {
// we don't emit nested messages for groups since
// they get special treatment
skip[extd.GetMessageType()] = true
}
elements.addrs = append(elements.addrs, elementAddr{elementType: internal.Message_extensionsTag, elementIndex: i})
}
p.sort(elements, sourceInfo, path)
pkg := md.GetFile().GetPackage()
scope := md.GetFullyQualifiedName()
for i, el := range elements.addrs {
d := elements.at(el)
// skip[d] will panic if d is a slice (which it could be for []option),
// so just ignore it since we don't try to skip options
if reflect.TypeOf(d).Kind() != reflect.Slice && skip[d] {
// skip this element
continue
}
if i > 0 {
p.newLine(w)
}
childPath := append(path, el.elementType, int32(el.elementIndex))
switch d := d.(type) {
case []option:
p.printOptionsLong(d, reg, w, sourceInfo, childPath, indent)
case *desc.FieldDescriptor:
if d.IsExtension() {
extDecl := exts[d]
p.printExtensions(extDecl, exts, elements, i, reg, w, sourceInfo, path, internal.Message_extensionsTag, pkg, scope, indent)
// we printed all extensions in the group, so we can skip the others
for _, fld := range extDecl.fields {
skip[fld] = true
}
} else {
ood := d.GetOneOf()
if ood == nil || ood.IsSynthetic() {
p.printField(d, reg, w, sourceInfo, childPath, scope, indent)
} else {
// print the one-of, including all of its fields
p.printOneOf(ood, elements, i, reg, w, sourceInfo, path, indent, d.AsFieldDescriptorProto().GetOneofIndex())
for _, fld := range ood.GetChoices() {
skip[fld] = true
}
}
}
case *desc.MessageDescriptor:
p.printMessage(d, reg, w, sourceInfo, childPath, indent)
case *desc.EnumDescriptor:
p.printEnum(d, reg, w, sourceInfo, childPath, indent)
case *descriptorpb.DescriptorProto_ExtensionRange:
// collapse ranges into a single "extensions" block
ranges := []*descriptorpb.DescriptorProto_ExtensionRange{d}
addrs := []elementAddr{el}
for idx := i + 1; idx < len(elements.addrs); idx++ {
elnext := elements.addrs[idx]
if elnext.elementType != el.elementType {
break
}
extr := elements.at(elnext).(*descriptorpb.DescriptorProto_ExtensionRange)
if !proto.Equal(d.Options, extr.Options) {
break
}
ranges = append(ranges, extr)
addrs = append(addrs, elnext)
skip[extr] = true
}
p.printExtensionRanges(md, ranges, maxTag, addrs, reg, w, sourceInfo, path, indent)
case reservedRange:
// collapse reserved ranges into a single "reserved" block
ranges := []reservedRange{d}
addrs := []elementAddr{el}
for idx := i + 1; idx < len(elements.addrs); idx++ {
elnext := elements.addrs[idx]
if elnext.elementType != el.elementType {
break
}
rr := elements.at(elnext).(reservedRange)
ranges = append(ranges, rr)
addrs = append(addrs, elnext)
skip[rr] = true
}
p.printReservedRanges(ranges, maxTag, addrs, w, sourceInfo, path, indent)
case string: // reserved name
// collapse reserved names into a single "reserved" block
names := []string{d}
addrs := []elementAddr{el}
for idx := i + 1; idx < len(elements.addrs); idx++ {
elnext := elements.addrs[idx]
if elnext.elementType != el.elementType {
break
}
rn := elements.at(elnext).(string)
names = append(names, rn)
addrs = append(addrs, elnext)
skip[rn] = true
}
p.printReservedNames(names, addrs, w, sourceInfo, path, indent, useQuotedReserved(md.GetFile()))
}
}
}
func (p *Printer) printField(fld *desc.FieldDescriptor, reg *protoregistry.Types, w *writer, sourceInfo internal.SourceInfoMap, path []int32, scope string, indent int) {
var groupPath []int32
var si *descriptorpb.SourceCodeInfo_Location
group := isGroup(fld)