Making a Python interpreter in 1024 bytes

To feel human, I write codeby handon the weekends.

My latest challenge? Make a Python interpreter in5121024 bytes of good ole C code. Oh, and no macro shenanigans or library tomfoolery.

I probably can’t fitallof the Python language into an interpreter that is only 1024 bytes of code. So what can I fit that willlooklike Python?

This fizzbuzz program looks distinctly Python. It has thedef, the colons, the indentations, and no parentheses forifstatements. Looks like Python to me! Of course, I’ll also have to add some additional limitations beyond just a subset of the syntax.

I’ve written many recursive descent parsers, so how different can this be? A subset of Python should be similar to the other languages I’ve implemented.

I started with the most basic code I could think of:1 + 2

Then I made it more complex:x = 1 + 2 * 3

And then I even added statements:if x > y: z = 3

Great, I made a calculator… Not what I meant with this challenge! I was already over the limit too. That is when I zoomed out and made a list of elements thatlookPythony, while also realizing that my code golf skills were not up to snuff to make it fit in 512 bytes.

Maybe I can do it in 1024 bytes? First, make it work, and then make it small.

The actualCPythonimplementation tokenizes the Python source, parses it into an abstract syntax tree, performs some analysis and optimizations, emits bytecode, and then interprets the bytecode.

The state is held in a handful of global variables. It uses a fixed-length array (999 for now) that will hold the raw Python code. The variables and function names all fit into a single array.