Brainfuck可视化解释器C++SFML源代码&bf2c

· · 个人记录

C++20\ SFML-3.0.0\ brainfuck.cpp

#include<cstdio>
#include<iostream>
#include<vector>
#include<windows.h>
#include<thread>
#include<set>
#include<fstream>
#include<SFML/System.hpp>
#include<SFML/Window.hpp>
#include<SFML/Graphics.hpp>
#define max(a,b) ((a)>(b)?(a):(b))
#define min(a,b) ((a)<(b)?(a):(b))
void inputWithDfltEditCont(const char* cont,std::string &result){
    HANDLE hStdout=GetStdHandle(STD_OUTPUT_HANDLE);
    HANDLE hStdin=GetStdHandle(STD_INPUT_HANDLE);
    DWORD oldMode;
    GetConsoleMode(hStdin,&oldMode);
    SetConsoleMode(hStdin,ENABLE_LINE_INPUT | ENABLE_ECHO_INPUT | ENABLE_PROCESSED_INPUT);
    CONSOLE_SCREEN_BUFFER_INFO csbi;
    GetConsoleScreenBufferInfo(hStdout,&csbi);
    std::vector<INPUT_RECORD> inputEvents;
    for(const char* p=cont;*p;p++){
        INPUT_RECORD irDown             ={0};
        irDown.EventType                =KEY_EVENT;
        irDown.Event.KeyEvent.bKeyDown  =TRUE;
        irDown.Event.KeyEvent.wRepeatCount      =1;
        irDown.Event.KeyEvent.uChar.AsciiChar   =*p;
        irDown.Event.KeyEvent.wVirtualKeyCode   =VkKeyScanA(*p);
        irDown.Event.KeyEvent.wVirtualScanCode  =MapVirtualKey(irDown.Event.KeyEvent.wVirtualKeyCode, 0);
        irDown.Event.KeyEvent.dwControlKeyState =0;
        INPUT_RECORD irUp=irDown;
        irUp.Event.KeyEvent.bKeyDown=FALSE;
        inputEvents.push_back(irDown);
        inputEvents.push_back(irUp);
    }
    DWORD eventsWritten;
    WriteConsoleInput(hStdin,inputEvents.data(),static_cast<DWORD>(inputEvents.size()),&eventsWritten);
    const int BUFSIZE=2048;
    result.resize(BUFSIZE);
    DWORD charsRead;
    ReadConsoleA(
        hStdin,
        result.data(),
        BUFSIZE-1,
        &charsRead,
        NULL
    );
    result.resize(charsRead);
    if(result.size()>=2&&result[result.size()-2]=='\r'&&result[result.size()-1]=='\n')
        result.erase(result.size()-2);
    else if(!result.empty()&&(result.back()=='\r'||result.back()=='\n'))
        result.pop_back();
    SetConsoleMode(hStdin,oldMode);
}
std::string GetSystemFontPath(const std::string& fontName){
    HKEY hKey;
    if(RegOpenKeyEx(HKEY_LOCAL_MACHINE,"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Fonts",
                    0,KEY_READ,&hKey)!=ERROR_SUCCESS)
        return "";
    char value[255];
    DWORD size=sizeof(value);
    if(RegQueryValueEx(hKey,(fontName+" (TrueType)").c_str(),nullptr,nullptr,(LPBYTE)value,&size)==ERROR_SUCCESS){
        RegCloseKey(hKey);
        return "C:\\Windows\\Fonts\\"+std::string(value);
    }
    RegCloseKey(hKey);
    return "";
}
int memptr=0,codeptr=0;
unsigned char data[100000];
bool updateWin=true;
DWORD sleepTime=45;
std::set<char> bfcod={'+','-','>','<','[',']','.',','};
int brainfuck(const char* code,bool ooMode=false){
    int count=0;memptr=0,codeptr=0;
    memset(data,0,sizeof(data));
    for(;code[codeptr];codeptr++){
        if(!bfcod.count(code[codeptr])){updateWin=false;continue;}
        else updateWin=true;
        switch(code[codeptr]){
            case '>':memptr++;if(memptr>=sizeof(data)) return 3;break;
            case '<':memptr--;memptr=max(memptr,0);break;
            case '+':data[memptr]++;break;
            case '-':data[memptr]--;break;
            case '.':putchar(data[memptr]);break;
            case ',':data[memptr]=getchar();if(data[memptr]=='\n'&&ooMode) system("cls");break;
            case '[':
                if(!data[memptr]){
                    updateWin=false;
                    count=1;
                    while(count){
                        codeptr++;
                        if(code[codeptr]==']')count--;
                        if(code[codeptr]=='[')count++;
                        if(code[codeptr]==0)return 1;
                    }
                    updateWin=true;
                }
                break;
            case ']':
                if(data[memptr]){
                    updateWin=false;
                    count=1;
                    while(count){
                        codeptr--;
                        if(code[codeptr]=='[')count--;
                        if(code[codeptr]==']')count++;
                        if(code[codeptr]==0)return 2;
                    }
                    updateWin=true;
                }
                break;
            default:break;
        }
        if(!updateWin) continue;
        if(sleepTime==-1){while(sleepTime==-1) Sleep(33);}
        else if(sleepTime==-2) break;
        else Sleep(sleepTime);
    }
    sleepTime=45;
    return 0;
}
std::string code;
sf::Font font;
void drawBackground(sf::RenderWindow& window){
    sf::RectangleShape rect({window.getSize().x*0.5f,(float)window.getSize().y});
    rect.setPosition({0,0});
    rect.setFillColor(sf::Color(128,88,165));
    window.draw(rect);
    rect.setPosition({rect.getSize().x,0});
    rect.setFillColor(sf::Color(31,141,214));
    window.draw(rect);

    sf::Text text(font,L"Memory",35);
    text.setFillColor(sf::Color::White);
    text.setPosition({rect.getSize().x+15,3});
    window.draw(text);

    rect.setSize({38.f,38.f});
    rect.setPosition({float(100+(sleepTime==45?1:(sleepTime==16?2:(sleepTime==1?3:(sleepTime==0?4:0))))*38),4.f});
    rect.setFillColor(sf::Color{0xdd,0x51,0x4c});
    window.draw(rect);

    text.setString(L"Code 0 1 2 3 4");
    text.setPosition({15,3});
    window.draw(text);
}
void draw(sf::RenderWindow& window){
    sf::RectangleShape rect({50,30});
    rect.setFillColor(sf::Color{0xdd,0x51,0x4c});
    int w=(window.getSize().x>>1)/50,h=(window.getSize().y-45)/30;
    int qua=w*h;
    int codePtr=codeptr%qua,memPtr=memptr%qua;
    rect.setPosition({float(codePtr%w*50),float(codePtr/w*30+45)});
    window.draw(rect);
    rect.setPosition({float(memPtr%w*50)+(window.getSize().x>>1),float(memPtr/w*30+45)});
    window.draw(rect);

    codePtr=codeptr/qua*qua;
    memPtr=memptr/qua*qua;
    sf::Text text(font,L"",29);
    text.setFillColor(sf::Color::White);
    for(int i=0;i<h;i++){
        for(int j=0;j<w;j++){
            if(codePtr+i*w+j>=code.size()) goto DrawCodeBreak;
            text.setString(code[codePtr+i*w+j]);
            text.setOrigin({text.getLocalBounds().size.x/2+2,6});
            text.setPosition({float(j*50+25),float(i*30+45)});
            window.draw(text);
        }
    }
    DrawCodeBreak:
    for(int i=0;i<h;i++){
        for(int j=0;j<w;j++){
            if(memPtr+i*w+j>=sizeof(data)) return;
            text.setString(std::to_wstring(data[memPtr+i*w+j]));
            text.setOrigin({text.getLocalBounds().size.x/2+2,6});
            text.setPosition({float(j*50+25+(window.getSize().x>>1)),float(i*30+45)});
            window.draw(text);
        }
    }
}
void win_main(){
    if(!font.openFromFile(GetSystemFontPath("Consolas"))) exit(1);
    sf::RenderWindow window(sf::VideoMode({800,500}),"Brainfuck Interpreter",sf::Style::Default,
            sf::State::Windowed,sf::ContextSettings{.antiAliasingLevel=8});
    window.setFramerateLimit(60);
    drawBackground(window);
    window.display();
    drawBackground(window);
    while(window.isOpen()){
        while(const std::optional event=window.pollEvent())
            if(event->is<sf::Event::Closed>())
                window.close();
            else if(const auto* resized=event->getIf<sf::Event::Resized>()){
                window.setSize({resized->size.x,resized->size.y});
                window.setView(sf::View(sf::FloatRect({0,0},{(float)resized->size.x,(float)resized->size.y})));
            }else if(const auto* key=event->getIf<sf::Event::KeyPressed>()){
                if(key->scancode==sf::Keyboard::Scancode::Escape)
                    window.close();
                else if(key->scancode==sf::Keyboard::Scancode::Num0)
                    sleepTime=-1;
                else if(key->scancode==sf::Keyboard::Scancode::Num1)
                    sleepTime=45;
                else if(key->scancode==sf::Keyboard::Scancode::Num2)
                    sleepTime=16;
                else if(key->scancode==sf::Keyboard::Scancode::Num3)
                    sleepTime=1;
                else if(key->scancode==sf::Keyboard::Scancode::Num4)
                    sleepTime=0;
                else if(key->scancode==sf::Keyboard::Scancode::R)
                    sleepTime=-2;
            }
        if(updateWin){
            drawBackground(window);
            draw(window);
        }
        window.display();
    }
    exit(0);
}
int main(int argc,char** argv){
    if(argc>2) return 1;
    std::thread wint(win_main);
    wint.detach();
    while(true){
        system("cls");
        if(argc==2){
            std::ifstream file(argv[1]);
            if(!file.is_open()) return 1;
            code=std::string((std::istreambuf_iterator<char>(file)),std::istreambuf_iterator<char>());
            file.close();
            argc=1;
        }else inputWithDfltEditCont(code.c_str(),code);
        if(code=="exit") break;
        std::cout<<">-----------<\n";
        int e=brainfuck(code.c_str(),code.substr(code.size()-2)=="oo");
        if(e==1) std::cout<<"\nError: Unmatched '['";
        else if(e==2) std::cout<<"\nError: Unmatched ']'";
        else if(e==3) std::cout<<"\nError: Memory overflow";
        std::cout<<'\n';
        system("pause");
    }
    return 0;
}

