-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathassembler.go
110 lines (88 loc) · 2.31 KB
/
assembler.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
package main
import (
"fmt"
"hack_assembler/code"
"hack_assembler/parser"
"os"
"regexp"
"strconv"
)
func main() {
argFilepath := os.Args[1]
if _, err := os.Stat(argFilepath); os.IsNotExist(err) {
fmt.Fprintf(os.Stderr, "error: %v\n", err)
os.Exit(1)
}
symbolParser := parser.New(argFilepath)
if err := symbolParser.OpenFile(); err != nil {
fmt.Fprintf(os.Stderr, "error: %v\n", err)
os.Exit(1)
}
err := symbolParser.Advance()
for err == nil {
commandType := symbolParser.CommandType()
if commandType == parser.LCommand {
symbolParser.AddSymbolLineNumber(symbolParser.GetSymbol())
}
err = symbolParser.Advance()
}
newFilePath := os.Args[2]
newFile, err := os.Create(newFilePath)
if err != nil {
fmt.Fprintf(os.Stderr, "error: %v\n", err)
os.Exit(1)
}
defer newFile.Close()
mainParser := parser.NewWithSymbol(argFilepath, symbolParser.GetSymbolTable())
if err := mainParser.OpenFile(); err != nil {
fmt.Fprintf(os.Stderr, "error: %v\n", err)
os.Exit(1)
}
err = mainParser.Advance()
for err == nil {
newLine := ""
commandType := mainParser.CommandType()
if commandType == parser.ACommand {
newLine = "0"
//assumes symbol is number already
reg := regexp.MustCompile(`[A-z]`)
currentCommand := mainParser.GetSymbol()
regTest := reg.FindStringSubmatch(currentCommand)
var symbolInt int64
if regTest != nil {
if !mainParser.ContainsSymbol(currentCommand) {
mainParser.AddRamSymbol(currentCommand)
}
symbolInt = int64(mainParser.GetAddress(currentCommand))
} else {
symbolInt, err = strconv.ParseInt(currentCommand, 10, 64)
}
if err != nil {
fmt.Fprintf(os.Stderr, "error: %v\n", err)
os.Exit(1)
}
symbol := strconv.FormatInt(symbolInt, 2)
for len(symbol) < 15 {
symbol = "0" + symbol
}
newLine += symbol
}
if commandType == parser.CCommand {
newLine = "111"
destination := mainParser.GetDestination()
comp := mainParser.GetComp()
jump := mainParser.GetJump()
newLine += code.CompToBinary(comp)
newLine += code.DestToBinary(destination)
newLine += code.JumpToBinary(jump)
}
if commandType != parser.LCommand {
newLine += "\n"
}
if _, err := newFile.WriteString(newLine); err != nil {
fmt.Fprintf(os.Stderr, "error: %v\n", err)
os.Exit(1)
}
err = mainParser.Advance()
}
}