Files
avo/internal/gen/gen.go
Josh Bleecher Snyder 599bdd1269 internal/cmd/avogen: write output file even when gofmt fails (#165)
This makes it easier to debug avogen: when you emit invalid syntax, you can inspect the generated file to determine what went wrong, instead of having only gofmt's error to work with.
2021-01-03 19:29:11 -08:00

40 lines
852 B
Go

package gen
import (
"go/format"
"github.com/mmcloughlin/avo/internal/inst"
"github.com/mmcloughlin/avo/printer"
)
// Interface of an instruction code generator.
type Interface interface {
Generate([]inst.Instruction) ([]byte, error)
}
// Func adapts a function to Interface.
type Func func([]inst.Instruction) ([]byte, error)
// Generate calls f.
func (f Func) Generate(is []inst.Instruction) ([]byte, error) {
return f(is)
}
// Builder constructs a code generator.
type Builder func(printer.Config) Interface
// 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
}
formatted, err := format.Source(b)
if err != nil {
return b, err
}
return formatted, nil
})
}