From c2a3cecc1ab2d3f27dcea40a6f0f353b0306d66a Mon Sep 17 00:00:00 2001 From: ov-4 Date: Thu, 29 Jan 2026 10:20:58 +0000 Subject: Added INPUT, OUTPUT and DECLARE --- lib/Parser/Parser.cc | 77 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 77 insertions(+) create mode 100644 lib/Parser/Parser.cc (limited to 'lib/Parser') diff --git a/lib/Parser/Parser.cc b/lib/Parser/Parser.cc new file mode 100644 index 0000000..90dc3a0 --- /dev/null +++ b/lib/Parser/Parser.cc @@ -0,0 +1,77 @@ +#include "cps/Parser.h" + +using namespace cps; + +int Parser::getNextToken() { + return CurTok = Lex.gettok(); +} + +std::unique_ptr Parser::ParseNumberExpr() { + auto Result = std::make_unique(Lex.NumVal); + getNextToken(); + return Result; +} + +std::unique_ptr Parser::ParseIdentifierExpr() { + std::string IdName = Lex.IdentifierStr; + getNextToken(); + return std::make_unique(IdName); +} + +std::unique_ptr Parser::ParseExpression() { + if (CurTok == tok_number) + return ParseNumberExpr(); + if (CurTok == tok_identifier) + return ParseIdentifierExpr(); + return nullptr; +} + +std::vector> Parser::Parse() { + std::vector> Statements; + + while (CurTok != tok_eof) { + if (CurTok == tok_declare) { + // DECLARE : INTEGER + getNextToken(); // eat DECLARE + if (CurTok != tok_identifier) break; // Error + std::string Name = Lex.IdentifierStr; + getNextToken(); // eat Name + + if (CurTok != tok_colon) break; // Error: expected ':' + getNextToken(); // eat ':' + + if (CurTok != tok_integer_kw) break; // Error: expected INTEGER + getNextToken(); // eat INTEGER + + Statements.push_back(std::make_unique(Name)); + } + else if (CurTok == tok_identifier) { + // <- + std::string Name = Lex.IdentifierStr; + getNextToken(); // eat Name + + if (CurTok != tok_assign) break; // Error: expected '<-' + getNextToken(); // eat '<-' + + auto Expr = ParseExpression(); + Statements.push_back(std::make_unique(Name, std::move(Expr))); + } + else if (CurTok == tok_input) { + // INPUT + getNextToken(); // eat INPUT + if (CurTok != tok_identifier) break; + Statements.push_back(std::make_unique(Lex.IdentifierStr)); + getNextToken(); + } + else if (CurTok == tok_output) { + // OUTPUT + getNextToken(); // eat OUTPUT + auto Expr = ParseExpression(); + Statements.push_back(std::make_unique(std::move(Expr))); + } + else { + getNextToken(); // Skip unknown + } + } + return Statements; +} -- cgit v1.3.1-4-g156e