From 98215c5ad6f9ad618aab5126b78ada1cbbd82e86 Mon Sep 17 00:00:00 2001 From: Christoph Urlacher Date: Thu, 18 Jan 2024 21:12:40 +0100 Subject: [PATCH] Implemented .bfuck file reading --- include/lex.hpp | 16 ++++++++++++++++ src/lex.cpp | 47 +++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 63 insertions(+) create mode 100644 include/lex.hpp create mode 100644 src/lex.cpp diff --git a/include/lex.hpp b/include/lex.hpp new file mode 100644 index 0000000..f9a6556 --- /dev/null +++ b/include/lex.hpp @@ -0,0 +1,16 @@ +#ifndef __LEX_H_ +#define __LEX_H_ + +#include + +/** + * @brief Lex a brainfuck file to a string from disk. Each element is a token. + * @param path The path to the file to be lexed + * @param tokens The string where the tokens will be written to + * @return True if the file was lexed successfully + */ +bool lex_brainfuck_file(const std::string &path, std::string &tokens); + +bool token_string_valid(std::string_view tokens); + +#endif \ No newline at end of file diff --git a/src/lex.cpp b/src/lex.cpp new file mode 100644 index 0000000..adaf023 --- /dev/null +++ b/src/lex.cpp @@ -0,0 +1,47 @@ +#include "lex.hpp" + +#include +#include +#include + +bool lex_brainfuck_file(const std::string &path, std::string &tokens) { + if (!tokens.empty()) { + std::cout << "Result string \"tokens\" has to be empty!" << std::endl; + return false; + } + + std::ifstream input_stream; + input_stream.open(path, std::ios::in); + if (!input_stream.is_open()) { + std::cout << "Failed to open file \"" << path << "\"" << std::endl; + return false; + } + + std::string line; + while (std::getline(input_stream, line)) { + tokens += line; + } + + if (!input_stream.eof() && input_stream.fail()) { + std::cout << "Error reading from file \"" << path << "\"" << std::endl; + input_stream.close(); + return false; + } + input_stream.close(); + + if (!token_string_valid(tokens)) { + std::cout << "Program is invalid!" << std::endl; + return false; + } + + std::cout << "Lexed BrainFuck program:\n" << tokens << std::endl; + return true; +} + +bool token_string_valid(const std::string_view tokens) { + std::string valid_tokens = "><+-.,[]"; + + return std::ranges::all_of(tokens.begin(), tokens.end(), [&valid_tokens](const char c){ + return valid_tokens.find(c) != std::string::npos; + }); +} \ No newline at end of file