bf2c.cpp

#include<iostream>
#include<fstream>
#include<string>
#include<set>
std::set<char> bfcod={'+','-','>','<','[',']','.',','};
void foutbf(std::ofstream& fout,char c,int n){
    static bool i=false;bool t=false;
    static int tabs=0;t=!bfcod.count(c);
    if(!t&&i){fout<<'\n';i=false;}
    #define outtabs for(int i=0;i<tabs;i++) fout<<'\t'
    switch(c){
        case '>':   outtabs;fout<<'\t';fout<<"cellptr+="<<n<<";\n";                         break;
        case '<':   outtabs;fout<<'\t';fout<<"cellptr-="<<n<<";\n";                         break;
        case '+':   outtabs;fout<<'\t';fout<<"memory[cellptr]+="<<n<<";\n";                 break;
        case '-':   outtabs;fout<<'\t';fout<<"memory[cellptr]-="<<n<<";\n";                 break;
        case '.':   while(n--){outtabs;fout<<'\t';fout<<"putchar(memory[cellptr]);\n";}     break;
        case ',':   while(n--){outtabs;fout<<'\t';fout<<"memory[cellptr]=getchar();\n";}    break;
        case '[':   while(n--){outtabs;fout<<'\t';fout<<"while(memory[cellptr]){\n";tabs++;}break;
        case ']':   while(n--){tabs--;outtabs;fout<<'\t';fout<<"}\n";}                      break;
        default :   if(!i){i=true;fout<<"//";}while(n--) fout<<c;                           break;
    }
    #undef outtabs
}
int main(int argc,char** argv){
    std::string bfcode;
    if(argc==2){
        std::ifstream fin(argv[1]);
        if(!fin.is_open()) return 1;
        std::getline(fin,bfcode);
    }else std::getline(std::cin,bfcode);
    std::string outpath;std::getline(std::cin,outpath);
    std::ofstream fout(outpath);
    if(!fout.is_open()) return 1;
    fout<<"#include<stdio.h>\nchar memory[30000];\nint cellptr=0;\nint main(){\n";
    int sum=1;
    for(int i=1;i<bfcode.size();i++){
        if(bfcode[i]==bfcode[i-1]) sum++;
        else{
            foutbf(fout,bfcode[i-1],sum);
            sum=1;
        }
    }
    foutbf(fout,bfcode[bfcode.size()-1],sum);
    if(!bfcod.count(bfcode[bfcode.size()-1])) fout<<'\n';
    fout<<"\treturn 0;\n}";
    return 0;
}