tst_qjsengine.cpp 239 KB
Newer Older
1 2
/****************************************************************************
**
3
** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
4
** Contact: http://www.qt-project.org/
5 6 7 8 9
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
10 11 12 13 14 15
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
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 20
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
21 22 23 24 25 26 27
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
28
**
29 30 31
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
32 33 34 35 36
**
**
**
**
**
37
**
38 39 40 41 42 43 44 45
** $QT_END_LICENSE$
**
****************************************************************************/


#include <QtTest/QtTest>

#include <qjsengine.h>
46
#include <qjsvalueiterator.h>
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315
#include <qgraphicsitem.h>
#include <qstandarditemmodel.h>
#include <QtCore/qnumeric.h>
#include <stdlib.h>

Q_DECLARE_METATYPE(QList<int>)
Q_DECLARE_METATYPE(QObjectList)

// The JavaScriptCore GC marks the C stack. To try to ensure that there is
// no JSObject* left in stack memory by the compiler, we call this function
// to zap some bytes of memory before calling collectGarbage().
static void zapSomeStack()
{
    char buf[4096];
    memset(buf, 0, sizeof(buf));
}

static void collectGarbage_helper(QJSEngine &eng)
{
    zapSomeStack();
    eng.collectGarbage();
}

class tst_QJSEngine : public QObject
{
    Q_OBJECT

public:
    tst_QJSEngine();
    virtual ~tst_QJSEngine();

private slots:
    void constructWithParent();
#if 0 // FIXME: no QScriptContext
    void currentContext();
    void pushPopContext();
#endif
#if 0 // FIXME: No prototype API in QScriptEngine
    void getSetDefaultPrototype_int();
    void getSetDefaultPrototype_customType();
#endif
#if 0 // FIXME: no QScriptContext
    void newFunction();
    void newFunctionWithArg();
    void newFunctionWithProto();
#endif
    void newObject();
    void newArray();
    void newArray_HooliganTask218092();
    void newArray_HooliganTask233836();
    void newVariant();
#if 0 // FIXME: No prototype API in QScriptEngine
    void newVariant_defaultPrototype();
#endif
#if 0 // ###FIXME: No QVariant object promotion API
    void newVariant_promoteObject();
    void newVariant_replaceValue();
#endif
    void newVariant_valueOfToString();
#if 0 // ###FIXME: No QVariant object promotion API
    void newVariant_promoteNonObject();
    void newVariant_promoteNonQScriptObject();
#endif
    void newRegExp();
    void jsRegExp();
    void newDate();
    void jsParseDate();
    void newQObject();
    void newQObject_ownership();
    void newQObject_promoteObject();
    void newQObject_sameQObject();
#if 0 // FIXME: No prototype API in QScriptEngine
    void newQObject_defaultPrototype();
#endif
    void newQObject_promoteNonObject();
    void newQObject_promoteNonQScriptObject();
#if 0 // ### FIXME: No QScript Metaobject support right now
    void newQMetaObject();
    void newActivationObject();
#endif
#if 0 // ###FIXME: No setGlobalObject support - yay
    void getSetGlobalObjectSimple();
    void getSetGlobalObject();
#endif
    void globalObjectProperties();
    void globalObjectEquals();
    void globalObjectProperties_enumerate();
    void createGlobalObjectProperty();
    void globalObjectGetterSetterProperty();
#if 0 // ###FIXME: No support for setting the global object
    void customGlobalObjectWithPrototype();
#endif
    void globalObjectWithCustomPrototype();
    void builtinFunctionNames_data();
    void builtinFunctionNames();
#if 0 // ###FIXME: No syntax checking result
    void checkSyntax_data();
    void checkSyntax();
#endif
#if 0 // ###FIXME: No support for canEvaluate
    void canEvaluate_data();
    void canEvaluate();
#endif
    void evaluate_data();
    void evaluate();
#if 0 // ###FIXME: no support for c-style callbacks
    void nestedEvaluate();
#endif
#if 0 // ### FIXME: No c-style callbacks
    void uncaughtException();
#endif
    void errorMessage_QT679();
    void valueConversion_basic();
#if 0 // FIXME: No API for custom types
    void valueConversion_customType();
    void valueConversion_sequence();
#endif
    void valueConversion_QVariant();
#if 0 // FIXME: No support for custom types
    void valueConversion_hooliganTask248802();
#endif
    void valueConversion_basic2();
    void valueConversion_dateTime();
    void valueConversion_regExp();
#if 0 // FIXME: No qScriptValueFromValue
    void qScriptValueFromValue_noEngine();
#endif
#if 0 // ###FIXME: No QScriptContext
    void importExtension();
    void infiniteRecursion();
#endif
#if 0 // FIXME: No support for default prototypes
    void castWithPrototypeChain();
#endif
    void castWithMultipleInheritance();
    void collectGarbage();
#if 0 // ###FIXME: no reportAdditionalMemoryCost API
    void reportAdditionalMemoryCost();
#endif
    void gcWithNestedDataStructure();
#if 0 // ###FIXME: No processEvents handling
    void processEventsWhileRunning();
    void processEventsWhileRunning_function();
    void throwErrorFromProcessEvents_data();
    void throwErrorFromProcessEvents();
    void disableProcessEventsInterval();
#endif
    void stacktrace();
    void numberParsing_data();
    void numberParsing();
    void automaticSemicolonInsertion();
#if 0 // ###FIXME: no abortEvaluation API
    void abortEvaluation_notEvaluating();
    void abortEvaluation_data();
    void abortEvaluation();
    void abortEvaluation_tryCatch();
    void abortEvaluation_fromNative();
    void abortEvaluation_QTBUG9433();
#endif
#if 0 // ###FIXME: no QScriptEngine::isEvaluating
    void isEvaluating_notEvaluating();
    void isEvaluating_fromNative();
    void isEvaluating_fromEvent();
#endif
#if 0 // ###FIXME: depracated
    void printFunctionWithCustomHandler();
    void printThrowsException();
#endif
    void errorConstructors();
    void argumentsProperty_globalContext();
    void argumentsProperty_JS();
#if 0 // ###FIXME: no QScriptContext API
    void argumentsProperty_evaluateInNativeFunction();
#endif
    void jsNumberClass();
    void jsForInStatement_simple();
    void jsForInStatement_prototypeProperties();
    void jsForInStatement_mutateWhileIterating();
    void jsForInStatement_arrays();
    void jsForInStatement_nullAndUndefined();
    void jsFunctionDeclarationAsStatement();
    void stringObjects();
    void jsStringPrototypeReplaceBugs();
    void getterSetterThisObject_global();
    void getterSetterThisObject_plain();
    void getterSetterThisObject_prototypeChain();
#if 0 // ###FIXME: no QScriptContext API
    void getterSetterThisObject_activation();
#endif
    void jsContinueInSwitch();
    void jsShadowReadOnlyPrototypeProperty();
    void jsReservedWords_data();
    void jsReservedWords();
    void jsFutureReservedWords_data();
    void jsFutureReservedWords();
    void jsThrowInsideWithStatement();
#if 0 // ###FIXME: No QScriptEngineAgent API
    void getSetAgent_ownership();
    void getSetAgent_deleteAgent();
    void getSetAgent_differentEngine();
#endif
#if 0 // ###FIXME: No QScriptString API
    void reentrancy_stringHandles();
#endif
#if 0 // ###FIXME: No processEventsInterval API
    void reentrancy_processEventsInterval();
#endif
#if 0 // FIXME: No support for custom types
    void reentrancy_typeConversion();
#endif
    void reentrancy_globalObjectProperties();
    void reentrancy_Array();
    void reentrancy_objectCreation();
    void jsIncDecNonObjectProperty();
#if 0 // ###FIXME: no installTranslatorFunctions API
    void installTranslatorFunctions();
    void translateScript_data();
    void translateScript();
    void translateScript_crossScript();
    void translateScript_callQsTrFromNative();
    void translateScript_trNoOp();
    void translateScript_callQsTrFromCpp();
    void translateWithInvalidArgs_data();
    void translateWithInvalidArgs();
    void translationContext_data();
    void translationContext();
    void translateScriptIdBased();
    void translateScriptUnicode_data();
    void translateScriptUnicode();
    void translateScriptUnicodeIdBased_data();
    void translateScriptUnicodeIdBased();
    void translateFromBuiltinCallback();
#endif
#if 0 // ###FIXME: No QScriptValue::scope API
    void functionScopes();
#endif
#if 0 // ###FIXME: No QScriptContext API
    void nativeFunctionScopes();
#endif
#if 0 // ###FIXME: No QScriptProgram API
    void evaluateProgram();
    void evaluateProgram_customScope();
    void evaluateProgram_closure();
    void evaluateProgram_executeLater();
    void evaluateProgram_multipleEngines();
    void evaluateProgram_empty();
#endif
#if 0 // ###FIXME: No QScriptContext API
    void collectGarbageAfterConnect();
    void collectGarbageAfterNativeArguments();
    void promoteThisObjectToQObjectInConstructor();
#endif
#if 0 // ###FIXME: No QScript MetaObject API
    void scriptValueFromQMetaObject();
#endif

    void qRegExpInport_data();
    void qRegExpInport();
#if 0 // ###FIXME: No QScriptContext API
    void reentrency();
#endif
#if 0 // ###FIXME: No QSCriptDeclarativeClass API
    void newFixedStaticScopeObject();
    void newGrowingStaticScopeObject();
#endif
    void dateRoundtripJSQtJS();
    void dateRoundtripQtJSQt();
    void dateConversionJSQt();
    void dateConversionQtJS();
316
    void functionPrototypeExtensions();
317
    void threadedEngine();
318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349
};

tst_QJSEngine::tst_QJSEngine()
{
}

tst_QJSEngine::~tst_QJSEngine()
{
}

void tst_QJSEngine::constructWithParent()
{
    QPointer<QJSEngine> ptr;
    {
        QObject obj;
        QJSEngine *engine = new QJSEngine(&obj);
        ptr = engine;
    }
    QVERIFY(ptr == 0);
}

