forked from djhworld/simple-computer
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
88 lines (70 loc) · 1.84 KB
/
main.go
File metadata and controls
88 lines (70 loc) · 1.84 KB
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
package main
import (
"encoding/binary"
"flag"
"fmt"
"io"
"os"
"github.com/djhworld/simple-computer/asm"
)
const USER_CODE_START = uint16(0x0500)
var inputFile = flag.String("i", "", "input file (default: stdin)")
var outputFile = flag.String("o", "", "output file (default: stdout)")
var render = flag.Bool("s", false, "output assembly as string")
func exitWithError(message string, err error, exitCode int) {
fmt.Fprintln(os.Stderr, message, err)
fmt.Fprint(os.Stderr, "\n")
flag.Usage()
os.Exit(exitCode)
}
func main() {
flag.Parse()
reader, err := getReaderFor(*inputFile)
if err != nil {
exitWithError("error reading input: ", err, 5)
}
defer reader.Close()
parser := asm.Parser{}
instructions, err := parser.Parse(reader)
if err != nil {
exitWithError("error parsing input: ", err, 104)
}
asm := asm.Assembler{}
if *render == false {
rawIns, err := asm.Process(USER_CODE_START, instructions)
if err != nil {
exitWithError("error assembling input: ", err, 104)
}
writer, err := getWriterFor(*outputFile)
if err != nil {
exitWithError("error getting output handle: ", err, 104)
}
defer writer.Close()
if err := binary.Write(writer, binary.LittleEndian, rawIns); err != nil {
exitWithError("error writing output handle: ", err, 5)
}
} else {
str, err := asm.ToString(USER_CODE_START, instructions)
if err != nil {
exitWithError("error assembling input: ", err, 104)
}
writer, err := getWriterFor(*outputFile)
if err != nil {
exitWithError("error getting output handle: ", err, 104)
}
defer writer.Close()
fmt.Fprint(writer, str)
}
}
func getReaderFor(file string) (io.ReadCloser, error) {
if file == "" {
return os.Stdin, nil
}
return os.Open(file)
}
func getWriterFor(file string) (io.WriteCloser, error) {
if file == "" {
return os.Stdout, nil
}
return os.Create(file)
}