Skip to content

Latest commit

 

History

History
69 lines (49 loc) · 1.35 KB

File metadata and controls

69 lines (49 loc) · 1.35 KB

Monkey Interpreter

A Rust implementation of the Monkey programming language from Thorsten Ball's Writing an Interpreter in Go.

Usage

cargo run

Starts the REPL.

cargo test

Runs the full test suite.

Language

Types: integers, booleans, strings, arrays, hashes, functions, null

Syntax

let x = 5;
let add = fn(x, y) { x + y };
let result = add(5, 10);

if (x > 0) { x } else { -x }

let a = [1, 2, 3];
let h = {"key": 1, true: 2, 3: 3};

a[0];
h["key"];

Closures

let newAdder = fn(x) { fn(y) { x + y } };
let addTwo = newAdder(2);
addTwo(3); // 5

Builtins

Function Description
len(x) length of string or array
first(arr) first element
last(arr) last element
rest(arr) new array without first element
push(arr, val) new array with val appended
puts(x, ...) print to stdout
map(arr, fn) apply fn to each element
reduce(arr, initial, fn) fold arr into a single value

Implementation

Tree-walk interpreter built from scratch:

  • Lexer — byte-oriented, u8/as_bytes() for O(1) indexing
  • Parser — Pratt (top-down operator precedence)
  • AST — Rust enums
  • Evaluator — recursive tree walk with Rc<RefCell<Environment>> scope chains
  • ObjectsHashMap<HashKey, Object> for hashes; HashKey derives Hash