clang-tools  3.9.0
DefinitionsInHeadersCheck.cpp
Go to the documentation of this file.
1 //===--- DefinitionsInHeadersCheck.cpp - clang-tidy------------------------===//
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 
11 #include "clang/AST/ASTContext.h"
12 #include "clang/ASTMatchers/ASTMatchFinder.h"
13 
14 using namespace clang::ast_matchers;
15 
16 namespace clang {
17 namespace tidy {
18 namespace misc {
19 
20 namespace {
21 
22 AST_MATCHER_P(NamedDecl, usesHeaderFileExtension,
23  utils::HeaderFileExtensionsSet, HeaderFileExtensions) {
25  Node.getLocStart(), Finder->getASTContext().getSourceManager(),
26  HeaderFileExtensions);
27 }
28 
29 } // namespace
30 
31 DefinitionsInHeadersCheck::DefinitionsInHeadersCheck(StringRef Name,
33  : ClangTidyCheck(Name, Context),
34  UseHeaderFileExtension(Options.get("UseHeaderFileExtension", true)),
35  RawStringHeaderFileExtensions(
36  Options.getLocalOrGlobal("HeaderFileExtensions", ",h,hh,hpp,hxx")) {
37  if (!utils::parseHeaderFileExtensions(RawStringHeaderFileExtensions,
38  HeaderFileExtensions,
39  ',')) {
40  // FIXME: Find a more suitable way to handle invalid configuration
41  // options.
42  llvm::errs() << "Invalid header file extension: "
43  << RawStringHeaderFileExtensions << "\n";
44  }
45 }
46 
49  Options.store(Opts, "UseHeaderFileExtension", UseHeaderFileExtension);
50  Options.store(Opts, "HeaderFileExtensions", RawStringHeaderFileExtensions);
51 }
52 
54  if (!getLangOpts().CPlusPlus)
55  return;
56  auto DefinitionMatcher =
57  anyOf(functionDecl(isDefinition(), unless(isDeleted())),
58  varDecl(isDefinition()));
59  if (UseHeaderFileExtension) {
60  Finder->addMatcher(namedDecl(DefinitionMatcher,
61  usesHeaderFileExtension(HeaderFileExtensions))
62  .bind("name-decl"),
63  this);
64  } else {
65  Finder->addMatcher(
66  namedDecl(DefinitionMatcher,
67  anyOf(usesHeaderFileExtension(HeaderFileExtensions),
68  unless(isExpansionInMainFile())))
69  .bind("name-decl"),
70  this);
71  }
72 }
73 
74 void DefinitionsInHeadersCheck::check(const MatchFinder::MatchResult &Result) {
75  // Don't run the check in failing TUs.
76  if (Result.Context->getDiagnostics().hasErrorOccurred())
77  return;
78 
79  // C++ [basic.def.odr] p6:
80  // There can be more than one definition of a class type, enumeration type,
81  // inline function with external linkage, class template, non-static function
82  // template, static data member of a class template, member function of a
83  // class template, or template specialization for which some template
84  // parameters are not specifiedin a program provided that each definition
85  // appears in a different translation unit, and provided the definitions
86  // satisfy the following requirements.
87  const auto *ND = Result.Nodes.getNodeAs<NamedDecl>("name-decl");
88  assert(ND);
89  if (ND->isInvalidDecl())
90  return;
91 
92  // Internal linkage variable definitions are ignored for now:
93  // const int a = 1;
94  // static int b = 1;
95  //
96  // Although these might also cause ODR violations, we can be less certain and
97  // should try to keep the false-positive rate down.
98  if (ND->getLinkageInternal() == InternalLinkage)
99  return;
100 
101  if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
102  // Inline functions are allowed.
103  if (FD->isInlined())
104  return;
105  // Function templates are allowed.
106  if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
107  return;
108  // Function template full specialization is prohibited in header file.
109  if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
110  return;
111  // Member function of a class template and member function of a nested class
112  // in a class template are allowed.
113  if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
114  const auto *DC = MD->getDeclContext();
115  while (DC->isRecord()) {
116  if (const auto *RD = dyn_cast<CXXRecordDecl>(DC)) {
117  if (isa<ClassTemplatePartialSpecializationDecl>(RD))
118  return;
119  if (RD->getDescribedClassTemplate())
120  return;
121  }
122  DC = DC->getParent();
123  }
124  }
125 
126  diag(FD->getLocation(),
127  "function %0 defined in a header file; "
128  "function definitions in header files can lead to ODR violations")
129  << FD << FixItHint::CreateInsertion(
130  FD->getReturnTypeSourceRange().getBegin(), "inline ");
131  } else if (const auto *VD = dyn_cast<VarDecl>(ND)) {
132  // Static data members of a class template are allowed.
133  if (VD->getDeclContext()->isDependentContext() && VD->isStaticDataMember())
134  return;
135  if (VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
136  return;
137  // Ignore variable definition within function scope.
138  if (VD->hasLocalStorage() || VD->isStaticLocal())
139  return;
140 
141  diag(VD->getLocation(),
142  "variable %0 defined in a header file; "
143  "variable definitions in header files can lead to ODR violations")
144  << VD;
145  }
146 }
147 
148 } // namespace misc
149 } // namespace tidy
150 } // namespace clang
const std::string Name
Definition: USRFinder.cpp:140
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
ClangTidyChecks that register ASTMatchers should do the actual work in here.
LangOptions getLangOpts() const
Returns the language options from the context.
Definition: ClangTidy.h:170
bool parseHeaderFileExtensions(StringRef AllHeaderFileExtensions, HeaderFileExtensionsSet &HeaderFileExtensions, char delimiter)
Parses header file extensions from a semicolon-separated list.
std::unique_ptr< ast_matchers::MatchFinder > Finder
Definition: ClangTidy.cpp:210
bool isExpansionLocInHeaderFile(SourceLocation Loc, const SourceManager &SM, const HeaderFileExtensionsSet &HeaderFileExtensions)
Checks whether expansion location of Loc is in header file.
AST_MATCHER_P(CXXForRangeStmt, hasRangeBeginEndStmt, ast_matchers::internal::Matcher< DeclStmt >, InnerMatcher)
void storeOptions(ClangTidyOptions::OptionMap &Opts) override
Should store all options supported by this check with their current values or default values for opti...
Base class for all clang-tidy checks.
Definition: ClangTidy.h:110
llvm::SmallSet< llvm::StringRef, 5 > HeaderFileExtensionsSet
void store(ClangTidyOptions::OptionMap &Options, StringRef LocalName, StringRef Value) const
Stores an option with the check-local name LocalName with string value Value to Options.
Definition: ClangTidy.cpp:385
std::map< std::string, std::string > OptionMap
void registerMatchers(ast_matchers::MatchFinder *Finder) override
Override this to register AST matchers with Finder.
ClangTidyContext & Context
Definition: ClangTidy.cpp:93
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
DiagnosticBuilder diag(SourceLocation Loc, StringRef Description, DiagnosticIDs::Level Level=DiagnosticIDs::Warning)
Add a diagnostic with the check's name.
Definition: ClangTidy.cpp:352
const NamedDecl * Result
Definition: USRFinder.cpp:137