Skip to content

Instantly share code, notes, and snippets.

@Johann150
Created August 16, 2019 23:15
Show Gist options
  • Save Johann150/d49c7d4b00eedb553f2303c393c5b923 to your computer and use it in GitHub Desktop.
Save Johann150/d49c7d4b00eedb553f2303c393c5b923 to your computer and use it in GitHub Desktop.
#include<iostream>
#include<fstream>
#include<string>
#include<vector>
#include<utility>
#include<algorithm>
int main(int argc,char** argv){
std::streambuf *cinbuf=std::cin.rdbuf(); // save cin buffer in case it is redirected
if(argc>1){
// redirect file to stdin
std::ifstream*f=new std::ifstream(argv[1]);
if(!f->is_open()){
std::cout<<"?file"<<std::endl;
return 1;
}
std::cin.rdbuf(f->rdbuf());
}
std::vector<std::pair<std::string,std::string>> replacements;
std::string buf;
while(true){
if(std::cin.eof()){
std::cout<<"?eof"<<std::endl;
return 2;
}
std::getline(std::cin,buf);
// ignore empty lines
if(buf.empty()) continue;
size_t i=buf.find("::=");
if(i!=std::string::npos&&i!=0){
replacements.emplace_back(buf.substr(0,i),buf.substr(i+3,buf.size()));
}else if(i==0){
break;
}else{
// no ::= found
std::cout<<"?syntax"<<std::endl;
return 3;
}
}
std::string state;
while(!std::cin.eof()){
std::getline(std::cin,buf);
state+=buf;
}
// initial state loaded, can now return to normal cin
std::cin.rdbuf(cinbuf); // also clears eof flag
bool applied;
do{
std::random_shuffle(replacements.begin(),replacements.end());
applied=false;
for(std::pair<std::string,std::string> p:replacements){
size_t i=state.find(p.first);
// skip if rule didn't match
if(i==std::string::npos) continue;
// rule did match, apply it
applied=true;
if(p.second==":::"){
// input
std::cout<<"> ";
std::getline(std::cin,buf);
state.replace(i,p.first.size(),buf);
}else if(p.second[0]=='~'){
// output
state.erase(i,p.first.size());
std::cout<<(p.second.size()==1?"\n":p.second.substr(1));
}else{
state.replace(i,p.first.size(),p.second);
}
}
}while(applied);
std::cout<<"\n\t"<<state<<std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment