qmljscheck.cpp 61.8 KB
Newer Older
hjk's avatar
hjk committed
1
/****************************************************************************
Christian Kamm's avatar
Christian Kamm committed
2
**
3 4
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
Christian Kamm's avatar
Christian Kamm committed
5
**
hjk's avatar
hjk committed
6
** This file is part of Qt Creator.
Christian Kamm's avatar
Christian Kamm committed
7
**
hjk's avatar
hjk committed
8 9 10 11
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
12 13 14
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
Christian Kamm's avatar
Christian Kamm committed
15
**
16 17 18 19 20 21 22
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
con's avatar
con committed
23
**
hjk's avatar
hjk committed
24
****************************************************************************/
Christian Kamm's avatar
Christian Kamm committed
25 26 27

#include "qmljscheck.h"
#include "qmljsbind.h"
28
#include "qmljsevaluate.h"
29
#include "qmljsutils.h"
Christian Kamm's avatar
Christian Kamm committed
30 31
#include "parser/qmljsast_p.h"

32 33
#include <utils/qtcassert.h>

34
#include <QColor>
35
#include <QDir>
Samuel Gaist's avatar
Samuel Gaist committed
36
#include <QRegExp>
Christian Kamm's avatar
Christian Kamm committed
37 38 39

using namespace QmlJS;
using namespace QmlJS::AST;
40
using namespace QmlJS::StaticAnalysis;
Christian Kamm's avatar
Christian Kamm committed
41

42 43 44 45 46
namespace {

class AssignmentCheck : public ValueVisitor
{
public:
47
    Message operator()(
48
            const Document::Ptr &document,
49
            const SourceLocation &location,
50 51
            const Value *lhsValue,
            const Value *rhsValue,
Christian Kamm's avatar
Christian Kamm committed
52
            Node *ast)
53
    {
54
        _doc = document;
55
        _rhsValue = rhsValue;
56
        _location = location;
Christian Kamm's avatar
Christian Kamm committed
57 58 59 60
        if (ExpressionStatement *expStmt = cast<ExpressionStatement *>(ast))
            _ast = expStmt->expression;
        else
            _ast = ast->expressionCast();
61 62 63 64 65 66 67

        if (lhsValue)
            lhsValue->accept(this);

        return _message;
    }

68 69 70 71 72
    void setMessage(Type type)
    {
        _message = Message(type, _location);
    }

73
    virtual void visit(const NumberValue *value)
74
    {
Christian Kamm's avatar
Christian Kamm committed
75
        if (const QmlEnumValue *enumValue = value_cast<QmlEnumValue>(value)) {
76
            if (StringLiteral *stringLiteral = cast<StringLiteral *>(_ast)) {
77
                const QString valueName = stringLiteral->value.toString();
78

79
                if (!enumValue->keys().contains(valueName))
80
                    setMessage(ErrInvalidEnumValue);
81
            } else if (! _rhsValue->asStringValue() && ! _rhsValue->asNumberValue()
82
                       && ! _rhsValue->asUnknownValue()) {
83
                setMessage(ErrEnumValueMustBeStringOrNumber);
84 85
            }
        } else {
Christian Kamm's avatar
Christian Kamm committed
86 87
            if (cast<TrueLiteral *>(_ast)
                    || cast<FalseLiteral *>(_ast)) {
88
                setMessage(ErrNumberValueExpected);
89
            }
90 91 92 93 94 95 96 97 98 99
        }
    }

    virtual void visit(const BooleanValue *)
    {
        UnaryMinusExpression *unaryMinus = cast<UnaryMinusExpression *>(_ast);

        if (cast<StringLiteral *>(_ast)
                || cast<NumericLiteral *>(_ast)
                || (unaryMinus && cast<NumericLiteral *>(unaryMinus->expression))) {
100
            setMessage(ErrBooleanValueExpected);
101 102 103
        }
    }

104
    virtual void visit(const StringValue *value)
105 106 107 108 109
    {
        UnaryMinusExpression *unaryMinus = cast<UnaryMinusExpression *>(_ast);

        if (cast<NumericLiteral *>(_ast)
                || (unaryMinus && cast<NumericLiteral *>(unaryMinus->expression))
Christian Kamm's avatar
Christian Kamm committed
110 111
                || cast<TrueLiteral *>(_ast)
                || cast<FalseLiteral *>(_ast)) {
112
            setMessage(ErrStringValueExpected);
113
        }
114 115 116

        if (value && value->asUrlValue()) {
            if (StringLiteral *literal = cast<StringLiteral *>(_ast)) {
117
                QUrl url(literal->value.toString());
118
                if (!url.isValid() && !url.isEmpty()) {
119
                    setMessage(ErrInvalidUrl);
120 121 122
                } else {
                    QString fileName = url.toLocalFile();
                    if (!fileName.isEmpty()) {
123
                        if (QFileInfo(fileName).isRelative()) {
124
                            fileName.prepend(QLatin1Char('/'));
125 126
                            fileName.prepend(_doc->path());
                        }
127
                        if (!QFileInfo::exists(fileName))
128
                            setMessage(WarnFileOrDirectoryDoesNotExist);
129 130 131 132
                    }
                }
            }
        }
133 134 135 136 137
    }

