Example #1
0
int main(int argc, char **argv) {

    if(argc < 3) {
        std::cout << "usage: " << argv[0] << " <infile> <outfilename>" << std::endl;
        return 1;
    }

    Program prog;

    std::ifstream infile(argv[1]);

    std::string line;

    while (std::getline(infile, line))
    {
        boost::regex e("^(HLT|INC|SET|OUT|IFE)\\s?([a-zA-Z][a-zA-Z0-9]+)?[,]?\\s?(.*)?$");
        boost::smatch match;

        if(boost::regex_match(line, match, e)) {
            if(match.size() == 2) {
                prog.addInstruction(match[1]);
            }
            else if(match.size() > 2) {
                if(match.size() == 3) {
                    prog.addInstruction(match[1],match[2]);
                }else if(match.size() == 4) {
                    prog.addInstruction(match[1],match[2],match[3]);
                }
            }
        }
    }

    /*prog.addInstruction("SET", "R1", "$\"foo\\n\"");
    prog.addInstruction("SET", "R2", "$'0'");
    prog.addInstruction("IFE", "R1", "R2");
    prog.addInstruction("HLT");
    prog.addInstruction("OUT", "R1");
    prog.addInstruction("INC", "R1");
    prog.addInstruction("SET", "IP", "$2");*/

    prog.writeBinary(std::string(argv[2]));
}
Example #2
0
Program* Compiler::compile(vector<string> lines) {
    Program *program = new Program();
    for(int i = 0; i < lines.size(); i++) {
        string line = lines[i];
        bool found = false;
        s.jmp(i);
        for(pair<string, factory> p: this->lines) {
            IInstruction *inst;
            regex r(p.first);
            if(regex_match(line, r)) {
                found = true;
                
                smatch result;
                vector<string> args;
                regex_search(line, result, r);
                
                for(int i = 1; i < result.size(); i++) {
                    args.push_back(result[i].str());
                }

                inst = p.second(args);
                program->addInstruction(inst);
                
                if(pre.find(p.first) != pre.end()) {
                    inst->run(s);
                }
            }
        }
        if(!found) {
            cerr << "Invalid opcode on line " << i << ": " << line << endl;
            delete program;
            return nullptr;
        }
    }
    
    s.jmp(0);
    return program;
}