glox/glox.go

75 lines
1 KiB
Go
Raw Normal View History

2024-09-29 18:45:11 +03:00
package main
import (
"bufio"
"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)
for {
print("> ")
2024-10-05 18:58:49 +03:00
if !scanner.Scan() {
2024-09-30 21:46:31 +03:00
break
}
2024-10-05 18:58:49 +03:00
gl.run(scanner.Bytes(), true)
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 18:58:49 +03:00
runErrors := gl.run(file, false)
2024-10-04 15:24:01 +03:00
2024-10-05 18:58:49 +03:00
if len(runErrors) != 0 {
for _, e := range runErrors {
log.Print(e)
}
2024-10-03 22:12:40 +03:00
2024-10-05 18:58:49 +03:00
os.Exit(1)
2024-10-04 15:24:01 +03:00
}
2024-10-05 18:58:49 +03:00
}
2024-10-04 15:24:01 +03:00
2024-10-05 18:58:49 +03:00
func (gl *Glox) run(source []byte, interactive bool) []error {
tokens, err := newScanner(source).scan()
2024-10-04 15:24:01 +03:00
2024-10-05 18:58:49 +03:00
if err != nil {
return []error{err}
2024-10-04 15:24:01 +03:00
}
2024-10-05 18:58:49 +03:00
stmts, parseErrs := newParser(tokens).parse()
2024-09-30 21:46:31 +03:00
2024-10-05 18:58:49 +03:00
if len(parseErrs) != 0 && !interactive {
return parseErrs
2024-09-29 18:45:11 +03:00
}
2024-10-05 18:58:49 +03:00
println(AstStringer{}.String(stmts))
return gl.Interpreter.interpret(stmts)
2024-09-29 18:45:11 +03:00
}