-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
82 lines (77 loc) · 1.56 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
package main
import (
"bufio"
"fmt"
"github.com/fatih/color"
"golox/interp"
"golox/lexer"
"golox/parser"
"golox/report"
"os"
)
// Run interprets source code
func Run(source string, intp *interp.Interpreter, show bool) {
scanner := lexer.NewLexer(source)
p := parser.New(&scanner)
prog := p.ParseProgram()
es := p.Errors()
if len(es) > 0 {
fmt.Printf("%s\n", color.MagentaString("%d parsing errors encountered.", len(es)))
for _, e := range p.Errors() {
fmt.Printf("%s %s\n", color.RedString("Error:"), e)
}
} else {
defer func() {
if err := recover(); err != nil {
fmt.Println(color.RedString("Runtime Error:"), err)
}
}()
if show {
fmt.Println(color.BlueString("%s", prog))
obj := intp.Eval(prog)
if obj != nil {
fmt.Println(" -> ", color.GreenString("%s", obj))
}
intp.PrintEnv()
}
}
}
// RunPrompt interprets lines in a REPL
func RunPrompt() {
reader := bufio.NewReader(os.Stdin)
intp := interp.New()
fmt.Print("> ")
for {
line, _, err := reader.ReadLine()
if err != nil {
os.Exit(64)
}
Run(string(line), &intp, true)
fmt.Print("> ")
report.HadError = false
}
}
// RunFile interprets a file
func RunFile(path string) {
fmt.Println("Reading from file...")
intp := interp.New()
bytes, err := os.ReadFile(path)
if err != nil {
fmt.Println(err)
os.Exit(64)
}
Run(string(bytes), &intp, true)
if report.HadError {
os.Exit(65)
}
}
func main() {
if len(os.Args) > 2 {
fmt.Println("Usage: golox [script]")
os.Exit(64)
} else if len(os.Args) == 2 {
RunFile(os.Args[1])
} else {
RunPrompt()
}
}