-
Notifications
You must be signed in to change notification settings - Fork 101
/
Type.java
1877 lines (1652 loc) · 69 KB
/
Type.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
/*
* Type.java
*
* This source file is part of the FoundationDB open source project
*
* Copyright 2015-2022 Apple Inc. and the FoundationDB project authors
*
* 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 com.apple.foundationdb.record.query.plan.cascades.typing;
import com.apple.foundationdb.record.RecordCoreException;
import com.apple.foundationdb.record.query.plan.cascades.Formatter;
import com.apple.foundationdb.record.query.plan.cascades.Narrowable;
import com.apple.foundationdb.record.query.plan.cascades.NullableArrayTypeUtils;
import com.apple.foundationdb.record.query.plan.cascades.PromoteValue;
import com.apple.foundationdb.record.query.plan.cascades.values.Value;
import com.apple.foundationdb.record.util.ProtoUtils;
import com.google.common.base.Suppliers;
import com.google.common.base.Verify;
import com.google.common.collect.BiMap;
import com.google.common.collect.ImmutableBiMap;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.protobuf.ByteString;
import com.google.protobuf.DescriptorProtos;
import com.google.protobuf.DescriptorProtos.DescriptorProto;
import com.google.protobuf.DescriptorProtos.FieldDescriptorProto;
import com.google.protobuf.Descriptors;
import com.google.protobuf.Message;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
/**
* Provides type information about the output of an expression such as {@link Value} in a QGM.
*
* Types bear a resemblance to protobuf types; they are either primitive such as <code>boolean</code>, <code>int</code>,
* and <code>string</code> or structured such as {@link Record} and {@link Array}. Moreover, it is possible to switch
* between a {@link Type} instance and an equivalent protobuf {@link Descriptors} in a lossless manner.
*
* Finally, {@link Type}s are non-referential, so two structural types are considered equal iff their structures
* are equal.
*/
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
public interface Type extends Narrowable<Type> {
@Nonnull
Null NULL = new Null();
@Nonnull
None NONE = new None();
/**
* A map from Java {@link Class} to corresponding {@link TypeCode}.
*/
@Nonnull
Supplier<BiMap<Class<?>, TypeCode>> CLASS_TO_TYPE_CODE_SUPPLIER = Suppliers.memoize(TypeCode::computeClassToTypeCodeMap);
/**
* Returns the {@link TypeCode} of the {@link Type} instance.
*
* @return The {@link TypeCode} of the {@link Type} instance.
*/
TypeCode getTypeCode();
/**
* Returns the corresponding Java {@link Class} of the {@link Type} instance.
*
* @return the corresponding Java {@link Class} of the {@link Type} instance.
*/
default Class<?> getJavaClass() {
return getTypeCode().getJavaClass();
}
/**
* Checks whether a {@link Type} is primitive or structured.
*
* @return <code>true</code> if the {@link Type} is primitive, otherwise <code>false</code>.
*/
default boolean isPrimitive() {
return getTypeCode().isPrimitive();
}
/**
* Checks whether a {@link Type} is nullable.
*
* @return <code>true</code> if the {@link Type} is nullable, otherwise <code>false</code>.
*/
boolean isNullable();
default Type nullable() {
return withNullability(true);
}
default Type notNullable() {
return withNullability(false);
}
/**
* Create a new type based on the current one that indicates nullability based on the {@code isNullable} parameter
* passed in.
* @param newIsNullable indicator whether the returned new type is nullable or not nullable
* @return a new type that is the same type as the current type but reflecting the nullability as passed in to
* this method.
*/
@Nonnull
Type withNullability(boolean newIsNullable);
/**
* Checks whether a {@link Type} is numeric.
* @return <code>true</code> if the {@link Type} is numeric, otherwise <code>false</code>.
*/
default boolean isNumeric() {
return getTypeCode().isNumeric();
}
default boolean isUnresolved() {
final var typeCode = getTypeCode();
return typeCode == TypeCode.UNKNOWN;
}
@Nonnull
default String describe(@Nonnull final Formatter formatter) {
// TODO make better
return toString();
}
/**
* Creates a synthetic protobuf descriptor that is equivalent to <code>this</code> {@link Type}.
*
* @param typeRepositoryBuilder The type repository builder.
*/
default void defineProtoType(final TypeRepository.Builder typeRepositoryBuilder) {
// by default we don't build anything here
}
/**
* Creates a synthetic protobuf descriptor that is equivalent to the <code>this</code> {@link Type} within a given
* protobuf descriptor.
* @param typeRepositoryBuilder The type repository.
* @param descriptorBuilder The parent descriptor into which the newly created descriptor will be created.
* @param fieldNumber The field number of the descriptor.
* @param fieldName The field name of the descriptor.
* @param typeNameOptional The type name of the descriptor.
* @param label The label of the descriptor.
*/
void addProtoField(@Nonnull TypeRepository.Builder typeRepositoryBuilder,
@Nonnull DescriptorProto.Builder descriptorBuilder,
int fieldNumber,
@Nonnull String fieldName,
@Nonnull Optional<String> typeNameOptional,
@Nonnull FieldDescriptorProto.Label label);
/**
* Returns a map from Java {@link Class} to corresponding {@link TypeCode}.
*
* @return A map from Java {@link Class} to corresponding {@link TypeCode}.
*/
@Nonnull
static Map<Class<?>, TypeCode> getClassToTypeCodeMap() {
return CLASS_TO_TYPE_CODE_SUPPLIER.get();
}
/**
* Constructs a field name for a given field suffix.
*
* @param fieldSuffix The field suffix.
* @return a field name generated using the field suffix.
*/
static String fieldName(final Object fieldSuffix) {
// do this in the style of Scala
return "_" + fieldSuffix;
}
@Nonnull
static Null nullType() {
return Type.NULL;
}
@Nonnull
static None noneType() {
return Type.NONE;
}
/**
* For a given {@link TypeCode}, it returns a corresponding <i>nullable</i> {@link Type}.
*
* pre-condition: The {@link TypeCode} is primitive.
*
* @param typeCode The primitive type code.
* @return the corresponding {@link Type}.
*/
@Nonnull
static Type primitiveType(@Nonnull final TypeCode typeCode) {
return primitiveType(typeCode, true);
}
/**
* For a given {@link TypeCode}, it returns a corresponding {@link Type}.
*
* pre-condition: The {@link TypeCode} is primitive.
*
* @param typeCode The primitive type code.
* @param isNullable True, if the {@link Type} is supposed to be nullable, otherwise, false.
* @return the corresponding {@link Type}.
*/
@Nonnull
static Type primitiveType(@Nonnull final TypeCode typeCode, final boolean isNullable) {
Verify.verify(typeCode.isPrimitive());
final int memoizedHashCode = Objects.hash(typeCode.name().hashCode(), isNullable);
return new Type() {
@Override
public TypeCode getTypeCode() {
return typeCode;
}
@Override
public boolean isNullable() {
return isNullable;
}
@Nonnull
@Override
public Type withNullability(final boolean newIsNullable) {
return newIsNullable == isNullable ? this : primitiveType(typeCode, newIsNullable);
}
@Override
public void addProtoField(@Nonnull final TypeRepository.Builder typeRepositoryBuilder,
@Nonnull final DescriptorProto.Builder descriptorBuilder,
final int fieldNumber,
@Nonnull final String fieldName,
@Nonnull final Optional<String> ignored,
@Nonnull final FieldDescriptorProto.Label label) {
final var protoType = Objects.requireNonNull(getTypeCode().getProtoType());
descriptorBuilder.addField(FieldDescriptorProto.newBuilder()
.setNumber(fieldNumber)
.setName(fieldName)
.setType(protoType)
.setLabel(label)
.build());
}
@Override
public int hashCode() {
return memoizedHashCode;
}
@Override
public boolean equals(final Object obj) {
if (obj == null) {
return false;
}
if (obj == this) {
return true;
}
if (getClass() != obj.getClass()) {
return false;
}
final var otherType = (Type)obj;
return getTypeCode() == otherType.getTypeCode() && isNullable() == otherType.isNullable();
}
@Override
public String toString() {
return getTypeCode().toString();
}
};
}
/**
* Maps a {@link List} of {@link Typed} instances to a {@link List} of their {@link Type}s.
* @param typedList The list of {@link Typed} objects.
* @return The list of {@link Type}s.
*/
@Nonnull
static List<Type> fromTyped(@Nonnull List<? extends Typed> typedList) {
return typedList.stream()
.map(Typed::getResultType)
.collect(ImmutableList.toImmutableList());
}
/**
* translates a protobuf {@link com.google.protobuf.Descriptors.Descriptor} to a {@link Type}.
*
* @param descriptor The protobuf descriptor.
* @param protoType The protobuf descriptor type.
* @param protoLabel The protobuf descriptor label.
* @param isNullable <code>true</code> if the generated {@link Type} should be nullable, otherwise <code>false</code>.
* @return A {@link Type} object that corresponds to the protobuf {@link com.google.protobuf.Descriptors.Descriptor}.
*/
@Nonnull
private static Type fromProtoType(@Nullable Descriptors.GenericDescriptor descriptor,
@Nonnull Descriptors.FieldDescriptor.Type protoType,
@Nonnull FieldDescriptorProto.Label protoLabel,
boolean isNullable) {
final var typeCode = TypeCode.fromProtobufType(protoType);
if (protoLabel == FieldDescriptorProto.Label.LABEL_REPEATED) {
// collection type
return fromProtoTypeToArray(descriptor, protoType, typeCode, false);
} else {
if (typeCode.isPrimitive()) {
return primitiveType(typeCode, isNullable);
} else if (typeCode == TypeCode.ENUM) {
final var enumDescriptor = (Descriptors.EnumDescriptor)Objects.requireNonNull(descriptor);
return Enum.fromProtoValues(isNullable, enumDescriptor.getValues());
} else if (typeCode == TypeCode.RECORD) {
Objects.requireNonNull(descriptor);
final var messageDescriptor = (Descriptors.Descriptor)descriptor;
if (NullableArrayTypeUtils.describesWrappedArray(messageDescriptor)) {
// find TypeCode of array elements
final var elementField = messageDescriptor.findFieldByName(NullableArrayTypeUtils.getRepeatedFieldName());
final var elementTypeCode = TypeCode.fromProtobufType(elementField.getType());
return fromProtoTypeToArray(descriptor, protoType, elementTypeCode, true);
} else {
return Record.fromFieldDescriptorsMap(isNullable, Record.toFieldDescriptorMap(messageDescriptor.getFields()));
}
}
}
throw new IllegalStateException("unable to translate protobuf descriptor to type");
}
/**
* Translates a repeated field in a protobuf descriptor to a {@link Array}.
* @param descriptor The protobuf descriptor.
* @param protoType The protobuf descriptor type.
* @return A {@link Array} object that corresponds to the protobuf {@link com.google.protobuf.Descriptors.Descriptor}.
*/
@Nonnull
private static Array fromProtoTypeToArray(@Nullable Descriptors.GenericDescriptor descriptor, @Nonnull Descriptors.FieldDescriptor.Type protoType, @Nonnull TypeCode typeCode, boolean isNullable) {
if (typeCode.isPrimitive()) {
final var primitiveType = primitiveType(typeCode, isNullable);
return new Array(isNullable, primitiveType);
} else if (typeCode == TypeCode.ENUM) {
final var enumDescriptor = (Descriptors.EnumDescriptor)Objects.requireNonNull(descriptor);
final var enumType = Enum.fromProtoValues(isNullable, enumDescriptor.getValues());
return new Array(isNullable, enumType);
} else {
if (isNullable) {
Descriptors.Descriptor wrappedDescriptor = ((Descriptors.Descriptor)Objects.requireNonNull(descriptor)).findFieldByName(NullableArrayTypeUtils.getRepeatedFieldName()).getMessageType();
Objects.requireNonNull(wrappedDescriptor);
return new Array(true, fromProtoType(wrappedDescriptor, Descriptors.FieldDescriptor.Type.MESSAGE, FieldDescriptorProto.Label.LABEL_OPTIONAL, true));
} else {
// case 2: any arbitrary sub message we don't understand
return new Array(false, fromProtoType(descriptor, protoType, FieldDescriptorProto.Label.LABEL_OPTIONAL, false));
}
}
}
/**
* For a given {@link com.google.protobuf.Descriptors.FieldDescriptor} descriptor, returns the type-specific
* descriptor if the field is a message or an enum, otherwise <code>null</code>.
*
* @param fieldDescriptor The descriptor.
* @return the type-specific descriptor for the field, otherwise <code>null</code>.
*/
@Nullable
private static Descriptors.GenericDescriptor getTypeSpecificDescriptor(@Nonnull final Descriptors.FieldDescriptor fieldDescriptor) {
switch (fieldDescriptor.getType()) {
case MESSAGE:
return fieldDescriptor.getMessageType();
case ENUM:
return fieldDescriptor.getEnumType();
default:
return null;
}
}
/**
* Find the maximum type of two types. The maximum type is the type that can describe all values adhering to both
* sides passed in. Some combinations are not defined.
* Primitive types are treated using the SQL-like promotion rules to form a promotion ladder meaning that
* <pre>
* {@code
* INT --> LONG --> FLOAT --> DOUBLE
* }
* </pre>
* can be promoted up (the values can be substituted without loss).
* <pre>
* Examples
* {@code
* int, int --> int
* int, float --> float
* int, string --> undefined
* record(int as a, int as b), record(int as a, int as b) --> record(int as a, int as b)
* record(int as a, int as b), record(int as c, int as d) --> record(int, int) (unnamed)
* record(int, int), record(float, float) --> record(float, float)
* record(int, float), record(float, int) --> record(float, float)
* record(int, array(float)), record(int, array(double)) --> record(int, array(double))
* record(int, string), record(float, int) --> undefined
* record(int), record(int, int) --> undefined
* }
* </pre>
*
* @param t1 one type
* @param t2 another type
* @return the maximum type of {@code t1} and type {@code t2} or {@code null} if the maximum type is not defined
*/
@Nullable
@SuppressWarnings("PMD.CompareObjectsWithEquals")
static Type maximumType(@Nonnull final Type t1, @Nonnull final Type t2) {
Verify.verify(!t1.isUnresolved());
Verify.verify(!t2.isUnresolved());
if (t1.isPrimitive() != t2.isPrimitive()) {
return null;
}
boolean isResultNullable = t1.isNullable() || t2.isNullable();
if (t1.isPrimitive()) {
if (t1.getTypeCode() == t2.getTypeCode()) {
return t1.withNullability(isResultNullable);
}
if (PromoteValue.resolvePromotionFunction(t1, t2) != null) {
return t2.withNullability(isResultNullable);
}
if (PromoteValue.isPromotionNeeded(t2, t1)) {
return t2.withNullability(isResultNullable);
}
throw new RecordCoreException("should not be here");
}
if (t1.getTypeCode() != t2.getTypeCode()) {
return null;
}
switch (t1.getTypeCode()) {
case RECORD:
final var t1Fields = ((Type.Record)t1).getFields();
final var t2Fields = ((Type.Record)t2).getFields();
if (t1Fields.size() != t2Fields.size()) {
return null;
}
final var resultFieldsBuilder = ImmutableList.<Type.Record.Field>builder();
for (int i = 0; i < t1Fields.size(); i++) {
final var t1Field = t1Fields.get(i);
final var t2Field = t2Fields.get(i);
final var resultFieldType = maximumType(t1Field.getFieldType(), t2Field.getFieldType());
if (resultFieldType == null) {
return null;
}
final Optional<String> resultFieldNameOptional =
t1Field.getFieldNameOptional().equals(t2Field.getFieldNameOptional())
? t1Field.getFieldNameOptional()
: Optional.empty();
resultFieldsBuilder.add(Record.Field.of(resultFieldType, resultFieldNameOptional));
}
return Type.Record.fromFields(isResultNullable, resultFieldsBuilder.build());
case ARRAY:
final var t1ElementType = Verify.verifyNotNull(((Type.Array)t1).getElementType());
final var t2ElementType = Verify.verifyNotNull(((Type.Array)t2).getElementType());
final var resultElementType = maximumType(t1ElementType, t2ElementType);
if (resultElementType == null) {
return null;
}
return new Type.Array(isResultNullable, resultElementType);
default:
throw new RecordCoreException("do not know how to handle type code");
}
}
/**
* All supported {@link Type}s.
*/
enum TypeCode {
UNKNOWN(null, null, true, false),
ANY(Object.class, null, false, false),
NULL(Void.class, null, true, false),
BOOLEAN(Boolean.class, FieldDescriptorProto.Type.TYPE_BOOL, true, false),
BYTES(ByteString.class, FieldDescriptorProto.Type.TYPE_BYTES, true, false),
DOUBLE(Double.class, FieldDescriptorProto.Type.TYPE_DOUBLE, true, true),
FLOAT(Float.class, FieldDescriptorProto.Type.TYPE_FLOAT, true, true),
INT(Integer.class, FieldDescriptorProto.Type.TYPE_INT32, true, true),
LONG(Long.class, FieldDescriptorProto.Type.TYPE_INT64, true, true),
STRING(String.class, FieldDescriptorProto.Type.TYPE_STRING, true, false),
ENUM(Enum.class, FieldDescriptorProto.Type.TYPE_ENUM, false, false),
RECORD(Message.class, null, false, false),
ARRAY(Array.class, null, false, false),
RELATION(null, null, false, false);
/**
* Java {@link Class} that corresponds to the {@link TypeCode}.
*/
@Nullable
private final Class<?> javaClass;
/**
* Protobuf {@link com.google.protobuf.DescriptorProtos.FieldDescriptorProto.Type} descriptor that corresponds
* to the {@link TypeCode}.
*/
@Nullable
private final FieldDescriptorProto.Type protoType;
/**
* flag to indicate whether a {@link TypeCode} is primitive or structured.
*/
private final boolean isPrimitive;
/**
* flag to indicate whether a {@link TypeCode} is numeric or not.
*/
private final boolean isNumeric;
/**
* Construct a new {@link TypeCode} instance.
* @param javaClass Java {@link Class} that corresponds to the {@link TypeCode}.
* @param protoType Protobuf {@link com.google.protobuf.DescriptorProtos.FieldDescriptorProto.Type} descriptor that corresponds
* @param isPrimitive <code>true</code> if a {@link TypeCode} is primitive, otherwise <code>false</code>.
* @param isNumeric <code>true</code> if a {@link TypeCode} is numeric, otherwise <code>false</code>.
*/
TypeCode(@Nullable final Class<?> javaClass,
@Nullable final FieldDescriptorProto.Type protoType,
final boolean isPrimitive,
final boolean isNumeric) {
this.javaClass = javaClass;
this.protoType = protoType;
this.isPrimitive = isPrimitive;
this.isNumeric = isNumeric;
}
/**
* Returns the corresponding Java {@link Class} of the {@link Type} instance.
*
* @return the corresponding Java {@link Class} of the {@link Type} instance.
*/
@Nullable
public Class<?> getJavaClass() {
return javaClass;
}
/**
* Returns the corresponding protobuf {@link com.google.protobuf.DescriptorProtos.FieldDescriptorProto.Type} of
* the {@link Type} instance.
*
* @return the corresponding protobuf {@link com.google.protobuf.DescriptorProtos.FieldDescriptorProto.Type} of
* the {@link Type} instance.
*/
@Nullable
public FieldDescriptorProto.Type getProtoType() {
return protoType;
}
/**
* Checks whether a {@link Type} is primitive or structured.
*
* @return <code>true</code> if the {@link Type} is primitive, otherwise <code>false</code>.
*/
public boolean isPrimitive() {
return isPrimitive;
}
/**
* Checks whether a {@link Type} is numeric.
*
* @return <code>true</code> if the {@link Type} is numeric, otherwise <code>false</code>.
*/
public boolean isNumeric() {
return isNumeric;
}
/**
* Computes a mapping from Java {@link Class} to corresponding {@link TypeCode} instance.
* @return a mapping from Java {@link Class} to corresponding {@link TypeCode} instance.
*/
@Nonnull
private static BiMap<Class<?>, TypeCode> computeClassToTypeCodeMap() {
final var builder = ImmutableBiMap.<Class<?>, TypeCode>builder();
for (final TypeCode typeCode : TypeCode.values()) {
if (typeCode.getJavaClass() != null) {
builder.put(typeCode.getJavaClass(), typeCode);
}
}
return builder.build();
}
/**
* Generates a {@link TypeCode} that corresponds to the given protobuf
* {@link com.google.protobuf.DescriptorProtos.FieldDescriptorProto.Type}.
* @param protobufType The protobuf type.
* @return A corresponding {@link TypeCode} instance.
*/
@Nonnull
public static TypeCode fromProtobufType(@Nonnull final Descriptors.FieldDescriptor.Type protobufType) {
switch (protobufType) {
case DOUBLE:
return TypeCode.DOUBLE;
case FLOAT:
return TypeCode.FLOAT;
case INT64:
case UINT64:
case FIXED64:
case SFIXED64:
case SINT64:
return TypeCode.LONG;
case INT32:
case FIXED32:
case UINT32:
case SFIXED32:
case SINT32:
return TypeCode.INT;
case BOOL:
return TypeCode.BOOLEAN;
case STRING:
return TypeCode.STRING;
case GROUP:
case ENUM:
return TypeCode.ENUM;
case MESSAGE:
return TypeCode.RECORD;
case BYTES:
return TypeCode.BYTES;
default:
throw new IllegalArgumentException("unknown protobuf type " + protobufType);
}
}
}
/**
* The null type is an unresolved type meaning that an entity returning a null type should resolve the
* type to a regular type as the runtime does not support a null-typed data producer. Note that a type can be
* nullable but that's not the same as to be null-typed. Only the constant {@code null} is actually of type null,
* however, that type is changed to an actual type during type resolution that then just happens to be nullable.
* It is correct to say that the null type (just as {@link None} type) are types that have no instances.
* It is still useful use this type for modelling purposes. Just as in Scala, the null-type is implicitly, a
* subtype of every other type in a sense that the substitution principle holds, e.g. {@code null} can be substituted
* for any value of type {@code int}, or {@code string}, etc...
*/
class Null implements Type {
@Override
public TypeCode getTypeCode() {
return TypeCode.NULL;
}
@Override
public boolean isNullable() {
return true;
}
@Nonnull
@Override
public Type withNullability(final boolean newIsNullable) {
Verify.verify(newIsNullable);
return this;
}
@Override
public boolean isUnresolved() {
return true;
}
@Override
public void addProtoField(@Nonnull final TypeRepository.Builder typeRepositoryBuilder, @Nonnull final DescriptorProto.Builder descriptorBuilder, final int fieldNumber, @Nonnull final String fieldName, @Nonnull final Optional<String> typeNameOptional, @Nonnull final FieldDescriptorProto.Label label) {
throw new RecordCoreException("should not be called");
}
@Override
public String toString() {
return "null";
}
}
/**
* The none type is an unresolved type meaning that an entity returning a none type should resolve the
* type to a regular type as the runtime does not support a none-typed data producer. Only the empty array constant
* is actually of type {@code none}, however, that type is changed to an actual type during type resolution (to an
* array of some regular type).
* It is correct to say that the none type (just as {@link Null} type) are types that have no instances.
* It is still useful use this type for modelling purposes. Just as in Scala, the none-type is implicitly, a
* subtype of every other type in a sense that the substitution principle holds, e.g. {@code none} can be substituted
* for any value of an array type.
*/
class None implements Type {
@Override
public TypeCode getTypeCode() {
return TypeCode.ARRAY;
}
@Override
public boolean isNullable() {
return false;
}
@Nonnull
@Override
public Type withNullability(final boolean newIsNullable) {
Verify.verify(!newIsNullable);
return this;
}
@Override
public boolean isUnresolved() {
return true;
}
@Override
public void addProtoField(@Nonnull final TypeRepository.Builder typeRepositoryBuilder, @Nonnull final DescriptorProto.Builder descriptorBuilder, final int fieldNumber, @Nonnull final String fieldName, @Nonnull final Optional<String> typeNameOptional, @Nonnull final FieldDescriptorProto.Label label) {
throw new RecordCoreException("should not be called");
}
@Override
public String toString() {
return "none";
}
}
/**
* Special {@link Type} that is undefined.
*/
class Any implements Type {
/**
* Memoized hash function.
*/
@Nonnull
private final Supplier<Integer> hashCodeSupplier = Suppliers.memoize(this::computeHashCode);
private int computeHashCode() {
return Objects.hash(getTypeCode().name().hashCode(), isNullable());
}
/**
* {@inheritDoc}
*/
@Override
public TypeCode getTypeCode() {
return TypeCode.ANY;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isNullable() {
return true;
}
@Nonnull
@Override
public Any withNullability(final boolean newIsNullable) {
Verify.verify(newIsNullable);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public void addProtoField(@Nonnull final TypeRepository.Builder typeRepositoryBuilder,
@Nonnull final DescriptorProto.Builder descriptorBuilder,
final int fieldNumber,
@Nonnull final String fieldName,
@Nonnull final Optional<String> typeNameOptional,
@Nonnull final FieldDescriptorProto.Label label) {
throw new UnsupportedOperationException("type any cannot be represented in protobuf");
}
@Override
public int hashCode() {
return hashCodeSupplier.get();
}
@Override
public boolean equals(final Object obj) {
if (obj == null) {
return false;
}
if (this == obj) {
return true;
}
if (getClass() != obj.getClass()) {
return false;
}
final var otherType = (Type)obj;
return getTypeCode() == otherType.getTypeCode() && isNullable() == otherType.isNullable();
}
@Override
public String toString() {
return getTypeCode().toString();
}
}
/**
* An enumeration type.
*/
class Enum implements Type {
final boolean isNullable;
@Nullable
final List<EnumValue> enumValues;
@Nullable
final String name;
/**
* Memoized hash function.
*/
@Nonnull
private final Supplier<Integer> hashFunctionSupplier = Suppliers.memoize(this::computeHashCode);
public Enum(final boolean isNullable,
@Nullable final List<EnumValue> enumValues) {
this(isNullable, enumValues, null);
}
public Enum(final boolean isNullable,
@Nullable final List<EnumValue> enumValues,
@Nullable final String name) {
this.isNullable = isNullable;
this.enumValues = enumValues;
this.name = name;
}
@Override
public TypeCode getTypeCode() {
return TypeCode.ENUM;
}
/**
* Checks whether the {@link Record} type instance is erased or not.
* @return <code>true</code> if the {@link Record} type is erased, other <code>false</code>.
*/
boolean isErased() {
return enumValues == null;
}
@Nonnull
public List<EnumValue> getEnumValues() {
return Objects.requireNonNull(enumValues);
}
@Override
public boolean isNullable() {
return isNullable;
}
@Nonnull
@Override
public Enum withNullability(final boolean newIsNullable) {
return new Enum(newIsNullable, enumValues, name);
}
@Nullable
public String getName() {
return name;
}
@Override
public void defineProtoType(@Nonnull final TypeRepository.Builder typeRepositoryBuilder) {
Verify.verify(!isErased());
final var typeName = name == null ? ProtoUtils.uniqueTypeName() : name;
final var enumDescriptorProtoBuilder = DescriptorProtos.EnumDescriptorProto.newBuilder();
enumDescriptorProtoBuilder.setName(typeName);
for (final var enumValue : Objects.requireNonNull(enumValues)) {
enumDescriptorProtoBuilder.addValue(DescriptorProtos.EnumValueDescriptorProto.newBuilder()
.setName(enumValue.getName())
.setNumber(enumValue.getNumber()));
}
typeRepositoryBuilder.addEnumType(enumDescriptorProtoBuilder.build());
typeRepositoryBuilder.registerTypeToTypeNameMapping(this, typeName);
}
@Override
public void addProtoField(@Nonnull final TypeRepository.Builder typeRepositoryBuilder,
@Nonnull final DescriptorProto.Builder descriptorBuilder,
final int fieldNumber,
@Nonnull final String fieldName,
@Nonnull final Optional<String> typeNameOptional,
@Nonnull final FieldDescriptorProto.Label label) {
final var protoType = Objects.requireNonNull(getTypeCode().getProtoType());
FieldDescriptorProto.Builder builder = FieldDescriptorProto.newBuilder()
.setNumber(fieldNumber)
.setName(fieldName)
.setType(protoType)
.setLabel(label);
typeNameOptional.ifPresent(builder::setTypeName);
descriptorBuilder.addField(builder);
}
@Nonnull
@Override
public String describe(@Nonnull final Formatter formatter) {
return toString();
}
@Override
public boolean equals(final Object obj) {
if (obj == null) {
return false;
}
if (this == obj) {
return true;
}
if (getClass() != obj.getClass()) {
return false;
}
final var otherType = (Enum)obj;
return getTypeCode() == otherType.getTypeCode() && isNullable() == otherType.isNullable()
&& Objects.equals(enumValues, otherType.enumValues);
}
private int computeHashCode() {
return Objects.hash(isNullable, enumValues);
}
@Override
public int hashCode() {
return hashFunctionSupplier.get();
}
@Override
public String toString() {
if (isErased()) {
return getTypeCode().toString();
}
return getTypeCode() + "<" +
Objects.requireNonNull(enumValues)
.stream()
.map(Object::toString)
.collect(Collectors.joining(", ")) + ">";
}
private static Enum fromProtoValues(boolean isNullable, @Nonnull List<Descriptors.EnumValueDescriptor> values) {
return new Enum(isNullable, enumValuesFromProto(values), null);
}
public static List<EnumValue> enumValuesFromProto(@Nonnull final List<Descriptors.EnumValueDescriptor> enumValueDescriptors) {
return enumValueDescriptors
.stream()
.map(enumValueDescriptor -> new EnumValue(enumValueDescriptor.getName(), enumValueDescriptor.getNumber()))
.collect(ImmutableList.toImmutableList());
}
/**
* A member value of an enumeration.
*/
public static class EnumValue {
@Nonnull
final String name;
final int number;
public EnumValue(@Nonnull final String name, final int number) {
this.name = name;
this.number = number;
}
@Nonnull
public String getName() {
return name;
}
public int getNumber() {
return number;
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {