Skip to content

Commit 56a4636

Browse files
committed
2.9 REPL (read-parse-print-loop)
1 parent 02f2502 commit 56a4636

File tree

1 file changed

+38
-4
lines changed

1 file changed

+38
-4
lines changed

repl/repl.go

Lines changed: 38 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,12 +9,27 @@ import (
99
"io"
1010

1111
"github.com/cedrickchee/hou/lexer"
12-
"github.com/cedrickchee/hou/token"
12+
"github.com/cedrickchee/hou/parser"
1313
)
1414

1515
// PROMPT is the REPL prompt displayed for each input.
1616
const PROMPT = ">> "
1717

18+
// MONKEYFACE is the REPL's face if we run into any parser errors. You get to
19+
// see a monkey :D
20+
const MONKEYFACE = ` __,__
21+
.--. .-" "-. .--.
22+
/ .. \/ .-. .-. \/ .. \
23+
| | '| / Y \ |' | |
24+
| \ \ \ 0 | 0 / / / |
25+
\ '- ,\.-"""""""-./, -' /
26+
''-' /_ ^ ^ _\ '-''
27+
| \._ _./ |
28+
\ \ '~' / /
29+
'._ '-=-' _.'
30+
'-----'
31+
`
32+
1833
// Start starts the REPL in a continuous loop.
1934
func Start(in io.Reader, out io.Writer) {
2035
scanner := bufio.NewScanner(in)
@@ -28,10 +43,29 @@ func Start(in io.Reader, out io.Writer) {
2843

2944
line := scanner.Text()
3045

31-
// A REPL that tokenizes Monkey source code and prints the tokens.
46+
// A REPL that tokenizes and parses Monkey source code and prints
47+
// the AST.
3248
l := lexer.New(line)
33-
for tok := l.NextToken(); tok.Type != token.EOF; tok = l.NextToken() {
34-
fmt.Printf("%+v\n", tok)
49+
p := parser.New(l)
50+
51+
program := p.ParseProgram()
52+
if len(p.Errors()) != 0 {
53+
printParseErrors(out, p.Errors())
54+
continue
3555
}
56+
57+
// Print stringified version of the AST to stdout.
58+
io.WriteString(out, program.String())
59+
io.WriteString(out, "\n")
60+
}
61+
}
62+
63+
// Print parser errors to stdout.
64+
func printParseErrors(out io.Writer, errors []string) {
65+
io.WriteString(out, MONKEYFACE)
66+
io.WriteString(out, "Woops! We ran into some monkey business here!\n")
67+
io.WriteString(out, "parser errors:\n")
68+
for _, msg := range errors {
69+
io.WriteString(out, "\t"+msg+"\n")
3670
}
3771
}

0 commit comments

Comments
 (0)