texttomodelmerger.cpp 60.1 KB
Newer Older
1 2 3 4
/**************************************************************************
**
** This file is part of Qt Creator
**
con's avatar
con committed
5
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
6
**
hjk's avatar
hjk committed
7
** Contact: Nokia Corporation (info@qt.nokia.com)
8 9 10 11
**
**
** GNU Lesser General Public License Usage
**
hjk's avatar
hjk committed
12 13 14 15 16 17
** 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.
18
**
con's avatar
con committed
19
** In addition, as a special exception, Nokia gives you certain additional
hjk's avatar
hjk committed
20
** rights. These rights are described in the Nokia Qt LGPL Exception
con's avatar
con committed
21 22
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
hjk's avatar
hjk committed
23 24 25 26 27
** 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.
**
con's avatar
con committed
28
** If you have questions regarding the use of this file, please contact
Tobias Hunger's avatar
Tobias Hunger committed
29
** Nokia at info@qt.nokia.com.
30 31 32 33 34
**
**************************************************************************/

#include "abstractproperty.h"
#include "bindingproperty.h"
35 36
#include "filemanager/firstdefinitionfinder.h"
#include "filemanager/objectlengthcalculator.h"
37 38
#include "filemanager/qmlrefactoring.h"
#include "rewriteaction.h"
39
#include "nodeproperty.h"
40
#include "propertyparser.h"
41
#include "textmodifier.h"
42 43 44
#include "texttomodelmerger.h"
#include "rewriterview.h"
#include "variantproperty.h"
45
#include "nodemetainfo.h"
46

47
#include <languageutils/componentversion.h>
48
#include <qmljs/qmljsevaluate.h>
49
#include <qmljs/qmljsinterpreter.h>
50 51
#include <qmljs/qmljslink.h>
#include <qmljs/qmljsscopebuilder.h>
52
#include <qmljs/parser/qmljsast_p.h>
53
#include <qmljs/qmljscheck.h>
54

55
#include <QtCore/QSet>
Thomas Hartmann's avatar
Thomas Hartmann committed
56
#include <QtGui/QMessageBox>
57
#include <QDir>
58

59
using namespace LanguageUtils;
60 61 62 63 64 65 66 67 68 69 70 71 72 73
using namespace QmlJS;
using namespace QmlJS::AST;

