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"
|
2018-12-11 00:18:22 -08:00
|
|
|
"github.com/mmcloughlin/avo/printer"
|
2018-11-21 13:02:18 -06:00
|
|
|
)
|
|
|
|
|
|
2019-01-05 14:12:50 -08: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
|
|
|
}
|
|
|
|
|
|
2019-01-05 14:12:50 -08: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
|
|
|
|
2019-01-05 14:12:50 -08: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)
|
|
|
|
|
}
|
|
|
|
|
|
2019-01-05 14:12:50 -08:00
|
|
|
// Builder constructs a code generator.
|
2018-12-11 00:18:22 -08:00
|
|
|
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
|
|
|
|
|
}
|
|
|
|
|
return format.Source(b)
|
|
|
|
|
})
|
2018-11-21 13:02:18 -06:00
|
|
|
}
|