1 //===--- UsingNamespaceDirectiveCheck.cpp - clang-tidy ----------*- C++ -*-===//
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 "UsingNamespaceDirectiveCheck.h"
10 #include "clang/AST/ASTContext.h"
11 #include "clang/ASTMatchers/ASTMatchFinder.h"
12 #include "clang/ASTMatchers/ASTMatchers.h"
13 
14 using namespace clang::ast_matchers;
15 
16 namespace clang {
17 namespace tidy {
18 namespace google {
19 namespace build {
20 
registerMatchers(ast_matchers::MatchFinder * Finder)21 void UsingNamespaceDirectiveCheck::registerMatchers(
22     ast_matchers::MatchFinder *Finder) {
23     Finder->addMatcher(usingDirectiveDecl().bind("usingNamespace"), this);
24 }
25 
check(const MatchFinder::MatchResult & Result)26 void UsingNamespaceDirectiveCheck::check(
27     const MatchFinder::MatchResult &Result) {
28   const auto *U = Result.Nodes.getNodeAs<UsingDirectiveDecl>("usingNamespace");
29   SourceLocation Loc = U->getBeginLoc();
30   if (U->isImplicit() || !Loc.isValid())
31     return;
32 
33   // Do not warn if namespace is a std namespace with user-defined literals. The
34   // user-defined literals can only be used with a using directive.
35   if (isStdLiteralsNamespace(U->getNominatedNamespace()))
36     return;
37 
38   diag(Loc, "do not use namespace using-directives; "
39             "use using-declarations instead");
40   // TODO: We could suggest a list of using directives replacing the using
41   //       namespace directive.
42 }
43 
isStdLiteralsNamespace(const NamespaceDecl * NS)44 bool UsingNamespaceDirectiveCheck::isStdLiteralsNamespace(
45     const NamespaceDecl *NS) {
46   if (!NS->getName().endswith("literals"))
47     return false;
48 
49   const auto *Parent = dyn_cast_or_null<NamespaceDecl>(NS->getParent());
50   if (!Parent)
51     return false;
52 
53   if (Parent->isStdNamespace())
54     return true;
55 
56   return Parent->getName() == "literals" && Parent->getParent() &&
57          Parent->getParent()->isStdNamespace();
58 }
59 } // namespace build
60 } // namespace google
61 } // namespace tidy
62 } // namespace clang
63