#if 0 // FIXME: no QScriptContext
void tst_QJSEngine::currentContext()
{
    QScriptEngine eng;
    QScriptContext *globalCtx = eng.currentContext();
    QVERIFY(globalCtx != 0);
    QVERIFY(globalCtx->parentContext() == 0);
    QCOMPARE(globalCtx->engine(), &eng);
    QCOMPARE(globalCtx->argumentCount(), 0);
    QCOMPARE(globalCtx->backtrace().size(), 1);
    QVERIFY(!globalCtx->isCalledAsConstructor());
350
    QVERIFY(globalCtx->callee().isUndefined());
351 352 353 354 355 356 357 358 359 360 361 362 363 364
    QCOMPARE(globalCtx->state(), QScriptContext::NormalState);
    QVERIFY(globalCtx->thisObject().strictlyEquals(eng.globalObject()));
    QVERIFY(globalCtx->activationObject().strictlyEquals(eng.globalObject()));
    QVERIFY(globalCtx->argumentsObject().isObject());
}

void tst_QJSEngine::pushPopContext()
{
    QScriptEngine eng;
    QScriptContext *globalCtx = eng.currentContext();
    QScriptContext *ctx = eng.pushContext();
    QVERIFY(ctx != 0);
    QCOMPARE(ctx->parentContext(), globalCtx);
    QVERIFY(!ctx->isCalledAsConstructor());
365
    QVERIFY(ctx->callee().isUndefined());
366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436
    QVERIFY(ctx->thisObject().strictlyEquals(eng.globalObject()));
    QCOMPARE(ctx->argumentCount(), 0);
    QCOMPARE(ctx->backtrace().size(), 2);
    QCOMPARE(ctx->engine(), &eng);
    QCOMPARE(ctx->state(), QScriptContext::NormalState);
    QVERIFY(ctx->activationObject().isObject());
    QVERIFY(ctx->argumentsObject().isObject());

    QScriptContext *ctx2 = eng.pushContext();
    QVERIFY(ctx2 != 0);
    QCOMPARE(ctx2->parentContext(), ctx);
    QVERIFY(!ctx2->activationObject().strictlyEquals(ctx->activationObject()));
    QVERIFY(!ctx2->argumentsObject().strictlyEquals(ctx->argumentsObject()));

    eng.popContext();
    eng.popContext();
    QTest::ignoreMessage(QtWarningMsg, "QScriptEngine::popContext() doesn't match with pushContext()");
    eng.popContext(); // ignored
    QTest::ignoreMessage(QtWarningMsg, "QScriptEngine::popContext() doesn't match with pushContext()");
    eng.popContext(); // ignored
}

static QScriptValue myFunction(QScriptContext *, QScriptEngine *eng)
{
    return eng->nullValue();
}

static QScriptValue myFunctionWithVoidArg(QScriptContext *, QScriptEngine *eng, void *)
{
    return eng->nullValue();
}

static QScriptValue myThrowingFunction(QScriptContext *ctx, QScriptEngine *)
{
    return ctx->throwError("foo");
}

static QScriptValue myFunctionThatReturns(QScriptContext *, QScriptEngine *eng)
{
    return QScriptValue(eng, 42);
}

static QScriptValue myFunctionThatReturnsWithoutEngine(QScriptContext *, QScriptEngine *)
{
    return QScriptValue(1024);
}

static QScriptValue myFunctionThatReturnsWrongEngine(QScriptContext *, QScriptEngine *, void *arg)
{
    QScriptEngine* wrongEngine = reinterpret_cast<QScriptEngine*>(arg);
    return QScriptValue(wrongEngine, 42);
}

static QScriptValue sumFunction(QScriptContext *context, QScriptEngine *engine)
{
    int sum = 0;

    for (int i = 0; i < context->argumentCount(); i++) {
        QScriptValue n = context->argument(i);
        if (n.isNumber())
            sum += n.toInteger();
    }

    return QScriptValue(engine, sum);
}

void tst_QJSEngine::newFunction()
{
    QScriptEngine eng;
    {
        QScriptValue fun = eng.newFunction(myFunction);
437
        QVERIFY(!fun.isUndefined());
438
        QCOMPARE(fun.isCallable(), true);
439 440 441 442 443 444 445 446 447
        QCOMPARE(fun.isObject(), true);
        QCOMPARE(fun.scriptClass(), (QScriptClass*)0);
        // a prototype property is automatically constructed
        {
            QScriptValue prot = fun.property("prototype", QScriptValue::ResolveLocal);
            QVERIFY(prot.isObject());
            QVERIFY(prot.property("constructor").strictlyEquals(fun));
        }
        // prototype should be Function.prototype
448
        QVERIFY(!fun.prototype().isUndefined());
449
        QCOMPARE(fun.prototype().isCallable(), true);
450 451 452
        QCOMPARE(fun.prototype().strictlyEquals(eng.evaluate("Function.prototype")), true);

        QCOMPARE(fun.call().isNull(), true);
453
        QCOMPARE(fun.callAsConstructor().isObject(), true);
454 455 456 457 458 459 460 461
    }
}

void tst_QJSEngine::newFunctionWithArg()
{
    QScriptEngine eng;
    {
        QScriptValue fun = eng.newFunction(myFunctionWithVoidArg, (void*)this);
462
        QVERIFY(fun.isCallable());
463 464 465 466 467 468 469 470
        QCOMPARE(fun.scriptClass(), (QScriptClass*)0);
        // a prototype property is automatically constructed
        {
            QScriptValue prot = fun.property("prototype", QScriptValue::ResolveLocal);
            QVERIFY(prot.isObject());
            QVERIFY(prot.property("constructor").strictlyEquals(fun));
        }
        // prototype should be Function.prototype
471
        QVERIFY(!fun.prototype().isUndefined());
472
        QCOMPARE(fun.prototype().isCallable(), true);
473 474 475
        QCOMPARE(fun.prototype().strictlyEquals(eng.evaluate("Function.prototype")), true);

        QCOMPARE(fun.call().isNull(), true);
476
        QCOMPARE(fun.callAsConstructor().isObject(), true);
477 478 479 480 481 482 483 484 485
    }
}

void tst_QJSEngine::newFunctionWithProto()
{
    QScriptEngine eng;
    {
        QScriptValue proto = eng.newObject();
        QScriptValue fun = eng.newFunction(myFunction, proto);
486
        QVERIFY(!fun.isUndefined());
487
        QCOMPARE(fun.isCallable(), true);
488 489
        QCOMPARE(fun.isObject(), true);
        // internal prototype should be Function.prototype
490
        QVERIFY(!fun.prototype().isUndefined());
491
        QCOMPARE(fun.prototype().isCallable(), true);
492 493 494 495 496 497
        QCOMPARE(fun.prototype().strictlyEquals(eng.evaluate("Function.prototype")), true);
        // public prototype should be the one we passed
        QCOMPARE(fun.property("prototype").strictlyEquals(proto), true);
        QCOMPARE(proto.property("constructor").strictlyEquals(fun), true);

        QCOMPARE(fun.call().isNull(), true);
498
        QCOMPARE(fun.callAsConstructor().isObject(), true);
499 500 501 502
    }
    // whether the return value is correct
    {
        QScriptValue fun = eng.newFunction(myFunctionThatReturns);
503
        QVERIFY(!fun.isUndefined());
504
        QCOMPARE(fun.isCallable(), true);
505 506 507 508
        QCOMPARE(fun.isObject(), true);

        QScriptValue result = fun.call();
        QCOMPARE(result.isNumber(), true);
509
        QCOMPARE(result.toInt(), 42);
510 511 512 513
    }
    // whether the return value is assigned to the correct engine
    {
        QScriptValue fun = eng.newFunction(myFunctionThatReturnsWithoutEngine);
514
        QVERIFY(!fun.isUndefined());
515
        QCOMPARE(fun.isCallable(), true);
516 517 518 519 520
        QCOMPARE(fun.isObject(), true);

        QScriptValue result = fun.call();
        QCOMPARE(result.engine(), &eng);
        QCOMPARE(result.isNumber(), true);
521
        QCOMPARE(result.toInt(), 1024);
522 523 524 525 526 527
    }
    // whether the return value is undefined when returning a value with wrong engine
    {
        QScriptEngine wrongEngine;

        QScriptValue fun = eng.newFunction(myFunctionThatReturnsWrongEngine, reinterpret_cast<void *>(&wrongEngine));
528
        QVERIFY(!fun.isUndefined());
529
        QCOMPARE(fun.isCallable(), true);
530 531 532 533 534 535 536 537 538 539 540
        QCOMPARE(fun.isObject(), true);

        QTest::ignoreMessage(QtWarningMsg, "QScriptValue::call(): Value from different engine returned from native function, returning undefined value instead.");
        QScriptValue result = fun.call();
        QCOMPARE(result.isUndefined(), true);
    }
    // checking if arguments are passed correctly
    {
        QScriptEngine wrongEngine;

        QScriptValue fun = eng.newFunction(sumFunction);
541
        QVERIFY(!fun.isUndefined());
542
        QCOMPARE(fun.isCallable(), true);
543 544 545 546
        QCOMPARE(fun.isObject(), true);

        QScriptValue result = fun.call();
        QCOMPARE(result.isNumber(), true);
547
        QCOMPARE(result.toInt(), 0);
548 549 550

        result = fun.call(QScriptValue(), QScriptValueList() << 1);
        QCOMPARE(result.isNumber(), true);
551
        QCOMPARE(result.toInt(), 1);
552 553 554

        result = fun.call(QScriptValue(), QScriptValueList() << 1 << 2 << 3);
        QCOMPARE(result.isNumber(), true);
555
        QCOMPARE(result.toInt(), 6);
556 557 558

        result = fun.call(QScriptValue(), QScriptValueList() << 1 << 2 << 3 << 4);
        QCOMPARE(result.isNumber(), true);
559
        QCOMPARE(result.toInt(), 10);
560 561 562 563 564 565 566 567
    }
}
#endif

void tst_QJSEngine::newObject()
{
    QJSEngine eng;
    QJSValue object = eng.newObject();
568
    QVERIFY(!object.isUndefined());
569
    QCOMPARE(object.isObject(), true);
570
    QCOMPARE(object.isCallable(), false);
571 572
// ###FIXME: No QScriptClass    QCOMPARE(object.scriptClass(), (QScriptClass*)0);
    // prototype should be Object.prototype
573
    QVERIFY(!object.prototype().isUndefined());
574 575 576 577 578 579 580 581
    QCOMPARE(object.prototype().isObject(), true);
    QCOMPARE(object.prototype().strictlyEquals(eng.evaluate("Object.prototype")), true);
}

