-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
258 lines (229 loc) · 5.37 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
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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
package main
import (
"embed"
"flag"
"fmt"
"io"
"io/fs"
"os"
"strings"
"github.com/AlanLuu/lox/ast"
"github.com/AlanLuu/lox/loxerror"
"github.com/AlanLuu/lox/scanner"
"github.com/AlanLuu/lox/util"
"github.com/chzyer/readline"
)
const PROMPT = ">>> "
const NEXT_LINE_PROMPT = "... "
//go:embed loxcode/*
var loxCodeFS embed.FS
func usageFunc(writer io.Writer) func() {
return func() {
usage :=
`Usage: lox [OPTIONS] [FILE]
OPTIONS:
-c <code>
Execute Lox code from command line argument
--disable-loxcode, -dl
Disable execution of all Lox files that are bundled inside this interpreter executable
-h, --help
Print this usage message and exit
`
fmt.Fprint(writer, usage)
}
}
func runLoxCode(interpreter *ast.Interpreter) error {
if util.DisableLoxCode {
return nil
}
dirFunc := func(path string, d fs.DirEntry, _ error) error {
if !d.IsDir() {
program, err := loxCodeFS.ReadFile(path)
if err != nil {
fmt.Fprintf(
os.Stderr,
"Warning: failed to read Lox file '%v'.\n",
path,
)
return nil
}
sc := scanner.NewScanner(string(program))
scanErr := sc.ScanTokens()
if scanErr != nil {
return scanErr
}
parser := ast.NewParser(sc.Tokens)
exprList, parseErr := parser.Parse()
defer exprList.Clear()
if parseErr != nil {
return parseErr
}
resolver := ast.NewResolver(interpreter)
resolverErr := resolver.Resolve(exprList)
if resolverErr != nil {
return resolverErr
}
valueErr := interpreter.Interpret(exprList, true)
if valueErr != nil {
return valueErr
}
}
return nil
}
return fs.WalkDir(loxCodeFS, ".", dirFunc)
}
func run(sc *scanner.Scanner, interpreter *ast.Interpreter) error {
scanErr := sc.ScanTokens()
if scanErr != nil {
return scanErr
}
parser := ast.NewParser(sc.Tokens)
exprList, parseErr := parser.Parse()
defer exprList.Clear()
if parseErr != nil {
return parseErr
}
resolver := ast.NewResolver(interpreter)
resolverErr := resolver.Resolve(exprList)
if resolverErr != nil {
return resolverErr
}
valueErr := interpreter.Interpret(exprList, true)
if valueErr != nil {
return valueErr
}
return nil
}
func processFile(filePath string) error {
file, openFileError := os.Open(filePath)
if openFileError != nil {
return openFileError
}
program, readErr := io.ReadAll(file)
file.Close()
if readErr != nil {
return readErr
}
sc := scanner.NewScanner(string(program))
interpreter := ast.NewInterpreter()
runLoxCodeErr := runLoxCode(interpreter)
if runLoxCodeErr != nil {
return runLoxCodeErr
}
resultError := run(sc, interpreter)
if resultError != nil {
return resultError
}
return nil
}
func interactiveMode() int {
l, _ := readline.NewEx(&readline.Config{
Prompt: PROMPT,
InterruptPrompt: "^C",
})
defer l.Close()
interpreter := ast.NewInterpreter()
runLoxCodeErr := runLoxCode(interpreter)
if runLoxCodeErr != nil {
loxerror.PrintErrorObject(runLoxCodeErr)
return 1
}
if util.StdinFromTerminal() {
numSpacesIndent := 2
outer:
for {
var program strings.Builder
scopeLevel := 0
for {
if scopeLevel > 0 {
indent := strings.Repeat(" ", numSpacesIndent*scopeLevel)
l.SetPrompt(NEXT_LINE_PROMPT + indent)
} else {
l.SetPrompt(PROMPT)
}
userInput, readError := l.Readline()
if readError == readline.ErrInterrupt {
continue
} else if readError == io.EOF {
break outer
}
if len(userInput) == 0 {
if scopeLevel > 0 {
program.WriteByte('\n')
}
continue
}
userInput = strings.TrimSpace(userInput)
program.WriteString(userInput)
leftBraceCount, rightBraceCount := util.CountBraces(userInput)
scopeLevel += (leftBraceCount - rightBraceCount)
if scopeLevel <= 0 {
break
}
program.WriteByte('\n')
}
sc := scanner.NewScanner(program.String())
resultError := run(sc, interpreter)
if resultError != nil {
loxerror.PrintErrorObject(resultError)
}
}
} else {
program, readErr := io.ReadAll(os.Stdin)
if readErr != nil {
loxerror.PrintErrorObject(readErr)
return 1
}
sc := scanner.NewScanner(string(program))
resultError := run(sc, interpreter)
if resultError != nil {
loxerror.PrintErrorObject(resultError)
return 1
}
}
return 0
}
func main() {
var (
exprCLine = flag.String("c", "", "")
disableLoxCode = flag.Bool("disable-loxcode", false, "")
disableLoxCode2 = flag.Bool("dl", false, "")
helpFlag1 = flag.Bool("h", false, "")
helpFlag2 = flag.Bool("help", false, "")
)
flag.Usage = usageFunc(os.Stderr)
flag.Parse()
if *helpFlag1 || *helpFlag2 {
usageFunc(os.Stdout)()
os.Exit(0)
}
args := flag.Args()
util.DisableLoxCode = *disableLoxCode || *disableLoxCode2
exitCode := 0
if *exprCLine != "" {
sc := scanner.NewScanner(*exprCLine)
interpreter := ast.NewInterpreter()
runLoxCodeErr := runLoxCode(interpreter)
if runLoxCodeErr == nil {
resultError := run(sc, interpreter)
if resultError != nil {
loxerror.PrintErrorObject(resultError)
exitCode = 1
}
} else {
loxerror.PrintErrorObject(runLoxCodeErr)
exitCode = 1
}
} else if len(args) > 0 && args[0] != "-" {
possibleError := processFile(args[0])
if possibleError != nil {
loxerror.PrintErrorObject(possibleError)
exitCode = 1
}
} else {
util.InteractiveMode = true
exitCode = interactiveMode()
}
ast.CloseInputFuncReadline()
os.Exit(exitCode)
}