Interpreters are used to process instructions which the user enters. Typical examples of interpreters include BASIC and PHP.
Learning to construct interpreters is a valued programming skill because it allows the designer to directly define the grammar that the computer understands. For this reason, it is also frequently used (with other techniques) in the field of artificial intelligence.
Interpreters can be simple, only understanding rudimentary commands such as "print this" or "add that". They can also understand complex commands if they are designed properly. In a way, a significant way, teaching the computer how to interpret commands gives it intelligence.
To design an interpreter, it is suggested that a compiler program is used. Code for the compiler used will be specific to its native language, but an outline is provided below.
Before beginning, create an empty sequence or list for the the commands:
Step 1: Add Interpreter Commands
Some find it helpful to write out a list of commands that the new interpreter will be able to process. These are then written into the program. Each argument (object a) is an object that can be passed through to the procedure. Functions can be used instead of procedures to add a debugging logger if desired.
The intended use of the above procedure is to print whatever object is passed through the procedure. A likely command for the interpreter would follow the form [myPrintCommand “Hello World”]. After the procedure is written, the command is added to the database.
A routine_id is the integer identity of a procedure to be called. The last object sent is the number of parameters to send. The first string entered is what the user will type in to run the command.
Step 2: Parser Creation
A parser is used to process the entire string command sent to the interpreter. In this instance, it would change the command print “Hello World” to {“print”,“Hello World”}.
Step 3: Prompt Design
The prompt command is finally added. This procedure will first ask for a command, check to make sure it's in the right form, and proceed by calling the pre-written procedure.
All that is left is to call the prompt:
To assign values, a database can be created as follows:
The variables can be modified, for example, with an assign procedure:
and called with a retrieve command:
Now that the engine for the interpreter is built, new commands can be designed by repeating step 2. The new interpreter can be used as a stand-alone program or placed inside of other source code and called with the 'prompt_stuff()' command.
Most of the work done on interpreters is not in the command section, the typical aim is not to produce a vast array of commands (at first). Modifications to the parsing section creates ease of use and allows for user-defined procedures, but that's for another article.