-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathglox.go
More file actions
78 lines (66 loc) · 1.48 KB
/
glox.go
File metadata and controls
78 lines (66 loc) · 1.48 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
package main
import (
"bufio"
"flag"
"fmt"
"io/ioutil"
"os"
"github.com/rmonnet/glox/interp"
)
const (
exUsage = 64
exDataErr = 65
exSwErr = 70
)
// main runs the glox interpreter command line
// it will:
// - interpret the script passed as argument
// - run the lox shell if no argument is passed
// - error if more than one argument is passed
func main() {
parseOnly := flag.Bool("parseOnly", false, "parse and dump the AST")
flag.Parse()
args := flag.Args()
if len(args) > 1 {
fmt.Println("Usage glox [-parseOnly] [script]")
os.Exit(exUsage)
} else if len(args) == 1 {
runFile(args[0], *parseOnly)
} else {
runPrompt(*parseOnly)
}
}
// runFile runs the lox interpreter on the
// script in the file
func runFile(filename string, parseOnly bool) {
script, err := ioutil.ReadFile(filename)
if err != nil {
fmt.Println("unable to read ", filename)
os.Exit(exDataErr)
}
interp := interp.New(os.Stdout, os.Stderr)
interp.Run(string(script), parseOnly)
if interp.HadCompileError() {
os.Exit(exDataErr)
}
if interp.HadRuntimeError() {
os.Exit(exSwErr)
}
}
// runPrompt runs the lox interpreter interactively
func runPrompt(parseOnly bool) {
scanner := bufio.NewScanner(os.Stdin)
interp := interp.New(os.Stdout, os.Stderr)
for {
fmt.Print("> ")
if !scanner.Scan() {
fmt.Println("")
break
}
interp.Run(scanner.Text(), parseOnly)
}
if err := scanner.Err(); err != nil {
fmt.Println("error while reading ", err)
os.Exit(exDataErr)
}
}