forked from bufbuild/protocompile
/
result.go
1254 lines (1148 loc) · 41.4 KB
/
result.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
// Copyright 2020-2023 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package parser
import (
"bytes"
"errors"
"fmt"
"math"
"sort"
"strings"
"unicode"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/reflect/protoreflect"
"google.golang.org/protobuf/types/descriptorpb"
"github.com/kralicky/protocompile/ast"
"github.com/kralicky/protocompile/editions"
"github.com/kralicky/protocompile/protointernal"
"github.com/kralicky/protocompile/reporter"
)
type result struct {
file *ast.FileNode
proto *descriptorpb.FileDescriptorProto
nodes map[proto.Message]ast.Node
nodesInverse map[ast.Node]proto.Message
fieldExtendeeNodes map[ast.Node]*ast.ExtendNode
// A position in the source file corresponding to the end of the last import
// statement (the point just after the semicolon). This can be used as an
// insertion point for new import statements.
importInsertionPoint ast.SourcePos
}
// ResultWithoutAST returns a parse result that has no AST. All methods for
// looking up AST nodes return a placeholder node that contains only the filename
// in position information.
func ResultWithoutAST(proto *descriptorpb.FileDescriptorProto) Result {
return &result{proto: proto}
}
// ResultFromAST constructs a descriptor proto from the given AST. The returned
// result includes the descriptor proto and also contains an index that can be
// used to lookup AST node information for elements in the descriptor proto
// hierarchy.
//
// If validate is true, some basic validation is performed, to make sure the
// resulting descriptor proto is valid per protobuf rules and semantics. Only
// some language elements can be validated since some rules and semantics can
// only be checked after all symbols are all resolved, which happens in the
// linking step.
//
// The given handler is used to report any errors or warnings encountered. If any
// errors are reported, this function returns a non-nil error.
func ResultFromAST(file *ast.FileNode, validate bool, handler *reporter.Handler) (Result, error) {
filename := file.Name()
r := &result{
file: file,
nodes: map[proto.Message]ast.Node{},
nodesInverse: map[ast.Node]proto.Message{},
fieldExtendeeNodes: map[ast.Node]*ast.ExtendNode{},
}
r.createFileDescriptor(filename, file, handler)
if validate {
validateBasic(r, handler)
}
// Now that we're done validating, we can set any missing labels to optional
// (we leave them absent in first pass if label was missing in source, so we
// can do validation on presence of label, but final descriptors are expected
// to always have them present).
fillInMissingLabels(r.proto)
var lastSeenImport *ast.ImportNode
DECLS:
for _, decl := range file.Decls {
switch decl := decl.Unwrap().(type) {
case *ast.PackageNode:
if lastSeenImport == nil {
// as a backup in case there are no imports
r.importInsertionPoint = file.NodeInfo(decl).End()
}
case *ast.ImportNode:
if decl.IsIncomplete() {
continue
}
lastSeenImport = decl
default:
if lastSeenImport != nil {
r.importInsertionPoint = file.NodeInfo(lastSeenImport).End()
break DECLS
}
}
}
return r, handler.Error()
}
func (r *result) ImportInsertionPoint() ast.SourcePos {
if r.file == nil {
return ast.SourcePos{}
}
if r.importInsertionPoint == (ast.SourcePos{}) {
return r.file.NodeInfo(r.file.Syntax).End()
}
return r.importInsertionPoint
}
func (r *result) AST() *ast.FileNode {
return r.file
}
func (r *result) FileDescriptorProto() *descriptorpb.FileDescriptorProto {
return r.proto
}
func (r *result) createFileDescriptor(filename string, file *ast.FileNode, handler *reporter.Handler) {
fd := &descriptorpb.FileDescriptorProto{Name: proto.String(filename)}
r.proto = fd
r.putFileNode(fd, file)
var syntax protoreflect.Syntax
switch {
case file.Syntax != nil:
switch file.Syntax.Syntax.AsString() {
case "proto3":
syntax = protoreflect.Proto3
case "proto2":
syntax = protoreflect.Proto2
default:
nodeInfo := file.NodeInfo(file.Syntax.Syntax)
if handler.HandleErrorf(nodeInfo, `syntax value must be "proto2" or "proto3"`) != nil {
return
}
}
// proto2 is the default, so no need to set for that value
if syntax != protoreflect.Proto2 {
fd.Syntax = proto.String(file.Syntax.Syntax.AsString())
}
case file.Edition != nil:
if !editions.AllowEditions {
nodeInfo := file.NodeInfo(file.Edition.Edition)
if handler.HandleErrorf(nodeInfo, `editions are not yet supported; use syntax proto2 or proto3 instead`) != nil {
return
}
}
edition := file.Edition.Edition.AsString()
syntax = protoreflect.Editions
fd.Syntax = proto.String("editions")
editionEnum, ok := editions.SupportedEditions[edition]
if !ok {
nodeInfo := file.NodeInfo(file.Edition.Edition)
editionStrs := make([]string, 0, len(editions.SupportedEditions))
for supportedEdition := range editions.SupportedEditions {
editionStrs = append(editionStrs, fmt.Sprintf("%q", supportedEdition))
}
sort.Strings(editionStrs)
if handler.HandleErrorf(nodeInfo, `edition value %q not recognized; should be one of [%s]`, edition, strings.Join(editionStrs, ",")) != nil {
return
}
}
fd.Edition = editionEnum.Enum()
default:
syntax = protoreflect.Proto2
nodeInfo := file.NodeInfo(file)
handler.HandleWarningWithPos(nodeInfo, ErrNoSyntax)
}
for _, decl := range file.Decls {
if handler.ReporterError() != nil {
return
}
switch decl := decl.Unwrap().(type) {
case *ast.EnumNode:
fd.EnumType = append(fd.EnumType, r.asEnumDescriptor(decl, syntax, handler))
case *ast.ExtendNode:
if decl.IsIncomplete() {
continue
}
r.addExtensions(decl, &fd.Extension, &fd.MessageType, syntax, handler, 0)
case *ast.ImportNode:
if decl.IsIncomplete() {
continue
}
index := len(fd.Dependency)
fd.Dependency = append(fd.Dependency, decl.Name.AsString())
if decl.Public != nil {
fd.PublicDependency = append(fd.PublicDependency, int32(index))
} else if decl.Weak != nil {
fd.WeakDependency = append(fd.WeakDependency, int32(index))
}
case *ast.MessageNode:
fd.MessageType = append(fd.MessageType, r.asMessageDescriptor(decl, syntax, handler, 1))
case *ast.OptionNode:
if decl.IsIncomplete() {
if decl.Name == nil || !ast.ExtendedSyntaxEnabled {
continue
}
}
if fd.Options == nil {
fd.Options = &descriptorpb.FileOptions{}
}
fd.Options.UninterpretedOption = append(fd.Options.UninterpretedOption, r.asUninterpretedOption(decl))
case *ast.ServiceNode:
fd.Service = append(fd.Service, r.asServiceDescriptor(decl))
case *ast.PackageNode:
if decl.IsIncomplete() {
continue
}
if fd.Package != nil {
nodeInfo := file.NodeInfo(decl)
if handler.HandleErrorf(nodeInfo, "files should have only one package declaration") != nil {
return
}
}
pkgName := string(decl.Name.AsIdentifier())
if len(pkgName) >= 512 {
nodeInfo := file.NodeInfo(decl.Name)
if handler.HandleErrorf(nodeInfo, "package name (with whitespace removed) must be less than 512 characters long") != nil {
return
}
}
if strings.Count(pkgName, ".") > 100 {
nodeInfo := file.NodeInfo(decl.Name)
if handler.HandleErrorf(nodeInfo, "package name may not contain more than 100 periods") != nil {
return
}
}
fd.Package = proto.String(string(decl.Name.AsIdentifier()))
}
}
}
func (r *result) asUninterpretedOptions(nodes []*ast.OptionNode) []*descriptorpb.UninterpretedOption {
if len(nodes) == 0 {
return nil
}
opts := make([]*descriptorpb.UninterpretedOption, 0, len(nodes))
for _, n := range nodes {
if n.IsIncomplete() {
if n.Name == nil || !ast.ExtendedSyntaxEnabled {
continue
}
}
opts = append(opts, r.asUninterpretedOption(n))
}
return opts
}
func (r *result) asUninterpretedOption(node *ast.OptionNode) *descriptorpb.UninterpretedOption {
opt := &descriptorpb.UninterpretedOption{Name: r.asUninterpretedOptionName(node.Name.FilterFieldReferences())}
r.putOptionNode(opt, node)
if node.Val == nil && ast.ExtendedSyntaxEnabled {
return opt
}
switch val := node.Val.Value().(type) {
case bool:
if val {
opt.IdentifierValue = proto.String("true")
} else {
opt.IdentifierValue = proto.String("false")
}
case int64:
opt.NegativeIntValue = proto.Int64(val)
case uint64:
opt.PositiveIntValue = proto.Uint64(val)
case float64:
opt.DoubleValue = proto.Float64(val)
case string:
opt.StringValue = []byte(val)
case ast.Identifier:
opt.IdentifierValue = proto.String(string(val))
default:
// the grammar does not allow arrays here, so the only possible case
// left should be []*ast.MessageFieldNode, which corresponds to an
// *ast.MessageLiteralNode
if n := node.Val.GetMessageLiteral(); n != nil {
var buf bytes.Buffer
for _, el := range n.Elements {
flattenNode(r.file, el, &buf)
}
aggStr := buf.String()
opt.AggregateValue = proto.String(aggStr)
}
// TODO: else that reports an error or panics??
}
return opt
}
func flattenNode(f *ast.FileNode, n ast.Node, buf *bytes.Buffer) {
ast.Inspect(n, func(node ast.Node) bool {
if ast.IsTerminalNode(node) {
if ast.IsVirtualNode(node) {
return true
}
if buf.Len() > 0 {
buf.WriteRune(' ')
}
str := f.NodeInfo(node).RawText()
buf.WriteString(str)
}
return true
})
}
func (r *result) asUninterpretedOptionName(parts []*ast.FieldReferenceNode) []*descriptorpb.UninterpretedOption_NamePart {
ret := make([]*descriptorpb.UninterpretedOption_NamePart, 0, len(parts))
for _, part := range parts {
if part.IsIncomplete() {
continue
}
np := &descriptorpb.UninterpretedOption_NamePart{
NamePart: proto.String(string(part.Name.AsIdentifier())),
IsExtension: proto.Bool(part.IsExtension()),
}
r.putOptionNamePartNode(np, part)
ret = append(ret, np)
}
return ret
}
func (r *result) addExtensions(ext *ast.ExtendNode, flds *[]*descriptorpb.FieldDescriptorProto, msgs *[]*descriptorpb.DescriptorProto, syntax protoreflect.Syntax, handler *reporter.Handler, depth int) {
extendee := string(ext.Extendee.AsIdentifier())
count := 0
for _, decl := range ext.Decls {
switch decl := decl.Unwrap().(type) {
case *ast.FieldNode:
if decl.IsIncomplete() {
continue
}
count++
// use higher limit since we don't know yet whether extendee is messageset wire format
fd := r.asFieldDescriptor(decl, protointernal.MaxTag, syntax, handler)
fd.Extendee = proto.String(extendee)
*flds = append(*flds, fd)
r.putFieldNode(fd, decl)
r.fieldExtendeeNodes[decl] = ext
case *ast.GroupNode:
count++
// ditto: use higher limit right now
fd, md := r.asGroupDescriptors(decl, syntax, protointernal.MaxTag, handler, depth+1)
fd.Extendee = proto.String(extendee)
r.fieldExtendeeNodes[decl] = ext
*flds = append(*flds, fd)
*msgs = append(*msgs, md)
}
}
if count == 0 {
nodeInfo := r.file.NodeInfo(ext.CloseBrace)
if ast.ExtendedSyntaxEnabled {
handler.HandleWarningWithPos(nodeInfo,
NewExtendedSyntaxError(errors.New("extend sections must define at least one extension"), CategoryEmptyDecl))
} else {
_ = handler.HandleErrorf(nodeInfo, "extend sections must define at least one extension")
}
}
}
func asLabel(lbl *ast.IdentNode) *descriptorpb.FieldDescriptorProto_Label {
if lbl == nil {
return nil
}
switch lbl.Val {
case "repeated":
return descriptorpb.FieldDescriptorProto_LABEL_REPEATED.Enum()
case "required":
return descriptorpb.FieldDescriptorProto_LABEL_REQUIRED.Enum()
case "optional":
return descriptorpb.FieldDescriptorProto_LABEL_OPTIONAL.Enum()
default:
return nil
}
}
func (r *result) asFieldDescriptor(node *ast.FieldNode, maxTag int32, syntax protoreflect.Syntax, handler *reporter.Handler) *descriptorpb.FieldDescriptorProto {
tag := node.Tag.Val
if err := r.checkTag(node.Tag, tag, maxTag); err != nil {
_ = handler.HandleError(err)
}
fd := newFieldDescriptor(node.Name.Val, string(node.GetFieldType().AsIdentifier()), int32(tag), asLabel(node.Label))
r.putFieldNode(fd, node)
if opts := node.Options.GetElements(); len(opts) > 0 {
fd.Options = &descriptorpb.FieldOptions{UninterpretedOption: r.asUninterpretedOptions(opts)}
}
if syntax == protoreflect.Proto3 && fd.Label != nil && fd.GetLabel() == descriptorpb.FieldDescriptorProto_LABEL_OPTIONAL {
fd.Proto3Optional = proto.Bool(true)
}
return fd
}
var fieldTypes = map[string]descriptorpb.FieldDescriptorProto_Type{
"double": descriptorpb.FieldDescriptorProto_TYPE_DOUBLE,
"float": descriptorpb.FieldDescriptorProto_TYPE_FLOAT,
"int32": descriptorpb.FieldDescriptorProto_TYPE_INT32,
"int64": descriptorpb.FieldDescriptorProto_TYPE_INT64,
"uint32": descriptorpb.FieldDescriptorProto_TYPE_UINT32,
"uint64": descriptorpb.FieldDescriptorProto_TYPE_UINT64,
"sint32": descriptorpb.FieldDescriptorProto_TYPE_SINT32,
"sint64": descriptorpb.FieldDescriptorProto_TYPE_SINT64,
"fixed32": descriptorpb.FieldDescriptorProto_TYPE_FIXED32,
"fixed64": descriptorpb.FieldDescriptorProto_TYPE_FIXED64,
"sfixed32": descriptorpb.FieldDescriptorProto_TYPE_SFIXED32,
"sfixed64": descriptorpb.FieldDescriptorProto_TYPE_SFIXED64,
"bool": descriptorpb.FieldDescriptorProto_TYPE_BOOL,
"string": descriptorpb.FieldDescriptorProto_TYPE_STRING,
"bytes": descriptorpb.FieldDescriptorProto_TYPE_BYTES,
}
func newFieldDescriptor(name string, fieldType string, tag int32, lbl *descriptorpb.FieldDescriptorProto_Label) *descriptorpb.FieldDescriptorProto {
fd := &descriptorpb.FieldDescriptorProto{
Name: proto.String(name),
JsonName: proto.String(protointernal.JSONName(name)),
Number: proto.Int32(tag),
Label: lbl,
}
t, ok := fieldTypes[fieldType]
if ok {
fd.Type = t.Enum()
} else {
// NB: we don't have enough info to determine whether this is an enum
// or a message type, so we'll leave Type nil and set it later
// (during linking)
fd.TypeName = proto.String(fieldType)
}
return fd
}
func (r *result) asGroupDescriptors(group *ast.GroupNode, syntax protoreflect.Syntax, maxTag int32, handler *reporter.Handler, depth int) (*descriptorpb.FieldDescriptorProto, *descriptorpb.DescriptorProto) {
tag := group.Tag.Val
if err := r.checkTag(group.Tag, tag, maxTag); err != nil {
_ = handler.HandleError(err)
}
if !unicode.IsUpper(rune(group.Name.Val[0])) {
nameNodeInfo := r.file.NodeInfo(group.Name)
_ = handler.HandleErrorf(nameNodeInfo, "group %s should have a name that starts with a capital letter", group.Name.Val)
}
fieldName := strings.ToLower(group.Name.Val)
fd := &descriptorpb.FieldDescriptorProto{
Name: proto.String(fieldName),
JsonName: proto.String(protointernal.JSONName(fieldName)),
Number: proto.Int32(int32(tag)),
Label: asLabel(group.Label),
Type: descriptorpb.FieldDescriptorProto_TYPE_GROUP.Enum(),
TypeName: proto.String(group.Name.Val),
}
if opts := group.Options.GetElements(); len(opts) > 0 {
fd.Options = &descriptorpb.FieldOptions{UninterpretedOption: r.asUninterpretedOptions(opts)}
}
md := &descriptorpb.DescriptorProto{Name: proto.String(group.Name.Val)}
r.putGroupNode(fd, md, group)
// don't bother processing body if we've exceeded depth
if r.checkDepth(depth, group, handler) {
r.addMessageBody(md, group.Decls, syntax, handler, depth)
}
return fd, md
}
func (r *result) asMapDescriptors(mapField *ast.MapFieldNode, syntax protoreflect.Syntax, maxTag int32, handler *reporter.Handler, depth int) (*descriptorpb.FieldDescriptorProto, *descriptorpb.DescriptorProto) {
tag := mapField.Tag.Val
if err := r.checkTag(mapField.Tag, tag, maxTag); err != nil {
_ = handler.HandleError(err)
}
r.checkDepth(depth, mapField, handler)
var lbl *descriptorpb.FieldDescriptorProto_Label
if syntax == protoreflect.Proto2 {
lbl = descriptorpb.FieldDescriptorProto_LABEL_OPTIONAL.Enum()
}
keyFd := newFieldDescriptor("key", mapField.MapType.KeyType.Val, 1, lbl)
r.putSyntheticFieldNode(keyFd, mapField.KeyField())
valFd := newFieldDescriptor("value", string(mapField.MapType.ValueType.AsIdentifier()), 2, lbl)
r.putSyntheticFieldNode(valFd, mapField.ValueField())
entryName := protointernal.InitCap(protointernal.JSONName(mapField.Name.Val)) + "Entry"
fd := newFieldDescriptor(mapField.Name.Val, entryName, int32(tag), descriptorpb.FieldDescriptorProto_LABEL_REPEATED.Enum())
if opts := mapField.Options.GetElements(); len(opts) > 0 {
fd.Options = &descriptorpb.FieldOptions{UninterpretedOption: r.asUninterpretedOptions(opts)}
}
md := &descriptorpb.DescriptorProto{
Name: proto.String(entryName),
Options: &descriptorpb.MessageOptions{MapEntry: proto.Bool(true)},
Field: []*descriptorpb.FieldDescriptorProto{keyFd, valFd},
}
r.putMapFieldNode(fd, md, mapField)
return fd, md
}
func (r *result) asExtensionRanges(node *ast.ExtensionRangeNode, maxTag int32, handler *reporter.Handler) []*descriptorpb.DescriptorProto_ExtensionRange {
opts := r.asUninterpretedOptions(node.Options.GetElements())
ers := make([]*descriptorpb.DescriptorProto_ExtensionRange, len(node.FilterRanges()))
for i, rng := range node.FilterRanges() {
start, end := r.getRangeBounds(rng, 1, maxTag, handler)
er := &descriptorpb.DescriptorProto_ExtensionRange{
Start: proto.Int32(start),
End: proto.Int32(end + 1),
}
if len(opts) > 0 {
er.Options = &descriptorpb.ExtensionRangeOptions{UninterpretedOption: opts}
}
r.putExtensionRangeNode(er, rng)
ers[i] = er
}
return ers
}
func (r *result) asEnumValue(ev *ast.EnumValueNode, handler *reporter.Handler) *descriptorpb.EnumValueDescriptorProto {
num, ok := ast.AsInt32(ev.Number, math.MinInt32, math.MaxInt32)
if !ok {
numberNodeInfo := r.file.NodeInfo(ev.Number)
_ = handler.HandleErrorf(numberNodeInfo, "value %d is out of range: should be between %d and %d", ev.Number.Value(), math.MinInt32, math.MaxInt32)
}
evd := &descriptorpb.EnumValueDescriptorProto{Name: proto.String(ev.Name.Val), Number: proto.Int32(num)}
r.putEnumValueNode(evd, ev)
if opts := ev.Options.GetElements(); len(opts) > 0 {
evd.Options = &descriptorpb.EnumValueOptions{UninterpretedOption: r.asUninterpretedOptions(opts)}
}
return evd
}
func (r *result) asMethodDescriptor(node *ast.RPCNode) *descriptorpb.MethodDescriptorProto {
var inputType, outputType string
if !node.Input.IsIncomplete() {
inputType = string(node.Input.MessageType.AsIdentifier())
}
if !node.Output.IsIncomplete() {
outputType = string(node.Output.MessageType.AsIdentifier())
}
md := &descriptorpb.MethodDescriptorProto{
Name: proto.String(node.Name.Val),
InputType: &inputType,
OutputType: &outputType,
}
r.putMethodNode(md, node)
if node.Input.Stream != nil {
md.ClientStreaming = proto.Bool(true)
}
if node.Output.Stream != nil {
md.ServerStreaming = proto.Bool(true)
}
// protoc always adds a MethodOptions if there are brackets
// We do the same to match protoc as closely as possible
// https://github.com/protocolbuffers/protobuf/blob/0c3f43a6190b77f1f68b7425d1b7e1a8257a8d0c/src/google/protobuf/compiler/parser.cc#L2152
if node.OpenBrace != nil {
md.Options = &descriptorpb.MethodOptions{}
for _, decl := range node.Decls {
if option := decl.GetOption(); option != nil {
if option.IsIncomplete() {
if option.Name == nil || !ast.ExtendedSyntaxEnabled {
continue
}
}
md.Options.UninterpretedOption = append(md.Options.UninterpretedOption, r.asUninterpretedOption(option))
}
}
}
return md
}
func (r *result) asEnumDescriptor(en *ast.EnumNode, syntax protoreflect.Syntax, handler *reporter.Handler) *descriptorpb.EnumDescriptorProto {
ed := &descriptorpb.EnumDescriptorProto{Name: proto.String(en.Name.Val)}
r.putEnumNode(ed, en)
rsvdNames := map[string]ast.SourcePos{}
for _, decl := range en.Decls {
switch decl := decl.Unwrap().(type) {
case *ast.OptionNode:
if decl.IsIncomplete() {
if decl.Name == nil || !ast.ExtendedSyntaxEnabled {
continue
}
}
if ed.Options == nil {
ed.Options = &descriptorpb.EnumOptions{}
}
ed.Options.UninterpretedOption = append(ed.Options.UninterpretedOption, r.asUninterpretedOption(decl))
case *ast.EnumValueNode:
ed.Value = append(ed.Value, r.asEnumValue(decl, handler))
case *ast.ReservedNode:
r.addReservedNames(&ed.ReservedName, decl, syntax, handler, rsvdNames)
for _, rng := range decl.FilterRanges() {
ed.ReservedRange = append(ed.ReservedRange, r.asEnumReservedRange(rng, handler))
}
}
}
return ed
}
func (r *result) asEnumReservedRange(rng *ast.RangeNode, handler *reporter.Handler) *descriptorpb.EnumDescriptorProto_EnumReservedRange {
start, end := r.getRangeBounds(rng, math.MinInt32, math.MaxInt32, handler)
rr := &descriptorpb.EnumDescriptorProto_EnumReservedRange{
Start: proto.Int32(start),
End: proto.Int32(end),
}
r.putEnumReservedRangeNode(rr, rng)
return rr
}
func (r *result) asMessageDescriptor(node *ast.MessageNode, syntax protoreflect.Syntax, handler *reporter.Handler, depth int) *descriptorpb.DescriptorProto {
msgd := &descriptorpb.DescriptorProto{Name: proto.String(node.Name.Val)}
r.putMessageNode(msgd, node)
// don't bother processing body if we've exceeded depth
if r.checkDepth(depth, node, handler) {
r.addMessageBody(msgd, node.Decls, syntax, handler, depth)
}
return msgd
}
func (r *result) addReservedNames(names *[]string, node *ast.ReservedNode, syntax protoreflect.Syntax, handler *reporter.Handler, alreadyReserved map[string]ast.SourcePos) {
if syntax == protoreflect.Editions {
if len(node.FilterNames()) > 0 {
nameNodeInfo := r.file.NodeInfo(node.FilterNames()[0])
_ = handler.HandleErrorf(nameNodeInfo, `must use identifiers, not string literals, to reserved names with editions`)
}
for _, n := range node.FilterIdentifiers() {
name := string(n.AsIdentifier())
nameNodeInfo := r.file.NodeInfo(n)
if existing, ok := alreadyReserved[name]; ok {
_ = handler.HandleErrorf(nameNodeInfo, "name %q is already reserved at %s", name, existing)
continue
}
alreadyReserved[name] = nameNodeInfo.Start()
*names = append(*names, name)
}
return
}
if len(node.FilterIdentifiers()) > 0 {
nameNodeInfo := r.file.NodeInfo(node.FilterIdentifiers()[0])
_ = handler.HandleErrorf(nameNodeInfo, `must use string literals, not identifiers, to reserved names with proto2 and proto3`)
}
for _, n := range node.FilterNames() {
name := n.AsString()
nameNodeInfo := r.file.NodeInfo(n)
if existing, ok := alreadyReserved[name]; ok {
_ = handler.HandleErrorf(nameNodeInfo, "name %q is already reserved at %s", name, existing)
continue
}
alreadyReserved[name] = nameNodeInfo.Start()
*names = append(*names, name)
}
}
func (r *result) checkDepth(depth int, node ast.Node, handler *reporter.Handler) bool {
if depth < 32 {
return true
}
if grp, ok := node.(*ast.GroupNode); ok {
// pinpoint the group keyword if the source is a group
node = grp.Keyword
}
_ = handler.HandleErrorf(r.file.NodeInfo(node), "message nesting depth must be less than 32")
return false
}
func (r *result) addMessageBody(msgd *descriptorpb.DescriptorProto, decls []*ast.MessageElement, syntax protoreflect.Syntax, handler *reporter.Handler, depth int) {
// first process any options
for _, decl := range decls {
if opt := decl.GetOption(); opt != nil {
if opt.IsIncomplete() {
if opt.Name == nil || !ast.ExtendedSyntaxEnabled {
continue
}
}
if msgd.Options == nil {
msgd.Options = &descriptorpb.MessageOptions{}
}
msgd.Options.UninterpretedOption = append(msgd.Options.UninterpretedOption, r.asUninterpretedOption(opt))
}
}
// now that we have options, we can see if this uses messageset wire format, which
// impacts how we validate tag numbers in any fields in the message
maxTag := int32(protointernal.MaxNormalTag)
messageSetOpt, err := r.isMessageSetWireFormat("message "+msgd.GetName(), msgd, handler)
if err != nil {
return
} else if messageSetOpt != nil {
if syntax == protoreflect.Proto3 {
node := r.OptionNode(messageSetOpt)
nodeInfo := r.file.NodeInfo(node)
_ = handler.HandleErrorf(nodeInfo, "messages with message-set wire format are not allowed with proto3 syntax")
}
maxTag = protointernal.MaxTag // higher limit for messageset wire format
}
rsvdNames := map[string]ast.SourcePos{}
// now we can process the rest
for _, decl := range decls {
switch decl := decl.Unwrap().(type) {
case *ast.EnumNode:
msgd.EnumType = append(msgd.EnumType, r.asEnumDescriptor(decl, syntax, handler))
case *ast.ExtendNode:
if decl.IsIncomplete() {
continue
}
r.addExtensions(decl, &msgd.Extension, &msgd.NestedType, syntax, handler, depth)
case *ast.ExtensionRangeNode:
msgd.ExtensionRange = append(msgd.ExtensionRange, r.asExtensionRanges(decl, maxTag, handler)...)
case *ast.FieldNode:
if decl.IsIncomplete() {
continue
}
fd := r.asFieldDescriptor(decl, maxTag, syntax, handler)
msgd.Field = append(msgd.Field, fd)
case *ast.MapFieldNode:
fd, md := r.asMapDescriptors(decl, syntax, maxTag, handler, depth+1)
msgd.Field = append(msgd.Field, fd)
msgd.NestedType = append(msgd.NestedType, md)
case *ast.GroupNode:
fd, md := r.asGroupDescriptors(decl, syntax, maxTag, handler, depth+1)
msgd.Field = append(msgd.Field, fd)
msgd.NestedType = append(msgd.NestedType, md)
case *ast.OneofNode:
oodIndex := len(msgd.OneofDecl)
ood := &descriptorpb.OneofDescriptorProto{Name: proto.String(decl.Name.Val)}
r.putOneofNode(ood, decl)
msgd.OneofDecl = append(msgd.OneofDecl, ood)
ooFields := 0
for _, oodecl := range decl.Decls {
switch oodecl := oodecl.Unwrap().(type) {
case *ast.OptionNode:
if oodecl.IsIncomplete() {
if oodecl.Name == nil || !ast.ExtendedSyntaxEnabled {
continue
}
}
if ood.Options == nil {
ood.Options = &descriptorpb.OneofOptions{}
}
ood.Options.UninterpretedOption = append(ood.Options.UninterpretedOption, r.asUninterpretedOption(oodecl))
case *ast.FieldNode:
if oodecl.IsIncomplete() {
continue
}
fd := r.asFieldDescriptor(oodecl, maxTag, syntax, handler)
fd.OneofIndex = proto.Int32(int32(oodIndex))
msgd.Field = append(msgd.Field, fd)
ooFields++
case *ast.GroupNode:
fd, md := r.asGroupDescriptors(oodecl, syntax, maxTag, handler, depth+1)
fd.OneofIndex = proto.Int32(int32(oodIndex))
msgd.Field = append(msgd.Field, fd)
msgd.NestedType = append(msgd.NestedType, md)
ooFields++
}
}
if ooFields == 0 {
declNodeInfo := r.file.NodeInfo(decl)
_ = handler.HandleErrorf(declNodeInfo, "oneof must contain at least one field")
}
case *ast.MessageNode:
msgd.NestedType = append(msgd.NestedType, r.asMessageDescriptor(decl, syntax, handler, depth+1))
case *ast.ReservedNode:
r.addReservedNames(&msgd.ReservedName, decl, syntax, handler, rsvdNames)
for _, rng := range decl.FilterRanges() {
msgd.ReservedRange = append(msgd.ReservedRange, r.asMessageReservedRange(rng, maxTag, handler))
}
}
}
if messageSetOpt != nil {
if len(msgd.Field) > 0 {
node := r.FieldNode(msgd.Field[0])
nodeInfo := r.file.NodeInfo(node)
_ = handler.HandleErrorf(nodeInfo, "messages with message-set wire format cannot contain non-extension fields")
}
if len(msgd.ExtensionRange) == 0 {
node := r.OptionNode(messageSetOpt)
nodeInfo := r.file.NodeInfo(node)
_ = handler.HandleErrorf(nodeInfo, "messages with message-set wire format must contain at least one extension range")
}
}
// process any proto3_optional fields
if syntax == protoreflect.Proto3 {
r.processProto3OptionalFields(msgd)
}
}
func (r *result) isMessageSetWireFormat(scope string, md *descriptorpb.DescriptorProto, handler *reporter.Handler) (*descriptorpb.UninterpretedOption, error) {
uo := md.GetOptions().GetUninterpretedOption()
index, err := protointernal.FindOption(r, handler, scope, uo, "message_set_wire_format")
if err != nil {
return nil, err
}
if index == -1 {
// no such option
return nil, nil
}
opt := uo[index]
switch opt.GetIdentifierValue() {
case "true":
return opt, nil
case "false":
return nil, nil
default:
optNode := r.OptionNode(opt)
optNodeInfo := r.file.NodeInfo(optNode.GetVal())
return nil, handler.HandleErrorf(optNodeInfo, "%s: expecting bool value for message_set_wire_format option", scope)
}
}
func (r *result) asMessageReservedRange(rng *ast.RangeNode, maxTag int32, handler *reporter.Handler) *descriptorpb.DescriptorProto_ReservedRange {
start, end := r.getRangeBounds(rng, 1, maxTag, handler)
rr := &descriptorpb.DescriptorProto_ReservedRange{
Start: proto.Int32(start),
End: proto.Int32(end + 1),
}
r.putMessageReservedRangeNode(rr, rng)
return rr
}
func (r *result) getRangeBounds(rng *ast.RangeNode, minVal, maxVal int32, handler *reporter.Handler) (int32, int32) {
checkOrder := true
start, ok := rng.StartValueAsInt32(minVal, maxVal)
if !ok {
checkOrder = false
startValNodeInfo := r.file.NodeInfo(rng.StartVal)
_ = handler.HandleErrorf(startValNodeInfo, "range start %d is out of range: should be between %d and %d", rng.StartValue(), minVal, maxVal)
}
end, ok := rng.EndValueAsInt32(minVal, maxVal)
if !ok {
checkOrder = false
if rng.EndVal != nil {
endValNodeInfo := r.file.NodeInfo(rng.EndVal)
_ = handler.HandleErrorf(endValNodeInfo, "range end %d is out of range: should be between %d and %d", rng.EndValue(), minVal, maxVal)
}
}
if checkOrder && start > end {
rangeStartNodeInfo := r.file.NodeInfo(rng.RangeStart())
_ = handler.HandleErrorf(rangeStartNodeInfo, "range, %d to %d, is invalid: start must be <= end", start, end)
}
return start, end
}
func (r *result) asServiceDescriptor(svc *ast.ServiceNode) *descriptorpb.ServiceDescriptorProto {
sd := &descriptorpb.ServiceDescriptorProto{Name: proto.String(svc.Name.Val)}
r.putServiceNode(sd, svc)
for _, decl := range svc.Decls {
switch decl := decl.Unwrap().(type) {
case *ast.OptionNode:
if decl.IsIncomplete() {
if decl.Name == nil || !ast.ExtendedSyntaxEnabled {
continue
}
}
if sd.Options == nil {
sd.Options = &descriptorpb.ServiceOptions{}
}
sd.Options.UninterpretedOption = append(sd.Options.UninterpretedOption, r.asUninterpretedOption(decl))
case *ast.RPCNode:
if decl.IsIncomplete() {
continue
}
sd.Method = append(sd.Method, r.asMethodDescriptor(decl))
}
}
return sd
}
func (r *result) checkTag(n ast.Node, v uint64, maxTag int32) error {
switch {
case v < 1:
return reporter.Errorf(r.file.NodeInfo(n), "tag number %d must be greater than zero", v)
case v > uint64(maxTag):
return reporter.Errorf(r.file.NodeInfo(n), "tag number %d is higher than max allowed tag number (%d)", v, maxTag)
case v >= protointernal.SpecialReservedStart && v <= protointernal.SpecialReservedEnd:
return reporter.Errorf(r.file.NodeInfo(n), "tag number %d is in disallowed reserved range %d-%d", v, protointernal.SpecialReservedStart, protointernal.SpecialReservedEnd)
default:
return nil
}
}
// processProto3OptionalFields adds synthetic oneofs to the given message descriptor
// for each proto3 optional field. It also updates the fields to have the correct
// oneof index reference.
func (r *result) processProto3OptionalFields(msgd *descriptorpb.DescriptorProto) {
// add synthetic oneofs to the given message descriptor for each proto3
// optional field, and update each field to have correct oneof index
var allNames map[string]struct{}
for _, fd := range msgd.Field {
if fd.GetProto3Optional() {
// lazy init the set of all names
if allNames == nil {
allNames = map[string]struct{}{}
for _, fd := range msgd.Field {
allNames[fd.GetName()] = struct{}{}
}
for _, od := range msgd.OneofDecl {
allNames[od.GetName()] = struct{}{}
}
// NB: protoc only considers names of other fields and oneofs
// when computing the synthetic oneof name. But that feels like
// a bug, since it means it could generate a name that conflicts
// with some other symbol defined in the message. If it's decided
// that's NOT a bug and is desirable, then we should remove the
// following four loops to mimic protoc's behavior.
for _, fd := range msgd.Extension {
allNames[fd.GetName()] = struct{}{}
}
for _, ed := range msgd.EnumType {
allNames[ed.GetName()] = struct{}{}
for _, evd := range ed.Value {
allNames[evd.GetName()] = struct{}{}
}
}
for _, fd := range msgd.NestedType {
allNames[fd.GetName()] = struct{}{}
}
}
// Compute a name for the synthetic oneof. This uses the same
// algorithm as used in protoc:
// https://github.com/protocolbuffers/protobuf/blob/74ad62759e0a9b5a21094f3fb9bb4ebfaa0d1ab8/src/google/protobuf/compiler/parser.cc#L785-L803
ooName := fd.GetName()
if !strings.HasPrefix(ooName, "_") {
ooName = "_" + ooName
}
for {
_, ok := allNames[ooName]
if !ok {
// found a unique name
allNames[ooName] = struct{}{}
break
}
ooName = "X" + ooName
}
fd.OneofIndex = proto.Int32(int32(len(msgd.OneofDecl)))
ood := &descriptorpb.OneofDescriptorProto{Name: proto.String(ooName)}
msgd.OneofDecl = append(msgd.OneofDecl, ood)
r.putOneofNode(ood, r.FieldNode(fd))
}
}
}
func (r *result) Node(m proto.Message) ast.Node {
return r.nodes[m]
}
func (r *result) FileNode() *ast.FileNode {
node, ok := r.nodes[r.proto].(*ast.FileNode)
if !ok {
return ast.NewEmptyFileNode(r.proto.GetName(), 0)
}
return node
}
func (r *result) OptionNode(o *descriptorpb.UninterpretedOption) *ast.OptionNode {
node, _ := r.nodes[o].(*ast.OptionNode)
return node
}
func (r *result) OptionNamePartNode(o *descriptorpb.UninterpretedOption_NamePart) ast.Node {
return r.nodes[o]
}
func (r *result) MessageNode(m *descriptorpb.DescriptorProto) *ast.MessageDeclNode {
switch n := r.nodes[m].(type) {
case *ast.MessageDeclNode:
return n
case interface{ AsMessageDeclNode() *ast.MessageDeclNode }:
return n.AsMessageDeclNode()
}
return nil
}
func (r *result) FieldNode(f *descriptorpb.FieldDescriptorProto) *ast.FieldDeclNode {
switch n := r.nodes[f].(type) {
case *ast.FieldDeclNode:
return n
case interface{ AsFieldDeclNode() *ast.FieldDeclNode }:
return n.AsFieldDeclNode()
}
return nil
}
func (r *result) FieldExtendeeNode(f *descriptorpb.FieldDescriptorProto) *ast.ExtendNode {