    virtual void visit(const ColorValue *)
    {
        if (StringLiteral *stringLiteral = cast<StringLiteral *>(_ast)) {
138
            if (!toQColor(stringLiteral->value.toString()).isValid())
139
                setMessage(ErrInvalidColor);
140 141 142 143 144 145 146
        } else {
            visit((StringValue *)0);
        }
    }

    virtual void visit(const AnchorLineValue *)
    {
147
        if (! (_rhsValue->asAnchorLineValue() || _rhsValue->asUnknownValue()))
148
            setMessage(ErrAnchorLineExpected);
149 150
    }

151
    Document::Ptr _doc;
152 153
    Message _message;
    SourceLocation _location;
154 155 156 157
    const Value *_rhsValue;
    ExpressionNode *_ast;
};

158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178
class ReachesEndCheck : protected Visitor
{
public:
    bool operator()(Node *node)
    {
        _labels.clear();
        _labelledBreaks.clear();
        return check(node) == ReachesEnd;
    }

protected:
    // Sorted by how much code will be reachable from that state, i.e.
    // ReachesEnd is guaranteed to reach more code than Break and so on.
    enum State
    {
        ReachesEnd = 0,
        Break = 1,
        Continue = 2,
        ReturnOrThrow = 3
    };
    State _state;
179
    QHash<QString, Node *> _labels;
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
    QSet<Node *> _labelledBreaks;

    virtual void onUnreachable(Node *)
    {}

    virtual State check(Node *node)
    {
        _state = ReachesEnd;
        Node::accept(node, this);
        return _state;
    }

    virtual bool preVisit(Node *ast)
    {
        if (ast->expressionCast())
            return false;
        if (_state == ReachesEnd)
            return true;
        if (Statement *stmt = ast->statementCast())
            onUnreachable(stmt);
        if (FunctionSourceElement *fun = cast<FunctionSourceElement *>(ast))
            onUnreachable(fun->declaration);
        if (StatementSourceElement *stmt = cast<StatementSourceElement *>(ast))
            onUnreachable(stmt->statement);
        return false;
    }

    virtual bool visit(LabelledStatement *ast)
    {
        // get the target statement
        Statement *end = ast->statement;
        forever {
            if (LabelledStatement *label = cast<LabelledStatement *>(end))
                end = label->statement;
            else
                break;
        }
217 218
        if (!ast->label.isEmpty())
            _labels[ast->label.toString()] = end;
219 220 221 222 223 224
        return true;
    }

    virtual bool visit(BreakStatement *ast)
    {
        _state = Break;
225
        if (!ast->label.isEmpty()) {
226
            if (Node *target = _labels.value(ast->label.toString())) {
227
                _labelledBreaks.insert(target);
228 229
                _state = ReturnOrThrow; // unwind until label is hit
            }
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
        }
        return false;
    }

    // labelled continues don't change control flow...
    virtual bool visit(ContinueStatement *) { _state = Continue; return false; }

    virtual bool visit(ReturnStatement *) { _state = ReturnOrThrow; return false; }
    virtual bool visit(ThrowStatement *) { _state = ReturnOrThrow; return false; }

    virtual bool visit(IfStatement *ast)
    {
        State ok = check(ast->ok);
        State ko = check(ast->ko);
        _state = qMin(ok, ko);
        return false;
    }

    void handleClause(StatementList *statements, State *result, bool *fallthrough)
    {
        State clauseResult = check(statements);
        if (clauseResult == ReachesEnd) {
            *fallthrough = true;
        } else {
            *fallthrough = false;
            *result = qMin(*result, clauseResult);
        }
    }

    virtual bool visit(SwitchStatement *ast)
    {
        if (!ast->block)
            return false;
        State result = ReturnOrThrow;
        bool lastWasFallthrough = false;

        for (CaseClauses *it = ast->block->clauses; it; it = it->next) {
            if (it->clause)
                handleClause(it->clause->statements, &result, &lastWasFallthrough);
        }
        if (ast->block->defaultClause)
            handleClause(ast->block->defaultClause->statements, &result, &lastWasFallthrough);
        for (CaseClauses *it = ast->block->moreClauses; it; it = it->next) {
            if (it->clause)
                handleClause(it->clause->statements, &result, &lastWasFallthrough);
        }

277
        if (lastWasFallthrough || !ast->block->defaultClause)
278 279 280 281 282 283 284 285 286 287
            result = ReachesEnd;
        if (result == Break || _labelledBreaks.contains(ast))
            result = ReachesEnd;
        _state = result;
        return false;
    }

