CheckUndefinedSymbols.cpp 16.7 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, 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.
**
** If you are unsure which license is appropriate for your use, please
hjk's avatar
hjk committed
26
** contact the sales department at http://qt.nokia.com/contact.
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
**
**************************************************************************/

#include "CheckUndefinedSymbols.h"
#include "Overview.h"

#include <Names.h>
#include <Literals.h>
#include <Symbols.h>
#include <TranslationUnit.h>
#include <Scope.h>
#include <AST.h>

using namespace CPlusPlus;


CheckUndefinedSymbols::CheckUndefinedSymbols(Document::Ptr doc)
    : ASTVisitor(doc->control()), _doc(doc)
{ }

CheckUndefinedSymbols::~CheckUndefinedSymbols()
{ }

void CheckUndefinedSymbols::setGlobalNamespaceBinding(NamespaceBindingPtr globalNamespaceBinding)
{
    _globalNamespaceBinding = globalNamespaceBinding;
    _types.clear();
54
    _protocols.clear();
55
56
57
58
59
60
61
62
63
64

    if (_globalNamespaceBinding) {
        QSet<NamespaceBinding *> processed;
        buildTypeMap(_globalNamespaceBinding.data(), &processed);
    }
}

void CheckUndefinedSymbols::operator()(AST *ast)
{ accept(ast); }

65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
QByteArray CheckUndefinedSymbols::templateParameterName(NameAST *ast) const
{
    if (ast && ast->name) {
        if (Identifier *id = ast->name->identifier())
            return QByteArray::fromRawData(id->chars(), id->size());
    }

    return QByteArray();
}

QByteArray CheckUndefinedSymbols::templateParameterName(DeclarationAST *ast) const
{
    if (ast) {
        if (TypenameTypeParameterAST *d = ast->asTypenameTypeParameter())
            return templateParameterName(d->name);
        else if (TemplateTypeParameterAST *d = ast->asTemplateTypeParameter())
            return templateParameterName(d->name);
82
83
84
85
86
87
        else if (ParameterDeclarationAST *d = ast->asParameterDeclaration()) {
            if (d->symbol) {
                if (const Identifier *id = d->symbol->identifier())
                    return QByteArray::fromRawData(id->chars(), id->size());
            }
        }
88
89
90
91
92
93
    }
    return QByteArray();
}

bool CheckUndefinedSymbols::isType(const QByteArray &name) const
{
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
    for (int i = _compoundStatementStack.size() - 1; i != -1; --i) {
        Scope *members = _compoundStatementStack.at(i)->symbol->members();

        for (unsigned m = 0; m < members->symbolCount(); ++m) {
            Symbol *member = members->symbolAt(m);

            if (member->isTypedef() && member->isDeclaration()) {
                if (Identifier *id = member->identifier()) {
                    if (name == id->chars())
                        return true;
                }
            }
        }
    }

109
110
    for (int i = _templateDeclarationStack.size() - 1; i != - 1; --i) {
        TemplateDeclarationAST *templateDeclaration = _templateDeclarationStack.at(i);
111

112
113
        for (DeclarationListAST *it = templateDeclaration->template_parameters; it; it = it->next) {
            DeclarationAST *templateParameter = it->declaration;
114

115
116
117
118
            if (templateParameterName(templateParameter) == name)
                return true;
        }
    }
119

120
121
122
123
124
125
126
127
128
129
130
    return _types.contains(name);
}

bool CheckUndefinedSymbols::isType(Identifier *id) const
{
    if (! id)
        return false;

    return isType(QByteArray::fromRawData(id->chars(), id->size()));
}

131
132
133
134
135
136
137
138
139
void CheckUndefinedSymbols::addType(Name *name)
{
    if (! name)
        return;

    if (Identifier *id = name->identifier())
        _types.insert(QByteArray(id->chars(), id->size()));
}

140
141
142
143
144
145
146
147
148
149
150
151
152
153
void CheckUndefinedSymbols::addProtocol(Name *name)
{
    if (!name)
        return;

    if (Identifier *id = name->identifier())
        _protocols.insert(QByteArray(id->chars(), id->size()));
}

bool CheckUndefinedSymbols::isProtocol(const QByteArray &name) const
{
    return _protocols.contains(name);
}

