-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathlox.go
107 lines (85 loc) · 1.84 KB
/
lox.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
100
101
102
103
104
105
106
107
package lox
import (
"bufio"
"context"
"fmt"
"io"
"os"
"github.com/nanmu42/bluelox/resolver"
"github.com/nanmu42/bluelox/interpreter"
"github.com/nanmu42/bluelox/parser"
"github.com/nanmu42/bluelox/scanner"
)
type Lox struct {
interpreter *interpreter.Interpreter
}
func NewLox(stdout io.Writer) *Lox {
return &Lox{
interpreter: interpreter.NewInterpreter(stdout),
}
}
func (l *Lox) RunFile(ctx context.Context, path string) (err error) {
script, err := os.ReadFile(path)
if err != nil {
err = fmt.Errorf("reading script file: %w", err)
return
}
err = l.Run(ctx, script)
if err != nil {
err = fmt.Errorf("running script: %w", err)
return
}
return
}
func (l *Lox) RunPrompt(ctx context.Context) (err error) {
lineReader := bufio.NewScanner(os.Stdin)
fmt.Printf("> ")
for lineReader.Scan() {
line := lineReader.Bytes()
if len(line) == 0 {
break
}
err = l.Run(ctx, line)
if err != nil {
fmt.Println(err)
}
fmt.Printf("> ")
}
err = lineReader.Err()
if err != nil {
err = fmt.Errorf("reading input: %w", err)
return
}
return
}
// Run provided script.
// context is used to early stop interpretation on statement level.
//
// The provided script is read only, should not be modified.
func (l *Lox) Run(ctx context.Context, script []byte) (err error) {
s := scanner.NewScanner(script)
tokens, err := s.ScanTokens()
if err != nil {
err = fmt.Errorf("scaning tokens: %w", err)
return
}
p := parser.NewParser(tokens)
stmts, err := p.Parse()
if err != nil {
return
}
resolve := resolver.NewResolver(l.interpreter)
err = resolve.ResolveStmts(stmts)
if err != nil {
err = fmt.Errorf("resolving statements: %w", err)
return
}
err = l.interpreter.Interpret(ctx, stmts)
if err != nil {
return
}
return
}
func (l *Lox) ChangeStdoutTo(writer io.Writer) {
l.interpreter.ChangeStdoutTo(writer)
}