Ejemplo n.º 1
0
std::string Interpreter::RunCommand(const std::string & in_src) {
    std::string in = in_src;
    std::vector<std::string> args;

    // compute any evaluator blocks in full
    in = ReduceEvaluators(in_src);


    Chain str = in;
    std::string command = str.GetLink();




    // the help keyword is special.
    // if it is the first token in the command 
    // after evaluation, it will treat the following 
    // argument as the command to request help for
    if (command == "help") {
        str++;
        std::string helpPage = str.GetLink();

        auto helpCmd = commands.find(helpPage.c_str());
        if (helpCmd == commands.end() || !helpPage.size()) {
            Chain c = "";            
            if (helpPage.size()) 
                c << "\"" << helpPage.c_str() << "\" does not exist as a command.\n";
            c << "Here are the list of available commands:\n";
            auto listIter = commands.begin();
            while(listIter != commands.end()) {
                c << "    " << (listIter++)->first.c_str() << "\n";
            }
            return c;
        }
        return (Chain() << helpPage << ": " << helpCmd->second->Help() << "\n");
    }






    auto iter = commands.find(command.c_str());

    if (iter == commands.end()) {
        return (Chain() << "Unknown command \"" << in << "\"");
    }

    // parse arguments
    while(str.LinksLeft()) {

        if (str.GetLink()[0] != '"') {
            // normal arg
            args.push_back(str.GetLink().c_str()); str++;
        } else {
            // double quote arg 
            Chain compoundArg;
            int iter = str.GetLinkPos();
            iter++;
            while(str.ToString()[iter] != '"' && iter < str.ToString().size()) {
                compoundArg<<str.ToString()[iter];
                iter++;
            }

            if (!(iter < str.ToString().size() && 
                  str.ToString()[iter] == '"'    && 
                  iter != str.GetLinkPos())) {
                return "Missing compound argument terminator \"...";
            }

            // push in arg minus quotes
            args.push_back(compoundArg);

            str = str.ToString().substr(iter+1, str.ToString().size()-1);
        }
    }

    return (*(iter->second))(args);
}