summaryrefslogtreecommitdiffstats
path: root/src/declarative/qml/qmlexpression.cpp
blob: 4fe7d0cf61697a6577ed0dfa8e9b0a256c13764a (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
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
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Qt Software Information (qt-info@nokia.com)
**
** This file is part of the QtDeclarative module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the either Technology Preview License Agreement or the
** Beta Release License Agreement.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at qt-sales@nokia.com.
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qmlexpression.h"
#include "qmlexpression_p.h"
#include "qmlengine_p.h"
#include "qmlcontext_p.h"
#include "rewriter/textwriter_p.h"
#include "parser/qmljslexer_p.h"
#include "parser/qmljsparser_p.h"
#include "parser/qmljsnodepool_p.h"
#include "QtCore/qdebug.h"

Q_DECLARE_METATYPE(QList<QObject *>);

QT_BEGIN_NAMESPACE

DEFINE_BOOL_CONFIG_OPTION(qmlDebugger, QML_DEBUGGER)

namespace {

using namespace QmlJS;

class RewriteBinding: protected AST::Visitor
{
    unsigned _position;
    TextWriter *_writer;

public:
    QString operator()(const QString &code)
    {
        Engine engine;
        NodePool pool(QString(), &engine);
        Lexer lexer(&engine);
        Parser parser(&engine);
        lexer.setCode(code, 0);
        parser.parseStatement();
        return rewrite(code, 0, parser.statement());
    }

protected:
    using AST::Visitor::visit;

    void accept(AST::Node *node)
    {
        AST::Node::acceptChild(node, this);
    }

    QString rewrite(QString code, unsigned position, AST::Statement *node)
    {
        TextWriter w;
        _writer = &w;
        _position = position;

        accept(node);

        unsigned startOfStatement = node->firstSourceLocation().begin() - _position;
        unsigned endOfStatement = node->lastSourceLocation().end() - _position;

        _writer->replace(startOfStatement, 0, QLatin1String("function() {\n"));
        _writer->replace(endOfStatement, 0, QLatin1String("\n}"));

        w.write(&code);

        return code;
    }

    virtual bool visit(AST::Block *ast)
    {
        for (AST::StatementList *it = ast->statements; it; it = it->next) {
            if (! it->next) {
                // we need to rewrite only the last statement of a block.
                accept(it->statement);
            }
        }

        return false;
    }

    virtual bool visit(AST::ExpressionStatement *ast)
    {
        unsigned startOfExpressionStatement = ast->firstSourceLocation().begin() - _position;
        _writer->replace(startOfExpressionStatement, 0, QLatin1String("return "));

        return false;
    }

    virtual bool visit(AST::NumericLiteral *node)
    {
        if (node->suffix != AST::NumericLiteral::noSuffix) {
            const int suffixLength = AST::NumericLiteral::suffixLength[node->suffix];
            const char *suffixSpell = AST::NumericLiteral::suffixSpell[node->suffix];
            QString pre;
            pre += QLatin1String("qmlNumberFrom");
            pre += QChar(QLatin1Char(suffixSpell[0])).toUpper();
            pre += QLatin1String(&suffixSpell[1]);
            pre += QLatin1Char('(');
            _writer->replace(node->literalToken.begin() - _position, 0, pre);
            _writer->replace(node->literalToken.end() - _position - suffixLength,
                             suffixLength,
                             QLatin1String(")"));
        }

        return false;
    }
};

} // end of anonymous namespace


QmlExpressionPrivate::QmlExpressionPrivate(QmlExpression *b)
: q(b), ctxt(0), expressionFunctionValid(false), sseData(0), proxy(0), me(0), trackChange(false), line(-1), id(0), log(0)
{
}

QmlExpressionPrivate::QmlExpressionPrivate(QmlExpression *b, void *expr, QmlRefCount *rc)
: q(b), ctxt(0), expressionFunctionValid(false), sse((const char *)expr, rc), sseData(0), proxy(0), me(0), trackChange(true), line(-1), id(0), log(0)
{
}

QmlExpressionPrivate::QmlExpressionPrivate(QmlExpression *b, const QString &expr)
: q(b), ctxt(0), expression(expr), expressionFunctionValid(false), sseData(0), proxy(0), me(0), trackChange(true), line(-1), id(0), log(0)
{
}

QmlExpressionPrivate::~QmlExpressionPrivate()
{
    sse.deleteScriptState(sseData);
    sseData = 0;
    delete proxy;
    delete log;
}

/*!
    Create an invalid QmlExpression.

    As the expression will not have an associated QmlContext, this will be a
    null expression object and its value will always be an invalid QVariant.
 */
QmlExpression::QmlExpression()
: d(new QmlExpressionPrivate(this))
{
}

/*! \internal */
QmlExpression::QmlExpression(QmlContext *ctxt, void *expr,
                             QmlRefCount *rc, QObject *me)
: d(new QmlExpressionPrivate(this, expr, rc))
{
    d->ctxt = ctxt;
    if(ctxt && ctxt->engine())
        d->id = ctxt->engine()->d_func()->getUniqueId();
    if(ctxt)
        ctxt->d_func()->childExpressions.insert(this);
    d->me = me;
}

/*!
    Create a QmlExpression object.

    The \a expression ECMAScript will be executed in the \a ctxt QmlContext.
    If specified, the \a scope object's properties will also be in scope during
    the expression's execution.
*/
QmlExpression::QmlExpression(QmlContext *ctxt, const QString &expression,
                             QObject *scope)
: d(new QmlExpressionPrivate(this, expression))
{
    d->ctxt = ctxt;
    if(ctxt && ctxt->engine())
        d->id = ctxt->engine()->d_func()->getUniqueId();
    if(ctxt)
        ctxt->d_func()->childExpressions.insert(this);
    d->me = scope;
}

/*!
    Destroy the QmlExpression instance.
*/
QmlExpression::~QmlExpression()
{
    if (d->ctxt)
        d->ctxt->d_func()->childExpressions.remove(this);
    delete d; d = 0;
}

/*!
    Returns the QmlEngine this expression is associated with, or 0 if there
    is no association or the QmlEngine has been destroyed.
*/
QmlEngine *QmlExpression::engine() const
{
    return d->ctxt?d->ctxt->engine():0;
}

/*!
    Returns the QmlContext this expression is associated with, or 0 if there
    is no association or the QmlContext has been destroyed.
*/
QmlContext *QmlExpression::context() const
{
    return d->ctxt;
}

/*!
    Returns the expression string.
*/
QString QmlExpression::expression() const
{
    if (d->sse.isValid())
        return QLatin1String(d->sse.expression());
    else
        return d->expression;
}

/*!
    Clear the expression.
*/
void QmlExpression::clearExpression()
{
    setExpression(QString());
}

/*!
    Set the expression to \a expression.
*/
void QmlExpression::setExpression(const QString &expression)
{
    if (d->sseData) {
        d->sse.deleteScriptState(d->sseData);
        d->sseData = 0;
    }

    delete d->proxy; d->proxy = 0;

    d->expression = expression;
    d->expressionFunctionValid = false;
    d->expressionFunction = QScriptValue();

    d->sse.clear();
}

/*!
    Called by QmlExpression each time the expression value changes from the
    last time it was evaluated.  The expression must have been evaluated at
    least once (by calling QmlExpression::value()) before this callback will
    be made.

    The default implementation does nothing.
*/
void QmlExpression::valueChanged()
{
}

QVariant QmlExpressionPrivate::evalSSE(QmlBasicScript::CacheState &cacheState)
{
#ifdef Q_ENABLE_PERFORMANCE_LOG
    QFxPerfTimer<QFxPerf::BindValueSSE> perfsse;
#endif

    QmlContextPrivate *ctxtPriv = ctxt->d_func();
    if (me)
        ctxtPriv->defaultObjects.insert(ctxtPriv->highPriorityCount , me);

    if (!sseData)
        sseData = sse.newScriptState();
    QVariant rv = sse.run(ctxt, sseData, &cacheState);

    if (me)
        ctxtPriv->defaultObjects.removeAt(ctxtPriv->highPriorityCount);

    return rv;
}

QVariant QmlExpressionPrivate::evalQtScript()
{
#ifdef Q_ENABLE_PERFORMANCE_LOG
    QFxPerfTimer<QFxPerf::BindValueQt> perfqt;
#endif

    QmlContextPrivate *ctxtPriv = ctxt->d_func();
    QmlEngine *engine = ctxt->engine();

    if (me)
       ctxtPriv->defaultObjects.insert(ctxtPriv->highPriorityCount, me);

    QScriptEngine *scriptEngine = engine->scriptEngine();
    QScriptValueList oldScopeChain =
        scriptEngine->currentContext()->scopeChain();

    for (int i = 0; i < oldScopeChain.size(); ++i)
        scriptEngine->currentContext()->popScope();
    for (int i = ctxtPriv->scopeChain.size() - 1; i > -1; --i)
        scriptEngine->currentContext()->pushScope(ctxtPriv->scopeChain.at(i));

    if (!expressionFunctionValid) {
        RewriteBinding rewriteBinding;

        const QString code = rewriteBinding(expression);
        expressionFunction = scriptEngine->evaluate(code, fileName.toString(), line);
        expressionFunctionValid = true;
    }

    QScriptValue svalue = expressionFunction.call();


    if (scriptEngine->hasUncaughtException()) {
        if (scriptEngine->uncaughtException().isError()){
            QScriptValue exception = scriptEngine->uncaughtException();
            QLatin1String fileNameProp("fileName");
            if (!exception.property(fileNameProp).toString().isEmpty()){
                    qWarning() << exception.property(fileNameProp).toString()
                               << scriptEngine->uncaughtExceptionLineNumber()
                               << exception.toString();
            } else {
                qWarning() << exception.toString();
            }
        }
    }

    if (me)
        ctxtPriv->defaultObjects.removeAt(ctxtPriv->highPriorityCount);

    QVariant rv;

    if (svalue.isArray()) {
        int length = svalue.property(QLatin1String("length")).toInt32();
        if (length && svalue.property(0).isObject()) {
            QList<QObject *> list;
            for (int ii = 0; ii < length; ++ii) {
                QScriptValue arrayItem = svalue.property(ii);
                QObject *d =
                    qvariant_cast<QObject *>(arrayItem.data().toVariant());
                if (d) {
                    list << d;
                } else {
                    list << 0;
                }
            }
            rv = QVariant::fromValue(list);
        }
    } else if (svalue.isObject() &&
               !svalue.isNumber() &&
               !svalue.isString() &&
               !svalue.isDate() &&
               !svalue.isError() &&
               !svalue.isFunction() &&
               !svalue.isNull() &&
               !svalue.isQMetaObject() &&
               !svalue.isQObject() &&
               !svalue.isRegExp()) {
        QScriptValue objValue = svalue.data();
        if (objValue.isValid()) {
            QVariant var = objValue.toVariant();
            if (var.userType() >= (int)QVariant::UserType &&
                QmlMetaType::isObject(var.userType()))
                rv = var;
        }
    }
    if (rv.isNull())
        rv = svalue.toVariant();

    for (int i = 0; i < ctxtPriv->scopeChain.size(); ++i)
        scriptEngine->currentContext()->popScope();
    for (int i = oldScopeChain.size() - 1; i > -1; --i)
        scriptEngine->currentContext()->pushScope(oldScopeChain.at(i));

    return rv;
}

/*!
    Returns the value of the expression, or an invalid QVariant if the
    expression is invalid or has an error.
*/
QVariant QmlExpression::value()
{
    QVariant rv;
    if (!d->ctxt || !engine() || (!d->sse.isValid() && d->expression.isEmpty()))
        return rv;

#ifdef Q_ENABLE_PERFORMANCE_LOG
    QFxPerfTimer<QFxPerf::BindValue> perf;
#endif

    QmlBasicScript::CacheState cacheState = QmlBasicScript::Reset;

    QmlEnginePrivate *ep = engine()->d_func();
    QmlExpression *lastCurrentExpression = ep->currentExpression;
    ep->currentExpression = this;

    if (d->sse.isValid()) {
        rv = d->evalSSE(cacheState);
    } else {
        rv = d->evalQtScript();
    }

    ep->currentExpression = lastCurrentExpression;

    if (cacheState != QmlBasicScript::NoChange) {
        if (cacheState != QmlBasicScript::Incremental && d->proxy) {
            delete d->proxy;
            d->proxy = 0;
        }

        if (trackChange() && ep->capturedProperties.count()) {
            if (!d->proxy)
                d->proxy = new QmlExpressionBindProxy(this);

            static int changedIndex = -1;
            if (changedIndex == -1)
                changedIndex = QmlExpressionBindProxy::staticMetaObject.indexOfSlot("changed()");

            if(qmlDebugger()) {
                QmlExpressionLog log;
                log.setTime(engine()->d_func()->getUniqueId());
                log.setExpression(expression());
                log.setResult(rv);

                for (int ii = 0; ii < ep->capturedProperties.count(); ++ii) {
                    const QmlEnginePrivate::CapturedProperty &prop =
                        ep->capturedProperties.at(ii);

                    if (prop.notifyIndex != -1) {
                        QMetaObject::connect(prop.object, prop.notifyIndex,
                                             d->proxy, changedIndex);
                    } else {
                        const QMetaObject *metaObj = prop.object->metaObject();
                        QMetaProperty metaProp =
                            metaObj->property(prop.coreIndex);

                        QString warn = QLatin1String("Expression depends on non-NOTIFYable property: ") +
                                       QLatin1String(metaObj->className()) +
                                       QLatin1String("::") +
                                       QLatin1String(metaProp.name());
                        log.addWarning(warn);
                    }
                }
                d->addLog(log);

            } else {
                bool outputWarningHeader = false;
                for (int ii = 0; ii < ep->capturedProperties.count(); ++ii) {
                    const QmlEnginePrivate::CapturedProperty &prop =
                        ep->capturedProperties.at(ii);

                    if (prop.notifyIndex != -1) {
                        QMetaObject::connect(prop.object, prop.notifyIndex,
                                             d->proxy, changedIndex);
                    } else {
                        if (!outputWarningHeader) {
                            outputWarningHeader = true;
                            qWarning() << "QmlExpression: Expression" << expression() << "depends on non-NOTIFYable properties:";
                        }

                        const QMetaObject *metaObj = prop.object->metaObject();
                        QMetaProperty metaProp =
                            metaObj->property(prop.coreIndex);

                        qWarning().nospace() << "    " << metaObj->className()
                                             << "::" << metaProp.name();
                    }
                }
            }
        } else {
            QmlExpressionLog log;
            log.setTime(engine()->d_func()->getUniqueId());
            log.setExpression(expression());
            log.setResult(rv);
            d->addLog(log);
        }

    } else {
        if(qmlDebugger()) {
            QmlExpressionLog log;
            log.setTime(engine()->d_func()->getUniqueId());
            log.setExpression(expression());
            log.setResult(rv);
            d->addLog(log);
        }
    }

    ep->capturedProperties.clear();

    return rv;
}

/*!
    Returns true if the expression results in a constant value.
    QmlExpression::value() must have been invoked at least once before the
    return from this method is valid.
 */
bool QmlExpression::isConstant() const
{
    return d->proxy == 0;
}

/*!
    Returns true if the changes are tracked in the expression's value.
*/
bool QmlExpression::trackChange() const
{
    return d->trackChange;
}

/*!
    Set whether changes are tracked in the expression's value to \a trackChange.

    If true, the QmlExpression will monitor properties involved in the
    expression's evaluation, and call QmlExpression::valueChanged() if they have
    changed.  This allows an application to ensure that any value associated
    with the result of the expression remains up to date.

    If false, the QmlExpression will not montitor properties involved in the
    expression's evaluation, and QmlExpression::valueChanged() will never be
    called.  This is more efficient if an application wants a "one off"
    evaluation of the expression.

    By default, trackChange is true.
*/
void QmlExpression::setTrackChange(bool trackChange)
{
    d->trackChange = trackChange;
}

/*!
    Set the location of this expression to \a line of \a fileName. This information
    is used by the script engine.
*/
void QmlExpression::setSourceLocation(const QUrl &fileName, int line)
{
    d->fileName = fileName;
    d->line = line;
}

/*!
    Returns the expression's scope object, if provided, otherwise 0.

    In addition to data provided by the expression's QmlContext, the scope
    object's properties are also in scope during the expression's evaluation.
*/
QObject *QmlExpression::scopeObject() const
{
    return d->me;
}

/*!
    \internal
*/
quint32 QmlExpression::id() const
{
    return d->id;
}

/*!
    \class QmlExpression
    \brief The QmlExpression class evaluates ECMAScript in a QML context.
*/

/*!
    \class QmlExpressionObject
    \brief The QmlExpressionObject class extends QmlExpression with signals and slots.

    To remain as lightweight as possible, QmlExpression does not inherit QObject
    and consequently cannot use signals or slots.  For the cases where this is
    more convenient in an application, QmlExpressionObject can be used instead.

    QmlExpressionObject behaves identically to QmlExpression, except that the
    QmlExpressionObject::value() method is a slot, and the
    QmlExpressionObject::valueChanged() callback is a signal.
*/
/*!
    Create a QmlExpression with the specified \a parent.

    As the expression will not have an associated QmlContext, this will be a
    null expression object and its value will always be an invalid QVariant.
*/
QmlExpressionObject::QmlExpressionObject(QObject *parent)
: QObject(parent)
{
}

/*!
    Create a QmlExpressionObject with the specified \a parent.

    The \a expression ECMAScript will be executed in the \a ctxt QmlContext.
    If specified, the \a scope object's properties will also be in scope during
    the expression's execution.
*/
QmlExpressionObject::QmlExpressionObject(QmlContext *ctxt, const QString &expression, QObject *scope, QObject *parent)
: QObject(parent), QmlExpression(ctxt, expression, scope)
{
}

/*!  \internal */
QmlExpressionObject::QmlExpressionObject(QmlContext *ctxt, void *d, QmlRefCount *rc, QObject *me)
: QmlExpression(ctxt, d, rc, me)
{
}

/*!
    Returns the value of the expression, or an invalid QVariant if the
    expression is invalid or has an error.
*/
QVariant QmlExpressionObject::value()
{
    return QmlExpression::value();
}

/*!
    \fn void QmlExpressionObject::valueChanged()

    Emitted each time the expression value changes from the last time it was
    evaluated.  The expression must have been evaluated at least once (by
    calling QmlExpressionObject::value()) before this signal will be emitted.
*/

void QmlExpressionPrivate::addLog(const QmlExpressionLog &l)
{
    if (!log)
        log = new QList<QmlExpressionLog>();
    log->append(l);
}

QmlExpressionLog::QmlExpressionLog()
{
}

QmlExpressionLog::QmlExpressionLog(const QmlExpressionLog &o)
: m_time(o.m_time),
  m_expression(o.m_expression),
  m_result(o.m_result),
  m_warnings(o.m_warnings)
{
}

QmlExpressionLog::~QmlExpressionLog()
{
}

QmlExpressionLog &QmlExpressionLog::operator=(const QmlExpressionLog &o)
{
    m_time = o.m_time;
    m_expression = o.m_expression;
    m_result = o.m_result;
    m_warnings = o.m_warnings;
    return *this;
}

void QmlExpressionLog::setTime(quint32 time)
{
    m_time = time;
}

quint32 QmlExpressionLog::time() const
{
    return m_time;
}

QString QmlExpressionLog::expression() const
{
    return m_expression;
}

void QmlExpressionLog::setExpression(const QString &e)
{
    m_expression = e;
}

QStringList QmlExpressionLog::warnings() const
{
    return m_warnings;
}

void QmlExpressionLog::addWarning(const QString &w)
{
    m_warnings << w;
}

QVariant QmlExpressionLog::result() const
{
    return m_result;
}

void QmlExpressionLog::setResult(const QVariant &r)
{
    m_result = r;
}


QT_END_NAMESPACE