crafting-interpreters/golox/internal/runner/runner.go

48 lines
942 B
Go
Raw Normal View History

package runner
import (
"bufio"
2023-05-06 22:53:19 +00:00
"errors"
"fmt"
"os"
2023-05-06 23:13:13 +00:00
lerrors "github.com/AYM1607/crafting-interpreters/golox/internal/errors"
)
2023-05-06 22:53:19 +00:00
var ErrInvalidScriptFile = errors.New("could not read script file")
2023-05-06 23:13:13 +00:00
var ErrScriptNotRunnable = errors.New("could not run script")
2023-05-06 22:53:19 +00:00
func RunPrompt() {
s := bufio.NewScanner(os.Stdin)
fmt.Print("> ")
for s.Scan() {
line := s.Text()
Run(line)
2023-05-06 23:13:13 +00:00
// TODO: Understand the implications of this. The book implies that it's
// to allow the users to keep issuing commands even if they make a mistake.
lerrors.HadError = false
fmt.Print("> ")
}
}
func RunFile(path string) error {
fBytes, err := os.ReadFile(path)
if err != nil {
2023-05-06 22:53:19 +00:00
return errors.Join(ErrInvalidScriptFile, err)
}
Run(string(fBytes))
2023-05-06 23:13:13 +00:00
if lerrors.HadError {
return ErrScriptNotRunnable
}
return nil
}
func Run(source string) {
s := NewScanner(source)
tokens := s.ScanTokens()
for _, t := range tokens {
fmt.Println(t)
}
}