void tst_QJSEngine::newArray()
{
    QJSEngine eng;
    QJSValue array = eng.newArray();
582
    QVERIFY(!array.isUndefined());
583 584
    QCOMPARE(array.isArray(), true);
    QCOMPARE(array.isObject(), true);
585
    QVERIFY(!array.isCallable());
586 587
// ###FIXME: No QScriptClass    QCOMPARE(array.scriptClass(), (QScriptClass*)0);
    // prototype should be Array.prototype
588
    QVERIFY(!array.prototype().isUndefined());
589 590 591 592 593 594 595 596 597 598
    QCOMPARE(array.prototype().isArray(), true);
    QCOMPARE(array.prototype().strictlyEquals(eng.evaluate("Array.prototype")), true);
}

void tst_QJSEngine::newArray_HooliganTask218092()
{
    QJSEngine eng;
    {
        QJSValue ret = eng.evaluate("[].splice(0, 0, 'a')");
        QVERIFY(ret.isArray());
599
        QCOMPARE(ret.property("length").toInt(), 0);
600 601 602 603
    }
    {
        QJSValue ret = eng.evaluate("['a'].splice(0, 1, 'b')");
        QVERIFY(ret.isArray());
604
        QCOMPARE(ret.property("length").toInt(), 1);
605 606 607 608
    }
    {
        QJSValue ret = eng.evaluate("['a', 'b'].splice(0, 1, 'c')");
        QVERIFY(ret.isArray());
609
        QCOMPARE(ret.property("length").toInt(), 1);
610 611 612 613
    }
    {
        QJSValue ret = eng.evaluate("['a', 'b', 'c'].splice(0, 2, 'd')");
        QVERIFY(ret.isArray());
614
        QCOMPARE(ret.property("length").toInt(), 2);
615 616 617 618
    }
    {
        QJSValue ret = eng.evaluate("['a', 'b', 'c'].splice(1, 2, 'd', 'e', 'f')");
        QVERIFY(ret.isArray());
619
        QCOMPARE(ret.property("length").toInt(), 2);
620 621 622 623 624 625 626 627 628 629 630 631 632 633
    }
}

void tst_QJSEngine::newArray_HooliganTask233836()
{
    QJSEngine eng;
    {
        // According to ECMA-262, this should cause a RangeError.
        QJSValue ret = eng.evaluate("a = new Array(4294967295); a.push('foo')");
        QVERIFY(ret.isError() && ret.toString().contains(QLatin1String("RangeError")));
    }
    {
        QJSValue ret = eng.newArray(0xFFFFFFFF);
        QEXPECT_FAIL("", "The maximum length of arrays is defined by v8 currently and differs from QtScript", Abort);
634
        QCOMPARE(ret.property("length").toUInt(), uint(0xFFFFFFFF));
635
        ret.setProperty(0xFFFFFFFF, 123);
636
        QCOMPARE(ret.property("length").toUInt(), uint(0xFFFFFFFF));
637
        QVERIFY(ret.property(0xFFFFFFFF).isNumber());
638
        QCOMPARE(ret.property(0xFFFFFFFF).toInt(), 123);
639
        ret.setProperty(123, 456);
640
        QCOMPARE(ret.property("length").toUInt(), uint(0xFFFFFFFF));
641
        QVERIFY(ret.property(123).isNumber());
642
        QCOMPARE(ret.property(123).toInt(), 456);
643 644 645 646 647 648 649
    }
}

void tst_QJSEngine::newVariant()
{
    QJSEngine eng;
    {
650
        QJSValue opaque = eng.toScriptValue(QVariant(QPoint(1, 2)));
651
        QVERIFY(!opaque.isUndefined());
652
        QCOMPARE(opaque.isVariant(), true);
653
        QVERIFY(!opaque.isCallable());
654
        QCOMPARE(opaque.isObject(), true);
655
        QVERIFY(!opaque.prototype().isUndefined());
656 657
        QEXPECT_FAIL("", "FIXME: newly created QObject's prototype is an JS Object", Continue);
        QCOMPARE(opaque.prototype().isVariant(), true);
658
        QVERIFY(opaque.property("valueOf").callWithInstance(opaque).equals(opaque));
659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693
    }
}

#if 0 // FIXME: No prototype API in QScriptEngine
void tst_QJSEngine::newVariant_defaultPrototype()
{
    // default prototype should be set automatically
    QScriptEngine eng;
    {
        QScriptValue proto = eng.newObject();
        eng.setDefaultPrototype(qMetaTypeId<QString>(), proto);
        QScriptValue ret = eng.newVariant(QVariant(QString::fromLatin1("hello")));
        QVERIFY(ret.isVariant());
// ###FIXME: No QScriptClass        QCOMPARE(ret.scriptClass(), (QScriptClass*)0);
        QVERIFY(ret.prototype().strictlyEquals(proto));
        eng.setDefaultPrototype(qMetaTypeId<QString>(), QScriptValue());
        QScriptValue ret2 = eng.newVariant(QVariant(QString::fromLatin1("hello")));
        QVERIFY(ret2.isVariant());
        QVERIFY(!ret2.prototype().strictlyEquals(proto));
    }
}
#endif

#if 0 // ###FIXME: No QVariant object promotion API
void tst_QJSEngine::newVariant_promoteObject()
{
    // "promote" plain object to variant
    QScriptEngine eng;
    {
        QScriptValue object = eng.newObject();
        object.setProperty("foo", eng.newObject());
        object.setProperty("bar", object.property("foo"));
        QVERIFY(object.property("foo").isObject());
        QVERIFY(!object.property("foo").isVariant());
        QScriptValue originalProto = object.property("foo").prototype();
694
        QSKIP("It is not possible to promote plain object to a wrapper");
695
        QScriptValue ret = eng.newVariant(object.property("foo"), QVariant(123));
696
        QVERIFY(ret.isObject());
697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713
        QVERIFY(ret.strictlyEquals(object.property("foo")));
        QVERIFY(ret.isVariant());
        QVERIFY(object.property("foo").isVariant());
        QVERIFY(object.property("bar").isVariant());
        QCOMPARE(ret.toVariant(), QVariant(123));
        QVERIFY(ret.prototype().strictlyEquals(originalProto));
    }
}

void tst_QJSEngine::newVariant_replaceValue()
{
    // replace value of existing object
    QScriptEngine eng;
    {
        QScriptValue object = eng.newVariant(QVariant(123));
        for (int x = 0; x < 2; ++x) {
            QScriptValue ret = eng.newVariant(object, QVariant(456));
714
            QVERIFY(!ret.isUndefined());
715 716 717 718 719 720 721 722 723 724 725 726 727
            QVERIFY(ret.strictlyEquals(object));
            QVERIFY(ret.isVariant());
            QCOMPARE(ret.toVariant(), QVariant(456));
        }
    }
}
#endif

void tst_QJSEngine::newVariant_valueOfToString()
{
    // valueOf() and toString()
    QJSEngine eng;
    {
728
        QJSValue object = eng.toScriptValue(QVariant(QPoint(10, 20)));
729
        QJSValue value = object.property("valueOf").callWithInstance(object);
730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749
        QVERIFY(value.isObject());
        QVERIFY(value.strictlyEquals(object));
        QCOMPARE(object.toString(), QString::fromLatin1("QVariant(QPoint)"));
    }
}

#if 0 // ###FIXME: No QVariant object promotion API
void tst_QJSEngine::newVariant_promoteNonObject()
{
    QScriptEngine eng;
    {
        QVariant var(456);
        QScriptValue ret = eng.newVariant(123, var);
        QVERIFY(ret.isVariant());
        QCOMPARE(ret.toVariant(), var);
    }
}

void tst_QJSEngine::newVariant_promoteNonQScriptObject()
{
750
    QSKIP("This test relay on limitation of QtScript JSC implementation");
751 752 753 754
    QScriptEngine eng;
    {
        QTest::ignoreMessage(QtWarningMsg, "QScriptEngine::newVariant(): changing class of non-QScriptObject not supported");
        QScriptValue ret = eng.newVariant(eng.newArray(), 123);
755
        QVERIFY(ret.isUndefined());
756 757 758 759 760 761
    }
}
#endif

void tst_QJSEngine::newRegExp()
{
762
    QSKIP("Test failing - QTBUG-22238");
763
    QJSEngine eng;
764
    QJSValue rexp = eng.toScriptValue(QRegExp("foo"));
765
    QVERIFY(!rexp.isUndefined());
766 767 768 769
    QCOMPARE(rexp.isRegExp(), true);
    QCOMPARE(rexp.isObject(), true);
    QVERIFY(rexp.isCallable()); // in JSC, RegExp objects are callable
    // prototype should be RegExp.prototype
770
    QVERIFY(!rexp.prototype().isUndefined());
771 772 773
    QCOMPARE(rexp.prototype().isObject(), true);
    QCOMPARE(rexp.prototype().isRegExp(), false);
    QCOMPARE(rexp.prototype().strictlyEquals(eng.evaluate("RegExp.prototype")), true);
774

775
    QCOMPARE(qjsvalue_cast<QRegExp>(rexp).pattern(), QRegExp("foo").pattern());
776 777 778 779
}

