fibonacci
Some checks failed
Build / build (push) Failing after 2m11s
Test / build (push) Failing after 2m10s

This commit is contained in:
Chuck Smith
2024-03-14 20:11:29 -04:00
parent cc78fee3c8
commit 36f04713bd
2 changed files with 90 additions and 10 deletions

76
main.go
View File

@@ -1,19 +1,75 @@
package main
import (
"flag"
"fmt"
"monkey/repl"
"os"
user2 "os/user"
"time"
"monkey/compiler"
"monkey/evaluator"
"monkey/lexer"
"monkey/object"
"monkey/parser"
"monkey/vm"
)
func main() {
user, err := user2.Current()
var engine = flag.String("engine", "vm", "use 'vm' or 'eval'")
if err != nil {
panic(err)
var input = `
let fibonacci = fn(x) {
if (x == 0) {
0
} else {
if (x == 1) {
return 1;
} else {
fibonacci(x - 1) + fibonacci(x - 2);
}
}
};
fibonacci(35);
`
func main() {
flag.Parse()
var duration time.Duration
var result object.Object
l := lexer.New(input)
p := parser.New(l)
program := p.ParseProgram()
if *engine == "vm" {
comp := compiler.New()
err := comp.Compile(program)
if err != nil {
fmt.Printf("compiler error: %s", err)
return
}
machine := vm.New(comp.Bytecode())
start := time.Now()
err = machine.Run()
if err != nil {
fmt.Printf("vm error: %s", err)
return
}
duration = time.Since(start)
result = machine.LastPoppedStackElem()
} else {
env := object.NewEnvironment()
start := time.Now()
result = evaluator.Eval(program, env)
duration = time.Since(start)
}
fmt.Printf("Hello %s! This is the Monkey programmig language!\n", user.Username)
fmt.Printf("Feel free to type in commands\n")
repl.Start(os.Stdin, os.Stdout)
fmt.Printf(
"engine=%s, result=%s, duration=%s\n",
*engine,
result.Inspect(),
duration)
}