Debian Codegraph @

types_generate.go

raw symbols SCIP
1 //go:build ignore
2 // +build ignore
3
4 // types_generate.go is meant to run with go generate. It will use
5 // go/{importer,types} to track down all the RR struct types. Then for each type
6 // it will generate conversion tables (TypeToRR and TypeToString) and banal
7 // methods (len, Header, copy) based on the struct tags. The generated source is
8 // written to ztypes.go, and is meant to be checked into git.
9 package main
10
11 import (
12 "bytes"
13 "fmt"
14 "go/format"
15 "go/types"
16 "log"
17 "os"
18 "strings"
19 "text/template"
20
21 "golang.org/x/tools/go/packages"
22 )
23
24 var skipLen = map[string]struct{}{
25 "NSEC": {},
26 "NSEC3": {},
27 "OPT": {},
28 "CSYNC": {},
29 }
30
31 var packageHdr = `
32 // Code generated by "go run types_generate.go"; DO NOT EDIT.
33
34 package dns
35
36 import (
37 "encoding/base64"
38 "net"
39 )
40
41 `
42
43 var TypeToRR = template.Must(template.New("TypeToRR").Parse(`
44 // TypeToRR is a map of constructors for each RR type.
45 var TypeToRR = map[uint16]func() RR{
46 {{range .}}{{if ne . "RFC3597"}} Type{{.}}: func() RR { return new({{.}}) },
47 {{end}}{{end}} }
48
49 `))
50
51 var typeToString = template.Must(template.New("typeToString").Parse(`
52 // TypeToString is a map of strings for each RR type.
53 var TypeToString = map[uint16]string{
54 {{range .}}{{if ne . "NSAPPTR"}} Type{{.}}: "{{.}}",
55 {{end}}{{end}} TypeNSAPPTR: "NSAP-PTR",
56 }
57
58 `))
59
60 var headerFunc = template.Must(template.New("headerFunc").Parse(`
61 {{range .}} func (rr *{{.}}) Header() *RR_Header { return &rr.Hdr }
62 {{end}}
63
64 `))
65
66 // getTypeStruct will take a type and the package scope, and return the
67 // (innermost) struct if the type is considered a RR type (currently defined as
68 // those structs beginning with a RR_Header, could be redefined as implementing
69 // the RR interface). The bool return value indicates if embedded structs were
70 // resolved.
71 func getTypeStruct(t types.Type, scope *types.Scope) (*types.Struct, bool) {
72 st, ok := t.Underlying().(*types.Struct)
73 if !ok {
74 return nil, false
75 }
76 if st.NumFields() == 0 {
77 return nil, false
78 }
79 if st.Field(0).Type() == scope.Lookup("RR_Header").Type() {
80 return st, false
81 }
82 if st.Field(0).Anonymous() {
83 st, _ := getTypeStruct(st.Field(0).Type(), scope)
84 return st, true
85 }
86 return nil, false
87 }
88
89 // loadModule retrieves package description for a given module.
90 func loadModule(name string) (*types.Package, error) {
91 conf := packages.Config{Mode: packages.NeedTypes | packages.NeedTypesInfo}
92 pkgs, err := packages.Load(&conf, name)
93 if err != nil {
94 return nil, err
95 }
96 return pkgs[0].Types, nil
97 }
98
99 func main() {
100 // Import and type-check the package
101 pkg, err := loadModule("github.com/miekg/dns")
102 fatalIfErr(err)
103 scope := pkg.Scope()
104
105 // Collect constants like TypeX
106 var numberedTypes []string
107 for _, name := range scope.Names() {
108 o := scope.Lookup(name)
109 if o == nil || !o.Exported() {
110 continue
111 }
112 b, ok := o.Type().(*types.Basic)
113 if !ok || b.Kind() != types.Uint16 {
114 continue
115 }
116 if !strings.HasPrefix(o.Name(), "Type") {
117 continue
118 }
119 name := strings.TrimPrefix(o.Name(), "Type")
120 if name == "PrivateRR" {
121 continue
122 }
123 numberedTypes = append(numberedTypes, name)
124 }
125
126 // Collect actual types (*X)
127 var namedTypes []string
128 for _, name := range scope.Names() {
129 o := scope.Lookup(name)
130 if o == nil || !o.Exported() {
131 continue
132 }
133 if st, _ := getTypeStruct(o.Type(), scope); st == nil {
134 continue
135 }
136 if name == "PrivateRR" {
137 continue
138 }
139
140 // Check if corresponding TypeX exists
141 if scope.Lookup("Type"+o.Name()) == nil && o.Name() != "RFC3597" {
142 log.Fatalf("Constant Type%s does not exist.", o.Name())
143 }
144
145 namedTypes = append(namedTypes, o.Name())
146 }
147
148 b := &bytes.Buffer{}
149 b.WriteString(packageHdr)
150
151 // Generate TypeToRR
152 fatalIfErr(TypeToRR.Execute(b, namedTypes))
153
154 // Generate typeToString
155 fatalIfErr(typeToString.Execute(b, numberedTypes))
156
157 // Generate headerFunc
158 fatalIfErr(headerFunc.Execute(b, namedTypes))
159
160 // Generate len()
161 fmt.Fprint(b, "// len() functions\n")
162 for _, name := range namedTypes {
163 if _, ok := skipLen[name]; ok {
164 continue
165 }
166 o := scope.Lookup(name)
167 st, isEmbedded := getTypeStruct(o.Type(), scope)
168 if isEmbedded {
169 continue
170 }
171 fmt.Fprintf(b, "func (rr *%s) len(off int, compression map[string]struct{}) int {\n", name)
172 fmt.Fprintf(b, "l := rr.Hdr.len(off, compression)\n")
173 for i := 1; i < st.NumFields(); i++ {
174 o := func(s string) { fmt.Fprintf(b, s, st.Field(i).Name()) }
175
176 if _, ok := st.Field(i).Type().(*types.Slice); ok {
177 switch st.Tag(i) {
178 case `dns:"-"`:
179 // ignored
180 case `dns:"cdomain-name"`:
181 o("for _, x := range rr.%s { l += domainNameLen(x, off+l, compression, true) }\n")
182 case `dns:"domain-name"`:
183 o("for _, x := range rr.%s { l += domainNameLen(x, off+l, compression, false) }\n")
184 case `dns:"txt"`:
185 o("for _, x := range rr.%s { l += len(x) + 1 }\n")
186 case `dns:"apl"`:
187 o("for _, x := range rr.%s { l += x.len() }\n")
188 case `dns:"pairs"`:
189 o("for _, x := range rr.%s { l += 4 + int(x.len()) }\n")
190 default:
191 log.Fatalln(name, st.Field(i).Name(), st.Tag(i))
192 }
193 continue
194 }
195
196 switch {
197 case st.Tag(i) == `dns:"-"`:
198 // ignored
199 case st.Tag(i) == `dns:"cdomain-name"`:
200 o("l += domainNameLen(rr.%s, off+l, compression, true)\n")
201 case st.Tag(i) == `dns:"domain-name"`:
202 o("l += domainNameLen(rr.%s, off+l, compression, false)\n")
203 case st.Tag(i) == `dns:"octet"`:
204 o("l += len(rr.%s)\n")
205 case strings.HasPrefix(st.Tag(i), `dns:"size-base64`):
206 fallthrough
207 case st.Tag(i) == `dns:"base64"`:
208 o("l += base64.StdEncoding.DecodedLen(len(rr.%s))\n")
209 case strings.HasPrefix(st.Tag(i), `dns:"size-hex:`): // this has an extra field where the length is stored
210 o("l += len(rr.%s)/2\n")
211 case st.Tag(i) == `dns:"hex"`:
212 o("l += len(rr.%s)/2\n")
213 case st.Tag(i) == `dns:"any"`:
214 o("l += len(rr.%s)\n")
215 case st.Tag(i) == `dns:"a"`:
216 o("if len(rr.%s) != 0 { l += net.IPv4len }\n")
217 case st.Tag(i) == `dns:"aaaa"`:
218 o("if len(rr.%s) != 0 { l += net.IPv6len }\n")
219 case st.Tag(i) == `dns:"txt"`:
220 o("for _, t := range rr.%s { l += len(t) + 1 }\n")
221 case st.Tag(i) == `dns:"uint48"`:
222 o("l += 6 // %s\n")
223 case st.Tag(i) == `dns:"ipsechost"`:
224 o(`switch rr.GatewayType {
225 case IPSECGatewayIPv4:
226 l += net.IPv4len
227 case IPSECGatewayIPv6:
228 l += net.IPv6len
229 case IPSECGatewayHost:
230 l += len(rr.%s) + 1
231 }
232 `)
233 case st.Tag(i) == `dns:"amtrelayhost"`:
234 o(`switch rr.GatewayType {
235 case AMTRELAYIPv4:
236 l += net.IPv4len
237 case AMTRELAYIPv6:
238 l += net.IPv6len
239 case AMTRELAYHost:
240 l += len(rr.%s) + 1
241 }
242 `)
243 case st.Tag(i) == `dns:"amtrelaytype"`:
244 o("l++ // %s\n")
245 case st.Tag(i) == "":
246 switch st.Field(i).Type().(*types.Basic).Kind() {
247 case types.Uint8:
248 o("l++ // %s\n")
249 case types.Uint16:
250 o("l += 2 // %s\n")
251 case types.Uint32:
252 o("l += 4 // %s\n")
253 case types.Uint64:
254 o("l += 8 // %s\n")
255 case types.String:
256 o("l += len(rr.%s) + 1\n")
257 default:
258 log.Fatalln(name, st.Field(i).Name())
259 }
260 default:
261 log.Fatalln(name, st.Field(i).Name(), st.Tag(i))
262 }
263 }
264 fmt.Fprint(b, "return l }\n\n")
265 }
266
267 // Generate copy()
268 fmt.Fprint(b, "// copy() functions\n")
269 for _, name := range namedTypes {
270 o := scope.Lookup(name)
271 st, isEmbedded := getTypeStruct(o.Type(), scope)
272 fmt.Fprintf(b, "func (rr *%s) copy() RR {\n", name)
273 fields := make([]string, 0, st.NumFields())
274 if isEmbedded {
275 a, _ := o.Type().Underlying().(*types.Struct)
276 parent := a.Field(0).Name()
277 fields = append(fields, "*rr."+parent+".copy().(*"+parent+")")
278 goto WriteCopy
279 }
280 fields = append(fields, "rr.Hdr")
281 for i := 1; i < st.NumFields(); i++ {
282 f := st.Field(i).Name()
283 if sl, ok := st.Field(i).Type().(*types.Slice); ok {
284 t := sl.Underlying().String()
285 t = strings.TrimPrefix(t, "[]")
286 if idx := strings.LastIndex(t, "."); idx >= 0 {
287 t = t[idx+1:]
288 }
289 // For the EDNS0 interface (and others), we need to call the copy method on each element.
290 if t == "EDNS0" || t == "APLPrefix" || t == "SVCBKeyValue" {
291 fmt.Fprintf(b, "%s := make([]%s, len(rr.%s));\nfor i,e := range rr.%s {\n %s[i] = e.copy()\n}\n",
292 f, t, f, f, f)
293 fields = append(fields, f)
294 continue
295 }
296 fields = append(fields, "cloneSlice(rr."+f+")")
297 continue
298 }
299 if st.Field(i).Type().String() == "net.IP" {
300 fields = append(fields, "cloneSlice(rr."+f+")")
301 continue
302 }
303 fields = append(fields, "rr."+f)
304 }
305 WriteCopy:
306 if len(fields) > 3 {
307 fmt.Fprintf(b, "return &%s{\n%s,\n}\n", name, strings.Join(fields, ",\n"))
308 } else {
309 fmt.Fprintf(b, "return &%s{%s}\n", name, strings.Join(fields, ","))
310 }
311 fmt.Fprint(b, "}\n\n")
312 }
313
314 // gofmt
315 res, err := format.Source(b.Bytes())
316 if err != nil {
317 b.WriteTo(os.Stderr)
318 log.Fatal(err)
319 }
320
321 // write result
322 f, err := os.Create("ztypes.go")
323 fatalIfErr(err)
324 defer f.Close()
325 f.Write(res)
326 }
327
328 func fatalIfErr(err error) {
329 if err != nil {
330 log.Fatal(err)
331 }
332 }