diff --git a/include/lex.hpp b/include/lex.hpp index f9a6556..dcc7585 100644 --- a/include/lex.hpp +++ b/include/lex.hpp @@ -11,6 +11,6 @@ */ bool lex_brainfuck_file(const std::string &path, std::string &tokens); -bool token_string_valid(std::string_view tokens); +bool program_valid(const std::string_view tokens); #endif \ No newline at end of file diff --git a/src/lex.cpp b/src/lex.cpp index adaf023..d529a62 100644 --- a/src/lex.cpp +++ b/src/lex.cpp @@ -3,6 +3,7 @@ #include #include #include +#include bool lex_brainfuck_file(const std::string &path, std::string &tokens) { if (!tokens.empty()) { @@ -29,19 +30,35 @@ bool lex_brainfuck_file(const std::string &path, std::string &tokens) { } input_stream.close(); - if (!token_string_valid(tokens)) { + if (!program_valid(tokens)) { std::cout << "Program is invalid!" << std::endl; return false; } - std::cout << "Lexed BrainFuck program:\n" << tokens << std::endl; + std::cout << "Lexed valid BrainFuck program:\n" << tokens << std::endl; return true; } -bool token_string_valid(const std::string_view tokens) { +bool program_valid(const std::string_view tokens) { + // Check tokens std::string valid_tokens = "><+-.,[]"; - - return std::ranges::all_of(tokens.begin(), tokens.end(), [&valid_tokens](const char c){ + bool tokens_valid = std::ranges::all_of(tokens.begin(), tokens.end(), [&valid_tokens](const char c){ return valid_tokens.find(c) != std::string::npos; }); + + // Check bracket balance + std::stack brackets; + for (const char c : tokens) { + if (c == '[') { + brackets.push('['); + } else if (c == ']') { + if (brackets.top() == '[') { + brackets.pop(); + } else { + return false; + } + } + } + + return tokens_valid && brackets.empty(); } \ No newline at end of file