Monkey Lang
Tiny interpreted programming language
Monkey Lang
Monkey is a programming language created by Thorston Ball
I have implemented the programming language in python and go
Features
It features integers, booleans, strings, arrays, hashes, and first-class functions. This dual implementation allowed me to explore how different paradigms handle memory, recursion, and type systems during the evaluation process.
Structure
Lexer (The Scanner)
The Lexer's job is to take raw source code (a string of characters) and turn it into a stream of Tokens. How it works: It traverses the source code character by character. When it encounters a character like +, it recognizes it as a PLUS token. When it sees letters, it groups them into IDENT (identifiers) or KEYWORDS (like let or fn). The Python vs. Go Experience: In Go, I utilized a struct with a byte pointer. In Python, I leaned on its powerful string slicing, though I had to be more mindful of performance overhead during the character-walking process.
Parser (The Architect)
The Parser takes the stream of Tokens and organizes them into a hierarchical structure. Monkey uses a Top-Down Operator Precedence (Pratt Parser).
Key Logic: It handles "precedence"—ensuring that in the expression 5 + 2 * 10, the parser knows that the multiplication happens before the addition.
Recursive Descent: I implemented functions that call themselves to parse nested expressions, such as functions inside functions or complex mathematical groupings.
AST (Abstract Syntax Tree)
The AST is the final representation of the source code before evaluation. It is a tree-like structure where every node represents a part of the syntax (e.g., an IfExpression node or an IntegerLiteral node).
Interfaces/Classes: * In Go, I used interfaces (Node, Statement, Expression) to ensure type safety across the tree.
In Python, I used a class hierarchy, which allowed for more dynamic inspection of the tree during debugging.
Purpose: By the time the code reaches the AST, all the "syntactic sugar" and raw text are gone. We are left with a pure logical map of what the program is intended to do.