    virtual bool visit(TryStatement *ast)
    {
        State tryBody = check(ast->statement);
288 289 290 291 292 293
        State catchBody = ReturnOrThrow;
        if (ast->catchExpression)
            catchBody = check(ast->catchExpression->statement);
        State finallyBody = ReachesEnd;
        if (ast->finallyExpression)
            finallyBody = check(ast->finallyExpression->statement);
294 295 296 297 298

        _state = qMax(qMin(tryBody, catchBody), finallyBody);
        return false;
    }

299
    bool preconditionLoopStatement(Node *, Statement *body)
300 301
    {
        check(body);
302
        _state = ReachesEnd; // condition could be false...
303 304 305
        return false;
    }

306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321
    virtual bool visit(WhileStatement *ast) { return preconditionLoopStatement(ast, ast->statement); }
    virtual bool visit(ForStatement *ast) { return preconditionLoopStatement(ast, ast->statement); }
    virtual bool visit(ForEachStatement *ast) { return preconditionLoopStatement(ast, ast->statement); }
    virtual bool visit(LocalForStatement *ast) { return preconditionLoopStatement(ast, ast->statement); }
    virtual bool visit(LocalForEachStatement *ast) { return preconditionLoopStatement(ast, ast->statement); }

    virtual bool visit(DoWhileStatement *ast)
    {
        check(ast->statement);
        // not necessarily an infinite loop due to labelled breaks
        if (_state == Continue)
            _state = ReturnOrThrow;
        if (_state == Break || _labelledBreaks.contains(ast))
            _state = ReachesEnd;
        return false;
    }
322 323 324 325
};

class MarkUnreachableCode : protected ReachesEndCheck
{
326
    QList<Message> _messages;
327 328 329
    bool _emittedWarning;

public:
330
    QList<Message> operator()(Node *ast)
331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352
    {
        _messages.clear();
        check(ast);
        return _messages;
    }

protected:
    virtual State check(Node *node)
    {
        bool oldwarning = _emittedWarning;
        _emittedWarning = false;
        State s = ReachesEndCheck::check(node);
        _emittedWarning = oldwarning;
        return s;
    }

    virtual void onUnreachable(Node *node)
    {
        if (_emittedWarning)
            return;
        _emittedWarning = true;

353
        Message message(WarnUnreachable, SourceLocation());
354
        if (Statement *statement = node->statementCast())
355
            message.location = locationFromRange(statement->firstSourceLocation(), statement->lastSourceLocation());
356
        else if (ExpressionNode *expr = node->expressionCast())
357 358
            message.location = locationFromRange(expr->firstSourceLocation(), expr->lastSourceLocation());
        if (message.isValid())
359 360 361 362
            _messages += message;
    }
};

363
class DeclarationsCheck : protected Visitor
364 365
{
public:
366
    QList<Message> operator()(FunctionExpression *function)
367
    {
368
        clear();
369
        for (FormalParameterList *plist = function->formals; plist; plist = plist->next) {
370 371
            if (!plist->name.isEmpty())
                _formalParameterNames += plist->name.toString();
372 373 374 375 376 377
        }

        Node::accept(function->body, this);
        return _messages;
    }

378
    QList<Message> operator()(Node *node)
379 380
    {
        clear();
381
        Node::accept(node, this);
382 383 384
        return _messages;
    }

385
protected:
386 387 388 389 390 391 392 393 394 395
    void clear()
    {
        _messages.clear();
        _declaredFunctions.clear();
        _declaredVariables.clear();
        _possiblyUndeclaredUses.clear();
        _seenNonDeclarationStatement = false;
        _formalParameterNames.clear();
    }

396 397 398 399 400 401 402 403 404 405
    void postVisit(Node *ast)
    {
        if (!_seenNonDeclarationStatement && ast->statementCast()
                && !cast<VariableStatement *>(ast)) {
            _seenNonDeclarationStatement = true;
        }
    }

    bool visit(IdentifierExpression *ast)
    {
406
        if (ast->name.isEmpty())
407
            return false;
408
        const QString &name = ast->name.toString();
409 410 411 412 413 414 415
        if (!_declaredFunctions.contains(name) && !_declaredVariables.contains(name))
            _possiblyUndeclaredUses[name].append(ast->identifierToken);
        return false;
    }

    bool visit(VariableStatement *ast)
    {
416
        if (_seenNonDeclarationStatement)
417
            addMessage(HintDeclarationsShouldBeAtStartOfFunction, ast->declarationKindToken);
418 419 420 421 422
        return true;
    }

    bool visit(VariableDeclaration *ast)
    {
423
        if (ast->name.isEmpty())
424
            return true;
425
        const QString &name = ast->name.toString();
426

427
        if (_formalParameterNames.contains(name))
428
            addMessage(WarnAlreadyFormalParameter, ast->identifierToken, name);
429
        else if (_declaredFunctions.contains(name))
430
            addMessage(WarnAlreadyFunction, ast->identifierToken, name);
431
        else if (_declaredVariables.contains(name))
432
            addMessage(WarnDuplicateDeclaration, ast->identifierToken, name);
433 434

        if (_possiblyUndeclaredUses.contains(name)) {
435 436
            foreach (const SourceLocation &loc, _possiblyUndeclaredUses.value(name)) {
                addMessage(WarnVarUsedBeforeDeclaration, loc, name);
437 438 439 440 441 442 443 444 445 446
            }
            _possiblyUndeclaredUses.remove(name);
        }
        _declaredVariables[name] = ast;

        return true;
    }

    bool visit(FunctionDeclaration *ast)
    {
447
        if (_seenNonDeclarationStatement)
448
            addMessage(HintDeclarationsShouldBeAtStartOfFunction, ast->functionToken);
449 450 451 452 453 454

        return visit(static_cast<FunctionExpression *>(ast));
    }

    bool visit(FunctionExpression *ast)
    {
455
        if (ast->name.isEmpty())
456
            return false;
457
        const QString &name = ast->name.toString();
458

459
        if (_formalParameterNames.contains(name))
460
            addMessage(WarnAlreadyFormalParameter, ast->identifierToken, name);
461
        else if (_declaredVariables.contains(name))
462
            addMessage(WarnAlreadyVar, ast->identifierToken, name);
463
        else if (_declaredFunctions.contains(name))
464
            addMessage(WarnDuplicateDeclaration, ast->identifierToken, name);
465 466 467

        if (FunctionDeclaration *decl = cast<FunctionDeclaration *>(ast)) {
            if (_possiblyUndeclaredUses.contains(name)) {
468 469
                foreach (const SourceLocation &loc, _possiblyUndeclaredUses.value(name)) {
                    addMessage(WarnFunctionUsedBeforeDeclaration, loc, name);
470 471 472 473 474 475 476 477 478 479
                }
                _possiblyUndeclaredUses.remove(name);
            }
            _declaredFunctions[name] = decl;
        }

        return false;
    }

private:
480
    void addMessage(Type type, const SourceLocation &loc, const QString &arg1 = QString())
481
    {
482
        _messages.append(Message(type, loc, arg1));
483 484
    }

485
    QList<Message> _messages;
486 487 488 489 490 491 492
    QStringList _formalParameterNames;
    QHash<QString, VariableDeclaration *> _declaredVariables;
    QHash<QString, FunctionDeclaration *> _declaredFunctions;
    QHash<QString, QList<SourceLocation> > _possiblyUndeclaredUses;
    bool _seenNonDeclarationStatement;
};

493 494 495
class IdsThatShouldNotBeUsedInDesigner  : public QStringList
{
public:
496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523
    IdsThatShouldNotBeUsedInDesigner() : QStringList({"top",
                                                      "bottom",
                                                      "left",
                                                      "right",
                                                      "width",
                                                      "height",
                                                      "x",
                                                      "y",
                                                      "opacity",
                                                      "parent",
                                                      "item",
                                                      "flow",
                                                      "color",
                                                      "margin",
                                                      "padding",
                                                      "border",
                                                      "font",
                                                      "text",
                                                      "source",
                                                      "state",
                                                      "visible",
                                                      "focus",
                                                      "data",
                                                      "clip",
                                                      "layer",
                                                      "scale",
                                                      "enabled",
                                                      "anchors"})
524 525 526 527 528
    {
    }

};

529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552
class VisualAspectsPropertyBlackList : public QStringList
{
public:
   VisualAspectsPropertyBlackList()
   {
       (*this) << QLatin1String("x") << QLatin1String("y") << QLatin1String("z")
            << QLatin1String("width") << QLatin1String("height") << QLatin1String("color")
            << QLatin1String("opacity") << QLatin1String("scale")
            << QLatin1String("rotation") << QLatin1String("margins")
            << QLatin1String("verticalCenterOffset") << QLatin1String("horizontalCenterOffset")
            << QLatin1String("baselineOffset") << QLatin1String("bottomMargin")
            << QLatin1String("topMargin") << QLatin1String("leftMargin")
            << QLatin1String("rightMargin") << QLatin1String("baseline")
            << QLatin1String("centerIn") << QLatin1String("fill")
            << QLatin1String("left") << QLatin1String("right")
            << QLatin1String("mirrored") << QLatin1String("verticalCenter")
            << QLatin1String("horizontalCenter");

   }
};

class UnsupportedTypesByVisualDesigner : public QStringList
{
public:
553
    UnsupportedTypesByVisualDesigner() : QStringList({"Transform",
554 555 556 557 558
                                                      "Timer",
                                                      "Rotation",
                                                      "Scale",
                                                      "Translate",
                                                      "Package",
559
                                                      "Particles"})
560 561
    {

562
    }
563
};
564

565 566 567
class UnsupportedTypesByQmlUi : public QStringList
{
public:
568
    UnsupportedTypesByQmlUi() : QStringList({"Binding",
569 570 571 572 573 574 575 576 577 578 579 580
                                             "ShaderEffect",
                                             "ShaderEffectSource",
                                             "Component",
                                             "Loader",
                                             "Transition",
                                             "PropertyAnimation",
                                             "SequentialAnimation",
                                             "PropertyAnimation",
                                             "SequentialAnimation",
                                             "ParallelAnimation",
                                             "NumberAnimation",
                                             "Drawer"})
581 582
    {
        append(UnsupportedTypesByVisualDesigner());
583 584 585
    }
};

586 587 588 589 590 591 592 593 594 595 596 597
class UnsupportedRootObjectTypesByVisualDesigner : public QStringList
{
public:
    UnsupportedRootObjectTypesByVisualDesigner()
    {
        (*this) << QLatin1String("QtObject") << QLatin1String("ListModel")
            << QLatin1String("Component") << QLatin1String("Timer")
            << QLatin1String("Package");
    }

};

598 599 600 601 602 603 604 605 606 607 608
class UnsupportedRootObjectTypesByQmlUi : public QStringList
{
public:
    UnsupportedRootObjectTypesByQmlUi()
    {
        (*this) << UnsupportedRootObjectTypesByVisualDesigner()
                << QLatin1String("Window") << QLatin1String("ApplicationWindow");
    }

};

609 610
} // end of anonymous namespace

