main.cpp 15.7 KB
Newer Older
Victor Yacovlev's avatar
Victor Yacovlev committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
#include <iostream>
#include <fstream>
#include "stdlib/kumirstdlib.hpp"
#include "vm/variant.hpp"
#include "vm/vm_bytecode.hpp"
#include "vm/vm.hpp"

#if !defined(WIN32) && !defined(_WIN32)
#define LOCALE Kumir::UTF8
#else
#define LOCALE Kumir::CP866
#endif

int usage(const char * programName)
{
    std::cerr << "Usage: " << std::endl;
    std::cerr << "\t" << programName << " FILENAME.kod | FILENAME.ks [ARG1 [ARG2 ... [ARGn]]]" << std::endl << std::endl;
    std::cerr << "\tFILENAME.kod\tKumir runtime code file name" << std::endl;
    std::cerr << "\tFILENAME.ks\tKumir assembler input file name" << std::endl;
    std::cerr << "\tARG1...ARGn\tKumir program main algorithm arguments" << std::endl;
    return 127;
}

24 25 26 27 28 29
class InteractionHandler
        : public VM::AbstractInteractionHandler
{
public:
    explicit InteractionHandler(int argc, char *argv[]);
    bool makeInputArgument(VM::Variable & reference);
30
    bool makeOutputArgument(const VM::Variable & reference);
31
private:
32 33
    void output(const Kumir::String & s);
    inline void output(const std::string & s) { output(Kumir::Core::fromAscii(s)); }
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
    bool readScalarArgument(const Kumir::String & message, const Kumir::String & name, VM::ValueType type, VM::AnyValue & val);
    std::deque< Kumir::String > m_arguments;
    size_t i_currentArgument;
};

InteractionHandler::InteractionHandler(int argc, char *argv[])
{
    i_currentArgument = 0;
    bool argumentsScope = false;
    for (int i=1; i<argc; i++) {
        std::string arg(argv[i]);
        if (!argumentsScope) {
            if (arg[0]!='-') {
                // Found not a switch -> it is a program,
                // so next arg is a program argument
                argumentsScope = true;
            }
        }
        else {
            m_arguments.push_back(Kumir::Coder::decode(LOCALE, arg));
        }
    }
}

58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
#define IS_HEX(x) ( (x>='0' && x<='9') || (x>='A' && x<='F') || (x>='a' && x<='f') )

Kumir::String decodeHttpStringValue(const std::string & s)
{
    Kumir::String result;
    size_t cpos = 0;
    std::string utf8string;
    utf8string.reserve(s.length());
    while (cpos<s.length()) {
        if (s[cpos]=='%'
                && cpos+2 < s.length()
                && IS_HEX(s[cpos+1])
                && IS_HEX(s[cpos+2])
                )
        {
            std::string hexcode = std::string("0x")+s.substr(cpos+1,2);
            bool ok;
            int value = Kumir::Converter::stringToInt(Kumir::Coder::decode(Kumir::ASCII,hexcode), ok);
            char ch = (char)value;
            utf8string.push_back(ch);
            cpos += 3;
        }
        else {
            utf8string.push_back(s[cpos]);
            cpos += 1;
        }

    }
    result = Kumir::Coder::decode(Kumir::UTF8, utf8string);
    return result;
}

90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
int showErrorMessage(const Kumir::String & message, int code) {
    bool toHttp = false;
#if !defined(WIN32) && !defined(_WIN32)
    char * REQUEST_METHOD = getenv("REQUEST_METHOD");
    char * QUERY_STRING = getenv("QUERY_STRING");
    toHttp = (REQUEST_METHOD!=0 && QUERY_STRING!=0);
#endif
    if (!toHttp) {
        const std::string localMessage = Kumir::Coder::encode(LOCALE, message);
        std::cerr << localMessage << std::endl;
        return code;
    }
    else {
        const std::string localMessage = Kumir::Coder::encode(Kumir::UTF8, message);
        std::cout << "Content-type: text/html;charset=utf-8\n\n\n";
        std::cout << "<html><head><title>An error occured on server</title></head>\n";
        std::cout << "<body>\n";
        std::cout << localMessage << std::endl;
        std::cout << "</body></html>\n";
        return 0;
    }
}

113 114 115 116 117 118 119 120
bool InteractionHandler::readScalarArgument(const Kumir::String &message, const Kumir::String &name, VM::ValueType type, VM::AnyValue &val)
{
    Kumir::IO::InputStream stream;
    bool foundValue = false;
#if !defined(WIN32) && !defined(_WIN32)
    char * REQUEST_METHOD = getenv("REQUEST_METHOD");
    char * QUERY_STRING = getenv("QUERY_STRING");
    if (REQUEST_METHOD && std::string(REQUEST_METHOD)==std::string("GET") && QUERY_STRING) {
121
        Kumir::String query_string = decodeHttpStringValue(std::string(QUERY_STRING));
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227
        Kumir::StringList pairs = Kumir::Core::splitString(query_string, Kumir::Char('&'), true);
        for (size_t i=0; i<pairs.size(); i++) {
            Kumir::StringList apair = Kumir::Core::splitString(pairs[i], Kumir::Char('='), true);
            if (apair.size()==2) {
                Kumir::String aname = apair[0];
                Kumir::String avalue = apair[1];
                if (aname==name) {
                    stream = Kumir::IO::InputStream(avalue);
                    foundValue = true;
                    break;
                }
            }
        }
    }
#endif
    if (!foundValue) {
        if (i_currentArgument<m_arguments.size()) {
            stream = Kumir::IO::InputStream(m_arguments[i_currentArgument]);
            i_currentArgument ++;
            foundValue = true;
        }
    }
    if (!foundValue) {
        Kumir::IO::writeString(0, message);
        stream = Kumir::IO::InputStream(stdin, LOCALE);
    }
    if      (type==VM::VT_int)
        val = Kumir::IO::readInteger(stream);
    else if (type==VM::VT_real)
        val = Kumir::IO::readReal(stream);
    else if (type==VM::VT_bool)
        val = Kumir::IO::readBool(stream);
    else if (type==VM::VT_char)
        val = Kumir::IO::readChar(stream);
    else if (type==VM::VT_string)
        val = Kumir::IO::readString(stream);
    return Kumir::Core::getError().size()==0;
}

bool InteractionHandler::makeInputArgument(VM::Variable &reference)
{
    Kumir::String message = Kumir::Core::fromUtf8("Введите ")+reference.name();
    if (reference.dimension()==0) {
        message += Kumir::Core::fromAscii(": ");
        VM::AnyValue val;
        if (readScalarArgument(message, reference.name(), reference.baseType(), val))
            reference.setValue(val);
    }
    else if (reference.dimension()==1) {
        int bounds[7];
        reference.getEffectiveBounds(bounds);
        for (int x=bounds[0]; x<=bounds[1]; x++) {
            VM::AnyValue val;
            message = Kumir::Core::fromUtf8("Введите ")+reference.name();
            message += Kumir::Core::fromAscii("[");
            message += Kumir::Converter::intToString(x);
            message += Kumir::Core::fromAscii("]: ");
            if (readScalarArgument(message, reference.name(), reference.baseType(),  val))
                reference.setValue(x,val);
            else
                return true;
        }
    }
    else if (reference.dimension()==2) {
        int bounds[7];
        reference.getEffectiveBounds(bounds);
        for (int y=bounds[0]; y<=bounds[1]; y++) {
            for (int x=bounds[2]; x<=bounds[3]; x++) {
                VM::AnyValue val;
                message = Kumir::Core::fromUtf8("Введите ")+reference.name();
                message += Kumir::Core::fromAscii("[");
                message += Kumir::Converter::intToString(y);
                message += Kumir::Core::fromAscii(",");
                message += Kumir::Converter::intToString(x);
                message += Kumir::Core::fromAscii("]: ");
                if (readScalarArgument(message, reference.name(), reference.baseType(),  val))
                    reference.setValue(y,x,val);
                else
                    return true;
            }
        }
    }
    else if (reference.dimension()==3) {
        int bounds[7];
        reference.getEffectiveBounds(bounds);
        for (int z=bounds[0]; z<=bounds[1]; z++) {
            for (int y=bounds[2]; y<=bounds[3]; y++) {
                for (int x=bounds[4]; x<=bounds[5]; x++) {
                    VM::AnyValue val;
                    message = Kumir::Core::fromUtf8("Введите ")+reference.name();
                    message += Kumir::Core::fromAscii("[");
                    message += Kumir::Converter::intToString(y);
                    message += Kumir::Core::fromAscii(",");
                    message += Kumir::Converter::intToString(x);
                    message += Kumir::Core::fromAscii("]: ");
                    if (readScalarArgument(message, reference.name(), reference.baseType(),  val))
                        reference.setValue(z,y,x,val);
                    else
                        return true;
                }
            }
        }
    }
    return true;
}

228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332
bool InteractionHandler::makeOutputArgument(const VM::Variable & reference) {
    Kumir::String repr;
    output(reference.name()+Kumir::Core::fromAscii(" = "));
    if (reference.dimension()==0) {
        if (reference.hasValue()) {
            repr = reference.value().toString();
            if (reference.baseType()==Bytecode::VT_string)
                repr = Kumir::Core::fromAscii("\"") + repr + Kumir::Core::fromAscii("\"");
            else if (reference.baseType()==Bytecode::VT_char)
                repr = Kumir::Core::fromAscii("'") + repr + Kumir::Core::fromAscii("'");
        }
        output(repr);
    }
    else if (reference.dimension()==1) {
        int bounds[7];
        reference.getEffectiveBounds(bounds);
        output("{ ");
        for (int x=bounds[0]; x<=bounds[1]; x++) {
            repr.clear();
            if (reference.hasValue(x)) {
                repr = reference.value(x).toString();
                if (reference.baseType()==Bytecode::VT_string)
                    repr = Kumir::Core::fromAscii("\"") + repr + Kumir::Core::fromAscii("\"");
                else if (reference.baseType()==Bytecode::VT_char)
                    repr = Kumir::Core::fromAscii("'") + repr + Kumir::Core::fromAscii("'");
            }
            output(repr);
            if (x<bounds[1]) {
                output(", ");
            }
        }
        output(" }");
    }
    else if (reference.dimension()==2) {
        int bounds[7];
        reference.getEffectiveBounds(bounds);
        output("{ ");
        for (int y=bounds[0]; y<=bounds[1]; y++) {
            output("{ ");
            for (int x=bounds[2]; x<=bounds[3]; x++) {
                repr.clear();
                if (reference.hasValue(y,x)) {
                    repr = reference.value(y,x).toString();
                    if (reference.baseType()==Bytecode::VT_string)
                        repr = Kumir::Core::fromAscii("\"") + repr + Kumir::Core::fromAscii("\"");
                    else if (reference.baseType()==Bytecode::VT_char)
                        repr = Kumir::Core::fromAscii("'") + repr + Kumir::Core::fromAscii("'");
                }
                output(repr);
                if (x<bounds[1]) {
                    output(", ");
                }
            }
            output(" }");
            if (y<bounds[1]) {
                output(", ");
            }
        }
        output(" }");
    }
    else if (reference.dimension()==3) {
        int bounds[7];
        reference.getEffectiveBounds(bounds);
        output("{ ");
        for (int z=bounds[0]; z<=bounds[1]; z++) {
            output("{ ");
            for (int y=bounds[2]; y<=bounds[3]; y++) {
                output("{ ");
                for (int x=bounds[4]; x<=bounds[5]; x++) {
                    repr.clear();
                    if (reference.hasValue(z,y,x)) {
                        repr = reference.value(z,y,x).toString();
                        if (reference.baseType()==Bytecode::VT_string)
                            repr = Kumir::Core::fromAscii("\"") + repr + Kumir::Core::fromAscii("\"");
                        else if (reference.baseType()==Bytecode::VT_char)
                            repr = Kumir::Core::fromAscii("'") + repr + Kumir::Core::fromAscii("'");
                    }
                    output(repr);
                    if (x<bounds[1]) {
                        output(", ");
                    }
                }
                output(" }");
                if (y<bounds[1]) {
                    output(", ");
                }
            }
            output(" }");
            if (z<bounds[1]) {
                output(", ");
            }
        }
        output(" }");
    }
    output("\n");
    return true;
}

void InteractionHandler::output(const Kumir::String &s)
{
    const std::string localstring = Kumir::Coder::encode(LOCALE, s);
    std::cout << localstring;
}


