-
Notifications
You must be signed in to change notification settings - Fork 160
Expand file tree
/
Copy pathgenerator.rb
More file actions
1913 lines (1776 loc) · 72.5 KB
/
generator.rb
File metadata and controls
1913 lines (1776 loc) · 72.5 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
require 'set'
class Generator < Xdrgen::Generators::Base
AST = Xdrgen::AST
STELLAR_SPECIFIC_TYPES = %w[
AccountID PublicKey NodeID ContractID
MuxedAccount MuxedEd25519Account SCAddress
SignerKey SignerKeyEd25519SignedPayload
PoolID ClaimableBalanceID
AssetCode4 AssetCode12
UInt128Parts Int128Parts UInt256Parts Int256Parts
].freeze
STELLAR_STRKEY_TYPES = %w[
AccountID PublicKey NodeID ContractID
MuxedAccount MuxedEd25519Account SCAddress
SignerKey SignerKeyEd25519SignedPayload
PoolID ClaimableBalanceID
].freeze
def generate
constants_container = Set[]
render_lib
render_definitions(@top, constants_container)
render_constants constants_container
end
def render_lib
template = IO.read(__dir__ + "/templates/XdrDataInputStream.erb")
result = ERB.new(template).result binding
@output.write "XdrDataInputStream.java", result
template = IO.read(__dir__ + "/templates/XdrDataOutputStream.erb")
result = ERB.new(template).result binding
@output.write "XdrDataOutputStream.java", result
template = IO.read(__dir__ + "/templates/XdrElement.erb")
result = ERB.new(template).result binding
@output.write "XdrElement.java", result
template = IO.read(__dir__ + "/templates/XdrString.erb")
result = ERB.new(template).result binding
@output.write "XdrString.java", result
template = IO.read(__dir__ + "/templates/XdrUnsignedHyperInteger.erb")
result = ERB.new(template).result binding
@output.write "XdrUnsignedHyperInteger.java", result
template = IO.read(__dir__ + "/templates/XdrUnsignedInteger.erb")
result = ERB.new(template).result binding
@output.write "XdrUnsignedInteger.java", result
end
def render_definitions(node, constants_container)
node.namespaces.each{|n| render_definitions n, constants_container }
node.definitions.each { |defn| render_definition(defn, constants_container) }
end
def add_imports_for_definition(defn, imports)
imports.add("org.stellar.sdk.Base64Factory")
imports.add("java.io.ByteArrayInputStream")
imports.add("java.io.ByteArrayOutputStream")
imports.add("java.util.LinkedHashMap")
imports.add("java.util.Map")
imports.add("java.util.List")
imports.add("java.util.ArrayList")
case defn
when AST::Definitions::Struct, AST::Definitions::Union
imports.add("lombok.Data")
imports.add("lombok.NoArgsConstructor")
imports.add("lombok.AllArgsConstructor")
imports.add("lombok.Builder")
when AST::Definitions::Typedef
imports.add("lombok.Data")
imports.add("lombok.NoArgsConstructor")
imports.add("lombok.AllArgsConstructor")
end
if needs_strkey_import_for_definition?(defn)
imports.add("org.stellar.sdk.StrKey")
end
if needs_biginteger_import_for_definition?(defn)
imports.add("java.math.BigInteger")
end
if defn.respond_to? :nested_definitions
defn.nested_definitions.each{ |child_defn| add_imports_for_definition(child_defn, imports) }
end
end
def needs_strkey_import_for_definition?(defn)
type_name = name(defn) rescue nil
return false if type_name.nil?
STELLAR_STRKEY_TYPES.include?(type_name)
end
def needs_biginteger_import_for_definition?(defn)
type_name = name(defn) rescue nil
return false if type_name.nil?
%w[UInt128Parts Int128Parts UInt256Parts Int256Parts].include?(type_name)
end
def stellar_specific_type?(type_name)
STELLAR_SPECIFIC_TYPES.include?(type_name)
end
def render_definition(defn, constants_container)
imports = Set[]
add_imports_for_definition(defn, imports)
case defn
when AST::Definitions::Struct ;
render_element defn, imports, defn do |out|
render_struct defn, out
render_nested_definitions defn, out
end
when AST::Definitions::Enum ;
render_element defn, imports, defn do |out|
render_enum defn, out
end
when AST::Definitions::Union ;
render_element defn, imports, defn do |out|
render_union defn, out
render_nested_definitions defn, out
end
when AST::Definitions::Typedef ;
render_element defn, imports, defn do |out|
render_typedef defn, out
end
when AST::Definitions::Const ;
const_name = defn.name
const_value = defn.value
constants_container.add([const_name, const_value])
end
end
def render_nested_definitions(defn, out, post_name="implements XdrElement")
return unless defn.respond_to? :nested_definitions
defn.nested_definitions.each{|ndefn|
render_source_comment out, ndefn
case ndefn
when AST::Definitions::Struct ;
name = name ndefn
out.puts "@Data"
out.puts "@NoArgsConstructor"
out.puts "@AllArgsConstructor"
out.puts "@Builder(toBuilder = true)"
out.puts "public static class #{name} #{post_name} {"
out.indent do
render_struct ndefn, out
render_nested_definitions ndefn , out
end
out.puts "}"
when AST::Definitions::Enum ;
name = name ndefn
out.puts "public static enum #{name} #{post_name} {"
out.indent do
render_enum ndefn, out
end
out.puts "}"
when AST::Definitions::Union ;
name = name ndefn
out.puts "@Data"
out.puts "@NoArgsConstructor"
out.puts "@AllArgsConstructor"
out.puts "@Builder(toBuilder = true)"
out.puts "public static class #{name} #{post_name} {"
out.indent do
render_union ndefn, out
render_nested_definitions ndefn, out
end
out.puts "}"
when AST::Definitions::Typedef ;
name = name ndefn
out.puts "@Data"
out.puts "@NoArgsConstructor"
out.puts "@AllArgsConstructor"
out.puts "public static class #{name} #{post_name} {"
out.indent do
render_typedef ndefn, out
end
out.puts "}"
end
}
end
def render_element(defn, imports, element, post_name="implements XdrElement")
path = element.name.camelize + ".java"
name = name_string element.name
out = @output.open(path)
render_top_matter out
imports.each do |import|
out.puts "import #{import};"
end
out.puts "\n"
render_source_comment out, element
case defn
when AST::Definitions::Struct, AST::Definitions::Union
out.puts "@Data"
out.puts "@NoArgsConstructor"
out.puts "@AllArgsConstructor"
out.puts "@Builder(toBuilder = true)"
out.puts "public class #{name} #{post_name} {"
when AST::Definitions::Enum
out.puts "public enum #{name} #{post_name} {"
when AST::Definitions::Typedef
out.puts "@Data"
out.puts "@NoArgsConstructor"
out.puts "@AllArgsConstructor"
out.puts "public class #{name} #{post_name} {"
end
out.indent do
yield out
out.unbreak
end
out.puts "}"
end
def render_constants(constants_container)
out = @output.open("Constants.java")
render_top_matter out
out.puts "public final class Constants {"
out.indent do
out.puts "private Constants() {}"
# Sort constants by name for consistent output
constants_container.sort_by { |const_name, _| const_name }.each do |const_name, const_value|
out.puts "public static final int #{const_name} = #{const_value};"
end
end
out.puts "}"
end
# ============================================================================
# Enum rendering
# ============================================================================
def render_enum(enum, out)
out.balance_after /,[\s]*/ do
enum.members.each_with_index do |em, index|
out.puts "#{em.name}(#{em.value})#{index == enum.members.size - 1 ? ';' : ','}"
end
end
out.break
out.puts <<-EOS.strip_heredoc
private final int value;
#{name_string enum.name}(int value) {
this.value = value;
}
public int getValue() {
return value;
}
public static #{name_string enum.name} decode(XdrDataInputStream stream, int maxDepth) throws IOException {
// maxDepth is intentionally not checked - enums are leaf types with no recursive decoding
int value = stream.readInt();
switch (value) {
EOS
out.indent 2 do
enum.members.each do |em|
out.puts "case #{em.value}: return #{em.name};"
end
end
out.puts <<-EOS.strip_heredoc
default:
throw new IllegalArgumentException("Unknown enum value: " + value);
}
}
public static #{name_string enum.name} decode(XdrDataInputStream stream) throws IOException {
return decode(stream, XdrDataInputStream.DEFAULT_MAX_DEPTH);
}
public void encode(XdrDataOutputStream stream) throws IOException {
stream.writeInt(value);
}
EOS
render_base64((name_string enum.name), out)
# JSON methods
render_enum_json(enum, out)
out.break
end
def render_enum_json(enum, out)
prefix_len = enum_prefix_length(enum)
enum_name = name_string enum.name
render_json_public_methods(enum_name, out)
# toJsonObject
out.puts "Object toJsonObject() {"
out.indent do
out.puts "switch (this) {"
enum.members.each do |em|
json_name = enum_json_name(em.name, prefix_len)
out.puts "case #{em.name}: return \"#{json_name}\";"
end
out.puts "default: throw new IllegalArgumentException(\"Unknown enum value: \" + this.value);"
out.puts "}"
end
out.puts "}"
# fromJsonObject
out.puts "static #{enum_name} fromJsonObject(Object json) {"
out.indent do
out.puts "String value = (String) json;"
out.puts "switch (value) {"
enum.members.each do |em|
json_name = enum_json_name(em.name, prefix_len)
out.puts "case \"#{json_name}\": return #{em.name};"
end
out.puts "default: throw new IllegalArgumentException(\"Unknown JSON value: \" + value);"
out.puts "}"
end
out.puts "}"
end
# ============================================================================
# Struct rendering
# ============================================================================
def render_struct(struct, out)
struct.members.each do |m|
out.puts "private #{decl_string(m.declaration)} #{m.name};"
end
out.puts "public void encode(XdrDataOutputStream stream) throws IOException{"
struct.members.each do |m|
out.indent do
encode_member m, out
end
end
out.puts "}"
# decode with maxDepth parameter
out.puts <<-EOS.strip_heredoc
public static #{name struct} decode(XdrDataInputStream stream, int maxDepth) throws IOException {
if (maxDepth <= 0) {
throw new IOException("Maximum decoding depth reached");
}
maxDepth -= 1;
#{name struct} decoded#{name struct} = new #{name struct}();
EOS
struct.members.each do |m|
out.indent do
decode_member "decoded#{name struct}", m, out, "maxDepth"
end
end
out.indent do
out.puts "return decoded#{name struct};"
end
out.puts "}"
# decode without maxDepth parameter (uses default)
out.puts <<-EOS.strip_heredoc
public static #{name struct} decode(XdrDataInputStream stream) throws IOException {
return decode(stream, XdrDataInputStream.DEFAULT_MAX_DEPTH);
}
EOS
render_base64((name struct), out)
# JSON methods
render_struct_json(struct, out)
out.break
end
def render_struct_json(struct, out)
struct_name = name struct
if stellar_specific_type?(struct_name)
render_stellar_struct_json(struct, struct_name, out)
return
end
render_json_public_methods(struct_name, out)
# toJsonObject
out.puts "Object toJsonObject() {"
out.indent do
out.puts "LinkedHashMap<String, Object> jsonMap = new LinkedHashMap<>();"
struct.members.each do |m|
json_key = m.name.underscore
expr = encode_value_to_json(m.declaration, m.name, m.type.sub_type == :optional)
out.puts "jsonMap.put(\"#{json_key}\", #{expr});"
end
out.puts "return jsonMap;"
end
out.puts "}"
# fromJsonObject
out.puts "@SuppressWarnings(\"unchecked\")"
out.puts "static #{struct_name} fromJsonObject(Object json) {"
out.indent do
out.puts "java.util.Map<String, Object> jsonMap = (java.util.Map<String, Object>) json;"
out.puts "#{struct_name} instance = new #{struct_name}();"
struct.members.each do |m|
json_key = m.name.underscore
decode_expr = decode_value_from_json(m.declaration, "jsonMap.get(\"#{json_key}\")", m.type.sub_type == :optional)
out.puts "instance.#{m.name} = #{decode_expr};"
end
out.puts "return instance;"
end
out.puts "}"
end
# ============================================================================
# Typedef rendering
# ============================================================================
def render_typedef(typedef, out)
out.puts "private #{decl_string typedef.declaration} #{typedef.name};"
out.puts "public void encode(XdrDataOutputStream stream) throws IOException {"
out.indent do
encode_member typedef, out
end
out.puts "}"
out.break
# decode with maxDepth parameter
out.puts <<-EOS.strip_heredoc
public static #{name typedef} decode(XdrDataInputStream stream, int maxDepth) throws IOException {
if (maxDepth <= 0) {
throw new IOException("Maximum decoding depth reached");
}
maxDepth -= 1;
#{name typedef} decoded#{name typedef} = new #{name typedef}();
EOS
out.indent do
decode_member "decoded#{name typedef}", typedef, out, "maxDepth"
out.puts "return decoded#{name typedef};"
end
out.puts "}"
# decode without maxDepth parameter (uses default)
out.puts <<-EOS.strip_heredoc
public static #{name typedef} decode(XdrDataInputStream stream) throws IOException {
return decode(stream, XdrDataInputStream.DEFAULT_MAX_DEPTH);
}
EOS
out.break
render_base64(typedef.name.camelize, out)
# JSON methods
render_typedef_json(typedef, out)
end
def render_typedef_json(typedef, out)
typedef_name = name typedef
if stellar_specific_type?(typedef_name)
render_stellar_typedef_json(typedef, typedef_name, out)
return
end
render_json_public_methods(typedef_name, out)
# toJsonObject
out.puts "Object toJsonObject() {"
out.indent do
expr = encode_value_to_json(typedef.declaration, typedef.name, typedef.type.sub_type == :optional)
out.puts "return #{expr};"
end
out.puts "}"
# fromJsonObject
out.puts "static #{typedef_name} fromJsonObject(Object json) {"
out.indent do
out.puts "#{typedef_name} instance = new #{typedef_name}();"
decode_expr = decode_value_from_json(typedef.declaration, "json", typedef.type.sub_type == :optional)
out.puts "instance.#{typedef.name} = #{decode_expr};"
out.puts "return instance;"
end
out.puts "}"
end
# ============================================================================
# Union rendering
# ============================================================================
def render_union(union, out)
out.puts "private #{type_string union.discriminant.type} discriminant;"
union.arms.each do |arm|
next if arm.void?
out.puts "private #{decl_string(arm.declaration)} #{arm.name};"
end
out.break
out.puts "public void encode(XdrDataOutputStream stream) throws IOException {"
if union.discriminant.type.is_a?(AST::Typespecs::Int)
out.puts "stream.writeInt(discriminant);"
elsif type_string(union.discriminant.type) == "Uint32"
# ugly workaround for compile error after generating source for AuthenticatedMessage in stellar-core
out.puts "stream.writeInt(discriminant.getUint32().getNumber().intValue());"
else
out.puts "stream.writeInt(discriminant.getValue());"
end
if type_string(union.discriminant.type) == "Uint32"
# ugly workaround for compile error after generating source for AuthenticatedMessage in stellar-core
out.puts "switch (discriminant.getUint32().getNumber().intValue()) {"
else
out.puts "switch (discriminant) {"
end
union.arms.each do |arm|
case arm
when AST::Definitions::UnionDefaultArm ;
out.puts "default:"
else
arm.cases.each do |kase|
if kase.value.is_a?(AST::Identifier)
if type_string(union.discriminant.type) == "Integer"
member = union.resolved_case(kase)
out.puts "case #{member.value}:"
else
out.puts "case #{kase.value.name}:"
end
else
out.puts "case #{kase.value.value}:"
end
end
end
encode_member arm, out
out.puts "break;"
end
out.puts "}\n}"
# decode with maxDepth parameter
out.puts "public static #{name union} decode(XdrDataInputStream stream, int maxDepth) throws IOException {"
out.puts "if (maxDepth <= 0) {"
out.puts " throw new IOException(\"Maximum decoding depth reached\");"
out.puts "}"
out.puts "maxDepth -= 1;"
out.puts "#{name union} decoded#{name union} = new #{name union}();"
if union.discriminant.type.is_a?(AST::Typespecs::Int)
out.puts "Integer discriminant = stream.readInt();"
else
out.puts "#{name union.discriminant.type} discriminant = #{name union.discriminant.type}.decode(stream, maxDepth);"
end
out.puts "decoded#{name union}.setDiscriminant(discriminant);"
if type_string(union.discriminant.type) == "Uint32"
# ugly workaround for compile error after generating source for AuthenticatedMessage in stellar-core
out.puts "switch (decoded#{name union}.getDiscriminant().getUint32().getNumber().intValue()) {"
else
out.puts "switch (decoded#{name union}.getDiscriminant()) {"
end
has_default_arm = union.arms.any? { |arm| arm.is_a?(AST::Definitions::UnionDefaultArm) }
union.arms.each do |arm|
case arm
when AST::Definitions::UnionDefaultArm ;
out.puts "default:"
else
arm.cases.each do |kase|
if kase.value.is_a?(AST::Identifier)
if type_string(union.discriminant.type) == "Integer"
member = union.resolved_case(kase)
out.puts "case #{member.value}:"
else
out.puts "case #{kase.value.name}:"
end
else
out.puts "case #{kase.value.value}:"
end
end
end
decode_member "decoded#{name union}", arm, out, "maxDepth"
out.puts "break;"
end
unless has_default_arm
out.puts "default:"
out.puts " throw new IOException(\"Unknown discriminant value: \" + discriminant);"
end
out.puts "}\n"
out.indent do
out.puts "return decoded#{name union};"
end
out.puts "}"
# decode without maxDepth parameter (uses default)
out.puts <<-EOS.strip_heredoc
public static #{name union} decode(XdrDataInputStream stream) throws IOException {
return decode(stream, XdrDataInputStream.DEFAULT_MAX_DEPTH);
}
EOS
render_base64((name union), out)
# JSON methods
render_union_json(union, out)
out.break
end
def render_union_json(union, out)
union_name = name union
if stellar_specific_type?(union_name)
render_stellar_union_json(union, union_name, out)
return
end
disc_enum = get_discriminant_enum(union)
# Collect void and non-void arm JSON keys
void_keys = []
non_void_keys = []
union.normal_arms.each do |arm|
arm.cases.each do |union_case|
key = json_key_for_case(union_case, disc_enum)
if arm.void?
void_keys << key
else
non_void_keys << key
end
end
end
has_void_default = union.default_arm.present? && union.default_arm.void?
render_json_public_methods(union_name, out)
# toJsonObject
out.puts "Object toJsonObject() {"
out.indent do
union.normal_arms.each do |arm|
arm.cases.each do |union_case|
json_key = json_key_for_case(union_case, disc_enum)
condition = render_union_case_condition_java(union, union_case)
out.puts "if (#{condition}) {"
out.indent do
if arm.void?
out.puts "return \"#{json_key}\";"
else
value_expr = encode_union_arm_value_to_json(arm)
out.puts "LinkedHashMap<String, Object> jsonMap = new LinkedHashMap<>();"
out.puts "jsonMap.put(\"#{json_key}\", #{value_expr});"
out.puts "return jsonMap;"
end
end
out.puts "}"
end
end
if union.default_arm.present?
if union.default_arm.void?
if disc_enum
out.puts "return discriminant.toJsonObject();"
else
out.puts "return \"v\" + discriminant;"
end
else
value_expr = encode_union_arm_value_to_json(union.default_arm)
out.puts "LinkedHashMap<String, Object> jsonMap = new LinkedHashMap<>();"
if disc_enum
out.puts "jsonMap.put((String) discriminant.toJsonObject(), #{value_expr});"
else
out.puts "jsonMap.put(\"v\" + discriminant, #{value_expr});"
end
out.puts "return jsonMap;"
end
else
out.puts "throw new IllegalArgumentException(\"Unknown discriminant: \" + discriminant);"
end
end
out.puts "}"
# fromJsonObject
out.puts "@SuppressWarnings(\"unchecked\")"
out.puts "static #{union_name} fromJsonObject(Object json) {"
out.indent do
has_void = void_keys.any? || has_void_default
has_non_void = non_void_keys.any? || (union.default_arm.present? && !union.default_arm.void?)
if has_void
out.puts "if (json instanceof String) {"
out.indent do
out.puts "String strVal = (String) json;"
render_union_void_from_json(out, union, union_name, disc_enum, void_keys, non_void_keys, has_void_default)
end
out.puts "}"
end
unless has_non_void
out.puts "throw new IllegalArgumentException(\"Expected a string for #{union_name}, got: \" + json);"
end
if has_non_void
out.puts "java.util.Map<String, Object> jsonMap = (java.util.Map<String, Object>) json;"
out.puts "if (jsonMap.containsKey(\"$schema\")) {"
out.puts " jsonMap = new LinkedHashMap<>(jsonMap);"
out.puts " jsonMap.remove(\"$schema\");"
out.puts "}"
out.puts "if (jsonMap.size() != 1) {"
out.puts " throw new IllegalArgumentException(\"Expected a single-key object for #{union_name}, got: \" + json);"
out.puts "}"
out.puts "String key = jsonMap.keySet().iterator().next();"
# Parse discriminant from key
if disc_enum
disc_type_name = name disc_enum
out.puts "#{type_string union.discriminant.type} discriminant = #{disc_type_name}.fromJsonObject(key);"
else
disc_type = type_string(union.discriminant.type)
if disc_type == "Integer"
out.puts "Integer discriminant = Integer.parseInt(key.substring(1));"
else
out.puts "#{disc_type} discriminant = #{disc_type}.fromJsonObject(Integer.parseInt(key.substring(1)));"
end
end
union.normal_arms.each do |arm|
next if arm.void?
arm.cases.each do |union_case|
json_key = json_key_for_case(union_case, disc_enum)
out.puts "if (key.equals(\"#{json_key}\")) {"
out.indent do
decode_expr = decode_union_arm_value_from_json(arm, "jsonMap.get(\"#{json_key}\")")
out.puts "#{union_name} instance = new #{union_name}();"
out.puts "instance.discriminant = discriminant;"
out.puts "instance.#{arm.name} = #{decode_expr};"
out.puts "return instance;"
end
out.puts "}"
end
end
if union.default_arm.present? && !union.default_arm.void?
decode_expr = decode_union_arm_value_from_json(union.default_arm, "jsonMap.get(key)")
out.puts "#{union_name} instance = new #{union_name}();"
out.puts "instance.discriminant = discriminant;"
out.puts "instance.#{union.default_arm.name} = #{decode_expr};"
out.puts "return instance;"
else
out.puts "throw new IllegalArgumentException(\"Unknown key '\" + key + \"' for #{union_name}\");"
end
end
end
out.puts "}"
end
def render_union_void_from_json(out, union, union_name, disc_enum, void_keys, non_void_keys, has_void_default)
if has_void_default
# Void default arm: string input valid for void arms and default
if non_void_keys.any?
nv_checks = non_void_keys.map { |k| "strVal.equals(\"#{k}\")" }.join(" || ")
out.puts "if (#{nv_checks}) {"
out.puts " throw new IllegalArgumentException(\"'\" + strVal + \"' requires a value for #{union_name}, use dict form instead\");"
out.puts "}"
end
if disc_enum
disc_type_name = name disc_enum
out.puts "#{union_name} instance = new #{union_name}();"
out.puts "instance.discriminant = #{disc_type_name}.fromJsonObject(strVal);"
out.puts "return instance;"
else
out.puts "#{union_name} instance = new #{union_name}();"
out.puts "instance.discriminant = Integer.parseInt(strVal.substring(1));"
out.puts "return instance;"
end
elsif void_keys.any?
# Only specific void arms
void_checks = void_keys.map { |k| "strVal.equals(\"#{k}\")" }.join(" || ")
out.puts "if (!(#{void_checks})) {"
out.puts " throw new IllegalArgumentException(\"Unexpected string '\" + strVal + \"' for #{union_name}\");"
out.puts "}"
if disc_enum
disc_type_name = name disc_enum
out.puts "#{union_name} instance = new #{union_name}();"
out.puts "instance.discriminant = #{disc_type_name}.fromJsonObject(strVal);"
out.puts "return instance;"
else
out.puts "#{union_name} instance = new #{union_name}();"
out.puts "instance.discriminant = Integer.parseInt(strVal.substring(1));"
out.puts "return instance;"
end
end
end
# ============================================================================
# Top matter & helpers
# ============================================================================
def render_top_matter(out)
out.puts <<-EOS.strip_heredoc
// Automatically generated by xdrgen
// DO NOT EDIT or your changes may be overwritten
package #{@namespace};
import java.io.IOException;
EOS
out.break
end
def render_source_comment(out, defn)
return if defn.is_a?(AST::Definitions::Namespace)
out.puts "/**"
out.puts " * #{name defn}'s original definition in the XDR file is:"
out.puts " * <pre>"
out.puts " * " + escape_html(defn.text_value).split("\n").join("\n * ")
out.puts " * </pre>"
out.puts " */"
end
def render_base64(return_type, out)
out.puts <<-EOS.strip_heredoc
public static #{return_type} fromXdrBase64(String xdr) throws IOException {
byte[] bytes = Base64Factory.getInstance().decode(xdr);
return fromXdrByteArray(bytes);
}
public static #{return_type} fromXdrByteArray(byte[] xdr) throws IOException {
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(xdr);
XdrDataInputStream xdrDataInputStream = new XdrDataInputStream(byteArrayInputStream);
xdrDataInputStream.setMaxInputLen(xdr.length);
return decode(xdrDataInputStream);
}
EOS
end
def render_json_public_methods(type_name, out)
out.puts <<-EOS.strip_heredoc
@Override
public String toJson() {
return XdrElement.gson.toJson(toJsonObject());
}
public static #{type_name} fromJson(String json) {
return fromJsonObject(XdrElement.gson.fromJson(json, Object.class));
}
EOS
end
# ============================================================================
# Encode/decode members (XDR binary)
# ============================================================================
def encode_member(member, out)
case member.declaration
when AST::Declarations::Void
return
end
if member.type.sub_type == :optional
out.puts "if (#{member.name} != null) {"
out.puts "stream.writeInt(1);"
end
case member.declaration
when AST::Declarations::Opaque ;
out.puts "int #{member.name}Size = #{member.name}.length;"
if member.declaration.fixed?
out.puts "if (#{member.name}Size != #{convert_constant member.declaration.size}) {"
out.puts " throw new IOException(\"#{member.name} size \" + #{member.name}Size + \" does not match fixed size #{member.declaration.size}\");"
out.puts "}"
else
max_size = member.declaration.resolved_size
if max_size
out.puts "if (#{member.name}Size > #{convert_constant max_size}) {"
out.puts " throw new IOException(\"#{member.name} size \" + #{member.name}Size + \" exceeds max size #{max_size}\");"
out.puts "}"
end
out.puts "stream.writeInt(#{member.name}Size);"
end
out.puts <<-EOS.strip_heredoc
stream.write(get#{member.name.slice(0,1).capitalize+member.name.slice(1..-1)}(), 0, #{member.name}Size);
EOS
when AST::Declarations::Array ;
out.puts "int #{member.name}Size = get#{member.name.slice(0,1).capitalize+member.name.slice(1..-1)}().length;"
if member.declaration.fixed?
out.puts "if (#{member.name}Size != #{convert_constant member.declaration.size}) {"
out.puts " throw new IOException(\"#{member.name} size \" + #{member.name}Size + \" does not match fixed size #{member.declaration.size}\");"
out.puts "}"
else
max_size = member.declaration.resolved_size
if max_size
out.puts "if (#{member.name}Size > #{convert_constant max_size}) {"
out.puts " throw new IOException(\"#{member.name} size \" + #{member.name}Size + \" exceeds max size #{max_size}\");"
out.puts "}"
end
out.puts "stream.writeInt(#{member.name}Size);"
end
out.puts <<-EOS.strip_heredoc
for (int i = 0; i < #{member.name}Size; i++) {
#{encode_type member.declaration.type, "#{member.name}[i]"};
}
EOS
when AST::Declarations::String ;
max_size = member.declaration.resolved_size
if max_size
out.puts "int #{member.name}Size = #{member.name}.getBytes().length;"
out.puts "if (#{member.name}Size > #{convert_constant max_size}) {"
out.puts " throw new IOException(\"#{member.name} size \" + #{member.name}Size + \" exceeds max size #{max_size}\");"
out.puts "}"
end
out.puts "#{member.name}.encode(stream);"
else
out.puts "#{encode_type member.declaration.type, "#{member.name}"};"
end
if member.type.sub_type == :optional
out.puts "} else {"
out.puts "stream.writeInt(0);"
out.puts "}"
end
end
def encode_type(type, value)
case type
when AST::Typespecs::Int ;
"stream.writeInt(#{value})"
when AST::Typespecs::UnsignedInt ;
"#{value}.encode(stream)"
when AST::Typespecs::Hyper ;
"stream.writeLong(#{value})"
when AST::Typespecs::UnsignedHyper ;
"#{value}.encode(stream)"
when AST::Typespecs::Float ;
"stream.writeFloat(#{value})"
when AST::Typespecs::Double ;
"stream.writeDouble(#{value})"
when AST::Typespecs::Quadruple ;
raise "cannot render quadruple in java"
when AST::Typespecs::Bool ;
"stream.writeInt(#{value} ? 1 : 0)"
when AST::Typespecs::String ;
"#{value}.encode(stream)"
when AST::Typespecs::Simple ;
"#{value}.encode(stream)"
when AST::Concerns::NestedDefinition ;
"#{value}.encode(stream)"
else
raise "Unknown typespec: #{type.class.name}"
end
end
def decode_member(value, member, out, depth_var = nil)
case member.declaration
when AST::Declarations::Void ;
return
end
if member.type.sub_type == :optional
out.puts <<-EOS.strip_heredoc
boolean #{member.name}Present = stream.readXdrBoolean();
if (#{member.name}Present) {
EOS
end
case member.declaration
when AST::Declarations::Opaque ;
if (member.declaration.fixed?)
out.puts "int #{member.name}Size = #{convert_constant member.declaration.size};"
else
out.puts "int #{member.name}Size = stream.readInt();"
# Add size validation for variable-length opaque
out.puts "if (#{member.name}Size < 0) {"
out.puts " throw new IOException(\"#{member.name} size \" + #{member.name}Size + \" is negative\");"
out.puts "}"
max_size = member.declaration.resolved_size
if max_size
out.puts "if (#{member.name}Size > #{convert_constant max_size}) {"
out.puts " throw new IOException(\"#{member.name} size \" + #{member.name}Size + \" exceeds max size #{max_size}\");"
out.puts "}"
end
# Add input length check to prevent DoS
out.puts "int #{member.name}RemainingInputLen = stream.getRemainingInputLen();"
out.puts "if (#{member.name}RemainingInputLen >= 0 && #{member.name}RemainingInputLen < #{member.name}Size) {"
out.puts " throw new IOException(\"#{member.name} size \" + #{member.name}Size + \" exceeds remaining input length \" + #{member.name}RemainingInputLen);"
out.puts "}"
end
out.puts <<-EOS.strip_heredoc
#{value}.#{member.name} = new byte[#{member.name}Size];
stream.readPaddedData(#{value}.#{member.name}, 0, #{member.name}Size);
EOS
when AST::Declarations::Array ;
if (member.declaration.fixed?)
out.puts "int #{member.name}Size = #{convert_constant member.declaration.size};"
else
out.puts "int #{member.name}Size = stream.readInt();"
# Add size validation for variable-length array
out.puts "if (#{member.name}Size < 0) {"
out.puts " throw new IOException(\"#{member.name} size \" + #{member.name}Size + \" is negative\");"
out.puts "}"
max_size = member.declaration.resolved_size
if max_size
out.puts "if (#{member.name}Size > #{convert_constant max_size}) {"
out.puts " throw new IOException(\"#{member.name} size \" + #{member.name}Size + \" exceeds max size #{max_size}\");"
out.puts "}"
end
# Add input length check to prevent DoS
out.puts "int #{member.name}RemainingInputLen = stream.getRemainingInputLen();"
out.puts "if (#{member.name}RemainingInputLen >= 0 && #{member.name}RemainingInputLen < #{member.name}Size) {"
out.puts " throw new IOException(\"#{member.name} size \" + #{member.name}Size + \" exceeds remaining input length \" + #{member.name}RemainingInputLen);"
out.puts "}"
end
out.puts <<-EOS.strip_heredoc