namespace {

static inline QString stripQuotes(const QString &str)
{
    if ((str.startsWith(QLatin1Char('"')) && str.endsWith(QLatin1Char('"')))
            || (str.startsWith(QLatin1Char('\'')) && str.endsWith(QLatin1Char('\''))))
        return str.mid(1, str.length() - 2);

    return str;
}

74
static inline QString deEscape(const QString &value)
75 76 77 78 79 80 81 82 83 84 85
{
    QString result = value;

    result.replace(QLatin1String("\\\\"), QLatin1String("\\"));
    result.replace(QLatin1String("\\\""), QLatin1String("\""));
    result.replace(QLatin1String("\\\t"), QLatin1String("\t"));
    result.replace(QLatin1String("\\\r"), QLatin1String("\\\r"));
    result.replace(QLatin1String("\\\n"), QLatin1String("\n"));

    return result;
}
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

static inline unsigned char convertHex(ushort c)
{
    if (c >= '0' && c <= '9')
        return (c - '0');
    else if (c >= 'a' && c <= 'f')
        return (c - 'a' + 10);
    else
        return (c - 'A' + 10);
}

static inline unsigned char convertHex(ushort c1, ushort c2)
{
    return ((convertHex(c1) << 4) + convertHex(c2));
}

QChar convertUnicode(ushort c1, ushort c2,
                             ushort c3, ushort c4)
{
    return QChar((convertHex(c3) << 4) + convertHex(c4),
                  (convertHex(c1) << 4) + convertHex(c2));
}

static inline bool isHexDigit(ushort c)
{
    return ((c >= '0' && c <= '9')
            || (c >= 'a' && c <= 'f')
            || (c >= 'A' && c <= 'F'));
}


static inline QString fixEscapedUnicodeChar(const QString &value) //convert "\u2939"
{
    if (value.count() == 6 && value.at(0) == '\\' && value.at(1) == 'u' &&
        isHexDigit(value.at(2).unicode()) && isHexDigit(value.at(3).unicode()) &&
        isHexDigit(value.at(4).unicode()) && isHexDigit(value.at(5).unicode())) {
            return convertUnicode(value.at(2).unicode(), value.at(3).unicode(), value.at(4).unicode(), value.at(5).unicode());
    }
    return value;
}
126
 
127
static inline int fixUpMajorVersionForQt(const QString &value, int i)
128
{
129 130
    if (i == 4 && value == "Qt")
        return 1;
131 132 133
    else return i;
}

134
static inline int fixUpMinorVersionForQt(const QString &value, int i)
135
{
136 137
    if (i == 7 && value == "Qt")
        return 0;
138 139
    else return i;
}
140

141
static inline QString fixUpPackeNameForQt(const QString &value)
142
{
143 144
    if (value == "Qt")
        return "QtQuick";
145 146
    return value;
}
147

148 149 150 151 152 153 154
static inline bool isSignalPropertyName(const QString &signalName)
{
    // see QmlCompiler::isSignalPropertyName
    return signalName.length() >= 3 && signalName.startsWith(QLatin1String("on")) &&
           signalName.at(2).isLetter();
}

155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170
static inline QVariant cleverConvert(const QString &value)
{
    if (value == "true")
        return QVariant(true);
    if (value == "false")
        return QVariant(false);
    bool flag;
    int i = value.toInt(&flag);
    if (flag)
        return QVariant(i);
    double d = value.toDouble(&flag);
    if (flag)
        return QVariant(d);
    return QVariant(value);
}

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
static QString flatten(UiQualifiedId *qualifiedId)
{
    QString result;

    for (UiQualifiedId *iter = qualifiedId; iter; iter = iter->next) {
        if (!iter->name)
            continue;

        if (!result.isEmpty())
            result.append(QLatin1Char('.'));

        result.append(iter->name->asString());
    }

    return result;
}

static bool isLiteralValue(ExpressionNode *expr)
{
    if (cast<NumericLiteral*>(expr))
        return true;
    else if (cast<StringLiteral*>(expr))
        return true;
    else if (UnaryPlusExpression *plusExpr = cast<UnaryPlusExpression*>(expr))
        return isLiteralValue(plusExpr->expression);
    else if (UnaryMinusExpression *minusExpr = cast<UnaryMinusExpression*>(expr))
        return isLiteralValue(minusExpr->expression);
    else if (cast<TrueLiteral*>(expr))
        return true;
    else if (cast<FalseLiteral*>(expr))
        return true;
    else
        return false;
}

206
static bool isLiteralValue(Statement *stmt)
207
{
208
    ExpressionStatement *exprStmt = cast<ExpressionStatement *>(stmt);
209 210 211 212
    if (exprStmt)
        return isLiteralValue(exprStmt->expression);
    else
        return false;
213 214
}

215 216 217 218 219 220 221 222
static inline bool isLiteralValue(UiScriptBinding *script)
{
    if (!script || !script->statement)
        return false;

    return isLiteralValue(script->statement);
}

223 224 225 226 227 228 229 230 231 232 233 234
static inline int propertyType(const QString &typeName)
{
    if (typeName == QLatin1String("bool"))
        return QMetaType::type("bool");
    else if (typeName == QLatin1String("color"))
        return QMetaType::type("QColor");
    else if (typeName == QLatin1String("date"))
        return QMetaType::type("QDate");
    else if (typeName == QLatin1String("int"))
        return QMetaType::type("int");
    else if (typeName == QLatin1String("real"))
        return QMetaType::type("double");
235 236
    else if (typeName == QLatin1String("double"))
        return QMetaType::type("double");
237 238 239 240
    else if (typeName == QLatin1String("string"))
        return QMetaType::type("QString");
    else if (typeName == QLatin1String("url"))
        return QMetaType::type("QUrl");
241
    else if (typeName == QLatin1String("var") || typeName == QLatin1String("variant"))
242 243 244 245 246
        return QMetaType::type("QVariant");
    else
        return -1;
}

247 248 249
static inline QVariant convertDynamicPropertyValueToVariant(const QString &astValue,
                                                            const QString &astType)
{
250
    const QString cleanedValue = fixEscapedUnicodeChar(deEscape(stripQuotes(astValue.trimmed())));
251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267

    if (astType.isEmpty())
        return QString();

    const int type = propertyType(astType);
    if (type == QMetaType::type("QVariant")) {
        if (cleanedValue.isNull()) // Explicitly isNull, NOT isEmpty!
            return QVariant(static_cast<QVariant::Type>(type));
        else
            return QVariant(cleanedValue);
    } else {
        QVariant value = QVariant(cleanedValue);
        value.convert(static_cast<QVariant::Type>(type));
        return value;
    }
}

268 269
static bool isComponentType(const QString &type)
{
270
    return  type == QLatin1String("Component") || type == QLatin1String("Qt.Component") || type == QLatin1String("QtQuick.Component");
271 272
}

273
static bool isCustomParserType(const QString &type)
274
{
275 276 277 278 279 280 281 282 283
    return type == "QtQuick.VisualItemModel" || type == "Qt.VisualItemModel" ||
           type == "QtQuick.VisualDataModel" || type == "Qt.VisualDataModel" ||
           type == "QtQuick.ListModel" || type == "Qt.ListModel" ||
           type == "QtQuick.XmlListModel" || type == "Qt.XmlListModel";
}


static bool isPropertyChangesType(const QString &type)
{    
284
    return  type == QLatin1String("PropertyChanges") || type == QLatin1String("QtQuick.PropertyChanges") || type == QLatin1String("Qt.PropertyChanges");
285 286
}

287 288 289 290 291 292
static bool propertyIsComponentType(const QmlDesigner::NodeAbstractProperty &property)
{
    return property.parentModelNode().isValid() &&
            isComponentType(property.parentModelNode().metaInfo().propertyTypeName(property.name()));
}

293

294 295
} // anonymous namespace

