1

Compare commits

...

3 Commits

Author SHA1 Message Date
5af36d220e Add HelloWorld.bfuck 2024-01-18 21:13:01 +01:00
c973e90a64 Read file passed through argv[] 2024-01-18 21:12:56 +01:00
98215c5ad6 Implemented .bfuck file reading 2024-01-18 21:12:40 +01:00
5 changed files with 78 additions and 3 deletions

View File

@ -8,7 +8,8 @@ set(CMAKE_CXX_STANDARD 20)
include_directories(include)
add_executable(bfuck
src/main.cpp
src/main.cpp
src/lex.cpp
)
# target_link_libraries(lasm Boost::program_options)

1
HelloWorld.bfuck Normal file
View File

@ -0,0 +1 @@
++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>.+++.

16
include/lex.hpp Normal file
View File

@ -0,0 +1,16 @@
#ifndef __LEX_H_
#define __LEX_H_
#include <string>
/**
* @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

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;
});
}

View File

@ -1,5 +1,15 @@
#include "lex.hpp"
#include <iostream>
int main() {
std::cout << "Hello, World!" << std::endl;
int main(int argc, char **argv) {
if (argc != 2) {
std::cout << "Usage: bfuck <IN-PATH>" << std::endl;
}
std::cout << "Running " << argv[1] << "...\n" << std::endl;
std::string tokens;
lex_brainfuck_file(argv[1], tokens);
return 0;
}