umx_compiler

UMX virtual machine "Monkey" interpreter / bytecode compiler
git clone git://bsandro.tech/umx_compiler
Log | Files | Refs | README | LICENSE

repl.go (1031B)


      1 package repl
      2 
      3 import (
      4 	"bufio"
      5 	"fmt"
      6 	"umx_compiler/eval"
      7 	"umx_compiler/lexer"
      8 	"umx_compiler/object"
      9 	"umx_compiler/parser"
     10 	"io"
     11 )
     12 
     13 const PROMPT = "$> "
     14 
     15 func Start(in io.Reader, out io.Writer) {
     16 	scanner := bufio.NewScanner(in)
     17 	ctx := object.NewContext()
     18 
     19 	for {
     20 		fmt.Fprintf(out, PROMPT)
     21 		scanned := scanner.Scan()
     22 		if !scanned {
     23 			return
     24 		}
     25 		line := scanner.Text()
     26 		l := lexer.New(line)
     27 		p := parser.New(l)
     28 		prg := p.ParseProgram()
     29 		if len(p.Errors()) != 0 {
     30 			printParserErrors(out, p.Errors())
     31 		}
     32 		evaluated := eval.Eval(prg, ctx)
     33 		if evaluated != nil {
     34 			io.WriteString(out, evaluated.Inspect())
     35 			io.WriteString(out, "\n")
     36 		}
     37 	}
     38 }
     39 
     40 func printParserErrors(out io.Writer, errors []string) {
     41 	for _, msg := range errors {
     42 		io.WriteString(out, "\t"+msg+"\n")
     43 	}
     44 }
     45 
     46 func Run(script string, out io.Writer) {
     47 	ctx := object.NewContext()
     48 	l := lexer.New(script)
     49 	p := parser.New(l)
     50 	prg := p.ParseProgram()
     51 	if len(p.Errors()) == 0 {
     52 		eval.Eval(prg, ctx)
     53 	} else {
     54 		printParserErrors(out, p.Errors())
     55 	}
     56 }