1

Implemented .bfuck file reading

This commit is contained in:
2024-01-18 21:12:40 +01:00
parent ea32025792
commit 98215c5ad6
2 changed files with 63 additions and 0 deletions

47
src/lex.cpp Normal file
View File

@ -0,0 +1,47 @@
#include "lex.hpp"
#include <iostream>
#include <fstream>
#include <algorithm>
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;
});
}