2025-01-13 19:51:49 -08:00
|
|
|
package repl
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"bufio"
|
|
|
|
|
"fmt"
|
|
|
|
|
"io"
|
|
|
|
|
|
2025-01-13 19:56:56 -08:00
|
|
|
"code.jmug.me/jmug/compiler-in-go/pkg/evaluator"
|
|
|
|
|
"code.jmug.me/jmug/compiler-in-go/pkg/lexer"
|
|
|
|
|
"code.jmug.me/jmug/compiler-in-go/pkg/object"
|
|
|
|
|
"code.jmug.me/jmug/compiler-in-go/pkg/parser"
|
2025-01-13 19:51:49 -08:00
|
|
|
)
|
|
|
|
|
|
|
|
|
|
const PROMPT = ">> "
|
|
|
|
|
|
|
|
|
|
func Start(in io.Reader, out io.Writer) {
|
|
|
|
|
scanner := bufio.NewScanner(in)
|
|
|
|
|
env := object.NewEnvironment()
|
|
|
|
|
for {
|
|
|
|
|
fmt.Fprint(out, PROMPT)
|
|
|
|
|
if !scanner.Scan() {
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
l := lexer.New(scanner.Text())
|
|
|
|
|
p := parser.New(l)
|
|
|
|
|
program := p.ParseProgram()
|
|
|
|
|
if len(p.Errors()) != 0 {
|
|
|
|
|
printParserErrors(out, p.Errors())
|
|
|
|
|
continue
|
|
|
|
|
}
|
|
|
|
|
res := evaluator.Eval(program, env)
|
|
|
|
|
if res != nil {
|
|
|
|
|
io.WriteString(out, res.Inspect())
|
|
|
|
|
io.WriteString(out, "\n")
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const MONKEY_FACE = ` __,__
|
|
|
|
|
.--. .-" "-. .--.
|
|
|
|
|
/ .. \/ .-. .-. \/ .. \
|
|
|
|
|
| | '| / Y \ |' | |
|
|
|
|
|
| \ \ \ 0 | 0 / / / |
|
|
|
|
|
\ '- ,\.-"""""""-./, -' /
|
|
|
|
|
''-' /_ ^ ^ _\ '-''
|
|
|
|
|
| \._ _./ |
|
|
|
|
|
\ \ '~' / /
|
|
|
|
|
'._ '-=-' _.'
|
|
|
|
|
'-----'
|
|
|
|
|
`
|
|
|
|
|
|
|
|
|
|
func printParserErrors(out io.Writer, errors []string) {
|
|
|
|
|
io.WriteString(out, MONKEY_FACE)
|
|
|
|
|
io.WriteString(out, "Woops! We ran into some monkey business here!\n")
|
|
|
|
|
io.WriteString(out, " parser errors:\n")
|
|
|
|
|
for _, msg := range errors {
|
|
|
|
|
io.WriteString(out, "\t"+msg+"\n")
|
|
|
|
|
}
|
|
|
|
|
}
|