Created
December 10, 2017 18:49
-
-
Save ShigekiKarita/3ed1f54c46f0f8dadce411ffdaa2fa87 to your computer and use it in GitHub Desktop.
Brainfuck interpreter in C++11
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <algorithm> | |
| #include <functional> | |
| #include <iostream> | |
| #include <fstream> | |
| #include <unordered_map> | |
| #include <vector> | |
| // byte array | |
| using Memory = std::vector<unsigned char>; | |
| using Pointer = Memory::iterator; | |
| auto read_program(const char* path) { | |
| Memory imem; | |
| std::ifstream fin(path); | |
| if (fin) { | |
| std::copy(std::istreambuf_iterator<char>(fin), | |
| std::istreambuf_iterator<char>(), | |
| std::back_inserter(imem)); | |
| } else { | |
| std::cerr << "file: " << path << " not found" << std::endl; | |
| } | |
| return std::move(imem); | |
| } | |
| int main(int argc, char* argv[]) { | |
| std::cin.unsetf(std::ios_base::skipws); | |
| std::ios_base::sync_with_stdio(false); | |
| if (argc != 2) { | |
| std::cerr << "usage: " << argv[0] << " <bf file>" << std::endl; | |
| } | |
| Memory imem = read_program(argv[1]); | |
| Memory dmem(65536); | |
| auto iptr = imem.begin(); | |
| auto dptr = dmem.begin(); | |
| std::unordered_map<char, std::function<void()>> actions = { | |
| {'>', [&]{ ++dptr; }}, | |
| {'<', [&]{ --dptr; }}, | |
| {'+', [&]{ ++(*dptr); }}, | |
| {'-', [&]{ --(*dptr); }}, | |
| {'.', [&]{ std::cout << *dptr; }}, | |
| {',', [&]{ std::cin >> *dptr; }}, | |
| {'[', [&]{ | |
| if (!*(dptr)) { | |
| for (int t = 1; t; ++iptr) { | |
| if (*iptr == '[') { ++t; } | |
| else if (*iptr == ']') { --t; } | |
| } | |
| } | |
| } | |
| }, | |
| {']', [&]{ | |
| iptr -= 2; | |
| for (int t = -1; t; --iptr) { | |
| if (*iptr == '[') { ++t; } | |
| else if (*iptr == ']') { --t; } | |
| } | |
| ++iptr; | |
| }} | |
| }; | |
| while (iptr != imem.end()) { | |
| if (auto f = actions[*iptr++]) { | |
| f(); | |
| } | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| >+++++++++[<++++++++>-]<.>+++++++[<++++>-]<+.+++++++..+++.[-]>++++++++[<++ | |
| ++>-]<.>+++++++++++[<+++++>-]<.>++++++++[<+++>-]<.+++.------.--------.[-]> | |
| ++++++++[<++++>-]<+.[-]++++++++++. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment