This project is a simple interpreter that tokenizes, parses, and evaluates arithmetic expressions and assignments in a basic scripting language. It includes a lexer, parser, and evaluator to process and execute the input code.
- Lexer: Tokenizes the input string into tokens such as numbers, identifiers, operators, and parentheses.
- Parser: Builds an Abstract Syntax Tree (AST) from the tokens.
- Evaluator: Evaluates the AST to compute results and handle variable assignments.
- Supports:
- Arithmetic operations: +, -, *, /
- Assignment operations: =
- Parentheses for grouping
- Variables
Enumerations representing different types of tokens:
NUMBER
IDENTIFIER
ASSIGN
PLUS
MINUS
MULTIPLY
DIVIDE
LPAREN
RPAREN
END
INVALID
Structure to hold token type and value:
struct Token {
TokenType type;
string value;
};
Class that tokenizes the input string into a vector of tokens.
class Lexer {
public:
explicit Lexer(const string &input);
vector<Token> tokenize();
private:
string input;
size_t pos;
string readNumber();
string readIdentifier();
};
Various node types representing different components of the AST:
NUMBER_NODE
IDENTIFIER_NODE
ASSIGN_NODE
PLUS_NODE
MINUS_NODE
MULTIPLY_NODE
DIVIDE_NODE
struct Node {
virtual ~Node() = default;
virtual NodeType getType() const = 0;
};
struct NumberNode : Node {
int value;
explicit NumberNode(int value);
NodeType getType() const override;
};
struct IdentifierNode : Node {
string name;
explicit IdentifierNode(const string &name);
NodeType getType() const override;
};
struct BinaryOpNode : Node {
NodeType type;
unique_ptr<Node> left;
unique_ptr<Node> right;
BinaryOpNode(NodeType type, unique_ptr<Node> left, unique_ptr<Node> right);
NodeType getType() const override;
};
struct AssignNode : Node {
unique_ptr<IdentifierNode> left;
unique_ptr<Node> right;
AssignNode(unique_ptr<IdentifierNode> left, unique_ptr<Node> right);
NodeType getType() const override;
};
Class that builds the AST from the tokens.
class Parser {
public:
explicit Parser(const vector<Token> &tokens);
unique_ptr<Node> parse();
private:
const vector<Token> &tokens;
size_t pos;
unique_ptr<Node> assignment();
unique_ptr<Node> expression();
unique_ptr<Node> term();
unique_ptr<Node> factor();
void consume(TokenType type);
Token currentToken() const;
};
Class that evaluates the AST to produce results and handle variable assignments.
class Evaluator {
public:
int eval(unique_ptr<Node> &node);
unordered_map<string, int> getEnv() const;
private:
unordered_map<string, int> env;
};
- Compile the code using a C++ compiler:
g++ -o interpreter main.cpp
- Run the compiled executable:
./interpreter