glox/glox.go

85 lines
1,023 B
Go
Raw Normal View History

2024-09-29 18:45:11 +03:00
package main
import (
"bufio"
2024-10-04 15:24:01 +03:00
"fmt"
2024-09-29 18:45:11 +03:00
"log"
"os"
)
func main() {
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
2024-10-04 15:24:01 +03:00
hadRuntimeError = false
2024-09-30 21:46:31 +03:00
}
}
func runFile(path string) {
file, err := os.ReadFile(path)
2024-10-03 22:12:40 +03:00
try(err)
2024-09-30 21:46:31 +03:00
run(file)
2024-10-04 15:24:01 +03:00
switch {
case hadError:
os.Exit(65)
case hadRuntimeError:
os.Exit(70)
default:
os.Exit(0)
}
2024-09-29 18:45:11 +03:00
}
2024-09-30 21:46:31 +03:00
func run(source []byte) {
tokens := newScanner(source).scan()
2024-10-04 15:24:01 +03:00
if hadError {
return
}
2024-10-03 22:12:40 +03:00
ast := newParser(tokens).parse()
2024-10-04 15:24:01 +03:00
if hadError {
return
}
2024-10-03 22:12:40 +03:00
println(AstStringer{}.String(ast))
2024-10-04 15:24:01 +03:00
res := newInterpreter().evaluate(ast)
if hadRuntimeError {
return
}
fmt.Printf("%v\n", res)
2024-09-30 21:46:31 +03:00
}
2024-10-03 22:12:40 +03:00
func try(err error) {
2024-09-29 18:45:11 +03:00
if err != nil {
log.Fatal(err)
}
}