summaryrefslogtreecommitdiffstats
path: root/src/qscxml/executablecontent.cpp
blob: 67db47ab8b038a0f5bb0b0d135595ec5c2e1b01a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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
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
90
91
92
93
94
95
96
97
98
99
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
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
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
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
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
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
478
479
480
481
482
483
484
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
570
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
/****************************************************************************
 **
 ** Copyright (c) 2015 Digia Plc
 ** For any questions to Digia, please use contact form at http://qt.digia.com/
 **
 ** All Rights Reserved.
 **
 ** NOTICE: All information contained herein is, and remains
 ** the property of Digia Plc and its suppliers,
 ** if any. The intellectual and technical concepts contained
 ** herein are proprietary to Digia Plc
 ** and its suppliers and may be covered by Finnish and Foreign Patents,
 ** patents in process, and are protected by trade secret or copyright law.
 ** Dissemination of this information or reproduction of this material
 ** is strictly forbidden unless prior written permission is obtained
 ** from Digia Plc.
 ****************************************************************************/

#include "executablecontent_p.h"
#include "scxmlevent_p.h"

using namespace Scxml;
using namespace Scxml::ExecutableContent;

static int parseTime(const QString &t, bool *ok = 0)
{
    if (t.isEmpty()) {
        if (ok)
            *ok = false;
        return -1;
    }
    bool negative = false;
    int startPos = 0;
    if (t[0] == QLatin1Char('-')) {
        negative = true;
        ++startPos;
    } else if (t[0] == QLatin1Char('+')) {
        ++startPos;
    }
    int pos = startPos;
    for (int endPos = t.length(); pos < endPos; ++pos) {
        auto c = t[pos];
        if (c < QLatin1Char('0') || c > QLatin1Char('9'))
            break;
    }
    if (pos == startPos) {
        if (ok) *ok = false;
        return -1;
    }
    int value = t.midRef(startPos, pos - startPos).toInt(ok);
    if (ok && !*ok) return -1;
    if (t.length() == pos + 1 && t[pos] == QLatin1Char('s')) {
        value *= 1000;
    } else if (t.length() != pos + 2 || t[pos] != QLatin1Char('m') || t[pos + 1] != QLatin1Char('s')) {
        if (ok) *ok = false;
        return -1;
    }
    return negative ? -value : value;
}

class ExecutionEngine::Data
{
public:
    Data(StateTable *table)
        : table(table)
    {}