154
155
156
157
158
void CheckUndefinedSymbols::buildTypeMap(Class *klass)
{
    addType(klass->name());

    for (unsigned i = 0; i < klass->memberCount(); ++i) {
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
        buildMemberTypeMap(klass->memberAt(i));
    }
}

void CheckUndefinedSymbols::buildMemberTypeMap(Symbol *member)
{
    if (member == 0)
        return;

    if (Class *klass = member->asClass()) {
        buildTypeMap(klass);
    } else if (Enum *e = member->asEnum()) {
        addType(e->name());
    } else if (ForwardClassDeclaration *fwd = member->asForwardClassDeclaration()) {
        addType(fwd->name());
    } else if (Declaration *decl = member->asDeclaration()) {
        if (decl->isTypedef())
            addType(decl->name());
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
    }
}

void CheckUndefinedSymbols::buildTypeMap(NamespaceBinding *binding, QSet<NamespaceBinding *> *processed)
{
    if (! processed->contains(binding)) {
        processed->insert(binding);

        if (Identifier *id = binding->identifier()) {
            _namespaceNames.insert(QByteArray(id->chars(), id->size()));
        }

        foreach (Namespace *ns, binding->symbols) {
            for (unsigned i = 0; i < ns->memberCount(); ++i) {
                Symbol *member = ns->memberAt(i);

                if (Class *klass = member->asClass()) {
                    buildTypeMap(klass);
                } else if (Enum *e = member->asEnum()) {
                    addType(e->name());
                } else if (ForwardClassDeclaration *fwd = member->asForwardClassDeclaration()) {
                    addType(fwd->name());
                } else if (Declaration *decl = member->asDeclaration()) {
                    if (decl->isTypedef())
                        addType(decl->name());
202
203
204
205
                } else if (ObjCForwardClassDeclaration *fKlass = member->asObjCForwardClassDeclaration()) {
                    addType(fKlass->name());
                } else if (ObjCClass *klass = member->asObjCClass()) {
                    addType(klass->name());
206
207
208

                    for (unsigned i = 0; i < klass->memberCount(); ++i)
                        buildMemberTypeMap(klass->memberAt(i));
209
                } else if (ObjCForwardProtocolDeclaration *fProto = member->asObjCForwardProtocolDeclaration()) {
210
                    addProtocol(fProto->name());
211
                } else if (ObjCProtocol *proto = member->asObjCProtocol()) {
212
                    addProtocol(proto->name());
213
214
215

                    for (unsigned i = 0; i < proto->memberCount(); ++i)
                        buildMemberTypeMap(proto->memberAt(i));
216
217
218
219
220
221
222
223
224
225
226
227
                }
            }
        }

        foreach (NamespaceBinding *childBinding, binding->children) {
            buildTypeMap(childBinding, processed);
        }
    }
}

FunctionDeclaratorAST *CheckUndefinedSymbols::currentFunctionDeclarator() const
{
228
    if (_functionDeclaratorStack.isEmpty())
229
230
        return 0;

231
    return _functionDeclaratorStack.last();
232
233
}

234
235
236
237
238
239
240
241
CompoundStatementAST *CheckUndefinedSymbols::compoundStatement() const
{
    if (_compoundStatementStack.isEmpty())
        return 0;

    return _compoundStatementStack.last();
}

242
243
bool CheckUndefinedSymbols::visit(FunctionDeclaratorAST *ast)
{
244
    _functionDeclaratorStack.append(ast);
245
246
247
248
249
    return true;
}

void CheckUndefinedSymbols::endVisit(FunctionDeclaratorAST *)
{
250
    _functionDeclaratorStack.removeLast();
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
}

bool CheckUndefinedSymbols::visit(TypeofSpecifierAST *ast)
{
    accept(ast->next);
    return false;
}

bool CheckUndefinedSymbols::visit(NamedTypeSpecifierAST *ast)
{
    if (ast->name) {
        if (! ast->name->name) {
            unsigned line, col;
            getTokenStartPosition(ast->firstToken(), &line, &col);
            // qWarning() << _doc->fileName() << line << col;
        } else if (Identifier *id = ast->name->name->identifier()) {
267
            if (! isType(id)) {
268
269
270
271
272
273
274
275
276
277
278
279
280
281
                if (FunctionDeclaratorAST *functionDeclarator = currentFunctionDeclarator()) {
                    if (functionDeclarator->as_cpp_initializer)
                        return true;
                }

                Overview oo;
                translationUnit()->warning(ast->firstToken(), "`%s' is not a type name",
                                           qPrintable(oo(ast->name->name)));
            }
        }
    }
    return true;
}

