blob: d8303d51897ba6e6e0eedb521f6063d886a2773d [file] [log] [blame]
Samuel Benzaquen59c8aa92015-02-11 21:21:05 +00001//===--- 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
16using namespace clang::ast_matchers;
17
18namespace clang {
19namespace tidy {
20namespace readability {
21
22void
23GlobalNamesInHeadersCheck::registerMatchers(ast_matchers::MatchFinder *Finder) {
24 Finder->addMatcher(
25 decl(anyOf(usingDecl(), usingDirectiveDecl()),
26 hasDeclContext(translationUnitDecl())).bind("using_decl"),
27 this);
28}
29
30void GlobalNamesInHeadersCheck::check(const MatchFinder::MatchResult &Result) {
31 const auto *D = Result.Nodes.getNodeAs<Decl>("using_decl");
32 // If it comes from a macro, we'll assume it is fine.
33 if (D->getLocStart().isMacroID())
34 return;
35
36 // Ignore if it comes from the "main" file ...
37 if (Result.SourceManager->isInMainFile(
38 Result.SourceManager->getExpansionLoc(D->getLocStart()))) {
39 // unless that file is a header.
40 StringRef Filename = Result.SourceManager->getFilename(
41 Result.SourceManager->getSpellingLoc(D->getLocStart()));
42
43 if (!Filename.endswith(".h"))
44 return;
45 }
46
47 diag(D->getLocStart(),
48 "using declarations in the global namespace in headers are prohibited");
49}
50
51} // namespace readability
52} // namespace tidy
53} // namespace clang