296 297 298 299 300 301 302 303 304 305
namespace QmlDesigner {
namespace Internal {

class ReadingContext
{
public:
    ReadingContext(const Snapshot &snapshot, const Document::Ptr &doc,
                   const QStringList importPaths)
        : m_snapshot(snapshot)
        , m_doc(doc)
306
        , m_context(new Interpreter::Context(snapshot))
307
        , m_link(m_context, snapshot, importPaths)
308
        , m_scopeBuilder(m_context, doc)
309
    {
310
        m_link(doc, &m_diagnosticLinkMessages);
311 312 313
        m_lookupContext = LookupContext::create(doc, *m_context, QList<AST::Node*>());
        // cheaper than calling m_scopeBuilder.initializeRootScope()
        *m_context = *m_lookupContext->context();
314 315 316
    }

    ~ReadingContext()
317
    { delete m_context; }
318 319 320 321 322 323 324 325 326 327 328 329 330 331

    Document::Ptr doc() const
    { return m_doc; }

    void enterScope(Node *node)
    { m_scopeBuilder.push(node); }

    void leaveScope()
    { m_scopeBuilder.pop(); }

    void lookup(UiQualifiedId *astTypeNode, QString &typeName, int &majorVersion,
                int &minorVersion, QString &defaultPropertyName)
    {
        const Interpreter::ObjectValue *value = m_context->lookupType(m_doc.data(), astTypeNode);
332 333
        defaultPropertyName = m_context->defaultPropertyName(value);

334 335
        const Interpreter::QmlObjectValue * qmlValue = dynamic_cast<const Interpreter::QmlObjectValue *>(value);
        if (qmlValue) {
336
            typeName = fixUpPackeNameForQt(qmlValue->packageName()) + QLatin1String(".") + qmlValue->className();
337 338

            //### todo this is just a hack to support QtQuick 1.0
339 340
            majorVersion = fixUpMajorVersionForQt(qmlValue->packageName(), qmlValue->version().majorVersion());
            minorVersion = fixUpMinorVersionForQt(qmlValue->packageName(), qmlValue->version().minorVersion());
341
        } else {
342 343 344
            for (UiQualifiedId *iter = astTypeNode; iter; iter = iter->next)
                if (!iter->next && iter->name)
                    typeName = iter->name->asString();
345 346 347 348 349 350 351 352 353

            QString fullTypeName;
            for (UiQualifiedId *iter = astTypeNode; iter; iter = iter->next)
                if (iter->name)
                    fullTypeName += iter->name->asString() + ".";

            if (fullTypeName.endsWith("."))
                fullTypeName.chop(1);

354 355
            majorVersion = ComponentVersion::NoVersion;
            minorVersion = ComponentVersion::NoVersion;
356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371

            const Interpreter::TypeEnvironment *typeEnv = m_lookupContext->context()->typeEnvironment(m_lookupContext->document().data());
            Interpreter::ImportInfo importInfo = typeEnv->importInfo(fullTypeName, m_context);
            if (importInfo.isValid() && importInfo.type() == Interpreter::ImportInfo::LibraryImport) {
                QString name = importInfo.name().replace("\\", ".");
                majorVersion = importInfo.version().majorVersion();
                minorVersion = importInfo.version().minorVersion();
                typeName.prepend(name + ".");
            } else if (importInfo.isValid() && importInfo.type() == Interpreter::ImportInfo::DirectoryImport) {
                QString path = importInfo.name();
                QDir dir(m_doc->path());
                QString relativeDir = dir.relativeFilePath(path);
                QString name = relativeDir.replace("/", ".");               
                if (!name.isEmpty())
                    typeName.prepend(name + ".");
            }
372 373 374 375 376 377
        }
    }

