refactors to code generation
This commit is contained in:
@@ -1,34 +1,46 @@
|
||||
package gen
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io"
|
||||
"go/format"
|
||||
|
||||
"github.com/mmcloughlin/avo/internal/inst"
|
||||
)
|
||||
|
||||
type Interface interface {
|
||||
Generate(io.Writer, []*inst.Instruction) error
|
||||
Generate([]*inst.Instruction) ([]byte, error)
|
||||
}
|
||||
|
||||
type Func func(io.Writer, []*inst.Instruction) error
|
||||
type Func func([]*inst.Instruction) ([]byte, error)
|
||||
|
||||
func (f Func) Generate(w io.Writer, is []*inst.Instruction) error {
|
||||
return f(w, is)
|
||||
func (f Func) Generate(is []*inst.Instruction) ([]byte, error) {
|
||||
return f(is)
|
||||
}
|
||||
|
||||
// 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)
|
||||
})
|
||||
}
|
||||
|
||||
type printer struct {
|
||||
w io.Writer
|
||||
buf bytes.Buffer
|
||||
err error
|
||||
}
|
||||
|
||||
func (p *printer) printf(format string, args ...interface{}) {
|
||||
func (p *printer) Printf(format string, args ...interface{}) {
|
||||
if p.err != nil {
|
||||
return
|
||||
}
|
||||
_, p.err = fmt.Fprintf(p.w, format, args...)
|
||||
_, p.err = fmt.Fprintf(&p.buf, format, args...)
|
||||
}
|
||||
|
||||
func (p *printer) Err() error {
|
||||
return p.err
|
||||
func (p *printer) Result() ([]byte, error) {
|
||||
return p.buf.Bytes(), p.err
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user