    bool step(Instructions &ip)
    {
        auto dataModel = table->dataModel();
        auto tableData = table->tableData();

        auto instr = reinterpret_cast<Instruction *>(ip);
        switch (instr->instructionType) {
        case Instruction::Sequence: {
            qDebug() << "Executing sequence step";
            InstructionSequence *sequence = reinterpret_cast<InstructionSequence *>(instr);
            ip = sequence->instructions();
            Instructions end = ip + sequence->entryCount;
            while (ip < end) {
                if (!step(ip)) {
                    ip = end;
                    qDebug() << "Finished sequence step UNsuccessfully";
                    return false;
                }
            }
            qDebug() << "Finished sequence step successfully";
            return true;
        }

        case Instruction::Sequences: {
            qDebug() << "Executing sequences step";
            InstructionSequences *sequences = reinterpret_cast<InstructionSequences *>(instr);
            ip += sequences->size();
            for (int i = 0; i != sequences->sequenceCount; ++i) {
                Instructions sequence = sequences->at(i);
                step(sequence);
            }
            qDebug() << "Finished sequences step";
            return true;
        }

        case Instruction::Send: {
            qDebug() << "Executing send step";
            Send *send = reinterpret_cast<Send *>(instr);
            ip += send->size();

            QString delay = tableData->string(send->delay);
            if (send->delayexpr != NoEvaluator) {
                bool ok = false;
                delay = table->dataModel()->evaluateToString(send->delayexpr, &ok);
                if (!ok)
                    return false;
            }

            ScxmlEvent *event = EventBuilder(table, *send).buildEvent();
            if (!event)
                return false;

            if (delay.isEmpty()) {
                table->submitEvent(event);
            } else {
                int msecs = parseTime(delay);
                if (msecs >= 0) {
                    table->submitDelayedEvent(msecs, event);
                } else {
                    qCDebug(scxmlLog) << "failed to parse delay time" << delay;
                    return false;
                }
            }

            return true;
        }

        case Instruction::JavaScript: {
            qDebug() << "Executing javascript step";
            JavaScript *javascript = reinterpret_cast<JavaScript *>(instr);
            ip += javascript->size();
            bool ok = true;
            dataModel->evaluateToVoid(javascript->go, &ok);
            return ok;
        }

        case Instruction::If: {
            qDebug() << "Executing if step";
            If *_if = reinterpret_cast<If *>(instr);
            ip += _if->size();
            auto blocks = _if->blocks();
            for (qint32 i = 0; i < _if->conditions.count; ++i) {
                bool ok = true;
                if (dataModel->evaluateToBool(_if->conditions.at(i), &ok) && ok) {
                    Instructions block = blocks->at(i);
                    bool res = step(block);
                    qDebug()<<"Finished if step";
                    return res;
                }
            }

            if (_if->conditions.count < blocks->sequenceCount) {
                Instructions block = blocks->at(_if->conditions.count);
                return step(block);
            }

            return true;
        }

        case Instruction::Foreach: {
            qDebug() << "Executing foreach step";
            Foreach *foreach = reinterpret_cast<Foreach *>(instr);
            Instructions loopStart = foreach->blockstart();
            ip += foreach->size();
            bool ok = true;
            bool evenMoreOk = dataModel->evaluateForeach(foreach->doIt, &ok, [this,loopStart]()-> bool {
                Instructions loop = loopStart;
                return step(loop);
            });
            return ok && evenMoreOk;
        }

        case Instruction::Raise: {
            qDebug() << "Executing raise step";
            Raise *raise = reinterpret_cast<Raise *>(instr);
            ip += raise->size();
            auto event = tableData->byteArray(raise->event);
            table->submitEvent(event, QVariantList(), QStringList(), ScxmlEvent::Internal);
            return true;
        }

        case Instruction::Log: {
            qDebug() << "Executing log step";
            Log *log = reinterpret_cast<Log *>(instr);
            ip += log->size();
            bool ok = true;
            QString str = dataModel->evaluateToString(log->expr, &ok);
            if (ok)
                table->doLog(tableData->string(log->label), str);
            return ok;
        }

        case Instruction::Cancel: {
            qDebug() << "Executing cancel step";
            Cancel *cancel = reinterpret_cast<Cancel *>(instr);
            ip += cancel->size();
            QByteArray e = tableData->byteArray(cancel->sendid);
            bool ok = true;
            if (cancel->sendidexpr != NoEvaluator)
                e = dataModel->evaluateToString(cancel->sendidexpr, &ok).toUtf8();
            if (ok && !e.isEmpty())
                table->cancelDelayedEvent(e);
            return ok;
        }

        case Instruction::Invoke:
            Q_UNIMPLEMENTED();
            Q_UNREACHABLE();
            return false;

        case Instruction::Assign: {
            qDebug() << "Executing assign step";
            Assign *assign = reinterpret_cast<Assign *>(instr);
            ip += assign->size();
            bool ok = true;
            dataModel->evaluateAssignment(assign->expression, &ok);
            return ok;
        }

        case Instruction::DoneData: {
            qDebug() << "Executing DoneData step";
            DoneData *doneData = reinterpret_cast<DoneData *>(instr);

            QString eventName = QStringLiteral("done.state.") + extraData.toString();
            EventBuilder event(table, eventName, doneData);
            qDebug() << "submitting event" << eventName;
            table->submitEvent(event());
            return true;
        }

        default:
            Q_UNREACHABLE();
            return false;
        }
    }