    /// When something is changed here, also change Check::checkScopeObjectMember in
    /// qmljscheck.cpp
    /// ### Maybe put this into the context as a helper method.
378
    bool lookupProperty(const QString &prefix, const UiQualifiedId *id, const Interpreter::Value **property = 0, const Interpreter::ObjectValue **parentObject = 0, QString *name = 0)
379 380 381 382 383 384 385 386 387 388 389
    {
        QList<const Interpreter::ObjectValue *> scopeObjects = m_context->scopeChain().qmlScopeObjects;
        if (scopeObjects.isEmpty())
            return false;

        if (! id)
            return false; // ### error?

        if (! id->name) // possible after error recovery
            return false;

390 391 392 393 394 395
        QString propertyName;
        if (prefix.isEmpty())
            propertyName = id->name->asString();
        else
            propertyName = prefix;

396 397 398 399 400 401 402 403 404 405
        if (name)
            *name = propertyName;

        if (propertyName == QLatin1String("id") && ! id->next)
            return false; // ### should probably be a special value

        // attached properties
        bool isAttachedProperty = false;
        if (! propertyName.isEmpty() && propertyName[0].isUpper()) {
            isAttachedProperty = true;
406
            if (const Interpreter::ObjectValue *qmlTypes = m_context->scopeChain().qmlTypes)
407
                scopeObjects += qmlTypes;
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
        }

        if (scopeObjects.isEmpty())
            return false;

        // global lookup for first part of id
        const Interpreter::ObjectValue *objectValue = 0;
        const Interpreter::Value *value = 0;
        for (int i = scopeObjects.size() - 1; i >= 0; --i) {
            objectValue = scopeObjects[i];
            value = objectValue->lookupMember(propertyName, m_context);
            if (value)
                break;
        }
        if (parentObject)
            *parentObject = objectValue;
        if (!value) {
            qWarning() << "Skipping invalid property name" << propertyName;
            return false;
        }

        // can't look up members for attached properties
        if (isAttachedProperty)
            return false;

433 434 435 436
        // resolve references
        if (const Interpreter::Reference *ref = value->asReference())
            value = m_context->lookupReference(ref);

437 438
        // member lookup
        const UiQualifiedId *idPart = id;
439 440 441
        if (prefix.isEmpty())
            idPart = idPart->next;
        for (; idPart; idPart = idPart->next) {
442 443 444 445 446 447 448 449 450 451
            objectValue = Interpreter::value_cast<const Interpreter::ObjectValue *>(value);
            if (! objectValue) {
//                if (idPart->name)
//                    qDebug() << idPart->name->asString() << "has no property named"
//                             << propertyName;
                return false;
            }
            if (parentObject)
                *parentObject = objectValue;

452
            if (! idPart->name) {
453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476
                // somebody typed "id." and error recovery still gave us a valid tree,
                // so just bail out here.
                return false;
            }

            propertyName = idPart->name->asString();
            if (name)
                *name = propertyName;

            value = objectValue->lookupMember(propertyName, m_context);
            if (! value) {
//                if (idPart->name)
//                    qDebug() << "In" << idPart->name->asString() << ":"
//                             << objectValue->className() << "has no property named"
//                             << propertyName;
                return false;
            }
        }

        if (property)
            *property = value;
        return true;
    }

477
    bool isArrayProperty(const Interpreter::Value *value, const Interpreter::ObjectValue *containingObject, const QString &name)
478 479 480 481
    {
        if (!value)
            return false;
        const Interpreter::ObjectValue *objectValue = value->asObjectValue();
482
        if (objectValue && objectValue->prototype(m_context) == m_context->engine()->arrayPrototype())
483
            return true;
484

485 486 487 488
        Interpreter::PrototypeIterator iter(containingObject, m_context);
        while (iter.hasNext()) {
            const Interpreter::ObjectValue *proto = iter.next();
            if (proto->property(name, m_context) == m_context->engine()->arrayPrototype())
489
                return true;
490
            if (const Interpreter::QmlObjectValue *qmlIter = dynamic_cast<const Interpreter::QmlObjectValue *>(proto)) {
491 492 493 494 495
                if (qmlIter->isListProperty(name))
                    return true;
            }
        }
        return false;
496 497
    }

498
    QVariant convertToVariant(const QString &astValue, const QString &propertyPrefix, UiQualifiedId *propertyId)
499
    {
500
        const bool hasQuotes = astValue.trimmed().left(1) == QLatin1String("\"") && astValue.trimmed().right(1) == QLatin1String("\"");
501
        const QString cleanedValue = fixEscapedUnicodeChar(deEscape(stripQuotes(astValue.trimmed())));
502 503 504
        const Interpreter::Value *property = 0;
        const Interpreter::ObjectValue *containingObject = 0;
        QString name;
505 506
        if (!lookupProperty(propertyPrefix, propertyId, &property, &containingObject, &name)) {
            qWarning() << "Unknown property" << propertyPrefix + QLatin1Char('.') + flatten(propertyId)
507 508
                       << "on line" << propertyId->identifierToken.startLine
                       << "column" << propertyId->identifierToken.startColumn;
509
            return hasQuotes ? QVariant(cleanedValue) : cleverConvert(cleanedValue);
510 511
        }

512 513
        if (containingObject)
            containingObject->lookupMember(name, m_context, &containingObject);
514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537

        if (const Interpreter::QmlObjectValue * qmlObject = dynamic_cast<const Interpreter::QmlObjectValue *>(containingObject)) {
            const QString typeName = qmlObject->propertyType(name);
            if (qmlObject->isEnum(typeName)) {
                return QVariant(cleanedValue);
            } else {
                int type = QMetaType::type(typeName.toUtf8().constData());
                QVariant result;
                if (type)
                    result = PropertyParser::read(type, cleanedValue);
                if (result.isValid())
                    return result;
            }
        }

        QVariant v(cleanedValue);
        if (property->asBooleanValue()) {
            v.convert(QVariant::Bool);
        } else if (property->asColorValue()) {
            v.convert(QVariant::Color);
        } else if (property->asNumberValue()) {
            v.convert(QVariant::Double);
        } else if (property->asStringValue()) {
            // nothing to do
538 539 540
        } else { //property alias et al
            if (!hasQuotes)
                return cleverConvert(cleanedValue);
541 542 543 544
        }
        return v;
    }

545
    QVariant convertToEnum(Statement *rhs, const QString &propertyPrefix, UiQualifiedId *propertyId)
546 547 548 549 550 551 552
    {
        ExpressionStatement *eStmt = cast<ExpressionStatement *>(rhs);
        if (!eStmt || !eStmt->expression)
            return QVariant();

        const Interpreter::ObjectValue *containingObject = 0;
        QString name;
553
        if (!lookupProperty(propertyPrefix, propertyId, 0, &containingObject, &name)) {
554 555 556
            return QVariant();
        }

557 558
        if (containingObject)
            containingObject->lookupMember(name, m_context, &containingObject);
559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579
        const Interpreter::QmlObjectValue * lhsQmlObject = dynamic_cast<const Interpreter::QmlObjectValue *>(containingObject);
        if (!lhsQmlObject)
            return QVariant();
        const QString lhsPropertyTypeName = lhsQmlObject->propertyType(name);

        const Interpreter::ObjectValue *rhsValueObject = 0;
        QString rhsValueName;
        if (IdentifierExpression *idExp = cast<IdentifierExpression *>(eStmt->expression)) {
            if (!m_context->scopeChain().qmlScopeObjects.isEmpty())
                rhsValueObject = m_context->scopeChain().qmlScopeObjects.last();
            if (idExp->name)
                rhsValueName = idExp->name->asString();
        } else if (FieldMemberExpression *memberExp = cast<FieldMemberExpression *>(eStmt->expression)) {
            Evaluate evaluate(m_context);
            const Interpreter::Value *result = evaluate(memberExp->base);
            rhsValueObject = result->asObjectValue();

            if (memberExp->name)
                rhsValueName = memberExp->name->asString();
        }

580 581
        if (rhsValueObject)
            rhsValueObject->lookupMember(rhsValueName, m_context, &rhsValueObject);
582 583 584 585 586 587 588 589 590 591 592

        const Interpreter::QmlObjectValue *rhsQmlObjectValue = dynamic_cast<const Interpreter::QmlObjectValue *>(rhsValueObject);
        if (!rhsQmlObjectValue)
            return QVariant();

        if (rhsQmlObjectValue->enumContainsKey(lhsPropertyTypeName, rhsValueName))
            return QVariant(rhsValueName);
        else
            return QVariant();
    }

593 594 595 596

