Index: clang-tidy/misc/CMakeLists.txt =================================================================== --- clang-tidy/misc/CMakeLists.txt +++ clang-tidy/misc/CMakeLists.txt @@ -6,12 +6,13 @@ AssignOperatorSignatureCheck.cpp BoolPointerImplicitConversionCheck.cpp DefinitionsInHeadersCheck.cpp + ForwardDeclarationNamespaceCheck.cpp InaccurateEraseCheck.cpp InefficientAlgorithmCheck.cpp MacroParenthesesCheck.cpp MacroRepeatedSideEffectsCheck.cpp MiscTidyModule.cpp - MoveConstantArgumentCheck.cpp + MoveConstantArgumentCheck.cpp MoveConstructorInitCheck.cpp NewDeleteOverloadsCheck.cpp NoexceptMoveConstructorCheck.cpp Index: clang-tidy/misc/ForwardDeclarationNamespaceCheck.h =================================================================== --- /dev/null +++ clang-tidy/misc/ForwardDeclarationNamespaceCheck.h @@ -0,0 +1,58 @@ +//===--- ForwardDeclarationNamespaceCheck.h - clang-tidy --------------------*- C++ -*-===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// + +#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_MISC_FORWARDDECLARATIONNAMESPACECHECK_H_ +#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_MISC_FORWARDDECLARATIONNAMESPACECHECK_H_ + +#include +#include +#include +#include +#include "../ClangTidy.h" + +namespace clang { +namespace tidy { +namespace misc { + +/// Checks if an unused forward declaration is in a wrong namespace +/// +/// The check inspects all unused forward declarations and checks if there is +/// any declaration/definition with the same name existing, which could indicate +/// that the forward declaration is in a potentially wrong namespace. +/// +/// \code +/// namespace na { struct A; } +/// namespace nb { struct A {} }; +/// nb::A a; +/// // warning : no definition found for 'A', but a definition with the same +/// name 'A' found in another namespace 'nb::' +/// \endcode +/// +/// This check can only generate warning but can't suggest fix at this point. + +class ForwardDeclarationNamespaceCheck : public ClangTidyCheck { +public: + ForwardDeclarationNamespaceCheck(StringRef Name, ClangTidyContext *Context) + : ClangTidyCheck(Name, Context) {} + void registerMatchers(ast_matchers::MatchFinder *Finder) override; + void check(const ast_matchers::MatchFinder::MatchResult &Result) override; + void onEndOfTranslationUnit() override; +private: + std::map> + DeclNameToDefinitions; + std::map> + DeclNameToDeclarations; + std::set FriendTypes; +}; + +} // namespace misc +} // namespace tidy +} // namespace clang + +#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_MISC_FORWARDDECLARATIONNAMESPACECHECK_H_ Index: clang-tidy/misc/ForwardDeclarationNamespaceCheck.cpp =================================================================== --- /dev/null +++ clang-tidy/misc/ForwardDeclarationNamespaceCheck.cpp @@ -0,0 +1,180 @@ +//===--- ForwardDeclarationNamespaceCheck.cpp - clang-tidy +//--------------------*- C++ -*-===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// + +#include "ForwardDeclarationNamespaceCheck.h" +#include +#include "clang/AST/ASTContext.h" +#include "clang/AST/Decl.h" +#include "clang/AST/DeclBase.h" +#include "clang/AST/DeclCXX.h" +#include "clang/ASTMatchers/ASTMatchFinder.h" +#include "clang/ASTMatchers/ASTMatchers.h" + +using namespace clang::ast_matchers; + +namespace clang { +namespace tidy { +namespace misc { + +void ForwardDeclarationNamespaceCheck::registerMatchers(MatchFinder *Finder) { + // Matches all class declarations/definitions *EXCEPT* + // 1. implicit class. Eg. class A {}; has implicit class A declared inside A + // 2. classes declared/defined inside classes(can be detected by compiler) + // 3. template class declaration, template instantiation or + // specialization(NOTE: extern specialization is filtered out by + // "unless(hasAncestor(cxxRecordDecl()))" + auto IsInSpecialization = hasAncestor( + decl(anyOf(cxxRecordDecl(isExplicitTemplateSpecialization()), + functionDecl(isExplicitTemplateSpecialization())))); + Finder->addMatcher( + cxxRecordDecl( + hasParent(decl(anyOf(namespaceDecl(), translationUnitDecl()))), + unless(isImplicit()), unless(hasAncestor(cxxRecordDecl())), + unless(isInstantiated()), unless(IsInSpecialization), + unless(classTemplateSpecializationDecl())) + .bind("record_decl"), + this); + // Match all friend declaration. Classes used in friend declarations are not + // marked as referenced in AST. We need to record all record classes used in + // friend declarations + Finder->addMatcher(friendDecl().bind("friend_decl"), this); +} + +void ForwardDeclarationNamespaceCheck::check( + const MatchFinder::MatchResult &Result) { + if (auto *RecordDecl = Result.Nodes.getNodeAs("record_decl")) { + std::string DeclName(RecordDecl->getName().data()); + if (RecordDecl->isThisDeclarationADefinition()) { + DeclNameToDefinitions[DeclName].push_back(RecordDecl); + } else { + // if a declaration has no definition, the definition could be in another + // namespace(a wrong namespace) + // NOTE: even a declaration does have definition, we still need it to + // compare with other declarations + DeclNameToDeclarations[DeclName].push_back(RecordDecl); + } + } else { + auto *decl = Result.Nodes.getNodeAs("friend_decl"); + assert(decl && "Decl is neither record_decl nor friend decl!"); + // classes used in friend delarations are not marked referenced in AST + // so we need to check classes used in friend declarations manually to + // reduce false positive + // For example, in + // struct A; + // struct B { friend A; }; + // A will not be marked as "referenced" in the AST + if (const TypeSourceInfo *tsi = decl->getFriendType()) { + QualType desugared = tsi->getType().getDesugaredType(*Result.Context); + FriendTypes.insert(desugared.getTypePtr()); + } + } +} + +namespace { + +bool haveSameNamespaceOrTranslationUnit(const CXXRecordDecl *Decl1, + const CXXRecordDecl *Decl2) { + const DeclContext *ParentDecl1 = Decl1->getLexicalParent(); + const DeclContext *ParentDecl2 = Decl2->getLexicalParent(); + // Since we only matched decls whose parent is Namespace or TranslationUnit + // declaration, parent should be either a translation unit or namespace + if (ParentDecl1->getDeclKind() == Decl::TranslationUnit || + ParentDecl2->getDeclKind() == Decl::TranslationUnit) { + return ParentDecl1 == ParentDecl2; + } + assert(ParentDecl1->getDeclKind() == Decl::Namespace && + "ParentDecl1 declaration must be a namespace"); + assert(ParentDecl2->getDeclKind() == Decl::Namespace && + "ParentDecl2 declaration must be a namespace"); + auto *Ns1 = NamespaceDecl::castFromDeclContext(ParentDecl1); + auto *Ns2 = NamespaceDecl::castFromDeclContext(ParentDecl2); + return Ns1->getOriginalNamespace() == Ns2->getOriginalNamespace(); +} + +std::string getNameOfNamespace(const CXXRecordDecl *Decl) { + std::stack Stk; + for (auto *ParentDecl = Decl->getLexicalParent(); + ParentDecl->getDeclKind() != Decl::TranslationUnit; + ParentDecl = ParentDecl->getLexicalParent()) { + auto *NsDecl = dyn_cast(ParentDecl); + assert(NsDecl && "Cast to NamespaceDecl failed"); + Stk.push(NsDecl); + } + std::string Ns = ""; + while (!Stk.empty()) { + auto *namespaceDecl = Stk.top(); + Stk.pop(); + Ns += namespaceDecl->getName().data(); + Ns += "::"; + } + if (Ns.length() == 0) { + Ns = "Top level"; + } + return Ns; +} + +} // anonymous namespace + +void ForwardDeclarationNamespaceCheck::onEndOfTranslationUnit() { + // Iterate each group of declarations grouped by names. + for (auto const &Iterator : DeclNameToDeclarations) { + auto &Declarations = Iterator.second; + // if more than 1 declarations exist, check if all have the same namesapce + for (const auto *CurDecl : Declarations) { + if (CurDecl->hasDefinition() || CurDecl->isReferenced()) { + continue; // skip forward declarations that are used/referenced + } + if (FriendTypes.find(CurDecl->getTypeForDecl()) != FriendTypes.end()) { + continue; // skip forward declarations referenced as friend + } + if (CurDecl->getLocation().isMacroID() || + CurDecl->getLocation().isInvalid()) { + continue; + } + // compare with all other declarations with the same name + for (auto *Decl : Declarations) { + if (Decl == CurDecl) { + continue; // don't compare with self + } + if (!CurDecl->hasDefinition() && + !haveSameNamespaceOrTranslationUnit(CurDecl, Decl)) { + diag(CurDecl->getLocation(), + "declaration is never referenced, but a declaration with the " + "same name '%0' found in another namespace '%1'") + << CurDecl->getName() << getNameOfNamespace(Decl); + diag(Decl->getLocation(), "a declaration of '%0' is found here", + DiagnosticIDs::Note) + << Decl->getName(); + break; // FIXME: if want location of all other decls, don't break + } + } + // check if a definition in another namespace exists + auto DeclName = CurDecl->getNameAsString(); + if (DeclNameToDefinitions.find(DeclName) == DeclNameToDefinitions.end()) { + continue; // No definition in this translation unit, skip it + } + // make a warning for each definition with the same name but different ns + auto &definitions = DeclNameToDefinitions[DeclName]; + for (const auto *Def : definitions) { + diag(CurDecl->getLocation(), + "no definition found for '%0', but a definition with " + "the same name '%1' found in another namespace '%2'") + << CurDecl->getName() << Def->getName() << getNameOfNamespace(Def); + diag(Def->getLocation(), "a definition of '%0' is found here", + DiagnosticIDs::Note) + << Def->getName(); + } + } + } +} + +} // namespace misc +} // namespace tidy +} // namespace clang Index: clang-tidy/misc/MiscTidyModule.cpp =================================================================== --- clang-tidy/misc/MiscTidyModule.cpp +++ clang-tidy/misc/MiscTidyModule.cpp @@ -15,6 +15,7 @@ #include "AssignOperatorSignatureCheck.h" #include "BoolPointerImplicitConversionCheck.h" #include "DefinitionsInHeadersCheck.h" +#include "ForwardDeclarationNamespaceCheck.h" #include "InaccurateEraseCheck.h" #include "InefficientAlgorithmCheck.h" #include "MacroParenthesesCheck.h" @@ -52,6 +53,8 @@ "misc-bool-pointer-implicit-conversion"); CheckFactories.registerCheck( "misc-definitions-in-headers"); + CheckFactories.registerCheck( + "misc-forward-declaration-namespace"); CheckFactories.registerCheck( "misc-inaccurate-erase"); CheckFactories.registerCheck( Index: docs/clang-tidy/checks/misc-forward-declaration-namespace.rst =================================================================== --- /dev/null +++ docs/clang-tidy/checks/misc-forward-declaration-namespace.rst @@ -0,0 +1,20 @@ +.. title:: clang-tidy - misc-forward-declaration-namespace + +misc-forward-declaration-namespace +================================== + + +Checks if an unused forward declaration is in a wrong namespace. + +The check inspects all unused forward declarations and checks if there is any +declaration/definition with the same name existing, which could indicate that +the forward declaration is in a potentially wrong namespace. + +.. code:: c++ + namespace na { struct A; } + namespace nb { struct A {}; } + nb::A a; + // warning : no definition found for 'A', but a definition with the same name + // 'A' found in another namespace 'nb::' + +This check can only generate warning but can't suggest fix at this point. Index: test/clang-tidy/misc-forward-declaration-namespace.cpp =================================================================== --- /dev/null +++ test/clang-tidy/misc-forward-declaration-namespace.cpp @@ -0,0 +1,154 @@ +// RUN: %check_clang_tidy %s misc-forward-declaration-namespace %t + +namespace { +// Delaration in the wrong namespace +class T_A; +// CHECK-MESSAGES: :[[@LINE-1]]:7: warning: declaration is never referenced, but a declaration with the same name 'T_A' found in another namespace 'na::' [misc-forward-declaration-namespace] +// CHECK-MESSAGES: note: a declaration of 'T_A' is found here +// CHECK-MESSAGES: :[[@LINE-3]]:7: warning: no definition found for 'T_A', but a definition with the same name 'T_A' found in another namespace 'Top level' [misc-forward-declaration-namespace] +// CHECK-MESSAGES: note: a definition of 'T_A' is found here +} + +namespace na { +// Delaration in the wrong namespace +class T_A; +// CHECK-MESSAGES: :[[@LINE-1]]:7: warning: declaration is never referenced, but a declaration with the same name 'T_A' found in another namespace '::' [misc-forward-declaration-namespace] +// CHECK-MESSAGES: note: a declaration of 'T_A' is found here +// CHECK-MESSAGES: :[[@LINE-3]]:7: warning: no definition found for 'T_A', but a definition with the same name 'T_A' found in another namespace 'Top level' [misc-forward-declaration-namespace] +// CHECK-MESSAGES: note: a definition of 'T_A' is found here +} + +class T_A; + +class T_A { + int x; +}; + + +namespace na { +class T_B; +// CHECK-MESSAGES: :[[@LINE-1]]:7: warning: declaration is never referenced, but a declaration with the same name 'T_B' found in another namespace 'nb::' [misc-forward-declaration-namespace] +// CHECK-MESSAGES: note: a declaration of 'T_B' is found here +// CHECK-MESSAGES: :[[@LINE-3]]:7: warning: no definition found for 'T_B', but a definition with the same name 'T_B' found in another namespace 'nb::' [misc-forward-declaration-namespace] +// CHECK-MESSAGES: note: a definition of 'T_B' is found here +} + +namespace nb { +class T_B; +} + +namespace nb { +class T_B { + int x; +}; +} + +namespace na { +class T_B; +// CHECK-MESSAGES: :[[@LINE-1]]:7: warning: declaration is never referenced, but a declaration with the same name 'T_B' found in another namespace 'nb::' [misc-forward-declaration-namespace] +// CHECK-MESSAGES: note: a declaration of 'T_B' is found here +// CHECK-MESSAGES: :[[@LINE-3]]:7: warning: no definition found for 'T_B', but a definition with the same name 'T_B' found in another namespace 'nb::' [misc-forward-declaration-namespace] +// CHECK-MESSAGES: note: a definition of 'T_B' is found here +} + +// simple forward declaration. although never used, but no same declaration +// found in other namespace +class OUTSIDER; + +namespace na { +// Referenced declaration, no warning +class OUTSIDER_1; +} + +void f(na::OUTSIDER_1); + +namespace nc { +// referenced as friend +class OUTSIDER_1; + +class OOP { + friend struct OUTSIDER_1; +}; +} + +namespace nd { +class OUTSIDER_1; +void f(OUTSIDER_1 *); +} + +namespace nb { +class OUTSIDER_1; +// CHECK-MESSAGES: :[[@LINE-1]]:7: warning: declaration is never referenced, but a declaration with the same name 'OUTSIDER_1' found in another namespace 'na::' [misc-forward-declaration-namespace] +// CHECK-MESSAGES: note: a declaration of 'OUTSIDER_1' is found here +} + + +namespace na { +template +class T_C; +} + +namespace nb { +// FIXME: this is an error, but we don't consider template class declaration now +template +class T_C; +} + +namespace na { +template +class T_C { + int x; +}; +} + +namespace na { + +template + class T_TEMP { + template + struct rebind + { typedef T_TEMP<_Tp1> other; }; +}; + +// Ignoring class template specialization +template class T_TEMP; +} + +namespace nb { + +template + class T_TEMP_1 { + template + struct rebind + { typedef T_TEMP_1<_Tp1> other; }; +}; + +// Ignoring class template specialization +extern template class T_TEMP_1; +} + +namespace nd { +class D; +// CHECK-MESSAGES: :[[@LINE-1]]:7: warning: declaration is never referenced, but a declaration with the same name 'D' found in another namespace 'nd::ne::' [misc-forward-declaration-namespace] +// CHECK-MESSAGES: note: a declaration of 'D' is found here +} + +namespace nd { +namespace ne { +class D; +} +} + +int f(nd::ne::D &d); + + +// Check if we can ignore this case +template +class Observer { + class Impl; +}; + +template +class Observer::Impl { + +};