282
283
284
285
286
287
288
289
290
291
292
bool CheckUndefinedSymbols::visit(TemplateDeclarationAST *ast)
{
    _templateDeclarationStack.append(ast);
    return true;
}

void CheckUndefinedSymbols::endVisit(TemplateDeclarationAST *)
{
    _templateDeclarationStack.removeLast();
}

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
bool CheckUndefinedSymbols::visit(ClassSpecifierAST *ast)
{
    if (ast->base_clause) {
        unsigned line, col;
        getTokenStartPosition(ast->firstToken(), &line, &col);
    }

    bool hasQ_OBJECT_CHECK = false;

    if (ast->symbol) {
        Class *klass = ast->symbol->asClass();

        for (unsigned i = 0; i < klass->memberCount(); ++i) {
            Symbol *symbol = klass->memberAt(i);

            if (symbol->name() && symbol->name()->isNameId()) {
                NameId *nameId = symbol->name()->asNameId();

                if (! qstrcmp(nameId->identifier()->chars(), "qt_check_for_QOBJECT_macro")) {
                    hasQ_OBJECT_CHECK = true;
                    break;
                }
            }
        }
    }

    _qobjectStack.append(hasQ_OBJECT_CHECK);

    return true;
}

void CheckUndefinedSymbols::endVisit(ClassSpecifierAST *)
{ _qobjectStack.removeLast(); }

bool CheckUndefinedSymbols::qobjectCheck() const
{
    if (_qobjectStack.isEmpty())
        return false;

    return _qobjectStack.last();
}

bool CheckUndefinedSymbols::visit(FunctionDefinitionAST *ast)
{
    if (ast->symbol) {
        Function *fun = ast->symbol->asFunction();
        if ((fun->isSignal() || fun->isSlot()) && ! qobjectCheck()) {
            translationUnit()->warning(ast->firstToken(),
                                       "you forgot the Q_OBJECT macro");
        }
    }
    return true;
}

347
348
349
void CheckUndefinedSymbols::endVisit(FunctionDefinitionAST *)
{ }

350
351
352
353
354
355
356
357
358
359
360
bool CheckUndefinedSymbols::visit(CompoundStatementAST *ast)
{
    _compoundStatementStack.append(ast);
    return true;
}

void CheckUndefinedSymbols::endVisit(CompoundStatementAST *)
{
    _compoundStatementStack.removeLast();
}

361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
bool CheckUndefinedSymbols::visit(SimpleDeclarationAST *ast)
{
    const bool check = qobjectCheck();
    for (List<Declaration *> *it = ast->symbols; it; it = it->next) {
        Declaration *decl = it->value;

        if (Function *fun = decl->type()->asFunctionType()) {
            if ((fun->isSignal() || fun->isSlot()) && ! check) {
                translationUnit()->warning(ast->firstToken(),
                                           "you forgot the Q_OBJECT macro");
            }
        }
    }
    return true;
}

bool CheckUndefinedSymbols::visit(BaseSpecifierAST *base)
{
    if (NameAST *nameAST = base->name) {
        bool resolvedBaseClassName = false;

        if (Name *name = nameAST->name) {
            Identifier *id = name->identifier();
            const QByteArray spell = QByteArray::fromRawData(id->chars(), id->size());
385
            if (isType(spell))
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
                resolvedBaseClassName = true;
        }

        if (! resolvedBaseClassName) {
            const char *token = "after `:'";

            if (base->comma_token)
                token = "after `,'";

            translationUnit()->warning(nameAST->firstToken(),
                                       "expected class-name %s token", token);
        }
    }

    return true;
}