    LookupContext::Ptr lookupContext() const
    { return m_lookupContext; }

597
    QList<DiagnosticMessage> diagnosticLinkMessages() const
598
    { return m_diagnosticLinkMessages; }
599

600 601 602 603
private:
    Snapshot m_snapshot;
    Document::Ptr m_doc;
    Interpreter::Context *m_context;
604
    QList<DiagnosticMessage> m_diagnosticLinkMessages;
605
    Link m_link;
606
    LookupContext::Ptr m_lookupContext;
607 608 609 610 611 612 613 614 615
    ScopeBuilder m_scopeBuilder;
};

} // namespace Internal
} // namespace QmlDesigner

using namespace QmlDesigner;
using namespace QmlDesigner::Internal;

616 617 618 619 620 621 622 623 624 625 626 627
static inline bool equals(const QVariant &a, const QVariant &b)
{
    if (a.type() == QVariant::Double && b.type() == QVariant::Double)
        return qFuzzyCompare(a.toDouble(), b.toDouble());
    else
        return a == b;
}

TextToModelMerger::TextToModelMerger(RewriterView *reWriterView):
        m_rewriterView(reWriterView),
        m_isActive(false)
{
628
    Q_ASSERT(reWriterView);
629 630 631 632 633 634 635 636 637 638 639 640
}

void TextToModelMerger::setActive(bool active)
{
    m_isActive = active;
}

bool TextToModelMerger::isActive() const
{
    return m_isActive;
}

641
void TextToModelMerger::setupImports(const Document::Ptr &doc,
642
                                     DifferenceHandler &differenceHandler)
643
{
644
    QList<Import> existingImports = m_rewriterView->model()->imports();
645

646 647 648 649 650 651 652 653 654 655 656 657 658 659
    for (UiImportList *iter = doc->qmlProgram()->imports; iter; iter = iter->next) {
        UiImport *import = iter->import;
        if (!import)
            continue;

        QString version;
        if (import->versionToken.isValid())
            version = textAt(doc, import->versionToken);
        QString as;
        if (import->importId)
            as = import->importId->asString();

        if (import->fileName) {
            const QString strippedFileName = stripQuotes(import->fileName->asString());
660
            const Import newImport = Import::createFileImport(strippedFileName,
661
                                                              version, as, m_rewriterView->textModifier()->importPaths());
662

663
            if (!existingImports.removeOne(newImport))
664 665
                differenceHandler.modelMissesImport(newImport);
        } else {
666
            QString importUri = flatten(import->importUri);
667 668 669
            if (importUri == QLatin1String("Qt") && version == QLatin1String("4.7")) {
                importUri = QLatin1String("QtQuick");
                version = QLatin1String("1.0");
670 671
            }

672
            const Import newImport =
673
                    Import::createLibraryImport(importUri, version, as, m_rewriterView->textModifier()->importPaths());
674

675
            if (!existingImports.removeOne(newImport))
676
                differenceHandler.modelMissesImport(newImport);
677 678
        }
    }
679 680

    foreach (const Import &import, existingImports)
681
        differenceHandler.importAbsentInQMl(import);
682 683
}

684
bool TextToModelMerger::load(const QString &data, DifferenceHandler &differenceHandler)
685
{
686 687
//    qDebug() << "TextToModelMerger::load with data:" << data;

688 689
    const QUrl url = m_rewriterView->model()->fileUrl();
    const QStringList importPaths = m_rewriterView->textModifier()->importPaths();
690 691
    setActive(true);

692 693 694 695

    try {
        Snapshot snapshot = m_rewriterView->textModifier()->getSnapshot();
        const QString fileName = url.toLocalFile();
Erik Verbruggen's avatar
Erik Verbruggen committed
696
        Document::Ptr doc = Document::create(fileName.isEmpty() ? QLatin1String("<internal>") : fileName);
697
        doc->setSource(data);
698
        doc->parseQml();
699 700 701 702 703 704 705 706 707

        if (!doc->isParsedCorrectly()) {
            QList<RewriterView::Error> errors;
            foreach (const QmlJS::DiagnosticMessage &message, doc->diagnosticMessages())
                errors.append(RewriterView::Error(message, QUrl::fromLocalFile(doc->fileName())));
            m_rewriterView->setErrors(errors);
            setActive(false);
            return false;
        }
708 709
        snapshot.insert(doc);
        ReadingContext ctxt(snapshot, doc, importPaths);
710 711
        m_lookupContext = ctxt.lookupContext();
        m_document = doc;
712

713
        QList<RewriterView::Error> errors;
714 715 716 717 718

        foreach (const QmlJS::DiagnosticMessage &diagnosticMessage, ctxt.diagnosticLinkMessages()) {
            errors.append(RewriterView::Error(diagnosticMessage, QUrl::fromLocalFile(doc->fileName())));
        }

719
        if (view()->checkSemanticErrors()) {
720
            Check check(doc, m_lookupContext->context());
721 722 723 724 725 726 727 728 729 730
            check.setOptions(check.options() & ~Check::ErrCheckTypeErrors);
            foreach (const QmlJS::DiagnosticMessage &diagnosticMessage, check())
                if (diagnosticMessage.isError())
                    errors.append(RewriterView::Error(diagnosticMessage, QUrl::fromLocalFile(doc->fileName())));

            if (!errors.isEmpty()) {
                m_rewriterView->setErrors(errors);
                setActive(false);
                return false;
            }
731 732
        }

733 734 735 736 737 738 739 740 741 742
        setupImports(doc, differenceHandler);

        UiObjectMember *astRootNode = 0;
        if (UiProgram *program = doc->qmlProgram())
            if (program->members)
                astRootNode = program->members->member;
        ModelNode modelRootNode = m_rewriterView->rootModelNode();
        syncNode(modelRootNode, astRootNode, &ctxt, differenceHandler);
        m_rewriterView->positionStorage()->cleanupInvalidOffsets();
        m_rewriterView->clearErrors();
743 744

        setActive(false);
745
        return true;
746
    } catch (Exception &e) {
747
        RewriterView::Error error(&e);
748 749 750 751
        // Somehow, the error below gets eaten in upper levels, so printing the
        // exception info here for debugging purposes:
        qDebug() << "*** An exception occurred while reading the QML file:"
                 << error.toString();
752
        m_rewriterView->addError(error);
753 754 755

        setActive(false);

756
        return false;
757 758 759
    }
}

760
void TextToModelMerger::syncNode(ModelNode &modelNode,
761 762
                                 UiObjectMember *astNode,
                                 ReadingContext *context,
763
                                 DifferenceHandler &differenceHandler)
