-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
3167 lines (2823 loc) · 90.6 KB
/
main.go
File metadata and controls
3167 lines (2823 loc) · 90.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 spec2cli reads YAML spec files (produced by aidl2spec) and
// generates registry_gen.go and commands_gen.go for the bindercli tool.
// It replaces genbindercli, which scanned Go AST instead of specs.
//
// Usage:
//
// spec2cli -specs specs/ -output cmd/bindercli/
package main
import (
"bytes"
"flag"
"fmt"
"go/format"
"os"
"os/exec"
"path/filepath"
"sort"
"strings"
"unicode"
"github.com/AndroidGoLab/binder/tools/pkg/codegen"
"github.com/AndroidGoLab/binder/tools/pkg/parser"
"github.com/AndroidGoLab/binder/tools/pkg/spec"
)
const (
modulePath = "github.com/AndroidGoLab/binder"
// legacyInterfaceType is the legacy spelling of "any" produced by
// the codegen library for unresolvable types. Spelled as a
// concatenation so that automated sweeps do not break source
// scanning logic that must still match existing generated code.
legacyInterfaceType = "interface" + "{}"
// svcProxyVarPrefix is the "svcProxy." prefix used when scanning
// generated Go source to locate proxy method calls.
svcProxyVarPrefix = "svcProxy."
)
// primitiveTypes maps Go type names to cobra flag helpers.
var primitiveTypes = map[string]flagInfo{
"string": {FlagMethod: "String", GetMethod: "GetString", ZeroVal: `""`},
"bool": {FlagMethod: "Bool", GetMethod: "GetBool", ZeroVal: "false"},
"int32": {FlagMethod: "Int32", GetMethod: "GetInt32", ZeroVal: "0"},
"int64": {FlagMethod: "Int64", GetMethod: "GetInt64", ZeroVal: "0"},
"float32": {FlagMethod: "Float32", GetMethod: "GetFloat32", ZeroVal: "0"},
"float64": {FlagMethod: "Float64", GetMethod: "GetFloat64", ZeroVal: "0"},
"byte": {FlagMethod: "Uint8", GetMethod: "GetUint8", ZeroVal: "0"},
"uint16": {FlagMethod: "Uint16", GetMethod: "GetUint16", ZeroVal: "0"},
}
// primitiveArrayElemTypes lists element types that can appear in
// comma-separated array flags.
var primitiveArrayElemTypes = map[string]struct{}{
"int32": {},
"int64": {},
"bool": {},
"float32": {},
"float64": {},
}
type flagInfo struct {
FlagMethod string
GetMethod string
ZeroVal string
}
// interfaceInfo holds metadata for one AIDL interface, derived from specs.
type interfaceInfo struct {
Descriptor string
ProxyConstructor string // e.g. "NewActivityManagerProxy"
ProxyType string // e.g. "ActivityManagerProxy"
ImportPath string // e.g. "github.com/AndroidGoLab/binder/android/app"
PkgName string // e.g. "app"
Methods []methodInfo
}
type methodInfo struct {
Name string
Params []paramInfo // excluding ctx
ReturnType string // empty if error-only
}
type paramInfo struct {
Name string
Type string
IsOut bool // true for "out" params — passed as zero values, no CLI flag
}
// structField describes one field inside a known struct type.
type structField struct {
Name string
Type string
}
// structInfo holds metadata for a known parcelable struct.
type structInfo struct {
Fields []structField
ImportPath string
PkgName string
Promoted bool // true if promoted from knownGoTypes (not in spec)
}
// typeKind classifies a parameter type for code generation.
type typeKind int
const (
kindUnsupported typeKind = iota
kindPrimitive
kindPrimitiveArray // []byte, []string, []int32, etc.
kindStruct // known parcelable struct
kindEnum // type Foo int32
kindBinderIBinder // binder.IBinder
kindInterface // any
kindInterfaceType // IFoo or pkg.IFoo (AIDL interface)
kindNullable // *T where T is supported
kindMap // map[K]V
kindComplexArray // []SomeStruct, []any, etc.
kindNullablePrimitive // *int32, *string, etc.
)
// knownStructs maps "importPath:TypeName" -> structInfo.
var knownStructs map[string]*structInfo
// knownEnums maps "importPath:TypeName" -> true.
var knownEnums map[string]bool
// knownServiceNames maps AIDL interface descriptors to their well-known
// Android ServiceManager names.
var knownServiceNames map[string]string
// knownInterfaces maps AIDL descriptors to interfaceInfo, used for
// resolving interface types (kindInterfaceType) in other packages.
var knownInterfaces map[string]*interfaceInfo
// knownInterfaceGoTypes maps "importPath:GoTypeName" -> true for every
// known interface. Used by classifyType/classifyFieldType to verify
// that an AIDL-named type actually has generated Go code before
// returning kindInterfaceType.
var knownInterfaceGoTypes map[string]bool
// subInterfaceDescriptors is the set of AIDL descriptors that are
// returned by methods on other interfaces but are NOT registered with
// ServiceManager. These cannot be discovered by findServiceByDescriptor
// and are excluded from top-level CLI command generation.
var subInterfaceDescriptors map[string]bool
// knownGoProxyMethods maps "importPath:MethodName" -> param count
// (excluding ctx) for every method found on proxy types in the Go
// source. A value of -1 means the method exists but param count
// could not be determined.
var knownGoProxyMethods map[string]int
// knownGoProxyConstructors maps "importPath:NewFooProxy" -> true for
// every proxy constructor found in the Go source.
var knownGoProxyConstructors map[string]bool
// goProxyMethodsWithInterfaceParams maps "importPath:MethodName" -> true
// for proxy methods that have at least one parameter using any or
// []any in the Go source.
var goProxyMethodsWithInterfaceParams map[string]bool
// goProxyMethodParamTypes maps "importPath:MethodName" -> list of Go
// parameter type strings (excluding ctx). Used to validate that
// generated code passes the correct types to proxy methods.
var goProxyMethodParamTypes map[string][]string
// knownGoTypes maps "importPath:TypeName" -> true for every type
// declaration found in Go source files. Used to validate that spec
// types (structs, enums) actually exist in Go code.
var knownGoTypes map[string]string
// typeByShortName maps a bare Go type name (e.g. "AttributionSource")
// to its full key "importPath:TypeName". This enables cross-package
// type resolution when a method parameter references a type defined in
// a different package. When multiple packages define the same short
// name, the entry is set to "" (ambiguous) and resolution falls back
// to same-package or promoted types.
var typeByShortName map[string]string
func main() {
specsDir := flag.String("specs", "specs/", "Directory containing spec YAML files")
outputDir := flag.String("output", "cmd/bindercli/", "Output directory for generated files")
flag.Parse()
if err := run(*specsDir, *outputDir); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
}
// findModuleRoot walks up from the current directory to find go.mod.
func findModuleRoot() (string, error) {
dir, err := os.Getwd()
if err != nil {
return "", err
}
for {
if _, err := os.Stat(filepath.Join(dir, "go.mod")); err == nil {
return dir, nil
}
parent := filepath.Dir(dir)
if parent == dir {
return "", fmt.Errorf("go.mod not found")
}
dir = parent
}
}
// scanGoProxyMethods scans Go source files under moduleRoot to find
// proxy constructor functions (func New*Proxy) and proxy methods
// (func (p *FooProxy) MethodName). It populates knownGoProxyMethods
// and knownGoProxyConstructors.
func scanGoProxyMethods(
moduleRoot string,
) error {
knownGoProxyMethods = map[string]int{}
knownGoProxyConstructors = map[string]bool{}
goProxyMethodParamTypes = map[string][]string{}
goProxyMethodsWithInterfaceParams = map[string]bool{}
knownGoTypes = map[string]string{}
return filepath.Walk(moduleRoot, func(path string, info os.FileInfo, err error) error {
if err != nil {
return nil
}
if info.IsDir() {
base := filepath.Base(path)
switch base {
case ".git", "vendor", "tools", "cmd", "specs":
return filepath.SkipDir
}
return nil
}
if !strings.HasSuffix(path, ".go") || strings.HasSuffix(path, "_test.go") {
return nil
}
relDir, relErr := filepath.Rel(moduleRoot, filepath.Dir(path))
if relErr != nil {
fmt.Fprintf(os.Stderr, "warning: filepath.Rel(%s, %s): %v\n", moduleRoot, filepath.Dir(path), relErr)
return nil
}
importPath := modulePath + "/" + relDir
data, err := os.ReadFile(path)
if err != nil {
return nil
}
lines := strings.Split(string(data), "\n")
for i, line := range lines {
switch {
case strings.HasPrefix(line, "func ("):
// Proxy method: func (p *FooProxy) MethodName(
if !strings.Contains(line, "Proxy)") {
continue
}
closeParen := strings.Index(line, ")")
if closeParen < 0 {
continue
}
rest := strings.TrimSpace(line[closeParen+1:])
openParen := strings.Index(rest, "(")
if openParen < 0 {
continue
}
methodName := strings.TrimSpace(rest[:openParen])
if methodName == "" || methodName[0] < 'A' || methodName[0] > 'Z' {
continue
}
// Count params by scanning subsequent lines.
// Each param is on its own line; ctx is the first.
paramCount := countMethodParams(lines, i)
paramTypes := extractMethodParamTypes(lines, i)
methodKey := importPath + ":" + methodName
knownGoProxyMethods[methodKey] = paramCount
goProxyMethodParamTypes[methodKey] = paramTypes
// Check if any param uses any or []any (or legacy equivalents).
if methodHasInterfaceParam(lines, i) {
goProxyMethodsWithInterfaceParams[methodKey] = true
}
case strings.HasPrefix(line, "func "):
// Proxy constructor: func NewFooProxy(
rest := line[len("func "):]
openParen := strings.Index(rest, "(")
if openParen < 0 {
continue
}
funcName := rest[:openParen]
if strings.HasPrefix(funcName, "New") && strings.HasSuffix(funcName, "Proxy") {
knownGoProxyConstructors[importPath+":"+funcName] = true
}
case strings.HasPrefix(line, "type "):
// Type declaration: type FooType struct/int32/etc.
rest := line[len("type "):]
spaceIdx := strings.IndexByte(rest, ' ')
if spaceIdx < 0 {
continue
}
typeName := rest[:spaceIdx]
if typeName == "" || typeName[0] < 'A' || typeName[0] > 'Z' {
continue
}
typeKeyword := strings.TrimSpace(rest[spaceIdx+1:])
if idx := strings.IndexByte(typeKeyword, ' '); idx >= 0 {
typeKeyword = typeKeyword[:idx]
}
if idx := strings.IndexByte(typeKeyword, '{'); idx >= 0 {
typeKeyword = typeKeyword[:idx]
}
knownGoTypes[importPath+":"+typeName] = typeKeyword
}
}
return nil
})
}
// countMethodParams counts the number of non-ctx parameters in a
// proxy method declaration. It scans lines starting from the func
// declaration line. Returns -1 if the count can't be determined.
func countMethodParams(
lines []string,
funcLineIdx int,
) int {
// Find the opening "(" of the params (after the method name).
line := lines[funcLineIdx]
// The line looks like: func (p *FooProxy) MethodName(
// Find the last "(" on the line (the param list opening).
lastOpen := strings.LastIndex(line, "(")
if lastOpen < 0 {
return -1
}
// Check if all params are on this one line.
paramPart := line[lastOpen+1:]
if idx := strings.Index(paramPart, ")"); idx >= 0 {
paramPart = strings.TrimSpace(paramPart[:idx])
if paramPart == "" {
return 0
}
count := strings.Count(paramPart, ",") + 1
// Subtract ctx.
if count > 0 {
count--
}
return count
}
// Multi-line: count lines until we hit ")".
count := 0
// The part after "(" on the func line may contain the first param.
if trimmed := strings.TrimSpace(paramPart); trimmed != "" {
count++
}
for j := funcLineIdx + 1; j < len(lines); j++ {
trimmed := strings.TrimSpace(lines[j])
if strings.HasPrefix(trimmed, ")") {
break
}
if trimmed != "" {
count++
}
}
// Subtract ctx.
if count > 0 {
count--
}
return count
}
// extractMethodParamTypes returns the Go type strings of each non-ctx
// parameter in a proxy method declaration. Each element is the raw Go
// type text (e.g., "face.Feature", "int32", "[]common.AudioUuid").
func extractMethodParamTypes(
lines []string,
funcLineIdx int,
) []string {
var types []string
skippedCtx := false
// Collect parameter lines.
line := lines[funcLineIdx]
lastOpen := strings.LastIndex(line, "(")
if lastOpen < 0 {
return nil
}
paramPart := line[lastOpen+1:]
// Single-line case.
if idx := strings.Index(paramPart, ")"); idx >= 0 {
paramPart = strings.TrimSpace(paramPart[:idx])
if paramPart == "" {
return nil
}
for _, seg := range strings.Split(paramPart, ",") {
seg = strings.TrimSpace(seg)
if seg == "" {
continue
}
fields := strings.Fields(seg)
if len(fields) < 2 {
continue
}
goType := fields[len(fields)-1]
if !skippedCtx {
skippedCtx = true
continue
}
types = append(types, goType)
}
return types
}
// Multi-line case.
if trimmed := strings.TrimSpace(paramPart); trimmed != "" {
fields := strings.Fields(strings.TrimSuffix(trimmed, ","))
if len(fields) >= 2 {
goType := fields[len(fields)-1]
if !skippedCtx {
skippedCtx = true
} else {
types = append(types, goType)
}
}
}
for j := funcLineIdx + 1; j < len(lines); j++ {
trimmed := strings.TrimSpace(lines[j])
if strings.HasPrefix(trimmed, ")") {
break
}
if trimmed == "" {
continue
}
trimmed = strings.TrimSuffix(trimmed, ",")
fields := strings.Fields(trimmed)
if len(fields) < 2 {
continue
}
goType := fields[len(fields)-1]
if !skippedCtx {
skippedCtx = true
continue
}
types = append(types, goType)
}
return types
}
// methodHasInterfaceParam checks whether a proxy method declaration (starting
// at funcLineIdx) has any parameter typed as any (or the legacy equivalent).
func methodHasInterfaceParam(
lines []string,
funcLineIdx int,
) bool {
line := lines[funcLineIdx]
lastOpen := strings.LastIndex(line, "(")
if lastOpen < 0 {
return false
}
paramPart := line[lastOpen+1:]
if idx := strings.Index(paramPart, ")"); idx >= 0 {
return containsAnyType(paramPart[:idx])
}
for j := funcLineIdx + 1; j < len(lines); j++ {
trimmed := strings.TrimSpace(lines[j])
if strings.HasPrefix(trimmed, ")") {
break
}
if containsAnyType(trimmed) {
return true
}
}
return false
}
// containsAnyType reports whether s contains a parameter typed as "any"
// or the legacy "interface{}" spelling. We look for word-boundary patterns
// so that "any" inside identifiers (e.g. "company") does not match.
func containsAnyType(s string) bool {
if strings.Contains(s, legacyInterfaceType) {
return true
}
// Match "any" as a standalone type token: preceded by a space and
// followed by a comma, closing paren, or space.
for _, pat := range []string{" any,", " any)", " any "} {
if strings.Contains(s, pat) {
return true
}
}
return false
}
func run(
specsDir string,
outputDir string,
) 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))
// Detect module root and scan existing Go proxy methods.
root, err := findModuleRoot()
if err != nil {
return fmt.Errorf("finding module root: %w", err)
}
if err := scanGoProxyMethods(root); err != nil {
return fmt.Errorf("scanning Go proxy methods: %w", err)
}
fmt.Fprintf(os.Stderr, "Scanned Go proxy methods: %d\n", len(knownGoProxyMethods))
knownStructs = map[string]*structInfo{}
knownEnums = map[string]bool{}
knownServiceNames = map[string]string{}
knownInterfaces = map[string]*interfaceInfo{}
knownInterfaceGoTypes = map[string]bool{}
// Phase 1: collect structs, enums, and service mappings from all specs.
for _, ps := range specs {
importPath := modulePath + "/" + ps.GoPackage
pkgName := filepath.Base(ps.GoPackage)
collectStructsAndEnums(ps, importPath, pkgName)
collectServiceMappings(ps)
}
// Validate spec types against actual Go source: remove structs
// and enums that don't have corresponding Go type declarations.
for key := range knownStructs {
if knownGoTypes[key] == "" {
delete(knownStructs, key)
}
}
for key := range knownEnums {
if knownGoTypes[key] == "" {
delete(knownEnums, key)
}
}
// Build cross-package type lookup: map bare Go type name to its
// full "importPath:TypeName" key. Entries that appear in multiple
// packages are marked ambiguous (empty string) since we cannot
// determine which one is intended without full AIDL import context.
typeByShortName = map[string]string{}
for key := range knownStructs {
parts := strings.SplitN(key, ":", 2)
if len(parts) != 2 {
continue
}
shortName := parts[1]
if existing, ok := typeByShortName[shortName]; ok {
if existing != key {
typeByShortName[shortName] = "" // ambiguous
}
} else {
typeByShortName[shortName] = key
}
}
for key := range knownEnums {
parts := strings.SplitN(key, ":", 2)
if len(parts) != 2 {
continue
}
shortName := parts[1]
if existing, ok := typeByShortName[shortName]; ok {
if existing != key {
typeByShortName[shortName] = "" // ambiguous
}
} else {
typeByShortName[shortName] = key
}
}
fmt.Fprintf(os.Stderr, "Scanned struct types: %d\n", len(knownStructs))
fmt.Fprintf(os.Stderr, "Scanned enum types: %d\n", len(knownEnums))
fmt.Fprintf(os.Stderr, "Known service mappings: %d\n", len(knownServiceNames))
// Phase 2: build interface list and detect sub-interfaces.
//
// A sub-interface is one that appears as a return type of a method on
// another interface but is not registered with ServiceManager. These
// cannot be discovered via findServiceByDescriptor and should not get
// top-level CLI commands.
var interfaces []*interfaceInfo
// Collect all interface descriptors that appear as method return types.
// These are potential sub-interfaces (obtained via a parent, not via
// ServiceManager).
returnedDescriptors := map[string]bool{}
for _, ps := range specs {
for _, iface := range ps.Interfaces {
for _, m := range iface.Methods {
rt := m.ReturnType.Name
if rt == "" {
continue
}
// Qualify unqualified names with the current package.
if !strings.Contains(rt, ".") && ps.AIDLPackage != "" {
rt = ps.AIDLPackage + "." + rt
}
returnedDescriptors[rt] = true
}
}
}
for _, ps := range specs {
importPath := modulePath + "/" + ps.GoPackage
pkgName := filepath.Base(ps.GoPackage)
for _, iface := range ps.Interfaces {
ii := convertInterfaceSpec(iface, ps.AIDLPackage, importPath, pkgName)
interfaces = append(interfaces, ii)
knownInterfaces[ii.Descriptor] = ii
goName := codegen.AIDLToGoName(iface.Name)
knownInterfaceGoTypes[importPath+":"+goName] = true
}
}
// Validate interface types against Go source: remove entries
// that don't have corresponding Go type declarations.
for key := range knownInterfaceGoTypes {
if knownGoTypes[key] == "" {
delete(knownInterfaceGoTypes, key)
}
}
sort.Slice(interfaces, func(i, j int) bool {
return interfaces[i].Descriptor < interfaces[j].Descriptor
})
// Identify sub-interfaces: descriptors that appear as method return
// types but have no ServiceManager registration.
subInterfaceDescriptors = map[string]bool{}
for _, ii := range interfaces {
if _, hasMapping := knownServiceNames[ii.Descriptor]; hasMapping {
continue
}
if returnedDescriptors[ii.Descriptor] {
subInterfaceDescriptors[ii.Descriptor] = true
}
}
fmt.Fprintf(os.Stderr, "Sub-interfaces (excluded from CLI): %d\n", len(subInterfaceDescriptors))
// Phase 3: promote unclassified Go types.
//
// Some Go types exist in knownGoTypes but aren't in knownStructs,
// knownEnums, or knownInterfaceGoTypes. These are typically Java
// parcelables with no AIDL-defined fields (generated as empty
// structs in Go) or cross-package interface references. Promote
// them to the appropriate classification so they don't fall
// through to an unhandled case.
promotedStructs := 0
promotedInterfaces := 0
for key, typeKeyword := range knownGoTypes {
if knownStructs[key] != nil || knownEnums[key] || knownInterfaceGoTypes[key] {
continue
}
parts := strings.SplitN(key, ":", 2)
if len(parts) != 2 {
continue
}
importPath := parts[0]
pkgName := filepath.Base(importPath)
switch typeKeyword {
case "struct":
knownStructs[key] = &structInfo{
ImportPath: importPath,
PkgName: pkgName,
Promoted: true,
}
promotedStructs++
case "interface":
knownInterfaceGoTypes[key] = true
promotedInterfaces++
}
}
fmt.Fprintf(os.Stderr, "Promoted unclassified Go types: %d structs, %d interfaces\n", promotedStructs, promotedInterfaces)
// Extend typeByShortName with interfaces and promoted types that
// were added after the initial index was built.
for key := range knownInterfaceGoTypes {
parts := strings.SplitN(key, ":", 2)
if len(parts) != 2 {
continue
}
shortName := parts[1]
if existing, ok := typeByShortName[shortName]; ok {
if existing != key {
typeByShortName[shortName] = "" // ambiguous
}
} else {
typeByShortName[shortName] = key
}
}
for key := range knownStructs {
parts := strings.SplitN(key, ":", 2)
if len(parts) != 2 {
continue
}
shortName := parts[1]
if existing, ok := typeByShortName[shortName]; ok {
if existing != key {
typeByShortName[shortName] = "" // ambiguous
}
} else {
typeByShortName[shortName] = key
}
}
totalMethods := 0
commandableMethods := 0
for _, iface := range interfaces {
for _, m := range iface.Methods {
totalMethods++
if allParamsSupported(m, iface) {
commandableMethods++
}
}
}
pct := float64(0)
if totalMethods > 0 {
pct = float64(commandableMethods) / float64(totalMethods) * 100
}
fmt.Fprintf(os.Stderr, "Scanned interfaces: %d\n", len(interfaces))
fmt.Fprintf(os.Stderr, "Total methods: %d\n", totalMethods)
fmt.Fprintf(os.Stderr, "Generated commands for %d/%d methods (%.1f%%)\n", commandableMethods, totalMethods, pct)
if err := os.MkdirAll(outputDir, 0o755); err != nil {
return fmt.Errorf("creating output directory: %w", err)
}
if err := writeRegistryGen(outputDir, interfaces); err != nil {
return fmt.Errorf("writing registry_gen.go: %w", err)
}
genPkgs, err := writeCommandsGenPackages(outputDir, interfaces)
if err != nil {
return fmt.Errorf("writing gen packages: %w", err)
}
if err := writeRegisterGen(outputDir, genPkgs); err != nil {
return fmt.Errorf("writing register_gen.go: %w", err)
}
// Verify the generated code compiles. If not, identify broken
// methods and regenerate with them excluded.
if excluded := verifyAndExclude(outputDir); excluded > 0 {
fmt.Fprintf(os.Stderr, "Compile-check: excluded %d broken commands, regenerating...\n", excluded)
if err := writeRegistryGen(outputDir, interfaces); err != nil {
return fmt.Errorf("writing registry_gen.go (retry): %w", err)
}
genPkgs, err = writeCommandsGenPackages(outputDir, interfaces)
if err != nil {
return fmt.Errorf("writing gen packages (retry): %w", err)
}
if err := writeRegisterGen(outputDir, genPkgs); err != nil {
return fmt.Errorf("writing register_gen.go (retry): %w", err)
}
}
fmt.Fprintf(os.Stderr, "Generated gen packages and register_gen.go in %s\n", outputDir)
return nil
}
// verifyAndExclude runs `go build` on the generated packages. If it
// fails, parses error line numbers from commands.go files inside
// gen/<pkg>/ directories, identifies the enclosing command functions,
// and marks them as excluded (via goProxyMethodsWithInterfaceParams)
// so the next generation pass skips them. Returns the number of
// methods excluded.
func verifyAndExclude(outputDir string) int {
cmd := exec.Command("go", "build", "./"+outputDir)
out, err := cmd.CombinedOutput()
if err == nil {
return 0 // compiles fine
}
// Build a map of relative file path -> lines for all generated
// commands.go files inside gen subdirectories.
genDir := filepath.Join(outputDir, "gen")
genFiles := map[string][]string{}
filepath.Walk(genDir, func(path string, info os.FileInfo, walkErr error) error {
if walkErr != nil || info.IsDir() {
return nil
}
if filepath.Base(path) != "commands.go" {
return nil
}
data, readErr := os.ReadFile(path)
if readErr != nil {
return nil
}
genFiles[path] = strings.Split(string(data), "\n")
return nil
})
if len(genFiles) == 0 {
return 0
}
// Collect error line numbers per file.
type fileError struct {
filePath string
lineNo int
}
var fileErrors []fileError
for _, line := range strings.Split(string(out), "\n") {
for filePath := range genFiles {
if !strings.Contains(line, filePath+":") {
continue
}
idx := strings.Index(line, filePath+":")
rest := line[idx+len(filePath)+1:]
parts := strings.SplitN(rest, ":", 3)
if len(parts) < 2 {
continue
}
lineNo := 0
fmt.Sscanf(parts[0], "%d", &lineNo)
if lineNo > 0 {
fileErrors = append(fileErrors, fileError{filePath: filePath, lineNo: lineNo})
}
}
}
if len(fileErrors) == 0 {
return 0
}
excluded := map[string]bool{}
for _, fe := range fileErrors {
lines := genFiles[fe.filePath]
methodKey := findMethodKeyForLine(lines, fe.lineNo)
if methodKey != "" {
excluded[methodKey] = true
}
}
for mk := range excluded {
goProxyMethodsWithInterfaceParams[mk] = true
}
return len(excluded)
}
// findMethodKeyForLine scans around a line number to find the
// method key (importPath:MethodName) for the enclosing command function.
func findMethodKeyForLine(lines []string, lineNo int) string {
if lineNo <= 0 || lineNo > len(lines) {
return ""
}
// Scan forward for "svcProxy.MethodName(" to extract the method name.
// The svcProxy call is usually after the struct-building code.
methodName := ""
for i := lineNo - 1; i < len(lines) && i < lineNo+200; i++ {
line := strings.TrimSpace(lines[i])
if strings.HasPrefix(line, "result") || strings.HasPrefix(line, "err") || strings.HasPrefix(line, "_, err") {
if strings.Contains(line, svcProxyVarPrefix) {
idx := strings.Index(line, svcProxyVarPrefix)
rest := line[idx+len(svcProxyVarPrefix):]
if paren := strings.Index(rest, "("); paren > 0 {
methodName = rest[:paren]
break
}
}
}
}
// Also try backward if forward didn't find it.
if methodName == "" {
for i := lineNo - 1; i >= 0 && i > lineNo-200; i-- {
line := strings.TrimSpace(lines[i])
if strings.Contains(line, svcProxyVarPrefix) && !strings.HasPrefix(line, "svcProxy :=") {
idx := strings.Index(line, svcProxyVarPrefix)
rest := line[idx+len(svcProxyVarPrefix):]
if paren := strings.Index(rest, "("); paren > 0 {
methodName = rest[:paren]
break
}
}
}
}
if methodName == "" {
return ""
}
// Scan backwards for FindServiceByDescriptor to get the interface.
for i := lineNo - 1; i >= 0 && i > lineNo-500; i-- {
line := strings.TrimSpace(lines[i])
if strings.Contains(line, "FindServiceByDescriptor") {
q1 := strings.LastIndex(line, "\"")
if q1 < 0 {
continue
}
q0 := strings.LastIndex(line[:q1], "\"")
if q0 < 0 {
continue
}
descriptor := line[q0+1 : q1]
goPkg := strings.ReplaceAll(descriptor[:strings.LastIndex(descriptor, ".")], ".", "/")
goPkg = strings.ReplaceAll(goPkg, "/internal/", "/internal_/")
importPath := modulePath + "/" + goPkg
return importPath + ":" + methodName
}
}
return ""
}
// collectStructsAndEnums populates knownStructs and knownEnums from a
// package spec's parcelables and enums.
func collectStructsAndEnums(
ps *spec.PackageSpec,
importPath string,
pkgName string,
) {
for _, parc := range ps.Parcelables {
goName := codegen.AIDLToGoName(parc.Name)
key := importPath + ":" + goName
si := &structInfo{
ImportPath: importPath,
PkgName: pkgName,
}
for _, f := range parc.Fields {
goFieldName := codegen.AIDLToGoName(f.Name)
goFieldType := typeRefToGoType(f.Type, ps.AIDLPackage)
si.Fields = append(si.Fields, structField{
Name: goFieldName,
Type: goFieldType,
})
}
knownStructs[key] = si
}
for _, enum := range ps.Enums {
goName := codegen.AIDLToGoName(enum.Name)
key := importPath + ":" + goName
knownEnums[key] = true
}
// Unions are similar to structs from the CLI perspective.
for _, union := range ps.Unions {
goName := codegen.AIDLToGoName(union.Name)
key := importPath + ":" + goName
si := &structInfo{
ImportPath: importPath,
PkgName: pkgName,
}
for _, f := range union.Fields {
goFieldName := codegen.AIDLToGoName(f.Name)
goFieldType := typeRefToGoType(f.Type, ps.AIDLPackage)
si.Fields = append(si.Fields, structField{
Name: goFieldName,
Type: goFieldType,
})
}
knownStructs[key] = si
}
}
// collectServiceMappings populates knownServiceNames from a package spec.
func collectServiceMappings(
ps *spec.PackageSpec,
) {
for _, svc := range ps.Services {
if svc.Descriptor != "" && svc.ServiceName != "" {
knownServiceNames[svc.Descriptor] = svc.ServiceName
}
}
}
// typeRefToGoType converts a spec.TypeRef to a Go type string,
// using the same logic as codegen.AIDLTypeToGo but working from specs.
func typeRefToGoType(
tr spec.TypeRef,
currentAIDLPkg string,
) string {
ts := typeRefToTypeSpecifier(tr)
goType := codegen.AIDLTypeToGo(ts)
return goType
}
// typeRefToTypeSpecifier converts a spec.TypeRef to a parser.TypeSpecifier.
func typeRefToTypeSpecifier(
tr spec.TypeRef,
) *parser.TypeSpecifier {