Victor Yacovlev's avatar
Victor Yacovlev committed
333 334
int main(int argc, char *argv[])
{
335
//    sleep(15); // for remote debugger
Victor Yacovlev's avatar
Victor Yacovlev committed
336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357
    // Look at arguments
    std::string programName;
    std::deque<std::string> args;
    bool forceTextForm = false;
    for (int i=1; i<argc; i++) {
        std::string  arg(argv[i]);
        static const std::string minuss("-s");
        static const std::string minusS("-S");
        if (programName.empty()) {
            if (arg==minuss || arg==minusS)
                forceTextForm = true;
            else
                programName = arg;
        }
        else {
            args.push_back(arg);
        }
    }
    if (programName.empty())
        return usage(argv[0]);

    // Load a program
Denis Khachko's avatar
Mac fix  
Denis Khachko committed
358
    std::ifstream programFile(programName.c_str());
Victor Yacovlev's avatar
Victor Yacovlev committed
359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387
    if (!programFile.is_open()) {
        std::cerr << "Can't open program file: " << programName << std::endl;
        return 1;
    }
    const std::string suffix = programName.substr(programName.length()-2);
    bool textForm = suffix=="ks" || forceTextForm;
    Bytecode::Data programData;
    try {
        if (textForm)
            Bytecode::bytecodeFromTextStream(programFile, programData);
        else
            Bytecode::bytecodeFromDataStream(programFile, programData);
    }
    catch (std::string e) {
        std::cerr << "Can't load program file: " << e << std::endl;
        return 2;
    }
    catch (Kumir::String e) {
        std::cerr << "Can't load program file: " << Kumir::Coder::encode(LOCALE, e) << std::endl;
        return 2;
    }
    catch (...) {
        std::cerr << "Can't load program file" << std::endl;
        return 2;
    }
    programFile.close();

    // Prepare runner
    VM::KumirVM vm;
388
    vm.setDebugOff(false);
389 390 391 392

    InteractionHandler interactionHandler(argc, argv);
    vm.setExternalHandler(&interactionHandler);

393 394 395 396 397 398 399 400 401
    Kumir::String programPath = Kumir::Files::getAbsolutePath(Kumir::Coder::decode(LOCALE, programName));
    size_t slashPos = programPath.find_last_of(Kumir::Char('/'));
    Kumir::String programDir;
    if (slashPos!=Kumir::String::npos) {
        programDir = programPath.substr(0, slashPos);
    }

    vm.setProgramDirectory(programDir);

402 403 404 405 406 407 408
    static const Kumir::String LOAD_ERROR = Kumir::Core::fromUtf8("ОШИБКА ЗАГРУЗКИ ПРОГРАММЫ: ");

    try {
        vm.setProgram(programData, true, Kumir::Coder::decode(LOCALE, programName));
    }
    catch (Kumir::String & msg) {
        Kumir::String message = LOAD_ERROR + msg;
409
        return showErrorMessage(message, 11);
410 411 412
    }
    catch (std::string & msg) {
        Kumir::String message = LOAD_ERROR + Kumir::Core::fromAscii(msg);
413
        return showErrorMessage(message, 11);
414 415
    }
    catch (...) {
416 417
        Kumir::String message = LOAD_ERROR;
        return showErrorMessage(message, 11);
418 419
    }

Victor Yacovlev's avatar
Victor Yacovlev committed
420 421
    vm.reset();

422

Victor Yacovlev's avatar
Victor Yacovlev committed
423 424 425
    // Main loop
    while (vm.hasMoreInstructions()) {
        vm.evaluateNextInstruction();
426
        if (vm.error().length()>0) {
Victor Yacovlev's avatar
Victor Yacovlev committed
427
            static const Kumir::String RUNTIME_ERROR = Kumir::Core::fromUtf8("ОШИБКА ВЫПОЛНЕНИЯ: ");
428 429 430 431 432 433 434 435 436 437 438 439
            static const Kumir::String RUNTIME_ERROR_AT = Kumir::Core::fromUtf8("ОШИБКА ВЫПОЛНЕНИЯ В СТРОКЕ ");
            static const Kumir::String COLON = Kumir::Core::fromAscii(": ");
            Kumir::String message;
            if (vm.effectiveLineNo()!=-1) {
                message = RUNTIME_ERROR_AT+
                        Kumir::Converter::sprintfInt(vm.effectiveLineNo()+1,10,0,0)+
                        COLON+
                        vm.error();
            }
            else {
                message = RUNTIME_ERROR + vm.error();
            }
440
            return showErrorMessage(message, 10);
Victor Yacovlev's avatar
Victor Yacovlev committed
441 442 443 444 445
            return 10;
        }
    }
    return 0;
}