How To Write An Interpreter

Table of contents:

How To Write An Interpreter
How To Write An Interpreter

Video: How To Write An Interpreter

Video: How To Write An Interpreter
Video: So you want to write an interpreter? 2024, July
Anonim

To create an interpreter, you have to write a source code parser, a bytecode execution loop, and a huge amount of standard library code. It's not always fun and easy if you don't use the tools that the compiler and parser will generate for you. With them, writing a language interpreter for a knowledgeable person will be easier than ever. Let's look at an example of writing an interpreter with JIT in PyPy.

How to write an interpreter
How to write an interpreter

Instructions

Step 1

Choose a language for writing. In this case, it's brainfuck. It is very simple and consists of a tape of integers, which are initialized to zero, and 1 pointer to the current cell in the tape. There are only eight commands in the language: ">" - move the pointer to the next cell,"

Step 2

Write an interpreter in plain Python. The instruction counter will store pointers to the current instruction. The first expression will retrieve the statement, after which several statements determine how to execute it. Omit the implementation of the "[" and "]" operators, since they must change the command counter to the position of the same parenthesis.

Step 3

Implement a Tape class that stores a pointer to the current number and a tape of integers. The tape will grow as needed. Parse the source code ahead of time so that multiple comments are not read one byte at a time. Create a parenthesis dictionary as well so you can find matching parentheses in it if needed.

Step 4

Execute def parse (program). This function only returns strings from commands and the parenthesis dictionary.

Step 5

Put everything together and you have a working brainfuck interpreter. Start the Python interpreter and make sure it works. This is just a single instance of writing an interpreter using the simplest language. If you wish, you can write in almost any language, having familiarized yourself with its properties and purpose.

Recommended: