Creating an interpreter for a new programming language is an exciting endeavor! Below, I'll guide you through building a simple interpreter using JavaScript. This interpreter will support basic features such as variable declarations, arithmetic operations, and printing output.
Overview
-
Language Design: We'll define a simple language called CalcScript with the following features:
- Variables: Declaration and assignment using
let.
- Arithmetic Operations: Addition, subtraction, multiplication, and division.
- Print Statement: Output values to the console using
print.
-
Interpreter Components:
- Lexer: Tokenizes the input source code.
- Parser: Builds an Abstract Syntax Tree (AST) from tokens.
- Interpreter: Traverses the AST and executes the code.
Step-by-Step Implementation
Below is the complete JavaScript code for the CalcScript interpreter. You can run this in a Node.js environment.
// CalcScript Interpreter in JavaScript
// 1. Lexer: Tokenizes the input source code
class Lexer {
constructor(input) {
this.input = input;
this.position = 0;
this.currentChar = this.input[this.position];
}
// Advance to the next character
advance() {
this.position += 1;
if (this.position < this.input.length) {
this.currentChar = this.input[this.position];
} else {
this.currentChar = null;
}
}
// Skip whitespace characters
skipWhitespace() {
while (this.currentChar && /\s/.test(this.currentChar)) {
this.advance();
}
}
// Extract multi-digit numbers
number() {
let result = '';
while (this.currentChar && /[0-9]/.test(this.currentChar)) {
result += this.currentChar;
this.advance();
}
return { type: 'NUMBER', value: Number(result) };
}
// Extract identifiers (variables and keywords)
identifier() {
let result = '';
while (this.currentChar && /[a-zA-Z_]/.test(this.currentChar)) {
result += this.currentChar;
this.advance();
}
const keywords = ['let', 'print'];
if (keywords.includes(result)) {
return { type: result.toUpperCase(), value: result };
}
return { type: 'IDENTIFIER', value: result };
}
// Tokenize the input
getTokens() {
const tokens = [];
while (this.currentChar !== null) {
if (/\s/.test(this.currentChar)) {
this.skipWhitespace();
continue;
}
if (/[0-9]/.test(this.currentChar)) {
tokens.push(this.number());
continue;
}
if (/[a-zA-Z_]/.test(this.currentChar)) {
tokens.push(this.identifier());
continue;
}
// Handle single-character tokens
switch (this.currentChar) {
case '+':
tokens.push({ type: 'PLUS', value: '+' });
break;
case '-':
tokens.push({ type: 'MINUS', value: '-' });
break;
case '*':
tokens.push({ type: 'MUL', value: '*' });
break;
case '/':
tokens.push({ type: 'DIV', value: '/' });
break;
case '=':
tokens.push({ type: 'EQUAL', value: '=' });
break;
case ';':
tokens.push({ type: 'SEMICOLON', value: ';' });
break;
case '(':
tokens.push({ type: 'LPAREN', value: '(' });
break;
case ')':
tokens.push({ type: 'RPAREN', value: ')' });
break;
default:
throw new SyntaxError(`Unknown character: ${this.currentChar}`);
}
this.advance();
}
tokens.push({ type: 'EOF', value: null });
return tokens;
}
}
// 2. Parser: Builds an Abstract Syntax Tree (AST) from tokens
class Parser {
constructor(tokens) {
this.tokens = tokens;
this.position = 0;
this.currentToken = this.tokens[this.position];
}
// Advance to the next token
eat(type) {
if (this.currentToken.type === type) {
this.position += 1;
this.currentToken = this.tokens[this.position];
} else {
throw new SyntaxError(`Expected token type ${type} but got ${this.currentToken.type}`);
}
}
// Grammar rules:
// program : statement_list
program() {
const statements = [];
while (this.currentToken.type !== 'EOF') {
statements.push(this.statement());
}
return { type: 'Program', body: statements };
}
// statement : variable_declaration | print_statement
statement() {
if (this.currentToken.type === 'LET') {
return this.variableDeclaration();
} else if (this.currentToken.type === 'PRINT') {
return this.printStatement();
} else {
throw new SyntaxError(`Unknown statement type: ${this.currentToken.type}`);
}
}
// variable_declaration : 'let' IDENTIFIER '=' expression ';'
variableDeclaration() {
this.eat('LET');
const varName = this.currentToken.value;
this.eat('IDENTIFIER');
this.eat('EQUAL');
const expr = this.expression();
this.eat('SEMICOLON');
return { type: 'VariableDeclaration', name: varName, value: expr };
}
// print_statement : 'print' '(' expression ')' ';'
printStatement() {
this.eat('PRINT');
this.eat('LPAREN');
const expr = this.expression();
this.eat('RPAREN');
this.eat('SEMICOLON');
return { type: 'PrintStatement', value: expr };
}
// expression : term ((PLUS | MINUS) term)*
expression() {
let node = this.term();
while (['PLUS', 'MINUS'].includes(this.currentToken.type)) {
const token = this.currentToken;
if (token.type === 'PLUS') {
this.eat('PLUS');
} else {
this.eat('MINUS');
}
node = { type: 'BinaryExpression', operator: token.value, left: node, right: this.term() };
}
return node;
}
// term : factor ((MUL | DIV) factor)*
term() {
let node = this.factor();
while (['MUL', 'DIV'].includes(this.currentToken.type)) {
const token = this.currentToken;
if (token.type === 'MUL') {
this.eat('MUL');
} else {
this.eat('DIV');
}
node = { type: 'BinaryExpression', operator: token.value, left: node, right: this.factor() };
}
return node;
}
// factor : NUMBER | IDENTIFIER | '(' expression ')'
factor() {
const token = this.currentToken;
if (token.type === 'NUMBER') {
this.eat('NUMBER');
return { type: 'Literal', value: token.value };
} else if (token.type === 'IDENTIFIER') {
this.eat('IDENTIFIER');
return { type: 'Identifier', name: token.value };
} else if (token.type === 'LPAREN') {
this.eat('LPAREN');
const node = this.expression();
this.eat('RPAREN');
return node;
} else {
throw new SyntaxError(`Unexpected token type: ${token.type}`);
}
}
// Parse the tokens and return the AST
parse() {
return this.program();
}
}
// 3. Interpreter: Traverses the AST and executes the code
class Interpreter {
constructor(ast) {
this.ast = ast;
this.globalScope = {};
}
visit(node) {
const methodName = `visit_${node.type}`;
if (this[methodName]) {
return this[methodName](node);
} else {
throw new ReferenceError(`No visit_${node.type} method`);
}
}
visit_Program(node) {
for (const statement of node.body) {
this.visit(statement);
}
}
visit_VariableDeclaration(node) {
const varName = node.name;
const varValue = this.visit(node.value);
this.globalScope[varName] = varValue;
}
visit_PrintStatement(node) {
const value = this.visit(node.value);
console.log(value);
}
visit_BinaryExpression(node) {
const left = this.visit(node.left);
const right = this.visit(node.right);
switch (node.operator) {
case '+':
return left + right;
case '-':
return left - right;
case '*':
return left * right;
case '/':
return left / right;
default:
throw new Error(`Unknown operator: ${node.operator}`);
}
}
visit_Literal(node) {
return node.value;
}
visit_Identifier(node) {
const varName = node.name;
if (varName in this.globalScope) {
return this.globalScope[varName];
} else {
throw new ReferenceError(`Undefined variable: ${varName}`);
}
}
interpret() {
this.visit(this.ast);
}
}
// 4. Putting It All Together
function runCalcScript(sourceCode) {
try {
const lexer = new Lexer(sourceCode);
const tokens = lexer.getTokens();
const parser = new Parser(tokens);
const ast = parser.parse();
const interpreter = new Interpreter(ast);
interpreter.interpret();
} catch (error) {
console.error(error.message);
}
}
// 5. Example Usage
const source = `
let a = 10;
let b = 20;
let c = a + b * 2;
print(c);
print((a + b) * 2);
`;
runCalcScript(source);
Explanation
-
Lexer: The lexer scans the input source code character by character and groups them into meaningful tokens (e.g., numbers, identifiers, operators).
-
Parser: The parser takes the list of tokens generated by the lexer and constructs an Abstract Syntax Tree (AST) representing the syntactic structure of the program.
-
Interpreter: The interpreter traverses the AST and performs operations based on the node types. It handles variable declarations, arithmetic operations, and print statements.
-
Execution: The runCalcScript function ties everything together. It takes the source code as input, tokenizes it, parses it into an AST, and then interprets it.
-
Example Usage: The example CalcScript program declares three variables (a, b, c), performs arithmetic operations, and prints the results.
Running the Interpreter
-
Save the Code: Save the above JavaScript code to a file, say calcscript.js.
-
Run with Node.js:
node calcscript.js
-
Expected Output:
50
60
c = 10 + 20 * 2 = 10 + 40 = 50
(10 + 20) * 2 = 30 * 2 = 60
Extending the Interpreter
This is a foundational interpreter. You can enhance it by adding more features such as:
- Control Flow:
if statements, loops (for, while).
- Functions: Define and call functions.
- Data Types: Strings, booleans, arrays, etc.
- Error Handling: More robust error messages and handling.
- Standard Library: Built-in functions for common tasks.
Building a full-fledged programming language is a complex task, but starting with a simple interpreter like CalcScript is a great way to understand the underlying concepts. Happy coding!