-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconstant_gen.go
More file actions
64 lines (52 loc) · 1.44 KB
/
constant_gen.go
File metadata and controls
64 lines (52 loc) · 1.44 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
package codegen
import (
"fmt"
"github.com/AndroidGoLab/binder/tools/pkg/parser"
)
// GenerateConstants writes const declarations to the given GoFile.
// prefix is prepended to each constant name to avoid collisions when
// multiple types in the same package define constants with the same name.
// Self-references within constant expressions are also prefixed so they
// resolve to the correct Go constant names.
func GenerateConstants(
constants []*parser.ConstantDecl,
f *GoFile,
prefix string,
) error {
if len(constants) == 0 {
return nil
}
f.P("const (")
for _, c := range constants {
goName := prefix + AIDLToGoName(c.ConstName)
goType := AIDLTypeToGo(c.Type)
valStr, err := typedConstExprToGo(c.Value, goType, prefix)
if err != nil {
return fmt.Errorf("evaluating constant %s: %w", c.ConstName, err)
}
if goType != "" {
f.P("\t%s %s = %s", goName, goType, valStr)
} else {
f.P("\t%s = %s", goName, valStr)
}
}
f.P(")")
return nil
}
// GenerateConstantsFile generates a standalone Go file containing only constant declarations.
// This is useful when constants are declared at package level.
func GenerateConstantsFile(
constants []*parser.ConstantDecl,
pkg string,
) ([]byte, error) {
if len(constants) == 0 {
return nil, nil
}
f := NewGoFile(pkg)
f.P("// Code generated by aidlgen. DO NOT EDIT.")
f.P("")
if err := GenerateConstants(constants, f, ""); err != nil {
return nil, err
}
return f.Bytes()
}