-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparser.go
117 lines (98 loc) · 2.13 KB
/
parser.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
package hackassembler
import (
"bufio"
"io"
"strings"
)
type (
Parser struct {
Contents io.Reader
}
InstructionType string
Instruction struct {
Type InstructionType
Symbol string
Dest string
Comp string
Jump string
}
)
const (
AInstruction InstructionType = "A"
CInstruction InstructionType = "C"
LInstruction InstructionType = "L"
)
func NewParser(contents io.Reader) *Parser {
return &Parser{Contents: contents}
}
func (p *Parser) Parse() <-chan Instruction {
instructions := make(chan Instruction)
scanner := bufio.NewScanner(p.Contents)
scanner.Split(bufio.ScanLines)
go func() {
defer close(instructions)
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
if p.SkipLine(line) {
continue
}
switch p.GetInstructionType(line) {
case AInstruction:
instructions <- Instruction{
Type: AInstruction,
Symbol: p.GetSymbol(line),
}
case CInstruction:
instructions <- Instruction{
Type: CInstruction,
Dest: p.GetDest(line),
Comp: p.GetComp(line),
Jump: p.GetJump(line),
}
case LInstruction:
// TODO: Handle this instruction, later.
}
}
}()
return instructions
}
func (p *Parser) SkipLine(line string) bool {
return strings.HasPrefix(line, "//") || line == ""
}
func (p *Parser) GetInstructionType(line string) InstructionType {
// TODO: Error handling, later
if strings.HasPrefix(line, "@") {
return AInstruction
} else if strings.HasPrefix(line, "(") {
return LInstruction
} else {
return CInstruction
}
}
func (p *Parser) GetSymbol(line string) string {
return strings.TrimLeft(line, "@")
}
func (p *Parser) GetDest(line string) string {
splitDest := strings.Split(line, "=")
if len(splitDest) == 1 {
return ""
}
return splitDest[0]
}
func (p *Parser) GetComp(line string) string {
splitDest := strings.Split(line, "=")
var noDest string
if len(splitDest) > 1 {
noDest = splitDest[1]
} else {
noDest = splitDest[0]
}
return strings.Split(noDest, ";")[0]
}
func (p *Parser) GetJump(line string) string {
splitJump := strings.Split(line, ";")
if len(splitJump) == 1 {
return ""
}
return splitJump[1]
}