bool CheckUndefinedSymbols::visit(UsingDirectiveAST *ast)
{
    if (ast->symbol && ast->symbol->name() && _globalNamespaceBinding) {
        const Location loc = Location(ast->symbol);

        NamespaceBinding *binding = _globalNamespaceBinding.data();

        if (Scope *enclosingNamespaceScope = ast->symbol->enclosingNamespaceScope())
            binding = NamespaceBinding::find(enclosingNamespaceScope->owner()->asNamespace(), binding);

        if (! binding || ! binding->resolveNamespace(loc, ast->symbol->name())) {
            translationUnit()->warning(ast->name->firstToken(),
                                       "expected a namespace");
        }
    }

    return true;
}

bool CheckUndefinedSymbols::visit(QualifiedNameAST *ast)
{
    if (ast->name) {
        QualifiedNameId *q = ast->name->asQualifiedNameId();
        for (unsigned i = 0; i < q->nameCount() - 1; ++i) {
            Name *name = q->nameAt(i);
            if (Identifier *id = name->identifier()) {
                const QByteArray spell = QByteArray::fromRawData(id->chars(), id->size());
430
                if (! (_namespaceNames.contains(spell) || isType(id))) {
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
                    translationUnit()->warning(ast->firstToken(),
                                               "`%s' is not a namespace or class name",
                                               spell.constData());
                }
            }
        }
    }

    return true;
}

bool CheckUndefinedSymbols::visit(CastExpressionAST *ast)
{
    if (ast->lparen_token && ast->type_id && ast->rparen_token && ast->expression) {
        if (TypeIdAST *cast_type_id = ast->type_id->asTypeId()) {
            SpecifierAST *type_specifier = cast_type_id->type_specifier;
            if (! cast_type_id->declarator && type_specifier && ! type_specifier->next &&
                type_specifier->asNamedTypeSpecifier() && ast->expression &&
                ast->expression->asUnaryExpression()) {
                // this ast node is ambigious, e.g.
                //   (a) + b
                // it can be parsed as
                //   ((a) + b)
                // or
                //   (a) (+b)
                accept(ast->expression);
                return false;
            }
        }
    }

    return true;
}

bool CheckUndefinedSymbols::visit(SizeofExpressionAST *ast)
{
    if (ast->lparen_token && ast->expression && ast->rparen_token) {
        if (TypeIdAST *type_id = ast->expression->asTypeId()) {
            SpecifierAST *type_specifier = type_id->type_specifier;
            if (! type_id->declarator && type_specifier && ! type_specifier->next &&
                type_specifier->asNamedTypeSpecifier()) {
                // this sizeof expression is ambiguos, e.g.
                // sizeof (a)
                //   `a' can be a typeid or a nested-expression.
                return false;
            } else if (type_id->declarator
                       &&   type_id->declarator->postfix_declarators
                       && ! type_id->declarator->postfix_declarators->next
                       &&   type_id->declarator->postfix_declarators->asArrayDeclarator() != 0) {
                // this sizeof expression is ambiguos, e.g.
                // sizeof(a[10])
                //   `a' can be a typeid or an expression.
                return false;
            }
        }
    }

    return true;
}
490
491
492
493
494
495
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
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539

bool CheckUndefinedSymbols::visit(ObjCClassDeclarationAST *ast)
{
    if (NameAST *nameAST = ast->superclass) {
        bool resolvedSuperClassName = false;

        if (Name *name = nameAST->name) {
            Identifier *id = name->identifier();
            const QByteArray spell = QByteArray::fromRawData(id->chars(), id->size());
            if (isType(spell))
                resolvedSuperClassName = true;
        }

        if (! resolvedSuperClassName) {
            translationUnit()->warning(nameAST->firstToken(),
                                       "expected class-name after ':' token");
        }
    }

    return true;
}

bool CheckUndefinedSymbols::visit(ObjCProtocolRefsAST *ast)
{
    for (IdentifierListAST *iter = ast->identifier_list; iter; iter = iter->next) {
        if (NameAST *nameAST = iter->name) {
            bool resolvedProtocolName = false;

            if (Name *name = nameAST->name) {
                Identifier *id = name->identifier();
                const QByteArray spell = QByteArray::fromRawData(id->chars(), id->size());
                if (isProtocol(spell))
                    resolvedProtocolName = true;
            }

            if (!resolvedProtocolName) {
                char after;

                if (iter == ast->identifier_list)
                    after = '<';
                else
                    after = ',';

                translationUnit()->warning(nameAST->firstToken(), "expected protocol name after '%c' token", after);
            }
        }
    }

    return false;
}