611
Q_GLOBAL_STATIC(IdsThatShouldNotBeUsedInDesigner, idsThatShouldNotBeUsedInDesigner)
612 613
Q_GLOBAL_STATIC(VisualAspectsPropertyBlackList, visualAspectsPropertyBlackList)
Q_GLOBAL_STATIC(UnsupportedTypesByVisualDesigner, unsupportedTypesByVisualDesigner)
614
Q_GLOBAL_STATIC(UnsupportedRootObjectTypesByVisualDesigner, unsupportedRootObjectTypesByVisualDesigner)
615 616
Q_GLOBAL_STATIC(UnsupportedRootObjectTypesByQmlUi, unsupportedRootObjectTypesByQmlUi)
Q_GLOBAL_STATIC(UnsupportedTypesByQmlUi, unsupportedTypesByQmlUi)
617

Christian Kamm's avatar
Christian Kamm committed
618
Check::Check(Document::Ptr doc, const ContextPtr &context)
Christian Kamm's avatar
Christian Kamm committed
619
    : _doc(doc)
Christian Kamm's avatar
Christian Kamm committed
620 621
    , _context(context)
    , _scopeChain(doc, _context)
622
    , _scopeBuilder(&_scopeChain)
623
    , _importsOk(false)
624
    , _inStatementBinding(false)
625 626 627
    , _imports(0)
    , _isQtQuick2(false)

Christian Kamm's avatar
Christian Kamm committed
628
{
629 630
    _imports = context->imports(doc.data());
    if (_imports && !_imports->importFailed()) {
631
        _importsOk = true;
632 633
        _isQtQuick2 = isQtQuick2();
    }
634

635 636 637 638
    _enabledMessages = Message::allMessageTypes().toSet();
    disableMessage(HintAnonymousFunctionSpacing);
    disableMessage(HintDeclareVarsInOneLine);
    disableMessage(HintDeclarationsShouldBeAtStartOfFunction);
639
    disableMessage(HintBinaryOperatorSpacing);
640
    disableMessage(HintOneStatementPerLine);
641
    disableMessage(HintExtraParentheses);
642 643

    if (isQtQuick2Ui()) {
644
        disableQmlDesignerChecks();
645 646 647 648
    } else {
        disableQmlDesignerChecks();
        disableQmlDesignerUiFileChecks();
    }
Christian Kamm's avatar
Christian Kamm committed
649 650 651 652 653 654
}

Check::~Check()
{
}

655
QList<Message> Check::operator()()
Christian Kamm's avatar
Christian Kamm committed
656 657
{
    _messages.clear();
658 659
    scanCommentsForAnnotations();

Christian Kamm's avatar
Christian Kamm committed
660
    Node::accept(_doc->ast(), this);
661 662
    warnAboutUnnecessarySuppressions();

Christian Kamm's avatar
Christian Kamm committed
663 664 665
    return _messages;
}

666 667 668 669 670 671 672 673 674 675
void Check::enableMessage(Type type)
{
    _enabledMessages.insert(type);
}

void Check::disableMessage(Type type)
{
    _enabledMessages.remove(type);
}

