1 /****************************************************************************
3 ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/
6 ** This file is part of the QtQml module of the Qt Toolkit.
8 ** $QT_BEGIN_LICENSE:LGPL$
9 ** GNU Lesser General Public License Usage
10 ** This file may be used under the terms of the GNU Lesser General Public
11 ** License version 2.1 as published by the Free Software Foundation and
12 ** appearing in the file LICENSE.LGPL included in the packaging of this
13 ** file. Please review the following information to ensure the GNU Lesser
14 ** General Public License version 2.1 requirements will be met:
15 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
17 ** In addition, as a special exception, Nokia gives you certain additional
18 ** rights. These rights are described in the Nokia Qt LGPL Exception
19 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
21 ** GNU General Public License Usage
22 ** Alternatively, this file may be used under the terms of the GNU General
23 ** Public License version 3.0 as published by the Free Software Foundation
24 ** and appearing in the file LICENSE.GPL included in the packaging of this
25 ** file. Please review the following information to ensure the GNU General
26 ** Public License version 3.0 requirements will be met:
27 ** http://www.gnu.org/copyleft/gpl.html.
30 ** Alternatively, this file may be used in accordance with the terms and
31 ** conditions contained in a signed written agreement between you and Nokia.
40 ****************************************************************************/
42 #include "qqmlvme_p.h"
44 #include "qqmlcompiler_p.h"
45 #include "qqmlboundsignal_p.h"
46 #include "qqmlstringconverters_p.h"
47 #include <private/qmetaobjectbuilder_p.h>
48 #include <private/qfastmetabuilder_p.h>
49 #include "qqmldata_p.h"
51 #include "qqmlcustomparser_p.h"
52 #include "qqmlengine.h"
53 #include "qqmlcontext.h"
54 #include "qqmlcomponent.h"
55 #include "qqmlcomponentattached_p.h"
56 #include "qqmlbinding_p.h"
57 #include "qqmlengine_p.h"
58 #include "qqmlcomponent_p.h"
59 #include "qqmlvmemetaobject_p.h"
60 #include "qqmlcontext_p.h"
61 #include <private/qv4bindings_p.h>
62 #include <private/qv8bindings_p.h>
63 #include "qqmlglobal_p.h"
64 #include <private/qfinitestack_p.h>
65 #include "qqmlscriptstring.h"
66 #include "qqmlscriptstring_p.h"
67 #include "qqmlpropertyvalueinterceptor_p.h"
68 #include "qqmlvaluetypeproxybinding_p.h"
74 #include <QtCore/qdebug.h>
75 #include <QtCore/qvarlengtharray.h>
76 #include <QtCore/qcoreapplication.h>
77 #include <QtCore/qdatetime.h>
78 #include <QtCore/qvarlengtharray.h>
79 #include <QtQml/qjsvalue.h>
83 using namespace QQmlVMETypes;
85 #define VME_EXCEPTION(desc, line) \
88 error.setDescription(desc.trimmed()); \
89 error.setLine(line); \
90 error.setUrl(COMP->url); \
95 void QQmlVME::init(QQmlContextData *ctxt, QQmlCompiledData *comp, int start,
96 QQmlContextData *creation)
104 creationContext = creation;
108 initState.context = ctxt;
109 initState.compiledData = comp;
110 initState.instructionStream = comp->bytecode.constData() + start;
111 states.push(initState);
113 typedef QQmlInstruction I;
114 I *i = (I *)initState.instructionStream;
116 Q_ASSERT(comp->instructionType(i) == I::Init);
118 objects.allocate(i->init.objectStackSize);
119 lists.allocate(i->init.listStackSize);
120 bindValues.allocate(i->init.bindingsSize);
121 parserStatus.allocate(i->init.parserStatusSize);
123 #ifdef QML_ENABLE_TRACE
124 parserStatusData.allocate(i->init.parserStatusSize);
125 rootComponent = comp;
129 engine = ctxt->engine;
132 bool QQmlVME::initDeferred(QObject *object)
134 QQmlData *data = QQmlData::get(object);
136 if (!data || !data->context || !data->deferredComponent)
139 QQmlContextData *ctxt = data->context;
140 QQmlCompiledData *comp = data->deferredComponent;
141 int start = data->deferredIdx;
144 initState.flags = State::Deferred;
145 initState.context = ctxt;
146 initState.compiledData = comp;
147 initState.instructionStream = comp->bytecode.constData() + start;
148 states.push(initState);
150 typedef QQmlInstruction I;
151 I *i = (I *)initState.instructionStream;
153 Q_ASSERT(comp->instructionType(i) == I::DeferInit);
155 objects.allocate(i->deferInit.objectStackSize);
156 lists.allocate(i->deferInit.listStackSize);
157 bindValues.allocate(i->deferInit.bindingsSize);
158 parserStatus.allocate(i->deferInit.parserStatusSize);
160 objects.push(object);
162 #ifdef QML_ENABLE_TRACE
163 parserStatusData.allocate(i->deferInit.parserStatusSize);
164 rootComponent = comp;
168 engine = ctxt->engine;
174 struct ActiveVMERestorer
176 ActiveVMERestorer(QQmlVME *me, QQmlEnginePrivate *ep)
177 : ep(ep), oldVME(ep->activeVME) { ep->activeVME = me; }
178 ~ActiveVMERestorer() { ep->activeVME = oldVME; }
180 QQmlEnginePrivate *ep;
185 QObject *QQmlVME::execute(QList<QQmlError> *errors, const Interrupt &interrupt)
187 Q_ASSERT(states.count() >= 1);
189 #ifdef QML_ENABLE_TRACE
190 QQmlTrace trace("VME Execute");
191 trace.addDetail("URL", rootComponent->url);
194 QQmlEnginePrivate *ep = QQmlEnginePrivate::get(states.at(0).context->engine);
196 ActiveVMERestorer restore(this, ep);
198 QObject *rv = run(errors, interrupt);
203 inline bool fastHasBinding(QObject *o, int index)
205 QQmlData *ddata = static_cast<QQmlData *>(QObjectPrivate::get(o)->declarativeData);
207 return ddata && (ddata->bindingBitsSize > index) &&
208 (ddata->bindingBits[index / 32] & (1 << (index % 32)));
211 static void removeBindingOnProperty(QObject *o, int index)
213 QQmlAbstractBinding *binding = QQmlPropertyPrivate::setBinding(o, index, -1, 0);
214 if (binding) binding->destroy();
217 static QVariant variantFromString(const QString &string)
219 return QQmlStringConverters::variantFromString(string);
222 // XXX we probably need some form of "work count" here to prevent us checking this
223 // for every instruction.
224 #define QML_BEGIN_INSTR_COMMON(I) { \
225 const QQmlInstructionMeta<(int)QQmlInstruction::I>::DataType &instr = QQmlInstructionMeta<(int)QQmlInstruction::I>::data(*genericInstr); \
226 INSTRUCTIONSTREAM += QQmlInstructionMeta<(int)QQmlInstruction::I>::Size; \
229 #ifdef QML_THREADED_VME_INTERPRETER
230 # define QML_BEGIN_INSTR(I) op_##I: \
231 QML_BEGIN_INSTR_COMMON(I)
233 # define QML_NEXT_INSTR(I) { \
234 if (watcher.hasRecursed()) return 0; \
235 genericInstr = reinterpret_cast<const QQmlInstruction *>(INSTRUCTIONSTREAM); \
236 goto *genericInstr->common.code; \
239 # define QML_END_INSTR(I) } \
240 if (watcher.hasRecursed()) return 0; \
241 genericInstr = reinterpret_cast<const QQmlInstruction *>(INSTRUCTIONSTREAM); \
242 if (interrupt.shouldInterrupt()) return 0; \
243 goto *genericInstr->common.code;
246 # define QML_BEGIN_INSTR(I) \
247 case QQmlInstruction::I: \
248 QML_BEGIN_INSTR_COMMON(I)
250 # define QML_NEXT_INSTR(I) { \
251 if (watcher.hasRecursed()) return 0; \
255 # define QML_END_INSTR(I) \
256 if (watcher.hasRecursed() || interrupt.shouldInterrupt()) return 0; \
260 #define QML_STORE_VALUE(name, cpptype, value) \
261 QML_BEGIN_INSTR(name) \
263 void *a[] = { (void *)&v, 0, &status, &flags }; \
264 QObject *target = objects.top(); \
265 CLEAN_PROPERTY(target, instr.propertyIndex); \
266 QMetaObject::metacall(target, QMetaObject::WriteProperty, instr.propertyIndex, a); \
269 #define QML_STORE_PROVIDER_VALUE(name, type, value) \
270 QML_BEGIN_INSTR(name) \
271 struct { void *data[4]; } buffer; \
272 if (QQml_valueTypeProvider()->storeValueType(type, &value, &buffer, sizeof(buffer))) { \
273 void *a[] = { reinterpret_cast<void *>(&buffer), 0, &status, &flags }; \
274 QObject *target = objects.top(); \
275 CLEAN_PROPERTY(target, instr.propertyIndex); \
276 QMetaObject::metacall(target, QMetaObject::WriteProperty, instr.propertyIndex, a); \
280 #define QML_STORE_LIST(name, cpptype, value) \
281 QML_BEGIN_INSTR(name) \
284 void *a[] = { (void *)&v, 0, &status, &flags }; \
285 QObject *target = objects.top(); \
286 CLEAN_PROPERTY(target, instr.propertyIndex); \
287 QMetaObject::metacall(target, QMetaObject::WriteProperty, instr.propertyIndex, a); \
290 #define QML_STORE_VAR(name, value) \
291 QML_BEGIN_INSTR(name) \
292 v8::Handle<v8::Value> v8value = value; \
293 QObject *target = objects.top(); \
294 CLEAN_PROPERTY(target, instr.propertyIndex); \
295 QMetaObject *mo = const_cast<QMetaObject *>(target->metaObject()); \
296 QQmlVMEMetaObject *vmemo = static_cast<QQmlVMEMetaObject *>(mo); \
297 vmemo->setVMEProperty(instr.propertyIndex, v8value); \
300 #define QML_STORE_POINTER(name, value) \
301 QML_BEGIN_INSTR(name) \
302 void *a[] = { (void *)value, 0, &status, &flags }; \
303 QObject *target = objects.top(); \
304 CLEAN_PROPERTY(target, instr.propertyIndex); \
305 QMetaObject::metacall(target, QMetaObject::WriteProperty, instr.propertyIndex, a); \
308 #define CLEAN_PROPERTY(o, index) \
309 if (fastHasBinding(o, index)) \
310 removeBindingOnProperty(o, index)
312 QObject *QQmlVME::run(QList<QQmlError> *errors,
313 const Interrupt &interrupt
314 #ifdef QML_THREADED_VME_INTERPRETER
315 , void ***storeJumpTable
319 #ifdef QML_THREADED_VME_INTERPRETER
320 if (storeJumpTable) {
321 #define QML_INSTR_ADDR(I, FMT) &&op_##I,
322 static void *jumpTable[] = {
323 FOR_EACH_QML_INSTR(QML_INSTR_ADDR)
325 #undef QML_INSTR_ADDR
326 *storeJumpTable = jumpTable;
330 Q_ASSERT(errors->isEmpty());
331 Q_ASSERT(states.count() >= 1);
333 QQmlEngine *engine = states.at(0).context->engine;
334 QQmlEnginePrivate *ep = QQmlEnginePrivate::get(engine);
336 // Need a v8 handle scope and execution context for StoreVar instructions.
337 v8::HandleScope handleScope;
338 v8::Context::Scope contextScope(ep->v8engine()->context());
340 int status = -1; // needed for dbus
341 QQmlPropertyPrivate::WriteFlags flags = QQmlPropertyPrivate::BypassInterceptor |
342 QQmlPropertyPrivate::RemoveBindingOnAliasWrite;
344 QRecursionWatcher<QQmlVME, &QQmlVME::recursion> watcher(this);
346 #define COMP states.top().compiledData
347 #define CTXT states.top().context
348 #define INSTRUCTIONSTREAM states.top().instructionStream
349 #define BINDINGSKIPLIST states.top().bindingSkipList
351 #define TYPES COMP->types
352 #define PRIMITIVES COMP->primitives
353 #define DATAS COMP->datas
354 #define PROGRAMS COMP->programs
355 #define PROPERTYCACHES COMP->propertyCaches
356 #define SCRIPTS COMP->scripts
357 #define URLS COMP->urls
359 #ifdef QML_THREADED_VME_INTERPRETER
360 const QQmlInstruction *genericInstr = reinterpret_cast<const QQmlInstruction *>(INSTRUCTIONSTREAM);
361 goto *genericInstr->common.code;
364 const QQmlInstruction *genericInstr = reinterpret_cast<const QQmlInstruction *>(INSTRUCTIONSTREAM);
366 switch (genericInstr->common.instructionType) {
369 // Store a created object in a property. These all pop from the objects stack.
370 QML_STORE_VALUE(StoreObject, QObject *, objects.pop());
371 QML_STORE_VALUE(StoreVariantObject, QVariant, QVariant::fromValue(objects.pop()));
372 QML_STORE_VAR(StoreVarObject, ep->v8engine()->newQObject(objects.pop()));
374 // Store a literal value in a corresponding property
375 QML_STORE_VALUE(StoreFloat, float, instr.value);
376 QML_STORE_VALUE(StoreDouble, double, instr.value);
377 QML_STORE_VALUE(StoreBool, bool, instr.value);
378 QML_STORE_VALUE(StoreInteger, int, instr.value);
379 QML_STORE_PROVIDER_VALUE(StoreColor, QMetaType::QColor, instr.value);
380 QML_STORE_VALUE(StoreDate, QDate, QDate::fromJulianDay(instr.value));
381 QML_STORE_VALUE(StoreDateTime, QDateTime,
382 QDateTime(QDate::fromJulianDay(instr.date), *(QTime *)&instr.time));
383 QML_STORE_POINTER(StoreTime, (QTime *)&instr.time);
384 QML_STORE_POINTER(StorePoint, (QPoint *)&instr.point);
385 QML_STORE_POINTER(StorePointF, (QPointF *)&instr.point);
386 QML_STORE_POINTER(StoreSize, (QSize *)&instr.size);
387 QML_STORE_POINTER(StoreSizeF, (QSizeF *)&instr.size);
388 QML_STORE_POINTER(StoreRect, (QRect *)&instr.rect);
389 QML_STORE_POINTER(StoreRectF, (QRectF *)&instr.rect);
390 QML_STORE_PROVIDER_VALUE(StoreVector3D, QMetaType::QVector3D, instr.vector);
391 QML_STORE_PROVIDER_VALUE(StoreVector4D, QMetaType::QVector4D, instr.vector);
392 QML_STORE_POINTER(StoreString, &PRIMITIVES.at(instr.value));
393 QML_STORE_POINTER(StoreByteArray, &DATAS.at(instr.value));
394 QML_STORE_POINTER(StoreUrl, &URLS.at(instr.value));
395 QML_STORE_VALUE(StoreTrString, QString,
396 QCoreApplication::translate(DATAS.at(instr.context).constData(),
397 DATAS.at(instr.text).constData(),
398 DATAS.at(instr.comment).constData(),
399 QCoreApplication::UnicodeUTF8,
401 QML_STORE_VALUE(StoreTrIdString, QString, qtTrId(DATAS.at(instr.text).constData(), instr.n));
403 // Store a literal value in a QList
404 QML_STORE_LIST(StoreStringList, QStringList, PRIMITIVES.at(instr.value));
405 QML_STORE_LIST(StoreStringQList, QList<QString>, PRIMITIVES.at(instr.value));
406 QML_STORE_LIST(StoreUrlQList, QList<QUrl>, URLS.at(instr.value));
407 QML_STORE_LIST(StoreDoubleQList, QList<double>, instr.value);
408 QML_STORE_LIST(StoreBoolQList, QList<bool>, instr.value);
409 QML_STORE_LIST(StoreIntegerQList, QList<int>, instr.value);
411 // Store a literal value in a QVariant property
412 QML_STORE_VALUE(StoreVariant, QVariant, variantFromString(PRIMITIVES.at(instr.value)));
413 QML_STORE_VALUE(StoreVariantInteger, QVariant, QVariant(instr.value));
414 QML_STORE_VALUE(StoreVariantDouble, QVariant, QVariant(instr.value));
415 QML_STORE_VALUE(StoreVariantBool, QVariant, QVariant(instr.value));
417 // Store a literal value in a var property.
418 // We deliberately do not use string converters here
419 QML_STORE_VAR(StoreVar, ep->v8engine()->fromVariant(PRIMITIVES.at(instr.value)));
420 QML_STORE_VAR(StoreVarInteger, v8::Integer::New(instr.value));
421 QML_STORE_VAR(StoreVarDouble, v8::Number::New(instr.value));
422 QML_STORE_VAR(StoreVarBool, v8::Boolean::New(instr.value));
425 QML_BEGIN_INSTR(Init)
426 // Ensure that the compiled data has been initialized
427 if (!COMP->isInitialized()) COMP->initialize(engine);
429 QQmlContextData *parentCtxt = CTXT;
430 CTXT = new QQmlContextData;
431 CTXT->isInternal = true;
432 CTXT->url = COMP->url;
433 CTXT->urlString = COMP->name;
434 CTXT->imports = COMP->importCache;
435 CTXT->imports->addref();
436 CTXT->setParent(parentCtxt);
437 if (instr.contextCache != -1)
438 CTXT->setIdPropertyData(COMP->contextCaches.at(instr.contextCache));
439 if (instr.compiledBinding != -1) {
440 const char *v4data = DATAS.at(instr.compiledBinding).constData();
441 CTXT->v4bindings = new QV4Bindings(v4data, CTXT, COMP);
443 if (states.count() == 1) {
445 rootContext->activeVMEData = data;
447 if (states.count() == 1 && !creationContext.isNull()) {
448 // A component that is logically created within another component instance shares the
449 // same instances of script imports. For example:
451 // import QtQuick 2.0
452 // import "test.js" as Test
454 // model: Test.getModel()
455 // delegate: Component {
456 // Text { text: Test.getValue(index); }
460 // Has the same "Test" instance. To implement this, we simply copy the v8 handles into
461 // the inner context. We have to create a fresh persistent handle for each to prevent
462 // double dispose. It is possible we could do this more efficiently using some form of
463 // referencing instead.
464 CTXT->importedScripts = creationContext->importedScripts;
465 for (int ii = 0; ii < CTXT->importedScripts.count(); ++ii)
466 CTXT->importedScripts[ii] = qPersistentNew<v8::Object>(CTXT->importedScripts[ii]);
470 QML_BEGIN_INSTR(DeferInit)
471 QML_END_INSTR(DeferInit)
473 QML_BEGIN_INSTR(Done)
476 if (states.isEmpty())
480 QML_BEGIN_INSTR(CreateQMLObject)
481 const QQmlCompiledData::TypeReference &type = TYPES.at(instr.type);
482 Q_ASSERT(type.component);
484 states.push(State());
486 State *cState = &states[states.count() - 2];
487 State *nState = &states[states.count() - 1];
489 nState->context = cState->context;
490 nState->compiledData = type.component;
491 nState->instructionStream = type.component->bytecode.constData();
493 if (instr.bindingBits != -1) {
494 const QByteArray &bits = cState->compiledData->datas.at(instr.bindingBits);
495 nState->bindingSkipList = QBitField((const quint32*)bits.constData(),
499 nState->bindingSkipList = nState->bindingSkipList.united(cState->bindingSkipList);
501 // As the state in the state stack changed, execution will continue in the new program.
502 QML_END_INSTR(CreateQMLObject)
504 QML_BEGIN_INSTR(CompleteQMLObject)
505 QObject *o = objects.top();
507 QQmlData *ddata = QQmlData::get(o);
511 if (ddata->context) {
512 Q_ASSERT(ddata->context != CTXT);
513 Q_ASSERT(ddata->outerContext);
514 Q_ASSERT(ddata->outerContext != CTXT);
515 QQmlContextData *c = ddata->context;
516 while (c->linkedContext) c = c->linkedContext;
517 c->linkedContext = CTXT;
522 ddata->ownContext = true;
523 } else if (!ddata->context) {
527 ddata->setImplicitDestructible();
528 ddata->outerContext = CTXT;
529 ddata->lineNumber = instr.line;
530 ddata->columnNumber = instr.column;
531 QML_END_INSTR(CompleteQMLObject)
533 QML_BEGIN_INSTR(CreateCppObject)
534 const QQmlCompiledData::TypeReference &type = TYPES.at(instr.type);
539 type.type->create(&o, &memory, sizeof(QQmlData));
540 QQmlData *ddata = new (memory) QQmlData;
541 ddata->ownMemory = false;
542 QObjectPrivate::get(o)->declarativeData = ddata;
544 if (type.typePropertyCache && !ddata->propertyCache) {
545 ddata->propertyCache = type.typePropertyCache;
546 ddata->propertyCache->addref();
550 VME_EXCEPTION(tr("Unable to create object of type %1").arg(type.className), instr.line);
553 if (ddata->context) {
554 Q_ASSERT(ddata->context != CTXT);
555 Q_ASSERT(ddata->outerContext);
556 Q_ASSERT(ddata->outerContext != CTXT);
557 QQmlContextData *c = ddata->context;
558 while (c->linkedContext) c = c->linkedContext;
559 c->linkedContext = CTXT;
564 ddata->ownContext = true;
565 } else if (!ddata->context) {
569 ddata->setImplicitDestructible();
570 ddata->outerContext = CTXT;
571 ddata->lineNumber = instr.line;
572 ddata->columnNumber = instr.column;
574 if (instr.data != -1) {
575 QQmlCustomParser *customParser =
576 TYPES.at(instr.type).type->customParser();
577 customParser->setCustomData(o, DATAS.at(instr.data));
579 if (!objects.isEmpty()) {
580 QObject *parent = objects.top();
581 #if 0 // ### refactor
582 if (o->isWidgetType() && parent->isWidgetType())
583 static_cast<QWidget*>(o)->setParent(static_cast<QWidget*>(parent));
586 QQml_setParent_noEvent(o, parent);
589 QML_END_INSTR(CreateCppObject)
591 QML_BEGIN_INSTR(CreateSimpleObject)
592 QObject *o = (QObject *)operator new(instr.typeSize + sizeof(QQmlData));
593 ::memset(o, 0, instr.typeSize + sizeof(QQmlData));
596 QQmlData *ddata = (QQmlData *)(((const char *)o) + instr.typeSize);
597 const QQmlCompiledData::TypeReference &ref = TYPES.at(instr.type);
598 if (!ddata->propertyCache && ref.typePropertyCache) {
599 ddata->propertyCache = ref.typePropertyCache;
600 ddata->propertyCache->addref();
602 ddata->lineNumber = instr.line;
603 ddata->columnNumber = instr.column;
605 QObjectPrivate::get(o)->declarativeData = ddata;
606 ddata->context = ddata->outerContext = CTXT;
607 ddata->nextContextObject = CTXT->contextObjects;
608 if (ddata->nextContextObject)
609 ddata->nextContextObject->prevContextObject = &ddata->nextContextObject;
610 ddata->prevContextObject = &CTXT->contextObjects;
611 CTXT->contextObjects = ddata;
613 QObject *parent = objects.top();
614 QQml_setParent_noEvent(o, parent);
617 QML_END_INSTR(CreateSimpleObject)
619 QML_BEGIN_INSTR(SetId)
620 QObject *target = objects.top();
621 CTXT->setIdProperty(instr.index, target);
624 QML_BEGIN_INSTR(SetDefault)
625 CTXT->contextObject = objects.top();
626 QML_END_INSTR(SetDefault)
628 QML_BEGIN_INSTR(CreateComponent)
629 QQmlComponent *qcomp =
630 new QQmlComponent(CTXT->engine, COMP, INSTRUCTIONSTREAM - COMP->bytecode.constData(),
631 objects.isEmpty() ? 0 : objects.top());
633 QQmlData *ddata = QQmlData::get(qcomp, true);
636 CTXT->addObject(qcomp);
639 ddata->ownContext = true;
641 ddata->setImplicitDestructible();
642 ddata->outerContext = CTXT;
643 ddata->lineNumber = instr.line;
644 ddata->columnNumber = instr.column;
646 QQmlComponentPrivate::get(qcomp)->creationContext = CTXT;
649 INSTRUCTIONSTREAM += instr.count;
650 QML_END_INSTR(CreateComponent)
652 QML_BEGIN_INSTR(StoreMetaObject)
653 QObject *target = objects.top();
656 const QByteArray &metadata = DATAS.at(instr.data);
657 QFastMetaBuilder::fromData(&mo, 0, metadata);
659 const QQmlVMEMetaData *data =
660 (const QQmlVMEMetaData *)DATAS.at(instr.aliasData).constData();
662 (void)new QQmlVMEMetaObject(target, &mo, data, COMP);
664 if (instr.propertyCache != -1) {
665 QQmlData *ddata = QQmlData::get(target, true);
666 if (ddata->propertyCache) ddata->propertyCache->release();
667 ddata->propertyCache = PROPERTYCACHES.at(instr.propertyCache);
668 ddata->propertyCache->addref();
670 QML_END_INSTR(StoreMetaObject)
672 QML_BEGIN_INSTR(AssignCustomType)
673 QObject *target = objects.top();
674 CLEAN_PROPERTY(target, instr.propertyIndex);
676 const QString &primitive = PRIMITIVES.at(instr.primitive);
677 int type = instr.type;
678 QQmlMetaType::StringConverter converter = QQmlMetaType::customStringConverter(type);
679 QVariant v = (*converter)(primitive);
682 target->metaObject()->property(instr.propertyIndex);
683 if (v.isNull() || ((int)prop.type() != type && prop.userType() != type))
684 VME_EXCEPTION(tr("Cannot assign value %1 to property %2").arg(primitive).arg(QString::fromUtf8(prop.name())), instr.line);
686 void *a[] = { (void *)v.data(), 0, &status, &flags };
687 QMetaObject::metacall(target, QMetaObject::WriteProperty,
688 instr.propertyIndex, a);
689 QML_END_INSTR(AssignCustomType)
691 QML_BEGIN_INSTR(AssignSignalObject)
694 QObject *assign = objects.pop();
695 QObject *target = objects.top();
696 int sigIdx = instr.signal;
697 const QString &pr = PRIMITIVES.at(sigIdx);
699 QQmlProperty prop(target, pr);
700 if (prop.type() & QQmlProperty::SignalProperty) {
702 QMetaMethod method = QQmlMetaType::defaultMethod(assign);
703 if (!method.isValid())
704 VME_EXCEPTION(tr("Cannot assign object type %1 with no default method").arg(QString::fromLatin1(assign->metaObject()->className())), instr.line);
706 if (!QMetaObject::checkConnectArgs(prop.method(), method)) {
707 VME_EXCEPTION(tr("Cannot connect mismatched signal/slot %1 %vs. %2")
708 .arg(QString::fromLatin1(method.methodSignature().constData()))
709 .arg(QString::fromLatin1(prop.method().methodSignature().constData())), instr.line);
712 QQmlPropertyPrivate::connect(target, prop.index(), assign, method.methodIndex());
715 VME_EXCEPTION(tr("Cannot assign an object to signal property %1").arg(pr), instr.line);
719 QML_END_INSTR(AssignSignalObject)
721 QML_BEGIN_INSTR(StoreSignal)
722 QObject *target = objects.top();
723 QObject *context = objects.at(objects.count() - 1 - instr.context);
725 QMetaMethod signal = target->metaObject()->method(instr.signalIndex);
727 QQmlBoundSignal *bs = new QQmlBoundSignal(target, signal, target);
728 QQmlExpression *expr =
729 new QQmlExpression(CTXT, context, DATAS.at(instr.value), true, COMP->name, instr.line, instr.column, *new QQmlExpressionPrivate);
730 bs->setExpression(expr);
731 QML_END_INSTR(StoreSignal)
733 QML_BEGIN_INSTR(StoreImportedScript)
734 CTXT->importedScripts << run(CTXT, SCRIPTS.at(instr.value));
735 QML_END_INSTR(StoreImportedScript)
737 QML_BEGIN_INSTR(StoreScriptString)
738 QObject *target = objects.top();
739 QObject *scope = objects.at(objects.count() - 1 - instr.scope);
741 ss.setContext(CTXT->asQQmlContext());
742 ss.setScopeObject(scope);
743 ss.setScript(PRIMITIVES.at(instr.value));
744 ss.d.data()->bindingId = instr.bindingId;
745 ss.d.data()->lineNumber = instr.line;
746 ss.d.data()->columnNumber = instr.column;
748 void *a[] = { &ss, 0, &status, &flags };
749 QMetaObject::metacall(target, QMetaObject::WriteProperty,
750 instr.propertyIndex, a);
751 QML_END_INSTR(StoreScriptString)
753 QML_BEGIN_INSTR(BeginObject)
754 QObject *target = objects.top();
755 QQmlParserStatus *status = reinterpret_cast<QQmlParserStatus *>(reinterpret_cast<char *>(target) + instr.castValue);
756 parserStatus.push(status);
757 #ifdef QML_ENABLE_TRACE
758 Q_ASSERT(QObjectPrivate::get(target)->declarativeData);
759 parserStatusData.push(static_cast<QQmlData *>(QObjectPrivate::get(target)->declarativeData));
761 status->d = &parserStatus.top();
763 status->classBegin();
764 QML_END_INSTR(BeginObject)
766 QML_BEGIN_INSTR(InitV8Bindings)
767 CTXT->v8bindings = new QV8Bindings(&PROGRAMS[instr.programIndex], instr.line, CTXT);
768 QML_END_INSTR(InitV8Bindings)
770 QML_BEGIN_INSTR(StoreBinding)
772 objects.at(objects.count() - 1 - instr.owner);
774 objects.at(objects.count() - 1 - instr.context);
776 if (instr.isRoot && BINDINGSKIPLIST.testBit(instr.property.coreIndex))
777 QML_NEXT_INSTR(StoreBinding);
779 QQmlBinding *bind = new QQmlBinding(PRIMITIVES.at(instr.value), true,
780 context, CTXT, COMP->name, instr.line,
782 bindValues.push(bind);
783 bind->m_mePtr = &bindValues.top();
784 bind->setTarget(target, instr.property, CTXT);
786 typedef QQmlPropertyPrivate QDPP;
787 Q_ASSERT(bind->propertyIndex() == QDPP::bindingIndex(instr.property));
788 Q_ASSERT(bind->object() == target);
791 QML_END_INSTR(StoreBinding)
793 QML_BEGIN_INSTR(StoreBindingOnAlias)
795 objects.at(objects.count() - 1 - instr.owner);
797 objects.at(objects.count() - 1 - instr.context);
799 if (instr.isRoot && BINDINGSKIPLIST.testBit(instr.property.coreIndex))
800 QML_NEXT_INSTR(StoreBindingOnAlias);
802 QQmlBinding *bind = new QQmlBinding(PRIMITIVES.at(instr.value), true,
803 context, CTXT, COMP->name, instr.line,
805 bindValues.push(bind);
806 bind->m_mePtr = &bindValues.top();
807 bind->setTarget(target, instr.property, CTXT);
809 QQmlAbstractBinding *old =
810 QQmlPropertyPrivate::setBindingNoEnable(target, instr.property.coreIndex,
811 instr.property.getValueTypeCoreIndex(),
813 if (old) { old->destroy(); }
814 QML_END_INSTR(StoreBindingOnAlias)
816 QML_BEGIN_INSTR(StoreV4Binding)
818 objects.at(objects.count() - 1 - instr.owner);
820 objects.at(objects.count() - 1 - instr.context);
822 int property = instr.property;
823 if (instr.isRoot && BINDINGSKIPLIST.testBit(property & 0xFFFF))
824 QML_NEXT_INSTR(StoreV4Binding);
826 QQmlAbstractBinding *binding =
827 CTXT->v4bindings->configBinding(instr.value, target, scope, property,
828 instr.line, instr.column);
829 bindValues.push(binding);
830 binding->m_mePtr = &bindValues.top();
832 Q_ASSERT(binding->propertyIndex() == (property & 0xFF00FFFF));
833 Q_ASSERT(binding->object() == target);
835 binding->addToObject();
836 QML_END_INSTR(StoreV4Binding)
838 QML_BEGIN_INSTR(StoreV8Binding)
840 objects.at(objects.count() - 1 - instr.owner);
842 objects.at(objects.count() - 1 - instr.context);
844 if (instr.isRoot && BINDINGSKIPLIST.testBit(instr.property.coreIndex))
845 QML_NEXT_INSTR(StoreV8Binding);
847 QQmlAbstractBinding *binding = CTXT->v8bindings->configBinding(target, scope,
850 bindValues.push(binding);
851 binding->m_mePtr = &bindValues.top();
853 typedef QQmlPropertyPrivate QDPP;
854 Q_ASSERT(binding->propertyIndex() == QDPP::bindingIndex(instr.property));
855 Q_ASSERT(binding->object() == target);
857 binding->addToObject();
859 QML_END_INSTR(StoreV8Binding)
861 QML_BEGIN_INSTR(StoreValueSource)
862 QObject *obj = objects.pop();
863 QQmlPropertyValueSource *vs = reinterpret_cast<QQmlPropertyValueSource *>(reinterpret_cast<char *>(obj) + instr.castValue);
864 QObject *target = objects.at(objects.count() - 1 - instr.owner);
866 obj->setParent(target);
867 vs->setTarget(QQmlPropertyPrivate::restore(target, instr.property, CTXT));
868 QML_END_INSTR(StoreValueSource)
870 QML_BEGIN_INSTR(StoreValueInterceptor)
871 QObject *obj = objects.pop();
872 QQmlPropertyValueInterceptor *vi = reinterpret_cast<QQmlPropertyValueInterceptor *>(reinterpret_cast<char *>(obj) + instr.castValue);
873 QObject *target = objects.at(objects.count() - 1 - instr.owner);
875 QQmlPropertyPrivate::restore(target, instr.property, CTXT);
876 obj->setParent(target);
878 QQmlVMEMetaObject *mo = static_cast<QQmlVMEMetaObject *>((QMetaObject*)target->metaObject());
879 mo->registerInterceptor(prop.index(), QQmlPropertyPrivate::valueTypeCoreIndex(prop), vi);
880 QML_END_INSTR(StoreValueInterceptor)
882 QML_BEGIN_INSTR(StoreObjectQList)
883 QObject *assign = objects.pop();
885 const List &list = lists.top();
886 list.qListProperty.append((QQmlListProperty<void>*)&list.qListProperty, assign);
887 QML_END_INSTR(StoreObjectQList)
889 QML_BEGIN_INSTR(AssignObjectList)
890 // This is only used for assigning interfaces
891 QObject *assign = objects.pop();
892 const List &list = lists.top();
894 int type = list.type;
898 const char *iid = QQmlMetaType::interfaceIId(type);
900 ptr = assign->qt_metacast(iid);
902 VME_EXCEPTION(tr("Cannot assign object to list"), instr.line);
905 list.qListProperty.append((QQmlListProperty<void>*)&list.qListProperty, ptr);
906 QML_END_INSTR(AssignObjectList)
908 QML_BEGIN_INSTR(StoreInterface)
909 QObject *assign = objects.pop();
910 QObject *target = objects.top();
911 CLEAN_PROPERTY(target, instr.propertyIndex);
913 int coreIdx = instr.propertyIndex;
914 QMetaProperty prop = target->metaObject()->property(coreIdx);
915 int t = prop.userType();
916 const char *iid = QQmlMetaType::interfaceIId(t);
919 void *ptr = assign->qt_metacast(iid);
921 void *a[] = { &ptr, 0, &status, &flags };
922 QMetaObject::metacall(target,
923 QMetaObject::WriteProperty,
930 VME_EXCEPTION(tr("Cannot assign object to interface property"), instr.line);
931 QML_END_INSTR(StoreInterface)
933 QML_BEGIN_INSTR(FetchAttached)
934 QObject *target = objects.top();
936 QObject *qmlObject = qmlAttachedPropertiesObjectById(instr.id, target);
939 VME_EXCEPTION(tr("Unable to create attached object"), instr.line);
941 objects.push(qmlObject);
942 QML_END_INSTR(FetchAttached)
944 QML_BEGIN_INSTR(FetchQList)
945 QObject *target = objects.top();
947 lists.push(List(instr.type));
950 a[0] = (void *)&(lists.top().qListProperty);
951 QMetaObject::metacall(target, QMetaObject::ReadProperty,
953 QML_END_INSTR(FetchQList)
955 QML_BEGIN_INSTR(FetchObject)
956 QObject *target = objects.top();
959 // NOTE: This assumes a cast to QObject does not alter the
963 QMetaObject::metacall(target, QMetaObject::ReadProperty,
967 VME_EXCEPTION(tr("Cannot set properties on %1 as it is null").arg(QString::fromUtf8(target->metaObject()->property(instr.property).name())), instr.line);
970 QML_END_INSTR(FetchObject)
972 QML_BEGIN_INSTR(PopQList)
974 QML_END_INSTR(PopQList)
976 QML_BEGIN_INSTR(Defer)
977 if (instr.deferCount) {
978 QObject *target = objects.top();
980 QQmlData::get(target, true);
982 data->deferredComponent = COMP;
983 data->deferredIdx = INSTRUCTIONSTREAM - COMP->bytecode.constData();
984 INSTRUCTIONSTREAM += instr.deferCount;
988 QML_BEGIN_INSTR(PopFetchedObject)
990 QML_END_INSTR(PopFetchedObject)
992 QML_BEGIN_INSTR(FetchValueType)
993 QObject *target = objects.top();
995 if (instr.bindingSkipList != 0) {
996 // Possibly need to clear bindings
997 QQmlData *targetData = QQmlData::get(target);
999 QQmlAbstractBinding *binding =
1000 QQmlPropertyPrivate::binding(target, instr.property, -1);
1002 if (binding && binding->bindingType() != QQmlAbstractBinding::ValueTypeProxy) {
1003 QQmlPropertyPrivate::setBinding(target, instr.property, -1, 0);
1005 } else if (binding) {
1006 QQmlValueTypeProxyBinding *proxy =
1007 static_cast<QQmlValueTypeProxyBinding *>(binding);
1008 proxy->removeBindings(instr.bindingSkipList);
1013 QQmlValueType *valueHandler = ep->valueTypes[instr.type];
1014 valueHandler->read(target, instr.property);
1015 objects.push(valueHandler);
1016 QML_END_INSTR(FetchValueType)
1018 QML_BEGIN_INSTR(PopValueType)
1019 QQmlValueType *valueHandler =
1020 static_cast<QQmlValueType *>(objects.pop());
1021 QObject *target = objects.top();
1022 valueHandler->write(target, instr.property, QQmlPropertyPrivate::BypassInterceptor);
1023 QML_END_INSTR(PopValueType)
1025 #ifdef QML_THREADED_VME_INTERPRETER
1029 qFatal("QQmlCompiledData: Internal error - unknown instruction %d", genericInstr->common.instructionType);
1036 Q_ASSERT(!states.isEmpty());
1037 Q_ASSERT(!errors->isEmpty());
1044 Q_ASSERT(objects.count() == 1);
1046 QObject *rv = objects.top();
1048 objects.deallocate();
1055 void QQmlVME::reset()
1057 Q_ASSERT(!states.isEmpty() || objects.isEmpty());
1059 QRecursionWatcher<QQmlVME, &QQmlVME::recursion> watcher(this);
1061 if (!objects.isEmpty() && !(states.at(0).flags & State::Deferred))
1062 delete objects.at(0);
1064 if (!rootContext.isNull())
1065 rootContext->activeVMEData = 0;
1067 // Remove the QQmlParserStatus and QQmlAbstractBinding back pointers
1068 blank(parserStatus);
1071 while (componentAttached) {
1072 QQmlComponentAttached *a = componentAttached;
1077 objects.deallocate();
1079 bindValues.deallocate();
1080 parserStatus.deallocate();
1081 #ifdef QML_ENABLE_TRACE
1082 parserStatusData.deallocate();
1084 finalizeCallbacks.clear();
1087 creationContext = 0;
1090 // Must be called with a handle scope and context
1091 void QQmlScriptData::initialize(QQmlEngine *engine)
1093 Q_ASSERT(m_program.IsEmpty());
1095 Q_ASSERT(!hasEngine());
1097 QQmlEnginePrivate *ep = QQmlEnginePrivate::get(engine);
1098 QV8Engine *v8engine = ep->v8engine();
1100 // If compilation throws an error, a surrounding v8::TryCatch will record it.
1101 v8::Local<v8::Script> program = v8engine->qmlModeCompile(m_programSource.constData(),
1102 m_programSource.length(), urlString, 1);
1103 if (program.IsEmpty())
1106 m_program = qPersistentNew<v8::Script>(program);
1107 m_programSource.clear(); // We don't need this anymore
1109 addToEngine(engine);
1114 v8::Persistent<v8::Object> QQmlVME::run(QQmlContextData *parentCtxt, QQmlScriptData *script)
1116 if (script->m_loaded)
1117 return qPersistentNew<v8::Object>(script->m_value);
1119 Q_ASSERT(parentCtxt && parentCtxt->engine);
1120 QQmlEnginePrivate *ep = QQmlEnginePrivate::get(parentCtxt->engine);
1121 QV8Engine *v8engine = ep->v8engine();
1123 bool shared = script->pragmas & QQmlScript::Object::ScriptBlock::Shared;
1125 QQmlContextData *effectiveCtxt = parentCtxt;
1129 // Create the script context if required
1130 QQmlContextData *ctxt = new QQmlContextData;
1131 ctxt->isInternal = true;
1132 ctxt->isJSContext = true;
1134 ctxt->isPragmaLibraryContext = true;
1136 ctxt->isPragmaLibraryContext = parentCtxt->isPragmaLibraryContext;
1137 ctxt->url = script->url;
1138 ctxt->urlString = script->urlString;
1140 // For backward compatibility, if there are no imports, we need to use the
1141 // imports from the parent context. See QTBUG-17518.
1142 if (!script->importCache->isEmpty()) {
1143 ctxt->imports = script->importCache;
1144 } else if (effectiveCtxt) {
1145 ctxt->imports = effectiveCtxt->imports;
1146 ctxt->importedScripts = effectiveCtxt->importedScripts;
1147 for (int ii = 0; ii < ctxt->importedScripts.count(); ++ii)
1148 ctxt->importedScripts[ii] = qPersistentNew<v8::Object>(ctxt->importedScripts[ii]);
1151 if (ctxt->imports) {
1152 ctxt->imports->addref();
1155 if (effectiveCtxt) {
1156 ctxt->setParent(effectiveCtxt, true);
1158 ctxt->engine = parentCtxt->engine; // Fix for QTBUG-21620
1161 for (int ii = 0; ii < script->scripts.count(); ++ii) {
1162 ctxt->importedScripts << run(ctxt, script->scripts.at(ii)->scriptData());
1165 v8::HandleScope handle_scope;
1166 v8::Context::Scope scope(v8engine->context());
1168 v8::TryCatch try_catch;
1169 if (!script->isInitialized())
1170 script->initialize(parentCtxt->engine);
1172 v8::Local<v8::Object> qmlglobal = v8engine->qmlScope(ctxt, 0);
1174 if (!script->m_program.IsEmpty()) {
1175 script->m_program->Run(qmlglobal);
1177 // Compilation failed.
1178 Q_ASSERT(try_catch.HasCaught());
1181 v8::Persistent<v8::Object> rv;
1183 if (try_catch.HasCaught()) {
1184 v8::Local<v8::Message> message = try_catch.Message();
1185 if (!message.IsEmpty()) {
1187 QQmlExpressionPrivate::exceptionToError(message, error);
1192 rv = qPersistentNew<v8::Object>(qmlglobal);
1194 script->m_value = qPersistentNew<v8::Object>(qmlglobal);
1195 script->m_loaded = true;
1201 #ifdef QML_THREADED_VME_INTERPRETER
1202 void **QQmlVME::instructionJumpTable()
1204 static void **jumpTable = 0;
1207 QQmlVME::Interrupt i;
1208 dummy.run(0, i, &jumpTable);
1214 QQmlContextData *QQmlVME::complete(const Interrupt &interrupt)
1217 (bindValues.isEmpty() &&
1218 parserStatus.isEmpty() &&
1219 componentAttached == 0 &&
1220 rootContext.isNull() &&
1221 finalizeCallbacks.isEmpty()));
1226 QQmlTrace trace("VME Complete");
1227 #ifdef QML_ENABLE_TRACE
1228 trace.addDetail("URL", rootComponent->url);
1231 ActiveVMERestorer restore(this, QQmlEnginePrivate::get(engine));
1232 QRecursionWatcher<QQmlVME, &QQmlVME::recursion> watcher(this);
1235 QQmlTrace trace("VME Binding Enable");
1236 trace.event("begin binding eval");
1237 while (!bindValues.isEmpty()) {
1238 QQmlAbstractBinding *b = bindValues.pop();
1242 b->setEnabled(true, QQmlPropertyPrivate::BypassInterceptor |
1243 QQmlPropertyPrivate::DontRemoveBinding);
1246 if (watcher.hasRecursed() || interrupt.shouldInterrupt())
1249 bindValues.deallocate();
1253 QQmlTrace trace("VME Component Complete");
1254 while (!parserStatus.isEmpty()) {
1255 QQmlParserStatus *status = parserStatus.pop();
1256 #ifdef QML_ENABLE_TRACE
1257 QQmlData *data = parserStatusData.pop();
1260 if (status && status->d) {
1262 #ifdef QML_ENABLE_TRACE
1263 QQmlTrace trace("Component complete");
1264 trace.addDetail("URL", data->outerContext->url);
1265 trace.addDetail("Line", data->lineNumber);
1267 status->componentComplete();
1270 if (watcher.hasRecursed() || interrupt.shouldInterrupt())
1273 parserStatus.deallocate();
1277 QQmlTrace trace("VME Finalize Callbacks");
1278 for (int ii = 0; ii < finalizeCallbacks.count(); ++ii) {
1279 QQmlEnginePrivate::FinalizeCallback callback = finalizeCallbacks.at(ii);
1280 QObject *obj = callback.first;
1282 void *args[] = { 0 };
1283 QMetaObject::metacall(obj, QMetaObject::InvokeMetaMethod, callback.second, args);
1285 if (watcher.hasRecursed())
1288 finalizeCallbacks.clear();
1292 QQmlTrace trace("VME Component.onCompleted Callbacks");
1293 while (componentAttached) {
1294 QQmlComponentAttached *a = componentAttached;
1296 QQmlData *d = QQmlData::get(a->parent());
1298 Q_ASSERT(d->context);
1299 a->add(&d->context->componentAttached);
1300 emit a->completed();
1302 if (watcher.hasRecursed() || interrupt.shouldInterrupt())
1307 QQmlContextData *rv = rootContext;
1311 if (rv) rv->activeVMEData = data;
1316 void QQmlVME::blank(QFiniteStack<QQmlAbstractBinding *> &bs)
1318 for (int ii = 0; ii < bs.count(); ++ii) {
1319 QQmlAbstractBinding *b = bs.at(ii);
1320 if (b) b->m_mePtr = 0;
1324 void QQmlVME::blank(QFiniteStack<QQmlParserStatus *> &pss)
1326 for (int ii = 0; ii < pss.count(); ++ii) {
1327 QQmlParserStatus *ps = pss.at(ii);
1332 QQmlVMEGuard::QQmlVMEGuard()
1333 : m_objectCount(0), m_objects(0), m_contextCount(0), m_contexts(0)
1337 QQmlVMEGuard::~QQmlVMEGuard()
1342 void QQmlVMEGuard::guard(QQmlVME *vme)
1346 m_objectCount = vme->objects.count();
1347 m_objects = new QQmlGuard<QObject>[m_objectCount];
1348 for (int ii = 0; ii < m_objectCount; ++ii)
1349 m_objects[ii] = vme->objects[ii];
1351 m_contextCount = (vme->rootContext.isNull()?0:1) + vme->states.count();
1352 m_contexts = new QQmlGuardedContextData[m_contextCount];
1353 for (int ii = 0; ii < vme->states.count(); ++ii)
1354 m_contexts[ii] = vme->states.at(ii).context;
1355 if (!vme->rootContext.isNull())
1356 m_contexts[m_contextCount - 1] = vme->rootContext.contextData();
1359 void QQmlVMEGuard::clear()
1361 delete [] m_objects;
1362 delete [] m_contexts;
1370 bool QQmlVMEGuard::isOK() const
1372 for (int ii = 0; ii < m_objectCount; ++ii)
1373 if (m_objects[ii].isNull())
1376 for (int ii = 0; ii < m_contextCount; ++ii)
1377 if (m_contexts[ii].isNull())