Files
avo/build/context.go

80 lines
1.3 KiB
Go
Raw Normal View History

2018-11-30 20:43:31 -08:00
package build
import (
"errors"
"io"
"log"
"github.com/mmcloughlin/avo"
2018-12-03 20:40:43 -08:00
"github.com/mmcloughlin/avo/reg"
2018-11-30 20:43:31 -08:00
)
type Context struct {
file *avo.File
function *avo.Function
errs []error
2018-12-03 20:40:43 -08:00
reg.Collection
2018-11-30 20:43:31 -08:00
}
func NewContext() *Context {
return &Context{
2018-12-03 20:40:43 -08:00
file: avo.NewFile(),
Collection: *reg.NewCollection(),
2018-11-30 20:43:31 -08:00
}
}
2018-11-30 20:58:51 -08:00
func (c *Context) Function(name string) {
2018-11-30 20:43:31 -08:00
c.function = avo.NewFunction(name)
c.file.Functions = append(c.file.Functions, c.function)
}
2018-12-02 23:59:29 -08:00
func (c *Context) Instruction(i *avo.Instruction) {
2018-11-30 21:37:17 -08:00
c.node(i)
}
func (c *Context) Label(l avo.Label) {
c.node(l)
}
func (c *Context) node(n avo.Node) {
2018-11-30 20:43:31 -08:00
if c.function == nil {
c.AddErrorMessage("no active function")
return
}
2018-11-30 21:37:17 -08:00
c.function.AddNode(n)
2018-11-30 20:43:31 -08:00
}
2018-11-30 20:58:51 -08:00
//go:generate avogen -output zinstructions.go build
2018-11-30 20:43:31 -08:00
func (c *Context) AddError(err error) {
c.errs = append(c.errs, err)
}
func (c *Context) AddErrorMessage(msg string) {
c.AddError(errors.New(msg))
}
func (c *Context) Result() (*avo.File, []error) {
return c.file, c.errs
}
2018-11-30 21:37:17 -08:00
func (c *Context) Main(wout, werr io.Writer) int {
2018-11-30 20:43:31 -08:00
diag := log.New(werr, "", 0)
f, errs := c.Result()
if errs != nil {
for _, err := range errs {
diag.Println(err)
}
2018-11-30 21:37:17 -08:00
return 1
2018-11-30 20:43:31 -08:00
}
p := avo.NewGoPrinter(wout)
if err := p.Print(f); err != nil {
2018-11-30 21:37:17 -08:00
diag.Println(err)
return 1
2018-11-30 20:43:31 -08:00
}
2018-11-30 21:37:17 -08:00
return 0
2018-11-30 20:43:31 -08:00
}