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"
|
|
|
|
|
)
|
|
|
|
|
|
2018-11-26 10:13:04 -08:00
|
|
|
const pkg = "github.com/mmcloughlin/avo"
|
|
|
|
|
|
2018-11-21 13:02:18 -06:00
|
|
|
type Interface interface {
|
2018-11-24 14:20:04 -08:00
|
|
|
Generate([]inst.Instruction) ([]byte, error)
|
2018-11-21 13:02:18 -06:00
|
|
|
}
|
|
|
|
|
|
2018-11-24 14:20:04 -08:00
|
|
|
type Func func([]inst.Instruction) ([]byte, error)
|
2018-11-21 13:02:18 -06:00
|
|
|
|
2018-11-24 14:20:04 -08:00
|
|
|
func (f Func) Generate(is []inst.Instruction) ([]byte, error) {
|
2018-11-24 13:00:27 -08:00
|
|
|
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 {
|
2018-11-24 14:20:04 -08:00
|
|
|
return Func(func(is []inst.Instruction) ([]byte, error) {
|
2018-11-24 13:00:27 -08:00
|
|
|
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
|
|
|
}
|