forked from goby-lang/goby
-
Notifications
You must be signed in to change notification settings - Fork 0
/
goby.go
114 lines (88 loc) · 2.02 KB
/
goby.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
package main
import (
"flag"
"fmt"
"github.com/goby-lang/goby/bytecode"
"github.com/goby-lang/goby/parser"
"github.com/goby-lang/goby/vm"
"github.com/pkg/profile"
"io/ioutil"
"log"
"os"
"path"
"path/filepath"
"strings"
)
// Version stores current Goby version
const Version string = "0.0.1"
func main() {
compileOptionPtr := flag.Bool("c", false, "Compile to bytecode")
profileOptionPtr := flag.Bool("p", false, "Profile program execution")
versionOptionPtr := flag.Bool("v", false, "Show current Goby version")
flag.Parse()
if *profileOptionPtr {
defer profile.Start().Stop()
}
if *versionOptionPtr {
fmt.Println(Version)
os.Exit(0)
}
filepath := flag.Arg(0)
if filepath == "" {
flag.Usage()
os.Exit(0)
}
args := flag.Args()[1:]
dir, filename, fileExt := extractFileInfo(filepath)
file := readFile(filepath)
switch fileExt {
case "gb":
program := parser.BuildAST(file)
g := bytecode.NewGenerator(program)
bytecodes := g.GenerateByteCode(program)
if !*compileOptionPtr {
v := vm.New(dir, args)
v.ExecBytecodes(bytecodes, filepath)
return
}
writeByteCode(bytecodes, dir, filename)
case "gbbc":
bytecodes := string(file)
v := vm.New(dir, args)
v.ExecBytecodes(bytecodes, filepath)
default:
fmt.Printf("Unknown file extension: %s", fileExt)
}
}
func sourcePath() string {
dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
if err != nil {
log.Fatal(err)
}
return dir
}
func extractFileInfo(filepath string) (dir, filename, fileExt string) {
dir, filename = path.Split(filepath)
splitedFN := strings.Split(filename, ".")
if len(splitedFN) <= 1 {
fmt.Printf("Only support eval/compile single file now.")
return
}
filename = splitedFN[0]
fileExt = splitedFN[1]
return
}
func writeByteCode(bytecodes, dir, filename string) {
f, err := os.Create(dir + filename + ".gbbc")
if err != nil {
panic(err)
}
f.WriteString(bytecodes)
}
func readFile(filepath string) []byte {
file, err := ioutil.ReadFile(filepath)
if err != nil {
panic(err)
}
return file
}