-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathassemble.go
76 lines (63 loc) · 2.02 KB
/
assemble.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
package main
import (
"bufio"
"fmt"
"io"
"regexp"
"strings"
"github.com/willbicks/dsdii-assembler/instruction"
"github.com/willbicks/dsdii-assembler/output"
)
// commentRegex matches comments so they can be stripped from the input.
var commentRegex *regexp.Regexp
type config struct {
in io.Reader // input reader
out output.Writer // output writer
nopBuff uint // number of nop instructions to include after each instruction
}
// stripComment removes any comments from the provided string, and returns a string containing only the instruction.
func stripComment(s string) string {
if commentRegex == nil {
commentRegex = regexp.MustCompile(`#.*?$`)
}
return strings.TrimSpace(commentRegex.ReplaceAllString(s, ""))
}
// assemble a series of instructions using the provided configuration, and return the number of lines assembled, and an error if one occurred.
func assemble(c config) (lines uint64, err error) {
if err := c.out.WriteStart("generated by dsdii-assembler"); err != nil {
return 0, fmt.Errorf("writing start: %v", err)
}
var line uint64
var mc uint32
inScan := bufio.NewScanner(c.in)
for inScan.Scan() {
line++
// strip comments and whitespace and skip parsing if result is empty
instWComment := strings.TrimSpace(inScan.Text())
instString := stripComment(instWComment)
if instString == "" {
continue
}
// assemble and write instruction
mc, err = instruction.Assemble(instString)
if err != nil {
return 0, fmt.Errorf("on line %d: %s", line, err)
}
if err := c.out.WriteInstruction(mc, instWComment); err != nil {
return 0, fmt.Errorf("writing instruction: %v", err)
}
// add nop buffer as configured
for i := uint(0); i < c.nopBuff; i++ {
if err := c.out.WriteInstruction(0, "nop buffer"); err != nil {
return 0, fmt.Errorf("writing nop: %v", err)
}
}
}
if err := inScan.Err(); err != nil {
return 0, fmt.Errorf("scan: %v", err)
}
if err := c.out.WriteEnd(); err != nil {
return 0, fmt.Errorf("writing end: %v", err)
}
return line, nil
}