void tst_QJSEngine::jsRegExp()
{
780
    QSKIP("Test failing - QTBUG-22238");
Martin Jones's avatar
Martin Jones committed
781

782 783 784 785 786 787 788 789 790 791 792 793 794
    // See ECMA-262 Section 15.10, "RegExp Objects".
    // These should really be JS-only tests, as they test the implementation's
    // ECMA-compliance, not the C++ API. Compliance should already be covered
    // by the Mozilla tests (qscriptjstestsuite).
    // We can consider updating the expected results of this test if the
    // RegExp implementation changes.

    QJSEngine eng;
    QJSValue r = eng.evaluate("/foo/gim");
    QVERIFY(r.isRegExp());
    QCOMPARE(r.toString(), QString::fromLatin1("/foo/gim"));

    QJSValue rxCtor = eng.globalObject().property("RegExp");
795
    QJSValue r2 = rxCtor.call(QJSValueList() << r);
796 797 798
    QVERIFY(r2.isRegExp());
    QVERIFY(r2.strictlyEquals(r));

799
    QJSValue r3 = rxCtor.call(QJSValueList() << r << "gim");
800 801 802
    QVERIFY(r3.isError());
    QVERIFY(r3.toString().contains(QString::fromLatin1("TypeError"))); // Cannot supply flags when constructing one RegExp from another

803
    QJSValue r4 = rxCtor.call(QJSValueList() << "foo" << "gim");
804 805
    QVERIFY(r4.isRegExp());

806
    QJSValue r5 = rxCtor.callAsConstructor(QJSValueList() << r);
807 808 809 810 811 812 813
    QVERIFY(r5.isRegExp());
    QCOMPARE(r5.toString(), QString::fromLatin1("/foo/gim"));
    // In JSC, constructing a RegExp from another produces the same identical object.
    // This is different from SpiderMonkey and old back-end.
    QVERIFY(!r5.strictlyEquals(r));

    QEXPECT_FAIL("", "V8 and jsc ignores invalid flags", Continue); //https://bugs.webkit.org/show_bug.cgi?id=41614
814
    QJSValue r6 = rxCtor.callAsConstructor(QJSValueList() << "foo" << "bar");
815 816 817 818 819 820 821 822 823 824 825 826 827 828 829
    QVERIFY(r6.isError());
    // QVERIFY(r6.toString().contains(QString::fromLatin1("SyntaxError"))); // Invalid regular expression flag


    QJSValue r7 = eng.evaluate("/foo/gimp");
    /*  v8 and jsc ignores invalid flags
    QVERIFY(r7.isError());
    QVERIFY(r7.toString().contains(QString::fromLatin1("SyntaxError"))); // Invalid regular expression flag
    */

    // JSC doesn't complain about duplicate flags.
    QJSValue r8 = eng.evaluate("/foo/migmigmig");
    QVERIFY(r8.isRegExp());
    QCOMPARE(r8.toString(), QString::fromLatin1("/foo/gim"));

830
    QJSValue r9 = rxCtor.callAsConstructor();
831 832 833
    QVERIFY(r9.isRegExp());
    QCOMPARE(r9.toString(), QString::fromLatin1("/(?:)/"));

834
    QJSValue r10 = rxCtor.callAsConstructor(QJSValueList() << "" << "gim");
835 836 837
    QVERIFY(r10.isRegExp());
    QCOMPARE(r10.toString(), QString::fromLatin1("/(?:)/gim"));

838
    QJSValue r11 = rxCtor.callAsConstructor(QJSValueList() << "{1.*}" << "g");
839 840 841 842 843 844 845 846 847
    QVERIFY(r11.isRegExp());
    QCOMPARE(r11.toString(), QString::fromLatin1("/{1.*}/g"));
}

void tst_QJSEngine::newDate()
{
    QJSEngine eng;

    {
848
        QJSValue date = eng.evaluate("new Date(0)");
849
        QVERIFY(!date.isUndefined());
850 851
        QCOMPARE(date.isDate(), true);
        QCOMPARE(date.isObject(), true);
852
        QVERIFY(!date.isCallable());
853
        // prototype should be Date.prototype
854
        QVERIFY(!date.prototype().isUndefined());
855 856 857 858 859 860
        QCOMPARE(date.prototype().isDate(), true);
        QCOMPARE(date.prototype().strictlyEquals(eng.evaluate("Date.prototype")), true);
    }

    {
        QDateTime dt = QDateTime(QDate(1, 2, 3), QTime(4, 5, 6, 7), Qt::LocalTime);
861
        QJSValue date = eng.toScriptValue(dt);
862
        QVERIFY(!date.isUndefined());
863 864 865
        QCOMPARE(date.isDate(), true);
        QCOMPARE(date.isObject(), true);
        // prototype should be Date.prototype
866
        QVERIFY(!date.prototype().isUndefined());
867 868 869 870 871 872 873 874
        QCOMPARE(date.prototype().isDate(), true);
        QCOMPARE(date.prototype().strictlyEquals(eng.evaluate("Date.prototype")), true);

        QCOMPARE(date.toDateTime(), dt);
    }

    {
        QDateTime dt = QDateTime(QDate(1, 2, 3), QTime(4, 5, 6, 7), Qt::UTC);
875
        QJSValue date = eng.toScriptValue(dt);
876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893
        // toDateTime() result should be in local time
        QCOMPARE(date.toDateTime(), dt.toLocalTime());
    }
}

void tst_QJSEngine::jsParseDate()
{
    QJSEngine eng;
    // Date.parse() should return NaN when it fails
    {
        QJSValue ret = eng.evaluate("Date.parse()");
        QVERIFY(ret.isNumber());
        QVERIFY(qIsNaN(ret.toNumber()));
    }

    // Date.parse() should be able to parse the output of Date().toString()
    {
        QJSValue ret = eng.evaluate("var x = new Date(); var s = x.toString(); s == new Date(Date.parse(s)).toString()");
894 895
        QVERIFY(ret.isBool());
        QCOMPARE(ret.toBool(), true);
896 897 898 899 900 901
    }
}

void tst_QJSEngine::newQObject()
{
    QJSEngine eng;
902
    QObject temp;
903 904 905 906 907 908 909 910

    {
        QJSValue qobject = eng.newQObject(0);
        QCOMPARE(qobject.isNull(), true);
        QCOMPARE(qobject.isObject(), false);
        QCOMPARE(qobject.toQObject(), (QObject *)0);
    }
    {
911
        QJSValue qobject = eng.newQObject(&temp);
912
        QVERIFY(!qobject.isUndefined());
913 914
        QCOMPARE(qobject.isQObject(), true);
        QCOMPARE(qobject.isObject(), true);
915
        QCOMPARE(qobject.toQObject(), (QObject *)&temp);
916
        QVERIFY(!qobject.isCallable());
917
        // prototype should be QObject.prototype
918
        QCOMPARE(qobject.prototype().isObject(), true);
919 920 921 922 923 924 925 926
        QEXPECT_FAIL("", "FIXME: newly created QObject's prototype is an JS Object", Continue);
        QCOMPARE(qobject.prototype().isQObject(), true);
// ###FIXME: No QScriptClass        QCOMPARE(qobject.scriptClass(), (QScriptClass*)0);
    }
}

void tst_QJSEngine::newQObject_ownership()
{
927
    QJSEngine eng;
928 929 930 931
    {
        QPointer<QObject> ptr = new QObject();
        QVERIFY(ptr != 0);
        {
932
            QJSValue v = eng.newQObject(ptr);
933
        }
934
        collectGarbage_helper(eng);
935
        if (ptr)
936
            QGuiApplication::sendPostedEvents(ptr, QEvent::DeferredDelete);
937 938 939
        QVERIFY(ptr == 0);
    }
    {
940
        QPointer<QObject> ptr = new QObject(this);
941 942
        QVERIFY(ptr != 0);
        {
943
            QJSValue v = eng.newQObject(ptr);
944 945
        }
        QObject *before = ptr;
946
        collectGarbage_helper(eng);
947 948 949 950 951 952
        QVERIFY(ptr == before);
        delete ptr;
    }
    {
        QObject *parent = new QObject();
        QObject *child = new QObject(parent);
953
        QJSValue v = eng.newQObject(child);
954 955 956 957 958 959 960 961
        QCOMPARE(v.toQObject(), child);
        delete parent;
        QCOMPARE(v.toQObject(), (QObject *)0);
    }
    {
        QPointer<QObject> ptr = new QObject();
        QVERIFY(ptr != 0);
        {
962
            QJSValue v = eng.newQObject(ptr);
963
        }
964
        collectGarbage_helper(eng);
965 966
        // no parent, so it should be like ScriptOwnership
        if (ptr)
967
            QGuiApplication::sendPostedEvents(ptr, QEvent::DeferredDelete);
968 969 970 971 972 973 974
        QVERIFY(ptr == 0);
    }
    {
        QObject *parent = new QObject();
        QPointer<QObject> child = new QObject(parent);
        QVERIFY(child != 0);
        {
975
            QJSValue v = eng.newQObject(child);
976
        }
977
        collectGarbage_helper(eng);
978 979 980 981 982 983 984 985 986 987 988 989 990 991 992
        // has parent, so it should be like QtOwnership
        QVERIFY(child != 0);
        delete parent;
    }
}

void tst_QJSEngine::newQObject_promoteObject()
{
#if 0 // ### FIXME: object promotion is not supported
    QScriptEngine eng;
    // "promote" plain object to QObject
    {
        QScriptValue obj = eng.newObject();
        QScriptValue originalProto = obj.prototype();
        QScriptValue ret = eng.newQObject(obj, this);
993
        QVERIFY(!ret.isUndefined());
994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020
        QVERIFY(ret.isQObject());
        QVERIFY(ret.strictlyEquals(obj));
        QVERIFY(obj.isQObject());
        QCOMPARE(ret.toQObject(), (QObject *)this);
        QVERIFY(ret.prototype().strictlyEquals(originalProto));
        QScriptValue val = ret.property("objectName");
        QVERIFY(val.isString());
    }
    // "promote" variant object to QObject
    {
        QScriptValue obj = eng.newVariant(123);
        QVERIFY(obj.isVariant());
        QScriptValue originalProto = obj.prototype();
        QScriptValue ret = eng.newQObject(obj, this);
        QVERIFY(ret.isQObject());
        QVERIFY(ret.strictlyEquals(obj));
        QVERIFY(obj.isQObject());
        QCOMPARE(ret.toQObject(), (QObject *)this);
        QVERIFY(ret.prototype().strictlyEquals(originalProto));
    }
    // replace QObject* of existing object
    {
        QScriptValue object = eng.newVariant(123);
        QScriptValue originalProto = object.prototype();
        QObject otherQObject;
        for (int x = 0; x < 2; ++x) {
            QScriptValue ret = eng.newQObject(object, &otherQObject);
1021
            QVERIFY(!ret.isUndefined());
1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033
            QVERIFY(ret.isQObject());
            QVERIFY(ret.strictlyEquals(object));
            QCOMPARE(ret.toQObject(), (QObject *)&otherQObject);
            QVERIFY(ret.prototype().strictlyEquals(originalProto));
        }
    }
#endif
}