    StateTable *table;
    QVariant extraData;
};

ExecutionEngine::ExecutionEngine(StateTable *table)
    : data(new Data(table))
{
    Q_ASSERT(table);
}

ExecutionEngine::~ExecutionEngine()
{
    delete data;
}

bool ExecutionEngine::execute(ContainerId id, const QVariant &extraData)
{
    Q_ASSERT(data->table);

    if (id == NoInstruction)
        return true;

    qint32 *ip = data->table->tableData()->instructions() + id;
    data->extraData = extraData;
    bool result = data->step(ip);
    data->extraData = QVariant();
    return result;
}

Builder::Builder()
{
    m_activeSequences.reserve(4);
}

bool Builder::visit(DocumentModel::Send *node)
{
    auto instr = m_instructions.add<Send>(Send::calculateExtraSize(node->params.size(), node->namelist.size()));
    instr->instructionLocation = createContext(QStringLiteral("send"));
    instr->event = addByteArray(node->event.toUtf8());
    instr->eventexpr = createEvaluatorString(QStringLiteral("send"), QStringLiteral("eventexpr"), node->eventexpr);
    instr->type = addString(node->type);
    instr->typeexpr = createEvaluatorString(QStringLiteral("send"), QStringLiteral("typeexpr"), node->typeexpr);
    instr->target = addString(node->target);
    instr->targetexpr = createEvaluatorString(QStringLiteral("send"), QStringLiteral("targetexpr"), node->targetexpr);
    instr->id = addByteArray(node->id.toUtf8());
    instr->idLocation = addString(node->idLocation);
    instr->delay = addString(node->delay);
    instr->delayexpr = createEvaluatorString(QStringLiteral("send"), QStringLiteral("delayexpr"), node->delayexpr);
    instr->content = addString(node->content);
    generate(&instr->namelist, node->namelist);
    generate(instr->params(), node->params);
    return false;
}

void Builder::visit(DocumentModel::Raise *node)
{
    auto instr = m_instructions.add<Raise>();
    instr->event = addByteArray(node->event.toUtf8());
}

void Builder::visit(DocumentModel::Log *node)
{
    auto instr = m_instructions.add<Log>();
    instr->label = addString(node->label);
    instr->expr = createEvaluatorString(QStringLiteral("log"), QStringLiteral("expr"), node->expr);
}

void Builder::visit(DocumentModel::Script *node)
{
    auto instr = m_instructions.add<JavaScript>();
    auto ctxt = createContext(QStringLiteral("script"), QStringLiteral("source"), node->content);
    instr->go = addEvaluator(node->content, ctxt);
}

void Builder::visit(DocumentModel::Assign *node)
{
    auto instr = m_instructions.add<Assign>();
//    qDebug()<<"...:" <<node->location<<"="<<node->expr;
    auto ctxt = createContext(QStringLiteral("assign"), QStringLiteral("expr"), node->expr);
    instr->expression = addAssignment(node->location, node->expr, ctxt);
}

bool Builder::visit(DocumentModel::If *node)
{
    auto instr = m_instructions.add<If>(node->conditions.size());
    instr->conditions.count = node->conditions.size();
    auto it = instr->conditions.data();
    QString tag = QStringLiteral("if");
    for (int i = 0, ei = node->conditions.size(); i != ei; ++i) {
        *it++ = createEvaluatorBool(tag, QStringLiteral("cond"), node->conditions.at(i));
        if (i == 0) {
            tag = QStringLiteral("elif");
        }
    }
    auto outSequences = m_instructions.add<InstructionSequences>();
    generate(outSequences, node->blocks);
    return false;
}

bool Builder::visit(DocumentModel::Foreach *node)
{
    auto instr = m_instructions.add<Foreach>();
    auto ctxt = createContextString(QStringLiteral("foreach"));
    instr->doIt = addForeach(node->array, node->item, node->index, ctxt);
    startSequence(&instr->block);
    visit(&node->block);
    endSequence();
    return false;
}

