-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
101 lines (86 loc) · 1.78 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
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
package main
import (
"fmt"
"io"
"io/ioutil"
"monkey/evaluator"
"monkey/lexer"
"monkey/object"
"monkey/parser"
"monkey/repl"
"os"
"os/user"
"path/filepath"
)
func main() {
if len(os.Args) == 1 {
startRepl()
} else if len(os.Args) == 2 {
runFile(os.Args[1])
}
}
func startRepl() {
user, err := user.Current()
if err != nil {
panic(err)
}
fmt.Printf("Hello %s! This is the Monkey programming language!\n", user.Username)
fmt.Printf("Feel free to type in commands\n")
repl.Start(os.Stdin, os.Stdout)
}
func runFile(file string) {
if !fileExists(file) {
fmt.Println("File not found")
return
}
if !checkExt(file) {
fmt.Println("File type not supported")
return
}
dat, err := ioutil.ReadFile(file)
check(err)
env := object.NewEnviroment()
l := lexer.New(string(dat))
p := parser.New(l)
program := p.ParseProgram()
if len(p.Errors()) != 0 {
printParserErrors(os.Stdout, p.Errors())
return
}
evaluator.Eval(program, env)
}
func check(e error) {
if e != nil {
panic(e)
}
}
func fileExists(filename string) bool {
info, err := os.Stat(filename)
if os.IsNotExist(err) {
return false
}
return !info.IsDir()
}
func checkExt(filename string) bool {
return filepath.Ext(filename) == ".mky"
}
const monkeyFace = ` __,__
.--. .-" "-. .--.
/ .. \/ .-. .-. \/ .. \
| | '| / Y \ |' | |
| \ \ \ 0 | 0 / / / |
\ '- ,\.-"""""""-./, -' /
''-' /_ ^ ^ _\ '-''
| \._ _./ |
\ \ '~' / /
'._ '-=-' _.'
'-----'
`
func printParserErrors(out io.Writer, errors []string) {
io.WriteString(out, monkeyFace)
io.WriteString(out, "Whoops! We ran into some monkey business here!\n")
io.WriteString(out, " parser errors:\n")
for _, msg := range errors {
io.WriteString(out, "\t"+msg+"\n")
}
}