764
{
765 766 767 768 769 770 771 772 773 774 775 776 777
    UiQualifiedId *astObjectType = 0;
    UiObjectInitializer *astInitializer = 0;
    if (UiObjectDefinition *def = cast<UiObjectDefinition *>(astNode)) {
        astObjectType = def->qualifiedTypeNameId;
        astInitializer = def->initializer;
    } else if (UiObjectBinding *bin = cast<UiObjectBinding *>(astNode)) {
        astObjectType = bin->qualifiedTypeNameId;
        astInitializer = bin->initializer;
    }

    if (!astObjectType || !astInitializer)
        return;

Erik Verbruggen's avatar
Erik Verbruggen committed
778
    m_rewriterView->positionStorage()->setNodeOffset(modelNode, astObjectType->identifierToken.offset);
779

780
    QString typeName, defaultPropertyName;
781 782
    int majorVersion;
    int minorVersion;
783
    context->lookup(astObjectType, typeName, majorVersion, minorVersion, defaultPropertyName);
784 785
    if (defaultPropertyName.isEmpty()) //fallback and use the meta system of the model
        defaultPropertyName = modelNode.metaInfo().defaultPropertyName();
786 787 788 789 790

    if (typeName.isEmpty()) {
        qWarning() << "Skipping node with unknown type" << flatten(astObjectType);
        return;
    }
791

792 793 794 795
    const QString typeNameFixedForImplicitComponents = modelNode.parentProperty().isValid() &&
                                                       propertyIsComponentType(modelNode.parentProperty()) ?
                                                       QLatin1String("QtQuick.Component") : typeName;

796
    if ((modelNode.parentProperty().isValid() || modelNode.isRootNode()) && modelNode.type() != typeNameFixedForImplicitComponents //If there is no valid parentProperty
797
                                                                                                       //the node has just been created. The type is correct then.
798 799
            /*|| modelNode.majorVersion() != domObject.objectTypeMajorVersion()
            || modelNode.minorVersion() != domObject.objectTypeMinorVersion()*/) {
800
        const bool isRootNode = m_rewriterView->rootModelNode() == modelNode;
801 802 803
        differenceHandler.typeDiffers(isRootNode, modelNode, typeName,
                                      majorVersion, minorVersion,
                                      astNode, context);
804 805 806 807
        if (!isRootNode)
            return; // the difference handler will create a new node, so we're done.
    }

808 809 810 811 812 813
    if (isComponentType(typeNameFixedForImplicitComponents))
        setupComponent(modelNode);

    if (isCustomParserType(typeName))
        setupCustomParserNode(modelNode);

814 815
    context->enterScope(astNode);

816
    QSet<QString> modelPropertyNames = QSet<QString>::fromList(modelNode.propertyNames());
817 818
    if (!modelNode.id().isEmpty())
        modelPropertyNames.insert(QLatin1String("id"));
819
    QList<UiObjectMember *> defaultPropertyItems;
820

821 822 823
    for (UiObjectMemberList *iter = astInitializer->members; iter; iter = iter->next) {
        UiObjectMember *member = iter->member;
        if (!member)
824 825
            continue;

826 827
        if (UiArrayBinding *array = cast<UiArrayBinding *>(member)) {
            const QString astPropertyName = flatten(array->qualifiedId);
828
            if (isPropertyChangesType(typeName) || context->lookupProperty(QString(), array->qualifiedId)) {
829
                AbstractProperty modelProperty = modelNode.property(astPropertyName);
Erik Verbruggen's avatar
Erik Verbruggen committed
830 831 832 833 834 835
                QList<UiObjectMember *> arrayMembers;
                for (UiArrayMemberList *iter = array->members; iter; iter = iter->next)
                    if (UiObjectMember *member = iter->member)
                        arrayMembers.append(member);

                syncArrayProperty(modelProperty, arrayMembers, context, differenceHandler);
836 837 838 839 840
                modelPropertyNames.remove(astPropertyName);
            } else {
                qWarning() << "Skipping invalid array property" << astPropertyName
                           << "for node type" << modelNode.type();
            }
841 842 843 844 845 846 847 848 849 850 851 852 853
        } else if (UiObjectDefinition *def = cast<UiObjectDefinition *>(member)) {
            const QString name = def->qualifiedTypeNameId->name->asString();
            if (name.isEmpty() || !name.at(0).isUpper()) {
                QStringList props = syncGroupedProperties(modelNode,
                                                          name,
                                                          def->initializer->members,
                                                          context,
                                                          differenceHandler);
                foreach (const QString &prop, props)
                    modelPropertyNames.remove(prop);
            } else {
                defaultPropertyItems.append(member);
            }
854 855 856 857 858
        } else if (UiObjectBinding *binding = cast<UiObjectBinding *>(member)) {
            const QString astPropertyName = flatten(binding->qualifiedId);
            if (binding->hasOnToken) {
                // skip value sources
            } else {
859 860 861
                const Interpreter::Value *propertyType = 0;
                const Interpreter::ObjectValue *containingObject = 0;
                QString name;
862
                if (context->lookupProperty(QString(), binding->qualifiedId, &propertyType, &containingObject, &name) || isPropertyChangesType(typeName)) {
863
                    AbstractProperty modelProperty = modelNode.property(astPropertyName);
864
                    if (context->isArrayProperty(propertyType, containingObject, name)) {
Erik Verbruggen's avatar
Erik Verbruggen committed
865
                        syncArrayProperty(modelProperty, QList<QmlJS::AST::UiObjectMember*>() << member, context, differenceHandler);
866 867 868
                    } else {
                        syncNodeProperty(modelProperty, binding, context, differenceHandler);
                    }
869 870 871 872 873 874 875
                    modelPropertyNames.remove(astPropertyName);
                } else {
                    qWarning() << "Skipping invalid node property" << astPropertyName
                               << "for node type" << modelNode.type();
                }
            }
        } else if (UiScriptBinding *script = cast<UiScriptBinding *>(member)) {
876
            modelPropertyNames.remove(syncScriptBinding(modelNode, QString(), script, context, differenceHandler));
877
        } else if (UiPublicMember *property = cast<UiPublicMember *>(member)) {
878 879 880 881 882 883
            if (property->type == UiPublicMember::Signal)
                continue; // QML designer doesn't support this yet.

            if (!property->name || !property->memberType)
                continue; // better safe than sorry.

884 885
            const QString astName = property->name->asString();
            QString astValue;
886
            if (property->statement)
887
                astValue = textAt(context->doc(),
888 889
                                  property->statement->firstSourceLocation(),
                                  property->statement->lastSourceLocation());
890 891
            const QString astType = property->memberType->asString();
            AbstractProperty modelProperty = modelNode.property(astName);
892
            if (!property->statement || isLiteralValue(property->statement)) {
893 894 895
                const QVariant variantValue = convertDynamicPropertyValueToVariant(astValue, astType);
                syncVariantProperty(modelProperty, variantValue, astType, differenceHandler);
            } else {
896
                syncExpressionProperty(modelProperty, astValue, astType, differenceHandler);
897
            }
898 899
            modelPropertyNames.remove(astName);
        } else {
dt's avatar
dt committed
900
            qWarning() << "Found an unknown QML value.";
901 902 903
        }
    }

904 905
    if (!defaultPropertyItems.isEmpty()) {
        if (defaultPropertyName.isEmpty()) {
906
            if (!isComponentType(modelNode.type())) {
Erik Verbruggen's avatar
Erik Verbruggen committed
907
                qWarning() << "No default property for node type" << modelNode.type() << ", ignoring child items.";
908 909 910
            } else {
                setupComponent(modelNode);
            }
911 912 913 914 915 916
        } else {
            AbstractProperty modelProperty = modelNode.property(defaultPropertyName);
            if (modelProperty.isNodeListProperty()) {
                NodeListProperty nodeListProperty = modelProperty.toNodeListProperty();
                syncNodeListProperty(nodeListProperty, defaultPropertyItems, context,
                                     differenceHandler);
917
            } else {
918 919 920
                differenceHandler.shouldBeNodeListProperty(modelProperty,
                                                           defaultPropertyItems,
                                                           context);
921
            }
922
            modelPropertyNames.remove(defaultPropertyName);
923 924 925 926 927 928
        }
    }

    foreach (const QString &modelPropertyName, modelPropertyNames) {
        AbstractProperty modelProperty = modelNode.property(modelPropertyName);

929
        // property deleted.
930 931 932 933
        if (modelPropertyName == QLatin1String("id"))
            differenceHandler.idsDiffer(modelNode, QString());
        else
            differenceHandler.propertyAbsentFromQml(modelProperty);
934
    }
935 936

    context->leaveScope();
937
}
938

