@ 6025dda55b1abdf77b71aa1d3aa49f2f5b7180b5 | history
package main
import (
"errors"
"fmt"
"io"
"strings"
"nmyk.io/government/eval"
"nmyk.io/government/sexpr"
)
const (
prompt = "gov> "
continuation = "...> "
)
// errInterrupt is Ctrl-C at a prompt: throw away the form being typed.
var errInterrupt = errors.New("interrupt")
// A lineSource hands the REPL one line of input at a time. At the end of
// input it returns io.EOF, and errInterrupt when the user asks to discard
// the current entry.
type lineSource interface {
readLine(prompt string) (string, error)
Close() error
}
// repl reads forms until end of input. A form may span several lines:
// while the input so far is an unfinished form, it keeps reading, with the
// continuation prompt. An error is reported and the session carries on;
// definitions made before it are kept.
func repl(top *eval.TopLevel, src lineSource, out io.Writer) {
var entry strings.Builder
for {
p := prompt
if entry.Len() > 0 {
p = continuation
}
line, err := src.readLine(p)
if errors.Is(err, errInterrupt) {
entry.Reset()
continue
}
if err != nil {
if entry.Len() > 0 {
if _, err := sexpr.ReadAll(entry.String()); err != nil {
fmt.Fprintf(out, "syntax error: %v\n", err)
}
}
return
}
entry.WriteString(line)
entry.WriteByte('\n')
forms, err := sexpr.ReadAll(entry.String())
if se, ok := err.(*sexpr.SyntaxError); ok && se.Incomplete {
continue
}
entry.Reset()
if err != nil {
fmt.Fprintf(out, "syntax error: %v\n", err)
continue
}
for _, form := range forms {
v, err := top.Eval(form)
if err != nil {
fmt.Fprintln(out, describe(err))
break
}
if !isDefine(form) {
fmt.Fprintln(out, sexpr.Print(v))
}
}
}
}
// describe adds the subexpression that failed to an evaluation error.
func describe(err error) string {
e, ok := err.(*eval.Error)
if !ok || e.Expr == nil {
return err.Error()
}
return fmt.Sprintf("%v\n in %s", err, sexpr.Print(e.Expr))
}