-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrun.go
58 lines (52 loc) · 969 Bytes
/
run.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
package main
import (
"bufio"
"bytes"
"errors"
"fmt"
"io"
"os"
"github.com/kevinmingtarja/golox/scanner"
)
func runFile(path string) error {
f, err := os.Open(path)
if err != nil {
return err
}
defer f.Close()
bytes, err := io.ReadAll(f)
if err != nil {
return err
}
return run(bytes)
}
func runPrompt() error {
sc := bufio.NewScanner(os.Stdin)
for fmt.Print("> "); sc.Scan(); fmt.Print("> ") {
line := sc.Bytes()
if bytes.Equal(line, []byte("exit")) {
break
}
err := run(line)
if err != nil {
if !errors.As(err, &scanner.Error{}) {
return err
}
// don't kill the entire session if the user makes a mistake
fmt.Println(err.Error())
}
}
if err := sc.Err(); err != nil {
if err != io.EOF {
return err
}
}
return nil
}
func run(src []byte) error {
scanner := scanner.New(src, func(line int, message string) {
fmt.Printf("[line %d] Error: %s\n", line, message)
})
scanner.ScanTokens()
return nil
}