void tst_QJSEngine::newQObject_sameQObject()
{
#if 0 // ###FIXME: No QObjectWrapOptions API
1034
    QSKIP("This test strongly relies on strictlyEquals feature that would change in near future");
1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071
    QScriptEngine eng;
    // calling newQObject() several times with same object
    for (int x = 0; x < 2; ++x) {
        QObject qobj;
        // the default is to create a new wrapper object
        QScriptValue obj1 = eng.newQObject(&qobj);
        QScriptValue obj2 = eng.newQObject(&qobj);
        QVERIFY(!obj2.strictlyEquals(obj1));

        QScriptEngine::QObjectWrapOptions opt = 0;
        bool preferExisting = (x != 0);
        if (preferExisting)
            opt |= QScriptEngine::PreferExistingWrapperObject;

        QScriptValue obj3 = eng.newQObject(&qobj, QScriptEngine::AutoOwnership, opt);
        QVERIFY(!obj3.strictlyEquals(obj2));
        QScriptValue obj4 = eng.newQObject(&qobj, QScriptEngine::AutoOwnership, opt);
        QCOMPARE(obj4.strictlyEquals(obj3), preferExisting);

        QScriptValue obj5 = eng.newQObject(&qobj, QScriptEngine::ScriptOwnership, opt);
        QVERIFY(!obj5.strictlyEquals(obj4));
        QScriptValue obj6 = eng.newQObject(&qobj, QScriptEngine::ScriptOwnership, opt);
        QCOMPARE(obj6.strictlyEquals(obj5), preferExisting);

        QScriptValue obj7 = eng.newQObject(&qobj, QScriptEngine::ScriptOwnership,
                                           QScriptEngine::ExcludeSuperClassMethods | opt);
        QVERIFY(!obj7.strictlyEquals(obj6));
        QScriptValue obj8 = eng.newQObject(&qobj, QScriptEngine::ScriptOwnership,
                                           QScriptEngine::ExcludeSuperClassMethods | opt);
        QCOMPARE(obj8.strictlyEquals(obj7), preferExisting);
    }
#endif
}

#if 0 // FIXME: No prototype API in QScriptEngine
void tst_QJSEngine::newQObject_defaultPrototype()
{
1072
    QObject temp;
1073 1074 1075 1076 1077 1078 1079 1080
    QScriptEngine eng;
    // newQObject() should set the default prototype, if one has been registered
    {
        QScriptValue oldQObjectProto = eng.defaultPrototype(qMetaTypeId<QObject*>());

        QScriptValue qobjectProto = eng.newObject();
        eng.setDefaultPrototype(qMetaTypeId<QObject*>(), qobjectProto);
        {
1081
            QScriptValue ret = eng.newQObject(&temp);
1082 1083 1084 1085 1086 1087
            QVERIFY(ret.prototype().equals(qobjectProto));
        }
        QScriptValue tstProto = eng.newObject();
        int typeId = qRegisterMetaType<tst_QJSEngine*>("tst_QJSEngine*");
        eng.setDefaultPrototype(typeId, tstProto);
        {
1088
            QScriptValue ret = eng.newQObject(temp);
1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112
            QVERIFY(ret.prototype().equals(tstProto));
        }

        eng.setDefaultPrototype(qMetaTypeId<QObject*>(), oldQObjectProto);
        eng.setDefaultPrototype(typeId, QScriptValue());
    }
}
#endif

void tst_QJSEngine::newQObject_promoteNonObject()
{
#if 0 // ### FIXME: object promotion is not supported
    QScriptEngine eng;
    {
        QScriptValue ret = eng.newQObject(123, this);
        QVERIFY(ret.isQObject());
        QCOMPARE(ret.toQObject(), this);
    }
#endif
}

void tst_QJSEngine::newQObject_promoteNonQScriptObject()
{
#if 0 // ### FIXME: object promotion is not supported
1113
    QSKIP("Promotion of non QScriptObjects kind of works (there is not difference between Object and Array, look at comments in newQObject implementation).");
1114 1115 1116 1117
    QScriptEngine eng;
    {
        QTest::ignoreMessage(QtWarningMsg, "QScriptEngine::newQObject(): changing class of non-QScriptObject not supported");
        QScriptValue ret = eng.newQObject(eng.newArray(), this);
1118
        QVERIFY(ret.isUndefined());
1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144
    }
#endif
}

#if 0 // ### FIXME: No QScript Metaobject support right now
QT_BEGIN_NAMESPACE
Q_SCRIPT_DECLARE_QMETAOBJECT(QObject, QObject*)
Q_SCRIPT_DECLARE_QMETAOBJECT(QWidget, QWidget*)
QT_END_NAMESPACE

static QScriptValue myConstructor(QScriptContext *ctx, QScriptEngine *eng)
{
    QScriptValue obj;
    if (ctx->isCalledAsConstructor()) {
        obj = ctx->thisObject();
    } else {
        obj = eng->newObject();
        obj.setPrototype(ctx->callee().property("prototype"));
    }
    obj.setProperty("isCalledAsConstructor", QScriptValue(eng, ctx->isCalledAsConstructor()));
    return obj;
}

static QScriptValue instanceofJS(const QScriptValue &inst, const QScriptValue &ctor)
{
    return inst.engine()->evaluate("(function(inst, ctor) { return inst instanceof ctor; })")
1145
        .call(QScriptValueList() << inst << ctor);
1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157
}

void tst_QJSEngine::newQMetaObject()
{
    QScriptEngine eng;
#if 0
    QScriptValue qclass = eng.newQMetaObject<QObject>();
    QScriptValue qclass2 = eng.newQMetaObject<QWidget>();
#else
    QScriptValue qclass = qScriptValueFromQMetaObject<QObject>(&eng);
    QScriptValue qclass2 = qScriptValueFromQMetaObject<QWidget>(&eng);
#endif
1158
    QVERIFY(!qclass.isUndefined());
1159 1160
    QCOMPARE(qclass.isQMetaObject(), true);
    QCOMPARE(qclass.toQMetaObject(), &QObject::staticMetaObject);
1161
    QCOMPARE(qclass.isCallable(), true);
1162 1163
    QVERIFY(qclass.property("prototype").isObject());

1164
    QVERIFY(!qclass2.isUndefined());
1165 1166
    QCOMPARE(qclass2.isQMetaObject(), true);
    QCOMPARE(qclass2.toQMetaObject(), &QWidget::staticMetaObject);
1167
    QCOMPARE(qclass2.isCallable(), true);
1168 1169 1170 1171 1172 1173
    QVERIFY(qclass2.property("prototype").isObject());

    // prototype should be QMetaObject.prototype
    QCOMPARE(qclass.prototype().isObject(), true);
    QCOMPARE(qclass2.prototype().isObject(), true);

1174
    QScriptValue instance = qclass.callAsConstructor();
1175 1176 1177 1178 1179 1180
    QCOMPARE(instance.isQObject(), true);
    QCOMPARE(instance.toQObject()->metaObject(), qclass.toQMetaObject());
    QEXPECT_FAIL("", "FIXME:  newQMetaObject not implemented properly yet", Abort);
    QVERIFY(instance.instanceOf(qclass));
    QVERIFY(instanceofJS(instance, qclass).strictlyEquals(true));

1181
    QScriptValue instance2 = qclass2.callAsConstructor();
1182 1183 1184 1185 1186 1187 1188 1189 1190
    QCOMPARE(instance2.isQObject(), true);
    QCOMPARE(instance2.toQObject()->metaObject(), qclass2.toQMetaObject());
    QVERIFY(instance2.instanceOf(qclass2));
    QVERIFY(instanceofJS(instance2, qclass2).strictlyEquals(true));
    QVERIFY(!instance2.instanceOf(qclass));
    QVERIFY(instanceofJS(instance2, qclass).strictlyEquals(false));

    QScriptValueList args;
    args << instance;
1191
    QScriptValue instance3 = qclass.callAsConstructor(args);
1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229
    QCOMPARE(instance3.isQObject(), true);
    QCOMPARE(instance3.toQObject()->parent(), instance.toQObject());
    QVERIFY(instance3.instanceOf(qclass));
    QVERIFY(instanceofJS(instance3, qclass).strictlyEquals(true));
    QVERIFY(!instance3.instanceOf(qclass2));
    QVERIFY(instanceofJS(instance3, qclass2).strictlyEquals(false));
    args.clear();

    QPointer<QObject> qpointer1 = instance.toQObject();
    QPointer<QObject> qpointer2 = instance2.toQObject();
    QPointer<QObject> qpointer3 = instance3.toQObject();

    QVERIFY(qpointer1);
    QVERIFY(qpointer2);
    QVERIFY(qpointer3);

    // verify that AutoOwnership is in effect
    instance = QScriptValue();
    collectGarbage_helper(eng);

    QVERIFY(!qpointer1);
    QVERIFY(qpointer2);
    QVERIFY(!qpointer3); // was child of instance

    QVERIFY(instance.toQObject() == 0);
    QVERIFY(instance3.toQObject() == 0); // was child of instance
    QVERIFY(instance2.toQObject() != 0);
    instance2 = QScriptValue();
    collectGarbage_helper(eng);
    QVERIFY(instance2.toQObject() == 0);

    // with custom constructor
    QScriptValue ctor = eng.newFunction(myConstructor);
    QScriptValue qclass3 = eng.newQMetaObject(&QObject::staticMetaObject, ctor);
    QVERIFY(qclass3.property("prototype").equals(ctor.property("prototype")));
    {
        QScriptValue ret = qclass3.call();
        QVERIFY(ret.isObject());
1230 1231
        QVERIFY(ret.property("isCalledAsConstructor").isBool());
        QVERIFY(!ret.property("isCalledAsConstructor").toBool());
1232 1233 1234 1235 1236 1237
        QVERIFY(ret.instanceOf(qclass3));
        QVERIFY(instanceofJS(ret, qclass3).strictlyEquals(true));
        QVERIFY(!ret.instanceOf(qclass));
        QVERIFY(instanceofJS(ret, qclass).strictlyEquals(false));
    }
    {
1238
        QScriptValue ret = qclass3.callAsConstructor();
1239
        QVERIFY(ret.isObject());
1240 1241
        QVERIFY(ret.property("isCalledAsConstructor").isBool());
        QVERIFY(ret.property("isCalledAsConstructor").toBool());
1242 1243 1244 1245 1246 1247 1248
        QVERIFY(ret.instanceOf(qclass3));
        QVERIFY(instanceofJS(ret, qclass3).strictlyEquals(true));
        QVERIFY(!ret.instanceOf(qclass2));
        QVERIFY(instanceofJS(ret, qclass2).strictlyEquals(false));
    }

    // subclassing
1249 1250 1251
    qclass2.setProperty("prototype", qclass.callAsConstructor());
    QVERIFY(qclass2.callAsConstructor().instanceOf(qclass));
    QVERIFY(instanceofJS(qclass2.callAsConstructor(), qclass).strictlyEquals(true));
1252 1253 1254 1255

    // with meta-constructor
    QScriptValue qclass4 = eng.newQMetaObject(&QObject::staticMetaObject);
    {
1256
        QScriptValue inst = qclass4.callAsConstructor();
1257 1258 1259 1260 1261 1262 1263 1264 1265
        QVERIFY(inst.isQObject());
        QVERIFY(inst.toQObject() != 0);
        QCOMPARE(inst.toQObject()->parent(), (QObject*)0);
        QVERIFY(inst.instanceOf(qclass4));
        QVERIFY(instanceofJS(inst, qclass4).strictlyEquals(true));
        QVERIFY(!inst.instanceOf(qclass3));
        QVERIFY(instanceofJS(inst, qclass3).strictlyEquals(false));
    }
    {
1266 1267
        QObject temp;
        QScriptValue inst = qclass4.callAsConstructor(QScriptValueList() << eng.newQObject(&temp));
1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281
        QVERIFY(inst.isQObject());
        QVERIFY(inst.toQObject() != 0);
        QCOMPARE(inst.toQObject()->parent(), (QObject*)this);
        QVERIFY(inst.instanceOf(qclass4));
        QVERIFY(instanceofJS(inst, qclass4).strictlyEquals(true));
        QVERIFY(!inst.instanceOf(qclass2));
        QVERIFY(instanceofJS(inst, qclass2).strictlyEquals(false));
    }
}
#endif

