pdautomata.cpp 64.9 KB
Newer Older
victor's avatar
 
victor committed
1 2
#include "pdautomata.h"
#include "pdautomata_p.h"
victor's avatar
 
victor committed
3
#include "dataformats/ast.h"
victor's avatar
 
victor committed
4
#include "interfaces/lexemtype.h"
victor's avatar
 
victor committed
5
#include "errormessages/errormessages.h"
victor's avatar
 
victor committed
6 7 8 9 10

#define isTerminal(x) QRegExp(QString::fromUtf8("[a-z|а-я][a-z|а-я|_]*")).exactMatch(x)
#define isNeterminal(x) QRegExp(QString::fromUtf8("[А-Я|A-Z][А-Я|A-Z|1-9|_*]*")).exactMatch(x)
#define isNagruzka(x) ( x.startsWith("{") && x.endsWith("}") )

victor's avatar
 
victor committed
11 12
#define MAXIMUM_ERRORS_COUNT 20

victor's avatar
 
victor committed
13 14
namespace KumirAnalizer {

victor's avatar
 
victor committed
15 16 17 18 19 20 21 22
AST::Module * moduleOfAlgorhitm(AST::Data * data, AST::Algorhitm * alg) {
    foreach (AST::Module * mod, data->modules) {
        if (mod->impl.algorhitms.contains(alg)) {
            return mod;
        }
    }
    return 0;
}
victor's avatar
 
victor committed
23

victor's avatar
 
victor committed
24 25 26 27
void prepareRules(const QStringList &files, QString &out, const QList<int> &priors);
QString terminalByCode(int code);
bool isCorrectTerminal(const QString &terminal);

28 29 30 31 32
PDAutomata::~PDAutomata()
{
    delete d;
}

victor's avatar
 
victor committed
33 34 35 36 37
PDAutomata::PDAutomata(QObject *parent) :
    QObject(parent)
{
    d = new PDAutomataPrivate();
    d->q = this;
victor's avatar
 
victor committed
38
    QString rulesPath = qApp->property("sharePath").toString()+"/kumiranalizer/"; // TODO set me
victor's avatar
 
victor committed
39 40 41
    d->loadRules(rulesPath);
}

victor's avatar
 
victor committed
42
void PDAutomata::init(bool teacherMode, const QList<Statement*> & statements, AST::Data *ast, AST::Algorhitm * algorhitm)
victor's avatar
 
victor committed
43
{
victor's avatar
 
victor committed
44
    d->teacherMode = teacherMode;
victor's avatar
 
victor committed
45
    static Statement * begin = new Statement(LexemType(0xFFFFFFFF));
victor's avatar
 
victor committed
46 47 48 49 50 51
    d->source.clear();
    d->source << begin;
    foreach (Statement * st, statements) {
        if (st->type!=LxTypeComment)
            d->source << st;
    }
victor's avatar
 
victor committed
52 53 54
    d->ast = ast;
    d->algorhitm = algorhitm;
    if (!algorhitm) {
victor's avatar
 
victor committed
55
        QList<AST::Module*>::iterator it = d->ast->modules.begin();
victor's avatar
 
victor committed
56
        AST::ModuleType moduleToRemove = teacherMode? AST::ModTypeHidden : AST::ModTypeUser;
victor's avatar
 
victor committed
57
        while (it!=d->ast->modules.end()) {
victor's avatar
 
victor committed
58
            if ( (*it)->header.type == moduleToRemove ) {
59 60
                AST::Module * module = (*it);
                delete module;
victor's avatar
 
victor committed
61 62 63 64 65 66
                it = d->ast->modules.erase(it);
            }
            else {
                it++;
            }
        }
67 68 69
        foreach (Statement * st, statements) {
            st->statement = 0;
        }
victor's avatar
 
victor committed
70 71
    }
    else {
victor's avatar
 
victor committed
72 73 74
        algorhitm->impl.pre.clear();
        algorhitm->impl.post.clear();
        algorhitm->impl.body.clear();
victor's avatar
 
victor committed
75 76
        algorhitm->impl.locals.clear();
        algorhitm->header.arguments.clear();
victor's avatar
 
victor committed
77 78 79
    }

    d->errorsCount = 0;
victor's avatar
 
victor committed
80 81
    for (int i=0; i<statements.size(); i++) {
        statements[i]->indentRank = QPoint(0,0);
victor's avatar
 
victor committed
82
    }
victor's avatar
 
victor committed
83 84 85 86 87 88 89 90
    d->currentPosition = 0;
    d->stack.clear();
    d->clearDataHistory();
    PDStackElem start;
    start.nonTerminal = "START";
    start.iterateStart = 0;
    start.priority = 0;
    d->stack.push(start);
victor's avatar
 
victor committed
91 92 93
    d->scripts = QVector< ScriptListPtr > (d->source.size()+2, NULL);
    d->fixedScripts = QVector< ScriptListPtr > (d->source.size()+2, NULL);
    d->nextPointers = QVector<int>(d->source.size());
victor's avatar
 
victor committed
94 95 96
    for (int i=0; i<d->nextPointers.size(); i++) {
        d->nextPointers[i] = i+1;
    }
victor's avatar
 
victor committed
97
    d->allowSkipParts = d->source.size() >= MAXIMUM_ERRORS_COUNT;
victor's avatar
 
victor committed
98 99
}

100 101 102 103 104 105 106 107 108 109 110 111 112
PDAutomataPrivate::~PDAutomataPrivate()
{
    const QStringList keys = matrix.keys();
    foreach ( const QString & key, keys ) {
        Rules rules = matrix[key];
        for (int i=0; i<rules.size(); i++) {
            RuleRightPart right = rules[i];
            if (right.script)
                delete right.script;
        }
    }
}

victor's avatar
 
victor committed
113
void PDAutomataPrivate::matchScript(const QString &text, ScriptListPtr & scripts)
victor's avatar
 
victor committed
114
{
victor's avatar
 
victor committed
115 116 117 118
    scripts = new QList<Script>;
    if (text.isEmpty()) {
        return;
    }
victor's avatar
 
victor committed
119 120
    QStringList statements = text.split(";");
    foreach (QString s, statements) {
victor's avatar
 
victor committed
121 122
        if (s.trimmed().isEmpty())
            continue;
victor's avatar
 
victor committed
123 124
        Script script;
        s = s.simplified();
victor's avatar
 
victor committed
125
        script.source = s;
victor's avatar
 
victor committed
126 127 128 129 130
        int op_br = s.indexOf("(");
        int cl_br = s.lastIndexOf(")");
        Q_ASSERT(op_br!=-1);
        Q_ASSERT(cl_br!=-1);
        const QString name = s.left(op_br).trimmed();
victor's avatar
 
victor committed
131 132 133 134
        const QString argline = s.mid(op_br+1, cl_br-op_br-1);
        QStringList args;
        if (!argline.isEmpty())
            args = argline.split(",");
victor's avatar
 
victor committed
135 136 137 138 139 140
        bool found = false;
        for (int i=0; i<metaObject()->methodCount(); i++) {
            QMetaMethod m = metaObject()->method(i);
            QString m_signature = m.signature();
            int spacePos = m_signature.indexOf(" ");
            int brPos = m_signature.indexOf("(");
victor's avatar
 
victor committed
141
            QString m_name = m_signature.mid(spacePos+1, brPos);
victor's avatar
 
victor committed
142 143 144 145 146 147 148 149 150
            if (name==m_name) {
                found = true;
                script.method = m;
                Q_ASSERT(args.size()==m.parameterTypes().size());
                break;
            }
        }
        Q_ASSERT(found);
        for (int i=0; i<args.size(); i++) {
victor's avatar
 
victor committed
151 152 153 154 155 156 157 158
            QString arg = args[i];
            if (arg.startsWith("\"")) {
                arg.remove("\"");
                script.arguments << QVariant(arg);
            }
            else {
                script.arguments << QVariant(arg.toInt());
            }
victor's avatar
 
victor committed
159
        }
victor's avatar
 
victor committed
160
        scripts->append(script);
victor's avatar
 
victor committed
161 162 163 164 165 166
    }
}

void PDAutomataPrivate::loadRules(const QString &rulesRoot)
{
    QDir rulesDir(rulesRoot);
victor's avatar
 
victor committed
167
    QStringList rulesFileList = rulesDir.entryList(QStringList() << "*.rules");
victor's avatar
 
victor committed
168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184
    QString normalizedRules;
    QList<int> priorities;
    for (int i=0; i<rulesFileList.count(); i++) {
        QString absName = rulesDir.absoluteFilePath(rulesFileList[i]);
        rulesFileList[i] = absName;
        priorities << i;
    }
    prepareRules(rulesFileList, normalizedRules, priorities);

    QStringList lines = normalizedRules.split("\n");

    QString leftPart;
    QString rightPart;
    QString script;
    QString terminal;

    int lineNo = 0;
victor's avatar
 
victor committed
185
    maxPriorityValue = 0;
victor's avatar
 
victor committed
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
    foreach ( QString line, lines ) {
        lineNo ++;
        // Обработка комментария
        if ( line.trimmed().startsWith("#") || line.trimmed().isEmpty() )
            continue;

        // Выделение приоритета
        QString prior_s;

        int bracket_p = line.lastIndexOf("[");
        if ( bracket_p == -1 ) {
            return; // ошибка: нет приоритета
        }
        else {
            prior_s = line.mid(bracket_p);
            line = line.left(bracket_p).trimmed();
        }

        prior_s = prior_s.remove("[").remove("]").trimmed();
        bool ok;
        int prior = prior_s.toInt(&ok);
        if ( ! ok )
            return; // ошибка: приоритет -- не целое число
        // Выделение левой части
        int arrow_p = line.indexOf("->");
        if ( arrow_p == -1 )
            return; // ошибка: неправильный формат правила
        leftPart = line.left(arrow_p).trimmed();
        if ( leftPart.isEmpty() ) {
            return; // ошибка: пустая левая часть
        }
        // Выделение правой части и скрипта
        rightPart = line.mid(arrow_p+2).trimmed();
        int script_p = rightPart.indexOf(":");
        if ( script_p != -1 ) {
            script = rightPart.mid(script_p+1).trimmed();
            rightPart = rightPart.left(script_p).trimmed();
        }
        else {
            script = ""; // очистка, т.к. могло что-то остаться от пред. строки
        }
        // Выделение терминала в правой части
        int space_p = rightPart.indexOf(' ');
        if ( space_p == -1 ) {
            if ( rightPart.startsWith("0") ) {
                // Правило \epsilon
                terminal = "";
                rightPart = "";
            }
            else {
                bool isCorrect = true;
                for ( int j=0; j<terminal.length(); j++ ) {
                    if (!( terminal[j]=='_' || ( terminal[j].isLetter() && terminal[j].isLower() ) )) {
                        isCorrect = false;
                        break;
                    }
                }
                if ( isCorrect ) {
                    terminal = rightPart;
                    rightPart = "";
                }
                else
                    return ; // ошибка: всего один ксимвол в правой части (не \epsilon и не терминал)
            }
        }
        else {
            terminal = rightPart.left(space_p);
            bool isCorrect = true;
            for ( int j=0; j<terminal.length(); j++ ) {
                if (!( terminal[j]=='_' || ( terminal[j].isLetter() && terminal[j].isLower() ) )) {
                    isCorrect = false;
                    break;
                }
            }
            if ( !isCorrect )
                return ; // ошибка: первый ксимвол в правой части -- нетерминал
            rightPart = rightPart.mid(space_p+1).trimmed();
        }
victor's avatar
 
victor committed
264
        maxPriorityValue = qMax(maxPriorityValue, prior);
victor's avatar
 
victor committed
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

        // Добавляем в таблицу правил
        if ( terminal.isEmpty() ) {
            LexemType allLines[] = {
                LxTypeEmpty,
                LxTypeDoc,
                LxNameClass,
                LxPriModule,
                LxPriEndModule,
                LxPriAlgHeader,
                LxPriAlgBegin,
                LxPriAlgEnd,
                LxPriPre,
                LxPriPost,
                LxPriIf,
                LxPriThen,
                LxPriElse,
                LxPriFi,
                LxPriSwitch,
                LxPriCase,
                LxPriLoop,
                LxPriEndLoop,
                LxPriInput,
                LxPriOutput,
                LxPriAssign,
                LxPriAssert,
                LxPriImport,
                LxPriExit,
victor's avatar
 
victor committed
293 294
                LxPriPause,
                LxPriExit,
Victor Yacovlev's avatar
Victor Yacovlev committed
295

victor's avatar
 
victor committed
296 297 298 299 300 301 302 303 304 305 306 307 308 309 310
                LexemType(0xFFFFFFFF)
            };

            int j = 0;
            do {
                QString key;
                RuleRightPart rule;
                if ( allLines[j] != 0 )
                    key = terminalByCode(allLines[j]) + "/" + leftPart;
                else
                    key = "end/" + leftPart;
                Q_ASSERT ( ! key.startsWith("/") );
                rule.nonTerminals = QStringList();
                rule.isEpsilon = true;
                rule.priority = prior;
victor's avatar
 
victor committed
311
                matchScript(script.mid(1, script.length()-2), rule.script);
victor's avatar
 
victor committed
312 313 314 315 316 317 318 319 320 321 322 323 324
                if ( matrix.contains(key) ) {
                    // Добавляем \epsilon-правило только если нет других правил
                    // c тем же приоритетом
                    bool allowToAdd = true;
                    Rules rulesList = matrix[key];
                    foreach ( RuleRightPart rule, rulesList ) {
                        if ( rule.priority == prior ) {
                            allowToAdd = false;
                            break;
                        }
                    }
                    if ( allowToAdd )
                        matrix[key].append(rule);
325 326
                    else
                        delete rule.script;
victor's avatar
 
victor committed
327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344
                }
                else {
                    Rules newRulesList;
                    newRulesList.append(rule);
                    matrix[key] = newRulesList;
                }
                j++;
            } while ( allLines[j] != 0xFFFFFFFF );
        }
        else {
            // Случай обычного правила
            QString key;
            Q_ASSERT( isCorrectTerminal(terminal) );
            key = terminal + "/" + leftPart;
            RuleRightPart rule;
            rule.nonTerminals = rightPart.isEmpty()? QStringList() : rightPart.split(" ");
            rule.isEpsilon = false;
            rule.priority = prior;
victor's avatar
 
victor committed
345
            matchScript(script.mid(1, script.length()-2), rule.script);
victor's avatar
 
victor committed
346 347 348 349 350
            if ( matrix.contains(key) ) {
                matrix[key].append(rule);
                // Удаляем \epsilon-правило, если оно там есть
                // и имеет тот же приоритет
                for ( int j=matrix[key].count()-1; j>=0; j-- ) {
351 352
                    if ( matrix[key][j].isEpsilon && matrix[key][j].priority==prior ) {
                        delete matrix[key][j].script;
victor's avatar
 
victor committed
353
                        matrix[key].removeAt(j);
354
                    }
victor's avatar
 
victor committed
355 356 357 358 359 360 361 362 363
                }
            }
            else {
                Rules newRulesList;
                newRulesList.append(rule);
                matrix[key] = newRulesList;
            }
        }
    }
victor's avatar
 
victor committed
364
//    qDebug() << "fff";
victor's avatar
 
victor committed
365 366 367 368 369
    foreach ( QString key, matrix.keys() ) {
        Rules rulesList = matrix[key];
        qSort(rulesList);
        matrix[key] = rulesList;
    }
victor's avatar
 
victor committed
370
//    qDebug() << "End load rules";
victor's avatar
 
victor committed
371 372
}

victor's avatar
 
victor committed
373 374 375
int PDAutomata::process()
{
    if ( d->stack.isEmpty() ) {
victor's avatar
 
victor committed
376
        if ( d->currentPosition == d->source.count() )
victor's avatar
 
victor committed
377 378 379 380 381 382 383 384 385 386 387 388
            return 0;
        else
            return 1;
    }
    do {
        if (d->errorsCount>MAXIMUM_ERRORS_COUNT) {
            d->setTooManyErrors();
            return 0;
        }
        PDStackElem currentStackElem = d->stack.pop();
        QString currentTerminal;
        QString key;
victor's avatar
 
victor committed
389
        if ( d->currentPosition > d->source.count() )
victor's avatar
 
victor committed
390
            break;
victor's avatar
 
victor committed
391 392
        if ( d->currentPosition < d->source.count() && d->currentPosition >= 0 ) {
            const Statement * st = d->source[d->currentPosition];
victor's avatar
 
victor committed
393
            currentTerminal = terminalByCode(st->type);
victor's avatar
 
victor committed
394 395 396 397 398 399 400 401 402 403 404 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 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477
        }
        else {
            currentTerminal = "end";
        }
        key = currentTerminal + "/" + currentStackElem.nonTerminal;
        if ( d->matrix.contains(key) ) {
            Rules rulesList = d->matrix[key];

            if ( rulesList.count() == 1 ) {
                // Линейный случай, когда паре {ТЕРМИНАЛ,НЕТЕРМИНАЛ}
                // соответствует только одно правило
                RuleRightPart rule = rulesList[0];

                if ( !rule.isEpsilon && d->currentPosition>=0 )
                    d->scripts[d->currentPosition] = rule.script;
                // Если левая часть правила итеративная (*), то помещаем её обратно в стек
                if ( !rule.isEpsilon && currentStackElem.nonTerminal.endsWith("*") ) {
                    PDStackElem backElem = currentStackElem;
                    backElem.priority = rule.priority;
                    d->stack.push(backElem);
                }
                PDStackElem cse;
                for ( int j=rule.nonTerminals.count()-1; j>=0; j-- ) {
                    cse.nonTerminal = rule.nonTerminals[j];
                    cse.iterateStart = d->currentPosition;
                    cse.priority = rule.priority;
                    d->stack.push(cse);
                }
                // Если отрабатываем правило вида: ИТЕРАТИВНЫЙ_НЕТЕРМИНАЛ* -> 0,
                // то устанавливаем соответствующий next-указатель
                if ( rule.isEpsilon && currentStackElem.nonTerminal.endsWith("*") && currentTerminal!="end")
                    d->finalizeIterativeRule(currentStackElem);
                if ( !rule.isEpsilon && !key.startsWith("end/") )
                    d->nextStep();
            }
            else {
                // Разветвление. Сохраняем состояние и пытаемся применять
                // правила до тех пор, пока одно из них не будет успешным
                uint success = 0;

                // 				int errorsBefore = m_errorWayCounter;
                for ( int i=0; i<rulesList.count(); i++ )  {
                    d->saveData();
                    RuleRightPart rule = rulesList[i];

                    if ( !rule.isEpsilon && d->currentPosition>=0 )
                        d->scripts[d->currentPosition] = rule.script;
                    // Если левая часть правила итеративная (*), то помещаем её обратно в стек
                    if ( !rule.isEpsilon && currentStackElem.nonTerminal.endsWith("*") ) {
                        PDStackElem backElem = currentStackElem;
                        backElem.priority = rule.priority;
                        d->stack.push(backElem);
                    }
                    PDStackElem cse;
                    for ( int j=rule.nonTerminals.count()-1; j>=0; j-- ) {
                        cse.nonTerminal = rule.nonTerminals[j];
                        cse.iterateStart = d->currentPosition;
                        cse.priority = rule.priority;
                        d->stack.push(cse);
                    }
                    // Если отрабатываем правило вида: ИТЕРАТИВНЫЙ_НЕТЕРМИНАЛ* -> 0,
                    // то устанавливаем соответствующий next-указатель
                    if ( rule.isEpsilon && currentStackElem.nonTerminal.endsWith("*") && currentTerminal!="end")
                        d->finalizeIterativeRule(currentStackElem);
                    if ( !rule.isEpsilon && !key.startsWith("end/") )
                        d->nextStep();
                    success = process();
                    if ( success == 0 ) {
                        d->popHistory();
                        break;
                    }
                    if ( success == 1 ) {
                        d->restoreData();
                    }
                }
                if ( success != 0 ) {
                    break;
                }
            }
        }
        else {
            return 1;
        }
    } while ( !d->stack.isEmpty() );
victor's avatar
 
victor committed
478
    bool hasEnd = (d->currentPosition) == (d->source.count());
victor's avatar
 
victor committed
479 480 481 482 483 484

    return ( d->stack.isEmpty() && hasEnd ) ? 0 : 1;
}



victor's avatar
 
victor committed
485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569
void prepareRules(const QStringList &files, QString &out, const QList<int> &priors)
{
    int iskNet = 0;

    if (files.isEmpty())
    {
        qDebug()<<QString::fromUtf8("Нет .rules-файлов");
        return;
    }

    QBuffer filIn1;
    filIn1.open(QIODevice::WriteOnly);

    QTextStream sIn1(&filIn1);
    sIn1.setCodec("UTF-8");


    int fileNum = -1;
    foreach ( QString ifn, files ) {

        ++fileNum;
        QFile filIn(ifn);

        filIn.open(QIODevice::ReadOnly);

        QTextStream sIn(&filIn);
        sIn.setCodec("UTF-8");


        for( ; !sIn.atEnd() ; )
        {
            QString str(sIn.readLine().trimmed());
            int openFig = 0;
            int i = 0;
            do
            {
                for( ; i<str.length(); ++i)
                {
                    if (str.at(i)=='{') ++openFig;
                    if (str.at(i)=='}') --openFig;
                }
                if (openFig==0)
                {
                    if (!str.startsWith("#") && !str.isEmpty())
                    {
                        sIn1 << str << " [" << priors[fileNum] << "]\n";
                    }
                    break;
                }
                else
                {
                    if (!sIn.atEnd())
                    {
                        str += sIn.readLine();
                    }
                    else
                    {
                        sIn1 << "Syntax error in {}:\n";
                        sIn1 << str << endl;
                        return;
                    }
                }
            } while (true);
        }
        filIn.close();
    }

    filIn1.close();

    QBuffer filIn;
    filIn.setData(filIn1.data());
    filIn.open(QIODevice::ReadOnly);
    QTextStream sIn(&filIn);
    sIn.setCodec("UTF-8");


    QStringList pravila1;
    for( ; !sIn.atEnd() ; )
    {
        QString str(sIn.readLine().trimmed());
        int i = str.indexOf('#');
        if (i!=-1)
        {
            str.truncate(i);
        }
570
        str = str.trimmed();
victor's avatar
 
victor committed
571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713
        if (!str.isEmpty())
        {
            pravila1 << str;
        }
    }

    pravila1.sort();


    QStringList nagruzki1;
    QList<int> priorities;
    for(int i=0; i<pravila1.size(); ++i)
    {
        QString str = pravila1[i];
        int d = str.indexOf(':');
        int d1 = str.lastIndexOf(':');
        if (d!=d1)
        {
            qDebug()<<QString::fromUtf8("Два двоеточия в строке: ")<<str<<endl;
            return;
        }
        int e = str.lastIndexOf('[');
        if (e==-1)
        {
            qDebug()<<QString::fromUtf8("Не задан приоритет строки: ")<<str<<endl;
            return;
        }
        if (d!=-1)
        {
            nagruzki1 << str.mid(d+1, e-d-1);
            pravila1[i].truncate(d);
        }
        else
        {
            nagruzki1 << QString();
            pravila1[i].truncate(e);
        }
        QString p(str.mid(e).trimmed());
        if (!p.startsWith("[") && !p.endsWith("]"))
        {
            qDebug()<<QString::fromUtf8("Ошибка задания приоритета в строке: ")<<str<<endl;
            return;
        }
        priorities << p.mid(1,p.length()-2).toInt();
    }

    QList<QStringList> pravila;
    foreach(QString s, pravila1)
    {
        pravila << s.split(QRegExp("\\s+"), QString::SkipEmptyParts);
        if (!isNeterminal(pravila.last()[0]) || pravila.last()[1]!="->" || pravila.last().count()<3)
        {
            qDebug()<<QString::fromUtf8("Ошибка в левой части: ")<<pravila.last().join(" ")<<endl;
            return;
        }
    }

    for(int i=0; i<nagruzki1.size(); ++i)
    {
        if (nagruzki1[i].isEmpty())
        {
            for(int j=0; j<pravila[i].size(); ++j)
            {
                if (isTerminal(pravila[i][j]))
                    nagruzki1[i] += "{}";
            }
        }
    }

    QList<QStringList> nagruzki;
    int ind = 0;
    foreach(QString s, nagruzki1)
    {
        QStringList rez;
        int countNagr = 0;
        int i, j;
        for(i=0; i<s.length()-1; )
        {
            j = i+1;
            int openFig = 0;
            if (s.at(i)=='{')
            {
                openFig = 1;
                for( ; j<s.length(); ++j)
                {
                    if (s.at(j)=='{') ++openFig;
                    if (s.at(j)=='}') --openFig;
                    if (openFig==0) break;
                }
                rez << s.mid(i,j-i+1);
                ++countNagr;
            }
            i=j;
        }
        int countTerm = 0;
        foreach(QString str, pravila[ind])
        {
            if (isTerminal(str))
                ++countTerm;
        }
        if (countTerm != countNagr)
        {
            qDebug() << QString::fromUtf8("Не совпадает число терминалов и нагрузок: ") << pravila[ind].join(" ") << " : " << s;
            return;
        }
        nagruzki << rez;
        ++ind;
    }

    int c;


    QStringList sorts;

    for(bool flag = true ; flag ;)
    {
        QString s;
        for(int i=0; i<pravila.size(); ++i)
        {
            s += pravila[i][0];
            s += " ";
            s += pravila[i][2];
            s += " ; ";
        }
        if (sorts.indexOf(s)!=-1)
        {
            qDebug() << QString::fromUtf8("Данная грамматика является леворекурсивной\n");
            return;
        }
        else
        {
            sorts << s;
        }
        flag = false;
        for(int i=1; i<pravila.size(); ++i)
        {
            for(int j=0; j<i; ++j)
            {
                if (isNeterminal(pravila[i][2]) && pravila[i][2]==pravila[j][0])
                {
                    QString s1(pravila[j][0]);
                    QString s2(pravila[i][0]);

victor's avatar
 
victor committed
714
                    int k1 = 0, k2 = 0;
victor's avatar
 
victor committed
715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842
                    for(int k = pravila.size()-1; k>=0; --k)
                    {
                        if (pravila[k][0]==s1)
                            k1 = k;
                        if (pravila[k][0]==s2)
                            k2 = k;
                    }
                    for(int shift = 0 ; pravila[k2+shift][0]==s2 ; ++shift)
                    {
                        pravila.move(k2+shift,k1+shift);
                        nagruzki.move(k2+shift,k1+shift);
                        priorities.move(k2+shift,k1+shift);
                    }
                    flag = true;
                }
            }
        }
    }



    for(int i=pravila.size()-1; i>=0; --i)
    {
        QList<QStringList> add;
        QList<QStringList> addNagr;
        QList<int> addPriors;
        for(int j=i+1; j<pravila.size(); ++j)
        {
            if (pravila[j][0]==pravila[i][2] && (isTerminal(pravila[j][2]) || isNeterminal(pravila[j][2])))
            {
                QStringList sl;
                sl << pravila[i][0] << "->" << pravila[j].mid(2, pravila[j].size()-2) << pravila[i].mid(3, pravila[i].size()-3);
                add << sl;
                sl.clear();
                sl << nagruzki[j] << nagruzki[i];
                addNagr << sl;
                int a = priorities[i];
                int b = priorities[j];
                addPriors << (a>b ? a:b);
            }
        }
        for(int j=0; j<add.size(); ++j)
        {
            pravila.insert(i+j+1, add[j]);
            nagruzki.insert(i+j+1, addNagr[j]);
            priorities.insert(i+j+1, addPriors[j]);
        }
        if (add.size()>0)
        {
            pravila.removeAt(i);
            nagruzki.removeAt(i);
            priorities.removeAt(i);
        }
    }


    for(int i=pravila.size()-1; i>=0; --i)
    {
        QList<int> nirps;
        for(int j=2; j<pravila[i].size(); ++j)
            if (isTerminal(pravila[i][j]))
                nirps << j;
        if (nirps.size()>1)
        {
            nirps << pravila[i].size();
            QList<QStringList> add;
            QList<QStringList> addNagr;
            QList<int> addPriors;
            bool flag = false;
            for(int j=0; j<nirps.size()-1; ++j)
            {
                QStringList sl;
                QStringList slNagr;
                if (!flag)
                {
                    sl << pravila[i][0];
                    flag = true;
                }
                else
                    sl << QString::number(iskNet);
                sl << "->" << pravila[i].mid(nirps[j], nirps[j+1]-nirps[j]);
                slNagr << nagruzki[i][j];
                if (j<nirps.size()-2)
                {
                    ++iskNet;
                    sl << QString::number(iskNet);
                }
                add << sl;
                addNagr << slNagr;
                addPriors << priorities[i];
            }
            for(int j=0; j<add.size(); ++j)
            {
                pravila.insert(i+j+1, add[j]);
                nagruzki.insert(i+j+1, addNagr[j]);
                priorities.insert(i+j+1, addPriors[j]);
            }
            if (add.size()>0)
            {
                pravila.removeAt(i);
                nagruzki.removeAt(i);
                priorities.removeAt(i);
            }
        }
    }


    for(c=0; c<pravila.size(); ++c)
    {
        QStringList sl(pravila[c]);
        QString pravilo( sl.join(" ") );
        QString nagruzka( nagruzki[c].join(" ") );
        int priority = priorities[c];
        for(int j=c+1; j<pravila.size(); )
        {
            QString pravilo1( pravila[j].join(" ") );
            QString nagruzka1( nagruzki[j].join(" ") );
            int priority1 = priorities[j];
            if (pravilo==pravilo1)
            {
                if (nagruzka==nagruzka1 && priority==priority1)
                {
                    pravila.removeAt(j);
                    nagruzki.removeAt(j);
                    priorities.removeAt(j);
                }
                else
                {
victor's avatar
 
victor committed
843 844 845
//                    qDebug() << "Dva pravila s raznoj nagruzkoj ili raznymi prioritetami:";
//                    qDebug() << pravilo << " : " << nagruzka << " [" << priority << "]";
//                    qDebug() << pravilo1 << " : " << nagruzka1 << " [" << priority1 << "]";
victor's avatar
 
victor committed
846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880
                    ++j;
                }
            }
            else
            {
                ++j;
            }
        }
    }

    c = 0;
    foreach(QStringList sl, pravila)
    {
        foreach(QString s, sl)
        {
            out += s + " ";
        }
        if (!nagruzki[c].isEmpty())
        {
            out += ":";
        }
        foreach(QString s, nagruzki[c])
        {
            out += " " + s;
        }
        out += QString(" [") + QString::number(priorities[c]) + "]\n";
        ++c;
    }
    out += "\n";
}

QString terminalByCode(int code)
{
    switch ( code ) {
    case LxNameClass:
victor's avatar
 
victor committed
881
        return QString::fromUtf8("простое_предложение");
victor's avatar
 
victor committed
882 883 884 885 886 887 888 889 890 891 892 893 894
    case LxPriAlgHeader:
        return QString::fromUtf8("алг");
    case LxPriAlgBegin:
        return QString::fromUtf8("нач");
    case LxPriAlgEnd:
        return QString::fromUtf8("кон");
    case LxPriLoop:
        return QString::fromUtf8("нц");
    case LxPriEndLoop:
        return QString::fromUtf8("кц");
    case LxPriElse:
        return QString::fromUtf8("иначе");
    case LxPriExit:
victor's avatar
 
victor committed
895
        return QString::fromUtf8("простое_предложение");
victor's avatar
 
victor committed
896 897 898 899 900 901 902 903 904 905 906
    case LxPriIf:
        return QString::fromUtf8("если");
    case LxPriThen:
        return QString::fromUtf8("то");
    case LxPriFi:
        return QString::fromUtf8("все");
    case LxPriSwitch:
        return QString::fromUtf8("выбор");
    case LxPriCase:
        return QString::fromUtf8("при");
    case LxPriAssign:
victor's avatar
 
victor committed
907
        return QString::fromUtf8("простое_предложение");
victor's avatar
 
victor committed
908
    case LxPriOutput:
victor's avatar
 
victor committed
909
        return QString::fromUtf8("простое_предложение");
victor's avatar
 
victor committed
910
    case LxPriAssert:
victor's avatar
 
victor committed
911
        return QString::fromUtf8("простое_предложение");
victor's avatar
 
victor committed
912
    case LxPriPre:
victor's avatar
 
victor committed
913
        return QString::fromUtf8("ограничение_алгоритма");
victor's avatar
 
victor committed
914
    case LxPriPost:
victor's avatar
 
victor committed
915
        return QString::fromUtf8("ограничение_алгоритма");
victor's avatar
 
victor committed
916
    case LxPriInput:
victor's avatar
 
victor committed
917
        return QString::fromUtf8("простое_предложение");
victor's avatar
 
victor committed
918 919 920 921 922 923
    case LxPriModule:
        return QString::fromUtf8("исп");
    case LxPriEndModule:
        return QString::fromUtf8("кон_исп");
    case LxPriImport:
        return QString::fromUtf8("использовать");
victor's avatar
 
victor committed
924 925 926 927
    case LxPriPause:
        return QString::fromUtf8("простое_предложение");
    case LxPriHalt:
        return QString::fromUtf8("простое_предложение");
victor's avatar
 
victor committed
928 929 930 931 932 933 934 935 936 937 938 939
    case LxTypeDoc:
        return QString::fromUtf8("строка_документации");
    case LexemType(0xFFFFFFFF):
        return "begin";
    default:
        return QString(" ");
    }
}

bool isCorrectTerminal(const QString &terminal)
{
    if (
victor's avatar
 
victor committed
940
            terminal == QString::fromUtf8("простое_предложение")
victor's avatar
 
victor committed
941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963
            ||
            terminal == QString::fromUtf8("алг")
            ||
            terminal == QString::fromUtf8("нач")
            ||
            terminal == QString::fromUtf8("кон")
            ||
            terminal == QString::fromUtf8("нц")
            ||
            terminal == QString::fromUtf8("кц")
            ||
            terminal == QString::fromUtf8("иначе")
            ||
            terminal == QString::fromUtf8("если")
            ||
            terminal == QString::fromUtf8("то")
            ||
            terminal == QString::fromUtf8("все")
            ||
            terminal == QString::fromUtf8("выбор")
            ||
            terminal == QString::fromUtf8("при")
            ||
victor's avatar
 
victor committed
964
            terminal == QString::fromUtf8("ограничение_алгоритма")
victor's avatar
 
victor committed
965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981
            ||
            terminal == QString::fromUtf8("исп")
            ||
            terminal == QString::fromUtf8("использовать")
            ||
            terminal == QString::fromUtf8("кон_исп")
            ||
            terminal == QString::fromUtf8("строка_документации")
            ||
            terminal == "end"
            ||
            terminal == "begin"
            ) return true;
    else
        return false;
}

victor's avatar
 
victor committed
982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024
void PDAutomataPrivate::finalizeIterativeRule(const PDStackElem & stackElem)
{
    int iterationStartPos = stackElem.iterateStart;
    for ( int i=iterationStartPos+1; i<currentPosition; i++ ) {
        if ( fixedScripts[i]==NULL )
            fixedScripts[i] = scripts[i];
    }
    if ( allowSkipParts || stackElem.priority==0 )
        nextPointers[iterationStartPos] = currentPosition;
}

void PDAutomataPrivate::saveData()
{
    history_stack.push(stack);
    history_currentPosition.push(currentPosition);
    history_scripts.push(scripts);
}

void PDAutomataPrivate::restoreData()
{
    currentPosition = history_currentPosition.pop();
    stack = history_stack.pop();
    scripts = history_scripts.pop();
}

void PDAutomataPrivate::popHistory()
{
    history_currentPosition.pop();
    history_stack.pop();
    history_scripts.pop();
}

void PDAutomataPrivate::clearDataHistory()
{
    history_currentPosition.clear();
    history_stack.clear();
    history_scripts.clear();
}

void PDAutomataPrivate::nextStep()
{
    currentPosition = currentPosition<nextPointers.size()
            ? nextPointers[currentPosition]
victor's avatar
 
victor committed
1025
            : source.size();
victor's avatar
 
victor committed
1026 1027 1028 1029
}

void PDAutomata::postProcess()
{
victor's avatar
 
victor committed
1030
    d->currentContext.clear();
victor's avatar
 
victor committed
1031
    d->currentPosition = 0;
victor's avatar
 
victor committed
1032 1033
    if (!d->algorhitm) {
        d->currentModule = new AST::Module();
victor's avatar
 
victor committed
1034 1035 1036 1037
        if (d->teacherMode) {
            d->currentModule->header.type = AST::ModTypeHidden;
            d->currentModule->header.name = "@";
        }
victor's avatar
 
victor committed
1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053
        d->currentAlgorhitm = 0;
        d->currentContext.push(&(d->currentModule->impl.initializerBody));
    }
    else {
        AST::Module * mod = 0;
        for (int i=0; i<d->ast->modules.size(); i++) {
            for (int j=0; j<d->ast->modules[i]->impl.algorhitms.size(); j++) {
                if (d->algorhitm==d->ast->modules[i]->impl.algorhitms[j]) {
                    mod = d->ast->modules[i];
                    break;
                }
            }
            if (mod)
                break;
        }
        d->currentModule = mod;
victor's avatar
 
victor committed
1054
//        d->currentContext.push(&(d->algorhitm->impl.body));
victor's avatar
 
victor committed
1055 1056 1057
        d->currentAlgorhitm = d->algorhitm;
    }

victor's avatar
 
victor committed
1058 1059 1060 1061 1062 1063 1064 1065
    for (int i=0; i<d->scripts.size(); i++) {
        ScriptListPtr scripts = d->scripts[i];
        if (!scripts) {
            scripts = d->fixedScripts[i];
        }
        if (scripts) {
            for (int j=0; j<scripts->size(); j++) {
                QMetaMethod m = scripts->at(j).method;
victor's avatar
 
victor committed
1066 1067
                const QString sign = m.signature();
                Q_UNUSED(sign); // Used only for debug
victor's avatar
 
victor committed
1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094
                const QList<QVariant> & arguments = scripts->at(j).arguments;
                switch (arguments.size()) {
                case 1:
                    if (QString::fromAscii(m.parameterTypes()[0])=="int") {
                        m.invoke(d, Qt::DirectConnection,
                                 Q_ARG(int, arguments[0].toInt())
                                 );
                    }
                    else {
                        m.invoke(d, Qt::DirectConnection,
                                 Q_ARG(QString, arguments[0].toString())
                                 );
                    }
                    break;
                case 2:
                    m.invoke(d, Qt::DirectConnection,
                             Q_ARG(int, arguments[0].toInt()),
                             Q_ARG(int, arguments[0].toInt())
                             );
                    break;
                default:
                    m.invoke(d, Qt::DirectConnection);
                }
            }
        }
        d->currentPosition ++;
    }
victor's avatar
 
victor committed
1095
    if (d->currentModule && !d->algorhitm) {
victor's avatar
 
victor committed
1096 1097
        d->ast->modules << d->currentModule;
    }
1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111
    if (!d->algorhitm && d->currentAlgorhitm) {
        bool foundAlgorhitm = false;
        for (int i=0; i<d->ast->modules.size(); i++) {
            AST::Module * module = d->ast->modules[i];
            foundAlgorhitm = module->impl.algorhitms.contains(d->currentAlgorhitm);
            if (foundAlgorhitm)
                break;
        }
        if (d->currentModule && !foundAlgorhitm) {
            foundAlgorhitm = d->currentModule->impl.algorhitms.contains(d->currentAlgorhitm);
        }
        if (!foundAlgorhitm)
            delete d->currentAlgorhitm;
    }
victor's avatar
 
victor committed
1112
    d->source.pop_front();
1113 1114 1115 1116 1117
    if (!d->ast->modules.contains(d->currentModule)) {
        delete d->currentModule;
        d->currentModule = 0;
    }
    d->currentAlgorhitm = 0;
victor's avatar
 
victor committed
1118

victor's avatar
 
victor committed
1119 1120 1121
}

void PDAutomataPrivate::setCurrentIndentRank(int start, int end)
victor's avatar
 
victor committed
1122
{   
victor's avatar
 
victor committed
1123
    source[currentPosition]->indentRank = QPoint(start, end);
victor's avatar
 
victor committed
1124 1125
}

victor's avatar
 
victor committed
1126
void PDAutomataPrivate::setCurrentError(const QString &value)
victor's avatar
 
victor committed
1127
{
victor's avatar
 
victor committed
1128
    for (int i=0; i<source[currentPosition]->data.size(); i++) {
1129 1130 1131 1132
        if (source[currentPosition]->data[i]->type!=LxTypeComment) {
            source[currentPosition]->data[i]->error = value;
            source[currentPosition]->data[i]->errorStage = AST::Lexem::PDAutomata;
        }
victor's avatar
 
victor committed
1133
    }
victor's avatar
 
victor committed
1134
}
victor's avatar
 
victor committed
1135

1136 1137 1138 1139 1140 1141 1142 1143 1144
void PDAutomataPrivate::setCurrentErrorRaisePosition(Lexem::ErrorRaisePosition pos)
{
    for (int i=0; i<source[currentPosition]->data.size(); i++) {
        if (source[currentPosition]->data[i]->type!=LxTypeComment) {
            source[currentPosition]->data[i]->errorRaisePosition = pos;
        }
    }
}

victor's avatar
 
victor committed
1145 1146 1147 1148 1149 1150 1151
void PDAutomataPrivate::setOutOfAlgError()
{
    QString value;
    if (source[currentPosition]->type & LxNameClass) {
        value = _("Variable declaration out of algorhitm");
    }
    else {
victor's avatar
 
victor committed
1152
        value = _("Instruction out of algorhitm");
victor's avatar
 
victor committed
1153 1154 1155 1156 1157
    }
    for (int i=0; i<source[currentPosition]->data.size(); i++) {
        source[currentPosition]->data[i]->error = value;
        source[currentPosition]->data[i]->errorStage = AST::Lexem::PDAutomata;
    }
victor's avatar
 
victor committed
1158 1159 1160 1161 1162 1163 1164 1165 1166

    bool doNotEvaluate = false;

    if (currentModule)
        doNotEvaluate = currentModule->impl.algorhitms.size()>0;

    appendSimpleLine();
    if (!currentContext.isEmpty() && currentContext.top())
        currentContext.top()->last()->skipErrorEvaluation = doNotEvaluate;
victor's avatar
 
victor committed
1167 1168 1169 1170
}

void PDAutomataPrivate::processCorrectAlgHeader()
{
victor's avatar
 
victor committed
1171
    AST::Algorhitm * alg = algorhitm? algorhitm : new AST::Algorhitm;
victor's avatar
 
victor committed
1172 1173
    if (teacherMode)
        alg->header.specialType = AST::AlgorhitmTypeTeacher;
victor's avatar
 
victor committed
1174
    alg->impl.headerLexems = source[currentPosition]->data;
victor's avatar
 
victor committed
1175
    currentAlgorhitm = alg;
victor's avatar
 
victor committed
1176
    if (algorhitm) {
victor's avatar
 
victor committed
1177 1178
        source.at(currentPosition)->mod = moduleOfAlgorhitm(ast, algorhitm);
        currentModule = source.at(currentPosition)->mod;
1179 1180
        currentAlgorhitm = algorhitm;
        delete alg;
victor's avatar
 
victor committed
1181 1182
    }
    else {
victor's avatar
 
victor committed
1183
        if (currentModule==0) {
victor's avatar
 
victor committed
1184 1185 1186 1187 1188
            AST::Module * lastModule = ast->modules.last();
            if (lastModule->header.type == AST::ModTypeUser) {
                lastModule->impl.algorhitms << alg;
                source.at(currentPosition)->mod = lastModule;
            }
1189
            setCurrentError(_("Algorithm out of module"));
victor's avatar
 
victor committed
1190 1191 1192 1193 1194
        }
        else {
            currentModule->impl.algorhitms << alg;
            source.at(currentPosition)->mod = currentModule;
        }
victor's avatar
 
victor committed
1195
    }
1196
    source.at(currentPosition)->alg = currentAlgorhitm;
victor's avatar
 
victor committed
1197 1198 1199 1200 1201
}

void PDAutomataPrivate::processCorrectAlgBegin()
{
    setCurrentIndentRank(  0, +1);
victor's avatar
 
victor committed
1202 1203 1204 1205 1206 1207
    if (currentAlgorhitm) {
        currentAlgorhitm->impl.beginLexems = source.at(currentPosition)->data;
        source.at(currentPosition)->mod = currentModule;
        source.at(currentPosition)->alg = currentAlgorhitm;
        currentContext.push(&(currentAlgorhitm->impl.body));
    }
victor's avatar
 
victor committed
1208 1209 1210 1211 1212
}

void PDAutomataPrivate::appendSimpleLine()
{
    AST::Statement * statement = new AST::Statement;
victor's avatar
 
victor committed
1213
    statement->skipErrorEvaluation = false;
victor's avatar
 
victor committed
1214 1215
    statement->lexems = source.at(currentPosition)->data;
    switch ( source.at(currentPosition)->type ) {
victor's avatar
 
victor committed
1216 1217 1218 1219 1220 1221
    case LxPriAssign:
        statement->type = AST::StAssign;
        break;
    case LxPriAssert:
        statement->type = AST::StAssert;
        break;
victor's avatar
 
victor committed
1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233
    case LxNameClass: {
            // Check for we are in algorhitm top or module top
            if (currentContext.size()>1) {
                QList<AST::Statement*> * body = currentContext[currentContext.size()-2];
                if (!body->isEmpty()) {
                    AST::Statement * st = body->last();
                    if (st->type==AST::StLoop
                            || st->type==AST::StIfThenElse
                            || st->type==AST::StSwitchCaseElse)
                    {
                        foreach (Lexem *lx, statement->lexems) {
                            lx->error = _("Can't declare variables at this level");
victor's avatar
 
victor committed
1234
                            lx->errorStage = AST::Lexem::PDAutomata;
victor's avatar
 
victor committed
1235 1236 1237 1238 1239 1240 1241
                        }
                    }
                }
            }
            statement->type = AST::StVarInitialize;
            break;
    }
victor's avatar
 
victor committed
1242 1243 1244 1245 1246 1247 1248 1249 1250
    case LxPriInput:
        statement->type = AST::StInput;
        break;
    case LxPriOutput:
        statement->type = AST::StOutput;
        break;
    case LxPriExit:
        statement->type = AST::StBreak;
        break;
victor's avatar
 
victor committed
1251 1252 1253 1254 1255 1256
    case LxPriPause:
        statement->type = AST::StPause;
        break;
    case LxPriHalt:
        statement->type = AST::StHalt;
        break;
victor's avatar
 
victor committed
1257 1258 1259 1260
    default:
        statement->type = AST::StError;
        break;
    }
victor's avatar
 
victor committed
1261 1262 1263 1264
    if (teacherMode) {
        if (currentContext.size()<=1) {
            // Can't do anything out of algorhitms
            foreach (Lexem * lx, statement->lexems) {
victor's avatar
 
victor committed
1265
                lx->error = _("Hidden part must contain only algorithm");
victor's avatar
 
victor committed
1266 1267 1268 1269 1270 1271
                lx->errorStage = AST::Lexem::PDAutomata;
            }

            statement->type = AST::StError;
        }
    }
victor's avatar
 
victor committed
1272
    if ( source.at(currentPosition)->data[0]->error.size()>0 ) {
victor's avatar
 
victor committed
1273
        statement->type = AST::StError;
victor's avatar
 
victor committed
1274
        statement->error = source.at(currentPosition)->data[0]->error;
victor's avatar
 
victor committed
1275
    }
victor's avatar
 
victor committed
1276 1277 1278 1279 1280 1281 1282 1283
    if (!currentContext.isEmpty() && currentContext.top()) {
        if (statement->type==AST::StError) {
            if (currentContext.top()==&(currentModule->impl.initializerBody)) {
                if (currentModule->impl.algorhitms.size()>0) {
                    statement->skipErrorEvaluation = true;
                }
            }
        }
victor's avatar
 
victor committed
1284
        currentContext.top()->append(statement);
victor's avatar
 
victor committed
1285
    }
victor's avatar
 
victor committed
1286 1287 1288
    source.at(currentPosition)->mod = currentModule;
    source.at(currentPosition)->alg = currentAlgorhitm;
    source.at(currentPosition)->statement = statement;
victor's avatar
 
victor committed
1289 1290
}

victor's avatar
 
victor committed
1291
AST::Statement * PDAutomata::createSimpleAstStatement(Statement * st)
victor's avatar
 
victor committed
1292 1293
{
    AST::Statement * statement = new AST::Statement;
victor's avatar
 
victor committed
1294
    statement->skipErrorEvaluation = false;
victor's avatar
 
victor committed
1295
    switch ( st->type ) {
victor's avatar
 
victor committed
1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314
    case LxPriAssign:
        statement->type = AST::StAssign;
        break;
    case LxPriAssert:
        statement->type = AST::StAssert;
        break;
    case LxPriInput:
        statement->type = AST::StInput;
        break;
    case LxPriOutput:
        statement->type = AST::StOutput;
        break;
    case LxPriExit:
        statement->type = AST::StBreak;
        break;
    default:
        statement->type = AST::StError;
        break;
    }
victor's avatar
 
victor committed
1315
    if (st->hasError()) {
victor's avatar
 
victor committed
1316
        statement->type = AST::StError;
victor's avatar
 
victor committed
1317 1318
        statement->error = st->data[0]->error;
        st->statement = statement;
victor's avatar
 
victor committed
1319 1320 1321 1322
    }
    return statement;
}

victor's avatar
 
victor committed
1323 1324
void PDAutomataPrivate::processCorrectAlgEnd()
{
victor's avatar
 
victor committed
1325
    int indentStart = 0;
victor's avatar
 
victor committed
1326
    bool beginFound = false;
victor's avatar
 
victor committed
1327 1328 1329 1330 1331 1332
    for (int i=currentPosition-1; i>=0; i--) {
        if (source[i]->type==LxPriAlgBegin) {
            if (currentContext.size()>0 && currentContext.top()->contains(source[i]->statement)) {

            }
            else {
victor's avatar
 
victor committed
1333
                beginFound = true;
victor's avatar
 
victor committed
1334 1335 1336 1337 1338 1339
                indentStart = - source[i]->indentRank.y();
                break;
            }
        }
    }

victor's avatar
 
victor committed
1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353
    if (!beginFound) {
        for (int i=currentPosition-1; i>=0; i--) {
            if (source[i]->type==LxPriAlgHeader) {
                if (currentContext.size()>0 && currentContext.top()->contains(source[i]->statement)) {

                }
                else {
                    indentStart = - source[i]->indentRank.y();
                    break;
                }
            }
        }
    }

victor's avatar
 
victor committed
1354
    setCurrentIndentRank(indentStart,  0);
victor's avatar
 
victor committed
1355
    if (currentAlgorhitm) {
victor's avatar
 
victor committed
1356
        currentAlgorhitm->impl.endLexems = source.at(currentPosition)->data;
victor's avatar
 
victor committed
1357
    }
victor's avatar
 
victor committed
1358
    currentContext.pop();
victor's avatar
 
victor committed
1359 1360
    source.at(currentPosition)->mod = currentModule;
    source.at(currentPosition)->alg = currentAlgorhitm;
victor's avatar
 
victor committed
1361 1362 1363
    currentAlgorhitm = 0;
}

victor's avatar
 
victor committed
1364 1365 1366 1367 1368
void PDAutomataPrivate::addDummyAlgHeader()
{
    // nothind to do
}

victor's avatar
 
victor committed
1369
void PDAutomataPrivate::setModuleBeginError(const QString & value)
victor's avatar
 
victor committed
1370
{
victor's avatar
 
victor committed
1371 1372
    for (int i=0; i<source.size(); i++) {
        if (source[i]->mod == currentModule && source[i]->type==LxPriModule) {
victor's avatar
 
victor committed
1373 1374 1375
            for (int a=0; a<source[i]->data.size(); a++) {
                source[i]->data[a]->error = value;
                source[i]->data[a]->errorStage = AST::Lexem::PDAutomata;
victor's avatar
 
victor committed
1376
            }
victor's avatar
 
victor committed
1377
            source[i]->indentRank = QPoint(0, 0);
victor's avatar
 
victor committed
1378 1379 1380 1381 1382 1383 1384 1385 1386 1387
        }
    }
}

void PDAutomataPrivate::processCorrectEndOfLoop()
{
    setCurrentIndentRank(-1,  0);
    currentContext.pop();
    Q_ASSERT(currentContext.size()>0);
    Q_ASSERT(currentContext.top()->last()->type==AST::StLoop);
victor's avatar
 
victor committed
1388 1389 1390 1391
    currentContext.top()->last()->loop.endLexems = source.at(currentPosition)->data;
    source.at(currentPosition)->mod = currentModule;
    source.at(currentPosition)->alg = currentAlgorhitm;
    source.at(currentPosition)->statement = currentContext.top()->last();
victor's avatar
 
victor committed
1392 1393 1394 1395 1396 1397
}

void PDAutomataPrivate::processAlgEndInsteadOfLoopEnd()
{
    setCurrentIndentRank(-1, 0);
    setCurrentError(_("'end' instead of 'endloop'"));
victor's avatar
 
victor committed
1398
//    currentContext.pop();
victor's avatar
 
victor committed
1399
    Q_ASSERT(currentContext.size()>0);
victor's avatar
 
victor committed
1400 1401 1402 1403
//    Q_ASSERT(currentContext.top()->last()->type==AST::StLoop);
    if (currentContext.top()->last()->type==AST::StLoop) {
        currentContext.top()->last()->loop.endLexems = source.at(currentPosition)->data;
    }
victor's avatar
 
victor committed
1404 1405 1406
    source.at(currentPosition)->mod = currentModule;
    source.at(currentPosition)->alg = currentAlgorhitm;
    source.at(currentPosition)->statement = currentContext.top()->last();
victor's avatar
 
victor committed
1407 1408 1409
    if (currentContext.top()->last()->type==AST::StLoop) {
        currentContext.pop();
    }
victor's avatar
 
victor committed
1410 1411
}

victor's avatar
 
victor committed
1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454
void PDAutomataPrivate::processModEndInsteadOfAlgEnd()
{
    int a = currentPosition-1;
    int modDeclPos = -1;
    int beginPos = -1;
    int algPos = -1;
    while (a>=0) {
        if (source[a]->type==LxPriEndModule && !source[a]->hasError()) {
            break;
        }
        else if (source[a]->type==LxPriAlgBegin) {
            beginPos = a;
        }
        else if (source[a]->type==LxPriAlgHeader) {
            algPos = a;
        }
        else if (source[a]->type==LxPriAlgEnd) {
            algPos = beginPos = -1;
            break;
        }
        else if (source[a]->type==LxPriEndModule && !source[a]->hasError()) {
            modDeclPos = -1;
            break;
        }
        else if (source[a]->type==LxPriModule && !source[a]->hasError()) {
            modDeclPos = a;
            break;
        }
        a--;
    }
    processCorrectAlgEnd();
    processCorrectModuleEnd();
    if (modDeclPos==-1) {
        setCurrentError(_("'end_module' instead of 'end'"));
        setCurrentIndentRank(-1, 0);
    }
    else {
        int pos = qMax(algPos, beginPos);
        if (pos!=-1) {
            const QString err = pos==beginPos
                    ? _("Extra 'begin'")
                    : _("Algorhitm not implemented");
            for (int i=0; i<source[pos]->data.size(); i++) {
1455 1456 1457 1458
                if (source[pos]->data[i]->type!=LxTypeComment) {
                    source[pos]->data[i]->error = err;
                    source[pos]->data[i]->errorStage = AST::Lexem::PDAutomata;
                }