clang-tools 18.0.0git
ImplementationInNamespaceCheck.cpp
Go to the documentation of this file.
1//===--- ImplementationInNamespaceCheck.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
10#include "clang/AST/ASTContext.h"
11#include "clang/ASTMatchers/ASTMatchFinder.h"
12
13using namespace clang::ast_matchers;
14
15namespace clang::tidy::llvm_libc {
16
17const static StringRef RequiredNamespaceStart = "__llvm_libc";
18const static StringRef RequiredNamespaceMacroName = "LIBC_NAMESPACE";
19
21 Finder->addMatcher(
22 translationUnitDecl(
23 forEach(decl(isExpansionInMainFile(), unless(linkageSpecDecl()),
24 // anonymous namespaces generate usingDirective
25 unless(usingDirectiveDecl(isImplicit())))
26 .bind("child_of_translation_unit"))),
27 this);
28}
29
31 const MatchFinder::MatchResult &Result) {
32 const auto *MatchedDecl =
33 Result.Nodes.getNodeAs<Decl>("child_of_translation_unit");
34 const auto *NS = dyn_cast<NamespaceDecl>(MatchedDecl);
35 if (NS == nullptr || NS->isAnonymousNamespace()) {
36 diag(MatchedDecl->getLocation(),
37 "declaration must be enclosed within the '%0' namespace")
39 return;
40 }
41 if (Result.SourceManager->isMacroBodyExpansion(NS->getLocation()) == false) {
42 diag(NS->getLocation(), "the outermost namespace should be the '%0' macro")
44 return;
45 }
46 if (NS->getName().starts_with(RequiredNamespaceStart) == false) {
47 diag(NS->getLocation(), "the '%0' macro should start with '%1'")
49 return;
50 }
51}
52
53} // namespace clang::tidy::llvm_libc
const FunctionDecl * Decl
DiagnosticBuilder diag(SourceLocation Loc, StringRef Description, DiagnosticIDs::Level Level=DiagnosticIDs::Warning)
Add a diagnostic with the check's name.
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
ClangTidyChecks that register ASTMatchers should do the actual work in here.
void registerMatchers(ast_matchers::MatchFinder *Finder) override
Override this to register AST matchers with Finder.
static const StringRef RequiredNamespaceStart
static const StringRef RequiredNamespaceMacroName