-
Notifications
You must be signed in to change notification settings - Fork 409
Expand file tree
/
Copy pathjava.py
More file actions
1634 lines (1450 loc) · 63.1 KB
/
java.py
File metadata and controls
1634 lines (1450 loc) · 63.1 KB
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
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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.
"""Java code generator."""
from pathlib import Path
from typing import Dict, List, Optional, Set, Tuple, Union as TypingUnion
from fory_compiler.generators.base import BaseGenerator, GeneratedFile
from fory_compiler.frontend.utils import parse_idl_file
from fory_compiler.ir.ast import (
Message,
Enum,
Union,
Field,
FieldType,
PrimitiveType,
NamedType,
ListType,
MapType,
Schema,
)
from fory_compiler.ir.types import PrimitiveKind
class JavaGenerator(BaseGenerator):
"""Generates Java POJOs with Fory annotations."""
language_name = "java"
file_extension = ".java"
def get_java_package(self) -> Optional[str]:
"""Get the Java package name.
Priority:
1. Command-line override (options.package_override)
2. java_package option from FDL file
3. FDL package declaration
"""
if self.options.package_override:
return self.options.package_override
java_package = self.schema.get_option("java_package")
if java_package:
return java_package
return self.schema.package
def get_registration_class_name(self) -> str:
"""Get the generated registration class name."""
java_package = self.get_java_package()
if java_package:
parts = java_package.split(".")
return self.to_pascal_case(parts[-1]) + "ForyRegistration"
return "ForyRegistration"
def get_java_outer_classname(self) -> Optional[str]:
"""Get the Java outer classname if specified.
When set, all types are generated as inner classes of this outer class
in a single file (unless java_multiple_files is true).
"""
return self.schema.get_option("java_outer_classname")
def get_java_multiple_files(self) -> bool:
"""Check if java_multiple_files option is set to true.
When true, each top-level type gets its own file, even if
java_outer_classname is set.
"""
value = self.schema.get_option("java_multiple_files")
return value is True
def is_imported_type(self, type_def: object) -> bool:
"""Return True if a type definition comes from an imported IDL file."""
if not self.schema.source_file:
return False
location = getattr(type_def, "location", None)
if location is None or not location.file:
return False
try:
return (
Path(location.file).resolve() != Path(self.schema.source_file).resolve()
)
except Exception:
return location.file != self.schema.source_file
def split_imported_types(
self, items: List[object]
) -> Tuple[List[object], List[object]]:
imported: List[object] = []
local: List[object] = []
for item in items:
if self.is_imported_type(item):
imported.append(item)
else:
local.append(item)
return imported, local
def _normalize_import_path(self, path_str: str) -> str:
if not path_str:
return path_str
try:
return str(Path(path_str).resolve())
except Exception:
return path_str
def _load_schema(self, file_path: str) -> Optional[Schema]:
if not file_path:
return None
if not hasattr(self, "_schema_cache"):
self._schema_cache = {}
cache: Dict[Path, Schema] = self._schema_cache
path = Path(file_path).resolve()
if path in cache:
return cache[path]
try:
schema = parse_idl_file(path)
except Exception:
return None
cache[path] = schema
return schema
def _java_package_for_schema(self, schema: Schema) -> Optional[str]:
java_package = schema.get_option("java_package")
if java_package:
return java_package
return schema.package
def _registration_class_name_for_schema(self, schema: Schema) -> str:
java_package = self._java_package_for_schema(schema)
if java_package:
parts = java_package.split(".")
return self.to_pascal_case(parts[-1]) + "ForyRegistration"
return "ForyRegistration"
def _java_package_for_type(self, type_def: object) -> Optional[str]:
location = getattr(type_def, "location", None)
file_path = getattr(location, "file", None) if location else None
schema = self._load_schema(file_path)
if schema is None:
return None
return self._java_package_for_schema(schema)
def _collect_imported_packages(self) -> List[Tuple[str, str]]:
packages: Dict[str, str] = {}
for type_def in self.schema.enums + self.schema.unions + self.schema.messages:
if not self.is_imported_type(type_def):
continue
java_package = self._java_package_for_type(type_def)
if not java_package:
continue
if java_package in packages:
continue
schema = self._load_schema(
getattr(getattr(type_def, "location", None), "file", None)
)
if schema is None:
continue
packages[java_package] = self._registration_class_name_for_schema(schema)
ordered: List[Tuple[str, str]] = []
used: Set[str] = set()
if self.schema.source_file:
base_dir = Path(self.schema.source_file).resolve().parent
for imp in self.schema.imports:
candidate = self._normalize_import_path(
str((base_dir / imp.path).resolve())
)
schema = self._load_schema(candidate)
if schema is None:
continue
java_package = self._java_package_for_schema(schema)
if not java_package or java_package in used:
continue
reg_class = self._registration_class_name_for_schema(schema)
ordered.append((java_package, reg_class))
used.add(java_package)
for pkg, reg in sorted(packages.items()):
if pkg in used:
continue
ordered.append((pkg, reg))
return ordered
def generate_bytes_methods(self, class_name: str) -> List[str]:
reg_class = self.get_registration_class_name()
lines = []
lines.append("public byte[] toBytes() {")
lines.append(f" return {reg_class}.getFory().serialize(this);")
lines.append("}")
lines.append("")
lines.append(f"public static {class_name} fromBytes(byte[] bytes) {{")
lines.append(
f" return {reg_class}.getFory().deserialize(bytes, {class_name}.class);"
)
lines.append("}")
lines.append("")
return lines
# Mapping from FDL primitive types to Java types
PRIMITIVE_MAP = {
PrimitiveKind.BOOL: "boolean",
PrimitiveKind.INT8: "byte",
PrimitiveKind.INT16: "short",
PrimitiveKind.INT32: "int",
PrimitiveKind.VARINT32: "int",
PrimitiveKind.INT64: "long",
PrimitiveKind.VARINT64: "long",
PrimitiveKind.TAGGED_INT64: "long",
PrimitiveKind.UINT8: "byte",
PrimitiveKind.UINT16: "short",
PrimitiveKind.UINT32: "int",
PrimitiveKind.VAR_UINT32: "int",
PrimitiveKind.UINT64: "long",
PrimitiveKind.VAR_UINT64: "long",
PrimitiveKind.TAGGED_UINT64: "long",
PrimitiveKind.FLOAT16: "float",
PrimitiveKind.FLOAT32: "float",
PrimitiveKind.FLOAT64: "double",
PrimitiveKind.STRING: "String",
PrimitiveKind.BYTES: "byte[]",
PrimitiveKind.DATE: "java.time.LocalDate",
PrimitiveKind.TIMESTAMP: "java.time.Instant",
PrimitiveKind.DURATION: "java.time.Duration",
PrimitiveKind.DECIMAL: "java.math.BigDecimal",
PrimitiveKind.ANY: "Object",
}
# Boxed versions for nullable primitives
BOXED_MAP = {
PrimitiveKind.BOOL: "Boolean",
PrimitiveKind.INT8: "Byte",
PrimitiveKind.INT16: "Short",
PrimitiveKind.INT32: "Integer",
PrimitiveKind.VARINT32: "Integer",
PrimitiveKind.INT64: "Long",
PrimitiveKind.VARINT64: "Long",
PrimitiveKind.TAGGED_INT64: "Long",
PrimitiveKind.UINT8: "Byte",
PrimitiveKind.UINT16: "Short",
PrimitiveKind.UINT32: "Integer",
PrimitiveKind.VAR_UINT32: "Integer",
PrimitiveKind.UINT64: "Long",
PrimitiveKind.VAR_UINT64: "Long",
PrimitiveKind.TAGGED_UINT64: "Long",
PrimitiveKind.FLOAT16: "Float",
PrimitiveKind.FLOAT32: "Float",
PrimitiveKind.FLOAT64: "Double",
PrimitiveKind.ANY: "Object",
}
# Primitive array types for repeated numeric fields
PRIMITIVE_ARRAY_MAP = {
PrimitiveKind.BOOL: "boolean[]",
PrimitiveKind.INT8: "byte[]",
PrimitiveKind.INT16: "short[]",
PrimitiveKind.INT32: "int[]",
PrimitiveKind.VARINT32: "int[]",
PrimitiveKind.INT64: "long[]",
PrimitiveKind.VARINT64: "long[]",
PrimitiveKind.TAGGED_INT64: "long[]",
PrimitiveKind.UINT8: "byte[]",
PrimitiveKind.UINT16: "short[]",
PrimitiveKind.UINT32: "int[]",
PrimitiveKind.VAR_UINT32: "int[]",
PrimitiveKind.UINT64: "long[]",
PrimitiveKind.VAR_UINT64: "long[]",
PrimitiveKind.TAGGED_UINT64: "long[]",
PrimitiveKind.FLOAT16: "float[]",
PrimitiveKind.FLOAT32: "float[]",
PrimitiveKind.FLOAT64: "double[]",
}
# Primitive list types for repeated integer fields (default mode)
PRIMITIVE_LIST_MAP = {
PrimitiveKind.INT8: "Int8List",
PrimitiveKind.INT16: "Int16List",
PrimitiveKind.INT32: "Int32List",
PrimitiveKind.VARINT32: "Int32List",
PrimitiveKind.INT64: "Int64List",
PrimitiveKind.VARINT64: "Int64List",
PrimitiveKind.TAGGED_INT64: "Int64List",
PrimitiveKind.UINT8: "Uint8List",
PrimitiveKind.UINT16: "Uint16List",
PrimitiveKind.UINT32: "Uint32List",
PrimitiveKind.VAR_UINT32: "Uint32List",
PrimitiveKind.UINT64: "Uint64List",
PrimitiveKind.VAR_UINT64: "Uint64List",
PrimitiveKind.TAGGED_UINT64: "Uint64List",
}
def generate(self) -> List[GeneratedFile]:
"""Generate Java files for the schema.
Generation mode depends on options:
- java_multiple_files = true: Separate file per type (default behavior)
- java_outer_classname set + java_multiple_files = false: Single file with outer class
- Neither set: Separate file per type
"""
files = []
outer_classname = self.get_java_outer_classname()
multiple_files = self.get_java_multiple_files()
if outer_classname and not multiple_files:
# Generate all types in a single outer class file
files.append(self.generate_outer_class_file(outer_classname))
# Generate registration helper (with outer class prefix)
files.append(self.generate_registration_file(outer_classname))
else:
# Generate separate files for each type
# Generate enum files (top-level only, nested enums go inside message files)
for enum in self.schema.enums:
if self.is_imported_type(enum):
continue
files.append(self.generate_enum_file(enum))
# Generate union files (top-level only, nested unions go inside message files)
for union in self.schema.unions:
if self.is_imported_type(union):
continue
files.append(self.generate_union_file(union))
# Generate message files (includes nested types as inner classes)
for message in self.schema.messages:
if self.is_imported_type(message):
continue
files.append(self.generate_message_file(message))
# Generate registration helper
files.append(self.generate_registration_file())
return files
def get_java_package_path(self) -> str:
"""Get the Java package as a path."""
java_package = self.get_java_package()
if java_package:
return java_package.replace(".", "/")
return ""
def generate_enum_file(self, enum: Enum) -> GeneratedFile:
"""Generate a Java enum file."""
lines = []
java_package = self.get_java_package()
# License header
lines.append(self.get_license_header())
lines.append("")
# Package
if java_package:
lines.append(f"package {java_package};")
lines.append("")
# Enum declaration
lines.append(f"public enum {enum.name} {{")
# Enum values (strip prefix for scoped enums)
for i, value in enumerate(enum.values):
comma = "," if i < len(enum.values) - 1 else ";"
stripped_name = self.strip_enum_prefix(enum.name, value.name)
lines.append(f" {stripped_name}{comma}")
lines.append("}")
lines.append("")
# Build file path
path = self.get_java_package_path()
if path:
path = f"{path}/{enum.name}.java"
else:
path = f"{enum.name}.java"
return GeneratedFile(path=path, content="\n".join(lines))
def generate_union_file(self, union: Union) -> GeneratedFile:
"""Generate a Java union class file."""
lines = []
imports: Set[str] = set()
java_package = self.get_java_package()
self.collect_union_imports(union, imports)
lines.append(self.get_license_header())
lines.append("")
if java_package:
lines.append(f"package {java_package};")
lines.append("")
if imports:
for imp in sorted(imports):
lines.append(f"import {imp};")
lines.append("")
for line in self.generate_union_class(union):
lines.append(line)
path = self.get_java_package_path()
if path:
path = f"{path}/{union.name}.java"
else:
path = f"{union.name}.java"
return GeneratedFile(path=path, content="\n".join(lines))
def generate_message_file(self, message: Message) -> GeneratedFile:
"""Generate a Java class file for a message."""
lines = []
imports: Set[str] = set()
java_package = self.get_java_package()
# Collect imports (including from nested types)
self.collect_message_imports(message, imports)
# License header
lines.append(self.get_license_header())
lines.append("")
# Package
if java_package:
lines.append(f"package {java_package};")
lines.append("")
# Imports
if imports:
for imp in sorted(imports):
lines.append(f"import {imp};")
lines.append("")
# Class declaration with semantic line wrapping
class_lines = self.format_long_line("public class ", message.name, " {")
lines.extend(class_lines)
# Generate nested enums as static inner classes
for nested_enum in message.nested_enums:
for line in self.generate_nested_enum(nested_enum):
lines.append(f" {line}")
# Generate nested unions as static inner classes
for nested_union in message.nested_unions:
for line in self.generate_union_class(
nested_union, indent=0, nested=True, parent_stack=[message]
):
lines.append(f" {line}")
# Generate nested messages as static inner classes
for nested_msg in message.nested_messages:
for line in self.generate_nested_message(
nested_msg, indent=1, parent_stack=[message]
):
lines.append(f" {line}")
# Fields
for field in message.fields:
field_lines = self.generate_field(field)
for line in field_lines:
lines.append(f" {line}")
lines.append("")
# Default constructor
lines.append(f" public {message.name}() {{")
lines.append(" }")
lines.append("")
# Getters and setters
for field in message.fields:
getter_setter = self.generate_getter_setter(field)
for line in getter_setter:
lines.append(f" {line}")
# toBytes/fromBytes
for line in self.generate_bytes_methods(message.name):
lines.append(f" {line}")
# equals method
for line in self.generate_equals_method(message):
lines.append(f" {line}")
# hashCode method
for line in self.generate_hashcode_method(message):
lines.append(f" {line}")
lines.append("}")
lines.append("")
# Build file path
path = self.get_java_package_path()
if path:
path = f"{path}/{message.name}.java"
else:
path = f"{message.name}.java"
return GeneratedFile(path=path, content="\n".join(lines))
def generate_outer_class_file(self, outer_classname: str) -> GeneratedFile:
"""Generate a single Java file with all types as inner classes of an outer class.
This is used when java_outer_classname option is set.
"""
lines = []
imports: Set[str] = set()
java_package = self.get_java_package()
# Collect imports from all types
for message in self.schema.messages:
self.collect_message_imports(message, imports)
for enum in self.schema.enums:
pass # Enums don't need special imports
for union in self.schema.unions:
self.collect_union_imports(union, imports)
# License header
lines.append(self.get_license_header())
lines.append("")
# Package
if java_package:
lines.append(f"package {java_package};")
lines.append("")
# Imports
if imports:
for imp in sorted(imports):
lines.append(f"import {imp};")
lines.append("")
# Outer class declaration
lines.append(f"public final class {outer_classname} {{")
lines.append("")
lines.append(f" private {outer_classname}() {{")
lines.append(" // Prevent instantiation")
lines.append(" }")
lines.append("")
# Generate all top-level enums as static inner classes
for enum in self.schema.enums:
if self.is_imported_type(enum):
continue
for line in self.generate_nested_enum(enum):
lines.append(f" {line}")
# Generate all top-level unions as static inner classes
for union in self.schema.unions:
if self.is_imported_type(union):
continue
for line in self.generate_union_class(union, indent=0, nested=True):
lines.append(f" {line}")
# Generate all top-level messages as static inner classes
for message in self.schema.messages:
if self.is_imported_type(message):
continue
for line in self.generate_nested_message(message, indent=1):
lines.append(f" {line}")
lines.append("}")
lines.append("")
# Build file path
path = self.get_java_package_path()
if path:
path = f"{path}/{outer_classname}.java"
else:
path = f"{outer_classname}.java"
return GeneratedFile(path=path, content="\n".join(lines))
def collect_message_imports(self, message: Message, imports: Set[str]):
"""Collect imports for a message and all its nested types recursively."""
for field in message.fields:
self.collect_field_imports(field, imports)
# Add imports for equals/hashCode
imports.add("java.util.Objects")
if self.has_array_field_recursive(message):
imports.add("java.util.Arrays")
# Collect imports from nested messages
for nested_msg in message.nested_messages:
self.collect_message_imports(nested_msg, imports)
for nested_union in message.nested_unions:
self.collect_union_imports(nested_union, imports)
def collect_union_imports(self, union: Union, imports: Set[str]):
"""Collect imports for a union and its cases."""
imports.add("org.apache.fory.type.union.Union")
imports.add("org.apache.fory.type.Types")
imports.add("java.util.Objects")
for field in union.fields:
self.collect_type_imports(
field.field_type,
imports,
field.element_optional,
field.element_ref,
field,
)
def has_array_field_recursive(self, message: Message) -> bool:
"""Check if message or any nested message has array fields."""
if self.has_array_field(message):
return True
for nested_msg in message.nested_messages:
if self.has_array_field_recursive(nested_msg):
return True
return False
def generate_nested_enum(self, enum: Enum) -> List[str]:
"""Generate a nested enum as a static inner class."""
lines = []
lines.append(f"public static enum {enum.name} {{")
# Enum values (strip prefix for scoped enums)
for i, value in enumerate(enum.values):
comma = "," if i < len(enum.values) - 1 else ";"
stripped_name = self.strip_enum_prefix(enum.name, value.name)
lines.append(f" {stripped_name}{comma}")
lines.append("}")
lines.append("")
return lines
def generate_union_class(
self,
union: Union,
indent: int = 0,
nested: bool = False,
parent_stack: Optional[List[Message]] = None,
) -> List[str]:
"""Generate a Java union class."""
lines: List[str] = []
ind = " " * indent
class_prefix = "public static final class" if nested else "public final class"
case_enum = f"{union.name}Case"
lines.append(f"{ind}{class_prefix} {union.name} extends Union {{")
lines.append(f"{ind} public enum {case_enum} {{")
for i, field in enumerate(union.fields):
comma = "," if i < len(union.fields) - 1 else ";"
case_name = self.to_upper_snake_case(field.name)
lines.append(f"{ind} {case_name}({field.number}){comma}")
lines.append(f"{ind} public final int id;")
lines.append(f"{ind} {case_enum}(int id) {{")
lines.append(f"{ind} this.id = id;")
lines.append(f"{ind} }}")
lines.append(f"{ind} }}")
lines.append("")
lines.append(f"{ind} private static int resolveTypeId(int caseId) {{")
lines.append(f"{ind} switch (caseId) {{")
for field in union.fields:
type_id_expr = self.get_union_case_type_id_expr(field, parent_stack)
lines.append(f"{ind} case {field.number}:")
lines.append(f"{ind} return {type_id_expr};")
lines.append(f"{ind} default:")
lines.append(
f'{ind} throw new IllegalStateException("Unknown " + '
f'"{union.name} case id: " + caseId);'
)
lines.append(f"{ind} }}")
lines.append(f"{ind} }}")
lines.append("")
lines.append(f"{ind} private {union.name}(int caseId, Object v) {{")
lines.append(f"{ind} super(caseId, v, resolveTypeId(caseId));")
lines.append(f"{ind} if (v == null) {{")
lines.append(f"{ind} throw new NullPointerException();")
lines.append(f"{ind} }}")
lines.append(f"{ind} get{union.name}Case();")
lines.append(f"{ind} }}")
lines.append("")
for field in union.fields:
case_name = self.to_pascal_case(field.name)
case_enum_name = self.to_upper_snake_case(field.name)
case_type = self.get_union_case_type(field)
lines.append(
f"{ind} public static {union.name} of{case_name}({case_type} v) {{"
)
lines.append(
f"{ind} return new {union.name}({case_enum}.{case_enum_name}.id, v);"
)
lines.append(f"{ind} }}")
lines.append("")
lines.append(f"{ind} public {case_enum} get{union.name}Case() {{")
lines.append(f"{ind} switch (index) {{")
for field in union.fields:
case_enum_name = self.to_upper_snake_case(field.name)
lines.append(f"{ind} case {field.number}:")
lines.append(f"{ind} return {case_enum}.{case_enum_name};")
lines.append(f"{ind} default:")
lines.append(
f'{ind} throw new IllegalStateException("Unknown " + '
f'"{union.name} case id: " + index);'
)
lines.append(f"{ind} }}")
lines.append(f"{ind} }}")
lines.append("")
lines.append(f"{ind} public int get{union.name}CaseId() {{")
lines.append(f"{ind} return index;")
lines.append(f"{ind} }}")
lines.append("")
for field in union.fields:
case_name = self.to_pascal_case(field.name)
case_enum_name = self.to_upper_snake_case(field.name)
case_type = self.get_union_case_type(field)
cast_type = self.get_union_case_cast_type(field)
wrap_array_type: Optional[str] = None
wrap_list_type: Optional[str] = None
if (
isinstance(field.field_type, ListType)
and isinstance(field.field_type.element_type, PrimitiveType)
and field.field_type.element_type.kind in self.PRIMITIVE_LIST_MAP
and not self.java_array(field)
):
kind = field.field_type.element_type.kind
wrap_list_type = self.PRIMITIVE_LIST_MAP[kind]
wrap_array_type = self.PRIMITIVE_ARRAY_MAP[kind]
lines.append(f"{ind} public boolean has{case_name}() {{")
lines.append(
f"{ind} return index == {case_enum}.{case_enum_name}.id;"
)
lines.append(f"{ind} }}")
lines.append("")
lines.append(f"{ind} public {case_type} get{case_name}() {{")
lines.append(
f"{ind} if (index != {case_enum}.{case_enum_name}.id) {{"
)
lines.append(
f'{ind} throw new IllegalStateException("{union.name} is not {case_enum_name}");'
)
lines.append(f"{ind} }}")
if wrap_array_type and wrap_list_type:
lines.append(f"{ind} if (value instanceof {wrap_array_type}) {{")
lines.append(
f"{ind} value = new {wrap_list_type}(({wrap_array_type}) value);"
)
lines.append(f"{ind} }}")
lines.append(f"{ind} return ({cast_type}) value;")
lines.append(f"{ind} }}")
lines.append("")
lines.append(f"{ind} public void set{case_name}({case_type} v) {{")
if not self.is_java_primitive_type(case_type):
lines.append(f"{ind} if (v == null) {{")
lines.append(f"{ind} throw new NullPointerException();")
lines.append(f"{ind} }}")
lines.append(f"{ind} this.index = {case_enum}.{case_enum_name}.id;")
lines.append(f"{ind} this.value = v;")
type_id_expr = self.get_union_case_type_id_expr(field, parent_stack)
lines.append(f"{ind} this.typeId = {type_id_expr};")
lines.append(f"{ind} }}")
lines.append("")
lines.append(f"{ind} @Override")
lines.append(f"{ind} public boolean equals(Object o) {{")
lines.append(f"{ind} if (this == o) {{")
lines.append(f"{ind} return true;")
lines.append(f"{ind} }}")
lines.append(f"{ind} if (!(o instanceof {union.name})) {{")
lines.append(f"{ind} return false;")
lines.append(f"{ind} }}")
lines.append(f"{ind} {union.name} that = ({union.name}) o;")
lines.append(
f"{ind} return index == that.index && Objects.equals(value, that.value);"
)
lines.append(f"{ind} }}")
lines.append("")
lines.append(f"{ind} @Override")
lines.append(f"{ind} public int hashCode() {{")
lines.append(f"{ind} return Objects.hash(index, value);")
lines.append(f"{ind} }}")
lines.append("")
for line in self.generate_bytes_methods(union.name):
lines.append(f"{ind} {line}")
lines.append(f"{ind}}}")
lines.append("")
return lines
def get_union_case_type(self, field: Field) -> str:
"""Return the Java type for a union case."""
return self.generate_type(
field.field_type,
False,
field.element_optional,
field.element_ref,
field,
)
def get_union_case_cast_type(self, field: Field) -> str:
"""Return the Java cast type for a union case value."""
if isinstance(field.field_type, PrimitiveType):
boxed = self.BOXED_MAP.get(field.field_type.kind)
if boxed is not None:
return boxed
return self.PRIMITIVE_MAP[field.field_type.kind]
return self.get_union_case_type(field)
def get_union_case_type_id_expr(
self, field: Field, parent_stack: Optional[List[Message]]
) -> str:
"""Return the Java expression for a union case value type id."""
if isinstance(field.field_type, PrimitiveType):
kind = field.field_type.kind
primitive_type_ids = {
PrimitiveKind.BOOL: "Types.BOOL",
PrimitiveKind.INT8: "Types.INT8",
PrimitiveKind.INT16: "Types.INT16",
PrimitiveKind.INT32: "Types.INT32",
PrimitiveKind.VARINT32: "Types.VARINT32",
PrimitiveKind.INT64: "Types.INT64",
PrimitiveKind.VARINT64: "Types.VARINT64",
PrimitiveKind.TAGGED_INT64: "Types.TAGGED_INT64",
PrimitiveKind.UINT8: "Types.UINT8",
PrimitiveKind.UINT16: "Types.UINT16",
PrimitiveKind.UINT32: "Types.UINT32",
PrimitiveKind.VAR_UINT32: "Types.VAR_UINT32",
PrimitiveKind.UINT64: "Types.UINT64",
PrimitiveKind.VAR_UINT64: "Types.VAR_UINT64",
PrimitiveKind.TAGGED_UINT64: "Types.TAGGED_UINT64",
PrimitiveKind.FLOAT16: "Types.FLOAT16",
PrimitiveKind.FLOAT32: "Types.FLOAT32",
PrimitiveKind.FLOAT64: "Types.FLOAT64",
PrimitiveKind.STRING: "Types.STRING",
PrimitiveKind.BYTES: "Types.BINARY",
PrimitiveKind.DATE: "Types.DATE",
PrimitiveKind.TIMESTAMP: "Types.TIMESTAMP",
PrimitiveKind.ANY: "Types.UNKNOWN",
}
return primitive_type_ids.get(kind, "Types.UNKNOWN")
if isinstance(field.field_type, ListType):
if (
isinstance(field.field_type.element_type, PrimitiveType)
and not field.element_optional
and not field.element_ref
):
kind = field.field_type.element_type.kind
array_type_ids = {
PrimitiveKind.BOOL: "Types.BOOL_ARRAY",
PrimitiveKind.INT8: "Types.INT8_ARRAY",
PrimitiveKind.INT16: "Types.INT16_ARRAY",
PrimitiveKind.INT32: "Types.INT32_ARRAY",
PrimitiveKind.VARINT32: "Types.INT32_ARRAY",
PrimitiveKind.INT64: "Types.INT64_ARRAY",
PrimitiveKind.VARINT64: "Types.INT64_ARRAY",
PrimitiveKind.TAGGED_INT64: "Types.INT64_ARRAY",
PrimitiveKind.UINT8: "Types.UINT8_ARRAY",
PrimitiveKind.UINT16: "Types.UINT16_ARRAY",
PrimitiveKind.UINT32: "Types.UINT32_ARRAY",
PrimitiveKind.VAR_UINT32: "Types.UINT32_ARRAY",
PrimitiveKind.UINT64: "Types.UINT64_ARRAY",
PrimitiveKind.VAR_UINT64: "Types.UINT64_ARRAY",
PrimitiveKind.TAGGED_UINT64: "Types.UINT64_ARRAY",
PrimitiveKind.FLOAT16: "Types.FLOAT16_ARRAY",
PrimitiveKind.FLOAT32: "Types.FLOAT32_ARRAY",
PrimitiveKind.FLOAT64: "Types.FLOAT64_ARRAY",
}
if kind in array_type_ids:
return array_type_ids[kind]
return "Types.LIST"
if isinstance(field.field_type, MapType):
return "Types.MAP"
if isinstance(field.field_type, NamedType):
type_def = self.resolve_named_type(field.field_type.name, parent_stack)
if isinstance(type_def, Enum):
if type_def.type_id is None:
return "Types.NAMED_ENUM"
return f"({type_def.type_id} << 8) | Types.ENUM"
if isinstance(type_def, Union):
if type_def.type_id is None:
return "Types.NAMED_UNION"
return f"({type_def.type_id} << 8) | Types.UNION"
if isinstance(type_def, Message):
if type_def.type_id is None:
return "Types.NAMED_STRUCT"
return f"({type_def.type_id} << 8) | Types.STRUCT"
return "Types.UNKNOWN"
def resolve_named_type(
self, name: str, parent_stack: Optional[List[Message]]
) -> Optional[TypingUnion[Message, Enum, Union]]:
"""Resolve a named type to a schema definition."""
parts = name.split(".")
if len(parts) > 1:
current = self.find_top_level_type(parts[0])
for part in parts[1:]:
if isinstance(current, Message):
current = current.get_nested_type(part)
else:
return None
return current
if parent_stack:
for msg in reversed(parent_stack):
nested = msg.get_nested_type(name)
if nested is not None:
return nested
return self.find_top_level_type(name)
def find_top_level_type(
self, name: str
) -> Optional[TypingUnion[Message, Enum, Union]]:
"""Find a top-level type definition by name."""
for msg in self.schema.messages:
if msg.name == name:
return msg
for enum in self.schema.enums:
if enum.name == name:
return enum
for union in self.schema.unions:
if union.name == name:
return union
return None
def is_java_primitive_type(self, type_name: str) -> bool:
"""Return True if the Java type name is a primitive type."""
return type_name in {
"boolean",
"byte",
"short",
"int",
"long",
"float",
"double",
"char",
}
def generate_nested_message(
self,
message: Message,
indent: int = 1,
parent_stack: Optional[List[Message]] = None,
) -> List[str]:
"""Generate a nested message as a static inner class."""
lines = []
lineage = (parent_stack or []) + [message]
# Class declaration
lines.append(f"public static class {message.name} {{")
# Generate nested enums
for nested_enum in message.nested_enums:
for line in self.generate_nested_enum(nested_enum):
lines.append(f" {line}")
# Generate nested unions
for nested_union in message.nested_unions:
for line in self.generate_union_class(
nested_union,
indent=0,
nested=True,
parent_stack=lineage,
):
lines.append(f" {line}")
# Generate nested messages (recursively)
for nested_msg in message.nested_messages:
for line in self.generate_nested_message(
nested_msg,
indent=1,
parent_stack=lineage,
):
lines.append(f" {line}")
# Fields
for field in message.fields:
field_lines = self.generate_field(field)
for line in field_lines:
lines.append(f" {line}")
lines.append("")
# Default constructor
lines.append(f" public {message.name}() {{")
lines.append(" }")
lines.append("")
# Getters and setters
for field in message.fields:
getter_setter = self.generate_getter_setter(field)
for line in getter_setter: