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 9 #include "ImplementationInNamespaceCheck.h" 10 #include "clang/AST/ASTContext.h" 11 #include "clang/ASTMatchers/ASTMatchFinder.h" 12 13 using namespace clang::ast_matchers; 14 15 namespace clang { 16 namespace tidy { 17 namespace llvm_libc { 18 19 const static StringRef RequiredNamespace = "__llvm_libc"; registerMatchers(MatchFinder * Finder)20void ImplementationInNamespaceCheck::registerMatchers(MatchFinder *Finder) { 21 Finder->addMatcher( 22 decl(hasParent(translationUnitDecl()), unless(linkageSpecDecl())) 23 .bind("child_of_translation_unit"), 24 this); 25 } 26 check(const MatchFinder::MatchResult & Result)27void ImplementationInNamespaceCheck::check( 28 const MatchFinder::MatchResult &Result) { 29 const auto *MatchedDecl = 30 Result.Nodes.getNodeAs<Decl>("child_of_translation_unit"); 31 if (!Result.SourceManager->isInMainFile(MatchedDecl->getLocation())) 32 return; 33 34 if (const auto *NS = dyn_cast<NamespaceDecl>(MatchedDecl)) { 35 if (NS->getName() != RequiredNamespace) { 36 diag(NS->getLocation(), "'%0' needs to be the outermost namespace") 37 << RequiredNamespace; 38 } 39 return; 40 } 41 diag(MatchedDecl->getLocation(), 42 "declaration must be declared within the '%0' namespace") 43 << RequiredNamespace; 44 return; 45 } 46 47 } // namespace llvm_libc 48 } // namespace tidy 49 } // namespace clang 50