-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
73 lines (63 loc) · 1.36 KB
/
main.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
package main
import (
"fmt"
"io/ioutil"
"os"
bf "github.com/vladk1m0/gbfm/brainfuck"
)
var usage string =`
usage: gbfm [run|translate] file.bf
run brainfuck program file.bf
translate brainfuck program file.bf into file.bf.js
`
func printHelp() {
fmt.Fprint(os.Stderr, usage)
os.Exit(0)
}
func main() {
if len(os.Args) != 3 {
printHelp()
}
cmd := os.Args[1]
if cmd != "translate" && cmd != "run" {
printHelp()
}
finName := os.Args[2]
if _, err := os.Stat(finName); err != nil {
fmt.Fprintf(os.Stderr, "%v\n", err)
os.Exit(1)
}
in, err := os.Open(finName)
if err != nil {
fmt.Fprintf(os.Stderr, "%v\n", err)
os.Exit(1)
}
srcCode, err := ioutil.ReadAll(in)
if err != nil {
fmt.Fprintf(os.Stderr, "%v\n", err)
os.Exit(1)
}
switch cmd {
case "run":
interpreter := bf.NewInterpreter(os.Stdin, os.Stdout)
_, err = interpreter.Run(srcCode)
if err != nil {
fmt.Fprintf(os.Stderr, "%v\n", err)
os.Exit(2)
}
case "translate":
transpiler := bf.NewTranspiler(bf.NewJSTranspilerTarget())
dstCode, err := transpiler.Transpile(srcCode)
if err != nil {
fmt.Fprintf(os.Stderr, "%v\n", err)
os.Exit(2)
}
foutName := finName + ".js"
err = ioutil.WriteFile(foutName, []byte(dstCode), 0644)
if err != nil {
fmt.Fprintf(os.Stderr, "%v\n", err)
os.Exit(1)
}
fmt.Fprintf(os.Stdout, "create out file [%s]\n", foutName)
}
}