/
Descriptors.java
3293 lines (2921 loc) · 113 KB
/
Descriptors.java
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
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file or at
// https://developers.google.com/open-source/licenses/bsd
package com.google.protobuf;
import static com.google.protobuf.Internal.checkNotNull;
import com.google.protobuf.DescriptorProtos.DescriptorProto;
import com.google.protobuf.DescriptorProtos.Edition;
import com.google.protobuf.DescriptorProtos.EnumDescriptorProto;
import com.google.protobuf.DescriptorProtos.EnumOptions;
import com.google.protobuf.DescriptorProtos.EnumValueDescriptorProto;
import com.google.protobuf.DescriptorProtos.EnumValueOptions;
import com.google.protobuf.DescriptorProtos.FeatureSet;
import com.google.protobuf.DescriptorProtos.FeatureSetDefaults;
import com.google.protobuf.DescriptorProtos.FeatureSetDefaults.FeatureSetEditionDefault;
import com.google.protobuf.DescriptorProtos.FieldDescriptorProto;
import com.google.protobuf.DescriptorProtos.FieldOptions;
import com.google.protobuf.DescriptorProtos.FileDescriptorProto;
import com.google.protobuf.DescriptorProtos.FileOptions;
import com.google.protobuf.DescriptorProtos.MessageOptions;
import com.google.protobuf.DescriptorProtos.MethodDescriptorProto;
import com.google.protobuf.DescriptorProtos.MethodOptions;
import com.google.protobuf.DescriptorProtos.OneofDescriptorProto;
import com.google.protobuf.DescriptorProtos.OneofOptions;
import com.google.protobuf.DescriptorProtos.ServiceDescriptorProto;
import com.google.protobuf.DescriptorProtos.ServiceOptions;
import com.google.protobuf.Descriptors.DescriptorValidationException;
import com.google.protobuf.JavaFeaturesProto.JavaFeatures;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Logger;
/**
* Contains a collection of classes which describe protocol message types.
*
* <p>Every message type has a {@link Descriptor}, which lists all its fields and other information
* about a type. You can get a message type's descriptor by calling {@code
* MessageType.getDescriptor()}, or (given a message object of the type) {@code
* message.getDescriptorForType()}. Furthermore, each message is associated with a {@link
* FileDescriptor} for a relevant {@code .proto} file. You can obtain it by calling {@code
* Descriptor.getFile()}. A {@link FileDescriptor} contains descriptors for all the messages defined
* in that file, and file descriptors for all the imported {@code .proto} files.
*
* <p>Descriptors are built from DescriptorProtos, as defined in {@code
* google/protobuf/descriptor.proto}.
*
* @author kenton@google.com Kenton Varda
*/
@CheckReturnValue
public final class Descriptors {
private static final Logger logger = Logger.getLogger(Descriptors.class.getName());
private static final int[] EMPTY_INT_ARRAY = new int[0];
private static final Descriptor[] EMPTY_DESCRIPTORS = new Descriptor[0];
private static final FieldDescriptor[] EMPTY_FIELD_DESCRIPTORS = new FieldDescriptor[0];
private static final EnumDescriptor[] EMPTY_ENUM_DESCRIPTORS = new EnumDescriptor[0];
private static final ServiceDescriptor[] EMPTY_SERVICE_DESCRIPTORS = new ServiceDescriptor[0];
private static final OneofDescriptor[] EMPTY_ONEOF_DESCRIPTORS = new OneofDescriptor[0];
private static final ConcurrentHashMap<Integer, FeatureSet> FEATURE_CACHE =
new ConcurrentHashMap<>();
@SuppressWarnings("NonFinalStaticField")
private static volatile FeatureSetDefaults javaEditionDefaults = null;
private static FeatureSet getEditionDefaults(Edition edition) {
// Force explicit initialization before synchronized block which can trigger initialization in
// `JavaFeaturesProto.registerAllExtensions()` and `FeatureSetdefaults.parseFrom()` calls.
// Otherwise, this can result in deadlock if another threads holds the static init block's
// implicit lock. This operation should be cheap if initialization has already occurred.
Descriptor unused1 = FeatureSetDefaults.getDescriptor();
FileDescriptor unused2 = JavaFeaturesProto.getDescriptor();
if (javaEditionDefaults == null) {
synchronized (Descriptors.class) {
if (javaEditionDefaults == null) {
try {
ExtensionRegistry registry = ExtensionRegistry.newInstance();
registry.add(JavaFeaturesProto.java);
javaEditionDefaults =
FeatureSetDefaults.parseFrom(
JavaEditionDefaults.PROTOBUF_INTERNAL_JAVA_EDITION_DEFAULTS.getBytes(
Internal.ISO_8859_1),
registry);
} catch (Exception e) {
throw new AssertionError(e);
}
}
}
}
if (edition.getNumber() < javaEditionDefaults.getMinimumEdition().getNumber()) {
throw new IllegalArgumentException(
"Edition "
+ edition
+ " is lower than the minimum supported edition "
+ javaEditionDefaults.getMinimumEdition()
+ "!");
}
if (edition.getNumber() > javaEditionDefaults.getMaximumEdition().getNumber()) {
throw new IllegalArgumentException(
"Edition "
+ edition
+ " is greater than the maximum supported edition "
+ javaEditionDefaults.getMaximumEdition()
+ "!");
}
FeatureSet found = null;
for (FeatureSetEditionDefault editionDefault : javaEditionDefaults.getDefaultsList()) {
if (editionDefault.getEdition().getNumber() > edition.getNumber()) {
break;
}
found = editionDefault.getFeatures();
}
if (found == null) {
throw new IllegalArgumentException(
"Edition " + edition + " does not have a valid default FeatureSet!");
}
return found;
}
private static FeatureSet internFeatures(FeatureSet features) {
FeatureSet cached = FEATURE_CACHE.putIfAbsent(features.hashCode(), features);
if (cached == null) {
return features;
}
return cached;
}
/**
* Describes a {@code .proto} file, including everything defined within. That includes, in
* particular, descriptors for all the messages and file descriptors for all other imported {@code
* .proto} files (dependencies).
*/
public static final class FileDescriptor extends GenericDescriptor {
/** Convert the descriptor to its protocol message representation. */
@Override
public FileDescriptorProto toProto() {
return proto;
}
/** Get the file name. */
@Override
public String getName() {
return proto.getName();
}
/** Returns this object. */
@Override
public FileDescriptor getFile() {
return this;
}
/** Returns the same as getName(). */
@Override
public String getFullName() {
return proto.getName();
}
/**
* Get the proto package name. This is the package name given by the {@code package} statement
* in the {@code .proto} file, which differs from the Java package.
*/
public String getPackage() {
return proto.getPackage();
}
/** Get the {@code FileOptions}, defined in {@code descriptor.proto}. */
public FileOptions getOptions() {
if (this.options == null) {
FileOptions strippedOptions = this.proto.getOptions();
if (strippedOptions.hasFeatures()) {
// Clients should be using feature accessor methods, not accessing features on the
// options
// proto.
strippedOptions = strippedOptions.toBuilder().clearFeatures().build();
}
synchronized (this) {
if (this.options == null) {
this.options = strippedOptions;
}
}
}
return this.options;
}
/** Get a list of top-level message types declared in this file. */
public List<Descriptor> getMessageTypes() {
return Collections.unmodifiableList(Arrays.asList(messageTypes));
}
/** Get a list of top-level enum types declared in this file. */
public List<EnumDescriptor> getEnumTypes() {
return Collections.unmodifiableList(Arrays.asList(enumTypes));
}
/** Get a list of top-level services declared in this file. */
public List<ServiceDescriptor> getServices() {
return Collections.unmodifiableList(Arrays.asList(services));
}
/** Get a list of top-level extensions declared in this file. */
public List<FieldDescriptor> getExtensions() {
return Collections.unmodifiableList(Arrays.asList(extensions));
}
/** Get a list of this file's dependencies (imports). */
public List<FileDescriptor> getDependencies() {
return Collections.unmodifiableList(Arrays.asList(dependencies));
}
/** Get a list of this file's public dependencies (public imports). */
public List<FileDescriptor> getPublicDependencies() {
return Collections.unmodifiableList(Arrays.asList(publicDependencies));
}
/** Get the edition of the .proto file. */
Edition getEdition() {
switch (proto.getSyntax()) {
case "editions":
return proto.getEdition();
case "proto3":
return Edition.EDITION_PROTO3;
default:
return Edition.EDITION_PROTO2;
}
}
public void copyHeadingTo(FileDescriptorProto.Builder protoBuilder) {
protoBuilder.setName(getName()).setSyntax(proto.getSyntax());
if (!getPackage().isEmpty()) {
protoBuilder.setPackage(getPackage());
}
if (proto.getSyntax().equals("editions")) {
protoBuilder.setEdition(proto.getEdition());
}
if (proto.hasOptions() && !proto.getOptions().equals(FileOptions.getDefaultInstance())) {
protoBuilder.setOptions(proto.getOptions());
}
}
/**
* Find a message type in the file by name. Does not find nested types.
*
* @param name The unqualified type name to look for.
* @return The message type's descriptor, or {@code null} if not found.
*/
public Descriptor findMessageTypeByName(String name) {
// Don't allow looking up nested types. This will make optimization
// easier later.
if (name.indexOf('.') != -1) {
return null;
}
final String packageName = getPackage();
if (!packageName.isEmpty()) {
name = packageName + '.' + name;
}
final GenericDescriptor result = pool.findSymbol(name);
if (result instanceof Descriptor && result.getFile() == this) {
return (Descriptor) result;
} else {
return null;
}
}
/**
* Find an enum type in the file by name. Does not find nested types.
*
* @param name The unqualified type name to look for.
* @return The enum type's descriptor, or {@code null} if not found.
*/
public EnumDescriptor findEnumTypeByName(String name) {
// Don't allow looking up nested types. This will make optimization
// easier later.
if (name.indexOf('.') != -1) {
return null;
}
final String packageName = getPackage();
if (!packageName.isEmpty()) {
name = packageName + '.' + name;
}
final GenericDescriptor result = pool.findSymbol(name);
if (result instanceof EnumDescriptor && result.getFile() == this) {
return (EnumDescriptor) result;
} else {
return null;
}
}
/**
* Find a service type in the file by name.
*
* @param name The unqualified type name to look for.
* @return The service type's descriptor, or {@code null} if not found.
*/
public ServiceDescriptor findServiceByName(String name) {
// Don't allow looking up nested types. This will make optimization
// easier later.
if (name.indexOf('.') != -1) {
return null;
}
final String packageName = getPackage();
if (!packageName.isEmpty()) {
name = packageName + '.' + name;
}
final GenericDescriptor result = pool.findSymbol(name);
if (result instanceof ServiceDescriptor && result.getFile() == this) {
return (ServiceDescriptor) result;
} else {
return null;
}
}
/**
* Find an extension in the file by name. Does not find extensions nested inside message types.
*
* @param name The unqualified extension name to look for.
* @return The extension's descriptor, or {@code null} if not found.
*/
public FieldDescriptor findExtensionByName(String name) {
if (name.indexOf('.') != -1) {
return null;
}
final String packageName = getPackage();
if (!packageName.isEmpty()) {
name = packageName + '.' + name;
}
final GenericDescriptor result = pool.findSymbol(name);
if (result instanceof FieldDescriptor && result.getFile() == this) {
return (FieldDescriptor) result;
} else {
return null;
}
}
/**
* Construct a {@code FileDescriptor}.
*
* @param proto the protocol message form of the FileDescriptort
* @param dependencies {@code FileDescriptor}s corresponding to all of the file's dependencies.
* @throws DescriptorValidationException {@code proto} is not a valid descriptor. This can occur
* for a number of reasons; for instance, because a field has an undefined type or because
* two messages were defined with the same name.
*/
public static FileDescriptor buildFrom(FileDescriptorProto proto, FileDescriptor[] dependencies)
throws DescriptorValidationException {
return buildFrom(proto, dependencies, false);
}
/**
* Construct a {@code FileDescriptor}.
*
* @param proto the protocol message form of the FileDescriptor
* @param dependencies {@code FileDescriptor}s corresponding to all of the file's dependencies
* @param allowUnknownDependencies if true, non-existing dependencies will be ignored and
* undefined message types will be replaced with a placeholder type. Undefined enum types
* still cause a DescriptorValidationException.
* @throws DescriptorValidationException {@code proto} is not a valid descriptor. This can occur
* for a number of reasons; for instance, because a field has an undefined type or because
* two messages were defined with the same name.
*/
public static FileDescriptor buildFrom(
FileDescriptorProto proto, FileDescriptor[] dependencies, boolean allowUnknownDependencies)
throws DescriptorValidationException {
return buildFrom(proto, dependencies, allowUnknownDependencies, false);
}
private static FileDescriptor buildFrom(
FileDescriptorProto proto,
FileDescriptor[] dependencies,
boolean allowUnknownDependencies,
boolean allowUnresolvedFeatures)
throws DescriptorValidationException {
// Building descriptors involves two steps: translating and linking.
// In the translation step (implemented by FileDescriptor's
// constructor), we build an object tree mirroring the
// FileDescriptorProto's tree and put all of the descriptors into the
// DescriptorPool's lookup tables. In the linking step, we look up all
// type references in the DescriptorPool, so that, for example, a
// FieldDescriptor for an embedded message contains a pointer directly
// to the Descriptor for that message's type. We also detect undefined
// types in the linking step.
DescriptorPool pool = new DescriptorPool(dependencies, allowUnknownDependencies);
FileDescriptor result =
new FileDescriptor(proto, dependencies, pool, allowUnknownDependencies);
result.crossLink();
// Skip feature resolution until later for calls from gencode.
if (!allowUnresolvedFeatures) {
// We do not need to force feature resolution for proto1 dependencies
// since dependencies from non-gencode should already be fully feature resolved.
result.resolveAllFeaturesInternal();
}
return result;
}
private static byte[] latin1Cat(final String[] strings) {
// Hack: We can't embed a raw byte array inside generated Java code
// (at least, not efficiently), but we can embed Strings. So, the
// protocol compiler embeds the FileDescriptorProto as a giant
// string literal which is passed to this function to construct the
// file's FileDescriptor. The string literal contains only 8-bit
// characters, each one representing a byte of the FileDescriptorProto's
// serialized form. So, if we convert it to bytes in ISO-8859-1, we
// should get the original bytes that we want.
// Literal strings are limited to 64k, so it may be split into multiple strings.
if (strings.length == 1) {
return strings[0].getBytes(Internal.ISO_8859_1);
}
StringBuilder descriptorData = new StringBuilder();
for (String part : strings) {
descriptorData.append(part);
}
return descriptorData.toString().getBytes(Internal.ISO_8859_1);
}
private static FileDescriptor[] findDescriptors(
final Class<?> descriptorOuterClass,
final String[] dependencyClassNames,
final String[] dependencyFileNames) {
List<FileDescriptor> descriptors = new ArrayList<>();
for (int i = 0; i < dependencyClassNames.length; i++) {
try {
Class<?> clazz = descriptorOuterClass.getClassLoader().loadClass(dependencyClassNames[i]);
descriptors.add((FileDescriptor) clazz.getField("descriptor").get(null));
} catch (Exception e) {
// We allow unknown dependencies by default. If a dependency cannot
// be found we only generate a warning.
logger.warning("Descriptors for \"" + dependencyFileNames[i] + "\" can not be found.");
}
}
return descriptors.toArray(new FileDescriptor[0]);
}
/**
* This method is to be called by generated code only. It is equivalent to {@code buildFrom}
* except that the {@code FileDescriptorProto} is encoded in protocol buffer wire format.
*/
public static FileDescriptor internalBuildGeneratedFileFrom(
final String[] descriptorDataParts, final FileDescriptor[] dependencies) {
final byte[] descriptorBytes = latin1Cat(descriptorDataParts);
FileDescriptorProto proto;
try {
proto = FileDescriptorProto.parseFrom(descriptorBytes);
} catch (InvalidProtocolBufferException e) {
throw new IllegalArgumentException(
"Failed to parse protocol buffer descriptor for generated code.", e);
}
try {
// When building descriptors for generated code, we allow unknown
// dependencies by default and delay feature resolution until later.
return buildFrom(proto, dependencies, true, true);
} catch (DescriptorValidationException e) {
throw new IllegalArgumentException(
"Invalid embedded descriptor for \"" + proto.getName() + "\".", e);
}
}
/**
* This method is to be called by generated code only. It uses Java reflection to load the
* dependencies' descriptors.
*/
public static FileDescriptor internalBuildGeneratedFileFrom(
final String[] descriptorDataParts,
final Class<?> descriptorOuterClass,
final String[] dependencyClassNames,
final String[] dependencyFileNames) {
FileDescriptor[] dependencies =
findDescriptors(descriptorOuterClass, dependencyClassNames, dependencyFileNames);
return internalBuildGeneratedFileFrom(descriptorDataParts, dependencies);
}
/**
* This method is to be called by generated code only. It updates the FileDescriptorProto
* associated with the descriptor by parsing it again with the given ExtensionRegistry. This is
* needed to recognize custom options.
*/
public static void internalUpdateFileDescriptor(
FileDescriptor descriptor, ExtensionRegistry registry) {
ByteString bytes = descriptor.proto.toByteString();
try {
FileDescriptorProto proto = FileDescriptorProto.parseFrom(bytes, registry);
descriptor.setProto(proto);
} catch (InvalidProtocolBufferException e) {
throw new IllegalArgumentException(
"Failed to parse protocol buffer descriptor for generated code.", e);
}
}
/**
* This class should be used by generated code only. When calling {@link
* FileDescriptor#internalBuildGeneratedFileFrom}, the caller provides a callback implementing
* this interface. The callback is called after the FileDescriptor has been constructed, in
* order to assign all the global variables defined in the generated code which point at parts
* of the FileDescriptor. The callback returns an ExtensionRegistry which contains any
* extensions which might be used in the descriptor -- that is, extensions of the various
* "Options" messages defined in descriptor.proto. The callback may also return null to indicate
* that no extensions are used in the descriptor.
*
* <p>This interface is deprecated. Use the return value of internalBuildGeneratedFrom()
* instead.
*/
@Deprecated
public interface InternalDescriptorAssigner {
ExtensionRegistry assignDescriptors(FileDescriptor root);
}
private FileDescriptorProto proto;
private volatile FileOptions options;
private final Descriptor[] messageTypes;
private final EnumDescriptor[] enumTypes;
private final ServiceDescriptor[] services;
private final FieldDescriptor[] extensions;
private final FileDescriptor[] dependencies;
private final FileDescriptor[] publicDependencies;
private final DescriptorPool pool;
private FileDescriptor(
final FileDescriptorProto proto,
final FileDescriptor[] dependencies,
final DescriptorPool pool,
boolean allowUnknownDependencies)
throws DescriptorValidationException {
this.pool = pool;
this.proto = proto;
this.dependencies = dependencies.clone();
HashMap<String, FileDescriptor> nameToFileMap = new HashMap<>();
for (FileDescriptor file : dependencies) {
nameToFileMap.put(file.getName(), file);
}
List<FileDescriptor> publicDependencies = new ArrayList<>();
for (int i = 0; i < proto.getPublicDependencyCount(); i++) {
int index = proto.getPublicDependency(i);
if (index < 0 || index >= proto.getDependencyCount()) {
throw new DescriptorValidationException(this, "Invalid public dependency index.");
}
String name = proto.getDependency(index);
FileDescriptor file = nameToFileMap.get(name);
if (file == null) {
if (!allowUnknownDependencies) {
throw new DescriptorValidationException(this, "Invalid public dependency: " + name);
}
// Ignore unknown dependencies.
} else {
publicDependencies.add(file);
}
}
this.publicDependencies = new FileDescriptor[publicDependencies.size()];
publicDependencies.toArray(this.publicDependencies);
pool.addPackage(getPackage(), this);
messageTypes =
(proto.getMessageTypeCount() > 0)
? new Descriptor[proto.getMessageTypeCount()]
: EMPTY_DESCRIPTORS;
for (int i = 0; i < proto.getMessageTypeCount(); i++) {
messageTypes[i] = new Descriptor(proto.getMessageType(i), this, null, i);
}
enumTypes =
(proto.getEnumTypeCount() > 0)
? new EnumDescriptor[proto.getEnumTypeCount()]
: EMPTY_ENUM_DESCRIPTORS;
for (int i = 0; i < proto.getEnumTypeCount(); i++) {
enumTypes[i] = new EnumDescriptor(proto.getEnumType(i), this, null, i);
}
services =
(proto.getServiceCount() > 0)
? new ServiceDescriptor[proto.getServiceCount()]
: EMPTY_SERVICE_DESCRIPTORS;
for (int i = 0; i < proto.getServiceCount(); i++) {
services[i] = new ServiceDescriptor(proto.getService(i), this, i);
}
extensions =
(proto.getExtensionCount() > 0)
? new FieldDescriptor[proto.getExtensionCount()]
: EMPTY_FIELD_DESCRIPTORS;
for (int i = 0; i < proto.getExtensionCount(); i++) {
extensions[i] = new FieldDescriptor(proto.getExtension(i), this, null, i, true);
}
}
/** Create a placeholder FileDescriptor for a message Descriptor. */
FileDescriptor(String packageName, Descriptor message) throws DescriptorValidationException {
this.parent = null;
this.pool = new DescriptorPool(new FileDescriptor[0], true);
this.proto =
FileDescriptorProto.newBuilder()
.setName(message.getFullName() + ".placeholder.proto")
.setPackage(packageName)
.addMessageType(message.toProto())
.build();
this.dependencies = new FileDescriptor[0];
this.publicDependencies = new FileDescriptor[0];
messageTypes = new Descriptor[] {message};
enumTypes = EMPTY_ENUM_DESCRIPTORS;
services = EMPTY_SERVICE_DESCRIPTORS;
extensions = EMPTY_FIELD_DESCRIPTORS;
pool.addPackage(packageName, this);
pool.addSymbol(message);
}
public void resolveAllFeaturesImmutable() {
try {
resolveAllFeaturesInternal();
} catch (DescriptorValidationException e) {
throw new IllegalArgumentException("Invalid features for \"" + proto.getName() + "\".", e);
}
}
/**
* This method is to be called by generated code only. It resolves features for the descriptor
* and all of its children.
*/
private void resolveAllFeaturesInternal() throws DescriptorValidationException {
if (this.features != null) {
return;
}
synchronized (this) {
if (this.features != null) {
return;
}
resolveFeatures(proto.getOptions().getFeatures());
for (Descriptor messageType : messageTypes) {
messageType.resolveAllFeatures();
}
for (EnumDescriptor enumType : enumTypes) {
enumType.resolveAllFeatures();
}
for (ServiceDescriptor service : services) {
service.resolveAllFeatures();
}
for (FieldDescriptor extension : extensions) {
extension.resolveAllFeatures();
}
}
}
@Override
FeatureSet inferLegacyProtoFeatures() {
FeatureSet.Builder features = FeatureSet.newBuilder();
if (getEdition().getNumber() >= Edition.EDITION_2023.getNumber()) {
return features.build();
}
if (getEdition() == Edition.EDITION_PROTO2) {
if (proto.getOptions().getJavaStringCheckUtf8()) {
features.setExtension(
JavaFeaturesProto.java,
JavaFeatures.newBuilder()
.setUtf8Validation(JavaFeatures.Utf8Validation.VERIFY)
.build());
}
}
return features.build();
}
@Override
boolean hasInferredLegacyProtoFeatures() {
if (getEdition().getNumber() >= Edition.EDITION_2023.getNumber()) {
return false;
}
if (getEdition() == Edition.EDITION_PROTO2) {
if (proto.getOptions().getJavaStringCheckUtf8()) {
return true;
}
}
return false;
}
/** Look up and cross-link all field types, etc. */
private void crossLink() throws DescriptorValidationException {
for (final Descriptor messageType : messageTypes) {
messageType.crossLink();
}
for (final ServiceDescriptor service : services) {
service.crossLink();
}
for (final FieldDescriptor extension : extensions) {
extension.crossLink();
}
}
/**
* Replace our {@link FileDescriptorProto} with the given one, which is identical except that it
* might contain extensions that weren't present in the original. This method is needed for
* bootstrapping when a file defines custom options. The options may be defined in the file
* itself, so we can't actually parse them until we've constructed the descriptors, but to
* construct the descriptors we have to have parsed the descriptor protos. So, we have to parse
* the descriptor protos a second time after constructing the descriptors.
*/
private synchronized void setProto(final FileDescriptorProto proto) {
this.proto = proto;
this.options = null;
try {
resolveFeatures(proto.getOptions().getFeatures());
for (int i = 0; i < messageTypes.length; i++) {
messageTypes[i].setProto(proto.getMessageType(i));
}
for (int i = 0; i < enumTypes.length; i++) {
enumTypes[i].setProto(proto.getEnumType(i));
}
for (int i = 0; i < services.length; i++) {
services[i].setProto(proto.getService(i));
}
for (int i = 0; i < extensions.length; i++) {
extensions[i].setProto(proto.getExtension(i));
}
} catch (DescriptorValidationException e) {
throw new IllegalArgumentException("Invalid features for \"" + proto.getName() + "\".", e);
}
}
}
// =================================================================
/** Describes a message type. */
public static final class Descriptor extends GenericDescriptor {
/**
* Get the index of this descriptor within its parent. In other words, given a {@link
* FileDescriptor} {@code file}, the following is true:
*
* <pre>
* for all i in [0, file.getMessageTypeCount()):
* file.getMessageType(i).getIndex() == i
* </pre>
*
* Similarly, for a {@link Descriptor} {@code messageType}:
*
* <pre>
* for all i in [0, messageType.getNestedTypeCount()):
* messageType.getNestedType(i).getIndex() == i
* </pre>
*/
public int getIndex() {
return index;
}
/** Convert the descriptor to its protocol message representation. */
@Override
public DescriptorProto toProto() {
return proto;
}
/** Get the type's unqualified name. */
@Override
public String getName() {
return proto.getName();
}
/**
* Get the type's fully-qualified name, within the proto language's namespace. This differs from
* the Java name. For example, given this {@code .proto}:
*
* <pre>
* package foo.bar;
* option java_package = "com.example.protos"
* message Baz {}
* </pre>
*
* {@code Baz}'s full name is "foo.bar.Baz".
*/
@Override
public String getFullName() {
return fullName;
}
/** Get the {@link FileDescriptor} containing this descriptor. */
@Override
public FileDescriptor getFile() {
return file;
}
/** If this is a nested type, get the outer descriptor, otherwise null. */
public Descriptor getContainingType() {
return containingType;
}
/** Get the {@code MessageOptions}, defined in {@code descriptor.proto}. */
public MessageOptions getOptions() {
if (this.options == null) {
MessageOptions strippedOptions = this.proto.getOptions();
if (strippedOptions.hasFeatures()) {
// Clients should be using feature accessor methods, not accessing features on the
// options
// proto.
strippedOptions = strippedOptions.toBuilder().clearFeatures().build();
}
synchronized (this) {
if (this.options == null) {
this.options = strippedOptions;
}
}
}
return this.options;
}
/** Get a list of this message type's fields. */
public List<FieldDescriptor> getFields() {
return Collections.unmodifiableList(Arrays.asList(fields));
}
/** Get a list of this message type's oneofs. */
public List<OneofDescriptor> getOneofs() {
return Collections.unmodifiableList(Arrays.asList(oneofs));
}
/** Get a list of this message type's real oneofs. */
public List<OneofDescriptor> getRealOneofs() {
return Collections.unmodifiableList(Arrays.asList(oneofs).subList(0, realOneofCount));
}
/** Get a list of this message type's extensions. */
public List<FieldDescriptor> getExtensions() {
return Collections.unmodifiableList(Arrays.asList(extensions));
}
/** Get a list of message types nested within this one. */
public List<Descriptor> getNestedTypes() {
return Collections.unmodifiableList(Arrays.asList(nestedTypes));
}
/** Get a list of enum types nested within this one. */
public List<EnumDescriptor> getEnumTypes() {
return Collections.unmodifiableList(Arrays.asList(enumTypes));
}
/** Determines if the given field number is an extension. */
public boolean isExtensionNumber(final int number) {
int index = Arrays.binarySearch(extensionRangeLowerBounds, number);
if (index < 0) {
index = ~index - 1;
}
// extensionRangeLowerBounds[index] is the biggest value <= number
return index >= 0 && number < extensionRangeUpperBounds[index];
}
/** Determines if the given field number is reserved. */
public boolean isReservedNumber(final int number) {
for (final DescriptorProto.ReservedRange range : proto.getReservedRangeList()) {
if (range.getStart() <= number && number < range.getEnd()) {
return true;
}
}
return false;
}
/** Determines if the given field name is reserved. */
public boolean isReservedName(final String name) {
checkNotNull(name);
for (final String reservedName : proto.getReservedNameList()) {
if (reservedName.equals(name)) {
return true;
}
}
return false;
}
/**
* Indicates whether the message can be extended. That is, whether it has any "extensions x to
* y" ranges declared on it.
*/
public boolean isExtendable() {
return !proto.getExtensionRangeList().isEmpty();
}
/**
* Finds a field by name.
*
* @param name The unqualified name of the field (e.g. "foo"). For protocol buffer messages that
* follow <a
* href=https://developers.google.com/protocol-buffers/docs/style#message_and_field_names>Google's
* guidance on naming</a> this will be a snake case string, such as
* <pre>song_name</pre>
* .
* @return The field's descriptor, or {@code null} if not found.
*/
public FieldDescriptor findFieldByName(final String name) {
final GenericDescriptor result = file.pool.findSymbol(fullName + '.' + name);
if (result instanceof FieldDescriptor) {
return (FieldDescriptor) result;
} else {
return null;
}
}
/**
* Finds a field by field number.
*
* @param number The field number within this message type.
* @return The field's descriptor, or {@code null} if not found.
*/
public FieldDescriptor findFieldByNumber(final int number) {
return binarySearch(
fieldsSortedByNumber, fieldsSortedByNumber.length, FieldDescriptor.NUMBER_GETTER, number);
}
/**
* Finds a nested message type by name.
*
* @param name The unqualified name of the nested type such as "Foo"
* @return The types's descriptor, or {@code null} if not found.
*/
public Descriptor findNestedTypeByName(final String name) {
final GenericDescriptor result = file.pool.findSymbol(fullName + '.' + name);
if (result instanceof Descriptor) {
return (Descriptor) result;
} else {
return null;
}
}
/**
* Finds a nested enum type by name.
*
* @param name The unqualified name of the nested type such as "Foo"
* @return The types's descriptor, or {@code null} if not found.
*/
public EnumDescriptor findEnumTypeByName(final String name) {
final GenericDescriptor result = file.pool.findSymbol(fullName + '.' + name);
if (result instanceof EnumDescriptor) {
return (EnumDescriptor) result;
} else {
return null;
}
}
private final int index;
private DescriptorProto proto;
private volatile MessageOptions options;
private final String fullName;
private final FileDescriptor file;
private final Descriptor containingType;
private final Descriptor[] nestedTypes;
private final EnumDescriptor[] enumTypes;
private final FieldDescriptor[] fields;
private final FieldDescriptor[] fieldsSortedByNumber;
private final FieldDescriptor[] extensions;
private final OneofDescriptor[] oneofs;
private final int realOneofCount;
private final int[] extensionRangeLowerBounds;
private final int[] extensionRangeUpperBounds;
// Used to create a placeholder when the type cannot be found.
Descriptor(final String fullname) throws DescriptorValidationException {
String name = fullname;
String packageName = "";
int pos = fullname.lastIndexOf('.');
if (pos != -1) {
name = fullname.substring(pos + 1);
packageName = fullname.substring(0, pos);
}
this.index = 0;
this.proto =
DescriptorProto.newBuilder()
.setName(name)
.addExtensionRange(
DescriptorProto.ExtensionRange.newBuilder().setStart(1).setEnd(536870912).build())
.build();
this.fullName = fullname;
this.containingType = null;
this.nestedTypes = EMPTY_DESCRIPTORS;
this.enumTypes = EMPTY_ENUM_DESCRIPTORS;
this.fields = EMPTY_FIELD_DESCRIPTORS;
this.fieldsSortedByNumber = EMPTY_FIELD_DESCRIPTORS;
this.extensions = EMPTY_FIELD_DESCRIPTORS;
this.oneofs = EMPTY_ONEOF_DESCRIPTORS;
this.realOneofCount = 0;