| 1 | package gen |
| 2 | |
| 3 | import ( |
| 4 | "go/format" |
| 5 | |
| 6 | "github.com/mmcloughlin/avo/internal/inst" |
| 7 | "github.com/mmcloughlin/avo/printer" |
| 8 | ) |
| 9 | |
| 10 | // Interface of an instruction code generator. |
| 11 | type Interface interface { |
| 12 | Generate([]inst.Instruction) ([]byte, error) |
| 13 | } |
| 14 | |
| 15 | // Func adapts a function to Interface. |
| 16 | type Func func([]inst.Instruction) ([]byte, error) |
| 17 | |
| 18 | // Generate calls f. |
| 19 | func (f Func) Generate(is []inst.Instruction) ([]byte, error) { |
| 20 | return f(is) |
| 21 | } |
| 22 | |
| 23 | // Builder constructs a code generator. |
| 24 | type Builder func(printer.Config) Interface |
| 25 | |
| 26 | // GoFmt formats Go code produced from the given generator. |
| 27 | func GoFmt(i Interface) Interface { |
| 28 | return Func(func(is []inst.Instruction) ([]byte, error) { |
| 29 | b, err := i.Generate(is) |
| 30 | if err != nil { |
| 31 | return nil, err |
| 32 | } |
| 33 | formatted, err := format.Source(b) |
| 34 | if err != nil { |
| 35 | return b, err |
| 36 | } |
| 37 | return formatted, nil |
| 38 | }) |
| 39 | } |