glox/glox.go

87 lines
1.2 KiB
Go
Raw Normal View History

2024-09-29 18:45:11 +03:00
package main
import (
"bufio"
2024-10-07 21:47:55 +03:00
"fmt"
2024-09-29 18:45:11 +03:00
"log"
"os"
)
2024-10-05 18:58:49 +03:00
type Glox struct {
Interpreter *Interpreter
}
2024-09-29 18:45:11 +03:00
func main() {
2024-10-05 18:58:49 +03:00
glox := &Glox{newInterpreter()}
2024-10-03 13:07:17 +03:00
switch len(os.Args) {
case 1:
2024-10-05 18:58:49 +03:00
glox.runPrompt()
2024-10-03 13:07:17 +03:00
case 2:
2024-10-05 18:58:49 +03:00
glox.runFile(os.Args[1])
2024-10-03 13:07:17 +03:00
default:
println("Usage: glox [file]")
os.Exit(1)
}
2024-09-30 21:46:31 +03:00
}
2024-10-05 18:58:49 +03:00
func (gl *Glox) runPrompt() {
2024-09-30 21:46:31 +03:00
scanner := bufio.NewScanner(os.Stdin)
scanner.Split(bufio.ScanLines)
2024-10-14 22:53:26 +03:00
doRun := func(line []byte) {
defer func() {
if err := recover(); err != nil {
log.Println(err)
}
}()
gl.run(line)
}
2024-09-30 21:46:31 +03:00
for {
print("> ")
2024-10-05 18:58:49 +03:00
if !scanner.Scan() {
2024-09-30 21:46:31 +03:00
break
}
2024-10-14 22:53:26 +03:00
doRun(scanner.Bytes())
2024-09-30 21:46:31 +03:00
}
}
2024-10-05 18:58:49 +03:00
func (gl *Glox) runFile(path string) {
2024-09-30 21:46:31 +03:00
file, err := os.ReadFile(path)
2024-10-05 18:58:49 +03:00
if err != nil {
log.Fatal(err)
2024-10-04 15:24:01 +03:00
}
2024-09-29 18:45:11 +03:00
2024-10-05 23:27:00 +03:00
gl.run(file)
2024-10-05 18:58:49 +03:00
}
2024-10-04 15:24:01 +03:00
2024-10-05 23:27:00 +03:00
func (gl *Glox) run(source []byte) {
2024-10-14 22:53:26 +03:00
tokens, err := newScanner(source).scan()
2024-10-04 15:24:01 +03:00
2024-10-14 22:53:26 +03:00
if err != nil {
panic(err)
}
stmts, parseErrs := newParser(tokens).parse()
if parseErrs != nil {
panic(parseErrs)
}
2024-10-05 18:58:49 +03:00
2024-10-07 21:47:55 +03:00
fmt.Println(AstStringer{stmts: stmts})
2024-10-05 18:58:49 +03:00
2024-10-14 22:53:26 +03:00
resolveErrs := newResolver(gl.Interpreter).resolveStmts(stmts...)
if resolveErrs != nil {
panic(resolveErrs)
}
interpreterErrs := gl.Interpreter.interpret(stmts)
if interpreterErrs != nil {
panic(interpreterErrs)
}
2024-09-29 18:45:11 +03:00
}