-
Notifications
You must be signed in to change notification settings - Fork 2
/
emit.go
140 lines (113 loc) · 2.32 KB
/
emit.go
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
package asm
import (
"fmt"
"io"
"strings"
)
type Emitter struct {
out io.Writer
src []string
section Section
indent string
}
func NewEmitter(out io.Writer) *Emitter {
return &Emitter{
out: out,
}
}
func (emit *Emitter) Func(fn *Func) {
for _, glob := range fn.Globals {
emit.global(glob)
}
emit.ensureSection(Code)
emit.line("")
emit.line("; %s", fn.Comment)
emit.line("%s:", fn.Label)
for _, blk := range fn.Blocks {
emit.block(blk)
}
emit.line("")
}
func (emit *Emitter) global(glob *Global) {
emit.ensureSection(glob.Section)
emit.line("%s:", glob.Label)
emit.indent = " "
if glob.Comment != "" {
emit.line("; %s", glob.Comment)
}
for _, l := range glob.Strings {
emit.line("%s", l)
}
emit.indent = ""
emit.line("")
}
func (emit *Emitter) ensureSection(section Section) {
if emit.section != section {
emit.line("#bank %s", section)
emit.section = section
}
}
func (emit *Emitter) block(blk *Block) {
emit.line("%s:", blk.Label)
emit.indent = " "
// this will emit bits of the original source to aid debugging
emit.source(blk.Block.Source)
for _, instr := range blk.Instrs {
emit.instr(instr)
}
emit.indent = ""
}
func (emit *Emitter) arg(v *Var) string {
if v.String != "" {
return v.String
}
if v.Value != nil {
return v.Value.String()
}
if v.Block != nil {
return "." + v.Block.String()
}
return ""
}
func (emit *Emitter) instr(instr *Instr) {
templ := instr.Op.Fmt().Template()
name := instr.Op.Asm()
if instr.Indent {
name = " " + name
}
for len(name) < 6 {
name += " "
}
strs := []interface{}{name}
for _, arg := range instr.Args {
strs = append(strs, emit.arg(arg))
}
emit.line("%s "+templ, strs...)
}
func (emit *Emitter) line(fmtstr string, args ...interface{}) {
nextline := ""
if len(emit.src) > 0 {
nextline, emit.src = emit.src[len(emit.src)-1], emit.src[:len(emit.src)-1]
}
output := fmt.Sprintf(emit.indent+fmtstr, args...)
if nextline != "" {
for len(output) < 30 {
output += " "
}
output += "; "
output += nextline
}
fmt.Fprintln(emit.out, output)
}
func (emit *Emitter) source(src string) {
if src == "" {
return
}
lines := strings.Split(src, "\n")
var revlines []string
for i := len(lines) - 1; i >= 0; i-- {
revlines = append(revlines, lines[i])
}
revlines = append(revlines, emit.src...)
emit.src = revlines
}