Debian Codegraph @

internal/generate/generate.go

raw
1 // Package generate holds helper function for the code generation that we use.
2 package generate
3
4 import (
5 "bytes"
6 "flag"
7 "fmt"
8 "go/ast"
9 "go/format"
10 "go/parser"
11 "go/token"
12 "log"
13 "os"
14 "reflect"
15 "slices"
16 )
17
18 var exclude = []string{""}
19
20 var FlagDebug = flag.Bool("debug", false, "Emit the non-formatted code to standard output and do not write it to a file.")
21
22 // EmptyData are RR that don't have rdata (or are embedding another type) and as such do not have an entry in rdata/rdata.go
23 var EmptyData = []string{
24 "ANY", "AVC", "AXFR", "CDNSKEY", "CDS", "CLA", "DELEGPARAM", "DLV", "HTTPS",
25 "IXFR", "KEY", "NXNAME", "NXT", "OPT", "SIG", "SPF", "RESINFO", "WALLET",
26 }
27
28 var Popular = []string{"A", "AAAA", "NS", "CNAME", "DNSKEY", "DS", "RRSIG", "DELEG", "MX", "TXT", "NSEC", "NSEC3", "OPT", "TSIG"}
29
30 // Ast returns the *ast.File of file or an error.
31 func Ast(file string) (f *ast.File, t *token.FileSet, err error) {
32 fset := token.NewFileSet()
33 node, err := parser.ParseFile(fset, file, nil, parser.AllErrors|parser.ParseComments|parser.SkipObjectResolution)
34 return node, fset, err
35 }
36
37 // Types returns all types names from the file that are exported.
38 func Types(file string) ([]string, error) {
39 node, _, err := Ast(file)
40 if err != nil {
41 return nil, fmt.Errorf("failed to parse %s: %v", file, err)
42 }
43
44 types := []string{}
45 for _, decl := range node.Decls {
46 declType := reflect.TypeOf(decl)
47
48 if declType.String() == "*ast.GenDecl" {
49 genDecl := decl.(*ast.GenDecl)
50 if genDecl.Tok == token.TYPE {
51 for _, spec := range genDecl.Specs {
52 if typeSpec, ok := spec.(*ast.TypeSpec); ok {
53 if typeSpec.Name.IsExported() {
54 if !slices.Contains(exclude, typeSpec.Name.Name) {
55 // prepend if popular
56 if slices.Contains(Popular, typeSpec.Name.Name) {
57 types = append([]string{typeSpec.Name.Name}, types...)
58 } else {
59 types = append(types, typeSpec.Name.Name)
60 }
61 }
62 }
63 }
64 }
65 }
66 }
67 }
68 return types, nil
69 }
70
71 // Fields returns the export type names and the field's names. Each name is prefixed with "rr.".
72 func Fields(file string) (map[string][]string, error) {
73 node, _, err := Ast(file)
74 if err != nil {
75 return nil, err
76 }
77
78 types := map[string][]string{}
79 for _, decl := range node.Decls {
80 declType := reflect.TypeOf(decl)
81
82 if declType.String() == "*ast.GenDecl" {
83 genDecl := decl.(*ast.GenDecl)
84 if genDecl.Tok == token.TYPE {
85 for _, spec := range genDecl.Specs {
86 if typeSpec, ok := spec.(*ast.TypeSpec); ok {
87 if typeSpec.Name.IsExported() {
88 types[typeSpec.Name.Name] = fields(typeSpec.Type)
89 }
90 }
91 }
92 }
93 }
94 }
95 return types, nil
96 }
97
98 func fields(node ast.Node) []string {
99 fields := []string{}
100 switch n := node.(type) {
101 case *ast.StructType:
102 for _, field := range n.Fields.List {
103 for _, f := range field.Names {
104 if f.String() == "Hdr" {
105 continue
106 }
107 fields = append(fields, "rr."+f.String())
108 }
109 }
110 }
111 return fields
112 }
113
114 // FilterTypeSpecs filters the type specs on name.
115 func FilterTypeSpecs(typeSpecs []*ast.TypeSpec, names []string) []*ast.TypeSpec {
116 filtered := []*ast.TypeSpec{}
117 for i := range typeSpecs {
118 if slices.Contains(names, typeSpecs[i].Name.String()) {
119 filtered = append(filtered, typeSpecs[i])
120 }
121 }
122 return filtered
123 }
124
125 // StructTypeSpecs returns the struct types from file that can be inspected for the struct tags.
126 func StructTypeSpecs(file string) ([]*ast.TypeSpec, error) {
127 node, _, err := Ast(file)
128 if err != nil {
129 return nil, err
130 }
131 structs := []*ast.TypeSpec{}
132
133 ast.Inspect(node, func(n ast.Node) bool {
134 typeSpec, ok := n.(*ast.TypeSpec)
135 if !ok {
136 return true
137 }
138
139 if _, ok := typeSpec.Type.(*ast.StructType); !ok {
140 return true
141 }
142
143 if !typeSpec.Name.IsExported() {
144 return true
145 }
146
147 structs = append(structs, typeSpec)
148 return true
149 })
150 return structs, nil
151 }
152
153 func Write(b *bytes.Buffer, out string) {
154 formatted, err := format.Source(b.Bytes())
155 if err != nil {
156 b.WriteTo(os.Stderr)
157 log.Fatalf("Failed to generate %s: %v", out, err)
158 }
159
160 if *FlagDebug {
161 fmt.Print(string(formatted))
162 return
163 }
164
165 if err := os.WriteFile(out, formatted, 0640); err != nil {
166 log.Fatalf("Failed to generate %s: %v", out, err)
167 }
168 }
169
170 func IsEmbedded(strct *ast.StructType) bool {
171 if len(strct.Fields.List) == 1 {
172 return strct.Fields.List[0].Type != nil && len(strct.Fields.List[0].Names) == 0
173 }
174 return false
175 }