676 677
void Check::enableQmlDesignerChecks()
{
678 679 680 681 682
    enableMessage(WarnImperativeCodeNotEditableInVisualDesigner);
    enableMessage(WarnUnsupportedTypeInVisualDesigner);
    enableMessage(WarnReferenceToParentItemNotSupportedByVisualDesigner);
    enableMessage(WarnAboutQtQuick1InsteadQtQuick2);
    enableMessage(ErrUnsupportedRootTypeInVisualDesigner);
683
    enableMessage(ErrInvalidIdeInVisualDesigner);
684 685 686 687 688 689 690 691 692 693 694
    //## triggers too often ## check.enableMessage(StaticAnalysis::WarnUndefinedValueForVisualDesigner);
}

void Check::disableQmlDesignerChecks()
{
    disableMessage(WarnImperativeCodeNotEditableInVisualDesigner);
    disableMessage(WarnUnsupportedTypeInVisualDesigner);
    disableMessage(WarnReferenceToParentItemNotSupportedByVisualDesigner);
    disableMessage(WarnUndefinedValueForVisualDesigner);
    disableMessage(WarnStatesOnlyInRootItemForVisualDesigner);
    disableMessage(ErrUnsupportedRootTypeInVisualDesigner);
695
    disableMessage(ErrInvalidIdeInVisualDesigner);
696 697 698 699
}

void Check::enableQmlDesignerUiFileChecks()
{
700 701 702 703 704
    enableMessage(ErrUnsupportedRootTypeInQmlUi);
    enableMessage(ErrUnsupportedTypeInQmlUi);
    enableMessage(ErrFunctionsNotSupportedInQmlUi);
    enableMessage(ErrBlocksNotSupportedInQmlUi);
    enableMessage(ErrBehavioursNotSupportedInQmlUi);
705 706
    enableMessage(ErrStatesOnlyInRootItemInQmlUi);
    enableMessage(ErrReferenceToParentItemNotSupportedInQmlUi);
707 708 709 710
}

void Check::disableQmlDesignerUiFileChecks()
{
711 712 713 714 715
    disableMessage(ErrUnsupportedRootTypeInQmlUi);
    disableMessage(ErrUnsupportedTypeInQmlUi);
    disableMessage(ErrFunctionsNotSupportedInQmlUi);
    disableMessage(ErrBlocksNotSupportedInQmlUi);
    disableMessage(ErrBehavioursNotSupportedInQmlUi);
716 717
    disableMessage(ErrStatesOnlyInRootItemInQmlUi);
    disableMessage(ErrReferenceToParentItemNotSupportedInQmlUi);
718 719
}

720 721 722 723 724 725 726 727 728 729 730
bool Check::preVisit(Node *ast)
{
    _chain.append(ast);
    return true;
}

void Check::postVisit(Node *)
{
    _chain.removeLast();
}

731
bool Check::visit(UiProgram *)
Christian Kamm's avatar
Christian Kamm committed
732 733 734 735
{
    return true;
}

736 737
bool Check::visit(UiObjectInitializer *)
{
738
    QString typeName;
739
    m_propertyStack.push(StringSet());
740 741 742 743 744 745 746
    UiQualifiedId *qualifiedTypeId = qualifiedTypeNameId(parent());
    if (qualifiedTypeId) {
        typeName = qualifiedTypeId->name.toString();
        if (typeName == QLatin1String("Component"))
            m_idStack.push(StringSet());
    }

Thomas Hartmann's avatar
Thomas Hartmann committed
747
    m_typeStack.push(typeName);
748

749 750
    if (m_idStack.isEmpty())
        m_idStack.push(StringSet());
751

752
    return true;
753 754 755 756 757
}

void Check::endVisit(UiObjectInitializer *)
{
    m_propertyStack.pop();
758
    m_typeStack.pop();
759
    UiObjectDefinition *objectDenition = cast<UiObjectDefinition *>(parent());
760
    if (objectDenition && objectDenition->qualifiedTypeNameId->name == QLatin1String("Component"))
761 762
        m_idStack.pop();
    UiObjectBinding *objectBinding = cast<UiObjectBinding *>(parent());
763
    if (objectBinding && objectBinding->qualifiedTypeNameId->name == QLatin1String("Component"))
764
        m_idStack.pop();
765 766 767 768
}

void Check::checkProperty(UiQualifiedId *qualifiedId)
{
769
    const QString id = toString(qualifiedId);
Thomas Hartmann's avatar
Thomas Hartmann committed
770 771 772 773

    if (id.isEmpty())
        return;

774
    if (id.at(0).isLower()) {
775
        if (m_propertyStack.top().contains(id))
776
            addMessage(ErrPropertiesCanOnlyHaveOneBinding, fullLocationForQualifiedId(qualifiedId));
777 778 779 780
        m_propertyStack.top().insert(id);
    }
}

