Debian Codegraph @

internal/gen/build.go

raw symbols SCIP
1 package gen
2
3 import (
4 "fmt"
5
6 "github.com/mmcloughlin/avo/internal/api"
7 "github.com/mmcloughlin/avo/internal/inst"
8 "github.com/mmcloughlin/avo/internal/prnt"
9 "github.com/mmcloughlin/avo/printer"
10 )
11
12 type build struct {
13 cfg printer.Config
14 prnt.Generator
15 }
16
17 // NewBuild builds a printer that will generate instruction functions in the
18 // build package. Each instruction will have one method on the build.Context
19 // type, and a corresponding wrapper operating on the global Context. These
20 // functions are thin wrappers around constructors generated by NewCtors.
21 func NewBuild(cfg printer.Config) Interface {
22 return GoFmt(&build{cfg: cfg})
23 }
24
25 func (b *build) Generate(is []inst.Instruction) ([]byte, error) {
26 b.Printf("// %s\n\n", b.cfg.GeneratedWarning())
27 b.Printf("package build\n\n")
28
29 b.Printf("import (\n")
30 b.Printf("\t%q\n", api.ImportPath(api.IRPackage))
31 b.Printf("\t%q\n", api.ImportPath(api.OperandPackage))
32 b.Printf("\t%q\n", api.ImportPath("x86"))
33 b.Printf(")\n\n")
34
35 // Helper to reduce source code size a little.
36 b.Printf("func (c *Context) addinstruction(i *ir.Instruction, err error) {\n")
37 b.Printf("if err == nil { c.Instruction(i) }")
38 b.Printf(" else { c.adderror(err) }\n")
39 b.Printf("}\n\n")
40
41 // Generate build functions.
42 fns := api.InstructionsFunctions(is)
43 for _, fn := range fns {
44 b.function(fn)
45 }
46
47 return b.Result()
48 }
49
50 func (b *build) function(fn *api.Function) {
51 s := fn.Signature()
52 d := fn.Doc()
53
54 // Context method.
55 methoddoc := append([]string{}, d...)
56 methoddoc = append(methoddoc, fmt.Sprintf("Construct and append a %s instruction to the active function.", fn.Opcode()))
57 b.Comment(methoddoc...)
58 b.Printf("func (c *Context) %s(%s) {\n", fn.Name(), s.ParameterList())
59 b.Printf("c.addinstruction(x86.%s(%s))", fn.Name(), s.Arguments())
60 b.Printf("}\n\n")
61
62 // Global version.
63 globaldoc := append([]string{}, methoddoc...)
64 globaldoc = append(globaldoc, "Operates on the global context.")
65 b.Comment(globaldoc...)
66 b.Printf("func %s(%s) { ctx.%s(%s) }\n\n", fn.Name(), s.ParameterList(), fn.Name(), s.Arguments())
67 }