A comprehensive interpreter for a custom programming language built from scratch using C++. This project implements a complete language processing pipeline with advanced features including optimization, error handling, and multi-type support.
- Multi-type Variables: Support for
int,float,string, andbooldata types - Arrays: 1D and 2D array support with dynamic indexing
- Control Flow: Complete implementation of
forloops,whileloops, and conditional statements - String Operations: String concatenation and manipulation capabilities
- Expressions: Complex nested expressions with proper operator precedence
- Constant Propagation Optimization: Compile-time expression evaluation to reduce runtime overhead
- Variable Scoping: Proper lexical scoping with nested scope support
- Error Diagnostics: Detailed error messages with line number information
- Symbol Table: Hash-based symbol table for efficient variable lookup
- Operator Support: Full range of arithmetic and logical operators
Source Code → Lexer → Parser → Semantic Analyzer → Interpreter → Output
-
Lexer (Tokenizer)
- Converts source code into tokens
- Handles keywords, identifiers, literals, and operators
- Maintains line number tracking for error reporting
-
Recursive Descent Parser
- Builds Abstract Syntax Tree (AST) from tokens
- Implements grammar rules for the custom language
- Handles operator precedence and associativity
-
Semantic Analyzer
- Type checking and validation
- Variable declaration and usage analysis
- Scope resolution and symbol table management
-
Interpreter
- AST traversal and execution
- Runtime value computation
- Memory management for variables and arrays
int x = 10;
float pi = 3.14;
string name = "John";
bool flag = true;
// For Loop
for (int i = 0; i < 10; i++) {
print(i);
}
// While Loop
while (x < 100) {
x = x * 2;
}
// If-Else
if (x > 0) {
print("Positive");
} else {
print("Non-positive");
}
string first = "Hello";
string second = "World";
string result = first + " " + second; // "Hello World"
The interpreter performs compile-time optimizations:
- Constant Folding: Evaluates constant expressions at compile time
Example:
// Before optimization
int x = 5 + 3 * 2;
int y = x + 1;
// After optimization (internally)
int x = 11; // 5 + 3 * 2 computed at compile time
int y = 12; // x + 1 resolved using propagated value
The interpreter provides detailed error diagnostics:
Error at line 15: Undefined variable 'count'
Error at line 23: Type mismatch - cannot assign string to int
Error at line 31: Array index out of bounds