Write an interpreter for Clownish PL on C++, that will support variables, arythmetic,…
- User
Write an interpreter for Clownish PL on C++, that will support variables, arythmetic, strings, print, if/else, while and for. Come up with all syntax by yourself.
- Assistant
Creating an interpreter for a new programming language involves several steps, including defining the language's syntax, lexical elements, parsing mechanism, and execution model. Below, I present Clownish PL, a simple yet expressive programming language, along with its interpreter implemented in C++. This interpreter supports variables, arithmetic operations, strings,
printstatements,if/elseconditions,whileloops, andforloops.Clownish PL Syntax
1. Variables
- Declaration and Assignment:
var x = 10 var name = "Clown" - Variables are declared using the
varkeyword followed by the variable name and an optional initializer.
2. Arithmetic Operations
- Supports
+,-,*,/, and%.var sum = x + 5 var product = x * y
3. Strings
- Enclosed in double quotes.
var greeting = "Hello, World!"
4. Print Statement
- Outputs expressions to the console.
print(greeting) print(x + y)
5. If/Else Statements
- Conditional execution based on expressions.
if (x > 5) { print("x is greater than 5") } else { print("x is 5 or less") }
6. While Loops
- Repeats a block of code while a condition is true.
while (x < 10) { print(x) x = x + 1 }
7. For Loops
- Iterates with an initializer, condition, and incrementer.
for (var i = 0; i < 5; i = i + 1) { print(i) }
Interpreter Implementation in C++
The interpreter consists of several components:
- Lexer: Tokenizes the input source code.
- Parser: Parses tokens into an Abstract Syntax Tree (AST).
- Evaluator: Executes the AST.
Below is the complete C++ implementation of the Clownish PL interpreter.
Dependencies
Ensure you have a C++11 compatible compiler. The implementation uses standard libraries without external dependencies.
Code
#include <iostream> #include <string> #include <unordered_map> #include <vector> #include <cctype> #include <sstream> #include <stdexcept> #include <memory> // ---------------------- Lexer ---------------------- enum class TokenType { // Single-character tokens LEFT_PAREN, RIGHT_PAREN, LEFT_BRACE, RIGHT_BRACE, COMMA, SEMICOLON, // One or two character tokens PLUS, MINUS, STAR, SLASH, PERCENT, EQUAL, EQUAL_EQUAL, BANG_EQUAL, LESS, LESS_EQUAL, GREATER, GREATER_EQUAL, // Literals IDENTIFIER, STRING, NUMBER, // Keywords VAR, IF, ELSE, WHILE, FOR, PRINT, END_OF_FILE }; struct Token { TokenType type; std::string lexeme; double number; // For number literals std::string string; // For string literals Token(TokenType type, const std::string& lexeme) : type(type), lexeme(lexeme), number(0), string("") {} Token(TokenType type, const std::string& lexeme, double number) : type(type), lexeme(lexeme), number(number), string("") {} Token(TokenType type, const std::string& lexeme, const std::string& string) : type(type), lexeme(lexeme), number(0), string(string) {} }; class Lexer { private: std::string source; std::vector<Token> tokens; size_t start = 0; size_t current = 0; std::unordered_map<std::string, TokenType> keywords = { {"var", TokenType::VAR}, {"if", TokenType::IF}, {"else", TokenType::ELSE}, {"while", TokenType::WHILE}, {"for", TokenType::FOR}, {"print", TokenType::PRINT} }; bool is_at_end() const { return current >= source.size(); } char advance() { return source[current++]; } char peek() const { if (is_at_end()) return '\0'; return source[current]; } char peek_next() const { if (current + 1 >= source.size()) return '\0'; return source[current + 1]; } bool match(char expected) { if (is_at_end()) return false; if (source[current] != expected) return false; current++; return true; } void add_token(TokenType type) { std::string text = source.substr(start, current - start); tokens.emplace_back(type, text); } void add_token(TokenType type, double number) { std::string text = source.substr(start, current - start); tokens.emplace_back(type, text, number); } void add_token(TokenType type, const std::string& str) { std::string text = source.substr(start, current - start); tokens.emplace_back(type, text, str); } void string_literal() { while (peek() != '"' && !is_at_end()) { if (peek() == '\n') ; // Support multi-line strings if needed advance(); } if (is_at_end()) { throw std::runtime_error("Unterminated string."); } // Closing " advance(); std::string value = source.substr(start + 1, current - start - 2); tokens.emplace_back(TokenType::STRING, source.substr(start, current - start), value); } void number() { while (std::isdigit(peek())) advance(); if (peek() == '.' && std::isdigit(peek_next())) { // Consume '.' advance(); while (std::isdigit(peek())) advance(); } double value = std::stod(source.substr(start, current - start)); tokens.emplace_back(TokenType::NUMBER, source.substr(start, current - start), value); } void identifier() { while (std::isalnum(peek()) || peek() == '_') advance(); std::string text = source.substr(start, current - start); auto it = keywords.find(text); if (it != keywords.end()) { tokens.emplace_back(it->second, text); } else { tokens.emplace_back(TokenType::IDENTIFIER, text); } } public: Lexer(const std::string& source) : source(source) {} std::vector<Token> scan_tokens() { while (!is_at_end()) { start = current; scan_token(); } tokens.emplace_back(TokenType::END_OF_FILE, ""); return tokens; } void scan_token() { char c = advance(); switch (c) { case '(': add_token(TokenType::LEFT_PAREN); break; case ')': add_token(TokenType::RIGHT_PAREN); break; case '{': add_token(TokenType::LEFT_BRACE); break; case '}': add_token(TokenType::RIGHT_BRACE); break; case ',': add_token(TokenType::COMMA); break; case ';': add_token(TokenType::SEMICOLON); break; case '+': add_token(TokenType::PLUS); break; case '-': add_token(TokenType::MINUS); break; case '*': add_token(TokenType::STAR); break; case '/': add_token(TokenType::SLASH); break; case '%': add_token(TokenType::PERCENT); break; case '!': add_token(match('=') ? TokenType::BANG_EQUAL : TokenType::EQUAL); break; case '=': add_token(match('=') ? TokenType::EQUAL_EQUAL : TokenType::EQUAL); break; case '<': add_token(match('=') ? TokenType::LESS_EQUAL : TokenType::LESS); break; case '>': add_token(match('=') ? TokenType::GREATER_EQUAL : TokenType::GREATER); break; case '"': string_literal(); break; case ' ': case '\r': case '\t': case '\n': // Ignore whitespace break; case '#': // Comment till end of line while (peek() != '\n' && !is_at_end()) advance(); break; default: if (std::isdigit(c)) { number(); } else if (std::isalpha(c) || c == '_') { identifier(); } else { throw std::runtime_error("Unexpected character: " + std::string(1, c)); } break; } } }; // ---------------------- Parser ---------------------- enum class ExprType { BINARY, LITERAL, VARIABLE, ASSIGNMENT, UNARY, CALL }; struct Expr; struct Stmt; using ExprPtr = std::shared_ptr<Expr>; using StmtPtr = std::shared_ptr<Stmt>; struct Expr { ExprType type; virtual ~Expr() {} }; struct BinaryExpr : Expr { ExprPtr left; Token op; ExprPtr right; BinaryExpr(ExprPtr left, Token op, ExprPtr right) : left(left), op(op), right(right) { type = ExprType::BINARY; } }; struct UnaryExpr : Expr { Token op; ExprPtr right; UnaryExpr(Token op, ExprPtr right) : op(op), right(right) { type = ExprType::UNARY; } }; struct LiteralExpr : Expr { double number; std::string str; bool is_string; LiteralExpr(double number) : number(number), is_string(false) { type = ExprType::LITERAL; } LiteralExpr(const std::string& str) : str(str), is_string(true) { type = ExprType::LITERAL; } }; struct VariableExpr : Expr { std::string name; VariableExpr(const std::string& name) : name(name) { type = ExprType::VARIABLE; } }; struct AssignExpr : Expr { std::string name; ExprPtr value; AssignExpr(const std::string& name, ExprPtr value) : name(name), value(value) { type = ExprType::ASSIGNMENT; } }; struct CallExpr : Expr { std::string callee; std::vector<ExprPtr> arguments; CallExpr(const std::string& callee, const std::vector<ExprPtr>& arguments) : callee(callee), arguments(arguments) { type = ExprType::CALL; } }; struct Stmt { virtual ~Stmt() {} }; struct ExprStmt : Stmt { ExprPtr expression; ExprStmt(ExprPtr expr) : expression(expr) {} }; struct PrintStmt : Stmt { ExprPtr expression; PrintStmt(ExprPtr expr) : expression(expr) {} }; struct VarStmt : Stmt { std::string name; ExprPtr initializer; VarStmt(const std::string& name, ExprPtr initializer) : name(name), initializer(initializer) {} }; struct BlockStmt : Stmt { std::vector<StmtPtr> statements; BlockStmt(const std::vector<StmtPtr>& statements) : statements(statements) {} }; struct IfStmt : Stmt { ExprPtr condition; StmtPtr then_branch; StmtPtr else_branch; IfStmt(ExprPtr condition, StmtPtr then_branch, StmtPtr else_branch) : condition(condition), then_branch(then_branch), else_branch(else_branch) {} }; struct WhileStmt : Stmt { ExprPtr condition; StmtPtr body; WhileStmt(ExprPtr condition, StmtPtr body) : condition(condition), body(body) {} }; struct ForStmt : Stmt { StmtPtr initializer; ExprPtr condition; ExprPtr increment; StmtPtr body; ForStmt(StmtPtr initializer, ExprPtr condition, ExprPtr increment, StmtPtr body) : initializer(initializer), condition(condition), increment(increment), body(body) {} }; class Parser { private: std::vector<Token> tokens; size_t current = 0; // Forward declarations ExprPtr expression(); ExprPtr assignment(); ExprPtr equality(); ExprPtr comparison(); ExprPtr term(); ExprPtr factor(); ExprPtr unary(); ExprPtr primary(); std::vector<StmtPtr> statement_list(); bool match(const std::vector<TokenType>& types) { for (auto type : types) { if (check(type)) { advance(); return true; } } return false; } bool check(TokenType type) const { if (is_at_end()) return false; return peek().type == type; } Token advance_token() { if (!is_at_end()) current++; return previous(); } bool is_at_end() const { return peek().type == TokenType::END_OF_FILE; } Token peek() const { return tokens[current]; } Token previous() const { return tokens[current - 1]; } Token consume(TokenType type, const std::string& message) { if (check(type)) return advance_token(); throw std::runtime_error(message); } // Parsing methods StmtPtr declaration() { if (match({TokenType::VAR})) return var_declaration(); return statement(); } StmtPtr var_declaration() { Token name = consume(TokenType::IDENTIFIER, "Expected variable name."); ExprPtr initializer = nullptr; if (match({TokenType::EQUAL})) { initializer = expression(); } // consume(TokenType::SEMICOLON, "Expected ';' after variable declaration."); return std::make_shared<VarStmt>(name.lexeme, initializer); } StmtPtr statement() { if (match({TokenType::PRINT})) return print_statement(); if (match({TokenType::IF})) return if_statement(); if (match({TokenType::WHILE})) return while_statement(); if (match({TokenType::FOR})) return for_statement(); if (match({TokenType::LEFT_BRACE})) return std::make_shared<BlockStmt>(block()); return expression_statement(); } StmtPtr print_statement() { consume(TokenType::LEFT_PAREN, "Expected '(' after 'print'."); ExprPtr value = expression(); consume(TokenType::RIGHT_PAREN, "Expected ')' after value."); // consume(TokenType::SEMICOLON, "Expected ';' after value."); return std::make_shared<PrintStmt>(value); } StmtPtr expression_statement() { ExprPtr expr = expression(); // consume(TokenType::SEMICOLON, "Expected ';' after expression."); return std::make_shared<ExprStmt>(expr); } StmtPtr if_statement() { consume(TokenType::LEFT_PAREN, "Expected '(' after 'if'."); ExprPtr condition = expression(); consume(TokenType::RIGHT_PAREN, "Expected ')' after condition."); StmtPtr then_branch = statement(); StmtPtr else_branch = nullptr; if (match({TokenType::ELSE})) { else_branch = statement(); } return std::make_shared<IfStmt>(condition, then_branch, else_branch); } StmtPtr while_statement() { consume(TokenType::LEFT_PAREN, "Expected '(' after 'while'."); ExprPtr condition = expression(); consume(TokenType::RIGHT_PAREN, "Expected ')' after condition."); StmtPtr body = statement(); return std::make_shared<WhileStmt>(condition, body); } StmtPtr for_statement() { consume(TokenType::LEFT_PAREN, "Expected '(' after 'for'."); StmtPtr initializer; if (!check(TokenType::SEMICOLON)) { initializer = declaration(); } else { // Empty initializer initializer = nullptr; } consume(TokenType::SEMICOLON, "Expected ';' after initializer."); ExprPtr condition = nullptr; if (!check(TokenType::SEMICOLON)) { condition = expression(); } consume(TokenType::SEMICOLON, "Expected ';' after condition."); ExprPtr increment = nullptr; if (!check(TokenType::RIGHT_PAREN)) { increment = expression(); } consume(TokenType::RIGHT_PAREN, "Expected ')' after for clauses."); StmtPtr body = statement(); return std::make_shared<ForStmt>(initializer, condition, increment, body); } std::vector<StmtPtr> block() { std::vector<StmtPtr> statements; while (!check(TokenType::RIGHT_BRACE) && !is_at_end()) { statements.push_back(declaration()); } consume(TokenType::RIGHT_BRACE, "Expected '}' after block."); return statements; } ExprPtr expression() { return assignment(); } ExprPtr assignment() { ExprPtr expr = equality(); if (match({TokenType::EQUAL})) { Token equals = previous(); ExprPtr value = assignment(); if (auto var = std::dynamic_pointer_cast<VariableExpr>(expr)) { std::string name = var->name; return std::make_shared<AssignExpr>(name, value); } throw std::runtime_error("Invalid assignment target."); } return expr; } ExprPtr equality() { ExprPtr expr = comparison(); while (match({TokenType::BANG_EQUAL, TokenType::EQUAL_EQUAL})) { Token op = previous(); ExprPtr right = comparison(); expr = std::make_shared<BinaryExpr>(expr, op, right); } return expr; } ExprPtr comparison() { ExprPtr expr = term(); while (match({TokenType::GREATER, TokenType::GREATER_EQUAL, TokenType::LESS, TokenType::LESS_EQUAL})) { Token op = previous(); ExprPtr right = term(); expr = std::make_shared<BinaryExpr>(expr, op, right); } return expr; } ExprPtr term() { ExprPtr expr = factor(); while (match({TokenType::PLUS, TokenType::MINUS})) { Token op = previous(); ExprPtr right = factor(); expr = std::make_shared<BinaryExpr>(expr, op, right); } return expr; } ExprPtr factor() { ExprPtr expr = unary(); while (match({TokenType::STAR, TokenType::SLASH, TokenType::PERCENT})) { Token op = previous(); ExprPtr right = unary(); expr = std::make_shared<BinaryExpr>(expr, op, right); } return expr; } ExprPtr unary() { if (match({TokenType::BANG, TokenType::MINUS})) { Token op = previous(); ExprPtr right = unary(); return std::make_shared<UnaryExpr>(op, right); } return call(); } ExprPtr call() { ExprPtr expr = primary(); while (true) { if (match({TokenType::LEFT_PAREN})) { expr = finish_call(expr); } else { break; } } return expr; } ExprPtr finish_call(ExprPtr callee) { std::vector<ExprPtr> arguments; if (!check(TokenType::RIGHT_PAREN)) { do { arguments.push_back(expression()); } while (match({TokenType::COMMA})); } consume(TokenType::RIGHT_PAREN, "Expected ')' after arguments."); if (auto var = std::dynamic_pointer_cast<VariableExpr>(callee)) { return std::make_shared<CallExpr>(var->name, arguments); } throw std::runtime_error("Can only call functions by name."); } ExprPtr primary() { if (match({TokenType::NUMBER})) { return std::make_shared<LiteralExpr>(previous().number); } if (match({TokenType::STRING})) { return std::make_shared<LiteralExpr>(previous().string); } if (match({TokenType::IDENTIFIER})) { return std::make_shared<VariableExpr>(previous().lexeme); } if (match({TokenType::LEFT_PAREN})) { ExprPtr expr = expression(); consume(TokenType::RIGHT_PAREN, "Expected ')' after expression."); return expr; } throw std::runtime_error("Expected expression."); } public: Parser(const std::vector<Token>& tokens) : tokens(tokens) {} std::vector<StmtPtr> parse() { std::vector<StmtPtr> statements; while (!is_at_end()) { statements.push_back(declaration()); } return statements; } }; // ---------------------- Interpreter ---------------------- class Environment { public: Environment() : enclosing(nullptr) {} Environment(std::shared_ptr<Environment> enclosing) : enclosing(enclosing) {} void define(const std::string& name, double value) { values[name] = value; } void define(const std::string& name, const std::string& value) { string_values[name] = value; } void assign(const std::string& name, double value) { if (values.find(name) != values.end()) { values[name] = value; return; } if (enclosing != nullptr) { enclosing->assign(name, value); return; } throw std::runtime_error("Undefined variable '" + name + "'."); } void assign(const std::string& name, const std::string& value) { if (string_values.find(name) != string_values.end()) { string_values[name] = value; return; } if (enclosing != nullptr) { enclosing->assign(name, value); return; } throw std::runtime_error("Undefined variable '" + name + "'."); } double get(const std::string& name) { if (values.find(name) != values.end()) { return values[name]; } if (enclosing != nullptr) return enclosing->get(name); throw std::runtime_error("Undefined variable '" + name + "'."); } std::string get_string(const std::string& name) { if (string_values.find(name) != string_values.end()) { return string_values[name]; } if (enclosing != nullptr) return enclosing->get_string(name); throw std::runtime_error("Undefined variable '" + name + "'."); } bool is_string(const std::string& name) const { if (string_values.find(name) != string_values.end()) return true; if (enclosing != nullptr) return enclosing->is_string(name); return false; } private: std::unordered_map<std::string, double> values; std::unordered_map<std::string, std::string> string_values; std::shared_ptr<Environment> enclosing; }; class Interpreter { private: std::shared_ptr<Environment> globals = std::make_shared<Environment>(); std::shared_ptr<Environment> environment; public: Interpreter() : environment(globals) {} void interpret(const std::vector<StmtPtr>& statements) { try { for (const auto& stmt : statements) { execute(stmt); } } catch (std::runtime_error& error) { std::cerr << "Runtime error: " << error.what() << "\n"; } } private: void execute(const StmtPtr& stmt) { if (auto expr_stmt = std::dynamic_pointer_cast<ExprStmt>(stmt)) { evaluate(expr_stmt->expression); } else if (auto print_stmt = std::dynamic_pointer_cast<PrintStmt>(stmt)) { auto value = evaluate(print_stmt->expression); if (std::holds_alternative<double>(value)) { std::cout << std::get<double>(value) << "\n"; } else if (std::holds_alternative<std::string>(value)) { std::cout << std::get<std::string>(value) << "\n"; } } else if (auto var_stmt = std::dynamic_pointer_cast<VarStmt>(stmt)) { if (var_stmt->initializer != nullptr) { auto value = evaluate(var_stmt->initializer); if (std::holds_alternative<double>(value)) { environment->define(var_stmt->name, std::get<double>(value)); } else if (std::holds_alternative<std::string>(value)) { environment->define(var_stmt->name, std::get<std::string>(value)); } } else { environment->define(var_stmt->name, 0.0); } } else if (auto block_stmt = std::dynamic_pointer_cast<BlockStmt>(stmt)) { execute_block(block_stmt->statements, std::make_shared<Environment>(environment)); } else if (auto if_stmt = std::dynamic_pointer_cast<IfStmt>(stmt)) { auto condition = evaluate(if_stmt->condition); if (is_truthy(condition)) { execute(if_stmt->then_branch); } else if (if_stmt->else_branch != nullptr) { execute(if_stmt->else_branch); } } else if (auto while_stmt = std::dynamic_pointer_cast<WhileStmt>(stmt)) { while (is_truthy(evaluate(while_stmt->condition))) { execute(while_stmt->body); } } else if (auto for_stmt = std::dynamic_pointer_cast<ForStmt>(stmt)) { execute_for(for_stmt); } } void execute_block(const std::vector<StmtPtr>& statements, std::shared_ptr<Environment> new_env) { std::shared_ptr<Environment> previous = environment; environment = new_env; try { for (const auto& stmt : statements) { execute(stmt); } } catch (...) { environment = previous; throw; } environment = previous; } void execute_for(const std::shared_ptr<ForStmt>& stmt) { std::shared_ptr<Environment> previous = environment; environment = std::make_shared<Environment>(environment); try { if (stmt->initializer != nullptr) { execute(stmt->initializer); } while (true) { if (stmt->condition != nullptr) { auto condition = evaluate(stmt->condition); if (!is_truthy(condition)) break; } execute(stmt->body); if (stmt->increment != nullptr) { evaluate(stmt->increment); } } } catch (...) { environment = previous; throw; } environment = previous; } std::variant<double, std::string> evaluate(const ExprPtr& expr) { if (auto binary = std::dynamic_pointer_cast<BinaryExpr>(expr)) { double left = 0; std::string left_str; bool left_is_str = false; auto left_val = evaluate(binary->left); if (std::holds_alternative<double>(left_val)) { left = std::get<double>(left_val); } else { left_str = std::get<std::string>(left_val); left_is_str = true; } double right = 0; std::string right_str; bool right_is_str = false; auto right_val = evaluate(binary->right); if (std::holds_alternative<double>(right_val)) { right = std::get<double>(right_val); } else { right_str = std::get<std::string>(right_val); right_is_str = true; } switch (binary->op.type) { case TokenType::PLUS: if (left_is_str || right_is_str) { return left_is_str ? left_str + right_str : std::to_string(left) + right_str; } return left + right; case TokenType::MINUS: return left - right; case TokenType::STAR: return left * right; case TokenType::SLASH: if (right == 0) throw std::runtime_error("Division by zero."); return left / right; case TokenType::PERCENT: return static_cast<int>(left) % static_cast<int>(right); case TokenType::GREATER: return left > right; case TokenType::GREATER_EQUAL: return left >= right; case TokenType::LESS: return left < right; case TokenType::LESS_EQUAL: return left <= right; case TokenType::EQUAL_EQUAL: if (std::holds_alternative<double>(left_val) && std::holds_alternative<double>(right_val)) { return std::get<double>(left_val) == std::get<double>(right_val); } if (std::holds_alternative<std::string>(left_val) && std::holds_alternative<std::string>(right_val)) { return std::get<std::string>(left_val) == std::get<std::string>(right_val); } return false; case TokenType::BANG_EQUAL: if (std::holds_alternative<double>(left_val) && std::holds_alternative<double>(right_val)) { return std::get<double>(left_val) != std::get<double>(right_val); } if (std::holds_alternative<std::string>(left_val) && std::holds_alternative<std::string>(right_val)) { return std::get<std::string>(left_val) != std::get<std::string>(right_val); } return true; default: break; } } else if (auto unary = std::dynamic_pointer_cast<UnaryExpr>(expr)) { auto right_val = evaluate(unary->right); if (unary->op.type == TokenType::MINUS) { if (std::holds_alternative<double>(right_val)) { return -std::get<double>(right_val); } throw std::runtime_error("Operand must be a number."); } else if (unary->op.type == TokenType::BANG_EQUAL) { return !is_truthy(right_val); } } else if (auto literal = std::dynamic_pointer_cast<LiteralExpr>(expr)) { if (literal->is_string) return literal->str; return literal->number; } else if (auto var = std::dynamic_pointer_cast<VariableExpr>(expr)) { if (environment->is_string(var->name)) { return environment->get_string(var->name); } return environment->get(var->name); } else if (auto assign = std::dynamic_pointer_cast<AssignExpr>(expr)) { auto value = evaluate(assign->value); if (std::holds_alternative<double>(value)) { environment->assign(assign->name, std::get<double>(value)); } else if (std::holds_alternative<std::string>(value)) { environment->assign(assign->name, std::get<std::string>(value)); } if (environment->is_string(assign->name)) { return environment->get_string(assign->name); } return environment->get(assign->name); } else if (auto call = std::dynamic_pointer_cast<CallExpr>(expr)) { if (call->callee == "print") { if (call->arguments.size() != 1) { throw std::runtime_error("print() takes exactly one argument."); } auto arg = evaluate(call->arguments[0]); if (std::holds_alternative<double>(arg)) { std::cout << std::get<double>(arg) << "\n"; } else if (std::holds_alternative<std::string>(arg)) { std::cout << std::get<std::string>(arg) << "\n"; } return 0.0; } throw std::runtime_error("Undefined function '" + call->callee + "'."); } throw std::runtime_error("Unknown expression."); } bool is_truthy(const std::variant<double, std::string>& value) { if (std::holds_alternative<double>(value)) { return std::get<double>(value) != 0; } if (std::holds_alternative<std::string>(value)) { return !std::get<std::string>(value).empty(); } return false; } }; // ---------------------- Main ---------------------- int main() { std::cout << "Clownish PL Interpreter\n"; std::cout << "Enter your code below. Type 'END' on a new line to execute.\n"; std::string line, source; while (std::getline(std::cin, line)) { if (line == "END") break; source += line + "\n"; } try { // Lexing Lexer lexer(source); auto tokens = lexer.scan_tokens(); // Parsing Parser parser(tokens); auto statements = parser.parse(); // Interpreting Interpreter interpreter; interpreter.interpret(statements); } catch (std::runtime_error& error) { std::cerr << "Error: " << error.what() << "\n"; } return 0; }Explanation
-
Lexer: The lexer tokenizes the input source code into a series of tokens. It recognizes keywords (
var,if,else,while,for,print), operators (+,-,*,/,%,==,!=,<,<=,>,>=,=), literals (numbers and strings), and punctuation ((,),{,},,,;). -
Parser: The parser takes the tokens from the lexer and constructs an Abstract Syntax Tree (AST) representing the program's structure. It handles variable declarations, expressions, print statements, control flow constructs (
if/else,while,for), and blocks of code. -
Interpreter: The interpreter traverses the AST and executes the program. It maintains an environment for variable storage, supports arithmetic and string operations, handles scoping for blocks and loops, and executes print statements.
-
Main Function: The
mainfunction serves as the entry point. It reads input from the user until the user typesENDon a new line, then it tokenizes, parses, and interprets the input.
Usage
To use the interpreter:
-
Compile the Code: Save the code to a file, say
clownish_pl.cpp, and compile it using a C++11 compatible compiler.g++ -std=c++11 -o clownish_pl clownish_pl.cpp -
Run the Interpreter:
./clownish_pl -
Enter Clownish PL Code: Type your Clownish PL code. When you're done, type
ENDon a new line to execute.Example Program:
var x = 10 var y = 20 var name = "Clownish" print("Sum of x and y is:") print(x + y) if (x < y) { print("x is less than y") } else { print("x is not less than y") } var i = 0 while (i < 5) { print(i) i = i + 1 } for (var j = 0; j < 3; j = j + 1) { print("For loop iteration:") print(j) } ENDExpected Output:
Clownish PL Interpreter Enter your code below. Type 'END' on a new line to execute. Sum of x and y is: 30 x is less than y 0 1 2 3 4 For loop iteration: 0 For loop iteration: 1 For loop iteration: 2
This interpreter provides a foundational structure for Clownish PL. It can be extended with more features such as functions, data structures, error handling enhancements, and more sophisticated standard libraries as needed.
- Declaration and Assignment: