glox/glox.go

59 lines
810 B
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)
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 23:27:00 +03:00
gl.run(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) {
tokens, _ := newScanner(source).scan()
2024-10-04 15:24:01 +03:00
2024-10-05 23:27:00 +03:00
stmts, _ := newParser(tokens).parse()
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-05 23:27:00 +03:00
gl.Interpreter.interpret(stmts)
2024-09-29 18:45:11 +03:00
}