1

Improve program validation (bracket balance)

This commit is contained in:
2024-01-19 00:22:04 +01:00
parent 5af36d220e
commit 5fa2d16ae1
2 changed files with 23 additions and 6 deletions

View File

@ -11,6 +11,6 @@
*/ */
bool lex_brainfuck_file(const std::string &path, std::string &tokens); 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 #endif

View File

@ -3,6 +3,7 @@
#include <iostream> #include <iostream>
#include <fstream> #include <fstream>
#include <algorithm> #include <algorithm>
#include <stack>
bool lex_brainfuck_file(const std::string &path, std::string &tokens) { bool lex_brainfuck_file(const std::string &path, std::string &tokens) {
if (!tokens.empty()) { if (!tokens.empty()) {
@ -29,19 +30,35 @@ bool lex_brainfuck_file(const std::string &path, std::string &tokens) {
} }
input_stream.close(); input_stream.close();
if (!token_string_valid(tokens)) { if (!program_valid(tokens)) {
std::cout << "Program is invalid!" << std::endl; std::cout << "Program is invalid!" << std::endl;
return false; return false;
} }
std::cout << "Lexed BrainFuck program:\n" << tokens << std::endl; std::cout << "Lexed valid BrainFuck program:\n" << tokens << std::endl;
return true; 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 = "><+-.,[]"; std::string valid_tokens = "><+-.,[]";
bool tokens_valid = std::ranges::all_of(tokens.begin(), tokens.end(), [&valid_tokens](const char c){
return std::ranges::all_of(tokens.begin(), tokens.end(), [&valid_tokens](const char c){
return valid_tokens.find(c) != std::string::npos; return valid_tokens.find(c) != std::string::npos;
}); });
// Check bracket balance
std::stack<char> 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();
} }