Build Your Own Interpreter / Chapter 1 — Before We Build (lessons 1–5) / Lesson 1
Interpreters and Compilers
Time needed: about 12 min (estimate)
Reading settings
These settings are remembered on this device only.
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
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
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.
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.