qmljscheck.cpp 34.8 KB
Newer Older
Christian Kamm's avatar
Christian Kamm committed
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).
Christian Kamm's avatar
Christian Kamm committed
6
**
hjk's avatar
hjk committed
7
** Contact: Nokia Corporation (info@qt.nokia.com)
Christian Kamm's avatar
Christian Kamm committed
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.
Christian Kamm's avatar
Christian Kamm committed
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.
Christian Kamm's avatar
Christian Kamm committed
30
31
32
33
34
**
**************************************************************************/

#include "qmljscheck.h"
#include "qmljsbind.h"
35
#include "qmljscontext.h"
36
#include "qmljsevaluate.h"
Christian Kamm's avatar
Christian Kamm committed
37
38
39
#include "parser/qmljsast_p.h"

#include <QtCore/QDebug>
40
#include <QtCore/QDir>
41
#include <QtGui/QColor>
42
#include <QtGui/QApplication>
Christian Kamm's avatar
Christian Kamm committed
43
44
45
46

using namespace QmlJS;
using namespace QmlJS::AST;

47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
QColor QmlJS::toQColor(const QString &qmlColorString)
{
    QColor color;
    if (qmlColorString.size() == 9 && qmlColorString.at(0) == QLatin1Char('#')) {
        bool ok;
        const int alpha = qmlColorString.mid(1, 2).toInt(&ok, 16);
        if (ok) {
            QString name(qmlColorString.at(0));
            name.append(qmlColorString.right(6));
            if (QColor::isValidColor(name)) {
                color.setNamedColor(name);
                color.setAlpha(alpha);
            }
        }
    } else {
        if (QColor::isValidColor(qmlColorString))
            color.setNamedColor(qmlColorString);
    }
    return color;
}
67

68
69
70
71
72
73
74
75
76
SourceLocation QmlJS::locationFromRange(const SourceLocation &start,
                                        const SourceLocation &end)
{
    return SourceLocation(start.offset,
                          end.end() - start.begin(),
                          start.startLine,
                          start.startColumn);
}

77
78
79
80
81
82
83
84
85
86
87
88
89
90
SourceLocation QmlJS::fullLocationForQualifiedId(AST::UiQualifiedId *qualifiedId)
{
    SourceLocation start = qualifiedId->identifierToken;
    SourceLocation end = qualifiedId->identifierToken;

    for (UiQualifiedId *iter = qualifiedId; iter; iter = iter->next) {
        if (iter->name)
            end = iter->identifierToken;
    }

    return locationFromRange(start, end);
}


91
92
93
94
95
DiagnosticMessage QmlJS::errorMessage(const AST::SourceLocation &loc, const QString &message)
{
    return DiagnosticMessage(DiagnosticMessage::Error, loc, message);
}

96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
namespace {
class SharedData
{
public:
    SharedData()
    {
        validBuiltinPropertyNames.insert(QLatin1String("action"));
        validBuiltinPropertyNames.insert(QLatin1String("bool"));
        validBuiltinPropertyNames.insert(QLatin1String("color"));
        validBuiltinPropertyNames.insert(QLatin1String("date"));
        validBuiltinPropertyNames.insert(QLatin1String("double"));
        validBuiltinPropertyNames.insert(QLatin1String("enumeration"));
        validBuiltinPropertyNames.insert(QLatin1String("font"));
        validBuiltinPropertyNames.insert(QLatin1String("int"));
        validBuiltinPropertyNames.insert(QLatin1String("list"));
        validBuiltinPropertyNames.insert(QLatin1String("point"));
        validBuiltinPropertyNames.insert(QLatin1String("real"));
        validBuiltinPropertyNames.insert(QLatin1String("rect"));
        validBuiltinPropertyNames.insert(QLatin1String("size"));
        validBuiltinPropertyNames.insert(QLatin1String("string"));
        validBuiltinPropertyNames.insert(QLatin1String("time"));
        validBuiltinPropertyNames.insert(QLatin1String("url"));
        validBuiltinPropertyNames.insert(QLatin1String("variant"));
        validBuiltinPropertyNames.insert(QLatin1String("vector3d"));
120
        validBuiltinPropertyNames.insert(QLatin1String("alias"));
121
122
123
124
125
126
127
128
129
130
131
132
    }

    QSet<QString> validBuiltinPropertyNames;
};
} // anonymous namespace
Q_GLOBAL_STATIC(SharedData, sharedData)

bool QmlJS::isValidBuiltinPropertyType(const QString &name)
{
    return sharedData()->validBuiltinPropertyNames.contains(name);
}

