glox/glox.go

73 lines
1 KiB
Go
Raw Normal View History

2024-09-29 18:45:11 +03:00
package main
import (
"bufio"
"log"
"os"
)
func main() {
2024-09-30 21:46:31 +03:00
expr := &Binary{
2024-10-03 13:07:17 +03:00
&Unary{Token{MINUS, "-", nil, 1}, &Literal{123}},
Token{STAR, "*", nil, 1},
&Grouping{&Grouping{&Binary{
&Unary{Token{MINUS, "-", nil, 1}, &Literal{123}},
Token{STAR, "*", nil, 1},
&Grouping{&Grouping{&Literal{45.67}}}}}},
2024-09-30 21:46:31 +03:00
}
2024-10-03 13:07:17 +03:00
println(AstStringer{}.String(expr))
2024-09-30 21:46:31 +03:00
2024-10-03 13:07:17 +03:00
switch len(os.Args) {
case 1:
runPrompt()
case 2:
runFile(os.Args[1])
default:
println("Usage: glox [file]")
os.Exit(1)
}
2024-09-30 21:46:31 +03:00
}
func runPrompt() {
scanner := bufio.NewScanner(os.Stdin)
scanner.Split(bufio.ScanLines)
for {
print("> ")
scanner.Scan()
line := scanner.Text()
if len(line) == 0 {
break
}
run([]byte(scanner.Text()))
hadError = false
}
}
func runFile(path string) {
file, err := os.ReadFile(path)
panic(err)
run(file)
if hadError {
2024-09-29 18:45:11 +03:00
os.Exit(1)
}
}
2024-09-30 21:46:31 +03:00
func run(source []byte) {
tokens := newScanner(source).scan()
for _, token := range tokens {
println(token.String())
}
}
2024-09-29 18:45:11 +03:00
func panic(err error) {
if err != nil {
log.Fatal(err)
}
}