This commit is contained in:
Chuck Smith
2024-03-16 20:02:57 -04:00
parent 83ad72a7fc
commit d454572870
3 changed files with 46 additions and 3 deletions

32
main.go
View File

@@ -3,15 +3,17 @@ package main
import (
"flag"
"fmt"
"io/ioutil"
"io"
"log"
"monkey/compiler"
"monkey/lexer"
"monkey/object"
"monkey/parser"
"monkey/repl"
"os"
"os/user"
"path"
"strings"
)
var (
@@ -37,6 +39,22 @@ func init() {
flag.StringVar(&engine, "e", "vm", "engine to use (eval or vm)")
}
// Indent indents a block of text with an indent string
func Indent(text, indent string) string {
if text[len(text)-1:] == "\n" {
result := ""
for _, j := range strings.Split(text[:len(text)-1], "\n") {
result += indent + j + "\n"
}
return result
}
result := ""
for _, j := range strings.Split(strings.TrimRight(text, "\n"), "\n") {
result += indent + j + "\n"
}
return result[:len(result)-1]
}
func main() {
flag.Parse()
@@ -59,7 +77,7 @@ func main() {
f, err := os.Open(args[0])
defer f.Close()
b, err := ioutil.ReadAll(f)
b, err := io.ReadAll(f)
if err != nil {
log.Fatal(err)
}
@@ -79,7 +97,15 @@ func main() {
}
code := c.Bytecode()
fmt.Printf("%s\n", code.Instructions)
fmt.Printf("Main:\n%s\n", code.Instructions)
fmt.Print("Constants:\n")
for i, constant := range code.Constants {
fmt.Printf("%04d %s\n", i, constant.Inspect())
if fn, ok := constant.(*object.CompiledFunction); ok {
fmt.Printf("%s\n", Indent(fn.Instructions.String(), " "))
}
}
} else {
opts := &repl.Options{
Debug: debug,