void Builder::visit(DocumentModel::Cancel *node)
{
    auto instr = m_instructions.add<Cancel>();
    instr->sendid = addByteArray(node->sendid.toUtf8());
    instr->sendidexpr = createEvaluatorString(QStringLiteral("cancel"), QStringLiteral("sendidexpr"), node->sendidexpr);
}

bool Builder::visit(DocumentModel::Invoke *)
{
    Q_UNIMPLEMENTED();
    return false;
}

ContainerId Builder::generate(const DocumentModel::DoneData *node)
{
    auto id = m_instructions.newContainerId();
    DoneData *doneData;
    if (node) {
        doneData = m_instructions.add<DoneData>(node->params.size() * Param::calculateSize());
        doneData->contents = addString(node->contents);
        doneData->expr = createEvaluatorString(QStringLiteral("donedata"), QStringLiteral("expr"), node->expr);
        generate(&doneData->params, node->params);
    } else {
        doneData = m_instructions.add<DoneData>();
        doneData->contents = NoString;
        doneData->expr = NoEvaluator;
        doneData->params.count = 0;
    }
    doneData->location = createContext(QStringLiteral("final"));
    return id;
}

StringId Builder::createContext(const QString &instrName)
{
    return addString(createContextString(instrName));
}

void Builder::generate(const QVector<DocumentModel::DataElement *> &dataElements)
{
    foreach (DocumentModel::DataElement *el, dataElements) {
        auto ctxt = createContext(QStringLiteral("data"), QStringLiteral("expr"), el->expr);
        auto evaluator = addDataElement(el->id, el->expr, ctxt);
        if (evaluator != NoEvaluator) {
            auto instr = m_instructions.add<ExecutableContent::Assign>();
            instr->expression = evaluator;
        }
    }
}

ContainerId Builder::generate(const DocumentModel::InstructionSequences &inSequences)
{
    if (inSequences.isEmpty())
        return NoInstruction;

    auto id = m_instructions.newContainerId();
    auto outSequences = m_instructions.add<InstructionSequences>();
    generate(outSequences, inSequences);
    return id;
}

void Builder::generate(Array<Param> *out, const QVector<DocumentModel::Param *> &in)
{
    out->count = in.size();
    Param *it = out->data();
    foreach (DocumentModel::Param *f, in) {
        it->name = addString(f->name);
        it->expr = createEvaluatorVariant(QStringLiteral("param"), QStringLiteral("expr"), f->expr);
        it->location = addString(f->location);
        ++it;
    }
}

void Builder::generate(InstructionSequences *outSequences, const DocumentModel::InstructionSequences &inSequences)
{
    int sequencesOffset = m_instructions.offset(outSequences);
    int sequenceCount = 0;
    int entryCount = 0;
    foreach (DocumentModel::InstructionSequence *sequence, inSequences) {
        ++sequenceCount;
        startNewSequence();
        visit(sequence);
        entryCount += endSequence()->size();
    }
    outSequences = m_instructions.at<InstructionSequences>(sequencesOffset);
    outSequences->sequenceCount = sequenceCount;
    outSequences->entryCount = entryCount;
}

void Builder::generate(Array<StringId> *out, const QStringList &in)
{
    out->count = in.size();
    StringId *it = out->data();
    foreach (const QString &str, in) {
        *it++ = addString(str);
    }
}

ContainerId Builder::startNewSequence()
{
    auto id = m_instructions.newContainerId();
    auto sequence = m_instructions.add<InstructionSequence>();
    startSequence(sequence);
    return id;
}

void Builder::startSequence(InstructionSequence *sequence)
{
    SequenceInfo info;
    info.location = m_instructions.offset(sequence);
    info.entryCount = 0;
    m_activeSequences.push_back(info);
    m_instructions.setSequenceInfo(&m_activeSequences.last());
    sequence->instructionType = Instruction::Sequence;
    sequence->entryCount = -1; // checked in endSequence
//    qDebug()<<"starting sequence with depth"<<m_activeSequences.size();
}

