-
Notifications
You must be signed in to change notification settings - Fork 10.8k
/
ImplementationInNamespaceCheck.cpp
53 lines (46 loc) · 1.99 KB
/
ImplementationInNamespaceCheck.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
//===--- ImplementationInNamespaceCheck.cpp - clang-tidy ------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "ImplementationInNamespaceCheck.h"
#include "clang/AST/ASTContext.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
using namespace clang::ast_matchers;
namespace clang::tidy::llvm_libc {
const static StringRef RequiredNamespaceStart = "__llvm_libc";
const static StringRef RequiredNamespaceMacroName = "LIBC_NAMESPACE";
void ImplementationInNamespaceCheck::registerMatchers(MatchFinder *Finder) {
Finder->addMatcher(
translationUnitDecl(
forEach(decl(isExpansionInMainFile(), unless(linkageSpecDecl()),
// anonymous namespaces generate usingDirective
unless(usingDirectiveDecl(isImplicit())))
.bind("child_of_translation_unit"))),
this);
}
void ImplementationInNamespaceCheck::check(
const MatchFinder::MatchResult &Result) {
const auto *MatchedDecl =
Result.Nodes.getNodeAs<Decl>("child_of_translation_unit");
const auto *NS = dyn_cast<NamespaceDecl>(MatchedDecl);
if (NS == nullptr || NS->isAnonymousNamespace()) {
diag(MatchedDecl->getLocation(),
"declaration must be enclosed within the '%0' namespace")
<< RequiredNamespaceMacroName;
return;
}
if (Result.SourceManager->isMacroBodyExpansion(NS->getLocation()) == false) {
diag(NS->getLocation(), "the outermost namespace should be the '%0' macro")
<< RequiredNamespaceMacroName;
return;
}
if (NS->getName().starts_with(RequiredNamespaceStart) == false) {
diag(NS->getLocation(), "the '%0' macro should start with '%1'")
<< RequiredNamespaceMacroName << RequiredNamespaceStart;
return;
}
}
} // namespace clang::tidy::llvm_libc