-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathenum_gen.go
More file actions
597 lines (565 loc) · 16.3 KB
/
enum_gen.go
File metadata and controls
597 lines (565 loc) · 16.3 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
package codegen
import (
"fmt"
"math"
"strconv"
"strings"
"github.com/AndroidGoLab/binder/tools/pkg/parser"
"github.com/AndroidGoLab/binder/tools/pkg/resolver"
)
// GenerateEnum generates Go source for an AIDL enum declaration.
// The output includes:
// - A Go type alias for the backing type
// - Typed constants for each enumerator
func GenerateEnum(
decl *parser.EnumDecl,
pkg string,
options ...GenOption,
) ([]byte, error) {
opts := applyGenOptions(options)
f := NewGoFile(pkg)
goName := AIDLToGoName(decl.EnumName)
backingGoType := enumBackingGoType(decl)
f.P("// Code generated by aidlgen. DO NOT EDIT.")
f.P("")
// Type declaration.
f.P("type %s %s", goName, backingGoType)
f.P("")
// Enumerator constants.
if len(decl.Enumerators) > 0 {
f.P("const (")
counter := int64(0)
for _, e := range decl.Enumerators {
constName := goName + AIDLToGoName(e.Name)
if e.Value != nil {
valStr, err := enumConstExprToGo(e.Value, backingGoType, goName, opts.Registry)
if err != nil {
return nil, fmt.Errorf("evaluating enumerator %s: %w", e.Name, err)
}
f.P("\t%s %s = %s", constName, goName, valStr)
// Try to parse the explicit value so subsequent implicit
// enumerators continue from the right number.
if parsed, parseErr := strconv.ParseInt(valStr, 0, 64); parseErr == nil {
counter = parsed + 1
} else {
// Cannot determine the numeric value (e.g. expression);
// subsequent implicit enumerators will be wrong, but
// this is the best we can do without a const evaluator.
counter++
}
} else {
f.P("\t%s %s = %d", constName, goName, counter)
counter++
}
}
f.P(")")
f.P("")
}
return f.Bytes()
}
// enumBackingGoType returns the Go type for an enum's backing type.
// Defaults to int32 if no backing type is specified.
func enumBackingGoType(decl *parser.EnumDecl) string {
if decl.BackingType != nil {
goType := AIDLTypeToGo(decl.BackingType)
if goType != "" {
return goType
}
}
return "int32"
}
// enumConstExprToGo converts a ConstExpr to a Go source string in the context
// of an enum with the given backing Go type (e.g., "int32", "int64", "byte").
// It handles:
// - Integer literals that overflow the backing type (two's complement conversion)
// - Cross-type identifier references (casting to the backing type)
// The optional registry parameter enables resolution of cross-enum references
// for overflow detection in complex expressions.
func enumConstExprToGo(
expr parser.ConstExpr,
backingGoType string,
enumGoName string,
registry ...*resolver.TypeRegistry,
) (string, error) {
var reg *resolver.TypeRegistry
if len(registry) > 0 {
reg = registry[0]
}
switch e := expr.(type) {
case *parser.IntegerLiteral:
return enumIntLiteralToGo(e.Value, backingGoType)
case *parser.IdentExpr:
goName := aidlDottedNameToGo(e.Name)
// Determine the cast target type: use the enum type if available,
// otherwise fall back to the backing Go type.
castType := enumGoName
if castType == "" {
castType = backingGoType
}
// If the AIDL name contains a dot, it's a qualified reference to
// another type's constant (e.g. "SourceClass.BUTTON") and always
// needs casting so Go allows the typed expression.
if strings.Contains(e.Name, ".") {
return castType + "(" + goName + ")", nil
}
if enumGoName == "" {
// No enum context (e.g. standalone constant): cast all idents.
return castType + "(" + goName + ")", nil
}
// Unqualified reference: this is a self-reference to another
// enumerator in the same enum (e.g., STYLUS referencing itself).
// Prefix with the enum name to match the generated constant name.
return enumGoName + goName, nil
case *parser.UnaryExpr:
// Handle negative integer literals that overflow unsigned backing types.
if e.Op == parser.TokenMinus {
if intLit, ok := e.Operand.(*parser.IntegerLiteral); ok {
stripped := stripAIDLIntSuffix(intLit.Value)
if parsed, parseErr := strconv.ParseUint(stripped, 0, 64); parseErr == nil {
negVal := -int64(parsed)
return enumSignedToBackingType(negVal, backingGoType), nil
}
}
}
operand, err := enumConstExprToGo(e.Operand, backingGoType, enumGoName, reg)
if err != nil {
return "", err
}
return tokenToGoOp(e.Op) + operand, nil
case *parser.BinaryExpr:
// Try to evaluate the full expression numerically (including
// cross-enum references via the registry). If it overflows
// the backing type, emit the folded signed value directly.
if val, ok := tryEvalConstExprWithRegistry(expr, reg); ok {
folded := foldUnsignedToSigned(val, backingGoType)
original := fmt.Sprintf("%d", val)
if folded != original {
return folded, nil
}
}
left, err := enumConstExprToGo(e.Left, backingGoType, enumGoName, reg)
if err != nil {
return "", err
}
right, err := enumConstExprToGo(e.Right, backingGoType, enumGoName, reg)
if err != nil {
return "", err
}
return fmt.Sprintf("(%s %s %s)", left, tokenToGoOp(e.Op), right), nil
default:
// For other expression types, fall back to the generic converter.
return constExprToGo(expr)
}
}
// enumIntLiteralToGo converts an AIDL integer literal to a Go source string,
// handling overflow for the given backing type by emitting two's complement.
func enumIntLiteralToGo(
value string,
backingGoType string,
) (string, error) {
stripped := stripAIDLIntSuffix(value)
// Try to parse as unsigned to detect overflow.
parsed, err := strconv.ParseUint(stripped, 0, 64)
if err != nil {
// Not a simple integer; return as-is (may be negative or valid).
return stripped, nil
}
return foldUnsignedToSigned(parsed, backingGoType), nil
}
// foldUnsignedToSigned converts an unsigned value to its signed representation
// if it overflows the range of the given Go backing type.
func foldUnsignedToSigned(
val uint64,
backingGoType string,
) string {
switch backingGoType {
case "byte":
if val > math.MaxUint8 {
// byte is uint8 in Go, so truncate to uint8 (not int8, which
// would produce negative numbers for values > 127).
return fmt.Sprintf("%d", byte(val))
}
case "int32":
if val > math.MaxInt32 {
return fmt.Sprintf("%d", int32(val))
}
case "int64":
if val > math.MaxInt64 {
return fmt.Sprintf("%d", int64(val))
}
}
return fmt.Sprintf("%d", val)
}
// tryEvalConstExpr attempts to evaluate a const expression to a uint64 value.
// Returns the value and true if evaluation succeeds, or 0 and false otherwise.
func tryEvalConstExpr(expr parser.ConstExpr) (uint64, bool) {
switch e := expr.(type) {
case *parser.IntegerLiteral:
stripped := stripAIDLIntSuffix(e.Value)
val, err := strconv.ParseUint(stripped, 0, 64)
if err != nil {
// Try signed parse for negative literals.
sval, err2 := strconv.ParseInt(stripped, 0, 64)
if err2 != nil {
return 0, false
}
return uint64(sval), true
}
return val, true
case *parser.UnaryExpr:
operand, ok := tryEvalConstExpr(e.Operand)
if !ok {
return 0, false
}
switch e.Op {
case parser.TokenMinus:
return uint64(-int64(operand)), true
case parser.TokenTilde:
return ^operand, true
case parser.TokenBang:
if operand == 0 {
return 1, true
}
return 0, true
default:
return 0, false
}
case *parser.BinaryExpr:
left, ok := tryEvalConstExpr(e.Left)
if !ok {
return 0, false
}
right, ok := tryEvalConstExpr(e.Right)
if !ok {
return 0, false
}
// Note: arithmetic on uint64 wraps on overflow, matching Java/C unsigned semantics.
switch e.Op {
case parser.TokenPlus:
return left + right, true
case parser.TokenMinus:
return left - right, true
case parser.TokenStar:
return left * right, true
case parser.TokenSlash:
if right == 0 {
return 0, false
}
return left / right, true
case parser.TokenPercent:
if right == 0 {
return 0, false
}
return left % right, true
case parser.TokenAmp:
return left & right, true
case parser.TokenPipe:
return left | right, true
case parser.TokenCaret:
return left ^ right, true
case parser.TokenLShift:
return left << right, true
case parser.TokenRShift:
return left >> right, true
default:
return 0, false
}
default:
return 0, false
}
}
// tryEvalConstExprWithRegistry attempts to evaluate a const expression to a
// uint64 value, using the type registry to resolve cross-enum ident references
// (e.g., "CameraMetadataSection.VENDOR_SECTION").
func tryEvalConstExprWithRegistry(
expr parser.ConstExpr,
registry *resolver.TypeRegistry,
) (uint64, bool) {
// First try without registry (handles pure numeric expressions).
if val, ok := tryEvalConstExpr(expr); ok {
return val, true
}
if registry == nil {
return 0, false
}
switch e := expr.(type) {
case *parser.IdentExpr:
return resolveEnumIdentValue(e.Name, registry)
case *parser.UnaryExpr:
operand, ok := tryEvalConstExprWithRegistry(e.Operand, registry)
if !ok {
return 0, false
}
switch e.Op {
case parser.TokenMinus:
return uint64(-int64(operand)), true
case parser.TokenTilde:
return ^operand, true
default:
return 0, false
}
case *parser.BinaryExpr:
left, ok := tryEvalConstExprWithRegistry(e.Left, registry)
if !ok {
return 0, false
}
right, ok := tryEvalConstExprWithRegistry(e.Right, registry)
if !ok {
return 0, false
}
// Note: arithmetic on uint64 wraps on overflow, matching Java/C unsigned semantics.
switch e.Op {
case parser.TokenPlus:
return left + right, true
case parser.TokenMinus:
return left - right, true
case parser.TokenStar:
return left * right, true
case parser.TokenSlash:
if right == 0 {
return 0, false
}
return left / right, true
case parser.TokenPercent:
if right == 0 {
return 0, false
}
return left % right, true
case parser.TokenAmp:
return left & right, true
case parser.TokenPipe:
return left | right, true
case parser.TokenCaret:
return left ^ right, true
case parser.TokenLShift:
return left << right, true
case parser.TokenRShift:
return left >> right, true
default:
return 0, false
}
default:
return 0, false
}
}
// resolveEnumIdentValue resolves an AIDL enum constant reference (e.g.,
// "CameraMetadataSection.VENDOR_SECTION") to its numeric value using the
// type registry.
func resolveEnumIdentValue(
name string,
registry *resolver.TypeRegistry,
) (uint64, bool) {
dotIdx := strings.LastIndex(name, ".")
if dotIdx < 0 {
return 0, false
}
enumName := name[:dotIdx]
constName := name[dotIdx+1:]
// Look up the enum definition by short name.
qualifiedName, def, ok := registry.LookupQualifiedByShortName(enumName)
if !ok {
// Try fully qualified.
def, ok = registry.Lookup(enumName)
if !ok {
return 0, false
}
qualifiedName = enumName
}
_ = qualifiedName
enumDecl, ok := def.(*parser.EnumDecl)
if !ok {
return 0, false
}
// Find the enumerator by name and evaluate its value.
counter := int64(0)
for _, e := range enumDecl.Enumerators {
if e.Value != nil {
if val, evalOK := tryEvalConstExpr(e.Value); evalOK {
counter = int64(val)
}
}
if e.Name == constName {
return uint64(counter), true
}
counter++
}
return 0, false
}
// enumSignedToBackingType converts a signed integer value to a valid Go
// representation for the given backing type. For unsigned types like byte,
// negative values are converted to their unsigned equivalent.
func enumSignedToBackingType(
val int64,
backingGoType string,
) string {
if val >= 0 {
return fmt.Sprintf("%d", val)
}
switch backingGoType {
case "byte":
return fmt.Sprintf("%d", byte(val))
default:
return fmt.Sprintf("%d", val)
}
}
// typedConstExprToGo converts a ConstExpr to a Go source string, handling
// integer overflow for the given Go type. For non-integer types or empty
// goType, it falls back to constExprToGo. The optional prefix is used to
// qualify self-referencing identifiers in constant expressions (e.g.,
// constants declared inside a struct/union/interface).
func typedConstExprToGo(
expr parser.ConstExpr,
goType string,
prefix ...string,
) (string, error) {
p := ""
if len(prefix) > 0 {
p = prefix[0]
}
switch goType {
case "int32", "int64", "byte":
if p != "" {
// For non-enum container constants (parcelable, union,
// interface), use the prefix only for self-reference
// qualification. The cast type must be the backing Go type,
// not the container name (which might be an interface type).
return prefixedIntConstExprToGo(expr, goType, p)
}
return enumConstExprToGo(expr, goType, "")
default:
if p != "" {
return prefixedConstExprToGo(expr, p)
}
return constExprToGo(expr)
}
}
// prefixedIntConstExprToGo converts integer constant expressions with
// a container prefix for self-references, using the backing Go type
// (not the container name) for cross-type casts.
func prefixedIntConstExprToGo(
expr parser.ConstExpr,
backingGoType string,
prefix string,
) (string, error) {
switch e := expr.(type) {
case *parser.IntegerLiteral:
return enumIntLiteralToGo(e.Value, backingGoType)
case *parser.IdentExpr:
goName := aidlDottedNameToGo(e.Name)
if strings.Contains(e.Name, ".") {
// Cross-type reference: cast to backing type.
return backingGoType + "(" + goName + ")", nil
}
// Self-reference: prefix with the container name.
return prefix + goName, nil
case *parser.UnaryExpr:
if e.Op == parser.TokenMinus {
if intLit, ok := e.Operand.(*parser.IntegerLiteral); ok {
stripped := stripAIDLIntSuffix(intLit.Value)
if parsed, parseErr := strconv.ParseUint(stripped, 0, 64); parseErr == nil {
negVal := -int64(parsed)
return enumSignedToBackingType(negVal, backingGoType), nil
}
}
}
operand, err := prefixedIntConstExprToGo(e.Operand, backingGoType, prefix)
if err != nil {
return "", err
}
return tokenToGoOp(e.Op) + operand, nil
case *parser.BinaryExpr:
if val, ok := tryEvalConstExpr(expr); ok {
folded := foldUnsignedToSigned(val, backingGoType)
original := fmt.Sprintf("%d", val)
if folded != original {
return folded, nil
}
}
left, err := prefixedIntConstExprToGo(e.Left, backingGoType, prefix)
if err != nil {
return "", err
}
right, err := prefixedIntConstExprToGo(e.Right, backingGoType, prefix)
if err != nil {
return "", err
}
return fmt.Sprintf("(%s %s %s)", left, tokenToGoOp(e.Op), right), nil
default:
return constExprToGo(expr)
}
}
// prefixedConstExprToGo converts a ConstExpr to a Go source string,
// prefixing unqualified identifier references with the given prefix.
// This handles constants declared inside types (parcelable, union) that
// reference other constants in the same type.
func prefixedConstExprToGo(
expr parser.ConstExpr,
prefix string,
) (string, error) {
switch e := expr.(type) {
case *parser.IdentExpr:
goName := aidlDottedNameToGo(e.Name)
if strings.Contains(e.Name, ".") {
return goName, nil
}
return prefix + goName, nil
case *parser.UnaryExpr:
operand, err := prefixedConstExprToGo(e.Operand, prefix)
if err != nil {
return "", err
}
return tokenToGoOp(e.Op) + operand, nil
case *parser.BinaryExpr:
left, err := prefixedConstExprToGo(e.Left, prefix)
if err != nil {
return "", err
}
right, err := prefixedConstExprToGo(e.Right, prefix)
if err != nil {
return "", err
}
return fmt.Sprintf("(%s %s %s)", left, tokenToGoOp(e.Op), right), nil
default:
return constExprToGo(expr)
}
}
// constExprToGo converts a ConstExpr to a Go source string.
func constExprToGo(expr parser.ConstExpr) (string, error) {
switch e := expr.(type) {
case *parser.IntegerLiteral:
return stripAIDLIntSuffix(e.Value), nil
case *parser.FloatLiteral:
return stripAIDLFloatSuffix(e.Value), nil
case *parser.StringLiteralExpr:
return fmt.Sprintf("%q", e.Value), nil
case *parser.BoolLiteral:
if e.Value {
return "true", nil
}
return "false", nil
case *parser.CharLiteralExpr:
return fmt.Sprintf("'%s'", e.Value), nil
case *parser.NullLiteral:
return "nil", nil
case *parser.IdentExpr:
return aidlDottedNameToGo(e.Name), nil
case *parser.UnaryExpr:
operand, err := constExprToGo(e.Operand)
if err != nil {
return "", err
}
return tokenToGoOp(e.Op) + operand, nil
case *parser.BinaryExpr:
left, err := constExprToGo(e.Left)
if err != nil {
return "", err
}
right, err := constExprToGo(e.Right)
if err != nil {
return "", err
}
return fmt.Sprintf("(%s %s %s)", left, tokenToGoOp(e.Op), right), nil
default:
return "", fmt.Errorf("unsupported constant expression type %T", expr)
}
}