#if 0 // ###FIXME: No activation object support
void tst_QJSEngine::newActivationObject()
{
1282
    QSKIP("internal function not implemented in JSC-based back-end");
1283 1284 1285
    QScriptEngine eng;
    QScriptValue act = eng.newActivationObject();
    QEXPECT_FAIL("", "", Continue);
1286
    QVERIFY(!act.isUndefined());
1287 1288
    QEXPECT_FAIL("", "", Continue);
    QCOMPARE(act.isObject(), true);
1289
    QVERIFY(!act.isCallable());
1290 1291 1292 1293
    QScriptValue v(&eng, 123);
    act.setProperty("prop", v);
    QEXPECT_FAIL("", "", Continue);
    QCOMPARE(act.property("prop").strictlyEquals(v), true);
1294
    QVERIFY(act.scope().isUndefined());
1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308
    QEXPECT_FAIL("", "", Continue);
    QVERIFY(act.prototype().isNull());
}
#endif

#if 0 // ###FIXME: No setGlobalObject support - yay
void tst_QJSEngine::getSetGlobalObjectSimple()
{
    QScriptEngine engine;
    QScriptValue object = engine.newObject();
    object.setProperty("foo", 123);
    engine.evaluate("var bar = 100");
    engine.setGlobalObject(object);
    engine.evaluate("rab = 100");
1309 1310 1311
    QVERIFY(!engine.globalObject().property("rab").isUndefined());
    QVERIFY(!engine.globalObject().property("foo").isUndefined());
    QVERIFY(engine.globalObject().property("bar").isUndefined());
1312 1313 1314 1315 1316 1317 1318 1319 1320 1321
}

void tst_QJSEngine::getSetGlobalObject()
{
    QScriptEngine eng;
    QScriptValue glob = eng.globalObject();
    glob = QScriptValue(); // kill reference to old global object
    collectGarbage_helper(eng);

    glob = eng.globalObject();
1322
    QVERIFY(!glob.isUndefined());
1323
    QCOMPARE(glob.isObject(), true);
1324
    QVERIFY(!glob.isCallable());
1325 1326 1327 1328 1329
    QVERIFY(eng.currentContext()->thisObject().strictlyEquals(glob));
    QVERIFY(eng.currentContext()->activationObject().strictlyEquals(glob));
    QEXPECT_FAIL("", "FIXME: Do we really want to enforce this? ECMA standard says that it is implementation dependent, skipping for now", Continue);
    QCOMPARE(glob.toString(), QString::fromLatin1("[object global]"));
    // prototype should be Object.prototype
1330
    QVERIFY(!glob.prototype().isUndefined());
1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362
    QCOMPARE(glob.prototype().isObject(), true);
    QEXPECT_FAIL("", "FIXME: Do we really want to enforce this? ECMA standard says that it is implementation dependent, skipping for now", Continue);
    QCOMPARE(glob.prototype().strictlyEquals(eng.evaluate("Object.prototype")), true);

    eng.setGlobalObject(glob);
    QVERIFY(eng.globalObject().equals(glob));
    eng.setGlobalObject(123);
    QVERIFY(eng.globalObject().equals(glob));

    QScriptValue obj = eng.newObject();
    eng.setGlobalObject(obj);
    QVERIFY(eng.globalObject().strictlyEquals(obj));
    QVERIFY(eng.currentContext()->thisObject().strictlyEquals(obj));
    QVERIFY(eng.currentContext()->activationObject().strictlyEquals(obj));
    QVERIFY(eng.evaluate("this").strictlyEquals(obj));
    QEXPECT_FAIL("", "FIXME: Do we really want to enforce this? ECMA standard says that it is implementation dependent, skipping for now", Continue);
    QCOMPARE(eng.globalObject().toString(), QString::fromLatin1("[object global]"));

    collectGarbage_helper(eng);
    glob = QScriptValue(); // kill reference to old global object
    collectGarbage_helper(eng);
    obj = eng.newObject();
    eng.setGlobalObject(obj);
    QVERIFY(eng.globalObject().strictlyEquals(obj));
    QVERIFY(eng.currentContext()->thisObject().strictlyEquals(obj));
    QVERIFY(eng.currentContext()->activationObject().strictlyEquals(obj));

    collectGarbage_helper(eng);
    QVERIFY(eng.globalObject().strictlyEquals(obj));
    QVERIFY(eng.currentContext()->thisObject().strictlyEquals(obj));
    QVERIFY(eng.currentContext()->activationObject().strictlyEquals(obj));

1363
    QVERIFY(obj.property("foo").isUndefined());
1364 1365 1366 1367
    eng.evaluate("var foo = 123");
    {
        QScriptValue ret = obj.property("foo");
        QVERIFY(ret.isNumber());
1368
        QCOMPARE(ret.toInt(), 123);
1369 1370
    }

1371
    QVERIFY(obj.property("bar").isUndefined());
1372 1373 1374 1375
    eng.evaluate("bar = 456");
    {
        QScriptValue ret = obj.property("bar");
        QVERIFY(ret.isNumber());
1376
        QCOMPARE(ret.toInt(), 456);
1377 1378
    }

1379
    QVERIFY(obj.property("baz").isUndefined());
1380 1381 1382 1383
    eng.evaluate("this['baz'] = 789");
    {
        QScriptValue ret = obj.property("baz");
        QVERIFY(ret.isNumber());
1384
        QCOMPARE(ret.toInt(), 789);
1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396
    }

    {
        QScriptValue ret = eng.evaluate("(function() { return this; })()");
        QVERIFY(ret.strictlyEquals(obj));
    }

    // Delete property.
    {
        QScriptValue ret = eng.evaluate("delete foo");
        QVERIFY(ret.isBool());
        QVERIFY(ret.toBool());
1397
        QVERIFY(obj.property("foo").isUndefined());
1398 1399 1400 1401 1402 1403
    }

    // Getter/setter property.
    //the custom global object have an interceptor
    QVERIFY(eng.evaluate("this.__defineGetter__('oof', function() { return this.bar; })").isUndefined());
    QVERIFY(eng.evaluate("this.__defineSetter__('oof', function(v) { this.bar = v; })").isUndefined());
1404 1405
    QVERIFY(eng.evaluate("this.__lookupGetter__('oof')").isCallable());
    QVERIFY(eng.evaluate("this.__lookupSetter__('oof')").isCallable());
1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427
    eng.evaluate("oof = 123");
    QVERIFY(eng.evaluate("oof").equals(obj.property("bar")));

    // Enumeration.
    {
        QScriptValue ret = eng.evaluate("a = []; for (var p in this) a.push(p); a");
        QCOMPARE(ret.toString(), QString::fromLatin1("bar,baz,oof,p,a"));
    }
}
#endif

#if 0 // ###FIXME: no c-style callbacks
static QScriptValue getSetFoo(QScriptContext *ctx, QScriptEngine *)
{
    if (ctx->argumentCount() > 0)
        ctx->thisObject().setProperty("foo", ctx->argument(0));
    return ctx->thisObject().property("foo");
}
#endif

void tst_QJSEngine::globalObjectProperties()
{
1428
    QSKIP("Test failing - QTBUG-22238");
1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441
    // See ECMA-262 Section 15.1, "The Global Object".

    QJSEngine eng;
    QJSValue global = eng.globalObject();

    QVERIFY(global.property("NaN").isNumber());
    QVERIFY(qIsNaN(global.property("NaN").toNumber()));

    QVERIFY(global.property("Infinity").isNumber());
    QVERIFY(qIsInf(global.property("Infinity").toNumber()));

    QVERIFY(global.property("undefined").isUndefined());

1442
    QVERIFY(global.property("eval").isCallable());
1443

1444
    QVERIFY(global.property("parseInt").isCallable());
1445

1446
    QVERIFY(global.property("parseFloat").isCallable());
1447

1448
    QVERIFY(global.property("isNaN").isCallable());
1449

1450
    QVERIFY(global.property("isFinite").isCallable());
1451

1452
    QVERIFY(global.property("decodeURI").isCallable());
1453

1454
    QVERIFY(global.property("decodeURIComponent").isCallable());
1455

1456
    QVERIFY(global.property("encodeURI").isCallable());
1457

1458
    QVERIFY(global.property("encodeURIComponent").isCallable());
1459

1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474
    QVERIFY(global.property("Object").isCallable());
    QVERIFY(global.property("Function").isCallable());
    QVERIFY(global.property("Array").isCallable());
    QVERIFY(global.property("String").isCallable());
    QVERIFY(global.property("Boolean").isCallable());
    QVERIFY(global.property("Number").isCallable());
    QVERIFY(global.property("Date").isCallable());
    QVERIFY(global.property("RegExp").isCallable());
    QVERIFY(global.property("Error").isCallable());
    QVERIFY(global.property("EvalError").isCallable());
    QVERIFY(global.property("RangeError").isCallable());
    QVERIFY(global.property("ReferenceError").isCallable());
    QVERIFY(global.property("SyntaxError").isCallable());
    QVERIFY(global.property("TypeError").isCallable());
    QVERIFY(global.property("URIError").isCallable());
1475
    QVERIFY(global.property("Math").isObject());
1476
    QVERIFY(!global.property("Math").isCallable());
1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488
}

void tst_QJSEngine::globalObjectEquals()
{
    QJSEngine eng;
    QJSValue o = eng.globalObject();
    QVERIFY(o.strictlyEquals(eng.globalObject()));
    QVERIFY(o.equals(eng.globalObject()));
}

