-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgolox.go
96 lines (80 loc) · 1.97 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
84
85
86
87
88
89
90
91
92
93
94
95
96
package main
import (
"bufio"
"fmt"
"io/ioutil"
"os"
"github.com/taki-mekhalfa/golox/interpreter"
"github.com/taki-mekhalfa/golox/parser"
"github.com/taki-mekhalfa/golox/resolver"
"github.com/taki-mekhalfa/golox/scanner"
)
const EX_USAGE = 64
const EX_DATAERR = 65
var syntaxErrFunc = func(line int, errMessage string) {
fmt.Printf("[line %d] Syntax Error: %s\n", line, errMessage)
}
var runtimeErrFunc = func(line int, errMessage string) {
fmt.Printf("[line %d] Runtime Error: %s\n", line, errMessage)
}
var interpreter_ = interpreter.Interpreter{Error: runtimeErrFunc}
func run(code string) error {
scanner := scanner.Scanner{Error: syntaxErrFunc}
scanner.Init(code)
scanner.Scan()
if scanner.ErrorCount != 0 {
return fmt.Errorf("encountred %d scanner errors", scanner.ErrorCount)
}
parser := parser.Parser{Error: syntaxErrFunc}
parser.Init(scanner.Tokens())
stmts := parser.Parse()
if parser.ErrorCount != 0 {
return fmt.Errorf("encountred %d parser errors", parser.ErrorCount)
}
resolver := &resolver.Resolver{
Error: runtimeErrFunc,
Interp: &interpreter_,
}
resolver.Resolve(stmts)
if resolver.ErrorCount != 0 {
return fmt.Errorf("encountred %d resolver errors", parser.ErrorCount)
}
interpreter_.Interpret(stmts)
if interpreter_.ErrorCount != 0 {
return fmt.Errorf("encountred %d interpreter errors", parser.ErrorCount)
}
return nil
}
func runPrompt() {
scanner := bufio.NewScanner(os.Stdin)
for {
fmt.Print(">> ")
if !scanner.Scan() {
if err := scanner.Err(); err != nil {
panic(err)
}
break
}
_ = run(scanner.Text())
interpreter_.ResetErrors()
}
}
func main() {
if len(os.Args) > 2 {
fmt.Println("Usage: golox [script]")
os.Exit(EX_USAGE)
}
interpreter_.Init()
if len(os.Args) == 2 {
b, err := ioutil.ReadFile(os.Args[1])
if err != nil {
fmt.Printf("Could not read the source file: %+v", err)
os.Exit(1)
}
if err := run(string(b)); err != nil {
os.Exit(EX_DATAERR)
}
} else {
runPrompt()
}
}