-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgolox.go
83 lines (67 loc) · 1.5 KB
/
golox.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
package main
import (
"bufio"
"errors"
"fmt"
"io/ioutil"
"log"
"os"
"github.com/maleksiuk/golox/errorreport"
"github.com/maleksiuk/golox/interpreter"
"github.com/maleksiuk/golox/parser"
"github.com/maleksiuk/golox/scanner"
)
func main() {
args := os.Args[1:]
argCount := len(args)
i := interpreter.NewInterpreter()
switch {
case argCount > 1:
fmt.Println("Usage: golox [script]")
case argCount == 1:
err := runFile(i, args[0])
if err != nil {
os.Exit(1)
}
default:
runPrompt(i)
}
}
func runFile(i interpreter.Interpreter, path string) error {
errorReport := errorreport.NewErrorReport()
buf, err := ioutil.ReadFile(path)
if err != nil {
log.Print(err)
return err
}
run(i, string(buf), &errorReport)
if errorReport.HadError {
return errors.New("Scanner error")
}
if errorReport.HadRuntimeError {
return errors.New("Runtime error")
}
return nil
}
func runPrompt(i interpreter.Interpreter) {
errorReport := errorreport.NewErrorReport()
scanner := bufio.NewScanner(os.Stdin)
fmt.Print("> ")
for scanner.Scan() {
run(i, scanner.Text(), &errorReport)
errorReport.HadError = false
fmt.Print("> ")
}
if err := scanner.Err(); err != nil {
log.Fatal(err)
}
}
func run(i interpreter.Interpreter, line string, errorReport *errorreport.ErrorReport) {
tokens := scanner.ScanTokens(line, errorReport)
statements := parser.Parse(tokens, errorReport)
// Stop if there was a syntax error.
if errorReport.HadError {
return
}
i.Interpret(statements, errorReport)
}