Reduce memory consumption in QV4Bindings::Binding
[profile/ivi/qtdeclarative.git] / src / qml / qml / qqmlvme.cpp
1 /****************************************************************************
2 **
3 ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/
5 **
6 ** This file is part of the QtQml module of the Qt Toolkit.
7 **
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.
16 **
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.
20 **
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.
28 **
29 ** Other Usage
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.
32 **
33 **
34 **
35 **
36 **
37 **
38 ** $QT_END_LICENSE$
39 **
40 ****************************************************************************/
41
42 #include "qqmlvme_p.h"
43
44 #include "qqmlcompiler_p.h"
45 #include "qqmlboundsignal_p.h"
46 #include "qqmlstringconverters_p.h"
47 #include <private/qmetaobjectbuilder_p.h>
48 #include "qqmldata_p.h"
49 #include "qqml.h"
50 #include "qqmlcustomparser_p.h"
51 #include "qqmlengine.h"
52 #include "qqmlcontext.h"
53 #include "qqmlcomponent.h"
54 #include "qqmlcomponentattached_p.h"
55 #include "qqmlbinding_p.h"
56 #include "qqmlengine_p.h"
57 #include "qqmlcomponent_p.h"
58 #include "qqmlvmemetaobject_p.h"
59 #include "qqmlcontext_p.h"
60 #include <private/qv4bindings_p.h>
61 #include <private/qv8bindings_p.h>
62 #include "qqmlglobal_p.h"
63 #include <private/qfinitestack_p.h>
64 #include "qqmlscriptstring.h"
65 #include "qqmlscriptstring_p.h"
66 #include "qqmlpropertyvalueinterceptor_p.h"
67 #include "qqmlvaluetypeproxybinding_p.h"
68
69 #include <QStack>
70 #include <QPointF>
71 #include <QSizeF>
72 #include <QRectF>
73 #include <QtCore/qdebug.h>
74 #include <QtCore/qvarlengtharray.h>
75 #include <QtCore/qcoreapplication.h>
76 #include <QtCore/qdatetime.h>
77 #include <QtCore/qvarlengtharray.h>
78 #include <QtQml/qjsvalue.h>
79
80 QT_BEGIN_NAMESPACE
81
82 using namespace QQmlVMETypes;
83
84 #define VME_EXCEPTION(desc, line) \
85     { \
86         QQmlError error; \
87         error.setDescription(desc.trimmed()); \
88         error.setLine(line); \
89         error.setUrl(COMP->url); \
90         *errors << error; \
91         goto exceptionExit; \
92     }
93
94 void QQmlVME::init(QQmlContextData *ctxt, QQmlCompiledData *comp, int start,
95                            QQmlContextData *creation)
96 {
97     Q_ASSERT(ctxt);
98     Q_ASSERT(comp);
99
100     if (start == -1) {
101         start = 0;
102     } else {
103         creationContext = creation;
104     }
105
106     State initState;
107     initState.context = ctxt;
108     initState.compiledData = comp;
109     initState.instructionStream = comp->bytecode.constData() + start;
110     states.push(initState);
111
112     typedef QQmlInstruction I;
113     I *i = (I *)initState.instructionStream;
114
115     Q_ASSERT(comp->instructionType(i) == I::Init);
116
117     objects.allocate(i->init.objectStackSize);
118     lists.allocate(i->init.listStackSize);
119     bindValues.allocate(i->init.bindingsSize);
120     parserStatus.allocate(i->init.parserStatusSize);
121
122 #ifdef QML_ENABLE_TRACE
123     parserStatusData.allocate(i->init.parserStatusSize);
124     rootComponent = comp;
125 #endif
126
127     rootContext = 0;
128     engine = ctxt->engine;
129 }
130
131 bool QQmlVME::initDeferred(QObject *object)
132 {
133     QQmlData *data = QQmlData::get(object);
134
135     if (!data || !data->context || !data->compiledData)
136         return false;
137
138     QQmlContextData *ctxt = data->context;
139     QQmlCompiledData *comp = data->compiledData;
140     int start = data->deferredIdx;
141
142     State initState;
143     initState.flags = State::Deferred;
144     initState.context = ctxt;
145     initState.compiledData = comp;
146     initState.instructionStream = comp->bytecode.constData() + start;
147     states.push(initState);
148
149     typedef QQmlInstruction I;
150     I *i = (I *)initState.instructionStream;
151
152     Q_ASSERT(comp->instructionType(i) == I::DeferInit);
153
154     objects.allocate(i->deferInit.objectStackSize);
155     lists.allocate(i->deferInit.listStackSize);
156     bindValues.allocate(i->deferInit.bindingsSize);
157     parserStatus.allocate(i->deferInit.parserStatusSize);
158
159     objects.push(object);
160
161 #ifdef QML_ENABLE_TRACE
162     parserStatusData.allocate(i->deferInit.parserStatusSize);
163     rootComponent = comp;
164 #endif
165
166     rootContext = 0;
167     engine = ctxt->engine;
168
169     return true;
170 }
171
172 namespace {
173 struct ActiveVMERestorer 
174 {
175     ActiveVMERestorer(QQmlVME *me, QQmlEnginePrivate *ep) 
176     : ep(ep), oldVME(ep->activeVME) { ep->activeVME = me; }
177     ~ActiveVMERestorer() { ep->activeVME = oldVME; }
178
179     QQmlEnginePrivate *ep;
180     QQmlVME *oldVME;
181 };
182 }
183
184 QObject *QQmlVME::execute(QList<QQmlError> *errors, const Interrupt &interrupt)
185 {
186     Q_ASSERT(states.count() >= 1);
187
188 #ifdef QML_ENABLE_TRACE
189     QQmlTrace trace("VME Execute");
190     trace.addDetail("URL", rootComponent->url);
191 #endif
192
193     QQmlEnginePrivate *ep = QQmlEnginePrivate::get(states.at(0).context->engine);
194
195     ActiveVMERestorer restore(this, ep);
196
197     QObject *rv = run(errors, interrupt);
198
199     return rv;
200 }
201
202 inline bool fastHasBinding(QObject *o, int index) 
203 {
204     QQmlData *ddata = static_cast<QQmlData *>(QObjectPrivate::get(o)->declarativeData);
205
206     index &= 0x0000FFFF; // To handle value types
207
208     return ddata && (ddata->bindingBitsSize > index) && 
209            (ddata->bindingBits[index / 32] & (1 << (index % 32)));
210 }
211
212 static void removeBindingOnProperty(QObject *o, int index)
213 {
214     int coreIndex = index & 0x0000FFFF;
215     int valueTypeIndex = (index & 0xFFFF0000 ? index >> 16 : -1);
216
217     QQmlAbstractBinding *binding = QQmlPropertyPrivate::setBinding(o, coreIndex, valueTypeIndex, 0);
218     if (binding) binding->destroy();
219 }
220
221 static QVariant variantFromString(const QString &string)
222 {
223     return QQmlStringConverters::variantFromString(string);
224 }
225
226 // XXX we probably need some form of "work count" here to prevent us checking this 
227 // for every instruction.
228 #define QML_BEGIN_INSTR_COMMON(I) { \
229     const QQmlInstructionMeta<(int)QQmlInstruction::I>::DataType &instr = QQmlInstructionMeta<(int)QQmlInstruction::I>::data(*genericInstr); \
230     INSTRUCTIONSTREAM += QQmlInstructionMeta<(int)QQmlInstruction::I>::Size; \
231     Q_UNUSED(instr);
232
233 #ifdef QML_THREADED_VME_INTERPRETER
234 #  define QML_BEGIN_INSTR(I) op_##I: \
235     QML_BEGIN_INSTR_COMMON(I)
236
237 #  define QML_NEXT_INSTR(I) { \
238     if (watcher.hasRecursed()) return 0; \
239     genericInstr = reinterpret_cast<const QQmlInstruction *>(INSTRUCTIONSTREAM); \
240     goto *genericInstr->common.code; \
241     }
242
243 #  define QML_END_INSTR(I) } \
244     if (watcher.hasRecursed()) return 0; \
245     genericInstr = reinterpret_cast<const QQmlInstruction *>(INSTRUCTIONSTREAM); \
246     if (interrupt.shouldInterrupt()) return 0; \
247     goto *genericInstr->common.code;
248
249 #else
250 #  define QML_BEGIN_INSTR(I) \
251     case QQmlInstruction::I: \
252     QML_BEGIN_INSTR_COMMON(I)
253
254 #  define QML_NEXT_INSTR(I) { \
255     if (watcher.hasRecursed()) return 0; \
256     break; \
257     }
258
259 #  define QML_END_INSTR(I) \
260     if (watcher.hasRecursed() || interrupt.shouldInterrupt()) return 0; \
261     } break;
262 #endif
263
264 #define QML_STORE_VALUE(name, cpptype, value) \
265     QML_BEGIN_INSTR(name) \
266         cpptype v = value; \
267         void *a[] = { (void *)&v, 0, &status, &flags }; \
268         QObject *target = objects.top(); \
269         CLEAN_PROPERTY(target, instr.propertyIndex); \
270         QMetaObject::metacall(target, QMetaObject::WriteProperty, instr.propertyIndex, a); \
271     QML_END_INSTR(name)
272
273 #define QML_STORE_PROVIDER_VALUE(name, type, value) \
274     QML_BEGIN_INSTR(name) \
275         struct { void *data[4]; } buffer; \
276         if (QQml_valueTypeProvider()->storeValueType(type, &value, &buffer, sizeof(buffer))) { \
277             void *a[] = { reinterpret_cast<void *>(&buffer), 0, &status, &flags }; \
278             QObject *target = objects.top(); \
279             CLEAN_PROPERTY(target, instr.propertyIndex); \
280             QMetaObject::metacall(target, QMetaObject::WriteProperty, instr.propertyIndex, a); \
281         } \
282     QML_END_INSTR(name)
283
284 #define QML_STORE_LIST(name, cpptype, value) \
285     QML_BEGIN_INSTR(name) \
286         cpptype v; \
287         v.append(value); \
288         void *a[] = { (void *)&v, 0, &status, &flags }; \
289         QObject *target = objects.top(); \
290         CLEAN_PROPERTY(target, instr.propertyIndex); \
291         QMetaObject::metacall(target, QMetaObject::WriteProperty, instr.propertyIndex, a); \
292     QML_END_INSTR(name)
293
294 #define QML_STORE_VAR(name, value) \
295     QML_BEGIN_INSTR(name) \
296         v8::Handle<v8::Value> v8value = value; \
297         QObject *target = objects.top(); \
298         CLEAN_PROPERTY(target, instr.propertyIndex); \
299         QQmlVMEMetaObject *vmemo = QQmlVMEMetaObject::get(target); \
300         Q_ASSERT(vmemo); \
301         vmemo->setVMEProperty(instr.propertyIndex, v8value); \
302     QML_END_INSTR(name)
303
304 #define QML_STORE_POINTER(name, value) \
305     QML_BEGIN_INSTR(name) \
306         void *a[] = { (void *)value, 0, &status, &flags }; \
307         QObject *target = objects.top(); \
308         CLEAN_PROPERTY(target, instr.propertyIndex); \
309         QMetaObject::metacall(target, QMetaObject::WriteProperty, instr.propertyIndex, a); \
310     QML_END_INSTR(name)
311
312 #define CLEAN_PROPERTY(o, index) \
313     if (fastHasBinding(o, index)) \
314         removeBindingOnProperty(o, index)
315
316 QObject *QQmlVME::run(QList<QQmlError> *errors,
317                               const Interrupt &interrupt
318 #ifdef QML_THREADED_VME_INTERPRETER
319                               , void ***storeJumpTable
320 #endif
321                               )
322 {
323 #ifdef QML_THREADED_VME_INTERPRETER
324     if (storeJumpTable) {
325 #define QML_INSTR_ADDR(I, FMT) &&op_##I,
326         static void *jumpTable[] = {
327             FOR_EACH_QML_INSTR(QML_INSTR_ADDR)
328         };
329 #undef QML_INSTR_ADDR
330         *storeJumpTable = jumpTable;
331         return 0;
332     }
333 #endif
334     Q_ASSERT(errors->isEmpty());
335     Q_ASSERT(states.count() >= 1);
336
337     QQmlEngine *engine = states.at(0).context->engine;
338     QQmlEnginePrivate *ep = QQmlEnginePrivate::get(engine);
339
340     // Need a v8 handle scope and execution context for StoreVar instructions.
341     v8::HandleScope handleScope;
342     v8::Context::Scope contextScope(ep->v8engine()->context());
343
344     int status = -1; // needed for dbus
345     QQmlPropertyPrivate::WriteFlags flags = QQmlPropertyPrivate::BypassInterceptor |
346                                                     QQmlPropertyPrivate::RemoveBindingOnAliasWrite;
347
348     QRecursionWatcher<QQmlVME, &QQmlVME::recursion> watcher(this);
349
350 #define COMP states.top().compiledData
351 #define CTXT states.top().context
352 #define INSTRUCTIONSTREAM states.top().instructionStream
353 #define BINDINGSKIPLIST states.top().bindingSkipList
354
355 #define TYPES COMP->types
356 #define PRIMITIVES COMP->primitives
357 #define DATAS COMP->datas
358 #define PROGRAMS COMP->programs
359 #define PROPERTYCACHES COMP->propertyCaches
360 #define SCRIPTS COMP->scripts
361 #define URLS COMP->urls
362
363 #ifdef QML_THREADED_VME_INTERPRETER
364     const QQmlInstruction *genericInstr = reinterpret_cast<const QQmlInstruction *>(INSTRUCTIONSTREAM);
365     goto *genericInstr->common.code;
366 #else
367     for (;;) {
368         const QQmlInstruction *genericInstr = reinterpret_cast<const QQmlInstruction *>(INSTRUCTIONSTREAM);
369
370         switch (genericInstr->common.instructionType) {
371 #endif
372
373         // Store a created object in a property.  These all pop from the objects stack.
374         QML_STORE_VALUE(StoreObject, QObject *, objects.pop());
375         QML_STORE_VALUE(StoreVariantObject, QVariant, QVariant::fromValue(objects.pop()));
376         QML_STORE_VAR(StoreVarObject, ep->v8engine()->newQObject(objects.pop()));
377
378         // Store a literal value in a corresponding property
379         QML_STORE_VALUE(StoreFloat, float, instr.value);
380         QML_STORE_VALUE(StoreDouble, double, instr.value);
381         QML_STORE_VALUE(StoreBool, bool, instr.value);
382         QML_STORE_VALUE(StoreInteger, int, instr.value);
383         QML_STORE_PROVIDER_VALUE(StoreColor, QMetaType::QColor, instr.value);
384         QML_STORE_VALUE(StoreDate, QDate, QDate::fromJulianDay(instr.value));
385         QML_STORE_VALUE(StoreDateTime, QDateTime,
386                         QDateTime(QDate::fromJulianDay(instr.date), *(QTime *)&instr.time));
387         QML_STORE_POINTER(StoreTime, (QTime *)&instr.time);
388         QML_STORE_POINTER(StorePoint, (QPoint *)&instr.point);
389         QML_STORE_POINTER(StorePointF, (QPointF *)&instr.point);
390         QML_STORE_POINTER(StoreSize, (QSize *)&instr.size);
391         QML_STORE_POINTER(StoreSizeF, (QSizeF *)&instr.size);
392         QML_STORE_POINTER(StoreRect, (QRect *)&instr.rect);
393         QML_STORE_POINTER(StoreRectF, (QRectF *)&instr.rect);
394         QML_STORE_PROVIDER_VALUE(StoreVector3D, QMetaType::QVector3D, instr.vector);
395         QML_STORE_PROVIDER_VALUE(StoreVector4D, QMetaType::QVector4D, instr.vector);
396         QML_STORE_POINTER(StoreString, &PRIMITIVES.at(instr.value));
397         QML_STORE_POINTER(StoreByteArray, &DATAS.at(instr.value));
398         QML_STORE_POINTER(StoreUrl, &URLS.at(instr.value));
399         QML_STORE_VALUE(StoreTrString, QString,
400                         QCoreApplication::translate(DATAS.at(instr.context).constData(),
401                                                     DATAS.at(instr.text).constData(),
402                                                     DATAS.at(instr.comment).constData(),
403                                                     instr.n));
404         QML_STORE_VALUE(StoreTrIdString, QString, qtTrId(DATAS.at(instr.text).constData(), instr.n));
405
406         // Store a literal value in a QList
407         QML_STORE_LIST(StoreStringList, QStringList, PRIMITIVES.at(instr.value));
408         QML_STORE_LIST(StoreStringQList, QList<QString>, PRIMITIVES.at(instr.value));
409         QML_STORE_LIST(StoreUrlQList, QList<QUrl>, URLS.at(instr.value));
410         QML_STORE_LIST(StoreDoubleQList, QList<double>, instr.value);
411         QML_STORE_LIST(StoreBoolQList, QList<bool>, instr.value);
412         QML_STORE_LIST(StoreIntegerQList, QList<int>, instr.value);
413
414         // Store a literal value in a QVariant property
415         QML_STORE_VALUE(StoreVariant, QVariant, variantFromString(PRIMITIVES.at(instr.value)));
416         QML_STORE_VALUE(StoreVariantInteger, QVariant, QVariant(instr.value));
417         QML_STORE_VALUE(StoreVariantDouble, QVariant, QVariant(instr.value));
418         QML_STORE_VALUE(StoreVariantBool, QVariant, QVariant(instr.value));
419
420         // Store a literal value in a var property.
421         // We deliberately do not use string converters here
422         QML_STORE_VAR(StoreVar, ep->v8engine()->fromVariant(PRIMITIVES.at(instr.value)));
423         QML_STORE_VAR(StoreVarInteger, v8::Integer::New(instr.value));
424         QML_STORE_VAR(StoreVarDouble, v8::Number::New(instr.value));
425         QML_STORE_VAR(StoreVarBool, v8::Boolean::New(instr.value));
426
427         // Store a literal value in a QJSValue property.
428         QML_STORE_VALUE(StoreJSValueString, QJSValue, QJSValue(PRIMITIVES.at(instr.value)));
429         QML_STORE_VALUE(StoreJSValueInteger, QJSValue, QJSValue(instr.value));
430         QML_STORE_VALUE(StoreJSValueDouble, QJSValue, QJSValue(instr.value));
431         QML_STORE_VALUE(StoreJSValueBool, QJSValue, QJSValue(instr.value));
432
433         QML_BEGIN_INSTR(Init)
434             // Ensure that the compiled data has been initialized
435             if (!COMP->isInitialized()) COMP->initialize(engine);
436
437             QQmlContextData *parentCtxt = CTXT;
438             CTXT = new QQmlContextData;
439             CTXT->isInternal = true;
440             CTXT->url = COMP->url;
441             CTXT->urlString = COMP->name;
442             CTXT->imports = COMP->importCache;
443             CTXT->imports->addref();
444             CTXT->setParent(parentCtxt);
445             if (instr.contextCache != -1) 
446                 CTXT->setIdPropertyData(COMP->contextCaches.at(instr.contextCache));
447             if (instr.compiledBinding != -1) {
448                 const char *v4data = DATAS.at(instr.compiledBinding).constData();
449                 CTXT->v4bindings = new QV4Bindings(v4data, CTXT);
450             }
451             if (states.count() == 1) {
452                 rootContext = CTXT;
453                 rootContext->activeVMEData = data;
454                 rootContext->isRootObjectInCreation = true;
455             }
456             if (states.count() == 1 && !creationContext.isNull()) {
457                 // A component that is logically created within another component instance shares the 
458                 // same instances of script imports.  For example:
459                 //
460                 //     import QtQuick 2.0
461                 //     import "test.js" as Test
462                 //     ListView {
463                 //         model: Test.getModel()
464                 //         delegate: Component {
465                 //             Text { text: Test.getValue(index); }
466                 //         }
467                 //     }
468                 //
469                 // Has the same "Test" instance.  To implement this, we simply copy the v8 handles into
470                 // the inner context.  We have to create a fresh persistent handle for each to prevent 
471                 // double dispose.  It is possible we could do this more efficiently using some form of
472                 // referencing instead.
473                 CTXT->importedScripts = creationContext->importedScripts;
474                 for (int ii = 0; ii < CTXT->importedScripts.count(); ++ii)
475                     CTXT->importedScripts[ii] = qPersistentNew<v8::Object>(CTXT->importedScripts[ii]);
476             }
477         QML_END_INSTR(Init)
478
479         QML_BEGIN_INSTR(DeferInit)
480         QML_END_INSTR(DeferInit)
481
482         QML_BEGIN_INSTR(Done)
483             states.pop();
484
485             if (states.isEmpty())
486                 goto normalExit;
487         QML_END_INSTR(Done)
488
489         QML_BEGIN_INSTR(CreateQMLObject)
490             const QQmlCompiledData::TypeReference &type = TYPES.at(instr.type);
491             Q_ASSERT(type.component);
492
493             states.push(State());
494
495             State *cState = &states[states.count() - 2];
496             State *nState = &states[states.count() - 1];
497
498             nState->context = cState->context;
499             nState->compiledData = type.component;
500             nState->instructionStream = type.component->bytecode.constData();
501
502             if (instr.bindingBits != -1) {
503                 const QByteArray &bits = cState->compiledData->datas.at(instr.bindingBits);
504                 nState->bindingSkipList = QBitField((const quint32*)bits.constData(),
505                                                     bits.size() * 8);
506             }
507             if (instr.isRoot)
508                 nState->bindingSkipList = nState->bindingSkipList.united(cState->bindingSkipList);
509
510             // As the state in the state stack changed, execution will continue in the new program.
511         QML_END_INSTR(CreateQMLObject)
512
513         QML_BEGIN_INSTR(CompleteQMLObject)
514             QObject *o = objects.top();
515             Q_ASSERT(o);
516
517             QQmlData *ddata = QQmlData::get(o);
518             Q_ASSERT(ddata);
519
520             if (states.count() == 1) {
521                 // Keep a reference to the compiled data we rely on.
522                 // Only the top-level component instance needs to add a reference - higher-level
523                 // components add a reference to the components they depend on, so an instance
524                 // of the top-level component keeps them all referenced.
525                 ddata->compiledData = states[0].compiledData;
526                 ddata->compiledData->addref();
527             }
528
529             if (instr.isRoot) {
530                 if (ddata->context) {
531                     Q_ASSERT(ddata->context != CTXT);
532                     Q_ASSERT(ddata->outerContext);
533                     Q_ASSERT(ddata->outerContext != CTXT);
534                     QQmlContextData *c = ddata->context;
535                     while (c->linkedContext) c = c->linkedContext;
536                     c->linkedContext = CTXT;
537                 } else {
538                     CTXT->addObject(o);
539                 }
540
541                 ddata->ownContext = true;
542             } else if (!ddata->context) {
543                 CTXT->addObject(o);
544             }
545
546             ddata->setImplicitDestructible();
547             ddata->outerContext = CTXT;
548             ddata->lineNumber = instr.line;
549             ddata->columnNumber = instr.column;
550         QML_END_INSTR(CompleteQMLObject)
551
552         QML_BEGIN_INSTR(CreateCppObject)
553             const QQmlCompiledData::TypeReference &type = TYPES.at(instr.type);
554             Q_ASSERT(type.type);
555
556             QObject *o = 0;
557             void *memory = 0;
558             type.type->create(&o, &memory, sizeof(QQmlData));
559             QQmlData *ddata = new (memory) QQmlData;
560             ddata->ownMemory = false;
561             QObjectPrivate::get(o)->declarativeData = ddata;
562
563             if (rootContext && rootContext->isRootObjectInCreation) {
564                 ddata->rootObjectInCreation = true;
565                 rootContext->isRootObjectInCreation = false;
566             }
567
568             if (type.typePropertyCache && !ddata->propertyCache) {
569                 ddata->propertyCache = type.typePropertyCache;
570                 ddata->propertyCache->addref();
571             }
572
573             if (!o) 
574                 VME_EXCEPTION(tr("Unable to create object of type %1").arg(type.type->elementName()),
575                               instr.line);
576
577             if (states.count() == 1) {
578                 // Keep a reference to the compiled data we rely on
579                 ddata->compiledData = states[0].compiledData;
580                 ddata->compiledData->addref();
581             }
582
583             if (instr.isRoot) {
584                 if (ddata->context) {
585                     Q_ASSERT(ddata->context != CTXT);
586                     Q_ASSERT(ddata->outerContext);
587                     Q_ASSERT(ddata->outerContext != CTXT);
588                     QQmlContextData *c = ddata->context;
589                     while (c->linkedContext) c = c->linkedContext;
590                     c->linkedContext = CTXT;
591                 } else {
592                     CTXT->addObject(o);
593                 }
594
595                 ddata->ownContext = true;
596             } else if (!ddata->context) {
597                 CTXT->addObject(o);
598             }
599
600             ddata->setImplicitDestructible();
601             ddata->outerContext = CTXT;
602             ddata->lineNumber = instr.line;
603             ddata->columnNumber = instr.column;
604
605             if (instr.data != -1) {
606                 QQmlCustomParser *customParser =
607                     TYPES.at(instr.type).type->customParser();
608                 customParser->setCustomData(o, DATAS.at(instr.data));
609             }
610             if (!objects.isEmpty()) {
611                 QObject *parent = objects.at(objects.count() - 1 - (instr.parentToSuper?1:0));
612 #if 0 // ### refactor
613                 if (o->isWidgetType() && parent->isWidgetType()) 
614                     static_cast<QWidget*>(o)->setParent(static_cast<QWidget*>(parent));
615                 else 
616 #endif
617                     QQml_setParent_noEvent(o, parent);
618                 ddata->parentFrozen = true;
619             }
620             objects.push(o);
621         QML_END_INSTR(CreateCppObject)
622
623         QML_BEGIN_INSTR(CreateSimpleObject)
624             QObject *o = (QObject *)operator new(instr.typeSize + sizeof(QQmlData));   
625             ::memset(o, 0, instr.typeSize + sizeof(QQmlData));
626             instr.create(o);
627
628             QQmlData *ddata = (QQmlData *)(((const char *)o) + instr.typeSize);
629             const QQmlCompiledData::TypeReference &ref = TYPES.at(instr.type);
630             if (!ddata->propertyCache && ref.typePropertyCache) {
631                 ddata->propertyCache = ref.typePropertyCache;
632                 ddata->propertyCache->addref();
633             }
634             ddata->lineNumber = instr.line;
635             ddata->columnNumber = instr.column;
636
637             QObjectPrivate::get(o)->declarativeData = ddata;                                                      
638             ddata->context = ddata->outerContext = CTXT;
639             ddata->nextContextObject = CTXT->contextObjects; 
640             if (ddata->nextContextObject) 
641                 ddata->nextContextObject->prevContextObject = &ddata->nextContextObject; 
642             ddata->prevContextObject = &CTXT->contextObjects; 
643             CTXT->contextObjects = ddata; 
644
645             QObject *parent = objects.at(objects.count() - 1 - (instr.parentToSuper?1:0));
646             QQml_setParent_noEvent(o, parent);                                                        
647
648             ddata->parentFrozen = true;
649             objects.push(o);
650         QML_END_INSTR(CreateSimpleObject)
651
652         QML_BEGIN_INSTR(SetId)
653             QObject *target = objects.top();
654             CTXT->setIdProperty(instr.index, target);
655         QML_END_INSTR(SetId)
656
657         QML_BEGIN_INSTR(SetDefault)
658             CTXT->contextObject = objects.top();
659         QML_END_INSTR(SetDefault)
660
661         QML_BEGIN_INSTR(CreateComponent)
662             QQmlComponent *qcomp = 
663                 new QQmlComponent(CTXT->engine, COMP, INSTRUCTIONSTREAM - COMP->bytecode.constData(),
664                                           objects.isEmpty() ? 0 : objects.top());
665
666             QQmlData *ddata = QQmlData::get(qcomp, true);
667             Q_ASSERT(ddata);
668
669             CTXT->addObject(qcomp);
670
671             if (states.count() == 1) {
672                 // Keep a reference to the compiled data we rely on
673                 ddata->compiledData = states[0].compiledData;
674                 ddata->compiledData->addref();
675             }
676
677             if (instr.isRoot)
678                 ddata->ownContext = true;
679
680             ddata->setImplicitDestructible();
681             ddata->outerContext = CTXT;
682             ddata->lineNumber = instr.line;
683             ddata->columnNumber = instr.column;
684
685             QQmlComponentPrivate::get(qcomp)->creationContext = CTXT;
686
687             objects.push(qcomp);
688             INSTRUCTIONSTREAM += instr.count;
689         QML_END_INSTR(CreateComponent)
690
691         QML_BEGIN_INSTR(StoreMetaObject)
692             QObject *target = objects.top();
693
694             QQmlPropertyCache *propertyCache = PROPERTYCACHES.at(instr.propertyCache);
695
696             const QQmlVMEMetaData *data = 
697                 (const QQmlVMEMetaData *)DATAS.at(instr.aliasData).constData();
698
699             (void)new QQmlVMEMetaObject(target, propertyCache, data);
700
701             QQmlData *ddata = QQmlData::get(target, true);
702             if (ddata->propertyCache) ddata->propertyCache->release();
703             ddata->propertyCache = propertyCache;
704             ddata->propertyCache->addref();
705
706         QML_END_INSTR(StoreMetaObject)
707
708         QML_BEGIN_INSTR(AssignCustomType)
709             QObject *target = objects.top();
710             CLEAN_PROPERTY(target, instr.propertyIndex);
711
712             const QString &primitive = PRIMITIVES.at(instr.primitive);
713             int type = instr.type;
714             QQmlMetaType::StringConverter converter = QQmlMetaType::customStringConverter(type);
715             QVariant v = (*converter)(primitive);
716
717             QMetaProperty prop = 
718                     target->metaObject()->property(instr.propertyIndex);
719             if (v.isNull() || ((int)prop.type() != type && prop.userType() != type)) 
720                 VME_EXCEPTION(tr("Cannot assign value %1 to property %2").arg(primitive).arg(QString::fromUtf8(prop.name())), instr.line);
721
722             void *a[] = { (void *)v.data(), 0, &status, &flags };
723             QMetaObject::metacall(target, QMetaObject::WriteProperty, 
724                                   instr.propertyIndex, a);
725         QML_END_INSTR(AssignCustomType)
726
727         QML_BEGIN_INSTR(AssignSignalObject)
728             // XXX optimize
729
730             QObject *assign = objects.pop();
731             QObject *target = objects.top();
732             int sigIdx = instr.signal;
733             const QString &pr = PRIMITIVES.at(sigIdx);
734
735             QQmlProperty prop(target, pr);
736             if (prop.type() & QQmlProperty::SignalProperty) {
737
738                 QMetaMethod method = QQmlMetaType::defaultMethod(assign);
739                 if (!method.isValid())
740                     VME_EXCEPTION(tr("Cannot assign object type %1 with no default method").arg(QString::fromLatin1(assign->metaObject()->className())), instr.line);
741
742                 if (!QMetaObject::checkConnectArgs(prop.method(), method)) {
743                     VME_EXCEPTION(tr("Cannot connect mismatched signal/slot %1 %vs. %2")
744                                   .arg(QString::fromLatin1(method.methodSignature().constData()))
745                                   .arg(QString::fromLatin1(prop.method().methodSignature().constData())), instr.line);
746                 }
747
748                 QQmlPropertyPrivate::connect(target, prop.index(), assign, method.methodIndex());
749
750             } else {
751                 VME_EXCEPTION(tr("Cannot assign an object to signal property %1").arg(pr), instr.line);
752             }
753
754
755         QML_END_INSTR(AssignSignalObject)
756
757         QML_BEGIN_INSTR(StoreSignal)
758             QObject *target = objects.top();
759             QObject *context = objects.at(objects.count() - 1 - instr.context);
760
761             QQmlBoundSignal *bs = new QQmlBoundSignal(target, instr.signalIndex, target, engine);
762             QQmlBoundSignalExpression *expr =
763                 new QQmlBoundSignalExpression(CTXT, context, DATAS.at(instr.value), true, COMP->name, instr.line, instr.column);
764             bs->takeExpression(expr);
765         QML_END_INSTR(StoreSignal)
766
767         QML_BEGIN_INSTR(StoreImportedScript)
768             CTXT->importedScripts << run(CTXT, SCRIPTS.at(instr.value));
769         QML_END_INSTR(StoreImportedScript)
770
771         QML_BEGIN_INSTR(StoreScriptString)
772             QObject *target = objects.top();
773             QObject *scope = objects.at(objects.count() - 1 - instr.scope);
774             QQmlScriptString ss(PRIMITIVES.at(instr.value), CTXT->asQQmlContext(), scope);
775             ss.d.data()->bindingId = instr.bindingId;
776             ss.d.data()->lineNumber = qmlSourceCoordinate(instr.line);
777             ss.d.data()->columnNumber = qmlSourceCoordinate(instr.column);
778             ss.d.data()->isStringLiteral = instr.isStringLiteral;
779             ss.d.data()->isNumberLiteral = instr.isNumberLiteral;
780             ss.d.data()->numberValue = instr.numberValue;
781
782             void *a[] = { &ss, 0, &status, &flags };
783             QMetaObject::metacall(target, QMetaObject::WriteProperty, 
784                                   instr.propertyIndex, a);
785         QML_END_INSTR(StoreScriptString)
786
787         QML_BEGIN_INSTR(BeginObject)
788             QObject *target = objects.top();
789             QQmlParserStatus *status = reinterpret_cast<QQmlParserStatus *>(reinterpret_cast<char *>(target) + instr.castValue);
790             parserStatus.push(status);
791 #ifdef QML_ENABLE_TRACE
792             Q_ASSERT(QObjectPrivate::get(target)->declarativeData);
793             parserStatusData.push(static_cast<QQmlData *>(QObjectPrivate::get(target)->declarativeData));
794 #endif
795             status->d = &parserStatus.top();
796
797             status->classBegin();
798         QML_END_INSTR(BeginObject)
799
800         QML_BEGIN_INSTR(InitV8Bindings)
801             CTXT->v8bindings = new QV8Bindings(&PROGRAMS[instr.programIndex], instr.line, CTXT);
802         QML_END_INSTR(InitV8Bindings)
803
804         QML_BEGIN_INSTR(StoreBinding)
805             QObject *target = 
806                 objects.at(objects.count() - 1 - instr.owner);
807             QObject *context = 
808                 objects.at(objects.count() - 1 - instr.context);
809
810             if (instr.isRoot && BINDINGSKIPLIST.testBit(instr.property.coreIndex))
811                 QML_NEXT_INSTR(StoreBinding);
812
813             QQmlBinding *bind = new QQmlBinding(PRIMITIVES.at(instr.value), true, 
814                                                 context, CTXT, COMP->name, instr.line,
815                                                 instr.column);
816             bindValues.push(bind);
817             bind->m_mePtr = &bindValues.top();
818             bind->setTarget(target, instr.property, CTXT);
819
820             if (instr.isAlias) {
821                 QQmlAbstractBinding *old =
822                     QQmlPropertyPrivate::setBindingNoEnable(target,
823                                                             instr.property.coreIndex,
824                                                             instr.property.getValueTypeCoreIndex(),
825                                                             bind);
826                 if (old) { old->destroy(); }
827             } else {
828                 typedef QQmlPropertyPrivate QDPP;
829                 Q_ASSERT(bind->propertyIndex() == QDPP::bindingIndex(instr.property));
830                 Q_ASSERT(bind->object() == target);
831
832                 CLEAN_PROPERTY(target, QDPP::bindingIndex(instr.property));
833
834                 bind->addToObject();
835             }
836         QML_END_INSTR(StoreBinding)
837
838         QML_BEGIN_INSTR(StoreV4Binding)
839             QObject *target = 
840                 objects.at(objects.count() - 1 - instr.owner);
841             QObject *scope = 
842                 objects.at(objects.count() - 1 - instr.context);
843
844             int propertyIdx = (instr.property & 0x0000FFFF);
845
846             if (instr.isRoot && BINDINGSKIPLIST.testBit(propertyIdx))
847                 QML_NEXT_INSTR(StoreV4Binding);
848
849             QQmlAbstractBinding *binding = CTXT->v4bindings->configBinding(target, scope, &instr);
850             bindValues.push(binding);
851             binding->m_mePtr = &bindValues.top();
852
853             if (instr.isAlias) {
854                 QQmlAbstractBinding *old =
855                     QQmlPropertyPrivate::setBindingNoEnable(target,
856                                                             propertyIdx,
857                                                             instr.propType ? (instr.property >> 16) : -1,
858                                                             binding);
859                 if (old) { old->destroy(); }
860             } else {
861                 Q_ASSERT(binding->propertyIndex() == instr.property);
862                 Q_ASSERT(binding->object() == target);
863
864                 CLEAN_PROPERTY(target, instr.property);
865
866                 binding->addToObject();
867             }
868         QML_END_INSTR(StoreV4Binding)
869
870         QML_BEGIN_INSTR(StoreV8Binding)
871             QObject *target = 
872                 objects.at(objects.count() - 1 - instr.owner);
873             QObject *scope = 
874                 objects.at(objects.count() - 1 - instr.context);
875
876             if (instr.isRoot && BINDINGSKIPLIST.testBit(instr.property.coreIndex))
877                 QML_NEXT_INSTR(StoreV8Binding);
878
879             QQmlAbstractBinding *binding = CTXT->v8bindings->configBinding(target, scope,
880                                                                                    &instr);
881             if (binding && !instr.isFallback) {
882                 bindValues.push(binding);
883                 binding->m_mePtr = &bindValues.top();
884
885                 if (instr.isAlias) {
886                     QQmlAbstractBinding *old =
887                         QQmlPropertyPrivate::setBindingNoEnable(target,
888                                                                 instr.property.coreIndex,
889                                                                 instr.property.getValueTypeCoreIndex(),
890                                                                 binding);
891                     if (old) { old->destroy(); }
892                 } else {
893                     typedef QQmlPropertyPrivate QDPP;
894                     Q_ASSERT(binding->propertyIndex() == QDPP::bindingIndex(instr.property));
895                     Q_ASSERT(binding->object() == target);
896
897                     CLEAN_PROPERTY(target, QDPP::bindingIndex(instr.property));
898
899                     binding->addToObject();
900                 }
901             }
902         QML_END_INSTR(StoreV8Binding)
903
904         QML_BEGIN_INSTR(StoreValueSource)
905             QObject *obj = objects.pop();
906             QQmlPropertyValueSource *vs = reinterpret_cast<QQmlPropertyValueSource *>(reinterpret_cast<char *>(obj) + instr.castValue);
907             QObject *target = obj->parent();
908             vs->setTarget(QQmlPropertyPrivate::restore(target, instr.property, CTXT));
909         QML_END_INSTR(StoreValueSource)
910
911         QML_BEGIN_INSTR(StoreValueInterceptor)
912             QObject *obj = objects.pop();
913             QQmlPropertyValueInterceptor *vi = reinterpret_cast<QQmlPropertyValueInterceptor *>(reinterpret_cast<char *>(obj) + instr.castValue);
914             QObject *target = obj->parent();
915             QQmlProperty prop = 
916                 QQmlPropertyPrivate::restore(target, instr.property, CTXT);
917             vi->setTarget(prop);
918             QQmlVMEMetaObject *mo = QQmlVMEMetaObject::get(target);
919             Q_ASSERT(mo);
920             mo->registerInterceptor(prop.index(), QQmlPropertyPrivate::valueTypeCoreIndex(prop), vi);
921         QML_END_INSTR(StoreValueInterceptor)
922
923         QML_BEGIN_INSTR(StoreObjectQList)
924             QObject *assign = objects.pop();
925
926             const List &list = lists.top();
927             list.qListProperty.append((QQmlListProperty<void>*)&list.qListProperty, assign);
928         QML_END_INSTR(StoreObjectQList)
929
930         QML_BEGIN_INSTR(AssignObjectList)
931             // This is only used for assigning interfaces
932             QObject *assign = objects.pop();
933             const List &list = lists.top();
934
935             int type = list.type;
936
937             void *ptr = 0;
938
939             const char *iid = QQmlMetaType::interfaceIId(type);
940             if (iid) 
941                 ptr = assign->qt_metacast(iid);
942             if (!ptr) 
943                 VME_EXCEPTION(tr("Cannot assign object to list"), instr.line);
944
945
946             list.qListProperty.append((QQmlListProperty<void>*)&list.qListProperty, ptr);
947         QML_END_INSTR(AssignObjectList)
948
949         QML_BEGIN_INSTR(StoreInterface)
950             QObject *assign = objects.pop();
951             QObject *target = objects.top();
952             CLEAN_PROPERTY(target, instr.propertyIndex);
953
954             int coreIdx = instr.propertyIndex;
955             QMetaProperty prop = target->metaObject()->property(coreIdx);
956             int t = prop.userType();
957             const char *iid = QQmlMetaType::interfaceIId(t);
958             bool ok = false;
959             if (iid) {
960                 void *ptr = assign->qt_metacast(iid);
961                 if (ptr) {
962                     void *a[] = { &ptr, 0, &status, &flags };
963                     QMetaObject::metacall(target, 
964                                           QMetaObject::WriteProperty,
965                                           coreIdx, a);
966                     ok = true;
967                 }
968             } 
969
970             if (!ok) 
971                 VME_EXCEPTION(tr("Cannot assign object to interface property"), instr.line);
972         QML_END_INSTR(StoreInterface)
973             
974         QML_BEGIN_INSTR(FetchAttached)
975             QObject *target = objects.top();
976
977             QObject *qmlObject = qmlAttachedPropertiesObjectById(instr.id, target);
978
979             if (!qmlObject)
980                 VME_EXCEPTION(tr("Unable to create attached object"), instr.line);
981
982             objects.push(qmlObject);
983         QML_END_INSTR(FetchAttached)
984
985         QML_BEGIN_INSTR(FetchQList)
986             QObject *target = objects.top();
987
988             lists.push(List(instr.type));
989
990             void *a[1];
991             a[0] = (void *)&(lists.top().qListProperty);
992             QMetaObject::metacall(target, QMetaObject::ReadProperty, 
993                                   instr.property, a);
994         QML_END_INSTR(FetchQList)
995
996         QML_BEGIN_INSTR(FetchObject)
997             QObject *target = objects.top();
998
999             QObject *obj = 0;
1000             // NOTE: This assumes a cast to QObject does not alter the 
1001             // object pointer
1002             void *a[1];
1003             a[0] = &obj;
1004             QMetaObject::metacall(target, QMetaObject::ReadProperty, 
1005                                   instr.property, a);
1006
1007             if (!obj)
1008                 VME_EXCEPTION(tr("Cannot set properties on %1 as it is null").arg(QString::fromUtf8(target->metaObject()->property(instr.property).name())), instr.line);
1009
1010             objects.push(obj);
1011         QML_END_INSTR(FetchObject)
1012
1013         QML_BEGIN_INSTR(PopQList)
1014             lists.pop();
1015         QML_END_INSTR(PopQList)
1016
1017         QML_BEGIN_INSTR(Defer)
1018             if (instr.deferCount) {
1019                 QObject *target = objects.top();
1020                 QQmlData *data = QQmlData::get(target, true);
1021                 data->compiledData = COMP;
1022                 data->compiledData->addref(); // Keep this data referenced until we're initialized
1023                 data->deferredIdx = INSTRUCTIONSTREAM - COMP->bytecode.constData();
1024                 Q_ASSERT(data->deferredIdx != 0);
1025                 INSTRUCTIONSTREAM += instr.deferCount;
1026             }
1027         QML_END_INSTR(Defer)
1028
1029         QML_BEGIN_INSTR(PopFetchedObject)
1030             objects.pop();
1031         QML_END_INSTR(PopFetchedObject)
1032
1033         QML_BEGIN_INSTR(FetchValueType)
1034             QObject *target = objects.top();
1035
1036             if (instr.bindingSkipList != 0) {
1037                 // Possibly need to clear bindings
1038                 QQmlData *targetData = QQmlData::get(target);
1039                 if (targetData) {
1040                     QQmlAbstractBinding *binding = 
1041                         QQmlPropertyPrivate::binding(target, instr.property, -1);
1042
1043                     if (binding && binding->bindingType() != QQmlAbstractBinding::ValueTypeProxy) {
1044                         QQmlPropertyPrivate::setBinding(target, instr.property, -1, 0);
1045                         binding->destroy();
1046                     } else if (binding) {
1047                         QQmlValueTypeProxyBinding *proxy = 
1048                             static_cast<QQmlValueTypeProxyBinding *>(binding);
1049                         proxy->removeBindings(instr.bindingSkipList);
1050                     }
1051                 }
1052             }
1053
1054             QQmlValueType *valueHandler = QQmlValueTypeFactory::valueType(instr.type);
1055             Q_ASSERT(valueHandler);
1056             valueHandler->read(target, instr.property);
1057             objects.push(valueHandler);
1058         QML_END_INSTR(FetchValueType)
1059
1060         QML_BEGIN_INSTR(PopValueType)
1061             QQmlValueType *valueHandler = 
1062                 static_cast<QQmlValueType *>(objects.pop());
1063             QObject *target = objects.top();
1064             valueHandler->write(target, instr.property, QQmlPropertyPrivate::BypassInterceptor);
1065         QML_END_INSTR(PopValueType)
1066
1067 #ifdef QML_THREADED_VME_INTERPRETER
1068     // nothing to do
1069 #else
1070         default:
1071             qFatal("QQmlCompiledData: Internal error - unknown instruction %d", genericInstr->common.instructionType);
1072             break;
1073         }
1074     }
1075 #endif
1076
1077 exceptionExit:
1078     Q_ASSERT(!states.isEmpty());
1079     Q_ASSERT(!errors->isEmpty());
1080
1081     reset();
1082
1083     return 0;
1084
1085 normalExit:
1086     Q_ASSERT(objects.count() == 1);
1087
1088     QObject *rv = objects.top();
1089
1090     objects.deallocate();
1091     lists.deallocate();
1092     states.clear();
1093
1094     return rv;
1095 }
1096
1097 void QQmlVME::reset()
1098 {
1099     Q_ASSERT(!states.isEmpty() || objects.isEmpty());
1100
1101     QRecursionWatcher<QQmlVME, &QQmlVME::recursion> watcher(this);
1102
1103     if (!objects.isEmpty() && !(states.at(0).flags & State::Deferred))
1104         delete objects.at(0); 
1105     
1106     if (!rootContext.isNull()) 
1107         rootContext->activeVMEData = 0;
1108
1109     // Remove the QQmlParserStatus and QQmlAbstractBinding back pointers
1110     blank(parserStatus);
1111     blank(bindValues);
1112
1113     while (componentAttached) {
1114         QQmlComponentAttached *a = componentAttached;
1115         a->rem();
1116     }
1117     
1118     engine = 0;
1119     objects.deallocate();
1120     lists.deallocate();
1121     bindValues.deallocate();
1122     parserStatus.deallocate();
1123 #ifdef QML_ENABLE_TRACE
1124     parserStatusData.deallocate();
1125 #endif
1126     finalizeCallbacks.clear();
1127     states.clear();
1128     rootContext = 0;
1129     creationContext = 0;
1130 }
1131
1132 // Must be called with a handle scope and context
1133 void QQmlScriptData::initialize(QQmlEngine *engine)
1134 {
1135     Q_ASSERT(m_program.IsEmpty());
1136     Q_ASSERT(engine);
1137     Q_ASSERT(!hasEngine());
1138
1139     QQmlEnginePrivate *ep = QQmlEnginePrivate::get(engine);
1140     QV8Engine *v8engine = ep->v8engine();
1141
1142     // If compilation throws an error, a surrounding v8::TryCatch will record it.
1143     v8::Local<v8::Script> program = v8engine->qmlModeCompile(m_programSource.constData(),
1144                                                              m_programSource.length(), urlString, 1);
1145     if (program.IsEmpty())
1146         return;
1147
1148     m_program = qPersistentNew<v8::Script>(program);
1149     m_programSource.clear(); // We don't need this anymore
1150
1151     addToEngine(engine);
1152
1153     addref();
1154 }
1155
1156 v8::Persistent<v8::Object> QQmlVME::run(QQmlContextData *parentCtxt, QQmlScriptData *script)
1157 {
1158     if (script->m_loaded)
1159         return qPersistentNew<v8::Object>(script->m_value);
1160
1161     v8::Persistent<v8::Object> rv;
1162
1163     Q_ASSERT(parentCtxt && parentCtxt->engine);
1164     QQmlEnginePrivate *ep = QQmlEnginePrivate::get(parentCtxt->engine);
1165     QV8Engine *v8engine = ep->v8engine();
1166
1167     if (script->hasError()) {
1168         ep->warning(script->error());
1169         return rv;
1170     }
1171
1172     bool shared = script->pragmas & QQmlScript::Object::ScriptBlock::Shared;
1173
1174     QQmlContextData *effectiveCtxt = parentCtxt;
1175     if (shared)
1176         effectiveCtxt = 0;
1177
1178     // Create the script context if required
1179     QQmlContextData *ctxt = new QQmlContextData;
1180     ctxt->isInternal = true;
1181     ctxt->isJSContext = true;
1182     if (shared)
1183         ctxt->isPragmaLibraryContext = true;
1184     else
1185         ctxt->isPragmaLibraryContext = parentCtxt->isPragmaLibraryContext;
1186     ctxt->url = script->url;
1187     ctxt->urlString = script->urlString;
1188
1189     // For backward compatibility, if there are no imports, we need to use the
1190     // imports from the parent context.  See QTBUG-17518.
1191     if (!script->importCache->isEmpty()) {
1192         ctxt->imports = script->importCache;
1193     } else if (effectiveCtxt) {
1194         ctxt->imports = effectiveCtxt->imports;
1195         ctxt->importedScripts = effectiveCtxt->importedScripts;
1196         for (int ii = 0; ii < ctxt->importedScripts.count(); ++ii)
1197             ctxt->importedScripts[ii] = qPersistentNew<v8::Object>(ctxt->importedScripts[ii]);
1198     }
1199
1200     if (ctxt->imports) {
1201         ctxt->imports->addref();
1202     }
1203
1204     if (effectiveCtxt) {
1205         ctxt->setParent(effectiveCtxt, true);
1206     } else {
1207         ctxt->engine = parentCtxt->engine; // Fix for QTBUG-21620
1208     }
1209
1210     for (int ii = 0; ii < script->scripts.count(); ++ii) {
1211         ctxt->importedScripts << run(ctxt, script->scripts.at(ii)->scriptData());
1212     }
1213
1214     v8::HandleScope handle_scope;
1215     v8::Context::Scope scope(v8engine->context());
1216
1217     v8::TryCatch try_catch;
1218     if (!script->isInitialized())
1219         script->initialize(parentCtxt->engine);
1220
1221     v8::Local<v8::Object> qmlglobal = v8engine->qmlScope(ctxt, 0);
1222
1223     if (!script->m_program.IsEmpty()) {
1224         script->m_program->Run(qmlglobal);
1225     } else {
1226         // Compilation failed.
1227         Q_ASSERT(try_catch.HasCaught());
1228     }
1229
1230     if (try_catch.HasCaught()) {
1231         v8::Local<v8::Message> message = try_catch.Message();
1232         if (!message.IsEmpty()) {
1233             QQmlError error;
1234             QQmlExpressionPrivate::exceptionToError(message, error);
1235             ep->warning(error);
1236         }
1237     } 
1238
1239     rv = qPersistentNew<v8::Object>(qmlglobal);
1240     if (shared) {
1241         script->m_value = qPersistentNew<v8::Object>(qmlglobal);
1242         script->m_loaded = true;
1243     }
1244
1245     return rv;
1246 }
1247
1248 #ifdef QML_THREADED_VME_INTERPRETER
1249 void **QQmlVME::instructionJumpTable()
1250 {
1251     static void **jumpTable = 0;
1252     if (!jumpTable) {
1253         QQmlVME dummy;
1254         QQmlVME::Interrupt i;
1255         dummy.run(0, i, &jumpTable);
1256     }
1257     return jumpTable;
1258 }
1259 #endif
1260
1261 QQmlContextData *QQmlVME::complete(const Interrupt &interrupt)
1262 {
1263     Q_ASSERT(engine ||
1264              (bindValues.isEmpty() &&
1265               parserStatus.isEmpty() &&
1266               componentAttached == 0 &&
1267               rootContext.isNull() &&
1268               finalizeCallbacks.isEmpty()));
1269
1270     if (!engine)
1271         return 0;
1272
1273     QQmlTrace trace("VME Complete");
1274 #ifdef QML_ENABLE_TRACE
1275     trace.addDetail("URL", rootComponent->url);
1276 #endif
1277
1278     ActiveVMERestorer restore(this, QQmlEnginePrivate::get(engine));
1279     QRecursionWatcher<QQmlVME, &QQmlVME::recursion> watcher(this);
1280
1281     {
1282     QQmlTrace trace("VME Binding Enable");
1283     trace.event("begin binding eval");
1284     while (!bindValues.isEmpty()) {
1285         QQmlAbstractBinding *b = bindValues.pop();
1286
1287         if (b) {
1288             b->m_mePtr = 0;
1289             b->setEnabled(true, QQmlPropertyPrivate::BypassInterceptor |
1290                                 QQmlPropertyPrivate::DontRemoveBinding);
1291         }
1292
1293         if (watcher.hasRecursed() || interrupt.shouldInterrupt())
1294             return 0;
1295     }
1296     bindValues.deallocate();
1297     }
1298
1299     {
1300     QQmlTrace trace("VME Component Complete");
1301     while (!parserStatus.isEmpty()) {
1302         QQmlParserStatus *status = parserStatus.pop();
1303 #ifdef QML_ENABLE_TRACE
1304         QQmlData *data = parserStatusData.pop();
1305 #endif
1306
1307         if (status && status->d) {
1308             status->d = 0;
1309 #ifdef QML_ENABLE_TRACE
1310             QQmlTrace trace("Component complete");
1311             trace.addDetail("URL", data->outerContext->url);
1312             trace.addDetail("Line", data->lineNumber);
1313 #endif
1314             status->componentComplete();
1315         }
1316         
1317         if (watcher.hasRecursed() || interrupt.shouldInterrupt())
1318             return 0;
1319     }
1320     parserStatus.deallocate();
1321     }
1322
1323     {
1324     QQmlTrace trace("VME Finalize Callbacks");
1325     for (int ii = 0; ii < finalizeCallbacks.count(); ++ii) {
1326         QQmlEnginePrivate::FinalizeCallback callback = finalizeCallbacks.at(ii);
1327         QObject *obj = callback.first;
1328         if (obj) {
1329             void *args[] = { 0 };
1330             QMetaObject::metacall(obj, QMetaObject::InvokeMetaMethod, callback.second, args);
1331         }
1332         if (watcher.hasRecursed())
1333             return 0;
1334     }
1335     finalizeCallbacks.clear();
1336     }
1337
1338     {
1339     QQmlTrace trace("VME Component.onCompleted Callbacks");
1340     while (componentAttached) {
1341         QQmlComponentAttached *a = componentAttached;
1342         a->rem();
1343         QQmlData *d = QQmlData::get(a->parent());
1344         Q_ASSERT(d);
1345         Q_ASSERT(d->context);
1346         a->add(&d->context->componentAttached);
1347         emit a->completed();
1348
1349         if (watcher.hasRecursed() || interrupt.shouldInterrupt())
1350             return 0;
1351     }
1352     }
1353
1354     QQmlContextData *rv = rootContext;
1355
1356     reset();
1357
1358     if (rv) rv->activeVMEData = data;
1359
1360     return rv;
1361 }
1362
1363 void QQmlVME::blank(QFiniteStack<QQmlAbstractBinding *> &bs)
1364 {
1365     for (int ii = 0; ii < bs.count(); ++ii) {
1366         QQmlAbstractBinding *b = bs.at(ii);
1367         if (b) b->m_mePtr = 0;
1368     }
1369 }
1370
1371 void QQmlVME::blank(QFiniteStack<QQmlParserStatus *> &pss)
1372 {
1373     for (int ii = 0; ii < pss.count(); ++ii) {
1374         QQmlParserStatus *ps = pss.at(ii);
1375         if(ps) ps->d = 0;
1376     }
1377 }
1378
1379 QQmlVMEGuard::QQmlVMEGuard()
1380 : m_objectCount(0), m_objects(0), m_contextCount(0), m_contexts(0)
1381 {
1382 }
1383
1384 QQmlVMEGuard::~QQmlVMEGuard()
1385 {
1386     clear();
1387 }
1388
1389 void QQmlVMEGuard::guard(QQmlVME *vme)
1390 {
1391     clear();
1392     
1393     m_objectCount = vme->objects.count();
1394     m_objects = new QQmlGuard<QObject>[m_objectCount];
1395     for (int ii = 0; ii < m_objectCount; ++ii)
1396         m_objects[ii] = vme->objects[ii];
1397
1398     m_contextCount = (vme->rootContext.isNull()?0:1) + vme->states.count();
1399     m_contexts = new QQmlGuardedContextData[m_contextCount];
1400     for (int ii = 0; ii < vme->states.count(); ++ii) 
1401         m_contexts[ii] = vme->states.at(ii).context;
1402     if (!vme->rootContext.isNull())
1403         m_contexts[m_contextCount - 1] = vme->rootContext.contextData();
1404 }
1405
1406 void QQmlVMEGuard::clear()
1407 {
1408     delete [] m_objects;
1409     delete [] m_contexts;
1410
1411     m_objectCount = 0;
1412     m_objects = 0;
1413     m_contextCount = 0;
1414     m_contexts = 0;
1415 }
1416
1417 bool QQmlVMEGuard::isOK() const
1418 {
1419     for (int ii = 0; ii < m_objectCount; ++ii)
1420         if (m_objects[ii].isNull())
1421             return false;
1422
1423     for (int ii = 0; ii < m_contextCount; ++ii)
1424         if (m_contexts[ii].isNull())
1425             return false;
1426
1427     return true;
1428 }
1429
1430 QT_END_NAMESPACE