CheckUndefinedSymbols.cpp 18 KB
Newer Older
1 2 3 4
/**************************************************************************
**
** This file is part of Qt Creator
**
hjk's avatar
hjk committed
5
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
**
** 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
**
**************************************************************************/

#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)
Roberto Raggi's avatar
Roberto Raggi committed
44
    : ASTVisitor(doc->translationUnit()), _doc(doc)
45 46 47 48 49 50 51 52 53
{ }

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
QByteArray CheckUndefinedSymbols::templateParameterName(NameAST *ast) const
{
    if (ast && ast->name) {
Roberto Raggi's avatar
Roberto Raggi committed
68
        if (const Identifier *id = ast->name->identifier())
69 70 71 72 73 74 75 76 77 78 79 80 81
            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
    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()) {
Roberto Raggi's avatar
Roberto Raggi committed
101
                if (const Identifier *id = member->identifier()) {
102 103 104 105 106 107 108
                    if (name == id->chars())
                        return true;
                }
            }
        }
    }

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

Roberto Raggi's avatar
Roberto Raggi committed
112
        for (DeclarationListAST *it = templateDeclaration->template_parameter_list; it; it = it->next) {
113
            DeclarationAST *templateParameter = it->value;
114

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

120 121 122
    return _types.contains(name);
}

Roberto Raggi's avatar
Roberto Raggi committed
123
bool CheckUndefinedSymbols::isType(const Identifier *id) const
124 125 126 127 128 129 130
{
    if (! id)
        return false;

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

Roberto Raggi's avatar
Roberto Raggi committed
131
void CheckUndefinedSymbols::addType(const Name *name)
132 133 134 135
{
    if (! name)
        return;

Roberto Raggi's avatar
Roberto Raggi committed
136
    if (const Identifier *id = name->identifier())
137 138 139
        _types.insert(QByteArray(id->chars(), id->size()));
}

Roberto Raggi's avatar
Roberto Raggi committed
140
void CheckUndefinedSymbols::addProtocol(const Name *name)
141 142 143 144
{
    if (!name)
        return;

Roberto Raggi's avatar
Roberto Raggi committed
145
    if (const Identifier *id = name->identifier())
146 147 148 149 150 151 152 153
        _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
    }
}

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

Roberto Raggi's avatar
Roberto Raggi committed
185
        if (const Identifier *id = binding->identifier()) {
186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201
            _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
}

