2018-11-30 20:43:31 -08:00
|
|
|
package gen
|
|
|
|
|
|
2018-12-11 00:18:22 -08:00
|
|
|
import (
|
2019-01-06 21:12:15 -08:00
|
|
|
"fmt"
|
|
|
|
|
|
2018-12-11 00:18:22 -08:00
|
|
|
"github.com/mmcloughlin/avo/internal/inst"
|
|
|
|
|
"github.com/mmcloughlin/avo/internal/prnt"
|
|
|
|
|
"github.com/mmcloughlin/avo/printer"
|
|
|
|
|
)
|
2018-11-30 20:43:31 -08:00
|
|
|
|
|
|
|
|
type build struct {
|
2018-12-11 00:18:22 -08:00
|
|
|
cfg printer.Config
|
|
|
|
|
prnt.Generator
|
2018-11-30 20:43:31 -08:00
|
|
|
}
|
|
|
|
|
|
2019-01-05 14:12:50 -08:00
|
|
|
// NewBuild builds a printer that will generate instruction functions in the
|
|
|
|
|
// build package. Each instruction will have one method on the build.Context
|
|
|
|
|
// type, and a corresponding wrapper operating on the global Context. These
|
|
|
|
|
// functions are thin wrappers around constructors generated by NewCtors.
|
2018-12-11 00:18:22 -08:00
|
|
|
func NewBuild(cfg printer.Config) Interface {
|
2018-11-30 20:43:31 -08:00
|
|
|
return GoFmt(&build{cfg: cfg})
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (b *build) Generate(is []inst.Instruction) ([]byte, error) {
|
|
|
|
|
b.Printf("// %s\n\n", b.cfg.GeneratedWarning())
|
|
|
|
|
b.Printf("package build\n\n")
|
|
|
|
|
|
|
|
|
|
b.Printf("import (\n")
|
2018-12-02 12:28:33 -08:00
|
|
|
b.Printf("\t\"%s/operand\"\n", pkg)
|
2018-11-30 20:43:31 -08:00
|
|
|
b.Printf("\t\"%s/x86\"\n", pkg)
|
|
|
|
|
b.Printf(")\n\n")
|
|
|
|
|
|
|
|
|
|
for _, i := range is {
|
|
|
|
|
b.instruction(i)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return b.Result()
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (b *build) instruction(i inst.Instruction) {
|
|
|
|
|
s := params(i)
|
2019-01-06 21:12:15 -08:00
|
|
|
d := doc(i)
|
2018-11-30 20:43:31 -08:00
|
|
|
|
|
|
|
|
// Context method.
|
2019-01-06 21:12:15 -08:00
|
|
|
methoddoc := append([]string{}, d...)
|
|
|
|
|
methoddoc = append(methoddoc, fmt.Sprintf("Construct and append a %s instruction to the active function.", i.Opcode))
|
|
|
|
|
b.Comment(methoddoc...)
|
2018-11-30 20:43:31 -08:00
|
|
|
b.Printf("func (c *Context) %s(%s) {\n", i.Opcode, s.ParameterList())
|
|
|
|
|
b.Printf("if inst, err := x86.%s(%s); err == nil", i.Opcode, s.Arguments())
|
2018-12-02 23:59:29 -08:00
|
|
|
b.Printf(" { c.Instruction(inst) }")
|
2019-01-05 16:49:51 -08:00
|
|
|
b.Printf(" else { c.adderror(err) }\n")
|
2019-01-06 21:12:15 -08:00
|
|
|
b.Printf("}\n\n")
|
2018-11-30 20:43:31 -08:00
|
|
|
|
|
|
|
|
// Global version.
|
2019-01-06 21:12:15 -08:00
|
|
|
globaldoc := append([]string{}, methoddoc...)
|
|
|
|
|
globaldoc = append(globaldoc, "Operates on the global context.")
|
|
|
|
|
b.Comment(globaldoc...)
|
2018-11-30 20:43:31 -08:00
|
|
|
b.Printf("func %s(%s) { ctx.%s(%s) }\n\n", i.Opcode, s.ParameterList(), i.Opcode, s.Arguments())
|
|
|
|
|
}
|