Skip to content

Dentrax/Monkey

Folders and files

NameName
Last commit message
Last commit date

Latest commit

d854799 · Sep 12, 2020

History

69 Commits
Sep 12, 2020
Jun 20, 2020
Jun 20, 2020
Sep 12, 2020
Jun 20, 2020
Sep 12, 2020

Repository files navigation

Monkey

Build

Yet another Monkey interpreter & compiler implementation in Rust, based on Thorsten Ball's Writing An Interpreter In Go and Writing A Compiler In Go books.

Features

  • AST
  • Tokenizer
  • Parser
  • Lexer
  • Evaluator
  • Compiler
  • SymbolTable
  • VirtualMachine
  • Builtin Functions
  • Functions & Closures
  • Read–Eval–Print Loop

Usage

1. Install rustup

2. Test

$ cargo test --all

3. Run

$ cargo run --bin monkey
Monkey Compiler v0.2.0
>>> "Hello, " + "World!"
Hello, World!
>>>

Examples

Functions

[1, 2 * 2, 3 + 3]

Function Call

let identity = fn(x) { x; }; identity(7); //7
let add = fn(a, b) { a + b }; 
let sub = fn(a, b) { a - b }; 
let applyFunc = fn(a, b, func) { 
    func(a, b) 
}; 
applyFunc(10, 2, sub); //8

If

if (x < y) { z } else { w }

Nested If

if (2 > 1) { if (3 > 1) { return 7; } return 0; }

HashMap

{"one": 0 + 1, "two": 10 - 8, "ten": 50 / 5}

Arrays

let arr = [1, 2 * 2, 3 + 3] //arr[1 + 1] => returns 6

Operator Precedence

3 + 4 * 5 == 3 * 1 + 4 * 5 //((3 + (4 * 5)) == ((3 * 1) + (4 * 5)))

Error Handlers

if (10 > 1) { if (10 > 1) { return true + false; } return 1; } //unknown operator: BOOLEAN + BOOLEAN
let newAdder = fn(x) { fn(y) { x + y } }; let addTwo = newAdder(2); x //identifier not found: x

Complete Example

Builtin

let map = fn(arr, f) {
	let iter = fn(arr, accumulated) {
		if (len(arr) == 0) {
			accumulated
		} else {
			iter(rest(arr), push(accumulated, f(first(arr))));
		}
	};
	iter(arr, []);
};
let a = [1, 2, 3, 4];
let double = fn(x) { x * 2 };
map(a, double);

HashMap

let people = [{"name": "Alice", "age": 24}, {"name": "Anna", "age": 28}];
let getAge = fn(person) { person["name"]; };
return getAge(people[0]) + getAge(people[1]);

Benchmark

$ cargo run --release --bin benchmark -- --vm
$ cargo run --release --bin benchmark -- --eval

TODO

  • Impl Compiler
  • Impl VM
  • Add Pipeline with Stages: fmt, check, clippy, test, build
  • Optimize overall performance
  • Fix clippy warnings

License

MIT License (LICENSE).