Christian Kamm's avatar
Christian Kamm committed
781 782
bool Check::visit(UiObjectDefinition *ast)
{
783
    visitQmlObject(ast, ast->qualifiedTypeNameId, ast->initializer);
Christian Kamm's avatar
Christian Kamm committed
784 785 786 787 788 789
    return false;
}

bool Check::visit(UiObjectBinding *ast)
{
    checkScopeObjectMember(ast->qualifiedId);
790
    if (!ast->hasOnToken) {
791
        checkProperty(ast->qualifiedId);
792 793 794
    } else {
        addMessage(ErrBehavioursNotSupportedInQmlUi, locationFromRange(ast->firstSourceLocation(), ast->lastSourceLocation()));
    }
Christian Kamm's avatar
Christian Kamm committed
795

796
    visitQmlObject(ast, ast->qualifiedTypeNameId, ast->initializer);
797 798 799
    return false;
}

800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836
static bool expressionAffectsVisualAspects(BinaryExpression *expression)
{
    if (expression->op == QSOperator::Assign
            || expression->op == QSOperator::InplaceSub
            || expression->op == QSOperator::InplaceAdd
            || expression->op == QSOperator::InplaceDiv
            || expression->op == QSOperator::InplaceMul
            || expression->op == QSOperator::InplaceOr
            || expression->op == QSOperator::InplaceXor
            || expression->op == QSOperator::InplaceAnd) {

        const ExpressionNode *lhsValue = expression->left;

        if (const IdentifierExpression* identifierExpression = cast<const IdentifierExpression *>(lhsValue)) {
            if (visualAspectsPropertyBlackList()->contains(identifierExpression->name.toString()))
                return true;
        } else if (const FieldMemberExpression* fieldMemberExpression = cast<const FieldMemberExpression *>(lhsValue)) {
            if (visualAspectsPropertyBlackList()->contains(fieldMemberExpression->name.toString()))
                return true;
        }
    }
    return false;
}

static UiQualifiedId *getRightMostIdentifier(UiQualifiedId *typeId)
{
        if (typeId->next)
            return getRightMostIdentifier(typeId->next);

        return typeId;
}

static bool checkTypeForDesignerSupport(UiQualifiedId *typeId)
{
    return unsupportedTypesByVisualDesigner()->contains(getRightMostIdentifier(typeId)->name.toString());
}

837 838 839 840 841
static bool checkTypeForQmlUiSupport(UiQualifiedId *typeId)
{
    return unsupportedTypesByQmlUi()->contains(getRightMostIdentifier(typeId)->name.toString());
}

842 843 844 845 846 847 848 849
static bool checkTopLevelBindingForParentReference(ExpressionStatement *expStmt, const QString &source)
{
    if (!expStmt)
        return false;

    SourceLocation location = locationFromRange(expStmt->firstSourceLocation(), expStmt->lastSourceLocation());
    QString stmtSource = source.mid(location.begin(), location.length);

850
    if (stmtSource.contains(QRegExp(QLatin1String("(^|\\W)parent\\."))))
851 852 853 854 855
        return true;

    return false;
}

856 857
void Check::visitQmlObject(Node *ast, UiQualifiedId *typeId,
                           UiObjectInitializer *initializer)
