@@ -9,12 +9,27 @@ import (
9
9
"io"
10
10
11
11
"github.com/cedrickchee/hou/lexer"
12
- "github.com/cedrickchee/hou/token "
12
+ "github.com/cedrickchee/hou/parser "
13
13
)
14
14
15
15
// PROMPT is the REPL prompt displayed for each input.
16
16
const PROMPT = ">> "
17
17
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
+
18
33
// Start starts the REPL in a continuous loop.
19
34
func Start (in io.Reader , out io.Writer ) {
20
35
scanner := bufio .NewScanner (in )
@@ -28,10 +43,29 @@ func Start(in io.Reader, out io.Writer) {
28
43
29
44
line := scanner .Text ()
30
45
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.
32
48
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
35
55
}
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 " )
36
70
}
37
71
}
0 commit comments