Files
avo/internal/gen/gen.go

40 lines
852 B
Go
Raw Normal View History

2018-11-21 13:02:18 -06:00
package gen
import (
2018-11-24 13:00:27 -08:00
"go/format"
2018-11-21 13:02:18 -06:00
"github.com/mmcloughlin/avo/internal/inst"
"github.com/mmcloughlin/avo/printer"
2018-11-21 13:02:18 -06:00
)
// Interface of an instruction code generator.
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
}
// Func adapts a function to Interface.
2018-11-24 14:20:04 -08:00
type Func func([]inst.Instruction) ([]byte, error)
2018-11-21 13:02:18 -06:00
// Generate calls f.
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)
}
// Builder constructs a code generator.
type Builder func(printer.Config) Interface
2018-11-24 13:47:30 -08:00
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
}
formatted, err := format.Source(b)
if err != nil {
return b, err
}
return formatted, nil
2018-11-24 13:00:27 -08:00
})
2018-11-21 13:02:18 -06:00
}