Roberto Raggi's avatar
Roberto Raggi committed
253
bool CheckUndefinedSymbols::visit(TypeofSpecifierAST *)
254 255 256 257 258 259 260 261 262 263 264
{
    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;
Roberto Raggi's avatar
Roberto Raggi committed
265
        } else if (const Identifier *id = ast->name->name->identifier()) {
266
            if (! isType(id)) {
267 268 269 270 271 272 273 274 275 276 277 278 279 280
                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;
}

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

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

292 293 294 295 296 297 298 299 300 301 302
bool CheckUndefinedSymbols::visit(ClassSpecifierAST *ast)
{
    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()) {
Roberto Raggi's avatar
Roberto Raggi committed
303
                const NameId *nameId = symbol->name()->asNameId();
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

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

341 342 343
void CheckUndefinedSymbols::endVisit(FunctionDefinitionAST *)
{ }

344 345 346 347 348 349 350 351 352 353 354
bool CheckUndefinedSymbols::visit(CompoundStatementAST *ast)
{
    _compoundStatementStack.append(ast);
    return true;
}

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

355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375
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;

Roberto Raggi's avatar
Roberto Raggi committed
376
        if (const Name *name = nameAST->name) {
Roberto Raggi's avatar
Roberto Raggi committed
377
            const Identifier *id = name->identifier();
378
            const QByteArray spell = QByteArray::fromRawData(id->chars(), id->size());
379
            if (isType(spell))
380 381 382
                resolvedBaseClassName = true;
        }

383 384
        if (! resolvedBaseClassName)
            translationUnit()->warning(nameAST->firstToken(), "expected class-name");
385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411
    }

    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) {
Roberto Raggi's avatar
Roberto Raggi committed
412
        const QualifiedNameId *q = ast->name->asQualifiedNameId();
413
        for (unsigned i = 0; i < q->nameCount() - 1; ++i) {
Roberto Raggi's avatar
Roberto Raggi committed
414
            const Name *name = q->nameAt(i);
Roberto Raggi's avatar
Roberto Raggi committed
415
            if (const Identifier *id = name->identifier()) {
416
                const QByteArray spell = QByteArray::fromRawData(id->chars(), id->size());
417
                if (! (_namespaceNames.contains(spell) || isType(id))) {
418 419 420 421 422 423 424 425 426 427 428 429 430 431 432
                    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()) {
Roberto Raggi's avatar
Roberto Raggi committed
433
            SpecifierListAST *type_specifier = cast_type_id->type_specifier_list;
434
            if (! cast_type_id->declarator && type_specifier && ! type_specifier->next &&
Roberto Raggi's avatar
Roberto Raggi committed
435
                type_specifier->value->asNamedTypeSpecifier() && ast->expression &&
436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455
                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()) {
Roberto Raggi's avatar
Roberto Raggi committed
456
            SpecifierListAST *type_specifier = type_id->type_specifier_list;
457
            if (! type_id->declarator && type_specifier && ! type_specifier->next &&
Roberto Raggi's avatar
Roberto Raggi committed
458
                type_specifier->value->asNamedTypeSpecifier()) {
459 460 461 462 463
                // 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
Roberto Raggi's avatar
Roberto Raggi committed
464 465 466
                       &&   type_id->declarator->postfix_declarator_list
                       && ! type_id->declarator->postfix_declarator_list->next
                       &&   type_id->declarator->postfix_declarator_list->value->asArrayDeclarator() != 0) {
467 468 469 470 471 472 473 474 475 476
                // this sizeof expression is ambiguos, e.g.
                // sizeof(a[10])
                //   `a' can be a typeid or an expression.
                return false;
            }
        }
    }

    return true;
}
477 478 479 480 481 482

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

Roberto Raggi's avatar
Roberto Raggi committed
483
        if (const Name *name = nameAST->name) {
Roberto Raggi's avatar
Roberto Raggi committed
484
            const Identifier *id = name->identifier();
485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500
            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)
{
501
    for (NameListAST *iter = ast->identifier_list; iter; iter = iter->next) {
Roberto Raggi's avatar
Roberto Raggi committed
502
        if (NameAST *nameAST = iter->value) {
503 504
            bool resolvedProtocolName = false;

Roberto Raggi's avatar
Roberto Raggi committed
505
            if (const Name *name = nameAST->name) {
Roberto Raggi's avatar
Roberto Raggi committed
506
                const Identifier *id = name->identifier();
507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526
                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;
}
527 528 529 530

bool CheckUndefinedSymbols::visit(ObjCPropertyDeclarationAST *ast)
{
    for (List<ObjCPropertyDeclaration *> *iter = ast->symbols; iter; iter = iter->next) {
Roberto Raggi's avatar
Roberto Raggi committed
531
        if (/*Name *getterName = */ iter->value->getterName()) {
532 533
            // FIXME: resolve the symbol for the name, and check its signature.
        }
534

Roberto Raggi's avatar
Roberto Raggi committed
535
        if (/*Name *setterName = */ iter->value->setterName()) {
536 537
            // FIXME: resolve the symbol for the name, and check its signature.
        }
538 539 540 541
    }

    return false;
}
542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572

bool CheckUndefinedSymbols::visit(QtEnumDeclarationAST *ast)
{
    for (NameListAST *iter = ast->enumerator_list; iter; iter = iter->next) {
        if (! iter->value)
            continue;

        if (SimpleNameAST *enumName = iter->value->asSimpleName()) {
            if (enumName->name) {
                const Identifier *enumId = enumName->name->identifier();
                if (!isType(enumId))// ### we're only checking if the enum name is known as a type name, not as an *enum*.
                    translationUnit()->warning(enumName->firstToken(),
                                               "unknown enum '%s'",
                                               enumId->chars());
            }
        }
    }
    return false;
}

bool CheckUndefinedSymbols::visit(QtFlagsDeclarationAST *)
{
    // ### TODO
    return false;
}

bool CheckUndefinedSymbols::visit(QtPropertyDeclarationAST *)
{
    // ### TODO
    return false;
}