133
134
135
136
137
138
namespace {

class AssignmentCheck : public ValueVisitor
{
public:
    DiagnosticMessage operator()(
139
            const Document::Ptr &document,
140
            const SourceLocation &location,
141
142
            const Value *lhsValue,
            const Value *rhsValue,
Christian Kamm's avatar
Christian Kamm committed
143
            Node *ast)
144
    {
145
        _doc = document;
146
147
        _message = DiagnosticMessage(DiagnosticMessage::Error, location, QString());
        _rhsValue = rhsValue;
Christian Kamm's avatar
Christian Kamm committed
148
149
150
151
        if (ExpressionStatement *expStmt = cast<ExpressionStatement *>(ast))
            _ast = expStmt->expression;
        else
            _ast = ast->expressionCast();
152
153
154
155
156
157
158

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

        return _message;
    }

159
    virtual void visit(const NumberValue *value)
160
    {
161
162
163
164
165
        if (const QmlEnumValue *enumValue = dynamic_cast<const QmlEnumValue *>(value)) {
            if (StringLiteral *stringLiteral = cast<StringLiteral *>(_ast)) {
                const QString valueName = stringLiteral->value->asString();

                if (!enumValue->keys().contains(valueName)) {
166
                    _message.message = Check::tr("unknown value for enum");
167
                }
168
169
            } else if (! _rhsValue->asStringValue() && ! _rhsValue->asNumberValue()
                       && ! _rhsValue->asUndefinedValue()) {
170
                _message.message = Check::tr("enum value is not a string or number");
171
172
            }
        } else {
Christian Kamm's avatar
Christian Kamm committed
173
174
            if (cast<TrueLiteral *>(_ast)
                    || cast<FalseLiteral *>(_ast)) {
175
                _message.message = Check::tr("numerical value expected");
176
            }
177
178
179
180
181
182
183
184
185
186
        }
    }

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

        if (cast<StringLiteral *>(_ast)
                || cast<NumericLiteral *>(_ast)
                || (unaryMinus && cast<NumericLiteral *>(unaryMinus->expression))) {
187
            _message.message = Check::tr("boolean value expected");
188
189
190
        }
    }

191
    virtual void visit(const StringValue *value)
192
193
194
195
196
    {
        UnaryMinusExpression *unaryMinus = cast<UnaryMinusExpression *>(_ast);

        if (cast<NumericLiteral *>(_ast)
                || (unaryMinus && cast<NumericLiteral *>(unaryMinus->expression))
Christian Kamm's avatar
Christian Kamm committed
197
198
                || cast<TrueLiteral *>(_ast)
                || cast<FalseLiteral *>(_ast)) {
199
            _message.message = Check::tr("string value expected");
200
        }
201
202
203
204
205
206
207
208
209

        if (value && value->asUrlValue()) {
            if (StringLiteral *literal = cast<StringLiteral *>(_ast)) {
                QUrl url(literal->value->asString());
                if (!url.isValid() && !url.isEmpty()) {
                    _message.message = Check::tr("not a valid url");
                } else {
                    QString fileName = url.toLocalFile();
                    if (!fileName.isEmpty()) {
210
                        if (QFileInfo(fileName).isRelative()) {
211
212
213
                            fileName.prepend(QDir::separator());
                            fileName.prepend(_doc->path());
                        }
214
                        if (!QFileInfo(fileName).exists()) {
215
                            _message.message = Check::tr("file or directory does not exist");
216
217
                            _message.kind = DiagnosticMessage::Warning;
                        }
218
219
220
221
                    }
                }
            }
        }
222
223
224
225
226
    }

    virtual void visit(const ColorValue *)
    {
        if (StringLiteral *stringLiteral = cast<StringLiteral *>(_ast)) {
227
            if (!toQColor(stringLiteral->value->asString()).isValid())
228
                _message.message = Check::tr("not a valid color");
229
230
231
232
233
234
235
236
        } else {
            visit((StringValue *)0);
        }
    }

    virtual void visit(const AnchorLineValue *)
    {
        if (! (_rhsValue->asAnchorLineValue() || _rhsValue->asUndefinedValue()))
237
            _message.message = Check::tr("expected anchor line");
238
239
    }

240
    Document::Ptr _doc;
241
242
243
244
245
    DiagnosticMessage _message;
    const Value *_rhsValue;
    ExpressionNode *_ast;
};

