Samuel Benzaquen | 59c8aa9 | 2015-02-11 21:21:05 +0000 | [diff] [blame] | 1 | //===--- GlobalNamesInHeadersCheck.cpp - clang-tidy -----------------*- C++ -*-===// |
| 2 | // |
| 3 | // The LLVM Compiler Infrastructure |
| 4 | // |
| 5 | // This file is distributed under the University of Illinois Open Source |
| 6 | // License. See LICENSE.TXT for details. |
| 7 | // |
| 8 | //===----------------------------------------------------------------------===// |
| 9 | |
| 10 | #include "GlobalNamesInHeadersCheck.h" |
| 11 | #include "clang/AST/ASTContext.h" |
| 12 | #include "clang/ASTMatchers/ASTMatchFinder.h" |
| 13 | #include "clang/ASTMatchers/ASTMatchers.h" |
| 14 | #include "clang/Lex/Lexer.h" |
| 15 | |
| 16 | using namespace clang::ast_matchers; |
| 17 | |
| 18 | namespace clang { |
| 19 | namespace tidy { |
Alexander Kornienko | ed824e0 | 2015-03-05 13:46:14 +0000 | [diff] [blame^] | 20 | namespace google { |
Samuel Benzaquen | 59c8aa9 | 2015-02-11 21:21:05 +0000 | [diff] [blame] | 21 | namespace readability { |
| 22 | |
| 23 | void |
| 24 | GlobalNamesInHeadersCheck::registerMatchers(ast_matchers::MatchFinder *Finder) { |
| 25 | Finder->addMatcher( |
| 26 | decl(anyOf(usingDecl(), usingDirectiveDecl()), |
| 27 | hasDeclContext(translationUnitDecl())).bind("using_decl"), |
| 28 | this); |
| 29 | } |
| 30 | |
| 31 | void GlobalNamesInHeadersCheck::check(const MatchFinder::MatchResult &Result) { |
| 32 | const auto *D = Result.Nodes.getNodeAs<Decl>("using_decl"); |
| 33 | // If it comes from a macro, we'll assume it is fine. |
| 34 | if (D->getLocStart().isMacroID()) |
| 35 | return; |
| 36 | |
| 37 | // Ignore if it comes from the "main" file ... |
| 38 | if (Result.SourceManager->isInMainFile( |
| 39 | Result.SourceManager->getExpansionLoc(D->getLocStart()))) { |
| 40 | // unless that file is a header. |
| 41 | StringRef Filename = Result.SourceManager->getFilename( |
| 42 | Result.SourceManager->getSpellingLoc(D->getLocStart())); |
| 43 | |
| 44 | if (!Filename.endswith(".h")) |
| 45 | return; |
| 46 | } |
| 47 | |
| 48 | diag(D->getLocStart(), |
| 49 | "using declarations in the global namespace in headers are prohibited"); |
| 50 | } |
| 51 | |
| 52 | } // namespace readability |
Alexander Kornienko | ed824e0 | 2015-03-05 13:46:14 +0000 | [diff] [blame^] | 53 | } // namespace google |
Samuel Benzaquen | 59c8aa9 | 2015-02-11 21:21:05 +0000 | [diff] [blame] | 54 | } // namespace tidy |
| 55 | } // namespace clang |