-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparcelable_gen.go
More file actions
1652 lines (1541 loc) · 54.2 KB
/
parcelable_gen.go
File metadata and controls
1652 lines (1541 loc) · 54.2 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
package codegen
import (
"fmt"
"strings"
"unicode"
"github.com/AndroidGoLab/binder/tools/pkg/parser"
)
// GenerateParcelable generates Go source for an AIDL parcelable declaration.
// The output includes:
// - A Go struct with all fields
// - A MarshalParcel method
// - An UnmarshalParcel method
// - Any constants declared inside the parcelable
func GenerateParcelable(
decl *parser.ParcelableDecl,
pkg string,
qualifiedName string,
options ...GenOption,
) ([]byte, error) {
opts := applyGenOptions(options)
// Forward-declared parcelables backed by native C++/NDK/Rust types
// produce no output -- they have no AIDL-defined structure to generate.
if len(decl.Fields) == 0 && len(decl.Constants) == 0 && len(decl.NestedTypes) == 0 &&
(decl.CppHeader != "" || decl.NdkHeader != "" || decl.RustType != "") {
return nil, nil
}
// Native parcelables have wire formats defined by C++/JNI code.
// Hand-written implementations are copied from native_impls/.
if decl.NativeParcelable {
return nil, nil
}
f := NewGoFile(pkg)
typeRef := opts.newTypeRefResolver(f)
f.AddImport("github.com/AndroidGoLab/binder/parcel", "")
// Add binder import if any field is an interface or IBinder type.
if hasBinderField(decl.Fields, opts, typeRef) {
f.AddImport("github.com/AndroidGoLab/binder/binder", "")
}
structName := AIDLToGoName(decl.ParcName)
recFields := opts.recursiveFields()
f.P("// Code generated by aidlgen. DO NOT EDIT.")
f.P("")
// Generate item structs for repeated (array-of-structs) wire fields.
// These must be emitted before the parent struct so Go can reference them.
for _, wf := range decl.JavaWireFormat {
if wf.WriteMethod != "repeated" || len(wf.Elements) == 0 {
continue
}
itemStructName := structName + singularize(AIDLToGoName(wf.Name))
f.P("type %s struct {", itemStructName)
for _, elem := range wf.Elements {
if !isValidGoFieldName(elem.Name) {
continue
}
elemGoName := AIDLToGoName(elem.Name)
switch elem.WriteMethod {
case "char_sequence":
f.P("\t%s *string", elemGoName)
case "string_list":
f.P("\t%s []string", elemGoName)
case "string8":
f.P("\t%s *string", elemGoName)
case "string16":
f.P("\t%s *string", elemGoName)
case "bool":
f.P("\t%s bool", elemGoName)
case "int32":
f.P("\t%s int32", elemGoName)
case "int64":
f.P("\t%s int64", elemGoName)
}
}
f.P("}")
f.P("")
}
// Struct declaration.
// For @nullable parcelable fields, use pointer types so that nil
// represents null. Other @nullable types (IBinder, ParcelFileDescriptor,
// slices, maps, strings) are already nullable in Go and don't need
// pointer wrapping.
// Fields whose types create recursive struct definitions also use
// pointer types to break the infinite-size cycle.
f.P("type %s struct {", structName)
for _, field := range decl.Fields {
goType := resolveTypeRef(typeRef, field.Type)
switch {
case isNullableParcelableField(field, opts, typeRef):
goType = "*" + goType
case recFields.needsPointer(structName, goType):
goType = "*" + goType
}
goFieldName := AIDLToGoName(field.FieldName)
f.P("\t%s %s", goFieldName, goType)
}
// Emit struct fields for typed_object JavaWireFormat fields that
// have a resolved parcelable type. These fields are not in
// decl.Fields (to avoid perturbing the import graph), so the
// codegen generates them directly from the wire field metadata.
for _, wf := range decl.JavaWireFormat {
switch wf.WriteMethod {
case "typed_object":
if wf.GoType == "" {
continue
}
goType := resolveJavaWireGoType(typeRef, wf.GoType)
if goType == "" {
continue // cycle can't be broken — field stays opaque
}
goName := AIDLToGoName(wf.Name)
f.P("\t%s *%s", goName, goType)
case "delegate":
if wf.GoType == "" {
continue
}
goType := resolveJavaWireGoType(typeRef, wf.GoType)
if goType == "" {
continue
}
goName := AIDLToGoName(wf.Name)
// Self-references and nullable delegates use pointer types
// to avoid infinite-size structs and represent null.
if wf.Condition == "_null_flag" || goType == structName {
f.P("\t%s *%s", goName, goType)
} else {
f.P("\t%s %s", goName, goType)
}
case "char_sequence":
if !isValidGoFieldName(wf.Name) {
continue
}
goName := AIDLToGoName(wf.Name)
f.P("\t%s *string", goName)
case "string_list":
if !isValidGoFieldName(wf.Name) {
continue
}
goName := AIDLToGoName(wf.Name)
f.P("\t%s []string", goName)
case "repeated":
if len(wf.Elements) == 0 {
continue
}
goName := AIDLToGoName(wf.Name)
itemType := structName + singularize(AIDLToGoName(wf.Name))
f.P("\t%s []%s", goName, itemType)
}
}
f.P("}")
f.P("")
// Constants declared inside the parcelable.
if len(decl.Constants) > 0 {
if err := GenerateConstants(decl.Constants, f, structName); err != nil {
return nil, fmt.Errorf("generating parcelable constants: %w", err)
}
f.P("")
}
// Parcelable interface compliance.
f.P("var _ parcel.Parcelable = (*%s)(nil)", structName)
f.P("")
if len(decl.JavaWireFormat) > 0 {
// Java wire format: generate marshal/unmarshal from the extracted
// writeToParcel() layout, handling conditional fields and opaque skips.
writeJavaWireMarshalParcel(f, structName, decl.JavaWireFormat, typeRef)
writeJavaWireUnmarshalParcel(f, structName, decl.JavaWireFormat, typeRef)
} else {
// Standard AIDL field-based marshal/unmarshal.
writeMarshalParcel(f, structName, decl.Fields, opts, typeRef, recFields)
writeUnmarshalParcel(f, structName, decl.Fields, opts, typeRef, recFields)
}
return f.Bytes()
}
// fieldTypeWithAnnotations returns a TypeSpecifier that includes both the
// field-level and type-level annotations. In AIDL, annotations like
// @utf8InCpp and @nullable are placed before the type in field declarations
// but the parser attaches them to the FieldDecl, not the TypeSpecifier.
// Merging them ensures marshalForType sees annotations like @utf8InCpp.
func fieldTypeWithAnnotations(
field *parser.FieldDecl,
) *parser.TypeSpecifier {
if len(field.Annots) == 0 {
return field.Type
}
merged := *field.Type
merged.Annots = append(append([]*parser.Annotation(nil), field.Annots...), field.Type.Annots...)
return &merged
}
// hasBinderField returns true if any field requires the binder import
// (either an AIDL interface type or the IBinder primitive type).
func hasBinderField(
fields []*parser.FieldDecl,
opts GenOptions,
typeRef *TypeRefResolver,
) bool {
for _, field := range fields {
if fieldRequiresBinderImport(field.Type, opts, typeRef) {
return true
}
}
return false
}
// fieldRequiresBinderImport returns true if the type or any element of an
// array/list type is an AIDL interface or IBinder, AND the type is not
// an opaque/unresolvable type that will be rendered as any.
func fieldRequiresBinderImport(
ts *parser.TypeSpecifier,
opts GenOptions,
typeRef *TypeRefResolver,
) bool {
// Check if the type resolves to any, in which case no
// binder import is needed.
if typeRef != nil {
resolved := typeRef.GoTypeRef(ts)
if isOpaqueGoType(resolved) {
return false
}
}
if ts.Name == "IBinder" {
return true
}
if ts.IsArray || ts.Name == "List" {
elemType := elementTypeSpec(ts)
return fieldRequiresBinderImport(elemType, opts, typeRef)
}
if ts.Name == "Map" {
keyType := mapKeyTypeSpec(ts)
valType := mapValTypeSpec(ts)
return fieldRequiresBinderImport(keyType, opts, typeRef) ||
fieldRequiresBinderImport(valType, opts, typeRef)
}
// Use marshalForTypeWithCycleCheck so that cycle-broken or
// opaque interface types (resolved to any due to import
// cycles) are correctly excluded. Without this, the binder import
// is added for fields whose marshal/unmarshal code is actually
// skipped, causing an "imported and not used" compile error.
info := marshalForTypeWithCycleCheck(ts, opts, typeRef)
return info.IsInterface || info.IsIBinder
}
// writeMarshalParcel generates the MarshalParcel method for a parcelable struct.
func writeMarshalParcel(
f *GoFile,
structName string,
fields []*parser.FieldDecl,
opts GenOptions,
typeRef *TypeRefResolver,
recFields *recursiveFieldSet,
) {
f.P("func (s *%s) MarshalParcel(", structName)
f.P("\tp *parcel.Parcel,")
f.P(") error {")
f.P("\t_headerPos := parcel.WriteParcelableHeader(p)")
for _, field := range fields {
goFieldName := AIDLToGoName(field.FieldName)
fieldAccess := "s." + goFieldName
// Merge field-level annotations (e.g. @utf8InCpp) into the type
// so marshalForType sees them when choosing the write method.
fieldType := fieldTypeWithAnnotations(field)
if fieldType.IsArray || fieldType.Name == "List" {
writeArrayFieldToParcel(f, fieldType, fieldAccess, "p", structName, opts, typeRef)
continue
}
if fieldType.Name == "Map" {
writeMapFieldToParcel(f, fieldType, fieldAccess, "p", opts, typeRef)
continue
}
info := marshalForTypeWithCycleCheck(fieldType, opts, typeRef)
if info.WriteExpr == "" {
continue
}
// Check if this field uses a pointer to break recursive types.
goType := resolveTypeRef(typeRef, field.Type)
fieldIsRecursivePtr := recFields.needsPointer(structName, goType)
// IBinder/interface fields need a nil guard: write a null binder
// object when nil, otherwise use WriteStrongBinder with the handle.
// MarshalParcel does not have ctx/transport, so WriteBinderToParcel
// cannot be used here; local StubBinders must be pre-registered.
switch {
case info.IsIBinder:
f.P("\tif %s == nil {", fieldAccess)
f.P("\t\tp.WriteNullStrongBinder()")
f.P("\t} else {")
f.P("\t\tp.WriteStrongBinder(%s.Handle())", fieldAccess)
f.P("\t}")
case info.IsInterface:
f.P("\tif %s == nil {", fieldAccess)
f.P("\t\tp.WriteNullStrongBinder()")
f.P("\t} else {")
f.P("\t\tp.WriteStrongBinder(%s.AsBinder().Handle())", fieldAccess)
f.P("\t}")
case strings.Contains(info.WriteExpr, ".MarshalParcel"):
if isNullableParcelableField(field, opts, typeRef) || fieldIsRecursivePtr {
// Pointer field (either @nullable or recursive-type pointer):
// write int32 null indicator (0 = null, 1 = non-null) before
// the parcelable data.
f.P("\tif %s == nil {", fieldAccess)
f.P("\t\tp.WriteInt32(0)")
f.P("\t} else {")
f.P("\t\tp.WriteInt32(1)")
writeExpr := fmt.Sprintf("%s.MarshalParcel(p)", fieldAccess)
f.P("\t\tif _err := %s; _err != nil {", writeExpr)
f.P("\t\t\treturn _err")
f.P("\t\t}")
f.P("\t}")
} else {
// NDK AIDL wire format: int32(1) non-null indicator before
// every non-nullable parcelable/union field.
f.P("\tp.WriteInt32(1) // non-null indicator")
writeExpr := fmt.Sprintf("%s.MarshalParcel(p)", fieldAccess)
f.P("\tif _err := %s; _err != nil {", writeExpr)
f.P("\t\treturn _err")
f.P("\t}")
}
default:
writeExpr := fmt.Sprintf(info.WriteExpr, fieldAccess)
writeExpr = strings.ReplaceAll(writeExpr, "_data", "p")
f.P("\t%s", writeExpr)
}
}
f.P("")
f.P("\tparcel.WriteParcelableFooter(p, _headerPos)")
f.P("\treturn nil")
f.P("}")
f.P("")
}
// writeArrayFieldToParcel writes array serialization code for a parcelable field.
// structName is the Go name of the enclosing struct, used to qualify constant
// references in fixed-size array dimensions (e.g. BYTE_SIZE_OF_CACHE_TOKEN
// becomes PrepareModelConfigByteSizeOfCacheToken).
func writeArrayFieldToParcel(
f *GoFile,
ts *parser.TypeSpecifier,
fieldAccess string,
parcelVar string,
structName string,
opts GenOptions,
typeRef *TypeRefResolver,
) {
elemType := elementTypeSpec(ts)
// Fixed-size byte arrays (e.g. byte[128]) use WriteFixedByteArray which
// writes int32(N) + exactly N raw bytes, matching the C++ Parcel::writeData
// for std::array<int8_t, N>.
if elemType.Name == "byte" && ts.FixedSize != "" {
goFixedSize := resolveFixedSizeExpr(ts.FixedSize, structName)
f.P("\t%s.WriteFixedByteArray(%s, %s)", parcelVar, fieldAccess, goFixedSize)
return
}
// The NDK AIDL backend uses AParcel_writeByteArray for byte[] which
// writes int32(len) + compact bytes (padded to 4 at the end), not
// per-element padded writes. Use WriteByteArray/ReadByteArray directly.
if elemType.Name == "byte" {
f.P("\t%s.WriteByteArray(%s)", parcelVar, fieldAccess)
return
}
elemInfo := marshalForTypeWithCycleCheck(elemType, opts, typeRef)
f.P("\tif %s == nil {", fieldAccess)
f.P("\t\t%s.WriteInt32(-1)", parcelVar)
f.P("\t} else {")
f.P("\t\t%s.WriteInt32(int32(len(%s)))", parcelVar, fieldAccess)
if elemInfo.WriteExpr != "" {
f.P("\t\tfor _, _item := range %s {", fieldAccess)
writeExpr := fmt.Sprintf(elemInfo.WriteExpr, "_item")
writeExpr = strings.ReplaceAll(writeExpr, "_data", parcelVar)
if strings.Contains(elemInfo.WriteExpr, ".MarshalParcel") {
writeExpr = fmt.Sprintf("_item.MarshalParcel(%s)", parcelVar)
// NDK AIDL wire format: int32(1) non-null indicator before each
// parcelable element, matching writeTypedObject semantics.
f.P("\t\t\t%s.WriteInt32(1)", parcelVar)
f.P("\t\t\tif _err := %s; _err != nil {", writeExpr)
f.P("\t\t\t\treturn _err")
f.P("\t\t\t}")
} else {
f.P("\t\t\t%s", writeExpr)
}
f.P("\t\t}")
}
f.P("\t}")
}
// writeUnmarshalParcel generates the UnmarshalParcel method for a parcelable struct.
func writeUnmarshalParcel(
f *GoFile,
structName string,
fields []*parser.FieldDecl,
opts GenOptions,
typeRef *TypeRefResolver,
recFields *recursiveFieldSet,
) {
f.P("func (s *%s) UnmarshalParcel(", structName)
f.P("\tp *parcel.Parcel,")
f.P(") error {")
f.P("\t_endPos, _err := parcel.ReadParcelableHeader(p)")
f.P("\tif _err != nil {")
f.P("\t\treturn _err")
f.P("\t}")
arrayIdx := 0
mapIdx := 0
for _, field := range fields {
goFieldName := AIDLToGoName(field.FieldName)
// Merge field-level annotations (e.g. @utf8InCpp) into the type
// so marshalForType sees them when choosing the read method.
fieldType := fieldTypeWithAnnotations(field)
// When the sender is from an older API level, the parcel may contain
// fewer fields than the current definition. Stop reading once we
// reach _endPos so the remaining fields keep their Go zero values.
f.P("")
f.P("\tif p.Position() >= _endPos {")
f.P("\t\tparcel.SkipToParcelableEnd(p, _endPos)")
f.P("\t\treturn nil")
f.P("\t}")
if fieldType.IsArray || fieldType.Name == "List" {
readArrayFieldFromParcel(f, fieldType, "s."+goFieldName, "p", arrayIdx, structName, opts, typeRef)
arrayIdx++
continue
}
if fieldType.Name == "Map" {
readMapFieldFromParcel(f, fieldType, "s."+goFieldName, "p", mapIdx, opts, typeRef)
mapIdx++
continue
}
info := marshalForTypeWithCycleCheck(fieldType, opts, typeRef)
if info.ReadExpr == "" {
continue
}
// Check if this field uses a pointer to break recursive types.
goType := resolveTypeRef(typeRef, field.Type)
fieldIsRecursivePtr := recFields.needsPointer(structName, goType)
readExpr := strings.ReplaceAll(info.ReadExpr, "_reply", "p")
switch {
case strings.Contains(info.ReadExpr, ".UnmarshalParcel"):
if isNullableParcelableField(field, opts, typeRef) || fieldIsRecursivePtr {
// Pointer field (either @nullable or recursive-type pointer):
// read int32 null indicator. 0 = null (leave field nil),
// non-zero = allocate and read the parcelable.
// Use a block scope for _nullInd to avoid redeclaration when
// multiple nullable/recursive parcelable fields exist.
f.P("")
f.P("\t{")
f.P("\t\t_nullInd, _nullErr := p.ReadInt32()")
f.P("\t\tif _nullErr != nil {")
f.P("\t\t\treturn _nullErr")
f.P("\t\t}")
f.P("\t\tif _nullInd != 0 {")
f.P("\t\t\tvar _val %s", goType)
f.P("\t\t\tif _err = _val.UnmarshalParcel(p); _err != nil {")
f.P("\t\t\t\treturn _err")
f.P("\t\t\t}")
f.P("\t\t\ts.%s = &_val", goFieldName)
f.P("\t\t}")
f.P("\t}")
} else {
// NDK AIDL wire format: int32(1) non-null indicator before
// every non-nullable parcelable/union field.
f.P("")
f.P("\tif _, _err = p.ReadInt32(); _err != nil { // non-null indicator")
f.P("\t\treturn _err")
f.P("\t}")
f.P("\tif _err = s.%s.UnmarshalParcel(p); _err != nil {", goFieldName)
f.P("\t\treturn _err")
f.P("\t}")
}
case info.IsInterface:
proxyConstructor := interfaceProxyConstructor(typeRef, field.Type)
f.P("")
f.P("\t_%sHandle, _err := %s", field.FieldName, readExpr)
f.P("\tif _err != nil {")
f.P("\t\treturn _err")
f.P("\t}")
f.P("\ts.%s = %s(binder.NewProxyBinder(nil, binder.CallerIdentity{}, _%sHandle))", goFieldName, proxyConstructor, field.FieldName)
case info.IsIBinder:
f.P("")
f.P("\t_%sHandle, _err := %s", field.FieldName, readExpr)
f.P("\tif _err != nil {")
f.P("\t\treturn _err")
f.P("\t}")
// Null binder handles are represented as 0; leave field nil.
f.P("\tif _%sHandle != 0 {", field.FieldName)
f.P("\t\ts.%s = binder.NewProxyBinder(nil, binder.CallerIdentity{}, _%sHandle)", goFieldName, field.FieldName)
f.P("\t}")
case info.NeedsCast:
goType := resolveTypeRef(typeRef, field.Type)
f.P("")
f.P("\t_%sRaw, _err := %s", field.FieldName, readExpr)
f.P("\tif _err != nil {")
f.P("\t\treturn _err")
f.P("\t}")
f.P("\ts.%s = %s(_%sRaw)", goFieldName, goType, field.FieldName)
default:
f.P("")
f.P("\ts.%s, _err = %s", goFieldName, readExpr)
f.P("\tif _err != nil {")
f.P("\t\treturn _err")
f.P("\t}")
}
}
f.P("")
f.P("\tparcel.SkipToParcelableEnd(p, _endPos)")
f.P("\treturn nil")
f.P("}")
f.P("")
}
// readArrayFieldFromParcel writes array deserialization code for a parcelable field.
// arrayIdx is used to create unique variable names when multiple array fields exist.
// structName is the Go name of the enclosing struct, used to qualify constant
// references in fixed-size array dimensions.
func readArrayFieldFromParcel(
f *GoFile,
ts *parser.TypeSpecifier,
fieldAccess string,
parcelVar string,
arrayIdx int,
structName string,
opts GenOptions,
typeRef *TypeRefResolver,
) {
goType := resolveTypeRef(typeRef, ts)
elemType := elementTypeSpec(ts)
// Fixed-size byte arrays (e.g. byte[128]) use ReadFixedByteArray which
// reads int32(N) + exactly N raw bytes.
if elemType.Name == "byte" && ts.FixedSize != "" {
goFixedSize := resolveFixedSizeExpr(ts.FixedSize, structName)
f.P("")
f.P("\t%s, _err = %s.ReadFixedByteArray(%s)", fieldAccess, parcelVar, goFixedSize)
f.P("\tif _err != nil {")
f.P("\t\treturn _err")
f.P("\t}")
return
}
// The NDK AIDL backend uses AParcel_readByteArray for byte[] which
// reads int32(len) + compact bytes, not per-element padded reads.
if elemType.Name == "byte" {
f.P("")
f.P("\t%s, _err = %s.ReadByteArray()", fieldAccess, parcelVar)
f.P("\tif _err != nil {")
f.P("\t\treturn _err")
f.P("\t}")
return
}
elemInfo := marshalForTypeWithCycleCheck(elemType, opts, typeRef)
// Use unique variable names per array to avoid redeclaration.
countVar := fmt.Sprintf("_count%d", arrayIdx)
f.P("")
f.P("\tvar %s int32", countVar)
f.P("\t%s, _err = %s.ReadInt32()", countVar, parcelVar)
f.P("\tif _err != nil {")
f.P("\t\treturn _err")
f.P("\t}")
f.P("\tif %s >= 0 {", countVar)
f.P("\t\t%s = make(%s, %s)", fieldAccess, goType, countVar)
f.P("\t\tfor _i := int32(0); _i < %s; _i++ {", countVar)
elemReadExpr := strings.ReplaceAll(elemInfo.ReadExpr, "_reply", parcelVar)
if elemReadExpr == "" {
// Opaque/unresolvable element type: skip deserialization.
f.P("\t\t}")
f.P("\t}")
return
}
switch {
case strings.Contains(elemInfo.ReadExpr, ".UnmarshalParcel"):
// NDK AIDL wire format: int32 non-null indicator before each
// parcelable element, matching readTypedObject semantics.
f.P("\t\t\tif _, _err = %s.ReadInt32(); _err != nil {", parcelVar)
f.P("\t\t\t\treturn _err")
f.P("\t\t\t}")
f.P("\t\t\tif _err = %s[_i].UnmarshalParcel(%s); _err != nil {", fieldAccess, parcelVar)
f.P("\t\t\t\treturn _err")
f.P("\t\t\t}")
case elemInfo.IsInterface:
proxyConstructor := interfaceProxyConstructor(typeRef, elemType)
f.P("\t\t\t_handle, _err := %s", elemReadExpr)
f.P("\t\t\tif _err != nil {")
f.P("\t\t\t\treturn _err")
f.P("\t\t\t}")
f.P("\t\t\t%s[_i] = %s(binder.NewProxyBinder(nil, binder.CallerIdentity{}, _handle))", fieldAccess, proxyConstructor)
case elemInfo.IsIBinder:
f.P("\t\t\t_handle, _err := %s", elemReadExpr)
f.P("\t\t\tif _err != nil {")
f.P("\t\t\t\treturn _err")
f.P("\t\t\t}")
f.P("\t\t\t%s[_i] = binder.NewProxyBinder(nil, binder.CallerIdentity{}, _handle)", fieldAccess)
case elemInfo.NeedsCast:
elemGoType := resolveTypeRef(typeRef, elemType)
f.P("\t\t\t_raw, _err := %s", elemReadExpr)
f.P("\t\t\tif _err != nil {")
f.P("\t\t\t\treturn _err")
f.P("\t\t\t}")
f.P("\t\t\t%s[_i] = %s(_raw)", fieldAccess, elemGoType)
default:
f.P("\t\t\t%s[_i], _err = %s", fieldAccess, elemReadExpr)
f.P("\t\t\tif _err != nil {")
f.P("\t\t\t\treturn _err")
f.P("\t\t\t}")
}
f.P("\t\t}")
f.P("\t}")
}
// writeMapFieldToParcel writes map serialization code for a parcelable field.
func writeMapFieldToParcel(
f *GoFile,
ts *parser.TypeSpecifier,
fieldAccess string,
parcelVar string,
opts GenOptions,
typeRef *TypeRefResolver,
) {
keyType := mapKeyTypeSpec(ts)
valType := mapValTypeSpec(ts)
keyInfo := marshalForTypeWithCycleCheck(keyType, opts, typeRef)
valInfo := marshalForTypeWithCycleCheck(valType, opts, typeRef)
f.P("\tif %s == nil {", fieldAccess)
f.P("\t\t%s.WriteInt32(-1)", parcelVar)
f.P("\t} else {")
f.P("\t\t%s.WriteInt32(int32(len(%s)))", parcelVar, fieldAccess)
// Map values (or keys) can be List<T> or T[] types, which have no
// single WriteExpr and require inline array serialization.
valIsList := valType.IsArray || valType.Name == "List"
keyIsList := keyType.IsArray || keyType.Name == "List"
if (keyInfo.WriteExpr != "" || keyIsList) && (valInfo.WriteExpr != "" || valIsList) {
f.P("\t\tfor _k, _v := range %s {", fieldAccess)
// When the map Go type has any for key or value,
// the range variables are any and need type assertions
// to match what the write expressions expect.
if keyIsList {
writeArrayFieldToParcel(f, keyType, "_k", parcelVar, "", opts, typeRef)
} else {
keyVar := mapRangeVarWithAssertion("_k", keyType, ts, 0, typeRef)
writeKeyExpr := fmt.Sprintf(keyInfo.WriteExpr, keyVar)
writeKeyExpr = strings.ReplaceAll(writeKeyExpr, "_data", parcelVar)
writeMapFieldElemExpr(f, keyInfo, writeKeyExpr, "\t\t\t", parcelVar)
}
if valIsList {
writeArrayFieldToParcel(f, valType, "_v", parcelVar, "", opts, typeRef)
} else {
valVar := mapRangeVarWithAssertion("_v", valType, ts, 1, typeRef)
writeValExpr := fmt.Sprintf(valInfo.WriteExpr, valVar)
writeValExpr = strings.ReplaceAll(writeValExpr, "_data", parcelVar)
writeMapFieldElemExpr(f, valInfo, writeValExpr, "\t\t\t", parcelVar)
}
f.P("\t\t}")
}
f.P("\t}")
}
// writeMapFieldElemExpr writes a single map element (key or value) write
// expression with error handling for parcelable marshal methods.
func writeMapFieldElemExpr(
f *GoFile,
info MarshalInfo,
writeExpr string,
indent string,
parcelVar string,
) {
if strings.Contains(info.WriteExpr, ".MarshalParcel") {
// NDK AIDL wire format: int32(1) non-null indicator before each
// parcelable element, matching writeTypedObject semantics.
f.P("%s%s.WriteInt32(1)", indent, parcelVar)
f.P("%sif _err := %s; _err != nil {", indent, writeExpr)
f.P("%s\treturn _err", indent)
f.P("%s}", indent)
} else {
f.P("%s%s", indent, writeExpr)
}
}
// readMapFieldFromParcel writes map deserialization code for a parcelable field.
// mapIdx is used to create unique variable names when multiple map fields exist.
func readMapFieldFromParcel(
f *GoFile,
ts *parser.TypeSpecifier,
fieldAccess string,
parcelVar string,
mapIdx int,
opts GenOptions,
typeRef *TypeRefResolver,
) {
goType := resolveTypeRef(typeRef, ts)
keyType := mapKeyTypeSpec(ts)
valType := mapValTypeSpec(ts)
keyInfo := marshalForTypeWithCycleCheck(keyType, opts, typeRef)
valInfo := marshalForTypeWithCycleCheck(valType, opts, typeRef)
keyReadExpr := strings.ReplaceAll(keyInfo.ReadExpr, "_reply", parcelVar)
valReadExpr := strings.ReplaceAll(valInfo.ReadExpr, "_reply", parcelVar)
// Use unique variable names per map to avoid redeclaration.
countVar := fmt.Sprintf("_mapCount%d", mapIdx)
f.P("")
f.P("\tvar %s int32", countVar)
f.P("\t%s, _err = %s.ReadInt32()", countVar, parcelVar)
f.P("\tif _err != nil {")
f.P("\t\treturn _err")
f.P("\t}")
f.P("\tif %s >= 0 {", countVar)
f.P("\t\t%s = make(%s, %s)", fieldAccess, goType, countVar)
// Map values (or keys) can be List<T> or T[] types, which have no
// single ReadExpr and require inline array deserialization.
valIsList := valType.IsArray || valType.Name == "List"
keyIsList := keyType.IsArray || keyType.Name == "List"
if (keyReadExpr != "" || keyIsList) && (valReadExpr != "" || valIsList) {
f.P("\t\tfor _mi := int32(0); _mi < %s; _mi++ {", countVar)
if keyIsList {
writeMapReadArrayElem(f, keyType, "_mk", "\t\t\t", opts, typeRef, parcelVar, "return _err")
} else {
readMapFieldElem(f, keyInfo, keyReadExpr, keyType, "_mk", "\t\t\t", "k", typeRef, parcelVar)
}
if valIsList {
writeMapReadArrayElem(f, valType, "_mv", "\t\t\t", opts, typeRef, parcelVar, "return _err")
} else {
readMapFieldElem(f, valInfo, valReadExpr, valType, "_mv", "\t\t\t", "v", typeRef, parcelVar)
}
f.P("\t\t\t%s[_mk] = _mv", fieldAccess)
f.P("\t\t}")
}
f.P("\t}")
}
// readMapFieldElem writes code to read a single map element (key or value)
// into a local variable in a parcelable unmarshal method.
// rawPrefix disambiguates the intermediate _raw variable when both key and
// value use NeedsCast (e.g., "k" produces _rawK, "v" produces _rawV).
func readMapFieldElem(
f *GoFile,
info MarshalInfo,
readExpr string,
ts *parser.TypeSpecifier,
varName string,
indent string,
rawPrefix string,
typeRef *TypeRefResolver,
parcelVar string,
) {
switch {
case strings.Contains(info.ReadExpr, ".UnmarshalParcel"):
// Parcelable map elements: declare variable, read null indicator,
// then unmarshal in-place. UnmarshalParcel returns only error,
// not (T, error), so it cannot use the default assignment pattern.
goType := resolveTypeRef(typeRef, ts)
f.P("%svar %s %s", indent, varName, goType)
f.P("%sif _, _err := %s.ReadInt32(); _err != nil {", indent, parcelVar)
f.P("%s\treturn _err", indent)
f.P("%s}", indent)
f.P("%sif _err := %s.UnmarshalParcel(%s); _err != nil {", indent, varName, parcelVar)
f.P("%s\treturn _err", indent)
f.P("%s}", indent)
case info.NeedsCast:
goType := resolveTypeRef(typeRef, ts)
rawVar := fmt.Sprintf("_raw%s", strings.ToUpper(rawPrefix[:1])+rawPrefix[1:])
f.P("%s%s, _err := %s", indent, rawVar, readExpr)
f.P("%sif _err != nil {", indent)
f.P("%s\treturn _err", indent)
f.P("%s}", indent)
f.P("%s%s := %s(%s)", indent, varName, goType, rawVar)
default:
f.P("%s%s, _err := %s", indent, varName, readExpr)
f.P("%sif _err != nil {", indent)
f.P("%s\treturn _err", indent)
f.P("%s}", indent)
}
}
// isNullableParcelableField returns true if a field has the @nullable annotation
// AND its type is a scalar parcelable (MarshalParcel/UnmarshalParcel).
// Types like IBinder, interfaces, primitives (including ParcelFileDescriptor),
// arrays, lists, and maps are already nullable in Go and don't need pointer
// wrapping or null indicators in parcelable marshal/unmarshal.
func isNullableParcelableField(
field *parser.FieldDecl,
opts GenOptions,
typeRef *TypeRefResolver,
) bool {
if !hasAnnotation(field.Annots, "nullable") && !hasAnnotation(field.Type.Annots, "nullable") {
return false
}
// Arrays, lists, and maps are nullable via nil slice/map in Go.
if field.Type.IsArray || field.Type.Name == "List" || field.Type.Name == "Map" {
return false
}
fieldType := fieldTypeWithAnnotations(field)
info := marshalForTypeWithCycleCheck(fieldType, opts, typeRef)
return strings.Contains(info.WriteExpr, ".MarshalParcel")
}
// resolveFixedSizeExpr converts an AIDL fixed-size array dimension to a Go
// expression. Numeric literals (e.g. "128") pass through unchanged. Constant
// names (e.g. "BYTE_SIZE_OF_CACHE_TOKEN") are resolved to the Go form by
// prepending the struct name prefix and wrapping in int() since
// WriteFixedByteArray/ReadFixedByteArray take int, but AIDL constants are
// typed as int32.
func resolveFixedSizeExpr(
fixedSize string,
structName string,
) string {
if len(fixedSize) == 0 {
return fixedSize
}
// Numeric literals start with a digit and need no transformation.
// Go untyped integer constants are compatible with int parameters.
if fixedSize[0] >= '0' && fixedSize[0] <= '9' {
return fixedSize
}
return "int(" + structName + AIDLToGoName(fixedSize) + ")"
}
// javaWireMethodInfo maps JavaWireField.WriteMethod values to the parcel
// method names for writing and reading.
type javaWireMethodInfo struct {
writeMethod string
readMethod string
zeroValue string // Go zero literal for placeholder writes.
}
var javaWireMethodMap = map[string]javaWireMethodInfo{
"bool": {writeMethod: "WriteBool", readMethod: "ReadBool", zeroValue: "false"},
"int32": {writeMethod: "WriteInt32", readMethod: "ReadInt32", zeroValue: "0"},
"int64": {writeMethod: "WriteInt64", readMethod: "ReadInt64", zeroValue: "0"},
"float32": {writeMethod: "WriteFloat32", readMethod: "ReadFloat32", zeroValue: "0"},
"float64": {writeMethod: "WriteFloat64", readMethod: "ReadFloat64", zeroValue: "0"},
"string8": {writeMethod: "WriteString", readMethod: "ReadString", zeroValue: `""`},
"string16": {writeMethod: "WriteString16", readMethod: "ReadString16", zeroValue: `""`},
}
// javaWireConditionToGo converts a spec condition like "FieldsMask & 256"
// into a Go boolean expression like "s.FieldsMask & 256 != 0".
// The field name in the condition is converted to PascalCase via AIDLToGoName.
// isJavaWireNumericLiteral returns true if s is a decimal integer literal,
// singularize returns the singular form of a simple plural English word
// by stripping a trailing 's'. Used to derive item struct names from
// repeated field names (e.g., "items" → "item" → "ClipDataItem").
func singularize(s string) string {
if len(s) > 1 && s[len(s)-1] == 's' {
return s[:len(s)-1]
}
return s
}
// isValidGoFieldName reports whether s can be used as a Go struct field name.
// Names containing characters like '?', ':', or spaces are not valid.
// These appear in JavaWireFormat for boolean-as-int fields (e.g.,
// "IsExternal?1:0") or dotted sub-field names (e.g.,
// "ViewBehavior.mShouldSmoothScroll").
func isValidGoFieldName(s string) bool {
if len(s) == 0 {
return false
}
for i, r := range s {
switch {
case r == '_' || unicode.IsLetter(r):
// valid
case i > 0 && unicode.IsDigit(r):
// valid
default:
return false
}
}
return true
}
// optionally negative (e.g., "0", "-1", "42"). These appear as field names
// in JavaWireFormat when Java writes a literal value (e.g., writeInt(-1)).
func isJavaWireNumericLiteral(s string) bool {
if len(s) == 0 {
return false
}
start := 0
if s[0] == '-' {
start = 1
}
if start >= len(s) {
return false
}
for i := start; i < len(s); i++ {
if s[i] < '0' || s[i] > '9' {
return false
}
}
return true
}
func javaWireConditionToGo(condition string) string {
parts := strings.SplitN(condition, " & ", 2)
if len(parts) != 2 {
return condition
}
return fmt.Sprintf("s.%s & %s != 0", AIDLToGoName(parts[0]), parts[1])
}
// writeJavaWireMarshalParcel generates a MarshalParcel method that follows
// the Java writeToParcel() wire format, including conditional fields.
// Java-defined parcelables do not use the AIDL header/footer framing;
// fields are written directly (matching the handwritten writeToParcel).
func writeJavaWireMarshalParcel(
f *GoFile,
structName string,
wireFields []parser.JavaWireField,
typeRef *TypeRefResolver,
) {
f.P("func (s *%s) MarshalParcel(", structName)
f.P("\tp *parcel.Parcel,")
f.P(") error {")
for _, wf := range wireFields {
// delegate field: inline marshal without nullable wrapper.
if wf.WriteMethod == "delegate" && wf.GoType != "" {
goType := resolveJavaWireGoType(typeRef, wf.GoType)
if goType == "" {
continue
}
goName := AIDLToGoName(wf.Name)
if wf.Condition == "_null_flag" || goType == structName {
// Nullable or self-referencing delegate: pointer field
// with int32 null flag.
f.P("\tif s.%s != nil {", goName)
f.P("\t\tp.WriteInt32(1)")
f.P("\t\tif _err := s.%s.MarshalParcel(p); _err != nil {", goName)
f.P("\t\t\treturn _err")
f.P("\t\t}")
f.P("\t} else {")
f.P("\t\tp.WriteInt32(0)")
f.P("\t}")
} else {
f.P("\tif _err := s.%s.MarshalParcel(p); _err != nil {", goName)
f.P("\t\treturn _err")
f.P("\t}")
}
continue
}
// typed_object field with a resolved parcelable type:
// generate nullable marshal (int32 flag + MarshalParcel).
if wf.WriteMethod == "typed_object" && wf.GoType != "" {
goType := resolveJavaWireGoType(typeRef, wf.GoType)
if goType == "" {
// Unbreakable cycle — write null marker.
f.P("\tp.WriteInt32(0) // opaque: cycle prevents typed marshal")
continue