void tst_QJSEngine::globalObjectProperties_enumerate()
{
1489
    QSKIP("Test failing - QTBUG-22238");
1490 1491
    QJSEngine eng;
    QJSValue global = eng.globalObject();
1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531

    QSet<QString> expectedNames;
    expectedNames
        << "isNaN"
        << "parseFloat"
        << "String"
        << "EvalError"
        << "URIError"
        << "Math"
        << "encodeURIComponent"
        << "RangeError"
        << "eval"
        << "isFinite"
        << "ReferenceError"
        << "Infinity"
        << "Function"
        << "RegExp"
        << "Number"
        << "parseInt"
        << "Object"
        << "decodeURI"
        << "TypeError"
        << "Boolean"
        << "encodeURI"
        << "NaN"
        << "Error"
        << "decodeURIComponent"
        << "Date"
        << "Array"
        << "escape"
        << "unescape"
        << "SyntaxError"
        << "undefined"
        // JavaScriptCore
        << "JSON"
        // V8
        << "execScript" //execScript for IE compatibility.
        ;
    QSet<QString> actualNames;
    {
1532
        QJSValueIterator it(global);
1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557
        while (it.hasNext()) {
            it.next();
            actualNames.insert(it.name());
        }
    }

    QSet<QString> remainingNames = actualNames;
    {
        QSet<QString>::const_iterator it;
        for (it = expectedNames.constBegin(); it != expectedNames.constEnd(); ++it) {
            QString name = *it;
            QVERIFY(actualNames.contains(name));
            remainingNames.remove(name);
        }
    }
    QVERIFY(remainingNames.isEmpty());
}

void tst_QJSEngine::createGlobalObjectProperty()
{
    QJSEngine eng;
    QJSValue global = eng.globalObject();
    // create property with no attributes
    {
        QString name = QString::fromLatin1("foo");
1558
        QVERIFY(global.property(name).isUndefined());
1559 1560 1561
        QJSValue val(123);
        global.setProperty(name, val);
        QVERIFY(global.property(name).equals(val));
1562 1563
        global.deleteProperty(name);
        QVERIFY(global.property(name).isUndefined());
1564 1565 1566 1567 1568
    }
    // create property with attributes
#if 0 // ###FIXME: setProperty with flags is not supported
    {
        QString name = QString::fromLatin1("bar");
1569
        QVERIFY(global.property(name).isUndefined());
1570 1571 1572 1573 1574 1575
        QScriptValue val(QString::fromLatin1("ciao"));
        QScriptValue::PropertyFlags flags = QScriptValue::ReadOnly | QScriptValue::SkipInEnumeration;
        global.setProperty(name, val, flags);
        QVERIFY(global.property(name).equals(val));
        //QEXPECT_FAIL("", "QTBUG-6134: custom Global Object properties don't retain attributes", Continue);
        global.setProperty(name, QScriptValue());
1576
        QVERIFY(global.property(name).isUndefined());
1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620
    }
#endif
}

void tst_QJSEngine::globalObjectGetterSetterProperty()
{
#if 0 // ###FIXME: No c-style callbacks
    QScriptEngine engine;
    QScriptValue global = engine.globalObject();
    global.setProperty("bar", engine.newFunction(getSetFoo),
                       QScriptValue::PropertySetter | QScriptValue::PropertyGetter);
    global.setProperty("foo", 123);
    QVERIFY(global.property("bar").equals(global.property("foo")));
    QVERIFY(engine.evaluate("bar").equals(global.property("foo")));
    global.setProperty("bar", 456);
    QVERIFY(global.property("bar").equals(global.property("foo")));

    engine.evaluate("__defineGetter__('baz', function() { return 789; })");
    QVERIFY(engine.evaluate("baz").equals(789));
    QVERIFY(global.property("baz").equals(789));
#endif
}

#if 0 // ###FIXME: No support for setting the global object
void tst_QJSEngine::customGlobalObjectWithPrototype()
{
    for (int x = 0; x < 2; ++x) {
        QScriptEngine engine;
        QScriptValue wrap = engine.newObject();
        QScriptValue global = engine.globalObject();
        QScriptValue originalGlobalProto = global.prototype();
        if (!x) {
            // Set prototype before setting global object
            wrap.setPrototype(global);
            QVERIFY(wrap.prototype().strictlyEquals(global));
            engine.setGlobalObject(wrap);
        } else {
            // Set prototype after setting global object
            engine.setGlobalObject(wrap);
            wrap.setPrototype(global);
            QVERIFY(wrap.prototype().strictlyEquals(global));
        }
        {
            QScriptValue ret = engine.evaluate("print");
1621
            QVERIFY(ret.isCallable());
1622 1623 1624 1625
            QVERIFY(ret.strictlyEquals(wrap.property("print")));
        }
        {
            QScriptValue ret = engine.evaluate("this.print");
1626
            QVERIFY(ret.isCallable());
1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646
            QVERIFY(ret.strictlyEquals(wrap.property("print")));
        }
        {
            QScriptValue ret = engine.evaluate("hasOwnProperty('print')");
            QVERIFY(ret.isBool());
            if (x) QEXPECT_FAIL("", "Why?", Continue);
            QVERIFY(!ret.toBool());
        }
        {
            QScriptValue ret = engine.evaluate("this.hasOwnProperty('print')");
            QVERIFY(ret.isBool());
            if (x) QEXPECT_FAIL("", "Why?", Continue);
            QVERIFY(!ret.toBool());
        }

        QScriptValue anotherProto = engine.newObject();
        anotherProto.setProperty("anotherProtoProperty", 123);
        global.setPrototype(anotherProto);
        {
            QScriptValue ret = engine.evaluate("print");
1647
            QVERIFY(ret.isCallable());
1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682
            QVERIFY(ret.strictlyEquals(wrap.property("print")));
        }
        {
            QScriptValue ret = engine.evaluate("anotherProtoProperty");
            QVERIFY(ret.isNumber());
            QVERIFY(ret.strictlyEquals(wrap.property("anotherProtoProperty")));
        }
        {
            QScriptValue ret = engine.evaluate("this.anotherProtoProperty");
            QVERIFY(ret.isNumber());
            QVERIFY(ret.strictlyEquals(wrap.property("anotherProtoProperty")));
        }

        wrap.setPrototype(anotherProto);
        {
            QScriptValue ret = engine.evaluate("print");
            QVERIFY(ret.isError());
            QCOMPARE(ret.toString(), QString::fromLatin1("ReferenceError: print is not defined"));
        }
        {
            QScriptValue ret = engine.evaluate("anotherProtoProperty");
            QVERIFY(ret.isNumber());
            QVERIFY(ret.strictlyEquals(wrap.property("anotherProtoProperty")));
        }
        QVERIFY(global.prototype().strictlyEquals(anotherProto));

        global.setPrototype(originalGlobalProto);
        engine.setGlobalObject(global);
        {
            QScriptValue ret = engine.evaluate("anotherProtoProperty");
            QVERIFY(ret.isError());
            QVERIFY(ret.toString().startsWith("ReferenceError: "));
        }
        {
            QScriptValue ret = engine.evaluate("print");
1683
            QVERIFY(ret.isCallable());
1684 1685
            QVERIFY(ret.strictlyEquals(global.property("print")));
        }
1686
        QVERIFY(anotherProto.property("print").isUndefined());
1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110
    }
}
#endif

void tst_QJSEngine::globalObjectWithCustomPrototype()
{
    QJSEngine engine;
    QJSValue proto = engine.newObject();
    proto.setProperty("protoProperty", 123);
    QJSValue global = engine.globalObject();
    QJSValue originalProto = global.prototype();
    global.setPrototype(proto);
    {
        QJSValue ret = engine.evaluate("protoProperty");
        QEXPECT_FAIL("", "Replacing the prototype of the global object is currently unsupported (see also v8 issue 1078)", Abort);
        QVERIFY(ret.isNumber());
        QVERIFY(ret.strictlyEquals(global.property("protoProperty")));
    }
    {
        QJSValue ret = engine.evaluate("this.protoProperty");
        QVERIFY(ret.isNumber());
        QVERIFY(ret.strictlyEquals(global.property("protoProperty")));
    }
    {
        QJSValue ret = engine.evaluate("hasOwnProperty('protoProperty')");
        QVERIFY(ret.isBool());
        QVERIFY(!ret.toBool());
    }
    {
        QJSValue ret = engine.evaluate("this.hasOwnProperty('protoProperty')");
        QVERIFY(ret.isBool());
        QVERIFY(!ret.toBool());
    }

    // Custom prototype set from JS
    {
        QJSValue ret = engine.evaluate("this.__proto__ = { 'a': 123 }; a");
        QVERIFY(ret.isNumber());
        QVERIFY(ret.strictlyEquals(global.property("a")));
    }
}

