-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.go
More file actions
54 lines (48 loc) · 1.03 KB
/
Copy pathmain.go
File metadata and controls
54 lines (48 loc) · 1.03 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
package main
import (
"bufio"
"fmt"
"os"
)
var _globalEnvironment = Environment{mem: make(map[string]interface{})} // should place this somewhere else.
func main() {
if len(os.Args) > 2 {
sendHelp() // because they need it
}
if len(os.Args) == 2 {
script(os.Args[1])
return
}
repl()
}
// sendHelp prints the default message for usage
func sendHelp() {
fmt.Print("glox: ./interpret [file]\n")
}
// script will interpret and evaluate the file
func script(file string) {
dat, err := os.ReadFile(file)
if err != nil {
panic(err) // wtf??
}
data := string(dat) // we're just slurpring the whole file in memory. Probably not a good idea.
eval(data)
}
// eval will evaluate source code, statement by statement.
func eval(code string) {
tokenScanner := NewTokenScanner(code)
tokens := tokenScanner.Scan()
parser := NewParser(tokens)
statements := parser.Parse()
for _, st := range statements {
st.eval()
}
}
func repl() {
scanner := bufio.NewScanner(os.Stdin)
for {
fmt.Print("> ")
scanner.Scan()
eval(scanner.Text())
}
}