main.cpp 17.5 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
#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)
{
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
    using namespace Kumir;

    bool russianLanguage = false;

#if defined(WIN32) || defined(_WIN32)
    russianLanguage = true;
    Char _n = Char('\r\n');
#else
    char * env = getenv("LANG");
    if (env) {
        std::string LANG(env);
        russianLanguage = LANG.find("ru")!=std::string::npos;
    }
    Char _n = Char('\n');
#endif
    String message;
    if (russianLanguage) {
        message  = Core::fromUtf8("Вызов:");
        message.push_back(_n);
        message += Core::fromUtf8("\t")+Core::fromUtf8(std::string(programName));
        message += Core::fromUtf8(" [-ansi] ИМЯФАЙЛА.kod [ПАРАМ1 [ПАРАМ2 ... [ПАРАМn]]]");
        message.push_back(_n);
        message.push_back(_n);
        message += Core::fromUtf8("\t-ansi\t\tИспользовть кодировку 1251 вместо 866 в терминале (только для Windows)");
        message.push_back(_n);
        message += Core::fromUtf8("\tИМЯФАЙЛА.kod\tИмя выполнеяемой программы)");
        message.push_back(_n);
        message += Core::fromUtf8("\tПАРАМ1...ПАРАМn\tАргументы главного алгоритма Кумир-программы");
        message.push_back(_n);
    }
    else {
        message  = Core::fromUtf8("Usage:");
        message.push_back(_n);
        message += Core::fromUtf8("\t")+Core::fromUtf8(std::string(programName));
        message += Core::fromUtf8(" [-ansi] FILENAME.kod [ARG1 [ARG2 ... [ARGn]]]");
        message.push_back(_n);
        message.push_back(_n);
        message += Core::fromUtf8("\t-ansi\t\tUse codepage 1251 instead of 866 in console (Windows only)");
        message.push_back(_n);
        message += Core::fromUtf8("\tFILENAME.kod\tKumir runtime file name)");
        message.push_back(_n);
        message += Core::fromUtf8("\tARG1...ARGn\tKumir program main algorithm arguments");
        message.push_back(_n);
    }
    std::cerr << Coder::encode(LOCALE, message);
Victor Yacovlev's avatar
Victor Yacovlev committed
61 62 63
    return 127;
}

64 65 66 67 68 69
class InteractionHandler
        : public VM::AbstractInteractionHandler
{
public:
    explicit InteractionHandler(int argc, char *argv[]);
    bool makeInputArgument(VM::Variable & reference);
70
    bool makeOutputArgument(const VM::Variable & reference);
71
private:
72 73
    void output(const Kumir::String & s);
    inline void output(const std::string & s) { output(Kumir::Core::fromAscii(s)); }
74 75 76 77 78 79 80 81 82 83 84
    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]);
85 86
        if (arg.length()==0)
            continue;
87 88 89 90 91 92 93 94 95 96 97 98 99
        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));
        }
    }
}

100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
#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;
}

132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154
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;
    }
}

155 156 157 158 159 160 161 162
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) {
163
        Kumir::String query_string = decodeHttpStringValue(std::string(QUERY_STRING));
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 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
        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;
}

270
bool InteractionHandler::makeOutputArgument(const VM::Variable & reference) {
271 272
    if (!reference.isValid())
        return true;
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 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376
    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
377 378
int main(int argc, char *argv[])
{
379
//    sleep(15); // for remote debugger
Victor Yacovlev's avatar
Victor Yacovlev committed
380 381 382 383 384 385
    // 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]);
386 387
        if (arg.length()==0)
            continue;
Victor Yacovlev's avatar
Victor Yacovlev committed
388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403
        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
404
    std::ifstream programFile(programName.c_str(), std::ios::in|std::ios::binary);
Victor Yacovlev's avatar
Victor Yacovlev committed
405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433
    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;
434
    vm.setDebugOff(false);
435 436 437 438

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

439 440 441 442 443 444 445 446 447
    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);

448 449 450 451 452 453 454
    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;
455
        return showErrorMessage(message, 11);
456 457 458
    }
    catch (std::string & msg) {
        Kumir::String message = LOAD_ERROR + Kumir::Core::fromAscii(msg);
459
        return showErrorMessage(message, 11);
460 461
    }
    catch (...) {
462 463
        Kumir::String message = LOAD_ERROR;
        return showErrorMessage(message, 11);
464 465
    }

Victor Yacovlev's avatar
Victor Yacovlev committed
466 467
    vm.reset();

468

Victor Yacovlev's avatar
Victor Yacovlev committed
469 470 471
    // Main loop
    while (vm.hasMoreInstructions()) {
        vm.evaluateNextInstruction();
472
        if (vm.error().length()>0) {
Victor Yacovlev's avatar
Victor Yacovlev committed
473
            static const Kumir::String RUNTIME_ERROR = Kumir::Core::fromUtf8("ОШИБКА ВЫПОЛНЕНИЯ: ");
474 475 476 477 478 479 480 481 482 483 484 485
            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();
            }
486
            return showErrorMessage(message, 10);
Victor Yacovlev's avatar
Victor Yacovlev committed
487 488 489 490 491
            return 10;
        }
    }
    return 0;
}