printing: commit some refactors (probably broken)

This commit is contained in:
Michael McLoughlin
2018-12-11 00:18:22 -08:00
parent 4dc909a81e
commit c882e52510
21 changed files with 398 additions and 222 deletions

63
printer/goasm.go Normal file
View File

@@ -0,0 +1,63 @@
package printer
import (
"strings"
"github.com/mmcloughlin/avo"
"github.com/mmcloughlin/avo/internal/prnt"
"github.com/mmcloughlin/avo/operand"
)
// dot is the pesky unicode dot used in Go assembly.
const dot = "\u00b7"
type goasm struct {
cfg Config
prnt.Generator
}
func NewGoAsm(cfg Config) Printer {
return &goasm{cfg: cfg}
}
func (p *goasm) Print(f *avo.File) ([]byte, error) {
p.header()
for _, fn := range f.Functions {
p.function(fn)
}
return p.Result()
}
func (p *goasm) header() {
p.NL()
p.include("textflag.h")
p.NL()
}
func (p *goasm) include(path string) {
p.Printf("#include \"%s\"\n", path)
}
func (p *goasm) function(f *avo.Function) {
p.Comment(f.Stub())
p.Printf("TEXT %s%s(SB),0,$%d-%d\n", dot, f.Name, f.FrameBytes(), f.ArgumentBytes())
for _, node := range f.Nodes {
switch n := node.(type) {
case *avo.Instruction:
p.Printf("\t%s\t%s\n", n.Opcode, joinOperands(n.Operands))
case avo.Label:
p.Printf("%s:\n", n)
default:
panic("unexpected node type")
}
}
}
func joinOperands(operands []operand.Op) string {
asm := make([]string, len(operands))
for i, op := range operands {
asm[i] = op.Asm()
}
return strings.Join(asm, ", ")
}

43
printer/printer.go Normal file
View File

@@ -0,0 +1,43 @@
package printer
import (
"fmt"
"os"
"path/filepath"
"strings"
"github.com/mmcloughlin/avo"
)
type Printer interface {
Print(*avo.File) ([]byte, error)
}
type Builder func(Config) Printer
type Config struct {
Name string
Argv []string
Pkg string
}
func NewDefaultConfig() Config {
cfg := Config{
Argv: os.Args,
}
if cwd, err := os.Getwd(); err == nil {
cfg.Pkg = filepath.Base(cwd)
}
return cfg
}
func (c Config) GeneratedBy() string {
if c.Argv == nil {
return c.Name
}
return fmt.Sprintf("command: %s", strings.Join(c.Argv, " "))
}
func (c Config) GeneratedWarning() string {
return fmt.Sprintf("Code generated by %s. DO NOT EDIT.", c.GeneratedBy())
}

23
printer/stubs.go Normal file
View File

@@ -0,0 +1,23 @@
package printer
import (
"github.com/mmcloughlin/avo"
"github.com/mmcloughlin/avo/internal/prnt"
)
type stubs struct {
cfg Config
prnt.Generator
}
func NewStubs(cfg Config) Printer {
return &stubs{cfg: cfg}
}
func (s *stubs) Print(f *avo.File) ([]byte, error) {
s.Printf("package %s\n\n", s.cfg.Pkg)
for _, fn := range f.Functions {
s.Printf("%s\n", fn.Stub())
}
return s.Result()
}