Skip to content

Commit

Permalink
feat: adds repl to interpreter
Browse files Browse the repository at this point in the history
  • Loading branch information
Tezzish committed Sep 26, 2024
1 parent c61627e commit 85f66ee
Show file tree
Hide file tree
Showing 2 changed files with 77 additions and 0 deletions.
19 changes: 19 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package main

import (
"Go-interpreter/repl"
"fmt"
"os"
"os/user"
)

func main() {
user, err := user.Current()
if err != nil {
panic(err)
}
fmt.Printf("Hello %s! This is the Monkey programming language!\n",
user.Username)
fmt.Printf("Feel free to type in commands\n")
repl.Start(os.Stdin, os.Stdout)
}
58 changes: 58 additions & 0 deletions repl/repl.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
package repl

import (
"Go-interpreter/lexer"
"Go-interpreter/parser"
"bufio"
"fmt"
"io"
)

const PROMPT = ">> "

func Start(in io.Reader, out io.Writer) {
scanner := bufio.NewScanner(in)

for {
fmt.Printf(PROMPT)
scanned := scanner.Scan()
if !scanned {
return
}

line := scanner.Text()
l := lexer.New(line)
p := parser.New(l)

program := p.ParseProgram()
if len(p.Errors()) != 0 {
printParserErrors(out, p.Errors())
continue
}

io.WriteString(out, program.String())
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")
}
}

0 comments on commit 85f66ee

Please sign in to comment.