Files
avo/internal/gen/gen.go

66 lines
1.2 KiB
Go
Raw Normal View History

2018-11-21 13:02:18 -06:00
package gen
import (
2018-11-24 13:00:27 -08:00
"bytes"
2018-11-21 13:02:18 -06:00
"fmt"
2018-11-24 13:00:27 -08:00
"go/format"
2018-11-24 13:47:30 -08:00
"strings"
2018-11-21 13:02:18 -06:00
"github.com/mmcloughlin/avo/internal/inst"
)
type Interface interface {
2018-11-24 13:00:27 -08:00
Generate([]*inst.Instruction) ([]byte, error)
2018-11-21 13:02:18 -06:00
}
2018-11-24 13:00:27 -08:00
type Func func([]*inst.Instruction) ([]byte, error)
2018-11-21 13:02:18 -06:00
2018-11-24 13:00:27 -08:00
func (f Func) Generate(is []*inst.Instruction) ([]byte, error) {
return f(is)
}
2018-11-24 13:47:30 -08:00
type Config struct {
Name string
Argv []string
}
func (c Config) GeneratedBy() string {
if c.Argv == nil {
return c.Name
}
return fmt.Sprintf("command: %s", strings.Join(c.Argv, " "))
}
func (c Config) GeneratedWarning() string {
return fmt.Sprintf("Code generated by %s. DO NOT EDIT.", c.GeneratedBy())
}
type Builder func(Config) Interface
2018-11-24 13:00:27 -08:00
// GoFmt formats Go code produced from the given generator.
func GoFmt(i Interface) Interface {
return Func(func(is []*inst.Instruction) ([]byte, error) {
b, err := i.Generate(is)
if err != nil {
return nil, err
}
return format.Source(b)
})
2018-11-21 13:02:18 -06:00
}
type printer struct {
2018-11-24 13:00:27 -08:00
buf bytes.Buffer
2018-11-21 13:02:18 -06:00
err error
}
2018-11-24 13:00:27 -08:00
func (p *printer) Printf(format string, args ...interface{}) {
2018-11-21 13:02:18 -06:00
if p.err != nil {
return
}
2018-11-24 13:00:27 -08:00
_, p.err = fmt.Fprintf(&p.buf, format, args...)
2018-11-21 13:02:18 -06:00
}
2018-11-24 13:00:27 -08:00
func (p *printer) Result() ([]byte, error) {
return p.buf.Bytes(), p.err
2018-11-21 13:02:18 -06:00
}