void tst_QJSEngine::builtinFunctionNames_data()
{
    QTest::addColumn<QString>("expression");
    QTest::addColumn<QString>("expectedName");

    // See ECMA-262 Chapter 15, "Standard Built-in ECMAScript Objects".

    QTest::newRow("parseInt") << QString("parseInt") << QString("parseInt");
    QTest::newRow("parseFloat") << QString("parseFloat") << QString("parseFloat");
    QTest::newRow("isNaN") << QString("isNaN") << QString("isNaN");
    QTest::newRow("isFinite") << QString("isFinite") << QString("isFinite");
    QTest::newRow("decodeURI") << QString("decodeURI") << QString("decodeURI");
    QTest::newRow("decodeURIComponent") << QString("decodeURIComponent") << QString("decodeURIComponent");
    QTest::newRow("encodeURI") << QString("encodeURI") << QString("encodeURI");
    QTest::newRow("encodeURIComponent") << QString("encodeURIComponent") << QString("encodeURIComponent");
    QTest::newRow("escape") << QString("escape") << QString("escape");
    QTest::newRow("unescape") << QString("unescape") << QString("unescape");

    QTest::newRow("Array") << QString("Array") << QString("Array");
    QTest::newRow("Array.prototype.toString") << QString("Array.prototype.toString") << QString("toString");
    QTest::newRow("Array.prototype.toLocaleString") << QString("Array.prototype.toLocaleString") << QString("toLocaleString");
    QTest::newRow("Array.prototype.concat") << QString("Array.prototype.concat") << QString("concat");
    QTest::newRow("Array.prototype.join") << QString("Array.prototype.join") << QString("join");
    QTest::newRow("Array.prototype.pop") << QString("Array.prototype.pop") << QString("pop");
    QTest::newRow("Array.prototype.push") << QString("Array.prototype.push") << QString("push");
    QTest::newRow("Array.prototype.reverse") << QString("Array.prototype.reverse") << QString("reverse");
    QTest::newRow("Array.prototype.shift") << QString("Array.prototype.shift") << QString("shift");
    QTest::newRow("Array.prototype.slice") << QString("Array.prototype.slice") << QString("slice");
    QTest::newRow("Array.prototype.sort") << QString("Array.prototype.sort") << QString("sort");
    QTest::newRow("Array.prototype.splice") << QString("Array.prototype.splice") << QString("splice");
    QTest::newRow("Array.prototype.unshift") << QString("Array.prototype.unshift") << QString("unshift");

    QTest::newRow("Boolean") << QString("Boolean") << QString("Boolean");
    QTest::newRow("Boolean.prototype.toString") << QString("Boolean.prototype.toString") << QString("toString");

    QTest::newRow("Date") << QString("Date") << QString("Date");
    QTest::newRow("Date.prototype.toString") << QString("Date.prototype.toString") << QString("toString");
    QTest::newRow("Date.prototype.toDateString") << QString("Date.prototype.toDateString") << QString("toDateString");
    QTest::newRow("Date.prototype.toTimeString") << QString("Date.prototype.toTimeString") << QString("toTimeString");
    QTest::newRow("Date.prototype.toLocaleString") << QString("Date.prototype.toLocaleString") << QString("toLocaleString");
    QTest::newRow("Date.prototype.toLocaleDateString") << QString("Date.prototype.toLocaleDateString") << QString("toLocaleDateString");
    QTest::newRow("Date.prototype.toLocaleTimeString") << QString("Date.prototype.toLocaleTimeString") << QString("toLocaleTimeString");
    QTest::newRow("Date.prototype.valueOf") << QString("Date.prototype.valueOf") << QString("valueOf");
    QTest::newRow("Date.prototype.getTime") << QString("Date.prototype.getTime") << QString("getTime");
    QTest::newRow("Date.prototype.getYear") << QString("Date.prototype.getYear") << QString("getYear");
    QTest::newRow("Date.prototype.getFullYear") << QString("Date.prototype.getFullYear") << QString("getFullYear");
    QTest::newRow("Date.prototype.getUTCFullYear") << QString("Date.prototype.getUTCFullYear") << QString("getUTCFullYear");
    QTest::newRow("Date.prototype.getMonth") << QString("Date.prototype.getMonth") << QString("getMonth");
    QTest::newRow("Date.prototype.getUTCMonth") << QString("Date.prototype.getUTCMonth") << QString("getUTCMonth");
    QTest::newRow("Date.prototype.getDate") << QString("Date.prototype.getDate") << QString("getDate");
    QTest::newRow("Date.prototype.getUTCDate") << QString("Date.prototype.getUTCDate") << QString("getUTCDate");
    QTest::newRow("Date.prototype.getDay") << QString("Date.prototype.getDay") << QString("getDay");
    QTest::newRow("Date.prototype.getUTCDay") << QString("Date.prototype.getUTCDay") << QString("getUTCDay");
    QTest::newRow("Date.prototype.getHours") << QString("Date.prototype.getHours") << QString("getHours");
    QTest::newRow("Date.prototype.getUTCHours") << QString("Date.prototype.getUTCHours") << QString("getUTCHours");
    QTest::newRow("Date.prototype.getMinutes") << QString("Date.prototype.getMinutes") << QString("getMinutes");
    QTest::newRow("Date.prototype.getUTCMinutes") << QString("Date.prototype.getUTCMinutes") << QString("getUTCMinutes");
    QTest::newRow("Date.prototype.getSeconds") << QString("Date.prototype.getSeconds") << QString("getSeconds");
    QTest::newRow("Date.prototype.getUTCSeconds") << QString("Date.prototype.getUTCSeconds") << QString("getUTCSeconds");
    QTest::newRow("Date.prototype.getMilliseconds") << QString("Date.prototype.getMilliseconds") << QString("getMilliseconds");
    QTest::newRow("Date.prototype.getUTCMilliseconds") << QString("Date.prototype.getUTCMilliseconds") << QString("getUTCMilliseconds");
    QTest::newRow("Date.prototype.getTimezoneOffset") << QString("Date.prototype.getTimezoneOffset") << QString("getTimezoneOffset");
    QTest::newRow("Date.prototype.setTime") << QString("Date.prototype.setTime") << QString("setTime");
    QTest::newRow("Date.prototype.setMilliseconds") << QString("Date.prototype.setMilliseconds") << QString("setMilliseconds");
    QTest::newRow("Date.prototype.setUTCMilliseconds") << QString("Date.prototype.setUTCMilliseconds") << QString("setUTCMilliseconds");
    QTest::newRow("Date.prototype.setSeconds") << QString("Date.prototype.setSeconds") << QString("setSeconds");
    QTest::newRow("Date.prototype.setUTCSeconds") << QString("Date.prototype.setUTCSeconds") << QString("setUTCSeconds");
    QTest::newRow("Date.prototype.setMinutes") << QString("Date.prototype.setMinutes") << QString("setMinutes");
    QTest::newRow("Date.prototype.setUTCMinutes") << QString("Date.prototype.setUTCMinutes") << QString("setUTCMinutes");
    QTest::newRow("Date.prototype.setHours") << QString("Date.prototype.setHours") << QString("setHours");
    QTest::newRow("Date.prototype.setUTCHours") << QString("Date.prototype.setUTCHours") << QString("setUTCHours");
    QTest::newRow("Date.prototype.setDate") << QString("Date.prototype.setDate") << QString("setDate");
    QTest::newRow("Date.prototype.setUTCDate") << QString("Date.prototype.setUTCDate") << QString("setUTCDate");
    QTest::newRow("Date.prototype.setMonth") << QString("Date.prototype.setMonth") << QString("setMonth");
    QTest::newRow("Date.prototype.setUTCMonth") << QString("Date.prototype.setUTCMonth") << QString("setUTCMonth");
    QTest::newRow("Date.prototype.setYear") << QString("Date.prototype.setYear") << QString("setYear");
    QTest::newRow("Date.prototype.setFullYear") << QString("Date.prototype.setFullYear") << QString("setFullYear");
    QTest::newRow("Date.prototype.setUTCFullYear") << QString("Date.prototype.setUTCFullYear") << QString("setUTCFullYear");
    QTest::newRow("Date.prototype.toUTCString") << QString("Date.prototype.toUTCString") << QString("toUTCString");
    QTest::newRow("Date.prototype.toGMTString") << QString("Date.prototype.toGMTString") << QString("toGMTString");

    QTest::newRow("Error") << QString("Error") << QString("Error");
//    QTest::newRow("Error.prototype.backtrace") << QString("Error.prototype.backtrace") << QString("backtrace");
    QTest::newRow("Error.prototype.toString") << QString("Error.prototype.toString") << QString("toString");

    QTest::newRow("EvalError") << QString("EvalError") << QString("EvalError");
    QTest::newRow("RangeError") << QString("RangeError") << QString("RangeError");
    QTest::newRow("ReferenceError") << QString("ReferenceError") << QString("ReferenceError");
    QTest::newRow("SyntaxError") << QString("SyntaxError") << QString("SyntaxError");
    QTest::newRow("TypeError") << QString("TypeError") << QString("TypeError");
    QTest::newRow("URIError") << QString("URIError") << QString("URIError");

    QTest::newRow("Function") << QString("Function") << QString("Function");
    QTest::newRow("Function.prototype.toString") << QString("Function.prototype.toString") << QString("toString");
    QTest::newRow("Function.prototype.apply") << QString("Function.prototype.apply") << QString("apply");
    QTest::newRow("Function.prototype.call") << QString("Function.prototype.call") << QString("call");
/*  In V8, those function are only there for signals
    QTest::newRow("Function.prototype.connect") << QString("Function.prototype.connect") << QString("connect");
    QTest::newRow("Function.prototype.disconnect") << QString("Function.prototype.disconnect") << QString("disconnect");*/

    QTest::newRow("Math.abs") << QString("Math.abs") << QString("abs");
    QTest::newRow("Math.acos") << QString("Math.acos") << QString("acos");
    QTest::newRow("Math.asin") << QString("Math.asin") << QString("asin");
    QTest::newRow("Math.atan") << QString("Math.atan") << QString("atan");
    QTest::newRow("Math.atan2") << QString("Math.atan2") << QString("atan2");
    QTest::newRow("Math.ceil") << QString("Math.ceil") << QString("ceil");
    QTest::newRow("Math.cos") << QString("Math.cos") << QString("cos");
    QTest::newRow("Math.exp") << QString("Math.exp") << QString("exp");
    QTest::newRow("Math.floor") << QString("Math.floor") << QString("floor");
    QTest::newRow("Math.log") << QString("Math.log") << QString("log");
    QTest::newRow("Math.max") << QString("Math.max") << QString("max");
    QTest::newRow("Math.min") << QString("Math.min") << QString("min");
    QTest::newRow("Math.pow") << QString("Math.pow") << QString("pow");
    QTest::newRow("Math.random") << QString("Math.random") << QString("random");
    QTest::newRow("Math.round") << QString("Math.round") << QString("round");
    QTest::newRow("Math.sin") << QString("Math.sin") << QString("sin");
    QTest::newRow("Math.sqrt") << QString("Math.sqrt") << QString("sqrt");
    QTest::newRow("Math.tan") << QString("Math.tan") << QString("tan");

    QTest::newRow("Number") << QString("Number") << QString("Number");
    QTest::newRow("Number.prototype.toString") << QString("Number.prototype.toString") << QString("toString");
    QTest::newRow("Number.prototype.toLocaleString") << QString("Number.prototype.toLocaleString") << QString("toLocaleString");
    QTest::newRow("Number.prototype.valueOf") << QString("Number.prototype.valueOf") << QString("valueOf");
    QTest::newRow("Number.prototype.toFixed") << QString("Number.prototype.toFixed") << QString("toFixed");
    QTest::newRow("Number.prototype.toExponential") << QString("Number.prototype.toExponential") << QString("toExponential");
    QTest::newRow("Number.prototype.toPrecision") << QString("Number.prototype.toPrecision") << QString("toPrecision");

    QTest::newRow("Object") << QString("Object") << QString("Object");
    QTest::newRow("Object.prototype.toString") << QString("Object.prototype.toString") << QString("toString");
    QTest::newRow("Object.prototype.toLocaleString") << QString("Object.prototype.toLocaleString") << QString(