File: gen.go

package info (click to toggle)
golang-github-mmcloughlin-avo 0.5.0-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 15,024 kB
  • sloc: xml: 71,029; asm: 14,862; sh: 194; makefile: 21; ansic: 11
file content (39 lines) | stat: -rw-r--r-- 852 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
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
	})
}