A simple Basic interpretor
published:
updated:
An old post, but still very useful: Bob Nystrom built a simple interpretor based on a single Java file here.
The language Jasic is a dialect of BASIC.
The implementation provides a simpilified view of how a real implementation of a BASIC interpretor would work. He has a few hacks which are cearly called out, as well as some shortcuts to keep the source more concise. There are also some assumptions that keep the code simpler (such as the constraint that each line contains a statement). This is not meant to be a full production-quuality implementation. But it does cover the basics...pun intended.
He also provides some sample apps that you can play with. Neat!
Overall structure
The source is well-documented so there is no need for any additional documentation.
At a very high-level, we are just running a basic CLI where we expected a single .jas file.
public static void main(String[] args) {
// Just show the usage and quit if a script wasn't provided.
if (args.length != 1) {
System.out.println("Usage: jasic <script>");
System.out.println("Where <script> is a relative path to a .jas script to run.");
return;
}
// Read the file.
String contents = readFile(args[0]);
// Run it.
Jasic jasic = new Jasic();
jasic.interpret(contents);
}The Interpretation loop
The implementation is listed roughly in the order of operations: Tokenizing, Parsing, Interpretion in a loop.
public void interpret(String source) {
// Tokenize.
List<Token> tokens = tokenize(source);
// Parse.
Parser parser = new Parser(tokens);
List<Statement> statements = parser.parse(labels);
// Interpret until we're done.
currentStatement = 0;
while (currentStatement < statements.size()) {
int thisStatement = currentStatement;
currentStatement++;
statements.get(thisStatement).execute();
}
}
These are types of token that we expect:
/**
* This defines the different kinds of tokens or meaningful chunks of code
* that the parser knows how to consume. These let us distinguish, for
* example, between a string "foo" and a variable named "foo".
*
* HACK: A typical tokenizer would actually have unique token types for
* each keyword (print, goto, etc.) so that the parser doesn't have to look
* at the names, but Jasic is a little more crude.
*/
private enum TokenType {
WORD, NUMBER, STRING, LABEL, LINE,
EQUALS, OPERATOR, LEFT_PAREN, RIGHT_PAREN, EOF
}
The parser takes in a sequence of tokens and generates an abstract syntax tree. This is the nested data structure that represents the series of statements, and the expressions (which can nest arbitrarily deeply) that they evaluate.
The tokenization uses a state machine while it scans the source character by character, identifies the tokens and adds them to a running list of all tokens that represents the source.
The parser walks the token-list and builds a list of statement objects.
Within the Abstract Syntax Tree (AST), we define the interfaces: Statement and Expression. Statement defines a contract called execute(). For example, the PrintStatement would implement:
public void execute() {
System.out.println(expression.evaluate().toString());
}
It gets an expression in the constructor.
Here is what an if ... then ... statement looks like:
/**
* An if then statement jumps execution to another place in the program, but
* only if an expression evaluates to something other than 0.
*/
public class IfThenStatement implements Statement {
public IfThenStatement(Expression condition, String label) {
this.condition = condition;
this.label = label;
}
public void execute() {
if (labels.containsKey(label)) {
double value = condition.evaluate().toNumber();
if (value != 0) {
currentStatement = labels.get(label).intValue();
}
}
}
private final Expression condition;
private final String label;
}
Expression defines one called evaluate().
There is a whole book about this which I should work through here.
That's for another set of posts.