858
{
859 860 861
    // Don't do type checks if it's a grouped property binding.
    // For instance: anchors { ... }
    if (_doc->bind()->isGroupedPropertyBinding(ast)) {
862 863 864 865 866
        checkScopeObjectMember(typeId);
        // ### don't give up!
        return;
    }

867 868
    const SourceLocation typeErrorLocation = fullLocationForQualifiedId(typeId);

869 870
    const QString typeName = getRightMostIdentifier(typeId)->name.toString();

871
    if (!m_typeStack.isEmpty() && m_typeStack.last() == QLatin1String("State")
872 873
            && typeId->name.toString() != "AnchorChanges"
            && typeId->name.toString() != "ParentChange"
874 875
            && typeId->name.toString() != "PropertyChanges"
            && typeId->name.toString() != "StateChangeScript")
876 877
        addMessage(StateCannotHaveChildItem, typeErrorLocation, typeName);

878
    if (checkTypeForDesignerSupport(typeId))
879 880 881 882
        addMessage(WarnUnsupportedTypeInVisualDesigner, typeErrorLocation, typeName);

    if (checkTypeForQmlUiSupport(typeId))
        addMessage(ErrUnsupportedTypeInQmlUi, typeErrorLocation, typeName);
883

884
    if (m_typeStack.count() > 1 && getRightMostIdentifier(typeId)->name.toString() == QLatin1String("State")) {
885
        addMessage(WarnStatesOnlyInRootItemForVisualDesigner, typeErrorLocation);
886 887
        addMessage(ErrStatesOnlyInRootItemInQmlUi, typeErrorLocation);
    }
888

889 890 891 892 893
    if (m_typeStack.isEmpty()
            && unsupportedRootObjectTypesByVisualDesigner()->contains(typeName))
        addMessage(ErrUnsupportedRootTypeInVisualDesigner,
                   locationFromRange(ast->firstSourceLocation(), ast->lastSourceLocation()), typeName);

894 895 896 897 898
    if (m_typeStack.isEmpty()
            && unsupportedRootObjectTypesByQmlUi()->contains(typeName))
        addMessage(ErrUnsupportedRootTypeInQmlUi,
                   locationFromRange(ast->firstSourceLocation(), ast->lastSourceLocation()), typeName);

899
    bool typeError = false;
900 901 902
    if (_importsOk) {
        const ObjectValue *prototype = _context->lookupType(_doc.data(), typeId);
        if (!prototype) {
903
            typeError = true;
904 905 906 907 908 909 910
            addMessage(ErrUnknownComponent, typeErrorLocation);
        } else {
            PrototypeIterator iter(prototype, _context);
            QList<const ObjectValue *> prototypes = iter.all();
            if (iter.error() != PrototypeIterator::NoError)
                typeError = true;
            const ObjectValue *lastPrototype = prototypes.last();
911 912 913 914 915 916 917
            foreach (const ObjectValue *objectValue, prototypes) {
                if (objectValue->className() == QLatin1String("QGraphicsObject")
                        && _isQtQuick2) {
                    addMessage(WarnAboutQtQuick1InsteadQtQuick2, typeErrorLocation);
                }
            }

918 919
            if (iter.error() == PrototypeIterator::ReferenceResolutionError) {
                if (const QmlPrototypeReference *ref =
Christian Kamm's avatar
Christian Kamm committed
920
                        value_cast<QmlPrototypeReference>(lastPrototype->prototype())) {
921 922 923 924 925 926 927 928
                    addMessage(ErrCouldNotResolvePrototypeOf, typeErrorLocation,
                               toString(ref->qmlTypeName()), lastPrototype->className());
                } else {
                    addMessage(ErrCouldNotResolvePrototype, typeErrorLocation,
                               lastPrototype->className());
                }
            } else if (iter.error() == PrototypeIterator::CycleError) {
                addMessage(ErrPrototypeCycle, typeErrorLocation,
929
                           lastPrototype->className());
930 931 932 933 934 935 936
            }
        }
    }

    _scopeBuilder.push(ast);

    if (typeError) {
937 938 939
        // suppress subsequent errors about scope object lookup by clearing
        // the scope object list
        // ### todo: better way?
940
        _scopeChain.setQmlScopeObjects(QList<const ObjectValue *>());
941 942
    }

943
    Node::accept(initializer, this);
Christian Kamm's avatar
Christian Kamm committed
944

945
    _scopeBuilder.pop();
Christian Kamm's avatar
Christian Kamm committed
946 947 948 949
}

bool Check::visit(UiScriptBinding *ast)
{
950
    // special case for id property
951
    if (ast->qualifiedId->name == QLatin1String("id") && ! ast->qualifiedId->next) {
952 953 954 955 956 957 958 959
        if (! ast->statement)
            return false;

        const SourceLocation loc = locationFromRange(ast->statement->firstSourceLocation(),
                                                     ast->statement->lastSourceLocation());

        ExpressionStatement *expStmt = cast<ExpressionStatement *>(ast->statement);
        if (!expStmt) {
960
            addMessage(ErrIdExpected, loc);
961 962 963
            return false;
        }

964 965
        QString id;
        if (IdentifierExpression *idExp = cast<IdentifierExpression *>(expStmt->expression)) {
966
            id = idExp->name.toString();
967
        } else if (StringLiteral *strExp = cast<StringLiteral *>(expStmt->expression)) {
968
            id = strExp->value.toString();
969
            addMessage(ErrInvalidId, loc);
970
        } else {
971
            addMessage(ErrIdExpected, loc);
972 973 974
            return false;
        }

975
        if (id.isEmpty() || (!id.at(0).isLower() && id.at(0) != QLatin1Char('_'))) {
976
            addMessage(ErrInvalidId, loc);
977 978
            return false;
        }
979

980 981 982 983
        if (idsThatShouldNotBeUsedInDesigner->contains(id)) {
            addMessage(ErrInvalidIdeInVisualDesigner, loc);
        }

984
        if (m_idStack.top().contains(id)) {
985
            addMessage(ErrDuplicateId, loc);
986 987
            return false;
        }
988
        m_idStack.top().insert(id);
989 990
    }

991 992 993 994 995
    if (m_typeStack.count() == 1
            && visualAspectsPropertyBlackList()->contains(ast->qualifiedId->name.toString())
            && checkTopLevelBindingForParentReference(cast<ExpressionStatement *>(ast->statement), _doc->source())) {
        addMessage(WarnReferenceToParentItemNotSupportedByVisualDesigner,
                   locationFromRange(ast->firstSourceLocation(), ast->lastSourceLocation()));