-
Notifications
You must be signed in to change notification settings - Fork 3
/
main.go
99 lines (80 loc) · 1.69 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
//go:generate go run cmd/ast.go
package main
import (
"bufio"
"flag"
"fmt"
"io"
"io/ioutil"
"os"
"github.com/chidiwilliams/glox/ast"
"github.com/chidiwilliams/glox/interpret"
"github.com/chidiwilliams/glox/parse"
"github.com/chidiwilliams/glox/resolve"
"github.com/chidiwilliams/glox/scan"
)
var (
hadError bool
hadRuntimeError bool
r = newRunner(os.Stdout, os.Stderr)
)
func main() {
var filePath string
flag.StringVar(&filePath, "filePath", "", "File path")
flag.Parse()
if filePath == "" {
runPrompt()
} else {
runFile(filePath)
}
}
func runPrompt() {
inputScanner := bufio.NewScanner(os.Stdin)
for {
fmt.Print("> ")
if !inputScanner.Scan() {
break
}
line := inputScanner.Text()
fmt.Println(r.run(line))
hadError = false
}
}
func runFile(path string) {
file, err := ioutil.ReadFile(path)
if err != nil {
panic(err)
}
r.run(string(file))
if hadError {
os.Exit(65)
}
if hadRuntimeError {
os.Exit(70)
}
}
func newRunner(stdOut io.Writer, stdErr io.Writer) runner {
return runner{interpreter: interpret.NewInterpreter(stdOut, stdErr), stdErr: stdErr}
}
type runner struct {
interpreter *interpret.Interpreter
stdErr io.Writer
}
func (r *runner) run(source string) interface{} {
scanner := scan.NewScanner(source, r.stdErr)
tokens := scanner.ScanTokens()
parser := parse.NewParser(tokens, r.stdErr)
var statements []ast.Stmt
statements, hadError = parser.Parse()
if hadError {
return nil
}
resolver := resolve.NewResolver(r.interpreter, r.stdErr)
hadError = resolver.ResolveStmts(statements)
if hadError {
return nil
}
var result interface{}
result, hadRuntimeError = r.interpreter.Interpret(statements)
return result
}