Build Your Own Interpreter / Chapter 1 — Before We Build (lessons 1–5) / Lesson 1

Interpreters and Compilers

Time needed: about 12 min (estimate)

☆ Read later

You can try the opening of this lesson without an account.

What you'll build in this course

In this course you'll build one small programming language, Mame, all the way through in Python. You'll write the program that reads and runs Mame programs, which is called an interpreter. The program below will run as-is by the end of Chapter 4. It creates variables with let, functions with fn, and even uses a closure, a function that remembers a variable from outside it.

examples/goal.mame

# Make a function that returns a number one larger each time it's called let make_counter = fn() { let n = 0; return fn() { n = n + 1; return n; }; }; let next = make_counter(); next(); next(); print("third call: " + str(next())); let i = 1; while i <= 15 { if i % 15 == 0 { print("FizzBuzz"); } else if i % 3 == 0 { print("Fizz"); } else if i % 5 == 0 { print("Buzz"); } else { print(i); } i = i + 1; }

An interpreter works in three stages

An interpreter doesn't understand the source all at once. (1) Lexing groups characters into tokens, the smallest meaningful units. (2) Parsing reads a nested structure, a tree, out of the token sequence. (3) Evaluation walks the tree to get a value. Because each stage has one job, each one stays short and can be checked on its own.

From source to value

Source (a string) let total = price * 3 + 10; │ (1) Lexing (lexer) group characters into the smallest meaningful units ▼ Tokens let total = price * 3 + 10 ; │ (2) Parsing (parser) read the nested structure out of the sequence ▼ Tree (AST) let total │ + ╱ ╲ * 10 ╱ ╲ price 3 │ (3) Evaluation walk the tree to get a value ▼ Value total = 1150 (when price is 380)

Looking inside Python

Python goes through the same stages. You can see the result of (1) with the standard tokenize module and the result of (2) with ast. Run the code below. In the tree, Mult (multiplication) sits inside Add (addition). The deeper an operation is, the earlier it's computed, so the multiplication happens first.

editor.py

Tab indents. To leave the editor, press Esc, then Tab.

Create a free account to keep reading

With an account you can read the rest of this lesson, take the quiz, and read every free lesson in this course. Lessons you answer correctly are recorded as complete.

Report a problem with this lesson

Log in to send a report.

Keyboard shortcuts

Keys available in a lesson
KeyAction
[ or Alt + ←Go to the previous lesson
] or Alt + →Go to the next lesson
?Open this list
EscClose this list

The keys do not work while the cursor is in a code editor or an input field.