InstructionSequence *Builder::endSequence()
{
    SequenceInfo info = m_activeSequences.back();
    m_activeSequences.pop_back();
    m_instructions.setSequenceInfo(m_activeSequences.isEmpty() ? nullptr : &m_activeSequences.last());

    auto sequence = m_instructions.at<InstructionSequence>(info.location);
    Q_ASSERT(sequence->entryCount == -1); // set in startSequence
    sequence->entryCount = info.entryCount;
    if (!m_activeSequences.isEmpty())
        m_activeSequences.last().entryCount += info.entryCount;
//    qDebug()<<"finished sequence with"<<info.entryCount<<"bytes, depth" << (m_activeSequences.size()+1);
    return sequence;
}

EvaluatorId Builder::createEvaluatorString(const QString &instrName, const QString &attrName, const QString &expr)
{
    if (!expr.isEmpty()) {
        QString loc = createContext(instrName, attrName, expr);
        return addEvaluator(expr, loc);
    }

    return NoEvaluator;
}

EvaluatorId Builder::createEvaluatorBool(const QString &instrName, const QString &attrName, const QString &cond)
{
    if (!cond.isEmpty()) {
        QString loc = createContext(instrName, attrName, cond);
        return addEvaluator(cond, loc);
    }

    return NoEvaluator;
}

EvaluatorId Builder::createEvaluatorVariant(const QString &instrName, const QString &attrName, const QString &cond)
{
    if (!cond.isEmpty()) {
        QString loc = createContext(instrName, attrName, cond);
        return addEvaluator(cond, loc);
    }

    return NoEvaluator;
}

DynamicTableData *Builder::tableData()
{
    auto td = new DynamicTableData;
    td->strings = m_stringTable.data();
    td->byteArrays = m_byteArrayTable.data();
    td->theInstructions = m_instructions.data();
    td->theEvaluators = m_evaluators.data();
    td->theAssignments = m_assignments.data();
    td->theForeaches = m_foreaches.data();
    td->theDataNameIds = m_dataIds;
    return td;
}


QString DynamicTableData::string(StringId id) const
{
    return id == NoString ? QString() : strings.at(id);
}

QByteArray DynamicTableData::byteArray(ByteArrayId id) const
{
    return byteArrays.at(id);
}

Instructions DynamicTableData::instructions() const
{
    return const_cast<Instructions>(theInstructions.data());
}

EvaluatorInfo DynamicTableData::evaluatorInfo(EvaluatorId evaluatorId) const
{
    return theEvaluators[evaluatorId];
}

AssignmentInfo DynamicTableData::assignmentInfo(EvaluatorId assignmentId) const
{
    return theAssignments[assignmentId];
}

ForeachInfo DynamicTableData::foreachInfo(EvaluatorId foreachId) const
{
    return theForeaches[foreachId];
}

StringId *DynamicTableData::dataNames(int *count) const
{
    Q_ASSERT(count);
    *count = theDataNameIds.size();
    return const_cast<StringId *>(theDataNameIds.data());
}

QVector<qint32> DynamicTableData::instructionTable() const
{
    return theInstructions;
}

QVector<QString> DynamicTableData::stringTable() const
{
    return strings;
}

QVector<QByteArray> DynamicTableData::byteArrayTable() const
{
    return byteArrays;
}

QVector<EvaluatorInfo> DynamicTableData::evaluators() const
{
    return theEvaluators;
}

QVector<AssignmentInfo> DynamicTableData::assignments() const
{
    return theAssignments;
}

QVector<ForeachInfo> DynamicTableData::foreaches() const
{
    return theForeaches;
}

StringIds DynamicTableData::allDataNameIds() const
{
    return theDataNameIds;
}