939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968
QString TextToModelMerger::syncScriptBinding(ModelNode &modelNode,
                                             const QString &prefix,
                                             UiScriptBinding *script,
                                             ReadingContext *context,
                                             DifferenceHandler &differenceHandler)
{
    QString astPropertyName = flatten(script->qualifiedId);
    if (!prefix.isEmpty())
        astPropertyName.prepend(prefix + QLatin1Char('.'));

    QString astValue;
    if (script->statement) {
        astValue = textAt(context->doc(),
                          script->statement->firstSourceLocation(),
                          script->statement->lastSourceLocation());
        astValue = astValue.trimmed();
        if (astValue.endsWith(QLatin1Char(';')))
            astValue = astValue.left(astValue.length() - 1);
        astValue = astValue.trimmed();
    }

    if (astPropertyName == QLatin1String("id")) {
        syncNodeId(modelNode, astValue, differenceHandler);
        return astPropertyName;
    }

    if (isSignalPropertyName(astPropertyName))
        return QString();

    if (isLiteralValue(script)) {
969
        if (isPropertyChangesType(modelNode.type())) {
970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990
            AbstractProperty modelProperty = modelNode.property(astPropertyName);
            const QVariant variantValue(deEscape(stripQuotes(astValue)));
            syncVariantProperty(modelProperty, variantValue, QString(), differenceHandler);
            return astPropertyName;
        } else {
            const QVariant variantValue = context->convertToVariant(astValue, prefix, script->qualifiedId);
            if (variantValue.isValid()) {
                AbstractProperty modelProperty = modelNode.property(astPropertyName);
                syncVariantProperty(modelProperty, variantValue, QString(), differenceHandler);
                return astPropertyName;
            } else {
                qWarning() << "Skipping invalid variant property" << astPropertyName
                           << "for node type" << modelNode.type();
                return QString();
            }
        }
    }

    const QVariant enumValue = context->convertToEnum(script->statement, prefix, script->qualifiedId);
    if (enumValue.isValid()) { // It is a qualified enum:
        AbstractProperty modelProperty = modelNode.property(astPropertyName);
991
        syncVariantProperty(modelProperty, enumValue, QString(), differenceHandler); // TODO: parse type
992 993
        return astPropertyName;
    } else { // Not an enum, so:
994
        if (isPropertyChangesType(modelNode.type()) || context->lookupProperty(prefix, script->qualifiedId)) {
995
            AbstractProperty modelProperty = modelNode.property(astPropertyName);
996
            syncExpressionProperty(modelProperty, astValue, QString(), differenceHandler); // TODO: parse type
997 998 999 1000 1001 1002 1003 1004 1005
            return astPropertyName;
        } else {
            qWarning() << "Skipping invalid expression property" << astPropertyName
                    << "for node type" << modelNode.type();
            return QString();
        }
    }
}

1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021
void TextToModelMerger::syncNodeId(ModelNode &modelNode, const QString &astObjectId,
                                   DifferenceHandler &differenceHandler)
{
    if (astObjectId.isEmpty()) {
        if (!modelNode.id().isEmpty()) {
            ModelNode existingNodeWithId = m_rewriterView->modelNodeForId(astObjectId);
            if (existingNodeWithId.isValid())
                existingNodeWithId.setId(QString());
            differenceHandler.idsDiffer(modelNode, astObjectId);
        }
    } else {
        if (modelNode.id() != astObjectId) {
            ModelNode existingNodeWithId = m_rewriterView->modelNodeForId(astObjectId);
            if (existingNodeWithId.isValid())
                existingNodeWithId.setId(QString());
            differenceHandler.idsDiffer(modelNode, astObjectId);