246
247
248
249
250
class FunctionBodyCheck : protected Visitor
{
public:
    QList<DiagnosticMessage> operator()(FunctionExpression *function, Check::Options options)
    {
251
        clear();
252
253
254
255
256
257
258
259
260
261
        _options = options;
        for (FormalParameterList *plist = function->formals; plist; plist = plist->next) {
            if (plist->name)
                _formalParameterNames += plist->name->asString();
        }

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

262
263
264
265
266
267
268
269
    QList<DiagnosticMessage> operator()(StatementList *statements, Check::Options options)
    {
        clear();
        _options = options;
        Node::accept(statements, this);
        return _messages;
    }

270
protected:
271
272
273
274
275
276
277
278
279
280
    void clear()
    {
        _messages.clear();
        _declaredFunctions.clear();
        _declaredVariables.clear();
        _possiblyUndeclaredUses.clear();
        _seenNonDeclarationStatement = false;
        _formalParameterNames.clear();
    }

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
316
317
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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
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
    void postVisit(Node *ast)
    {
        if (!_seenNonDeclarationStatement && ast->statementCast()
                && !cast<VariableStatement *>(ast)) {
            _seenNonDeclarationStatement = true;
        }
    }

    bool visit(IdentifierExpression *ast)
    {
        if (!ast->name)
            return false;
        const QString name = ast->name->asString();
        if (!_declaredFunctions.contains(name) && !_declaredVariables.contains(name))
            _possiblyUndeclaredUses[name].append(ast->identifierToken);
        return false;
    }

    bool visit(VariableStatement *ast)
    {
        if (_options & Check::WarnDeclarationsNotStartOfFunction && _seenNonDeclarationStatement) {
            warning(ast->declarationKindToken, Check::tr("declarations should be at the start of a function"));
        }
        return true;
    }

    bool visit(VariableDeclaration *ast)
    {
        if (!ast->name)
            return true;
        const QString name = ast->name->asString();

        if (_formalParameterNames.contains(name)) {
            if (_options & Check::WarnDuplicateDeclaration)
                warning(ast->identifierToken, Check::tr("already a formal parameter"));
            return true;
        }
        if (_declaredFunctions.contains(name)) {
            if (_options & Check::WarnDuplicateDeclaration)
                warning(ast->identifierToken, Check::tr("already declared as function"));
            return true;
        }
        if (_declaredVariables.contains(name)) {
            if (_options & Check::WarnDuplicateDeclaration)
                warning(ast->identifierToken, Check::tr("duplicate declaration"));
            return true;
        }

        if (_possiblyUndeclaredUses.contains(name)) {
            if (_options & Check::WarnUseBeforeDeclaration) {
                foreach (const SourceLocation &loc, _possiblyUndeclaredUses.value(name)) {
                    warning(loc, Check::tr("variable is used before being declared"));
                }
            }
            _possiblyUndeclaredUses.remove(name);
        }
        _declaredVariables[name] = ast;

        return true;
    }

    bool visit(FunctionDeclaration *ast)
    {
        if (_options & Check::WarnDeclarationsNotStartOfFunction &&_seenNonDeclarationStatement) {
            warning(ast->functionToken, Check::tr("declarations should be at the start of a function"));
        }

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

    bool visit(FunctionExpression *ast)
    {
        if (!ast->name)
            return false;
        const QString name = ast->name->asString();

        if (_formalParameterNames.contains(name)) {
            if (_options & Check::WarnDuplicateDeclaration)
                warning(ast->identifierToken, Check::tr("already a formal parameter"));
            return false;
        }
        if (_declaredVariables.contains(name)) {
            if (_options & Check::WarnDuplicateDeclaration)
                warning(ast->identifierToken, Check::tr("already declared as var"));
            return false;
        }
        if (_declaredFunctions.contains(name)) {
            if (_options & Check::WarnDuplicateDeclaration)
                warning(ast->identifierToken, Check::tr("duplicate declaration"));
            return false;
        }

        if (FunctionDeclaration *decl = cast<FunctionDeclaration *>(ast)) {
            if (_possiblyUndeclaredUses.contains(name)) {
                if (_options & Check::WarnUseBeforeDeclaration) {
                    foreach (const SourceLocation &loc, _possiblyUndeclaredUses.value(name)) {
                        warning(loc, Check::tr("function is used before being declared"));
                    }
                }
                _possiblyUndeclaredUses.remove(name);
            }
            _declaredFunctions[name] = decl;
        }

        return false;
    }

private:
    void warning(const SourceLocation &loc, const QString &message)
    {
        _messages.append(DiagnosticMessage(DiagnosticMessage::Warning, loc, message));
    }

    Check::Options _options;
    QList<DiagnosticMessage> _messages;
    QStringList _formalParameterNames;
    QHash<QString, VariableDeclaration *> _declaredVariables;
    QHash<QString, FunctionDeclaration *> _declaredFunctions;
    QHash<QString, QList<SourceLocation> > _possiblyUndeclaredUses;
    bool _seenNonDeclarationStatement;
};

403
404
405
} // end of anonymous namespace


Christian Kamm's avatar
Christian Kamm committed
406
Check::Check(Document::Ptr doc, const ContextPtr &context)
Christian Kamm's avatar
Christian Kamm committed
407
    : _doc(doc)
Christian Kamm's avatar
Christian Kamm committed
408
409
    , _context(context)
    , _scopeChain(doc, _context)
410
    , _scopeBuilder(&_scopeChain)
411
    , _options(WarnDangerousNonStrictEqualityChecks | WarnBlocks | WarnWith
412
413
414
415
               | WarnVoid | WarnCommaExpression | WarnExpressionStatement
               | WarnAssignInCondition | WarnUseBeforeDeclaration | WarnDuplicateDeclaration
               | WarnCaseWithoutFlowControlEnd | WarnNonCapitalizedNew
               | WarnCallsOfCapitalizedFunctions | ErrCheckTypeErrors)
416
    , _lastValue(0)
Christian Kamm's avatar
Christian Kamm committed
417
418
419
420
421
422
423
424
425
426
427
428
429
430
{
}

Check::~Check()
{
}

QList<DiagnosticMessage> Check::operator()()
{
    _messages.clear();
    Node::accept(_doc->ast(), this);
    return _messages;
}

431
432
433
434
435
436
437
438
439
440
441
bool Check::preVisit(Node *ast)
{
    _chain.append(ast);
    return true;
}

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

442
bool Check::visit(UiProgram *)
Christian Kamm's avatar
Christian Kamm committed
443
444
445
446
{
    return true;
}

447
448
bool Check::visit(UiObjectInitializer *)
{
449
450
451
452
453
454
455
456
457
458
    m_propertyStack.push(StringSet());
    UiObjectDefinition *objectDefinition = cast<UiObjectDefinition *>(parent());
    if (objectDefinition && objectDefinition->qualifiedTypeNameId->name->asString() == "Component")
        m_idStack.push(StringSet());
    UiObjectBinding *objectBinding = cast<UiObjectBinding *>(parent());
    if (objectBinding && objectBinding->qualifiedTypeNameId->name->asString() == "Component")
        m_idStack.push(StringSet());
    if (m_idStack.isEmpty())
        m_idStack.push(StringSet());
    return true;
459
460
461
462
463
}

void Check::endVisit(UiObjectInitializer *)
{
    m_propertyStack.pop();
464
465
466
467
468
469
    UiObjectDefinition *objectDenition = cast<UiObjectDefinition *>(parent());
    if (objectDenition && objectDenition->qualifiedTypeNameId->name->asString() == "Component")
        m_idStack.pop();
    UiObjectBinding *objectBinding = cast<UiObjectBinding *>(parent());
    if (objectBinding && objectBinding->qualifiedTypeNameId->name->asString() == "Component")
        m_idStack.pop();
470
471
472
473
474
475
476
477
478
479
480
481
482
483
}

void Check::checkProperty(UiQualifiedId *qualifiedId)
{
    const QString id = Bind::toString(qualifiedId);
    if (id.at(0).isLower()) {
        if (m_propertyStack.top().contains(id)) {
            error(fullLocationForQualifiedId(qualifiedId),
                  Check::tr("properties can only be assigned once"));
        }
        m_propertyStack.top().insert(id);
    }
}

Christian Kamm's avatar
Christian Kamm committed
484
485
bool Check::visit(UiObjectDefinition *ast)
{
486
    visitQmlObject(ast, ast->qualifiedTypeNameId, ast->initializer);
Christian Kamm's avatar
Christian Kamm committed
487
488
489
490
491
492
    return false;
}

bool Check::visit(UiObjectBinding *ast)
{
    checkScopeObjectMember(ast->qualifiedId);
493
494
    if (!ast->hasOnToken)
        checkProperty(ast->qualifiedId);
Christian Kamm's avatar
Christian Kamm committed
495

496
    visitQmlObject(ast, ast->qualifiedTypeNameId, ast->initializer);
497
498
499
    return false;
}

500
501
void Check::visitQmlObject(Node *ast, UiQualifiedId *typeId,
                           UiObjectInitializer *initializer)
502
{
503
504
505
    // Don't do type checks if it's a grouped property binding.
    // For instance: anchors { ... }
    if (_doc->bind()->isGroupedPropertyBinding(ast)) {
506
507
508
509
510
        checkScopeObjectMember(typeId);
        // ### don't give up!
        return;
    }

511
    bool typeError = false;
512
    const SourceLocation typeErrorLocation = fullLocationForQualifiedId(typeId);
Christian Kamm's avatar
Christian Kamm committed
513
    const ObjectValue *prototype = _context->lookupType(_doc.data(), typeId);
514
515
    if (!prototype) {
        typeError = true;
516
        if (_options & ErrCheckTypeErrors)
517
            error(typeErrorLocation,
518
                  Check::tr("unknown type"));
519
    } else {
Christian Kamm's avatar
Christian Kamm committed
520
        PrototypeIterator iter(prototype, _context);
521
522
523
524
525
526
527
528
        QList<const ObjectValue *> prototypes = iter.all();
        if (iter.error() != PrototypeIterator::NoError)
            typeError = true;
        if (_options & ErrCheckTypeErrors) {
            const ObjectValue *lastPrototype = prototypes.last();
            if (iter.error() == PrototypeIterator::ReferenceResolutionError) {
                if (const QmlPrototypeReference *ref =
                        dynamic_cast<const QmlPrototypeReference *>(lastPrototype->prototype())) {
529
                    error(typeErrorLocation,
530
531
532
                          Check::tr("could not resolve the prototype %1 of %2").arg(
                              Bind::toString(ref->qmlTypeName()), lastPrototype->className()));
                } else {
533
                    error(typeErrorLocation,
534
535
536
537
                          Check::tr("could not resolve the prototype of %1").arg(
                              lastPrototype->className()));
                }
            } else if (iter.error() == PrototypeIterator::CycleError) {
538
                error(typeErrorLocation,
539
540
541
542
543
544
545
546
547
                      Check::tr("prototype cycle, the last non-repeated object is %1").arg(
                          lastPrototype->className()));
            }
        }
    }

    _scopeBuilder.push(ast);

    if (typeError) {
548
549
550
        // suppress subsequent errors about scope object lookup by clearing
        // the scope object list
        // ### todo: better way?
551
        _scopeChain.setQmlScopeObjects(QList<const ObjectValue *>());
552
553
    }

554
    Node::accept(initializer, this);
Christian Kamm's avatar
Christian Kamm committed
555

556
    _scopeBuilder.pop();
Christian Kamm's avatar
Christian Kamm committed
557
558
559
560
}

bool Check::visit(UiScriptBinding *ast)
{
561
562
563
564
565
566
567
568
569
570
    // special case for id property
    if (ast->qualifiedId->name->asString() == QLatin1String("id") && ! ast->qualifiedId->next) {
        if (! ast->statement)
            return false;

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

        ExpressionStatement *expStmt = cast<ExpressionStatement *>(ast->statement);
        if (!expStmt) {
571
            error(loc, Check::tr("expected id"));
572
573
574
            return false;
        }

575
576
577
578
579
        QString id;
        if (IdentifierExpression *idExp = cast<IdentifierExpression *>(expStmt->expression)) {
            id = idExp->name->asString();
        } else if (StringLiteral *strExp = cast<StringLiteral *>(expStmt->expression)) {
            id = strExp->value->asString();
580
            warning(loc, Check::tr("using string literals for ids is discouraged"));
581
        } else {
582
            error(loc, Check::tr("expected id"));
583
584
585
            return false;
        }

586
587
        if (id.isEmpty() || (!id[0].isLower() && id[0] != '_')) {
            error(loc, Check::tr("ids must be lower case or start with underscore"));
588
589
            return false;
        }
590

591
        if (m_idStack.top().contains(id)) {
592
593
594
            error(loc, Check::tr("ids must be unique"));
            return false;
        }
595
        m_idStack.top().insert(id);
596
597
    }

598
599
    checkProperty(ast->qualifiedId);

Christian Kamm's avatar
Christian Kamm committed
600
601
602
    if (!ast->statement)
        return false;

603
604
    const Value *lhsValue = checkScopeObjectMember(ast->qualifiedId);
    if (lhsValue) {
Christian Kamm's avatar
Christian Kamm committed
605
606
        Evaluate evaluator(&_scopeChain);
        const Value *rhsValue = evaluator(ast->statement);
607

Christian Kamm's avatar
Christian Kamm committed
608
609
610
611
612
613
        const SourceLocation loc = locationFromRange(ast->statement->firstSourceLocation(),
                                                     ast->statement->lastSourceLocation());
        AssignmentCheck assignmentCheck;
        DiagnosticMessage message = assignmentCheck(_doc, loc, lhsValue, rhsValue, ast->statement);
        if (! message.message.isEmpty())
            _messages += message;
614
    }
Christian Kamm's avatar
Christian Kamm committed
615

616
617
618
    if (Block *block = cast<Block *>(ast->statement)) {
        FunctionBodyCheck bodyCheck;
        _messages.append(bodyCheck(block->statements, _options));
619
620
621
622
623
        Node::accept(ast->qualifiedId, this);
        _scopeBuilder.push(ast);
        Node::accept(block->statements, this);
        _scopeBuilder.pop();
        return false;
624
625
    }

Christian Kamm's avatar
Christian Kamm committed
626
627
628
629
630
631
    return true;
}

bool Check::visit(UiArrayBinding *ast)
{
    checkScopeObjectMember(ast->qualifiedId);
632
    checkProperty(ast->qualifiedId);
Christian Kamm's avatar
Christian Kamm committed
633
634
635
636

    return true;
}

637
638
639
640
641
642
643
644
645
646
647
648
649
bool Check::visit(UiPublicMember *ast)
{
    // check if the member type is valid
    if (ast->memberType) {
        const QString name = ast->memberType->asString();
        if (!name.isEmpty() && name.at(0).isLower()) {
            if (!isValidBuiltinPropertyType(name))
                error(ast->typeToken, tr("'%1' is not a valid property type").arg(name));
        }
    }
    return true;
}

650
651
652
653
654
655
656
bool Check::visit(IdentifierExpression *ast)
{
    // currently disabled: too many false negatives
    return true;

    _lastValue = 0;
    if (ast->name) {
657
        Evaluate evaluator(&_scopeChain);
658
659
660
661
        _lastValue = evaluator.reference(ast);
        if (!_lastValue)
            error(ast->identifierToken, tr("unknown identifier"));
        if (const Reference *ref = value_cast<const Reference *>(_lastValue)) {
Christian Kamm's avatar
Christian Kamm committed
662
            _lastValue = _context->lookupReference(ref);
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
            if (!_lastValue)
                error(ast->identifierToken, tr("could not resolve"));
        }
    }
    return false;
}

bool Check::visit(FieldMemberExpression *ast)
{
    // currently disabled: too many false negatives
    return true;

    Node::accept(ast->base, this);
    if (!_lastValue)
        return false;
    const ObjectValue *obj = _lastValue->asObjectValue();
    if (!obj) {
        error(locationFromRange(ast->base->firstSourceLocation(), ast->base->lastSourceLocation()),
              tr("does not have members"));
    }
    if (!obj || !ast->name) {
        _lastValue = 0;
        return false;
    }
Christian Kamm's avatar
Christian Kamm committed
687
    _lastValue = obj->lookupMember(ast->name->asString(), _context);
688
689
690
691
692
693
694
695
696
697
698
699
    if (!_lastValue)
        error(ast->identifierToken, tr("unknown member"));
    return false;
}

bool Check::visit(FunctionDeclaration *ast)
{
    return visit(static_cast<FunctionExpression *>(ast));
}

bool Check::visit(FunctionExpression *ast)
{
700
701
702
    FunctionBodyCheck bodyCheck;
    _messages.append(bodyCheck(ast, _options));

703
704
705
706
707
708
709
    Node::accept(ast->formals, this);
    _scopeBuilder.push(ast);
    Node::accept(ast->body, this);
    _scopeBuilder.pop();
    return false;
}

710
static bool shouldAvoidNonStrictEqualityCheck(ExpressionNode *exp, const Value *other)
711
712
{
    if (NumericLiteral *literal = cast<NumericLiteral *>(exp)) {
713
        if (literal->value == 0 && !other->asNumberValue())
714
            return true;
715
716
717
    } else if ((cast<TrueLiteral *>(exp) || cast<FalseLiteral *>(exp)) && !other->asBooleanValue()) {
        return true;
    } else if (cast<NullExpression *>(exp)) {
718
719
720
721
722
        return true;
    } else if (IdentifierExpression *ident = cast<IdentifierExpression *>(exp)) {
        if (ident->name && ident->name->asString() == QLatin1String("undefined"))
            return true;
    } else if (StringLiteral *literal = cast<StringLiteral *>(exp)) {
723
        if ((!literal->value || literal->value->asString().isEmpty()) && !other->asStringValue())
724
725
726
727
728
729
730
731
            return true;
    }
    return false;
}

bool Check::visit(BinaryExpression *ast)
{
    if (ast->op == QSOperator::Equal || ast->op == QSOperator::NotEqual) {
732
733
        bool warn = _options & WarnAllNonStrictEqualityChecks;
        if (!warn && _options & WarnDangerousNonStrictEqualityChecks) {
734
            Evaluate eval(&_scopeChain);
735
736
737
738
739
740
            const Value *lhs = eval(ast->left);
            const Value *rhs = eval(ast->right);
            warn = shouldAvoidNonStrictEqualityCheck(ast->left, rhs)
                    || shouldAvoidNonStrictEqualityCheck(ast->right, lhs);
        }
        if (warn) {
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
            warning(ast->operatorToken, tr("== and != perform type coercion, use === or !== instead to avoid"));
        }
    }
    return true;
}

bool Check::visit(Block *ast)
{
    if (Node *p = parent()) {
        if (_options & WarnBlocks
                && !cast<UiScriptBinding *>(p)
                && !cast<TryStatement *>(p)
                && !cast<Catch *>(p)
                && !cast<Finally *>(p)
                && !cast<ForStatement *>(p)
                && !cast<ForEachStatement *>(p)
757
758
                && !cast<LocalForStatement *>(p)
                && !cast<LocalForEachStatement *>(p)
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
                && !cast<DoWhileStatement *>(p)
                && !cast<WhileStatement *>(p)
                && !cast<IfStatement *>(p)
                && !cast<SwitchStatement *>(p)
                && !cast<WithStatement *>(p)) {
            warning(ast->lbraceToken, tr("blocks do not introduce a new scope, avoid"));
        }
    }
    return true;
}

bool Check::visit(WithStatement *ast)
{
    if (_options & WarnWith)
        warning(ast->withToken, tr("use of the with statement is not recommended, use a var instead"));
    return true;
}

bool Check::visit(VoidExpression *ast)
{
    if (_options & WarnVoid)
        warning(ast->voidToken, tr("use of void is usually confusing and not recommended"));
    return true;
}

bool Check::visit(Expression *ast)
{
    if (_options & WarnCommaExpression && ast->left && ast->right) {
787
788
789
        Node *p = parent();
        if (!cast<ForStatement *>(p)
                && !cast<LocalForStatement *>(p)) {
790
            warning(ast->commaToken, tr("avoid comma expressions"));
791
        }
792
793
794
795
796
797
798
799
800
801
802
803
    }
    return true;
}

bool Check::visit(ExpressionStatement *ast)
{
    if (_options & WarnExpressionStatement && ast->expression) {
        bool ok = cast<CallExpression *>(ast->expression)
                || cast<DeleteExpression *>(ast->expression)
                || cast<PreDecrementExpression *>(ast->expression)
                || cast<PreIncrementExpression *>(ast->expression)
                || cast<PostIncrementExpression *>(ast->expression)
804
805
                || cast<PostDecrementExpression *>(ast->expression)
                || cast<FunctionExpression *>(ast->expression);
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
        if (BinaryExpression *binary = cast<BinaryExpression *>(ast->expression)) {
            switch (binary->op) {
            case QSOperator::Assign:
            case QSOperator::InplaceAdd:
            case QSOperator::InplaceAnd:
            case QSOperator::InplaceDiv:
            case QSOperator::InplaceLeftShift:
            case QSOperator::InplaceRightShift:
            case QSOperator::InplaceMod:
            case QSOperator::InplaceMul:
            case QSOperator::InplaceOr:
            case QSOperator::InplaceSub:
            case QSOperator::InplaceURightShift:
            case QSOperator::InplaceXor:
                ok = true;
            default: break;
            }
        }
824
825
826
827
828
829
830
831
        if (!ok) {
            for (int i = 0; Node *p = parent(i); ++i) {
                if (UiScriptBinding *binding = cast<UiScriptBinding *>(p)) {
                    if (!cast<Block *>(binding->statement)) {
                        ok = true;
                        break;
                    }
                }
832
833
834
835
836
837
                if (UiPublicMember *member = cast<UiPublicMember *>(p)) {
                    if (!cast<Block *>(member->statement)) {
                        ok = true;
                        break;
                    }
                }
838
839
            }
        }
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862

        if (!ok) {
            warning(locationFromRange(ast->firstSourceLocation(), ast->lastSourceLocation()),
                    tr("expression statements should be assignments, calls or delete expressions only"));
        }
    }
    return true;
}

bool Check::visit(IfStatement *ast)
{
    if (ast->expression)
        checkAssignInCondition(ast->expression);
    return true;
}

bool Check::visit(ForStatement *ast)
{
    if (ast->condition)
        checkAssignInCondition(ast->condition);
    return true;
}

863
864
865
866
867
868
869
bool Check::visit(LocalForStatement *ast)
{
    if (ast->condition)
        checkAssignInCondition(ast->condition);
    return true;
}

870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
bool Check::visit(WhileStatement *ast)
{
    if (ast->expression)
        checkAssignInCondition(ast->expression);
    return true;
}

bool Check::visit(DoWhileStatement *ast)
{
    if (ast->expression)
        checkAssignInCondition(ast->expression);
    return true;
}

bool Check::visit(CaseClause *ast)
{
    checkEndsWithControlFlow(ast->statements, ast->caseToken);
    return true;
}

bool Check::visit(DefaultClause *ast)
{
    checkEndsWithControlFlow(ast->statements, ast->defaultToken);
    return true;
}

896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
static QString functionName(ExpressionNode *ast, SourceLocation *location)
{
    if (IdentifierExpression *id = cast<IdentifierExpression *>(ast)) {
        if (id->name) {
            *location = id->identifierToken;
            return id->name->asString();
        }
    } else if (FieldMemberExpression *fme = cast<FieldMemberExpression *>(ast)) {
        if (fme->name) {
            *location = fme->identifierToken;
            return fme->name->asString();
        }
    }
    return QString();
}

void Check::checkNewExpression(ExpressionNode *ast)
{
    if (!(_options & WarnNonCapitalizedNew))
        return;
    SourceLocation location;
    const QString name = functionName(ast, &location);
    if (name.isEmpty())
        return;
    if (!name.at(0).isUpper()) {
        warning(location, tr("'new' should only be used with functions that start with an uppercase letter"));
    }
}

bool Check::visit(NewExpression *ast)
{
    checkNewExpression(ast->expression);
    return true;
}

bool Check::visit(NewMemberExpression *ast)
{
    checkNewExpression(ast->base);
    return true;
}

bool Check::visit(CallExpression *ast)
{
    // check for capitalized function name being called
    if (_options & WarnCallsOfCapitalizedFunctions) {
        SourceLocation location;
        const QString name = functionName(ast->base, &location);
        if (!name.isEmpty() && name.at(0).isUpper()) {
            warning(location, tr("calls of functions that start with an uppercase letter should use 'new'"));
        }
    }
    return true;
}

950
951
952
/// When something is changed here, also change ReadingContext::lookupProperty in
/// texttomodelmerger.cpp
/// ### Maybe put this into the context as a helper method.
953
const Value *Check::checkScopeObjectMember(const UiQualifiedId *id)
Christian Kamm's avatar
Christian Kamm committed
954
{
955
    QList<const ObjectValue *> scopeObjects = _scopeChain.qmlScopeObjects();
956
957
    if (scopeObjects.isEmpty())
        return 0;
Christian Kamm's avatar
Christian Kamm committed
958
959

    if (! id)
960
        return 0; // ### error?
Christian Kamm's avatar
Christian Kamm committed
961

962
963
964
    if (! id->name) // possible after error recovery
        return 0;

965
    QString propertyName = id->name->asString();
Christian Kamm's avatar
Christian Kamm committed
966
967

    if (propertyName == QLatin1String("id") && ! id->next)
968
        return 0; // ### should probably be a special value
Christian Kamm's avatar
Christian Kamm committed
969
970

    // attached properties
971
972
973
    bool isAttachedProperty = false;
    if (! propertyName.isEmpty() && propertyName[0].isUpper()) {
        isAttachedProperty = true;
974
        if (const ObjectValue *qmlTypes = _scopeChain.qmlTypes())
975
            scopeObjects += qmlTypes;
976
    }
977

978
    if (scopeObjects.isEmpty())
979
        return 0;
Christian Kamm's avatar
Christian Kamm committed
980

981
    // global lookup for first part of id
982
983
    const Value *value = 0;
    for (int i = scopeObjects.size() - 1; i >= 0; --i) {
Christian Kamm's avatar
Christian Kamm committed
984
        value = scopeObjects[i]->lookupMember(propertyName, _context);
985
986
987
        if (value)
            break;
    }
Christian Kamm's avatar
Christian Kamm committed
988
989
    if (!value) {
        error(id->identifierToken,
990
              Check::tr("'%1' is not a valid property name").arg(propertyName));
991
        return 0;
Christian Kamm's avatar
Christian Kamm committed
992
993
    }

994
995
    // can't look up members for attached properties
    if (isAttachedProperty)
996
        return 0;
997

998
999
    // resolve references
    if (const Reference *ref = value->asReference())
Christian Kamm's avatar
Christian Kamm committed
1000
        value = _context->lookupReference(ref);
1001

1002
1003
1004
1005
1006
1007
    // member lookup
    const UiQualifiedId *idPart = id;
    while (idPart->next) {
        const ObjectValue *objectValue = value_cast<const ObjectValue *>(value);
        if (! objectValue) {
            error(idPart->identifierToken,
1008
                  Check::tr("'%1' does not have members").arg(propertyName));
1009
            return 0;
1010
1011
        }

1012
1013
1014
1015
1016
1017
        if (! idPart->next->name) {
            // somebody typed "id." and error recovery still gave us a valid tree,
            // so just bail out here.
            return 0;
        }

1018
1019
1020
        idPart = idPart->next;
        propertyName = idPart->name->asString();

Christian Kamm's avatar
Christian Kamm committed
1021
        value = objectValue->lookupMember(propertyName, _context);
1022
1023
        if (! value) {
            error(idPart->identifierToken,
1024
                  Check::tr("'%1' is not a member of '%2'").arg(
1025
                          propertyName, objectValue->className()));
1026
            return 0;
1027
1028
        }
    }
1029
1030

    return value;
Christian Kamm's avatar
Christian Kamm committed
1031
1032
}

1033
1034
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
void Check::checkAssignInCondition(AST::ExpressionNode *condition)
{
    if (_options & WarnAssignInCondition) {
        if (BinaryExpression *binary = cast<BinaryExpression *>(condition)) {
            if (binary->op == QSOperator::Assign)
                warning(binary->operatorToken, tr("avoid assignments in conditions"));
        }
    }
}

void Check::checkEndsWithControlFlow(StatementList *statements, SourceLocation errorLoc)
{
    // full flow analysis would be neat
    if (!statements || !(_options & WarnCaseWithoutFlowControlEnd))
        return;

    Statement *lastStatement = 0;
    for (StatementList *slist = statements; slist; slist = slist->next)
        lastStatement = slist->statement;

    if (!cast<ReturnStatement *>(lastStatement)
            && !cast<ThrowStatement *>(lastStatement)
            && !cast<BreakStatement *>(lastStatement)
            && !cast<ContinueStatement *>(lastStatement)) {
        warning(errorLoc, tr("case does not end with return, break, continue or throw"));
    }
}

Christian Kamm's avatar
Christian Kamm committed
1061
1062
1063
1064
1065
1066
1067
1068
1069
void Check::error(const AST::SourceLocation &loc, const QString &message)
{
    _messages.append(DiagnosticMessage(DiagnosticMessage::Error, loc, message));
}

void Check::warning(const AST::SourceLocation &loc, const QString &message)
{
    _messages.append(DiagnosticMessage(DiagnosticMessage::Warning, loc, message));
}
1070
1071
1072
1073
1074
1075
1076
1077

Node *Check::parent(int distance)
{
    const int index = _chain.size() - 2 - distance;
    if (index < 0)
        return 0;
    return _chain.at(index);
}