-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
1711 lines (1520 loc) · 46.6 KB
/
main.go
File metadata and controls
1711 lines (1520 loc) · 46.6 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
// Command spec2go generates Go source code from YAML spec files.
//
// It reads spec files produced by aidl2spec, converts them back to the
// parser AST types, and feeds them through the existing codegen.Generator
// to produce identical Go output without requiring AIDL source files.
//
// Usage:
//
// spec2go -specs specs/ -output . [-smoke-tests] [-codes-output binder/versionaware/codes_gen.go] [-default-api 36]
package main
import (
"bytes"
"flag"
"fmt"
"go/format"
"os"
"path/filepath"
"sort"
"strings"
"unicode"
"github.com/AndroidGoLab/binder/binder"
"github.com/AndroidGoLab/binder/tools/pkg/codegen"
"github.com/AndroidGoLab/binder/tools/pkg/parser"
"github.com/AndroidGoLab/binder/tools/pkg/resolver"
"github.com/AndroidGoLab/binder/tools/pkg/spec"
)
func main() {
specsDir := flag.String("specs", "specs/", "Directory containing spec YAML files")
outputDir := flag.String("output", ".", "Output directory for generated Go files")
nativeImplsDir := flag.String("native-impls", "", "Directory containing hand-written native parcelable implementations")
smokeTests := flag.Bool("smoke-tests", false, "Generate smoke tests")
codesOutput := flag.String("codes-output", "", "Output path for codes_gen.go")
defaultAPI := flag.Int("default-api", 36, "Default API level")
flag.Parse()
if err := run(
*specsDir,
*outputDir,
*nativeImplsDir,
*smokeTests,
*codesOutput,
*defaultAPI,
); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
}
func run(
specsDir string,
outputDir string,
nativeImplsDir string,
smokeTests bool,
codesOutput string,
defaultAPI int,
) error {
fmt.Fprintf(os.Stderr, "Reading specs from %s...\n", specsDir)
specs, err := spec.ReadAllSpecs(specsDir)
if err != nil {
return fmt.Errorf("reading specs: %w", err)
}
fmt.Fprintf(os.Stderr, "Read %d package specs\n", len(specs))
// Build an index of parcelable short names → AIDL qualified names
// so that typed_object fields can be resolved to concrete Go types.
parcelableIndex := buildParcelableIndex(specs)
// Convert specs to parser AST and register in a type registry.
registry := resolver.NewTypeRegistry()
for _, ps := range specs {
registerPackageSpec(registry, ps, parcelableIndex)
}
allDefs := registry.All()
fmt.Fprintf(os.Stderr, "Registered %d definitions\n", len(allDefs))
// Create a resolver wrapping the pre-populated registry.
r := newRegistryResolver(registry)
// Generate Go code.
fmt.Fprintf(os.Stderr, "Generating Go code into %s...\n", outputDir)
gen := codegen.NewGenerator(r, outputDir)
gen.NativeImplsDir = nativeImplsDir
gen.SetSkipErrors(true)
if err := gen.GenerateAll(); err != nil {
// errors.Join returns an error implementing Unwrap() []error.
// Use comma-ok to avoid panicking if the error type changes.
multi, ok := err.(interface{ Unwrap() []error })
if !ok {
return fmt.Errorf("codegen failed: %w", err)
}
joinedErrs := multi.Unwrap()
fmt.Fprintf(os.Stderr, "Codegen completed with %d definition errors (skipped)\n", len(joinedErrs))
for _, e := range joinedErrs {
fmt.Fprintf(os.Stderr, " error: %v\n", e)
}
return fmt.Errorf("codegen produced %d definition errors", len(joinedErrs))
}
if smokeTests {
fmt.Fprintf(os.Stderr, "Generating smoke tests...\n")
if err := gen.GenerateAllSmokeTests(); err != nil {
smokeErrors := strings.Split(err.Error(), "\n")
fmt.Fprintf(os.Stderr, "Smoke test generation completed with %d errors (skipped)\n", len(smokeErrors))
}
}
// Generate service name constants and accessor files from the
// servicemanager spec, if present.
if err := generateServiceNamesFile(specs, outputDir); err != nil {
return fmt.Errorf("generating service names: %w", err)
}
if err := generateAccessorFiles(specs, outputDir); err != nil {
return fmt.Errorf("generating accessor files: %w", err)
}
if err := generateJavaConstantsFiles(specs, outputDir); err != nil {
return fmt.Errorf("generating java constants: %w", err)
}
genCount, err := countGoFiles(outputDir)
if err != nil {
return fmt.Errorf("counting Go files: %w", err)
}
fmt.Fprintf(os.Stderr, "Generated %d Go files\n", genCount)
// Generate codes_gen.go from version_codes in interface specs.
if codesOutput == "" {
return nil
}
return generateCodesFile(specs, codesOutput, defaultAPI)
}
// parcelableIndex maps a short parcelable name (e.g., "WorkSource") to its
// AIDL qualified name (e.g., "android.os.WorkSource"). When multiple
// parcelables share the same short name, none is stored (ambiguous).
type parcelableIndex map[string]string
// buildParcelableIndex scans all specs and builds a short name → qualified
// name index for parcelables that have a JavaWireFormat (i.e., are concrete
// types with marshal/unmarshal support).
func buildParcelableIndex(
specs map[string]*spec.PackageSpec,
) parcelableIndex {
idx := parcelableIndex{}
for _, ps := range specs {
for _, parc := range ps.Parcelables {
shortName := parc.Name
qualifiedName := ps.AIDLPackage + "." + parc.Name
if existing, ok := idx[shortName]; ok {
if existing != qualifiedName {
// Ambiguous: multiple parcelables with same short name.
idx[shortName] = ""
}
} else {
idx[shortName] = qualifiedName
}
}
}
return idx
}
// resolveDelegateName tries common name transformations to find a
// parcelable matching the delegate field name. For example, a field
// named "Locales" may correspond to the parcelable "LocaleList".
func resolveDelegateName(fieldName string, parcIdx parcelableIndex) string {
// Try: strip trailing 's' (plurals) and append "List".
// "Locales" → "Locale" + "List" → "LocaleList"
if len(fieldName) > 1 && fieldName[len(fieldName)-1] == 's' {
candidate := fieldName[:len(fieldName)-1] + "List"
if q := parcIdx[candidate]; q != "" {
return q
}
}
// Try: append "List" directly.
// "Foo" → "FooList"
if q := parcIdx[fieldName+"List"]; q != "" {
return q
}
// Try: append "Handle" — e.g. "User" → "UserHandle".
if q := parcIdx[fieldName+"Handle"]; q != "" {
return q
}
return ""
}
// delegateFieldName extracts a clean field name from a java_wire_format
// delegate name. Names like "This.notification" become "Notification".
// Names without a "This." prefix are returned as-is.
func delegateFieldName(name string) string {
if strings.HasPrefix(name, "This.") {
suffix := name[len("This."):]
if len(suffix) > 0 {
return strings.ToUpper(suffix[:1]) + suffix[1:]
}
}
return name
}
// isNullCheckCondition returns true if the condition is a Java-style null
// check like "this.tag!=null", "this.mInstanceId!=null", or "mFoo!=null".
// Both "this."-prefixed and bare field references are accepted since
// different Java classes use different conventions.
func isNullCheckCondition(cond string) bool {
return strings.HasSuffix(cond, "!=null")
}
// mergeNullFlagPairs preprocesses JavaWireFormat fields to merge the
// "flag + conditional data" pattern used for nullable fields in Java
// writeToParcel(). The pattern is:
//
// { name: "1", write_method: int32, condition: "this.xxx!=null" } ← flag
// { name: FieldName, write_method: ..., condition: "this.xxx!=null" } ← data
//
// This merges into a single field with condition "_null_flag", meaning
// the codegen should emit: read int32 flag, then conditionally read/write data.
func mergeNullFlagPairs(fields []spec.JavaWireField) []spec.JavaWireField {
var result []spec.JavaWireField
for i := 0; i < len(fields); i++ {
f := fields[i]
// Detect flag field: numeric literal int32 with null-check condition.
if isNumericLiteral(f.Name) && f.WriteMethod == "int32" &&
isNullCheckCondition(f.Condition) &&
i+1 < len(fields) && fields[i+1].Condition == f.Condition {
// Merge: skip the flag field, mark the data field with _null_flag.
i++
merged := fields[i]
merged.Condition = "_null_flag"
result = append(result, merged)
continue
}
result = append(result, f)
}
return result
}
// registerPackageSpec converts all definitions in a PackageSpec to parser
// AST types and registers them in the type registry.
func registerPackageSpec(
registry *resolver.TypeRegistry,
ps *spec.PackageSpec,
parcIdx parcelableIndex,
) {
for _, iface := range ps.Interfaces {
qualifiedName := ps.AIDLPackage + "." + iface.Name
def := convertInterfaceToAST(iface)
registry.Register(qualifiedName, def)
}
for _, parc := range ps.Parcelables {
qualifiedName := ps.AIDLPackage + "." + parc.Name
def := convertParcelableToAST(parc, ps.AIDLPackage, parcIdx)
registry.Register(qualifiedName, def)
}
for _, enum := range ps.Enums {
qualifiedName := ps.AIDLPackage + "." + enum.Name
def := convertEnumToAST(enum)
registry.Register(qualifiedName, def)
}
for _, union := range ps.Unions {
qualifiedName := ps.AIDLPackage + "." + union.Name
def := convertUnionToAST(union)
registry.Register(qualifiedName, def)
}
}
// convertInterfaceToAST converts an InterfaceSpec back to a parser.InterfaceDecl.
func convertInterfaceToAST(
iface spec.InterfaceSpec,
) *parser.InterfaceDecl {
decl := &parser.InterfaceDecl{
IntfName: iface.Name,
Oneway: iface.Oneway,
Annots: convertAnnotationNamesToAST(iface.Annotations),
}
for _, m := range iface.Methods {
decl.Methods = append(decl.Methods, convertMethodToAST(m))
}
for _, c := range iface.Constants {
decl.Constants = append(decl.Constants, convertConstantToAST(c))
}
return decl
}
// convertMethodToAST converts a MethodSpec back to a parser.MethodDecl.
func convertMethodToAST(
m spec.MethodSpec,
) *parser.MethodDecl {
decl := &parser.MethodDecl{
MethodName: m.Name,
Oneway: m.Oneway,
// Set TransactionID = offset + 1 so ComputeTransactionCodes produces
// the correct offset. TransactionID is 1-based in the parser; 0 means
// auto-assign. By making every method "explicit", the counter resets
// correctly for each method.
TransactionID: m.TransactionCodeOffset + 1,
Annots: convertAnnotationNamesToAST(m.Annotations),
}
if m.ReturnType.Name != "" {
decl.ReturnType = convertTypeRefToAST(m.ReturnType)
}
for _, p := range m.Params {
decl.Params = append(decl.Params, convertParamToAST(p))
}
return decl
}
// convertParamToAST converts a ParamSpec back to a parser.ParamDecl.
func convertParamToAST(
p spec.ParamSpec,
) *parser.ParamDecl {
decl := &parser.ParamDecl{
ParamName: p.Name,
Type: convertTypeRefToAST(p.Type),
Annots: convertAnnotationNamesToAST(p.Annotations),
MinAPILevel: p.MinAPILevel,
MaxAPILevel: p.MaxAPILevel,
}
switch p.Direction {
case spec.DirectionIn:
decl.Direction = parser.DirectionIn
case spec.DirectionOut:
decl.Direction = parser.DirectionOut
case spec.DirectionInOut:
decl.Direction = parser.DirectionInOut
default:
decl.Direction = parser.DirectionNone
}
return decl
}
// convertTypeRefToAST converts a TypeRef back to a parser.TypeSpecifier.
func convertTypeRefToAST(
tr spec.TypeRef,
) *parser.TypeSpecifier {
ts := &parser.TypeSpecifier{
Name: tr.Name,
IsArray: tr.IsArray,
FixedSize: tr.FixedSize,
}
if tr.IsNullable {
ts.Annots = append(ts.Annots, &parser.Annotation{Name: "nullable"})
}
// Restore type-level annotations beyond @nullable.
for _, name := range tr.Annotations {
ts.Annots = append(ts.Annots, &parser.Annotation{Name: name})
}
for _, arg := range tr.TypeArgs {
ts.TypeArgs = append(ts.TypeArgs, convertTypeRefToAST(arg))
}
return ts
}
// javaWireTypeToAIDL maps JavaWireField.WriteMethod values to the AIDL type
// name used by the parser/codegen (matching marshalPrimitiveMap keys).
var javaWireTypeToAIDL = map[string]string{
"bool": "boolean",
"int32": "int",
"int64": "long",
"float32": "float",
"float64": "double",
"string8": "String", // UTF-8
"string16": "String", // UTF-16
}
// isValidJavaWireFieldName returns true if the name is a simple identifier
// suitable for use as a Go struct field (no dots, parens, or Java-isms).
// isNumericLiteral returns true if the string is a decimal integer literal
// (optionally negative), e.g., "0", "-1", "42".
func isNumericLiteral(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 isValidJavaWireFieldName(name string) bool {
if len(name) == 0 {
return false
}
for i, r := range name {
if i == 0 {
if !unicode.IsLetter(r) && r != '_' {
return false
}
} else {
if !unicode.IsLetter(r) && !unicode.IsDigit(r) && r != '_' {
return false
}
}
}
return true
}
// isResolvableJavaWireCondition returns true if the condition is a simple
// "FieldName & number" bitmask pattern that can be translated to Go.
func isResolvableJavaWireCondition(condition string) bool {
if condition == "" {
return true
}
if condition == "_null_flag" {
return true
}
parts := strings.SplitN(condition, " & ", 2)
if len(parts) != 2 {
return false
}
return isValidJavaWireFieldName(parts[0])
}
// convertParcelableToAST converts a ParcelableSpec back to a parser.ParcelableDecl.
// currentPkg is the AIDL package of the parcelable being converted.
// parcIdx maps short parcelable names to AIDL qualified names, used
// to resolve typed_object fields to concrete struct fields.
func convertParcelableToAST(
parc spec.ParcelableSpec,
currentPkg string,
parcIdx parcelableIndex,
) *parser.ParcelableDecl {
decl := &parser.ParcelableDecl{
ParcName: parc.Name,
Annots: convertAnnotationNamesToAST(parc.Annotations),
NativeParcelable: parc.NativeParcelable,
}
for _, f := range parc.Fields {
decl.Fields = append(decl.Fields, convertFieldToAST(f))
}
// When a bare AIDL parcelable has no fields but does have a Java wire
// format extracted from writeToParcel(), synthesize struct fields from
// the wire format and store the wire layout for custom marshal/unmarshal.
if len(decl.Fields) == 0 && len(parc.JavaWireFormat) > 0 {
var wireFields []parser.JavaWireField
seenNames := map[string]int{} // track Go field names for dedup
jwfList := mergeNullFlagPairs(parc.JavaWireFormat)
for _, jwf := range jwfList {
// Strip "This." prefix from field names to get clean Go
// identifiers. Java writeToParcel often references fields
// as "this.field" → spec records them as "This.field".
cleanName := delegateFieldName(jwf.Name)
if cleanName != jwf.Name {
jwf.Name = cleanName
}
// repeated wire field: array-of-structs with sub-elements.
// Handle early before typed_object/delegate or knownType checks.
if jwf.WriteMethod == "repeated" && len(jwf.Elements) > 0 {
var elems []parser.JavaWireField
for _, e := range jwf.Elements {
elems = append(elems, parser.JavaWireField{
Name: e.Name,
WriteMethod: e.WriteMethod,
})
}
wireFields = append(wireFields, parser.JavaWireField{
Name: jwf.Name,
WriteMethod: "repeated",
Elements: elems,
})
continue
}
// Check if this field has a valid name and resolvable condition.
validName := isValidJavaWireFieldName(jwf.Name)
resolvableCond := isResolvableJavaWireCondition(jwf.Condition)
_, knownType := javaWireTypeToAIDL[jwf.WriteMethod]
// For typed_object/delegate fields with a valid name, check if
// the field name corresponds to a known parcelable in the specs.
// If found, store the AIDL qualified name in GoType so the
// codegen can generate a struct field with proper marshal/unmarshal.
//
// The struct field is NOT added to decl.Fields here — it's
// generated directly by the codegen from JavaWireField.GoType.
// This avoids adding import graph edges that could destabilize
// the cycle-breaking back-edge computation for unrelated packages.
if (jwf.WriteMethod == "typed_object" || jwf.WriteMethod == "delegate") && validName {
qualifiedName := parcIdx[jwf.Name]
if qualifiedName == "" && jwf.DelegateType != "" {
qualifiedName = parcIdx[jwf.DelegateType]
}
if qualifiedName == "" && jwf.WriteMethod == "delegate" {
qualifiedName = resolveDelegateName(jwf.Name, parcIdx)
}
if qualifiedName != "" {
goName := codegen.AIDLToGoName(jwf.Name)
seenNames[goName]++
dedupName := jwf.Name
if seenNames[goName] > 1 {
dedupName = fmt.Sprintf("%s%d", jwf.Name, seenNames[goName])
}
wireFields = append(wireFields, parser.JavaWireField{
Name: dedupName,
WriteMethod: jwf.WriteMethod, // preserve typed_object vs delegate
GoType: qualifiedName,
Condition: jwf.Condition,
})
continue
}
}
// Treat fields with invalid names, unresolvable conditions,
// or non-primitive types as opaque in the wire format.
// For non-primitive types (bundle, typed_object, etc.), preserve
// the specific write_method for correct null marker generation.
// For primitive types with unresolvable conditions (e.g., a bool
// field guarded by "hasGainmap()"), use the specific write_method
// but clear the condition — the codegen can't translate Java
// method calls to Go, and the field has no corresponding struct field.
if !validName || !resolvableCond || !knownType {
wm := jwf.WriteMethod
// Fields with unresolvable conditions or invalid names that
// are known primitive types need careful handling:
//
// - Invalid name + known type (e.g., "IsExternal?1:0" int32):
// keep the original write_method so the codegen reads and
// discards the correct number of bytes. Previously this
// converted to "typed_object", causing bool-as-int fields
// to be treated as null indicators, aborting deserialization
// when the value is 1.
//
// - Valid name + unresolvable condition + known type: convert
// to typed_object (these have struct fields that aren't
// conditionally writable from Go).
//
// - Unknown type: preserve the write_method as-is (bundle,
// typed_object, opaque).
if knownType && !isNumericLiteral(jwf.Name) && validName {
wm = "typed_object"
}
wireFields = append(wireFields, parser.JavaWireField{
Name: jwf.Name,
WriteMethod: wm,
})
continue
}
// Deduplicate Go field names by appending a numeric suffix.
goName := codegen.AIDLToGoName(jwf.Name)
seenNames[goName]++
dedupName := jwf.Name
if seenNames[goName] > 1 {
dedupName = fmt.Sprintf("%s%d", jwf.Name, seenNames[goName])
}
wireFields = append(wireFields, parser.JavaWireField{
Name: dedupName,
WriteMethod: jwf.WriteMethod,
Condition: jwf.Condition,
})
aidlType := javaWireTypeToAIDL[jwf.WriteMethod]
decl.Fields = append(decl.Fields, &parser.FieldDecl{
FieldName: dedupName,
Type: &parser.TypeSpecifier{Name: aidlType},
})
}
decl.JavaWireFormat = wireFields
}
for _, c := range parc.Constants {
decl.Constants = append(decl.Constants, convertConstantToAST(c))
}
return decl
}
// convertFieldToAST converts a FieldSpec back to a parser.FieldDecl.
func convertFieldToAST(
f spec.FieldSpec,
) *parser.FieldDecl {
decl := &parser.FieldDecl{
FieldName: f.Name,
Type: convertTypeRefToAST(f.Type),
Annots: convertAnnotationNamesToAST(f.Annotations),
}
if f.DefaultValue != "" {
decl.DefaultValue = parseConstExpr(f.DefaultValue)
}
return decl
}
// convertEnumToAST converts an EnumSpec back to a parser.EnumDecl.
func convertEnumToAST(
enum spec.EnumSpec,
) *parser.EnumDecl {
decl := &parser.EnumDecl{
EnumName: enum.Name,
Annots: convertAnnotationNamesToAST(enum.Annotations),
}
if enum.BackingType != "" {
decl.BackingType = &parser.TypeSpecifier{Name: enum.BackingType}
}
for _, e := range enum.Values {
enumerator := &parser.Enumerator{
Name: e.Name,
}
if e.Value != "" {
enumerator.Value = parseConstExpr(e.Value)
}
decl.Enumerators = append(decl.Enumerators, enumerator)
}
return decl
}
// convertUnionToAST converts a UnionSpec back to a parser.UnionDecl.
func convertUnionToAST(
union spec.UnionSpec,
) *parser.UnionDecl {
decl := &parser.UnionDecl{
UnionName: union.Name,
Annots: convertAnnotationNamesToAST(union.Annotations),
}
for _, f := range union.Fields {
decl.Fields = append(decl.Fields, convertFieldToAST(f))
}
for _, c := range union.Constants {
decl.Constants = append(decl.Constants, convertConstantToAST(c))
}
return decl
}
// convertConstantToAST converts a ConstantSpec back to a parser.ConstantDecl.
func convertConstantToAST(
c spec.ConstantSpec,
) *parser.ConstantDecl {
decl := &parser.ConstantDecl{
ConstName: c.Name,
}
if c.Type != "" {
decl.Type = &parser.TypeSpecifier{Name: c.Type}
}
if c.Value != "" {
decl.Value = parseConstExpr(c.Value)
}
return decl
}
// convertAnnotationNamesToAST converts annotation name strings back to
// parser.Annotation values.
func convertAnnotationNamesToAST(
names []string,
) []*parser.Annotation {
if len(names) == 0 {
return nil
}
annots := make([]*parser.Annotation, 0, len(names))
for _, name := range names {
annots = append(annots, &parser.Annotation{Name: name})
}
return annots
}
// parseConstExpr parses a string constant expression back to a parser.ConstExpr.
// This handles the string representations produced by aidl2spec's constExprToString.
func parseConstExpr(
value string,
) parser.ConstExpr {
value = strings.TrimSpace(value)
if value == "" {
return nil
}
// Boolean literals.
switch value {
case "true":
return &parser.BoolLiteral{Value: true}
case "false":
return &parser.BoolLiteral{Value: false}
case "null":
return &parser.NullLiteral{}
}
// String literals: "..."
if len(value) >= 2 && value[0] == '"' && value[len(value)-1] == '"' {
return &parser.StringLiteralExpr{Value: value[1 : len(value)-1]}
}
// Char literals: '...'
if len(value) >= 2 && value[0] == '\'' && value[len(value)-1] == '\'' {
return &parser.CharLiteralExpr{Value: value[1 : len(value)-1]}
}
// Try to parse as integer (decimal, hex, octal, binary).
// Accept optional AIDL suffixes (L, u32, etc.) by checking the
// stripped value, but keep the original for the literal.
if looksLikeInteger(value) {
return &parser.IntegerLiteral{Value: value}
}
// Parenthesized expressions: (...)
if len(value) >= 2 && value[0] == '(' && value[len(value)-1] == ')' {
// Verify the parens are balanced (the closing paren matches the opening one).
if findMatchingParen(value) == len(value)-1 {
return parseConstExpr(value[1 : len(value)-1])
}
}
// Unary operators: -, +, ~, !
if len(value) > 1 {
switch value[0] {
case '-':
inner := value[1:]
if looksLikeInteger(inner) {
return &parser.UnaryExpr{
Op: parser.TokenMinus,
Operand: &parser.IntegerLiteral{Value: inner},
}
}
if looksLikeFloat(inner) {
return &parser.UnaryExpr{
Op: parser.TokenMinus,
Operand: &parser.FloatLiteral{Value: inner},
}
}
return &parser.UnaryExpr{
Op: parser.TokenMinus,
Operand: parseConstExpr(inner),
}
case '+':
return &parser.UnaryExpr{
Op: parser.TokenPlus,
Operand: parseConstExpr(value[1:]),
}
case '~':
return &parser.UnaryExpr{
Op: parser.TokenTilde,
Operand: parseConstExpr(value[1:]),
}
case '!':
return &parser.UnaryExpr{
Op: parser.TokenBang,
Operand: parseConstExpr(value[1:]),
}
}
}
// Float literals.
if looksLikeFloat(value) {
return &parser.FloatLiteral{Value: value}
}
// Binary expressions: "left OP right" — try to parse.
if expr := tryParseBinaryExpr(value); expr != nil {
return expr
}
// Ternary expressions: "cond ? then : else"
if expr := tryParseTernaryExpr(value); expr != nil {
return expr
}
// Everything else is an identifier reference.
return &parser.IdentExpr{Name: value}
}
// looksLikeInteger returns true if the value looks like an integer literal
// (decimal, hex, octal, or binary), optionally with AIDL type suffixes.
func looksLikeInteger(
value string,
) bool {
if len(value) == 0 {
return false
}
s := value
// Strip known AIDL integer suffixes.
for _, suffix := range []string{"u64", "u32", "u16", "u8", "i64", "i32", "i16", "i8", "L", "l"} {
if strings.HasSuffix(s, suffix) {
s = s[:len(s)-len(suffix)]
break
}
}
if len(s) == 0 {
return false
}
// Hex: 0x...
if len(s) > 2 && s[0] == '0' && (s[1] == 'x' || s[1] == 'X') {
for _, c := range s[2:] {
if !isHexDigit(c) {
return false
}
}
return len(s) > 2
}
// Binary: 0b...
if len(s) > 2 && s[0] == '0' && (s[1] == 'b' || s[1] == 'B') {
for _, c := range s[2:] {
if c != '0' && c != '1' {
return false
}
}
return len(s) > 2
}
// Decimal digits.
for _, c := range s {
if c < '0' || c > '9' {
return false
}
}
return true
}
func isHexDigit(c rune) bool {
return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F')
}
// looksLikeFloat returns true if the value looks like a floating-point literal.
// This includes values with a dot, exponent, or Java/AIDL float suffix
// (e.g., "1.0", "1e5", "1f", "1.5d"), as well as hex floats (e.g., "0x1.Ap+3").
func looksLikeFloat(
value string,
) bool {
if len(value) == 0 {
return false
}
// Hex float: 0x<hex>[.<hex>]p[+-]<dec>[fFdD]
if len(value) > 2 && value[0] == '0' && (value[1] == 'x' || value[1] == 'X') {
return looksLikeHexFloat(value)
}
s := value
hasSuffix := false
// Strip Java/AIDL float suffixes.
last := s[len(s)-1]
if last == 'f' || last == 'F' || last == 'd' || last == 'D' {
s = s[:len(s)-1]
hasSuffix = true
}
hasDot := false
hasE := false
hasDigit := false
for i, c := range s {
switch {
case c >= '0' && c <= '9':
hasDigit = true
case c == '.':
if hasDot || hasE {
return false
}
hasDot = true
case c == 'e' || c == 'E':
if hasE || !hasDigit {
return false
}
hasE = true
case c == '+' || c == '-':
if i == 0 || (s[i-1] != 'e' && s[i-1] != 'E') {
return false
}
default:
return false
}
}
// A float needs digits plus at least one float indicator: dot, exponent, or suffix.
return hasDigit && (hasDot || hasE || hasSuffix)
}
// looksLikeHexFloat returns true if the value looks like a hex float literal
// (e.g., "0x1.Ap+3", "0xABp-2f"). Hex floats require a binary exponent (p/P).
func looksLikeHexFloat(
value string,
) bool {
s := value[2:] // skip "0x"/"0X"
if len(s) == 0 {
return false
}
// Strip optional float suffix.
last := s[len(s)-1]
if last == 'f' || last == 'F' || last == 'd' || last == 'D' {
s = s[:len(s)-1]
}
// Must contain 'p' or 'P' (binary exponent).
pIdx := strings.IndexAny(s, "pP")
if pIdx < 0 {
return false
}
mantissa := s[:pIdx]
exponent := s[pIdx+1:]
// Mantissa: hex digits with optional dot.
hasHexDigit := false
for _, c := range mantissa {
switch {
case isHexDigit(c):
hasHexDigit = true
case c == '.':
// allow dot
default:
return false
}
}
if !hasHexDigit {
return false
}
// Exponent: optional sign, then decimal digits.
if len(exponent) == 0 {
return false
}
if exponent[0] == '+' || exponent[0] == '-' {
exponent = exponent[1:]
}
if len(exponent) == 0 {
return false
}
for _, c := range exponent {
if c < '0' || c > '9' {
return false
}
}
return true
}
// binaryOpGroup is a set of operators at the same precedence level.
// Within a group, the rightmost match is used so that left-to-right
// associativity is preserved (e.g., "a - b + c" → "(a - b) + c").
type binaryOpGroup struct {
Ops []struct {
Symbol string
Token parser.TokenKind
}
}
// binaryOpGroups lists operator groups from lowest to highest precedence.
// Multi-character operators must appear before single-character operators
// that are their prefixes within the same group (e.g., ">=" before ">").
var binaryOpGroups = []binaryOpGroup{
{Ops: []struct {
Symbol string
Token parser.TokenKind
}{
{"||", parser.TokenPipePipe},
}},
{Ops: []struct {
Symbol string
Token parser.TokenKind
}{
{"&&", parser.TokenAmpAmp},
}},
{Ops: []struct {
Symbol string
Token parser.TokenKind
}{
{"|", parser.TokenPipe},