Debian Codegraph @

llvm-project/clang-tools-extra/clang-tidy/misc/DefinitionsInHeadersCheck.cpp

raw
1 //===--- DefinitionsInHeadersCheck.cpp - clang-tidy------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8
9 #include "DefinitionsInHeadersCheck.h"
10 #include "clang/AST/ASTContext.h"
11 #include "clang/ASTMatchers/ASTMatchFinder.h"
12
13 using namespace clang::ast_matchers;
14
15 namespace clang::tidy::misc {
16
17 namespace {
18
19 AST_MATCHER_P(NamedDecl, usesHeaderFileExtension, utils::FileExtensionsSet,
20 HeaderFileExtensions) {
21 return utils::isExpansionLocInHeaderFile(
22 Node.getBeginLoc(), Finder->getASTContext().getSourceManager(),
23 HeaderFileExtensions);
24 }
25
26 } // namespace
27
28 DefinitionsInHeadersCheck::DefinitionsInHeadersCheck(StringRef Name,
29 ClangTidyContext *Context)
30 : ClangTidyCheck(Name, Context),
31 UseHeaderFileExtension(Options.get("UseHeaderFileExtension", true)),
32 RawStringHeaderFileExtensions(Options.getLocalOrGlobal(
33 "HeaderFileExtensions", utils::defaultHeaderFileExtensions())) {
34 if (!utils::parseFileExtensions(RawStringHeaderFileExtensions,
35 HeaderFileExtensions,
36 utils::defaultFileExtensionDelimiters())) {
37 this->configurationDiag("Invalid header file extension: '%0'")
38 << RawStringHeaderFileExtensions;
39 }
40 }
41
42 void DefinitionsInHeadersCheck::storeOptions(
43 ClangTidyOptions::OptionMap &Opts) {
44 Options.store(Opts, "UseHeaderFileExtension", UseHeaderFileExtension);
45 Options.store(Opts, "HeaderFileExtensions", RawStringHeaderFileExtensions);
46 }
47
48 void DefinitionsInHeadersCheck::registerMatchers(MatchFinder *Finder) {
49 auto DefinitionMatcher =
50 anyOf(functionDecl(isDefinition(), unless(isDeleted())),
51 varDecl(isDefinition()));
52 if (UseHeaderFileExtension) {
53 Finder->addMatcher(namedDecl(DefinitionMatcher,
54 usesHeaderFileExtension(HeaderFileExtensions))
55 .bind("name-decl"),
56 this);
57 } else {
58 Finder->addMatcher(
59 namedDecl(DefinitionMatcher,
60 anyOf(usesHeaderFileExtension(HeaderFileExtensions),
61 unless(isExpansionInMainFile())))
62 .bind("name-decl"),
63 this);
64 }
65 }
66
67 void DefinitionsInHeadersCheck::check(const MatchFinder::MatchResult &Result) {
68 // Don't run the check in failing TUs.
69 if (Result.Context->getDiagnostics().hasUncompilableErrorOccurred())
70 return;
71
72 // C++ [basic.def.odr] p6:
73 // There can be more than one definition of a class type, enumeration type,
74 // inline function with external linkage, class template, non-static function
75 // template, static data member of a class template, member function of a
76 // class template, or template specialization for which some template
77 // parameters are not specifiedin a program provided that each definition
78 // appears in a different translation unit, and provided the definitions
79 // satisfy the following requirements.
80 const auto *ND = Result.Nodes.getNodeAs<NamedDecl>("name-decl");
81 assert(ND);
82 if (ND->isInvalidDecl())
83 return;
84
85 // Internal linkage variable definitions are ignored for now:
86 // const int a = 1;
87 // static int b = 1;
88 //
89 // Although these might also cause ODR violations, we can be less certain and
90 // should try to keep the false-positive rate down.
91 //
92 // FIXME: Should declarations in anonymous namespaces get the same treatment
93 // as static / const declarations?
94 if (!ND->hasExternalFormalLinkage() && !ND->isInAnonymousNamespace())
95 return;
96
97 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
98 // Inline functions are allowed.
99 if (FD->isInlined())
100 return;
101 // Function templates are allowed.
102 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
103 return;
104 // Ignore instantiated functions.
105 if (FD->isTemplateInstantiation())
106 return;
107 // Member function of a class template and member function of a nested class
108 // in a class template are allowed.
109 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
110 const auto *DC = MD->getDeclContext();
111 while (DC->isRecord()) {
112 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC)) {
113 if (isa<ClassTemplatePartialSpecializationDecl>(RD))
114 return;
115 if (RD->getDescribedClassTemplate())
116 return;
117 }
118 DC = DC->getParent();
119 }
120 }
121
122 bool IsFullSpec = FD->getTemplateSpecializationKind() != TSK_Undeclared;
123 diag(FD->getLocation(),
124 "%select{function|full function template specialization}0 %1 defined "
125 "in a header file; function definitions in header files can lead to "
126 "ODR violations")
127 << IsFullSpec << FD;
128 // inline is not allowed for main function.
129 if (FD->isMain())
130 return;
131 diag(FD->getLocation(), /*Description=*/"make as 'inline'",
132 DiagnosticIDs::Note)
133 << FixItHint::CreateInsertion(FD->getInnerLocStart(), "inline ");
134 } else if (const auto *VD = dyn_cast<VarDecl>(ND)) {
135 // C++14 variable templates are allowed.
136 if (VD->getDescribedVarTemplate())
137 return;
138 // Static data members of a class template are allowed.
139 if (VD->getDeclContext()->isDependentContext() && VD->isStaticDataMember())
140 return;
141 // Ignore instantiated static data members of classes.
142 if (isTemplateInstantiation(VD->getTemplateSpecializationKind()))
143 return;
144 // Ignore variable definition within function scope.
145 if (VD->hasLocalStorage() || VD->isStaticLocal())
146 return;
147 // Ignore inline variables.
148 if (VD->isInline())
149 return;
150 // Ignore partial specializations.
151 if (isa<VarTemplatePartialSpecializationDecl>(VD))
152 return;
153
154 diag(VD->getLocation(),
155 "variable %0 defined in a header file; "
156 "variable definitions in header files can lead to ODR violations")
157 << VD;
158 }
159 }
160
161 } // namespace clang::tidy::misc