1 //===----------------------------------------------------------------------===//
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
7 //===----------------------------------------------------------------------===//
9 #include "clang-tidy/ClangTidyCheck.h"
10 #include "clang-tidy/ClangTidyModuleRegistry.h"
12 #include "clang/Basic/Module.h"
14 #include "llvm/ADT/ArrayRef.h"
16 #include "header_exportable_declarations.hpp"
24 struct clang::tidy::OptionEnumMapping
<libcpp::header_exportable_declarations::FileType
> {
25 static llvm::ArrayRef
<std::pair
<libcpp::header_exportable_declarations::FileType
, llvm::StringRef
>> getEnumMapping() {
26 static constexpr std::pair
<libcpp::header_exportable_declarations::FileType
, llvm::StringRef
> Mapping
[] = {
27 {libcpp::header_exportable_declarations::FileType::Header
, "Header"},
28 {libcpp::header_exportable_declarations::FileType::ModulePartition
, "ModulePartition"},
29 {libcpp::header_exportable_declarations::FileType::Module
, "Module"},
30 {libcpp::header_exportable_declarations::FileType::CHeader
, "CHeader"},
31 {libcpp::header_exportable_declarations::FileType::CompatModulePartition
, "CompatModulePartition"},
32 {libcpp::header_exportable_declarations::FileType::CompatModule
, "CompatModule"}};
33 return ArrayRef(Mapping
);
38 header_exportable_declarations::header_exportable_declarations(
39 llvm::StringRef name
, clang::tidy::ClangTidyContext
* context
)
40 : clang::tidy::ClangTidyCheck(name
, context
),
41 filename_(Options
.get("Filename", "")),
42 file_type_(Options
.get("FileType", header_exportable_declarations::FileType::Unknown
)),
43 extra_header_(Options
.get("ExtraHeader", "")) {
45 case header_exportable_declarations::FileType::CHeader
:
46 case header_exportable_declarations::FileType::Header
:
47 if (filename_
.empty())
48 llvm::errs() << "No filename is provided.\n";
49 if (extra_header_
.empty())
50 extra_header_
= "$^"; // Use a never matching regex to silence an error message.
52 case header_exportable_declarations::FileType::ModulePartition
:
53 case header_exportable_declarations::FileType::CompatModulePartition
:
54 if (filename_
.empty())
55 llvm::errs() << "No filename is provided.\n";
57 case header_exportable_declarations::FileType::Module
:
58 case header_exportable_declarations::FileType::CompatModule
:
59 if (!extra_header_
.empty())
60 llvm::errs() << "Extra headers are not allowed for modules.\n";
61 if (Options
.get("SkipDeclarations"))
62 llvm::errs() << "Modules may not skip declarations.\n";
63 if (Options
.get("ExtraDeclarations"))
64 llvm::errs() << "Modules may not have extra declarations.\n";
66 case header_exportable_declarations::FileType::Unknown
:
67 llvm::errs() << "No file type is provided.\n";
71 std::optional
<llvm::StringRef
> list
= Options
.get("SkipDeclarations");
72 // TODO(LLVM-17) Remove clang 15 work-around.
73 #if defined(__clang_major__) && __clang_major__ < 16
75 std::string_view s
= *list
;
77 auto e
= std::find(b
, s
.end(), ' ');
79 skip_decls_
.emplace(b
, e
);
83 e
= std::find(b
, s
.end(), ' ');
86 #else // defined(__clang_major__) && __clang_major__ < 16
88 for (auto decl
: std::views::split(*list
, ' ')) {
90 std::ranges::copy(decl
, std::back_inserter(s
)); // use range based constructor
91 skip_decls_
.emplace(std::move(s
));
93 #endif // defined(__clang_major__) && __clang_major__ < 16
96 list
= Options
.get("ExtraDeclarations");
97 // TODO(LLVM-17) Remove clang 15 work-around.
98 #if defined(__clang_major__) && __clang_major__ < 16
100 std::string_view s
= *list
;
102 auto e
= std::find(b
, s
.end(), ' ');
104 std::cout
<< "using ::" << std::string_view
{b
, e
} << ";\n";
108 e
= std::find(b
, s
.end(), ' ');
111 #else // defined(__clang_major__) && __clang_major__ < 16
113 for (auto decl
: std::views::split(*list
, ' '))
114 std::cout
<< "using ::" << std::string_view
{decl
.data(), decl
.size()} << ";\n";
115 #endif // defined(__clang_major__) && __clang_major__ < 16
118 header_exportable_declarations::~header_exportable_declarations() {
119 for (const auto& name
: global_decls_
)
120 if (!skip_decls_
.contains("std::" + name
) && decls_
.contains("std::" + name
))
121 std::cout
<< "using ::" << name
<< ";\n";
124 void header_exportable_declarations::registerMatchers(clang::ast_matchers::MatchFinder
* finder
) {
125 // there are no public names in the Standard starting with an underscore, so
126 // no need to check the strict rules.
127 using namespace clang::ast_matchers
;
129 switch (file_type_
) {
130 case FileType::Header
:
133 // Looks at the common locations where headers store their data
137 anyOf(isExpansionInFileMatching(("v1/__" + filename_
+ "/").str()),
138 isExpansionInFileMatching(extra_header_
),
139 isExpansionInFileMatching(("v1/__fwd/" + filename_
+ "\\.h$").str()),
140 isExpansionInFileMatching(("v1/" + filename_
+ "$").str())),
141 unless(hasAncestor(friendDecl())))
142 .bind("header_exportable_declarations"),
145 case FileType::CHeader
:
146 // For C headers of the std.compat two matchers are used
147 // - The cheader matcher; in libc++ these are never split in multiple
148 // headers so limiting the declarations to that header works.
149 // - The header.h; where the declarations of this header are provided
150 // is not specified and depends on the libc used. Therefore it is not
151 // possible to restrict the location in a portable way.
152 finder
->addMatcher(namedDecl().bind("cheader_exportable_declarations"), this);
155 case FileType::ModulePartition
:
156 case FileType::CompatModulePartition
:
157 finder
->addMatcher(namedDecl(isExpansionInFileMatching(filename_
)).bind("header_exportable_declarations"), this);
159 case FileType::Module
:
160 case FileType::CompatModule
:
161 finder
->addMatcher(namedDecl().bind("header_exportable_declarations"), this);
163 case header_exportable_declarations::FileType::Unknown
:
164 llvm::errs() << "This should be unreachable.\n";
169 /// Returns the qualified name of a declaration.
171 /// There is a small issue with qualified names. Typically the name returned is
172 /// in the namespace \c std instead of the namespace \c std::__1. Except when a
173 /// name is declared both in the namespace \c std and in the namespace
174 /// \c std::__1. In that case the returned value will adjust the name to use
175 /// the namespace \c std.
177 /// The reason this happens is due to some parts of libc++ using
178 /// \code namespace std \endcode instead of
179 /// \code _LIBCPP_BEGIN_NAMESPACE_STD \endcode
181 /// * cstddef has bitwise operators for the type \c byte
182 /// * exception has equality operators for the type \c exception_ptr
183 /// * initializer_list has the functions \c begin and \c end
185 /// \warning In some cases the returned name can be an empty string.
186 /// The cause has not been investigated.
187 static std::string
get_qualified_name(const clang::NamedDecl
& decl
) {
188 std::string result
= decl
.getQualifiedNameAsString();
190 if (result
.starts_with("std::__1::"))
196 static bool is_viable_declaration(const clang::NamedDecl
* decl
) {
197 // Declarations that are a subobject of a friend Declaration are automatically exported with the record itself.
198 if (decl
->getFriendObjectKind() != clang::Decl::FOK_None
)
201 // *** Function declarations ***
203 if (clang::CXXMethodDecl::classof(decl
))
206 if (clang::CXXDeductionGuideDecl::classof(decl
))
209 if (clang::FunctionDecl::classof(decl
))
212 if (clang::CXXConstructorDecl::classof(decl
))
215 // implicit constructors disallowed
216 if (const auto* r
= llvm::dyn_cast_or_null
<clang::RecordDecl
>(decl
))
217 return !r
->isLambda() && !r
->isImplicit();
219 // *** Unconditionally accepted declarations ***
220 return llvm::isa
<clang::EnumDecl
, clang::VarDecl
, clang::ConceptDecl
, clang::TypedefNameDecl
, clang::UsingDecl
>(decl
);
223 /// Returns the name is a reserved name.
225 /// Detected reserved names are names starting with __ or _[A-Z].
226 /// These names can be in the global namespace, std namespace or any namespace
227 /// inside std. For example, std::ranges contains reserved names to implement
230 /// This test misses candidates which are not used in libc++
231 /// * any identifier with two underscores not at the start
232 bool is_reserved_name(std::string_view name
) {
233 if (name
.starts_with("_")) {
234 // This is a public name declared in cstdlib.
238 return name
.size() > 1 && (name
[1] == '_' || std::isupper(name
[1]));
241 std::size_t pos
= name
.find("::_");
242 if (pos
== std::string::npos
)
245 if (pos
+ 3 > name
.size())
248 // This is a public name declared in cstdlib.
249 if (name
== "std::_Exit")
252 return name
[pos
+ 3] == '_' || std::isupper(name
[pos
+ 3]);
255 /// Some declarations in the global namespace are exported from the std module.
256 static bool is_global_name_exported_by_std_module(std::string_view name
) {
257 static const std::set
<std::string_view
> valid
{
258 "operator delete", "operator delete[]", "operator new", "operator new[]"};
259 return valid
.contains(name
);
262 static bool is_valid_declaration_context(
263 const clang::NamedDecl
& decl
, std::string_view name
, header_exportable_declarations::FileType file_type
) {
264 if (decl
.getDeclContext()->isNamespace())
267 if (is_global_name_exported_by_std_module(name
))
270 return file_type
!= header_exportable_declarations::FileType::Header
;
273 static bool is_module(header_exportable_declarations::FileType file_type
) {
275 case header_exportable_declarations::FileType::Module
:
276 case header_exportable_declarations::FileType::ModulePartition
:
277 case header_exportable_declarations::FileType::CompatModule
:
278 case header_exportable_declarations::FileType::CompatModulePartition
:
281 case header_exportable_declarations::FileType::Header
:
282 case header_exportable_declarations::FileType::CHeader
:
285 case header_exportable_declarations::FileType::Unknown
:
286 llvm::errs() << "This should be unreachable.\n";
291 void header_exportable_declarations::check(const clang::ast_matchers::MatchFinder::MatchResult
& result
) {
292 if (const auto* decl
= result
.Nodes
.getNodeAs
<clang::NamedDecl
>("header_exportable_declarations"); decl
!= nullptr) {
293 if (!is_viable_declaration(decl
))
296 std::string name
= get_qualified_name(*decl
);
300 if (is_reserved_name(name
))
303 // For modules only take the declarations exported.
304 if (is_module(file_type_
))
305 if (decl
->getModuleOwnershipKind() != clang::Decl::ModuleOwnershipKind::VisibleWhenImported
)
308 if (!is_valid_declaration_context(*decl
, name
, file_type_
))
311 if (decls_
.contains(name
)) {
312 // For modules avoid exporting the same named declaration twice. For
313 // header files this is common and valid.
314 if (file_type_
== FileType::ModulePartition
|| file_type_
== FileType::CompatModulePartition
)
315 // After the warning the script continues.
316 // The test will fail since modules have duplicated entries and headers not.
317 llvm::errs() << "Duplicated export of '" << name
<< "'.\n";
322 // For named declarations in std this is valid
324 // for named declarations it is invalid to use
326 // Since fully qualifying named declarations in the std namespace is valid
327 // using fully qualified names unconditionally.
328 std::cout
<< "using ::" << std::string
{name
} << ";\n";
330 } else if (const auto* decl
= result
.Nodes
.getNodeAs
<clang::NamedDecl
>("cheader_exportable_declarations");
332 if (decl
->getDeclContext()->isNamespace())
335 if (!is_viable_declaration(decl
))
338 std::string name
= get_qualified_name(*decl
);
339 if (is_reserved_name(name
))
342 if (global_decls_
.contains(name
))
345 global_decls_
.insert(name
);
349 } // namespace libcpp